A seek storm and a play loop, and the underruns they cost
Browse files at this commit8271b5dee66c5b08815958be19b576499d92eaa4Parent: f6f8156- feat
- a seek storm and a play loop, and the underruns they cost
5 changed files +361 -4
- crates/engine-audio/src/lib.rs +40 -0
- crates/engine/examples/bench.rs +258 -2
- crates/engine/src/ao.rs +17 -0
- crates/engine/src/playback.rs +31 -0
- scripts/bench.sh +15 -2
crates/engine-audio/src/lib.rsmodified+40 -0
| @@ -157,6 +157,11 @@ struct Shared { | |||
| 157 | /// per callback on the RT thread, so it is an atomic rather than a lock. | 157 | /// per callback on the RT thread, so it is an atomic rather than a lock. |
| 158 | gain: AtomicU32, | 158 | gain: AtomicU32, |
| 159 | underruns: AtomicU64, | 159 | underruns: AtomicU64, |
| 160 | + /// Device position (samples per channel) read at the most recent underrun, | ||
| 161 | + /// `-1` until one happens: what says whether the count in hand is old news | ||
| 162 | + /// or is still growing. Written on the RT thread, and only on the starved | ||
| 163 | + /// path, so the ordinary callback pays nothing for it. | ||
| 164 | + last_underrun: AtomicI64, | ||
| 160 | } | 165 | } |
| 161 | 166 | ||
| 162 | enum Ctl { | 167 | enum Ctl { |
| @@ -251,6 +256,12 @@ fn run( | |||
| 251 | // that silence, so it really is elapsed time. | 256 | // that silence, so it really is elapsed time. |
| 252 | slice[got * 4..want * 4].fill(0); | 257 | slice[got * 4..want * 4].fill(0); |
| 253 | shared.underruns.fetch_add(1, Ordering::Relaxed); | 258 | shared.underruns.fetch_add(1, Ordering::Relaxed); |
| 259 | + // The position this callback is about to compute is | ||
| 260 | + // not known yet; the previous one is a quantum | ||
| 261 | + // (~23 ms) behind and needs no clock call here. | ||
| 262 | + shared | ||
| 263 | + .last_underrun | ||
| 264 | + .store(shared.position.load(Ordering::Relaxed), Ordering::Relaxed); | ||
| 254 | } | 265 | } |
| 255 | // After the fill, so the silence stays silent whatever | 266 | // After the fill, so the silence stays silent whatever |
| 256 | // the gain is, and the underrun count keeps meaning | 267 | // the gain is, and the underrun count keeps meaning |
| @@ -410,6 +421,7 @@ pub extern "C" fn ao_open(sample_rate: u32, channels: u32) -> *mut c_void { | |||
| 410 | resumed: AtomicBool::new(false), | 421 | resumed: AtomicBool::new(false), |
| 411 | gain: AtomicU32::new(1.0f32.to_bits()), | 422 | gain: AtomicU32::new(1.0f32.to_bits()), |
| 412 | underruns: AtomicU64::new(0), | 423 | underruns: AtomicU64::new(0), |
| 424 | + last_underrun: AtomicI64::new(-1), | ||
| 413 | }); | 425 | }); |
| 414 | let (ready_tx, ready_rx) = mpsc::channel(); | 426 | let (ready_tx, ready_rx) = mpsc::channel(); |
| 415 | let (ctl_tx, ctl_rx) = mpsc::channel(); | 427 | let (ctl_tx, ctl_rx) = mpsc::channel(); |
| @@ -479,6 +491,34 @@ pub unsafe extern "C" fn ao_position(session: *mut c_void) -> i64 { | |||
| 479 | .unwrap_or(-1) | 491 | .unwrap_or(-1) |
| 480 | } | 492 | } |
| 481 | 493 | ||
| 494 | +/// Starved callbacks since the stream opened -- one per quantum the decoder was | ||
| 495 | +/// late for -- and, through `last_at`, the device position the newest of them | ||
| 496 | +/// was seen at (`-1` if there has been none). The same number the drop print | ||
| 497 | +/// reports, asked for while the session is still running: a caller measuring a | ||
| 498 | +/// seek reads it before and after and the difference is that seek's cost. | ||
| 499 | +/// | ||
| 500 | +/// Two relaxed atomic loads, nothing else: the RT thread writes both and must | ||
| 501 | +/// never wait on a reader. | ||
| 502 | +/// | ||
| 503 | +/// # Safety | ||
| 504 | +/// `session` must come from [`ao_open`]; `last_at` is either null or writable. | ||
| 505 | +#[unsafe(no_mangle)] | ||
| 506 | +pub unsafe extern "C" fn ao_underruns(session: *mut c_void, last_at: *mut i64) -> i64 { | ||
| 507 | + catch_unwind(AssertUnwindSafe(|| { | ||
| 508 | + if session.is_null() { | ||
| 509 | + return -1; | ||
| 510 | + } | ||
| 511 | + // SAFETY: caller-guaranteed live session. | ||
| 512 | + let session = unsafe { &*(session as *const Session) }; | ||
| 513 | + if !last_at.is_null() { | ||
| 514 | + // SAFETY: caller-guaranteed writable, and it is a plain i64. | ||
| 515 | + unsafe { *last_at = session.shared.last_underrun.load(Ordering::Relaxed) }; | ||
| 516 | + } | ||
| 517 | + session.shared.underruns.load(Ordering::Relaxed) as i64 | ||
| 518 | + })) | ||
| 519 | + .unwrap_or(-1) | ||
| 520 | +} | ||
| 521 | + | ||
| 482 | /// Pauses (0) or resumes (non-zero) playback. Paused freezes the position. | 522 | /// Pauses (0) or resumes (non-zero) playback. Paused freezes the position. |
| 483 | /// 0 on success, negative on failure. | 523 | /// 0 on success, negative on failure. |
| 484 | /// | 524 | /// |
crates/engine/examples/bench.rsmodified+258 -2
| @@ -1,5 +1,6 @@ | |||
| 1 | //! The baseline every later decode/encode change is measured against: open, | 1 | //! The baseline every later decode/encode change is measured against: open, |
| 2 | -//! seek, scrub and export, timed on the real library rather than on a fixture. | 2 | +//! seek, seek storm, play loop, scrub and export, timed on the real library |
| 3 | +//! rather than on a fixture. | ||
| 3 | //! | 4 | //! |
| 4 | //! `cargo run --release -p engine --example bench -- <metric> <file> [args]` | 5 | //! `cargo run --release -p engine --example bench -- <metric> <file> [args]` |
| 5 | //! | 6 | //! |
| @@ -9,7 +10,10 @@ | |||
| 9 | //! failure down as data. | 10 | //! failure down as data. |
| 10 | //! | 11 | //! |
| 11 | //! Every row is one TSV line -- `file, metric, unit, n, median, min, max, note` | 12 | //! Every row is one TSV line -- `file, metric, unit, n, median, min, max, note` |
| 12 | -//! -- so the whole baseline is `cat`ted together and diffed later. | 13 | +//! -- so the whole baseline is `cat`ted together and diffed later. The note is |
| 14 | +//! where the tail percentile and the **decode backend** live: a row that does | ||
| 15 | +//! not say `backend hw` was measured in software, and a baseline that does not | ||
| 16 | +//! say which is not a baseline (see `scripts/bench.sh` on `LD_LIBRARY_PATH`). | ||
| 13 | //! | 17 | //! |
| 14 | //! **Cold and warm.** Cold means the file's pages are dropped from the page | 18 | //! **Cold and warm.** Cold means the file's pages are dropped from the page |
| 15 | //! cache immediately before the measurement, with `posix_fadvise(DONTNEED)` on | 19 | //! cache immediately before the measurement, with `posix_fadvise(DONTNEED)` on |
| @@ -49,6 +53,8 @@ fn main() { | |||
| 49 | match metric.as_str() { | 53 | match metric.as_str() { |
| 50 | "open" => open_bench(&path), | 54 | "open" => open_bench(&path), |
| 51 | "seek" => seek_bench(&path, arg_f64(args.next(), "seconds")), | 55 | "seek" => seek_bench(&path, arg_f64(args.next(), "seconds")), |
| 56 | + "seekstorm" => seekstorm_bench(&path, arg_seed(args.next())), | ||
| 57 | + "playloop" => playloop_bench(&path, arg_f64(args.next(), "seconds"), arg_seed(args.next())), | ||
| 52 | "scrub" => scrub_bench(&path), | 58 | "scrub" => scrub_bench(&path), |
| 53 | "waveform" => waveform_bench(&path), | 59 | "waveform" => waveform_bench(&path), |
| 54 | "export" => { | 60 | "export" => { |
| @@ -63,6 +69,8 @@ fn main() { | |||
| 63 | fn usage() -> ! { | 69 | fn usage() -> ! { |
| 64 | eprintln!( | 70 | eprintln!( |
| 65 | "usage: bench open <file>\n bench seek <file> <secs>\n \ | 71 | "usage: bench open <file>\n bench seek <file> <secs>\n \ |
| 72 | + bench seekstorm <file> [seed]\n \ | ||
| 73 | + bench playloop <file> <secs> [seed]\n \ | ||
| 66 | bench scrub <file>\n bench waveform <file>\n \ | 74 | bench scrub <file>\n bench waveform <file>\n \ |
| 67 | bench export <file> <h264sw|h264hw|av1|hevc|hevchw> <out_dir>" | 75 | bench export <file> <h264sw|h264hw|av1|hevc|hevchw> <out_dir>" |
| 68 | ); | 76 | ); |
| @@ -74,6 +82,12 @@ fn arg_f64(arg: Option<String>, what: &str) -> f64 { | |||
| 74 | .unwrap_or_else(|| panic!("missing {what}")) | 82 | .unwrap_or_else(|| panic!("missing {what}")) |
| 75 | } | 83 | } |
| 76 | 84 | ||
| 85 | +/// The seed the random metrics draw their positions from: same seed, same | ||
| 86 | +/// seeks, so a before and an after are the same measurement. | ||
| 87 | +fn arg_seed(arg: Option<String>) -> u64 { | ||
| 88 | + arg.and_then(|s| s.parse().ok()).unwrap_or(1) | ||
| 89 | +} | ||
| 90 | + | ||
| 77 | // ---------------------------------------------------------------- reporting | 91 | // ---------------------------------------------------------------- reporting |
| 78 | 92 | ||
| 79 | /// One TSV row: the median is what a comparison uses, the min and max are what | 93 | /// One TSV row: the median is what a comparison uses, the min and max are what |
| @@ -125,6 +139,34 @@ fn ttff_timeout() -> Duration { | |||
| 125 | Duration::from_secs_f64(env_f64("BENCH_TTFF_TIMEOUT", 180.0)) | 139 | Duration::from_secs_f64(env_f64("BENCH_TTFF_TIMEOUT", 180.0)) |
| 126 | } | 140 | } |
| 127 | 141 | ||
| 142 | +/// The p'th percentile of `samples`, nearest rank on the sorted copy. The | ||
| 143 | +/// median is [`row`]'s business; this is for the tail, which is the number a | ||
| 144 | +/// dropped frame and a starved ring both live in. | ||
| 145 | +fn pct(samples: &[f64], p: f64) -> f64 { | ||
| 146 | + if samples.is_empty() { | ||
| 147 | + return 0.0; | ||
| 148 | + } | ||
| 149 | + let mut sorted = samples.to_vec(); | ||
| 150 | + sorted.sort_by(f64::total_cmp); | ||
| 151 | + sorted[((sorted.len() - 1) as f64 * p).round() as usize] | ||
| 152 | +} | ||
| 153 | + | ||
| 154 | +/// A seeded LCG, so "random" seeks are the same random seeks tomorrow. Sixteen | ||
| 155 | +/// lines of a crate would do the same thing and none of the quality a real | ||
| 156 | +/// generator has matters to a list of positions in a film. | ||
| 157 | +struct Lcg(u64); | ||
| 158 | + | ||
| 159 | +impl Lcg { | ||
| 160 | + /// The next position, in `0.0..1.0`. | ||
| 161 | + fn next(&mut self) -> f64 { | ||
| 162 | + self.0 = self | ||
| 163 | + .0 | ||
| 164 | + .wrapping_mul(6_364_136_223_846_793_005) | ||
| 165 | + .wrapping_add(1_442_695_040_888_963_407); | ||
| 166 | + (self.0 >> 11) as f64 / (1u64 << 53) as f64 | ||
| 167 | + } | ||
| 168 | +} | ||
| 169 | + | ||
| 128 | fn env_f64(key: &str, default: f64) -> f64 { | 170 | fn env_f64(key: &str, default: f64) -> f64 { |
| 129 | std::env::var(key) | 171 | std::env::var(key) |
| 130 | .ok() | 172 | .ok() |
| @@ -250,6 +292,220 @@ fn seek_bench(path: &Path, secs: f64) { | |||
| 250 | row(path, &format!("seek_ttff_{secs:.0}s"), "ms", &samples, ¬e); | 292 | row(path, &format!("seek_ttff_{secs:.0}s"), "ms", &samples, ¬e); |
| 251 | } | 293 | } |
| 252 | 294 | ||
| 295 | +// -------------------------------------------------------------- seek storm | ||
| 296 | + | ||
| 297 | +/// Seeks a film opens with none of: fifty positions nobody chose, drawn from a | ||
| 298 | +/// seed so the same fifty come back tomorrow. `seek` measures one point five | ||
| 299 | +/// times over; this measures the spread across the whole file, which is where | ||
| 300 | +/// an index lookup, a keyframe distance and a decoder reopen all vary. | ||
| 301 | +/// | ||
| 302 | +/// Cold is the first pass over a freshly evicted file, warm the same fifty | ||
| 303 | +/// again straight after -- the same two questions the other metrics ask, and | ||
| 304 | +/// the audio underruns each pass cost are counted with it | ||
| 305 | +/// ([`engine::PlaybackSession::audio_underruns`]), because a seek that lands | ||
| 306 | +/// fast and starves the ring is not a seek that worked. | ||
| 307 | +const STORM_SEEKS: usize = 50; | ||
| 308 | + | ||
| 309 | +fn seekstorm_bench(path: &Path, seed: u64) { | ||
| 310 | + evict(path); | ||
| 311 | + let mut session = match engine::PlaybackSession::open(path) { | ||
| 312 | + Ok(session) => session, | ||
| 313 | + Err(e) => { | ||
| 314 | + row(path, "seekstorm_ttff_cold", "ms", &[], &format!("FAIL({e})")); | ||
| 315 | + return; | ||
| 316 | + } | ||
| 317 | + }; | ||
| 318 | + // Playing throughout, because the underruns are the point: a paused device | ||
| 319 | + // runs no callbacks and can never starve, so a storm measured paused would | ||
| 320 | + // report zero however badly the seeks fed it. This is the complaint's own | ||
| 321 | + // shape -- a film that is playing, jumped around in. | ||
| 322 | + session.play(); | ||
| 323 | + let duration = session.timeline_duration(); | ||
| 324 | + let mut rng = Lcg(seed); | ||
| 325 | + // Short of the very end: a landing with no picture after it is a different | ||
| 326 | + // measurement (end of stream), and every seek here is meant to be one. | ||
| 327 | + let targets: Vec<f64> = (0..STORM_SEEKS) | ||
| 328 | + .map(|_| rng.next() * duration * 0.95) | ||
| 329 | + .collect(); | ||
| 330 | + | ||
| 331 | + for pass in ["cold", "warm"] { | ||
| 332 | + let before = session.audio_underruns().map_or(0, |(n, _)| n); | ||
| 333 | + let mut samples = Vec::new(); | ||
| 334 | + let mut missed = Vec::new(); | ||
| 335 | + let mut peak = threads(); | ||
| 336 | + for &secs in &targets { | ||
| 337 | + match seek_ttff(&mut session, secs, &mut peak) { | ||
| 338 | + Ok(ms) => samples.push(ms), | ||
| 339 | + Err(why) => missed.push(why), | ||
| 340 | + } | ||
| 341 | + } | ||
| 342 | + let audio = session.audio_underruns(); | ||
| 343 | + let backend = session.decode_backend().label(); | ||
| 344 | + let mut note = format!( | ||
| 345 | + "backend {backend}, p95 {:.2}ms, peak {peak} threads, seed {seed}", | ||
| 346 | + pct(&samples, 0.95) | ||
| 347 | + ); | ||
| 348 | + if !missed.is_empty() { | ||
| 349 | + note += &format!(", {}/{STORM_SEEKS} NO-FRAME({})", missed.len(), missed[0]); | ||
| 350 | + } | ||
| 351 | + row(path, &format!("seekstorm_ttff_{pass}"), "ms", &samples, ¬e); | ||
| 352 | + row( | ||
| 353 | + path, | ||
| 354 | + &format!("seekstorm_underruns_{pass}"), | ||
| 355 | + "count", | ||
| 356 | + &[audio.map_or(0, |(n, _)| n).saturating_sub(before) as f64], | ||
| 357 | + &match audio { | ||
| 358 | + None => "no audio device".into(), | ||
| 359 | + Some((total, last)) => format!( | ||
| 360 | + "backend {backend}, {total} since open, {}", | ||
| 361 | + last.map_or_else(|| "none yet".into(), |t| format!("last at {t:.1}s device")) | ||
| 362 | + ), | ||
| 363 | + }, | ||
| 364 | + ); | ||
| 365 | + } | ||
| 366 | +} | ||
| 367 | + | ||
| 368 | +// --------------------------------------------------------------- play loop | ||
| 369 | + | ||
| 370 | +/// How long a picture waits between frames while the sound runs: the app's own | ||
| 371 | +/// pump (`crates/app/src/player/transport.rs`), driven here for `secs` with a | ||
| 372 | +/// seek to a random point every five seconds -- the shape of the complaint, | ||
| 373 | +/// which is a film played and jumped around in rather than a seek measured on | ||
| 374 | +/// its own. | ||
| 375 | +/// | ||
| 376 | +/// Three numbers come out: the gap between frames (p50 and p99, the tail being | ||
| 377 | +/// the jump a person sees), the audio underruns over the whole run, and how | ||
| 378 | +/// many times the picture worker was restarted -- by a seek, by a clip | ||
| 379 | +/// boundary, or by the late-picture resync, which is counted separately in the | ||
| 380 | +/// note. | ||
| 381 | +/// | ||
| 382 | +/// The resync rule is the app's, repeated here (`LATE_RESYNC`, `RESYNC_GAP` in | ||
| 383 | +/// `crates/app/src/transport.rs`) because an engine example cannot depend on | ||
| 384 | +/// the binary. Repeated only: nothing in this file changes how playback runs. | ||
| 385 | +const PLAYLOOP_SEEK_GAP: Duration = Duration::from_secs(5); | ||
| 386 | +const LATE_RESYNC: f64 = 0.4; | ||
| 387 | +const RESYNC_GAP: Duration = Duration::from_secs(2); | ||
| 388 | + | ||
| 389 | +fn playloop_bench(path: &Path, secs: f64, seed: u64) { | ||
| 390 | + evict(path); | ||
| 391 | + let mut session = match engine::PlaybackSession::open(path) { | ||
| 392 | + Ok(session) => session, | ||
| 393 | + Err(e) => { | ||
| 394 | + row(path, "playloop_frame_gap", "ms", &[], &format!("FAIL({e})")); | ||
| 395 | + return; | ||
| 396 | + } | ||
| 397 | + }; | ||
| 398 | + let fps = session.meta().frame_rate; | ||
| 399 | + let duration = session.timeline_duration(); | ||
| 400 | + let mut rng = Lcg(seed); | ||
| 401 | + | ||
| 402 | + let mut gaps = Vec::new(); | ||
| 403 | + let mut held: Option<engine::Frame> = None; | ||
| 404 | + let (mut shown, mut dropped, mut seeks, mut resyncs) = (0u64, 0u64, 0u64, 0u64); | ||
| 405 | + let mut last_resync: Option<Instant> = None; | ||
| 406 | + // The first frame of the run is owed exactly as a seek's landing is. | ||
| 407 | + let mut owed = true; | ||
| 408 | + | ||
| 409 | + session.play(); | ||
| 410 | + let start = Instant::now(); | ||
| 411 | + let deadline = start + Duration::from_secs_f64(secs); | ||
| 412 | + let mut last_frame = start; | ||
| 413 | + let mut next_seek = start + PLAYLOOP_SEEK_GAP; | ||
| 414 | + while Instant::now() < deadline { | ||
| 415 | + session.tick(); | ||
| 416 | + let target = session.now() * fps; | ||
| 417 | + let mut newest = None; | ||
| 418 | + while session.is_playing() || owed { | ||
| 419 | + let frame = match held.take() { | ||
| 420 | + Some(frame) => frame, | ||
| 421 | + None => match session.try_frame() { | ||
| 422 | + // Timed here and only here: a frame taken back out of | ||
| 423 | + // `held` cost no decode, and counting it would report a | ||
| 424 | + // zero gap for a frame nobody waited for. | ||
| 425 | + Some(frame) => { | ||
| 426 | + let now = Instant::now(); | ||
| 427 | + gaps.push((now - last_frame).as_secs_f64() * 1000.0); | ||
| 428 | + last_frame = now; | ||
| 429 | + frame | ||
| 430 | + } | ||
| 431 | + None => break, | ||
| 432 | + }, | ||
| 433 | + }; | ||
| 434 | + if f64::from(frame.index) <= target { | ||
| 435 | + dropped += u64::from(newest.is_some()); | ||
| 436 | + newest = Some(frame); | ||
| 437 | + } else { | ||
| 438 | + held = Some(frame); | ||
| 439 | + break; | ||
| 440 | + } | ||
| 441 | + } | ||
| 442 | + let late = newest | ||
| 443 | + .as_ref() | ||
| 444 | + .map_or(0.0, |f| (target - f64::from(f.index)) / fps); | ||
| 445 | + if newest.is_some() { | ||
| 446 | + shown += 1; | ||
| 447 | + owed = false; | ||
| 448 | + } | ||
| 449 | + if !owed | ||
| 450 | + && session.is_playing() | ||
| 451 | + && late > LATE_RESYNC | ||
| 452 | + && last_resync.is_none_or(|t| t.elapsed() >= RESYNC_GAP) | ||
| 453 | + { | ||
| 454 | + session.resync_picture(); | ||
| 455 | + held = None; | ||
| 456 | + last_resync = Some(Instant::now()); | ||
| 457 | + resyncs += 1; | ||
| 458 | + } | ||
| 459 | + // End of stream inside a five-second stretch is the same jump early: | ||
| 460 | + // the loop is here to keep playing, not to stop at whatever it landed | ||
| 461 | + // near. | ||
| 462 | + if Instant::now() >= next_seek || session.is_eos() { | ||
| 463 | + session.seek(rng.next() * duration * 0.95); | ||
| 464 | + held = None; | ||
| 465 | + owed = true; | ||
| 466 | + seeks += 1; | ||
| 467 | + next_seek = Instant::now() + PLAYLOOP_SEEK_GAP; | ||
| 468 | + } | ||
| 469 | + std::thread::sleep(Duration::from_millis(1)); | ||
| 470 | + } | ||
| 471 | + session.pause(); | ||
| 472 | + | ||
| 473 | + let elapsed = start.elapsed().as_secs_f64(); | ||
| 474 | + let backend = session.decode_backend().label(); | ||
| 475 | + let audio = session.audio_underruns(); | ||
| 476 | + row( | ||
| 477 | + path, | ||
| 478 | + "playloop_frame_gap", | ||
| 479 | + "ms", | ||
| 480 | + &gaps, | ||
| 481 | + &format!( | ||
| 482 | + "backend {backend}, p99 {:.2}ms, {shown} shown, {dropped} dropped, \ | ||
| 483 | + {seeks} seeks in {elapsed:.0}s, seed {seed}", | ||
| 484 | + pct(&gaps, 0.99) | ||
| 485 | + ), | ||
| 486 | + ); | ||
| 487 | + row( | ||
| 488 | + path, | ||
| 489 | + "playloop_underruns", | ||
| 490 | + "count", | ||
| 491 | + &[audio.map_or(0, |(n, _)| n) as f64], | ||
| 492 | + &match audio { | ||
| 493 | + None => "no audio device".into(), | ||
| 494 | + Some((_, last)) => format!( | ||
| 495 | + "backend {backend}, {}", | ||
| 496 | + last.map_or_else(|| "none".into(), |t| format!("last at {t:.1}s device")) | ||
| 497 | + ), | ||
| 498 | + }, | ||
| 499 | + ); | ||
| 500 | + row( | ||
| 501 | + path, | ||
| 502 | + "playloop_restarts", | ||
| 503 | + "count", | ||
| 504 | + &[session.restarts() as f64], | ||
| 505 | + &format!("backend {backend}, {resyncs} late-picture resyncs, {seeks} seeks"), | ||
| 506 | + ); | ||
| 507 | +} | ||
| 508 | + | ||
| 253 | // ---------------------------------------------------------------- waveform | 509 | // ---------------------------------------------------------------- waveform |
| 254 | 510 | ||
| 255 | /// What a lane waits for before it has an envelope: one whole | 511 | /// What a lane waits for before it has an envelope: one whole |
crates/engine/src/ao.rsmodified+17 -0
| @@ -20,6 +20,7 @@ struct Plugin { | |||
| 20 | set_active: unsafe extern "C" fn(*mut c_void, u32) -> i32, | 20 | set_active: unsafe extern "C" fn(*mut c_void, u32) -> i32, |
| 21 | set_volume: unsafe extern "C" fn(*mut c_void, f32) -> i32, | 21 | set_volume: unsafe extern "C" fn(*mut c_void, f32) -> i32, |
| 22 | flush: unsafe extern "C" fn(*mut c_void) -> i32, | 22 | flush: unsafe extern "C" fn(*mut c_void) -> i32, |
| 23 | + underruns: unsafe extern "C" fn(*mut c_void, *mut i64) -> i64, | ||
| 23 | close: unsafe extern "C" fn(*mut c_void), | 24 | close: unsafe extern "C" fn(*mut c_void), |
| 24 | // Never dropped (lives in a static), so the fn pointers above stay valid. | 25 | // Never dropped (lives in a static), so the fn pointers above stay valid. |
| 25 | _lib: Library, | 26 | _lib: Library, |
| @@ -63,6 +64,11 @@ fn load() -> Option<Plugin> { | |||
| 63 | // with no sound at all, which at least says so. | 64 | // with no sound at all, which at least says so. |
| 64 | set_volume: *lib.get(b"ao_set_volume\0").ok()?, | 65 | set_volume: *lib.get(b"ao_set_volume\0").ok()?, |
| 65 | flush: *lib.get(b"ao_flush\0").ok()?, | 66 | flush: *lib.get(b"ao_flush\0").ok()?, |
| 67 | + // Required on the same terms as the two above: the plugin | ||
| 68 | + // ships from this build, and a measurement that silently | ||
| 69 | + // reads zero underruns is worse than a run that says the | ||
| 70 | + // plugin is the wrong one. | ||
| 71 | + underruns: *lib.get(b"ao_underruns\0").ok()?, | ||
| 66 | close: *lib.get(b"ao_close\0").ok()?, | 72 | close: *lib.get(b"ao_close\0").ok()?, |
| 67 | _lib: lib, | 73 | _lib: lib, |
| 68 | }) | 74 | }) |
| @@ -143,6 +149,17 @@ impl AoSession { | |||
| 143 | // SAFETY: `handle` came from `ao_open` and is still open. | 149 | // SAFETY: `handle` came from `ao_open` and is still open. |
| 144 | unsafe { (self.plugin.flush)(self.handle) == 0 } | 150 | unsafe { (self.plugin.flush)(self.handle) == 0 } |
| 145 | } | 151 | } |
| 152 | + | ||
| 153 | + /// Starved callbacks so far, and the device position (samples per channel) | ||
| 154 | + /// the last of them was seen at -- `None` for a stream that has never run | ||
| 155 | + /// dry. Two atomic loads inside the plugin, so it is cheap enough to poll | ||
| 156 | + /// and it never touches the RT thread's path. | ||
| 157 | + pub fn underruns(&self) -> (u64, Option<i64>) { | ||
| 158 | + let mut last = -1i64; | ||
| 159 | + // SAFETY: `handle` came from `ao_open`, and `last` is a live i64 of ours. | ||
| 160 | + let count = unsafe { (self.plugin.underruns)(self.handle, &raw mut last) }; | ||
| 161 | + (count.max(0) as u64, (last >= 0).then_some(last)) | ||
| 162 | + } | ||
| 146 | } | 163 | } |
| 147 | 164 | ||
| 148 | impl Drop for AoSession { | 165 | impl Drop for AoSession { |
crates/engine/src/playback.rsmodified+31 -0
| @@ -250,6 +250,12 @@ pub struct PlaybackSession { | |||
| 250 | /// | 250 | /// |
| 251 | /// [`retire`]: PlaybackSession::retire | 251 | /// [`retire`]: PlaybackSession::retire |
| 252 | retired: Vec<Worker>, | 252 | retired: Vec<Worker>, |
| 253 | + /// Picture workers that replaced another one, i.e. every restart the | ||
| 254 | + /// session's first worker did not cost: a seek, a resync, a clip boundary. | ||
| 255 | + /// Each carries a demuxer reopen and a VA-API init, so this is what a | ||
| 256 | + /// playback measurement counts to say how often the picture was thrown away | ||
| 257 | + /// ([`restarts`](Self::restarts)). | ||
| 258 | + restarts: u64, | ||
| 253 | clock: PlaybackClock, | 259 | clock: PlaybackClock, |
| 254 | audio: Option<Audio>, | 260 | audio: Option<Audio>, |
| 255 | /// Why this timeline is silent, when the file itself is not: an audio track | 261 | /// Why this timeline is silent, when the file itself is not: an audio track |
| @@ -411,6 +417,7 @@ impl PlaybackSession { | |||
| 411 | worker: stream.worker, | 417 | worker: stream.worker, |
| 412 | backend: stream.backend, | 418 | backend: stream.backend, |
| 413 | retired: Vec::new(), | 419 | retired: Vec::new(), |
| 420 | + restarts: 0, | ||
| 414 | clock: PlaybackClock::new(source), | 421 | clock: PlaybackClock::new(source), |
| 415 | audio, | 422 | audio, |
| 416 | audio_disabled, | 423 | audio_disabled, |
| @@ -515,6 +522,7 @@ impl PlaybackSession { | |||
| 515 | worker: stream.worker, | 522 | worker: stream.worker, |
| 516 | backend: stream.backend, | 523 | backend: stream.backend, |
| 517 | retired: Vec::new(), | 524 | retired: Vec::new(), |
| 525 | + restarts: 0, | ||
| 518 | // The song keeps the clock, as a video's own sound does -- and wall | 526 | // The song keeps the clock, as a video's own sound does -- and wall |
| 519 | // time keeps it on a machine with no device, where the picture | 527 | // time keeps it on a machine with no device, where the picture |
| 520 | // (black) still has to move at some rate. | 528 | // (black) still has to move at some rate. |
| @@ -595,6 +603,7 @@ impl PlaybackSession { | |||
| 595 | worker: stream.worker, | 603 | worker: stream.worker, |
| 596 | backend: stream.backend, | 604 | backend: stream.backend, |
| 597 | retired: Vec::new(), | 605 | retired: Vec::new(), |
| 606 | + restarts: 0, | ||
| 598 | clock: PlaybackClock::new(ClockSource::Wall), | 607 | clock: PlaybackClock::new(ClockSource::Wall), |
| 599 | audio: None, | 608 | audio: None, |
| 600 | audio_disabled: None, | 609 | audio_disabled: None, |
| @@ -884,6 +893,7 @@ impl PlaybackSession { | |||
| 884 | worker: stream.worker, | 893 | worker: stream.worker, |
| 885 | backend: stream.backend, | 894 | backend: stream.backend, |
| 886 | retired: Vec::new(), | 895 | retired: Vec::new(), |
| 896 | + restarts: 0, | ||
| 887 | clock: PlaybackClock::new(match audio { | 897 | clock: PlaybackClock::new(match audio { |
| 888 | Some(_) => ClockSource::Audio, | 898 | Some(_) => ClockSource::Audio, |
| 889 | None => ClockSource::Wall, | 899 | None => ClockSource::Wall, |
| @@ -1230,11 +1240,32 @@ impl PlaybackSession { | |||
| 1230 | /// (plus whatever VA-API init it was inside), so a scrub reaps last seek's | 1240 | /// (plus whatever VA-API init it was inside), so a scrub reaps last seek's |
| 1231 | /// worker on this seek and the list stays a handful long. Nothing waits. | 1241 | /// worker on this seek and the list stays a handful long. Nothing waits. |
| 1232 | fn retire(&mut self, replacement: Worker) { | 1242 | fn retire(&mut self, replacement: Worker) { |
| 1243 | + self.restarts += 1; | ||
| 1233 | self.retired | 1244 | self.retired |
| 1234 | .push(std::mem::replace(&mut self.worker, replacement)); | 1245 | .push(std::mem::replace(&mut self.worker, replacement)); |
| 1235 | self.retired.retain(|w| !w.is_finished()); | 1246 | self.retired.retain(|w| !w.is_finished()); |
| 1236 | } | 1247 | } |
| 1237 | 1248 | ||
| 1249 | + /// Picture restarts so far; see [`restarts`](Self::restarts). The one place | ||
| 1250 | + /// a worker is ever replaced counts them, so a seek, a resync and a clip | ||
| 1251 | + /// boundary all land here and a measurement need not guess which it saw. | ||
| 1252 | + #[doc(hidden)] | ||
| 1253 | + pub fn restarts(&self) -> u64 { | ||
| 1254 | + self.restarts | ||
| 1255 | + } | ||
| 1256 | + | ||
| 1257 | + /// Starved audio callbacks since the device opened, and how far into the | ||
| 1258 | + /// device's own playback (seconds) the last of them was -- `None` for a | ||
| 1259 | + /// session with no device at all. The counter the plugin prints on drop, | ||
| 1260 | + /// readable while the session runs: read it either side of a seek and the | ||
| 1261 | + /// difference is what that seek cost the ear. | ||
| 1262 | + #[doc(hidden)] | ||
| 1263 | + pub fn audio_underruns(&self) -> Option<(u64, Option<f64>)> { | ||
| 1264 | + let audio = self.audio.as_ref()?; | ||
| 1265 | + let (count, last) = audio.ao.lock().unwrap().underruns(); | ||
| 1266 | + Some((count, last.map(|p| p as f64 / f64::from(audio.sample_rate)))) | ||
| 1267 | + } | ||
| 1268 | + | ||
| 1238 | /// How many threads this session still has running of its own: the decode | 1269 | /// How many threads this session still has running of its own: the decode |
| 1239 | /// worker, every retired one that has not returned yet, and the audio | 1270 | /// worker, every retired one that has not returned yet, and the audio |
| 1240 | /// feeders still in the air. One for a session playing along quietly. | 1271 | /// feeders still in the air. One for a session playing along quietly. |
scripts/bench.shmodified+15 -2
| @@ -19,7 +19,10 @@ | |||
| 19 | # before the measurement -- no root, nothing else on the machine evicted, | 19 | # before the measurement -- no root, nothing else on the machine evicted, |
| 20 | # and advisory, so it is the optimistic end of cold. | 20 | # and advisory, so it is the optimistic end of cold. |
| 21 | # * warm = the same call repeated straight after, cache as the cold run left it. | 21 | # * warm = the same call repeated straight after, cache as the cold run left it. |
| 22 | -# * medians of 5 for open and seek, 20 steps for a scrub, and for export as | 22 | +# * medians of 5 for open and seek, 50 seeded random seeks for a seek storm, |
| 23 | +# $BENCH_PLAYLOOP_SECS (30) of playing with a jump every 5 s for a play | ||
| 24 | +# loop -- both drawn from $BENCH_SEED (1), so a rerun seeks the same | ||
| 25 | +# places -- 20 steps for a scrub, and for export as | ||
| 23 | # many reps as $BENCH_EXPORT_CAP seconds leave room for (at least one, | 26 | # many reps as $BENCH_EXPORT_CAP seconds leave room for (at least one, |
| 24 | # which is then marked CAPPED if it did not finish). | 27 | # which is then marked CAPPED if it did not finish). |
| 25 | # * every metric runs as its own process: a decoder that panics costs one | 28 | # * every metric runs as its own process: a decoder that panics costs one |
| @@ -41,7 +44,13 @@ LOG="$OUT_DIR/bench.log" | |||
| 41 | # Absolute, because $CARGO_TARGET_DIR may already be one and the plugin path | 44 | # Absolute, because $CARGO_TARGET_DIR may already be one and the plugin path |
| 42 | # below must not become "$PWD/$HOME/...". | 45 | # below must not become "$PWD/$HOME/...". |
| 43 | TARGET=$(realpath -m "${CARGO_TARGET_DIR:-target}") | 46 | TARGET=$(realpath -m "${CARGO_TARGET_DIR:-target}") |
| 44 | -cargo build --release -p engine -p engine-hw --example bench || exit 1 | 47 | +# The plugins are their own build: `--example` selects example targets in every |
| 48 | +# package it is given, and a cdylib is not one, so `-p engine-hw --example | ||
| 49 | +# bench` built no plugin at all and every run measured software while the line | ||
| 50 | +# below said otherwise. engine-audio is here for the same reason -- the play | ||
| 51 | +# loop's underruns come from the device, and with no plugin there is no device. | ||
| 52 | +cargo build --release -p engine-hw -p engine-audio || exit 1 | ||
| 53 | +cargo build --release -p engine --example bench || exit 1 | ||
| 45 | BENCH="$TARGET/release/examples/bench" | 54 | BENCH="$TARGET/release/examples/bench" |
| 46 | # The plugin is looked for beside the running executable, and an example binary | 55 | # The plugin is looked for beside the running executable, and an example binary |
| 47 | # lives one directory below the plugin: without this, hardware decode and | 56 | # lives one directory below the plugin: without this, hardware decode and |
| @@ -98,6 +107,10 @@ for file in "${files[@]}"; do | |||
| 98 | run 1800 "seek_ttff_${t}s" "$file" seek "$t" | 107 | run 1800 "seek_ttff_${t}s" "$file" seek "$t" |
| 99 | done | 108 | done |
| 100 | run 3600 scrub "$file" scrub | 109 | run 3600 scrub "$file" scrub |
| 110 | + # The two random metrics: same seed both sides of a change, or the "before" | ||
| 111 | + # and the "after" are different seeks and the comparison means nothing. | ||
| 112 | + run 3600 seekstorm "$file" seekstorm "${BENCH_SEED:-1}" | ||
| 113 | + run 1800 playloop "$file" playloop "${BENCH_PLAYLOOP_SECS:-30}" "${BENCH_SEED:-1}" | ||
| 101 | for seat in h264sw h264hw av1 hevc hevchw; do | 114 | for seat in h264sw h264hw av1 hevc hevchw; do |
| 102 | run "$export_limit" "export_fps_$seat" "$file" export "$seat" "$OUT_DIR" | 115 | run "$export_limit" "export_fps_$seat" "$file" export "$seat" "$OUT_DIR" |
| 103 | done | 116 | done |