Android: cameras in the Stream Studio through Camera2

The studio listed only the test pattern on Android. voelin-media gains a
camera provider hook (like the external screen capture): the app
registers Camera2, whose cameras the studio's picker lists first (front
ones first, with their YUV sizes and highest frame rate), and a camera
source opens one. CameraCapture.kt asks for the CAMERA permission when a
camera is first opened (the source shows why if it is refused), opens
the camera into an ImageReader (YUV_420_888) at the wished size or the
nearest one (16:9 first, 1280x720 by default) with a fitting frame-rate
range, and hands each frame's planes to Rust as direct buffers valid
during the call, with the clockwise turn that makes it upright for the
screen's current rotation (front cameras turn the other way).

Rust takes the planes as YuvPlanes: an upright planar or NV12 picture
goes to the studio's sink as it is, converted straight from the
camera's memory; NV21 (what most cameras give) and turned pictures are
gathered into I420 in a buffer each camera keeps, so a running camera
allocates nothing per frame. Errors after the start (permission refused,
camera taken by another app) go to the source's feed.

Front and back: a camera's default mirroring now follows the camera (a
back camera is not mirrored, what faces the user is), and the source
menu gains Switch camera, which moves a camera source to the next
camera (and its name with it, if it was named after the camera).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
selikhovandClaude Opus 5.5 committed 2026-10-03 18:17:13 +03:00
1 parent 5da3f94479
commit 1eabbb4704
12 files changed
+972 -15

No files matched your search

