The device waits for a sample instead of playing its own silence
Browse files at this commit290699ea95dc69d9dc50804ac49a2ea11ad4e840Parent: 267d45b- fix
- the device waits for a sample instead of playing its own silence
4 changed files +222 -19
- crates/engine-audio/src/lib.rs +54 -2
- crates/engine/src/ao.rs +15 -0
- crates/engine/src/playback.rs +73 -17
- crates/engine/tests/playback.rs +80 -0
crates/engine-audio/src/lib.rsmodified+54 -2
| @@ -156,6 +156,18 @@ struct Shared { | ||
| 156 | 156 | /// Output gain as f32 bits, 1.0 until the caller says otherwise. Read once |
| 157 | 157 | /// per callback on the RT thread, so it is an atomic rather than a lock. |
| 158 | 158 | gain: AtomicU32, |
| 159 | + /// Whether the ring has been given a sample to play since it was last | |
| 160 | + /// emptied *on purpose*: `false` from the open and from every `ao_flush` | |
| 161 | + /// until the next accepted write. | |
| 162 | + /// | |
| 163 | + /// A callback that finds nothing to play while this is false is the silence | |
| 164 | + /// of a stream that has not started yet -- the head of a seek, whose decoder | |
| 165 | + /// is still being opened -- and not a decoder that fell behind. Counting it | |
| 166 | + /// made the number below say "a seek happened" (1721 of them over a scripted | |
| 167 | + /// cold play-seek-scrub, against 5 warm) instead of the one thing it is for. | |
| 168 | + /// The wait itself is not hidden by this: it is the clock's business, and | |
| 169 | + /// the clock holds still through it (`Audio::content_at`). | |
| 170 | + primed: AtomicBool, | |
| 159 | 171 | underruns: AtomicU64, |
| 160 | 172 | } |
| 161 | 173 | |
| @@ -250,7 +262,12 @@ fn run( | ||
| 250 | 262 | // the clock below keeps running -- the device plays |
| 251 | 263 | // that silence, so it really is elapsed time. |
| 252 | 264 | slice[got * 4..want * 4].fill(0); |
| 253 | - shared.underruns.fetch_add(1, Ordering::Relaxed); | |
| 265 | + // ...but only a *started* stream can be late; see | |
| 266 | + // `Shared::primed`. One relaxed load on the RT | |
| 267 | + // thread, which is what this branch can afford. | |
| 268 | + if shared.primed.load(Ordering::Relaxed) { | |
| 269 | + shared.underruns.fetch_add(1, Ordering::Relaxed); | |
| 270 | + } | |
| 254 | 271 | } |
| 255 | 272 | // After the fill, so the silence stays silent whatever |
| 256 | 273 | // the gain is, and the underrun count keeps meaning |
| @@ -409,6 +426,9 @@ pub extern "C" fn ao_open(sample_rate: u32, channels: u32) -> *mut c_void { | ||
| 409 | 426 | flush: AtomicBool::new(false), |
| 410 | 427 | resumed: AtomicBool::new(false), |
| 411 | 428 | gain: AtomicU32::new(1.0f32.to_bits()), |
| 429 | + // Nothing has been queued yet, so the callbacks between the connect | |
| 430 | + // and the caller's first write have nothing to be late for. | |
| 431 | + primed: AtomicBool::new(false), | |
| 412 | 432 | underruns: AtomicU64::new(0), |
| 413 | 433 | }); |
| 414 | 434 | let (ready_tx, ready_rx) = mpsc::channel(); |
| @@ -457,7 +477,13 @@ pub unsafe extern "C" fn ao_write(session: *mut c_void, samples: *const f32, n: | ||
| 457 | 477 | return -1; |
| 458 | 478 | } |
| 459 | 479 | let samples = unsafe { std::slice::from_raw_parts(samples, n) }; |
| 460 | - accept(&session.shared.flush, &session.shared.ring, samples) as isize | |
| 480 | + let accepted = accept(&session.shared.flush, &session.shared.ring, samples); | |
| 481 | + if accepted > 0 { | |
| 482 | + // There is something to play from here on, so a starved callback | |
| 483 | + // means what it says again (`Shared::primed`). | |
| 484 | + session.shared.primed.store(true, Ordering::Release); | |
| 485 | + } | |
| 486 | + accepted as isize | |
| 461 | 487 | })) |
| 462 | 488 | .unwrap_or(-1) |
| 463 | 489 | } |
| @@ -479,6 +505,28 @@ pub unsafe extern "C" fn ao_position(session: *mut c_void) -> i64 { | ||
| 479 | 505 | .unwrap_or(-1) |
| 480 | 506 | } |
| 481 | 507 | |
| 508 | +/// Quanta the device had to fill with silence because the ring was empty -- | |
| 509 | +/// "the decoder was late", counted since the stream opened and never reset. | |
| 510 | +/// The same number [`Session::drop`] prints, readable while the stream runs so | |
| 511 | +/// a benchmark can attribute it to the seek it followed rather than to a whole | |
| 512 | +/// session. -1 on a null session; an inactive stream has no callbacks and so | |
| 513 | +/// cannot underrun at all. | |
| 514 | +/// | |
| 515 | +/// # Safety | |
| 516 | +/// `session` must come from [`ao_open`]. | |
| 517 | +#[unsafe(no_mangle)] | |
| 518 | +pub unsafe extern "C" fn ao_underruns(session: *mut c_void) -> i64 { | |
| 519 | + catch_unwind(AssertUnwindSafe(|| { | |
| 520 | + if session.is_null() { | |
| 521 | + return -1; | |
| 522 | + } | |
| 523 | + // SAFETY: caller-guaranteed live session. | |
| 524 | + let session = unsafe { &*(session as *const Session) }; | |
| 525 | + session.shared.underruns.load(Ordering::Relaxed) as i64 | |
| 526 | + })) | |
| 527 | + .unwrap_or(-1) | |
| 528 | +} | |
| 529 | + | |
| 482 | 530 | /// Pauses (0) or resumes (non-zero) playback. Paused freezes the position. |
| 483 | 531 | /// 0 on success, negative on failure. |
| 484 | 532 | /// |
| @@ -545,6 +593,10 @@ pub unsafe extern "C" fn ao_flush(session: *mut c_void) -> i32 { | ||
| 545 | 593 | } |
| 546 | 594 | // SAFETY: caller-guaranteed live session. |
| 547 | 595 | let session = unsafe { &*(session as *const Session) }; |
| 596 | + // Unprimed first, so the callback that consumes the flag below cannot | |
| 597 | + // find an empty ring and count the head of the restart as a late | |
| 598 | + // decoder (`Shared::primed`). | |
| 599 | + session.shared.primed.store(false, Ordering::Release); | |
| 548 | 600 | session.shared.flush.store(true, Ordering::Release); |
| 549 | 601 | 0 |
| 550 | 602 | })) |
crates/engine/src/ao.rsmodified+15 -0
| @@ -20,6 +20,11 @@ struct Plugin { | ||
| 20 | 20 | set_active: unsafe extern "C" fn(*mut c_void, u32) -> i32, |
| 21 | 21 | set_volume: unsafe extern "C" fn(*mut c_void, f32) -> i32, |
| 22 | 22 | flush: unsafe extern "C" fn(*mut c_void) -> i32, |
| 23 | + /// Optional, unlike its neighbours: this one is a *counter*, and a plugin | |
| 24 | + /// too old to have it is a session that plays perfectly and cannot say how | |
| 25 | + /// many quanta it starved for. Rejecting the whole plugin over that would | |
| 26 | + /// trade the sound for the diagnostic. | |
| 27 | + underruns: Option<unsafe extern "C" fn(*mut c_void) -> i64>, | |
| 23 | 28 | close: unsafe extern "C" fn(*mut c_void), |
| 24 | 29 | // Never dropped (lives in a static), so the fn pointers above stay valid. |
| 25 | 30 | _lib: Library, |
| @@ -63,6 +68,7 @@ fn load() -> Option<Plugin> { | ||
| 63 | 68 | // with no sound at all, which at least says so. |
| 64 | 69 | set_volume: *lib.get(b"ao_set_volume\0").ok()?, |
| 65 | 70 | flush: *lib.get(b"ao_flush\0").ok()?, |
| 71 | + underruns: lib.get(b"ao_underruns\0").ok().map(|f| *f), | |
| 66 | 72 | close: *lib.get(b"ao_close\0").ok()?, |
| 67 | 73 | _lib: lib, |
| 68 | 74 | }) |
| @@ -122,6 +128,15 @@ impl AoSession { | ||
| 122 | 128 | } |
| 123 | 129 | } |
| 124 | 130 | |
| 131 | + /// Quanta the device filled with silence for want of samples, since the | |
| 132 | + /// stream opened: what a benchmark reads to say the decoder kept up. | |
| 133 | + /// `None` from a plugin that does not carry the counter. | |
| 134 | + pub fn underruns(&self) -> Option<u64> { | |
| 135 | + // SAFETY: `handle` came from `ao_open` and is still open. | |
| 136 | + let n = unsafe { (self.plugin.underruns?)(self.handle) }; | |
| 137 | + (n >= 0).then_some(n as u64) | |
| 138 | + } | |
| 139 | + | |
| 125 | 140 | /// Pauses or resumes playback; while paused the position stays put. |
| 126 | 141 | pub fn set_active(&self, active: bool) -> bool { |
| 127 | 142 | // SAFETY: `handle` came from `ao_open` and is still open. |
crates/engine/src/playback.rsmodified+73 -17
| @@ -111,6 +111,22 @@ struct Audio { | ||
| 111 | 111 | /// seek counts it as such, which is a permanent offset between the picture |
| 112 | 112 | /// and the sound, re-rolled by every edit made while playing. |
| 113 | 113 | content_at: Arc<AtomicI64>, |
| 114 | + /// The timeline is *meant* to be playing: what a play or a seek-while-playing | |
| 115 | + /// asks for, and what the feeder turns into a running device the moment it | |
| 116 | + /// has a real sample to play ([`Audio::set_playing`], [`feed`]). | |
| 117 | + /// | |
| 118 | + /// The device is not started by the intent, because an inactive stream has | |
| 119 | + /// no callbacks and therefore no starved quanta: between the flush of a seek | |
| 120 | + /// and the first sample of the new stream -- seconds, on a cold 25 GB film | |
| 121 | + /// whose decoder is opened on the feeder -- a device started here would play | |
| 122 | + /// its own silence and count every quantum of it as an underrun. | |
| 123 | + /// | |
| 124 | + /// Written and read under the device lock, beside the [`Audio::content_at`] | |
| 125 | + /// stamp, and that is the whole race: whichever of the two sides takes the | |
| 126 | + /// lock first, the other sees its half (a stamp already there, or an intent | |
| 127 | + /// already set), so the device is started exactly once and a pause landing | |
| 128 | + /// during an open can never be overtaken by a late activation. | |
| 129 | + wants_active: Arc<AtomicBool>, | |
| 114 | 130 | /// The last [`TAP_SAMPLES`] mono samples handed to the device, oldest |
| 115 | 131 | /// first: what a meter or an analyser draws. Written by the feeder, which |
| 116 | 132 | /// is not the device's own callback -- the plugin's RT thread never sees |
| @@ -136,6 +152,22 @@ impl Audio { | ||
| 136 | 152 | && position as u64 * self.channels >= self.fed.load(Ordering::Relaxed) |
| 137 | 153 | } |
| 138 | 154 | |
| 155 | + /// Says whether the timeline is playing, and starts or stops the device for | |
| 156 | + /// it: `true` runs it *if there is already something to play*, and otherwise | |
| 157 | + /// leaves it to the feeder's first sample ([`Audio::wants_active`]). `false` | |
| 158 | + /// stops it at once -- a pause is never deferred, whatever an open in flight | |
| 159 | + /// is about to find. | |
| 160 | + fn set_playing(&self, playing: bool) { | |
| 161 | + // The lock, not the atomics, is what orders this against the feeder's | |
| 162 | + // stamp: the store below and the load after it are one critical section, | |
| 163 | + // and so is the feeder's pair. | |
| 164 | + let ao = self.ao.lock().unwrap(); | |
| 165 | + self.wants_active.store(playing, Ordering::Release); | |
| 166 | + if !playing || self.content_at.load(Ordering::Acquire) >= 0 { | |
| 167 | + ao.set_active(playing); | |
| 168 | + } | |
| 169 | + } | |
| 170 | + | |
| 139 | 171 | /// Keeps the newest [`TAP_SAMPLES`] of what was just queued, downmixed to |
| 140 | 172 | /// mono. Called from the feeder only, once per accepted write. |
| 141 | 173 | fn note_tap(&self, accepted: &[f32]) { |
| @@ -2368,7 +2400,7 @@ impl PlaybackSession { | ||
| 2368 | 2400 | // here too -- `clock.seek_to(t)` and then `set_active(true)`. |
| 2369 | 2401 | self.clock.play(); |
| 2370 | 2402 | if let Some(audio) = &self.audio { |
| 2371 | - audio.ao.lock().unwrap().set_active(true); | |
| 2403 | + audio.set_playing(true); | |
| 2372 | 2404 | } |
| 2373 | 2405 | } |
| 2374 | 2406 | |
| @@ -2377,7 +2409,7 @@ impl PlaybackSession { | ||
| 2377 | 2409 | return; |
| 2378 | 2410 | } |
| 2379 | 2411 | if let Some(audio) = &self.audio { |
| 2380 | - audio.ao.lock().unwrap().set_active(false); | |
| 2412 | + audio.set_playing(false); | |
| 2381 | 2413 | } |
| 2382 | 2414 | self.clock.pause(); |
| 2383 | 2415 | } |
| @@ -2443,6 +2475,16 @@ impl PlaybackSession { | ||
| 2443 | 2475 | Some((tap, audio.sample_rate)) |
| 2444 | 2476 | } |
| 2445 | 2477 | |
| 2478 | + /// How many quanta the device has had to fill with silence for want of | |
| 2479 | + /// samples since this session opened: the count that means "the decoder was | |
| 2480 | + /// late", sampled live rather than printed at the end of the process, so a | |
| 2481 | + /// caller can attribute it to the seek it followed | |
| 2482 | + /// ([`AoSession::underruns`]). `None` with no device, and with a plugin too | |
| 2483 | + /// old to carry the counter. | |
| 2484 | + pub fn audio_underruns(&self) -> Option<u64> { | |
| 2485 | + self.audio.as_ref()?.ao.lock().unwrap().underruns() | |
| 2486 | + } | |
| 2487 | + | |
| 2446 | 2488 | /// Repositions the timeline to `secs`, clamped to the *timeline*. Both decode |
| 2447 | 2489 | /// workers are replaced rather than steered: a fresh channel cannot hold a |
| 2448 | 2490 | /// stale frame, and it works just as well after EOF, where the old workers |
| @@ -2526,23 +2568,17 @@ impl PlaybackSession { | ||
| 2526 | 2568 | /// the clock held until the new stream is really audible (see |
| 2527 | 2569 | /// [`Audio::content_at`]). |
| 2528 | 2570 | /// |
| 2529 | - /// corner-cut: the device is made active here, before the new stream has been | |
| 2530 | - /// opened ([`start_audio`](Self::start_audio) opens on the feeder now), so a | |
| 2531 | - /// cold open leaves it playing its own silence with an empty ring -- audibly | |
| 2532 | - /// the same silence as before, and counted: a scripted cold play-seek-scrub | |
| 2533 | - /// session goes from 5 to 1721 `engine_audio: N underruns`, one per starved | |
| 2534 | - /// quantum, while a warm one is unchanged (46 -> 53 over the suite's 11 | |
| 2535 | - /// sessions). Ceiling: the count stops meaning "the decoder was late" during | |
| 2536 | - /// a cold seek. Upgrade path is a `wants_active` flag written here and read | |
| 2537 | - /// by the feeder under the device lock beside the [`Audio::content_at`] | |
| 2538 | - /// stamp, so the device is started by the first real sample rather than by | |
| 2539 | - /// the intent to play -- it has to be the lock and the epoch check, or a | |
| 2540 | - /// pause during the open would be overtaken by a late activation and the | |
| 2541 | - /// timeline would play while it says it is paused. | |
| 2571 | + /// Only the *intent* is set here: the open runs on the feeder | |
| 2572 | + /// ([`start_audio`](Self::start_audio)), so the device is started by that | |
| 2573 | + /// stream's first real sample instead ([`Audio::wants_active`]). A device | |
| 2574 | + /// made active over an empty ring plays its own silence and counts one | |
| 2575 | + /// underrun per starved quantum -- a scripted cold play-seek-scrub session | |
| 2576 | + /// used to go from 5 to 1721 of them -- while the ear hears the same silence | |
| 2577 | + /// either way, so nothing is gained for the count that is lost. | |
| 2542 | 2578 | fn resume(&mut self, was_playing: bool) { |
| 2543 | 2579 | self.priming = true; |
| 2544 | - if was_playing && let Some(audio) = &self.audio { | |
| 2545 | - audio.ao.lock().unwrap().set_active(true); | |
| 2580 | + if let Some(audio) = &self.audio { | |
| 2581 | + audio.set_playing(was_playing); | |
| 2546 | 2582 | } |
| 2547 | 2583 | } |
| 2548 | 2584 | |
| @@ -2988,6 +3024,7 @@ fn open_audio(path: &Path, stream: usize) -> (Option<Audio>, Option<String>) { | ||
| 2988 | 3024 | died: Arc::new(AtomicBool::new(false)), |
| 2989 | 3025 | epoch: Arc::new(AtomicU64::new(0)), |
| 2990 | 3026 | content_at: Arc::new(AtomicI64::new(-1)), |
| 3027 | + wants_active: Arc::new(AtomicBool::new(false)), | |
| 2991 | 3028 | tap: Arc::new(Mutex::new(Vec::with_capacity(TAP_SAMPLES))), |
| 2992 | 3029 | feeders: Arc::new(AtomicUsize::new(0)), |
| 2993 | 3030 | }; |
| @@ -3042,6 +3079,25 @@ fn feed(rx: Receiver<AudioChunk>, audio: &Audio, epoch: u64) { | ||
| 3042 | 3079 | audio |
| 3043 | 3080 | .fed |
| 3044 | 3081 | .store(at as u64 * audio.channels, Ordering::Relaxed); |
| 3082 | + // ...and *this* is where a playing timeline's device starts: on | |
| 3083 | + // the first sample there is to play, under the same lock and | |
| 3084 | + // past the same epoch check as the stamp, so the silence of the | |
| 3085 | + // open was never played and never counted | |
| 3086 | + // ([`Audio::wants_active`]). | |
| 3087 | + if audio.wants_active.load(Ordering::Acquire) { | |
| 3088 | + ao.set_active(true); | |
| 3089 | + } | |
| 3090 | + } else if accepted == 0 && audio.content_at.load(Ordering::Acquire) < 0 { | |
| 3091 | + // Nothing taken with nothing yet queued is the *flush* of the | |
| 3092 | + // restart still standing: the ring refuses a write until a | |
| 3093 | + // callback has consumed the flag (`engine_audio::accept`), and | |
| 3094 | + // only a running device has callbacks. So the device is started | |
| 3095 | + // here too -- there is a sample in hand, which is what the wait | |
| 3096 | + // was for -- and the quantum or two of that handshake is the | |
| 3097 | + // silence `Shared::primed` does not count. | |
| 3098 | + if audio.wants_active.load(Ordering::Acquire) { | |
| 3099 | + ao.set_active(true); | |
| 3100 | + } | |
| 3045 | 3101 | } |
| 3046 | 3102 | accepted |
| 3047 | 3103 | }; |
crates/engine/tests/playback.rsmodified+80 -0
| @@ -450,6 +450,86 @@ fn a_cold_audio_open_does_not_block_the_seek() { | ||
| 450 | 450 | ); |
| 451 | 451 | } |
| 452 | 452 | |
| 453 | +/// The seek storm the *ear* is in: 20 random seeks into a cold file, each | |
| 454 | +/// resuming playback, and not one starved quantum out of the device. | |
| 455 | +/// | |
| 456 | +/// The device is started by the feeder's first real sample, never by the intent | |
| 457 | +/// to play ([`PlaybackSession::play`] and the seek's own resume), because an | |
| 458 | +/// audio open is not free -- seconds, on a cold film -- and a stream made active | |
| 459 | +/// over an empty ring plays its own silence and counts every quantum of it as | |
| 460 | +/// an underrun. It sounds identical either way; what it destroys is the meaning | |
| 461 | +/// of the count, which is the only thing that says the decoder is keeping up. | |
| 462 | +/// This is the regression guard for that: cold storm, count must be nil. | |
| 463 | +/// | |
| 464 | +/// `assets/test_av.mp4` by default; `EDITH_COLD_FILM=<a big film>` and | |
| 465 | +/// `EDITH_SEEKS=<n>` make it the measurement (the rubric's floor is 50 seeks | |
| 466 | +/// into a two-hour film). | |
| 467 | +#[test] | |
| 468 | +#[ignore = "needs a running PipeWire daemon"] | |
| 469 | +fn a_cold_seek_storm_starves_no_quantum() { | |
| 470 | + let path = std::env::var_os("EDITH_COLD_FILM") | |
| 471 | + .map(PathBuf::from) | |
| 472 | + .unwrap_or_else(|| asset("test_av.mp4")); | |
| 473 | + let seeks: u32 = std::env::var("EDITH_SEEKS") | |
| 474 | + .ok() | |
| 475 | + .and_then(|n| n.parse().ok()) | |
| 476 | + .unwrap_or(20); | |
| 477 | + let mut session = open(&path); | |
| 478 | + let duration = session.timeline_duration(); | |
| 479 | + let mut last_index = None; | |
| 480 | + session.play(); | |
| 481 | + run_for(&mut session, &mut last_index, Duration::from_millis(300)); | |
| 482 | + // Only a machine with the plugin *and* a daemon can starve at all; without | |
| 483 | + // one the session plays wall-paced and there is nothing to measure. | |
| 484 | + let Some(before) = session.audio_underruns() else { | |
| 485 | + eprintln!("no audio device: seek storm not measured"); | |
| 486 | + return; | |
| 487 | + }; | |
| 488 | + evict(&path); | |
| 489 | + | |
| 490 | + // xorshift64 off a fixed seed: the same storm every run, so two runs of | |
| 491 | + // this are comparable without a dependency to draw the numbers from. | |
| 492 | + let mut rng = 0x2545_f491_4f6c_dd1du64; | |
| 493 | + let storm = Instant::now(); | |
| 494 | + for i in 0..seeks { | |
| 495 | + rng ^= rng << 13; | |
| 496 | + rng ^= rng >> 7; | |
| 497 | + rng ^= rng << 17; | |
| 498 | + // Off the end of the timeline is a seek with nothing to play; keep the | |
| 499 | + // storm inside the film. | |
| 500 | + let target = duration * 0.98 * (rng >> 11) as f64 / (1u64 << 53) as f64; | |
| 501 | + session.seek(target); | |
| 502 | + // The sound has to *come back*, which is the other half of this: a | |
| 503 | + // device that never plays starves no quantum either, so the count below | |
| 504 | + // means nothing unless every seek resumed. The clock is held at the | |
| 505 | + // target until the first real sample is queued, so it moving is the | |
| 506 | + // sound arriving ([`PlaybackSession::tick`]). | |
| 507 | + let mut landed = None; | |
| 508 | + let deadline = Instant::now() + Duration::from_secs(20); | |
| 509 | + while session.now() <= target + 0.05 { | |
| 510 | + pump(&mut session, &mut landed); | |
| 511 | + assert!( | |
| 512 | + Instant::now() < deadline, | |
| 513 | + "seek {i} to {target:.1}s never resumed: the clock stood still" | |
| 514 | + ); | |
| 515 | + sleep(Duration::from_millis(8)); | |
| 516 | + } | |
| 517 | + // ...and then plays for a moment, which is where a late decoder shows. | |
| 518 | + run_for(&mut session, &mut landed, Duration::from_millis(300)); | |
| 519 | + } | |
| 520 | + let underruns = session.audio_underruns().expect("device still open") - before; | |
| 521 | + eprintln!( | |
| 522 | + "{seeks} cold seeks into {} in {:?}: {underruns} underruns ({before} before the storm)", | |
| 523 | + path.display(), | |
| 524 | + storm.elapsed() | |
| 525 | + ); | |
| 526 | + assert_eq!( | |
| 527 | + underruns, 0, | |
| 528 | + "the device starved during the storm: {underruns} quanta of silence it \ | |
| 529 | + counted as a late decoder" | |
| 530 | + ); | |
| 531 | +} | |
| 532 | + | |
| 453 | 533 | /// The edit list end to end: two cuts, drop the middle clip, play the result. |
| 454 | 534 | /// What comes out is one contiguous timeline whose *pictures* skip the hole -- |
| 455 | 535 | /// no audio needed, so this runs anywhere. |