Create polished demo videos without editing skills. Mac/Windows/Linux
Revert "feat: Advanced Video Editor Implementation, Native WGC Integration, and AI Auto-Captions"
webadderall20f9259d505c
diff --git a/.gitignore b/.gitignoreindex a817d16a..bc75a52a 100644--- a/.gitignore+++ b/.gitignore@@ -3,32 +3,32 @@ logs*.lognpm-debug.log*yarn-debug.log*-yarn-error.log*-pnpm-debug.log*-lerna-debug.log*--node_modules-dist-dist-electron-dist-ssr-*.local--# Editor directories and files-.vscode/*-!.vscode/extensions.json-.idea-.DS_Store-*.suo-*.ntvs*-*.njsproj-*.sln-*.sw?-release/**-*.kiro/-# npx electron-builder --mac --win-.tmp/-.history/-*.tsbuildinfo+yarn-error.log*+pnpm-debug.log*+lerna-debug.log*++node_modules+dist+dist-electron+dist-ssr+*.local++# Editor directories and files+.vscode/*+!.vscode/extensions.json+.idea+.DS_Store+*.suo+*.ntvs*+*.njsproj+*.sln+*.sw?+release/**+*.kiro/+# npx electron-builder --mac --win+.tmp/+.history/+*.tsbuildinfovite.config.jsvite.config.d.ts@@ -36,12 +36,6 @@ vite.config.d.tselectron/native/wgc-capture/build/electron/native/cursor-monitor/build/-# Local build tools and caches-.cache/-.cmake_ext/-ebcache/-docs/-# Local debug helperstmp-*.ps1.tmp-*.ps1diff --git a/electron-builder.json5 b/electron-builder.json5index 677d0a38..0fd0b26e 100644--- a/electron-builder.json5+++ b/electron-builder.json5@@ -9,7 +9,6 @@"electron/native/**"],"productName": "Recordly",- "copyright": "Copyright (c) 2026 webadderall","npmRebuild": true,"buildDependenciesFromSource": true,"compression": "normal",@@ -63,8 +62,9 @@"target": ["nsis"],- "icon": "icons/icons/win/icon.ico",- "executableName": "Recordly",- "artifactName": "Recordly.${ext}"+ "icon": "icons/icons/win/icon.ico"+ ,+ "artifactName": "Recordly.exe"}-}+}+diff --git a/electron/electron-env.d.ts b/electron/electron-env.d.tsindex a6410fc7..1f570cd8 100644--- a/electron/electron-env.d.ts+++ b/electron/electron-env.d.ts@@ -147,28 +147,23 @@ interface Window {canceled?: boolean;error?: string;}>;- getWhisperModelStatus: (- modelName: string,- ) => Promise<{+ getWhisperSmallModelStatus: () => Promise<{success: boolean;exists: boolean;path?: string | null;error?: string;}>;- downloadWhisperModel: (- modelName: string,- ) => Promise<{+ downloadWhisperSmallModel: () => Promise<{success: boolean;path?: string;alreadyDownloaded?: boolean;error?: string;}>;- deleteWhisperModel: (modelName: string) => Promise<{ success: boolean; error?: string }>;- onWhisperModelDownloadProgress: (+ deleteWhisperSmallModel: () => Promise<{ success: boolean; error?: string }>;+ onWhisperSmallModelDownloadProgress: (callback: (state: {status: "idle" | "downloading" | "downloaded" | "error";progress: number;- model: string;path?: string | null;error?: string;}) => void,@@ -178,11 +173,9 @@ interface Window {whisperExecutablePath?: string;whisperModelPath: string;language?: string;- durationMs?: number;- startTimeMs?: number;}) => Promise<{success: boolean;- cues?: CaptionCue[];+ cues?: AutoCaptionCue[];message?: string;error?: string;}>;@@ -304,8 +297,6 @@ interface Window {startCountdown: (seconds: number) => Promise<{ success: boolean; cancelled?: boolean }>;cancelCountdown: () => Promise<{ success: boolean }>;getActiveCountdown: () => Promise<{ success: boolean; seconds: number | null }>;- onAutoCaptionProgress: (callback: (payload: { progress: number }) => void) => () => void;- onAutoCaptionChunk: (callback: (payload: { cues: CaptionCue[] }) => void) => () => void;onCountdownTick: (callback: (seconds: number) => void) => () => void;};}@@ -347,7 +338,7 @@ interface SystemCursorAsset {height: number;}-interface CaptionCue {+interface AutoCaptionCue {id: string;startMs: number;endMs: number;diff --git a/electron/ipc/handlers.ts b/electron/ipc/handlers.tsindex ee2b4a05..4aea0572 100644--- a/electron/ipc/handlers.ts+++ b/electron/ipc/handlers.ts@@ -30,48 +30,9 @@ const AUTO_RECORDING_RETENTION_COUNT = 20const AUTO_RECORDING_MAX_AGE_MS = 14 * 24 * 60 * 60 * 1000const ALLOW_RECORDLY_WINDOW_CAPTURE = Boolean(process.env['VITE_DEV_SERVER_URL'])const RECORDING_SESSION_MANIFEST_SUFFIX = '.recordly-session.json'-const WHISPER_MODEL_DIR = path.join(app.getPath("userData"), "whisper");--const WHISPER_MODELS = {- tiny: {- label: "Tiny",- size: "75 MB",- filename: "ggml-tiny.bin",- url: "https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-tiny.bin",- },- base: {- label: "Base",- size: "142 MB",- filename: "ggml-base.bin",- url: "https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-base.bin",- },- small: {- label: "Small",- size: "466 MB",- filename: "ggml-small.bin",- url: "https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-small.bin",- },- medium: {- label: "Medium",- size: "1.5 GB",- filename: "ggml-medium.bin",- url: "https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-medium.bin",- },- large: {- label: "Large (v3)",- size: "2.9 GB",- filename: "ggml-large-v3.bin",- url: "https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-large-v3.bin",- },-} as const;--function getWhisperModelPath(modelName: string) {- const model = WHISPER_MODELS[modelName as keyof typeof WHISPER_MODELS];- if (!model) {- throw new Error(`Unsupported Whisper model: ${modelName}`);- }- return path.join(WHISPER_MODEL_DIR, model.filename);-}+const WHISPER_MODEL_DOWNLOAD_URL = 'https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-small.bin'+const WHISPER_MODEL_DIR = path.join(app.getPath('userData'), 'whisper')+const WHISPER_SMALL_MODEL_PATH = path.join(WHISPER_MODEL_DIR, 'ggml-small.bin')function getAssetRootPath() {if (app.isPackaged) {@@ -93,7 +54,9 @@ function normalizeRecordingTimeOffsetMs(value: unknown): number {function broadcastSelectedSourceChange() {for (const window of BrowserWindow.getAllWindows()) {- safeSend(window.webContents, 'selected-source-changed', selectedSource)+ if (!window.isDestroyed()) {+ window.webContents.send('selected-source-changed', selectedSource)+ }}}@@ -989,80 +952,28 @@ function getFfmpegBinaryPath() {return ffmpegStatic}-function runWhisperWithProgress(- executablePath: string,- args: string[],- onProgress: (progress: number) => void,-): Promise<void> {- return new Promise((resolve, reject) => {- const proc = spawn(executablePath, args);- let output = "";-- proc.stdout?.on("data", (data) => {- output += data.toString();- });-- proc.stderr?.on("data", (data) => {- const text = data.toString();- output += text;- // whisper.cpp variants use this pattern on stderr- const match = text.match(/progress\s*=\s*(\d+)%/i);- if (match) {- onProgress(parseInt(match[1], 10));- }- });-- proc.on("close", (code) => {- if (code === 0) {- resolve();- } else {- reject(new Error(output.trim() || `Whisper exited with code ${code}`));- }- });-- proc.on("error", (err) => {- reject(err);- });- });-}--function safeSend(webContents: Electron.WebContents | undefined, channel: string, ...args: any[]) {- if (webContents && !webContents.isDestroyed()) {- webContents.send(channel, ...args)- }-}--type WhisperModelDownloadStatus = {- status: "idle" | "downloading" | "downloaded" | "error";- progress: number;- model: string;- path?: string | null;- error?: string;-}-function sendWhisperModelDownloadProgress(- webContents: Electron.WebContents | undefined,- progress: WhisperModelDownloadStatus,+ webContents: Electron.WebContents,+ payload: { status: 'idle' | 'downloading' | 'downloaded' | 'error'; progress: number; path?: string | null; error?: string },) {- safeSend(webContents, 'whisper-model-download-progress', progress)-}--async function getWhisperModelStatus(_event: any, modelName: string) {- try {- const modelPath = getWhisperModelPath(modelName);- await fs.access(modelPath, fsConstants.R_OK);- return {- success: true,- exists: true,- path: modelPath,- };- } catch {- return {- success: true,- exists: false,- path: null,- };- }+ webContents.send('whisper-small-model-download-progress', payload)+}++async function getWhisperSmallModelStatus() {+ try {+ await fs.access(WHISPER_SMALL_MODEL_PATH, fsConstants.R_OK)+ return {+ success: true,+ exists: true,+ path: WHISPER_SMALL_MODEL_PATH,+ }+ } catch {+ return {+ success: true,+ exists: false,+ path: null,+ }+ }}function downloadFileWithProgress(@@ -1114,9 +1025,7 @@ function downloadFileWithProgress(reject(error)})- // On Windows, the 'finish' event might fire before the OS has fully released the file handle.- // We listen for 'close' to be absolutely sure the file descriptor is closed.- fileStream.on('close', () => {+ fileStream.on('finish', () => {onProgress(100)resolve()})@@ -1131,65 +1040,37 @@ function downloadFileWithProgress(return request(url)}-async function downloadWhisperModel(- webContents: Electron.WebContents,- modelName: string,-) {- const model = WHISPER_MODELS[modelName as keyof typeof WHISPER_MODELS];- if (!model) {- throw new Error(`Unsupported Whisper model: ${modelName}`);- }-- await fs.mkdir(WHISPER_MODEL_DIR, { recursive: true });- const modelPath = getWhisperModelPath(modelName);- const tempPath = `${modelPath}.download`;-- sendWhisperModelDownloadProgress(webContents, {- status: "downloading",- progress: 0,- model: modelName,- path: null,- });+async function downloadWhisperSmallModel(webContents: Electron.WebContents) {+ await fs.mkdir(WHISPER_MODEL_DIR, { recursive: true })+ const tempPath = `${WHISPER_SMALL_MODEL_PATH}.download`++ sendWhisperModelDownloadProgress(webContents, {+ status: 'downloading',+ progress: 0,+ path: null,+ })try {- await fs.rm(tempPath, { force: true }).catch(() => undefined)- await downloadFileWithProgress(model.url, tempPath, (progress) => {+ await fs.rm(tempPath, { force: true })+ await downloadFileWithProgress(WHISPER_MODEL_DOWNLOAD_URL, tempPath, (progress) => {sendWhisperModelDownloadProgress(webContents, {status: 'downloading',progress,- model: modelName,path: null,})})-- // Robust rename logic for Windows to avoid EPERM/EBUSY- let renameRetries = 0- const maxRetries = 5- while (renameRetries < maxRetries) {- try {- await fs.rename(tempPath, modelPath)- break- } catch (err) {- renameRetries++- if (renameRetries >= maxRetries) throw err- // Wait briefly between retries to allow OS to release file handles- await new Promise((resolve) => setTimeout(resolve, 100 * renameRetries))- }- }-+ await fs.rename(tempPath, WHISPER_SMALL_MODEL_PATH)sendWhisperModelDownloadProgress(webContents, {status: 'downloaded',progress: 100,- model: modelName,- path: modelPath,+ path: WHISPER_SMALL_MODEL_PATH,})- return modelPath+ return WHISPER_SMALL_MODEL_PATH} catch (error) {await fs.rm(tempPath, { force: true }).catch(() => undefined)sendWhisperModelDownloadProgress(webContents, {status: 'error',progress: 0,- model: modelName,path: null,error: String(error),})@@ -1197,9 +1078,8 @@ async function downloadWhisperModel(}}-async function deleteWhisperModel(_event: any, modelName: string) {- const modelPath = getWhisperModelPath(modelName);- await fs.rm(modelPath, { force: true });+async function deleteWhisperSmallModel() {+ await fs.rm(WHISPER_SMALL_MODEL_PATH, { force: true })}function parseSrtTimestamp(value: string) {@@ -1488,8 +1368,6 @@ async function extractCaptionAudioSource(options: {videoPath: stringffmpegPath: stringwavPath: string- startTime?: number // in seconds- duration?: number // in seconds}) {const candidates = await resolveCaptionAudioCandidates(options.videoPath)const attemptedCandidates: Array<{@@ -1503,23 +1381,11 @@ async function extractCaptionAudioSource(options: {for (const candidate of candidates) {try {await ensureReadableFile(candidate.path, 'video file')- console.log('[auto-captions] Extracting audio from:', path.basename(candidate.path), options.startTime ? `at ${options.startTime}s` : '')-- const ffmpegArgs = ['-y'];- if (options.startTime !== undefined) {- ffmpegArgs.push('-ss', options.startTime.toString());- }- if (options.duration !== undefined) {- ffmpegArgs.push('-t', options.duration.toString());- }- ffmpegArgs.push('-i', candidate.path, '-map', '0:a:0', '-vn', '-ac', '1', '-ar', '16000', '-c:a', 'pcm_s16le', options.wavPath);-await execFileAsync(options.ffmpegPath,- ffmpegArgs,+ ['-y', '-i', candidate.path, '-map', '0:a:0', '-vn', '-ac', '1', '-ar', '16000', '-c:a', 'pcm_s16le', options.wavPath],{ timeout: 5 * 60 * 1000, maxBuffer: 20 * 1024 * 1024 },)- console.log('[auto-captions] Audio extracted successfully to temporary workspace')attemptedCandidates.push({ ...candidate, readable: true, extractedAudio: true })return candidate} catch (error) {@@ -1533,22 +1399,17 @@ async function extractCaptionAudioSource(options: {}}- console.warn('[auto-captions] No audio source candidate could be extracted')+ console.warn('[auto-captions] No audio source candidate could be extracted:', attemptedCandidates)throw new Error('No audio was found to transcribe in the saved recording file. Captions need an audio track. If this recording should have contained sound, the recording was saved without an audio stream.')}-async function generateAutoCaptionsFromVideo(- webContents: Electron.WebContents,- options: {- videoPath: string;- whisperExecutablePath?: string;- whisperModelPath: string;- language?: string;- durationMs?: number;- startTimeMs?: number;- },-) {+async function generateAutoCaptionsFromVideo(options: {+ videoPath: string+ whisperExecutablePath?: string+ whisperModelPath: string+ language?: string+}) {const ffmpegPath = getFfmpegBinaryPath()const normalizedVideoPath = normalizeVideoSourcePath(options.videoPath)if (!normalizedVideoPath) {@@ -1560,125 +1421,68 @@ async function generateAutoCaptionsFromVideo(await ensureReadableFile(whisperExecutablePath, 'whisper executable')await ensureReadableFile(whisperModelPath, 'whisper model')- // Constants for segmentation- const CHUNK_SIZE_MS = 5 * 60 * 1000; // 5 minutes- const OVERLAP_MS = 10 * 1000; // 10 seconds overlap for word boundaries-- const startTimeMs = options.startTimeMs || 0;- const totalDurationMs = options.durationMs || 0;- const endTimeMs = totalDurationMs > 0 ? startTimeMs + totalDurationMs : Infinity;-- console.log('[auto-captions] Starting segmented caption generation sequence')- console.log('[auto-captions] Video:', path.basename(normalizedVideoPath))- console.log('[auto-captions] Range:', `${(startTimeMs/1000).toFixed(2)}s - ${totalDurationMs ? `${((startTimeMs + totalDurationMs)/1000).toFixed(2)}s` : 'End'}`)-- const allCues: any[] = [];- let audioSourceLabel = 'Unknown';-- for (let offsetMs = startTimeMs; offsetMs < endTimeMs; offsetMs += CHUNK_SIZE_MS) {- const chunkIndex = Math.floor((offsetMs - startTimeMs) / CHUNK_SIZE_MS);- const tempBase = path.join(app.getPath('temp'), `recordly-captions-chunk-${chunkIndex}-${Date.now()}`)- const wavPath = `${tempBase}.wav`- const outputBase = `${tempBase}-whisper`- const srtPath = `${outputBase}.srt`- const jsonPath = `${outputBase}.json`+ const tempBase = path.join(app.getPath('temp'), `recordly-captions-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`)+ const wavPath = `${tempBase}.wav`+ const outputBase = `${tempBase}-whisper`+ const srtPath = `${outputBase}.srt`+ const jsonPath = `${outputBase}.json`- try {-- const audioSource = await extractCaptionAudioSource({- videoPath: normalizedVideoPath,- ffmpegPath,- wavPath,- startTime: offsetMs / 1000,- duration: (CHUNK_SIZE_MS + OVERLAP_MS) / 1000- })- audioSourceLabel = audioSource.label;-- const language = options.language && options.language.trim() ? options.language.trim() : 'auto'- const whisperBaseArgs = [- '-m', whisperModelPath,- '-f', wavPath,- '-osrt',- '-of', outputBase,- '-l', language,- '-np',- ]-- let jsonEnabled = true- const updateChunkProgress = (progress: number) => {- if (totalDurationMs > 0) {- const totalRangeMs = totalDurationMs > 0 ? totalDurationMs : 1;- const rangeOffsetMs = offsetMs - startTimeMs;- const totalProgress = (rangeOffsetMs / totalRangeMs * 100) + (progress / (totalRangeMs / CHUNK_SIZE_MS));- safeSend(webContents, 'auto-caption-progress', { progress: Math.min(99, totalProgress) })- } else {- safeSend(webContents, 'auto-caption-progress', { progress })- }- };-- try {- await runWhisperWithProgress(whisperExecutablePath, [...whisperBaseArgs, '-ojf'], updateChunkProgress)- } catch (error) {- if (!shouldRetryWhisperWithoutJson(error)) throw error- jsonEnabled = false- console.warn(`[auto-captions] Whisper runtime error, retrying with SRT: ${error}`)- await runWhisperWithProgress(whisperExecutablePath, whisperBaseArgs, updateChunkProgress)- }+ try {+ const audioSource = await extractCaptionAudioSource({+ videoPath: normalizedVideoPath,+ ffmpegPath,+ wavPath,+ })- let cues = jsonEnabled- ? parseWhisperJsonCues(await fs.readFile(jsonPath, 'utf-8'))- : parseSrtCues(await fs.readFile(srtPath, 'utf-8'))-- if (cues.length === 0 && !jsonEnabled) {- // If JSON failed, SRT might be empty or not yet read?- try { cues = parseSrtCues(await fs.readFile(srtPath, 'utf-8')); } catch { /* ignore */ }- }+ const language = options.language && options.language.trim() ? options.language.trim() : 'auto'+ const whisperBaseArgs = [+ '-m', whisperModelPath,+ '-f', wavPath,+ '-osrt',+ '-of', outputBase,+ '-l', language,+ '-np',+ ]- // Adjust timings and deduplicate- const adjustedCues = cues- .map((cue, idx) => ({- ...cue,- id: `caption-${offsetMs}-${idx}`,- startMs: cue.startMs + offsetMs,- endMs: cue.endMs + offsetMs- }))- // Only keep cues that START within this chunk's main window (prevent overlap duplicates)- // Except for the very last chunk where we take everything- .filter(cue => {- const isLastChunk = offsetMs + CHUNK_SIZE_MS >= endTimeMs;- if (isLastChunk) return true;- return cue.startMs < offsetMs + CHUNK_SIZE_MS;- });-- if (adjustedCues.length > 0) {- allCues.push(...adjustedCues);- safeSend(webContents, 'auto-caption-chunk', { cues: adjustedCues });+ let jsonEnabled = true+ try {+ await execFileAsync(whisperExecutablePath, [...whisperBaseArgs, '-ojf'], {+ timeout: 30 * 60 * 1000,+ maxBuffer: 20 * 1024 * 1024,+ })+ } catch (error) {+ if (!shouldRetryWhisperWithoutJson(error)) {+ throw error}- // If we don't know duration and this was a short chunk, we might be at the end- // Actually, FFmpeg will just produce a short file if duration is past EOS.- const stats = await fs.stat(wavPath).catch(() => null);- if (stats && stats.size < 1000) { // Tiny audio file means we hit the end- break;- }-- if (offsetMs + CHUNK_SIZE_MS >= endTimeMs) {- break;- }+ jsonEnabled = false+ console.warn('[auto-captions] Whisper runtime does not support JSON full output, retrying with SRT only:', error)+ await execFileAsync(whisperExecutablePath, whisperBaseArgs, {+ timeout: 30 * 60 * 1000,+ maxBuffer: 20 * 1024 * 1024,+ })+ }- } finally {- await Promise.allSettled([- fs.rm(wavPath, { force: true }),- fs.rm(srtPath, { force: true }),- fs.rm(jsonPath, { force: true }),- ])+ const timedCues = jsonEnabled+ ? parseWhisperJsonCues(await fs.readFile(jsonPath, 'utf-8'))+ : []+ const cues = timedCues.length > 0+ ? timedCues+ : parseSrtCues(await fs.readFile(srtPath, 'utf-8'))+ if (cues.length === 0) {+ throw new Error('Whisper completed, but no caption cues were produced.')}- }- safeSend(webContents, 'auto-caption-progress', { progress: 100 })- return {- cues: allCues,- audioSourceLabel,+ return {+ cues,+ audioSourceLabel: audioSource.label,+ }+ } finally {+ await Promise.allSettled([+ fs.rm(wavPath, { force: true }),+ fs.rm(srtPath, { force: true }),+ fs.rm(jsonPath, { force: true }),+ ])}}@@ -1968,7 +1772,7 @@ function attachWindowsCaptureLifecycle(proc: ChildProcessWithoutNullStreams) {const sourceName = selectedSource?.name ?? 'Screen'BrowserWindow.getAllWindows().forEach((window) => {if (!window.isDestroyed()) {- safeSend(window.webContents, 'recording-state-changed', {+ window.webContents.send('recording-state-changed', {recording: false,sourceName,})@@ -2205,7 +2009,7 @@ async function muxNativeMacRecordingWithAudio(function emitRecordingInterrupted(reason: string, message: string) {BrowserWindow.getAllWindows().forEach((window) => {if (!window.isDestroyed()) {- safeSend(window.webContents, 'recording-interrupted', { reason, message })+ window.webContents.send('recording-interrupted', { reason, message })}})}@@ -2213,7 +2017,7 @@ function emitRecordingInterrupted(reason: string, message: string) {function emitCursorStateChanged(cursorType: CursorVisualType) {BrowserWindow.getAllWindows().forEach((window) => {if (!window.isDestroyed()) {- safeSend(window.webContents, 'cursor-state-changed', { cursorType })+ window.webContents.send('cursor-state-changed', { cursorType })}})}@@ -2249,7 +2053,7 @@ function attachNativeCaptureLifecycle(process: ChildProcessWithoutNullStreams) {const sourceName = selectedSource?.name ?? 'Screen'BrowserWindow.getAllWindows().forEach((window) => {if (!window.isDestroyed()) {- safeSend(window.webContents, 'recording-state-changed', {+ window.webContents.send('recording-state-changed', {recording: false,sourceName,})@@ -3229,18 +3033,6 @@ body{background:transparent;overflow:hidden;width:100vw;height:100vh}config.displayId = Number.isFinite(screenId) && screenId > 0? screenId: Number(getScreen().getPrimaryDisplay().id)-- // Include display bounds for more robust matching in the native helper- const allDisplays = getScreen().getAllDisplays()- const display = allDisplays.find((d) => String(d.id) === String(config.displayId))- || getScreen().getPrimaryDisplay()-- if (display) {- config.displayX = Math.round(display.bounds.x)- config.displayY = Math.round(display.bounds.y)- config.displayW = Math.round(display.bounds.width)- config.displayH = Math.round(display.bounds.height)- }}windowsCaptureOutputBuffer = ''@@ -3797,7 +3589,7 @@ body{background:transparent;overflow:hidden;width:100vw;height:100vh}const source = selectedSource || { name: 'Screen' }BrowserWindow.getAllWindows().forEach((window) => {if (!window.isDestroyed()) {- safeSend(window.webContents, 'recording-state-changed', {+ window.webContents.send('recording-state-changed', {recording,sourceName: source.name,})@@ -4139,59 +3931,57 @@ body{background:transparent;overflow:hidden;width:100vw;height:100vh}}})- ipcMain.handle('get-whisper-model-status', async (event, modelName: string) => {+ ipcMain.handle('get-whisper-small-model-status', async () => {try {- return await getWhisperModelStatus(event, modelName)+ return await getWhisperSmallModelStatus()} catch (error) {return { success: false, exists: false, path: null, error: String(error) }}})- ipcMain.handle('download-whisper-model', async (event, modelName: string) => {+ ipcMain.handle('download-whisper-small-model', async (event) => {try {- const existing = await getWhisperModelStatus(event, modelName)+ const existing = await getWhisperSmallModelStatus()if (existing.exists) {sendWhisperModelDownloadProgress(event.sender, {status: 'downloaded',progress: 100,- model: modelName,path: existing.path,})return { success: true, path: existing.path, alreadyDownloaded: true }}- const modelPath = await downloadWhisperModel(event.sender, modelName)+ const modelPath = await downloadWhisperSmallModel(event.sender)return { success: true, path: modelPath }} catch (error) {- console.error(`Failed to download Whisper model ${modelName}:`, error)+ console.error('Failed to download Whisper small model:', error)return { success: false, error: String(error) }}})- ipcMain.handle('delete-whisper-model', async (event, modelName: string) => {+ ipcMain.handle('delete-whisper-small-model', async (event) => {try {- await deleteWhisperModel(event, modelName)+ await deleteWhisperSmallModel()sendWhisperModelDownloadProgress(event.sender, {status: 'idle',progress: 0,- model: modelName,path: null,})return { success: true }} catch (error) {- console.error(`Failed to delete Whisper model ${modelName}:`, error)+ console.error('Failed to delete Whisper small model:', error)return { success: false, error: String(error) }}})- ipcMain.handle('generate-auto-captions', async (event, options: {+ ipcMain.handle('generate-auto-captions', async (_, options: {videoPath: stringwhisperExecutablePath: stringwhisperModelPath: stringlanguage?: string}) => {try {- const result = await generateAutoCaptionsFromVideo(event.sender, options)+ const result = await generateAutoCaptionsFromVideo(options)return {success: true,cues: result.cues,@@ -4614,7 +4404,7 @@ body{background:transparent;overflow:hidden;width:100vw;height:100vh}let remaining = secondscountdownRemaining = remaining- safeSend(countdownWin.webContents, 'countdown-tick', remaining)+ countdownWin.webContents.send('countdown-tick', remaining)countdownTimer = setInterval(() => {if (countdownCancelled) {@@ -4643,11 +4433,9 @@ body{background:transparent;overflow:hidden;width:100vw;height:100vh}resolve({ success: true })} else {const win = getCountdownWindow()- try {- if (win && !win.isDestroyed()) {- safeSend(win.webContents, 'countdown-tick', remaining)- }- } catch {}+ if (win && !win.isDestroyed()) {+ win.webContents.send('countdown-tick', remaining)+ }}}, 1000)})diff --git a/electron/native/bin/win32-x64/whisper-bench.exe b/electron/native/bin/win32-x64/whisper-bench.exedeleted file mode 100644index 0fd3aee9..00000000Binary files a/electron/native/bin/win32-x64/whisper-bench.exe and /dev/null differdiff --git a/electron/native/bin/win32-x64/whisper-cli.exe b/electron/native/bin/win32-x64/whisper-cli.exedeleted file mode 100644index b8d9a673..00000000Binary files a/electron/native/bin/win32-x64/whisper-cli.exe and /dev/null differdiff --git a/electron/native/bin/win32-x64/whisper-quantize.exe b/electron/native/bin/win32-x64/whisper-quantize.exedeleted file mode 100644index 2db4102d..00000000Binary files a/electron/native/bin/win32-x64/whisper-quantize.exe and /dev/null differdiff --git a/electron/native/bin/win32-x64/whisper-runtime.json b/electron/native/bin/win32-x64/whisper-runtime.jsondeleted file mode 100644index 40343aa8..00000000--- a/electron/native/bin/win32-x64/whisper-runtime.json+++ /dev/null@@ -1,6 +0,0 @@-{- "version": "v1.8.4",- "platform": "win32",- "arch": "x64",- "binary": "whisper-cli.exe"-}\ No newline at end of filediff --git a/electron/native/bin/win32-x64/whisper-server.exe b/electron/native/bin/win32-x64/whisper-server.exedeleted file mode 100644index 4615dfbf..00000000Binary files a/electron/native/bin/win32-x64/whisper-server.exe and /dev/null differdiff --git a/electron/native/bin/win32-x64/whisper-vad-speech-segments.exe b/electron/native/bin/win32-x64/whisper-vad-speech-segments.exedeleted file mode 100644index ea02c8aa..00000000Binary files a/electron/native/bin/win32-x64/whisper-vad-speech-segments.exe and /dev/null differdiff --git a/electron/native/wgc-capture/src/main.cpp b/electron/native/wgc-capture/src/main.cppindex 8d69d1c5..dd80bee2 100644--- a/electron/native/wgc-capture/src/main.cpp+++ b/electron/native/wgc-capture/src/main.cpp@@ -33,11 +33,6 @@ struct CaptureConfig {int fps = 60;int width = 0;int height = 0;- int displayX = 0;- int displayY = 0;- int displayW = 0;- int displayH = 0;- bool hasDisplayBounds = false;bool captureSystemAudio = false;bool captureMic = false;};@@ -132,18 +127,6 @@ static bool parseSimpleJson(const std::string& json, CaptureConfig& config) {config.captureSystemAudio = findBool("captureSystemAudio");config.captureMic = findBool("captureMic");- int dx = findInt("displayX");- int dy = findInt("displayY");- int dw = findInt("displayW");- int dh = findInt("displayH");- if (dw > 0 && dh > 0) {- config.displayX = dx;- config.displayY = dy;- config.displayW = dw;- config.displayH = dh;- config.hasDisplayBounds = true;- }-return true;}@@ -215,12 +198,6 @@ int main(int argc, char* argv[]) {}} else {HMONITOR monitor = findMonitorByDisplayId(config.displayId);- if (!monitor && config.hasDisplayBounds) {- std::cerr << "Monitor ID match failed, attempting coordinate-based match: "- << config.displayX << "," << config.displayY << " " << config.displayW << "x" << config.displayH << std::endl;- monitor = findMonitorByBounds(config.displayX, config.displayY, config.displayW, config.displayH);- }-if (!monitor) {std::cerr << "ERROR: Could not find monitor for displayId " << config.displayId << std::endl;return 1;diff --git a/electron/native/wgc-capture/src/monitor_utils.cpp b/electron/native/wgc-capture/src/monitor_utils.cppindex c4fe0739..e6b0d03d 100644--- a/electron/native/wgc-capture/src/monitor_utils.cpp+++ b/electron/native/wgc-capture/src/monitor_utils.cpp@@ -1,6 +1,5 @@#include "monitor_utils.h"#include <ShellScalingApi.h>-#include <iostream>static BOOL CALLBACK enumMonitorCallback(HMONITOR hMonitor, HDC, LPRECT, LPARAM lParam) {auto* monitors = reinterpret_cast<std::vector<MonitorInfo>*>(lParam);@@ -27,56 +26,16 @@ std::vector<MonitorInfo> enumerateMonitors() {return monitors;}-static std::string wstringToString(const std::wstring& wstr) {- if (wstr.empty()) return "";- int size_needed = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), (int)wstr.size(), NULL, 0, NULL, NULL);- std::string str(size_needed, 0);- WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), (int)wstr.size(), &str[0], size_needed, NULL, NULL);- return str;-}-// Electron uses the HMONITOR handle value cast to a number as the display ID.HMONITOR findMonitorByDisplayId(int64_t displayId) {auto monitors = enumerateMonitors();- // Try exact match firstfor (const auto& m : monitors) {if (static_cast<int64_t>(reinterpret_cast<intptr_t>(m.handle)) == displayId) {return m.handle;}}- // No exact ID match found. Return nullptr to allow main.cpp to try coordinate-based matching.- return nullptr;-}--HMONITOR findMonitorByBounds(int x, int y, int width, int height) {- auto monitors = enumerateMonitors();-- // 1. Try exact bounds match- for (const auto& m : monitors) {- if (m.x == x && m.y == y && m.width == width && m.height == height) {- std::cerr << "Found monitor by exact bounds: " << x << "," << y << " " << width << "x" << height << std::endl;- return m.handle;- }- }-- // 2. Try matching top-left point (sometimes size differs due to DPI scaling, but top-left is usually more stable in screen-space)- for (const auto& m : monitors) {- if (m.x == x && m.y == y) {- std::cerr << "Found monitor by top-left point match: " << x << "," << y << std::endl;- return m.handle;- }- }-- // 3. Last resort: MonitorFromRect/Point (OS choice for the best matching monitor for these coordinates)- RECT rect = { x, y, x + width, y + height };- HMONITOR hMonitor = MonitorFromRect(&rect, MONITOR_DEFAULTTONULL);- if (hMonitor) {- std::cerr << "Found monitor via Windows OS MonitorFromRect fallback" << std::endl;- return hMonitor;- }-return nullptr;}diff --git a/electron/native/wgc-capture/src/monitor_utils.h b/electron/native/wgc-capture/src/monitor_utils.hindex 90f3ac39..8889410d 100644--- a/electron/native/wgc-capture/src/monitor_utils.h+++ b/electron/native/wgc-capture/src/monitor_utils.h@@ -16,5 +16,4 @@ struct MonitorInfo {std::vector<MonitorInfo> enumerateMonitors();HMONITOR findMonitorByDisplayId(int64_t displayId);-HMONITOR findMonitorByBounds(int x, int y, int width, int height);MonitorInfo getMonitorInfo(HMONITOR monitor);diff --git a/electron/preload.ts b/electron/preload.tsindex 462cdb5f..638511d0 100644--- a/electron/preload.ts+++ b/electron/preload.ts@@ -164,36 +164,24 @@ contextBridge.exposeInMainWorld("electronAPI", {openWhisperModelPicker: () => {return ipcRenderer.invoke("open-whisper-model-picker");},- getWhisperModelStatus: (modelName: string) => {- return ipcRenderer.invoke("get-whisper-model-status", modelName);- },- downloadWhisperModel: (modelName: string) => {- return ipcRenderer.invoke("download-whisper-model", modelName);- },- deleteWhisperModel: (modelName: string) => {- return ipcRenderer.invoke("delete-whisper-model", modelName);- },- onWhisperModelDownloadProgress: (- callback: (state: {- status: "idle" | "downloading" | "downloaded" | "error";- progress: number;- model: string;- path?: string | null;- error?: string;- }) => void,+ getWhisperSmallModelStatus: () => {+ return ipcRenderer.invoke("get-whisper-small-model-status");+ },+ downloadWhisperSmallModel: () => {+ return ipcRenderer.invoke("download-whisper-small-model");+ },+ deleteWhisperSmallModel: () => {+ return ipcRenderer.invoke("delete-whisper-small-model");+ },+ onWhisperSmallModelDownloadProgress: (+ callback: (state: { status: "idle" | "downloading" | "downloaded" | "error"; progress: number; path?: string | null; error?: string }) => void,) => {const listener = (_event: Electron.IpcRendererEvent,- payload: {- status: "idle" | "downloading" | "downloaded" | "error";- progress: number;- model: string;- path?: string | null;- error?: string;- },+ payload: { status: "idle" | "downloading" | "downloaded" | "error"; progress: number; path?: string | null; error?: string },) => callback(payload);- ipcRenderer.on("whisper-model-download-progress", listener);- return () => ipcRenderer.removeListener("whisper-model-download-progress", listener);+ ipcRenderer.on("whisper-small-model-download-progress", listener);+ return () => ipcRenderer.removeListener("whisper-small-model-download-progress", listener);},generateAutoCaptions: (options: {videoPath: string;@@ -203,18 +191,6 @@ contextBridge.exposeInMainWorld("electronAPI", {}) => {return ipcRenderer.invoke("generate-auto-captions", options);},- onAutoCaptionProgress: (callback: (payload: { progress: number }) => void) => {- const listener = (_event: Electron.IpcRendererEvent, payload: { progress: number }) =>- callback(payload);- ipcRenderer.on("auto-caption-progress", listener);- return () => ipcRenderer.removeListener("auto-caption-progress", listener);- },- onAutoCaptionChunk: (callback: (payload: { cues: CaptionCue[] }) => void) => {- const listener = (_event: Electron.IpcRendererEvent, payload: { cues: CaptionCue[] }) =>- callback(payload);- ipcRenderer.on("auto-caption-chunk", listener);- return () => ipcRenderer.removeListener("auto-caption-chunk", listener);- },setCurrentVideoPath: (path: string) => {return ipcRenderer.invoke("set-current-video-path", path);},diff --git a/electron/windows.ts b/electron/windows.tsindex a9904667..cb265237 100644--- a/electron/windows.ts+++ b/electron/windows.ts@@ -246,9 +246,7 @@ export function createHudOverlayWindow(): BrowserWindow {}win.webContents.on("did-finish-load", () => {- if (!win.isDestroyed()) {- win.webContents.send("main-process-message", new Date().toLocaleString());- }+ win?.webContents.send("main-process-message", new Date().toLocaleString());setTimeout(() => {if (!win.isDestroyed()) {win.show();@@ -312,9 +310,7 @@ export function createEditorWindow(): BrowserWindow {});win.webContents.on("did-finish-load", () => {- if (!win.isDestroyed()) {- win.webContents.send("main-process-message", new Date().toLocaleString());- }+ win?.webContents.send("main-process-message", new Date().toLocaleString());});if (VITE_DEV_SERVER_URL) {diff --git a/package.json b/package.jsonindex 124d9a16..6bba3611 100644--- a/package.json+++ b/package.json@@ -20,7 +20,6 @@"build": "npm run build:platform-native-helpers && tsc && vite build && electron-builder","lint": "biome check .","lint:fix": "biome check --write .",- "typecheck": "tsc --noEmit","format": "biome format --write .","preview": "vite preview","rebuild:native": "node ./node_modules/electron-rebuild/lib/src/cli.js --force --only uiohook-napi",@@ -105,4 +104,4 @@"web-demuxer": "^4.0.0"},"main": "dist-electron/main.js"-}\ No newline at end of file+}diff --git a/scripts/build-cursor-monitor.mjs b/scripts/build-cursor-monitor.mjsindex df973241..5b7409f1 100644--- a/scripts/build-cursor-monitor.mjs+++ b/scripts/build-cursor-monitor.mjs@@ -25,13 +25,6 @@ function findCmake() {// not on PATH}- // Local .cmake_ext path- const localCmake = path.join(projectRoot, ".cmake_ext", "cmake-4.3.0-windows-x86_64", "bin", "cmake.exe");- if (existsSync(localCmake)) {- return `"${localCmake}"`;- }-- // Standalone CMake pathsconst standaloneCmakePaths = [path.join("C:", "Program Files", "CMake", "bin", "cmake.exe"),path.join("C:", "Program Files (x86)", "CMake", "bin", "cmake.exe"),@@ -42,7 +35,7 @@ function findCmake() {}}- // VS 2022/2019 bundled CMake+ // VS 2022 bundled CMakeconst vsRoots = [path.join("C:", "Program Files", "Microsoft Visual Studio"),path.join("C:", "Program Files (x86)", "Microsoft Visual Studio"),diff --git a/scripts/build-whisper-runtime.mjs b/scripts/build-whisper-runtime.mjsindex 1c284a4a..0bdf9dd8 100644--- a/scripts/build-whisper-runtime.mjs+++ b/scripts/build-whisper-runtime.mjs@@ -137,12 +137,6 @@ function findCmake() {}if (process.platform === "win32") {- // Local .cmake_ext path- const localCmake = path.join(projectRoot, ".cmake_ext", "cmake-4.3.0-windows-x86_64", "bin", "cmake.exe");- if (existsSync(localCmake)) {- return localCmake;- }-const vsEditions = ["Community", "Professional", "Enterprise", "BuildTools"];for (const edition of vsEditions) {const cmakePath = path.join(@@ -242,7 +236,7 @@ async function ensureSourceTree() {}ensureTarAvailable();- execFileSync("tar", ["-xzf", path.relative(projectRoot, archivePath), "-C", path.relative(projectRoot, extractRoot)], { stdio: "inherit" });+ execFileSync("tar", ["-xzf", archivePath, "-C", extractRoot], { stdio: "inherit" });if (!existsSync(path.join(extractedSourceDir, "CMakeLists.txt"))) {throw new Error(diff --git a/scripts/build-windows-capture.mjs b/scripts/build-windows-capture.mjsindex 8df2c6e3..3cc3dcfc 100644--- a/scripts/build-windows-capture.mjs+++ b/scripts/build-windows-capture.mjs@@ -1,136 +1,127 @@-import { execSync } from "node:child_process";-import { mkdirSync, existsSync, rmSync } from "node:fs";-import path from "node:path";+import { execSync } from 'node:child_process';+import { mkdirSync, existsSync, rmSync } from 'node:fs';+import path from 'node:path';const projectRoot = process.cwd();-const sourceDir = path.join(projectRoot, "electron", "native", "wgc-capture");-const buildDir = path.join(sourceDir, "build");+const sourceDir = path.join(projectRoot, 'electron', 'native', 'wgc-capture');+const buildDir = path.join(sourceDir, 'build');-if (process.platform !== "win32") {- console.log("[build-windows-capture] Skipping native Windows capture build: host platform is not Windows.");- process.exit(0);+if (process.platform !== 'win32') {+ console.log('[build-windows-capture] Skipping native Windows capture build: host platform is not Windows.');+ process.exit(0);}-if (!existsSync(path.join(sourceDir, "CMakeLists.txt"))) {- console.error("[build-windows-capture] CMakeLists.txt not found at", sourceDir);- process.exit(1);+if (!existsSync(path.join(sourceDir, 'CMakeLists.txt'))) {+ console.error('[build-windows-capture] CMakeLists.txt not found at', sourceDir);+ process.exit(1);}function findCmake() {- // Check PATH first- try {- execSync("cmake --version", { stdio: "pipe" });- return "cmake";- } catch {- // not on PATH- }+ // Check PATH first+ try {+ execSync('cmake --version', { stdio: 'pipe' });+ return 'cmake';+ } catch {+ // not on PATH+ }- // Local .cmake_ext path- const localCmake = path.join(projectRoot, ".cmake_ext", "cmake-4.3.0-windows-x86_64", "bin", "cmake.exe");- if (existsSync(localCmake)) {- return `"${localCmake}"`;- }+ const standaloneCmakePaths = [+ path.join('C:', 'Program Files', 'CMake', 'bin', 'cmake.exe'),+ path.join('C:', 'Program Files (x86)', 'CMake', 'bin', 'cmake.exe'),+ ];+ for (const cmakePath of standaloneCmakePaths) {+ if (existsSync(cmakePath)) {+ return `"${cmakePath}"`;+ }+ }- // Standalone CMake paths- const standaloneCmakePaths = [- path.join("C:", "Program Files", "CMake", "bin", "cmake.exe"),- path.join("C:", "Program Files (x86)", "CMake", "bin", "cmake.exe"),- ];- for (const cmakePath of standaloneCmakePaths) {- if (existsSync(cmakePath)) {- return `"${cmakePath}"`;- }- }+ // VS 2022 bundled CMake+ const vsRoots = [+ path.join('C:', 'Program Files', 'Microsoft Visual Studio'),+ path.join('C:', 'Program Files (x86)', 'Microsoft Visual Studio'),+ ];+ const vsEditions = ['Community', 'Professional', 'Enterprise', 'BuildTools'];+ const vsVersions = ['2022', '2019'];+ for (const root of vsRoots) {+ for (const version of vsVersions) {+ for (const edition of vsEditions) {+ const cmakePath = path.join(+ root,+ version,+ edition,+ 'Common7',+ 'IDE',+ 'CommonExtensions',+ 'Microsoft',+ 'CMake',+ 'CMake',+ 'bin',+ 'cmake.exe'+ );+ if (existsSync(cmakePath)) {+ return `"${cmakePath}"`;+ }+ }+ }+ }- // VS 2022/2019 bundled CMake- const vsRoots = [- path.join("C:", "Program Files", "Microsoft Visual Studio"),- path.join("C:", "Program Files (x86)", "Microsoft Visual Studio"),- ];- const vsEditions = ["Community", "Professional", "Enterprise", "BuildTools"];- const vsVersions = ["2022", "2019"];- for (const root of vsRoots) {- for (const version of vsVersions) {- for (const edition of vsEditions) {- const cmakePath = path.join(- root,- version,- edition,- "Common7",- "IDE",- "CommonExtensions",- "Microsoft",- "CMake",- "CMake",- "bin",- "cmake.exe",- );- if (existsSync(cmakePath)) {- return `"${cmakePath}"`;- }- }- }- }-- return null;+ return null;}const cmake = findCmake();if (!cmake) {- console.error(- "[build-windows-capture] CMake not found. Install Visual Studio with C++ CMake tools or standalone CMake.",- );- process.exit(1);+ console.error('[build-windows-capture] CMake not found. Install Visual Studio with C++ CMake tools or standalone CMake.');+ process.exit(1);}mkdirSync(buildDir, { recursive: true });-const cacheFile = path.join(buildDir, "CMakeCache.txt");-const cacheDir = path.join(buildDir, "CMakeFiles");+const cacheFile = path.join(buildDir, 'CMakeCache.txt');+const cacheDir = path.join(buildDir, 'CMakeFiles');function clearCmakeCache() {- rmSync(cacheFile, { force: true });- rmSync(cacheDir, { recursive: true, force: true });+ rmSync(cacheFile, { force: true });+ rmSync(cacheDir, { recursive: true, force: true });}-console.log("[build-windows-capture] Configuring CMake...");+console.log('[build-windows-capture] Configuring CMake...');try {- clearCmakeCache();- execSync(`${cmake} .. -G "Visual Studio 17 2022" -A x64`, {- cwd: buildDir,- stdio: "inherit",- timeout: 120000,- });+ clearCmakeCache();+ execSync(`${cmake} .. -G "Visual Studio 17 2022" -A x64`, {+ cwd: buildDir,+ stdio: 'inherit',+ timeout: 120000,+ });} catch {- console.log("[build-windows-capture] VS 2022 generator not found, trying VS 2019...");- try {- clearCmakeCache();- execSync(`${cmake} .. -G "Visual Studio 16 2019" -A x64`, {- cwd: buildDir,- stdio: "inherit",- timeout: 120000,- });- } catch (innerError) {- console.error("[build-windows-capture] CMake configure failed:", innerError.message);- process.exit(1);- }+ console.log('[build-windows-capture] VS 2022 generator not found, trying VS 2019...');+ try {+ clearCmakeCache();+ execSync(`${cmake} .. -G "Visual Studio 16 2019" -A x64`, {+ cwd: buildDir,+ stdio: 'inherit',+ timeout: 120000,+ });+ } catch (innerError) {+ console.error('[build-windows-capture] CMake configure failed:', innerError.message);+ process.exit(1);+ }}-console.log("[build-windows-capture] Building native Windows capture helper...");+console.log('[build-windows-capture] Building native Windows capture helper...');try {- execSync(`${cmake} --build . --config Release`, {- cwd: buildDir,- stdio: "inherit",- timeout: 300000,- });+ execSync(`${cmake} --build . --config Release`, {+ cwd: buildDir,+ stdio: 'inherit',+ timeout: 300000,+ });} catch (error) {- console.error("[build-windows-capture] Build failed:", error.message);- process.exit(1);+ console.error('[build-windows-capture] Build failed:', error.message);+ process.exit(1);}-const exePath = path.join(buildDir, "Release", "wgc-capture.exe");+const exePath = path.join(buildDir, 'Release', 'wgc-capture.exe');if (existsSync(exePath)) {- console.log(`[build-windows-capture] Built successfully: ${exePath}`);+ console.log(`[build-windows-capture] Built successfully: ${exePath}`);} else {- console.error("[build-windows-capture] Expected exe not found at", exePath);- process.exit(1);+ console.error('[build-windows-capture] Expected exe not found at', exePath);+ process.exit(1);}diff --git a/src/components/video-editor/AnnotationOverlay.tsx b/src/components/video-editor/AnnotationOverlay.tsxindex 921908a8..3260a542 100644--- a/src/components/video-editor/AnnotationOverlay.tsx+++ b/src/components/video-editor/AnnotationOverlay.tsx@@ -111,17 +111,6 @@ export function AnnotationOverlay({</div>);- case 'blur':- return (- <div- className="w-full h-full rounded-lg backdrop-blur-md"- style={{- backdropFilter: `blur(${annotation.blurIntensity ?? 12}px)`,- WebkitBackdropFilter: `blur(${annotation.blurIntensity ?? 12}px)`- }}- />- );-default:return null;}@@ -219,7 +208,6 @@ export function AnnotationOverlay({annotation.type === 'text' && "bg-transparent",annotation.type === 'image' && "bg-transparent",annotation.type === 'figure' && "bg-transparent",- annotation.type === 'blur' && "bg-transparent",isSelected && "shadow-lg")}>diff --git a/src/components/video-editor/AnnotationSettingsPanel.tsx b/src/components/video-editor/AnnotationSettingsPanel.tsxindex b24cd228..2cddf970 100644--- a/src/components/video-editor/AnnotationSettingsPanel.tsx+++ b/src/components/video-editor/AnnotationSettingsPanel.tsx@@ -1,10 +1,10 @@import { useRef, useState, useEffect, useMemo } from "react";import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";import { Button } from "@/components/ui/button";-import { Trash2, Type, Image as ImageIcon, Upload, Bold, Italic, Underline, AlignLeft, AlignCenter, AlignRight, ChevronDown, Info, Droplets } from "lucide-react";+import { Trash2, Type, Image as ImageIcon, Upload, Bold, Italic, Underline, AlignLeft, AlignCenter, AlignRight, ChevronDown, Info } from "lucide-react";import { toast } from "sonner";import Block from '@uiw/react-color-block';-import { DEFAULT_BLUR_INTENSITY, type AnnotationRegion, type AnnotationType, type ArrowDirection, type FigureData } from "./types";+import type { AnnotationRegion, AnnotationType, ArrowDirection, FigureData } from "./types";import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";@@ -21,7 +21,6 @@ interface AnnotationSettingsPanelProps {onTypeChange: (type: AnnotationType) => void;onStyleChange: (style: Partial<AnnotationRegion['style']>) => void;onFigureDataChange?: (figureData: FigureData) => void;- onBlurIntensityChange?: (intensity: number) => void;onDelete: () => void;}@@ -44,7 +43,6 @@ export function AnnotationSettingsPanel({onTypeChange,onStyleChange,onFigureDataChange,- onBlurIntensityChange,onDelete,}: AnnotationSettingsPanelProps) {const t = useScopedT('editor');@@ -130,7 +128,7 @@ export function AnnotationSettingsPanel({{/* Type Selector */}<Tabs value={annotation.type} onValueChange={(value) => onTypeChange(value as AnnotationType)} className="mb-6">- <TabsList className="mb-4 bg-white/5 border border-white/5 p-1 w-full grid grid-cols-4 h-auto rounded-xl">+ <TabsList className="mb-4 bg-white/5 border border-white/5 p-1 w-full grid grid-cols-3 h-auto rounded-xl"><TabsTrigger value="text" className="data-[state=active]:bg-[#2563EB] data-[state=active]:text-white text-slate-400 py-2 rounded-lg transition-all gap-2"><Type className="w-4 h-4" />{t('annotations.text')}@@ -145,32 +143,8 @@ export function AnnotationSettingsPanel({</svg>{t('annotations.arrow')}</TabsTrigger>- <TabsTrigger value="blur" className="data-[state=active]:bg-[#2563EB] data-[state=active]:text-white text-slate-400 py-2 rounded-lg transition-all gap-2">- <Droplets className="w-4 h-4" />- Blur- </TabsTrigger></TabsList>- <TabsContent value="blur" className="mt-0 space-y-4">- <div>- <label className="text-xs font-medium text-slate-200 mb-2 block">- Blur Intensity: {annotation.blurIntensity ?? DEFAULT_BLUR_INTENSITY}px- </label>- <Slider- value={[annotation.blurIntensity ?? DEFAULT_BLUR_INTENSITY]}- onValueChange={([value]) => {- if (onBlurIntensityChange) {- onBlurIntensityChange(value);- }- }}- min={2}- max={50}- step={1}- className="w-full"- />- </div>- </TabsContent>-{/* Text Content */}<TabsContent value="text" className="mt-0 space-y-4"><div>diff --git a/src/components/video-editor/AudioSettingsPanel.tsx b/src/components/video-editor/AudioSettingsPanel.tsxdeleted file mode 100644index da1b7c06..00000000--- a/src/components/video-editor/AudioSettingsPanel.tsx+++ /dev/null@@ -1,221 +0,0 @@-import { Volume2, VolumeX, Trash2, Music } from "lucide-react";-import { Button } from "@/components/ui/button";-import { Slider } from "@/components/ui/slider";-import { cn } from "@/lib/utils";-import { generateWaveform } from "@/utils/audioWaveform";-import { useEffect, useState } from "react";-import type { AudioRegion } from "./types";--interface AudioSettingsPanelProps {- audio: AudioRegion;- onVolumeChange: (volume: number) => void;- onMutedChange: (muted: boolean) => void;- onSoloedChange: (soloed: boolean) => void;- onFadeInMsChange: (ms: number) => void;- onFadeOutMsChange: (ms: number) => void;- onDelete: () => void;-}--function formatFadeTime(ms: number): string {- if (ms === 0) return "Off";- if (ms < 1000) return `${ms}ms`;- return `${(ms / 1000).toFixed(1)}s`;-}--export function AudioSettingsPanel({- audio,- onVolumeChange,- onMutedChange,- onSoloedChange,- onFadeInMsChange,- onFadeOutMsChange,- onDelete,-}: AudioSettingsPanelProps) {- const [waveform, setWaveform] = useState<number[] | null>(null);-- useEffect(() => {- let active = true;- if (audio.audioPath) {- generateWaveform(audio.audioPath, 120).then(result => {- if (active) setWaveform(result);- });- }- return () => { active = false; };- }, [audio.audioPath]);-- const clipDurationMs = audio.endMs - audio.startMs;- const maxFadeMs = Math.max(0, Math.floor(clipDurationMs / 2));- const volumePct = Math.round(audio.volume * 100);- const isMaster = audio.id === "master";-- // Mute and Solo are mutually exclusive- const handleMuteToggle = () => {- const nextMuted = !audio.muted;- onMutedChange(nextMuted);- if (nextMuted && audio.soloed) onSoloedChange(false);- };-- const handleSoloToggle = () => {- const nextSoloed = !audio.soloed;- onSoloedChange(nextSoloed);- if (nextSoloed && audio.muted) onMutedChange(false);- };-- return (- <section className="flex flex-col gap-3 pb-4">- {/* Header */}- <div className="flex items-center justify-between gap-2 pb-1">- <div className="flex items-center gap-2">- <div className="p-1.5 rounded-lg bg-purple-500/10 text-purple-400 shrink-0">- <Music className="w-3.5 h-3.5" />- </div>- <div>- <p className="text-sm font-semibold text-slate-100 leading-none">- {isMaster ? "Original Audio" : "Audio Region"}- </p>- {!isMaster && (- <p className="text-[10px] text-slate-500 mt-0.5 truncate max-w-[160px]">- {audio.audioPath.split(/[\\/]/).pop()}- </p>- )}- {isMaster && (- <p className="text-[10px] text-slate-500 mt-0.5">- Adjust the volume of the video's audio- </p>- )}- </div>- </div>- <span className="text-[9px] uppercase tracking-widest font-semibold text-[#2563EB] bg-[#2563EB]/10 px-2 py-1 rounded-full shrink-0">- Active- </span>- </div>-- {/* Waveform — only for audio regions with a dedicated audio path */}- {waveform && !isMaster && (- <div className="h-10 bg-white/[0.03] rounded-xl border border-white/5 flex items-center overflow-hidden relative">- <div className="absolute inset-0 flex items-center pointer-events-none px-2">- <svg- width="100%"- height="100%"- viewBox={`0 0 ${waveform.length} 100`}- preserveAspectRatio="none"- className="text-purple-400 opacity-50"- >- {waveform.map((peak, i) => (- <rect- key={i}- x={i}- y={50 - peak * 50}- width={0.8}- height={peak * 100}- fill="currentColor"- rx={0.2}- />- ))}- </svg>- </div>- </div>- )}-- {/* Mute / Solo — only for audio regions, not master */}- {!isMaster && (- <div className="grid grid-cols-2 gap-2">- <button- type="button"- onClick={handleMuteToggle}- className={cn(- "flex items-center gap-2 px-3 py-2 rounded-xl border text-xs font-medium transition-all",- audio.muted- ? "bg-red-500/15 border-red-500/30 text-red-400"- : "bg-white/[0.03] border-white/[0.08] text-slate-400 hover:bg-white/[0.06] hover:text-slate-200"- )}- >- <VolumeX className="w-3.5 h-3.5 shrink-0" />- <span>Mute</span>- </button>- <button- type="button"- onClick={handleSoloToggle}- className={cn(- "flex items-center gap-2 px-3 py-2 rounded-xl border text-xs font-medium transition-all",- audio.soloed- ? "bg-amber-500/15 border-amber-500/30 text-amber-400"- : "bg-white/[0.03] border-white/[0.08] text-slate-400 hover:bg-white/[0.06] hover:text-slate-200"- )}- >- <span className="text-[11px] font-bold w-3.5 text-center shrink-0">S</span>- <span>Solo</span>- </button>- </div>- )}-- {/* Volume */}- <div className="rounded-xl bg-white/[0.03] border border-white/5 px-3 py-2.5 space-y-3">- <div className="flex items-center justify-between">- <div className="flex items-center gap-1.5">- <Volume2 className="w-3.5 h-3.5 text-slate-500" />- <span className="text-xs font-medium text-slate-300">Volume</span>- </div>- <span- className={cn(- "text-[11px] tabular-nums font-semibold px-1.5 py-0.5 rounded-md",- volumePct > 100- ? "text-amber-400 bg-amber-500/10"- : "text-[#2563EB] bg-[#2563EB]/10"- )}- >- {volumePct}%- </span>- </div>- <Slider- value={[audio.volume * 100]}- onValueChange={([value]) => onVolumeChange(value / 100)}- min={0}- max={200}- step={1}- />- {volumePct > 100 && (- <p className="text-[10px] text-amber-500/70 leading-snug">- Amplifying above 100% may clip the audio.- </p>- )}- </div>-- {/* Fades — only for audio regions */}- {!isMaster && (- <div className="rounded-xl bg-white/[0.03] border border-white/5 px-3 py-2.5 space-y-3">- <span className="text-xs font-medium text-slate-300">Fades</span>- <div className="grid grid-cols-2 gap-x-4 gap-y-3">- <div className="space-y-2">- <div className="flex items-center justify-between">- <span className="text-[10px] text-slate-500 uppercase tracking-wider font-semibold">Fade In</span>- <span className="text-[10px] tabular-nums text-slate-400 font-medium">{formatFadeTime(audio.fadeInMs || 0)}</span>- </div>- <Slider value={[audio.fadeInMs || 0]} onValueChange={([v]) => onFadeInMsChange(v)} min={0} max={maxFadeMs} step={50} />- </div>- <div className="space-y-2">- <div className="flex items-center justify-between">- <span className="text-[10px] text-slate-500 uppercase tracking-wider font-semibold">Fade Out</span>- <span className="text-[10px] tabular-nums text-slate-400 font-medium">{formatFadeTime(audio.fadeOutMs || 0)}</span>- </div>- <Slider value={[audio.fadeOutMs || 0]} onValueChange={([v]) => onFadeOutMsChange(v)} min={0} max={maxFadeMs} step={50} />- </div>- </div>- </div>- )}-- {/* Delete — only for audio regions */}- {!isMaster && (- <Button- onClick={onDelete}- variant="ghost"- size="sm"- className="w-full gap-2 text-red-400/70 hover:text-red-400 hover:bg-red-500/10 border border-transparent hover:border-red-500/20 transition-all mt-1"- >- <Trash2 className="w-3.5 h-3.5" />- Remove Audio Region- </Button>- )}- </section>- );-}diff --git a/src/components/video-editor/SettingsPanel.tsx b/src/components/video-editor/SettingsPanel.tsxindex b5fdd118..d0b2d656 100644--- a/src/components/video-editor/SettingsPanel.tsx+++ b/src/components/video-editor/SettingsPanel.tsx@@ -1,4 +1,4 @@-import { MessageSquare, Music, Palette, Trash2, Upload, X } from "lucide-react";+import { Palette, Trash2, Upload, X } from "lucide-react";import { AnimatePresence, LayoutGroup, motion } from "motion/react";import { useEffect, useMemo, useRef, useState } from "react";import { toast } from "sonner";@@ -26,13 +26,11 @@ import parchedCursorUrl from "../../assets/cursors/parched/default.png";import turtleCursorUrl from "../../assets/cursors/turtle/default.png";import { useI18n, useScopedT } from "../../contexts/I18nContext";import { AnnotationSettingsPanel } from "./AnnotationSettingsPanel";-import { AudioSettingsPanel } from "./AudioSettingsPanel";import { loadEditorPreferences, saveEditorPreferences } from "./editorPreferences";import { SliderControl } from "./SliderControl";import type {AnnotationRegion,AnnotationType,- AudioRegion,AutoCaptionAnimation,AutoCaptionSettings,CaptionCue,@@ -113,7 +111,6 @@ export type EditorEffectSection =| "cursor"| "captions"| "webcam"- | "audio"| "zoom"| "frame"| "crop";@@ -211,13 +208,8 @@ interface SettingsPanelProps {onAnnotationTypeChange?: (id: string, type: AnnotationType) => void;onAnnotationStyleChange?: (id: string, style: Partial<AnnotationRegion["style"]>) => void;onAnnotationFigureDataChange?: (id: string, figureData: FigureData) => void;- onAnnotationBlurIntensityChange?: (id: string, blurIntensity: number) => void;onAnnotationDelete?: (id: string) => void;- onSeek?: (time: number) => void;autoCaptions?: CaptionCue[];- onAutoCaptionsChange?: (captions: CaptionCue[]) => void;- selectedCaptionId?: string | null;- onSelectCaption?: (id: string | null) => void;autoCaptionSettings?: AutoCaptionSettings;whisperExecutablePath?: string | null;whisperModelPath?: string | null;@@ -229,31 +221,12 @@ interface SettingsPanelProps {onPickWhisperModel?: () => void;onGenerateAutoCaptions?: () => void;onClearAutoCaptions?: () => void;- autoCaptionProgress?: number;- onDownloadWhisperModel?: () => void;- onDeleteWhisperModel?: () => void;+ onDownloadWhisperSmallModel?: () => void;+ onDeleteWhisperSmallModel?: () => void;selectedSpeedId?: string | null;selectedSpeedValue?: PlaybackSpeed | null;onSpeedChange?: (speed: PlaybackSpeed) => void;onSpeedDelete?: (id: string) => void;- audioRegions?: AudioRegion[];- selectedAudioId?: string | null;- onAudioVolumeChange?: (id: string, volume: number) => void;- onAudioMutedChange?: (id: string, muted: boolean) => void;- onAudioSoloedChange?: (id: string, soloed: boolean) => void;- onAudioFadeInMsChange?: (id: string, ms: number) => void;- onAudioFadeOutMsChange?: (id: string, ms: number) => void;- onAudioDelete?: (id: string) => void;- timeSelection?: { startMs: number; endMs: number } | null;- isMasterSelected?: boolean;- masterAudioVolume?: number;- masterAudioMuted?: boolean;- masterAudioSoloed?: boolean;- videoDuration?: number;- videoPath?: string;- onMasterAudioVolumeChange?: (volume: number) => void;- onMasterAudioMutedChange?: (muted: boolean) => void;- onMasterAudioSoloedChange?: (soloed: boolean) => void;}export default SettingsPanel;@@ -305,24 +278,8 @@ const CAPTION_LANGUAGE_OPTIONS = [{ value: "zh", label: "Chinese" },{ value: "ja", label: "Japanese" },{ value: "ko", label: "Korean" },- { value: "id", label: "Indonesian" },] as const;-export type WhisperModelInfo = {- value: "tiny" | "base" | "small" | "medium" | "large" | "custom";- label: string;- size: string;-};--const WHISPER_MODEL_OPTIONS: WhisperModelInfo[] = [- { value: "tiny", label: "Tiny", size: "75 MB" },- { value: "base", label: "Base", size: "142 MB" },- { value: "small", label: "Small", size: "466 MB" },- { value: "medium", label: "Medium", size: "1.5 GB" },- { value: "large", label: "Large (v3)", size: "2.9 GB" },- { value: "custom", label: "Custom", size: "Local File" },-];-function loadPreviewImage(url: string) {return new Promise<HTMLImageElement>((resolve, reject) => {const image = new Image();@@ -588,12 +545,8 @@ export function SettingsPanel({onAnnotationTypeChange,onAnnotationStyleChange,onAnnotationFigureDataChange,- onAnnotationBlurIntensityChange,onAnnotationDelete,- onSeek,autoCaptions = [],- onAutoCaptionsChange,- autoCaptionProgress = 0,autoCaptionSettings = DEFAULT_AUTO_CAPTION_SETTINGS,whisperModelPath,whisperModelDownloadStatus = "idle",@@ -603,36 +556,15 @@ export function SettingsPanel({onPickWhisperModel,onGenerateAutoCaptions,onClearAutoCaptions,- onDownloadWhisperModel,- onDeleteWhisperModel,- selectedCaptionId,- onSelectCaption,+ onDownloadWhisperSmallModel,+ onDeleteWhisperSmallModel,selectedSpeedId,selectedSpeedValue,onSpeedChange,onSpeedDelete,- audioRegions = [],- selectedAudioId,- onAudioVolumeChange,- onAudioMutedChange,- onAudioSoloedChange,- onAudioFadeInMsChange,- onAudioFadeOutMsChange,- onAudioDelete,- timeSelection,- isMasterSelected,- masterAudioVolume = 1,- masterAudioMuted = false,- masterAudioSoloed = false,- videoDuration,- videoPath,- onMasterAudioVolumeChange,- onMasterAudioMutedChange,- onMasterAudioSoloedChange,}: SettingsPanelProps) {const tSettings = useScopedT("settings");const { t } = useI18n();-const isBackgroundPanel = panelMode === "background";const initialEditorPreferences = useMemo(() => loadEditorPreferences(), []);const [builtInWallpapers, setBuiltInWallpapers] =@@ -1247,11 +1179,6 @@ export function SettingsPanel({? (figureData) => onAnnotationFigureDataChange(selectedAnnotation.id, figureData): undefined}- onBlurIntensityChange={- onAnnotationBlurIntensityChange- ? (intensity) => onAnnotationBlurIntensityChange(selectedAnnotation.id, intensity)- : undefined- }onDelete={() => onAnnotationDelete(selectedAnnotation.id)}/>);@@ -1448,6 +1375,16 @@ export function SettingsPanel({</div><div className="rounded-lg bg-white/[0.03] px-2.5 py-2 space-y-3">+ <div>+ <Button+ type="button"+ variant="outline"+ onClick={onPickWhisperModel}+ className="h-10 w-full rounded-xl border-white/10 bg-white/5 px-4 text-sm text-slate-200 hover:bg-white/10 hover:text-white"+ >+ {tSettings("captions.selectModel", "Select Model")}+ </Button>+ </div><div className="flex items-center justify-between gap-3"><div className="text-sm font-medium text-slate-200">{tSettings("captions.language", "Language")}@@ -1468,44 +1405,6 @@ export function SettingsPanel({</SelectContent></Select></div>- <div className="flex items-center justify-between gap-3">- <div className="text-sm font-medium text-slate-200">Model</div>- <Select- value={autoCaptionSettings.selectedModel || "small"}- onValueChange={(value) => updateAutoCaptionSettings({ selectedModel: value as any })}- >- <SelectTrigger className="h-10 w-[180px] rounded-xl border-white/10 bg-white/5 text-sm text-slate-200 hover:bg-white/10">- <SelectValue />- </SelectTrigger>- <SelectContent className="border-white/10 bg-[#1a1a1f] text-slate-200">- {WHISPER_MODEL_OPTIONS.map((option) => (- <SelectItem key={option.value} value={option.value}>- <div className="flex items-center justify-between w-full gap-4">- <span>{option.label}</span>- <span className="text-[10px] text-slate-500">{option.size}</span>- </div>- </SelectItem>- ))}- </SelectContent>- </Select>- </div>- {autoCaptionSettings.selectedModel === "custom" && (- <div>- <Button- type="button"- variant="outline"- onClick={onPickWhisperModel}- className="h-10 w-full rounded-xl border-white/10 bg-white/5 px-4 text-sm text-slate-200 hover:bg-white/10 hover:text-white"- >- {tSettings("captions.selectModel", "Select Model")}- </Button>- {whisperModelPath && (- <p className="mt-1 truncate px-1 text-[10px] text-slate-500">- {whisperModelPath.split(/[\\/]/).pop()}- </p>- )}- </div>- )}<div className="flex flex-wrap items-center gap-2"><div className="grid w-full grid-cols-2 gap-2">{whisperModelDownloadStatus === "downloading" ? (@@ -1521,26 +1420,23 @@ export function SettingsPanel({<Buttontype="button"variant="outline"- onClick={onDeleteWhisperModel}+ onClick={onDeleteWhisperSmallModel}className="h-10 w-full rounded-xl border-white/10 bg-white/5 px-4 text-sm text-slate-200 hover:bg-white/10 hover:text-white">{tSettings("captions.deleteModel", "Delete Model")}</Button>- ) : autoCaptionSettings.selectedModel !== "custom" ? (+ ) : (<Buttontype="button"- onClick={onDownloadWhisperModel}+ onClick={onDownloadWhisperSmallModel}className="h-10 w-full rounded-xl bg-[#2563EB] px-4 text-sm font-medium text-white hover:bg-[#2563EB]/90">{tSettings("captions.downloadModel", "Download Model")}</Button>- ) : (- <div className="flex h-10 w-full items-center justify-center rounded-xl bg-white/5 px-4 text-[10px] text-slate-500 italic">- No local model selected- </div>)}<Buttontype="button"+ variant="outline"onClick={onClearAutoCaptions}disabled={captionCueCount === 0}className="h-10 w-full rounded-xl border-white/10 bg-white/5 px-4 text-sm text-slate-200 hover:bg-white/10 hover:text-white disabled:opacity-50"@@ -1549,124 +1445,19 @@ export function SettingsPanel({</Button></div></div>- <div className="flex flex-col gap-3 pt-1">- <div className="flex flex-col gap-1.5 px-1">- <SectionLabel>Generation Range</SectionLabel>- <ToggleGroup- type="single"- value={autoCaptionSettings?.generationRange || "full"}- onValueChange={(val) =>- val &&- onAutoCaptionSettingsChange?.({- ...autoCaptionSettings!,- generationRange: val as any,- })- }- className="justify-start gap-1"- >- <ToggleGroupItem- value="full"- className="h-7 cursor-pointer rounded-lg border border-white/5 bg-white/5 px-2.5 text-[10px] data-[state=on]:border-blue-500/50 data-[state=on]:bg-blue-500/20 data-[state=on]:text-blue-400"- >- Full Video- </ToggleGroupItem>- <ToggleGroupItem- value="selected"- className="h-7 cursor-pointer rounded-lg border border-white/5 bg-white/5 px-2.5 text-[10px] data-[state=on]:border-blue-500/50 data-[state=on]:bg-blue-500/20 data-[state=on]:text-blue-400"- >- Selected Timeline {timeSelection ? `(${(timeSelection.startMs / 1000).toFixed(1)}s - ${(timeSelection.endMs / 1000).toFixed(1)}s)` : ""}- </ToggleGroupItem>- </ToggleGroup>- </div>- </div><div className="flex flex-col gap-2"><Buttontype="button"onClick={onGenerateAutoCaptions}- disabled={isGeneratingCaptions}- className="relative h-10 w-full overflow-hidden rounded-xl bg-[#2563EB] px-4 text-sm font-medium text-white hover:bg-[#2563EB]/90 disabled:bg-[#2563EB]/50"+ disabled={isGeneratingCaptions || !whisperModelPath}+ className="h-10 w-full rounded-xl bg-[#2563EB] px-4 text-sm font-medium text-white hover:bg-[#2563EB]/90 disabled:opacity-60">- {isGeneratingCaptions && (- <motion.div- className="absolute inset-y-0 left-0 bg-white/20"- initial={{ width: 0 }}- animate={{ width: `${autoCaptionProgress}%` }}- transition={{ duration: 0.3 }}- />- )}- <span className="relative z-10">- {isGeneratingCaptions- ? `${tSettings("captions.generating", "Generating...")} (${autoCaptionProgress}%)`- : tSettings("captions.generateAutoCaptions", "Generate Captions")}- </span>+ {isGeneratingCaptions+ ? tSettings("captions.generating", "Generating...")+ : captionCueCount > 0+ ? tSettings("captions.regenerateFull", "Regenerate Captions")+ : tSettings("captions.generateFull", "Generate Captions")}</Button>-- {autoCaptions.length > 0 && (- <div className="mt-4 flex flex-col gap-2">- <div className="flex items-center justify-between px-1">- <span className="text-[10px] font-semibold uppercase tracking-wider text-slate-500">- {selectedCaptionId ? "Edit Selected Cue" : "Select Cue on Timeline"}- </span>- </div>-- <div className="rounded-xl border border-white/5 bg-black/20 p-2">- {selectedCaptionId ? (- (() => {- const index = autoCaptions.findIndex((c) => c.id === selectedCaptionId);- const cue = autoCaptions[index];- if (!cue) return null;-- return (- <div className="flex flex-col gap-2">- <div className="flex items-center justify-between">- <button- type="button"- onClick={() => onSeek?.(cue.startMs / 1000)}- className="text-[10px] font-medium text-slate-500 hover:text-[#2563EB]"- >- {(cue.startMs / 1000).toFixed(2)}s – {(cue.endMs / 1000).toFixed(2)}s- </button>- <button- type="button"- onClick={() => {- const newCaptions = [...autoCaptions];- newCaptions.splice(index, 1);- onAutoCaptionsChange?.(newCaptions);- onSelectCaption?.(null);- }}- className="text-slate-500 hover:text-red-400 p-1"- >- <Trash2 className="h-4 w-4" />- </button>- </div>- <textarea- value={cue.text}- onChange={(e) => {- const newCaptions = [...autoCaptions];- newCaptions[index] = { ...cue, text: e.target.value };- onAutoCaptionsChange?.(newCaptions);- }}- rows={2}- autoFocus- className="w-full resize-none rounded-lg border-none bg-white/5 p-2 text-sm text-slate-300 placeholder:text-slate-600 focus:outline-none focus:ring-1 focus:ring-[#2563EB]"- />- </div>- );- })()- ) : (- <div className="flex flex-col items-center justify-center py-6 px-4 text-center">- <div className="mb-2 rounded-full bg-white/5 p-2.5">- <MessageSquare className="h-4 w-4 text-slate-600" />- </div>- <p className="text-[11px] text-slate-500 leading-relaxed max-w-[160px]">- Select a caption block on the timeline to edit its text and timing- </p>- </div>- )}- </div>- </div>- )}-{isGeneratingCaptions ? (<div className="space-y-1"><div className="text-xs text-slate-400">@@ -1819,54 +1610,6 @@ export function SettingsPanel({return sceneSectionContent;case "captions":return captionsSectionContent;- case "audio": {- const selectedAudio = audioRegions?.find((a) => a.id === selectedAudioId);- if (selectedAudio) {- return (- <AudioSettingsPanel- audio={selectedAudio}- onVolumeChange={(volume) => onAudioVolumeChange?.(selectedAudio.id, volume)}- onMutedChange={(muted) => onAudioMutedChange?.(selectedAudio.id, muted)}- onSoloedChange={(soloed) => onAudioSoloedChange?.(selectedAudio.id, soloed)}- onFadeInMsChange={(ms) => onAudioFadeInMsChange?.(selectedAudio.id, ms)}- onFadeOutMsChange={(ms) => onAudioFadeOutMsChange?.(selectedAudio.id, ms)}- onDelete={() => onAudioDelete?.(selectedAudio.id)}- />- );- }-- if (isMasterSelected) {- const masterAudioMock: AudioRegion = {- id: "master",- startMs: 0,- endMs: (videoDuration || 0) * 1000,- volume: masterAudioVolume,- muted: masterAudioMuted,- soloed: masterAudioSoloed,- audioPath: videoPath || "",- fadeInMs: 0,- fadeOutMs: 0,- };- return (- <AudioSettingsPanel- audio={masterAudioMock}- onVolumeChange={onMasterAudioVolumeChange || (() => {})}- onMutedChange={onMasterAudioMutedChange || (() => {})}- onSoloedChange={onMasterAudioSoloedChange || (() => {})}- onFadeInMsChange={() => {}}- onFadeOutMsChange={() => {}}- onDelete={() => {}}- />- );- }-- return (- <div className="flex flex-col items-center justify-center h-full text-slate-500 gap-2 py-12">- <Music className="w-8 h-8 opacity-20" />- <p className="text-xs">Select an audio region to edit its settings</p>- </div>- );- }case "cursor":return (<section className="flex flex-col gap-2">diff --git a/src/components/video-editor/VideoEditor.tsx b/src/components/video-editor/VideoEditor.tsxindex 0f084da4..dc11eec5 100644--- a/src/components/video-editor/VideoEditor.tsx+++ b/src/components/video-editor/VideoEditor.tsx@@ -6,14 +6,12 @@ import {FolderOpen,Languages,MousePointer2,- Music,Redo2,Save,Sparkles,Undo2,X,} from "lucide-react";-import { v4 as uuidv4 } from "uuid";import { AnimatePresence, LayoutGroup, motion } from "motion/react";import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { Panel, PanelGroup, PanelResizeHandle } from "react-resizable-panels";@@ -86,7 +84,6 @@ import {DEFAULT_ANNOTATION_SIZE,DEFAULT_ANNOTATION_STYLE,DEFAULT_AUTO_CAPTION_SETTINGS,- DEFAULT_BLUR_INTENSITY,DEFAULT_CONNECTED_ZOOM_DURATION_MS,DEFAULT_CONNECTED_ZOOM_EASING,DEFAULT_CONNECTED_ZOOM_GAP_MS,@@ -110,7 +107,6 @@ import {type ZoomFocus,type ZoomRegion,type ZoomTransitionEasing,- type TimeSelection,} from "./types";import VideoPlayback, { VideoPlaybackRef } from "./VideoPlayback";import {@@ -130,12 +126,6 @@ type EditorHistorySnapshot = {selectedSpeedId: string | null;selectedAnnotationId: string | null;selectedAudioId: string | null;- selectedCaptionId: string | null;- masterAudioMuted: boolean;- masterAudioSoloed: boolean;- masterAudioVolume: number;- audioTrackVolume: number;- isMasterSelected: boolean;};type PendingExportSave = {@@ -386,33 +376,25 @@ export default function VideoEditor() {const [audioRegions, setAudioRegions] = useState<AudioRegion[]>([]);const [selectedAudioId, setSelectedAudioId] = useState<string | null>(null);const [autoCaptions, setAutoCaptions] = useState<CaptionCue[]>([]);- const [selectedCaptionId, setSelectedCaptionId] = useState<string | null>(null);- const [timeSelection, setTimeSelection] = useState<TimeSelection | null>(null);- const [autoCaptionSettings, setAutoCaptionSettings] = useState<AutoCaptionSettings>(() => ({- ...DEFAULT_AUTO_CAPTION_SETTINGS,- selectedModel: (initialEditorPreferences.whisperSelectedModel as any) || "small",- }));+ const [autoCaptionSettings, setAutoCaptionSettings] = useState<AutoCaptionSettings>(+ DEFAULT_AUTO_CAPTION_SETTINGS,+ );const [whisperExecutablePath, setWhisperExecutablePath] = useState<string | null>(initialEditorPreferences.whisperExecutablePath,);const [whisperModelPath, setWhisperModelPath] = useState<string | null>(initialEditorPreferences.whisperModelPath,);+ const [downloadedWhisperModelPath, setDownloadedWhisperModelPath] = useState<string | null>(null);const [whisperModelDownloadStatus, setWhisperModelDownloadStatus] = useState<"idle" | "downloading" | "downloaded" | "error">(initialEditorPreferences.whisperModelPath ? "downloaded" : "idle");const [whisperModelDownloadProgress, setWhisperModelDownloadProgress] = useState(0);const [isGeneratingCaptions, setIsGeneratingCaptions] = useState(false);- const [autoCaptionProgress, setAutoCaptionProgress] = useState(0);const [isExporting, setIsExporting] = useState(false);const [exportProgress, setExportProgress] = useState<ExportProgress | null>(null);const [exportError, setExportError] = useState<string | null>(null);const [showExportDropdown, setShowExportDropdown] = useState(false);- const [masterAudioMuted, setMasterAudioMuted] = useState(false);- const [masterAudioSoloed, setMasterAudioSoloed] = useState(false);- const [masterAudioVolume, setMasterAudioVolume] = useState(1);- const [audioTrackVolume, setAudioTrackVolume] = useState(1);- const [isMasterSelected, setIsMasterSelected] = useState(false);const [previewVolume, setPreviewVolume] = useState(1);const [aspectRatio, setAspectRatio] = useState<AspectRatio>(initialEditorPreferences.aspectRatio);const [activeEffectSection, setActiveEffectSection] = useState<EditorEffectSection>("scene");@@ -434,15 +416,8 @@ export default function VideoEditor() {const [lastSavedSnapshot, setLastSavedSnapshot] = useState<EditorProjectData | null>(null);const [showCropModal, setShowCropModal] = useState(false);const [previewVersion, setPreviewVersion] = useState(0);- const [isAudioEngineReady, setIsAudioEngineReady] = useState(false);- const [timelineMode, setTimelineMode] = useState<'move' | 'select'>('move');const videoPlaybackRef = useRef<VideoPlaybackRef>(null);- const audioContextRef = useRef<AudioContext | null>(null);- const masterGainRef = useRef<GainNode | null>(null);- const audioRegionNodesRef = useRef<Map<string, { source: MediaElementAudioSourceNode; gain: GainNode }>>(new Map());- const videoAudioNodeRef = useRef<{ source: MediaElementAudioSourceNode; gain: GainNode } | null>(null);-const projectBrowserTriggerRef = useRef<HTMLButtonElement | null>(null);const projectBrowserFallbackTriggerRef = useRef<HTMLButtonElement | null>(null);const nextZoomIdRef = useRef(1);@@ -816,7 +791,6 @@ export default function VideoEditor() {label: t("settings.sections.captions", "Captions"),icon: Captions,},- { id: "audio" as const, label: t("settings.sections.audio", "Audio"), icon: Music },],[t],);@@ -991,12 +965,6 @@ export default function VideoEditor() {selectedSpeedId,selectedAnnotationId,selectedAudioId,- selectedCaptionId,- masterAudioMuted,- masterAudioSoloed,- masterAudioVolume,- audioTrackVolume,- isMasterSelected,};}, [zoomRegions,@@ -1010,57 +978,46 @@ export default function VideoEditor() {selectedSpeedId,selectedAnnotationId,selectedAudioId,- selectedCaptionId,- masterAudioMuted,- masterAudioSoloed,- masterAudioVolume,- audioTrackVolume,- isMasterSelected,]);const applyHistorySnapshot = useCallback((snapshot: EditorHistorySnapshot) => {applyingHistoryRef.current = true;- setZoomRegions(cloneStructured(snapshot.zoomRegions));- setTrimRegions(cloneStructured(snapshot.trimRegions));- setSpeedRegions(cloneStructured(snapshot.speedRegions));- setAnnotationRegions(cloneStructured(snapshot.annotationRegions));- setAudioRegions(cloneStructured(snapshot.audioRegions));- setAutoCaptions(cloneStructured(snapshot.autoCaptions));- setSelectedZoomId(snapshot.selectedZoomId);- setSelectedTrimId(snapshot.selectedTrimId);- setSelectedSpeedId(snapshot.selectedSpeedId);- setSelectedAnnotationId(snapshot.selectedAnnotationId);- setSelectedAudioId(snapshot.selectedAudioId);- setSelectedCaptionId(snapshot.selectedCaptionId);- setMasterAudioMuted(snapshot.masterAudioMuted);- setMasterAudioSoloed(snapshot.masterAudioSoloed);- setMasterAudioVolume(snapshot.masterAudioVolume);- setAudioTrackVolume(snapshot.audioTrackVolume);- setIsMasterSelected(snapshot.isMasterSelected);+ const cloned = cloneSnapshot(snapshot);+ setZoomRegions(cloned.zoomRegions);+ setTrimRegions(cloned.trimRegions);+ setSpeedRegions(cloned.speedRegions);+ setAnnotationRegions(cloned.annotationRegions);+ setAudioRegions(cloned.audioRegions);+ setAutoCaptions(cloned.autoCaptions);+ setSelectedZoomId(cloned.selectedZoomId);+ setSelectedTrimId(cloned.selectedTrimId);+ setSelectedSpeedId(cloned.selectedSpeedId);+ setSelectedAnnotationId(cloned.selectedAnnotationId);+ setSelectedAudioId(cloned.selectedAudioId);nextZoomIdRef.current = deriveNextId("zoom",- snapshot.zoomRegions.map((region: ZoomRegion) => region.id),+ cloned.zoomRegions.map((region) => region.id),);nextTrimIdRef.current = deriveNextId("trim",- snapshot.trimRegions.map((region: TrimRegion) => region.id),+ cloned.trimRegions.map((region) => region.id),);nextSpeedIdRef.current = deriveNextId("speed",- snapshot.speedRegions.map((region: SpeedRegion) => region.id),+ cloned.speedRegions.map((region) => region.id),);nextAnnotationIdRef.current = deriveNextId("annotation",- snapshot.annotationRegions.map((region: AnnotationRegion) => region.id),+ cloned.annotationRegions.map((region) => region.id),);nextAudioIdRef.current = deriveNextId("audio",- snapshot.audioRegions.map((region: AudioRegion) => region.id),+ cloned.audioRegions.map((region) => region.id),);nextAnnotationZIndexRef.current =- snapshot.annotationRegions.reduce((max: number, region: AnnotationRegion) => Math.max(max, region.zIndex), 0) + 1;+ cloned.annotationRegions.reduce((max, region) => Math.max(max, region.zIndex), 0) + 1;},[cloneSnapshot],);@@ -1162,11 +1119,6 @@ export default function VideoEditor() {setGifFrameRate(normalizedEditor.gifFrameRate);setGifLoop(normalizedEditor.gifLoop);setGifSizePreset(normalizedEditor.gifSizePreset);- setMasterAudioMuted(normalizedEditor.masterAudioMuted);- setMasterAudioSoloed(normalizedEditor.masterAudioSoloed);- setMasterAudioVolume(normalizedEditor.masterAudioVolume);- setAudioTrackVolume(normalizedEditor.audioTrackVolume);- setIsMasterSelected(normalizedEditor.isMasterSelected ?? false);setSelectedZoomId(null);setSelectedTrimId(null);@@ -1311,9 +1263,9 @@ export default function VideoEditor() {() =>Boolean(currentProjectPath &&- currentProjectSnapshot &&- lastSavedSnapshot &&- !areDeepEqual(currentProjectSnapshot, lastSavedSnapshot),+ currentProjectSnapshot &&+ lastSavedSnapshot &&+ !areDeepEqual(currentProjectSnapshot, lastSavedSnapshot),),[currentProjectPath, currentProjectSnapshot, lastSavedSnapshot],);@@ -1405,11 +1357,8 @@ export default function VideoEditor() {gifFrameRate,gifLoop,gifSizePreset,- masterAudioMuted,- masterAudioSoloed,whisperExecutablePath,whisperModelPath,- whisperSelectedModel: autoCaptionSettings.selectedModel,});}, [wallpaper,@@ -1445,73 +1394,45 @@ export default function VideoEditor() {gifSizePreset,whisperExecutablePath,whisperModelPath,- autoCaptionSettings.selectedModel,]);useEffect(() => {- const unsubscribe = window.electronAPI.onWhisperModelDownloadProgress((state) => {- if (state.model === autoCaptionSettings.selectedModel) {- setWhisperModelDownloadStatus(state.status);- setWhisperModelDownloadProgress(state.progress);- }-+ const unsubscribe = window.electronAPI.onWhisperSmallModelDownloadProgress((state) => {+ setWhisperModelDownloadStatus(state.status);+ setWhisperModelDownloadProgress(state.progress);if (state.status === "downloaded") {- if (state.model === autoCaptionSettings.selectedModel) {- setWhisperModelPath(state.path ?? null);- }+ setDownloadedWhisperModelPath(state.path ?? null);+ setWhisperModelPath((currentPath) => currentPath ?? state.path ?? null);}-if (state.status === "idle") {- if (state.model === autoCaptionSettings.selectedModel) {- setWhisperModelPath(null);- }+ setDownloadedWhisperModelPath(null);}-if (state.status === "error" && state.error) {toast.error(state.error);}});- return () => unsubscribe?.();- }, [autoCaptionSettings.selectedModel]);-- useEffect(() => {- const unlistenProgress = window.electronAPI.onAutoCaptionProgress((payload: { progress: number }) => {- setAutoCaptionProgress(payload.progress);- });- const unlistenChunk = window.electronAPI.onAutoCaptionChunk(({ cues }) => {- setAutoCaptions((prev) => {- const existingIds = new Set(prev.map((c) => c.id));- const newCues = cues.filter((c) => !existingIds.has(c.id));- if (newCues.length === 0) return prev;- return [...prev, ...newCues].sort((a, b) => a.startMs - b.startMs);- });- });- return () => {- unlistenProgress();- unlistenChunk();- };- }, []);-- useEffect(() => {void (async () => {- const result = await window.electronAPI.getWhisperModelStatus(- autoCaptionSettings.selectedModel,- );+ const result = await window.electronAPI.getWhisperSmallModelStatus();if (!result.success) {return;}if (result.exists && result.path) {+ setDownloadedWhisperModelPath(result.path);setWhisperModelPath((currentPath) => currentPath ?? result.path ?? null);setWhisperModelDownloadStatus("downloaded");setWhisperModelDownloadProgress(100);- } else {- setWhisperModelDownloadStatus("idle");- setWhisperModelDownloadProgress(0);+ return;}++ setDownloadedWhisperModelPath(null);+ setWhisperModelDownloadStatus("idle");+ setWhisperModelDownloadProgress(0);})();- }, [autoCaptionSettings.selectedModel]);++ return () => unsubscribe?.();+ }, []);const handlePickWhisperExecutable = useCallback(async () => {const result = await window.electronAPI.openWhisperExecutablePicker();@@ -1523,42 +1444,25 @@ export default function VideoEditor() {toast.success("Whisper executable selected");}, []);- const handleSelectMaster = useCallback((selected: boolean) => {- setIsMasterSelected(selected);- if (selected) {- setSelectedZoomId(null);- setSelectedTrimId(null);- setSelectedSpeedId(null);- setSelectedAnnotationId(null);- setSelectedAudioId(null);- setSelectedCaptionId(null);- setActiveEffectSection("audio");- }- }, []);-- const handleDownloadWhisperModel = useCallback(async () => {+ const handleDownloadWhisperSmallModel = useCallback(async () => {if (whisperModelDownloadStatus === "downloading") {return;}setWhisperModelDownloadStatus("downloading");setWhisperModelDownloadProgress(0);- const result = await window.electronAPI.downloadWhisperModel(- autoCaptionSettings.selectedModel,- );+ const result = await window.electronAPI.downloadWhisperSmallModel();if (!result.success) {setWhisperModelDownloadStatus("error");- toast.error(- result.error ||- `Failed to download Whisper ${autoCaptionSettings.selectedModel} model`,- );+ toast.error(result.error || "Failed to download Whisper small model");return;}if (result.path) {+ setDownloadedWhisperModelPath(result.path);setWhisperModelPath(result.path);}- }, [whisperModelDownloadStatus, autoCaptionSettings.selectedModel]);+ }, [whisperModelDownloadStatus]);const handlePickWhisperModel = useCallback(async () => {const result = await window.electronAPI.openWhisperModelPicker();@@ -1570,23 +1474,21 @@ export default function VideoEditor() {toast.success("Whisper model selected");}, []);- const handleDeleteWhisperModel = useCallback(async () => {- const result = await window.electronAPI.deleteWhisperModel(- autoCaptionSettings.selectedModel,- );+ const handleDeleteWhisperSmallModel = useCallback(async () => {+ const result = await window.electronAPI.deleteWhisperSmallModel();if (!result.success) {- toast.error(- result.error ||- `Failed to delete Whisper ${autoCaptionSettings.selectedModel} model`,- );+ toast.error(result.error || "Failed to delete Whisper small model");return;}- setWhisperModelPath(null);+ setWhisperModelPath((currentPath) =>+ currentPath === downloadedWhisperModelPath ? null : currentPath,+ );+ setDownloadedWhisperModelPath(null);setWhisperModelDownloadStatus("idle");setWhisperModelDownloadProgress(0);- toast.success(`Whisper ${autoCaptionSettings.selectedModel} model deleted`);- }, [autoCaptionSettings.selectedModel]);+ toast.success("Whisper small model deleted");+ }, [downloadedWhisperModelPath]);const handleGenerateAutoCaptions = useCallback(async () => {if (isGeneratingCaptions) {@@ -1627,77 +1529,39 @@ export default function VideoEditor() {return;}- console.log("[VideoEditor] handleGenerateAutoCaptions: starting", {- sourcePath,- whisperExecutablePath,- whisperModelPath,- language: autoCaptionSettings.language,- });-setIsGeneratingCaptions(true);- setAutoCaptionProgress(0);-- const startTimeMs = autoCaptionSettings.generationRange === "selected" && timeSelection- ? timeSelection.startMs- : 0;- const rangeDurationMs = autoCaptionSettings.generationRange === "selected" && timeSelection- ? timeSelection.endMs - timeSelection.startMs- : duration * 1000;-- if (autoCaptionSettings.generationRange === "selected" && !timeSelection) {- toast.error("Please select a range on the timeline first", {- description: "Click and drag or Shift+Click on the timeline to select a range for caption generation.",- });- setIsGeneratingCaptions(false);- return;- }-try {const result = await window.electronAPI.generateAutoCaptions({videoPath: sourcePath,whisperExecutablePath: whisperExecutablePath ?? undefined,whisperModelPath,language: autoCaptionSettings.language,- durationMs: rangeDurationMs,- startTimeMs,});- console.log("[VideoEditor] handleGenerateAutoCaptions: result", result);-- if (result.success && result.cues) {- const cuesWithIds = result.cues.map((cue: CaptionCue) => ({- ...cue,- id: cue.id || uuidv4(),- }));- // Sort cues by time- cuesWithIds.sort((a, b) => a.startMs - b.startMs);- setAutoCaptions(cuesWithIds);- setAutoCaptionSettings((prev) => ({ ...prev, enabled: true }));- toast.success(`Generated ${cuesWithIds.length} captions`);- } else if (!result.success) {+ if (!result.success || !result.cues) {toast.error(result.message || getErrorMessage(result.error) || "Failed to generate captions",);- } else {- toast.error("No captions were generated");+ return;}++ setAutoCaptions(result.cues);+ setAutoCaptionSettings((prev) => ({ ...prev, enabled: true }));+ toast.success(result.message || `Generated ${result.cues.length} captions`);} catch (error) {toast.error(getErrorMessage(error));} finally {setIsGeneratingCaptions(false);- setAutoCaptionProgress(0);}}, [autoCaptionSettings.language,- autoCaptionSettings.generationRange,isGeneratingCaptions,- videoSourcePath,+ webcam.sourcePath,+ syncActiveVideoSource,videoPath,- duration,+ videoSourcePath,+ whisperExecutablePath,whisperModelPath,- timeSelection,- syncActiveVideoSource,- webcam.sourcePath,]);const handleClearAutoCaptions = useCallback(() => {@@ -1843,30 +1707,6 @@ export default function VideoEditor() {};}, [handleOpenProjectBrowser, handleSaveProject, handleSaveProjectAs]);- useEffect(() => {- const video = videoPlaybackRef.current?.video;- if (!video || !audioContextRef.current || (videoAudioNodeRef.current && videoAudioNodeRef.current.source.mediaElement === video)) {- return;- }-- try {- // If we had an old source node for a different video, disconnect it- if (videoAudioNodeRef.current) {- videoAudioNodeRef.current.source.disconnect();- videoAudioNodeRef.current.gain.disconnect();- }-- const source = audioContextRef.current.createMediaElementSource(video);- const gain = audioContextRef.current.createGain();- source.connect(gain);- gain.connect(masterGainRef.current!);- videoAudioNodeRef.current = { source, gain };- console.log("[VideoEditor] Video audio routed through Web Audio API");- } catch (e) {- console.warn("[VideoEditor] Could not route video audio", e);- }- }, [videoPlaybackRef.current?.video, previewVersion, isAudioEngineReady]);-useEffect(() => {let mounted = true;@@ -1898,25 +1738,6 @@ export default function VideoEditor() {};}, [videoPath]);- // Apply master volume to the master gain node- useEffect(() => {- if (masterGainRef.current) {- masterGainRef.current.gain.setTargetAtTime(masterAudioVolume * previewVolume, 0, 0.03);- }- }, [masterAudioVolume, previewVolume]);-- // Handle video master solo/mute- useEffect(() => {- if (videoAudioNodeRef.current) {- const hasGlobalSolo = masterAudioSoloed || audioRegions.some((r) => r.soloed);- let vol = 1;- if (masterAudioMuted || (hasGlobalSolo && !masterAudioSoloed)) {- vol = 0;- }- videoAudioNodeRef.current.gain.gain.setTargetAtTime(vol, 0, 0.03);- }- }, [masterAudioMuted, masterAudioSoloed, audioRegions]);-const normalizedCursorTelemetry = useMemo(() => {if (cursorTelemetry.length === 0) {return [] as CursorTelemetryPoint[];@@ -2035,50 +1856,18 @@ export default function VideoEditor() {autoSuggestedVideoPathRef.current = videoPath;}, [videoPath, duration, effectiveCursorTelemetry, loopCursor, zoomRegions.length]);- const initAudioContext = useCallback(() => {- if (audioContextRef.current) {- if (audioContextRef.current.state === 'suspended') {- audioContextRef.current.resume().then(() => setIsAudioEngineReady(true));- }- return;- }-- try {- const ctx = new (window.AudioContext || (window as any).webkitAudioContext)();- const masterGain = ctx.createGain();- masterGain.connect(ctx.destination);- audioContextRef.current = ctx;- masterGainRef.current = masterGain;- setIsAudioEngineReady(true);- console.log("[VideoEditor] Web Audio API context initialized");- } catch (e) {- console.error("[VideoEditor] Failed to initialize AudioContext", e);- }- }, []);-function togglePlayPause() {const playback = videoPlaybackRef.current;const video = playback?.video;if (!playback || !video) return;- initAudioContext();-if (!video.paused && !video.ended) {playback.pause();} else {- // Selection awareness: if playing with a selection active, jump to start if out of bounds- if (timeSelection) {- const currentTimeMs = Math.round(currentTime * 1000);- const bufferMs = 50; // Small buffer for end boundary- if (currentTimeMs < timeSelection.startMs || currentTimeMs >= timeSelection.endMs - bufferMs) {- handleSeek(timeSelection.startMs / 1000);- }- }playback.play().catch((err) => console.error("Video play failed:", err));}}-function handleSeek(time: number) {const video = videoPlaybackRef.current?.video;if (!video) return;@@ -2090,10 +1879,6 @@ export default function VideoEditor() {if (id) {setSelectedTrimId(null);setSelectedAudioId(null);- setSelectedSpeedId(null);- setSelectedAnnotationId(null);- setSelectedCaptionId(null);- setIsMasterSelected(false);}}, []);@@ -2103,9 +1888,6 @@ export default function VideoEditor() {setSelectedZoomId(null);setSelectedAnnotationId(null);setSelectedAudioId(null);- setSelectedSpeedId(null);- setSelectedCaptionId(null);- setIsMasterSelected(false);}}, []);@@ -2115,9 +1897,6 @@ export default function VideoEditor() {setSelectedZoomId(null);setSelectedTrimId(null);setSelectedAudioId(null);- setSelectedSpeedId(null);- setSelectedCaptionId(null);- setIsMasterSelected(false);}}, []);@@ -2134,7 +1913,6 @@ export default function VideoEditor() {setSelectedZoomId(id);setSelectedTrimId(null);setSelectedAnnotationId(null);- setSelectedCaptionId(null);}, []);const handleZoomSuggested = useCallback((span: Span, focus: ZoomFocus) => {@@ -2150,7 +1928,6 @@ export default function VideoEditor() {setSelectedZoomId(id);setSelectedTrimId(null);setSelectedAnnotationId(null);- setSelectedCaptionId(null);}, []);const handleTrimAdded = useCallback((span: Span) => {@@ -2164,8 +1941,6 @@ export default function VideoEditor() {setSelectedTrimId(id);setSelectedZoomId(null);setSelectedAnnotationId(null);- setSelectedCaptionId(null);- setIsMasterSelected(false);}, []);const handleZoomSpanChange = useCallback((id: string, span: Span) => {@@ -2173,10 +1948,10 @@ export default function VideoEditor() {prev.map((region) =>region.id === id? {- ...region,- startMs: Math.round(span.start),- endMs: Math.round(span.end),- }+ ...region,+ startMs: Math.round(span.start),+ endMs: Math.round(span.end),+ }: region,),);@@ -2187,10 +1962,10 @@ export default function VideoEditor() {prev.map((region) =>region.id === id? {- ...region,- startMs: Math.round(span.start),- endMs: Math.round(span.end),- }+ ...region,+ startMs: Math.round(span.start),+ endMs: Math.round(span.end),+ }: region,),);@@ -2201,9 +1976,9 @@ export default function VideoEditor() {prev.map((region) =>region.id === id? {- ...region,- focus: clampFocusToDepth(focus, region.depth),- }+ ...region,+ focus: clampFocusToDepth(focus, region.depth),+ }: region,),);@@ -2216,10 +1991,10 @@ export default function VideoEditor() {prev.map((region) =>region.id === selectedZoomId? {- ...region,- depth,- focus: clampFocusToDepth(region.focus, depth),- }+ ...region,+ depth,+ focus: clampFocusToDepth(region.focus, depth),+ }: region,),);@@ -2254,8 +2029,6 @@ export default function VideoEditor() {setSelectedTrimId(null);setSelectedAnnotationId(null);setSelectedAudioId(null);- setSelectedCaptionId(null);- setIsMasterSelected(false);}}, []);@@ -2272,7 +2045,6 @@ export default function VideoEditor() {setSelectedZoomId(null);setSelectedTrimId(null);setSelectedAnnotationId(null);- setSelectedCaptionId(null);}, []);const handleSpeedSpanChange = useCallback((id: string, span: Span) => {@@ -2280,10 +2052,10 @@ export default function VideoEditor() {prev.map((region) =>region.id === id? {- ...region,- startMs: Math.round(span.start),- endMs: Math.round(span.end),- }+ ...region,+ startMs: Math.round(span.start),+ endMs: Math.round(span.end),+ }: region,),);@@ -2306,9 +2078,6 @@ export default function VideoEditor() {setSelectedTrimId(null);setSelectedAnnotationId(null);setSelectedSpeedId(null);- setSelectedCaptionId(null);- setIsMasterSelected(false);- setActiveEffectSection("audio");}}, []);@@ -2327,8 +2096,6 @@ export default function VideoEditor() {setSelectedTrimId(null);setSelectedAnnotationId(null);setSelectedSpeedId(null);- setSelectedCaptionId(null);- setIsMasterSelected(false);}, []);const handleAudioSpanChange = useCallback((id: string, span: Span) => {@@ -2336,10 +2103,10 @@ export default function VideoEditor() {prev.map((region) =>region.id === id? {- ...region,- startMs: Math.round(span.start),- endMs: Math.round(span.end),- }+ ...region,+ startMs: Math.round(span.start),+ endMs: Math.round(span.end),+ }: region,),);@@ -2355,52 +2122,6 @@ export default function VideoEditor() {[selectedAudioId],);- const handleAudioVolumeChange = useCallback((id: string, volume: number) => {- setAudioRegions((prev) => prev.map((r) => (r.id === id ? { ...r, volume } : r)));- }, []);-- const handleAudioMutedChange = useCallback((id: string, muted: boolean) => {- setAudioRegions((prev) => prev.map((r) => (r.id === id ? { ...r, muted } : r)));- }, []);-- const handleAudioSoloedChange = useCallback((id: string, soloed: boolean) => {- setAudioRegions((prev) => prev.map((r) => (r.id === id ? { ...r, soloed } : r)));- }, []);-- const handleAudioFadeInMsChange = useCallback((id: string, fadeInMs: number) => {- setAudioRegions((prev) => prev.map((r) => (r.id === id ? { ...r, fadeInMs } : r)));- }, []);-- const handleAudioFadeOutMsChange = useCallback((id: string, fadeOutMs: number) => {- setAudioRegions((prev) => prev.map((r) => (r.id === id ? { ...r, fadeOutMs } : r)));- }, []);-- const handleCaptionSpanChange = useCallback((id: string, span: Span) => {- setAutoCaptions((prev) =>- prev.map((caption) =>- caption.id === id- ? {- ...caption,- startMs: Math.round(span.start),- endMs: Math.round(span.end),- }- : caption,- ),- );- }, []);-- const handleSelectCaption = useCallback((id: string | null) => {- setSelectedCaptionId(id);- if (id) {- setSelectedZoomId(null);- setSelectedTrimId(null);- setSelectedAnnotationId(null);- setSelectedSpeedId(null);- setSelectedAudioId(null);- setIsMasterSelected(false);- }- }, []);-const handleSpeedChange = useCallback((speed: PlaybackSpeed) => {if (!selectedSpeedId) return;@@ -2429,8 +2150,6 @@ export default function VideoEditor() {setSelectedAnnotationId(id);setSelectedZoomId(null);setSelectedTrimId(null);- setSelectedCaptionId(null);- setIsMasterSelected(false);}, []);const handleAnnotationSpanChange = useCallback((id: string, span: Span) => {@@ -2438,10 +2157,10 @@ export default function VideoEditor() {prev.map((region) =>region.id === id? {- ...region,- startMs: Math.round(span.start),- endMs: Math.round(span.end),- }+ ...region,+ startMs: Math.round(span.start),+ endMs: Math.round(span.end),+ }: region,),);@@ -2492,11 +2211,6 @@ export default function VideoEditor() {if (!region.figureData) {updatedRegion.figureData = { ...DEFAULT_FIGURE_DATA };}- } else if (type === "blur") {- updatedRegion.content = "";- if (updatedRegion.blurIntensity === undefined) {- updatedRegion.blurIntensity = DEFAULT_BLUR_INTENSITY;- }}return updatedRegion;@@ -2522,12 +2236,6 @@ export default function VideoEditor() {);}, []);- const handleAnnotationBlurIntensityChange = useCallback((id: string, blurIntensity: number) => {- setAnnotationRegions((prev) =>- prev.map((region) => (region.id === id ? { ...region, blurIntensity } : region)),- );- }, []);-const handleAnnotationPositionChange = useCallback((id: string, position: { x: number; y: number }) => {setAnnotationRegions((prev) =>@@ -2602,14 +2310,6 @@ export default function VideoEditor() {}}}-- if (!isEditableTarget) {- if (key === "v") {- setTimelineMode("move");- } else if (key === "r") {- setTimelineMode("select");- }- }};window.addEventListener("keydown", handleKeyDown, { capture: true });@@ -2649,86 +2349,45 @@ export default function VideoEditor() {}}, [selectedAudioId, audioRegions]);- useEffect(() => {- if (selectedCaptionId && !autoCaptions.some((cue) => cue.id === selectedCaptionId)) {- setSelectedCaptionId(null);- }- }, [selectedCaptionId, autoCaptions]);-// Audio playback sync: manage Audio elements that play in sync with videoconst audioElementsRef = useRef<Map<string, HTMLAudioElement>>(new Map());useEffect(() => {const existing = audioElementsRef.current;- const unused = new Set(existing.keys());+ const currentIds = new Set(audioRegions.map((r) => r.id));- const hasAudioContext = !!(audioContextRef.current && masterGainRef.current && isAudioEngineReady);+ // Remove old audio elements+ for (const [id, audio] of existing) {+ if (!currentIds.has(id)) {+ audio.pause();+ audio.src = "";+ existing.delete(id);+ }+ }+ // Create/update audio elementsfor (const region of audioRegions) {- unused.delete(region.id);let audio = existing.get(region.id);if (!audio) {audio = new Audio();- // Ensure cross-origin is handled to avoid CORS issues with AudioContext- audio.crossOrigin = "anonymous";+ audio.preload = "auto";existing.set(region.id, audio);}const expectedSrc = toFileUrl(region.audioPath);if (audio.src !== expectedSrc) {audio.src = expectedSrc;}-- // Route through Web Audio API if ready- if (hasAudioContext && !audioRegionNodesRef.current.has(region.id)) {- try {- const source = audioContextRef.current!.createMediaElementSource(audio);- const gain = audioContextRef.current!.createGain();- source.connect(gain);- gain.connect(masterGainRef.current!);- audioRegionNodesRef.current.set(region.id, { source, gain });- console.log(`[VideoEditor] Audio region ${region.id} routed through GainNode`);- } catch (e) {- console.warn(`[VideoEditor] Failed to route audio ${region.id}:`, e);- }- }-- // Initial volume setup — masterAudioMuted only affects the video element, not audio regions- const hasGlobalSolo = audioRegions.some((r) => r.soloed);- let baseVolume = region.volume * audioTrackVolume * previewVolume * masterAudioVolume;- if (region.muted || (hasGlobalSolo && !region.soloed)) {- baseVolume = 0;- }-- const nodeEntry = audioRegionNodesRef.current.get(region.id);- if (nodeEntry) {- audio.volume = 1;- nodeEntry.gain.gain.setTargetAtTime(baseVolume, 0, 0.03);- } else {- // Fallback to native volume (limited to 100%)- audio.volume = Math.max(0, Math.min(1, baseVolume));- }+ audio.volume = Math.max(0, Math.min(1, region.volume * previewVolume));}return () => {- for (const id of unused) {- const audio = existing.get(id);- if (audio) {- audio.pause();- audio.src = "";- }- existing.delete(id);-- const nodeEntry = audioRegionNodesRef.current.get(id);- if (nodeEntry) {- try {- nodeEntry.source.disconnect();- nodeEntry.gain.disconnect();- } catch (e) { /* ignore */ }- audioRegionNodesRef.current.delete(id);- }+ for (const audio of existing.values()) {+ audio.pause();+ audio.src = "";}+ existing.clear();};- }, [audioRegions, previewVolume, masterAudioVolume, audioTrackVolume, isAudioEngineReady]);+ }, [audioRegions, previewVolume]);// Sync audio playback with video currentTime and isPlaying stateuseEffect(() => {@@ -2740,39 +2399,9 @@ export default function VideoEditor() {const isInRegion = currentTimeMs >= region.startMs && currentTimeMs < region.endMs;if (isPlaying && isInRegion) {- // Calculate fade multiplier- let fadeMultiplier = 1;- if (region.fadeInMs && currentTimeMs < region.startMs + region.fadeInMs) {- fadeMultiplier = (currentTimeMs - region.startMs) / region.fadeInMs;- } else if (region.fadeOutMs && currentTimeMs > region.endMs - region.fadeOutMs) {- fadeMultiplier = (region.endMs - currentTimeMs) / region.fadeOutMs;- }- fadeMultiplier = Math.max(0, Math.min(1, fadeMultiplier));-- // masterAudioMuted only affects the video element — not audio regions- const hasGlobalSolo = audioRegions.some((r) => r.soloed);- let baseVolume = region.volume * audioTrackVolume * previewVolume * masterAudioVolume;- if (region.muted || (hasGlobalSolo && !region.soloed)) {- baseVolume = 0;- }-- const targetVolume = baseVolume * fadeMultiplier;- const nodeEntry = audioRegionNodesRef.current.get(region.id);-- if (nodeEntry) {- // Use Web Audio gain automation for smooth high-precision fade- nodeEntry.gain.gain.setTargetAtTime(targetVolume, 0, 0.03);- } else {- // Fallback to native volume (limited to 1.0)- const fallbackValue = Math.max(0, Math.min(1, targetVolume));- if (Math.abs(audio.volume - fallbackValue) > 0.01) {- audio.volume = fallbackValue;- }- }-const audioOffset = (currentTimeMs - region.startMs) / 1000;- // Only seek if significantly out of sync (> 20ms) - tightened for Web Audio era- if (Math.abs(audio.currentTime - audioOffset) > 0.02) {+ // Only seek if significantly out of sync (> 200ms)+ if (Math.abs(audio.currentTime - audioOffset) > 0.2) {audio.currentTime = audioOffset;}if (audio.paused) {@@ -2784,7 +2413,7 @@ export default function VideoEditor() {}}}- }, [isPlaying, currentTime, audioRegions, previewVolume, masterAudioVolume, audioTrackVolume]);+ }, [isPlaying, currentTime, audioRegions]);const showExportSuccessToast = useCallback((filePath: string) => {toast.success(`Exported successfully to ${filePath}`, {@@ -2994,10 +2623,6 @@ export default function VideoEditor() {cursorClickBounceDuration,cursorSway,audioRegions,- masterAudioVolume: masterAudioVolume ?? 1,- audioTrackVolume: audioTrackVolume ?? 1,- masterAudioMuted: masterAudioMuted ?? false,- masterAudioSoloed: masterAudioSoloed ?? false,previewWidth,previewHeight,onProgress: (progress: ExportProgress) => {@@ -3141,12 +2766,12 @@ export default function VideoEditor() {gifConfig:exportFormat === "gif"? {- frameRate: gifFrameRate,- loop: gifLoop,- sizePreset: gifSizePreset,- width: gifDimensions.width,- height: gifDimensions.height,- }+ frameRate: gifFrameRate,+ loop: gifLoop,+ sizePreset: gifSizePreset,+ width: gifDimensions.width,+ height: gifDimensions.height,+ }: undefined,};@@ -3263,11 +2888,11 @@ export default function VideoEditor() {? t("editor.exportStatus.saving", "Opening save dialog..."): isExportFinalizing && typeof exportProgress.renderProgress === "number"? t("editor.exportStatus.finalizingPercent", "Finalizing {{percent}}%", {- percent: Math.round(exportProgress.renderProgress),- })+ percent: Math.round(exportProgress.renderProgress),+ }): t("editor.exportStatus.completePercent", "{{percent}}% complete", {- percent: Math.round(exportProgress.percentage),- })+ percent: Math.round(exportProgress.percentage),+ }): t("editor.exportStatus.preparing", "Preparing export...");const projectBrowser = (@@ -3606,13 +3231,6 @@ export default function VideoEditor() {><VideoPlaybackkey={`${videoPath || "no-video"}:${previewVersion}`}- volume={(() => {- const hasGlobalSolo = masterAudioSoloed || audioRegions.some((r) => r.soloed);- if (masterAudioMuted || (hasGlobalSolo && !masterAudioSoloed)) {- return 0;- }- return previewVolume * masterAudioVolume;- })()}aspectRatio={aspectRatio}ref={videoPlaybackRef}videoPath={videoPath || ""}@@ -3663,9 +3281,8 @@ export default function VideoEditor() {cursorClickBounce={cursorClickBounce}cursorClickBounceDuration={cursorClickBounceDuration}cursorSway={cursorSway}- timeSelection={timeSelection}+ volume={previewVolume}/>-</div></div></div>@@ -3703,15 +3320,6 @@ export default function VideoEditor() {<div className="h-full min-h-0 bg-[#17171a] rounded-2xl border border-white/10 shadow-lg overflow-auto flex flex-col"><TimelineEditorvideoDuration={duration}- videoPath={videoPath || undefined}- masterAudioMuted={masterAudioMuted}- onMasterAudioMutedChange={setMasterAudioMuted}- masterAudioSoloed={masterAudioSoloed}- onMasterAudioSoloedChange={setMasterAudioSoloed}- masterAudioVolume={masterAudioVolume}- onMasterAudioVolumeChange={setMasterAudioVolume}- audioTrackVolume={audioTrackVolume}- onAudioTrackVolumeChange={setAudioTrackVolume}currentTime={currentTime}onSeek={handleSeek}cursorTelemetry={normalizedCursorTelemetry}@@ -3737,8 +3345,6 @@ export default function VideoEditor() {audioRegions={audioRegions}onAudioAdded={handleAudioAdded}onAudioSpanChange={handleAudioSpanChange}- onAudioMutedChange={handleAudioMutedChange}- onAudioSoloedChange={handleAudioSoloedChange}onAudioDelete={handleAudioDelete}selectedAudioId={selectedAudioId}onSelectAudio={handleSelectAudio}@@ -3748,21 +3354,10 @@ export default function VideoEditor() {onAnnotationDelete={handleAnnotationDelete}selectedAnnotationId={selectedAnnotationId}onSelectAnnotation={handleSelectAnnotation}- autoCaptions={autoCaptions}- onCaptionSpanChange={handleCaptionSpanChange}- selectedCaptionId={selectedCaptionId}- onSelectCaption={handleSelectCaption}- onClearAutoCaptions={handleClearAutoCaptions}aspectRatio={aspectRatio}onAspectRatioChange={setAspectRatio}onOpenCropEditor={handleOpenCropEditor}isCropped={isCropped}- timeSelection={timeSelection}- onTimeSelectionChange={setTimeSelection}- isMasterSelected={isMasterSelected}- onSelectMaster={handleSelectMaster}- timelineMode={timelineMode}- onTimelineModeChange={setTimelineMode}/></div></Panel>@@ -3840,28 +3435,24 @@ export default function VideoEditor() {onAspectRatioChange={setAspectRatio}selectedAnnotationId={selectedAnnotationId}annotationRegions={annotationRegions}- onSeek={(time) => videoPlaybackRef.current?.seek(time)}autoCaptions={autoCaptions}- onAutoCaptionsChange={setAutoCaptions}autoCaptionSettings={autoCaptionSettings}whisperExecutablePath={whisperExecutablePath}whisperModelPath={whisperModelPath}whisperModelDownloadStatus={whisperModelDownloadStatus}whisperModelDownloadProgress={whisperModelDownloadProgress}isGeneratingCaptions={isGeneratingCaptions}- autoCaptionProgress={autoCaptionProgress}onAutoCaptionSettingsChange={setAutoCaptionSettings}onPickWhisperExecutable={handlePickWhisperExecutable}onPickWhisperModel={handlePickWhisperModel}onGenerateAutoCaptions={handleGenerateAutoCaptions}onClearAutoCaptions={handleClearAutoCaptions}- onDownloadWhisperModel={handleDownloadWhisperModel}- onDeleteWhisperModel={handleDeleteWhisperModel}+ onDownloadWhisperSmallModel={handleDownloadWhisperSmallModel}+ onDeleteWhisperSmallModel={handleDeleteWhisperSmallModel}onAnnotationContentChange={handleAnnotationContentChange}onAnnotationTypeChange={handleAnnotationTypeChange}onAnnotationStyleChange={handleAnnotationStyleChange}onAnnotationFigureDataChange={handleAnnotationFigureDataChange}- onAnnotationBlurIntensityChange={handleAnnotationBlurIntensityChange}onAnnotationDelete={handleAnnotationDelete}selectedSpeedId={selectedSpeedId}selectedSpeedValue={@@ -3871,26 +3462,6 @@ export default function VideoEditor() {}onSpeedChange={handleSpeedChange}onSpeedDelete={handleSpeedDelete}- audioRegions={audioRegions}- selectedAudioId={selectedAudioId}- onAudioVolumeChange={handleAudioVolumeChange}- onAudioMutedChange={handleAudioMutedChange}- onAudioSoloedChange={handleAudioSoloedChange}- onAudioFadeInMsChange={handleAudioFadeInMsChange}- onAudioFadeOutMsChange={handleAudioFadeOutMsChange}- onAudioDelete={handleAudioDelete}- selectedCaptionId={selectedCaptionId}- onSelectCaption={handleSelectCaption}- timeSelection={timeSelection}- isMasterSelected={isMasterSelected}- masterAudioVolume={masterAudioVolume}- masterAudioMuted={masterAudioMuted}- masterAudioSoloed={masterAudioSoloed}- videoDuration={duration}- videoPath={videoPath || undefined}- onMasterAudioVolumeChange={setMasterAudioVolume}- onMasterAudioMutedChange={setMasterAudioMuted}- onMasterAudioSoloedChange={setMasterAudioSoloed}/></div></div>diff --git a/src/components/video-editor/VideoPlayback.tsx b/src/components/video-editor/VideoPlayback.tsxindex a1fdf222..0e8fe195 100644--- a/src/components/video-editor/VideoPlayback.tsx+++ b/src/components/video-editor/VideoPlayback.tsx@@ -202,10 +202,8 @@ interface VideoPlaybackProps {cursorClickBounceDuration?: number;cursorSway?: number;volume?: number;- timeSelection?: import("./types").TimeSelection | null;}-export interface VideoPlaybackRef {video: HTMLVideoElement | null;app: Application | null;@@ -215,7 +213,6 @@ export interface VideoPlaybackRef {play: () => Promise<void>;pause: () => void;refreshFrame: () => Promise<void>;- seek: (time: number) => void;}const VideoPlayback = forwardRef<VideoPlaybackRef, VideoPlaybackProps>(@@ -271,9 +268,7 @@ const VideoPlayback = forwardRef<VideoPlaybackRef, VideoPlaybackProps>(cursorClickBounceDuration = DEFAULT_CURSOR_CLICK_BOUNCE_DURATION,cursorSway = DEFAULT_CURSOR_SWAY,volume = 1,- timeSelection = null,},-ref,) => {const videoRef = useRef<HTMLVideoElement | null>(null);@@ -351,8 +346,6 @@ const VideoPlayback = forwardRef<VideoPlaybackRef, VideoPlaybackProps>(const cursorClickBounceRef = useRef(cursorClickBounce);const cursorClickBounceDurationRef = useRef(cursorClickBounceDuration);const cursorSwayRef = useRef(cursorSway);- const timeSelectionRef = useRef(timeSelection);-const activeCaptionLayout = useMemo(() => {if (!autoCaptionSettings?.enabled || autoCaptions.length === 0 || typeof document === "undefined") {@@ -667,11 +660,6 @@ const VideoPlayback = forwardRef<VideoPlaybackRef, VideoPlaybackProps>(video.currentTime = nudgeTarget;});},- seek: (time: number) => {- const video = videoRef.current;- if (!video) return;- video.currentTime = time;- },}));const updateFocusFromClientPoint = (clientX: number, clientY: number) => {@@ -847,11 +835,6 @@ const VideoPlayback = forwardRef<VideoPlaybackRef, VideoPlaybackProps>(cursorSwayRef.current = cursorSway;}, [cursorSway]);- useEffect(() => {- timeSelectionRef.current = timeSelection;- }, [timeSelection]);--useEffect(() => {currentTimeRef.current = currentTime * 1000;}, [currentTime]);@@ -1194,10 +1177,8 @@ const VideoPlayback = forwardRef<VideoPlaybackRef, VideoPlaybackProps>(onTimeUpdate,trimRegionsRef,speedRegionsRef,- timeSelectionRef,});-video.addEventListener("play", handlePlay);video.addEventListener("pause", handlePause);video.addEventListener("ended", handlePause);diff --git a/src/components/video-editor/editorPreferences.ts b/src/components/video-editor/editorPreferences.tsindex 0a5d132e..6523de7b 100644--- a/src/components/video-editor/editorPreferences.ts+++ b/src/components/video-editor/editorPreferences.ts@@ -33,9 +33,6 @@ type PersistedEditorControls = Pick<| "gifFrameRate"| "gifLoop"| "gifSizePreset"- | "masterAudioMuted"- | "masterAudioSoloed"- | "masterAudioVolume">;type PartialEditorControls = Partial<PersistedEditorControls>;@@ -46,7 +43,6 @@ export interface EditorPreferences extends PersistedEditorControls {customWallpapers: string[];whisperExecutablePath: string | null;whisperModelPath: string | null;- whisperSelectedModel: string;}export const EDITOR_PREFERENCES_STORAGE_KEY = "recordly.editor.preferences";@@ -85,15 +81,11 @@ export const DEFAULT_EDITOR_PREFERENCES: EditorPreferences = {gifFrameRate: DEFAULT_EDITOR_CONTROLS.gifFrameRate,gifLoop: DEFAULT_EDITOR_CONTROLS.gifLoop,gifSizePreset: DEFAULT_EDITOR_CONTROLS.gifSizePreset,- masterAudioMuted: DEFAULT_EDITOR_CONTROLS.masterAudioMuted,- masterAudioSoloed: DEFAULT_EDITOR_CONTROLS.masterAudioSoloed,- masterAudioVolume: DEFAULT_EDITOR_CONTROLS.masterAudioVolume,customAspectWidth: "16",customAspectHeight: "9",customWallpapers: [],whisperExecutablePath: null,whisperModelPath: null,- whisperSelectedModel: "small",};function normalizePositiveIntegerString(value: unknown, fallback: string): string {@@ -167,9 +159,6 @@ function normalizeEditorControls(gifFrameRate: raw.gifFrameRate ?? fallback.gifFrameRate,gifLoop: raw.gifLoop ?? fallback.gifLoop,gifSizePreset: raw.gifSizePreset ?? fallback.gifSizePreset,- masterAudioMuted: raw.masterAudioMuted ?? fallback.masterAudioMuted,- masterAudioSoloed: raw.masterAudioSoloed ?? fallback.masterAudioSoloed,- masterAudioVolume: raw.masterAudioVolume ?? fallback.masterAudioVolume,};const normalized = normalizeProjectEditor(candidate);@@ -206,9 +195,6 @@ function normalizeEditorControls(gifFrameRate: normalized.gifFrameRate,gifLoop: normalized.gifLoop,gifSizePreset: normalized.gifSizePreset,- masterAudioMuted: normalized.masterAudioMuted,- masterAudioSoloed: normalized.masterAudioSoloed,- masterAudioVolume: normalized.masterAudioVolume,};}@@ -234,10 +220,6 @@ export function normalizeEditorPreferences(normalizeNullablePath(raw.whisperExecutablePath) ?? fallback.whisperExecutablePath,whisperModelPath:normalizeNullablePath(raw.whisperModelPath) ?? fallback.whisperModelPath,- whisperSelectedModel:- typeof raw.whisperSelectedModel === "string"- ? raw.whisperSelectedModel- : fallback.whisperSelectedModel,};}diff --git a/src/components/video-editor/projectPersistence.ts b/src/components/video-editor/projectPersistence.tsindex 1cf10469..c5d25385 100644--- a/src/components/video-editor/projectPersistence.ts+++ b/src/components/video-editor/projectPersistence.ts@@ -94,11 +94,6 @@ export interface ProjectEditorState {gifFrameRate: GifFrameRate;gifLoop: boolean;gifSizePreset: GifSizePreset;- masterAudioMuted: boolean;- masterAudioSoloed: boolean;- masterAudioVolume: number;- audioTrackVolume: number;- isMasterSelected?: boolean;}export interface EditorProjectData {@@ -341,10 +336,7 @@ export function normalizeProjectEditor(editor: Partial<ProjectEditorState>): Proid: region.id,startMs,endMs,- type:- region.type === "image" || region.type === "figure" || region.type === "blur"- ? region.type- : "text",+ type: region.type === "image" || region.type === "figure" ? region.type : "text",content: typeof region.content === "string" ? region.content : "",textContent: typeof region.textContent === "string" ? region.textContent : undefined,imageContent: typeof region.imageContent === "string" ? region.imageContent : undefined,@@ -387,11 +379,10 @@ export function normalizeProjectEditor(editor: Partial<ProjectEditorState>): ProzIndex: isFiniteNumber(region.zIndex) ? region.zIndex : index + 1,figureData: region.figureData? {- ...DEFAULT_FIGURE_DATA,- ...region.figureData,- }+ ...DEFAULT_FIGURE_DATA,+ ...region.figureData,+ }: undefined,- blurIntensity: isFiniteNumber(region.blurIntensity) ? region.blurIntensity : undefined,};}): [];@@ -412,11 +403,7 @@ export function normalizeProjectEditor(editor: Partial<ProjectEditorState>): ProstartMs,endMs,audioPath: typeof region.audioPath === "string" ? region.audioPath : "",- volume: isFiniteNumber(region.volume) ? clamp(region.volume, 0, 2) : 1,- muted: typeof region.muted === "boolean" ? region.muted : false,- soloed: typeof region.soloed === "boolean" ? region.soloed : false,- fadeInMs: isFiniteNumber(region.fadeInMs) ? clamp(region.fadeInMs, 0, 10000) : 0,- fadeOutMs: isFiniteNumber(region.fadeOutMs) ? clamp(region.fadeOutMs, 0, 10000) : 0,+ volume: isFiniteNumber(region.volume) ? clamp(region.volume, 0, 1) : 1,};}): [];@@ -513,14 +500,6 @@ export function normalizeProjectEditor(editor: Partial<ProjectEditorState>): ProbackgroundOpacity: isFiniteNumber(rawAutoCaptionSettings.backgroundOpacity)? clamp(rawAutoCaptionSettings.backgroundOpacity, 0, 1): DEFAULT_AUTO_CAPTION_SETTINGS.backgroundOpacity,- selectedModel: typeof rawAutoCaptionSettings.selectedModel === "string"- ? rawAutoCaptionSettings.selectedModel- : DEFAULT_AUTO_CAPTION_SETTINGS.selectedModel,- generationRange:- rawAutoCaptionSettings.generationRange === "full" ||- rawAutoCaptionSettings.generationRange === "selected"- ? rawAutoCaptionSettings.generationRange- : "full",};const rawCropX = isFiniteNumber(editor.cropRegion?.x)@@ -696,11 +675,6 @@ export function normalizeProjectEditor(editor: Partial<ProjectEditorState>): Proeditor.gifSizePreset === "original"? editor.gifSizePreset: "medium",- masterAudioMuted: typeof editor.masterAudioMuted === "boolean" ? editor.masterAudioMuted : false,- masterAudioSoloed: typeof editor.masterAudioSoloed === "boolean" ? editor.masterAudioSoloed : false,- masterAudioVolume: isFiniteNumber(editor.masterAudioVolume) ? clamp(editor.masterAudioVolume, 0, 2) : 1,- audioTrackVolume: isFiniteNumber(editor.audioTrackVolume) ? clamp(editor.audioTrackVolume, 0, 2) : 1,- isMasterSelected: Boolean(editor.isMasterSelected),};}diff --git a/src/components/video-editor/timeline/Item.tsx b/src/components/video-editor/timeline/Item.tsxindex 655ffb16..cc387ea9 100644--- a/src/components/video-editor/timeline/Item.tsx+++ b/src/components/video-editor/timeline/Item.tsx@@ -1,13 +1,9 @@import type { Span } from "dnd-timeline";import { useItem } from "dnd-timeline";import { Gauge, MessageSquare, Music, Scissors, ZoomIn } from "lucide-react";-import { useEffect, useMemo, useRef, useState } from "react";+import { useMemo } from "react";import { cn } from "@/lib/utils";import glassStyles from "./ItemGlass.module.css";-import { generateWaveform } from "@/utils/audioWaveform";---interface ItemProps {id: string;@@ -18,14 +14,7 @@ interface ItemProps {onSelect?: () => void;zoomDepth?: number;speedValue?: number;- audioPath?: string;- variant?: 'zoom' | 'trim' | 'annotation' | 'speed' | 'audio' | 'caption' | 'caption-range';- isDraggable?: boolean;- isResizable?: boolean;- muted?: boolean;- fadeInMs?: number;- fadeOutMs?: number;- timelineMode?: 'move' | 'select';+ variant?: 'zoom' | 'trim' | 'annotation' | 'speed' | 'audio';}// Map zoom depth to multiplier labels@@ -56,69 +45,19 @@ export default function Item({onSelect,zoomDepth = 1,speedValue,- audioPath,variant = "zoom",children,- isDraggable = true,- isResizable = true,- muted = false,- fadeInMs,- fadeOutMs,- timelineMode = 'move',}: ItemProps) {- const isDraggableEffective = isDraggable && timelineMode === 'move';-const { setNodeRef, attributes, listeners, itemStyle, itemContentStyle } = useItem({id,span,- disabled: !isDraggableEffective,data: { rowId },});- const durationMs = span.end - span.start;-const isZoom = variant === 'zoom';const isTrim = variant === 'trim';const isSpeed = variant === 'speed';const isAudio = variant === 'audio';- const isCaption = variant === 'caption';- const isCaptionRange = variant === 'caption-range';-- const [waveform, setWaveform] = useState<number[] | null>(null);-- useEffect(() => {- if (isAudio && audioPath) {- generateWaveform(audioPath).then((peaks) => {- setWaveform(peaks);- });- }- }, [isAudio, audioPath]);-- const mouseDownPosRef = useRef({ x: 0, y: 0 });-- const handlePointerDown = (e: React.PointerEvent) => {- mouseDownPosRef.current = { x: e.clientX, y: e.clientY };- // If dragging is enabled, let dnd-timeline handle its part- if (isDraggableEffective) {- listeners?.onPointerDown(e);- }- };-- const handlePointerUp = (e: React.PointerEvent) => {- // We MUST NOT stop propagation on the pointer-up event.- // Standard dnd libraries (like dnd-timeline) need this event to bubble- // up to the window/document to successfully terminate the drag state.- // If we stop it here, the item stays 'sticky' to the mouse.- const deltaX = Math.abs(e.clientX - mouseDownPosRef.current.x);- const deltaY = Math.abs(e.clientY - mouseDownPosRef.current.y);-- if (deltaX < 5 && deltaY < 5) {- onSelect?.();- }- };---const glassClass = isZoom? glassStyles.glassGreen@@ -128,10 +67,6 @@ export default function Item({? glassStyles.glassAmber: isAudio? glassStyles.glassPurple- : isCaption- ? glassStyles.glassCyan- : isCaptionRange- ? glassStyles.glassCyanDashed: glassStyles.glassYellow;const endCapColor = isZoom@@ -142,10 +77,6 @@ export default function Item({? '#d97706': isAudio? '#a855f7'- : isCaption- ? '#0891b2'- : isCaptionRange- ? '#06b6d4': '#B4A046';const timeLabel = useMemo(@@ -160,99 +91,37 @@ export default function Item({<divref={setNodeRef}style={safeItemStyle}- {...(isDraggableEffective ? attributes : {})}- onPointerDown={handlePointerDown}- onPointerUp={handlePointerUp}- onMouseDown={(e) => {- // Prevent background selection logic in Move mode- if (timelineMode === 'move') {- e.stopPropagation();- }- }}- onClick={(e) => {- // Prevent the timeline background's onClick (seeking) from firing- // when we click on a track item.- e.stopPropagation();- }}+ {...listeners}+ {...attributes}+ onPointerDownCapture={() => onSelect?.()}className="group h-full">-<div className="h-full" style={{ ...itemContentStyle, minWidth: 24, height: "100%" }}><divclassName={cn(glassClass,- "w-full h-full overflow-hidden flex items-center justify-center gap-1.5 relative",- isDraggableEffective ? "cursor-grab active:cursor-grabbing" : "cursor-default",- isSelected && glassStyles.selected,- muted && "opacity-40 grayscale-[0.5]"+ "w-full h-full overflow-hidden flex items-center justify-center gap-1.5 cursor-grab active:cursor-grabbing relative",+ isSelected && glassStyles.selected)}style={{ height: "100%", minHeight: 22, color: '#fff', minWidth: 24 }}onClick={(event) => {event.stopPropagation();+ onSelect?.();}}>-- {/* Waveform Background for Audio */}- {isAudio && waveform && (- <div className="absolute inset-0 z-0 opacity-30 flex items-center pointer-events-none px-4">- <svg- width="100%"- height="80%"- viewBox={`0 0 ${waveform.length} 100`}- preserveAspectRatio="none"- className="text-white"- >- {waveform.map((peak, i) => (- <rect- key={i}- x={i}- y={50 - (peak * 50)}- width={0.8}- height={peak * 100}- fill="currentColor"- rx={0.2}- />- ))}- </svg>- </div>- )}-- {/* Fade Visualizations */}- {isAudio && (fadeInMs || fadeOutMs) && (- <div className="absolute inset-0 z-[5] pointer-events-none flex">- {fadeInMs && fadeInMs > 0 && (- <div- className="h-full bg-gradient-to-r from-black/40 to-transparent"- style={{ width: `${(fadeInMs / durationMs) * 100}%` }}- />- )}- <div className="flex-1" />- {fadeOutMs && fadeOutMs > 0 && (- <div- className="h-full bg-gradient-to-l from-black/40 to-transparent"- style={{ width: `${(fadeOutMs / durationMs) * 100}%` }}- />- )}- </div>- )}-- {isResizable && (- <>- <div- className={cn(glassStyles.zoomEndCap, glassStyles.left)}- style={{ cursor: 'col-resize', pointerEvents: 'auto', width: 8, opacity: 0.9, background: endCapColor }}- title="Resize left"- />- <div- className={cn(glassStyles.zoomEndCap, glassStyles.right)}- style={{ cursor: 'col-resize', pointerEvents: 'auto', width: 8, opacity: 0.9, background: endCapColor }}- title="Resize right"- />- </>- )}+ <div+ className={cn(glassStyles.zoomEndCap, glassStyles.left)}+ style={{ cursor: 'col-resize', pointerEvents: 'auto', width: 8, opacity: 0.9, background: endCapColor }}+ title="Resize left"+ />+ <div+ className={cn(glassStyles.zoomEndCap, glassStyles.right)}+ style={{ cursor: 'col-resize', pointerEvents: 'auto', width: 8, opacity: 0.9, background: endCapColor }}+ title="Resize right"+ />{/* Content */}- <div className="relative z-10 flex flex-col items-center justify-center text-white/90 opacity-80 group-hover:opacity-100 transition-opacity select-none overflow-hidden max-w-full">- <div className="flex items-center gap-1.5 max-w-full">+ <div className="relative z-10 flex flex-col items-center justify-center text-white/90 opacity-80 group-hover:opacity-100 transition-opacity select-none overflow-hidden">+ <div className="flex items-center gap-1.5">{isZoom ? (<><ZoomIn className="w-3.5 h-3.5 shrink-0" />@@ -277,7 +146,7 @@ export default function Item({) : isAudio ? (<><Music className="w-3.5 h-3.5 shrink-0" />- <span className="text-[11px] font-semibold tracking-tight truncate max-w-full px-2">+ <span className="text-[11px] font-semibold tracking-tight truncate max-w-full">{children}</span></>diff --git a/src/components/video-editor/timeline/ItemGlass.module.css b/src/components/video-editor/timeline/ItemGlass.module.cssindex deedc7a9..95cfe5e3 100644--- a/src/components/video-editor/timeline/ItemGlass.module.css+++ b/src/components/video-editor/timeline/ItemGlass.module.css@@ -128,32 +128,6 @@z-index: 10;}-.glassCyan {- position: relative;- border-radius: 8px;- -corner-smoothing: antialiased;- background: rgba(8, 145, 178, 0.15);- border: 1px solid rgba(8, 145, 178, 0.3);- box-shadow: 0 2px 12px 0 rgba(8, 145, 178, 0.1) inset;- margin: 1px 0;- backdrop-filter: blur(4px);- -webkit-backdrop-filter: blur(4px);- transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);-}--.glassCyan:hover {- background: rgba(8, 145, 178, 0.25);- border-color: rgba(8, 145, 178, 0.5);- box-shadow: 0 4px 20px 0 rgba(8, 145, 178, 0.2) inset;-}--.glassCyan.selected {- background: rgba(8, 145, 178, 0.35);- border-color: #0891b2;- box-shadow: 0 0 0 1px #0891b2, 0 4px 20px 0 rgba(8, 145, 178, 0.3) inset;- z-index: 10;-}-.zoomEndCap {position: absolute;top: 0;@@ -174,39 +148,10 @@.glassAmber:hover .zoomEndCap,.glassAmber.selected .zoomEndCap,.glassPurple:hover .zoomEndCap,-.glassPurple.selected .zoomEndCap,-.glassCyan.selected .zoomEndCap,-.glassCyanDashed:hover .zoomEndCap,-.glassCyanDashed.selected .zoomEndCap {+.glassPurple.selected .zoomEndCap {opacity: 1;}-.glassCyanDashed {- position: relative;- border-radius: 8px;- -corner-smoothing: antialiased;- background: rgba(8, 145, 178, 0.05);- border: 1px dashed rgba(8, 145, 178, 0.5);- box-shadow: 0 2px 12px 0 rgba(8, 145, 178, 0.05) inset;- margin: 1px 0;- backdrop-filter: blur(2px);- -webkit-backdrop-filter: blur(2px);- transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);-}--.glassCyanDashed:hover {- background: rgba(8, 145, 178, 0.1);- border-color: rgba(8, 145, 178, 0.7);-}--.glassCyanDashed.selected {- background: rgba(8, 145, 178, 0.2);- border-color: #0891b2;- border-style: solid;- box-shadow: 0 0 0 1px #0891b2, 0 4px 20px 0 rgba(8, 145, 178, 0.15) inset;- z-index: 10;-}-.zoomEndCap.left {left: 0;cursor: ew-resize;diff --git a/src/components/video-editor/timeline/KeyframeMarkers.tsx b/src/components/video-editor/timeline/KeyframeMarkers.tsxindex 59bbcb52..d5c18be3 100644--- a/src/components/video-editor/timeline/KeyframeMarkers.tsx+++ b/src/components/video-editor/timeline/KeyframeMarkers.tsx@@ -23,7 +23,7 @@ const KeyframeMarkers: React.FC<KeyframeMarkersProps> = ({videoDurationMs,timelineRef}) => {- const { sidebarWidth = 0, range, valueToPixels, pixelsToValue } = useTimelineContext();+ const { sidebarWidth, range, valueToPixels, pixelsToValue } = useTimelineContext();const [draggingKeyframeId, setDraggingKeyframeId] = useState<string | null>(null);useEffect(() => {diff --git a/src/components/video-editor/timeline/Row.tsx b/src/components/video-editor/timeline/Row.tsxindex ee487038..434aab29 100644--- a/src/components/video-editor/timeline/Row.tsx+++ b/src/components/video-editor/timeline/Row.tsx@@ -7,10 +7,9 @@ interface RowProps extends RowDefinition {hint?: string;isEmpty?: boolean;labelColor?: string;- controls?: React.ReactNode;}-export default function Row({ id, children, label, hint, isEmpty, labelColor = '#666', controls }: RowProps) {+export default function Row({ id, children, label, hint, isEmpty, labelColor = '#666' }: RowProps) {const { setNodeRef, rowWrapperStyle, rowStyle } = useRow({ id });return (@@ -18,20 +17,12 @@ export default function Row({ id, children, label, hint, isEmpty, labelColor = 'className="border-b border-[#18181b] bg-[#18181b] relative flex-1 min-h-[26px]"style={{ ...rowWrapperStyle, marginBottom: 2 }}>- {(label || controls) && (+ {label && (<div- className="absolute left-1.5 top-1/2 -translate-y-1/2 z-20 flex items-center gap-2"- style={{ writingMode: 'horizontal-tb' }}+ className="absolute left-1.5 top-1/2 -translate-y-1/2 text-[9px] font-semibold uppercase tracking-widest z-20 pointer-events-none select-none"+ style={{ color: labelColor, writingMode: 'horizontal-tb' }}>- {label && (- <div- className="text-[9px] font-semibold uppercase tracking-widest select-none pointer-events-none"- style={{ color: labelColor }}- >- {label}- </div>- )}- {controls}+ {label}</div>)}{isEmpty && hint && (diff --git a/src/components/video-editor/timeline/TimelineEditor.tsx b/src/components/video-editor/timeline/TimelineEditor.tsxindex c3edf44d..ee0080e0 100644--- a/src/components/video-editor/timeline/TimelineEditor.tsx+++ b/src/components/video-editor/timeline/TimelineEditor.tsx@@ -2,12 +2,12 @@ import { useCallback, useEffect, useMemo, useRef, useState, type KeyboardEvent aimport { useTimelineContext } from "dnd-timeline";import { Button } from "@/components/ui/button";import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuTrigger,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,} from "@/components/ui/dropdown-menu";-import { Plus, Scissors, ZoomIn, MessageSquare, ChevronDown, Check, Gauge, WandSparkles, Music, Crop, MousePointer2, BoxSelect } from "lucide-react";+import { Plus, Scissors, ZoomIn, MessageSquare, ChevronDown, Check, Gauge, WandSparkles, Music, Crop } from "lucide-react";import { toast } from "sonner";import { cn } from "@/lib/utils";import { v4 as uuidv4 } from 'uuid';@@ -23,7 +23,7 @@ import Row from "./Row";import Item from "./Item";import KeyframeMarkers from "./KeyframeMarkers";import type { Range, Span } from "dnd-timeline";-import type { ZoomRegion, TrimRegion, AnnotationRegion, SpeedRegion, AudioRegion, CursorTelemetryPoint, ZoomFocus, CaptionCue, TimeSelection } from "../types";+import type { ZoomRegion, TrimRegion, AnnotationRegion, SpeedRegion, AudioRegion, CursorTelemetryPoint, ZoomFocus } from "../types";import { toFileUrl } from "../projectPersistence";import { detectInteractionCandidates, normalizeCursorTelemetry } from "./zoomSuggestionUtils";@@ -31,17 +31,13 @@ const ZOOM_ROW_ID = "row-zoom";const TRIM_ROW_ID = "row-trim";const ANNOTATION_ROW_ID = "row-annotation";const SPEED_ROW_ID = "row-speed";-const ORIGINAL_AUDIO_ROW_ID = "row-original-audio";const AUDIO_ROW_ID = "row-audio";-const CAPTION_ROW_ID = "row-caption";const FALLBACK_RANGE_MS = 1000;const TARGET_MARKER_COUNT = 12;const SUGGESTION_SPACING_MS = 1800;-const DRAG_THRESHOLD_PX = 5;interface TimelineEditorProps {videoDuration: number;- videoPath?: string;currentTime: number;onSeek?: (time: number) => void;cursorTelemetry?: CursorTelemetryPoint[];@@ -74,40 +70,19 @@ interface TimelineEditorProps {audioRegions?: AudioRegion[];onAudioAdded?: (span: Span, audioPath: string) => void;onAudioSpanChange?: (id: string, span: Span) => void;- onAudioMutedChange?: (id: string, muted: boolean) => void;- onAudioSoloedChange?: (id: string, soloed: boolean) => void;onAudioDelete?: (id: string) => void;selectedAudioId?: string | null;onSelectAudio?: (id: string | null) => void;- masterAudioMuted?: boolean;- onMasterAudioMutedChange?: (muted: boolean) => void;- masterAudioSoloed?: boolean;- onMasterAudioSoloedChange?: (soloed: boolean) => void;- masterAudioVolume?: number;- audioTrackVolume?: number;- onMasterAudioVolumeChange?: (volume: number) => void;- onAudioTrackVolumeChange?: (volume: number) => void;- autoCaptions?: CaptionCue[];- onCaptionSpanChange?: (id: string, span: Span) => void;- selectedCaptionId?: string | null;- onSelectCaption?: (id: string | null) => void;- onClearAutoCaptions?: () => void;aspectRatio: AspectRatio;onAspectRatioChange: (aspectRatio: AspectRatio) => void;onOpenCropEditor?: () => void;isCropped?: boolean;- timeSelection?: TimeSelection | null;- onTimeSelectionChange?: (selection: TimeSelection | null) => void;- isMasterSelected?: boolean;- onSelectMaster?: (selected: boolean) => void;- timelineMode?: 'move' | 'select';- onTimelineModeChange?: (mode: 'move' | 'select') => void;}interface TimelineScaleConfig {- minItemDurationMs: number;- defaultItemDurationMs: number;- minVisibleRangeMs: number;+ minItemDurationMs: number;+ defaultItemDurationMs: number;+ minVisibleRangeMs: number;}interface TimelineRenderItem {@@ -117,383 +92,351 @@ interface TimelineRenderItem {label: string;zoomDepth?: number;speedValue?: number;- audioPath?: string;- variant: 'zoom' | 'trim' | 'annotation' | 'speed' | 'audio' | 'caption';- muted?: boolean;- soloed?: boolean;- fadeInMs?: number;- fadeOutMs?: number;+ variant: 'zoom' | 'trim' | 'annotation' | 'speed' | 'audio';}const SCALE_CANDIDATES = [- { intervalSeconds: 0.05, gridSeconds: 0.01 },- { intervalSeconds: 0.1, gridSeconds: 0.02 },- { intervalSeconds: 0.25, gridSeconds: 0.05 },- { intervalSeconds: 0.5, gridSeconds: 0.1 },- { intervalSeconds: 1, gridSeconds: 0.25 },- { intervalSeconds: 2, gridSeconds: 0.5 },- { intervalSeconds: 5, gridSeconds: 1 },- { intervalSeconds: 10, gridSeconds: 2 },- { intervalSeconds: 15, gridSeconds: 3 },- { intervalSeconds: 30, gridSeconds: 5 },- { intervalSeconds: 60, gridSeconds: 10 },- { intervalSeconds: 120, gridSeconds: 20 },- { intervalSeconds: 300, gridSeconds: 30 },- { intervalSeconds: 600, gridSeconds: 60 },- { intervalSeconds: 900, gridSeconds: 120 },- { intervalSeconds: 1800, gridSeconds: 180 },- { intervalSeconds: 3600, gridSeconds: 300 },+ { intervalSeconds: 0.05, gridSeconds: 0.01 },+ { intervalSeconds: 0.1, gridSeconds: 0.02 },+ { intervalSeconds: 0.25, gridSeconds: 0.05 },+ { intervalSeconds: 0.5, gridSeconds: 0.1 },+ { intervalSeconds: 1, gridSeconds: 0.25 },+ { intervalSeconds: 2, gridSeconds: 0.5 },+ { intervalSeconds: 5, gridSeconds: 1 },+ { intervalSeconds: 10, gridSeconds: 2 },+ { intervalSeconds: 15, gridSeconds: 3 },+ { intervalSeconds: 30, gridSeconds: 5 },+ { intervalSeconds: 60, gridSeconds: 10 },+ { intervalSeconds: 120, gridSeconds: 20 },+ { intervalSeconds: 300, gridSeconds: 30 },+ { intervalSeconds: 600, gridSeconds: 60 },+ { intervalSeconds: 900, gridSeconds: 120 },+ { intervalSeconds: 1800, gridSeconds: 180 },+ { intervalSeconds: 3600, gridSeconds: 300 },];function calculateAxisScale(visibleRangeMs: number): { intervalMs: number; gridMs: number } {- const visibleSeconds = visibleRangeMs / 1000;- const candidate =- SCALE_CANDIDATES.find((scaleCandidate) => {- if (visibleSeconds <= 0) {- return true;- }- return visibleSeconds / scaleCandidate.intervalSeconds <= TARGET_MARKER_COUNT;- }) ?? SCALE_CANDIDATES[SCALE_CANDIDATES.length - 1];-- return {- intervalMs: Math.round(candidate.intervalSeconds * 1000),- gridMs: Math.round(candidate.gridSeconds * 1000),- };+ const visibleSeconds = visibleRangeMs / 1000;+ const candidate =+ SCALE_CANDIDATES.find((scaleCandidate) => {+ if (visibleSeconds <= 0) {+ return true;+ }+ return visibleSeconds / scaleCandidate.intervalSeconds <= TARGET_MARKER_COUNT;+ }) ?? SCALE_CANDIDATES[SCALE_CANDIDATES.length - 1];++ return {+ intervalMs: Math.round(candidate.intervalSeconds * 1000),+ gridMs: Math.round(candidate.gridSeconds * 1000),+ };}function calculateTimelineScale(durationSeconds: number): TimelineScaleConfig {- const totalMs = Math.max(0, Math.round(durationSeconds * 1000));+ const totalMs = Math.max(0, Math.round(durationSeconds * 1000));- const minItemDurationMs = 100;+ const minItemDurationMs = 100;- const defaultItemDurationMs =- totalMs > 0- ? Math.max(minItemDurationMs, Math.min(Math.round(totalMs * 0.05), 30000))- : Math.max(minItemDurationMs, 1000);+ const defaultItemDurationMs =+ totalMs > 0+ ? Math.max(minItemDurationMs, Math.min(Math.round(totalMs * 0.05), 30000))+ : Math.max(minItemDurationMs, 1000);- const minVisibleRangeMs = 300;+ const minVisibleRangeMs = 300;- return {- minItemDurationMs,- defaultItemDurationMs,- minVisibleRangeMs,- };+ return {+ minItemDurationMs,+ defaultItemDurationMs,+ minVisibleRangeMs,+ };}function createInitialRange(totalMs: number): Range {- if (totalMs > 0) {- return { start: 0, end: totalMs };- }+ if (totalMs > 0) {+ return { start: 0, end: totalMs };+ }- return { start: 0, end: FALLBACK_RANGE_MS };+ return { start: 0, end: FALLBACK_RANGE_MS };}function normalizeWheelDeltaToPixels(delta: number, deltaMode: number) {- if (deltaMode === 1) {- return delta * 16;- }+ if (deltaMode === 1) {+ return delta * 16;+ }- if (deltaMode === 2) {- return delta * 240;- }+ if (deltaMode === 2) {+ return delta * 240;+ }- return delta;+ return delta;}function formatTimeLabel(milliseconds: number, intervalMs: number) {- const totalSeconds = milliseconds / 1000;- const hours = Math.floor(totalSeconds / 3600);- const minutes = Math.floor((totalSeconds % 3600) / 60);- const seconds = totalSeconds % 60;-- const fractionalDigits = intervalMs < 250 ? 2 : intervalMs < 1000 ? 1 : 0;-- if (hours > 0) {- const minutesString = minutes.toString().padStart(2, "0");- const secondsString = Math.floor(seconds).toString().padStart(2, "0");- return `${hours}:${minutesString}:${secondsString}`;- }-- if (fractionalDigits > 0) {- const secondsWithFraction = seconds.toFixed(fractionalDigits);- const [wholeSeconds, fraction] = secondsWithFraction.split(".");- return `${minutes}:${wholeSeconds.padStart(2, "0")}.${fraction}`;- }-- return `${minutes}:${Math.floor(seconds).toString().padStart(2, "0")}`;+ const totalSeconds = milliseconds / 1000;+ const hours = Math.floor(totalSeconds / 3600);+ const minutes = Math.floor((totalSeconds % 3600) / 60);+ const seconds = totalSeconds % 60;++ const fractionalDigits = intervalMs < 250 ? 2 : intervalMs < 1000 ? 1 : 0;++ if (hours > 0) {+ const minutesString = minutes.toString().padStart(2, "0");+ const secondsString = Math.floor(seconds).toString().padStart(2, "0");+ return `${hours}:${minutesString}:${secondsString}`;+ }++ if (fractionalDigits > 0) {+ const secondsWithFraction = seconds.toFixed(fractionalDigits);+ const [wholeSeconds, fraction] = secondsWithFraction.split(".");+ return `${minutes}:${wholeSeconds.padStart(2, "0")}.${fraction}`;+ }++ return `${minutes}:${Math.floor(seconds).toString().padStart(2, "0")}`;}-function formatPlayheadTime(ms: number): string {- const s = ms / 1000;- const min = Math.floor(s / 60);- const sec = s % 60;- if (min > 0) return `${min}:${sec.toFixed(1).padStart(4, "0")}`;- return `${sec.toFixed(1)}s`;+ const s = ms / 1000;+ const min = Math.floor(s / 60);+ const sec = s % 60;+ if (min > 0) return `${min}:${sec.toFixed(1).padStart(4, "0")}`;+ return `${sec.toFixed(1)}s`;}function PlaybackCursor({- currentTimeMs,- videoDurationMs,- onSeek,- timelineRef,- keyframes = [],- timeSelection = null,+ currentTimeMs,+ videoDurationMs,+ onSeek,+ timelineRef,+ keyframes = [],}: {-- currentTimeMs: number;- videoDurationMs: number;- onSeek?: (time: number) => void;- timelineRef: React.RefObject<HTMLDivElement>;- keyframes?: { id: string; time: number }[];- timeSelection?: import('../types').TimeSelection | null;+ currentTimeMs: number;+ videoDurationMs: number;+ onSeek?: (time: number) => void;+ timelineRef: React.RefObject<HTMLDivElement>;+ keyframes?: { id: string; time: number }[];}) {-- const { sidebarWidth = 0, direction, range, valueToPixels, pixelsToValue } = useTimelineContext();- const sideProperty = direction === "rtl" ? "right" : "left";- const [isDragging, setIsDragging] = useState(false);-- useEffect(() => {- if (!isDragging) return;-- const handleMouseMove = (e: MouseEvent) => {- if (!timelineRef.current || !onSeek) return;-- const rect = timelineRef.current.getBoundingClientRect();- const clickX = e.clientX - rect.left - sidebarWidth;-- // Allow dragging outside to 0 or max, but clamp the value- const relativeMs = pixelsToValue(clickX);- let absoluteMs = Math.max(0, Math.min(range.start + relativeMs, videoDurationMs));-- // Snap to nearby keyframe if within threshold (150ms)- const snapThresholdMs = 150;- const nearbyKeyframe = keyframes.find(- (kf) =>- Math.abs(kf.time - absoluteMs) <= snapThresholdMs &&- kf.time >= range.start &&- kf.time <= range.end,- );-- if (nearbyKeyframe) {- absoluteMs = nearbyKeyframe.time;- }-- onSeek(absoluteMs / 1000);- };-- const handleMouseUp = (e: MouseEvent) => {- if (isDragging && timeSelection && onSeek) {- const rect = timelineRef.current?.getBoundingClientRect();- if (rect) {- const clickX = e.clientX - rect.left - sidebarWidth;- const relativeMs = pixelsToValue(clickX);- const absoluteMs = Math.max(0, Math.min(range.start + relativeMs, videoDurationMs));-- // If released outside selection, jump back to selection start- if (absoluteMs < timeSelection.startMs || absoluteMs > timeSelection.endMs) {- onSeek(timeSelection.startMs / 1000);- }- }- }- setIsDragging(false);- document.body.style.cursor = "";- };--- window.addEventListener("mousemove", handleMouseMove);- window.addEventListener("mouseup", handleMouseUp);- document.body.style.cursor = "ew-resize";-- return () => {- window.removeEventListener("mousemove", handleMouseMove);- window.removeEventListener("mouseup", handleMouseUp);- document.body.style.cursor = "";- };- }, [- isDragging,- onSeek,- timelineRef,- sidebarWidth,- range.start,- range.end,- videoDurationMs,- pixelsToValue,- keyframes,- ]);-- if (videoDurationMs <= 0 || currentTimeMs < 0) {- return null;- }-- const clampedTime = Math.min(currentTimeMs, videoDurationMs);-- if (clampedTime < range.start || clampedTime > range.end) {- return null;- }-- const offset = valueToPixels(clampedTime - range.start);-- return (- <div- className="absolute top-0 bottom-0 z-50 group/cursor"- style={{- [sideProperty === "right" ? "marginRight" : "marginLeft"]: `${sidebarWidth - 1}px`,- pointerEvents: "none", // Allow clicks to pass through to timeline, but we'll enable pointer events on the handle- }}- >- <div- className="absolute top-0 bottom-0 w-[2px] bg-[#2563EB] shadow-[0_0_10px_rgba(37,99,235,0.5)] cursor-ew-resize pointer-events-auto hover:shadow-[0_0_15px_rgba(37,99,235,0.7)] transition-shadow"- style={{- [sideProperty]: `${offset}px`,- }}- onMouseDown={(e) => {- e.stopPropagation(); // Prevent timeline click- setIsDragging(true);- }}- >- <div- className="absolute -top-1 left-1/2 -translate-x-1/2 hover:scale-125 transition-transform"- style={{ width: "16px", height: "16px" }}- >- <div className="w-3 h-3 mx-auto mt-[2px] bg-[#2563EB] rotate-45 rounded-sm shadow-lg border border-white/20" />- </div>- {isDragging && (- <div className="absolute -top-6 left-1/2 -translate-x-1/2 px-1.5 py-0.5 rounded bg-black/80 text-[10px] text-white/90 font-medium tabular-nums whitespace-nowrap border border-white/10 shadow-lg pointer-events-none">- {formatPlayheadTime(clampedTime)}- </div>- )}- </div>- </div>- );+ const { sidebarWidth, direction, range, valueToPixels, pixelsToValue } = useTimelineContext();+ const sideProperty = direction === "rtl" ? "right" : "left";+ const [isDragging, setIsDragging] = useState(false);++ useEffect(() => {+ if (!isDragging) return;++ const handleMouseMove = (e: MouseEvent) => {+ if (!timelineRef.current || !onSeek) return;++ const rect = timelineRef.current.getBoundingClientRect();+ const clickX = e.clientX - rect.left - sidebarWidth;++ // Allow dragging outside to 0 or max, but clamp the value+ const relativeMs = pixelsToValue(clickX);+ let absoluteMs = Math.max(0, Math.min(range.start + relativeMs, videoDurationMs));++ // Snap to nearby keyframe if within threshold (150ms)+ const snapThresholdMs = 150;+ const nearbyKeyframe = keyframes.find(+ (kf) =>+ Math.abs(kf.time - absoluteMs) <= snapThresholdMs &&+ kf.time >= range.start &&+ kf.time <= range.end,+ );++ if (nearbyKeyframe) {+ absoluteMs = nearbyKeyframe.time;+ }++ onSeek(absoluteMs / 1000);+ };++ const handleMouseUp = () => {+ setIsDragging(false);+ document.body.style.cursor = "";+ };++ window.addEventListener("mousemove", handleMouseMove);+ window.addEventListener("mouseup", handleMouseUp);+ document.body.style.cursor = "ew-resize";++ return () => {+ window.removeEventListener("mousemove", handleMouseMove);+ window.removeEventListener("mouseup", handleMouseUp);+ document.body.style.cursor = "";+ };+ }, [+ isDragging,+ onSeek,+ timelineRef,+ sidebarWidth,+ range.start,+ range.end,+ videoDurationMs,+ pixelsToValue,+ keyframes,+ ]);++ if (videoDurationMs <= 0 || currentTimeMs < 0) {+ return null;+ }++ const clampedTime = Math.min(currentTimeMs, videoDurationMs);++ if (clampedTime < range.start || clampedTime > range.end) {+ return null;+ }++ const offset = valueToPixels(clampedTime - range.start);++ return (+ <div+ className="absolute top-0 bottom-0 z-50 group/cursor"+ style={{+ [sideProperty === "right" ? "marginRight" : "marginLeft"]: `${sidebarWidth - 1}px`,+ pointerEvents: "none", // Allow clicks to pass through to timeline, but we'll enable pointer events on the handle+ }}+ >+ <div+ className="absolute top-0 bottom-0 w-[2px] bg-[#2563EB] shadow-[0_0_10px_rgba(37,99,235,0.5)] cursor-ew-resize pointer-events-auto hover:shadow-[0_0_15px_rgba(37,99,235,0.7)] transition-shadow"+ style={{+ [sideProperty]: `${offset}px`,+ }}+ onMouseDown={(e) => {+ e.stopPropagation(); // Prevent timeline click+ setIsDragging(true);+ }}+ >+ <div+ className="absolute -top-1 left-1/2 -translate-x-1/2 hover:scale-125 transition-transform"+ style={{ width: "16px", height: "16px" }}+ >+ <div className="w-3 h-3 mx-auto mt-[2px] bg-[#2563EB] rotate-45 rounded-sm shadow-lg border border-white/20" />+ </div>+ {isDragging && (+ <div className="absolute -top-6 left-1/2 -translate-x-1/2 px-1.5 py-0.5 rounded bg-black/80 text-[10px] text-white/90 font-medium tabular-nums whitespace-nowrap border border-white/10 shadow-lg pointer-events-none">+ {formatPlayheadTime(clampedTime)}+ </div>+ )}+ </div>+ </div>+ );}function TimelineAxis({- videoDurationMs,- currentTimeMs,+ videoDurationMs,+ currentTimeMs,}: {- videoDurationMs: number;- currentTimeMs: number;+ videoDurationMs: number;+ currentTimeMs: number;}) {- const { sidebarWidth = 0, direction, range, valueToPixels } = useTimelineContext();- const sideProperty = direction === "rtl" ? "right" : "left";-- const { intervalMs } = useMemo(- () => calculateAxisScale(range.end - range.start),- [range.end, range.start],- );-- const markers = useMemo(() => {- if (intervalMs <= 0) {- return { markers: [], minorTicks: [] };- }-- const maxTime = videoDurationMs > 0 ? videoDurationMs : range.end;- const visibleStart = Math.max(0, Math.min(range.start, maxTime));- const visibleEnd = Math.min(range.end, maxTime);- const markerTimes = new Set<number>();-- const firstMarker = Math.ceil(visibleStart / intervalMs) * intervalMs;-- for (let time = firstMarker; time <= maxTime; time += intervalMs) {- if (time >= visibleStart && time <= visibleEnd) {- markerTimes.add(Math.round(time));- }- }-- if (visibleStart <= maxTime) {- markerTimes.add(Math.round(visibleStart));- }-- if (videoDurationMs > 0) {- markerTimes.add(Math.round(videoDurationMs));- }-- const sorted = Array.from(markerTimes)- .filter((time) => time <= maxTime)- .sort((a, b) => a - b);-- // Generate minor ticks (4 ticks between major intervals)- const minorTicks = [];- const minorInterval = intervalMs / 5;-- for (let time = firstMarker; time <= maxTime; time += minorInterval) {- if (time >= visibleStart && time <= visibleEnd) {- // Skip if it's close to a major marker- const isMajor = Math.abs(time % intervalMs) < 1;- if (!isMajor) {- minorTicks.push(time);- }- }- }-- return {- markers: sorted.map((time) => ({- time,- label: formatTimeLabel(time, intervalMs),- })),- minorTicks,- };- }, [intervalMs, range.end, range.start, videoDurationMs]);-- return (- <div- className="h-8 bg-[#161619] border-b border-white/10 relative overflow-hidden select-none cursor-pointer"- style={{- [sideProperty === "right" ? "marginRight" : "marginLeft"]: `${sidebarWidth}px`,- }}- onMouseDown={(e) => {- // Also allow starting selection from the ruler- (e.currentTarget.parentElement as any)?.__handleMouseDown?.(e);- }}- onClick={(e) => {- // Also allow seeking/clearing from the ruler- (e.currentTarget.parentElement as any)?.__handleTimelineClick?.(e);- }}- >- {/* Minor Ticks */}- {markers.minorTicks.map((time) => {- const offset = valueToPixels(time - range.start);- return (- <div- key={`minor-${time}`}- className="absolute bottom-0 h-1 w-[1px] bg-white/5"- style={{ [sideProperty]: `${offset}px` }}- />- );- })}-- {/* Major Markers */}- {markers.markers.map((marker) => {- const offset = valueToPixels(marker.time - range.start);- const markerStyle: React.CSSProperties = {- position: "absolute",- bottom: 0,- height: "100%",- display: "flex",- flexDirection: "row",- alignItems: "flex-end",- [sideProperty]: `${offset}px`,- };-- return (- <div key={marker.time} style={markerStyle}>- <div className="flex flex-col items-center pb-1">- <div className="h-2 w-[1px] bg-white/20 mb-1" />- <span- className={cn(- "text-[10px] font-medium tabular-nums tracking-tight",- marker.time === currentTimeMs ? "text-[#2563EB]" : "text-slate-500",- )}- >- {marker.label}- </span>- </div>- </div>- );- })}- </div>- );+ const { sidebarWidth, direction, range, valueToPixels } = useTimelineContext();+ const sideProperty = direction === "rtl" ? "right" : "left";++ const { intervalMs } = useMemo(+ () => calculateAxisScale(range.end - range.start),+ [range.end, range.start],+ );++ const markers = useMemo(() => {+ if (intervalMs <= 0) {+ return { markers: [], minorTicks: [] };+ }++ const maxTime = videoDurationMs > 0 ? videoDurationMs : range.end;+ const visibleStart = Math.max(0, Math.min(range.start, maxTime));+ const visibleEnd = Math.min(range.end, maxTime);+ const markerTimes = new Set<number>();++ const firstMarker = Math.ceil(visibleStart / intervalMs) * intervalMs;++ for (let time = firstMarker; time <= maxTime; time += intervalMs) {+ if (time >= visibleStart && time <= visibleEnd) {+ markerTimes.add(Math.round(time));+ }+ }++ if (visibleStart <= maxTime) {+ markerTimes.add(Math.round(visibleStart));+ }++ if (videoDurationMs > 0) {+ markerTimes.add(Math.round(videoDurationMs));+ }++ const sorted = Array.from(markerTimes)+ .filter((time) => time <= maxTime)+ .sort((a, b) => a - b);++ // Generate minor ticks (4 ticks between major intervals)+ const minorTicks = [];+ const minorInterval = intervalMs / 5;++ for (let time = firstMarker; time <= maxTime; time += minorInterval) {+ if (time >= visibleStart && time <= visibleEnd) {+ // Skip if it's close to a major marker+ const isMajor = Math.abs(time % intervalMs) < 1;+ if (!isMajor) {+ minorTicks.push(time);+ }+ }+ }++ return {+ markers: sorted.map((time) => ({+ time,+ label: formatTimeLabel(time, intervalMs),+ })),+ minorTicks,+ };+ }, [intervalMs, range.end, range.start, videoDurationMs]);++ return (+ <div+ className="h-8 bg-[#161619] border-b border-white/10 relative overflow-hidden select-none"+ style={{+ [sideProperty === "right" ? "marginRight" : "marginLeft"]: `${sidebarWidth}px`,+ }}+ >+ {/* Minor Ticks */}+ {markers.minorTicks.map((time) => {+ const offset = valueToPixels(time - range.start);+ return (+ <div+ key={`minor-${time}`}+ className="absolute bottom-0 h-1 w-[1px] bg-white/5"+ style={{ [sideProperty]: `${offset}px` }}+ />+ );+ })}++ {/* Major Markers */}+ {markers.markers.map((marker) => {+ const offset = valueToPixels(marker.time - range.start);+ const markerStyle: React.CSSProperties = {+ position: "absolute",+ bottom: 0,+ height: "100%",+ display: "flex",+ flexDirection: "row",+ alignItems: "flex-end",+ [sideProperty]: `${offset}px`,+ };++ return (+ <div key={marker.time} style={markerStyle}>+ <div className="flex flex-col items-center pb-1">+ <div className="h-2 w-[1px] bg-white/20 mb-1" />+ <span+ className={cn(+ "text-[10px] font-medium tabular-nums tracking-tight",+ marker.time === currentTimeMs ? "text-[#2563EB]" : "text-slate-500",+ )}+ >+ {marker.label}+ </span>+ </div>+ </div>+ );+ })}+ </div>+ );}function Timeline({@@ -506,30 +449,14 @@ function Timeline({onSelectAnnotation,onSelectSpeed,onSelectAudio,- onAudioMutedChange,- onAudioSoloedChange,- audioRegions,- masterAudioMuted = false,- onMasterAudioMutedChange,- masterAudioSoloed = false,- onMasterAudioSoloedChange,- masterAudioVolume = 1,- audioTrackVolume = 1,selectedZoomId,selectedTrimId,selectedAnnotationId,selectedSpeedId,selectedAudioId,- selectedCaptionId,- onSelectCaption,selectAllBlocksActive = false,onClearBlockSelection,keyframes = [],- timeSelection,- onTimeSelectionChange,- isMasterSelected = false,- onSelectMaster,- timelineMode = 'move',}: {items: TimelineRenderItem[];videoDurationMs: number;@@ -540,334 +467,73 @@ function Timeline({onSelectAnnotation?: (id: string | null) => void;onSelectSpeed?: (id: string | null) => void;onSelectAudio?: (id: string | null) => void;- onAudioMutedChange?: (id: string, muted: boolean) => void;- onAudioSoloedChange?: (id: string, soloed: boolean) => void;- audioRegions?: AudioRegion[];- masterAudioMuted?: boolean;- onMasterAudioMutedChange?: (muted: boolean) => void;- masterAudioSoloed?: boolean;- onMasterAudioSoloedChange?: (soloed: boolean) => void;- masterAudioVolume?: number;- audioTrackVolume?: number;- onMasterAudioVolumeChange?: (volume: number) => void;- onAudioTrackVolumeChange?: (volume: number) => void;selectedZoomId: string | null;selectedTrimId?: string | null;selectedAnnotationId?: string | null;selectedSpeedId?: string | null;selectedAudioId?: string | null;- selectedCaptionId?: string | null;- onSelectCaption?: (id: string | null) => void;selectAllBlocksActive?: boolean;onClearBlockSelection?: () => void;keyframes?: { id: string; time: number }[];- timeSelection?: TimeSelection | null;- onTimeSelectionChange?: (selection: TimeSelection | null) => void;- isMasterSelected?: boolean;- onSelectMaster?: (selected: boolean) => void;- timelineMode?: 'move' | 'select';}) {- const { setTimelineRef, style, sidebarWidth = 0, range, pixelsToValue, valueToPixels } = useTimelineContext();- const localTimelineRef = useRef<HTMLDivElement | null>(null);-- const setRefs = useCallback(- (node: HTMLDivElement | null) => {- if (localTimelineRef.current !== node) {- setTimelineRef(node);- localTimelineRef.current = node;- }- },- [setTimelineRef],- );-- const isDraggingSelectionRef = useRef(false);- const selectionAnchorMsRef = useRef<number | null>(null);- const selectionCurrentMsRef = useRef<number | null>(null);- const initialMouseDownPosRef = useRef<{ x: number; y: number } | null>(null);--- const handleMouseDown = useCallback(- (e: React.MouseEvent<HTMLDivElement>) => {- // In Move mode, the timeline background never starts a selection drag.- // Items handle their own drag-and-drop via dnd-timeline.- if (timelineMode !== 'select') return;-- if (videoDurationMs <= 0) return;-- // Capture the rect NOW — e.currentTarget becomes null after React's- // synthetic event is processed and must not be read inside async closures.- const capturedRect = e.currentTarget.getBoundingClientRect();- const clickX = e.clientX - capturedRect.left - sidebarWidth;-- if (clickX < 0) return;-- const relativeMs = pixelsToValue(clickX);- const absoluteMs = Math.max(0, Math.min(range.start + relativeMs, videoDurationMs));-- initialMouseDownPosRef.current = { x: e.clientX, y: e.clientY };- isDraggingSelectionRef.current = false; // Reset drag flag-- if (e.shiftKey) {- // Shift+mousedown: anchor to the far edge of the existing selection,- // or to the current playhead if there is no selection yet.- let anchor = currentTimeMs;- if (timeSelection) {- const distToStart = Math.abs(timeSelection.startMs - absoluteMs);- const distToEnd = Math.abs(timeSelection.endMs - absoluteMs);- anchor = distToStart > distToEnd ? timeSelection.startMs : timeSelection.endMs;- }-- selectionAnchorMsRef.current = anchor;- const start = Math.min(anchor, absoluteMs);- const end = Math.max(anchor, absoluteMs);- onTimeSelectionChange?.({ startMs: start, endMs: end });- } else {- // Plain drag: anchor starts at the click point itself- selectionAnchorMsRef.current = absoluteMs;- selectionCurrentMsRef.current = absoluteMs;- onTimeSelectionChange?.({ startMs: absoluteMs, endMs: absoluteMs });- }--- const handleGlobalMouseMove = (moveEvent: MouseEvent) => {- if (selectionAnchorMsRef.current === null || initialMouseDownPosRef.current === null) return;-- const dx = Math.abs(moveEvent.clientX - initialMouseDownPosRef.current.x);- const dy = Math.abs(moveEvent.clientY - initialMouseDownPosRef.current.y);-- if (dx > DRAG_THRESHOLD_PX || dy > DRAG_THRESHOLD_PX) {- isDraggingSelectionRef.current = true;- }-- // Use the captured rect — safe to read from an async listener- const moveX = moveEvent.clientX - capturedRect.left - sidebarWidth;- const moveRelativeMs = pixelsToValue(moveX);- const moveAbsoluteMs = Math.max(0, Math.min(range.start + moveRelativeMs, videoDurationMs));- selectionCurrentMsRef.current = moveAbsoluteMs;--- const start = Math.min(selectionAnchorMsRef.current, moveAbsoluteMs);- const end = Math.max(selectionAnchorMsRef.current, moveAbsoluteMs);-- onTimeSelectionChange?.({ startMs: start, endMs: end });- };-- const handleGlobalMouseUp = () => {- if (isDraggingSelectionRef.current && selectionAnchorMsRef.current !== null && selectionCurrentMsRef.current !== null) {- // When finished dragging a selection, jump playhead to the start of selection- const start = Math.min(selectionAnchorMsRef.current, selectionCurrentMsRef.current);- onSeek?.(start / 1000);- }-- selectionAnchorMsRef.current = null;- selectionCurrentMsRef.current = null;- initialMouseDownPosRef.current = null;- window.removeEventListener("mousemove", handleGlobalMouseMove);- window.removeEventListener("mouseup", handleGlobalMouseUp);- };---- window.addEventListener("mousemove", handleGlobalMouseMove);- window.addEventListener("mouseup", handleGlobalMouseUp);- },- [timelineMode, range.start, sidebarWidth, pixelsToValue, videoDurationMs, onTimeSelectionChange, timeSelection, currentTimeMs],- );--- const handleTimelineClick = useCallback(- (e: React.MouseEvent<HTMLDivElement>) => {- // If a selection-drag occurred (only possible in Select mode), swallow the click- if (isDraggingSelectionRef.current) {- isDraggingSelectionRef.current = false;- return;- }-- if (!onSeek || videoDurationMs <= 0) return;-- // In Select mode, shift+click updates the selection (already done in mousedown) — don't seek- if (timelineMode === 'select' && e.shiftKey) return;-- // Plain click: deselect all blocks, then seek and clear time selection- onTimeSelectionChange?.(null);-- onSelectZoom?.(null);- onSelectTrim?.(null);- onSelectAnnotation?.(null);- onSelectSpeed?.(null);- onSelectAudio?.(null);- onSelectCaption?.(null);- onSelectMaster?.(false);- onClearBlockSelection?.();-- const rect = e.currentTarget.getBoundingClientRect();- const clickX = e.clientX - rect.left - sidebarWidth;-- if (clickX < 0) return;+ const { setTimelineRef, style, sidebarWidth, range, pixelsToValue } = useTimelineContext();+ const localTimelineRef = useRef<HTMLDivElement | null>(null);++ const setRefs = useCallback(+ (node: HTMLDivElement | null) => {+ setTimelineRef(node);+ localTimelineRef.current = node;+ },+ [setTimelineRef],+ );++ const handleTimelineClick = useCallback(+ (e: React.MouseEvent<HTMLDivElement>) => {+ if (!onSeek || videoDurationMs <= 0) return;++ // Only clear selection if clicking on empty space (not on items)+ // This is handled by event propagation - items stop propagation+ onSelectZoom?.(null);+ onSelectTrim?.(null);+ onSelectAnnotation?.(null);+ onSelectSpeed?.(null);+ onSelectAudio?.(null);+ onClearBlockSelection?.();- const relativeMs = pixelsToValue(clickX);- const absoluteMs = Math.max(0, Math.min(range.start + relativeMs, videoDurationMs));+ const rect = e.currentTarget.getBoundingClientRect();+ const clickX = e.clientX - rect.left - sidebarWidth;- onSeek(absoluteMs / 1000);- },- [timelineMode, onSeek, onSelectZoom, onSelectTrim, onSelectAnnotation, onSelectSpeed, onSelectAudio, onSelectCaption, videoDurationMs, sidebarWidth, range.start, pixelsToValue, onTimeSelectionChange, onClearBlockSelection],- );+ if (clickX < 0) return;+ const relativeMs = pixelsToValue(clickX);+ const absoluteMs = Math.max(0, Math.min(range.start + relativeMs, videoDurationMs));+ const timeInSeconds = absoluteMs / 1000;- useEffect(() => {- if (localTimelineRef.current) {- // Expose handlers for internal components like Axis- (localTimelineRef.current as any).__handleMouseDown = handleMouseDown;- (localTimelineRef.current as any).__handleTimelineClick = handleTimelineClick;- }- }, [handleMouseDown, handleTimelineClick]);+ onSeek(timeInSeconds);+ }, [onSeek, onSelectZoom, onSelectTrim, onSelectAnnotation, onSelectSpeed, onSelectAudio, videoDurationMs, sidebarWidth, range.start, pixelsToValue]);const zoomItems = items.filter(item => item.rowId === ZOOM_ROW_ID);const trimItems = items.filter(item => item.rowId === TRIM_ROW_ID);const annotationItems = items.filter(item => item.rowId === ANNOTATION_ROW_ID);const speedItems = items.filter(item => item.rowId === SPEED_ROW_ID);- const originalAudioItems = items.filter(item => item.rowId === ORIGINAL_AUDIO_ROW_ID);const audioItems = items.filter(item => item.rowId === AUDIO_ROW_ID);- const captionItems = items.filter(item => item.rowId === CAPTION_ROW_ID);-- const handleAllAudioMute = useCallback(() => {- if (!audioRegions || audioRegions.length === 0) return;- const allMuted = audioRegions.every((r) => r.muted);- audioRegions.forEach((r) => {- onAudioMutedChange?.(r.id, !allMuted);- if (!allMuted && r.soloed) onAudioSoloedChange?.(r.id, false);- });- }, [audioRegions, onAudioMutedChange, onAudioSoloedChange]);-- const handleAllAudioSolo = useCallback(() => {- if (!audioRegions || audioRegions.length === 0) return;- const anySoloed = audioRegions.some((r) => r.soloed);- audioRegions.forEach((r) => {- onAudioSoloedChange?.(r.id, !anySoloed);- if (!anySoloed && r.muted) onAudioMutedChange?.(r.id, false);- });- }, [audioRegions, onAudioSoloedChange, onAudioMutedChange]);-- const anyAudioMuted = useMemo(() => audioRegions && audioRegions.length > 0 && audioRegions.every((r) => r.muted), [audioRegions]);- const anyAudioSoloed = useMemo(() => audioRegions && audioRegions.length > 0 && audioRegions.some((r) => r.soloed), [audioRegions]);-- const masterAudioControls = (- <div className="flex items-center gap-1 ml-1 overflow-hidden pointer-events-auto">- <button- type="button"- onMouseDown={(e) => e.stopPropagation()}- onClick={(e) => {- e.stopPropagation();- const nextMuted = !masterAudioMuted;- onMasterAudioMutedChange?.(nextMuted);- if (nextMuted && masterAudioSoloed) onMasterAudioSoloedChange?.(false);- }}- className={cn(- "w-4 h-4 rounded-[4px] border flex items-center justify-center text-[8px] font-bold transition-all",- masterAudioMuted- ? "bg-red-500/20 border-red-500/50 text-red-400"- : "bg-white/5 border-white/10 text-white/50 hover:bg-white/10 hover:text-white"- )}- title="Mute Master"- >- M- </button>- <button- type="button"- onMouseDown={(e) => e.stopPropagation()}- onClick={(e) => {- e.stopPropagation();- const nextSoloed = !masterAudioSoloed;- onMasterAudioSoloedChange?.(nextSoloed);- if (nextSoloed && masterAudioMuted) onMasterAudioMutedChange?.(false);- }}- className={cn(- "w-4 h-4 rounded-[4px] border flex items-center justify-center text-[8px] font-bold transition-all",- masterAudioSoloed- ? "bg-amber-500/20 border-amber-500/50 text-amber-400"- : "bg-white/5 border-white/10 text-white/50 hover:bg-white/10 hover:text-white"- )}- title="Solo Master"- >- S- </button>- {masterAudioVolume !== 1 && (- <span className="text-[8px] tabular-nums text-white/30 ml-0.5">{Math.round(masterAudioVolume * 100)}%</span>- )}- </div>- );- const audioControls = (- <div className="flex items-center gap-1 ml-1 overflow-hidden pointer-events-auto">- <button- type="button"- onMouseDown={(e) => e.stopPropagation()}- onClick={(e) => {- e.stopPropagation();- handleAllAudioMute();- }}- className={cn(- "w-4 h-4 rounded-[4px] border flex items-center justify-center text-[8px] font-bold transition-all",- anyAudioMuted- ? "bg-red-500/20 border-red-500/50 text-red-400"- : "bg-white/5 border-white/10 text-white/50 hover:bg-white/10 hover:text-white"- )}- title="Mute All Audio"- >- M- </button>- <button- type="button"- onMouseDown={(e) => e.stopPropagation()}- onClick={(e) => {- e.stopPropagation();- handleAllAudioSolo();- }}- className={cn(- "w-4 h-4 rounded-[4px] border flex items-center justify-center text-[8px] font-bold transition-all",- anyAudioSoloed- ? "bg-amber-500/20 border-amber-500/50 text-amber-400"- : "bg-white/5 border-white/10 text-white/50 hover:bg-white/10 hover:text-white"- )}- title="Solo All Audio"- >- S- </button>- {audioTrackVolume !== 1 && (- <span className="text-[8px] tabular-nums text-white/30 ml-0.5">{Math.round(audioTrackVolume * 100)}%</span>- )}- </div>- );-- return (- <div- ref={setRefs}- style={style}+ return (+ <div+ ref={setRefs}+ style={style}className="select-none bg-[#17171a] h-full min-h-0 relative cursor-pointer group flex flex-col"- onMouseDown={handleMouseDown}- onClick={handleTimelineClick}- >- {timeSelection && (- <div- className="absolute top-0 bottom-0 bg-blue-500/20 border-x border-blue-500/50 z-20 pointer-events-none"- style={{- left: `${sidebarWidth + valueToPixels(Math.max(range.start, timeSelection.startMs) - range.start)}px`,- width: `${valueToPixels(Math.min(range.end, timeSelection.endMs) - Math.max(range.start, timeSelection.startMs))}px`,- display: (timeSelection.endMs < range.start || timeSelection.startMs > range.end) ? 'none' : 'block'- }}- />- )}- <div className="absolute inset-0 bg-[linear-gradient(to_right,#ffffff03_1px,transparent_1px)] bg-[length:20px_100%] pointer-events-none" />- <TimelineAxis videoDurationMs={videoDurationMs} currentTimeMs={currentTimeMs} />- <PlaybackCursor- currentTimeMs={currentTimeMs}- videoDurationMs={videoDurationMs}- onSeek={onSeek}- timelineRef={localTimelineRef}- keyframes={keyframes}- timeSelection={timeSelection}- />-+ onClick={handleTimelineClick}+ >+ <div className="absolute inset-0 bg-[linear-gradient(to_right,#ffffff03_1px,transparent_1px)] bg-[length:20px_100%] pointer-events-none" />+ <TimelineAxis videoDurationMs={videoDurationMs} currentTimeMs={currentTimeMs} />+ <PlaybackCursor+ currentTimeMs={currentTimeMs}+ videoDurationMs={videoDurationMs}+ onSeek={onSeek}+ timelineRef={localTimelineRef}+ keyframes={keyframes}+ /><div className="relative z-10 flex flex-1 min-h-0 flex-col"><Row id={ZOOM_ROW_ID} isEmpty={zoomItems.length === 0} hint="Press Z to add zoom">@@ -881,7 +547,6 @@ function Timeline({onSelect={() => onSelectZoom?.(item.id)}zoomDepth={item.zoomDepth}variant="zoom"- timelineMode={timelineMode}>{item.label}</Item>@@ -898,7 +563,6 @@ function Timeline({isSelected={selectAllBlocksActive || item.id === selectedTrimId}onSelect={() => onSelectTrim?.(item.id)}variant="trim"- timelineMode={timelineMode}>{item.label}</Item>@@ -919,7 +583,6 @@ function Timeline({isSelected={selectAllBlocksActive || item.id === selectedAnnotationId}onSelect={() => onSelectAnnotation?.(item.id)}variant="annotation"- timelineMode={timelineMode}>{item.label}</Item>@@ -937,41 +600,13 @@ function Timeline({onSelect={() => onSelectSpeed?.(item.id)}variant="speed"speedValue={item.speedValue}- timelineMode={timelineMode}- >- {item.label}- </Item>- ))}- </Row>-- <Row- id={ORIGINAL_AUDIO_ROW_ID}- label="Master"- labelColor="#A855F7"- isEmpty={originalAudioItems.length === 0}- controls={masterAudioControls}- >- {originalAudioItems.map((item) => (- <Item- id={item.id}- key={item.id}- rowId={item.rowId}- span={item.span}- isSelected={isMasterSelected}- onSelect={() => onSelectMaster?.(true)}- variant="audio"- audioPath={item.audioPath}- isDraggable={false}- isResizable={false}- muted={item.muted}- timelineMode={timelineMode}>{item.label}</Item>))}</Row>- <Row id={AUDIO_ROW_ID} label="Audio" labelColor="#A855F7" controls={audioControls} isEmpty={audioItems.length === 0} hint="Click music icon to add audio">+ <Row id={AUDIO_ROW_ID} isEmpty={audioItems.length === 0} hint="Click music icon to add audio">{audioItems.map((item) => (<Itemid={item.id}@@ -981,27 +616,6 @@ function Timeline({isSelected={selectAllBlocksActive || item.id === selectedAudioId}onSelect={() => onSelectAudio?.(item.id)}variant="audio"- audioPath={item.audioPath}- muted={item.muted}- fadeInMs={item.fadeInMs}- fadeOutMs={item.fadeOutMs}- timelineMode={timelineMode}- >- {item.label}- </Item>- ))}- </Row>-- <Row id={CAPTION_ROW_ID} isEmpty={captionItems.length === 0} hint="Generated captions will appear here">- {captionItems.map((item) => (- <Item- id={item.id}- key={item.id}- rowId={item.rowId}- span={item.span}- isSelected={selectAllBlocksActive || item.id === selectedCaptionId}- onSelect={() => onSelectCaption?.(item.id)}- variant="caption">{item.label}</Item>@@ -1049,30 +663,10 @@ export default function TimelineEditor({onAudioDelete,selectedAudioId,onSelectAudio,- onAudioMutedChange,- onAudioSoloedChange,- autoCaptions = [],- onCaptionSpanChange,- selectedCaptionId,- onSelectCaption,- onClearAutoCaptions,- videoPath,- masterAudioMuted = false,- onMasterAudioMutedChange,- masterAudioSoloed = false,- onMasterAudioSoloedChange,- masterAudioVolume = 1,- audioTrackVolume = 1,- isMasterSelected = false,- onSelectMaster,aspectRatio,onAspectRatioChange,onOpenCropEditor,isCropped = false,- timeSelection,- onTimeSelectionChange,- timelineMode = 'move',- onTimelineModeChange,}: TimelineEditorProps) {const t = useScopedT("settings");const initialEditorPreferences = useMemo(() => loadEditorPreferences(), []);@@ -1199,24 +793,21 @@ export default function TimelineEditor({onSelectAudio(null);}, [selectedAudioId, onAudioDelete, onSelectAudio]);-const clearSelectedBlocks = useCallback(() => {onSelectZoom(null);onSelectTrim?.(null);onSelectAnnotation?.(null);onSelectSpeed?.(null);onSelectAudio?.(null);- onSelectCaption?.(null);setSelectAllBlocksActive(false);- }, [onSelectAnnotation, onSelectAudio, onSelectSpeed, onSelectTrim, onSelectZoom, onSelectCaption]);+ }, [onSelectAnnotation, onSelectAudio, onSelectSpeed, onSelectTrim, onSelectZoom]);const hasAnyTimelineBlocks =zoomRegions.length > 0 ||trimRegions.length > 0 ||annotationRegions.length > 0 ||speedRegions.length > 0 ||- audioRegions.length > 0 ||- autoCaptions.length > 0;+ audioRegions.length > 0;const deleteAllBlocks = useCallback(() => {const zoomIds = zoomRegions.map((region) => region.id);@@ -1231,7 +822,6 @@ export default function TimelineEditor({speedIds.forEach((id) => onSpeedDelete?.(id));audioIds.forEach((id) => onAudioDelete?.(id));- onClearAutoCaptions?.();clearSelectedBlocks();setSelectedKeyframeId(null);}, [@@ -1240,7 +830,6 @@ export default function TimelineEditor({clearSelectedBlocks,onAnnotationDelete,onAudioDelete,- onClearAutoCaptions,onSpeedDelete,onTrimDelete,onZoomDelete,@@ -1252,80 +841,27 @@ export default function TimelineEditor({const handleSelectZoom = useCallback((id: string | null) => {setSelectAllBlocksActive(false);onSelectZoom(id);- if (id) {- onSelectTrim?.(null);- onSelectAnnotation?.(null);- onSelectSpeed?.(null);- onSelectAudio?.(null);- onSelectCaption?.(null);- onTimeSelectionChange?.(null);- }- }, [onSelectZoom, onSelectTrim, onSelectAnnotation, onSelectSpeed, onSelectAudio, onSelectCaption, onTimeSelectionChange]);+ }, [onSelectZoom]);const handleSelectTrim = useCallback((id: string | null) => {setSelectAllBlocksActive(false);onSelectTrim?.(id);- if (id) {- onSelectZoom(null);- onSelectAnnotation?.(null);- onSelectSpeed?.(null);- onSelectAudio?.(null);- onSelectCaption?.(null);- onTimeSelectionChange?.(null);- }- }, [onSelectZoom, onSelectTrim, onSelectAnnotation, onSelectSpeed, onSelectAudio, onSelectCaption, onTimeSelectionChange]);+ }, [onSelectTrim]);const handleSelectAnnotation = useCallback((id: string | null) => {setSelectAllBlocksActive(false);onSelectAnnotation?.(id);- if (id) {- onSelectZoom(null);- onSelectTrim?.(null);- onSelectSpeed?.(null);- onSelectAudio?.(null);- onSelectCaption?.(null);- onTimeSelectionChange?.(null);- }- }, [onSelectZoom, onSelectTrim, onSelectAnnotation, onSelectSpeed, onSelectAudio, onSelectCaption, onTimeSelectionChange]);+ }, [onSelectAnnotation]);const handleSelectSpeed = useCallback((id: string | null) => {setSelectAllBlocksActive(false);onSelectSpeed?.(id);- if (id) {- onSelectZoom(null);- onSelectTrim?.(null);- onSelectAnnotation?.(null);- onSelectAudio?.(null);- onSelectCaption?.(null);- onTimeSelectionChange?.(null);- }- }, [onSelectZoom, onSelectTrim, onSelectAnnotation, onSelectSpeed, onSelectAudio, onSelectCaption, onTimeSelectionChange]);+ }, [onSelectSpeed]);const handleSelectAudio = useCallback((id: string | null) => {setSelectAllBlocksActive(false);onSelectAudio?.(id);- if (id) {- onSelectZoom(null);- onSelectTrim?.(null);- onSelectAnnotation?.(null);- onSelectSpeed?.(null);- onSelectCaption?.(null);- onTimeSelectionChange?.(null);- }- }, [onSelectZoom, onSelectTrim, onSelectAnnotation, onSelectSpeed, onSelectAudio, onSelectCaption, onTimeSelectionChange]);-- const handleSelectCaption = useCallback((id: string | null) => {- setSelectAllBlocksActive(false);- onSelectCaption?.(id);- if (id) {- onSelectZoom(null);- onSelectTrim?.(null);- onSelectAnnotation?.(null);- onSelectSpeed?.(null);- onSelectAudio?.(null);- onTimeSelectionChange?.(null);- }- }, [onSelectZoom, onSelectTrim, onSelectAnnotation, onSelectSpeed, onSelectAudio, onSelectCaption, onTimeSelectionChange]);+ }, [onSelectAudio]);useEffect(() => {setRange(createInitialRange(totalMs));@@ -1338,12 +874,10 @@ export default function TimelineEditor({const trimRegionsRef = useRef(trimRegions);const speedRegionsRef = useRef(speedRegions);const audioRegionsRef = useRef(audioRegions);- const autoCaptionsRef = useRef(autoCaptions);zoomRegionsRef.current = zoomRegions;trimRegionsRef.current = trimRegions;speedRegionsRef.current = speedRegions;audioRegionsRef.current = audioRegions;- autoCaptionsRef.current = autoCaptions;useEffect(() => {if (totalMs === 0 || safeMinDurationMs <= 0) {@@ -1397,20 +931,8 @@ export default function TimelineEditor({onAudioSpanChange?.(region.id, { start: normalizedStart, end: normalizedEnd });}});-- autoCaptionsRef.current.forEach((caption: CaptionCue) => {- const clampedStart = Math.max(0, Math.min(caption.startMs, totalMs));- const minEnd = clampedStart + safeMinDurationMs;- const clampedEnd = Math.min(totalMs, Math.max(minEnd, caption.endMs));- const normalizedStart = Math.max(0, Math.min(clampedStart, totalMs - safeMinDurationMs));- const normalizedEnd = Math.max(minEnd, Math.min(clampedEnd, totalMs));-- if (normalizedStart !== caption.startMs || normalizedEnd !== caption.endMs) {- onCaptionSpanChange?.(caption.id, { start: normalizedStart, end: normalizedEnd });- }- });// Only re-run when the timeline scale changes, not on every region edit- }, [totalMs, safeMinDurationMs, onZoomSpanChange, onTrimSpanChange, onSpeedSpanChange, onAudioSpanChange, onCaptionSpanChange]);+ }, [totalMs, safeMinDurationMs, onZoomSpanChange, onTrimSpanChange, onSpeedSpanChange, onAudioSpanChange]);const hasOverlap = useCallback((newSpan: Span, excludeId?: string): boolean => {// Determine which row the item belongs to@@ -1419,9 +941,8 @@ export default function TimelineEditor({const isAnnotationItem = annotationRegions.some(r => r.id === excludeId);const isSpeedItem = speedRegions.some(r => r.id === excludeId);const isAudioItem = audioRegions.some(r => r.id === excludeId);- const isCaptionItem = autoCaptions.some(r => r.id === excludeId);- if (isAnnotationItem || isCaptionItem) {+ if (isAnnotationItem) {return false;}@@ -1451,7 +972,7 @@ export default function TimelineEditor({}return false;- }, [zoomRegions, trimRegions, annotationRegions, speedRegions, audioRegions, autoCaptions]);+ }, [zoomRegions, trimRegions, annotationRegions, speedRegions, audioRegions]);// Keep newly added timeline regions at the original short default instead of// scaling them with the full recording length.@@ -1472,23 +993,23 @@ export default function TimelineEditor({// Always place zoom at playheadconst startPos = Math.max(0, Math.min(currentTimeMs, totalMs));+ // Find the next zoom region after the playheadconst sorted = [...zoomRegions].sort((a, b) => a.startMs - b.startMs);const nextRegion = sorted.find(region => region.startMs > startPos);const gapToNext = nextRegion ? nextRegion.startMs - startPos : totalMs - startPos;- const actualDuration = timeSelection- ? timeSelection.endMs - timeSelection.startMs- : Math.min(defaultRegionDurationMs, gapToNext);-- const finalStart = timeSelection ? timeSelection.startMs : startPos;- const finalEnd = timeSelection ? timeSelection.endMs : startPos + actualDuration;-- onZoomAdded({ start: finalStart, end: finalEnd });-- if (timeSelection) {- onTimeSelectionChange?.(null);+ // Check if playhead is inside any zoom region+ const isOverlapping = sorted.some(region => startPos >= region.startMs && startPos < region.endMs);+ if (isOverlapping || gapToNext <= 0) {+ toast.error("Cannot place zoom here", {+ description: "Zoom already exists at this location or not enough space available.",+ });+ return;}- }, [videoDuration, totalMs, currentTimeMs, zoomRegions, onZoomAdded, defaultRegionDurationMs, timeSelection, onTimeSelectionChange]);++ const actualDuration = Math.min(defaultRegionDurationMs, gapToNext);+ onZoomAdded({ start: startPos, end: startPos + actualDuration });+ }, [videoDuration, totalMs, currentTimeMs, zoomRegions, onZoomAdded, defaultRegionDurationMs]);const handleSuggestZooms = useCallback(() => {if (!videoDuration || videoDuration === 0 || totalMs === 0) {@@ -1600,23 +1121,23 @@ export default function TimelineEditor({// Always place trim at playheadconst startPos = Math.max(0, Math.min(currentTimeMs, totalMs));+ // Find the next trim region after the playheadconst sorted = [...trimRegions].sort((a, b) => a.startMs - b.startMs);const nextRegion = sorted.find(region => region.startMs > startPos);const gapToNext = nextRegion ? nextRegion.startMs - startPos : totalMs - startPos;- const actualDuration = timeSelection- ? timeSelection.endMs - timeSelection.startMs- : Math.min(defaultRegionDurationMs, gapToNext);-- const finalStart = timeSelection ? timeSelection.startMs : startPos;- const finalEnd = timeSelection ? timeSelection.endMs : startPos + actualDuration;-- onTrimAdded({ start: finalStart, end: finalEnd });-- if (timeSelection) {- onTimeSelectionChange?.(null);+ // Check if playhead is inside any trim region+ const isOverlapping = sorted.some(region => startPos >= region.startMs && startPos < region.endMs);+ if (isOverlapping || gapToNext <= 0) {+ toast.error("Cannot place trim here", {+ description: "Trim already exists at this location or not enough space available.",+ });+ return;}- }, [videoDuration, totalMs, currentTimeMs, trimRegions, onTrimAdded, defaultRegionDurationMs, timeSelection, onTimeSelectionChange]);++ const actualDuration = Math.min(defaultRegionDurationMs, gapToNext);+ onTrimAdded({ start: startPos, end: startPos + actualDuration });+ }, [videoDuration, totalMs, currentTimeMs, trimRegions, onTrimAdded, defaultRegionDurationMs]);const handleAddSpeed = useCallback(() => {if (!videoDuration || videoDuration === 0 || totalMs === 0 || !onSpeedAdded) {@@ -1630,23 +1151,23 @@ export default function TimelineEditor({// Always place speed region at playheadconst startPos = Math.max(0, Math.min(currentTimeMs, totalMs));+ // Find the next speed region after the playheadconst sorted = [...speedRegions].sort((a, b) => a.startMs - b.startMs);const nextRegion = sorted.find(region => region.startMs > startPos);const gapToNext = nextRegion ? nextRegion.startMs - startPos : totalMs - startPos;- const actualDuration = timeSelection- ? timeSelection.endMs - timeSelection.startMs- : Math.min(defaultRegionDurationMs, gapToNext);-- const finalStart = timeSelection ? timeSelection.startMs : startPos;- const finalEnd = timeSelection ? timeSelection.endMs : startPos + actualDuration;-- onSpeedAdded({ start: finalStart, end: finalEnd });-- if (timeSelection) {- onTimeSelectionChange?.(null);+ // Check if playhead is inside any speed region+ const isOverlapping = sorted.some(region => startPos >= region.startMs && startPos < region.endMs);+ if (isOverlapping || gapToNext <= 0) {+ toast.error("Cannot place speed here", {+ description: "Speed region already exists at this location or not enough space available.",+ });+ return;}- }, [videoDuration, totalMs, currentTimeMs, speedRegions, onSpeedAdded, defaultRegionDurationMs, timeSelection, onTimeSelectionChange]);++ const actualDuration = Math.min(defaultRegionDurationMs, gapToNext);+ onSpeedAdded({ start: startPos, end: startPos + actualDuration });+ }, [videoDuration, totalMs, currentTimeMs, speedRegions, onSpeedAdded, defaultRegionDurationMs]);const handleAddAudio = useCallback(async () => {if (!videoDuration || videoDuration === 0 || totalMs === 0 || !onAudioAdded) {@@ -1658,11 +1179,11 @@ export default function TimelineEditor({return;}- const audioPath = result.path;+ const audioPath = result.path;// Load the audio file to get its full durationconst audioDurationMs = await new Promise<number>((resolve) => {- const audio = new Audio(toFileUrl(audioPath));+ const audio = new Audio(toFileUrl(audioPath));audio.addEventListener('loadedmetadata', () => {resolve(Math.round(audio.duration * 1000));});@@ -1707,16 +1228,11 @@ export default function TimelineEditor({}// Multiple annotations can exist at the same timestamp- const finalStart = timeSelection ? timeSelection.startMs : Math.max(0, Math.min(currentTimeMs, totalMs));- const finalEnd = timeSelection ? timeSelection.endMs : Math.min(finalStart + defaultDuration, totalMs);-- onAnnotationAdded({ start: finalStart, end: finalEnd });-- if (timeSelection) {- onTimeSelectionChange?.(null);- }- }, [videoDuration, totalMs, currentTimeMs, onAnnotationAdded, defaultRegionDurationMs, timeSelection, onTimeSelectionChange]);+ const startPos = Math.max(0, Math.min(currentTimeMs, totalMs));+ const endPos = Math.min(startPos + defaultDuration, totalMs);+ onAnnotationAdded({ start: startPos, end: endPos });+ }, [videoDuration, totalMs, currentTimeMs, onAnnotationAdded, defaultRegionDurationMs]);useEffect(() => {const handleKeyDown = (e: KeyboardEvent) => {@@ -1735,6 +1251,9 @@ export default function TimelineEditor({return;}+ if (matchesShortcut(e, keyShortcuts.addKeyframe, isMac)) {+ addKeyframe();+ }if (matchesShortcut(e, keyShortcuts.addZoom, isMac)) {handleAddZoom();}@@ -1748,15 +1267,6 @@ export default function TimelineEditor({handleAddSpeed();}- // Mode switching shortcuts- if (e.key.toLowerCase() === 'v' && !e.ctrlKey && !e.metaKey && !e.altKey) {- onTimelineModeChange?.('move');- }- if (e.key.toLowerCase() === 'e' && !e.ctrlKey && !e.metaKey && !e.altKey) {- onTimelineModeChange?.('select');- }--// Tab: Cycle through overlapping annotations at current timeif (e.key === 'Tab' && annotationRegions.length > 0) {const currentTimeMs = Math.round(currentTime * 1000);@@ -1863,40 +1373,19 @@ export default function TimelineEditor({variant: 'speed',}));- const videoAudio: TimelineRenderItem[] = videoPath && totalMs > 0 ? [{- id: 'original-video-audio',- rowId: ORIGINAL_AUDIO_ROW_ID,- span: { start: 0, end: totalMs },- label: 'Original Audio',- variant: 'audio',- audioPath: videoPath,- muted: masterAudioMuted- }] : [];-- const audios: TimelineRenderItem[] = [- ...audioRegions.map((audio): TimelineRenderItem => ({- id: audio.id,+ const audios: TimelineRenderItem[] = audioRegions.map((region) => {+ const fileName = region.audioPath.split(/[\\/]/).pop()?.replace(/\.[^.]+$/, '') || 'Audio';+ return {+ id: region.id,rowId: AUDIO_ROW_ID,- span: { start: audio.startMs, end: audio.endMs },- label: audio.audioPath.split(/[\\/]/).pop() || 'Audio',+ span: { start: region.startMs, end: region.endMs },+ label: fileName,variant: 'audio',- audioPath: audio.audioPath,- muted: audio.muted,- soloed: audio.soloed,- fadeInMs: audio.fadeInMs,- fadeOutMs: audio.fadeOutMs- })),- ...autoCaptions.map((cue): TimelineRenderItem => ({- id: cue.id,- rowId: CAPTION_ROW_ID,- span: { start: cue.startMs, end: cue.endMs },- label: cue.text,- variant: 'caption'- }))- ];-- return [...zooms, ...trims, ...annotations, ...speeds, ...videoAudio, ...audios];- }, [zoomRegions, trimRegions, annotationRegions, speedRegions, audioRegions, autoCaptions, videoPath, totalMs, masterAudioMuted]);+ };+ });++ return [...zooms, ...trims, ...annotations, ...speeds, ...audios];+ }, [zoomRegions, trimRegions, annotationRegions, speedRegions, audioRegions]);// Flat list of all non-annotation region spans for neighbour-clamping during drag/resizeconst allRegionSpans = useMemo(() => {@@ -1904,25 +1393,23 @@ export default function TimelineEditor({const trims = trimRegions.map((r) => ({ id: r.id, start: r.startMs, end: r.endMs }));const speeds = speedRegions.map((r) => ({ id: r.id, start: r.startMs, end: r.endMs }));const audios = audioRegions.map((r) => ({ id: r.id, start: r.startMs, end: r.endMs }));- const captions = autoCaptions.map((r) => ({ id: r.id, start: r.startMs, end: r.endMs }));- return [...zooms, ...trims, ...speeds, ...audios, ...captions];- }, [zoomRegions, trimRegions, speedRegions, audioRegions, autoCaptions]);+ return [...zooms, ...trims, ...speeds, ...audios];+ }, [zoomRegions, trimRegions, speedRegions, audioRegions]);- const handleItemSpanChange = useCallback((id: string, span: Span, rowId: string) => {- if (rowId === ZOOM_ROW_ID) {+ const handleItemSpanChange = useCallback((id: string, span: Span) => {+ // Check if it's a zoom, trim, speed, or annotation item+ if (zoomRegions.some(r => r.id === id)) {onZoomSpanChange(id, span);- } else if (rowId === TRIM_ROW_ID && onTrimSpanChange) {- onTrimSpanChange(id, span);- } else if (rowId === ANNOTATION_ROW_ID && onAnnotationSpanChange) {- onAnnotationSpanChange(id, span);- } else if (rowId === SPEED_ROW_ID && onSpeedSpanChange) {- onSpeedSpanChange(id, span);- } else if (rowId === AUDIO_ROW_ID && onAudioSpanChange) {- onAudioSpanChange(id, span);- } else if (rowId === CAPTION_ROW_ID && onCaptionSpanChange) {- onCaptionSpanChange(id, span);+ } else if (trimRegions.some(r => r.id === id)) {+ onTrimSpanChange?.(id, span);+ } else if (speedRegions.some(r => r.id === id)) {+ onSpeedSpanChange?.(id, span);+ } else if (annotationRegions.some(r => r.id === id)) {+ onAnnotationSpanChange?.(id, span);+ } else if (audioRegions.some(r => r.id === id)) {+ onAudioSpanChange?.(id, span);}- }, [onZoomSpanChange, onTrimSpanChange, onAnnotationSpanChange, onSpeedSpanChange, onAudioSpanChange, onCaptionSpanChange]);+ }, [zoomRegions, trimRegions, speedRegions, annotationRegions, audioRegions, onZoomSpanChange, onTrimSpanChange, onSpeedSpanChange, onAnnotationSpanChange, onAudioSpanChange]);const panTimelineRange = useCallback((deltaMs: number) => {if (!Number.isFinite(deltaMs) || deltaMs === 0 || totalMs <= 0) {@@ -1987,43 +1474,7 @@ export default function TimelineEditor({return (<div className="flex-1 min-h-0 flex flex-col bg-[#17171a] overflow-auto">- <div className="flex items-center gap-4 px-4 py-2 border-b border-white/10 bg-[#161619]">- <div className="flex items-center bg-black/40 rounded-lg p-1 border border-white/5 shadow-inner">- <Button- onClick={() => onTimelineModeChange?.('move')}- variant="ghost"- size="sm"- className={cn(- "h-7 px-3 text-[11px] transition-all gap-1.5 rounded-md border border-transparent",- timelineMode === 'move'- ? "bg-[#2563EB] text-white hover:bg-[#3b82f6] shadow-lg shadow-blue-500/20 border-white/10"- : "text-white/50 hover:text-white/80 hover:bg-white/5"- )}- title="Move Tools (V)"- >- <MousePointer2 className={cn("w-3.5 h-3.5", timelineMode === 'move' ? "text-white" : "text-white/40")} />- <span className="font-semibold uppercase tracking-wider">Move</span>- </Button>- <Button- onClick={() => onTimelineModeChange?.('select')}- variant="ghost"- size="sm"- className={cn(- "h-7 px-3 text-[11px] transition-all gap-1.5 rounded-md border border-transparent",- timelineMode === 'select'- ? "bg-[#2563EB] text-white hover:bg-[#3b82f6] shadow-lg shadow-blue-500/20 border-white/10"- : "text-white/50 hover:text-white/80 hover:bg-white/5"- )}- title="Select Tools (E)"- >- <BoxSelect className={cn("w-3.5 h-3.5", timelineMode === 'select' ? "text-white" : "text-white/40")} />- <span className="font-semibold uppercase tracking-wider">Select</span>- </Button>- </div>---- <div className="w-[1px] h-4 bg-white/10" />+ <div className="flex items-center gap-2 px-4 py-2 border-b border-white/10 bg-[#161619]"><div className="flex items-center gap-1"><ButtononClick={handleAddZoom}@@ -2214,30 +1665,14 @@ export default function TimelineEditor({onSelectAnnotation={handleSelectAnnotation}onSelectSpeed={handleSelectSpeed}onSelectAudio={handleSelectAudio}- onAudioMutedChange={onAudioMutedChange}- onAudioSoloedChange={onAudioSoloedChange}- audioRegions={audioRegions}- onSelectCaption={handleSelectCaption}- masterAudioMuted={masterAudioMuted}- onMasterAudioMutedChange={onMasterAudioMutedChange}- masterAudioSoloed={masterAudioSoloed}- onMasterAudioSoloedChange={onMasterAudioSoloedChange}- masterAudioVolume={masterAudioVolume}- audioTrackVolume={audioTrackVolume}selectedZoomId={selectedZoomId}selectedTrimId={selectedTrimId}selectedAnnotationId={selectedAnnotationId}selectedSpeedId={selectedSpeedId}selectedAudioId={selectedAudioId}- selectedCaptionId={selectedCaptionId}selectAllBlocksActive={selectAllBlocksActive}onClearBlockSelection={clearSelectedBlocks}keyframes={keyframes}- timeSelection={timeSelection}- onTimeSelectionChange={onTimeSelectionChange}- isMasterSelected={isMasterSelected}- onSelectMaster={onSelectMaster}- timelineMode={timelineMode}/></TimelineWrapper></div>diff --git a/src/components/video-editor/timeline/TimelineWrapper.tsx b/src/components/video-editor/timeline/TimelineWrapper.tsxindex dd9887b9..a40f9a14 100644--- a/src/components/video-editor/timeline/TimelineWrapper.tsx+++ b/src/components/video-editor/timeline/TimelineWrapper.tsx@@ -20,7 +20,7 @@ interface TimelineWrapperProps {minItemDurationMs: number;minVisibleRangeMs: number;gridSizeMs?: number;- onItemSpanChange: (id: string, span: Span, rowId: string) => void;+ onItemSpanChange: (id: string, span: Span) => void;allRegionSpans?: { id: string; start: number; end: number }[];}@@ -133,7 +133,6 @@ export default function TimelineWrapper({if (!updatedSpan) return;const activeItemId = event.active.id as string;- const rowId = event.active.data.current.rowId as string;let clampedSpan = clampSpanToBounds(updatedSpan);const effectiveMinDuration = totalMs > 0@@ -152,7 +151,7 @@ export default function TimelineWrapper({}}- onItemSpanChange(activeItemId, clampedSpan, rowId);+ onItemSpanChange(activeItemId, clampedSpan);},[clampSpanToBounds, clampToNeighbours, hasOverlap, minItemDurationMs, onItemSpanChange, totalMs]);@@ -164,7 +163,6 @@ export default function TimelineWrapper({if (!updatedSpan || !activeRowId) return;const activeItemId = event.active.id as string;- const rowId = event.active.data.current.rowId as string;let clampedSpan = clampSpanToBounds(updatedSpan);// Clamp to neighbour boundaries instead of rejecting@@ -175,7 +173,7 @@ export default function TimelineWrapper({}}- onItemSpanChange(activeItemId, clampedSpan, rowId);+ onItemSpanChange(activeItemId, clampedSpan);},[clampSpanToBounds, clampToNeighbours, hasOverlap, onItemSpanChange]);diff --git a/src/components/video-editor/types.ts b/src/components/video-editor/types.tsindex d0b1045f..5406210c 100644--- a/src/components/video-editor/types.ts+++ b/src/components/video-editor/types.ts@@ -127,7 +127,7 @@ export interface TrimRegion {endMs: number;}-export type AnnotationType = "text" | "image" | "figure" | "blur";+export type AnnotationType = "text" | "image" | "figure";export type ArrowDirection =| "up"@@ -195,11 +195,8 @@ export interface AnnotationRegion {style: AnnotationTextStyle;zIndex: number;figureData?: FigureData;- blurIntensity?: number;}-export const DEFAULT_BLUR_INTENSITY = 12;-export const DEFAULT_ANNOTATION_POSITION: AnnotationPosition = {x: 50,y: 50,@@ -247,16 +244,6 @@ export interface AudioRegion {endMs: number;audioPath: string;volume: number;- muted?: boolean;- soloed?: boolean;- fadeInMs?: number;- fadeOutMs?: number;-}---export interface TimeSelection {- startMs: number;- endMs: number;}export interface CaptionCue {@@ -275,12 +262,10 @@ export interface CaptionCueWord {}export type AutoCaptionAnimation = "none" | "fade" | "rise" | "pop";-export type WhisperModel = "tiny" | "base" | "small" | "medium" | "large" | "custom";export interface AutoCaptionSettings {enabled: boolean;language: string;- selectedModel: WhisperModel;fontFamily: string;fontSize: number;bottomOffset: number;@@ -291,13 +276,11 @@ export interface AutoCaptionSettings {textColor: string;inactiveTextColor: string;backgroundOpacity: number;- generationRange: "full" | "selected";}export const DEFAULT_AUTO_CAPTION_SETTINGS: AutoCaptionSettings = {enabled: false,language: "auto",- selectedModel: "small",fontFamily: getDefaultCaptionFontFamily(),fontSize: 30,bottomOffset: 3,@@ -307,8 +290,7 @@ export const DEFAULT_AUTO_CAPTION_SETTINGS: AutoCaptionSettings = {boxRadius: 17.5,textColor: "#FFFFFF",inactiveTextColor: "#A3A3A3",- backgroundOpacity: 0.1,- generationRange: "full",+ backgroundOpacity: 0.9,};export type PlaybackSpeed = 0.25 | 0.5 | 0.75 | 1.25 | 1.5 | 1.75 | 2;diff --git a/src/components/video-editor/videoPlayback/videoEventHandlers.ts b/src/components/video-editor/videoPlayback/videoEventHandlers.tsindex 25b5db61..9ee7ae54 100644--- a/src/components/video-editor/videoPlayback/videoEventHandlers.ts+++ b/src/components/video-editor/videoPlayback/videoEventHandlers.ts@@ -12,10 +12,8 @@ interface VideoEventHandlersParams {onTimeUpdate: (time: number) => void;trimRegionsRef: React.MutableRefObject<TrimRegion[]>;speedRegionsRef: React.MutableRefObject<SpeedRegion[]>;- timeSelectionRef: React.MutableRefObject<import('../types').TimeSelection | null>;}-export function createVideoEventHandlers(params: VideoEventHandlersParams) {const {video,@@ -28,10 +26,8 @@ export function createVideoEventHandlers(params: VideoEventHandlersParams) {onTimeUpdate,trimRegionsRef,speedRegionsRef,- timeSelectionRef,} = params;-const emitTime = (timeValue: number) => {currentTimeRef.current = timeValue * 1000;onTimeUpdate(timeValue);@@ -56,21 +52,8 @@ export function createVideoEventHandlers(params: VideoEventHandlersParams) {if (!video) return;const currentTimeMs = video.currentTime * 1000;-- // Selection awareness: stop playback at the end of selection range- const selection = timeSelectionRef.current;- if (selection && !video.paused && !isSeekingRef.current) {- if (currentTimeMs >= selection.endMs) {- video.pause();- video.currentTime = selection.startMs / 1000;- emitTime(selection.startMs / 1000);- return; // Selection boundary reached, stop update loop- }- }-const activeTrimRegion = findActiveTrimRegion(currentTimeMs);-// If we're in a trim region during playback, skip to the end of itif (activeTrimRegion && !video.paused && !video.ended) {const skipToTime = activeTrimRegion.endMs / 1000;diff --git a/src/index.css b/src/index.cssindex 35f25625..80d8fc45 100644--- a/src/index.css+++ b/src/index.css@@ -121,23 +121,6 @@.custom-scrollbar::-webkit-scrollbar {display: none; /* Chrome, Safari, Opera */}-- .subtle-scrollbar::-webkit-scrollbar {- width: 4px;- }-- .subtle-scrollbar::-webkit-scrollbar-track {- background: transparent;- }-- .subtle-scrollbar::-webkit-scrollbar-thumb {- background: rgba(255, 255, 255, 0.1);- border-radius: 10px;- }-- .subtle-scrollbar::-webkit-scrollbar-thumb:hover {- background: rgba(255, 255, 255, 0.2);- }/* Smooth playback scrubber */input[type="range"] {diff --git a/src/lib/exporter/annotationRenderer.ts b/src/lib/exporter/annotationRenderer.tsindex a9a73ff1..0df4541c 100644--- a/src/lib/exporter/annotationRenderer.ts+++ b/src/lib/exporter/annotationRenderer.ts@@ -289,67 +289,6 @@ async function renderImage(});}-function renderBlur(- ctx: CanvasRenderingContext2D,- annotation: AnnotationRegion,- x: number,- y: number,- width: number,- height: number,- scaleFactor: number-) {- // Get intensity scaled to canvas resolution- const intensity = (annotation.blurIntensity ?? 12) * scaleFactor;- if (intensity <= 0 || width <= 0 || height <= 0) return;-- ctx.save();- try {- // Determine bounds and ensure they are within canvas to avoid ImageData errors- const srcX = Math.max(0, x);- const srcY = Math.max(0, y);- const srcWidth = Math.min(x + width, ctx.canvas.width) - srcX;- const srcHeight = Math.min(y + height, ctx.canvas.height) - srcY;-- if (srcWidth <= 0 || srcHeight <= 0) {- ctx.restore();- return;- }-- // Capture the current canvas region precisely for this intersection- const imageData = ctx.getImageData(srcX, srcY, srcWidth, srcHeight);-- let offscreen: HTMLCanvasElement | OffscreenCanvas;- if (typeof document !== 'undefined') {- offscreen = document.createElement('canvas');- } else {- offscreen = new OffscreenCanvas(srcWidth, srcHeight);- }- offscreen.width = srcWidth;- offscreen.height = srcHeight;-- const offCtx = offscreen.getContext('2d') as CanvasRenderingContext2D;- offCtx.putImageData(imageData, 0, 0);-- // Create rounded rect clipping path (matches UI's rounded-lg approx 8px)- const radius = 8 * scaleFactor;- ctx.beginPath();- if (ctx.roundRect) {- ctx.roundRect(x, y, width, height, radius);- } else {- ctx.rect(x, y, width, height);- }- ctx.clip();-- // Apply the blur filter and draw the captured region back at its source position- ctx.filter = `blur(${intensity}px)`;- ctx.drawImage(offscreen as any, srcX, srcY);-- } catch (err) {- console.warn('[AnnotationRenderer] Blur annotation render failed:', err);- }- ctx.restore();-}-export async function renderAnnotations(ctx: CanvasRenderingContext2D,annotations: AnnotationRegion[],@@ -396,10 +335,6 @@ export async function renderAnnotations();}break;-- case 'blur':- renderBlur(ctx, annotation, x, y, width, height, scaleFactor);- break;}}}diff --git a/src/lib/exporter/audioEncoder.ts b/src/lib/exporter/audioEncoder.tsindex c617cf66..a40c4740 100644--- a/src/lib/exporter/audioEncoder.ts+++ b/src/lib/exporter/audioEncoder.ts@@ -25,10 +25,6 @@ export class AudioProcessor {speedRegions?: SpeedRegion[],readEndSec?: number,audioRegions?: AudioRegion[],- masterAudioVolume = 1,- audioTrackVolume = 1,- masterAudioMuted = false,- masterAudioSoloed = false,): Promise<void> {const sortedTrims = trimRegions ? [...trimRegions].sort((a, b) => a.startMs - b.startMs) : []const sortedSpeedRegions = speedRegions@@ -40,24 +36,13 @@ export class AudioProcessor {? [...audioRegions].sort((a, b) => a.startMs - b.startMs): []- // When audio regions, speed edits, or global volume/mute settings are present, use AudioContext mixing path.- if (- sortedSpeedRegions.length > 0 ||- sortedAudioRegions.length > 0 ||- masterAudioVolume !== 1 ||- audioTrackVolume !== 1 ||- masterAudioMuted ||- masterAudioSoloed- ) {+ // When audio regions or speed edits are present, use AudioContext mixing path.+ if (sortedSpeedRegions.length > 0 || sortedAudioRegions.length > 0) {const renderedAudioBlob = await this.renderMixedTimelineAudio(videoUrl,sortedTrims,sortedSpeedRegions,sortedAudioRegions,- masterAudioVolume,- audioTrackVolume,- masterAudioMuted,- masterAudioSoloed,)if (!this.cancelled) {await this.muxRenderedAudioBlob(renderedAudioBlob, muxer)@@ -294,10 +279,6 @@ export class AudioProcessor {trimRegions: TrimRegion[],speedRegions: SpeedRegion[],audioRegions: AudioRegion[],- masterAudioVolume: number,- audioTrackVolume: number,- masterAudioMuted: boolean,- masterAudioSoloed: boolean,): Promise<Blob> {const mediaSource = await resolveMediaElementSource(videoUrl)const media = document.createElement('audio')@@ -321,11 +302,9 @@ export class AudioProcessor {const audioContext = new AudioContext()const destinationNode = audioContext.createMediaStreamDestination()- // Connect original video audio with its own gain node+ // Connect original video audioconst sourceNode = audioContext.createMediaElementSource(media)- const masterGainNode = audioContext.createGain()- sourceNode.connect(masterGainNode)- masterGainNode.connect(destinationNode)+ sourceNode.connect(destinationNode)// Prepare external audio region elementsconst audioRegionElements: {@@ -352,8 +331,7 @@ export class AudioProcessor {const regionSourceNode = audioContext.createMediaElementSource(audioEl)const gainNode = audioContext.createGain()- // Initial volume (will be updated in the tick loop for fades)- gainNode.gain.value = 0+ gainNode.gain.value = Math.max(0, Math.min(1, region.volume))regionSourceNode.connect(gainNode)gainNode.connect(destinationNode)@@ -424,56 +402,22 @@ export class AudioProcessor {}}- // Check for Solo - if any track is soloed, everything else is muted- const anyTrackSoloed = masterAudioSoloed || audioRegionElements.some(e => e.region.soloed);-- // Update Master Video Audio Track Volume- let masterTargetVolume = masterAudioMuted ? 0 : audioTrackVolume;- if (anyTrackSoloed && !masterAudioSoloed) {- masterTargetVolume = 0;- }- // Factor in the overall Master output volume- masterTargetVolume *= masterAudioVolume;- masterGainNode.gain.setTargetAtTime(masterTargetVolume, audioContext.currentTime, 0.015);-// Sync external audio regions with the video timeline positionfor (const entry of audioRegionElements) {- const { media: audioEl, region, gainNode } = entry+ const { media: audioEl, region } = entryconst isInRegion = currentTimeMs >= region.startMs && currentTimeMs < region.endMsif (isInRegion) {const audioOffset = (currentTimeMs - region.startMs) / 1000-- // Apply fade-in / fade-out multiplier- let fadeMultiplier = 1;- if (region.fadeInMs && currentTimeMs < region.startMs + region.fadeInMs) {- fadeMultiplier = (currentTimeMs - region.startMs) / region.fadeInMs;- } else if (region.fadeOutMs && currentTimeMs > region.endMs - region.fadeOutMs) {- fadeMultiplier = (region.endMs - currentTimeMs) / region.fadeOutMs;- }- fadeMultiplier = Math.max(0, Math.min(1, fadeMultiplier));-- // Respect Solo and Mute- let regionTargetVolume = (region.muted || masterAudioMuted) ? 0 : region.volume;- if (anyTrackSoloed && !region.soloed) {- regionTargetVolume = 0;- }- // Also factor in global master volume- regionTargetVolume *= masterAudioVolume * fadeMultiplier;-- gainNode.gain.setTargetAtTime(regionTargetVolume, audioContext.currentTime, 0.015);-if (audioEl.paused) {audioEl.currentTime = audioOffsetaudioEl.play().catch(() => {})- } else if (Math.abs(audioEl.currentTime - audioOffset) > 0.1) {- // Tightened sync for export+ } else if (Math.abs(audioEl.currentTime - audioOffset) > 0.3) {audioEl.currentTime = audioOffset}} else {if (!audioEl.paused) {audioEl.pause()- gainNode.gain.value = 0}}}diff --git a/src/lib/exporter/types.ts b/src/lib/exporter/types.tsindex 2a17bb4e..a92d28db 100644--- a/src/lib/exporter/types.ts+++ b/src/lib/exporter/types.ts@@ -4,9 +4,6 @@ export interface ExportConfig {frameRate: number;bitrate: number;codec?: string;- masterAudioVolume?: number;- audioTrackVolume?: number;- masterAudioMuted?: boolean;}export interface ExportProgress {diff --git a/src/lib/exporter/videoExporter.ts b/src/lib/exporter/videoExporter.tsindex a6b3e030..2e1e105d 100644--- a/src/lib/exporter/videoExporter.ts+++ b/src/lib/exporter/videoExporter.ts@@ -59,10 +59,6 @@ interface VideoExporterConfig extends ExportConfig {previewWidth?: number;previewHeight?: number;onProgress?: (progress: ExportProgress) => void;- masterAudioVolume?: number;- masterAudioMuted?: boolean;- masterAudioSoloed?: boolean;- audioTrackVolume?: number;}export class VideoExporter {@@ -211,10 +207,6 @@ export class VideoExporter {this.config.speedRegions,undefined,this.config.audioRegions,- this.config.masterAudioVolume,- this.config.audioTrackVolume,- this.config.masterAudioMuted,- this.config.masterAudioSoloed,),"audio processing",);diff --git a/src/utils/audioWaveform.ts b/src/utils/audioWaveform.tsdeleted file mode 100644index 017faac5..00000000--- a/src/utils/audioWaveform.ts+++ /dev/null@@ -1,50 +0,0 @@-/**- * Extracts waveform peaks from an audio file.- * We decode the audio file using the Web Audio API and calculate the max peaks for each sample.- */--import { toFileUrl } from "@/components/video-editor/projectPersistence";--const waveformCache = new Map<string, number[]>();--export async function generateWaveform(audioPath: string, samples = 200): Promise<number[]> {- const cacheKey = `${audioPath}:${samples}`;- if (waveformCache.has(cacheKey)) {- return waveformCache.get(cacheKey)!;- }-- const audioContext = new (window.AudioContext || (window as any).webkitAudioContext)();- try {- const response = await fetch(toFileUrl(audioPath));- const arrayBuffer = await response.arrayBuffer();-- // Use an offline audio context to decode the data- const audioBuffer = await audioContext.decodeAudioData(arrayBuffer);-- const channelData = audioBuffer.getChannelData(0); // Use the first channel- const blockSize = Math.floor(channelData.length / samples);- const peaks: number[] = [];-- for (let i = 0; i < samples; i++) {- const start = i * blockSize;- let max = 0;- for (let j = 0; j < blockSize; j++) {- const value = Math.abs(channelData[start + j]);- if (value > max) max = value;- }- peaks.push(max);- }-- waveformCache.set(cacheKey, peaks);- return peaks;- } catch (error) {- console.error('Failed to generate waveform:', error);- return new Array(samples).fill(0);- } finally {- try {- await audioContext.close();- } catch (e) {- // ignore close errors- }- }-}