Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

feat(editor): add audio mastering and webcam crop controls

Vitali Gusatinskyef0af7de2ef2
diff --git a/crates/compositor/src/audio.rs b/crates/compositor/src/audio.rs
index 1b51a7a99..9a6375528 100644
--- a/crates/compositor/src/audio.rs
+++ b/crates/compositor/src/audio.rs
@@ -4,6 +4,7 @@
use crate::ffi::*;
use crate::regions::SpeedSegment;
+use crate::scene::SceneAudio;
use anyhow::{bail, Result};
use std::f32::consts::PI;
use std::ffi::CString;
@@ -26,6 +27,114 @@ const PASSTHROUGH_EPSILON: f64 = 1e-3;
pub type PlanarPcm = Vec<Vec<f32>>;
+/// Apply the editor's signed sync offset and fast voice-oriented mastering.
+///
+/// The automatic path is deliberately deterministic and dependency-free: an 80 Hz high-pass
+/// removes desk/room rumble, a linked-stereo 3:1 compressor controls speech peaks, and a final
+/// RMS/peak pass raises intelligibility without clipping. Linking the envelope preserves the
+/// stereo image. The result stays the same length so video and following clips cannot drift.
+pub fn finish_audio(mut pcm: PlanarPcm, settings: SceneAudio) -> PlanarPcm {
+ let samples = pcm.first().map(Vec::len).unwrap_or(0);
+ if samples == 0 {
+ return pcm;
+ }
+ for channel in pcm.iter_mut() {
+ channel.resize(samples, 0.0);
+ }
+
+ if settings.auto_master {
+ let cutoff_hz = 80.0f32;
+ let dt = 1.0 / AUDIO_OUTPUT_SAMPLE_RATE as f32;
+ let rc = 1.0 / (2.0 * PI * cutoff_hz);
+ let alpha = rc / (rc + dt);
+ for channel in pcm.iter_mut() {
+ let mut previous_input = 0.0f32;
+ let mut previous_output = 0.0f32;
+ for sample in channel.iter_mut() {
+ let input = *sample;
+ let output = alpha * (previous_output + input - previous_input);
+ *sample = output;
+ previous_input = input;
+ previous_output = output;
+ }
+ }
+
+ let threshold_db = -18.0f32;
+ let ratio = 3.0f32;
+ let attack = (-1.0 / (0.010 * AUDIO_OUTPUT_SAMPLE_RATE as f32)).exp();
+ let release = (-1.0 / (0.120 * AUDIO_OUTPUT_SAMPLE_RATE as f32)).exp();
+ let mut envelope = 0.0f32;
+ for index in 0..samples {
+ let peak = pcm
+ .iter()
+ .map(|channel| channel[index].abs())
+ .fold(0.0f32, f32::max);
+ let coefficient = if peak > envelope { attack } else { release };
+ envelope = coefficient * envelope + (1.0 - coefficient) * peak;
+ let level_db = 20.0 * envelope.max(1e-9).log10();
+ let reduction_db = if level_db > threshold_db {
+ (level_db - threshold_db) * (1.0 - 1.0 / ratio)
+ } else {
+ 0.0
+ };
+ let reduction = 10.0f32.powf(-reduction_db / 20.0);
+ for channel in pcm.iter_mut() {
+ channel[index] *= reduction;
+ }
+ }
+
+ let mut sum_squares = 0.0f64;
+ let mut count = 0usize;
+ let mut peak = 0.0f32;
+ for &sample in pcm.iter().flatten() {
+ peak = peak.max(sample.abs());
+ if sample.abs() > 1e-5 {
+ sum_squares += (sample as f64) * (sample as f64);
+ count += 1;
+ }
+ }
+ if count > 0 && peak > 0.0 {
+ let rms = (sum_squares / count as f64).sqrt() as f32;
+ let target_rms = 10.0f32.powf(-16.0 / 20.0);
+ let peak_ceiling = 10.0f32.powf(-1.0 / 20.0);
+ let makeup = (target_rms / rms.max(1e-9))
+ .min(peak_ceiling / peak)
+ .clamp(0.1, 4.0);
+ for sample in pcm.iter_mut().flatten() {
+ *sample *= makeup;
+ }
+ }
+ }
+
+ let trim = 10.0f32.powf(settings.gain_db.clamp(-24.0, 18.0) / 20.0);
+ for sample in pcm.iter_mut().flatten() {
+ *sample = (*sample * trim).clamp(-1.0, 1.0);
+ }
+
+ let shift = ((settings.offset_ms.clamp(-2_000.0, 2_000.0) / 1_000.0)
+ * AUDIO_OUTPUT_SAMPLE_RATE as f64)
+ .round() as i64;
+ if shift == 0 {
+ return pcm;
+ }
+ let mut shifted = vec![vec![0.0f32; samples]; pcm.len()];
+ if shift > 0 {
+ let destination = (shift as usize).min(samples);
+ let count = samples - destination;
+ for channel in 0..pcm.len() {
+ shifted[channel][destination..destination + count]
+ .copy_from_slice(&pcm[channel][..count]);
+ }
+ } else {
+ let source = ((-shift) as usize).min(samples);
+ let count = samples - source;
+ for channel in 0..pcm.len() {
+ shifted[channel][..count].copy_from_slice(&pcm[channel][source..source + count]);
+ }
+ }
+ shifted
+}
+
extern "C" {
fn sn_fmt_stream(s: *mut AVFormatContext, i: i32) -> *mut AVStream;
// bindgen rend `AVFormatContext` opaque (atteinte seulement par pointeur), d'où l'accesseur
@@ -1063,4 +1172,65 @@ mod tests {
let mixed = mix_aligned_tracks(&[(-0.001, &early)], 0.0, 8);
assert_eq!(mixed[0], vec![0.5; 8]);
}
+
+ #[test]
+ fn signed_audio_offset_is_length_preserving() {
+ let settings = SceneAudio {
+ offset_ms: 1000.0 / AUDIO_OUTPUT_SAMPLE_RATE as f64,
+ gain_db: 0.0,
+ auto_master: false,
+ };
+ let delayed = finish_audio(planar(&[1.0, 2.0, 3.0]), settings);
+ assert_eq!(delayed[0], vec![0.0, 1.0, 1.0]);
+
+ let advanced = finish_audio(
+ planar(&[1.0, 0.5, 0.25]),
+ SceneAudio {
+ offset_ms: -1000.0 / AUDIO_OUTPUT_SAMPLE_RATE as f64,
+ ..settings
+ },
+ );
+ assert_eq!(advanced[0], vec![0.5, 0.25, 0.0]);
+ }
+
+ #[test]
+ fn manual_gain_is_applied_when_auto_master_is_off() {
+ let result = finish_audio(
+ planar(&[0.25, -0.25]),
+ SceneAudio {
+ offset_ms: 0.0,
+ gain_db: 6.0206,
+ auto_master: false,
+ },
+ );
+ assert!((result[0][0] - 0.5).abs() < 1e-4);
+ assert!((result[0][1] + 0.5).abs() < 1e-4);
+ }
+
+ #[test]
+ fn auto_master_removes_dc_and_respects_peak_ceiling() {
+ let mut input = vec![0.2f32; AUDIO_OUTPUT_SAMPLE_RATE as usize / 2];
+ for index in (0..input.len()).step_by(400) {
+ input[index] = 1.0;
+ }
+ let result = finish_audio(
+ planar(&input),
+ SceneAudio {
+ offset_ms: 0.0,
+ gain_db: 0.0,
+ auto_master: true,
+ },
+ );
+ let peak = result
+ .iter()
+ .flatten()
+ .fold(0.0f32, |value, sample| value.max(sample.abs()));
+ let tail_mean = result[0][result[0].len() / 2..]
+ .iter()
+ .copied()
+ .sum::<f32>()
+ / (result[0].len() / 2) as f32;
+ assert!(peak <= 10.0f32.powf(-1.0 / 20.0) + 1e-5);
+ assert!(tail_mean.abs() < 0.01);
+ }
}
diff --git a/crates/compositor/src/compositor_linux.rs b/crates/compositor/src/compositor_linux.rs
index 99535d143..8b950f753 100644
--- a/crates/compositor/src/compositor_linux.rs
+++ b/crates/compositor/src/compositor_linux.rs
@@ -1230,9 +1230,12 @@ impl Compositor {
// `cover_crop_uv` est la primitive partagee que macOS et Windows
// utilisent ; elle rend le rect inchange quand il a deja le bon
// ratio, donc aucun placement correct ne bouge.
- let (cu0, cv0, cu1, cv1) = crate::frame_geometry::cover_crop_uv(
+ let [cu0, cv0, cu1, cv1] = crate::frame_geometry::webcam_source_rect(
[wcw, wch],
[wtw as f32, wth as f32],
+ scene_ref
+ .as_ref()
+ .and_then(|scene| scene.layout.webcam_crop),
g.w_px[0] / g.w_px[1].max(0.0001),
);
// MIROIR : on inverse l'intervalle u. Le VS interpole `src`
diff --git a/crates/compositor/src/compositor_macos.rs b/crates/compositor/src/compositor_macos.rs
index 4cd629c28..2cee70e30 100644
--- a/crates/compositor/src/compositor_macos.rs
+++ b/crates/compositor/src/compositor_macos.rs
@@ -1604,9 +1604,10 @@ impl Compositor {
// --- caméra : ombre PiP puis vidéo ---
let enc = self.begin_pass(cmd_buf, &self.rt, None, &self.pipeline_main)?;
if let (true, Some((wy, wuv))) = (lp.has_webcam, webcam_tex.as_ref()) {
- let (cu0, cv0, cu1, cv1) = crate::frame_geometry::cover_crop_uv(
+ let [cu0, cv0, cu1, cv1] = crate::frame_geometry::webcam_source_rect(
[wcw, wch],
[wtw as f32, wth as f32],
+ scene_ref.as_ref().and_then(|scene| scene.layout.webcam_crop),
g.w_px[0] / g.w_px[1].max(0.0001),
);
let (u0, u1) = if lp.webcam_mirror { (cu1, cu0) } else { (cu0, cu1) };
diff --git a/crates/compositor/src/compositor_windows.rs b/crates/compositor/src/compositor_windows.rs
index 0054cb5ec..dbaf6f855 100644
--- a/crates/compositor/src/compositor_windows.rs
+++ b/crates/compositor/src/compositor_windows.rs
@@ -1517,9 +1517,12 @@ impl Compositor {
//
// Le center-crop carré de square/circle en est un cas particulier (boîte 1:1) — il n'a
// plus besoin d'être traité à part.
- let (su0, sv0, su1, sv1) = cover_crop_uv(
+ let [su0, sv0, su1, sv1] = crate::frame_geometry::webcam_source_rect(
[wcw, wch],
[wtw as f32, wth as f32],
+ scene_ref
+ .as_ref()
+ .and_then(|scene| scene.layout.webcam_crop),
w_px[0] / w_px[1].max(0.0001),
);
// miroir = échanger les bornes u du rect source (flip horizontal).
diff --git a/crates/compositor/src/frame_geometry.rs b/crates/compositor/src/frame_geometry.rs
index 902ba1d8f..655b746b7 100644
--- a/crates/compositor/src/frame_geometry.rs
+++ b/crates/compositor/src/frame_geometry.rs
@@ -284,6 +284,23 @@ pub(crate) fn cover_crop_uv(visible: [f32; 2], tex: [f32; 2], box_ar: f32) -> (f
let [u0, v0, u1, v1] = cover_uv_rect(full, tex, box_ar);
(u0, v0, u1, v1)
}
+
+/// Camera equivalent of the screen crop pipeline: apply the user crop first, then a centred
+/// cover-crop inside that authored window so arbitrary layout slots never stretch the image.
+pub(crate) fn webcam_source_rect(
+ visible: [f32; 2],
+ tex: [f32; 2],
+ crop: Option<SceneCrop>,
+ box_ar: f32,
+) -> [f32; 4] {
+ let u_max = visible[0].max(1.0) / tex[0].max(1.0);
+ let v_max = visible[1].max(1.0) / tex[1].max(1.0);
+ cover_uv_rect(
+ screen_source_rect(u_max, v_max, crop, 1.0, [0.5, 0.5]),
+ tex,
+ box_ar,
+ )
+}
/// Rétrécit un rect SOURCE déjà exprimé en UV (`[u0, v0, u1, v1]`) autour de son
/// centre pour qu'il porte le ratio `box_ar` une fois rapporté aux pixels de la
/// texture. C'est la forme générale de `object-fit: cover`, et LA primitive qui
@@ -1873,4 +1890,22 @@ mod tests {
assert!((su0 - (960.0 - 720.0) * 0.5 / tex[0]).abs() < 1e-6);
assert!((su1 - (960.0 + 720.0) * 0.5 / tex[0]).abs() < 1e-6);
}
+
+ #[test]
+ fn webcam_crop_identity_keeps_the_full_visible_frame() {
+ let uv = webcam_source_rect([1280.0, 720.0], [2048.0, 1024.0], None, 16.0 / 9.0);
+ assert_rect(uv, [0.0, 0.0, 1280.0 / 2048.0, 720.0 / 1024.0]);
+ }
+
+ #[test]
+ fn webcam_crop_applies_authored_zoom_and_pan_before_layout_cover() {
+ let crop = SceneCrop {
+ x: 0.25,
+ y: 0.20,
+ width: 0.50,
+ height: 0.60,
+ };
+ let uv = webcam_source_rect([100.0, 100.0], [100.0, 100.0], Some(crop), 0.50 / 0.60);
+ assert_rect(uv, [0.25, 0.20, 0.75, 0.80]);
+ }
}
diff --git a/crates/compositor/src/pipeline_linux.rs b/crates/compositor/src/pipeline_linux.rs
index 0d0d9804b..910738fc0 100644
--- a/crates/compositor/src/pipeline_linux.rs
+++ b/crates/compositor/src/pipeline_linux.rs
@@ -21,7 +21,7 @@ use std::ffi::CString;
use std::ptr;
use crate::audio::{
- assemble_concatenated_pcm, build_audio_concat_plan, decode_clip_audio,
+ assemble_concatenated_pcm, build_audio_concat_plan, decode_clip_audio, finish_audio,
stretch_clip_pcm_by_speed, AacEncoder, PlanarPcm,
};
use crate::config::Cfg;
@@ -457,6 +457,7 @@ pub fn run_composited_multi(
let mut clip_frame_counts: Vec<u64> = vec![0; clips.len()];
let scene = comp.scene_snapshot();
+ let audio_settings = scene.as_ref().map(|scene| scene.audio).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.
@@ -533,7 +534,10 @@ pub fn run_composited_multi(
// raccourci voit son audio raccourci d'autant), puis un seul encode AAC.
let declared_audio: Vec<bool> = clips.iter().map(|c| c.has_audio).collect();
let plan = build_audio_concat_plan(&clip_frame_counts, &declared_audio, out_fps as f64);
- audio_encoder.encode(&assemble_concatenated_pcm(&clip_pcm, &plan), octx)?;
+ audio_encoder.encode(
+ &finish_audio(assemble_concatenated_pcm(&clip_pcm, &plan), audio_settings),
+ octx,
+ )?;
crate::ffi::averr(crate::ffi::av_write_trailer(octx), "write_trailer")?;
crate::ffi::avio_closep(&mut pb);
crate::ffi::avformat_free_context(octx);
diff --git a/crates/compositor/src/pipeline_macos.rs b/crates/compositor/src/pipeline_macos.rs
index 2ad12b662..10de3fac2 100644
--- a/crates/compositor/src/pipeline_macos.rs
+++ b/crates/compositor/src/pipeline_macos.rs
@@ -30,7 +30,7 @@
//! décodeurs, symétrique.
use crate::audio::{
- assemble_concatenated_pcm, build_audio_concat_plan, decode_clip_audio,
+ assemble_concatenated_pcm, build_audio_concat_plan, decode_clip_audio, finish_audio,
stretch_clip_pcm_by_speed, AacEncoder, PlanarPcm,
};
use crate::compositor::Compositor;
@@ -1076,6 +1076,7 @@ pub fn run_composited_multi(
// exactement le bug de troncature en slow-motion que la doc de `walk_composited_timeline`
// 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();
frames = unsafe {
crate::timeline_walk::walk_composited_timeline(
clips,
@@ -1130,7 +1131,10 @@ pub fn run_composited_multi(
// d'autant, sinon la piste dérive pour tous les suivants.
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(&assemble_concatenated_pcm(&clip_pcm, &plan), octx)?;
+ audio_encoder.encode(
+ &finish_audio(assemble_concatenated_pcm(&clip_pcm, &plan), audio_settings),
+ octx,
+ )?;
crate::ffi::averr(
crate::ffi::av_write_trailer(octx),
@@ -1188,4 +1192,4 @@ pub fn probe_frame_count(_path: &str) -> Result<u64> {
// cfg-re-export `crate::compositor::Compositor`, et cette fonction helper garantit
// que le type reste référencé.
#[allow(dead_code)]
-fn _typecheck_compositor(_c: &Compositor, _g: &Gpu) {}
\ No newline at end of file
+fn _typecheck_compositor(_c: &Compositor, _g: &Gpu) {}
diff --git a/crates/compositor/src/pipeline_windows.rs b/crates/compositor/src/pipeline_windows.rs
index f5b02ac27..11738bcd4 100644
--- a/crates/compositor/src/pipeline_windows.rs
+++ b/crates/compositor/src/pipeline_windows.rs
@@ -3,7 +3,7 @@
//! 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, decode_clip_audio,
+ assemble_concatenated_pcm, build_audio_concat_plan, decode_clip_audio, finish_audio,
stretch_clip_pcm_by_speed, AacEncoder, PlanarPcm,
};
use crate::compositor::{Compositor, OUT_H, OUT_W};
@@ -1342,6 +1342,7 @@ unsafe fn run_multi_inner(
// La scène (déjà posée par l'appelant via comp.set_scene) pilote le curseur et le
// 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();
// ---- encodeur (choisi à l'exécution, cf. ExportCodec::candidates) + mux ----
// Backend CPU : pas de pool D3D11 du tout. `av_hwdevice_ctx_init(D3D11VA)` échoue sur
@@ -1465,7 +1466,10 @@ unsafe fn run_multi_inner(
&declared_audio,
out_fps as f64,
);
- let assembled_audio = assemble_concatenated_pcm(&clip_pcm, &audio_plan);
+ let assembled_audio = finish_audio(
+ assemble_concatenated_pcm(&clip_pcm, &audio_plan),
+ audio_settings,
+ );
audio_encoder.encode(&assembled_audio, octx)?;
averr(av_write_trailer(octx), "write_trailer")?;
diff --git a/crates/compositor/src/scene.rs b/crates/compositor/src/scene.rs
index cab3f7d23..34209c286 100644
--- a/crates/compositor/src/scene.rs
+++ b/crates/compositor/src/scene.rs
@@ -45,6 +45,9 @@ pub struct SceneLayout {
pub webcam_position: Option<WebcamPosition>,
/// la webcam rétrécit pendant un zoom actif.
pub webcam_reactive_zoom: bool,
+ /// User-authored source crop for the camera. Absent keeps the full frame.
+ #[serde(default)]
+ pub webcam_crop: Option<SceneCrop>,
/// Rect webcam résolu côté app (0..1 fractions du cadre de sortie), en PARITÉ EXACTE avec
/// `computeCompositeLayout` (TS). Permet à TS et Rust de partager la même source de vérité :
/// le natif ne dérive PLUS ses propres placements pour PiP/dual-frame/vertical-stack — il
@@ -392,6 +395,24 @@ pub struct SceneCrop {
pub height: f32,
}
+#[derive(Debug, Clone, Copy, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SceneAudio {
+ pub offset_ms: f64,
+ pub gain_db: f32,
+ pub auto_master: bool,
+}
+
+impl Default for SceneAudio {
+ fn default() -> Self {
+ Self {
+ offset_ms: 0.0,
+ gain_db: 0.0,
+ auto_master: false,
+ }
+ }
+}
+
#[derive(Debug, Clone, Copy, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SceneOutput {
@@ -420,6 +441,9 @@ pub struct Scene {
#[serde(default)]
pub camera_fullscreen_regions: Vec<SceneCameraFullscreenRegion>,
pub cursor: SceneCursor,
+ /// Global audio finishing. Default keeps old scene payloads bit-for-bit compatible.
+ #[serde(default)]
+ pub audio: SceneAudio,
/// 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/components/ai-edition/NewEditorShell.module.css b/src/components/ai-edition/NewEditorShell.module.css
index 19928dbe0..833dda366 100644
--- a/src/components/ai-edition/NewEditorShell.module.css
+++ b/src/components/ai-edition/NewEditorShell.module.css
@@ -2094,6 +2094,26 @@
color: var(--danger);
}
+.secondaryBtn {
+ margin: 4px var(--sp-4) 12px;
+ min-height: 32px;
+ padding: 0 12px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ background: var(--surface-2);
+ color: var(--fg-2);
+ font: 500 12px/1 var(--font-body);
+ cursor: pointer;
+}
+.secondaryBtn:hover {
+ background: var(--surface-3);
+ color: var(--fg);
+}
+.secondaryBtn:disabled {
+ opacity: 0.45;
+ cursor: not-allowed;
+}
+
.authPanel {
padding: 14px 16px;
border: 1px solid var(--brand);
diff --git a/src/components/ai-edition/NewEditorShell.tsx b/src/components/ai-edition/NewEditorShell.tsx
index b28f8558e..1f22da311 100644
--- a/src/components/ai-edition/NewEditorShell.tsx
+++ b/src/components/ai-edition/NewEditorShell.tsx
@@ -318,6 +318,7 @@ export function NewEditorShell() {
if (!document) return [];
return document.assets.map((asset) => ({
id: asset.id,
+ filePath: /^(https?|blob|data):/.test(asset.originalPath) ? undefined : asset.originalPath,
// Real Electron assets are filesystem paths and go through toFileUrl.
// In the browser preview an asset can already point at an http(s)/
// blob/data URL served by Vite; toFileUrl would mangle those into a
@@ -1196,7 +1197,7 @@ export function NewEditorShell() {
/>
</>
) : mode === "media" ? (
- <MediaStage />
+ <MediaStage onAddToTimeline={handleDropAsset} />
) : (
<RecStage
onStartRecording={() => void handleNewRecording()}
diff --git a/src/components/ai-edition/RightPanes.tsx b/src/components/ai-edition/RightPanes.tsx
index 30206f587..81e9d57f8 100644
--- a/src/components/ai-edition/RightPanes.tsx
+++ b/src/components/ai-edition/RightPanes.tsx
@@ -6,6 +6,7 @@
// self-sufficient).
import {
+ AudioLines,
FileText,
HelpCircle,
Layout as LayoutIcon,
@@ -1538,6 +1539,23 @@ export function LayoutPane() {
// still on disk. Say so, otherwise the only signal the user gets is their setting
// apparently having been thrown away.
const helpText = hasDocument && !hasAnyCamera ? ts("layout.helpNoWebcam") : ts("layout.help");
+ const webcamCrop = settings.webcamCropRegion;
+ const cropZoomPct = Math.round(100 / webcamCrop.width);
+ const cropPanX = webcamCrop.width >= 0.999 ? 50 : (webcamCrop.x / (1 - webcamCrop.width)) * 100;
+ const cropPanY = webcamCrop.height >= 0.999 ? 50 : (webcamCrop.y / (1 - webcamCrop.height)) * 100;
+ const setCropZoom = (zoomPct: number) => {
+ const size = 100 / Math.max(100, zoomPct);
+ const centerX = webcamCrop.x + webcamCrop.width / 2;
+ const centerY = webcamCrop.y + webcamCrop.height / 2;
+ setLive({
+ webcamCropRegion: {
+ x: Math.min(1 - size, Math.max(0, centerX - size / 2)),
+ y: Math.min(1 - size, Math.max(0, centerY - size / 2)),
+ width: size,
+ height: size,
+ },
+ });
+ };
return (
<Pane title={ts("layout.title")} icon={<LayoutIcon size={14} />} helpText={helpText}>
<div className={styles.sectionLabel}>{ts("layout.preset")}</div>
@@ -1671,6 +1689,99 @@ export function LayoutPane() {
</div>
</div>
) : null}
+ <div className={styles.sectionLabel}>{ts("layout.webcamFraming")}</div>
+ <div className={styles.sliderGrid}>
+ <SliderCell
+ label={ts("layout.webcamCropZoom")}
+ value={cropZoomPct}
+ min={100}
+ max={300}
+ suffix="%"
+ disabled={layoutControlsDisabled}
+ onChange={setCropZoom}
+ onCommit={() => void commit()}
+ />
+ <SliderCell
+ label={ts("layout.webcamCropX")}
+ value={cropPanX}
+ min={0}
+ max={100}
+ suffix="%"
+ disabled={layoutControlsDisabled || webcamCrop.width >= 0.999}
+ onChange={(value) =>
+ setLive({
+ webcamCropRegion: { ...webcamCrop, x: (value / 100) * (1 - webcamCrop.width) },
+ })
+ }
+ onCommit={() => void commit()}
+ />
+ <SliderCell
+ label={ts("layout.webcamCropY")}
+ value={cropPanY}
+ min={0}
+ max={100}
+ suffix="%"
+ disabled={layoutControlsDisabled || webcamCrop.height >= 0.999}
+ onChange={(value) =>
+ setLive({
+ webcamCropRegion: { ...webcamCrop, y: (value / 100) * (1 - webcamCrop.height) },
+ })
+ }
+ onCommit={() => void commit()}
+ />
+ </div>
+ </Pane>
+ );
+}
+
+// ─── Audio ────────────────────────────────────────────────────────
+
+export function AudioPane() {
+ const ts = useScopedT("settings");
+ const { settings, set, setLive, commit, hasDocument } = useEditorSettings();
+ return (
+ <Pane title={ts("audio.title")} icon={<AudioLines size={14} />} helpText={ts("audio.help")}>
+ <div className={styles.paneRow}>
+ <span className="label">{ts("audio.autoMaster")}</span>
+ <Toggle
+ checked={settings.audioAutoMaster}
+ disabled={!hasDocument}
+ onChange={(value) => void set({ audioAutoMaster: value })}
+ />
+ </div>
+ <div className={styles.sliderGrid}>
+ <SliderCell
+ label={ts("audio.syncOffset")}
+ value={settings.audioOffsetMs}
+ min={-500}
+ max={500}
+ step={1}
+ suffix=" ms"
+ disabled={!hasDocument}
+ onChange={(value) => setLive({ audioOffsetMs: value })}
+ onCommit={() => void commit()}
+ />
+ <SliderCell
+ label={ts("audio.outputGain")}
+ value={settings.audioGainDb}
+ min={-12}
+ max={12}
+ step={0.5}
+ decimals={1}
+ suffix=" dB"
+ disabled={!hasDocument}
+ onChange={(value) => setLive({ audioGainDb: value })}
+ onCommit={() => void commit()}
+ />
+ </div>
+ <button
+ type="button"
+ className={styles.secondaryBtn}
+ disabled={!hasDocument}
+ onClick={() => void set({ audioOffsetMs: 0, audioGainDb: 0, audioAutoMaster: true })}
+ >
+ {ts("audio.reset")}
+ </button>
</Pane>
);
}
diff --git a/src/components/ai-edition/VirtualPreview.audio.test.ts b/src/components/ai-edition/VirtualPreview.audio.test.ts
new file mode 100644
index 000000000..cf67db989
--- /dev/null
+++ b/src/components/ai-edition/VirtualPreview.audio.test.ts
@@ -0,0 +1,20 @@
+import { describe, expect, it } from "vitest";
+import { resolveAudioPreviewTime } from "./VirtualPreview";
+
+describe("resolveAudioPreviewTime", () => {
+ it("delays audio for a positive offset", () => {
+ expect(resolveAudioPreviewTime(0.1, 160, 10)).toEqual({ targetTimeSec: 0, shouldPlay: false });
+ expect(resolveAudioPreviewTime(1, 160, 10)).toEqual({ targetTimeSec: 0.84, shouldPlay: true });
+ });
+
+ it("advances audio for a negative offset", () => {
+ expect(resolveAudioPreviewTime(1, -160, 10)).toEqual({ targetTimeSec: 1.16, shouldPlay: true });
+ });
+
+ it("stops instead of seeking past the track", () => {
+ expect(resolveAudioPreviewTime(9.9, -160, 10)).toEqual({
+ targetTimeSec: 10,
+ shouldPlay: false,
+ });
+ });
+});
diff --git a/src/components/ai-edition/VirtualPreview.tsx b/src/components/ai-edition/VirtualPreview.tsx
index 0df2ff1ee..4af4e1e13 100644
--- a/src/components/ai-edition/VirtualPreview.tsx
+++ b/src/components/ai-edition/VirtualPreview.tsx
@@ -35,9 +35,24 @@ import styles from "./VirtualPreview.module.css";
export interface VideoSource {
id: string;
src: string;
+ /** Original filesystem path, used by the main process to expose the second audio track. */
+ filePath?: string;
label: string;
}
+export function resolveAudioPreviewTime(
+ videoTimeSec: number,
+ offsetMs: number,
+ durationSec = Number.POSITIVE_INFINITY,
+) {
+ const raw = videoTimeSec - offsetMs / 1000;
+ const finiteDuration = Number.isFinite(durationSec) && durationSec > 0 ? durationSec : Infinity;
+ return {
+ targetTimeSec: Math.min(Math.max(0, raw), finiteDuration),
+ shouldPlay: raw >= 0 && raw < finiteDuration,
+ };
+}
+
/** First clip (by timeline order) starting strictly after `afterTimelineStartSec` —
* independent of the `clips` array's own order, which is never guaranteed to match
* timeline order (a clip can be inserted/reordered at any array index; only
@@ -114,6 +129,8 @@ export function VirtualPreview({
clockRef,
}: VirtualPreviewProps) {
const { settings } = useEditorSettings();
+ const audioOffsetMsRef = useRef(settings.audioOffsetMs);
+ audioOffsetMsRef.current = settings.audioOffsetMs;
// ponytail: an oversized, offset video inside .videoFrame's overflow:hidden
// box — the same "scale + negative-position the full frame, let the
// container clip the rest" technique the export renderer uses via a Pixi
@@ -135,6 +152,18 @@ export function VirtualPreview({
top: `${(-region.y * 100) / region.height}%`,
};
const videoRef = useRef<HTMLVideoElement | null>(null);
+ const primaryAudioRef = useRef<HTMLAudioElement | null>(null);
+ const supplementalAudioRef = useRef<HTMLAudioElement | null>(null);
+ const [primaryAudioEl, setPrimaryAudioEl] = useState<HTMLAudioElement | null>(null);
+ const [supplementalAudioEl, setSupplementalAudioEl] = useState<HTMLAudioElement | null>(null);
+ const [supplementalAudioSrc, setSupplementalAudioSrc] = useState<string | null>(null);
+ const [audioProbeComplete, setAudioProbeComplete] = useState(false);
+ const audioGraphRef = useRef<{
+ context: AudioContext;
+ highpasses: BiquadFilterNode[];
+ compressor: DynamicsCompressorNode;
+ gain: GainNode;
+ } | null>(null);
const videoFrameRef = useRef<HTMLDivElement | null>(null);
const isProgrammaticSeekRef = useRef(false);
@@ -173,6 +202,80 @@ export function VirtualPreview({
const virtualDurationSec = useMemo(() => totalVirtualDuration(clips), [clips]);
const activeSource = videoSources[sourceIndex] ?? null;
+ useEffect(() => {
+ let cancelled = false;
+ setSupplementalAudioSrc(null);
+ setAudioProbeComplete(false);
+ if (!activeSource?.filePath || !window.electronAPI?.preparePreviewAudioTrack) {
+ setAudioProbeComplete(true);
+ return () => {
+ cancelled = true;
+ };
+ }
+ void window.electronAPI.preparePreviewAudioTrack(activeSource.filePath).then((result) => {
+ if (cancelled) return;
+ setSupplementalAudioSrc(result.success ? (result.path ?? null) : null);
+ setAudioProbeComplete(true);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [activeSource?.filePath]);
+
+ // Route preview audio through the same fast voice-oriented controls the native export uses.
+ // The primary media element carries track 1; on macOS the existing IPC helper extracts track 2
+ // (normally the microphone) so both are audible instead of Chromium silently choosing one.
+ useEffect(() => {
+ if (!primaryAudioEl || !audioProbeComplete) return;
+ if (supplementalAudioSrc && !supplementalAudioEl) return;
+ let context: AudioContext | null = null;
+ try {
+ context = new AudioContext();
+ const compressor = context.createDynamicsCompressor();
+ const gain = context.createGain();
+ compressor.connect(gain).connect(context.destination);
+ const highpasses: BiquadFilterNode[] = [];
+ for (const element of [primaryAudioEl, supplementalAudioEl].filter(
+ (value): value is HTMLAudioElement => Boolean(value),
+ )) {
+ const source = context.createMediaElementSource(element);
+ const highpass = context.createBiquadFilter();
+ highpass.type = "highpass";
+ source.connect(highpass).connect(compressor);
+ highpasses.push(highpass);
+ }
+ audioGraphRef.current = { context, highpasses, compressor, gain };
+ } catch {
+ // WebAudio can be unavailable in unit tests or under a denied audio policy. The media
+ // elements remain usable; the sync loop below still applies offset and playback state.
+ }
+ return () => {
+ audioGraphRef.current = null;
+ if (context) void context.close();
+ };
+ }, [primaryAudioEl, supplementalAudioEl, supplementalAudioSrc, audioProbeComplete]);
+
+ useEffect(() => {
+ const graph = audioGraphRef.current;
+ const outputGain = 10 ** (settings.audioGainDb / 20);
+ if (!graph) {
+ for (const element of [primaryAudioRef.current, supplementalAudioRef.current]) {
+ if (element) element.volume = Math.min(1, outputGain);
+ }
+ return;
+ }
+ for (const filter of graph.highpasses) {
+ filter.frequency.value = settings.audioAutoMaster ? 80 : 20;
+ filter.Q.value = 0.707;
+ }
+ graph.compressor.threshold.value = settings.audioAutoMaster ? -18 : 0;
+ graph.compressor.knee.value = settings.audioAutoMaster ? 12 : 0;
+ graph.compressor.ratio.value = settings.audioAutoMaster ? 3 : 1;
+ graph.compressor.attack.value = 0.01;
+ graph.compressor.release.value = 0.12;
+ graph.gain.gain.value = outputGain;
+ }, [settings.audioAutoMaster, settings.audioGainDb]);
+
// ponytail: the cursor overlay wants source-media time (the recorded
// cursor samples live on the original mp4 timeline, not the edited
// virtual timeline). `setSourceTimeSec` is called from the 60 Hz rAF
@@ -249,6 +352,30 @@ export function VirtualPreview({
if (!v || !Number.isFinite(v.currentTime)) {
return;
}
+ for (const audio of [primaryAudioRef.current, supplementalAudioRef.current]) {
+ if (!audio) continue;
+ const target = resolveAudioPreviewTime(
+ v.currentTime,
+ audioOffsetMsRef.current,
+ audio.duration,
+ );
+ if (audio.playbackRate !== v.playbackRate) audio.playbackRate = v.playbackRate;
+ if (Math.abs(audio.currentTime - target.targetTimeSec) > 0.025) {
+ try {
+ audio.currentTime = target.targetTimeSec;
+ } catch {
+ // media metadata not ready yet
+ }
+ }
+ if (!v.paused && target.shouldPlay && audio.paused) {
+ if (audioGraphRef.current?.context.state === "suspended") {
+ void audioGraphRef.current.context.resume();
+ }
+ void audio.play().catch(() => undefined);
+ } else if ((v.paused || !target.shouldPlay) && !audio.paused) {
+ audio.pause();
+ }
+ }
// Publish this frame's live position/rate for other media elements
// (webcam) to read directly — see playback-clock.ts for why this
// bypasses React state entirely.
@@ -752,6 +879,7 @@ export function VirtualPreview({
cursor: settings.cursorShow ? "none" : undefined,
}}
preload="metadata"
+ muted
playsInline
onLoadedMetadata={(e) => {
setLoadState("ready");
@@ -905,6 +1033,30 @@ export function VirtualPreview({
// handles clip-end advancement, so dropping the event
// handler here is safe.
/>
+ <audio
+ key={`${activeSource.id}:primary-audio`}
+ ref={(element) => {
+ primaryAudioRef.current = element;
+ setPrimaryAudioEl(element);
+ }}
+ src={activeSource.src}
+ preload="metadata"
+ aria-hidden="true"
+ data-testid="preview-audio-primary"
+ />
+ {supplementalAudioSrc ? (
+ <audio
+ key={`${activeSource.id}:supplemental-audio`}
+ ref={(element) => {
+ supplementalAudioRef.current = element;
+ setSupplementalAudioEl(element);
+ }}
+ src={supplementalAudioSrc}
+ preload="metadata"
+ aria-hidden="true"
+ data-testid="preview-audio-supplemental"
+ />
+ ) : null}
{/* Plus d'overlay ici du tout. « Loading preview… » reflétait l'état du
<video> CACHÉ (source horloge/audio), pas la preview RÉELLE — le canvas
natif, qui montre déjà une image valide pendant que le <video> re-seek.
diff --git a/src/components/ai-edition/v4/FloatingInspector.tsx b/src/components/ai-edition/v4/FloatingInspector.tsx
index 6f53c4dad..2caca6d72 100644
--- a/src/components/ai-edition/v4/FloatingInspector.tsx
+++ b/src/components/ai-edition/v4/FloatingInspector.tsx
@@ -1,4 +1,5 @@
import {
+ AudioLines,
Captions as CaptionsIcon,
ChevronRight,
FileText,
@@ -42,6 +43,7 @@ import { coalescedTrimGroups } from "@/lib/ai-edition/timeline/trim-mapping";
import { CaptionsPane } from "../CaptionsPane";
import { ColorField } from "../ColorField";
import {
+ AudioPane,
BackgroundPane,
CursorPane,
LayoutPane,
@@ -54,12 +56,20 @@ import styles from "./EditorShellV4.module.css";
type TimelineApi = ReturnType<typeof useTimeline>;
-export type Facet = "background" | "effects" | "layout" | "cursor" | "captions" | "transcript";
+export type Facet =
+ | "background"
+ | "effects"
+ | "layout"
+ | "audio"
+ | "cursor"
+ | "captions"
+ | "transcript";
const FACETS: Array<{ id: Facet; labelKey: string; icon: typeof ImageIcon }> = [
{ id: "background", labelKey: "background.title", icon: ImageIcon },
{ id: "effects", labelKey: "effects.title", icon: SlidersHorizontal },
{ id: "layout", labelKey: "layout.title", icon: LayoutIcon },
+ { id: "audio", labelKey: "audio.title", icon: AudioLines },
{ id: "cursor", labelKey: "cursor.title", icon: MousePointer2 },
{ id: "captions", labelKey: "facets.captions", icon: CaptionsIcon },
{ id: "transcript", labelKey: "facets.transcript", icon: FileText },
@@ -1055,6 +1065,7 @@ function FacetBody({
if (facet === "background") return wrap(collapse, <BackgroundPane />);
if (facet === "effects") return wrap(collapse, <VideoEffectsPane />);
if (facet === "layout") return wrap(collapse, <LayoutPane />);
+ if (facet === "audio") return wrap(collapse, <AudioPane />);
if (facet === "cursor") return wrap(collapse, <CursorPane />);
if (facet === "transcript") return wrap(collapse, <TranscriptPane {...transcriptProps} />);
return wrap(collapse, <CaptionsPane />);
diff --git a/src/components/ai-edition/v4/MediaStage.tsx b/src/components/ai-edition/v4/MediaStage.tsx
index a9933bc8f..bf72f2f42 100644
--- a/src/components/ai-edition/v4/MediaStage.tsx
+++ b/src/components/ai-edition/v4/MediaStage.tsx
@@ -33,7 +33,7 @@ function basename(path: string): string {
return path.split(/[\\/]/).pop() ?? path;
}
-export function MediaStage() {
+export function MediaStage({ onAddToTimeline }: { onAddToTimeline: (assetId: string) => void }) {
const t = useScopedT("editor");
const projectId = useProjectStore((s) => s.projectId);
const document = useProjectStore((s) => s.document);
@@ -95,6 +95,12 @@ export function MediaStage() {
setDetailOpen(true);
};
+ const addSelectedToTimeline = () => {
+ if (!selected) return;
+ onAddToTimeline(selected.id);
+ toast.success(t("mediaStage.addedToTimeline", { label: selected.label }));
+ };
+
return (
<div className={styles.mediaStage}>
<div className={styles.mediaInner} style={{ maxWidth: detailOpen ? 1120 : 900 }}>
@@ -234,7 +240,7 @@ export function MediaStage() {
style={{
fontSize: 12,
color: "var(--muted)",
- marginBottom: 16,
+ marginBottom: 10,
whiteSpace: "nowrap",
overflow: "hidden",
textOverflow: "ellipsis",
@@ -242,6 +248,29 @@ export function MediaStage() {
>
{selected.label || basename(selected.originalPath)}
</div>
+ <button
+ type="button"
+ onClick={addSelectedToTimeline}
+ style={{
+ width: "100%",
+ height: 36,
+ display: "inline-flex",
+ alignItems: "center",
+ justifyContent: "center",
+ gap: 7,
+ marginBottom: 16,
+ borderRadius: 9,
+ border: "1px solid var(--accent)",
+ background: "var(--accent)",
+ color: "var(--on-accent, #fff)",
+ fontSize: 12.5,
+ fontWeight: 650,
+ cursor: "pointer",
+ }}
+ >
+ <Plus size={14} />
+ {t("mediaStage.addToTimeline")}
+ </button>
<div style={{ marginBottom: 16 }}>
<span
diff --git a/src/i18n/locales/ar/editor.json b/src/i18n/locales/ar/editor.json
index 64441099d..acac12eb2 100644
--- a/src/i18n/locales/ar/editor.json
+++ b/src/i18n/locales/ar/editor.json
@@ -134,6 +134,8 @@
"emptyHint": "لا توجد وسائط بعد — استورد تسجيلاً للبدء.",
"importMedia": "استيراد وسائط",
"added": "تمت إضافة {{label}}",
+ "addToTimeline": "إضافة إلى الخط الزمني",
+ "addedToTimeline": "تمت إضافة {{label}} إلى الخط الزمني",
"sourceTranscript": "نص المصدر",
"close": "إغلاق",
"transcriptReady": "النص جاهز",
diff --git a/src/i18n/locales/ar/settings.json b/src/i18n/locales/ar/settings.json
index 26c10e26f..95351aa2c 100644
--- a/src/i18n/locales/ar/settings.json
+++ b/src/i18n/locales/ar/settings.json
@@ -54,6 +54,10 @@
"reactiveWebcamDescription": "تتقلص الكاميرا بسلاسة أثناء تكبير الفيديو حتى لا تعيق الرؤية.",
"help": "طريقة دمج كاميرا الويب مع الشاشة: صورة داخل صورة، أو تكديس عمودي، أو إطار مزدوج، وشكل القناع والحجم والانعكاس.",
"helpNoWebcam": "لا يحتوي هذا المشروع على كاميرا، لذلك فإن عناصر التحكم في التخطيط معطّلة ويعرض الإعداد المسبق «بدون كاميرا». يُحتفظ بالتخطيط المحفوظ لحين إضافة كاميرا.",
+ "webcamFraming": "Webcam framing",
+ "webcamCropZoom": "Crop zoom",
+ "webcamCropX": "Horizontal pan",
+ "webcamCropY": "Vertical pan",
"shapes": {
"rectangle": "مستطيل",
"circle": "دائرة",
@@ -299,5 +303,13 @@
"lineLength": "طول السطر",
"minWords": "أقل عدد كلمات في السطر",
"maxWords": "أكثر عدد كلمات في السطر"
+ },
+ "audio": {
+ "title": "Audio",
+ "autoMaster": "Auto master",
+ "syncOffset": "Sync offset",
+ "outputGain": "Output trim",
+ "reset": "Reset audio",
+ "help": "Automatically clean and balance voice audio, then fine-tune timing and level."
}
}
diff --git a/src/i18n/locales/en/editor.json b/src/i18n/locales/en/editor.json
index 316eea139..cc09660de 100644
--- a/src/i18n/locales/en/editor.json
+++ b/src/i18n/locales/en/editor.json
@@ -134,6 +134,8 @@
"emptyHint": "No media yet — import a recording to get started.",
"importMedia": "Import media",
"added": "Added {{label}}",
+ "addToTimeline": "Add to timeline",
+ "addedToTimeline": "Added {{label}} to the timeline",
"sourceTranscript": "Source Transcript",
"close": "Close",
"transcriptReady": "Transcript ready",
diff --git a/src/i18n/locales/en/settings.json b/src/i18n/locales/en/settings.json
index 653d652b0..dc10fa46e 100644
--- a/src/i18n/locales/en/settings.json
+++ b/src/i18n/locales/en/settings.json
@@ -49,6 +49,10 @@
"noWebcam": "No Webcam",
"webcamShape": "Camera Shape",
"webcamSize": "Webcam Size",
+ "webcamFraming": "Webcam crop",
+ "webcamCropZoom": "Zoom",
+ "webcamCropX": "Pan horizontally",
+ "webcamCropY": "Pan vertically",
"mirrorWebcam": "Mirror Webcam",
"reactiveWebcam": "Shrink on Zoom",
"reactiveWebcamDescription": "Camera smoothly shrinks while the video is zoomed in, so it stays out of the way.",
@@ -61,6 +65,14 @@
"rounded": "Rounded"
}
},
+ "audio": {
+ "title": "Audio",
+ "help": "Nudge audio into sync, adjust output trim, and apply automatic speech-focused EQ, compression, and loudness finishing.",
+ "autoMaster": "Auto master voice",
+ "syncOffset": "Sync offset",
+ "outputGain": "Output trim",
+ "reset": "Reset audio"
+ },
"effects": {
"title": "Video Effects",
"blurBg": "Blur BG",
diff --git a/src/i18n/locales/es/editor.json b/src/i18n/locales/es/editor.json
index 00a9e268c..2124adde1 100644
--- a/src/i18n/locales/es/editor.json
+++ b/src/i18n/locales/es/editor.json
@@ -134,6 +134,8 @@
"emptyHint": "Aún no hay contenido — importa una grabación para empezar.",
"importMedia": "Importar contenido",
"added": "{{label}} añadido",
+ "addToTimeline": "Añadir a la línea de tiempo",
+ "addedToTimeline": "{{label}} añadido a la línea de tiempo",
"sourceTranscript": "Transcripción de la fuente",
"close": "Cerrar",
"transcriptReady": "Transcripción lista",
diff --git a/src/i18n/locales/es/settings.json b/src/i18n/locales/es/settings.json
index e4a71a8b3..0445f456c 100644
--- a/src/i18n/locales/es/settings.json
+++ b/src/i18n/locales/es/settings.json
@@ -54,6 +54,10 @@
"reactiveWebcamDescription": "La cámara se reduce suavemente mientras el vídeo está ampliado, para no estorbar.",
"help": "Cómo se compone la webcam con la pantalla: imagen en imagen, pila vertical, marco doble, forma de máscara, tamaño y efecto espejo.",
"helpNoWebcam": "Este proyecto no tiene cámara, así que los controles de diseño están desactivados y el preajuste muestra «Sin cámara». Tu diseño guardado se conserva para cuando añadas una cámara.",
+ "webcamFraming": "Webcam framing",
+ "webcamCropZoom": "Crop zoom",
+ "webcamCropX": "Horizontal pan",
+ "webcamCropY": "Vertical pan",
"shapes": {
"rectangle": "Rect.",
"circle": "Círculo",
@@ -299,5 +303,13 @@
"lineLength": "Longitud de línea",
"minWords": "Mín. palabras por línea",
"maxWords": "Máx. palabras por línea"
+ },
+ "audio": {
+ "title": "Audio",
+ "autoMaster": "Auto master",
+ "syncOffset": "Sync offset",
+ "outputGain": "Output trim",
+ "reset": "Reset audio",
+ "help": "Automatically clean and balance voice audio, then fine-tune timing and level."
}
}
diff --git a/src/i18n/locales/fr/editor.json b/src/i18n/locales/fr/editor.json
index aaad5b6bb..96e0e94c7 100644
--- a/src/i18n/locales/fr/editor.json
+++ b/src/i18n/locales/fr/editor.json
@@ -134,6 +134,8 @@
"emptyHint": "Aucun média pour l'instant — importez un enregistrement pour commencer.",
"importMedia": "Importer un média",
"added": "{{label}} ajouté",
+ "addToTimeline": "Ajouter à la timeline",
+ "addedToTimeline": "{{label}} ajouté à la timeline",
"sourceTranscript": "Transcription de la source",
"close": "Fermer",
"transcriptReady": "Transcription prête",
diff --git a/src/i18n/locales/fr/settings.json b/src/i18n/locales/fr/settings.json
index 69fe1e89a..169c9fc1f 100644
--- a/src/i18n/locales/fr/settings.json
+++ b/src/i18n/locales/fr/settings.json
@@ -54,6 +54,10 @@
"reactiveWebcamDescription": "La caméra rétrécit doucement pendant le zoom, pour ne pas gêner.",
"help": "Composition de la webcam avec l'écran : incrustation, empilement vertical, double cadre, forme du masque, taille et effet miroir.",
"helpNoWebcam": "Ce projet n’a pas de caméra : les réglages de disposition sont désactivés et le préréglage affiche « Sans webcam ». Votre disposition enregistrée est conservée pour le jour où une caméra sera ajoutée.",
+ "webcamFraming": "Webcam framing",
+ "webcamCropZoom": "Crop zoom",
+ "webcamCropX": "Horizontal pan",
+ "webcamCropY": "Vertical pan",
"shapes": {
"rectangle": "Rect.",
"circle": "Cercle",
@@ -299,5 +303,13 @@
"lineLength": "Longueur des lignes",
"minWords": "Mots min. par ligne",
"maxWords": "Mots max. par ligne"
+ },
+ "audio": {
+ "title": "Audio",
+ "autoMaster": "Auto master",
+ "syncOffset": "Sync offset",
+ "outputGain": "Output trim",
+ "reset": "Reset audio",
+ "help": "Automatically clean and balance voice audio, then fine-tune timing and level."
}
}
diff --git a/src/i18n/locales/it/editor.json b/src/i18n/locales/it/editor.json
index ce5e89260..e08a7f833 100644
--- a/src/i18n/locales/it/editor.json
+++ b/src/i18n/locales/it/editor.json
@@ -134,6 +134,8 @@
"emptyHint": "Nessun media ancora — importa una registrazione per iniziare.",
"importMedia": "Importa media",
"added": "{{label}} aggiunto",
+ "addToTimeline": "Aggiungi alla timeline",
+ "addedToTimeline": "{{label}} aggiunto alla timeline",
"sourceTranscript": "Trascrizione sorgente",
"close": "Chiudi",
"transcriptReady": "Trascrizione pronta",
diff --git a/src/i18n/locales/it/settings.json b/src/i18n/locales/it/settings.json
index 4fd93214f..2c025602e 100644
--- a/src/i18n/locales/it/settings.json
+++ b/src/i18n/locales/it/settings.json
@@ -54,6 +54,10 @@
"reactiveWebcamDescription": "La webcam si riduce dolcemente durante lo zoom, così non intralcia.",
"help": "Come la webcam viene composta con lo schermo: picture-in-picture, pila verticale, doppio riquadro, forma della maschera, dimensione e effetto specchio.",
"helpNoWebcam": "Questo progetto non ha una webcam, quindi i controlli di layout sono disattivati e il preset mostra «Nessuna webcam». Il layout salvato viene conservato per quando aggiungerai una webcam.",
+ "webcamFraming": "Webcam framing",
+ "webcamCropZoom": "Crop zoom",
+ "webcamCropX": "Horizontal pan",
+ "webcamCropY": "Vertical pan",
"shapes": {
"rectangle": "Rett.",
"circle": "Cerchio",
@@ -299,5 +303,13 @@
"lineLength": "Lunghezza riga",
"minWords": "Parole min. per riga",
"maxWords": "Parole max. per riga"
+ },
+ "audio": {
+ "title": "Audio",
+ "autoMaster": "Auto master",
+ "syncOffset": "Sync offset",
+ "outputGain": "Output trim",
+ "reset": "Reset audio",
+ "help": "Automatically clean and balance voice audio, then fine-tune timing and level."
}
}
diff --git a/src/i18n/locales/ja-JP/editor.json b/src/i18n/locales/ja-JP/editor.json
index 12a4a09e7..524ed5156 100644
--- a/src/i18n/locales/ja-JP/editor.json
+++ b/src/i18n/locales/ja-JP/editor.json
@@ -134,6 +134,8 @@
"emptyHint": "まだメディアがありません — 録画をインポートして開始してください。",
"importMedia": "メディアをインポート",
"added": "{{label}} を追加しました",
+ "addToTimeline": "タイムラインに追加",
+ "addedToTimeline": "{{label}} をタイムラインに追加しました",
"sourceTranscript": "ソースの文字起こし",
"close": "閉じる",
"transcriptReady": "文字起こし完了",
diff --git a/src/i18n/locales/ja-JP/settings.json b/src/i18n/locales/ja-JP/settings.json
index e42d9fffd..3577cf13e 100644
--- a/src/i18n/locales/ja-JP/settings.json
+++ b/src/i18n/locales/ja-JP/settings.json
@@ -54,6 +54,10 @@
"reactiveWebcamDescription": "ズーム中はカメラがスムーズに縮小し、邪魔になりません。",
"help": "ウェブカメラと画面の合成方法: ピクチャインピクチャ、縦積み、デュアルフレーム、マスク形状、サイズ、左右反転。",
"helpNoWebcam": "このプロジェクトにはカメラがないため、レイアウトの設定は無効で、プリセットは「Webカメラなし」と表示されます。保存されたレイアウトは、カメラを追加したときのために保持されます。",
+ "webcamFraming": "Webcam framing",
+ "webcamCropZoom": "Crop zoom",
+ "webcamCropX": "Horizontal pan",
+ "webcamCropY": "Vertical pan",
"shapes": {
"rectangle": "長方形",
"circle": "円",
@@ -299,5 +303,13 @@
"lineLength": "行の長さ",
"minWords": "1 行の最小単語数",
"maxWords": "1 行の最大単語数"
+ },
+ "audio": {
+ "title": "Audio",
+ "autoMaster": "Auto master",
+ "syncOffset": "Sync offset",
+ "outputGain": "Output trim",
+ "reset": "Reset audio",
+ "help": "Automatically clean and balance voice audio, then fine-tune timing and level."
}
}
diff --git a/src/i18n/locales/ko-KR/editor.json b/src/i18n/locales/ko-KR/editor.json
index a8f8595d8..ec6a431c9 100644
--- a/src/i18n/locales/ko-KR/editor.json
+++ b/src/i18n/locales/ko-KR/editor.json
@@ -134,6 +134,8 @@
"emptyHint": "아직 미디어가 없습니다 — 녹화 파일을 가져와서 시작하세요.",
"importMedia": "미디어 가져오기",
"added": "{{label}} 추가됨",
+ "addToTimeline": "타임라인에 추가",
+ "addedToTimeline": "{{label}}이(가) 타임라인에 추가됨",
"sourceTranscript": "소스 대본",
"close": "닫기",
"transcriptReady": "대본 준비 완료",
diff --git a/src/i18n/locales/ko-KR/settings.json b/src/i18n/locales/ko-KR/settings.json
index 7ca326d35..437738b74 100644
--- a/src/i18n/locales/ko-KR/settings.json
+++ b/src/i18n/locales/ko-KR/settings.json
@@ -54,6 +54,10 @@
"reactiveWebcamDescription": "확대하는 동안 카메라가 부드럽게 작아져 방해되지 않습니다.",
"help": "웹캠과 화면을 합성하는 방식: PIP, 세로 배치, 이중 프레임, 마스크 모양, 크기, 좌우 반전.",
"helpNoWebcam": "이 프로젝트에는 카메라가 없어 레이아웃 설정이 비활성화되고 프리셋이 “웹캠 없음”으로 표시됩니다. 저장된 레이아웃은 카메라를 추가할 때를 위해 유지됩니다.",
+ "webcamFraming": "Webcam framing",
+ "webcamCropZoom": "Crop zoom",
+ "webcamCropX": "Horizontal pan",
+ "webcamCropY": "Vertical pan",
"shapes": {
"rectangle": "직사각형",
"circle": "원형",
@@ -299,5 +303,13 @@
"lineLength": "줄 길이",
"minWords": "줄당 최소 단어 수",
"maxWords": "줄당 최대 단어 수"
+ },
+ "audio": {
+ "title": "Audio",
+ "autoMaster": "Auto master",
+ "syncOffset": "Sync offset",
+ "outputGain": "Output trim",
+ "reset": "Reset audio",
+ "help": "Automatically clean and balance voice audio, then fine-tune timing and level."
}
}
diff --git a/src/i18n/locales/pt-BR/editor.json b/src/i18n/locales/pt-BR/editor.json
index b95566670..183e2c82f 100644
--- a/src/i18n/locales/pt-BR/editor.json
+++ b/src/i18n/locales/pt-BR/editor.json
@@ -134,6 +134,8 @@
"emptyHint": "Ainda não há mídia — importe uma gravação para começar.",
"importMedia": "Importar mídia",
"added": "{{label}} adicionado",
+ "addToTimeline": "Adicionar à linha do tempo",
+ "addedToTimeline": "{{label}} adicionado à linha do tempo",
"sourceTranscript": "Transcrição da Fonte",
"close": "Fechar",
"transcriptReady": "Transcrição pronta",
diff --git a/src/i18n/locales/pt-BR/settings.json b/src/i18n/locales/pt-BR/settings.json
index cc9589479..838c0cccb 100644
--- a/src/i18n/locales/pt-BR/settings.json
+++ b/src/i18n/locales/pt-BR/settings.json
@@ -54,6 +54,10 @@
"reactiveWebcamDescription": "A câmera diminui suavemente enquanto o vídeo está ampliado, para não atrapalhar.",
"help": "Como a webcam é composta com a tela: picture-in-picture, pilha vertical, quadro duplo, formato da máscara, tamanho e espelhamento.",
"helpNoWebcam": "Este projeto não tem câmera, então os controles de layout estão desativados e a predefinição mostra “Sem Webcam”. Seu layout salvo é mantido para quando você adicionar uma câmera.",
+ "webcamFraming": "Webcam framing",
+ "webcamCropZoom": "Crop zoom",
+ "webcamCropX": "Horizontal pan",
+ "webcamCropY": "Vertical pan",
"shapes": {
"rectangle": "Ret.",
"circle": "Círculo",
@@ -299,5 +303,13 @@
"lineLength": "Comprimento da linha",
"minWords": "Mín. de palavras por linha",
"maxWords": "Máx. de palavras por linha"
+ },
+ "audio": {
+ "title": "Audio",
+ "autoMaster": "Auto master",
+ "syncOffset": "Sync offset",
+ "outputGain": "Output trim",
+ "reset": "Reset audio",
+ "help": "Automatically clean and balance voice audio, then fine-tune timing and level."
}
}
diff --git a/src/i18n/locales/ru/editor.json b/src/i18n/locales/ru/editor.json
index bbcc623f1..b6c3bf906 100644
--- a/src/i18n/locales/ru/editor.json
+++ b/src/i18n/locales/ru/editor.json
@@ -134,6 +134,8 @@
"emptyHint": "Пока нет медиафайлов — импортируйте запись, чтобы начать.",
"importMedia": "Импортировать медиа",
"added": "Добавлено: {{label}}",
+ "addToTimeline": "Добавить на таймлайн",
+ "addedToTimeline": "{{label}} добавлено на таймлайн",
"sourceTranscript": "Транскрипт источника",
"close": "Закрыть",
"transcriptReady": "Транскрипт готов",
diff --git a/src/i18n/locales/ru/settings.json b/src/i18n/locales/ru/settings.json
index 3ff87aa11..f61ff0001 100644
--- a/src/i18n/locales/ru/settings.json
+++ b/src/i18n/locales/ru/settings.json
@@ -54,6 +54,10 @@
"reactiveWebcamDescription": "Камера плавно уменьшается во время приближения, чтобы не мешать.",
"help": "Как камера совмещается с экраном: «картинка в картинке», вертикальная стопка, двойной кадр, форма маски, размер и зеркальное отражение.",
"helpNoWebcam": "В этом проекте нет камеры, поэтому настройки компоновки отключены, а пресет показывает «Без веб-камеры». Сохранённая компоновка останется на случай, если вы добавите камеру.",
+ "webcamFraming": "Webcam framing",
+ "webcamCropZoom": "Crop zoom",
+ "webcamCropX": "Horizontal pan",
+ "webcamCropY": "Vertical pan",
"shapes": {
"rectangle": "Прямоуг.",
"circle": "Круг",
@@ -299,5 +303,13 @@
"lineLength": "Длина строки",
"minWords": "Мин. слов в строке",
"maxWords": "Макс. слов в строке"
+ },
+ "audio": {
+ "title": "Audio",
+ "autoMaster": "Auto master",
+ "syncOffset": "Sync offset",
+ "outputGain": "Output trim",
+ "reset": "Reset audio",
+ "help": "Automatically clean and balance voice audio, then fine-tune timing and level."
}
}
diff --git a/src/i18n/locales/tr/editor.json b/src/i18n/locales/tr/editor.json
index 25bc0145d..81abd078e 100644
--- a/src/i18n/locales/tr/editor.json
+++ b/src/i18n/locales/tr/editor.json
@@ -134,6 +134,8 @@
"emptyHint": "Henüz medya yok — başlamak için bir kayıt içe aktarın.",
"importMedia": "Medya içe aktar",
"added": "{{label}} eklendi",
+ "addToTimeline": "Zaman çizelgesine ekle",
+ "addedToTimeline": "{{label}} zaman çizelgesine eklendi",
"sourceTranscript": "Kaynak Metin Dökümü",
"close": "Kapat",
"transcriptReady": "Metin dökümü hazır",
diff --git a/src/i18n/locales/tr/settings.json b/src/i18n/locales/tr/settings.json
index 278100998..cef53c15f 100644
--- a/src/i18n/locales/tr/settings.json
+++ b/src/i18n/locales/tr/settings.json
@@ -54,6 +54,10 @@
"reactiveWebcamDescription": "Video yakınlaştırıldığında kamera yumuşakça küçülür, böylece yoldan çekilir.",
"help": "Web kamerasının ekranla birleştirilme biçimi: resim içinde resim, dikey yığın, çift çerçeve, maske şekli, boyut ve aynalama.",
"helpNoWebcam": "Bu projede kamera yok; bu yüzden yerleşim denetimleri kapalı ve ön ayar “Web kamerası yok” gösteriyor. Kaydettiğiniz yerleşim, bir kamera eklediğinizde kullanılmak üzere korunur.",
+ "webcamFraming": "Webcam framing",
+ "webcamCropZoom": "Crop zoom",
+ "webcamCropX": "Horizontal pan",
+ "webcamCropY": "Vertical pan",
"shapes": {
"rectangle": "Dikdörtgen",
"circle": "Daire",
@@ -299,5 +303,13 @@
"lineLength": "Satır uzunluğu",
"minWords": "Satır başına en az kelime",
"maxWords": "Satır başına en çok kelime"
+ },
+ "audio": {
+ "title": "Audio",
+ "autoMaster": "Auto master",
+ "syncOffset": "Sync offset",
+ "outputGain": "Output trim",
+ "reset": "Reset audio",
+ "help": "Automatically clean and balance voice audio, then fine-tune timing and level."
}
}
diff --git a/src/i18n/locales/vi/editor.json b/src/i18n/locales/vi/editor.json
index d471e20eb..43f878897 100644
--- a/src/i18n/locales/vi/editor.json
+++ b/src/i18n/locales/vi/editor.json
@@ -134,6 +134,8 @@
"emptyHint": "Chưa có media nào — nhập một bản ghi để bắt đầu.",
"importMedia": "Nhập media",
"added": "Đã thêm {{label}}",
+ "addToTimeline": "Thêm vào dòng thời gian",
+ "addedToTimeline": "Đã thêm {{label}} vào dòng thời gian",
"sourceTranscript": "Bản ghi lời thoại nguồn",
"close": "Đóng",
"transcriptReady": "Bản ghi lời thoại đã sẵn sàng",
diff --git a/src/i18n/locales/vi/settings.json b/src/i18n/locales/vi/settings.json
index 02a4929eb..05bce87e5 100644
--- a/src/i18n/locales/vi/settings.json
+++ b/src/i18n/locales/vi/settings.json
@@ -54,6 +54,10 @@
"reactiveWebcamDescription": "Camera thu nhỏ mượt mà khi video được phóng to, để không che khuất.",
"help": "Cách ghép webcam với màn hình: hình trong hình, xếp dọc, khung đôi, hình dạng mặt nạ, kích thước và lật gương.",
"helpNoWebcam": "Dự án này không có camera nên các tùy chọn bố cục bị tắt và thiết lập sẵn hiển thị “Không có webcam”. Bố cục đã lưu của bạn vẫn được giữ lại cho khi bạn thêm camera.",
+ "webcamFraming": "Webcam framing",
+ "webcamCropZoom": "Crop zoom",
+ "webcamCropX": "Horizontal pan",
+ "webcamCropY": "Vertical pan",
"shapes": {
"rectangle": "Chữ nhật",
"circle": "Tròn",
@@ -299,5 +303,13 @@
"lineLength": "Độ dài dòng",
"minWords": "Số từ tối thiểu mỗi dòng",
"maxWords": "Số từ tối đa mỗi dòng"
+ },
+ "audio": {
+ "title": "Audio",
+ "autoMaster": "Auto master",
+ "syncOffset": "Sync offset",
+ "outputGain": "Output trim",
+ "reset": "Reset audio",
+ "help": "Automatically clean and balance voice audio, then fine-tune timing and level."
}
}
diff --git a/src/i18n/locales/zh-CN/editor.json b/src/i18n/locales/zh-CN/editor.json
index 2cc1cffe0..0d0689992 100644
--- a/src/i18n/locales/zh-CN/editor.json
+++ b/src/i18n/locales/zh-CN/editor.json
@@ -134,6 +134,8 @@
"emptyHint": "暂无媒体 — 导入录制内容以开始。",
"importMedia": "导入媒体",
"added": "已添加 {{label}}",
+ "addToTimeline": "添加到时间线",
+ "addedToTimeline": "已将 {{label}} 添加到时间线",
"sourceTranscript": "来源转录文本",
"close": "关闭",
"transcriptReady": "转录已就绪",
diff --git a/src/i18n/locales/zh-CN/settings.json b/src/i18n/locales/zh-CN/settings.json
index 984d3e372..78a75aa50 100644
--- a/src/i18n/locales/zh-CN/settings.json
+++ b/src/i18n/locales/zh-CN/settings.json
@@ -54,6 +54,10 @@
"reactiveWebcamDescription": "放大视频时摄像头会平滑缩小,以免遮挡内容。",
"help": "摄像头与屏幕的合成方式:画中画、垂直堆叠、双画面、遮罩形状、大小和镜像。",
"helpNoWebcam": "此项目没有摄像头,因此布局控件已禁用,预设显示为“无摄像头”。你保存的布局会保留,以便添加摄像头后使用。",
+ "webcamFraming": "Webcam framing",
+ "webcamCropZoom": "Crop zoom",
+ "webcamCropX": "Horizontal pan",
+ "webcamCropY": "Vertical pan",
"shapes": {
"rectangle": "矩形",
"circle": "圆形",
@@ -299,5 +303,13 @@
"lineLength": "行长",
"minWords": "每行最少词数",
"maxWords": "每行最多词数"
+ },
+ "audio": {
+ "title": "Audio",
+ "autoMaster": "Auto master",
+ "syncOffset": "Sync offset",
+ "outputGain": "Output trim",
+ "reset": "Reset audio",
+ "help": "Automatically clean and balance voice audio, then fine-tune timing and level."
}
}
diff --git a/src/i18n/locales/zh-TW/editor.json b/src/i18n/locales/zh-TW/editor.json
index ea338776f..f37bfe620 100644
--- a/src/i18n/locales/zh-TW/editor.json
+++ b/src/i18n/locales/zh-TW/editor.json
@@ -134,6 +134,8 @@
"emptyHint": "尚無媒體 — 匯入錄製內容以開始。",
"importMedia": "匯入媒體",
"added": "已新增 {{label}}",
+ "addToTimeline": "新增至時間軸",
+ "addedToTimeline": "已將 {{label}} 新增至時間軸",
"sourceTranscript": "來源逐字稿",
"close": "關閉",
"transcriptReady": "逐字稿已就緒",
diff --git a/src/i18n/locales/zh-TW/settings.json b/src/i18n/locales/zh-TW/settings.json
index 0778cd0e1..0534687ec 100644
--- a/src/i18n/locales/zh-TW/settings.json
+++ b/src/i18n/locales/zh-TW/settings.json
@@ -55,6 +55,10 @@
"reactiveWebcamDescription": "放大影片時鏡頭會平滑縮小,以免遮擋內容。",
"help": "攝影機與螢幕的合成方式:子母畫面、垂直堆疊、雙畫面、遮罩形狀、大小與鏡像。",
"helpNoWebcam": "此專案沒有攝影機,因此版面配置控制項已停用,預設顯示為「無網路攝影機」。你儲存的版面配置會保留,以便新增攝影機後使用。",
+ "webcamFraming": "Webcam framing",
+ "webcamCropZoom": "Crop zoom",
+ "webcamCropX": "Horizontal pan",
+ "webcamCropY": "Vertical pan",
"shapes": {
"rectangle": "矩形",
"circle": "圓形",
@@ -300,5 +304,13 @@
"lineLength": "行長",
"minWords": "每行最少字數",
"maxWords": "每行最多字數"
+ },
+ "audio": {
+ "title": "Audio",
+ "autoMaster": "Auto master",
+ "syncOffset": "Sync offset",
+ "outputGain": "Output trim",
+ "reset": "Reset audio",
+ "help": "Automatically clean and balance voice audio, then fine-tune timing and level."
}
}
diff --git a/src/lib/ai-edition/store/editorSettings.ts b/src/lib/ai-edition/store/editorSettings.ts
index c77f42330..aef27e97e 100644
--- a/src/lib/ai-edition/store/editorSettings.ts
+++ b/src/lib/ai-edition/store/editorSettings.ts
@@ -53,6 +53,11 @@ export interface EditorSettingsSnapshot {
webcamReactiveZoom: boolean;
webcamSizePreset: WebcamSizePreset;
webcamPosition: WebcamPosition | null;
+ webcamCropRegion: CropRegion;
+ /** Positive values move audio later; negative values advance it. */
+ audioOffsetMs: number;
+ audioGainDb: number;
+ audioAutoMaster: boolean;
cursor: CursorVisualSettings;
cursorShow: boolean;
cursorTheme: string;
@@ -79,6 +84,10 @@ export const DEFAULT_EDITOR_SETTINGS: EditorSettingsSnapshot = {
webcamReactiveZoom: DEFAULT_WEBCAM_REACTIVE_ZOOM,
webcamSizePreset: DEFAULT_WEBCAM_SIZE_PRESET,
webcamPosition: DEFAULT_WEBCAM_POSITION,
+ webcamCropRegion: DEFAULT_CROP_REGION,
+ audioOffsetMs: 0,
+ audioGainDb: 0,
+ audioAutoMaster: true,
cursor: {
size: DEFAULT_CURSOR_SIZE,
smoothing: DEFAULT_CURSOR_SMOOTHING,
@@ -106,6 +115,10 @@ interface LegacyShape {
webcamReactiveZoom?: boolean;
webcamSizePreset?: WebcamSizePreset;
webcamPosition?: WebcamPosition | null;
+ webcamCropRegion?: CropRegion;
+ audioOffsetMs?: number;
+ audioGainDb?: number;
+ audioAutoMaster?: boolean;
cursorSize?: number;
cursorSmoothing?: number;
cursorMotionBlur?: number;
@@ -160,6 +173,10 @@ export function getEditorSettings(doc: AxcutDocument | null | undefined): Editor
),
webcamSizePreset: num(legacy?.webcamSizePreset, DEFAULT_EDITOR_SETTINGS.webcamSizePreset),
webcamPosition: normaliseWebcamPosition(legacy?.webcamPosition),
+ webcamCropRegion: normaliseCropRegion(legacy?.webcamCropRegion),
+ audioOffsetMs: Math.min(2_000, Math.max(-2_000, num(legacy?.audioOffsetMs, 0))),
+ audioGainDb: Math.min(18, Math.max(-24, num(legacy?.audioGainDb, 0))),
+ audioAutoMaster: bool(legacy?.audioAutoMaster, true),
cursor,
cursorShow: bool(legacy?.cursorShow, DEFAULT_EDITOR_SETTINGS.cursorShow),
cursorTheme: str(legacy?.cursorTheme, DEFAULT_EDITOR_SETTINGS.cursorTheme),
@@ -181,6 +198,10 @@ export interface EditorSettingsPatch {
webcamReactiveZoom?: boolean;
webcamSizePreset?: WebcamSizePreset;
webcamPosition?: WebcamPosition | null;
+ webcamCropRegion?: CropRegion;
+ audioOffsetMs?: number;
+ audioGainDb?: number;
+ audioAutoMaster?: boolean;
cursor?: Partial<CursorVisualSettings> & { theme?: string; show?: boolean };
autoFocusAll?: boolean;
}
@@ -233,3 +254,17 @@ function normaliseWebcamPosition(value: unknown): WebcamPosition | null {
cy: Math.min(1, Math.max(0, cyRaw)),
};
}
+
+function normaliseCropRegion(value: unknown): CropRegion {
+ if (!value || typeof value !== "object") return DEFAULT_CROP_REGION;
+ const candidate = value as Record<string, unknown>;
+ const x = isNumber(candidate.x) ? Math.min(1, Math.max(0, candidate.x)) : 0;
+ const y = isNumber(candidate.y) ? Math.min(1, Math.max(0, candidate.y)) : 0;
+ const width = isNumber(candidate.width)
+ ? Math.min(1 - x, Math.max(0.01, candidate.width))
+ : 1 - x;
+ const height = isNumber(candidate.height)
+ ? Math.min(1 - y, Math.max(0.01, candidate.height))
+ : 1 - y;
+ return { x, y, width, height };
+}
diff --git a/src/native/sceneDescription.ts b/src/native/sceneDescription.ts
index df4c68e44..fe95ac43f 100644
--- a/src/native/sceneDescription.ts
+++ b/src/native/sceneDescription.ts
@@ -213,6 +213,8 @@ export interface SceneLayout {
webcamPosition: { cx: number; cy: number } | null;
/** Webcam shrinks while a zoom region is active. */
webcamReactiveZoom: boolean;
+ /** User-authored webcam framing, as fractions of the camera source. */
+ webcamCrop: { x: number; y: number; width: number; height: number };
/**
* Webcam rect resolved by the app (= `computeCompositeLayout(...).webcamRect`, pixels
* → fractions of the output frame, parity EXACTE entre preview et natif). When set, the
@@ -368,6 +370,13 @@ export interface SceneDescription {
*/
speedRegions: SceneSpeedRegion[];
cursor: SceneCursor;
+ /** Voice-oriented finishing applied to preview/export audio. Offset is signed:
+ * positive delays audio, negative advances it. */
+ audio: {
+ offsetMs: number;
+ gainDb: number;
+ autoMaster: 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
@@ -602,6 +611,12 @@ export function buildSceneDescription(
* screen squeezed into its half with nothing beside it. `has_webcam` (native) only
* gates the camera's own draw — it cannot give the screen its frame back.
*/
+ const croppedWebcamSize = webcamSourceSize
+ ? {
+ width: Math.max(1, webcamSourceSize.width * settings.webcamCropRegion.width),
+ height: Math.max(1, webcamSourceSize.height * settings.webcamCropRegion.height),
+ }
+ : null;
const layoutForClip = (screenSize: { width: number; height: number }, hasCamera: boolean) => {
const preset = resolveWebcamLayoutPreset(settings.webcamLayoutPreset, hasCamera);
return computeCompositeLayout({
@@ -611,7 +626,8 @@ export function buildSceneDescription(
height: Math.round(outputDims.height * paddingFit),
},
screenSize,
- webcamSize: preset === "no-webcam" ? null : (webcamSourceSize ?? { width: 960, height: 720 }),
+ webcamSize:
+ preset === "no-webcam" ? null : (croppedWebcamSize ?? { width: 960, height: 720 }),
layoutPreset: preset,
webcamSizePreset: settings.webcamSizePreset,
webcamPosition: preset === "picture-in-picture" ? settings.webcamPosition : null,
@@ -677,6 +693,7 @@ export function buildSceneDescription(
settings.webcamLayoutPreset,
settings.webcamReactiveZoom,
),
+ webcamCrop: settings.webcamCropRegion,
webcamRect,
screenRect,
screenRadiusFrac: radiusFractionOf(
@@ -709,6 +726,11 @@ export function buildSceneDescription(
clipToBounds: settings.cursor.clipToBounds,
theme: settings.cursorTheme,
},
+ audio: {
+ offsetMs: settings.audioOffsetMs,
+ gainDb: settings.audioGainDb,
+ autoMaster: settings.audioAutoMaster,
+ },
background: parseWallpaper(settings.wallpaper),
zoomRegions: projectedZoomRegions.map((region) => ({
id: region.id,