perf: vers 60 i/s, envoi déclenché par l'encodeur et banc de latence
CI / Formatting, tests and builds (push) Successful in 4m6s
CI / Formatting, tests and builds (push) Successful in 4m6s
Banc de bout en bout (scripts/bench-latency.sh): la mire écrit l'instant de sa capture dans l'image, le viewer le relit à chaque image affichée (?perf=1, requestVideoFrameCallback). En 1080p à 60 i/s, 60 images affichées au lieu de 49 à 53, latence p95 de 34 à 39 ms au lieu de 1,6 s. L'encodeur prévient les sessions par un watch au lieu d'être interrogé à cadence fixe, et l'horodatage RTP vient de l'instant de capture. Une image inchangée (fresh) n'est réencodée qu'une fois par seconde, les images partagent leur tampon (Arc). La cadence se divise par deux quand le travail par image dépasse 85 % de la période, et remonte avec la marge. Conversion de couleur réécrite en une passe sur des paires de lignes, identique au pixel près, en bandes parallèles au-delà de 2560x1440. Profils revus pour le réseau local: équilibré à 60 i/s et 6 Mbit/s. Chiffres avant et après dans docs/perf.md. Reste le même banc sur un vrai écran. Refs #86 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
a7a77208fb
commit
a49d1002f8
25 files changed
+1161
-100
No files matched your search
Generated
+1
@@ -1668,6 +1668,7 @@ dependencies = [
|
||||
"rs-capture",
|
||||
"rs-proto",
|
||||
"thiserror",
|
||||
"tokio",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
|
||||
Generated
+1
@@ -3470,6 +3470,7 @@ dependencies = [
|
||||
"env-libvpx-sys",
|
||||
"rs-capture",
|
||||
"thiserror 2.0.21",
|
||||
"tokio",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
|
||||
import { probeRequested, startProbe } from '../lib/perfProbe';
|
||||
import { type Rotation, rotatedBox } from '../lib/rotation';
|
||||
|
||||
type Props = {
|
||||
@@ -33,6 +34,13 @@ export function VideoStage({ stream, live, label, rotation, mirror }: Props) {
|
||||
}
|
||||
}, [stream]);
|
||||
|
||||
// Latency probe for the bench (#86), only when the URL asks for it.
|
||||
useEffect(() => {
|
||||
const video = videoRef.current;
|
||||
if (!video || !probeRequested(window.location.search)) return;
|
||||
return startProbe(video);
|
||||
}, []);
|
||||
|
||||
// The turned box depends on the stage size: full screen, switching to
|
||||
// portrait, the virtual keyboard all change it.
|
||||
useEffect(() => {
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { readStamp, STAMP_BITS, STAMP_BLOCK, STAMP_MARGIN, summarize } from './perfProbe';
|
||||
|
||||
function stripFor(millis: number): { rgba: Uint8ClampedArray; width: number } {
|
||||
const width = STAMP_MARGIN * 2 + STAMP_BITS * STAMP_BLOCK;
|
||||
const height = STAMP_MARGIN * 2 + 2 * STAMP_BLOCK;
|
||||
const rgba = new Uint8ClampedArray(width * height * 4);
|
||||
const paint = (bit: number, line: number, on: boolean) => {
|
||||
const y0 = STAMP_MARGIN + line * STAMP_BLOCK;
|
||||
const x0 = STAMP_MARGIN + bit * STAMP_BLOCK;
|
||||
for (let y = y0; y < y0 + STAMP_BLOCK; y++) {
|
||||
for (let x = x0; x < x0 + STAMP_BLOCK; x++) {
|
||||
rgba.fill(on ? 250 : 5, (y * width + x) * 4, (y * width + x) * 4 + 3);
|
||||
}
|
||||
}
|
||||
};
|
||||
for (let bit = 0; bit < STAMP_BITS; bit++) {
|
||||
const set = Math.floor(millis / 2 ** (STAMP_BITS - 1 - bit)) % 2 === 1;
|
||||
// Row 0: the bit; row 1: its complement, as the test pattern draws it.
|
||||
paint(bit, 0, set);
|
||||
paint(bit, 1, !set);
|
||||
}
|
||||
return { rgba, width };
|
||||
}
|
||||
|
||||
describe('latency probe (#86)', () => {
|
||||
it('reads back the capture instant written by the test pattern', () => {
|
||||
const millis = 1_793_034_067_276;
|
||||
const { rgba, width } = stripFor(millis);
|
||||
expect(readStamp(rgba, width)).toBe(millis);
|
||||
});
|
||||
|
||||
it('rejects a stamp blurred by compression instead of misreading it', () => {
|
||||
const { rgba, width } = stripFor(1_793_034_067_276);
|
||||
// Bit 11 (2048 ms) turns gray on its first row.
|
||||
const x = STAMP_MARGIN + 36 * STAMP_BLOCK + STAMP_BLOCK / 2;
|
||||
const y = STAMP_MARGIN + STAMP_BLOCK / 2;
|
||||
rgba.fill(128, (y * width + x) * 4, (y * width + x) * 4 + 3);
|
||||
expect(readStamp(rgba, width)).toBeNull();
|
||||
});
|
||||
|
||||
it('summarizes latency percentiles and displayed frames per second', () => {
|
||||
const times = Array.from({ length: 120 }, (_, i) => i * (1000 / 60));
|
||||
const summary = summarize([10, 20, 30, 40, 100], times, 2, 120, { width: 1920, height: 1080 });
|
||||
expect(summary.latencyMs).toEqual({ median: 30, p95: 100, max: 100 });
|
||||
expect(summary.fps).toBe(60);
|
||||
expect(summary.skipped).toBe(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,155 @@
|
||||
/**
|
||||
* Latency probe (#86), enabled with `?perf=1` in the session URL.
|
||||
*
|
||||
* The synthetic test pattern writes its capture instant (Unix milliseconds)
|
||||
* as a row of black and white blocks. For every displayed frame
|
||||
* (`requestVideoFrameCallback`), the probe reads that row back and measures
|
||||
* the end-to-end latency: capture, conversion, encoding, network, decoding
|
||||
* and display, on one clock when host and viewer share a machine. It also
|
||||
* counts displayed frames per second and skipped frames.
|
||||
*
|
||||
* The results are exposed on `window.__rustscreenPerf` for the bench script;
|
||||
* nothing is shown to the user.
|
||||
*/
|
||||
|
||||
/** Layout of the stamp, in step with `rs-capture/src/synthetic.rs`. */
|
||||
export const STAMP_BITS = 48;
|
||||
export const STAMP_BLOCK = 16;
|
||||
export const STAMP_MARGIN = 8;
|
||||
|
||||
/**
|
||||
* Reads the stamp from RGBA pixels of the top-left strip, `width` wide. The
|
||||
* second row holds the complement: a bit blurred by compression on either
|
||||
* row makes the whole stamp unreadable rather than wrong.
|
||||
*/
|
||||
export function readStamp(rgba: Uint8ClampedArray, width: number): number | null {
|
||||
let millis = 0;
|
||||
for (let bit = 0; bit < STAMP_BITS; bit++) {
|
||||
const x = STAMP_MARGIN + bit * STAMP_BLOCK + STAMP_BLOCK / 2;
|
||||
const at = (line: number) =>
|
||||
rgba[((STAMP_MARGIN + line * STAMP_BLOCK + STAMP_BLOCK / 2) * width + x) * 4 + 1];
|
||||
const value = at(0);
|
||||
const complement = at(1);
|
||||
if (value === undefined || complement === undefined) return null;
|
||||
if (Math.abs(value - complement) < 128) return null;
|
||||
millis = millis * 2 + (value > complement ? 1 : 0);
|
||||
}
|
||||
return millis;
|
||||
}
|
||||
|
||||
export type PerfSummary = {
|
||||
frames: number;
|
||||
/** Displayed frames per second over the last second. */
|
||||
fps: number;
|
||||
/** Frames the compositor never showed (`presentedFrames` gaps). */
|
||||
skipped: number;
|
||||
latencyMs: { median: number; p95: number; max: number } | null;
|
||||
width: number;
|
||||
height: number;
|
||||
};
|
||||
|
||||
const STAMP_MODULO = 2 ** STAMP_BITS;
|
||||
|
||||
export function summarize(
|
||||
latencies: number[],
|
||||
presentTimes: number[],
|
||||
skipped: number,
|
||||
frames: number,
|
||||
size: { width: number; height: number },
|
||||
): PerfSummary {
|
||||
const sorted = [...latencies].sort((a, b) => a - b);
|
||||
const pick = (q: number) =>
|
||||
sorted[Math.min(sorted.length - 1, Math.floor(q * sorted.length))] ?? 0;
|
||||
const last = presentTimes.at(-1) ?? 0;
|
||||
const fps = presentTimes.filter((t) => last - t < 1000).length;
|
||||
return {
|
||||
frames,
|
||||
fps,
|
||||
skipped,
|
||||
latencyMs: sorted.length
|
||||
? { median: pick(0.5), p95: pick(0.95), max: sorted.at(-1) ?? 0 }
|
||||
: null,
|
||||
width: size.width,
|
||||
height: size.height,
|
||||
};
|
||||
}
|
||||
|
||||
type FrameCallbackVideo = HTMLVideoElement & {
|
||||
requestVideoFrameCallback?: (
|
||||
callback: (
|
||||
now: number,
|
||||
metadata: { presentedFrames: number; expectedDisplayTime: number },
|
||||
) => void,
|
||||
) => number;
|
||||
cancelVideoFrameCallback?: (handle: number) => void;
|
||||
};
|
||||
|
||||
/** Starts the probe on `video`; returns the function that stops it. */
|
||||
export function startProbe(video: HTMLVideoElement): () => void {
|
||||
const target = video as FrameCallbackVideo;
|
||||
if (!target.requestVideoFrameCallback) return () => undefined;
|
||||
const canvas = document.createElement('canvas');
|
||||
const width = STAMP_MARGIN * 2 + STAMP_BITS * STAMP_BLOCK;
|
||||
const height = STAMP_MARGIN * 2 + 2 * STAMP_BLOCK;
|
||||
canvas.width = width;
|
||||
canvas.height = height;
|
||||
const context = canvas.getContext('2d', { willReadFrequently: true });
|
||||
const latencies: number[] = [];
|
||||
const presentTimes: number[] = [];
|
||||
let skipped = 0;
|
||||
let frames = 0;
|
||||
let lastPresented: number | null = null;
|
||||
let handle = 0;
|
||||
let stopped = false;
|
||||
|
||||
const onFrame = (
|
||||
_now: number,
|
||||
metadata: { presentedFrames: number; expectedDisplayTime: number },
|
||||
) => {
|
||||
if (stopped) return;
|
||||
frames++;
|
||||
if (lastPresented !== null && metadata.presentedFrames > lastPresented + 1) {
|
||||
skipped += metadata.presentedFrames - lastPresented - 1;
|
||||
}
|
||||
lastPresented = metadata.presentedFrames;
|
||||
presentTimes.push(metadata.expectedDisplayTime);
|
||||
if (presentTimes.length > 600) presentTimes.shift();
|
||||
if (context && video.videoWidth >= width) {
|
||||
context.drawImage(video, 0, 0, width, height, 0, 0, width, height);
|
||||
const stamp = readStamp(context.getImageData(0, 0, width, height).data, width);
|
||||
if (stamp !== null) {
|
||||
const shown = (performance.timeOrigin + metadata.expectedDisplayTime) % STAMP_MODULO;
|
||||
const latency = shown - stamp;
|
||||
if (latency > -50 && latency < 5000) {
|
||||
latencies.push(Math.max(0, latency));
|
||||
if (latencies.length > 3000) latencies.shift();
|
||||
}
|
||||
}
|
||||
}
|
||||
handle = target.requestVideoFrameCallback?.(onFrame) ?? 0;
|
||||
};
|
||||
handle = target.requestVideoFrameCallback(onFrame);
|
||||
|
||||
(window as unknown as { __rustscreenPerf?: unknown }).__rustscreenPerf = {
|
||||
summary: () =>
|
||||
summarize(latencies, presentTimes, skipped, frames, {
|
||||
width: video.videoWidth,
|
||||
height: video.videoHeight,
|
||||
}),
|
||||
reset: () => {
|
||||
latencies.length = 0;
|
||||
presentTimes.length = 0;
|
||||
skipped = 0;
|
||||
frames = 0;
|
||||
},
|
||||
};
|
||||
return () => {
|
||||
stopped = true;
|
||||
target.cancelVideoFrameCallback?.(handle);
|
||||
};
|
||||
}
|
||||
|
||||
/** The probe runs only when the URL asks for it. */
|
||||
export function probeRequested(search: string): boolean {
|
||||
return new URLSearchParams(search).get('perf') === '1';
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { createTranslator } from './i18n';
|
||||
import { backoffDelay, isRetryable, isTerminal, messageFor } from './session';
|
||||
import { backoffDelay, isRetryable, isTerminal, messageFor, minimizeJitterBuffer } from './session';
|
||||
|
||||
describe('backoffDelay', () => {
|
||||
it('doubles at each attempt then caps', () => {
|
||||
@@ -69,3 +69,15 @@ describe('messageFor', () => {
|
||||
expect(messageFor('something_new', t)).toBe('Connexion perdue.');
|
||||
});
|
||||
});
|
||||
|
||||
describe('minimizeJitterBuffer (#86)', () => {
|
||||
it('sets the standard target when the browser has it, the older hint otherwise', () => {
|
||||
const standard = { jitterBufferTarget: null } as unknown as RTCRtpReceiver;
|
||||
minimizeJitterBuffer(standard);
|
||||
expect((standard as unknown as { jitterBufferTarget: number }).jitterBufferTarget).toBe(0);
|
||||
const older = { playoutDelayHint: null } as unknown as RTCRtpReceiver;
|
||||
minimizeJitterBuffer(older);
|
||||
expect((older as unknown as { playoutDelayHint: number }).playoutDelayHint).toBe(0);
|
||||
expect(() => minimizeJitterBuffer({} as RTCRtpReceiver)).not.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -350,6 +350,7 @@ export class ViewerSession {
|
||||
pc.addTransceiver('video', { direction: 'recvonly' });
|
||||
pc.addEventListener('track', (event) => {
|
||||
if (!current()) return;
|
||||
minimizeJitterBuffer(event.receiver);
|
||||
const [stream] = event.streams;
|
||||
this.options.onStream(stream ?? new MediaStream([event.track]));
|
||||
});
|
||||
@@ -508,3 +509,21 @@ async function waitForIceGathering(pc: RTCPeerConnection, timeoutMs: number): Pr
|
||||
pc.addEventListener('icegatheringstatechange', check);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Asks the browser to hold as few frames as possible before display (#86).
|
||||
* Its jitter buffer is sized for calls over the Internet; on a local network
|
||||
* a screen share wants the frame on screen as soon as it is decoded.
|
||||
* `jitterBufferTarget` is the standard (Chrome 114+, Firefox 125+),
|
||||
* `playoutDelayHint` the older Chrome spelling. Unknown to the browser: no
|
||||
* effect.
|
||||
*/
|
||||
export function minimizeJitterBuffer(receiver: RTCRtpReceiver): void {
|
||||
const tunable = receiver as unknown as Record<string, unknown>;
|
||||
try {
|
||||
if ('jitterBufferTarget' in tunable) tunable.jitterBufferTarget = 0;
|
||||
else if ('playoutDelayHint' in tunable) tunable.playoutDelayHint = 0;
|
||||
} catch {
|
||||
// A browser refusing the value keeps its default.
|
||||
}
|
||||
}
|
||||
@@ -11,9 +11,15 @@ use std::time::Instant;
|
||||
pub struct CapturedFrame {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
/// Width * height * 4 bytes, in B, G, R, A order.
|
||||
pub bgra: Vec<u8>,
|
||||
/// Width * height * 4 bytes, in B, G, R, A order. Shared: a source that
|
||||
/// repeats its last image hands out the same buffer, without a copy.
|
||||
pub bgra: std::sync::Arc<Vec<u8>>,
|
||||
pub captured_at: Instant,
|
||||
/// The image changed since the previous frame. A compositor that sends
|
||||
/// images only on change (GNOME) makes most frames of an idle screen
|
||||
/// repeats: the encoder can skip them (#86). A source that cannot tell
|
||||
/// says `true`.
|
||||
pub fresh: bool,
|
||||
/// Sequence number, to detect a skipped or duplicated frame.
|
||||
pub sequence: u64,
|
||||
}
|
||||
|
||||
@@ -102,8 +102,12 @@ pub struct PipeWireCapturer {
|
||||
/// Size negotiated at start, to describe the source. Images then follow
|
||||
/// the current size of the stream.
|
||||
output: Option<(u32, u32)>,
|
||||
last: Vec<u8>,
|
||||
fitted: Vec<u8>,
|
||||
/// Last image from the compositor, shared with the encoder: repeating
|
||||
/// it costs no copy.
|
||||
last: Arc<Vec<u8>>,
|
||||
/// The same image trimmed to even dimensions, when the stream has an odd
|
||||
/// one; computed once per new image.
|
||||
fitted: Option<Arc<Vec<u8>>>,
|
||||
started: bool,
|
||||
}
|
||||
|
||||
@@ -155,8 +159,8 @@ impl PipeWireCapturer {
|
||||
cadence: Cadence::new(options.fps),
|
||||
sequence: 0,
|
||||
output: None,
|
||||
last: Vec::new(),
|
||||
fitted: Vec::new(),
|
||||
last: Arc::new(Vec::new()),
|
||||
fitted: None,
|
||||
started: false,
|
||||
})
|
||||
}
|
||||
@@ -263,8 +267,12 @@ impl ScreenCapturer for PipeWireCapturer {
|
||||
}
|
||||
|
||||
let (w, h) = state.size;
|
||||
if state.fresh {
|
||||
std::mem::swap(&mut self.last, &mut state.bgra);
|
||||
// The compositor sends an image only when the screen changes (GNOME):
|
||||
// without one, this frame repeats the last, and says so (#86).
|
||||
let fresh = state.fresh;
|
||||
if fresh {
|
||||
self.last = Arc::new(std::mem::take(&mut state.bgra));
|
||||
self.fitted = None;
|
||||
state.fresh = false;
|
||||
}
|
||||
drop(state);
|
||||
@@ -274,16 +282,20 @@ impl ScreenCapturer for PipeWireCapturer {
|
||||
// Only an odd dimension is trimmed.
|
||||
let output = pixels::even((w, h));
|
||||
let bgra = if (w, h) == output {
|
||||
self.last.clone()
|
||||
Arc::clone(&self.last)
|
||||
} else {
|
||||
pixels::fit(
|
||||
&self.last,
|
||||
w as usize,
|
||||
h as usize,
|
||||
(output.0 as usize, output.1 as usize),
|
||||
&mut self.fitted,
|
||||
);
|
||||
self.fitted.clone()
|
||||
let last = &self.last;
|
||||
Arc::clone(self.fitted.get_or_insert_with(|| {
|
||||
let mut fitted = Vec::new();
|
||||
pixels::fit(
|
||||
last,
|
||||
w as usize,
|
||||
h as usize,
|
||||
(output.0 as usize, output.1 as usize),
|
||||
&mut fitted,
|
||||
);
|
||||
Arc::new(fitted)
|
||||
}))
|
||||
};
|
||||
|
||||
let frame = CapturedFrame {
|
||||
@@ -291,6 +303,7 @@ impl ScreenCapturer for PipeWireCapturer {
|
||||
height: output.1,
|
||||
bgra,
|
||||
captured_at: Instant::now(),
|
||||
fresh,
|
||||
sequence: self.sequence,
|
||||
};
|
||||
self.sequence += 1;
|
||||
|
||||
@@ -4,8 +4,17 @@
|
||||
//! It draws three bands (red, green, blue) and a moving white square. This is
|
||||
//! what lets you check in a browser that the colors land in the right place
|
||||
//! and that the image moves, instead of merely seeing bytes flow.
|
||||
//!
|
||||
//! The top rows carry a latency stamp (#86): the capture instant, in Unix
|
||||
//! milliseconds, as [`STAMP_BITS`] black or white blocks, then the same bits
|
||||
//! inverted on a second row. A reader accepts a stamp only when both rows
|
||||
//! disagree clearly on every bit, so a block blurred by compression is
|
||||
//! rejected instead of misread. The viewer reads it
|
||||
//! back when the frame is displayed, which measures the whole chain (capture,
|
||||
//! conversion, encoding, network, decoding, display) on one clock.
|
||||
|
||||
use std::time::{Duration, Instant};
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use rs_proto::{SourceId, SourceInfo, SourceKind};
|
||||
|
||||
@@ -16,6 +25,14 @@ pub const SOURCE_ID: &str = "synthetic";
|
||||
|
||||
const SQUARE: usize = 120;
|
||||
|
||||
/// Bits of the latency stamp: Unix milliseconds modulo 2^48 (8900 years).
|
||||
pub const STAMP_BITS: usize = 48;
|
||||
/// Side of one stamp block, in pixels: large enough to survive compression
|
||||
/// at any bitrate the encoder uses.
|
||||
pub const STAMP_BLOCK: usize = 16;
|
||||
/// Left and top margin of the stamp, in pixels.
|
||||
pub const STAMP_MARGIN: usize = 8;
|
||||
|
||||
pub struct SyntheticCapturer {
|
||||
width: usize,
|
||||
height: usize,
|
||||
@@ -23,8 +40,10 @@ pub struct SyntheticCapturer {
|
||||
sequence: u64,
|
||||
next_at: Option<Instant>,
|
||||
started: bool,
|
||||
/// Current image, reused from one frame to the next.
|
||||
bgra: Vec<u8>,
|
||||
/// Current image, reused from one frame to the next: painting goes
|
||||
/// through `Arc::make_mut`, which copies only if the encoder still holds
|
||||
/// the previous frame.
|
||||
bgra: Arc<Vec<u8>>,
|
||||
/// Last square drawn, to erase before drawing the next one.
|
||||
last_square: Option<(usize, usize)>,
|
||||
}
|
||||
@@ -40,7 +59,7 @@ impl SyntheticCapturer {
|
||||
sequence: 0,
|
||||
next_at: None,
|
||||
started: false,
|
||||
bgra: vec![0; width * height * 4],
|
||||
bgra: Arc::new(vec![0; width * height * 4]),
|
||||
last_square: None,
|
||||
}
|
||||
}
|
||||
@@ -57,28 +76,34 @@ impl SyntheticCapturer {
|
||||
}
|
||||
|
||||
fn fill_bands(&mut self) {
|
||||
let third = self.width / 3;
|
||||
for row in 0..self.height {
|
||||
for col in 0..self.width {
|
||||
let width = self.width;
|
||||
let height = self.height;
|
||||
let third = width / 3;
|
||||
let bgra = Arc::make_mut(&mut self.bgra);
|
||||
for row in 0..height {
|
||||
for col in 0..width {
|
||||
let color = band_color(col, third);
|
||||
let index = (row * self.width + col) * 4;
|
||||
self.bgra[index..index + 4].copy_from_slice(&color);
|
||||
let index = (row * width + col) * 4;
|
||||
bgra[index..index + 4].copy_from_slice(&color);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn fill_rect(&mut self, x: usize, y: usize, size: usize, color: [u8; 4]) {
|
||||
let third = self.width / 3;
|
||||
for row in y..(y + size).min(self.height) {
|
||||
for col in x..(x + size).min(self.width) {
|
||||
let index = (row * self.width + col) * 4;
|
||||
let width = self.width;
|
||||
let height = self.height;
|
||||
let third = width / 3;
|
||||
let bgra = Arc::make_mut(&mut self.bgra);
|
||||
for row in y..(y + size).min(height) {
|
||||
for col in x..(x + size).min(width) {
|
||||
let index = (row * width + col) * 4;
|
||||
// The white rectangle is erased by repainting the original band.
|
||||
let value = if color == [255, 255, 255, 255] {
|
||||
color
|
||||
} else {
|
||||
band_color(col, third)
|
||||
};
|
||||
self.bgra[index..index + 4].copy_from_slice(&value);
|
||||
bgra[index..index + 4].copy_from_slice(&value);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -96,6 +121,60 @@ impl SyntheticCapturer {
|
||||
}
|
||||
}
|
||||
|
||||
impl SyntheticCapturer {
|
||||
/// Writes `millis` as the latency stamp, most significant bit first. A
|
||||
/// pattern too narrow for the stamp simply goes without it.
|
||||
fn paint_stamp(&mut self, millis: u64) {
|
||||
let needed = STAMP_MARGIN * 2 + STAMP_BITS * STAMP_BLOCK;
|
||||
if self.width < needed || self.height < STAMP_MARGIN * 2 + 2 * STAMP_BLOCK {
|
||||
return;
|
||||
}
|
||||
let width = self.width;
|
||||
let bgra = Arc::make_mut(&mut self.bgra);
|
||||
for bit in 0..STAMP_BITS {
|
||||
let set = (millis >> (STAMP_BITS - 1 - bit)) & 1 == 1;
|
||||
let x0 = STAMP_MARGIN + bit * STAMP_BLOCK;
|
||||
// Row 0: the bit; row 1: its complement.
|
||||
for (line, on) in [(0, set), (1, !set)] {
|
||||
let value = if on { 255 } else { 0 };
|
||||
let y0 = STAMP_MARGIN + line * STAMP_BLOCK;
|
||||
for row in y0..y0 + STAMP_BLOCK {
|
||||
for col in x0..x0 + STAMP_BLOCK {
|
||||
let index = (row * width + col) * 4;
|
||||
bgra[index..index + 4].copy_from_slice(&[value, value, value, 255]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads a latency stamp back from a BGRA image, for tests and tools.
|
||||
/// `None` when a bit is unclear on either row.
|
||||
pub fn read_stamp(bgra: &[u8], width: usize) -> Option<u64> {
|
||||
let mut millis = 0u64;
|
||||
for bit in 0..STAMP_BITS {
|
||||
let x = STAMP_MARGIN + bit * STAMP_BLOCK + STAMP_BLOCK / 2;
|
||||
let at = |line: usize| -> Option<i32> {
|
||||
let y = STAMP_MARGIN + line * STAMP_BLOCK + STAMP_BLOCK / 2;
|
||||
bgra.get((y * width + x) * 4 + 1).map(|g| i32::from(*g))
|
||||
};
|
||||
let (value, complement) = (at(0)?, at(1)?);
|
||||
if (value - complement).abs() < 128 {
|
||||
return None;
|
||||
}
|
||||
millis = (millis << 1) | u64::from(value > complement);
|
||||
}
|
||||
Some(millis)
|
||||
}
|
||||
|
||||
fn unix_millis() -> u64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map_or(0, |d| d.as_millis() as u64)
|
||||
& ((1 << STAMP_BITS) - 1)
|
||||
}
|
||||
|
||||
fn band_color(col: usize, third: usize) -> [u8; 4] {
|
||||
if col < third {
|
||||
// BGRA: red
|
||||
@@ -151,11 +230,13 @@ impl ScreenCapturer for SyntheticCapturer {
|
||||
self.next_at = Some(due + period);
|
||||
|
||||
self.paint_next();
|
||||
self.paint_stamp(unix_millis());
|
||||
let frame = CapturedFrame {
|
||||
width: self.width as u32,
|
||||
height: self.height as u32,
|
||||
bgra: self.bgra.clone(),
|
||||
bgra: Arc::clone(&self.bgra),
|
||||
captured_at: Instant::now(),
|
||||
fresh: true,
|
||||
sequence: self.sequence,
|
||||
};
|
||||
self.sequence += 1;
|
||||
@@ -207,6 +288,20 @@ mod tests {
|
||||
assert_ne!(first.bgra, second.bgra, "the square must have moved");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_frame_carries_its_capture_instant() {
|
||||
let mut capturer = SyntheticCapturer::new(1280, 720, 60);
|
||||
capturer.start(&SourceId(SOURCE_ID.into())).unwrap();
|
||||
let before = unix_millis();
|
||||
let frame = capturer.next_frame().unwrap();
|
||||
let after = unix_millis();
|
||||
let stamp = read_stamp(&frame.bgra, frame.width as usize).unwrap();
|
||||
assert!(
|
||||
(before..=after).contains(&stamp),
|
||||
"{before} <= {stamp} <= {after}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn odd_dimensions_are_rounded_down() {
|
||||
let capturer = SyntheticCapturer::new(301, 121, 30);
|
||||
|
||||
@@ -670,7 +670,9 @@ impl ScreenCapturer for X11Capturer {
|
||||
let frame = CapturedFrame {
|
||||
width: output.0,
|
||||
height: output.1,
|
||||
bgra,
|
||||
bgra: std::sync::Arc::new(bgra),
|
||||
// X11 cannot tell an unchanged image without XDamage.
|
||||
fresh: true,
|
||||
captured_at: Instant::now(),
|
||||
sequence: self.sequence,
|
||||
};
|
||||
|
||||
@@ -10,6 +10,8 @@ repository.workspace = true
|
||||
[dependencies]
|
||||
rs-capture = { path = "../rs-capture" }
|
||||
thiserror.workspace = true
|
||||
# `watch` only: the encoding thread tells the sessions a frame is ready (#86).
|
||||
tokio = { version = "1.54.1", default-features = false, features = ["sync"] }
|
||||
tracing.workspace = true
|
||||
# Direct binding to libvpx: `vpx-encode` controlled neither the lag queue nor
|
||||
# forced keyframes (#67). The `unsafe` code lives in `src/vpx.rs`.
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
//! Splits the per-frame cost of the encoding thread into its stages (#86):
|
||||
//! BGRA to I420 conversion, then encoding, at a given size.
|
||||
//!
|
||||
//! cargo run --release -p rs-codec --example bench_stages -- 1920x1080 vp8 60
|
||||
//!
|
||||
//! The image moves a little every frame (a band of "text" scrolls), like a
|
||||
//! desktop being used: an immobile image would let the encoder skip almost
|
||||
//! everything and hide its real cost.
|
||||
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use rs_codec::{BgraFrame, EncodeConfig, VideoCodec, VideoEncoder, VpxEncoder, bgra_to_i420};
|
||||
|
||||
fn desktop_frame(width: usize, height: usize, frame: usize) -> Vec<u8> {
|
||||
let mut data = vec![0u8; width * height * 4];
|
||||
for y in 0..height {
|
||||
for x in 0..width {
|
||||
let i = (y * width + x) * 4;
|
||||
// Flat background with a scrolling band of fine "text" detail.
|
||||
let text_band = (height / 3..height / 3 + 200).contains(&y);
|
||||
let v = if text_band && ((x + frame * 3) % 7 < 2) && (y % 9 < 6) {
|
||||
20
|
||||
} else {
|
||||
235
|
||||
};
|
||||
data[i..i + 4].copy_from_slice(&[v, v, v.saturating_sub(10), 255]);
|
||||
}
|
||||
}
|
||||
data
|
||||
}
|
||||
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut args = std::env::args().skip(1);
|
||||
let size = args.next().unwrap_or_else(|| "1920x1080".into());
|
||||
let codec = match args.next().as_deref() {
|
||||
Some("vp9") => VideoCodec::Vp9,
|
||||
_ => VideoCodec::Vp8,
|
||||
};
|
||||
let fps: u8 = args.next().map_or(Ok(60), |f| f.parse())?;
|
||||
let (width, height) = size
|
||||
.split_once('x')
|
||||
.and_then(|(w, h)| Some((w.parse::<usize>().ok()?, h.parse::<usize>().ok()?)))
|
||||
.ok_or("size: WIDTHxHEIGHT")?;
|
||||
|
||||
let frames: Vec<Vec<u8>> = (0..30).map(|i| desktop_frame(width, height, i)).collect();
|
||||
let mut encoder = VpxEncoder::new(EncodeConfig {
|
||||
width: width as u32,
|
||||
height: height as u32,
|
||||
fps,
|
||||
bitrate_kbps: 8_000,
|
||||
codec,
|
||||
})?;
|
||||
|
||||
let rounds = 240;
|
||||
let mut i420 = Vec::new();
|
||||
let mut convert = Duration::ZERO;
|
||||
let mut encode = Duration::ZERO;
|
||||
for n in 0..rounds {
|
||||
let frame = BgraFrame::new(&frames[n % frames.len()], width, height)?;
|
||||
let start = Instant::now();
|
||||
bgra_to_i420(&frame, &mut i420);
|
||||
convert += start.elapsed();
|
||||
let start = Instant::now();
|
||||
// `encode` converts again internally: what it adds over the
|
||||
// conversion measured above is the encoder's own cost.
|
||||
let _ = encoder.encode(&frame);
|
||||
encode += start.elapsed();
|
||||
}
|
||||
let per = |d: Duration| d.as_secs_f64() * 1000.0 / rounds as f64;
|
||||
let convert_ms = per(convert);
|
||||
let total_ms = per(encode);
|
||||
println!(
|
||||
"{width}x{height} {} @{fps}: conversion {convert_ms:.2} ms, encoding {:.2} ms, \
|
||||
total {total_ms:.2} ms per frame (budget {:.2} ms)",
|
||||
codec.as_str(),
|
||||
total_ms - convert_ms,
|
||||
1000.0 / f64::from(fps)
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
+129
-27
@@ -50,7 +50,11 @@ impl<'a> BgraFrame<'a> {
|
||||
/// Converts a BGRA image to I420 (full-size Y, U and V in 4:2:0).
|
||||
///
|
||||
/// `out` is reused from one frame to the next to avoid one allocation per
|
||||
/// image, which matters at 30 frames per second.
|
||||
/// image, which matters at 60 frames per second.
|
||||
///
|
||||
/// One pass over pairs of rows: each 2x2 block gives its four luma values and
|
||||
/// its chroma at once. Very large images are cut into bands of row pairs
|
||||
/// converted in parallel (see [`conversion_bands`]).
|
||||
pub fn bgra_to_i420(frame: &BgraFrame, out: &mut Vec<u8>) {
|
||||
let width = frame.width;
|
||||
let height = frame.height;
|
||||
@@ -61,43 +65,86 @@ pub fn bgra_to_i420(frame: &BgraFrame, out: &mut Vec<u8>) {
|
||||
|
||||
let (y_plane, rest) = out.split_at_mut(y_size);
|
||||
let (u_plane, v_plane) = rest.split_at_mut(chroma_size);
|
||||
let source = &frame.data[..y_size * 4];
|
||||
|
||||
for row in 0..height {
|
||||
let src_row = &frame.data[row * width * 4..(row + 1) * width * 4];
|
||||
for col in 0..width {
|
||||
let px = &src_row[col * 4..col * 4 + 4];
|
||||
let b = px[0] as i32;
|
||||
let g = px[1] as i32;
|
||||
let r = px[2] as i32;
|
||||
y_plane[row * width + col] = rgb_to_y(r, g, b);
|
||||
let pairs = height / 2;
|
||||
let bands = conversion_bands(width * height).min(pairs.max(1));
|
||||
let pairs_per_band = pairs.div_ceil(bands);
|
||||
std::thread::scope(|scope| {
|
||||
let mut source = source;
|
||||
let (mut y_rest, mut u_rest, mut v_rest) = (y_plane, u_plane, v_plane);
|
||||
while !source.is_empty() {
|
||||
let rows = (pairs_per_band * 2).min(source.len() / (width * 4));
|
||||
let (band, next) = source.split_at(rows * width * 4);
|
||||
let (y_band, y_next) = y_rest.split_at_mut(rows * width);
|
||||
let (u_band, u_next) = u_rest.split_at_mut(rows / 2 * width / 2);
|
||||
let (v_band, v_next) = v_rest.split_at_mut(rows / 2 * width / 2);
|
||||
(source, y_rest, u_rest, v_rest) = (next, y_next, u_next, v_next);
|
||||
if source.is_empty() {
|
||||
// The last band runs on this thread: one spawn fewer.
|
||||
convert_band(band, width, y_band, u_band, v_band);
|
||||
} else {
|
||||
scope.spawn(move || convert_band(band, width, y_band, u_band, v_band));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Chroma: average of the four pixels of the 2x2 block, at full resolution.
|
||||
for row in (0..height).step_by(2) {
|
||||
for col in (0..width).step_by(2) {
|
||||
let mut sum_u = 0i32;
|
||||
let mut sum_v = 0i32;
|
||||
for dy in 0..2 {
|
||||
let src_row = &frame.data[(row + dy) * width * 4..(row + dy + 1) * width * 4];
|
||||
for dx in 0..2 {
|
||||
let px = &src_row[(col + dx) * 4..(col + dx) * 4 + 4];
|
||||
let b = px[0] as i32;
|
||||
let g = px[1] as i32;
|
||||
let r = px[2] as i32;
|
||||
/// Bands to cut an image of `pixels` into. One up to 2560x1440: measured at
|
||||
/// 1920x1080 (#86), four bands halve the conversion time but double the CPU
|
||||
/// the host burns, for a step that already fits the 60 fps budget. Beyond,
|
||||
/// one per core, at most four.
|
||||
fn conversion_bands(pixels: usize) -> usize {
|
||||
if pixels <= 2560 * 1440 {
|
||||
return 1;
|
||||
}
|
||||
std::thread::available_parallelism()
|
||||
.map(|n| n.get())
|
||||
.unwrap_or(1)
|
||||
.clamp(1, 4)
|
||||
}
|
||||
|
||||
/// Converts whole row pairs: `source` holds `y.len() / width` BGRA rows.
|
||||
fn convert_band(source: &[u8], width: usize, y: &mut [u8], u: &mut [u8], v: &mut [u8]) {
|
||||
let row_bytes = width * 4;
|
||||
let half = width / 2;
|
||||
for ((pair, y_pair), (u_row, v_row)) in source
|
||||
.chunks_exact(2 * row_bytes)
|
||||
.zip(y.chunks_exact_mut(2 * width))
|
||||
.zip(u.chunks_exact_mut(half).zip(v.chunks_exact_mut(half)))
|
||||
{
|
||||
let (top, bottom) = pair.split_at(row_bytes);
|
||||
let (y_top, y_bottom) = y_pair.split_at_mut(width);
|
||||
for (((top, bottom), (y_top, y_bottom)), (u_out, v_out)) in top
|
||||
.as_chunks::<8>()
|
||||
.0
|
||||
.iter()
|
||||
.zip(bottom.as_chunks::<8>().0)
|
||||
.zip(
|
||||
y_top
|
||||
.as_chunks_mut::<2>()
|
||||
.0
|
||||
.iter_mut()
|
||||
.zip(y_bottom.as_chunks_mut::<2>().0.iter_mut()),
|
||||
)
|
||||
.zip(u_row.iter_mut().zip(v_row.iter_mut()))
|
||||
{
|
||||
let mut sum_u = 0;
|
||||
let mut sum_v = 0;
|
||||
for (pixels, luma) in [(top, y_top), (bottom, y_bottom)] {
|
||||
for (px, out) in pixels.as_chunks::<4>().0.iter().zip(luma.iter_mut()) {
|
||||
let (b, g, r) = (i32::from(px[0]), i32::from(px[1]), i32::from(px[2]));
|
||||
*out = rgb_to_y(r, g, b);
|
||||
sum_u += rgb_to_u(r, g, b);
|
||||
sum_v += rgb_to_v(r, g, b);
|
||||
}
|
||||
}
|
||||
let index = (row / 2) * (width / 2) + (col / 2);
|
||||
u_plane[index] = ((sum_u + 2) / 4).clamp(0, 255) as u8;
|
||||
v_plane[index] = ((sum_v + 2) / 4).clamp(0, 255) as u8;
|
||||
*u_out = ((sum_u + 2) / 4).clamp(0, 255) as u8;
|
||||
*v_out = ((sum_v + 2) / 4).clamp(0, 255) as u8;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Y in BT.709, limited range (16 to 235).
|
||||
#[inline]
|
||||
fn rgb_to_y(r: i32, g: i32, b: i32) -> u8 {
|
||||
(((47 * r + 157 * g + 16 * b + 128) >> 8) + 16).clamp(0, 255) as u8
|
||||
}
|
||||
@@ -132,6 +179,61 @@ pub enum ColorError {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The straightforward conversion this module used before #86, kept as
|
||||
/// the reference the fast one must match byte for byte.
|
||||
fn reference_i420(frame: &BgraFrame) -> Vec<u8> {
|
||||
let (width, height) = (frame.width, frame.height);
|
||||
let mut out = vec![0; width * height * 3 / 2];
|
||||
let (y_plane, rest) = out.split_at_mut(width * height);
|
||||
let (u_plane, v_plane) = rest.split_at_mut(width * height / 4);
|
||||
let pixel = |row: usize, col: usize| {
|
||||
let i = (row * width + col) * 4;
|
||||
let p = &frame.data[i..i + 4];
|
||||
(i32::from(p[2]), i32::from(p[1]), i32::from(p[0]))
|
||||
};
|
||||
for row in 0..height {
|
||||
for col in 0..width {
|
||||
let (r, g, b) = pixel(row, col);
|
||||
y_plane[row * width + col] = rgb_to_y(r, g, b);
|
||||
}
|
||||
}
|
||||
for row in (0..height).step_by(2) {
|
||||
for col in (0..width).step_by(2) {
|
||||
let (mut su, mut sv) = (0, 0);
|
||||
for (dy, dx) in [(0, 0), (0, 1), (1, 0), (1, 1)] {
|
||||
let (r, g, b) = pixel(row + dy, col + dx);
|
||||
su += rgb_to_u(r, g, b);
|
||||
sv += rgb_to_v(r, g, b);
|
||||
}
|
||||
let index = (row / 2) * (width / 2) + col / 2;
|
||||
u_plane[index] = ((su + 2) / 4).clamp(0, 255) as u8;
|
||||
v_plane[index] = ((sv + 2) / 4).clamp(0, 255) as u8;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_fast_conversion_matches_the_reference_byte_for_byte() {
|
||||
// Parallel bands at 1920x1080, a single band at 320x240, and a height
|
||||
// that does not split evenly into bands.
|
||||
for (width, height) in [(1920, 1080), (320, 240), (1282, 722)] {
|
||||
let mut state = 0x2545_f491_u32;
|
||||
let data: Vec<u8> = (0..width * height * 4)
|
||||
.map(|_| {
|
||||
state ^= state << 13;
|
||||
state ^= state >> 17;
|
||||
state ^= state << 5;
|
||||
state as u8
|
||||
})
|
||||
.collect();
|
||||
let frame = BgraFrame::new(&data, width, height).unwrap();
|
||||
let mut fast = Vec::new();
|
||||
bgra_to_i420(&frame, &mut fast);
|
||||
assert!(fast == reference_i420(&frame), "{width}x{height}");
|
||||
}
|
||||
}
|
||||
|
||||
fn solid(width: usize, height: usize, b: u8, g: u8, r: u8) -> Vec<u8> {
|
||||
let mut data = Vec::with_capacity(width * height * 4);
|
||||
for _ in 0..width * height {
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
//! screen or a GPU.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
|
||||
/// Cadence and content of a video source.
|
||||
///
|
||||
@@ -18,6 +19,17 @@ pub trait FrameSource: Send {
|
||||
fn next_frame(&mut self) -> Arc<[u8]>;
|
||||
/// Number of frames already served, for statistics.
|
||||
fn served(&self) -> u64;
|
||||
/// Capture instant of the frame `next_frame` last returned, when known.
|
||||
/// The session derives the RTP timestamp from it, so that an irregular
|
||||
/// cadence (unchanged frames skipped) stays true to real time (#86).
|
||||
fn captured_at(&self) -> Option<Instant> {
|
||||
None
|
||||
}
|
||||
/// Changes when a new frame is ready, for a session to send it at once
|
||||
/// instead of polling at the frame rate (#86). `None`: poll.
|
||||
fn frames_ready(&self) -> Option<tokio::sync::watch::Receiver<u64>> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// A media source shareable between several sessions.
|
||||
|
||||
+230
-12
@@ -21,10 +21,12 @@ use crate::encoder::{EncodeConfig, EncodeError, VideoEncoder};
|
||||
use crate::frame::{FrameSource, SharedMedia};
|
||||
|
||||
/// What the encoding thread publishes, and what the viewers read.
|
||||
#[derive(Default)]
|
||||
struct SharedOutput {
|
||||
frame: Mutex<Arc<[u8]>>,
|
||||
/// Last encoded frame and the instant its image was captured.
|
||||
frame: Mutex<(Arc<[u8]>, Option<Instant>)>,
|
||||
version: AtomicU64,
|
||||
/// Bumped with `version`: sessions wait on it instead of polling (#86).
|
||||
ready: tokio::sync::watch::Sender<u64>,
|
||||
/// Keyframe request for the next encode: a viewer arriving mid-stream
|
||||
/// cannot decode without one.
|
||||
keyframe: AtomicBool,
|
||||
@@ -33,6 +35,14 @@ struct SharedOutput {
|
||||
capture_errors: AtomicU64,
|
||||
encode_errors: AtomicU64,
|
||||
empty_frames: AtomicU64,
|
||||
/// Captured frames skipped because the image had not changed.
|
||||
unchanged: AtomicU64,
|
||||
/// Captured frames dropped to hold the adaptive cadence.
|
||||
paced: AtomicU64,
|
||||
/// Cadence the encoder currently holds, at most the configured one.
|
||||
effective_fps: std::sync::atomic::AtomicU8,
|
||||
/// Configured cadence, for the adaptive one to start from.
|
||||
max_fps: std::sync::atomic::AtomicU8,
|
||||
subscribers: AtomicU64,
|
||||
/// The capture has ended for good, and why.
|
||||
ended: Mutex<Option<CaptureError>>,
|
||||
@@ -42,6 +52,33 @@ struct SharedOutput {
|
||||
resolution_changes: AtomicU64,
|
||||
}
|
||||
|
||||
impl Default for SharedOutput {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
frame: Mutex::new((Arc::from(&[][..]), None)),
|
||||
version: AtomicU64::new(0),
|
||||
ready: tokio::sync::watch::Sender::new(0),
|
||||
keyframe: AtomicBool::default(),
|
||||
captured: AtomicU64::default(),
|
||||
encoded: AtomicU64::default(),
|
||||
capture_errors: AtomicU64::default(),
|
||||
encode_errors: AtomicU64::default(),
|
||||
empty_frames: AtomicU64::default(),
|
||||
unchanged: AtomicU64::default(),
|
||||
paced: AtomicU64::default(),
|
||||
effective_fps: std::sync::atomic::AtomicU8::default(),
|
||||
max_fps: std::sync::atomic::AtomicU8::default(),
|
||||
subscribers: AtomicU64::default(),
|
||||
ended: Mutex::default(),
|
||||
dimensions: AtomicU64::default(),
|
||||
resolution_changes: AtomicU64::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Longest gap between two encoded frames on an unchanged screen.
|
||||
const REFRESH: Duration = Duration::from_secs(1);
|
||||
|
||||
fn pack(width: u32, height: u32) -> u64 {
|
||||
(u64::from(width) << 32) | u64::from(height)
|
||||
}
|
||||
@@ -51,25 +88,31 @@ fn unpack(value: u64) -> (u32, u32) {
|
||||
}
|
||||
|
||||
impl SharedOutput {
|
||||
fn publish(&self, frame: Vec<u8>) {
|
||||
fn max_fps(&self) -> u8 {
|
||||
self.max_fps.load(Ordering::Relaxed).max(1)
|
||||
}
|
||||
|
||||
fn publish(&self, frame: Vec<u8>, captured_at: Instant) {
|
||||
if frame.is_empty() {
|
||||
self.empty_frames.fetch_add(1, Ordering::Relaxed);
|
||||
return;
|
||||
}
|
||||
{
|
||||
let mut slot = self.frame.lock().unwrap_or_else(|e| e.into_inner());
|
||||
*slot = Arc::from(frame.as_slice());
|
||||
*slot = (Arc::from(frame.as_slice()), Some(captured_at));
|
||||
}
|
||||
self.version.fetch_add(1, Ordering::Release);
|
||||
let version = self.version.fetch_add(1, Ordering::Release) + 1;
|
||||
// Wakes the sessions waiting for a frame; nobody waiting is fine.
|
||||
self.ready.send_replace(version);
|
||||
}
|
||||
|
||||
fn read(&self) -> (u64, Arc<[u8]>) {
|
||||
fn read(&self) -> (u64, Arc<[u8]>, Option<Instant>) {
|
||||
let version = self.version.load(Ordering::Acquire);
|
||||
let frame = {
|
||||
let (frame, captured_at) = {
|
||||
let slot = self.frame.lock().unwrap_or_else(|e| e.into_inner());
|
||||
slot.clone()
|
||||
};
|
||||
(version, frame)
|
||||
(version, frame, captured_at)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -85,6 +128,12 @@ pub struct LiveStats {
|
||||
pub encode_errors: u64,
|
||||
/// Frames the encoder returned empty (insignificant image).
|
||||
pub empty_frames: u64,
|
||||
/// Captured frames not encoded because the image had not changed.
|
||||
pub unchanged: u64,
|
||||
/// Captured frames dropped to hold the adaptive cadence.
|
||||
pub paced: u64,
|
||||
/// Cadence the encoder currently holds (adaptive, at most `fps`).
|
||||
pub effective_fps: u8,
|
||||
/// Viewers subscribed to this source.
|
||||
pub subscribers: u64,
|
||||
/// Resolution changes followed since start.
|
||||
@@ -114,6 +163,10 @@ impl LiveSource {
|
||||
output
|
||||
.dimensions
|
||||
.store(pack(config.width, config.height), Ordering::Relaxed);
|
||||
output.max_fps.store(config.fps.max(1), Ordering::Relaxed);
|
||||
output
|
||||
.effective_fps
|
||||
.store(config.fps.max(1), Ordering::Relaxed);
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
|
||||
let worker_output = output.clone();
|
||||
@@ -128,9 +181,12 @@ impl LiveSource {
|
||||
// nothing explaining why.
|
||||
let mut logged = Logged::default();
|
||||
let start = Instant::now();
|
||||
let mut last_encode: Option<Instant> = None;
|
||||
let mut cadence = AdaptiveCadence::new(worker_output.max_fps());
|
||||
while !worker_stop.load(Ordering::Relaxed) {
|
||||
// A keyframe request arrives when a viewer joins.
|
||||
if worker_output.keyframe.swap(false, Ordering::Relaxed) {
|
||||
let keyframe = worker_output.keyframe.swap(false, Ordering::Relaxed);
|
||||
if keyframe {
|
||||
encoder.request_keyframe();
|
||||
}
|
||||
|
||||
@@ -170,6 +226,27 @@ impl LiveSource {
|
||||
};
|
||||
worker_output.captured.fetch_add(1, Ordering::Relaxed);
|
||||
|
||||
// An unchanged image is not encoded again (#86): an idle
|
||||
// screen costs almost nothing, and the viewer's decoder
|
||||
// keeps showing the last frame. Still encoded: a frame a
|
||||
// viewer asked a keyframe for, and one per second, so a
|
||||
// still screen does not look like a dead stream.
|
||||
if !frame.fresh
|
||||
&& !keyframe
|
||||
&& last_encode.is_some_and(|at| at.elapsed() < REFRESH)
|
||||
{
|
||||
worker_output.unchanged.fetch_add(1, Ordering::Relaxed);
|
||||
continue;
|
||||
}
|
||||
// The cadence the encoder actually holds: frames in
|
||||
// between are dropped instead of piling up as latency.
|
||||
if !keyframe && last_encode.is_some_and(|at| !cadence.due(at.elapsed())) {
|
||||
worker_output.paced.fetch_add(1, Ordering::Relaxed);
|
||||
continue;
|
||||
}
|
||||
let work_started = Instant::now();
|
||||
last_encode = Some(work_started);
|
||||
|
||||
// The source changed size (resolution, rotation, window
|
||||
// resized): follow it instead of cropping.
|
||||
let current = encoder.config();
|
||||
@@ -219,7 +296,18 @@ impl LiveSource {
|
||||
}
|
||||
};
|
||||
|
||||
match encoder.encode(&view) {
|
||||
let encoded = encoder.encode(&view);
|
||||
if let Some(fps) = cadence.record(work_started.elapsed()) {
|
||||
tracing::info!(
|
||||
event = "cadence_changed",
|
||||
fps,
|
||||
"the encoding cadence follows what this machine holds"
|
||||
);
|
||||
}
|
||||
worker_output
|
||||
.effective_fps
|
||||
.store(cadence.fps(), Ordering::Relaxed);
|
||||
match encoded {
|
||||
Ok(packets) => {
|
||||
let mut joined = Vec::new();
|
||||
for packet in packets {
|
||||
@@ -236,7 +324,7 @@ impl LiveSource {
|
||||
"first image encoded"
|
||||
);
|
||||
}
|
||||
worker_output.publish(joined);
|
||||
worker_output.publish(joined, frame.captured_at);
|
||||
worker_output.encoded.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
Err(EncodeError::NoFrame) => {
|
||||
@@ -277,6 +365,9 @@ impl LiveSource {
|
||||
capture_errors: self.output.capture_errors.load(Ordering::Relaxed),
|
||||
encode_errors: self.output.encode_errors.load(Ordering::Relaxed),
|
||||
empty_frames: self.output.empty_frames.load(Ordering::Relaxed),
|
||||
unchanged: self.output.unchanged.load(Ordering::Relaxed),
|
||||
paced: self.output.paced.load(Ordering::Relaxed),
|
||||
effective_fps: self.output.effective_fps.load(Ordering::Relaxed),
|
||||
subscribers: self.output.subscribers.load(Ordering::Relaxed),
|
||||
resolution_changes: self.output.resolution_changes.load(Ordering::Relaxed),
|
||||
ended: self.ended().is_some(),
|
||||
@@ -301,6 +392,7 @@ impl SharedMedia for LiveSource {
|
||||
config: self.config,
|
||||
last_version: 0,
|
||||
served: 0,
|
||||
captured_at: None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -331,6 +423,7 @@ pub struct SourceView {
|
||||
config: EncodeConfig,
|
||||
last_version: u64,
|
||||
served: u64,
|
||||
captured_at: Option<Instant>,
|
||||
}
|
||||
|
||||
impl FrameSource for SourceView {
|
||||
@@ -344,17 +437,26 @@ impl FrameSource for SourceView {
|
||||
|
||||
fn next_frame(&mut self) -> Arc<[u8]> {
|
||||
self.served += 1;
|
||||
let (version, frame) = self.output.read();
|
||||
let (version, frame, captured_at) = self.output.read();
|
||||
if version == self.last_version {
|
||||
return Arc::from(&[][..]);
|
||||
}
|
||||
self.last_version = version;
|
||||
self.captured_at = captured_at;
|
||||
frame
|
||||
}
|
||||
|
||||
fn served(&self) -> u64 {
|
||||
self.served
|
||||
}
|
||||
|
||||
fn captured_at(&self) -> Option<Instant> {
|
||||
self.captured_at
|
||||
}
|
||||
|
||||
fn frames_ready(&self) -> Option<tokio::sync::watch::Receiver<u64>> {
|
||||
Some(self.output.ready.subscribe())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for SourceView {
|
||||
@@ -381,9 +483,125 @@ struct Logged {
|
||||
first: bool,
|
||||
}
|
||||
|
||||
/// The cadence the encoder actually holds (#86): "60 fps when possible".
|
||||
///
|
||||
/// The configured cadence is the ceiling. When the work per frame (conversion
|
||||
/// and encoding) takes more than [`LOWER_ABOVE`] of the frame period, the
|
||||
/// cadence halves (60, 30, 15): frames that cannot be encoded in time would
|
||||
/// otherwise pile up as latency and stutter. When it has stayed under
|
||||
/// [`RAISE_BELOW`] of the faster period for [`RAISE_AFTER`] frames, it doubles
|
||||
/// back. The RTP timestamps follow the capture instants, so the browser sees
|
||||
/// a slower stream, not a jerky one.
|
||||
struct AdaptiveCadence {
|
||||
max_fps: u8,
|
||||
fps: u8,
|
||||
/// Smoothed work time per encoded frame.
|
||||
work: Option<Duration>,
|
||||
/// Encoded frames in a row with room to spare for the faster cadence.
|
||||
roomy: u32,
|
||||
}
|
||||
|
||||
/// Lower the cadence when the work takes more than this share of a period.
|
||||
const LOWER_ABOVE: f64 = 0.85;
|
||||
/// Raise it back when the work fits in this share of the faster period...
|
||||
const RAISE_BELOW: f64 = 0.5;
|
||||
/// ...for this many frames in a row (a second at 60 fps).
|
||||
const RAISE_AFTER: u32 = 60;
|
||||
/// The slowest cadence the adaptation goes down to.
|
||||
const MIN_FPS: u8 = 15;
|
||||
|
||||
impl AdaptiveCadence {
|
||||
fn new(max_fps: u8) -> Self {
|
||||
let max_fps = max_fps.max(1);
|
||||
Self {
|
||||
max_fps,
|
||||
fps: max_fps,
|
||||
work: None,
|
||||
roomy: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn fps(&self) -> u8 {
|
||||
self.fps
|
||||
}
|
||||
|
||||
fn period(fps: u8) -> Duration {
|
||||
Duration::from_secs_f64(1.0 / f64::from(fps.max(1)))
|
||||
}
|
||||
|
||||
/// Whether a frame may be encoded `since` the last one. A tenth of a
|
||||
/// period of slack absorbs the capture's own jitter.
|
||||
fn due(&self, since: Duration) -> bool {
|
||||
since >= Self::period(self.fps).mul_f64(0.9)
|
||||
}
|
||||
|
||||
/// Records the work time of an encoded frame; returns the new cadence
|
||||
/// when it changes.
|
||||
fn record(&mut self, work: Duration) -> Option<u8> {
|
||||
let smoothed = match self.work {
|
||||
Some(previous) => previous.mul_f64(0.9) + work.mul_f64(0.1),
|
||||
None => work,
|
||||
};
|
||||
self.work = Some(smoothed);
|
||||
if smoothed > Self::period(self.fps).mul_f64(LOWER_ABOVE) && self.fps / 2 >= MIN_FPS {
|
||||
self.fps /= 2;
|
||||
self.roomy = 0;
|
||||
return Some(self.fps);
|
||||
}
|
||||
let faster = self.fps.saturating_mul(2).min(self.max_fps);
|
||||
if faster > self.fps && smoothed < Self::period(faster).mul_f64(RAISE_BELOW) {
|
||||
self.roomy += 1;
|
||||
if self.roomy >= RAISE_AFTER {
|
||||
self.fps = faster;
|
||||
self.roomy = 0;
|
||||
return Some(self.fps);
|
||||
}
|
||||
} else {
|
||||
self.roomy = 0;
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_cadence_halves_when_the_work_does_not_fit_and_comes_back() {
|
||||
let mut cadence = AdaptiveCadence::new(60);
|
||||
// 15 ms of work per frame: above 85 % of the 16.7 ms period at 60 fps.
|
||||
assert_eq!(cadence.record(Duration::from_millis(15)), Some(30));
|
||||
assert_eq!(cadence.fps(), 30);
|
||||
// Light work again: back to 60 after a second of frames.
|
||||
let mut changed = None;
|
||||
for _ in 0..200 {
|
||||
changed = changed.or(cadence.record(Duration::from_millis(3)));
|
||||
}
|
||||
assert_eq!(changed, Some(60));
|
||||
assert_eq!(cadence.fps(), 60);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cadence_never_drops_below_its_floor_nor_climbs_above_the_ceiling() {
|
||||
let mut cadence = AdaptiveCadence::new(60);
|
||||
for _ in 0..50 {
|
||||
cadence.record(Duration::from_millis(500));
|
||||
}
|
||||
assert_eq!(cadence.fps(), MIN_FPS);
|
||||
let mut thirty = AdaptiveCadence::new(30);
|
||||
for _ in 0..500 {
|
||||
thirty.record(Duration::from_millis(1));
|
||||
}
|
||||
assert_eq!(thirty.fps(), 30);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_frame_is_due_after_most_of_a_period() {
|
||||
let cadence = AdaptiveCadence::new(30);
|
||||
assert!(!cadence.due(Duration::from_millis(20)));
|
||||
assert!(cadence.due(Duration::from_millis(31)));
|
||||
}
|
||||
use crate::encoder::VpxEncoder;
|
||||
use rs_capture::SyntheticCapturer;
|
||||
use rs_proto::SourceId;
|
||||
|
||||
@@ -134,7 +134,7 @@ impl Environment {
|
||||
pub fn advice(&self, portal: Option<&PortalInfo>) -> &'static str {
|
||||
match self.virtual_display_backend(portal) {
|
||||
VirtualDisplayBackend::PortalVirtual => {
|
||||
"virtual display available through the portal: --virtuel extends the desktop \
|
||||
"virtual display available through the portal: --virtual extends the desktop \
|
||||
onto the tablet"
|
||||
}
|
||||
VirtualDisplayBackend::WlrootsHeadless => {
|
||||
|
||||
@@ -149,19 +149,21 @@ pub struct StreamSettings {
|
||||
impl StreamSettings {
|
||||
pub fn for_preset(quality: QualityPreset) -> Self {
|
||||
match quality {
|
||||
// Sized for a local network (#86): 60 fps by default, the host
|
||||
// lowering its cadence by itself when it cannot keep up.
|
||||
QualityPreset::Saver => Self {
|
||||
quality,
|
||||
max_bitrate_kbps: 1_200,
|
||||
max_fps: 20,
|
||||
max_bitrate_kbps: 2_000,
|
||||
max_fps: 30,
|
||||
},
|
||||
QualityPreset::Balanced => Self {
|
||||
quality,
|
||||
max_bitrate_kbps: 3_000,
|
||||
max_fps: 30,
|
||||
max_bitrate_kbps: 6_000,
|
||||
max_fps: 60,
|
||||
},
|
||||
QualityPreset::Sharp => Self {
|
||||
quality,
|
||||
max_bitrate_kbps: 8_000,
|
||||
max_bitrate_kbps: 12_000,
|
||||
max_fps: 60,
|
||||
},
|
||||
}
|
||||
|
||||
+65
-18
@@ -45,6 +45,11 @@ pub async fn run(
|
||||
// it beats an unresolvable mDNS candidate (AGENTS.md).
|
||||
let mut peer: Option<SocketAddr> = None;
|
||||
let mut first_frame = true;
|
||||
// Sources that signal ready frames are sent from at once; the ticker is
|
||||
// the fallback for those that do not (IVF replay) and after a capture
|
||||
// swap, until the new capture's signal is fetched (#86).
|
||||
let mut ready = source.frames_ready();
|
||||
let mut just_connected = false;
|
||||
|
||||
loop {
|
||||
// Full drain. No mutation before reaching the Timeout.
|
||||
@@ -61,6 +66,7 @@ pub async fn run(
|
||||
Poll::Event(event) => {
|
||||
tracing::debug!(?event, "session event");
|
||||
if matches!(event, SessionEvent::Connected) {
|
||||
just_connected = true;
|
||||
tracing::info!(
|
||||
event = "ice_candidate_selected",
|
||||
local = %destination,
|
||||
@@ -78,6 +84,13 @@ pub async fn run(
|
||||
}
|
||||
};
|
||||
|
||||
// A viewer that just connected gets the latest frame right away,
|
||||
// without waiting for the screen to change.
|
||||
if just_connected {
|
||||
just_connected = false;
|
||||
send_frame(&mut session, source.as_mut(), &mut first_frame)?;
|
||||
}
|
||||
|
||||
tokio::select! {
|
||||
biased;
|
||||
|
||||
@@ -120,25 +133,18 @@ pub async fn run(
|
||||
}
|
||||
}
|
||||
|
||||
changed = wait_ready(&mut ready) => {
|
||||
match changed {
|
||||
Ok(()) => send_frame(&mut session, source.as_mut(), &mut first_frame)?,
|
||||
// The capture was replaced: poll until the new one signals.
|
||||
Err(_) => ready = None,
|
||||
}
|
||||
}
|
||||
|
||||
_ = ticker.tick() => {
|
||||
if session.is_connected() {
|
||||
let frame = source.next_frame();
|
||||
if !frame.is_empty() {
|
||||
match session.write_frame(&frame, Instant::now()) {
|
||||
Ok(()) if first_frame => {
|
||||
first_frame = false;
|
||||
tracing::info!(
|
||||
event = "first_frame_sent",
|
||||
delay_ms = session.uptime().as_millis() as u64,
|
||||
bytes = frame.len(),
|
||||
"first frame sent"
|
||||
);
|
||||
}
|
||||
Ok(()) => {}
|
||||
Err(SessionError::NotConnected | SessionError::NoMedia) => {}
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
}
|
||||
if ready.is_none() {
|
||||
send_frame(&mut session, source.as_mut(), &mut first_frame)?;
|
||||
ready = source.frames_ready();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -149,6 +155,47 @@ pub async fn run(
|
||||
}
|
||||
}
|
||||
|
||||
/// Waits for the next ready frame, forever when the source does not signal.
|
||||
async fn wait_ready(
|
||||
ready: &mut Option<tokio::sync::watch::Receiver<u64>>,
|
||||
) -> Result<(), tokio::sync::watch::error::RecvError> {
|
||||
match ready {
|
||||
Some(receiver) => receiver.changed().await,
|
||||
None => std::future::pending().await,
|
||||
}
|
||||
}
|
||||
|
||||
/// Sends the source's latest frame if the session is connected and the frame
|
||||
/// is new. A frame is only consumed once connected: a viewer still
|
||||
/// negotiating finds it waiting.
|
||||
fn send_frame(
|
||||
session: &mut Session,
|
||||
source: &mut dyn FrameSource,
|
||||
first_frame: &mut bool,
|
||||
) -> Result<(), SessionError> {
|
||||
if !session.is_connected() {
|
||||
return Ok(());
|
||||
}
|
||||
let frame = source.next_frame();
|
||||
if frame.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
match session.write_frame(&frame, Instant::now(), source.captured_at()) {
|
||||
Ok(()) if *first_frame => {
|
||||
*first_frame = false;
|
||||
tracing::info!(
|
||||
event = "first_frame_sent",
|
||||
delay_ms = session.uptime().as_millis() as u64,
|
||||
bytes = frame.len(),
|
||||
"first frame sent"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
Ok(()) | Err(SessionError::NotConnected | SessionError::NoMedia) => Ok(()),
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}
|
||||
|
||||
/// LAN address of this machine that a browser can reach.
|
||||
///
|
||||
/// Chrome ignores a `127.0.0.1` candidate: take the address of the interface
|
||||
|
||||
@@ -80,6 +80,8 @@ pub struct Session {
|
||||
connected: bool,
|
||||
frames_sent: u64,
|
||||
started: Instant,
|
||||
/// Last RTP timestamp written: the next one must be strictly greater.
|
||||
last_rtp: Option<u64>,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
@@ -120,6 +122,7 @@ impl Session {
|
||||
connected: false,
|
||||
frames_sent: 0,
|
||||
started,
|
||||
last_rtp: None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -225,7 +228,18 @@ impl Session {
|
||||
///
|
||||
/// Explicitly refused before connection: writing into the void gives a
|
||||
/// session that looks alive and delivers nothing.
|
||||
pub fn write_frame(&mut self, frame: &[u8], now: Instant) -> Result<(), SessionError> {
|
||||
///
|
||||
/// `captured_at` is the capture instant of the image, when the source
|
||||
/// knows it: the RTP timestamp then follows real time, which keeps the
|
||||
/// browser's jitter estimate right when frames arrive irregularly (unchanged
|
||||
/// frames skipped, #86). Without it, the timestamp advances by one frame
|
||||
/// period per frame.
|
||||
pub fn write_frame(
|
||||
&mut self,
|
||||
frame: &[u8],
|
||||
now: Instant,
|
||||
captured_at: Option<Instant>,
|
||||
) -> Result<(), SessionError> {
|
||||
if !self.connected {
|
||||
return Err(SessionError::NotConnected);
|
||||
}
|
||||
@@ -247,7 +261,18 @@ impl Session {
|
||||
pt
|
||||
}
|
||||
};
|
||||
let rtp_time = MediaTime::from_90khz(self.rtp_timestamp(self.frames_sent));
|
||||
let ideal = match captured_at {
|
||||
Some(at) => {
|
||||
at.saturating_duration_since(self.started).as_micros() as u64 * VIDEO_CLOCK
|
||||
/ 1_000_000
|
||||
}
|
||||
None => self.rtp_timestamp(self.frames_sent),
|
||||
};
|
||||
// Strictly increasing: two frames with one timestamp would be one frame
|
||||
// for the decoder.
|
||||
let rtp = self.last_rtp.map_or(ideal, |last| ideal.max(last + 1));
|
||||
self.last_rtp = Some(rtp);
|
||||
let rtp_time = MediaTime::from_90khz(rtp);
|
||||
let writer = self.rtc.writer(mid).ok_or(SessionError::NoMedia)?;
|
||||
writer.write(pt, now, rtp_time, frame.to_vec())?;
|
||||
self.frames_sent += 1;
|
||||
@@ -306,7 +331,9 @@ mod tests {
|
||||
#[test]
|
||||
fn write_before_connect_is_refused() {
|
||||
let mut session = Session::new(candidate(), 30, rs_codec::VideoCodec::Vp8).unwrap();
|
||||
let err = session.write_frame(b"frame", Instant::now()).unwrap_err();
|
||||
let err = session
|
||||
.write_frame(b"frame", Instant::now(), None)
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, SessionError::NotConnected));
|
||||
}
|
||||
|
||||
|
||||
@@ -105,6 +105,17 @@ impl FrameSource for SwitchableView {
|
||||
fn served(&self) -> u64 {
|
||||
self.served
|
||||
}
|
||||
|
||||
fn captured_at(&self) -> Option<std::time::Instant> {
|
||||
self.inner.captured_at()
|
||||
}
|
||||
|
||||
/// The current capture's signal. After a swap the old one closes: the
|
||||
/// session then polls once, which switches to the new capture, and asks
|
||||
/// again.
|
||||
fn frames_ready(&self) -> Option<tokio::sync::watch::Receiver<u64>> {
|
||||
self.inner.frames_ready()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -193,6 +193,48 @@ conditions réelles:
|
||||
La cause du second point: avec VP9 activé, str0m annonçait aussi VP8, H.264 et H.265, et
|
||||
`payload_params().next()` choisissait VP8. Le flux VP9 partait étiqueté VP8.
|
||||
|
||||
## 27 octobre 2026, vers 60 i/s (#86)
|
||||
|
||||
Mesuré par `scripts/bench-latency.sh`: la mire écrit l'instant de sa capture dans l'image (deux
|
||||
lignes de blocs, la seconde inversée pour rejeter une lecture brouillée), le viewer le relit à
|
||||
chaque image affichée (`?perf=1`, `requestVideoFrameCallback`). Hôte et Firefox (sans écran) sur la
|
||||
même machine, i5-1335U, VP8. Latence de bout en bout: capture, conversion, encodage, réseau local,
|
||||
décodage, affichage.
|
||||
|
||||
| Configuration | Avant | Après |
|
||||
| --- | --- | --- |
|
||||
| 1280x720, 30 i/s: latence médiane / p95 | 41 / 43 ms | 21 à 26 / 26 ms |
|
||||
| 1920x1080, 60 i/s: images affichées (min / médiane) | 49 / 53 | 60 / 60 |
|
||||
| 1920x1080, 60 i/s: latence médiane / p95 | 35 ms / 1,6 s | 27 à 38 / 34 à 39 ms |
|
||||
| 1920x1080, 60 i/s: processeur de l'hôte | 93 % d'un cœur | 94 à 114 % |
|
||||
| 2560x1440, 60 i/s: images affichées / latence médiane | non mesuré | 59 à 60 / 41 ms |
|
||||
|
||||
D'un essai à l'autre, la médiane bouge de 10 à 15 ms (phase entre capture et rafraîchissement de
|
||||
l'écran); à l'intérieur d'un essai, l'écart entre médiane et p95 reste sous 2 ms.
|
||||
|
||||
Ce qui a compté:
|
||||
|
||||
- **Envoi déclenché par l'encodeur.** Les sessions interrogeaient l'encodeur à cadence fixe: deux
|
||||
horloges à 60 Hz non synchronisées perdaient une image sur huit et faisaient grossir la mémoire
|
||||
tampon du navigateur (le p95 à 1,6 s). L'encodeur prévient désormais les sessions (`watch`), et
|
||||
l'horodatage RTP vient de l'instant de capture.
|
||||
- **Images inchangées non encodées.** GNOME n'envoie une image qu'au changement: la capture le dit
|
||||
(`fresh`), et le pipeline ne réencode qu'une fois par seconde un écran immobile. Les images
|
||||
partagent leur tampon (`Arc`) au lieu d'être copiées. Gain à mesurer sur un vrai écran.
|
||||
- **Cadence adaptative.** 60 i/s par défaut (profil `balanced`, 6 Mbit/s); si le travail par image
|
||||
dépasse 85 % de la période, la cadence se divise par deux, et remonte quand la marge revient.
|
||||
- **Conversion de couleur** réécrite en une passe sur des paires de lignes, identique au pixel près
|
||||
à l'ancienne (test). Découper l'image en bandes parallèles divisait son temps par deux (4,8 à
|
||||
2,3 ms en 1080p) mais doublait le processeur consommé: gardé seulement au-delà de 2560x1440.
|
||||
|
||||
Essayé sans gain mesurable, donc retiré: partitions de VP8 (`VP8E_SET_TOKEN_PARTITIONS`), retrait
|
||||
des bornes des formules de couleur (elles sont nécessaires: V vaut 256 sur un rouge pur). Réglé
|
||||
mais sans effet visible dans Firefox: mémoire tampon de gigue minimale (`jitterBufferTarget`), qui
|
||||
vise surtout Chrome.
|
||||
|
||||
Coût d'une image 1080p dans le thread d'encodage (`examples/bench_stages.rs`): conversion 4,7 ms,
|
||||
encodage 3 ms, pour un budget de 16,7 ms à 60 i/s.
|
||||
|
||||
## Ce qui reste à mesurer
|
||||
|
||||
- **Latence verre-à-verre.** La VM n'a pas d'écran et la mire n'a pas d'horloge commune avec le
|
||||
|
||||
Executable
+64
@@ -0,0 +1,64 @@
|
||||
#!/usr/bin/env bash
|
||||
# End-to-end latency and frame rate bench (#86).
|
||||
#
|
||||
# Starts rustscreen-cli on the synthetic test pattern (which stamps its capture
|
||||
# instant into every frame), opens the session in a headless Firefox with the
|
||||
# latency probe, and prints what the viewer measured plus the host's CPU use.
|
||||
# Host and viewer run on this machine: one clock, no synchronisation needed.
|
||||
#
|
||||
# Usage: scripts/bench-latency.sh [WIDTHxHEIGHT] [quality: saver|balanced|sharp] [seconds]
|
||||
# Environment:
|
||||
# RUSTSCREEN_CLI binary to bench (default: target/release/rustscreen-cli)
|
||||
# FIREFOX_PROFILE profile directory (snap Firefox: under ~/snap/firefox/common)
|
||||
# BENCH_PORT host port (default 8199), MARIONETTE_PORT (default 2829)
|
||||
set -euo pipefail
|
||||
|
||||
size=${1:-1920x1080}
|
||||
quality=${2:-sharp}
|
||||
seconds=${3:-10}
|
||||
root=$(cd "$(dirname "$0")/.." && pwd)
|
||||
cli=${RUSTSCREEN_CLI:-$root/target/release/rustscreen-cli}
|
||||
port=${BENCH_PORT:-8199}
|
||||
marionette=${MARIONETTE_PORT:-2829}
|
||||
work=$(mktemp -d)
|
||||
profile=${FIREFOX_PROFILE:-$work/profile}
|
||||
mkdir -p "$profile"
|
||||
|
||||
cleanup() {
|
||||
[ -n "${host_pid:-}" ] && kill "$host_pid" 2>/dev/null || true
|
||||
[ -n "${firefox_pid:-}" ] && kill "$firefox_pid" 2>/dev/null || true
|
||||
rm -rf "$work"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
printf '{"version":1,"port":%s,"quality":"%s"}\n' "$port" "$quality" >"$work/settings.json"
|
||||
cat >"$profile/user.js" <<PREFS
|
||||
user_pref("marionette.port", $marionette);
|
||||
user_pref("media.autoplay.default", 0);
|
||||
user_pref("datareporting.policy.dataSubmissionEnabled", false);
|
||||
PREFS
|
||||
|
||||
RUSTSCREEN_CONFIG="$work/settings.json" RUSTSCREEN_LOG_DIR="$work/logs" \
|
||||
RUSTSCREEN_VIEWER="${RUSTSCREEN_VIEWER:-$root/apps/viewer/dist}" \
|
||||
"$cli" --synthetic --size "$size" >"$work/host.log" 2>&1 &
|
||||
host_pid=$!
|
||||
firefox --headless --marionette --no-remote --profile "$profile" --window-size=1920,1200 about:blank \
|
||||
>"$work/firefox.log" 2>&1 &
|
||||
firefox_pid=$!
|
||||
|
||||
url=""
|
||||
for _ in $(seq 100); do
|
||||
url=$(grep -o 'http://[0-9.]*:[0-9]*/r/[^ ]*' "$work/host.log" | head -1 || true)
|
||||
[ -n "$url" ] && ss -ltn | grep -q ":$marionette " && break
|
||||
sleep 0.2
|
||||
done
|
||||
[ -n "$url" ] || { cat "$work/host.log" >&2; echo "the host did not start" >&2; exit 1; }
|
||||
|
||||
ticks() { awk '{print $14 + $15}' "/proc/$host_pid/stat"; }
|
||||
hz=$(getconf CLK_TCK)
|
||||
before=$(ticks)
|
||||
result=$(node "$root/scripts/bench/latency.mjs" "$url" "$marionette" 3 "$seconds")
|
||||
after=$(ticks)
|
||||
# CPU over warmup and measurement, in percent of one core.
|
||||
cpu=$(awk -v a="$before" -v b="$after" -v hz="$hz" -v s="$((seconds + 3))" 'BEGIN { printf "%.0f", (b - a) / hz / s * 100 }')
|
||||
echo "{\"size\":\"$size\",\"quality\":\"$quality\",\"hostCpuPercent\":$cpu,\"viewer\":$result}"
|
||||
Executable
+45
@@ -0,0 +1,45 @@
|
||||
#!/usr/bin/env node
|
||||
// Drives a headless Firefox to a session URL with the latency probe enabled
|
||||
// (`?perf=1`, see apps/viewer/src/lib/perfProbe.ts), waits for the stream to
|
||||
// settle, then prints one JSON line: displayed fps, skipped frames and
|
||||
// end-to-end latency percentiles.
|
||||
//
|
||||
// Usage: latency.mjs <session URL> [marionette port] [warmup s] [measure s]
|
||||
import { connect, sleep } from './marionette.mjs';
|
||||
|
||||
const [url, port = '2828', warmup = '3', measure = '10'] = process.argv.slice(2);
|
||||
if (!url) {
|
||||
console.error('usage: latency.mjs <session URL> [marionette port] [warmup s] [measure s]');
|
||||
process.exit(2);
|
||||
}
|
||||
const probeUrl = `${url}${url.includes('?') ? '&' : '?'}perf=1`;
|
||||
|
||||
const firefox = await connect(Number(port));
|
||||
await firefox.navigate(probeUrl);
|
||||
const started = Date.now();
|
||||
while (Date.now() - started < 15000) {
|
||||
const width = await firefox.run('return document.querySelector("video")?.videoWidth ?? 0');
|
||||
if (width > 0) break;
|
||||
await sleep(100);
|
||||
}
|
||||
const firstFrameMs = Date.now() - started;
|
||||
await sleep(Number(warmup) * 1000);
|
||||
await firefox.run('window.__rustscreenPerf?.reset()');
|
||||
const samples = [];
|
||||
for (let second = 0; second < Number(measure); second++) {
|
||||
await sleep(1000);
|
||||
samples.push(await firefox.run('return window.__rustscreenPerf?.summary() ?? null'));
|
||||
}
|
||||
const last = samples.at(-1);
|
||||
const fps = samples.map((s) => s?.fps ?? 0);
|
||||
console.log(
|
||||
JSON.stringify({
|
||||
firstFrameMs,
|
||||
size: last ? `${last.width}x${last.height}` : null,
|
||||
fpsMin: Math.min(...fps),
|
||||
fpsMedian: fps.sort((a, b) => a - b)[Math.floor(fps.length / 2)],
|
||||
skipped: last?.skipped ?? null,
|
||||
latencyMs: last?.latencyMs ?? null,
|
||||
}),
|
||||
);
|
||||
firefox.close();
|
||||
@@ -0,0 +1,47 @@
|
||||
// Minimal Marionette client (Firefox's remote protocol), without dependencies.
|
||||
// Enough to drive the viewer in a headless Firefox for the latency bench.
|
||||
import net from 'node:net';
|
||||
|
||||
export async function connect(port, host = '127.0.0.1') {
|
||||
const socket = net.connect(port, host);
|
||||
let buffer = Buffer.alloc(0);
|
||||
const pending = new Map();
|
||||
let greeted;
|
||||
const greeting = new Promise((resolve) => {
|
||||
greeted = resolve;
|
||||
});
|
||||
socket.on('data', (chunk) => {
|
||||
buffer = Buffer.concat([buffer, chunk]);
|
||||
for (;;) {
|
||||
const colon = buffer.indexOf(':');
|
||||
if (colon < 0) return;
|
||||
const length = Number(buffer.subarray(0, colon).toString());
|
||||
if (buffer.length < colon + 1 + length) return;
|
||||
const message = JSON.parse(buffer.subarray(colon + 1, colon + 1 + length).toString('utf8'));
|
||||
buffer = buffer.subarray(colon + 1 + length);
|
||||
if (!Array.isArray(message)) greeted(message);
|
||||
else pending.get(message[1])?.(message);
|
||||
}
|
||||
});
|
||||
await greeting;
|
||||
let id = 0;
|
||||
const send = (command, params = {}) =>
|
||||
new Promise((resolve, reject) => {
|
||||
const n = ++id;
|
||||
pending.set(n, ([, , error, result]) => {
|
||||
pending.delete(n);
|
||||
if (error) reject(new Error(JSON.stringify(error)));
|
||||
else resolve(result);
|
||||
});
|
||||
const body = JSON.stringify([0, n, command, params]);
|
||||
socket.write(`${Buffer.byteLength(body)}:${body}`);
|
||||
});
|
||||
await send('WebDriver:NewSession', { capabilities: {} });
|
||||
return {
|
||||
navigate: (url) => send('WebDriver:Navigate', { url }),
|
||||
run: async (script, args = []) => (await send('WebDriver:ExecuteScript', { script, args })).value,
|
||||
close: () => socket.end(),
|
||||
};
|
||||
}
|
||||
|
||||
export const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
Reference in new issue
Block a user