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 #[cfg(any(sew_preview_events, test))]
277 _preview: Option<super::camera_tap::PreviewLease>,
278}
279
280impl std::fmt::Debug for Capture {
281 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
282 f.debug_struct("Capture")
283 .field("kind", &self.kind)
284 .field("device", &self.device)
285 .field("ended", &self.ended)
286 .field("paused", &self.paused)
287 .finish_non_exhaustive()
288 }
289}
290
291impl Capture {
292 fn new(
293 kind: CaptureKind,
294 source: Box<dyn FrameSource>,
295 hub: Arc<WakeHub>,
296 constraints: CaptureConstraints,
297 device: Option<String>,
298 ) -> Capture {
299 Capture {
300 kind,
301 source,
302 hub,
303 constraints,
304 device,
305 ended: None,
306 paused: None,
307 #[cfg(any(sew_preview_events, test))]
308 _preview: None,
309 }
310 }
311
312 pub fn kind(&self) -> CaptureKind {
314 self.kind
315 }
316
317 pub fn content_hint(&self) -> ContentHint {
320 match self.kind {
321 CaptureKind::Screen => ContentHint::Screen,
322 _ => ContentHint::Camera,
323 }
324 }
325
326 pub fn device(&self) -> Option<&str> {
329 self.device.as_deref()
330 }
331
332 pub fn constraints(&self) -> CaptureConstraints {
334 self.constraints
335 }
336
337 pub fn set_constraints(&mut self, c: CaptureConstraints) -> Result<(), CaptureError> {
340 let r = self.source.set_constraints(c);
341 r.map_err(|e| match self.kind {
342 CaptureKind::Camera => camera_error(e),
343 _ => screen_error(e),
344 })?;
345 self.constraints = c;
346 Ok(())
347 }
348
349 pub fn set_paused(&mut self, paused: bool) {
352 self.source.set_paused(paused);
353 }
354
355 pub fn try_frame(&mut self) -> Option<kessel_video::VideoFrame> {
358 if self.ended.is_some() {
359 return None;
360 }
361 self.source.try_recv()
362 }
363
364 pub fn try_event(&mut self) -> Option<CaptureEvent> {
366 loop {
367 let e = map_event(self.source.try_event()?);
368 match &e {
369 Some(CaptureEvent::Ended(end)) => self.ended = Some(*end),
370 Some(CaptureEvent::Paused(p)) => self.paused = Some(*p),
371 Some(CaptureEvent::Resumed) => self.paused = None,
372 _ => {}
373 }
374 if e.is_some() {
375 return e;
376 }
377 }
378 }
379
380 pub async fn ready(&self) {
384 self.hub.ready.notified().await;
385 }
386
387 pub fn wake(&self) -> Wake {
390 notify_wake(&self.hub.ready)
391 }
392
393 pub fn notifier(&self) -> Arc<Notify> {
395 Arc::clone(&self.hub.ready)
396 }
397
398 pub(crate) fn chain_wake(&self, wake: Wake) {
401 *self
402 .hub
403 .chained
404 .lock()
405 .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(wake);
406 self.hub.wake()();
408 }
409
410 pub fn ended(&self) -> Option<CaptureEnd> {
412 self.ended
413 }
414
415 pub fn paused(&self) -> Option<CapturePause> {
417 self.paused
418 }
419
420 pub fn stats(&self) -> SourceStats {
422 self.source.stats()
423 }
424}
425
426impl FrameSource for Capture {
430 fn try_recv(&mut self) -> Option<kessel_video::VideoFrame> {
431 self.source.try_recv()
432 }
433
434 fn try_event(&mut self) -> Option<SourceEvent> {
435 self.source.try_event()
436 }
437
438 fn set_constraints(&mut self, c: CaptureConstraints) -> Result<(), VideoError> {
439 self.source.set_constraints(c)?;
440 self.constraints = c;
441 Ok(())
442 }
443
444 fn set_paused(&mut self, paused: bool) {
445 self.source.set_paused(paused);
446 }
447
448 fn stats(&self) -> SourceStats {
449 self.source.stats()
450 }
451
452 #[cfg(sew_apple_preview)]
453 fn apple_preview(&self) -> Option<kessel_video::ApplePreview> {
454 self.source.apple_preview()
455 }
456}
457
458#[derive(Debug)]
460pub struct CameraSource(Capture);
461
462#[derive(Debug)]
465pub struct ScreenSource(Capture);
466
467macro_rules! capture_handle {
468 ($t:ty) => {
469 impl std::ops::Deref for $t {
470 type Target = Capture;
471 fn deref(&self) -> &Capture {
472 &self.0
473 }
474 }
475
476 impl std::ops::DerefMut for $t {
477 fn deref_mut(&mut self) -> &mut Capture {
478 &mut self.0
479 }
480 }
481
482 impl $t {
483 pub fn into_capture(self) -> Capture {
485 self.0
486 }
487 }
488 };
489}
490
491capture_handle!(CameraSource);
492capture_handle!(ScreenSource);
493
494#[derive(Debug, Clone, PartialEq, Eq)]
496#[non_exhaustive]
497pub enum ScreenPick {
498 Listed(String),
500 System {
503 parent_window: Option<u64>,
505 },
506}
507
508#[derive(Debug, Clone, PartialEq, Eq)]
510#[non_exhaustive]
511pub struct ScreenChoice {
512 pub id: String,
514 pub kind: ScreenKind,
516 pub title: String,
518 pub app: Option<String>,
520 pub width: u32,
522 pub height: u32,
524 pub thumbnail_png: Option<Vec<u8>>,
526}
527
528pub fn screen_constraints(max_width: u32, max_height: u32, fps: u32) -> CaptureConstraints {
532 let mut c = CaptureConstraints::new(max_width, max_height, fps);
533 c.cursor = true;
534 c.exclude_own_windows = true;
535 c
536}
537
538#[derive(Clone)]
544pub struct VideoCapture {
545 backend: Arc<dyn VideoBackend>,
546 preview: Arc<Mutex<Option<Weak<super::preview::Shared>>>>,
548 taps: super::camera_tap::CameraTaps,
550 #[cfg(all(not(sew_apple_preview), any(test, feature = "testing")))]
553 fake_previews: Arc<Mutex<u64>>,
554}
555
556impl std::fmt::Debug for VideoCapture {
557 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
558 f.debug_struct("VideoCapture")
559 .field("backend", &self.backend.capabilities().backend)
560 .finish()
561 }
562}
563
564async fn blocking<T: Send + 'static>(
566 f: impl FnOnce() -> Result<T, VideoError> + Send + 'static,
567) -> Result<T, VideoError> {
568 tokio::task::spawn_blocking(f)
569 .await
570 .map_err(|e| VideoError::os(0, format!("capture task: {e}")))?
571}
572
573impl VideoCapture {
574 pub fn new(backend: Arc<dyn VideoBackend>) -> VideoCapture {
576 VideoCapture {
577 backend,
578 preview: Arc::new(Mutex::new(None)),
579 taps: super::camera_tap::CameraTaps::default(),
580 #[cfg(all(not(sew_apple_preview), any(test, feature = "testing")))]
581 fake_previews: Arc::default(),
582 }
583 }
584
585 #[cfg(all(test, not(sew_apple_preview)))]
588 pub(crate) fn fake_previews(&self, from: u64) {
589 *self
590 .fake_previews
591 .lock()
592 .unwrap_or_else(std::sync::PoisonError::into_inner) = from;
593 }
594
595 #[cfg(sew_apple_preview)]
598 fn preview_of(
599 &self,
600 source: &dyn FrameSource,
601 _device: Option<&str>,
602 ) -> (
603 Option<super::camera_tap::PreviewHandle>,
604 kessel_video::Facing,
605 ) {
606 match source.apple_preview() {
607 Some(p) => {
608 let facing = p.facing();
609 (Some(p), facing)
610 }
611 None => (None, kessel_video::Facing::Unknown),
612 }
613 }
614
615 #[cfg(all(not(sew_apple_preview), any(test, feature = "testing")))]
617 fn preview_of(
618 &self,
619 _source: &dyn FrameSource,
620 device: Option<&str>,
621 ) -> (
622 Option<super::camera_tap::PreviewHandle>,
623 kessel_video::Facing,
624 ) {
625 let next = {
626 let mut n = self
627 .fake_previews
628 .lock()
629 .unwrap_or_else(std::sync::PoisonError::into_inner);
630 let this = *n;
631 if this != 0 {
632 *n += 1;
633 }
634 (this != 0).then_some(this)
635 };
636 match next {
637 Some(n) => (
638 Some(super::camera_tap::FakePreview(n)),
639 self.camera_facing(device),
640 ),
641 None => (None, kessel_video::Facing::Unknown),
642 }
643 }
644
645 pub fn camera_tap(&self) -> super::CameraTap {
651 self.taps.open()
652 }
653
654 pub(crate) fn camera_taps(&self) -> &super::camera_tap::CameraTaps {
656 &self.taps
657 }
658
659 pub fn stop_preview(&self) {
661 let running = self
662 .preview
663 .lock()
664 .unwrap_or_else(std::sync::PoisonError::into_inner)
665 .take()
666 .and_then(|w| w.upgrade());
667 if let Some(p) = running {
668 p.stop();
669 }
670 }
671
672 pub fn preview_running(&self) -> bool {
674 self.preview
675 .lock()
676 .unwrap_or_else(std::sync::PoisonError::into_inner)
677 .as_ref()
678 .and_then(Weak::upgrade)
679 .is_some_and(|p| p.running())
680 }
681
682 pub(crate) fn set_preview(&self, p: &Arc<super::preview::Shared>) {
684 *self
685 .preview
686 .lock()
687 .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(Arc::downgrade(p));
688 }
689
690 pub fn null() -> VideoCapture {
692 VideoCapture::new(kessel_video::null())
693 }
694
695 pub fn backend(&self) -> &Arc<dyn VideoBackend> {
697 &self.backend
698 }
699
700 pub fn capabilities(&self) -> Capabilities {
702 self.backend.capabilities()
703 }
704
705 pub fn camera_facing(&self, device: Option<&str>) -> kessel_video::Facing {
708 let cams = self.cameras();
709 match device {
710 Some(id) => cams.iter().find(|c| c.id == id),
711 None => cams.iter().find(|c| c.is_default).or(cams.first()),
712 }
713 .map_or(kessel_video::Facing::Unknown, |c| c.facing)
714 }
715
716 pub fn cameras(&self) -> Vec<CameraInfo> {
718 self.backend.cameras()
719 }
720
721 pub fn camera_permission(&self) -> Permission {
723 self.backend.camera_permission()
724 }
725
726 pub fn screen_permission(&self) -> Permission {
728 self.backend.screen_permission()
729 }
730
731 pub fn events(&self) -> EventRx {
733 self.backend.subscribe()
734 }
735
736 pub async fn request_camera_permission(&self) -> Permission {
738 let (tx, rx) = oneshot::channel();
739 self.backend.request_camera_permission(Box::new(move |p| {
740 let _ = tx.send(p);
741 }));
742 rx.await.unwrap_or(Permission::Denied)
743 }
744
745 pub async fn request_screen_permission(&self) -> Permission {
747 let (tx, rx) = oneshot::channel();
748 self.backend.request_screen_permission(Box::new(move |p| {
749 let _ = tx.send(p);
750 }));
751 rx.await.unwrap_or(Permission::Denied)
752 }
753
754 pub(crate) async fn camera_allowed(&self) -> Result<(), CaptureError> {
755 let p = match self.camera_permission() {
756 Permission::NotDetermined => self.request_camera_permission().await,
757 p => p,
758 };
759 match p {
760 Permission::Granted => Ok(()),
761 _ => Err(CaptureError::CameraDenied),
762 }
763 }
764
765 async fn screen_allowed(&self) -> Result<(), CaptureError> {
766 let p = match self.screen_permission() {
767 Permission::NotDetermined => self.request_screen_permission().await,
768 p => p,
769 };
770 match p {
771 Permission::Granted => Ok(()),
772 _ => Err(CaptureError::ScreenDenied),
773 }
774 }
775
776 pub async fn open_camera(
781 &self,
782 device: Option<&str>,
783 constraints: CaptureConstraints,
784 ) -> Result<CameraSource, CaptureError> {
785 if !self.capabilities().camera {
786 return Err(CaptureError::VideoUnsupported);
787 }
788 self.camera_allowed().await?;
789 self.stop_preview();
790 let hub = Arc::new(WakeHub::default());
791 let wake = hub.wake();
792 let backend = Arc::clone(&self.backend);
793 let id = device.map(str::to_owned);
794 let asked = id.clone();
795 let source = blocking(move || backend.open_camera(asked.as_deref(), constraints, wake))
796 .await
797 .map_err(camera_error)?;
798 #[cfg(any(sew_preview_events, test))]
801 let lease = {
802 let (preview, facing) = self.preview_of(&*source, device);
803 self.taps.preview_open(preview, facing)
804 };
805 let capture = Capture::new(CaptureKind::Camera, source, hub, constraints, id);
806 #[cfg(any(sew_preview_events, test))]
807 let capture = Capture {
808 _preview: Some(lease),
809 ..capture
810 };
811 Ok(CameraSource(capture))
812 }
813
814 pub async fn screen_sources(&self) -> Result<Vec<ScreenChoice>, CaptureError> {
817 let screen = self.capabilities().screen;
818 if !screen.supported {
819 return Err(CaptureError::ScreenUnsupported);
820 }
821 if !screen.list {
822 return Ok(Vec::new());
823 }
824 let backend = Arc::clone(&self.backend);
825 let list = blocking(move || {
826 let list = backend.screen_sources()?;
827 Ok(list.iter().map(choice).collect::<Vec<_>>())
828 })
829 .await
830 .map_err(screen_error)?;
831 Ok(list)
832 }
833
834 async fn pick(&self, opts: PickOptions) -> Result<ScreenSelection, CaptureError> {
836 let (tx, rx) = oneshot::channel();
837 self.backend.pick_screen(
838 opts,
839 Box::new(move |r| {
840 let _ = tx.send(r);
841 }),
842 );
843 match rx.await {
844 Ok(r) => r.map_err(pick_error),
845 Err(_) => Err(CaptureError::ScreenUnsupported),
846 }
847 }
848
849 pub async fn open_screen(
855 &self,
856 pick: ScreenPick,
857 constraints: CaptureConstraints,
858 ) -> Result<ScreenSource, CaptureError> {
859 let screen = self.capabilities().screen;
860 if !screen.supported {
861 return Err(CaptureError::ScreenUnsupported);
862 }
863 self.screen_allowed().await?;
864 let (selection, device) = match pick {
865 ScreenPick::Listed(id) => {
866 if !screen.list {
867 return Err(CaptureError::ScreenNotFound);
868 }
869 (ScreenSelection::Listed(id.clone()), Some(id))
870 }
871 ScreenPick::System { parent_window } => {
872 if !screen.system_picker {
873 return Err(CaptureError::ScreenUnsupported);
874 }
875 let mut opts = PickOptions::new();
876 opts.displays = true;
877 opts.windows = screen.windows;
878 if let Some(h) = parent_window {
879 opts = opts.with_parent_window(h);
880 }
881 (self.pick(opts).await?, None)
882 }
883 };
884 let mut c = constraints;
885 c.exclude_own_windows &= screen.exclude_own_windows;
886 let hub = Arc::new(WakeHub::default());
887 let wake = hub.wake();
888 let backend = Arc::clone(&self.backend);
889 let source = blocking(move || backend.open_screen(&selection, c, wake))
890 .await
891 .map_err(screen_error)?;
892 Ok(ScreenSource(Capture::new(
893 CaptureKind::Screen,
894 source,
895 hub,
896 c,
897 device,
898 )))
899 }
900}
901
902fn choice(s: &ScreenSourceInfo) -> ScreenChoice {
905 ScreenChoice {
906 id: s.id.clone(),
907 kind: s.kind,
908 title: s.title.clone(),
909 app: s.app.clone(),
910 width: s.width,
911 height: s.height,
912 thumbnail_png: thumbnail_png(s),
913 }
914}
915
916fn thumbnail_size(s: &ScreenSourceInfo, p: &kessel_video::Planes) -> Option<(u32, u32)> {
920 let (w, h) = s.thumbnail_size()?;
921 p.validate(w, h).ok()?;
922 Some((w, h))
923}
924
925pub fn thumbnail_png(s: &ScreenSourceInfo) -> Option<Vec<u8>> {
929 let p = s.thumbnail.as_ref()?;
930 let bgra = match p.format {
931 PixelFormat::Rgba => false,
932 PixelFormat::Bgra => true,
933 _ => return None,
934 };
935 let (w, h) = thumbnail_size(s, p)?;
936 let (tw, th) = if w > THUMBNAIL_MAX_WIDTH {
937 kessel_video::fit_within(w, h, THUMBNAIL_MAX_WIDTH, h)
938 } else {
939 (w, h)
940 };
941 let rgba = shrink_rgba(p, (w, h), (tw, th), bgra);
942 encode_png(tw, th, &rgba)
943}
944
945fn shrink_rgba(p: &kessel_video::Planes, from: (u32, u32), to: (u32, u32), bgra: bool) -> Vec<u8> {
949 let (w, h) = (from.0 as usize, from.1 as usize);
950 let (tw, th) = (to.0 as usize, to.1 as usize);
951 let (stride, off) = (p.strides[0] as usize, p.offsets[0]);
952 let mut out = Vec::with_capacity(tw * th * 4);
953 for ty in 0..th {
954 let (y0, y1) = (ty * h / th, ((ty + 1) * h / th).max(ty * h / th + 1).min(h));
955 for tx in 0..tw {
956 let (x0, x1) = (tx * w / tw, ((tx + 1) * w / tw).max(tx * w / tw + 1).min(w));
957 let mut sum = [0u64; 4];
958 for y in y0..y1 {
959 let row = &p.data[off + y * stride..];
960 for x in x0..x1 {
961 for (c, v) in sum.iter_mut().enumerate() {
962 *v += u64::from(row[x * 4 + c]);
963 }
964 }
965 }
966 let n = ((y1 - y0) * (x1 - x0)) as u64;
967 let avg = sum.map(|v| u8::try_from((v + n / 2) / n).unwrap_or(u8::MAX));
968 let px = if bgra {
969 [avg[2], avg[1], avg[0], avg[3]]
970 } else {
971 avg
972 };
973 out.extend_from_slice(&px);
974 }
975 }
976 out
977}
978
979fn encode_png(width: u32, height: u32, rgba: &[u8]) -> Option<Vec<u8>> {
981 let mut out = Vec::new();
982 let mut enc = png::Encoder::new(&mut out, width, height);
983 enc.set_color(png::ColorType::Rgba);
984 enc.set_depth(png::BitDepth::Eight);
985 let mut w = enc.write_header().ok()?;
986 w.write_image_data(rgba).ok()?;
987 w.finish().ok()?;
988 Some(out)
989}
990
991#[cfg(test)]
992mod tests;