+2 -1
View File
@@ -14,7 +14,7 @@ use voelin_core::Command;
use crate::foreground::Foreground;
use crate::host::EngineHost;
use crate::{bridge, capture, egl, secrets};
use crate::{bridge, camera, capture, egl, secrets};
/// Store setting (`bool`): the user's opt-in to local crash reports (read
/// before the settings service starts, straight from the database).
@@ -77,6 +77,7 @@ fn run(app: AndroidApp) -> anyhow::Result<()> {
// Before Slint creates the first window surface.
egl::reserve_skia_extension_slots();
capture::register();
camera::register();
watch_voice(host);
});
if let Err(e) = bridge::request_permissions() {
+145
View File
@@ -214,6 +214,56 @@ fn parse_apps(lines: &str) -> Vec<(String, String)> {
.collect()
}
/// The cameras (`CameraCapture.list`): `id<TAB>facing<TAB>sizes<TAB>maxFps`
/// lines.
pub fn cameras() -> Result<String> {
with_bridge(|env, class| {
let value = env
.call_static_method(class, jni_str!("cameras"), jni_sig!(() -> java.lang.String), &[])?
.l()?;
if value.is_null() {
return Ok(String::new());
}
let value = env.cast_local::<JString>(value)?;
value.try_to_string(env)
})
}
/// Open camera `device` for feed `id` (frames to `Native.onCameraFrame`,
/// later failures to `Native.onCameraError`); 0 x 0: its default size.
pub fn start_camera(id: u64, device: &str, width: u32, height: u32, fps: u32) -> Result<bool> {
with_bridge(|env, class| {
let device = JObject::from(env.new_string(device)?);
env.call_static_method(
class,
jni_str!("startCamera"),
jni_sig!(
(id: jlong, camera_id: java.lang.String, width: jint, height: jint, fps: jint) -> jboolean
),
&[
JValue::Long(id as jlong),
JValue::Object(&device),
JValue::Int(width as jint),
JValue::Int(height as jint),
JValue::Int(fps as jint),
],
)?
.z()
})
}
pub fn stop_camera(id: u64) -> Result<()> {
with_bridge(|env, class| {
env.call_static_method(
class,
jni_str!("stopCamera"),
jni_sig!((id: jlong) -> void),
&[JValue::Long(id as jlong)],
)?;
Ok(())
})
}
pub fn secret_get(key: &str) -> Result<Option<String>> {
with_bridge(|env, class| {
let key = JObject::from(env.new_string(key)?);
@@ -385,6 +435,101 @@ fn on_audio_input<'local>(
})
}
/// The memory of a direct buffer: its address and capacity.
fn direct(env: &Env<'_>, buffer: &JByteBuffer<'_>, what: &'static str) -> Result<(*mut u8, usize)> {
let address = env.get_direct_buffer_address(buffer)?;
if address.is_null() {
return Err(Error::NullPtr(what));
}
Ok((address, env.get_direct_buffer_capacity(buffer)?))
}
const _: jni::NativeMethod = native_method! {
java_type = "io.github.faumaray.voelin.Native",
static extern fn on_camera_frame(
id: jlong,
y: JByteBuffer,
u: JByteBuffer,
v: JByteBuffer,
y_row_stride: jint,
uv_row_stride: jint,
uv_pixel_stride: jint,
width: jint,
height: jint,
rotation: jint,
timestamp_ns: jlong,
) -> jboolean,
};
/// A YUV_420_888 camera frame (see `crate::camera`). Returns `false` once
/// it is no longer wanted.
#[allow(clippy::too_many_arguments)]
fn on_camera_frame<'local>(
env: &mut Env<'local>,
_class: JClass<'local>,
id: jlong,
y: JByteBuffer<'local>,
u: JByteBuffer<'local>,
v: JByteBuffer<'local>,
y_row_stride: jint,
uv_row_stride: jint,
uv_pixel_stride: jint,
width: jint,
height: jint,
rotation: jint,
timestamp_ns: jlong,
) -> Result<jboolean> {
let (y_at, y_len) = direct(env, &y, "camera luma")?;
let (u_at, u_len) = direct(env, &u, "camera U")?;
let (v_at, v_len) = direct(env, &v, "camera V")?;
let step = uv_pixel_stride.max(1) as usize;
// SAFETY: a direct buffer's memory is `capacity` bytes at its address,
// and the `Image` the planes belong to stays open until this call
// returns. With V one byte after U (interleaved, U first), U's address
// and V's length plus one span both planes up to the end of V's buffer:
// memory of the same image.
#[allow(unsafe_code)]
let (y, u, v, nv12) = unsafe {
let nv12 = (step == 2 && v_at as usize == u_at as usize + 1)
.then(|| std::slice::from_raw_parts(u_at, v_len + 1));
(
std::slice::from_raw_parts(y_at, y_len),
std::slice::from_raw_parts(u_at, u_len),
std::slice::from_raw_parts(v_at, v_len),
nv12,
)
};
let planes = voelin_media::studio::camera::YuvPlanes {
width: width.max(0) as u32,
height: height.max(0) as u32,
y,
y_stride: y_row_stride.max(0) as usize,
u,
v,
uv_stride: uv_row_stride.max(0) as usize,
uv_step: step,
nv12,
rotation: rotation.max(0) as u32,
};
Ok(crate::camera::on_frame(id as u64, &planes, timestamp_ns))
}
const _: jni::NativeMethod = native_method! {
java_type = "io.github.faumaray.voelin.Native",
static extern fn on_camera_error(id: jlong, message: JString),
};
fn on_camera_error<'local>(
env: &mut Env<'local>,
_class: JClass<'local>,
id: jlong,
message: JString<'local>,
) -> Result<()> {
let message = if message.is_null() { String::new() } else { message.try_to_string(env)? };
crate::camera::on_error(id as u64, message);
Ok(())
}
const _: jni::NativeMethod = native_method! {
java_type = "io.github.faumaray.voelin.Native",
static extern fn on_disconnect_voice(),
+174
View File
@@ -0,0 +1,174 @@
//! Cameras for the Stream Studio through Camera2.
//!
//! Registered as the studio's [`CameraProvider`]: the studio's camera
//! picker lists the device's cameras (front ones first; a back camera is
//! not mirrored by default), and a camera source opens one.
//! `CameraCapture.kt` asks for the CAMERA permission if needed, opens the
//! camera into an `ImageReader` (YUV_420_888) and hands each frame's planes
//! to [`on_frame`] as direct buffers valid during the call, with the turn
//! that makes it upright for the screen's rotation. The studio's sink
//! converts straight from the camera's memory when the picture is upright
//! and planar or NV12; otherwise it is gathered (and turned) into a buffer
//! each camera keeps, so a running camera allocates nothing per frame.
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::time::Duration;
use tracing::warn;
use voelin_media::capture::FrameSink;
use voelin_media::studio::camera::{Camera, CameraProvider, Format, Pixel, YuvPlanes};
use voelin_media::studio::compose::Feed;
use voelin_media::{Error, Result};
use crate::bridge;
const BACKEND: &str = "camera2";
struct Running {
sink: Box<dyn FrameSink>,
feed: Arc<Feed>,
/// Clock origin of the frames' timestamps (`Image.timestamp`).
origin_ns: Option<i64>,
/// Gathered or turned pictures (I420), reused.
scratch: Vec<u8>,
}
static RUNNING: Mutex<Option<HashMap<u64, Running>>> = Mutex::new(None);
fn running() -> MutexGuard<'static, Option<HashMap<u64, Running>>> {
RUNNING.lock().unwrap_or_else(PoisonError::into_inner)
}
/// Make Camera2 the studio's cameras.
pub fn register() {
voelin_media::studio::camera::set_provider(Some(Arc::new(Camera2)));
}
struct Camera2;
/// Stops its camera when dropped.
struct Guard(u64);
impl Drop for Guard {
fn drop(&mut self) {
running().as_mut().map(|r| r.remove(&self.0));
if let Err(e) = bridge::stop_camera(self.0) {
warn!("stopping camera {}: {e}", self.0);
}
}
}
impl CameraProvider for Camera2 {
fn name(&self) -> &'static str {
BACKEND
}
fn list(&self) -> Vec<Camera> {
match bridge::cameras() {
Ok(lines) => parse(&lines),
Err(e) => {
warn!("listing cameras: {e}");
Vec::new()
}
}
}
fn start(
&self,
device: &str,
size: Option<(u32, u32)>,
fps: u32,
sink: Box<dyn FrameSink>,
feed: Arc<Feed>,
) -> Result<Box<dyn Send>> {
static NEXT: AtomicU64 = AtomicU64::new(1);
let id = NEXT.fetch_add(1, Ordering::Relaxed);
let entry = Running { sink, feed, origin_ns: None, scratch: Vec::new() };
running().get_or_insert_with(HashMap::new).insert(id, entry);
let (width, height) = size.unwrap_or((0, 0));
match bridge::start_camera(id, device, width, height, fps) {
Ok(true) => Ok(Box::new(Guard(id))),
started => {
running().as_mut().map(|r| r.remove(&id));
let reason = match started {
Err(e) => e.to_string(),
_ => format!("camera {device:?} cannot be opened"),
};
Err(Error::CaptureUnavailable { backend: BACKEND, reason })
}
}
}
}
/// `id<TAB>facing<TAB>sizes<TAB>maxFps` lines (`CameraCapture.list`).
fn parse(lines: &str) -> Vec<Camera> {
let mut seen: HashMap<String, usize> = HashMap::new();
lines
.lines()
.filter_map(|line| {
let mut parts = line.split('\t');
let id = parts.next()?.trim();
let facing = parts.next()?.trim();
let sizes = parts
.next()
.unwrap_or_default()
.split(',')
.filter_map(|s| {
let (w, h) = s.trim().split_once('x')?;
Some((w.parse().ok()?, h.parse().ok()?))
})
.collect::<Vec<(u32, u32)>>();
let max_fps = parts.next().and_then(|f| f.trim().parse().ok()).unwrap_or(0);
if id.is_empty() {
return None;
}
let label = match facing {
"front" => "Front camera",
"back" => "Back camera",
_ => "External camera",
};
let n = seen.entry(label.to_owned()).or_insert(0);
*n += 1;
let name = if *n == 1 { label.to_owned() } else { format!("{label} {n}") };
Some(Camera {
id: id.to_owned(),
name,
backend: BACKEND,
formats: vec![Format { pixel: Pixel::I420, sizes, max_fps }],
// What faces the user is mirrored, as a mirror would be.
mirrored: facing != "back",
})
})
.collect()
}
/// A frame of camera `id`. Returns `false` once it is no longer wanted.
pub fn on_frame(id: u64, planes: &YuvPlanes<'_>, timestamp_ns: i64) -> bool {
let mut guard = running();
let Some(run) = guard.as_mut().and_then(|r| r.get_mut(&id)) else { return false };
let Running { sink, feed, origin_ns, scratch } = run;
if feed.is_closed() {
return false;
}
let origin = *origin_ns.get_or_insert(timestamp_ns);
let timestamp = Duration::from_nanos(u64::try_from(timestamp_ns - origin).unwrap_or(0));
if !sink.wants(timestamp) {
return true;
}
match planes.frame(timestamp, scratch) {
Ok(frame) => sink.frame(frame),
Err(e) => {
warn!("dropping a camera frame: {e}");
true
}
}
}
/// Camera `id` failed (or could not open): the studio shows why.
pub fn on_error(id: u64, message: String) {
if let Some(run) = running().as_ref().and_then(|r| r.get(&id)) {
run.feed.set_error(Error::Capture { backend: BACKEND, message });
}
}
+4
View File
@@ -13,6 +13,8 @@
//! native methods it calls back (`Native`)
//! - `capture` (Android): screen and system-audio capture through
//! MediaProjection, registered as `voelin_media` capture providers
//! - `camera` (Android): the Stream Studio's cameras through Camera2,
//! registered as its camera provider
//! - `secrets` (Android): passwords encrypted with an Android Keystore key
//! - `egl` (Android): keeps EGL extension slots for Skia, without which the
//! UI cannot draw on Mesa-based Android (Waydroid)
@@ -27,6 +29,8 @@ mod app;
#[cfg(target_os = "android")]
mod bridge;
#[cfg(target_os = "android")]
mod camera;
#[cfg(target_os = "android")]
mod capture;
#[cfg(target_os = "android")]
mod egl;