M8 (part 2): tsc-media integration tests and docs
- tests/codec_roundtrip.rs: synthetic pattern -> VP8 / VP9 -> decode (PSNR, rectangle and background colours, forced keyframes, bitrate change) and capture thread -> encoder -> decoder - tests/x11_capture.rs: draws windows on a real X server ($DISPLAY, e.g. Xvfb), checks MIT-SHM and GetImage pixels, window listing, window capture -> VP8 -> decode colours, and cursor drawing; skipped without DISPLAY - tests/openh264.rs: missing-library errors; with TSC_OPENH264_LIB a full H.264 roundtrip incl. SPS profile checks (High 100, Baseline 66); an ignored test downloads Cisco's binary and runs the roundtrip - OpenH264: allow frame skipping so rate control holds the bitrate, no adaptive quantisation / background detection for screen content - docs/media.md: API, backends, features, build requirements, licenses (OpenH264 runtime download and attribution), verification status Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G
This commit is contained in:
5 files changed
+626
-1
No files matched your search
@@ -217,7 +217,11 @@ impl OpenH264Encoder {
|
||||
.rate_control_mode(RateControlMode::Bitrate)
|
||||
.usage_type(usage)
|
||||
.profile(profile)
|
||||
.skip_frames(false)
|
||||
// Rate control only holds the bitrate if it may skip frames.
|
||||
.skip_frames(true)
|
||||
// Not supported for screen content; OpenH264 would warn and drop them.
|
||||
.adaptive_quantization(self.config.content == ContentHint::Motion)
|
||||
.background_detection(self.config.content == ContentHint::Motion)
|
||||
.intra_frame_period(IntraFramePeriod::from_num_frames(
|
||||
self.config.keyframe_interval.unwrap_or(0),
|
||||
))
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
//! Synthetic capture -> encoder -> decoder, through the public API.
|
||||
#![cfg(feature = "vpx")]
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use tsc_media::capture::synthetic::{BACKGROUND, RECT_COLOR, SyntheticScreen, TEXT_COLOR};
|
||||
use tsc_media::{
|
||||
CaptureOptions, Codec, Codecs, EncoderBackend, EncoderConfig, ScreenCapture, SourceId,
|
||||
VideoFrame, convert,
|
||||
};
|
||||
|
||||
const W: u32 = 320;
|
||||
const H: u32 = 240;
|
||||
const FPS: u32 = 30;
|
||||
|
||||
fn rgb_at(frame: &VideoFrame, x: u32, y: u32) -> [u8; 3] {
|
||||
let rgba = convert::to_rgba_vec(frame).unwrap();
|
||||
let i = ((y * frame.width + x) * 4) as usize;
|
||||
[rgba[i], rgba[i + 1], rgba[i + 2]]
|
||||
}
|
||||
|
||||
fn assert_close(actual: [u8; 3], expected: [u8; 3], tolerance: i32, what: &str) {
|
||||
let ok = (0..3).all(|c| (i32::from(actual[c]) - i32::from(expected[c])).abs() <= tolerance);
|
||||
assert!(ok, "{what}: got {actual:?}, expected {expected:?} ±{tolerance}");
|
||||
}
|
||||
|
||||
/// Encode 30 frames of the pattern, force a keyframe midway, lower the
|
||||
/// bitrate, and check every decoded frame.
|
||||
fn roundtrip(codec: Codec) {
|
||||
let codecs = Codecs::new();
|
||||
let screen = SyntheticScreen::new(W, H);
|
||||
let config = EncoderConfig { fps: FPS, bitrate_bps: 1_500_000, ..EncoderConfig::default() };
|
||||
let mut encoder = codecs.new_encoder(codec, config).unwrap();
|
||||
assert_eq!(encoder.backend(), EncoderBackend::Libvpx);
|
||||
let mut decoder = codecs.new_decoder(codec).unwrap();
|
||||
let mut worst = f64::INFINITY;
|
||||
for n in 0..30 {
|
||||
if n == 20 {
|
||||
encoder.set_bitrate(600_000).unwrap();
|
||||
}
|
||||
let source = screen.frame(n, FPS);
|
||||
let encoded = encoder.encode(&source, n == 15).unwrap();
|
||||
assert_eq!(encoded.len(), 1, "{codec} frame {n}");
|
||||
let encoded = &encoded[0];
|
||||
assert_eq!(encoded.keyframe, n == 0 || n == 15, "{codec} frame {n}");
|
||||
assert_eq!(encoded.pts_90khz, source.pts_90khz());
|
||||
let decoded = decoder.decode(&encoded.data).unwrap().expect("a picture per frame");
|
||||
assert_eq!((decoded.width, decoded.height), (W, H));
|
||||
worst = worst.min(convert::psnr(&source, &decoded).unwrap());
|
||||
|
||||
// The rectangle is where the pattern put it, in its colour.
|
||||
let (x, y, w, h) = screen.rect(n);
|
||||
assert_close(rgb_at(&decoded, x + w / 2, y + h / 2), RECT_COLOR, 16, "rectangle");
|
||||
assert_close(rgb_at(&decoded, W - 10, H - 10), BACKGROUND, 16, "background");
|
||||
}
|
||||
assert!(worst > 30.0, "{codec}: worst PSNR {worst:.1} dB");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vp8_synthetic_roundtrip() {
|
||||
roundtrip(Codec::Vp8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vp9_synthetic_roundtrip() {
|
||||
roundtrip(Codec::Vp9);
|
||||
}
|
||||
|
||||
/// Frames from the capture thread go through encode / decode in order.
|
||||
#[tokio::test]
|
||||
async fn capture_thread_to_decoder() {
|
||||
let codecs = Codecs::new();
|
||||
let mut screen = SyntheticScreen::new(W, H);
|
||||
let options = CaptureOptions { fps: 60, cursor: false, queue: 8 };
|
||||
let mut frames = screen.start(&SourceId::Synthetic, &options).await.unwrap();
|
||||
let config = EncoderConfig { fps: 60, bitrate_bps: 1_000_000, ..EncoderConfig::default() };
|
||||
let mut encoder = codecs.new_encoder(Codec::Vp8, config).unwrap();
|
||||
let mut decoder = codecs.new_decoder(Codec::Vp8).unwrap();
|
||||
let mut last_pts = None;
|
||||
for _ in 0..10 {
|
||||
let frame =
|
||||
tokio::time::timeout(Duration::from_secs(5), frames.recv()).await.unwrap().unwrap();
|
||||
let encoded = encoder.encode(&frame, false).unwrap();
|
||||
for e in &encoded {
|
||||
assert!(last_pts.is_none_or(|p| e.pts_90khz > p));
|
||||
last_pts = Some(e.pts_90khz);
|
||||
let decoded = decoder.decode(&e.data).unwrap().unwrap();
|
||||
// The counter's first digit (3x5 cells of 5 px) sits at (10, 10).
|
||||
let rgba = convert::to_rgba_vec(&decoded).unwrap();
|
||||
let lit = (10..25u32)
|
||||
.flat_map(|x| (10..35u32).map(move |y| (x, y)))
|
||||
.filter(|&(x, y)| {
|
||||
let p = &rgba[((y * W + x) * 4) as usize..][..3];
|
||||
(0..3).all(|c| (i32::from(p[c]) - i32::from(TEXT_COLOR[c])).abs() < 60)
|
||||
})
|
||||
.count();
|
||||
assert!(lit >= 25, "counter digit missing ({lit} lit pixels)");
|
||||
}
|
||||
}
|
||||
screen.stop();
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
//! H.264 through Cisco's OpenH264, loaded at runtime.
|
||||
//!
|
||||
//! Without the library only the "unavailable" paths run. To test encoding
|
||||
//! and decoding, point `TSC_OPENH264_LIB` at Cisco's library (for example the
|
||||
//! file the ignored `download_and_roundtrip` test fetches:
|
||||
//! `cargo test -p tsc-media --test openh264 -- --ignored`).
|
||||
#![cfg(feature = "openh264")]
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use tsc_media::capture::synthetic::{RECT_COLOR, SyntheticScreen};
|
||||
use tsc_media::codec::h264::{H264Profile, OpenH264};
|
||||
use tsc_media::{
|
||||
Codec, Codecs, EncoderBackend, EncoderConfig, Error, VideoEncoder, VideoFrame, convert,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn missing_library_is_a_clear_error() {
|
||||
let err = OpenH264::load("/nonexistent/dir/libopenh264.so").unwrap_err();
|
||||
assert!(matches!(err, Error::CodecUnavailable { codec: Codec::H264, .. }), "{err}");
|
||||
assert!(err.to_string().contains("OpenH264 library not found"), "{err}");
|
||||
|
||||
// Without a library, H.264 is neither decodable nor encodable.
|
||||
let codecs = Codecs::new();
|
||||
assert!(!codecs.decoders().contains(&Codec::H264));
|
||||
assert!(!codecs.encoder_codecs().contains(&Codec::H264));
|
||||
let err = codecs.new_decoder(Codec::H264).err().unwrap();
|
||||
assert!(err.to_string().contains("OpenH264 library is not loaded"), "{err}");
|
||||
assert!(codecs.new_encoder(Codec::H264, EncoderConfig::default()).is_err());
|
||||
}
|
||||
|
||||
fn rgb_at(frame: &VideoFrame, x: u32, y: u32) -> [u8; 3] {
|
||||
let rgba = convert::to_rgba_vec(frame).unwrap();
|
||||
let i = ((y * frame.width + x) * 4) as usize;
|
||||
[rgba[i], rgba[i + 1], rgba[i + 2]]
|
||||
}
|
||||
|
||||
/// `profile_idc` of the first SPS in an Annex B stream.
|
||||
fn sps_profile(data: &[u8]) -> Option<u8> {
|
||||
let mut i = 0;
|
||||
while i + 4 < data.len() {
|
||||
if data[i..i + 3] == [0, 0, 1] {
|
||||
if data[i + 3] & 0x1f == 7 {
|
||||
return data.get(i + 4).copied();
|
||||
}
|
||||
i += 3;
|
||||
} else {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn roundtrip(library: OpenH264) {
|
||||
let codecs = Codecs::new().with_openh264(library.clone());
|
||||
assert_eq!(codecs.decoders().last(), Some(&Codec::H264));
|
||||
assert!(codecs.encoders().contains(&(Codec::H264, EncoderBackend::OpenH264)));
|
||||
|
||||
let screen = SyntheticScreen::new(320, 240);
|
||||
let config = EncoderConfig { fps: 30, bitrate_bps: 1_500_000, ..EncoderConfig::default() };
|
||||
let mut encoder = codecs.new_encoder(Codec::H264, config.clone()).unwrap();
|
||||
let mut decoder = codecs.new_decoder(Codec::H264).unwrap();
|
||||
let mut decoded_frames = 0;
|
||||
let mut worst = f64::INFINITY;
|
||||
for n in 0..20 {
|
||||
if n == 12 {
|
||||
encoder.set_bitrate(800_000).unwrap();
|
||||
}
|
||||
let source = screen.frame(n, 30);
|
||||
let encoded = encoder.encode(&source, n == 6).unwrap();
|
||||
for e in &encoded {
|
||||
if n == 0 {
|
||||
assert!(e.keyframe);
|
||||
// Constrained High: profile_idc 100.
|
||||
assert_eq!(sps_profile(&e.data), Some(100));
|
||||
}
|
||||
if n == 6 {
|
||||
assert!(e.keyframe);
|
||||
}
|
||||
if let Some(picture) = decoder.decode(&e.data).unwrap() {
|
||||
decoded_frames += 1;
|
||||
worst = worst.min(convert::psnr(&source, &picture).unwrap());
|
||||
let (x, y, w, h) = screen.rect(n);
|
||||
let rect = rgb_at(&picture, x + w / 2, y + h / 2);
|
||||
let close =
|
||||
(0..3).all(|c| (i32::from(rect[c]) - i32::from(RECT_COLOR[c])).abs() <= 16);
|
||||
assert!(close, "frame {n}: rectangle {rect:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(decoded_frames >= 18, "only {decoded_frames} frames decoded");
|
||||
assert!(worst > 30.0, "worst PSNR {worst:.1} dB");
|
||||
|
||||
// Constrained Baseline on request: profile_idc 66.
|
||||
let mut baseline = library.encoder(config).unwrap();
|
||||
baseline.set_profile(H264Profile::ConstrainedBaseline).unwrap();
|
||||
let encoded = baseline.encode(&screen.frame(0, 30), true).unwrap();
|
||||
assert_eq!(sps_profile(&encoded[0].data), Some(66));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roundtrip_with_library_from_env() {
|
||||
let Some(path) = std::env::var_os("TSC_OPENH264_LIB") else {
|
||||
eprintln!("skipped: TSC_OPENH264_LIB is not set");
|
||||
return;
|
||||
};
|
||||
roundtrip(OpenH264::load(PathBuf::from(path)).unwrap());
|
||||
}
|
||||
|
||||
/// Downloads Cisco's binary (network access needed).
|
||||
#[cfg(feature = "openh264-download")]
|
||||
#[tokio::test]
|
||||
#[ignore = "downloads from ciscobinary.openh264.org"]
|
||||
async fn download_and_roundtrip() {
|
||||
if tsc_media::codec::h264::platform_library_name().is_none() {
|
||||
return;
|
||||
}
|
||||
let dir = std::env::temp_dir().join(format!("tsc-media-openh264-{}", std::process::id()));
|
||||
let library = tsc_media::codec::h264::download_openh264(&dir).await.unwrap();
|
||||
assert!(library.path().starts_with(&dir));
|
||||
// A second call reuses the verified file.
|
||||
let again = tsc_media::codec::h264::download_openh264(&dir).await.unwrap();
|
||||
assert_eq!(again, library);
|
||||
tokio::task::spawn_blocking(move || roundtrip(library)).await.unwrap();
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
//! X11 capture against a real X server: draws known windows, captures them
|
||||
//! (MIT-SHM and GetImage), checks pixels, and sends a window capture through
|
||||
//! VP8 and back.
|
||||
//!
|
||||
//! Needs `DISPLAY` (e.g. `Xvfb :101 -screen 0 1280x720x24 & DISPLAY=:101
|
||||
//! cargo test -p tsc-media --test x11_capture`); skipped without it.
|
||||
#![cfg(all(target_os = "linux", feature = "x11", feature = "vpx"))]
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use tsc_media::capture::x11::X11Capture;
|
||||
use tsc_media::{
|
||||
CaptureOptions, Codec, Codecs, EncoderConfig, FrameReceiver, ScreenCapture, SourceId,
|
||||
VideoFrame, convert,
|
||||
};
|
||||
use x11rb::connection::Connection;
|
||||
use x11rb::protocol::xproto::{
|
||||
AtomEnum, ConnectionExt as _, CreateWindowAux, PropMode, Window, WindowClass,
|
||||
};
|
||||
use x11rb::rust_connection::RustConnection;
|
||||
use x11rb::wrapper::ConnectionExt as _;
|
||||
|
||||
const TITLE: &str = "tsc-media-x11-test";
|
||||
const BACKGROUND: u32 = 0x202020;
|
||||
const WINDOW: u32 = 0x3060c0;
|
||||
const INNER: u32 = 0xf08020;
|
||||
/// Test window: position and size on the root window.
|
||||
const WX: i16 = 160;
|
||||
const WY: i16 = 120;
|
||||
const WW: u16 = 320;
|
||||
const WH: u16 = 240;
|
||||
/// Inner child window, relative to the test window.
|
||||
const IX: i16 = 80;
|
||||
const IY: i16 = 60;
|
||||
const IW: u16 = 160;
|
||||
const IH: u16 = 120;
|
||||
|
||||
fn rgb(pixel: u32) -> [u8; 3] {
|
||||
[(pixel >> 16) as u8, (pixel >> 8) as u8, pixel as u8]
|
||||
}
|
||||
|
||||
/// Windows drawn for the test, destroyed on drop.
|
||||
struct Scene {
|
||||
conn: RustConnection,
|
||||
root: Window,
|
||||
windows: Vec<Window>,
|
||||
test_window: Window,
|
||||
screen: (u16, u16),
|
||||
}
|
||||
|
||||
impl Scene {
|
||||
fn create(display: &str) -> Self {
|
||||
let (conn, screen_num) = RustConnection::connect(Some(display)).expect("connect");
|
||||
let screen = &conn.setup().roots[screen_num];
|
||||
let (root, depth, visual) = (screen.root, screen.root_depth, screen.root_visual);
|
||||
let size = (screen.width_in_pixels, screen.height_in_pixels);
|
||||
let mut windows = Vec::new();
|
||||
let mut create = |parent, x, y, w, h, pixel, override_redirect| {
|
||||
let id = conn.generate_id().unwrap();
|
||||
let aux = CreateWindowAux::new()
|
||||
.background_pixel(pixel)
|
||||
.override_redirect(u32::from(override_redirect));
|
||||
conn.create_window(
|
||||
depth,
|
||||
id,
|
||||
parent,
|
||||
x,
|
||||
y,
|
||||
w,
|
||||
h,
|
||||
0,
|
||||
WindowClass::INPUT_OUTPUT,
|
||||
visual,
|
||||
&aux,
|
||||
)
|
||||
.unwrap();
|
||||
windows.push(id);
|
||||
id
|
||||
};
|
||||
// A flat background over the whole screen (not a listed window),
|
||||
// then the test window with a child on top.
|
||||
let background = create(root, 0, 0, size.0, size.1, BACKGROUND, true);
|
||||
let test_window = create(root, WX, WY, WW, WH, WINDOW, false);
|
||||
let inner = create(test_window, IX, IY, IW, IH, INNER, false);
|
||||
conn.change_property8(
|
||||
PropMode::REPLACE,
|
||||
test_window,
|
||||
AtomEnum::WM_NAME,
|
||||
AtomEnum::STRING,
|
||||
TITLE.as_bytes(),
|
||||
)
|
||||
.unwrap();
|
||||
for w in [background, test_window, inner] {
|
||||
conn.map_window(w).unwrap();
|
||||
}
|
||||
conn.sync().unwrap();
|
||||
// Backgrounds are painted when the exposures are processed.
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
Self { conn, root, windows, test_window, screen: size }
|
||||
}
|
||||
|
||||
fn warp_pointer(&self, x: i16, y: i16) {
|
||||
self.conn.warp_pointer(x11rb::NONE, self.root, 0, 0, 0, 0, x, y).unwrap();
|
||||
self.conn.sync().unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Scene {
|
||||
fn drop(&mut self) {
|
||||
for &w in self.windows.iter().rev() {
|
||||
let _ = self.conn.destroy_window(w);
|
||||
}
|
||||
let _ = self.conn.flush();
|
||||
}
|
||||
}
|
||||
|
||||
async fn first_frame(frames: &mut FrameReceiver<VideoFrame>) -> VideoFrame {
|
||||
tokio::time::timeout(Duration::from_secs(10), frames.recv())
|
||||
.await
|
||||
.expect("a frame within 10 s")
|
||||
.expect("capture ended")
|
||||
}
|
||||
|
||||
fn pixel(rgba: &[u8], width: u32, x: u32, y: u32) -> [u8; 3] {
|
||||
let i = ((y * width + x) * 4) as usize;
|
||||
[rgba[i], rgba[i + 1], rgba[i + 2]]
|
||||
}
|
||||
|
||||
fn assert_close(actual: [u8; 3], expected: [u8; 3], tolerance: i32, what: &str) {
|
||||
let ok = (0..3).all(|c| (i32::from(actual[c]) - i32::from(expected[c])).abs() <= tolerance);
|
||||
assert!(ok, "{what}: got {actual:?}, expected {expected:?} ±{tolerance}");
|
||||
}
|
||||
|
||||
/// Capture monitor 0 and check the drawn windows' pixels exactly.
|
||||
async fn check_monitor(capture: &mut X11Capture, scene: &Scene) {
|
||||
let options = CaptureOptions { fps: 10, cursor: false, queue: 2 };
|
||||
let mut frames = capture.start(&SourceId::Monitor(0), &options).await.unwrap();
|
||||
let frame = first_frame(&mut frames).await;
|
||||
capture.stop();
|
||||
assert_eq!((frame.width, frame.height), (u32::from(scene.screen.0), u32::from(scene.screen.1)));
|
||||
let rgba = convert::to_rgba_vec(&frame).unwrap();
|
||||
let w = frame.width;
|
||||
assert_eq!(pixel(&rgba, w, 20, 20), rgb(BACKGROUND), "background");
|
||||
let (wx, wy) = (WX as u32, WY as u32);
|
||||
assert_eq!(pixel(&rgba, w, wx + 10, wy + 10), rgb(WINDOW), "test window");
|
||||
let inner = (wx + IX as u32 + 10, wy + IY as u32 + 10);
|
||||
assert_eq!(pixel(&rgba, w, inner.0, inner.1), rgb(INNER), "inner window");
|
||||
assert_eq!(pixel(&rgba, w, wx + WW as u32 + 5, wy), rgb(BACKGROUND), "right of the window");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn x11_capture_end_to_end() {
|
||||
let Some(display) = std::env::var("DISPLAY").ok().filter(|d| !d.is_empty()) else {
|
||||
eprintln!("skipped: DISPLAY is not set");
|
||||
return;
|
||||
};
|
||||
let scene = Scene::create(&display);
|
||||
|
||||
// Sources: the whole screen (or RandR monitors) and our named window.
|
||||
let mut capture = X11Capture::with_display(display.clone());
|
||||
let sources = capture.sources().unwrap();
|
||||
let monitor = sources.iter().find(|s| s.id == SourceId::Monitor(0)).expect("monitor 0");
|
||||
assert!(monitor.width > 0 && monitor.height > 0);
|
||||
let window = sources
|
||||
.iter()
|
||||
.find(|s| s.name == TITLE)
|
||||
.unwrap_or_else(|| panic!("test window not listed in {sources:?}"));
|
||||
assert_eq!(window.id, SourceId::Window(scene.test_window.into()));
|
||||
assert_eq!((window.width, window.height), (u32::from(WW), u32::from(WH)));
|
||||
|
||||
// Same pixels through MIT-SHM and through GetImage.
|
||||
check_monitor(&mut capture, &scene).await;
|
||||
let mut get_image = X11Capture::with_display(display.clone()).use_shm(false);
|
||||
check_monitor(&mut get_image, &scene).await;
|
||||
|
||||
// Unknown sources fail at start.
|
||||
let options = CaptureOptions { fps: 10, cursor: false, queue: 2 };
|
||||
assert!(capture.start(&SourceId::Monitor(99), &options).await.is_err());
|
||||
assert!(capture.start(&SourceId::Window(0x7fff_fff0), &options).await.is_err());
|
||||
|
||||
// Window capture -> VP8 -> decode: the colours survive.
|
||||
let mut frames = capture.start(&window.id, &options).await.unwrap();
|
||||
let codecs = Codecs::new();
|
||||
let config = EncoderConfig { fps: 10, bitrate_bps: 1_000_000, ..EncoderConfig::default() };
|
||||
let mut encoder = codecs.new_encoder(Codec::Vp8, config).unwrap();
|
||||
let mut decoder = codecs.new_decoder(Codec::Vp8).unwrap();
|
||||
let mut decoded = None;
|
||||
let mut source = None;
|
||||
for i in 0..4 {
|
||||
let frame = first_frame(&mut frames).await;
|
||||
assert_eq!((frame.width, frame.height), (u32::from(WW), u32::from(WH)));
|
||||
let encoded = encoder.encode(&frame, false).unwrap();
|
||||
assert_eq!(encoded.len(), 1);
|
||||
assert_eq!(encoded[0].keyframe, i == 0);
|
||||
decoded = decoder.decode(&encoded[0].data).unwrap();
|
||||
source = Some(frame);
|
||||
}
|
||||
capture.stop();
|
||||
let (decoded, source) = (decoded.expect("decoded frame"), source.unwrap());
|
||||
let psnr = convert::psnr(&source, &decoded).unwrap();
|
||||
assert!(psnr > 30.0, "PSNR {psnr:.1} dB");
|
||||
let rgba = convert::to_rgba_vec(&decoded).unwrap();
|
||||
let w = decoded.width;
|
||||
assert_close(pixel(&rgba, w, 20, 20), rgb(WINDOW), 12, "decoded window corner");
|
||||
let center = (IX as u32 + IW as u32 / 2, IY as u32 + IH as u32 / 2);
|
||||
assert_close(pixel(&rgba, w, center.0, center.1), rgb(INNER), 12, "decoded inner window");
|
||||
|
||||
// The cursor is drawn when asked for.
|
||||
scene.warp_pointer(40, 40);
|
||||
let with_cursor = CaptureOptions { fps: 10, cursor: true, queue: 2 };
|
||||
let mut frames = capture.start(&SourceId::Monitor(0), &with_cursor).await.unwrap();
|
||||
let frame = first_frame(&mut frames).await;
|
||||
capture.stop();
|
||||
let rgba = convert::to_rgba_vec(&frame).unwrap();
|
||||
let background = rgb(BACKGROUND);
|
||||
let changed = (24..72)
|
||||
.flat_map(|y| (24..72).map(move |x| (x, y)))
|
||||
.filter(|&(x, y)| pixel(&rgba, frame.width, x, y) != background)
|
||||
.count();
|
||||
assert!(changed > 10, "no cursor drawn near (40, 40): {changed} pixels differ");
|
||||
}
|
||||
+173
@@ -0,0 +1,173 @@
|
||||
# Media: frames, codecs and capture (`tsc-media`)
|
||||
|
||||
`crates/tsc-media` turns screens and system audio into frames, encodes and
|
||||
decodes video, and converts pixels for rendering. It does no networking:
|
||||
`tsc-stream` carries the encoded frames (`Peer::write(MediaKind::Video,
|
||||
MediaTime::new(frame.pts_90khz, Frequency::NINETY_KHZ), data)`), and received
|
||||
`MediaFrame`s go to `VideoDecoder::decode`.
|
||||
|
||||
## API overview
|
||||
|
||||
| Item | What it is |
|
||||
|---|---|
|
||||
| `VideoFrame { width, height, timestamp, data: FrameData }` | `FrameData::I420 { y, u, v }`, `Nv12 { y, uv }`, `Bgra(Plane)`, `Rgba(Plane)`; `Plane { data, stride }` |
|
||||
| `AudioBuffer { samples, channels, timestamp }` | interleaved `f32`, 48 kHz |
|
||||
| `convert::to_rgba(&frame, out, stride)`, `to_rgba_vec`, `to_i420`, `psnr` | BT.601 limited range (the WebRTC default). `to_rgba` writes straight into a Slint `SharedPixelBuffer<Rgba8Pixel>` (`make_mut_bytes()`, stride `width * 4`) |
|
||||
| `Codec` | `Vp8`, `Vp9`, `H264`, `Av1`; `FromStr` for SDP/MIME names; `From`/`TryFrom` `str0m::format::Codec` with feature `str0m` |
|
||||
| `VideoEncoder` | `encode(&frame, force_keyframe) -> Vec<EncodedFrame>`, `set_bitrate(bps)`, `codec()`, `backend()` |
|
||||
| `EncodedFrame { data, keyframe, pts_90khz }` | one frame for `Peer::write` |
|
||||
| `VideoDecoder` | `decode(&[u8]) -> Option<VideoFrame>` (timestamp zero; the caller knows the RTP time) |
|
||||
| `EncoderConfig { fps, bitrate_bps, keyframe_interval, content, threads }` | resolution follows the frames; a size change restarts with a keyframe |
|
||||
| `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(&SourceId, &CaptureOptions)` (async: the portal asks the user), `stop()` |
|
||||
| `AudioCapture` | `start() -> FrameReceiver<AudioBuffer>`, `stop()` |
|
||||
| `FrameReceiver<T>` | bounded queue that drops the oldest item; `recv().await`, `try_recv()`, `recv_timeout()` |
|
||||
| `capture::default_screen_capture()`, `default_audio_capture()` | the backend for this session |
|
||||
| `capture::synthetic::{SyntheticScreen, SineSource}` | test pattern (moving rectangle, frame counter) and sine tone |
|
||||
|
||||
```rust
|
||||
let codecs = Codecs::new().with_openh264(OpenH264::find_in(&data_dir)?); // H.264 optional
|
||||
let mut capture = tsc_media::capture::default_screen_capture()?;
|
||||
let mut frames = capture.start(&SourceId::Monitor(0), &CaptureOptions::default()).await?;
|
||||
let codec = codecs.pick_encoder(&viewer_codecs).unwrap();
|
||||
let mut encoder = codecs.new_encoder(codec, EncoderConfig::default())?;
|
||||
while let Some(frame) = frames.recv().await {
|
||||
for f in encoder.encode(&frame, keyframe_requested)? {
|
||||
peer.write(MediaKind::Video, MediaTime::new(f.pts_90khz, Frequency::NINETY_KHZ), f.data);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Codecs
|
||||
|
||||
Preference: a viewer accepts VP9 > VP8 > AV1 > H.264; a streamer encodes with
|
||||
hardware > VP8 (libvpx) > H.264 (OpenH264) > VP9 (libvpx, expensive in
|
||||
software). `Codecs` filters both lists by what is compiled in and loaded.
|
||||
|
||||
| Backend | Feature | Encode | Decode | Library |
|
||||
|---|---|---|---|---|
|
||||
| libvpx | `vpx` (default) | VP8, VP9 | VP8, VP9 | system libvpx (1.14 tested), dynamically linked; bindings from `libvpx-native-sys` (pre-generated, no bindgen) |
|
||||
| OpenH264 | `openh264` (default) | H.264 Constrained High / Baseline | H.264 | Cisco's prebuilt binary, loaded at runtime |
|
||||
| dav1d | `av1` | – | AV1 | system libdav1d >= 1.3 (1.4.1 tested) |
|
||||
| hardware | – | not yet | – | `codec::hw::HardwareEncoderFactory`; VA-API and Media Foundation stubs report nothing (TODO) |
|
||||
|
||||
libvpx settings follow libwebrtc's realtime setup: one pass CBR, no lag,
|
||||
`VPX_DL_REALTIME`, error resilient, `cpu-used` 8 (VP8: fixed speed −8), keyframes
|
||||
only at start and on request unless `keyframe_interval` is set, screen content
|
||||
tuning (`VP8E_SET_SCREEN_CONTENT_MODE`, `VP9E_SET_TUNE_CONTENT`, static
|
||||
threshold), VP9 row-mt, tiles and cyclic-refresh AQ. `set_bitrate` reconfigures
|
||||
the running encoder (`vpx_codec_enc_config_set`). The C API is wrapped in
|
||||
`codec/vpx/raw.rs`, one of the two modules with `unsafe` code; existing safe
|
||||
wrappers either encode only or cannot change the bitrate at runtime.
|
||||
|
||||
The OpenH264 encoder has no safe runtime bitrate change in the `openh264`
|
||||
crate, so `set_bitrate` recreates it (the next frame is an IDR). It enables
|
||||
frame skipping so rate control can hold the bitrate (`encode` may then return
|
||||
no frame).
|
||||
|
||||
### OpenH264 and Cisco's license
|
||||
|
||||
H.264 is patent-encumbered. Cisco pays the MPEG LA royalties for its own
|
||||
OpenH264 binaries, but only when every user downloads the binary from Cisco
|
||||
themselves. Therefore:
|
||||
|
||||
- The OpenH264 source is never compiled (the `openh264` crate is used with
|
||||
`default-features = false, features = ["libloading"]`; its bundled sources
|
||||
stay unused in the registry).
|
||||
- `codec::h264::download_openh264(dir)` (feature `openh264-download`) fetches
|
||||
`https://ciscobinary.openh264.org/<file>.bz2` for this platform (OpenH264
|
||||
2.6.0), unpacks it, checks the SHA-256 against a pinned table, and stores it
|
||||
in `dir`. Call it only after the user opted in.
|
||||
- `OpenH264::load(path)` / `find_in(dir)` load only files whose SHA-256 matches
|
||||
a known Cisco build, so no other code gets executed.
|
||||
- The app must show `codec::h264::OPENH264_ATTRIBUTION` ("OpenH264 Video Codec
|
||||
provided by Cisco Systems, Inc.") next to the switch that enables it and in
|
||||
its About page / notices, must let the user disable it, and must not ship
|
||||
the binary in its packages. Cisco's binary is BSD-2-Clause licensed; its
|
||||
license text belongs in the notices shipped with the app.
|
||||
|
||||
Without the library, `Codecs` neither offers nor accepts H.264, and
|
||||
`OpenH264::load` fails with `Error::CodecUnavailable` ("OpenH264 library not
|
||||
found at ...").
|
||||
|
||||
## Capture
|
||||
|
||||
| Platform | Screen | System audio |
|
||||
|---|---|---|
|
||||
| any | `SyntheticScreen` | `SineSource` |
|
||||
| Linux X11 (`x11`, default) | `X11Capture`: MIT-SHM 1.2 (memfd passed to the server) or GetImage; RandR 1.5 monitors; windows from `_NET_CLIENT_LIST` (root children without a WM); XFixes cursor blended in | |
|
||||
| Linux Wayland (`pipewire`, default) | `PortalCapture`: xdg-desktop-portal ScreenCast via `ashpd`, frames from a PipeWire video stream | `PipeWireAudioCapture`: default sink monitor (`stream.capture.sink = true`) |
|
||||
| Windows | `WindowsCapture`: Windows Graphics Capture (`windows-capture`), monitors and windows | `WasapiLoopback`: process loopback excluding our own process tree, falling back to plain loopback |
|
||||
|
||||
`default_screen_capture()` picks the portal when `WAYLAND_DISPLAY` is set (or
|
||||
`XDG_SESSION_TYPE=wayland`), X11 when `DISPLAY` is set, WGC on Windows.
|
||||
|
||||
Notes:
|
||||
|
||||
- X11 needs a 24/32-bit TrueColor visual (BGRx in memory). Window capture
|
||||
reads the window itself, clipped to the screen; without a compositor, parts
|
||||
covered by other windows may be stale. MIT-SHM needs a local server with
|
||||
MIT-SHM 1.2; otherwise GetImage is used. The only `unsafe` here is mapping
|
||||
our memfd (`capture/x11/shm.rs`).
|
||||
- Portal: `start` needs a tokio runtime (zbus runs on it) and may show the
|
||||
desktop's picker. Choices persist with `PersistMode::ExplicitlyRevoked`: store
|
||||
`PortalCapture::restore_token()` (e.g. in `tsc-store` settings) and pass it to
|
||||
`PortalCapture::with_restore_token` next time. The cursor is embedded when
|
||||
the portal supports it. Only shared-memory buffers (BGRx/BGRA/RGBx/RGBA) are
|
||||
negotiated; DMA-BUF import is a TODO. Without a session bus or portal,
|
||||
`start` returns `Error::CaptureUnavailable`; a cancelled dialog returns
|
||||
`Error::Cancelled`.
|
||||
- PipeWire system audio captures everything the default sink plays, including
|
||||
our own playback (TeamSpeak voices): PipeWire has no "all but this process"
|
||||
monitor. Excluding our nodes needs a private null sink with links from every
|
||||
other application's output (via the registry); TODO. Until then, play voices
|
||||
on another sink or accept that viewers hear them. Without a PipeWire daemon,
|
||||
`start` returns `Error::CaptureUnavailable`.
|
||||
- Windows process loopback needs Windows 10 2004 or later.
|
||||
|
||||
## Build requirements
|
||||
|
||||
Linux (Debian/Ubuntu packages): `libvpx-dev` (feature `vpx`),
|
||||
`libpipewire-0.3-dev libspa-0.2-dev libclang-dev` (feature `pipewire`; the
|
||||
PipeWire bindings run bindgen), `pkg-config`, and `libdav1d-dev` for
|
||||
`--features av1`. X11 capture is pure Rust (x11rb) and needs no packages.
|
||||
Tests of X11 capture need an X server: `xvfb`, run with `xvfb-run -a cargo
|
||||
test -p tsc-media` (skipped without `DISPLAY`).
|
||||
|
||||
Windows: libvpx is not found through pkg-config there. Install it (e.g.
|
||||
`vcpkg install libvpx:x64-windows`) and set `VPX_LIB_DIR`, `VPX_INCLUDE_DIR`
|
||||
and `VPX_VERSION`, or build without the `vpx` feature. The Windows capture
|
||||
code is type-checked on Linux (`cargo clippy -p tsc-media --target
|
||||
x86_64-pc-windows-gnu --no-default-features --features openh264`) but has not
|
||||
run on Windows yet.
|
||||
|
||||
## Licenses
|
||||
|
||||
| Component | License | How it is used |
|
||||
|---|---|---|
|
||||
| libvpx | BSD-3-Clause | system library, dynamic |
|
||||
| `libvpx-native-sys` | MPL-2.0 | unmodified bindings |
|
||||
| `yuv` (yuvutils-rs) | BSD-3-Clause OR Apache-2.0 | |
|
||||
| `openh264` / `openh264-sys2` | BSD-2-Clause | bindings, `libloading` only |
|
||||
| Cisco OpenH264 binary | BSD-2-Clause + Cisco's royalty coverage | downloaded by the user, see above |
|
||||
| `dav1d` crate / libdav1d | MIT / BSD-2-Clause | optional, system library |
|
||||
| `x11rb`, `memmap2`, `rustix` | MIT OR Apache-2.0 (rustix also Apache-2.0 WITH LLVM-exception) | |
|
||||
| `ashpd`, `pipewire`, `libspa` / libpipewire | MIT | libpipewire is dynamic |
|
||||
| `windows-capture`, `wasapi`, `windows` | MIT (`windows`: MIT OR Apache-2.0) | Windows only |
|
||||
| `bzip2` / `libbz2-rs-sys` | MIT OR Apache-2.0 / bzip2-1.0.6 | unpacks the OpenH264 download; `bzip2-1.0.6` is allowed in `deny.toml` |
|
||||
|
||||
## Verification status
|
||||
|
||||
| What | How | Status |
|
||||
|---|---|---|
|
||||
| Frame validation, YUV ↔ RGB (values, NV12, odd sizes, strides) | unit tests | tested |
|
||||
| VP8 / VP9 encode → decode (PSNR > 30 dB, rectangle colour, forced keyframes, bitrate change, resolution change) | unit tests, `tests/codec_roundtrip.rs` | tested |
|
||||
| H.264 with Cisco's 2.6.0 library (PSNR, Constrained High `profile_idc` 100, Baseline 66) | `tests/openh264.rs` with `TSC_OPENH264_LIB` | tested locally, skipped without the library |
|
||||
| OpenH264 download, SHA-256 check, reuse | `tests/openh264.rs -- --ignored` | tested locally (network) |
|
||||
| H.264 library missing / unknown file | unit + integration tests | tested |
|
||||
| AV1 decoder construction, garbage input | unit test (`--features av1`) | tested; no AV1 stream decoded (no encoder available) |
|
||||
| X11 capture (MIT-SHM and GetImage), sources, window capture → VP8 → decode, cursor | `tests/x11_capture.rs` under Xvfb | tested |
|
||||
| Portal / PipeWire error paths (no bus, bus without portal, no daemon) | unit tests, manual probe | tested |
|
||||
| Portal capture, PipeWire video and audio streams | – | compiles only (no portal or PipeWire daemon here) |
|
||||
| Windows Graphics Capture, WASAPI | – | type-checked for `x86_64-pc-windows-gnu` only |
|
||||
| Hardware encoders | – | stubs |
|
||||
Reference in new issue
Block a user