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:
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.
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
# Why watched streams played at a low frame rate
|
||||
|
||||
Watching a TeamSpeak 6 stream (someone's screen share in the viewer) showed
|
||||
fewer frames than were sent, with freezes until the next keyframe. This
|
||||
note records what was measured, what changed, and what is left.
|
||||
|
||||
## Measurements
|
||||
|
||||
On a 4-core 2.1 GHz VM (one core busy with another build for part of the
|
||||
runs), with the app's own code: a 2560x1440 stream at 60 fps and about
|
||||
25 Mbit/s, encoded by `VpxEncoder` from synthetic content (moving gradients,
|
||||
a scrolling text-like area), fed to the viewer's decode loop in real time
|
||||
with the same queue rules as `decode_loop`.
|
||||
|
||||
| Stream (VP8 token partitions) | Decode per picture | Shown | Freezes in 10 s |
|
||||
|---|---|---|---|
|
||||
| 4 or 8 (a sender with 6 cores or more) | 18-21 ms | 35-49 of 60 fps | 2-3 queue drops, 34-167 frames skipped waiting for a keyframe |
|
||||
| 1 or 2 | 10.0-10.5 ms | 60 of 60 fps | none |
|
||||
|
||||
FFmpeg's command line on the same streams: `vp8` on 1 thread 95-101 fps, on
|
||||
4 slice threads (what the viewer used) 54-60 fps; libvpx on 4 threads 23 and
|
||||
11 fps on the 4- and 8-partition streams, on 2 threads 143 and 129. On clean
|
||||
1080p test clips, 4 partitions decode at 290 fps on one thread and 47-74 fps
|
||||
on 3-4 slice threads.
|
||||
|
||||
Handing a picture to the window (`video.rs`, a new zeroed `SharedPixelBuffer`
|
||||
and the I420 to RGBA conversion, on the decode thread):
|
||||
|
||||
| Size | New buffer + convert | Reused buffer + convert |
|
||||
|---|---|---|
|
||||
| 1920x1080 | 3.0-3.6 ms | 0.6-0.8 ms |
|
||||
| 2560x1440 | 5.1 ms | 1.0 ms |
|
||||
| 3840x2160 | 12.4-12.8 ms | 2.4-2.5 ms |
|
||||
|
||||
## Causes and what changed
|
||||
|
||||
1. **FFmpeg's VP8 decoder on slice threads** (the main cause). Every software
|
||||
decoder got all cores (up to 8) as slice threads. VP8's slice threads work
|
||||
on the frame's token partitions, and Voelin's VP8 senders use 4 (6-8
|
||||
cores) or 8 (9 or more) partitions, so the threads wait on each other and
|
||||
one 1440p picture took 18-21 ms: the decoder could not keep 60 fps, fell
|
||||
30 frames behind, dropped its queue and skipped everything until the next
|
||||
keyframe. FFmpeg's `vp8` comes before libvpx in the ladder, and Windows
|
||||
(and AMD under VA-API) have no VP8 hardware decoder, so most viewers took
|
||||
this path. **Now** VP8 decodes on one thread (`ffmpeg::decoder::decoder_threads`).
|
||||
2. **The picture's conversion on the decode thread.** Every decoded picture
|
||||
was converted to RGBA on the decode thread, into a new zeroed buffer, even
|
||||
when the window would only show the newest. **Now** the decoder hands its
|
||||
newest frame to a converter thread (`video.rs`, `deliver`), which converts
|
||||
only what can be shown, into buffers reused three pictures later (a buffer
|
||||
the window still holds copies itself first).
|
||||
3. **libvpx's decoder threads** spin waiting for each other and collapse when
|
||||
another core is busy (the fallback without FFmpeg, e.g. Windows without its
|
||||
FFmpeg libraries). **Now** at most 2 threads (`codec/vpx.rs`).
|
||||
4. **dav1d** with a frame delay of one is slower on 3-4 threads (155-166 fps)
|
||||
than on one (211 fps) on this 4-core machine, while 8 threads on a
|
||||
32-core one gave 412 fps at 1440p. **Now** a quarter of the cores, 1 to 4
|
||||
(`codec::dav1d_threads`, for our dav1d and FFmpeg's `libdav1d`).
|
||||
|
||||
## Left as they are
|
||||
|
||||
- **The sender.** The software VP8 encoder took 18-29 ms per 1440p frame on
|
||||
this machine, so a similar sender tops out at 35-55 fps; frames beyond that
|
||||
are dropped before encoding. The automatic bitrate is 0.12 bits per pixel
|
||||
per frame (27 Mbit/s at 1440p60); about 0.07 would suit screen content and
|
||||
decode faster. Showing the sender's encode rate next to the viewer's decode
|
||||
rate would tell the two apart.
|
||||
- **H.264 with one slice per frame** (the official client's AMF streams):
|
||||
slice threads give nothing (about 180 fps either way); frame threads give
|
||||
336-423 fps but add a frame of delay per thread, and the decoder self-test
|
||||
expects a picture from every frame at once.
|
||||
- **The window's texture upload.** The image has no cache key, so the
|
||||
renderer uploads a new full-size texture per frame (not measured, no GPU
|
||||
here).
|
||||
- **Lossy links.** str0m waits up to 30 complete frames for a lost packet
|
||||
before the frame is handed over as non-contiguous, and VP8/VP9/AV1 then
|
||||
wait for a keyframe (asked for at most every 500 ms).
|
||||
|
||||
The measuring harnesses were throwaway programs around `voelin-media`'s
|
||||
`VpxEncoder` and decoders and FFmpeg's command line; they are not part of the
|
||||
repository.
|
||||
Reference in new issue
Block a user