FIX: Đã fix cross-machine (v202608060700)

This commit is contained in:
2026-08-05 22:02:43 +07:00
parent e9f29e09ca
commit 454dd91f96
7 changed files with 79 additions and 15 deletions
+5 -1
View File
@@ -151,7 +151,11 @@ async def delete_soundfont(sf_id: str, current_user: dict = Depends(get_current_
@router.get("/soundfonts/download/{sf_id}") @router.get("/soundfonts/download/{sf_id}")
async def download_soundfont_asset(sf_id: str): async def download_soundfont_asset(sf_id: str):
clean_id = sf_id.replace("sf_", "") if sf_id.startswith("sf_") else sf_id clean_id = sf_id.replace("sf_", "") if sf_id.startswith("sf_") else sf_id
for base_dir in [UPLOAD_SF_DIR, SYSTEM_SF_DIR]: # Cũng tìm trong static/soundfonts (font bundled theo deployment) — trước
# đây chỉ UPLOAD + SYSTEM → font bundled 404 → incognito (IndexedDB rỗng)
# không tải được font → instrument CÂM (browser thường dùng cache nên OK).
static_sf_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "static", "soundfonts")
for base_dir in [UPLOAD_SF_DIR, SYSTEM_SF_DIR, static_sf_dir]:
if not os.path.isdir(base_dir): if not os.path.isdir(base_dir):
continue continue
# Prefer SF2: the client FluidSynth WASM cannot decode SF3 (Ogg Vorbis) # Prefer SF2: the client FluidSynth WASM cannot decode SF3 (Ogg Vorbis)
+6 -1
View File
@@ -81,7 +81,12 @@ async def get_index():
if not os.path.exists(index_path): if not os.path.exists(index_path):
return HTMLResponse(content=f"<h1>SonicForge Studio: index.html not found at {index_path}</h1>", status_code=404) return HTMLResponse(content=f"<h1>SonicForge Studio: index.html not found at {index_path}</h1>", status_code=404)
with open(index_path, "r", encoding="utf-8") as file: with open(index_path, "r", encoding="utf-8") as file:
return HTMLResponse(content=file.read(), status_code=200) resp = HTMLResponse(content=file.read(), status_code=200)
# no-cache: index.html PHẢI luôn mới (các bundle JS dùng ?v= để bust) —
# nếu browser cache HTML cũ → stamp cũ → tải bundle cũ (bug "không load
# được bundle mới" ở incognito — cache heuristic không có Cache-Control).
resp.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
return resp
@app.get("/favicon.svg") @app.get("/favicon.svg")
+5 -3
View File
@@ -2675,6 +2675,7 @@ const WaveformLane = ({
// Check if hovering near right edge of a clip for time-stretching (Alt key required) // Check if hovering near right edge of a clip for time-stretching (Alt key required)
const toleranceSec = 8 / zoom; const toleranceSec = 8 / zoom;
const rightEdgeClip = clips.find(c => { const rightEdgeClip = clips.find(c => {
if (!c.buffer) return false;
const duration = c.buffer.duration / (c.speed || 1.0); const duration = c.buffer.duration / (c.speed || 1.0);
return Math.abs(time - (c.startTime + duration)) <= toleranceSec; return Math.abs(time - (c.startTime + duration)) <= toleranceSec;
}); });
@@ -2725,7 +2726,7 @@ const WaveformLane = ({
return; return;
} }
const hoveredClip = clips.find(c => time >= c.startTime && time < c.startTime + c.buffer.duration / (c.speed || 1.0)); const hoveredClip = clips.find(c => c.buffer && time >= c.startTime && time < c.startTime + c.buffer.duration / (c.speed || 1.0));
const isOverClip = !!hoveredClip; const isOverClip = !!hoveredClip;
if (activeTool === 'pen') { if (activeTool === 'pen') {
canvasRef.current.style.cursor = isOverClip ? 'copy' : 'not-allowed'; canvasRef.current.style.cursor = isOverClip ? 'copy' : 'not-allowed';
@@ -2806,6 +2807,7 @@ const WaveformLane = ({
// Check if time-stretching (Alt + Right Edge) // Check if time-stretching (Alt + Right Edge)
const toleranceSec = 8 / zoom; const toleranceSec = 8 / zoom;
const rightEdgeClip = clips.find(c => { const rightEdgeClip = clips.find(c => {
if (!c.buffer) return false;
const duration = c.buffer.duration / (c.speed || 1.0); const duration = c.buffer.duration / (c.speed || 1.0);
return Math.abs(time - (c.startTime + duration)) <= toleranceSec; return Math.abs(time - (c.startTime + duration)) <= toleranceSec;
}); });
@@ -2880,7 +2882,7 @@ const WaveformLane = ({
return; return;
} }
const clickedClip = clips.find(c => time >= c.startTime && time < c.startTime + c.buffer.duration / (c.speed || 1.0)); const clickedClip = clips.find(c => c.buffer && time >= c.startTime && time < c.startTime + c.buffer.duration / (c.speed || 1.0));
// Set selected clip ID // Set selected clip ID
if (clickedClip) { if (clickedClip) {
@@ -3022,7 +3024,7 @@ const WaveformLane = ({
if (onEditMidiInTab) onEditMidiInTab(track.id, dblMidiHit.id); if (onEditMidiInTab) onEditMidiInTab(track.id, dblMidiHit.id);
return; return;
} }
const clickedClip = clips.find(c => time >= c.startTime && time < c.startTime + c.buffer.duration / (c.speed || 1.0)); const clickedClip = clips.find(c => c.buffer && time >= c.startTime && time < c.startTime + c.buffer.duration / (c.speed || 1.0));
if (clickedClip) { if (clickedClip) {
e.preventDefault(); e.preventDefault();
e.stopPropagation(); e.stopPropagation();
+5 -5
View File
@@ -236,22 +236,22 @@ const midiItems=track.midiItems||[];midiItems.forEach(midi=>{const midiStartLoca
if(selectionMode==='local'&&localSelectionTrackId===track.id&&localSelLeft!==null&&localSelRight!==null&&localSelRight>localSelLeft){const hlLeftLocal=localSelLeft*zoom-scrollLeftVal;const hlWidth=(localSelRight-localSelLeft)*zoom;ctx.fillStyle='rgba(245, 158, 11, 0.15)';ctx.fillRect(hlLeftLocal,0,hlWidth,height);ctx.strokeStyle='#f59e0b';ctx.lineWidth=1;ctx.strokeRect(hlLeftLocal,0,hlWidth,height);}},[track,zoom,timelineWidth,viewportWidth,isSelected,markers,selectionMode,localSelectionTrackId,localSelLeft,localSelRight,snapValue,bpm,scrollLeft,recordingState,recTempMidiNotes,recStartTimelineTime,canvasRedrawCount,currentTime,selectedItemIds]);return/*#__PURE__*/React.createElement(React.Fragment,null,/*#__PURE__*/React.createElement("div",{key:"virtual-spacer",style:{width:`${timelineWidth}px`,height:'1px',pointerEvents:'none'}}),/*#__PURE__*/React.createElement("canvas",{ref:canvasRef,style:{position:'sticky',left:0,imageRendering:'pixelated'},className:"cursor-crosshair",onMouseMove:e=>{if(!canvasRef.current)return;const rect=canvasRef.current.getBoundingClientRect();const x=e.clientX-rect.left+(scrollLeft||0);const time=Math.max(0,x/zoom-leadInMargin);const clips=track.clips&&track.clips.length>0?track.clips:track.buffer?[{id:'default',buffer:track.buffer,startTime:track.startTime||0,name:track.name,speed:track.speed||1.0}]:[];// 1. Shift+Drag (TOP PRIORITY): Range selection on track waveform if(selectionMode==='local'&&localSelectionTrackId===track.id&&localSelLeft!==null&&localSelRight!==null&&localSelRight>localSelLeft){const hlLeftLocal=localSelLeft*zoom-scrollLeftVal;const hlWidth=(localSelRight-localSelLeft)*zoom;ctx.fillStyle='rgba(245, 158, 11, 0.15)';ctx.fillRect(hlLeftLocal,0,hlWidth,height);ctx.strokeStyle='#f59e0b';ctx.lineWidth=1;ctx.strokeRect(hlLeftLocal,0,hlWidth,height);}},[track,zoom,timelineWidth,viewportWidth,isSelected,markers,selectionMode,localSelectionTrackId,localSelLeft,localSelRight,snapValue,bpm,scrollLeft,recordingState,recTempMidiNotes,recStartTimelineTime,canvasRedrawCount,currentTime,selectedItemIds]);return/*#__PURE__*/React.createElement(React.Fragment,null,/*#__PURE__*/React.createElement("div",{key:"virtual-spacer",style:{width:`${timelineWidth}px`,height:'1px',pointerEvents:'none'}}),/*#__PURE__*/React.createElement("canvas",{ref:canvasRef,style:{position:'sticky',left:0,imageRendering:'pixelated'},className:"cursor-crosshair",onMouseMove:e=>{if(!canvasRef.current)return;const rect=canvasRef.current.getBoundingClientRect();const x=e.clientX-rect.left+(scrollLeft||0);const time=Math.max(0,x/zoom-leadInMargin);const clips=track.clips&&track.clips.length>0?track.clips:track.buffer?[{id:'default',buffer:track.buffer,startTime:track.startTime||0,name:track.name,speed:track.speed||1.0}]:[];// 1. Shift+Drag (TOP PRIORITY): Range selection on track waveform
if(e.shiftKey&&e.buttons>0){e.preventDefault();e.stopPropagation();const currentAnchor=getLocalAnchor?getLocalAnchor():null;const anchor=currentAnchor!==null&&currentAnchor!==undefined?currentAnchor:localSelectionStart!==null?localSelectionStart:currentTime;const selS=Math.min(anchor,time);const selE=Math.max(anchor,time);if(onSetSelectionMode)onSetSelectionMode('local');if(onSetLocalSelectionTrackId)onSetLocalSelectionTrackId(track.id);if(onSetLocalSelectionStart)onSetLocalSelectionStart(selS);if(onSetLocalSelectionEnd)onSetLocalSelectionEnd(selE);if(onSetSelectionStart)onSetSelectionStart(selS);if(onSetSelectionEnd)onSetSelectionEnd(selE);if(onSetCurrentTime)onSetCurrentTime(time);if(onSelectTrack)onSelectTrack(track.id);return;}// Check if hovering near local selection boundaries of this track if(e.shiftKey&&e.buttons>0){e.preventDefault();e.stopPropagation();const currentAnchor=getLocalAnchor?getLocalAnchor():null;const anchor=currentAnchor!==null&&currentAnchor!==undefined?currentAnchor:localSelectionStart!==null?localSelectionStart:currentTime;const selS=Math.min(anchor,time);const selE=Math.max(anchor,time);if(onSetSelectionMode)onSetSelectionMode('local');if(onSetLocalSelectionTrackId)onSetLocalSelectionTrackId(track.id);if(onSetLocalSelectionStart)onSetLocalSelectionStart(selS);if(onSetLocalSelectionEnd)onSetLocalSelectionEnd(selE);if(onSetSelectionStart)onSetSelectionStart(selS);if(onSetSelectionEnd)onSetSelectionEnd(selE);if(onSetCurrentTime)onSetCurrentTime(time);if(onSelectTrack)onSelectTrack(track.id);return;}// Check if hovering near local selection boundaries of this track
const isLocal=selectionMode==='local'&&localSelectionTrackId===track.id;if(isLocal&&localSelLeft!==null&&localSelRight!==null){const leftPx=localSelLeft*zoom;const rightPx=localSelRight*zoom;const distToLeft=Math.abs(x-leftPx);const distToRight=Math.abs(x-rightPx);if(distToLeft<=5||distToRight<=5){canvasRef.current.style.cursor='ew-resize';return;}}// Check if hovering near right edge of a clip for time-stretching (Alt key required) const isLocal=selectionMode==='local'&&localSelectionTrackId===track.id;if(isLocal&&localSelLeft!==null&&localSelRight!==null){const leftPx=localSelLeft*zoom;const rightPx=localSelRight*zoom;const distToLeft=Math.abs(x-leftPx);const distToRight=Math.abs(x-rightPx);if(distToLeft<=5||distToRight<=5){canvasRef.current.style.cursor='ew-resize';return;}}// Check if hovering near right edge of a clip for time-stretching (Alt key required)
const toleranceSec=8/zoom;const rightEdgeClip=clips.find(c=>{const duration=c.buffer.duration/(c.speed||1.0);return Math.abs(time-(c.startTime+duration))<=toleranceSec;});if(rightEdgeClip&&e.altKey){canvasRef.current.style.cursor='ew-resize';return;}// Check section/MIDI item hover for resize or drag const toleranceSec=8/zoom;const rightEdgeClip=clips.find(c=>{if(!c.buffer)return false;const duration=c.buffer.duration/(c.speed||1.0);return Math.abs(time-(c.startTime+duration))<=toleranceSec;});if(rightEdgeClip&&e.altKey){canvasRef.current.style.cursor='ew-resize';return;}// Check section/MIDI item hover for resize or drag
const allSections=track.sections||[];const allMidiItems=track.midiItems||[];const sectionTolerance=8/zoom;let foundSectionItem=null;let sectionItemEdge=null;const checkEdge=(item,startTime,dur)=>{const leftEdge=Math.abs(time-startTime)<=sectionTolerance;const rightEdge=Math.abs(time-(startTime+dur))<=sectionTolerance;if(leftEdge||rightEdge)return leftEdge?'left':'right';return null;};for(const sec of allSections){const edge=checkEdge(sec,sec.start,sec.duration);if(edge){foundSectionItem={type:'section',item:sec};sectionItemEdge=edge;break;}}if(!foundSectionItem){for(const midi of allMidiItems){const edge=checkEdge(midi,midi.startTime,midi.duration);if(edge){foundSectionItem={type:'midiItem',item:midi};sectionItemEdge=edge;break;}}}if(foundSectionItem&&sectionItemEdge){canvasRef.current.style.cursor='ew-resize';return;}// Check body hover for drag const allSections=track.sections||[];const allMidiItems=track.midiItems||[];const sectionTolerance=8/zoom;let foundSectionItem=null;let sectionItemEdge=null;const checkEdge=(item,startTime,dur)=>{const leftEdge=Math.abs(time-startTime)<=sectionTolerance;const rightEdge=Math.abs(time-(startTime+dur))<=sectionTolerance;if(leftEdge||rightEdge)return leftEdge?'left':'right';return null;};for(const sec of allSections){const edge=checkEdge(sec,sec.start,sec.duration);if(edge){foundSectionItem={type:'section',item:sec};sectionItemEdge=edge;break;}}if(!foundSectionItem){for(const midi of allMidiItems){const edge=checkEdge(midi,midi.startTime,midi.duration);if(edge){foundSectionItem={type:'midiItem',item:midi};sectionItemEdge=edge;break;}}}if(foundSectionItem&&sectionItemEdge){canvasRef.current.style.cursor='ew-resize';return;}// Check body hover for drag
if(!foundSectionItem){for(const sec of allSections){if(time>=sec.start&&time<sec.start+sec.duration){foundSectionItem={type:'section',item:sec};break;}}}if(!foundSectionItem){for(const midi of allMidiItems){if(time>=midi.startTime&&time<midi.startTime+midi.duration){foundSectionItem={type:'midiItem',item:midi};break;}}}if(foundSectionItem){canvasRef.current.style.cursor='grab';return;}const hoveredClip=clips.find(c=>time>=c.startTime&&time<c.startTime+c.buffer.duration/(c.speed||1.0));const isOverClip=!!hoveredClip;if(activeTool==='pen'){canvasRef.current.style.cursor=isOverClip?'copy':'not-allowed';}else if(activeTool==='grab'){canvasRef.current.style.cursor=isOverClip?'grab':'default';}else if(activeTool==='razor'){canvasRef.current.style.cursor=isOverClip?'cell':'not-allowed';}else{// select tool if(!foundSectionItem){for(const sec of allSections){if(time>=sec.start&&time<sec.start+sec.duration){foundSectionItem={type:'section',item:sec};break;}}}if(!foundSectionItem){for(const midi of allMidiItems){if(time>=midi.startTime&&time<midi.startTime+midi.duration){foundSectionItem={type:'midiItem',item:midi};break;}}}if(foundSectionItem){canvasRef.current.style.cursor='grab';return;}const hoveredClip=clips.find(c=>c.buffer&&time>=c.startTime&&time<c.startTime+c.buffer.duration/(c.speed||1.0));const isOverClip=!!hoveredClip;if(activeTool==='pen'){canvasRef.current.style.cursor=isOverClip?'copy':'not-allowed';}else if(activeTool==='grab'){canvasRef.current.style.cursor=isOverClip?'grab':'default';}else if(activeTool==='razor'){canvasRef.current.style.cursor=isOverClip?'cell':'not-allowed';}else{// select tool
canvasRef.current.style.cursor=isOverClip&&(e.altKey||e.ctrlKey)?'grab':'crosshair';}},onMouseDown:e=>{// Ignore right-click for local selection drag (context menu handles it) canvasRef.current.style.cursor=isOverClip&&(e.altKey||e.ctrlKey)?'grab':'crosshair';}},onMouseDown:e=>{// Ignore right-click for local selection drag (context menu handles it)
if(e.button===2)return;const rect=canvasRef.current.getBoundingClientRect();const x=e.clientX-rect.left+(scrollLeft||0);const time=Math.max(0,x/zoom-leadInMargin);onSelectTrack(track.id);const clips=track.clips&&track.clips.length>0?track.clips:track.buffer?[{id:'default',buffer:track.buffer,startTime:track.startTime||0,name:track.name,speed:track.speed||1.0}]:[];// Check if Ctrl+Click to exit selection if(e.button===2)return;const rect=canvasRef.current.getBoundingClientRect();const x=e.clientX-rect.left+(scrollLeft||0);const time=Math.max(0,x/zoom-leadInMargin);onSelectTrack(track.id);const clips=track.clips&&track.clips.length>0?track.clips:track.buffer?[{id:'default',buffer:track.buffer,startTime:track.startTime||0,name:track.name,speed:track.speed||1.0}]:[];// Check if Ctrl+Click to exit selection
if(e.ctrlKey&&selectionMode){e.preventDefault();e.stopPropagation();if(onClearLocalSelection)onClearLocalSelection();if(onSetSelectionMode)onSetSelectionMode(null);if(onSetSelectionStart)onSetSelectionStart(null);if(onSetSelectionEnd)onSetSelectionEnd(null);return;}// 1. Shift+Click (TOP PRIORITY): Range selection on track waveform if(e.ctrlKey&&selectionMode){e.preventDefault();e.stopPropagation();if(onClearLocalSelection)onClearLocalSelection();if(onSetSelectionMode)onSetSelectionMode(null);if(onSetSelectionStart)onSetSelectionStart(null);if(onSetSelectionEnd)onSetSelectionEnd(null);return;}// 1. Shift+Click (TOP PRIORITY): Range selection on track waveform
if(e.shiftKey){e.preventDefault();e.stopPropagation();const currentAnchor=getLocalAnchor?getLocalAnchor():null;const anchor=currentAnchor!==null&&currentAnchor!==undefined?currentAnchor:localSelectionStart!==null?localSelectionStart:currentTime;const selS=Math.min(anchor,time);const selE=Math.max(anchor,time);if(onSetSelectionMode)onSetSelectionMode('local');if(onSetLocalSelectionTrackId)onSetLocalSelectionTrackId(track.id);if(onSetLocalSelectionStart)onSetLocalSelectionStart(selS);if(onSetLocalSelectionEnd)onSetLocalSelectionEnd(selE);if(onSetSelectionStart)onSetSelectionStart(selS);if(onSetSelectionEnd)onSetSelectionEnd(selE);if(onSetCurrentTime)onSetCurrentTime(time);if(onSelectTrack)onSelectTrack(track.id);return;}// Check if dragging selection boundaries (local mode) if(e.shiftKey){e.preventDefault();e.stopPropagation();const currentAnchor=getLocalAnchor?getLocalAnchor():null;const anchor=currentAnchor!==null&&currentAnchor!==undefined?currentAnchor:localSelectionStart!==null?localSelectionStart:currentTime;const selS=Math.min(anchor,time);const selE=Math.max(anchor,time);if(onSetSelectionMode)onSetSelectionMode('local');if(onSetLocalSelectionTrackId)onSetLocalSelectionTrackId(track.id);if(onSetLocalSelectionStart)onSetLocalSelectionStart(selS);if(onSetLocalSelectionEnd)onSetLocalSelectionEnd(selE);if(onSetSelectionStart)onSetSelectionStart(selS);if(onSetSelectionEnd)onSetSelectionEnd(selE);if(onSetCurrentTime)onSetCurrentTime(time);if(onSelectTrack)onSelectTrack(track.id);return;}// Check if dragging selection boundaries (local mode)
const isLocal=selectionMode==='local'&&localSelectionTrackId===track.id;if(isLocal&&localSelLeft!==null&&localSelRight!==null){const leftPx=localSelLeft*zoom;const rightPx=localSelRight*zoom;const distToLeft=Math.abs(x-leftPx);const distToRight=Math.abs(x-rightPx);if(distToLeft<=5){e.preventDefault();e.stopPropagation();if(onSelectionEdgeDragStart)onSelectionEdgeDragStart(e,track.id,'left');return;}else if(distToRight<=5){e.preventDefault();e.stopPropagation();if(onSelectionEdgeDragStart)onSelectionEdgeDragStart(e,track.id,'right');return;}}// Check if time-stretching (Alt + Right Edge) const isLocal=selectionMode==='local'&&localSelectionTrackId===track.id;if(isLocal&&localSelLeft!==null&&localSelRight!==null){const leftPx=localSelLeft*zoom;const rightPx=localSelRight*zoom;const distToLeft=Math.abs(x-leftPx);const distToRight=Math.abs(x-rightPx);if(distToLeft<=5){e.preventDefault();e.stopPropagation();if(onSelectionEdgeDragStart)onSelectionEdgeDragStart(e,track.id,'left');return;}else if(distToRight<=5){e.preventDefault();e.stopPropagation();if(onSelectionEdgeDragStart)onSelectionEdgeDragStart(e,track.id,'right');return;}}// Check if time-stretching (Alt + Right Edge)
const toleranceSec=8/zoom;const rightEdgeClip=clips.find(c=>{const duration=c.buffer.duration/(c.speed||1.0);return Math.abs(time-(c.startTime+duration))<=toleranceSec;});if(rightEdgeClip&&e.altKey){e.preventDefault();e.stopPropagation();if(onClipStretchStart){onClipStretchStart(track.id,rightEdgeClip.id,time);}return;}// Check section/MIDI item edge for resize, then body for drag const toleranceSec=8/zoom;const rightEdgeClip=clips.find(c=>{if(!c.buffer)return false;const duration=c.buffer.duration/(c.speed||1.0);return Math.abs(time-(c.startTime+duration))<=toleranceSec;});if(rightEdgeClip&&e.altKey){e.preventDefault();e.stopPropagation();if(onClipStretchStart){onClipStretchStart(track.id,rightEdgeClip.id,time);}return;}// Check section/MIDI item edge for resize, then body for drag
const secItems=track.sections||[];const midiItems=track.midiItems||[];const secTol=8/zoom;let hitItem=null;let hitEdge=null;for(const sec of secItems){if(Math.abs(time-sec.start)<=secTol){hitItem={type:'section',id:sec.id,start:sec.start,dur:sec.duration};hitEdge='left';break;}if(Math.abs(time-(sec.start+sec.duration))<=secTol){hitItem={type:'section',id:sec.id,start:sec.start,dur:sec.duration};hitEdge='right';break;}}if(!hitItem){for(const midi of midiItems){if(Math.abs(time-midi.startTime)<=secTol){hitItem={type:'midiItem',id:midi.id,start:midi.startTime,dur:midi.duration};hitEdge='left';break;}if(Math.abs(time-(midi.startTime+midi.duration))<=secTol){hitItem={type:'midiItem',id:midi.id,start:midi.startTime,dur:midi.duration};hitEdge='right';break;}}}if(hitItem&&hitEdge){e.preventDefault();e.stopPropagation();if(onSectionItemResizeStart)onSectionItemResizeStart(track.id,hitItem.type,hitItem.id,hitEdge,time);return;}if(!hitItem){for(const sec of secItems){if(time>=sec.start&&time<sec.start+sec.duration){hitItem={type:'section',id:sec.id,start:sec.start};break;}}}if(!hitItem){for(const midi of midiItems){if(time>=midi.startTime&&time<midi.startTime+midi.duration){hitItem={type:'midiItem',id:midi.id,start:midi.startTime};break;}}}if(hitItem&&!e.altKey&&!e.shiftKey){e.preventDefault();e.stopPropagation();if(e.ctrlKey){// Ctrl+Click: toggle selection (add/remove from group) + set pending copy-drag const secItems=track.sections||[];const midiItems=track.midiItems||[];const secTol=8/zoom;let hitItem=null;let hitEdge=null;for(const sec of secItems){if(Math.abs(time-sec.start)<=secTol){hitItem={type:'section',id:sec.id,start:sec.start,dur:sec.duration};hitEdge='left';break;}if(Math.abs(time-(sec.start+sec.duration))<=secTol){hitItem={type:'section',id:sec.id,start:sec.start,dur:sec.duration};hitEdge='right';break;}}if(!hitItem){for(const midi of midiItems){if(Math.abs(time-midi.startTime)<=secTol){hitItem={type:'midiItem',id:midi.id,start:midi.startTime,dur:midi.duration};hitEdge='left';break;}if(Math.abs(time-(midi.startTime+midi.duration))<=secTol){hitItem={type:'midiItem',id:midi.id,start:midi.startTime,dur:midi.duration};hitEdge='right';break;}}}if(hitItem&&hitEdge){e.preventDefault();e.stopPropagation();if(onSectionItemResizeStart)onSectionItemResizeStart(track.id,hitItem.type,hitItem.id,hitEdge,time);return;}if(!hitItem){for(const sec of secItems){if(time>=sec.start&&time<sec.start+sec.duration){hitItem={type:'section',id:sec.id,start:sec.start};break;}}}if(!hitItem){for(const midi of midiItems){if(time>=midi.startTime&&time<midi.startTime+midi.duration){hitItem={type:'midiItem',id:midi.id,start:midi.startTime};break;}}}if(hitItem&&!e.altKey&&!e.shiftKey){e.preventDefault();e.stopPropagation();if(e.ctrlKey){// Ctrl+Click: toggle selection (add/remove from group) + set pending copy-drag
var preToggle=selectedItemIds?new Set(selectedItemIds):new Set();if(selectedItemIds&&selectedItemIds.has(hitItem.id)){if(onDeselectItem)onDeselectItem(hitItem.id);}else{if(onAddToSelection)onAddToSelection(hitItem.id);}if(onSetPendingDrag)onSetPendingDrag(track.id,hitItem.type,hitItem.id,time-hitItem.start,e.nativeEvent||e,preToggle);}else{// Click: select this item (clear others if not already selected). var preToggle=selectedItemIds?new Set(selectedItemIds):new Set();if(selectedItemIds&&selectedItemIds.has(hitItem.id)){if(onDeselectItem)onDeselectItem(hitItem.id);}else{if(onAddToSelection)onAddToSelection(hitItem.id);}if(onSetPendingDrag)onSetPendingDrag(track.id,hitItem.type,hitItem.id,time-hitItem.start,e.nativeEvent||e,preToggle);}else{// Click: select this item (clear others if not already selected).
// Drag only starts after a small movement threshold (5px) — click alone // Drag only starts after a small movement threshold (5px) — click alone
// just selects; this unifies section/MIDI/clip behavior and stops // just selects; this unifies section/MIDI/clip behavior and stops
// accidental moves from mouse jitter. // accidental moves from mouse jitter.
if(!selectedItemIds||!selectedItemIds.has(hitItem.id)){if(onClearSelection)onClearSelection();if(onAddToSelection)onAddToSelection(hitItem.id);}// Drag all currently selected items (or just this one) if(!selectedItemIds||!selectedItemIds.has(hitItem.id)){if(onClearSelection)onClearSelection();if(onAddToSelection)onAddToSelection(hitItem.id);}// Drag all currently selected items (or just this one)
var dragIds=selectedItemIds&&selectedItemIds.has(hitItem.id)&&selectedItemIds.size>1?selectedItemIds:new Set([hitItem.id]);if(onSetPendingDragMove)onSetPendingDragMove(track.id,hitItem.type,hitItem.id,time-hitItem.start,e.nativeEvent||e,dragIds);}return;}const clickedClip=clips.find(c=>time>=c.startTime&&time<c.startTime+c.buffer.duration/(c.speed||1.0));// Set selected clip ID var dragIds=selectedItemIds&&selectedItemIds.has(hitItem.id)&&selectedItemIds.size>1?selectedItemIds:new Set([hitItem.id]);if(onSetPendingDragMove)onSetPendingDragMove(track.id,hitItem.type,hitItem.id,time-hitItem.start,e.nativeEvent||e,dragIds);}return;}const clickedClip=clips.find(c=>c.buffer&&time>=c.startTime&&time<c.startTime+c.buffer.duration/(c.speed||1.0));// Set selected clip ID
if(clickedClip){setSelectedClipId({trackId:track.id,clipId:clickedClip.id==='default'?'default_'+track.id:clickedClip.id});}else{setSelectedClipId(null);}if(activeTool==='pen'&&!e.ctrlKey){if(clickedClip){e.preventDefault();e.stopPropagation();if(onEditClipInSubTab){onEditClipInSubTab(track.id,clickedClip.id);}}return;}if(activeTool==='razor'&&!e.ctrlKey){if(clickedClip){e.preventDefault();e.stopPropagation();if(onSplitTrackAtTime){onSplitTrackAtTime(track.id,clickedClip.id,time);}}return;}if(activeTool==='grab'){if(onTrackLaneMouseDown){onTrackLaneMouseDown(track.id,time,e);}if(clickedClip){e.preventDefault();e.stopPropagation();if(onClipDragStart){onClipDragStart(track.id,clickedClip.id,time-clickedClip.startTime,e.ctrlKey);}}else{onPlayheadSet(time);}return;}// Check for click drag clip (plain click = move, Alt = sweep-select duration, Ctrl = duplicate) if(clickedClip){setSelectedClipId({trackId:track.id,clipId:clickedClip.id==='default'?'default_'+track.id:clickedClip.id});}else{setSelectedClipId(null);}if(activeTool==='pen'&&!e.ctrlKey){if(clickedClip){e.preventDefault();e.stopPropagation();if(onEditClipInSubTab){onEditClipInSubTab(track.id,clickedClip.id);}}return;}if(activeTool==='razor'&&!e.ctrlKey){if(clickedClip){e.preventDefault();e.stopPropagation();if(onSplitTrackAtTime){onSplitTrackAtTime(track.id,clickedClip.id,time);}}return;}if(activeTool==='grab'){if(onTrackLaneMouseDown){onTrackLaneMouseDown(track.id,time,e);}if(clickedClip){e.preventDefault();e.stopPropagation();if(onClipDragStart){onClipDragStart(track.id,clickedClip.id,time-clickedClip.startTime,e.ctrlKey);}}else{onPlayheadSet(time);}return;}// Check for click drag clip (plain click = move, Alt = sweep-select duration, Ctrl = duplicate)
if(clickedClip&&e.ctrlKey){e.preventDefault();e.stopPropagation();// Ctrl+Click: toggle selection, store pending drag w/ pre-toggle snapshot if(clickedClip&&e.ctrlKey){e.preventDefault();e.stopPropagation();// Ctrl+Click: toggle selection, store pending drag w/ pre-toggle snapshot
var clipCanonicalId=clickedClip.id==='default'?'default_'+track.id:clickedClip.id;var clipPreToggleSnapshot=selectedItemIds?new Set(selectedItemIds):new Set();if(selectedItemIds&&selectedItemIds.has(clipCanonicalId)){if(onDeselectItem)onDeselectItem(clipCanonicalId);}else if(onAddToSelection){onAddToSelection(clipCanonicalId);}if(onSetPendingDrag)onSetPendingDrag(track.id,'clip',clipCanonicalId,time-clickedClip.startTime,e.nativeEvent||e,clipPreToggleSnapshot);return;}// Alt+Click on a clip: sweep-select duration (the OLD plain click+drag var clipCanonicalId=clickedClip.id==='default'?'default_'+track.id:clickedClip.id;var clipPreToggleSnapshot=selectedItemIds?new Set(selectedItemIds):new Set();if(selectedItemIds&&selectedItemIds.has(clipCanonicalId)){if(onDeselectItem)onDeselectItem(clipCanonicalId);}else if(onAddToSelection){onAddToSelection(clipCanonicalId);}if(onSetPendingDrag)onSetPendingDrag(track.id,'clip',clipCanonicalId,time-clickedClip.startTime,e.nativeEvent||e,clipPreToggleSnapshot);return;}// Alt+Click on a clip: sweep-select duration (the OLD plain click+drag
@@ -263,7 +263,7 @@ if(clickedClip){e.preventDefault();e.stopPropagation();var clipCanonicalId2=clic
if(e.ctrlKey&&!clickedClip&&!hitItem){e.preventDefault();e.stopPropagation();// Start a pending sweep: mouseup with no drag → deselect all; drag → marquee if(e.ctrlKey&&!clickedClip&&!hitItem){e.preventDefault();e.stopPropagation();// Start a pending sweep: mouseup with no drag → deselect all; drag → marquee
if(onSweepSelectStart)onSweepSelectStart(track.id,time,e.clientY);return;}onPlayheadSet(time);if(onTrackLaneMouseDown){onTrackLaneMouseDown(track.id,time,e);}e.stopPropagation();},onDoubleClick:e=>{const rect=canvasRef.current.getBoundingClientRect();const x=e.clientX-rect.left+(scrollLeft||0);const time=Math.max(0,x/zoom-leadInMargin);const clips=track.clips&&track.clips.length>0?track.clips:track.buffer?[{id:'default',buffer:track.buffer,startTime:track.startTime||0,name:track.name,speed:track.speed||1.0}]:[];// Check double-click on section first if(onSweepSelectStart)onSweepSelectStart(track.id,time,e.clientY);return;}onPlayheadSet(time);if(onTrackLaneMouseDown){onTrackLaneMouseDown(track.id,time,e);}e.stopPropagation();},onDoubleClick:e=>{const rect=canvasRef.current.getBoundingClientRect();const x=e.clientX-rect.left+(scrollLeft||0);const time=Math.max(0,x/zoom-leadInMargin);const clips=track.clips&&track.clips.length>0?track.clips:track.buffer?[{id:'default',buffer:track.buffer,startTime:track.startTime||0,name:track.name,speed:track.speed||1.0}]:[];// Check double-click on section first
const dblSecItems=track.sections||[];let dblSecHit=null;for(const sec of dblSecItems){if(time>=sec.start&&time<sec.start+sec.duration){dblSecHit=sec;break;}}if(dblSecHit){e.preventDefault();e.stopPropagation();if(onEditSectionInTab)onEditSectionInTab(track.id,dblSecHit.id);return;}// Check double-click on MIDI item next const dblSecItems=track.sections||[];let dblSecHit=null;for(const sec of dblSecItems){if(time>=sec.start&&time<sec.start+sec.duration){dblSecHit=sec;break;}}if(dblSecHit){e.preventDefault();e.stopPropagation();if(onEditSectionInTab)onEditSectionInTab(track.id,dblSecHit.id);return;}// Check double-click on MIDI item next
const dblMidiItems=track.midiItems||[];let dblMidiHit=null;for(const midi of dblMidiItems){if(time>=midi.startTime&&time<midi.startTime+midi.duration){dblMidiHit=midi;break;}}if(dblMidiHit){e.preventDefault();e.stopPropagation();if(onEditMidiInTab)onEditMidiInTab(track.id,dblMidiHit.id);return;}const clickedClip=clips.find(c=>time>=c.startTime&&time<c.startTime+c.buffer.duration/(c.speed||1.0));if(clickedClip){e.preventDefault();e.stopPropagation();if(onEditClipInSubTab){onEditClipInSubTab(track.id,clickedClip.id);}}},onContextMenu:e=>{e.preventDefault();e.stopPropagation();onSelectTrack(track.id);const rect=canvasRef.current.getBoundingClientRect();const x=e.clientX-rect.left+(scrollLeft||0);const time=Math.max(0,x/zoom-leadInMargin);// Detect section under cursor const dblMidiItems=track.midiItems||[];let dblMidiHit=null;for(const midi of dblMidiItems){if(time>=midi.startTime&&time<midi.startTime+midi.duration){dblMidiHit=midi;break;}}if(dblMidiHit){e.preventDefault();e.stopPropagation();if(onEditMidiInTab)onEditMidiInTab(track.id,dblMidiHit.id);return;}const clickedClip=clips.find(c=>c.buffer&&time>=c.startTime&&time<c.startTime+c.buffer.duration/(c.speed||1.0));if(clickedClip){e.preventDefault();e.stopPropagation();if(onEditClipInSubTab){onEditClipInSubTab(track.id,clickedClip.id);}}},onContextMenu:e=>{e.preventDefault();e.stopPropagation();onSelectTrack(track.id);const rect=canvasRef.current.getBoundingClientRect();const x=e.clientX-rect.left+(scrollLeft||0);const time=Math.max(0,x/zoom-leadInMargin);// Detect section under cursor
const secList=track.sections||[];let hitSectionId=null;for(const sec of secList){if(time>=sec.start&&time<sec.start+sec.duration){hitSectionId=sec.id;break;}}if(onContextMenu)onContextMenu(e,track.id,time,hitSectionId);}}));};const TimelineRuler=({bpm,zoom,timelineWidth,viewportWidth,onPlayheadSet,snapValue,onRulerMouseDown,scrollLeft,canvasRedrawCount})=>{const canvasRef=useRef(null);const RULER_HEIGHT=40;const drawWidth=Math.min(timelineWidth,viewportWidth);useEffect(()=>{const canvas=canvasRef.current;if(!canvas)return;const ctx=canvas.getContext('2d');const dpr=window.devicePixelRatio||1;let scrollLeftVal=scrollLeft||0;const height=RULER_HEIGHT;canvas.width=Math.min(Math.round(drawWidth*dpr),32768);canvas.height=Math.min(Math.round(height*dpr),32768);ctx.scale(dpr,dpr);ctx.imageSmoothingEnabled=false;canvas.style.width=`${drawWidth}px`;canvas.style.height=`${height}px`;ctx.fillStyle='#242424';ctx.fillRect(0,0,drawWidth,height);ctx.strokeStyle='rgba(255,255,255,0.08)';ctx.lineWidth=1;ctx.beginPath();ctx.moveTo(0,height-0.5);ctx.lineTo(drawWidth,height-0.5);ctx.stroke();const CLIP_BUFFER=400;const PADDING_LEFT=0;const tStart=scrollLeftVal/zoom-PADDING_LEFT;const tEnd=(scrollLeftVal+drawWidth)/zoom+CLIP_BUFFER/zoom;// Draw bar markers (aligned with TempoTrackLane) const secList=track.sections||[];let hitSectionId=null;for(const sec of secList){if(time>=sec.start&&time<sec.start+sec.duration){hitSectionId=sec.id;break;}}if(onContextMenu)onContextMenu(e,track.id,time,hitSectionId);}}));};const TimelineRuler=({bpm,zoom,timelineWidth,viewportWidth,onPlayheadSet,snapValue,onRulerMouseDown,scrollLeft,canvasRedrawCount})=>{const canvasRef=useRef(null);const RULER_HEIGHT=40;const drawWidth=Math.min(timelineWidth,viewportWidth);useEffect(()=>{const canvas=canvasRef.current;if(!canvas)return;const ctx=canvas.getContext('2d');const dpr=window.devicePixelRatio||1;let scrollLeftVal=scrollLeft||0;const height=RULER_HEIGHT;canvas.width=Math.min(Math.round(drawWidth*dpr),32768);canvas.height=Math.min(Math.round(height*dpr),32768);ctx.scale(dpr,dpr);ctx.imageSmoothingEnabled=false;canvas.style.width=`${drawWidth}px`;canvas.style.height=`${height}px`;ctx.fillStyle='#242424';ctx.fillRect(0,0,drawWidth,height);ctx.strokeStyle='rgba(255,255,255,0.08)';ctx.lineWidth=1;ctx.beginPath();ctx.moveTo(0,height-0.5);ctx.lineTo(drawWidth,height-0.5);ctx.stroke();const CLIP_BUFFER=400;const PADDING_LEFT=0;const tStart=scrollLeftVal/zoom-PADDING_LEFT;const tEnd=(scrollLeftVal+drawWidth)/zoom+CLIP_BUFFER/zoom;// Draw bar markers (aligned with TempoTrackLane)
const beatDuration=60/bpm;const barDuration=beatDuration*4;const firstBarNum=Math.floor(tStart/barDuration);const lastBarNum=Math.ceil(tEnd/barDuration);for(let bn=firstBarNum;bn<=lastBarNum;bn++){const t=bn*barDuration;const localX=(t-tStart)*zoom;if(localX<-CLIP_BUFFER||localX>drawWidth+CLIP_BUFFER)continue;ctx.strokeStyle='rgba(255, 255, 255, 0.25)';ctx.lineWidth=1.2;ctx.beginPath();ctx.moveTo(localX,0);ctx.lineTo(localX,height);ctx.stroke();ctx.fillStyle='rgba(255, 255, 255, 0.8)';ctx.font='bold 10px Inter, sans-serif';ctx.textAlign='center';ctx.fillText(`${bn}`,localX,32);}// Draw time duration labels with drag-selection markers const beatDuration=60/bpm;const barDuration=beatDuration*4;const firstBarNum=Math.floor(tStart/barDuration);const lastBarNum=Math.ceil(tEnd/barDuration);for(let bn=firstBarNum;bn<=lastBarNum;bn++){const t=bn*barDuration;const localX=(t-tStart)*zoom;if(localX<-CLIP_BUFFER||localX>drawWidth+CLIP_BUFFER)continue;ctx.strokeStyle='rgba(255, 255, 255, 0.25)';ctx.lineWidth=1.2;ctx.beginPath();ctx.moveTo(localX,0);ctx.lineTo(localX,height);ctx.stroke();ctx.fillStyle='rgba(255, 255, 255, 0.8)';ctx.font='bold 10px Inter, sans-serif';ctx.textAlign='center';ctx.fillText(`${bn}`,localX,32);}// Draw time duration labels with drag-selection markers
const minTimePx=60;const rawSecInt=Math.max(1,Math.ceil(minTimePx/zoom));const timePowers=[1,2,5,10,30,60];let secInterval=timePowers.find(p=>p>=rawSecInt)||120;if(secInterval*zoom<minTimePx)secInterval=Math.ceil(minTimePx/zoom);const firstSec=Math.floor(tStart/secInterval)*secInterval;for(let t=firstSec;t<=tEnd;t+=secInterval){const localX=(t-tStart)*zoom;if(localX<-CLIP_BUFFER||localX>drawWidth+CLIP_BUFFER)continue;ctx.strokeStyle='rgba(255, 180, 100, 0.12)';ctx.lineWidth=0.8;ctx.beginPath();ctx.moveTo(localX,0);ctx.lineTo(localX,height);ctx.stroke();ctx.strokeStyle='rgba(255, 180, 100, 0.3)';ctx.lineWidth=1.5;ctx.beginPath();ctx.moveTo(localX,0);ctx.lineTo(localX,10);ctx.stroke();ctx.fillStyle='rgba(255, 180, 100, 0.7)';ctx.font='bold 11px monospace';ctx.textAlign='center';ctx.fillText(formatTimeSimple(t),localX,24);}},[bpm,zoom,timelineWidth,viewportWidth,scrollLeft,canvasRedrawCount]);return React.createElement(React.Fragment,null,React.createElement("div",{key:"virtual-spacer-ruler",style:{width:`${timelineWidth}px`,height:'1px',pointerEvents:'none'}}),React.createElement("canvas",{ref:canvasRef,style:{position:'sticky',left:0,imageRendering:'pixelated'},className:"cursor-crosshair",onMouseDown:e=>{const rect=canvasRef.current.getBoundingClientRect();const x=e.clientX-rect.left+(scrollLeft||0);const time=Math.max(0,x/zoom);if(e.shiftKey){e.preventDefault();e.stopPropagation();}if(onRulerMouseDown)onRulerMouseDown(e);else onPlayheadSet(time,e.shiftKey);}}));};const TempoTrackLane=({bpm,zoom,timelineWidth,viewportWidth,onPlayheadSet,snapValue,onRulerMouseDown,scrollLeft,canvasRedrawCount,leadInMargin:propLeadIn})=>{const canvasRef=useRef(null);const drawWidth=Math.min(timelineWidth,viewportWidth);useEffect(()=>{const canvas=canvasRef.current;if(!canvas)return;const ctx=canvas.getContext('2d');const dpr=window.devicePixelRatio||1;// Use scrollLeft prop directly (DOM traversal broken by sticky wrapper) const minTimePx=60;const rawSecInt=Math.max(1,Math.ceil(minTimePx/zoom));const timePowers=[1,2,5,10,30,60];let secInterval=timePowers.find(p=>p>=rawSecInt)||120;if(secInterval*zoom<minTimePx)secInterval=Math.ceil(minTimePx/zoom);const firstSec=Math.floor(tStart/secInterval)*secInterval;for(let t=firstSec;t<=tEnd;t+=secInterval){const localX=(t-tStart)*zoom;if(localX<-CLIP_BUFFER||localX>drawWidth+CLIP_BUFFER)continue;ctx.strokeStyle='rgba(255, 180, 100, 0.12)';ctx.lineWidth=0.8;ctx.beginPath();ctx.moveTo(localX,0);ctx.lineTo(localX,height);ctx.stroke();ctx.strokeStyle='rgba(255, 180, 100, 0.3)';ctx.lineWidth=1.5;ctx.beginPath();ctx.moveTo(localX,0);ctx.lineTo(localX,10);ctx.stroke();ctx.fillStyle='rgba(255, 180, 100, 0.7)';ctx.font='bold 11px monospace';ctx.textAlign='center';ctx.fillText(formatTimeSimple(t),localX,24);}},[bpm,zoom,timelineWidth,viewportWidth,scrollLeft,canvasRedrawCount]);return React.createElement(React.Fragment,null,React.createElement("div",{key:"virtual-spacer-ruler",style:{width:`${timelineWidth}px`,height:'1px',pointerEvents:'none'}}),React.createElement("canvas",{ref:canvasRef,style:{position:'sticky',left:0,imageRendering:'pixelated'},className:"cursor-crosshair",onMouseDown:e=>{const rect=canvasRef.current.getBoundingClientRect();const x=e.clientX-rect.left+(scrollLeft||0);const time=Math.max(0,x/zoom);if(e.shiftKey){e.preventDefault();e.stopPropagation();}if(onRulerMouseDown)onRulerMouseDown(e);else onPlayheadSet(time,e.shiftKey);}}));};const TempoTrackLane=({bpm,zoom,timelineWidth,viewportWidth,onPlayheadSet,snapValue,onRulerMouseDown,scrollLeft,canvasRedrawCount,leadInMargin:propLeadIn})=>{const canvasRef=useRef(null);const drawWidth=Math.min(timelineWidth,viewportWidth);useEffect(()=>{const canvas=canvasRef.current;if(!canvas)return;const ctx=canvas.getContext('2d');const dpr=window.devicePixelRatio||1;// Use scrollLeft prop directly (DOM traversal broken by sticky wrapper)
+25 -3
View File
@@ -25,6 +25,7 @@
let _pendingOutputDestination = null; let _pendingOutputDestination = null;
let _outputDestination = null; // cache đích route — dedupe swap dư giữa stream let _outputDestination = null; // cache đích route — dedupe swap dư giữa stream
let _validPercCache = {}; // { sfId: [bank, prog] | null } — preset percussion hợp lệ let _validPercCache = {}; // { sfId: [bank, prog] | null } — preset percussion hợp lệ
let _sfLoadFailAt = {}; // { sfId: timestamp } — cooldown 10s sau load fail
let _scheduledNotes = []; let _scheduledNotes = [];
let _loadPromises = {}; let _loadPromises = {};
let _sfloadSeq = 0; let _sfloadSeq = 0;
@@ -326,8 +327,15 @@
var url = "/api/v1/plugins/soundfonts/download/" + encodeURIComponent(sfId) + "?t=" + Date.now(); var url = "/api/v1/plugins/soundfonts/download/" + encodeURIComponent(sfId) + "?t=" + Date.now();
var resp = await fetch(url); var resp = await fetch(url);
if (!resp.ok) { if (!resp.ok) {
console.warn("[SonicSF] SoundFont not found:", sfId); // Fallback: font bundled theo deployment (static/soundfonts —
return false; // serve qua /soundfonts/{f} — catalog default-soundfonts).
var url2 = "/soundfonts/" + encodeURIComponent(sfId.replace(/^sf_/, '')) + "?t=" + Date.now();
var resp2 = await fetch(url2);
if (!resp2.ok) {
console.warn("[SonicSF] SoundFont not found:", sfId);
return false;
}
resp = resp2;
} }
buf = await resp.arrayBuffer(); buf = await resp.arrayBuffer();
if (cache) await cache.saveBuffer(sfId, buf); if (cache) await cache.saveBuffer(sfId, buf);
@@ -543,10 +551,24 @@
// Quick instrument pick on a track does not pre-load it, so load // Quick instrument pick on a track does not pre-load it, so load
// lazily here and retry the note once the font is ready. // lazily here and retry the note once the font is ready.
if (finalSfId && !_sfHandleMap.has(finalSfId)) { if (finalSfId && !_sfHandleMap.has(finalSfId)) {
// Cooldown lỗi: font 404 → KHÔNG spam fetch mỗi note (10s)
// — note chạy thẳng fallback để CÓ ÂM.
var _lastFail = _sfLoadFailAt[finalSfId] || 0;
if (Date.now() - _lastFail < 10000) {
try { self._playNoteFallback(note, velocity, durationMs, startTime, program, null, channel, synthEngine); } catch (e) {}
return;
}
console.log('[SonicSF] soundfont not loaded yet, loading:', finalSfId); console.log('[SonicSF] soundfont not loaded yet, loading:', finalSfId);
self.loadSoundFont(finalSfId).then(function (ok) { self.loadSoundFont(finalSfId).then(function (ok) {
console.log('[SonicSF] loadSoundFont result:', ok, 'for:', finalSfId); console.log('[SonicSF] loadSoundFont result:', ok, 'for:', finalSfId);
if (ok) doNote(); if (ok) {
doNote();
} else {
// Font KHÔNG tải được (404/format) → KHÔNG drop note
// câm lặng ("bỏ qua WASM") — fallback oscillator.
_sfLoadFailAt[finalSfId] = Date.now();
try { self._playNoteFallback(note, velocity, durationMs, startTime, program, null, channel, synthEngine); } catch (e) {}
}
}); });
return; return;
} }
+2 -2
View File
@@ -16,7 +16,7 @@
<script src="/static/js/services/audioEngine.js?v=202607271016"></script> <script src="/static/js/services/audioEngine.js?v=202607271016"></script>
<script src="/static/js/services/storage.js?v=202608038200"></script> <script src="/static/js/services/storage.js?v=202608038200"></script>
<script src="/static/js/services/soundfontStorage.js?v=202607271016"></script> <script src="/static/js/services/soundfontStorage.js?v=202607271016"></script>
<script src="/static/js/services/soundfontPlayer.js?v=202608060200"></script> <script src="/static/js/services/soundfontPlayer.js?v=202608060630"></script>
<script src="/static/js/services/aiGateway.js?v=202608037200"></script> <script src="/static/js/services/aiGateway.js?v=202608037200"></script>
<script src="/static/js/services/dawCommandDispatcher.js?v=202607271016"></script> <script src="/static/js/services/dawCommandDispatcher.js?v=202607271016"></script>
<script src="/static/js/services/pianoRollTabService.js?v=202607272044"></script> <script src="/static/js/services/pianoRollTabService.js?v=202607272044"></script>
@@ -24,7 +24,7 @@
<script src="/static/js/services/midiExtractor.js?v=202607281052"></script> <script src="/static/js/services/midiExtractor.js?v=202607281052"></script>
<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/app.precompiled.js?v=202608060500" defer></script> <script src="/static/js/app.precompiled.js?v=202608060700" 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 {
+31
View File
@@ -1964,3 +1964,34 @@
(2) `handleSaveLocalProject`: đã login → **đồng bộ lên Cloud (fire-and-forget saveCloudProject)** — project mở được từ máy khác. (2) `handleSaveLocalProject`: đã login → **đồng bộ lên Cloud (fire-and-forget saveCloudProject)** — project mở được từ máy khác.
- **Các file ảnh hưởng:** `app/static/js/app.jsx`, `app/templates/index.html` (?v=202608060500), `wiki.md`. Rebuild precompiled. - **Các file ảnh hưởng:** `app/static/js/app.jsx`, `app/templates/index.html` (?v=202608060500), `wiki.md`. Rebuild precompiled.
- **Ghi chú/Test:** `npm run build` → hard refresh → login máy mới/ẩn danh → tự mở project Cloud gần nhất. Lưu local khi login → xuất hiện trong Cloud tab ở máy khác. Project local CŨ (tạo trước fix) → mở trên máy cũ + lưu lại → sync. - **Ghi chú/Test:** `npm run build` → hard refresh → login máy mới/ẩn danh → tự mở project Cloud gần nhất. Lưu local khi login → xuất hiện trong Cloud tab ở máy khác. Project local CŨ (tạo trước fix) → mở trên máy cũ + lưu lại → sync.
### [2026-08-06 05:30] Task: Incognito instrument câm — font KHÔNG còn trên server (chỉ trong IndexedDB browser thường)
- **Báo cáo user:** load project cũ ở browser ẩn danh → instrument không có âm; browser thường → OK.
- **Chẩn đoán:** soundfont (SGM-V2.01, latin hand perc) load từ IndexedDB cache → incognito cache RỖNG → fetch `/api/v1/plugins/soundfonts/download/{sfId}`**404 — font KHÔNG còn trên server** (upload dir chỉ còn weedsgm3/518e850f; static/soundfonts rỗng; SYSTEM_SF_DIR không tồn tại). Browser thường: IndexedDB đã cache (từ lúc font từng tồn tại server) → không fetch → OK.
- **FIX:**
(1) Backend `app/api/v1/plugins.py` download endpoint: thêm `static/soundfonts` vào danh sách thư mục tìm (font bundled).
(2) Frontend `soundfontPlayer.js` loadSoundFont: fetch API download fail → **fallback `/soundfonts/{sfId}`** (route tĩnh).
- **ĐIỀU KIỆN ĐỦ:** font PHẢI tồn tại trên server — user cần đặt file `SGM-V2.01.sf2/.sf3` + `latin hand perc.sf2/.sf3` vào `app/storage/soundfonts/` (hoặc upload qua UI) → mọi máy/browser fetch được.
- **Các file ảnh hưởng:** `app/api/v1/plugins.py`, `soundfontPlayer.js` (?v=202608060530 — hard refresh), `wiki.md`. Backend cần restart.
- **Ghi chú/Test:** đặt font vào storage/soundfonts → restart backend → hard refresh → incognito load project → instrument có âm.
### [2026-08-06 06:00] Task: Incognito log xác nhận font vẫn 404 + fix crash onMouseMove (guard clip.buffer)
- **Log incognito (v0530):** `soundfont not loaded yet, loading: SGM-V2.01` ×17 — load thất bại liên tục = font VẪN không có trên server (404). Kèm `Uncaught TypeError: Cannot read properties of undefined (reading 'duration')` onMouseMove — guard clip.buffer bị mất theo commit user 55d3464.
- **FIX (app.jsx):** re-apply guard `c.buffer` cho 5 chỗ `.buffer.duration` (rightEdgeClip ×2, hoveredClip, clickedClip ×2) — hết crash khi clip không có buffer (audio file load fail ở incognito).
- **ĐIỀU KIỆN CẦN (chưa đủ — user PHẢI thực hiện):** đặt file font (SF2 — export từ cache browser thường hoặc copy từ production /opt/daw_engine/soundfonts) vào `app/storage/soundfonts/` — dev instance KHÔNG có ffmpeg → KHÔNG dùng được .sf3 (cần .sf2). Fix code endpoint + fallback đã vào (v0530) — chỉ có tác dụng khi file tồn tại server-side.
- **Các file ảnh hưởng:** `app/static/js/app.jsx`, `app/templates/index.html` (?v=202608060600), `wiki.md`. Rebuild precompiled.
### [2026-08-06 06:30] Task: Note bị DROP khi font không tải được (incognito) → fallback oscillator + cooldown 10s
- **Xác nhận hypothesis user:** "incognito bỏ qua bước FluidSynth WASM" — đúng cơ chế: doNote `if (finalSfId && !_sfHandleMap.has(finalSfId))` → loadSoundFont → `if (ok) doNote();`**load FAIL (font 404) → note bị DROP âm thầm → WASM không nhận noteon → CÂM.** Incognito: cache rỗng → fetch 404; browser thường: cache có → ok.
- **FIX (soundfontPlayer.js doNote):**
(1) Load fail → **`_playNoteFallback` (oscillator — CÓ ÂM thay vì câm lặng)** + `_sfLoadFailAt[sfId]` timestamp.
(2) **Cooldown 10s**: sau fail, các note tiếp theo chạy thẳng fallback (không spam fetch 404 mỗi note).
- **Các file ảnh hưởng:** `soundfontPlayer.js` (?v=202608060630 — hard refresh, không build), `wiki.md`.
- **Ghi chú/Test:** hard refresh → incognito play track font chưa có → NGHE ĐƯỢC fallback (beep theo pattern — không câm). Vẫn khuyến nghị đặt font thật (SGM-V2.01.sf2...) để có âm thật.
### [2026-08-06 07:00] Task: Bundle mới KHÔNG load ở incognito — index.html cache heuristic (thiếu Cache-Control)
- **Báo cáo user:** re-compile + rebuild docker nhưng incognito vẫn không load bundle mới (URL cũ).
- **Xác minh production (daw.labz.io.vn):** index.html ĐÃ serve `soundfontPlayer?v=202608060630` + `precompiled?v=202608060600` — bundle MỚI NHẤT (precompiled chứa 9 markers fix: nanOut/effMidiBypass/prevActiveTabRef). **Production ĐÚNG** — vấn đề: **incognito dùng index.html CACHED CŨ** (stamp cũ → URL bundle cũ). Server không gửi Cache-Control → browser cache heuristic → HTML cũ.
- **FIX (app/main.py):** index.html (`/`) thêm `Cache-Control: no-cache, no-store, must-revalidate` — HTML luôn mới, bundle JS bust bằng ?v=.
- **Các file ảnh hưởng:** `app/main.py`. Cần rebuild docker + restart.
- **Ghi chú/Test:** sau khi deploy: incognito (đóng + mở lại tab — hoặc Ctrl+Shift+R 1 lần) → load trang → bundle mới. Verify: console thấy stamp mới.