Merge branch 'claude/gifted-lovelace-1crlx2' into worktree-agent-a3369fb4a9337b614
This commit is contained in:
commit
6e59ac93d9
32 files changed
+1966
-354
No files matched your search
+324
-42
@@ -69,6 +69,7 @@ use voelin_stream::{
|
||||
};
|
||||
|
||||
use crate::settings::{AudioSourceKindSetting, AudioSourceSetting};
|
||||
pub use crate::stream::LayerFormat;
|
||||
use crate::stream::StreamSink;
|
||||
use crate::{Command, Engine, SessionId};
|
||||
|
||||
@@ -274,6 +275,22 @@ pub fn test_pattern_source() -> CaptureSource {
|
||||
}
|
||||
}
|
||||
|
||||
/// The most an automatic bitrate ([`auto_bitrate`]) gives, in bit/s. A
|
||||
/// typed bitrate may be higher: nothing in Voelin caps it.
|
||||
pub const AUTO_BITRATE_MAX: u64 = 60_000_000;
|
||||
|
||||
/// The least an automatic bitrate gives, in bit/s.
|
||||
pub const AUTO_BITRATE_MIN: u64 = 300_000;
|
||||
|
||||
/// The automatic bitrate (bit/s) of a `width` x `height` stream at `fps`:
|
||||
/// 0.12 bits per pixel and frame (7.5 Mbit/s at 1080p30, 15 at 1080p60, 27
|
||||
/// at 1440p60), from [`AUTO_BITRATE_MIN`] up to [`AUTO_BITRATE_MAX`], which
|
||||
/// 3840x2160 reaches at 60 fps and 1920x1080 at 240.
|
||||
pub fn auto_bitrate(width: u32, height: u32, fps: u32) -> u64 {
|
||||
let pixels = u128::from(width) * u128::from(height) * u128::from(fps.max(1));
|
||||
(pixels * 12 / 100).clamp(AUTO_BITRATE_MIN.into(), AUTO_BITRATE_MAX.into()) as u64
|
||||
}
|
||||
|
||||
/// Where a [`Streamer`] puts encoded frames.
|
||||
pub trait MediaSink: Send + Sync {
|
||||
/// Send one frame; `false` once nobody takes frames any more.
|
||||
@@ -309,6 +326,16 @@ pub trait MediaSink: Send + Sync {
|
||||
fn video_codecs(&self, out: &mut Vec<VideoFormat>) {
|
||||
let _ = out;
|
||||
}
|
||||
|
||||
/// What layer `layer` is encoded at: size, frame rate and bitrate (an
|
||||
/// automatic one, [`auto_bitrate`] of its size and frame rate, so marked).
|
||||
/// Told when the sink is attached (from the size captured so far), with
|
||||
/// the layer's first frame, and whenever it changes, so the stream's
|
||||
/// connections can probe for the bitrate and offers can declare the
|
||||
/// H.264 level the stream needs.
|
||||
fn layer_format(&self, layer: LayerId, format: LayerFormat) {
|
||||
let _ = (layer, format);
|
||||
}
|
||||
}
|
||||
|
||||
impl MediaSink for StreamSink {
|
||||
@@ -335,6 +362,10 @@ impl MediaSink for StreamSink {
|
||||
fn layer_bitrate(&self, layer: LayerId) -> Option<u64> {
|
||||
StreamSink::layer_bitrate(self, layer)
|
||||
}
|
||||
|
||||
fn layer_format(&self, layer: LayerId, format: LayerFormat) {
|
||||
StreamSink::layer_format(self, layer, format);
|
||||
}
|
||||
}
|
||||
|
||||
/// Which backend captures monitors and windows.
|
||||
@@ -538,7 +569,8 @@ pub struct StreamerConfig {
|
||||
/// gives up to this rate; layers may cap lower.
|
||||
pub fps: u32,
|
||||
/// Video bitrate in kbit/s, as in `StreamSetup::bitrate`, for the single
|
||||
/// layer when `layers` is empty.
|
||||
/// layer when `layers` is empty; 0: automatic, [`auto_bitrate`] of the
|
||||
/// size and frame rate encoded, following both as they change.
|
||||
pub bitrate_kbps: u32,
|
||||
/// The codec of our offer, see [`stream_codec`].
|
||||
pub codec: Codec,
|
||||
@@ -560,6 +592,9 @@ pub struct StreamerConfig {
|
||||
/// ([`SyntheticScreen::with_dmabuf`]): drives the GPU path without a
|
||||
/// portal (Linux, `/dev/udmabuf`).
|
||||
pub synthetic_dmabuf: bool,
|
||||
/// With `synthetic_dmabuf`: buffers in video memory drawn in advance, as
|
||||
/// a compositor's are ([`SyntheticScreen::with_video_memory`]; VA-API).
|
||||
pub synthetic_video_memory: bool,
|
||||
/// Portal restore token from an earlier share: the desktop may skip its
|
||||
/// dialog. The new one is [`Streamer::restore_token`].
|
||||
pub restore_token: Option<String>,
|
||||
@@ -583,6 +618,7 @@ impl Default for StreamerConfig {
|
||||
synthetic_size: (1280, 720),
|
||||
synthetic_pattern: Pattern::Simple,
|
||||
synthetic_dmabuf: false,
|
||||
synthetic_video_memory: false,
|
||||
restore_token: None,
|
||||
layers: Vec::new(),
|
||||
}
|
||||
@@ -591,10 +627,10 @@ impl Default for StreamerConfig {
|
||||
|
||||
impl StreamerConfig {
|
||||
/// The layers that are encoded: [`layers`](Self::layers), or one layer at
|
||||
/// `bitrate_kbps`.
|
||||
/// `bitrate_kbps` (bitrate 0: automatic).
|
||||
pub fn effective_layers(&self) -> Vec<LayerSpec> {
|
||||
if self.layers.is_empty() {
|
||||
vec![LayerSpec::single(u64::from(self.bitrate_kbps.max(1)) * 1000)]
|
||||
vec![LayerSpec::single(u64::from(self.bitrate_kbps) * 1000)]
|
||||
} else {
|
||||
self.layers.clone()
|
||||
}
|
||||
@@ -607,7 +643,8 @@ impl StreamerConfig {
|
||||
pub struct StreamerConfigUpdate {
|
||||
/// Frame-rate cap; the capture follows without restarting.
|
||||
pub fps: Option<u32>,
|
||||
/// Bitrate of the single layer (used while `layers` is empty).
|
||||
/// Bitrate of the single layer (used while `layers` is empty); 0:
|
||||
/// automatic.
|
||||
pub bitrate_kbps: Option<u32>,
|
||||
/// Another codec: new encoders, starting with keyframes.
|
||||
pub codec: Option<Codec>,
|
||||
@@ -673,11 +710,13 @@ pub struct StreamerStats {
|
||||
/// Mean time to convert a captured frame to I420 and scale it for every
|
||||
/// layer that is due, on the CPU.
|
||||
pub convert_time: Duration,
|
||||
/// Captured frames that never reached the CPU: DMA-BUFs converted to
|
||||
/// NV12 and scaled for every layer on the GPU, for VA-API encoders.
|
||||
/// Captured frames converted to NV12 and scaled for every layer on the
|
||||
/// GPU, for VA-API encoders: DMA-BUFs, which the CPU never reads, and
|
||||
/// pictures in memory, which it copies into a surface first.
|
||||
pub gpu_frames: u64,
|
||||
/// Mean time the capture thread spends on such a frame (it waits for
|
||||
/// the GPU, so the buffer can go back to the compositor).
|
||||
/// Mean time the capture thread spends on such a frame (the copy, if
|
||||
/// any, and the wait for the GPU, so the buffer can go back to the
|
||||
/// compositor).
|
||||
pub gpu_convert_time: Duration,
|
||||
/// Why the GPU path stopped (it fell back to the CPU), if it did.
|
||||
pub gpu_error: Option<String>,
|
||||
@@ -712,7 +751,7 @@ struct Layer {
|
||||
/// A keyframe was asked for.
|
||||
keyframe: AtomicBool,
|
||||
stop: AtomicBool,
|
||||
/// Configured bitrate and cap (0: none), bit/s.
|
||||
/// Configured bitrate (0: automatic) and cap (0: none), bit/s.
|
||||
bitrate: AtomicU64,
|
||||
max_bitrate: AtomicU64,
|
||||
/// Frame rate the encoder plans for.
|
||||
@@ -746,7 +785,7 @@ impl Layer {
|
||||
gpu: AtomicU64::new(0),
|
||||
keyframe: AtomicBool::new(false),
|
||||
stop: AtomicBool::new(false),
|
||||
bitrate: AtomicU64::new(spec.bitrate.max(1)),
|
||||
bitrate: AtomicU64::new(spec.bitrate),
|
||||
max_bitrate: AtomicU64::new(spec.max_bitrate.unwrap_or(0)),
|
||||
fps: AtomicU32::new(layer_fps(spec, fps)),
|
||||
next_encoder: Mutex::new(None),
|
||||
@@ -766,7 +805,7 @@ impl Layer {
|
||||
|
||||
fn update(&self, spec: &LayerSpec, fps: u32) {
|
||||
*lock(&self.spec) = spec.clone();
|
||||
self.bitrate.store(spec.bitrate.max(1), Ordering::Relaxed);
|
||||
self.bitrate.store(spec.bitrate, Ordering::Relaxed);
|
||||
self.max_bitrate.store(spec.max_bitrate.unwrap_or(0), Ordering::Relaxed);
|
||||
self.fps.store(layer_fps(spec, fps), Ordering::Relaxed);
|
||||
}
|
||||
@@ -774,6 +813,17 @@ impl Layer {
|
||||
fn stopped(&self) -> bool {
|
||||
self.stop.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// What the layer encodes pictures of `size` at: its bitrate, or the
|
||||
/// automatic one for that size and its frame rate.
|
||||
fn format(&self, (width, height): (u32, u32)) -> LayerFormat {
|
||||
let fps = self.fps.load(Ordering::Relaxed);
|
||||
let (bitrate, automatic) = match self.bitrate.load(Ordering::Relaxed) {
|
||||
0 => (auto_bitrate(width, height, fps), true),
|
||||
bitrate => (bitrate, false),
|
||||
};
|
||||
LayerFormat { width, height, fps, bitrate, automatic }
|
||||
}
|
||||
}
|
||||
|
||||
/// The frame rate a layer encodes at: its cap, within the capture's.
|
||||
@@ -916,6 +966,8 @@ fn cores() -> u32 {
|
||||
fn encoder_config(spec: &LayerSpec, fps: u32, threads: u32) -> EncoderConfig {
|
||||
EncoderConfig {
|
||||
fps: layer_fps(spec, fps),
|
||||
// An automatic bitrate (0) is set with the first frame, whose size it
|
||||
// takes.
|
||||
bitrate_bps: spec.bitrate.clamp(1, u64::from(u32::MAX)) as u32,
|
||||
content: ContentHint::Screen,
|
||||
threads,
|
||||
@@ -1040,7 +1092,8 @@ impl Streamer {
|
||||
SourceId::Synthetic => {
|
||||
let (w, h) = config.synthetic_size;
|
||||
let mut screen = SyntheticScreen::with_pattern(w, h, config.synthetic_pattern)
|
||||
.with_dmabuf(config.synthetic_dmabuf);
|
||||
.with_dmabuf(config.synthetic_dmabuf)
|
||||
.with_video_memory(config.synthetic_video_memory);
|
||||
screen.start_sink(&SourceId::Synthetic, &options, ingest).await?;
|
||||
(Box::new(screen), None)
|
||||
}
|
||||
@@ -1210,6 +1263,15 @@ impl Streamer {
|
||||
|
||||
/// Start encoding into `sink` (replacing an earlier one).
|
||||
pub fn attach(&self, sink: Arc<dyn MediaSink>) {
|
||||
// What the layers are, from the size captured so far: a viewer may
|
||||
// join before the first frame is encoded.
|
||||
let size = self.shared.size.load(Ordering::Relaxed);
|
||||
if size != 0 {
|
||||
for layer in lock(&self.shared.layers).iter() {
|
||||
let picture = lock(&layer.spec).output_size((size >> 32) as u32, size as u32);
|
||||
sink.layer_format(layer.id, layer.format(picture));
|
||||
}
|
||||
}
|
||||
*lock(&self.shared.sink) = Some(sink);
|
||||
}
|
||||
|
||||
@@ -1257,6 +1319,25 @@ impl Streamer {
|
||||
lock(&self.shared.layers).iter().map(|l| l.id).collect()
|
||||
}
|
||||
|
||||
/// The stream's video bitrate in kbit/s, for `StreamSetup::bitrate`: its
|
||||
/// highest layer's; an automatic one ([`auto_bitrate`]) from the size
|
||||
/// captured last and the layer's frame rate, [`AUTO_BITRATE_MAX`] while
|
||||
/// nothing was captured yet.
|
||||
pub fn bitrate_kbps(&self) -> u32 {
|
||||
let size = self.shared.size.load(Ordering::Relaxed);
|
||||
let (width, height) = ((size >> 32) as u32, size as u32);
|
||||
let layers = lock(&self.shared.layers).clone();
|
||||
let bitrate = layers.iter().map(|layer| match layer.bitrate.load(Ordering::Relaxed) {
|
||||
0 if size == 0 => AUTO_BITRATE_MAX,
|
||||
0 => {
|
||||
let (w, h) = lock(&layer.spec).output_size(width, height);
|
||||
auto_bitrate(w, h, layer.fps.load(Ordering::Relaxed))
|
||||
}
|
||||
bitrate => bitrate,
|
||||
});
|
||||
u32::try_from(bitrate.max().unwrap_or(0) / 1000).unwrap_or(u32::MAX)
|
||||
}
|
||||
|
||||
pub fn stats(&self) -> StreamerStats {
|
||||
let shared = &self.shared;
|
||||
let audio = lock(&self.audio);
|
||||
@@ -1590,6 +1671,15 @@ struct Ingest {
|
||||
gpu: GpuStage,
|
||||
}
|
||||
|
||||
/// What the GPU stage converts: a DMA-BUF, or a picture in memory, which
|
||||
/// it copies into a surface first.
|
||||
#[cfg(all(target_os = "linux", feature = "media-desktop"))]
|
||||
#[derive(Clone, Copy)]
|
||||
enum GpuInput<'a, 'b> {
|
||||
Dmabuf(&'a DmaBufRef),
|
||||
Memory(&'a FrameRef<'b>),
|
||||
}
|
||||
|
||||
/// The GPU stage of [`Ingest`].
|
||||
#[cfg(all(target_os = "linux", feature = "media-desktop"))]
|
||||
#[derive(Default)]
|
||||
@@ -1649,33 +1739,36 @@ impl Ingest {
|
||||
false
|
||||
}
|
||||
|
||||
/// The GPU stage's converter, made for the first frame; `None` once
|
||||
/// making it (or a conversion) failed.
|
||||
#[cfg(all(target_os = "linux", feature = "media-desktop"))]
|
||||
fn gpu_converter(&mut self) -> Option<&mut voelin_media::ffmpeg::GpuConverter> {
|
||||
if self.gpu.converter.is_none() {
|
||||
match voelin_media::ffmpeg::GpuConverter::new() {
|
||||
Ok(converter) => self.gpu.converter = Some(Ok(converter)),
|
||||
Err(e) => {
|
||||
warn!("no GPU conversion of captured frames, the CPU converts them: {e}");
|
||||
*lock(&self.shared.gpu_error) = Some(e.to_string());
|
||||
self.gpu.converter = Some(Err(()));
|
||||
}
|
||||
}
|
||||
}
|
||||
self.gpu.converter.as_mut()?.as_mut().ok()
|
||||
}
|
||||
|
||||
/// Convert DMA-BUF `frame` on the GPU for every layer that is due; `None`
|
||||
/// if it is not taken (the backend maps it for [`FrameSink::frame`]).
|
||||
#[cfg(all(target_os = "linux", feature = "media-desktop"))]
|
||||
fn gpu_frame(&mut self, frame: &DmaBufRef) -> Option<bool> {
|
||||
use voelin_media::ffmpeg::{GpuConverter, GpuLayer};
|
||||
|
||||
if self.shared.stopped() {
|
||||
return Some(false);
|
||||
}
|
||||
if !self.gpu_path() {
|
||||
return None;
|
||||
}
|
||||
let shared = self.shared.clone();
|
||||
let converter = match &mut self.gpu.converter {
|
||||
Some(Ok(converter)) => converter,
|
||||
Some(Err(())) => return None,
|
||||
None => match GpuConverter::new() {
|
||||
Ok(converter) => self.gpu.converter.insert(Ok(converter)).as_mut().ok()?,
|
||||
Err(e) => {
|
||||
warn!("no GPU conversion of captured frames, the CPU converts them: {e}");
|
||||
*lock(&shared.gpu_error) = Some(e.to_string());
|
||||
self.gpu.converter = Some(Err(()));
|
||||
return None;
|
||||
}
|
||||
},
|
||||
};
|
||||
self.gpu_converter()?;
|
||||
self.pacer.keep(frame.timestamp);
|
||||
let shared = &self.shared;
|
||||
shared.captured.fetch_add(1, Ordering::Relaxed);
|
||||
shared
|
||||
.size
|
||||
@@ -1683,32 +1776,55 @@ impl Ingest {
|
||||
if shared.sink().is_none() {
|
||||
return Some(true);
|
||||
}
|
||||
self.gpu_convert(GpuInput::Dmabuf(frame));
|
||||
Some(true)
|
||||
}
|
||||
|
||||
/// Convert `input` on the GPU for every layer that is due, into their
|
||||
/// GPU inboxes. A failure turns the GPU stage off: the frame is dropped
|
||||
/// (its layers' pacing taken) and the next one takes the CPU path.
|
||||
#[cfg(all(target_os = "linux", feature = "media-desktop"))]
|
||||
fn gpu_convert(&mut self, input: GpuInput<'_, '_>) {
|
||||
use voelin_media::ffmpeg::GpuLayer;
|
||||
|
||||
let ((width, height), timestamp) = match input {
|
||||
GpuInput::Dmabuf(f) => ((f.width, f.height), f.timestamp),
|
||||
GpuInput::Memory(f) => ((f.width, f.height), f.timestamp),
|
||||
};
|
||||
let mut any = false;
|
||||
self.gpu.layers.clear();
|
||||
for l in &mut self.layers {
|
||||
let due = !l.layer.stopped() && l.pacer.take(frame.timestamp);
|
||||
let due = !l.layer.stopped() && l.pacer.take(timestamp);
|
||||
any |= due;
|
||||
let alignment = l.layer.gpu.load(Ordering::Relaxed);
|
||||
self.gpu.layers.push(GpuLayer {
|
||||
size: l.spec.output_size(frame.width, frame.height),
|
||||
size: l.spec.output_size(width, height),
|
||||
alignment: ((alignment >> 32) as u32, alignment as u32),
|
||||
due,
|
||||
});
|
||||
}
|
||||
if !any {
|
||||
return Some(true);
|
||||
return;
|
||||
}
|
||||
self.gpu.out.clear();
|
||||
self.gpu.out.resize(self.layers.len(), None);
|
||||
let Some(Ok(converter)) = &mut self.gpu.converter else { return };
|
||||
let started = Instant::now();
|
||||
if let Err(e) = converter.convert(frame, &self.gpu.layers, &mut self.gpu.out) {
|
||||
let result = match input {
|
||||
GpuInput::Dmabuf(frame) => {
|
||||
converter.convert(frame, &self.gpu.layers, &mut self.gpu.out)
|
||||
}
|
||||
GpuInput::Memory(frame) => {
|
||||
converter.convert_memory(frame, &self.gpu.layers, &mut self.gpu.out)
|
||||
}
|
||||
};
|
||||
let shared = &self.shared;
|
||||
if let Err(e) = result {
|
||||
warn!("GPU conversion failed, the CPU converts captured frames from now on: {e}");
|
||||
*lock(&shared.gpu_error) = Some(e.to_string());
|
||||
self.gpu.converter = Some(Err(()));
|
||||
self.gpu.out.clear();
|
||||
// This frame is counted and its layers' pacing taken: it is
|
||||
// dropped, and the next one takes the CPU path.
|
||||
return Some(true);
|
||||
return;
|
||||
}
|
||||
shared.gpu_convert_ns.fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed);
|
||||
shared.gpu_converted.fetch_add(1, Ordering::Relaxed);
|
||||
@@ -1717,7 +1833,6 @@ impl Ingest {
|
||||
l.layer.gpu_inbox.put(frame);
|
||||
}
|
||||
}
|
||||
Some(true)
|
||||
}
|
||||
|
||||
/// Pick up layer and frame-rate changes.
|
||||
@@ -1840,6 +1955,15 @@ impl FrameSink for Ingest {
|
||||
if shared.sink().is_none() {
|
||||
return true;
|
||||
}
|
||||
// While every encoder takes GPU frames, a picture in memory is
|
||||
// copied into a surface and converted and scaled there.
|
||||
#[cfg(all(target_os = "linux", feature = "media-desktop"))]
|
||||
if self.gpu_path()
|
||||
&& self.gpu_converter().is_some_and(|converter| converter.takes(&frame.pixels))
|
||||
{
|
||||
self.gpu_convert(GpuInput::Memory(&frame));
|
||||
return true;
|
||||
}
|
||||
let mut any = false;
|
||||
for (i, l) in self.layers.iter_mut().enumerate() {
|
||||
self.sizes[i] = l.spec.output_size(frame.width, frame.height);
|
||||
@@ -1850,6 +1974,7 @@ impl FrameSink for Ingest {
|
||||
return true;
|
||||
}
|
||||
let started = Instant::now();
|
||||
let shared = &self.shared;
|
||||
if let Err(e) = self.pyramid.process(&frame, &self.sizes, &self.due, &mut self.out) {
|
||||
warn!("cannot convert a captured frame: {e}");
|
||||
shared.set_error(e);
|
||||
@@ -2096,6 +2221,8 @@ fn encode_loop(shared: &Shared, layer: &Layer, encoder: Box<dyn VideoEncoder>) {
|
||||
let mut generation = shared.encoders_generation.load(Ordering::Relaxed);
|
||||
// Whether the stream codec was encoded for the last frame.
|
||||
let mut primary_on = true;
|
||||
// What the layer was last told to be, and to which sink.
|
||||
let mut told: Option<(LayerFormat, *const ())> = None;
|
||||
// The last picture, and when it came: a static screen sends no frames,
|
||||
// so keyframe requests are answered by encoding it again.
|
||||
let mut last: Option<(Picture, Instant)> = None;
|
||||
@@ -2199,9 +2326,20 @@ fn encode_loop(shared: &Shared, layer: &Layer, encoder: Box<dyn VideoEncoder>) {
|
||||
None => continue,
|
||||
};
|
||||
// Follow the layer's bitrate, or what the viewers' estimates allow.
|
||||
let configured = layer.bitrate.load(Ordering::Relaxed);
|
||||
let format = layer.format(picture.size());
|
||||
let to = Arc::as_ptr(&sink).cast::<()>();
|
||||
if told != Some((format, to)) {
|
||||
told = Some((format, to));
|
||||
sink.layer_format(layer.id, format);
|
||||
}
|
||||
// Estimates move it down, and back up to the layer's bitrate or its
|
||||
// `max_bitrate` (`LayerSpec::bitrate`), never beyond: an automatic
|
||||
// bitrate stays within `AUTO_BITRATE_MAX`, a typed one is what was
|
||||
// typed. With the pacer no longer held to one packet a millisecond,
|
||||
// a 60 Mbit/s stream's estimate rose to 110 Mbit/s on loopback.
|
||||
let configured = format.bitrate;
|
||||
let cap = match layer.max_bitrate.load(Ordering::Relaxed) {
|
||||
0 => u64::MAX,
|
||||
0 => configured,
|
||||
max => max,
|
||||
};
|
||||
let target = sink.layer_bitrate(layer.id).unwrap_or(configured).clamp(1, cap);
|
||||
@@ -3304,6 +3442,8 @@ mod tests {
|
||||
codecs: Mutex<Vec<VideoFormat>>,
|
||||
frames: Mutex<Vec<(VideoFormat, EncodedFrame)>>,
|
||||
keyframe: AtomicBool,
|
||||
/// What [`MediaSink::layer_format`] told, in order.
|
||||
formats: Mutex<Vec<(LayerId, LayerFormat)>>,
|
||||
}
|
||||
|
||||
impl MediaSink for CodecSink {
|
||||
@@ -3323,6 +3463,93 @@ mod tests {
|
||||
fn video_codecs(&self, out: &mut Vec<VideoFormat>) {
|
||||
out.extend(lock(&self.codecs).iter());
|
||||
}
|
||||
|
||||
fn layer_format(&self, layer: LayerId, format: LayerFormat) {
|
||||
lock(&self.formats).push((layer, format));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn automatic_bitrates() {
|
||||
assert_eq!(auto_bitrate(1920, 1080, 30), 7_464_960);
|
||||
assert_eq!(auto_bitrate(1920, 1080, 60), 14_929_920);
|
||||
assert_eq!(auto_bitrate(2560, 1440, 60), 26_542_080);
|
||||
// The ceiling: 4K60, 1080p240 and anything beyond.
|
||||
assert_eq!(auto_bitrate(3840, 2160, 60), 59_719_680);
|
||||
assert_eq!(auto_bitrate(3840, 2160, 120), AUTO_BITRATE_MAX);
|
||||
assert_eq!(auto_bitrate(7680, 4320, 320), AUTO_BITRATE_MAX);
|
||||
assert_eq!(auto_bitrate(1920, 1080, 320), AUTO_BITRATE_MAX);
|
||||
// The floor, and no overflow at absurd sizes.
|
||||
assert_eq!(auto_bitrate(160, 120, 1), AUTO_BITRATE_MIN);
|
||||
assert_eq!(auto_bitrate(u32::MAX, u32::MAX, u32::MAX), AUTO_BITRATE_MAX);
|
||||
assert_eq!(auto_bitrate(0, 0, 0), AUTO_BITRATE_MIN);
|
||||
}
|
||||
|
||||
/// Bitrate 0 is automatic: the encoder runs at the stream's own
|
||||
/// automatic bitrate, and the sink is told the layer's format (once per
|
||||
/// change, not per frame), which follows a new frame rate.
|
||||
#[cfg(feature = "media-desktop")]
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_automatic_bitrate_follows_the_stream() {
|
||||
let codecs = Codecs::builtin();
|
||||
let config = StreamerConfig {
|
||||
source: SourceId::Synthetic,
|
||||
synthetic_size: (640, 480),
|
||||
fps: 30,
|
||||
bitrate_kbps: 0,
|
||||
audio: false,
|
||||
..StreamerConfig::default()
|
||||
};
|
||||
let streamer = Streamer::start(&codecs, config).await.unwrap();
|
||||
let sink = Arc::new(CodecSink::default());
|
||||
streamer.attach(sink.clone());
|
||||
let told = |fps: u32| {
|
||||
let sink = sink.clone();
|
||||
let format = LayerFormat {
|
||||
width: 640,
|
||||
height: 480,
|
||||
fps,
|
||||
bitrate: auto_bitrate(640, 480, fps),
|
||||
automatic: true,
|
||||
};
|
||||
async move {
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
while lock(&sink.formats).last() != Some(&(0, format)) {
|
||||
assert!(Instant::now() < deadline, "{:?}", lock(&sink.formats));
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
}
|
||||
};
|
||||
told(30).await;
|
||||
assert_eq!(streamer.bitrate_kbps(), 1105);
|
||||
// Not per frame.
|
||||
let count = lock(&sink.formats).len();
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
assert_eq!(lock(&sink.formats).len(), count);
|
||||
assert_eq!(streamer.stats().layers[0].bitrate, auto_bitrate(640, 480, 30));
|
||||
let update = StreamerConfigUpdate { fps: Some(15), ..StreamerConfigUpdate::default() };
|
||||
streamer.reconfigure(&codecs, update).unwrap();
|
||||
told(15).await;
|
||||
// A typed bitrate is not automatic.
|
||||
let update =
|
||||
StreamerConfigUpdate { bitrate_kbps: Some(2000), ..StreamerConfigUpdate::default() };
|
||||
streamer.reconfigure(&codecs, update).unwrap();
|
||||
assert_eq!(streamer.bitrate_kbps(), 2000);
|
||||
let typed = LayerFormat {
|
||||
fps: 15,
|
||||
bitrate: 2_000_000,
|
||||
automatic: false,
|
||||
..lock(&sink.formats)[0].1
|
||||
};
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
while lock(&sink.formats).last() != Some(&(0, typed)) {
|
||||
assert!(Instant::now() < deadline, "{:?}", lock(&sink.formats));
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
// A new sink is told at once, from the size captured.
|
||||
let next = Arc::new(CodecSink::default());
|
||||
streamer.attach(next.clone());
|
||||
assert_eq!(lock(&next.formats).first(), Some(&(0, typed)));
|
||||
}
|
||||
|
||||
impl CodecSink {
|
||||
@@ -3719,6 +3946,53 @@ mod tests {
|
||||
assert_eq!(stats.gpu_error, None, "a planned switch, not a failure");
|
||||
}
|
||||
|
||||
/// Pictures in memory take the GPU path too while every encoder takes
|
||||
/// GPU frames: copied into a surface and converted and scaled there, in
|
||||
/// the right colours (a red-blue swap would turn the orange rectangle
|
||||
/// blue). Skipped without `h264_vaapi` or an H.264 decoder.
|
||||
#[cfg(all(target_os = "linux", feature = "media-desktop"))]
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn memory_frames_take_the_gpu_path_too() {
|
||||
let vaapi = voelin_media::ffmpeg::probe()
|
||||
.iter()
|
||||
.any(|s| s.spec.name == "h264_vaapi" && s.available.is_ok());
|
||||
let codecs = Codecs::new();
|
||||
if !vaapi || codecs.new_decoder(Codec::H264).is_err() {
|
||||
eprintln!("no h264_vaapi or H.264 decoder, skipped");
|
||||
return;
|
||||
}
|
||||
let config = StreamerConfig {
|
||||
source: SourceId::Synthetic,
|
||||
synthetic_size: (640, 360),
|
||||
fps: 30,
|
||||
audio: false,
|
||||
codec: Codec::H264,
|
||||
encoder: EncoderPreference { hardware: true, backend: "h264_vaapi".parse().unwrap() },
|
||||
layers: vec![layer(0, 1.0, None, 1_000_000), layer(5, 0.5, Some(15), 300_000)],
|
||||
..StreamerConfig::default()
|
||||
};
|
||||
let streamer = Streamer::start(&codecs, config).await.unwrap();
|
||||
let mut source = EncodedSource::new(streamer);
|
||||
let count = |frames: &[EncodedFrame], id| frames.iter().filter(|f| f.layer == id).count();
|
||||
let frames = collect(&mut source, |f| count(f, 0) >= 20 && count(f, 5) >= 5).await;
|
||||
let stats = source.streamer().stats();
|
||||
assert_eq!(stats.gpu_error, None);
|
||||
let on_cpu = stats.captured_frames - stats.gpu_frames;
|
||||
assert!(on_cpu <= 1, "{on_cpu} of {} frames on the CPU", stats.captured_frames);
|
||||
assert_eq!(decoded_size(Codec::H264, &frames, 5), ((320, 180), true));
|
||||
let mut decoder = codecs.new_decoder(Codec::H264).unwrap();
|
||||
let mut picture = None;
|
||||
for f in frames.iter().filter(|f| f.layer == 0) {
|
||||
picture = decoder.decode(&f.data).unwrap().or(picture);
|
||||
}
|
||||
let picture = picture.expect("pictures of layer 0");
|
||||
assert_eq!((picture.width, picture.height), (640, 360));
|
||||
let rgba = voelin_media::convert::to_rgba_vec(&picture).unwrap();
|
||||
let middle = &rgba[180 * 640 * 4..181 * 640 * 4];
|
||||
let orange = middle.chunks_exact(4).any(|p| p[0] > 180 && p[2] < 100);
|
||||
assert!(orange, "no orange rectangle in the middle row");
|
||||
}
|
||||
|
||||
/// Two layers at their own sizes and frame rates, keyframes per layer,
|
||||
/// then a new codec and another layer set while streaming.
|
||||
#[cfg(feature = "media-desktop")]
|
||||
@@ -3758,16 +4032,24 @@ mod tests {
|
||||
|
||||
// A viewer's estimate lowers layer 5's encoder bitrate only.
|
||||
source.set_layer_bitrate(5, 150_000);
|
||||
let target = |id| {
|
||||
let target = |source: &EncodedSource, id| {
|
||||
let stats = source.streamer().stats();
|
||||
stats.layers.iter().find(|l| l.id == id).map(|l| l.bitrate)
|
||||
};
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
while target(5) != Some(150_000) {
|
||||
assert!(Instant::now() < deadline, "layer 5 at {:?}", target(5));
|
||||
while target(&source, 5) != Some(150_000) {
|
||||
assert!(Instant::now() < deadline, "layer 5 at {:?}", target(&source, 5));
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
assert_eq!(target(0), Some(800_000));
|
||||
assert_eq!(target(&source, 0), Some(800_000));
|
||||
// A higher one raises it back to its bitrate, not beyond.
|
||||
source.set_layer_bitrate(5, 50_000_000);
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
while target(&source, 5) == Some(150_000) {
|
||||
assert!(Instant::now() < deadline, "layer 5 at {:?}", target(&source, 5));
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
assert_eq!(target(&source, 5), Some(300_000));
|
||||
|
||||
// VP9, layer 5 gone, a new layer 7 at a fixed size.
|
||||
let fixed = LayerSpec { size: Some((96, 64)), ..layer(7, 1.0, None, 200_000) };
|
||||
|
||||
@@ -831,14 +831,15 @@ pub static STREAM_FPS: Key<u32> =
|
||||
Key::new("stream.fps", Kind::UInt { min: 1 }, "Frames per second of our stream.", || 60)
|
||||
.validated(at_least_one);
|
||||
|
||||
/// Video bitrate of our stream in kbit/s (no maximum).
|
||||
/// Video bitrate of our stream in kbit/s (no maximum); 0, the default:
|
||||
/// automatic, from the size and frame rate streamed
|
||||
/// (`media::auto_bitrate`, up to 60 Mbit/s), following both live.
|
||||
pub static STREAM_BITRATE_KBPS: Key<u32> = Key::new(
|
||||
"stream.bitrate_kbps",
|
||||
Kind::UInt { min: 1 },
|
||||
"Video bitrate of our stream in kbit/s.",
|
||||
|| 8000,
|
||||
)
|
||||
.validated(at_least_one);
|
||||
Kind::UInt { min: 0 },
|
||||
"Video bitrate of our stream in kbit/s (0: automatic, up to 60 Mbit/s).",
|
||||
|| 0,
|
||||
);
|
||||
|
||||
/// One simulcast layer as stored; see [`LayerSpec`] for the fields. The
|
||||
/// serde form of a layer: `{"scale": 0.5, "max_fps": 30, "bitrate": 1500000}`
|
||||
@@ -1400,7 +1401,7 @@ mod tests {
|
||||
fn defaults_and_registry() {
|
||||
let s = Settings::in_memory();
|
||||
assert_eq!(s.get(&STREAM_FPS), 60);
|
||||
assert_eq!(s.get(&STREAM_BITRATE_KBPS), 8000);
|
||||
assert_eq!(s.get(&STREAM_BITRATE_KBPS), 0, "automatic");
|
||||
assert!(s.get(&STREAM_LAYERS).is_empty());
|
||||
assert_eq!(s.get(&STREAM_CODEC), CodecChoice::Auto);
|
||||
assert_eq!(s.get(&STREAM_PERMISSIONS), StreamPermissions::Channel);
|
||||
@@ -1476,6 +1477,8 @@ mod tests {
|
||||
s.set_json("stream.fps", json!(1000)).unwrap();
|
||||
s.set(&STREAM_BITRATE_KBPS, u32::MAX).unwrap();
|
||||
assert_eq!(s.get(&STREAM_BITRATE_KBPS), u32::MAX);
|
||||
// 0 is automatic again.
|
||||
s.set(&STREAM_BITRATE_KBPS, 0).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -76,6 +76,19 @@ pub struct StreamFrame {
|
||||
pub frame: MediaFrame,
|
||||
}
|
||||
|
||||
/// What a simulcast layer of our stream is encoded at
|
||||
/// ([`StreamSink::layer_format`]).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct LayerFormat {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub fps: u32,
|
||||
/// Bit/s: the layer's bitrate, or its automatic one.
|
||||
pub bitrate: u64,
|
||||
/// The bitrate is automatic (from the size and frame rate).
|
||||
pub automatic: bool,
|
||||
}
|
||||
|
||||
/// Hands encoded frames of our stream to the engine, e.g. from an encoder
|
||||
/// thread, and tells the encoders what the viewers need per simulcast layer:
|
||||
/// keyframes and bitrates. Those are read lock-free from the stream session.
|
||||
@@ -124,6 +137,15 @@ impl StreamSink {
|
||||
self.feedback.bitrate(layer)
|
||||
}
|
||||
|
||||
/// What the encoder of `layer` makes. An automatic bitrate goes into the
|
||||
/// stream's layer, so new connections start at it and every connection
|
||||
/// probes for it; the largest layer sets the H.264 level of new offers
|
||||
/// (`PeerConfig::set_h264_format`), so the offer declares what the
|
||||
/// encoder writes into its SPS, also for 4K, 8K and high frame rates.
|
||||
pub fn layer_format(&self, layer: LayerId, format: LayerFormat) {
|
||||
let _ = self.tx.send(StreamInput::LayerFormat { layer, format });
|
||||
}
|
||||
|
||||
pub fn is_live(&self) -> bool {
|
||||
self.live.load(Ordering::Relaxed)
|
||||
}
|
||||
@@ -173,6 +195,11 @@ pub(crate) enum StreamInput {
|
||||
},
|
||||
/// Simulcast layers of our stream (now and for streams started later).
|
||||
Layers(Vec<LayerSpec>),
|
||||
/// What a layer of our stream is encoded at ([`StreamSink::layer_format`]).
|
||||
LayerFormat {
|
||||
layer: LayerId,
|
||||
format: LayerFormat,
|
||||
},
|
||||
/// SRTP profile order of new connections.
|
||||
SrtpProfiles(Vec<SrtpProfile>),
|
||||
Frame(EncodedFrame),
|
||||
@@ -284,6 +311,7 @@ impl StreamHandle {
|
||||
settings,
|
||||
own,
|
||||
setup: None,
|
||||
formats: BTreeMap::new(),
|
||||
live: None,
|
||||
viewers: 0,
|
||||
clients: BTreeMap::new(),
|
||||
@@ -299,6 +327,25 @@ impl StreamHandle {
|
||||
}
|
||||
}
|
||||
|
||||
/// What an offer's H.264 level must hold: the largest size, frame rate and
|
||||
/// bitrate of the stream's layers that are encoded (`formats`), a layer's
|
||||
/// bitrate taken at its `max_bitrate` when that is higher, since bandwidth
|
||||
/// estimates may raise the encoder to it. `None` before any is.
|
||||
fn offer_format(
|
||||
formats: &BTreeMap<LayerId, LayerFormat>,
|
||||
layers: &[LayerSpec],
|
||||
) -> Option<(u32, u32, u32, u64)> {
|
||||
formats.iter().filter(|(id, _)| layers.iter().any(|l| l.id == **id)).fold(
|
||||
None,
|
||||
|most, (id, f)| {
|
||||
let max = layers.iter().find(|l| l.id == *id).and_then(|l| l.max_bitrate);
|
||||
let bitrate = f.bitrate.max(max.unwrap_or(0));
|
||||
let (w, h, fps, b) = most.unwrap_or((0, 0, 0, 0));
|
||||
Some((w.max(f.width), h.max(f.height), fps.max(f.fps), b.max(bitrate)))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
struct StreamTask {
|
||||
session: SessionId,
|
||||
streams: Streams,
|
||||
@@ -319,6 +366,8 @@ struct StreamTask {
|
||||
own: mpsc::UnboundedSender<OwnStreamEvent>,
|
||||
/// The setup of our stream since `Start`.
|
||||
setup: Option<StreamSetup>,
|
||||
/// What each layer of our stream is encoded at, since `Start`.
|
||||
formats: BTreeMap<LayerId, LayerFormat>,
|
||||
/// Our live stream's id.
|
||||
live: Option<String>,
|
||||
/// Connected viewers of our stream, as last told.
|
||||
@@ -356,11 +405,42 @@ impl StreamTask {
|
||||
let _ = self.events.send(event);
|
||||
}
|
||||
|
||||
/// A layer of our stream is encoded at `format` (see
|
||||
/// [`StreamSink::layer_format`]).
|
||||
fn layer_format(
|
||||
&mut self,
|
||||
layer: LayerId,
|
||||
format: LayerFormat,
|
||||
) -> Result<(), voelin_stream::SessionError> {
|
||||
// The live stream's layers only; the configured ones (for streams
|
||||
// started later) keep their automatic bitrate.
|
||||
let Some(mut layers) = self.streams.streamer().map(|s| s.layers().to_vec()) else {
|
||||
return Ok(());
|
||||
};
|
||||
self.formats.insert(layer, format);
|
||||
if let Some((width, height, fps, bitrate)) = offer_format(&self.formats, &layers) {
|
||||
let mut config = self.streams.peer_config().clone();
|
||||
config.set_h264_format(width, height, fps, bitrate);
|
||||
if config.h264_profile_level_ids != self.streams.peer_config().h264_profile_level_ids {
|
||||
debug!(width, height, fps, bitrate, "H.264 offered for the stream's largest layer");
|
||||
self.streams.set_peer_config(config);
|
||||
}
|
||||
}
|
||||
match layers.iter_mut().find(|l| l.id == layer) {
|
||||
Some(spec) if format.automatic && spec.bitrate != format.bitrate => {
|
||||
spec.bitrate = format.bitrate;
|
||||
self.streams.set_layers(layers)
|
||||
}
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn input(&mut self, input: StreamInput) {
|
||||
let session = self.session;
|
||||
let result = match input {
|
||||
StreamInput::Start { setup, auto_accept } => {
|
||||
self.setup = Some(setup.clone());
|
||||
self.formats.clear();
|
||||
let layers = self.layers.clone();
|
||||
let options = StreamerOptions { setup, auto_accept, layers, ..Default::default() };
|
||||
self.streams.start(options).map(|()| {
|
||||
@@ -394,6 +474,7 @@ impl StreamTask {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
StreamInput::LayerFormat { layer, format } => self.layer_format(layer, format),
|
||||
StreamInput::SrtpProfiles(profiles) => {
|
||||
self.streams.set_srtp_profiles(profiles);
|
||||
Ok(())
|
||||
@@ -637,8 +718,17 @@ mod tests {
|
||||
const CLIENTS: [u16; 2] = [5, 6];
|
||||
|
||||
/// The notifications the server sends for `request` from `from`, per receiver.
|
||||
/// Every offer the fake server relayed, from all tests of this process.
|
||||
fn lock_offers() -> std::sync::MutexGuard<'static, Vec<String>> {
|
||||
static OFFERS: Mutex<Vec<String>> = Mutex::new(Vec::new());
|
||||
OFFERS.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
fn relay(from: u16, request: Request) -> Vec<(u16, StreamNotification)> {
|
||||
let both = |n: StreamNotification| CLIENTS.map(|c| (c, n.clone())).to_vec();
|
||||
if let Request::Respond { offer: Some(sdp), .. } = &request {
|
||||
lock_offers().push(sdp.clone());
|
||||
}
|
||||
match request {
|
||||
Request::Setup(setup) => CLIENTS
|
||||
.map(|c| {
|
||||
@@ -728,11 +818,11 @@ mod tests {
|
||||
audio: Option<AudioHandle>,
|
||||
settings: &Settings,
|
||||
) -> (Handles, broadcast::Receiver<Event>, broadcast::Receiver<StreamFrame>) {
|
||||
let (handles, rx, frames, _) = pair_full(audio, settings, false);
|
||||
let (handles, rx, frames, _) = pair_full(audio, settings, false, PeerConfig::loopback());
|
||||
(handles, rx, frames)
|
||||
}
|
||||
|
||||
/// [`pair_with`]; with `late`, the server does not tell the viewer
|
||||
/// [`pair_with`] with peers of `config`; with `late`, the server does not tell the viewer
|
||||
/// (session 2) about streams, as for a client that joined after the
|
||||
/// stream started, and does not answer lookups. Also returns what the
|
||||
/// streamer (session 1) reports about its own stream.
|
||||
@@ -740,6 +830,7 @@ mod tests {
|
||||
audio: Option<AudioHandle>,
|
||||
settings: &Settings,
|
||||
late: bool,
|
||||
config: PeerConfig,
|
||||
) -> (
|
||||
Handles,
|
||||
broadcast::Receiver<Event>,
|
||||
@@ -754,7 +845,7 @@ mod tests {
|
||||
let mut audio = audio;
|
||||
for (i, clid) in CLIENTS.into_iter().enumerate() {
|
||||
let (voice, voice_rx) = mpsc::unbounded_channel();
|
||||
let config = PeerConfig::loopback();
|
||||
let config = config.clone();
|
||||
let session = i as u64 + 1;
|
||||
handles.push(StreamHandle::spawn(
|
||||
session,
|
||||
@@ -967,12 +1058,101 @@ mod tests {
|
||||
feeder.await.unwrap();
|
||||
}
|
||||
|
||||
/// What the encoder tells about a layer reaches the live stream: the
|
||||
/// largest layer's size, frame rate and bitrate set the H.264 level of
|
||||
/// the next offer (both profiles), and an automatic bitrate goes into the
|
||||
/// layer (which asks the viewer's layer for a keyframe, as every layer
|
||||
/// change does); the same again changes nothing.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn layer_formats_reach_the_live_stream() {
|
||||
// The streamer offers H.264 (and the viewer takes it).
|
||||
let config = PeerConfig { video_codecs: vec![VideoCodec::H264], ..PeerConfig::loopback() };
|
||||
let (handles, mut rx, _frames, _) = pair_full(None, &Settings::in_memory(), false, config);
|
||||
let setup = StreamSetup { name: "4K120".into(), ..Default::default() };
|
||||
handles[0].send(StreamInput::Start { setup, auto_accept: true });
|
||||
// Live for the streamer and listed for the viewer, in either order.
|
||||
let (mut sink, mut listed) = (None, false);
|
||||
wait(&mut rx, |e| {
|
||||
match e {
|
||||
Event::StreamState { session: 1, state: StreamState::Live { sink: s, .. } } => {
|
||||
sink = Some(s);
|
||||
}
|
||||
Event::StreamsChanged { session: 2, streams } => listed = streams.len() == 1,
|
||||
_ => {}
|
||||
}
|
||||
(sink.is_some() && listed).then_some(())
|
||||
})
|
||||
.await;
|
||||
let sink = sink.unwrap();
|
||||
let format =
|
||||
|bitrate| LayerFormat { width: 3840, height: 2160, fps: 60, bitrate, automatic: true };
|
||||
// Before the viewer asks: its offer is made after this.
|
||||
sink.layer_format(0, format(60_000_000));
|
||||
handles[1].send(StreamInput::Watch { stream_id: "s-1".into() });
|
||||
wait(&mut rx, |e| match e {
|
||||
Event::WatchState { session: 2, state: WatchState::Connected, .. } => Some(()),
|
||||
_ => None,
|
||||
})
|
||||
.await;
|
||||
// 3840x2160 at 60 fps is level 5.2 (0x34) in both profiles.
|
||||
let offers = lock_offers().clone();
|
||||
assert!(
|
||||
offers.iter().any(|o| o.contains("profile-level-id=640c34") && o.contains("42e034")),
|
||||
"{offers:?}"
|
||||
);
|
||||
|
||||
let keyframes = || {
|
||||
let mut layers = LayerSet::new();
|
||||
sink.take_layer_keyframes(&mut layers);
|
||||
layers.contains(0)
|
||||
};
|
||||
keyframes();
|
||||
sink.layer_format(0, format(9_000_000));
|
||||
timeout(Duration::from_secs(5), async {
|
||||
while !keyframes() {
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("the layer did not change");
|
||||
sink.layer_format(0, format(9_000_000));
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
assert!(!keyframes(), "nothing changed");
|
||||
handles[0].send(StreamInput::Stop);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_offer_covers_the_largest_layer() {
|
||||
let format = |width, height, fps, bitrate| LayerFormat {
|
||||
width,
|
||||
height,
|
||||
fps,
|
||||
bitrate,
|
||||
automatic: false,
|
||||
};
|
||||
let layers = [
|
||||
LayerSpec { max_bitrate: Some(12_000_000), ..LayerSpec::single(8_000_000) },
|
||||
LayerSpec { id: 1, scale: 0.5, ..LayerSpec::single(2_000_000) },
|
||||
];
|
||||
let mut formats = BTreeMap::new();
|
||||
assert_eq!(offer_format(&formats, &layers), None);
|
||||
formats.insert(1, format(960, 540, 120, 2_000_000));
|
||||
formats.insert(0, format(1920, 1080, 60, 8_000_000));
|
||||
// Layer 0's size and its bitrate at its maximum, layer 1's rate.
|
||||
assert_eq!(offer_format(&formats, &layers), Some((1920, 1080, 120, 12_000_000)));
|
||||
// A layer the stream no longer has does not count.
|
||||
formats.insert(7, format(7680, 4320, 30, 60_000_000));
|
||||
assert_eq!(offer_format(&formats, &layers), Some((1920, 1080, 120, 12_000_000)));
|
||||
}
|
||||
|
||||
/// A viewer that was not told about a running stream, and whose server
|
||||
/// lookup goes unanswered, finds it in the gateway directory and
|
||||
/// watches it; the streamer reports its stream's life for the directory.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn late_viewer_finds_the_stream_in_the_gateway_directory() {
|
||||
let (handles, mut rx, _frames, mut own) = pair_full(None, &Settings::in_memory(), true);
|
||||
let loopback = PeerConfig::loopback();
|
||||
let (handles, mut rx, _frames, mut own) =
|
||||
pair_full(None, &Settings::in_memory(), true, loopback);
|
||||
let setup = StreamSetup {
|
||||
name: "directory test".into(),
|
||||
kind: StreamKind::Window,
|
||||
|
||||
@@ -388,17 +388,26 @@ fn size_range() -> Property {
|
||||
)
|
||||
}
|
||||
|
||||
/// Up to `fps`, as the compositor can (it sends frames on damage only).
|
||||
fn framerate_range(fps: u32) -> Property {
|
||||
property!(
|
||||
FormatProperties::VideoFramerate,
|
||||
Choice,
|
||||
Range,
|
||||
Fraction,
|
||||
Fraction { num: fps, denom: 1 },
|
||||
Fraction { num: 0, denom: 1 },
|
||||
Fraction { num: fps, denom: 1 }
|
||||
)
|
||||
/// Up to `fps`, as the compositor can (it sends frames on damage only):
|
||||
/// the frame rate (compositors offer 0, variable) and the most frames it
|
||||
/// may send, preferably `fps`. Compositors offer their screen's refresh rate
|
||||
/// as the maximum (Mutter, KWin, xdg-desktop-portal-hyprland, whose
|
||||
/// `screencopy:max_fps` defaults to 120), so the intersection is the
|
||||
/// lower of the two: the compositor neither sends frames the sink would
|
||||
/// drop nor fewer than its screen shows.
|
||||
fn framerate_range(fps: u32) -> [Property; 2] {
|
||||
let up_to = |key: FormatProperties, min: u32| {
|
||||
property!(
|
||||
key,
|
||||
Choice,
|
||||
Range,
|
||||
Fraction,
|
||||
Fraction { num: fps, denom: 1 },
|
||||
Fraction { num: min, denom: 1 },
|
||||
Fraction { num: fps, denom: 1 }
|
||||
)
|
||||
};
|
||||
[up_to(FormatProperties::VideoFramerate, 0), up_to(FormatProperties::VideoMaxFramerate, 1)]
|
||||
}
|
||||
|
||||
/// The modifiers we take, best first: the sink's tiled ones, then LINEAR,
|
||||
@@ -471,7 +480,7 @@ fn enum_formats(
|
||||
properties.push(property!(FormatProperties::VideoFormat, Id, format));
|
||||
properties.push(modifier_property(&modifiers, false));
|
||||
properties.push(size_range());
|
||||
properties.push(framerate_range(fps));
|
||||
properties.extend(framerate_range(fps));
|
||||
formats.push(serialize(format_object(properties))?);
|
||||
}
|
||||
}
|
||||
@@ -488,7 +497,7 @@ fn enum_formats(
|
||||
FORMATS[3]
|
||||
));
|
||||
properties.push(size_range());
|
||||
properties.push(framerate_range(fps));
|
||||
properties.extend(framerate_range(fps));
|
||||
formats.push(serialize(format_object(properties))?);
|
||||
Ok(formats)
|
||||
}
|
||||
@@ -543,7 +552,7 @@ fn format_changed(
|
||||
Rectangle { width: size.width, height: size.height }
|
||||
),
|
||||
];
|
||||
properties.push(framerate_range(state.fps));
|
||||
properties.extend(framerate_range(state.fps));
|
||||
let fixed = serialize(format_object(properties))?;
|
||||
stream.update_params(&mut [pod(&fixed)?]).map_err(|e| e.to_string())?;
|
||||
return Ok(());
|
||||
@@ -808,6 +817,27 @@ mod tests {
|
||||
assert!(modifier.is_none(), "shared memory has no modifier");
|
||||
}
|
||||
}
|
||||
// The frame rate and the most frames a second: 320 preferred, as
|
||||
// much as the compositor can.
|
||||
for bytes in enum_formats(320, true, &[]).unwrap() {
|
||||
let object = pod(&bytes).unwrap().as_object().unwrap();
|
||||
for (key, min) in
|
||||
[(FormatProperties::VideoFramerate, 0), (FormatProperties::VideoMaxFramerate, 1)]
|
||||
{
|
||||
use pw::spa::pod::deserialize::PodDeserializer;
|
||||
let prop = object.find_prop(Id(key.as_raw())).expect("a frame rate");
|
||||
let value =
|
||||
PodDeserializer::deserialize_any_from(prop.value().as_bytes()).unwrap().1;
|
||||
let Value::Choice(ChoiceValue::Fraction(Choice(
|
||||
_,
|
||||
ChoiceEnum::Range { default, min: low, max },
|
||||
))) = value
|
||||
else {
|
||||
panic!("{value:?}");
|
||||
};
|
||||
assert_eq!((default.num, low.num, max.num), (320, min, 320));
|
||||
}
|
||||
}
|
||||
let linear_only = enum_formats(60, true, &[]).unwrap();
|
||||
let object = pod(&linear_only[0]).unwrap().as_object().unwrap();
|
||||
let prop = object.find_prop(Id(FormatProperties::VideoModifier.as_raw())).unwrap();
|
||||
|
||||
@@ -11,6 +11,7 @@ use crate::capture::{
|
||||
};
|
||||
use crate::frame::{AUDIO_SAMPLE_RATE, AudioBuffer, FrameRef, PixelsRef, PlaneRef, VideoFrame};
|
||||
use crate::queue::{FrameReceiver, frame_channel};
|
||||
use crate::workers::{Slots, Workers};
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// Background colour of the pattern (RGB).
|
||||
@@ -205,13 +206,16 @@ impl Desktop {
|
||||
Self { page, editor, document, document_rows }
|
||||
}
|
||||
|
||||
/// The page with the document scrolled by `offset` rows.
|
||||
fn draw(&self, out: &mut [u8], width: usize, offset: usize) {
|
||||
out[..self.page.len()].copy_from_slice(&self.page);
|
||||
/// Rows `first..` of the page with the document scrolled by `offset`
|
||||
/// rows, into `out` (whole rows).
|
||||
fn draw(&self, out: &mut [u8], width: usize, first: usize, offset: usize) {
|
||||
let start = first * width * 4;
|
||||
out.copy_from_slice(&self.page[start..start + out.len()]);
|
||||
let (ex, ey, ew, eh) = self.editor;
|
||||
for row in 0..eh {
|
||||
let src = (offset + row) % self.document_rows * ew * 4;
|
||||
let dst = ((ey + row) * width + ex) * 4;
|
||||
let rows = first..first + out.len() / (width * 4);
|
||||
for y in rows.start.max(ey)..rows.end.min(ey + eh) {
|
||||
let src = (offset + y - ey) % self.document_rows * ew * 4;
|
||||
let dst = ((y - first) * width + ex) * 4;
|
||||
out[dst..dst + ew * 4].copy_from_slice(&self.document[src..src + ew * 4]);
|
||||
}
|
||||
}
|
||||
@@ -225,6 +229,7 @@ pub struct SyntheticScreen {
|
||||
desktop: Option<Arc<Desktop>>,
|
||||
worker: Option<Worker>,
|
||||
dmabuf: bool,
|
||||
video_memory: bool,
|
||||
}
|
||||
|
||||
impl SyntheticScreen {
|
||||
@@ -237,7 +242,7 @@ impl SyntheticScreen {
|
||||
let (width, height) = (width.max(16), height.max(16));
|
||||
let desktop = (pattern == Pattern::Desktop)
|
||||
.then(|| Arc::new(Desktop::render(width as usize, height as usize)));
|
||||
Self { width, height, pattern, desktop, worker: None, dmabuf: false }
|
||||
Self { width, height, pattern, desktop, worker: None, dmabuf: false, video_memory: false }
|
||||
}
|
||||
|
||||
/// Draw into a DMA-BUF of ordinary memory and offer it to sinks that
|
||||
@@ -251,6 +256,20 @@ impl SyntheticScreen {
|
||||
self
|
||||
}
|
||||
|
||||
/// With [`with_dmabuf`](Self::with_dmabuf): the DMA-BUFs are buffers in
|
||||
/// video memory in the GPU driver's own (tiled) layout, as a
|
||||
/// compositor's are, drawn once in advance ([`VIDEO_MEMORY_FRAMES`]
|
||||
/// frames of the pattern, handed over in turn) so the source costs
|
||||
/// nothing per frame. The GPU reads ordinary memory over the bus, several
|
||||
/// times slower (measured on a Radeon RX 7900 GRE: 9.7 ms against 0.16
|
||||
/// for a 3840x2160 conversion), and `/dev/udmabuf` refuses buffers of
|
||||
/// more than 64 MiB by default (7680x4320 is 132). Linux with the `ffmpeg`
|
||||
/// feature and VA-API; elsewhere, ordinary memory as before.
|
||||
pub fn with_video_memory(mut self, enabled: bool) -> Self {
|
||||
self.video_memory = enabled;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn pattern(&self) -> Pattern {
|
||||
self.pattern
|
||||
}
|
||||
@@ -264,6 +283,7 @@ impl SyntheticScreen {
|
||||
desktop: self.desktop.clone(),
|
||||
worker: None,
|
||||
dmabuf: self.dmabuf,
|
||||
video_memory: self.video_memory,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -282,28 +302,30 @@ impl SyntheticScreen {
|
||||
/// its memory.
|
||||
pub fn render(&self, n: u64, out: &mut Vec<u8>) {
|
||||
out.resize(self.width as usize * self.height as usize * 4, 0);
|
||||
self.draw(n, out);
|
||||
self.draw(n, out, &mut Workers::new("voelin-synthetic", 1));
|
||||
}
|
||||
|
||||
/// [`render`](Self::render) into the first `width * height * 4` bytes of
|
||||
/// `out`.
|
||||
fn draw(&self, n: u64, out: &mut [u8]) {
|
||||
/// `out`, the background in bands of rows on `workers` (a 7680x4320
|
||||
/// frame is 130 MB to write).
|
||||
fn draw(&self, n: u64, out: &mut [u8], workers: &mut Workers) {
|
||||
let (w, h) = (self.width as usize, self.height as usize);
|
||||
let out = &mut out[..w * h * 4];
|
||||
match &self.desktop {
|
||||
Some(desktop) => desktop.draw(out, w, n as usize * 3),
|
||||
None => {
|
||||
// One row, then copies of it.
|
||||
let px = bgra(BACKGROUND);
|
||||
for d in out[..w * 4].chunks_exact_mut(4) {
|
||||
d.copy_from_slice(&px);
|
||||
}
|
||||
let (first, rest) = out.split_at_mut(w * 4);
|
||||
for row in rest.chunks_exact_mut(w * 4) {
|
||||
row.copy_from_slice(first);
|
||||
let tasks = workers.tasks(h);
|
||||
let band = h.div_ceil(tasks);
|
||||
let bands = Slots::new(out.chunks_mut(band * w * 4).enumerate());
|
||||
let background = bgra(BACKGROUND);
|
||||
workers.run(bands.len(), &|i| {
|
||||
let Some((i, rows)) = bands.take(i) else { return };
|
||||
match &self.desktop {
|
||||
Some(desktop) => desktop.draw(rows, w, i * band, n as usize * 3),
|
||||
None => {
|
||||
for px in rows.chunks_exact_mut(4) {
|
||||
px.copy_from_slice(&background);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
let (rx, ry, rw, rh) = self.rect(n);
|
||||
fill(out, w, (rx as usize, ry as usize, rw as usize, rh as usize), RECT_COLOR);
|
||||
// Frame counter in the top-left corner.
|
||||
@@ -370,18 +392,27 @@ impl ScreenCapture for SyntheticScreen {
|
||||
let mut fps = sink.max_fps();
|
||||
let mut ticker = Ticker::new(fps);
|
||||
let mut buffer = Buffer::new(&pattern);
|
||||
// A few threads: drawing is memory-bound, and many threads
|
||||
// cost far more CPU for little time.
|
||||
let mut workers = Workers::new("voelin-synthetic", 4);
|
||||
let started = Instant::now();
|
||||
let mut n = 0;
|
||||
loop {
|
||||
let timestamp = started.elapsed();
|
||||
if sink.wants(timestamp) {
|
||||
let bytes = buffer.bytes();
|
||||
pattern.draw(n, bytes);
|
||||
let taken = match buffer.dmabuf(&pattern, timestamp) {
|
||||
// Buffers in video memory are drawn in advance; memory
|
||||
// only for a sink that declines them.
|
||||
if !buffer.drawn_in_advance() {
|
||||
pattern.draw(n, buffer.bytes(), &mut workers);
|
||||
}
|
||||
let taken = match buffer.dmabuf(&pattern, n, timestamp) {
|
||||
Some(frame) if sink.accepts_dmabuf() => sink.dmabuf(&frame),
|
||||
_ => None,
|
||||
};
|
||||
let more = taken.unwrap_or_else(|| {
|
||||
if buffer.drawn_in_advance() {
|
||||
pattern.draw(n, buffer.bytes(), &mut workers);
|
||||
}
|
||||
let plane = PlaneRef::new(buffer.bytes(), width as usize * 4);
|
||||
sink.frame(FrameRef {
|
||||
width,
|
||||
@@ -413,17 +444,31 @@ impl ScreenCapture for SyntheticScreen {
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the test pattern is drawn: plain memory, or a DMA-BUF of ordinary
|
||||
/// memory ([`SyntheticScreen::with_dmabuf`]).
|
||||
/// Frames of the pattern drawn in advance into video memory
|
||||
/// ([`SyntheticScreen::with_video_memory`]), handed over in turn.
|
||||
pub const VIDEO_MEMORY_FRAMES: usize = 8;
|
||||
|
||||
/// Where the test pattern is drawn: plain memory, a DMA-BUF of ordinary
|
||||
/// memory ([`SyntheticScreen::with_dmabuf`]), or buffers in video memory
|
||||
/// drawn in advance (and memory for a sink that declines them).
|
||||
enum Buffer {
|
||||
Memory(Vec<u8>),
|
||||
#[cfg(all(target_os = "linux", feature = "pipewire"))]
|
||||
Dmabuf(super::dmabuf::Udmabuf),
|
||||
#[cfg(all(target_os = "linux", feature = "ffmpeg"))]
|
||||
Video(Vec<crate::ffmpeg::Exported>, Vec<u8>),
|
||||
}
|
||||
|
||||
impl Buffer {
|
||||
fn new(pattern: &SyntheticScreen) -> Self {
|
||||
let len = pattern.width as usize * pattern.height as usize * 4;
|
||||
#[cfg(all(target_os = "linux", feature = "ffmpeg"))]
|
||||
if pattern.dmabuf && pattern.video_memory {
|
||||
match Self::video_memory(pattern) {
|
||||
Ok(frames) => return Self::Video(frames, vec![0; len]),
|
||||
Err(e) => tracing::warn!("test pattern not in video memory: {e}"),
|
||||
}
|
||||
}
|
||||
#[cfg(all(target_os = "linux", feature = "pipewire"))]
|
||||
if pattern.dmabuf {
|
||||
match super::dmabuf::Udmabuf::new(len) {
|
||||
@@ -434,21 +479,54 @@ impl Buffer {
|
||||
Self::Memory(vec![0; len])
|
||||
}
|
||||
|
||||
/// [`VIDEO_MEMORY_FRAMES`] frames of the pattern in VA-API surfaces of
|
||||
/// the driver's layout, exported as DMA-BUFs.
|
||||
#[cfg(all(target_os = "linux", feature = "ffmpeg"))]
|
||||
fn video_memory(
|
||||
pattern: &SyntheticScreen,
|
||||
) -> std::result::Result<Vec<crate::ffmpeg::Exported>, String> {
|
||||
let ffmpeg = crate::ffmpeg::Ffmpeg::get().map_err(str::to_owned)?;
|
||||
let bgr0 = ffmpeg.pix.bgr0.ok_or("no bgr0 pixel format")?;
|
||||
let size = (pattern.width, pattern.height);
|
||||
(0..VIDEO_MEMORY_FRAMES as u64)
|
||||
.map(|n| {
|
||||
let picture = pattern.frame(n, 1);
|
||||
crate::ffmpeg::Exported::new(size, bgr0, super::drm_fourcc(b"XR24"), Some(&picture))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The frames are in video memory already.
|
||||
fn drawn_in_advance(&self) -> bool {
|
||||
#[cfg(all(target_os = "linux", feature = "ffmpeg"))]
|
||||
if let Self::Video(..) = self {
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn bytes(&mut self) -> &mut [u8] {
|
||||
match self {
|
||||
Self::Memory(bytes) => bytes,
|
||||
#[cfg(all(target_os = "linux", feature = "pipewire"))]
|
||||
Self::Dmabuf(buffer) => buffer.bytes_mut(),
|
||||
#[cfg(all(target_os = "linux", feature = "ffmpeg"))]
|
||||
Self::Video(_, bytes) => bytes,
|
||||
}
|
||||
}
|
||||
|
||||
/// The buffer as a LINEAR `XR24` DMA-BUF, if it is one.
|
||||
fn dmabuf(&self, pattern: &SyntheticScreen, timestamp: Duration) -> Option<DmaBufRef> {
|
||||
/// Frame `n` as an `XR24` DMA-BUF, if the buffers are DMA-BUFs.
|
||||
fn dmabuf(&self, pattern: &SyntheticScreen, n: u64, timestamp: Duration) -> Option<DmaBufRef> {
|
||||
match self {
|
||||
Self::Memory(_) => {
|
||||
let _ = (pattern, timestamp);
|
||||
let _ = (pattern, n, timestamp);
|
||||
None
|
||||
}
|
||||
#[cfg(all(target_os = "linux", feature = "ffmpeg"))]
|
||||
Self::Video(frames, _) => {
|
||||
let exported = &frames[n as usize % frames.len()];
|
||||
Some(DmaBufRef { timestamp, ..exported.frame })
|
||||
}
|
||||
#[cfg(all(target_os = "linux", feature = "pipewire"))]
|
||||
Self::Dmabuf(buffer) => Some(DmaBufRef {
|
||||
width: pattern.width,
|
||||
@@ -663,4 +741,72 @@ mod tests {
|
||||
assert_eq!(row, expected[..64 * 4], "the first row of frame 0");
|
||||
}
|
||||
}
|
||||
|
||||
/// In video memory: the frames drawn in advance come in turn, each its
|
||||
/// own buffer; a sink that declines them gets memory frames.
|
||||
#[cfg(all(target_os = "linux", feature = "ffmpeg"))]
|
||||
#[tokio::test]
|
||||
async fn the_pattern_in_video_memory() {
|
||||
use std::sync::mpsc;
|
||||
|
||||
/// Takes DMA-BUFs (or declines them) and reports each one's fd.
|
||||
struct Sink {
|
||||
take: bool,
|
||||
got: mpsc::Sender<Option<i32>>,
|
||||
}
|
||||
impl FrameSink for Sink {
|
||||
fn max_fps(&self) -> u32 {
|
||||
100
|
||||
}
|
||||
fn frame(&mut self, _: FrameRef<'_>) -> bool {
|
||||
self.got.send(None).is_ok()
|
||||
}
|
||||
fn accepts_dmabuf(&self) -> bool {
|
||||
true
|
||||
}
|
||||
fn dmabuf(&mut self, frame: &DmaBufRef) -> Option<bool> {
|
||||
assert_eq!((frame.width, frame.height), (256, 128));
|
||||
self.take.then(|| self.got.send(Some(frame.fd)).is_ok())
|
||||
}
|
||||
}
|
||||
|
||||
let exports =
|
||||
crate::ffmpeg::Ffmpeg::get().ok().and_then(|f| f.pix.bgr0).is_some_and(|bgr0| {
|
||||
crate::ffmpeg::Exported::new(
|
||||
(64, 64),
|
||||
bgr0,
|
||||
super::super::drm_fourcc(b"XR24"),
|
||||
None,
|
||||
)
|
||||
.is_ok()
|
||||
});
|
||||
if !exports {
|
||||
eprintln!("no VA-API surfaces to export, skipped");
|
||||
return;
|
||||
}
|
||||
for take in [true, false] {
|
||||
let mut screen =
|
||||
SyntheticScreen::new(256, 128).with_dmabuf(true).with_video_memory(true);
|
||||
let (got, frames) = mpsc::channel();
|
||||
let sink = Box::new(Sink { take, got });
|
||||
screen
|
||||
.start_sink(&SourceId::Synthetic, &CaptureOptions::default(), sink)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut fds = std::collections::BTreeSet::new();
|
||||
for _ in 0..2 * VIDEO_MEMORY_FRAMES {
|
||||
match frames.recv_timeout(Duration::from_secs(5)).unwrap() {
|
||||
Some(fd) => {
|
||||
assert!(take, "declined, yet a DMA-BUF");
|
||||
fds.insert(fd);
|
||||
}
|
||||
None => assert!(!take, "taken, yet a memory frame"),
|
||||
}
|
||||
}
|
||||
screen.stop();
|
||||
if take {
|
||||
assert_eq!(fds.len(), VIDEO_MEMORY_FRAMES, "each buffer in turn");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,12 +12,12 @@
|
||||
//! Type-checked on Linux (`--target x86_64-pc-windows-gnu`), not run yet.
|
||||
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::Instant;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use tracing::{debug, warn};
|
||||
use windows_capture::capture::{CaptureControl, Context, GraphicsCaptureApiHandler};
|
||||
use windows_capture::frame::Frame;
|
||||
use windows_capture::graphics_capture_api::InternalCaptureControl;
|
||||
use windows_capture::graphics_capture_api::{GraphicsCaptureApi, InternalCaptureControl};
|
||||
use windows_capture::monitor::Monitor;
|
||||
use windows_capture::settings::{
|
||||
ColorFormat, CursorCaptureSettings, DirtyRegionSettings, DrawBorderSettings,
|
||||
@@ -105,13 +105,20 @@ where
|
||||
} else {
|
||||
CursorCaptureSettings::WithoutCursor
|
||||
};
|
||||
// Left alone, Windows delivers about 60 frames a second (reported for
|
||||
// a default and for anything under 1 ms: robmikh/Win32CaptureSample#82).
|
||||
// 1 ms lets the sink's frame-rate cap decide, which can change while
|
||||
// capturing. Windows 10 has no such setting.
|
||||
let interval = match GraphicsCaptureApi::is_minimum_update_interval_supported() {
|
||||
Ok(true) => MinimumUpdateIntervalSettings::Custom(Duration::from_millis(1)),
|
||||
_ => MinimumUpdateIntervalSettings::Default,
|
||||
};
|
||||
let settings = Settings::new(
|
||||
item,
|
||||
cursor,
|
||||
DrawBorderSettings::WithoutBorder,
|
||||
SecondaryWindowSettings::Default,
|
||||
// No minimum: the frame rate can change while capturing.
|
||||
MinimumUpdateIntervalSettings::Default,
|
||||
interval,
|
||||
DirtyRegionSettings::Default,
|
||||
ColorFormat::Bgra8,
|
||||
(sink, Instant::now()),
|
||||
|
||||
@@ -148,7 +148,8 @@ pub enum H264Profile {
|
||||
pub struct EncoderConfig {
|
||||
/// Expected frame rate (rate control; timestamps come from the frames).
|
||||
pub fps: u32,
|
||||
/// Target bitrate in bits per second. TeamSpeak caps streams at 10 Mbit/s.
|
||||
/// Target bitrate in bits per second (no limit; TeamSpeak 6 servers
|
||||
/// enforce none, see `voelin_stream::proto::MAX_ANNOUNCED_BITRATE`).
|
||||
pub bitrate_bps: u32,
|
||||
/// Maximum frames between keyframes; `None` sends keyframes only at the
|
||||
/// start and on request (PLI), like WebRTC.
|
||||
|
||||
@@ -245,6 +245,98 @@ fn h264_level(profile: H264Profile, width: u32, height: u32, fps: u32, bitrate:
|
||||
.map_or(H264_LEVELS[H264_LEVELS.len() - 1].0, |l| l.0)
|
||||
}
|
||||
|
||||
/// An HEVC level (ITU-T H.265 Table A.8 and A.9): `general_level_idc` (30
|
||||
/// times the level), luma samples per picture and per second, Main and High
|
||||
/// tier bitrate in kbit/s (High from level 4 on).
|
||||
type HevcLevel = (i64, u64, u64, u64, u64);
|
||||
|
||||
const HEVC_LEVELS: [HevcLevel; 13] = [
|
||||
(30, 36_864, 552_960, 128, 0),
|
||||
(60, 122_880, 3_686_400, 1_500, 0),
|
||||
(63, 245_760, 7_372_800, 3_000, 0),
|
||||
(90, 552_960, 16_588_800, 6_000, 0),
|
||||
(93, 983_040, 33_177_600, 10_000, 0),
|
||||
(120, 2_228_224, 66_846_720, 12_000, 30_000),
|
||||
(123, 2_228_224, 133_693_440, 20_000, 50_000),
|
||||
(150, 8_912_896, 267_386_880, 25_000, 100_000),
|
||||
(153, 8_912_896, 534_773_760, 40_000, 160_000),
|
||||
(156, 8_912_896, 1_069_547_520, 60_000, 240_000),
|
||||
(180, 35_651_584, 1_069_547_520, 60_000, 240_000),
|
||||
(183, 35_651_584, 2_139_095_040, 120_000, 480_000),
|
||||
(186, 35_651_584, 4_278_190_080, 240_000, 800_000),
|
||||
];
|
||||
|
||||
/// An AV1 level (AV1 specification A.3): `seq_level_idx`, samples per
|
||||
/// picture, width, height, samples per second (MaxDisplayRate), frame
|
||||
/// headers per second, Main and High tier bitrate in kbit/s (High from 4.0
|
||||
/// on).
|
||||
type Av1Level = (i64, u64, u32, u32, u64, u32, u64, u64);
|
||||
|
||||
const AV1_LEVELS: [Av1Level; 14] = [
|
||||
(0, 147_456, 2048, 1152, 4_423_680, 150, 1_500, 0),
|
||||
(1, 278_784, 2816, 1584, 8_363_520, 150, 3_000, 0),
|
||||
(4, 665_856, 4352, 2448, 19_975_680, 150, 6_000, 0),
|
||||
(5, 1_065_024, 5504, 3096, 31_950_720, 150, 10_000, 0),
|
||||
(8, 2_359_296, 6144, 3456, 70_778_880, 300, 12_000, 30_000),
|
||||
(9, 2_359_296, 6144, 3456, 141_557_760, 300, 20_000, 50_000),
|
||||
(12, 8_912_896, 8192, 4352, 267_386_880, 300, 30_000, 100_000),
|
||||
(13, 8_912_896, 8192, 4352, 534_773_760, 300, 40_000, 160_000),
|
||||
(14, 8_912_896, 8192, 4352, 1_069_547_520, 300, 60_000, 240_000),
|
||||
(15, 8_912_896, 8192, 4352, 1_069_547_520, 300, 60_000, 240_000),
|
||||
(16, 35_651_584, 16384, 8704, 1_069_547_520, 300, 60_000, 240_000),
|
||||
(17, 35_651_584, 16384, 8704, 2_139_095_040, 300, 100_000, 480_000),
|
||||
(18, 35_651_584, 16384, 8704, 4_278_190_080, 300, 160_000, 800_000),
|
||||
(19, 35_651_584, 16384, 8704, 4_278_190_080, 300, 160_000, 800_000),
|
||||
];
|
||||
|
||||
/// The lowest level of `levels` (`fits` its picture and rate limits) whose
|
||||
/// Main tier holds `kbps`, else the lowest whose High tier does: Main is
|
||||
/// what more decoders take. `None` beyond every level.
|
||||
fn tiered_level<L: Copy>(
|
||||
levels: &[L],
|
||||
fits: impl Fn(&L) -> bool,
|
||||
tiers: impl Fn(&L) -> (i64, u64, u64),
|
||||
kbps: u64,
|
||||
) -> Option<(i64, bool)> {
|
||||
let fitting = || levels.iter().filter(|l| fits(l)).map(&tiers);
|
||||
let main = fitting().find(|&(_, main, _)| kbps <= main).map(|(level, ..)| (level, false));
|
||||
main.or_else(|| fitting().find(|&(.., high)| kbps <= high).map(|(level, ..)| (level, true)))
|
||||
}
|
||||
|
||||
/// HEVC `general_level_idc` and High tier for this stream (see
|
||||
/// [`tiered_level`]); beyond every level 8.5 (255) in the High tier, as
|
||||
/// FFmpeg's own guess does.
|
||||
fn hevc_level(width: u32, height: u32, fps: u32, bitrate: u32) -> (i64, bool) {
|
||||
let picture = u64::from(width) * u64::from(height);
|
||||
let rate = picture * u64::from(fps.max(1));
|
||||
let side = u64::from(width.max(height));
|
||||
let fits = |&(_, max_picture, max_rate, ..): &HevcLevel| {
|
||||
picture <= max_picture && side * side <= 8 * max_picture && rate <= max_rate
|
||||
};
|
||||
let tiers = |&(level, .., main, high): &HevcLevel| (level, main, high);
|
||||
tiered_level(&HEVC_LEVELS, fits, tiers, u64::from(bitrate).div_ceil(1000))
|
||||
.unwrap_or((255, true))
|
||||
}
|
||||
|
||||
/// AV1 `seq_level_idx` and High tier for this stream (see
|
||||
/// [`tiered_level`]); beyond every level 31, which has no limits, as
|
||||
/// FFmpeg's own guess does. Unlike that guess this counts the frame rate:
|
||||
/// FFmpeg's wrappers read it from `AVCodecContext.framerate`, which has no
|
||||
/// AVOption.
|
||||
fn av1_level(width: u32, height: u32, fps: u32, bitrate: u32) -> (i64, bool) {
|
||||
let picture = u64::from(width) * u64::from(height);
|
||||
let rate = picture * u64::from(fps.max(1));
|
||||
let fits = |&(_, max_picture, max_w, max_h, max_rate, headers, ..): &Av1Level| {
|
||||
picture <= max_picture
|
||||
&& width <= max_w
|
||||
&& height <= max_h
|
||||
&& rate <= max_rate
|
||||
&& fps <= headers
|
||||
};
|
||||
let tiers = |&(level, .., main, high): &Av1Level| (level, main, high);
|
||||
tiered_level(&AV1_LEVELS, fits, tiers, u64::from(bitrate).div_ceil(1000)).unwrap_or((31, true))
|
||||
}
|
||||
|
||||
/// The backend's realtime settings (besides size, format, time base and
|
||||
/// rate, which every backend gets).
|
||||
fn settings(spec: &BackendSpec, config: &EncoderConfig, low_power: bool) -> Vec<Setting> {
|
||||
@@ -855,9 +947,12 @@ impl FfmpegEncoder {
|
||||
// 7.9 % at 1440p60 / 10 Mbit/s (RX 7900 GRE, desktop pattern);
|
||||
// with two it lands within 1.2 % at both and at 720p30, no frame
|
||||
// skipped, the largest 68 KB against 64 KB at 1440p60.
|
||||
// `bufsize` is an int: from 1 Gbit/s (2.1 for one second) the
|
||||
// buffer stays at the most it holds rather than failing the open.
|
||||
generic(
|
||||
"bufsize",
|
||||
u64::from(bitrate) * if self.spec.name == "av1_vaapi" { 2 } else { 1 },
|
||||
(u64::from(bitrate) * if self.spec.name == "av1_vaapi" { 2 } else { 1 })
|
||||
.min(i32::MAX as u64),
|
||||
),
|
||||
generic("g", gop),
|
||||
generic("bf", 0),
|
||||
@@ -879,6 +974,21 @@ impl FfmpegEncoder {
|
||||
list.push(generic("level", &level));
|
||||
list.push(Setting { values: vec![level], ..opt("level", &[]) });
|
||||
}
|
||||
// HEVC and AV1 through VA-API: the level and tier the stream needs.
|
||||
// Left to FFmpeg, a 4K240 stream declares a 4K60 level (neither guess
|
||||
// counts the frame rate, and the HEVC one ignores it entirely). Only
|
||||
// VA-API, whose `level` is `general_level_idc` and `seq_level_idx`;
|
||||
// other wrappers count levels differently (Quick Sync in tenths).
|
||||
let tiered = match self.spec.codec {
|
||||
Codec::H265 if self.spec.is_vaapi() => Some(hevc_level(width, height, fps, bitrate)),
|
||||
Codec::Av1 if self.spec.is_vaapi() => Some(av1_level(width, height, fps, bitrate)),
|
||||
_ => None,
|
||||
};
|
||||
if let Some((level, high)) = tiered {
|
||||
list.push(generic("level", level));
|
||||
list.push(Setting { values: vec![level.to_string()], ..opt("level", &[]) });
|
||||
list.push(opt("tier", &[if high { "high" } else { "main" }]));
|
||||
}
|
||||
list.extend(settings(self.spec, &self.config, low_power));
|
||||
for setting in &list {
|
||||
self.apply(ctx, private, setting)?;
|
||||
@@ -1883,6 +1993,7 @@ impl EncoderFactory for FfmpegFactory {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::gpu::Exported;
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
@@ -2026,112 +2137,6 @@ mod tests {
|
||||
probe().iter().any(|s| s.spec.name == name && s.available.is_ok())
|
||||
}
|
||||
|
||||
/// A VA-API surface of `sw_format` (holding `picture`, BGRA, if given)
|
||||
/// exported as a DRM PRIME DMA-BUF: what a compositor hands over,
|
||||
/// tiling modifier and all. The buffer is valid while this lives.
|
||||
struct Exported {
|
||||
pool: Ptr,
|
||||
surface: Ptr,
|
||||
drm: Ptr,
|
||||
frame: DmaBufRef,
|
||||
}
|
||||
|
||||
impl Exported {
|
||||
fn new(
|
||||
(width, height): (u32, u32),
|
||||
sw_format: c_int,
|
||||
fourcc: u32,
|
||||
picture: Option<&VideoFrame>,
|
||||
) -> Self {
|
||||
let ffmpeg = Ffmpeg::get().unwrap();
|
||||
let api = &ffmpeg.api;
|
||||
let pool = vaapi_pool(ffmpeg, width, height, sw_format).expect("a VA-API surface pool");
|
||||
// SAFETY: `pool` is a live frames context of this process's
|
||||
// VA-API device; the frames are ours and freed by the drop. The
|
||||
// exported frame's `data[0]` is the AVDRMFrameDescriptor FFmpeg
|
||||
// filled, valid while the frame holds the mapping.
|
||||
unsafe {
|
||||
let mut exported = Exported {
|
||||
pool,
|
||||
surface: (api.av_frame_alloc)(),
|
||||
drm: (api.av_frame_alloc)(),
|
||||
frame: DmaBufRef {
|
||||
width,
|
||||
height,
|
||||
timestamp: Duration::ZERO,
|
||||
fourcc,
|
||||
modifier: 0,
|
||||
fd: -1,
|
||||
size: 0,
|
||||
planes: [(0, 0); 4],
|
||||
plane_count: 0,
|
||||
},
|
||||
};
|
||||
let (surface, drm) = (exported.surface, exported.drm);
|
||||
assert!(!surface.is_null() && !drm.is_null());
|
||||
let ret = (api.av_hwframe_get_buffer)(pool, surface, 0);
|
||||
assert!(ret >= 0, "av_hwframe_get_buffer: {}", api.error_text(ret));
|
||||
if let Some(picture) = picture {
|
||||
let FrameData::Bgra(pixels) = &picture.data else { panic!("BGRA only") };
|
||||
let mut sw = (api.av_frame_alloc)();
|
||||
let head = sw.cast::<FrameHead>();
|
||||
((*head).width, (*head).height) = (width as c_int, height as c_int);
|
||||
(*head).format = sw_format;
|
||||
assert!((api.av_frame_get_buffer)(sw, 0) >= 0);
|
||||
let stride = (*head).linesize[0] as usize;
|
||||
let rows =
|
||||
std::slice::from_raw_parts_mut((*head).data[0], stride * height as usize);
|
||||
for (y, row) in rows.chunks_exact_mut(stride).enumerate() {
|
||||
row[..width as usize * 4]
|
||||
.copy_from_slice(pixels.row(y, width as usize * 4));
|
||||
}
|
||||
let ret = (api.av_hwframe_transfer_data)(surface, sw, 0);
|
||||
(api.av_frame_free)(&mut sw);
|
||||
assert!(ret >= 0, "upload: {}", api.error_text(ret));
|
||||
}
|
||||
(*drm.cast::<FrameHead>()).format = ffmpeg.pix.drm_prime.expect("DRM PRIME");
|
||||
let ret = (api.av_hwframe_map)(
|
||||
drm,
|
||||
surface,
|
||||
sys::HWFRAME_MAP_READ | sys::HWFRAME_MAP_DIRECT,
|
||||
);
|
||||
assert!(ret >= 0, "this driver cannot export a VA-API surface as a DMA-BUF");
|
||||
let descriptor =
|
||||
*(*drm.cast::<FrameHead>()).data[0].cast::<sys::DrmFrameDescriptor>();
|
||||
assert_eq!(descriptor.nb_objects, 1, "one buffer object");
|
||||
// The driver may describe a surface one plane per layer (NV12
|
||||
// as R8 for Y and GR88 for UV) rather than as one layer, which
|
||||
// is how a compositor hands it over. Both name the same bytes
|
||||
// of the same object, so flatten the layers into planes.
|
||||
let object = descriptor.objects[0];
|
||||
let frame = &mut exported.frame;
|
||||
for layer in &descriptor.layers[..descriptor.nb_layers as usize] {
|
||||
for plane in &layer.planes[..layer.nb_planes as usize] {
|
||||
frame.planes[frame.plane_count] =
|
||||
(plane.offset as usize, plane.pitch as usize);
|
||||
frame.plane_count += 1;
|
||||
}
|
||||
}
|
||||
(frame.modifier, frame.fd, frame.size) =
|
||||
(object.format_modifier, object.fd, object.size);
|
||||
assert!(frame.fd >= 0 && frame.size > 0);
|
||||
exported
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Exported {
|
||||
fn drop(&mut self) {
|
||||
let api = &Ffmpeg::get().unwrap().api;
|
||||
// SAFETY: ours; the mapping goes before the surface it maps.
|
||||
unsafe {
|
||||
(api.av_frame_free)(&mut self.drm);
|
||||
(api.av_frame_free)(&mut self.surface);
|
||||
(api.av_buffer_unref)(&mut self.pool);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The picture of a GPU frame, read back into memory as I420.
|
||||
fn download(frame: &GpuFrame) -> VideoFrame {
|
||||
let ffmpeg = Ffmpeg::get().unwrap();
|
||||
@@ -2185,7 +2190,8 @@ mod tests {
|
||||
);
|
||||
let picture = screen.frame(5, 30);
|
||||
let rgb =
|
||||
Exported::new(SIZE, ffmpeg.pix.bgr0.unwrap(), drm_fourcc(b"XR24"), Some(&picture));
|
||||
Exported::new(SIZE, ffmpeg.pix.bgr0.unwrap(), drm_fourcc(b"XR24"), Some(&picture))
|
||||
.unwrap();
|
||||
let mut converter = GpuConverter::new().expect("VA-API video processing");
|
||||
eprintln!("tiled RGB modifiers the import takes: {:x?}", converter.modifiers());
|
||||
let layers = [
|
||||
@@ -2270,7 +2276,7 @@ mod tests {
|
||||
return;
|
||||
}
|
||||
let nv12 = Ffmpeg::get().unwrap().pix.nv12;
|
||||
let exported = Exported::new((320, 240), nv12, drm_fourcc(b"NV12"), None);
|
||||
let exported = Exported::new((320, 240), nv12, drm_fourcc(b"NV12"), None).unwrap();
|
||||
let frame = exported.frame;
|
||||
assert_eq!(frame.plane_count, 2, "NV12 has two planes");
|
||||
let mut encoder = FfmpegEncoder::new("h264_vaapi", EncoderConfig::default()).unwrap();
|
||||
@@ -2311,7 +2317,8 @@ mod tests {
|
||||
);
|
||||
let picture = screen.frame(3, 30);
|
||||
let rgb =
|
||||
Exported::new(SIZE, ffmpeg.pix.bgr0.unwrap(), drm_fourcc(b"XR24"), Some(&picture));
|
||||
Exported::new(SIZE, ffmpeg.pix.bgr0.unwrap(), drm_fourcc(b"XR24"), Some(&picture))
|
||||
.unwrap();
|
||||
assert_eq!(rgb.frame.plane_count, 1);
|
||||
|
||||
// The conversion alone: the GPU's NV12 against the CPU's I420.
|
||||
@@ -2497,7 +2504,8 @@ mod tests {
|
||||
drop(encoder);
|
||||
|
||||
let rgb =
|
||||
Exported::new(SIZE, ffmpeg.pix.bgr0.unwrap(), drm_fourcc(b"XR24"), Some(&picture));
|
||||
Exported::new(SIZE, ffmpeg.pix.bgr0.unwrap(), drm_fourcc(b"XR24"), Some(&picture))
|
||||
.unwrap();
|
||||
let mut encoder = FfmpegEncoder::new("h264_vaapi", config).unwrap();
|
||||
measure("GPU: RGB DMA-BUF imported and converted", &mut |timestamp| {
|
||||
let frame = DmaBufRef { timestamp, ..rgb.frame };
|
||||
@@ -2505,6 +2513,145 @@ mod tests {
|
||||
});
|
||||
}
|
||||
|
||||
/// A picture in memory, BGRx (a screen) or RGBx (the studio's
|
||||
/// composite), copied into a surface and converted on the GPU: the same
|
||||
/// picture as the CPU's conversion, at full and half size.
|
||||
#[test]
|
||||
fn memory_pictures_are_converted_on_the_gpu() {
|
||||
const SIZE: (u32, u32) = (1280, 720);
|
||||
if !usable("h264_vaapi") {
|
||||
eprintln!("no usable h264_vaapi, skipped");
|
||||
return;
|
||||
}
|
||||
let screen = crate::capture::synthetic::SyntheticScreen::with_pattern(
|
||||
SIZE.0,
|
||||
SIZE.1,
|
||||
crate::capture::synthetic::Pattern::Desktop,
|
||||
);
|
||||
let bgra = screen.frame(7, 30);
|
||||
let FrameData::Bgra(pixels) = &bgra.data else { unreachable!() };
|
||||
let mut swapped = pixels.data.clone();
|
||||
for px in swapped.chunks_exact_mut(4) {
|
||||
px.swap(0, 2);
|
||||
}
|
||||
let rgba = VideoFrame::from_rgba(SIZE.0, SIZE.1, pixels.stride, swapped).unwrap();
|
||||
let cpu = convert::to_i420(&bgra).unwrap().into_owned();
|
||||
let mut half = VideoFrame::black_i420(SIZE.0 / 2, SIZE.1 / 2);
|
||||
let mut workers = crate::workers::Workers::new("voelin-test-scale", 1);
|
||||
crate::scale::scale_i420(&mut workers, &cpu, &mut half).unwrap();
|
||||
let mut converter = GpuConverter::new().expect("VA-API video processing");
|
||||
let layers = [
|
||||
GpuLayer { size: SIZE, alignment: (2, 2), due: true },
|
||||
GpuLayer { size: (SIZE.0 / 2, SIZE.1 / 2), alignment: (2, 2), due: true },
|
||||
];
|
||||
for picture in [&bgra, &rgba] {
|
||||
let mut out = [None, None];
|
||||
assert!(converter.takes(&picture.view().pixels));
|
||||
converter.convert_memory(&picture.view(), &layers, &mut out).expect("converted");
|
||||
for (frame, reference) in out.iter().flatten().zip([&cpu, &half]) {
|
||||
let psnr = convert::psnr(reference, &download(frame)).unwrap();
|
||||
eprintln!("{}x{}: PSNR {psnr:.1} dB against the CPU's", frame.width, frame.height);
|
||||
assert!(psnr > 30.0, "{}x{}: {psnr:.1} dB", frame.width, frame.height);
|
||||
}
|
||||
}
|
||||
// Not RGB: the caller converts it.
|
||||
let i420 = VideoFrame::black_i420(64, 64);
|
||||
assert!(!converter.takes(&i420.view().pixels));
|
||||
}
|
||||
|
||||
/// What the GPU path costs per captured frame: the DMA-BUF import alone,
|
||||
/// and the whole conversion (import, VPP to NV12, the wait for the GPU),
|
||||
/// from a buffer of the driver's own (video memory, tiled) and from a
|
||||
/// LINEAR one of ordinary memory where `/dev/udmabuf` allows its size.
|
||||
/// `cargo test -p voelin-media --release --lib gpu_conversion_cost --
|
||||
/// --ignored --nocapture`.
|
||||
#[cfg(feature = "pipewire")]
|
||||
#[test]
|
||||
#[ignore = "a measurement, not a check"]
|
||||
fn gpu_conversion_cost() {
|
||||
if !usable("h264_vaapi") {
|
||||
eprintln!("no usable h264_vaapi, skipped");
|
||||
return;
|
||||
}
|
||||
// CPU time of every thread of the process.
|
||||
let cpu_time = || -> Duration {
|
||||
let tasks = std::fs::read_dir("/proc/self/task").unwrap().flatten();
|
||||
tasks
|
||||
.filter_map(|t| std::fs::read_to_string(t.path().join("schedstat")).ok())
|
||||
.filter_map(|s| s.split_whitespace().next()?.parse().ok())
|
||||
.map(Duration::from_nanos)
|
||||
.sum()
|
||||
};
|
||||
let ffmpeg = Ffmpeg::get().unwrap();
|
||||
for size in [(1920, 1080), (3840, 2160), (7680, 4320)] {
|
||||
let screen = crate::capture::synthetic::SyntheticScreen::with_pattern(
|
||||
size.0,
|
||||
size.1,
|
||||
crate::capture::synthetic::Pattern::Desktop,
|
||||
);
|
||||
let picture = screen.frame(3, 60);
|
||||
let vram =
|
||||
Exported::new(size, ffmpeg.pix.bgr0.unwrap(), drm_fourcc(b"XR24"), Some(&picture))
|
||||
.unwrap();
|
||||
let len = size.0 as usize * size.1 as usize * 4;
|
||||
let mut ram = crate::capture::dmabuf::Udmabuf::new(len).ok();
|
||||
if let Some(ram) = &mut ram {
|
||||
let FrameData::Bgra(pixels) = &picture.data else { unreachable!() };
|
||||
ram.bytes_mut().copy_from_slice(&pixels.data[..len]);
|
||||
}
|
||||
let linear = ram.as_ref().map(|ram| DmaBufRef {
|
||||
fd: ram.fd(),
|
||||
size: ram.len(),
|
||||
modifier: crate::capture::DRM_MOD_LINEAR,
|
||||
planes: [(0, size.0 as usize * 4), (0, 0), (0, 0), (0, 0)],
|
||||
plane_count: 1,
|
||||
..vram.frame
|
||||
});
|
||||
let mut converter = GpuConverter::new().unwrap();
|
||||
let layer = [GpuLayer { size, alignment: (2, 2), due: true }];
|
||||
let mut out = [None];
|
||||
for (what, frame) in [("video memory", Some(vram.frame)), ("udmabuf", linear)] {
|
||||
let Some(frame) = frame else {
|
||||
eprintln!("{}x{} {what}: no buffer of that size", size.0, size.1);
|
||||
continue;
|
||||
};
|
||||
converter.convert(&frame, &layer, &mut out).unwrap();
|
||||
let started = Instant::now();
|
||||
for _ in 0..100 {
|
||||
converter.import_only(&frame).unwrap();
|
||||
}
|
||||
let import = started.elapsed() / 100;
|
||||
let started = Instant::now();
|
||||
for _ in 0..100 {
|
||||
converter.convert(&frame, &layer, &mut out).unwrap();
|
||||
}
|
||||
let convert = started.elapsed() / 100;
|
||||
eprintln!(
|
||||
"{}x{} {what}: import {:.2} ms, whole conversion {:.2} ms",
|
||||
size.0,
|
||||
size.1,
|
||||
import.as_secs_f64() * 1e3,
|
||||
convert.as_secs_f64() * 1e3
|
||||
);
|
||||
}
|
||||
// The same picture in memory, copied into a surface.
|
||||
let view = picture.view();
|
||||
converter.convert_memory(&view, &layer, &mut out).unwrap();
|
||||
let (cpu, started) = (cpu_time(), Instant::now());
|
||||
for _ in 0..50 {
|
||||
converter.convert_memory(&view, &layer, &mut out).unwrap();
|
||||
}
|
||||
let (wall, cpu) = (started.elapsed() / 50, (cpu_time() - cpu) / 50);
|
||||
eprintln!(
|
||||
"{}x{} memory: {:.2} ms, {:.2} ms CPU per frame",
|
||||
size.0,
|
||||
size.1,
|
||||
wall.as_secs_f64() * 1e3,
|
||||
cpu.as_secs_f64() * 1e3
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// On Linux an AMF encoder is not even made unless asked for, so AMF's
|
||||
/// runtime is never loaded by default; other backends are made as
|
||||
/// before.
|
||||
@@ -2528,6 +2675,39 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Levels and tiers per H.265 Table A.8 and AV1 A.3, with the frame rate
|
||||
/// and the bitrate counted.
|
||||
#[test]
|
||||
fn hevc_and_av1_levels() {
|
||||
// 1080p60 at 8 Mbit/s: 4.1 Main; 4K60 at 60 Mbit/s: 5.1's Main
|
||||
// tier holds 40, so 5.2 Main.
|
||||
assert_eq!(hevc_level(1920, 1080, 60, 8_000_000), (123, false));
|
||||
assert_eq!(hevc_level(3840, 2160, 60, 60_000_000), (156, false));
|
||||
// 4K240 needs 6.1 for its sample rate; 8K30, 8K60, 8K120: 6, 6.1, 6.2.
|
||||
assert_eq!(hevc_level(3840, 2160, 240, 60_000_000), (183, false));
|
||||
assert_eq!(hevc_level(7680, 4320, 30, 60_000_000), (180, false));
|
||||
assert_eq!(hevc_level(7680, 4320, 60, 60_000_000), (183, false));
|
||||
assert_eq!(hevc_level(7680, 4320, 120, 60_000_000), (186, false));
|
||||
// Beyond the Main tier of every level: High.
|
||||
assert_eq!(hevc_level(1920, 1080, 30, 300_000_000), (183, true));
|
||||
// Beyond every level: 8.5.
|
||||
assert_eq!(hevc_level(7680, 4320, 320, 60_000_000), (255, true));
|
||||
assert_eq!(hevc_level(16384, 16384, 30, 60_000_000), (255, true));
|
||||
|
||||
// AV1: 1080p60 at 6 Mbit/s 4.1; 4K60 at 60 Mbit/s 5.2 (5.1 Main
|
||||
// holds 40).
|
||||
assert_eq!(av1_level(1920, 1080, 60, 6_000_000), (9, false));
|
||||
assert_eq!(av1_level(3840, 2160, 60, 60_000_000), (14, false));
|
||||
// The frame rate counts: 4K240 6.1, 1440p240 5.2, 8K60 6.1.
|
||||
assert_eq!(av1_level(3840, 2160, 240, 60_000_000), (17, false));
|
||||
assert_eq!(av1_level(2560, 1440, 240, 60_000_000), (14, false));
|
||||
assert_eq!(av1_level(7680, 4320, 60, 60_000_000), (17, false));
|
||||
// 8K30 at 100 Mbit/s: 6.1 Main rather than 6.0 High.
|
||||
assert_eq!(av1_level(7680, 4320, 30, 100_000_000), (17, false));
|
||||
// More than 300 frame headers a second is beyond every level.
|
||||
assert_eq!(av1_level(1920, 1080, 320, 60_000_000), (31, true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_per_backend() {
|
||||
let config = EncoderConfig::default();
|
||||
|
||||
@@ -22,7 +22,7 @@ use super::layout::{self, FrameRefs};
|
||||
use super::sys::{self, FrameHead, Ptr};
|
||||
use super::{Ffmpeg, vpp};
|
||||
use crate::capture::{DRM_MOD_INVALID, DRM_MOD_LINEAR, DmaBufRef, drm_fourcc};
|
||||
use crate::frame::GpuFrame;
|
||||
use crate::frame::{FrameRef, GpuFrame, PixelsRef, PlaneRef};
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// The DRM formats of RGB buffers the conversion takes (8 bits per
|
||||
@@ -138,6 +138,142 @@ pub(crate) fn map_dmabuf(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A VA-API surface of `sw_format` (holding `picture`, BGRA, if given)
|
||||
/// exported as a DRM PRIME DMA-BUF: a buffer in video memory as a
|
||||
/// compositor hands one over, the driver's tiling modifier and all. The
|
||||
/// buffer ([`frame`](Self::frame)) is valid while this lives.
|
||||
#[cfg(target_os = "linux")]
|
||||
pub(crate) struct Exported {
|
||||
pool: Ptr,
|
||||
surface: Ptr,
|
||||
drm: Ptr,
|
||||
pub(crate) frame: DmaBufRef,
|
||||
}
|
||||
|
||||
// SAFETY: the frames and the pool are ours; FFmpeg's buffer references are
|
||||
// thread-safe and the surface is only read once it is made.
|
||||
#[cfg(target_os = "linux")]
|
||||
unsafe impl Send for Exported {}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
impl Exported {
|
||||
pub(crate) fn new(
|
||||
(width, height): (u32, u32),
|
||||
sw_format: c_int,
|
||||
fourcc: u32,
|
||||
picture: Option<&crate::frame::VideoFrame>,
|
||||
) -> std::result::Result<Self, String> {
|
||||
let ffmpeg = Ffmpeg::get().map_err(str::to_owned)?;
|
||||
let api = &ffmpeg.api;
|
||||
let pool = vaapi_pool(ffmpeg, width, height, sw_format)?;
|
||||
let mut exported = Exported {
|
||||
pool,
|
||||
// SAFETY: allocations, checked below; the drop frees them.
|
||||
surface: unsafe { (api.av_frame_alloc)() },
|
||||
drm: unsafe { (api.av_frame_alloc)() },
|
||||
frame: DmaBufRef {
|
||||
width,
|
||||
height,
|
||||
timestamp: Duration::ZERO,
|
||||
fourcc,
|
||||
modifier: 0,
|
||||
fd: -1,
|
||||
size: 0,
|
||||
planes: [(0, 0); 4],
|
||||
plane_count: 0,
|
||||
},
|
||||
};
|
||||
let (surface, drm) = (exported.surface, exported.drm);
|
||||
if surface.is_null() || drm.is_null() {
|
||||
return Err("out of memory".into());
|
||||
}
|
||||
// SAFETY: `pool` is a live frames context of this process's VA-API
|
||||
// device; the frames are ours. The exported frame's `data[0]` is the
|
||||
// AVDRMFrameDescriptor FFmpeg filled, valid while the frame holds
|
||||
// the mapping; a picture's rows are `width * 4` bytes.
|
||||
unsafe {
|
||||
let ret = (api.av_hwframe_get_buffer)(pool, surface, 0);
|
||||
if ret < 0 {
|
||||
return Err(format!("VA-API surface: {}", api.error_text(ret)));
|
||||
}
|
||||
if let Some(picture) = picture {
|
||||
let crate::frame::FrameData::Bgra(pixels) = &picture.data else {
|
||||
return Err("only BGRA pictures are uploaded".into());
|
||||
};
|
||||
let mut sw = (api.av_frame_alloc)();
|
||||
if sw.is_null() {
|
||||
return Err("out of memory".into());
|
||||
}
|
||||
let head = sw.cast::<FrameHead>();
|
||||
((*head).width, (*head).height) = (width as c_int, height as c_int);
|
||||
(*head).format = sw_format;
|
||||
let mut ret = (api.av_frame_get_buffer)(sw, 0);
|
||||
if ret >= 0 {
|
||||
let stride = (*head).linesize[0] as usize;
|
||||
let rows =
|
||||
std::slice::from_raw_parts_mut((*head).data[0], stride * height as usize);
|
||||
for (y, row) in rows.chunks_exact_mut(stride).enumerate() {
|
||||
row[..width as usize * 4]
|
||||
.copy_from_slice(pixels.row(y, width as usize * 4));
|
||||
}
|
||||
ret = (api.av_hwframe_transfer_data)(surface, sw, 0);
|
||||
}
|
||||
(api.av_frame_free)(&mut sw);
|
||||
if ret < 0 {
|
||||
return Err(format!("upload: {}", api.error_text(ret)));
|
||||
}
|
||||
}
|
||||
(*drm.cast::<FrameHead>()).format =
|
||||
ffmpeg.pix.drm_prime.ok_or("no DRM PRIME format")?;
|
||||
let flags = sys::HWFRAME_MAP_READ | sys::HWFRAME_MAP_DIRECT;
|
||||
if (api.av_hwframe_map)(drm, surface, flags) < 0 {
|
||||
return Err("this driver cannot export a VA-API surface as a DMA-BUF".into());
|
||||
}
|
||||
let descriptor = *(*drm.cast::<FrameHead>()).data[0].cast::<sys::DrmFrameDescriptor>();
|
||||
if descriptor.nb_objects != 1 {
|
||||
return Err(format!("{} buffer objects, not one", descriptor.nb_objects));
|
||||
}
|
||||
// The driver may describe a surface one plane per layer (NV12 as
|
||||
// R8 for Y and GR88 for UV) rather than as one layer, which is how
|
||||
// a compositor hands it over. Both name the same bytes of the same
|
||||
// object, so the layers are flattened into planes.
|
||||
let object = descriptor.objects[0];
|
||||
let frame = &mut exported.frame;
|
||||
let layers = descriptor.layers.iter().take(descriptor.nb_layers.max(0) as usize);
|
||||
for layer in layers {
|
||||
for plane in layer.planes.iter().take(layer.nb_planes.max(0) as usize) {
|
||||
if frame.plane_count == frame.planes.len() {
|
||||
return Err("more than four planes".into());
|
||||
}
|
||||
frame.planes[frame.plane_count] = (plane.offset as usize, plane.pitch as usize);
|
||||
frame.plane_count += 1;
|
||||
}
|
||||
}
|
||||
(frame.modifier, frame.fd, frame.size) =
|
||||
(object.format_modifier, object.fd, object.size);
|
||||
if frame.fd < 0 || frame.size == 0 {
|
||||
return Err("no DMA-BUF exported".into());
|
||||
}
|
||||
}
|
||||
Ok(exported)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
impl Drop for Exported {
|
||||
fn drop(&mut self) {
|
||||
if let Ok(ffmpeg) = Ffmpeg::get() {
|
||||
// SAFETY: ours (or NULL); the mapping goes before the surface it
|
||||
// maps.
|
||||
unsafe {
|
||||
(ffmpeg.api.av_frame_free)(&mut self.drm);
|
||||
(ffmpeg.api.av_frame_free)(&mut self.surface);
|
||||
(ffmpeg.api.av_buffer_unref)(&mut self.pool);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One output of [`GpuConverter::convert`]: a layer's size, the multiple
|
||||
/// its encoder takes, and whether it wants this frame.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
@@ -180,8 +316,12 @@ pub struct GpuConverter {
|
||||
vpp: Option<(vpp::Converter, (u32, u32))>,
|
||||
/// The frames context DMA-BUFs of this size are mapped onto.
|
||||
import: Option<(Ptr, (u32, u32))>,
|
||||
/// Holds a mapping while it is converted.
|
||||
/// Surfaces pictures in memory of this size and format are copied into.
|
||||
upload: Option<(Ptr, (u32, u32), c_int)>,
|
||||
/// Holds a mapping (or an uploaded surface) while it is converted.
|
||||
mapped: Surface,
|
||||
/// An uploaded surface mapped into memory while its rows are written.
|
||||
writable: Surface,
|
||||
outputs: Vec<Output>,
|
||||
modifiers: Vec<u64>,
|
||||
}
|
||||
@@ -205,7 +345,9 @@ impl GpuConverter {
|
||||
display,
|
||||
vpp: None,
|
||||
import: None,
|
||||
upload: None,
|
||||
mapped: Surface::alloc(ffmpeg)?,
|
||||
writable: Surface::alloc(ffmpeg)?,
|
||||
outputs: Vec::new(),
|
||||
modifiers: Vec::new(),
|
||||
};
|
||||
@@ -275,12 +417,107 @@ impl GpuConverter {
|
||||
self.prepare(source)?;
|
||||
let pool = self.import.as_ref().expect("prepared").0;
|
||||
map_dmabuf(self.ffmpeg, frame, pool, self.mapped.0, self.refs).map_err(Error::Convert)?;
|
||||
let result = self.convert_mapped(frame, layers, out);
|
||||
let result = self.convert_mapped(source, frame.timestamp, layers, out);
|
||||
// SAFETY: our frame; this lets the buffer go.
|
||||
unsafe { (self.ffmpeg.api.av_frame_unref)(self.mapped.0) };
|
||||
result
|
||||
}
|
||||
|
||||
/// Whether [`convert_memory`](Self::convert_memory) takes pictures like
|
||||
/// `pixels`: BGRx or RGBx (alpha is ignored).
|
||||
pub fn takes(&self, pixels: &PixelsRef<'_>) -> bool {
|
||||
self.upload_format(pixels).is_some()
|
||||
}
|
||||
|
||||
fn upload_format<'a>(&self, pixels: &PixelsRef<'a>) -> Option<(PlaneRef<'a>, c_int)> {
|
||||
match *pixels {
|
||||
PixelsRef::Bgra(plane) => Some((plane, self.ffmpeg.pix.bgr0?)),
|
||||
PixelsRef::Rgba(plane) => Some((plane, self.ffmpeg.pix.rgb0?)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert `frame`, an RGB picture in memory ([`takes`](Self::takes)),
|
||||
/// like [`convert`](Self::convert): it is copied into a surface of its
|
||||
/// own, which the GPU converts and scales for every due layer. That copy
|
||||
/// is all the CPU does, where converting the picture to I420 and scaling
|
||||
/// it on every core, then uploading each layer from its encoder's
|
||||
/// thread, cost several times as much. Measured on a Radeon RX 7900
|
||||
/// GRE: 11.9 ms a 7680x4320 frame, 5.7 ms of it the copy on the CPU and
|
||||
/// the rest the GPU's upload and conversion, waited for. More threads
|
||||
/// copying gained little (9.9 ms with eight) for several times the CPU
|
||||
/// (26 ms), so it is one. Not waiting for the GPU (only before the next
|
||||
/// copy into the same surface) was slower in the streamer: 36 fps at
|
||||
/// 7680x4320 against 42, the encoder then waiting for the conversion.
|
||||
pub fn convert_memory(
|
||||
&mut self,
|
||||
frame: &FrameRef<'_>,
|
||||
layers: &[GpuLayer],
|
||||
out: &mut [Option<Arc<GpuFrame>>],
|
||||
) -> Result<()> {
|
||||
let Some((plane, format)) = self.upload_format(&frame.pixels) else {
|
||||
return Err(Error::Convert("not an RGB picture".into()));
|
||||
};
|
||||
let source = (frame.width, frame.height);
|
||||
let (row, rows) = (frame.width as usize * 4, frame.height as usize);
|
||||
if rows == 0 || plane.stride < row || plane.data.len() < plane.stride * (rows - 1) + row {
|
||||
return Err(Error::InvalidFrame("the picture is smaller than its size".into()));
|
||||
}
|
||||
self.outputs.retain(|o| layers.iter().any(|l| exact_size(l.size, l.alignment) == o.size));
|
||||
self.prepare(source)?;
|
||||
if self.upload.as_ref().is_none_or(|&(_, size, f)| (size, f) != (source, format)) {
|
||||
if let Some((mut pool, ..)) = self.upload.take() {
|
||||
// SAFETY: our reference.
|
||||
unsafe { (self.ffmpeg.api.av_buffer_unref)(&mut pool) };
|
||||
}
|
||||
let pool =
|
||||
vaapi_pool(self.ffmpeg, source.0, source.1, format).map_err(Error::Convert)?;
|
||||
self.upload = Some((pool, source, format));
|
||||
}
|
||||
let pool = self.upload.as_ref().expect("made above").0;
|
||||
let api = &self.ffmpeg.api;
|
||||
let (surface, writable) = (self.mapped.0, self.writable.0);
|
||||
// SAFETY: our frames; `surface` takes a surface of our pool and
|
||||
// `writable` maps it (`format` is the pool's), so its first plane
|
||||
// is `linesize[0]` bytes per row for `height` rows until the unref,
|
||||
// which writes it to the surface (`vaPutImage`).
|
||||
let mapped = unsafe {
|
||||
let ret = (api.av_hwframe_get_buffer)(pool, surface, 0);
|
||||
if ret < 0 {
|
||||
return Err(Error::Convert(format!("VA-API surface: {}", api.error_text(ret))));
|
||||
}
|
||||
(*writable.cast::<FrameHead>()).format = format;
|
||||
let flags = sys::HWFRAME_MAP_WRITE | sys::HWFRAME_MAP_OVERWRITE;
|
||||
let ret = (api.av_hwframe_map)(writable, surface, flags);
|
||||
if ret < 0 {
|
||||
(api.av_frame_unref)(surface);
|
||||
return Err(Error::Convert(format!("mapping a surface: {}", api.error_text(ret))));
|
||||
}
|
||||
let head = &*writable.cast::<FrameHead>();
|
||||
std::slice::from_raw_parts_mut(head.data[0], head.linesize[0] as usize * rows)
|
||||
};
|
||||
for (y, out) in mapped.chunks_exact_mut(mapped.len() / rows).enumerate() {
|
||||
out[..row].copy_from_slice(plane.row(y, row));
|
||||
}
|
||||
// SAFETY: our mapping; unmapping uploads it.
|
||||
unsafe { (api.av_frame_unref)(writable) };
|
||||
let result = self.convert_mapped(source, frame.timestamp, layers, out);
|
||||
// SAFETY: our frame; the surface goes back to the pool.
|
||||
unsafe { (api.av_frame_unref)(surface) };
|
||||
result
|
||||
}
|
||||
|
||||
/// Map `frame` and let it go again: the import alone, for measuring.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn import_only(&mut self, frame: &DmaBufRef) -> Result<()> {
|
||||
self.prepare((frame.width, frame.height))?;
|
||||
let pool = self.import.as_ref().expect("prepared").0;
|
||||
map_dmabuf(self.ffmpeg, frame, pool, self.mapped.0, self.refs).map_err(Error::Convert)?;
|
||||
// SAFETY: our frame.
|
||||
unsafe { (self.ffmpeg.api.av_frame_unref)(self.mapped.0) };
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The import pool and the video processing for buffers of `source`'s
|
||||
/// size.
|
||||
fn prepare(&mut self, source: (u32, u32)) -> Result<()> {
|
||||
@@ -302,9 +539,12 @@ impl GpuConverter {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Convert and scale the picture in `mapped`, `size` large, taken at
|
||||
/// `timestamp`, for every due layer.
|
||||
fn convert_mapped(
|
||||
&mut self,
|
||||
frame: &DmaBufRef,
|
||||
size: (u32, u32),
|
||||
timestamp: Duration,
|
||||
layers: &[GpuLayer],
|
||||
out: &mut [Option<Arc<GpuFrame>>],
|
||||
) -> Result<()> {
|
||||
@@ -319,11 +559,8 @@ impl GpuConverter {
|
||||
let part = |full: u32, kept: u32, of: u32| {
|
||||
(u64::from(full) * u64::from(kept) / u64::from(of.max(1))).max(1) as u32
|
||||
};
|
||||
let src = (
|
||||
part(frame.width, exact.0, layer.size.0),
|
||||
part(frame.height, exact.1, layer.size.1),
|
||||
);
|
||||
let gpu = self.output(exact, frame.timestamp)?;
|
||||
let src = (part(size.0, exact.0, layer.size.0), part(size.1, exact.1, layer.size.1));
|
||||
let gpu = self.output(exact, timestamp)?;
|
||||
let (vpp, _) = self.vpp.as_ref().expect("prepared");
|
||||
vpp.convert(input, src, gpu.surface.id(), exact).map_err(Error::Convert)?;
|
||||
*slot = Some(gpu);
|
||||
@@ -381,5 +618,9 @@ impl Drop for GpuConverter {
|
||||
// SAFETY: our reference.
|
||||
unsafe { (self.ffmpeg.api.av_buffer_unref)(&mut pool) };
|
||||
}
|
||||
if let Some((mut pool, ..)) = self.upload.take() {
|
||||
// SAFETY: our reference.
|
||||
unsafe { (self.ffmpeg.api.av_buffer_unref)(&mut pool) };
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -30,6 +30,8 @@ mod layout;
|
||||
pub mod sys;
|
||||
mod vpp;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub(crate) use gpu::Exported;
|
||||
pub(crate) use gpu::Surface;
|
||||
pub use gpu::{GpuConverter, GpuLayer};
|
||||
|
||||
@@ -51,6 +53,8 @@ pub(crate) struct PixFmts {
|
||||
pub drm_prime: Option<c_int>,
|
||||
/// `bgr0`: B, G, R, x in memory, the DRM `XR24` of captured screens.
|
||||
pub bgr0: Option<c_int>,
|
||||
/// `rgb0`: R, G, B, x in memory (`XB24`), the studio's composite.
|
||||
pub rgb0: Option<c_int>,
|
||||
}
|
||||
|
||||
/// libavformat's I/O functions and where a write error lands
|
||||
@@ -128,6 +132,7 @@ impl Ffmpeg {
|
||||
vaapi: api.pix_fmt("vaapi").or_else(|| api.pix_fmt("vaapi_vld")),
|
||||
drm_prime: api.pix_fmt("drm_prime"),
|
||||
bgr0: api.pix_fmt("bgr0"),
|
||||
rgb0: api.pix_fmt("rgb0"),
|
||||
};
|
||||
let hw_fields = layout::codec_hw_fields(&api);
|
||||
let codec_hw_frames = hw_fields.clone().map(|(frames, _)| frames);
|
||||
|
||||
@@ -150,8 +150,10 @@ pub const LOG_QUIET: c_int = -8;
|
||||
pub const LOG_ERROR: c_int = 16;
|
||||
pub const LOG_WARNING: c_int = 24;
|
||||
|
||||
/// `AV_HWFRAME_MAP_READ` and `AV_HWFRAME_MAP_DIRECT`.
|
||||
/// `AV_HWFRAME_MAP_READ`, `_WRITE`, `_OVERWRITE` and `_DIRECT`.
|
||||
pub const HWFRAME_MAP_READ: c_int = 1;
|
||||
pub const HWFRAME_MAP_WRITE: c_int = 2;
|
||||
pub const HWFRAME_MAP_OVERWRITE: c_int = 4;
|
||||
pub const HWFRAME_MAP_DIRECT: c_int = 8;
|
||||
|
||||
/// `AVERROR(EAGAIN)`: FFmpeg errors are negated `errno` values of the C
|
||||
|
||||
@@ -92,8 +92,18 @@ pub fn profile_level_id(profile: H264Profile, level_idc: u8) -> u32 {
|
||||
/// offer official clients know stays the same for small streams.
|
||||
pub const MIN_OFFER_LEVEL: u8 = 31;
|
||||
|
||||
/// The highest level an offer declares (5.2): libwebrtc (the official
|
||||
/// client's stack; `H264Level` in `h264_profile_level_id.h`, main branch
|
||||
/// 2026-10) and str0m 0.23 (`H264LevelIdc`) know no level above it, and a
|
||||
/// `profile-level-id` they cannot parse matches nothing: a viewer answered
|
||||
/// such an offer without video (tried with str0m: `m=video 0`, no payload
|
||||
/// type). Streams that need 6.0-6.2 (3840x2160 above 60 fps, 7680x4320,
|
||||
/// 1080p above 250 fps) are offered as 5.2 and still carry their real level
|
||||
/// in the SPS, which decoders size themselves from.
|
||||
pub const MAX_OFFER_LEVEL: u8 = 52;
|
||||
|
||||
/// `profile-level-id` for a stream of this size, frame rate and bitrate,
|
||||
/// at least level 3.1.
|
||||
/// at least level 3.1 and at most [`MAX_OFFER_LEVEL`].
|
||||
pub fn offer_profile_level_id(
|
||||
profile: H264Profile,
|
||||
width: u32,
|
||||
@@ -101,8 +111,8 @@ pub fn offer_profile_level_id(
|
||||
fps: u32,
|
||||
bitrate: u64,
|
||||
) -> u32 {
|
||||
let level = level_idc(profile, width, height, fps, bitrate).max(MIN_OFFER_LEVEL);
|
||||
profile_level_id(profile, level)
|
||||
let level = level_idc(profile, width, height, fps, bitrate);
|
||||
profile_level_id(profile, level.clamp(MIN_OFFER_LEVEL, MAX_OFFER_LEVEL))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -142,6 +152,11 @@ mod tests {
|
||||
assert_eq!(profile_level_id(HIGH, 31), 0x640c1f);
|
||||
assert_eq!(profile_level_id(H264Profile::ConstrainedBaseline, 31), 0x42e01f);
|
||||
assert_eq!(offer_profile_level_id(HIGH, 320, 240, 15, 200_000), 0x640c1f);
|
||||
// 4K60 is 5.2; 4K120 and 8K need 6.x, which peers cannot parse: 5.2.
|
||||
assert_eq!(offer_profile_level_id(HIGH, 3840, 2160, 60, 60_000_000), 0x640c34);
|
||||
assert_eq!(offer_profile_level_id(HIGH, 3840, 2160, 120, 60_000_000), 0x640c34);
|
||||
let baseline = H264Profile::ConstrainedBaseline;
|
||||
assert_eq!(offer_profile_level_id(baseline, 7680, 4320, 60, 60_000_000), 0x42e034);
|
||||
assert_eq!(offer_profile_level_id(HIGH, 1920, 1080, 60, 8_000_000), 0x640c2a);
|
||||
// Back from the SDP, at any level; other profiles are not ours.
|
||||
assert_eq!(H264Profile::from_profile_level_id(0x640c2a), Some(HIGH));
|
||||
|
||||
@@ -993,6 +993,8 @@ impl Task {
|
||||
&mut self,
|
||||
mut stun_servers: mpsc::UnboundedReceiver<SocketAddr>,
|
||||
) -> Result<(), PeerError> {
|
||||
// Turns in a row str0m wanted again at once.
|
||||
let mut immediate = 0u32;
|
||||
loop {
|
||||
let now = Instant::now();
|
||||
self.rtc.handle_input(Input::Timeout(now))?;
|
||||
@@ -1022,6 +1024,18 @@ impl Task {
|
||||
}
|
||||
};
|
||||
let deadline = self.stall.due(self.offerer).map_or(deadline, |due| due.min(deadline));
|
||||
// The pacer asks for a timeout at once after every packet it lets
|
||||
// out. Tokio's timer rounds that up to its next millisecond, so a
|
||||
// paced stream sent one packet a millisecond: 9.5 Mbit/s at 1188
|
||||
// bytes (str0m's probes measured exactly that, and the estimate
|
||||
// of a 60 Mbit/s stream on loopback fell to 9 Mbit/s). A due
|
||||
// timeout is handled at once instead, a bounded number of turns
|
||||
// in a row so packets and commands are still read in between.
|
||||
if deadline <= Instant::now() && immediate < 256 {
|
||||
immediate += 1;
|
||||
continue;
|
||||
}
|
||||
immediate = 0;
|
||||
let sleep = tokio::time::sleep_until(tokio::time::Instant::from_std(deadline));
|
||||
tokio::select! {
|
||||
packet = self.net.incoming.recv() => {
|
||||
|
||||
@@ -76,12 +76,19 @@ impl LeaveReason {
|
||||
}
|
||||
}
|
||||
|
||||
/// The most `setupstream` announces, in kbit/s: TeamSpeak 6 servers keep
|
||||
/// the bitrate in 16 bits and wrap anything above (6.0.0-beta13.1 announced
|
||||
/// 100000 as 34464), but enforce nothing, so a stream sends its real rate
|
||||
/// peer to peer whatever the announcement says.
|
||||
pub const MAX_ANNOUNCED_BITRATE: u32 = u16::MAX as u32;
|
||||
|
||||
/// Parameters of `setupstream`.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct StreamSetup {
|
||||
pub name: String,
|
||||
pub kind: StreamKind,
|
||||
/// kbit/s; the server caps streams at 10 Mbit/s.
|
||||
/// The stream's video bitrate in kbit/s (the single layer's without
|
||||
/// simulcast); announced as at most [`MAX_ANNOUNCED_BITRATE`].
|
||||
pub bitrate: u32,
|
||||
/// `accessibility`: the official client and ts6-manager send 1.
|
||||
pub accessibility: u8,
|
||||
@@ -301,7 +308,7 @@ pub fn setup(setup: &StreamSetup) -> OutCommand {
|
||||
c2s::OutSetupStreamMessage::new(&mut iter::once(c2s::OutSetupStreamPart {
|
||||
stream_name: Cow::Borrowed(&setup.name),
|
||||
stream_type: setup.kind.to_u8(),
|
||||
bitrate: setup.bitrate,
|
||||
bitrate: setup.bitrate.min(MAX_ANNOUNCED_BITRATE),
|
||||
access: setup.accessibility,
|
||||
stream_mode: setup.mode,
|
||||
viewer_limit: setup.viewer_limit,
|
||||
@@ -442,6 +449,11 @@ mod tests {
|
||||
"setupstream name=my\\sscreen type=3 bitrate=4608 accessibility=1 mode=1 viewer_limit=0 \
|
||||
audio=1"
|
||||
);
|
||||
// 60 Mbit/s is announced as it is; beyond 16 bits, the most the
|
||||
// server keeps instead of a wrapped value.
|
||||
let fast = |bitrate| text(setup(&StreamSetup { bitrate, ..s.clone() }));
|
||||
assert!(fast(60_000).contains(" bitrate=60000 "));
|
||||
assert!(fast(100_000).contains(" bitrate=65535 "));
|
||||
assert_eq!(
|
||||
text(join_request("u-1", ClientId(5), "", false)),
|
||||
"joinstreamrequest id=u-1 clid=5 msg is_remove=0"
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use tokio::time::timeout;
|
||||
use voelin_stream::{MediaKind, MediaTime, Peer, PeerConfig, PeerEvent, SrtpProfile};
|
||||
use voelin_stream::{MediaKind, MediaTime, OfferOptions, Peer, PeerConfig, PeerEvent, SrtpProfile};
|
||||
|
||||
mod relay;
|
||||
use relay::{Relay, Rule};
|
||||
@@ -232,22 +232,77 @@ async fn stream_noise(
|
||||
|
||||
/// One media packet in 25 lost on the way to the viewer: the viewer asks
|
||||
/// again (NACK) and the streamer retransmits (RTX) before the depacketizer
|
||||
/// gives up, so every frame arrives whole and in order.
|
||||
/// gives up, so every frame arrives whole and in order. A NACK needs a later
|
||||
/// packet to show the hole, so one more frame follows the 90 counted: a loss
|
||||
/// at the very end (retransmissions shift which packet is the 25th) can only
|
||||
/// cut that one.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn losses_are_repaired_by_retransmission() {
|
||||
let _ = tracing_subscriber::fmt().with_env_filter("warn").with_test_writer().try_init();
|
||||
let relay = Relay::new(Rule::LoseEvery(25)).await;
|
||||
let config = PeerConfig { bandwidth_estimation: false, ..PeerConfig::loopback() };
|
||||
let (streamer, mut viewer) = connect(&config, &config, Some(&relay)).await;
|
||||
// 3 s at 30 fps, 12 KB frames (about 10 packets each), keyframes of 60 KB.
|
||||
let received = stream_noise(streamer, &mut viewer, (90, 30, 12_000), (30, 60_000)).await;
|
||||
// 3 s at 30 fps, 12 KB frames (about 10 packets each), keyframes of 60 KB,
|
||||
// and the one more frame.
|
||||
let received = stream_noise(streamer, &mut viewer, (91, 30, 12_000), (30, 60_000)).await;
|
||||
let (media, lost) = relay.media();
|
||||
eprintln!("{received:?}; relay: {lost} of {media} media packets lost");
|
||||
assert!(lost >= 30, "the relay lost too little: {lost} of {media}");
|
||||
assert_eq!(received.frames, 90, "{received:?}");
|
||||
assert!(received.frames >= 90, "{received:?}");
|
||||
assert_eq!(received.gaps, 0, "a loss reached the viewer: {received:?}");
|
||||
}
|
||||
|
||||
/// A 60 Mbit/s stream with bandwidth estimation: the pacer lets it out at
|
||||
/// that rate and the estimate stays near it. Before the peer task handled a
|
||||
/// due timeout at once, tokio's millisecond timer let the pacer out one
|
||||
/// packet a millisecond (9.5 Mbit/s at 1188 bytes), and a 4K60 stream's
|
||||
/// estimate through the TeamSpeak 6 server fell from 60 to 9 Mbit/s.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_pacer_keeps_up_with_60_mbits() {
|
||||
let _ = tracing_subscriber::fmt().with_env_filter("warn").with_test_writer().try_init();
|
||||
let config = PeerConfig::loopback();
|
||||
// The streamer starts at the stream's bitrate, as a session does.
|
||||
let options = OfferOptions {
|
||||
start_bitrate: Some(60_000_000),
|
||||
desired_bitrate: Some(72_000_000),
|
||||
..OfferOptions::default()
|
||||
};
|
||||
let (mut streamer, offer) = Peer::offer_with(&config, "fast", &options).await.unwrap();
|
||||
let (mut viewer, answer) = Peer::answer(&config, &offer).await.unwrap();
|
||||
streamer.accept_answer(&answer).await.unwrap();
|
||||
tokio::join!(wait_connected(&mut streamer), wait_connected(&mut viewer));
|
||||
// 60 Mbit/s at 60 fps: 125 KB a frame, keyframes of 1 MB every second.
|
||||
let sender = tokio::spawn(async move {
|
||||
let start = Instant::now();
|
||||
let mut estimates = Vec::new();
|
||||
let mut streamer = streamer;
|
||||
for i in 0..300u64 {
|
||||
let keyframe = i % 60 == 0;
|
||||
let data = noise_frame(i, if keyframe { 1_000_000 } else { 125_000 }, keyframe);
|
||||
streamer.write(MediaKind::Video, MediaTime::from_90khz(i * 1500), data);
|
||||
while let Some(event) = streamer.try_next_event() {
|
||||
if let PeerEvent::BitrateEstimate(b) = event {
|
||||
estimates.push(b);
|
||||
}
|
||||
}
|
||||
tokio::time::sleep_until((start + Duration::from_micros((i + 1) * 16_667)).into())
|
||||
.await;
|
||||
}
|
||||
estimates
|
||||
});
|
||||
let (mut bytes, start) = (0usize, Instant::now());
|
||||
while let Ok(Some(event)) = timeout(Duration::from_secs(1), viewer.next_event()).await {
|
||||
if let PeerEvent::Media(f) = event {
|
||||
bytes += f.data.len();
|
||||
}
|
||||
}
|
||||
let mbits = bytes as f64 * 8.0 / start.elapsed().as_secs_f64() / 1e6;
|
||||
let estimates = sender.await.unwrap();
|
||||
let last = estimates.last().copied().unwrap_or(0);
|
||||
eprintln!("received {mbits:.1} Mbit/s; estimates {estimates:?}");
|
||||
assert!(last >= 40_000_000, "the estimate fell to {last} bit/s");
|
||||
}
|
||||
|
||||
/// UDP receive errors of this host so far (`RcvbufErrors` in
|
||||
/// `/proc/net/snmp`: datagrams dropped because a socket's buffer was full).
|
||||
fn receive_buffer_errors() -> Option<u64> {
|
||||
|
||||
@@ -532,7 +532,11 @@ async fn no_layer_request_without_the_offer_listing_layers() {
|
||||
assert!(viewer.watching().next().unwrap().layers().is_empty());
|
||||
assert_eq!(viewer.set_watch_layer(&id, Some(0)), Err(SessionError::NoLayers(id.clone())));
|
||||
assert_eq!(viewer.set_watch_layer(&id, None), Err(SessionError::NoLayers(id.clone())));
|
||||
assert!(viewer.poll_output().is_none(), "nothing sent");
|
||||
// Nothing sent (frames that arrived meanwhile are events, not requests).
|
||||
let requests = std::iter::from_fn(|| viewer.poll_output())
|
||||
.filter(|o| matches!(o, Output::Request(_)))
|
||||
.count();
|
||||
assert_eq!(requests, 0, "nothing sent");
|
||||
net.flush().await;
|
||||
assert!(!net.signals.iter().any(|(_, s)| matches!(s, Signal::Layer { .. })));
|
||||
}
|
||||
|
||||
@@ -233,10 +233,16 @@ pub fn page_keys() -> [&'static dyn voelin_core::settings::Setting; 10] {
|
||||
]
|
||||
}
|
||||
|
||||
/// Frame rates and bitrates (kbit/s) the share dialog offers; any other
|
||||
/// value can be typed in.
|
||||
pub const FPS_CHOICES: [u32; 3] = [15, 30, 60];
|
||||
pub const BITRATE_CHOICES: [u32; 4] = [2500, 4608, 8000, 10_000];
|
||||
/// Frame rates and bitrates (kbit/s; 0: automatic) the share dialog
|
||||
/// offers, in the order of its lists (`dialogs.slint`); any other value can
|
||||
/// be typed in.
|
||||
pub const FPS_CHOICES: [u32; 7] = [15, 30, 60, 120, 144, 240, 320];
|
||||
pub const BITRATE_CHOICES: [u32; 8] = [0, 2500, 4608, 8000, 10_000, 20_000, 40_000, 60_000];
|
||||
|
||||
/// The share dialog's lists before they grew, which [`ShareDefaults`]
|
||||
/// indexes for older versions.
|
||||
pub const LEGACY_FPS_CHOICES: [u32; 3] = [15, 30, 60];
|
||||
pub const LEGACY_BITRATE_CHOICES: [u32; 4] = [2500, 4608, 8000, 10_000];
|
||||
|
||||
/// The index of the choice closest to `value`.
|
||||
pub fn nearest_choice(choices: &[u32], value: u32) -> usize {
|
||||
@@ -279,7 +285,8 @@ impl Default for UiSettings {
|
||||
|
||||
/// The last choices in the share dialog. Frame rate and bitrate are the
|
||||
/// settings `stream.fps` and `stream.bitrate_kbps`; the indices of the
|
||||
/// closest choices are kept for older versions.
|
||||
/// closest choices of the old lists ([`LEGACY_FPS_CHOICES`],
|
||||
/// [`LEGACY_BITRATE_CHOICES`]) are kept for older versions.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct ShareDefaults {
|
||||
@@ -484,9 +491,12 @@ mod tests {
|
||||
#[test]
|
||||
fn free_values() {
|
||||
assert_eq!(nearest_choice(&FPS_CHOICES, 60), 2);
|
||||
assert_eq!(nearest_choice(&FPS_CHOICES, 144), 2);
|
||||
assert_eq!(nearest_choice(&BITRATE_CHOICES, 3000), 0);
|
||||
assert_eq!(nearest_choice(&BITRATE_CHOICES, 50_000), 3);
|
||||
assert_eq!(nearest_choice(&FPS_CHOICES, 144), 4);
|
||||
assert_eq!(nearest_choice(&FPS_CHOICES, 1000), 6);
|
||||
assert_eq!(nearest_choice(&BITRATE_CHOICES, 0), 0, "automatic");
|
||||
assert_eq!(nearest_choice(&BITRATE_CHOICES, 3000), 1);
|
||||
assert_eq!(nearest_choice(&BITRATE_CHOICES, 55_000), 7);
|
||||
assert_eq!(nearest_choice(&BITRATE_CHOICES, 120_000), 7);
|
||||
assert_eq!(parse_positive(" 144 "), Some(144));
|
||||
assert_eq!(parse_positive("0"), None);
|
||||
assert_eq!(parse_positive("fast"), None);
|
||||
|
||||
@@ -12,6 +12,7 @@ use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
use slint::{ComponentHandle, Model, SharedString};
|
||||
use tracing::warn;
|
||||
use voelin_core::media::auto_bitrate;
|
||||
use voelin_core::settings::{
|
||||
AudioSourceKindSetting, AudioSourceSetting, BlockMode, CACHE_FETCH_IMAGES, CACHE_MAX_MB,
|
||||
CHAT_DEDUPE_TOLERANCE_MS, CHAT_HISTORY_PAGE, CHAT_RETENTION_DAYS, CHAT_STORE_HISTORY,
|
||||
@@ -39,7 +40,8 @@ use crate::settings::{
|
||||
use crate::social::{allowed_index, allowed_of};
|
||||
|
||||
/// Sizes of the stream quality presets (Auto: the source's size).
|
||||
const PRESETS: [(u32, u32); 3] = [(1280, 720), (1920, 1080), (2560, 1440)];
|
||||
const PRESETS: [(u32, u32); 5] =
|
||||
[(1280, 720), (1920, 1080), (2560, 1440), (3840, 2160), (7680, 4320)];
|
||||
|
||||
/// An identity whose level is being raised.
|
||||
pub(crate) struct Improving {
|
||||
@@ -109,6 +111,22 @@ pub(crate) fn layer_of(item: &LayerItem, base: &LayerSetting) -> Option<LayerSet
|
||||
|
||||
/// The preset of a list of layers: 0 Auto (none), 1..3 a preset size, -1
|
||||
/// other layers.
|
||||
/// The layers of quality preset `quality` (0: none, the source's size;
|
||||
/// then [`PRESETS`]) at `kbps` (0: automatic, for the preset's size and
|
||||
/// `fps`); `None` for no preset (layers of one's own).
|
||||
fn preset_layers(quality: i32, kbps: u32, fps: u32) -> Option<Vec<LayerSetting>> {
|
||||
match usize::try_from(quality).ok()? {
|
||||
0 => Some(Vec::new()),
|
||||
q => PRESETS.get(q - 1).map(|&(width, height)| {
|
||||
let bitrate = match kbps {
|
||||
0 => auto_bitrate(width, height, fps),
|
||||
kbps => u64::from(kbps) * 1000,
|
||||
};
|
||||
vec![LayerSetting { size: Some((width, height)), bitrate, ..LayerSetting::default() }]
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn quality_of(layers: &[LayerSetting]) -> i32 {
|
||||
match layers {
|
||||
[] => 0,
|
||||
@@ -401,21 +419,15 @@ impl App {
|
||||
if self.prefs.get(&STREAM_PERMISSIONS) != permissions {
|
||||
self.put(&STREAM_PERMISSIONS, permissions);
|
||||
}
|
||||
let bitrate = form.bitrate.round().max(1.0) as u32;
|
||||
// 0: automatic.
|
||||
let bitrate = form.bitrate.round().max(0.0) as u32;
|
||||
if self.prefs.get(&STREAM_BITRATE_KBPS) != bitrate {
|
||||
self.put(&STREAM_BITRATE_KBPS, bitrate);
|
||||
}
|
||||
// A preset: one layer of that size at the bitrate; Auto: none.
|
||||
// A preset: one layer of that size at the bitrate (an automatic one
|
||||
// for that size and the frame rate); Auto: none.
|
||||
let layers = self.prefs.get(&STREAM_LAYERS);
|
||||
let wanted = match form.quality {
|
||||
0 => Some(Vec::new()),
|
||||
q @ 1..=3 => Some(vec![LayerSetting {
|
||||
size: Some(PRESETS[q as usize - 1]),
|
||||
bitrate: u64::from(bitrate) * 1000,
|
||||
..LayerSetting::default()
|
||||
}]),
|
||||
_ => None,
|
||||
};
|
||||
let wanted = preset_layers(form.quality, bitrate, self.prefs.get(&STREAM_FPS));
|
||||
if let Some(wanted) = wanted.filter(|w| *w != layers) {
|
||||
self.put(&STREAM_LAYERS, wanted);
|
||||
}
|
||||
@@ -426,7 +438,10 @@ impl App {
|
||||
if let Some(fps) = crate::settings::parse_positive(&form.fps) {
|
||||
self.put(&STREAM_FPS, fps);
|
||||
}
|
||||
if let Some(bitrate) = crate::settings::parse_positive(&form.bitrate) {
|
||||
// Nothing, 0 or "auto": automatic.
|
||||
let bitrate = form.bitrate.trim();
|
||||
let auto = bitrate.is_empty() || bitrate == "0" || bitrate.eq_ignore_ascii_case("auto");
|
||||
if let Some(bitrate) = crate::settings::parse_positive(bitrate).or(auto.then_some(0)) {
|
||||
self.put(&STREAM_BITRATE_KBPS, bitrate);
|
||||
}
|
||||
self.put(&STREAM_CODEC, codec_of(form.codec));
|
||||
@@ -1377,7 +1392,16 @@ mod tests {
|
||||
assert_eq!(quality_of(&[]), 0);
|
||||
let layer = |size| LayerSetting { size: Some(size), ..LayerSetting::default() };
|
||||
assert_eq!(quality_of(&[layer((1920, 1080))]), 2);
|
||||
assert_eq!(quality_of(&[layer((3840, 2160))]), 4);
|
||||
assert_eq!(quality_of(&[layer((7680, 4320))]), 5);
|
||||
assert_eq!(quality_of(&[layer((800, 600))]), -1);
|
||||
// A preset at the bitrate, or the automatic one of its size and rate.
|
||||
let one = |l: Option<Vec<LayerSetting>>| l.map(|l| (l[0].size, l[0].bitrate));
|
||||
assert_eq!(one(preset_layers(5, 60_000, 30)), Some((Some((7680, 4320)), 60_000_000)));
|
||||
assert_eq!(one(preset_layers(4, 0, 60)), Some((Some((3840, 2160)), 59_719_680)));
|
||||
assert_eq!(preset_layers(0, 0, 60), Some(Vec::new()));
|
||||
assert_eq!(preset_layers(-1, 0, 60), None);
|
||||
assert_eq!(preset_layers(6, 0, 60), None);
|
||||
assert_eq!(quality_of(&[layer((1280, 720)), layer((640, 360))]), -1);
|
||||
for i in 0..5 {
|
||||
assert_eq!(codec_index(codec_of(i)), i);
|
||||
|
||||
@@ -19,7 +19,8 @@ use crate::app::{
|
||||
App, Bridge, ShareForm, SourceItem, StreamItem, ViewerItem, later, model, with_app,
|
||||
};
|
||||
use crate::settings::{
|
||||
BITRATE_CHOICES, FPS_CHOICES, ShareDefaults, nearest_choice, parse_positive,
|
||||
BITRATE_CHOICES, FPS_CHOICES, LEGACY_BITRATE_CHOICES, LEGACY_FPS_CHOICES, ShareDefaults,
|
||||
nearest_choice, parse_positive,
|
||||
};
|
||||
use crate::video::{self, Capture, CaptureRequest, Decoder};
|
||||
|
||||
@@ -540,7 +541,8 @@ impl App {
|
||||
fps_index: nearest_choice(&FPS_CHOICES, fps) as i32,
|
||||
fps: fps.to_string().into(),
|
||||
bitrate_index: nearest_choice(&BITRATE_CHOICES, bitrate) as i32,
|
||||
bitrate: bitrate.to_string().into(),
|
||||
// Automatic (0): the field stays empty.
|
||||
bitrate: if bitrate == 0 { String::new() } else { bitrate.to_string() }.into(),
|
||||
audio: defaults.audio,
|
||||
auto_accept: defaults.auto_accept,
|
||||
}
|
||||
@@ -586,7 +588,8 @@ impl App {
|
||||
self.refresh_streams();
|
||||
return;
|
||||
}
|
||||
// Typed values (no maximum), else the chosen presets.
|
||||
// Typed values (no maximum), else the chosen presets (bitrate 0:
|
||||
// automatic).
|
||||
let choice = |i: i32, choices: &[u32]| {
|
||||
choices[usize::try_from(i).unwrap_or(0).min(choices.len() - 1)]
|
||||
};
|
||||
@@ -602,8 +605,8 @@ impl App {
|
||||
}
|
||||
}
|
||||
let defaults = ShareDefaults {
|
||||
fps_index: nearest_choice(&FPS_CHOICES, fps),
|
||||
bitrate_index: nearest_choice(&BITRATE_CHOICES, bitrate),
|
||||
fps_index: nearest_choice(&LEGACY_FPS_CHOICES, fps),
|
||||
bitrate_index: nearest_choice(&LEGACY_BITRATE_CHOICES, bitrate),
|
||||
audio: form.audio,
|
||||
auto_accept: form.auto_accept,
|
||||
};
|
||||
@@ -650,6 +653,10 @@ impl App {
|
||||
self.settings.portal_restore_token = Some(token);
|
||||
self.store_settings();
|
||||
}
|
||||
if setup.bitrate == 0 {
|
||||
// Automatic: what it comes to for the size captured.
|
||||
setup.bitrate = capture.streamer().bitrate_kbps();
|
||||
}
|
||||
if setup.audio && !capture.has_audio() {
|
||||
setup.audio = false;
|
||||
let reason = capture.audio_error().unwrap_or_default();
|
||||
@@ -660,6 +667,8 @@ impl App {
|
||||
(true, demo_viewers())
|
||||
} else {
|
||||
let session = session as u64;
|
||||
// One layer, whatever a studio stream had before.
|
||||
self.engine.send(Command::SetStreamLayers { session, layers: Vec::new() });
|
||||
self.engine.send(Command::StartStream { session, setup, auto_accept });
|
||||
(false, Vec::new())
|
||||
};
|
||||
|
||||
@@ -29,14 +29,14 @@ use voelin_core::media::voelin_media::mix::SourceHandle;
|
||||
use voelin_core::media::voelin_media::{VideoFrame, convert};
|
||||
use voelin_core::media::{
|
||||
AudioApps, AudioSourceSpec, AudioSourceStats, Latest, Streamer, StreamerConfigUpdate,
|
||||
StreamerStats, audio_apps, audio_source_specs, screen_sources,
|
||||
StreamerStats, audio_apps, audio_source_specs, auto_bitrate, screen_sources,
|
||||
};
|
||||
use voelin_core::settings::{
|
||||
AudioSourceKindSetting, AudioSourceSetting, Key, Kind, STREAM_AUDIO_SOURCES,
|
||||
STREAM_BITRATE_KBPS, STREAM_LAYERS, STUDIO_RECORDING_DIR, STUDIO_REPLAY_MEMORY_MB,
|
||||
STUDIO_REPLAY_SECONDS, STUDIO_SCENES, Settings, layer_specs,
|
||||
};
|
||||
use voelin_core::stream::{EndReason, StreamSetup, ViewerInfo, ViewerState};
|
||||
use voelin_core::stream::{EndReason, LayerSpec, StreamSetup, ViewerInfo, ViewerState};
|
||||
use voelin_core::studio::scene::{
|
||||
Align, Background, Colour, Crop, Fit, Scene, Scenes, Source, SourceKind, Transform,
|
||||
};
|
||||
@@ -436,6 +436,30 @@ impl App {
|
||||
self.studio.run.as_ref()?.streamer.as_ref()
|
||||
}
|
||||
|
||||
/// The stream's layers for the engine: `stream.layers`, or the single
|
||||
/// layer at [`studio_bitrate_kbps`](Self::studio_bitrate_kbps).
|
||||
fn studio_session_layers(&self, settings: &Settings) -> Vec<LayerSpec> {
|
||||
match layer_specs(&settings.get(&STREAM_LAYERS)) {
|
||||
layers if layers.is_empty() => {
|
||||
vec![LayerSpec::single(u64::from(self.studio_bitrate_kbps(settings)) * 1000)]
|
||||
}
|
||||
layers => layers,
|
||||
}
|
||||
}
|
||||
|
||||
/// `stream.bitrate_kbps`, an automatic one (0) as it comes to for the
|
||||
/// output's size and frame rate.
|
||||
fn studio_bitrate_kbps(&self, settings: &Settings) -> u32 {
|
||||
match settings.get(&STREAM_BITRATE_KBPS) {
|
||||
0 => {
|
||||
let (width, height) = self.studio.scenes.size();
|
||||
let bitrate = auto_bitrate(width, height, self.studio.scenes.fps());
|
||||
u32::try_from(bitrate / 1000).unwrap_or(u32::MAX)
|
||||
}
|
||||
kbps => kbps,
|
||||
}
|
||||
}
|
||||
|
||||
fn studio_op(&self, op: Op) {
|
||||
if let Some(run) = &self.studio.run {
|
||||
let _ = run.ops.send(op);
|
||||
@@ -960,7 +984,9 @@ impl App {
|
||||
.destination
|
||||
.and_then(|id| list.iter().position(|(d, _)| *d == id))
|
||||
.map_or(-1, |i| i as i32);
|
||||
// Automatic (0): the field stays empty and says so.
|
||||
let bitrate = self.studio.settings.as_ref().map_or(0, |s| s.get(&STREAM_BITRATE_KBPS));
|
||||
let bitrate = if bitrate == 0 { String::new() } else { bitrate.to_string() };
|
||||
let form = StudioForm {
|
||||
destination,
|
||||
title: ui.title.clone().into(),
|
||||
@@ -970,7 +996,7 @@ impl App {
|
||||
show_chat: ui.show_chat,
|
||||
show_now_playing: ui.show_now_playing,
|
||||
audio: ui.audio,
|
||||
bitrate: bitrate.to_string().into(),
|
||||
bitrate: bitrate.into(),
|
||||
};
|
||||
self.studio_each(|b| {
|
||||
if b.get_form() != form {
|
||||
@@ -993,7 +1019,7 @@ impl App {
|
||||
let measured: f64 = encoder.map_or(0.0, |e| e.layers.iter().map(|l| l.kbps).sum());
|
||||
let layers = settings.map(|s| s.get(&STREAM_LAYERS)).unwrap_or_default();
|
||||
let configured_bps: u64 = if layers.is_empty() {
|
||||
settings.map_or(0, |s| u64::from(s.get(&STREAM_BITRATE_KBPS)) * 1000)
|
||||
settings.map_or(0, |s| u64::from(self.studio_bitrate_kbps(s)) * 1000)
|
||||
} else {
|
||||
layers.iter().map(|l| l.bitrate).max().unwrap_or(0)
|
||||
};
|
||||
@@ -1191,6 +1217,11 @@ impl App {
|
||||
/// `stream.layers` or `stream.bitrate_kbps` changed.
|
||||
pub(crate) fn studio_encoding_changed(&mut self) {
|
||||
let settings = self.studio_settings();
|
||||
if let Some(stream) = &self.studio.stream {
|
||||
let session = stream.session as u64;
|
||||
let layers = self.studio_session_layers(&settings);
|
||||
self.engine.send(Command::SetStreamLayers { session, layers });
|
||||
}
|
||||
let update = StreamerConfigUpdate {
|
||||
bitrate_kbps: Some(settings.get(&STREAM_BITRATE_KBPS)),
|
||||
layers: Some(layer_specs(&settings.get(&STREAM_LAYERS))),
|
||||
@@ -1254,13 +1285,16 @@ impl App {
|
||||
"audio" => ui.audio = on,
|
||||
"bitrate" => {
|
||||
let settings = self.studio_settings();
|
||||
match parse_positive(value) {
|
||||
// Nothing, 0 or "auto": automatic.
|
||||
let auto =
|
||||
matches!(value.trim(), "" | "0") || value.trim().eq_ignore_ascii_case("auto");
|
||||
match parse_positive(value).or(auto.then_some(0)) {
|
||||
Some(kbps) => {
|
||||
if let Err(e) = settings.set(&STREAM_BITRATE_KBPS, kbps) {
|
||||
self.set_status(e.to_string());
|
||||
}
|
||||
}
|
||||
None => self.set_status("The bitrate is a whole number of kbit/s above 0."),
|
||||
None => self.set_status("The bitrate is a whole number of kbit/s, or auto."),
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -1328,7 +1362,7 @@ impl App {
|
||||
pub(crate) fn studio_add_layer(&mut self) {
|
||||
let settings = self.studio_settings();
|
||||
let mut layers = settings.get(&STREAM_LAYERS);
|
||||
let bitrate = settings.get(&STREAM_BITRATE_KBPS);
|
||||
let bitrate = self.studio_bitrate_kbps(&settings);
|
||||
if layers.is_empty() {
|
||||
layers.push(vm::studio::next_layer(&[], bitrate));
|
||||
}
|
||||
@@ -1897,7 +1931,7 @@ impl App {
|
||||
let layers = settings.get(&STREAM_LAYERS);
|
||||
let bitrate = match layers.iter().map(|l| l.bitrate).max() {
|
||||
Some(bps) => u32::try_from(bps / 1000).unwrap_or(u32::MAX),
|
||||
None => settings.get(&STREAM_BITRATE_KBPS),
|
||||
None => self.studio_bitrate_kbps(&settings),
|
||||
};
|
||||
let setup = StreamSetup {
|
||||
name: stream_name(&self.studio.ui),
|
||||
@@ -1906,7 +1940,12 @@ impl App {
|
||||
..StreamSetup::default()
|
||||
};
|
||||
let auto_accept = self.settings.share.auto_accept;
|
||||
self.engine.send(Command::StartStream { session: session as u64, setup, auto_accept });
|
||||
// The stream's layers are the encoder's, so viewers move between
|
||||
// them (the session sends only layers it knows of).
|
||||
let session = session as u64;
|
||||
let layers = self.studio_session_layers(&settings);
|
||||
self.engine.send(Command::SetStreamLayers { session, layers });
|
||||
self.engine.send(Command::StartStream { session, setup, auto_accept });
|
||||
self.studio_refresh_status();
|
||||
}
|
||||
|
||||
|
||||
@@ -270,13 +270,15 @@ export struct SourceItem {
|
||||
export struct ShareForm {
|
||||
source: int,
|
||||
name: string,
|
||||
// Index into the frame rate choices (15, 30, 60).
|
||||
// Index into the frame rate choices (15, 30, 60, 120, 144, 240, 320).
|
||||
fps-index: int,
|
||||
// Frames per second as typed; a choice fills it in. Any number above 0.
|
||||
fps: string,
|
||||
// Index into the bitrate choices (2.5, 4.6, 8, 10 Mbit/s).
|
||||
// Index into the bitrate choices (Auto, 2.5, 4.6, 8, 10, 20, 40, 60
|
||||
// Mbit/s).
|
||||
bitrate-index: int,
|
||||
// Video bitrate in kbit/s as typed; a choice fills it in.
|
||||
// Video bitrate in kbit/s as typed; a choice fills it in. Empty with
|
||||
// Auto: from the size and frame rate shared, up to 60 Mbit/s.
|
||||
bitrate: string,
|
||||
audio: bool,
|
||||
auto-accept: bool,
|
||||
|
||||
@@ -391,10 +391,11 @@ component ShareCard inherits Modal {
|
||||
HorizontalLayout {
|
||||
spacing: Theme.space-2;
|
||||
Select {
|
||||
model: [@tr("15 fps"), @tr("30 fps"), @tr("60 fps")];
|
||||
// FPS_CHOICES (settings.rs).
|
||||
model: [@tr("15 fps"), @tr("30 fps"), @tr("60 fps"), @tr("120 fps"), @tr("144 fps"), @tr("240 fps"), @tr("320 fps")];
|
||||
current-index <=> form.fps-index;
|
||||
label: @tr("Frame rate");
|
||||
selected => { form.fps = [15, 30, 60][self.current-index]; }
|
||||
selected => { form.fps = [15, 30, 60, 120, 144, 240, 320][self.current-index]; }
|
||||
}
|
||||
TextField {
|
||||
text <=> form.fps;
|
||||
@@ -412,15 +413,16 @@ component ShareCard inherits Modal {
|
||||
HorizontalLayout {
|
||||
spacing: Theme.space-2;
|
||||
Select {
|
||||
model: [@tr("Low (2.5 Mbit/s)"), @tr("Standard (4.6 Mbit/s)"), @tr("High (8 Mbit/s)"), @tr("Best (10 Mbit/s)")];
|
||||
// BITRATE_CHOICES (settings.rs); Auto leaves the field empty.
|
||||
model: [@tr("Auto (up to 60 Mbit/s)"), @tr("Low (2.5 Mbit/s)"), @tr("Standard (4.6 Mbit/s)"), @tr("High (8 Mbit/s)"), @tr("10 Mbit/s"), @tr("20 Mbit/s"), @tr("40 Mbit/s"), @tr("Best (60 Mbit/s)")];
|
||||
current-index <=> form.bitrate-index;
|
||||
label: @tr("Quality");
|
||||
selected => { form.bitrate = [2500, 4608, 8000, 10000][self.current-index]; }
|
||||
selected => { form.bitrate = self.current-index == 0 ? "" : "\{[0, 2500, 4608, 8000, 10000, 20000, 40000, 60000][self.current-index]}"; }
|
||||
}
|
||||
TextField {
|
||||
text <=> form.bitrate;
|
||||
input-type: number;
|
||||
placeholder: @tr("kbit/s");
|
||||
placeholder: form.bitrate-index == 0 ? @tr("auto") : @tr("kbit/s");
|
||||
label: @tr("Bitrate in kbit/s");
|
||||
// On a phone both pairs fit side by side.
|
||||
width: Nav.narrow ? 60px : 80px;
|
||||
|
||||
@@ -620,7 +620,7 @@ export component StreamingSection inherits VerticalLayout {
|
||||
}
|
||||
NumberRow {
|
||||
text: @tr("Video bitrate");
|
||||
description: @tr("Of the single layer, when no layers are set below.");
|
||||
description: @tr("Of the single layer, when no layers are set below. 0: automatic, from the size and frame rate, up to 60 Mbit/s.");
|
||||
value: Bridge.streaming.bitrate;
|
||||
unit: "kbit/s";
|
||||
accepted(t) => {
|
||||
|
||||
@@ -411,11 +411,11 @@ component VideoCard inherits Card {
|
||||
Field {
|
||||
label: @tr("Frame Rate");
|
||||
Select {
|
||||
model: ["15 FPS", "24 FPS", "30 FPS", "60 FPS", "120 FPS"];
|
||||
current-index: Bridge.video.fps == "15" ? 0 : Bridge.video.fps == "24" ? 1 : Bridge.video.fps == "30" ? 2 : Bridge.video.fps == "120" ? 4 : 3;
|
||||
model: ["15 FPS", "24 FPS", "30 FPS", "60 FPS", "120 FPS", "144 FPS", "240 FPS", "320 FPS"];
|
||||
current-index: Bridge.video.fps == "15" ? 0 : Bridge.video.fps == "24" ? 1 : Bridge.video.fps == "30" ? 2 : Bridge.video.fps == "120" ? 4 : Bridge.video.fps == "144" ? 5 : Bridge.video.fps == "240" ? 6 : Bridge.video.fps == "320" ? 7 : 3;
|
||||
label: @tr("Frame rate");
|
||||
selected => {
|
||||
Bridge.video.fps = self.current-index == 0 ? "15" : self.current-index == 1 ? "24" : self.current-index == 2 ? "30" : self.current-index == 4 ? "120" : "60";
|
||||
Bridge.video.fps = ["15", "24", "30", "60", "120", "144", "240", "320"][self.current-index];
|
||||
Bridge.video-changed(Bridge.video);
|
||||
}
|
||||
}
|
||||
@@ -544,6 +544,24 @@ component QualityCard inherits Card {
|
||||
Bridge.video-changed(Bridge.video);
|
||||
}
|
||||
}
|
||||
PresetTile {
|
||||
text: "4K";
|
||||
detail: "2160p";
|
||||
selected: Bridge.video.quality == 4;
|
||||
clicked => {
|
||||
Bridge.video.quality = 4;
|
||||
Bridge.video-changed(Bridge.video);
|
||||
}
|
||||
}
|
||||
PresetTile {
|
||||
text: "8K";
|
||||
detail: "4320p";
|
||||
selected: Bridge.video.quality == 5;
|
||||
clicked => {
|
||||
Bridge.video.quality = 5;
|
||||
Bridge.video-changed(Bridge.video);
|
||||
}
|
||||
}
|
||||
}
|
||||
if Bridge.video.quality < 0: Text {
|
||||
text: @tr("Your own simulcast layers are set (Streaming page); a preset replaces them.");
|
||||
@@ -562,7 +580,8 @@ component QualityCard inherits Card {
|
||||
y: (parent.height - self.height) / 2;
|
||||
horizontal-stretch: 1;
|
||||
minimum: 500;
|
||||
maximum: 20000;
|
||||
// 60 Mbit/s; any number can be typed, and 0 is automatic.
|
||||
maximum: 60000;
|
||||
step: 250;
|
||||
value: Bridge.video.bitrate;
|
||||
label: @tr("Stream bitrate");
|
||||
@@ -573,12 +592,14 @@ component QualityCard inherits Card {
|
||||
}
|
||||
TextField {
|
||||
width: 80px;
|
||||
text: round(Bridge.video.bitrate);
|
||||
// Empty: automatic (from the size and frame rate, up to 60 Mbit/s).
|
||||
text: Bridge.video.bitrate == 0 ? "" : round(Bridge.video.bitrate);
|
||||
placeholder: @tr("auto");
|
||||
input-type: number;
|
||||
label: @tr("Stream bitrate in kbit/s");
|
||||
accepted(t) => {
|
||||
if t.is-float() && t.to-float() >= 1 {
|
||||
Bridge.video.bitrate = t.to-float();
|
||||
if t == "" || (t.is-float() && t.to-float() >= 0) {
|
||||
Bridge.video.bitrate = t == "" ? 0 : t.to-float();
|
||||
Bridge.video-changed(Bridge.video);
|
||||
}
|
||||
}
|
||||
@@ -598,7 +619,9 @@ component QualityCard inherits Card {
|
||||
y: (parent.height - self.height) / 2;
|
||||
}
|
||||
Text {
|
||||
text: @tr("Estimated Upload Usage: ~{} GB per hour", round(Bridge.video.bitrate * 3600 / 8 / 100000) / 10);
|
||||
text: Bridge.video.bitrate == 0
|
||||
? @tr("Automatic: from the size and frame rate, up to 60 Mbit/s (~27 GB per hour)")
|
||||
: @tr("Estimated Upload Usage: ~{} GB per hour", round(Bridge.video.bitrate * 3600 / 8 / 100000) / 10);
|
||||
color: Theme.text-muted;
|
||||
font-size: Theme.font-sm;
|
||||
}
|
||||
|
||||
@@ -1459,40 +1459,28 @@ export component StreamSettings inherits VerticalLayout {
|
||||
}
|
||||
HorizontalLayout {
|
||||
spacing: Theme.space-2;
|
||||
Button {
|
||||
for size in [
|
||||
{ text: "720p", width: "1280", height: 720 },
|
||||
{ text: "1080p", width: "1920", height: 1080 },
|
||||
{ text: "1440p", width: "2560", height: 1440 },
|
||||
{ text: "4K", width: "3840", height: 2160 },
|
||||
{ text: "8K", width: "7680", height: 4320 },
|
||||
]: Button {
|
||||
small: true;
|
||||
text: "720p";
|
||||
text: size.text;
|
||||
horizontal-stretch: 1;
|
||||
checked: StudioBridge.status.output-height == 720;
|
||||
clicked => { StudioBridge.set-output("1280", "720", out-fps.text); }
|
||||
checked: StudioBridge.status.output-height == size.height;
|
||||
clicked => { StudioBridge.set-output(size.width, "\{size.height}", out-fps.text); }
|
||||
}
|
||||
Button {
|
||||
}
|
||||
HorizontalLayout {
|
||||
spacing: Theme.space-2;
|
||||
for fps in [30, 60, 120, 144, 240] : Button {
|
||||
small: true;
|
||||
text: "1080p";
|
||||
text: "\{fps}";
|
||||
horizontal-stretch: 1;
|
||||
checked: StudioBridge.status.output-height == 1080;
|
||||
clicked => { StudioBridge.set-output("1920", "1080", out-fps.text); }
|
||||
}
|
||||
Button {
|
||||
small: true;
|
||||
text: "1440p";
|
||||
horizontal-stretch: 1;
|
||||
checked: StudioBridge.status.output-height == 1440;
|
||||
clicked => { StudioBridge.set-output("2560", "1440", out-fps.text); }
|
||||
}
|
||||
Button {
|
||||
small: true;
|
||||
text: "30";
|
||||
horizontal-stretch: 1;
|
||||
checked: StudioBridge.status.fps == 30;
|
||||
clicked => { StudioBridge.set-output(out-w.text, out-h.text, "30"); }
|
||||
}
|
||||
Button {
|
||||
small: true;
|
||||
text: "60";
|
||||
horizontal-stretch: 1;
|
||||
checked: StudioBridge.status.fps == 60;
|
||||
clicked => { StudioBridge.set-output(out-w.text, out-h.text, "60"); }
|
||||
checked: StudioBridge.status.fps == fps;
|
||||
clicked => { StudioBridge.set-output(out-w.text, out-h.text, "\{fps}"); }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1502,6 +1490,8 @@ export component StreamSettings inherits VerticalLayout {
|
||||
if StudioBridge.layers.length == 0: TextField {
|
||||
text: StudioBridge.form.bitrate;
|
||||
input-type: number;
|
||||
// Empty: automatic, from the output's size and frame rate.
|
||||
placeholder: @tr("Auto (up to 60 Mbit/s)");
|
||||
label: @tr("Bitrate in kbit/s");
|
||||
accepted(t) => { StudioBridge.edit-form("bitrate", t); }
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user