From 80f8a4dc50f8490d872e6d48c396f9e707a286cc Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 26 Sep 2026 10:31:17 +0000 Subject: [PATCH] wip: tsc-android engine host, JNI bridge, MediaProjection capture, MediaCodec --- Cargo.lock | 2 + crates/tsc-android/Cargo.toml | 11 +- crates/tsc-android/src/app.rs | 119 +++++ crates/tsc-android/src/bridge.rs | 255 ++++++++++ crates/tsc-android/src/capture.rs | 210 ++++++++ crates/tsc-android/src/foreground.rs | 106 ++++ crates/tsc-android/src/host.rs | 314 ++++++++++++ crates/tsc-android/src/lib.rs | 31 +- crates/tsc-android/src/secrets.rs | 29 ++ crates/tsc-media/Cargo.toml | 3 + crates/tsc-media/src/capture/external.rs | 274 ++++++++++ crates/tsc-media/src/capture/mod.rs | 14 +- crates/tsc-media/src/codec/hw.rs | 5 + crates/tsc-media/src/codec/image_layout.rs | 317 ++++++++++++ crates/tsc-media/src/codec/mediacodec.rs | 558 +++++++++++++++++++++ crates/tsc-media/src/codec/mod.rs | 13 + crates/tsc-ui/Cargo.toml | 9 +- crates/tsc-ui/src/app.rs | 105 +++- crates/tsc-ui/src/lib.rs | 2 +- 19 files changed, 2347 insertions(+), 30 deletions(-) create mode 100644 crates/tsc-android/src/app.rs create mode 100644 crates/tsc-android/src/bridge.rs create mode 100644 crates/tsc-android/src/capture.rs create mode 100644 crates/tsc-android/src/foreground.rs create mode 100644 crates/tsc-android/src/host.rs create mode 100644 crates/tsc-android/src/secrets.rs create mode 100644 crates/tsc-media/src/capture/external.rs create mode 100644 crates/tsc-media/src/codec/image_layout.rs create mode 100644 crates/tsc-media/src/codec/mediacodec.rs diff --git a/Cargo.lock b/Cargo.lock index cf5d08e..9f0cc3d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8672,6 +8672,7 @@ dependencies = [ name = "tsc-android" version = "0.1.0" dependencies = [ + "anyhow", "jni 0.22.4", "rustls-platform-verifier", "slint", @@ -8776,6 +8777,7 @@ dependencies = [ "dav1d", "libvpx-native-sys", "memmap2", + "ndk 0.9.0", "openh264", "pipewire", "reqwest", diff --git a/crates/tsc-android/Cargo.toml b/crates/tsc-android/Cargo.toml index c4274a7..3f27c20 100644 --- a/crates/tsc-android/Cargo.toml +++ b/crates/tsc-android/Cargo.toml @@ -18,16 +18,19 @@ crate-type = ["cdylib", "rlib"] tokio = { version = "1.53.1", features = ["rt-multi-thread", "macros", "sync", "time"] } tracing = "0.1.44" tsc-core = { path = "../tsc-core" } -tsc-media = { path = "../tsc-media", default-features = false } -tsc-model = { path = "../tsc-model" } -tsc-store = { path = "../tsc-store" } [target.'cfg(target_os = "android")'.dependencies] +anyhow = "1.0.104" jni = "0.22.4" rustls-platform-verifier = "0.7.1" -slint = { version = "1.18", features = ["backend-android-activity-06"] } +slint = { version = "1.18", default-features = false, features = ["std", "compat-1-2", "backend-android-activity-06"] } tracing-subscriber = { version = "0.3.23", features = ["env-filter"] } +tsc-media = { path = "../tsc-media", default-features = false } +tsc-store = { path = "../tsc-store" } tsc-ui = { path = "../tsc-ui" } +[dev-dependencies] +tsc-model = { path = "../tsc-model" } + [lints] workspace = true diff --git a/crates/tsc-android/src/app.rs b/crates/tsc-android/src/app.rs new file mode 100644 index 0000000..db39416 --- /dev/null +++ b/crates/tsc-android/src/app.rs @@ -0,0 +1,119 @@ +//! `android_main`: the activity's native thread. +//! +//! android-activity calls it on a new thread for every activity instance +//! (the process can outlive activities while voice runs in the service). +//! Process-wide setup happens once; the window is built per activity. + +use std::sync::{Mutex, Once, OnceLock, PoisonError}; + +use anyhow::Context as _; +use slint::android::AndroidApp; +use tracing::{error, info, warn}; +use tsc_core::Command; + +use crate::foreground::Foreground; +use crate::host::EngineHost; +use crate::{bridge, capture, secrets}; + +static HOST: OnceLock = OnceLock::new(); +static FOREGROUND: Mutex> = Mutex::new(None); + +fn host() -> anyhow::Result<&'static EngineHost> { + if let Some(host) = HOST.get() { + return Ok(host); + } + let host = EngineHost::start().context("starting the engine runtime")?; + Ok(HOST.get_or_init(|| host)) +} + +fn with_foreground(f: impl FnOnce(&mut Foreground) -> R) -> R { + let mut guard = FOREGROUND.lock().unwrap_or_else(PoisonError::into_inner); + f(guard.get_or_insert_with(Foreground::default)) +} + +/// The entry point android-activity looks up in this library. +#[allow(unsafe_code)] // an exported symbol +#[unsafe(no_mangle)] +fn android_main(app: AndroidApp) { + init_logging(); + info!("android_main"); + if let Err(e) = run(app) { + error!("{e:#}"); + } + info!("android_main done"); +} + +fn init_logging() { + // android-activity forwards stderr to logcat (tag RustStdoutStderr). + let filter = tracing_subscriber::EnvFilter::try_from_default_env() + .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")); + let _ = tracing_subscriber::fmt() + .with_env_filter(filter) + .with_ansi(false) + .without_time() + .with_writer(std::io::stderr) + .try_init(); +} + +fn run(app: AndroidApp) -> anyhow::Result<()> { + jni::JavaVM::singleton()?.attach_current_thread(|env| -> jni::errors::Result<()> { + bridge::init(env)?; + // reqwest (HTTPS queries, tsclientlib) verifies certificates with + // the system's trust store through rustls-platform-verifier. + let context = bridge::context(env)?; + rustls_platform_verifier::android::init_with_env(env, context)?; + Ok(()) + })?; + let host = host()?; + static PROCESS: Once = Once::new(); + PROCESS.call_once(|| { + capture::register(); + watch_voice(host); + }); + if let Err(e) = bridge::request_permissions() { + warn!("requesting permissions: {e}"); + } + + let data_dir = app.internal_data_path().context("the app has no internal storage path")?; + slint::android::init(app).context("Slint Android backend")?; + let attached = host.attach(); + tsc_ui::run(tsc_ui::RunOptions { + data_dir: Some(data_dir), + secrets: Some(Box::new(secrets::KeystoreSecrets)), + engine: Some(tsc_ui::HostedEngine { + engine: attached.engine, + runtime: attached.runtime, + events: attached.events, + }), + }) +} + +/// Keep the voice foreground service in step with the voice connections. +fn watch_voice(host: &'static EngineHost) { + let mut events = host.engine().subscribe(); + host.runtime().spawn(async move { + loop { + match events.recv().await { + Ok(event) => { + if let Some(text) = with_foreground(|f| f.update(&event)) { + if let Err(e) = bridge::set_voice_notification(text.as_deref()) { + warn!("voice service: {e}"); + } + } + } + Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue, + Err(tokio::sync::broadcast::error::RecvError::Closed) => break, + } + } + }); +} + +/// "Disconnect" in the voice notification. +pub fn disconnect_voice() { + let Some(host) = HOST.get() else { + return; + }; + for session in with_foreground(|f| f.voice_sessions()) { + host.engine().send(Command::DisconnectVoice { session }); + } +} diff --git a/crates/tsc-android/src/bridge.rs b/crates/tsc-android/src/bridge.rs new file mode 100644 index 0000000..59ec77f --- /dev/null +++ b/crates/tsc-android/src/bridge.rs @@ -0,0 +1,255 @@ +//! JNI glue with the app's Kotlin side (`android/app/src/main/java/...`). +//! +//! - Rust → Kotlin: static methods of `io.github.faumaray.tsc.Bridge`, called +//! from any thread (the class is looked up once on the `android_main` +//! thread, whose class loader sees the app's classes). +//! - Kotlin → Rust: the `external` methods of `io.github.faumaray.tsc.Native`, +//! exported below with `native_method!` (panics and errors become Java +//! exceptions instead of crossing the FFI boundary). + +use std::sync::OnceLock; + +use jni::errors::{Error, Result}; +use jni::objects::{JByteBuffer, JClass, JFloatArray, JObject, JString, JValue}; +use jni::refs::{Global, Reference as _}; +use jni::sys::{jboolean, jint, jlong}; +use jni::{Env, JavaVM, jni_sig, jni_str, native_method}; + +static BRIDGE: OnceLock>> = OnceLock::new(); + +/// Look up `Bridge` (on the `android_main` thread). +pub fn init(env: &mut Env) -> Result<()> { + if BRIDGE.get().is_none() { + let class = env.load_class(jni_str!("io.github.faumaray.tsc.Bridge"))?; + let _ = BRIDGE.set(env.new_global_ref(class)?); + } + Ok(()) +} + +/// Run `f` with an attached thread and the `Bridge` class. +fn with_bridge(f: impl FnOnce(&mut Env, &Global>) -> Result) -> Result { + let class = BRIDGE + .get() + .ok_or_else(|| Error::ClassNotFound { name: "io.github.faumaray.tsc.Bridge".into() })?; + JavaVM::singleton()?.attach_current_thread(|env| f(env, class)) +} + +/// The application `Context`, as a local reference of `env`'s frame. +pub fn context<'local>(env: &mut Env<'local>) -> Result> { + let class = BRIDGE + .get() + .ok_or_else(|| Error::ClassNotFound { name: "io.github.faumaray.tsc.Bridge".into() })?; + env.call_static_method(class, jni_str!("context"), jni_sig!(() -> android.content.Context), &[])? + .l() +} + +/// Ask for the microphone and notification permissions if not granted yet. +pub fn request_permissions() -> Result<()> { + with_bridge(|env, class| { + env.call_static_method(class, jni_str!("requestPermissions"), jni_sig!(() -> void), &[])?; + Ok(()) + }) +} + +/// Show or update the voice service's notification; `None` stops the service. +pub fn set_voice_notification(text: Option<&str>) -> Result<()> { + with_bridge(|env, class| { + let text = match text { + Some(text) => JObject::from(env.new_string(text)?), + None => JObject::null(), + }; + env.call_static_method( + class, + jni_str!("setVoiceNotification"), + jni_sig!((text: java.lang.String) -> void), + &[JValue::Object(&text)], + )?; + 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<()> { + with_bridge(|env, class| { + env.call_static_method( + class, + jni_str!("requestScreenCapture"), + jni_sig!((fps: jint, max_size: jint) -> void), + &[JValue::Int(fps as jint), JValue::Int(max_size as jint)], + )?; + Ok(()) + }) +} + +pub fn stop_screen_capture() -> Result<()> { + with_bridge(|env, class| { + env.call_static_method(class, jni_str!("stopScreenCapture"), jni_sig!(() -> void), &[])?; + Ok(()) + }) +} + +/// Capture what the device plays; `false` without a running screen capture. +pub fn start_system_audio() -> Result { + with_bridge(|env, class| { + env.call_static_method(class, jni_str!("startSystemAudio"), jni_sig!(() -> jboolean), &[])? + .z() + }) +} + +pub fn stop_system_audio() -> Result<()> { + with_bridge(|env, class| { + env.call_static_method(class, jni_str!("stopSystemAudio"), jni_sig!(() -> void), &[])?; + Ok(()) + }) +} + +pub fn secret_get(key: &str) -> Result> { + with_bridge(|env, class| { + let key = JObject::from(env.new_string(key)?); + let value = env + .call_static_method( + class, + jni_str!("secretGet"), + jni_sig!((key: java.lang.String) -> java.lang.String), + &[JValue::Object(&key)], + )? + .l()?; + if value.is_null() { + return Ok(None); + } + let value = env.cast_local::(value)?; + Ok(Some(value.try_to_string(env)?)) + }) +} + +pub fn secret_set(key: &str, value: &str) -> Result<()> { + with_bridge(|env, class| { + let key = JObject::from(env.new_string(key)?); + let value = JObject::from(env.new_string(value)?); + env.call_static_method( + class, + jni_str!("secretSet"), + jni_sig!((key: java.lang.String, value: java.lang.String) -> void), + &[JValue::Object(&key), JValue::Object(&value)], + )?; + Ok(()) + }) +} + +pub fn secret_delete(key: &str) -> Result<()> { + with_bridge(|env, class| { + let key = JObject::from(env.new_string(key)?); + env.call_static_method( + class, + jni_str!("secretDelete"), + jni_sig!((key: java.lang.String) -> void), + &[JValue::Object(&key)], + )?; + Ok(()) + }) +} + +// Native methods of `Native` (Kotlin `object` with `@JvmStatic external`). + +const _: jni::NativeMethod = native_method! { + java_type = "io.github.faumaray.tsc.Native", + static extern fn on_screen_capture_result(granted: jboolean, error: JString), +}; + +fn on_screen_capture_result<'local>( + env: &mut Env<'local>, + _class: JClass<'local>, + granted: jboolean, + error: JString<'local>, +) -> Result<()> { + let error = if error.is_null() { None } else { Some(error.try_to_string(env)?) }; + crate::capture::on_result(granted, error); + Ok(()) +} + +const _: jni::NativeMethod = native_method! { + java_type = "io.github.faumaray.tsc.Native", + static extern fn on_screen_frame( + pixels: JByteBuffer, + width: jint, + height: jint, + row_stride: jint, + timestamp_ns: jlong, + ) -> jboolean, +}; + +/// An RGBA frame from the `ImageReader`. Returns `false` when frames are no +/// longer wanted (the service then stops capturing). +fn on_screen_frame<'local>( + env: &mut Env<'local>, + _class: JClass<'local>, + pixels: JByteBuffer<'local>, + width: jint, + height: jint, + row_stride: jint, + timestamp_ns: jlong, +) -> Result { + if !crate::capture::wants_frames() { + return Ok(false); + } + let address = env.get_direct_buffer_address(&pixels)?; + let capacity = env.get_direct_buffer_capacity(&pixels)?; + if address.is_null() { + 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. + #[allow(unsafe_code)] + let bytes = unsafe { std::slice::from_raw_parts(address, capacity) }.to_vec(); + Ok(crate::capture::on_frame( + bytes, + width.max(0) as u32, + height.max(0) as u32, + row_stride.max(0) as usize, + timestamp_ns, + )) +} + +const _: jni::NativeMethod = native_method! { + java_type = "io.github.faumaray.tsc.Native", + static extern fn on_screen_capture_stopped(), +}; + +fn on_screen_capture_stopped<'local>(_env: &mut Env<'local>, _class: JClass<'local>) -> Result<()> { + crate::capture::on_stopped(); + Ok(()) +} + +const _: jni::NativeMethod = native_method! { + java_type = "io.github.faumaray.tsc.Native", + static extern fn on_system_audio(samples: jfloat[], count: jint, channels: jint, timestamp_ns: jlong) -> jboolean, +}; + +/// Interleaved 48 kHz float samples of what the device plays. +fn on_system_audio<'local>( + env: &mut Env<'local>, + _class: JClass<'local>, + samples: JFloatArray<'local>, + count: jint, + channels: jint, + timestamp_ns: jlong, +) -> Result { + if !crate::capture::wants_audio() { + return Ok(false); + } + let mut buffer = vec![0f32; count.max(0) as usize]; + samples.get_region(env, 0, &mut buffer)?; + Ok(crate::capture::on_audio(buffer, channels.clamp(1, 8) as u16, timestamp_ns)) +} + +const _: jni::NativeMethod = native_method! { + java_type = "io.github.faumaray.tsc.Native", + static extern fn on_disconnect_voice(), +}; + +/// "Disconnect" in the voice notification. +fn on_disconnect_voice<'local>(_env: &mut Env<'local>, _class: JClass<'local>) -> Result<()> { + crate::app::disconnect_voice(); + Ok(()) +} diff --git a/crates/tsc-android/src/capture.rs b/crates/tsc-android/src/capture.rs new file mode 100644 index 0000000..f34decf --- /dev/null +++ b/crates/tsc-android/src/capture.rs @@ -0,0 +1,210 @@ +//! Screen and system-audio capture through MediaProjection. +//! +//! Registered as `tsc_media` capture providers, so stream code captures with +//! `tsc_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. + +use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; +use std::time::Duration; + +use tokio::sync::oneshot; +use tracing::warn; +use tsc_media::capture::external::{self, AudioProvider, ScreenProvider}; +use tsc_media::capture::{BoxFuture, CaptureOptions, CaptureSource, SourceId}; +use tsc_media::{AudioBuffer, Error, FrameSender, Result, VideoFrame}; + +use crate::bridge; + +const SCREEN: &str = "mediaprojection"; +const AUDIO: &str = "playbackcapture"; +/// Longest side of captured frames (the service scales the display down). +const MAX_SIZE: u32 = 1920; + +#[derive(Default)] +struct State { + frames: Option>, + /// Answer for the pending `start`. + pending: Option>>, + audio: Option>, + first_frame_ns: Option, + first_audio_ns: Option, +} + +static STATE: Mutex> = Mutex::new(None); + +fn with_state(f: impl FnOnce(&mut State) -> R) -> R { + let mut guard: MutexGuard<'_, Option> = + STATE.lock().unwrap_or_else(PoisonError::into_inner); + f(guard.get_or_insert_with(State::default)) +} + +/// Make MediaProjection the default screen and audio capture. +pub fn register() { + external::set_screen_provider(Some(Arc::new(Projection))); + external::set_audio_provider(Some(Arc::new(PlaybackAudio))); +} + +fn since(first: &mut Option, now_ns: i64) -> Duration { + let first = *first.get_or_insert(now_ns); + Duration::from_nanos(u64::try_from(now_ns - first).unwrap_or(0)) +} + +struct Projection; + +impl ScreenProvider for Projection { + fn name(&self) -> &'static str { + SCREEN + } + + fn sources(&self) -> Vec { + vec![CaptureSource { + // The system dialog picks (whole screen, or one app on Android 14+). + id: SourceId::Portal, + name: "Screen".into(), + width: 0, + height: 0, + primary: true, + }] + } + + fn start( + &self, + _source: &SourceId, + options: &CaptureOptions, + 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.first_frame_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) }); + } + Box::pin(async move { rx.await.unwrap_or(Err(Error::Cancelled)) }) + } + + fn stop(&self) { + on_stopped(); + if let Err(e) = bridge::stop_screen_capture() { + warn!("stopping screen capture: {e}"); + } + } +} + +struct PlaybackAudio; + +impl AudioProvider for PlaybackAudio { + fn name(&self) -> &'static str { + AUDIO + } + + fn start(&self, buffers: FrameSender) -> Result<()> { + with_state(|s| { + s.audio = Some(buffers); + s.first_audio_ns = None; + }); + let started = bridge::start_system_audio(); + match started { + Ok(true) => Ok(()), + Ok(false) | Err(_) => { + with_state(|s| s.audio = None); + let reason = match started { + Err(e) => e.to_string(), + _ => "needs a running screen capture (and the microphone permission)".into(), + }; + Err(Error::CaptureUnavailable { backend: AUDIO, reason }) + } + } + } + + fn stop(&self) { + with_state(|s| s.audio = None); + if let Err(e) = bridge::stop_system_audio() { + warn!("stopping system audio: {e}"); + } + } +} + +/// The user answered the consent dialog (or the service failed to start). +pub fn on_result(granted: bool, error: Option) { + with_state(|s| { + let result = match (granted, error) { + (true, _) => Ok(()), + (false, None) => Err(Error::Cancelled), + (false, Some(message)) => Err(Error::Capture { backend: SCREEN, message }), + }; + if result.is_err() { + s.frames = None; + } + if let Some(pending) = s.pending.take() { + let _ = pending.send(result); + } + }); +} + +pub fn wants_frames() -> bool { + 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| { + let timestamp = since(&mut s.first_frame_ns, timestamp_ns); + let Some(frames) = &s.frames else { + return false; + }; + match VideoFrame::from_rgba(width, height, stride, pixels) { + Ok(frame) => { + if !frames.send(frame.with_timestamp(timestamp)) { + s.frames = None; + return false; + } + } + Err(e) => warn!("dropping a screen frame: {e}"), + } + true + }) +} + +/// The projection ended (stopped by us, the user, or the system): the +/// consumers see their channels close. +pub fn on_stopped() { + with_state(|s| { + s.frames = None; + s.audio = None; + if let Some(pending) = s.pending.take() { + let _ = pending.send(Err(Error::Cancelled)); + } + }); +} + +pub fn wants_audio() -> bool { + with_state(|s| s.audio.as_ref().is_some_and(|a| !a.is_closed())) +} + +/// Captured playback audio. Returns `false` once nobody wants it. +pub fn on_audio(samples: Vec, channels: u16, timestamp_ns: i64) -> bool { + with_state(|s| { + let timestamp = since(&mut s.first_audio_ns, timestamp_ns); + let Some(audio) = &s.audio else { + return false; + }; + if !audio.send(AudioBuffer { samples, channels, timestamp }) { + s.audio = None; + return false; + } + true + }) +} diff --git a/crates/tsc-android/src/foreground.rs b/crates/tsc-android/src/foreground.rs new file mode 100644 index 0000000..6e328e4 --- /dev/null +++ b/crates/tsc-android/src/foreground.rs @@ -0,0 +1,106 @@ +//! When the app needs its voice foreground service. +//! +//! Android keeps the microphone and the process of a backgrounded app only +//! while a foreground service with a visible notification runs. The service +//! runs while any session has a voice connection (connecting or connected); +//! its notification names the servers and offers "Disconnect". + +use std::collections::BTreeMap; + +use tsc_core::{Event, SessionId, VoiceState}; + +#[derive(Default)] +pub struct Foreground { + sessions: BTreeMap, +} + +#[derive(Default)] +struct Session { + name: Option, + voice: VoiceState, +} + +impl Foreground { + /// Apply `event`. Returns the new notification text when it changed: + /// `Some(None)` means the service should stop. + pub fn update(&mut self, event: &Event) -> Option> { + let before = self.notification(); + match event { + Event::State { session, state } => { + self.sessions.entry(*session).or_default().voice = state.voice; + } + Event::ServerInfo { session, name, .. } => { + self.sessions.entry(*session).or_default().name = Some(name.clone()); + } + _ => return None, + } + let after = self.notification(); + (after != before).then_some(after) + } + + /// Sessions with a voice connection (for "Disconnect"). + pub fn voice_sessions(&self) -> Vec { + self.sessions + .iter() + .filter(|(_, s)| s.voice != VoiceState::Disconnected) + .map(|(id, _)| *id) + .collect() + } + + /// The notification text, `None` without voice. + pub fn notification(&self) -> Option { + let active: Vec<&Session> = + self.sessions.values().filter(|s| s.voice != VoiceState::Disconnected).collect(); + if active.is_empty() { + return None; + } + let names: Vec<&str> = + active.iter().map(|s| s.name.as_deref().unwrap_or("a server")).collect(); + let names = names.join(", "); + Some(if active.iter().all(|s| s.voice == VoiceState::Connecting) { + format!("Connecting to {names}") + } else { + format!("In voice on {names}") + }) + } +} + +#[cfg(test)] +mod tests { + use tsc_core::SessionState; + use tsc_model::{Capabilities, ServerFlavor}; + + use super::*; + + fn voice(session: SessionId, voice: VoiceState) -> Event { + Event::State { session, state: SessionState { voice, ..SessionState::default() } } + } + + #[test] + fn service_follows_voice_connections() { + let mut fg = Foreground::default(); + assert_eq!(fg.update(&voice(1, VoiceState::Disconnected)), None); + assert_eq!( + fg.update(&voice(1, VoiceState::Connecting)), + Some(Some("Connecting to a server".into())) + ); + let info = Event::ServerInfo { + session: 1, + name: "Home".into(), + flavor: ServerFlavor::Unknown(String::new()), + capabilities: Capabilities::default(), + }; + assert_eq!(fg.update(&info), Some(Some("Connecting to Home".into()))); + assert_eq!(fg.update(&voice(1, VoiceState::Connected)), Some(Some("In voice on Home".into()))); + assert_eq!(fg.update(&voice(1, VoiceState::Connected)), None, "no change"); + assert_eq!( + fg.update(&voice(2, VoiceState::Connecting)), + Some(Some("In voice on Home, a server".into())) + ); + assert_eq!(fg.voice_sessions(), [1, 2]); + assert_eq!(fg.update(&Event::Error { session: 1, message: "x".into() }), None); + fg.update(&voice(2, VoiceState::Disconnected)); + assert_eq!(fg.update(&voice(1, VoiceState::Disconnected)), Some(None)); + assert!(fg.voice_sessions().is_empty()); + } +} diff --git a/crates/tsc-android/src/host.rs b/crates/tsc-android/src/host.rs new file mode 100644 index 0000000..a2117b5 --- /dev/null +++ b/crates/tsc-android/src/host.rs @@ -0,0 +1,314 @@ +//! The engine for the whole process. +//! +//! Android destroys and recreates the activity (and so the window and its +//! thread) while a voice call goes on in a foreground service. The engine +//! therefore lives here, on its own runtime, for as long as the process; a +//! new window [attaches](EngineHost::attach) and first receives events that +//! rebuild the current state ([`Replay`]), then the live ones. + +use std::collections::{BTreeMap, VecDeque}; +use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; + +use tokio::runtime::{Handle, Runtime}; +use tokio::sync::{broadcast, mpsc}; +use tsc_core::{Engine, Event, SessionId, StreamState, WatchState}; + +/// Chat messages per session a new window gets back. +pub const CHAT_BACKLOG: usize = 300; + +/// The latest state-bearing events per session. +#[derive(Default)] +pub struct Replay { + sessions: BTreeMap, +} + +#[derive(Default)] +struct SessionReplay { + server_info: Option, + state: Option, + presence: Option, + streams: Option, + own_stream: Option, + viewers: Option, + watching: BTreeMap, + chat: VecDeque, +} + +impl Replay { + /// Remember what `event` changes. + pub fn record(&mut self, event: &Event) { + let session = match event { + Event::State { session, .. } + | Event::ServerInfo { session, .. } + | Event::Presence { session, .. } + | Event::Chat { session, .. } + | Event::StreamsChanged { session, .. } + | Event::StreamState { session, .. } + | Event::StreamViewers { session, .. } + | Event::WatchState { session, .. } => *session, + // Transient: talking flags, errors, requests, keyframe requests. + _ => return, + }; + let s = self.sessions.entry(session).or_default(); + let slot = Some(event.clone()); + match event { + Event::State { .. } => s.state = slot, + Event::ServerInfo { .. } => s.server_info = slot, + Event::Presence { .. } => s.presence = slot, + Event::StreamsChanged { .. } => s.streams = slot, + Event::StreamViewers { .. } => s.viewers = slot, + Event::StreamState { state, .. } => { + if matches!(state, StreamState::Ended(_)) { + s.own_stream = None; + s.viewers = None; + } else { + s.own_stream = slot; + } + } + Event::WatchState { stream_id, state, .. } => { + if matches!(state, WatchState::Ended(_)) { + s.watching.remove(stream_id); + } else { + s.watching.insert(stream_id.clone(), event.clone()); + } + } + Event::Chat { .. } => { + if s.chat.len() == CHAT_BACKLOG { + s.chat.pop_front(); + } + s.chat.push_back(event.clone()); + } + _ => {} + } + } + + /// Events that rebuild the recorded state, per session: server info, + /// state, presence, chat, then streams. + pub fn events(&self) -> Vec { + let mut out = Vec::new(); + for s in self.sessions.values() { + out.extend(s.server_info.iter().cloned()); + out.extend(s.state.iter().cloned()); + out.extend(s.presence.iter().cloned()); + out.extend(s.chat.iter().cloned()); + out.extend(s.streams.iter().cloned()); + out.extend(s.own_stream.iter().cloned()); + out.extend(s.viewers.iter().cloned()); + out.extend(s.watching.values().cloned()); + } + out + } +} + +/// Events of one source, recorded and passed on to the attached window. +#[derive(Clone, Default)] +pub struct Fanout { + shared: Arc>, +} + +#[derive(Default)] +struct FanoutState { + replay: Replay, + window: Option>, +} + +impl Fanout { + fn lock(&self) -> MutexGuard<'_, FanoutState> { + self.shared.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// Record `event` and pass it to the window, if one is attached. + pub fn publish(&self, event: Event) { + let mut state = self.lock(); + state.replay.record(&event); + if let Some(window) = &state.window + && window.send(event).is_err() + { + state.window = None; + } + } + + /// Receive events from now on, starting with the replay. A previously + /// attached window stops receiving (its channel closes). + pub fn attach(&self) -> mpsc::UnboundedReceiver { + let (tx, rx) = mpsc::unbounded_channel(); + let mut state = self.lock(); + for event in state.replay.events() { + let _ = tx.send(event); + } + state.window = Some(tx); + rx + } + + /// Forward `source` until it closes; then the window's channel closes. + pub async fn pump(self, mut source: broadcast::Receiver) { + loop { + match source.recv().await { + Ok(event) => self.publish(event), + Err(broadcast::error::RecvError::Lagged(n)) => { + tracing::warn!(missed = n, "engine events lagged"); + } + Err(broadcast::error::RecvError::Closed) => break, + } + } + self.lock().window = None; + } +} + +/// The process's engine, runtime and event fan-out. +pub struct EngineHost { + runtime: Runtime, + engine: Engine, + fanout: Fanout, +} + +/// What a window needs: see `tsc_ui::HostedEngine`. +pub struct Attached { + pub engine: Engine, + pub runtime: Handle, + pub events: mpsc::UnboundedReceiver, +} + +impl EngineHost { + pub fn start() -> std::io::Result { + let runtime = tokio::runtime::Builder::new_multi_thread() + .enable_all() + .thread_name("tsc-engine") + .build()?; + let engine = runtime.block_on(async { Engine::start() }); + let fanout = Fanout::default(); + runtime.spawn(fanout.clone().pump(engine.subscribe())); + Ok(Self { runtime, engine, fanout }) + } + + pub fn engine(&self) -> &Engine { + &self.engine + } + + pub fn runtime(&self) -> &Handle { + self.runtime.handle() + } + + /// Hand the engine to a new window. + pub fn attach(&self) -> Attached { + Attached { + engine: self.engine.clone(), + runtime: self.runtime.handle().clone(), + events: self.fanout.attach(), + } + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc as StdArc; + + use tsc_core::{SessionState, VoiceState}; + use tsc_model::{ChatMessage, ChatTarget, Presence}; + + use super::*; + + fn state(session: SessionId, voice: VoiceState) -> Event { + Event::State { session, state: SessionState { voice, ..SessionState::default() } } + } + + fn chat(session: SessionId, text: &str) -> Event { + Event::Chat { + session, + message: ChatMessage { + target: ChatTarget::Server, + author_name: "a".into(), + author_uid: None, + author_id: None, + text: text.into(), + ts_ms: 0, + via_relay: false, + }, + } + } + + fn describe(events: &[Event]) -> Vec { + events + .iter() + .map(|e| match e { + Event::State { session, state } => format!("{session} state {:?}", state.voice), + Event::Presence { session, .. } => format!("{session} presence"), + Event::Chat { session, message } => format!("{session} chat {}", message.text), + Event::WatchState { session, stream_id, .. } => { + format!("{session} watch {stream_id}") + } + other => format!("{other:?}"), + }) + .collect() + } + + #[test] + fn replay_keeps_the_latest_state_and_the_chat_backlog() { + let mut replay = Replay::default(); + replay.record(&state(2, VoiceState::Connecting)); + replay.record(&Event::Presence { session: 2, presence: StdArc::new(Presence::default()) }); + replay.record(&state(2, VoiceState::Connected)); + replay.record(&Event::Talking { session: 2, client: 5, talking: true }); + replay.record(&Event::Error { session: 2, message: "x".into() }); + for i in 0..CHAT_BACKLOG + 2 { + replay.record(&chat(1, &i.to_string())); + } + replay.record(&Event::WatchState { + session: 2, + stream_id: "s1".into(), + state: WatchState::Connected, + }); + replay.record(&Event::WatchState { + session: 2, + stream_id: "s2".into(), + state: WatchState::Requested, + }); + replay.record(&Event::WatchState { + session: 2, + stream_id: "s2".into(), + state: WatchState::Ended(tsc_core::stream::EndReason::Local), + }); + + let events = describe(&replay.events()); + assert_eq!(events.len(), CHAT_BACKLOG + 3); + assert_eq!(events[0], "1 chat 2", "the oldest messages are dropped"); + assert_eq!(events[CHAT_BACKLOG - 1], format!("1 chat {}", CHAT_BACKLOG + 1)); + assert_eq!( + events[CHAT_BACKLOG..], + ["2 state Connected", "2 presence", "2 watch s1"].map(String::from) + ); + } + + #[tokio::test] + async fn a_new_window_gets_the_replay_then_live_events() { + let (tx, rx) = broadcast::channel(16); + let fanout = Fanout::default(); + let pump = tokio::spawn(fanout.clone().pump(rx)); + + tx.send(state(1, VoiceState::Connected)).unwrap(); + tx.send(chat(1, "before")).unwrap(); + tokio::task::yield_now().await; + while fanout.lock().replay.events().len() < 2 { + tokio::task::yield_now().await; + } + + let mut first = fanout.attach(); + assert_eq!(describe(&[first.recv().await.unwrap()]), ["1 state Connected"]); + assert_eq!(describe(&[first.recv().await.unwrap()]), ["1 chat before"]); + tx.send(chat(1, "live")).unwrap(); + assert_eq!(describe(&[first.recv().await.unwrap()]), ["1 chat live"]); + + // The activity is recreated: the old window's channel ends. + let mut second = fanout.attach(); + assert!(first.recv().await.is_none()); + let mut replayed = Vec::new(); + for _ in 0..3 { + replayed.push(second.recv().await.unwrap()); + } + assert_eq!(describe(&replayed), ["1 state Connected", "1 chat before", "1 chat live"]); + + drop(tx); + pump.await.unwrap(); + assert!(second.recv().await.is_none(), "the source closed"); + } +} diff --git a/crates/tsc-android/src/lib.rs b/crates/tsc-android/src/lib.rs index 179adb7..dcd1198 100644 --- a/crates/tsc-android/src/lib.rs +++ b/crates/tsc-android/src/lib.rs @@ -1 +1,30 @@ -//! placeholder +//! The Android app's native library (`libtsc_android.so`). +//! +//! The APK (`android/`) starts a `NativeActivity` subclass that loads this +//! library; `android_main` then runs the shared Slint UI (`tsc_ui`) on +//! Slint's Android backend. The pieces around it: +//! +//! - [`host`]: one engine per process, so voice survives the activity being +//! destroyed and recreated; a new window gets the current state replayed +//! - [`foreground`]: when the voice foreground service must run (Android +//! only lets a service with a notification keep the microphone in the +//! background) +//! - `bridge` (Android): JNI calls into the Kotlin side (`Bridge`) and the +//! native methods it calls back (`Native`) +//! - `capture` (Android): screen and system-audio capture through +//! MediaProjection, registered as `tsc_media` capture providers +//! - `secrets` (Android): passwords encrypted with an Android Keystore key +//! +//! Only [`host`] and [`foreground`] build on other platforms, for tests. + +pub mod foreground; +pub mod host; + +#[cfg(target_os = "android")] +mod app; +#[cfg(target_os = "android")] +mod bridge; +#[cfg(target_os = "android")] +mod capture; +#[cfg(target_os = "android")] +mod secrets; diff --git a/crates/tsc-android/src/secrets.rs b/crates/tsc-android/src/secrets.rs new file mode 100644 index 0000000..ccdb032 --- /dev/null +++ b/crates/tsc-android/src/secrets.rs @@ -0,0 +1,29 @@ +//! Passwords in the Android Keystore. +//! +//! The Kotlin `SecretStore` encrypts each value with an AES-GCM key that +//! lives in the Android Keystore (hardware-backed where the device has it) +//! and keeps the ciphertext in the app's private preferences. + +use tsc_store::{Error, Result, Secrets}; + +use crate::bridge; + +pub struct KeystoreSecrets; + +fn error(e: jni::errors::Error) -> Error { + Error::Secrets(format!("Android Keystore: {e}")) +} + +impl Secrets for KeystoreSecrets { + fn get(&self, key: &str) -> Result> { + bridge::secret_get(key).map_err(error) + } + + fn set(&self, key: &str, value: &str) -> Result<()> { + bridge::secret_set(key, value).map_err(error) + } + + fn delete(&self, key: &str) -> Result<()> { + bridge::secret_delete(key).map_err(error) + } +} diff --git a/crates/tsc-media/Cargo.toml b/crates/tsc-media/Cargo.toml index 2e9cb5e..427736f 100644 --- a/crates/tsc-media/Cargo.toml +++ b/crates/tsc-media/Cargo.toml @@ -47,6 +47,9 @@ pipewire = { version = "0.10.1", optional = true } rustix = { version = "1.1.5", features = ["fs"], optional = true } x11rb = { version = "0.13.2", features = ["randr", "shm", "xfixes"], optional = true } +[target.'cfg(target_os = "android")'.dependencies] +ndk = { version = "0.9.0", default-features = false, features = ["media", "api-level-29"] } + [target.'cfg(windows)'.dependencies] wasapi = "0.24.0" windows-capture = "2.0.1" diff --git a/crates/tsc-media/src/capture/external.rs b/crates/tsc-media/src/capture/external.rs new file mode 100644 index 0000000..be60731 --- /dev/null +++ b/crates/tsc-media/src/capture/external.rs @@ -0,0 +1,274 @@ +//! Capture driven by platform code outside this crate. +//! +//! On Android, screen and system-audio capture need a MediaProjection, which +//! only the app's Java/Kotlin side can obtain (it asks the user and runs a +//! foreground service). The app registers a [`ScreenProvider`] and an +//! [`AudioProvider`] at start; [`super::default_screen_capture`] and +//! [`super::default_audio_capture`] then hand out capture backends that +//! forward to them, so stream code needs no platform knowledge. +//! +//! A provider receives the [`FrameSender`] of the capture and pushes frames +//! into it from any thread; dropping the sender ends the capture for the +//! consumer (e.g. when the user stops sharing from the system UI). + +use std::sync::{Arc, Mutex, PoisonError}; + +use crate::Result; +use crate::capture::{ + AudioCapture, BoxFuture, CaptureOptions, CaptureSource, ScreenCapture, SourceId, +}; +use crate::frame::{AudioBuffer, VideoFrame}; +use crate::queue::{FrameReceiver, FrameSender, frame_channel}; + +/// Platform code that captures the screen. +pub trait ScreenProvider: Send + Sync { + /// Short name for logs (`"mediaprojection"`). + fn name(&self) -> &'static str; + + /// What can be captured (Android: the whole screen, as one + /// [`SourceId::Portal`] entry since the system dialog picks). + fn sources(&self) -> Vec; + + /// Start delivering frames into `frames`. Resolves once frames flow, or + /// with an error such as [`crate::Error::Cancelled`] when the user + /// declined. + fn start( + &self, + source: &SourceId, + options: &CaptureOptions, + frames: FrameSender, + ) -> BoxFuture<'static, Result<()>>; + + fn stop(&self); +} + +/// Platform code that captures what the device plays (48 kHz `f32`). +pub trait AudioProvider: Send + Sync { + fn name(&self) -> &'static str; + + /// Start delivering audio into `buffers`. + fn start(&self, buffers: FrameSender) -> Result<()>; + + fn stop(&self); +} + +type Slot = Mutex>>; + +static SCREEN: Slot = Mutex::new(None); +static AUDIO: Slot = Mutex::new(None); + +fn get(slot: &Slot) -> Option> { + slot.lock().unwrap_or_else(PoisonError::into_inner).clone() +} + +/// Make [`super::default_screen_capture`] use `provider` (`None` restores +/// the built-in backends). +pub fn set_screen_provider(provider: Option>) { + *SCREEN.lock().unwrap_or_else(PoisonError::into_inner) = provider; +} + +/// Make [`super::default_audio_capture`] use `provider`. +pub fn set_audio_provider(provider: Option>) { + *AUDIO.lock().unwrap_or_else(PoisonError::into_inner) = provider; +} + +pub fn screen_provider() -> Option> { + get(&SCREEN) +} + +pub fn audio_provider() -> Option> { + get(&AUDIO) +} + +/// A [`ScreenCapture`] backed by a [`ScreenProvider`]. +pub struct ExternalScreenCapture { + provider: Arc, + running: bool, +} + +impl ExternalScreenCapture { + pub fn new(provider: Arc) -> Self { + Self { provider, running: false } + } +} + +impl ScreenCapture for ExternalScreenCapture { + fn backend(&self) -> &'static str { + self.provider.name() + } + + fn sources(&mut self) -> Result> { + Ok(self.provider.sources()) + } + + fn start( + &mut self, + source: &SourceId, + options: &CaptureOptions, + ) -> BoxFuture<'_, Result>> { + self.stop(); + let (tx, rx) = frame_channel(options.queue); + let started = self.provider.start(source, options, tx); + self.running = true; + Box::pin(async move { + started.await?; + Ok(rx) + }) + } + + fn stop(&mut self) { + if std::mem::take(&mut self.running) { + self.provider.stop(); + } + } +} + +impl Drop for ExternalScreenCapture { + fn drop(&mut self) { + self.stop(); + } +} + +/// An [`AudioCapture`] backed by an [`AudioProvider`]. +pub struct ExternalAudioCapture { + provider: Arc, + running: bool, +} + +impl ExternalAudioCapture { + pub fn new(provider: Arc) -> Self { + Self { provider, running: false } + } +} + +impl AudioCapture for ExternalAudioCapture { + fn backend(&self) -> &'static str { + self.provider.name() + } + + fn start(&mut self) -> Result> { + self.stop(); + // About a second of 10 ms buffers. + let (tx, rx) = frame_channel(100); + self.provider.start(tx)?; + self.running = true; + Ok(rx) + } + + fn stop(&mut self) { + if std::mem::take(&mut self.running) { + self.provider.stop(); + } + } +} + +impl Drop for ExternalAudioCapture { + fn drop(&mut self) { + self.stop(); + } +} + +#[cfg(test)] +mod tests { + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::time::Duration; + + use super::*; + use crate::Error; + + /// Sends one frame per start, or refuses. + #[derive(Default)] + struct Fake { + refuse: bool, + stops: AtomicUsize, + sender: Mutex>>, + } + + impl ScreenProvider for Fake { + fn name(&self) -> &'static str { + "fake" + } + + fn sources(&self) -> Vec { + vec![CaptureSource { + id: SourceId::Portal, + name: "Screen".into(), + width: 0, + height: 0, + primary: true, + }] + } + + fn start( + &self, + _: &SourceId, + _: &CaptureOptions, + frames: FrameSender, + ) -> BoxFuture<'static, Result<()>> { + if self.refuse { + return Box::pin(async { Err(Error::Cancelled) }); + } + frames.send(VideoFrame::black_i420(4, 4)); + *self.sender.lock().unwrap() = Some(frames); + Box::pin(async { Ok(()) }) + } + + fn stop(&self) { + self.stops.fetch_add(1, Ordering::Relaxed); + self.sender.lock().unwrap().take(); + } + } + + #[tokio::test] + async fn frames_flow_until_the_provider_drops_the_sender() { + let fake = Arc::new(Fake::default()); + let mut capture = ExternalScreenCapture::new(fake.clone()); + assert_eq!(capture.backend(), "fake"); + assert_eq!(capture.sources().unwrap().len(), 1); + let mut rx = capture.start(&SourceId::Portal, &CaptureOptions::default()).await.unwrap(); + assert_eq!(rx.recv().await.unwrap().width, 4); + // The system stopped the projection. + fake.sender.lock().unwrap().take(); + assert!(rx.recv_timeout(Duration::from_millis(10)).is_none()); + assert!(rx.is_closed()); + drop(capture); + assert_eq!(fake.stops.load(Ordering::Relaxed), 1); + } + + #[tokio::test] + async fn refusal_is_an_error_and_stop_is_not_repeated() { + let fake = Arc::new(Fake { refuse: true, ..Fake::default() }); + let mut capture = ExternalScreenCapture::new(fake.clone()); + let result = capture.start(&SourceId::Portal, &CaptureOptions::default()).await; + assert!(matches!(result, Err(Error::Cancelled))); + capture.stop(); + capture.stop(); + assert_eq!(fake.stops.load(Ordering::Relaxed), 1); + } + + #[test] + fn registered_provider_is_the_default() { + struct Silent; + impl AudioProvider for Silent { + fn name(&self) -> &'static str { + "silent" + } + fn start(&self, buffers: FrameSender) -> Result<()> { + buffers.send(AudioBuffer { + samples: vec![0.0; 960], + channels: 2, + timestamp: Duration::ZERO, + }); + Ok(()) + } + fn stop(&self) {} + } + set_audio_provider(Some(Arc::new(Silent))); + let mut capture = crate::capture::default_audio_capture().unwrap(); + assert_eq!(capture.backend(), "silent"); + let mut rx = capture.start().unwrap(); + assert_eq!(rx.try_recv().unwrap().frames(), 480); + set_audio_provider(None); + assert!(audio_provider().is_none()); + } +} diff --git a/crates/tsc-media/src/capture/mod.rs b/crates/tsc-media/src/capture/mod.rs index 4264192..c8a10d3 100644 --- a/crates/tsc-media/src/capture/mod.rs +++ b/crates/tsc-media/src/capture/mod.rs @@ -9,6 +9,7 @@ //! | `x11` (Linux, feature `x11`) | MIT-SHM / GetImage, XFixes cursor | | //! | `portal` / `pipewire_audio` (Linux, feature `pipewire`) | ScreenCast portal + PipeWire | default sink monitor | //! | `windows` | Windows Graphics Capture | WASAPI process loopback | +//! | [`external`] | platform code (Android MediaProjection) | same | use std::future::Future; use std::pin::Pin; @@ -27,6 +28,7 @@ pub mod pipewire_audio; pub mod portal; #[cfg(all(target_os = "linux", feature = "pipewire"))] mod pw; +pub mod external; pub mod synthetic; #[cfg(windows)] pub mod windows; @@ -106,9 +108,13 @@ pub trait AudioCapture: Send { fn stop(&mut self); } -/// The screen capture backend for this session: the ScreenCast portal on +/// The screen capture backend for this session: a registered +/// [`external::ScreenProvider`] (Android), else the ScreenCast portal on /// Wayland, X11 otherwise on Linux, Windows Graphics Capture on Windows. pub fn default_screen_capture() -> Result> { + if let Some(provider) = external::screen_provider() { + return Ok(Box::new(external::ExternalScreenCapture::new(provider))); + } #[cfg(target_os = "linux")] { let wayland = std::env::var_os("WAYLAND_DISPLAY").is_some() @@ -132,8 +138,12 @@ pub fn default_screen_capture() -> Result> { }) } -/// The system-audio backend: PipeWire on Linux, WASAPI loopback on Windows. +/// The system-audio backend: a registered [`external::AudioProvider`] +/// (Android), else PipeWire on Linux, WASAPI loopback on Windows. pub fn default_audio_capture() -> Result> { + if let Some(provider) = external::audio_provider() { + return Ok(Box::new(external::ExternalAudioCapture::new(provider))); + } #[cfg(all(target_os = "linux", feature = "pipewire"))] return Ok(Box::new(pipewire_audio::PipeWireAudioCapture::new())); #[cfg(windows)] diff --git a/crates/tsc-media/src/codec/hw.rs b/crates/tsc-media/src/codec/hw.rs index da24495..5d26b17 100644 --- a/crates/tsc-media/src/codec/hw.rs +++ b/crates/tsc-media/src/codec/hw.rs @@ -7,6 +7,7 @@ //! through `cros-libva`. TODO. //! - Windows: Media Foundation H.264 encoder MFT (NVENC / QuickSync / AMF //! behind it). TODO. +//! - Android: MediaCodec ([`super::mediacodec`]). use crate::Result; use crate::codec::{Codec, EncoderConfig, VideoEncoder}; @@ -33,6 +34,10 @@ pub fn probe() -> Vec> { if let Some(f) = media_foundation::probe() { found.push(Box::new(f)); } + #[cfg(target_os = "android")] + if let Some(f) = super::mediacodec::probe() { + found.push(Box::new(f)); + } found } diff --git a/crates/tsc-media/src/codec/image_layout.rs b/crates/tsc-media/src/codec/image_layout.rs new file mode 100644 index 0000000..e63bc02 --- /dev/null +++ b/crates/tsc-media/src/codec/image_layout.rs @@ -0,0 +1,317 @@ +//! Where the Y, U and V samples of a 4:2:0 image sit in a codec's linear +//! buffer, and copies between such buffers and [`VideoFrame`]s. +//! +//! Android's MediaCodec describes its byte-buffer layout either by a color +//! format (19 = planar I420, 21 = semi-planar NV12) plus `stride` and +//! `slice-height`, or exactly by a `MediaImage2` struct in the format's +//! `image-data` entry. Both become an [`ImageLayout`] here; this module has +//! no Android dependency so it is tested on every platform. + +use crate::convert; +use crate::frame::{FrameData, Plane, VideoFrame, chroma_size}; +use crate::{Error, Result}; + +/// `COLOR_FormatYUV420Planar`. +pub const COLOR_FORMAT_I420: i32 = 19; +/// `COLOR_FormatYUV420SemiPlanar`. +pub const COLOR_FORMAT_NV12: i32 = 21; +/// `COLOR_FormatYUV420Flexible`: the real layout is in `image-data`. +pub const COLOR_FORMAT_FLEXIBLE: i32 = 0x7F42_0888; + +/// One plane: first sample at `offset`, next sample in the row `col_inc` +/// bytes further, next row `row_inc` bytes further. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct PlaneLayout { + pub offset: usize, + pub col_inc: usize, + pub row_inc: usize, +} + +/// An 8-bit YUV 4:2:0 image of `width` x `height` in a linear buffer. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ImageLayout { + pub width: u32, + pub height: u32, + pub y: PlaneLayout, + pub u: PlaneLayout, + pub v: PlaneLayout, +} + +/// Size of `MediaImage2` (`media/hardware/VideoAPI.h`): six `u32` fields +/// and four planes of five 32-bit fields. +const MEDIA_IMAGE2_SIZE: usize = 6 * 4 + 4 * 5 * 4; +const MEDIA_IMAGE_TYPE_YUV: u32 = 1; + +impl ImageLayout { + /// Planar I420: Y rows of `stride` bytes, `slice_height` rows, then U and + /// V with half the stride and half the rows. + pub fn i420(width: u32, height: u32, stride: usize, slice_height: usize) -> Self { + let stride = stride.max(width as usize); + let slice_height = slice_height.max(height as usize); + let c_stride = stride.div_ceil(2); + let u = stride * slice_height; + let v = u + c_stride * slice_height.div_ceil(2); + Self { + width, + height, + y: PlaneLayout { offset: 0, col_inc: 1, row_inc: stride }, + u: PlaneLayout { offset: u, col_inc: 1, row_inc: c_stride }, + v: PlaneLayout { offset: v, col_inc: 1, row_inc: c_stride }, + } + } + + /// Semi-planar NV12: Y, then interleaved U/V rows of `stride` bytes. + pub fn nv12(width: u32, height: u32, stride: usize, slice_height: usize) -> Self { + let stride = stride.max(width as usize); + let slice_height = slice_height.max(height as usize); + let uv = stride * slice_height; + Self { + width, + height, + y: PlaneLayout { offset: 0, col_inc: 1, row_inc: stride }, + u: PlaneLayout { offset: uv, col_inc: 2, row_inc: stride }, + v: PlaneLayout { offset: uv + 1, col_inc: 2, row_inc: stride }, + } + } + + /// The layout of a color format with `stride` / `slice-height` (0 when + /// unknown). Flexible and vendor formats need `image-data` instead. + pub fn from_color_format( + color_format: i32, + width: u32, + height: u32, + stride: usize, + slice_height: usize, + ) -> Option { + match color_format { + COLOR_FORMAT_I420 => Some(Self::i420(width, height, stride, slice_height)), + COLOR_FORMAT_NV12 => Some(Self::nv12(width, height, stride, slice_height)), + _ => None, + } + } + + /// Parse a `MediaImage2` (little-endian, as on every Android ABI). + /// Only 8-bit YUV 4:2:0 with three planes is accepted. + pub fn from_media_image2(data: &[u8]) -> Option { + if data.len() < MEDIA_IMAGE2_SIZE { + return None; + } + let word = |i: usize| u32::from_le_bytes(data[i * 4..i * 4 + 4].try_into().unwrap()); + let (kind, planes, width, height, depth, allocated) = + (word(0), word(1), word(2), word(3), word(4), word(5)); + if kind != MEDIA_IMAGE_TYPE_YUV || planes != 3 || depth != 8 || allocated != 8 { + return None; + } + let plane = |p: usize, subsampling: u32| -> Option { + let base = 6 + p * 5; + let (offset, col_inc, row_inc) = + (word(base), word(base + 1) as i32, word(base + 2) as i32); + if word(base + 3) != subsampling || word(base + 4) != subsampling { + return None; + } + Some(PlaneLayout { + offset: offset as usize, + col_inc: usize::try_from(col_inc).ok().filter(|&c| c > 0)?, + row_inc: usize::try_from(row_inc).ok().filter(|&r| r > 0)?, + }) + }; + Some(Self { width, height, y: plane(0, 1)?, u: plane(1, 2)?, v: plane(2, 2)? }) + } + + /// The same buffer layout for a smaller visible area (a crop from the + /// top-left corner), e.g. a decoder's 1920x1088 buffer showing 1080 rows. + pub fn cropped(mut self, width: u32, height: u32) -> Self { + self.width = width.min(self.width); + self.height = height.min(self.height); + self + } + + /// Bytes a buffer needs to hold this image. + pub fn buffer_len(&self) -> usize { + let (cw, ch) = chroma_size(self.width, self.height); + let end = |p: &PlaneLayout, w: usize, h: usize| { + if w == 0 || h == 0 { 0 } else { p.offset + (h - 1) * p.row_inc + (w - 1) * p.col_inc + 1 } + }; + let (w, h) = (self.width as usize, self.height as usize); + end(&self.y, w, h).max(end(&self.u, cw, ch)).max(end(&self.v, cw, ch)) + } + + fn check(&self, len: usize) -> Result<()> { + if len < self.buffer_len() { + return Err(Error::InvalidFrame(format!( + "codec buffer has {len} bytes, the {}x{} image needs {}", + self.width, + self.height, + self.buffer_len() + ))); + } + Ok(()) + } + + /// Copy an image out of a codec buffer: NV12 when the layout is NV12, + /// I420 otherwise. + pub fn read(&self, buf: &[u8]) -> Result { + self.check(buf.len())?; + let (w, h) = (self.width as usize, self.height as usize); + let (cw, ch) = chroma_size(self.width, self.height); + let y = read_plane(buf, &self.y, w, h); + let data = if self.u.col_inc == 2 + && self.v.col_inc == 2 + && self.v.offset == self.u.offset + 1 + && self.u.row_inc == self.v.row_inc + { + let uv = PlaneLayout { col_inc: 1, ..self.u }; + FrameData::Nv12 { y, uv: read_plane(buf, &uv, cw * 2, ch) } + } else { + FrameData::I420 { y, u: read_plane(buf, &self.u, cw, ch), v: read_plane(buf, &self.v, cw, ch) } + }; + let frame = VideoFrame { + width: self.width, + height: self.height, + timestamp: std::time::Duration::ZERO, + data, + }; + frame.validate()?; + Ok(frame) + } + + /// Write `frame` (any pixel format, same size as the layout) into a codec + /// buffer. Returns the bytes used. + pub fn write(&self, frame: &VideoFrame, buf: &mut [u8]) -> Result { + if (frame.width, frame.height) != (self.width, self.height) { + return Err(Error::InvalidFrame(format!( + "{}x{} frame for a {}x{} codec buffer", + frame.width, frame.height, self.width, self.height + ))); + } + self.check(buf.len())?; + let i420 = convert::to_i420(frame)?; + let FrameData::I420 { y, u, v } = &i420.data else { + unreachable!("to_i420 returns I420"); + }; + let (w, h) = (self.width as usize, self.height as usize); + let (cw, ch) = chroma_size(self.width, self.height); + write_plane(buf, &self.y, y, w, h); + write_plane(buf, &self.u, u, cw, ch); + write_plane(buf, &self.v, v, cw, ch); + Ok(self.buffer_len()) + } +} + +fn read_plane(buf: &[u8], p: &PlaneLayout, width: usize, rows: usize) -> Plane { + let mut data = Vec::with_capacity(width * rows); + for row in 0..rows { + let start = p.offset + row * p.row_inc; + if p.col_inc == 1 { + data.extend_from_slice(&buf[start..start + width]); + } else { + data.extend((0..width).map(|x| buf[start + x * p.col_inc])); + } + } + Plane::new(data, width) +} + +fn write_plane(buf: &mut [u8], p: &PlaneLayout, src: &Plane, width: usize, rows: usize) { + for row in 0..rows { + let line = src.row(row, width); + let start = p.offset + row * p.row_inc; + if p.col_inc == 1 { + buf[start..start + width].copy_from_slice(line); + } else { + for (x, &sample) in line.iter().enumerate() { + buf[start + x * p.col_inc] = sample; + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A 6x4 I420 frame with distinct samples per plane. + fn frame() -> VideoFrame { + let (w, h) = (6usize, 4usize); + let (cw, ch) = chroma_size(6, 4); + VideoFrame { + width: 6, + height: 4, + timestamp: std::time::Duration::ZERO, + data: FrameData::I420 { + y: Plane::new((0..w * h).map(|i| i as u8).collect(), w), + u: Plane::new((0..cw * ch).map(|i| 100 + i as u8).collect(), cw), + v: Plane::new((0..cw * ch).map(|i| 200 + i as u8).collect(), cw), + }, + } + } + + fn as_i420(frame: &VideoFrame) -> VideoFrame { + convert::to_i420(frame).unwrap().into_owned() + } + + #[test] + fn i420_and_nv12_round_trip_with_padding() { + let src = frame(); + for layout in [ImageLayout::i420(6, 4, 8, 6), ImageLayout::nv12(6, 4, 8, 6)] { + let mut buf = vec![0xEE; layout.buffer_len()]; + assert_eq!(layout.write(&src, &mut buf).unwrap(), buf.len()); + let back = layout.read(&buf).unwrap(); + assert_eq!(as_i420(&back).data, src.data, "{layout:?}"); + } + // NV12 reads back as NV12 without conversion. + let layout = ImageLayout::nv12(6, 4, 6, 4); + let mut buf = vec![0; layout.buffer_len()]; + layout.write(&src, &mut buf).unwrap(); + assert!(matches!(layout.read(&buf).unwrap().data, FrameData::Nv12 { .. })); + assert_eq!(&buf[24..30], &[100, 200, 101, 201, 102, 202]); + } + + #[test] + fn media_image2_describes_nv21() { + // 6x4, stride 8, 4 rows: V first in the interleaved plane (NV21). + let mut raw = Vec::new(); + for w in [1u32, 3, 6, 4, 8, 8] { + raw.extend(w.to_le_bytes()); + } + for (offset, col, row, sub) in [(0u32, 1i32, 8i32, 1u32), (33, 2, 8, 2), (32, 2, 8, 2)] { + raw.extend(offset.to_le_bytes()); + raw.extend(col.to_le_bytes()); + raw.extend(row.to_le_bytes()); + raw.extend(sub.to_le_bytes()); + raw.extend(sub.to_le_bytes()); + } + raw.extend([0; 20]); + let layout = ImageLayout::from_media_image2(&raw).unwrap(); + assert_eq!(layout.u, PlaneLayout { offset: 33, col_inc: 2, row_inc: 8 }); + let mut buf = vec![0; layout.buffer_len()]; + layout.write(&frame(), &mut buf).unwrap(); + assert_eq!(&buf[32..36], &[200, 100, 201, 101]); + let back = layout.read(&buf).unwrap(); + assert!(matches!(back.data, FrameData::I420 { .. })); + assert_eq!(back.data, frame().data); + + // Not YUV, too short, or a 10-bit image: rejected. + let mut rgb = raw.clone(); + rgb[0] = 3; + assert!(ImageLayout::from_media_image2(&rgb).is_none()); + assert!(ImageLayout::from_media_image2(&raw[..100]).is_none()); + let mut deep = raw.clone(); + deep[16] = 10; + assert!(ImageLayout::from_media_image2(&deep).is_none()); + } + + #[test] + fn crop_and_size_checks() { + // A decoder buffer of 8x6 (stride 8) showing 6x4. + let layout = ImageLayout::from_color_format(COLOR_FORMAT_I420, 8, 6, 8, 6) + .unwrap() + .cropped(6, 4); + assert_eq!((layout.width, layout.height), (6, 4)); + assert_eq!(layout.u.offset, 48); + assert!(ImageLayout::from_color_format(COLOR_FORMAT_FLEXIBLE, 8, 6, 8, 6).is_none()); + let short = vec![0; 10]; + assert!(matches!(layout.read(&short), Err(Error::InvalidFrame(_)))); + let mut buf = vec![0; 100]; + assert!(layout.write(&VideoFrame::black_i420(4, 4), &mut buf).is_err()); + } +} diff --git a/crates/tsc-media/src/codec/mediacodec.rs b/crates/tsc-media/src/codec/mediacodec.rs new file mode 100644 index 0000000..d24910e --- /dev/null +++ b/crates/tsc-media/src/codec/mediacodec.rs @@ -0,0 +1,558 @@ +//! Android MediaCodec (NDK `AMediaCodec`) encoders and decoders. +//! +//! Byte-buffer mode on both sides, so frames stay [`VideoFrame`]s like with +//! the software codecs: encoders take I420 / NV12 (whatever the codec asks +//! for, see [`ImageLayout`]), decoders return I420 or NV12. The device's +//! default codec for a MIME type is used; most phones have hardware H.264, +//! many hardware VP8 / VP9, and every Android has Google's software VP8, +//! VP9 and H.264 (`c2.android.*`). +//! +//! H.264 is encoded as High profile without B-frames (the Constrained High +//! stream TeamSpeak negotiates, see `tsc-stream`), SPS/PPS in front of every +//! keyframe. + +// 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::time::Duration; + +use ndk::media::media_codec::{ + DequeuedInputBufferResult, DequeuedOutputBufferInfoResult, MediaCodec, MediaCodecDirection, +}; +use ndk::media::media_format::MediaFormat; +use tracing::{debug, info}; + +use super::hw::HardwareEncoderFactory; +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 crate::{Error, Result, convert}; + +/// `BUFFER_FLAG_KEY_FRAME`. +const FLAG_KEY_FRAME: u32 = 1; +/// `BUFFER_FLAG_CODEC_CONFIG`: SPS/PPS (H.264), no picture. +const FLAG_CODEC_CONFIG: u32 = 2; +/// `AVCProfileHigh`, `AVCProfileConstrainedHigh`. +const AVC_PROFILE_HIGH: i32 = 0x08; +const AVC_PROFILE_CONSTRAINED_HIGH: i32 = 0x80000; +/// `BITRATE_MODE_VBR`. +const BITRATE_MODE_VBR: i32 = 1; +/// Keyframe interval for "only on request" (seconds; what WebRTC uses). +const NO_PERIODIC_KEYFRAMES: i32 = 3600; +/// How long `decode` / `encode` wait for a free input buffer. +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); + +pub const NAME: &str = "mediacodec"; + +fn mime(codec: Codec) -> &'static str { + match codec { + Codec::Vp8 => "video/x-vnd.on2.vp8", + Codec::Vp9 => "video/x-vnd.on2.vp9", + Codec::H264 => "video/avc", + Codec::Av1 => "video/av01", + } +} + +/// Google's software codecs (as opposed to the vendor's hardware ones). +fn is_software(name: &str) -> bool { + name.starts_with("c2.android.") || name.starts_with("OMX.google.") || name.contains(".sw.") +} + +/// An `AMediaCodec` that may move between threads. +struct Handle(MediaCodec); + +// SAFETY: see the module attribute; `Handle` is only reached through +// `&mut self` of its owner, never shared. +unsafe impl Send for Handle {} + +impl Drop for Handle { + fn drop(&mut self) { + let _ = self.0.stop(); + } +} + +fn encoder_error(codec: Codec, context: &str, e: impl std::fmt::Display) -> Error { + Error::Encoder { codec, message: format!("{context}: {e}") } +} + +fn decoder_error(codec: Codec, context: &str, e: impl std::fmt::Display) -> Error { + Error::Decoder { codec, message: format!("{context}: {e}") } +} + +/// The default codec's name per MIME type and direction, probed once. +struct Available { + encoders: Vec<(Codec, String)>, + decoders: Vec<(Codec, String)>, +} + +fn available() -> &'static Available { + static AVAILABLE: OnceLock = OnceLock::new(); + AVAILABLE.get_or_init(|| { + let probe = |create: fn(&str) -> Option| { + Codec::ALL + .into_iter() + .filter_map(|codec| { + let handle = Handle(create(mime(codec))?); + let name = handle.0.name().unwrap_or_else(|_| "?".into()); + Some((codec, name)) + }) + .collect::>() + }; + let found = Available { + encoders: probe(MediaCodec::from_encoder_type), + decoders: probe(MediaCodec::from_decoder_type), + }; + info!(encoders = ?found.encoders, decoders = ?found.decoders, "MediaCodec"); + found + }) +} + +/// Whether the device decodes `codec`. +pub fn check_decoder(codec: Codec) -> Result<()> { + if available().decoders.iter().any(|(c, _)| *c == codec) { + Ok(()) + } else { + Err(Error::CodecUnavailable { codec, reason: "no MediaCodec decoder".into() }) + } +} + +/// Encoders of this device: hardware ones first (H.264, VP9, VP8), then +/// Google's software VP8 and H.264. Software VP9 and AV1 are too slow. +pub fn probe() -> Option { + let encoders = &available().encoders; + let name = |codec| encoders.iter().find(|(c, _)| *c == codec).map(|(_, n)| n.as_str()); + let mut codecs = Vec::new(); + for codec in [Codec::H264, Codec::Vp9, Codec::Vp8, Codec::Av1] { + if name(codec).is_some_and(|n| !is_software(n)) { + codecs.push(codec); + } + } + for codec in [Codec::Vp8, Codec::H264] { + if name(codec).is_some_and(is_software) { + codecs.push(codec); + } + } + (!codecs.is_empty()).then_some(MediaCodecFactory { codecs }) +} + +pub struct MediaCodecFactory { + codecs: Vec, +} + +impl HardwareEncoderFactory for MediaCodecFactory { + fn name(&self) -> &'static str { + NAME + } + + fn codecs(&self) -> Vec { + self.codecs.clone() + } + + fn create(&self, codec: Codec, config: &EncoderConfig) -> Result> { + 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 })) + } +} + +/// A MediaCodec encoder. The codec is (re)created for the frame size. +pub struct MediaCodecEncoder { + codec: Codec, + config: EncoderConfig, + session: Option, +} + +struct EncoderSession { + handle: Handle, + layout: ImageLayout, + /// H.264 SPS/PPS, put in front of keyframes that lack them. + parameter_sets: Vec, + /// Staging buffer for the codec's input layout. + staging: Vec, + last_pts_us: Option, +} + +impl MediaCodecEncoder { + fn format(&self, width: u32, height: u32, color_format: i32, profile: Option) -> MediaFormat { + let mut format = MediaFormat::new(); + format.set_str("mime", mime(self.codec)); + format.set_i32("width", width as i32); + format.set_i32("height", height as i32); + format.set_i32("color-format", color_format); + format.set_i32("bitrate", self.config.bitrate_bps.min(i32::MAX as u32) as i32); + format.set_i32("bitrate-mode", BITRATE_MODE_VBR); + format.set_i32("frame-rate", self.config.fps.max(1) as i32); + let interval = match self.config.keyframe_interval { + Some(frames) => frames.div_ceil(self.config.fps.max(1)).max(1) as i32, + None => NO_PERIODIC_KEYFRAMES, + }; + format.set_i32("i-frame-interval", interval); + if self.codec == Codec::H264 { + format.set_i32("max-bframes", 0); + format.set_i32("prepend-sps-pps-to-idr-frames", 1); + if let Some(profile) = profile { + format.set_i32("profile", profile); + } + } + format + } + + /// Start a codec for `width` x `height`: NV12 input, else I420; for + /// H.264 Constrained High, else High, else the codec's default profile. + fn start(&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 color_format in [COLOR_FORMAT_NV12, COLOR_FORMAT_I420] { + for &profile in profiles { + let handle = Handle( + MediaCodec::from_encoder_type(mime(codec)) + .ok_or_else(|| encoder_error(codec, "create", "no encoder"))?, + ); + let format = self.format(width, height, color_format, profile); + if let Err(e) = handle.0.configure(&format, None, MediaCodecDirection::Encoder) { + last_error = format!("configure {color_format}/{profile:?}: {e}"); + continue; + } + let layout = input_layout(&handle.0.input_format(), width, height, color_format); + handle.0.start().map_err(|e| encoder_error(codec, "start", e))?; + debug!(%codec, width, height, color_format, ?profile, ?layout, "MediaCodec encoder"); + return Ok(EncoderSession { + handle, + layout, + parameter_sets: Vec::new(), + staging: Vec::new(), + last_pts_us: None, + }); + } + } + Err(encoder_error(codec, "no working configuration", last_error)) + } +} + +/// Where the encoder wants its input: `image-data` if it says, else the +/// color format with its `stride` / `slice-height`. +fn input_layout(format: &MediaFormat, width: u32, height: u32, requested: i32) -> ImageLayout { + if let Some(layout) = format + .buffer("image-data") + .and_then(ImageLayout::from_media_image2) + .filter(|l| l.width >= width && l.height >= height) + { + return layout.cropped(width, height); + } + let stride = format.i32("stride").and_then(|s| usize::try_from(s).ok()).unwrap_or(0); + let slice = format.i32("slice-height").and_then(|s| usize::try_from(s).ok()).unwrap_or(0); + let color = match format.i32("color-format") { + Some(c @ (COLOR_FORMAT_I420 | COLOR_FORMAT_NV12)) => c, + // Flexible or unset: what we asked for. + _ => requested, + }; + ImageLayout::from_color_format(color, width, height, stride, slice) + .unwrap_or_else(|| ImageLayout::nv12(width, height, stride, slice)) +} + +/// The top-left `width` x `height` of an I420 frame (planes keep their +/// stride, so nothing is copied). +fn crop_i420(mut frame: VideoFrame, width: u32, height: u32) -> VideoFrame { + debug_assert!(matches!(frame.data, FrameData::I420 { .. })); + frame.width = width; + frame.height = height; + frame +} + +/// H.264 NAL unit type of the first NAL after a start code. +fn first_nal_type(data: &[u8]) -> Option { + let start = if data.starts_with(&[0, 0, 0, 1]) { + 4 + } else if data.starts_with(&[0, 0, 1]) { + 3 + } else { + return None; + }; + data.get(start).map(|b| b & 0x1f) +} + +impl VideoEncoder for MediaCodecEncoder { + fn codec(&self) -> Codec { + self.codec + } + + fn backend(&self) -> EncoderBackend { + EncoderBackend::Hardware(NAME) + } + + fn encode(&mut self, frame: &VideoFrame, force_keyframe: bool) -> Result> { + let codec = self.codec; + // Encoders want even sizes. + 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 resized = self + .session + .as_ref() + .is_some_and(|s| (s.layout.width, s.layout.height) != (width, height)); + if resized || self.session.is_none() { + self.session = None; + self.session = Some(self.start(width, height)?); + } + let session = self.session.as_mut().expect("started above"); + let mut i420 = convert::to_i420(frame)?.into_owned(); + if (i420.width, i420.height) != (width, height) { + i420 = crop_i420(i420, width, height); + } + + // Strictly increasing presentation times. + let mut pts_us = i420.timestamp.as_micros() as u64; + if let Some(last) = session.last_pts_us + && pts_us <= last + { + pts_us = last + 1; + } + + if force_keyframe && !resized { + let mut params = MediaFormat::new(); + params.set_i32("request-sync", 0); + session + .handle + .0 + .set_parameters(params) + .map_err(|e| encoder_error(codec, "request keyframe", e))?; + } + + let len = session.layout.buffer_len(); + session.staging.resize(len, 0); + session.layout.write(&i420, &mut session.staging)?; + match session + .handle + .0 + .dequeue_input_buffer(INPUT_WAIT) + .map_err(|e| encoder_error(codec, "dequeue input", e))? + { + DequeuedInputBufferResult::Buffer(mut buffer) => { + let dst = buffer.buffer_mut(); + if dst.len() < len { + return Err(encoder_error( + codec, + "input buffer", + format!("{} bytes, need {len}", dst.len()), + )); + } + dst[..len].write_copy_of_slice(&session.staging); + session + .handle + .0 + .queue_input_buffer(buffer, 0, len, pts_us, 0) + .map_err(|e| encoder_error(codec, "queue input", e))?; + session.last_pts_us = Some(pts_us); + } + // The codec is still busy: skip this frame (rate control). + DequeuedInputBufferResult::TryAgainLater => {} + } + drain_encoder(codec, session) + } + + fn set_bitrate(&mut self, bps: u32) -> Result<()> { + self.config.bitrate_bps = bps; + if let Some(session) = &self.session { + let mut params = MediaFormat::new(); + params.set_i32("video-bitrate", bps.min(i32::MAX as u32) as i32); + session + .handle + .0 + .set_parameters(params) + .map_err(|e| encoder_error(self.codec, "set bitrate", e))?; + } + Ok(()) + } +} + +/// Collect what the encoder has finished. +fn drain_encoder(codec: Codec, session: &mut EncoderSession) -> Result> { + let mut out = Vec::new(); + let mut wait = OUTPUT_WAIT; + loop { + let result = session + .handle + .0 + .dequeue_output_buffer(wait) + .map_err(|e| encoder_error(codec, "dequeue output", e))?; + wait = Duration::ZERO; + match result { + DequeuedOutputBufferInfoResult::Buffer(buffer) => { + let info = *buffer.info(); + let offset = usize::try_from(info.offset()).unwrap_or(0); + let size = usize::try_from(info.size()).unwrap_or(0); + let data = buffer.buffer().get(offset..offset + size).map(<[u8]>::to_vec); + session + .handle + .0 + .release_output_buffer(buffer, false) + .map_err(|e| encoder_error(codec, "release output", e))?; + let Some(mut data) = data.filter(|d| !d.is_empty()) else { + continue; + }; + if info.flags() & FLAG_CODEC_CONFIG != 0 { + session.parameter_sets = data; + continue; + } + let keyframe = info.flags() & FLAG_KEY_FRAME != 0; + if keyframe + && codec == Codec::H264 + && !session.parameter_sets.is_empty() + && first_nal_type(&data) != Some(7) + { + let mut with_sps = session.parameter_sets.clone(); + with_sps.append(&mut data); + data = with_sps; + } + let pts_us = u64::try_from(info.presentation_time_us()).unwrap_or(0); + out.push(EncodedFrame { data, keyframe, pts_90khz: pts_us * 9 / 100 }); + } + DequeuedOutputBufferInfoResult::OutputFormatChanged + | DequeuedOutputBufferInfoResult::OutputBuffersChanged => {} + DequeuedOutputBufferInfoResult::TryAgainLater => return Ok(out), + } + } +} + +/// A MediaCodec decoder. +pub struct MediaCodecDecoder { + codec: Codec, + handle: Handle, + /// Output layout, known after the first format change. + layout: Option, + pts_us: u64, +} + +impl MediaCodecDecoder { + pub fn new(codec: Codec) -> Result { + check_decoder(codec)?; + let handle = Handle( + MediaCodec::from_decoder_type(mime(codec)) + .ok_or_else(|| decoder_error(codec, "create", "no decoder"))?, + ); + let mut format = MediaFormat::new(); + format.set_str("mime", mime(codec)); + // A hint; the stream's own size wins. + format.set_i32("width", 1920); + format.set_i32("height", 1080); + format.set_i32("color-format", COLOR_FORMAT_FLEXIBLE); + handle + .0 + .configure(&format, None, MediaCodecDirection::Decoder) + .map_err(|e| decoder_error(codec, "configure", e))?; + handle.0.start().map_err(|e| decoder_error(codec, "start", e))?; + Ok(Self { codec, handle, layout: None, pts_us: 0 }) + } + + fn update_layout(&mut self) { + let format = self.handle.0.output_format(); + let width = format.i32("width").unwrap_or(0).max(0) as u32; + let height = format.i32("height").unwrap_or(0).max(0) as u32; + let (visible_w, visible_h) = match format.rect("crop") { + Some((left, top, right, bottom)) if left == 0 && top == 0 => { + ((right + 1).max(0) as u32, (bottom + 1).max(0) as u32) + } + _ => (width, height), + }; + let stride = format.i32("stride").and_then(|s| usize::try_from(s).ok()).unwrap_or(0); + let slice = format.i32("slice-height").and_then(|s| usize::try_from(s).ok()).unwrap_or(0); + let layout = format + .buffer("image-data") + .and_then(ImageLayout::from_media_image2) + .or_else(|| { + ImageLayout::from_color_format( + format.i32("color-format").unwrap_or(0), + width, + height, + stride, + slice, + ) + }) + .map(|l| l.cropped(visible_w, visible_h)); + debug!(codec = %self.codec, ?layout, "MediaCodec decoder output"); + self.layout = layout; + } +} + +impl VideoDecoder for MediaCodecDecoder { + fn codec(&self) -> Codec { + self.codec + } + + fn decode(&mut self, data: &[u8]) -> Result> { + let codec = self.codec; + match self + .handle + .0 + .dequeue_input_buffer(INPUT_WAIT) + .map_err(|e| decoder_error(codec, "dequeue input", e))? + { + DequeuedInputBufferResult::Buffer(mut buffer) => { + let dst = buffer.buffer_mut(); + if dst.len() < data.len() { + return Err(decoder_error( + codec, + "input buffer", + format!("{} bytes for a {} byte frame", dst.len(), data.len()), + )); + } + dst[..data.len()].write_copy_of_slice(data); + // Only the order matters; the caller knows the RTP time. + self.pts_us += 33_333; + self.handle + .0 + .queue_input_buffer(buffer, 0, data.len(), self.pts_us, 0) + .map_err(|e| decoder_error(codec, "queue input", e))?; + } + DequeuedInputBufferResult::TryAgainLater => { + return Err(decoder_error(codec, "dequeue input", "the decoder is stalled")); + } + } + + // The newest finished picture; older ones are dropped. + let mut picture = None; + let mut wait = OUTPUT_WAIT; + loop { + let result = self + .handle + .0 + .dequeue_output_buffer(wait) + .map_err(|e| decoder_error(codec, "dequeue output", e))?; + wait = Duration::ZERO; + match result { + DequeuedOutputBufferInfoResult::Buffer(buffer) => { + let info = *buffer.info(); + let offset = usize::try_from(info.offset()).unwrap_or(0); + let size = usize::try_from(info.size()).unwrap_or(0); + let read = match (&self.layout, buffer.buffer().get(offset..offset + size)) { + (Some(layout), Some(bytes)) if size > 0 => Some(layout.read(bytes)), + _ => None, + }; + self.handle + .0 + .release_output_buffer(buffer, false) + .map_err(|e| decoder_error(codec, "release output", e))?; + match read { + Some(Ok(frame)) => picture = Some(frame), + Some(Err(e)) => return Err(decoder_error(codec, "output", e)), + None => {} + } + } + DequeuedOutputBufferInfoResult::OutputFormatChanged => self.update_layout(), + DequeuedOutputBufferInfoResult::OutputBuffersChanged => {} + DequeuedOutputBufferInfoResult::TryAgainLater => return Ok(picture), + } + } + } +} diff --git a/crates/tsc-media/src/codec/mod.rs b/crates/tsc-media/src/codec/mod.rs index c666333..48e7d9e 100644 --- a/crates/tsc-media/src/codec/mod.rs +++ b/crates/tsc-media/src/codec/mod.rs @@ -8,6 +8,8 @@ //! loaded at runtime //! - [`av1`] (feature `av1`): AV1 decoding with the system libdav1d //! - [`hw`]: hardware encoders (VA-API, Media Foundation); not implemented yet +//! - `mediacodec` (Android): the device's MediaCodec encoders and decoders +//! (hardware, or Google's software VP8 / VP9 / H.264) use std::fmt; use std::str::FromStr; @@ -20,6 +22,9 @@ pub mod av1; #[cfg(feature = "openh264")] pub mod h264; pub mod hw; +pub mod image_layout; +#[cfg(target_os = "android")] +pub mod mediacodec; #[cfg(feature = "vpx")] pub mod vpx; @@ -263,6 +268,10 @@ impl Codecs { /// Whether `codec` can be decoded, or why not. pub fn check_decoder(&self, codec: Codec) -> Result<()> { + #[cfg(target_os = "android")] + if mediacodec::check_decoder(codec).is_ok() { + return Ok(()); + } match codec { Codec::Vp8 | Codec::Vp9 => { #[cfg(feature = "vpx")] @@ -321,6 +330,10 @@ impl Codecs { } pub fn new_decoder(&self, codec: Codec) -> Result> { + #[cfg(target_os = "android")] + if mediacodec::check_decoder(codec).is_ok() { + return Ok(Box::new(mediacodec::MediaCodecDecoder::new(codec)?)); + } self.check_decoder(codec)?; match codec { #[cfg(feature = "vpx")] diff --git a/crates/tsc-ui/Cargo.toml b/crates/tsc-ui/Cargo.toml index fbfa2cb..bbfd97f 100644 --- a/crates/tsc-ui/Cargo.toml +++ b/crates/tsc-ui/Cargo.toml @@ -21,7 +21,6 @@ anyhow = "1.0.104" chrono = { version = "0.4.45", default-features = false, features = ["clock"] } dirs = "6" png = "0.18" -slint = { version = "1.18", features = ["renderer-software"] } tokio = { version = "1.53.1", features = ["rt-multi-thread", "macros", "time", "sync"] } tracing = "0.1.44" tracing-subscriber = { version = "0.3.23", features = ["env-filter"] } @@ -31,11 +30,15 @@ tsc-query = { path = "../tsc-query" } tsc-store = { path = "../tsc-store" } tsclientlib = { path = "../proto/tsclientlib" } -# The keyring crate has no Android backend; the Android app passes its own -# `Secrets` (Android Keystore) to `run_with_engine`. +# Android (tsc-android): no keyring backend (the app passes Keystore-backed +# secrets) and no winit/femtovg (the app picks Slint's Android backend). [target.'cfg(not(target_os = "android"))'.dependencies] +slint = { version = "1.18", features = ["renderer-software"] } tsc-store = { path = "../tsc-store", features = ["keyring"] } +[target.'cfg(target_os = "android")'.dependencies] +slint = { version = "1.18", default-features = false, features = ["std", "compat-1-2", "renderer-software"] } + [build-dependencies] slint-build = "1.18" diff --git a/crates/tsc-ui/src/app.rs b/crates/tsc-ui/src/app.rs index 1a10ac8..95033df 100644 --- a/crates/tsc-ui/src/app.rs +++ b/crates/tsc-ui/src/app.rs @@ -19,11 +19,25 @@ slint::include_modules!(); /// Secrets in the OS keyring, or in memory when there is none (headless /// Linux without a Secret Service). +#[cfg(not(target_os = "android"))] struct FallbackSecrets { keyring: tsc_store::KeyringSecrets, memory: MemorySecrets, } +/// The secrets store when [`RunOptions::secrets`] is not given: the OS +/// keyring on desktop, memory elsewhere. +fn default_secrets() -> Box { + #[cfg(not(target_os = "android"))] + return Box::new(FallbackSecrets { + keyring: tsc_store::KeyringSecrets::new("tsc-client"), + memory: MemorySecrets::default(), + }); + #[cfg(target_os = "android")] + return Box::new(MemorySecrets::default()); +} + +#[cfg(not(target_os = "android"))] impl Secrets for FallbackSecrets { fn get(&self, key: &str) -> tsc_store::Result> { match self.memory.get(key)? { @@ -105,18 +119,76 @@ fn with_app(f: impl FnOnce(&mut App) -> R) -> Option { } /// Start options for [`run`]. -#[derive(Clone, Debug, Default)] +#[derive(Default)] pub struct RunOptions { /// Where the client database lives. Default: `TSC_DATA_DIR`, else /// `/tsc`. Mobile platforms pass their app storage directory. pub data_dir: Option, + /// Where passwords are kept. Default: the OS keyring, in memory when it + /// is unavailable. + pub secrets: Option>, + /// An engine the caller keeps running across windows (Android: voice + /// goes on in a service while the activity is recreated). Default: an + /// engine that stops with the window. + pub engine: Option, +} + +impl std::fmt::Debug for RunOptions { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("RunOptions") + .field("data_dir", &self.data_dir) + .field("secrets", &self.secrets.is_some()) + .field("engine", &self.engine.is_some()) + .finish() + } +} + +/// An engine owned by the caller of [`run`]. +pub struct HostedEngine { + pub engine: Engine, + /// The runtime the engine runs on; the window's tasks run there too. + pub runtime: tokio::runtime::Handle, + /// The engine's events for this window: first events that rebuild the + /// current state of every session, then new ones. The window stops + /// reading when it closes. + pub events: tokio::sync::mpsc::UnboundedReceiver, +} + +impl HostedEngine { + /// A new engine on `runtime`, all of whose events go to the window. + fn start(runtime: &Runtime) -> Self { + let engine = runtime.block_on(async { Engine::start() }); + let (tx, events) = tokio::sync::mpsc::unbounded_channel(); + let mut rx = engine.subscribe(); + runtime.spawn(async move { + loop { + match rx.recv().await { + Ok(event) => { + if tx.send(event).is_err() { + break; + } + } + Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue, + Err(_) => break, + } + } + }); + Self { engine, runtime: runtime.handle().clone(), events } + } } /// Run the app on the current thread until the window closes. The Slint /// platform must be set up before (the default backend on desktop). pub fn run(options: RunOptions) -> Result<()> { - let runtime = Runtime::new()?; - let engine = runtime.block_on(async { Engine::start() }); + let (own_runtime, hosted) = match options.engine { + Some(hosted) => (None, hosted), + None => { + let runtime = Runtime::new()?; + let hosted = HostedEngine::start(&runtime); + (Some(runtime), hosted) + } + }; + let HostedEngine { engine, runtime, mut events } = hosted; // Development switches: TSC_DATA_DIR isolates the database, // TSC_AUTOCONNECT=voice|observe connects the first bookmark on start, @@ -143,10 +215,7 @@ pub fn run(options: RunOptions) -> Result<()> { let app = App { ui: ui.as_weak(), store, - secrets: Box::new(FallbackSecrets { - keyring: tsc_store::KeyringSecrets::new("tsc-client"), - memory: MemorySecrets::default(), - }), + secrets: options.secrets.unwrap_or_else(default_secrets), engine: engine.clone(), identity, current: bookmarks.first().map(|b| b.id), @@ -158,18 +227,14 @@ pub fn run(options: RunOptions) -> Result<()> { wire_callbacks(&ui); with_app(|app| app.refresh_all()); - // Engine events -> UI thread. - let mut events = engine.subscribe(); + // Engine events -> UI thread, until the event loop is gone. runtime.spawn(async move { - loop { - match events.recv().await { - Ok(event) => { - let _ = slint::invoke_from_event_loop(move || { - with_app(|app| app.handle_event(event)); - }); - } - Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue, - Err(_) => break, + while let Some(event) = events.recv().await { + let posted = slint::invoke_from_event_loop(move || { + with_app(|app| app.handle_event(event)); + }); + if posted.is_err() { + break; } } }); @@ -205,7 +270,9 @@ pub fn run(options: RunOptions) -> Result<()> { ui.run()?; APP.with(|a| a.borrow_mut().take()); - runtime.shutdown_timeout(std::time::Duration::from_secs(2)); + if let Some(runtime) = own_runtime { + runtime.shutdown_timeout(std::time::Duration::from_secs(2)); + } Ok(()) } diff --git a/crates/tsc-ui/src/lib.rs b/crates/tsc-ui/src/lib.rs index f65782f..30d05ec 100644 --- a/crates/tsc-ui/src/lib.rs +++ b/crates/tsc-ui/src/lib.rs @@ -2,4 +2,4 @@ mod app; -pub use app::{RunOptions, run}; +pub use app::{HostedEngine, RunOptions, run};