From 6c16bf841071cc1cea829bb01909a659568393e0 Mon Sep 17 00:00:00 2001 From: 3dtours Date: Fri, 7 Aug 2026 10:37:34 +0700 Subject: [PATCH] =?UTF-8?q?FIX:=20s=E1=BB=ADa=20l=E1=BB=97i=20=C4=91?= =?UTF-8?q?=E1=BB=93ng=20b=E1=BB=99=20playhead=20v=E1=BB=8B=20tr=C3=AD=20p?= =?UTF-8?q?lay=20gi=E1=BB=AFa=20MAIN=20SESSION/SECTION-TAB/PIANO=20ROLL=20?= =?UTF-8?q?TAB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/static/js/app.jsx | 104 +++++++++++++++++++++++-------- app/static/js/app.precompiled.js | 34 +++++----- app/templates/index.html | 2 +- wiki.md | 16 +++++ 4 files changed, 116 insertions(+), 40 deletions(-) diff --git a/app/static/js/app.jsx b/app/static/js/app.jsx index 5d94710..d5b2355 100644 --- a/app/static/js/app.jsx +++ b/app/static/js/app.jsx @@ -14750,6 +14750,31 @@ const App = () => { const sessionTabsRef = useRef(sessionTabs); sessionTabsRef.current = sessionTabs; + // Vị trí MIDI item (trong context của piano roll) — dùng để đồng bộ playhead + // 2 chiều SECTION-TAB ↔ PIANO ROLL: item.startTime (local section / main) + + // st.currentTime (vị trí TRONG item). Dùng REFS (activeTracksRef/ + // sessionTabsRef) — an toàn với closure cũ (updatePlayhead/rAF loop). + const getPianoRollItemInfo = st => { + try { + if (!st) return null; + let list = null; + if (st.parent_tab_id && st.parent_tab_id.startsWith('session_')) { + const _pst = sessionTabsRef.current.find(s => s.id === st.parent_tab_id); + list = _pst ? _pst.tracks : null; + } else { + list = activeTracksRef.current; + } + if (!list) return null; + const _trk = list.find(t => t.id === st.trackId); + if (!_trk) return null; + const _item = (_trk.midiItems || []).find(m => m.id === st.target_id); + if (!_item) return null; + return { startTime: _item.startTime || 0, duration: _item.duration || 4 }; + } catch (e) { + return null; + } + }; + // Track mute/solo/volume signature: only re-apply gains when something that // affects audibility actually changed (loads, undo, AI ops, section tabs). const trackMuteSoloSigRef = useRef({}); @@ -14851,28 +14876,41 @@ const App = () => { // trước đó mở tab lúc main đang play (mainResumeRef đã set). const _resume = mainResumeRef.current; mainResumeRef.current = null; - if (_resume && prevSub.type === 'PIANO_ROLL' && (activeTab === 'main' || (activeTab && activeTab.startsWith('session_')))) { - try { - const _elapsed = getAudioContext().currentTime - _resume.audioTime; - const _resumeAt = _resume.offset + _elapsed; - console.log('[Resume] main play từ', _resumeAt.toFixed(2), 's (offset', _resume.offset.toFixed(2), '+ elapsed', _elapsed.toFixed(2), ')'); - stopAllPlayback(); - startOffsetTimeRef.current = _resumeAt; - startAudioTimeRef.current = getAudioContext().currentTime; - startTrackPlayback(_resumeAt); + if (prevSub.type === 'PIANO_ROLL' && (activeTab === 'main' || (activeTab && activeTab.startsWith('session_')))) { + // Resume section/main play tại vị trí TƯƠNG ỨNG với piano roll: + // resumeAt = item.startTime + st.currentTime (vị trí TRONG item — + // yêu cầu: play piano roll ở vị trí nào → về SECTION play đúng vị trí + // đó). Ưu tiên item info; fallback mainResumeRef (offset+elapsed); + // fallback cuối: setIsPlaying(true) — playhead chạy theo âm còn kêu. + let _resumeAt = null; + const _itemInfo = getPianoRollItemInfo(prevSub); + if (_itemInfo) { + _resumeAt = _itemInfo.startTime + (prevSub.currentTime || 0); + // Về MAIN mà item thuộc SECTION: vị trí main = secStart + local + if (activeTab === 'main' && prevSub.parent_tab_id && prevSub.parent_tab_id.startsWith('session_')) { + const _pst = sessionTabsRef.current.find(s => s.id === prevSub.parent_tab_id); + if (_pst && _pst.sectionId) { + (activeTracksRef.current || []).forEach(_t => (_t.sections || []).forEach(_s => { + if (_s.sectionId === _pst.sectionId || _s.id === _pst.sectionId) _resumeAt += (_s.start || 0); + })); + } + } + } else if (_resume) { + _resumeAt = _resume.offset + (getAudioContext().currentTime - _resume.audioTime); + } + if (_resumeAt !== null) { + try { + console.log('[Resume] play tại', _resumeAt.toFixed(2), 's (item.startTime=' + (_itemInfo ? _itemInfo.startTime.toFixed(2) : '?') + ' + st.currentTime=' + (prevSub.currentTime || 0).toFixed(2) + ')'); + stopAllPlayback(); + startOffsetTimeRef.current = _resumeAt; + startAudioTimeRef.current = getAudioContext().currentTime; + startTrackPlayback(_resumeAt); + setIsPlaying(true); + } catch (e) { console.warn('[Resume] error:', e); } + } else { + console.log('[Playhead] tiếp tục theo piano roll (không stop âm) — activeTab=' + activeTab); setIsPlaying(true); - } catch (e) { console.warn('[Resume] error:', e); } - } else if (prevSub.type === 'PIANO_ROLL' && (activeTab === 'main' || (activeTab && activeTab.startsWith('session_')))) { - // Play THUẦN piano roll (main chưa từng play — mainResumeRef null): - // rời tab → KHÔNG stop âm (0415) — NHƯNG isPlaying=false → nhánh - // main updatePlayhead `if (!isPlaying) return` → playhead NGỪNG dù - // âm piano roll còn kêu (user: playhead không đồng bộ/ngừng khi - // chuyển tab). → setIsPlaying(true): playhead main/section chạy theo - // elapsed (startOffsetTimeRef/startAudioTimeRef đang là của piano - // roll play — đồng bộ với âm đang phát). Hết bài (projectEnd) → - // nhánh main tự stop. - console.log('[Playhead] tiếp tục theo piano roll (không stop âm) — activeTab=' + activeTab); - setIsPlaying(true); + } } } else if (prevSub && prevSub.type === 'PIANO_ROLL') { // Rời PIANO ROLL tab KHÔNG play: main/section play ngầm vẫn chạy (âm @@ -18495,13 +18533,29 @@ const App = () => { if (!st || !st.buffer) return; if (!st.isPlaying) { // PIANO ROLL / sub-tab KHÔNG play: playhead theo MAIN/SECTION nếu đang - // play (đồng bộ vị trí âm THẬT — user: di chuyển tab qua lại → quay - // lại piano roll tab → playhead phải chạy theo âm đang phát); không - // có play nào → đứng yên (chế độ edit). Loop luôn tiếp tục (rAF). + // play — ĐỒNG BỘ 2 CHIỀU: vị trí play (section/main) → vị trí TRONG + // item (st.currentTime = playPos - item.startTime); playhead vượt ra + // ngoài duration item → bắt đầu từ đầu (0). Không có play nào → đứng + // yên (chế độ edit). Loop luôn tiếp tục (rAF). if (isPlaying) { const context = getAudioContext(); const _ph = startOffsetTimeRef.current + (context.currentTime - startAudioTimeRef.current); - setSubTabs(prev => prev.map(s => s.id === st.id ? { ...s, currentTime: _ph } : s)); + let _local = _ph; + const _itemInfo = getPianoRollItemInfo(st); + if (_itemInfo) { + if (_ph < _itemInfo.startTime) _local = 0; + else if (_ph >= _itemInfo.startTime + _itemInfo.duration) _local = 0; // vượt duration item → đầu + else _local = _ph - _itemInfo.startTime; + } + // Log chẩn đoán (rate-limited ~2 lần/giây): xác nhận đồng bộ MAIN/ + // SECTION ↔ PIANO ROLL — ph (vị trí play) → local (trong item). + try { + const _sf = (window.__syncFrame = (window.__syncFrame || 0) + 1); + if (_sf % 45 === 0) { + console.log('[Sync] PR', st.id, 'ph=', _ph.toFixed(2), 'item.start=', _itemInfo ? _itemInfo.startTime.toFixed(2) : '-', 'dur=', _itemInfo ? _itemInfo.duration.toFixed(2) : '-', '→ local=', _local.toFixed(2), 'tab=', activeTabRef.current); + } + } catch (e) { } + setSubTabs(prev => prev.map(s => s.id === st.id ? { ...s, currentTime: _local } : s)); } animationFrameIdRef.current = requestAnimationFrame(updatePlayhead); return; diff --git a/app/static/js/app.precompiled.js b/app/static/js/app.precompiled.js index ac712dd..68c04b5 100644 --- a/app/static/js/app.precompiled.js +++ b/app/static/js/app.precompiled.js @@ -670,7 +670,11 @@ const[activeTab,setActiveTab]=useState('main');const[subTabSelectedNodeTime,setS const[pianoRollClipboard,setPianoRollClipboard]=useState(null);// notes copy giữa các PIANO ROLL TAB const[sessionTabs,setSessionTabs]=useState([]);// [{id, name, tracks}, ...] const[tabContextMenu,setTabContextMenu]=useState(null);// { x, y, tabId, tabType } -const handleSetTabColor=(tabId,tabType,color)=>{if(tabType==='session'){setSessionTabs(prev=>prev.map(s=>s.id===tabId?{...s,color:color}:s));const tab=sessionTabs.find(s=>s.id===tabId);if(tab){setTracks(prev=>prev.map(t=>{if(!t.sections||t.sections.length===0)return t;return{...t,sections:t.sections.map(s=>{if(s.sectionId===tab.sectionId){return{...s,color:color};}return s;})};}));}}else{setSubTabs(prev=>prev.map(s=>s.id===tabId?{...s,color:color}:s));}};const activeTracks=useMemo(()=>{var st=sessionTabs.find(s=>s.id===activeTab);if(st)return st.tracks;var pr=subTabs.find(s=>s.id===activeTab&&s.type==='PIANO_ROLL');if(pr&&pr.parent_tab_id&&pr.parent_tab_id.startsWith('session_')){var parentSt=sessionTabs.find(s=>s.id===pr.parent_tab_id);if(parentSt)return parentSt.tracks;}return tracks;},[activeTab,sessionTabs,subTabs,tracks]);const activeTracksRef=useRef([]);activeTracksRef.current=activeTracks;const sessionTabsRef=useRef(sessionTabs);sessionTabsRef.current=sessionTabs;// Track mute/solo/volume signature: only re-apply gains when something that +const handleSetTabColor=(tabId,tabType,color)=>{if(tabType==='session'){setSessionTabs(prev=>prev.map(s=>s.id===tabId?{...s,color:color}:s));const tab=sessionTabs.find(s=>s.id===tabId);if(tab){setTracks(prev=>prev.map(t=>{if(!t.sections||t.sections.length===0)return t;return{...t,sections:t.sections.map(s=>{if(s.sectionId===tab.sectionId){return{...s,color:color};}return s;})};}));}}else{setSubTabs(prev=>prev.map(s=>s.id===tabId?{...s,color:color}:s));}};const activeTracks=useMemo(()=>{var st=sessionTabs.find(s=>s.id===activeTab);if(st)return st.tracks;var pr=subTabs.find(s=>s.id===activeTab&&s.type==='PIANO_ROLL');if(pr&&pr.parent_tab_id&&pr.parent_tab_id.startsWith('session_')){var parentSt=sessionTabs.find(s=>s.id===pr.parent_tab_id);if(parentSt)return parentSt.tracks;}return tracks;},[activeTab,sessionTabs,subTabs,tracks]);const activeTracksRef=useRef([]);activeTracksRef.current=activeTracks;const sessionTabsRef=useRef(sessionTabs);sessionTabsRef.current=sessionTabs;// Vị trí MIDI item (trong context của piano roll) — dùng để đồng bộ playhead +// 2 chiều SECTION-TAB ↔ PIANO ROLL: item.startTime (local section / main) + +// st.currentTime (vị trí TRONG item). Dùng REFS (activeTracksRef/ +// sessionTabsRef) — an toàn với closure cũ (updatePlayhead/rAF loop). +const getPianoRollItemInfo=st=>{try{if(!st)return null;let list=null;if(st.parent_tab_id&&st.parent_tab_id.startsWith('session_')){const _pst=sessionTabsRef.current.find(s=>s.id===st.parent_tab_id);list=_pst?_pst.tracks:null;}else{list=activeTracksRef.current;}if(!list)return null;const _trk=list.find(t=>t.id===st.trackId);if(!_trk)return null;const _item=(_trk.midiItems||[]).find(m=>m.id===st.target_id);if(!_item)return null;return{startTime:_item.startTime||0,duration:_item.duration||4};}catch(e){return null;}};// Track mute/solo/volume signature: only re-apply gains when something that // affects audibility actually changed (loads, undo, AI ops, section tabs). const trackMuteSoloSigRef=useRef({});// Last-known audibility per track id (used to detect inaudible→audible // transitions that need a playback re-schedule). @@ -701,15 +705,13 @@ if(prevSub.type!=='PIANO_ROLL'){try{stopAllPlayback();}catch(e){}}setSubTabs(pre // play piano roll → stopAllPlayback dừng main → quay lại MAIN/SECTION // bị CÂM. Resume startTrackPlayback(offset + elapsed thật) — chỉ khi // trước đó mở tab lúc main đang play (mainResumeRef đã set). -const _resume=mainResumeRef.current;mainResumeRef.current=null;if(_resume&&prevSub.type==='PIANO_ROLL'&&(activeTab==='main'||activeTab&&activeTab.startsWith('session_'))){try{const _elapsed=getAudioContext().currentTime-_resume.audioTime;const _resumeAt=_resume.offset+_elapsed;console.log('[Resume] main play từ',_resumeAt.toFixed(2),'s (offset',_resume.offset.toFixed(2),'+ elapsed',_elapsed.toFixed(2),')');stopAllPlayback();startOffsetTimeRef.current=_resumeAt;startAudioTimeRef.current=getAudioContext().currentTime;startTrackPlayback(_resumeAt);setIsPlaying(true);}catch(e){console.warn('[Resume] error:',e);}}else if(prevSub.type==='PIANO_ROLL'&&(activeTab==='main'||activeTab&&activeTab.startsWith('session_'))){// Play THUẦN piano roll (main chưa từng play — mainResumeRef null): -// rời tab → KHÔNG stop âm (0415) — NHƯNG isPlaying=false → nhánh -// main updatePlayhead `if (!isPlaying) return` → playhead NGỪNG dù -// âm piano roll còn kêu (user: playhead không đồng bộ/ngừng khi -// chuyển tab). → setIsPlaying(true): playhead main/section chạy theo -// elapsed (startOffsetTimeRef/startAudioTimeRef đang là của piano -// roll play — đồng bộ với âm đang phát). Hết bài (projectEnd) → -// nhánh main tự stop. -console.log('[Playhead] tiếp tục theo piano roll (không stop âm) — activeTab='+activeTab);setIsPlaying(true);}}else if(prevSub&&prevSub.type==='PIANO_ROLL'){// Rời PIANO ROLL tab KHÔNG play: main/section play ngầm vẫn chạy (âm +const _resume=mainResumeRef.current;mainResumeRef.current=null;if(prevSub.type==='PIANO_ROLL'&&(activeTab==='main'||activeTab&&activeTab.startsWith('session_'))){// Resume section/main play tại vị trí TƯƠNG ỨNG với piano roll: +// resumeAt = item.startTime + st.currentTime (vị trí TRONG item — +// yêu cầu: play piano roll ở vị trí nào → về SECTION play đúng vị trí +// đó). Ưu tiên item info; fallback mainResumeRef (offset+elapsed); +// fallback cuối: setIsPlaying(true) — playhead chạy theo âm còn kêu. +let _resumeAt=null;const _itemInfo=getPianoRollItemInfo(prevSub);if(_itemInfo){_resumeAt=_itemInfo.startTime+(prevSub.currentTime||0);// Về MAIN mà item thuộc SECTION: vị trí main = secStart + local +if(activeTab==='main'&&prevSub.parent_tab_id&&prevSub.parent_tab_id.startsWith('session_')){const _pst=sessionTabsRef.current.find(s=>s.id===prevSub.parent_tab_id);if(_pst&&_pst.sectionId){(activeTracksRef.current||[]).forEach(_t=>(_t.sections||[]).forEach(_s=>{if(_s.sectionId===_pst.sectionId||_s.id===_pst.sectionId)_resumeAt+=_s.start||0;}));}}}else if(_resume){_resumeAt=_resume.offset+(getAudioContext().currentTime-_resume.audioTime);}if(_resumeAt!==null){try{console.log('[Resume] play tại',_resumeAt.toFixed(2),'s (item.startTime='+(_itemInfo?_itemInfo.startTime.toFixed(2):'?')+' + st.currentTime='+(prevSub.currentTime||0).toFixed(2)+')');stopAllPlayback();startOffsetTimeRef.current=_resumeAt;startAudioTimeRef.current=getAudioContext().currentTime;startTrackPlayback(_resumeAt);setIsPlaying(true);}catch(e){console.warn('[Resume] error:',e);}}else{console.log('[Playhead] tiếp tục theo piano roll (không stop âm) — activeTab='+activeTab);setIsPlaying(true);}}}else if(prevSub&&prevSub.type==='PIANO_ROLL'){// Rời PIANO ROLL tab KHÔNG play: main/section play ngầm vẫn chạy (âm // tiếp tục tự nhiên — không cần resume) → clear resume point. // ⚠️ KHÔNG clear khi prevTab = main/session (đang DI CHUYỂN VÀO piano // roll — mainResumeRef vừa set bởi handleEditMidiInTab — clear nhầm ở @@ -933,10 +935,14 @@ while(true){const beatNum=nextMetronomeBeatRef.current;const elapsedBeats=beatNu const now=Date.now();if(now-lastTempCompileTimeRef.current>200){lastTempCompileTimeRef.current=now;// Audio preview for(let trackId in recordingPCMDataRef.current){const data=recordingPCMDataRef.current[trackId];if(data&&data.length>0){const tempBuf=audioCtx.createBuffer(1,data.length,audioCtx.sampleRate);tempBuf.getChannelData(0).set(data);setRecTempAudioBuffer(tempBuf);}}// MIDI preview let combinedNotes=[];const armedTracks=activeTracksRef.current.filter(t=>t.isArmed);for(let track of armedTracks){const midiRec=activeMIDIRecordersRef.current[track.id];if(midiRec){const currentBeat=(audioCtx.currentTime-midiRec.recStartAudioTime-midiRec.latencyCompSec)/secondsPerBeat;const notes=[...midiRec.recordedNotes,...Array.from(midiRec.activeNotes.values()).map(n=>({...n,duration_beats:currentBeat-n.start_beat}))];combinedNotes=combinedNotes.concat(notes);}}if(combinedNotes.length>0||armedTracks.some(t=>activeMIDIRecordersRef.current[t.id])){setRecTempMidiNotes(combinedNotes);setCanvasRedrawCount(n=>n+1);}}}const isSubTab=subTabsRef.current.some(sub=>sub.id===activeTabRef.current);if(isSubTab){const st=subTabsRef.current.find(s=>s.id===activeTabRef.current);if(!st||!st.buffer)return;if(!st.isPlaying){// PIANO ROLL / sub-tab KHÔNG play: playhead theo MAIN/SECTION nếu đang -// play (đồng bộ vị trí âm THẬT — user: di chuyển tab qua lại → quay -// lại piano roll tab → playhead phải chạy theo âm đang phát); không -// có play nào → đứng yên (chế độ edit). Loop luôn tiếp tục (rAF). -if(isPlaying){const context=getAudioContext();const _ph=startOffsetTimeRef.current+(context.currentTime-startAudioTimeRef.current);setSubTabs(prev=>prev.map(s=>s.id===st.id?{...s,currentTime:_ph}:s));}animationFrameIdRef.current=requestAnimationFrame(updatePlayhead);return;}const context=getAudioContext();const speedFactor=st.speed||1.0;const elapsed=context.currentTime-startAudioTimeRef.current;const wallTime=startOffsetTimeRef.current+elapsed;const bufferPos=startBufferOffsetRef.current+elapsed*speedFactor;// Loop sub-tab selection (bufferPos is buffer-time) +// play — ĐỒNG BỘ 2 CHIỀU: vị trí play (section/main) → vị trí TRONG +// item (st.currentTime = playPos - item.startTime); playhead vượt ra +// ngoài duration item → bắt đầu từ đầu (0). Không có play nào → đứng +// yên (chế độ edit). Loop luôn tiếp tục (rAF). +if(isPlaying){const context=getAudioContext();const _ph=startOffsetTimeRef.current+(context.currentTime-startAudioTimeRef.current);let _local=_ph;const _itemInfo=getPianoRollItemInfo(st);if(_itemInfo){if(_ph<_itemInfo.startTime)_local=0;else if(_ph>=_itemInfo.startTime+_itemInfo.duration)_local=0;// vượt duration item → đầu +else _local=_ph-_itemInfo.startTime;}// Log chẩn đoán (rate-limited ~2 lần/giây): xác nhận đồng bộ MAIN/ +// SECTION ↔ PIANO ROLL — ph (vị trí play) → local (trong item). +try{const _sf=window.__syncFrame=(window.__syncFrame||0)+1;if(_sf%45===0){console.log('[Sync] PR',st.id,'ph=',_ph.toFixed(2),'item.start=',_itemInfo?_itemInfo.startTime.toFixed(2):'-','dur=',_itemInfo?_itemInfo.duration.toFixed(2):'-','→ local=',_local.toFixed(2),'tab=',activeTabRef.current);}}catch(e){}setSubTabs(prev=>prev.map(s=>s.id===st.id?{...s,currentTime:_local}:s));}animationFrameIdRef.current=requestAnimationFrame(updatePlayhead);return;}const context=getAudioContext();const speedFactor=st.speed||1.0;const elapsed=context.currentTime-startAudioTimeRef.current;const wallTime=startOffsetTimeRef.current+elapsed;const bufferPos=startBufferOffsetRef.current+elapsed*speedFactor;// Loop sub-tab selection (bufferPos is buffer-time) if(st.selectionStart!==null&&st.selectionEnd!==null&&st.selectionStart!==st.selectionEnd&&st.isLooping){const start=Math.min(st.selectionStart,st.selectionEnd);const end=Math.max(st.selectionStart,st.selectionEnd);if(bufferPos>=end){stopAllPlayback();setSubTabs(prev=>prev.map(s=>s.id===activeTabRef.current?{...s,buffer:s.buffer||getAudioContext().createBuffer(1,128,getAudioContext().sampleRate),currentTime:start,isPlaying:true}:s));schedulePianoRollMidi(st,start);startSubTabPlayback(st,start);animationFrameIdRef.current=requestAnimationFrame(updatePlayhead);return;}}const effectiveDuration=st.type==='PIANO_ROLL'?(()=>{const notes=st.notes||[];const bpmVal=parseInt(bpmRef?.current||bpm)||120;const beatSec=60.0/bpmVal;if(recordingStateRef.current==='RECORDING')return 600.0;// 10 min during recording let maxEnd=0;notes.forEach(n=>{const end=(n.start_beat||0)+(n.duration_beats||1);if(end>maxEnd)maxEnd=end;});return Math.max(maxEnd*beatSec,16*beatSec*4)+1.0;})():st.buffer.duration;if(bufferPos>=effectiveDuration){stopAllPlayback();if(st.isLooping){setSubTabs(prev=>prev.map(s=>s.id===activeTabRef.current?{...s,buffer:s.buffer||getAudioContext().createBuffer(1,128,getAudioContext().sampleRate),currentTime:0,isPlaying:true}:s));// Loop lại: phải schedule notes MỚI (âm piano roll mất ở lần loop 2 // nếu chỉ chạy silent buffer). diff --git a/app/templates/index.html b/app/templates/index.html index bf8caa4..9a1cc99 100644 --- a/app/templates/index.html +++ b/app/templates/index.html @@ -24,7 +24,7 @@ - +