Nightly's clippy flagged the two chunks_exact(4) loops of common/src/bgra.rs (chunks_exact_to_as_chunks): both now use as_chunks::<4>() and as_chunks_mut::<4>() (stable since 1.88). Behind them, because clippy stops at the first crate that fails, it flags the raw source's `for n in 0u64..` in video/src/main.rs (for_unbounded_range): now `0..=u64::MAX`, the same loop. `cargo clippy --locked --all-targets -- -D warnings` is clean on 1.95.0 and on nightly 2026-10-24 (through shell.sh); the README and the report's clippy sentence say so. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
353 lines
11 KiB
Rust
353 lines
11 KiB
Rust
//! Spike 1, the video path (plan section 6 step 1): the synthetic test
|
|
//! pattern through the real encoder and decoder (`LocalPreview`, as
|
|
//! `voelin-ui`'s `Video::demo` runs it) or straight from memory (`raw`),
|
|
//! converted to BGRA on a thread of its own (`frames`, the port of
|
|
//! `video.rs`' delivery) and shown with `img()` in a GPUI window, measured
|
|
//! once a second (`spike_common::meter`). `static` is the control: one
|
|
//! picture, uploaded once, the window repainted every frame.
|
|
//!
|
|
//! ```text
|
|
//! spike-video [--mode pipeline|raw|static] [--size 2560x1440] [--fps 60]
|
|
//! [--bitrate KBPS (0: automatic)] [--convert bgra|rgba]
|
|
//! [--no-drop] [--window WxH] [--seconds 60] [--warmup 10]
|
|
//! [--out FILE.jsonl]
|
|
//! spike-video --bench [--iterations 200]
|
|
//! ```
|
|
//!
|
|
//! `--no-drop` leaves every picture in GPUI's sprite atlas (the negative
|
|
//! control for `cx.drop_image`). See the README for the measurements.
|
|
|
|
mod convert;
|
|
mod frames;
|
|
|
|
use std::path::PathBuf;
|
|
use std::sync::atomic::AtomicU64;
|
|
use std::sync::{Arc, Mutex, PoisonError};
|
|
use std::time::{Duration, Instant};
|
|
|
|
use futures::StreamExt as _;
|
|
use gpui_kit::{
|
|
App, AppContext as _, Bounds, Context, ImageSource, IntoElement, ObjectFit, ParentElement,
|
|
Render, RenderImage, SharedString, Styled, StyledImage, TitlebarOptions, Window, WindowBounds,
|
|
WindowOptions, div, img, px, rgb, size,
|
|
};
|
|
use serde_json::json;
|
|
use spike_common::meter::{Counter, Meter};
|
|
use voelin_core::media::voelin_media::capture::SourceId;
|
|
use voelin_core::media::voelin_media::capture::synthetic::{Pattern, SyntheticScreen};
|
|
use voelin_core::media::voelin_media::{Codecs, VideoFrame, convert as media_convert};
|
|
use voelin_core::media::{Latest, LocalPreview, StreamerConfig};
|
|
|
|
use crate::convert::Order;
|
|
|
|
/// Where frames come from.
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
enum Mode {
|
|
/// `LocalPreview`: capture, VP8 encoder, decoder (what the Slint demo
|
|
/// shows).
|
|
Pipeline,
|
|
/// Decoded-looking I420 frames from memory, paced at `fps`: only the
|
|
/// conversion and GPUI, so a frame rate below the source's is theirs.
|
|
Raw,
|
|
/// One picture, converted and uploaded once, the window repainted every
|
|
/// frame (`request_animation_frame`): what GPUI and the renderer manage
|
|
/// with no new picture to upload, the most a texture kept across frames
|
|
/// could give.
|
|
Static,
|
|
}
|
|
|
|
struct Config {
|
|
mode: Mode,
|
|
size: (u32, u32),
|
|
fps: u32,
|
|
bitrate_kbps: u32,
|
|
order: Order,
|
|
drop_images: bool,
|
|
window: (u32, u32),
|
|
seconds: u64,
|
|
warmup: u64,
|
|
out: Option<PathBuf>,
|
|
}
|
|
|
|
impl Config {
|
|
fn from_args() -> anyhow::Result<Self> {
|
|
use spike_common::{arg, flag, parse_size};
|
|
let size = parse_size(&arg("size").unwrap_or_else(|| "2560x1440".into()))
|
|
.ok_or_else(|| anyhow::anyhow!("--size WIDTHxHEIGHT"))?;
|
|
let window = match arg("window") {
|
|
Some(w) => parse_size(&w).ok_or_else(|| anyhow::anyhow!("--window WIDTHxHEIGHT"))?,
|
|
None => size,
|
|
};
|
|
Ok(Self {
|
|
mode: match arg("mode").as_deref() {
|
|
None | Some("pipeline") => Mode::Pipeline,
|
|
Some("raw") => Mode::Raw,
|
|
Some("static") => Mode::Static,
|
|
Some(other) => anyhow::bail!("--mode pipeline|raw|static, not {other}"),
|
|
},
|
|
size,
|
|
fps: arg("fps").map_or(Ok(60), |v| v.parse())?,
|
|
bitrate_kbps: arg("bitrate").map_or(Ok(0), |v| v.parse())?,
|
|
order: match arg("convert").as_deref() {
|
|
None | Some("bgra") => Order::Bgra,
|
|
Some("rgba") => Order::Rgba,
|
|
Some(other) => anyhow::bail!("--convert bgra|rgba, not {other}"),
|
|
},
|
|
drop_images: !flag("no-drop"),
|
|
window,
|
|
seconds: arg("seconds").map_or(Ok(60), |v| v.parse())?,
|
|
warmup: arg("warmup").map_or(Ok(10), |v| v.parse())?,
|
|
out: arg("out").map(PathBuf::from),
|
|
})
|
|
}
|
|
|
|
fn json(&self) -> serde_json::Value {
|
|
json!({
|
|
"spike": "video",
|
|
"mode": format!("{:?}", self.mode),
|
|
"size": format!("{}x{}", self.size.0, self.size.1),
|
|
"fps": self.fps,
|
|
"bitrate_kbps": self.bitrate_kbps,
|
|
"convert": format!("{:?}", self.order),
|
|
"drop_image": self.drop_images,
|
|
"window": format!("{}x{}", self.window.0, self.window.1),
|
|
"display": std::env::var("DISPLAY").ok(),
|
|
"vk_driver_files": std::env::var("VK_DRIVER_FILES").ok(),
|
|
})
|
|
}
|
|
}
|
|
|
|
/// The window: the newest picture, and a line about the run.
|
|
struct Viewer {
|
|
pictures: Arc<Latest<Arc<RenderImage>>>,
|
|
current: Option<Arc<RenderImage>>,
|
|
drop_images: bool,
|
|
/// Repaint every frame (`Mode::Static`).
|
|
repaint: bool,
|
|
shown: Counter,
|
|
renders: Counter,
|
|
label: SharedString,
|
|
}
|
|
|
|
impl Render for Viewer {
|
|
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
|
self.renders.incr();
|
|
if self.repaint {
|
|
window.request_animation_frame();
|
|
}
|
|
if let Some(next) = self.pictures.take() {
|
|
if let Some(previous) = self.current.replace(next)
|
|
&& self.drop_images
|
|
{
|
|
// Out of every window's sprite atlas; without this the atlas
|
|
// keeps every picture ever shown.
|
|
cx.drop_image(previous, Some(window));
|
|
}
|
|
self.shown.incr();
|
|
}
|
|
let picture = match &self.current {
|
|
Some(picture) => img(ImageSource::Render(picture.clone()))
|
|
.size_full()
|
|
.object_fit(ObjectFit::Contain)
|
|
.into_any_element(),
|
|
None => div().child("Waiting for the first picture…").into_any_element(),
|
|
};
|
|
div()
|
|
.size_full()
|
|
.bg(rgb(0x000000))
|
|
.text_color(rgb(0xffffff))
|
|
.child(picture)
|
|
.child(div().absolute().top_2().left_2().child(self.label.clone()))
|
|
}
|
|
}
|
|
|
|
/// The view, woken by the converter through a channel: GPUI's `AsyncApp`
|
|
/// is not `Send`, so other threads reach the UI thread this way.
|
|
fn open_viewer(
|
|
cx: &mut App,
|
|
config: &Config,
|
|
pictures: Arc<Latest<Arc<RenderImage>>>,
|
|
counters: (Counter, Counter),
|
|
wakes: futures::channel::mpsc::UnboundedReceiver<()>,
|
|
) {
|
|
let (w, h) = config.window;
|
|
let label: SharedString = format!(
|
|
"{:?} {}x{} at {} fps, {:?}{}",
|
|
config.mode,
|
|
config.size.0,
|
|
config.size.1,
|
|
config.fps,
|
|
config.order,
|
|
if config.drop_images { "" } else { ", no drop_image" }
|
|
)
|
|
.into();
|
|
let drop_images = config.drop_images;
|
|
let repaint = config.mode == Mode::Static;
|
|
let options = WindowOptions {
|
|
window_bounds: Some(WindowBounds::Windowed(Bounds::centered(
|
|
None,
|
|
size(px(w as f32), px(h as f32)),
|
|
cx,
|
|
))),
|
|
titlebar: Some(TitlebarOptions { title: Some("spike-video".into()), ..Default::default() }),
|
|
// A video plays at its rate whether the window has focus or not.
|
|
inactive_frame_interval: None,
|
|
..Default::default()
|
|
};
|
|
cx.open_window(options, move |_, cx| {
|
|
cx.new(move |cx| {
|
|
let mut wakes = wakes;
|
|
cx.spawn(async move |this, cx| {
|
|
while wakes.next().await.is_some() {
|
|
if this.update(cx, |_, cx| cx.notify()).is_err() {
|
|
break;
|
|
}
|
|
}
|
|
})
|
|
.detach();
|
|
Viewer {
|
|
pictures,
|
|
current: None,
|
|
drop_images,
|
|
repaint,
|
|
shown: counters.0,
|
|
renders: counters.1,
|
|
label,
|
|
}
|
|
})
|
|
})
|
|
.expect("a window");
|
|
}
|
|
|
|
/// The raw source: `fps` frames a second from a ring of pictures converted
|
|
/// to I420 once, handed to `on_frame` on a thread of its own.
|
|
fn start_raw(config: &Config, mut on_frame: impl FnMut(Arc<VideoFrame>) + Send + 'static) {
|
|
let (w, h, fps) = (config.size.0, config.size.1, config.fps.max(1));
|
|
std::thread::Builder::new()
|
|
.name("spike-raw-source".into())
|
|
.spawn(move || {
|
|
let screen = SyntheticScreen::with_pattern(w, h, Pattern::Simple);
|
|
let ring: Vec<Arc<VideoFrame>> = (0..30u64)
|
|
.map(|n| {
|
|
let picture = screen.frame(n, fps);
|
|
Arc::new(media_convert::to_i420(&picture).expect("I420").into_owned())
|
|
})
|
|
.collect();
|
|
let start = Instant::now();
|
|
for n in 0..=u64::MAX {
|
|
let due = start + Duration::from_secs(n) / fps;
|
|
if let Some(wait) = due.checked_duration_since(Instant::now()) {
|
|
std::thread::sleep(wait);
|
|
}
|
|
on_frame(ring[(n % ring.len() as u64) as usize].clone());
|
|
}
|
|
})
|
|
.expect("a source thread");
|
|
}
|
|
|
|
fn main() -> anyhow::Result<()> {
|
|
spike_common::init_logging();
|
|
if spike_common::flag("bench") {
|
|
convert::bench(spike_common::arg("iterations").map_or(Ok(200), |v| v.parse())?);
|
|
return Ok(());
|
|
}
|
|
let config = Config::from_args()?;
|
|
let runtime = tokio::runtime::Builder::new_multi_thread().enable_all().build()?;
|
|
let pictures: Arc<Latest<Arc<RenderImage>>> = Arc::new(Latest::new());
|
|
let counts = frames::Counts::default();
|
|
let (shown, renders) = (Counter::default(), Counter::default());
|
|
let (captured, encoded, decoded, skipped) =
|
|
(Counter::default(), Counter::default(), Counter::default(), Counter::default());
|
|
let (wake_tx, wakes) = futures::channel::mpsc::unbounded::<()>();
|
|
let on_frame = frames::deliver(pictures.clone(), config.order, counts.clone(), move || {
|
|
let _ = wake_tx.unbounded_send(());
|
|
});
|
|
let preview: Arc<Mutex<Option<LocalPreview>>> = Arc::default();
|
|
match config.mode {
|
|
Mode::Raw => start_raw(&config, on_frame),
|
|
Mode::Static => {
|
|
// Converted here, before the window opens: its first frame takes it.
|
|
let (w, h) = config.size;
|
|
let picture = SyntheticScreen::with_pattern(w, h, Pattern::Simple).frame(1, config.fps);
|
|
let i420 = media_convert::to_i420(&picture)?.into_owned();
|
|
pictures.put(spike_common::bgra::picture(&i420).map_err(anyhow::Error::msg)?);
|
|
drop(on_frame);
|
|
}
|
|
Mode::Pipeline => {
|
|
let streamer = StreamerConfig {
|
|
source: SourceId::Synthetic,
|
|
synthetic_size: config.size,
|
|
fps: config.fps,
|
|
bitrate_kbps: config.bitrate_kbps,
|
|
..StreamerConfig::default()
|
|
};
|
|
let codecs = Arc::new(Codecs::new());
|
|
let slot = preview.clone();
|
|
runtime.spawn(async move {
|
|
match LocalPreview::start(codecs, streamer, on_frame).await {
|
|
Ok(p) => *slot.lock().unwrap_or_else(PoisonError::into_inner) = Some(p),
|
|
Err(e) => {
|
|
log::error!("the preview failed: {e}");
|
|
std::process::exit(3);
|
|
}
|
|
}
|
|
});
|
|
// The encoder's and decoder's own counts, for the meter.
|
|
let (slot, captured, encoded, decoded, skipped) = (
|
|
preview.clone(),
|
|
captured.clone(),
|
|
encoded.clone(),
|
|
decoded.clone(),
|
|
skipped.clone(),
|
|
);
|
|
std::thread::Builder::new().name("spike-stats".into()).spawn(move || {
|
|
let mut logged = false;
|
|
loop {
|
|
std::thread::sleep(Duration::from_millis(250));
|
|
let guard = slot.lock().unwrap_or_else(PoisonError::into_inner);
|
|
let Some(p) = guard.as_ref() else { continue };
|
|
let s = p.streamer().stats();
|
|
let d = p.stats();
|
|
captured.set(s.captured_frames);
|
|
encoded.set(s.video_frames);
|
|
decoded.set(d.decoded);
|
|
skipped.set(d.skipped);
|
|
if !logged && d.decoded > 0 {
|
|
log::info!(
|
|
"encoder {:?} {:?}, decoder {:?}",
|
|
s.codec,
|
|
s.layers.first().map(|l| (l.width, l.height)),
|
|
d.decoder
|
|
);
|
|
logged = true;
|
|
}
|
|
}
|
|
})?;
|
|
}
|
|
}
|
|
let meter = Meter {
|
|
config: config.json(),
|
|
counters: vec![
|
|
("captured", captured),
|
|
("encoded", encoded),
|
|
("decoded", decoded),
|
|
("decode_skipped", skipped),
|
|
("arrived", counts.arrived.clone()),
|
|
("converted", counts.converted.clone()),
|
|
("convert_us", counts.convert_us.clone()),
|
|
("shown", shown.clone()),
|
|
("renders", renders.clone()),
|
|
],
|
|
gauges: vec![],
|
|
warmup: Duration::from_secs(config.warmup),
|
|
duration: Duration::from_secs(config.seconds),
|
|
out: config.out.clone(),
|
|
};
|
|
meter.start(Arc::new(AtomicU64::new(0)));
|
|
gpui_kit::application().run(move |cx| {
|
|
open_viewer(cx, &config, pictures, (shown, renders), wakes);
|
|
});
|
|
drop(runtime);
|
|
Ok(())
|
|
}
|