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
feat(export): mix imported audio tracks into the exported MP4
Benjamin Freeman83eb89b61b0b
diff --git a/crates/compositor/src/audio.rs b/crates/compositor/src/audio.rsindex e51f0f8af..bfc7d264c 100644--- a/crates/compositor/src/audio.rs+++ b/crates/compositor/src/audio.rs@@ -5,7 +5,7 @@use crate::ffi::*;use crate::regions::SpeedSegment;-use crate::scene::SceneAudio;+use crate::scene::{SceneAudio, SceneAudioTrack};use anyhow::{bail, Result};use std::f32::consts::PI;use std::ffi::CString;@@ -1381,6 +1381,71 @@ pub fn assemble_concatenated_pcm(output}+/// Mix imported audio tracks (issue #350) over the assembled programme.+///+/// Each track is decoded across its trim window — already resampled to 48 kHz+/// stereo by `decode_clip_audio`, the same path a clip's own audio takes — scaled+/// by its per-track gain (the same `10^(dB/20)` law as `finish_audio`), and summed+/// into the programme at `start_sec`. The programme length is NOT extended: a+/// track that runs past the video is truncated to it, so the audio and video+/// streams stay the same length for the muxer.+///+/// A muted track, or one 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.+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 {+ if track.mute {+ continue;+ }+ let trim_start = track.trim_start_sec.max(0.0);+ let Some(trim_end) = 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;+ };+ if trim_end <= trim_start {+ continue;+ }+ let decoded = match decode_clip_audio(&track.path, trim_start, trim_end) {+ Ok(Some(pcm)) => pcm,+ _ => 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+}++/// Sum one decoded track into the programme at `offset` samples, scaled by `gain`,+/// truncated at the programme's end. Split out of `mix_external_tracks` so the+/// placement/gain/clamp math is testable without ffmpeg, exactly like+/// `mix_aligned_tracks` is split from the decode above.+fn overlay_track_pcm(programme: &mut PlanarPcm, decoded: &PlanarPcm, offset: usize, gain: f32) {+ let programme_len = programme.first().map(Vec::len).unwrap_or(0);+ if offset >= programme_len {+ return;+ }+ let room = programme_len - offset;+ for channel in 0..AUDIO_OUTPUT_CHANNELS {+ let Some(source) = decoded.get(channel) else {+ continue;+ };+ let count = source.len().min(room);+ let dst = &mut programme[channel];+ for k in 0..count {+ dst[offset + k] += source[k] * gain;+ }+ }+}+/// Encodeur AAC attaché au muxer avant son header. Les paquets utilisent le même interleaver/// que la vidéo ; les pts restent en unités échantillon jusqu'au rescale vers l'AVStream.pub(crate) struct AacEncoder {@@ -1692,6 +1757,58 @@ mod tests {assert_eq!(mixed[1], vec![0.25, -0.5, 0.75]);}+ // Imported audio track overlay (issue #350).+ #[test]+ fn overlay_sums_at_offset_with_gain() {+ let mut programme = planar(&[0.1, 0.1, 0.1, 0.1]);+ // ×2 gain, placed at sample offset 1.+ overlay_track_pcm(&mut programme, &planar(&[0.2, 0.2]), 1, 2.0);+ assert_eq!(programme[0], vec![0.1, 0.5, 0.5, 0.1]);+ assert_eq!(programme[1], vec![0.1, 0.5, 0.5, 0.1]);+ }++ #[test]+ fn overlay_truncates_a_track_that_runs_past_the_programme() {+ let mut programme = planar(&[0.0, 0.0, 0.0]);+ // A 4-sample track placed at offset 2 has room for only 1 sample.+ overlay_track_pcm(&mut programme, &planar(&[1.0, 1.0, 1.0, 1.0]), 2, 1.0);+ assert_eq!(programme[0], vec![0.0, 0.0, 1.0]);+ }++ #[test]+ fn overlay_past_the_end_is_a_no_op() {+ let mut programme = planar(&[0.3, 0.3]);+ overlay_track_pcm(&mut programme, &planar(&[1.0]), 5, 1.0);+ assert_eq!(programme[0], vec![0.3, 0.3]);+ }++ #[test]+ fn mix_external_tracks_skips_muted_and_empty_windows() {+ let programme = planar(&[0.4, 0.4]);+ let tracks = vec![+ SceneAudioTrack {+ path: "/nope.mp3".into(),+ start_sec: 0.0,+ gain_db: 0.0,+ trim_start_sec: 0.0,+ trim_end_sec: Some(1.0),+ mute: true,+ },+ SceneAudioTrack {+ path: "/nope.mp3".into(),+ start_sec: 0.0,+ gain_db: 0.0,+ trim_start_sec: 2.0,+ trim_end_sec: Some(1.0), // end <= start: empty window, never decoded+ mute: false,+ },+ ];+ // Both tracks are skipped before any decode, so the programme is untouched+ // even though the path does not exist.+ 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/crates/compositor/src/pipeline_linux.rs b/crates/compositor/src/pipeline_linux.rsindex 03a8a5e52..bc54c3843 100644--- a/crates/compositor/src/pipeline_linux.rs+++ b/crates/compositor/src/pipeline_linux.rs@@ -27,8 +27,8 @@ use std::ffi::CString;use std::ptr;use crate::audio::{- assemble_concatenated_pcm, build_audio_concat_plan, finish_audio,- AacEncoder, PlanarPcm,+ assemble_concatenated_pcm, build_audio_concat_plan, decode_clip_audio, finish_audio,+ mix_external_tracks, stretch_clip_pcm_by_speed, AacEncoder, PlanarPcm,};use crate::audio_jobs::{decode_and_stretch_clip_audio, ClipAudioJobs};use crate::config::Cfg;@@ -1002,6 +1002,12 @@ pub fn run_composited_multi(let scene = comp.scene_snapshot();let audio_settings = scene.as_ref().map(|scene| scene.audio).unwrap_or_default();+ // Imported audio tracks (issue #350), cloned out of the borrowed scene so the+ // mix step below owns them. Empty for a project with no imported audio.+ let audio_tracks = scene+ .as_ref()+ .map(|scene| scene.audio_tracks.clone())+ .unwrap_or_default();// Ring de staging a 2 : l'export ne veut que du debit, une frame de latence// ne se voit pas dans un fichier. Voir `Compositor::set_readback_depth` pour// la raison pour laquelle la preview, elle, reste a 1.@@ -1190,7 +1196,10 @@ pub fn run_composited_multi(let plan = build_audio_concat_plan(&clip_frame_counts, &declared_audio, out_fps as f64);let octx = mux.octx;mux.aac.encode(- &finish_audio(assemble_concatenated_pcm(&clip_pcm, &plan), audio_settings),+ &finish_audio(+ mix_external_tracks(assemble_concatenated_pcm(&clip_pcm, &plan), &audio_tracks),+ audio_settings,+ ),octx,)?;mux.finish()?;diff --git a/crates/compositor/src/pipeline_macos.rs b/crates/compositor/src/pipeline_macos.rsindex ba6034d0f..1b3f75798 100644--- a/crates/compositor/src/pipeline_macos.rs+++ b/crates/compositor/src/pipeline_macos.rs@@ -30,8 +30,8 @@//! décodeurs, symétrique.use crate::audio::{- assemble_concatenated_pcm, build_audio_concat_plan, finish_audio,- AacEncoder, PlanarPcm,+ assemble_concatenated_pcm, build_audio_concat_plan, decode_clip_audio, finish_audio,+ mix_external_tracks, stretch_clip_pcm_by_speed, AacEncoder, PlanarPcm,};use crate::audio_jobs::{decode_and_stretch_clip_audio, ClipAudioJobs};use crate::compositor::Compositor;@@ -1172,6 +1172,11 @@ pub fn run_composited_multi(// raconte avoir déjà coûté une fois.let scene = comp.scene_snapshot();let audio_settings = scene.as_ref().map(|scene| scene.audio).unwrap_or_default();+ // Imported audio tracks (issue #350), cloned out of the borrowed scene.+ let audio_tracks = scene+ .as_ref()+ .map(|scene| scene.audio_tracks.clone())+ .unwrap_or_default();frames = unsafe {crate::timeline_walk::walk_composited_timeline(clips,@@ -1247,7 +1252,10 @@ pub fn run_composited_multi(let declared_audio: Vec<bool> = clips.iter().map(|clip| clip.has_audio).collect();let plan = build_audio_concat_plan(&clip_frame_counts, &declared_audio, out_fps as f64);audio_encoder.encode(- &finish_audio(assemble_concatenated_pcm(&clip_pcm, &plan), audio_settings),+ &finish_audio(+ mix_external_tracks(assemble_concatenated_pcm(&clip_pcm, &plan), &audio_tracks),+ audio_settings,+ ),octx,)?;diff --git a/crates/compositor/src/pipeline_windows.rs b/crates/compositor/src/pipeline_windows.rsindex f51e9e656..43e6fc826 100644--- a/crates/compositor/src/pipeline_windows.rs+++ b/crates/compositor/src/pipeline_windows.rs@@ -3,8 +3,8 @@//! tout le run, deux lectures seulement. Rien dans la boucle ne peut fausser le fps.use crate::audio::{- assemble_concatenated_pcm, build_audio_concat_plan, finish_audio,- AacEncoder, PlanarPcm,+ assemble_concatenated_pcm, build_audio_concat_plan, decode_clip_audio, finish_audio,+ mix_external_tracks, stretch_clip_pcm_by_speed, AacEncoder, PlanarPcm,};use crate::audio_jobs::{decode_and_stretch_clip_audio, ClipAudioJobs};use crate::compositor::{Compositor, OUT_H, OUT_W};@@ -1351,6 +1351,11 @@ unsafe fn run_multi_inner(// fenêtrage par clip ; `walk_composited_timeline` s'en charge.let scene = comp.scene_snapshot();let audio_settings = scene.as_ref().map(|scene| scene.audio).unwrap_or_default();+ // Imported audio tracks (issue #350), cloned out of the borrowed scene.+ let audio_tracks = scene+ .as_ref()+ .map(|scene| scene.audio_tracks.clone())+ .unwrap_or_default();// ---- encodeur (choisi à l'exécution, cf. ExportCodec::candidates) + mux ----// Backend CPU : pas de pool D3D11 du tout. `av_hwdevice_ctx_init(D3D11VA)` échoue sur@@ -1484,7 +1489,7 @@ unsafe fn run_multi_inner(out_fps as f64,);let assembled_audio = finish_audio(- assemble_concatenated_pcm(&clip_pcm, &audio_plan),+ mix_external_tracks(assemble_concatenated_pcm(&clip_pcm, &audio_plan), &audio_tracks),audio_settings,);audio_encoder.encode(&assembled_audio, octx)?;diff --git a/crates/compositor/src/scene.rs b/crates/compositor/src/scene.rsindex ff300d475..3a88e4870 100644--- a/crates/compositor/src/scene.rs+++ b/crates/compositor/src/scene.rs@@ -432,6 +432,31 @@ pub struct SceneAudio {pub gain_db: f32,}+/// One imported audio track (issue #350) mixed over the assembled programme —+/// voiceover / BGM / SFX. Deliberately a SEPARATE `Scene` field rather than a+/// member of `SceneAudio`, so `SceneAudio` stays `Copy` and the pipelines keep+/// copying it out of a borrow unchanged.+///+/// `start_sec` is the track's head on the OUTPUT programme; `trim_start_sec` /+/// `trim_end_sec` window the source file (both source seconds). The renderer+/// resolves `start_sec` from the track's raw timeline position — equal to it when+/// the project has no trims/speed, which is the case this first cut mixes exactly.+#[derive(Debug, Clone, Default, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct SceneAudioTrack {+ pub path: String,+ #[serde(default)]+ pub start_sec: f64,+ #[serde(default)]+ pub gain_db: f32,+ #[serde(default)]+ pub trim_start_sec: f64,+ #[serde(default)]+ pub trim_end_sec: Option<f64>,+ #[serde(default)]+ pub mute: bool,+}+#[derive(Debug, Clone, Copy, Deserialize)]#[serde(rename_all = "camelCase")]pub struct SceneOutput {@@ -500,6 +525,10 @@ pub struct Scene {/// Global audio finishing. Default keeps old scene payloads bit-for-bit compatible.#[serde(default)]pub audio: SceneAudio,+ /// Imported audio tracks mixed over the programme (issue #350). `#[serde(default)]`:+ /// absent from every scene written before this, and from a project with none.+ #[serde(default)]+ pub audio_tracks: Vec<SceneAudioTrack>,/// Crop écran par clip, dans le même ordre que `clips` (`cropByClip` côté TS).#[serde(default)]pub crop_by_clip: Vec<Option<SceneCrop>>,diff --git a/src/lib/ai-edition/schema/index.ts b/src/lib/ai-edition/schema/index.tsindex b55ef79fc..f0998feed 100644--- a/src/lib/ai-edition/schema/index.ts+++ b/src/lib/ai-edition/schema/index.ts@@ -477,16 +477,21 @@ export const zoomRegionSchema = endGteStart();// External audio import (issue #350) — voiceover / BGM / SFX layered over the-// assembled programme. Unlike zoom/speed/annotation/trim, an audio track is NOT-// clip-anchored: it floats over the whole timeline, so it is addressed in OUTPUT-// (post-trim, post-speed) timeline seconds — the same domain the compositor's-// concatenated programme PCM lives in (see `SceneAudio` in-// src/native/sceneDescription.ts and `audio.rs`). That single invariant is what-// keeps the live preview and the export in sync without a per-track sync offset.+// programme. Unlike zoom/speed/annotation/trim, an audio track is NOT+// clip-anchored: it floats over the whole timeline, addressed in RAW/document+// timeline seconds — the same clock the ruler, playhead and clip+// `timelineStartSec`/`timelineEndSec` use, and the one `addAudioTrack` seeds from+// the playhead. The preview positions the track on exactly this clock (see+// `resolveTimelineAudioPlayback` in VirtualPreview). The export's OUTPUT programme+// is trim-compressed, so the renderer maps this position to output time when+// building the scene — an identity map when the project has no trims/speed (the+// common case), an accepted approximation otherwise, the same way the preview+// approximates trims by re-seeking. See `SceneAudioTrack` (sceneDescription.ts,+// audio.rs).//// `assetId` points at an asset with `kind: "audio"`. `timelineStartSec` places-// the track's head on the programme; `trimStartSec`/`trimEndSec` window the-// source file (both in source seconds); `gainDb` + `mute` set its level.+// the track's head; `trimStartSec`/`trimEndSec` window the source file (both in+// source seconds); `gainDb` + `mute` set its level.export const audioTrackSchema = z.object({id: z.string().min(1),diff --git a/src/native/sceneDescription.test.ts b/src/native/sceneDescription.test.tsindex 171d2ac4d..6b2bcde7c 100644--- a/src/native/sceneDescription.test.ts+++ b/src/native/sceneDescription.test.ts@@ -1991,3 +1991,57 @@ describe("buildSceneDescription.captions", () => {expect(text?.color).toBe("#ffffff");});});++// --- imported audio tracks (issue #350) ------------------------------------+describe("buildSceneDescription.audioTracks", () => {+ const audioAsset = makeAsset({+ id: "aud",+ kind: "audio",+ originalPath: "/music.mp3",+ durationSec: 30,+ });+ const track = {+ id: "trk1",+ assetId: "aud",+ timelineStartSec: 5,+ durationSec: 30,+ trimStartSec: 2,+ trimEndSec: 12 as number | undefined,+ gainDb: -3,+ mute: false,+ label: "",+ };++ it("maps a track to the mix list with its resolved path and window", () => {+ const doc = makeDoc({ assets: [audioAsset], audioTracks: [track] });+ expect(buildSceneDescription(doc).audioTracks).toEqual([+ {+ path: "/music.mp3",+ startSec: 5,+ gainDb: -3,+ trimStartSec: 2,+ trimEndSec: 12,+ mute: false,+ },+ ]);+ });++ it("resolves the trim-out to the source duration when the tail isn't trimmed", () => {+ const doc = makeDoc({+ assets: [audioAsset],+ audioTracks: [{ ...track, trimEndSec: undefined }],+ });+ // trimEndSec must be concrete for the compositor; falls back to durationSec.+ expect(buildSceneDescription(doc).audioTracks[0]?.trimEndSec).toBe(30);+ });++ it("drops a track whose asset has no resolvable path", () => {+ const doc = makeDoc({ assets: [], audioTracks: [track] });+ expect(buildSceneDescription(doc).audioTracks).toEqual([]);+ });++ it("is empty for a project with no imported audio", () => {+ const doc = makeDoc({ assets: [makeAsset({ id: "a", originalPath: "/a.mp4" })] });+ expect(buildSceneDescription(doc).audioTracks).toEqual([]);+ });+});diff --git a/src/native/sceneDescription.ts b/src/native/sceneDescription.tsindex 376a8580a..db03ad82b 100644--- a/src/native/sceneDescription.ts+++ b/src/native/sceneDescription.ts@@ -411,6 +411,23 @@ export interface SceneDescription {audio: {gainDb: number;};+ /**+ * Imported audio tracks (issue #350), mixed over the assembled programme by+ * `audio::mix_external_tracks`. `startSec` is the head on the OUTPUT programme;+ * it equals the track's raw timeline position, which is exact when the project+ * has no trims/speed and an accepted approximation otherwise (the preview+ * approximates the same way). `trimEndSec` is always concrete — the compositor+ * preallocates the decode window from it — so it is resolved to the source+ * duration when the track's tail isn't trimmed.+ */+ audioTracks: Array<{+ path: string;+ startSec: number;+ gainDb: number;+ trimStartSec: number;+ trimEndSec: number;+ mute: boolean;+ }>;/*** Per-clip screen crop (fractions of the frame), or null for the identity* (full-frame) crop. One entry per clip in the same order as `clips`, so a@@ -487,6 +504,25 @@ export function buildSceneDescription(const settings = getEditorSettings(document);const assetById = new Map(document.assets.map((a) => [a.id, a]));+ // Imported audio tracks (issue #350) → the compositor's mix list. Resolve the+ // asset's file path and a concrete trim-out (the source duration when the tail+ // isn't trimmed — the compositor preallocates its decode window from it). A+ // track whose asset or path is missing is dropped rather than sent path-less.+ const audioTracks = document.audioTracks.flatMap((track) => {+ const asset = assetById.get(track.assetId);+ if (!asset?.originalPath) return [];+ const trimEndSec = track.trimEndSec ?? asset.durationSec ?? track.durationSec;+ return [+ {+ path: asset.originalPath,+ startSec: track.timelineStartSec,+ gainDb: track.gainDb,+ trimStartSec: track.trimStartSec,+ trimEndSec,+ mute: track.mute,+ },+ ];+ });const visibleClips = resolveVisibleClips(document);const clips: CompositorClipInput[] = visibleClips.flatMap((clip) => {const asset = assetById.get(clip.assetId);@@ -821,6 +857,7 @@ export function buildSceneDescription(audio: {gainDb: settings.audioGainDb,},+ audioTracks,background: parseWallpaper(settings.wallpaper),zoomRegions: projectedZoomRegions.map((region) => ({id: region.id,diff --git a/technical-documentation/architecture/export-pipeline.md b/technical-documentation/architecture/export-pipeline.mdindex fd2d7446f..6f44d3a9d 100644--- a/technical-documentation/architecture/export-pipeline.md+++ b/technical-documentation/architecture/export-pipeline.md@@ -110,6 +110,19 @@ and **one** encoder + muxer pair:table, asserted by `outputFrameCount.test.ts` and by`speed_segments_match_the_exporter_frame_totals`.+- **Imported audio tracks** (voiceover / BGM / SFX, issue #350) are mixed+ on top of the assembled programme by `audio.rs::mix_external_tracks`,+ between `assemble_concatenated_pcm` and `finish_audio`. Each track's+ trim window is decoded through the same `decode_clip_audio` path a clip+ uses, scaled by its per-track gain, and summed in at its `startSec`+ offset; a track running past the video is truncated to it so the two+ streams stay the same length. `startSec` is resolved renderer-side+ (`buildSceneDescription`) from the track's raw timeline position — an+ identity map without trims/speed, an accepted approximation otherwise,+ matching how the preview approximates trims by re-seeking. The CLI's+ `openscreen export --audio` remains a separate post-export remux+ (`voiceoverMix.ts`) for a single track and is unaffected.+- **Output** honours the timeline's selected aspect ratio(`resolveAspectRatioValue` over `getEditorSettings(document).aspectRatio` —the same typed façade `buildSceneDescription` reads, so the dialog cannot