1use std::sync::{Arc, Mutex, Weak};
16
17use kessel_video::{
18 CameraInfo, Capabilities, CaptureConstraints, ContentHint, EndReason, EventRx, FrameSource,
19 Interruption, Permission, PickOptions, PixelFormat, ScreenKind, ScreenSelection,
20 ScreenSourceInfo, SourceEvent, SourceStats, VideoBackend, VideoError, Wake,
21};
22use tokio::sync::{Notify, oneshot};
23
24pub const THUMBNAIL_MAX_WIDTH: u32 = 320;
26
27#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
29#[non_exhaustive]
30pub enum CaptureError {
31 #[error("video_unsupported")]
33 VideoUnsupported,
34 #[error("camera_denied")]
36 CameraDenied,
37 #[error("camera_busy")]
39 CameraBusy,
40 #[error("camera_not_found")]
42 CameraNotFound,
43 #[error("camera_lost")]
45 CameraLost,
46 #[error("codec_unavailable")]
48 CodecUnavailable,
49 #[error("screen_unsupported")]
52 ScreenUnsupported,
53 #[error("screen_denied")]
55 ScreenDenied,
56 #[error("picker_cancelled")]
58 PickerCancelled,
59 #[error("screen_not_found")]
61 ScreenNotFound,
62 #[error("encoder_lost")]
64 EncoderLost,
65 #[error("capture_failed: {0}")]
67 Failed(VideoError),
68}
69
70impl CaptureError {
71 pub fn code(&self) -> &'static str {
73 match self {
74 CaptureError::VideoUnsupported => "video_unsupported",
75 CaptureError::CameraDenied => "camera_denied",
76 CaptureError::CameraBusy => "camera_busy",
77 CaptureError::CameraNotFound => "camera_not_found",
78 CaptureError::CameraLost => "camera_lost",
79 CaptureError::CodecUnavailable => "codec_unavailable",
80 CaptureError::ScreenUnsupported => "screen_unsupported",
81 CaptureError::ScreenDenied => "screen_denied",
82 CaptureError::PickerCancelled => "picker_cancelled",
83 CaptureError::ScreenNotFound => "screen_not_found",
84 CaptureError::EncoderLost => "encoder_lost",
85 CaptureError::Failed(_) => "capture_failed",
86 }
87 }
88}
89
90fn camera_error(e: VideoError) -> CaptureError {
91 match e {
92 VideoError::NoPermission => CaptureError::CameraDenied,
93 VideoError::DeviceBusy => CaptureError::CameraBusy,
94 VideoError::NotFound => CaptureError::CameraNotFound,
95 VideoError::DeviceLost => CaptureError::CameraLost,
96 VideoError::Unsupported(_) | VideoError::ShutDown => CaptureError::VideoUnsupported,
97 other => CaptureError::Failed(other),
98 }
99}
100
101fn screen_error(e: VideoError) -> CaptureError {
102 match e {
103 VideoError::NoPermission => CaptureError::ScreenDenied,
104 VideoError::NotFound | VideoError::DeviceLost => CaptureError::ScreenNotFound,
105 VideoError::Unsupported(_) | VideoError::ShutDown => CaptureError::ScreenUnsupported,
106 other => CaptureError::Failed(other),
107 }
108}
109
110fn pick_error(e: VideoError) -> CaptureError {
111 match e {
112 VideoError::NotFound => CaptureError::PickerCancelled,
114 other => screen_error(other),
115 }
116}
117
118#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
122#[non_exhaustive]
123pub enum CaptureKind {
124 Camera,
126 Screen,
128}
129
130#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
132#[non_exhaustive]
133pub enum CapturePause {
134 Hidden,
136 Background,
138 InUseByAnother,
140 Thermal,
142 Other,
144 Suspended,
148}
149
150#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
152#[non_exhaustive]
153pub enum CaptureEnd {
154 Closed,
156 DeviceLost,
158 UserStopped,
160 SourceClosed,
162 Revoked,
164}
165
166#[derive(Debug, Clone, PartialEq, Eq)]
168#[non_exhaustive]
169pub enum CaptureEvent {
170 Started {
172 width: u32,
174 height: u32,
176 fps: u32,
178 },
179 Paused(CapturePause),
181 Resumed,
183 Ended(CaptureEnd),
185 Error(VideoError),
187}
188
189impl CaptureEnd {
190 pub fn reason(self, kind: CaptureKind) -> &'static str {
194 let screen = kind == CaptureKind::Screen;
195 match self {
196 CaptureEnd::UserStopped => "user_stopped",
197 CaptureEnd::SourceClosed => "source_closed",
198 CaptureEnd::Revoked if screen => "screen_denied",
199 CaptureEnd::Revoked => "camera_denied",
200 CaptureEnd::DeviceLost if screen => "source_closed",
201 CaptureEnd::DeviceLost => "camera_lost",
202 CaptureEnd::Closed => "unpublished",
203 }
204 }
205}
206
207pub(crate) fn map_event(e: SourceEvent) -> Option<CaptureEvent> {
208 Some(match e {
209 SourceEvent::Started { width, height, fps } => CaptureEvent::Started { width, height, fps },
210 SourceEvent::Interrupted(i) => CaptureEvent::Paused(match i {
211 Interruption::Hidden => CapturePause::Hidden,
212 Interruption::Background => CapturePause::Background,
213 Interruption::InUseByAnother => CapturePause::InUseByAnother,
214 Interruption::Thermal => CapturePause::Thermal,
215 Interruption::Suspended => CapturePause::Suspended,
216 _ => CapturePause::Other,
217 }),
218 SourceEvent::Resumed => CaptureEvent::Resumed,
219 SourceEvent::Ended(r) => CaptureEvent::Ended(match r {
220 EndReason::Closed => CaptureEnd::Closed,
221 EndReason::DeviceLost => CaptureEnd::DeviceLost,
222 EndReason::UserStopped => CaptureEnd::UserStopped,
223 EndReason::SourceClosed => CaptureEnd::SourceClosed,
224 EndReason::Revoked => CaptureEnd::Revoked,
225 _ => CaptureEnd::DeviceLost,
226 }),
227 SourceEvent::Error(e) => CaptureEvent::Error(e),
228 _ => return None,
229 })
230}
231
232fn notify_wake(n: &Arc<Notify>) -> Wake {
234 let n = Arc::clone(n);
235 Arc::new(move || n.notify_one())
236}
237
238#[derive(Default)]
241struct WakeHub {
242 ready: Arc<Notify>,
243 chained: Mutex<Option<Wake>>,
244}
245
246impl WakeHub {
247 fn wake(self: &Arc<WakeHub>) -> Wake {
248 let hub = Arc::clone(self);
249 Arc::new(move || {
250 hub.ready.notify_one();
251 let chained = hub
252 .chained
253 .lock()
254 .unwrap_or_else(std::sync::PoisonError::into_inner)
255 .clone();
256 if let Some(w) = chained {
257 w();
258 }
259 })
260 }
261}
262
263pub struct Capture {
267 kind: CaptureKind,
268 source: Box<dyn FrameSource>,
269 hub: Arc<WakeHub>,
270 constraints: CaptureConstraints,
271 device: Option<String>,
272 ended: Option<CaptureEnd>,
273 paused: Option<CapturePause>,
274}
275
276impl std::fmt::Debug for Capture {
277 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
278 f.debug_struct("Capture")
279 .field("kind", &self.kind)
280 .field("device", &self.device)
281 .field("ended", &self.ended)
282 .field("paused", &self.paused)
283 .finish_non_exhaustive()
284 }
285}
286
287impl Capture {
288 fn new(
289 kind: CaptureKind,
290 source: Box<dyn FrameSource>,
291 hub: Arc<WakeHub>,
292 constraints: CaptureConstraints,
293 device: Option<String>,
294 ) -> Capture {
295 Capture {
296 kind,
297 source,
298 hub,
299 constraints,
300 device,
301 ended: None,
302 paused: None,
303 }
304 }
305
306 pub fn kind(&self) -> CaptureKind {
308 self.kind
309 }
310
311 pub fn content_hint(&self) -> ContentHint {
314 match self.kind {
315 CaptureKind::Screen => ContentHint::Screen,
316 _ => ContentHint::Camera,
317 }
318 }
319
320 pub fn device(&self) -> Option<&str> {
323 self.device.as_deref()
324 }
325
326 pub fn constraints(&self) -> CaptureConstraints {
328 self.constraints
329 }
330
331 pub fn set_constraints(&mut self, c: CaptureConstraints) -> Result<(), CaptureError> {
334 let r = self.source.set_constraints(c);
335 r.map_err(|e| match self.kind {
336 CaptureKind::Camera => camera_error(e),
337 _ => screen_error(e),
338 })?;
339 self.constraints = c;
340 Ok(())
341 }
342
343 pub fn set_paused(&mut self, paused: bool) {
346 self.source.set_paused(paused);
347 }
348
349 pub fn try_frame(&mut self) -> Option<kessel_video::VideoFrame> {
352 if self.ended.is_some() {
353 return None;
354 }
355 self.source.try_recv()
356 }
357
358 pub fn try_event(&mut self) -> Option<CaptureEvent> {
360 loop {
361 let e = map_event(self.source.try_event()?);
362 match &e {
363 Some(CaptureEvent::Ended(end)) => self.ended = Some(*end),
364 Some(CaptureEvent::Paused(p)) => self.paused = Some(*p),
365 Some(CaptureEvent::Resumed) => self.paused = None,
366 _ => {}
367 }
368 if e.is_some() {
369 return e;
370 }
371 }
372 }
373
374 pub async fn ready(&self) {
378 self.hub.ready.notified().await;
379 }
380
381 pub fn wake(&self) -> Wake {
384 notify_wake(&self.hub.ready)
385 }
386
387 pub fn notifier(&self) -> Arc<Notify> {
389 Arc::clone(&self.hub.ready)
390 }
391
392 pub(crate) fn chain_wake(&self, wake: Wake) {
395 *self
396 .hub
397 .chained
398 .lock()
399 .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(wake);
400 self.hub.wake()();
402 }
403
404 pub fn ended(&self) -> Option<CaptureEnd> {
406 self.ended
407 }
408
409 pub fn paused(&self) -> Option<CapturePause> {
411 self.paused
412 }
413
414 pub fn stats(&self) -> SourceStats {
416 self.source.stats()
417 }
418}
419
420impl FrameSource for Capture {
424 fn try_recv(&mut self) -> Option<kessel_video::VideoFrame> {
425 self.source.try_recv()
426 }
427
428 fn try_event(&mut self) -> Option<SourceEvent> {
429 self.source.try_event()
430 }
431
432 fn set_constraints(&mut self, c: CaptureConstraints) -> Result<(), VideoError> {
433 self.source.set_constraints(c)?;
434 self.constraints = c;
435 Ok(())
436 }
437
438 fn set_paused(&mut self, paused: bool) {
439 self.source.set_paused(paused);
440 }
441
442 fn stats(&self) -> SourceStats {
443 self.source.stats()
444 }
445}
446
447#[derive(Debug)]
449pub struct CameraSource(Capture);
450
451#[derive(Debug)]
454pub struct ScreenSource(Capture);
455
456macro_rules! capture_handle {
457 ($t:ty) => {
458 impl std::ops::Deref for $t {
459 type Target = Capture;
460 fn deref(&self) -> &Capture {
461 &self.0
462 }
463 }
464
465 impl std::ops::DerefMut for $t {
466 fn deref_mut(&mut self) -> &mut Capture {
467 &mut self.0
468 }
469 }
470
471 impl $t {
472 pub fn into_capture(self) -> Capture {
474 self.0
475 }
476 }
477 };
478}
479
480capture_handle!(CameraSource);
481capture_handle!(ScreenSource);
482
483#[derive(Debug, Clone, PartialEq, Eq)]
485#[non_exhaustive]
486pub enum ScreenPick {
487 Listed(String),
489 System {
492 parent_window: Option<u64>,
494 },
495}
496
497#[derive(Debug, Clone, PartialEq, Eq)]
499#[non_exhaustive]
500pub struct ScreenChoice {
501 pub id: String,
503 pub kind: ScreenKind,
505 pub title: String,
507 pub app: Option<String>,
509 pub width: u32,
511 pub height: u32,
513 pub thumbnail_png: Option<Vec<u8>>,
515}
516
517pub fn screen_constraints(max_width: u32, max_height: u32, fps: u32) -> CaptureConstraints {
521 let mut c = CaptureConstraints::new(max_width, max_height, fps);
522 c.cursor = true;
523 c.exclude_own_windows = true;
524 c
525}
526
527#[derive(Clone)]
533pub struct VideoCapture {
534 backend: Arc<dyn VideoBackend>,
535 preview: Arc<Mutex<Option<Weak<super::preview::Shared>>>>,
537 taps: super::camera_tap::CameraTaps,
539}
540
541impl std::fmt::Debug for VideoCapture {
542 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
543 f.debug_struct("VideoCapture")
544 .field("backend", &self.backend.capabilities().backend)
545 .finish()
546 }
547}
548
549async fn blocking<T: Send + 'static>(
551 f: impl FnOnce() -> Result<T, VideoError> + Send + 'static,
552) -> Result<T, VideoError> {
553 tokio::task::spawn_blocking(f)
554 .await
555 .map_err(|e| VideoError::os(0, format!("capture task: {e}")))?
556}
557
558impl VideoCapture {
559 pub fn new(backend: Arc<dyn VideoBackend>) -> VideoCapture {
561 VideoCapture {
562 backend,
563 preview: Arc::new(Mutex::new(None)),
564 taps: super::camera_tap::CameraTaps::default(),
565 }
566 }
567
568 pub fn camera_tap(&self) -> super::CameraTap {
574 self.taps.open()
575 }
576
577 pub(crate) fn camera_taps(&self) -> &super::camera_tap::CameraTaps {
579 &self.taps
580 }
581
582 pub fn stop_preview(&self) {
584 let running = self
585 .preview
586 .lock()
587 .unwrap_or_else(std::sync::PoisonError::into_inner)
588 .take()
589 .and_then(|w| w.upgrade());
590 if let Some(p) = running {
591 p.stop();
592 }
593 }
594
595 pub fn preview_running(&self) -> bool {
597 self.preview
598 .lock()
599 .unwrap_or_else(std::sync::PoisonError::into_inner)
600 .as_ref()
601 .and_then(Weak::upgrade)
602 .is_some_and(|p| p.running())
603 }
604
605 pub(crate) fn set_preview(&self, p: &Arc<super::preview::Shared>) {
607 *self
608 .preview
609 .lock()
610 .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(Arc::downgrade(p));
611 }
612
613 pub fn null() -> VideoCapture {
615 VideoCapture::new(kessel_video::null())
616 }
617
618 pub fn backend(&self) -> &Arc<dyn VideoBackend> {
620 &self.backend
621 }
622
623 pub fn capabilities(&self) -> Capabilities {
625 self.backend.capabilities()
626 }
627
628 pub fn camera_facing(&self, device: Option<&str>) -> kessel_video::Facing {
631 let cams = self.cameras();
632 match device {
633 Some(id) => cams.iter().find(|c| c.id == id),
634 None => cams.iter().find(|c| c.is_default).or(cams.first()),
635 }
636 .map_or(kessel_video::Facing::Unknown, |c| c.facing)
637 }
638
639 pub fn cameras(&self) -> Vec<CameraInfo> {
641 self.backend.cameras()
642 }
643
644 pub fn camera_permission(&self) -> Permission {
646 self.backend.camera_permission()
647 }
648
649 pub fn screen_permission(&self) -> Permission {
651 self.backend.screen_permission()
652 }
653
654 pub fn events(&self) -> EventRx {
656 self.backend.subscribe()
657 }
658
659 pub async fn request_camera_permission(&self) -> Permission {
661 let (tx, rx) = oneshot::channel();
662 self.backend.request_camera_permission(Box::new(move |p| {
663 let _ = tx.send(p);
664 }));
665 rx.await.unwrap_or(Permission::Denied)
666 }
667
668 pub async fn request_screen_permission(&self) -> Permission {
670 let (tx, rx) = oneshot::channel();
671 self.backend.request_screen_permission(Box::new(move |p| {
672 let _ = tx.send(p);
673 }));
674 rx.await.unwrap_or(Permission::Denied)
675 }
676
677 pub(crate) async fn camera_allowed(&self) -> Result<(), CaptureError> {
678 let p = match self.camera_permission() {
679 Permission::NotDetermined => self.request_camera_permission().await,
680 p => p,
681 };
682 match p {
683 Permission::Granted => Ok(()),
684 _ => Err(CaptureError::CameraDenied),
685 }
686 }
687
688 async fn screen_allowed(&self) -> Result<(), CaptureError> {
689 let p = match self.screen_permission() {
690 Permission::NotDetermined => self.request_screen_permission().await,
691 p => p,
692 };
693 match p {
694 Permission::Granted => Ok(()),
695 _ => Err(CaptureError::ScreenDenied),
696 }
697 }
698
699 pub async fn open_camera(
704 &self,
705 device: Option<&str>,
706 constraints: CaptureConstraints,
707 ) -> Result<CameraSource, CaptureError> {
708 if !self.capabilities().camera {
709 return Err(CaptureError::VideoUnsupported);
710 }
711 self.camera_allowed().await?;
712 self.stop_preview();
713 let hub = Arc::new(WakeHub::default());
714 let wake = hub.wake();
715 let backend = Arc::clone(&self.backend);
716 let id = device.map(str::to_owned);
717 let asked = id.clone();
718 let source = blocking(move || backend.open_camera(asked.as_deref(), constraints, wake))
719 .await
720 .map_err(camera_error)?;
721 Ok(CameraSource(Capture::new(
722 CaptureKind::Camera,
723 source,
724 hub,
725 constraints,
726 id,
727 )))
728 }
729
730 pub async fn screen_sources(&self) -> Result<Vec<ScreenChoice>, CaptureError> {
733 let screen = self.capabilities().screen;
734 if !screen.supported {
735 return Err(CaptureError::ScreenUnsupported);
736 }
737 if !screen.list {
738 return Ok(Vec::new());
739 }
740 let backend = Arc::clone(&self.backend);
741 let list = blocking(move || {
742 let list = backend.screen_sources()?;
743 Ok(list.iter().map(choice).collect::<Vec<_>>())
744 })
745 .await
746 .map_err(screen_error)?;
747 Ok(list)
748 }
749
750 async fn pick(&self, opts: PickOptions) -> Result<ScreenSelection, CaptureError> {
752 let (tx, rx) = oneshot::channel();
753 self.backend.pick_screen(
754 opts,
755 Box::new(move |r| {
756 let _ = tx.send(r);
757 }),
758 );
759 match rx.await {
760 Ok(r) => r.map_err(pick_error),
761 Err(_) => Err(CaptureError::ScreenUnsupported),
762 }
763 }
764
765 pub async fn open_screen(
771 &self,
772 pick: ScreenPick,
773 constraints: CaptureConstraints,
774 ) -> Result<ScreenSource, CaptureError> {
775 let screen = self.capabilities().screen;
776 if !screen.supported {
777 return Err(CaptureError::ScreenUnsupported);
778 }
779 self.screen_allowed().await?;
780 let (selection, device) = match pick {
781 ScreenPick::Listed(id) => {
782 if !screen.list {
783 return Err(CaptureError::ScreenNotFound);
784 }
785 (ScreenSelection::Listed(id.clone()), Some(id))
786 }
787 ScreenPick::System { parent_window } => {
788 if !screen.system_picker {
789 return Err(CaptureError::ScreenUnsupported);
790 }
791 let mut opts = PickOptions::new();
792 opts.displays = true;
793 opts.windows = screen.windows;
794 if let Some(h) = parent_window {
795 opts = opts.with_parent_window(h);
796 }
797 (self.pick(opts).await?, None)
798 }
799 };
800 let mut c = constraints;
801 c.exclude_own_windows &= screen.exclude_own_windows;
802 let hub = Arc::new(WakeHub::default());
803 let wake = hub.wake();
804 let backend = Arc::clone(&self.backend);
805 let source = blocking(move || backend.open_screen(&selection, c, wake))
806 .await
807 .map_err(screen_error)?;
808 Ok(ScreenSource(Capture::new(
809 CaptureKind::Screen,
810 source,
811 hub,
812 c,
813 device,
814 )))
815 }
816}
817
818fn choice(s: &ScreenSourceInfo) -> ScreenChoice {
821 ScreenChoice {
822 id: s.id.clone(),
823 kind: s.kind,
824 title: s.title.clone(),
825 app: s.app.clone(),
826 width: s.width,
827 height: s.height,
828 thumbnail_png: thumbnail_png(s),
829 }
830}
831
832fn thumbnail_size(s: &ScreenSourceInfo, p: &kessel_video::Planes) -> Option<(u32, u32)> {
836 let (w, h) = s.thumbnail_size()?;
837 p.validate(w, h).ok()?;
838 Some((w, h))
839}
840
841pub fn thumbnail_png(s: &ScreenSourceInfo) -> Option<Vec<u8>> {
845 let p = s.thumbnail.as_ref()?;
846 let bgra = match p.format {
847 PixelFormat::Rgba => false,
848 PixelFormat::Bgra => true,
849 _ => return None,
850 };
851 let (w, h) = thumbnail_size(s, p)?;
852 let (tw, th) = if w > THUMBNAIL_MAX_WIDTH {
853 kessel_video::fit_within(w, h, THUMBNAIL_MAX_WIDTH, h)
854 } else {
855 (w, h)
856 };
857 let rgba = shrink_rgba(p, (w, h), (tw, th), bgra);
858 encode_png(tw, th, &rgba)
859}
860
861fn shrink_rgba(p: &kessel_video::Planes, from: (u32, u32), to: (u32, u32), bgra: bool) -> Vec<u8> {
865 let (w, h) = (from.0 as usize, from.1 as usize);
866 let (tw, th) = (to.0 as usize, to.1 as usize);
867 let (stride, off) = (p.strides[0] as usize, p.offsets[0]);
868 let mut out = Vec::with_capacity(tw * th * 4);
869 for ty in 0..th {
870 let (y0, y1) = (ty * h / th, ((ty + 1) * h / th).max(ty * h / th + 1).min(h));
871 for tx in 0..tw {
872 let (x0, x1) = (tx * w / tw, ((tx + 1) * w / tw).max(tx * w / tw + 1).min(w));
873 let mut sum = [0u64; 4];
874 for y in y0..y1 {
875 let row = &p.data[off + y * stride..];
876 for x in x0..x1 {
877 for (c, v) in sum.iter_mut().enumerate() {
878 *v += u64::from(row[x * 4 + c]);
879 }
880 }
881 }
882 let n = ((y1 - y0) * (x1 - x0)) as u64;
883 let avg = sum.map(|v| u8::try_from((v + n / 2) / n).unwrap_or(u8::MAX));
884 let px = if bgra {
885 [avg[2], avg[1], avg[0], avg[3]]
886 } else {
887 avg
888 };
889 out.extend_from_slice(&px);
890 }
891 }
892 out
893}
894
895fn encode_png(width: u32, height: u32, rgba: &[u8]) -> Option<Vec<u8>> {
897 let mut out = Vec::new();
898 let mut enc = png::Encoder::new(&mut out, width, height);
899 enc.set_color(png::ColorType::Rgba);
900 enc.set_depth(png::BitDepth::Eight);
901 let mut w = enc.write_header().ok()?;
902 w.write_image_data(rgba).ok()?;
903 w.finish().ok()?;
904 Some(out)
905}
906
907#[cfg(test)]
908mod tests;