1use std::collections::{BTreeMap, HashMap};
68use std::sync::atomic::{AtomicBool, Ordering};
69use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError};
70use std::time::Duration;
71
72use kessel_video::{
73 Capabilities, CaptureConstraints, CodecCapability, CodecConfig, CodecDirection, ContentHint,
74 EncodeOptions, EncoderConfig, Facing, FrameBuffer, FrameSource, ImplPreference, Implementation,
75 PixelFormat, Rates, SourceEvent, VideoBackend, VideoEncoder, VideoError as KError, Wake,
76};
77use serde::Serialize;
78use tokio::sync::{broadcast, mpsc};
79
80use super::camera_tap::{CameraFeed, CameraTaps};
81use super::capture::{
82 Capture, CaptureEnd, CaptureError, CaptureEvent, CaptureKind, CapturePause, VideoCapture,
83 map_event,
84};
85use super::codec_pref::{
86 H264Detection, VideoCodecPreference as CodecPreference, effective_publish_codec_under_policy,
87 h264_encode_detection,
88};
89use super::preview::LocalFrame;
90use super::publish::{
91 BackupCaps, BackupSpec, EncodedVideo, LayerRate, LayerSpec, VideoControl, VideoCtl, VideoError,
92 VideoPublication, VideoPublish, VideoSender, backup_layers_for, plan_source_layers,
93};
94use super::types::{VideoCodec, VideoSource};
95use crate::call::Call;
96
97pub(crate) const CAMERA_SWITCH: &str = "camera_switch";
99pub(crate) const ENCODER_LOST: &str = "encoder_lost";
101
102const BACKUP_RETRY: Duration = Duration::from_secs(1);
104const START_WAIT: Duration = Duration::from_secs(3);
106const FIRST_FRAME_WAIT: Duration = Duration::from_millis(2500);
110const STOP_WAIT: Duration = Duration::from_secs(2);
113const SELF_VIEW_QUEUE: usize = 8;
115const EVENT_QUEUE: usize = 32;
117
118#[derive(Clone, Debug, Default, PartialEq, Eq)]
120#[non_exhaustive]
121pub struct CameraRequest {
122 pub on: bool,
124 pub device: Option<String>,
126 pub temporal_layers: Option<u8>,
128 pub reason: Option<String>,
131}
132
133impl CameraRequest {
134 pub fn on() -> CameraRequest {
136 CameraRequest {
137 on: true,
138 device: None,
139 temporal_layers: None,
140 reason: None,
141 }
142 }
143
144 pub fn off() -> CameraRequest {
146 CameraRequest::default()
147 }
148
149 pub fn with_device(mut self, device: &str) -> CameraRequest {
151 self.device = Some(device.to_owned());
152 self
153 }
154
155 pub fn with_reason(mut self, reason: &str) -> CameraRequest {
157 self.reason = Some(reason.to_owned());
158 self
159 }
160
161 pub fn with_temporal_layers(mut self, n: u8) -> CameraRequest {
163 self.temporal_layers = Some(n);
164 self
165 }
166}
167
168#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
170#[serde(tag = "camera", rename_all = "snake_case")]
171#[non_exhaustive]
172pub enum CameraState {
173 Off,
175 On {
177 codec: VideoCodec,
179 layers: Vec<LayerSpec>,
181 width: u32,
183 height: u32,
185 },
186}
187
188#[derive(Clone, Debug, PartialEq, Eq)]
190#[non_exhaustive]
191pub struct SourceNote {
192 pub source: VideoSource,
194 pub event: CaptureEvent,
197}
198
199#[derive(Clone, Debug, PartialEq, Eq)]
201#[non_exhaustive]
202pub enum SelfViewItem {
203 Frame {
205 source: VideoSource,
207 frame: LocalFrame,
209 },
210 Ended {
212 source: VideoSource,
214 },
215}
216
217pub type SelfViewFrames = mpsc::Receiver<SelfViewItem>;
219
220fn our_codec(c: kessel_video::VideoCodec) -> Option<VideoCodec> {
221 match c {
222 kessel_video::VideoCodec::Vp8 => Some(VideoCodec::Vp8),
223 kessel_video::VideoCodec::H264 => Some(VideoCodec::H264),
224 _ => None,
225 }
226}
227
228fn their_codec(c: VideoCodec) -> kessel_video::VideoCodec {
229 match c {
230 VideoCodec::Vp8 => kessel_video::VideoCodec::Vp8,
231 VideoCodec::H264 => kessel_video::VideoCodec::H264,
232 }
233}
234
235#[deprecated(
242 note = "use choose_codecs: it takes only usable (hardware) OS H.264 and plans the VP8 backup"
243)]
244pub fn choose_codec(
245 policy: &[sew_proto::voice::VideoCodec],
246 caps: &Capabilities,
247) -> Option<(VideoCodec, CodecCapability)> {
248 for want in [VideoCodec::Vp8, VideoCodec::H264] {
249 let listed = policy
250 .iter()
251 .any(|c| super::publish::codec_of_policy(*c) == Some(want));
252 if !listed {
253 continue;
254 }
255 if let Some(cap) = caps.best(their_codec(want), CodecDirection::Encode) {
256 return Some((want, cap.clone()));
257 }
258 }
259 None
260}
261
262#[derive(Clone, Debug, PartialEq, Eq)]
264#[non_exhaustive]
265pub struct PlannedCodec {
266 pub codec: VideoCodec,
268 pub capability: CodecCapability,
270}
271
272#[derive(Clone, Debug, PartialEq, Eq)]
274#[non_exhaustive]
275pub struct CodecPlan {
276 pub primary: PlannedCodec,
278 pub backup: Option<PlannedCodec>,
281 pub reason: &'static str,
285}
286
287fn platform_h264(caps: &Capabilities) -> bool {
293 const OS: bool = cfg!(any(target_os = "macos", target_os = "ios"));
294 OS || (cfg!(feature = "testing") && caps.backend == "fixture")
295}
296
297fn usable_h264(caps: &Capabilities) -> Option<&CodecCapability> {
303 if !platform_h264(caps) {
304 return None;
305 }
306 caps.codecs
307 .iter()
308 .filter(|c| {
309 c.codec == kessel_video::VideoCodec::H264
310 && c.direction == CodecDirection::Encode
311 && c.implementation == Implementation::Hardware
312 })
313 .max_by_key(|c| u64::from(c.max_width) * u64::from(c.max_height))
314}
315
316pub fn choose_codecs(
329 policy: &sew_proto::voice::MediaPolicy,
330 caps: &Capabilities,
331) -> Option<CodecPlan> {
332 choose_codecs_with(
333 policy,
334 caps,
335 crate::default_video_h264(),
336 CodecPreference::default(),
337 false,
338 )
339}
340
341pub(crate) fn choose_codecs_with(
345 policy: &sew_proto::voice::MediaPolicy,
346 caps: &Capabilities,
347 decodes_h264: bool,
348 pref: CodecPreference,
349 h264_lost: bool,
350) -> Option<CodecPlan> {
351 let listed = |want: VideoCodec| {
352 policy
353 .codecs
354 .iter()
355 .any(|c| super::publish::codec_of_policy(*c) == Some(want))
356 };
357 let vp8 = caps
358 .best(kessel_video::VideoCodec::Vp8, CodecDirection::Encode)
359 .cloned();
360 let detected = if platform_h264(caps) {
362 h264_encode_detection(caps)
363 } else {
364 H264Detection::NoPlatformCheck
365 };
366 let h264 = if h264_lost || !decodes_h264 || !detected.is_usable() {
367 None
368 } else {
369 usable_h264(caps).cloned()
370 };
371 let planned = |codec, capability| PlannedCodec { codec, capability };
372 let both = policy.backup_codec
373 && policy.dynacast
374 && listed(VideoCodec::Vp8)
375 && listed(VideoCodec::H264);
376 let ready = if h264.is_some() && vp8.is_some() {
378 H264Detection::Usable
379 } else if detected.is_usable() {
380 H264Detection::NotDetected
381 } else {
382 detected
383 };
384 let (pick, _) = effective_publish_codec_under_policy(pref, ready, both);
385 if pick == VideoCodec::H264
386 && let (Some(h), Some(v)) = (h264.clone(), vp8.clone())
387 {
388 return Some(CodecPlan {
389 primary: planned(VideoCodec::H264, h),
390 backup: Some(planned(VideoCodec::Vp8, v)),
391 reason: if pref == CodecPreference::PreferH264 {
392 "preferred_h264"
393 } else {
394 "h264_detected"
395 },
396 });
397 }
398 let reason = if pref == CodecPreference::PreferVp8 {
399 "preferred_vp8"
400 } else if h264_lost {
401 "h264_lost"
402 } else if !both {
403 "backup_off"
404 } else if !decodes_h264 {
405 "no_h264_decode"
406 } else {
407 "h264_not_detected"
408 };
409 if listed(VideoCodec::Vp8)
411 && let Some(v) = vp8
412 {
413 return Some(CodecPlan {
414 primary: planned(VideoCodec::Vp8, v),
415 backup: None,
416 reason,
417 });
418 }
419 if listed(VideoCodec::H264)
420 && let Some(h) = h264
421 {
422 return Some(CodecPlan {
423 primary: planned(VideoCodec::H264, h),
424 backup: None,
425 reason,
426 });
427 }
428 None
429}
430
431fn camera_error(e: &KError) -> VideoError {
432 match e {
433 KError::NoPermission => VideoError::CameraDenied,
434 KError::DeviceBusy => VideoError::CameraBusy,
435 KError::NotFound | KError::DeviceLost => VideoError::CameraNotFound,
436 other => VideoError::PublishFailed(format!("camera: {}", other.code())),
437 }
438}
439
440fn capture_error(e: &CaptureError) -> VideoError {
442 match e {
443 CaptureError::CameraDenied => VideoError::CameraDenied,
444 CaptureError::CameraBusy => VideoError::CameraBusy,
445 CaptureError::CameraNotFound | CaptureError::CameraLost => VideoError::CameraNotFound,
446 CaptureError::CodecUnavailable => VideoError::CodecUnavailable,
447 CaptureError::Failed(k) => camera_error(k),
448 other => VideoError::PublishFailed(format!("camera: {}", other.code())),
449 }
450}
451
452fn capture_kind(kind: VideoSource) -> CaptureKind {
453 match kind {
454 VideoSource::Camera => CaptureKind::Camera,
455 VideoSource::ScreenShare => CaptureKind::Screen,
456 }
457}
458
459fn self_view_rid(kind: VideoSource, layers: &[LayerSpec]) -> Option<String> {
462 let want = match kind {
463 VideoSource::Camera => "h",
464 VideoSource::ScreenShare => "q",
465 };
466 if let Some(l) = layers.iter().find(|l| l.rid == want) {
467 return Some(l.rid.clone());
468 }
469 let pick = match kind {
470 VideoSource::Camera => layers
471 .iter()
472 .find(|l| l.height >= 360)
473 .or_else(|| layers.last()),
474 VideoSource::ScreenShare => layers.first(),
475 };
476 pick.map(|l| l.rid.clone())
477}
478
479const PHONE: bool = cfg!(any(target_os = "ios", target_os = "android"));
481
482fn backup_ladder(layers: &[LayerSpec], phone: bool, temporal: u8) -> Vec<LayerSpec> {
486 let mut out: Vec<LayerSpec> = layers
487 .iter()
488 .filter(|l| !phone || l.width.min(l.height) <= 360)
489 .cloned()
490 .collect();
491 if out.is_empty()
492 && let Some(l) = layers.first()
493 {
494 out.push(l.clone());
495 }
496 for l in &mut out {
497 l.temporal_layers = temporal;
498 }
499 out
500}
501
502fn thermal_backup_caps(level: kessel_video::ThermalLevel) -> BackupCaps {
505 use kessel_video::ThermalLevel as T;
506 match level {
507 T::Critical => BackupCaps {
508 max_layers: Some(1),
509 max_fps: Some(15),
510 },
511 T::Serious => BackupCaps {
512 max_layers: Some(1),
513 max_fps: None,
514 },
515 _ => BackupCaps::default(),
516 }
517}
518
519fn vp8_temporal(cap: &CodecCapability, asked: Option<u8>) -> u8 {
521 let offered = cap.max_temporal_layers.clamp(1, 3);
522 asked.map_or(offered, |t| t.clamp(1, offered))
523}
524
525fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
526 m.lock().unwrap_or_else(PoisonError::into_inner)
527}
528
529fn camera_box(max_width: u32, max_height: u32, phone: bool) -> (u32, u32) {
532 if !phone {
533 return (max_width, max_height);
534 }
535 if max_width >= max_height {
536 (max_width.min(1280), max_height.min(720))
537 } else {
538 (max_width.min(720), max_height.min(1280))
539 }
540}
541
542#[derive(Default)]
544struct Bell {
545 rung: Mutex<bool>,
546 cv: Condvar,
547}
548
549impl Bell {
550 fn ring(&self) {
551 *self.rung.lock().unwrap_or_else(PoisonError::into_inner) = true;
552 self.cv.notify_one();
553 }
554
555 fn wait(&self, at_most: Duration) {
556 let g = self.rung.lock().unwrap_or_else(PoisonError::into_inner);
557 let (mut g, _) = self
558 .cv
559 .wait_timeout_while(g, at_most, |r| !*r)
560 .unwrap_or_else(PoisonError::into_inner);
561 *g = false;
562 }
563
564 fn wake(self: &Arc<Bell>) -> Wake {
565 let b = self.clone();
566 Arc::new(move || b.ring())
567 }
568}
569
570fn content_of(kind: VideoSource) -> ContentHint {
571 match kind {
572 VideoSource::Camera => ContentHint::Camera,
573 VideoSource::ScreenShare => ContentHint::Screen,
574 }
575}
576
577fn encoder_config(codec: VideoCodec, l: &LayerSpec, content: ContentHint) -> EncoderConfig {
578 let bps = l.max_kbps.saturating_mul(1000).max(10_000);
579 let mut cfg = match codec {
580 VideoCodec::Vp8 => EncoderConfig::new(CodecConfig::Vp8, l.width, l.height, l.fps, bps),
581 VideoCodec::H264 => EncoderConfig::h264(l.width, l.height, l.fps, bps),
582 };
583 cfg.temporal_layers = if codec == VideoCodec::Vp8 {
584 l.temporal_layers.clamp(1, 3)
585 } else {
586 1
587 };
588 cfg.content = content;
589 if codec == VideoCodec::H264 {
590 cfg.implementation = ImplPreference::HardwareOnly;
592 }
593 cfg
594}
595
596fn open_encoder(
601 backend: &Arc<dyn VideoBackend>,
602 codec: VideoCodec,
603 l: &LayerSpec,
604 content: ContentHint,
605 wake: &Wake,
606) -> Result<Box<dyn VideoEncoder>, KError> {
607 let enc = backend.encoder(encoder_config(codec, l, content), wake.clone())?;
608 if codec == VideoCodec::H264 {
609 let got = enc.implementation();
610 let name = enc.info().name;
611 tracing::info!(target: "sew_call_client", rid = %l.rid, implementation = ?got, encoder = %name, "H.264 session opened");
612 if got != Implementation::Hardware {
613 tracing::info!(target: "sew_call_client", rid = %l.rid, implementation = ?got, encoder = %name, "the H.264 session is not run by the hardware: refused");
614 return Err(KError::Unsupported(
615 "the H.264 session is not hardware".to_owned(),
616 ));
617 }
618 if backend.capabilities().backend == "apple" && !apple_h264_name_is_hardware(&name) {
619 tracing::info!(target: "sew_call_client", rid = %l.rid, implementation = ?got, encoder = %name, "the H.264 session says hardware but its encoder isn't named as hardware: refused");
620 return Err(KError::Unsupported(
621 "the H.264 session's encoder is not named as hardware".to_owned(),
622 ));
623 }
624 }
625 Ok(enc)
626}
627
628fn apple_h264_name_is_hardware(name: &str) -> bool {
634 let name = name.to_ascii_lowercase();
635 if name.contains("ave.avc") {
636 return true;
637 }
638 if name.contains("rtvc") || name.contains("software") || name.contains("low-latency") {
639 return false;
640 }
641 name.contains("hardware")
642}
643
644struct Enc {
646 spec: LayerSpec,
647 enc: Box<dyn VideoEncoder>,
648 active: bool,
649 key_owed: bool,
653}
654
655impl Enc {
656 fn submit(&mut self, frame: &kessel_video::VideoFrame) -> Result<(), KError> {
658 let opts = if self.key_owed {
659 EncodeOptions::keyframe()
660 } else {
661 EncodeOptions::default()
662 };
663 self.enc.submit(frame, opts)?;
664 self.key_owed = false;
665 Ok(())
666 }
667}
668
669fn open_encoders(
672 backend: &Arc<dyn VideoBackend>,
673 codec: VideoCodec,
674 cap: &CodecCapability,
675 mut plan: Vec<LayerSpec>,
676 content: ContentHint,
677 wake: &Wake,
678) -> Vec<Enc> {
679 if let Some(m) = cap.max_instances {
680 plan.truncate(usize::try_from(m.max(1)).unwrap_or(1));
681 }
682 while !plan.is_empty() {
683 let mut opened = Vec::new();
684 let mut failed = false;
685 for l in plan.iter().rev() {
686 match open_encoder(backend, codec, l, content, wake) {
687 Ok(enc) => opened.push(Enc {
688 spec: l.clone(),
689 enc,
690 active: true,
691 key_owed: false,
692 }),
693 Err(e) => {
694 tracing::info!(target: "sew_call_client", rid = %l.rid, error = %e, "an encoder did not open; one layer fewer");
695 failed = true;
696 break;
697 }
698 }
699 }
700 if !failed {
701 opened.reverse();
702 return opened;
703 }
704 drop(opened);
705 plan.pop();
706 }
707 Vec::new()
708}
709
710async fn wait_started(
714 mut src: Box<dyn FrameSource>,
715 fallback: (u32, u32),
716 camera: bool,
717 ended: VideoError,
718) -> Result<(Box<dyn FrameSource>, (u32, u32)), VideoError> {
719 tokio::task::spawn_blocking(move || {
720 let until = std::time::Instant::now() + START_WAIT;
721 let size = loop {
722 match src.try_event() {
723 Some(SourceEvent::Started { width, height, .. }) => break (width, height),
724 Some(SourceEvent::Ended(_)) => return Err(ended),
725 Some(SourceEvent::Error(e)) if camera => return Err(camera_error(&e)),
726 Some(_) => {}
727 None if std::time::Instant::now() >= until => break fallback,
728 None => std::thread::sleep(Duration::from_millis(5)),
729 }
730 };
731 Ok((src, (size.0 & !1, size.1 & !1)))
732 })
733 .await
734 .map_err(|_| VideoError::PublishFailed("source thread".to_owned()))?
735}
736
737async fn wait_first_frame(
743 mut src: Box<dyn FrameSource>,
744) -> Result<(Box<dyn FrameSource>, (u32, u32)), VideoError> {
745 tokio::task::spawn_blocking(move || {
746 let until = std::time::Instant::now() + FIRST_FRAME_WAIT;
747 let mut started = None;
748 let mut events = std::collections::VecDeque::new();
749 loop {
750 while let Some(ev) = src.try_event() {
751 match ev {
752 SourceEvent::Started { width, height, .. } => started = Some((width, height)),
753 SourceEvent::Ended(_) => return Err(VideoError::CameraNotFound),
754 SourceEvent::Error(e) => return Err(camera_error(&e)),
755 other => events.push_back(other),
756 }
757 }
758 if let Some(frame) = src.try_recv() {
759 let size = started.unwrap_or((frame.width, frame.height));
760 let primed: Box<dyn FrameSource> = Box::new(Primed {
761 first: Some(frame),
762 events,
763 inner: src,
764 });
765 return Ok((primed, (size.0 & !1, size.1 & !1)));
766 }
767 if std::time::Instant::now() >= until {
768 tracing::info!(target: "sew_call_client", waited_ms = FIRST_FRAME_WAIT.as_millis() as u64, "the camera gave no frame: no_frames");
769 return Err(VideoError::NoFrames);
770 }
771 std::thread::sleep(Duration::from_millis(5));
772 }
773 })
774 .await
775 .map_err(|_| VideoError::PublishFailed("source thread".to_owned()))?
776}
777
778struct Primed {
781 first: Option<kessel_video::VideoFrame>,
782 events: std::collections::VecDeque<SourceEvent>,
783 inner: Box<dyn FrameSource>,
784}
785
786impl FrameSource for Primed {
787 fn try_recv(&mut self) -> Option<kessel_video::VideoFrame> {
788 if !self.events.is_empty() {
789 return None;
791 }
792 self.first.take().or_else(|| self.inner.try_recv())
793 }
794 fn try_event(&mut self) -> Option<SourceEvent> {
795 self.events.pop_front().or_else(|| self.inner.try_event())
796 }
797 fn set_constraints(&mut self, c: CaptureConstraints) -> Result<(), KError> {
798 self.inner.set_constraints(c)
799 }
800 fn set_paused(&mut self, paused: bool) {
801 self.inner.set_paused(paused);
802 }
803 fn stats(&self) -> kessel_video::SourceStats {
804 self.inner.stats()
805 }
806}
807
808struct Feed {
810 src: Box<dyn FrameSource>,
811 size: (u32, u32),
812 facing: Facing,
813}
814
815enum ToPipe {
817 Source(Box<dyn FrameSource>, Vec<LayerSpec>, Facing),
820 Release(std::sync::mpsc::Sender<()>),
825 Pause(bool),
828}
829
830struct Released;
833
834impl FrameSource for Released {
835 fn try_recv(&mut self) -> Option<kessel_video::VideoFrame> {
836 None
837 }
838 fn try_event(&mut self) -> Option<SourceEvent> {
839 None
840 }
841 fn set_constraints(&mut self, _c: CaptureConstraints) -> Result<(), KError> {
842 Ok(())
843 }
844 fn set_paused(&mut self, _paused: bool) {}
845 fn stats(&self) -> kessel_video::SourceStats {
846 kessel_video::SourceStats::default()
847 }
848}
849
850const RELEASE_WAIT: Duration = Duration::from_secs(3);
852
853struct Running {
854 call: u64,
856 stop: Arc<AtomicBool>,
857 ended: Arc<AtomicBool>,
859 bell: Arc<Bell>,
860 to_pipe: std::sync::mpsc::Sender<ToPipe>,
861 thread: Option<std::thread::JoinHandle<()>>,
862 codec: VideoCodec,
863 live: Arc<Mutex<VideoCodec>>,
865 cap: CodecCapability,
866 layers: Vec<LayerSpec>,
867 size: (u32, u32),
868 device: Option<String>,
869 temporal: Option<u8>,
871 held: Arc<AtomicBool>,
874}
875
876impl Running {
877 fn state(&self) -> CameraState {
878 CameraState::On {
879 codec: *lock(&self.live),
880 layers: self.layers.clone(),
881 width: self.size.0,
882 height: self.size.1,
883 }
884 }
885
886 fn alive(&self) -> bool {
887 !self.ended.load(Ordering::SeqCst)
888 }
889
890 fn stop(mut self) {
893 self.stop.store(true, Ordering::SeqCst);
894 self.bell.ring();
895 let Some(t) = self.thread.take() else { return };
896 let until = std::time::Instant::now() + STOP_WAIT;
897 while !t.is_finished() {
898 if std::time::Instant::now() >= until {
899 tracing::warn!(target: "sew_call_client", waited_ms = STOP_WAIT.as_millis() as u64, "a video pipeline is still stopping (its source closes slowly); it finishes on its own");
900 return;
901 }
902 std::thread::sleep(Duration::from_millis(5));
903 }
904 let _ = t.join();
905 }
906}
907
908async fn stop_running(r: Running) {
909 tokio::task::spawn_blocking(move || r.stop()).await.ok();
910}
911
912fn same_rids(a: &[LayerSpec], b: &[LayerSpec]) -> bool {
914 a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.rid == y.rid)
915}
916
917async fn release_source(r: &Running) -> Result<(), VideoError> {
919 let (tx, rx) = std::sync::mpsc::channel();
920 if r.to_pipe.send(ToPipe::Release(tx)).is_err() {
921 return Err(VideoError::Ended);
922 }
923 r.bell.ring();
924 match tokio::task::spawn_blocking(move || rx.recv_timeout(RELEASE_WAIT)).await {
925 Ok(Ok(())) => Ok(()),
926 _ => Err(VideoError::Ended),
927 }
928}
929
930#[derive(Clone)]
932struct Taps {
933 events: broadcast::Sender<SourceNote>,
934 self_view: Arc<Mutex<Option<mpsc::Sender<SelfViewItem>>>>,
935 h264_lost: Arc<Mutex<Option<u64>>>,
938 camera: CameraTaps,
940}
941
942type SelfKey = (Arc<AtomicBool>, Arc<Bell>);
944
945pub struct VideoBridge {
947 capture: VideoCapture,
948 camera: tokio::sync::Mutex<Option<Running>>,
949 feeds: tokio::sync::Mutex<HashMap<VideoSource, Running>>,
952 taps: Taps,
953 self_keys: Mutex<HashMap<VideoSource, SelfKey>>,
955}
956
957pub struct SourceFeed {
961 pub frames: Box<dyn FrameSource>,
963 pub width: u32,
965 pub height: u32,
967}
968
969impl std::fmt::Debug for SourceFeed {
970 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
971 f.debug_struct("SourceFeed")
972 .field("width", &self.width)
973 .field("height", &self.height)
974 .finish_non_exhaustive()
975 }
976}
977
978impl SourceFeed {
979 pub fn new(frames: Box<dyn FrameSource>, width: u32, height: u32) -> SourceFeed {
981 SourceFeed {
982 frames,
983 width,
984 height,
985 }
986 }
987}
988
989impl std::fmt::Debug for VideoBridge {
990 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
991 f.debug_struct("VideoBridge").finish_non_exhaustive()
992 }
993}
994
995impl VideoBridge {
996 pub fn new(backend: Arc<dyn VideoBackend>) -> VideoBridge {
998 VideoBridge::with_capture(VideoCapture::new(backend))
999 }
1000
1001 pub fn with_capture(capture: VideoCapture) -> VideoBridge {
1004 let camera = capture.camera_taps().clone();
1005 VideoBridge {
1006 capture,
1007 camera: tokio::sync::Mutex::new(None),
1008 feeds: tokio::sync::Mutex::new(HashMap::new()),
1009 taps: Taps {
1010 events: broadcast::channel(EVENT_QUEUE).0,
1011 self_view: Arc::new(Mutex::new(None)),
1012 h264_lost: Arc::new(Mutex::new(None)),
1013 camera,
1014 },
1015 self_keys: Mutex::new(HashMap::new()),
1016 }
1017 }
1018
1019 pub fn capture(&self) -> &VideoCapture {
1021 &self.capture
1022 }
1023
1024 pub fn backend(&self) -> &Arc<dyn VideoBackend> {
1026 self.capture.backend()
1027 }
1028
1029 pub fn events(&self) -> broadcast::Receiver<SourceNote> {
1031 self.taps.events.subscribe()
1032 }
1033
1034 pub fn self_view(&self) -> SelfViewFrames {
1038 let (tx, rx) = mpsc::channel(SELF_VIEW_QUEUE);
1039 *lock(&self.taps.self_view) = Some(tx);
1040 for (key, bell) in lock(&self.self_keys).values() {
1041 key.store(true, Ordering::Release);
1042 bell.ring();
1043 }
1044 rx
1045 }
1046
1047 pub fn self_view_keyframe(&self, source: VideoSource) {
1050 if let Some((key, bell)) = lock(&self.self_keys).get(&source) {
1051 key.store(true, Ordering::Release);
1052 bell.ring();
1053 }
1054 }
1055
1056 pub async fn camera_state(&self) -> CameraState {
1058 match self.camera.lock().await.as_ref() {
1059 Some(r) if r.alive() => r.state(),
1060 _ => CameraState::Off,
1061 }
1062 }
1063
1064 pub async fn camera_device(&self) -> Option<String> {
1066 self.camera
1067 .lock()
1068 .await
1069 .as_ref()
1070 .filter(|r| r.alive())
1071 .and_then(|r| r.device.clone())
1072 }
1073
1074 pub async fn publish_source(
1080 &self,
1081 call: &Call,
1082 kind: VideoSource,
1083 feed: SourceFeed,
1084 temporal_layers: Option<u8>,
1085 ) -> Result<CameraState, VideoError> {
1086 let size = (feed.width & !1, feed.height & !1);
1087 let bell = Arc::new(Bell::default());
1088 let feed_in = Feed {
1089 src: feed.frames,
1090 size,
1091 facing: Facing::Unknown,
1092 };
1093 self.publish_frames(call, kind, feed_in, temporal_layers, bell)
1094 .await
1095 }
1096
1097 pub async fn publish_capture(
1101 &self,
1102 call: &Call,
1103 kind: VideoSource,
1104 capture: Capture,
1105 temporal_layers: Option<u8>,
1106 ) -> Result<CameraState, VideoError> {
1107 let bell = Arc::new(Bell::default());
1108 capture.chain_wake(bell.wake());
1109 let facing = match kind {
1110 VideoSource::Camera => self.capture.camera_facing(capture.device()),
1111 VideoSource::ScreenShare => Facing::Unknown,
1112 };
1113 let c = capture.constraints();
1114 let fallback = (c.max_width.unwrap_or(1280), c.max_height.unwrap_or(720));
1115 let ended = match kind {
1116 VideoSource::Camera => VideoError::CameraNotFound,
1117 VideoSource::ScreenShare => VideoError::PublishFailed("screen: ended".to_owned()),
1118 };
1119 let (src, size) = wait_started(
1120 Box::new(capture),
1121 fallback,
1122 kind == VideoSource::Camera,
1123 ended,
1124 )
1125 .await?;
1126 let feed = Feed { src, size, facing };
1127 self.publish_frames(call, kind, feed, temporal_layers, bell)
1128 .await
1129 }
1130
1131 async fn publish_frames(
1132 &self,
1133 call: &Call,
1134 kind: VideoSource,
1135 feed: Feed,
1136 temporal_layers: Option<u8>,
1137 bell: Arc<Bell>,
1138 ) -> Result<CameraState, VideoError> {
1139 let mut feeds = self.feeds.lock().await;
1140 if feeds
1141 .get(&kind)
1142 .is_some_and(|r| !r.alive() || r.call != call.local_id())
1143 && let Some(r) = feeds.remove(&kind)
1144 {
1145 stop_running(r).await;
1146 }
1147 if feeds.contains_key(&kind) {
1148 return Err(VideoError::AlreadyPublished);
1149 }
1150 let policy = call.media_policy().ok_or(VideoError::NotAllowed)?;
1151 let allowed = match kind {
1152 VideoSource::Camera => policy.camera_allowed,
1153 VideoSource::ScreenShare => policy.screen_allowed,
1154 };
1155 if !policy.video_enabled || !allowed {
1156 return Err(VideoError::NotAllowed);
1157 }
1158 call.set_video_lease(kind, true).await?;
1159 let started = self
1160 .start_from(call, &policy, kind, feed, temporal_layers, None, bell)
1161 .await;
1162 match started {
1163 Ok(r) => {
1164 let state = r.state();
1165 feeds.insert(kind, r);
1166 Ok(state)
1167 }
1168 Err(e) => {
1169 let _ = call.set_video_lease(kind, false).await;
1170 Err(e)
1171 }
1172 }
1173 }
1174
1175 pub async fn stop_source(&self, call: &Call, kind: VideoSource) -> Result<(), VideoError> {
1178 let running = self.feeds.lock().await.remove(&kind);
1179 if let Some(r) = running {
1180 stop_running(r).await;
1181 }
1182 match call.unpublish_video(kind, true).await {
1183 Ok(()) | Err(VideoError::NotPublished) => Ok(()),
1184 Err(e) => Err(e),
1185 }
1186 }
1187
1188 pub async fn set_camera(
1191 &self,
1192 call: &Call,
1193 req: CameraRequest,
1194 ) -> Result<CameraState, VideoError> {
1195 let mut slot = self.camera.lock().await;
1196 if slot
1197 .as_ref()
1198 .is_some_and(|r| !r.alive() || r.call != call.local_id())
1199 && let Some(r) = slot.take()
1200 {
1201 stop_running(r).await;
1204 }
1205 if !req.on {
1206 if let Some(r) = slot.take() {
1207 stop_running(r).await;
1208 }
1209 let reason = req.reason.as_deref().unwrap_or(super::publish::UNPUBLISHED);
1210 tracing::info!(target: "sew_call_client", %reason, "the camera turns off");
1211 return match call
1212 .unpublish_video_because(VideoSource::Camera, true, reason)
1213 .await
1214 {
1215 Ok(()) | Err(VideoError::NotPublished) => Ok(CameraState::Off),
1216 Err(e) => Err(e),
1217 };
1218 }
1219 let policy = call.media_policy().ok_or(VideoError::NotAllowed)?;
1220 if !policy.video_enabled || !policy.camera_allowed {
1221 return Err(VideoError::NotAllowed);
1222 }
1223 if slot.as_ref().is_none_or(|r| r.device != req.device) {
1226 call.noise_grace();
1227 }
1228 if let Some(r) = slot.as_ref() {
1229 if r.device == req.device {
1230 return Ok(r.state());
1231 }
1232 return self.switch(call, &mut slot, &policy, req).await;
1233 }
1234 self.capture
1235 .camera_allowed()
1236 .await
1237 .map_err(|e| capture_error(&e))?;
1238 call.set_video_lease(VideoSource::Camera, true).await?;
1239 match self.start(call, &policy, &req).await {
1240 Ok(r) => {
1241 let state = r.state();
1242 *slot = Some(r);
1243 Ok(state)
1244 }
1245 Err(e) => {
1246 let _ = call.set_video_lease(VideoSource::Camera, false).await;
1247 Err(e)
1248 }
1249 }
1250 }
1251
1252 pub async fn switch_camera(
1256 &self,
1257 call: &Call,
1258 device: Option<String>,
1259 ) -> Result<CameraState, VideoError> {
1260 let mut slot = self.camera.lock().await;
1261 let Some(r) = slot
1262 .as_ref()
1263 .filter(|r| r.alive() && r.call == call.local_id())
1264 else {
1265 return Ok(CameraState::Off);
1266 };
1267 if r.device == device {
1268 return Ok(r.state());
1269 }
1270 let mut req = CameraRequest::on();
1271 req.device = device;
1272 req.temporal_layers = r.temporal;
1273 let policy = call.media_policy().ok_or(VideoError::NotAllowed)?;
1274 call.noise_grace();
1275 self.switch(call, &mut slot, &policy, req).await
1276 }
1277
1278 async fn open(
1281 &self,
1282 device: Option<String>,
1283 policy: &sew_proto::voice::MediaPolicy,
1284 bell: &Arc<Bell>,
1285 ) -> Result<(Box<dyn FrameSource>, (u32, u32)), VideoError> {
1286 let hint = &policy.camera;
1287 let phone = cfg!(any(target_os = "ios", target_os = "android"));
1288 let (w, h) = camera_box(hint.max_width, hint.max_height, phone);
1289 let mut c = CaptureConstraints::new(w.max(16), h.max(16), hint.max_fps.clamp(1, 240));
1290 c.prefer_native = true;
1291 let cam = self
1292 .capture
1293 .open_camera(device.as_deref(), c)
1294 .await
1295 .map_err(|e| capture_error(&e))?
1296 .into_capture();
1297 cam.chain_wake(bell.wake());
1298 wait_first_frame(Box::new(cam)).await
1300 }
1301
1302 fn plan(
1303 policy: &sew_proto::voice::MediaPolicy,
1304 kind: VideoSource,
1305 codec: VideoCodec,
1306 cap: &CodecCapability,
1307 temporal_layers: Option<u8>,
1308 size: (u32, u32),
1309 ) -> Vec<LayerSpec> {
1310 let tl = if codec == VideoCodec::Vp8 {
1311 let offered = cap.max_temporal_layers.clamp(1, 3);
1312 temporal_layers.map_or(offered, |t| t.clamp(1, offered))
1313 } else {
1314 1
1315 };
1316 let mut plan =
1317 plan_source_layers(kind, super::publish::hint_of(kind, policy), size.0, size.1);
1318 for l in &mut plan {
1319 l.temporal_layers = tl;
1320 }
1321 plan
1322 }
1323
1324 async fn start(
1325 &self,
1326 call: &Call,
1327 policy: &sew_proto::voice::MediaPolicy,
1328 req: &CameraRequest,
1329 ) -> Result<Running, VideoError> {
1330 let bell = Arc::new(Bell::default());
1331 let (src, size) = self.open(req.device.clone(), policy, &bell).await?;
1332 let facing = self.capture.camera_facing(req.device.as_deref());
1333 self.start_from(
1334 call,
1335 policy,
1336 VideoSource::Camera,
1337 Feed { src, size, facing },
1338 req.temporal_layers,
1339 req.device.clone(),
1340 bell,
1341 )
1342 .await
1343 }
1344
1345 #[allow(clippy::too_many_arguments)]
1347 async fn start_from(
1348 &self,
1349 call: &Call,
1350 policy: &sew_proto::voice::MediaPolicy,
1351 kind: VideoSource,
1352 feed: Feed,
1353 temporal_layers: Option<u8>,
1354 device: Option<String>,
1355 bell: Arc<Bell>,
1356 ) -> Result<Running, VideoError> {
1357 let Feed { src, size, facing } = feed;
1358 let backend = Arc::clone(self.backend());
1359 let caps = backend.capabilities();
1360 let lost = *lock(&self.taps.h264_lost) == Some(call.local_id());
1361 let pref = call.video_codec_preference();
1363 let Some(mut plan) = choose_codecs_with(policy, &caps, call.decodes_h264(), pref, lost)
1364 else {
1365 return Err(VideoError::CodecUnavailable);
1366 };
1367 tracing::info!(target: "sew_call_client", source = ?kind, codec = plan.primary.codec.as_str(), backup = plan.backup.as_ref().map(|b| b.codec.as_str()), reason = plan.reason, "the codec plan");
1368 let content = content_of(kind);
1369 let open = |codec: VideoCodec, cap: CodecCapability| {
1370 let layers = VideoBridge::plan(policy, kind, codec, &cap, temporal_layers, size);
1371 let wake = bell.wake();
1372 let b2 = Arc::clone(&backend);
1373 async move {
1374 tokio::task::spawn_blocking(move || {
1375 open_encoders(&b2, codec, &cap, layers, content, &wake)
1376 })
1377 .await
1378 .map_err(|_| VideoError::PublishFailed("encoder thread".to_owned()))
1379 }
1380 };
1381 let mut encs = open(plan.primary.codec, plan.primary.capability.clone()).await?;
1382 if encs.is_empty() && plan.primary.codec == VideoCodec::H264 {
1383 tracing::info!(target: "sew_call_client", source = ?kind, "the H.264 encoder did not open on the hardware: VP8 only");
1385 match choose_codecs_with(policy, &caps, false, pref, true) {
1386 Some(p) if p.primary.codec == VideoCodec::Vp8 => {
1387 plan = p;
1388 plan.reason = "h264_open_failed";
1389 encs = open(VideoCodec::Vp8, plan.primary.capability.clone()).await?;
1390 }
1391 _ => {}
1392 }
1393 }
1394 if encs.is_empty() {
1395 return Err(VideoError::CodecUnavailable);
1396 }
1397 let (codec, cap) = (plan.primary.codec, plan.primary.capability.clone());
1398 let layers: Vec<LayerSpec> = encs.iter().map(|e| e.spec.clone()).collect();
1399 let vp8 = match &plan.backup {
1400 Some(b) => Some(b.capability.clone()),
1401 None if codec == VideoCodec::Vp8 => Some(cap.clone()),
1402 None => caps
1403 .best(kessel_video::VideoCodec::Vp8, CodecDirection::Encode)
1404 .cloned(),
1405 };
1406 let backup = plan.backup.as_ref().map(|b| {
1407 let ladder =
1408 backup_ladder(&layers, PHONE, vp8_temporal(&b.capability, temporal_layers));
1409 BackupPipe::new(b.codec, ladder)
1410 });
1411 let mut req = VideoPublish::new(kind, codec, layers.clone(), size.0, size.1);
1412 if let Some(b) = &backup {
1413 req = req.with_backup(BackupSpec::new(b.codec, b.ladder.clone()));
1414 }
1415 let publication = call.publish_video(req).await?;
1416 tracing::info!(target: "sew_call_client", source = ?kind, codec = codec.as_str(), layers = layers.len(), backup = backup.as_ref().map(|b| b.ladder.len()), width = size.0, height = size.1, "video source on");
1417 let live = Arc::new(Mutex::new(codec));
1418 let stop = Arc::new(AtomicBool::new(false));
1419 let ended = Arc::new(AtomicBool::new(false));
1420 let self_key = Arc::new(AtomicBool::new(false));
1421 lock(&self.self_keys).insert(kind, (Arc::clone(&self_key), Arc::clone(&bell)));
1422 let held = Arc::new(AtomicBool::new(false));
1423 let (to_pipe, from_bridge) = std::sync::mpsc::channel();
1424 let mut pipe = Pipe {
1425 backend,
1426 kind,
1427 codec,
1428 content,
1429 src,
1430 facing,
1431 was_facing: facing,
1432 facing_since_us: 0,
1433 released_us: None,
1434 self_rid: self_view_rid(kind, &layers),
1435 encs: encs.into_iter().map(|e| (e.spec.rid.clone(), e)).collect(),
1436 publication,
1437 ctl: call.video_ctl(),
1438 taps: self.taps.clone(),
1439 stop: stop.clone(),
1440 ended: ended.clone(),
1441 self_key,
1442 bell: bell.clone(),
1443 from_bridge,
1444 paused: false,
1445 hidden: false,
1446 hidden_why: None,
1447 fresh_since_us: 0,
1448 held: Arc::clone(&held),
1449 scene_paused: false,
1450 end_asked: false,
1451 call: call.local_id(),
1452 backup,
1453 vp8,
1454 temporal: temporal_layers,
1455 live: live.clone(),
1456 phone: PHONE,
1457 machine: self.backend().subscribe(),
1458 thermal: kessel_video::ThermalLevel::Nominal,
1459 backup_converts: Arc::default(),
1460 };
1461 let name = match kind {
1462 VideoSource::Camera => "sew-video-camera",
1463 VideoSource::ScreenShare => "sew-video-screen",
1464 };
1465 let thread = std::thread::Builder::new()
1466 .name(name.to_owned())
1467 .spawn(move || pipe.run())
1468 .map_err(|e| VideoError::PublishFailed(format!("spawn: {e}")))?;
1469 Ok(Running {
1470 call: call.local_id(),
1471 stop,
1472 ended,
1473 bell,
1474 to_pipe,
1475 thread: Some(thread),
1476 codec,
1477 live,
1478 cap,
1479 layers,
1480 size,
1481 device,
1482 temporal: temporal_layers,
1483 held,
1484 })
1485 }
1486
1487 async fn switch(
1493 &self,
1494 call: &Call,
1495 slot: &mut Option<Running>,
1496 policy: &sew_proto::voice::MediaPolicy,
1497 req: CameraRequest,
1498 ) -> Result<CameraState, VideoError> {
1499 let Some(r) = slot.as_mut() else {
1500 return Err(VideoError::NotPublished);
1501 };
1502 let bell = Arc::clone(&r.bell);
1503 let began = std::time::Instant::now();
1504 release_source(r).await?;
1507 let (src, size) = match self.open(req.device.clone(), policy, &bell).await {
1508 Ok(v) => v,
1509 Err(e) => {
1510 tracing::warn!(target: "sew_call_client", code = e.code(), device = ?req.device, "the new camera did not open: back to the old one");
1511 match self.open(r.device.clone(), policy, &bell).await {
1512 Ok((src, size)) => {
1513 let plan = VideoBridge::plan(
1514 policy,
1515 VideoSource::Camera,
1516 r.codec,
1517 &r.cap,
1518 r.temporal,
1519 size,
1520 );
1521 let plan = if same_rids(&plan, &r.layers) {
1522 plan
1523 } else {
1524 r.layers.clone()
1525 };
1526 let facing = self.capture.camera_facing(r.device.as_deref());
1527 if r.to_pipe
1528 .send(ToPipe::Source(src, plan.clone(), facing))
1529 .is_err()
1530 {
1531 return Err(VideoError::Ended);
1532 }
1533 r.bell.ring();
1534 r.layers = plan;
1535 r.size = size;
1536 tracing::info!(target: "sew_call_client", gap_ms = began.elapsed().as_millis() as u64, "the old camera is back");
1537 }
1538 Err(e2) => {
1539 tracing::warn!(target: "sew_call_client", code = e2.code(), "the old camera did not open again: camera_lost");
1540 if let Some(r) = slot.take() {
1541 stop_running(r).await;
1542 }
1543 let reason = CaptureEnd::DeviceLost.reason(CaptureKind::Camera);
1544 let _ = self.taps.events.send(SourceNote {
1545 source: VideoSource::Camera,
1546 event: CaptureEvent::Ended(CaptureEnd::DeviceLost),
1547 });
1548 let _ = call
1549 .unpublish_video_because(VideoSource::Camera, true, reason)
1550 .await;
1551 }
1552 }
1553 return Err(e);
1554 }
1555 };
1556 let plan = VideoBridge::plan(
1557 policy,
1558 VideoSource::Camera,
1559 r.codec,
1560 &r.cap,
1561 req.temporal_layers,
1562 size,
1563 );
1564 if same_rids(&plan, &r.layers) {
1565 let facing = self.capture.camera_facing(req.device.as_deref());
1566 if r.to_pipe
1567 .send(ToPipe::Source(src, plan.clone(), facing))
1568 .is_err()
1569 {
1570 return Err(VideoError::Ended);
1571 }
1572 r.bell.ring();
1573 r.layers = plan;
1574 r.size = size;
1575 r.device = req.device.clone();
1576 tracing::info!(target: "sew_call_client", device = ?req.device, gap_ms = began.elapsed().as_millis() as u64, "the camera switched");
1577 return Ok(r.state());
1578 }
1579 if let Some(r) = slot.take() {
1580 stop_running(r).await;
1581 }
1582 tracing::info!(target: "sew_call_client", "the camera switches with a new layer set: published again");
1583 call.unpublish_video_because(VideoSource::Camera, false, CAMERA_SWITCH)
1584 .await?;
1585 let r = self
1586 .start_from(
1587 call,
1588 policy,
1589 VideoSource::Camera,
1590 Feed {
1591 src,
1592 size,
1593 facing: self.capture.camera_facing(req.device.as_deref()),
1594 },
1595 req.temporal_layers,
1596 req.device.clone(),
1597 bell,
1598 )
1599 .await?;
1600 let state = r.state();
1601 *slot = Some(r);
1602 Ok(state)
1603 }
1604
1605 pub async fn pause_camera(&self, paused: bool) -> bool {
1611 let slot = self.camera.lock().await;
1612 let Some(r) = slot.as_ref() else {
1613 return false;
1614 };
1615 if r.to_pipe.send(ToPipe::Pause(paused)).is_err() {
1616 return false;
1617 }
1618 r.bell.ring();
1619 true
1620 }
1621
1622 pub async fn reopen_held_camera(&self, call: &Call) -> bool {
1629 let mut slot = self.camera.lock().await;
1630 let Some(r) = slot
1631 .as_mut()
1632 .filter(|r| r.alive() && r.call == call.local_id() && r.held.load(Ordering::SeqCst))
1633 else {
1634 return false;
1635 };
1636 let Some(policy) = call.media_policy() else {
1637 return false;
1638 };
1639 tracing::info!(target: "sew_call_client", "the camera opens again: still paused by the background after the app came back");
1640 let began = std::time::Instant::now();
1641 if release_source(r).await.is_err() {
1643 return false;
1644 }
1645 let bell = Arc::clone(&r.bell);
1646 let (src, size) = match self.open(r.device.clone(), &policy, &bell).await {
1647 Ok(v) => v,
1648 Err(e) => {
1649 tracing::info!(target: "sew_call_client", code = e.code(), "the camera did not open again: it stays paused");
1651 r.held.store(true, Ordering::SeqCst);
1652 return false;
1653 }
1654 };
1655 let plan = VideoBridge::plan(
1656 &policy,
1657 VideoSource::Camera,
1658 r.codec,
1659 &r.cap,
1660 r.temporal,
1661 size,
1662 );
1663 let plan = if same_rids(&plan, &r.layers) {
1664 plan
1665 } else {
1666 r.layers.clone()
1667 };
1668 let facing = self.capture.camera_facing(r.device.as_deref());
1669 if r.to_pipe
1670 .send(ToPipe::Source(src, plan.clone(), facing))
1671 .is_err()
1672 {
1673 return false;
1674 }
1675 r.bell.ring();
1676 r.layers = plan;
1677 r.size = size;
1678 tracing::info!(target: "sew_call_client", gap_ms = began.elapsed().as_millis() as u64, "the camera is back after the background");
1679 true
1680 }
1681
1682 pub async fn close_call(&self, call: u64) {
1686 let mut all: Vec<Running> = {
1687 let mut feeds = self.feeds.lock().await;
1688 let kinds: Vec<VideoSource> = feeds
1689 .iter()
1690 .filter(|(_, r)| r.call == call)
1691 .map(|(k, _)| *k)
1692 .collect();
1693 kinds.iter().filter_map(|k| feeds.remove(k)).collect()
1694 };
1695 {
1696 let mut cam = self.camera.lock().await;
1697 if cam.as_ref().is_some_and(|r| r.call == call) {
1698 all.extend(cam.take());
1699 }
1700 }
1701 for r in all {
1702 stop_running(r).await;
1703 }
1704 }
1705
1706 pub async fn close(&self) {
1708 let mut all: Vec<Running> = self.feeds.lock().await.drain().map(|(_, r)| r).collect();
1709 all.extend(self.camera.lock().await.take());
1710 for r in all {
1711 stop_running(r).await;
1712 }
1713 }
1714}
1715
1716struct Pipe {
1718 backend: Arc<dyn VideoBackend>,
1719 kind: VideoSource,
1720 codec: VideoCodec,
1721 content: ContentHint,
1722 src: Box<dyn FrameSource>,
1723 facing: Facing,
1725 was_facing: Facing,
1727 facing_since_us: u64,
1728 released_us: Option<u64>,
1730 encs: BTreeMap<String, Enc>,
1731 self_rid: Option<String>,
1733 publication: VideoPublication,
1734 ctl: VideoCtl,
1735 taps: Taps,
1736 stop: Arc<AtomicBool>,
1737 ended: Arc<AtomicBool>,
1738 self_key: Arc<AtomicBool>,
1740 bell: Arc<Bell>,
1741 from_bridge: std::sync::mpsc::Receiver<ToPipe>,
1742 paused: bool,
1745 hidden: bool,
1747 hidden_why: Option<CapturePause>,
1749 fresh_since_us: u64,
1753 held: Arc<AtomicBool>,
1756 scene_paused: bool,
1758 end_asked: bool,
1760 call: u64,
1762 backup: Option<BackupPipe>,
1764 vp8: Option<CodecCapability>,
1766 temporal: Option<u8>,
1768 live: Arc<Mutex<VideoCodec>>,
1770 phone: bool,
1772 machine: kessel_video::EventRx,
1774 thermal: kessel_video::ThermalLevel,
1776 backup_converts: Arc<std::sync::atomic::AtomicU64>,
1778}
1779
1780struct BackupPipe {
1782 codec: VideoCodec,
1783 ladder: Vec<LayerSpec>,
1785 encs: BTreeMap<String, Enc>,
1786 on: bool,
1788 pending: Vec<LayerSpec>,
1790 retry_at: Option<std::time::Instant>,
1791 retried: bool,
1793 last_rates: Vec<LayerRate>,
1795}
1796
1797impl BackupPipe {
1798 fn new(codec: VideoCodec, ladder: Vec<LayerSpec>) -> BackupPipe {
1799 BackupPipe {
1800 codec,
1801 ladder,
1802 encs: BTreeMap::new(),
1803 on: false,
1804 pending: Vec::new(),
1805 retry_at: None,
1806 retried: false,
1807 last_rates: Vec::new(),
1808 }
1809 }
1810
1811 fn any_active(&self) -> bool {
1812 self.on && self.encs.values().any(|e| e.active)
1813 }
1814
1815 fn close(&mut self) {
1817 self.on = false;
1818 self.encs.clear();
1819 self.pending.clear();
1820 self.retry_at = None;
1821 self.last_rates.clear();
1822 }
1823}
1824
1825impl Pipe {
1826 fn run(&mut self) {
1827 self.pump();
1828 self.ended.store(true, Ordering::SeqCst);
1829 self.to_self_view(SelfViewItem::Ended { source: self.kind });
1830 self.tap_feed(CameraFeed::Off);
1831 }
1832
1833 fn pump(&mut self) {
1834 let sender = self.publication.sender();
1835 while !self.stop.load(Ordering::SeqCst) {
1836 if !self.controls() {
1837 return;
1838 }
1839 while let Ok(m) = self.from_bridge.try_recv() {
1840 match m {
1841 ToPipe::Source(src, sizes, facing) => {
1842 self.src = src;
1843 self.was_facing = self.facing;
1846 self.facing = facing;
1847 self.facing_since_us = self
1848 .released_us
1849 .take()
1850 .unwrap_or_else(|| self.backend.now_us());
1851 self.hidden_why = None;
1852 if std::mem::take(&mut self.hidden) {
1853 let _ = self.taps.events.send(SourceNote {
1855 source: self.kind,
1856 event: CaptureEvent::Resumed,
1857 });
1858 }
1859 self.src.set_paused(self.paused);
1860 for e in self.encs.values_mut() {
1864 e.key_owed = true;
1865 }
1866 for l in sizes {
1867 if let Some(e) = self.encs.get_mut(&l.rid)
1868 && (e.spec.width, e.spec.height) != (l.width, l.height)
1869 {
1870 let _ = e.enc.set_size(l.width, l.height);
1871 e.spec.width = l.width;
1872 e.spec.height = l.height;
1873 }
1874 if let Some(b) = self.backup.as_mut() {
1875 if let Some(r) = b.ladder.iter_mut().find(|r| r.rid == l.rid) {
1877 r.width = l.width;
1878 r.height = l.height;
1879 }
1880 if let Some(e) = b.encs.get_mut(&l.rid) {
1881 e.key_owed = true;
1882 if (e.spec.width, e.spec.height) != (l.width, l.height) {
1883 let _ = e.enc.set_size(l.width, l.height);
1884 e.spec.width = l.width;
1885 e.spec.height = l.height;
1886 }
1887 }
1888 }
1889 }
1890 }
1891 ToPipe::Release(done) => {
1892 self.src = Box::new(Released);
1893 self.released_us = Some(self.backend.now_us());
1894 let _ = done.send(());
1895 }
1896 ToPipe::Pause(p) => self.scene(p),
1897 }
1898 }
1899 if !self.source_events() {
1900 return;
1901 }
1902 self.backup_retry();
1903 if self.end_asked {
1904 return;
1905 }
1906 self.machine_events();
1907 let self_view = self.self_view_open();
1908 self.repause(self_view || self.tapped());
1909 if self.self_key.swap(false, Ordering::AcqRel)
1910 && let Some(e) = self.self_rid.as_ref().and_then(|r| self.encs.get_mut(r))
1911 {
1912 e.enc.request_keyframe();
1913 }
1914 if self.background_held() {
1915 if let Some(frame) = self.latest()
1918 && frame.capture_us >= self.fresh_since_us
1919 {
1920 tracing::info!(target: "sew_call_client", source = ?self.kind, "the video source runs again after a background pause it never ended");
1921 self.resume_hidden();
1922 let _ = self.taps.events.send(SourceNote {
1923 source: self.kind,
1924 event: CaptureEvent::Resumed,
1925 });
1926 self.to_taps(&frame);
1927 self.submit(&frame, self_view);
1928 }
1929 } else if !self.hidden
1930 && !self.scene_paused
1931 && let Some(frame) = self.latest()
1932 {
1933 self.to_taps(&frame);
1934 self.submit(&frame, self_view);
1935 }
1936 self.held.store(self.background_held(), Ordering::SeqCst);
1937 self.drain(&sender);
1938 self.bell.wait(Duration::from_millis(20));
1939 }
1940 }
1941
1942 fn source_events(&mut self) -> bool {
1944 while let Some(ev) = self.src.try_event() {
1945 let Some(ev) = map_event(ev) else { continue };
1946 let mut over = false;
1947 match &ev {
1948 CaptureEvent::Paused(why) => {
1949 tracing::info!(target: "sew_call_client", source = ?self.kind, ?why, "the video source paused");
1950 self.tap_feed(CameraFeed::Paused);
1951 self.hidden = true;
1952 self.hidden_why = Some(*why);
1953 if *why == CapturePause::Background {
1954 self.fresh_since_us = self.fresh_since_us.max(self.backend.now_us());
1956 }
1957 }
1958 CaptureEvent::Resumed => {
1959 if self.hidden {
1961 self.resume_hidden();
1962 }
1963 }
1964 CaptureEvent::Ended(end) => {
1965 let reason = end.reason(capture_kind(self.kind));
1966 tracing::info!(target: "sew_call_client", source = ?self.kind, reason, "the video source ended");
1967 self.ctl.end(self.kind, reason);
1968 over = true;
1969 }
1970 _ => {}
1971 }
1972 let _ = self.taps.events.send(SourceNote {
1973 source: self.kind,
1974 event: ev,
1975 });
1976 if over {
1977 return false;
1978 }
1979 }
1980 true
1981 }
1982
1983 fn self_view_open(&self) -> bool {
1984 lock(&self.taps.self_view)
1985 .as_ref()
1986 .is_some_and(|tx| !tx.is_closed())
1987 }
1988
1989 fn tapped(&self) -> bool {
1991 self.kind == VideoSource::Camera && self.taps.camera.any()
1992 }
1993
1994 fn to_taps(&self, frame: &kessel_video::VideoFrame) {
1997 if self.kind != VideoSource::Camera {
1998 return;
1999 }
2000 let facing = if frame.capture_us >= self.facing_since_us {
2001 self.facing
2002 } else {
2003 self.was_facing
2004 };
2005 self.taps.camera.frame(frame, facing);
2006 }
2007
2008 fn tap_feed(&self, feed: CameraFeed) {
2010 if self.kind == VideoSource::Camera {
2011 self.taps.camera.feed(feed);
2012 }
2013 }
2014
2015 fn to_self_view(&self, item: SelfViewItem) {
2016 let full = match lock(&self.taps.self_view).as_ref() {
2017 Some(tx) => matches!(tx.try_send(item), Err(mpsc::error::TrySendError::Full(_))),
2018 None => false,
2019 };
2020 if full {
2021 self.self_key.store(true, Ordering::Release);
2023 }
2024 }
2025
2026 fn repause(&mut self, self_view: bool) {
2029 let want = !self.scene_paused
2030 && (self_view
2031 || self.encs.values().any(|e| e.active)
2032 || self.backup.as_ref().is_some_and(BackupPipe::any_active));
2033 if want == self.paused {
2034 self.paused = !want;
2035 self.src.set_paused(self.paused);
2036 }
2037 }
2038
2039 fn controls(&mut self) -> bool {
2041 while let Some(c) = self.publication.try_control() {
2042 match c {
2043 VideoControl::Keyframe { rid } => {
2044 if let Some(e) = self.encs.get_mut(&rid) {
2045 e.enc.request_keyframe();
2046 }
2047 }
2048 VideoControl::Rates(rates) => {
2049 for r in rates {
2050 if let Some(e) = self.encs.get_mut(&r.rid) {
2051 e.active = r.active;
2052 if r.active {
2053 let _ = e
2054 .enc
2055 .set_rates(Rates::new(r.bitrate_bps.max(10_000), r.fps.max(1)));
2056 }
2057 }
2058 }
2059 }
2060 VideoControl::Republish(layers) => self.relayer(layers),
2061 VideoControl::Ended { reason } => {
2062 tracing::info!(target: "sew_call_client", source = ?self.kind, %reason, "the video publication ended");
2063 return false;
2064 }
2065 VideoControl::BackupStart(layers) => self.backup_start(layers),
2066 VideoControl::BackupRates(rates) => self.backup_rates(rates),
2067 VideoControl::BackupKeyframe { rid } => {
2068 if let Some(e) = self.backup.as_mut().and_then(|b| b.encs.get_mut(&rid)) {
2069 e.enc.request_keyframe();
2070 }
2071 }
2072 VideoControl::BackupStop => {
2073 if let Some(b) = self.backup.as_mut() {
2074 tracing::info!(target: "sew_call_client", source = ?self.kind, encoders = b.encs.len(), "the backup stops: its encoders close");
2075 b.close();
2076 }
2077 }
2078 }
2079 if self.end_asked {
2080 return true;
2081 }
2082 }
2083 true
2084 }
2085
2086 fn background_held(&self) -> bool {
2088 self.hidden && !self.scene_paused && self.hidden_why == Some(CapturePause::Background)
2089 }
2090
2091 fn resume_hidden(&mut self) {
2093 self.hidden = false;
2094 self.hidden_why = None;
2095 for e in self.encs.values_mut() {
2096 e.enc.request_keyframe();
2097 }
2098 for e in self.backup.iter_mut().flat_map(|b| b.encs.values_mut()) {
2099 e.enc.request_keyframe();
2100 }
2101 }
2102
2103 fn scene(&mut self, paused: bool) {
2107 if paused == self.scene_paused {
2108 return;
2109 }
2110 self.scene_paused = paused;
2111 if paused {
2112 tracing::info!(target: "sew_call_client", "the camera pauses (background)");
2113 self.tap_feed(CameraFeed::Paused);
2114 } else {
2115 tracing::info!(target: "sew_call_client", "the camera resumes with a keyframe");
2116 self.fresh_since_us = self.fresh_since_us.max(self.backend.now_us());
2117 while self.src.try_recv().is_some() {}
2118 for e in self.encs.values_mut() {
2119 e.enc.request_keyframe();
2120 }
2121 for e in self.backup.iter_mut().flat_map(|b| b.encs.values_mut()) {
2122 e.enc.request_keyframe();
2123 }
2124 }
2125 let self_view = self.self_view_open();
2126 self.repause(self_view || self.tapped());
2127 }
2128
2129 fn relayer(&mut self, layers: Vec<LayerSpec>) {
2131 self.self_rid = self_view_rid(self.kind, &layers);
2132 if let Some(b) = self.backup.as_mut() {
2133 b.close();
2135 b.ladder = backup_layers_for(&layers, &b.ladder);
2136 }
2137 let wake = self.bell.wake();
2138 let mut next = BTreeMap::new();
2139 for l in layers {
2140 match self.encs.remove(&l.rid) {
2141 Some(mut e) => {
2142 if (e.spec.width, e.spec.height) != (l.width, l.height) {
2143 let _ = e.enc.set_size(l.width, l.height);
2144 }
2145 let _ = e.enc.set_rates(Rates::new(
2146 l.max_kbps.saturating_mul(1000).max(10_000),
2147 l.fps.max(1),
2148 ));
2149 e.spec = l.clone();
2150 next.insert(l.rid.clone(), e);
2151 }
2152 None => match open_encoder(&self.backend, self.codec, &l, self.content, &wake) {
2153 Ok(enc) => {
2154 next.insert(
2155 l.rid.clone(),
2156 Enc {
2157 spec: l,
2158 enc,
2159 active: true,
2160 key_owed: false,
2161 },
2162 );
2163 }
2164 Err(e) => {
2165 tracing::info!(target: "sew_call_client", rid = %l.rid, error = %e, "a republished layer's encoder did not open");
2166 }
2167 },
2168 }
2169 }
2170 self.encs = next;
2171 }
2172
2173 fn machine_events(&mut self) {
2176 while let Some(ev) = self.machine.try_recv() {
2177 let kessel_video::BackendEvent::Thermal(level) = ev else {
2178 continue;
2179 };
2180 if !self.phone || self.backup.is_none() || level == self.thermal {
2181 continue;
2182 }
2183 self.thermal = level;
2184 let caps = thermal_backup_caps(level);
2185 tracing::info!(target: "sew_call_client", ?level, max_layers = ?caps.max_layers, max_fps = ?caps.max_fps, "thermal pressure: the backup's caps");
2186 self.ctl.backup_caps(caps);
2187 }
2188 }
2189
2190 fn backup_start(&mut self, layers: Vec<LayerSpec>) {
2192 let Some(b) = self.backup.as_mut() else {
2193 return;
2194 };
2195 b.on = true;
2196 for l in &layers {
2197 match b.ladder.iter_mut().find(|r| r.rid == l.rid) {
2198 Some(r) => *r = l.clone(),
2199 None => b.ladder.push(l.clone()),
2200 }
2201 }
2202 tracing::info!(target: "sew_call_client", source = ?self.kind, layers = layers.len(), "the backup starts: its encoders open");
2203 self.backup_open(layers);
2204 }
2205
2206 fn backup_rates(&mut self, rates: Vec<LayerRate>) {
2208 let Some(b) = self.backup.as_mut() else {
2209 return;
2210 };
2211 if !b.on {
2212 return;
2213 }
2214 let open: Vec<LayerSpec> = rates
2215 .iter()
2216 .filter(|r| r.active && !b.encs.contains_key(&r.rid))
2217 .filter(|r| !b.pending.iter().any(|p| p.rid == r.rid))
2218 .filter_map(|r| b.ladder.iter().find(|l| l.rid == r.rid).cloned())
2219 .collect();
2220 if !open.is_empty() {
2221 self.backup_open(open);
2222 }
2223 let Some(b) = self.backup.as_mut() else {
2224 return;
2225 };
2226 b.last_rates.clone_from(&rates);
2227 for r in rates {
2228 if let Some(e) = b.encs.get_mut(&r.rid) {
2229 e.active = r.active;
2230 if r.active {
2231 let _ = e
2232 .enc
2233 .set_rates(Rates::new(r.bitrate_bps.max(10_000), r.fps.max(1)));
2234 }
2235 }
2236 }
2237 }
2238
2239 fn backup_open(&mut self, layers: Vec<LayerSpec>) {
2243 let wake = self.bell.wake();
2244 let Some(b) = self.backup.as_mut() else {
2245 return;
2246 };
2247 let mut failed = Vec::new();
2248 for l in layers {
2249 if b.encs.contains_key(&l.rid) {
2250 continue;
2251 }
2252 match open_encoder(&self.backend, b.codec, &l, self.content, &wake) {
2253 Ok(mut enc) => {
2254 enc.request_keyframe();
2255 let r = b.last_rates.iter().find(|r| r.rid == l.rid && r.active);
2257 if let Some(r) = r {
2258 let _ = enc.set_rates(Rates::new(r.bitrate_bps.max(10_000), r.fps.max(1)));
2259 }
2260 b.encs.insert(
2261 l.rid.clone(),
2262 Enc {
2263 spec: l,
2264 enc,
2265 active: r.is_some(),
2266 key_owed: false,
2267 },
2268 );
2269 }
2270 Err(e) => {
2271 tracing::info!(target: "sew_call_client", rid = %l.rid, error = %e, "a backup encoder did not open");
2272 failed.push(l);
2273 }
2274 }
2275 }
2276 if failed.is_empty() {
2277 if b.pending.is_empty() {
2278 b.retried = false;
2279 }
2280 return;
2281 }
2282 if b.retried {
2283 self.fall_back_to_vp8("the backup's encoder did not open again");
2284 return;
2285 }
2286 b.pending.extend(failed);
2287 b.retry_at = Some(std::time::Instant::now() + BACKUP_RETRY);
2288 }
2289
2290 fn backup_retry(&mut self) {
2292 let Some(b) = self.backup.as_mut() else {
2293 return;
2294 };
2295 if b.retry_at.is_none_or(|t| std::time::Instant::now() < t) {
2296 return;
2297 }
2298 b.retry_at = None;
2299 b.retried = true;
2300 let pending = std::mem::take(&mut b.pending);
2301 if b.on {
2302 tracing::info!(target: "sew_call_client", layers = pending.len(), "the backup's encoders: the one retry");
2303 self.backup_open(pending);
2304 }
2305 }
2306
2307 fn fall_back_to_vp8(&mut self, why: &str) {
2312 if let Some(mut b) = self.backup.take() {
2313 b.close();
2314 }
2315 let Some(cap) = self.vp8.clone() else {
2316 tracing::info!(target: "sew_call_client", source = ?self.kind, why, "no VP8 encoder to fall back to: unpublishing");
2317 self.end_asked = true;
2318 self.ctl.end(self.kind, ENCODER_LOST);
2319 return;
2320 };
2321 let tl = vp8_temporal(&cap, self.temporal);
2322 let mut plan: Vec<LayerSpec> = self
2323 .encs
2324 .values()
2325 .map(|e| {
2326 let mut l = e.spec.clone();
2327 l.temporal_layers = tl;
2328 l
2329 })
2330 .collect();
2331 plan.sort_by_key(|l| (l.width.min(l.height), l.width.max(l.height)));
2332 self.encs.clear();
2334 let wake = self.bell.wake();
2335 let encs = open_encoders(
2336 &self.backend,
2337 VideoCodec::Vp8,
2338 &cap,
2339 plan,
2340 self.content,
2341 &wake,
2342 );
2343 if encs.is_empty() {
2344 tracing::info!(target: "sew_call_client", source = ?self.kind, why, "no VP8 encoder opened: unpublishing");
2345 self.end_asked = true;
2346 self.ctl.end(self.kind, ENCODER_LOST);
2347 return;
2348 }
2349 let layers: Vec<LayerSpec> = encs.iter().map(|e| e.spec.clone()).collect();
2350 tracing::info!(target: "sew_call_client", source = ?self.kind, why, layers = layers.len(), "published again in VP8 alone");
2351 self.codec = VideoCodec::Vp8;
2352 *lock(&self.live) = VideoCodec::Vp8;
2353 self.self_rid = self_view_rid(self.kind, &layers);
2354 self.encs = encs.into_iter().map(|e| (e.spec.rid.clone(), e)).collect();
2355 for e in self.encs.values_mut() {
2356 e.enc.request_keyframe();
2357 }
2358 self.publication
2359 .republish_without_backup(VideoCodec::Vp8, layers);
2360 }
2361
2362 fn latest(&mut self) -> Option<kessel_video::VideoFrame> {
2364 let mut last = None;
2365 while let Some(f) = self.src.try_recv() {
2366 last = Some(f);
2367 }
2368 last
2369 }
2370
2371 fn submit(&mut self, frame: &kessel_video::VideoFrame, self_view: bool) {
2374 let mut planes: Option<kessel_video::VideoFrame> = None;
2375 for (rid, e) in &mut self.encs {
2376 let for_self = self_view && self.self_rid.as_ref() == Some(rid);
2377 if !e.active && !for_self {
2378 continue;
2379 }
2380 match e.submit(frame) {
2381 Ok(()) => {}
2382 Err(KError::Unsupported(_)) if matches!(frame.buffer, FrameBuffer::Native(_)) => {
2383 if planes.is_none() {
2385 planes = self
2386 .backend
2387 .convert(frame, frame.width, frame.height, PixelFormat::I420)
2388 .ok();
2389 }
2390 if let Some(p) = &planes {
2391 let _ = e.submit(p);
2392 }
2393 }
2394 Err(_) => {}
2396 }
2397 }
2398 self.submit_backup(frame);
2399 }
2400
2401 fn submit_backup(&mut self, frame: &kessel_video::VideoFrame) {
2405 let Some(b) = self.backup.as_mut().filter(|b| b.any_active()) else {
2406 return;
2407 };
2408 let area = |w: u32, h: u32| u64::from(w) * u64::from(h);
2409 let Some((tw, th)) = b
2410 .encs
2411 .values()
2412 .filter(|e| e.active)
2413 .map(|e| (e.spec.width, e.spec.height))
2414 .max_by_key(|(w, h)| area(*w, *h))
2415 else {
2416 return;
2417 };
2418 let native = matches!(frame.buffer, FrameBuffer::Native(_));
2419 let converted = if native || area(frame.width, frame.height) > area(tw, th) {
2420 match self.backend.convert(frame, tw, th, PixelFormat::I420) {
2421 Ok(f) => {
2422 self.backup_converts.fetch_add(1, Ordering::Relaxed);
2423 Some(f)
2424 }
2425 Err(_) if native => return,
2427 Err(_) => None,
2428 }
2429 } else {
2430 None
2431 };
2432 let input = converted.as_ref().unwrap_or(frame);
2433 for e in b.encs.values_mut().filter(|e| e.active) {
2434 let _ = e.submit(input);
2436 }
2437 }
2438
2439 fn drain_backup(&mut self, sender: &VideoSender) {
2442 let Some(b) = self.backup.as_mut() else {
2443 return;
2444 };
2445 let mut dead = Vec::new();
2446 for (rid, e) in &mut b.encs {
2447 while let Some(r) = e.enc.poll() {
2448 match r {
2449 Ok(f) => {
2450 let Some(codec) = our_codec(f.codec) else {
2451 continue;
2452 };
2453 if !e.active || !b.on {
2454 continue;
2455 }
2456 sender.push(
2457 EncodedVideo::new(
2458 rid,
2459 codec,
2460 f.data,
2461 f.keyframe,
2462 f.capture_us,
2463 f.width,
2464 f.height,
2465 )
2466 .with_layer(f.layer.temporal_id, f.layer.layer_sync),
2467 );
2468 }
2469 Err(err) => {
2470 tracing::info!(target: "sew_call_client", rid = %rid, error = %err, "a backup encoder session was lost; reopening");
2471 dead.push(e.spec.clone());
2472 break;
2473 }
2474 }
2475 }
2476 }
2477 if dead.is_empty() {
2478 return;
2479 }
2480 for l in &dead {
2481 b.encs.remove(&l.rid);
2482 }
2483 self.backup_open(dead);
2484 }
2485
2486 fn drain(&mut self, sender: &VideoSender) {
2487 let mut dead = Vec::new();
2488 let mut local = Vec::new();
2489 for (rid, e) in &mut self.encs {
2490 let for_self = self.self_rid.as_ref() == Some(rid);
2491 while let Some(r) = e.enc.poll() {
2492 match r {
2493 Ok(f) => {
2494 let Some(codec) = our_codec(f.codec) else {
2495 continue;
2496 };
2497 if for_self {
2498 local.push(LocalFrame {
2499 codec,
2500 data: f.data.clone(),
2501 keyframe: f.keyframe,
2502 capture_us: f.capture_us,
2503 facing: if f.capture_us >= self.facing_since_us {
2504 self.facing
2505 } else {
2506 self.was_facing
2507 },
2508 width: f.width,
2509 height: f.height,
2510 });
2511 }
2512 if !e.active {
2513 continue;
2515 }
2516 sender.push(
2517 EncodedVideo::new(
2518 rid,
2519 codec,
2520 f.data,
2521 f.keyframe,
2522 f.capture_us,
2523 f.width,
2524 f.height,
2525 )
2526 .with_layer(f.layer.temporal_id, f.layer.layer_sync),
2527 );
2528 }
2529 Err(err) => {
2530 tracing::info!(target: "sew_call_client", rid = %rid, error = %err, "an encoder session was lost; reopening");
2531 dead.push(rid.clone());
2532 break;
2533 }
2534 }
2535 }
2536 }
2537 for frame in local {
2538 self.to_self_view(SelfViewItem::Frame {
2539 source: self.kind,
2540 frame,
2541 });
2542 }
2543 let wake = self.bell.wake();
2544 let any_dead = !dead.is_empty();
2545 for rid in dead {
2546 let Some(e) = self.encs.get_mut(&rid) else {
2547 continue;
2548 };
2549 match open_encoder(&self.backend, self.codec, &e.spec, self.content, &wake) {
2550 Ok(mut enc) => {
2551 enc.request_keyframe();
2552 e.enc = enc;
2553 }
2554 Err(err) if self.codec == VideoCodec::H264 => {
2555 tracing::info!(target: "sew_call_client", rid = %rid, error = %err, "the hardware H.264 encoder was lost and did not reopen");
2558 *lock(&self.taps.h264_lost) = Some(self.call);
2559 self.fall_back_to_vp8("the hardware H.264 encoder was lost");
2560 return;
2561 }
2562 Err(err) => {
2563 tracing::info!(target: "sew_call_client", rid = %rid, error = %err, "a lost encoder did not reopen: its layer stops");
2564 self.encs.remove(&rid);
2565 }
2566 }
2567 }
2568 self.drain_backup(sender);
2569 if any_dead && self.encs.is_empty() && !self.end_asked {
2570 tracing::info!(target: "sew_call_client", source = ?self.kind, "no encoder left: unpublishing");
2571 self.end_asked = true;
2572 self.ctl.end(self.kind, ENCODER_LOST);
2573 }
2574 }
2575}
2576
2577#[cfg(test)]
2578mod tests {
2579 use super::*;
2580 use kessel_video::{CodecCapability, Implementation};
2581
2582 fn caps(codecs: &[kessel_video::VideoCodec]) -> Capabilities {
2583 let mut c = Capabilities::new("test", "test");
2584 for k in codecs {
2585 c.codecs.push(CodecCapability::new(
2586 *k,
2587 CodecDirection::Encode,
2588 Implementation::Software,
2589 "enc",
2590 1280,
2591 720,
2592 30,
2593 ));
2594 }
2595 c
2596 }
2597
2598 #[test]
2599 #[allow(deprecated)]
2600 fn vp8_first_then_h264_and_only_what_the_policy_lists() {
2601 use sew_proto::voice::VideoCodec as P;
2602 let both = caps(&[
2603 kessel_video::VideoCodec::H264,
2604 kessel_video::VideoCodec::Vp8,
2605 ]);
2606 let pick = |policy: &[P], c: &Capabilities| choose_codec(policy, c).map(|(c, _)| c);
2607 assert_eq!(pick(&[P::Vp8, P::H264], &both), Some(VideoCodec::Vp8));
2608 assert_eq!(pick(&[P::H264, P::Vp8], &both), Some(VideoCodec::Vp8));
2609 assert_eq!(pick(&[P::H264], &both), Some(VideoCodec::H264));
2610 let h264_only = caps(&[kessel_video::VideoCodec::H264]);
2611 assert_eq!(pick(&[P::Vp8, P::H264], &h264_only), Some(VideoCodec::H264));
2612 assert_eq!(pick(&[P::Vp8], &h264_only), None, "codec_unavailable");
2613 assert_eq!(pick(&[], &both), None);
2614 }
2615
2616 fn caps_of(
2618 backend: &'static str,
2619 encoders: &[(kessel_video::VideoCodec, Implementation)],
2620 ) -> Capabilities {
2621 let mut c = Capabilities::new(backend, "test");
2622 for (k, i) in encoders {
2623 c.codecs.push(CodecCapability::new(
2624 *k,
2625 CodecDirection::Encode,
2626 *i,
2627 "enc",
2628 1920,
2629 1080,
2630 30,
2631 ));
2632 }
2633 c
2634 }
2635
2636 pub(super) fn media_policy(
2637 codecs: &[sew_proto::voice::VideoCodec],
2638 backup: bool,
2639 ) -> sew_proto::voice::MediaPolicy {
2640 let hint = sew_proto::voice::TrackHint {
2641 max_width: 1280,
2642 max_height: 720,
2643 max_fps: 30,
2644 layers: Vec::new(),
2645 };
2646 {
2647 let mut media_policy = sew_proto::voice::MediaPolicy::new(
2648 sew_proto::voice::MediaTier::Normal,
2649 hint.clone(),
2650 hint,
2651 );
2652 media_policy.video_enabled = true;
2653 media_policy.e2ee = "required".to_owned();
2654 media_policy.audio_codecs = vec!["opus".to_owned()];
2655 media_policy.codecs = codecs.to_vec();
2656 media_policy.backup_codec = backup;
2657 media_policy.vp9 = None;
2658 media_policy.dynacast = true;
2659 media_policy.adaptive_stream = true;
2660 media_policy.camera_allowed = true;
2661 media_policy.screen_allowed = true;
2662 media_policy.relay_only = false;
2663 media_policy
2664 }
2665 }
2666
2667 fn shape(p: Option<CodecPlan>) -> Option<(VideoCodec, Option<VideoCodec>, &'static str)> {
2669 p.map(|p| (p.primary.codec, p.backup.map(|b| b.codec), p.reason))
2670 }
2671
2672 #[test]
2673 #[cfg(feature = "testing")]
2674 fn h264_with_a_vp8_backup_only_when_every_rule_holds() {
2675 use kessel_video::VideoCodec as K;
2676 use sew_proto::voice::VideoCodec as P;
2677 let hw = caps_of(
2678 "fixture",
2679 &[
2680 (K::Vp8, Implementation::Software),
2681 (K::H264, Implementation::Hardware),
2682 ],
2683 );
2684 let auto = CodecPreference::Automatic;
2685 let plan =
2686 |pol: &sew_proto::voice::MediaPolicy,
2687 c: &Capabilities,
2688 dec: bool,
2689 pref: CodecPreference,
2690 lost: bool| shape(choose_codecs_with(pol, c, dec, pref, lost));
2691 let both = media_policy(&[P::Vp8, P::H264], true);
2692 let want = Some((VideoCodec::H264, Some(VideoCodec::Vp8), "h264_detected"));
2694 assert_eq!(plan(&both, &hw, true, auto, false), want);
2695 let h264_first = media_policy(&[P::H264, P::Vp8], true);
2696 assert_eq!(plan(&h264_first, &hw, true, auto, false), want);
2697 let vp8 = Some((VideoCodec::Vp8, None, "backup_off"));
2699 let off = media_policy(&[P::Vp8, P::H264], false);
2700 assert_eq!(plan(&off, &hw, true, auto, false), vp8);
2701 let mut no_dyn = both.clone();
2702 no_dyn.dynacast = false;
2703 assert_eq!(plan(&no_dyn, &hw, true, auto, false), vp8);
2704 assert_eq!(
2705 plan(&media_policy(&[P::Vp8], true), &hw, true, auto, false),
2706 vp8
2707 );
2708 let only = media_policy(&[P::H264], true);
2710 assert_eq!(
2711 plan(&only, &hw, true, auto, false),
2712 Some((VideoCodec::H264, None, "backup_off"))
2713 );
2714 assert_eq!(
2716 plan(&both, &hw, false, auto, false),
2717 Some((VideoCodec::Vp8, None, "no_h264_decode"))
2718 );
2719 assert_eq!(plan(&only, &hw, false, auto, false), None);
2720 assert_eq!(
2722 plan(&both, &hw, true, auto, true),
2723 Some((VideoCodec::Vp8, None, "h264_lost"))
2724 );
2725 assert_eq!(
2727 plan(&both, &hw, true, CodecPreference::PreferVp8, false),
2728 Some((VideoCodec::Vp8, None, "preferred_vp8"))
2729 );
2730 assert_eq!(
2731 plan(&both, &hw, true, CodecPreference::PreferH264, false),
2732 Some((VideoCodec::H264, Some(VideoCodec::Vp8), "preferred_h264"))
2733 );
2734 let sw = caps_of(
2735 "fixture",
2736 &[
2737 (K::Vp8, Implementation::Software),
2738 (K::H264, Implementation::Software),
2739 ],
2740 );
2741 assert_eq!(
2742 plan(&both, &sw, true, CodecPreference::PreferH264, false),
2743 Some((VideoCodec::Vp8, None, "h264_not_detected"))
2744 );
2745 let h264_only = caps_of("fixture", &[(K::H264, Implementation::Hardware)]);
2747 assert_eq!(
2748 plan(&both, &h264_only, true, auto, false),
2749 Some((VideoCodec::H264, None, "h264_not_detected"))
2750 );
2751 }
2752
2753 #[test]
2754 fn a_software_h264_encoder_is_never_usable() {
2755 use kessel_video::VideoCodec as K;
2756 use sew_proto::voice::VideoCodec as P;
2757 for backend in ["fixture", "apple", "android", "windows", "linux"] {
2761 let sw = caps_of(
2762 backend,
2763 &[
2764 (K::Vp8, Implementation::Software),
2765 (K::H264, Implementation::Software),
2766 ],
2767 );
2768 let both = media_policy(&[P::Vp8, P::H264], true);
2769 let p = choose_codecs_with(&both, &sw, true, CodecPreference::Automatic, false);
2770 assert_eq!(
2771 shape(p),
2772 Some((VideoCodec::Vp8, None, "h264_not_detected")),
2773 "{backend}"
2774 );
2775 let only = media_policy(&[P::H264], true);
2776 let p = choose_codecs_with(&only, &sw, true, CodecPreference::Automatic, false);
2777 assert_eq!(shape(p), None, "{backend}: codec_unavailable");
2778 }
2779 let vp8 = caps_of("apple", &[(K::Vp8, Implementation::Software)]);
2780 assert_eq!(
2782 shape(choose_codecs(&media_policy(&[P::Vp8, P::H264], true), &vp8))
2783 .map(|(c, b, _)| (c, b)),
2784 Some((VideoCodec::Vp8, None))
2785 );
2786 assert_eq!(
2787 choose_codecs(&media_policy(&[], true), &caps_of("apple", &[])),
2788 None
2789 );
2790 }
2791
2792 #[test]
2793 fn only_macos_and_ios_publish_os_h264() {
2794 use kessel_video::VideoCodec as K;
2795 use sew_proto::voice::VideoCodec as P;
2796 let os_allowed = cfg!(any(target_os = "macos", target_os = "ios"));
2799 for backend in ["apple", "android", "windows", "linux"] {
2800 let hw = caps_of(
2801 backend,
2802 &[
2803 (K::Vp8, Implementation::Software),
2804 (K::H264, Implementation::Hardware),
2805 ],
2806 );
2807 let both = media_policy(&[P::Vp8, P::H264], true);
2808 let got = shape(choose_codecs_with(
2809 &both,
2810 &hw,
2811 true,
2812 CodecPreference::Automatic,
2813 false,
2814 ));
2815 if os_allowed {
2816 assert_eq!(got.map(|g| g.1), Some(Some(VideoCodec::Vp8)), "{backend}");
2817 } else {
2818 assert_eq!(
2819 got,
2820 Some((VideoCodec::Vp8, None, "h264_not_detected")),
2821 "{backend}"
2822 );
2823 }
2824 }
2825 #[cfg(target_os = "linux")]
2826 {
2827 let hw = caps_of("linux", &[(K::H264, Implementation::Hardware)]);
2828 let only = media_policy(&[P::H264], true);
2829 for pref in [
2830 CodecPreference::Automatic,
2831 CodecPreference::PreferH264,
2832 CodecPreference::PreferVp8,
2833 ] {
2834 assert_eq!(
2835 choose_codecs_with(&only, &hw, true, pref, false),
2836 None,
2837 "Linux never publishes H.264"
2838 );
2839 }
2840 }
2841 }
2842
2843 #[test]
2844 #[cfg(all(feature = "testing", sew_fixtures))]
2845 fn an_h264_session_opens_hardware_only_and_must_report_hardware() {
2846 use super::super::fixture::{FixtureBackend, FixtureH264, FixtureOptions};
2847 let dir = concat!(
2848 env!("CARGO_MANIFEST_DIR"),
2849 "/../sew-media-testclient/fixtures"
2850 );
2851 let wake: Wake = Arc::new(|| {});
2852 let l = LayerSpec::new("q", 320, 180, 150, 30);
2853 let cfg = encoder_config(VideoCodec::H264, &l, ContentHint::Camera);
2854 assert_eq!(cfg.implementation, ImplPreference::HardwareOnly);
2855 let cfg = encoder_config(VideoCodec::Vp8, &l, ContentHint::Camera);
2856 assert_eq!(cfg.implementation, ImplPreference::PreferHardware);
2857 let cap = CodecCapability::new(
2858 kessel_video::VideoCodec::H264,
2859 CodecDirection::Encode,
2860 Implementation::Hardware,
2861 "hw",
2862 1280,
2863 720,
2864 30,
2865 );
2866 let plan = vec![
2867 LayerSpec::new("q", 320, 180, 150, 30),
2868 LayerSpec::new("h", 640, 360, 500, 30),
2869 ];
2870 for (mode, ok) in [
2874 (FixtureH264::Software, false),
2875 (FixtureH264::HardwareOpenFails, false),
2876 (FixtureH264::HardwareReportsSoftware, false),
2877 (FixtureH264::HardwareReportsUnknown, false),
2878 (FixtureH264::Hardware, true),
2879 ] {
2880 let fx = FixtureBackend::load_with(dir, FixtureOptions::new().with_h264(mode))
2881 .expect("the fixtures");
2882 let b: Arc<dyn VideoBackend> = fx.clone();
2883 let one = open_encoder(&b, VideoCodec::H264, &l, ContentHint::Camera, &wake);
2884 assert_eq!(one.is_ok(), ok, "{mode:?}");
2885 drop(one);
2886 let encs = open_encoders(
2887 &b,
2888 VideoCodec::H264,
2889 &cap,
2890 plan.clone(),
2891 ContentHint::Camera,
2892 &wake,
2893 );
2894 assert_eq!(encs.len(), if ok { 2 } else { 0 }, "{mode:?}");
2895 drop(encs);
2896 assert_eq!(
2897 fx.encoders_open(kessel_video::VideoCodec::H264),
2898 0,
2899 "{mode:?}"
2900 );
2901 assert!(open_encoder(&b, VideoCodec::Vp8, &l, ContentHint::Camera, &wake).is_ok());
2903 }
2904 }
2905
2906 #[test]
2909 fn apple_h264_names() {
2910 for (name, hw) in [
2911 ("VideoToolbox H.264 (hardware)", true),
2912 (
2913 "VideoToolbox H.264 (hardware, low-latency rate control)",
2914 false,
2915 ),
2916 ("VideoToolbox H.264 (software)", false),
2917 (
2918 "VideoToolbox H.264 (hardware or software: the OS doesn't say)",
2919 false,
2920 ),
2921 (
2922 "VideoToolbox H.264 (hardware, low-latency rate control, encoder com.apple.videotoolbox.videoencoder.ave.avc)",
2923 true,
2924 ),
2925 (
2926 "VideoToolbox H.264 (hardware, low-latency rate control, encoder com.apple.videotoolbox.videoencoder.h264.rtvc)",
2927 false,
2928 ),
2929 (
2931 "VideoToolbox H.264 (hardware, encoder com.apple.videotoolbox.videoencoder.ave.avc, Constrained High)",
2932 true,
2933 ),
2934 (
2935 "VideoToolbox H.264 (hardware, encoder com.apple.videotoolbox.videoencoder.ave.avc, Constrained High, low-latency rate control)",
2936 true,
2937 ),
2938 (
2939 "VideoToolbox H.264 (software, encoder com.apple.videotoolbox.videoencoder.h264.rtvc, Constrained High, low-latency rate control)",
2940 false,
2941 ),
2942 (
2943 "VideoToolbox H.264 (hardware, encoder com.apple.videotoolbox.videoencoder.h264.rtvc, High)",
2944 false,
2945 ),
2946 (
2947 "VideoToolbox H.264 (hardware, encoder not named, High)",
2948 true,
2949 ),
2950 (
2951 "VideoToolbox H.264 (hardware, encoder not named, High, low-latency rate control)",
2952 false,
2953 ),
2954 ("", false),
2955 ] {
2956 assert_eq!(apple_h264_name_is_hardware(name), hw, "{name}");
2957 }
2958 }
2959
2960 fn queued(rx: &mut mpsc::Receiver<super::super::publish::VideoIn>) -> Vec<bool> {
2962 let mut out = Vec::new();
2963 while let Ok(f) = rx.try_recv() {
2964 out.push(f.frame.keyframe);
2965 }
2966 out
2967 }
2968
2969 fn collect_until(
2970 rx: &mut mpsc::Receiver<super::super::publish::VideoIn>,
2971 what: &str,
2972 n: usize,
2973 ) -> Vec<bool> {
2974 let until = std::time::Instant::now() + Duration::from_secs(10);
2975 let mut got = Vec::new();
2976 while got.len() < n {
2977 assert!(
2978 std::time::Instant::now() < until,
2979 "timed out waiting for {what}"
2980 );
2981 got.extend(queued(rx));
2982 std::thread::sleep(Duration::from_millis(5));
2983 }
2984 got
2985 }
2986
2987 #[test]
2988 fn a_background_pause_stops_capture_and_encoding_and_the_return_starts_at_a_keyframe() {
2989 let backend: Arc<dyn VideoBackend> = HwFake::new(kessel_video::fake::FakeConfig::default());
2990 let bell = Arc::new(Bell::default());
2991 let src = backend
2992 .open_camera(None, CaptureConstraints::new(640, 360, 30), bell.wake())
2993 .expect("the fake camera opens");
2994 let cap = backend
2995 .capabilities()
2996 .best(kessel_video::VideoCodec::H264, CodecDirection::Encode)
2997 .expect("the fake's H.264")
2998 .clone();
2999 let encs = open_encoders(
3000 &backend,
3001 VideoCodec::H264,
3002 &cap,
3003 vec![LayerSpec::new("q", 320, 180, 150, 30)],
3004 ContentHint::Camera,
3005 &bell.wake(),
3006 );
3007 assert_eq!(encs.len(), 1);
3008 let (publication, mut rx, _ctl) = VideoPublication::for_test(VideoSource::Camera);
3009 let stop = Arc::new(AtomicBool::new(false));
3010 let (to_pipe, from_bridge) = std::sync::mpsc::channel();
3011 let (cmd, _cmds) = mpsc::unbounded_channel();
3012 let mut pipe = Pipe {
3013 backend: backend.clone(),
3014 kind: VideoSource::Camera,
3015 codec: VideoCodec::H264,
3016 content: ContentHint::Camera,
3017 src,
3018 facing: Facing::Unknown,
3019 was_facing: Facing::Unknown,
3020 facing_since_us: 0,
3021 released_us: None,
3022 encs: encs.into_iter().map(|e| (e.spec.rid.clone(), e)).collect(),
3023 self_rid: None,
3024 publication,
3025 ctl: VideoCtl::new(cmd),
3026 taps: Taps {
3027 events: broadcast::channel(EVENT_QUEUE).0,
3028 self_view: Arc::new(Mutex::new(None)),
3029 h264_lost: Arc::new(Mutex::new(None)),
3030 camera: CameraTaps::default(),
3031 },
3032 stop: stop.clone(),
3033 ended: Arc::new(AtomicBool::new(false)),
3034 self_key: Arc::new(AtomicBool::new(false)),
3035 bell: bell.clone(),
3036 from_bridge,
3037 paused: false,
3038 hidden: false,
3039 hidden_why: None,
3040 fresh_since_us: 0,
3041 held: Arc::default(),
3042 scene_paused: false,
3043 end_asked: false,
3044 call: 1,
3045 backup: None,
3046 vp8: None,
3047 temporal: None,
3048 live: Arc::new(Mutex::new(VideoCodec::H264)),
3049 phone: false,
3050 machine: backend.subscribe(),
3051 thermal: kessel_video::ThermalLevel::Nominal,
3052 backup_converts: Arc::default(),
3053 };
3054 let thread = std::thread::spawn(move || pipe.run());
3055
3056 let first = collect_until(&mut rx, "the first frames", 5);
3058 assert!(first[0], "the first frame is a keyframe");
3059 assert!(first[1..].iter().all(|k| !k), "then deltas only: {first:?}");
3060
3061 to_pipe.send(ToPipe::Pause(true)).expect("pause");
3063 bell.ring();
3064 std::thread::sleep(Duration::from_millis(100));
3065 let _ = queued(&mut rx);
3066 std::thread::sleep(Duration::from_millis(300));
3067 assert_eq!(queued(&mut rx), Vec::<bool>::new(), "no frame while paused");
3068 to_pipe.send(ToPipe::Pause(true)).expect("pause");
3070 bell.ring();
3071 std::thread::sleep(Duration::from_millis(100));
3072 assert!(queued(&mut rx).is_empty());
3073
3074 to_pipe.send(ToPipe::Pause(false)).expect("resume");
3076 bell.ring();
3077 let back = collect_until(&mut rx, "frames after the return", 4);
3078 assert!(back[0], "the return starts at a keyframe: {back:?}");
3079 assert!(back[1..].iter().all(|k| !k), "one keyframe: {back:?}");
3080
3081 stop.store(true, Ordering::SeqCst);
3082 bell.ring();
3083 thread.join().expect("the pipeline ends");
3084 }
3085
3086 #[test]
3087 fn a_source_that_ends_asks_the_engine_to_unpublish_with_its_reason() {
3088 let mut cfg = kessel_video::fake::FakeConfig::default();
3089 cfg.source_events = vec![(
3090 Duration::from_millis(300),
3091 SourceEvent::Ended(kessel_video::EndReason::DeviceLost),
3092 )];
3093 let backend: Arc<dyn VideoBackend> = HwFake::new(cfg);
3094 let bell = Arc::new(Bell::default());
3095 let src = backend
3096 .open_camera(None, CaptureConstraints::new(640, 360, 30), bell.wake())
3097 .expect("the fake camera opens");
3098 let cap = backend
3099 .capabilities()
3100 .best(kessel_video::VideoCodec::H264, CodecDirection::Encode)
3101 .expect("the fake's H.264")
3102 .clone();
3103 let encs = open_encoders(
3104 &backend,
3105 VideoCodec::H264,
3106 &cap,
3107 vec![LayerSpec::new("q", 320, 180, 150, 30)],
3108 ContentHint::Camera,
3109 &bell.wake(),
3110 );
3111 let (publication, mut rx, _ctl) = VideoPublication::for_test(VideoSource::Camera);
3112 let (cmd, mut cmds) = mpsc::unbounded_channel();
3113 let (_to_pipe, from_bridge) = std::sync::mpsc::channel();
3114 let mut pipe = Pipe {
3115 backend: backend.clone(),
3116 kind: VideoSource::Camera,
3117 codec: VideoCodec::H264,
3118 content: ContentHint::Camera,
3119 src,
3120 facing: Facing::Unknown,
3121 was_facing: Facing::Unknown,
3122 facing_since_us: 0,
3123 released_us: None,
3124 encs: encs.into_iter().map(|e| (e.spec.rid.clone(), e)).collect(),
3125 self_rid: None,
3126 publication,
3127 ctl: VideoCtl::new(cmd),
3128 taps: Taps {
3129 events: broadcast::channel(EVENT_QUEUE).0,
3130 self_view: Arc::new(Mutex::new(None)),
3131 h264_lost: Arc::new(Mutex::new(None)),
3132 camera: CameraTaps::default(),
3133 },
3134 stop: Arc::new(AtomicBool::new(false)),
3135 ended: Arc::new(AtomicBool::new(false)),
3136 self_key: Arc::new(AtomicBool::new(false)),
3137 bell: bell.clone(),
3138 from_bridge,
3139 paused: false,
3140 hidden: false,
3141 hidden_why: None,
3142 fresh_since_us: 0,
3143 held: Arc::default(),
3144 scene_paused: false,
3145 end_asked: false,
3146 call: 1,
3147 backup: None,
3148 vp8: None,
3149 temporal: None,
3150 live: Arc::new(Mutex::new(VideoCodec::H264)),
3151 phone: false,
3152 machine: backend.subscribe(),
3153 thermal: kessel_video::ThermalLevel::Nominal,
3154 backup_converts: Arc::default(),
3155 };
3156 let thread = std::thread::spawn(move || pipe.run());
3157 let _ = collect_until(&mut rx, "frames before the end", 2);
3158 let until = std::time::Instant::now() + Duration::from_secs(10);
3159 while !thread.is_finished() {
3160 assert!(
3161 std::time::Instant::now() < until,
3162 "the pipeline ends with its source"
3163 );
3164 std::thread::sleep(Duration::from_millis(10));
3165 }
3166 thread.join().expect("the pipeline ends");
3167 match cmds.try_recv().expect("the engine is asked to unpublish") {
3168 crate::call::Cmd::Publish(super::super::publish::VideoCmd::Unpublish {
3169 source,
3170 release,
3171 reason,
3172 ..
3173 }) => {
3174 assert_eq!(source, VideoSource::Camera);
3175 assert!(release, "the lease is released");
3176 assert_eq!(reason, "camera_lost");
3177 }
3178 _ => panic!("not an unpublish"),
3179 }
3180 assert!(cmds.try_recv().is_err(), "once");
3181 }
3182
3183 struct TestPipe {
3185 to_pipe: std::sync::mpsc::Sender<ToPipe>,
3186 rx: mpsc::Receiver<super::super::publish::VideoIn>,
3187 notes: broadcast::Receiver<SourceNote>,
3188 stop: Arc<AtomicBool>,
3189 bell: Arc<Bell>,
3190 thread: Option<std::thread::JoinHandle<()>>,
3191 ctl: mpsc::UnboundedSender<VideoControl>,
3192 cmds: mpsc::UnboundedReceiver<crate::call::Cmd>,
3193 fallbacks: mpsc::UnboundedReceiver<super::super::publish::ProducerFallback>,
3194 h264_lost: Arc<Mutex<Option<u64>>>,
3195 converts: Arc<std::sync::atomic::AtomicU64>,
3196 held: Arc<AtomicBool>,
3198 camera_taps: CameraTaps,
3200 }
3201
3202 impl TestPipe {
3203 fn start(
3205 backend: &Arc<dyn VideoBackend>,
3206 src: Box<dyn FrameSource>,
3207 bell: &Arc<Bell>,
3208 ) -> TestPipe {
3209 TestPipe::start_with(backend, src, bell, None)
3210 }
3211
3212 fn start_with(
3215 backend: &Arc<dyn VideoBackend>,
3216 src: Box<dyn FrameSource>,
3217 bell: &Arc<Bell>,
3218 backup: Option<Vec<LayerSpec>>,
3219 ) -> TestPipe {
3220 TestPipe::start_full(backend, src, bell, backup, false)
3221 }
3222
3223 fn start_full(
3225 backend: &Arc<dyn VideoBackend>,
3226 src: Box<dyn FrameSource>,
3227 bell: &Arc<Bell>,
3228 backup: Option<Vec<LayerSpec>>,
3229 phone: bool,
3230 ) -> TestPipe {
3231 let converts: Arc<std::sync::atomic::AtomicU64> = Arc::default();
3232 let vp8 = backend
3233 .capabilities()
3234 .best(kessel_video::VideoCodec::Vp8, CodecDirection::Encode)
3235 .cloned();
3236 let backup = backup.map(|l| BackupPipe::new(VideoCodec::Vp8, l));
3237 let h264_lost = Arc::new(Mutex::new(None));
3238 let cap = backend
3239 .capabilities()
3240 .best(kessel_video::VideoCodec::H264, CodecDirection::Encode)
3241 .expect("the fake's H.264")
3242 .clone();
3243 let encs = open_encoders(
3244 backend,
3245 VideoCodec::H264,
3246 &cap,
3247 vec![LayerSpec::new("q", 320, 180, 150, 30)],
3248 ContentHint::Camera,
3249 &bell.wake(),
3250 );
3251 assert_eq!(encs.len(), 1);
3252 let (publication, rx, ctl, _ends, fallbacks) =
3253 VideoPublication::for_test_with_fallbacks(VideoSource::Camera);
3254 let (cmd, cmds) = mpsc::unbounded_channel();
3255 let events = broadcast::channel(EVENT_QUEUE).0;
3256 let notes = events.subscribe();
3257 let stop = Arc::new(AtomicBool::new(false));
3258 let held = Arc::new(AtomicBool::new(false));
3259 let camera_taps = CameraTaps::default();
3260 let (to_pipe, from_bridge) = std::sync::mpsc::channel();
3261 let mut pipe = Pipe {
3262 backend: backend.clone(),
3263 kind: VideoSource::Camera,
3264 codec: VideoCodec::H264,
3265 content: ContentHint::Camera,
3266 src,
3267 facing: Facing::Front,
3268 was_facing: Facing::Front,
3269 facing_since_us: 0,
3270 released_us: None,
3271 encs: encs.into_iter().map(|e| (e.spec.rid.clone(), e)).collect(),
3272 self_rid: None,
3273 publication,
3274 ctl: VideoCtl::new(cmd),
3275 taps: Taps {
3276 events,
3277 self_view: Arc::new(Mutex::new(None)),
3278 h264_lost: h264_lost.clone(),
3279 camera: camera_taps.clone(),
3280 },
3281 stop: stop.clone(),
3282 ended: Arc::new(AtomicBool::new(false)),
3283 self_key: Arc::new(AtomicBool::new(false)),
3284 bell: bell.clone(),
3285 from_bridge,
3286 paused: false,
3287 hidden: false,
3288 hidden_why: None,
3289 fresh_since_us: 0,
3290 held: held.clone(),
3291 scene_paused: false,
3292 end_asked: false,
3293 call: 1,
3294 backup,
3295 vp8,
3296 temporal: None,
3297 live: Arc::new(Mutex::new(VideoCodec::H264)),
3298 phone,
3299 machine: backend.subscribe(),
3300 thermal: kessel_video::ThermalLevel::Nominal,
3301 backup_converts: converts.clone(),
3302 };
3303 let thread = std::thread::spawn(move || pipe.run());
3304 TestPipe {
3305 to_pipe,
3306 rx,
3307 notes,
3308 stop,
3309 bell: bell.clone(),
3310 thread: Some(thread),
3311 ctl,
3312 cmds,
3313 fallbacks,
3314 h264_lost,
3315 converts,
3316 held,
3317 camera_taps,
3318 }
3319 }
3320
3321 fn control(&self, c: VideoControl) {
3323 self.ctl.send(c).expect("the pipeline runs");
3324 self.bell.ring();
3325 }
3326
3327 fn frames_for(&mut self, within: Duration) -> Vec<(String, VideoCodec, bool)> {
3329 let until = std::time::Instant::now() + within;
3330 let mut out = Vec::new();
3331 while std::time::Instant::now() < until {
3332 while let Ok(f) = self.rx.try_recv() {
3333 out.push((f.frame.rid.clone(), f.frame.codec, f.frame.keyframe));
3334 }
3335 std::thread::sleep(Duration::from_millis(5));
3336 }
3337 out
3338 }
3339
3340 fn frames_until(
3343 &mut self,
3344 what: &str,
3345 enough: impl Fn(&[(String, VideoCodec, bool)]) -> bool,
3346 ) -> Vec<(String, VideoCodec, bool)> {
3347 let until = std::time::Instant::now() + Duration::from_secs(20);
3348 let mut out = Vec::new();
3349 while !enough(&out) {
3350 assert!(
3351 std::time::Instant::now() < until,
3352 "{what} within 20 s: {out:?}"
3353 );
3354 while let Ok(f) = self.rx.try_recv() {
3355 out.push((f.frame.rid.clone(), f.frame.codec, f.frame.keyframe));
3356 }
3357 std::thread::sleep(Duration::from_millis(5));
3358 }
3359 out
3360 }
3361
3362 fn drain_until(&mut self, what: &str, done: impl Fn() -> bool) {
3364 let until = std::time::Instant::now() + Duration::from_secs(5);
3365 while !done() {
3366 assert!(std::time::Instant::now() < until, "{what} within 5 s");
3367 while self.rx.try_recv().is_ok() {}
3368 std::thread::sleep(Duration::from_millis(5));
3369 }
3370 }
3371
3372 fn until_fallback(
3375 &mut self,
3376 ) -> (
3377 super::super::publish::ProducerFallback,
3378 Vec<(String, VideoCodec, bool)>,
3379 ) {
3380 let until = std::time::Instant::now() + Duration::from_secs(5);
3381 let mut seen = Vec::new();
3382 let f = loop {
3383 if let Ok(f) = self.fallbacks.try_recv() {
3384 break f;
3385 }
3386 assert!(
3387 std::time::Instant::now() < until,
3388 "no fall back to VP8 alone"
3389 );
3390 seen.extend(self.frames_for(Duration::from_millis(20)));
3391 };
3392 seen.extend(self.frames_for(Duration::from_millis(500)));
3393 (f, seen)
3394 }
3395
3396 fn send(&self, m: ToPipe) {
3397 self.to_pipe.send(m).expect("the pipeline runs");
3398 self.bell.ring();
3399 }
3400
3401 fn next_note(&mut self, what: &str) -> CaptureEvent {
3404 let until = std::time::Instant::now() + Duration::from_secs(10);
3405 loop {
3406 match self.notes.try_recv() {
3407 Ok(n) if is_state(&n.event) => return n.event,
3408 Ok(_) => {}
3409 Err(broadcast::error::TryRecvError::Empty) => {}
3410 Err(e) => panic!("{what}: the notes failed: {e}"),
3411 }
3412 assert!(
3413 std::time::Instant::now() < until,
3414 "timed out waiting for {what}"
3415 );
3416 std::thread::sleep(Duration::from_millis(5));
3417 }
3418 }
3419
3420 fn assert_quiet(&mut self, what: &str) {
3422 std::thread::sleep(Duration::from_millis(100));
3423 let _ = queued(&mut self.rx);
3424 std::thread::sleep(Duration::from_millis(300));
3425 assert_eq!(queued(&mut self.rx), Vec::<bool>::new(), "{what}");
3426 }
3427
3428 fn finish(mut self) {
3429 self.stop.store(true, Ordering::SeqCst);
3430 self.bell.ring();
3431 if let Some(t) = self.thread.take() {
3432 t.join().expect("the pipeline ends");
3433 }
3434 }
3435 }
3436
3437 struct HwFake {
3442 inner: Arc<dyn VideoBackend>,
3443 vp8_failures: std::sync::atomic::AtomicU32,
3444 vp8_live: Arc<std::sync::atomic::AtomicU64>,
3445 h264_epoch: Arc<std::sync::atomic::AtomicU64>,
3446 h264_refused: AtomicBool,
3447 lag: AtomicBool,
3449 }
3450
3451 impl HwFake {
3452 fn new(cfg: kessel_video::fake::FakeConfig) -> Arc<HwFake> {
3453 let mut cfg = cfg;
3454 cfg.codec = kessel_video::fake::FakeCodec::Structural;
3455 Arc::new(HwFake {
3456 inner: kessel_video::fake::FakeBackend::new(cfg),
3457 vp8_failures: Default::default(),
3458 vp8_live: Default::default(),
3459 h264_epoch: Default::default(),
3460 h264_refused: AtomicBool::new(false),
3461 lag: AtomicBool::new(false),
3462 })
3463 }
3464
3465 fn fail_vp8_opens(&self, n: u32) {
3466 self.vp8_failures.store(n, Ordering::SeqCst);
3467 }
3468
3469 fn vp8_open(&self) -> u64 {
3470 self.vp8_live.load(Ordering::SeqCst)
3471 }
3472
3473 fn lose_h264(&self) {
3474 self.h264_refused.store(true, Ordering::SeqCst);
3475 self.h264_epoch.fetch_add(1, Ordering::SeqCst);
3476 }
3477 }
3478
3479 struct Wrapped {
3482 inner: Box<dyn VideoEncoder>,
3483 lost: Option<(Arc<std::sync::atomic::AtomicU64>, u64)>,
3484 live: Option<Arc<std::sync::atomic::AtomicU64>>,
3485 lag: Option<Lag>,
3486 }
3487
3488 #[derive(Default)]
3492 struct Lag {
3493 held: Option<(kessel_video::VideoFrame, EncodeOptions)>,
3494 key_asked: bool,
3495 }
3496
3497 impl Drop for Wrapped {
3498 fn drop(&mut self) {
3499 if let Some(l) = &self.live {
3500 l.fetch_sub(1, Ordering::SeqCst);
3501 }
3502 }
3503 }
3504
3505 impl VideoEncoder for Wrapped {
3506 fn submit(
3507 &mut self,
3508 frame: &kessel_video::VideoFrame,
3509 opts: EncodeOptions,
3510 ) -> Result<(), KError> {
3511 let Some(lag) = self.lag.as_mut() else {
3512 return self.inner.submit(frame, opts);
3513 };
3514 if let Some((f, o)) = lag.held.replace((frame.clone(), opts)) {
3515 let key = o.keyframe || std::mem::take(&mut lag.key_asked);
3516 let o = if key {
3517 EncodeOptions::keyframe()
3518 } else {
3519 EncodeOptions::default()
3520 };
3521 self.inner.submit(&f, o)?;
3522 }
3523 Ok(())
3524 }
3525 fn poll(&mut self) -> Option<Result<kessel_video::EncodedFrame, KError>> {
3526 if let Some((epoch, at)) = &self.lost
3527 && epoch.load(Ordering::SeqCst) != *at
3528 {
3529 return Some(Err(KError::DeviceLost));
3530 }
3531 self.inner.poll()
3532 }
3533 fn request_keyframe(&mut self) {
3534 match self.lag.as_mut() {
3535 Some(lag) => lag.key_asked = true,
3536 None => self.inner.request_keyframe(),
3537 }
3538 }
3539 fn set_rates(&mut self, rates: Rates) -> Result<(), KError> {
3540 self.inner.set_rates(rates)
3541 }
3542 fn set_size(&mut self, width: u32, height: u32) -> Result<(), KError> {
3543 self.inner.set_size(width, height)
3544 }
3545 fn info(&self) -> kessel_video::EncoderInfo {
3546 self.inner.info()
3547 }
3548 fn stats(&self) -> kessel_video::EncoderStats {
3549 self.inner.stats()
3550 }
3551 fn implementation(&self) -> Implementation {
3552 if self.lost.is_some() {
3553 Implementation::Hardware
3554 } else {
3555 self.inner.implementation()
3556 }
3557 }
3558 }
3559
3560 impl VideoBackend for HwFake {
3561 fn capabilities(&self) -> Capabilities {
3562 let mut c = self.inner.capabilities();
3563 for e in &mut c.codecs {
3564 if e.codec == kessel_video::VideoCodec::H264 {
3565 e.implementation = Implementation::Hardware;
3566 }
3567 }
3568 c
3569 }
3570 fn now_us(&self) -> u64 {
3571 self.inner.now_us()
3572 }
3573 fn cameras(&self) -> Vec<kessel_video::CameraInfo> {
3574 self.inner.cameras()
3575 }
3576 fn camera_permission(&self) -> kessel_video::Permission {
3577 self.inner.camera_permission()
3578 }
3579 fn request_camera_permission(&self, done: kessel_video::Done<kessel_video::Permission>) {
3580 self.inner.request_camera_permission(done);
3581 }
3582 fn open_camera(
3583 &self,
3584 id: Option<&str>,
3585 constraints: CaptureConstraints,
3586 wake: Wake,
3587 ) -> Result<Box<dyn FrameSource>, KError> {
3588 self.inner.open_camera(id, constraints, wake)
3589 }
3590 fn screen_permission(&self) -> kessel_video::Permission {
3591 self.inner.screen_permission()
3592 }
3593 fn request_screen_permission(&self, done: kessel_video::Done<kessel_video::Permission>) {
3594 self.inner.request_screen_permission(done);
3595 }
3596 fn screen_sources(&self) -> Result<Vec<kessel_video::ScreenSourceInfo>, KError> {
3597 self.inner.screen_sources()
3598 }
3599 fn pick_screen(
3600 &self,
3601 opts: kessel_video::PickOptions,
3602 done: kessel_video::Done<Result<kessel_video::ScreenSelection, KError>>,
3603 ) {
3604 self.inner.pick_screen(opts, done);
3605 }
3606 fn open_screen(
3607 &self,
3608 source: &kessel_video::ScreenSelection,
3609 constraints: CaptureConstraints,
3610 wake: Wake,
3611 ) -> Result<Box<dyn FrameSource>, KError> {
3612 self.inner.open_screen(source, constraints, wake)
3613 }
3614 fn encoder(
3615 &self,
3616 mut config: EncoderConfig,
3617 wake: Wake,
3618 ) -> Result<Box<dyn VideoEncoder>, KError> {
3619 if config.codec.codec() == kessel_video::VideoCodec::H264 {
3620 if self.h264_refused.load(Ordering::SeqCst) {
3621 return Err(KError::NoResources);
3622 }
3623 config.implementation = ImplPreference::PreferHardware;
3625 let at = self.h264_epoch.load(Ordering::SeqCst);
3626 let inner = self.inner.encoder(config, wake)?;
3627 return Ok(Box::new(Wrapped {
3628 inner,
3629 lost: Some((self.h264_epoch.clone(), at)),
3630 live: None,
3631 lag: self.lag.load(Ordering::SeqCst).then(Lag::default),
3632 }));
3633 }
3634 let fail = self
3635 .vp8_failures
3636 .try_update(Ordering::SeqCst, Ordering::SeqCst, |n| n.checked_sub(1))
3637 .is_ok();
3638 if fail {
3639 return Err(KError::NoResources);
3640 }
3641 let inner = self.inner.encoder(config, wake)?;
3642 self.vp8_live.fetch_add(1, Ordering::SeqCst);
3643 Ok(Box::new(Wrapped {
3644 inner,
3645 lost: None,
3646 live: Some(self.vp8_live.clone()),
3647 lag: self.lag.load(Ordering::SeqCst).then(Lag::default),
3648 }))
3649 }
3650 fn decoder(
3651 &self,
3652 config: kessel_video::DecoderConfig,
3653 wake: Wake,
3654 ) -> Result<Box<dyn kessel_video::VideoDecoder>, KError> {
3655 self.inner.decoder(config, wake)
3656 }
3657 fn convert(
3658 &self,
3659 frame: &kessel_video::VideoFrame,
3660 width: u32,
3661 height: u32,
3662 format: PixelFormat,
3663 ) -> Result<kessel_video::VideoFrame, KError> {
3664 self.inner.convert(frame, width, height, format)
3665 }
3666 fn subscribe(&self) -> kessel_video::EventRx {
3667 self.inner.subscribe()
3668 }
3669 fn shutdown(&self) {
3670 self.inner.shutdown();
3671 }
3672 }
3673
3674 fn rate(rid: &str, active: bool) -> LayerRate {
3675 LayerRate {
3676 rid: rid.to_owned(),
3677 active,
3678 bitrate_bps: if active { 150_000 } else { 0 },
3679 fps: 30,
3680 }
3681 }
3682
3683 #[test]
3684 fn the_backup_runs_between_its_start_and_stop_from_the_same_capture() {
3685 let fake = HwFake::new(kessel_video::fake::FakeConfig::default());
3686 let backend: Arc<dyn VideoBackend> = fake.clone();
3687 let bell = Arc::new(Bell::default());
3688 let src = fake_camera(&backend, &bell);
3689 let q = LayerSpec::new("q", 320, 180, 150, 30);
3690 let mut p = TestPipe::start_with(&backend, src, &bell, Some(vec![q.clone()]));
3691 let count = |fs: &[(String, VideoCodec, bool)], c: VideoCodec| {
3692 fs.iter().filter(|f| f.1 == c).count()
3693 };
3694 let before = p.frames_until("3 H.264 frames", |fs| count(fs, VideoCodec::H264) >= 3);
3696 assert!(before.iter().all(|f| f.1 == VideoCodec::H264), "{before:?}");
3697 assert_eq!(
3698 fake.vp8_open(),
3699 0,
3700 "the backup's encoders open only on demand"
3701 );
3702 p.control(VideoControl::BackupStart(vec![q.clone()]));
3704 p.control(VideoControl::BackupRates(vec![rate("q", true)]));
3705 let on = p.frames_until("3 VP8 frames and the primary's", |fs| {
3706 count(fs, VideoCodec::Vp8) >= 3 && count(fs, VideoCodec::H264) >= 1
3707 });
3708 let vp8: Vec<&(String, VideoCodec, bool)> =
3709 on.iter().filter(|f| f.1 == VideoCodec::Vp8).collect();
3710 assert!(vp8[0].2, "the backup's first frame is a keyframe: {vp8:?}");
3711 assert!(vp8.iter().all(|f| f.0 == "q"));
3712 assert!(
3713 on.iter().any(|f| f.1 == VideoCodec::H264),
3714 "the primary goes on"
3715 );
3716 assert_eq!(fake.vp8_open(), 1);
3717 p.control(VideoControl::BackupKeyframe { rid: "q".into() });
3719 let _ = p.frames_until("a backup keyframe", |fs| {
3720 fs.iter().any(|f| f.1 == VideoCodec::Vp8 && f.2)
3721 });
3722 p.control(VideoControl::BackupStop);
3724 p.drain_until("the backup's encoder closed", || fake.vp8_open() == 0);
3725 let _ = p.frames_for(Duration::from_millis(200));
3727 let after = p.frames_until("3 H.264 frames", |fs| count(fs, VideoCodec::H264) >= 3);
3728 assert!(after.iter().all(|f| f.1 == VideoCodec::H264), "{after:?}");
3729 assert_eq!(fake.vp8_open(), 0, "the backup's encoder closed");
3730 assert!(p.fallbacks.try_recv().is_err(), "nothing fell back");
3731 p.finish();
3732 }
3733
3734 #[test]
3735 fn a_backup_that_does_not_open_is_tried_once_then_the_publication_goes_vp8_alone() {
3736 let fake = HwFake::new(kessel_video::fake::FakeConfig::default());
3737 let backend: Arc<dyn VideoBackend> = fake.clone();
3738 let bell = Arc::new(Bell::default());
3739 let src = fake_camera(&backend, &bell);
3740 let q = LayerSpec::new("q", 320, 180, 150, 30);
3741 let mut p = TestPipe::start_with(&backend, src, &bell, Some(vec![q.clone()]));
3742 fake.fail_vp8_opens(1);
3744 p.control(VideoControl::BackupStart(vec![q.clone()]));
3745 p.control(VideoControl::BackupRates(vec![rate("q", true)]));
3746 let early = p.frames_for(Duration::from_millis(600));
3747 assert!(early.iter().all(|f| f.1 == VideoCodec::H264), "{early:?}");
3748 let later = p.frames_for(Duration::from_millis(900));
3749 assert!(
3750 later.iter().any(|f| f.1 == VideoCodec::Vp8 && f.2),
3751 "the retry opened the backup: {later:?}"
3752 );
3753 assert!(p.fallbacks.try_recv().is_err());
3754 p.control(VideoControl::BackupStop);
3757 let _ = p.frames_for(Duration::from_millis(200));
3758 fake.fail_vp8_opens(2);
3759 p.control(VideoControl::BackupStart(vec![q.clone()]));
3760 p.control(VideoControl::BackupRates(vec![rate("q", true)]));
3761 let (f, seen) = p.until_fallback();
3762 assert_eq!(f.codec, VideoCodec::Vp8);
3763 let rids: Vec<&str> = f.layers.iter().map(|l| l.rid.as_str()).collect();
3764 assert_eq!(rids, vec!["q"]);
3765 assert_vp8_alone_from_a_keyframe(&seen);
3766 p.finish();
3767 }
3768
3769 fn assert_vp8_alone_from_a_keyframe(seen: &[(String, VideoCodec, bool)]) {
3771 let at = seen
3772 .iter()
3773 .position(|f| f.1 == VideoCodec::Vp8)
3774 .unwrap_or_else(|| panic!("no VP8 frame after the fall back: {seen:?}"));
3775 assert!(seen[at].2, "a keyframe first: {seen:?}");
3776 let rest = &seen[at..];
3777 assert!(rest.len() >= 3, "{seen:?}");
3778 assert!(
3779 rest.iter().all(|f| f.1 == VideoCodec::Vp8),
3780 "VP8 alone: {seen:?}"
3781 );
3782 }
3783
3784 #[test]
3785 fn a_lost_hardware_encoder_publishes_vp8_alone_and_h264_is_not_tried_again() {
3786 let fake = HwFake::new(kessel_video::fake::FakeConfig::default());
3787 let backend: Arc<dyn VideoBackend> = fake.clone();
3788 let bell = Arc::new(Bell::default());
3789 let src = fake_camera(&backend, &bell);
3790 let q = LayerSpec::new("q", 320, 180, 150, 30);
3791 let mut p = TestPipe::start_with(&backend, src, &bell, Some(vec![q]));
3792 let before = p.frames_for(Duration::from_millis(300));
3793 assert!(before.iter().any(|f| f.1 == VideoCodec::H264));
3794 fake.lose_h264();
3795 let (f, seen) = p.until_fallback();
3796 assert_eq!(f.codec, VideoCodec::Vp8);
3797 assert_eq!(*lock(&p.h264_lost), Some(1), "no H.264 again in this call");
3798 assert_vp8_alone_from_a_keyframe(&seen);
3799 assert!(
3800 p.cmds.try_recv().is_err(),
3801 "not unpublished: the lease is kept"
3802 );
3803 p.finish();
3804 }
3805
3806 #[test]
3807 fn the_backups_ladder_is_the_primarys_and_a_phones_stops_at_360p() {
3808 let layers = vec![
3809 LayerSpec::new("q", 320, 180, 150, 30),
3810 LayerSpec::new("h", 640, 360, 500, 30),
3811 LayerSpec::new("f", 1280, 720, 1700, 30),
3812 ];
3813 let rids = |l: &[LayerSpec]| l.iter().map(|x| x.rid.clone()).collect::<Vec<_>>();
3814 let desk = backup_ladder(&layers, false, 3);
3815 assert_eq!(rids(&desk), vec!["q", "h", "f"]);
3816 assert!(desk.iter().all(|l| l.temporal_layers == 3));
3817 assert_eq!(rids(&backup_ladder(&layers, true, 2)), vec!["q", "h"]);
3818 let portrait = vec![
3820 LayerSpec::new("q", 180, 320, 150, 30),
3821 LayerSpec::new("h", 360, 640, 500, 30),
3822 LayerSpec::new("f", 720, 1280, 1700, 30),
3823 ];
3824 assert_eq!(rids(&backup_ladder(&portrait, true, 1)), vec!["q", "h"]);
3825 let big = vec![LayerSpec::new("f", 1280, 720, 1700, 30)];
3827 assert_eq!(rids(&backup_ladder(&big, true, 1)), vec!["f"]);
3828 }
3829
3830 #[test]
3831 fn one_capture_feeds_both_codecs_and_the_backup_converts_once_per_frame() {
3832 let fake = HwFake::new(kessel_video::fake::FakeConfig::default());
3833 let backend: Arc<dyn VideoBackend> = fake.clone();
3834 let bell = Arc::new(Bell::default());
3835 let src = backend
3837 .open_camera(None, CaptureConstraints::new(1280, 720, 30), bell.wake())
3838 .expect("the fake camera opens");
3839 let q = LayerSpec::new("q", 320, 180, 150, 30);
3840 let h = LayerSpec::new("h", 640, 360, 500, 30);
3841 let mut p = TestPipe::start_with(&backend, src, &bell, Some(vec![q.clone(), h.clone()]));
3842 let _ = p.frames_until("3 frames", |fs| fs.len() >= 3);
3843 assert_eq!(
3844 p.converts.load(Ordering::SeqCst),
3845 0,
3846 "nothing is converted while the backup doesn't run"
3847 );
3848 p.control(VideoControl::BackupStart(vec![q, h]));
3849 p.control(VideoControl::BackupRates(vec![
3850 rate("q", true),
3851 rate("h", true),
3852 ]));
3853 let n = |fs: &[(String, VideoCodec, bool)], c: VideoCodec, rid: Option<&str>| {
3854 fs.iter()
3855 .filter(|f| f.1 == c && rid.is_none_or(|r| f.0 == r))
3856 .count() as u64
3857 };
3858 let on = p.frames_until("both codecs", |fs| {
3860 n(fs, VideoCodec::Vp8, Some("q")) >= 5
3861 && n(fs, VideoCodec::Vp8, Some("h")) >= 5
3862 && n(fs, VideoCodec::H264, None) >= 20
3863 });
3864 let converts = p.converts.load(Ordering::SeqCst);
3865 let (nq, nh) = (
3866 n(&on, VideoCodec::Vp8, Some("q")),
3867 n(&on, VideoCodec::Vp8, Some("h")),
3868 );
3869 let primary = n(&on, VideoCodec::H264, None);
3870 assert!(
3874 converts >= primary / 2 && converts <= primary + 5,
3875 "{converts} conversions for {primary} captured frames ({nq} q, {nh} h)"
3876 );
3877 p.control(VideoControl::BackupStop);
3878 p.drain_until("the backup's encoders closed", || fake.vp8_open() == 0);
3879 let _ = p.frames_for(Duration::from_millis(200));
3880 let c0 = p.converts.load(Ordering::SeqCst);
3881 let _ = p.frames_for(Duration::from_millis(400));
3882 assert_eq!(
3883 p.converts.load(Ordering::SeqCst),
3884 c0,
3885 "no conversion after the stop"
3886 );
3887 p.finish();
3888 }
3889
3890 #[test]
3891 fn heat_caps_a_phones_backup_but_never_stops_it() {
3892 use kessel_video::ThermalLevel as T;
3893 assert_eq!(thermal_backup_caps(T::Nominal), BackupCaps::default());
3894 assert_eq!(thermal_backup_caps(T::Fair), BackupCaps::default());
3895 assert_eq!(
3896 thermal_backup_caps(T::Serious),
3897 BackupCaps {
3898 max_layers: Some(1),
3899 max_fps: None
3900 }
3901 );
3902 assert_eq!(
3903 thermal_backup_caps(T::Critical),
3904 BackupCaps {
3905 max_layers: Some(1),
3906 max_fps: Some(15)
3907 }
3908 );
3909 let mut cfg = kessel_video::fake::FakeConfig::default();
3911 cfg.backend_events = vec![
3912 (
3913 Duration::from_millis(400),
3914 kessel_video::BackendEvent::Thermal(T::Serious),
3915 ),
3916 (
3917 Duration::from_millis(700),
3918 kessel_video::BackendEvent::Thermal(T::Critical),
3919 ),
3920 (
3921 Duration::from_millis(1000),
3922 kessel_video::BackendEvent::Thermal(T::Nominal),
3923 ),
3924 ];
3925 let fake = HwFake::new(cfg);
3926 let backend: Arc<dyn VideoBackend> = fake.clone();
3927 let bell = Arc::new(Bell::default());
3928 let src = fake_camera(&backend, &bell);
3929 let q = LayerSpec::new("q", 320, 180, 150, 30);
3930 let mut p = TestPipe::start_full(&backend, src, &bell, Some(vec![q]), true);
3931 let until = std::time::Instant::now() + Duration::from_secs(5);
3932 let mut got = Vec::new();
3933 while got.len() < 3 {
3934 assert!(std::time::Instant::now() < until, "caps so far: {got:?}");
3935 while let Ok(c) = p.cmds.try_recv() {
3936 if let crate::call::Cmd::Publish(super::super::publish::VideoCmd::BackupCaps(c)) = c
3937 {
3938 got.push(c);
3939 }
3940 }
3941 let _ = p.frames_for(Duration::from_millis(20));
3942 }
3943 assert_eq!(
3944 got,
3945 vec![
3946 thermal_backup_caps(T::Serious),
3947 thermal_backup_caps(T::Critical),
3948 BackupCaps::default()
3949 ]
3950 );
3951 p.finish();
3952 }
3953
3954 fn is_state(e: &CaptureEvent) -> bool {
3955 matches!(
3956 e,
3957 CaptureEvent::Paused(_) | CaptureEvent::Resumed | CaptureEvent::Ended(_)
3958 )
3959 }
3960
3961 fn fake_camera(backend: &Arc<dyn VideoBackend>, bell: &Arc<Bell>) -> Box<dyn FrameSource> {
3962 backend
3963 .open_camera(None, CaptureConstraints::new(640, 360, 30), bell.wake())
3964 .expect("the fake camera opens")
3965 }
3966
3967 #[test]
3970 fn a_camera_busy_pause_resumes_with_a_keyframe_when_it_ends() {
3971 let mut cfg = kessel_video::fake::FakeConfig::default();
3972 cfg.source_events = vec![
3973 (
3974 Duration::from_millis(400),
3975 SourceEvent::Interrupted(kessel_video::Interruption::InUseByAnother),
3976 ),
3977 (Duration::from_millis(1200), SourceEvent::Resumed),
3978 ];
3979 let backend: Arc<dyn VideoBackend> = HwFake::new(cfg);
3980 let bell = Arc::new(Bell::default());
3981 let src = fake_camera(&backend, &bell);
3982 let mut p = TestPipe::start(&backend, src, &bell);
3983 let first = collect_until(&mut p.rx, "the first frames", 3);
3984 assert!(first[0], "the first frame is a keyframe");
3985
3986 assert_eq!(
3987 p.next_note("the camera_busy pause"),
3988 CaptureEvent::Paused(CapturePause::InUseByAnother)
3989 );
3990 p.assert_quiet("no frame while another app holds the camera");
3991
3992 assert_eq!(p.next_note("the resume"), CaptureEvent::Resumed);
3993 let back = collect_until(&mut p.rx, "frames after the resume", 4);
3994 assert!(back[0], "the resume starts at a keyframe: {back:?}");
3995 assert!(back[1..].iter().all(|k| !k), "one keyframe: {back:?}");
3996 p.finish();
3997 }
3998
3999 #[test]
4004 fn a_background_pause_that_never_ends_resumes_on_the_frames_after_the_return() {
4005 let mut cfg = kessel_video::fake::FakeConfig::default();
4006 cfg.source_events = vec![(
4007 Duration::from_millis(400),
4008 SourceEvent::Interrupted(kessel_video::Interruption::Background),
4009 )];
4010 let backend: Arc<dyn VideoBackend> = HwFake::new(cfg);
4011 let bell = Arc::new(Bell::default());
4012 let src = fake_camera(&backend, &bell);
4013 let mut p = TestPipe::start(&backend, src, &bell);
4014 let _ = collect_until(&mut p.rx, "the first frames", 3);
4015 p.send(ToPipe::Pause(true));
4016 assert_eq!(
4017 p.next_note("the background pause"),
4018 CaptureEvent::Paused(CapturePause::Background)
4019 );
4020 p.assert_quiet("nothing sent in the background");
4021 assert!(
4022 !p.held.load(Ordering::SeqCst),
4023 "not held while the app is in the background"
4024 );
4025 p.send(ToPipe::Pause(false));
4026 assert_eq!(
4027 p.next_note("the pause over on the frames"),
4028 CaptureEvent::Resumed
4029 );
4030 let back = collect_until(&mut p.rx, "frames after the return", 4);
4031 assert!(back[0], "the return starts at a keyframe: {back:?}");
4032 assert!(back[1..].iter().all(|k| !k), "one keyframe: {back:?}");
4033 assert!(!p.held.load(Ordering::SeqCst), "not held once frames run");
4034 p.finish();
4035 }
4036
4037 #[test]
4040 fn a_background_pause_ended_before_the_return_waits_for_the_return() {
4041 let mut cfg = kessel_video::fake::FakeConfig::default();
4042 cfg.source_events = vec![
4043 (
4044 Duration::from_millis(400),
4045 SourceEvent::Interrupted(kessel_video::Interruption::Background),
4046 ),
4047 (Duration::from_millis(700), SourceEvent::Resumed),
4048 ];
4049 let backend: Arc<dyn VideoBackend> = HwFake::new(cfg);
4050 let bell = Arc::new(Bell::default());
4051 let src = fake_camera(&backend, &bell);
4052 let mut p = TestPipe::start(&backend, src, &bell);
4053 let _ = collect_until(&mut p.rx, "the first frames", 3);
4054 p.send(ToPipe::Pause(true));
4055 assert!(matches!(
4056 p.next_note("the background pause"),
4057 CaptureEvent::Paused(_)
4058 ));
4059 assert_eq!(p.next_note("the pause's end"), CaptureEvent::Resumed);
4060 p.assert_quiet("the app is still in the background");
4061 p.send(ToPipe::Pause(false));
4062 let back = collect_until(&mut p.rx, "frames after the return", 4);
4063 assert!(back[0], "the return starts at a keyframe: {back:?}");
4064 assert!(back[1..].iter().all(|k| !k), "one keyframe: {back:?}");
4065 let mut notes = Vec::new();
4066 while let Ok(n) = p.notes.try_recv() {
4067 notes.push(n.event);
4068 }
4069 assert!(!notes.iter().any(is_state), "no second resume: {notes:?}");
4070 p.finish();
4071 }
4072
4073 #[test]
4076 fn a_background_pause_ended_after_the_return_adds_no_keyframe() {
4077 let mut cfg = kessel_video::fake::FakeConfig::default();
4078 cfg.source_events = vec![
4079 (
4080 Duration::from_millis(400),
4081 SourceEvent::Interrupted(kessel_video::Interruption::Background),
4082 ),
4083 (Duration::from_millis(2500), SourceEvent::Resumed),
4084 ];
4085 let backend: Arc<dyn VideoBackend> = HwFake::new(cfg);
4086 let bell = Arc::new(Bell::default());
4087 let src = fake_camera(&backend, &bell);
4088 let mut p = TestPipe::start(&backend, src, &bell);
4089 let _ = collect_until(&mut p.rx, "the first frames", 3);
4090 p.send(ToPipe::Pause(true));
4091 assert!(matches!(
4092 p.next_note("the background pause"),
4093 CaptureEvent::Paused(_)
4094 ));
4095 p.send(ToPipe::Pause(false));
4096 assert_eq!(p.next_note("the frames' resume"), CaptureEvent::Resumed);
4097 let mut back = Vec::new();
4100 let until = std::time::Instant::now() + Duration::from_secs(10);
4101 loop {
4102 back.extend(queued(&mut p.rx));
4103 match p.notes.try_recv() {
4104 Ok(n) if is_state(&n.event) => {
4105 assert_eq!(n.event, CaptureEvent::Resumed, "the source's late resume");
4106 break;
4107 }
4108 _ => {}
4109 }
4110 assert!(
4111 std::time::Instant::now() < until,
4112 "timed out waiting for the late resume"
4113 );
4114 std::thread::sleep(Duration::from_millis(5));
4115 }
4116 back.extend(collect_until(&mut p.rx, "frames after the late resume", 4));
4117 assert!(back[0], "the return starts at a keyframe: {back:?}");
4118 assert!(back[1..].iter().all(|k| !k), "one keyframe: {back:?}");
4119 p.finish();
4120 }
4121
4122 #[test]
4125 fn only_a_background_pause_ends_on_frames() {
4126 let mut cfg = kessel_video::fake::FakeConfig::default();
4127 cfg.source_events = vec![(
4128 Duration::from_millis(400),
4129 SourceEvent::Interrupted(kessel_video::Interruption::InUseByAnother),
4130 )];
4131 let backend: Arc<dyn VideoBackend> = HwFake::new(cfg);
4132 let bell = Arc::new(Bell::default());
4133 let src = fake_camera(&backend, &bell);
4134 let mut p = TestPipe::start(&backend, src, &bell);
4135 let _ = collect_until(&mut p.rx, "the first frames", 3);
4136 assert!(matches!(p.next_note("the pause"), CaptureEvent::Paused(_)));
4137 p.send(ToPipe::Pause(true));
4138 p.send(ToPipe::Pause(false));
4139 p.assert_quiet("another app still holds the camera");
4140 assert!(!p.held.load(Ordering::SeqCst));
4141 p.finish();
4142 }
4143
4144 #[test]
4147 fn a_silent_background_pause_after_the_return_is_held() {
4148 let backend: Arc<dyn VideoBackend> = HwFake::new(kessel_video::fake::FakeConfig::default());
4149 let bell = Arc::new(Bell::default());
4150 let src: Box<dyn FrameSource> = Box::new(Silent(vec![SourceEvent::Interrupted(
4151 kessel_video::Interruption::Background,
4152 )]));
4153 let mut p = TestPipe::start(&backend, src, &bell);
4154 p.send(ToPipe::Pause(true));
4155 assert!(matches!(
4156 p.next_note("the background pause"),
4157 CaptureEvent::Paused(_)
4158 ));
4159 std::thread::sleep(Duration::from_millis(200));
4160 assert!(
4161 !p.held.load(Ordering::SeqCst),
4162 "the app is in the background"
4163 );
4164 p.send(ToPipe::Pause(false));
4165 wait_held(&p.held, true, "held after the return");
4166 p.send(ToPipe::Pause(true));
4167 wait_held(&p.held, false, "not held in the background again");
4168 p.finish();
4169 }
4170
4171 fn wait_held(held: &AtomicBool, want: bool, what: &str) {
4172 let until = std::time::Instant::now() + Duration::from_secs(10);
4173 while held.load(Ordering::SeqCst) != want {
4174 assert!(std::time::Instant::now() < until, "timed out: {what}");
4175 std::thread::sleep(Duration::from_millis(5));
4176 }
4177 }
4178
4179 struct Silent(Vec<SourceEvent>);
4181
4182 impl FrameSource for Silent {
4183 fn try_recv(&mut self) -> Option<kessel_video::VideoFrame> {
4184 None
4185 }
4186 fn try_event(&mut self) -> Option<SourceEvent> {
4187 (!self.0.is_empty()).then(|| self.0.remove(0))
4188 }
4189 fn set_constraints(&mut self, _c: CaptureConstraints) -> Result<(), KError> {
4190 Ok(())
4191 }
4192 fn set_paused(&mut self, _paused: bool) {}
4193 fn stats(&self) -> kessel_video::SourceStats {
4194 kessel_video::SourceStats::default()
4195 }
4196 }
4197
4198 #[test]
4203 fn a_released_source_holds_the_pipeline_and_the_next_one_starts_at_a_keyframe() {
4204 let mut cfg = kessel_video::fake::FakeConfig::default();
4205 cfg.source_events = vec![(
4206 Duration::from_millis(400),
4207 SourceEvent::Interrupted(kessel_video::Interruption::InUseByAnother),
4208 )];
4209 let old_backend: Arc<dyn VideoBackend> = HwFake::new(cfg);
4210 let backend: Arc<dyn VideoBackend> = HwFake::new(kessel_video::fake::FakeConfig::default());
4211 let bell = Arc::new(Bell::default());
4212 let src = fake_camera(&old_backend, &bell);
4213 let mut p = TestPipe::start(&backend, src, &bell);
4214 let _ = collect_until(&mut p.rx, "the first frames", 3);
4215 assert!(matches!(
4216 p.next_note("the old camera's pause"),
4217 CaptureEvent::Paused(_)
4218 ));
4219
4220 let (tx, done) = std::sync::mpsc::channel();
4221 p.send(ToPipe::Release(tx));
4222 done.recv_timeout(Duration::from_secs(5))
4223 .expect("the pipeline drops the source and says so");
4224 p.assert_quiet("no frame while released");
4225 assert!(
4226 p.thread.as_ref().is_some_and(|t| !t.is_finished()),
4227 "the publication is kept"
4228 );
4229
4230 let next = fake_camera(&backend, &bell);
4231 p.send(ToPipe::Source(
4232 next,
4233 vec![LayerSpec::new("q", 320, 180, 150, 30)],
4234 Facing::Back,
4235 ));
4236 assert_eq!(
4237 p.next_note("the pause reported over"),
4238 CaptureEvent::Resumed
4239 );
4240 let back = collect_until(&mut p.rx, "the new camera's frames", 4);
4241 assert!(back[0], "the new camera starts at a keyframe: {back:?}");
4242 assert!(back[1..].iter().all(|k| !k), "one keyframe: {back:?}");
4243 p.finish();
4244 }
4245
4246 #[test]
4249 fn a_switched_source_starts_at_a_keyframe() {
4250 let backend: Arc<dyn VideoBackend> = HwFake::new(kessel_video::fake::FakeConfig::default());
4251 let bell = Arc::new(Bell::default());
4252 let src = fake_camera(&backend, &bell);
4253 let mut p = TestPipe::start(&backend, src, &bell);
4254 let first = collect_until(&mut p.rx, "the first frames", 6);
4255 assert!(first[0] && first[1..].iter().all(|k| !k), "{first:?}");
4256 let (tx, done) = std::sync::mpsc::channel();
4257 p.send(ToPipe::Release(tx));
4258 done.recv_timeout(Duration::from_secs(5)).expect("released");
4259 p.assert_quiet("no frame while released");
4260 let next = fake_camera(&backend, &bell);
4261 p.send(ToPipe::Source(
4262 next,
4263 vec![LayerSpec::new("q", 320, 180, 150, 30)],
4264 Facing::Back,
4265 ));
4266 let back = collect_until(&mut p.rx, "the new camera's frames", 4);
4267 assert!(back[0], "the switch starts at a keyframe: {back:?}");
4268 let mut notes = Vec::new();
4269 while let Ok(n) = p.notes.try_recv() {
4270 notes.push(n.event);
4271 }
4272 assert!(
4273 !notes.iter().any(is_state),
4274 "no pause, no resume: {notes:?}"
4275 );
4276 p.finish();
4277 }
4278
4279 #[test]
4283 fn a_switch_keys_the_new_cameras_first_frame_not_a_pending_old_one() {
4284 let fake = HwFake::new(kessel_video::fake::FakeConfig::default());
4285 fake.lag.store(true, Ordering::SeqCst);
4286 let backend: Arc<dyn VideoBackend> = fake.clone();
4287 let bell = Arc::new(Bell::default());
4288 let src = fake_camera(&backend, &bell);
4289 let mut p = TestPipe::start(&backend, src, &bell);
4290 let _ = timed_until(&mut p.rx, "the first frames", 4);
4291 let (tx, done) = std::sync::mpsc::channel();
4292 p.send(ToPipe::Release(tx));
4293 done.recv_timeout(Duration::from_secs(5)).expect("released");
4294 let released = backend.now_us();
4295 let next = fake_camera(&backend, &bell);
4296 p.send(ToPipe::Source(
4297 next,
4298 vec![LayerSpec::new("q", 320, 180, 150, 30)],
4299 Facing::Back,
4300 ));
4301 let mut got = Vec::new();
4302 let until = std::time::Instant::now() + Duration::from_secs(10);
4303 while got.iter().filter(|(t, _)| *t >= released).count() < 3 {
4304 assert!(
4305 std::time::Instant::now() < until,
4306 "the new camera's frames: {got:?}"
4307 );
4308 got.extend(timed(&mut p.rx));
4309 std::thread::sleep(Duration::from_millis(5));
4310 }
4311 let old: Vec<bool> = got
4312 .iter()
4313 .filter(|(t, _)| *t < released)
4314 .map(|f| f.1)
4315 .collect();
4316 let new: Vec<bool> = got
4317 .iter()
4318 .filter(|(t, _)| *t >= released)
4319 .map(|f| f.1)
4320 .collect();
4321 assert!(
4322 !old.is_empty(),
4323 "the old camera's last frame came out after the switch (the lag): {got:?}"
4324 );
4325 assert!(
4326 new[0],
4327 "the new camera's first frame is a keyframe: {got:?}"
4328 );
4329 assert!(new[1..].iter().all(|k| !k), "one keyframe: {got:?}");
4330 assert!(
4331 !old.iter().any(|k| *k),
4332 "no keyframe on the old camera's last frame: {got:?}"
4333 );
4334 p.finish();
4335 }
4336
4337 fn timed(rx: &mut mpsc::Receiver<super::super::publish::VideoIn>) -> Vec<(u64, bool)> {
4339 let mut out = Vec::new();
4340 while let Ok(f) = rx.try_recv() {
4341 out.push((f.frame.capture_us, f.frame.keyframe));
4342 }
4343 out
4344 }
4345
4346 fn timed_until(
4347 rx: &mut mpsc::Receiver<super::super::publish::VideoIn>,
4348 what: &str,
4349 n: usize,
4350 ) -> Vec<(u64, bool)> {
4351 let until = std::time::Instant::now() + Duration::from_secs(10);
4352 let mut got = Vec::new();
4353 while got.len() < n {
4354 assert!(
4355 std::time::Instant::now() < until,
4356 "timed out waiting for {what}"
4357 );
4358 got.extend(timed(rx));
4359 std::thread::sleep(Duration::from_millis(5));
4360 }
4361 got
4362 }
4363
4364 #[test]
4365 fn phones_capture_at_most_720p() {
4366 assert_eq!(camera_box(1920, 1080, true), (1280, 720));
4367 assert_eq!(camera_box(1080, 1920, true), (720, 1280));
4368 assert_eq!(camera_box(640, 360, true), (640, 360));
4369 assert_eq!(camera_box(1920, 1080, false), (1920, 1080));
4370 }
4371
4372 #[test]
4373 fn encoders_open_from_the_top_and_drop_layers_at_the_instance_limit() {
4374 let mut cfg = kessel_video::fake::FakeConfig::default();
4375 cfg.max_instances = Some(2);
4376 let backend: Arc<dyn VideoBackend> = HwFake::new(cfg);
4377 let mut cap = caps(&[kessel_video::VideoCodec::H264]).codecs.remove(0);
4378 let plan = vec![
4379 LayerSpec::new("q", 320, 180, 150, 30),
4380 LayerSpec::new("h", 640, 360, 500, 30),
4381 LayerSpec::new("f", 1280, 720, 1700, 30),
4382 ];
4383 let wake = kessel_video::no_wake();
4384 let encs = open_encoders(
4386 &backend,
4387 VideoCodec::H264,
4388 &cap,
4389 plan.clone(),
4390 ContentHint::Camera,
4391 &wake,
4392 );
4393 let rids: Vec<&str> = encs.iter().map(|e| e.spec.rid.as_str()).collect();
4394 assert_eq!(rids, vec!["q", "h"]);
4395 drop(encs);
4396 cap.max_instances = Some(1);
4398 let encs = open_encoders(
4399 &backend,
4400 VideoCodec::H264,
4401 &cap,
4402 plan,
4403 ContentHint::Camera,
4404 &wake,
4405 );
4406 assert_eq!(encs.len(), 1);
4407 assert_eq!(encs[0].spec.rid, "q");
4408 }
4409
4410 fn tap_item(tap: &super::super::CameraTap, what: &str) -> super::super::CameraTapItem {
4412 tap.recv_timeout(Duration::from_secs(10))
4413 .unwrap_or_else(|| panic!("timed out waiting for {what}"))
4414 }
4415
4416 fn tap_frames(
4419 tap: &super::super::CameraTap,
4420 what: &str,
4421 n: usize,
4422 ) -> (Vec<Facing>, Vec<CameraFeed>) {
4423 let mut facings = Vec::new();
4424 let mut feeds = Vec::new();
4425 while facings.len() < n {
4426 match tap_item(tap, what) {
4427 super::super::CameraTapItem::Frame(f) => {
4428 assert_eq!(f.rotation, 0, "frames come upright");
4429 facings.push(f.facing);
4430 }
4431 super::super::CameraTapItem::Feed(f) => feeds.push(f),
4432 }
4433 }
4434 (facings, feeds)
4435 }
4436
4437 fn tap_quiet(tap: &super::super::CameraTap, what: &str) -> Vec<CameraFeed> {
4439 let until = std::time::Instant::now() + Duration::from_millis(400);
4440 let mut feeds = Vec::new();
4441 while let Some(item) =
4442 tap.recv_timeout(until.saturating_duration_since(std::time::Instant::now()))
4443 {
4444 match item {
4445 super::super::CameraTapItem::Feed(f) => feeds.push(f),
4446 super::super::CameraTapItem::Frame(_) => panic!("{what}: a frame came"),
4447 }
4448 }
4449 feeds
4450 }
4451
4452 #[test]
4458 fn a_camera_tap_gets_the_published_cameras_raw_frames_and_its_feed() {
4459 let backend: Arc<dyn VideoBackend> = HwFake::new(kessel_video::fake::FakeConfig::default());
4460 let bell = Arc::new(Bell::default());
4461 let src = fake_camera(&backend, &bell);
4462 let mut p = TestPipe::start(&backend, src, &bell);
4463 let _ = collect_until(&mut p.rx, "the first frames", 3);
4464 let tap = p.camera_taps.open();
4465 assert!(matches!(
4466 tap_item(&tap, "the feed"),
4467 super::super::CameraTapItem::Feed(CameraFeed::Live)
4468 ));
4469 let (facings, _) = tap_frames(&tap, "the front camera's frames", 3);
4470 assert!(facings.iter().all(|f| *f == Facing::Front), "{facings:?}");
4471
4472 p.send(ToPipe::Pause(true));
4475 std::thread::sleep(Duration::from_millis(100));
4476 let mut feeds = Vec::new();
4477 while let Some(item) = tap.try_recv() {
4478 if let super::super::CameraTapItem::Feed(f) = item {
4479 feeds.push(f);
4480 }
4481 }
4482 feeds.extend(tap_quiet(&tap, "paused"));
4483 assert_eq!(feeds, vec![CameraFeed::Paused]);
4484 p.send(ToPipe::Pause(false));
4485 let (_, feeds) = tap_frames(&tap, "frames after the return", 2);
4486 assert_eq!(feeds, vec![CameraFeed::Live]);
4487
4488 let (tx, done) = std::sync::mpsc::channel();
4490 p.send(ToPipe::Release(tx));
4491 done.recv_timeout(Duration::from_secs(5)).expect("released");
4492 let next = fake_camera(&backend, &bell);
4493 p.send(ToPipe::Source(
4494 next,
4495 vec![LayerSpec::new("q", 320, 180, 150, 30)],
4496 Facing::Back,
4497 ));
4498 let deadline = std::time::Instant::now() + Duration::from_secs(10);
4499 loop {
4500 assert!(std::time::Instant::now() < deadline, "no back camera frame");
4501 let (f, _) = tap_frames(&tap, "the back camera's frames", 1);
4502 if f[0] == Facing::Back {
4503 break;
4504 }
4505 }
4506
4507 p.control(VideoControl::Rates(vec![rate("q", false)]));
4509 p.assert_quiet("no layer wanted: nothing encoded");
4510 let _ = tap_frames(&tap, "frames for the tap alone", 3);
4511
4512 drop(tap);
4514 p.control(VideoControl::Rates(vec![rate("q", true)]));
4515 let _ = collect_until(&mut p.rx, "frames after the tap closed", 3);
4516
4517 let last = p.camera_taps.open();
4519 let taps = p.camera_taps.clone();
4520 p.finish();
4521 let mut feeds = Vec::new();
4522 while let Some(item) = last.try_recv() {
4523 if let super::super::CameraTapItem::Feed(f) = item {
4524 feeds.push(f);
4525 }
4526 }
4527 assert_eq!(feeds.last(), Some(&CameraFeed::Off), "{feeds:?}");
4528 drop(last);
4529 assert!(!taps.any());
4530 }
4531
4532 #[test]
4533 fn the_self_view_layer_is_the_cameras_h_and_the_screens_q() {
4534 let q = LayerSpec::new("q", 320, 180, 150, 30);
4535 let h = LayerSpec::new("h", 640, 360, 500, 30);
4536 let f = LayerSpec::new("f", 1280, 720, 1700, 30);
4537 let cam = VideoSource::Camera;
4538 let scr = VideoSource::ScreenShare;
4539 let all = vec![q.clone(), h.clone(), f.clone()];
4540 assert_eq!(self_view_rid(cam, &all).as_deref(), Some("h"));
4541 assert_eq!(self_view_rid(scr, &all).as_deref(), Some("q"));
4542 let qf = vec![q.clone(), f.clone()];
4544 assert_eq!(self_view_rid(cam, &qf).as_deref(), Some("f"));
4545 let hf = vec![h.clone(), f];
4546 assert_eq!(self_view_rid(scr, &hf).as_deref(), Some("h"));
4547 assert_eq!(self_view_rid(cam, &[q]).as_deref(), Some("q"));
4549 assert_eq!(self_view_rid(cam, &[]), None);
4550 }
4551
4552 #[test]
4553 fn capture_refusals_keep_the_publish_codes() {
4554 for (e, code) in [
4555 (CaptureError::CameraDenied, "camera_denied"),
4556 (CaptureError::CameraBusy, "camera_busy"),
4557 (CaptureError::CameraNotFound, "camera_not_found"),
4558 (CaptureError::CameraLost, "camera_not_found"),
4559 (CaptureError::CodecUnavailable, "codec_unavailable"),
4560 (CaptureError::Failed(KError::DeviceBusy), "camera_busy"),
4561 (CaptureError::VideoUnsupported, "publish_failed"),
4562 ] {
4563 assert_eq!(capture_error(&e).code(), code, "{e:?}");
4564 }
4565 assert_eq!(VideoError::NoFrames.code(), "no_frames");
4566 }
4567
4568 struct Scripted {
4571 events: std::collections::VecDeque<SourceEvent>,
4572 frames_from: Option<std::time::Instant>,
4573 drop_takes: Duration,
4574 }
4575
4576 impl Scripted {
4577 fn new(events: Vec<SourceEvent>, frames_after: Option<Duration>) -> Scripted {
4578 Scripted {
4579 events: events.into(),
4580 frames_from: frames_after.map(|d| std::time::Instant::now() + d),
4581 drop_takes: Duration::ZERO,
4582 }
4583 }
4584 }
4585
4586 impl Drop for Scripted {
4587 fn drop(&mut self) {
4588 std::thread::sleep(self.drop_takes);
4589 }
4590 }
4591
4592 impl FrameSource for Scripted {
4593 fn try_recv(&mut self) -> Option<kessel_video::VideoFrame> {
4594 if self
4595 .frames_from
4596 .is_some_and(|t| std::time::Instant::now() >= t)
4597 {
4598 kessel_video::VideoFrame::filled(PixelFormat::I420, 64, 36, [16, 128, 128], 0).ok()
4599 } else {
4600 None
4601 }
4602 }
4603 fn try_event(&mut self) -> Option<SourceEvent> {
4604 self.events.pop_front()
4605 }
4606 fn set_constraints(&mut self, _c: CaptureConstraints) -> Result<(), KError> {
4607 Ok(())
4608 }
4609 fn set_paused(&mut self, _paused: bool) {}
4610 fn stats(&self) -> kessel_video::SourceStats {
4611 kessel_video::SourceStats::default()
4612 }
4613 }
4614
4615 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
4618 async fn a_camera_without_frames_is_no_frames_after_the_watchdog() {
4619 let began = std::time::Instant::now();
4620 let src = Scripted::new(
4621 vec![SourceEvent::Interrupted(
4622 kessel_video::Interruption::Suspended,
4623 )],
4624 None,
4625 );
4626 let r = wait_first_frame(Box::new(src)).await;
4627 assert!(
4628 matches!(r, Err(VideoError::NoFrames)),
4629 "{:?}",
4630 r.as_ref().map(|(_, s)| s)
4631 );
4632 let took = began.elapsed();
4633 assert!(
4634 took >= FIRST_FRAME_WAIT && took < FIRST_FRAME_WAIT + Duration::from_secs(2),
4635 "the watchdog's time: {took:?}"
4636 );
4637 }
4638
4639 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
4642 async fn the_first_frame_comes_after_the_events_seen_before_it() {
4643 let src = Scripted::new(
4644 vec![
4645 SourceEvent::Interrupted(kessel_video::Interruption::Suspended),
4646 SourceEvent::Resumed,
4647 ],
4648 Some(Duration::from_millis(300)),
4649 );
4650 let (mut primed, size) = wait_first_frame(Box::new(src)).await.expect("a frame");
4651 assert_eq!(size, (64, 36));
4652 assert!(primed.try_recv().is_none(), "the events first");
4653 assert_eq!(
4654 primed.try_event(),
4655 Some(SourceEvent::Interrupted(
4656 kessel_video::Interruption::Suspended
4657 ))
4658 );
4659 assert_eq!(primed.try_event(), Some(SourceEvent::Resumed));
4660 assert_eq!(primed.try_event(), None);
4661 let f = primed.try_recv().expect("the kept first frame");
4662 assert_eq!((f.width, f.height), (64, 36));
4663 let ended = Scripted::new(
4665 vec![SourceEvent::Ended(kessel_video::EndReason::DeviceLost)],
4666 None,
4667 );
4668 assert!(matches!(
4669 wait_first_frame(Box::new(ended)).await,
4670 Err(VideoError::CameraNotFound)
4671 ));
4672 }
4673
4674 #[test]
4677 fn a_pipeline_whose_camera_closes_slowly_stops_within_the_bound() {
4678 let stop = Arc::new(AtomicBool::new(false));
4679 let s2 = Arc::clone(&stop);
4680 let thread = std::thread::spawn(move || {
4681 let mut src = Scripted::new(Vec::new(), None);
4682 src.drop_takes = Duration::from_secs(8);
4683 while !s2.load(Ordering::SeqCst) {
4684 std::thread::sleep(Duration::from_millis(5));
4685 }
4686 drop(src);
4687 });
4688 let (to_pipe, _from) = std::sync::mpsc::channel();
4689 let cap = caps(&[kessel_video::VideoCodec::Vp8]).codecs[0].clone();
4690 let r = Running {
4691 call: 1,
4692 stop,
4693 ended: Arc::new(AtomicBool::new(false)),
4694 bell: Arc::new(Bell::default()),
4695 to_pipe,
4696 thread: Some(thread),
4697 codec: VideoCodec::Vp8,
4698 live: Arc::new(Mutex::new(VideoCodec::Vp8)),
4699 cap,
4700 layers: Vec::new(),
4701 size: (640, 360),
4702 device: None,
4703 temporal: None,
4704 held: Arc::default(),
4705 };
4706 let began = std::time::Instant::now();
4707 r.stop();
4708 let took = began.elapsed();
4709 assert!(
4710 took >= STOP_WAIT && took < STOP_WAIT + Duration::from_secs(1),
4711 "the stop waited {took:?}"
4712 );
4713 }
4714}