use std::sync::{Arc, Mutex, Weak};
use kessel_video::{
CameraInfo, Capabilities, CaptureConstraints, ContentHint, EndReason, EventRx, FrameSource,
Interruption, Permission, PickOptions, PixelFormat, ScreenKind, ScreenSelection,
ScreenSourceInfo, SourceEvent, SourceStats, VideoBackend, VideoError, Wake,
};
use tokio::sync::{Notify, oneshot};
pub const THUMBNAIL_MAX_WIDTH: u32 = 320;
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum CaptureError {
#[error("video_unsupported")]
VideoUnsupported,
#[error("camera_denied")]
CameraDenied,
#[error("camera_busy")]
CameraBusy,
#[error("camera_not_found")]
CameraNotFound,
#[error("camera_lost")]
CameraLost,
#[error("codec_unavailable")]
CodecUnavailable,
#[error("screen_unsupported")]
ScreenUnsupported,
#[error("screen_denied")]
ScreenDenied,
#[error("picker_cancelled")]
PickerCancelled,
#[error("screen_not_found")]
ScreenNotFound,
#[error("encoder_lost")]
EncoderLost,
#[error("capture_failed: {0}")]
Failed(VideoError),
}
impl CaptureError {
pub fn code(&self) -> &'static str {
match self {
CaptureError::VideoUnsupported => "video_unsupported",
CaptureError::CameraDenied => "camera_denied",
CaptureError::CameraBusy => "camera_busy",
CaptureError::CameraNotFound => "camera_not_found",
CaptureError::CameraLost => "camera_lost",
CaptureError::CodecUnavailable => "codec_unavailable",
CaptureError::ScreenUnsupported => "screen_unsupported",
CaptureError::ScreenDenied => "screen_denied",
CaptureError::PickerCancelled => "picker_cancelled",
CaptureError::ScreenNotFound => "screen_not_found",
CaptureError::EncoderLost => "encoder_lost",
CaptureError::Failed(_) => "capture_failed",
}
}
}
fn camera_error(e: VideoError) -> CaptureError {
match e {
VideoError::NoPermission => CaptureError::CameraDenied,
VideoError::DeviceBusy => CaptureError::CameraBusy,
VideoError::NotFound => CaptureError::CameraNotFound,
VideoError::DeviceLost => CaptureError::CameraLost,
VideoError::Unsupported(_) | VideoError::ShutDown => CaptureError::VideoUnsupported,
other => CaptureError::Failed(other),
}
}
fn screen_error(e: VideoError) -> CaptureError {
match e {
VideoError::NoPermission => CaptureError::ScreenDenied,
VideoError::NotFound | VideoError::DeviceLost => CaptureError::ScreenNotFound,
VideoError::Unsupported(_) | VideoError::ShutDown => CaptureError::ScreenUnsupported,
other => CaptureError::Failed(other),
}
}
fn pick_error(e: VideoError) -> CaptureError {
match e {
VideoError::NotFound => CaptureError::PickerCancelled,
other => screen_error(other),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum CaptureKind {
Camera,
Screen,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum CapturePause {
Hidden,
Background,
InUseByAnother,
Thermal,
Other,
Suspended,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum CaptureEnd {
Closed,
DeviceLost,
UserStopped,
SourceClosed,
Revoked,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum CaptureEvent {
Started {
width: u32,
height: u32,
fps: u32,
},
Paused(CapturePause),
Resumed,
Ended(CaptureEnd),
Error(VideoError),
}
impl CaptureEnd {
pub fn reason(self, kind: CaptureKind) -> &'static str {
let screen = kind == CaptureKind::Screen;
match self {
CaptureEnd::UserStopped => "user_stopped",
CaptureEnd::SourceClosed => "source_closed",
CaptureEnd::Revoked if screen => "screen_denied",
CaptureEnd::Revoked => "camera_denied",
CaptureEnd::DeviceLost if screen => "source_closed",
CaptureEnd::DeviceLost => "camera_lost",
CaptureEnd::Closed => "unpublished",
}
}
}
pub(crate) fn map_event(e: SourceEvent) -> Option<CaptureEvent> {
Some(match e {
SourceEvent::Started { width, height, fps } => CaptureEvent::Started { width, height, fps },
SourceEvent::Interrupted(i) => CaptureEvent::Paused(match i {
Interruption::Hidden => CapturePause::Hidden,
Interruption::Background => CapturePause::Background,
Interruption::InUseByAnother => CapturePause::InUseByAnother,
Interruption::Thermal => CapturePause::Thermal,
Interruption::Suspended => CapturePause::Suspended,
_ => CapturePause::Other,
}),
SourceEvent::Resumed => CaptureEvent::Resumed,
SourceEvent::Ended(r) => CaptureEvent::Ended(match r {
EndReason::Closed => CaptureEnd::Closed,
EndReason::DeviceLost => CaptureEnd::DeviceLost,
EndReason::UserStopped => CaptureEnd::UserStopped,
EndReason::SourceClosed => CaptureEnd::SourceClosed,
EndReason::Revoked => CaptureEnd::Revoked,
_ => CaptureEnd::DeviceLost,
}),
SourceEvent::Error(e) => CaptureEvent::Error(e),
_ => return None,
})
}
fn notify_wake(n: &Arc<Notify>) -> Wake {
let n = Arc::clone(n);
Arc::new(move || n.notify_one())
}
#[derive(Default)]
struct WakeHub {
ready: Arc<Notify>,
chained: Mutex<Option<Wake>>,
}
impl WakeHub {
fn wake(self: &Arc<WakeHub>) -> Wake {
let hub = Arc::clone(self);
Arc::new(move || {
hub.ready.notify_one();
let chained = hub
.chained
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone();
if let Some(w) = chained {
w();
}
})
}
}
pub struct Capture {
kind: CaptureKind,
source: Box<dyn FrameSource>,
hub: Arc<WakeHub>,
constraints: CaptureConstraints,
device: Option<String>,
ended: Option<CaptureEnd>,
paused: Option<CapturePause>,
#[cfg(any(sew_preview_events, test))]
_preview: Option<super::camera_tap::PreviewLease>,
}
impl std::fmt::Debug for Capture {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Capture")
.field("kind", &self.kind)
.field("device", &self.device)
.field("ended", &self.ended)
.field("paused", &self.paused)
.finish_non_exhaustive()
}
}
impl Capture {
fn new(
kind: CaptureKind,
source: Box<dyn FrameSource>,
hub: Arc<WakeHub>,
constraints: CaptureConstraints,
device: Option<String>,
) -> Capture {
Capture {
kind,
source,
hub,
constraints,
device,
ended: None,
paused: None,
#[cfg(any(sew_preview_events, test))]
_preview: None,
}
}
pub fn kind(&self) -> CaptureKind {
self.kind
}
pub fn content_hint(&self) -> ContentHint {
match self.kind {
CaptureKind::Screen => ContentHint::Screen,
_ => ContentHint::Camera,
}
}
pub fn device(&self) -> Option<&str> {
self.device.as_deref()
}
pub fn constraints(&self) -> CaptureConstraints {
self.constraints
}
pub fn set_constraints(&mut self, c: CaptureConstraints) -> Result<(), CaptureError> {
let r = self.source.set_constraints(c);
r.map_err(|e| match self.kind {
CaptureKind::Camera => camera_error(e),
_ => screen_error(e),
})?;
self.constraints = c;
Ok(())
}
pub fn set_paused(&mut self, paused: bool) {
self.source.set_paused(paused);
}
pub fn try_frame(&mut self) -> Option<kessel_video::VideoFrame> {
if self.ended.is_some() {
return None;
}
self.source.try_recv()
}
pub fn try_event(&mut self) -> Option<CaptureEvent> {
loop {
let e = map_event(self.source.try_event()?);
match &e {
Some(CaptureEvent::Ended(end)) => self.ended = Some(*end),
Some(CaptureEvent::Paused(p)) => self.paused = Some(*p),
Some(CaptureEvent::Resumed) => self.paused = None,
_ => {}
}
if e.is_some() {
return e;
}
}
}
pub async fn ready(&self) {
self.hub.ready.notified().await;
}
pub fn wake(&self) -> Wake {
notify_wake(&self.hub.ready)
}
pub fn notifier(&self) -> Arc<Notify> {
Arc::clone(&self.hub.ready)
}
pub(crate) fn chain_wake(&self, wake: Wake) {
*self
.hub
.chained
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) = Some(wake);
self.hub.wake()();
}
pub fn ended(&self) -> Option<CaptureEnd> {
self.ended
}
pub fn paused(&self) -> Option<CapturePause> {
self.paused
}
pub fn stats(&self) -> SourceStats {
self.source.stats()
}
}
impl FrameSource for Capture {
fn try_recv(&mut self) -> Option<kessel_video::VideoFrame> {
self.source.try_recv()
}
fn try_event(&mut self) -> Option<SourceEvent> {
self.source.try_event()
}
fn set_constraints(&mut self, c: CaptureConstraints) -> Result<(), VideoError> {
self.source.set_constraints(c)?;
self.constraints = c;
Ok(())
}
fn set_paused(&mut self, paused: bool) {
self.source.set_paused(paused);
}
fn stats(&self) -> SourceStats {
self.source.stats()
}
#[cfg(sew_apple_preview)]
fn apple_preview(&self) -> Option<kessel_video::ApplePreview> {
self.source.apple_preview()
}
}
#[derive(Debug)]
pub struct CameraSource(Capture);
#[derive(Debug)]
pub struct ScreenSource(Capture);
macro_rules! capture_handle {
($t:ty) => {
impl std::ops::Deref for $t {
type Target = Capture;
fn deref(&self) -> &Capture {
&self.0
}
}
impl std::ops::DerefMut for $t {
fn deref_mut(&mut self) -> &mut Capture {
&mut self.0
}
}
impl $t {
pub fn into_capture(self) -> Capture {
self.0
}
}
};
}
capture_handle!(CameraSource);
capture_handle!(ScreenSource);
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ScreenPick {
Listed(String),
System {
parent_window: Option<u64>,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ScreenChoice {
pub id: String,
pub kind: ScreenKind,
pub title: String,
pub app: Option<String>,
pub width: u32,
pub height: u32,
pub thumbnail_png: Option<Vec<u8>>,
}
pub fn screen_constraints(max_width: u32, max_height: u32, fps: u32) -> CaptureConstraints {
let mut c = CaptureConstraints::new(max_width, max_height, fps);
c.cursor = true;
c.exclude_own_windows = true;
c
}
#[derive(Clone)]
pub struct VideoCapture {
backend: Arc<dyn VideoBackend>,
preview: Arc<Mutex<Option<Weak<super::preview::Shared>>>>,
taps: super::camera_tap::CameraTaps,
#[cfg(all(not(sew_apple_preview), any(test, feature = "testing")))]
fake_previews: Arc<Mutex<u64>>,
}
impl std::fmt::Debug for VideoCapture {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("VideoCapture")
.field("backend", &self.backend.capabilities().backend)
.finish()
}
}
async fn blocking<T: Send + 'static>(
f: impl FnOnce() -> Result<T, VideoError> + Send + 'static,
) -> Result<T, VideoError> {
tokio::task::spawn_blocking(f)
.await
.map_err(|e| VideoError::os(0, format!("capture task: {e}")))?
}
impl VideoCapture {
pub fn new(backend: Arc<dyn VideoBackend>) -> VideoCapture {
VideoCapture {
backend,
preview: Arc::new(Mutex::new(None)),
taps: super::camera_tap::CameraTaps::default(),
#[cfg(all(not(sew_apple_preview), any(test, feature = "testing")))]
fake_previews: Arc::default(),
}
}
#[cfg(all(test, not(sew_apple_preview)))]
pub(crate) fn fake_previews(&self, from: u64) {
*self
.fake_previews
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) = from;
}
#[cfg(sew_apple_preview)]
fn preview_of(
&self,
source: &dyn FrameSource,
_device: Option<&str>,
) -> (
Option<super::camera_tap::PreviewHandle>,
kessel_video::Facing,
) {
match source.apple_preview() {
Some(p) => {
let facing = p.facing();
(Some(p), facing)
}
None => (None, kessel_video::Facing::Unknown),
}
}
#[cfg(all(not(sew_apple_preview), any(test, feature = "testing")))]
fn preview_of(
&self,
_source: &dyn FrameSource,
device: Option<&str>,
) -> (
Option<super::camera_tap::PreviewHandle>,
kessel_video::Facing,
) {
let next = {
let mut n = self
.fake_previews
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let this = *n;
if this != 0 {
*n += 1;
}
(this != 0).then_some(this)
};
match next {
Some(n) => (
Some(super::camera_tap::FakePreview(n)),
self.camera_facing(device),
),
None => (None, kessel_video::Facing::Unknown),
}
}
pub fn camera_tap(&self) -> super::CameraTap {
self.taps.open()
}
pub(crate) fn camera_taps(&self) -> &super::camera_tap::CameraTaps {
&self.taps
}
pub fn stop_preview(&self) {
let running = self
.preview
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.take()
.and_then(|w| w.upgrade());
if let Some(p) = running {
p.stop();
}
}
pub fn preview_running(&self) -> bool {
self.preview
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.as_ref()
.and_then(Weak::upgrade)
.is_some_and(|p| p.running())
}
pub(crate) fn set_preview(&self, p: &Arc<super::preview::Shared>) {
*self
.preview
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) = Some(Arc::downgrade(p));
}
pub fn null() -> VideoCapture {
VideoCapture::new(kessel_video::null())
}
pub fn backend(&self) -> &Arc<dyn VideoBackend> {
&self.backend
}
pub fn capabilities(&self) -> Capabilities {
self.backend.capabilities()
}
pub fn camera_facing(&self, device: Option<&str>) -> kessel_video::Facing {
let cams = self.cameras();
match device {
Some(id) => cams.iter().find(|c| c.id == id),
None => cams.iter().find(|c| c.is_default).or(cams.first()),
}
.map_or(kessel_video::Facing::Unknown, |c| c.facing)
}
pub fn cameras(&self) -> Vec<CameraInfo> {
self.backend.cameras()
}
pub fn camera_permission(&self) -> Permission {
self.backend.camera_permission()
}
pub fn screen_permission(&self) -> Permission {
self.backend.screen_permission()
}
pub fn events(&self) -> EventRx {
self.backend.subscribe()
}
pub async fn request_camera_permission(&self) -> Permission {
let (tx, rx) = oneshot::channel();
self.backend.request_camera_permission(Box::new(move |p| {
let _ = tx.send(p);
}));
rx.await.unwrap_or(Permission::Denied)
}
pub async fn request_screen_permission(&self) -> Permission {
let (tx, rx) = oneshot::channel();
self.backend.request_screen_permission(Box::new(move |p| {
let _ = tx.send(p);
}));
rx.await.unwrap_or(Permission::Denied)
}
pub(crate) async fn camera_allowed(&self) -> Result<(), CaptureError> {
let p = match self.camera_permission() {
Permission::NotDetermined => self.request_camera_permission().await,
p => p,
};
match p {
Permission::Granted => Ok(()),
_ => Err(CaptureError::CameraDenied),
}
}
async fn screen_allowed(&self) -> Result<(), CaptureError> {
let p = match self.screen_permission() {
Permission::NotDetermined => self.request_screen_permission().await,
p => p,
};
match p {
Permission::Granted => Ok(()),
_ => Err(CaptureError::ScreenDenied),
}
}
pub async fn open_camera(
&self,
device: Option<&str>,
constraints: CaptureConstraints,
) -> Result<CameraSource, CaptureError> {
if !self.capabilities().camera {
return Err(CaptureError::VideoUnsupported);
}
self.camera_allowed().await?;
self.stop_preview();
let hub = Arc::new(WakeHub::default());
let wake = hub.wake();
let backend = Arc::clone(&self.backend);
let id = device.map(str::to_owned);
let asked = id.clone();
let source = blocking(move || backend.open_camera(asked.as_deref(), constraints, wake))
.await
.map_err(camera_error)?;
#[cfg(any(sew_preview_events, test))]
let lease = {
let (preview, facing) = self.preview_of(&*source, device);
self.taps.preview_open(preview, facing)
};
let capture = Capture::new(CaptureKind::Camera, source, hub, constraints, id);
#[cfg(any(sew_preview_events, test))]
let capture = Capture {
_preview: Some(lease),
..capture
};
Ok(CameraSource(capture))
}
pub async fn screen_sources(&self) -> Result<Vec<ScreenChoice>, CaptureError> {
let screen = self.capabilities().screen;
if !screen.supported {
return Err(CaptureError::ScreenUnsupported);
}
if !screen.list {
return Ok(Vec::new());
}
let backend = Arc::clone(&self.backend);
let list = blocking(move || {
let list = backend.screen_sources()?;
Ok(list.iter().map(choice).collect::<Vec<_>>())
})
.await
.map_err(screen_error)?;
Ok(list)
}
async fn pick(&self, opts: PickOptions) -> Result<ScreenSelection, CaptureError> {
let (tx, rx) = oneshot::channel();
self.backend.pick_screen(
opts,
Box::new(move |r| {
let _ = tx.send(r);
}),
);
match rx.await {
Ok(r) => r.map_err(pick_error),
Err(_) => Err(CaptureError::ScreenUnsupported),
}
}
pub async fn open_screen(
&self,
pick: ScreenPick,
constraints: CaptureConstraints,
) -> Result<ScreenSource, CaptureError> {
let screen = self.capabilities().screen;
if !screen.supported {
return Err(CaptureError::ScreenUnsupported);
}
self.screen_allowed().await?;
let (selection, device) = match pick {
ScreenPick::Listed(id) => {
if !screen.list {
return Err(CaptureError::ScreenNotFound);
}
(ScreenSelection::Listed(id.clone()), Some(id))
}
ScreenPick::System { parent_window } => {
if !screen.system_picker {
return Err(CaptureError::ScreenUnsupported);
}
let mut opts = PickOptions::new();
opts.displays = true;
opts.windows = screen.windows;
if let Some(h) = parent_window {
opts = opts.with_parent_window(h);
}
(self.pick(opts).await?, None)
}
};
let mut c = constraints;
c.exclude_own_windows &= screen.exclude_own_windows;
let hub = Arc::new(WakeHub::default());
let wake = hub.wake();
let backend = Arc::clone(&self.backend);
let source = blocking(move || backend.open_screen(&selection, c, wake))
.await
.map_err(screen_error)?;
Ok(ScreenSource(Capture::new(
CaptureKind::Screen,
source,
hub,
c,
device,
)))
}
}
fn choice(s: &ScreenSourceInfo) -> ScreenChoice {
ScreenChoice {
id: s.id.clone(),
kind: s.kind,
title: s.title.clone(),
app: s.app.clone(),
width: s.width,
height: s.height,
thumbnail_png: thumbnail_png(s),
}
}
fn thumbnail_size(s: &ScreenSourceInfo, p: &kessel_video::Planes) -> Option<(u32, u32)> {
let (w, h) = s.thumbnail_size()?;
p.validate(w, h).ok()?;
Some((w, h))
}
pub fn thumbnail_png(s: &ScreenSourceInfo) -> Option<Vec<u8>> {
let p = s.thumbnail.as_ref()?;
let bgra = match p.format {
PixelFormat::Rgba => false,
PixelFormat::Bgra => true,
_ => return None,
};
let (w, h) = thumbnail_size(s, p)?;
let (tw, th) = if w > THUMBNAIL_MAX_WIDTH {
kessel_video::fit_within(w, h, THUMBNAIL_MAX_WIDTH, h)
} else {
(w, h)
};
let rgba = shrink_rgba(p, (w, h), (tw, th), bgra);
encode_png(tw, th, &rgba)
}
fn shrink_rgba(p: &kessel_video::Planes, from: (u32, u32), to: (u32, u32), bgra: bool) -> Vec<u8> {
let (w, h) = (from.0 as usize, from.1 as usize);
let (tw, th) = (to.0 as usize, to.1 as usize);
let (stride, off) = (p.strides[0] as usize, p.offsets[0]);
let mut out = Vec::with_capacity(tw * th * 4);
for ty in 0..th {
let (y0, y1) = (ty * h / th, ((ty + 1) * h / th).max(ty * h / th + 1).min(h));
for tx in 0..tw {
let (x0, x1) = (tx * w / tw, ((tx + 1) * w / tw).max(tx * w / tw + 1).min(w));
let mut sum = [0u64; 4];
for y in y0..y1 {
let row = &p.data[off + y * stride..];
for x in x0..x1 {
for (c, v) in sum.iter_mut().enumerate() {
*v += u64::from(row[x * 4 + c]);
}
}
}
let n = ((y1 - y0) * (x1 - x0)) as u64;
let avg = sum.map(|v| u8::try_from((v + n / 2) / n).unwrap_or(u8::MAX));
let px = if bgra {
[avg[2], avg[1], avg[0], avg[3]]
} else {
avg
};
out.extend_from_slice(&px);
}
}
out
}
fn encode_png(width: u32, height: u32, rgba: &[u8]) -> Option<Vec<u8>> {
let mut out = Vec::new();
let mut enc = png::Encoder::new(&mut out, width, height);
enc.set_color(png::ColorType::Rgba);
enc.set_depth(png::BitDepth::Eight);
let mut w = enc.write_header().ok()?;
w.write_image_data(rgba).ok()?;
w.finish().ok()?;
Some(out)
}
#[cfg(test)]
mod tests;