spikes/gpui/video: spike 1, decoded video as BGRA RenderImages in img()
video.rs' delivery (deliver, FrameSlot, Handoff, Buffers; video.rs:360-480) ported to GPUI: the decoder hands over its newest frame only, a converter thread turns it into an Arc<RenderImage> (BGRA, spike_common::bgra), the window takes the newest from a Latest in render and drops the one it replaces from every window's atlas (cx.drop_image). A RenderImage owns its pixels with no way back to them, so Buffers' reuse cannot be ported. Sources: --mode pipeline is LocalPreview with SourceId::Synthetic through the real VP8 encoder and decoder, as Video::demo; --mode raw hands I420 frames from memory to the converter; --mode static (added in this attempt) is the control: one picture, uploaded once, the window repainted every frame. --convert rgba measures voelin-media's conversion in place, --no-drop is the negative control for drop_image, --bench times RGBA against BGRA. measure.sh runs every case on the headless display, with damage-count beside it and the Slint app's demo stream for comparison. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
c9859bcfb4
commit
fd421b9982
8 files changed
+3458
-29
No files matched your search
Generated
+2682
-28
File diff suppressed because it is too large.
Load diff
@@ -4,7 +4,7 @@
|
||||
# into the checkout's target directory (.cargo/config.toml).
|
||||
[workspace]
|
||||
resolver = "3"
|
||||
members = ["common"]
|
||||
members = ["common", "video"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.0.0"
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
[package]
|
||||
name = "spike-video"
|
||||
description = "Spike 1: decoded video frames shown with img() as BGRA RenderImages."
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1"
|
||||
gpui-kit = { workspace = true }
|
||||
log = { workspace = true }
|
||||
spike-common = { workspace = true }
|
||||
futures = "0.3"
|
||||
serde_json = "1"
|
||||
tokio = { version = "1", features = ["rt-multi-thread", "time"] }
|
||||
voelin-core = { workspace = true }
|
||||
voelin-media = { workspace = true }
|
||||
yuv = { workspace = true }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,63 @@
|
||||
# Spike 1: the video path
|
||||
|
||||
`spike-video` shows the synthetic test pattern in a GPUI window the way
|
||||
`voelin-ui` shows a watched stream:
|
||||
|
||||
- **Source.** `--mode pipeline` runs `voelin_core::media::LocalPreview` with
|
||||
`SourceId::Synthetic`, as `Video::demo` (`crates/voelin-ui/src/video.rs`)
|
||||
does: capture, the VP8 encoder (libvpx), the decoder, no server.
|
||||
`--mode raw` hands decoded-looking I420 frames from memory at `--fps`
|
||||
straight to the converter, so a frame rate below the source's belongs to
|
||||
the conversion and GPUI alone.
|
||||
- **Delivery** (`src/frames.rs`): the port of `video.rs`' `deliver`,
|
||||
`FrameSlot`, `Handoff` and `Buffers`. The decoder hands over its newest
|
||||
frame only; a converter thread (`voelin-picture`) turns it into an
|
||||
`Arc<RenderImage>` (BGRA, `spike_common::bgra::to_bgra`, the BGRA twin of
|
||||
`voelin_media::convert::to_rgba`) and puts it into a `Latest`; the window
|
||||
is woken through a channel only when the slot was empty (GPUI's
|
||||
`AsyncApp` is not `Send`). A `RenderImage` owns its pixels and gives no
|
||||
way back to them, so the buffer reuse of `Buffers` cannot be ported: every
|
||||
picture is a new buffer.
|
||||
- **Window** (`src/main.rs`): `img(ImageSource::Render(..))`, the picture
|
||||
taken from `Latest` in `render`, the one it replaces dropped from every
|
||||
window's sprite atlas with `cx.drop_image` (`--no-drop` leaves it: the
|
||||
negative control). `inactive_frame_interval: None`: GPUI throttles
|
||||
animation frames of an unfocused window to 30 fps by default.
|
||||
|
||||
Once a second it prints a JSON line (CPU of the process and of each thread
|
||||
group in percent of one core, resident memory, and per second: frames
|
||||
captured, encoded, decoded, handed to the converter, converted, shown and
|
||||
rendered, conversion time); at the end a summary over the steady part.
|
||||
|
||||
## Reproducing the measurements
|
||||
|
||||
Build, then run every case on the headless display (Xvfb `:91`, openbox,
|
||||
lavapipe through wgpu's Vulkan backend; see [../README.md](../README.md)):
|
||||
|
||||
```sh
|
||||
spikes/gpui/shell.sh sh -c 'cd spikes/gpui && cargo build --locked --release'
|
||||
# the Slint app, for its demo stream (the root workspace, Rust 1.94):
|
||||
TOOLCHAIN=1.94 spikes/gpui/shell.sh cargo build --locked --release -p voelin-ui
|
||||
spikes/gpui/shell.sh spikes/gpui/headless.sh -- spikes/gpui/video/measure.sh
|
||||
```
|
||||
|
||||
`measure.sh` runs, 70 s each with 10 s of warm-up not averaged
|
||||
(`SECONDS_RUN`, `WARMUP`), and writes `<case>.jsonl`, `<case>-damage.jsonl`
|
||||
(the X server's count of the window's content changes), `<case>.load` (load
|
||||
average before and after) and a screenshot from the warm-up to `$OUT`
|
||||
(default `.scratch/gpui-spikes-results`):
|
||||
|
||||
| Case | Command |
|
||||
|---|---|
|
||||
| `bench` | `spike-video --bench --iterations 300` (RGBA against BGRA, 1080p and 1440p, into a reused and a new buffer, and as a `RenderImage`) |
|
||||
| `raw-1080p60`, `raw-1440p60` | `spike-video --mode raw --size 1920x1080` (or `2560x1440`) `--fps 60` |
|
||||
| `pipeline-1080p60`, `pipeline-1440p60` | `spike-video --mode pipeline --size … --fps 60` (bitrate automatic, as the share dialog's default) |
|
||||
| `pipeline-1440p60-rgba` | the same with `--convert rgba` (voelin-media's conversion; red and blue show swapped) |
|
||||
| `nodrop-1440p` | `spike-video --mode pipeline --size 2560x1440 --fps 15 --no-drop --seconds 12 --warmup 2` (memory grows by a picture per frame) |
|
||||
| `pipeline-720p30` | `spike-video --mode pipeline --size 1280x720 --fps 30 --bitrate 4608`: `Video::demo`'s own settings (`StreamerConfig::default()`) |
|
||||
| `slint-720p30` | `voelin` with `VOELIN_DEMO_STREAM=1 SLINT_BACKEND=winit-software`, measured from outside with `proc-meter` and `damage-count` |
|
||||
|
||||
One case: `spikes/gpui/shell.sh spikes/gpui/headless.sh -- spikes/gpui/video/measure.sh raw-1440p60`.
|
||||
|
||||
The figures and what they mean are in
|
||||
[docs/design/gpui-spikes.md](../../../docs/design/gpui-spikes.md#spike-1-the-video-path).
|
||||
Executable
+87
@@ -0,0 +1,87 @@
|
||||
#!/bin/sh
|
||||
# Spike 1's measurements on the headless display, one case after another;
|
||||
# every case writes <case>.jsonl (one line a second, then the summary) to
|
||||
# $OUT. Cases (default: all, in this order):
|
||||
#
|
||||
# bench RGBA against BGRA conversion, no window
|
||||
# static-1080p60 static-1440p60 one picture, repainted every frame (the control)
|
||||
# raw-1080p60 raw-1440p60 frames from memory: conversion + GPUI only
|
||||
# pipeline-1080p60 pipeline-1440p60 LocalPreview: capture, VP8, decoder (as Video::demo)
|
||||
# pipeline-1440p60-rgba the same with voelin-media's RGBA conversion
|
||||
# nodrop-1440p the negative control: no cx.drop_image (15 fps, 12 s)
|
||||
# pipeline-720p30 GPUI with Video::demo's own settings (1280x720, 30 fps, 4.6 Mbit/s)
|
||||
# slint-720p30 the Slint app's demo stream (VOELIN_DEMO_STREAM), same display
|
||||
#
|
||||
# spikes/gpui/shell.sh spikes/gpui/headless.sh -- spikes/gpui/video/measure.sh [CASE...]
|
||||
#
|
||||
# SECONDS_RUN (default 70) and WARMUP (default 10) set the length of the
|
||||
# window cases. damage-count runs beside every window case: it counts the
|
||||
# window's content changes from the X server's side.
|
||||
set -eu
|
||||
root=$(cd "$(dirname "$0")/../../.." && pwd)
|
||||
out=${OUT:-$root/.scratch/gpui-spikes-results}
|
||||
mkdir -p "$out"
|
||||
out=$(cd "$out" && pwd)
|
||||
bin=$root/target/release
|
||||
seconds=${SECONDS_RUN:-70}
|
||||
warmup=${WARMUP:-10}
|
||||
cases=${*:-bench static-1080p60 static-1440p60 raw-1080p60 raw-1440p60 pipeline-1080p60 pipeline-1440p60 pipeline-1440p60-rgba nodrop-1440p pipeline-720p30 slint-720p30}
|
||||
|
||||
video() {
|
||||
name=$1
|
||||
shift
|
||||
echo "== $name: spike-video $*" >&2
|
||||
echo "load before: $(cat /proc/loadavg)" >"$out/$name.load"
|
||||
"$bin/damage-count" spike-video "$((seconds - 1))" "$warmup" >"$out/$name-damage.jsonl" &
|
||||
damage=$!
|
||||
# A picture of the window during the warm-up (not averaged).
|
||||
(sleep 5 && w=$(xdotool search --name '^spike-video$' | head -1) && xwd -id "$w" -silent | magick xwd:- -resize 50% "png:$out/$name.png") &
|
||||
"$bin/spike-video" "$@" --out "$out/$name.jsonl" >/dev/null 2>"$out/$name.log"
|
||||
wait "$damage" || true
|
||||
echo "load after: $(cat /proc/loadavg)" >>"$out/$name.load"
|
||||
tail -1 "$out/$name.jsonl"
|
||||
tail -1 "$out/$name-damage.jsonl"
|
||||
}
|
||||
|
||||
for c in $cases; do
|
||||
case $c in
|
||||
bench) "$bin/spike-video" --bench --iterations 300 | tee "$out/bench.jsonl" ;;
|
||||
static-1080p60) video "$c" --mode static --size 1920x1080 --seconds "$seconds" --warmup "$warmup" ;;
|
||||
static-1440p60) video "$c" --mode static --size 2560x1440 --seconds "$seconds" --warmup "$warmup" ;;
|
||||
raw-1080p60) video "$c" --mode raw --size 1920x1080 --fps 60 --seconds "$seconds" --warmup "$warmup" ;;
|
||||
raw-1440p60) video "$c" --mode raw --size 2560x1440 --fps 60 --seconds "$seconds" --warmup "$warmup" ;;
|
||||
pipeline-1080p60) video "$c" --mode pipeline --size 1920x1080 --fps 60 --seconds "$seconds" --warmup "$warmup" ;;
|
||||
pipeline-1440p60) video "$c" --mode pipeline --size 2560x1440 --fps 60 --seconds "$seconds" --warmup "$warmup" ;;
|
||||
pipeline-1440p60-rgba)
|
||||
video "$c" --mode pipeline --size 2560x1440 --fps 60 --convert rgba --seconds "$seconds" --warmup "$warmup"
|
||||
;;
|
||||
nodrop-1440p) video "$c" --mode pipeline --size 2560x1440 --fps 15 --no-drop --seconds 12 --warmup 2 ;;
|
||||
pipeline-720p30)
|
||||
video "$c" --mode pipeline --size 1280x720 --fps 30 --bitrate 4608 --seconds "$seconds" --warmup "$warmup"
|
||||
;;
|
||||
slint-720p30)
|
||||
echo "== $c: voelin (Slint, software renderer) with VOELIN_DEMO_STREAM=1" >&2
|
||||
echo "load before: $(cat /proc/loadavg)" >"$out/$c.load"
|
||||
data=$out/slint-data
|
||||
rm -rf "$data"
|
||||
mkdir -p "$data"
|
||||
SLINT_BACKEND=winit-software SLINT_DEBUG_PERFORMANCE=console,refresh_lazy \
|
||||
VOELIN_DATA_DIR="$data" VOELIN_DEMO_STREAM=1 VOELIN_WINDOW_SIZE=1440x960 VOELIN_FFMPEG=0 \
|
||||
"$bin/voelin" >"$out/$c.log" 2>&1 &
|
||||
app=$!
|
||||
"$bin/damage-count" Voelin "$((seconds - 1))" "$warmup" >"$out/$c-damage.jsonl" &
|
||||
damage=$!
|
||||
sleep 8
|
||||
w=$(xdotool search --name '^Voelin$' | head -1)
|
||||
xwd -id "$w" -silent | magick xwd:- "png:$out/$c.png"
|
||||
"$bin/proc-meter" "$app" "$((seconds - 8))" "$((warmup > 8 ? warmup - 8 : 1))" >"$out/$c.jsonl"
|
||||
wait "$damage" || true
|
||||
echo "load after: $(cat /proc/loadavg)" >>"$out/$c.load"
|
||||
kill "$app" 2>/dev/null || true
|
||||
wait "$app" 2>/dev/null || true
|
||||
tail -1 "$out/$c.jsonl"
|
||||
tail -1 "$out/$c-damage.jsonl"
|
||||
;;
|
||||
*) echo "unknown case $c" >&2; exit 2 ;;
|
||||
esac
|
||||
done
|
||||
@@ -0,0 +1,90 @@
|
||||
//! Which conversion the converter thread runs (BGRA, what GPUI shows, or
|
||||
//! voelin-media's RGBA for comparison), and the benchmark of the two.
|
||||
|
||||
use std::time::Instant;
|
||||
|
||||
use spike_common::bgra::{render_image, to_bgra};
|
||||
use voelin_media::convert;
|
||||
use voelin_media::frame::VideoFrame;
|
||||
|
||||
/// Which conversion the converter thread runs.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Order {
|
||||
/// What GPUI wants.
|
||||
Bgra,
|
||||
/// voelin-media's (what Slint wants): the picture shows with red and
|
||||
/// blue swapped; only for measuring the difference in place.
|
||||
Rgba,
|
||||
}
|
||||
|
||||
impl Order {
|
||||
/// Convert with this order.
|
||||
pub fn convert(self, frame: &VideoFrame, out: &mut [u8], stride: usize) -> Result<(), String> {
|
||||
match self {
|
||||
Self::Bgra => to_bgra(frame, out, stride),
|
||||
Self::Rgba => convert::to_rgba(frame, out, stride).map_err(|e| e.to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Milliseconds per call of `f`, over `n` calls after two warm-up calls:
|
||||
/// (mean, median).
|
||||
fn time(n: usize, mut f: impl FnMut()) -> (f64, f64) {
|
||||
f();
|
||||
f();
|
||||
let mut samples: Vec<f64> = (0..n)
|
||||
.map(|_| {
|
||||
let t = Instant::now();
|
||||
f();
|
||||
t.elapsed().as_secs_f64() * 1000.0
|
||||
})
|
||||
.collect();
|
||||
samples.sort_by(f64::total_cmp);
|
||||
(samples.iter().sum::<f64>() / n as f64, samples[n / 2])
|
||||
}
|
||||
|
||||
/// The conversion benchmark (`spike-video --bench`): RGBA against BGRA at
|
||||
/// 1080p and 1440p, into a reused buffer and into a new one, and the new
|
||||
/// buffer wrapped as GPUI's `RenderImage` (what the converter thread does
|
||||
/// per frame). Prints one JSON line per case.
|
||||
pub fn bench(iterations: usize) {
|
||||
use voelin_media::capture::synthetic::{Pattern, SyntheticScreen};
|
||||
for (w, h) in [(1920u32, 1080u32), (2560, 1440)] {
|
||||
let picture = SyntheticScreen::with_pattern(w, h, Pattern::Desktop).frame(1, 60);
|
||||
let i420 = convert::to_i420(&picture).expect("I420").into_owned();
|
||||
let stride = w as usize * 4;
|
||||
let bytes = stride * h as usize;
|
||||
for order in [Order::Rgba, Order::Bgra] {
|
||||
let mut reused = vec![0u8; bytes];
|
||||
let (reuse_mean, reuse_median) = time(iterations, || {
|
||||
order.convert(&i420, &mut reused, stride).expect("convert");
|
||||
});
|
||||
let (new_mean, new_median) = time(iterations, || {
|
||||
let mut fresh = vec![0u8; bytes];
|
||||
order.convert(&i420, &mut fresh, stride).expect("convert");
|
||||
std::hint::black_box(&fresh);
|
||||
});
|
||||
let (image_mean, image_median) = time(iterations, || {
|
||||
let mut fresh = vec![0u8; bytes];
|
||||
order.convert(&i420, &mut fresh, stride).expect("convert");
|
||||
std::hint::black_box(render_image(w, h, fresh));
|
||||
});
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::json!({
|
||||
"size": format!("{w}x{h}"),
|
||||
"order": format!("{order:?}"),
|
||||
"threads": 1,
|
||||
"reused_ms": {"mean": r3(reuse_mean), "median": r3(reuse_median)},
|
||||
"new_buffer_ms": {"mean": r3(new_mean), "median": r3(new_median)},
|
||||
"new_buffer_render_image_ms": {"mean": r3(image_mean), "median": r3(image_median)},
|
||||
"iterations": iterations,
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn r3(v: f64) -> f64 {
|
||||
(v * 1000.0).round() / 1000.0
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
//! `voelin-ui`'s `video.rs` delivery (`deliver`, `FrameSlot`, `Handoff`,
|
||||
//! `Buffers`, video.rs:360-480) ported to GPUI: decoded frames become
|
||||
//! `Arc<RenderImage>` (BGRA) instead of Slint pixel buffers.
|
||||
//!
|
||||
//! What carries over unchanged: the decoder hands over its newest frame only
|
||||
//! and never waits for the conversion; a converter thread converts only what
|
||||
//! the window can show; the window takes the newest picture from a
|
||||
//! [`Latest`] and is woken only when the slot was empty.
|
||||
//!
|
||||
//! What does not: buffer reuse. A `RenderImage` owns its pixels
|
||||
//! (`SmallVec<[image::Frame; 1]>`, private, no accessor), so the buffer of
|
||||
//! a picture the window let go of cannot be recovered and every frame is a
|
||||
//! new allocation. [`Buffers`] keeps the shape (and the size check) without
|
||||
//! the reuse; the allocator may still hand the same memory back.
|
||||
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Condvar, Mutex, PoisonError};
|
||||
|
||||
use gpui_kit::RenderImage;
|
||||
use spike_common::bgra::render_image;
|
||||
use spike_common::meter::Counter;
|
||||
use voelin_core::media::Latest;
|
||||
use voelin_media::VideoFrame;
|
||||
|
||||
use crate::convert::Order;
|
||||
|
||||
/// What the converter counts.
|
||||
#[derive(Clone, Default)]
|
||||
pub struct Counts {
|
||||
/// Frames the decoder (or the raw source) handed over.
|
||||
pub arrived: Counter,
|
||||
/// Frames converted into pictures.
|
||||
pub converted: Counter,
|
||||
/// Microseconds spent converting (with the allocation), summed.
|
||||
pub convert_us: Counter,
|
||||
}
|
||||
|
||||
/// A callback for the decoder that converts its newest frame on a thread of
|
||||
/// its own into `pictures`; `wake` runs (on that thread) when a picture is
|
||||
/// ready and none was waiting.
|
||||
pub fn deliver(
|
||||
pictures: Arc<Latest<Arc<RenderImage>>>,
|
||||
order: Order,
|
||||
counts: Counts,
|
||||
wake: impl Fn() + Send + Sync + 'static,
|
||||
) -> impl FnMut(Arc<VideoFrame>) + Send + 'static {
|
||||
let slot = Arc::new(FrameSlot::default());
|
||||
let wake = Arc::new(wake);
|
||||
let thread = {
|
||||
let (slot, pictures, wake, counts) =
|
||||
(slot.clone(), pictures.clone(), wake.clone(), counts.clone());
|
||||
std::thread::Builder::new().name("voelin-picture".into()).spawn(move || {
|
||||
let mut buffers = Buffers::new(order, counts);
|
||||
while let Some(frame) = slot.wait() {
|
||||
buffers.show(&frame, &pictures, &*wake);
|
||||
}
|
||||
})
|
||||
};
|
||||
let mut inline = match thread {
|
||||
Ok(_) => None,
|
||||
Err(e) => {
|
||||
log::warn!("no picture thread, converting on the decoder's: {e}");
|
||||
Some(Buffers::new(order, counts.clone()))
|
||||
}
|
||||
};
|
||||
let handoff = Handoff(slot);
|
||||
move |frame: Arc<VideoFrame>| {
|
||||
counts.arrived.incr();
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts frames into new pictures (see the module docs on reuse).
|
||||
struct Buffers {
|
||||
order: Order,
|
||||
counts: Counts,
|
||||
/// Size of the last picture.
|
||||
size: (u32, u32),
|
||||
}
|
||||
|
||||
/// Pictures converted so far (for the log line of the first one).
|
||||
static CONVERTED: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
impl Buffers {
|
||||
fn new(order: Order, counts: Counts) -> Self {
|
||||
Self { order, counts, size: (0, 0) }
|
||||
}
|
||||
|
||||
fn show(&mut self, frame: &VideoFrame, pictures: &Latest<Arc<RenderImage>>, wake: &dyn Fn()) {
|
||||
let (width, height) = (frame.width, frame.height);
|
||||
if self.size != (width, height) {
|
||||
log::info!("pictures of {width}x{height}");
|
||||
self.size = (width, height);
|
||||
}
|
||||
let started = std::time::Instant::now();
|
||||
let stride = width as usize * 4;
|
||||
let mut bgra = vec![0u8; stride * height as usize];
|
||||
if let Err(e) = self.order.convert(frame, &mut bgra, stride) {
|
||||
log::warn!("cannot show a picture: {e}");
|
||||
return;
|
||||
}
|
||||
let picture = render_image(width, height, bgra);
|
||||
self.counts.convert_us.add(started.elapsed().as_micros() as u64);
|
||||
self.counts.converted.incr();
|
||||
if CONVERTED.fetch_add(1, Ordering::Relaxed) == 0 {
|
||||
log::info!("first picture converted ({:?})", self.order);
|
||||
}
|
||||
if pictures.put(picture) {
|
||||
wake();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,352 @@
|
||||
//! 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 0u64.. {
|
||||
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(())
|
||||
}
|
||||
Reference in new issue
Block a user