Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(editor): offline audio output for verification harnesses

Richie McIlroyf9855c3a899f
diff --git a/crates/editor/Cargo.toml b/crates/editor/Cargo.toml
index e0bc091d4..5091c32fc 100644
--- a/crates/editor/Cargo.toml
+++ b/crates/editor/Cargo.toml
@@ -26,6 +26,10 @@ path = "examples/audio-output-idle-benchmark.rs"
name = "editor-startup-benchmark"
path = "examples/editor-startup-benchmark.rs"
+[features]
+# Offline audio output for the cap-verify suite. Never enabled by the app.
+test-hooks = []
+
[dependencies]
cap-utils = { path = "../utils" }
cap-media = { path = "../media" }
diff --git a/crates/editor/src/audio.rs b/crates/editor/src/audio.rs
index f15188a1d..3204f8924 100644
--- a/crates/editor/src/audio.rs
+++ b/crates/editor/src/audio.rs
@@ -1687,6 +1687,26 @@ impl<T: FromSampleBytes + cpal::FromSample<f32>> PrerenderedAudioBuffer<T> {
}
}
+ /// Blocks until the next `samples` reads are rendered (or the render
+ /// finished or failed). Returns false on timeout or failure.
+ #[cfg(feature = "test-hooks")]
+ pub(crate) fn wait_until_rendered(&self, samples: usize, timeout: std::time::Duration) -> bool {
+ let deadline = std::time::Instant::now() + timeout;
+ loop {
+ let ready = match &self.mode {
+ PrerenderedAudioBufferMode::Progressive(buffer) => buffer.rendered(samples),
+ PrerenderedAudioBufferMode::Streaming(buffer) => buffer.rendered(samples),
+ };
+ match ready {
+ Some(ready) if !ready && std::time::Instant::now() < deadline => {
+ std::thread::sleep(std::time::Duration::from_micros(200));
+ }
+ Some(ready) => return ready,
+ None => return false,
+ }
+ }
+ }
+
pub fn set_playhead(&mut self, playhead_secs: f64) {
match &mut self.mode {
PrerenderedAudioBufferMode::Progressive(buffer) => buffer.set_playhead(playhead_secs),
@@ -1845,6 +1865,35 @@ impl<T: FromSampleBytes + cpal::FromSample<f32>> ProgressiveAudioBuffer<T> {
}
}
+ /// Whether the next `samples` reads are rendered; `None` once the
+ /// render can no longer produce them.
+ #[cfg(feature = "test-hooks")]
+ fn rendered(&self, samples: usize) -> Option<bool> {
+ let timeline = &self.timeline;
+ let start = self.read_position.min(timeline.samples.len());
+ let end = (self.read_position + samples).min(timeline.samples.len());
+ if start >= end || timeline.complete.load(Ordering::Acquire) {
+ return Some(true);
+ }
+ let primary_end = timeline.primary_end.load(Ordering::Acquire);
+ let wrap_end = timeline.wrap_end.load(Ordering::Acquire);
+ let primary = timeline.primary_start;
+ let covered = if start >= primary {
+ primary_end >= end
+ } else if end <= primary {
+ wrap_end >= end
+ } else {
+ wrap_end >= primary && primary_end >= end
+ };
+ if covered {
+ Some(true)
+ } else if timeline.stop.load(Ordering::Acquire) {
+ None
+ } else {
+ Some(false)
+ }
+ }
+
pub fn set_playhead(&mut self, playhead_secs: f64) {
let sample_position = (playhead_secs * self.sample_rate as f64) as usize * self.channels;
self.read_position = sample_position.min(self.timeline.samples.len());
@@ -2056,6 +2105,18 @@ impl<T: FromSampleBytes + cpal::FromSample<f32>> StreamingAudioBuffer<T> {
}
}
+ #[cfg(feature = "test-hooks")]
+ fn rendered(&self, samples: usize) -> Option<bool> {
+ if self.timeline.failed.load(Ordering::Acquire) {
+ return None;
+ }
+ Some(
+ self.timeline.published_generation.load(Ordering::Acquire) == self.generation
+ && self.timeline.published_end.load(Ordering::Acquire)
+ >= self.read_position + samples,
+ )
+ }
+
fn set_playhead(&mut self, playhead_secs: f64) {
let position =
output_sample_index(playhead_secs, self.sample_rate, self.channels, usize::MAX);
diff --git a/crates/editor/src/audio_output.rs b/crates/editor/src/audio_output.rs
index f93c3958c..d7d5f7218 100644
--- a/crates/editor/src/audio_output.rs
+++ b/crates/editor/src/audio_output.rs
@@ -875,6 +875,23 @@ fn drain_source_commands<T: FromSampleBytes + cpal::FromSample<f32>>(
}
}
+/// Re-anchors the audio on the video playhead when they drift apart.
+fn sync_video_playhead<T: FromSampleBytes + cpal::FromSample<f32>>(
+ audio: &mut PrerenderedAudioBuffer<T>,
+ playhead_rx: &mut watch::Receiver<f64>,
+ latency_secs: f64,
+) {
+ if playhead_rx.has_changed().unwrap_or(false) {
+ let video_playhead = *playhead_rx.borrow_and_update();
+ let audible_playhead = audio.current_audible_playhead(latency_secs);
+ let drift = (video_playhead - audible_playhead).abs();
+
+ if drift > 0.04 {
+ audio.set_playhead(video_playhead + latency_secs);
+ }
+ }
+}
+
/// Renders one output block from the active source: applies the video
/// playhead sync policy, fills the buffer and acknowledges the first
/// consumed block. Shared by the live cpal callback and the headless sink so
@@ -894,15 +911,7 @@ fn render_source_block<T: FromSampleBytes + cpal::FromSample<f32>>(
}
match &mut source.buffer {
ActiveSourceBuffer::Ordinary(audio) => {
- if source.playhead_rx.has_changed().unwrap_or(false) {
- let video_playhead = *source.playhead_rx.borrow_and_update();
- let audible_playhead = audio.current_audible_playhead(latency_secs);
- let drift = (video_playhead - audible_playhead).abs();
-
- if drift > 0.04 {
- audio.set_playhead(video_playhead + latency_secs);
- }
- }
+ sync_video_playhead(audio, &mut source.playhead_rx, latency_secs);
audio.fill(buffer);
}
ActiveSourceBuffer::Preparing(audio) => {
@@ -1274,6 +1283,129 @@ fn control_thread_headless(control_rx: std_mpsc::Receiver<ControlMsg>, mut tap:
info!("Headless audio output thread finished");
}
+/// A sink with no device and no clock, for verification harnesses: the
+/// caller pulls every block, and each pull first waits until the samples it
+/// reads are rendered, so the PCM depends only on the sequence of plays,
+/// seeks and pulls, never on render speed. Sources are built by the same
+/// `install_source` as the device and headless sinks.
+#[cfg(feature = "test-hooks")]
+pub struct OfflineAudioSink {
+ source_rx: std_mpsc::Receiver<SourceCommand<f32>>,
+ active: Option<ActiveSource<f32>>,
+}
+
+#[cfg(feature = "test-hooks")]
+impl AudioOutput {
+ /// Output at [`HEADLESS_SAMPLE_RATE`] / [`HEADLESS_CHANNELS`] whose blocks
+ /// are pulled through the returned sink. `play` returns once the source
+ /// is installed.
+ pub fn new_offline() -> (Self, OfflineAudioSink) {
+ let (control_tx, control_rx) = std_mpsc::channel();
+ let (source_tx, source_rx) = std_mpsc::channel();
+ if let Err(e) = std::thread::Builder::new()
+ .name("cap-audio-offline".into())
+ .spawn(move || control_thread_offline(control_rx, source_tx))
+ {
+ error!("Failed to spawn offline audio output thread: {e}");
+ }
+ (
+ Self {
+ control_tx,
+ next_generation: AtomicU64::new(0),
+ },
+ OfflineAudioSink {
+ source_rx,
+ active: None,
+ },
+ )
+ }
+}
+
+#[cfg(feature = "test-hooks")]
+impl OfflineAudioSink {
+ /// Renders the next interleaved block. Returns false (and silence) when
+ /// no source is installed or its samples did not render within
+ /// `timeout`.
+ pub fn pull(&mut self, block: &mut [f32], timeout: Duration) -> bool {
+ drain_source_commands(&mut self.active, &self.source_rx);
+ let Some(source) = self.active.as_mut() else {
+ block.fill(0.0);
+ return false;
+ };
+ let mut rendered = true;
+ if let ActiveSourceBuffer::Ordinary(audio) = &mut source.buffer {
+ sync_video_playhead(audio, &mut source.playhead_rx, 0.0);
+ rendered = audio.wait_until_rendered(block.len(), timeout);
+ }
+ render_source_block(source, block, 0.0);
+ rendered
+ }
+}
+
+#[cfg(feature = "test-hooks")]
+fn control_thread_offline(
+ control_rx: std_mpsc::Receiver<ControlMsg>,
+ source_tx: std_mpsc::Sender<SourceCommand<f32>>,
+) {
+ let output_info = AudioInfo::new_raw(
+ AudioData::SAMPLE_FORMAT,
+ HEADLESS_SAMPLE_RATE,
+ HEADLESS_CHANNELS,
+ );
+ while let Ok(msg) = control_rx.recv() {
+ match msg {
+ ControlMsg::Refresh {
+ spec,
+ generation,
+ revision,
+ retire_tx,
+ } => {
+ if let Err(error) = install_source::<f32>(
+ spec,
+ generation,
+ SourceAcknowledgement::Refresh(retire_tx, revision),
+ output_info,
+ false,
+ &source_tx,
+ ) {
+ error!(%error, "Could not update offline audio playback");
+ }
+ }
+ ControlMsg::Play {
+ spec,
+ generation,
+ result_tx,
+ } => {
+ let (ack_tx, _ack_rx) = std_mpsc::channel();
+ let ok = install_source::<f32>(
+ spec,
+ generation,
+ SourceAcknowledgement::Ordinary(ack_tx),
+ output_info,
+ false,
+ &source_tx,
+ )
+ .inspect_err(|e| error!("Failed to install offline audio source: {e}"))
+ .is_ok();
+ let _ = result_tx.send(ok);
+ }
+ ControlMsg::PreparePlayback { request, .. } => request.complete(false),
+ ControlMsg::PrepareProgressivePlayback { installation, .. } => {
+ installation.request.complete(false)
+ }
+ ControlMsg::StopPlayback { generation } => {
+ let _ = source_tx.send(SourceCommand::Remove {
+ generation: Some(generation),
+ });
+ }
+ ControlMsg::EnsureStream | ControlMsg::HoldAwake | ControlMsg::ReleaseAwake => {}
+ ControlMsg::Retire(source) => drop(source),
+ ControlMsg::Realign(realign) => realign(),
+ ControlMsg::Shutdown => break,
+ }
+ }
+}
+
fn handle_play(state: &mut Option<StreamState>, spec: Box<PlaySpec>, generation: u64) -> bool {
if !ensure_stream(state) {
return false;
diff --git a/crates/editor/src/lib.rs b/crates/editor/src/lib.rs
index 612c25cb4..16a618e21 100644
--- a/crates/editor/src/lib.rs
+++ b/crates/editor/src/lib.rs
@@ -15,6 +15,8 @@ mod telemetry;
mod thumbnail;
pub use audio::{AudioRenderer, AudioSegment, MusicTracks};
+#[cfg(feature = "test-hooks")]
+pub use audio_output::OfflineAudioSink;
pub use audio_output::{
AudioOutput, HEADLESS_BLOCK_FRAMES, HEADLESS_CHANNELS, HEADLESS_SAMPLE_RATE, HeadlessAudioTap,
PlaySpec,