Skip to content

The truly free, open-source, local-first, cross-platform CapCut replacement. Scriptable through a JSON-RPC API & MCP.

feat(voiceover): Record Voiceover opens a floating panel with pause, retake, a meter and a teleprompter (#213)

Jareer1b0f8761b873
diff --git a/src/crates/concat-android/Cargo.toml b/src/crates/concat-android/Cargo.toml
index 8cfc3a26..4e6c0e77 100644
--- a/src/crates/concat-android/Cargo.toml
+++ b/src/crates/concat-android/Cargo.toml
@@ -57,6 +57,11 @@ target_sdk_version = 35
[[package.metadata.android.uses_permission]]
name = "android.permission.INTERNET"
+# The voiceover. A permission the person grants while the app runs, so
+# the manifest only makes it askable; ConcatFiles.askMicrophone asks.
+[[package.metadata.android.uses_permission]]
+name = "android.permission.RECORD_AUDIO"
+
[package.metadata.android.application]
label = "Concat"
icon = "@mipmap/ic_launcher"
diff --git a/src/crates/concat-android/java/ConcatFiles.java b/src/crates/concat-android/java/ConcatFiles.java
index 08be186e..573906e3 100644
--- a/src/crates/concat-android/java/ConcatFiles.java
+++ b/src/crates/concat-android/java/ConcatFiles.java
@@ -3,12 +3,14 @@
package app.concat.editor;
+import android.Manifest;
import android.app.Activity;
import android.app.Fragment;
import android.content.ClipData;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
+import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
@@ -47,11 +49,15 @@ import java.util.List;
* {@link #publishVideo} moves it into the phone's Movies through the
* media store, where the gallery and every file manager show it.
*
+ * And the microphone, for a voiceover: a permission granted while the
+ * app runs, asked for through the activity by {@link #askMicrophone}.
+ *
* Compiled by build.rs with the SDK's javac and d8, and loaded at run time
* from the dex inside the binary; see src/lib.rs.
*/
public class ConcatFiles extends Fragment {
private static final int REQUEST_PICK = 0xC0C4;
+ private static final int REQUEST_MICROPHONE = 0xC0C5;
private static final String TAG = "concat-files";
/**
@@ -135,6 +141,30 @@ public class ConcatFiles extends Fragment {
return new String[] {folder + "/" + displayName(activity, uri), null};
}
+ /**
+ * Whether the app may record from the microphone. When it may not yet,
+ * the system's question is put up and false comes back at once; the
+ * answer is read the next time this is asked, which is the voiceover
+ * panel's Try again. From any thread.
+ */
+ public static boolean askMicrophone(final Activity activity) {
+ if (Build.VERSION.SDK_INT < 23) {
+ return true;
+ }
+ if (activity.checkSelfPermission(Manifest.permission.RECORD_AUDIO)
+ == PackageManager.PERMISSION_GRANTED) {
+ return true;
+ }
+ activity.runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ activity.requestPermissions(
+ new String[] {Manifest.permission.RECORD_AUDIO}, REQUEST_MICROPHONE);
+ }
+ });
+ return false;
+ }
+
/** Registered from Rust: the picked files' paths, or none. */
public static native void filesPicked(String[] paths);
diff --git a/src/crates/concat-android/src/lib.rs b/src/crates/concat-android/src/lib.rs
index 18bd5742..a5edc6d1 100644
--- a/src/crates/concat-android/src/lib.rs
+++ b/src/crates/concat-android/src/lib.rs
@@ -377,6 +377,40 @@ mod publisher {
}
}
+/// The microphone, for a voiceover.
+///
+/// Android grants it while the app runs, not at install, and an input
+/// stream opened without it hears only silence; so the voiceover panel
+/// asks here before it opens one, and the Java puts the system's question
+/// up when the answer is not yet yes.
+#[cfg(target_os = "android")]
+mod microphone {
+ use jni::{jni_sig, jni_str};
+ use slint::android::AndroidApp;
+
+ /// Hands the window's crate the way to ask.
+ pub fn install(app: &AndroidApp) {
+ let app = app.clone();
+ concat::install_microphone_access(Box::new(move || {
+ super::java::with_class(&app, |env, activity, class| {
+ env.call_static_method(
+ class,
+ jni_str!("askMicrophone"),
+ jni_sig!("(Landroid/app/Activity;)Z"),
+ &[activity.into()],
+ )?
+ .z()
+ })
+ .unwrap_or_else(|error| {
+ // Not knowing is not a no: the device is opened, and its
+ // own error, or its silence, says the rest.
+ log::warn!("could not ask for the microphone: {error}");
+ true
+ })
+ }));
+ }
+}
+
/// Called by the activity's native glue; the name is the contract.
#[cfg(target_os = "android")]
#[unsafe(no_mangle)]
@@ -392,6 +426,7 @@ fn android_main(app: slint::android::AndroidApp) {
// After the backend, which seeds the JavaVM the Java is reached by.
picker::install(&app);
publisher::install(&app);
+ microphone::install(&app);
if let Err(error) = concat::run() {
log::error!("{error}");
}
diff --git a/src/crates/concat-host/src/record.rs b/src/crates/concat-host/src/record.rs
index 209d86d8..ca552f53 100644
--- a/src/crates/concat-host/src/record.rs
+++ b/src/crates/concat-host/src/record.rs
@@ -4,26 +4,63 @@
//! 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.
+//! The microphone is opened when the voiceover panel opens and held until
+//! it closes, so the meter shows the room before a word is spoken and a
+//! take begins the instant Record is pressed, not after a device has woken
+//! up. One thread owns the input stream from open to close (a cpal stream
+//! may not cross threads) and writes the take. The callback only mixes
+//! each buffer down to mono, measures it for the meter and, while a take is
+//! being written, passes it on as 16-bit samples, so the device is never
+//! kept waiting on the disk. A paused take is the same take with nothing
+//! passed on: the pause is cut out of the file, and the picture, paused
+//! with it, stays in step.
+//!
+//! The file is good on disk as it goes: its header is brought up to date
+//! about once a second, so a take cut short by a crash or a pulled plug is
+//! a WAV that plays up to the last second, not a file nothing opens.
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::atomic::{AtomicBool, AtomicU32, AtomicU64, 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 sample at or past this is a sample the converter could not hold: the
+/// meter's clip light.
+const CLIP: f32 = 0.999;
+
+/// The microphones the system offers, by the names it gives them, the
+/// default first when it says which that is. Empty when there are none or
+/// the system will not list them.
+pub fn microphones() -> Vec<String> {
+ use cpal::traits::{DeviceTrait, HostTrait};
+
+ let host = cpal::default_host();
+ let default = host
+ .default_input_device()
+ .and_then(|device| device.name().ok());
+ let mut names: Vec<String> = host
+ .input_devices()
+ .map(|devices| devices.filter_map(|device| device.name().ok()).collect())
+ .unwrap_or_default();
+ names.dedup();
+ if let Some(default) = default {
+ names.retain(|name| *name != default);
+ names.insert(0, default);
+ }
+ names
+}
+
+/// The microphone, open. Dropping it closes the device, finishing any take
+/// still being written so what was heard is kept.
+pub struct Microphone {
+ shared: Arc<Shared>,
+ events: mpsc::Sender<Event>,
+ thread: Option<std::thread::JoinHandle<()>>,
+ name: String,
+ /// Samples a second, the device's own.
+ rate: u32,
}
/// A finished take.
@@ -31,107 +68,258 @@ pub struct Recorder {
pub struct Take {
/// The WAV file, 16-bit mono at the device's own rate.
pub path: PathBuf,
- /// Its length, in seconds.
+ /// Its length, in seconds: the time spent recording, pauses left out.
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.
+ /// When the microphone heard the take's 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()))?;
+/// What the meter shows: the loudest sample and the average power since it
+/// last looked, both `0..=1`, and whether anything reached the top.
+#[derive(Clone, Copy, Debug, Default, PartialEq)]
+pub struct Level {
+ /// The loudest sample, held to the top of the bar.
+ pub peak: f32,
+ /// The root of the mean square: how loud it sounded, near enough.
+ pub rms: f32,
+ /// A sample reached the converter's limit: the clip light.
+ pub clipped: bool,
+}
+
+/// What the callback, the writer and the window share.
+struct Shared {
+ /// A take is being written: set from begin to end, and clear while it
+ /// is paused.
+ writing: AtomicBool,
+ /// The input gain, linear, as f32 bits.
+ gain: AtomicU32,
+ meter: Mutex<Meter>,
+ /// When the take's first sample was heard. Cleared at begin.
+ first: Mutex<Option<Instant>>,
+ /// Samples in the take so far.
+ written: AtomicU64,
+ /// Anything but digital silence has arrived since the device opened.
+ /// A system that keeps the microphone from an app tends to hand it
+ /// zeros rather than an error, and this is how that is noticed.
+ heard: AtomicBool,
+ /// What went wrong with the device after it opened: unplugged, taken.
+ failed: Mutex<Option<String>>,
+}
+
+impl Shared {
+ fn new() -> Self {
+ Shared {
+ writing: AtomicBool::new(false),
+ gain: AtomicU32::new(1.0f32.to_bits()),
+ meter: Mutex::new(Meter::default()),
+ first: Mutex::new(None),
+ written: AtomicU64::new(0),
+ heard: AtomicBool::new(false),
+ failed: Mutex::new(None),
+ }
+ }
+
+ /// One buffer from the device, already mono and gained: measured for
+ /// the meter always, and handed back as 16-bit samples for the take
+ /// only while one is being written. `heard` is when the buffer's first
+ /// sample reached the microphone.
+ fn capture(&self, mono: &[f32], heard: Option<Instant>) -> Option<Vec<i16>> {
+ // The meter is the window's to read; a buffer that finds it busy
+ // goes unmeasured rather than keeping the device waiting.
+ if let Ok(mut meter) = self.meter.try_lock() {
+ meter.add(mono);
}
- let stop = Arc::new(AtomicBool::new(false));
- let level = Arc::new(AtomicU32::new(0));
- let (ready_tx, ready_rx) = mpsc::channel::<Result<(), String>>();
+ if !self.heard.load(Ordering::Relaxed) && mono.iter().any(|sample| *sample != 0.0) {
+ self.heard.store(true, Ordering::Relaxed);
+ }
+ if !self.writing.load(Ordering::Relaxed) {
+ return None;
+ }
+ if let Ok(mut first) = self.first.try_lock()
+ && first.is_none()
+ {
+ *first = heard;
+ }
+ Some(to_pcm(mono))
+ }
+}
+
+/// What the writer thread is told.
+enum Event {
+ /// Samples for the take.
+ Samples(Vec<i16>),
+ /// Start a take in this file.
+ Begin(PathBuf, mpsc::Sender<Result<(), String>>),
+ /// Finish the take.
+ End(mpsc::Sender<Result<Take, String>>),
+ /// Close the device.
+ Close,
+}
+
+impl Microphone {
+ /// Opens the microphone the system calls `name`, or its default one
+ /// when there is no such microphone or no name is given. 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 open(name: Option<&str>) -> Result<Microphone, String> {
+ let shared = Arc::new(Shared::new());
+ let (events, inbox) = mpsc::channel::<Event>();
+ let (ready_tx, ready_rx) = mpsc::channel::<Result<(String, u32), String>>();
+ let wanted = name.map(str::to_owned);
let thread = {
- let stop = Arc::clone(&stop);
- let level = Arc::clone(&level);
+ let shared = Arc::clone(&shared);
+ let events = events.clone();
std::thread::Builder::new()
.name("audio-input".into())
- .spawn(move || record(&path, &stop, &level, &ready_tx))
+ .spawn(move || run(wanted.as_deref(), &shared, events, &inbox, &ready_tx))
.map_err(|error| format!("could not spawn the recording thread: {error}"))?
};
match ready_rx.recv() {
- Ok(Ok(())) => Ok(Recorder {
- stop,
- level,
+ Ok(Ok((name, rate))) => Ok(Microphone {
+ shared,
+ events,
thread: Some(thread),
+ name,
+ rate,
}),
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(),
- }),
+ Err(_) => {
+ let _ = thread.join();
+ Err("the recording thread stopped before the microphone opened".to_owned())
+ }
+ }
+ }
+
+ /// The name of the microphone that opened.
+ pub fn name(&self) -> &str {
+ &self.name
+ }
+
+ /// Starts a take in a new file at `path`, written from the next buffer
+ /// on.
+ pub fn begin(&self, path: PathBuf) -> Result<(), String> {
+ if let Some(folder) = path.parent() {
+ std::fs::create_dir_all(folder)
+ .map_err(|error| format!("could not make {}: {error}", folder.display()))?;
}
+ self.shared.writing.store(false, Ordering::Relaxed);
+ *lock(&self.shared.first) = None;
+ self.shared.written.store(0, Ordering::Relaxed);
+ let (reply, answer) = mpsc::channel();
+ self.events
+ .send(Event::Begin(path, reply))
+ .map_err(|_| "the microphone has closed".to_owned())?;
+ answer
+ .recv()
+ .map_err(|_| "the microphone has closed".to_owned())??;
+ self.shared.writing.store(true, Ordering::Relaxed);
+ Ok(())
+ }
+
+ /// Holds the take: what is heard meanwhile is measured, not kept.
+ pub fn pause(&self) {
+ self.shared.writing.store(false, Ordering::Relaxed);
+ }
+
+ /// Carries the take on from where it was held.
+ pub fn resume(&self) {
+ self.shared.writing.store(true, Ordering::Relaxed);
+ }
+
+ /// Finishes the take and its file.
+ pub fn end(&self) -> Result<Take, String> {
+ self.shared.writing.store(false, Ordering::Relaxed);
+ let (reply, answer) = mpsc::channel();
+ self.events
+ .send(Event::End(reply))
+ .map_err(|_| "the microphone has closed".to_owned())?;
+ answer
+ .recv()
+ .map_err(|_| "the microphone has closed".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))
+ /// What was heard since the last look: the meter's feed.
+ pub fn level(&self) -> Level {
+ lock(&self.shared.meter).take()
}
- /// Stops the take and finishes the file.
- pub fn stop(mut self) -> Result<Take, String> {
- self.finish()
+ /// How long the take is so far, in seconds, pauses left out.
+ pub fn seconds(&self) -> f64 {
+ self.shared.written.load(Ordering::Relaxed) as f64 / f64::from(self.rate.max(1))
}
- 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())?
+ /// Whether anything but silence has come from the device yet.
+ pub fn heard(&self) -> bool {
+ self.shared.heard.load(Ordering::Relaxed)
+ }
+
+ /// The input gain, linear: what every sample is multiplied by before it
+ /// is measured or kept.
+ pub fn set_gain(&self, gain: f32) {
+ self.shared
+ .gain
+ .store(gain.clamp(0.0, 16.0).to_bits(), Ordering::Relaxed);
+ }
+
+ /// What went wrong with the device after it opened, if anything has.
+ pub fn failed(&self) -> Option<String> {
+ lock(&self.shared.failed).clone()
}
}
-impl Drop for Recorder {
+impl Drop for Microphone {
fn drop(&mut self) {
- if self.thread.is_some() {
- let _ = self.finish();
+ let _ = self.events.send(Event::Close);
+ if let Some(thread) = self.thread.take() {
+ let _ = thread.join();
}
}
}
-/// 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> {
+fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
+ mutex
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+}
+
+/// The recording thread: opens the device, says so, and writes takes until
+/// told to close; a take still open then is finished, not lost.
+fn run(
+ name: Option<&str>,
+ shared: &Arc<Shared>,
+ events: mpsc::Sender<Event>,
+ inbox: &mpsc::Receiver<Event>,
+ ready: &mpsc::Sender<Result<(String, u32), 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 host = cpal::default_host();
+ let named = name.and_then(|name| {
+ host.input_devices()
+ .ok()?
+ .find(|device| device.name().is_ok_and(|found| found == name))
+ });
+ let device = match named {
+ Some(device) => device,
+ None => 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),
+ cpal::SampleFormat::F32 => input::<f32>(&device, &config, events, shared),
+ cpal::SampleFormat::I16 => input::<i16>(&device, &config, events, shared),
+ cpal::SampleFormat::U16 => input::<u16>(&device, &config, events, shared),
+ cpal::SampleFormat::I32 => input::<i32>(&device, &config, events, shared),
other => Err(format!(
"the microphone records {other:?} samples, which Concat does not read"
)),
@@ -139,61 +327,141 @@ fn record(
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 name = device.name().unwrap_or_default();
+ Ok((stream, config.sample_rate.0, name))
})();
- let (stream, rx, mut writer, first, failed) = match opened {
- Ok(parts) => {
- let _ = ready.send(Ok(()));
- parts
+ let (stream, rate) = match opened {
+ Ok((stream, rate, name)) => {
+ let _ = ready.send(Ok((name, rate)));
+ (stream, rate)
}
Err(error) => {
- let _ = ready.send(Err(error.clone()));
- return Err(error);
+ let _ = ready.send(Err(error));
+ return;
}
};
- while !stop.load(Ordering::Relaxed) {
- match rx.recv_timeout(Duration::from_millis(20)) {
- Ok(samples) => writer.write(&samples)?,
+ let mut takes = Takes::new(rate, Arc::clone(shared));
+ loop {
+ match inbox.recv_timeout(Duration::from_millis(250)) {
+ Ok(Event::Close) | Err(mpsc::RecvTimeoutError::Disconnected) => break,
+ Ok(event) => takes.handle(event),
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.
+ // its way is written, and a take left open is finished.
+ shared.writing.store(false, Ordering::Relaxed);
drop(stream);
- while let Ok(samples) = rx.try_recv() {
- writer.write(&samples)?;
+ while let Ok(event) = inbox.try_recv() {
+ if let Event::Samples(_) = event {
+ takes.handle(event);
+ }
+ }
+ if let Some(Ok(take)) = takes.finish() {
+ log::info!(
+ "voiceover: closed mid-take, kept {:.2}s in {}",
+ take.seconds,
+ take.path.display()
+ );
+ }
+}
+
+/// The writer's side of the takes: one file at a time, written as samples
+/// arrive and finished on End. Apart from the device, so a take can be
+/// assembled without one.
+struct Takes {
+ rate: u32,
+ shared: Arc<Shared>,
+ open: Option<(PathBuf, WavWriter)>,
+ /// Why the open take's file stopped being written, if it did.
+ broken: Option<String>,
+}
+
+impl Takes {
+ fn new(rate: u32, shared: Arc<Shared>) -> Self {
+ Takes {
+ rate,
+ shared,
+ open: None,
+ broken: None,
+ }
+ }
+
+ fn handle(&mut self, event: Event) {
+ match event {
+ Event::Samples(samples) => {
+ let Some((_, writer)) = self.open.as_mut() else {
+ return;
+ };
+ if self.broken.is_some() {
+ return;
+ }
+ match writer.write(&samples) {
+ Ok(()) => {
+ self.shared.written.store(writer.samples, Ordering::Relaxed);
+ }
+ Err(error) => {
+ log::warn!("voiceover: {error}");
+ self.broken = Some(error);
+ }
+ }
+ }
+ Event::Begin(path, reply) => {
+ // A take still open is finished first: two files are never
+ // written at once.
+ let _ = self.finish();
+ let result = WavWriter::create(&path, self.rate).map(|writer| {
+ self.open = Some((path, writer));
+ self.broken = None;
+ });
+ let _ = reply.send(result);
+ }
+ Event::End(reply) => {
+ let result = self
+ .finish()
+ .unwrap_or_else(|| Err("no take was being recorded".to_owned()));
+ let _ = reply.send(result);
+ }
+ Event::Close => {}
+ }
+ }
+
+ /// Finishes the open take, if there is one.
+ fn finish(&mut self) -> Option<Result<Take, String>> {
+ let (path, writer) = self.open.take()?;
+ let finished = writer.finish();
+ if let Some(error) = self.broken.take() {
+ return Some(Err(error));
+ }
+ let seconds = match finished {
+ Ok(seconds) => seconds,
+ Err(error) => return Some(Err(error)),
+ };
+ let first = *lock(&self.shared.first);
+ if first.is_none() {
+ let why = lock(&self.shared.failed).clone();
+ return Some(Err(
+ why.unwrap_or_else(|| "the microphone sent no sound".to_owned())
+ ));
+ }
+ Some(Ok(Take {
+ path,
+ seconds,
+ first,
+ }))
}
- 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.
+/// at the input gain, measured, and sent to the writer while a take is
+/// being written.
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>>>,
+ events: mpsc::Sender<Event>,
+ shared: &Arc<Shared>,
) -> Result<cpal::Stream, String>
where
T: cpal::SizedSample,
@@ -202,69 +470,107 @@ where
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);
+ let shared = Arc::clone(shared);
+ let failed = Arc::clone(&shared);
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 stamp = info.timestamp();
+ let latency = stamp
+ .callback
+ .duration_since(&stamp.capture)
+ .unwrap_or_default();
+ let heard = Instant::now().checked_sub(latency);
+ let gain = f32::from_bits(shared.gain.load(Ordering::Relaxed));
+ let mono = mix_down(data.iter().map(|s| s.to_sample::<f32>()), channels, gain);
+ if let Some(samples) = shared.capture(&mono, heard) {
+ let _ = events.send(Event::Samples(samples));
}
- 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}"));
- }
+ lock(&failed.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) {
+/// Interleaved samples of `channels` channels as mono - the mean of each
+/// frame's channels - times `gain`. A trailing part frame is dropped.
+/// Unclamped: the meter wants to see a sample that went over.
+fn mix_down(samples: impl Iterator<Item = f32>, channels: usize, gain: f32) -> Vec<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);
+ mono.push(sum / channels as f32 * gain);
sum = 0.0;
count = 0;
}
}
- (mono, peak)
+ mono
+}
+
+/// Mono samples as 16-bit, held to the range.
+fn to_pcm(mono: &[f32]) -> Vec<i16> {
+ mono.iter()
+ .map(|sample| (sample.clamp(-1.0, 1.0) * f32::from(i16::MAX)).round() as i16)
+ .collect()
+}
+
+/// The meter's arithmetic: what has been heard since it was last read.
+#[derive(Default)]
+struct Meter {
+ peak: f32,
+ squares: f64,
+ count: u64,
+ clipped: bool,
+}
+
+impl Meter {
+ fn add(&mut self, mono: &[f32]) {
+ for sample in mono {
+ let size = sample.abs();
+ self.peak = self.peak.max(size);
+ self.clipped |= size >= CLIP;
+ self.squares += f64::from(*sample) * f64::from(*sample);
+ }
+ self.count += mono.len() as u64;
+ }
+
+ /// The reading, and a fresh start for the next one.
+ fn take(&mut self) -> Level {
+ let rms = if self.count == 0 {
+ 0.0
+ } else {
+ (self.squares / self.count as f64).sqrt() as f32
+ };
+ let level = Level {
+ peak: self.peak.min(1.0),
+ rms: rms.min(1.0),
+ clipped: self.clipped,
+ };
+ *self = Meter::default();
+ level
+ }
}
-/// A 16-bit mono WAV written as it goes: the header up front with its sizes
-/// left open, filled in by [`WavWriter::finish`].
+/// A 16-bit mono WAV written as it goes: the header up front, its sizes
+/// brought up to date every second or so and for good by
+/// [`WavWriter::finish`].
struct WavWriter {
out: BufWriter<File>,
rate: u32,
samples: u64,
+ /// Samples written when the header was last brought up to date.
+ noted: u64,
}
impl WavWriter {
@@ -275,6 +581,7 @@ impl WavWriter {
out: BufWriter::new(file),
rate,
samples: 0,
+ noted: 0,
};
writer.header(0)?;
Ok(writer)
@@ -305,20 +612,40 @@ impl WavWriter {
.map_err(|error| format!("could not write the recording: {error}"))?;
}
self.samples += samples.len() as u64;
+ if self.samples - self.noted >= u64::from(self.rate) {
+ self.checkpoint()?;
+ }
+ Ok(())
+ }
+
+ /// The sizes the header should say for what is written so far. 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.
+ fn data_bytes(&self) -> u32 {
+ u32::try_from(self.samples * 2).unwrap_or(u32::MAX - 36)
+ }
+
+ /// Writes what is buffered and brings the header's two sizes up to
+ /// date, then carries on at the end: the file on disk is a whole WAV
+ /// from here on, whatever happens to the process.
+ fn checkpoint(&mut self) -> Result<(), String> {
+ let io = |error: std::io::Error| format!("could not write the recording: {error}");
+ let data_bytes = self.data_bytes();
+ self.out.seek(SeekFrom::Start(4)).map_err(io)?;
+ self.out
+ .write_all(&(36 + data_bytes).to_le_bytes())
+ .map_err(io)?;
+ self.out.seek(SeekFrom::Start(40)).map_err(io)?;
+ self.out.write_all(&data_bytes.to_le_bytes()).map_err(io)?;
+ self.out.seek(SeekFrom::End(0)).map_err(io)?;
+ self.out.flush().map_err(io)?;
+ self.noted = self.samples;
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()
+ self.checkpoint()
.map_err(|error| format!("could not finish the recording: {error}"))?;
Ok(self.samples as f64 / f64::from(self.rate))
}
@@ -337,21 +664,70 @@ pub fn landing(playhead: f64, rolled: Instant, first: Option<Instant>) -> f64 {
(playhead + offset).max(0.0)
}
+/// A gain in decibels as the factor samples are multiplied by.
+pub fn gain_of(decibels: f32) -> f32 {
+ 10f32.powf(decibels / 20.0)
+}
+
+/// A level `0..=1` as the meter draws it: decibels from -60 to 0 spread
+/// evenly along the bar, so a voice at a sensible level fills most of it
+/// rather than its first tenth.
+pub fn meter_position(level: f32) -> f32 {
+ if level <= 0.001 {
+ return 0.0;
+ }
+ ((20.0 * level.log10() + 60.0) / 60.0).clamp(0.0, 1.0)
+}
+
#[cfg(test)]
mod tests {
use super::*;
+ fn temp(name: &str) -> PathBuf {
+ std::env::temp_dir().join(format!("concat-record-{name}-{}.wav", std::process::id()))
+ }
+
#[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);
+ fn stereo_mixes_down_to_the_mean_at_the_gain() {
+ let mono = mix_down([0.5, 0.5, -1.0, 0.0, 0.25].into_iter(), 2, 1.0);
// The fifth sample is half a frame and is not written.
- assert_eq!(mono, vec![16384, -16384]);
- assert!((peak - 0.5).abs() < 1e-6);
+ assert_eq!(mono, vec![0.5, -0.5]);
+ assert_eq!(to_pcm(&mono), vec![16384, -16384]);
+ let louder = mix_down([0.25, 0.25].into_iter(), 2, 2.0);
+ assert_eq!(louder, vec![0.5]);
+ // Over the top is held there in the file.
+ assert_eq!(to_pcm(&[1.5, -3.0]), vec![i16::MAX, -i16::MAX]);
+ }
+
+ #[test]
+ fn the_meter_reads_peak_power_and_clipping_then_starts_again() {
+ let mut meter = Meter::default();
+ meter.add(&[0.5, -0.5, 0.5, -0.5]);
+ let level = meter.take();
+ assert!((level.peak - 0.5).abs() < 1e-6);
+ assert!((level.rms - 0.5).abs() < 1e-6);
+ assert!(!level.clipped);
+
+ meter.add(&[0.0, 1.2]);
+ let level = meter.take();
+ assert_eq!(level.peak, 1.0, "held to the top of the bar");
+ assert!(level.clipped);
+ assert_eq!(meter.take(), Level::default(), "read once, then fresh");
+ }
+
+ #[test]
+ fn the_meter_spreads_decibels_along_the_bar() {
+ assert_eq!(meter_position(0.0), 0.0);
+ assert!((meter_position(1.0) - 1.0).abs() < 1e-6);
+ // -20 dB is two thirds of the way along.
+ assert!((meter_position(0.1) - 2.0 / 3.0).abs() < 1e-4);
+ assert!((gain_of(6.0) - 1.995).abs() < 1e-3);
+ assert_eq!(gain_of(0.0), 1.0);
}
#[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 path = temp("finished");
let mut writer = WavWriter::create(&path, 48_000).expect("creates");
writer.write(&[1, -1, 2, -2]).expect("writes");
writer.write(&[3]).expect("writes");
@@ -370,6 +746,91 @@ mod tests {
assert!((seconds - 5.0 / 48_000.0).abs() < 1e-12);
}
+ #[test]
+ fn a_wav_still_being_written_is_whole_on_disk_every_second() {
+ let path = temp("checkpoint");
+ let mut writer = WavWriter::create(&path, 4).expect("creates");
+ // Under a second at 4 Hz: nothing noted yet.
+ writer.write(&[1, 2, 3]).expect("writes");
+ // The fourth sample is a second's worth; the header catches up
+ // without the file being finished, as a crash would leave it.
+ writer.write(&[4, 5]).expect("writes");
+ let bytes = std::fs::read(&path).expect("reads");
+ assert_eq!(bytes.len(), 44 + 10);
+ assert_eq!(u32::from_le_bytes(bytes[4..8].try_into().unwrap()), 36 + 10);
+ assert_eq!(u32::from_le_bytes(bytes[40..44].try_into().unwrap()), 10);
+ // And writing carries on at the end, not over the header.
+ writer.write(&[6]).expect("writes");
+ writer.finish().expect("finishes");
+ let bytes = std::fs::read(&path).expect("reads");
+ let _ = std::fs::remove_file(&path);
+ assert_eq!(bytes.len(), 44 + 12);
+ assert_eq!(i16::from_le_bytes([bytes[54], bytes[55]]), 6);
+ assert_eq!(u32::from_le_bytes(bytes[40..44].try_into().unwrap()), 12);
+ }
+
+ #[test]
+ fn a_paused_take_is_one_file_with_the_pause_cut_out() {
+ let shared = Arc::new(Shared::new());
+ let mut takes = Takes::new(8, Arc::clone(&shared));
+ let path = temp("paused");
+ let (reply, answer) = mpsc::channel();
+ takes.handle(Event::Begin(path.clone(), reply));
+ answer.recv().expect("answered").expect("begins");
+
+ // Before the take is written to, a buffer is only measured.
+ assert_eq!(shared.capture(&[0.9], None), None);
+ shared.writing.store(true, Ordering::Relaxed);
+ let start = Instant::now();
+ let spoken = shared.capture(&[0.5, 0.5], Some(start)).expect("kept");
+ takes.handle(Event::Samples(spoken));
+ // Paused: heard, measured, not kept.
+ shared.writing.store(false, Ordering::Relaxed);
+ assert_eq!(shared.capture(&[0.25, 0.25, 0.25], None), None);
+ // Resumed: the take carries on in the same file, and still began
+ // when its first sample was heard.
+ shared.writing.store(true, Ordering::Relaxed);
+ let later = start + Duration::from_secs(5);
+ let more = shared.capture(&[-0.5], Some(later)).expect("kept");
+ takes.handle(Event::Samples(more));
+ assert_eq!(shared.written.load(Ordering::Relaxed), 3);
+
+ let (reply, answer) = mpsc::channel();
+ takes.handle(Event::End(reply));
+ let take = answer.recv().expect("answered").expect("a take");
+ let bytes = std::fs::read(&path).expect("reads");
+ let _ = std::fs::remove_file(&path);
+ assert_eq!(take.first, Some(start));
+ assert!((take.seconds - 3.0 / 8.0).abs() < 1e-12);
+ assert_eq!(bytes.len(), 44 + 6);
+ let samples: Vec<i16> = bytes[44..]
+ .chunks(2)
+ .map(|pair| i16::from_le_bytes([pair[0], pair[1]]))
+ .collect();
+ assert_eq!(samples, vec![16384, 16384, -16384]);
+ // The pause was still on the meter.
+ assert!((lock(&shared.meter).take().peak - 0.9).abs() < 1e-6);
+ assert!(shared.heard.load(Ordering::Relaxed));
+ }
+
+ #[test]
+ fn a_take_that_heard_nothing_says_so() {
+ let shared = Arc::new(Shared::new());
+ let mut takes = Takes::new(8, Arc::clone(&shared));
+ let path = temp("silent");
+ let (reply, answer) = mpsc::channel();
+ takes.handle(Event::Begin(path.clone(), reply));
+ answer.recv().expect("answered").expect("begins");
+ let (reply, answer) = mpsc::channel();
+ takes.handle(Event::End(reply));
+ let result = answer.recv().expect("answered");
+ let _ = std::fs::remove_file(&path);
+ assert!(result.is_err());
+ let (reply, answer) = mpsc::channel();
+ takes.handle(Event::End(reply));
+ assert!(answer.recv().expect("answered").is_err(), "nothing open");
+ }
+
#[test]
fn a_take_lands_where_its_first_sample_was_heard() {
let rolled = Instant::now();
diff --git a/src/crates/concat/locales/en.json b/src/crates/concat/locales/en.json
index 9ebabb49..3057662c 100644
--- a/src/crates/concat/locales/en.json
+++ b/src/crates/concat/locales/en.json
@@ -327,6 +327,7 @@
"phone.noEffectYet": "Nothing on this clip yet. Tap an effect below to add it.",
"phone.noMediaYet": "Nothing in the bin yet. Import a video, a sound or a picture to start.",
"phone.project": "Project",
+ "phone.voiceover": "Voiceover",
"phone.redo": "Redo",
"phone.selectClipFirst": "Tap a clip on the timeline first: this goes on the selected clip.",
"phone.speak": "Speak",
@@ -690,5 +691,30 @@
"tray.undo": "Undo ({0})",
"tray.zoomToFit": "Zoom to fit",
"voiceover.added": "Voiceover added to the timeline",
- "voiceover.failed": "Couldn't record: {0}"
+ "voiceover.clip": "CLIP",
+ "voiceover.clipping": "Clipping: turn the input gain down",
+ "voiceover.close": "Close",
+ "voiceover.closeKeeps": "Stop, keep the take and close",
+ "voiceover.countIn": "Count in 3 seconds",
+ "voiceover.failed": "Couldn't record: {0}",
+ "voiceover.fast": "Fast",
+ "voiceover.inputGain": "Input gain",
+ "voiceover.muteTimeline": "Mute timeline while recording",
+ "voiceover.noMicrophone": "No microphone",
+ "voiceover.opening": "Opening the microphone…",
+ "voiceover.pause": "Pause",
+ "voiceover.paused": "Paused",
+ "voiceover.permission": "Concat needs your permission to use the microphone. Allow it when asked, then press Try again.",
+ "voiceover.record": "Record",
+ "voiceover.recording": "Recording",
+ "voiceover.resume": "Resume",
+ "voiceover.retake": "Retake",
+ "voiceover.scriptPlaceholder": "Type or paste what you will read. It scrolls while you record.",
+ "voiceover.silent": "Only silence is reaching Concat. If the system is keeping the microphone from it, allow Concat under Privacy & Security › Microphone in the system settings.",
+ "voiceover.slow": "Slow",
+ "voiceover.steady": "Steady",
+ "voiceover.stop": "Stop",
+ "voiceover.teleprompter": "Teleprompter",
+ "voiceover.title": "Voiceover",
+ "voiceover.tryAgain": "Try again"
}
diff --git a/src/crates/concat/src/lib.rs b/src/crates/concat/src/lib.rs
index 0e6ba6bc..4873a940 100644
--- a/src/crates/concat/src/lib.rs
+++ b/src/crates/concat/src/lib.rs
@@ -50,6 +50,8 @@ mod platform;
/// `platform::publish_export`.
#[cfg(any(target_os = "android", target_os = "ios"))]
pub use platform::{ExportPublisher, FilePicker, install_export_publisher, install_file_picker};
+#[cfg(any(target_os = "android", target_os = "ios"))]
+pub use platform::{MicrophoneAccess, install_microphone_access};
mod panes;
mod prefs;
mod presets;
@@ -95,6 +97,7 @@ use panes::settings::SettingsMsg;
use panes::speech::SpeechMsg;
use panes::start::StartMsg;
use panes::timeline::TimelineMsg;
+use panes::voiceover::VoiceoverMsg;
use studio::{ASPECTS, Models, OUTPUTS, RATES, SIZES, Studio};
use ui::*;
@@ -359,6 +362,7 @@ fn start(project: Option<std::path::PathBuf>, smoke: bool) -> Result<(), slint::
app.set_speech_samples(ModelRc::from(models.speech_samples.clone()));
app.set_speech_sample_waves(ModelRc::from(models.speech_sample_waves.clone()));
app.set_speech_sample_details(ModelRc::from(models.speech_sample_details.clone()));
+ app.set_voiceover_devices(ModelRc::from(models.voiceover_devices.clone()));
app.set_app_menu_items(ModelRc::from(models.bar.clone()));
app.set_transcribers(ModelRc::from(models.transcribers.clone()));
app.set_voices(ModelRc::from(models.voices.clone()));
@@ -1678,9 +1682,43 @@ fn start(project: Option<std::path::PathBuf>, smoke: bool) -> Result<(), slint::
state.handle(Msg::Captions(CaptionsMsg::Open));
}));
editor.on_record_voiceover(on_window!(|state| {
- state.handle(Msg::Voiceover(
- crate::panes::voiceover::VoiceoverMsg::Toggle,
- ));
+ state.handle(Msg::Voiceover(VoiceoverMsg::Toggle));
+ }));
+ app.on_voiceover_closed(on_window!(|state| {
+ state.handle(Msg::Voiceover(VoiceoverMsg::Close));
+ }));
+ app.on_voiceover_action(on_window!(|state, verb: SharedString| {
+ let msg = match verb.as_str() {
+ "record" => VoiceoverMsg::Record,
+ "pause" => VoiceoverMsg::Pause,
+ "resume" => VoiceoverMsg::Resume,
+ "stop" => VoiceoverMsg::Stop,
+ "retake" => VoiceoverMsg::Retake,
+ "retry" => VoiceoverMsg::Retry,
+ other => {
+ log::warn!("voiceover: no such action {other:?}");
+ return;
+ }
+ };
+ state.handle(Msg::Voiceover(msg));
+ }));
+ app.on_voiceover_device_changed(on_window!(|state, index: i32| {
+ state.handle(Msg::Voiceover(VoiceoverMsg::Device(index)));
+ }));
+ app.on_voiceover_countdown_changed(on_window!(|state, on: bool| {
+ state.handle(Msg::Voiceover(VoiceoverMsg::Countdown(on)));
+ }));
+ app.on_voiceover_mute_changed(on_window!(|state, on: bool| {
+ state.handle(Msg::Voiceover(VoiceoverMsg::Mute(on)));
+ }));
+ app.on_voiceover_gain_changed(on_window!(|state, db: f32| {
+ state.handle(Msg::Voiceover(VoiceoverMsg::Gain(db)));
+ }));
+ app.on_voiceover_prompt_edited(on_window!(|state, text: SharedString| {
+ state.handle(Msg::Voiceover(VoiceoverMsg::Prompt(text.to_string())));
+ }));
+ app.on_voiceover_prompt_speed_changed(on_window!(|state, index: i32| {
+ state.handle(Msg::Voiceover(VoiceoverMsg::PromptSpeed(index)));
}));
editor.on_speak(on_window!(|state| {
state.handle(Msg::Speech(SpeechMsg::Open));
diff --git a/src/crates/concat/src/panes/voiceover.rs b/src/crates/concat/src/panes/voiceover.rs
index f540ebbf..cdd3c271 100644
--- a/src/crates/concat/src/panes/voiceover.rs
+++ b/src/crates/concat/src/panes/voiceover.rs
@@ -4,39 +4,109 @@
//! 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.
+//! The tray's microphone opens a panel that floats over the editor - a
+//! sheet at the foot of a phone's screen - and stays up while the cut is
+//! worked on around it. The panel opens the microphone at once, so its
+//! meter shows the room before a word is said: which microphone, how loud,
+//! whether it clips. Record counts three in, then rolls the picture from
+//! the playhead with the timeline's own sound held silent, unless asked
+//! otherwise, so the speakers do not bleed into the take. Pause holds the
+//! picture and the take together, and Resume carries both on from there:
+//! one take is one clip, its pauses cut out, because the picture paused
+//! with them. Stop lands the take on a lane under the picture, at the
+//! playhead plus the moment the microphone actually began; the next take
+//! goes on the same lane when it is free there. Retake throws the last
+//! take away - the one running, or the one just landed - and goes again
+//! from where it began.
+//!
+//! The file goes into the project's audio folder and is whole on disk as
+//! it is written (see concat_host::record). Closing the panel mid-take
+//! stops it and keeps it.
-use std::time::Instant;
+use std::path::PathBuf;
+use std::time::{Duration, Instant};
use concat_host::media;
-use concat_host::record::{self, Recorder};
+use concat_host::record::{self, Microphone};
use concat_project::Command;
+use slint::ComponentHandle;
-use crate::host::spawn_in_project;
+use crate::host::{on_ui, spawn_in_project};
use crate::i18n::{t, tf};
use crate::panes::Msg;
use crate::studio::Studio;
-use crate::ui::Editor;
-use slint::ComponentHandle;
+use crate::ui::{Editor, VoiceoverData};
-/// Everything that can happen to a take.
+/// Everything that can happen to the panel and its takes.
pub enum VoiceoverMsg {
- /// The tray's button: start a take, or stop the one running.
+ /// The tray's button: open the panel, or stop the take it is running.
Toggle,
+ /// The panel's close button. A take running stops and is kept.
+ Close,
+ /// The microphone is open, with the list it was chosen from, or why
+ /// it is not. The number is the opening it answers; see `opening`.
+ Opened(u32, Box<Result<(Microphone, Vec<String>), String>>),
+ /// Record: a take from the playhead, counted in or not.
+ Record,
+ /// A second of the count-in has passed.
+ Tick,
+ Pause,
+ Resume,
+ Stop,
+ /// Throw the last take away and go again from where it began.
+ Retake,
+ /// Open the microphone again, after it would not open.
+ Retry,
+ /// The device failed after it opened: unplugged, taken by another app.
+ Lost(String),
+ /// A microphone from the list, by its place in it.
+ Device(i32),
+ Countdown(bool),
+ Mute(bool),
+ /// The input gain, in decibels.
+ Gain(f32),
+ /// The teleprompter's script, as typed.
+ Prompt(String),
+ PromptSpeed(i32),
/// The take is written and probed: onto the timeline with it.
- Finished(Box<Result<media::MediaSummary, String>>),
+ Finished(Box<Landed>),
+}
+
+/// A finished take on its way to the timeline.
+pub struct Landed {
+ result: Result<media::MediaSummary, String>,
+ /// Where on the timeline its first sample belongs.
+ landing: f64,
+ /// Its length, in seconds.
+ seconds: f64,
+ /// Where the playhead was when it began: where a retake goes back to.
+ start: f64,
}
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() {
+ Self::Close => write!(f, "Close"),
+ Self::Opened(token, result) => match result.as_ref() {
+ Ok((mic, _)) => write!(f, "Opened({token}, {})", mic.name()),
+ Err(error) => write!(f, "Opened({token}, error {error:?})"),
+ },
+ Self::Record => write!(f, "Record"),
+ Self::Tick => write!(f, "Tick"),
+ Self::Pause => write!(f, "Pause"),
+ Self::Resume => write!(f, "Resume"),
+ Self::Stop => write!(f, "Stop"),
+ Self::Retake => write!(f, "Retake"),
+ Self::Retry => write!(f, "Retry"),
+ Self::Lost(error) => write!(f, "Lost({error:?})"),
+ Self::Device(index) => write!(f, "Device({index})"),
+ Self::Countdown(on) => write!(f, "Countdown({on})"),
+ Self::Mute(on) => write!(f, "Mute({on})"),
+ Self::Gain(db) => write!(f, "Gain({db})"),
+ Self::Prompt(text) => write!(f, "Prompt({} chars)", text.chars().count()),
+ Self::PromptSpeed(index) => write!(f, "PromptSpeed({index})"),
+ Self::Finished(landed) => match &landed.result {
Ok(summary) => write!(f, "Finished({})", summary.path),
Err(error) => write!(f, "Finished(error {error:?})"),
},
@@ -44,65 +114,320 @@ impl std::fmt::Debug for VoiceoverMsg {
}
}
-/// The take in progress, if one is.
+/// Where a take is.
+#[derive(Clone, Copy, Debug, Default, PartialEq)]
+enum Phase {
+ #[default]
+ Ready,
+ /// Counting in, this many seconds to go.
+ Counting(u8),
+ Recording,
+ Paused,
+}
+
+/// The take being recorded.
+struct Running {
+ path: PathBuf,
+ /// Where the playhead was when it began.
+ start: f64,
+ /// When the picture started rolling under it.
+ rolled: Instant,
+ /// Where the playhead was when it was paused: where the picture
+ /// carries on from, wherever the playhead was moved meanwhile, so the
+ /// take and the picture stay one continuous run.
+ held: f32,
+}
+
+/// The take that landed last, for Retake.
+struct Last {
+ media_id: String,
+ start: f64,
+}
+
+/// The panel, its microphone and its take.
#[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.
+ open: bool,
+ mic: Option<Microphone>,
+ /// When the microphone opened: a microphone that has said nothing but
+ /// silence for a while is one the system is keeping from the app.
+ opened: Option<Instant>,
+ /// Counts openings, so the answer to one the panel has since moved on
+ /// from - closed, another microphone picked - is let go.
+ opening: u32,
+ /// An opening is on its way.
+ waiting: bool,
+ devices: Vec<String>,
+ /// Which of `devices` is open.
+ device: usize,
+ /// Why there is no microphone, or what last went wrong.
+ error: Option<String>,
+ phase: Phase,
+ take: Option<Running>,
+ last: Option<Last>,
+ /// The lane the last take went on: the next goes there too when it
+ /// can, so a voiceover reads as one line under the picture.
+ lane: Option<String>,
+ prompt: String,
+ /// Feeds the meter while the panel is open.
meter: Option<slint::Timer>,
+ /// Beats the count-in.
+ countdown: Option<slint::Timer>,
}
impl VoiceoverPane {
- /// Whether a take is running: the button reads Stop, the meter shows.
+ /// Whether a take is under way, counted in or paused: the tray's
+ /// button reads Stop.
pub fn recording(&self) -> bool {
- self.recorder.is_some()
+ self.phase != Phase::Ready
}
/// 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);
- }
+ VoiceoverMsg::Toggle => match self.phase {
+ Phase::Counting(_) => self.cancel_count(),
+ Phase::Recording | Phase::Paused => self.stop(studio),
+ Phase::Ready if self.open => self.close(studio),
+ Phase::Ready => self.open(studio),
+ },
+ VoiceoverMsg::Close => self.close(studio),
+ VoiceoverMsg::Opened(token, result) => {
+ self.opened(token, *result);
+ self.apply_gain(studio);
+ }
+ VoiceoverMsg::Record => self.record(studio),
+ VoiceoverMsg::Tick => match self.phase {
+ Phase::Counting(left) if left > 1 => self.phase = Phase::Counting(left - 1),
+ Phase::Counting(_) => {
+ self.countdown = None;
+ self.begin(studio);
}
- Err(error) => studio.notify(&tf("voiceover.failed", &[&error]), true),
+ _ => self.countdown = None,
+ },
+ VoiceoverMsg::Pause => self.pause(studio),
+ VoiceoverMsg::Resume => self.resume(studio),
+ VoiceoverMsg::Stop => match self.phase {
+ Phase::Counting(_) => self.cancel_count(),
+ _ => self.stop(studio),
},
+ VoiceoverMsg::Retake => self.retake(studio),
+ VoiceoverMsg::Retry => self.reopen(studio),
+ VoiceoverMsg::Lost(error) => {
+ log::warn!("voiceover: the microphone was lost: {error}");
+ self.stop(studio);
+ self.mic = None;
+ self.error = Some(error);
+ }
+ VoiceoverMsg::Device(index) => {
+ let Some((index, name)) = usize::try_from(index)
+ .ok()
+ .and_then(|index| Some((index, self.devices.get(index)?)))
+ else {
+ return;
+ };
+ if self.phase != Phase::Ready || (self.mic.is_some() && self.device == index) {
+ return;
+ }
+ studio.prefs.voiceover.device = Some(name.clone());
+ studio.prefs.save(&studio.host.dirs);
+ self.reopen(studio);
+ }
+ VoiceoverMsg::Countdown(on) => {
+ studio.prefs.voiceover.countdown = on;
+ studio.prefs.save(&studio.host.dirs);
+ }
+ VoiceoverMsg::Mute(on) => {
+ studio.prefs.voiceover.mute = on;
+ studio.prefs.save(&studio.host.dirs);
+ if matches!(self.phase, Phase::Recording | Phase::Paused) {
+ studio.host.playback.set_muted(on);
+ }
+ }
+ VoiceoverMsg::Gain(db) => {
+ let db = db.clamp(GAIN_FLOOR, GAIN_CEILING);
+ studio.prefs.voiceover.gain_db = db;
+ if let Some(mic) = self.mic.as_ref() {
+ mic.set_gain(record::gain_of(db));
+ }
+ studio.prefs.save(&studio.host.dirs);
+ }
+ VoiceoverMsg::Prompt(text) => self.prompt = text,
+ VoiceoverMsg::PromptSpeed(index) => {
+ studio.prefs.voiceover.prompt_speed = index.clamp(0, 2) as u8;
+ studio.prefs.save(&studio.host.dirs);
+ }
+ VoiceoverMsg::Finished(landed) => self.land(*landed, studio),
+ }
+ }
+
+ /// What the panel shows.
+ pub fn data(&self, studio: &Studio) -> VoiceoverData {
+ let prefs = &studio.prefs.voiceover;
+ let (phase, count) = match self.phase {
+ Phase::Ready => (0, 0),
+ Phase::Counting(left) => (1, i32::from(left)),
+ Phase::Recording => (2, 0),
+ Phase::Paused => (3, 0),
+ };
+ VoiceoverData {
+ open: self.open,
+ phase,
+ count,
+ waiting: self.waiting,
+ ready: self.mic.is_some(),
+ device: self.device as i32,
+ countdown: prefs.countdown,
+ mute: prefs.mute,
+ gain: prefs.gain_db,
+ error: self.error.clone().unwrap_or_default().into(),
+ can_retake: self.can_retake(studio),
+ prompt: self.prompt.clone().into(),
+ prompt_speed: i32::from(prefs.prompt_speed),
+ }
+ }
+
+ /// The microphones the panel lists.
+ pub fn device_rows(&self) -> Vec<slint::SharedString> {
+ self.devices.iter().map(|name| name.into()).collect()
+ }
+
+ fn can_retake(&self, studio: &Studio) -> bool {
+ match self.phase {
+ Phase::Recording | Phase::Paused => true,
+ Phase::Counting(_) => false,
+ Phase::Ready => self.last.as_ref().is_some_and(|last| {
+ studio
+ .project()
+ .media
+ .iter()
+ .any(|item| item.id == last.media_id)
+ }),
+ }
+ }
+
+ fn open(&mut self, studio: &mut Studio) {
+ if studio.session.is_none() {
+ return;
+ }
+ self.open = true;
+ self.reopen(studio);
+ }
+
+ /// Opens the microphone the preferences name, off the window's thread:
+ /// listing and opening devices can take a moment, and the panel is up
+ /// meanwhile, saying so.
+ fn reopen(&mut self, studio: &mut Studio) {
+ self.mic = None;
+ self.meter = None;
+ self.opened = None;
+ self.error = None;
+ if !crate::platform::microphone_allowed() {
+ self.error = Some(t("voiceover.permission"));
+ return;
+ }
+ self.opening = self.opening.wrapping_add(1);
+ self.waiting = true;
+ let token = self.opening;
+ let wanted = studio.prefs.voiceover.device.clone();
+ spawn_in_project(
+ move || {
+ let devices = record::microphones();
+ Microphone::open(wanted.as_deref()).map(|mic| (mic, devices))
+ },
+ move |studio, _, _, result| {
+ studio.handle(Msg::Voiceover(VoiceoverMsg::Opened(
+ token,
+ Box::new(result),
+ )));
+ },
+ );
+ }
+
+ fn opened(&mut self, token: u32, result: Result<(Microphone, Vec<String>), String>) {
+ if token != self.opening || !self.open {
+ // Dropped here: the device closes again.
+ return;
+ }
+ self.waiting = false;
+ match result {
+ Ok((mic, mut devices)) => {
+ log::info!("voiceover: listening to {}", mic.name());
+ // The one that opened is on the list whatever the list
+ // says: some systems do not list their default.
+ let device = match devices.iter().position(|name| name == mic.name()) {
+ Some(index) => index,
+ None => {
+ devices.insert(0, mic.name().to_owned());
+ 0
+ }
+ };
+ self.devices = devices;
+ self.device = device;
+ self.mic = Some(mic);
+ self.opened = Some(Instant::now());
+ self.meter = Some(meter());
+ self.error = None;
+ }
+ Err(error) => {
+ log::warn!("voiceover: the microphone would not open: {error}");
+ self.error = Some(tf("voiceover.failed", &[&error]));
+ }
+ }
+ }
+
+ /// Applies the gain the preferences hold to the open microphone.
+ fn apply_gain(&self, studio: &Studio) {
+ if let Some(mic) = self.mic.as_ref() {
+ mic.set_gain(record::gain_of(studio.prefs.voiceover.gain_db));
+ }
+ }
+
+ fn close(&mut self, studio: &mut Studio) {
+ self.cancel_count();
+ self.stop(studio);
+ self.open = false;
+ self.waiting = false;
+ self.mic = None;
+ self.meter = None;
+ self.opened = None;
+ self.error = None;
+ self.last = None;
+ }
+
+ fn record(&mut self, studio: &mut Studio) {
+ if self.phase != Phase::Ready || self.mic.is_none() || studio.session.is_none() {
+ return;
+ }
+ if studio.prefs.voiceover.countdown {
+ self.phase = Phase::Counting(COUNT_IN);
+ let timer = slint::Timer::default();
+ timer.start(slint::TimerMode::Repeated, Duration::from_secs(1), || {
+ on_ui(|studio, _, _| studio.handle(Msg::Voiceover(VoiceoverMsg::Tick)))
+ });
+ self.countdown = Some(timer);
+ } else {
+ self.begin(studio);
+ }
+ }
+
+ fn cancel_count(&mut self) {
+ self.countdown = None;
+ if matches!(self.phase, Phase::Counting(_)) {
+ self.phase = Phase::Ready;
}
}
- /// Opens the microphone and rolls the picture from the playhead.
- fn start(&mut self, studio: &mut Studio) {
+ /// Starts writing and rolls the picture from the playhead.
+ fn begin(&mut self, studio: &mut Studio) {
+ self.phase = Phase::Ready;
+ let Some(mic) = self.mic.as_ref() else {
+ return;
+ };
let Some(project) = studio
.session
.as_ref()
- .map(|session| std::path::PathBuf::from(session.path()))
+ .map(|session| PathBuf::from(session.path()))
else {
return;
};
@@ -111,72 +436,271 @@ impl VoiceoverPane {
.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;
- }
- };
+ self.apply_gain(studio);
+ if let Err(error) = mic.begin(path.clone()) {
+ self.error = Some(tf("voiceover.failed", &[&error]));
+ 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);
+ self.error = None;
+ let start = f64::from(studio.playhead.max(0.0));
+ // The picture rolls under the words, without its sound unless the
+ // panel says otherwise. At the end of the cut there is nothing to
+ // roll, and the take just records.
+ studio.host.playback.set_muted(studio.prefs.voiceover.mute);
if !studio.playing && studio.playhead < studio.duration() {
studio.play_toggle();
}
- self.rolled = Some(Instant::now());
- self.meter = Some(meter());
+ self.take = Some(Running {
+ path,
+ start,
+ rolled: Instant::now(),
+ held: studio.playhead,
+ });
+ self.phase = Phase::Recording;
+ }
+
+ fn pause(&mut self, studio: &mut Studio) {
+ if self.phase != Phase::Recording {
+ return;
+ }
+ if let Some(mic) = self.mic.as_ref() {
+ mic.pause();
+ }
+ if studio.playing {
+ studio.pause();
+ }
+ if let Some(take) = self.take.as_mut() {
+ take.held = studio.playhead;
+ }
+ self.phase = Phase::Paused;
+ }
+
+ fn resume(&mut self, studio: &mut Studio) {
+ if self.phase != Phase::Paused {
+ return;
+ }
+ let Some(mic) = self.mic.as_ref() else {
+ return;
+ };
+ if let Some(held) = self.take.as_ref().map(|take| take.held)
+ && (studio.playhead - held).abs() > 1e-4
+ {
+ studio.seek(held);
+ }
+ mic.resume();
+ if !studio.playing && studio.playhead < studio.duration() {
+ studio.play_toggle();
+ }
+ self.phase = Phase::Recording;
}
/// 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 {
+ self.cancel_count();
+ let Some(take) = self.take.take() else {
+ self.phase = Phase::Ready;
return;
};
+ self.phase = Phase::Ready;
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);
+ let Some(mic) = self.mic.as_ref() else {
+ return;
+ };
+ match mic.end() {
+ Ok(done) => {
+ log::info!("voiceover: {:.2}s to {}", done.seconds, done.path.display());
+ let landing = record::landing(take.start, take.rolled, done.first);
+ let seconds = done.seconds;
+ let start = take.start;
spawn_in_project(
- move || media::probe(&take.path.to_string_lossy()),
- |studio, _, _, result| {
- studio.handle(Msg::Voiceover(VoiceoverMsg::Finished(Box::new(result))));
+ move || media::probe(&done.path.to_string_lossy()),
+ move |studio, _, _, result| {
+ studio.handle(Msg::Voiceover(VoiceoverMsg::Finished(Box::new(Landed {
+ result,
+ landing,
+ seconds,
+ start,
+ }))));
},
);
}
- Err(error) => studio.notify(&tf("voiceover.failed", &[&error]), true),
+ Err(error) => {
+ let _ = std::fs::remove_file(&take.path);
+ studio.notify(&tf("voiceover.failed", &[&error]), true);
+ }
+ }
+ }
+
+ /// Throws the last take away and goes again from where it began: the
+ /// one running, its file deleted, or the one that landed last, taken
+ /// off the timeline and out of the bin as one step that undo brings
+ /// back - so its file stays on disk.
+ fn retake(&mut self, studio: &mut Studio) {
+ let start = match self.phase {
+ Phase::Counting(_) => return,
+ Phase::Recording | Phase::Paused => {
+ let Some(take) = self.take.take() else {
+ return;
+ };
+ self.phase = Phase::Ready;
+ if studio.playing {
+ studio.pause();
+ }
+ // Heard again until the next take begins: a count-in
+ // cancelled from here must not leave the timeline silent.
+ studio.host.playback.set_muted(false);
+ if let Some(mic) = self.mic.as_ref() {
+ let _ = mic.end();
+ }
+ let _ = std::fs::remove_file(&take.path);
+ take.start
+ }
+ Phase::Ready => {
+ if !self.can_retake(studio) {
+ return;
+ }
+ let Some(last) = self.last.take() else {
+ return;
+ };
+ studio.apply(Command::RemoveMedia {
+ media_id: last.media_id,
+ });
+ last.start
+ }
+ };
+ log::info!("voiceover: retake from {start:.3}s");
+ studio.seek(start as f32);
+ self.record(studio);
+ }
+
+ /// Puts a probed take into the bin and on the timeline.
+ fn land(&mut self, landed: Landed, studio: &mut Studio) {
+ let summary = match landed.result {
+ Ok(summary) => summary,
+ Err(error) => {
+ studio.notify(&tf("voiceover.failed", &[&error]), true);
+ return;
+ }
+ };
+ // 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 Some(media_id) = created.or_else(|| {
+ studio
+ .project()
+ .media
+ .iter()
+ .find(|item| item.path == summary.path)
+ .map(|item| item.id.clone())
+ }) else {
+ return;
+ };
+ // The lane the last take went on, when it is free over this one.
+ let lane = self.lane.clone().filter(|lane| {
+ let timeline = studio.project().active();
+ timeline.tracks.iter().any(|track| track.id == *lane)
+ && timeline.is_free(lane, landed.landing, landed.seconds, &[])
+ });
+ let clip = match lane {
+ Some(track_id) => studio.apply(Command::AddClip {
+ media_id: media_id.clone(),
+ track_id,
+ start: landed.landing,
+ ripple: false,
+ }),
+ None => studio.apply(Command::AddClipAtFirstFree {
+ media_id: media_id.clone(),
+ start: landed.landing,
+ }),
+ };
+ if let Some(clip) = clip {
+ self.lane = studio
+ .project()
+ .active()
+ .clips
+ .iter()
+ .find(|placed| placed.id == clip)
+ .map(|placed| placed.track_id.clone());
+ self.last = Some(Last {
+ media_id,
+ start: landed.start,
+ });
+ studio.notify(&t("voiceover.added"), false);
}
}
}
-/// 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.
+/// Seconds counted in before a take.
+const COUNT_IN: u8 = 3;
+
+/// The input gain's range, in decibels.
+const GAIN_FLOOR: f32 = -12.0;
+const GAIN_CEILING: f32 = 18.0;
+
+/// How long the clip light stays on after a sample reached the top: long
+/// enough to be seen, short enough to say when it stopped.
+const CLIP_HOLD: Duration = Duration::from_millis(1500);
+
+/// How long a microphone may say nothing but silence before the panel
+/// says the system may be keeping it from the app.
+const SILENT_AFTER: Duration = Duration::from_secs(2);
+
+/// A timer that shows the microphone on the panel's meter thirty times a
+/// second, straight onto the Editor's properties, with no publish around
+/// it - and says so if the device went away.
fn meter() -> slint::Timer {
let timer = slint::Timer::default();
let mut shown = 0.0f32;
+ let mut clipped_until: Option<Instant> = None;
+ let mut reported = false;
timer.start(
slint::TimerMode::Repeated,
- std::time::Duration::from_millis(33),
+ 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;
+ // A native dialog can run this under a handler that holds
+ // the studio; the meter skips a beat rather than panic.
+ let lost = {
+ let Ok(studio) = shell.studio.try_borrow() else {
+ return;
+ };
+ let pane = &studio.voiceover;
+ let Some(mic) = pane.mic.as_ref() else {
+ return;
+ };
+ let level = mic.level();
+ let now = Instant::now();
+ // Up at once, down gently: a meter that falls as fast as
+ // it rises flickers.
+ shown = record::meter_position(level.peak).max(shown * 0.85);
+ if level.clipped {
+ clipped_until = Some(now + CLIP_HOLD);
+ }
+ let editor = app.global::<Editor>();
+ editor.set_record_level(shown);
+ editor.set_record_rms(record::meter_position(level.rms));
+ editor.set_record_clipped(clipped_until.is_some_and(|until| now < until));
+ editor.set_record_seconds(mic.seconds() as f32);
+ editor.set_record_silent(
+ !mic.heard()
+ && pane
+ .opened
+ .is_some_and(|opened| opened.elapsed() > SILENT_AFTER),
+ );
+ if reported { None } else { mic.failed() }
};
- // 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);
+ if let Some(error) = lost {
+ reported = true;
+ on_ui(move |studio, _, _| {
+ studio.handle(Msg::Voiceover(VoiceoverMsg::Lost(error)));
+ });
+ }
});
},
);
diff --git a/src/crates/concat/src/platform.rs b/src/crates/concat/src/platform.rs
index 8d2344ff..0f96af2e 100644
--- a/src/crates/concat/src/platform.rs
+++ b/src/crates/concat/src/platform.rs
@@ -744,6 +744,38 @@ pub fn install_export_publisher(publisher: ExportPublisher) {
let _ = EXPORT_PUBLISHER.set(publisher);
}
+/// Whether the app may record from the microphone, asking when it has not
+/// been told: on a phone, false puts the system's question up and comes
+/// back at once, and the answer is read the next time this is asked.
+/// Installed by the phone's own crate; see [`install_microphone_access`].
+#[cfg(any(target_os = "android", target_os = "ios"))]
+pub type MicrophoneAccess = Box<dyn Fn() -> bool + Send + Sync>;
+
+#[cfg(any(target_os = "android", target_os = "ios"))]
+static MICROPHONE_ACCESS: std::sync::OnceLock<MicrophoneAccess> = std::sync::OnceLock::new();
+
+/// Installs how a phone is asked for its microphone. Once; a second call
+/// is ignored.
+#[cfg(any(target_os = "android", target_os = "ios"))]
+pub fn install_microphone_access(access: MicrophoneAccess) {
+ let _ = MICROPHONE_ACCESS.set(access);
+}
+
+/// Whether the microphone may be opened now. A desktop asks when the
+/// device opens, which is the system's business, so it is always yes here;
+/// a phone with nothing installed is too, and the device's own error says
+/// the rest.
+pub fn microphone_allowed() -> bool {
+ #[cfg(any(target_os = "android", target_os = "ios"))]
+ {
+ MICROPHONE_ACCESS.get().is_none_or(|access| access())
+ }
+ #[cfg(not(any(target_os = "android", target_os = "ios")))]
+ {
+ true
+ }
+}
+
/// Where a finished export ends up on this device when that is not the
/// folder the export writes into: a phone's "Movies/Concat". None on a
/// desktop, and on a phone too old to be asked, where the file stays where
diff --git a/src/crates/concat/src/prefs.rs b/src/crates/concat/src/prefs.rs
index 537e34ea..542aa2b2 100644
--- a/src/crates/concat/src/prefs.rs
+++ b/src/crates/concat/src/prefs.rs
@@ -103,6 +103,41 @@ pub struct Preferences {
/// unless the Settings sheet was asked for more or less. CONCAT_LOG in
/// the environment overrides it for one run.
pub log_level: Option<String>,
+ /// How the voiceover panel was last set up.
+ #[serde(default)]
+ pub voiceover: VoiceoverPrefs,
+}
+
+/// The voiceover panel's choices, kept from one take to the next and one
+/// run to the next: a microphone picked once stays picked.
+#[derive(Clone, Debug, Serialize, Deserialize)]
+#[serde(default, rename_all = "camelCase")]
+pub struct VoiceoverPrefs {
+ /// The microphone, by the name the system gives it. None, or one that
+ /// is no longer plugged in, is the system's default.
+ pub device: Option<String>,
+ /// Three seconds counted in before a take starts. On by default: the
+ /// breath before the first word is what a count-in is for.
+ pub countdown: bool,
+ /// The timeline is silent while a take records, so the speakers do not
+ /// bleed into the microphone. On by default; off is for headphones.
+ pub mute: bool,
+ /// The input gain, in decibels.
+ pub gain_db: f32,
+ /// How fast the teleprompter scrolls: 0 slow, 1 steady, 2 fast.
+ pub prompt_speed: u8,
+}
+
+impl Default for VoiceoverPrefs {
+ fn default() -> Self {
+ VoiceoverPrefs {
+ device: None,
+ countdown: true,
+ mute: true,
+ gain_db: 0.0,
+ prompt_speed: 1,
+ }
+ }
}
impl Preferences {
diff --git a/src/crates/concat/src/studio.rs b/src/crates/concat/src/studio.rs
index 45ebac64..75594ad4 100644
--- a/src/crates/concat/src/studio.rs
+++ b/src/crates/concat/src/studio.rs
@@ -655,6 +655,8 @@ pub struct Models {
pub speakers: Rc<VecModel<SharedString>>,
pub speaker_details: Rc<VecModel<SharedString>>,
pub speech_samples: Rc<VecModel<SharedString>>,
+ /// The microphones the voiceover panel lists.
+ pub voiceover_devices: Rc<VecModel<SharedString>>,
pub speech_sample_waves: Rc<VecModel<SharedString>>,
pub speech_sample_details: Rc<VecModel<SharedString>>,
pub transcribers: Rc<VecModel<ModelData>>,
@@ -722,6 +724,7 @@ impl Models {
speakers: Rc::new(VecModel::default()),
speaker_details: Rc::new(VecModel::default()),
speech_samples: Rc::new(VecModel::default()),
+ voiceover_devices: Rc::new(VecModel::default()),
speech_sample_waves: Rc::new(VecModel::default()),
speech_sample_details: Rc::new(VecModel::default()),
transcribers: Rc::new(VecModel::default()),
@@ -9910,6 +9913,8 @@ impl Studio {
);
app.set_speech(self.speech.data(self));
self.publish_source(app);
+ sync(&models.voiceover_devices, self.voiceover.device_rows());
+ app.set_voiceover(self.voiceover.data(self));
editor.set_recording(self.voiceover.recording());
let bar = self.menu_bar();
diff --git a/src/crates/concat/ui/app.slint b/src/crates/concat/ui/app.slint
index 936440fc..fc65805b 100644
--- a/src/crates/concat/ui/app.slint
+++ b/src/crates/concat/ui/app.slint
@@ -28,6 +28,7 @@ import { RelinkDialog, RelinkData, MissingMediaItem } from "dialogs/relink.slint
import { ConfirmData, ConfirmDialog } from "dialogs/confirm.slint";
import { CaptionsDialog, CaptionsSheetData } from "dialogs/captions.slint";
import { SpeechDialog, SpeechSheetData } from "dialogs/speech.slint";
+import { VoiceoverData, VoiceoverPanel } from "dialogs/voiceover.slint";
import { DockDivider, DockSide, SeatBox } from "dock.slint";
import { Editor } from "editor.slint";
import { PaneKind, Panes } from "workspace/pane-switcher.slint";
@@ -62,7 +63,7 @@ export {
SelectedClipData, SelectedTransitionData, StageGuideData, StageItemData, TextAlignment, TimelineTabData,
TimelineTool, TrackData, TrackSize, MenuItemData, MenuRow, ExportData, ExportPhase, ModelData, SettingsData,
ChipOption, RecentProjectData, StartData, SystemFactData, ToastData, ProjectSheetData,
- CaptionsSheetData, SpeechSheetData,
+ CaptionsSheetData, SpeechSheetData, VoiceoverData,
}
export component App inherits Window {
@@ -322,6 +323,19 @@ export component App inherits Window {
callback speech-begin();
callback speech-cancel();
+ /// The voiceover panel; see VoiceoverPanel. Its meter and clock come
+ /// on the Editor global, from a timer.
+ in property <VoiceoverData> voiceover;
+ in property <[string]> voiceover-devices;
+ callback voiceover-closed();
+ callback voiceover-action(verb: string);
+ callback voiceover-device-changed(index: int);
+ callback voiceover-countdown-changed(on: bool);
+ callback voiceover-mute-changed(on: bool);
+ callback voiceover-gain-changed(db: float);
+ callback voiceover-prompt-edited(text: string);
+ callback voiceover-prompt-speed-changed(index: int);
+
/// Takes focus back from whatever field holds it. The keyboard scope is
/// where focus rests when nothing is being typed into, so giving it the
/// focus is what "click beside the field" means. Rust calls this for
@@ -692,6 +706,37 @@ export component App inherits Window {
}
}
+ // The voiceover panel floats over the editor and under every sheet:
+ // it has no scrim, so the work beside it carries on, and a sheet put up
+ // while it is open - Export, Settings - covers it like the rest.
+ if !root.on-start: VoiceoverPanel {
+ x: 0;
+ y: 0;
+ width: root.width;
+ height: root.height;
+ phone: root.phone;
+ inset-top: root.safe-area-insets.top;
+ inset-bottom: root.safe-area-insets.bottom;
+ inset-left: root.safe-area-insets.left;
+ inset-right: root.safe-area-insets.right;
+ data: root.voiceover;
+ devices: root.voiceover-devices;
+ level: Editor.record-level;
+ rms: Editor.record-rms;
+ clipped: Editor.record-clipped;
+ seconds: Editor.record-seconds;
+ silent: Editor.record-silent;
+
+ closed => { root.voiceover-closed(); }
+ action(verb) => { root.voiceover-action(verb); }
+ device-changed(index) => { root.voiceover-device-changed(index); }
+ countdown-changed(on) => { root.voiceover-countdown-changed(on); }
+ mute-changed(on) => { root.voiceover-mute-changed(on); }
+ gain-changed(db) => { root.voiceover-gain-changed(db); }
+ prompt-edited(text) => { root.voiceover-prompt-edited(text); }
+ prompt-speed-changed(index) => { root.voiceover-prompt-speed-changed(index); }
+ }
+
// Declared last, and that is load-bearing: Slint paints siblings in
// declaration order, so a modal placed above the workspace in the file is
// painted *under* it on screen — open, correct, and completely hidden.
diff --git a/src/crates/concat/ui/dialogs/voiceover.slint b/src/crates/concat/ui/dialogs/voiceover.slint
new file mode 100644
index 00000000..ba75ac70
--- /dev/null
+++ b/src/crates/concat/ui/dialogs/voiceover.slint
@@ -0,0 +1,593 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+// SPDX-FileCopyrightText: 2026 Jareer and Concat contributors
+
+import { I18n } from "../i18n.slint";
+import { Theme } from "../theme/theme.slint";
+import { Glyph, Icon } from "../icons.slint";
+import { Button } from "../primitives/modal.slint";
+import { IconButton } from "../primitives/panel.slint";
+import { LevelMeter } from "../primitives/level-meter.slint";
+import { SegmentedControl } from "../primitives/segmented-control.slint";
+import { Select } from "../primitives/select.slint";
+import { Rail, Switch } from "../inspector/controls.slint";
+import { Fmt } from "../util.slint";
+
+// The voiceover panel: what the tray's microphone opens.
+//
+// Not a sheet. A sheet puts a scrim over the editor, and a voiceover is
+// recorded over the editor - the picture rolling in the monitor, the
+// playhead crossing the lanes, a clip trimmed between takes - so the panel
+// floats beside the work instead, with nothing behind it held back. On a
+// desk it is a card that goes where its header is dragged and stays inside
+// the window; on a phone it is a sheet at the foot of the screen, over the
+// bar and the lanes, with the monitor left in view above it.
+//
+// Everything it shows is Rust's: the take's state, the microphones, the
+// choices, remembered between runs. The meter and the clock arrive on the
+// Editor global thirty times a second from a timer, not through this
+// struct, so a reading is not a publish of the whole window.
+export struct VoiceoverData {
+ open: bool,
+ /// 0 ready, 1 counting in, 2 recording, 3 paused.
+ phase: int,
+ /// Seconds left of the count-in.
+ count: int,
+ /// The microphone is being opened.
+ waiting: bool,
+ /// A microphone is open and listening.
+ ready: bool,
+ /// Which of the listed microphones it is.
+ device: int,
+ /// Three seconds counted in before a take.
+ countdown: bool,
+ /// The timeline is silent while a take records.
+ mute: bool,
+ /// The input gain, in decibels.
+ gain: float,
+ /// Why there is no microphone, or what last went wrong; empty when
+ /// all is well.
+ error: string,
+ /// There is a take to throw away and go again from: the one running,
+ /// or the one that landed last.
+ can-retake: bool,
+ /// The teleprompter's script.
+ prompt: string,
+ /// How fast it scrolls: 0 slow, 1 steady, 2 fast.
+ prompt-speed: int,
+}
+
+// The transport's middle button: round, the size of a thumb, and the one
+// thing on the panel worth reaching for blind. A red dot is Record and
+// Resume, as on every recorder; two bars are Pause.
+component TransportButton inherits Rectangle {
+ in property <string> label;
+ in property <bool> dot;
+ in property <Glyph> glyph: Glyph.none;
+ in property <bool> enabled: true;
+
+ callback clicked();
+
+ property <bool> lit: touch.has-hover && root.enabled;
+
+ width: 52px;
+ height: 52px;
+ border-radius: self.width / 2;
+ background: touch.pressed ? Theme.field-active : root.lit ? Theme.field-hover : Theme.field;
+ border-width: 1px;
+ border-color: root.lit ? Theme.line-strong : Theme.line;
+ opacity: root.enabled ? 1.0 : 0.45;
+ accessible-role: button;
+ accessible-label: root.label;
+ accessible-enabled: root.enabled;
+ accessible-action-default => { root.clicked(); }
+
+ animate background { duration: 100ms; easing: cubic-bezier(0.4, 0, 0.2, 1); }
+
+ if root.dot: Rectangle {
+ x: (parent.width - self.width) / 2;
+ y: (parent.height - self.height) / 2;
+ width: 20px;
+ height: 20px;
+ border-radius: self.width / 2;
+ background: Theme.danger;
+ }
+ if !root.dot: Icon {
+ x: (parent.width - self.width) / 2;
+ y: (parent.height - self.height) / 2;
+ glyph: root.glyph;
+ size: 20px;
+ tint: Theme.fg;
+ }
+
+ touch := TouchArea {
+ enabled: root.enabled;
+ mouse-cursor: pointer;
+ clicked => { root.clicked(); }
+ }
+}
+
+// A switch with its words before it, on the panel's own margins.
+component ChoiceRow inherits HorizontalLayout {
+ in property <string> label;
+ in property <bool> checked;
+ in property <bool> enabled: true;
+
+ callback toggled(on: bool);
+
+ spacing: 8px;
+ min-height: 26px;
+
+ Text {
+ horizontal-stretch: 1;
+ text: root.label;
+ color: Theme.fg-muted;
+ font-size: Theme.fs;
+ vertical-alignment: center;
+ overflow: elide;
+ }
+ VerticalLayout {
+ alignment: center;
+ Switch {
+ checked: root.checked;
+ enabled: root.enabled;
+ toggled(on) => { root.toggled(on); }
+ }
+ }
+}
+
+export component VoiceoverPanel inherits Rectangle {
+ in property <VoiceoverData> data;
+ in property <[string]> devices;
+ in property <bool> phone;
+ in property <length> inset-top;
+ in property <length> inset-bottom;
+ in property <length> inset-left;
+ in property <length> inset-right;
+ /// The live feed: the meter's peak and power as positions along the
+ /// bar, the clip light, the take's length so far, and whether the
+ /// microphone has given nothing but silence since it opened.
+ in property <float> level;
+ in property <float> rms;
+ in property <bool> clipped;
+ in property <float> seconds;
+ in property <bool> silent;
+
+ callback closed();
+ /// The transport, by verb: record, pause, resume, stop, retake, retry.
+ callback action(verb: string);
+ callback device-changed(index: int);
+ callback countdown-changed(on: bool);
+ callback mute-changed(on: bool);
+ callback gain-changed(db: float);
+ callback prompt-edited(text: string);
+ callback prompt-speed-changed(index: int);
+
+ visible: root.data.open;
+
+ property <bool> taking: root.data.phase == 2 || root.data.phase == 3;
+ property <bool> busy: root.data.phase != 0;
+
+ // The script and the slider hold their own copies, seeded from the
+ // data the way the speech sheet's are: a TextInput or a Rail writes to
+ // the property it is bound to, which drops the binding.
+ property <string> draft;
+ property <bool> typing;
+ property <float> gain-v;
+ /// The script is shown: when there is one, or once asked for.
+ property <bool> show-prompt;
+ changed data => {
+ if (!root.typing) {
+ root.draft = root.data.prompt;
+ }
+ root.gain-v = root.data.gain;
+ }
+ init => {
+ root.draft = root.data.prompt;
+ root.gain-v = root.data.gain;
+ }
+
+ // Where the card sits on a desk: its home under the title strip at the
+ // right, over the inspector, moved by however far its header has been
+ // dragged - and kept wholly inside the window, the drag included, so
+ // pulling it back from an edge moves it at once.
+ property <length> card-w: root.phone ? root.width - root.inset-left - root.inset-right : 340px;
+ property <length> home-x: root.width - root.card-w - 16px - root.inset-right;
+ property <length> home-y: 48px + root.inset-top;
+ property <length> dx;
+ property <length> dy;
+ property <length> min-dx: 8px - root.home-x;
+ property <length> max-dx: root.width - root.card-w - 8px - root.home-x;
+ property <length> min-dy: 8px - root.home-y;
+ property <length> max-dy: root.height - card.height - 8px - root.home-y;
+
+ /// Lines a second the teleprompter climbs at, as pixels.
+ property <float> prompt-rate: root.data.prompt-speed == 0 ? 9
+ : root.data.prompt-speed == 2 ? 22 : 14;
+
+ card := Rectangle {
+ x: root.phone ? root.inset-left
+ : root.home-x + Math.max(root.min-dx, Math.min(root.max-dx, root.dx));
+ y: root.phone ? root.height - self.height - root.inset-bottom
+ : root.home-y + Math.max(root.min-dy, Math.min(root.max-dy, root.dy));
+ width: root.card-w;
+ height: body.preferred-height;
+ background: Theme.panel;
+ border-width: 1px;
+ border-color: Theme.line-strong;
+ // A phone's sheet stands on the foot of the screen: round at the
+ // top only.
+ border-top-left-radius: Theme.r-lg;
+ border-top-right-radius: Theme.r-lg;
+ border-bottom-left-radius: root.phone ? 0 : Theme.r-lg;
+ border-bottom-right-radius: root.phone ? 0 : Theme.r-lg;
+ drop-shadow-blur: 24px;
+ drop-shadow-offset-y: 6px;
+ drop-shadow-color: #00000059;
+ clip: true;
+
+ // Swallows presses that land on the card, so they do not reach the
+ // lanes or the monitor underneath.
+ TouchArea { }
+
+ body := VerticalLayout {
+ padding-bottom: 14px;
+ spacing: 10px;
+
+ // ── the header, and what drags the card ──────────────────────
+ Rectangle {
+ height: 42px;
+
+ if !root.phone: TouchArea {
+ mouse-cursor: move;
+ moved => {
+ if (self.pressed) {
+ root.dx = Math.max(root.min-dx, Math.min(root.max-dx,
+ root.dx + self.mouse-x - self.pressed-x));
+ root.dy = Math.max(root.min-dy, Math.min(root.max-dy,
+ root.dy + self.mouse-y - self.pressed-y));
+ }
+ }
+ }
+
+ HorizontalLayout {
+ padding-left: Theme.pad;
+ padding-right: 8px;
+ spacing: 8px;
+
+ VerticalLayout {
+ alignment: center;
+ Icon {
+ glyph: Glyph.mic;
+ size: 15px;
+ tint: root.taking ? Theme.danger : Theme.fg;
+ }
+ }
+ Text {
+ text: I18n.t("voiceover.title");
+ color: Theme.fg;
+ font-size: Theme.fs-lg;
+ font-weight: Theme.weight-title;
+ vertical-alignment: center;
+ }
+ // What the take is doing, in a word, beside the title:
+ // seen at a glance from across the window.
+ if root.data.phase == 2: Text {
+ text: I18n.t("voiceover.recording");
+ color: Theme.danger;
+ font-size: Theme.fs-sm;
+ font-weight: Theme.weight-title;
+ vertical-alignment: center;
+ }
+ if root.data.phase == 3: Text {
+ text: I18n.t("voiceover.paused");
+ color: Theme.fg-muted;
+ font-size: Theme.fs-sm;
+ font-weight: Theme.weight-title;
+ vertical-alignment: center;
+ }
+ Rectangle { horizontal-stretch: 1; }
+ IconButton {
+ glyph: Glyph.close;
+ label: root.taking ? I18n.t("voiceover.closeKeeps") : I18n.t("voiceover.close");
+ clicked => { root.closed(); }
+ }
+ }
+
+ Rectangle {
+ y: parent.height - 1px;
+ height: 1px;
+ background: Theme.line;
+ }
+ }
+
+ // ── the microphone ───────────────────────────────────────────
+ VerticalLayout {
+ padding-left: Theme.pad;
+ padding-right: Theme.pad;
+ spacing: 8px;
+
+ // Said plainly, with the way out beside it: a microphone
+ // the system will not hand over is the commonest reason a
+ // voiceover does not work, and the fix is not in this app.
+ if root.data.error != "": Rectangle {
+ border-radius: Theme.r;
+ background: Theme.danger-soft;
+
+ HorizontalLayout {
+ padding: 8px;
+ spacing: 8px;
+
+ Text {
+ horizontal-stretch: 1;
+ text: root.data.error;
+ color: Theme.fg;
+ font-size: Theme.fs;
+ wrap: word-wrap;
+ vertical-alignment: center;
+ }
+ if !root.data.ready: VerticalLayout {
+ alignment: center;
+ Button {
+ label: I18n.t("voiceover.tryAgain");
+ clicked => { root.action("retry"); }
+ }
+ }
+ }
+ }
+ if root.data.error == "" && root.data.ready && root.silent: Text {
+ text: I18n.t("voiceover.silent");
+ color: Theme.fg-muted;
+ font-size: Theme.fs-sm;
+ wrap: word-wrap;
+ }
+
+ Select {
+ options: root.devices;
+ current: root.data.device;
+ glyph: Glyph.mic;
+ placeholder: root.data.waiting ? I18n.t("voiceover.opening")
+ : I18n.t("voiceover.noMicrophone");
+ enabled: root.data.ready && !root.busy && root.devices.length > 0;
+ changed(index) => { root.device-changed(index); }
+ }
+
+ // The meter: the power as the bar, the peak as its tick,
+ // and a light at the end for a sample that hit the top.
+ HorizontalLayout {
+ spacing: 8px;
+ height: 18px;
+
+ LevelMeter {
+ horizontal-stretch: 1;
+ value: root.data.ready ? root.rms : 0;
+ peak: root.data.ready ? root.level : -1;
+ thickness: 8px;
+ }
+ Rectangle {
+ width: 34px;
+ border-radius: Theme.r-xs;
+ background: root.clipped ? Theme.danger : Theme.well;
+ accessible-role: text;
+ accessible-label: root.clipped ? I18n.t("voiceover.clipping") : "";
+
+ Text {
+ text: I18n.t("voiceover.clip");
+ color: root.clipped ? Theme.on-accent : Theme.fg-dim;
+ font-size: Theme.fs-xs;
+ font-weight: Theme.weight-title;
+ horizontal-alignment: center;
+ vertical-alignment: center;
+ }
+ }
+ }
+
+ HorizontalLayout {
+ spacing: 8px;
+
+ Text {
+ text: I18n.t("voiceover.inputGain");
+ color: Theme.fg-muted;
+ font-size: Theme.fs;
+ vertical-alignment: center;
+ }
+ Rail {
+ horizontal-stretch: 1;
+ value <=> root.gain-v;
+ minimum: -12;
+ maximum: 18;
+ step: 0.5;
+ default-value: 0;
+ enabled: root.data.ready;
+ changed(v) => { root.gain-changed(v); }
+ }
+ Text {
+ width: 52px;
+ text: Fmt.decibels(root.gain-v);
+ color: Theme.fg-muted;
+ font-size: Theme.fs-sm;
+ font-family: Theme.font-technical;
+ horizontal-alignment: right;
+ vertical-alignment: center;
+ }
+ }
+ }
+
+ // ── the clock, and the count-in over it ──────────────────────
+ Text {
+ text: root.data.phase == 1 ? "\{root.data.count}"
+ : Fmt.short-duration(root.seconds) + "."
+ + "\{Math.mod(Math.floor(root.seconds * 10), 10)}";
+ color: root.data.phase == 1 ? Theme.accent
+ : root.data.phase == 2 ? Theme.fg
+ : Theme.fg-muted;
+ font-size: 30px;
+ font-weight: Theme.weight-display;
+ font-family: Theme.font-technical;
+ horizontal-alignment: center;
+ accessible-role: text;
+ }
+
+ // ── the transport ────────────────────────────────────────────
+ HorizontalLayout {
+ padding-left: Theme.pad;
+ padding-right: Theme.pad;
+ spacing: 12px;
+ alignment: center;
+
+ VerticalLayout {
+ alignment: center;
+ Button {
+ glyph: Glyph.undo;
+ label: I18n.t("voiceover.retake");
+ ghost: true;
+ enabled: root.data.can-retake;
+ clicked => { root.action("retake"); }
+ }
+ }
+
+ TransportButton {
+ label: root.data.phase == 2 ? I18n.t("voiceover.pause")
+ : root.data.phase == 3 ? I18n.t("voiceover.resume")
+ : I18n.t("voiceover.record");
+ dot: root.data.phase != 2;
+ glyph: Glyph.pause;
+ enabled: root.data.ready && root.data.phase != 1;
+ clicked => {
+ if (root.data.phase == 2) {
+ root.action("pause");
+ } else if (root.data.phase == 3) {
+ root.action("resume");
+ } else {
+ root.action("record");
+ }
+ }
+ }
+
+ VerticalLayout {
+ alignment: center;
+ Button {
+ glyph: Glyph.stop;
+ label: root.data.phase == 1 ? I18n.t("common.cancel")
+ : I18n.t("voiceover.stop");
+ ghost: true;
+ enabled: root.busy;
+ clicked => { root.action("stop"); }
+ }
+ }
+ }
+
+ // ── the choices ──────────────────────────────────────────────
+ VerticalLayout {
+ padding-left: Theme.pad;
+ padding-right: Theme.pad;
+ spacing: 2px;
+
+ ChoiceRow {
+ label: I18n.t("voiceover.countIn");
+ checked: root.data.countdown;
+ enabled: !root.busy;
+ toggled(on) => { root.countdown-changed(on); }
+ }
+ ChoiceRow {
+ label: I18n.t("voiceover.muteTimeline");
+ checked: root.data.mute;
+ toggled(on) => { root.mute-changed(on); }
+ }
+ }
+
+ // ── the teleprompter ─────────────────────────────────────────
+ //
+ // The words to read, typed or pasted in before the take and
+ // climbing the box while it records, at a pace set beside it;
+ // a pause holds them where they are, since the clock they
+ // follow is the take's own.
+ // https://github.com/jub0t/Concat/issues/213
+ VerticalLayout {
+ padding-left: Theme.pad;
+ padding-right: Theme.pad;
+ spacing: 6px;
+
+ HorizontalLayout {
+ spacing: 8px;
+
+ IconButton {
+ glyph: root.show-prompt || root.data.prompt != "" ? Glyph.chevron-down : Glyph.chevron-right;
+ label: I18n.t("voiceover.teleprompter");
+ icon-size: 12px;
+ clicked => {
+ root.show-prompt = !(root.show-prompt || root.data.prompt != "");
+ }
+ }
+ Text {
+ text: I18n.t("voiceover.teleprompter");
+ color: Theme.fg-muted;
+ font-size: Theme.fs;
+ vertical-alignment: center;
+ }
+ Rectangle { horizontal-stretch: 1; }
+ if root.show-prompt || root.data.prompt != "": SegmentedControl {
+ width: 150px;
+ options: [
+ I18n.t("voiceover.slow"),
+ I18n.t("voiceover.steady"),
+ I18n.t("voiceover.fast"),
+ ];
+ current: root.data.prompt-speed;
+ changed(index) => { root.prompt-speed-changed(index); }
+ }
+ }
+
+ if root.show-prompt || root.data.prompt != "": Rectangle {
+ height: root.phone ? 96px : 120px;
+ border-radius: Theme.r;
+ background: Theme.well;
+ border-width: 1px;
+ border-color: script.has-focus ? Theme.accent : Theme.line;
+ clip: true;
+
+ script := TextInput {
+ x: 10px;
+ y: 8px;
+ width: parent.width - 20px;
+ height: parent.height - 16px;
+ visible: !root.taking;
+ enabled: !root.taking;
+ text <=> root.draft;
+ color: Theme.fg;
+ font-size: Theme.fs-input;
+ single-line: false;
+ wrap: word-wrap;
+ selection-background-color: Theme.accent;
+ selection-foreground-color: Theme.on-accent;
+ changed has-focus => { root.typing = self.has-focus; }
+ edited => { root.prompt-edited(self.text); }
+ }
+
+ if !root.taking && root.draft == "" && !script.has-focus: Text {
+ x: 10px;
+ y: 8px;
+ width: parent.width - 20px;
+ text: I18n.t("voiceover.scriptPlaceholder");
+ color: Theme.fg-dim;
+ font-size: Theme.fs-input;
+ wrap: word-wrap;
+ }
+
+ // While a take runs: the script read-only, a third of
+ // the way down to start with and climbing from there,
+ // larger, so it reads from arm's length.
+ if root.taking: Text {
+ x: 10px;
+ width: parent.width - 20px;
+ y: parent.height / 3
+ - Math.min(root.seconds * root.prompt-rate * 1px, self.preferred-height);
+ text: root.data.prompt;
+ color: Theme.fg;
+ font-size: 17px;
+ wrap: word-wrap;
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/src/crates/concat/ui/editor.slint b/src/crates/concat/ui/editor.slint
index 79d34d31..7730a86f 100644
--- a/src/crates/concat/ui/editor.slint
+++ b/src/crates/concat/ui/editor.slint
@@ -367,12 +367,24 @@ 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.
+ /// The tray's record button: opens the voiceover panel, closes it, or
+ /// stops the take it is running.
callback record-voiceover();
- /// A voiceover take is running.
+ /// A voiceover take is under way: counting in, recording or paused.
in-out property <bool> recording;
- /// The take's level, `0..1`, for the meter beside the button.
+ /// The microphone while the voiceover panel is open, as positions
+ /// along a meter, `0..1`: the peak (beside the tray's button too) and
+ /// the power. Set by a timer thirty times a second, not by a publish.
in-out property <float> record-level;
+ in-out property <float> record-rms;
+ /// A sample reached the top lately: the panel's clip light.
+ in-out property <bool> record-clipped;
+ /// The take's length so far, pauses left out: the panel's clock and
+ /// what its teleprompter scrolls by.
+ in-out property <float> record-seconds;
+ /// The microphone has given nothing but silence since it opened: a
+ /// system that keeps it from the app tends to hand over zeros.
+ in-out property <bool> record-silent;
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/phone/editor.slint b/src/crates/concat/ui/phone/editor.slint
index f201b08b..36ec063f 100644
--- a/src/crates/concat/ui/phone/editor.slint
+++ b/src/crates/concat/ui/phone/editor.slint
@@ -690,6 +690,17 @@ export component PhoneEditor inherits Rectangle {
label: I18n.t("phone.speak");
clicked => { Editor.speak(); }
}
+ // The voiceover panel, which stands at the foot of the screen
+ // over this bar; the same press puts it away, or stops a take.
+ ToolItem {
+ glyph: Glyph.mic;
+ label: I18n.t("phone.voiceover");
+ current: Editor.recording;
+ clicked => {
+ root.hide();
+ Editor.record-voiceover();
+ }
+ }
ToolItem {
glyph: Glyph.info;
label: I18n.t("phone.project");