Merge the Stream Studio UI

Both sides kept: the studio page and the new home, friends, messages,
events and settings pages in the Page enum, app.slint, the phone's top
bar (studio, search, bell), bind/ and vm/ modules, dev.rs switches. The
layers icon and Video::codecs were added on both sides; one of each is
kept.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
selikhovandClaude Opus 5.5 committed 2026-10-03 12:17:41 +03:00
commit bea6b335fa
52 files changed
+8115 -486

No files matched your search

+344 -28
View File
@@ -45,7 +45,7 @@ pub use voelin_media::capture::playback::{AppMatch, AudioApp, AudioApps};
pub use voelin_media::capture::synthetic::Pattern;
use voelin_media::capture::synthetic::{SineSource, SyntheticScreen};
use voelin_media::capture::{
self, CaptureOptions, CaptureSource, FramePacer, FrameSink, ScreenCapture, SourceId,
self, CaptureOptions, CaptureSource, DmaBufRef, FramePacer, FrameSink, ScreenCapture, SourceId,
};
use voelin_media::handoff::Handoff;
use voelin_media::mix::{
@@ -55,7 +55,10 @@ pub use voelin_media::mix::{Level, SourceState};
use voelin_media::scale::Pyramid;
use voelin_media::studio::Studio;
use voelin_media::studio::output::{Packet, Track};
use voelin_media::{Codec, Codecs, ContentHint, EncoderConfig, FrameRef, VideoEncoder, VideoFrame};
use voelin_media::{
Codec, Codecs, ContentHint, EncodedChunk, EncoderConfig, FrameRef, GpuFrame, VideoEncoder,
VideoFrame,
};
pub use voelin_media::{EncoderBackend, EncoderPreference};
use voelin_stream::{
EncodedFrame, FrameSource, Frequency, LayerId, LayerSet, LayerSpec, MediaFrame, MediaKind,
@@ -502,6 +505,11 @@ pub struct StreamerConfig {
pub synthetic_size: (u32, u32),
/// What the test pattern shows.
pub synthetic_pattern: Pattern,
/// Hand the test pattern over as DMA-BUFs of ordinary memory, as the
/// ScreenCast portal hands over the screen
/// ([`SyntheticScreen::with_dmabuf`]): drives the GPU path without a
/// portal (Linux, `/dev/udmabuf`).
pub synthetic_dmabuf: 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>,
@@ -524,6 +532,7 @@ impl Default for StreamerConfig {
cursor: true,
synthetic_size: (1280, 720),
synthetic_pattern: Pattern::Simple,
synthetic_dmabuf: false,
restore_token: None,
layers: Vec::new(),
}
@@ -612,8 +621,16 @@ pub struct StreamerStats {
pub captured_frames: u64,
pub capture_fps: f64,
/// Mean time to convert a captured frame to I420 and scale it for every
/// layer that is due.
/// 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.
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).
pub gpu_convert_time: Duration,
/// Why the GPU path stopped (it fell back to the CPU), if it did.
pub gpu_error: Option<String>,
/// Frames dropped between conversion and the encoders, all layers.
pub dropped_frames: u64,
/// Threads converting and scaling.
@@ -636,6 +653,12 @@ struct Layer {
spec: Mutex<LayerSpec>,
/// Newest converted frame for the encoder.
inbox: Handoff<VideoFrame>,
/// Newest frame converted on the GPU, instead.
gpu_inbox: Handoff<GpuFrame>,
/// What every encoder of the layer takes GPU frames at, written by the
/// encoder thread: `width << 32 | height` alignment, 0 if one of them
/// needs frames in memory.
gpu: AtomicU64,
/// A keyframe was asked for.
keyframe: AtomicBool,
stop: AtomicBool,
@@ -669,6 +692,8 @@ impl Layer {
id: spec.id,
spec: Mutex::new(spec.clone()),
inbox: Handoff::new(),
gpu_inbox: Handoff::new(),
gpu: AtomicU64::new(0),
keyframe: AtomicBool::new(false),
stop: AtomicBool::new(false),
bitrate: AtomicU64::new(spec.bitrate.max(1)),
@@ -731,6 +756,7 @@ impl Settings {
struct Rates {
capture_fps: f64,
convert_time: Duration,
gpu_convert_time: Duration,
/// Per layer: id, fps, kbit/s, encode time.
layers: Vec<(LayerId, f64, f64, Duration)>,
}
@@ -751,6 +777,10 @@ struct Shared {
converted: AtomicU64,
convert_ns: AtomicU64,
convert_threads: AtomicUsize,
/// Frames converted on the GPU instead, and the time it took.
gpu_converted: AtomicU64,
gpu_convert_ns: AtomicU64,
gpu_error: Mutex<Option<String>>,
/// The layers being encoded, in configuration order.
layers: Mutex<Vec<Arc<Layer>>>,
/// Bumped whenever `layers` or a layer's spec changes.
@@ -959,7 +989,8 @@ impl Streamer {
let (screen, restore_token): (Box<dyn ScreenCapture>, _) = match &config.source {
SourceId::Synthetic => {
let (w, h) = config.synthetic_size;
let mut screen = SyntheticScreen::with_pattern(w, h, config.synthetic_pattern);
let mut screen = SyntheticScreen::with_pattern(w, h, config.synthetic_pattern)
.with_dmabuf(config.synthetic_dmabuf);
screen.start_sink(&SourceId::Synthetic, &options, ingest).await?;
(Box::new(screen), None)
}
@@ -1220,6 +1251,9 @@ impl Streamer {
captured_frames: shared.captured.load(Ordering::Relaxed),
capture_fps: rates.capture_fps,
convert_time: rates.convert_time,
gpu_frames: shared.gpu_converted.load(Ordering::Relaxed),
gpu_convert_time: rates.gpu_convert_time,
gpu_error: lock(&shared.gpu_error).clone(),
dropped_frames: layers.iter().map(|l| l.dropped).sum(),
convert_threads: shared.convert_threads.load(Ordering::Relaxed),
codec,
@@ -1487,6 +1521,11 @@ struct IngestLayer {
/// converts and scales them for every layer that is due, and hands each
/// layer's frame to its encoder. Allocates nothing per frame once the
/// frame pools are warm.
///
/// Frames still in a DMA-BUF (the portal's) are converted and scaled on
/// the GPU instead when every encoder of every layer takes GPU frames
/// (VA-API): the CPU never reads them, and the buffer is free again as
/// soon as the GPU is done with it.
struct Ingest {
shared: Arc<Shared>,
pyramid: Pyramid,
@@ -1497,6 +1536,19 @@ struct Ingest {
sizes: Vec<(u32, u32)>,
due: Vec<bool>,
out: Vec<Option<Arc<VideoFrame>>>,
#[cfg(all(target_os = "linux", feature = "media-desktop"))]
gpu: GpuStage,
}
/// The GPU stage of [`Ingest`].
#[cfg(all(target_os = "linux", feature = "media-desktop"))]
#[derive(Default)]
struct GpuStage {
/// Made for the first DMA-BUF; `Err` once it failed (the CPU converts
/// from then on).
converter: Option<Result<voelin_media::ffmpeg::GpuConverter, ()>>,
layers: Vec<voelin_media::ffmpeg::GpuLayer>,
out: Vec<Option<Arc<GpuFrame>>>,
}
impl Ingest {
@@ -1514,9 +1566,98 @@ impl Ingest {
sizes: Vec::new(),
due: Vec::new(),
out: Vec::new(),
#[cfg(all(target_os = "linux", feature = "media-desktop"))]
gpu: GpuStage::default(),
}
}
/// Whether frames go to the GPU: every layer's encoders take GPU frames
/// and the GPU stage has not failed.
fn gpu_path(&self) -> bool {
#[cfg(all(target_os = "linux", feature = "media-desktop"))]
{
!matches!(self.gpu.converter, Some(Err(())))
&& !self.layers.is_empty()
&& self
.layers
.iter()
.all(|l| l.layer.stopped() || l.layer.gpu.load(Ordering::Relaxed) != 0)
}
#[cfg(not(all(target_os = "linux", feature = "media-desktop")))]
false
}
/// 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.pacer.keep(frame.timestamp);
shared.captured.fetch_add(1, Ordering::Relaxed);
shared
.size
.store(u64::from(frame.width) << 32 | u64::from(frame.height), Ordering::Relaxed);
if shared.sink().is_none() {
return Some(true);
}
let mut any = false;
self.gpu.layers.clear();
for l in &mut self.layers {
let due = !l.layer.stopped() && l.pacer.take(frame.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),
alignment: ((alignment >> 32) as u32, alignment as u32),
due,
});
}
if !any {
return Some(true);
}
self.gpu.out.clear();
self.gpu.out.resize(self.layers.len(), None);
let started = Instant::now();
if let Err(e) = converter.convert(frame, &self.gpu.layers, &mut self.gpu.out) {
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);
}
shared.gpu_convert_ns.fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed);
shared.gpu_converted.fetch_add(1, Ordering::Relaxed);
for (l, out) in self.layers.iter().zip(&mut self.gpu.out) {
if let Some(frame) = out.take() {
l.layer.gpu_inbox.put(frame);
}
}
Some(true)
}
/// Pick up layer and frame-rate changes.
fn refresh(&mut self) {
let fps = self.shared.fps.load(Ordering::Relaxed);
@@ -1560,14 +1701,38 @@ impl FrameSink for Ingest {
if self.shared.stopped() {
return false;
}
let fps = self.shared.fps.load(Ordering::Relaxed);
if fps != self.fps {
self.fps = fps;
self.pacer.set_fps(Some(fps));
}
// Also the layers, which `accepts_dmabuf` (asked next) looks at.
self.refresh();
self.pacer.due(timestamp)
}
fn accepts_dmabuf(&self) -> bool {
self.gpu_path()
}
/// The tiled layout the GPU's own RGB surfaces have, once the GPU stage
/// runs (its first DMA-BUF is LINEAR); none on the CPU path, which
/// cannot read tiled buffers.
fn dmabuf_modifiers(&self) -> &[u64] {
#[cfg(all(target_os = "linux", feature = "media-desktop"))]
if self.gpu_path()
&& let Some(Ok(converter)) = &self.gpu.converter
{
return converter.modifiers();
}
&[]
}
fn dmabuf(&mut self, frame: &DmaBufRef) -> Option<bool> {
#[cfg(all(target_os = "linux", feature = "media-desktop"))]
return self.gpu_frame(frame);
#[cfg(not(all(target_os = "linux", feature = "media-desktop")))]
{
let _ = frame;
None
}
}
fn frame(&mut self, frame: FrameRef<'_>) -> bool {
if self.shared.stopped() {
return false;
@@ -1617,6 +1782,66 @@ impl Drop for Ingest {
}
}
/// A layer's picture: in memory, or on the GPU (converted from a captured
/// DMA-BUF there).
#[derive(Clone)]
enum Picture {
Cpu(Arc<VideoFrame>),
Gpu(Arc<GpuFrame>),
}
impl Picture {
fn size(&self) -> (u32, u32) {
match self {
Self::Cpu(frame) => (frame.width, frame.height),
Self::Gpu(frame) => (frame.width, frame.height),
}
}
/// The same picture `later` after it was captured (a still screen sent
/// again; copies a frame in memory).
fn later(&self, later: Duration) -> Self {
match self {
Self::Cpu(frame) => {
let timestamp = frame.timestamp + later;
Self::Cpu(Arc::new((**frame).clone().with_timestamp(timestamp)))
}
Self::Gpu(frame) => Self::Gpu(Arc::new(frame.at(frame.timestamp + later))),
}
}
}
/// A layer's next picture, from either inbox, or `None` after [`POLL`] or
/// once the layer is closed. The encoder thread is registered with both
/// ([`Handoff::register`]), so a `put` to either wakes it.
fn next_picture(layer: &Layer) -> Option<Picture> {
let deadline = Instant::now() + POLL;
loop {
if let Some(frame) = layer.gpu_inbox.take() {
return Some(Picture::Gpu(frame));
}
if let Some(frame) = layer.inbox.take() {
return Some(Picture::Cpu(frame));
}
let now = Instant::now();
if now >= deadline || layer.inbox.is_closed() {
return None;
}
std::thread::park_timeout(deadline - now);
}
}
/// What every encoder of a layer takes GPU frames at, for [`Layer::gpu`]:
/// the largest alignment of them all, or 0 if one of them takes none.
fn gpu_alignment<'a>(encoders: impl IntoIterator<Item = &'a dyn VideoEncoder>) -> u64 {
let mut alignment = (2, 2);
for encoder in encoders {
let Some((w, h)) = encoder.gpu_alignment() else { return 0 };
alignment = (alignment.0.max(w), alignment.1.max(h));
}
u64::from(alignment.0) << 32 | u64::from(alignment.1)
}
/// One encoder of a layer: its keyframe and bitrate state.
struct LayerEncoder {
codec: Codec,
@@ -1635,7 +1860,7 @@ impl LayerEncoder {
Self { codec: encoder.codec(), encoder: Some(encoder), keyframe_due: true, bitrate: 0, fps }
}
/// Encode `frame` and hand the frames to `sink` (and `studio`'s
/// Encode `picture` and hand the frames to `sink` (and `studio`'s
/// outputs); follows the layer's target bitrate and frame rate first.
#[allow(clippy::too_many_arguments)]
fn encode(
@@ -1644,12 +1869,20 @@ impl LayerEncoder {
layer: &Layer,
sink: &dyn MediaSink,
studio: Option<&Studio>,
frame: &VideoFrame,
picture: &Picture,
requested: bool,
target: u64,
) {
let codec = self.codec;
let Some(encoder) = &mut self.encoder else { return };
if matches!(picture, Picture::Gpu(_)) && encoder.gpu_alignment().is_none() {
// The capture switches to frames in memory once it sees this
// encoder (made for a viewer just now); until then it waits, and
// its first frame then is a keyframe.
self.keyframe_due = true;
return;
}
let (width, height) = picture.size();
if target.abs_diff(self.bitrate) * 100 > self.bitrate {
match encoder.set_bitrate(target.min(u64::from(u32::MAX)) as u32) {
Ok(()) => self.bitrate = target,
@@ -1662,15 +1895,15 @@ impl LayerEncoder {
}
let force = requested || self.keyframe_due;
let mut produced_keyframe = false;
let result = encoder.encode_with(frame, force, &mut |chunk| {
let mut out = |chunk: EncodedChunk<'_>| {
produced_keyframe |= chunk.keyframe;
if let Some(studio) = studio {
studio.write_packet(&Packet {
track: Track::Video { codec, layer: u32::from(layer.id) },
pts_90khz: chunk.pts_90khz,
keyframe: chunk.keyframe,
width: frame.width,
height: frame.height,
width,
height,
data: chunk.data,
});
}
@@ -1688,7 +1921,11 @@ impl LayerEncoder {
layer.bytes.fetch_add(chunk.data.len() as u64, Ordering::Relaxed);
shared.video_frames.fetch_add(1, Ordering::Relaxed);
}
});
};
let result = match picture {
Picture::Cpu(frame) => encoder.encode_with(frame, force, &mut out),
Picture::Gpu(frame) => encoder.encode_gpu(frame, force, &mut out),
};
match result {
Ok(()) => self.keyframe_due = force && !produced_keyframe,
Err(e) => {
@@ -1736,13 +1973,17 @@ fn encode_loop(shared: &Shared, layer: &Layer, encoder: Box<dyn VideoEncoder>) {
let mut primary_on = true;
// 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<(Arc<VideoFrame>, Instant)> = None;
let mut last: Option<(Picture, Instant)> = None;
layer.speed.store(
primary.encoder.as_ref().and_then(|e| e.speed()).map_or(i64::MIN, i64::from),
Ordering::Relaxed,
);
// The capture may hand over GPU frames once every encoder takes them.
layer.inbox.register();
layer.gpu_inbox.register();
layer.gpu.store(gpu_alignment(primary.encoder.as_deref()), Ordering::Relaxed);
while !shared.stopped() && !layer.stopped() {
let frame = layer.inbox.wait_timeout(POLL);
let picture = next_picture(layer);
if let Some(next) = lock(&layer.next_encoder).take() {
// Another codec: its first frame is a keyframe anyway.
*lock(&layer.backend) = Some(next.backend());
@@ -1785,21 +2026,26 @@ fn encode_loop(shared: &Shared, layer: &Layer, encoder: Box<dyn VideoEncoder>) {
codecs.extend(primary_on.then_some(primary.codec));
codecs.extend(extra.iter().filter(|e| e.encoder.is_some()).map(|e| e.codec));
}
// The stream codec's encoder counts even while nobody takes it, so
// the capture does not switch paths as viewers come and go.
let encoders = primary.encoder.as_deref().into_iter();
let gpu = gpu_alignment(encoders.chain(extra.iter().filter_map(|e| e.encoder.as_deref())));
layer.gpu.store(gpu, Ordering::Relaxed);
let requested = layer.keyframe.swap(false, Ordering::Relaxed);
let due = primary_on && primary.keyframe_due
|| extra.iter().any(|e| e.keyframe_due && e.encoder.is_some());
let frame = match frame {
Some(frame) => {
last = Some((frame.clone(), Instant::now()));
frame
let picture = match picture {
Some(picture) => {
last = Some((picture.clone(), Instant::now()));
picture
}
None if requested || due => {
let Some((frame, at)) = &last else {
let Some((picture, at)) = &last else {
layer.keyframe.store(requested, Ordering::Relaxed);
continue;
};
// Same picture, later timestamp (rare: copies the frame).
Arc::new((**frame).clone().with_timestamp(frame.timestamp + at.elapsed()))
// Same picture, later timestamp (rare).
picture.later(at.elapsed())
}
None => continue,
};
@@ -1813,15 +2059,16 @@ fn encode_loop(shared: &Shared, layer: &Layer, encoder: Box<dyn VideoEncoder>) {
let started = Instant::now();
if primary_on {
let studio = shared.studio.as_deref();
primary.encode(shared, layer, &*sink, studio, &frame, requested, target);
primary.encode(shared, layer, &*sink, studio, &picture, requested, target);
layer.target.store(primary.bitrate, Ordering::Relaxed);
}
for encoder in &mut extra {
encoder.encode(shared, layer, &*sink, None, &frame, requested, target);
encoder.encode(shared, layer, &*sink, None, &picture, requested, target);
}
layer.encode_ns.fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed);
layer.encoded.fetch_add(1, Ordering::Relaxed);
layer.size.store(u64::from(frame.width) << 32 | u64::from(frame.height), Ordering::Relaxed);
let (width, height) = picture.size();
layer.size.store(u64::from(width) << 32 | u64::from(height), Ordering::Relaxed);
layer.speed.store(
primary.encoder.as_ref().and_then(|e| e.speed()).map_or(i64::MIN, i64::from),
Ordering::Relaxed,
@@ -1835,6 +2082,8 @@ struct Sample {
captured: u64,
converted: u64,
convert_ns: u64,
gpu_converted: u64,
gpu_convert_ns: u64,
}
/// Once a second: rates for [`Streamer::stats`]; every five seconds a
@@ -1861,11 +2110,15 @@ fn stats_loop(shared: &Shared) {
captured: shared.captured.load(Ordering::Relaxed),
converted: shared.converted.load(Ordering::Relaxed),
convert_ns: shared.convert_ns.load(Ordering::Relaxed),
gpu_converted: shared.gpu_converted.load(Ordering::Relaxed),
gpu_convert_ns: shared.gpu_convert_ns.load(Ordering::Relaxed),
};
let mean = |ns: u64, n: u64| Duration::from_nanos(ns.checked_div(n).unwrap_or(0));
let mut rates = lock(&shared.rates);
rates.capture_fps = (now.captured - last.captured) as f64 / secs;
rates.convert_time = mean(now.convert_ns - last.convert_ns, now.converted - last.converted);
rates.gpu_convert_time =
mean(now.gpu_convert_ns - last.gpu_convert_ns, now.gpu_converted - last.gpu_converted);
rates.layers.clear();
let layers = lock(&shared.layers);
for layer in layers.iter() {
@@ -1912,9 +2165,10 @@ fn stats_loop(shared: &Shared) {
})
.collect();
debug!(
"stream: capture {:.1} fps, convert {:.1} ms, {}",
"stream: capture {:.1} fps, convert {:.1} ms (GPU {:.1} ms), {}",
rates.capture_fps,
rates.convert_time.as_secs_f64() * 1e3,
rates.gpu_convert_time.as_secs_f64() * 1e3,
summary.join(", ")
);
}
@@ -2742,6 +2996,68 @@ mod tests {
(size, first_keyframe == Some(true))
}
/// The test pattern as DMA-BUFs, as the portal hands over the screen:
/// with VA-API encoders on every layer, each frame is converted and
/// scaled on the GPU and none on the CPU; after a switch to libvpx,
/// which needs frames in memory, the CPU converts them again and the
/// stream goes on. Skipped without `h264_vaapi` or `/dev/udmabuf`.
#[cfg(target_os = "linux")]
#[tokio::test(flavor = "multi_thread")]
async fn dmabufs_take_the_gpu_path_while_every_encoder_does() {
let vaapi = voelin_media::ffmpeg::probe()
.iter()
.any(|s| s.spec.name == "h264_vaapi" && s.available.is_ok());
if !vaapi || !std::path::Path::new("/dev/udmabuf").exists() {
eprintln!("no h264_vaapi or /dev/udmabuf, skipped");
return;
}
let codecs = Codecs::new();
let vaapi = EncoderPreference { hardware: true, backend: "h264_vaapi".parse().unwrap() };
let config = StreamerConfig {
source: SourceId::Synthetic,
synthetic_size: (640, 360),
synthetic_dmabuf: true,
fps: 30,
audio: false,
codec: Codec::H264,
encoder: vaapi,
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;
for id in [0, 5] {
assert!(frames.iter().find(|f| f.layer == id).unwrap().keyframe, "layer {id}");
}
let stats = source.streamer().stats();
assert_eq!(stats.gpu_error, None);
assert!(stats.gpu_frames >= 20, "{} frames on the GPU", stats.gpu_frames);
let on_cpu = stats.captured_frames - stats.gpu_frames;
assert!(on_cpu <= 1, "{on_cpu} of {} frames on the CPU", stats.captured_frames);
let sizes: Vec<_> = stats.layers.iter().map(|l| (l.width, l.height)).collect();
assert_eq!(sizes, [(640, 360), (320, 180)]);
let libvpx = EncoderPreference { hardware: false, backend: "libvpx".parse().unwrap() };
let update = StreamerConfigUpdate {
codec: Some(Codec::Vp8),
encoder: Some(libvpx),
..StreamerConfigUpdate::default()
};
source.streamer().reconfigure(&codecs, update).unwrap();
let gpu = source.streamer().stats().gpu_frames;
let frames = collect(&mut source, |f| count(f, 0) >= 40).await;
assert_eq!(decoded_size(Codec::Vp8, &frames, 0), ((640, 360), true));
let stats = source.streamer().stats();
assert!(
stats.gpu_frames <= gpu + 2,
"{} frames on the GPU after the switch",
stats.gpu_frames - gpu
);
assert_eq!(stats.gpu_error, None, "a planned switch, not a failure");
}
/// 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")]
+90 -2
View File
@@ -1,11 +1,13 @@
//! CPU access to LINEAR DMA-BUFs (screen capture buffers a compositor
//! shares): a read-only mapping, and `DMA_BUF_IOCTL_SYNC` around each read
//! so caches are coherent with what the GPU wrote. Tiled buffers cannot be
//! read like this; they need a GPU import (not done here).
//! read like this; they go to the GPU (`ffmpeg::GpuConverter`). Also
//! DMA-BUFs of ordinary memory ([`Udmabuf`]), to drive that path without a
//! compositor.
#![allow(unsafe_code)]
use std::io;
use std::os::fd::{BorrowedFd, RawFd};
use std::os::fd::{BorrowedFd, OwnedFd, RawFd};
use memmap2::{Mmap, MmapOptions};
@@ -21,6 +23,92 @@ const DMA_BUF_SYNC_END: u64 = 1 << 2;
/// `DMA_BUF_IOCTL_SYNC`: `_IOW('b', 0, struct dma_buf_sync)`.
const SYNC: rustix::ioctl::Opcode = rustix::ioctl::opcode::write::<DmaBufSync>(b'b', 0);
/// `struct udmabuf_create` of `<linux/udmabuf.h>`; `UDMABUF_CREATE` returns
/// the new DMA-BUF.
#[repr(C)]
struct UdmabufCreate {
memfd: u32,
flags: u32,
offset: u64,
size: u64,
}
/// `UDMABUF_FLAGS_CLOEXEC`.
const UDMABUF_CLOEXEC: u32 = 1;
// SAFETY: `UDMABUF_CREATE` (`_IOW('u', 0x42, struct udmabuf_create)`) only
// reads the struct and returns a new descriptor.
unsafe impl rustix::ioctl::Ioctl for UdmabufCreate {
type Output = OwnedFd;
const IS_MUTATING: bool = false;
fn opcode(&self) -> rustix::ioctl::Opcode {
rustix::ioctl::opcode::write::<UdmabufCreate>(b'u', 0x42)
}
fn as_ptr(&mut self) -> *mut std::ffi::c_void {
(&raw mut *self).cast()
}
unsafe fn output_from_ptr(
out: rustix::ioctl::IoctlOutput,
_: *mut std::ffi::c_void,
) -> rustix::io::Result<OwnedFd> {
// SAFETY: the descriptor the kernel just made, ours to own.
Ok(unsafe { std::os::fd::FromRawFd::from_raw_fd(out) })
}
}
/// A DMA-BUF of ordinary memory that the CPU writes into: a sealed memfd
/// shared through `/dev/udmabuf` (LINEAR rows, any pitch). What a
/// compositor that renders on the CPU hands over, and the way to drive the
/// DMA-BUF path without one (the test pattern's
/// [`with_dmabuf`](super::synthetic::SyntheticScreen::with_dmabuf)). Needs
/// read and write access to `/dev/udmabuf`.
pub(crate) struct Udmabuf {
map: memmap2::MmapMut,
dmabuf: OwnedFd,
}
impl Udmabuf {
/// A buffer of at least `len` bytes (whole pages).
pub fn new(len: usize) -> io::Result<Self> {
use rustix::fs::{MemfdFlags, SealFlags};
let len = len.max(1).next_multiple_of(4096);
let flags = MemfdFlags::CLOEXEC | MemfdFlags::ALLOW_SEALING;
let memfd = std::fs::File::from(rustix::fs::memfd_create("voelin-udmabuf", flags)?);
memfd.set_len(len as u64)?;
// udmabuf only takes memory that cannot shrink under it.
rustix::fs::fcntl_add_seals(&memfd, SealFlags::SHRINK)?;
let device = std::fs::OpenOptions::new().read(true).write(true).open("/dev/udmabuf")?;
let create = UdmabufCreate {
memfd: std::os::fd::AsRawFd::as_raw_fd(&memfd) as u32,
flags: UDMABUF_CLOEXEC,
offset: 0,
size: len as u64,
};
// SAFETY: see the `Ioctl` impl; `device` is /dev/udmabuf.
let dmabuf = unsafe { rustix::ioctl::ioctl(&device, create) }?;
// SAFETY: our own sealed memfd, which nothing else writes or
// truncates; the mapping keeps its pages after the file is closed.
let map = unsafe { memmap2::MmapOptions::new().len(len).map_mut(&memfd) }?;
Ok(Self { map, dmabuf })
}
pub fn fd(&self) -> RawFd {
std::os::fd::AsRawFd::as_raw_fd(&self.dmabuf)
}
pub fn len(&self) -> usize {
self.map.len()
}
pub fn bytes_mut(&mut self) -> &mut [u8] {
&mut self.map
}
}
/// The size of DMA-BUF `fd` in bytes (`lseek(fd, 0, SEEK_END)`, which a
/// DMA-BUF answers with its buffer object's size without moving anything).
pub(crate) fn size_of(fd: RawFd) -> Option<usize> {
+10 -1
View File
@@ -28,7 +28,7 @@ use crate::queue::{FrameReceiver, FrameSender, frame_channel};
use crate::{Error, Result};
#[cfg(all(target_os = "linux", feature = "pipewire"))]
mod dmabuf;
pub(crate) mod dmabuf;
pub mod external;
#[cfg(all(target_os = "linux", feature = "pipewire"))]
pub mod pipewire_audio;
@@ -129,6 +129,15 @@ pub trait FrameSink: Send {
let _ = frame;
None
}
/// Tiled DRM format modifiers of RGB buffers the sink takes now
/// ([`accepts_dmabuf`](Self::accepts_dmabuf)), best first; backends that
/// negotiate buffers (the portal) offer them ahead of LINEAR, and offer
/// again when this changes. The CPU cannot read tiled buffers, so a sink
/// lists only what it imports.
fn dmabuf_modifiers(&self) -> &[u64] {
&[]
}
}
/// `fourcc_code(a, b, c, d)` of `drm_fourcc.h`.
+77 -24
View File
@@ -288,6 +288,8 @@ struct VideoState {
fps: u32,
/// Offer DMA-BUFs.
dmabuf: bool,
/// The sink's tiled modifiers the offer was made with (ahead of LINEAR).
modifiers: Vec<u64>,
/// Mappings of the DMA-BUFs PipeWire cycles through.
maps: Vec<DmaBufMap>,
/// Time spent handing DMA-BUF frames to the sink, and how many.
@@ -315,12 +317,15 @@ fn video_stream(
let stream = pw::stream::StreamRc::new(core.clone(), "voelin-screen-capture", props)
.map_err(|e| format!("PipeWire stream: {e}"))?;
let fps = sink.max_fps().max(1);
let modifiers = sink.dmabuf_modifiers().to_vec();
let formats = enum_formats(fps, dmabuf, &modifiers)?;
let state = VideoState {
sink,
format: None,
started: Instant::now(),
fps,
dmabuf,
modifiers,
maps: Vec::new(),
dmabuf_time: Duration::ZERO,
dmabuf_frames: 0,
@@ -359,7 +364,6 @@ fn video_stream(
.register()
.map_err(|e| format!("PipeWire listener: {e}"))?;
let formats = enum_formats(fps, dmabuf)?;
let mut pods = formats.iter().map(|f| pod(f)).collect::<std::result::Result<Vec<_>, _>>()?;
stream
.connect(
@@ -397,15 +401,24 @@ fn framerate_range(fps: u32) -> Property {
)
}
fn modifier_property(fixed: bool) -> Property {
/// The modifiers we take, best first: the sink's tiled ones, then LINEAR,
/// which the CPU can always read.
fn our_modifiers(tiled: &[u64]) -> Vec<i64> {
tiled.iter().map(|&m| m as i64).chain([MODIFIER_LINEAR]).collect()
}
/// The modifier property of a DMA-BUF format: a choice of `modifiers` the
/// producer must not fixate (we pick, see [`format_changed`]), or one fixed
/// modifier.
fn modifier_property(modifiers: &[i64], fixed: bool) -> Property {
let flags = pw::spa::sys::SPA_POD_PROP_FLAG_MANDATORY
| if fixed { 0 } else { pw::spa::sys::SPA_POD_PROP_FLAG_DONT_FIXATE };
let value = if fixed {
Value::Long(MODIFIER_LINEAR)
Value::Long(modifiers[0])
} else {
Value::Choice(ChoiceValue::Long(Choice(
ChoiceFlags::empty(),
ChoiceEnum::Enum { default: MODIFIER_LINEAR, alternatives: vec![MODIFIER_LINEAR] },
ChoiceEnum::Enum { default: modifiers[0], alternatives: modifiers.to_vec() },
)))
};
Property {
@@ -415,6 +428,19 @@ fn modifier_property(fixed: bool) -> Property {
}
}
/// The modifiers a producer's modifier property leaves to choose from.
fn offered_modifiers(prop: &pw::spa::pod::PodProp) -> Vec<i64> {
use pw::spa::pod::deserialize::PodDeserializer;
match PodDeserializer::deserialize_any_from(prop.value().as_bytes()).map(|(_, v)| v) {
Ok(Value::Long(m)) => vec![m],
Ok(Value::Choice(ChoiceValue::Long(Choice(
_,
ChoiceEnum::Enum { default, alternatives },
)))) => std::iter::once(default).chain(alternatives).collect(),
_ => Vec::new(),
}
}
fn format_object(properties: Vec<Property>) -> Value {
Value::Object(Object {
type_: SpaTypes::ObjectParamFormat.as_raw(),
@@ -423,9 +449,15 @@ fn format_object(properties: Vec<Property>) -> Value {
})
}
/// The formats we offer: each pixel format as a LINEAR DMA-BUF (if
/// `dmabuf`), then all of them in shared memory.
fn enum_formats(fps: u32, dmabuf: bool) -> std::result::Result<Vec<Vec<u8>>, String> {
/// The formats we offer: each pixel format as a DMA-BUF (if `dmabuf`) with
/// the sink's tiled modifiers ahead of LINEAR, then all of them in shared
/// memory.
fn enum_formats(
fps: u32,
dmabuf: bool,
tiled: &[u64],
) -> std::result::Result<Vec<Vec<u8>>, String> {
let modifiers = our_modifiers(tiled);
let mut formats = Vec::new();
let base = || {
vec![
@@ -437,7 +469,7 @@ fn enum_formats(fps: u32, dmabuf: bool) -> std::result::Result<Vec<Vec<u8>>, Str
for format in FORMATS {
let mut properties = base();
properties.push(property!(FormatProperties::VideoFormat, Id, format));
properties.push(modifier_property(false));
properties.push(modifier_property(&modifiers, false));
properties.push(size_range());
properties.push(framerate_range(fps));
formats.push(serialize(format_object(properties))?);
@@ -461,10 +493,10 @@ fn enum_formats(fps: u32, dmabuf: bool) -> std::result::Result<Vec<Vec<u8>>, Str
Ok(formats)
}
/// Offer formats again (another frame rate, or no DMA-BUFs); PipeWire
/// renegotiates.
fn renegotiate(stream: &pw::stream::Stream, fps: u32, dmabuf: bool) {
let result = enum_formats(fps, dmabuf).and_then(|formats| {
/// Offer formats again (another frame rate, other modifiers, or no
/// DMA-BUFs); PipeWire renegotiates.
fn renegotiate(stream: &pw::stream::Stream, state: &VideoState) {
let result = enum_formats(state.fps, state.dmabuf, &state.modifiers).and_then(|formats| {
let mut pods =
formats.iter().map(|f| pod(f)).collect::<std::result::Result<Vec<_>, _>>()?;
stream.update_params(&mut pods).map_err(|e| e.to_string())
@@ -494,12 +526,17 @@ fn format_changed(
.and_then(|o| o.find_prop(Id(FormatProperties::VideoModifier.as_raw())));
let modifier = match modifier {
Some(prop) if prop.flags().contains(PodPropFlags::DONT_FIXATE) => {
// The producer left the choice to us; we only take LINEAR.
// The producer left the choice to us: the best of ours that it
// can make, else LINEAR.
let theirs = offered_modifiers(prop);
let ours = our_modifiers(&state.modifiers);
let chosen = ours.into_iter().find(|m| theirs.contains(m)).unwrap_or(MODIFIER_LINEAR);
debug!(offered = ?theirs, chosen, "screen capture modifier");
let mut properties = vec![
property!(FormatProperties::MediaType, Id, MediaType::Video),
property!(FormatProperties::MediaSubtype, Id, MediaSubtype::Raw),
property!(FormatProperties::VideoFormat, Id, info.format()),
modifier_property(true),
modifier_property(&[chosen], true),
property!(
FormatProperties::VideoSize,
Rectangle,
@@ -539,16 +576,20 @@ fn format_changed(
}
fn process(stream: &pw::stream::Stream, state: &mut VideoState) {
// Follow the sink's frame rate: ask the compositor for another rate.
// Follow the sink: ask the compositor for another rate, or buffers with
// the modifiers the sink takes now.
let fps = state.sink.max_fps().max(1);
if fps != state.fps {
let modifiers = state.sink.dmabuf_modifiers();
if fps != state.fps || (state.dmabuf && modifiers != state.modifiers.as_slice()) {
state.fps = fps;
renegotiate(stream, fps, state.dmabuf);
state.modifiers = modifiers.to_vec();
renegotiate(stream, state);
}
let Some(mut buffer) = stream.dequeue_buffer() else { return };
let Some(format) = state.format else { return };
if format.modifier.is_some_and(|m| m != MODIFIER_LINEAR) && !state.sink.accepts_dmabuf() {
// Tiled: the CPU cannot read it (we only offer LINEAR).
// Tiled, and the sink no longer imports it: the CPU cannot read it.
// The new offer (above) brings LINEAR buffers.
return;
}
let timestamp = state.started.elapsed();
@@ -661,7 +702,7 @@ fn process(stream: &pw::stream::Stream, state: &mut VideoState) {
"screen capture DMA-BUFs cannot be mapped; switching to shared memory"
);
state.dmabuf = false;
renegotiate(stream, state.fps, false);
renegotiate(stream, state);
}
return;
}
@@ -718,7 +759,7 @@ fn probe_dmabuf(
"reading DMA-BUFs takes {per_pixel:.1} ns per pixel; switching screen capture to shared memory"
);
state.dmabuf = false;
renegotiate(stream, state.fps, false);
renegotiate(stream, state);
}
}
@@ -748,20 +789,32 @@ mod tests {
/// left to us to fixate) per pixel format, then shared memory.
#[test]
fn offered_formats() {
let formats = enum_formats(60, true).unwrap();
// A sink that imports one tiled modifier (an AMD one here).
const TILED: u64 = 0x0200_0000_28a0_1f04;
let formats = enum_formats(60, true, &[TILED]).unwrap();
assert_eq!(formats.len(), FORMATS.len() + 1);
for (i, bytes) in formats.iter().enumerate() {
let object = pod(bytes).unwrap().as_object().unwrap();
let modifier = object.find_prop(Id(FormatProperties::VideoModifier.as_raw()));
if i < FORMATS.len() {
let flags = modifier.expect("a modifier").flags();
let modifier = modifier.expect("a modifier");
let flags = modifier.flags();
assert!(flags.contains(PodPropFlags::MANDATORY | PodPropFlags::DONT_FIXATE));
// Read back as a producer's choice is: ours first, LINEAR last.
let offered = offered_modifiers(modifier);
assert_eq!(offered.first(), Some(&(TILED as i64)));
assert_eq!(offered.last(), Some(&MODIFIER_LINEAR));
} else {
assert!(modifier.is_none(), "shared memory has no modifier");
}
}
assert_eq!(enum_formats(30, false).unwrap().len(), 1);
let fixed = serialize(format_object(vec![modifier_property(true)])).unwrap();
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();
assert_eq!(offered_modifiers(prop), [MODIFIER_LINEAR, MODIFIER_LINEAR]);
assert_eq!(enum_formats(30, false, &[TILED]).unwrap().len(), 1);
let fixed =
serialize(format_object(vec![modifier_property(&[MODIFIER_LINEAR], true)])).unwrap();
let object = pod(&fixed).unwrap().as_object().unwrap();
let prop = object.find_prop(Id(FormatProperties::VideoModifier.as_raw())).unwrap();
assert_eq!(prop.value().get_long().unwrap(), MODIFIER_LINEAR);
+150 -10
View File
@@ -6,8 +6,8 @@ use std::sync::Arc;
use std::time::{Duration, Instant};
use crate::capture::{
AudioCapture, BoxFuture, CaptureOptions, CaptureSource, FrameSink, QueueSink, ScreenCapture,
SourceId, Ticker, Worker,
AudioCapture, BoxFuture, CaptureOptions, CaptureSource, DmaBufRef, FrameSink, QueueSink,
ScreenCapture, SourceId, Ticker, Worker,
};
use crate::frame::{AUDIO_SAMPLE_RATE, AudioBuffer, FrameRef, PixelsRef, PlaneRef, VideoFrame};
use crate::queue::{FrameReceiver, frame_channel};
@@ -224,6 +224,7 @@ pub struct SyntheticScreen {
pattern: Pattern,
desktop: Option<Arc<Desktop>>,
worker: Option<Worker>,
dmabuf: bool,
}
impl SyntheticScreen {
@@ -236,7 +237,18 @@ 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 }
Self { width, height, pattern, desktop, worker: None, dmabuf: false }
}
/// Draw into a DMA-BUF of ordinary memory and offer it to sinks that
/// take DMA-BUFs ([`FrameSink::accepts_dmabuf`]) as a LINEAR `XR24`
/// buffer, as the ScreenCast portal does; sinks that do not, or decline
/// it, get the same memory as a frame. Linux with the `pipewire`
/// feature and access to `/dev/udmabuf`; elsewhere frames are handed
/// over as before.
pub fn with_dmabuf(mut self, enabled: bool) -> Self {
self.dmabuf = enabled;
self
}
pub fn pattern(&self) -> Pattern {
@@ -251,6 +263,7 @@ impl SyntheticScreen {
pattern: self.pattern,
desktop: self.desktop.clone(),
worker: None,
dmabuf: self.dmabuf,
}
}
@@ -268,8 +281,15 @@ impl SyntheticScreen {
/// Draw frame `n` as BGRA (`width * 4` bytes per row) into `out`, reusing
/// 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);
}
/// [`render`](Self::render) into the first `width * height * 4` bytes of
/// `out`.
fn draw(&self, n: u64, out: &mut [u8]) {
let (w, h) = (self.width as usize, self.height as usize);
out.resize(w * h * 4, 0);
let out = &mut out[..w * h * 4];
match &self.desktop {
Some(desktop) => desktop.draw(out, w, n as usize * 3),
None => {
@@ -349,17 +369,28 @@ impl ScreenCapture for SyntheticScreen {
let (width, height) = (pattern.width, pattern.height);
let mut fps = sink.max_fps();
let mut ticker = Ticker::new(fps);
let mut buffer = Vec::new();
let mut buffer = Buffer::new(&pattern);
let started = Instant::now();
let mut n = 0;
loop {
let timestamp = started.elapsed();
if sink.wants(timestamp) {
pattern.render(n, &mut buffer);
let plane = PlaneRef::new(&buffer, width as usize * 4);
let frame =
FrameRef { width, height, timestamp, pixels: PixelsRef::Bgra(plane) };
if !sink.frame(frame) {
let bytes = buffer.bytes();
pattern.draw(n, bytes);
let taken = match buffer.dmabuf(&pattern, timestamp) {
Some(frame) if sink.accepts_dmabuf() => sink.dmabuf(&frame),
_ => None,
};
let more = taken.unwrap_or_else(|| {
let plane = PlaneRef::new(buffer.bytes(), width as usize * 4);
sink.frame(FrameRef {
width,
height,
timestamp,
pixels: PixelsRef::Bgra(plane),
})
});
if !more {
break;
}
n += 1;
@@ -382,6 +413,58 @@ impl ScreenCapture for SyntheticScreen {
}
}
/// Where the test pattern is drawn: plain memory, or a DMA-BUF of ordinary
/// memory ([`SyntheticScreen::with_dmabuf`]).
enum Buffer {
Memory(Vec<u8>),
#[cfg(all(target_os = "linux", feature = "pipewire"))]
Dmabuf(super::dmabuf::Udmabuf),
}
impl Buffer {
fn new(pattern: &SyntheticScreen) -> Self {
let len = pattern.width as usize * pattern.height as usize * 4;
#[cfg(all(target_os = "linux", feature = "pipewire"))]
if pattern.dmabuf {
match super::dmabuf::Udmabuf::new(len) {
Ok(buffer) => return Self::Dmabuf(buffer),
Err(e) => tracing::warn!("test pattern without DMA-BUFs (/dev/udmabuf): {e}"),
}
}
Self::Memory(vec![0; len])
}
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(),
}
}
/// The buffer as a LINEAR `XR24` DMA-BUF, if it is one.
fn dmabuf(&self, pattern: &SyntheticScreen, timestamp: Duration) -> Option<DmaBufRef> {
match self {
Self::Memory(_) => {
let _ = (pattern, timestamp);
None
}
#[cfg(all(target_os = "linux", feature = "pipewire"))]
Self::Dmabuf(buffer) => Some(DmaBufRef {
width: pattern.width,
height: pattern.height,
timestamp,
fourcc: super::drm_fourcc(b"XR24"),
modifier: super::DRM_MOD_LINEAR,
fd: buffer.fd(),
size: buffer.len(),
planes: [(0, pattern.width as usize * 4), (0, 0), (0, 0), (0, 0)],
plane_count: 1,
}),
}
}
}
/// A sine tone as an [`AudioCapture`] backend: 10 ms stereo buffers.
pub struct SineSource {
frequency: f32,
@@ -523,4 +606,61 @@ mod tests {
assert_eq!((buffer.channels, buffer.frames()), (2, 480));
tone.stop();
}
/// With DMA-BUFs, a sink that takes them gets the pattern as a LINEAR
/// `XR24` DMA-BUF that reads back as the pattern; one that declines it
/// gets the same picture as a frame.
#[cfg(all(target_os = "linux", feature = "pipewire"))]
#[tokio::test]
async fn the_pattern_as_dmabufs() {
use std::sync::mpsc;
/// Takes DMA-BUFs (or declines them) and reports what it got.
struct Sink {
take: bool,
got: mpsc::Sender<(bool, Vec<u8>)>,
}
impl FrameSink for Sink {
fn max_fps(&self) -> u32 {
50
}
fn frame(&mut self, frame: FrameRef<'_>) -> bool {
let PixelsRef::Bgra(plane) = frame.pixels else { panic!("BGRA") };
self.got.send((false, plane.row(0, 64 * 4).to_vec())).is_ok()
}
fn accepts_dmabuf(&self) -> bool {
true
}
fn dmabuf(&mut self, frame: &DmaBufRef) -> Option<bool> {
assert_eq!(frame.fourcc, crate::capture::drm_fourcc(b"XR24"));
assert_eq!((frame.width, frame.height, frame.planes[0].1), (64, 48, 256));
if !self.take {
return None;
}
let map = super::super::dmabuf::DmaBufMap::new(frame.fd, frame.size).unwrap();
let row = map.read(|bytes| bytes[..64 * 4].to_vec());
Some(self.got.send((true, row)).is_ok())
}
}
if !std::path::Path::new("/dev/udmabuf").exists() {
eprintln!("no /dev/udmabuf, skipped");
return;
}
let mut expected = Vec::new();
SyntheticScreen::new(64, 48).render(0, &mut expected);
for take in [true, false] {
let mut screen = SyntheticScreen::new(64, 48).with_dmabuf(true);
let (got, frames) = mpsc::channel();
let sink = Box::new(Sink { take, got });
screen
.start_sink(&SourceId::Synthetic, &CaptureOptions::default(), sink)
.await
.unwrap();
let (dmabuf, row) = frames.recv_timeout(Duration::from_secs(5)).unwrap();
screen.stop();
assert_eq!(dmabuf, take, "taken as a DMA-BUF");
assert_eq!(row, expected[..64 * 4], "the first row of frame 0");
}
}
}
+26
View File
@@ -257,6 +257,32 @@ pub trait VideoEncoder: Send {
fn speed(&self) -> Option<i32> {
None
}
/// Whether this encoder takes [`GpuFrame`](crate::GpuFrame)s
/// ([`encode_gpu`](Self::encode_gpu)), and then the multiple their
/// width and height must be of (a size it encodes exactly; GPU frames
/// are made at that size instead of being cropped here). `None` for
/// encoders that need the pixels in memory: all but VA-API.
fn gpu_alignment(&self) -> Option<(u32, u32)> {
None
}
/// Encode a frame that is in GPU memory, like
/// [`encode_with`](Self::encode_with). Only for encoders with a
/// [`gpu_alignment`](Self::gpu_alignment), and frames of a size that is a
/// multiple of it; the rest fail with `Error::CodecUnavailable`.
fn encode_gpu(
&mut self,
frame: &crate::GpuFrame,
force_keyframe: bool,
out: &mut dyn FnMut(EncodedChunk<'_>),
) -> Result<()> {
let _ = (frame, force_keyframe, out);
Err(Error::CodecUnavailable {
codec: self.codec(),
reason: format!("{} takes no frames in GPU memory", self.backend()),
})
}
}
/// A video decoder.
+291 -325
View File
@@ -15,6 +15,7 @@ use std::ffi::c_int;
use std::sync::OnceLock;
use std::time::{Duration, Instant};
use super::gpu::{self, GpuConverter, GpuLayer, RGB_FOURCCS};
use super::layout::{self, HwFramesFields};
use super::sys::{self, FrameHead, PacketHead, Ptr, Rational, cstr};
use super::{Ffmpeg, take_log, vpp};
@@ -25,7 +26,7 @@ use crate::codec::{
VideoEncoder,
};
use crate::convert;
use crate::frame::{FrameData, VideoFrame};
use crate::frame::{FrameData, GpuFrame, VideoFrame};
use crate::{Error, Result};
/// How a backend takes frames.
@@ -454,7 +455,7 @@ fn vaapi_device(ffmpeg: &Ffmpeg) -> std::result::Result<Ptr, String> {
/// The `VADisplay` of the process's VA-API device (the first field of its
/// `AVVAAPIDeviceContext`).
fn vaapi_display(ffmpeg: &Ffmpeg) -> std::result::Result<vpp::Display, String> {
pub(crate) fn vaapi_display(ffmpeg: &Ffmpeg) -> std::result::Result<vpp::Display, String> {
let device = vaapi_device(ffmpeg)?;
let name = cstr("vaapi");
// SAFETY: a C string; `device` is a live VA-API device reference, whose
@@ -466,6 +467,56 @@ fn vaapi_display(ffmpeg: &Ffmpeg) -> std::result::Result<vpp::Display, String> {
}
}
/// A pool of VA-API surfaces of `sw_format` (an `AVPixelFormat`) and
/// `width` x `height` on the process's device (an `AVHWFramesContext`
/// reference); surfaces are made on demand and recycled.
pub(crate) fn vaapi_pool(
ffmpeg: &Ffmpeg,
width: u32,
height: u32,
sw_format: c_int,
) -> std::result::Result<Ptr, String> {
let api = &ffmpeg.api;
let device = vaapi_device(ffmpeg)?;
let vaapi = ffmpeg.pix.vaapi.ok_or("no VA-API pixel format")?;
// SAFETY: `device` is a live device reference.
let mut pool = unsafe { (api.av_hwframe_ctx_alloc)(device) };
if pool.is_null() {
return Err("av_hwframe_ctx_alloc failed".into());
}
// SAFETY: `pool` was just allocated on `device`.
let fields: HwFramesFields = match unsafe { layout::hw_frames_fields(pool, device) } {
Ok(f) => f,
Err(e) => {
// SAFETY: allocated above.
unsafe { (api.av_buffer_unref)(&mut pool) };
return Err(e);
}
};
// SAFETY: the fields were located and checked on this very context;
// setting them before av_hwframe_ctx_init is what FFmpeg expects.
let ret = unsafe {
let ctx = (*pool.cast::<sys::BufferRefHead>()).data.cast::<std::ffi::c_void>();
layout::write::<c_int>(ctx, fields.format, vaapi);
layout::write::<c_int>(ctx, fields.sw_format, sw_format);
layout::write::<c_int>(ctx, fields.width, width as c_int);
layout::write::<c_int>(ctx, fields.height, height as c_int);
// Surfaces are allocated on demand and recycled by the pool.
layout::write::<c_int>(ctx, fields.initial_pool_size, 0);
(api.av_hwframe_ctx_init)(pool)
};
if ret < 0 {
// SAFETY: allocated above.
unsafe { (api.av_buffer_unref)(&mut pool) };
return Err(format!(
"VA-API surface pool: {}{}",
api.error_text(ret),
log_suffix("AVHWFramesContext")
));
}
Ok(pool)
}
/// FFmpeg's recent messages, appended to an error.
fn log_suffix(context: &str) -> String {
let log = take_log(context);
@@ -527,8 +578,6 @@ struct Session {
opened: Instant,
timestamps: Timestamps,
nv12: bool,
/// RGB DMA-BUFs: made on the first one; why not, if they cannot be.
rgb: Option<std::result::Result<RgbImport, String>>,
/// An AMF encoder: opened and closed under [`amf_lock`].
amf: bool,
}
@@ -552,47 +601,6 @@ fn amf_lock() -> std::sync::MutexGuard<'static, ()> {
AMF.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}
/// What RGB DMA-BUFs need on their way into the session's NV12 surfaces:
/// a frames context of their own size to be mapped onto (FFmpeg gives an
/// imported surface the size of the destination's frames context, and the
/// session's has the coded size), the frame that holds the mapping, and
/// the GPU colour conversion.
struct RgbImport {
pool: Ptr,
mapped: Ptr,
size: (u32, u32),
converter: vpp::Converter,
}
// SAFETY: as `Session`, which owns it.
unsafe impl Send for RgbImport {}
impl Drop for RgbImport {
fn drop(&mut self) {
let api = &Ffmpeg::get().expect("an import exists only with FFmpeg").api;
// SAFETY: both are NULL or ours.
unsafe {
(api.av_frame_free)(&mut self.mapped);
(api.av_buffer_unref)(&mut self.pool);
}
}
}
/// The VA-API surface of a VA-API frame (`data[3]`, `hwcontext_vaapi.h`).
///
/// # Safety
/// `frame` must be a live frame of format `AV_PIX_FMT_VAAPI` holding a
/// surface.
unsafe fn surface_id(frame: Ptr) -> std::ffi::c_uint {
// SAFETY: guaranteed by the caller.
unsafe { (*frame.cast::<FrameHead>()).data[3] as usize as std::ffi::c_uint }
}
/// The DRM formats of RGB buffers the conversion takes (8 bits per
/// channel, 4 bytes per pixel; what screen capture offers).
const RGB_FOURCCS: [u32; 4] =
[drm_fourcc(b"XR24"), drm_fourcc(b"AR24"), drm_fourcc(b"XB24"), drm_fourcc(b"AB24")];
impl Drop for Session {
fn drop(&mut self) {
let api = &Ffmpeg::get().expect("a session exists only with FFmpeg").api;
@@ -640,6 +648,19 @@ pub struct FfmpegEncoder {
/// Sizes it encodes exactly are multiples of these
/// ([`BackendStatus::alignment`]).
alignment: (u32, u32),
/// For RGB DMA-BUFs ([`encode_dmabuf`](Self::encode_dmabuf)): made on
/// the first one; why not, if it cannot be.
gpu: Option<std::result::Result<GpuConverter, String>>,
}
/// `size` cropped to a multiple of `alignment` (even at least, for 4:2:0
/// chroma; at least 2x2): what an encoder of that alignment encodes exactly.
pub(crate) fn exact_size(size: (u32, u32), alignment: (u32, u32)) -> (u32, u32) {
let crop = |v: u32, a: u32| {
let a = a.max(2);
if v >= a { v / a * a } else { (v & !1).max(2) }
};
(crop(size.0, alignment.0), crop(size.1, alignment.1))
}
impl FfmpegEncoder {
@@ -670,6 +691,7 @@ impl FfmpegEncoder {
low_power: false,
dmabuf_checked: false,
alignment,
gpu: None,
})
}
@@ -735,11 +757,10 @@ impl FfmpegEncoder {
}
/// The encoder size: the frame cropped to a multiple of the backend's
/// alignment (even at least, for 4:2:0 chroma), so that the stream
/// declares exactly the picture it carries; at least 2x2.
/// alignment, so that the stream declares exactly the picture it
/// carries ([`exact_size`]).
fn coded_size(&self, width: u32, height: u32) -> (u32, u32) {
let crop = |v: u32, a: u32| if v >= a { v / a * a } else { (v & !1).max(2) };
(crop(width, self.alignment.0), crop(height, self.alignment.1))
exact_size((width, height), self.alignment)
}
/// Open a session for `width` x `height`.
@@ -791,7 +812,7 @@ impl FfmpegEncoder {
opened: Instant::now(),
timestamps: Timestamps::new(),
nv12: self.spec.input != Input::Yuv420p,
rgb: None,
amf: false,
};
// SAFETY: `ctx` is a live codec context; the first child is its
@@ -863,7 +884,8 @@ impl FfmpegEncoder {
self.apply(ctx, private, setting)?;
}
if self.spec.is_vaapi() {
session.pool = self.vaapi_pool(width, height, self.ffmpeg.pix.nv12)?;
session.pool = vaapi_pool(self.ffmpeg, width, height, self.ffmpeg.pix.nv12)
.map_err(|e| self.unavailable(e))?;
let offset = self.ffmpeg.codec_hw_frames.clone().map_err(|e| self.unavailable(e))?;
// SAFETY: `offset` is AVCodecContext.hw_frames_ctx (checked at
// load); the context takes the new reference and frees it.
@@ -919,45 +941,6 @@ impl FfmpegEncoder {
/// A VA-API surface pool of `sw_format` (an `AVPixelFormat`) for `width`
/// x `height`.
fn vaapi_pool(&self, width: u32, height: u32, sw_format: c_int) -> Result<Ptr> {
let api = &self.ffmpeg.api;
let device = vaapi_device(self.ffmpeg).map_err(|e| self.unavailable(e))?;
let vaapi =
self.ffmpeg.pix.vaapi.ok_or_else(|| self.unavailable("no VA-API format".into()))?;
// SAFETY: `device` is a live device reference.
let mut pool = unsafe { (api.av_hwframe_ctx_alloc)(device) };
if pool.is_null() {
return Err(self.unavailable("av_hwframe_ctx_alloc failed".into()));
}
// SAFETY: `pool` was just allocated on `device`.
let fields: HwFramesFields = match unsafe { layout::hw_frames_fields(pool, device) } {
Ok(f) => f,
Err(e) => {
// SAFETY: allocated above.
unsafe { (api.av_buffer_unref)(&mut pool) };
return Err(self.unavailable(e));
}
};
// SAFETY: the fields were located and checked on this very context;
// setting them before av_hwframe_ctx_init is what FFmpeg expects.
let ret = unsafe {
let ctx = (*pool.cast::<sys::BufferRefHead>()).data.cast::<std::ffi::c_void>();
layout::write::<c_int>(ctx, fields.format, vaapi);
layout::write::<c_int>(ctx, fields.sw_format, sw_format);
layout::write::<c_int>(ctx, fields.width, width as c_int);
layout::write::<c_int>(ctx, fields.height, height as c_int);
// Surfaces are allocated on demand and recycled by the pool.
layout::write::<c_int>(ctx, fields.initial_pool_size, 0);
(api.av_hwframe_ctx_init)(pool)
};
if ret < 0 {
// SAFETY: allocated above.
unsafe { (api.av_buffer_unref)(&mut pool) };
return Err(self.error("VA-API surface pool", ret));
}
Ok(pool)
}
/// Copy the I420 picture into the session's frame (cropped to the coded
/// size; NV12 interleaved where the backend wants it).
fn fill(&self, session: &Session, frame: &VideoFrame) -> Result<()> {
@@ -1132,9 +1115,8 @@ impl FfmpegEncoder {
/// (their size must be one it encodes exactly), and stay in use until
/// this frame's packet came out (the encoder reads them one frame deep).
/// RGB buffers (`XR24`, `AR24`, `XB24`, `AB24`: what screen capture
/// delivers) are converted into the session's NV12 surfaces on the GPU
/// (VA-API video processing), cropped to the coded size, and
/// are no longer read when this returns.
/// delivers) are converted to NV12 on the GPU ([`GpuConverter`]), cropped
/// to the coded size, and are no longer read when this returns.
///
/// Anything else fails with `Error::CodecUnavailable`; callers then map
/// the buffer and use [`encode_with`](VideoEncoder::encode_with).
@@ -1147,11 +1129,35 @@ impl FfmpegEncoder {
if !self.spec.is_vaapi() {
return Err(self.unavailable(format!("{} does not import DMA-BUFs", self.spec.name)));
}
let rgb = RGB_FOURCCS.contains(&frame.fourcc) && frame.plane_count == 1;
if !rgb && (frame.fourcc != drm_fourcc(b"NV12") || frame.plane_count != 2) {
if RGB_FOURCCS.contains(&frame.fourcc) && frame.plane_count == 1 {
let converter = match self
.gpu
.get_or_insert_with(|| GpuConverter::new().map_err(|e| e.to_string()))
{
Ok(converter) => converter,
Err(e) => {
return Err(Error::CodecUnavailable {
codec: self.spec.codec,
reason: e.clone(),
});
}
};
let layer = GpuLayer {
size: (frame.width, frame.height),
alignment: self.alignment,
due: true,
};
let mut converted = [None];
if let Err(e) = converter.convert(frame, &[layer], &mut converted) {
return Err(self.unavailable(e.to_string()));
}
let gpu = converted[0].take().expect("a due layer gets a frame");
return self.encode_gpu(&gpu, force_keyframe, out);
}
if frame.fourcc != drm_fourcc(b"NV12") || frame.plane_count != 2 {
return Err(self.unavailable("only NV12 and RGB DMA-BUFs are imported".into()));
}
if !rgb && self.coded_size(frame.width, frame.height) != (frame.width, frame.height) {
if self.coded_size(frame.width, frame.height) != (frame.width, frame.height) {
return Err(self.unavailable(format!(
"{}x{} is not a size {} encodes exactly",
frame.width, frame.height, self.spec.name
@@ -1159,16 +1165,16 @@ impl FfmpegEncoder {
}
let refs = self.ffmpeg.frame_refs.clone().map_err(|e| self.unavailable(e))?;
let (mut session, force) = self.prepare(frame.width, frame.height, force_keyframe, out)?;
let result = self.import_and_send(&mut session, frame, rgb, force, refs, out);
let result = self.import_and_send(&mut session, frame, force, refs, out);
self.session = Some(session);
result
}
/// Map an NV12 DMA-BUF onto a surface of the session and encode it.
fn import_and_send(
&mut self,
session: &mut Session,
frame: &DmaBufRef,
rgb: bool,
force: bool,
refs: layout::FrameRefs,
out: &mut dyn FnMut(EncodedChunk<'_>),
@@ -1189,35 +1195,25 @@ impl FfmpegEncoder {
}
self.dmabuf_checked = true;
}
let (pool, hw) = (session.pool, session.hw);
if rgb {
let import = self.rgb_import(session, frame)?;
self.map_dmabuf(frame, import.pool, import.mapped, refs)?;
// SAFETY: `hw` is our frame (unreferenced after each frame), the
// pool the session's; both surfaces belong to the process's
// device, the converter's display.
let converted = unsafe {
let ret = (api.av_hwframe_get_buffer)(pool, hw, 0);
let converted = if ret < 0 {
Err(self.error("VA-API surface", ret))
} else {
let done = import.converter.convert(surface_id(import.mapped), surface_id(hw));
done.map_err(|e| self.unavailable(e))
};
// The buffer has been read: the mapping can go.
(api.av_frame_unref)(import.mapped);
converted
};
if let Err(e) = converted {
// SAFETY: our frame.
unsafe { (api.av_frame_unref)(hw) };
return Err(e);
}
} else {
self.map_dmabuf(frame, pool, hw, refs)?;
}
let hw = session.hw;
gpu::map_dmabuf(self.ffmpeg, frame, session.pool, hw, refs).map_err(|e| {
Error::Encoder { codec: self.spec.codec, message: format!("{}: {e}", self.spec.name) }
})?;
let pts =
self.stamp(session, frame.timestamp, (frame.timestamp.as_micros() * 9 / 100) as u64);
self.send_surface(session, pts, force, out)
}
/// Encode the surface in `session.hw` (taken from the session's frame
/// afterwards; the encoder keeps its own reference while it needs it).
fn send_surface(
&self,
session: &mut Session,
pts: i64,
force: bool,
out: &mut dyn FnMut(EncodedChunk<'_>),
) -> Result<()> {
let hw = session.hw;
let pict_type = if force { sys::PICTURE_TYPE_I } else { sys::PICTURE_TYPE_NONE };
// SAFETY: offsets checked at load for this release's AVFrame; `hw`
// holds a surface until the unref.
@@ -1226,103 +1222,11 @@ impl FfmpegEncoder {
layout::write::<c_int>(hw, self.ffmpeg.frame.pict_type, pict_type);
}
let result = self.send(session, hw, out);
// SAFETY: our frame; the encoder holds its own reference.
unsafe { (api.av_frame_unref)(hw) };
// SAFETY: our frame.
unsafe { (self.ffmpeg.api.av_frame_unref)(hw) };
result.map(|_| ())
}
/// The session's [`RgbImport`] for `frame`, made on first use (again
/// when the buffers change size within the session's coded size).
fn rgb_import<'s>(&self, session: &'s mut Session, frame: &DmaBufRef) -> Result<&'s RgbImport> {
let size = (frame.width, frame.height);
let stale = match &session.rgb {
None => true,
Some(Ok(import)) => import.size != size,
Some(Err(_)) => false,
};
if stale {
session.rgb = None;
session.rgb = Some(self.new_rgb_import(size, (session.width, session.height)));
}
match session.rgb.as_ref().expect("made above") {
Ok(import) => Ok(import),
Err(e) => Err(self.unavailable(e.clone())),
}
}
fn new_rgb_import(
&self,
size: (u32, u32),
coded: (u32, u32),
) -> std::result::Result<RgbImport, String> {
let bgr0 = self.ffmpeg.pix.bgr0.ok_or("no bgr0 pixel format")?;
let display = vaapi_display(self.ffmpeg)?;
let converter = vpp::Converter::new(display, coded.0, coded.1)?;
let pool = self.vaapi_pool(size.0, size.1, bgr0).map_err(|e| e.to_string())?;
// SAFETY: an allocation (NULL is freed as nothing by the drop).
let mapped = unsafe { (self.ffmpeg.api.av_frame_alloc)() };
let import = RgbImport { pool, mapped, size, converter };
if import.mapped.is_null() { Err("out of memory".into()) } else { Ok(import) }
}
/// Map DMA-BUF `frame` onto a VA-API surface in `dst` (one of our
/// frames), which gets a reference to `pool`: the import takes that
/// frames context's size and device.
fn map_dmabuf(
&self,
frame: &DmaBufRef,
pool: Ptr,
dst: Ptr,
refs: layout::FrameRefs,
) -> Result<()> {
let api = &self.ffmpeg.api;
let drm_prime =
self.ffmpeg.pix.drm_prime.ok_or_else(|| self.unavailable("no DRM PRIME".into()))?;
let vaapi = self.ffmpeg.pix.vaapi.ok_or_else(|| self.unavailable("no VA-API".into()))?;
let mut descriptor =
sys::DrmFrameDescriptor { nb_objects: 1, nb_layers: 1, ..Default::default() };
descriptor.objects[0] =
sys::DrmObject { fd: frame.fd, size: frame.size, format_modifier: frame.modifier };
descriptor.layers[0].format = frame.fourcc;
descriptor.layers[0].nb_planes = frame.plane_count as c_int;
for (plane, &(offset, pitch)) in
descriptor.layers[0].planes.iter_mut().zip(&frame.planes[..frame.plane_count])
{
*plane =
sys::DrmPlane { object_index: 0, offset: offset as isize, pitch: pitch as isize };
}
// SAFETY: the descriptor lives in a buffer the source frame owns
// (buf[0], checked offset), so FFmpeg can keep it while mapped; the
// destination frame gets a reference to the pool at the checked
// hw_frames_ctx offset; av_frame_free / av_frame_unref release both.
unsafe {
let mut buffer = (api.av_buffer_allocz)(std::mem::size_of::<sys::DrmFrameDescriptor>());
let mut src = (api.av_frame_alloc)();
if buffer.is_null() || src.is_null() {
(api.av_buffer_unref)(&mut buffer);
(api.av_frame_free)(&mut src);
return Err(self.unavailable("out of memory".into()));
}
let data = (*buffer.cast::<sys::BufferRefHead>()).data;
data.cast::<sys::DrmFrameDescriptor>().write(descriptor);
let head = src.cast::<FrameHead>();
(*head).format = drm_prime;
(*head).width = frame.width as c_int;
(*head).height = frame.height as c_int;
(*head).data[0] = data;
layout::write::<Ptr>(src, refs.buf, buffer);
(*dst.cast::<FrameHead>()).format = vaapi;
layout::write::<Ptr>(dst, refs.hw_frames_ctx, (api.av_buffer_ref)(pool));
let ret = (api.av_hwframe_map)(dst, src, sys::HWFRAME_MAP_READ);
(api.av_frame_free)(&mut src);
if ret < 0 {
(api.av_frame_unref)(dst);
return Err(self.error("DMA-BUF import", ret));
}
}
Ok(())
}
/// The pts of a frame taken at `timestamp`: frame numbers at the
/// session's rate (its time base), strictly increasing; remembered with
/// the 90 kHz time for the packets.
@@ -1508,6 +1412,45 @@ impl VideoEncoder for FfmpegEncoder {
}
Ok(())
}
/// VA-API encoders take NV12 surfaces of the sizes they encode exactly.
fn gpu_alignment(&self) -> Option<(u32, u32)> {
self.spec.is_vaapi().then_some(self.alignment)
}
/// The surface goes to the encoder as it is: the encoder takes a
/// reference, so it stays out of its pool until the encoder is done.
fn encode_gpu(
&mut self,
frame: &GpuFrame,
force_keyframe: bool,
out: &mut dyn FnMut(EncodedChunk<'_>),
) -> Result<()> {
if !self.spec.is_vaapi() {
return Err(self.unavailable(format!("{} takes no VA-API surfaces", self.spec.name)));
}
if frame.surface.0.is_null() {
return Err(self.unavailable("a GPU frame without a surface (out of memory)".into()));
}
if self.coded_size(frame.width, frame.height) != (frame.width, frame.height) {
return Err(self.unavailable(format!(
"{}x{} is not a size {} encodes exactly",
frame.width, frame.height, self.spec.name
)));
}
let (mut session, force) = self.prepare(frame.width, frame.height, force_keyframe, out)?;
let pts = self.stamp(&mut session, frame.timestamp, frame.pts_90khz());
// SAFETY: `hw` is our frame, unreferenced after each frame;
// `surface` is a live VA-API frame of the same device.
let ret = unsafe { (self.ffmpeg.api.av_frame_ref)(session.hw, frame.surface.0) };
let result = if ret < 0 {
Err(self.error("GPU frame", ret))
} else {
self.send_surface(&mut session, pts, force, out)
};
self.session = Some(session);
result
}
}
/// A gradient test picture.
@@ -2102,8 +2045,7 @@ mod tests {
) -> Self {
let ffmpeg = Ffmpeg::get().unwrap();
let api = &ffmpeg.api;
let encoder = FfmpegEncoder::new("h264_vaapi", EncoderConfig::default()).unwrap();
let pool = encoder.vaapi_pool(width, height, sw_format).expect("a VA-API surface pool");
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
@@ -2190,6 +2132,113 @@ mod tests {
}
}
/// The picture of a GPU frame, read back into memory as I420.
fn download(frame: &GpuFrame) -> VideoFrame {
let ffmpeg = Ffmpeg::get().unwrap();
let api = &ffmpeg.api;
let (w, h) = (frame.width as usize, frame.height as usize);
let mut out = VideoFrame::black_i420(frame.width, frame.height);
let FrameData::I420 { y, u, v } = &mut out.data else { unreachable!() };
// SAFETY: `sw` is ours and freed below; a downloaded plane holds
// `linesize * rows` bytes.
unsafe {
let mut sw = (api.av_frame_alloc)();
(*sw.cast::<FrameHead>()).format = ffmpeg.pix.nv12;
assert!((api.av_hwframe_transfer_data)(sw, frame.surface.0, 0) >= 0, "download");
let head = &*sw.cast::<FrameHead>();
let rows = |i: usize, rows: usize| {
let stride = head.linesize[i] as usize;
std::slice::from_raw_parts(head.data[i], stride * rows).chunks_exact(stride)
};
for (row, src) in rows(0, h).enumerate() {
y.data[row * w..][..w].copy_from_slice(&src[..w]);
}
let cw = w / 2;
for (row, src) in rows(1, h / 2).enumerate() {
for (i, pair) in src[..cw * 2].chunks_exact(2).enumerate() {
u.data[row * u.stride + i] = pair[0];
v.data[row * v.stride + i] = pair[1];
}
}
(api.av_frame_free)(&mut sw);
}
out
}
/// One captured RGB DMA-BUF made into a GPU frame per simulcast layer:
/// full size, half and a fixed 640x360 at AV1's alignment, each the
/// whole picture scaled (cropped to the alignment) as the CPU pyramid
/// does it, and each encoded by `h264_vaapi` straight from its surface
/// and decoded. The frames are recycled once nothing holds them.
#[test]
fn gpu_frames_for_every_layer() {
const SIZE: (u32, u32) = (1280, 720);
if !usable("h264_vaapi") {
eprintln!("no usable h264_vaapi, skipped");
return;
}
let ffmpeg = Ffmpeg::get().unwrap();
let screen = crate::capture::synthetic::SyntheticScreen::with_pattern(
SIZE.0,
SIZE.1,
crate::capture::synthetic::Pattern::Desktop,
);
let picture = screen.frame(5, 30);
let rgb =
Exported::new(SIZE, ffmpeg.pix.bgr0.unwrap(), drm_fourcc(b"XR24"), Some(&picture));
let mut converter = GpuConverter::new().expect("VA-API video processing");
eprintln!("tiled RGB modifiers the import takes: {:x?}", converter.modifiers());
let layers = [
GpuLayer { size: SIZE, alignment: (2, 2), due: true },
GpuLayer { size: (640, 360), alignment: (64, 16), due: true },
GpuLayer { size: (320, 180), alignment: (2, 2), due: false },
];
let mut out = [None, None, None];
converter.convert(&rgb.frame, &layers, &mut out).expect("converted");
assert!(out[2].is_none(), "a layer that is not due gets nothing");
let sizes: Vec<_> = out.iter().flatten().map(|f| (f.width, f.height)).collect();
assert_eq!(sizes, [SIZE, (640, 352)], "cropped to the alignment");
let cpu = convert::to_i420(&picture).unwrap().into_owned();
let mut half = VideoFrame::black_i420(640, 360);
let mut workers = crate::workers::Workers::new("voelin-test-scale", 1);
crate::scale::scale_i420(&mut workers, &cpu, &mut half).unwrap();
for frame in out.iter().flatten() {
// The CPU's picture at the layer's size, cropped the same way.
let reference = if (frame.width, frame.height) == SIZE { &cpu } else { &half };
let mut cropped = reference.view();
(cropped.width, cropped.height) = (frame.width, frame.height);
let gpu = download(frame);
let psnr = convert::psnr(&cropped.to_frame(), &gpu).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);
let mut encoder = FfmpegEncoder::new("h264_vaapi", EncoderConfig::default()).unwrap();
let mut decoder = decoder(Codec::H264);
let mut packets = 0;
encoder
.encode_gpu(frame, true, &mut |chunk| {
packets += 1;
if let Some(decoder) = &mut decoder {
let decoded = decoder.decode(chunk.data).unwrap().expect("a picture");
assert_eq!((decoded.width, decoded.height), (frame.width, frame.height));
let psnr = convert::psnr(&gpu, &decoded).unwrap();
assert!(psnr > 30.0, "decoded at {psnr:.1} dB");
}
})
.expect("encoded from the surface");
assert!(packets > 0);
}
// Once nothing holds them, the same frames come back.
let first: Vec<*const GpuFrame> =
out.iter().flatten().map(std::sync::Arc::as_ptr).collect();
out = [None, None, None];
converter.convert(&rgb.frame, &layers, &mut out).expect("converted again");
let again: Vec<*const GpuFrame> =
out.iter().flatten().map(std::sync::Arc::as_ptr).collect();
assert_eq!(first, again, "recycled");
}
/// Our decoder for `codec`, if this build and machine have one: OpenH264
/// with `VOELIN_OPENH264_LIB`, dav1d with `--features av1`.
fn decoder(codec: Codec) -> Option<Box<dyn crate::codec::VideoDecoder>> {
@@ -2255,7 +2304,6 @@ mod tests {
return;
}
let ffmpeg = Ffmpeg::get().unwrap();
let api = &ffmpeg.api;
let screen = crate::capture::synthetic::SyntheticScreen::with_pattern(
SIZE.0,
SIZE.1,
@@ -2267,45 +2315,21 @@ mod tests {
assert_eq!(rgb.frame.plane_count, 1);
// The conversion alone: the GPU's NV12 against the CPU's I420.
let converter =
vpp::Converter::new(vaapi_display(ffmpeg).unwrap(), SIZE.0, SIZE.1).unwrap();
let encoder = FfmpegEncoder::new("h264_vaapi", EncoderConfig::default()).unwrap();
let mut pool = encoder.vaapi_pool(SIZE.0, SIZE.1, ffmpeg.pix.nv12).unwrap();
let mut converter = GpuConverter::new().expect("VA-API video processing");
let layer = GpuLayer { size: SIZE, alignment: (2, 2), due: true };
let mut converted = [None];
converter.convert(&rgb.frame, &[layer], &mut converted).expect("converted");
let downloaded = download(converted[0].as_ref().unwrap());
drop((converted, converter));
let cpu = convert::to_i420(&picture).unwrap();
let FrameData::I420 { y, u, v } = &cpu.data else { unreachable!() };
let FrameData::I420 { y: gy, u: gu, v: gv } = &downloaded.data else { unreachable!() };
let (w, h, cw, ch) =
(SIZE.0 as usize, SIZE.1 as usize, SIZE.0 as usize / 2, SIZE.1 as usize / 2);
let mut gpu = [Vec::new(), Vec::new(), Vec::new()];
// SAFETY: frames and pool are ours and freed below; the downloaded
// planes hold `linesize * rows` bytes.
unsafe {
let (mut out, mut sw) = ((api.av_frame_alloc)(), (api.av_frame_alloc)());
assert!((api.av_hwframe_get_buffer)(pool, out, 0) >= 0);
converter.convert(surface_id(rgb.surface), surface_id(out)).expect("converted");
(*sw.cast::<FrameHead>()).format = ffmpeg.pix.nv12;
assert!((api.av_hwframe_transfer_data)(sw, out, 0) >= 0, "download");
let head = &*sw.cast::<FrameHead>();
let plane = |i: usize, rows: usize| {
let stride = head.linesize[i] as usize;
std::slice::from_raw_parts(head.data[i], stride * rows).chunks_exact(stride)
};
for row in plane(0, h) {
gpu[0].extend_from_slice(&row[..w]);
}
for row in plane(1, ch) {
for pair in row[..cw * 2].chunks_exact(2) {
gpu[1].push(pair[0]);
gpu[2].push(pair[1]);
}
}
(api.av_frame_free)(&mut sw);
(api.av_frame_free)(&mut out);
(api.av_buffer_unref)(&mut pool);
}
drop(converter);
for (name, gpu, cpu, width, rows) in
[("Y", &gpu[0], y, w, h), ("U", &gpu[1], u, cw, ch), ("V", &gpu[2], v, cw, ch)]
[("Y", gy, y, w, h), ("U", gu, u, cw, ch), ("V", gv, v, cw, ch)]
{
let gpu: Vec<u8> = (0..rows).flat_map(|r| gpu.row(r, width).to_vec()).collect();
let cpu: Vec<u8> = (0..rows).flat_map(|r| cpu.row(r, width).to_vec()).collect();
let mean = gpu.iter().zip(&cpu).map(|(a, b)| u64::from(a.abs_diff(*b))).sum::<u64>()
as f64 / cpu.len() as f64;
@@ -2317,9 +2341,9 @@ mod tests {
// The buffers: the driver's own (tiled), and a LINEAR one with a
// padded pitch in system memory, which is what the portal negotiates.
#[cfg(target_os = "linux")]
#[cfg(all(target_os = "linux", feature = "pipewire"))]
let linear = linear_dmabuf(&picture, (SIZE.0 as usize * 4).next_multiple_of(256));
#[cfg(not(target_os = "linux"))]
#[cfg(not(all(target_os = "linux", feature = "pipewire")))]
let linear: Option<((), DmaBufRef)> = None;
if linear.is_none() {
eprintln!("no /dev/udmabuf: the LINEAR buffer is skipped");
@@ -2384,91 +2408,33 @@ mod tests {
}
}
/// `struct udmabuf_create` of `<linux/udmabuf.h>`, and `UDMABUF_CREATE`
/// returning the new DMA-BUF.
#[cfg(target_os = "linux")]
#[repr(C)]
struct UdmabufCreate {
memfd: u32,
flags: u32,
offset: u64,
size: u64,
}
// SAFETY: `UDMABUF_CREATE` (`_IOW('u', 0x42, struct udmabuf_create)`)
// only reads the struct and returns a new descriptor.
#[cfg(target_os = "linux")]
unsafe impl rustix::ioctl::Ioctl for UdmabufCreate {
type Output = std::os::fd::OwnedFd;
const IS_MUTATING: bool = false;
fn opcode(&self) -> rustix::ioctl::Opcode {
rustix::ioctl::opcode::write::<UdmabufCreate>(b'u', 0x42)
}
fn as_ptr(&mut self) -> *mut std::ffi::c_void {
(&raw mut *self).cast()
}
unsafe fn output_from_ptr(
out: rustix::ioctl::IoctlOutput,
_: *mut std::ffi::c_void,
) -> rustix::io::Result<Self::Output> {
// SAFETY: the descriptor the kernel just made, ours to own.
Ok(unsafe { std::os::fd::FromRawFd::from_raw_fd(out) })
}
}
/// `picture` (BGRA) in a LINEAR DMA-BUF of system memory, rows `stride`
/// bytes apart: `/dev/udmabuf` over a sealed memfd. The descriptor has
/// to outlive the returned buffer. `None` without access to
/// `picture` (BGRA) in a LINEAR DMA-BUF of ordinary memory, rows
/// `stride` bytes apart ([`Udmabuf`](crate::capture::dmabuf::Udmabuf));
/// the buffer has to outlive the reference. `None` without access to
/// `/dev/udmabuf`.
#[cfg(target_os = "linux")]
#[cfg(all(target_os = "linux", feature = "pipewire"))]
fn linear_dmabuf(
picture: &VideoFrame,
stride: usize,
) -> Option<(std::os::fd::OwnedFd, DmaBufRef)> {
use rustix::fs::{MemfdFlags, SealFlags};
use std::io::Write;
use std::os::fd::AsRawFd;
) -> Option<(crate::capture::dmabuf::Udmabuf, DmaBufRef)> {
let FrameData::Bgra(pixels) = &picture.data else { return None };
let (w, h) = (picture.width as usize, picture.height as usize);
let size = (stride * h).next_multiple_of(4096);
let memfd = rustix::fs::memfd_create(
"voelin-linear-dmabuf",
MemfdFlags::CLOEXEC | MemfdFlags::ALLOW_SEALING,
)
.ok()?;
let mut bytes = vec![0; size];
for (y, row) in bytes.chunks_exact_mut(stride).take(h).enumerate() {
let mut buffer = crate::capture::dmabuf::Udmabuf::new(stride * h).ok()?;
for (y, row) in buffer.bytes_mut().chunks_exact_mut(stride).take(h).enumerate() {
row[..w * 4].copy_from_slice(pixels.row(y, w * 4));
}
let mut file = std::fs::File::from(memfd);
file.write_all(&bytes).ok()?;
rustix::fs::fcntl_add_seals(&file, SealFlags::SHRINK).ok()?;
let device =
std::fs::OpenOptions::new().read(true).write(true).open("/dev/udmabuf").ok()?;
let create = UdmabufCreate {
memfd: file.as_raw_fd() as u32,
flags: 1,
offset: 0,
size: size as u64,
};
// SAFETY: see the `Ioctl` impl; `device` is /dev/udmabuf.
let fd = unsafe { rustix::ioctl::ioctl(&device, create) }.ok()?;
let frame = DmaBufRef {
width: picture.width,
height: picture.height,
timestamp: Duration::ZERO,
fourcc: drm_fourcc(b"XR24"),
modifier: crate::capture::DRM_MOD_LINEAR,
fd: fd.as_raw_fd(),
size,
fd: buffer.fd(),
size: buffer.len(),
planes: [(0, stride), (0, 0), (0, 0), (0, 0)],
plane_count: 1,
};
Some((fd, frame))
Some((buffer, frame))
}
/// What the CPU spends per frame on its way into a VA-API encoder at
+385
View File
@@ -0,0 +1,385 @@
//! Captured RGB DMA-BUFs converted and scaled into NV12 VA-API surfaces on
//! the GPU, for VA-API encoders: screen sharing without the CPU reading a
//! pixel.
//!
//! A DMA-BUF (what the ScreenCast portal hands over) is mapped onto a VA-API
//! surface ([`map_dmabuf`]), and VA-API video processing ([`super::vpp`])
//! converts it to NV12 at the size of every layer that wants a frame, into
//! surfaces from pools of our own. The buffer is free again once
//! [`GpuConverter::convert`] returns; the surfaces travel to the encoders as
//! [`GpuFrame`]s ([`VideoEncoder::encode_gpu`](crate::VideoEncoder::encode_gpu))
//! and go back to their pools when the last reference is dropped. The
//! frames are recycled, so nothing is allocated per frame once the pools
//! are warm.
#![allow(unsafe_code)]
use std::ffi::{c_int, c_uint};
use std::sync::Arc;
use std::time::Duration;
use super::encoder::{exact_size, vaapi_display, vaapi_pool};
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::{Error, Result};
/// The DRM formats of RGB buffers the conversion takes (8 bits per
/// channel, 4 bytes per pixel, one plane; what screen capture offers).
pub(crate) const RGB_FOURCCS: [u32; 4] =
[drm_fourcc(b"XR24"), drm_fourcc(b"AR24"), drm_fourcc(b"XB24"), drm_fourcc(b"AB24")];
/// An `AVFrame` that holds a VA-API surface (or nothing yet). Freeing it
/// gives the surface back to its pool.
pub(crate) struct Surface(pub(crate) Ptr);
// SAFETY: the frame is ours. Once it holds a surface it is only read: its
// surface id, and as the source of `av_frame_ref`, which takes references
// of its own (FFmpeg's buffer references are thread-safe).
unsafe impl Send for Surface {}
unsafe impl Sync for Surface {}
impl Surface {
fn alloc(ffmpeg: &Ffmpeg) -> Result<Self> {
// SAFETY: an allocation; NULL is checked.
let frame = unsafe { (ffmpeg.api.av_frame_alloc)() };
if frame.is_null() {
return Err(Error::Convert("out of memory".into()));
}
Ok(Self(frame))
}
/// Another frame of the same surface (NULL, which encoders refuse, if
/// memory runs out).
pub(crate) fn new_ref(&self) -> Self {
let api = &Ffmpeg::get().expect("a surface exists only with FFmpeg").api;
// SAFETY: a new frame takes a reference to ours; freed on failure.
unsafe {
let mut frame = (api.av_frame_alloc)();
if !frame.is_null() && (api.av_frame_ref)(frame, self.0) < 0 {
(api.av_frame_free)(&mut frame);
}
Self(frame)
}
}
/// The VA-API surface id (`data[3]` of an `AV_PIX_FMT_VAAPI` frame,
/// `hwcontext_vaapi.h`).
pub(crate) fn id(&self) -> c_uint {
// SAFETY: a live frame; `data` is its leading field.
unsafe { (*self.0.cast::<FrameHead>()).data[3] as usize as c_uint }
}
}
impl Drop for Surface {
fn drop(&mut self) {
if let Ok(ffmpeg) = Ffmpeg::get() {
// SAFETY: our frame (or NULL).
unsafe { (ffmpeg.api.av_frame_free)(&mut self.0) };
}
}
}
/// Map DMA-BUF `frame` onto a VA-API surface in `dst` (an unreferenced frame
/// of ours), which takes a reference to `pool`: the surface gets that frames
/// context's device. The surface reads the buffer itself, without a copy;
/// unreferencing `dst` lets the buffer go.
pub(crate) fn map_dmabuf(
ffmpeg: &Ffmpeg,
frame: &DmaBufRef,
pool: Ptr,
dst: Ptr,
refs: FrameRefs,
) -> std::result::Result<(), String> {
let api = &ffmpeg.api;
let drm_prime = ffmpeg.pix.drm_prime.ok_or("no DRM PRIME pixel format")?;
let vaapi = ffmpeg.pix.vaapi.ok_or("no VA-API pixel format")?;
let mut descriptor =
sys::DrmFrameDescriptor { nb_objects: 1, nb_layers: 1, ..Default::default() };
descriptor.objects[0] =
sys::DrmObject { fd: frame.fd, size: frame.size, format_modifier: frame.modifier };
descriptor.layers[0].format = frame.fourcc;
descriptor.layers[0].nb_planes = frame.plane_count as c_int;
for (plane, &(offset, pitch)) in
descriptor.layers[0].planes.iter_mut().zip(&frame.planes[..frame.plane_count])
{
*plane = sys::DrmPlane { object_index: 0, offset: offset as isize, pitch: pitch as isize };
}
// SAFETY: the descriptor lives in a buffer the source frame owns (buf[0],
// checked offset), so FFmpeg can keep it while mapped; the destination
// gets a reference to the pool at the checked hw_frames_ctx offset;
// av_frame_free / av_frame_unref release both.
unsafe {
let mut buffer = (api.av_buffer_allocz)(size_of::<sys::DrmFrameDescriptor>());
let mut src = (api.av_frame_alloc)();
if buffer.is_null() || src.is_null() {
(api.av_buffer_unref)(&mut buffer);
(api.av_frame_free)(&mut src);
return Err("out of memory".into());
}
let data = (*buffer.cast::<sys::BufferRefHead>()).data;
data.cast::<sys::DrmFrameDescriptor>().write(descriptor);
let head = src.cast::<FrameHead>();
(*head).format = drm_prime;
(*head).width = frame.width as c_int;
(*head).height = frame.height as c_int;
(*head).data[0] = data;
layout::write::<Ptr>(src, refs.buf, buffer);
(*dst.cast::<FrameHead>()).format = vaapi;
layout::write::<Ptr>(dst, refs.hw_frames_ctx, (api.av_buffer_ref)(pool));
let ret = (api.av_hwframe_map)(dst, src, sys::HWFRAME_MAP_READ);
(api.av_frame_free)(&mut src);
if ret < 0 {
(api.av_frame_unref)(dst);
return Err(format!("DMA-BUF import: {}", api.error_text(ret)));
}
}
Ok(())
}
/// 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)]
pub struct GpuLayer {
/// The size the whole picture is scaled to.
pub size: (u32, u32),
/// What the encoded width and height must be a multiple of
/// ([`VideoEncoder::gpu_alignment`](crate::VideoEncoder::gpu_alignment)):
/// the scaled picture is cropped to it at the right and bottom, as
/// encoders crop frames in memory.
pub alignment: (u32, u32),
pub due: bool,
}
/// NV12 surfaces of one size, and the frames that hold them, reused once
/// nothing else does.
struct Output {
size: (u32, u32),
pool: Ptr,
frames: Vec<Arc<GpuFrame>>,
}
impl Drop for Output {
fn drop(&mut self) {
// Frames still held elsewhere keep their surfaces and the pool.
self.frames.clear();
if let Ok(ffmpeg) = Ffmpeg::get() {
// SAFETY: our reference.
unsafe { (ffmpeg.api.av_buffer_unref)(&mut self.pool) };
}
}
}
/// See the [module docs](self). One per capture, used from one thread.
pub struct GpuConverter {
ffmpeg: &'static Ffmpeg,
refs: FrameRefs,
display: vpp::Display,
/// Video processing, and the source size it was made for.
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.
mapped: Surface,
outputs: Vec<Output>,
modifiers: Vec<u64>,
}
// SAFETY: the FFmpeg and libva objects are ours and used from one thread
// at a time (`&mut self`).
unsafe impl Send for GpuConverter {}
impl GpuConverter {
/// A converter on the process's VA-API device, or why there is none (no
/// FFmpeg, no VA-API device, no video processing).
pub fn new() -> Result<Self> {
let ffmpeg = Ffmpeg::get().map_err(|e| Error::Convert(e.into()))?;
let refs = ffmpeg.frame_refs.clone().map_err(Error::Convert)?;
let display = vaapi_display(ffmpeg).map_err(Error::Convert)?;
// Fail now rather than on the first frame.
vpp::Converter::new(display, 64, 64).map_err(Error::Convert)?;
let mut converter = Self {
ffmpeg,
refs,
display,
vpp: None,
import: None,
mapped: Surface::alloc(ffmpeg)?,
outputs: Vec::new(),
modifiers: Vec::new(),
};
converter.modifiers.extend(converter.tiled_modifier());
Ok(converter)
}
/// The tiled DRM format modifiers RGB buffers may have besides LINEAR:
/// the one this GPU's driver gives RGB surfaces of its own (it imports
/// what it makes), if that is tiled and needs a single plane (no
/// compression metadata). Empty if there is none.
pub fn modifiers(&self) -> &[u64] {
&self.modifiers
}
fn tiled_modifier(&self) -> Option<u64> {
let ffmpeg = self.ffmpeg;
let api = &ffmpeg.api;
let drm_prime = ffmpeg.pix.drm_prime?;
// The size of a typical screen: drivers may lay out small surfaces
// differently.
let mut pool = vaapi_pool(ffmpeg, 1920, 1080, ffmpeg.pix.bgr0?).ok()?;
let (surface, drm) = (Surface::alloc(ffmpeg).ok()?, Surface::alloc(ffmpeg).ok()?);
// SAFETY: frames and pool are ours; the exported frame's data[0] is
// the descriptor FFmpeg filled, read while the mapping lives (`drm`
// goes before `surface`).
let modifier = unsafe {
let mut modifier = None;
if (api.av_hwframe_get_buffer)(pool, surface.0, 0) >= 0 {
(*drm.0.cast::<FrameHead>()).format = drm_prime;
let flags = sys::HWFRAME_MAP_READ | sys::HWFRAME_MAP_DIRECT;
if (api.av_hwframe_map)(drm.0, surface.0, flags) >= 0 {
let d = *(*drm.0.cast::<FrameHead>()).data[0].cast::<sys::DrmFrameDescriptor>();
let layers = &d.layers[..(d.nb_layers.max(0) as usize).min(d.layers.len())];
let planes: c_int = layers.iter().map(|l| l.nb_planes).sum();
let m = d.objects[0].format_modifier;
let tiled = m != DRM_MOD_LINEAR && m != DRM_MOD_INVALID;
modifier = (d.nb_objects == 1 && planes == 1 && tiled).then_some(m);
}
}
modifier
};
drop(drm);
drop(surface);
// SAFETY: our reference.
unsafe { (api.av_buffer_unref)(&mut pool) };
modifier
}
/// Convert `frame`, an RGB DMA-BUF (`XR24`, `AR24`, `XB24` or `AB24` in
/// one plane, LINEAR or one of [`modifiers`](Self::modifiers)), for every
/// due layer: each gets an NV12 [`GpuFrame`] in `out` (same index), the
/// whole picture scaled to the layer's size and cropped to its alignment.
/// The buffer is no longer read when this returns. On an error nothing
/// in `out` is valid for this frame.
pub fn convert(
&mut self,
frame: &DmaBufRef,
layers: &[GpuLayer],
out: &mut [Option<Arc<GpuFrame>>],
) -> Result<()> {
if !RGB_FOURCCS.contains(&frame.fourcc) || frame.plane_count != 1 {
return Err(Error::Convert("not an RGB DMA-BUF of one plane".into()));
}
let source = (frame.width, frame.height);
self.outputs.retain(|o| layers.iter().any(|l| exact_size(l.size, l.alignment) == o.size));
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);
// SAFETY: our frame; this lets the buffer go.
unsafe { (self.ffmpeg.api.av_frame_unref)(self.mapped.0) };
result
}
/// The import pool and the video processing for buffers of `source`'s
/// size.
fn prepare(&mut self, source: (u32, u32)) -> Result<()> {
if self.import.as_ref().is_none_or(|(_, size)| *size != source) {
if let Some((mut pool, _)) = self.import.take() {
// SAFETY: our reference.
unsafe { (self.ffmpeg.api.av_buffer_unref)(&mut pool) };
}
let bgr0 = self.ffmpeg.pix.bgr0.ok_or(Error::Convert("no bgr0 pixel format".into()))?;
let pool = vaapi_pool(self.ffmpeg, source.0, source.1, bgr0).map_err(Error::Convert)?;
self.import = Some((pool, source));
}
if self.vpp.as_ref().is_none_or(|(_, size)| *size != source) {
self.vpp = None;
let converter =
vpp::Converter::new(self.display, source.0, source.1).map_err(Error::Convert)?;
self.vpp = Some((converter, source));
}
Ok(())
}
fn convert_mapped(
&mut self,
frame: &DmaBufRef,
layers: &[GpuLayer],
out: &mut [Option<Arc<GpuFrame>>],
) -> Result<()> {
let input = self.mapped.id();
for (layer, slot) in layers.iter().zip(out.iter_mut()) {
if !layer.due {
continue;
}
let exact = exact_size(layer.size, layer.alignment);
// The part of the picture that scales to `exact`: all of it
// scales to `size`, the rest is cropped.
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 (vpp, _) = self.vpp.as_ref().expect("prepared");
vpp.convert(input, src, gpu.surface.id(), exact).map_err(Error::Convert)?;
*slot = Some(gpu);
}
Ok(())
}
/// A frame with a fresh NV12 surface of `size`: one that nothing else
/// holds any more, else a new one.
fn output(&mut self, size: (u32, u32), timestamp: Duration) -> Result<Arc<GpuFrame>> {
let ffmpeg = self.ffmpeg;
let index = match self.outputs.iter().position(|o| o.size == size) {
Some(i) => i,
None => {
let pool =
vaapi_pool(ffmpeg, size.0, size.1, ffmpeg.pix.nv12).map_err(Error::Convert)?;
self.outputs.push(Output { size, pool, frames: Vec::new() });
self.outputs.len() - 1
}
};
let output = &mut self.outputs[index];
let free = match output.frames.iter_mut().position(|f| Arc::get_mut(f).is_some()) {
Some(free) => free,
None => {
let surface = Surface::alloc(ffmpeg)?;
output.frames.push(Arc::new(GpuFrame {
width: size.0,
height: size.1,
timestamp,
surface,
}));
output.frames.len() - 1
}
};
let frame = Arc::get_mut(&mut output.frames[free]).expect("nothing else holds it");
frame.timestamp = timestamp;
let api = &ffmpeg.api;
// SAFETY: our frame; unreferencing gives its old surface back (once
// the encoder that referenced it is done), then it takes a new one.
let ret = unsafe {
(api.av_frame_unref)(frame.surface.0);
(api.av_hwframe_get_buffer)(output.pool, frame.surface.0, 0)
};
if ret < 0 {
return Err(Error::Convert(format!("VA-API surface: {}", api.error_text(ret))));
}
Ok(output.frames[free].clone())
}
}
impl Drop for GpuConverter {
fn drop(&mut self) {
self.outputs.clear();
if let Some((mut pool, _)) = self.import.take() {
// SAFETY: our reference.
unsafe { (self.ffmpeg.api.av_buffer_unref)(&mut pool) };
}
}
}
+4
View File
@@ -19,10 +19,14 @@ use std::path::PathBuf;
use std::sync::{Mutex, OnceLock};
pub mod encoder;
mod gpu;
mod layout;
pub mod sys;
mod vpp;
pub(crate) use gpu::Surface;
pub use gpu::{GpuConverter, GpuLayer};
pub use encoder::{
BACKENDS, BackendKind, BackendSpec, BackendStatus, FfmpegEncoder, FfmpegFactory, Input, probe,
};
+1
View File
@@ -199,6 +199,7 @@ api! {
fn av_frame_get_buffer(frame: Ptr, align: c_int) -> c_int;
fn av_frame_make_writable(frame: Ptr) -> c_int;
fn av_frame_unref(frame: Ptr);
fn av_frame_ref(dst: Ptr, src: Ptr) -> c_int;
fn av_opt_set(obj: Ptr, name: *const c_char, val: *const c_char, flags: c_int) -> c_int;
fn av_opt_set_int(obj: Ptr, name: *const c_char, val: i64, flags: c_int) -> c_int;
fn av_opt_set_q(obj: Ptr, name: *const c_char, val: Rational, flags: c_int) -> c_int;
+24 -14
View File
@@ -171,14 +171,12 @@ impl Va {
}
/// A VA-API video processing context that converts RGB surfaces into NV12
/// ones of `width` x `height`.
/// ones, cropping and scaling on the way.
pub struct Converter {
va: &'static Va,
display: Display,
config: c_uint,
context: c_uint,
width: u32,
height: u32,
}
// SAFETY: libva serialises calls per display; the context is used from one
@@ -187,8 +185,8 @@ unsafe impl Send for Converter {}
impl Converter {
/// A context on `display` (FFmpeg's, see
/// [`layout::device_hwctx`](super::layout::device_hwctx)) for output
/// surfaces of `width` x `height`.
/// [`layout::device_hwctx`](super::layout::device_hwctx)) for pictures of
/// up to `width` x `height`.
pub fn new(display: Display, width: u32, height: u32) -> Result<Self, String> {
let va = Va::get()?;
let mut config = 0;
@@ -224,24 +222,36 @@ impl Converter {
unsafe { (va.destroy_config)(display, config) };
return Err(e);
}
Ok(Self { va, display, config, context, width, height })
Ok(Self { va, display, config, context })
}
/// Convert the top-left `width` x `height` of RGB surface `input` into
/// NV12 surface `output` (both of this display): BT.601, limited range,
/// what the encoders signal and the CPU path ([`crate::convert`])
/// produces.
/// Convert the top-left `src` (width, height) of RGB surface `input`
/// into the top-left `dst` of NV12 surface `output` (both of this
/// display), scaled if the two differ: BT.601, limited range, what the
/// encoders signal and the CPU path ([`crate::convert`]) produces.
///
/// Returns once the GPU has read `input`, so a captured buffer can go
/// back to the compositor; `output` is ready for an encoder of the same
/// display, which orders its reads after this.
pub fn convert(&self, input: c_uint, output: c_uint) -> Result<(), String> {
pub fn convert(
&self,
input: c_uint,
src: (u32, u32),
output: c_uint,
dst: (u32, u32),
) -> Result<(), String> {
let va = self.va;
let region = Rectangle { x: 0, y: 0, width: self.width as u16, height: self.height as u16 };
let rect = |(width, height): (u32, u32)| Rectangle {
x: 0,
y: 0,
width: width.min(u32::from(u16::MAX)) as u16,
height: height.min(u32::from(u16::MAX)) as u16,
};
let (src, dst) = (rect(src), rect(dst));
let mut parameters = PipelineParameters {
surface: input,
surface_region: &region,
output_region: &region,
surface_region: &src,
output_region: &dst,
output_background_color: 0xff00_0000,
output_color_standard: COLOR_STANDARD_BT601,
pipeline_flags: 0,
+41
View File
@@ -284,6 +284,47 @@ impl VideoFrame {
}
}
/// A picture in GPU memory: an NV12 VA-API surface, converted and scaled
/// from a captured DMA-BUF on the GPU (`ffmpeg::GpuConverter`, Linux) so
/// that no CPU reads its pixels, for the encoders that take one
/// ([`VideoEncoder::gpu_alignment`](crate::VideoEncoder::gpu_alignment)).
/// Dropping it gives the surface back to its pool. Only this crate makes
/// them.
#[non_exhaustive]
pub struct GpuFrame {
pub width: u32,
pub height: u32,
/// As [`VideoFrame::timestamp`].
pub timestamp: Duration,
#[cfg(feature = "ffmpeg")]
pub(crate) surface: crate::ffmpeg::Surface,
}
impl GpuFrame {
/// The timestamp on the 90 kHz RTP video clock.
pub fn pts_90khz(&self) -> u64 {
(self.timestamp.as_micros() * u128::from(VIDEO_CLOCK_RATE) / 1_000_000) as u64
}
/// The same picture at another time (another reference to the same
/// surface), e.g. to send a still screen again.
pub fn at(&self, timestamp: Duration) -> Self {
Self {
width: self.width,
height: self.height,
timestamp,
#[cfg(feature = "ffmpeg")]
surface: self.surface.new_ref(),
}
}
}
impl std::fmt::Debug for GpuFrame {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "GpuFrame({}x{} at {:?})", self.width, self.height, self.timestamp)
}
}
/// Interleaved 32-bit float audio at [`AUDIO_SAMPLE_RATE`].
#[derive(Clone, Debug, PartialEq)]
pub struct AudioBuffer {
+8
View File
@@ -95,6 +95,14 @@ impl<T> Handoff<T> {
}
}
/// Make the calling thread the consumer that [`put`](Self::put) wakes
/// (what the first [`wait_timeout`](Self::wait_timeout) does), for a
/// thread that waits on several handoffs itself
/// (`std::thread::park_timeout`, then [`take`](Self::take) from each).
pub fn register(&self) {
self.consumer.get_or_init(std::thread::current);
}
/// Wake the consumer and make waits return at once (items can still be
/// taken).
pub fn close(&self) {
+1 -1
View File
@@ -49,7 +49,7 @@ pub use codec::{
VideoEncoder,
};
pub use frame::{
AudioBuffer, FrameData, FrameRef, PixelFormat, PixelsRef, Plane, PlaneRef, VideoFrame,
AudioBuffer, FrameData, FrameRef, GpuFrame, PixelFormat, PixelsRef, Plane, PlaneRef, VideoFrame,
};
pub use queue::{FrameReceiver, FrameSender, frame_channel};
+23 -2
View File
@@ -798,8 +798,10 @@ impl Studio {
wanted.iter().any(|(w, kind, background)| {
w == id
&& input.kind().same_input(kind)
// A background filter is set up when the input starts.
&& input.background().needs_mask() == background.needs_mask()
// A background filter is set up when the input starts,
// with the effect it applies: another effect (or
// strength, image, colour) needs a new input.
&& input.background() == background
})
});
}
@@ -1196,6 +1198,25 @@ mod tests {
assert!(studio.apply(Command::RenameScene { scene: 99, name: "x".into() }).await.is_err());
}
#[tokio::test]
async fn a_new_background_effect_reaches_the_input() {
let studio = Studio::start(one_colour_scene()).await.unwrap();
for background in [
Background::Blur { strength: 0.02 },
Background::Blur { strength: 0.08 },
Background::Colour { colour: Colour::rgb(0, 200, 0) },
Background::Keep,
] {
let change =
SourceChange { background: Some(background.clone()), ..Default::default() };
let command = Command::UpdateSource { scene: 1, source: 1, change: Box::new(change) };
studio.apply(command).await.unwrap();
let graph = lock(&studio.graph);
assert_eq!(graph.inputs.len(), 1);
assert_eq!(graph.inputs[0].1.background(), &background);
}
}
#[tokio::test]
async fn go_live_and_recording_change_the_status() {
let studio = Studio::start(one_colour_scene()).await.unwrap();
+8
View File
@@ -66,8 +66,16 @@ mod tests {
use super::*;
/// Without a notification service this must fail, not hang or panic.
/// Skipped where a session bus exists: on a desktop the notification
/// would really show.
#[tokio::test]
async fn notify_returns() {
let runtime_bus = std::env::var_os("XDG_RUNTIME_DIR")
.is_some_and(|d| std::path::Path::new(&d).join("bus").exists());
if std::env::var_os("DBUS_SESSION_BUS_ADDRESS").is_some() || runtime_bus {
eprintln!("skipped: a D-Bus session bus is configured");
return;
}
let n = Notification { urgent: true, ..Notification::new("Poke", "from a test") };
let result = tokio::time::timeout(Duration::from_secs(10), notify(&n)).await;
assert!(result.is_ok(), "notify hung");
+11
View File
@@ -53,6 +53,7 @@ fn open_settings(dir: &Path, overrides: &[String]) -> Settings {
for key in crate::settings::page_keys() {
prefs.register(key);
}
prefs.register(&crate::studio::STUDIO_UI);
let config = std::env::var_os("VOELIN_CONFIG")
.map(PathBuf::from)
.or_else(|| Some(dir.join("config.toml")).filter(|p| p.exists()));
@@ -419,6 +420,8 @@ pub(crate) struct App {
pub social: crate::social::Social,
/// The settings pages of the new design.
pub pages: crate::settings_pages::Pages,
/// The Stream Studio (studio.rs).
pub studio: crate::studio::StudioState,
}
thread_local! {
@@ -614,6 +617,7 @@ pub fn run(options: RunOptions) -> Result<()> {
uploads: HashMap::new(),
social: Default::default(),
pages: Default::default(),
studio: Default::default(),
};
APP.with(|a| *a.borrow_mut() = Some(app));
crate::bind::wire(&ui);
@@ -900,6 +904,13 @@ impl App {
Event::SettingRejected { key, message } => {
self.set_status(format!("Setting {key}: {message}"));
}
// The Stream Studio's stream (studio.rs).
Event::StreamState { session, state } if self.studio_streams_to(session as i64) => {
self.studio_stream_state(state);
}
Event::StreamViewers { session, viewers } if self.studio_streams_to(session as i64) => {
self.studio_viewers(viewers);
}
event => self.stream_event(event),
}
}
+1
View File
@@ -37,6 +37,7 @@ impl App {
image_cache_mb: cache_mb as f32,
});
bridge.set_image_cache_usage(images::usage_text().into());
self.studio_theme();
}
/// The settings page changed the form: store the keys (they apply
+5 -1
View File
@@ -8,8 +8,11 @@ mod servers;
mod settings;
mod social;
mod streams;
pub(crate) mod studio;
use crate::app::MainWindow;
use slint::ComponentHandle;
use crate::app::{MainWindow, StudioBridge};
/// Connect every callback of the window.
pub(crate) fn wire(ui: &MainWindow) {
@@ -20,4 +23,5 @@ pub(crate) fn wire(ui: &MainWindow) {
emoji::wire(ui);
social::wire(ui);
pages::wire(ui);
studio::wire(&ui.global::<StudioBridge>());
}
+137
View File
@@ -0,0 +1,137 @@
//! The Stream Studio's callbacks, for the main window and for the studio's
//! own window (each has its own StudioBridge global).
use voelin_core::studio::Command;
use crate::app::{StudioBridge, with_app};
/// Slint ids are ints; the studio's are u64.
fn id(value: i32) -> u64 {
u64::try_from(value).unwrap_or(u64::MAX)
}
fn index(value: i32) -> usize {
usize::try_from(value).unwrap_or(usize::MAX)
}
pub(crate) fn wire(bridge: &StudioBridge) {
// From a page's init: run it after the page is built, outside of Slint's
// update.
bridge.on_open(|| {
let _ = slint::invoke_from_event_loop(|| {
with_app(|app| app.studio_open());
});
});
bridge.on_detach(|| {
with_app(|app| app.studio_detach());
});
bridge.on_dock(|| {
with_app(|app| app.studio_dock());
});
bridge.on_select_scene(|scene| {
with_app(|app| app.studio_scene_command(Command::SetActiveScene { scene: id(scene) }));
});
bridge.on_add_scene(|| {
with_app(|app| app.studio_add_scene());
});
bridge.on_rename_scene(|scene, name| {
let name = name.trim().to_owned();
if !name.is_empty() {
with_app(|app| {
app.studio_scene_command(Command::RenameScene { scene: id(scene), name })
});
}
});
bridge.on_remove_scene(|scene| {
with_app(|app| app.studio_scene_command(Command::RemoveScene { scene: id(scene) }));
});
bridge.on_list_sources(|kind| with_app(|app| app.studio_list_sources(&kind)).unwrap_or(false));
bridge.on_add_picked(|_, i| {
with_app(|app| app.studio_add_picked(index(i)));
});
bridge.on_add_source(|form| {
with_app(|app| app.studio_add_source(&form));
});
bridge.on_source_form(|source| {
with_app(|app| app.studio_source_form(id(source))).unwrap_or_default()
});
bridge.on_apply_source(|form| {
with_app(|app| app.studio_apply_source(&form));
});
bridge.on_toggle_source(|source| {
with_app(|app| app.studio_toggle_source(id(source)));
});
bridge.on_source_action(|source, action| {
with_app(|app| app.studio_source_action(id(source), &action));
});
bridge.on_main_source(|kind| {
with_app(|app| app.studio_main_source(&kind));
});
bridge.on_list_audio(|| {
with_app(|app| app.studio_list_audio());
});
bridge.on_add_audio(|i| {
with_app(|app| app.studio_add_audio(index(i)));
});
bridge.on_set_gain(|i, db, done| {
with_app(|app| app.studio_set_gain(index(i), db, done));
});
bridge.on_toggle_mute(|i| {
with_app(|app| app.studio_toggle_mute(index(i)));
});
bridge.on_remove_audio(|i| {
with_app(|app| app.studio_remove_audio(index(i)));
});
bridge.on_edit_form(|key, value| {
with_app(|app| app.studio_edit(&key, &value));
});
bridge.on_set_output(|w, h, fps| {
with_app(|app| app.studio_set_output(&w, &h, &fps));
});
bridge.on_set_layer(|i, layer| {
with_app(|app| app.studio_set_layer(index(i), &layer));
});
bridge.on_add_layer(|| {
with_app(|app| app.studio_add_layer());
});
bridge.on_remove_layer(|i| {
with_app(|app| app.studio_remove_layer(index(i)));
});
bridge.on_advanced_settings(|| {
with_app(|app| app.studio_advanced());
});
bridge.on_save_clip(|| {
with_app(|app| app.studio_save_clip());
});
bridge.on_toggle_recording(|| {
with_app(|app| app.studio_toggle_recording());
});
bridge.on_open_recordings(|| {
with_app(|app| app.studio_open_recordings());
});
bridge.on_go_live(|| {
with_app(|app| app.studio_go_live());
});
bridge.on_end_stream(|| {
with_app(|app| app.studio_end());
});
bridge.on_settings_form(|| with_app(|app| app.studio_settings_form()).unwrap_or_default());
bridge.on_apply_settings(|form| {
with_app(|app| app.studio_apply_settings(&form));
});
bridge.on_respond_viewer(|client, accept| {
with_app(|app| app.studio_respond_viewer(u16::try_from(client).unwrap_or(0), accept));
});
bridge.on_send_chat(|text| {
with_app(|app| app.studio_send_chat(text.to_string()));
});
bridge.on_open_chat(|| {
with_app(|app| app.studio_open_chat());
});
}
+10 -2
View File
@@ -173,6 +173,7 @@ impl App {
if !shown {
self.refresh_servers();
}
self.studio_chat_changed(id, &message.target);
}
/// Messages the engine stored: added or updated by their local id.
@@ -222,6 +223,7 @@ impl App {
if fresh > 0 && !shown {
self.refresh_servers();
}
self.studio_chat_changed(id, target);
}
/// The page of messages before the oldest one shown.
@@ -239,8 +241,14 @@ impl App {
self.refresh_chat();
}
/// The lines of a tab, grouped and with everything the row shows.
fn lines_of(&self, view: &SessionView, tab: &Tab, messages: &[Msg]) -> Vec<ChatLine> {
/// The lines of a tab, grouped and with everything the row shows (also
/// the stream chat of the Stream Studio, studio.rs).
pub(crate) fn lines_of(
&self,
view: &SessionView,
tab: &Tab,
messages: &[Msg],
) -> Vec<ChatLine> {
let gateway = view.gateway_has(feature::PINS)
|| view.gateway_has(feature::REACTIONS)
|| view.gateway_has(feature::TOPICS);
+45 -12
View File
@@ -25,7 +25,13 @@
//! `notifications` (the bell), `join` (join by address), `offline` (an
//! offline message), `picture` (a chat picture opened large), `camera`
//! (the settings' camera preview); settings sections also `account`,
//! `profiles`, `devices`, `notifications`, `integrations`, `advanced`.
//! `profiles`, `devices`, `notifications`, `integrations`, `advanced`;
//! `studio[:<what>]`: the Stream Studio (with `VOELIN_DEMO_UI` a demo
//! studio from synthetic sources), `studio:window` in a window of its own,
//! `studio:live` going live, `studio:record`, or a dialog: `studio:source`,
//! `studio:audio`, `studio:camera`, `studio:scene`, `studio:settings`.
//! A screenshot also saves the studio's window (`<name>-window.png`) and
//! draws it over the main window.
//! - `VOELIN_AUTOWATCH=1`: watch the first stream that shows up.
//! - `VOELIN_AUTOSHARE=test-pattern`: share the test pattern (accepting
//! everyone) once connected to a TeamSpeak 6 server.
@@ -34,7 +40,7 @@ use std::sync::Arc;
use std::time::Duration;
use anyhow::Result;
use slint::ComponentHandle;
use slint::{ComponentHandle, Rgba8Pixel, SharedPixelBuffer};
use voelin_core::gateway::Pin;
use voelin_core::stream::{StreamInfo, StreamKind};
use voelin_core::{
@@ -223,6 +229,12 @@ pub(crate) fn start(ui: &MainWindow, switches: &Switches) -> Running {
app.refresh_pages();
});
}
"studio" => {
if arg != "window" {
nav.invoke_open_studio();
}
with_app(|app| app.studio_dev(arg));
}
// Opened once connected (settings_page.rs).
"client" => {}
other => eprintln!("VOELIN_OPEN: unknown screen {other:?}"),
@@ -257,6 +269,8 @@ pub(crate) fn start(ui: &MainWindow, switches: &Switches) -> Running {
eprintln!("screenshot failed: {e}");
}
let _ = ui.hide();
// Also when the studio's own window is open.
let _ = slint::quit_event_loop();
}
},
);
@@ -266,7 +280,33 @@ pub(crate) fn start(ui: &MainWindow, switches: &Switches) -> Running {
}
fn save_screenshot(ui: &MainWindow, path: &std::path::Path) -> Result<()> {
let image = ui.window().take_snapshot()?;
let mut image = ui.window().take_snapshot()?;
if let Some(studio) = with_app(|app| app.studio_snapshot()).flatten() {
let stem = path.file_stem().unwrap_or_default().to_string_lossy();
save_png(&studio, &path.with_file_name(format!("{stem}-window.png")))?;
paste(&mut image, &studio);
}
save_png(&image, path)
}
/// Draw `top` over the bottom right of `image` with a border, as a second
/// window sits on a desktop.
fn paste(image: &mut SharedPixelBuffer<Rgba8Pixel>, top: &SharedPixelBuffer<Rgba8Pixel>) {
let (w, h) = (image.width() as usize, image.height() as usize);
let (tw, th) = (top.width() as usize, top.height() as usize);
let (x0, y0) = (w.saturating_sub(tw + 24), h.saturating_sub(th + 24));
let border = Rgba8Pixel { r: 0x3f, g: 0x7b, b: 0xff, a: 0xff };
let pixels = image.make_mut_slice();
for y in y0.saturating_sub(1)..(y0 + th + 1).min(h) {
for x in x0.saturating_sub(1)..(x0 + tw + 1).min(w) {
let (ty, tx) = (y.wrapping_sub(y0), x.wrapping_sub(x0));
pixels[y * w + x] =
if ty < th && tx < tw { top.as_slice()[ty * tw + tx] } else { border };
}
}
}
fn save_png(image: &SharedPixelBuffer<Rgba8Pixel>, path: &std::path::Path) -> Result<()> {
let file = std::io::BufWriter::new(std::fs::File::create(path)?);
let mut encoder = png::Encoder::new(file, image.width(), image.height());
encoder.set_color(png::ColorType::Rgba);
@@ -611,14 +651,7 @@ fn demo_social(app: &mut App) {
70,
),
private(311, "demo-2", false, ("Lumen", 2), "Let's run it tonight!".into(), 120),
private(
312,
"demo-5",
false,
("dex", 5),
format!("{}", file_link(2, "map-notes.png", 96_120)),
26 * 60,
),
private(312, "demo-5", false, ("dex", 5), file_link(2, "map-notes.png", 96_120), 26 * 60),
];
for m in lines {
let target = m.message.target.clone();
@@ -937,7 +970,7 @@ fn demo_picture(width: u32, height: u32, seed: u32) -> Vec<u8> {
let castle = (fx > w * 0.36
&& fx < w * 0.52
&& fy > h * 0.38
&& (((fx - w * 0.36) / (w * 0.02)) as u32 % 2 == 0 || fy > h * 0.45))
&& ((((fx - w * 0.36) / (w * 0.02)) as u32).is_multiple_of(2) || fy > h * 0.45))
|| (fx > w * 0.42 && fx < w * 0.46 && fy > h * 0.24);
if fy > near {
c = [6.0, 10.0, 26.0];
+1
View File
@@ -20,6 +20,7 @@ mod settings_page;
mod settings_pages;
mod social;
mod streams;
mod studio;
mod video;
mod vm;
+5
View File
@@ -474,6 +474,11 @@ impl App {
if self.share_busy || self.share.is_some() {
return;
}
if self.studio_streams_to(session) {
self.share_error = "The Stream Studio is live here: end that stream first.".into();
self.refresh_streams();
return;
}
// Typed values (no maximum), else the chosen presets.
let choice = |i: i32, choices: &[u32]| {
choices[usize::try_from(i).unwrap_or(0).min(choices.len() - 1)]
File diff suppressed because it is too large. Load diff
+41 -7
View File
@@ -16,7 +16,8 @@ use voelin_core::media::{
self, AudioSourceSpec, EncoderPreference, Latest, LocalPreview, Streamer, StreamerConfig,
Viewer, peer_config, preferred_codec, stream_codec,
};
use voelin_core::stream::PeerConfig;
use voelin_core::stream::{LayerSpec, PeerConfig};
use voelin_core::studio::Studio;
use voelin_core::{Engine, StreamSink};
/// Whether this build can share and decode video.
@@ -106,12 +107,6 @@ impl Video {
self.codec = codec;
}
/// The codecs in use, e.g. for `Codecs::report` (every encoder backend,
/// what works and why the rest does not) off the UI thread.
pub fn codecs(&self) -> Arc<Codecs> {
self.codecs.clone()
}
/// Whether H.264 works, and a line for the settings page.
pub fn h264_status(&self) -> (bool, String) {
#[cfg(target_os = "android")]
@@ -271,6 +266,45 @@ impl Video {
});
}
/// The codecs, for reconfiguring a running streamer.
pub fn codecs(&self) -> Arc<Codecs> {
self.codecs.clone()
}
/// Encode the Stream Studio's composite ([`Streamer::start_studio`]):
/// from the start, so its recording and replay buffer work before it
/// goes live, and a stream attaches to it like to a capture. `done` runs
/// on the runtime.
pub fn start_studio(
&self,
runtime: &Handle,
studio: Arc<Studio>,
options: CaptureRequest,
layers: Vec<LayerSpec>,
done: impl FnOnce(Result<Streamer, String>) + Send + 'static,
) {
let peer = self.peer_config(PeerConfig::default());
let Some(codec) = stream_codec(&self.codecs, &peer) else {
done(Err("No video encoder is available.".into()));
return;
};
let codecs = self.codecs.clone();
let config = StreamerConfig {
fps: options.fps,
bitrate_kbps: options.bitrate_kbps,
codec,
encoder: self.encoder.clone(),
audio: options.audio,
audio_sources: options.audio_sources,
layers,
..StreamerConfig::default()
};
runtime.spawn(async move {
let result = Streamer::start_studio(&codecs, config, studio).await;
done(result.map_err(|e| e.to_string()));
});
}
/// Decode stream `stream_id` of `session`; `wake` is called (on the
/// decoder thread) when a picture is ready and none is waiting.
pub fn watch(
+1
View File
@@ -8,4 +8,5 @@ pub mod chat;
pub mod list;
pub mod servers;
pub mod social;
pub mod studio;
pub mod tree;
+734
View File
@@ -0,0 +1,734 @@
//! The Stream Studio's view models: scene, source, mixer and layer rows,
//! the header's numbers, the source dialog's form, where new sources go and
//! the overlay sources the stream settings' switches keep in the scenes.
use std::time::Duration;
use voelin_core::settings::{AudioSourceKindSetting, AudioSourceSetting, LayerSetting};
use voelin_core::studio::SourceChange;
use voelin_core::studio::SourceStats;
use voelin_core::studio::scene::{
Align, Background, Colour, Crop, Fit, Scene, Scenes, Source, SourceKind, Transform,
};
use crate::app::{StudioAudio, StudioLayer, StudioScene, StudioSource, StudioSourceForm};
/// The scenes; the live one marked, each with what it shows.
pub fn scenes(scenes: &Scenes) -> Vec<StudioScene> {
let live = scenes.active().map(|s| s.id);
scenes
.scenes
.iter()
.map(|scene| StudioScene {
id: scene.id as i32,
name: scene.name.clone().into(),
detail: summary(scene).into(),
live: Some(scene.id) == live,
kind: scene.sources.first().map_or("", |s| s.kind.label()).into(),
})
.collect()
}
/// "Screen + Camera": the names of the visible sources, back first (the
/// main picture, then what is over it).
fn summary(scene: &Scene) -> String {
let names: Vec<&str> = scene.sources.iter().filter(|s| s.visible).map(Source::label).collect();
if names.is_empty() { "Empty".into() } else { names.join(" + ") }
}
pub fn background_name(background: &Background) -> &'static str {
match background {
Background::Keep => "keep",
Background::Blur { .. } => "blur",
Background::Image { .. } => "image",
Background::Colour { .. } => "colour",
}
}
/// The sources of `scene`, front first, with what the studio reports.
pub fn sources(scene: Option<&Scene>, stats: &[SourceStats]) -> Vec<StudioSource> {
let Some(scene) = scene else { return Vec::new() };
let last = scene.sources.len().saturating_sub(1);
scene
.sources
.iter()
.enumerate()
.rev()
.map(|(i, s)| {
let stat = stats.iter().find(|st| st.id == s.id);
let info = stat
.filter(|st| st.width > 0)
.map(|st| format!("{}×{} · {:.0} fps", st.width, st.height, st.fps))
.unwrap_or_default();
StudioSource {
id: s.id as i32,
name: s.label().into(),
kind: s.kind.label().into(),
visible: s.visible,
locked: s.locked,
background: background_name(&s.background).into(),
error: stat.and_then(|st| st.error.clone()).unwrap_or_default().into(),
info: info.into(),
front: i == last,
back: i == 0,
}
})
.collect()
}
/// Linear gain as dB (silence: -60).
pub fn gain_db(gain: f32) -> f32 {
if gain > 0.001 { 20.0 * gain.log10() } else { -60.0 }
}
/// dB as linear gain.
pub fn gain_linear(db: f32) -> f32 {
10f32.powf(db / 20.0)
}
/// Name, detail and icon kind of an audio source.
pub fn audio_label(kind: &AudioSourceKindSetting) -> (String, String, &'static str) {
match kind {
AudioSourceKindSetting::Microphone => ("Microphone".into(), String::new(), "microphone"),
AudioSourceKindSetting::Desktop => {
("Desktop Audio".into(), "without Voelin".into(), "desktop")
}
AudioSourceKindSetting::App { name: Some(name), .. } => {
("App Audio".into(), name.clone(), "app")
}
AudioSourceKindSetting::App { pid, .. } => {
("App Audio".into(), pid.map(|p| format!("process {p}")).unwrap_or_default(), "app")
}
AudioSourceKindSetting::Window => {
("Window Audio".into(), "the shared window".into(), "window-audio")
}
AudioSourceKindSetting::Synthetic { frequency } => {
("Test Tone".into(), format!("{frequency} Hz"), "tone")
}
}
}
/// What the mixer says about one source now.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct AudioLive {
/// Peak in dBFS.
pub level: f32,
pub error: Option<String>,
}
/// The mixer rows: the stream's audio sources with their meters.
pub fn audio(sources: &[AudioSourceSetting], live: &[Option<AudioLive>]) -> Vec<StudioAudio> {
sources
.iter()
.enumerate()
.map(|(i, s)| {
let (name, detail, kind) = audio_label(&s.kind);
let live = live.get(i).cloned().flatten();
StudioAudio {
name: name.into(),
detail: detail.into(),
kind: kind.into(),
gain_db: gain_db(s.gain),
muted: s.muted,
level: live.as_ref().map_or(-100.0, |l| l.level),
error: live.and_then(|l| l.error).unwrap_or_default().into(),
}
})
.collect()
}
/// A number without trailing zeros ("0.5", "1").
fn short(value: f32) -> String {
let text = format!("{value:.3}");
text.trim_end_matches('0').trim_end_matches('.').to_owned()
}
/// The simulcast layers as rows (bitrates in kbit/s).
pub fn layers(layers: &[LayerSetting]) -> Vec<StudioLayer> {
layers
.iter()
.map(|l| StudioLayer {
size: l.size.map(|(w, h)| format!("{w}x{h}")).unwrap_or_default().into(),
scale: short(l.scale).into(),
fps: l.max_fps.map(|f| f.to_string()).unwrap_or_default().into(),
bitrate: (l.bitrate / 1000).to_string().into(),
min_bitrate: (l.min_bitrate / 1000).to_string().into(),
})
.collect()
}
/// A layer as typed into `old`: a size ("1280x720") or a scale ("0.5",
/// "0.5×", "50%"), a frame-rate cap (empty: none), kbit/s. Any numbers.
pub fn parse_layer(row: &StudioLayer, old: &LayerSetting) -> Result<LayerSetting, String> {
let mut layer = old.clone();
let size = row.size.trim();
let parts: Vec<&str> = size.split(['x', 'X', '×']).map(str::trim).collect();
match parts.as_slice() {
[w, h] if !w.is_empty() && !h.is_empty() => {
let (w, h) = (w.parse::<u32>(), h.parse::<u32>());
let (Ok(w), Ok(h)) = (w, h) else { return Err(format!("{size:?} is not a size")) };
layer.size = Some((w, h));
}
_ => {
let text = size.trim_end_matches(['x', 'X', '×', '%']).trim();
let mut scale: f32 = text.parse().map_err(|_| format!("{size:?} is not a size"))?;
if size.ends_with('%') {
scale /= 100.0;
}
layer.size = None;
layer.scale = scale;
}
}
let fps = row.fps.trim();
layer.max_fps =
if fps.is_empty() { None } else { Some(fps.parse().map_err(|_| "a frame rate")?) };
let kbps: u64 = row.bitrate.trim().parse().map_err(|_| "kbit/s as a number")?;
layer.bitrate = kbps * 1000;
Ok(layer)
}
/// A layer below the last one: half its size, a quarter of its bitrate.
pub fn next_layer(layers: &[LayerSetting], bitrate_kbps: u32) -> LayerSetting {
match layers.last() {
None => LayerSetting { bitrate: u64::from(bitrate_kbps) * 1000, ..LayerSetting::default() },
Some(last) => LayerSetting {
id: None,
scale: last.size.map_or(last.scale / 2.0, |_| 0.5),
size: last.size.map(|(w, h)| (w / 2, h / 2)),
bitrate: (last.bitrate / 4).max(100_000),
rid: None,
..last.clone()
},
}
}
/// 0: not live, 1 poor … 4 excellent; how the stream gets out. The worse
/// of the frame rate made (against the output's) and the bandwidth the
/// viewers have (their estimates against the bitrate sent).
pub fn quality(
live: bool,
wanted_fps: u32,
fps: f64,
bandwidth: Option<f64>,
) -> (i32, &'static str) {
if !live {
return (0, "Not live");
}
let rate = if wanted_fps == 0 { 1.0 } else { fps / f64::from(wanted_fps) };
let worst = rate.min(bandwidth.unwrap_or(1.0));
match worst {
w if w >= 0.9 => (4, "Excellent Connection"),
w if w >= 0.75 => (3, "Good Connection"),
w if w >= 0.5 => (2, "Fair Connection"),
_ => (1, "Poor Connection"),
}
}
/// 8250 → "8,250".
pub fn thousands(n: u64) -> String {
let digits = n.to_string();
let mut out = String::new();
for (i, c) in digits.chars().enumerate() {
if i > 0 && (digits.len() - i).is_multiple_of(3) {
out.push(',');
}
out.push(c);
}
out
}
/// "1080p • 60 FPS • 8,250 kbps".
pub fn format_line(height: u32, fps: u32, kbps: u64) -> String {
format!("{height}p • {fps} FPS • {} kbps", thousands(kbps))
}
/// "00:12:34".
pub fn clock(d: Duration) -> String {
let s = d.as_secs();
format!("{:02}:{:02}:{:02}", s / 3600, s / 60 % 60, s % 60)
}
/// "#rrggbb" or "#rrggbbaa" (the # optional).
pub fn parse_colour(text: &str) -> Option<Colour> {
let hex = text.trim().trim_start_matches('#');
if !matches!(hex.len(), 6 | 8) || !hex.is_ascii() {
return None;
}
let byte = |i: usize| u8::from_str_radix(&hex[i..i + 2], 16).ok();
let a = if hex.len() == 8 { byte(6)? } else { 255 };
Some(Colour::rgba(byte(0)?, byte(2)?, byte(4)?, a))
}
pub fn colour_text(c: Colour) -> String {
if c.a == 255 {
format!("#{:02x}{:02x}{:02x}", c.r, c.g, c.b)
} else {
format!("#{:02x}{:02x}{:02x}{:02x}", c.r, c.g, c.b, c.a)
}
}
fn number(value: f32) -> String {
short(value)
}
/// The source dialog's form for `source`.
pub fn form(source: &Source) -> StudioSourceForm {
let t = &source.transform;
let mut form = StudioSourceForm {
id: source.id as i32,
name: source.name.clone().into(),
kind: source.kind.label().into(),
x: number(t.x).into(),
y: number(t.y).into(),
width: t.width.map(number).unwrap_or_default().into(),
height: t.height.map(number).unwrap_or_default().into(),
scale: number(t.scale).into(),
fit: match t.fit {
Fit::Contain => "contain",
Fit::Cover => "cover",
Fit::Stretch => "stretch",
}
.into(),
crop_left: source.crop.left.to_string().into(),
crop_top: source.crop.top.to_string().into(),
crop_right: source.crop.right.to_string().into(),
crop_bottom: source.crop.bottom.to_string().into(),
opacity: source.opacity * 100.0,
locked: source.locked,
visible: source.visible,
background: background_name(&source.background).into(),
blur: "4".into(),
background_colour: "#00b140".into(),
..StudioSourceForm::default()
};
match &source.background {
Background::Blur { strength } => form.blur = number(strength * 100.0).into(),
Background::Image { path } => form.background_path = path.display().to_string().into(),
Background::Colour { colour } => form.background_colour = colour_text(*colour).into(),
Background::Keep => {}
}
match &source.kind {
SourceKind::Text { text, size_px, colour, .. } => {
form.text = text.replace('\n', "\\n").into();
form.text_size = number(*size_px).into();
form.colour = colour_text(*colour).into();
}
SourceKind::Colour { colour, .. } => form.colour = colour_text(*colour).into(),
SourceKind::Image { path } => form.path = path.display().to_string().into(),
SourceKind::Camera { mirror, .. } => form.mirror = *mirror,
_ => {}
}
form
}
fn parse_f32(text: &str, what: &str) -> Result<f32, String> {
text.trim()
.parse::<f32>()
.ok()
.filter(|v| v.is_finite())
.ok_or_else(|| format!("{what}: a number"))
}
/// An optional size: empty is `None`.
fn parse_size(text: &str, what: &str) -> Result<Option<f32>, String> {
if text.trim().is_empty() {
return Ok(None);
}
let v = parse_f32(text, what)?;
if v > 0.0 { Ok(Some(v)) } else { Err(format!("{what}: above 0")) }
}
fn parse_crop(text: &str) -> Result<u32, String> {
if text.trim().is_empty() {
return Ok(0);
}
text.trim().parse().map_err(|_| "crop: whole pixels".to_owned())
}
fn transform(form: &StudioSourceForm) -> Result<Transform, String> {
let scale = if form.scale.trim().is_empty() { 1.0 } else { parse_f32(&form.scale, "scale")? };
if scale <= 0.0 {
return Err("scale: above 0".into());
}
Ok(Transform {
x: parse_f32(&form.x, "X").unwrap_or(0.0),
y: parse_f32(&form.y, "Y").unwrap_or(0.0),
width: parse_size(&form.width, "width")?,
height: parse_size(&form.height, "height")?,
scale,
fit: match form.fit.as_str() {
"cover" => Fit::Cover,
"stretch" => Fit::Stretch,
_ => Fit::Contain,
},
})
}
fn background(form: &StudioSourceForm) -> Result<Background, String> {
Ok(match form.background.as_str() {
"blur" => Background::Blur { strength: parse_f32(&form.blur, "blur")?.max(0.0) / 100.0 },
"image" if !form.background_path.trim().is_empty() => {
Background::Image { path: form.background_path.trim().into() }
}
"image" => return Err("background image: a file".into()),
"colour" => Background::Colour {
colour: parse_colour(&form.background_colour).ok_or("background colour: #rrggbb")?,
},
_ => Background::Keep,
})
}
/// What `form` changes in `old` (only what differs).
pub fn change(form: &StudioSourceForm, old: &Source) -> Result<SourceChange, String> {
let transform = transform(form)?;
let crop = Crop {
left: parse_crop(&form.crop_left)?,
top: parse_crop(&form.crop_top)?,
right: parse_crop(&form.crop_right)?,
bottom: parse_crop(&form.crop_bottom)?,
};
let kind = kind(form, Some(&old.kind))?;
let background = background(form)?;
let opacity = (form.opacity / 100.0).clamp(0.0, 1.0);
let differs = |a: bool| a.then_some(());
Ok(SourceChange {
name: differs(form.name.as_str() != old.name).map(|_| form.name.to_string()),
kind: differs(kind != old.kind).map(|_| kind),
transform: differs(transform != old.transform).map(|_| transform),
crop: differs(crop != old.crop).map(|_| crop),
opacity: differs((opacity - old.opacity).abs() > f32::EPSILON).map(|_| opacity),
visible: differs(form.visible != old.visible).map(|_| form.visible),
locked: differs(form.locked != old.locked).map(|_| form.locked),
background: differs(background != old.background).map(|_| background),
})
}
/// The kind as the form says: text, colour and image from their fields, a
/// camera's mirroring, anything else as it was.
fn kind(form: &StudioSourceForm, old: Option<&SourceKind>) -> Result<SourceKind, String> {
Ok(match (form.kind.as_str(), old) {
("text", old) => {
let (font, backdrop, align, padding) = match old {
Some(SourceKind::Text { font, backdrop, align, padding, .. }) => {
(font.clone(), *backdrop, *align, *padding)
}
_ => (None, Colour::CLEAR, Align::Left, 0),
};
let size_px = parse_f32(&form.text_size, "text size")?;
if size_px <= 0.0 {
return Err("text size: above 0".into());
}
SourceKind::Text {
text: form.text.replace("\\n", "\n"),
font,
size_px,
colour: parse_colour(&form.colour).ok_or("colour: #rrggbb")?,
backdrop,
align,
padding,
}
}
("colour", old) => SourceKind::Colour {
colour: parse_colour(&form.colour).ok_or("colour: #rrggbb")?,
size: match old {
Some(SourceKind::Colour { size, .. }) => *size,
_ => (1920, 1080),
},
},
("image", _) if form.path.trim().is_empty() => return Err("image: a file".into()),
("image", _) => SourceKind::Image { path: form.path.trim().into() },
(_, Some(SourceKind::Camera { device, size, fps, .. })) => SourceKind::Camera {
device: device.clone(),
size: *size,
fps: *fps,
mirror: form.mirror,
},
(_, Some(old)) => old.clone(),
(other, None) => return Err(format!("cannot add a {other} source here")),
})
}
/// A new text, colour or image source from the dialog (id 0: the
/// controller gives it one).
pub fn new_source(form: &StudioSourceForm, output: (u32, u32)) -> Result<Source, String> {
let kind = kind(form, None)?;
let mut source = Source::new(0, kind);
source.name = form.name.trim().to_owned();
source.transform = if form.kind == "colour" {
Transform::full(output.0, output.1)
} else {
let mut t = placement(&source.kind, output);
if let Ok(x) = parse_f32(&form.x, "X") {
t.x = x;
}
if let Ok(y) = parse_f32(&form.y, "Y") {
t.y = y;
}
t
};
source.opacity = (form.opacity / 100.0).clamp(0.0, 1.0);
Ok(source)
}
/// Where a new source goes in a `w` x `h` picture: captures fill it
/// (cropping what does not fit), a camera sits in the bottom right corner,
/// text at the bottom left, images at their own size in the top left.
pub fn placement(kind: &SourceKind, (w, h): (u32, u32)) -> Transform {
let (w, h) = (w as f32, h as f32);
match kind {
SourceKind::Camera { .. } => {
let width = (w * 0.25).round();
let height = (width * 9.0 / 16.0).round();
let margin = (h * 0.03).round();
Transform {
fit: Fit::Cover,
..Transform::box_at(w - width - margin, h - height - margin, width, height)
}
}
SourceKind::Text { .. } => {
Transform { x: (w * 0.03).round(), y: (h * 0.8).round(), ..Transform::default() }
}
SourceKind::Image { .. } => Transform::default(),
_ => Transform { fit: Fit::Cover, ..Transform::box_at(0.0, 0.0, w, h) },
}
}
/// A source the stream settings' switches keep: its name, and its text
/// (`None`: switched off, so it is removed).
#[derive(Clone, Debug, PartialEq)]
pub struct Overlay {
pub name: &'static str,
pub text: Option<String>,
}
pub const OVERLAY_VIEWERS: &str = "Viewer count";
pub const OVERLAY_CHAT: &str = "Chat overlay";
pub const OVERLAY_NOW_PLAYING: &str = "Now playing";
fn overlay_kind(name: &str, text: &str) -> SourceKind {
SourceKind::Text {
text: text.to_owned(),
font: None,
size_px: if name == OVERLAY_CHAT { 26.0 } else { 34.0 },
colour: Colour::WHITE,
backdrop: Colour::rgba(6, 10, 24, 170),
align: Align::Left,
padding: 14,
}
}
/// Where an overlay starts (people can move it): the viewer count at the
/// top right (by an estimate of its width), the chat at the left, what is
/// on above the bottom left. Clear of the corners the studio's own badges
/// cover in the preview.
fn overlay_place(name: &str, text: &str, (w, h): (u32, u32)) -> Transform {
let (w, h) = (w as f32, h as f32);
let margin = (w * 0.025).round();
let (x, y) = match name {
OVERLAY_VIEWERS => {
let wide = text.chars().count() as f32 * 34.0 * 0.58 + 28.0;
(w - margin - wide, h * 0.14)
}
OVERLAY_CHAT => (margin, h * 0.3),
_ => (margin, h * 0.7),
};
Transform { x: x.max(0.0).round(), y: y.round(), ..Transform::default() }
}
/// Make the scenes hold `wanted`: an overlay that is on is added to the live
/// scene if it has none, and its text follows in every scene; one that is
/// off is removed everywhere. Overlays are found by their names, so a
/// person can move them like any source. Returns whether anything changed.
pub fn apply_overlays(scenes: &mut Scenes, wanted: &[Overlay]) -> bool {
let size = scenes.size();
let live = scenes.active().map(|s| s.id);
let mut changed = false;
for overlay in wanted {
match &overlay.text {
None => {
for scene in &mut scenes.scenes {
let before = scene.sources.len();
scene.sources.retain(|s| s.name != overlay.name);
changed |= scene.sources.len() != before;
}
}
Some(text) => {
for scene in &mut scenes.scenes {
for source in scene.sources.iter_mut().filter(|s| s.name == overlay.name) {
if let SourceKind::Text { text: shown, .. } = &mut source.kind
&& shown != text
{
shown.clone_from(text);
changed = true;
}
}
}
let Some(scene) = live.and_then(|id| scenes.scene_mut(id)) else { continue };
if !scene.sources.iter().any(|s| s.name == overlay.name) {
let id = scene.next_source_id();
scene.sources.push(Source {
name: overlay.name.into(),
transform: overlay_place(overlay.name, text, size),
..Source::new(id, overlay_kind(overlay.name, text))
});
changed = true;
}
}
}
}
changed
}
#[cfg(test)]
mod tests {
use super::*;
fn scene_with(names: &[&str]) -> Scenes {
let mut scene = Scene::new(1, "Main");
for (i, name) in names.iter().enumerate() {
let kind = SourceKind::Colour { colour: Colour::BLACK, size: (16, 16) };
scene.sources.push(Source { name: (*name).into(), ..Source::new(i as u64 + 1, kind) });
}
Scenes { scenes: vec![scene, Scene::new(2, "Break")], active: 1, ..Scenes::default() }
}
#[test]
fn rows_show_scenes_and_sources_front_first() {
let scenes = scene_with(&["Screen", "Camera"]);
let rows = super::scenes(&scenes);
assert_eq!(rows.len(), 2);
assert!(rows[0].live && !rows[1].live);
assert_eq!(rows[0].detail, "Screen + Camera");
assert_eq!(rows[1].detail, "Empty");
let sources = super::sources(scenes.active(), &[]);
assert_eq!(
sources.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(),
["Camera", "Screen"]
);
assert!(sources[0].front && !sources[0].back && sources[1].back);
}
#[test]
fn numbers_for_the_header() {
assert_eq!(thousands(8250), "8,250");
assert_eq!(thousands(1_234_567), "1,234,567");
assert_eq!(thousands(999), "999");
assert_eq!(format_line(1080, 60, 8250), "1080p • 60 FPS • 8,250 kbps");
assert_eq!(clock(Duration::from_secs(12 * 60 + 34)), "00:12:34");
assert_eq!(clock(Duration::from_secs(3 * 3600 + 5)), "03:00:05");
assert_eq!(quality(false, 60, 60.0, None).0, 0);
assert_eq!(quality(true, 60, 59.0, None).0, 4);
assert_eq!(quality(true, 60, 59.0, Some(0.6)).0, 2);
assert_eq!(quality(true, 60, 20.0, Some(1.0)).0, 1);
}
#[test]
fn gains_and_colours_round_trip() {
assert!((gain_db(1.0)).abs() < 1e-6);
assert!((gain_db(gain_linear(-6.0)) + 6.0).abs() < 1e-4);
assert_eq!(gain_db(0.0), -60.0);
let c = parse_colour("#ff8000").unwrap();
assert_eq!(c, Colour::rgb(255, 128, 0));
assert_eq!(colour_text(c), "#ff8000");
assert_eq!(parse_colour("10203040"), Some(Colour::rgba(16, 32, 48, 64)));
assert_eq!(parse_colour("#ff80"), None);
assert_eq!(parse_colour("#gg0000"), None);
}
#[test]
fn layers_as_typed() {
let old = LayerSetting::default();
let row = |size: &str, fps: &str, kbps: &str| StudioLayer {
size: size.into(),
fps: fps.into(),
bitrate: kbps.into(),
..StudioLayer::default()
};
let l = parse_layer(&row("1280x720", "30", "2500"), &old).unwrap();
assert_eq!((l.size, l.max_fps, l.bitrate), (Some((1280, 720)), Some(30), 2_500_000));
let l = parse_layer(&row("0.5×", "", "800"), &old).unwrap();
assert_eq!((l.size, l.scale, l.max_fps), (None, 0.5, None));
assert_eq!(parse_layer(&row("50%", "", "800"), &old).unwrap().scale, 0.5);
assert!(parse_layer(&row("big", "", "800"), &old).is_err());
assert!(parse_layer(&row("1", "", "fast"), &old).is_err());
let rows = layers(&[l]);
assert_eq!((rows[0].scale.as_str(), rows[0].bitrate.as_str()), ("0.5", "800"));
let below = next_layer(&[LayerSetting { bitrate: 8_000_000, ..old.clone() }], 8000);
assert_eq!((below.scale, below.bitrate), (0.5, 2_000_000));
}
#[test]
fn the_source_form_changes_only_what_differs() {
let mut source = Source::new(
3,
SourceKind::Text {
text: "Hello\nthere".into(),
font: None,
size_px: 48.0,
colour: Colour::WHITE,
backdrop: Colour::CLEAR,
align: Align::Center,
padding: 4,
},
);
source.transform = Transform::box_at(10.0, 20.0, 300.0, 100.0);
let mut f = form(&source);
assert_eq!(f.text, "Hello\\nthere");
assert_eq!((f.x.as_str(), f.width.as_str()), ("10", "300"));
assert_eq!(change(&f, &source).unwrap(), SourceChange::default());
f.x = "40".into();
f.opacity = 50.0;
f.text = "Bye".into();
let c = change(&f, &source).unwrap();
assert_eq!(c.transform.unwrap().x, 40.0);
assert_eq!(c.opacity, Some(0.5));
let Some(SourceKind::Text { text, align, padding, .. }) = c.kind else { panic!() };
assert_eq!((text.as_str(), align, padding), ("Bye", Align::Center, 4));
f.width = "-1".into();
assert!(change(&f, &source).is_err());
}
#[test]
fn new_sources_are_placed_by_kind() {
let camera =
SourceKind::Camera { device: String::new(), size: None, fps: None, mirror: false };
let t = placement(&camera, (1920, 1080));
assert_eq!((t.width, t.height, t.fit), (Some(480.0), Some(270.0), Fit::Cover));
assert!(t.x + 480.0 < 1920.0 && t.y + 270.0 < 1080.0);
let screen = SourceKind::Screen { monitor: 0, backend: None, cursor: true };
assert_eq!(placement(&screen, (1920, 1080)).width, Some(1920.0));
let form = StudioSourceForm {
kind: "colour".into(),
name: "Slate".into(),
colour: "#101a3c".into(),
opacity: 100.0,
..Default::default()
};
let s = new_source(&form, (1280, 720)).unwrap();
assert_eq!((s.name.as_str(), s.transform.width), ("Slate", Some(1280.0)));
assert!(new_source(&StudioSourceForm { kind: "image".into(), ..form }, (1, 1)).is_err());
}
#[test]
fn overlays_follow_the_switches() {
let mut scenes = scene_with(&["Screen"]);
let on = |text: &str| Overlay { name: OVERLAY_VIEWERS, text: Some(text.into()) };
assert!(apply_overlays(&mut scenes, &[on("3 watching")]));
let live = &scenes.scenes[0];
assert_eq!(live.sources.len(), 2);
assert_eq!(live.sources[1].name, OVERLAY_VIEWERS);
// Nothing to do the second time; the text follows.
assert!(!apply_overlays(&mut scenes, &[on("3 watching")]));
assert!(apply_overlays(&mut scenes, &[on("4 watching")]));
let SourceKind::Text { text, .. } = &scenes.scenes[0].sources[1].kind else { panic!() };
assert_eq!(text, "4 watching");
// A scene switch adds it to the new live scene too; off removes all.
scenes.active = 2;
assert!(apply_overlays(&mut scenes, &[on("4 watching")]));
assert_eq!(scenes.scenes[1].sources.len(), 1);
assert!(apply_overlays(&mut scenes, &[Overlay { name: OVERLAY_VIEWERS, text: None }]));
assert_eq!(scenes.scenes[0].sources.len(), 1);
assert!(scenes.scenes[1].sources.is_empty());
assert!(scenes.check().is_ok());
}
}
+10 -1
View File
@@ -31,11 +31,16 @@ import { ServerLinks, EventsPage, EventDialog } from "screens/events.slint";
import { NotificationsPanel, SearchPalette, Lightbox } from "screens/overlays.slint";
import { MobileServers, ActivityPage, YouPage } from "screens/mobile.slint";
import { BookmarkDialog, ShareDialog, ClientAudioDialog, AboutDialog } from "screens/dialogs.slint";
import { StudioBridge } from "studio-bridge.slint";
import { StudioPage, MobileStudio } from "screens/studio.slint";
// Rust reaches the globals and structs through this file.
export * from "bridge.slint";
export { Theme } from "theme.slint";
export { Nav, Page, MobileTab, SettingsSection } from "nav.slint";
// The Stream Studio: its data, and its own window (src/studio.rs).
export { StudioBridge, StudioNav, StudioScene, StudioSource, StudioAudio, StudioLayer, StudioViewer, StudioPick, StudioStatus, StudioForm, StudioSourceForm, StudioSettingsForm } from "studio-bridge.slint";
export { StudioWindow } from "studio-window.slint";
export component MainWindow inherits Window {
title: Bridge.app-name;
@@ -122,7 +127,7 @@ export component MainWindow inherits Window {
if !root.chrome: StreamViewer { }
if !Nav.narrow && root.chrome: DesktopShell {
context: Nav.page == Page.settings ? @tr("Settings") : "";
context: Nav.page == Page.settings ? @tr("Settings") : Nav.page == Page.studio ? @tr("Stream Studio") : "";
if Nav.page == Page.home: Sidebar {
HomeNav { }
Rectangle { vertical-stretch: 1; }
@@ -203,6 +208,9 @@ export component MainWindow inherits Window {
horizontal-stretch: 1;
SettingsPage { }
}
if Nav.page == Page.studio && !StudioBridge.status.detached: StudioPage {
horizontal-stretch: 1;
}
}
if Nav.narrow && root.chrome: MobileShell {
@@ -252,6 +260,7 @@ export component MainWindow inherits Window {
}
if Nav.page == Page.server && Nav.mobile-tab == MobileTab.activity: ActivityPage { }
if Nav.page == Page.server && Nav.mobile-tab == MobileTab.you: YouPage { }
if Nav.page == Page.studio && !StudioBridge.status.detached: MobileStudio { }
}
}
}
@@ -0,0 +1,18 @@
<!-- @license lucide-static v1.48.0 - ISC -->
<svg
class="lucide lucide-app-window"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<rect x="2" y="4" width="20" height="16" rx="2" />
<path d="M10 4v4" />
<path d="M2 8h20" />
<path d="M6 4v4" />
</svg>

After

Width:  |  Height:  |  Size: 410 B

+16
View File
@@ -0,0 +1,16 @@
<!-- @license lucide-static v1.48.0 - ISC -->
<svg
class="lucide lucide-crop"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M6 2v14a2 2 0 0 0 2 2h14" />
<path d="M18 22V8a2 2 0 0 0-2-2H2" />
</svg>

After

Width:  |  Height:  |  Size: 363 B

+4 -2
View File
@@ -1,4 +1,4 @@
<!-- @license lucide-react v0.563.0 - ISC -->
<!-- @license lucide-static v1.48.0 - ISC -->
<svg
class="lucide lucide-layers"
xmlns="http://www.w3.org/2000/svg"
@@ -11,5 +11,7 @@
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z" />
<path d="M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12" />
<path d="M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17" />
</svg>

Before

Width:  |  Height:  |  Size: 286 B

After

Width:  |  Height:  |  Size: 587 B

+3 -1
View File
@@ -5,6 +5,7 @@
export global Icons {
out property <image> activity: @image-url("assets/icons/activity.svg");
out property <image> app-window: @image-url("assets/icons/app-window.svg");
out property <image> arrow-left: @image-url("assets/icons/arrow-left.svg");
out property <image> arrow-right: @image-url("assets/icons/arrow-right.svg");
out property <image> at-sign: @image-url("assets/icons/at-sign.svg");
@@ -28,6 +29,7 @@ export global Icons {
out property <image> coffee: @image-url("assets/icons/coffee.svg");
out property <image> compass: @image-url("assets/icons/compass.svg");
out property <image> copy: @image-url("assets/icons/copy.svg");
out property <image> crop: @image-url("assets/icons/crop.svg");
out property <image> crown: @image-url("assets/icons/crown.svg");
out property <image> download: @image-url("assets/icons/download.svg");
out property <image> more-vertical: @image-url("assets/icons/ellipsis-vertical.svg");
@@ -54,6 +56,7 @@ export global Icons {
out property <image> image: @image-url("assets/icons/image.svg");
out property <image> info: @image-url("assets/icons/info.svg");
out property <image> keyboard: @image-url("assets/icons/keyboard.svg");
out property <image> layers: @image-url("assets/icons/layers.svg");
out property <image> layout-grid: @image-url("assets/icons/layout-grid.svg");
out property <image> leaf: @image-url("assets/icons/leaf.svg");
out property <image> library: @image-url("assets/icons/library.svg");
@@ -134,7 +137,6 @@ export global Icons {
out property <image> id-card: @image-url("assets/icons/id-card.svg");
out property <image> inbox: @image-url("assets/icons/inbox.svg");
out property <image> key-round: @image-url("assets/icons/key-round.svg");
out property <image> layers: @image-url("assets/icons/layers.svg");
out property <image> mail: @image-url("assets/icons/mail.svg");
out property <image> megaphone: @image-url("assets/icons/megaphone.svg");
out property <image> message-square-plus: @image-url("assets/icons/message-square-plus.svg");
+12
View File
@@ -3,6 +3,7 @@
// development switch VOELIN_OPEN (src/dev.rs).
import { Bridge, BookmarkForm, ShareForm, EventForm, OfflineForm } from "bridge.slint";
import { StudioBridge } from "studio-bridge.slint";
export enum Page {
// Welcome page: servers at a glance.
@@ -18,6 +19,8 @@ export enum Page {
library,
// A server's scheduled events (gateway `events`).
events,
// The Stream Studio (scenes, preview, mixer, going live).
studio,
}
// Sections of the settings page (`settings-section` takes these numbers).
@@ -221,6 +224,15 @@ export global Nav {
}
}
// The Stream Studio: its page, or its window when it has one.
public function open-studio() {
if StudioBridge.status.detached {
StudioBridge.open();
} else {
show(Page.studio);
}
}
// The pins and the topics share the drawer, so opening one closes the
// other.
public function show-pins(on: bool) {
File diff suppressed because it is too large. Load diff
+662
View File
@@ -0,0 +1,662 @@
// The Stream Studio in the main window (desktop and phone). The pieces are
// in studio-parts.slint; the detached window is studio-window.slint.
import { Theme } from "../theme.slint";
import { Icons } from "../icons.slint";
import { Bridge } from "../bridge.slint";
import { Nav, Page } from "../nav.slint";
import { StudioBridge, StudioNav } from "../studio-bridge.slint";
import { Icon, Button, ButtonKind, IconButton, Avatar, Status, TextField, Select, Slider, Meter, Divider, ScrollView } from "../components/index.slint";
import { StudioKinds, StudioPanel, PanelTitle, ScenesCard, SourcesCard, StudioPreview, StudioHeader, StudioMark, MixerCard, StudioChat, StreamSettings, DestinationSelect, StudioActions, ViewerRequests, StudioDialogs } from "studio-parts.slint";
// Who streams, at the bottom left.
component StudioUser inherits HorizontalLayout {
spacing: Theme.space-3;
VerticalLayout {
alignment: center;
Avatar {
size: 38px;
initials: Bridge.nickname != "" ? "" : "?";
tint: Theme.accent;
label: Bridge.nickname;
crown: StudioBridge.status.live;
status: Bridge.voice-connected ? Status.online : Status.offline;
Icon {
source: Icons.user;
size: 20px;
tint: #ffffff;
visible: Bridge.nickname != "";
}
}
}
VerticalLayout {
alignment: center;
horizontal-stretch: 1;
Text {
text: Bridge.nickname != "" ? Bridge.nickname : Bridge.app-name;
color: Theme.text;
font-weight: Theme.weight-semibold;
overflow: elide;
}
Text {
text: StudioBridge.status.live ? @tr("Live") : Bridge.voice-connected ? @tr("Online") : @tr("Offline");
color: StudioBridge.status.live ? Theme.live : Theme.text-muted;
font-size: Theme.font-xs;
}
}
}
// The studio as a page of the main window: scenes and sources, the
// preview with the mixer and the chat, the stream settings, the bottom bar.
export component StudioPage inherits Rectangle {
init => { StudioBridge.open(); }
VerticalLayout {
spacing: Theme.space-3;
HorizontalLayout {
vertical-stretch: 1;
spacing: Theme.space-3;
VerticalLayout {
width: 250px * max(1.0, Theme.font-scale);
spacing: Theme.space-3;
ScenesCard {
vertical-stretch: 1;
}
SourcesCard {
vertical-stretch: 1;
}
}
VerticalLayout {
horizontal-stretch: 1;
spacing: Theme.space-3;
// As tall as a 16:9 picture across the column needs; the
// mixer and the chat get the rest.
StudioPanel {
vertical-stretch: 0;
preferred-height: (self.width - 2 * Theme.space-4) * 9 / 16 + 96px + (StudioBridge.viewers.length > 0 ? 40px : 0px);
min-height: 260px;
VerticalLayout {
padding: Theme.space-4;
padding-top: Theme.space-3;
spacing: Theme.space-3;
StudioHeader { }
if StudioBridge.viewers.length > 0: ViewerRequests { }
StudioPreview {
vertical-stretch: 1;
min-height: 160px;
}
}
}
HorizontalLayout {
vertical-stretch: 1;
min-height: 240px;
spacing: Theme.space-3;
MixerCard {
horizontal-stretch: 1.35;
}
StudioChat {
horizontal-stretch: 1;
}
}
}
StudioPanel {
width: 300px * max(1.0, Theme.font-scale);
ScrollView {
StreamSettings { }
}
}
}
HorizontalLayout {
height: 64px;
spacing: Theme.space-3;
StudioUser {
padding-left: Theme.space-3;
horizontal-stretch: 0;
}
StudioActions {
horizontal-stretch: 1;
}
Rectangle {
width: 150px;
Rectangle {
y: (parent.height - self.height) / 2;
height: 48px;
border-radius: Theme.radius-lg;
background: settings-touch.has-hover ? Theme.surface-3 : Theme.surface.transparentize(0.08);
border-width: 1px;
border-color: Theme.border;
accessible-role: AccessibleRole.button;
accessible-label: @tr("Studio Settings");
accessible-action-default => { StudioNav.open-settings(); }
settings-touch := TouchArea {
mouse-cursor: MouseCursor.pointer;
clicked => { StudioNav.open-settings(); }
}
HorizontalLayout {
alignment: center;
spacing: Theme.space-3;
Icon {
source: Icons.settings;
size: Theme.icon-md;
tint: Theme.text-secondary;
y: (parent.height - self.height) / 2;
}
Text {
text: @tr("Studio Settings");
color: Theme.text;
font-size: Theme.font-sm;
vertical-alignment: center;
}
}
}
}
}
}
StudioDialogs {
width: parent.width;
height: parent.height;
}
}
// A section title of the phone layout with a link at the right.
component PhoneSection inherits HorizontalLayout {
in property <string> text;
in property <image> icon;
in property <string> action;
callback action-clicked();
spacing: Theme.space-3;
min-height: 32px;
if root.icon.width > 0: Icon {
source: root.icon;
size: Theme.icon-md;
tint: Theme.text-secondary;
y: (parent.height - self.height) / 2;
}
Text {
text: root.text;
color: Theme.text;
font-size: Theme.font-lg;
font-weight: Theme.weight-semibold;
vertical-alignment: center;
horizontal-stretch: 1;
}
if root.action != "": Text {
text: root.action;
color: Theme.accent-text;
font-size: Theme.font-sm;
vertical-alignment: center;
TouchArea {
clicked => { root.action-clicked(); }
}
}
}
// One of the phone's source cards.
component SourceCard inherits Rectangle {
in property <string> kind;
in property <string> title;
in property <string> subtitle;
in property <image> icon;
// A visible source of this kind is in the live scene.
in property <bool> shown;
height: 104px;
horizontal-stretch: 1;
border-radius: Theme.radius-lg;
background: root.shown ? Theme.accent-soft : touch.has-hover ? Theme.surface-3 : Theme.surface-2;
border-width: root.shown ? 2px : 1px;
border-color: root.shown ? Theme.accent : Theme.border;
accessible-role: AccessibleRole.radio-button;
accessible-label: root.title;
accessible-description: root.subtitle;
accessible-checkable: true;
accessible-checked: root.shown;
accessible-action-default => { StudioBridge.main-source(root.kind); }
touch := TouchArea {
clicked => { StudioBridge.main-source(root.kind); }
}
Rectangle {
x: parent.width - 26px;
y: 10px;
width: 18px;
height: 18px;
border-radius: 9px;
border-width: 2px;
border-color: root.shown ? Theme.accent-text : Theme.text-muted;
if root.shown: Rectangle {
width: 8px;
height: 8px;
border-radius: 4px;
background: Theme.accent-text;
}
}
VerticalLayout {
alignment: center;
spacing: Theme.space-2;
padding: Theme.space-2;
HorizontalLayout {
alignment: center;
Icon {
source: root.icon;
size: 28px;
tint: root.shown ? Theme.accent-text : Theme.icon;
}
}
Text {
text: root.title;
color: Theme.text;
font-size: Theme.font-body;
font-weight: Theme.weight-medium;
horizontal-alignment: center;
overflow: elide;
}
Text {
text: root.subtitle;
color: Theme.text-muted;
font-size: Theme.font-xs;
horizontal-alignment: center;
overflow: elide;
}
}
}
// An audio row of the phone layout.
component PhoneAudioRow inherits Rectangle {
in property <int> index;
property <bool> valid: index < StudioBridge.audio.length;
height: 72px;
border-radius: Theme.radius-lg;
background: Theme.surface-2.transparentize(0.3);
border-width: 1px;
border-color: Theme.border;
HorizontalLayout {
padding-left: Theme.space-3;
padding-right: Theme.space-2;
spacing: Theme.space-3;
Rectangle {
width: 42px;
height: 42px;
y: (parent.height - self.height) / 2;
border-radius: Theme.radius-md;
background: Theme.surface-3;
Icon {
source: StudioKinds.icon(root.valid ? StudioBridge.audio[root.index].kind : "");
size: 22px;
}
}
VerticalLayout {
alignment: center;
horizontal-stretch: 1;
spacing: Theme.space-2;
HorizontalLayout {
Text {
text: root.valid ? StudioBridge.audio[root.index].name + (StudioBridge.audio[root.index].detail != "" ? " (" + StudioBridge.audio[root.index].detail + ")" : "") : "";
color: Theme.text;
font-size: Theme.font-sm;
horizontal-stretch: 1;
overflow: elide;
}
Text {
text: !root.valid ? "" : StudioBridge.audio[root.index].muted ? @tr("muted") : @tr("{} dB", round(StudioBridge.audio[root.index].gain-db * 10) / 10);
color: Theme.text-secondary;
font-size: Theme.font-xs;
}
}
HorizontalLayout {
spacing: Theme.space-3;
Meter {
y: (parent.height - self.height) / 2;
height: 8px;
segments: 14;
floor: -60;
min-width: 60px;
level: root.valid ? StudioBridge.audio[root.index].level : -100;
active: root.valid && !StudioBridge.audio[root.index].muted;
}
Slider {
width: 46%;
horizontal-stretch: 0;
y: (parent.height - self.height) / 2;
minimum: -60;
maximum: 20;
step: 0.5;
value: root.valid ? StudioBridge.audio[root.index].gain-db : 0;
label: @tr("Gain");
changed(v) => { StudioBridge.set-gain(root.index, v, false); }
released(v) => { StudioBridge.set-gain(root.index, v, true); }
}
}
}
IconButton {
icon: root.valid && StudioBridge.audio[root.index].muted ? Icons.volume-x : Icons.volume-2;
label: @tr("Mute");
checked: root.valid && StudioBridge.audio[root.index].muted;
danger: true;
size: 34px;
y: (parent.height - self.height) / 2;
clicked => { StudioBridge.toggle-mute(root.index); }
}
}
}
// The studio in the phone layout: preview, what to share, audio, details,
// Go Live.
export component MobileStudio inherits Rectangle {
init => { StudioBridge.open(); }
sv := ScrollView {
VerticalLayout {
width: sv.visible-width;
alignment: start;
padding: Theme.space-4;
padding-top: Theme.space-2;
spacing: Theme.space-4;
// Header: back, the mark, title, destination.
HorizontalLayout {
spacing: Theme.space-3;
IconButton {
icon: Icons.chevron-left;
label: @tr("Back");
size: 32px;
y: (parent.height - self.height) / 2;
clicked => { Nav.show(Page.server); }
}
StudioMark {
size: 40px;
y: (parent.height - self.height) / 2;
}
VerticalLayout {
alignment: center;
horizontal-stretch: 1;
Text {
text: @tr("Stream Studio");
color: Theme.text;
font-size: Theme.font-xl;
font-weight: Theme.weight-semibold;
overflow: elide;
}
Text {
text: StudioBridge.status.live ? @tr("Live · {}", StudioBridge.status.elapsed) : StudioBridge.chat-name != "" ? @tr("Go live to {}", StudioBridge.chat-name) : StudioBridge.status.hint;
color: StudioBridge.status.live ? Theme.live : Theme.accent-text;
font-size: Theme.font-sm;
overflow: elide;
}
}
}
// The preview.
Rectangle {
height: (sv.visible-width - 2 * Theme.space-4) * 9 / 16;
border-radius: Theme.radius-lg;
border-width: 1px;
border-color: Theme.accent.transparentize(0.4);
clip: true;
StudioPreview {
large: false;
caption: false;
}
Rectangle {
x: Theme.space-3;
y: Theme.space-3;
width: badge.preferred-width + 16px;
height: 24px;
border-radius: Theme.radius-xs;
background: Theme.live;
visible: !StudioBridge.status.live;
badge := Text {
text: @tr("LIVE PREVIEW");
color: #ffffff;
font-size: Theme.font-xs;
font-weight: Theme.weight-bold;
}
}
if StudioBridge.sources.length > 0: Rectangle {
x: Theme.space-3;
y: parent.height - self.height - Theme.space-3;
width: min(parent.width - 2 * Theme.space-3, caption.preferred-width);
height: 46px;
border-radius: Theme.radius-md;
background: #060a18b0;
caption := HorizontalLayout {
padding-left: Theme.space-2;
padding-right: Theme.space-4;
spacing: Theme.space-3;
Rectangle {
width: 34px;
height: 34px;
y: (parent.height - self.height) / 2;
border-radius: Theme.radius-sm;
background: #ffffff18;
Icon {
source: StudioKinds.icon(StudioBridge.sources[StudioBridge.sources.length - 1].kind);
size: 20px;
tint: #ffffff;
}
}
VerticalLayout {
alignment: center;
Text {
text: StudioBridge.form.title != "" ? StudioBridge.form.title : StudioBridge.sources[StudioBridge.sources.length - 1].name;
color: #ffffff;
font-size: Theme.font-body;
font-weight: Theme.weight-medium;
overflow: elide;
}
Text {
text: StudioBridge.sources[StudioBridge.sources.length - 1].name + " • " + (StudioBridge.status.output-height * 16 == StudioBridge.status.output-width * 9 ? "16:9" : StudioBridge.status.output-width + "×" + StudioBridge.status.output-height);
color: #ffffffb0;
font-size: Theme.font-xs;
overflow: elide;
}
}
}
}
Rectangle {
x: parent.width - self.width - Theme.space-3;
y: Theme.space-3;
width: fmt.preferred-width + 20px;
height: 26px;
border-radius: Theme.radius-pill;
background: #060a18c8;
border-width: 1px;
border-color: #ffffff20;
fmt := Text {
text: StudioBridge.status.output-height + "p • " + StudioBridge.status.fps + " FPS";
color: #ffffff;
font-size: Theme.font-xs;
}
}
}
// What to share.
PhoneSection {
text: @tr("Source");
action: @tr("What do you want to share?");
}
HorizontalLayout {
spacing: Theme.space-2;
SourceCard {
kind: "screen";
title: @tr("Screen / Game");
subtitle: @tr("Apps or games");
icon: Icons.gamepad-2;
shown: StudioBridge.status.screen-shown;
}
SourceCard {
kind: "camera";
title: @tr("Camera");
subtitle: @tr("Front or back");
icon: Icons.video;
shown: StudioBridge.status.camera-shown;
}
SourceCard {
kind: "window";
title: @tr("App Window");
subtitle: @tr("A single app");
icon: Icons.smartphone;
shown: StudioBridge.status.window-shown;
}
}
// Audio.
PhoneSection {
text: @tr("Audio");
icon: Icons.mic;
action: @tr("Add a source");
action-clicked => { StudioNav.pick-audio(); }
}
for audio[i] in StudioBridge.audio: PhoneAudioRow {
index: i;
}
// Details.
PhoneSection {
text: @tr("Stream Details");
icon: Icons.file-text;
}
TextField {
text: StudioBridge.form.title;
placeholder: @tr("What are you streaming?");
label: @tr("Stream title");
edited(t) => { StudioBridge.edit-form("title", t); }
}
HorizontalLayout {
spacing: Theme.space-3;
VerticalLayout {
spacing: Theme.space-2;
Text {
text: @tr("Game");
color: Theme.text-secondary;
font-size: Theme.font-sm;
}
TextField {
text: StudioBridge.form.game;
placeholder: @tr("Category");
label: @tr("Game or category");
edited(t) => { StudioBridge.edit-form("game", t); }
}
}
VerticalLayout {
spacing: Theme.space-2;
Text {
text: @tr("Quality");
color: Theme.text-secondary;
font-size: Theme.font-sm;
}
Select {
model: ["720p • 30 FPS", "720p • 60 FPS", "1080p • 30 FPS", "1080p • 60 FPS"];
current-value: StudioBridge.status.output-height + "p • " + StudioBridge.status.fps + " FPS";
label: @tr("Output quality");
selected(v) => {
if v == "720p • 30 FPS" {
StudioBridge.set-output("1280", "720", "30");
} else if v == "720p • 60 FPS" {
StudioBridge.set-output("1280", "720", "60");
} else if v == "1080p • 30 FPS" {
StudioBridge.set-output("1920", "1080", "30");
} else {
StudioBridge.set-output("1920", "1080", "60");
}
}
}
}
}
HorizontalLayout {
spacing: Theme.space-3;
HorizontalLayout {
spacing: Theme.space-2;
Icon {
source: Icons.radio;
tint: Theme.accent-text;
y: (parent.height - self.height) / 2;
}
Text {
text: @tr("Go Live To");
color: Theme.accent-text;
vertical-alignment: center;
}
}
DestinationSelect {
horizontal-stretch: 1;
}
}
// Go live (or end) and save a clip.
HorizontalLayout {
spacing: Theme.space-3;
height: 68px;
Rectangle {
horizontal-stretch: 1;
border-radius: Theme.radius-lg;
background: StudioBridge.status.live || StudioBridge.status.starting ? Theme.danger-soft : !StudioBridge.status.can-go-live ? Theme.surface-3 : go.pressed ? Theme.accent-pressed : Theme.accent;
border-width: 1px;
border-color: StudioBridge.status.live ? Theme.danger : Theme.accent-hover;
accessible-role: AccessibleRole.button;
accessible-label: StudioBridge.status.live ? @tr("End Stream") : @tr("Go Live");
accessible-description: StudioBridge.status.hint;
go := TouchArea {
clicked => {
if StudioBridge.status.live || StudioBridge.status.starting {
StudioBridge.end-stream();
} else if StudioBridge.status.can-go-live {
StudioBridge.go-live();
}
}
}
HorizontalLayout {
alignment: center;
spacing: Theme.space-4;
Icon {
source: StudioBridge.status.live ? Icons.square : Icons.radio;
size: 30px;
tint: StudioBridge.status.live ? Theme.danger : Theme.on-accent;
y: (parent.height - self.height) / 2;
}
VerticalLayout {
alignment: center;
Text {
text: StudioBridge.status.live ? @tr("End Stream") : StudioBridge.status.starting ? @tr("Starting…") : @tr("Go Live");
color: StudioBridge.status.live ? Theme.danger : Theme.on-accent;
font-size: Theme.font-xl;
font-weight: Theme.weight-semibold;
}
Text {
text: StudioBridge.status.live ? StudioBridge.status.elapsed : StudioBridge.chat-name != "" ? @tr("Start streaming to {}", StudioBridge.chat-name) : StudioBridge.status.hint;
color: StudioBridge.status.live ? Theme.danger : #ffffffc0;
font-size: Theme.font-xs;
overflow: elide;
}
}
}
}
Rectangle {
width: 88px;
border-radius: Theme.radius-lg;
background: clip.pressed ? Theme.surface-4 : Theme.surface-2;
border-width: 1px;
border-color: Theme.border;
accessible-role: AccessibleRole.button;
accessible-label: @tr("Save a clip");
clip := TouchArea {
clicked => { StudioBridge.save-clip(); }
}
VerticalLayout {
alignment: center;
spacing: Theme.space-1;
HorizontalLayout {
alignment: center;
Icon {
source: Icons.record;
size: 26px;
tint: Theme.live;
}
}
Text {
text: @tr("Clip");
color: Theme.text-secondary;
font-size: Theme.font-sm;
horizontal-alignment: center;
}
}
}
}
if StudioBridge.viewers.length > 0: ViewerRequests { }
}
}
StudioDialogs {
width: parent.width;
height: parent.height;
}
}
+7
View File
@@ -222,6 +222,13 @@ export component TopBar inherits Rectangle {
y: (parent.height - self.height) / 2;
clicked => { Nav.notifications-open = !Nav.notifications-open; }
}
IconButton {
icon: Icons.radio;
label: @tr("Stream Studio");
checked: Nav.page == Page.studio;
y: (parent.height - self.height) / 2;
clicked => { Nav.open-studio(); }
}
IconButton {
icon: Icons.users;
label: @tr("Members");
+9
View File
@@ -117,6 +117,15 @@ export component MobileShell inherits Rectangle {
overflow: elide;
}
}
IconButton {
icon: Icons.radio;
label: @tr("Stream Studio");
round: true;
filled: true;
checked: Nav.page == Page.studio;
y: (parent.height - self.height) / 2;
clicked => { Nav.open-studio(); }
}
IconButton {
icon: Icons.search;
label: @tr("Search");
+321
View File
@@ -0,0 +1,321 @@
// The Stream Studio's data and callbacks (Rust: src/studio.rs, the view
// models in src/vm/studio.rs). The main window and the detached studio
// window each have their own instance of these globals: Rust sets the same
// models and values on both, and wires both to the same controller.
import { ChatLine } from "bridge.slint";
// A scene of the studio.
export struct StudioScene {
id: int,
name: string,
// Its sources, front first: "Screen + Camera + Text".
detail: string,
// Composited now (the live scene).
live: bool,
// The kind of its front-most source (for the icon).
kind: string,
}
// A source of the live scene, front first.
export struct StudioSource {
id: int,
name: string,
// screen, window, portal, camera, image, text, colour, pattern
kind: string,
visible: bool,
locked: bool,
// keep, blur, image, colour
background: string,
// Why it shows nothing ("" while it works).
error: string,
// "1920×1080 · 60 fps"
info: string,
// At the front or the back (cannot move further).
front: bool,
back: bool,
}
// An audio source of the stream (`stream.audio_sources`).
export struct StudioAudio {
name: string,
// "Elgato Wave:3", the application...
detail: string,
// microphone, desktop, app, window, tone
kind: string,
gain-db: float,
muted: bool,
// The meter in dBFS, after the gain.
level: float,
// Why it captures nothing.
error: string,
}
// A simulcast layer (`stream.layers`) as typed: any numbers.
export struct StudioLayer {
// "1280x720"; empty: `scale` of the output.
size: string,
scale: string,
// Frame-rate cap; empty: the output's.
fps: string,
// kbit/s.
bitrate: string,
// kbit/s a viewer needs for this layer.
min-bitrate: string,
}
// A viewer of the studio's stream.
export struct StudioViewer {
client: int,
name: string,
// requested, connecting, connected
state: string,
}
// An entry of a picker (screens, windows, cameras, audio sources).
export struct StudioPick {
name: string,
detail: string,
// For the icon: monitor, window, portal, camera, microphone, desktop, app, tone
kind: string,
}
// The header, the preview's badges and the bottom bar.
export struct StudioStatus {
// The engine runs (preview, mixer, replay buffer).
running: bool,
// "Chill Zone • Starfall Community"; empty without a destination.
destination: string,
// 0: not live, 1: poor, 2: fair, 3: good, 4: excellent.
quality: int,
quality-text: string,
// "1080p • 60 FPS • 8,250 kbps"
format: string,
// The numbers behind it, for the info button.
details: string,
live: bool,
// Going live: waiting for the server.
starting: bool,
// "00:12:34"
elapsed: string,
viewers: int,
participants: int,
can-go-live: bool,
// Why Go Live is off, or what goes wrong.
hint: string,
recording: bool,
recorded: string,
// The replay buffer's window (0: off) and what it holds now.
replay-seconds: int,
replay-held: string,
output-width: int,
output-height: int,
fps: int,
detached: bool,
// A window of its own is possible (not on Android).
can-detach: bool,
// The live scene shows a screen, a camera, a window (the phone's cards).
screen-shown: bool,
camera-shown: bool,
window-shown: bool,
}
// The stream settings panel (`studio.stream`, `stream.bitrate_kbps`).
export struct StudioForm {
destination: int,
title: string,
game: string,
message: string,
show-viewers: bool,
show-chat: bool,
show-now-playing: bool,
audio: bool,
// kbit/s of the stream without layers, as typed.
bitrate: string,
}
// The source properties dialog (also for adding text, colour and image
// sources: `id` -1). Numbers as typed.
export struct StudioSourceForm {
id: int,
name: string,
kind: string,
x: string,
y: string,
// Empty: the source's own size times `scale`.
width: string,
height: string,
scale: string,
// contain, cover, stretch
fit: string,
crop-left: string,
crop-top: string,
crop-right: string,
crop-bottom: string,
// Percent.
opacity: float,
locked: bool,
visible: bool,
// keep, blur, image, colour
background: string,
// Blur radius in percent of the picture's height.
blur: string,
background-path: string,
background-colour: string,
// Text, colour ("#rrggbb" or "#rrggbbaa") and image sources.
text: string,
text-size: string,
colour: string,
path: string,
mirror: bool,
}
// The studio settings dialog (`studio.*` keys and the preview).
export struct StudioSettingsForm {
replay-seconds: string,
replay-memory: string,
recording-dir: string,
preview-width: string,
preview-fps: string,
}
export global StudioBridge {
in property <StudioStatus> status;
in property <StudioForm> form;
// The composite, downscaled (the engine's preview tap).
in property <image> preview;
in property <bool> has-preview;
in property <[StudioScene]> scenes;
in property <[StudioSource]> sources;
in property <[StudioAudio]> audio;
in property <[StudioLayer]> layers;
// Where the stream can go: the channel (name) on each server (detail).
in property <[StudioPick]> destinations;
in property <[StudioViewer]> viewers;
// The chat of the channel the stream goes to, and its name.
in property <[ChatLine]> chat;
in property <string> chat-name;
// Filled right before a picker shows.
in property <[StudioPick]> picks;
// The studio page or window appeared: start the engine.
callback open();
// Into a window of its own, and back.
callback detach();
callback dock();
callback select-scene(int);
callback add-scene();
callback rename-scene(int, string);
callback remove-scene(int);
// Fill `picks` for adding a screen, window or camera source; false:
// nothing to pick (it was added directly, e.g. through the portal).
callback list-sources(string) -> bool;
callback add-picked(string, int);
// Text, colour and image sources from the dialog.
callback add-source(StudioSourceForm);
callback source-form(int) -> StudioSourceForm;
callback apply-source(StudioSourceForm);
callback toggle-source(int);
// up, down, lock, remove, bg-keep, bg-blur
callback source-action(int, string);
// The phone layout's source cards: screen, camera, window.
callback main-source(string);
// Audio: fill `picks` with what can be added; add, change, remove.
callback list-audio();
callback add-audio(int);
// While dragging (`done` false) and at the end.
callback set-gain(int, float, bool);
callback toggle-mute(int);
callback remove-audio(int);
// A field of the stream settings: title, game, message, show-viewers,
// show-chat, show-now-playing, audio ("true"/"false"), bitrate,
// destination (its index).
callback edit-form(string, string);
callback set-output(string, string, string);
callback set-layer(int, StudioLayer);
callback add-layer();
callback remove-layer(int);
callback advanced-settings();
// Bottom bar.
callback save-clip();
callback toggle-recording();
callback open-recordings();
callback go-live();
callback end-stream();
callback settings-form() -> StudioSettingsForm;
callback apply-settings(StudioSettingsForm);
callback respond-viewer(int, bool);
callback send-chat(string);
callback open-chat();
}
// What one window shows of the studio: dialogs and pickers (each window has
// its own).
export global StudioNav {
// "", "pick", "source", "scene", "settings"
in-out property <string> dialog;
// What the picker picks: screen, window, camera, audio
in-out property <string> pick-kind;
in-out property <StudioSourceForm> source-form;
// The scene being renamed.
in-out property <int> scene-id: -1;
in-out property <string> scene-name;
in-out property <StudioSettingsForm> settings-form;
public function pick(kind: string) {
if StudioBridge.list-sources(kind) {
pick-kind = kind;
dialog = "pick";
}
}
public function pick-audio() {
StudioBridge.list-audio();
pick-kind = "audio";
dialog = "pick";
}
public function edit-source(id: int) {
source-form = StudioBridge.source-form(id);
dialog = "source";
}
// A new text, colour or image source.
public function new-source(kind: string) {
source-form = {
id: -1,
kind: kind,
name: kind == "text" ? @tr("Text") : kind == "colour" ? @tr("Colour") : @tr("Image"),
text: @tr("Your text"),
text-size: "64",
colour: kind == "text" ? "#ffffff" : "#101a3c",
opacity: 100,
visible: true,
fit: "contain",
scale: "1",
background: "keep",
};
dialog = "source";
}
public function rename-scene(id: int, name: string) {
scene-id = id;
scene-name = name;
dialog = "scene";
}
public function open-settings() {
settings-form = StudioBridge.settings-form();
dialog = "settings";
}
public function close() {
dialog = "";
}
}
+146
View File
@@ -0,0 +1,146 @@
// The Stream Studio in a window of its own, while the main window goes on.
// Same pieces as the integrated studio (screens/studio-parts.slint), more
// compact; it has its own globals, which Rust fills from the same models
// (src/studio.rs). Closing it docks the studio back into the main window.
import { Palette } from "std-widgets.slint";
import { Theme } from "theme.slint";
import { Icons } from "icons.slint";
import { StudioBridge, StudioNav } from "studio-bridge.slint";
import { IconButton, ScrollView } from "components/index.slint";
import { ScenesCard, SourcesCard, StudioPanel, PanelTitle, StudioPreview, MixerCard, StreamSettings, StudioActions, ViewerRequests, StudioDialogs } from "screens/studio-parts.slint";
export component StudioWindow inherits Window {
title: @tr("Stream Studio");
preferred-width: 900px;
preferred-height: 720px;
min-width: 640px;
min-height: 480px;
background: Theme.bg-app;
default-font-family: "Inter";
default-font-size: Theme.font-body;
icon: Icons.logo;
// Scroll bars and menus follow the theme (Rust copies the main
// window's Theme here).
property <bool> dark: Theme.dark;
changed dark => { Palette.color-scheme = Theme.dark ? ColorScheme.dark : ColorScheme.light; }
init => { Palette.color-scheme = Theme.dark ? ColorScheme.dark : ColorScheme.light; }
Rectangle {
background: Theme.backdrop;
VerticalLayout {
padding: Theme.space-3;
padding-top: 0;
spacing: Theme.space-3;
// The app and what this is, and back into the main window.
HorizontalLayout {
height: 52px;
spacing: Theme.space-3;
padding-left: Theme.space-2;
Image {
width: 28px;
height: 28px;
y: (parent.height - self.height) / 2;
source: Icons.logo;
}
Text {
text: "Voelin";
color: Theme.text;
font-size: Theme.font-xl;
font-weight: Theme.weight-semibold;
vertical-alignment: center;
}
Text {
text: @tr("Stream Studio");
color: Theme.accent-text;
font-size: Theme.font-md;
vertical-alignment: center;
horizontal-stretch: 1;
}
IconButton {
icon: Icons.minimize-2;
label: @tr("Back into the main window");
y: (parent.height - self.height) / 2;
clicked => { StudioBridge.dock(); }
}
}
HorizontalLayout {
vertical-stretch: 1;
spacing: Theme.space-3;
VerticalLayout {
width: 216px * max(1.0, Theme.font-scale);
spacing: Theme.space-3;
ScenesCard {
compact: true;
vertical-stretch: 1;
}
SourcesCard {
compact: true;
vertical-stretch: 1;
}
}
VerticalLayout {
horizontal-stretch: 1;
spacing: Theme.space-3;
StudioPanel {
vertical-stretch: 1.2;
min-height: 200px;
VerticalLayout {
padding: Theme.space-3;
spacing: Theme.space-2;
PanelTitle {
text: @tr("Stream Preview");
compact: true;
}
if StudioBridge.viewers.length > 0: ViewerRequests { }
StudioPreview {
vertical-stretch: 1;
large: false;
caption: false;
controls: true;
}
}
}
HorizontalLayout {
vertical-stretch: 1;
min-height: 200px;
spacing: Theme.space-3;
MixerCard {
compact: true;
horizontal-stretch: 1.15;
}
StudioPanel {
horizontal-stretch: 1;
ScrollView {
StreamSettings {
compact: true;
}
}
}
}
}
}
HorizontalLayout {
height: 52px;
spacing: Theme.space-3;
StudioActions {
compact: true;
horizontal-stretch: 1;
}
IconButton {
icon: Icons.settings;
label: @tr("Studio Settings");
filled: true;
size: 44px;
y: (parent.height - self.height) / 2;
clicked => { StudioNav.open-settings(); }
}
}
}
}
StudioDialogs {
width: parent.width;
height: parent.height;
}
}