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 c34475205b
commit 601ce661b1
12 files changed
+972 -15

No files matched your search

+3
View File
@@ -10,6 +10,9 @@
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PROJECTION" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<!-- Camera sources of the Stream Studio; asked for when one is added. -->
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera.any" android:required="false" />
<!--
Launchable apps are visible (Android 11+ package visibility): the
@@ -108,6 +108,23 @@ object Bridge {
.joinToString("\n") { (packageName, label) -> label.replace(separators, " ") + "\t" + packageName }
}
/** The cameras, as CameraCapture.list describes them. */
@JvmStatic
fun cameras(): String = CameraCapture.list(app)
/**
* Open camera `cameraId` for feed `id` (Native.onCameraFrame, errors to
* Native.onCameraError); 0 x 0: its default size.
*/
@JvmStatic
fun startCamera(id: Long, cameraId: String, width: Int, height: Int, fps: Int): Boolean =
CameraCapture.start(app, id, cameraId, width, height, fps)
@JvmStatic
fun stopCamera(id: Long) {
CameraCapture.stop(id)
}
@JvmStatic
fun secretGet(key: String): String? = SecretStore.get(app, key)
@@ -0,0 +1,293 @@
package io.github.faumaray.voelin
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.graphics.ImageFormat
import android.hardware.camera2.CameraCaptureSession
import android.hardware.camera2.CameraCharacteristics
import android.hardware.camera2.CameraDevice
import android.hardware.camera2.CameraManager
import android.hardware.camera2.CaptureRequest
import android.hardware.camera2.params.OutputConfiguration
import android.hardware.camera2.params.SessionConfiguration
import android.hardware.display.DisplayManager
import android.media.ImageReader
import android.os.Handler
import android.os.HandlerThread
import android.util.Log
import android.util.Range
import android.util.Size
import android.view.Display
import android.view.Surface
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.Executor
import kotlin.math.abs
/**
* Cameras for the Stream Studio (crates/voelin-android/src/camera.rs):
* Camera2 into an ImageReader (YUV_420_888); each frame's planes go to
* Native.onCameraFrame as direct buffers, valid during the call, so the
* Rust side converts straight from the camera's memory. Several cameras
* may run at once, each under the id the Rust side gave it.
*/
object CameraCapture {
private const val TAG = "CameraCapture"
/** Without a wish: about this size (16:9, what the studio composes). */
private const val DEFAULT_WIDTH = 1280
private const val DEFAULT_HEIGHT = 720
private class Running(val id: Long, val cameraId: String) {
@Volatile
var stopped = false
var thread: HandlerThread? = null
var device: CameraDevice? = null
var session: CameraCaptureSession? = null
var reader: ImageReader? = null
}
private val running = ConcurrentHashMap<Long, Running>()
/** Starts waiting for the CAMERA permission, by id. */
private val waiting = ConcurrentHashMap<Long, () -> Unit>()
private fun facing(c: CameraCharacteristics): String = when (c.get(CameraCharacteristics.LENS_FACING)) {
CameraCharacteristics.LENS_FACING_FRONT -> "front"
CameraCharacteristics.LENS_FACING_BACK -> "back"
else -> "external"
}
private fun sizes(c: CameraCharacteristics): List<Size> =
c.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP)
?.getOutputSizes(ImageFormat.YUV_420_888)
?.sortedByDescending { it.width.toLong() * it.height }
.orEmpty()
private fun fpsRanges(c: CameraCharacteristics): List<Range<Int>> =
c.get(CameraCharacteristics.CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES)?.toList().orEmpty()
/**
* The cameras, front ones first: "id<TAB>facing<TAB>sizes<TAB>maxFps"
* lines, sizes as "1920x1080,1280x720" (largest first).
*/
fun list(context: Context): String {
val manager = context.getSystemService(CameraManager::class.java) ?: return ""
val ids = try {
manager.cameraIdList.toList()
} catch (e: Exception) {
Log.w(TAG, "cannot list the cameras", e)
return ""
}
return ids.mapNotNull { id ->
try {
val c = manager.getCameraCharacteristics(id)
val sizes = sizes(c).joinToString(",") { "${it.width}x${it.height}" }
val fps = fpsRanges(c).maxOfOrNull { it.upper } ?: 30
Triple(id, facing(c), "$sizes\t$fps")
} catch (e: Exception) {
Log.w(TAG, "cannot ask camera $id", e)
null
}
}
.sortedBy { (_, facing, _) -> if (facing == "front") 0 else if (facing == "back") 1 else 2 }
.joinToString("\n") { (id, facing, rest) -> "$id\t$facing\t$rest" }
}
/**
* Open `cameraId` for mixer feed `id` at about `width` x `height` (0:
* the default) and `fps`. Asks for the CAMERA permission first if
* needed; failures later go to Native.onCameraError.
*/
fun start(context: Context, id: Long, cameraId: String, width: Int, height: Int, fps: Int): Boolean {
if (context.checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
return open(context, id, cameraId, width, height, fps)
}
val activity = MainActivity.current?.get()
if (activity == null) {
Native.onCameraError(id, "Allow Voelin to use the camera (open the app)")
return false
}
waiting[id] = { open(context, id, cameraId, width, height, fps) }
activity.runOnUiThread { activity.requestCameraPermission() }
return true
}
/** The answer to the CAMERA permission prompt (MainActivity). */
fun onPermissionResult(granted: Boolean) {
val starts = waiting.keys.toList().mapNotNull { id -> waiting.remove(id)?.let { id to it } }
for ((id, start) in starts) {
if (granted) {
start()
} else {
Native.onCameraError(id, "Voelin may not use the camera (Android settings, Apps, Voelin, Permissions)")
}
}
}
private fun open(context: Context, id: Long, cameraId: String, width: Int, height: Int, fps: Int): Boolean {
stop(id)
val manager = context.getSystemService(CameraManager::class.java) ?: return false
val c = try {
manager.getCameraCharacteristics(cameraId)
} catch (e: Exception) {
Native.onCameraError(id, "no camera $cameraId: ${e.message}")
return false
}
val size = pick(sizes(c), width, height) ?: run {
Native.onCameraError(id, "camera $cameraId has no YUV output")
return false
}
val range = fpsRange(fpsRanges(c), fps)
val front = c.get(CameraCharacteristics.LENS_FACING) == CameraCharacteristics.LENS_FACING_FRONT
val sensor = c.get(CameraCharacteristics.SENSOR_ORIENTATION) ?: 0
val display = context.getSystemService(DisplayManager::class.java)?.getDisplay(Display.DEFAULT_DISPLAY)
val run = Running(id, cameraId)
running[id] = run
val thread = HandlerThread("voelin-camera-$id").also { it.start() }
run.thread = thread
val handler = Handler(thread.looper)
val executor = Executor { handler.post(it) }
val reader = ImageReader.newInstance(size.width, size.height, ImageFormat.YUV_420_888, 3)
run.reader = reader
reader.setOnImageAvailableListener({ r ->
val image = try {
r.acquireLatestImage()
} catch (e: IllegalStateException) {
null
} ?: return@setOnImageAvailableListener
try {
if (run.stopped) return@setOnImageAvailableListener
val planes = image.planes
val wanted = Native.onCameraFrame(
id,
planes[0].buffer,
planes[1].buffer,
planes[2].buffer,
planes[0].rowStride,
planes[1].rowStride,
planes[1].pixelStride,
image.width,
image.height,
rotation(sensor, front, display),
image.timestamp,
)
if (!wanted) stop(id)
} finally {
image.close()
}
}, handler)
val fail = { message: String ->
if (!run.stopped) Native.onCameraError(id, message)
stop(id)
}
try {
manager.openCamera(cameraId, executor, object : CameraDevice.StateCallback() {
override fun onOpened(device: CameraDevice) {
if (run.stopped) {
device.close()
return
}
run.device = device
val request = device.createCaptureRequest(CameraDevice.TEMPLATE_RECORD).apply {
addTarget(reader.surface)
if (range != null) set(CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE, range)
}
val outputs = listOf(OutputConfiguration(reader.surface))
device.createCaptureSession(
SessionConfiguration(
SessionConfiguration.SESSION_REGULAR,
outputs,
executor,
object : CameraCaptureSession.StateCallback() {
override fun onConfigured(session: CameraCaptureSession) {
if (run.stopped) {
session.close()
return
}
run.session = session
try {
session.setRepeatingRequest(request.build(), null, handler)
} catch (e: Exception) {
fail("camera $cameraId: ${e.message}")
}
}
override fun onConfigureFailed(session: CameraCaptureSession) {
fail("camera $cameraId cannot deliver ${size.width}x${size.height}")
}
},
),
)
}
override fun onDisconnected(device: CameraDevice) {
device.close()
// Another app took it, or it was unplugged.
fail("camera $cameraId was disconnected")
}
override fun onError(device: CameraDevice, error: Int) {
device.close()
fail("camera $cameraId failed (error $error)")
}
})
} catch (e: SecurityException) {
fail("Voelin may not use the camera")
return false
} catch (e: Exception) {
fail("cannot open camera $cameraId: ${e.message}")
return false
}
return true
}
fun stop(id: Long) {
waiting.remove(id)
val run = running.remove(id) ?: return
run.stopped = true
try {
run.session?.close()
run.device?.close()
} catch (e: Exception) {
Log.w(TAG, "closing camera ${run.cameraId}", e)
}
run.thread?.let { thread ->
// The reader is closed on its own thread, after the last frame.
Handler(thread.looper).post { run.reader?.close() }
thread.quitSafely()
}
}
/** The wished size if the camera has it, else the nearest in pixels (16:9 first). */
private fun pick(sizes: List<Size>, width: Int, height: Int): Size? {
if (sizes.isEmpty()) return null
val (w, h) = if (width > 0 && height > 0) width to height else DEFAULT_WIDTH to DEFAULT_HEIGHT
sizes.firstOrNull { it.width == w && it.height == h }?.let { return it }
val wanted = w.toLong() * h
val sameShape = sizes.filter { it.width.toLong() * h == it.height.toLong() * w }
return (sameShape.ifEmpty { sizes }).minByOrNull { abs(it.width.toLong() * it.height - wanted) }
}
/** A fixed `fps` range if there is one, else the nearest that reaches it. */
private fun fpsRange(ranges: List<Range<Int>>, fps: Int): Range<Int>? =
ranges.firstOrNull { it.lower == fps && it.upper == fps }
?: ranges.filter { it.upper >= fps }.minWithOrNull(compareBy({ it.upper }, { -it.lower }))
?: ranges.maxByOrNull { it.upper }
/**
* Clockwise degrees that turn the sensor's picture upright for the
* screen's current rotation (front cameras turn the other way).
*/
private fun rotation(sensor: Int, front: Boolean, display: Display?): Int {
val screen = when (display?.rotation) {
Surface.ROTATION_90 -> 90
Surface.ROTATION_180 -> 180
Surface.ROTATION_270 -> 270
else -> 0
}
return if (front) (sensor + screen) % 360 else (sensor - screen + 360) % 360
}
}
@@ -1,7 +1,9 @@
package io.github.faumaray.voelin
import android.Manifest
import android.app.NativeActivity
import android.content.Intent
import android.content.pm.PackageManager
import android.media.projection.MediaProjectionManager
import android.net.Uri
import android.os.Build
@@ -123,6 +125,18 @@ class MainActivity : NativeActivity() {
return name?.replace(Regex("[/\\\\\n\r\u0000]"), "_")?.trim()?.takeIf { it.isNotEmpty() && it != "." && it != ".." }
}
/** Ask for the camera (a studio camera source); CameraCapture gets the answer. */
fun requestCameraPermission() {
requestPermissions(arrayOf(Manifest.permission.CAMERA), REQUEST_CAMERA)
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == REQUEST_CAMERA) {
CameraCapture.onPermissionResult(grantResults.firstOrNull() == PackageManager.PERMISSION_GRANTED)
}
}
/** Show the system's "start recording or casting?" dialog. */
fun requestScreenCapture(fps: Int, maxSize: Int) {
captureFps = fps
@@ -148,6 +162,7 @@ class MainActivity : NativeActivity() {
companion object {
private const val TAG = "MainActivity"
private const val REQUEST_SCREEN_CAPTURE = 1001
private const val REQUEST_CAMERA = 1002
/** The activity in front, if any. */
@Volatile
@@ -54,6 +54,32 @@ object Native {
@JvmStatic
external fun onToggleDeafen()
/**
* A YUV_420_888 camera frame for feed `id`: the three planes (direct
* buffers, valid during the call), the luma and chroma row strides, the
* chroma pixel stride (1: planar, 2: interleaved), and the clockwise
* rotation that turns it upright. Returns false when it is no longer
* wanted.
*/
@JvmStatic
external fun onCameraFrame(
id: Long,
y: ByteBuffer,
u: ByteBuffer,
v: ByteBuffer,
yRowStride: Int,
uvRowStride: Int,
uvPixelStride: Int,
width: Int,
height: Int,
rotation: Int,
timestampNs: Long,
): Boolean
/** Camera feed `id` failed or could not start (`message`: why). */
@JvmStatic
external fun onCameraError(id: Long, message: String)
/** The voice notification was tapped: show the voice channel. */
@JvmStatic
external fun onOpenVoice()
+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;
+254 -9
View File
@@ -18,19 +18,24 @@
//! [`SYNTHETIC`] is a camera that is always there: the test pattern. Tests
//! and machines without a camera use it.
//!
//! Windows and Android have no camera backend yet ([`list`] returns only the
//! synthetic one).
//! Android: the app registers a [`CameraProvider`] (Camera2 through its
//! Kotlin side) whose cameras [`list`] puts first and [`Capture::start`]
//! opens; its frames come as [`YuvPlanes`], converted straight from the
//! camera's memory where the layout allows. Windows has no camera backend
//! yet ([`list`] returns only the synthetic one there).
use std::sync::Arc;
use std::sync::atomic::AtomicU32;
use std::sync::{Arc, Mutex, PoisonError};
use std::time::Duration;
use crate::Result;
use crate::capture::synthetic::SyntheticScreen;
use crate::capture::{CaptureOptions, ScreenCapture, SourceId};
use crate::capture::{CaptureOptions, FrameSink, ScreenCapture, SourceId};
use crate::frame::{FrameRef, PixelsRef, PlaneRef};
use crate::studio::compose::Feed;
use crate::studio::scene::Background;
use crate::studio::segment::BackgroundFilter;
use crate::studio::source::FeedSink;
use crate::{Error, Result};
/// The id of the camera that is always available: the test pattern.
pub const SYNTHETIC: &str = "synthetic";
@@ -108,9 +113,12 @@ pub struct Camera {
/// on Linux, or [`SYNTHETIC`].
pub id: String,
pub name: String,
/// Where the list came from (`"v4l2"`, `"synthetic"`).
/// Where the list came from (`"v4l2"`, `"synthetic"`, `"camera2"`).
pub backend: &'static str,
pub formats: Vec<Format>,
/// Shown mirrored by default: a camera facing the user (webcams, a
/// phone's front camera), not one facing away.
pub mirrored: bool,
}
/// Every camera this session can use. Never fails: a device that cannot be
@@ -126,8 +134,150 @@ pub fn list() -> Vec<Camera> {
name: "Test pattern".to_owned(),
backend: "synthetic",
formats: vec![Format { pixel: Pixel::Bgrx, sizes: vec![(1280, 720)], max_fps: 60 }],
mirrored: true,
};
devices.into_iter().chain([synthetic]).collect()
let external = provider().map(|p| p.list()).unwrap_or_default();
external.into_iter().chain(devices).chain([synthetic]).collect()
}
/// Cameras of a platform API outside this crate, registered by the app at
/// start like the external screen capture ([`crate::capture::external`]):
/// on Android, Camera2 through the app's Kotlin side.
pub trait CameraProvider: Send + Sync {
/// Short name for logs and [`Capture::backend`] (`"camera2"`).
fn name(&self) -> &'static str;
/// The cameras, in the order a picker shows them.
fn list(&self) -> Vec<Camera>;
/// Open `device` and feed `sink` with up to `fps` frames a second at
/// about `size` (`None`: the camera's default); what fails after the
/// start (a permission refused, the camera taken by another app) goes
/// to `feed`. The camera stops when the returned value is dropped.
fn start(
&self,
device: &str,
size: Option<(u32, u32)>,
fps: u32,
sink: Box<dyn FrameSink>,
feed: Arc<Feed>,
) -> Result<Box<dyn Send>>;
}
static PROVIDER: Mutex<Option<Arc<dyn CameraProvider>>> = Mutex::new(None);
/// Make [`list`] and [`Capture::start`] use `provider` (`None`: only the
/// built-in cameras).
pub fn set_provider(provider: Option<Arc<dyn CameraProvider>>) {
*PROVIDER.lock().unwrap_or_else(PoisonError::into_inner) = provider;
}
fn provider() -> Option<Arc<dyn CameraProvider>> {
PROVIDER.lock().unwrap_or_else(PoisonError::into_inner).clone()
}
/// A camera picture in three 4:2:0 planes whose chroma samples may lie
/// apart (`uv_step` 2), as Android's `YUV_420_888` hands them over, and the
/// clockwise turn that makes it upright.
#[derive(Clone, Copy, Debug)]
pub struct YuvPlanes<'a> {
pub width: u32,
pub height: u32,
pub y: &'a [u8],
pub y_stride: usize,
pub u: &'a [u8],
pub v: &'a [u8],
/// Bytes per chroma row (both planes).
pub uv_stride: usize,
/// Bytes from one chroma sample to the next in a row: 1 (planar) or 2
/// (interleaved).
pub uv_step: usize,
/// The chroma as one interleaved block with U first (NV12), when it is
/// one: then taken as it is.
pub nv12: Option<&'a [u8]>,
/// Clockwise degrees: 0, 90, 180 or 270.
pub rotation: u32,
}
impl<'a> YuvPlanes<'a> {
/// The picture as a frame: borrowed when it is upright and planar or
/// NV12, else gathered (and turned) into `scratch` as I420; `scratch`
/// keeps its capacity, so nothing is allocated once it has grown.
pub fn frame(&self, timestamp: Duration, scratch: &'a mut Vec<u8>) -> Result<FrameRef<'a>> {
let (w, h) = (self.width as usize, self.height as usize);
if w == 0 || h == 0 {
return Err(Error::InvalidFrame(format!("{w}x{h} camera frame")));
}
let rotation = self.rotation / 90 % 4 * 90;
let (width, height) = (self.width, self.height);
if rotation == 0 {
let y = PlaneRef::new(self.y, self.y_stride);
let pixels = if self.uv_step == 1 {
let u = PlaneRef::new(self.u, self.uv_stride);
let v = PlaneRef::new(self.v, self.uv_stride);
Some(PixelsRef::I420 { y, u, v })
} else {
self.nv12.map(|uv| PixelsRef::Nv12 { y, uv: PlaneRef::new(uv, self.uv_stride) })
};
if let Some(pixels) = pixels {
return Ok(FrameRef { width, height, timestamp, pixels });
}
}
let (cw, ch) = crate::frame::chroma_size(self.width, self.height);
let turned = rotation % 180 == 90;
let (ow, oh) = if turned { (h, w) } else { (w, h) };
let (ocw, och) = if turned { (ch, cw) } else { (cw, ch) };
scratch.resize(ow * oh + 2 * ocw * och, 0);
{
let (y, rest) = scratch.split_at_mut(ow * oh);
let (u, v) = rest.split_at_mut(ocw * och);
turn(self.y, self.y_stride, 1, w, h, rotation, y)?;
turn(self.u, self.uv_stride, self.uv_step, cw, ch, rotation, u)?;
turn(self.v, self.uv_stride, self.uv_step, cw, ch, rotation, v)?;
}
let scratch: &'a [u8] = scratch;
let (y, rest) = scratch.split_at(ow * oh);
let (u, v) = rest.split_at(ocw * och);
let pixels = PixelsRef::I420 {
y: PlaneRef::new(y, ow),
u: PlaneRef::new(u, ocw),
v: PlaneRef::new(v, ocw),
};
Ok(FrameRef { width: ow as u32, height: oh as u32, timestamp, pixels })
}
}
/// Copy the `w` x `h` samples of a plane (`step` bytes apart in a row,
/// `stride` bytes per row) into `out`, turned clockwise by `rotation`, rows
/// without padding.
fn turn(
src: &[u8],
stride: usize,
step: usize,
w: usize,
h: usize,
rotation: u32,
out: &mut [u8],
) -> Result<()> {
if src.len() < (h - 1) * stride + (w - 1) * step + 1 {
return Err(Error::InvalidFrame(format!(
"camera plane of {} bytes is too small for {w}x{h}",
src.len()
)));
}
for y in 0..h {
let row = &src[y * stride..];
for x in 0..w {
let at = match rotation {
90 => x * h + (h - 1 - y),
180 => (h - 1 - y) * w + (w - 1 - x),
270 => (w - 1 - x) * h + y,
_ => y * w + x,
};
out[at] = row[x * step];
}
}
Ok(())
}
/// A running camera; stops when dropped.
@@ -135,6 +285,8 @@ pub struct Capture {
backend: &'static str,
device: String,
screen: Option<Box<dyn ScreenCapture>>,
/// A [`CameraProvider`]'s camera, stopped when dropped.
_external: Option<Box<dyn Send>>,
#[cfg(all(target_os = "linux", feature = "pipewire"))]
stream: Option<pipewire_camera::Stream>,
}
@@ -174,6 +326,23 @@ impl Capture {
backend: "synthetic",
device: wanted,
screen: Some(Box::new(screen)),
_external: None,
#[cfg(all(target_os = "linux", feature = "pipewire"))]
stream: None,
});
}
if let Some(provider) = provider() {
let mut sink = FeedSink::new(feed.clone(), Arc::new(AtomicU32::new(fps)));
if background.needs_mask() {
sink = sink.with_background(BackgroundFilter::with_default_segmenter(background));
}
let running = provider.start(&wanted, size, fps, Box::new(sink), feed)?;
tracing::debug!(device = %wanted, backend = provider.name(), "camera");
return Ok(Self {
backend: provider.name(),
device: wanted,
screen: None,
_external: Some(running),
#[cfg(all(target_os = "linux", feature = "pipewire"))]
stream: None,
});
@@ -183,7 +352,13 @@ impl Capture {
let stream =
pipewire_camera::Stream::start(&wanted, size, fps, feed, background).await?;
tracing::debug!(device = %wanted, "camera through PipeWire");
Ok(Self { backend: "pipewire", device: wanted, screen: None, stream: Some(stream) })
Ok(Self {
backend: "pipewire",
device: wanted,
screen: None,
_external: None,
stream: Some(stream),
})
}
#[cfg(not(all(target_os = "linux", feature = "pipewire")))]
{
@@ -195,7 +370,8 @@ impl Capture {
}
}
/// Where the frames come from (`"pipewire"`, `"portal"`, `"synthetic"`).
/// Where the frames come from (`"pipewire"`, `"portal"`, `"synthetic"`,
/// a provider's name).
pub fn backend(&self) -> &'static str {
#[cfg(all(target_os = "linux", feature = "pipewire"))]
if let Some(stream) = &self.stream {
@@ -455,6 +631,7 @@ mod v4l2 {
name: if name.is_empty() { path.to_string_lossy().into_owned() } else { name },
backend: "v4l2",
formats,
mirrored: true,
})
})
.collect()
@@ -933,6 +1110,74 @@ mod tests {
}
}
#[test]
fn camera_planes_are_borrowed_gathered_and_turned() {
// 4x2 luma 0..8, one 2x1 chroma row: U 10 11, V 20 21.
let y: Vec<u8> = (0..8).collect();
let planar = YuvPlanes {
width: 4,
height: 2,
y: &y,
y_stride: 4,
u: &[10, 11],
v: &[20, 21],
uv_stride: 2,
uv_step: 1,
nv12: None,
rotation: 0,
};
let mut scratch = Vec::new();
let frame = planar.frame(Duration::from_millis(3), &mut scratch).unwrap();
frame.validate().unwrap();
assert_eq!(frame.timestamp, Duration::from_millis(3));
let PixelsRef::I420 { y: luma, .. } = frame.pixels else { panic!("not I420") };
assert!(std::ptr::eq(luma.data, &y[..]), "upright planar is borrowed");
let uv = [10, 20, 11, 21];
let nv12 = YuvPlanes {
u: &uv[..3],
v: &uv[1..],
uv_stride: 4,
uv_step: 2,
nv12: Some(&uv),
..planar
};
let mut scratch = Vec::new();
let frame = nv12.frame(Duration::ZERO, &mut scratch).unwrap();
frame.validate().unwrap();
assert!(
matches!(frame.pixels, PixelsRef::Nv12 { uv: p, .. } if std::ptr::eq(p.data, &uv[..]))
);
// NV21 (V first) is gathered into I420.
let vu = [20, 10, 21, 11];
let nv21 = YuvPlanes { u: &vu[1..], v: &vu[..3], uv_stride: 4, uv_step: 2, ..planar };
let mut scratch = Vec::new();
let frame = nv21.frame(Duration::ZERO, &mut scratch).unwrap();
frame.validate().unwrap();
let PixelsRef::I420 { y: luma, u, v } = frame.pixels else { panic!("not I420") };
assert_eq!((luma.data, u.data, v.data), (&y[..], &[10, 11][..], &[20, 21][..]));
// Turned clockwise; the chroma turns with the luma.
for (rotation, size, luma) in [
(90, (2, 4), [4, 0, 5, 1, 6, 2, 7, 3]),
(180, (4, 2), [7, 6, 5, 4, 3, 2, 1, 0]),
(270, (2, 4), [3, 7, 2, 6, 1, 5, 0, 4]),
] {
let mut scratch = Vec::new();
let frame = YuvPlanes { rotation, ..nv21 }.frame(Duration::ZERO, &mut scratch).unwrap();
frame.validate().unwrap();
assert_eq!((frame.width, frame.height), size, "{rotation}");
let PixelsRef::I420 { y, u, .. } = frame.pixels else { panic!("not I420") };
assert_eq!(y.data, luma, "{rotation}");
let chroma: &[u8] = if rotation == 90 { &[10, 11] } else { &[11, 10] };
assert_eq!(u.data, chroma, "{rotation}");
}
let short = YuvPlanes { y: &y[..7], rotation: 90, ..planar };
assert!(short.frame(Duration::ZERO, &mut Vec::new()).is_err());
}
#[test]
fn four_character_codes() {
assert_eq!(Pixel::from_fourcc(u32::from_le_bytes(*b"YUYV")), Some(Pixel::Yuyv));
+33 -3
View File
@@ -1364,6 +1364,35 @@ impl App {
"remove" => {
self.studio_op(Op::Apply(studio::Command::RemoveSource { scene, source: id }));
}
// The next camera (a phone's front and back), mirrored as that
// camera is by default.
"next-camera" => {
let SourceKind::Camera { device, size, fps, .. } = source.kind.clone() else {
return;
};
let name = source.name.clone();
let cameras = if self.demo_ui { Vec::new() } else { camera::list() };
let real: Vec<_> = cameras.iter().filter(|c| c.backend != "synthetic").collect();
let at = real.iter().position(|c| c.id == device);
let next = at.map_or(real.first(), |i| real.get((i + 1) % real.len()));
let Some(next) = next.filter(|c| c.id != device) else {
self.set_status("There is no other camera.");
return;
};
let kind = SourceKind::Camera {
device: next.id.clone(),
size,
fps,
mirror: next.mirrored,
};
// A source named after its camera is named after the next.
let renamed = name.is_empty() || at.is_some_and(|i| real[i].name == name);
let name = renamed.then(|| next.name.clone());
self.studio_update(
id,
SourceChange { kind: Some(kind), name, ..Default::default() },
);
}
"bg-keep" | "bg-blur" => {
let background = if action == "bg-blur" {
Background::Blur { strength: 0.04 }
@@ -1435,6 +1464,7 @@ impl App {
camera::SYNTHETIC.to_owned(),
"Test pattern".to_owned(),
"1280×720".to_owned(),
true,
)]
} else {
camera::list()
@@ -1444,12 +1474,12 @@ impl App {
c.formats.iter().flat_map(|f| &f.sizes).max_by_key(|(w, h)| w * h);
let detail =
biggest.map_or(String::new(), |(w, h)| format!("up to {w}×{h}"));
(c.id, c.name, detail)
(c.id, c.name, detail, c.mirrored)
})
.collect()
};
for (device, name, detail) in cameras {
let kind = SourceKind::Camera { device, size: None, fps: None, mirror: true };
for (device, name, detail, mirror) in cameras {
let kind = SourceKind::Camera { device, size: None, fps: None, mirror };
picks.push((source(&name, kind), row(&name, detail, "camera")));
}
}
@@ -317,21 +317,25 @@ component SourceRow inherits Rectangle {
{ text: source.locked ? @tr("Unlock") : @tr("Lock"), icon: Icons.lock, enabled: true },
{ text: source.background == "keep" ? @tr("Blur background") : @tr("Background effect off"), icon: Icons.sparkles, enabled: source.kind == "camera", separator: true },
{ text: @tr("Background effect…"), icon: Icons.sliders-horizontal, enabled: source.kind == "camera" },
// A phone's front and back camera, or the next webcam.
{ text: @tr("Switch camera"), icon: Icons.video, enabled: source.kind == "camera" },
{ text: @tr("Bring forward"), icon: Icons.chevron-up, enabled: !source.front, separator: true },
{ text: @tr("Send backward"), icon: Icons.chevron-down, enabled: !source.back },
{ text: @tr("Rename…"), icon: Icons.pencil, enabled: true, separator: true },
{ text: @tr("Remove"), icon: Icons.trash-2, enabled: true, danger: true },
];
activated(i) => {
if i == 0 || i == 1 || i == 2 || i == 5 || i == 8 {
if i == 0 || i == 1 || i == 2 || i == 5 || i == 9 {
StudioNav.edit-source(source.id);
} else if i == 3 {
StudioBridge.source-action(source.id, "lock");
} else if i == 4 {
StudioBridge.source-action(source.id, source.background == "keep" ? "bg-blur" : "bg-keep");
} else if i == 6 {
StudioBridge.source-action(source.id, "up");
StudioBridge.source-action(source.id, "next-camera");
} else if i == 7 {
StudioBridge.source-action(source.id, "up");
} else if i == 8 {
StudioBridge.source-action(source.id, "down");
} else {
StudioBridge.source-action(source.id, "remove");