Encoders use all CPUs but one by default

libvpx's worker threads wait on each other by spinning. With one thread
per core, an encode slows down many times over as soon as anything else
wants a core: the capture and conversion of the next frame, another
layer, the desktop. The bench on a 4-core machine showed single frames
at 1080p and 1440p taking 130-290 ms with 4 threads under load, where the
same frames took 9-17 ms with 3 threads next to two other layers. The
default (`codec::encoder_cpus`) is now all CPUs but one, for single
encoders and for the streamer's split across layers; an explicit
`EncoderConfig::threads` still wins.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G
This commit is contained in:
Claude committed 2026-09-27 18:38:33 +00:00
1 parent 6187cc24de
commit 3e498497d7
3 files changed
+23 -9

No files matched your search

+3 -1
View File
@@ -530,8 +530,10 @@ fn thread_split(layers: &[LayerSpec], cores: u32) -> Vec<u32> {
layers.iter().map(|l| ((f64::from(cores) * area(l) / total).round() as u32).max(1)).collect() layers.iter().map(|l| ((f64::from(cores) * area(l) / total).round() as u32).max(1)).collect()
} }
/// CPUs split between the layers' encoders (all but one, see
/// `voelin_media::codec::encoder_cpus`).
fn cores() -> u32 { fn cores() -> u32 {
std::thread::available_parallelism().map_or(1, |n| n.get() as u32) voelin_media::codec::encoder_cpus()
} }
fn new_encoder( fn new_encoder(
+15 -4
View File
@@ -127,7 +127,7 @@ pub struct EncoderConfig {
pub keyframe_interval: Option<u32>, pub keyframe_interval: Option<u32>,
pub content: ContentHint, pub content: ContentHint,
/// Most encoder threads (still no more than the frame size can use); 0: /// Most encoder threads (still no more than the frame size can use); 0:
/// all CPUs. /// all CPUs but one ([`encoder_cpus`]).
pub threads: u32, pub threads: u32,
/// A fixed speed / quality trade-off in the backend's own terms (libvpx /// A fixed speed / quality trade-off in the backend's own terms (libvpx
/// `cpu-used`); `None` lets the encoder adapt it to how long frames take /// `cpu-used`); `None` lets the encoder adapt it to how long frames take
@@ -148,13 +148,24 @@ impl Default for EncoderConfig {
} }
} }
/// CPUs encoders use by default: all but one (at least one). libvpx's
/// threads wait on each other by spinning, so an encode that wants every
/// core slows down many times over as soon as anything else runs (the
/// capture and conversion of the next frame, another layer, the desktop);
/// measured on a 4-core machine: 130-290 ms per 1080p frame with 4 threads
/// under load, against 9-17 ms with 3.
pub fn encoder_cpus() -> u32 {
let cpus = std::thread::available_parallelism().map_or(1, |n| n.get() as u32);
cpus.saturating_sub(1).max(1)
}
impl EncoderConfig { impl EncoderConfig {
/// Threads for a `width` x `height` encode: [`threads`](Self::threads) /// Threads for a `width` x `height` encode: [`threads`](Self::threads)
/// (or all CPUs), but no more than one per 320x240 pixels: more would /// (or [`encoder_cpus`]), but no more than one per 320x240 pixels: more
/// idle on small frames and cost quality (VP8 token partitions). /// would idle on small frames and cost quality (VP8 token partitions).
pub fn threads_for(&self, width: u32, height: u32) -> u32 { pub fn threads_for(&self, width: u32, height: u32) -> u32 {
let cpus = match self.threads { let cpus = match self.threads {
0 => std::thread::available_parallelism().map_or(1, |n| n.get() as u32), 0 => encoder_cpus(),
n => n, n => n,
}; };
let useful = (u64::from(width) * u64::from(height) / (320 * 240)).clamp(1, 64) as u32; let useful = (u64::from(width) * u64::from(height) / (320 * 240)).clamp(1, 64) as u32;
+5 -4
View File
@@ -18,7 +18,7 @@ MediaTime::new(frame.pts_90khz, Frequency::NINETY_KHZ), data)`), and received
| `VideoEncoder` | `encode(&frame, force_keyframe) -> Vec<EncodedFrame>`; `encode_with(&frame, force_keyframe, &mut |EncodedChunk| ..)` hands out the encoder's own buffer (no copy); `set_bitrate(bps)` (libvpx: in place, no keyframe), `set_fps`, `speed()`, `codec()`, `backend()` | | `VideoEncoder` | `encode(&frame, force_keyframe) -> Vec<EncodedFrame>`; `encode_with(&frame, force_keyframe, &mut |EncodedChunk| ..)` hands out the encoder's own buffer (no copy); `set_bitrate(bps)` (libvpx: in place, no keyframe), `set_fps`, `speed()`, `codec()`, `backend()` |
| `EncodedFrame { data, keyframe, pts_90khz }` | one frame for `Peer::write` | | `EncodedFrame { data, keyframe, pts_90khz }` | one frame for `Peer::write` |
| `VideoDecoder` | `decode(&[u8]) -> Option<VideoFrame>` (timestamp zero; the caller knows the RTP time) | | `VideoDecoder` | `decode(&[u8]) -> Option<VideoFrame>` (timestamp zero; the caller knows the RTP time) |
| `EncoderConfig { fps, bitrate_bps, keyframe_interval, content, threads, speed }` | resolution follows the frames; a size change restarts with a keyframe; `threads` is a maximum (0: all CPUs), still capped at one per 320x240 pixels; `speed: None` adapts libvpx `cpu-used` to the encode time | | `EncoderConfig { fps, bitrate_bps, keyframe_interval, content, threads, speed }` | resolution follows the frames; a size change restarts with a keyframe; `threads` is a maximum (0: all CPUs but one), still capped at one per 320x240 pixels; `speed: None` adapts libvpx `cpu-used` to the encode time |
| `Codecs` | `new()`, `with_openh264(lib)`, `decoders()` (viewer order), `encoders()` / `encoder_codecs()` (streamer order), `new_decoder(codec)`, `new_encoder(codec, config)`, `pick_encoder(&accepted)` | | `Codecs` | `new()`, `with_openh264(lib)`, `decoders()` (viewer order), `encoders()` / `encoder_codecs()` (streamer order), `new_decoder(codec)`, `new_encoder(codec, config)`, `pick_encoder(&accepted)` |
| `ScreenCapture` | `sources()`, `start_sink(&SourceId, &CaptureOptions, Box<dyn FrameSink>)` (frames borrowed from the capture buffer, on the backend's thread), `start(..)` (copies into a queue), `stop()`; async: the portal asks the user | | `ScreenCapture` | `sources()`, `start_sink(&SourceId, &CaptureOptions, Box<dyn FrameSink>)` (frames borrowed from the capture buffer, on the backend's thread), `start(..)` (copies into a queue), `stop()`; async: the portal asks the user |
| `FrameSink` | `max_fps()` (may change while capturing), `wants(timestamp)` (asked before anything is mapped or copied), `frame(FrameRef) -> bool` | | `FrameSink` | `max_fps()` (may change while capturing), `wants(timestamp)` (asked before anything is mapped or copied), `frame(FrameRef) -> bool` |
@@ -152,9 +152,10 @@ unless `keyframe_interval` is set, screen content tuning
(`VP8E_SET_SCREEN_CONTENT_MODE`, `VP9E_SET_TUNE_CONTENT`, static threshold), (`VP8E_SET_SCREEN_CONTENT_MODE`, `VP9E_SET_TUNE_CONTENT`, static threshold),
VP9 row-mt, tile columns from the thread count and width (tiles are at least VP9 row-mt, tile columns from the thread count and width (tiles are at least
256 pixels wide) and cyclic-refresh AQ, VP8 token partitions from the thread 256 pixels wide) and cyclic-refresh AQ, VP8 token partitions from the thread
count. Threads: all CPUs (or the streamer's share per layer), at most one per count. Threads: all CPUs but one (libvpx threads spin-wait on each other and
320x240 pixels. `cpu-used` adapts to the measured encode time against the slow down many times over when every core is taken), or the streamer's share
frame interval (faster at once when one frame overruns the interval or the of them per layer, at most one per 320x240 pixels. `cpu-used` adapts to the
measured encode time against the frame interval (faster at once when one frame overruns the interval or the
mean is above 75 %; slower when the mean stayed below 35 % for 15 frames, mean is above 75 %; slower when the mean stayed below 35 % for 15 frames,
waiting twice as long after each slower step that had to be undone): VP8 waiting twice as long after each slower step that had to be undone): VP8
starts at −10 and moves within −10..−6 (on screen content −12 and faster starts at −10 and moves within −10..−6 (on screen content −12 and faster