Fix burst callback clock observations with reproducing audio regressions
android-ci / android-arm64 (push) Successful in 14m15s
android-ci / android-arm64 (push) Successful in 14m15s
This commit is contained in:
1 parent
b4c363b99b
commit
b58483ed62
9 files changed
+230
-32
No files matched your search
@@ -16,7 +16,8 @@ cargo run --locked -p xtask -- build --target "$TARGET" --llvm-dir "$LLVM_HOME"
|
||||
# Explicit online dependency resolution supports a fresh Gradle cache.
|
||||
# Bootstrap still requires the local checksum-pinned zip; SDK downloads stay disabled.
|
||||
cargo run --locked -p xtask -- package --target "$TARGET" --out "$out" --test-harness "$harness" --gradle-online true
|
||||
cargo run --locked -p xtask -- verify-package --target "$TARGET" --out "$out" --test-harness "$harness"
|
||||
# xtask package already verifies the completed APK/AAB before returning success.
|
||||
# The receipt and artifact hashes below bind that verification to the uploaded bytes.
|
||||
cp "$CARGO_TARGET_DIR/$TARGET/release/native-build.json" "$out/$TARGET/native-build.json"
|
||||
cp native/native-deps.lock.json "$out/$TARGET/native-deps.lock.json"
|
||||
cp "target/native-deps/$TARGET/provenance.json" "$out/$TARGET/dependency-provenance.json"
|
||||
|
||||
@@ -2,6 +2,10 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
- Fix callback clock observations being confused with their internal PCM subdivisions, which caused
|
||||
false TimestampReversed shutdown on bursty Android playback. Preserve hardware-derived PCM timestamps,
|
||||
expiry/privacy checks and reject genuine clock/sample-position discontinuities.
|
||||
- Avoid running APK verification twice in Android CI; packaging already verifies final archive bytes.
|
||||
- Retain sanitized first audio fault/callback counters across teardown; preserve operation-stage errors.
|
||||
Keep connection playback epochs coherent across output replacement and distinguish first-device startup
|
||||
time from live stream stalls. Voice-follow recovery retains logical route ownership without stale sink traps.
|
||||
|
||||
@@ -305,6 +305,21 @@ Updated **2026-11-11**. Windows baseline remains `05e8d34bcf0e24a44f76e65220293c
|
||||
- Manager now emits exact-key Closed before losing its worker, so close/restart releases playback scopes.
|
||||
Agent verified production scheduling helper5 tests and std-only first-fault retention/sanitization1 test;
|
||||
full integration and device tests pending. Xrun behavior remains unchanged until first-fault evidence.
|
||||
- Run4899 SUCCESS, APK SHA256 `27d839a0271cb2ad5943a6fca6ad7e88db0557b399f26603b6a7997dd7f28a14`
|
||||
installed. First-fault evidence finally identifies `audio_clock_discontinuity`/render_reference,
|
||||
UI TimestampReversed: output5 callbacks/4100frames, fault=None, xruns0, drops0; no input. This excludes
|
||||
Xrun/overflow as the first failure in this observed run; callbacks were subdivided before clock analysis.
|
||||
- Exact old ClockTracker snapshot regression FAILED as expected:1024-frame callback subdivisions then
|
||||
next callback estimate+5ms triggers false TimestampReversed. New production callbacks retain original
|
||||
callback observation separately from block timestamps; sample-position and raw-clock reversal gates remain.
|
||||
Cached-dependency harness compiled actual devices/resample/ring modules: **45 tests passed**, including
|
||||
exact failure reproduction,4100-frame burst,44.1/48k, stale PCM/privacy, expiry and overflow boundaries.
|
||||
Drift starts nominal and is acquired conservatively only outside200ms span uncertainty; no relaxed
|
||||
PCM age cap. Full Android integration/device proof still pending.
|
||||
- CI4899 measured13m21s total, actual Rust compilation2m11s; tools/application caches hit with832
|
||||
unchanged build-start stamps. WebRTC restore1m27s, deps3m23s; package redundantly ran verify twice.
|
||||
Removed external duplicate verify-package call: xtask package already runs full mandatory verifier,
|
||||
and bundle code still checks passed receipt + hashes. Dependency provenance checks remain unchanged.
|
||||
|
||||
|
||||
## First Android APK build
|
||||
|
||||
@@ -17,7 +17,7 @@ use cpal::{
|
||||
StreamInstant, SupportedBufferSize, SupportedStreamConfigRange,
|
||||
};
|
||||
use crate::services::{Result, ServiceError};
|
||||
use super::ring::{self, Consumer, Producer};
|
||||
use super::{resample::ClockObservation, ring::{self, Consumer, Producer}};
|
||||
|
||||
pub const BLOCK_FRAMES: usize = 256;
|
||||
pub const MAX_AUDIO_AGE: Duration = Duration::from_millis(200);
|
||||
@@ -276,6 +276,8 @@ pub struct CaptureBlock {
|
||||
pub captured_at: Instant,
|
||||
pub callback_at: Instant,
|
||||
pub frame_position: u64,
|
||||
/// Unsubdivided callback clock observation; shared by all blocks from that callback.
|
||||
pub clock: ClockObservation,
|
||||
}
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct PlaybackBlock {
|
||||
@@ -305,6 +307,7 @@ pub struct RenderBlock {
|
||||
pub playback_at: Instant,
|
||||
pub callback_at: Instant,
|
||||
pub frame_position: u64,
|
||||
pub clock: ClockObservation,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
@@ -496,7 +499,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 };
|
||||
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 } };
|
||||
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)); }
|
||||
@@ -575,7 +578,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 };
|
||||
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 } };
|
||||
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])],
|
||||
|
||||
@@ -176,6 +176,71 @@ fn device_clock_discontinuity_disables_capture() {
|
||||
assert!(samples.try_pop().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_bursty_playback_estimates_keep_raw_callback_observations() {
|
||||
for rate in [44_100, 48_000] {
|
||||
let (mut callback, _samples, mut rendered, origin) = playback_fixture(rate, 1, 32);
|
||||
let mut tracker = super::super::resample::ClockTracker::new(rate).unwrap();
|
||||
let mut previous_block_at = None;
|
||||
let mut saw_chunk_overlap = false;
|
||||
// The observed Android failure had five callbacks / 4100 frames, no
|
||||
// dropped PCM and no CPAL xrun. Callback estimates may repeat or arrive
|
||||
// in a burst, even though every callback contains multiple 256 blocks.
|
||||
for (index, millis) in [0, 0, 1, 2, 3].into_iter().enumerate() {
|
||||
callback.process(&mut [0.0_f32; 820], output_time(millis, millis + 10), origin + Duration::from_millis(millis));
|
||||
for offset in (0..820).step_by(BLOCK_FRAMES) {
|
||||
let block = rendered.try_pop().unwrap();
|
||||
assert_eq!(block.clock, ClockObservation { at: origin + Duration::from_millis(millis + 10), position: index as u64 * 820 });
|
||||
assert_eq!(block.playback_at, block.clock.at + frames_duration(offset as u64, rate));
|
||||
assert_eq!(block.frame_position, block.clock.position + offset as u64);
|
||||
if previous_block_at.is_some_and(|previous| block.playback_at < previous) { saw_chunk_overlap = true; }
|
||||
previous_block_at = Some(block.playback_at);
|
||||
assert_eq!(tracker.observe(block.clock.at, block.clock.position), Ok(None));
|
||||
}
|
||||
}
|
||||
assert!(saw_chunk_overlap, "regression must exercise the actual split-block reversal");
|
||||
let stats = callback.state.stats();
|
||||
assert_eq!(stats.callbacks, 5);
|
||||
assert_eq!(stats.frames, 4100);
|
||||
assert_eq!(stats.xruns, 0);
|
||||
assert_eq!(stats.dropped_blocks, 0);
|
||||
assert_eq!(stats.fault, StreamFault::None);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exact_1024_frame_callback_split_with_five_ms_next_estimate_does_not_fault() {
|
||||
for rate in [44_100, 48_000] {
|
||||
let (mut callback, _samples, mut rendered, origin) = playback_fixture(rate, 1, 8);
|
||||
let mut tracker = super::super::resample::ClockTracker::new(rate).unwrap();
|
||||
for millis in [0, 5] {
|
||||
callback.process(&mut [0.0_f32; 1024], output_time(millis, millis), origin + Duration::from_millis(millis));
|
||||
for _ in 0..4 {
|
||||
let block = rendered.try_pop().unwrap();
|
||||
assert_eq!(tracker.observe(block.clock.at, block.clock.position), Ok(None));
|
||||
}
|
||||
}
|
||||
assert_eq!(callback.state.fault(), StreamFault::None);
|
||||
assert_eq!(callback.state.stats().xruns, 0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_playback_estimates_do_not_refresh_source_expiry() {
|
||||
let (mut callback, mut samples, mut rendered, origin) = playback_fixture(48_000, 1, 8);
|
||||
callback.process(&mut [0.0_f32; 1024], output_time(0, 0), origin);
|
||||
rendered.discard_pending();
|
||||
let mut expiring = block(origin, 256, [0.75; 2]);
|
||||
expiring.expires_at = origin + Duration::from_millis(9);
|
||||
samples.try_push(expiring).unwrap();
|
||||
let mut output = [1.0_f32; 256];
|
||||
// The next callback's raw estimate overlaps the previous callback's last
|
||||
// subblock. Its proposed last frame is still after the source deadline.
|
||||
callback.process(&mut output, output_time(5, 5), origin + Duration::from_millis(5));
|
||||
assert_eq!(output, [0.0; 256]);
|
||||
assert_eq!(callback.state.fault(), StreamFault::None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn playback_preserves_stereo_and_reports_submitted_quantized_reference() {
|
||||
let (mut callback, mut samples, mut rendered, origin) = playback_fixture(48_000, 2, 4);
|
||||
|
||||
@@ -12,7 +12,7 @@ use crate::{app::connections::{CapturePermit, ConnectionManager, SessionKey},
|
||||
use super::{capture::CapturePipeline, devices::{self, CapturePort, DeviceCatalog, DeviceHost,
|
||||
DeviceSelection, Direction, PlaybackBlock, PlaybackPort, StartPermission, StreamOwner, StreamState, StreamStats},
|
||||
mixer::{PlaybackDsp, PlaybackMixer, StereoBlock, StreamRegistry}, notification::{NotificationOutput, clip_mix},
|
||||
resample::{AudioResampler, ClockTracker}};
|
||||
resample::{AudioResampler, ClockObservation, ClockTracker}};
|
||||
|
||||
const COMMAND_CAPACITY: usize = 64;
|
||||
const PCM_CAPACITY: usize = 32;
|
||||
@@ -358,23 +358,28 @@ struct MonoConversion {
|
||||
first: Option<Instant>,
|
||||
produced: u64,
|
||||
clock: ClockTracker,
|
||||
next_position: Option<u64>,
|
||||
}
|
||||
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)? })
|
||||
produced: 0, 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.used = 0; self.first = None; self.produced = 0; self.next_position = None;
|
||||
Ok(())
|
||||
}
|
||||
fn append(&mut self, samples: &[f32], at: Instant, position: u64) -> Result<()> {
|
||||
if let Some(ppm) = self.clock.observe(at, position).map_err(|error| ServiceError::new("audio_clock_discontinuity", format!("{error:?}")))? {
|
||||
fn append(&mut self, samples: &[f32], at: Instant, position: u64, observation: ClockObservation) -> Result<()> {
|
||||
if self.next_position.is_some_and(|next| position < next) {
|
||||
return Err(ServiceError::new("audio_clock_discontinuity", "FramePositionReversed"));
|
||||
}
|
||||
if let Some(ppm) = self.clock.observe(observation.at, observation.position).map_err(|error| ServiceError::new("audio_clock_discontinuity", format!("{error:?}")))? {
|
||||
self.converter.set_device_drift_ppm(ppm)?;
|
||||
}
|
||||
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.input[self.used..self.used + samples.len()].copy_from_slice(samples);
|
||||
@@ -1033,7 +1038,7 @@ impl Worker {
|
||||
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"));
|
||||
}
|
||||
output.reverse.append(&block.samples[..block.frames], block.playback_at, block.frame_position)?;
|
||||
output.reverse.append(&block.samples[..block.frames], block.playback_at, 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); }
|
||||
}
|
||||
@@ -1054,7 +1059,7 @@ impl Worker {
|
||||
return Err(ServiceError::new("audio_capture_stale", "Microphone PCM crossed a capture boundary or exceeded 200 ms"));
|
||||
}
|
||||
input.last = now;
|
||||
input.conversion.append(&block.samples[..block.frames], block.captured_at, block.frame_position)?;
|
||||
input.conversion.append(&block.samples[..block.frames], block.captured_at, 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; }
|
||||
|
||||
@@ -40,7 +40,8 @@ fn callback_chunks_are_converted_to_fixed_capture_blocks_without_retiming() {
|
||||
// clock-estimation noise or any endpoint activation.
|
||||
for packet in 0..160_u64 {
|
||||
let position = packet * 256;
|
||||
conversion.append(&[0.25; 256], origin + sample_duration(position, rate), position).unwrap();
|
||||
let at = origin + sample_duration(position, rate);
|
||||
conversion.append(&[0.25; 256], at, 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);
|
||||
@@ -58,8 +59,46 @@ 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).unwrap();
|
||||
let error = conversion.append(&[0.2; 256], origin, 512).unwrap_err();
|
||||
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();
|
||||
assert_eq!(error.code, "audio_clock_discontinuity");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_callback_estimates_do_not_reverse_the_sample_clock() {
|
||||
for rate in [44_100, 48_000] {
|
||||
let origin = Instant::now();
|
||||
let mut conversion = MonoConversion::new(rate).unwrap();
|
||||
let mut produced = 0;
|
||||
// AAudio startup fallback/burst: each 1024-frame callback is split into
|
||||
// four blocks, but the second estimate is only 1 ms after the first.
|
||||
for callback in 0..160_u64 {
|
||||
let position = callback * 1024;
|
||||
let at = if callback < 2 { origin + Duration::from_millis(callback) }
|
||||
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();
|
||||
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);
|
||||
produced += 480;
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(produced > 150_000);
|
||||
assert_eq!(conversion.clock.drift_ppm(), 0.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
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();
|
||||
assert_eq!(error.code, "audio_clock_discontinuity");
|
||||
}
|
||||
|
||||
|
||||
@@ -123,6 +123,11 @@ impl AudioResampler {
|
||||
}
|
||||
}
|
||||
|
||||
/// A backend estimate of the first frame in an entire hardware callback. Splitting
|
||||
/// PCM into worker blocks does not create additional hardware clock observations.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct ClockObservation { pub at: Instant, pub position: u64 }
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ClockDiscontinuity {
|
||||
TimestampReversed,
|
||||
@@ -131,10 +136,12 @@ pub enum ClockDiscontinuity {
|
||||
DriftOutOfRange,
|
||||
}
|
||||
|
||||
/// Estimates hardware drift from hardware first-frame timestamps, not worker wake times.
|
||||
/// The device adapter maps each device clock to `Instant` before calling this. A complete
|
||||
/// one-second window feeds a one-second exponential smoothing filter. On any error the
|
||||
/// caller must invalidate capture/output epochs, flush PCM, reset DSP and rebuffer.
|
||||
/// 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.
|
||||
pub struct ClockTracker {
|
||||
sample_rate: u32,
|
||||
anchor: Option<(Instant, u64)>,
|
||||
@@ -174,10 +181,10 @@ impl ClockTracker {
|
||||
.ok_or(ClockDiscontinuity::TimestampReversed)?;
|
||||
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);
|
||||
}
|
||||
if elapsed.is_zero() && frames > 0 { return Err(ClockDiscontinuity::TimestampJump); }
|
||||
}
|
||||
self.previous = Some((hardware_at, frame_position));
|
||||
let Some((anchor_at, anchor_position)) = self.anchor else {
|
||||
@@ -185,12 +192,26 @@ impl ClockTracker {
|
||||
return Ok(None);
|
||||
};
|
||||
let elapsed = hardware_at.duration_since(anchor_at);
|
||||
if elapsed < CLOCK_WINDOW { return Ok(None); }
|
||||
let frames = frame_position - anchor_position;
|
||||
let ppm = (frames as f64 / (f64::from(self.sample_rate) * elapsed.as_secs_f64()) - 1.0) * 1_000_000.0;
|
||||
if !ppm.is_finite() || ppm.abs() > MAX_DRIFT_PPM {
|
||||
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);
|
||||
}
|
||||
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;
|
||||
|
||||
@@ -82,26 +82,38 @@ fn drift_correction_is_reciprocal_for_capture_and_direct_for_output() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clock_uses_hardware_time_and_one_second_smoothing() {
|
||||
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));
|
||||
assert_eq!(clock.observe(start + Duration::from_millis(500), 24_012), Ok(None));
|
||||
let first = clock.observe(start + Duration::from_secs(1), 48_024).unwrap().unwrap();
|
||||
assert!((300.0..330.0).contains(&first));
|
||||
for seconds in 2..=10 {
|
||||
let ppm = clock.observe(start + Duration::from_secs(seconds), seconds * 48_024).unwrap().unwrap();
|
||||
assert!((first..=500.000_001).contains(&ppm));
|
||||
for seconds in 1..=400 {
|
||||
assert_eq!(clock.observe(start + Duration::from_secs(seconds), seconds * 48_024), Ok(None));
|
||||
}
|
||||
assert!((clock.drift_ppm() - 500.0).abs() < 0.1);
|
||||
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;
|
||||
}
|
||||
}
|
||||
assert!(acquired);
|
||||
assert!((clock.drift_ppm() - 500.0).abs() < 0.000_001);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clock_fault_clears_estimate_instead_of_hiding_excess_drift() {
|
||||
let start = Instant::now();
|
||||
let mut clock = ClockTracker::new(48_000).unwrap();
|
||||
clock.observe(start, 100).unwrap();
|
||||
assert_eq!(clock.observe(start + Duration::from_secs(1), 48_196), Err(ClockDiscontinuity::DriftOutOfRange));
|
||||
clock.observe(start, 0).unwrap();
|
||||
let mut fault = None;
|
||||
for seconds in 1..=201 {
|
||||
if let Err(error) = clock.observe(start + Duration::from_secs(seconds), seconds * 48_096) {
|
||||
fault = Some(error);
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert_eq!(fault, Some(ClockDiscontinuity::DriftOutOfRange));
|
||||
assert_eq!(clock.drift_ppm(), 0.0);
|
||||
assert_eq!(clock.observe(start, 0), Ok(None));
|
||||
assert_eq!(clock.observe(start - Duration::from_millis(1), 480), Err(ClockDiscontinuity::TimestampReversed));
|
||||
@@ -111,6 +123,39 @@ fn clock_fault_clears_estimate_instead_of_hiding_excess_drift() {
|
||||
assert_eq!(clock.observe(start + Duration::from_secs(1), 480), Err(ClockDiscontinuity::TimestampJump));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clock_accepts_repeated_callback_estimates_but_bounds_cumulative_uncertainty() {
|
||||
for rate in [44_100, 48_000] {
|
||||
let start = Instant::now();
|
||||
let mut clock = ClockTracker::new(rate).unwrap();
|
||||
assert_eq!(clock.observe(start, 0), Ok(None));
|
||||
assert_eq!(clock.observe(start, 0), Ok(None)); // another subblock, not a clock tick
|
||||
for callback in 1..=9 {
|
||||
assert_eq!(clock.observe(start, u64::from(rate) * callback / 50), Ok(None));
|
||||
}
|
||||
// Each individual callback advances only 20 ms; the aggregate must still
|
||||
// fail rather than turn an indefinitely clamped clock into valid timing.
|
||||
assert_eq!(clock.observe(start, u64::from(rate) * 11 / 50), Err(ClockDiscontinuity::TimestampJump));
|
||||
clock.observe(start, 0).unwrap();
|
||||
assert_eq!(clock.observe(start + Duration::from_millis(211), u64::from(rate) / 100), Err(ClockDiscontinuity::TimestampJump));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn burst_offset_is_not_misreported_as_hardware_drift_after_one_second() {
|
||||
for rate in [44_100, 48_000] {
|
||||
let start = Instant::now();
|
||||
let mut clock = ClockTracker::new(rate).unwrap();
|
||||
clock.observe(start, 0).unwrap();
|
||||
for callback in 1..=500 {
|
||||
let position = u64::from(rate) * callback / 100;
|
||||
let at = start + Duration::from_millis((callback * 10).saturating_sub(30));
|
||||
assert_eq!(clock.observe(at, position), Ok(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