Fix shared audio timing and gate Android builds on native worker tests
android-ci / android-arm64 (push) Failing after 8m46s
android-ci / android-arm64 (push) Failing after 8m46s
This commit is contained in:
1 parent
b58483ed62
commit
f47caf178a
11 files changed
+817
-105
No files matched your search
@@ -275,6 +275,9 @@ pub struct CaptureBlock {
|
||||
pub epoch: u64,
|
||||
pub captured_at: Instant,
|
||||
pub callback_at: Instant,
|
||||
/// Local callback entry time, independent of the calibrated backend clock.
|
||||
pub arrived_at: Instant,
|
||||
pub calibration_uncertainty: Duration,
|
||||
pub frame_position: u64,
|
||||
/// Unsubdivided callback clock observation; shared by all blocks from that callback.
|
||||
pub clock: ClockObservation,
|
||||
@@ -306,6 +309,9 @@ pub struct RenderBlock {
|
||||
/// CPAL's hardware-clock playback estimate, not a measured acoustic time.
|
||||
pub playback_at: Instant,
|
||||
pub callback_at: Instant,
|
||||
/// Queue residence uses local callback entry, not the mapped backend estimate.
|
||||
pub arrived_at: Instant,
|
||||
pub calibration_uncertainty: Duration,
|
||||
pub frame_position: u64,
|
||||
pub clock: ClockObservation,
|
||||
}
|
||||
@@ -430,6 +436,12 @@ pub struct StreamOwner {
|
||||
_owner_thread: PhantomData<Rc<()>>,
|
||||
}
|
||||
impl StreamOwner {
|
||||
#[cfg(test)]
|
||||
pub(super) fn test(format: DeviceFormat, epoch: u64, origin: Instant) -> Self {
|
||||
let state = Arc::new(StreamState::new(epoch, origin));
|
||||
assert!(state.resume());
|
||||
Self { stream: None, state, device_id: "test-only".into(), format, _owner_thread: PhantomData }
|
||||
}
|
||||
/// Pausing closes the OS stream on its owner. Resume is a fresh permitted
|
||||
/// start, so backends without hardware pause cannot silently keep recording.
|
||||
pub fn pause(&mut self) { self.stop(); }
|
||||
@@ -446,15 +458,21 @@ impl Drop for StreamOwner { fn drop(&mut self) { self.stop(); } }
|
||||
/// Common monotonic mapping calibrated on the owner before play. Each stream
|
||||
/// has its own CPAL origin, so CPAL timestamps from different sinks are never
|
||||
/// subtracted directly. Calibration does not use callback arrival cadence.
|
||||
struct ClockAnchor { origin: Instant, device_ns: AtomicU64, local_ns: AtomicU64 }
|
||||
struct ClockAnchor { origin: Instant, device_ns: AtomicU64, local_ns: AtomicU64, uncertainty_ns: AtomicU64 }
|
||||
impl ClockAnchor {
|
||||
fn new(origin: Instant) -> Self { Self { origin, device_ns: AtomicU64::new(0), local_ns: AtomicU64::new(0) } }
|
||||
fn new(origin: Instant) -> Self { Self { origin, device_ns: AtomicU64::new(0), local_ns: AtomicU64::new(0), uncertainty_ns: AtomicU64::new(0) } }
|
||||
fn calibrate(&self, stream: &cpal::Stream) {
|
||||
let before = Instant::now();
|
||||
let device = stream.now();
|
||||
let after = Instant::now();
|
||||
let midpoint = before + after.duration_since(before) / 2;
|
||||
self.set_calibration(before, device, after);
|
||||
}
|
||||
fn set_calibration(&self, before: Instant, device: StreamInstant, after: Instant) {
|
||||
let bracket = after.duration_since(before);
|
||||
let midpoint = before + bracket / 2;
|
||||
self.device_ns.store(device.as_nanos().min(u64::MAX as u128) as u64, Ordering::Relaxed);
|
||||
// Round up: an odd-nanosecond bracket must not understate uncertainty.
|
||||
self.uncertainty_ns.store(nanos(bracket).div_ceil(2), Ordering::Relaxed);
|
||||
self.local_ns.store(nanos(midpoint.duration_since(self.origin)), Ordering::Release);
|
||||
}
|
||||
fn map(&self, timestamp: StreamInstant) -> Option<Instant> {
|
||||
@@ -464,6 +482,7 @@ impl ClockAnchor {
|
||||
if mapped >= 0 { self.origin.checked_add(Duration::from_nanos(u64::try_from(mapped).ok()?)) }
|
||||
else { self.origin.checked_sub(Duration::from_nanos(u64::try_from(-mapped).ok()?)) }
|
||||
}
|
||||
fn uncertainty(&self) -> Duration { Duration::from_nanos(self.uncertainty_ns.load(Ordering::Relaxed)) }
|
||||
}
|
||||
fn nanos(duration: Duration) -> u64 { duration.as_nanos().min(u64::MAX as u128) as u64 }
|
||||
fn frames_duration(frames: u64, rate: u32) -> Duration {
|
||||
@@ -499,7 +518,7 @@ impl CaptureCallback {
|
||||
let count = BLOCK_FRAMES.min(frames - offset);
|
||||
let Some(at) = captured_at.checked_add(frames_duration(offset as u64, self.format.sample_rate)) else { self.state.fail(StreamFault::ClockDiscontinuity); return; };
|
||||
if !self.state.accepts_capture(epoch, at, now) { continue; }
|
||||
let mut block = CaptureBlock { samples: [0.0; BLOCK_FRAMES], frames: count, sample_rate: self.format.sample_rate, epoch, captured_at: at, callback_at, frame_position: position + offset as u64, clock: ClockObservation { at: captured_at, position } };
|
||||
let mut block = CaptureBlock { samples: [0.0; BLOCK_FRAMES], frames: count, sample_rate: self.format.sample_rate, epoch, captured_at: at, callback_at, arrived_at: now, calibration_uncertainty: self.clock.uncertainty(), frame_position: position + offset as u64, clock: ClockObservation { at: captured_at, position } };
|
||||
for (output, input) in block.samples[..count].iter_mut().zip(data[offset * channels..(offset + count) * channels].chunks_exact(channels)) {
|
||||
let mut mono = 0.0;
|
||||
for &sample in input { mono += finite_sample(<f32 as cpal::Sample>::from_sample(sample)); }
|
||||
@@ -578,7 +597,7 @@ impl PlaybackCallback {
|
||||
for offset in (0..frames).step_by(BLOCK_FRAMES) {
|
||||
let count = BLOCK_FRAMES.min(frames - offset);
|
||||
let Some(at) = playback_at.checked_add(frames_duration(offset as u64, self.format.sample_rate)) else { self.state.fail(StreamFault::ClockDiscontinuity); return; };
|
||||
let mut rendered = RenderBlock { samples: [0.0; BLOCK_FRAMES], frames: count, sample_rate: self.format.sample_rate, epoch, playback_at: at, callback_at, frame_position: position + offset as u64, clock: ClockObservation { at: playback_at, position } };
|
||||
let mut rendered = RenderBlock { samples: [0.0; BLOCK_FRAMES], frames: count, sample_rate: self.format.sample_rate, epoch, playback_at: at, callback_at, arrived_at: now, calibration_uncertainty: self.clock.uncertainty(), frame_position: position + offset as u64, clock: ClockObservation { at: playback_at, position } };
|
||||
for (index, frame) in data[offset * channels..(offset + count) * channels].chunks_exact_mut(channels).enumerate() {
|
||||
let stereo = match self.next_frame(epoch, now, playback_at, offset + index, &mut deadline_checked, &mut budget) {
|
||||
Some(stereo) => [finite_sample(stereo[0]), finite_sample(stereo[1])],
|
||||
|
||||
@@ -101,6 +101,8 @@ fn capture_splits_variable_callback_and_preserves_hardware_clock() {
|
||||
assert_eq!(block.frame_position, position);
|
||||
assert_eq!(block.captured_at, origin + frames_duration(position, 48_000));
|
||||
assert_eq!(block.callback_at, origin + Duration::from_millis(15));
|
||||
assert_eq!(block.arrived_at, origin + Duration::from_millis(15));
|
||||
assert_eq!(block.calibration_uncertainty, Duration::ZERO);
|
||||
assert_eq!(block.epoch, 7);
|
||||
assert!(block.samples[..frames].iter().all(|&sample| sample == 0.5));
|
||||
}
|
||||
@@ -166,6 +168,38 @@ fn clock_mapping_aligns_independent_stream_origins_without_callback_jitter() {
|
||||
assert_eq!(a.map(StreamInstant::from_millis(9990)), origin.checked_sub(Duration::from_millis(8)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn calibrated_bracket_is_retained_without_replacing_hardware_capture_time() {
|
||||
let (mut callback, mut samples, origin) = capture_fixture(48_000, 1, 2);
|
||||
callback.clock.set_calibration(origin, StreamInstant::from_millis(0), origin + Duration::from_millis(10));
|
||||
callback.process(&[0.5_f32; 48], input_time(0, 20), origin + Duration::from_millis(6));
|
||||
let block = samples.try_pop().unwrap();
|
||||
assert_eq!(block.captured_at, origin + Duration::from_millis(5));
|
||||
assert_eq!(block.callback_at, origin + Duration::from_millis(25));
|
||||
assert_eq!(block.arrived_at, origin + Duration::from_millis(6));
|
||||
assert_eq!(block.calibration_uncertainty, Duration::from_millis(5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn calibration_uncertainty_does_not_authorize_future_hardware_capture() {
|
||||
let (mut callback, mut samples, origin) = capture_fixture(48_000, 1, 2);
|
||||
callback.clock.set_calibration(origin, StreamInstant::from_millis(0), origin + Duration::from_millis(10));
|
||||
callback.process(&[0.5_f32; 48], input_time(0, 1), origin + Duration::from_millis(4));
|
||||
assert!(samples.try_pop().is_none(), "mapped capture remains future even within the calibration bracket");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_queue_arrival_is_not_the_mapped_backend_callback() {
|
||||
let (mut callback, _samples, mut rendered, origin) = playback_fixture(48_000, 1, 2);
|
||||
callback.clock.set_calibration(origin, StreamInstant::from_millis(0), origin + Duration::from_nanos(3));
|
||||
callback.process(&mut [0.0_f32; 48], output_time(20, 30), origin + Duration::from_millis(1));
|
||||
let block = rendered.try_pop().unwrap();
|
||||
assert_eq!(block.arrived_at, origin + Duration::from_millis(1));
|
||||
assert_eq!(block.callback_at, origin + Duration::from_millis(20) + Duration::from_nanos(1));
|
||||
assert_eq!(block.playback_at, origin + Duration::from_millis(30) + Duration::from_nanos(1));
|
||||
assert_eq!(block.calibration_uncertainty, Duration::from_nanos(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn device_clock_discontinuity_disables_capture() {
|
||||
let (mut callback, mut samples, origin) = capture_fixture(48_000, 1, 2);
|
||||
|
||||
@@ -127,6 +127,44 @@ pub struct AudioFirstFault {
|
||||
pub notification_revision: u64,
|
||||
pub input: Option<StreamStats>,
|
||||
pub outputs: [Option<StreamStats>; 2],
|
||||
pub freshness: Option<AudioFreshnessFault>,
|
||||
}
|
||||
/// Signed ages keep clock-future failures distinct from expired queues. No PCM or IDs.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum AudioFreshnessReason { InvalidFrames, NegativeAge, Expired, Epoch, Boundary }
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct AudioFreshnessFault {
|
||||
pub reason: AudioFreshnessReason,
|
||||
pub frames: usize,
|
||||
/// Queue occupancy immediately after removing the rejected block.
|
||||
pub remaining_blocks: usize,
|
||||
pub queue_capacity: usize,
|
||||
pub queue_age_ns: i64,
|
||||
pub hardware_age_ns: i64,
|
||||
pub mapped_callback_age_ns: i64,
|
||||
pub calibration_uncertainty_ns: u64,
|
||||
}
|
||||
impl AudioFreshnessFault {
|
||||
fn new(reason: AudioFreshnessReason, frames: usize, remaining_blocks: usize, queue_capacity: usize,
|
||||
now: Instant, arrived_at: Instant, hardware_at: Instant, callback_at: Instant, uncertainty: Duration) -> Self {
|
||||
Self { reason, frames, remaining_blocks, queue_capacity, queue_age_ns: signed_age_ns(now, arrived_at),
|
||||
hardware_age_ns: signed_age_ns(now, hardware_at), mapped_callback_age_ns: signed_age_ns(now, callback_at),
|
||||
calibration_uncertainty_ns: uncertainty.as_nanos().min(u64::MAX as u128) as u64 }
|
||||
}
|
||||
}
|
||||
fn signed_age_ns(now: Instant, at: Instant) -> i64 {
|
||||
if now >= at { now.duration_since(at).as_nanos().min(i64::MAX as u128) as i64 }
|
||||
else { -(at.duration_since(now).as_nanos().min(i64::MAX as u128) as i64) }
|
||||
}
|
||||
fn freshness_reason(frames: usize, now: Instant, arrived_at: Instant, captured_at: Option<Instant>) -> Option<AudioFreshnessReason> {
|
||||
if frames == 0 || frames > devices::BLOCK_FRAMES { return Some(AudioFreshnessReason::InvalidFrames); }
|
||||
let queue_age = now.checked_duration_since(arrived_at);
|
||||
let hardware_age = captured_at.map(|at| now.checked_duration_since(at));
|
||||
if queue_age.is_none() || hardware_age == Some(None) { return Some(AudioFreshnessReason::NegativeAge); }
|
||||
if queue_age.is_some_and(|age| age > MAX_AGE) || hardware_age.flatten().is_some_and(|age| age > MAX_AGE) {
|
||||
return Some(AudioFreshnessReason::Expired);
|
||||
}
|
||||
None
|
||||
}
|
||||
#[derive(Default)]
|
||||
struct FirstFault { snapshot: Mutex<Option<AudioFirstFault>> }
|
||||
@@ -315,7 +353,7 @@ impl AudioEngine {
|
||||
worker_shared.first_fault.record(AudioFirstFault {
|
||||
code: fault_code(&error.code), stage: "worker_init", command: "none", direction: None,
|
||||
capture_revision: worker_shared.revision.load(Ordering::Acquire), output_revision: worker_shared.outputs.revision(),
|
||||
worker_output_revision: 0, stream_revision: 0, notification_revision: 0, input: None, outputs: [None; 2],
|
||||
worker_output_revision: 0, stream_revision: 0, notification_revision: 0, input: None, outputs: [None; 2], freshness: None,
|
||||
});
|
||||
*worker_shared.terminal_error.lock().expect("audio terminal error") = Some(error.clone());
|
||||
let _ = events.try_send(AudioEvent::Error(error));
|
||||
@@ -355,8 +393,7 @@ struct MonoConversion {
|
||||
input: Vec<f32>,
|
||||
output: Vec<f32>,
|
||||
used: usize,
|
||||
first: Option<Instant>,
|
||||
produced: u64,
|
||||
first_position: Option<u64>,
|
||||
clock: ClockTracker,
|
||||
next_position: Option<u64>,
|
||||
}
|
||||
@@ -364,15 +401,15 @@ impl MonoConversion {
|
||||
fn new(rate: u32) -> Result<Self> {
|
||||
let converter = AudioResampler::new_capture(rate, 1)?;
|
||||
Ok(Self { input: vec![0.; converter.input_frames_max() + devices::BLOCK_FRAMES],
|
||||
output: vec![0.; converter.output_frames_max()], converter, used: 0, first: None,
|
||||
produced: 0, clock: ClockTracker::new(rate)?, next_position: None })
|
||||
output: vec![0.; converter.output_frames_max()], converter, used: 0, first_position: None,
|
||||
clock: ClockTracker::new(rate)?, next_position: None })
|
||||
}
|
||||
fn reset(&mut self) -> Result<()> {
|
||||
self.converter.reset()?; self.clock.reset(); self.input.fill(0.0); self.output.fill(0.0);
|
||||
self.used = 0; self.first = None; self.produced = 0; self.next_position = None;
|
||||
self.used = 0; self.first_position = None; self.next_position = None;
|
||||
Ok(())
|
||||
}
|
||||
fn append(&mut self, samples: &[f32], at: Instant, position: u64, observation: ClockObservation) -> Result<()> {
|
||||
fn append(&mut self, samples: &[f32], position: u64, observation: ClockObservation) -> Result<()> {
|
||||
if self.next_position.is_some_and(|next| position < next) {
|
||||
return Err(ServiceError::new("audio_clock_discontinuity", "FramePositionReversed"));
|
||||
}
|
||||
@@ -381,7 +418,7 @@ impl MonoConversion {
|
||||
}
|
||||
self.next_position = Some(position + samples.len() as u64);
|
||||
if self.used + samples.len() > self.input.len() { return Err(ServiceError::new("audio_buffer", "Mono conversion accumulation overflow")); }
|
||||
self.first.get_or_insert(at);
|
||||
self.first_position.get_or_insert(position);
|
||||
self.input[self.used..self.used + samples.len()].copy_from_slice(samples);
|
||||
self.used += samples.len();
|
||||
Ok(())
|
||||
@@ -392,9 +429,10 @@ impl MonoConversion {
|
||||
if counts.produced != 480 { return Err(ServiceError::new("audio_buffer", "Capture converter did not produce a ten-millisecond block")); }
|
||||
self.input.copy_within(counts.consumed..self.used, 0);
|
||||
self.used -= counts.consumed;
|
||||
let first = self.first.expect("samples establish hardware origin");
|
||||
let at = (first + sample_duration(self.produced, 48_000)).checked_sub(self.converter.output_delay()).unwrap_or(first);
|
||||
self.produced += counts.produced as u64;
|
||||
let source_position = self.first_position.expect("samples establish hardware origin") as f64
|
||||
+ self.converter.last_output_source_position();
|
||||
let at = self.clock.timestamp(source_position).and_then(|at| at.checked_sub(self.converter.output_delay()))
|
||||
.ok_or_else(|| ServiceError::new("audio_clock_discontinuity", "Source hardware timestamp is not representable"))?;
|
||||
let mut pcm = [0.; 480];
|
||||
pcm.copy_from_slice(&self.output[..480]);
|
||||
Ok(Some((pcm, at)))
|
||||
@@ -681,6 +719,10 @@ impl Worker {
|
||||
self.current_command = "none";
|
||||
}
|
||||
fn record_fault(&self, stage: &'static str, direction: Option<Direction>, error: &ServiceError, extra: Option<StreamStats>) {
|
||||
self.record_fault_detail(stage, direction, error, extra, None);
|
||||
}
|
||||
fn record_fault_detail(&self, stage: &'static str, direction: Option<Direction>, error: &ServiceError,
|
||||
extra: Option<StreamStats>, freshness: Option<AudioFreshnessFault>) {
|
||||
if self.shared.first_fault.get().is_some() { return; }
|
||||
let mut input = self.input.as_ref().map(|input| input.port.state.stats());
|
||||
let mut outputs = [None; 2];
|
||||
@@ -698,7 +740,7 @@ impl Worker {
|
||||
code: fault_code(&error.code), stage, command: self.current_command, direction,
|
||||
capture_revision: self.shared.revision.load(Ordering::Acquire), output_revision: self.shared.outputs.revision(),
|
||||
worker_output_revision: self.output_revision, stream_revision: self.shared.outputs.stream_revision.load(Ordering::Acquire),
|
||||
notification_revision: self.notifications.revision(), input, outputs,
|
||||
notification_revision: self.notifications.revision(), input, outputs, freshness,
|
||||
});
|
||||
}
|
||||
fn observe_stream_faults(&self, stage: &'static str) {
|
||||
@@ -1027,39 +1069,58 @@ impl Worker {
|
||||
if !accepted { return Err(ServiceError::new("audio_playback_rejected", "Playback PCM was stale, disabled, or belonged to an old route")); }
|
||||
Ok(())
|
||||
}
|
||||
fn render_references(&mut self) -> Result<()> {
|
||||
let now = Instant::now();
|
||||
for output in &mut self.outputs {
|
||||
if let Some(error) = output.port.state.fault().service_error() { return Err(error); }
|
||||
for _ in 0..output.port.rendered.capacity() {
|
||||
let Some(block) = output.port.rendered.try_pop() else { break; };
|
||||
if block.epoch != output.epoch { continue; }
|
||||
if block.frames == 0 || block.frames > devices::BLOCK_FRAMES ||
|
||||
now.checked_duration_since(block.callback_at).is_none_or(|age| age > MAX_AGE) {
|
||||
return Err(ServiceError::new("audio_reference_stale", "Playback reference no longer matches the live hardware clock"));
|
||||
fn render_references(&mut self) -> Result<()> { self.render_references_with_clock(Instant::now) }
|
||||
fn render_references_with_clock(&mut self, mut clock: impl FnMut() -> Instant) -> Result<()> {
|
||||
for index in 0..self.outputs.len() {
|
||||
if let Some(error) = self.outputs[index].port.state.fault().service_error() { return Err(error); }
|
||||
for _ in 0..self.outputs[index].port.rendered.capacity() {
|
||||
let Some(block) = self.outputs[index].port.rendered.try_pop() else { break; };
|
||||
// Sample only after acquiring this block: the producer can enqueue
|
||||
// between pops, after any previous worker clock sample.
|
||||
let now = clock();
|
||||
if block.epoch != self.outputs[index].epoch { continue; }
|
||||
if let Some(reason) = freshness_reason(block.frames, now, block.arrived_at, None) {
|
||||
let queue = &self.outputs[index].port.rendered;
|
||||
let detail = AudioFreshnessFault::new(reason, block.frames, queue.occupied_len(), queue.capacity(),
|
||||
now, block.arrived_at, block.playback_at, block.callback_at, block.calibration_uncertainty);
|
||||
let error = ServiceError::new("audio_reference_stale", "Playback reference no longer matches the live hardware clock");
|
||||
self.record_fault_detail("render_reference", Some(Direction::Output), &error, None, Some(detail));
|
||||
return Err(error);
|
||||
}
|
||||
output.reverse.append(&block.samples[..block.frames], block.playback_at, block.frame_position, block.clock)?;
|
||||
let output = &mut self.outputs[index];
|
||||
output.reverse.append(&block.samples[..block.frames], block.frame_position, block.clock)?;
|
||||
output.conversion.set_device_drift_ppm(output.reverse.clock.drift_ppm())?;
|
||||
while let Some((pcm, at)) = output.reverse.next()? { self.references.add(&pcm, at); }
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn capture_blocks(&mut self) -> Result<()> {
|
||||
let now = Instant::now();
|
||||
let Some(input) = &mut self.input else { return Ok(()); };
|
||||
fn capture_blocks(&mut self) -> Result<()> { self.capture_blocks_with_clock(Instant::now) }
|
||||
fn capture_blocks_with_clock(&mut self, mut clock: impl FnMut() -> Instant) -> Result<()> {
|
||||
let Some(input) = &self.input else { return Ok(()); };
|
||||
if let Some(error) = input.port.state.fault().service_error() { return Err(error); }
|
||||
if now.duration_since(input.last) > MAX_AGE { return Err(ServiceError::new("audio_input_timeout", "Microphone produced no fresh PCM for 200 ms")); }
|
||||
let capacity = input.port.samples.capacity();
|
||||
let mut test_finished = false;
|
||||
for _ in 0..input.port.samples.capacity() {
|
||||
let Some(block) = input.port.samples.try_pop() else { break; };
|
||||
for _ in 0..capacity {
|
||||
let Some(block) = self.input.as_mut().expect("capture input").port.samples.try_pop() else { break; };
|
||||
let now = clock();
|
||||
if self.shared.revision.load(Ordering::Acquire) != self.revision { break; }
|
||||
if block.epoch != input.port.state.epoch() || block.frames == 0 || block.frames > devices::BLOCK_FRAMES ||
|
||||
block.captured_at < input.boundary || now.checked_duration_since(block.captured_at).is_none_or(|age| age > MAX_AGE) {
|
||||
return Err(ServiceError::new("audio_capture_stale", "Microphone PCM crossed a capture boundary or exceeded 200 ms"));
|
||||
let input = self.input.as_ref().expect("capture input");
|
||||
let reason = if block.epoch != input.port.state.epoch() { Some(AudioFreshnessReason::Epoch) }
|
||||
else if block.frames == 0 || block.frames > devices::BLOCK_FRAMES { Some(AudioFreshnessReason::InvalidFrames) }
|
||||
else if block.captured_at < input.boundary { Some(AudioFreshnessReason::Boundary) }
|
||||
else { freshness_reason(block.frames, now, block.arrived_at, Some(block.captured_at)) };
|
||||
if let Some(reason) = reason {
|
||||
let queue = &input.port.samples;
|
||||
let detail = AudioFreshnessFault::new(reason, block.frames, queue.occupied_len(), queue.capacity(),
|
||||
now, block.arrived_at, block.captured_at, block.callback_at, block.calibration_uncertainty);
|
||||
let error = ServiceError::new("audio_capture_stale", "Microphone PCM crossed a capture boundary or exceeded 200 ms");
|
||||
self.record_fault_detail("capture", Some(Direction::Input), &error, None, Some(detail));
|
||||
return Err(error);
|
||||
}
|
||||
input.last = now;
|
||||
input.conversion.append(&block.samples[..block.frames], block.captured_at, block.frame_position, block.clock)?;
|
||||
let input = self.input.as_mut().expect("capture input");
|
||||
input.last = block.arrived_at;
|
||||
input.conversion.append(&block.samples[..block.frames], block.frame_position, block.clock)?;
|
||||
while let Some((mut pcm, at)) = input.conversion.next()? {
|
||||
if at < input.boundary { continue; }
|
||||
if self.shared.revision.load(Ordering::Acquire) != self.revision { break; }
|
||||
@@ -1079,6 +1140,12 @@ impl Worker {
|
||||
}
|
||||
}
|
||||
}
|
||||
// A worker delay is not a microphone timeout if fresh input is already
|
||||
// queued. Inspect the bounded live ring first, then check callback arrival.
|
||||
let input = self.input.as_ref().expect("capture input");
|
||||
if clock().saturating_duration_since(input.last) > MAX_AGE {
|
||||
return Err(ServiceError::new("audio_input_timeout", "Microphone produced no fresh PCM for 200 ms"));
|
||||
}
|
||||
if test_finished {
|
||||
self.stop_capture();
|
||||
self.emit(AudioEvent::MicrophoneTest { state: MicrophoneTestState::Ready, samples: TEST_SAMPLES });
|
||||
@@ -1169,7 +1236,6 @@ fn fault_code(code: &str) -> &'static str {
|
||||
"audio_worker" => "audio_worker", _ => "audio_other",
|
||||
}
|
||||
}
|
||||
fn sample_duration(frames: u64, rate: u32) -> Duration { Duration::from_secs_f64(frames as f64 / f64::from(rate)) }
|
||||
fn changed() -> ServiceError { ServiceError::new("target_changed", "Audio permit, connection, or privacy epoch changed") }
|
||||
fn closed() -> ServiceError { ServiceError::new("audio_closed", "Audio worker is stopped") }
|
||||
fn queue_error<T>(error: TrySendError<T>) -> ServiceError {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Engine algorithm and ordered command-consumer tests. No CPAL endpoint or server connection.
|
||||
use super::*;
|
||||
fn sample_duration(frames: u64, rate: u32) -> Duration { Duration::from_secs_f64(frames as f64 / f64::from(rate)) }
|
||||
|
||||
#[test]
|
||||
fn render_references_sum_physical_sinks_at_their_playback_times() {
|
||||
@@ -41,11 +42,11 @@ fn callback_chunks_are_converted_to_fixed_capture_blocks_without_retiming() {
|
||||
for packet in 0..160_u64 {
|
||||
let position = packet * 256;
|
||||
let at = origin + sample_duration(position, rate);
|
||||
conversion.append(&[0.25; 256], at, position, ClockObservation { at, position }).unwrap();
|
||||
conversion.append(&[0.25; 256], position, ClockObservation { at, position }).unwrap();
|
||||
while let Some((samples, timestamp)) = conversion.next().unwrap() {
|
||||
assert!(samples.iter().all(|sample| sample.is_finite()));
|
||||
let expected = (origin + sample_duration(produced, 48_000)).checked_sub(delay).unwrap_or(origin);
|
||||
assert_eq!(timestamp, expected);
|
||||
assert!(signed_age_ns(timestamp, expected).abs() <= 1_000);
|
||||
produced += 480;
|
||||
}
|
||||
}
|
||||
@@ -59,13 +60,13 @@ fn callback_chunks_are_converted_to_fixed_capture_blocks_without_retiming() {
|
||||
fn reversed_hardware_clock_is_an_error_not_unprocessed_fallback() {
|
||||
let origin = Instant::now();
|
||||
let mut conversion = MonoConversion::new(48_000).unwrap();
|
||||
conversion.append(&[0.1; 256], origin + TICK, 256, ClockObservation { at: origin + TICK, position: 256 }).unwrap();
|
||||
let error = conversion.append(&[0.2; 256], origin, 512, ClockObservation { at: origin, position: 512 }).unwrap_err();
|
||||
conversion.append(&[0.1; 256], 256, ClockObservation { at: origin + TICK, position: 256 }).unwrap();
|
||||
let error = conversion.append(&[0.2; 256], 512, ClockObservation { at: origin, position: 512 }).unwrap_err();
|
||||
assert_eq!(error.code, "audio_clock_discontinuity");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_callback_estimates_do_not_reverse_the_sample_clock() {
|
||||
fn overlapping_callback_estimates_preserve_raw_hardware_source_projection() {
|
||||
for rate in [44_100, 48_000] {
|
||||
let origin = Instant::now();
|
||||
let mut conversion = MonoConversion::new(rate).unwrap();
|
||||
@@ -78,11 +79,16 @@ fn overlapping_callback_estimates_do_not_reverse_the_sample_clock() {
|
||||
else { origin + sample_duration(position, rate) };
|
||||
let clock = ClockObservation { at, position };
|
||||
for offset in (0..1024).step_by(256) {
|
||||
conversion.append(&[0.25; 256], at + sample_duration(offset, rate), position + offset, clock).unwrap();
|
||||
conversion.append(&[0.25; 256], position + offset, clock).unwrap();
|
||||
while let Some((pcm, timestamp)) = conversion.next().unwrap() {
|
||||
assert!(pcm.iter().all(|value| value.is_finite()));
|
||||
let expected = (origin + sample_duration(produced, 48_000)).checked_sub(conversion.converter.output_delay()).unwrap_or(origin);
|
||||
assert_eq!(timestamp, expected);
|
||||
// Project actual SRC phase from this callback, not a made-up
|
||||
// perfectly regular timeline anchored to stream startup.
|
||||
let source = conversion.converter.last_output_source_position();
|
||||
let seconds = (source - position as f64) / f64::from(rate);
|
||||
let delta = Duration::from_secs_f64(seconds.abs());
|
||||
let hardware = if seconds < 0.0 { at - delta } else { at + delta };
|
||||
assert!(signed_age_ns(timestamp, hardware - conversion.converter.output_delay()).abs() <= 2);
|
||||
produced += 480;
|
||||
}
|
||||
}
|
||||
@@ -97,8 +103,8 @@ fn sample_position_reversal_is_rejected_even_with_a_repeated_callback_clock() {
|
||||
let origin = Instant::now();
|
||||
let clock = ClockObservation { at: origin, position: 0 };
|
||||
let mut conversion = MonoConversion::new(48_000).unwrap();
|
||||
conversion.append(&[0.1; 256], origin, 0, clock).unwrap();
|
||||
let error = conversion.append(&[0.1; 256], origin, 0, clock).unwrap_err();
|
||||
conversion.append(&[0.1; 256], 0, clock).unwrap();
|
||||
let error = conversion.append(&[0.1; 256], 0, clock).unwrap_err();
|
||||
assert_eq!(error.code, "audio_clock_discontinuity");
|
||||
}
|
||||
|
||||
@@ -454,3 +460,252 @@ fn first_fault_retains_counters_across_cleanup_and_cannot_be_overwritten() {
|
||||
assert!(worker.outputs.is_empty());
|
||||
assert_eq!(fault_code("server-or-device-identifier"), "audio_other");
|
||||
}
|
||||
|
||||
fn drain_format() -> devices::DeviceFormat {
|
||||
devices::DeviceFormat { sample_rate: 48_000, channels: 1, sample_format: cpal::SampleFormat::F32,
|
||||
buffer_size: cpal::BufferSize::Default }
|
||||
}
|
||||
fn capture_drain_fixture(capacity: usize) -> (Worker, AudioHandle, super::super::ring::Producer<devices::CaptureBlock>, Instant) {
|
||||
let (mut worker, handle, _, _) = command_fixture();
|
||||
let origin = Instant::now();
|
||||
let owner = StreamOwner::test(drain_format(), 7, origin);
|
||||
let (producer, samples) = super::super::ring::channel(capacity);
|
||||
let port = CapturePort { samples, state: owner.state.clone() };
|
||||
worker.input = Some(Input { _owner: owner, port, conversion: MonoConversion::new(48_000).unwrap(), boundary: origin, last: origin });
|
||||
(worker, handle, producer, origin)
|
||||
}
|
||||
fn render_drain_fixture(capacity: usize) -> (Worker, AudioHandle, super::super::ring::Producer<devices::RenderBlock>, Instant) {
|
||||
let (mut worker, handle, _, _) = command_fixture();
|
||||
let origin = Instant::now();
|
||||
let owner = StreamOwner::test(drain_format(), 7, origin);
|
||||
let (samples, _consumer) = super::super::ring::channel(capacity);
|
||||
let (producer, rendered) = super::super::ring::channel(capacity);
|
||||
let port = PlaybackPort { samples, rendered, state: owner.state.clone() };
|
||||
worker.outputs.push(Output::new(owner, port, PreparedOutput::new(48_000).unwrap(), 7, worker.output_revision));
|
||||
(worker, handle, producer, origin)
|
||||
}
|
||||
fn capture_packet(at: Instant, position: u64) -> devices::CaptureBlock {
|
||||
devices::CaptureBlock { samples: [0.25; devices::BLOCK_FRAMES], frames: 48, sample_rate: 48_000,
|
||||
epoch: 7, captured_at: at, callback_at: at, arrived_at: at, calibration_uncertainty: Duration::ZERO,
|
||||
frame_position: position, clock: ClockObservation { at, position } }
|
||||
}
|
||||
fn render_packet(at: Instant, position: u64) -> devices::RenderBlock {
|
||||
devices::RenderBlock { samples: [0.25; devices::BLOCK_FRAMES], frames: 48, sample_rate: 48_000,
|
||||
epoch: 7, playback_at: at, callback_at: at, arrived_at: at, calibration_uncertainty: Duration::ZERO,
|
||||
frame_position: position, clock: ClockObservation { at, position } }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn production_render_drain_accepts_a_producer_callback_between_pops() {
|
||||
let (mut worker, handle, mut producer, origin) = render_drain_fixture(2);
|
||||
producer.try_push(render_packet(origin, 0)).unwrap();
|
||||
let (request, requested) = mpsc::sync_channel(0);
|
||||
let (published, publication) = mpsc::sync_channel(0);
|
||||
let producer = thread::spawn(move || {
|
||||
requested.recv().unwrap();
|
||||
producer.try_push(render_packet(origin + Duration::from_millis(1), 48)).unwrap();
|
||||
published.send(()).unwrap();
|
||||
});
|
||||
let mut samples = 0;
|
||||
worker.render_references_with_clock(|| {
|
||||
samples += 1;
|
||||
if samples == 1 {
|
||||
// The first block has already been popped. Publish the next callback
|
||||
// with a timestamp later than this first clock sample.
|
||||
request.send(()).unwrap();
|
||||
publication.recv().unwrap();
|
||||
origin
|
||||
} else { origin + Duration::from_millis(2) }
|
||||
}).unwrap();
|
||||
producer.join().unwrap();
|
||||
assert_eq!(samples, 2);
|
||||
assert_eq!(worker.outputs[0].reverse.next_position, Some(96));
|
||||
assert_eq!(worker.outputs[0].port.rendered.occupied_len(), 0);
|
||||
assert!(handle.first_fault().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn production_capture_drain_accepts_a_producer_callback_between_pops() {
|
||||
let (mut worker, handle, mut producer, origin) = capture_drain_fixture(2);
|
||||
producer.try_push(capture_packet(origin, 0)).unwrap();
|
||||
let (request, requested) = mpsc::sync_channel(0);
|
||||
let (published, publication) = mpsc::sync_channel(0);
|
||||
let producer = thread::spawn(move || {
|
||||
requested.recv().unwrap();
|
||||
producer.try_push(capture_packet(origin + Duration::from_millis(1), 48)).unwrap();
|
||||
published.send(()).unwrap();
|
||||
});
|
||||
let mut samples = 0;
|
||||
worker.capture_blocks_with_clock(|| {
|
||||
samples += 1;
|
||||
if samples == 1 {
|
||||
request.send(()).unwrap();
|
||||
publication.recv().unwrap();
|
||||
origin
|
||||
} else { origin + Duration::from_millis(2) }
|
||||
}).unwrap();
|
||||
producer.join().unwrap();
|
||||
assert_eq!(samples, 3, "two post-pop observations and one final timeout check");
|
||||
assert_eq!(worker.input.as_ref().unwrap().conversion.next_position, Some(96));
|
||||
assert!(handle.first_fault().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn production_capture_timeout_checks_queued_fresh_pcm_before_failing() {
|
||||
let (mut worker, handle, mut producer, origin) = capture_drain_fixture(2);
|
||||
let now = origin + MAX_AGE + Duration::from_millis(1);
|
||||
producer.try_push(capture_packet(now, 0)).unwrap();
|
||||
worker.capture_blocks_with_clock(|| now).unwrap();
|
||||
assert_eq!(worker.input.as_ref().unwrap().last, now);
|
||||
assert!(handle.first_fault().is_none());
|
||||
assert_eq!(worker.capture_blocks_with_clock(|| now + MAX_AGE + Duration::from_nanos(1)).unwrap_err().code, "audio_input_timeout");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn production_render_drain_uses_local_residence_and_preserves_backend_estimates() {
|
||||
let (mut worker, handle, mut producer, origin) = render_drain_fixture(2);
|
||||
let mut block = render_packet(origin, 0);
|
||||
block.callback_at = origin + Duration::from_millis(10);
|
||||
block.playback_at = origin + Duration::from_millis(20);
|
||||
block.clock.at = block.playback_at;
|
||||
block.calibration_uncertainty = Duration::from_millis(2);
|
||||
producer.try_push(block).unwrap();
|
||||
worker.render_references_with_clock(|| origin).unwrap();
|
||||
assert!(handle.first_fault().is_none());
|
||||
assert_eq!(worker.outputs[0].reverse.clock.timestamp(0.0), Some(block.playback_at));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn production_render_drain_classifies_stale_faults_before_teardown() {
|
||||
for (frames, age, expected) in [
|
||||
(0, 1_i64, AudioFreshnessReason::InvalidFrames),
|
||||
(devices::BLOCK_FRAMES + 1, 1, AudioFreshnessReason::InvalidFrames),
|
||||
(48, -1, AudioFreshnessReason::NegativeAge),
|
||||
(48, 200_000_001, AudioFreshnessReason::Expired),
|
||||
] {
|
||||
let (mut worker, handle, mut producer, origin) = render_drain_fixture(3);
|
||||
let now = origin + Duration::from_secs(1);
|
||||
let arrived = if age < 0 { now + Duration::from_nanos((-age) as u64) }
|
||||
else { now - Duration::from_nanos(age as u64) };
|
||||
let mut block = render_packet(arrived, 0);
|
||||
block.frames = frames;
|
||||
block.callback_at = now + Duration::from_millis(3);
|
||||
block.playback_at = now + Duration::from_millis(4);
|
||||
block.calibration_uncertainty = Duration::from_millis(2);
|
||||
producer.try_push(block).unwrap();
|
||||
producer.try_push(render_packet(now, 48)).unwrap();
|
||||
let error = worker.render_references_with_clock(|| now).unwrap_err();
|
||||
assert_eq!(error.code, "audio_reference_stale");
|
||||
let first = handle.first_fault().unwrap();
|
||||
let detail = first.freshness.unwrap();
|
||||
assert_eq!(detail.reason, expected);
|
||||
assert_eq!((detail.frames, detail.remaining_blocks, detail.queue_capacity), (frames, 1, 3));
|
||||
assert_eq!(detail.queue_age_ns, age);
|
||||
assert_eq!(detail.hardware_age_ns, -4_000_000);
|
||||
assert_eq!(detail.mapped_callback_age_ns, -3_000_000);
|
||||
assert_eq!(detail.calibration_uncertainty_ns, 2_000_000);
|
||||
assert!(first.outputs[0].is_some());
|
||||
worker.fail_devices("render_reference", error);
|
||||
assert!(worker.outputs.is_empty());
|
||||
assert_eq!(handle.first_fault().unwrap().freshness, Some(detail));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn production_capture_drain_preserves_frame_epoch_boundary_and_hardware_age_checks() {
|
||||
for (case, expected) in [
|
||||
(0, AudioFreshnessReason::InvalidFrames), (1, AudioFreshnessReason::InvalidFrames),
|
||||
(2, AudioFreshnessReason::Epoch), (3, AudioFreshnessReason::Boundary),
|
||||
(4, AudioFreshnessReason::NegativeAge), (5, AudioFreshnessReason::Expired),
|
||||
(6, AudioFreshnessReason::NegativeAge), (7, AudioFreshnessReason::Expired),
|
||||
] {
|
||||
let (mut worker, handle, mut producer, origin) = capture_drain_fixture(3);
|
||||
let now = origin + Duration::from_secs(1);
|
||||
let mut block = capture_packet(now, 0);
|
||||
match case {
|
||||
0 => block.frames = 0,
|
||||
1 => block.frames = devices::BLOCK_FRAMES + 1,
|
||||
2 => block.epoch = 6,
|
||||
3 => block.captured_at = origin - Duration::from_nanos(1),
|
||||
4 => block.captured_at = now + Duration::from_nanos(1),
|
||||
5 => block.captured_at = now - MAX_AGE - Duration::from_nanos(1),
|
||||
6 => block.arrived_at = now + Duration::from_nanos(1),
|
||||
7 => block.arrived_at = now - MAX_AGE - Duration::from_nanos(1),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
producer.try_push(block).unwrap();
|
||||
producer.try_push(capture_packet(now, 48)).unwrap();
|
||||
assert_eq!(worker.capture_blocks_with_clock(|| now).unwrap_err().code, "audio_capture_stale");
|
||||
let first = handle.first_fault().unwrap();
|
||||
let detail = first.freshness.unwrap();
|
||||
assert_eq!(detail.reason, expected, "case {case}");
|
||||
assert_eq!((detail.remaining_blocks, detail.queue_capacity), (1, 3));
|
||||
if case == 4 { assert_eq!(detail.hardware_age_ns, -1); }
|
||||
if case == 5 { assert_eq!(detail.hardware_age_ns, 200_000_001); }
|
||||
if case == 6 { assert_eq!(detail.queue_age_ns, -1); }
|
||||
if case == 7 { assert_eq!(detail.queue_age_ns, 200_000_001); }
|
||||
assert!(first.input.is_some());
|
||||
worker.stop_capture();
|
||||
assert_eq!(handle.first_fault().unwrap().freshness, Some(detail));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn production_drains_accept_the_inclusive_200ms_limit_and_render_skips_old_epochs() {
|
||||
let (mut capture, handle, mut producer, origin) = capture_drain_fixture(2);
|
||||
producer.try_push(capture_packet(origin, 0)).unwrap();
|
||||
capture.capture_blocks_with_clock(|| origin + MAX_AGE).unwrap();
|
||||
assert!(handle.first_fault().is_none());
|
||||
let (mut render, handle, mut producer, origin) = render_drain_fixture(2);
|
||||
let mut obsolete = render_packet(origin, 0);
|
||||
obsolete.epoch = 6;
|
||||
obsolete.frames = devices::BLOCK_FRAMES + 1;
|
||||
producer.try_push(obsolete).unwrap();
|
||||
producer.try_push(render_packet(origin, 0)).unwrap();
|
||||
render.render_references_with_clock(|| origin + MAX_AGE).unwrap();
|
||||
assert_eq!(render.outputs[0].reverse.next_position, Some(48));
|
||||
assert!(handle.first_fault().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn actual_mono_conversion_keeps_hardware_age_bounded_for_451_seconds_of_drift() {
|
||||
// Virtual hardware time, but every source frame traverses the real converter:
|
||||
// no source-position gaps, phase injection, sleeps, or shortened PCM history.
|
||||
// This exceeds the old 400 s / 500 ppm age crossover in both clock directions.
|
||||
for rate in [44_100_u32, 48_000] {
|
||||
for ppm in [-500.0_f64, 500.0] {
|
||||
let origin = Instant::now();
|
||||
let physical_rate = f64::from(rate) * (1.0 + ppm / 1_000_000.0);
|
||||
let first_position = u64::from(rate) * 37 + 123;
|
||||
let mut conversion = MonoConversion::new(rate).unwrap();
|
||||
let input_capacity = conversion.input.capacity();
|
||||
let output_capacity = conversion.output.capacity();
|
||||
let callbacks = (physical_rate * 451.0 / 1024.0).ceil() as u64;
|
||||
let mut emitted = 0_u64;
|
||||
for callback in 0..callbacks {
|
||||
let position = first_position + callback * 1024;
|
||||
let at = origin + Duration::from_secs_f64(position as f64 / physical_rate);
|
||||
let arrival = origin + Duration::from_secs_f64((position + 1024) as f64 / physical_rate);
|
||||
let observation = ClockObservation { at, position };
|
||||
for offset in (0..1024).step_by(256) {
|
||||
conversion.append(&[0.125; 256], position + offset, observation).unwrap();
|
||||
while let Some((pcm, timestamp)) = conversion.next().unwrap() {
|
||||
let age = arrival.checked_duration_since(timestamp)
|
||||
.expect("source timestamps must never move into future hardware capture");
|
||||
assert!(age < Duration::from_millis(40), "rate={rate} ppm={ppm} callback={callback} age={age:?}");
|
||||
assert!(pcm[0].is_finite());
|
||||
emitted += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(emitted > 44_000, "the complete virtual 451-second PCM history must be converted");
|
||||
assert_eq!(conversion.first_position, Some(first_position));
|
||||
assert_eq!(conversion.next_position, Some(first_position + callbacks * 1024));
|
||||
assert_eq!(conversion.input.capacity(), input_capacity);
|
||||
assert_eq!(conversion.output.capacity(), output_capacity);
|
||||
conversion.reset().unwrap();
|
||||
assert_eq!(conversion.first_position, None);
|
||||
assert_eq!(conversion.next_position, None);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,8 @@ pub const BLOCK_FRAMES: usize = 480;
|
||||
pub const MAX_DRIFT_PPM: f64 = 1_000.0;
|
||||
const CLOCK_WINDOW: Duration = Duration::from_secs(1);
|
||||
const MAX_CLOCK_DISCONTINUITY: f64 = 0.2;
|
||||
const CLOCK_SAMPLE_SPACING: Duration = Duration::from_millis(50);
|
||||
const CLOCK_SAMPLES: usize = 32;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Direction { Capture, Playback }
|
||||
@@ -26,6 +28,8 @@ pub struct AudioResampler {
|
||||
device_rate: u32,
|
||||
channels: usize,
|
||||
history_tail_output_frames: usize,
|
||||
source_position: f64,
|
||||
last_output_source_position: f64,
|
||||
}
|
||||
|
||||
impl AudioResampler {
|
||||
@@ -59,7 +63,8 @@ impl AudioResampler {
|
||||
let retained_input = 2 * parameters.sinc_len.next_multiple_of(8) + 4;
|
||||
let history_tail_output_frames = (retained_input as f64 * ratio * max_relative_ratio).ceil() as usize
|
||||
+ inner.output_frames_max();
|
||||
Ok(Self { inner, direction, device_rate, channels, history_tail_output_frames })
|
||||
Ok(Self { inner, direction, device_rate, channels, history_tail_output_frames,
|
||||
source_position: 0.0, last_output_source_position: 0.0 })
|
||||
}
|
||||
|
||||
pub fn channels(&self) -> usize { self.channels }
|
||||
@@ -85,6 +90,11 @@ impl AudioResampler {
|
||||
}
|
||||
pub fn ratio(&self) -> f64 { self.inner.resample_ratio() }
|
||||
|
||||
/// Source coordinate of the FIRST frame of the most recently produced block,
|
||||
/// relative to the first input frame, before subtracting sinc group delay.
|
||||
/// This follows rubato's actual ramp, not nominal output-frame wall time.
|
||||
pub fn last_output_source_position(&self) -> f64 { self.last_output_source_position }
|
||||
|
||||
/// Buffers are interleaved (a mono slice is also interleaved). Allocate their maximum
|
||||
/// sizes once on the worker. Only the returned frame counts were consumed/produced.
|
||||
pub fn process_interleaved(&mut self, input: &[f32], output: &mut [f32]) -> Result<ProcessedFrames> {
|
||||
@@ -97,8 +107,14 @@ impl AudioResampler {
|
||||
.map_err(|error| ServiceError::new("audio_buffer", error.to_string()))?;
|
||||
let mut destination = InterleavedSlice::new_mut(&mut output[..output_frames * self.channels], self.channels, output_frames)
|
||||
.map_err(|error| ServiceError::new("audio_buffer", error.to_string()))?;
|
||||
let before = self.inner.resample_ratio().recip();
|
||||
let (consumed, produced) = self.inner.process_into_buffer(&source, &mut destination, None)
|
||||
.map_err(|error| ServiceError::new("audio_resampler", error.to_string()))?;
|
||||
let after = self.inner.resample_ratio().recip();
|
||||
self.last_output_source_position = self.source_position;
|
||||
// rubato 5.0.1 advances its input index BEFORE each output frame, with
|
||||
// a linear reciprocal-ratio ramp; sum exactly that arithmetic series.
|
||||
self.source_position += produced as f64 * 0.5 * (before + after) + 0.5 * (after - before);
|
||||
Ok(ProcessedFrames { consumed, produced })
|
||||
}
|
||||
|
||||
@@ -118,6 +134,8 @@ impl AudioResampler {
|
||||
/// Call only as part of a route/epoch boundary, after dropping queued old PCM.
|
||||
pub fn reset(&mut self) -> Result<()> {
|
||||
self.inner.reset();
|
||||
self.source_position = 0.0;
|
||||
self.last_output_source_position = 0.0;
|
||||
self.inner.set_resample_ratio_relative(1.0, false)
|
||||
.map_err(|error| ServiceError::new("audio_resampler", error.to_string()))
|
||||
}
|
||||
@@ -136,17 +154,20 @@ pub enum ClockDiscontinuity {
|
||||
DriftOutOfRange,
|
||||
}
|
||||
|
||||
/// Tracks raw callback-start observations separately from subdivided PCM positions.
|
||||
/// CPAL supplies estimates without a precision flag (including AAudio's startup
|
||||
/// `now()` fallback). Their existing 200 ms discontinuity budget is therefore an
|
||||
/// uncertainty interval, not a precise one-second drift measurement. Nominal SRC
|
||||
/// starts immediately; a correction requires an interval wholly within ±1000 ppm
|
||||
/// and excluding zero. On error the caller must reset the stream epoch and DSP.
|
||||
/// Tracks raw callback observations independently of PCM subdivisions. The
|
||||
/// discontinuity budget is NOT timestamp precision: drift acquisition instead
|
||||
/// uses a short rolling fit and its explicitly measured residual interval.
|
||||
/// Timestamps project source coordinates from the latest raw callback, so even
|
||||
/// an unresolved rate estimate cannot accumulate unbounded wall-clock phase.
|
||||
pub struct ClockTracker {
|
||||
sample_rate: u32,
|
||||
anchor: Option<(Instant, u64)>,
|
||||
previous: Option<(Instant, u64)>,
|
||||
anchor: Option<ClockObservation>,
|
||||
previous: Option<ClockObservation>,
|
||||
samples: [Option<ClockObservation>; CLOCK_SAMPLES],
|
||||
sample_count: usize,
|
||||
sample_next: usize,
|
||||
smoothed_ppm: f64,
|
||||
measured_jitter: Duration,
|
||||
}
|
||||
|
||||
impl ClockTracker {
|
||||
@@ -154,16 +175,35 @@ impl ClockTracker {
|
||||
if !(8_000..=384_000).contains(&sample_rate) {
|
||||
return Err(ServiceError::new("audio_format", "Audio clock sample rate is outside 8–384 kHz"));
|
||||
}
|
||||
Ok(Self { sample_rate, anchor: None, previous: None, smoothed_ppm: 0.0 })
|
||||
Ok(Self { sample_rate, anchor: None, previous: None, samples: [None; CLOCK_SAMPLES],
|
||||
sample_count: 0, sample_next: 0, smoothed_ppm: 0.0, measured_jitter: Duration::ZERO })
|
||||
}
|
||||
|
||||
pub fn reset(&mut self) {
|
||||
self.anchor = None;
|
||||
self.previous = None;
|
||||
self.samples.fill(None);
|
||||
self.sample_count = 0;
|
||||
self.sample_next = 0;
|
||||
self.smoothed_ppm = 0.0;
|
||||
self.measured_jitter = Duration::ZERO;
|
||||
}
|
||||
|
||||
pub fn drift_ppm(&self) -> f64 { self.smoothed_ppm }
|
||||
pub fn measured_jitter(&self) -> Duration { self.measured_jitter }
|
||||
|
||||
/// Hardware-domain projection, never a worker wake-time replacement. The
|
||||
/// caller supplies actual SRC source phase and separately subtracts delay.
|
||||
/// Its error depends on distance from this callback, not stream duration.
|
||||
pub fn timestamp(&self, frame_position: f64) -> Option<Instant> {
|
||||
if !frame_position.is_finite() { return None; }
|
||||
let observation = self.previous?;
|
||||
let seconds = (frame_position - observation.position as f64)
|
||||
/ (f64::from(self.sample_rate) * (1.0 + self.smoothed_ppm / 1_000_000.0));
|
||||
let duration = Duration::try_from_secs_f64(seconds.abs()).ok()?;
|
||||
if seconds < 0.0 { observation.at.checked_sub(duration) }
|
||||
else { observation.at.checked_add(duration) }
|
||||
}
|
||||
|
||||
pub fn observe(&mut self, hardware_at: Instant, frame_position: u64)
|
||||
-> std::result::Result<Option<f64>, ClockDiscontinuity>
|
||||
@@ -176,45 +216,78 @@ impl ClockTracker {
|
||||
fn observe_inner(&mut self, hardware_at: Instant, frame_position: u64)
|
||||
-> std::result::Result<Option<f64>, ClockDiscontinuity>
|
||||
{
|
||||
if let Some((previous_at, previous_position)) = self.previous {
|
||||
let elapsed = hardware_at.checked_duration_since(previous_at)
|
||||
if let Some(previous) = self.previous {
|
||||
let elapsed = hardware_at.checked_duration_since(previous.at)
|
||||
.ok_or(ClockDiscontinuity::TimestampReversed)?;
|
||||
let frames = frame_position.checked_sub(previous_position)
|
||||
let frames = frame_position.checked_sub(previous.position)
|
||||
.ok_or(ClockDiscontinuity::FramePositionReversed)?;
|
||||
if elapsed.is_zero() && frames == 0 { return Ok(None); }
|
||||
if (elapsed.as_secs_f64() - frames as f64 / f64::from(self.sample_rate)).abs() > MAX_CLOCK_DISCONTINUITY {
|
||||
return Err(ClockDiscontinuity::TimestampJump);
|
||||
}
|
||||
}
|
||||
self.previous = Some((hardware_at, frame_position));
|
||||
let Some((anchor_at, anchor_position)) = self.anchor else {
|
||||
self.anchor = self.previous;
|
||||
return Ok(None);
|
||||
};
|
||||
let elapsed = hardware_at.duration_since(anchor_at);
|
||||
let frames = frame_position - anchor_position;
|
||||
let nominal_seconds = frames as f64 / f64::from(self.sample_rate);
|
||||
if elapsed < CLOCK_WINDOW {
|
||||
if (elapsed.as_secs_f64() - nominal_seconds).abs() > MAX_CLOCK_DISCONTINUITY {
|
||||
return Err(ClockDiscontinuity::TimestampJump);
|
||||
}
|
||||
let observation = ClockObservation { at: hardware_at, position: frame_position };
|
||||
self.previous = Some(observation);
|
||||
let anchor = *self.anchor.get_or_insert(observation);
|
||||
let seconds = hardware_at.duration_since(anchor.at).as_secs_f64();
|
||||
let nominal = (frame_position - anchor.position) as f64 / f64::from(self.sample_rate);
|
||||
// Keep an epoch-wide bound: a rolling fit must not hide a frozen clock
|
||||
// or a succession of individually small jumps. Legitimate drift gets
|
||||
// its own rate allowance, not another 200 ms per observation/window.
|
||||
if (seconds - nominal).abs() > MAX_CLOCK_DISCONTINUITY + nominal * MAX_DRIFT_PPM / 1_000_000.0 {
|
||||
return Err(if seconds < CLOCK_WINDOW.as_secs_f64() { ClockDiscontinuity::TimestampJump }
|
||||
else { ClockDiscontinuity::DriftOutOfRange });
|
||||
}
|
||||
if self.sample_count > 0 {
|
||||
let last = self.samples[(self.sample_next + CLOCK_SAMPLES - 1) % CLOCK_SAMPLES].unwrap();
|
||||
if hardware_at.duration_since(last.at) < CLOCK_SAMPLE_SPACING { return Ok(None); }
|
||||
}
|
||||
self.samples[self.sample_next] = Some(observation);
|
||||
self.sample_next = (self.sample_next + 1) % CLOCK_SAMPLES;
|
||||
self.sample_count = (self.sample_count + 1).min(CLOCK_SAMPLES);
|
||||
let oldest = self.samples[if self.sample_count == CLOCK_SAMPLES { self.sample_next } else { 0 }].unwrap();
|
||||
if hardware_at.duration_since(oldest.at) < CLOCK_WINDOW { return Ok(None); }
|
||||
// Least-squares elapsed time against nominal source time. Residual
|
||||
// peak-to-peak is an observed jitter interval, NOT a precision promise.
|
||||
let mut sum_x = 0.0;
|
||||
let mut sum_y = 0.0;
|
||||
for sample in self.samples.iter().flatten() {
|
||||
sum_x += (sample.position - oldest.position) as f64 / f64::from(self.sample_rate);
|
||||
sum_y += sample.at.duration_since(oldest.at).as_secs_f64();
|
||||
}
|
||||
let mean_x = sum_x / self.sample_count as f64;
|
||||
let mean_y = sum_y / self.sample_count as f64;
|
||||
let mut covariance = 0.0;
|
||||
let mut variance = 0.0;
|
||||
for sample in self.samples.iter().flatten() {
|
||||
let x = (sample.position - oldest.position) as f64 / f64::from(self.sample_rate) - mean_x;
|
||||
let y = sample.at.duration_since(oldest.at).as_secs_f64() - mean_y;
|
||||
covariance += x * y;
|
||||
variance += x * x;
|
||||
}
|
||||
if variance == 0.0 { return Ok(None); }
|
||||
let slope = covariance / variance;
|
||||
let mut low = f64::INFINITY;
|
||||
let mut high = f64::NEG_INFINITY;
|
||||
for sample in self.samples.iter().flatten() {
|
||||
let x = (sample.position - oldest.position) as f64 / f64::from(self.sample_rate) - mean_x;
|
||||
let y = sample.at.duration_since(oldest.at).as_secs_f64() - mean_y;
|
||||
let residual = y - slope * x;
|
||||
low = low.min(residual);
|
||||
high = high.max(residual);
|
||||
}
|
||||
let jitter = (high - low).max(0.000_000_002);
|
||||
self.measured_jitter = Duration::from_secs_f64(jitter);
|
||||
let span = (frame_position - oldest.position) as f64 / f64::from(self.sample_rate);
|
||||
if slope <= 0.0 || span <= 0.0 { return Ok(None); }
|
||||
let uncertainty = 2.0 * jitter / span;
|
||||
if slope <= uncertainty { return Ok(None); }
|
||||
let lower_ppm = ((slope + uncertainty).recip() - 1.0) * 1_000_000.0;
|
||||
let upper_ppm = ((slope - uncertainty).recip() - 1.0) * 1_000_000.0;
|
||||
if lower_ppm < -MAX_DRIFT_PPM || upper_ppm > MAX_DRIFT_PPM || lower_ppm <= 0.0 && upper_ppm >= 0.0 {
|
||||
return Ok(None);
|
||||
}
|
||||
// The uncertainty applies to the span, not to every callback separately:
|
||||
// repeated/clamped timestamps cannot accumulate an unlimited sample lead.
|
||||
let seconds = elapsed.as_secs_f64();
|
||||
let lower_ppm = (nominal_seconds / (seconds + MAX_CLOCK_DISCONTINUITY) - 1.0) * 1_000_000.0;
|
||||
let upper_ppm = (nominal_seconds / (seconds - MAX_CLOCK_DISCONTINUITY) - 1.0) * 1_000_000.0;
|
||||
if lower_ppm > MAX_DRIFT_PPM || upper_ppm < -MAX_DRIFT_PPM {
|
||||
return Err(ClockDiscontinuity::DriftOutOfRange);
|
||||
}
|
||||
if lower_ppm <= 0.0 && upper_ppm >= 0.0 || lower_ppm < -MAX_DRIFT_PPM || upper_ppm > MAX_DRIFT_PPM {
|
||||
return Ok(None);
|
||||
}
|
||||
let ppm = (nominal_seconds / seconds - 1.0) * 1_000_000.0;
|
||||
let weight = 1.0 - (-elapsed.as_secs_f64()).exp();
|
||||
self.smoothed_ppm += weight * (ppm - self.smoothed_ppm);
|
||||
self.anchor = self.previous;
|
||||
self.smoothed_ppm = (slope.recip() - 1.0) * 1_000_000.0;
|
||||
Ok(Some(self.smoothed_ppm))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,23 +82,25 @@ fn drift_correction_is_reciprocal_for_capture_and_direct_for_output() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clock_withholds_drift_until_timestamp_uncertainty_is_resolved() {
|
||||
let start = Instant::now();
|
||||
let mut clock = ClockTracker::new(48_000).unwrap();
|
||||
assert_eq!(clock.observe(start, 0), Ok(None));
|
||||
for seconds in 1..=400 {
|
||||
assert_eq!(clock.observe(start + Duration::from_secs(seconds), seconds * 48_024), Ok(None));
|
||||
}
|
||||
assert_eq!(clock.drift_ppm(), 0.0);
|
||||
let mut acquired = false;
|
||||
for seconds in 401..=1_000 {
|
||||
if let Some(ppm) = clock.observe(start + Duration::from_secs(seconds), seconds * 48_024).unwrap() {
|
||||
assert!((ppm - 500.0).abs() < 0.000_001);
|
||||
acquired = true;
|
||||
fn stable_callback_clock_acquires_drift_without_spending_the_age_budget() {
|
||||
for rate in [44_100, 48_000] {
|
||||
for ppm in [-500.0, 500.0] {
|
||||
let start = Instant::now();
|
||||
let mut clock = ClockTracker::new(rate).unwrap();
|
||||
let physical_rate = f64::from(rate) * (1.0 + ppm / 1_000_000.0);
|
||||
let mut acquired = false;
|
||||
for callback in 0..=300_u64 {
|
||||
let position = callback * u64::from(rate) / 100;
|
||||
let at = start + Duration::from_secs_f64(position as f64 / physical_rate);
|
||||
if let Some(estimate) = clock.observe(at, position).unwrap() {
|
||||
assert!((estimate - ppm).abs() < 0.01);
|
||||
acquired = true;
|
||||
}
|
||||
}
|
||||
assert!(acquired, "rate={rate}, ppm={ppm}");
|
||||
assert!(clock.measured_jitter() <= Duration::from_nanos(3));
|
||||
}
|
||||
}
|
||||
assert!(acquired);
|
||||
assert!((clock.drift_ppm() - 500.0).abs() < 0.000_001);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -156,6 +158,95 @@ fn burst_offset_is_not_misreported_as_hardware_drift_after_one_second() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn callback_projection_bounds_two_hour_phase_even_when_jitter_prevents_drift_acquisition() {
|
||||
for rate in [44_100, 48_000] {
|
||||
for ppm in [-500.0, 500.0] {
|
||||
let start = Instant::now();
|
||||
let mut clock = ClockTracker::new(rate).unwrap();
|
||||
let physical_rate = f64::from(rate) * (1.0 + ppm / 1_000_000.0);
|
||||
// Deterministic callback timestamp jitter exceeds the 500 ppm signal
|
||||
// inside the short fit. Projection must still stay bounded in phase.
|
||||
for callback in 0..=720_000_u64 {
|
||||
let position = callback * u64::from(rate) / 100;
|
||||
let jitter = if (callback / 20) % 2 == 0 { 0.000_6 } else { 0.0 };
|
||||
let at = start + Duration::from_secs_f64(position as f64 / physical_rate + jitter);
|
||||
clock.observe(at, position).unwrap();
|
||||
if callback == 0 { continue; }
|
||||
let source = position as f64 - f64::from(rate) * 0.02 + 0.25;
|
||||
let projected = clock.timestamp(source).unwrap();
|
||||
let truth = start + Duration::from_secs_f64(source.max(0.0) / physical_rate);
|
||||
let now = at + Duration::from_millis(10);
|
||||
assert!(projected <= now);
|
||||
assert!(now.duration_since(projected) < Duration::from_millis(32));
|
||||
if source >= 0.0 {
|
||||
let error = projected.max(truth).duration_since(projected.min(truth));
|
||||
assert!(error < Duration::from_micros(650), "rate={rate}, ppm={ppm}, callback={callback}, error={error:?}");
|
||||
}
|
||||
}
|
||||
assert!(clock.measured_jitter() >= Duration::from_micros(500));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn emitted_src_timestamps_follow_actual_ramped_source_phase() {
|
||||
for rate in [44_100, 48_000] {
|
||||
for ppm in [-500.0, 500.0] {
|
||||
let start = Instant::now();
|
||||
let mut clock = ClockTracker::new(rate).unwrap();
|
||||
let mut converter = AudioResampler::new_capture(rate, 1).unwrap();
|
||||
let input = vec![0.25; converter.input_frames_max()];
|
||||
let mut output = vec![0.0; converter.output_frames_max()];
|
||||
let physical_rate = f64::from(rate) * (1.0 + ppm / 1_000_000.0);
|
||||
let mut consumed = 0_u64;
|
||||
let mut phase = 0.0;
|
||||
for block in 0..400 {
|
||||
let at = start + Duration::from_secs_f64(consumed as f64 / physical_rate);
|
||||
if let Some(estimate) = clock.observe(at, consumed).unwrap() {
|
||||
converter.set_device_drift_ppm(estimate).unwrap();
|
||||
}
|
||||
let before = converter.ratio().recip();
|
||||
let counts = converter.process_interleaved(&input, &mut output).unwrap();
|
||||
let after = converter.ratio().recip();
|
||||
assert!((converter.last_output_source_position() - phase).abs() < 1e-7);
|
||||
let projected = clock.timestamp(converter.last_output_source_position()).unwrap();
|
||||
let emitted = projected.checked_sub(converter.output_delay()).unwrap();
|
||||
let now = start + Duration::from_secs_f64((consumed + counts.consumed as u64) as f64 / physical_rate);
|
||||
assert!(emitted <= now, "rate={rate}, ppm={ppm}, block={block}");
|
||||
assert!(now.duration_since(emitted) < Duration::from_millis(40));
|
||||
phase += counts.produced as f64 * (before + after) * 0.5 + (after - before) * 0.5;
|
||||
consumed += counts.consumed as u64;
|
||||
}
|
||||
assert!((clock.drift_ppm() - ppm).abs() < 0.01);
|
||||
// Buffer consumption includes bounded sinc lookahead; the sample
|
||||
// phase must not accidentally use that lookahead as source time.
|
||||
assert!(consumed as f64 - phase > 1.0);
|
||||
assert!(consumed as f64 - phase < f64::from(rate) * 0.02);
|
||||
converter.reset().unwrap();
|
||||
converter.process_interleaved(&input, &mut output).unwrap();
|
||||
assert_eq!(converter.last_output_source_position(), 0.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rolling_clock_fit_does_not_erase_cumulative_small_discontinuities() {
|
||||
let start = Instant::now();
|
||||
let mut clock = ClockTracker::new(48_000).unwrap();
|
||||
let mut fault = None;
|
||||
for callback in 0..=250_u64 {
|
||||
let at = start + Duration::from_millis(callback * 11);
|
||||
if let Err(error) = clock.observe(at, callback * 480) {
|
||||
fault = Some(error);
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert_eq!(fault, Some(ClockDiscontinuity::DriftOutOfRange));
|
||||
assert!(clock.timestamp(0.0).is_none());
|
||||
assert_eq!(clock.drift_ppm(), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_format_is_explicit() {
|
||||
assert!(AudioResampler::new_capture(0, 1).is_err());
|
||||
|
||||
Reference in new issue
Block a user