diff --git a/android/app/src/main/java/io/github/faumaray/voelin/Bridge.kt b/android/app/src/main/java/io/github/faumaray/voelin/Bridge.kt index f79aa31..28b912e 100644 --- a/android/app/src/main/java/io/github/faumaray/voelin/Bridge.kt +++ b/android/app/src/main/java/io/github/faumaray/voelin/Bridge.kt @@ -8,6 +8,7 @@ import android.content.pm.ResolveInfo import android.graphics.Bitmap import android.graphics.Canvas import android.os.Build +import android.view.Surface import java.io.File /** @@ -69,6 +70,16 @@ object Bridge { ScreenCaptureService.stop(app) } + /** + * Render the shared screen into `surface` (an encoder's input, + * `width` x `height`: the zero-copy path), or with null back into the + * frame reader. + */ + @JvmStatic + fun setScreenSurface(surface: Surface?, width: Int, height: Int) { + ScreenCaptureService.redirect(surface, width, height) + } + /** Capture what the device plays; false without a running screen capture. */ @JvmStatic fun startSystemAudio(): Boolean = ScreenCaptureService.startAudio() diff --git a/android/app/src/main/java/io/github/faumaray/voelin/ScreenCaptureService.kt b/android/app/src/main/java/io/github/faumaray/voelin/ScreenCaptureService.kt index 814a6f5..b76a793 100644 --- a/android/app/src/main/java/io/github/faumaray/voelin/ScreenCaptureService.kt +++ b/android/app/src/main/java/io/github/faumaray/voelin/ScreenCaptureService.kt @@ -36,9 +36,10 @@ import kotlin.math.roundToInt /** * Screen sharing: holds the MediaProjection (a `mediaProjection` foreground * service, as Android requires), mirrors the display into an ImageReader and - * hands each RGBA frame to Native.onScreenFrame; optionally captures what - * other apps play (AudioPlaybackCapture: all but us, or one app) for - * Native.onSystemAudio and Native.onAudioInput. + * hands each RGBA frame to Native.onScreenFrame, or (the zero-copy path, + * Bridge.setScreenSurface) straight into an encoder's input surface; + * optionally captures what other apps play (AudioPlaybackCapture: all but + * us, or one app) for Native.onSystemAudio and Native.onAudioInput. */ class ScreenCaptureService : Service() { private var projection: MediaProjection? = null @@ -149,6 +150,32 @@ class ScreenCaptureService : Service() { ) } + /** + * Point the virtual display at `surface` (an encoder's input surface, + * `width` x `height`: the screen goes into the encoder without a copy), + * or with null back at the reader, at the reader's size. + */ + @Synchronized + private fun redirectTo(surface: Surface?, width: Int, height: Int) { + val display = display ?: return + val reader = reader ?: return + val dpi = resources.displayMetrics.densityDpi + try { + // Detached while resizing, so neither consumer gets a picture of + // the other's size. + display.surface = null + if (surface != null) { + display.resize(width, height, dpi) + display.surface = surface + } else { + display.resize(reader.width, reader.height, dpi) + display.surface = reader.surface + } + } catch (e: RuntimeException) { + Log.w(TAG, "cannot point the screen at ${if (surface != null) "the encoder" else "the reader"}", e) + } + } + /** * Capture media, game and unknown-usage playback as 48 kHz stereo float: * of app `uid`, or with null of every app but us (our voices and watched @@ -293,6 +320,11 @@ class ScreenCaptureService : Service() { context.stopService(Intent(context, ScreenCaptureService::class.java)) } + /** See redirectTo; nothing without a running capture. */ + fun redirect(surface: Surface?, width: Int, height: Int) { + instance?.redirectTo(surface, width, height) + } + fun startAudio(): Boolean { val service = instance ?: return false return service.startAudioCapture(SYSTEM_AUDIO, null) diff --git a/crates/voelin-android/src/bridge.rs b/crates/voelin-android/src/bridge.rs index 8169720..1047256 100644 --- a/crates/voelin-android/src/bridge.rs +++ b/crates/voelin-android/src/bridge.rs @@ -113,6 +113,40 @@ pub fn set_screen_notification(notice: Option<&ScreenNotice>) -> Result<()> { }) } +/// Point the screen's virtual display at an encoder's input surface (the +/// zero-copy path), or back at the frame reader with `None`. +pub fn set_screen_surface( + surface: Option<&voelin_media::codec::mediacodec::InputSurface>, +) -> Result<()> { + with_bridge(|env, class| { + let (object, width, height) = match surface { + Some(surface) => { + // SAFETY: `env` is this thread's JNI environment, and the + // window stays alive (`surface` holds a reference) while + // Java makes a Surface of it. + #[allow(unsafe_code)] + let raw = unsafe { surface.window.to_surface(env.get_raw().cast()) }; + if raw.is_null() { + return Err(Error::NullPtr("encoder surface")); + } + // SAFETY: `raw` is a new local reference to an + // android.view.Surface of this frame. + #[allow(unsafe_code)] + let object = unsafe { JObject::from_raw(env, raw.cast()) }; + (object, surface.width, surface.height) + } + None => (JObject::null(), 0, 0), + }; + env.call_static_method( + class, + jni_str!("setScreenSurface"), + jni_sig!((surface: android.view.Surface, width: jint, height: jint) -> void), + &[JValue::Object(&object), JValue::Int(width as jint), JValue::Int(height as jint)], + )?; + Ok(()) + }) +} + /// Ask the user to share the screen. The answer comes back through /// `Native.onScreenCaptureResult`. pub fn request_screen_capture(fps: u32, max_size: u32) -> Result<()> { @@ -362,9 +396,10 @@ fn on_screen_frame<'local>( return Err(Error::NullPtr("screen frame buffer")); } // SAFETY: a direct buffer's memory is `capacity` bytes at `address`, and - // the `Image` it belongs to stays open until this call returns. + // the `Image` it belongs to stays open until this call returns (the + // frame is borrowed only during it). #[allow(unsafe_code)] - let bytes = unsafe { std::slice::from_raw_parts(address, capacity) }.to_vec(); + let bytes = unsafe { std::slice::from_raw_parts(address, capacity) }; Ok(crate::capture::on_frame( bytes, width.max(0) as u32, diff --git a/crates/voelin-android/src/capture.rs b/crates/voelin-android/src/capture.rs index 14adb5c..744695c 100644 --- a/crates/voelin-android/src/capture.rs +++ b/crates/voelin-android/src/capture.rs @@ -4,23 +4,38 @@ //! `voelin_media::capture::default_screen_capture()` as on desktop. Starting //! asks the Kotlin side for the user's consent; on consent it runs //! `ScreenCaptureService` (a `mediaProjection` foreground service) whose -//! `ImageReader` hands RGBA frames to [`on_frame`]. System audio -//! (`AudioPlaybackCapture`, 48 kHz float) needs that running projection: -//! everything but our own uid, or one app's uid, each into a stream mixer -//! input ([`on_input`]); several captures may run at once. +//! virtual display renders into an `ImageReader`, whose RGBA frames come to +//! [`on_frame`]. A stream's sink takes them borrowed, converting straight +//! from the reader's buffer. +//! +//! The zero-copy path: while every encoder the sink feeds takes pictures +//! straight from the screen ([`FrameSink::accepts_gpu`]: one MediaCodec +//! encoder, see `voelin_media::codec::mediacodec`), a ticker at the +//! stream's frame rate tells the sink a picture is due; the first one makes +//! the encoder publish its input surface, and the virtual display is +//! pointed at it, so the screen goes from the compositor into the encoder +//! without a copy. When that stops (a second simulcast layer or codec, the +//! encoder gone or failed) the display goes back to the reader. +//! +//! System audio (`AudioPlaybackCapture`, 48 kHz float) needs that running +//! projection: everything but our own uid, or one app's uid, each into a +//! stream mixer input ([`on_input`]); several captures may run at once. use std::collections::HashMap; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; -use std::time::Duration; +use std::time::{Duration, Instant}; use tokio::sync::oneshot; -use tracing::warn; +use tracing::{debug, warn}; use voelin_media::capture::external::{self, AudioProvider, ScreenProvider}; use voelin_media::capture::playback::{AppMatch, AudioApp, PlaybackFilter}; -use voelin_media::capture::{BoxFuture, CaptureOptions, CaptureSource, SourceId}; +use voelin_media::capture::{BoxFuture, CaptureOptions, CaptureSource, FrameSink, SourceId}; +use voelin_media::codec::mediacodec::{self, InputSurface}; use voelin_media::mix::SourceInput; -use voelin_media::{AudioBuffer, Error, FrameSender, Result, VideoFrame}; +use voelin_media::{ + AudioBuffer, Error, FrameRef, FrameSender, GpuFrame, PixelsRef, PlaneRef, Result, VideoFrame, +}; use crate::bridge; @@ -50,6 +65,29 @@ fn with_state(f: impl FnOnce(&mut State) -> R) -> R { f(guard.get_or_insert_with(State::default)) } +/// The screen's consumer of [`ScreenProvider::start_sink`], apart from the +/// audio state so that converting a frame does not hold up audio. +#[derive(Default)] +struct Video { + sink: Option>, + /// The ticker that serves this sink. + ticker: u64, + /// Size of the captured screen (the reader's), once a frame came. + size: (u32, u32), + /// The last frame's time and when it came: the ticker's pictures + /// continue that clock. + last: Option<(Duration, Instant)>, + /// The encoder surface the display renders into (its generation). + rendering: Option, +} + +static VIDEO: Mutex> = Mutex::new(None); + +fn with_video(f: impl FnOnce(&mut Video) -> R) -> R { + let mut guard = VIDEO.lock().unwrap_or_else(PoisonError::into_inner); + f(guard.get_or_insert_with(Video::default)) +} + /// Make MediaProjection the default screen and audio capture. pub fn register() { external::set_screen_provider(Some(Arc::new(Projection))); @@ -63,6 +101,22 @@ fn since(first: &mut Option, now_ns: i64) -> Duration { struct Projection; +impl Projection { + /// Ask for consent; `Ok` once the capture runs. + fn request(options: &CaptureOptions, tx: oneshot::Sender>) -> Result<()> { + with_state(|s| { + if let Some(previous) = s.pending.replace(tx) { + let _ = previous.send(Err(Error::Cancelled)); + } + s.origin_ns = None; + }); + bridge::request_screen_capture(options.fps.clamp(1, 60), MAX_SIZE).map_err(|e| { + with_state(|s| s.pending = None); + Error::CaptureUnavailable { backend: SCREEN, reason: e.to_string() } + }) + } +} + impl ScreenProvider for Projection { fn name(&self) -> &'static str { SCREEN @@ -86,20 +140,35 @@ impl ScreenProvider for Projection { frames: FrameSender, ) -> BoxFuture<'static, Result<()>> { let (tx, rx) = oneshot::channel(); - with_state(|s| { - if let Some(previous) = s.pending.replace(tx) { - let _ = previous.send(Err(Error::Cancelled)); - } - s.frames = Some(frames); - s.origin_ns = None; - }); - if let Err(e) = bridge::request_screen_capture(options.fps.clamp(1, 60), MAX_SIZE) { - with_state(|s| { - s.pending = None; - s.frames = None; - }); - let error = Error::CaptureUnavailable { backend: SCREEN, reason: e.to_string() }; - return Box::pin(async move { Err(error) }); + with_video(|v| v.sink = None); + with_state(|s| s.frames = Some(frames)); + if let Err(e) = Self::request(options, tx) { + with_state(|s| s.frames = None); + return Box::pin(async move { Err(e) }); + } + Box::pin(async move { rx.await.unwrap_or(Err(Error::Cancelled)) }) + } + + fn start_sink( + &self, + _source: &SourceId, + options: &CaptureOptions, + sink: Box, + ) -> BoxFuture<'static, Result<()>> { + static TICKERS: AtomicU64 = AtomicU64::new(1); + let (tx, rx) = oneshot::channel(); + with_state(|s| s.frames = None); + let ticker = TICKERS.fetch_add(1, Ordering::Relaxed); + with_video(|v| *v = Video { sink: Some(sink), ticker, ..Video::default() }); + if let Err(e) = Self::request(options, tx) { + with_video(|v| v.sink = None); + return Box::pin(async move { Err(e) }); + } + if let Err(e) = std::thread::Builder::new() + .name("voelin-screen-ticker".into()) + .spawn(move || run_ticker(ticker)) + { + warn!("no zero-copy screen path: {e}"); } Box::pin(async move { rx.await.unwrap_or(Err(Error::Cancelled)) }) } @@ -112,6 +181,64 @@ impl ScreenProvider for Projection { } } +/// The zero-copy path's ticker (see the [module docs](self)): runs until +/// its sink is gone or replaced. +fn run_ticker(id: u64) { + loop { + let mut redirect: Option> = None; + let interval = with_video(|v| { + if v.ticker != id { + return None; + } + let Some(sink) = v.sink.as_mut() else { + // Back to the reader, whose next frame stops the service. + if v.rendering.take().is_some() { + redirect = Some(None); + } + return None; + }; + let interval = Duration::from_secs(1) / sink.max_fps().max(1); + let (width, height) = v.size; + if width == 0 { + // No frame yet. + return Some(interval); + } + if !sink.accepts_gpu() { + if v.rendering.take().is_some() { + debug!("screen back to frames in memory"); + redirect = Some(None); + } + return Some(interval); + } + // The encoder makes its surface for the first picture. + match (mediacodec::input_surface(), v.rendering) { + (Some(surface), rendering) if rendering != Some(surface.generation) => { + debug!(surface.width, surface.height, "screen straight into the encoder"); + v.rendering = Some(surface.generation); + redirect = Some(Some(surface)); + } + (None, Some(_)) => { + v.rendering = None; + redirect = Some(None); + } + _ => {} + } + let timestamp = v.last.map_or(Duration::ZERO, |(at, when)| at + when.elapsed()); + if sink.wants(timestamp) && !sink.gpu(GpuFrame::rendered(width, height, timestamp)) { + v.sink = None; + } + Some(interval) + }); + if let Some(target) = redirect + && let Err(e) = bridge::set_screen_surface(target.as_ref()) + { + warn!("pointing the screen at the encoder: {e}"); + } + let Some(interval) = interval else { return }; + std::thread::sleep(interval); + } +} + struct PlaybackAudio; impl AudioProvider for PlaybackAudio { @@ -231,6 +358,9 @@ pub fn on_input(id: u64, samples: &[f32], channels: u16) -> bool { /// The user answered the consent dialog (or the service failed to start). pub fn on_result(granted: bool, error: Option) { + if !granted { + with_video(|v| v.sink = None); + } with_state(|s| { let result = match (granted, error) { (true, _) => Ok(()), @@ -247,23 +377,49 @@ pub fn on_result(granted: bool, error: Option) { } pub fn wants_frames() -> bool { - with_state(|s| s.frames.as_ref().is_some_and(|f| !f.is_closed())) + with_video(|v| v.sink.is_some()) + || with_state(|s| s.frames.as_ref().is_some_and(|f| !f.is_closed())) } -/// A captured RGBA frame. Returns `false` once nobody wants frames. -pub fn on_frame( - pixels: Vec, - width: u32, - height: u32, - stride: usize, - timestamp_ns: i64, -) -> bool { - with_state(|s| { +/// A captured RGBA frame, valid during the call. Returns `false` once +/// nobody wants frames. +pub fn on_frame(pixels: &[u8], width: u32, height: u32, stride: usize, timestamp_ns: i64) -> bool { + let timestamp = with_state(|s| { let timestamp = since(&mut s.origin_ns, timestamp_ns); + if let Some(origin) = s.origin_ns { + mediacodec::set_screen_origin(origin); + } + timestamp + }); + let taken = with_video(|v| { + let sink = v.sink.as_mut()?; + v.size = (width, height); + v.last = Some((timestamp, Instant::now())); + // While the screen renders into the encoder, what still reaches + // the reader is not used. + if sink.accepts_gpu() || !sink.wants(timestamp) { + return Some(true); + } + let pixels = PixelsRef::Rgba(PlaneRef::new(pixels, stride)); + let frame = FrameRef { width, height, timestamp, pixels }; + if let Err(e) = frame.validate() { + warn!("dropping a screen frame: {e}"); + return Some(true); + } + if !sink.frame(frame) { + v.sink = None; + return Some(false); + } + Some(true) + }); + if let Some(more) = taken { + return more; + } + with_state(|s| { let Some(frames) = &s.frames else { return false; }; - match VideoFrame::from_rgba(width, height, stride, pixels) { + match VideoFrame::from_rgba(width, height, stride, pixels.to_vec()) { Ok(frame) => { if !frames.send(frame.with_timestamp(timestamp)) { s.frames = None; @@ -279,6 +435,7 @@ pub fn on_frame( /// The projection ended (stopped by us, the user, or the system): the /// consumers see their channels close. pub fn on_stopped() { + with_video(|v| v.sink = None); with_state(|s| { s.frames = None; s.audio = None; diff --git a/crates/voelin-core/src/media.rs b/crates/voelin-core/src/media.rs index 8350064..c551358 100644 --- a/crates/voelin-core/src/media.rs +++ b/crates/voelin-core/src/media.rs @@ -1572,7 +1572,8 @@ impl Ingest { } /// Whether frames go to the GPU: every layer's encoders take GPU frames - /// and the GPU stage has not failed. + /// and the GPU stage has not failed. On Android: the screen can render + /// straight into the encoder (`mediacodec`'s surface path). fn gpu_path(&self) -> bool { #[cfg(all(target_os = "linux", feature = "media-desktop"))] { @@ -1583,7 +1584,18 @@ impl Ingest { .iter() .all(|l| l.layer.stopped() || l.layer.gpu.load(Ordering::Relaxed) != 0) } - #[cfg(not(all(target_os = "linux", feature = "media-desktop")))] + #[cfg(target_os = "android")] + { + !self.layers.is_empty() + && self + .layers + .iter() + .all(|l| l.layer.stopped() || l.layer.gpu.load(Ordering::Relaxed) != 0) + } + #[cfg(not(any( + all(target_os = "linux", feature = "media-desktop"), + target_os = "android" + )))] false } @@ -1707,7 +1719,38 @@ impl FrameSink for Ingest { } fn accepts_dmabuf(&self) -> bool { - self.gpu_path() + cfg!(all(target_os = "linux", feature = "media-desktop")) && self.gpu_path() + } + + fn accepts_gpu(&self) -> bool { + cfg!(target_os = "android") && self.gpu_path() + } + + /// Android: the screen goes straight into each due layer's encoder, + /// which draws it at the layer's size; only its size and time come here. + #[cfg(target_os = "android")] + fn gpu(&mut self, frame: GpuFrame) -> bool { + if self.shared.stopped() { + return false; + } + self.pacer.keep(frame.timestamp); + self.refresh(); + let shared = &self.shared; + 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 true; + } + for l in &mut self.layers { + if !l.layer.stopped() && l.pacer.take(frame.timestamp) { + let (width, height) = l.spec.output_size(frame.width, frame.height); + l.layer.gpu_inbox.put(Arc::new(frame.sized(width, height))); + } + } + shared.gpu_converted.fetch_add(1, Ordering::Relaxed); + true } /// The tiled layout the GPU's own RGB surfaces have, once the GPU stage diff --git a/crates/voelin-media/src/capture/external.rs b/crates/voelin-media/src/capture/external.rs index 2d72691..37d44f0 100644 --- a/crates/voelin-media/src/capture/external.rs +++ b/crates/voelin-media/src/capture/external.rs @@ -15,7 +15,7 @@ use std::sync::{Arc, Mutex, PoisonError}; use crate::capture::playback::{AudioApp, PlaybackFilter, SourceCapture, forward_audio}; use crate::capture::{ - AudioCapture, BoxFuture, CaptureOptions, CaptureSource, ScreenCapture, SourceId, + AudioCapture, BoxFuture, CaptureOptions, CaptureSource, FrameSink, ScreenCapture, SourceId, }; use crate::frame::{AUDIO_SAMPLE_RATE, AudioBuffer, VideoFrame}; use crate::mix::{SourceHandle, SourceInput}; @@ -41,6 +41,24 @@ pub trait ScreenProvider: Send + Sync { frames: FrameSender, ) -> BoxFuture<'static, Result<()>>; + /// Like [`start`](Self::start), but frames go to `sink` from the + /// provider's own thread, borrowed (no copy), and the provider may hand + /// it [`FrameSink::gpu`] pictures while it accepts them. The default + /// forwards the frames of `start`. + fn start_sink( + &self, + source: &SourceId, + options: &CaptureOptions, + sink: Box, + ) -> BoxFuture<'static, Result<()>> { + let (tx, rx) = frame_channel(options.queue); + let started = self.start(source, options, tx); + Box::pin(async move { + started.await?; + super::forward(rx, sink) + }) + } + fn stop(&self); } @@ -175,6 +193,19 @@ impl ScreenCapture for ExternalScreenCapture { }) } + fn start_sink( + &mut self, + source: &SourceId, + options: &CaptureOptions, + sink: Box, + ) -> BoxFuture<'_, Result<()>> { + self.stop(); + let options = CaptureOptions { fps: sink.max_fps(), ..options.clone() }; + let started = self.provider.start_sink(source, &options, sink); + self.running = true; + started + } + fn stop(&mut self) { if std::mem::take(&mut self.running) { self.provider.stop(); diff --git a/crates/voelin-media/src/capture/mod.rs b/crates/voelin-media/src/capture/mod.rs index f064d63..f0568d9 100644 --- a/crates/voelin-media/src/capture/mod.rs +++ b/crates/voelin-media/src/capture/mod.rs @@ -130,6 +130,22 @@ pub trait FrameSink: Send { None } + /// Whether the sink takes pictures the platform puts straight into the + /// encoder ([`gpu`](Self::gpu)), because every encoder it feeds takes + /// them. Android's screen capture then renders into MediaCodec's input + /// surface instead of handing over pixels. + fn accepts_gpu(&self) -> bool { + false + } + + /// Such a picture: only its size and time + /// ([`GpuFrame::rendered`](crate::GpuFrame::rendered)). Returns `false` + /// when no more frames are wanted. + fn gpu(&mut self, frame: crate::GpuFrame) -> bool { + let _ = frame; + true + } + /// 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 diff --git a/crates/voelin-media/src/codec/mediacodec.rs b/crates/voelin-media/src/codec/mediacodec.rs index 0cd9df5..2f173d4 100644 --- a/crates/voelin-media/src/codec/mediacodec.rs +++ b/crates/voelin-media/src/codec/mediacodec.rs @@ -10,26 +10,42 @@ //! H.264 is encoded as High profile without B-frames (the Constrained High //! stream TeamSpeak negotiates, see `voelin-stream`), SPS/PPS in front of every //! keyframe. +//! +//! The zero-copy path: while it is the only MediaCodec encoder in the +//! process, an encoder takes [`GpuFrame`]s +//! ([`VideoEncoder::gpu_alignment`]). For the first one it starts a codec +//! with an input surface and publishes it ([`input_surface`]); Android's +//! screen capture points its virtual display at that surface, so the +//! screen goes from the compositor into the encoder without a copy or a +//! CPU conversion, and the `GpuFrame`s only say a picture is due (the +//! encoder hands over what it encoded since). With a second encoder (a +//! simulcast layer, another codec for some viewers) none takes them, and +//! the capture goes back to frames in memory; so does an encoder whose +//! surface failed once. // AMediaCodec handles are used from one thread at a time (`&mut self`), which // the NDK allows from any thread; the wrapper only asserts that. #![allow(unsafe_code)] -use std::sync::OnceLock; +use std::sync::atomic::{AtomicI64, AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Mutex, OnceLock, PoisonError}; use std::time::Duration; use ndk::media::media_codec::{ DequeuedInputBufferResult, DequeuedOutputBufferInfoResult, MediaCodec, MediaCodecDirection, }; use ndk::media::media_format::MediaFormat; +use ndk::native_window::NativeWindow; use tracing::{debug, info}; use super::hw::EncoderFactory; use super::image_layout::{ COLOR_FORMAT_FLEXIBLE, COLOR_FORMAT_I420, COLOR_FORMAT_NV12, ImageLayout, }; -use super::{Codec, EncodedFrame, EncoderBackend, EncoderConfig, VideoDecoder, VideoEncoder}; -use crate::frame::{FrameData, VideoFrame}; +use super::{ + Codec, EncodedChunk, EncodedFrame, EncoderBackend, EncoderConfig, VideoDecoder, VideoEncoder, +}; +use crate::frame::{FrameData, GpuFrame, VideoFrame}; use crate::{Error, Result, convert}; /// `BUFFER_FLAG_KEY_FRAME`. @@ -48,8 +64,47 @@ const INPUT_WAIT: Duration = Duration::from_millis(20); /// How long they wait for the first output of a call. const OUTPUT_WAIT: Duration = Duration::from_millis(5); +/// `COLOR_FormatSurface`: pictures come through an input surface. +const COLOR_FORMAT_SURFACE: i32 = 0x7F00_0789; +/// On the surface path a still screen is encoded again after this long +/// (µs), so a keyframe asked for while nothing moves comes this late at +/// most. +const REPEAT_AFTER_US: i64 = 100_000; + pub const NAME: &str = "mediacodec"; +/// MediaCodec encoders alive in this process. +static LIVE: AtomicUsize = AtomicUsize::new(0); +/// The published input surface (see the [module docs](self)). +static SURFACE: Mutex> = Mutex::new(None); +static GENERATION: AtomicU64 = AtomicU64::new(0); +/// The screen capture's clock origin (`CLOCK_MONOTONIC` ns), which the +/// surface's presentation times are on. +static SCREEN_ORIGIN_NS: AtomicI64 = AtomicI64::new(i64::MIN); + +/// The input surface of the encoder that takes the screen straight from +/// the capture, for the capture's virtual display to render into. +#[derive(Clone)] +pub struct InputSurface { + pub window: NativeWindow, + pub width: u32, + pub height: u32, + /// Changes with every new surface. + pub generation: u64, +} + +/// The surface to render the screen into, if an encoder has one. +pub fn input_surface() -> Option { + SURFACE.lock().unwrap_or_else(PoisonError::into_inner).clone() +} + +/// Where the screen capture's frame times start (`CLOCK_MONOTONIC` ns, +/// what its frames' times are counted from): the surface path puts its +/// presentation times, which are on that clock, on the stream's timeline. +pub fn set_screen_origin(origin_ns: i64) { + SCREEN_ORIGIN_NS.store(origin_ns, Ordering::Relaxed); +} + fn mime(codec: Codec) -> &'static str { match codec { Codec::Vp8 => "video/x-vnd.on2.vp8", @@ -159,15 +214,32 @@ impl EncoderFactory for MediaCodecFactory { if !self.codecs.contains(&codec) { return Err(Error::CodecUnavailable { codec, reason: "no MediaCodec encoder".into() }); } - Ok(Box::new(MediaCodecEncoder { codec, config: config.clone(), session: None })) + LIVE.fetch_add(1, Ordering::Relaxed); + Ok(Box::new(MediaCodecEncoder { + codec, + config: config.clone(), + session: None, + surface_failed: false, + })) } } -/// A MediaCodec encoder. The codec is (re)created for the frame size. +/// A MediaCodec encoder. The codec is (re)created for the frame size, and +/// for frames in memory or on the surface path. pub struct MediaCodecEncoder { codec: Codec, config: EncoderConfig, session: Option, + /// The surface path failed: frames in memory only from now on. + surface_failed: bool, +} + +impl Drop for MediaCodecEncoder { + fn drop(&mut self) { + // Its surface goes first. + self.session = None; + LIVE.fetch_sub(1, Ordering::Relaxed); + } } struct EncoderSession { @@ -178,6 +250,18 @@ struct EncoderSession { /// Staging buffer for the codec's input layout. staging: Vec, last_pts_us: Option, + /// The surface path: the generation of the input surface it published. + surface: Option, +} + +impl Drop for EncoderSession { + fn drop(&mut self) { + let Some(generation) = self.surface else { return }; + let mut slot = SURFACE.lock().unwrap_or_else(PoisonError::into_inner); + if slot.as_ref().is_some_and(|s| s.generation == generation) { + *slot = None; + } + } } impl MediaCodecEncoder { @@ -241,11 +325,54 @@ impl MediaCodecEncoder { parameter_sets: Vec::new(), staging: Vec::new(), last_pts_us: None, + surface: None, }); } } Err(encoder_error(codec, "no working configuration", last_error)) } + + /// Start a codec for `width` x `height` that takes its pictures through + /// an input surface, and publish the surface for the screen capture. + fn start_surface(&self, width: u32, height: u32) -> Result { + let codec = self.codec; + let profiles: &[Option] = if codec == Codec::H264 { + &[Some(AVC_PROFILE_CONSTRAINED_HIGH), Some(AVC_PROFILE_HIGH), None] + } else { + &[None] + }; + let mut last_error = String::from("no configuration tried"); + for &profile in profiles { + let handle = Handle( + MediaCodec::from_encoder_type(mime(codec)) + .ok_or_else(|| encoder_error(codec, "create", "no encoder"))?, + ); + let mut format = self.format(width, height, COLOR_FORMAT_SURFACE, profile); + // The display renders at its own rate; encode at most ours. + format.set_f32("max-fps-to-encoder", self.config.fps.max(1) as f32); + format.set_i64("repeat-previous-frame-after", REPEAT_AFTER_US); + if let Err(e) = handle.0.configure(&format, None, MediaCodecDirection::Encoder) { + last_error = format!("configure surface input/{profile:?}: {e}"); + continue; + } + let window = + handle.0.create_input_surface().map_err(|e| encoder_error(codec, "surface", e))?; + handle.0.start().map_err(|e| encoder_error(codec, "start", e))?; + let generation = GENERATION.fetch_add(1, Ordering::Relaxed) + 1; + *SURFACE.lock().unwrap_or_else(PoisonError::into_inner) = + Some(InputSurface { window, width, height, generation }); + debug!(%codec, width, height, ?profile, "MediaCodec encoder on the surface path"); + return Ok(EncoderSession { + handle, + layout: ImageLayout::nv12(width, height, 0, 0), + parameter_sets: Vec::new(), + staging: Vec::new(), + last_pts_us: None, + surface: Some(generation), + }); + } + Err(encoder_error(codec, "no surface configuration", last_error)) + } } /// Where the encoder wants its input: `image-data` if it says, else the @@ -310,7 +437,9 @@ impl VideoEncoder for MediaCodecEncoder { .session .as_ref() .is_some_and(|s| (s.layout.width, s.layout.height) != (width, height)); - if resized || self.session.is_none() { + // Frames in memory again after the surface path: a codec for them. + let surface = self.session.as_ref().is_some_and(|s| s.surface.is_some()); + if resized || surface || self.session.is_none() { self.session = None; self.session = Some(self.start(width, height)?); } @@ -367,7 +496,72 @@ impl VideoEncoder for MediaCodecEncoder { // The codec is still busy: skip this frame (rate control). DequeuedInputBufferResult::TryAgainLater => {} } - drain_encoder(codec, session) + drain_encoder(codec, session, OUTPUT_WAIT) + } + + /// Only while it is the only MediaCodec encoder: one input surface + /// takes the screen (see the [module docs](self)). + fn gpu_alignment(&self) -> Option<(u32, u32)> { + (!self.surface_failed && LIVE.load(Ordering::Relaxed) == 1).then_some((2, 2)) + } + + /// A picture is due: on the first one (and when the size changes) the + /// codec starts on the surface path; then what it encoded since goes to + /// `out`. + fn encode_gpu( + &mut self, + frame: &GpuFrame, + force_keyframe: bool, + out: &mut dyn FnMut(EncodedChunk<'_>), + ) -> Result<()> { + let codec = self.codec; + let (width, height) = (frame.width & !1, frame.height & !1); + if width == 0 || height == 0 { + return Err(Error::InvalidFrame(format!("{}x{} frame", frame.width, frame.height))); + } + let current = self.session.as_ref().is_some_and(|s| { + s.surface.is_some() && (s.layout.width, s.layout.height) == (width, height) + }); + if !current { + self.session = None; + match self.start_surface(width, height) { + Ok(session) => self.session = Some(session), + Err(e) => { + // Frames in memory from now on (the capture follows + // `gpu_alignment`). + self.surface_failed = true; + return Err(e); + } + } + } else if force_keyframe { + let mut params = MediaFormat::new(); + params.set_i32("request-sync", 0); + let session = self.session.as_ref().expect("checked above"); + session + .handle + .0 + .set_parameters(params) + .map_err(|e| encoder_error(codec, "request keyframe", e))?; + } + let session = self.session.as_mut().expect("started above"); + // Wait up to half a frame for what the display rendered. + let wait = Duration::from_micros(500_000 / u64::from(self.config.fps.max(1))); + for f in drain_encoder(codec, session, wait)? { + out(EncodedChunk { data: &f.data, keyframe: f.keyframe, pts_90khz: f.pts_90khz }); + } + Ok(()) + } + + /// On the surface path the rate caps what the codec takes from the + /// display (`max-fps-to-encoder`, fixed when it starts): the next + /// picture starts it anew. Frames in memory follow their timestamps. + fn set_fps(&mut self, fps: u32) -> Result<()> { + let fps = fps.max(1); + if fps != self.config.fps && self.session.as_ref().is_some_and(|s| s.surface.is_some()) { + self.session = None; + } + self.config.fps = fps; + Ok(()) } fn set_bitrate(&mut self, bps: u32) -> Result<()> { @@ -385,10 +579,15 @@ impl VideoEncoder for MediaCodecEncoder { } } -/// Collect what the encoder has finished. -fn drain_encoder(codec: Codec, session: &mut EncoderSession) -> Result> { +/// Collect what the encoder has finished, waiting up to `wait` for the +/// first of it. +fn drain_encoder( + codec: Codec, + session: &mut EncoderSession, + wait: Duration, +) -> Result> { let mut out = Vec::new(); - let mut wait = OUTPUT_WAIT; + let mut wait = wait; loop { let result = session .handle @@ -424,7 +623,15 @@ fn drain_encoder(codec: Codec, session: &mut EncoderSession) -> Result Self { + Self { width, height, timestamp } + } + + /// Such a picture as a simulcast layer of `width` x `height` sees it + /// (Android: the encoder draws the screen at its own size). + #[cfg(target_os = "android")] + pub fn sized(&self, width: u32, height: u32) -> Self { + Self { + width, + height, + timestamp: self.timestamp, + #[cfg(feature = "ffmpeg")] + surface: self.surface.new_ref(), + } + } + /// 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 { diff --git a/docs/media.md b/docs/media.md index b121203..817664a 100644 --- a/docs/media.md +++ b/docs/media.md @@ -20,8 +20,8 @@ video, recording, a replay buffer, WHIP) is described in | `AudioBuffer { samples, channels, timestamp }` | interleaved `f32`, 48 kHz | | `convert::to_rgba(&frame, out, stride)`, `to_rgba_vec`, `to_i420`, `psnr` | BT.601 limited range (the WebRTC default). `to_rgba` writes straight into a Slint `SharedPixelBuffer` (`make_mut_bytes()`, stride `width * 4`) | | `Codec` | `Vp8`, `Vp9`, `H264`, `Av1`; `FromStr` for SDP/MIME names; `From`/`TryFrom` `str0m::format::Codec` with feature `str0m` | -| `VideoEncoder` | `encode(&frame, force_keyframe) -> Vec`; `encode_with(&frame, force_keyframe, &mut |EncodedChunk| ..)` hands out the encoder's own buffer (no copy); `set_bitrate(bps)` (libvpx: in place, no keyframe), `set_fps`, `speed()`, `codec()`, `backend()`; `gpu_alignment()` / `encode_gpu(&GpuFrame, ..)` for encoders that take frames in GPU memory (VA-API) | -| `GpuFrame` | a picture in GPU memory (an NV12 VA-API surface), made by `ffmpeg::GpuConverter` from a captured DMA-BUF; `width`, `height`, `timestamp`, `at(timestamp)` (the same surface at another time) | +| `VideoEncoder` | `encode(&frame, force_keyframe) -> Vec`; `encode_with(&frame, force_keyframe, &mut |EncodedChunk| ..)` hands out the encoder's own buffer (no copy); `set_bitrate(bps)` (libvpx: in place, no keyframe), `set_fps`, `speed()`, `codec()`, `backend()`; `gpu_alignment()` / `encode_gpu(&GpuFrame, ..)` for encoders that take frames in GPU memory (VA-API; MediaCodec's surface path on Android) | +| `GpuFrame` | a picture in GPU memory (an NV12 VA-API surface), made by `ffmpeg::GpuConverter` from a captured DMA-BUF; `width`, `height`, `timestamp`, `at(timestamp)` (the same surface at another time). On Android `rendered(width, height, timestamp)`: a screen picture the virtual display renders straight into MediaCodec's input surface, only its size and time travel | | `EncodedFrame { data, keyframe, pts_90khz }` | one frame for `Peer::write` | | `VideoDecoder` | `decode(&[u8]) -> Option` (timestamp zero; the caller knows the RTP time) | | `EncoderConfig { fps, bitrate_bps, keyframe_interval, content, threads, speed }` | resolution follows the frames; a size change restarts with a keyframe; `threads` is a maximum (0: all CPUs but one), still capped at one per 320x240 pixels; `speed: None` adapts libvpx `cpu-used` to the encode time | @@ -492,6 +492,25 @@ changes at runtime (`video-bitrate`). Encoder order: the device's hardware encoders (H.264, VP9, VP8), then Google's software VP8 and H.264. Decoders return the newest finished picture per `decode` call (NV12 or I420). +The zero-copy path for screen sharing: while it is the only MediaCodec +encoder in the process (one simulcast layer, one codec), an encoder reports a +`gpu_alignment`, and the capture's sink then takes `GpuFrame`s. The Android +provider's ticker hands it one per frame at the stream's rate; for the first +the encoder starts a codec with an input surface (`createInputSurface`, +`COLOR_FormatSurface`, `max-fps-to-encoder` at the stream's rate, +`repeat-previous-frame-after` 100 ms so a still screen still answers keyframe +requests) and publishes it (`mediacodec::input_surface`); the app points its +virtual display at that surface (`Bridge.setScreenSurface`, resized to the +layer's size), so the compositor renders the screen into the encoder: no +`ImageReader` frame, no RGBA to NV12 conversion, no copy. Each `GpuFrame` +then only collects what the codec encoded since; presentation times are the +display's (`CLOCK_MONOTONIC`), moved onto the capture's timeline. A second +encoder (another simulcast layer, another codec a viewer chose) turns the +path off for every encoder: the display goes back to the reader and frames +in memory, until it is the only one again. An encoder whose surface fails to +start stays on frames in memory. A frame-rate change restarts the surface +codec (the cap is fixed when it starts). + libvpx settings follow libwebrtc's realtime setup: one pass CBR, no lag, `VPX_DL_REALTIME`, error resilient, keyframes only at start and on request unless `keyframe_interval` is set, screen content tuning @@ -559,7 +578,7 @@ found at ..."). | Linux Wayland (`pipewire`, default) | `PortalCapture`: xdg-desktop-portal ScreenCast via `ashpd`, frames from a PipeWire video stream (LINEAR DMA-BUF or shared memory) | `PipeWireAudioCapture`: default sink monitor (`stream.capture.sink = true`) | | Linux wlroots (`wlroots`, default) | `WlrootsCapture`: `ext-image-copy-capture-v1`, else `wlr-screencopy-unstable-v1`, outputs only, shared memory | | | Windows | `WindowsCapture`: Windows Graphics Capture (`windows-capture`), monitors and windows | `WasapiLoopback`: process loopback excluding our own process tree, falling back to plain loopback | -| Android | `ExternalScreenCapture` fed by the app (MediaProjection → `ImageReader`, RGBA; see [android.md](android.md)) | `ExternalAudioCapture` fed by the app (`AudioPlaybackCapture` of every app but ours, 48 kHz float) | +| Android | `ExternalScreenCapture` fed by the app (MediaProjection → `ImageReader`, RGBA borrowed from the reader; or straight into the MediaCodec encoder's input surface, see [MediaCodec](#codecs); [android.md](android.md)) | `ExternalAudioCapture` fed by the app (`AudioPlaybackCapture` of every app but ours, 48 kHz float) | `default_screen_capture()` picks a registered external provider first (`capture::external::set_screen_provider`, which the Android app calls at @@ -623,7 +642,8 @@ renders into one buffer, conversion and scaling write into recycled frames, handoffs are atomic pointer swaps, and libvpx output is borrowed. The one allocation per encoded frame is the `Arc<[u8]>` of `EncodedFrame`, whose size varies per frame and so cannot be recycled. Backends outside our control add -their own (x11rb reply buffers; the Android provider hands owned frames). +their own (x11rb reply buffers; the Android provider's `start` path copies +frames into the queue, its `start_sink` path, the one streams use, does not). ```sh # The real pipeline on the test pattern, no server: @@ -956,3 +976,4 @@ has not run on Windows yet. | External capture providers (start, refusal, end of capture, default selection) | unit tests | tested | | MediaCodec buffer layouts (I420, NV12 with padding, `MediaImage2` NV21, crop) | unit tests (`codec::image_layout`) | tested | | MediaCodec encoders and decoders | – | compiles for `aarch64-linux-android` only (no device or emulator here) | +| MediaCodec zero-copy screen path (virtual display into the encoder's input surface, back to the reader for simulcast) | `cargo ndk -t arm64-v8a clippy` | compiles only (no device or emulator here; fps and CPU not measured) |