Android: share the screen into the encoder without a copy
Screen sharing went MediaProjection -> ImageReader -> an owned Vec per frame -> RGBA to NV12 on the CPU -> MediaCodec's input buffers: two copies and a conversion of every frame on a phone's CPU. Now, while it is the only MediaCodec encoder in the process (one simulcast layer, one codec), an encoder takes GpuFrames: for the first it starts a codec with an input surface (COLOR_FormatSurface, max-fps-to-encoder at the stream's rate, repeat-previous-frame-after so a still screen answers keyframe requests) and publishes it, and the capture points its virtual display at that surface, resized to the layer's size. The compositor renders the screen into the encoder; a ticker at the stream's rate hands the sink GpuFrames that only collect what the codec encoded, on the capture's timeline. Simulcast keeps working by falling back: a second encoder (another layer, or another codec a viewer chose) turns the path off for every encoder and the display goes back to the reader, until it is the only one again. One display can only render into one surface, and a GL fan-out to several encoder surfaces is a lot of code for a case phones rarely need. An encoder whose surface fails stays on frames in memory. The fallback path no longer copies either: the provider's start_sink hands the reader's buffer to the stream's sink borrowed. A frame-rate change restarts the surface codec (its cap is fixed when it starts), and the display is detached while it is resized, so neither consumer sees a picture of the other's size. Compiled for aarch64-linux-android only: there is no device here, so frames per second and CPU use are not measured. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
ecb0e11668
commit
c79bb7dd07
10 files changed
+635
-59
No files matched your search
@@ -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,
|
||||
|
||||
@@ -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<R>(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<Box<dyn FrameSink>>,
|
||||
/// 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<u64>,
|
||||
}
|
||||
|
||||
static VIDEO: Mutex<Option<Video>> = Mutex::new(None);
|
||||
|
||||
fn with_video<R>(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<i64>, now_ns: i64) -> Duration {
|
||||
|
||||
struct Projection;
|
||||
|
||||
impl Projection {
|
||||
/// Ask for consent; `Ok` once the capture runs.
|
||||
fn request(options: &CaptureOptions, tx: oneshot::Sender<Result<()>>) -> 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<VideoFrame>,
|
||||
) -> 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<dyn FrameSink>,
|
||||
) -> 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<Option<InputSurface>> = 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<String>) {
|
||||
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<String>) {
|
||||
}
|
||||
|
||||
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<u8>,
|
||||
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;
|
||||
|
||||
Reference in new issue
Block a user