diff --git a/crates/voelin-core/src/media.rs b/crates/voelin-core/src/media.rs index f3712b8..b2588a1 100644 --- a/crates/voelin-core/src/media.rs +++ b/crates/voelin-core/src/media.rs @@ -32,7 +32,7 @@ use std::time::{Duration, Instant}; use tracing::{debug, warn}; use voelin_audio::{VoiceCodec, VoiceEncoder}; pub use voelin_media; -use voelin_media::capture::synthetic::{SineSource, SyntheticScreen}; +use voelin_media::capture::synthetic::{Pattern, SineSource, SyntheticScreen}; use voelin_media::capture::{ self, AudioCapture, CaptureOptions, CaptureSource, ScreenCapture, SourceId, }; @@ -202,6 +202,8 @@ pub struct StreamerConfig { pub cursor: bool, /// Size of the test pattern ([`SourceId::Synthetic`]). pub synthetic_size: (u32, u32), + /// What the test pattern shows. + pub synthetic_pattern: Pattern, /// Portal restore token from an earlier share: the desktop may skip its /// dialog. The new one is [`Streamer::restore_token`]. pub restore_token: Option, @@ -220,6 +222,7 @@ impl Default for StreamerConfig { audio: true, cursor: true, synthetic_size: (1280, 720), + synthetic_pattern: Pattern::Simple, restore_token: None, layers: Vec::new(), } @@ -296,7 +299,7 @@ impl Streamer { let (screen, frames, restore_token): (Box, _, _) = match &config.source { SourceId::Synthetic => { let (w, h) = config.synthetic_size; - let mut screen = SyntheticScreen::new(w, h); + let mut screen = SyntheticScreen::with_pattern(w, h, config.synthetic_pattern); let frames = screen.start(&SourceId::Synthetic, &options).await?; (Box::new(screen), frames, None) } diff --git a/crates/voelin-media/src/capture/synthetic.rs b/crates/voelin-media/src/capture/synthetic.rs index 63f8618..4f6eb18 100644 --- a/crates/voelin-media/src/capture/synthetic.rs +++ b/crates/voelin-media/src/capture/synthetic.rs @@ -1,7 +1,8 @@ -//! Synthetic sources for tests and `--synthetic` streaming: an animated test -//! pattern (a rectangle moving over a flat background, plus a frame counter) -//! and a sine tone. +//! Synthetic sources for tests, benchmarks and `--synthetic` streaming: an +//! animated test pattern (a rectangle moving over a flat background, or over +//! a desktop-like picture, plus a frame counter) and a sine tone. +use std::sync::Arc; use std::time::Duration; use crate::capture::{ @@ -32,16 +33,224 @@ const DIGITS: [[u8; 5]; 10] = [ [7, 5, 7, 1, 7], ]; +/// What the test pattern shows. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub enum Pattern { + /// A flat background, the moving rectangle and a frame counter: cheap to + /// encode and easy to check after decoding. + #[default] + Simple, + /// Like a desktop with a code editor: a title bar with a gradient, a side + /// bar, lines of coloured text in a document that scrolls three pixels + /// per frame, a status bar, and the moving rectangle and frame counter on + /// top. Costs an encoder about as much as real screen content (for + /// benchmarks). + Desktop, +} + +/// A rectangle: `(x, y, width, height)`. +type Rect = (usize, usize, usize, usize); + +fn bgra(c: [u8; 3]) -> [u8; 4] { + [c[2], c[1], c[0], 255] +} + +/// Fill a rectangle of a BGRA image (`width` pixels per row), clipped. +fn fill(data: &mut [u8], width: usize, rect: Rect, color: [u8; 3]) { + let rows = data.len() / (width * 4).max(1); + let (x0, y0, w, h) = rect; + let x1 = (x0 + w).min(width); + if x0 >= x1 { + return; + } + let px = bgra(color); + for y in y0..(y0 + h).min(rows) { + for d in data[(y * width + x0) * 4..(y * width + x1) * 4].chunks_exact_mut(4) { + d.copy_from_slice(&px); + } + } +} + +/// Draw one 3x5 glyph at `scale` pixels per dot. +fn glyph( + data: &mut [u8], + width: usize, + at: (usize, usize), + scale: usize, + bitmap: [u8; 5], + color: [u8; 3], +) { + for (row, bits) in bitmap.iter().enumerate() { + for col in 0..3 { + if bits & (4 >> col) != 0 { + fill(data, width, (at.0 + col * scale, at.1 + row * scale, scale, scale), color); + } + } + } +} + +/// Draw the decimal digits of `n`. +fn number(data: &mut [u8], width: usize, at: (usize, usize), scale: usize, n: u64, color: [u8; 3]) { + let mut digits = [0u8; 20]; + let (mut rest, mut len) = (n, 0); + loop { + digits[len] = (rest % 10) as u8; + len += 1; + rest /= 10; + if rest == 0 { + break; + } + } + for i in 0..len { + let bitmap = DIGITS[usize::from(digits[len - 1 - i])]; + glyph(data, width, (at.0 + i * 4 * scale, at.1), scale, bitmap, color); + } +} + +/// A small deterministic generator (xorshift64). +struct Rng(u64); + +impl Rng { + fn below(&mut self, n: usize) -> usize { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + (self.0 % n.max(1) as u64) as usize + } +} + +/// Lines of "code" in `area`: words of glyphs in the palette's colours, +/// indented, some lines empty. +fn text_lines( + data: &mut [u8], + width: usize, + area: Rect, + scale: usize, + palette: &[[u8; 3]], + rng: &mut Rng, +) { + let (ax, ay, aw, ah) = area; + let (advance, pitch) = (4 * scale, 8 * scale); + let columns = aw.saturating_sub(2 * advance) / advance; + let mut y = ay + 2 * scale; + while columns > 0 && y + pitch <= ay + ah { + let indent = rng.below(4) * 2; + let end = if rng.below(6) == 0 { 0 } else { indent + 4 + rng.below(columns) }; + let mut col = indent; + while col < end.min(columns) { + let word = 2 + rng.below(8); + let color = palette[rng.below(palette.len())]; + for _ in 0..word.min(columns - col) { + let x = ax + advance + col * advance; + glyph(data, width, (x, y), scale, DIGITS[rng.below(10)], color); + col += 1; + } + col += 1; + } + y += pitch; + } +} + +/// The parts of [`Pattern::Desktop`] that do not change, rendered once: the +/// page, and the document that scrolls through the editor area. +struct Desktop { + page: Vec, + editor: Rect, + /// `editor.2` pixels wide, twice the editor's height (it wraps around). + document: Vec, + document_rows: usize, +} + +impl Desktop { + fn render(width: usize, height: usize) -> Self { + let mut rng = Rng(0x9e37_79b9_7f4a_7c15); + let scale = (height / 540).max(1); + let mut page = vec![0; width * height * 4]; + let title = (height / 20).max(4); + let status = (height / 40).max(2); + let side = width / 5; + // Title bar: a vertical gradient with tabs. + for y in 0..title { + let t = y * 255 / title; + let c = [(40 + t / 8) as u8, (60 + t / 6) as u8, (110 + t / 4) as u8]; + fill(&mut page, width, (0, y, width, 1), c); + } + for tab in 0..6 { + let tab = (side + tab * width / 8, title / 3, width / 9, title - title / 3); + fill(&mut page, width, tab, [30, 30, 30]); + text_lines(&mut page, width, tab, scale, &[[200, 200, 200]], &mut rng); + } + // Side bar with a file list, status bar. + let sidebar = (0, title, side, height - title - status); + fill(&mut page, width, sidebar, [37, 37, 38]); + let palette = [[204, 204, 204], [150, 150, 150], [230, 200, 120]]; + text_lines(&mut page, width, sidebar, scale, &palette, &mut rng); + fill(&mut page, width, (0, height - status, width, status), [0, 122, 204]); + // The editor's document. + let editor = (side, title, width - side, height - title - status); + let document_rows = editor.3 * 2; + let mut document = vec![0; editor.2 * document_rows * 4]; + fill(&mut document, editor.2, (0, 0, editor.2, document_rows), [30, 30, 30]); + let palette = + [[212, 212, 212], [86, 156, 214], [206, 145, 120], [106, 153, 85], [197, 134, 192]]; + text_lines( + &mut document, + editor.2, + (0, 0, editor.2, document_rows), + scale, + &palette, + &mut rng, + ); + Self { page, editor, document, document_rows } + } + + /// The page with the document scrolled by `offset` rows. + fn draw(&self, out: &mut [u8], width: usize, offset: usize) { + out[..self.page.len()].copy_from_slice(&self.page); + let (ex, ey, ew, eh) = self.editor; + for row in 0..eh { + let src = (offset + row) % self.document_rows * ew * 4; + let dst = ((ey + row) * width + ex) * 4; + out[dst..dst + ew * 4].copy_from_slice(&self.document[src..src + ew * 4]); + } + } +} + /// The test pattern as a [`ScreenCapture`] backend. pub struct SyntheticScreen { width: u32, height: u32, + pattern: Pattern, + desktop: Option>, worker: Option, } impl SyntheticScreen { pub fn new(width: u32, height: u32) -> Self { - Self { width: width.max(16), height: height.max(16), worker: None } + Self::with_pattern(width, height, Pattern::Simple) + } + + /// A test pattern of another kind. + pub fn with_pattern(width: u32, height: u32, pattern: Pattern) -> Self { + let (width, height) = (width.max(16), height.max(16)); + let desktop = (pattern == Pattern::Desktop) + .then(|| Arc::new(Desktop::render(width as usize, height as usize))); + Self { width, height, pattern, desktop, worker: None } + } + + pub fn pattern(&self) -> Pattern { + self.pattern + } + + /// Another source drawing the same pattern. + fn same_pattern(&self) -> Self { + Self { + width: self.width, + height: self.height, + pattern: self.pattern, + desktop: self.desktop.clone(), + worker: None, + } } /// The moving rectangle in frame `n`: `(x, y, width, height)`. @@ -55,40 +264,38 @@ impl SyntheticScreen { (x as u32, (self.height - rh) / 2, rw, rh) } - /// Frame `n` as BGRA, stamped `n / fps` seconds. - pub fn frame(&self, n: u64, fps: u32) -> VideoFrame { + /// Draw frame `n` as BGRA (`width * 4` bytes per row) into `out`, reusing + /// its memory. + pub fn render(&self, n: u64, out: &mut Vec) { let (w, h) = (self.width as usize, self.height as usize); - let mut data = vec![0; w * h * 4]; - let bgra = |c: [u8; 3]| [c[2], c[1], c[0], 255]; - for px in data.chunks_exact_mut(4) { - px.copy_from_slice(&bgra(BACKGROUND)); - } - let mut fill = |x0: usize, y0: usize, rw: usize, rh: usize, c: [u8; 3]| { - for y in y0..(y0 + rh).min(h) { - for x in x0..(x0 + rw).min(w) { - data[(y * w + x) * 4..][..4].copy_from_slice(&bgra(c)); + out.resize(w * h * 4, 0); + match &self.desktop { + Some(desktop) => desktop.draw(out, w, n as usize * 3), + None => { + // One row, then copies of it. + let px = bgra(BACKGROUND); + for d in out[..w * 4].chunks_exact_mut(4) { + d.copy_from_slice(&px); + } + let (first, rest) = out.split_at_mut(w * 4); + for row in rest.chunks_exact_mut(w * 4) { + row.copy_from_slice(first); } } - }; + } let (rx, ry, rw, rh) = self.rect(n); - fill(rx as usize, ry as usize, rw as usize, rh as usize, RECT_COLOR); - + fill(out, w, (rx as usize, ry as usize, rw as usize, rh as usize), RECT_COLOR); // Frame counter in the top-left corner. let scale = (h / 48).max(1); - for (i, digit) in n.to_string().bytes().enumerate() { - let bitmap = DIGITS[usize::from(digit - b'0')]; - let x0 = scale * 2 + i * 4 * scale; - for (row, bits) in bitmap.iter().enumerate() { - for col in 0..3 { - if bits & (4 >> col) != 0 { - let (x, y) = (x0 + col * scale, scale * 2 + row * scale); - fill(x, y, scale, scale, TEXT_COLOR); - } - } - } - } + number(out, w, (scale * 2, scale * 2), scale, n, TEXT_COLOR); + } + + /// Frame `n` as BGRA, stamped `n / fps` seconds. + pub fn frame(&self, n: u64, fps: u32) -> VideoFrame { + let mut data = Vec::new(); + self.render(n, &mut data); let timestamp = Duration::from_secs(n) / fps.max(1); - VideoFrame::from_bgra(self.width, self.height, w * 4, data) + VideoFrame::from_bgra(self.width, self.height, self.width as usize * 4, data) .expect("pattern buffer matches its size") .with_timestamp(timestamp) } @@ -122,7 +329,7 @@ impl ScreenCapture for SyntheticScreen { } self.stop(); let (tx, rx) = frame_channel(options.queue); - let pattern = SyntheticScreen::new(self.width, self.height); + let pattern = self.same_pattern(); let fps = options.fps; self.worker = Some(Worker::spawn("voelin-synthetic-video", move |stop| { let mut ticker = Ticker::new(fps); @@ -225,6 +432,29 @@ mod tests { } } + #[test] + fn desktop_pattern_scrolls() { + let screen = SyntheticScreen::with_pattern(640, 360, Pattern::Desktop); + assert_eq!(screen.pattern(), Pattern::Desktop); + let (mut a, mut b) = (Vec::new(), Vec::new()); + screen.render(1, &mut a); + screen.render(2, &mut b); + assert_eq!(a.len(), 640 * 360 * 4); + // The editor (right of the side bar, below the title bar) scrolled. + let row = |data: &[u8], y: usize| data[(y * 640 + 200) * 4..(y * 640 + 600) * 4].to_vec(); + let differs = (40..340).any(|y| row(&a, y) != row(&b, y)); + assert!(differs); + // Lots of detail: many distinct colours in the editor. + let mut colours: Vec<&[u8]> = a.chunks_exact(4).collect(); + colours.sort_unstable(); + colours.dedup(); + assert!(colours.len() >= 8, "{} colours", colours.len()); + // Rendering reuses the buffer. + let capacity = a.capacity(); + screen.render(3, &mut a); + assert_eq!(a.capacity(), capacity); + } + #[test] fn sine_is_continuous() { let tone = SineSource::new(1000.0, 0.5); diff --git a/tools/voelinctl/src/alloc.rs b/tools/voelinctl/src/alloc.rs new file mode 100644 index 0000000..0af2263 --- /dev/null +++ b/tools/voelinctl/src/alloc.rs @@ -0,0 +1,51 @@ +//! The process's global allocator: the system allocator, counting +//! allocations (for `voelinctl stream bench`, which reports heap +//! allocations per frame). The count is one relaxed atomic add per +//! allocation. +#![allow(unsafe_code)] + +use std::alloc::{GlobalAlloc, Layout, System}; +use std::sync::atomic::{AtomicU64, Ordering}; + +static ALLOCATIONS: AtomicU64 = AtomicU64::new(0); +static BYTES: AtomicU64 = AtomicU64::new(0); + +/// Allocations (including reallocations) and bytes requested so far. +pub fn counts() -> (u64, u64) { + (ALLOCATIONS.load(Ordering::Relaxed), BYTES.load(Ordering::Relaxed)) +} + +pub struct Counting; + +fn count(size: usize) { + ALLOCATIONS.fetch_add(1, Ordering::Relaxed); + BYTES.fetch_add(size as u64, Ordering::Relaxed); +} + +// SAFETY: every method forwards to `System` with the caller's arguments +// unchanged, so `System`'s guarantees hold; counting touches only atomics +// and never allocates. +unsafe impl GlobalAlloc for Counting { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + count(layout.size()); + // SAFETY: forwarded unchanged (see above). + unsafe { System.alloc(layout) } + } + + unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { + count(layout.size()); + // SAFETY: forwarded unchanged. + unsafe { System.alloc_zeroed(layout) } + } + + unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { + count(new_size); + // SAFETY: forwarded unchanged. + unsafe { System.realloc(ptr, layout, new_size) } + } + + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { + // SAFETY: forwarded unchanged. + unsafe { System.dealloc(ptr, layout) } + } +} diff --git a/tools/voelinctl/src/bench.rs b/tools/voelinctl/src/bench.rs new file mode 100644 index 0000000..6637b1e --- /dev/null +++ b/tools/voelinctl/src/bench.rs @@ -0,0 +1,318 @@ +//! `voelinctl stream bench`: the streamer's capture → convert → encode +//! pipeline on the test pattern, without a server. Prints frame rates, bit +//! rates and heap allocations per frame in the steady state. + +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::time::{Duration, Instant}; + +use anyhow::{Context, Result, bail}; +use clap::{Args, Subcommand}; +use voelin_core::media::voelin_media::capture::SourceId; +use voelin_core::media::voelin_media::capture::synthetic::Pattern; +use voelin_core::media::voelin_media::{Codec, Codecs}; +use voelin_core::media::{MediaSink, Streamer, StreamerConfig}; +use voelin_stream::{EncodedFrame, LayerId, LayerSet, LayerSpec, MediaKind}; + +use crate::alloc; + +#[derive(Args, Debug)] +pub struct StreamToolArgs { + #[command(subcommand)] + command: StreamTool, +} + +#[derive(Subcommand, Debug)] +enum StreamTool { + /// Run the streamer's pipeline (capture → convert/scale → encode) on the + /// test pattern without a server; print per-stage and per-layer numbers + /// and heap allocations per frame. + Bench(BenchArgs), +} + +#[derive(Args, Debug)] +struct BenchArgs { + /// Size of the test pattern. + #[arg(long, default_value = "1920x1080")] + res: String, + /// Frame rate of the capture. + #[arg(long, default_value_t = 30)] + fps: u32, + /// Test pattern: `desktop` (text, a scrolling document; about as costly + /// as real screen content) or `simple` (a flat background). + #[arg(long, default_value = "desktop")] + pattern: String, + /// Video codec: vp8, vp9 or h264 (needs --openh264). + #[arg(long, default_value = "vp8")] + codec: String, + /// A simulcast layer, e.g. `scale=0.5,bitrate=1500k,fps=15` (keys: id, + /// scale, size=WxH, fps, bitrate, max, min, rid; bitrates in bit/s with + /// k/M suffixes); repeatable. Without it: one layer at --bitrate. + #[arg(long = "layer")] + layers: Vec, + /// Bitrate in kbit/s without --layer. + #[arg(long, default_value_t = 4608)] + bitrate: u32, + /// Measured time in seconds (after the warm-up). + #[arg(long, default_value_t = 10)] + seconds: u64, + /// Seconds to run before measuring. + #[arg(long, default_value_t = 2)] + warmup: u64, + /// Cisco's OpenH264 library, for --codec h264. + #[arg(long)] + openh264: Option, +} + +pub fn run(args: StreamToolArgs) -> Result<()> { + match args.command { + StreamTool::Bench(args) => bench(args), + } +} + +/// Frames and bytes the sink got for one layer. +#[derive(Default)] +struct LayerCount { + frames: AtomicU64, + keyframes: AtomicU64, + bytes: AtomicU64, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +struct LayerSnapshot { + frames: u64, + keyframes: u64, + bytes: u64, +} + +/// Counts what the streamer sends; asks for one keyframe per layer at the +/// start, like a new viewer. +struct BenchSink { + layers: Vec<(LayerId, LayerCount)>, + keyframe: AtomicBool, +} + +impl BenchSink { + fn snapshot(&self) -> Vec<(LayerId, LayerSnapshot)> { + self.layers + .iter() + .map(|(id, c)| { + let snapshot = LayerSnapshot { + frames: c.frames.load(Ordering::Relaxed), + keyframes: c.keyframes.load(Ordering::Relaxed), + bytes: c.bytes.load(Ordering::Relaxed), + }; + (*id, snapshot) + }) + .collect() + } +} + +impl MediaSink for BenchSink { + fn send(&self, frame: EncodedFrame) -> bool { + if frame.kind != MediaKind::Video { + return true; + } + if let Some((_, count)) = self.layers.iter().find(|(id, _)| *id == frame.layer) { + count.frames.fetch_add(1, Ordering::Relaxed); + count.keyframes.fetch_add(u64::from(frame.keyframe), Ordering::Relaxed); + count.bytes.fetch_add(frame.data.len() as u64, Ordering::Relaxed); + } + true + } + + fn take_keyframe_request(&self) -> bool { + self.keyframe.swap(false, Ordering::Relaxed) + } + + fn take_layer_keyframes(&self, layers: &mut LayerSet) { + if self.keyframe.swap(false, Ordering::Relaxed) { + for (id, _) in &self.layers { + layers.insert(*id); + } + } + } +} + +/// `x`. +fn parse_size(size: &str) -> Result<(u32, u32)> { + let parsed = size.split_once('x').and_then(|(w, h)| Some((w.parse().ok()?, h.parse().ok()?))); + parsed.with_context(|| format!("bad size {size:?}, expected e.g. 1280x720")) +} + +/// Bit/s with an optional `k` / `M` suffix. +fn parse_bitrate(value: &str) -> Result { + let (number, factor) = match value.as_bytes().last() { + Some(b'k' | b'K') => (&value[..value.len() - 1], 1_000.0), + Some(b'm' | b'M') => (&value[..value.len() - 1], 1_000_000.0), + _ => (value, 1.0), + }; + let number: f64 = number.parse().with_context(|| format!("bad bitrate {value:?}"))?; + Ok((number * factor) as u64) +} + +/// `key=value,...` (see `--layer`). +fn parse_layer(spec: &str, index: usize) -> Result { + let mut layer = LayerSpec::single(1_000_000); + layer.id = index as LayerId; + for part in spec.split(',').filter(|p| !p.is_empty()) { + let (key, value) = part.split_once('=').with_context(|| format!("{part:?}: no `=`"))?; + match key { + "id" => layer.id = value.parse().context("layer id")?, + "scale" => layer.scale = value.parse().context("layer scale")?, + "size" => layer.size = Some(parse_size(value)?), + "fps" => layer.max_fps = Some(value.parse().context("layer fps")?), + "bitrate" => layer.bitrate = parse_bitrate(value)?, + "max" => layer.max_bitrate = Some(parse_bitrate(value)?), + "min" => layer.min_bitrate = parse_bitrate(value)?, + "rid" => layer.rid = Some(value.to_owned()), + _ => bail!("unknown layer key {key:?} in {spec:?}"), + } + } + Ok(layer) +} + +/// CPU time of this process (user + system), Linux only. +fn cpu_time() -> Option { + let stat = std::fs::read_to_string("/proc/self/stat").ok()?; + // Fields after the command name, which is in parentheses. + let rest = stat.rsplit_once(')')?.1; + let fields: Vec<&str> = rest.split_whitespace().collect(); + // utime and stime are fields 14 and 15 (1-based), in clock ticks of + // 1/100 s on Linux. + let ticks: u64 = fields.get(11)?.parse::().ok()? + fields.get(12)?.parse::().ok()?; + Some(Duration::from_millis(ticks * 10)) +} + +struct Sample { + at: Instant, + allocations: u64, + bytes: u64, + cpu: Option, + layers: Vec<(LayerId, LayerSnapshot)>, + sent: u64, +} + +fn sample(sink: &BenchSink, streamer: &Streamer) -> Sample { + let (allocations, bytes) = alloc::counts(); + Sample { + at: Instant::now(), + allocations, + bytes, + cpu: cpu_time(), + layers: sink.snapshot(), + sent: streamer.stats().video_frames, + } +} + +fn bench(args: BenchArgs) -> Result<()> { + let (width, height) = parse_size(&args.res)?; + let pattern = match args.pattern.as_str() { + "desktop" => Pattern::Desktop, + "simple" => Pattern::Simple, + other => bail!("unknown pattern {other:?}: desktop or simple"), + }; + let codec: Codec = args.codec.parse().map_err(|e| anyhow::anyhow!("{e}"))?; + let mut codecs = Codecs::new(); + if let Some(path) = &args.openh264 { + let library = voelin_core::media::voelin_media::codec::h264::OpenH264::load(path) + .context("OpenH264")?; + codecs = codecs.with_openh264(library); + } + let layers = args + .layers + .iter() + .enumerate() + .map(|(i, spec)| parse_layer(spec, i)) + .collect::>>()?; + let ids: Vec = + if layers.is_empty() { vec![0] } else { layers.iter().map(|l| l.id).collect() }; + let config = StreamerConfig { + source: SourceId::Synthetic, + synthetic_size: (width, height), + synthetic_pattern: pattern, + fps: args.fps, + bitrate_kbps: args.bitrate, + codec, + audio: false, + layers: layers.clone(), + ..StreamerConfig::default() + }; + let runtime = tokio::runtime::Runtime::new()?; + let streamer = runtime.block_on(Streamer::start(&codecs, config)).context("streamer")?; + let sink = Arc::new(BenchSink { + layers: ids.iter().map(|id| (*id, LayerCount::default())).collect(), + keyframe: AtomicBool::new(true), + }); + streamer.attach(sink.clone()); + println!( + "{width}x{height} {} test pattern at {} fps, {codec}, {} layer(s), {} s after {} s warm-up", + args.pattern, + args.fps, + ids.len(), + args.seconds, + args.warmup + ); + std::thread::sleep(Duration::from_secs(args.warmup)); + let start = sample(&sink, &streamer); + std::thread::sleep(Duration::from_secs(args.seconds)); + let end = sample(&sink, &streamer); + let stats = streamer.stats(); + drop(streamer); + + let secs = (end.at - start.at).as_secs_f64(); + let mut output_frames = 0; + for ((id, a), (_, b)) in start.layers.iter().zip(&end.layers) { + let frames = b.frames - a.frames; + output_frames += frames; + let spec = layers.iter().find(|l| l.id == *id); + let size = spec.map_or((width, height), |l| l.output_size(width, height)); + println!( + "layer {id}: {}x{} {:.1} fps {:.0} kbit/s {} keyframes", + size.0, + size.1, + frames as f64 / secs, + (b.bytes - a.bytes) as f64 * 8.0 / secs / 1000.0, + b.keyframes - a.keyframes, + ); + } + if let Some(e) = &stats.error { + println!("encoder error: {e}"); + } + if let (Some(a), Some(b)) = (start.cpu, end.cpu) { + println!("cpu: {:.2} cores", (b - a).as_secs_f64() / secs); + } + let allocations = end.allocations - start.allocations; + let bytes = end.bytes - start.bytes; + let sent = (end.sent - start.sent).max(1); + println!( + "heap: {allocations} allocations ({:.1} per sent frame, {:.0} bytes per sent frame)", + allocations as f64 / sent as f64, + bytes as f64 / sent as f64, + ); + if output_frames == 0 { + bail!("no frames were encoded"); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn layer_specs() { + let layer = parse_layer("scale=0.5,bitrate=1.5M,fps=15,rid=m", 2).unwrap(); + assert_eq!(layer.id, 2); + assert_eq!(layer.scale, 0.5); + assert_eq!(layer.bitrate, 1_500_000); + assert_eq!(layer.max_fps, Some(15)); + assert_eq!(layer.rid.as_deref(), Some("m")); + let layer = parse_layer("id=7,size=640x360,bitrate=500k,max=800k,min=300k", 0).unwrap(); + assert_eq!((layer.id, layer.size), (7, Some((640, 360)))); + assert_eq!((layer.max_bitrate, layer.min_bitrate), (Some(800_000), 300_000)); + assert!(parse_layer("speed=3", 0).is_err()); + assert!(parse_layer("scale", 0).is_err()); + } +} diff --git a/tools/voelinctl/src/main.rs b/tools/voelinctl/src/main.rs index b23cef5..6b7fdb6 100644 --- a/tools/voelinctl/src/main.rs +++ b/tools/voelinctl/src/main.rs @@ -1,5 +1,7 @@ //! `voelinctl`: headless TeamSpeak 3/6 client for development and integration tests. +mod alloc; +mod bench; mod gateway; mod identity; mod observe; @@ -17,6 +19,10 @@ use anyhow::Result; use clap::{Args, Parser, Subcommand}; use tracing_subscriber::EnvFilter; +/// Counts heap allocations for `stream bench`. +#[global_allocator] +static ALLOCATOR: alloc::Counting = alloc::Counting; + #[derive(Parser, Debug)] #[command(version, about)] struct Cli { @@ -46,6 +52,8 @@ enum Command { Relay(observe::RelayArgs), /// Use a tsgw gateway as a user: presence, chat, history. Gateway(gateway::GatewayArgs), + /// Stream tools that need no server (`bench`). + Stream(bench::StreamToolArgs), } #[derive(Subcommand, Debug)] @@ -208,6 +216,7 @@ fn main() -> Result<()> { Command::Observe(args) => tokio::runtime::Runtime::new()?.block_on(observe::observe(args)), Command::Relay(args) => tokio::runtime::Runtime::new()?.block_on(observe::relay(args)), Command::Gateway(args) => tokio::runtime::Runtime::new()?.block_on(gateway::run(args)), + Command::Stream(args) => bench::run(args), } }