1589 lines
85 KiB
HTML
1589 lines
85 KiB
HTML
<!DOCTYPE html>
|
|
<html lang="vi">
|
|
<head>
|
|
<meta charset="UTF-8">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
<title>SonicForge Studio - Professional DAW Editor</title>
|
|
<!-- Tailwind CSS for styling -->
|
|
<script src="https://cdn.tailwindcss.com"></script>
|
|
<!-- Lucide Icons -->
|
|
<script src="https://unpkg.com/lucide@latest"></script>
|
|
<!-- React & ReactDOM -->
|
|
<script src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
|
|
<script src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
|
|
<!-- Babel for browser compilation -->
|
|
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
|
|
<style>
|
|
body {
|
|
background-color: #1a1a1a;
|
|
color: #c0c0c0;
|
|
font-family: 'Inter', system-ui, -apple-system, sans-serif;
|
|
overflow: hidden;
|
|
user-select: none;
|
|
}
|
|
/* Style inspired by dark charcoal theme */
|
|
.daw-bg { background-color: #1e1e1e; }
|
|
.daw-panel { background-color: #262626; }
|
|
.daw-header { background-color: #2e2e2e; }
|
|
.daw-border { border-color: #181818; }
|
|
.daw-track-active { background-color: #333333; }
|
|
|
|
/* Custom Scrollbars to match professional DAW */
|
|
::-webkit-scrollbar {
|
|
width: 10px;
|
|
height: 10px;
|
|
}
|
|
::-webkit-scrollbar-track {
|
|
background: #141414;
|
|
}
|
|
::-webkit-scrollbar-thumb {
|
|
background: #3a3a3a;
|
|
border: 2px solid #141414;
|
|
border-radius: 4px;
|
|
}
|
|
::-webkit-scrollbar-thumb:hover {
|
|
background: #4a4a4a;
|
|
}
|
|
|
|
/* Interactive Knobs styling */
|
|
.knob-container {
|
|
position: relative;
|
|
width: 28px;
|
|
height: 28px;
|
|
}
|
|
.knob-dial {
|
|
transform-origin: center;
|
|
transition: transform 0.1s ease;
|
|
}
|
|
</style>
|
|
</head>
|
|
<body class="h-screen w-screen flex flex-col">
|
|
<div id="root" class="h-full w-full flex flex-col"></div>
|
|
|
|
<script type="text/babel">
|
|
const { useState, useRef, useEffect, useMemo } = React;
|
|
|
|
let audioCtx;
|
|
function getAudioContext() {
|
|
if (!audioCtx) {
|
|
audioCtx = new (window.AudioContext || window.webkitAudioContext)();
|
|
}
|
|
if (audioCtx.state === 'suspended') {
|
|
audioCtx.resume();
|
|
}
|
|
return audioCtx;
|
|
}
|
|
|
|
const formatTime = (secs) => {
|
|
if (isNaN(secs) || secs < 0) return "0:00.000";
|
|
const m = Math.floor(secs / 60);
|
|
const s = Math.floor(secs % 60);
|
|
const ms = Math.floor((secs % 1) * 1000).toString().padStart(3, '0');
|
|
return `${m}:${s.toString().padStart(2, '0')}.${ms}`;
|
|
};
|
|
|
|
/**
|
|
* Find Zero Crossing to prevent pop/clicks on cut.
|
|
* [PYTHON PORTING NOTICE]: Ensure you mirror this boundary validation logic exactly.
|
|
* In Python (with numpy):
|
|
* def find_zero_crossing(y, sample_rate, target_time):
|
|
* target_sample = int(target_time * sample_rate)
|
|
* window = int(0.04 * sample_rate)
|
|
* start = max(0, target_sample - window)
|
|
* end = min(len(y) - 2, target_sample + window)
|
|
* # Find best index i in range where y[i] * y[i+1] <= 0
|
|
*/
|
|
const findZeroCrossing = (buffer, targetTime) => {
|
|
if (!buffer) return targetTime;
|
|
const sampleRate = buffer.sampleRate;
|
|
const data = buffer.getChannelData(0);
|
|
const targetSample = Math.floor(targetTime * sampleRate);
|
|
const windowSize = Math.floor(0.04 * sampleRate); // 40ms window
|
|
const start = Math.max(0, targetSample - windowSize);
|
|
const end = Math.min(data.length - 2, targetSample + windowSize);
|
|
|
|
let bestSample = targetSample;
|
|
let minDistance = Infinity;
|
|
|
|
for (let i = start; i <= end; i++) {
|
|
if ((data[i] >= 0 && data[i+1] <= 0) || (data[i] <= 0 && data[i+1] >= 0)) {
|
|
const dist = Math.abs(i - targetSample);
|
|
if (dist < minDistance) {
|
|
minDistance = dist;
|
|
bestSample = i;
|
|
}
|
|
}
|
|
}
|
|
return bestSample / sampleRate;
|
|
};
|
|
|
|
const VolumeKnob = ({ value, onChange, min = 0, max = 1 }) => {
|
|
const [isDragging, setIsDragging] = useState(false);
|
|
const startY = useRef(0);
|
|
const startValue = useRef(0);
|
|
|
|
const rotation = useMemo(() => {
|
|
const percent = (value - min) / (max - min);
|
|
return -135 + percent * 270;
|
|
}, [value, min, max]);
|
|
|
|
const handleMouseDown = (e) => {
|
|
setIsDragging(true);
|
|
startY.current = e.clientY;
|
|
startValue.current = value;
|
|
document.addEventListener('mousemove', handleMouseMove);
|
|
document.addEventListener('mouseup', handleMouseUp);
|
|
};
|
|
|
|
const handleMouseMove = (e) => {
|
|
const deltaY = startY.current - e.clientY;
|
|
const sensitivity = 0.005;
|
|
const newValue = Math.max(min, Math.min(max, startValue.current + deltaY * sensitivity));
|
|
onChange(parseFloat(newValue.toFixed(2)));
|
|
};
|
|
|
|
const handleMouseUp = () => {
|
|
setIsDragging(false);
|
|
document.removeEventListener('mousemove', handleMouseMove);
|
|
document.removeEventListener('mouseup', handleMouseUp);
|
|
};
|
|
|
|
return (
|
|
<div
|
|
className="knob-container cursor-ns-resize flex flex-col items-center"
|
|
onMouseDown={handleMouseDown}
|
|
title={`Volume: ${Math.round(value * 100)}%`}
|
|
>
|
|
<svg className="w-7 h-7" viewBox="0 0 40 40">
|
|
<circle cx="20" cy="20" r="16" fill="#141414" stroke="#444" strokeWidth="2" />
|
|
<g transform={`rotate(${rotation} 20 20)`} className="knob-dial">
|
|
<line x1="20" y1="20" x2="20" y2="6" stroke="#ef4444" strokeWidth="3" strokeLinecap="round" />
|
|
</g>
|
|
</svg>
|
|
</div>
|
|
);
|
|
};
|
|
|
|
const WaveformLane = ({
|
|
track,
|
|
zoom,
|
|
timelineWidth,
|
|
onSelectRange,
|
|
onPlayheadSet,
|
|
isSelected,
|
|
onSelectTrack,
|
|
markers
|
|
}) => {
|
|
const canvasRef = useRef(null);
|
|
|
|
useEffect(() => {
|
|
const canvas = canvasRef.current;
|
|
if (!canvas) return;
|
|
const ctx = canvas.getContext('2d');
|
|
const dpr = window.devicePixelRatio || 1;
|
|
const width = timelineWidth;
|
|
const height = canvas.parentElement.clientHeight;
|
|
|
|
canvas.width = width * dpr;
|
|
canvas.height = height * dpr;
|
|
ctx.scale(dpr, dpr);
|
|
|
|
// Background track colors based on selection
|
|
ctx.fillStyle = isSelected ? '#2a2a2a' : (track.id % 2 === 0 ? '#181818' : '#1d1d1d');
|
|
ctx.fillRect(0, 0, width, height);
|
|
|
|
// Grid lines (each 1s or 0.5s based on zoom)
|
|
ctx.strokeStyle = 'rgba(255, 255, 255, 0.02)';
|
|
ctx.lineWidth = 1;
|
|
const stepSeconds = zoom > 120 ? 0.5 : 1;
|
|
const totalSec = width / zoom;
|
|
|
|
for (let s = 0; s <= totalSec; s += stepSeconds) {
|
|
const x = s * zoom;
|
|
ctx.beginPath();
|
|
ctx.moveTo(x, 0);
|
|
ctx.lineTo(x, height);
|
|
ctx.stroke();
|
|
}
|
|
|
|
// Render Full Waveform based on decoded buffer
|
|
if (track.buffer) {
|
|
const buffer = track.buffer;
|
|
const data = buffer.getChannelData(0);
|
|
const sampleRate = buffer.sampleRate;
|
|
const duration = buffer.duration;
|
|
|
|
ctx.fillStyle = track.color || '#4f4f4f';
|
|
const midY = height / 2;
|
|
|
|
// Waveform peak reduction algorithm
|
|
for (let x = 0; x < width; x++) {
|
|
const timeAtPixel = x / zoom;
|
|
if (timeAtPixel > duration) break;
|
|
|
|
const sampleIndex = Math.floor(timeAtPixel * sampleRate);
|
|
const samplesPerPixel = Math.max(1, Math.floor(sampleRate / zoom));
|
|
|
|
let min = 1.0;
|
|
let max = -1.0;
|
|
for (let i = 0; i < samplesPerPixel; i++) {
|
|
const idx = sampleIndex + i;
|
|
if (idx >= data.length) break;
|
|
const val = data[idx];
|
|
if (val < min) min = val;
|
|
if (val > max) max = val;
|
|
}
|
|
|
|
if (min === 1.0) { min = 0; max = 0; }
|
|
|
|
const yTop = midY + (min * (height * 0.42));
|
|
const yBottom = midY + (max * (height * 0.42));
|
|
|
|
ctx.fillRect(x, yTop, 1, Math.max(1, yBottom - yTop));
|
|
}
|
|
} else {
|
|
// Placeholder text
|
|
ctx.fillStyle = 'rgba(255, 255, 255, 0.1)';
|
|
ctx.font = '10px monospace';
|
|
ctx.fillText('KÉO THẢ HOẶC CLICK TẢI NHẠC Ở TCP BÊN TRÁI', 15, height / 2 + 3);
|
|
}
|
|
|
|
markers.forEach(marker => {
|
|
const x = marker.time * zoom;
|
|
ctx.strokeStyle = '#c084fc';
|
|
ctx.lineWidth = 1.5;
|
|
ctx.beginPath();
|
|
ctx.moveTo(x, 0);
|
|
ctx.lineTo(x, height);
|
|
ctx.stroke();
|
|
});
|
|
|
|
}, [track.buffer, zoom, timelineWidth, markers, track.color, isSelected]);
|
|
|
|
const handleMouseDown = (e) => {
|
|
onSelectTrack(track.id);
|
|
|
|
// If clicking directly on selection overlay / handles, skip drag select
|
|
if (e.target.closest('.selection-interactive-box')) return;
|
|
|
|
const rect = canvasRef.current.getBoundingClientRect();
|
|
const startX = e.clientX - rect.left;
|
|
const startTime = startX / zoom;
|
|
|
|
onSelectRange(startTime, startTime, true); // start selection
|
|
onPlayheadSet(startTime);
|
|
|
|
const handleMouseMove = (moveEvent) => {
|
|
const currentX = moveEvent.clientX - rect.left;
|
|
const currentTime = Math.max(0, currentX / zoom);
|
|
onSelectRange(startTime, currentTime, false);
|
|
};
|
|
|
|
const handleMouseUp = () => {
|
|
document.removeEventListener('mousemove', handleMouseMove);
|
|
document.removeEventListener('mouseup', handleMouseUp);
|
|
};
|
|
|
|
document.addEventListener('mousemove', handleMouseMove);
|
|
document.addEventListener('mouseup', handleMouseUp);
|
|
};
|
|
|
|
return (
|
|
<div className={`relative w-full h-[96px] border-b border-[#141414] cursor-text ${isSelected ? 'ring-1 ring-cyan-500/20' : ''}`}>
|
|
<canvas
|
|
ref={canvasRef}
|
|
onMouseDown={handleMouseDown}
|
|
className="absolute inset-y-0 left-0 h-full block"
|
|
/>
|
|
</div>
|
|
);
|
|
};
|
|
|
|
const App = () => {
|
|
const [tracks, setTracks] = useState([]);
|
|
const [isPlaying, setIsPlaying] = useState(false);
|
|
const [selectedTrackId, setSelectedTrackId] = useState('1');
|
|
const [soloedTrackId, setSoloedTrackId] = useState(null);
|
|
const [currentTime, setCurrentTime] = useState(0);
|
|
|
|
// Unified width tracking for optimal zoom fitting
|
|
const [containerWidth, setContainerWidth] = useState(800);
|
|
const [zoom, setZoom] = useState(100); // pixels per second
|
|
|
|
// Global selection states (Seconds)
|
|
const [selectionStart, setSelectionStart] = useState(null);
|
|
const [selectionEnd, setSelectionEnd] = useState(null);
|
|
const [isLoopingSelection, setIsLoopingSelection] = useState(false);
|
|
|
|
// Toast Alert state
|
|
const [toastMessage, setToastMessage] = useState(null);
|
|
|
|
// Export configuration
|
|
const [exportSettings, setExportSettings] = useState({ sampleRate: '44100', bitDepth: '16', format: 'wav' });
|
|
const [isExporting, setIsExporting] = useState(false);
|
|
|
|
// AI OpenAI-compatible variables
|
|
const [aiConfig, setAiConfig] = useState({
|
|
baseUrl: 'https://api.openai.com/v1',
|
|
apiKey: '',
|
|
model: 'gpt-4o-mini',
|
|
showSettings: false
|
|
});
|
|
const [analysisState, setAnalysisState] = useState({ status: 'Idle', data: null, isRunning: false });
|
|
|
|
// Refs
|
|
const activeSourcesRef = useRef([]);
|
|
const startAudioTimeRef = useRef(0);
|
|
const startOffsetTimeRef = useRef(0);
|
|
const animationFrameId = useRef(null);
|
|
const timelineWrapperRef = useRef(null);
|
|
|
|
const showToast = (msg, type = 'info') => {
|
|
setToastMessage({ text: msg, type });
|
|
setTimeout(() => setToastMessage(null), 4000);
|
|
};
|
|
|
|
useEffect(() => {
|
|
setTracks([
|
|
{ id: '1', name: 'Armour_Stomp.wav', buffer: null, volume: 0.8, muted: false, solo: false, color: '#3f6212', markers: [] },
|
|
{ id: '2', name: 'Scrape_Metal03.wav', buffer: null, volume: 0.7, muted: false, solo: false, color: '#9a3412', markers: [] },
|
|
{ id: '3', name: 'Metal_Impact.wav', buffer: null, volume: 0.6, muted: false, solo: false, color: '#1e3a8a', markers: [] }
|
|
]);
|
|
setTimeout(() => lucide.createIcons(), 300);
|
|
}, []);
|
|
|
|
// Dynamic calculation of max timeline length (defaults to 30s)
|
|
const maxDuration = useMemo(() => {
|
|
const durations = tracks.map(t => t.buffer ? t.buffer.duration : 30);
|
|
return Math.max(...durations, 30);
|
|
}, [tracks]);
|
|
|
|
// Track wrapper width changes dynamically to compute accurate minZoom limit
|
|
useEffect(() => {
|
|
const timeline = timelineWrapperRef.current;
|
|
if (!timeline) return;
|
|
|
|
const observer = new ResizeObserver((entries) => {
|
|
for (let entry of entries) {
|
|
setContainerWidth(entry.contentRect.width);
|
|
}
|
|
});
|
|
observer.observe(timeline);
|
|
return () => observer.disconnect();
|
|
}, []);
|
|
|
|
// Compute the absolute minimum zoom to ensure waveform fits exactly in the viewport width when zoom out is complete
|
|
const minZoom = useMemo(() => {
|
|
return containerWidth / maxDuration;
|
|
}, [containerWidth, maxDuration]);
|
|
|
|
// Clamp current zoom when limits change
|
|
useEffect(() => {
|
|
setZoom(prev => Math.max(minZoom, Math.min(2000, prev)));
|
|
}, [minZoom]);
|
|
|
|
const timelineWidth = useMemo(() => {
|
|
return maxDuration * zoom;
|
|
}, [maxDuration, zoom]);
|
|
|
|
// High-precision Zoom Handler that anchors exactly at the current mouse pointer's timeline coordinates
|
|
useEffect(() => {
|
|
const timeline = timelineWrapperRef.current;
|
|
if (!timeline) return;
|
|
|
|
const handleWheel = (e) => {
|
|
if (e.ctrlKey) {
|
|
e.preventDefault();
|
|
// Playhead scrubbing (Ctrl + Mouse wheel)
|
|
const direction = e.deltaY > 0 ? 1 : -1;
|
|
const timeShift = (15 / zoom) * direction;
|
|
setCurrentTime(prev => Math.max(0, Math.min(maxDuration, prev + timeShift)));
|
|
} else {
|
|
e.preventDefault();
|
|
|
|
// Accurate Mouse-Anchored Zooming
|
|
const rect = timeline.getBoundingClientRect();
|
|
const mouseXInViewport = e.clientX - rect.left;
|
|
const mouseXInCanvas = mouseXInViewport + timeline.scrollLeft;
|
|
const anchorTime = mouseXInCanvas / zoom; // Absolute timeline time under the mouse cursor
|
|
|
|
const zoomFactor = e.deltaY > 0 ? 0.9 : 1.1;
|
|
|
|
setZoom(prevZoom => {
|
|
let newZoom = prevZoom * zoomFactor;
|
|
if (newZoom < minZoom) newZoom = minZoom;
|
|
if (newZoom > 2000) newZoom = 2000;
|
|
|
|
const newMouseXInCanvas = anchorTime * newZoom;
|
|
// Re-align scroll left on render to keep anchorTime locked to identical physical position
|
|
requestAnimationFrame(() => {
|
|
timeline.scrollLeft = newMouseXInCanvas - mouseXInViewport;
|
|
});
|
|
return newZoom;
|
|
});
|
|
}
|
|
};
|
|
|
|
timeline.addEventListener('wheel', handleWheel, { passive: false });
|
|
return () => timeline.removeEventListener('wheel', handleWheel);
|
|
}, [zoom, minZoom, maxDuration]);
|
|
|
|
const updatePlayhead = () => {
|
|
if (!isPlaying) return;
|
|
const context = getAudioContext();
|
|
const elapsed = context.currentTime - startAudioTimeRef.current;
|
|
const updatedTime = startOffsetTimeRef.current + elapsed;
|
|
|
|
// Selection Loop check
|
|
if (isLoopingSelection && selectionStart !== null && selectionEnd !== null) {
|
|
const selStart = Math.min(selectionStart, selectionEnd);
|
|
const selEnd = Math.max(selectionStart, selectionEnd);
|
|
if (selEnd > selStart && updatedTime >= selEnd) {
|
|
// Reset playhead back to selection start seamlessly
|
|
stopAllPlayback();
|
|
startOffsetTimeRef.current = selStart;
|
|
startAudioTimeRef.current = context.currentTime;
|
|
startTrackPlayback(selStart);
|
|
setCurrentTime(selStart);
|
|
animationFrameId.current = requestAnimationFrame(updatePlayhead);
|
|
return;
|
|
}
|
|
}
|
|
|
|
if (updatedTime >= maxDuration) {
|
|
stopAllPlayback();
|
|
setCurrentTime(0);
|
|
return;
|
|
}
|
|
|
|
setCurrentTime(updatedTime);
|
|
animationFrameId.current = requestAnimationFrame(updatePlayhead);
|
|
};
|
|
|
|
useEffect(() => {
|
|
if (isPlaying) {
|
|
animationFrameId.current = requestAnimationFrame(updatePlayhead);
|
|
} else {
|
|
cancelAnimationFrame(animationFrameId.current);
|
|
}
|
|
return () => cancelAnimationFrame(animationFrameId.current);
|
|
}, [isPlaying, isLoopingSelection, selectionStart, selectionEnd]);
|
|
|
|
const startTrackPlayback = (offsetTime) => {
|
|
const context = getAudioContext();
|
|
const hasSolo = tracks.some(t => t.solo) || soloedTrackId !== null;
|
|
|
|
tracks.forEach(track => {
|
|
if (!track.buffer) return;
|
|
|
|
const isPlayable = hasSolo
|
|
? (track.id === soloedTrackId || track.solo)
|
|
: !track.muted;
|
|
|
|
if (!isPlayable) return;
|
|
|
|
const source = context.createBufferSource();
|
|
source.buffer = track.buffer;
|
|
|
|
const gainNode = context.createGain();
|
|
gainNode.gain.setValueAtTime(track.volume, context.currentTime);
|
|
|
|
source.connect(gainNode);
|
|
gainNode.connect(context.destination);
|
|
|
|
if (offsetTime < track.buffer.duration) {
|
|
source.start(0, offsetTime);
|
|
activeSourcesRef.current.push(source);
|
|
}
|
|
});
|
|
};
|
|
|
|
const handlePlayPause = () => {
|
|
const context = getAudioContext();
|
|
if (isPlaying) {
|
|
stopAllPlayback();
|
|
} else {
|
|
startOffsetTimeRef.current = currentTime;
|
|
startAudioTimeRef.current = context.currentTime;
|
|
startTrackPlayback(currentTime);
|
|
setIsPlaying(true);
|
|
}
|
|
};
|
|
|
|
const handlePause = () => {
|
|
if (isPlaying) {
|
|
stopAllPlayback();
|
|
}
|
|
};
|
|
|
|
const stopAllPlayback = () => {
|
|
activeSourcesRef.current.forEach(src => {
|
|
try { src.stop(); } catch(e) {}
|
|
});
|
|
activeSourcesRef.current = [];
|
|
setIsPlaying(false);
|
|
};
|
|
|
|
const handleStop = () => {
|
|
stopAllPlayback();
|
|
setCurrentTime(0);
|
|
};
|
|
|
|
const handleSelectRange = (start, end, reset) => {
|
|
// Safeguard boundaries to prevent Python segmentation faults on slice calculations
|
|
const maxLen = maxDuration;
|
|
const cleanStart = Math.max(0, Math.min(maxLen, start));
|
|
const cleanEnd = Math.max(0, Math.min(maxLen, end));
|
|
|
|
if (reset) {
|
|
setSelectionStart(cleanStart);
|
|
setSelectionEnd(cleanEnd);
|
|
} else {
|
|
setSelectionEnd(cleanEnd);
|
|
}
|
|
};
|
|
|
|
const handleSelectionInputChange = (field, val) => {
|
|
const numericVal = Math.max(0, parseFloat(val) || 0);
|
|
if (field === 'start') {
|
|
setSelectionStart(numericVal);
|
|
} else {
|
|
setSelectionEnd(numericVal);
|
|
}
|
|
};
|
|
|
|
// Calculate formatted selection stats
|
|
const selectionStats = useMemo(() => {
|
|
if (selectionStart === null || selectionEnd === null) {
|
|
return { start: 0, end: 0, length: 0 };
|
|
}
|
|
const s = Math.min(selectionStart, selectionEnd);
|
|
const e = Math.max(selectionStart, selectionEnd);
|
|
return {
|
|
start: parseFloat(s.toFixed(3)),
|
|
end: parseFloat(e.toFixed(3)),
|
|
length: parseFloat((e - s).toFixed(3))
|
|
};
|
|
}, [selectionStart, selectionEnd]);
|
|
|
|
const handleHandleDragStart = (e, side) => {
|
|
e.preventDefault();
|
|
e.stopPropagation();
|
|
const startX = e.clientX;
|
|
const initialLeft = Math.min(selectionStart, selectionEnd);
|
|
const initialRight = Math.max(selectionStart, selectionEnd);
|
|
|
|
const handleMouseMove = (moveEvent) => {
|
|
const deltaX = moveEvent.clientX - startX;
|
|
const deltaSec = deltaX / zoom;
|
|
if (side === 'left') {
|
|
const newLeft = Math.max(0, Math.min(initialRight - 0.05, initialLeft + deltaSec));
|
|
setSelectionStart(newLeft);
|
|
setSelectionEnd(initialRight);
|
|
} else {
|
|
const newRight = Math.max(initialLeft + 0.05, Math.min(maxDuration, initialRight + deltaSec));
|
|
setSelectionStart(initialLeft);
|
|
setSelectionEnd(newRight);
|
|
}
|
|
};
|
|
|
|
const handleMouseUp = () => {
|
|
document.removeEventListener('mousemove', handleMouseMove);
|
|
document.removeEventListener('mouseup', handleMouseUp);
|
|
};
|
|
|
|
document.addEventListener('mousemove', handleMouseMove);
|
|
document.addEventListener('mouseup', handleMouseUp);
|
|
};
|
|
|
|
const handleSelectionBodyDragStart = (e) => {
|
|
e.preventDefault();
|
|
e.stopPropagation();
|
|
const startX = e.clientX;
|
|
const initialLeft = Math.min(selectionStart, selectionEnd);
|
|
const initialRight = Math.max(selectionStart, selectionEnd);
|
|
const widthSec = initialRight - initialLeft;
|
|
|
|
const handleMouseMove = (moveEvent) => {
|
|
const deltaX = moveEvent.clientX - startX;
|
|
const deltaSec = deltaX / zoom;
|
|
let newLeft = initialLeft + deltaSec;
|
|
let newRight = initialRight + deltaSec;
|
|
|
|
if (newLeft < 0) {
|
|
newLeft = 0;
|
|
newRight = widthSec;
|
|
}
|
|
if (newRight > maxDuration) {
|
|
newRight = maxDuration;
|
|
newLeft = maxDuration - widthSec;
|
|
}
|
|
|
|
setSelectionStart(newLeft);
|
|
setSelectionEnd(newRight);
|
|
};
|
|
|
|
const handleMouseUp = () => {
|
|
document.removeEventListener('mousemove', handleMouseMove);
|
|
document.removeEventListener('mouseup', handleMouseUp);
|
|
};
|
|
|
|
document.addEventListener('mousemove', handleMouseMove);
|
|
document.addEventListener('mouseup', handleMouseUp);
|
|
};
|
|
|
|
const handleMarkSelection = () => {
|
|
if (selectionStart === null || selectionEnd === null || selectionStats.length === 0) {
|
|
showToast("Vui lòng chọn một khoảng thời gian trên sóng âm trước.", "warning");
|
|
return;
|
|
}
|
|
|
|
const targetTrack = tracks.find(t => t.id === selectedTrackId);
|
|
if (!targetTrack || !targetTrack.buffer) {
|
|
showToast("Vui lòng nhấp chọn một Track có sóng âm để gán Marker.", "warning");
|
|
return;
|
|
}
|
|
|
|
// Apply on selected track lane
|
|
setTracks(prev => prev.map(t => {
|
|
if (t.id !== selectedTrackId) return t;
|
|
const snapStart = findZeroCrossing(t.buffer, selectionStats.start);
|
|
const snapEnd = findZeroCrossing(t.buffer, selectionStats.end);
|
|
|
|
const newMarkers = [
|
|
...t.markers,
|
|
{ id: Date.now() + '_s', time: snapStart },
|
|
{ id: Date.now() + '_e', time: snapEnd }
|
|
].sort((a,b) => a.time - b.time);
|
|
|
|
return { ...t, markers: newMarkers };
|
|
}));
|
|
|
|
showToast(`Đã tạo 2 Markers tại đầu và cuối dải chọn của Track đang chọn (Snap Zero-Crossing)`, "success");
|
|
};
|
|
|
|
const handleAICutToNewTrack = () => {
|
|
const activeTrack = tracks.find(t => t.id === selectedTrackId);
|
|
if (!activeTrack || !activeTrack.buffer) {
|
|
showToast("Vui lòng chọn một Track có dữ liệu âm thanh trước.", "warning");
|
|
return;
|
|
}
|
|
if (selectionStart === null || selectionEnd === null || selectionStats.length === 0) {
|
|
showToast("Vui lòng kéo chọn một khoảng thời gian trên sóng âm để thực hiện cắt bằng AI.", "warning");
|
|
return;
|
|
}
|
|
|
|
setAnalysisState({ status: 'AI đang phân tích điểm Zero-crossing...', data: null, isRunning: true });
|
|
showToast("AI đang dò tìm điểm Zero-crossing và tính toán mẫu...", "info");
|
|
|
|
const buffer = activeTrack.buffer;
|
|
const sampleRate = buffer.sampleRate;
|
|
const channelData = buffer.getChannelData(0);
|
|
|
|
const snapStart = findZeroCrossing(buffer, selectionStats.start);
|
|
const snapEnd = findZeroCrossing(buffer, selectionStats.end);
|
|
|
|
// Safe Boundary Assertions to prevent array slice failures when ported to Python
|
|
const startSample = Math.max(0, Math.min(channelData.length - 1, Math.floor(snapStart * sampleRate)));
|
|
const endSample = Math.max(0, Math.min(channelData.length, Math.floor(snapEnd * sampleRate)));
|
|
const sliceLength = endSample - startSample;
|
|
|
|
if (sliceLength <= 0) {
|
|
showToast("Dải cắt không hợp lệ hoặc khoảng thời gian quá ngắn.", "error");
|
|
setAnalysisState({ status: 'Thất bại', data: null, isRunning: false });
|
|
return;
|
|
}
|
|
|
|
setTimeout(() => {
|
|
try {
|
|
const context = getAudioContext();
|
|
const slicedBuffer = context.createBuffer(1, sliceLength, sampleRate);
|
|
const slicedData = slicedBuffer.getChannelData(0);
|
|
slicedData.set(channelData.subarray(startSample, endSample));
|
|
|
|
const newId = 'track_ai_cut_' + Date.now();
|
|
const colors = ['#0f766e', '#1d4ed8', '#701a75', '#a21caf', '#b45309'];
|
|
const selectColor = colors[tracks.length % colors.length];
|
|
|
|
setTracks(prev => [
|
|
...prev,
|
|
{
|
|
id: newId,
|
|
name: `AI_Cut_${activeTrack.name.replace('.wav', '')}_${snapStart.toFixed(1)}s.wav`,
|
|
buffer: slicedBuffer,
|
|
volume: 0.8,
|
|
muted: false,
|
|
solo: false,
|
|
color: selectColor,
|
|
markers: [
|
|
{ id: Date.now() + '_s', time: 0 },
|
|
{ id: Date.now() + '_e', time: snapEnd - snapStart }
|
|
]
|
|
}
|
|
]);
|
|
|
|
setSelectedTrackId(newId);
|
|
setAnalysisState({
|
|
status: 'Phân đoạn AI hoàn tất!',
|
|
data: { bpm: 120, bars: 4, timeSig: '4/4', detectedKey: 'Am' },
|
|
isRunning: false
|
|
});
|
|
showToast(`AI đã cắt & gộp thành công vào Track mới (Zero-Crossing aligned)`, "success");
|
|
setTimeout(() => lucide.createIcons(), 200);
|
|
} catch (err) {
|
|
showToast("Lỗi giải mã dải cắt: " + err.message, "error");
|
|
setAnalysisState({ status: 'Lỗi biên tập', data: null, isRunning: false });
|
|
}
|
|
}, 1000);
|
|
};
|
|
|
|
const handleSplitTrack = (trackId) => {
|
|
const track = tracks.find(t => t.id === trackId);
|
|
if (!track || !track.buffer) return;
|
|
|
|
const cutTime = findZeroCrossing(track.buffer, currentTime);
|
|
const sampleRate = track.buffer.sampleRate;
|
|
const cutSample = Math.floor(cutTime * sampleRate);
|
|
const originalData = track.buffer.getChannelData(0);
|
|
|
|
if (cutSample <= 0 || cutSample >= originalData.length) {
|
|
showToast("Vị trí Playhead nằm ngoài dải biên tập âm thanh.", "warning");
|
|
return;
|
|
}
|
|
|
|
const ctx = getAudioContext();
|
|
const b1 = ctx.createBuffer(1, cutSample, sampleRate);
|
|
b1.copyToChannel(originalData.subarray(0, cutSample), 0);
|
|
|
|
const b2 = ctx.createBuffer(1, originalData.length - cutSample, sampleRate);
|
|
b2.copyToChannel(originalData.subarray(cutSample), 0);
|
|
|
|
setTracks(prev => {
|
|
const idx = prev.findIndex(t => t.id === trackId);
|
|
const updated = [...prev];
|
|
updated[idx] = { ...track, name: `${track.name} (Part 1)`, buffer: b1 };
|
|
|
|
const newTrack = {
|
|
...track,
|
|
id: 'track_split_' + Date.now(),
|
|
name: `${track.name} (Part 2)`,
|
|
buffer: b2,
|
|
markers: []
|
|
};
|
|
updated.splice(idx + 1, 0, newTrack);
|
|
return updated;
|
|
});
|
|
showToast("Đã chia nhỏ track tại vị trí Playhead.", "info");
|
|
};
|
|
|
|
const toggleTrackSoloEvaluate = (trackId) => {
|
|
const wasPlaying = isPlaying;
|
|
stopAllPlayback();
|
|
|
|
setTracks(prev => prev.map(t => {
|
|
if (t.id === trackId) {
|
|
return { ...t, solo: !t.solo, muted: false };
|
|
}
|
|
return { ...t, solo: false };
|
|
}));
|
|
|
|
setSoloedTrackId(prev => prev === trackId ? null : trackId);
|
|
|
|
if (wasPlaying) {
|
|
setTimeout(() => {
|
|
startOffsetTimeRef.current = currentTime;
|
|
startAudioTimeRef.current = getAudioContext().currentTime;
|
|
setIsPlaying(true);
|
|
}, 50);
|
|
}
|
|
};
|
|
|
|
const toggleTrackMute = (trackId) => {
|
|
setTracks(prev => prev.map(t => t.id === trackId ? { ...t, muted: !t.muted } : t));
|
|
};
|
|
|
|
const updateTrackVolume = (trackId, val) => {
|
|
setTracks(prev => prev.map(t => t.id === trackId ? { ...t, volume: val } : t));
|
|
};
|
|
|
|
const loadFileOnTrack = (trackId, file) => {
|
|
if (!file) return;
|
|
const context = getAudioContext();
|
|
showToast(`Đang nạp file ${file.name}...`, 'info');
|
|
|
|
const reader = new FileReader();
|
|
reader.onload = async (e) => {
|
|
try {
|
|
const decodedBuffer = await context.decodeAudioData(e.target.result);
|
|
setTracks(prev => prev.map(t => t.id === trackId ? {
|
|
...t,
|
|
name: file.name,
|
|
buffer: decodedBuffer
|
|
} : t));
|
|
showToast(`Nạp file thành công: ${file.name}`, 'success');
|
|
} catch (err) {
|
|
showToast("Lỗi giải mã âm thanh. Định dạng file không tương thích.", 'error');
|
|
}
|
|
};
|
|
reader.readAsArrayBuffer(file);
|
|
};
|
|
|
|
const generateSynthToTrack = (trackId, type) => {
|
|
const sampleRate = 44100;
|
|
const duration = 12.0;
|
|
const context = getAudioContext();
|
|
const frameCount = sampleRate * duration;
|
|
const newBuffer = context.createBuffer(1, frameCount, sampleRate);
|
|
const channelData = newBuffer.getChannelData(0);
|
|
|
|
if (type === 'kick') {
|
|
for (let i = 0; i < frameCount; i++) {
|
|
const t = i / sampleRate;
|
|
const beatTime = t % 0.5;
|
|
const freq = 120 * Math.exp(-35 * beatTime);
|
|
channelData[i] = Math.sin(2 * Math.PI * freq * beatTime) * Math.exp(-6 * beatTime);
|
|
}
|
|
} else {
|
|
const notes = [220.00, 261.63, 293.66, 329.63, 392.00];
|
|
for (let i = 0; i < frameCount; i++) {
|
|
const t = i / sampleRate;
|
|
const noteIdx = Math.floor(t * 2) % notes.length;
|
|
const freq = notes[noteIdx];
|
|
channelData[i] = Math.sin(2 * Math.PI * freq * t) * 0.25 * (1.0 - (t % 0.5) / 0.5);
|
|
}
|
|
}
|
|
|
|
setTracks(prev => prev.map(t => t.id === trackId ? {
|
|
...t,
|
|
name: `Demo_${type.toUpperCase()}.wav`,
|
|
buffer: newBuffer
|
|
} : t));
|
|
showToast(`Đã nạp sóng âm tổng hợp: ${type.toUpperCase()}`, 'success');
|
|
};
|
|
|
|
const addNewTrack = () => {
|
|
const newId = (tracks.length + 1).toString();
|
|
const colors = ['#0f766e', '#1d4ed8', '#701a75', '#a21caf', '#b45309'];
|
|
const selectColor = colors[tracks.length % colors.length];
|
|
|
|
setTracks(prev => [...prev, {
|
|
id: newId,
|
|
name: `Track ${newId}`,
|
|
buffer: null,
|
|
volume: 0.8,
|
|
muted: false,
|
|
solo: false,
|
|
color: selectColor,
|
|
markers: []
|
|
}]);
|
|
showToast(`Đã thêm Track ${newId}.`, 'info');
|
|
setTimeout(() => lucide.createIcons(), 200);
|
|
};
|
|
|
|
const triggerWavExport = async () => {
|
|
const activeTracks = tracks.filter(t => t.buffer && !t.muted);
|
|
if (activeTracks.length === 0) {
|
|
showToast("Không tìm thấy dữ liệu âm thanh hợp lệ để xuất.", "warning");
|
|
return;
|
|
}
|
|
|
|
setIsExporting(true);
|
|
showToast("Đang trộn âm thanh đa kênh (Offline Mixdown)...", "info");
|
|
|
|
try {
|
|
const targetRate = parseInt(exportSettings.sampleRate);
|
|
const bitDepth = parseInt(exportSettings.bitDepth);
|
|
const durationLimit = Math.max(...activeTracks.map(t => t.buffer.duration));
|
|
|
|
const offlineCtx = new OfflineAudioContext(1, targetRate * durationLimit, targetRate);
|
|
|
|
activeTracks.forEach(t => {
|
|
const source = offlineCtx.createBufferSource();
|
|
source.buffer = t.buffer;
|
|
const gain = offlineCtx.createGain();
|
|
gain.gain.setValueAtTime(t.volume, 0);
|
|
|
|
source.connect(gain);
|
|
gain.connect(offlineCtx.destination);
|
|
source.start(0);
|
|
});
|
|
|
|
const renderedBuffer = await offlineCtx.startRendering();
|
|
const monoData = renderedBuffer.getChannelData(0);
|
|
|
|
const bufferLength = monoData.length;
|
|
const bytesPerSample = bitDepth / 8;
|
|
const headerSize = 44;
|
|
const fileSizeBytes = headerSize + (bufferLength * bytesPerSample);
|
|
const fileBuffer = new ArrayBuffer(fileSizeBytes);
|
|
const view = new DataView(fileBuffer);
|
|
|
|
const writeString = (offset, string) => {
|
|
for (let i = 0; i < string.length; i++) {
|
|
view.setUint8(offset + i, string.charCodeAt(i));
|
|
}
|
|
};
|
|
|
|
writeString(0, 'RIFF');
|
|
view.setUint32(4, fileSizeBytes - 8, true);
|
|
writeString(8, 'WAVE');
|
|
writeString(12, 'fmt ');
|
|
view.setUint32(16, 16, true);
|
|
view.setUint16(20, 1, true); // PCM
|
|
view.setUint16(22, 1, true); // Mono channel
|
|
view.setUint32(24, targetRate, true);
|
|
view.setUint32(28, targetRate * bytesPerSample, true);
|
|
view.setUint16(32, bytesPerSample, true);
|
|
view.setUint16(34, bitDepth, true);
|
|
writeString(36, 'data');
|
|
view.setUint32(40, bufferLength * bytesPerSample, true);
|
|
|
|
let offset = 44;
|
|
for (let i = 0; i < bufferLength; i++) {
|
|
const sample = Math.max(-1, Math.min(1, monoData[i]));
|
|
|
|
if (bitDepth === 8) {
|
|
const val8 = Math.floor((sample + 1.0) * 127.5);
|
|
view.setUint8(offset, val8);
|
|
} else if (bitDepth === 16) {
|
|
const val16 = sample < 0 ? sample * 0x8000 : sample * 0x7FFF;
|
|
view.setInt16(offset, Math.floor(val16), true);
|
|
} else if (bitDepth === 24) {
|
|
const val24 = Math.floor(sample < 0 ? sample * 0x800000 : sample * 0x7FFFFF);
|
|
view.setUint8(offset, val24 & 0xFF);
|
|
view.setUint8(offset + 1, (val24 >> 8) & 0xFF);
|
|
view.setUint8(offset + 2, (val24 >> 16) & 0xFF);
|
|
}
|
|
offset += bytesPerSample;
|
|
}
|
|
|
|
const blob = new Blob([view], { type: 'audio/wav' });
|
|
const url = URL.createObjectURL(blob);
|
|
const a = document.createElement('a');
|
|
a.href = url;
|
|
a.download = `sonicforge-session-${targetRate}hz-${bitDepth}bit.wav`;
|
|
a.click();
|
|
URL.revokeObjectURL(url);
|
|
showToast("Xuất bản âm thanh hoàn tất!", "success");
|
|
} catch (err) {
|
|
showToast("Lỗi xuất âm thanh: " + err.message, "error");
|
|
} finally {
|
|
setIsExporting(false);
|
|
}
|
|
};
|
|
|
|
const triggerAIAnalysis = async () => {
|
|
setAnalysisState({ status: 'Connecting to AI Engine...', data: null, isRunning: true });
|
|
|
|
if (!aiConfig.apiKey) {
|
|
setTimeout(() => {
|
|
setAnalysisState({ status: 'Processing PyDub structural detection...', data: null, isRunning: true });
|
|
setTimeout(() => {
|
|
const simulatedTempo = Math.floor(Math.random() * (135 - 90) + 90);
|
|
setAnalysisState({
|
|
status: 'Hoàn thành phân tích (Simulation)',
|
|
data: { bpm: simulatedTempo, bars: 16, timeSig: '4/4', detectedKey: 'Am' },
|
|
isRunning: false
|
|
});
|
|
showToast(`AI đã phân tích cấu trúc nhịp: ${simulatedTempo} BPM`, 'success');
|
|
}, 1200);
|
|
}, 1000);
|
|
return;
|
|
}
|
|
|
|
try {
|
|
const response = await fetch(`${aiConfig.baseUrl}/chat/completions`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'Authorization': `Bearer ${aiConfig.apiKey}`
|
|
},
|
|
body: JSON.stringify({
|
|
model: aiConfig.model,
|
|
messages: [
|
|
{
|
|
role: 'system',
|
|
content: 'You are an acoustic analysis AI. The user is editing audio. Predict potential tempo, key signature, and bar count based on file structure meta.'
|
|
},
|
|
{
|
|
role: 'user',
|
|
content: `Analyze this workspace: Total tracks: ${tracks.length}, Total duration: ${maxDuration}s. Output JSON with fields: "bpm" (number), "bars" (number), "detectedKey" (string), "timeSig" (string)`
|
|
}
|
|
],
|
|
response_format: { type: "json_object" }
|
|
})
|
|
});
|
|
|
|
if (!response.ok) throw new Error("API Connection Failed.");
|
|
|
|
const jsonResult = await response.json();
|
|
const aiPayload = JSON.parse(jsonResult.choices[0].message.content);
|
|
|
|
setAnalysisState({
|
|
status: 'Phân tích thành công từ Server AI!',
|
|
data: {
|
|
bpm: aiPayload.bpm || 120,
|
|
bars: aiPayload.bars || 8,
|
|
timeSig: aiPayload.timeSig || '4/4',
|
|
detectedKey: aiPayload.detectedKey || 'C'
|
|
},
|
|
isRunning: false
|
|
});
|
|
showToast("Server AI phân tích dữ liệu âm học hoàn tất!", "success");
|
|
} catch (err) {
|
|
setAnalysisState({ status: 'Lỗi API: Sử dụng dữ liệu mô phỏng.', data: null, isRunning: false });
|
|
showToast("Kết nối API AI thất bại. Đang chuyển sang Chế độ Mô phỏng.", "warning");
|
|
}
|
|
};
|
|
|
|
const playheadLeftPos = currentTime * zoom;
|
|
const selLeft = selectionStart !== null && selectionEnd !== null ? Math.min(selectionStart, selectionEnd) : null;
|
|
const selRight = selectionStart !== null && selectionEnd !== null ? Math.max(selectionStart, selectionEnd) : null;
|
|
|
|
return (
|
|
<div className="flex-1 flex flex-col h-full overflow-hidden select-none">
|
|
|
|
{/* Top Control Panel Tools */}
|
|
<header className="h-11 daw-panel flex items-center justify-between px-4 border-b border-zinc-900 text-xs">
|
|
<div className="flex items-center gap-3">
|
|
<span className="font-extrabold text-[#ef4444] tracking-wider flex items-center gap-1">
|
|
<i data-lucide="waves" className="w-4 h-4"></i> SONICFORGE STUDIO Pro
|
|
</span>
|
|
<div className="h-4 w-[1px] bg-zinc-800"></div>
|
|
<button
|
|
onClick={addNewTrack}
|
|
className="px-2.5 py-1 bg-zinc-800 hover:bg-zinc-700 text-zinc-200 rounded flex items-center gap-1.5 font-medium transition"
|
|
>
|
|
<i data-lucide="plus" className="w-3.5 h-3.5 text-zinc-400"></i> Thêm Track Mới
|
|
</button>
|
|
</div>
|
|
<div className="flex items-center gap-2">
|
|
<button
|
|
onClick={() => setAiConfig(prev => ({ ...prev, showSettings: !prev.showSettings }))}
|
|
className={`px-2.5 py-1.5 rounded flex items-center gap-1 transition ${
|
|
aiConfig.showSettings ? 'bg-purple-800 text-white' : 'bg-zinc-800 hover:bg-zinc-700 text-zinc-300'
|
|
}`}
|
|
>
|
|
<i data-lucide="settings" className="w-3.5 h-3.5"></i> Cấu hình AI Server
|
|
</button>
|
|
<span className="text-[10px] text-zinc-500 uppercase font-bold">Lưới đồng bộ: Bật</span>
|
|
</div>
|
|
</header>
|
|
|
|
{/* OpenAI Compatible Settings Popup Drawer */}
|
|
{aiConfig.showSettings && (
|
|
<div className="bg-zinc-900 border-b border-purple-900 p-3 flex flex-col gap-2 transition-all">
|
|
<div className="text-xs font-bold text-purple-400 uppercase tracking-wider flex items-center gap-1">
|
|
<i data-lucide="cpu" className="w-4 h-4"></i> Cấu hình cổng kết nối OpenAI Compatible (Docker / Local / Cloud)
|
|
</div>
|
|
<div className="grid grid-cols-1 md:grid-cols-3 gap-2 text-xs">
|
|
<div className="flex flex-col gap-1">
|
|
<span className="text-[10px] text-zinc-500 font-bold uppercase">Endpoint Base URL</span>
|
|
<input
|
|
type="text"
|
|
value={aiConfig.baseUrl}
|
|
onChange={(e) => setAiConfig(prev => ({ ...prev, baseUrl: e.target.value }))}
|
|
className="bg-zinc-850 text-zinc-200 p-1.5 rounded border border-zinc-800 focus:outline-none focus:border-purple-600 font-mono text-[11px]"
|
|
placeholder="https://api.openai.com/v1"
|
|
/>
|
|
</div>
|
|
<div className="flex flex-col gap-1">
|
|
<span className="text-[10px] text-zinc-500 font-bold uppercase">API Token Key</span>
|
|
<input
|
|
type="password"
|
|
value={aiConfig.apiKey}
|
|
onChange={(e) => setAiConfig(prev => ({ ...prev, apiKey: e.target.value }))}
|
|
className="bg-zinc-850 text-zinc-200 p-1.5 rounded border border-zinc-800 focus:outline-none focus:border-purple-600 font-mono text-[11px]"
|
|
placeholder="sk-..."
|
|
/>
|
|
</div>
|
|
<div className="flex flex-col gap-1">
|
|
<span className="text-[10px] text-zinc-500 font-bold uppercase">Model Name Target</span>
|
|
<input
|
|
type="text"
|
|
value={aiConfig.model}
|
|
onChange={(e) => setAiConfig(prev => ({ ...prev, model: e.target.value }))}
|
|
className="bg-zinc-850 text-zinc-200 p-1.5 rounded border border-zinc-800 focus:outline-none focus:border-purple-600 font-mono text-[11px]"
|
|
placeholder="gpt-4o-mini"
|
|
/>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
)}
|
|
|
|
{/* Pro DAW Unified Workspace Interface with synchronized vertical scrolling */}
|
|
<div className="flex-1 flex overflow-y-auto select-none daw-bg relative">
|
|
|
|
{/* TCP Left Columns */}
|
|
<div className="w-[300px] flex flex-col daw-panel border-r border-zinc-900 z-10 select-none shrink-0">
|
|
<div className="h-8 border-b border-zinc-900 bg-[#242424] flex items-center px-4 justify-between sticky top-0 z-30">
|
|
<span className="text-[10px] font-bold text-zinc-500 uppercase">Danh Sách Kênh / TCP</span>
|
|
<span className="text-[9px] bg-cyan-950 text-cyan-400 px-1 rounded font-bold uppercase">Chọn Click</span>
|
|
</div>
|
|
|
|
{/* TCP Channels Stack */}
|
|
<div className="flex flex-col divide-y divide-[#141414]">
|
|
{tracks.map((track, idx) => {
|
|
const isSelected = selectedTrackId === track.id;
|
|
return (
|
|
<div
|
|
key={track.id}
|
|
onClick={() => setSelectedTrackId(track.id)}
|
|
className={`h-[96px] p-2.5 flex flex-col justify-between transition-all relative cursor-pointer ${
|
|
isSelected
|
|
? 'bg-zinc-800/80 border-l-4 border-cyan-500 pl-1.5 ring-1 ring-cyan-500/30'
|
|
: 'hover:bg-zinc-800/30'
|
|
}`}
|
|
>
|
|
<div className="flex items-start justify-between">
|
|
<div className="flex items-center gap-2">
|
|
<span className="text-[10px] font-bold text-zinc-500 font-mono">{(idx+1).toString().padStart(2, '0')}</span>
|
|
<div
|
|
className="w-2.5 h-2.5 rounded-full"
|
|
style={{ backgroundColor: track.color }}
|
|
/>
|
|
<span className="text-xs font-semibold text-zinc-300 truncate max-w-[120px]" title={track.name}>
|
|
{track.name}
|
|
</span>
|
|
</div>
|
|
|
|
<div className="flex items-center gap-1">
|
|
<button
|
|
onClick={(e) => { e.stopPropagation(); toggleTrackMute(track.id); }}
|
|
className={`px-1.5 py-0.5 text-[10px] rounded font-mono font-bold border transition ${
|
|
track.muted
|
|
? 'bg-red-950 text-red-400 border-red-700'
|
|
: 'bg-zinc-800 text-zinc-400 border-transparent hover:text-zinc-200'
|
|
}`}
|
|
>
|
|
M
|
|
</button>
|
|
<button
|
|
onClick={(e) => { e.stopPropagation(); toggleTrackSoloEvaluate(track.id); }}
|
|
className={`px-1.5 py-0.5 text-[10px] rounded font-mono font-bold border transition ${
|
|
soloedTrackId === track.id || track.solo
|
|
? 'bg-amber-950 text-amber-400 border-amber-600'
|
|
: 'bg-zinc-800 text-zinc-400 border-transparent hover:text-zinc-200'
|
|
}`}
|
|
title="Solo nghe thử độc lập"
|
|
>
|
|
S
|
|
</button>
|
|
</div>
|
|
</div>
|
|
|
|
{/* Synth loop loaders */}
|
|
<div className="flex items-center gap-1 text-[9px] text-zinc-400" onClick={e => e.stopPropagation()}>
|
|
<span className="font-semibold uppercase text-[8px] text-zinc-500">Mô phỏng:</span>
|
|
<button
|
|
onClick={() => generateSynthToTrack(track.id, 'kick')}
|
|
className="px-1 bg-zinc-800 hover:bg-zinc-700 rounded border border-zinc-700"
|
|
>
|
|
Kick Drum
|
|
</button>
|
|
<button
|
|
onClick={() => generateSynthToTrack(track.id, 'synth')}
|
|
className="px-1 bg-zinc-800 hover:bg-zinc-700 rounded border border-zinc-700"
|
|
>
|
|
Arpeggiator
|
|
</button>
|
|
</div>
|
|
|
|
{/* Volume dial */}
|
|
<div className="flex items-center justify-between gap-2" onClick={e => e.stopPropagation()}>
|
|
<div className="flex items-center gap-1.5">
|
|
<VolumeKnob
|
|
value={track.volume}
|
|
onChange={(v) => updateTrackVolume(track.id, v)}
|
|
/>
|
|
<span className="text-[10px] font-mono text-zinc-500">
|
|
Gain: {Math.round(track.volume * 100)}%
|
|
</span>
|
|
</div>
|
|
|
|
{/* Local Upload Picker */}
|
|
<div>
|
|
<input
|
|
type="file"
|
|
id={`upload-${track.id}`}
|
|
accept="audio/*"
|
|
className="hidden"
|
|
onChange={(e) => loadFileOnTrack(track.id, e.target.files[0])}
|
|
/>
|
|
<label
|
|
htmlFor={`upload-${track.id}`}
|
|
className="px-2 py-1 bg-zinc-800 hover:bg-zinc-700 text-zinc-300 rounded text-[10px] flex items-center gap-1 cursor-pointer transition border border-zinc-700"
|
|
>
|
|
<i data-lucide="upload" className="w-3 h-3"></i> Tải file
|
|
</label>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
);
|
|
})}
|
|
</div>
|
|
</div>
|
|
|
|
{/* Timeline Right Canvas lanes area (Synchronously scrolling along total duration) */}
|
|
<div
|
|
ref={timelineWrapperRef}
|
|
className="flex-1 overflow-x-auto relative bg-[#111111]"
|
|
>
|
|
<div style={{ width: `${timelineWidth}px` }} className="relative flex flex-col h-full">
|
|
|
|
{/* Ruler bar element - STICKY top */}
|
|
<div className="h-8 border-b border-zinc-900 bg-[#242424] sticky top-0 z-30 flex items-center select-none shrink-0">
|
|
{Array.from({ length: Math.ceil(maxDuration) }).map((_, i) => {
|
|
const sec = i;
|
|
const x = sec * zoom;
|
|
return (
|
|
<div
|
|
key={i}
|
|
className="absolute h-full border-l border-zinc-800 pl-1 pt-1 text-[9px] font-mono text-zinc-500 pointer-events-none"
|
|
style={{ left: `${x}px` }}
|
|
>
|
|
{formatTime(sec)}
|
|
</div>
|
|
);
|
|
})}
|
|
</div>
|
|
|
|
{/* Stacked Lanes Aligned with Left controls */}
|
|
<div className="flex-1 flex flex-col relative divide-y divide-[#141414]">
|
|
{tracks.map((track) => {
|
|
const isSelected = selectedTrackId === track.id;
|
|
return (
|
|
<div
|
|
key={track.id}
|
|
className="h-[96px] w-full relative flex-shrink-0"
|
|
onDragOver={(e) => e.preventDefault()}
|
|
onDrop={(e) => {
|
|
e.preventDefault();
|
|
if (e.dataTransfer.files[0]) {
|
|
loadFileOnTrack(track.id, e.dataTransfer.files[0]);
|
|
}
|
|
}}
|
|
>
|
|
<WaveformLane
|
|
track={track}
|
|
zoom={zoom}
|
|
timelineWidth={timelineWidth}
|
|
onSelectRange={handleSelectRange}
|
|
onPlayheadSet={setCurrentTime}
|
|
isSelected={isSelected}
|
|
onSelectTrack={setSelectedTrackId}
|
|
markers={track.markers}
|
|
/>
|
|
|
|
{/* Fast contextual toolbar overlay on wave */}
|
|
{track.buffer && (
|
|
<div className="absolute right-2 top-2 flex items-center gap-1 z-10 opacity-70 hover:opacity-100 transition">
|
|
<button
|
|
onClick={() => handleSplitTrack(track.id)}
|
|
className="px-1.5 py-0.5 bg-zinc-900/90 text-zinc-300 rounded text-[9px] flex items-center gap-1 border border-zinc-700/50"
|
|
title="Cắt đoạn tại Playhead"
|
|
>
|
|
<i data-lucide="scissors" className="w-2.5 h-2.5 text-cyan-400"></i> Cắt (Split)
|
|
</button>
|
|
</div>
|
|
)}
|
|
</div>
|
|
);
|
|
})}
|
|
|
|
{/* Selection Overlay with Interactive Left/Right Resize and Middle Move handles */}
|
|
{/* FIX: Set top-8 to start exactly below the Ruler and cover the full lanes without cutting waveforms */}
|
|
{selLeft !== null && selRight !== null && selRight > selLeft && (
|
|
<div
|
|
className="absolute top-8 bottom-0 border-l border-r border-amber-500 bg-amber-500/10 z-20 selection-interactive-box cursor-grab active:cursor-grabbing"
|
|
style={{
|
|
left: `${selLeft * zoom}px`,
|
|
width: `${(selRight - selLeft) * zoom}px`
|
|
}}
|
|
onMouseDown={handleSelectionBodyDragStart}
|
|
title="Nhấp kéo để di chuyển vùng chọn"
|
|
>
|
|
{/* Left handle */}
|
|
<div
|
|
className="absolute -left-1.5 top-0 bottom-0 w-3 bg-amber-500 hover:bg-amber-400 cursor-ew-resize flex items-center justify-center z-30 transition-colors"
|
|
onMouseDown={(e) => handleHandleDragStart(e, 'left')}
|
|
title="Kéo giãn mốc bắt đầu"
|
|
>
|
|
<div className="w-[1.5px] h-4 bg-zinc-950/70 rounded"></div>
|
|
</div>
|
|
|
|
{/* Right handle */}
|
|
<div
|
|
className="absolute -right-1.5 top-0 bottom-0 w-3 bg-amber-500 hover:bg-amber-400 cursor-ew-resize flex items-center justify-center z-30 transition-colors"
|
|
onMouseDown={(e) => handleHandleDragStart(e, 'right')}
|
|
title="Kéo giãn mốc kết thúc"
|
|
>
|
|
<div className="w-[1.5px] h-4 bg-zinc-950/70 rounded"></div>
|
|
</div>
|
|
</div>
|
|
)}
|
|
|
|
{/* Overlay Continuous Global Playhead line */}
|
|
<div
|
|
className="absolute top-0 bottom-0 w-[2px] bg-[#ef4444] z-20 pointer-events-none"
|
|
style={{ left: `${playheadLeftPos}px` }}
|
|
>
|
|
<div className="w-3 h-3 bg-[#ef4444] rotate-45 transform -translate-x-1/2 -translate-y-1/2 absolute top-0"></div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
{/* Pro DAW Bottom Controls Footer Layout */}
|
|
<footer className="h-44 bg-[#1c1c1c] border-t border-zinc-900 p-4 grid grid-cols-1 md:grid-cols-12 gap-4 text-xs shrink-0 select-none">
|
|
|
|
{/* Audio Export Section */}
|
|
<section className="md:col-span-4 bg-[#262626] border border-zinc-800 rounded p-3 flex flex-col justify-between">
|
|
<div>
|
|
<h3 className="font-bold text-zinc-200 flex items-center gap-1.5 mb-1.5">
|
|
<i data-lucide="save" className="w-4 h-4 text-cyan-400"></i> Trộn & Xuất bản âm thanh (WAV)
|
|
</h3>
|
|
<div className="grid grid-cols-3 gap-2 mt-1">
|
|
<div>
|
|
<label className="block text-[8px] text-zinc-500 font-bold uppercase mb-0.5">Sample Rate</label>
|
|
<select
|
|
value={exportSettings.sampleRate}
|
|
onChange={(e) => setExportSettings(prev => ({ ...prev, sampleRate: e.target.value }))}
|
|
className="w-full bg-[#141414] border border-zinc-800 rounded px-1.5 py-1 text-[10px] text-zinc-300 focus:outline-none"
|
|
>
|
|
<option value="22500">22.5 kHz</option>
|
|
<option value="44100">44.1 kHz</option>
|
|
<option value="48000">48.0 kHz</option>
|
|
</select>
|
|
</div>
|
|
<div>
|
|
<label className="block text-[8px] text-zinc-500 font-bold uppercase mb-0.5">Bit Depth</label>
|
|
<select
|
|
value={exportSettings.bitDepth}
|
|
onChange={(e) => setExportSettings(prev => ({ ...prev, bitDepth: e.target.value }))}
|
|
className="w-full bg-[#141414] border border-zinc-800 rounded px-1.5 py-1 text-[10px] text-zinc-300 focus:outline-none"
|
|
>
|
|
<option value="8">8-bit</option>
|
|
<option value="16">16-bit</option>
|
|
<option value="24">24-bit</option>
|
|
</select>
|
|
</div>
|
|
<div>
|
|
<label className="block text-[8px] text-zinc-500 font-bold uppercase mb-0.5">Mã Hóa</label>
|
|
<select
|
|
value={exportSettings.format}
|
|
onChange={(e) => setExportSettings(prev => ({ ...prev, format: e.target.value }))}
|
|
className="w-full bg-[#141414] border border-zinc-800 rounded px-1.5 py-1 text-[10px] text-zinc-300 focus:outline-none"
|
|
>
|
|
<option value="wav">WAV (.wav)</option>
|
|
<option value="mp3">MP3 (.mp3)</option>
|
|
<option value="ogg">OGG (.ogg)</option>
|
|
</select>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<button
|
|
onClick={triggerWavExport}
|
|
disabled={isExporting}
|
|
className="w-full py-1.5 mt-2 bg-cyan-700 hover:bg-cyan-600 active:bg-cyan-800 text-zinc-100 font-bold rounded flex items-center justify-center gap-1.5 transition text-xs shadow-md"
|
|
>
|
|
<i data-lucide="download-cloud" className="w-4 h-4"></i>
|
|
{isExporting ? 'Đang xuất...' : 'Xuất bản bản phối'}
|
|
</button>
|
|
</section>
|
|
|
|
{/* Transport Center Play, Pause, Region Selection stats */}
|
|
<section className="md:col-span-4 bg-[#242424] border border-zinc-800 rounded p-3 flex flex-col justify-between items-center text-center">
|
|
<div className="flex w-full items-center justify-between">
|
|
<span className="text-[10px] text-zinc-500 font-bold uppercase tracking-wider">Transport Controls</span>
|
|
<div className="text-sm font-bold font-mono text-zinc-100">
|
|
{formatTime(currentTime)}
|
|
</div>
|
|
</div>
|
|
|
|
{/* Active Region Selection Monitor */}
|
|
<div className="grid grid-cols-3 gap-2 w-full mt-1 bg-[#141414] p-1.5 rounded border border-zinc-800">
|
|
<div>
|
|
<span className="block text-[8px] text-zinc-500 font-bold uppercase mb-0.5">Vùng Chọn Đầu</span>
|
|
<input
|
|
type="number"
|
|
step="0.01"
|
|
value={selectionStats.start}
|
|
onChange={(e) => handleSelectionInputChange('start', e.target.value)}
|
|
className="w-full bg-[#242424] text-amber-400 text-center font-mono text-[11px] rounded py-0.5 border border-zinc-700 focus:outline-none"
|
|
/>
|
|
</div>
|
|
<div>
|
|
<span className="block text-[8px] text-zinc-500 font-bold uppercase mb-0.5">Vùng Chọn Cuối</span>
|
|
<input
|
|
type="number"
|
|
step="0.01"
|
|
value={selectionStats.end}
|
|
onChange={(e) => handleSelectionInputChange('end', e.target.value)}
|
|
className="w-full bg-[#242424] text-amber-400 text-center font-mono text-[11px] rounded py-0.5 border border-zinc-700 focus:outline-none"
|
|
/>
|
|
</div>
|
|
<div className="flex flex-col justify-center">
|
|
<span className="text-[8px] text-zinc-500 font-bold uppercase">Thời Lượng</span>
|
|
<span className="text-zinc-200 font-mono text-[11px] font-semibold mt-0.5">
|
|
{selectionStats.length}s
|
|
</span>
|
|
</div>
|
|
</div>
|
|
|
|
{/* Equal Sized Transport Grid Buttons */}
|
|
<div className="flex items-center gap-1 justify-center w-full mt-1.5">
|
|
<button
|
|
onClick={() => setCurrentTime(0)}
|
|
className="w-8 h-8 flex items-center justify-center bg-zinc-800 hover:bg-zinc-700 text-zinc-200 rounded border border-zinc-700 transition"
|
|
title="Quay lại đầu track"
|
|
>
|
|
<i data-lucide="skip-back" className="w-4 h-4"></i>
|
|
</button>
|
|
<button
|
|
onClick={() => { if (selLeft !== null) setCurrentTime(selLeft); }}
|
|
className="w-8 h-8 flex items-center justify-center bg-zinc-800 hover:bg-zinc-700 text-zinc-200 rounded border border-zinc-700 transition"
|
|
title="Quay lại đầu vùng chọn"
|
|
>
|
|
<i data-lucide="step-back" className="w-4 h-4"></i>
|
|
</button>
|
|
<button
|
|
onClick={handlePlayPause}
|
|
className={`w-8 h-8 flex items-center justify-center rounded border transition ${
|
|
isPlaying
|
|
? 'bg-emerald-600 text-black border-emerald-500 hover:bg-emerald-500'
|
|
: 'bg-cyan-600 text-white border-cyan-500 hover:bg-cyan-500'
|
|
}`}
|
|
title={isPlaying ? "Tạm dừng phát" : "Master Play"}
|
|
>
|
|
<i data-lucide="play" className="w-4 h-4 fill-current"></i>
|
|
</button>
|
|
<button
|
|
onClick={handlePause}
|
|
className="w-8 h-8 flex items-center justify-center bg-zinc-800 hover:bg-zinc-700 text-zinc-200 rounded border border-zinc-700 transition"
|
|
title="Tạm dừng"
|
|
>
|
|
<i data-lucide="pause" className="w-4 h-4"></i>
|
|
</button>
|
|
<button
|
|
onClick={handleStop}
|
|
className="w-8 h-8 flex items-center justify-center bg-zinc-800 hover:bg-zinc-700 text-zinc-200 rounded border border-zinc-700 transition"
|
|
title="Stop & Reset về đầu"
|
|
>
|
|
<i data-lucide="square" className="w-4 h-4 fill-current"></i>
|
|
</button>
|
|
<button
|
|
onClick={() => { if (selRight !== null) setCurrentTime(selRight); }}
|
|
className="w-8 h-8 flex items-center justify-center bg-zinc-800 hover:bg-zinc-700 text-zinc-200 rounded border border-zinc-700 transition"
|
|
title="Đến cuối vùng chọn"
|
|
>
|
|
<i data-lucide="step-forward" className="w-4 h-4"></i>
|
|
</button>
|
|
<button
|
|
onClick={() => setCurrentTime(maxDuration)}
|
|
className="w-8 h-8 flex items-center justify-center bg-zinc-800 hover:bg-zinc-700 text-zinc-200 rounded border border-zinc-700 transition"
|
|
title="Đến cuối track"
|
|
>
|
|
<i data-lucide="skip-forward" className="w-4 h-4"></i>
|
|
</button>
|
|
<button
|
|
onClick={() => setIsLoopingSelection(prev => !prev)}
|
|
className={`w-8 h-8 flex items-center justify-center rounded border transition ${
|
|
isLoopingSelection
|
|
? 'bg-amber-600 text-black border-amber-500 hover:bg-amber-500'
|
|
: 'bg-zinc-800 text-zinc-200 border-zinc-700 hover:bg-zinc-700'
|
|
}`}
|
|
title="Bật/Tắt Lặp vùng chọn (Loop)"
|
|
>
|
|
<i data-lucide="repeat" className="w-4 h-4"></i>
|
|
</button>
|
|
</div>
|
|
</section>
|
|
|
|
{/* OpenAI Compatible AI Engine Section */}
|
|
<section className="md:col-span-4 bg-[#262626] border border-zinc-800 rounded p-3 flex flex-col justify-between">
|
|
<div>
|
|
<h3 className="font-bold text-zinc-200 flex items-center gap-1.5 mb-1">
|
|
<i data-lucide="cpu" className="text-purple-400 w-4 h-4"></i> AI Structural & Cut Engine
|
|
</h3>
|
|
<div className="p-1.5 bg-[#141414] rounded border border-zinc-800 text-[10px] font-mono min-h-[46px] flex flex-col justify-center">
|
|
<div className="text-zinc-500">// Status: <span className="text-zinc-300">{analysisState.status}</span></div>
|
|
{analysisState.data && (
|
|
<div className="text-emerald-500 font-semibold mt-0.5">
|
|
BPM: {analysisState.data.bpm} | Khóa: {analysisState.data.detectedKey} | Đoạn: {analysisState.data.bars} ({analysisState.data.timeSig})
|
|
</div>
|
|
)}
|
|
</div>
|
|
</div>
|
|
|
|
<div className="flex gap-2 mt-1.5">
|
|
<button
|
|
onClick={handleMarkSelection}
|
|
className="flex-1 py-1 px-1 bg-purple-900 hover:bg-purple-800 text-purple-100 font-bold rounded flex items-center justify-center gap-1 border border-purple-700 transition"
|
|
title="Tạo Marker cho Track đang chọn"
|
|
>
|
|
<i data-lucide="map-pin" className="w-3.5 h-3.5"></i> Mark
|
|
</button>
|
|
<button
|
|
onClick={handleAICutToNewTrack}
|
|
disabled={analysisState.isRunning}
|
|
className="flex-[2] py-1 px-1 bg-purple-700 hover:bg-purple-600 text-white font-bold rounded flex items-center justify-center gap-1 transition shadow-md"
|
|
title="AI dò tìm Zero-crossing, Cắt & dán sang Track Mới"
|
|
>
|
|
<i data-lucide="scissors" className="w-3.5 h-3.5"></i> AI Cut & New Track
|
|
</button>
|
|
<button
|
|
onClick={triggerAIAnalysis}
|
|
disabled={analysisState.isRunning}
|
|
className="p-1 bg-zinc-800 hover:bg-zinc-700 text-zinc-300 rounded border border-zinc-700"
|
|
title="Chạy AI Phân Tích Nhịp Toàn Cục"
|
|
>
|
|
<i data-lucide="sparkles" className="w-4 h-4"></i>
|
|
</button>
|
|
</div>
|
|
</section>
|
|
</footer>
|
|
|
|
{/* Bottom Utility Status / Zoom controls */}
|
|
<div className="h-6 bg-[#141414] border-t border-zinc-900 px-4 flex items-center justify-between text-[10px] text-zinc-500 select-none shrink-0">
|
|
<div className="flex items-center gap-4">
|
|
<span>Status: {isPlaying ? 'Playing' : 'Stopped'}</span>
|
|
<span className="text-cyan-400 font-semibold uppercase">Track Đang Chọn: ID {selectedTrackId}</span>
|
|
{soloedTrackId && (
|
|
<span className="text-amber-500 font-semibold">Solo Active: ID {soloedTrackId}</span>
|
|
)}
|
|
</div>
|
|
<div className="flex items-center gap-3">
|
|
<span className="flex items-center gap-1">
|
|
<i data-lucide="info" className="w-3 h-3 text-zinc-600"></i> Mousewheel: Phóng to thu nhỏ
|
|
</span>
|
|
<span>|</span>
|
|
<span className="flex items-center gap-1">
|
|
<i data-lucide="keyboard" className="w-3 h-3 text-zinc-600"></i> Ctrl + Mousewheel: Di chuyển Playhead
|
|
</span>
|
|
</div>
|
|
</div>
|
|
|
|
{/* Toast Notification element */}
|
|
{toastMessage && (
|
|
<div className="absolute top-14 right-4 z-50 px-4 py-2.5 rounded shadow-lg text-xs font-semibold flex items-center gap-2 border bg-zinc-900 text-zinc-100 border-zinc-800">
|
|
<i data-lucide="bell" className={`w-4 h-4 ${
|
|
toastMessage.type === 'success' ? 'text-emerald-400' :
|
|
toastMessage.type === 'error' ? 'text-rose-400' :
|
|
toastMessage.type === 'warning' ? 'text-amber-400' : 'text-cyan-400'
|
|
}`}></i>
|
|
{toastMessage.text}
|
|
</div>
|
|
)}
|
|
</div>
|
|
);
|
|
};
|
|
|
|
const root = ReactDOM.createRoot(document.getElementById('root'));
|
|
root.render(<App />);
|
|
setTimeout(() => lucide.createIcons(), 300);
|
|
</script>
|
|
</body>
|
|
</html> |