wip: tsc-android engine host, JNI bridge, MediaProjection capture, MediaCodec
This commit is contained in:
19 files changed
+2347
-30
No files matched your search
@@ -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<EngineHost> = OnceLock::new();
|
||||
static FOREGROUND: Mutex<Option<Foreground>> = 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<R>(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 });
|
||||
}
|
||||
}
|
||||
@@ -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<Global<JClass<'static>>> = 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<T>(f: impl FnOnce(&mut Env, &Global<JClass<'static>>) -> Result<T>) -> Result<T> {
|
||||
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<JObject<'local>> {
|
||||
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<bool> {
|
||||
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<Option<String>> {
|
||||
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::<JString>(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<jboolean> {
|
||||
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<jboolean> {
|
||||
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(())
|
||||
}
|
||||
@@ -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<FrameSender<VideoFrame>>,
|
||||
/// Answer for the pending `start`.
|
||||
pending: Option<oneshot::Sender<Result<()>>>,
|
||||
audio: Option<FrameSender<AudioBuffer>>,
|
||||
first_frame_ns: Option<i64>,
|
||||
first_audio_ns: Option<i64>,
|
||||
}
|
||||
|
||||
static STATE: Mutex<Option<State>> = Mutex::new(None);
|
||||
|
||||
fn with_state<R>(f: impl FnOnce(&mut State) -> R) -> R {
|
||||
let mut guard: MutexGuard<'_, Option<State>> =
|
||||
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<i64>, 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<CaptureSource> {
|
||||
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<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.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<AudioBuffer>) -> 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<String>) {
|
||||
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<u8>, 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<f32>, 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
|
||||
})
|
||||
}
|
||||
@@ -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<SessionId, Session>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Session {
|
||||
name: Option<String>,
|
||||
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<Option<String>> {
|
||||
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<SessionId> {
|
||||
self.sessions
|
||||
.iter()
|
||||
.filter(|(_, s)| s.voice != VoiceState::Disconnected)
|
||||
.map(|(id, _)| *id)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The notification text, `None` without voice.
|
||||
pub fn notification(&self) -> Option<String> {
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -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<SessionId, SessionReplay>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct SessionReplay {
|
||||
server_info: Option<Event>,
|
||||
state: Option<Event>,
|
||||
presence: Option<Event>,
|
||||
streams: Option<Event>,
|
||||
own_stream: Option<Event>,
|
||||
viewers: Option<Event>,
|
||||
watching: BTreeMap<String, Event>,
|
||||
chat: VecDeque<Event>,
|
||||
}
|
||||
|
||||
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<Event> {
|
||||
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<Mutex<FanoutState>>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct FanoutState {
|
||||
replay: Replay,
|
||||
window: Option<mpsc::UnboundedSender<Event>>,
|
||||
}
|
||||
|
||||
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<Event> {
|
||||
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<Event>) {
|
||||
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<Event>,
|
||||
}
|
||||
|
||||
impl EngineHost {
|
||||
pub fn start() -> std::io::Result<Self> {
|
||||
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<String> {
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
@@ -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<Option<String>> {
|
||||
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)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user