Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.
TypeScript cross-platformelectronffmpegopen-sourceproduct-demorustscreen-capturescreen-recorderscreen-recordingscreen-studioscreencastspeech-to-texttypescriptvideo-editingvideo-editorwaylandwgpuwhisper
fix(editor): address CodeRabbit review on the audio-import PR (#502)
Benjamin Freeman6a9c32df4053
diff --git a/crates/compositor/src/audio.rs b/crates/compositor/src/audio.rsindex 5de0e19d4..89da8cbec 100644--- a/crates/compositor/src/audio.rs+++ b/crates/compositor/src/audio.rs@@ -1390,23 +1390,40 @@ pub fn assemble_concatenated_pcm(/// track that runs past the video is truncated to it, so the audio and video/// streams stay the same length for the muxer.///+/// The decode window is capped up front at the room left in the programme after+/// `start_sec`, and a track starting at/after the end is skipped without decoding.+/// `decode_clip_audio` preallocates from the window, so this keeps a long track+/// pinned near a short programme's end from buffering (and clamping away) hours of+/// PCM. `trim_end_sec` must therefore be concrete — the renderer sends+/// `trimEnd ?? durationSec`.+////// A track whose file has no decodable audio is skipped — the same degradation a-/// stream-less clip gets. `trim_end_sec` must be concrete (the renderer sends-/// `trimEnd ?? durationSec`): `decode_clip_audio` preallocates from it, so an-/// unbounded end would try to allocate the whole real line.+/// stream-less clip gets.pub fn mix_external_tracks(mut programme: PlanarPcm, tracks: &[SceneAudioTrack]) -> PlanarPcm {let programme_len = programme.first().map(Vec::len).unwrap_or(0);if programme_len == 0 {return programme;}for track in tracks {+ let offset = (track.start_sec.max(0.0) * AUDIO_OUTPUT_SAMPLE_RATE as f64).round() as usize;+ // A track that starts at or past the programme end contributes nothing —+ // skip it before decoding anything.+ if offset >= programme_len {+ continue;+ }let trim_start = track.trim_start_sec.max(0.0);- let Some(trim_end) = track.trim_end_sec else {+ let Some(trim_end_full) = track.trim_end_sec else {// Without a concrete end there is no safe window to decode (see the doc// comment); the renderer always resolves one, so this only guards a// hand-written scene.continue;};+ // Cap the decode window at the room left in the programme. Everything past+ // `offset` that overflows is discarded by `overlay_track_pcm` anyway, so+ // decoding it only wastes time and memory — a three-hour track placed at+ // second 9 of a ten-second export must not buffer three hours of PCM.+ let remaining_sec = (programme_len - offset) as f64 / AUDIO_OUTPUT_SAMPLE_RATE as f64;+ let trim_end = trim_end_full.min(trim_start + remaining_sec);if trim_end <= trim_start {continue;}@@ -1415,7 +1432,6 @@ pub fn mix_external_tracks(mut programme: PlanarPcm, tracks: &[SceneAudioTrack])_ => continue,};let gain = 10.0f32.powf(track.gain_db.clamp(-12.0, 12.0) / 20.0);- let offset = (track.start_sec.max(0.0) * AUDIO_OUTPUT_SAMPLE_RATE as f64).round() as usize;overlay_track_pcm(&mut programme, &decoded, offset, gain);}programme@@ -1795,6 +1811,23 @@ mod tests {assert_eq!(out[0], vec![0.4, 0.4]);}+ #[test]+ fn mix_external_tracks_skips_a_track_that_starts_past_the_programme() {+ // 2 samples = ~0.00004 s of programme at 48 kHz; the track starts at 1 s, so+ // its offset is past the end. It must be skipped before any decode is+ // attempted (the path does not exist), never buffering its window.+ let programme = planar(&[0.4, 0.4]);+ let tracks = vec![SceneAudioTrack {+ path: "/nope.mp3".into(),+ start_sec: 1.0,+ gain_db: 0.0,+ trim_start_sec: 0.0,+ trim_end_sec: Some(3600.0),+ }];+ let out = mix_external_tracks(programme, &tracks);+ assert_eq!(out[0], vec![0.4, 0.4]);+ }+#[test]fn single_track_is_not_clamped() {// Promesse de non-régression : une source mono-piste ressort telle quelle, y comprisdiff --git a/electron/ai-edition/document-service.test.ts b/electron/ai-edition/document-service.test.tsindex 91e780acf..91448d350 100644--- a/electron/ai-edition/document-service.test.ts+++ b/electron/ai-edition/document-service.test.ts@@ -405,6 +405,50 @@ describe("DocumentService", () => {expect(after.project.primaryAssetId).toBe(b.assets[1]?.id);});+ // Issue #350 — an audio overlay can never be primary.+ it("passes primary to the next VIDEO asset, never to an audio asset", async () => {+ const doc = await service.createProject("P");+ const video = await service.addAsset(doc.project.id, { path: "/tmp/screen.mp4" });+ await service.addAsset(doc.project.id, { path: "/tmp/music.mp3", kind: "audio" });+ const primaryId = video.project.primaryAssetId;+ expect(primaryId).toBeTruthy();+ // Removing the only video leaves just the audio asset; primary must clear,+ // not fall to the audio one.+ const after = await service.removeAsset(doc.project.id, primaryId ?? "");+ expect(after.project.primaryAssetId).toBeUndefined();+ expect(after.assets).toHaveLength(1);+ expect(after.assets[0]?.kind).toBe("audio");+ });++ it("drops audioTracks that referenced a removed audio asset", async () => {+ const doc = await service.createProject("P");+ await service.addAsset(doc.project.id, { path: "/tmp/screen.mp4" });+ const withAudio = await service.addAsset(doc.project.id, {+ path: "/tmp/music.mp3",+ kind: "audio",+ });+ const audioId = withAudio.assets.find((a) => a.kind === "audio")?.id ?? "";+ expect(audioId).toBeTruthy();+ const withTrack = await service.saveProject({+ ...withAudio,+ audioTracks: [+ {+ id: "trk_1",+ assetId: audioId,+ timelineStartSec: 0,+ durationSec: 10,+ trimStartSec: 0,+ gainDb: 0,+ label: "music",+ },+ ],+ });+ expect(withTrack.audioTracks).toHaveLength(1);+ const after = await service.removeAsset(doc.project.id, audioId);+ expect(after.audioTracks).toEqual([]);+ expect(after.assets.some((a) => a.id === audioId)).toBe(false);+ });+it("resequences other assets and rederives their anchored regions", async () => {const created = await service.createProject("P");const withA = await service.addAsset(created.project.id, { path: "/tmp/a.mp4" });diff --git a/electron/ai-edition/document-service.ts b/electron/ai-edition/document-service.tsindex f519379e4..cf471e4df 100644--- a/electron/ai-edition/document-service.ts+++ b/electron/ai-edition/document-service.ts@@ -359,9 +359,13 @@ export class DocumentService {throw new ProjectFileError(`Asset ${assetId} not found in project ${projectId}.`, projectId);}const assets = doc.assets.filter((a) => a.id !== assetId);+ // Primary is the thing the timeline is built around, so it must fall to the+ // next VIDEO asset — never an audio overlay (issue #350), which can't be+ // primary (see addAsset). Falling back to `assets[0]` would hand primary to+ // an audio asset when the removed one was the last video.const primaryAssetId =doc.project.primaryAssetId === assetId- ? (assets[0]?.id ?? undefined)+ ? (assets.find((a) => a.kind !== "audio")?.id ?? undefined): doc.project.primaryAssetId;const withoutAssetClips = doc.timeline.clips.filter((clip) => clip.assetId === assetId)@@ -369,6 +373,9 @@ export class DocumentService {const next: AxcutDocument = {...withoutAssetClips,assets,+ // Drop imported audio tracks that referenced the removed asset — they+ // would otherwise dangle, pointing at an asset the document no longer has.+ audioTracks: withoutAssetClips.audioTracks.filter((t) => t.assetId !== assetId),timeline: {...withoutAssetClips.timeline,trimRanges: withoutAssetClips.timeline.trimRanges.filter((r) => r.assetId !== assetId),diff --git a/src/components/ai-edition/v4/V4Timeline.tsx b/src/components/ai-edition/v4/V4Timeline.tsxindex cff3eb60e..a03368963 100644--- a/src/components/ai-edition/v4/V4Timeline.tsx+++ b/src/components/ai-edition/v4/V4Timeline.tsx@@ -933,7 +933,10 @@ export function V4Timeline({let nts = origTrimStart;let nte = origTrimEnd;if (mode === "move") {- ns = Math.max(0, snap(origStart + dxSec));+ // Cap so the whole track lands by `total`: no pill past 100%, and the+ // export (which truncates at the programme end) matches what's shown.+ const upper = Math.max(0, total - (origTrimEnd - origTrimStart));+ ns = Math.min(Math.max(0, snap(origStart + dxSec)), upper);} else if (mode === "l") {// The left edge can't cross the right one, and can't reveal more head// than the source has (trimStart floors at 0 → head floors at@@ -950,7 +953,12 @@ export function V4Timeline({// position of the edge, then map back to a source out-point.const snappedRight = snap(origStart + (origTrimEnd - origTrimStart) + dxSec);const newTrimEnd = origTrimStart + (snappedRight - origStart);- nte = Math.min(Math.max(newTrimEnd, origTrimStart + MIN_REGION_SEC), maxEnd);+ // Cap the out-point at the source length AND the programme end (`total`).+ nte = Math.min(+ Math.max(newTrimEnd, origTrimStart + MIN_REGION_SEC),+ maxEnd,+ origTrimStart + Math.max(0, total - origStart),+ );}const next = { id: track.id, start: ns, trimStart: nts, trimEnd: nte };audioDragRef.current = next;diff --git a/src/i18n/locales/ar/dialogs.json b/src/i18n/locales/ar/dialogs.jsonindex 1032d22cb..cf7c6f554 100644--- a/src/i18n/locales/ar/dialogs.json+++ b/src/i18n/locales/ar/dialogs.json@@ -79,13 +79,13 @@"saveGif": "حفظ GIF المصدر","saveVideo": "حفظ الفيديو المصدر","selectVideo": "حدد ملف فيديو",- "selectAudio": "Select Audio File",+ "selectAudio": "اختر ملف صوت","saveProject": "حفظ مشروع OpenScreen","openProject": "فتح مشروع OpenScreen","gifImage": "صورة GIF","mp4Video": "فيديو MP4","videoFiles": "ملفات فيديو",- "audioFiles": "Audio Files",+ "audioFiles": "ملفات الصوت","openscreenProject": "مشروع OpenScreen","allFiles": "جميع الملفات"}diff --git a/src/i18n/locales/ar/settings.json b/src/i18n/locales/ar/settings.jsonindex c97a9c024..4d673a706 100644--- a/src/i18n/locales/ar/settings.json+++ b/src/i18n/locales/ar/settings.json@@ -328,10 +328,10 @@"help": "اضبط مستوى إخراج الصوت. يُطبَّق بالطريقة نفسها في المعاينة وعند التصدير."},"audioTrack": {- "add": "Add audio track",- "importFailed": "Could not add audio",- "defaultLabel": "Audio track",- "help": "Volume, position, and mute for this imported audio track. It mixes over the recording in the preview and the export.",- "remove": "Delete track"+ "add": "إضافة مسار صوتي",+ "importFailed": "تعذّر إضافة الصوت",+ "defaultLabel": "مسار صوتي",+ "help": "مستوى صوت هذا المسار الصوتي المستورد. يُمزج فوق التسجيل في المعاينة والتصدير. اسحب المسار على المخطط الزمني لتحريكه أو اقتصاصه.",+ "remove": "حذف المسار"}}diff --git a/src/i18n/locales/es/dialogs.json b/src/i18n/locales/es/dialogs.jsonindex 10ebb2315..8f26a3aff 100644--- a/src/i18n/locales/es/dialogs.json+++ b/src/i18n/locales/es/dialogs.json@@ -79,13 +79,13 @@"saveGif": "Guardar GIF exportado","saveVideo": "Guardar video exportado","selectVideo": "Seleccionar archivo de video",- "selectAudio": "Select Audio File",+ "selectAudio": "Seleccionar archivo de audio","saveProject": "Guardar proyecto OpenScreen","openProject": "Abrir proyecto OpenScreen","gifImage": "Imagen GIF","mp4Video": "Video MP4","videoFiles": "Archivos de video",- "audioFiles": "Audio Files",+ "audioFiles": "Archivos de audio","openscreenProject": "Proyecto OpenScreen","allFiles": "Todos los archivos"}diff --git a/src/i18n/locales/es/settings.json b/src/i18n/locales/es/settings.jsonindex 2904ea0f4..06cd91da3 100644--- a/src/i18n/locales/es/settings.json+++ b/src/i18n/locales/es/settings.json@@ -328,10 +328,10 @@"help": "Ajusta el nivel de salida del audio. Se aplica igual en la vista previa y en la exportación."},"audioTrack": {- "add": "Add audio track",- "importFailed": "Could not add audio",- "defaultLabel": "Audio track",- "help": "Volume, position, and mute for this imported audio track. It mixes over the recording in the preview and the export.",- "remove": "Delete track"+ "add": "Añadir pista de audio",+ "importFailed": "No se pudo añadir el audio",+ "defaultLabel": "Pista de audio",+ "help": "Volumen de esta pista de audio importada. Se mezcla sobre la grabación en la vista previa y en la exportación. Arrastra la pista en la línea de tiempo para moverla o recortarla.",+ "remove": "Eliminar pista"}}diff --git a/src/i18n/locales/fr/dialogs.json b/src/i18n/locales/fr/dialogs.jsonindex a7691550e..ad5b4edf6 100644--- a/src/i18n/locales/fr/dialogs.json+++ b/src/i18n/locales/fr/dialogs.json@@ -79,13 +79,13 @@"saveGif": "Enregistrer le GIF exporté","saveVideo": "Enregistrer la vidéo exportée","selectVideo": "Sélectionner un fichier vidéo",- "selectAudio": "Select Audio File",+ "selectAudio": "Sélectionner un fichier audio","saveProject": "Enregistrer le projet OpenScreen","openProject": "Ouvrir un projet OpenScreen","gifImage": "Image GIF","mp4Video": "Vidéo MP4","videoFiles": "Fichiers vidéo",- "audioFiles": "Audio Files",+ "audioFiles": "Fichiers audio","openscreenProject": "Projet OpenScreen","allFiles": "Tous les fichiers"}diff --git a/src/i18n/locales/fr/settings.json b/src/i18n/locales/fr/settings.jsonindex 41acd38d5..16f8c8d98 100644--- a/src/i18n/locales/fr/settings.json+++ b/src/i18n/locales/fr/settings.json@@ -328,10 +328,10 @@"help": "Ajustez le niveau de sortie audio. Il s’applique à l’identique dans l’aperçu et à l’export."},"audioTrack": {- "add": "Add audio track",- "importFailed": "Could not add audio",- "defaultLabel": "Audio track",- "help": "Volume, position, and mute for this imported audio track. It mixes over the recording in the preview and the export.",- "remove": "Delete track"+ "add": "Ajouter une piste audio",+ "importFailed": "Impossible d’ajouter l’audio",+ "defaultLabel": "Piste audio",+ "help": "Volume de cette piste audio importée. Elle est mixée par-dessus l’enregistrement dans l’aperçu et à l’export. Faites glisser la piste sur la timeline pour la déplacer ou la rogner.",+ "remove": "Supprimer la piste"}}diff --git a/src/i18n/locales/it/dialogs.json b/src/i18n/locales/it/dialogs.jsonindex b26a83da9..e8e326c91 100644--- a/src/i18n/locales/it/dialogs.json+++ b/src/i18n/locales/it/dialogs.json@@ -79,13 +79,13 @@"saveGif": "Salva GIF esportata","saveVideo": "Salva video esportato","selectVideo": "Seleziona file video",- "selectAudio": "Select Audio File",+ "selectAudio": "Seleziona file audio","saveProject": "Salva progetto OpenScreen","openProject": "Apri progetto OpenScreen","gifImage": "Immagine GIF","mp4Video": "Video MP4","videoFiles": "File video",- "audioFiles": "Audio Files",+ "audioFiles": "File audio","openscreenProject": "Progetto OpenScreen","allFiles": "Tutti i file"}diff --git a/src/i18n/locales/it/settings.json b/src/i18n/locales/it/settings.jsonindex 83f0ae3c2..730a39397 100644--- a/src/i18n/locales/it/settings.json+++ b/src/i18n/locales/it/settings.json@@ -328,10 +328,10 @@"help": "Regola il livello di uscita audio. Si applica allo stesso modo nell’anteprima e nell’esportazione."},"audioTrack": {- "add": "Add audio track",- "importFailed": "Could not add audio",- "defaultLabel": "Audio track",- "help": "Volume, position, and mute for this imported audio track. It mixes over the recording in the preview and the export.",- "remove": "Delete track"+ "add": "Aggiungi traccia audio",+ "importFailed": "Impossibile aggiungere l’audio",+ "defaultLabel": "Traccia audio",+ "help": "Volume di questa traccia audio importata. Viene mixata sopra la registrazione nell’anteprima e nell’esportazione. Trascina la traccia sulla timeline per spostarla o ritagliarla.",+ "remove": "Elimina traccia"}}diff --git a/src/i18n/locales/ja-JP/dialogs.json b/src/i18n/locales/ja-JP/dialogs.jsonindex 911c2ad94..c0c00ad80 100644--- a/src/i18n/locales/ja-JP/dialogs.json+++ b/src/i18n/locales/ja-JP/dialogs.json@@ -79,13 +79,13 @@"saveGif": "エクスポートしたGIFを保存","saveVideo": "エクスポートした動画を保存","selectVideo": "動画ファイルを選択",- "selectAudio": "Select Audio File",+ "selectAudio": "オーディオファイルを選択","saveProject": "OpenScreen プロジェクトを保存","openProject": "OpenScreen プロジェクトを開く","gifImage": "GIF 画像","mp4Video": "MP4 動画","videoFiles": "動画ファイル",- "audioFiles": "Audio Files",+ "audioFiles": "オーディオファイル","openscreenProject": "OpenScreen プロジェクト","allFiles": "すべてのファイル"}diff --git a/src/i18n/locales/ja-JP/settings.json b/src/i18n/locales/ja-JP/settings.jsonindex 665fdf2e5..75ad59deb 100644--- a/src/i18n/locales/ja-JP/settings.json+++ b/src/i18n/locales/ja-JP/settings.json@@ -328,10 +328,10 @@"help": "音声の出力レベルを調整します。プレビューと書き出しで同じように適用されます。"},"audioTrack": {- "add": "Add audio track",- "importFailed": "Could not add audio",- "defaultLabel": "Audio track",- "help": "Volume, position, and mute for this imported audio track. It mixes over the recording in the preview and the export.",- "remove": "Delete track"+ "add": "オーディオトラックを追加",+ "importFailed": "オーディオを追加できませんでした",+ "defaultLabel": "オーディオトラック",+ "help": "このインポートしたオーディオトラックの音量。プレビューとエクスポートで録画に重ねてミックスされます。タイムライン上でドラッグして移動またはトリミングできます。",+ "remove": "トラックを削除"}}diff --git a/src/i18n/locales/ko-KR/dialogs.json b/src/i18n/locales/ko-KR/dialogs.jsonindex d654a5f52..2b64240ae 100644--- a/src/i18n/locales/ko-KR/dialogs.json+++ b/src/i18n/locales/ko-KR/dialogs.json@@ -79,13 +79,13 @@"saveGif": "내보낸 GIF 저장","saveVideo": "내보낸 비디오 저장","selectVideo": "비디오 파일 선택",- "selectAudio": "Select Audio File",+ "selectAudio": "오디오 파일 선택","saveProject": "OpenScreen 프로젝트 저장","openProject": "OpenScreen 프로젝트 열기","gifImage": "GIF 이미지","mp4Video": "MP4 비디오","videoFiles": "비디오 파일",- "audioFiles": "Audio Files",+ "audioFiles": "오디오 파일","openscreenProject": "OpenScreen 프로젝트","allFiles": "모든 파일"}diff --git a/src/i18n/locales/ko-KR/settings.json b/src/i18n/locales/ko-KR/settings.jsonindex be3e85813..98dbdcee9 100644--- a/src/i18n/locales/ko-KR/settings.json+++ b/src/i18n/locales/ko-KR/settings.json@@ -328,10 +328,10 @@"help": "오디오 출력 레벨을 조정합니다. 미리보기와 내보내기에 동일하게 적용됩니다."},"audioTrack": {- "add": "Add audio track",- "importFailed": "Could not add audio",- "defaultLabel": "Audio track",- "help": "Volume, position, and mute for this imported audio track. It mixes over the recording in the preview and the export.",- "remove": "Delete track"+ "add": "오디오 트랙 추가",+ "importFailed": "오디오를 추가할 수 없습니다",+ "defaultLabel": "오디오 트랙",+ "help": "가져온 이 오디오 트랙의 볼륨입니다. 미리 보기와 내보내기에서 녹화 위에 믹싱됩니다. 타임라인에서 트랙을 드래그하여 이동하거나 자를 수 있습니다.",+ "remove": "트랙 삭제"}}diff --git a/src/i18n/locales/pt-BR/dialogs.json b/src/i18n/locales/pt-BR/dialogs.jsonindex 7dbb4c642..88f163d99 100644--- a/src/i18n/locales/pt-BR/dialogs.json+++ b/src/i18n/locales/pt-BR/dialogs.json@@ -79,13 +79,13 @@"saveGif": "Salvar GIF Exportado","saveVideo": "Salvar Vídeo Exportado","selectVideo": "Selecionar Arquivo de Vídeo",- "selectAudio": "Select Audio File",+ "selectAudio": "Selecionar arquivo de áudio","saveProject": "Salvar Projeto OpenScreen","openProject": "Abrir Projeto OpenScreen","gifImage": "Imagem GIF","mp4Video": "Vídeo MP4","videoFiles": "Arquivos de Vídeo",- "audioFiles": "Audio Files",+ "audioFiles": "Arquivos de áudio","openscreenProject": "Projeto OpenScreen","allFiles": "Todos os Arquivos"}diff --git a/src/i18n/locales/pt-BR/settings.json b/src/i18n/locales/pt-BR/settings.jsonindex c67bf76f3..fd60b7a7e 100644--- a/src/i18n/locales/pt-BR/settings.json+++ b/src/i18n/locales/pt-BR/settings.json@@ -328,10 +328,10 @@"help": "Ajuste o nível de saída do áudio. Ele se aplica da mesma forma na prévia e na exportação."},"audioTrack": {- "add": "Add audio track",- "importFailed": "Could not add audio",- "defaultLabel": "Audio track",- "help": "Volume, position, and mute for this imported audio track. It mixes over the recording in the preview and the export.",- "remove": "Delete track"+ "add": "Adicionar faixa de áudio",+ "importFailed": "Não foi possível adicionar o áudio",+ "defaultLabel": "Faixa de áudio",+ "help": "Volume desta faixa de áudio importada. Ela é mixada sobre a gravação na prévia e na exportação. Arraste a faixa na linha do tempo para movê-la ou cortá-la.",+ "remove": "Excluir faixa"}}diff --git a/src/i18n/locales/ru/dialogs.json b/src/i18n/locales/ru/dialogs.jsonindex 7e1dbaeed..1f46a14fc 100644--- a/src/i18n/locales/ru/dialogs.json+++ b/src/i18n/locales/ru/dialogs.json@@ -79,13 +79,13 @@"saveGif": "Сохранить экспортированный GIF","saveVideo": "Сохранить экспортированное видео","selectVideo": "Выбрать видеофайл",- "selectAudio": "Select Audio File",+ "selectAudio": "Выбрать аудиофайл","saveProject": "Сохранить проект OpenScreen","openProject": "Открыть проект OpenScreen","gifImage": "GIF изображение","mp4Video": "MP4 видео","videoFiles": "Видеофайлы",- "audioFiles": "Audio Files",+ "audioFiles": "Аудиофайлы","openscreenProject": "Проект OpenScreen","allFiles": "Все файлы"}diff --git a/src/i18n/locales/ru/settings.json b/src/i18n/locales/ru/settings.jsonindex e8cdd5353..038d5a1f6 100644--- a/src/i18n/locales/ru/settings.json+++ b/src/i18n/locales/ru/settings.json@@ -328,10 +328,10 @@"help": "Настройте уровень звука на выходе. Он одинаково применяется в предпросмотре и при экспорте."},"audioTrack": {- "add": "Add audio track",- "importFailed": "Could not add audio",- "defaultLabel": "Audio track",- "help": "Volume, position, and mute for this imported audio track. It mixes over the recording in the preview and the export.",- "remove": "Delete track"+ "add": "Добавить аудиодорожку",+ "importFailed": "Не удалось добавить аудио",+ "defaultLabel": "Аудиодорожка",+ "help": "Громкость импортированной аудиодорожки. Она микшируется поверх записи в предпросмотре и при экспорте. Перетащите дорожку на шкале времени, чтобы переместить или обрезать её.",+ "remove": "Удалить дорожку"}}diff --git a/src/i18n/locales/tr/dialogs.json b/src/i18n/locales/tr/dialogs.jsonindex c6299d520..6b01da744 100644--- a/src/i18n/locales/tr/dialogs.json+++ b/src/i18n/locales/tr/dialogs.json@@ -79,13 +79,13 @@"saveGif": "Dışa Aktarılan GIF'i Kaydet","saveVideo": "Dışa Aktarılan Videoyu Kaydet","selectVideo": "Video Dosyası Seç",- "selectAudio": "Select Audio File",+ "selectAudio": "Ses dosyası seç","saveProject": "OpenScreen Projesini Kaydet","openProject": "OpenScreen Projesini Aç","gifImage": "GIF Görüntüsü","mp4Video": "MP4 Video","videoFiles": "Video Dosyaları",- "audioFiles": "Audio Files",+ "audioFiles": "Ses dosyaları","openscreenProject": "OpenScreen Projesi","allFiles": "Tüm Dosyalar"}diff --git a/src/i18n/locales/tr/settings.json b/src/i18n/locales/tr/settings.jsonindex 29b54ba66..31d925c21 100644--- a/src/i18n/locales/tr/settings.json+++ b/src/i18n/locales/tr/settings.json@@ -328,10 +328,10 @@"help": "Ses çıkış seviyesini ayarlayın. Önizlemede ve dışa aktarmada aynı şekilde uygulanır."},"audioTrack": {- "add": "Add audio track",- "importFailed": "Could not add audio",- "defaultLabel": "Audio track",- "help": "Volume, position, and mute for this imported audio track. It mixes over the recording in the preview and the export.",- "remove": "Delete track"+ "add": "Ses parçası ekle",+ "importFailed": "Ses eklenemedi",+ "defaultLabel": "Ses parçası",+ "help": "Bu içe aktarılmış ses parçasının ses düzeyi. Önizlemede ve dışa aktarmada kaydın üzerine miksleniyor. Taşımak veya kırpmak için parçayı zaman çizelgesinde sürükleyin.",+ "remove": "Parçayı sil"}}diff --git a/src/i18n/locales/vi/dialogs.json b/src/i18n/locales/vi/dialogs.jsonindex 213240763..452e80e2f 100644--- a/src/i18n/locales/vi/dialogs.json+++ b/src/i18n/locales/vi/dialogs.json@@ -79,13 +79,13 @@"saveGif": "Lưu GIF đã xuất","saveVideo": "Lưu Video đã xuất","selectVideo": "Chọn tệp video",- "selectAudio": "Select Audio File",+ "selectAudio": "Chọn tệp âm thanh","saveProject": "Lưu dự án OpenScreen","openProject": "Mở dự án OpenScreen","gifImage": "Hình ảnh GIF","mp4Video": "Video MP4","videoFiles": "Tệp Video",- "audioFiles": "Audio Files",+ "audioFiles": "Tệp âm thanh","openscreenProject": "Dự án OpenScreen","allFiles": "Tất cả các tệp"}diff --git a/src/i18n/locales/vi/settings.json b/src/i18n/locales/vi/settings.jsonindex 0a039ee2d..5bc0342b5 100644--- a/src/i18n/locales/vi/settings.json+++ b/src/i18n/locales/vi/settings.json@@ -328,10 +328,10 @@"help": "Điều chỉnh mức đầu ra của âm thanh. Nó được áp dụng giống hệt nhau trong bản xem trước và khi xuất."},"audioTrack": {- "add": "Add audio track",- "importFailed": "Could not add audio",- "defaultLabel": "Audio track",- "help": "Volume, position, and mute for this imported audio track. It mixes over the recording in the preview and the export.",- "remove": "Delete track"+ "add": "Thêm bản âm thanh",+ "importFailed": "Không thể thêm âm thanh",+ "defaultLabel": "Bản âm thanh",+ "help": "Âm lượng của bản âm thanh đã nhập này. Nó được trộn lên trên bản ghi trong bản xem trước và khi xuất. Kéo bản nhạc trên dòng thời gian để di chuyển hoặc cắt.",+ "remove": "Xóa bản nhạc"}}diff --git a/src/i18n/locales/zh-CN/dialogs.json b/src/i18n/locales/zh-CN/dialogs.jsonindex b28304f6c..db4f12730 100644--- a/src/i18n/locales/zh-CN/dialogs.json+++ b/src/i18n/locales/zh-CN/dialogs.json@@ -79,13 +79,13 @@"saveGif": "保存导出的 GIF","saveVideo": "保存导出的视频","selectVideo": "选择视频文件",- "selectAudio": "Select Audio File",+ "selectAudio": "选择音频文件","saveProject": "保存 OpenScreen 项目","openProject": "打开 OpenScreen 项目","gifImage": "GIF 图片","mp4Video": "MP4 视频","videoFiles": "视频文件",- "audioFiles": "Audio Files",+ "audioFiles": "音频文件","openscreenProject": "OpenScreen 项目","allFiles": "所有文件"}diff --git a/src/i18n/locales/zh-CN/settings.json b/src/i18n/locales/zh-CN/settings.jsonindex 4d0df64df..e4f40ee3c 100644--- a/src/i18n/locales/zh-CN/settings.json+++ b/src/i18n/locales/zh-CN/settings.json@@ -328,10 +328,10 @@"help": "调整音频输出电平。它在预览和导出中的效果完全一致。"},"audioTrack": {- "add": "Add audio track",- "importFailed": "Could not add audio",- "defaultLabel": "Audio track",- "help": "Volume, position, and mute for this imported audio track. It mixes over the recording in the preview and the export.",- "remove": "Delete track"+ "add": "添加音频轨道",+ "importFailed": "无法添加音频",+ "defaultLabel": "音频轨道",+ "help": "此导入音频轨道的音量。在预览和导出中会叠加混合到录制内容上。在时间轴上拖动轨道即可移动或裁剪。",+ "remove": "删除轨道"}}diff --git a/src/i18n/locales/zh-TW/dialogs.json b/src/i18n/locales/zh-TW/dialogs.jsonindex 6c3601511..f4830a611 100644--- a/src/i18n/locales/zh-TW/dialogs.json+++ b/src/i18n/locales/zh-TW/dialogs.json@@ -79,13 +79,13 @@"saveGif": "儲存匯出的 GIF","saveVideo": "儲存匯出的影片","selectVideo": "選擇影片檔案",- "selectAudio": "Select Audio File",+ "selectAudio": "選擇音訊檔案","saveProject": "儲存 OpenScreen 專案","openProject": "開啟 OpenScreen 專案","gifImage": "GIF 圖片","mp4Video": "MP4 影片","videoFiles": "影片檔案",- "audioFiles": "Audio Files",+ "audioFiles": "音訊檔案","openscreenProject": "OpenScreen 專案","allFiles": "所有檔案"}diff --git a/src/i18n/locales/zh-TW/settings.json b/src/i18n/locales/zh-TW/settings.jsonindex a34d7217d..be23c79c4 100644--- a/src/i18n/locales/zh-TW/settings.json+++ b/src/i18n/locales/zh-TW/settings.json@@ -329,10 +329,10 @@"help": "調整音訊輸出電平。它在預覽與匯出中的效果完全一致。"},"audioTrack": {- "add": "Add audio track",- "importFailed": "Could not add audio",- "defaultLabel": "Audio track",- "help": "Volume, position, and mute for this imported audio track. It mixes over the recording in the preview and the export.",- "remove": "Delete track"+ "add": "新增音訊軌道",+ "importFailed": "無法新增音訊",+ "defaultLabel": "音訊軌道",+ "help": "此匯入音訊軌道的音量。在預覽與匯出時會疊加混音到錄製內容上。在時間軸上拖曳軌道即可移動或裁剪。",+ "remove": "刪除軌道"}}diff --git a/src/lib/ai-edition/store/documentWriteAudit.test.ts b/src/lib/ai-edition/store/documentWriteAudit.test.tsindex 3641782fb..4647d87a4 100644--- a/src/lib/ai-edition/store/documentWriteAudit.test.ts+++ b/src/lib/ai-edition/store/documentWriteAudit.test.ts@@ -267,6 +267,9 @@ const DECLARED: WritePath[] = [// Source-dimension backfill for assets a migration left unprobed. On load, for// every project, whether or not the user touches anything.w("src/lib/ai-edition/store/useTimeline.ts", "useTimeline", "save", "automatic"),+ // Audio-duration backfill (issue #350) — the same on-load, un-asked-for probe+ // for imported audio assets whose duration didn't stamp at import.+ w("src/lib/ai-edition/store/useTimeline.ts", "useTimeline", "save", "automatic"),];function w(diff --git a/src/lib/ai-edition/store/projectStore.test.ts b/src/lib/ai-edition/store/projectStore.test.tsindex e2f69fce7..6039f0a11 100644--- a/src/lib/ai-edition/store/projectStore.test.ts+++ b/src/lib/ai-edition/store/projectStore.test.ts@@ -341,8 +341,7 @@ describe("useProjectStore", () => {"audio",);// Audio has no camera sidecar — the lookup that addAsset does must not run.- // biome-ignore lint/suspicious/noExplicitAny: test-only stub of the legacy contextBridge surface- expect((window as any).electronAPI.findRecordingCamera).not.toHaveBeenCalled();+ expect(vi.mocked(window.electronAPI.findRecordingCamera)).not.toHaveBeenCalled();// Probe returned null, so nothing to stamp: no extra save.expect(bridgeMocks.save).not.toHaveBeenCalled();});diff --git a/src/lib/ai-edition/store/projectStore.ts b/src/lib/ai-edition/store/projectStore.tsindex fef92136e..1b8217753 100644--- a/src/lib/ai-edition/store/projectStore.ts+++ b/src/lib/ai-edition/store/projectStore.ts@@ -426,8 +426,11 @@ export const useProjectStore = create<ProjectState>((set, get) => ({const asset = await get().addAudioAsset(path, label);if (!asset) return null;// addAudioAsset already committed the asset (with its probed duration), so- // the current document is the one to place the track on.- await get().addAudioTrack(asset.id);+ // the current document is the one to place the track on. If the placement+ // write fails or is superseded, the import did NOT succeed as a one-shot —+ // report failure rather than claim success with an asset but no track.+ const trackId = await get().addAudioTrack(asset.id);+ if (!trackId) return null;return asset;},diff --git a/src/lib/ai-edition/store/useTimeline.test.ts b/src/lib/ai-edition/store/useTimeline.test.tsindex c79ec343f..68bf29a97 100644--- a/src/lib/ai-edition/store/useTimeline.test.ts+++ b/src/lib/ai-edition/store/useTimeline.test.ts@@ -20,6 +20,7 @@ const probeVideoDurationMock = vi.hoisted(() => vi.fn());const probeVideoDimensionsMock = vi.hoisted(() =>vi.fn().mockResolvedValue({ width: 1920, height: 1080 }),);+const probeAudioDurationMock = vi.hoisted(() => vi.fn().mockResolvedValue(null));const toastErrorMock = vi.hoisted(() => vi.fn());vi.mock("sonner", () => ({ toast: { error: toastErrorMock } }));@@ -30,6 +31,7 @@ vi.mock("../timeline/duration", async (importOriginal) => {...actual,probeVideoDuration: probeVideoDurationMock,probeVideoDimensions: probeVideoDimensionsMock,+ probeAudioDuration: probeAudioDurationMock,};});@@ -1310,6 +1312,8 @@ describe("useTimeline audio tracks", () => {useProjectStore.getState().clear();clearHistory();for (const mock of Object.values(bridgeMocks)) mock.mockReset();+ probeAudioDurationMock.mockReset();+ probeAudioDurationMock.mockResolvedValue(null);bridgeMocks.save.mockImplementation(async (doc: typeof sampleDoc) => ({success: true,document: doc,@@ -1402,4 +1406,50 @@ describe("useTimeline audio tracks", () => {});expect(useProjectStore.getState().document?.audioTracks).toEqual([]);});++ // #350 regression: a failed import-time probe leaves durationSec at 0, which+ // makes the playback window zero-length. The on-load backfill re-probes and+ // stamps the real duration onto the asset AND the track, so it can play again.+ it("backfills a missing audio duration on load", async () => {+ probeAudioDurationMock.mockResolvedValue(12.5);+ // Asset imported with an unknown duration (probe failed), and a track that+ // cached the resulting 0.+ useProjectStore.setState({+ projectId: "proj_test",+ document: {+ ...sampleDoc,+ assets: [+ ...sampleDoc.assets,+ {+ id: "audio_2",+ kind: "audio",+ label: "bgm.mp3",+ originalPath: "/tmp/bgm.mp3",+ cameraTrack: null,+ },+ ],+ audioTracks: [+ {+ id: "trk_2",+ assetId: "audio_2",+ timelineStartSec: 0,+ durationSec: 0,+ trimStartSec: 0,+ gainDb: 0,+ label: "bgm.mp3",+ },+ ],+ },+ revision: 1,+ status: "ready",+ error: null,+ });+ renderTimeline();+ await waitFor(() => {+ const doc = useProjectStore.getState().document;+ expect(doc?.assets.find((a) => a.id === "audio_2")?.durationSec).toBe(12.5);+ expect(doc?.audioTracks[0]?.durationSec).toBe(12.5);+ });+ expect(probeAudioDurationMock).toHaveBeenCalledTimes(1);+ });});diff --git a/src/lib/ai-edition/store/useTimeline.ts b/src/lib/ai-edition/store/useTimeline.tsindex aed880208..df761bfed 100644--- a/src/lib/ai-edition/store/useTimeline.ts+++ b/src/lib/ai-edition/store/useTimeline.ts@@ -26,7 +26,7 @@ import {} from "../document/timeline";import type { AxcutClipCropRegion, AxcutDocument } from "../schema";import { hasAnyClipWithCamera } from "../timeline/camera";-import { probeVideoDimensions, probeVideoDuration } from "../timeline/duration";+import { probeAudioDuration, probeVideoDimensions, probeVideoDuration } from "../timeline/duration";import {anchorRegionsWithDerivedMs,dropPillsByIds,@@ -226,6 +226,57 @@ export function useTimeline() {};}, [document]);+ // Backfill the real duration of imported audio assets (issue #350), the audio+ // counterpart of the dimension backfill above. `addAudioAsset` probes once at+ // import; a transient failure (timeout, a file still being written) would+ // otherwise leave `durationSec` at 0 forever, and a 0-length window is a track+ // that never plays and a pill with no width. Re-probe on load — once per asset+ // per session, success or not — and stamp both the asset AND every track that+ // caches its duration, with `history: false` so the fix is not an undo step.+ const probedAudioAssetIdsRef = useRef<Set<string>>(new Set());+ useEffect(() => {+ if (!document) return;+ const usedAssetIds = new Set(document.audioTracks.map((t) => t.assetId));+ const missing = document.assets.filter(+ (a) =>+ a.kind === "audio" &&+ a.originalPath &&+ usedAssetIds.has(a.id) &&+ !(a.durationSec && a.durationSec > 0) &&+ !probedAudioAssetIdsRef.current.has(a.id),+ );+ if (missing.length === 0) return;+ let cancelled = false;+ void (async () => {+ const probed: Record<string, number> = {};+ for (const a of missing) {+ probedAudioAssetIdsRef.current.add(a.id);+ const durationSec = await probeAudioDuration(toFileUrl(a.originalPath));+ if (durationSec != null && durationSec > 0) probed[a.id] = durationSec;+ }+ if (cancelled || Object.keys(probed).length === 0) return;+ const current = useProjectStore.getState().document;+ if (!current) return;+ await useProjectStore.getState().saveDocument(+ {+ ...current,+ assets: current.assets.map((a) =>+ probed[a.id] ? { ...a, durationSec: probed[a.id] } : a,+ ),+ audioTracks: current.audioTracks.map((t) =>+ probed[t.assetId] && !(t.durationSec > 0)+ ? { ...t, durationSec: probed[t.assetId] }+ : t,+ ),+ },+ { history: false },+ );+ })();+ return () => {+ cancelled = true;+ };+ }, [document]);+// Every add* below anchors the new region to the clip(s) it covers before storing it.// A modifier MUST own a clip anchor to survive reorder/trim (see// technical-documentation/architecture/timeline-model.md) — writing only startMs/endMs@@ -1209,18 +1260,31 @@ export function useTimeline() {// Place a new track for an imported audio asset, its head at the playhead (in// output-timeline seconds) unless the caller says otherwise. Delegates to the- // store op, which also selects the new track and returns its id (or null).+ // store op, which also selects the new track and returns its id (or null). On+ // success, retire the hook-local region/clip selection so the new audio-track+ // selection isn't held CONCURRENTLY with a stale region/clip one.const addAudioTrack = useCallback(- (assetId: string, timelineStartSec?: number): Promise<string | null> =>- storeAddAudioTrack(assetId, timelineStartSec ?? playheadSec()),+ async (assetId: string, timelineStartSec?: number): Promise<string | null> => {+ const id = await storeAddAudioTrack(assetId, timelineStartSec ?? playheadSec());+ if (id) {+ setSelection(null);+ setMultiSelection([]);+ setClipSelection(null);+ }+ return id;+ },[storeAddAudioTrack],);const removeAudioTrack = useCallback(async (trackId: string) => {if (!document) return;- if (selectedAudioTrackId === trackId) setSelectedAudioTrackId(null);- await saveDocument(removeAudioTrackInDocument(document, trackId), { history: true });+ // Clear the inspector selection only AFTER the delete commits. A failed+ // write leaves the track in the document, so it must keep its selection.+ const ok = await saveDocument(removeAudioTrackInDocument(document, trackId), {+ history: true,+ });+ if (ok && selectedAudioTrackId === trackId) setSelectedAudioTrackId(null);},[document, saveDocument, selectedAudioTrackId, setSelectedAudioTrackId],);diff --git a/src/native/browserShim.test.ts b/src/native/browserShim.test.tsnew file mode 100644index 000000000..07f5966b8--- /dev/null+++ b/src/native/browserShim.test.ts@@ -0,0 +1,60 @@+// @vitest-environment jsdom+// The shim persists projects to localStorage, so this needs a DOM.+import { beforeAll, beforeEach, describe, expect, it } from "vitest";+import type { AxcutDocument } from "@/lib/ai-edition/schema";+import { installBrowserShims } from "./browserShim";+import { nativeBridgeClient } from "./client";++// The bridge contract types `document` as `unknown`; the shim returns real+// AxcutDocuments, so narrow here rather than reaching for `any`.+const asDoc = (d: unknown) => d as AxcutDocument;++// installBrowserShims patches the real nativeBridgeClient's methods in place, so+// installing once is enough; each test starts from a clean localStorage. The+// `?browser` query is what flips detectBrowserMode() on outside Electron.+beforeAll(() => {+ window.history.replaceState(null, "", "/?browser");+ installBrowserShims();+});+beforeEach(() => {+ localStorage.clear();+});++async function freshProjectId(): Promise<string> {+ const created = await nativeBridgeClient.aiEdition.create("P");+ const id = asDoc(created.document).project.id;+ if (!id) throw new Error("shim create returned no project");+ return id;+}++describe("browserShim addAsset (issue #350)", () => {+ it("keeps kind 'audio' and does not claim the empty primary slot", async () => {+ const projectId = await freshProjectId();+ const res = await nativeBridgeClient.aiEdition.addAsset(+ projectId,+ "/tmp/music.mp3",+ "music",+ "audio",+ );+ const doc = asDoc(res.document);+ const asset = doc.assets.at(-1);+ expect(asset?.kind).toBe("audio");+ // An audio import must never become the primary asset (mirrors the main+ // process's document-service.addAsset).+ expect(doc.project.primaryAssetId).toBeUndefined();+ });++ it("still lets a video import claim the empty primary slot", async () => {+ const projectId = await freshProjectId();+ const res = await nativeBridgeClient.aiEdition.addAsset(+ projectId,+ "/tmp/screen.mp4",+ "screen",+ "video",+ );+ const doc = asDoc(res.document);+ const asset = doc.assets.at(-1);+ expect(asset?.kind).toBe("video");+ expect(doc.project.primaryAssetId).toBe(asset?.id);+ });+});