diff --git a/Cargo.toml b/Cargo.toml index e336592..06e1089 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -25,7 +25,16 @@ edition = "2024" # declared one, which fails every seek into an open-GOP Blu-ray # remux -- the gap is the *editor's*, made by restarting at a # random access point, so the patch fills it with the §8.2.5.2 -# non-existing frames the loop right below it already builds +# non-existing frames the loop right below it already builds. +# It also has no HEVC *encoder* at all in 0.0.6: the seven +# commits behind cros-codecs' own `hevc-vaapi-encoder` branch +# (`codec/h265/{nalu_writer,synthesizer}`, the VPS/SPS/PPS +# builders in `codec/h265/parser.rs`, `encoder/stateless/h265` +# with its predictor and VA-API backend, and the H.264 NALU +# writer's emulation-prevention fix that shares that code) are +# applied here verbatim -- upstream work carried early, not a +# local invention, and the H.265 half of what makes edith's +# HEVC export run on the GPU # rusty_aac - its *decoder* runs the direct O(N²) IMDCT with a `cos` call per # term (the fast path in the same file serves the encoder only), # which is 4x slower than real time for 5.1 and therefore not diff --git a/crates/engine-hw/src/lib.rs b/crates/engine-hw/src/lib.rs index d71266b..8ad361d 100644 --- a/crates/engine-hw/src/lib.rs +++ b/crates/engine-hw/src/lib.rs @@ -1,5 +1,5 @@ -//! VA-API decode (H.264, HEVC, VP9 and AV1) and encode (H.264, and AV1 where -//! the GPU has an entrypoint for it), shipped as a +//! VA-API decode (H.264, HEVC, VP9 and AV1) and encode (H.264 and HEVC, and AV1 +//! where the GPU has an entrypoint for it), shipped as a //! `dlopen`-able plugin so the main binary never gets a DT_NEEDED on //! libva/gbm/drm. Every entry point is //! `extern "C"`, catches unwinds and reports failure as a null pointer or a @@ -20,6 +20,7 @@ use cros_codecs::backend::vaapi::decoder::VaapiBackend; use cros_codecs::backend::vaapi::encoder::VaapiBackend as VaapiEncBackend; use cros_codecs::codec::av1::parser::Profile as Av1Profile; use cros_codecs::codec::h264::parser::{Level, Profile as H264Profile}; +use cros_codecs::codec::h265::parser::{Level as H265Level, Profile as H265Profile}; use cros_codecs::decoder::stateless::av1::Av1; use cros_codecs::decoder::stateless::h264::H264; use cros_codecs::decoder::stateless::h265::H265; @@ -28,8 +29,10 @@ use cros_codecs::decoder::stateless::{DecodeError, StatelessDecoder, StatelessVi use cros_codecs::decoder::{BlockingMode, DecodedHandle, DecoderEvent, StreamInfo}; use cros_codecs::encoder::av1::EncoderConfig as Av1Config; use cros_codecs::encoder::h264::EncoderConfig as H264Config; +use cros_codecs::encoder::h265::EncoderConfig as H265Config; use cros_codecs::encoder::stateless::av1::StatelessEncoder as Av1StatelessEncoder; use cros_codecs::encoder::stateless::h264::StatelessEncoder; +use cros_codecs::encoder::stateless::h265::StatelessEncoder as H265StatelessEncoder; use cros_codecs::encoder::{ FrameMetadata, PredictionStructure, RateControl, Tunings, VideoEncoder, }; @@ -98,6 +101,10 @@ type Av1Encoder = Av1StatelessEncoder< GenericDmaVideoFrame, VaapiEncBackend>, >; +type HevcEncoder = H265StatelessEncoder< + GenericDmaVideoFrame, + VaapiEncBackend>, +>; /// Ceiling on decode/drain iterations that make no progress. VA-API in blocking /// mode should always either hand back an event or accept input; this only @@ -608,8 +615,8 @@ pub unsafe extern "C" fn vh_close(session: *mut c_void) { /// What each codec needs of the driver before this plugin can claim it: the /// 8-bit decode profiles, the 10-bit ones, and the profile the *encoder* here -/// would open -- `None` for the two this plugin has no encoder for at all, so a -/// GPU with an HEVC or VP9 encode entrypoint is never reported as one edith can +/// would open -- `None` for the one this plugin has no encoder for at all, so a +/// GPU with a VP9 encode entrypoint is never reported as one edith can /// reach. The encode profiles are the very ones [`EncSession::open_codec`] /// asks for, which is what keeps this a description of the plugin rather than a /// second opinion about it. @@ -628,7 +635,11 @@ const CAP_TABLE: [(u32, &[VAProfile::Type], &[VAProfile::Type], Option>, - /// H.264 only: the byte the driver leaves at zero is a *NAL* header, and an - /// AV1 temporal unit has no such thing. - h264: bool, + /// Which codec the open picked, kept because one thing past it still + /// differs: the H.264 driver leaves a *NAL* header byte at zero, and + /// neither an HEVC access unit nor an AV1 temporal unit has that one. + codec: EncCodec, /// Owns the DRM node the buffer object below was allocated from. _gbm: gbm::Device, frame: GenericDmaVideoFrame, @@ -786,9 +799,18 @@ struct EncSession { out: Vec, } +/// Which codec an [`EncSession`] was opened for. Decided once, at the open, the +/// way the H.264 seat's dimensions are -- everything after it is one trait. +#[derive(Clone, Copy, PartialEq, Eq)] +enum EncCodec { + H264, + Hevc, + Av1, +} + impl EncSession { fn open(width: u32, height: u32, fps_num: u32, fps_den: u32, bitrate: u64) -> Option { - Self::open_codec(width, height, fps_num, fps_den, bitrate, false) + Self::open_codec(width, height, fps_num, fps_den, bitrate, EncCodec::H264) } fn open_codec( @@ -797,13 +819,21 @@ impl EncSession { fps_num: u32, fps_den: u32, bitrate: u64, - av1: bool, + codec: EncCodec, ) -> Option { // NV12 chroma is half resolution, so odd dimensions have no packing; // and radeonsi refuses encode contexts below 64x64 (measured). if width < 64 || height < 64 || width % 2 != 0 || height % 2 != 0 { return None; } + // The HEVC entrypoint's own floor, which is a different number: the same + // driver that takes a 128x128 H.264 context answers `VaError(19)` to an + // HEVC one below 384x384 (measured 2026-08-13 on radeonsi). Said here so + // a small export falls back to software at the open rather than through + // a driver refusal, and so the C ABI never claims a seat it has not got. + if codec == EncCodec::Hevc && (width < 384 || height < 384) { + return None; + } if fps_num == 0 || fps_den == 0 || bitrate == 0 { return None; } @@ -813,9 +843,10 @@ impl EncSession { height: align16(height), }; let framerate = ((fps_num as f64 / fps_den as f64).round() as i64).clamp(1, 240) as u32; - let profile = match av1 { - true => VAProfile::VAProfileAV1Profile0, - false => VAProfile::VAProfileH264Main, + let profile = match codec { + EncCodec::Av1 => VAProfile::VAProfileAV1Profile0, + EncCodec::Hevc => VAProfile::VAProfileHEVCMain, + EncCodec::H264 => VAProfile::VAProfileH264Main, }; // The driver's own answer to "can you encode this at all": a GPU with no // AV1 encode entrypoint is what makes the caller fall back to `rav1e`, @@ -833,8 +864,8 @@ impl EncSession { let pred_structure = PredictionStructure::LowDelay { limit: (framerate * 2) as u16, }; - let encoder: Box> = match av1 { - true => { + let encoder: Box> = match codec { + EncCodec::Av1 => { // Constant quality, because that is the only rate control the // vendored AV1 backend takes (`stateless/av1/vaapi.rs` refuses // anything else outright); 128 of 255 is its own reference @@ -867,7 +898,50 @@ impl EncSession { .ok()?, ) } - false => { + EncCodec::Hevc => { + // **Every picture an IDR**, which is the one place this seat + // does not mirror the H.264 one. A GOP's P slices come out of + // this driver undecodable: the slice segment headers are the + // *driver's* to write (as they are for H.264) and radeonsi + // writes a constant picture order count into every one of them, + // so a decoder sees frame after frame claiming to be the same + // output picture. Measured 2026-08-13: with the default GOP, + // only the leading IDR of each group decodes. + // + // So the hardware seat is intra-only exactly as the software one + // is (`export::Enc::open_hevc`), and an HEVC export is an + // intraframe master either way -- the same file, coded by the + // GPU instead of by twelve cores. + // + // corner-cut: inter HEVC on this GPU needs the slice segment + // header written here rather than by the driver + // (`VAEncPackedHeaderSlice`), which is a change in the vendored + // backend; upgrade path is that, or a driver that writes a + // correct POC. + let config = H265Config { + resolution: Resolution { width, height }, + profile: H265Profile::Main, + level: H265Level::L4, + pred_structure: PredictionStructure::LowDelay { limit: 1 }, + initial_tunings: Tunings { + rate_control: RateControl::ConstantBitrate(bitrate), + framerate, + ..Default::default() + }, + }; + Box::new( + HevcEncoder::new_vaapi( + display, + config, + Fourcc::from(b"NV12"), + coded, + low_power, + BlockingMode::Blocking, + ) + .ok()?, + ) + } + EncCodec::H264 => { let config = H264Config { resolution: Resolution { width, height }, profile: H264Profile::Main, @@ -898,7 +972,7 @@ impl EncSession { let layout = nv12_layout(coded, frame.get_plane_pitch()[0], false); Some(Self { encoder, - h264: !av1, + codec, _gbm: gbm, frame, layout, @@ -981,7 +1055,7 @@ impl EncSession { fn collect(&mut self) -> Result<(), String> { while let Some(coded) = self.encoder.poll().map_err(|e| e.to_string())? { let mut au = coded.bitstream; - if self.h264 { + if self.codec == EncCodec::H264 { fix_slice_nal_headers(&mut au); } self.ready.push_back(au); @@ -1044,7 +1118,37 @@ pub extern "C" fn vh_enc_av1_open( bitrate: u64, ) -> *mut c_void { catch_unwind(AssertUnwindSafe(|| { - match EncSession::open_codec(width, height, fps_num, fps_den, bitrate, true) { + match EncSession::open_codec(width, height, fps_num, fps_den, bitrate, EncCodec::Av1) { + Some(session) => Box::into_raw(Box::new(session)) as *mut c_void, + None => std::ptr::null_mut(), + } + })) + .unwrap_or(std::ptr::null_mut()) +} + +/// The same, coding HEVC: null unless this GPU has an HEVC encode entrypoint and +/// the picture is at least 384x384 ([`EncSession::open_codec`] states that floor +/// and where it was measured), and the caller then encodes HEVC in software +/// instead. +/// +/// **Intra-only**: every picture it hands back is an IDR carrying its own VPS, +/// SPS and PPS, which is what makes the file decodable at all on this driver -- +/// see the `EncCodec::Hevc` arm of [`EncSession::open_codec`]. `bitrate` is the +/// constant bitrate the GPU codes at, as the H.264 seat's is. +/// +/// The session it returns is fed, drained and closed through `vh_enc_frame`, +/// `vh_enc_drain` and `vh_enc_close` exactly as an H.264 one is; what comes back +/// out of them is Annex-B HEVC access units. +#[unsafe(no_mangle)] +pub extern "C" fn vh_enc_hevc_open( + width: u32, + height: u32, + fps_num: u32, + fps_den: u32, + bitrate: u64, +) -> *mut c_void { + catch_unwind(AssertUnwindSafe(|| { + match EncSession::open_codec(width, height, fps_num, fps_den, bitrate, EncCodec::Hevc) { Some(session) => Box::into_raw(Box::new(session)) as *mut c_void, None => std::ptr::null_mut(), } @@ -1160,9 +1264,13 @@ mod tests { return; }; eprintln!("{caps:?}"); - // Encode is this plugin's two seats and no others, whatever entrypoints - // the driver has: an HEVC or VP9 EncSlice is not an encoder here. - assert_eq!(caps.encode & !(CAP_H264 | CAP_AV1), 0, "{caps:?}"); + // Encode is this plugin's three seats and no others, whatever + // entrypoints the driver has: a VP9 EncSlice is not an encoder here. + assert_eq!( + caps.encode & !(CAP_H264 | CAP_HEVC | CAP_AV1), + 0, + "{caps:?}" + ); // A 10-bit claim is a decode claim -- same profile family, read back // through P010 -- and there is no 10-bit encode path at all. assert_eq!(caps.decode_10bit & !caps.decode, 0, "{caps:?}"); diff --git a/crates/engine/examples/bench.rs b/crates/engine/examples/bench.rs index 69807f3..ae88085 100644 --- a/crates/engine/examples/bench.rs +++ b/crates/engine/examples/bench.rs @@ -26,7 +26,8 @@ //! first frame, `BENCH_EXPORT_CAP` (s, default 300) the wall clock any single //! export measurement may take, `BENCH_EXPORT_REPS` (default 5) how many times //! an export is repeated *if the cap leaves room* -- a 4K encode gets one -//! capped rep, the small control gets five. +//! capped rep, the small control gets five -- and `BENCH_KEEP` (unset) whether +//! the exported file survives the run instead of being deleted with the number. use std::path::{Path, PathBuf}; use std::time::{Duration, Instant}; @@ -63,7 +64,7 @@ fn usage() -> ! { eprintln!( "usage: bench open \n bench seek \n \ bench scrub \n bench waveform \n \ - bench export " + bench export " ); std::process::exit(2) } @@ -356,7 +357,11 @@ fn export_bench(path: &Path, seat: &str, out_dir: &Path) { "h264sw" => (Format::Mp4, true), "h264hw" => (Format::Mp4, false), "av1" => (Format::Av1, true), + // `hevc` keeps meaning the software intra seat, so a row measured + // against an older baseline still compares with the one beside it; the + // GPU seat is the new name. "hevc" => (Format::Hevc, true), + "hevchw" => (Format::Hevc, false), _ => usage(), }; let metric = format!("export_fps_{seat}"); @@ -426,7 +431,12 @@ fn export_bench(path: &Path, seat: &str, out_dir: &Path) { } let seats = handle.encoders().unwrap_or_else(|| "?".into()); let outcome = handle.result(); - let _ = std::fs::remove_file(&out); + // A throughput run leaves nothing behind; `BENCH_KEEP=1` keeps the last + // one, which is how a seat is checked for *decodability* rather than + // speed (`ffprobe -count_frames` on the file it wrote). + if std::env::var_os("BENCH_KEEP").is_none() { + let _ = std::fs::remove_file(&out); + } if capped { samples.push(progress * f64::from(span) / elapsed); notes.push(format!("CAPPED at {:.0}s, {:.0}% done, {seats}", elapsed, progress * 100.0)); diff --git a/crates/engine/src/caps.rs b/crates/engine/src/caps.rs index 164581c..858e16a 100644 --- a/crates/engine/src/caps.rs +++ b/crates/engine/src/caps.rs @@ -104,18 +104,19 @@ mod tests { assert!(hw_line(None).starts_with("none —")); // A driver that answers with nothing is its own sentence. assert!(hw_line(Some(VhCaps::default())).starts_with("none —")); - // This project's own GPU as `vainfo` lists it: H.264 both ways, HEVC - // and VP9 decode with their 10-bit profiles, AV1 both ways. HEVC has a - // VA encode entrypoint here and is *not* an encode seat: the plugin has - // no HEVC encoder, so the line must not offer one. + // This project's own GPU as `vainfo` lists it: H.264, HEVC and AV1 both + // ways, VP9 decode only, and the 10-bit profiles on three of the four. + // HEVC is an encode seat here as of the plugin's `vh_enc_hevc_open` -- + // the 10-bit note beside it stays a *decode* claim, that seat coding + // 8-bit Main whatever the source was. let radeonsi = VhCaps { decode: CAP_H264 | CAP_HEVC | CAP_VP9 | CAP_AV1, - encode: CAP_H264 | CAP_AV1, + encode: CAP_H264 | CAP_HEVC | CAP_AV1, decode_10bit: CAP_HEVC | CAP_VP9 | CAP_AV1, }; assert_eq!( hw_line(Some(radeonsi)), - "H.264 dec+enc · HEVC dec (10-bit) · VP9 dec (10-bit) · AV1 dec+enc (10-bit)" + "H.264 dec+enc · HEVC dec+enc (10-bit) · VP9 dec (10-bit) · AV1 dec+enc (10-bit)" ); // A codec the driver has neither seat for is left out rather than // listed as a refusal: this line is what the machine *can* do. diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 8f9087d..8bc6ffe 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -496,11 +496,15 @@ fn hw_seat(meta: &VideoMeta, settings: &ExportSettings) -> Option { let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate).ok()?; let bitrate = bitrate_of(meta, settings); match settings.format { - // The HEVC pair is software only, and not for want of a GPU: the plugin - // has no HEVC *encode* entry point at all (`hw::HwEncoder` opens H.264 - // and AV1), so there is no seat to probe. Said here rather than left to - // a failed open, which would read as a driver refusal. - format if format.is_hevc() => None, + // Both HEVC formats sit on the plugin's HEVC seat, and it is the + // default: what it codes is intra-only, the very file the software seat + // writes, so preferring the GPU changes how long an export takes and + // not what comes out of it. `None` here is the plugin's own "no" -- + // no entrypoint, or a picture under the driver's 384x384 floor -- and + // the software intra encoder takes the file. + format if format.is_hevc() => { + HwEncoder::open_hevc(meta.width, meta.height, fps_num, fps_den, bitrate) + } // Opt-in only, for the reason [`Enc::open_av1`] states in full. Both // AV1 formats sit on it: the container is not the encoder's business. format if format.is_av1() && !forced("VE_HW_AV1") => None, @@ -2627,6 +2631,9 @@ enum Enc { }, /// AV1 on the GPU, through the same plugin the H.264 seat uses. Av1Hw(HwEncoder), + /// HEVC on the GPU, through that same plugin -- and intra-only there too, + /// so this and [`Enc::Hevc`] write the same kind of file. + HevcHw(HwEncoder), Av1Sw { context: rav1e::Context, /// Temporal units the encoder has finished but the caller has not @@ -2687,6 +2694,7 @@ impl Enc { Self::Sw { .. } => video_label(Format::Mp4, false), Self::Av1Hw(_) => video_label(Format::Av1, true), Self::Av1Sw { .. } => video_label(Format::Av1, false), + Self::HevcHw(_) => video_label(Format::Hevc, true), Self::Hevc(_) => video_label(Format::Hevc, false), } } @@ -2810,11 +2818,14 @@ impl Enc { }) } - /// The intra HEVC seat, software and frame-parallel. There is no hardware - /// half: the plugin encodes H.264 and AV1 and nothing else, which - /// [`hw_seat`] says by refusing to probe one. + /// The HEVC pair: the plugin's VA-API seat where the GPU has one, and the + /// frame-parallel software encoder everywhere else -- below the driver's + /// 384x384 floor, on a plugin too old to carry the symbol, on a GPU with no + /// HEVC encode entrypoint. Silent either way, because both write the same + /// kind of file. /// - /// **Intra-only, deliberately.** The vendored encoder's inter modes code + /// **Intra-only, deliberately, on both seats.** The software encoder's inter + /// modes code /// 1080p at 0.81 fps across 12 cores (measured 2026-08-11) -- a minute of /// timeline in half an hour, which is not an export anybody waits for -- /// while the intra path does 4.30 fps on the same picture and the same @@ -2839,6 +2850,10 @@ impl Enc { ) .into()); } + if let Some(hw) = hw_seat(meta, settings) { + eprintln!("export encoder: hardware HEVC intra (VA-API plugin)"); + return Ok(Self::HevcHw(hw)); + } let (width, height) = ( (meta.width as usize).next_multiple_of(CTB), (meta.height as usize).next_multiple_of(CTB), @@ -2900,6 +2915,12 @@ impl Enc { collect_av1(context, ready)?; Ok(pop_av1(ready, au)) } + // Every unit this seat hands back is an IDR carrying its own + // parameter sets (the plugin codes HEVC intra-only), so every one of + // them is a sync point -- said as a constant rather than parsed back + // out of the bitstream, because it is this encoder's configuration + // and not a driver's choice. + Self::HevcHw(hw) => Ok(hw.encode(y, u, v, width, height, true)?.map(|au| (au, true))), Self::Hevc(hevc) => { hevc.pending.push(pad_to_ctb( y, @@ -2956,6 +2977,7 @@ impl Enc { } Ok(pop_av1(ready, au)) } + Self::HevcHw(hw) => Ok(hw.drain()?.map(|au| (au, true))), Self::Hevc(hevc) => { // The tail batch: fewer frames than lanes, coded on as many // cores as there are frames left. diff --git a/crates/engine/src/hw.rs b/crates/engine/src/hw.rs index e1a465e..79852bf 100644 --- a/crates/engine/src/hw.rs +++ b/crates/engine/src/hw.rs @@ -259,6 +259,9 @@ struct EncPlugin { /// plugin keeps one session type for both codecs, so the codec is decided /// once, at the open, exactly as the H.264 seat's parameters are. open_av1: Option *mut c_void>, + /// The HEVC seat, missing from an older plugin for the same reason and at + /// the same cost: an HEVC export then runs on the software intra encoder. + open_hevc: Option *mut c_void>, frame: unsafe extern "C" fn(*mut c_void, *const VhFrame, i32, *mut *const u8, *mut usize) -> i32, drain: unsafe extern "C" fn(*mut c_void, *mut *const u8, *mut usize) -> i32, @@ -285,6 +288,7 @@ fn load_enc() -> Option { Some(EncPlugin { open: *lib.get(b"vh_enc_open\0").ok()?, open_av1: lib.get(b"vh_enc_av1_open\0").ok().map(|s| *s), + open_hevc: lib.get(b"vh_enc_hevc_open\0").ok().map(|s| *s), frame: *lib.get(b"vh_enc_frame\0").ok()?, drain: *lib.get(b"vh_enc_drain\0").ok()?, close: *lib.get(b"vh_enc_close\0").ok()?, @@ -345,6 +349,28 @@ impl HwEncoder { Self::opened(plugin, open, width, height, fps_num, fps_den, bitrate) } + /// The same, coding HEVC. Unlike the AV1 seat this is **not** behind an + /// opt-in: it is the default for an HEVC export, and what makes that safe is + /// that the pictures it codes are intra-only, which is the same file the + /// software seat writes ([`crate::export::Enc::open_hevc`]) and not the + /// GPU-resetting inter path AV1's opt-in exists for. + /// + /// `None` on everything [`HwEncoder::open`] answers `None` to, on a plugin + /// too old to export the symbol, on a GPU with no HEVC encode entrypoint, + /// and below 384x384 -- the driver's own floor, stated in the plugin. The + /// caller then takes the software intra encoder without a word about it. + pub fn open_hevc( + width: u32, + height: u32, + fps_num: u32, + fps_den: u32, + bitrate: u64, + ) -> Option { + let plugin = enc_plugin()?; + let open = plugin.open_hevc?; + Self::opened(plugin, open, width, height, fps_num, fps_den, bitrate) + } + /// The null check both opens share, which is the plugin's whole way of /// saying "no". fn opened( diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index f44a313..adc56de 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -12,7 +12,7 @@ //! the renderer decides which frame that means. use std::path::Path; -use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, AtomicUsize, Ordering}; use std::sync::mpsc::{Receiver, TryRecvError}; use std::sync::{Arc, Mutex}; use std::thread; @@ -116,6 +116,11 @@ struct Audio { /// is not the device's own callback -- the plugin's RT thread never sees /// this lock, and the feeder holds it for one memcpy per write. tap: Arc>>, + /// Feeder threads started and not yet returned. They are detached, so there + /// is no handle to count instead, and a scrub leaves dozens of them exiting + /// at once -- which is precisely what + /// [`live_workers`](PlaybackSession::live_workers) is asked about. + feeders: Arc, } /// How much of the played signal the tap keeps. A power of two, because what @@ -174,24 +179,35 @@ impl Audio { ) -> bool { let me = self.clone(); let epoch = self.epoch.load(Ordering::Acquire); - thread::Builder::new() + // Counted before the spawn, so the count is never behind the thread. + self.feeders.fetch_add(1, Ordering::Release); + let started = thread::Builder::new() .name("audio-feed".into()) .spawn(move || { // Superseded before this thread was even scheduled: do not open // anything at all. A scrub leaves all but the last one here. - if me.epoch.load(Ordering::Acquire) != epoch { - return; - } - if let Some(rx) = open() { - feed(rx, &me, epoch); - } - // Only the current feeder gets to declare the end of the audio: - // a superseded one is finished, the stream is not. if me.epoch.load(Ordering::Acquire) == epoch { - me.fed_all.store(true, Ordering::Release); + if let Some(rx) = open() { + feed(rx, &me, epoch); + } + // Only the current feeder gets to declare the end of the + // audio: a superseded one is finished, the stream is not. + if me.epoch.load(Ordering::Acquire) == epoch { + me.fed_all.store(true, Ordering::Release); + } } + me.feeders.fetch_sub(1, Ordering::Release); }) - .is_ok() + .is_ok(); + if !started { + self.feeders.fetch_sub(1, Ordering::Release); + } + started + } + + /// Feeder threads still running; see [`Self::feeders`]. + fn live_feeders(&self) -> usize { + self.feeders.load(Ordering::Acquire) } } @@ -1219,6 +1235,21 @@ impl PlaybackSession { self.retired.retain(|w| !w.is_finished()); } + /// How many threads this session still has running of its own: the decode + /// worker, every retired one that has not returned yet, and the audio + /// feeders still in the air. One for a session playing along quietly. + /// + /// The oracle a seek storm is judged by. `/proc/self/status` counts the + /// *process*, and a suite decoding twenty files at once moves that number + /// under a test that never touched them -- this counts only what the + /// session in hand owns, so it says the same thing alone and in a crowd. + #[doc(hidden)] + pub fn live_workers(&self) -> usize { + usize::from(!self.worker.is_finished()) + + self.retired.iter().filter(|w| !w.is_finished()).count() + + self.audio.as_ref().map_or(0, Audio::live_feeders) + } + /// Starts feeding whatever follows the current span on the timeline -- /// another clip, or a gap, which is black frames from a worker that opens no /// file. `false` past the end. The next timeline frame is derived rather @@ -2958,6 +2989,7 @@ fn open_audio(path: &Path, stream: usize) -> (Option