hex/crates/capture/src/audio.rs
Dax cdb96f585e
capture: keep all audio in long captures (#1795) (#1894)
* capture: stream audio to disk so long captures keep all of it

A capture's timeline now writes 16 kHz mono PCM16 to its bundle's
audio.wav as it records, with the leading offset and gaps as silence, so
memory stays flat and the 20-minute drop is gone. An 8-hour guard bounds
disk use only; past it the rest is one recorded gap.

A finished capture is transcribed from the WAV in 30 s pieces, the
reader hex transcribe already used (lifted to transcription/pieces.rs),
and each piece's words move onto the capture clock. The Parakeet, Apple
(path-based), and GGUF paths keep every word without holding the
session. The pipeline never rewrites a streamed audio.wav from empty
samples, an iPhone narration is read back where it must be re-based,
and a cancelled capture closes and removes its file.

* capture: say where a capture's audio stopped

A streamed capture keeps all of its audio, but the 8-hour disk guard (or
a failed audio write) still stops it early, and only the process log
said so. The timeline now carries the stop point onto RecordedAudio,
the bundle stores it as audioStoppedAtMs (serde default, so old bundles
load unchanged), and three places say it plainly: summary.md, `hex
capture show`, and `hex capture status`.

The guard records its point at a 1 s test limit, and the summary line is
tested at 12:34 and 8:00:00 so both clock shapes are covered.

* capture: fill the replay's stop point from its bundle

The 15 s replay builds Written too, on macOS only, so the new field
broke the macOS clippy job while Linux never compiled that function.

* capture: keep a recording out of recovery until it stops

Review fixes for the streamed timeline.

A capture now streams to `audio.wav.partial` and renames it to `audio.wav`
in `Timeline::finish`, so a bundle with a movie and an in-progress audio
file is never mistaken for a capture whose build never ran (recover's
orphan rule, Scrawl.app's `scrawl recover`) and retention cleans a crashed
one like any other bundle. Cancel and discard remove the partial; a failed
publish reads it back into memory rather than pointing at a missing file.

Also: a write failure's stop point is the last sample that reached the
file, not the end of the failed chunk; a trim failure counts every written
sample; the capture's words keep one running frame total instead of
adding truncated per-piece millis; an iPhone narration's `since` drains the
decoded samples instead of copying them and treats a missing file as no
audio; the phone and replay paths carry the audio stop point into their
bundles; and empty audio answers `source: "none"`, as `transcribe_with`
does.

Tests: a movie plus partial audio is never owed, retention trashes a
crashed bundle's media, a write failure records its stop point, a missing
streamed file shifts to no samples, and the replay shift moves the stop
point with the clock.

* capture: publish audio.wav only once its build journals the capture

Follow-ups from review.

A capture now streams to audio.wav.partial and keeps that name after it
stops: the partial is renamed to audio.wav right after the build writes
unfinished.json, so audio.wav never exists without a journal, and a
stopped capture waiting in the finish queue no longer looks like an
orphan to Scrawl.app's recover. A partial that cannot take the name is
read back and written by the build, and its partial name removed; the
replay removes the unshifted partial once the narration is read for
shifting.

Also: a periodic header flush error is now a write failure (the rest of
the capture is a gap) rather than a log line; the midpoint of a failed
write records where the file stopped; and the words test cuts pieces at
odd sample counts and computes offsets from the running frame total, so
per-piece millisecond drift would fail it.

Tests: a streamed audio takes its final name only when the build settles
it (and falls back when it cannot), a capture that has not been
journaled is never owed a rebuild, a mid-capture write failure stops
where the file stopped, and the word offsets are exact at odd piece
lengths.

* capture: consume a streamed recording's partial when it is read

Follow-ups from review.

`RecordedAudio::since` and `into_memory` now remove the partial once its
samples are read: an iPhone narration (capture.rs's `host_narration`
path) used to leave the whole streamed file in the finished bundle. The
replay relies on the same path instead of removing it by hand, and the
light zip leaves `audio.wav.partial` out defensively. A read that fails
is an error to `into_memory` (so a build keeps the only copy) while
`since` still treats a missing file as no audio for an iPhone.

A failed publish now reads the audio back only when it produced the
samples the recording had; a failed read keeps the partial and removes
any half-copied `audio.wav`. `publish_audio` takes `&mut self` and points
the recording at the published file.

A journaled bundle whose `audio.wav` is missing adopts `audio.wav.partial`
before rebuilding. Docs say the guarantee is a streamed capture's, and
that a crash while recording or queued is retention's job, not
recovery's.

Tests: reading a streamed recording consumes the partial; a finished
iPhone bundle keeps none; a streamed audio is published only when its
build settles it, including the read-back and unreadable-partial cases; a
journaled capture adopts its partial.

* capture: keep a failed audio publish recoverable

Follow-ups from review.

The publish fallback read the partial with `into_memory`, which deletes
it, and then ignored whether its own write landed: a failed write left
the audio nowhere. It now reads through `read_streamed` (no deletion),
writes `audio.wav` and checks the result, and removes the partial only
once that write succeeded. A failed read or write removes any half
`audio.wav` and fails the build, which is the pipeline's existing failed
path: `recover::finished` runs only for an `Ok` build, so `unfinished.json`
stays and the next launch's recovery adopts the partial instead of the
capture quietly finishing without its audio.

`publish_audio` also treats a landed copy as success even when deleting
the partial fails, logging it rather than reporting failure and letting
the fallback overwrite a good `audio.wav`.

Tests: a blocked target keeps the partial and fails the build; a
fallback write that lands consumes the partial and writes `audio.wav`;
an unreadable partial is kept.
2026-11-16 10:28:54 -05:00

1050 lines
38 KiB
Rust

use std::io::Cursor;
use std::sync::{Arc, Mutex};
use anyhow::{Context, Result, anyhow, bail, ensure};
#[cfg(feature = "mic")]
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
const SAMPLE_RATE: u32 = 16_000;
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GapSpan {
pub start_ms: u64,
pub end_ms: u64,
}
/// Mono audio on the capture's clock. `samples[0]` is `start_offset_ms` after the capture
/// started; spans in `gaps` (also from the capture's start) are silence where audio was
/// missing or dropped.
#[derive(Clone, Debug, Default)]
pub struct RecordedAudio {
pub samples: Vec<f32>,
pub sample_rate: u32,
pub start_offset_ms: u64,
pub gaps: Vec<GapSpan>,
/// Where the samples live when they were streamed to disk: reading them
/// back is only needed by a path that shifts or rewrites the audio.
pub(crate) streamed: Option<std::path::PathBuf>,
/// Where the audio stops on the capture's clock (ms), when Hex had to stop
/// keeping it: a streamed capture's disk guard, or a failed write.
pub(crate) audio_stopped_at_ms: Option<u64>,
pub(crate) sample_count: usize,
pub(crate) duration_ms: u64,
pub(crate) wav_bytes: Vec<u8>,
pub(crate) live: crate::live_transcribe::Slot,
}
impl RecordedAudio {
pub fn new(
samples: Vec<f32>,
sample_rate: u32,
start_offset_ms: u64,
gaps: Vec<GapSpan>,
) -> Self {
let rate = if sample_rate == 0 {
SAMPLE_RATE
} else {
sample_rate
};
let sample_count = samples.len();
let duration_ms = start_offset_ms + (sample_count as u64 * 1_000) / u64::from(rate);
Self {
samples,
sample_rate: rate,
start_offset_ms,
gaps,
streamed: None,
audio_stopped_at_ms: None,
sample_count,
duration_ms,
wav_bytes: Vec::new(),
live: Default::default(),
}
}
/// A recording whose samples stay in `audio.wav` on disk: a capture streams
/// them while it records instead of holding the whole session in memory.
/// `sample_count` counts the samples after `start_offset_ms`, as `samples`
/// would.
pub fn on_disk(
path: &std::path::Path,
sample_count: usize,
sample_rate: u32,
start_offset_ms: u64,
gaps: Vec<GapSpan>,
) -> Self {
let rate = if sample_rate == 0 {
SAMPLE_RATE
} else {
sample_rate
};
Self {
samples: Vec::new(),
sample_rate: rate,
start_offset_ms,
gaps,
streamed: Some(path.to_path_buf()),
audio_stopped_at_ms: None,
sample_count,
duration_ms: start_offset_ms + (sample_count as u64 * 1_000) / u64::from(rate),
wav_bytes: Vec::new(),
live: Default::default(),
}
}
/// Records where the audio stops on the capture's clock, when Hex had to
/// stop keeping it: a streamed capture's disk guard, or a failed write.
#[must_use]
pub fn stopping_audio_at(mut self, ms: Option<u64>) -> Self {
self.audio_stopped_at_ms = ms;
self
}
/// Where the capture's audio stops, when it does not run to the end.
pub fn audio_stopped_at_ms(&self) -> Option<u64> {
self.audio_stopped_at_ms
}
/// Gives a streamed recording its final `audio.wav` name in `bundle_dir`,
/// now that its bundle is journaled. A folder on the same filesystem
/// renames; anything else copies. The partial file stays if this fails, so
/// the caller can read it back itself. On success the recording points at
/// the published file from then on.
pub fn publish_audio(&mut self, bundle_dir: &std::path::Path) -> bool {
let Some(streamed) = &self.streamed else {
return false;
};
let path = bundle_dir.join("audio.wav");
if *streamed == path {
return path.is_file();
}
if std::fs::rename(streamed, &path).is_ok() {
self.streamed = Some(path);
return true;
}
// A copy that lands is a published audio.wav even if the partial cannot
// be deleted: the file is there, and a stale partial is harmless.
match std::fs::copy(streamed, &path) {
Ok(_) => {
if let Err(error) = std::fs::remove_file(streamed) {
crate::log::scrawl_log(format!(
"audio: copied {} but could not remove it: {error}",
streamed.display()
));
}
self.streamed = Some(path);
true
}
Err(_) => false,
}
}
/// Removes a streamed recording's partial file once its samples are in
/// memory or its final file is written. Only a partial name is removed,
/// never a finished `audio.wav`.
pub fn discard_streamed(&self) {
if let Some(path) = &self.streamed {
consume_partial(path);
}
}
/// Whether its samples are already in `audio.wav` on disk, so they are
/// never encoded into `wav_bytes` or read from `samples`.
pub fn is_on_disk(&self) -> bool {
self.streamed.is_some()
}
/// Its samples in memory, read back from the streamed file when they are
/// on disk and kept as they are otherwise. A streamed recording is decoded
/// in full into memory, so only a path that must shift or rewrite the
/// audio (an iPhone narration, a replay) asks for this. Once read, the
/// partial file is removed: its samples are this recording's now.
pub fn into_memory(self) -> Result<Self> {
let Some(path) = self.streamed.clone() else {
return Ok(self);
};
let audio = self.read_streamed()?;
consume_partial(&path);
Ok(audio)
}
/// The same samples as [`Self::into_memory`], without touching the file: a
/// build that must write them elsewhere removes the partial only after its
/// own write succeeded, so a failed write never leaves the audio nowhere.
pub fn read_streamed(&self) -> Result<Self> {
let Some(path) = &self.streamed else {
return Ok(self.clone());
};
let expected = self.sample_count;
let audio = self.clone().shifted_from_file(path, 0)?;
if audio.samples.len() != expected {
bail!(
"{} holds {} samples, not the {expected} it recorded",
path.display(),
audio.samples.len()
);
}
Ok(audio)
}
pub fn sample_count(&self) -> usize {
if !self.samples.is_empty() {
self.samples.len()
} else {
self.sample_count
}
}
pub fn duration_ms(&self) -> u64 {
if self.duration_ms > 0 {
self.duration_ms
} else if !self.samples.is_empty() {
let rate = if self.sample_rate == 0 {
SAMPLE_RATE
} else {
self.sample_rate
};
self.start_offset_ms + (self.samples.len() as u64 * 1_000) / u64::from(rate)
} else if self.sample_count > 0 {
self.start_offset_ms + (self.sample_count as u64 * 1_000) / u64::from(SAMPLE_RATE)
} else {
self.start_offset_ms
}
}
pub fn total_duration_ms(&self) -> u64 {
self.duration_ms()
}
pub fn samples_16k(&self) -> Result<std::borrow::Cow<'_, [f32]>> {
if !self.samples.is_empty() {
if self.sample_rate == 0 || self.sample_rate == SAMPLE_RATE {
return Ok(std::borrow::Cow::Borrowed(&self.samples));
}
return Ok(std::borrow::Cow::Owned(resample_to_16k(
&self.samples,
self.sample_rate,
)));
}
if !self.wav_bytes.is_empty() {
return Ok(std::borrow::Cow::Owned(decode_wav_16k(&self.wav_bytes)?));
}
Ok(std::borrow::Cow::Borrowed(&[]))
}
/// Encodes 16 kHz mono PCM16 WAV bytes. When `start_offset_ms > 0`, leading silence is
/// prepended so `audio.wav` on disk starts at `0 ms` of the capture clock.
pub fn wav_bytes_16k(&self) -> Result<std::borrow::Cow<'_, [u8]>> {
if !self.wav_bytes.is_empty() && self.start_offset_ms == 0 {
return Ok(std::borrow::Cow::Borrowed(&self.wav_bytes));
}
let samples = self.samples_16k()?;
let pad = (self.start_offset_ms * u64::from(SAMPLE_RATE) / 1_000) as usize;
if pad == 0 {
return Ok(std::borrow::Cow::Owned(encode_wav_16k(&samples)?));
}
let mut padded = vec![0.0_f32; pad + samples.len()];
padded[pad..].copy_from_slice(&samples);
Ok(std::borrow::Cow::Owned(encode_wav_16k(&padded)?))
}
/// The same audio on a clock that starts `ms` later (a phone movie's first frame): what came
/// before is dropped, and the gaps move with the clock. A streamed recording is decoded into
/// memory to do it, and its partial file is removed once read.
pub fn since(self, ms: u64) -> Result<Self> {
if let Some(path) = self.streamed.clone() {
let start_offset_ms = self.start_offset_ms;
let gaps = self.gaps.clone();
let stopped = self.audio_stopped_at_ms;
return match self.shifted_from_file(&path, ms) {
Ok(audio) => {
consume_partial(&path);
Ok(audio)
}
// No audio to shift (gone or unreadable): a phone capture still
// finishes with its video and transcript.
Err(error) => {
crate::log::scrawl_log(format!(
"audio: could not read {}: {error:#}",
path.display()
));
Ok(Self::new(
Vec::new(),
SAMPLE_RATE,
start_offset_ms.saturating_sub(ms),
shifted_gaps(gaps, ms),
)
.stopping_audio_at(stopped.map(|at| at.saturating_sub(ms))))
}
};
}
if ms == 0 {
return Ok(self);
}
let (mut samples, rate) = if self.samples.is_empty() {
(self.samples_16k()?.into_owned(), SAMPLE_RATE)
} else {
let rate = if self.sample_rate == 0 {
SAMPLE_RATE
} else {
self.sample_rate
};
(self.samples, rate)
};
let start_offset_ms = self.start_offset_ms.saturating_sub(ms);
let skip_ms = ms.saturating_sub(self.start_offset_ms);
let skip = usize::try_from(skip_ms * u64::from(rate) / 1_000).unwrap_or(usize::MAX);
samples.drain(..skip.min(samples.len()));
let gaps = shifted_gaps(self.gaps, ms);
let stopped = self.audio_stopped_at_ms.map(|at| at.saturating_sub(ms));
Ok(Self::new(samples, rate, start_offset_ms, gaps).stopping_audio_at(stopped))
}
/// [`Self::since`] for a recording streamed to `path`: reads it back into
/// memory and drops the audio before `ms`, exactly as the in-memory shift
/// does. A file that cannot be read or decoded is an error; each caller
/// decides whether that is no audio (an iPhone) or a failed read (a build).
fn shifted_from_file(self, path: &std::path::Path, ms: u64) -> Result<Self> {
let bytes =
std::fs::read(path).with_context(|| format!("could not read {}", path.display()))?;
let mut samples = decode_wav_16k(&bytes)?;
let lead = (self.start_offset_ms * u64::from(SAMPLE_RATE) / 1_000) as usize;
samples.drain(..lead.min(samples.len()));
let skip_ms = ms.saturating_sub(self.start_offset_ms);
let skip = usize::try_from(skip_ms * u64::from(SAMPLE_RATE) / 1_000).unwrap_or(usize::MAX);
samples.drain(..skip.min(samples.len()));
let start_offset_ms = self.start_offset_ms.saturating_sub(ms);
let gaps = shifted_gaps(self.gaps, ms);
let stopped = self.audio_stopped_at_ms.map(|at| at.saturating_sub(ms));
Ok(Self::new(samples, SAMPLE_RATE, start_offset_ms, gaps).stopping_audio_at(stopped))
}
pub fn set_live(&self, live: Option<crate::live_transcribe::Live>) {
self.live.set(live);
}
pub fn take_live(&self) -> Option<crate::live_transcribe::Live> {
self.live.take()
}
}
fn shifted_gaps(gaps: Vec<GapSpan>, ms: u64) -> Vec<GapSpan> {
gaps.iter()
.filter(|gap| gap.end_ms > ms)
.map(|gap| GapSpan {
start_ms: gap.start_ms.saturating_sub(ms),
end_ms: gap.end_ms - ms,
})
.collect()
}
/// Removes a streamed recording's file once its samples were read into memory.
/// Only the partial name goes: a published `audio.wav` is the bundle's.
fn consume_partial(path: &std::path::Path) {
if path
.file_name()
.is_some_and(|name| name == crate::recover::PARTIAL_AUDIO)
{
let _ = std::fs::remove_file(path);
}
}
fn resample_to_16k(samples: &[f32], rate: u32) -> Vec<f32> {
if rate == 0 || rate == SAMPLE_RATE {
return samples.to_vec();
}
let mut output = Vec::with_capacity(
(samples.len() as u64 * u64::from(SAMPLE_RATE) / u64::from(rate)) as usize + 1,
);
let mut phase = 0_u32;
let mut sum = 0.0_f64;
for &sample in samples {
let mono = if sample.is_finite() {
f64::from(sample)
} else {
0.0
};
let mut remaining = SAMPLE_RATE;
while remaining > 0 {
let weight = remaining.min(rate - phase);
sum += mono * f64::from(weight);
phase += weight;
remaining -= weight;
if phase == rate {
output.push((sum / f64::from(rate)) as f32);
phase = 0;
sum = 0.0;
}
}
}
output
}
pub struct AudioRecorder {
worker: Option<std::thread::JoinHandle<Result<()>>>,
stop_sender: Option<std::sync::mpsc::Sender<()>>,
samples: Arc<Mutex<Vec<f32>>>,
error: Arc<Mutex<Option<String>>>,
live: Option<crate::live_transcribe::Live>,
}
impl AudioRecorder {
#[cfg(not(feature = "mic"))]
pub fn start() -> Result<Self> {
bail!("Built-in microphone recording requires the `mic` feature")
}
#[cfg(feature = "mic")]
pub fn start() -> Result<Self> {
let started = std::time::Instant::now();
let samples = Arc::new(Mutex::new(Vec::new()));
let error = Arc::new(Mutex::new(None));
let (stop_sender, stop_receiver) = std::sync::mpsc::channel();
let worker_samples = Arc::clone(&samples);
let worker_error = Arc::clone(&error);
let worker = std::thread::Builder::new()
.name("scrawl-audio".into())
.spawn(move || {
let stream =
Self::open_stream(worker_samples, worker_error).inspect_err(|error| {
crate::log::scrawl_log(format!("Microphone startup failed: {error:#}"));
})?;
crate::log::start_metric("audio_ready_ms", started);
// Stream never crosses threads. Disconnect also stops abandoned recorders.
let _ = stop_receiver.recv();
drop(stream);
Ok(())
})
.context("Could not spawn microphone worker")?;
let live = crate::live_transcribe::wanted()
.then(|| crate::live_transcribe::Live::start(Arc::clone(&samples)))
.and_then(|live| {
live.inspect_err(|error| {
crate::log::scrawl_log(format!("Live transcription: {error:#}"));
})
.ok()
});
Ok(Self {
worker: Some(worker),
stop_sender: Some(stop_sender),
samples,
error,
live,
})
}
/// The chosen microphone (`mic`), else the macOS default. A chosen device that is missing or
/// won't open never stops the recording.
#[cfg(feature = "mic")]
fn open_stream(
samples: Arc<Mutex<Vec<f32>>>,
error: Arc<Mutex<Option<String>>>,
) -> Result<cpal::Stream> {
let choice = crate::mic::choice();
if let Some(choice) = &choice {
if let Some(device) = crate::mic::device(&choice.id) {
let input = crate::mic::Input {
id: choice.id.clone(),
name: device_name(&device).unwrap_or_else(|| choice.name.clone()),
};
crate::mic::note_pick(&crate::mic::Pick::Chosen(&input));
match Self::open_device(&device, samples.clone(), error.clone()) {
Ok(stream) => {
crate::log::scrawl_log(format!("Microphone: {}", input.name));
return Ok(stream);
}
Err(e) => crate::log::scrawl_log(format!(
"Microphone: could not open {} ({e:#}); using the default",
input.name
)),
}
} else {
let default = cpal::default_host()
.default_input_device()
.and_then(|device| {
Some(crate::mic::Input {
id: device.id().ok()?.id().to_owned(),
name: device_name(&device)?,
})
});
let inputs = crate::mic::Inputs {
default: default.as_ref().map(|d| d.id.clone()),
devices: default.into_iter().collect(),
};
crate::mic::note_pick(&crate::mic::Pick::new(Some(choice), &inputs));
}
}
let device = cpal::default_host()
.default_input_device()
.context("No microphone is available")?;
let stream = Self::open_device(&device, samples, error)?;
crate::log::scrawl_log(format!(
"Microphone: {} (default)",
device_name(&device).unwrap_or_default()
));
Ok(stream)
}
#[cfg(feature = "mic")]
fn open_device(
device: &cpal::Device,
samples: Arc<Mutex<Vec<f32>>>,
error: Arc<Mutex<Option<String>>>,
) -> Result<cpal::Stream> {
let supported = device.default_input_config()?;
let config = supported.config();
crate::log::scrawl_log(format!(
"Microphone: {} Hz, {} ch, {:?}",
config.sample_rate,
config.channels,
supported.sample_format()
));
ensure!(
config.channels > 0 && config.sample_rate > 0,
"Invalid microphone format"
);
macro_rules! stream {
($ty:ty) => {
input_stream::<$ty>(&device, config, samples.clone(), error.clone())?
};
}
let stream = match supported.sample_format() {
cpal::SampleFormat::F32 => stream!(f32),
cpal::SampleFormat::F64 => stream!(f64),
cpal::SampleFormat::I8 => stream!(i8),
cpal::SampleFormat::I16 => stream!(i16),
cpal::SampleFormat::I24 => stream!(cpal::I24),
cpal::SampleFormat::I32 => stream!(i32),
cpal::SampleFormat::I64 => stream!(i64),
cpal::SampleFormat::U8 => stream!(u8),
cpal::SampleFormat::U16 => stream!(u16),
cpal::SampleFormat::U24 => stream!(cpal::U24),
cpal::SampleFormat::U32 => stream!(u32),
cpal::SampleFormat::U64 => stream!(u64),
format => bail!("Unsupported microphone format: {format}"),
};
stream.play().context("Could not start microphone")?;
Ok(stream)
}
fn join_worker(&mut self) -> Result<()> {
self.stop_sender.take();
if let Some(worker) = self.worker.take() {
worker
.join()
.map_err(|_| anyhow!("Microphone worker panicked"))??;
}
Ok(())
}
pub fn stop(mut self) -> Result<RecordedAudio> {
// Joining drops the stream and stops its callback before taking the buffer,
// including a stop requested while the device was still being initialized.
self.join_worker()?;
let error = self
.error
.lock()
.map_err(|_| anyhow!("Microphone error lock poisoned"))?
.take();
let samples_16k = std::mem::take(
&mut *self
.samples
.lock()
.map_err(|_| anyhow!("Microphone buffer lock poisoned"))?,
);
// An overload, or a device unplugged partway, keeps what was heard before it.
if let Some(error) = error {
if samples_16k.is_empty() {
bail!("Microphone capture failed: {error}");
}
crate::log::scrawl_log(format!("Microphone: {error}; keeping what it heard"));
}
let sample_count = samples_16k.len();
let duration_ms = sample_count as u64 * 1_000 / SAMPLE_RATE as u64;
let wav_bytes = encode_wav_16k(&samples_16k)?;
Ok(RecordedAudio {
samples: Vec::new(),
sample_rate: SAMPLE_RATE,
start_offset_ms: 0,
gaps: Vec::new(),
streamed: None,
audio_stopped_at_ms: None,
sample_count,
duration_ms,
wav_bytes,
live: crate::live_transcribe::Slot::new(self.live.take()),
})
}
}
impl Drop for AudioRecorder {
fn drop(&mut self) {
let _ = self.join_worker();
}
}
#[cfg(feature = "mic")]
fn device_name(device: &cpal::Device) -> Option<String> {
Some(device.description().ok()?.name().to_owned())
}
#[cfg(feature = "mic")]
fn input_stream<T>(
device: &cpal::Device,
config: cpal::StreamConfig,
samples: Arc<Mutex<Vec<f32>>>,
error: Arc<Mutex<Option<String>>>,
) -> Result<cpal::Stream>
where
T: cpal::SizedSample,
f32: cpal::FromSample<T>,
{
let channels = usize::from(config.channels);
let rate = config.sample_rate;
let mut phase = 0_u32;
let mut sum = 0.0_f64;
Ok(device.build_input_stream::<T, _, _>(
config,
move |data, _| {
let Ok(mut output) = samples.lock() else {
return;
};
for frame in data.chunks_exact(channels) {
let mono = frame
.iter()
.map(|sample| sample.to_sample::<f32>() as f64)
.sum::<f64>()
/ channels as f64;
let mono = if mono.is_finite() { mono } else { 0.0 };
// Area averaging gives a continuous-phase downmix/decimator,
// including non-integer ratios such as 44.1 kHz -> 16 kHz.
let mut remaining = SAMPLE_RATE;
while remaining > 0 {
let weight = remaining.min(rate - phase);
sum += mono * weight as f64;
phase += weight;
remaining -= weight;
if phase == rate {
output.push((sum / rate as f64) as f32);
phase = 0;
sum = 0.0;
}
}
}
},
move |err| {
// A buffer under- or overrun drops a few samples; the recording goes on.
if err.kind() == cpal::ErrorKind::Xrun {
return;
}
if let Ok(mut error) = error.lock() {
*error = Some(err.to_string());
}
},
None,
)?)
}
/// Reads a 16 kHz mono WAV (as written by `scrawl-helper audio`) back into a recording.
pub fn recorded_audio_from_wav(wav_bytes: Vec<u8>) -> Result<RecordedAudio> {
let sample_count = wav_16k_reader(&wav_bytes)?.duration() as usize;
Ok(RecordedAudio {
samples: Vec::new(),
sample_rate: SAMPLE_RATE,
start_offset_ms: 0,
gaps: Vec::new(),
streamed: None,
audio_stopped_at_ms: None,
sample_count,
duration_ms: sample_count as u64 * 1_000 / u64::from(SAMPLE_RATE),
wav_bytes,
live: Default::default(),
})
}
/// Decodes a 16 kHz mono 16-bit WAV (this module's own format) into samples.
pub fn decode_wav_16k(wav_bytes: &[u8]) -> Result<Vec<f32>> {
wav_16k_reader(wav_bytes)?
.into_samples::<i16>()
.map(|sample| Ok(f32::from(sample?) / 32_768.0))
.collect()
}
/// Decodes a 16 kHz mono 16-bit WAV into its raw samples.
pub fn decode_wav_pcm16(wav_bytes: &[u8]) -> Result<Vec<i16>> {
Ok(wav_16k_reader(wav_bytes)?
.into_samples::<i16>()
.collect::<Result<_, _>>()?)
}
fn wav_16k_reader(wav_bytes: &[u8]) -> Result<hound::WavReader<Cursor<&[u8]>>> {
let reader = hound::WavReader::new(Cursor::new(wav_bytes))?;
let spec = reader.spec();
ensure!(
spec.sample_rate == SAMPLE_RATE
&& spec.channels == 1
&& spec.bits_per_sample == 16
&& spec.sample_format == hound::SampleFormat::Int,
"Expected 16 kHz mono 16-bit audio"
);
Ok(reader)
}
const ISLAND_WINDOW_MS: u64 = 50;
const ISLAND_MERGE_SILENCE_MS: u64 = 350;
/// The lowest speech threshold (about -56 dBFS): a quiet microphone's speech can sit well under
/// the old 0.005 floor while still being clearly above its own silence.
const ISLAND_MIN_THRESHOLD: f64 = 0.0015;
const ISLAND_MAX_THRESHOLD: f64 = 0.02;
/// Never speech, whatever the recording's levels (about -66 dBFS): keeps a recording that is
/// mostly digital silence (padded gaps) from counting faint hiss as speech.
const ISLAND_SILENCE_RMS: f64 = 0.0005;
/// Energy-based speech spans in milliseconds, quantized to 50 ms. These are not recognizer
/// timestamps. The speech threshold follows the recording's own noise floor (10th percentile of
/// window energy) so a quiet microphone and a noisy room both find their speech, and never sits
/// above half the recording's speech level (90th percentile), so quiet speech is not dropped,
/// while staying at least twice the floor.
pub fn speech_islands(samples_16k: &[f32]) -> Vec<(u64, u64)> {
let window = (u64::from(SAMPLE_RATE) * ISLAND_WINDOW_MS / 1_000) as usize;
let rms: Vec<f64> = samples_16k
.chunks(window)
.map(|chunk| {
(chunk
.iter()
.map(|&x| {
if x.is_finite() {
f64::from(x).powi(2)
} else {
0.0
}
})
.sum::<f64>()
/ chunk.len() as f64)
.sqrt()
})
.collect();
if rms.is_empty() {
return Vec::new();
}
let mut sorted = rms.clone();
sorted.sort_by(f64::total_cmp);
let floor = sorted[sorted.len() / 10];
let speech = sorted[sorted.len() * 9 / 10];
let threshold = (floor * 3.0)
.clamp(ISLAND_MIN_THRESHOLD, ISLAND_MAX_THRESHOLD)
.min(speech * 0.5)
.max(floor * 2.0)
.max(ISLAND_SILENCE_RMS);
let mut islands: Vec<(u64, u64)> = Vec::new();
for (index, &level) in rms.iter().enumerate() {
if level <= threshold {
continue;
}
let start = index as u64 * ISLAND_WINDOW_MS;
let end = start + ISLAND_WINDOW_MS;
match islands.last_mut() {
Some(last) if start.saturating_sub(last.1) < ISLAND_MERGE_SILENCE_MS => last.1 = end,
_ => islands.push((start, end)),
}
}
let duration = samples_16k.len() as u64 * 1_000 / u64::from(SAMPLE_RATE);
for island in &mut islands {
island.1 = island.1.min(duration);
}
islands.retain(|&(a, b)| b > a);
islands
}
/// One sample as `audio.wav` stores it.
pub fn pcm16(sample: f32) -> i16 {
let sample = if sample.is_finite() {
sample.clamp(-1.0, 1.0)
} else {
0.0
};
(sample * 32_768.0).round().clamp(-32_768.0, 32_767.0) as i16
}
pub fn encode_wav_16k(samples_16k: &[f32]) -> Result<Vec<u8>> {
let mut bytes = Cursor::new(Vec::with_capacity(44 + samples_16k.len() * 2));
{
let mut writer = hound::WavWriter::new(
&mut bytes,
hound::WavSpec {
channels: 1,
sample_rate: SAMPLE_RATE,
bits_per_sample: 16,
sample_format: hound::SampleFormat::Int,
},
)?;
let mut i16_writer = writer.get_i16_writer(samples_16k.len() as u32);
for &sample in samples_16k {
i16_writer.write_sample(pcm16(sample));
}
i16_writer.flush()?;
writer.finalize()?;
}
Ok(bytes.into_inner())
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::Duration;
#[test]
fn stop_joins_worker_before_reading_its_last_samples() {
let samples = Arc::new(Mutex::new(Vec::new()));
let output = Arc::clone(&samples);
let (stop_sender, stop_receiver) = std::sync::mpsc::channel();
let worker = std::thread::spawn(move || {
// Model a final callback flushed while the worker drops its stream.
assert!(matches!(
stop_receiver.recv_timeout(Duration::from_secs(2)),
Err(std::sync::mpsc::RecvTimeoutError::Disconnected)
));
output.lock().unwrap().extend([0.1, 0.2, 0.3]);
Ok(())
});
let audio = AudioRecorder {
worker: Some(worker),
stop_sender: Some(stop_sender),
samples,
error: Arc::new(Mutex::new(None)),
live: None,
}
.stop()
.unwrap();
assert_eq!(audio.sample_count(), 3);
let wav = audio.wav_bytes_16k().unwrap();
assert_eq!(
hound::WavReader::new(Cursor::new(&*wav))
.unwrap()
.duration(),
3
);
}
#[test]
fn a_device_lost_partway_keeps_what_it_heard() {
let recorder = |samples: Vec<f32>| AudioRecorder {
worker: None,
stop_sender: None,
samples: Arc::new(Mutex::new(samples)),
error: Arc::new(Mutex::new(Some("Device disconnected".into()))),
live: None,
};
assert_eq!(recorder(vec![0.1; 160]).stop().unwrap().sample_count(), 160);
assert!(recorder(Vec::new()).stop().is_err());
}
#[test]
fn stop_propagates_background_initialization_failure() {
let recorder = AudioRecorder {
worker: Some(std::thread::spawn(|| bail!("device unavailable"))),
stop_sender: None,
samples: Arc::new(Mutex::new(Vec::new())),
error: Arc::new(Mutex::new(None)),
live: None,
};
assert!(
recorder
.stop()
.unwrap_err()
.to_string()
.contains("device unavailable")
);
}
#[test]
fn speech_islands_merge_only_short_silences() {
let mut samples = vec![0.0; 32_000];
samples[1_600..4_800].fill(0.2); // 100..300
samples[8_800..12_800].fill(0.2); // 550..800: merge 250 ms gap
samples[18_400..20_800].fill(0.2); // 1150..1300: keep 350 ms gap
assert_eq!(speech_islands(&samples), vec![(100, 800), (1_150, 1_300)]);
assert!(speech_islands(&[0.001; 800]).is_empty());
assert!(speech_islands(&[]).is_empty());
}
#[test]
fn speech_islands_adapt_to_a_noisy_floor() {
let mut samples: Vec<f32> = (0..32_000)
.map(|i| if i % 2 == 0 { 0.006 } else { -0.006 })
.collect();
samples[8_000..16_000]
.iter_mut()
.for_each(|s| *s = if *s > 0.0 { 0.15 } else { -0.15 });
assert_eq!(speech_islands(&samples), vec![(500, 1_000)]);
}
#[test]
fn speech_islands_keep_quiet_speech() {
// A quiet microphone: hiss at 0.0003, speech at 0.003, under the old 0.005 minimum.
let mut samples: Vec<f32> = (0..32_000)
.map(|i| if i % 2 == 0 { 0.0003 } else { -0.0003 })
.collect();
samples[8_000..16_000]
.iter_mut()
.for_each(|s| *s = if *s > 0.0 { 0.003 } else { -0.003 });
assert_eq!(speech_islands(&samples), vec![(500, 1_000)]);
// Mostly digital silence with faint hiss is still not speech.
let mut padded = vec![0.0_f32; 32_000];
padded[8_000..9_600].fill(0.0002);
assert!(speech_islands(&padded).is_empty());
}
#[test]
fn decoded_wav_round_trips() {
let wav = encode_wav_16k(&[0.0, 0.5, -0.5]).unwrap();
assert_eq!(decode_wav_16k(&wav).unwrap(), vec![0.0, 0.5, -0.5]);
assert!(decode_wav_16k(b"nope").is_err());
}
#[test]
fn wav_is_mono_16k_pcm_and_clips_safely() {
let bytes = encode_wav_16k(&[-2.0, -0.5, 0.0, 0.5, 2.0, f32::NAN]).unwrap();
let mut reader = hound::WavReader::new(Cursor::new(bytes)).unwrap();
assert_eq!(reader.spec().channels, 1);
assert_eq!(reader.spec().sample_rate, 16_000);
assert_eq!(reader.spec().bits_per_sample, 16);
assert_eq!(reader.spec().sample_format, hound::SampleFormat::Int);
assert_eq!(
reader
.samples::<i16>()
.collect::<std::result::Result<Vec<_>, _>>()
.unwrap(),
vec![-32_768, -16_384, 0, 16_384, 32_767, 0]
);
}
#[test]
fn since_moves_audio_and_gaps_onto_a_later_clock() {
let gaps = vec![
GapSpan {
start_ms: 20,
end_ms: 40,
},
GapSpan {
start_ms: 90,
end_ms: 120,
},
];
let audio = RecordedAudio::new(vec![0.25; 3_200], 16_000, 50, gaps);
let later = audio.clone().since(100).unwrap();
assert_eq!(later.start_offset_ms, 0);
assert_eq!(later.samples.len(), 3_200 - 800);
assert_eq!(
later.gaps,
vec![GapSpan {
start_ms: 0,
end_ms: 20
}]
);
assert_eq!(later.duration_ms(), 150);
let earlier = audio.since(30).unwrap();
assert_eq!(earlier.start_offset_ms, 20);
assert_eq!(earlier.samples.len(), 3_200);
}
#[test]
fn wav_bytes_16k_pads_leading_silence_for_start_offset() {
let audio = RecordedAudio::new(vec![0.5; 160], 16_000, 100, Vec::new());
let wav = audio.wav_bytes_16k().unwrap();
let decoded = decode_wav_16k(&wav).unwrap();
// 100 ms of leading silence (1_600 samples) + 160 samples = 1_760 samples.
assert_eq!(decoded.len(), 1_760);
assert!(decoded[..1_600].iter().all(|&s| s == 0.0));
assert!(decoded[1_600..].iter().all(|&s| (s - 0.5).abs() < 0.01));
}
#[test]
fn audio_streamed_to_disk_counts_its_samples_and_can_be_read_back() {
let dir = std::env::temp_dir().join(format!("hex-audio-streamed-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join(crate::recover::PARTIAL_AUDIO);
// 250 ms of leading silence and 1 s of audio at 16 kHz.
let mut padded = vec![0.0_f32; 4_000];
padded.extend(vec![0.5_f32; 16_000]);
// Each read consumes the file, so a fresh one is written before every
// case, as a later capture would.
let write = || std::fs::write(&path, encode_wav_16k(&padded).unwrap()).unwrap();
let streamed = || {
RecordedAudio::on_disk(
&path,
16_000,
16_000,
250,
vec![GapSpan {
start_ms: 1_000,
end_ms: 2_000,
}],
)
};
write();
let audio = streamed();
assert!(audio.is_on_disk());
assert!(audio.samples.is_empty() && audio.wav_bytes.is_empty());
assert_eq!(audio.sample_count(), 16_000);
// 250 ms before the first sample + 1 s of samples.
assert_eq!(audio.duration_ms(), 1_250);
assert_eq!(audio.gaps.len(), 1);
let read_back = audio.clone().into_memory().unwrap();
assert!(!read_back.is_on_disk());
assert_eq!(read_back.samples.len(), 16_000);
assert_eq!(read_back.start_offset_ms, 250);
assert!(!path.exists(), "reading it consumed the partial file");
// A zero shift still reads it back, because the caller rewrites the
// file (the phone path) rather than keeping the streamed one.
write();
let unchanged = streamed().since(0).unwrap();
assert!(!unchanged.is_on_disk());
assert_eq!(unchanged.samples.len(), 16_000);
assert_eq!(unchanged.start_offset_ms, 250);
assert!(!path.exists(), "reading it consumed the partial file");
// The phone path drops the first 300 ms: 50 ms of samples go, and the
// gaps move with the clock.
write();
let shifted = streamed().since(300).unwrap();
assert!(!shifted.is_on_disk());
assert_eq!(shifted.start_offset_ms, 0);
assert_eq!(shifted.samples.len(), 15_200);
assert_eq!(
shifted.gaps,
vec![GapSpan {
start_ms: 700,
end_ms: 1_700
}]
);
let _ = std::fs::remove_file(&path);
let _ = std::fs::remove_dir_all(&dir);
assert!(!RecordedAudio::new(vec![0.5; 160], 16_000, 0, Vec::new()).is_on_disk());
}
#[test]
fn a_streamed_recording_whose_file_is_gone_has_no_samples() {
let missing =
std::env::temp_dir().join(format!("hex-audio-gone-{}.wav", std::process::id()));
let _ = std::fs::remove_file(&missing);
// A phone capture's narration can outlive its streamed file (or never
// have one): that is no audio, not a failed capture.
let shifted = RecordedAudio::on_disk(&missing, 16_000, 16_000, 0, Vec::new())
.since(500)
.unwrap();
assert!(shifted.samples.is_empty());
assert!(!shifted.is_on_disk());
assert_eq!(shifted.sample_count(), 0);
// A build that needs the audio itself is told the read failed, so it
// can keep the partial instead of writing an empty `audio.wav`.
assert!(
RecordedAudio::on_disk(&missing, 16_000, 16_000, 0, Vec::new())
.into_memory()
.is_err()
);
}
}