The truly free, open-source, local-first, cross-platform CapCut replacement. Scriptable through a JSON-RPC API & MCP.
Rust ffmpegfree-video-editormodel-context-protocolnon-linear-editoroffline-firstopen-source-video-editorself-hostedvideo-editingvideo-editing-automationvideo-editing-softwarevideo-editing-toolsvideo-editorvoice-cloningyoutube-automationyoutube-shorts
feat(voiceover): record from the microphone over the picture, onto the timeline
Jareer1370adb8568f
diff --git a/.github/workflows/build-app.yml b/.github/workflows/build-app.ymlindex d128bf65..79bbef97 100644--- a/.github/workflows/build-app.yml+++ b/.github/workflows/build-app.yml@@ -451,6 +451,7 @@ jobs:<key>NSSupportsAutomaticGraphicsSwitching</key><true/><key>LSApplicationCategoryType</key><string>public.app-category.video</string><key>NSHumanReadableCopyright</key><string>AGPL-3.0-or-later. See THIRD_PARTY_NOTICES.md.</string>+ <key>NSMicrophoneUsageDescription</key><string>Concat records voiceovers from your microphone.</string></dict></plist>PLIST@@ -501,8 +502,15 @@ jobs:# signature covers what is beneath it.find "$app/Contents/Frameworks" -name '*.dylib' -exec \codesign --force --options runtime --timestamp -s "$IDENTITY" {} \;- codesign --force --options runtime --timestamp -s "$IDENTITY" "$app/Contents/MacOS/concat"- codesign --force --options runtime --timestamp -s "$IDENTITY" "$app"+ # The hardened runtime keeps the microphone shut unless the app+ # says it records: the voiceover.+ entitlements="$RUNNER_TEMP/concat.entitlements"+ printf '%s\n' '<?xml version="1.0" encoding="UTF-8"?>' \+ '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">' \+ '<plist version="1.0"><dict><key>com.apple.security.device.audio-input</key><true/></dict></plist>' \+ > "$entitlements"+ codesign --force --options runtime --timestamp --entitlements "$entitlements" -s "$IDENTITY" "$app/Contents/MacOS/concat"+ codesign --force --options runtime --timestamp --entitlements "$entitlements" -s "$IDENTITY" "$app"codesign --verify --deep --strict "$app"elseecho "No signing identity: ad-hoc signing."diff --git a/src/crates/concat-host/src/lib.rs b/src/crates/concat-host/src/lib.rsindex f4429f76..6a978b10 100644--- a/src/crates/concat-host/src/lib.rs+++ b/src/crates/concat-host/src/lib.rs@@ -33,6 +33,7 @@ pub mod playback;pub mod preview;pub mod projects;pub mod proxy;+pub mod record;pub mod reverse;pub mod session;pub mod templates;diff --git a/src/crates/concat-host/src/playback.rs b/src/crates/concat-host/src/playback.rsindex f44efeea..5f49ae2e 100644--- a/src/crates/concat-host/src/playback.rs+++ b/src/crates/concat-host/src/playback.rs@@ -290,6 +290,10 @@ struct Shared {origin_micros: AtomicI64,epoch: std::time::Instant,playing: AtomicBool,+ /// Silent while set: the clock runs on, the speakers say nothing. A+ /// voiceover takes the picture without the timeline's sound, so the+ /// speakers do not bleed into the microphone.+ muted: AtomicBool,}/// The longest the clock runs on past the callback's last word. A callback@@ -304,6 +308,7 @@ impl Shared {origin_micros: AtomicI64::new(0),epoch: std::time::Instant::now(),playing: AtomicBool::new(false),+ muted: AtomicBool::new(false),}}@@ -533,6 +538,12 @@ impl Playback {self.shared.playing.load(Ordering::Relaxed)}+ /// Silences the output, or lets it speak again. The clock is not+ /// touched: the picture plays on in time either way.+ pub fn set_muted(&self, muted: bool) {+ self.shared.muted.store(muted, Ordering::Relaxed);+ }+/// Replaces the audible clip set.////// Anything already decoded plays immediately; anything new joins the@@ -1102,6 +1113,7 @@ wherereturn;}+ let silent = shared.muted.load(Ordering::Relaxed);for frame in data.chunks_mut(channels) {let mut left = 0.0f32;let mut right = 0.0f32;@@ -1131,6 +1143,10 @@ where+ pcm.sample(index + 1, 1) * fraction);}+ if silent {+ left = 0.0;+ right = 0.0;+ }// Hard limit. A mix of boosted clips can exceed full// scale; wrapping would be far worse than flattening.frame[0] = T::from_sample(left.clamp(-1.0, 1.0));diff --git a/src/crates/concat-host/src/record.rs b/src/crates/concat-host/src/record.rsnew file mode 100644index 00000000..209d86d8--- /dev/null+++ b/src/crates/concat-host/src/record.rs@@ -0,0 +1,385 @@+// SPDX-License-Identifier: AGPL-3.0-or-later+// SPDX-FileCopyrightText: 2026 Jareer and Concat contributors++//! Recording from the microphone: a voiceover, straight into a WAV file in+//! the project's audio folder.+//!+//! One thread owns the input stream from open to close (a cpal stream may+//! not cross threads) and writes what the device hands it. The callback+//! only mixes each buffer down to mono, turns it into 16-bit samples and+//! passes it on, so the device is never kept waiting on the disk. What the+//! window reads while a take runs is the level for its meter; what it gets+//! at the end is the file, its length, and when its first sample was heard,+//! which is what lines the take up with the picture it was spoken over.++use std::fs::File;+use std::io::{BufWriter, Seek, SeekFrom, Write};+use std::path::{Path, PathBuf};+use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};+use std::sync::{Arc, Mutex, mpsc};+use std::time::{Duration, Instant};++/// A take in progress. Dropping it stops the take and keeps what was heard.+pub struct Recorder {+ stop: Arc<AtomicBool>,+ level: Arc<AtomicU32>,+ thread: Option<std::thread::JoinHandle<Result<Take, String>>>,+}++/// A finished take.+#[derive(Clone, Debug)]+pub struct Take {+ /// The WAV file, 16-bit mono at the device's own rate.+ pub path: PathBuf,+ /// Its length, in seconds.+ pub seconds: f64,+ /// When the microphone heard the first sample, as near as the device+ /// says: the callback's time less the latency it reports. None when no+ /// sound arrived at all.+ pub first: Option<Instant>,+}++impl Recorder {+ /// Opens the default microphone and starts writing to `path`. Returns+ /// once the device is open and running, or with why it would not open:+ /// no microphone, or one the system will not hand over.+ pub fn start(path: PathBuf) -> Result<Recorder, String> {+ if let Some(folder) = path.parent() {+ std::fs::create_dir_all(folder)+ .map_err(|error| format!("could not make {}: {error}", folder.display()))?;+ }+ let stop = Arc::new(AtomicBool::new(false));+ let level = Arc::new(AtomicU32::new(0));+ let (ready_tx, ready_rx) = mpsc::channel::<Result<(), String>>();+ let thread = {+ let stop = Arc::clone(&stop);+ let level = Arc::clone(&level);+ std::thread::Builder::new()+ .name("audio-input".into())+ .spawn(move || record(&path, &stop, &level, &ready_tx))+ .map_err(|error| format!("could not spawn the recording thread: {error}"))?+ };+ match ready_rx.recv() {+ Ok(Ok(())) => Ok(Recorder {+ stop,+ level,+ thread: Some(thread),+ }),+ Ok(Err(error)) => {+ let _ = thread.join();+ Err(error)+ }+ Err(_) => Err(match thread.join() {+ Ok(Err(error)) => error,+ _ => "the recording thread stopped before the microphone opened".to_owned(),+ }),+ }+ }++ /// The loudest sample since the last look, `0..=1`: the meter's feed.+ pub fn level(&self) -> f32 {+ f32::from_bits(self.level.swap(0, Ordering::Relaxed))+ }++ /// Stops the take and finishes the file.+ pub fn stop(mut self) -> Result<Take, String> {+ self.finish()+ }++ fn finish(&mut self) -> Result<Take, String> {+ self.stop.store(true, Ordering::Relaxed);+ let thread = self+ .thread+ .take()+ .ok_or_else(|| "the take was already stopped".to_owned())?;+ thread+ .join()+ .map_err(|_| "the recording thread panicked".to_owned())?+ }+}++impl Drop for Recorder {+ fn drop(&mut self) {+ if self.thread.is_some() {+ let _ = self.finish();+ }+ }+}++/// The recording thread: opens the device, says so, writes until told to+/// stop, then closes the stream and the file.+fn record(+ path: &Path,+ stop: &AtomicBool,+ level: &Arc<AtomicU32>,+ ready: &mpsc::Sender<Result<(), String>>,+) -> Result<Take, String> {+ use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};++ let opened = (|| -> Result<_, String> {+ let device = cpal::default_host()+ .default_input_device()+ .ok_or_else(|| "no microphone was found".to_owned())?;+ let supported = device+ .default_input_config()+ .map_err(|error| format!("the microphone would not say how it records: {error}"))?;+ let config: cpal::StreamConfig = supported.config();+ let (tx, rx) = mpsc::channel::<Vec<i16>>();+ let first: Arc<Mutex<Option<Instant>>> = Arc::new(Mutex::new(None));+ let failed: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None));+ let stream = match supported.sample_format() {+ cpal::SampleFormat::F32 => input::<f32>(&device, &config, tx, level, &first, &failed),+ cpal::SampleFormat::I16 => input::<i16>(&device, &config, tx, level, &first, &failed),+ cpal::SampleFormat::U16 => input::<u16>(&device, &config, tx, level, &first, &failed),+ cpal::SampleFormat::I32 => input::<i32>(&device, &config, tx, level, &first, &failed),+ other => Err(format!(+ "the microphone records {other:?} samples, which Concat does not read"+ )),+ }?;+ stream+ .play()+ .map_err(|error| format!("the microphone would not start: {error}"))?;+ let writer = WavWriter::create(path, config.sample_rate.0)?;+ Ok((stream, rx, writer, first, failed))+ })();++ let (stream, rx, mut writer, first, failed) = match opened {+ Ok(parts) => {+ let _ = ready.send(Ok(()));+ parts+ }+ Err(error) => {+ let _ = ready.send(Err(error.clone()));+ return Err(error);+ }+ };++ while !stop.load(Ordering::Relaxed) {+ match rx.recv_timeout(Duration::from_millis(20)) {+ Ok(samples) => writer.write(&samples)?,+ Err(mpsc::RecvTimeoutError::Timeout) => {}+ Err(mpsc::RecvTimeoutError::Disconnected) => break,+ }+ }+ // Closed first, so nothing more is sent; then whatever was already on+ // its way is written.+ drop(stream);+ while let Ok(samples) = rx.try_recv() {+ writer.write(&samples)?;+ }+ let seconds = writer.finish()?;+ let first = *first+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner());+ if first.is_none() {+ let why = failed+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner())+ .take();+ return Err(why.unwrap_or_else(|| "the microphone sent no sound".to_owned()));+ }+ Ok(Take {+ path: path.to_owned(),+ seconds,+ first,+ })+}++/// The input stream for one sample format: each buffer mixed down to mono+/// 16-bit and sent to the writer, its loudest sample kept for the meter.+fn input<T>(+ device: &cpal::Device,+ config: &cpal::StreamConfig,+ tx: mpsc::Sender<Vec<i16>>,+ level: &Arc<AtomicU32>,+ first: &Arc<Mutex<Option<Instant>>>,+ failed: &Arc<Mutex<Option<String>>>,+) -> Result<cpal::Stream, String>+where+ T: cpal::SizedSample,+ f32: cpal::FromSample<T>,+{+ use cpal::traits::DeviceTrait;++ let channels = usize::from(config.channels.max(1));+ let level = Arc::clone(level);+ let first = Arc::clone(first);+ let failed = Arc::clone(failed);+ device+ .build_input_stream(+ config,+ move |data: &[T], info: &cpal::InputCallbackInfo| {+ if let Ok(mut first) = first.try_lock()+ && first.is_none()+ {+ let stamp = info.timestamp();+ let latency = stamp+ .callback+ .duration_since(&stamp.capture)+ .unwrap_or_default();+ *first = Instant::now().checked_sub(latency);+ }+ let (mono, peak) = mix_down(data.iter().map(|s| s.to_sample::<f32>()), channels);+ let held = f32::from_bits(level.load(Ordering::Relaxed));+ if peak > held {+ level.store(peak.to_bits(), Ordering::Relaxed);+ }+ let _ = tx.send(mono);+ },+ move |error| {+ log::warn!("microphone: {error}");+ if let Ok(mut failed) = failed.lock() {+ failed.get_or_insert_with(|| format!("the microphone failed: {error}"));+ }+ },+ None,+ )+ .map_err(|error| format!("the microphone would not open: {error}"))+}++/// Interleaved samples of `channels` channels as 16-bit mono - the mean of+/// each frame's channels - and the loudest of them, `0..=1`.+fn mix_down(samples: impl Iterator<Item = f32>, channels: usize) -> (Vec<i16>, f32) {+ let channels = channels.max(1);+ let mut mono = Vec::new();+ let mut peak = 0.0f32;+ let mut sum = 0.0f32;+ let mut count = 0;+ for sample in samples {+ sum += sample;+ count += 1;+ if count == channels {+ let value = (sum / channels as f32).clamp(-1.0, 1.0);+ peak = peak.max(value.abs());+ mono.push((value * f32::from(i16::MAX)).round() as i16);+ sum = 0.0;+ count = 0;+ }+ }+ (mono, peak)+}++/// A 16-bit mono WAV written as it goes: the header up front with its sizes+/// left open, filled in by [`WavWriter::finish`].+struct WavWriter {+ out: BufWriter<File>,+ rate: u32,+ samples: u64,+}++impl WavWriter {+ fn create(path: &Path, rate: u32) -> Result<Self, String> {+ let file = File::create(path)+ .map_err(|error| format!("could not write {}: {error}", path.display()))?;+ let mut writer = WavWriter {+ out: BufWriter::new(file),+ rate,+ samples: 0,+ };+ writer.header(0)?;+ Ok(writer)+ }++ fn header(&mut self, data_bytes: u32) -> Result<(), String> {+ let io = |error: std::io::Error| format!("could not write the recording: {error}");+ let out = &mut self.out;+ out.write_all(b"RIFF").map_err(io)?;+ out.write_all(&(36 + data_bytes).to_le_bytes())+ .map_err(io)?;+ out.write_all(b"WAVEfmt ").map_err(io)?;+ out.write_all(&16u32.to_le_bytes()).map_err(io)?;+ out.write_all(&1u16.to_le_bytes()).map_err(io)?; // PCM+ out.write_all(&1u16.to_le_bytes()).map_err(io)?; // mono+ out.write_all(&self.rate.to_le_bytes()).map_err(io)?;+ out.write_all(&(self.rate * 2).to_le_bytes()).map_err(io)?;+ out.write_all(&2u16.to_le_bytes()).map_err(io)?; // block align+ out.write_all(&16u16.to_le_bytes()).map_err(io)?;+ out.write_all(b"data").map_err(io)?;+ out.write_all(&data_bytes.to_le_bytes()).map_err(io)+ }++ fn write(&mut self, samples: &[i16]) -> Result<(), String> {+ for sample in samples {+ self.out+ .write_all(&sample.to_le_bytes())+ .map_err(|error| format!("could not write the recording: {error}"))?;+ }+ self.samples += samples.len() as u64;+ Ok(())+ }++ /// Fills in the sizes and closes the file; returns its length in seconds.+ fn finish(mut self) -> Result<f64, String> {+ // A WAV's sizes are 32-bit: past about thirteen hours of mono at+ // 48 kHz the header would wrap, so it says as much as it can.+ let data_bytes = u32::try_from(self.samples * 2).unwrap_or(u32::MAX - 36);+ self.out+ .seek(SeekFrom::Start(0))+ .map_err(|error| format!("could not finish the recording: {error}"))?;+ self.header(data_bytes)?;+ self.out+ .flush()+ .map_err(|error| format!("could not finish the recording: {error}"))?;+ Ok(self.samples as f64 / f64::from(self.rate))+ }+}++/// Where a take spoken from `playhead` lands on the timeline: shifted by how+/// long after the picture started rolling the microphone heard its first+/// sample, so the words sit under the frames they were spoken to. Never+/// before zero.+pub fn landing(playhead: f64, rolled: Instant, first: Option<Instant>) -> f64 {+ let offset = match first {+ Some(first) if first >= rolled => first.duration_since(rolled).as_secs_f64(),+ Some(first) => -rolled.duration_since(first).as_secs_f64(),+ None => 0.0,+ };+ (playhead + offset).max(0.0)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn stereo_mixes_down_to_the_mean_and_reports_its_peak() {+ let (mono, peak) = mix_down([0.5, 0.5, -1.0, 0.0, 0.25].into_iter(), 2);+ // The fifth sample is half a frame and is not written.+ assert_eq!(mono, vec![16384, -16384]);+ assert!((peak - 0.5).abs() < 1e-6);+ }++ #[test]+ fn a_wav_says_its_own_size_once_finished() {+ let path = std::env::temp_dir().join(format!("concat-record-{}.wav", std::process::id()));+ let mut writer = WavWriter::create(&path, 48_000).expect("creates");+ writer.write(&[1, -1, 2, -2]).expect("writes");+ writer.write(&[3]).expect("writes");+ let seconds = writer.finish().expect("finishes");+ let bytes = std::fs::read(&path).expect("reads");+ let _ = std::fs::remove_file(&path);+ assert_eq!(bytes.len(), 44 + 10);+ assert_eq!(&bytes[0..4], b"RIFF");+ assert_eq!(u32::from_le_bytes(bytes[4..8].try_into().unwrap()), 36 + 10);+ assert_eq!(+ u32::from_le_bytes(bytes[24..28].try_into().unwrap()),+ 48_000+ );+ assert_eq!(u32::from_le_bytes(bytes[40..44].try_into().unwrap()), 10);+ assert_eq!(i16::from_le_bytes([bytes[44], bytes[45]]), 1);+ assert!((seconds - 5.0 / 48_000.0).abs() < 1e-12);+ }++ #[test]+ fn a_take_lands_where_its_first_sample_was_heard() {+ let rolled = Instant::now();+ let late = rolled + Duration::from_millis(120);+ assert!((landing(10.0, rolled, Some(late)) - 10.12).abs() < 1e-9);+ let early = rolled+ .checked_sub(Duration::from_millis(30))+ .expect("not at boot");+ assert!((landing(10.0, rolled, Some(early)) - 9.97).abs() < 1e-9);+ assert_eq!(landing(0.01, rolled, Some(early)), 0.0, "never before zero");+ assert_eq!(landing(4.0, rolled, None), 4.0);+ }+}diff --git a/src/crates/concat/locales/de.json b/src/crates/concat/locales/de.jsonindex d2f510ed..dde588ab 100644--- a/src/crates/concat/locales/de.json+++ b/src/crates/concat/locales/de.json@@ -999,12 +999,16 @@"tray.panTool": "Pan tool (H)","tray.playerFollowsResizePlayhead": "Wiedergabe folgt dem Kürzen: Der Abspielkopf wandert mit der Kante, die du kürzt","tray.previewAxisOptions": "Optionen der Vorschauachse",+ "tray.recordVoiceover": "Voiceover aufnehmen","tray.redo": "Wiederholen ({0})","tray.splitAtPlayhead": "Am Abspielkopf teilen ({0})","tray.splitTool": "Schneidewerkzeug (B): Klick auf einen Clip schneidet ihn dort",+ "tray.stopRecording": "Aufnahme beenden","tray.textToSpeech": "Text zu Sprache","tray.turnOffPreviewAxis": "Vorschauachse ausschalten (S)","tray.turnOnPreviewAxis": "Vorschauachse einschalten (S)","tray.undo": "Rückgängig ({0})",- "tray.zoomToFit": "Einpassen"+ "tray.zoomToFit": "Einpassen",+ "voiceover.added": "Voiceover zur Zeitleiste hinzugefügt",+ "voiceover.failed": "Aufnahme nicht möglich: {0}"}diff --git a/src/crates/concat/locales/en.json b/src/crates/concat/locales/en.jsonindex 808c57c8..7d2dd71e 100644--- a/src/crates/concat/locales/en.json+++ b/src/crates/concat/locales/en.json@@ -999,12 +999,16 @@"tray.panTool": "Pan tool (H)","tray.playerFollowsResizePlayhead": "Player follows the resize: the playhead rides the edge you trim","tray.previewAxisOptions": "Preview axis options",+ "tray.recordVoiceover": "Record Voiceover","tray.redo": "Redo ({0})","tray.splitAtPlayhead": "Split at playhead ({0})","tray.splitTool": "Split tool (B): click a clip to cut it there",+ "tray.stopRecording": "Stop Recording","tray.textToSpeech": "Text to Speech","tray.turnOffPreviewAxis": "Turn off Preview Axis (S)","tray.turnOnPreviewAxis": "Turn on Preview Axis (S)","tray.undo": "Undo ({0})",- "tray.zoomToFit": "Zoom to fit"+ "tray.zoomToFit": "Zoom to fit",+ "voiceover.added": "Voiceover added to the timeline",+ "voiceover.failed": "Couldn't record: {0}"}diff --git a/src/crates/concat/locales/es.json b/src/crates/concat/locales/es.jsonindex 5de4dbeb..adfd44ac 100644--- a/src/crates/concat/locales/es.json+++ b/src/crates/concat/locales/es.json@@ -999,12 +999,16 @@"tray.panTool": "Pan tool (H)","tray.playerFollowsResizePlayhead": "El reproductor sigue el recorte: el cabezal de reproducción acompaña el borde que recortas","tray.previewAxisOptions": "Opciones del eje de previsualización",+ "tray.recordVoiceover": "Grabar voz en off","tray.redo": "Rehacer ({0})","tray.splitAtPlayhead": "Dividir en el cabezal ({0})","tray.splitTool": "Herramienta de corte (B): clic en un clip para cortarlo ahí",+ "tray.stopRecording": "Detener grabación","tray.textToSpeech": "Texto a voz","tray.turnOffPreviewAxis": "Desactivar el eje de previsualización (S)","tray.turnOnPreviewAxis": "Activar el eje de previsualización (S)","tray.undo": "Deshacer ({0})",- "tray.zoomToFit": "Ajustar a la vista"+ "tray.zoomToFit": "Ajustar a la vista",+ "voiceover.added": "Voz en off añadida a la línea de tiempo",+ "voiceover.failed": "No se pudo grabar: {0}"}diff --git a/src/crates/concat/locales/fa.json b/src/crates/concat/locales/fa.jsonindex b3110165..c94ff8fe 100644--- a/src/crates/concat/locales/fa.json+++ b/src/crates/concat/locales/fa.json@@ -999,12 +999,16 @@"tray.panTool": "ابزار Pan (H)","tray.playerFollowsResizePlayhead": "پخشکننده برش را دنبال میکند: نشانگر پخش همراه لبهای که برش میدهید حرکت میکند","tray.previewAxisOptions": "گزینههای محور پیشنمایش",+ "tray.recordVoiceover": "ضبط صداگذاری","tray.redo": "انجام مجدد ({0})","tray.splitAtPlayhead": "تقسیم در نشانگر پخش ({0})","tray.splitTool": "ابزار برش (B): روی کلیپ کلیک کنید تا همانجا بریده شود",+ "tray.stopRecording": "توقف ضبط","tray.textToSpeech": "تبدیل متن به گفتار","tray.turnOffPreviewAxis": "خاموش کردن محور پیشنمایش (S)","tray.turnOnPreviewAxis": "روشن کردن محور پیشنمایش (S)","tray.undo": "واگرد ({0})",- "tray.zoomToFit": "بزرگنمایی متناسب"+ "tray.zoomToFit": "بزرگنمایی متناسب",+ "voiceover.added": "صداگذاری به خط زمانی اضافه شد",+ "voiceover.failed": "ضبط ممکن نشد: {0}"}diff --git a/src/crates/concat/locales/fr.json b/src/crates/concat/locales/fr.jsonindex 8ab9f326..e95c1efa 100644--- a/src/crates/concat/locales/fr.json+++ b/src/crates/concat/locales/fr.json@@ -999,12 +999,16 @@"tray.panTool": "Pan tool (H)","tray.playerFollowsResizePlayhead": "Le lecteur suit le rognage : la tête de lecture accompagne le bord que vous rognez","tray.previewAxisOptions": "Options de l'axe d'aperçu",+ "tray.recordVoiceover": "Enregistrer une voix off","tray.redo": "Rétablir ({0})","tray.splitAtPlayhead": "Couper à la tête de lecture ({0})","tray.splitTool": "Outil de coupe (B) : cliquez sur un clip pour le couper là",+ "tray.stopRecording": "Arrêter l'enregistrement","tray.textToSpeech": "Synthèse vocale","tray.turnOffPreviewAxis": "Désactiver l'axe d'aperçu (S)","tray.turnOnPreviewAxis": "Activer l'axe d'aperçu (S)","tray.undo": "Annuler ({0})",- "tray.zoomToFit": "Ajuster à la vue"+ "tray.zoomToFit": "Ajuster à la vue",+ "voiceover.added": "Voix off ajoutée à la timeline",+ "voiceover.failed": "Enregistrement impossible : {0}"}diff --git a/src/crates/concat/locales/hr.json b/src/crates/concat/locales/hr.jsonindex 3da7afa7..de0cb4be 100644--- a/src/crates/concat/locales/hr.json+++ b/src/crates/concat/locales/hr.json@@ -999,12 +999,16 @@"tray.panTool": "Pan tool (H)","tray.playerFollowsResizePlayhead": "Reprodukcija prati skraćivanje: glava za reprodukciju prati rub koji skraćujete","tray.previewAxisOptions": "Mogućnosti osi pregleda",+ "tray.recordVoiceover": "Snimi glas","tray.redo": "Ponovi ({0})","tray.splitAtPlayhead": "Podijeli na playheadu ({0})","tray.splitTool": "Alat za rezanje (B): klik na klip reže ga ondje",+ "tray.stopRecording": "Zaustavi snimanje","tray.textToSpeech": "Tekst u govor","tray.turnOffPreviewAxis": "Isključi os pregleda (S)","tray.turnOnPreviewAxis": "Uključi os pregleda (S)","tray.undo": "Poništi ({0})",- "tray.zoomToFit": "Povećaj da stane"+ "tray.zoomToFit": "Povećaj da stane",+ "voiceover.added": "Glas dodan na vremensku crtu",+ "voiceover.failed": "Snimanje nije uspjelo: {0}"}diff --git a/src/crates/concat/locales/it.json b/src/crates/concat/locales/it.jsonindex 3680454f..8f39e0cd 100644--- a/src/crates/concat/locales/it.json+++ b/src/crates/concat/locales/it.json@@ -999,12 +999,16 @@"tray.panTool": "Pan tool (H)","tray.playerFollowsResizePlayhead": "Il player segue l'accorciamento: la testina di riproduzione segue il bordo che accorci","tray.previewAxisOptions": "Opzioni dell'asse di anteprima",+ "tray.recordVoiceover": "Registra voce fuori campo","tray.redo": "Ripeti ({0})","tray.splitAtPlayhead": "Dividi alla testina ({0})","tray.splitTool": "Strumento taglio (B): clic su una clip per tagliarla lì",+ "tray.stopRecording": "Interrompi registrazione","tray.textToSpeech": "Sintesi vocale","tray.turnOffPreviewAxis": "Disattiva l'asse di anteprima (S)","tray.turnOnPreviewAxis": "Attiva l'asse di anteprima (S)","tray.undo": "Annulla ({0})",- "tray.zoomToFit": "Adatta alla vista"+ "tray.zoomToFit": "Adatta alla vista",+ "voiceover.added": "Voce fuori campo aggiunta alla timeline",+ "voiceover.failed": "Impossibile registrare: {0}"}diff --git a/src/crates/concat/locales/ja.json b/src/crates/concat/locales/ja.jsonindex 587a5ca9..2f361ac8 100644--- a/src/crates/concat/locales/ja.json+++ b/src/crates/concat/locales/ja.json@@ -999,12 +999,16 @@"tray.panTool": "Pan tool (H)","tray.playerFollowsResizePlayhead": "プレーヤーがトリミングに追従:再生ヘッドがトリミング中の端に合わせて動きます","tray.previewAxisOptions": "プレビュー軸のオプション",+ "tray.recordVoiceover": "ナレーションを録音","tray.redo": "やり直す ({0})","tray.splitAtPlayhead": "再生ヘッドで分割 ({0})","tray.splitTool": "分割ツール (B): クリップをクリックした位置で切る",+ "tray.stopRecording": "録音を停止","tray.textToSpeech": "テキスト読み上げ","tray.turnOffPreviewAxis": "プレビュー軸をオフにする (S)","tray.turnOnPreviewAxis": "プレビュー軸をオンにする (S)","tray.undo": "取り消す ({0})",- "tray.zoomToFit": "全体を表示"+ "tray.zoomToFit": "全体を表示",+ "voiceover.added": "ナレーションをタイムラインに追加しました",+ "voiceover.failed": "録音できませんでした:{0}"}diff --git a/src/crates/concat/locales/ko.json b/src/crates/concat/locales/ko.jsonindex 3a5350ee..6d2a8a4a 100644--- a/src/crates/concat/locales/ko.json+++ b/src/crates/concat/locales/ko.json@@ -999,12 +999,16 @@"tray.panTool": "Pan tool (H)","tray.playerFollowsResizePlayhead": "플레이어가 다듬기를 따라감: 재생 헤드가 다듬는 가장자리를 따라 움직입니다","tray.previewAxisOptions": "미리보기 축 옵션",+ "tray.recordVoiceover": "내레이션 녹음","tray.redo": "다시 실행 ({0})","tray.splitAtPlayhead": "재생 헤드에서 나누기 ({0})","tray.splitTool": "자르기 도구 (B): 클립을 클릭한 곳에서 자릅니다",+ "tray.stopRecording": "녹음 중지","tray.textToSpeech": "텍스트 음성 변환","tray.turnOffPreviewAxis": "미리보기 축 끄기 (S)","tray.turnOnPreviewAxis": "미리보기 축 켜기 (S)","tray.undo": "실행 취소 ({0})",- "tray.zoomToFit": "화면에 맞추기"+ "tray.zoomToFit": "화면에 맞추기",+ "voiceover.added": "내레이션을 타임라인에 추가했습니다",+ "voiceover.failed": "녹음할 수 없습니다: {0}"}diff --git a/src/crates/concat/locales/pt-BR.json b/src/crates/concat/locales/pt-BR.jsonindex a2bf6bd2..be98b2d6 100644--- a/src/crates/concat/locales/pt-BR.json+++ b/src/crates/concat/locales/pt-BR.json@@ -999,12 +999,16 @@"tray.panTool": "Pan tool (H)","tray.playerFollowsResizePlayhead": "O player acompanha o corte: a agulha segue a borda que você arrasta","tray.previewAxisOptions": "Opções do eixo de prévia",+ "tray.recordVoiceover": "Gravar narração","tray.redo": "Refazer ({0})","tray.splitAtPlayhead": "Dividir no cursor ({0})","tray.splitTool": "Ferramenta de corte (B): clique em um clipe para cortá-lo ali",+ "tray.stopRecording": "Parar gravação","tray.textToSpeech": "Texto para fala","tray.turnOffPreviewAxis": "Desligar o eixo de prévia (S)","tray.turnOnPreviewAxis": "Ligar o eixo de prévia (S)","tray.undo": "Desfazer ({0})",- "tray.zoomToFit": "Ajustar à janela"+ "tray.zoomToFit": "Ajustar à janela",+ "voiceover.added": "Narração adicionada à linha do tempo",+ "voiceover.failed": "Não foi possível gravar: {0}"}diff --git a/src/crates/concat/locales/ru.json b/src/crates/concat/locales/ru.jsonindex fb4b2215..efd514b0 100644--- a/src/crates/concat/locales/ru.json+++ b/src/crates/concat/locales/ru.json@@ -999,12 +999,16 @@"tray.panTool": "Инструмент «Рука» (H)","tray.playerFollowsResizePlayhead": "Плеер следует за подрезкой: курсор движется вместе с краем, который вы подрезаете","tray.previewAxisOptions": "Параметры оси предпросмотра",+ "tray.recordVoiceover": "Записать закадровый голос","tray.redo": "Повторить ({0})","tray.splitAtPlayhead": "Разрезать по курсору ({0})","tray.splitTool": "Инструмент разрезания (B): щелчок по клипу режет его в этом месте",+ "tray.stopRecording": "Остановить запись","tray.textToSpeech": "Озвучить текст","tray.turnOffPreviewAxis": "Выключить ось предпросмотра (S)","tray.turnOnPreviewAxis": "Включить ось предпросмотра (S)","tray.undo": "Отменить ({0})",- "tray.zoomToFit": "Вместить"+ "tray.zoomToFit": "Вместить",+ "voiceover.added": "Закадровый голос добавлен на таймлайн",+ "voiceover.failed": "Не удалось записать: {0}"}diff --git a/src/crates/concat/locales/tr.json b/src/crates/concat/locales/tr.jsonindex 7ebe6110..92c8658f 100644--- a/src/crates/concat/locales/tr.json+++ b/src/crates/concat/locales/tr.json@@ -999,12 +999,16 @@"tray.panTool": "Pan tool (H)","tray.playerFollowsResizePlayhead": "Oynatıcı kırpmayı izler: oynatma kafası kırptığınız kenarla birlikte hareket eder","tray.previewAxisOptions": "Önizleme ekseni seçenekleri",+ "tray.recordVoiceover": "Seslendirme kaydet","tray.redo": "Yinele ({0})","tray.splitAtPlayhead": "Playhead konumunda böl ({0})","tray.splitTool": "Kesme aracı (B): bir klibe tıklayınca orada keser",+ "tray.stopRecording": "Kaydı durdur","tray.textToSpeech": "Metinden konuşmaya","tray.turnOffPreviewAxis": "Önizleme eksenini kapat (S)","tray.turnOnPreviewAxis": "Önizleme eksenini aç (S)","tray.undo": "Geri al ({0})",- "tray.zoomToFit": "Sığdır"+ "tray.zoomToFit": "Sığdır",+ "voiceover.added": "Seslendirme zaman çizelgesine eklendi",+ "voiceover.failed": "Kayıt yapılamadı: {0}"}diff --git a/src/crates/concat/locales/zh-Hans.json b/src/crates/concat/locales/zh-Hans.jsonindex 6ae69747..e93dea05 100644--- a/src/crates/concat/locales/zh-Hans.json+++ b/src/crates/concat/locales/zh-Hans.json@@ -999,12 +999,16 @@"tray.panTool": "平移工具 (H)","tray.playerFollowsResizePlayhead": "播放器跟随修剪:播放头随你修剪的边缘移动","tray.previewAxisOptions": "预览坐标轴选项",+ "tray.recordVoiceover": "录制旁白","tray.redo": "重做 ({0})","tray.splitAtPlayhead": "在播放头处分割({0})","tray.splitTool": "分割工具(B):点击片段即在该处切开",+ "tray.stopRecording": "停止录制","tray.textToSpeech": "文字转语音","tray.turnOffPreviewAxis": "关闭预览坐标轴 (S)","tray.turnOnPreviewAxis": "打开预览坐标轴 (S)","tray.undo": "撤销 ({0})",- "tray.zoomToFit": "缩放至适合"+ "tray.zoomToFit": "缩放至适合",+ "voiceover.added": "旁白已添加到时间线",+ "voiceover.failed": "无法录制:{0}"}diff --git a/src/crates/concat/locales/zh-TW.json b/src/crates/concat/locales/zh-TW.jsonindex cb84db54..6dfa818f 100644--- a/src/crates/concat/locales/zh-TW.json+++ b/src/crates/concat/locales/zh-TW.json@@ -999,12 +999,16 @@"tray.panTool": "平移工具 (H)","tray.playerFollowsResizePlayhead": "播放器跟隨修剪:播放磁頭隨你修剪的邊緣移動","tray.previewAxisOptions": "預覽座標軸選項",+ "tray.recordVoiceover": "錄製旁白","tray.redo": "重做 ({0})","tray.splitAtPlayhead": "在播放磁頭處分割({0})","tray.splitTool": "分割工具(B):點擊片段即在該處切開",+ "tray.stopRecording": "停止錄製","tray.textToSpeech": "文字轉語音","tray.turnOffPreviewAxis": "關閉預覽座標軸 (S)","tray.turnOnPreviewAxis": "打開預覽座標軸 (S)","tray.undo": "復原 ({0})",- "tray.zoomToFit": "縮放至符合大小"+ "tray.zoomToFit": "縮放至符合大小",+ "voiceover.added": "旁白已加入時間軸",+ "voiceover.failed": "無法錄製:{0}"}diff --git a/src/crates/concat/src/lib.rs b/src/crates/concat/src/lib.rsindex 8c0abd09..99390950 100644--- a/src/crates/concat/src/lib.rs+++ b/src/crates/concat/src/lib.rs@@ -1484,6 +1484,11 @@ pub fn run() -> Result<(), slint::PlatformError> {editor.on_captions(on_window!(|state| {state.handle(Msg::Captions(CaptionsMsg::Open));}));+ editor.on_record_voiceover(on_window!(|state| {+ state.handle(Msg::Voiceover(+ crate::panes::voiceover::VoiceoverMsg::Toggle,+ ));+ }));editor.on_speak(on_window!(|state| {state.handle(Msg::Speech(SpeechMsg::Open));}));diff --git a/src/crates/concat/src/panes/mod.rs b/src/crates/concat/src/panes/mod.rsindex 13d16385..caf71dd2 100644--- a/src/crates/concat/src/panes/mod.rs+++ b/src/crates/concat/src/panes/mod.rs@@ -24,6 +24,7 @@ pub mod settings;pub mod speech;pub mod start;pub mod timeline;+pub mod voiceover;/// One thing that happened, to one pane.#[derive(Debug)]@@ -48,6 +49,8 @@ pub enum Msg {Monitor(monitor::MonitorMsg),/// To the timeline's view.Timeline(timeline::TimelineMsg),+ /// To the voiceover take.+ Voiceover(voiceover::VoiceoverMsg),}/// What a message says in the log: the activity trail of what the persondiff --git a/src/crates/concat/src/panes/voiceover.rs b/src/crates/concat/src/panes/voiceover.rsnew file mode 100644index 00000000..f540ebbf--- /dev/null+++ b/src/crates/concat/src/panes/voiceover.rs@@ -0,0 +1,184 @@+// SPDX-License-Identifier: AGPL-3.0-or-later+// SPDX-FileCopyrightText: 2026 Jareer and Concat contributors++//! The voiceover: words recorded from the microphone over the picture,+//! and laid on the timeline where they were spoken.+//!+//! The tray's button starts a take at the playhead: the picture rolls so+//! the words can follow it, the timeline's own sound held silent so the+//! speakers do not bleed into the microphone, and a meter beside the button+//! shows the level. The same button stops it. The file goes into the+//! project's audio folder and onto the lowest free lane, at the playhead+//! less nothing and plus the moment the microphone actually began.++use std::time::Instant;++use concat_host::media;+use concat_host::record::{self, Recorder};+use concat_project::Command;++use crate::host::spawn_in_project;+use crate::i18n::{t, tf};+use crate::panes::Msg;+use crate::studio::Studio;+use crate::ui::Editor;+use slint::ComponentHandle;++/// Everything that can happen to a take.+pub enum VoiceoverMsg {+ /// The tray's button: start a take, or stop the one running.+ Toggle,+ /// The take is written and probed: onto the timeline with it.+ Finished(Box<Result<media::MediaSummary, String>>),+}++impl std::fmt::Debug for VoiceoverMsg {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ match self {+ Self::Toggle => write!(f, "Toggle"),+ Self::Finished(result) => match result.as_ref() {+ Ok(summary) => write!(f, "Finished({})", summary.path),+ Err(error) => write!(f, "Finished(error {error:?})"),+ },+ }+ }+}++/// The take in progress, if one is.+#[derive(Default)]+pub struct VoiceoverPane {+ recorder: Option<Recorder>,+ /// Where the take began on the timeline.+ playhead: f64,+ /// When the picture started rolling under it.+ rolled: Option<Instant>,+ /// Where the take lands, worked out when it stopped.+ landing: f64,+ /// Feeds the meter while a take runs.+ meter: Option<slint::Timer>,+}++impl VoiceoverPane {+ /// Whether a take is running: the button reads Stop, the meter shows.+ pub fn recording(&self) -> bool {+ self.recorder.is_some()+ }++ /// Applies one message.+ pub fn update(&mut self, msg: VoiceoverMsg, studio: &mut Studio) {+ match msg {+ VoiceoverMsg::Toggle if self.recorder.is_some() => self.stop(studio),+ VoiceoverMsg::Toggle => self.start(studio),+ VoiceoverMsg::Finished(result) => match *result {+ Ok(summary) => {+ // The user's own media, like an import: shelved under+ // Audio, not under Generated.+ let created = studio.apply(Command::AddMedia {+ item: summary.to_new_media(),+ });+ let media_id = created.or_else(|| {+ studio+ .project()+ .media+ .iter()+ .find(|item| item.path == summary.path)+ .map(|item| item.id.clone())+ });+ if let Some(media_id) = media_id {+ studio.apply(Command::AddClipAtFirstFree {+ media_id,+ start: self.landing,+ });+ studio.notify(&t("voiceover.added"), false);+ }+ }+ Err(error) => studio.notify(&tf("voiceover.failed", &[&error]), true),+ },+ }+ }++ /// Opens the microphone and rolls the picture from the playhead.+ fn start(&mut self, studio: &mut Studio) {+ let Some(project) = studio+ .session+ .as_ref()+ .map(|session| std::path::PathBuf::from(session.path()))+ else {+ return;+ };+ let stamp = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|since| since.as_millis())+ .unwrap_or_default();+ let path = project.join("audio").join(format!("voiceover-{stamp}.wav"));+ let recorder = match Recorder::start(path) {+ Ok(recorder) => recorder,+ Err(error) => {+ studio.notify(&tf("voiceover.failed", &[&error]), true);+ return;+ }+ };+ log::info!("voiceover: recording from {:.3}s", studio.playhead);+ self.recorder = Some(recorder);+ self.playhead = f64::from(studio.playhead.max(0.0));+ // The picture rolls under the words, without its sound. At the end+ // of the cut there is nothing to roll, and the take just records.+ studio.host.playback.set_muted(true);+ if !studio.playing && studio.playhead < studio.duration() {+ studio.play_toggle();+ }+ self.rolled = Some(Instant::now());+ self.meter = Some(meter());+ }++ /// Stops the take and the picture, and sends the file to be probed.+ fn stop(&mut self, studio: &mut Studio) {+ self.meter = None;+ let Some(recorder) = self.recorder.take() else {+ return;+ };+ if studio.playing {+ studio.pause();+ }+ studio.host.playback.set_muted(false);+ let take = recorder.stop();+ let rolled = self.rolled.take().unwrap_or_else(Instant::now);+ match take {+ Ok(take) => {+ log::info!("voiceover: {:.2}s to {}", take.seconds, take.path.display());+ self.landing = record::landing(self.playhead, rolled, take.first);+ spawn_in_project(+ move || media::probe(&take.path.to_string_lossy()),+ |studio, _, _, result| {+ studio.handle(Msg::Voiceover(VoiceoverMsg::Finished(Box::new(result))));+ },+ );+ }+ Err(error) => studio.notify(&tf("voiceover.failed", &[&error]), true),+ }+ }+}++/// A timer that shows the take's level on the tray's meter thirty times a+/// second, straight onto the one property, with no publish around it.+fn meter() -> slint::Timer {+ let timer = slint::Timer::default();+ let mut shown = 0.0f32;+ timer.start(+ slint::TimerMode::Repeated,+ std::time::Duration::from_millis(33),+ move || {+ crate::host::Shell::with(|shell, app| {+ let studio = shell.studio.borrow();+ let Some(recorder) = studio.voiceover.recorder.as_ref() else {+ return;+ };+ // Up at once, down gently: a meter that falls as fast as+ // it rises flickers.+ shown = recorder.level().max(shown * 0.85);+ app.global::<Editor>().set_record_level(shown);+ });+ },+ );+ timer+}diff --git a/src/crates/concat/src/studio.rs b/src/crates/concat/src/studio.rsindex 2786afed..4a35c479 100644--- a/src/crates/concat/src/studio.rs+++ b/src/crates/concat/src/studio.rs@@ -893,6 +893,8 @@ pub struct Studio {pub project_sheet: crate::panes::project::ProjectPane,pub captions: crate::panes::captions::CaptionsPane,pub speech: crate::panes::speech::SpeechPane,+ /// The voiceover take, while one runs.+ pub voiceover: crate::panes::voiceover::VoiceoverPane,/// Every speaker the voice engine offers, in its own order./// The looks the Text page offers; see `presets`.pub text_presets: Vec<TextPreset>,@@ -1991,6 +1993,7 @@ impl Studio {project_sheet: crate::panes::project::ProjectPane::default(),captions: crate::panes::captions::CaptionsPane::default(),speech: crate::panes::speech::SpeechPane::default(),+ voiceover: crate::panes::voiceover::VoiceoverPane::default(),text_presets,installed_fonts: presets::installed_fonts(&host.dirs),system_fonts: Vec::new(),@@ -7023,6 +7026,10 @@ impl Studio {self.captions.progress = 0.0;self.speech.running = false;self.speech.progress = 0.0;+ // A take running as the project closes stops, keeping its file;+ // the next project's speakers are not left silent.+ self.voiceover = Default::default();+ self.host.playback.set_muted(false);self.echo = None;self.dirty = false;self.selection.clear();@@ -7101,6 +7108,11 @@ impl Studio {pane.update(msg, self);self.speech = pane;}+ crate::panes::Msg::Voiceover(msg) => {+ let mut pane = std::mem::take(&mut self.voiceover);+ pane.update(msg, self);+ self.voiceover = pane;+ }crate::panes::Msg::Relink(msg) => {let mut pane = std::mem::take(&mut self.relink);pane.update(msg, self);@@ -9210,6 +9222,7 @@ impl Studio {self.speech.sample_detail_rows(self),);app.set_speech(self.speech.data(self));+ editor.set_recording(self.voiceover.recording());let bar = self.menu_bar();app.set_app_menu_height(Self::menu_height(&bar));diff --git a/src/crates/concat/ui/editor.slint b/src/crates/concat/ui/editor.slintindex 388c728d..3c4b0b87 100644--- a/src/crates/concat/ui/editor.slint+++ b/src/crates/concat/ui/editor.slint@@ -356,6 +356,12 @@ export global Editor {/// of the clip's own menu - see `clip-context`.callback captions();callback speak();+ /// The tray's record button: starts a voiceover take, or stops it.+ callback record-voiceover();+ /// A voiceover take is running.+ in-out property <bool> recording;+ /// The take's level, `0..1`, for the meter beside the button.+ in-out property <float> record-level;callback add-track(bottom: bool);callback zoom-to-fit(width: length);callback zoom(factor: float, anchor-seconds: float);diff --git a/src/crates/concat/ui/icons.slint b/src/crates/concat/ui/icons.slintindex 9ebd303c..37f756f1 100644--- a/src/crates/concat/ui/icons.slint+++ b/src/crates/concat/ui/icons.slint@@ -118,6 +118,10 @@ export enum Glyph {waveform,filter,eye-off,+ /// a microphone: the tray's voiceover+ mic,+ /// a square: stop, as on any recorder+ stop,volume,volume-off,unlock,@@ -388,6 +392,19 @@ export component Icon inherits Rectangle {+ " 0 0 0 8.268 8.268c.344-.215.825-.004.803.401";}+ // lucide/mic+ if root.glyph == Glyph.mic: Stroked {+ size: root.size; tint: root.tint; weight: root.weight;+ commands: "M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3z"+ + " M19 10v2a7 7 0 0 1-14 0v-2 M12 19v3";+ }++ // lucide/square+ if root.glyph == Glyph.stop: Stroked {+ size: root.size; tint: root.tint; weight: root.weight;+ commands: "M5 3h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z";+ }+// lucide/volume-2if root.glyph == Glyph.volume: Stroked {size: root.size; tint: root.tint; weight: root.weight;diff --git a/src/crates/concat/ui/timeline/tray.slint b/src/crates/concat/ui/timeline/tray.slintindex 95b8d3f5..ffdbf472 100644--- a/src/crates/concat/ui/timeline/tray.slint+++ b/src/crates/concat/ui/timeline/tray.slint@@ -5,6 +5,7 @@ import { I18n } from "../i18n.slint";import { Theme } from "../theme/theme.slint";import { Glyph, Icon } from "../icons.slint";import { IconButton } from "../primitives/panel.slint";+import { LevelMeter } from "../primitives/level-meter.slint";import { TimelineTool } from "model.slint";// The timeline's tool tray.@@ -214,6 +215,10 @@ export component TimelineTray inherits Rectangle {/// freeze. Rust's answers, like the two above.in property <bool> picture-selected;in property <bool> freezable;+ /// A voiceover take is running: the record button reads Stop, in red,+ /// with the take's level beside it.+ in property <bool> recording;+ in property <float> record-level;callback tool-changed(tool: TimelineTool);callback snap-changed(snap: bool);@@ -235,6 +240,7 @@ export component TimelineTray inherits Rectangle {callback delete-selected();callback captions();callback speak();+ callback record-voiceover();/// Add a lane: on top of the stack, or with `bottom` under it.callback add-track(bottom: bool);callback fit();@@ -413,6 +419,20 @@ export component TimelineTray inherits Rectangle {icon-size: 16px;clicked => { root.speak(); }}+ // A voiceover: the picture rolls from the playhead and the words go+ // onto a lane under it. The same button stops the take.+ TrayButton {+ glyph: root.recording ? Glyph.stop : Glyph.mic;+ label: root.recording ? I18n.t("tray.stopRecording") : I18n.t("tray.recordVoiceover");+ icon-size: 16px;+ idle: root.recording ? Theme.danger : Theme.fg;+ clicked => { root.record-voiceover(); }+ }+ if root.recording: LevelMeter {+ width: 56px;+ horizontal-stretch: 0;+ value: root.record-level;+ }Rectangle { horizontal-stretch: 1; }diff --git a/src/crates/concat/ui/workspace/seat.slint b/src/crates/concat/ui/workspace/seat.slintindex dd904fc9..817019ae 100644--- a/src/crates/concat/ui/workspace/seat.slint+++ b/src/crates/concat/ui/workspace/seat.slint@@ -362,6 +362,8 @@ export component Seat inherits Rectangle {title-selected: Editor.title-selected;picture-selected: Editor.picture-selected;freezable: Editor.freezable;+ recording: Editor.recording;+ record-level: Editor.record-level;reversible: Editor.reversible;playhead: Editor.playhead;frame-rate: Editor.frame-rate;@@ -391,6 +393,7 @@ export component Seat inherits Rectangle {delete-selected => { Editor.delete-selected(); }captions => { Editor.captions(); }speak => { Editor.speak(); }+ record-voiceover => { Editor.record-voiceover(); }add-track(bottom) => { Editor.add-track(bottom); }zoom-to-fit(width) => { Editor.zoom-to-fit(width); }zoom(factor, anchor) => { Editor.zoom(factor, anchor); }diff --git a/src/crates/concat/ui/workspace/timeline-pane.slint b/src/crates/concat/ui/workspace/timeline-pane.slintindex 75c317b9..8e27b92f 100644--- a/src/crates/concat/ui/workspace/timeline-pane.slint+++ b/src/crates/concat/ui/workspace/timeline-pane.slint@@ -51,6 +51,8 @@ export component TimelinePane inherits Rectangle {in property <bool> title-selected;in property <bool> picture-selected;in property <bool> freezable;+ in property <bool> recording;+ in property <float> record-level;in property <bool> reversible;callback tool-changed(tool: TimelineTool);@@ -76,6 +78,7 @@ export component TimelinePane inherits Rectangle {callback delete-selected();callback captions();callback speak();+ callback record-voiceover();callback add-track(bottom: bool);callback zoom-to-fit(width: length);callback zoom(factor: float, anchor-seconds: float);@@ -319,6 +322,8 @@ export component TimelinePane inherits Rectangle {title-selected: root.title-selected;picture-selected: root.picture-selected;freezable: root.freezable;+ recording: root.recording;+ record-level: root.record-level;tool-changed(tool) => { root.tool-changed(tool); }snap-changed(snap) => { root.snap-changed(snap); }@@ -348,6 +353,7 @@ export component TimelinePane inherits Rectangle {delete-selected => { root.delete-selected(); }captions => { root.captions(); }speak => { root.speak(); }+ record-voiceover => { root.record-voiceover(); }add-track(bottom) => { root.add-track(bottom); }fit => { root.zoom-to-fit(lanes.width); }// No anchor from a button: a wheel zooms about the pointer and a