1use crate::error::{invalid, VideoError};
9use crate::frame::{PixelFormat, Planes};
10use bytes::Bytes;
11use std::any::Any;
12use std::sync::Arc;
13
14#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
18#[non_exhaustive]
19pub enum VideoCodec {
20 Vp8,
23 H264,
26}
27
28impl VideoCodec {
29 pub fn sdp_name(&self) -> &'static str {
31 match self {
32 VideoCodec::Vp8 => "VP8",
33 VideoCodec::H264 => "H264",
34 }
35 }
36}
37
38#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
40#[non_exhaustive]
41pub enum CodecDirection {
42 Encode,
44 Decode,
46}
47
48#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
54#[non_exhaustive]
55pub enum Implementation {
56 Hardware,
58 Software,
60 Unknown,
65}
66
67#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
69#[non_exhaustive]
70pub enum ImplPreference {
71 #[default]
73 PreferHardware,
74 HardwareOnly,
76 SoftwareOnly,
78}
79
80#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
82#[non_exhaustive]
83pub enum H264Profile {
84 #[default]
87 ConstrainedBaseline,
88 ConstrainedHigh,
91}
92
93#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
95pub struct H264Level(pub u8);
96
97impl H264Level {
98 pub const L3_1: H264Level = H264Level(31);
100 pub const L4_0: H264Level = H264Level(40);
102 pub const L5_1: H264Level = H264Level(51);
104
105 pub fn for_size(width: u32, height: u32, fps: u32) -> H264Level {
108 let mbs = (width.div_ceil(16) * height.div_ceil(16)) as u64;
109 let rate = mbs * fps.max(1) as u64;
110 const TABLE: [(u8, u64, u64); 12] = [
111 (10, 1_485, 99),
112 (11, 3_000, 396),
113 (12, 6_000, 396),
114 (13, 11_880, 396),
115 (20, 11_880, 396),
116 (21, 19_800, 792),
117 (22, 20_250, 1_620),
118 (30, 40_500, 1_620),
119 (31, 108_000, 3_600),
120 (32, 216_000, 5_120),
121 (40, 245_760, 8_192),
122 (51, 983_040, 36_864),
123 ];
124 for (level, max_rate, max_fs) in TABLE {
125 if rate <= max_rate && mbs <= max_fs {
126 return H264Level(level);
127 }
128 }
129 H264Level(52)
130 }
131}
132
133#[derive(Clone, Debug, PartialEq, Eq)]
135#[non_exhaustive]
136pub struct H264Capability {
137 pub profiles: Vec<H264Profile>,
139 pub max_level: H264Level,
141}
142
143impl H264Capability {
144 pub fn new(profiles: Vec<H264Profile>, max_level: H264Level) -> H264Capability {
146 H264Capability {
147 profiles,
148 max_level,
149 }
150 }
151}
152
153#[derive(Clone, Debug, PartialEq, Eq)]
156#[non_exhaustive]
157pub struct CodecCapability {
158 pub codec: VideoCodec,
160 pub direction: CodecDirection,
162 pub implementation: Implementation,
164 pub name: String,
166 pub max_width: u32,
168 pub max_height: u32,
170 pub max_fps: u32,
172 pub max_instances: Option<u32>,
175 pub max_temporal_layers: u8,
177 pub h264: Option<H264Capability>,
179 pub formats: Vec<PixelFormat>,
181 pub file_mode: bool,
184}
185
186impl CodecCapability {
187 pub fn new(
190 codec: VideoCodec,
191 direction: CodecDirection,
192 implementation: Implementation,
193 name: impl Into<String>,
194 max_width: u32,
195 max_height: u32,
196 max_fps: u32,
197 ) -> CodecCapability {
198 CodecCapability {
199 codec,
200 direction,
201 implementation,
202 name: name.into(),
203 max_width,
204 max_height,
205 max_fps,
206 max_instances: None,
207 max_temporal_layers: 1,
208 h264: None,
209 formats: Vec::new(),
210 file_mode: false,
211 }
212 }
213}
214
215#[derive(Clone, Debug, Default, PartialEq, Eq)]
217#[non_exhaustive]
218pub struct ScreenCapability {
219 pub supported: bool,
221 pub system_picker: bool,
223 pub list: bool,
225 pub windows: bool,
227 pub cursor: bool,
229 pub exclude_own_windows: bool,
231 pub frame_in: bool,
236}
237
238#[derive(Clone, Debug, PartialEq, Eq)]
240#[non_exhaustive]
241pub struct Capabilities {
242 pub backend: &'static str,
244 pub os: String,
246 pub codecs: Vec<CodecCapability>,
248 pub camera: bool,
250 pub screen: ScreenCapability,
252}
253
254impl Capabilities {
255 pub fn new(backend: &'static str, os: impl Into<String>) -> Capabilities {
257 Capabilities {
258 backend,
259 os: os.into(),
260 codecs: Vec::new(),
261 camera: false,
262 screen: ScreenCapability::default(),
263 }
264 }
265
266 pub fn best(&self, codec: VideoCodec, dir: CodecDirection) -> Option<&CodecCapability> {
269 self.codecs
270 .iter()
271 .filter(|c| c.codec == codec && c.direction == dir)
272 .max_by_key(|c| {
273 (
274 c.implementation == Implementation::Hardware,
275 c.max_width as u64 * c.max_height as u64,
276 )
277 })
278 }
279}
280
281#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
285#[non_exhaustive]
286pub enum Permission {
287 Granted,
289 Denied,
291 Restricted,
293 NotDetermined,
295}
296
297#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
299#[non_exhaustive]
300pub enum Facing {
301 Front,
303 Back,
305 External,
307 Unknown,
309}
310
311#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
313#[non_exhaustive]
314pub struct CaptureMode {
315 pub width: u32,
317 pub height: u32,
319 pub max_fps: u32,
321 pub format: PixelFormat,
323}
324
325impl CaptureMode {
326 pub fn new(width: u32, height: u32, max_fps: u32, format: PixelFormat) -> CaptureMode {
328 CaptureMode {
329 width,
330 height,
331 max_fps,
332 format,
333 }
334 }
335}
336
337#[derive(Clone, Debug, PartialEq, Eq)]
339#[non_exhaustive]
340pub struct CameraInfo {
341 pub id: String,
347 pub name: String,
349 pub facing: Facing,
351 pub is_default: bool,
354 pub modes: Vec<CaptureMode>,
356 pub suspended: bool,
367}
368
369pub(crate) fn default_camera(cams: &[CameraInfo]) -> Option<&CameraInfo> {
373 let def = cams.iter().find(|c| c.is_default).or(cams.first())?;
374 if !def.suspended {
375 return Some(def);
376 }
377 Some(cams.iter().find(|c| !c.suspended).unwrap_or(def))
378}
379
380impl CameraInfo {
381 pub fn new(
383 id: impl Into<String>,
384 name: impl Into<String>,
385 facing: Facing,
386 is_default: bool,
387 ) -> CameraInfo {
388 CameraInfo {
389 id: id.into(),
390 name: name.into(),
391 facing,
392 is_default,
393 modes: Vec::new(),
394 suspended: false,
395 }
396 }
397}
398
399#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
403#[non_exhaustive]
404pub struct CaptureConstraints {
405 pub max_width: Option<u32>,
407 pub max_height: Option<u32>,
409 pub fps: Option<u32>,
411 pub facing: Option<Facing>,
413 pub prefer_native: bool,
415 pub cursor: bool,
417 pub exclude_own_windows: bool,
421}
422
423impl CaptureConstraints {
424 pub fn new(max_width: u32, max_height: u32, fps: u32) -> CaptureConstraints {
426 CaptureConstraints {
427 max_width: Some(max_width),
428 max_height: Some(max_height),
429 fps: Some(fps),
430 ..CaptureConstraints::default()
431 }
432 }
433
434 pub(crate) fn validate(&self) -> Result<(), VideoError> {
435 for v in [self.max_width, self.max_height].into_iter().flatten() {
436 if !(16..=8192).contains(&v) {
437 return Err(invalid(format!("a capture size of {v}")));
438 }
439 }
440 if let Some(f) = self.fps {
441 if !(1..=240).contains(&f) {
442 return Err(invalid(format!("{f} fps")));
443 }
444 }
445 Ok(())
446 }
447}
448
449pub fn nearest_mode(modes: &[CaptureMode], c: &CaptureConstraints) -> Option<CaptureMode> {
452 let (w, h, fps) = (
453 c.max_width.unwrap_or(1280),
454 c.max_height.unwrap_or(720),
455 c.fps.unwrap_or(30),
456 );
457 let area = |m: &CaptureMode| m.width as u64 * m.height as u64;
458 modes
459 .iter()
460 .filter(|m| m.width >= w && m.height >= h && m.max_fps >= fps)
461 .min_by_key(|m| (area(m), std::cmp::Reverse(m.max_fps)))
462 .or_else(|| {
463 modes
465 .iter()
466 .filter(|m| m.max_fps >= fps)
467 .max_by_key(|m| (area(m), m.max_fps))
468 .or_else(|| modes.iter().max_by_key(|m| (area(m), m.max_fps)))
469 })
470 .copied()
471}
472
473#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
475#[non_exhaustive]
476pub enum EndReason {
477 Closed,
479 DeviceLost,
488 UserStopped,
490 SourceClosed,
492 Revoked,
494}
495
496#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
498#[non_exhaustive]
499pub enum Interruption {
500 Background,
502 InUseByAnother,
504 Thermal,
506 Hidden,
508 Suspended,
512}
513
514#[derive(Clone, Debug, PartialEq, Eq)]
516#[non_exhaustive]
517pub enum SourceEvent {
518 Started {
520 width: u32,
522 height: u32,
524 fps: u32,
526 },
527 Interrupted(Interruption),
529 Resumed,
531 Ended(EndReason),
533 Error(VideoError),
535}
536
537#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
539#[non_exhaustive]
540pub struct SourceStats {
541 pub frames: u64,
543 pub dropped: u64,
545 pub width: u32,
547 pub height: u32,
549 pub fps: u32,
551}
552
553#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
555#[non_exhaustive]
556pub enum ScreenKind {
557 Display,
559 Window,
561}
562
563#[derive(Clone, Debug, PartialEq, Eq)]
565#[non_exhaustive]
566pub struct ScreenSourceInfo {
567 pub id: String,
569 pub kind: ScreenKind,
571 pub title: String,
573 pub app: Option<String>,
575 pub width: u32,
577 pub height: u32,
579 pub thumbnail: Option<Planes>,
584 pub thumbnail_width: u32,
586 pub thumbnail_height: u32,
588}
589
590impl ScreenSourceInfo {
591 pub fn new(
593 id: impl Into<String>,
594 kind: ScreenKind,
595 title: impl Into<String>,
596 width: u32,
597 height: u32,
598 ) -> ScreenSourceInfo {
599 ScreenSourceInfo {
600 id: id.into(),
601 kind,
602 title: title.into(),
603 app: None,
604 width,
605 height,
606 thumbnail: None,
607 thumbnail_width: 0,
608 thumbnail_height: 0,
609 }
610 }
611
612 pub fn with_thumbnail(
616 mut self,
617 planes: Planes,
618 width: u32,
619 height: u32,
620 ) -> Result<ScreenSourceInfo, VideoError> {
621 if planes.format != PixelFormat::Rgba {
622 return Err(invalid(format!(
623 "a thumbnail is RGBA, not {:?}",
624 planes.format
625 )));
626 }
627 if width > 320 {
628 return Err(invalid(format!(
629 "a thumbnail is at most 320 px wide, not {width}"
630 )));
631 }
632 planes.validate(width, height)?;
633 self.thumbnail = Some(planes);
634 self.thumbnail_width = width;
635 self.thumbnail_height = height;
636 Ok(self)
637 }
638
639 pub fn thumbnail_size(&self) -> Option<(u32, u32)> {
642 let sized = self.thumbnail_width > 0 && self.thumbnail_height > 0;
643 (self.thumbnail.is_some() && sized).then_some((self.thumbnail_width, self.thumbnail_height))
644 }
645}
646
647#[derive(Clone)]
649#[non_exhaustive]
650pub enum ScreenSelection {
651 Listed(String),
653 Picked(Arc<dyn Any + Send + Sync>),
655}
656
657impl std::fmt::Debug for ScreenSelection {
658 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
659 match self {
660 ScreenSelection::Listed(id) => f.debug_tuple("Listed").field(id).finish(),
661 ScreenSelection::Picked(_) => f.write_str("Picked(..)"),
662 }
663 }
664}
665
666#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
668#[non_exhaustive]
669pub struct PickOptions {
670 pub displays: bool,
672 pub windows: bool,
674 pub parent_window: Option<u64>,
677}
678
679impl PickOptions {
680 pub fn new() -> PickOptions {
682 PickOptions::default()
683 }
684
685 pub fn with_parent_window(mut self, handle: u64) -> PickOptions {
687 self.parent_window = Some(handle);
688 self
689 }
690}
691
692#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
696#[non_exhaustive]
697pub enum ContentHint {
698 #[default]
700 Camera,
701 Screen,
703}
704
705#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
707#[non_exhaustive]
708pub enum CodecConfig {
709 Vp8,
711 H264 {
713 profile: H264Profile,
715 level: H264Level,
717 },
718}
719
720impl CodecConfig {
721 pub fn codec(&self) -> VideoCodec {
723 match self {
724 CodecConfig::Vp8 => VideoCodec::Vp8,
725 CodecConfig::H264 { .. } => VideoCodec::H264,
726 }
727 }
728}
729
730#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
732#[non_exhaustive]
733pub struct EncoderConfig {
734 pub codec: CodecConfig,
736 pub width: u32,
738 pub height: u32,
740 pub fps: u32,
742 pub bitrate_bps: u32,
744 pub max_bitrate_bps: u32,
746 pub keyframe_interval: Option<u32>,
748 pub temporal_layers: u8,
750 pub content: ContentHint,
752 pub implementation: ImplPreference,
754}
755
756impl EncoderConfig {
757 pub fn new(
760 codec: CodecConfig,
761 width: u32,
762 height: u32,
763 fps: u32,
764 bitrate_bps: u32,
765 ) -> EncoderConfig {
766 EncoderConfig {
767 codec,
768 width,
769 height,
770 fps,
771 bitrate_bps,
772 max_bitrate_bps: bitrate_bps.saturating_add(bitrate_bps / 2),
773 keyframe_interval: None,
774 temporal_layers: 1,
775 content: ContentHint::default(),
776 implementation: ImplPreference::default(),
777 }
778 }
779
780 pub fn h264(width: u32, height: u32, fps: u32, bitrate_bps: u32) -> EncoderConfig {
782 let level = H264Level::for_size(width, height, fps).max(H264Level::L3_1);
783 EncoderConfig::new(
784 CodecConfig::H264 {
785 profile: H264Profile::ConstrainedBaseline,
786 level,
787 },
788 width,
789 height,
790 fps,
791 bitrate_bps,
792 )
793 }
794
795 pub fn validate(&self) -> Result<(), VideoError> {
797 validate_size(self.width, self.height)?;
798 if !(1..=240).contains(&self.fps) {
799 return Err(invalid(format!("{} fps", self.fps)));
800 }
801 if self.bitrate_bps < 10_000 {
802 return Err(invalid(format!("{} bit/s", self.bitrate_bps)));
803 }
804 if self.max_bitrate_bps < self.bitrate_bps {
805 return Err(invalid(format!(
806 "max_bitrate_bps {} is below bitrate_bps {}",
807 self.max_bitrate_bps, self.bitrate_bps
808 )));
809 }
810 if self.keyframe_interval == Some(0) {
811 return Err(invalid("a keyframe interval of 0 frames"));
812 }
813 let max_tl = if self.codec.codec() == VideoCodec::H264 {
814 1
815 } else {
816 3
817 };
818 if self.temporal_layers == 0 || self.temporal_layers > max_tl {
819 return Err(invalid(format!(
820 "{} temporal layers for {:?}",
821 self.temporal_layers,
822 self.codec.codec()
823 )));
824 }
825 Ok(())
826 }
827}
828
829pub(crate) fn validate_size(width: u32, height: u32) -> Result<(), VideoError> {
830 if width < 16
831 || height < 16
832 || width > 8192
833 || height > 8192
834 || !width.is_multiple_of(2)
835 || !height.is_multiple_of(2)
836 {
837 return Err(invalid(format!(
838 "coded size {width}x{height} (even, 16 to 8192)"
839 )));
840 }
841 Ok(())
842}
843
844#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
846#[non_exhaustive]
847pub struct Rates {
848 pub bitrate_bps: u32,
850 pub fps: u32,
852}
853
854impl Rates {
855 pub fn new(bitrate_bps: u32, fps: u32) -> Rates {
857 Rates { bitrate_bps, fps }
858 }
859
860 pub(crate) fn validate(&self) -> Result<(), VideoError> {
861 if self.bitrate_bps < 10_000 || !(1..=240).contains(&self.fps) {
862 return Err(invalid(format!(
863 "rates {} bit/s at {} fps",
864 self.bitrate_bps, self.fps
865 )));
866 }
867 Ok(())
868 }
869}
870
871#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
873#[non_exhaustive]
874pub struct EncodeOptions {
875 pub keyframe: bool,
877}
878
879impl EncodeOptions {
880 pub fn keyframe() -> EncodeOptions {
882 EncodeOptions { keyframe: true }
883 }
884}
885
886#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
888#[non_exhaustive]
889pub struct LayerInfo {
890 pub temporal_id: u8,
892 pub layer_sync: bool,
894 pub spatial_id: u8,
896}
897
898impl LayerInfo {
899 pub fn new(temporal_id: u8, layer_sync: bool) -> LayerInfo {
901 LayerInfo {
902 temporal_id,
903 layer_sync,
904 spatial_id: 0,
905 }
906 }
907}
908
909#[derive(Clone, Debug, PartialEq, Eq)]
911#[non_exhaustive]
912pub struct EncodedFrame {
913 pub codec: VideoCodec,
915 pub data: Bytes,
917 pub keyframe: bool,
919 pub capture_us: u64,
921 pub width: u32,
923 pub height: u32,
925 pub layer: LayerInfo,
927 pub encode_us: u32,
929}
930
931impl EncodedFrame {
932 pub fn new(
934 codec: VideoCodec,
935 data: impl Into<Bytes>,
936 keyframe: bool,
937 capture_us: u64,
938 width: u32,
939 height: u32,
940 ) -> EncodedFrame {
941 EncodedFrame {
942 codec,
943 data: data.into(),
944 keyframe,
945 capture_us,
946 width,
947 height,
948 layer: LayerInfo::new(0, true),
949 encode_us: 0,
950 }
951 }
952}
953
954#[derive(Clone, Debug, PartialEq, Eq)]
956#[non_exhaustive]
957pub struct EncoderInfo {
958 pub implementation: Implementation,
962 pub name: String,
964 pub config: EncoderConfig,
966}
967
968impl EncoderInfo {
969 pub fn new(
971 implementation: Implementation,
972 name: impl Into<String>,
973 config: EncoderConfig,
974 ) -> EncoderInfo {
975 EncoderInfo {
976 implementation,
977 name: name.into(),
978 config,
979 }
980 }
981}
982
983#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
985#[non_exhaustive]
986pub struct EncoderStats {
987 pub frames_in: u64,
989 pub frames_out: u64,
991 pub keyframes: u64,
993 pub dropped_by_rc: u64,
995 pub busy: u64,
997 pub bytes_out: u64,
999}
1000
1001#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
1005#[non_exhaustive]
1006pub enum DecodeMode {
1007 #[default]
1012 Realtime,
1013 File,
1032}
1033
1034#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1036#[non_exhaustive]
1037pub struct DecoderConfig {
1038 pub codec: VideoCodec,
1040 pub implementation: ImplPreference,
1042 pub output: PixelFormat,
1044 pub fit: Option<(u32, u32)>,
1047 pub mode: DecodeMode,
1049 pub output_queue: usize,
1055}
1056
1057impl DecoderConfig {
1058 pub fn new(codec: VideoCodec) -> DecoderConfig {
1060 DecoderConfig {
1061 codec,
1062 implementation: ImplPreference::default(),
1063 output: PixelFormat::I420,
1064 fit: None,
1065 mode: DecodeMode::Realtime,
1066 output_queue: crate::kit::FILE_OUTPUT_QUEUE,
1067 }
1068 }
1069
1070 pub fn file(codec: VideoCodec) -> DecoderConfig {
1074 DecoderConfig {
1075 mode: DecodeMode::File,
1076 ..DecoderConfig::new(codec)
1077 }
1078 }
1079
1080 pub fn validate(&self) -> Result<(), VideoError> {
1083 let max = crate::kit::FILE_OUTPUT_QUEUE_MAX;
1084 if self.mode == DecodeMode::File && !(1..=max).contains(&self.output_queue) {
1085 return Err(invalid(format!(
1086 "a File-mode output queue of {} (1 to {max})",
1087 self.output_queue
1088 )));
1089 }
1090 Ok(())
1091 }
1092}
1093
1094#[derive(Clone, Debug, PartialEq, Eq)]
1096#[non_exhaustive]
1097pub struct EncodedInput {
1098 pub codec: VideoCodec,
1100 pub data: Bytes,
1102 pub keyframe: bool,
1104 pub capture_us: u64,
1108 pub dts_us: Option<u64>,
1112}
1113
1114impl EncodedInput {
1115 pub fn new(
1117 codec: VideoCodec,
1118 data: impl Into<Bytes>,
1119 keyframe: bool,
1120 capture_us: u64,
1121 ) -> EncodedInput {
1122 EncodedInput {
1123 codec,
1124 data: data.into(),
1125 keyframe,
1126 capture_us,
1127 dts_us: None,
1128 }
1129 }
1130
1131 pub fn file(
1135 codec: VideoCodec,
1136 data: impl Into<Bytes>,
1137 keyframe: bool,
1138 pts_us: u64,
1139 dts_us: Option<u64>,
1140 ) -> EncodedInput {
1141 EncodedInput {
1142 dts_us,
1143 ..EncodedInput::new(codec, data, keyframe, pts_us)
1144 }
1145 }
1146}
1147
1148#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1150#[non_exhaustive]
1151pub struct DecoderStats {
1152 pub frames_in: u64,
1154 pub frames_out: u64,
1156 pub dropped_out: u64,
1161 pub errors: u64,
1163 pub implementation: Option<Implementation>,
1167}
1168
1169#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
1173#[non_exhaustive]
1174pub enum ThermalLevel {
1175 Nominal,
1177 Fair,
1179 Serious,
1181 Critical,
1183}
1184
1185#[derive(Clone, Debug, PartialEq, Eq)]
1187#[non_exhaustive]
1188pub enum BackendEvent {
1189 Cameras(Vec<CameraInfo>),
1191 CapabilitiesChanged,
1193 Thermal(ThermalLevel),
1195 LowPower(bool),
1197 Background(bool),
1199}
1200
1201#[cfg(test)]
1202mod tests {
1203 use super::*;
1204
1205 #[test]
1206 fn levels_follow_table_a1() {
1207 assert_eq!(H264Level::for_size(320, 180, 30), H264Level(13));
1208 assert_eq!(H264Level::for_size(640, 360, 30), H264Level(30));
1209 assert_eq!(H264Level::for_size(1280, 720, 30), H264Level(31));
1210 assert_eq!(H264Level::for_size(1280, 720, 60), H264Level(32));
1211 assert_eq!(H264Level::for_size(1920, 1080, 30), H264Level(40));
1212 assert_eq!(H264Level::for_size(3840, 2160, 30), H264Level(51));
1213 }
1214
1215 #[test]
1216 fn encoder_configs_are_checked() {
1217 let c = EncoderConfig::h264(1280, 720, 30, 1_500_000);
1218 assert!(c.validate().is_ok());
1219 assert_eq!(c.max_bitrate_bps, 2_250_000);
1220 assert_eq!(
1221 c.codec,
1222 CodecConfig::H264 {
1223 profile: H264Profile::ConstrainedBaseline,
1224 level: H264Level(31)
1225 }
1226 );
1227 let mut odd = c;
1228 odd.width = 1281;
1229 assert!(matches!(odd.validate(), Err(VideoError::Invalid(_))));
1230 let mut tl = c;
1231 tl.temporal_layers = 2;
1232 assert!(tl.validate().is_err(), "H.264 has one temporal layer");
1233 let mut vp8 = EncoderConfig::new(CodecConfig::Vp8, 640, 360, 30, 500_000);
1234 vp8.temporal_layers = 3;
1235 assert!(vp8.validate().is_ok());
1236 vp8.max_bitrate_bps = 1;
1237 assert!(vp8.validate().is_err());
1238 let mut k = c;
1239 k.keyframe_interval = Some(0);
1240 assert!(k.validate().is_err());
1241 assert!(Rates::new(5_000, 30).validate().is_err());
1242 }
1243
1244 #[test]
1245 fn best_prefers_hardware_then_size() {
1246 let mut caps = Capabilities::new("fake", "test");
1247 caps.codecs.push(CodecCapability::new(
1248 VideoCodec::H264,
1249 CodecDirection::Encode,
1250 Implementation::Software,
1251 "sw",
1252 3840,
1253 2160,
1254 30,
1255 ));
1256 caps.codecs.push(CodecCapability::new(
1257 VideoCodec::H264,
1258 CodecDirection::Encode,
1259 Implementation::Hardware,
1260 "hw",
1261 1920,
1262 1080,
1263 30,
1264 ));
1265 caps.codecs.push(CodecCapability::new(
1266 VideoCodec::H264,
1267 CodecDirection::Decode,
1268 Implementation::Software,
1269 "dec",
1270 1920,
1271 1080,
1272 30,
1273 ));
1274 assert_eq!(
1275 caps.best(VideoCodec::H264, CodecDirection::Encode)
1276 .map(|c| c.name.as_str()),
1277 Some("hw")
1278 );
1279 assert_eq!(
1280 caps.best(VideoCodec::H264, CodecDirection::Decode)
1281 .map(|c| c.name.as_str()),
1282 Some("dec")
1283 );
1284 assert!(caps.best(VideoCodec::Vp8, CodecDirection::Encode).is_none());
1285 }
1286
1287 #[test]
1288 fn nearest_mode_covers_the_ask() {
1289 let f = PixelFormat::Nv12;
1290 let ms = [
1291 CaptureMode::new(1920, 1080, 30, f),
1292 CaptureMode::new(1280, 720, 60, f),
1293 CaptureMode::new(640, 480, 30, f),
1294 ];
1295 let at = |w, h, fps| nearest_mode(&ms, &CaptureConstraints::new(w, h, fps)).expect("one");
1296 assert_eq!(
1297 (at(1280, 720, 30).width, at(1280, 720, 30).max_fps),
1298 (1280, 60)
1299 );
1300 assert_eq!(at(640, 360, 30).width, 640);
1301 assert_eq!(
1302 at(1920, 1080, 60).width,
1303 1280,
1304 "nothing covers 1080p60: the largest at 60"
1305 );
1306 assert_eq!(at(4000, 3000, 30).width, 1920);
1307 assert_eq!(nearest_mode(&[], &CaptureConstraints::default()), None);
1308 assert!(CaptureConstraints::new(8, 8, 30).validate().is_err());
1309 }
1310
1311 #[test]
1312 fn a_thumbnail_carries_its_size() {
1313 let info = ScreenSourceInfo::new("d1", ScreenKind::Display, "Main", 2560, 1440);
1314 assert_eq!(info.thumbnail_size(), None);
1315 let planes = Planes::new(
1318 PixelFormat::Rgba,
1319 160,
1320 90,
1321 vec![0u8; 768 * 90],
1322 [768, 0, 0],
1323 [0, 0, 0],
1324 )
1325 .expect("padded planes");
1326 let info = info.with_thumbnail(planes, 160, 90).expect("thumbnail");
1327 assert_eq!(info.thumbnail_size(), Some((160, 90)));
1328 assert_eq!((info.thumbnail_width, info.thumbnail_height), (160, 90));
1329
1330 let base = ScreenSourceInfo::new("d1", ScreenKind::Display, "Main", 2560, 1440);
1331 let bgra = Planes::tight(PixelFormat::Bgra, 4, 4, vec![0u8; 64]).expect("bgra");
1332 assert!(base.clone().with_thumbnail(bgra, 4, 4).is_err());
1333 let wide = Planes::tight(PixelFormat::Rgba, 321, 1, vec![0u8; 321 * 4]).expect("wide");
1334 assert!(base.clone().with_thumbnail(wide, 321, 1).is_err());
1335 let small = Planes::tight(PixelFormat::Rgba, 4, 4, vec![0u8; 64]).expect("small");
1336 assert!(base.with_thumbnail(small, 8, 8).is_err());
1337 }
1338}