streams: decode VP8 on one thread, convert pictures off the decoder
Watching was slow because FFmpeg's VP8 decoder ran on slice threads: they split frames by token partitions, and our 4- and 8-partition streams (from senders with 6 cores or more) took 18-21 ms per 1440p picture against 10 on one thread, so the decoder fell behind, dropped its queue and waited for keyframes (35-49 of 60 fps shown). VP8 now decodes on one thread. The decode thread also converted every picture to RGBA into a new zeroed buffer (3.6 ms at 1080p, 5.1 at 1440p). It now hands its newest frame to a converter thread, which converts only what the window can show into buffers reused three pictures later (0.8 and 1.0 ms). libvpx's decoder spins its threads (4 threads: 23 and 11 fps on those streams with a core busy, 2: 143 and 129): at most 2. dav1d with a frame delay of one gets a quarter of the cores, 1 to 4. docs/research/stream-fps.md has the measurements and what is left (the sender's encode rate and bitrate, H.264 frame threads, texture uploads). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01VZBWxxMsxUzp4PSTKVzbZN
This commit is contained in:
1 parent
a88d267937
commit
eafa67cfe9
6 files changed
+262
-14
No files matched your search
@@ -21,9 +21,7 @@ impl Dav1dDecoder {
|
||||
pub fn new() -> Result<Self> {
|
||||
let mut settings = Settings::new();
|
||||
settings.set_max_frame_delay(1);
|
||||
settings.set_n_threads(
|
||||
std::thread::available_parallelism().map_or(1, |n| n.get().min(4) as u32),
|
||||
);
|
||||
settings.set_n_threads(crate::codec::dav1d_threads() as u32);
|
||||
let decoder = dav1d::Decoder::with_settings(&settings).map_err(|e| {
|
||||
Error::CodecUnavailable { codec: Codec::Av1, reason: format!("dav1d: {e}") }
|
||||
})?;
|
||||
|
||||
@@ -25,6 +25,15 @@ use std::sync::Arc;
|
||||
use crate::frame::VideoFrame;
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// dav1d's threads with a frame delay of one (ours and FFmpeg's `libdav1d`):
|
||||
/// a quarter of the cores, 1 to 4. They wait on each other where cores are
|
||||
/// few (on 4 cores, 1080p: 211 fps on one thread, 155-166 on 3 or 4) and
|
||||
/// help where there are many (32 cores, 1440p: 412 fps on 8).
|
||||
#[cfg_attr(not(any(feature = "av1", feature = "ffmpeg")), allow(dead_code))]
|
||||
pub(crate) fn dav1d_threads() -> usize {
|
||||
std::thread::available_parallelism().map_or(1, |n| (n.get() / 4).clamp(1, 4))
|
||||
}
|
||||
|
||||
#[cfg(feature = "av1")]
|
||||
pub mod av1;
|
||||
#[cfg(feature = "openh264")]
|
||||
|
||||
@@ -302,7 +302,11 @@ impl VpxDecoder {
|
||||
pub fn new(codec: Codec) -> Result<Self> {
|
||||
let vp9 = is_vp9(codec)?;
|
||||
check(codec, false)?;
|
||||
let threads = std::thread::available_parallelism().map_or(1, |n| n.get().min(4) as u32);
|
||||
// libvpx's decoder threads spin waiting for each other: on 4 threads
|
||||
// with another core busy, our 4- and 8-partition 1440p streams
|
||||
// decoded at 23 and 11 fps, on 2 at 143 and 129.
|
||||
let cores = std::thread::available_parallelism().map_or(1, |n| n.get());
|
||||
let threads = (cores / 2).clamp(1, 2) as u32;
|
||||
let decoder =
|
||||
raw::Decoder::new(vp9, threads).map_err(|message| Error::Decoder { codec, message })?;
|
||||
Ok(Self { codec, decoder })
|
||||
|
||||
@@ -16,7 +16,8 @@
|
||||
//! Every decoder is set up for live video: slice threads only (frame
|
||||
//! threads hold one frame per thread before the first picture comes out),
|
||||
//! dav1d with a frame delay of one, so each frame's picture comes out of
|
||||
//! the call that decoded it.
|
||||
//! the call that decoded it. VP8 decodes on one thread: its slice threads
|
||||
//! split frames by token partitions and wait on each other ([`decoder_threads`]).
|
||||
//!
|
||||
//! [`probe`] runs every decoder once per process (in parallel) on a short
|
||||
//! clip of its codec: three frames of a test picture encoded by this crate's
|
||||
@@ -196,9 +197,18 @@ fn hw_device(ffmpeg: &Ffmpeg, kind: &'static str) -> std::result::Result<Ptr, St
|
||||
}
|
||||
|
||||
/// Threads of a software decoder: slice (or dav1d's tile and row) threads,
|
||||
/// which add no delay.
|
||||
fn decoder_threads() -> usize {
|
||||
std::thread::available_parallelism().map_or(1, |n| n.get().min(8))
|
||||
/// which add no delay. Except for VP8, whose slice threads work on the
|
||||
/// frame's token partitions and wait on each other: a stream of 4 or 8
|
||||
/// partitions (ours, from a sender with 6 cores or more) decoded 40-80 %
|
||||
/// slower on 4 threads than on one, too slow for 1440p at 60 fps. dav1d
|
||||
/// ([`crate::codec::dav1d_threads`]) gets a quarter of the cores.
|
||||
fn decoder_threads(codec: Codec, decoder: &str) -> usize {
|
||||
let cores = std::thread::available_parallelism().map_or(1, |n| n.get());
|
||||
match (codec, decoder) {
|
||||
(Codec::Vp8, _) => 1,
|
||||
(_, "libdav1d") => crate::codec::dav1d_threads(),
|
||||
_ => cores.min(8),
|
||||
}
|
||||
}
|
||||
|
||||
/// A decoder of one [`DecoderSpec`]; see the [module docs](self).
|
||||
@@ -258,7 +268,8 @@ impl FfmpegDecoder {
|
||||
// private options object (NULL if the decoder has none).
|
||||
let private = unsafe { (api.av_opt_child_next)(this.ctx, std::ptr::null_mut()) };
|
||||
// A hardware decoder's work is on the GPU.
|
||||
let threads = if spec.is_hardware() { 1 } else { decoder_threads() };
|
||||
let threads =
|
||||
if spec.is_hardware() { 1 } else { decoder_threads(spec.codec, spec.decoder) };
|
||||
this.set(this.ctx, "threads", &threads.to_string());
|
||||
this.set(this.ctx, "thread_type", "slice");
|
||||
if spec.decoder == "libdav1d"
|
||||
|
||||
@@ -2,10 +2,11 @@
|
||||
//! into Slint images when we watch, and the optional OpenH264 library
|
||||
//! (desktop; Android decodes H.264 with the device's MediaCodec).
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::path::Path;
|
||||
#[cfg(not(target_os = "android"))]
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::{Arc, Condvar, Mutex, PoisonError};
|
||||
|
||||
use slint::{Image, Rgba8Pixel, SharedPixelBuffer};
|
||||
use tokio::runtime::Handle;
|
||||
@@ -357,17 +358,116 @@ impl Video {
|
||||
}
|
||||
|
||||
/// Converts decoded frames into Slint pixel buffers, keeping the newest.
|
||||
///
|
||||
/// The decoder only hands its newest frame over: a converter thread turns
|
||||
/// it into RGBA, so decoding never waits for the conversion (at 1440p it
|
||||
/// took a third of a 60 fps frame's time on the decode thread, and a
|
||||
/// decoder that falls behind drops its queue and waits for a keyframe),
|
||||
/// and frames the window could not show anyway are never converted. The
|
||||
/// converter reuses the buffers of earlier pictures, which the window has
|
||||
/// let go of by then, instead of a new zeroed buffer per frame. Without a
|
||||
/// thread, frames are converted on the decoder's.
|
||||
fn deliver(
|
||||
pictures: Arc<Latest<Picture>>,
|
||||
wake: impl Fn() + Send + Sync + 'static,
|
||||
) -> impl FnMut(Arc<VideoFrame>) + Send + 'static {
|
||||
move |frame: Arc<VideoFrame>| {
|
||||
let mut buffer = Picture::new(frame.width, frame.height);
|
||||
let stride = frame.width as usize * 4;
|
||||
if let Err(e) = convert::to_rgba(&frame, buffer.make_mut_bytes(), stride) {
|
||||
let slot = Arc::new(FrameSlot::default());
|
||||
let wake = Arc::new(wake);
|
||||
let thread = {
|
||||
let (slot, pictures, wake) = (slot.clone(), pictures.clone(), wake.clone());
|
||||
std::thread::Builder::new().name("voelin-picture".into()).spawn(move || {
|
||||
let mut buffers = Buffers::default();
|
||||
while let Some(frame) = slot.wait() {
|
||||
buffers.show(&frame, &pictures, &*wake);
|
||||
}
|
||||
})
|
||||
};
|
||||
let mut inline = match thread {
|
||||
Ok(_) => None,
|
||||
Err(e) => {
|
||||
warn!("no picture thread, converting on the decoder's: {e}");
|
||||
Some(Buffers::default())
|
||||
}
|
||||
};
|
||||
let handoff = Handoff(slot);
|
||||
move |frame: Arc<VideoFrame>| match &mut inline {
|
||||
Some(buffers) => buffers.show(&frame, &pictures, &*wake),
|
||||
None => handoff.0.put(frame),
|
||||
}
|
||||
}
|
||||
|
||||
/// The newest decoded frame, waiting for the converter thread.
|
||||
#[derive(Default)]
|
||||
struct FrameSlot {
|
||||
/// The frame, and whether the decoder is gone.
|
||||
state: Mutex<(Option<Arc<VideoFrame>>, bool)>,
|
||||
ready: Condvar,
|
||||
}
|
||||
|
||||
impl FrameSlot {
|
||||
/// Replace the waiting frame (an older one is never converted).
|
||||
fn put(&self, frame: Arc<VideoFrame>) {
|
||||
self.state.lock().unwrap_or_else(PoisonError::into_inner).0 = Some(frame);
|
||||
self.ready.notify_one();
|
||||
}
|
||||
|
||||
fn close(&self) {
|
||||
self.state.lock().unwrap_or_else(PoisonError::into_inner).1 = true;
|
||||
self.ready.notify_one();
|
||||
}
|
||||
|
||||
/// The next frame; `None` once the decoder is gone.
|
||||
fn wait(&self) -> Option<Arc<VideoFrame>> {
|
||||
let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
loop {
|
||||
if state.1 {
|
||||
return None;
|
||||
}
|
||||
if let Some(frame) = state.0.take() {
|
||||
return Some(frame);
|
||||
}
|
||||
state = self.ready.wait(state).unwrap_or_else(PoisonError::into_inner);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The decoder's side of a [`FrameSlot`]: dropped with the decoder's
|
||||
/// callback, it ends the converter thread.
|
||||
struct Handoff(Arc<FrameSlot>);
|
||||
|
||||
impl Drop for Handoff {
|
||||
fn drop(&mut self) {
|
||||
self.0.close();
|
||||
}
|
||||
}
|
||||
|
||||
/// Pictures between a buffer's use and its reuse: the window shows one and
|
||||
/// may still be drawing the one before.
|
||||
const REUSE_AFTER: usize = 3;
|
||||
|
||||
/// The pixel buffers of the last pictures, reused when they come round.
|
||||
#[derive(Default)]
|
||||
struct Buffers {
|
||||
recent: VecDeque<Picture>,
|
||||
}
|
||||
|
||||
impl Buffers {
|
||||
fn show(&mut self, frame: &VideoFrame, pictures: &Latest<Picture>, wake: &dyn Fn()) {
|
||||
let (width, height) = (frame.width, frame.height);
|
||||
if self.recent.front().is_some_and(|b| (b.width(), b.height()) != (width, height)) {
|
||||
self.recent.clear();
|
||||
}
|
||||
let mut buffer = if self.recent.len() >= REUSE_AFTER {
|
||||
self.recent.pop_front().expect("a buffer")
|
||||
} else {
|
||||
Picture::new(width, height)
|
||||
};
|
||||
// A buffer the window still holds copies itself here first.
|
||||
if let Err(e) = convert::to_rgba(frame, buffer.make_mut_bytes(), width as usize * 4) {
|
||||
warn!("cannot show a picture: {e}");
|
||||
return;
|
||||
}
|
||||
self.recent.push_back(buffer.clone());
|
||||
if pictures.put(buffer) {
|
||||
wake();
|
||||
}
|
||||
@@ -544,6 +644,51 @@ impl Decoder {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
/// The converter thread shows the newest frame, wakes the window once
|
||||
/// per picture it waits for, and ends with the decoder's callback.
|
||||
#[test]
|
||||
fn frames_reach_the_window_through_the_converter() {
|
||||
let pictures = Arc::new(Latest::new());
|
||||
let wakes = Arc::new(AtomicUsize::new(0));
|
||||
let counted = wakes.clone();
|
||||
let mut on_frame = deliver(pictures.clone(), move || {
|
||||
counted.fetch_add(1, Ordering::SeqCst);
|
||||
});
|
||||
on_frame(Arc::new(VideoFrame::black_i420(8, 6)));
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
|
||||
let picture = loop {
|
||||
if let Some(picture) = pictures.take() {
|
||||
break picture;
|
||||
}
|
||||
assert!(std::time::Instant::now() < deadline, "no picture");
|
||||
std::thread::sleep(std::time::Duration::from_millis(5));
|
||||
};
|
||||
assert_eq!((picture.width(), picture.height()), (8, 6));
|
||||
assert_eq!(wakes.load(Ordering::SeqCst), 1);
|
||||
drop(on_frame);
|
||||
}
|
||||
|
||||
/// Buffers come round again after [`REUSE_AFTER`] pictures; a new size
|
||||
/// starts over.
|
||||
#[test]
|
||||
fn picture_buffers_are_reused() {
|
||||
let pictures = Latest::new();
|
||||
let mut buffers = Buffers::default();
|
||||
let frame = VideoFrame::black_i420(4, 4);
|
||||
for _ in 0..REUSE_AFTER + 2 {
|
||||
buffers.show(&frame, &pictures, &|| {});
|
||||
pictures.take();
|
||||
}
|
||||
assert_eq!(buffers.recent.len(), REUSE_AFTER);
|
||||
buffers.show(&VideoFrame::black_i420(2, 2), &pictures, &|| {});
|
||||
assert_eq!(buffers.recent.len(), 1);
|
||||
let picture = pictures.take().unwrap();
|
||||
assert_eq!((picture.width(), picture.height()), (2, 2));
|
||||
// Black, opaque.
|
||||
assert_eq!(picture.as_bytes()[3], 255);
|
||||
}
|
||||
|
||||
/// "Choose via system dialog" never passes the restore token, so the
|
||||
/// portal always asks; with a token the last choice gets its own row.
|
||||
|
||||
Reference in new issue
Block a user