The queue a file opens with, and the driver a parked worker holds
Browse files at this commit7985bd573d2b4cce4c8f79e6cf1bd5ead91597bbParent: dd2001c- fix
- the queue a file opens with, and the driver a parked worker holds
4 changed files +207 -32
- crates/engine/src/decode.rs +50 -7
- crates/engine/src/playback.rs +11 -4
- crates/engine/src/scale.rs +32 -11
- crates/engine/tests/playback.rs +114 -10
crates/engine/src/decode.rsmodified+50 -7
| @@ -4,7 +4,7 @@ | ||
| 4 | 4 | use std::path::{Path, PathBuf}; |
| 5 | 5 | use std::sync::Arc; |
| 6 | 6 | use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU32, AtomicU64, Ordering}; |
| 7 | -use std::sync::mpsc::{Receiver, SyncSender, sync_channel}; | |
| 7 | +use std::sync::mpsc::{Receiver, RecvTimeoutError, SyncSender, sync_channel}; | |
| 8 | 8 | use std::thread; |
| 9 | 9 | |
| 10 | 10 | use rusty_h264::Decoder; |
| @@ -670,7 +670,18 @@ fn span_worker( | ||
| 670 | 670 | canvas: Composer, |
| 671 | 671 | tone: tonemap::Preset, |
| 672 | 672 | ) -> FrameStream { |
| 673 | - let (tx, rx) = sync_channel(canvas.queue_depth()); | |
| 673 | + // The depth is the size of the pictures this worker will *emit*, which for a | |
| 674 | + // pass-through canvas is the stream's own -- and the sync opener has already | |
| 675 | + // read that on the caller's thread. Asking the canvas alone is how the file | |
| 676 | + // door came up with 2: every session opens pass-through (a freshly opened | |
| 677 | + // file *is* the project resolution), so a whole file would play at the | |
| 678 | + // decode-ahead this engine had before there was one, until the first seek | |
| 679 | + // built a real canvas. | |
| 680 | + let depth = match (&opened, canvas.places_nothing()) { | |
| 681 | + (Some(source), true) => crate::scale::queue_depth(source.meta.width, source.meta.height), | |
| 682 | + _ => canvas.queue_depth(), | |
| 683 | + }; | |
| 684 | + let (tx, rx) = sync_channel(depth); | |
| 674 | 685 | let cancel = Arc::new(AtomicBool::new(false)); |
| 675 | 686 | // Written by the worker the moment it knows, so a caller reading it sees |
| 676 | 687 | // what opened rather than what was hoped for -- and kept across the spans |
| @@ -714,12 +725,38 @@ fn span_worker( | ||
| 714 | 725 | if !abort.hit() { |
| 715 | 726 | run_span(&worker_path, &mut source, cmd, &abort, &worker_backend); |
| 716 | 727 | } |
| 717 | - // The session dropped the command channel: this worker is | |
| 718 | - // retired (or was detached), so the file, the decoder and the | |
| 719 | - // VA-API session it holds go now -- before Mesa's `atexit`. | |
| 720 | - match commands.recv() { | |
| 728 | + // Parked between spans. A seek and a clip boundary arrive in | |
| 729 | + // milliseconds and find the decoder still open, which is the | |
| 730 | + // whole point of this thread -- but a session nobody comes back | |
| 731 | + // to (the timeline played out, the window was left alone) must | |
| 732 | + // not sit on the driver: it would hold a live libva thread into | |
| 733 | + // whatever exit path the process takes, which is the SIGSEGV in | |
| 734 | + // Mesa's `atexit` the retired pool exists to prevent, and | |
| 735 | + // holding it *while idle* would widen that from "quit during a | |
| 736 | + // decode" to "quit any time after opening a file". | |
| 737 | + // | |
| 738 | + // So the wait is in two halves: the fast one keeps everything, | |
| 739 | + // and past [`IDLE`] the hardware session is closed. The demuxer | |
| 740 | + // stays -- it is a file handle and an index, not driver state, | |
| 741 | + // and rebuilding it is what costs seconds on a big Matroska -- | |
| 742 | + // so the reseek after a long pause pays one VA-API init and | |
| 743 | + // nothing else. | |
| 744 | + match commands.recv_timeout(IDLE) { | |
| 721 | 745 | Ok(next) => cmd = next, |
| 722 | - Err(_) => return, | |
| 746 | + Err(RecvTimeoutError::Timeout) => { | |
| 747 | + if let Some(source) = &mut source | |
| 748 | + && source.hw.take().is_some() | |
| 749 | + { | |
| 750 | + eprintln!("decode worker idle: hardware session closed"); | |
| 751 | + } | |
| 752 | + // The session dropped the command channel: this worker | |
| 753 | + // is retired (or was detached), so the file goes now. | |
| 754 | + match commands.recv() { | |
| 755 | + Ok(next) => cmd = next, | |
| 756 | + Err(_) => return, | |
| 757 | + } | |
| 758 | + } | |
| 759 | + Err(RecvTimeoutError::Disconnected) => return, | |
| 723 | 760 | } |
| 724 | 761 | } |
| 725 | 762 | }) |
| @@ -741,6 +778,12 @@ fn span_worker( | ||
| 741 | 778 | } |
| 742 | 779 | } |
| 743 | 780 | |
| 781 | +/// How long a parked worker keeps its hardware session before closing it. Long | |
| 782 | +/// enough that a seek, a scrub step and a clip boundary all find the decoder | |
| 783 | +/// where they left it; short enough that a session left alone is not holding | |
| 784 | +/// libva when the process exits. | |
| 785 | +const IDLE: std::time::Duration = std::time::Duration::from_secs(2); | |
| 786 | + | |
| 744 | 787 | /// How many pictures in a row a worker may drop for being late before it hands |
| 745 | 788 | /// one over regardless. The policy needs a floor of its own: a machine that |
| 746 | 789 | /// cannot decode a file in real time is late on *every* picture, and dropping |
crates/engine/src/playback.rsmodified+11 -4
| @@ -1491,8 +1491,9 @@ impl PlaybackSession { | ||
| 1491 | 1491 | // [`decode_backend`](Self::decode_backend) describing a worker that |
| 1492 | 1492 | // is no longer feeding anything). A dead receiver instead, which is |
| 1493 | 1493 | // what carries the session on to the next span. The old worker stays |
| 1494 | - // parked in `self.worker` where the caller already cancelled it; the | |
| 1495 | - // next span retires it. | |
| 1494 | + // parked in `self.worker`, where the caller has already abandoned | |
| 1495 | + // the span it was decoding ([`Worker::abandon`]) without ending the | |
| 1496 | + // thread; the next span reseeks it or retires it. | |
| 1496 | 1497 | self.frames = std::sync::mpsc::channel().1; |
| 1497 | 1498 | self.backend = BackendCell::new(Backend::Gap); |
| 1498 | 1499 | self.span = span; |
| @@ -2608,8 +2609,14 @@ impl PlaybackSession { | ||
| 2608 | 2609 | /// A front-end that turns this on was dropping those very frames itself, one |
| 2609 | 2610 | /// repaint later (`Player::pump` takes everything due and shows the last): |
| 2610 | 2611 | /// what changes is where the work stops, and therefore how quickly a decoder |
| 2611 | - /// that fell behind catches up -- without the restart-every-two-seconds that | |
| 2612 | - /// was the only way back before ([`Self::resync_picture`]). | |
| 2612 | + /// that fell behind catches up. | |
| 2613 | + /// | |
| 2614 | + /// It does not replace [`resync_picture`](Self::resync_picture): both | |
| 2615 | + /// mechanisms are live and this one is the first line. It catches up without | |
| 2616 | + /// restarting anything, which is why the front-end's resync -- a picture | |
| 2617 | + /// restart, once per `RESYNC_GAP` -- now fires only where dropping was not | |
| 2618 | + /// enough (a decoder so far behind that even one picture in nine | |
| 2619 | + /// ([`crate::decode`]'s `LATE_RUN`) cannot close the gap). | |
| 2613 | 2620 | pub fn drop_late_pictures(&mut self, on: bool) { |
| 2614 | 2621 | self.drop_late = on; |
| 2615 | 2622 | } |
crates/engine/src/scale.rsmodified+32 -11
| @@ -345,6 +345,24 @@ pub fn compose_i420( | ||
| 345 | 345 | /// lift the black frame around the picture. Callers therefore grade the source |
| 346 | 346 | /// planes and place the result; the bars stay exactly [`black_i420`]. |
| 347 | 347 | /// |
| 348 | +/// How many `width` x `height` BGRA pictures a decode worker may keep ahead of | |
| 349 | +/// its consumer: ~96 MB of them, so the queue is a memory budget rather than a | |
| 350 | +/// frame count -- 16 at 720p (the ceiling), 12 at 1080p, 3 at 3840x2160, 2 at | |
| 351 | +/// 4096x2160 (the floor), all measured. A worker holds one more than this in its | |
| 352 | +/// hand, so a burst off a full queue is `queue_depth + 1`. | |
| 353 | +/// | |
| 354 | +/// The floor of 2 is the bound this engine ran on everywhere before there was | |
| 355 | +/// any decode-ahead; the ceiling keeps a small picture from queueing a second of | |
| 356 | +/// video the consumer would have to walk through after a seek. | |
| 357 | +pub(crate) fn queue_depth(width: u32, height: u32) -> usize { | |
| 358 | + const BUDGET: usize = 96 << 20; | |
| 359 | + let bytes = width as usize * height as usize * 4; | |
| 360 | + if bytes == 0 { | |
| 361 | + return 2; | |
| 362 | + } | |
| 363 | + (BUDGET / bytes).clamp(2, 16) | |
| 364 | +} | |
| 365 | + | |
| 348 | 366 | /// A canvas of the picture's own size is a pass-through: [`place`](Composer::place) |
| 349 | 367 | /// hands the caller's own planes straight back, allocates nothing and touches no |
| 350 | 368 | /// byte, which is what keeps a project at its media's resolution the byte-for-byte |
| @@ -386,22 +404,25 @@ impl Composer { | ||
| 386 | 404 | Self::new(0, 0, FitPolicy::Fit) |
| 387 | 405 | } |
| 388 | 406 | |
| 407 | + /// Whether this canvas is the one that places nothing | |
| 408 | + /// ([`passthrough`](Self::passthrough)) -- asked without a picture in hand, | |
| 409 | + /// unlike [`is_passthrough`](Self::is_passthrough), because the caller that | |
| 410 | + /// needs it is sizing a queue before anything has been decoded. | |
| 411 | + pub(crate) fn places_nothing(&self) -> bool { | |
| 412 | + self.width == 0 || self.height == 0 | |
| 413 | + } | |
| 414 | + | |
| 389 | 415 | /// How many decoded pictures a worker over this canvas may keep ahead of |
| 390 | 416 | /// its consumer: a budget in *bytes*, so a 4K project runs a shallower queue |
| 391 | 417 | /// than a 1080p one instead of the same number of far bigger frames. |
| 392 | 418 | /// |
| 393 | - /// The floor is 2 -- the bound this engine ran on everywhere before there | |
| 394 | - /// was a decode-ahead at all -- and it is also what a pass-through canvas | |
| 395 | - /// gets, since that one does not know what size the pictures will be (they | |
| 396 | - /// are the source's) and its callers pull frame by frame anyway. | |
| 419 | + /// A **pass-through** canvas has no size of its own -- the pictures come out | |
| 420 | + /// at the source's -- so it cannot answer, and the caller that knows the | |
| 421 | + /// stream asks [`queue_depth`] with those dimensions instead. Answering 2 | |
| 422 | + /// here would be the pre-decode-ahead bound, which is exactly the bug this | |
| 423 | + /// pair exists to keep out of the file-open path. | |
| 397 | 424 | pub(crate) fn queue_depth(&self) -> usize { |
| 398 | - /// ~96 MB of BGRA in flight: eleven 1080p pictures, two 4K ones. | |
| 399 | - const BUDGET: usize = 96 << 20; | |
| 400 | - let bytes = self.width as usize * self.height as usize * 4; | |
| 401 | - if bytes == 0 { | |
| 402 | - return 2; | |
| 403 | - } | |
| 404 | - (BUDGET / bytes).clamp(2, 16) | |
| 425 | + queue_depth(self.width, self.height) | |
| 405 | 426 | } |
| 406 | 427 | |
| 407 | 428 | /// Whether a `src_w` x `src_h` picture is already the canvas, i.e. this |
crates/engine/tests/playback.rsmodified+114 -10
| @@ -47,16 +47,16 @@ fn pump(session: &mut PlaybackSession, last_index: &mut Option<u32>) { | ||
| 47 | 47 | let target = session.now() * session.meta().frame_rate; |
| 48 | 48 | while let Some(frame) = session.try_frame() { |
| 49 | 49 | if let Some(previous) = *last_index { |
| 50 | - // Forwards, never twice and never backwards -- but not necessarily | |
| 51 | - // one at a time: a worker whose pictures have fallen behind the | |
| 52 | - // playhead drops them where they are cheap to drop rather than | |
| 53 | - // converting and queueing what nobody can be shown | |
| 54 | - // (`PlaybackSession::publish_playhead`), so a decoder that cannot | |
| 55 | - // keep real time skips instead of falling further behind. | |
| 56 | - assert!( | |
| 57 | - frame.index > previous, | |
| 58 | - "frames must arrive in index order: {} after {previous}", | |
| 59 | - frame.index | |
| 50 | + // One at a time, in order. Every session here is a *pull* consumer | |
| 51 | + // -- `open` leaves `drop_late_pictures` off -- and such a caller is | |
| 52 | + // owed every frame of the range it asked for, which is the contract | |
| 53 | + // an export and the file-level API rest on. Only a session told it | |
| 54 | + // is being watched in real time may skip, and the two tests that | |
| 55 | + // turn that on take their frames through `next_index` instead. | |
| 56 | + assert_eq!( | |
| 57 | + frame.index, | |
| 58 | + previous + 1, | |
| 59 | + "frames must arrive in index order" | |
| 60 | 60 | ); |
| 61 | 61 | } |
| 62 | 62 | *last_index = Some(frame.index); |
| @@ -1542,3 +1542,107 @@ fn a_reseek_decodes_the_same_picture_a_fresh_decoder_does() { | ||
| 1542 | 1542 | ); |
| 1543 | 1543 | } |
| 1544 | 1544 | } |
| 1545 | + | |
| 1546 | +/// What the drop policy must never do: thin a picture the decoder was keeping up | |
| 1547 | +/// with. `pump`'s own contiguity assert covers every *pull* consumer above; | |
| 1548 | +/// nothing there bounds what a **watched** session delivers, and a one-in-N | |
| 1549 | +/// regression inside the worker would pass the whole suite otherwise. | |
| 1550 | +/// | |
| 1551 | +/// The fixture is the smallest one here (320x180) so the question can be asked | |
| 1552 | +/// on a debug build at the file's own rate -- no retime, because a retimed | |
| 1553 | +/// timeline legitimately shows only every n-th source frame and the sharp half | |
| 1554 | +/// of this test is that the indices arrive one at a time. A box too slow even | |
| 1555 | +/// for this says so and stops: thinning the picture there is the policy working | |
| 1556 | +/// (`LATE_RUN`), not a regression. | |
| 1557 | +#[test] | |
| 1558 | +fn a_watched_session_keeps_every_picture_its_decoder_keeps_up_with() { | |
| 1559 | + let path = asset("test_speed_sync.mp4"); | |
| 1560 | + | |
| 1561 | + // What this box decodes, flat out, with nothing dropped: frames per second. | |
| 1562 | + let mut measure = open(&path); | |
| 1563 | + let fps = measure.meta().frame_rate; | |
| 1564 | + measure.play(); | |
| 1565 | + let mut decoded = 0u32; | |
| 1566 | + let taken = Instant::now(); | |
| 1567 | + while taken.elapsed() < Duration::from_millis(500) && !measure.is_eos() { | |
| 1568 | + measure.tick(); | |
| 1569 | + while measure.try_frame().is_some() { | |
| 1570 | + decoded += 1; | |
| 1571 | + } | |
| 1572 | + sleep(Duration::from_millis(2)); | |
| 1573 | + } | |
| 1574 | + let capable = f64::from(decoded) / taken.elapsed().as_secs_f64(); | |
| 1575 | + drop(measure); | |
| 1576 | + eprintln!("this box decodes the fixture at {capable:.1} fps, which plays at {fps:.1}"); | |
| 1577 | + if capable < fps * 1.2 { | |
| 1578 | + eprintln!("SKIP: too slow to ask the question at all"); | |
| 1579 | + return; | |
| 1580 | + } | |
| 1581 | + | |
| 1582 | + // Watched, playing at its own rate, drained like a front-end that keeps up: | |
| 1583 | + // every picture is due when it arrives and none of them may be dropped. | |
| 1584 | + let mut session = open(&path); | |
| 1585 | + session.drop_late_pictures(true); | |
| 1586 | + session.play(); | |
| 1587 | + let mut delivered = 0u32; | |
| 1588 | + let mut last: Option<u32> = None; | |
| 1589 | + let watched = Instant::now(); | |
| 1590 | + while watched.elapsed() < Duration::from_millis(500) && !session.is_eos() { | |
| 1591 | + session.tick(); | |
| 1592 | + while let Some(frame) = session.try_frame() { | |
| 1593 | + delivered += 1; | |
| 1594 | + if let Some(previous) = last { | |
| 1595 | + assert_eq!( | |
| 1596 | + frame.index, | |
| 1597 | + previous + 1, | |
| 1598 | + "a picture was dropped while the decoder was keeping up" | |
| 1599 | + ); | |
| 1600 | + } | |
| 1601 | + last = Some(frame.index); | |
| 1602 | + } | |
| 1603 | + sleep(Duration::from_millis(2)); | |
| 1604 | + } | |
| 1605 | + // Frames the clock went over, which is what the timeline owed the screen. | |
| 1606 | + let passed = session.now() * fps; | |
| 1607 | + let density = f64::from(delivered) / passed.max(1.0); | |
| 1608 | + eprintln!("watched: {delivered} delivered over {passed:.1} frames of clock"); | |
| 1609 | + assert!( | |
| 1610 | + density >= 0.9, | |
| 1611 | + "the worker thinned a picture it was keeping up with: {delivered} of \ | |
| 1612 | + {passed:.1} frames ({density:.2}), decoder measured at {capable:.1} fps" | |
| 1613 | + ); | |
| 1614 | +} | |
| 1615 | + | |
| 1616 | +/// The decode-ahead a **freshly opened** file gets. Every session opens its first | |
| 1617 | +/// worker pass-through -- a file just opened *is* the project resolution -- and | |
| 1618 | +/// asking a pass-through canvas how deep to queue answers 2, the bound this | |
| 1619 | +/// engine had before there was any decode-ahead: the whole file would then play | |
| 1620 | +/// at that depth until the first seek built a real canvas. The depth is taken | |
| 1621 | +/// from the stream instead (`scale::queue_depth`), and this is where that is | |
| 1622 | +/// visible from outside: a paused session left alone fills its queue, and the | |
| 1623 | +/// burst that comes off it is the depth plus the picture in the worker's hand. | |
| 1624 | +/// | |
| 1625 | +/// 720p fixture: ~96 MB of BGRA is 16 pictures at that size (the ceiling), so | |
| 1626 | +/// the burst is 17 and the regression it guards against is a burst of 3. | |
| 1627 | +#[test] | |
| 1628 | +fn a_freshly_opened_file_queues_more_than_two_pictures() { | |
| 1629 | + let mut session = open(asset("test_baseline.mp4")); | |
| 1630 | + // Paused throughout: no seek, no play, nothing that would build a canvas. | |
| 1631 | + // The best of three attempts, because filling the queue is the decoder's own | |
| 1632 | + // work and this box shares itself with whatever else is running. | |
| 1633 | + let mut burst = 0; | |
| 1634 | + for _ in 0..3 { | |
| 1635 | + sleep(Duration::from_millis(1500)); | |
| 1636 | + let mut n = 0; | |
| 1637 | + while session.try_frame().is_some() { | |
| 1638 | + n += 1; | |
| 1639 | + } | |
| 1640 | + burst = burst.max(n); | |
| 1641 | + } | |
| 1642 | + eprintln!("burst off a freshly opened file: {burst} pictures"); | |
| 1643 | + assert!( | |
| 1644 | + burst > 8, | |
| 1645 | + "a freshly opened file queued {burst} pictures: the first worker is \ | |
| 1646 | + still sizing its queue from a pass-through canvas" | |
| 1647 | + ); | |
| 1648 | +} |