Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat(verify): audio oracle for exports and offline playback
Richie McIlroy9ae7738b366c
diff --git a/crates/verify/Cargo.toml b/crates/verify/Cargo.tomlindex b0da67135..c79fe824a 100644--- a/crates/verify/Cargo.toml+++ b/crates/verify/Cargo.toml@@ -30,7 +30,7 @@ cap-enc-avfoundation = { path = "../enc-avfoundation" }cidre = { workspace = true }[dev-dependencies]-cap-editor = { path = "../editor" }+cap-editor = { path = "../editor", features = ["test-hooks"] }cap-export = { path = "../export" }cap-rendering = { path = "../rendering" }tempfile = "3"diff --git a/crates/verify/src/audio_fixture.rs b/crates/verify/src/audio_fixture.rsnew file mode 100644index 000000000..99ebc1eaf--- /dev/null+++ b/crates/verify/src/audio_fixture.rs@@ -0,0 +1,123 @@+//! Fixtures for the audio, captions and editing tracks: projects whose mic,+//! system audio and timeline music carry distinct audio markers, written by+//! [`crate::fixture::write_fixture`] plus a music file.++use std::path::Path;++use cap_project::{AudioTrackSegment, ProjectConfiguration};++use crate::{+ audio_code::{self, AudioSource},+ catalog::{SCREEN_H, SCREEN_W},+ fixture::{self, AudioTrackSpec, FixtureSpec, SegmentSpec, Timing, VideoTrackSpec},+ media::{self, AudioCodec},+ report::Tier,+};++/// Bump when the music writer changes so cached fixtures are rebuilt.+const AUDIO_GENERATOR_VERSION: u32 = 2;+/// Music file written next to `recording-meta.json`.+pub const MUSIC_FILE: &str = "music.ogg";+pub const MUSIC_SECS: f64 = 12.0;++fn audio(source: AudioSource, duration: f64, start_time: f64) -> AudioTrackSpec {+ AudioTrackSpec {+ source,+ sample_rate: 48_000,+ channels: if source == AudioSource::System { 2 } else { 1 },+ duration,+ start_time,+ }+}++/// One clip: screen at 30 fps (starting 0.10 s into the recording), mic+/// starting 0.5 s in (the latest track, so screen and system audio get+/// alignment offsets), stereo system audio from 0, plus a stereo music file.+/// The mic start is one marker period so the sources' markers stay apart+/// once aligned.+pub fn mix(tier: Tier) -> FixtureSpec {+ let duration = match tier {+ Tier::Fast => 8.0,+ Tier::Full => 30.0,+ };+ let mut display = VideoTrackSpec::new(SCREEN_W, SCREEN_H, 30, Timing::Constant { duration });+ display.start_time = 0.10;+ FixtureSpec {+ name: format!("audio-mix-{duration:.0}s-a{AUDIO_GENERATOR_VERSION}"),+ segments: vec![SegmentSpec {+ display,+ camera: None,+ mic: Some(audio(AudioSource::Mic, duration - 0.5, 0.5)),+ system_audio: Some(audio(AudioSource::System, duration, 0.0)),+ }],+ }+}++/// Two clips (pause/resume): the second has a mic only.+pub fn multi(_tier: Tier) -> FixtureSpec {+ let screen =+ |duration| VideoTrackSpec::new(SCREEN_W, SCREEN_H, 30, Timing::Constant { duration });+ FixtureSpec {+ name: format!("audio-multi-a{AUDIO_GENERATOR_VERSION}"),+ segments: vec![+ SegmentSpec {+ display: screen(5.0),+ camera: None,+ mic: Some(audio(AudioSource::Mic, 5.0, 0.0)),+ system_audio: Some(audio(AudioSource::System, 5.0, 0.0)),+ },+ SegmentSpec {+ display: screen(4.0),+ camera: None,+ mic: Some(audio(AudioSource::Mic, 4.0, 0.0)),+ system_audio: None,+ },+ ],+ }+}++/// Writes the fixture tracks and the music file.+pub fn write(spec: &FixtureSpec, dir: &Path) -> anyhow::Result<()> {+ fixture::write_fixture(spec, dir)?;+ let rate = 48_000;+ let mut mono = vec![0.0f32; (MUSIC_SECS * f64::from(rate)) as usize];+ let schedule = audio_code::standard_schedule(AudioSource::Media, 0.1, MUSIC_SECS - 0.1, 0.5);+ audio_code::render_markers(+ &mut mono,+ rate,+ AudioSource::Media,+ &schedule,+ audio_code::DEFAULT_AMPLITUDE,+ );+ media::write_audio(+ &dir.join(MUSIC_FILE),+ &[mono.clone(), mono],+ rate,+ AudioCodec::Opus,+ 128_000,+ )+}++/// Adds a timeline music segment playing [`MUSIC_FILE`].+pub fn add_music(+ config: &mut ProjectConfiguration,+ start: f64,+ end: f64,+ trim_start: f64,+ volume_db: f32,+) {+ let timeline = config.timeline.as_mut().expect("timeline");+ timeline.audio_segments.push(AudioTrackSegment {+ start,+ end,+ track: 0,+ path: MUSIC_FILE.into(),+ name: None,+ enabled: true,+ trim_start,+ volume_db,+ fade_in: 0.0,+ fade_out: 0.0,+ duration: Some(MUSIC_SECS),+ });+}diff --git a/crates/verify/src/audio_model.rs b/crates/verify/src/audio_model.rsnew file mode 100644index 000000000..da48dc6b9--- /dev/null+++ b/crates/verify/src/audio_model.rs@@ -0,0 +1,814 @@+//! Reference model and oracle for audio: where every source marker must be+//! heard in an output (export or offline playback), at what level, and+//! nowhere else.+//!+//! Written from the project's documented rules, not by calling the+//! production mapping:+//! - Timeline segments play back to back; segment `k` covers+//! `(end - start) / timescale` output seconds and maps output time `u` in it+//! to recording time `start + u * timescale`. A transition into segment `k`+//! overlaps the two segments by its clamped duration; markers inside the+//! overlap may be heard at any level (a blend) and are not required.+//! - A recording audio track sample at track time `t` plays at recording time+//! `t - offset`, where `offset` is the clip's stored offset for that track+//! (mic or system audio; auto-calculated offsets align every track to the+//! latest track start).+//! - Track gain is `10^(dB / 20)`; at or below -30 dB, or with the project+//! muted, the track is silent. Clip volume multiplies the recording mix. A+//! mono track is centre-panned at -3 dB (0.707 per channel).+//! - Retimed segments (timescale != 1) are silent in the default `mute` speed+//! audio mode; `matchSpeed` plays the source resampled (the marker is+//! compressed in time by the timescale and its pitch scaled with it);+//! `maintainPitch` time-stretches and is not marker-checked.+//! - Timeline music (audio segments) plays in output time from `trim_start`,+//! independent of recording edits, at `10^(volume_db / 20)` (silent at or+//! below -60 dB), with linear fades that are not level-checked.+//! - Studio Sound processes the microphone only: mic markers must still be+//! heard exactly once at the right time, but their level is not checked.++use std::path::Path;++use anyhow::{Context, bail};+use cap_project::{ClipSpeedAudioMode, ProjectConfiguration, RecordingMeta, StudioRecordingMeta};+use serde::{Deserialize, Serialize};++use crate::{+ audio_code::{self, AudioSource, LocatedMarker, MARKER_SECS},+ media,+};++/// Sample rate every analysis runs at (the editor's mixing rate).+pub const ANALYSIS_RATE: u32 = 48_000;+/// Largest allowed difference between a marker's heard and expected time.+pub const TIME_TOLERANCE_SECS: f64 = 0.005;+/// Largest allowed relative level error where the level is checked.+pub const GAIN_TOLERANCE: f64 = 0.25;+const MATCH_WINDOW_SECS: f64 = 0.040;+/// Detections quieter than this (-60 dB below a unit marker) are numerical+/// noise: the chirp correlation is normalised, so near-silent rounding+/// residue can correlate. Real markers are heard at 0.05 or more.+const MIN_HEARD_GAIN: f64 = 1e-3;+/// Chirps of one source correlate weakly (up to ~0.7) with another source's+/// chirp and bit tones. Undecodable detections below this are that+/// cross-talk; unprocessed markers correlate above 0.95 even after AAC.+/// Studio Sound bends the mic chirp (down to ~0.74) and can smear its bits,+/// so processed mic markers are matched by time instead.+const CROSSTALK_CORRELATION: f64 = 0.8;+const MIN_TRANSITION: f64 = 0.05;+const MONO_PAN: f64 = 0.707;++/// One marker found in a source file.+#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq)]+pub struct SourceMarker {+ pub index: u32,+ /// Chirp start in seconds of file time.+ pub time_secs: f64,+ /// Level relative to a unit marker, averaged over the file's channels.+ pub gain: f64,+}++#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct TrackAudioTruth {+ pub source: AudioSource,+ pub channels: usize,+ pub markers: Vec<SourceMarker>,+}++#[derive(Clone, Debug, Default, Serialize, Deserialize)]+pub struct SegmentAudioTruth {+ pub mic: Option<TrackAudioTruth>,+ pub system: Option<TrackAudioTruth>,+}++/// Markers of every recording audio track (and timeline music files), read+/// back from the files.+#[derive(Clone, Debug, Default, Serialize, Deserialize)]+pub struct AudioTruth {+ pub segments: Vec<SegmentAudioTruth>,+ /// Music file path (as written in the project) -> markers.+ pub music: Vec<(String, TrackAudioTruth)>,+}++/// Locates every marker of `source` in a file (all channels averaged).+pub fn read_track_truth(path: &Path, source: AudioSource) -> anyhow::Result<TrackAudioTruth> {+ let decoded = media::decode_audio(path, Some(ANALYSIS_RATE))+ .with_context(|| format!("decode {path:?}"))?;+ let found = audio_code::locate_markers(&decoded.mono(), ANALYSIS_RATE, source);+ let mut markers = Vec::new();+ for marker in found {+ let Some(index) = marker.index else {+ bail!(+ "{path:?}: undecodable {} marker at {:.3}s",+ source.name(),+ marker.time_secs+ );+ };+ markers.push(SourceMarker {+ index,+ time_secs: marker.time_secs + decoded.start_secs,+ gain: marker.gain,+ });+ }+ if markers.is_empty() {+ bail!("{path:?}: no {} markers", source.name());+ }+ Ok(TrackAudioTruth {+ source,+ channels: decoded.channels.len(),+ markers,+ })+}++impl AudioTruth {+ /// Reads every audio track of a multi-segment studio project plus the+ /// music files referenced by `config`. Cached in the project directory.+ pub fn read(project: &Path, config: &ProjectConfiguration) -> anyhow::Result<Self> {+ let cache = project.join("verify-audio-truth.json");+ let mut truth: AudioTruth = std::fs::read_to_string(&cache)+ .ok()+ .and_then(|text| serde_json::from_str(&text).ok())+ .unwrap_or_default();+ let meta = RecordingMeta::load_for_project(project)+ .map_err(|e| anyhow::anyhow!("load meta: {e:?}"))?;+ let Some(StudioRecordingMeta::MultipleSegments { inner }) = meta.studio_meta() else {+ bail!("not a multi-segment studio project");+ };+ let mut changed = false;+ if truth.segments.len() != inner.segments.len() {+ truth.segments = inner+ .segments+ .iter()+ .map(|segment| -> anyhow::Result<SegmentAudioTruth> {+ Ok(SegmentAudioTruth {+ mic: segment+ .mic+ .as_ref()+ .map(|m| {+ read_track_truth(&project.join(m.path.as_str()), AudioSource::Mic)+ })+ .transpose()?,+ system: segment+ .system_audio+ .as_ref()+ .map(|s| {+ read_track_truth(+ &project.join(s.path.as_str()),+ AudioSource::System,+ )+ })+ .transpose()?,+ })+ })+ .collect::<anyhow::Result<_>>()?;+ changed = true;+ }+ if let Some(timeline) = &config.timeline {+ for segment in &timeline.audio_segments {+ if truth.music.iter().any(|(p, _)| *p == segment.path) {+ continue;+ }+ let path = Path::new(&segment.path);+ let path = if path.is_absolute() {+ path.to_path_buf()+ } else {+ project.join(path)+ };+ truth.music.push((+ segment.path.clone(),+ read_track_truth(&path, AudioSource::Media)?,+ ));+ changed = true;+ }+ }+ if changed {+ let _ = std::fs::write(&cache, serde_json::to_string(&truth)?);+ }+ Ok(truth)+ }+}++#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "lowercase")]+pub enum Presence {+ /// Must be heard exactly once.+ Required,+ /// May be heard (cut by an edit boundary, inside a transition or fade);+ /// if heard it must be at the right time.+ Optional,+}++/// Where one source marker must be heard in the output.+#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct ExpectedMarker {+ pub source: AudioSource,+ pub index: u32,+ /// Output time of the chirp start.+ pub time_secs: f64,+ /// Expected level of the output's channel average, when checked.+ pub gain: Option<f64>,+ pub presence: Presence,+ /// Time compression of the marker (the segment timescale for+ /// `matchSpeed`, else 1).+ pub rate: f64,+ /// Recording clip and recording time the marker belongs to (`None` for+ /// timeline music), for A/V checks and reports.+ pub recording: Option<(usize, f64)>,+ /// Whether the marker's payload survives processing. Studio Sound can+ /// smear the FSK bits; such a marker is matched by its chirp time.+ pub payload: bool,+}++/// An output window in which detections of `source` are not judged.+#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct UncheckedWindow {+ pub source: AudioSource,+ pub start: f64,+ pub end: f64,+ pub reason: String,+}++/// A window of output time with time-compressed markers (`matchSpeed`).+#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct RateWindow {+ pub start: f64,+ pub end: f64,+ pub rate: f64,+}++#[derive(Clone, Debug)]+struct ModelSegment {+ clip: usize,+ start: f64,+ end: f64,+ timescale: f64,+ mode: ClipSpeedAudioMode,+ volume: f64,+ transition_in: f64,+}++impl ModelSegment {+ fn duration(&self) -> f64 {+ (self.end - self.start) / self.timescale+ }+}++/// Clip track offsets as stored in the project.+#[derive(Clone, Copy, Debug)]+struct ClipAudioOffsets {+ mic: f64,+ system: f64,+}++pub struct AudioModel {+ pub expected: Vec<ExpectedMarker>,+ pub unchecked: Vec<UncheckedWindow>,+ pub rate_windows: Vec<RateWindow>,+ pub duration: f64,+}++fn db_gain(db: f32) -> Option<f64> {+ (db > -30.0).then(|| 10f64.powf(f64::from(db) / 20.0))+}++impl AudioModel {+ pub fn new(+ meta: &RecordingMeta,+ project: &ProjectConfiguration,+ truth: &AudioTruth,+ ) -> anyhow::Result<Self> {+ let Some(StudioRecordingMeta::MultipleSegments { inner }) = meta.studio_meta() else {+ bail!("the audio model covers multi-segment studio projects");+ };+ let timeline = project+ .timeline+ .as_ref()+ .ok_or_else(|| anyhow::anyhow!("project has no timeline"))?;+ let offsets: Vec<ClipAudioOffsets> = (0..inner.segments.len())+ .map(|i| {+ let clip = project.clips.iter().find(|c| c.index as usize == i);+ ClipAudioOffsets {+ mic: clip.map_or(0.0, |c| f64::from(c.offsets.mic)),+ system: clip.map_or(0.0, |c| f64::from(c.offsets.system_audio)),+ }+ })+ .collect();+ let mut segments: Vec<ModelSegment> = timeline+ .segments+ .iter()+ .map(|s| ModelSegment {+ clip: s.recording_clip as usize,+ start: s.start,+ end: s.end,+ timescale: s.timescale,+ mode: s.speed_audio_mode.unwrap_or_default(),+ volume: s+ .volume+ .filter(|v| v.is_finite())+ .unwrap_or(1.0)+ .clamp(0.0, 2.0),+ transition_in: 0.0,+ })+ .collect();+ for transition in &timeline.transitions {+ let k = transition.segment_index as usize;+ if k == 0 || k >= segments.len() {+ continue;+ }+ let max = segments[k - 1].duration().min(segments[k].duration()) / 2.0;+ if transition.duration.is_finite() && transition.duration > 0.0 && max >= MIN_TRANSITION+ {+ segments[k].transition_in = transition.duration.clamp(MIN_TRANSITION, max);+ }+ }+ let mut output_starts = Vec::with_capacity(segments.len());+ let mut at = 0.0;+ for (k, segment) in segments.iter().enumerate() {+ output_starts.push(at);+ let next_in = segments.get(k + 1).map_or(0.0, |n| n.transition_in);+ at += segment.duration() - next_in;+ }+ let duration = at;+ let audio = &project.audio;+ let mut expected = Vec::new();+ let mut unchecked = Vec::new();+ let mut rate_windows = Vec::new();++ for (k, segment) in segments.iter().enumerate() {+ let out_start = output_starts[k];+ let out_end = out_start + segment.duration();+ // Output window shared with a neighbour's transition.+ let blend_until = out_start + segment.transition_in;+ let blend_from = out_end - segments.get(k + 1).map_or(0.0, |n| n.transition_in);+ let Some(clip_truth) = truth.segments.get(segment.clip) else {+ continue;+ };+ let retimed = (segment.timescale - 1.0).abs() > f64::EPSILON;+ if retimed && segment.mode == ClipSpeedAudioMode::MaintainPitch {+ for source in [AudioSource::Mic, AudioSource::System] {+ unchecked.push(UncheckedWindow {+ source,+ start: out_start,+ end: out_end,+ reason: "maintainPitch time stretch".into(),+ });+ }+ continue;+ }+ let silent = audio.mute || (retimed && segment.mode == ClipSpeedAudioMode::Mute);+ if retimed && !silent {+ rate_windows.push(RateWindow {+ start: out_start,+ end: out_end,+ rate: segment.timescale,+ });+ }+ let tracks = [+ (+ clip_truth.mic.as_ref(),+ offsets[segment.clip].mic,+ db_gain(audio.mic_volume_db),+ audio.improve,+ ),+ (+ clip_truth.system.as_ref(),+ offsets[segment.clip].system,+ db_gain(audio.system_volume_db),+ false,+ ),+ ];+ for (track, offset, gain, processed) in tracks {+ let Some(track) = track else { continue };+ let Some(gain) = gain.filter(|_| !silent) else {+ continue;+ };+ let pan = if track.channels == 1 { MONO_PAN } else { 1.0 };+ let marker_len = MARKER_SECS * segment.timescale;+ for marker in &track.markers {+ let recording_time = marker.time_secs - offset;+ if recording_time + marker_len <= segment.start || recording_time >= segment.end+ {+ continue;+ }+ let time = out_start + (recording_time - segment.start) / segment.timescale;+ let whole = recording_time >= segment.start+ && recording_time + marker_len <= segment.end;+ let blended =+ time < blend_until || time + MARKER_SECS / segment.timescale > blend_from;+ let level_known = !processed && segment.volume > 0.0;+ let presence = if whole && !blended && segment.volume > 0.0 {+ Presence::Required+ } else {+ Presence::Optional+ };+ if segment.volume == 0.0 {+ continue;+ }+ expected.push(ExpectedMarker {+ source: track.source,+ index: marker.index,+ time_secs: time,+ gain: (level_known && !blended)+ .then_some(marker.gain * pan * gain * segment.volume),+ presence,+ rate: if retimed { segment.timescale } else { 1.0 },+ recording: Some((segment.clip, recording_time)),+ payload: !processed,+ });+ }+ }+ }++ for music in &timeline.audio_segments {+ let gain = if music.volume_db <= -60.0 {+ continue;+ } else {+ 10f64.powf(f64::from(music.volume_db) / 20.0)+ };+ if !music.enabled || music.end <= music.start {+ continue;+ }+ let Some((_, track)) = truth.music.iter().find(|(p, _)| *p == music.path) else {+ bail!("no truth for music file {}", music.path);+ };+ let pan = if track.channels == 1 { MONO_PAN } else { 1.0 };+ let trim = music.trim_start.max(0.0);+ let seg_end = music.end.min(duration);+ for marker in &track.markers {+ let time = music.start + marker.time_secs - trim;+ if time + MARKER_SECS <= music.start || time >= seg_end {+ continue;+ }+ let whole = time >= music.start && time + MARKER_SECS <= seg_end;+ let faded = time < music.start + music.fade_in.max(0.0)+ || time + MARKER_SECS > music.end - music.fade_out.max(0.0);+ expected.push(ExpectedMarker {+ source: AudioSource::Media,+ index: marker.index,+ time_secs: time,+ gain: (!faded).then_some(marker.gain * pan * gain),+ presence: if whole {+ Presence::Required+ } else {+ Presence::Optional+ },+ rate: 1.0,+ recording: None,+ payload: true,+ });+ }+ }+ expected.sort_by(|a, b| a.time_secs.total_cmp(&b.time_secs));+ Ok(Self {+ expected,+ unchecked,+ rate_windows,+ duration,+ })+ }++ /// Expectations for an output that starts at timeline time `from` and+ /// covers `length` seconds; times become relative to the output start.+ pub fn window(&self, from: f64, length: f64) -> Self {+ let to = from + length;+ let expected = self+ .expected+ .iter()+ .filter(|e| e.time_secs + MARKER_SECS / e.rate > from && e.time_secs < to)+ .map(|e| {+ let whole = e.time_secs >= from && e.time_secs + MARKER_SECS / e.rate <= to;+ ExpectedMarker {+ time_secs: e.time_secs - from,+ presence: if whole {+ e.presence+ } else {+ Presence::Optional+ },+ ..e.clone()+ }+ })+ .collect();+ Self {+ expected,+ unchecked: self+ .unchecked+ .iter()+ .map(|w| UncheckedWindow {+ start: w.start - from,+ end: w.end - from,+ ..w.clone()+ })+ .collect(),+ rate_windows: self+ .rate_windows+ .iter()+ .map(|w| RateWindow {+ start: w.start - from,+ end: w.end - from,+ rate: w.rate,+ })+ .collect(),+ duration: length,+ }+ }++ /// Appends `other` (a later output window) shifted by `at` seconds.+ pub fn append(&mut self, other: Self, at: f64) {+ self.expected+ .extend(other.expected.into_iter().map(|e| ExpectedMarker {+ time_secs: e.time_secs + at,+ ..e+ }));+ self.unchecked+ .extend(other.unchecked.into_iter().map(|w| UncheckedWindow {+ start: w.start + at,+ end: w.end + at,+ ..w+ }));+ self.rate_windows+ .extend(other.rate_windows.into_iter().map(|w| RateWindow {+ start: w.start + at,+ end: w.end + at,+ rate: w.rate,+ }));+ self.duration = self.duration.max(at + other.duration);+ }++ pub fn required(&self) -> usize {+ self.expected+ .iter()+ .filter(|e| e.presence == Presence::Required)+ .count()+ }+}++/// A located marker with its time relative to the analysed output.+#[derive(Clone, Copy, Debug, Serialize, Deserialize)]+pub struct HeardMarker {+ pub source: AudioSource,+ pub index: Option<u32>,+ pub time_secs: f64,+ pub gain: f64,+ pub rate: f64,+ pub correlation: f64,+}++/// Finds every marker of every source in a mono output (at+/// [`ANALYSIS_RATE`]), including time-compressed markers inside+/// `rate_windows`. `start_secs` is the output time of sample 0.+pub fn hear(mono: &[f32], start_secs: f64, rate_windows: &[RateWindow]) -> Vec<HeardMarker> {+ let mut heard = Vec::new();+ for source in AudioSource::ALL {+ for m in audio_code::locate_markers(mono, ANALYSIS_RATE, source) {+ if m.gain.abs() < MIN_HEARD_GAIN {+ continue;+ }+ let time = m.time_secs + start_secs;+ if rate_windows+ .iter()+ .any(|w| time >= w.start - 0.001 && time < w.end)+ {+ continue;+ }+ heard.push(heard_marker(m, time, 1.0));+ }+ for window in rate_windows {+ let scaled_rate = (f64::from(ANALYSIS_RATE) / window.rate).round() as u32;+ let from = (((window.start - start_secs) * f64::from(ANALYSIS_RATE))+ .floor()+ .max(0.0)) as usize;+ let to = ((((window.end - start_secs) * f64::from(ANALYSIS_RATE)).ceil()) as usize+ + (MARKER_SECS * f64::from(ANALYSIS_RATE)) as usize)+ .min(mono.len());+ if from >= to {+ continue;+ }+ for m in audio_code::locate_markers(&mono[from..to], scaled_rate, source) {+ if m.gain.abs() < MIN_HEARD_GAIN {+ continue;+ }+ let time = start_secs+ + from as f64 / f64::from(ANALYSIS_RATE)+ + m.time_secs * f64::from(scaled_rate) / f64::from(ANALYSIS_RATE);+ if time >= window.start - 0.001 && time < window.end {+ heard.push(heard_marker(m, time, window.rate));+ }+ }+ }+ }+ heard.sort_by(|a, b| a.time_secs.total_cmp(&b.time_secs));+ heard+}++fn heard_marker(m: LocatedMarker, time_secs: f64, rate: f64) -> HeardMarker {+ HeardMarker {+ source: m.source,+ index: m.index,+ time_secs,+ gain: m.gain,+ rate,+ correlation: m.correlation,+ }+}++/// The verdict of one output against the model.+#[derive(Clone, Debug, Default, Serialize, Deserialize)]+pub struct AudioReport {+ pub required: usize,+ pub matched: usize,+ pub missing: Vec<String>,+ pub doubled: Vec<String>,+ pub unexpected: Vec<String>,+ pub mistimed: Vec<String>,+ pub level: Vec<String>,+ pub damaged: Vec<String>,+ pub max_time_error_ms: f64,+ pub max_gain_error: f64,+ pub min_correlation: f64,+ /// (expected, heard) pairs, for A/V checks.+ #[serde(skip)]+ pub pairs: Vec<(ExpectedMarker, HeardMarker)>,+}++impl AudioReport {+ pub fn passed(&self) -> bool {+ self.missing.is_empty()+ && self.doubled.is_empty()+ && self.unexpected.is_empty()+ && self.mistimed.is_empty()+ && self.level.is_empty()+ && self.damaged.is_empty()+ }++ pub fn summary(&self) -> String {+ let mut parts = vec![format!(+ "audio {}/{} required markers matched, max time error {:.3} ms, max level error {:.0}%, min correlation {:.2}",+ self.matched,+ self.required,+ self.max_time_error_ms,+ self.max_gain_error * 100.0,+ self.min_correlation+ )];+ for (label, list) in [+ ("missing", &self.missing),+ ("doubled", &self.doubled),+ ("unexpected", &self.unexpected),+ ("mistimed", &self.mistimed),+ ("wrong level", &self.level),+ ("undecodable", &self.damaged),+ ] {+ if !list.is_empty() {+ parts.push(format!(+ "{} {label} (first: {})",+ list.len(),+ list.iter().take(4).cloned().collect::<Vec<_>>().join("; ")+ ));+ }+ }+ parts.join(", ")+ }+}++fn describe(e: &ExpectedMarker) -> String {+ match e.recording {+ Some((clip, t)) => format!(+ "{} #{} at {:.4}s (clip {clip} {:.4}s)",+ e.source.name(),+ e.index,+ e.time_secs,+ t+ ),+ None => format!("{} #{} at {:.4}s", e.source.name(), e.index, e.time_secs),+ }+}++/// Matches what was heard against the model.+pub fn check(model: &AudioModel, heard: &[HeardMarker]) -> AudioReport {+ let mut report = AudioReport {+ required: model.required(),+ min_correlation: 1.0,+ ..Default::default()+ };+ let mut hits = vec![0usize; model.expected.len()];+ for h in heard {+ let unchecked = model.unchecked.iter().any(|w| {+ w.source == h.source+ && h.time_secs >= w.start - MATCH_WINDOW_SECS+ && h.time_secs < w.end+ });+ if unchecked || h.time_secs < -MATCH_WINDOW_SECS || h.time_secs > model.duration + 0.5 {+ continue;+ }+ let candidate = model+ .expected+ .iter()+ .enumerate()+ .filter(|(_, e)| {+ e.source == h.source && (e.time_secs - h.time_secs).abs() <= MATCH_WINDOW_SECS+ })+ .min_by(|a, b| {+ let key = |e: &ExpectedMarker| {+ (h.index != Some(e.index), (e.time_secs - h.time_secs).abs())+ };+ let (ka, kb) = (key(a.1), key(b.1));+ ka.0.cmp(&kb.0).then(ka.1.total_cmp(&kb.1))+ });+ let time_only = h.index.is_none() && candidate.is_some_and(|(_, e)| !e.payload);+ if h.index.is_none() && !time_only && h.correlation < CROSSTALK_CORRELATION {+ continue;+ }+ let Some((i, e)) = candidate else {+ report.unexpected.push(format!(+ "{} #{} at {:.4}s (correlation {:.2})",+ h.source.name(),+ h.index.map_or("?".into(), |i| i.to_string()),+ h.time_secs,+ h.correlation+ ));+ continue;+ };+ match h.index {+ None if e.presence == Presence::Optional => continue,+ None if !e.payload => {}+ None => {+ report+ .damaged+ .push(format!("{} heard at {:.4}s", describe(e), h.time_secs));+ hits[i] += 1;+ continue;+ }+ Some(index) if index != e.index => {+ report.unexpected.push(format!(+ "{} #{index} at {:.4}s (near {})",+ h.source.name(),+ h.time_secs,+ describe(e)+ ));+ continue;+ }+ Some(_) => {}+ }+ hits[i] += 1;+ report.min_correlation = report.min_correlation.min(h.correlation);+ let error = h.time_secs - e.time_secs;+ report.max_time_error_ms = report.max_time_error_ms.max(error.abs() * 1000.0);+ if error.abs() > TIME_TOLERANCE_SECS {+ report.mistimed.push(format!(+ "{} heard at {:.4}s ({:+.2} ms)",+ describe(e),+ h.time_secs,+ error * 1000.0+ ));+ }+ if let Some(gain) = e.gain {+ let rel = h.gain / gain - 1.0;+ report.max_gain_error = report.max_gain_error.max(rel.abs());+ if rel.abs() > GAIN_TOLERANCE {+ report.level.push(format!(+ "{} level {:.3}, expected {:.3}",+ describe(e),+ h.gain,+ gain+ ));+ }+ }+ report.pairs.push((e.clone(), *h));+ }+ for (e, hits) in model.expected.iter().zip(hits) {+ match (e.presence, hits) {+ (Presence::Required, 0) => report.missing.push(describe(e)),+ (Presence::Required, 1) => report.matched += 1,+ (_, 0 | 1) => {}+ (_, n) => report+ .doubled+ .push(format!("{} heard {n} times", describe(e))),+ }+ }+ report+}++/// Splits interleaved stereo into its channel average.+pub fn interleaved_mono(samples: &[f32], channels: usize) -> Vec<f32> {+ samples+ .chunks_exact(channels.max(1))+ .map(|frame| frame.iter().sum::<f32>() / frame.len() as f32)+ .collect()+}++/// Peak absolute difference between two PCM buffers in dBFS (`None` when+/// identical), and the first differing sample.+pub fn pcm_difference(a: &[f32], b: &[f32]) -> Option<(f64, usize)> {+ let mut peak = 0.0f32;+ let mut first = None;+ for (i, (x, y)) in a.iter().zip(b).enumerate() {+ let d = (x - y).abs();+ if d > 0.0 && first.is_none() {+ first = Some(i);+ }+ peak = peak.max(d);+ }+ if a.len() != b.len() && first.is_none() {+ first = Some(a.len().min(b.len()));+ peak = peak.max(1.0);+ }+ first.map(|i| (20.0 * f64::from(peak.max(1e-12)).log10(), i))+}diff --git a/crates/verify/src/lib.rs b/crates/verify/src/lib.rsindex 69ad33ae4..2de87cb49 100644--- a/crates/verify/src/lib.rs+++ b/crates/verify/src/lib.rs@@ -11,3 +11,5 @@ pub mod model;pub mod oracle;pub mod report;pub mod video_code;+pub mod audio_fixture;+pub mod audio_model;diff --git a/crates/verify/tests/audio.rs b/crates/verify/tests/audio.rsnew file mode 100644index 000000000..0746dc5c1--- /dev/null+++ b/crates/verify/tests/audio.rs@@ -0,0 +1,451 @@+//! Audio oracle: every mic, system audio and music marker must be heard+//! exactly once, at the time and level the reference audio model computes,+//! in exports and in offline editor playback, and in sync with the video.++mod audio_support;+mod common;++use audio_support::{ExportPath, OfflinePlayer};+use cap_project::{ClipSpeedAudioMode, ProjectConfiguration};+use cap_verify::{+ audio_fixture,+ audio_model::{self, AudioModel},+ fixture::FixtureSpec,+ report::{self, Case, Tier},+};++struct Variant {+ edit: &'static str,+ apply: fn(&mut ProjectConfiguration),+}++fn full(_: &mut ProjectConfiguration) {}++/// Cuts, a backward jump (1.0-2.0 plays again after 3.4-5.0) and a skip.+fn cuts(config: &mut ProjectConfiguration) {+ common::set_cuts(+ config,+ &[+ (0.5, 2.6, 1.0),+ (3.4, 5.0, 1.0),+ (1.0, 2.0, 1.0),+ (5.5, 7.8, 1.0),+ ],+ );+}++fn speeds(config: &mut ProjectConfiguration, mode: Option<ClipSpeedAudioMode>) {+ common::set_cuts(+ config,+ &[+ (0.3, 2.0, 1.0),+ (2.0, 4.0, 2.0),+ (4.0, 5.0, 0.5),+ (5.0, 7.0, 1.5),+ (7.0, 7.8, 1.0),+ ],+ );+ for segment in &mut config.timeline.as_mut().expect("timeline").segments {+ segment.speed_audio_mode = mode;+ }+}++/// Retimed segments in the default speed audio mode are silent.+fn speeds_muted(config: &mut ProjectConfiguration) {+ speeds(config, None);+}++/// Retimed segments resampled like tape (markers compressed in time).+fn speeds_match(config: &mut ProjectConfiguration) {+ speeds(config, Some(ClipSpeedAudioMode::MatchSpeed));+}++/// Mic at -6 dB, system audio at the -30 dB mute floor, clip volume 0.5 on+/// the second segment and 0 on the third.+fn levels(config: &mut ProjectConfiguration) {+ common::set_cuts(config, &[(0.2, 3.0, 1.0), (3.0, 5.5, 1.0), (5.5, 7.8, 1.0)]);+ config.audio.mic_volume_db = -6.0;+ config.audio.system_volume_db = -30.0;+ let segments = &mut config.timeline.as_mut().expect("timeline").segments;+ segments[1].volume = Some(0.5);+ segments[2].volume = Some(0.0);+}++/// Project mute: recording audio silent, timeline music still plays.+fn muted_with_music(config: &mut ProjectConfiguration) {+ config.audio.mute = true;+ audio_fixture::add_music(config, 1.0, 7.0, 0.5, -6.0);+}++/// Music on top of cuts: music follows output time, not the edits.+fn music_over_cuts(config: &mut ProjectConfiguration) {+ cuts(config);+ audio_fixture::add_music(config, 0.75, 6.5, 2.0, -3.0);+}++fn studio_sound(config: &mut ProjectConfiguration) {+ cuts(config);+ config.audio.improve = true;+}++fn transition(config: &mut ProjectConfiguration) {+ common::set_cuts(config, &[(0.3, 3.5, 1.0), (4.5, 7.8, 1.0)]);+ common::add_transition(config, 1, 0.4);+}++fn variants() -> Vec<Variant> {+ vec![+ Variant {+ edit: "full",+ apply: full,+ },+ Variant {+ edit: "cuts",+ apply: cuts,+ },+ Variant {+ edit: "speeds-muted",+ apply: speeds_muted,+ },+ Variant {+ edit: "speeds-match",+ apply: speeds_match,+ },+ Variant {+ edit: "levels",+ apply: levels,+ },+ Variant {+ edit: "muted-music",+ apply: muted_with_music,+ },+ Variant {+ edit: "music-cuts",+ apply: music_over_cuts,+ },+ Variant {+ edit: "studio-sound",+ apply: studio_sound,+ },+ Variant {+ edit: "transition",+ apply: transition,+ },+ ]+}++const FPS: u32 = 30;+const RES: (u32, u32) = (320, 180);++fn export_case(spec: &FixtureSpec, variant: &Variant, path: ExportPath) -> Option<String> {+ let id = format!("audio/{}/{}/{}{FPS}", spec.name, variant.edit, path.label());+ if !report::selected(&id) {+ return None;+ }+ let project = audio_support::project(spec);+ let rt = common::runtime();+ let mut config = project.config();+ (variant.apply)(&mut config);+ let mut case = Case::new(&id);+ let dir = common::scratch_dir(&id);+ match rt.block_on(audio_support::export(+ &project,+ config.clone(),+ path,+ FPS,+ RES,+ dir.path(),+ )) {+ Err(e) => case.problem(format!("export failed: {e}")),+ Ok(out) => match path {+ ExportPath::Gif => {+ if audio_support::has_audio_stream(&out) {+ case.problem("GIF export has an audio stream");+ }+ }+ ExportPath::Mov if !audio_support::has_audio_stream(&out) => {+ case.note(+ "MOV export carries no audio (the app uses MOV for cursor-only overlays)",+ );+ }+ _ => {+ let model = audio_support::audio_model(&project, &config);+ match audio_support::exported_mono(&out) {+ Err(e) => case.problem(e),+ Ok(mono) => {+ let report = audio_support::check_pcm(&mut case, "export", &model, &mono);+ let frames = common::read_output(&out);+ let video = project.model(&config);+ common::check_sequence(&mut case, &video, &frames, FPS, true);+ audio_support::check_av(&mut case, &project.meta, &report, &frames, FPS);+ }+ }+ }+ },+ }+ report::settle(case).err()+}++fn run_exports(spec: FixtureSpec, variants: &[Variant], paths: &[ExportPath]) {+ let mut failures = Vec::new();+ for variant in variants {+ for &path in paths {+ failures.extend(export_case(&spec, variant, path));+ }+ }+ assert!(failures.is_empty(), "{}", failures.join("\n"));+}++#[test]+fn export_mp4() {+ run_exports(+ audio_fixture::mix(report::tier()),+ &variants(),+ &[ExportPath::App, ExportPath::Plain],+ );+}++#[test]+fn export_other_formats() {+ run_exports(+ audio_fixture::mix(report::tier()),+ &[Variant {+ edit: "cuts",+ apply: cuts,+ }],+ &[ExportPath::Mov, ExportPath::Gif],+ );+}++#[test]+fn export_multi_clip() {+ run_exports(+ audio_fixture::multi(report::tier()),+ &[+ Variant {+ edit: "full",+ apply: full,+ },+ Variant {+ edit: "reorder",+ apply: |config| {+ let timeline = config.timeline.as_mut().expect("timeline");+ timeline.segments.reverse();+ },+ },+ ],+ &[ExportPath::App, ExportPath::Plain],+ );+}++/// Plays the whole timeline from 0 through the offline output.+fn playback_case(spec: &FixtureSpec, variant: &Variant) -> Option<String> {+ let id = format!("audio/{}/{}/playback", spec.name, variant.edit);+ if !report::selected(&id) {+ return None;+ }+ let project = audio_support::project(spec);+ let rt = common::runtime();+ let mut config = project.config();+ (variant.apply)(&mut config);+ let model = audio_support::audio_model(&project, &config);+ let mut case = Case::new(&id);+ let mut player = OfflinePlayer::open(&rt, &project, config);+ player.play(0.0);+ let pcm = player.pull(model.duration + 0.3);+ audio_support::check_pcm(+ &mut case,+ "play from 0",+ &model.window(0.0, audio_support::frames_secs(&pcm)),+ &audio_support::mono(&pcm),+ );+ if player.starved > 0 {+ case.problem(format!(+ "{} pulls starved (samples never rendered)",+ player.starved+ ));+ }+ report::settle(case).err()+}++#[test]+fn playback() {+ let spec = audio_fixture::mix(report::tier());+ let failures: Vec<String> = variants()+ .iter()+ .filter_map(|variant| playback_case(&spec, variant))+ .collect();+ assert!(failures.is_empty(), "{}", failures.join("\n"));+}++#[test]+fn playback_multi_clip() {+ let spec = audio_fixture::multi(report::tier());+ let failures: Vec<String> = [Variant {+ edit: "full",+ apply: full,+ }]+ .iter()+ .filter_map(|variant| playback_case(&spec, variant))+ .collect();+ assert!(failures.is_empty(), "{}", failures.join("\n"));+}++/// One play/seek script step.+#[derive(Clone, Copy, Debug)]+enum Step {+ /// Press play at a timeline position (a pause before it is implied).+ Play(f64),+ /// Live seek during playback.+ Seek(f64),+ /// Pull this many seconds of output.+ Pull(f64),+}++/// Runs a script; returns the output of every play/seek span as+/// (timeline start, interleaved PCM).+fn run_script(player: &mut OfflinePlayer, script: &[Step]) -> Vec<(f64, Vec<f32>)> {+ let mut spans: Vec<(f64, Vec<f32>)> = Vec::new();+ for step in script {+ match *step {+ Step::Play(at) => {+ player.play(at);+ spans.push((at, Vec::new()));+ }+ Step::Seek(to) => {+ player.seek(to);+ spans.push((to, Vec::new()));+ }+ Step::Pull(secs) => {+ let pcm = player.pull(secs);+ spans.last_mut().expect("pull after play").1.extend(pcm);+ }+ }+ }+ spans+}++fn span_model(model: &AudioModel, spans: &[(f64, Vec<f32>)]) -> Vec<AudioModel> {+ spans+ .iter()+ .map(|(start, pcm)| model.window(*start, audio_support::frames_secs(pcm)))+ .collect()+}++const SPAN: f64 = 1.2;++/// Pause/play and live seeks: every span is checked against the model, and+/// every span's PCM must equal what main's player produces for it: a play+/// equals a fresh output's first play at that position; a live seek keeps+/// reading the render the play started.+fn transport_case(+ spec: &FixtureSpec,+ edit: &str,+ apply: fn(&mut ProjectConfiguration),+) -> Option<String> {+ let id = format!("audio/{}/{edit}/transport", spec.name);+ if !report::selected(&id) {+ return None;+ }+ let project = audio_support::project(spec);+ let rt = common::runtime();+ let mut config = project.config();+ apply(&mut config);+ let model = audio_support::audio_model(&project, &config);+ let mut case = Case::new(&id);+ let script = [+ Step::Play(2.0),+ Step::Pull(SPAN),+ Step::Play(4.5),+ Step::Pull(SPAN),+ Step::Play(0.6),+ Step::Pull(SPAN),+ Step::Play(2.0),+ Step::Pull(SPAN),+ Step::Seek(5.2),+ Step::Pull(SPAN),+ Step::Seek(1.1),+ Step::Pull(SPAN),+ ];+ let mut player = OfflinePlayer::open(&rt, &project, config.clone());+ let spans = run_script(&mut player, &script);+ for ((start, pcm), expected) in spans.iter().zip(span_model(&model, &spans)) {+ audio_support::check_pcm(+ &mut case,+ &format!("span at {start:.2}s"),+ &expected,+ &audio_support::mono(pcm),+ );+ }+ // Reference PCM for every span from fresh outputs: a play is a fresh+ // play there; a seek target is read from the play it happened in.+ let mut play_start = 0.0;+ let mut offset_in_play = 0.0;+ let mut kinds = Vec::new();+ for step in &script {+ match *step {+ Step::Play(at) => {+ play_start = at;+ offset_in_play = 0.0;+ kinds.push((at, None));+ }+ Step::Seek(to) => kinds.push((to, Some((play_start, offset_in_play)))),+ Step::Pull(secs) => offset_in_play += secs,+ }+ }+ for ((start, pcm), (_, seek)) in spans.iter().zip(&kinds) {+ let mut fresh = OfflinePlayer::open(&rt, &project, config.clone());+ let reference = match seek {+ None => {+ fresh.play(*start);+ fresh.pull(audio_support::frames_secs(pcm))+ }+ Some((play_at, _)) => {+ fresh.play(*play_at);+ fresh.seek(*start);+ fresh.pull(audio_support::frames_secs(pcm))+ }+ };+ if seek.is_some() {+ let mut cold = OfflinePlayer::open(&rt, &project, config.clone());+ cold.play(*start);+ let cold = cold.pull(audio_support::frames_secs(pcm));+ case.note(match audio_model::pcm_difference(pcm, &cold) {+ None => format!("seek to {start:.2}s: also identical to a fresh play there"),+ Some((db, _)) => format!(+ "seek to {start:.2}s: differs from a fresh play there by {db:.1} dBFS (main keeps the play's render)"+ ),+ });+ }+ let label = match seek {+ None => format!("play at {start:.2}s"),+ Some((play_at, _)) => format!("seek to {start:.2}s (play from {play_at:.2}s)"),+ };+ match audio_model::pcm_difference(pcm, &reference) {+ None => case.note(format!("{label}: PCM identical to a fresh output")),+ Some((db, at)) => case.problem(format!(+ "{label}: PCM differs from a fresh output (peak difference {db:.1} dBFS, first at {:.4}s into the span)",+ (at / audio_support::CHANNELS) as f64 / f64::from(audio_support::RATE)+ )),+ }+ }+ if player.starved > 0 {+ case.problem(format!("{} pulls starved", player.starved));+ }+ report::settle(case).err()+}++#[test]+fn transport() {+ let spec = audio_fixture::mix(report::tier());+ let mut failures = Vec::new();+ failures.extend(transport_case(&spec, "full", full));+ failures.extend(transport_case(&spec, "studio-sound-full", |config| {+ config.audio.improve = true;+ }));+ if report::tier() == Tier::Full {+ failures.extend(transport_case(&spec, "cuts", cuts));+ failures.extend(transport_case(&spec, "studio-sound-cuts", studio_sound));+ }+ assert!(failures.is_empty(), "{}", failures.join("\n"));+}diff --git a/crates/verify/tests/audio_support/mod.rs b/crates/verify/tests/audio_support/mod.rsnew file mode 100644index 000000000..c87cb10c7--- /dev/null+++ b/crates/verify/tests/audio_support/mod.rs@@ -0,0 +1,400 @@+#![allow(dead_code)]++//! Shared pieces of the audio, captions and editing tests: marker fixtures,+//! the offline playback driver and export helpers.++use std::{+ path::{Path, PathBuf},+ time::Duration,+};++use cap_editor::{AudioOutput, AudioSegment, MusicTracks, OfflineAudioSink, PlaySpec};+use cap_project::{ProjectConfiguration, RecordingMeta, StudioRecordingMeta, XY};+use cap_verify::{+ audio_fixture,+ audio_model::{self, AudioModel, AudioReport, AudioTruth},+ fixture::{self, FixtureSpec, SourceTruth},+ media,+ report::Case,+ video_code::StreamKind,+};+use tokio::sync::watch;++use crate::common::{self, OutputFrame, Project};++pub const RATE: u32 = cap_editor::HEADLESS_SAMPLE_RATE;+pub const CHANNELS: usize = cap_editor::HEADLESS_CHANNELS as usize;+pub const BLOCK: usize = cap_editor::HEADLESS_BLOCK_FRAMES;+/// A pull waits at most this long for its samples to render.+const RENDER_TIMEOUT: Duration = Duration::from_secs(60);++pub fn project(spec: &FixtureSpec) -> Project {+ common::init();+ let path = fixture::ensure_fixture(spec, audio_fixture::write)+ .unwrap_or_else(|e| panic!("fixture {}: {e:?}", spec.name));+ let meta = RecordingMeta::load_for_project(&path).expect("fixture meta");+ let truth = SourceTruth::read(&path).expect("fixture truth");+ Project { path, meta, truth }+}++pub fn audio_model(project: &Project, config: &ProjectConfiguration) -> AudioModel {+ let truth = AudioTruth::read(&project.path, config).expect("audio truth");+ AudioModel::new(&project.meta, config, &truth).expect("audio model")+}++/// Records an audio verdict on a case.+pub fn judge(case: &mut Case, label: &str, report: &AudioReport) {+ if report.passed() {+ case.note(format!("{label}: {}", report.summary()));+ } else {+ case.problem(format!("{label}: {}", report.summary()));+ }+}++/// Checks a mono output starting at output time `start_secs`.+pub fn check_pcm(case: &mut Case, label: &str, model: &AudioModel, mono: &[f32]) -> AudioReport {+ let heard = audio_model::hear(mono, 0.0, &model.rate_windows);+ let report = audio_model::check(model, &heard);+ if std::env::var_os("CAP_VERIFY_DUMP_AUDIO").is_some() {+ for h in &heard {+ eprintln!(" heard {label}: {h:?}");+ }+ for e in &model.expected {+ eprintln!(" expected {label}: {e:?}");+ }+ }+ judge(case, label, &report);+ report+}++/// Plays a project's audio through the editor's real output source+/// pipeline (`AudioOutput::play` -> `install_source` -> pre-render buffer+/// -> playhead sync -> fill), pulled offline block by block.+pub struct OfflinePlayer {+ output: AudioOutput,+ sink: OfflineAudioSink,+ segments: Vec<AudioSegment>,+ music: MusicTracks,+ pub config: ProjectConfiguration,+ pub duration: f64,+ playhead: Option<watch::Sender<f64>>,+ generation: Option<u64>,+ /// Pulls whose samples did not render in time (silence was played).+ pub starved: usize,+}++impl OfflinePlayer {+ pub fn open(+ rt: &tokio::runtime::Runtime,+ project: &Project,+ config: ProjectConfiguration,+ ) -> Self {+ let meta = project.meta.studio_meta().expect("studio").clone();+ let segments = rt.block_on(async {+ let media = cap_editor::create_segments(&project.meta, &meta, false)+ .await+ .expect("segments");+ cap_editor::get_audio_segments(&media).await+ });+ let music = cap_editor::load_music_tracks_uncached(&config, &project.path);+ let (output, sink) = AudioOutput::new_offline();+ let duration = config.timeline.as_ref().map_or(0.0, |t| t.duration());+ Self {+ output,+ sink,+ segments,+ music,+ config,+ duration,+ playhead: None,+ generation: None,+ starved: 0,+ }+ }++ /// Presses play at `start` (stopping any current playback first).+ pub fn play(&mut self, start: f64) {+ self.stop();+ let (tx, rx) = watch::channel(start);+ let generation = self+ .output+ .play(PlaySpec {+ segments: self.segments.clone(),+ music: self.music.clone(),+ project: self.config.clone(),+ duration_secs: self.duration,+ start_playhead_secs: start,+ playhead_rx: rx,+ })+ .expect("offline audio output accepted the play request");+ self.playhead = Some(tx);+ self.generation = Some(generation);+ }++ /// Live seek while playing, as the playback loop sends it.+ pub fn seek(&mut self, to: f64) {+ if let Some(tx) = &self.playhead {+ let _ = tx.send(to);+ }+ }++ pub fn stop(&mut self) {+ if let Some(generation) = self.generation.take() {+ self.output.stop_playback(generation);+ }+ self.playhead = None;+ }++ /// Pulls at least `secs` of interleaved output in device-sized blocks.+ pub fn pull(&mut self, secs: f64) -> Vec<f32> {+ let blocks = (secs * f64::from(RATE) / BLOCK as f64).ceil() as usize;+ let mut out = Vec::with_capacity(blocks * BLOCK * CHANNELS);+ let mut block = vec![0.0f32; BLOCK * CHANNELS];+ for _ in 0..blocks {+ if !self.sink.pull(&mut block, RENDER_TIMEOUT) {+ self.starved += 1;+ }+ out.extend_from_slice(&block);+ }+ out+ }+}++impl Drop for OfflinePlayer {+ fn drop(&mut self) {+ self.stop();+ }+}++pub fn frames_secs(interleaved: &[f32]) -> f64 {+ (interleaved.len() / CHANNELS) as f64 / f64::from(RATE)+}++pub fn mono(interleaved: &[f32]) -> Vec<f32> {+ audio_model::interleaved_mono(interleaved, CHANNELS)+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum ExportPath {+ /// What the app does: `build_for_mp4` (streaming audio when eligible)+ /// then `export_prepared`.+ App,+ /// `build` then `export` (CLI and other callers).+ Plain,+ Mov,+ Gif,+}++impl ExportPath {+ pub fn label(self) -> &'static str {+ match self {+ ExportPath::App => "mp4-app",+ ExportPath::Plain => "mp4-plain",+ ExportPath::Mov => "mov",+ ExportPath::Gif => "gif",+ }+ }++ fn extension(self) -> &'static str {+ match self {+ ExportPath::App | ExportPath::Plain => "mp4",+ ExportPath::Mov => "mov",+ ExportPath::Gif => "gif",+ }+ }+}++pub async fn export(+ project: &Project,+ config: ProjectConfiguration,+ path: ExportPath,+ fps: u32,+ resolution: (u32, u32),+ dir: &Path,+) -> Result<PathBuf, String> {+ let out = dir.join(format!("out.{}", path.extension()));+ let builder = cap_export::ExporterBase::builder(project.path.clone())+ .with_config(config)+ .with_output_path(out);+ let resolution_base = XY::new(resolution.0, resolution.1);+ let mp4 = cap_export::mp4::Mp4ExportSettings {+ fps,+ resolution_base,+ compression: cap_export::mp4::ExportCompression::Social,+ custom_bpp: None,+ force_ffmpeg_decoder: false,+ optimize_filesize: false,+ };+ match path {+ ExportPath::App => {+ let cancel = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));+ let base = builder+ .build_for_mp4(cancel)+ .await+ .map_err(|e| format!("exporter build: {e}"))?;+ mp4.export_prepared(base, |_| true).await+ }+ ExportPath::Plain => {+ let base = builder+ .build()+ .await+ .map_err(|e| format!("exporter build: {e}"))?;+ mp4.export(base, |_| true).await+ }+ ExportPath::Mov => {+ let base = builder+ .build()+ .await+ .map_err(|e| format!("exporter build: {e}"))?;+ cap_export::mov::MovExportSettings {+ fps,+ resolution_base,+ cursor_only: false,+ }+ .export(base, |_| true)+ .await+ }+ ExportPath::Gif => {+ let base = builder+ .build()+ .await+ .map_err(|e| format!("exporter build: {e}"))?;+ cap_export::gif::GifExportSettings {+ fps,+ resolution_base,+ quality: None,+ }+ .export(base, |_| true)+ .await+ }+ }+}++/// Whether a media file has an audio stream.+pub fn has_audio_stream(path: &Path) -> bool {+ media::init();+ ffmpeg::format::input(&path)+ .map(|input| input.streams().best(ffmpeg::media::Type::Audio).is_some())+ .unwrap_or(false)+}++/// Decodes an exported file's audio as mono at the analysis rate, with+/// sample 0 at output time 0.+pub fn exported_mono(path: &Path) -> Result<Vec<f32>, String> {+ let decoded = media::decode_audio(path, Some(audio_model::ANALYSIS_RATE))+ .map_err(|e| format!("decode audio: {e:?}"))?;+ let mut mono = decoded.mono();+ let lead = (decoded.start_secs * f64::from(audio_model::ANALYSIS_RATE)).round() as i64;+ if lead > 0 {+ let mut padded = vec![0.0; lead as usize];+ padded.extend_from_slice(&mono);+ mono = padded;+ } else if lead < 0 {+ mono.drain(..(-lead as usize).min(mono.len()));+ }+ Ok(mono)+}++/// Per clip: (display alignment offset, display nominal fps).+pub fn display_timing(meta: &RecordingMeta) -> Vec<(f64, u32)> {+ let Some(StudioRecordingMeta::MultipleSegments { inner }) = meta.studio_meta() else {+ return Vec::new();+ };+ inner+ .segments+ .iter()+ .map(|segment| {+ let starts = [+ segment.display.start_time,+ segment.camera.as_ref().and_then(|c| c.start_time),+ segment.mic.as_ref().and_then(|m| m.start_time),+ segment.system_audio.as_ref().and_then(|s| s.start_time),+ ];+ let latest = starts+ .iter()+ .flatten()+ .copied()+ .fold(f64::NEG_INFINITY, f64::max);+ let offset = match segment.display.start_time {+ Some(start) if latest.is_finite() => latest - start,+ _ => 0.0,+ };+ (offset, segment.display.fps)+ })+ .collect()+}++/// A/V offset per heard recording marker: the output time the marker is+/// heard minus the output time the screen first shows the source frame+/// that contains the marker's recording time. Must be within one output+/// frame (or one source frame at the segment's speed) plus 5 ms.+pub fn check_av(+ case: &mut Case,+ meta: &RecordingMeta,+ report: &AudioReport,+ frames: &[OutputFrame],+ fps: u32,+) {+ let timing = display_timing(meta);+ let mut worst = 0.0f64;+ let mut bad = Vec::new();+ let mut checked = 0;+ for (expected, heard) in &report.pairs {+ // Partial markers and markers inside a transition (a video blend)+ // have no single source frame to compare with.+ if expected.presence != audio_model::Presence::Required {+ continue;+ }+ let Some((clip, recording_time)) = expected.recording else {+ continue;+ };+ let Some(&(offset, src_fps)) = timing.get(clip) else {+ continue;+ };+ let slot = ((recording_time + offset) * f64::from(src_fps)).floor() as i64;+ // Search near the heard time only: a timeline can show the same+ // source frame again elsewhere (backward jumps, reorders).+ let first = ((heard.time_secs - 0.2) * f64::from(fps)).floor().max(0.0) as usize;+ let shown = frames+ .iter()+ .enumerate()+ .skip(first)+ .take((0.4 * f64::from(fps)).ceil() as usize)+ .find(|(_, f)| {+ f.readout.get(StreamKind::Screen).marker().is_some_and(|m| {+ usize::from(m.segment) == clip+ && (slot..=slot + i64::from(src_fps) / 4).contains(&i64::from(m.index))+ })+ });+ let Some((i, _)) = shown else {+ continue;+ };+ checked += 1;+ let av = heard.time_secs - i as f64 / f64::from(fps);+ let limit = (1.0 / f64::from(fps)).max(1.0 / (f64::from(src_fps) * heard.rate)) + 0.005;+ worst = worst.max(av.abs());+ if av.abs() > limit {+ bad.push(format!(+ "{} #{} heard at {:.4}s, its source frame first shown at {:.4}s ({:+.1} ms)",+ expected.source.name(),+ expected.index,+ heard.time_secs,+ i as f64 / f64::from(fps),+ av * 1000.0+ ));+ }+ }+ let summary = format!(+ "A/V: {checked} markers, worst offset {:.1} ms (limit one frame + 5 ms)",+ worst * 1000.0+ );+ if bad.is_empty() {+ case.note(summary);+ } else {+ case.problem(format!(+ "{summary}, {} out of sync (first: {})",+ bad.len(),+ bad.iter().take(3).cloned().collect::<Vec<_>>().join("; ")+ ));+ }+}