1use std::collections::BTreeSet;
10use std::fmt;
11
12use serde::{Deserialize, Serialize};
13
14use crate::CodecString;
15
16macro_rules! vocabulary {
17 ($(#[$doc:meta])* $name:ident { $($(#[$vdoc:meta])* $variant:ident => $wire:literal,)* }) => {
18 $(#[$doc])*
19 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
20 #[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
21 #[serde(rename_all = "snake_case")]
22 pub enum $name {
23 $($(#[$vdoc])* $variant,)*
24 #[serde(other)]
26 Unknown,
27 }
28
29 impl $name {
30 pub fn as_str(self) -> &'static str {
32 match self {
33 $($name::$variant => $wire,)*
34 $name::Unknown => "unknown",
35 }
36 }
37 }
38
39 impl fmt::Display for $name {
40 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41 f.write_str(self.as_str())
42 }
43 }
44 };
45}
46
47vocabulary!(
48 VideoCodec {
50 H264 => "h264",
51 Hevc => "hevc",
52 Av1 => "av1",
53 Vp9 => "vp9",
54 Vp8 => "vp8",
55 Mpeg2 => "mpeg2",
56 Mpeg4 => "mpeg4",
57 Vc1 => "vc1",
58 }
59);
60
61vocabulary!(
62 AudioCodec {
64 Aac => "aac",
65 Ac3 => "ac3",
66 Eac3 => "eac3",
67 Dts => "dts",
68 TrueHd => "true_hd",
69 Flac => "flac",
70 Alac => "alac",
71 Opus => "opus",
72 Vorbis => "vorbis",
73 Mp3 => "mp3",
74 Pcm => "pcm",
75 }
76);
77
78vocabulary!(
79 Container {
81 Matroska => "matroska",
82 Mp4 => "mp4",
83 MpegTs => "mpeg_ts",
84 Avi => "avi",
85 Flac => "flac",
86 Mp3 => "mp3",
87 Ogg => "ogg",
88 }
89);
90
91impl Container {
92 pub fn mime(self) -> &'static str {
96 match self {
97 Container::Mp4 => "video/mp4",
98 Container::Matroska => "video/x-matroska",
99 Container::MpegTs => "video/mp2t",
100 Container::Avi => "video/x-msvideo",
101 Container::Flac => "audio/flac",
102 Container::Mp3 => "audio/mpeg",
103 Container::Ogg => "audio/ogg",
104 _ => "application/octet-stream",
105 }
106 }
107}
108
109vocabulary!(
110 SubtitleFormat {
112 Srt => "srt",
113 Ass => "ass",
114 WebVtt => "web_vtt",
115 MovText => "mov_text",
116 Pgs => "pgs",
117 VobSub => "vob_sub",
118 DvbSub => "dvb_sub",
119 }
120);
121
122vocabulary!(
123 Delivery {
125 Range => "range",
127 Hls => "hls",
129 Progressive => "progressive",
131 }
132);
133
134vocabulary!(
135 HdrFormat {
137 Hdr10 => "hdr10",
138 Hlg => "hlg",
139 DolbyVision => "dolby_vision",
140 }
141);
142
143#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
146pub struct VideoLimits {
147 #[serde(deserialize_with = "crate::required::option")]
150 pub height: Option<u32>,
151 #[serde(deserialize_with = "crate::required::option")]
153 pub frame_rate: Option<u32>,
154 #[serde(deserialize_with = "crate::required::option")]
156 pub bit_depth: Option<u32>,
157 #[serde(deserialize_with = "crate::required::option")]
160 pub hdr: Option<BTreeSet<HdrFormat>>,
161}
162
163#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
171pub struct ClientCapabilities {
172 pub video: BTreeSet<VideoCodec>,
173 pub audio: BTreeSet<AudioCodec>,
174 pub containers: BTreeSet<Container>,
175 pub subtitles: BTreeSet<SubtitleFormat>,
176 pub delivery: Vec<Delivery>,
179 #[serde(deserialize_with = "crate::required::option")]
180 pub max_video: Option<VideoLimits>,
181 #[serde(deserialize_with = "crate::required::option")]
182 pub max_audio_channels: Option<u32>,
183 #[serde(deserialize_with = "crate::required::option")]
185 pub max_bitrate: Option<u64>,
186 #[serde(default)]
193 pub hardware_video: Option<BTreeSet<VideoCodec>>,
194 #[serde(default)]
202 pub video_codecs: Option<BTreeSet<String>>,
203}
204
205#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
214pub struct DisplayCapabilities {
215 #[serde(deserialize_with = "crate::required::option")]
217 pub bit_depth: Option<u32>,
218 #[serde(deserialize_with = "crate::required::option")]
220 pub hdr: Option<BTreeSet<HdrFormat>>,
221 #[serde(default)]
226 pub video_codecs: Option<BTreeSet<String>>,
227 #[serde(default)]
231 pub height: Option<u32>,
232 #[serde(default)]
235 pub frame_rate: Option<u32>,
236}
237
238fn said(limit: Option<u32>) -> Option<u32> {
241 limit.filter(|v| *v > 0)
242}
243
244fn lower(a: Option<u32>, b: Option<u32>) -> Option<u32> {
247 match (said(a), said(b)) {
248 (Some(a), Some(b)) => Some(a.min(b)),
249 (a, b) => a.or(b),
250 }
251}
252
253impl ClientCapabilities {
254 pub fn with_display(&self, display: Option<&DisplayCapabilities>) -> ClientCapabilities {
260 let mut caps = self.clone();
261 if let Some(display) = display {
262 let limits = caps.max_video.get_or_insert_with(VideoLimits::default);
263 limits.hdr = display.hdr.clone();
264 limits.bit_depth = display.bit_depth;
265 limits.height = lower(limits.height, display.height);
268 limits.frame_rate = lower(limits.frame_rate, display.frame_rate);
269 if display.video_codecs.is_some() {
270 caps.video_codecs = display.video_codecs.clone();
271 }
272 }
273 if let Some(limits) = caps.max_video.as_mut() {
274 limits.height = said(limits.height);
275 limits.frame_rate = said(limits.frame_rate);
276 }
277 caps
278 }
279
280 pub fn plays_codec_string(&self, source: &CodecString) -> Option<bool> {
285 let listed = self.video_codecs.as_ref()?;
286 Some(
287 listed
288 .iter()
289 .filter_map(|s| s.parse::<CodecString>().ok())
290 .any(|listed| listed.covers(source)),
291 )
292 }
293
294 pub fn decodes_in_hardware(&self, codec: VideoCodec) -> bool {
297 self.video.contains(&codec)
298 && self
299 .hardware_video
300 .as_ref()
301 .is_none_or(|hardware| hardware.contains(&codec))
302 }
303
304 pub fn deliveries(&self) -> Vec<Delivery> {
307 if self.delivery.is_empty() {
308 vec![Delivery::Range]
309 } else {
310 self.delivery.clone()
311 }
312 }
313}
314
315#[cfg(test)]
316mod tests {
317 use super::*;
318
319 #[test]
322 fn a_display_replaces_hdr_and_bit_depth_only() {
323 let hello = ClientCapabilities {
324 video: [VideoCodec::Hevc].into(),
325 max_video: Some(VideoLimits {
326 height: Some(1080),
327 frame_rate: Some(60),
328 bit_depth: Some(10),
329 hdr: Some([HdrFormat::Hdr10, HdrFormat::DolbyVision].into()),
330 }),
331 ..ClientCapabilities::default()
332 };
333 assert_eq!(hello.with_display(None), hello);
334 let sdr = DisplayCapabilities {
335 bit_depth: Some(8),
336 hdr: Some(BTreeSet::new()),
337 video_codecs: None,
338 height: None,
339 frame_rate: None,
340 };
341 let now = hello.with_display(Some(&sdr));
342 assert_eq!(
343 now.max_video,
344 Some(VideoLimits {
345 height: Some(1080),
346 frame_rate: Some(60),
347 bit_depth: Some(8),
348 hdr: Some(BTreeSet::new()),
349 })
350 );
351 assert_eq!(now.video, hello.video);
352 let unlimited = ClientCapabilities::default().with_display(Some(&sdr));
354 assert_eq!(unlimited.max_video.unwrap().hdr, Some(BTreeSet::new()));
355 }
356
357 #[test]
360 fn hello_at_zero_with_no_display_is_no_limit() {
361 let hello = ClientCapabilities {
362 max_video: Some(VideoLimits {
363 height: Some(0),
364 frame_rate: Some(0),
365 bit_depth: Some(10),
366 hdr: None,
367 }),
368 ..ClientCapabilities::default()
369 };
370 assert_eq!(
371 hello.with_display(None).max_video,
372 Some(VideoLimits {
373 height: None,
374 frame_rate: None,
375 bit_depth: Some(10),
376 hdr: None,
377 })
378 );
379 }
380
381 #[test]
384 fn a_display_at_zero_changes_no_limit() {
385 let limits = |height, frame_rate| ClientCapabilities {
386 max_video: Some(VideoLimits {
387 height,
388 frame_rate,
389 ..VideoLimits::default()
390 }),
391 ..ClientCapabilities::default()
392 };
393 let mode = |height, frame_rate| DisplayCapabilities {
394 height,
395 frame_rate,
396 ..DisplayCapabilities::default()
397 };
398 let limited = |caps: ClientCapabilities, display| {
399 let video = caps.with_display(Some(&display)).max_video.unwrap();
400 (video.height, video.frame_rate)
401 };
402 assert_eq!(
403 [
404 limited(limits(Some(2160), Some(60)), mode(Some(0), Some(0))),
405 limited(limits(None, None), mode(Some(0), Some(0))),
406 limited(limits(Some(0), Some(0)), mode(Some(1080), Some(30))),
407 ],
408 [(Some(2160), Some(60)), (None, None), (Some(1080), Some(30))]
409 );
410 }
411
412 #[test]
413 fn codecs_are_snake_case_on_the_wire() {
414 assert_eq!(
415 serde_json::to_string(&AudioCodec::TrueHd).unwrap(),
416 r#""true_hd""#
417 );
418 assert_eq!(AudioCodec::TrueHd.as_str(), "true_hd");
419 }
420
421 #[test]
422 fn a_codec_from_a_newer_peer_is_unknown() {
423 assert_eq!(
424 serde_json::from_str::<VideoCodec>(r#""h266""#).unwrap(),
425 VideoCodec::Unknown
426 );
427 }
428
429 #[test]
433 fn hardware_decoders_may_be_left_out() {
434 let old = r#"{"video":["hevc","av1"],"audio":[],"containers":[],"subtitles":[],
435 "delivery":[],"max_video":null,"max_audio_channels":null,"max_bitrate":null}"#;
436 let caps: ClientCapabilities = serde_json::from_str(old).unwrap();
437 assert_eq!(caps.hardware_video, None);
438 assert!(caps.decodes_in_hardware(VideoCodec::Av1));
439 assert!(
440 !caps.decodes_in_hardware(VideoCodec::H264),
441 "not played at all"
442 );
443 let said = ClientCapabilities {
444 hardware_video: Some([VideoCodec::Hevc].into()),
445 ..caps
446 };
447 assert!(said.decodes_in_hardware(VideoCodec::Hevc));
448 assert!(!said.decodes_in_hardware(VideoCodec::Av1));
449 let wire = serde_json::to_value(&said).unwrap();
450 assert_eq!(wire["hardware_video"], serde_json::json!(["hevc"]));
451 }
452
453 #[test]
458 fn a_client_lists_the_codec_strings_it_plays() {
459 let hello = r#"{"video":["hevc"],"audio":[],"containers":[],"subtitles":[],
460 "delivery":[],"max_video":null,"max_audio_channels":null,"max_bitrate":null,
461 "hardware_video":["hevc"],
462 "video_codecs":["hvc1.2.4.L153.B0","dvh1.08.06","vp09.00.10.08","nonsense"]}"#;
463 let caps: ClientCapabilities = serde_json::from_str(hello).unwrap();
464 let judge = |s: &str| caps.plays_codec_string(&s.parse().unwrap());
465 assert_eq!(judge("hvc1.2.4.L150.B0"), Some(true));
466 assert_eq!(judge("hvc1.2.4.L186.B0"), Some(false));
467 assert_eq!(judge("dvh1.08.06"), Some(true));
468 assert_eq!(judge("dvh1.07.06"), Some(false));
469 let wire = serde_json::to_value(&caps).unwrap();
470 assert_eq!(wire["video_codecs"][0], "dvh1.08.06", "a sorted set");
471 let unsaid = ClientCapabilities {
472 video_codecs: None,
473 ..caps.clone()
474 };
475 assert_eq!(
476 unsaid.plays_codec_string(&"hvc1.2.4.L186.B0".parse().unwrap()),
477 None
478 );
479 let old = r#"{"video":["hevc"],"audio":[],"containers":[],"subtitles":[],
480 "delivery":[],"max_video":null,"max_audio_channels":null,"max_bitrate":null}"#;
481 let old: ClientCapabilities = serde_json::from_str(old).unwrap();
482 assert_eq!(old.video_codecs, None);
483 }
484
485 #[test]
488 fn a_display_s_codec_strings_replace_hello_s() {
489 let hello = ClientCapabilities {
490 video: [VideoCodec::Hevc].into(),
491 video_codecs: Some(["dvh1.08.06".to_owned(), "hvc1.2.4.L153.B0".to_owned()].into()),
492 ..ClientCapabilities::default()
493 };
494 let sdr = DisplayCapabilities {
495 bit_depth: Some(8),
496 hdr: Some(BTreeSet::new()),
497 video_codecs: None,
498 height: None,
499 frame_rate: None,
500 };
501 assert_eq!(
502 hello.with_display(Some(&sdr)).video_codecs,
503 hello.video_codecs
504 );
505 let hdr10 = DisplayCapabilities {
506 video_codecs: Some(["hvc1.2.4.L153.B0".to_owned()].into()),
507 ..sdr
508 };
509 assert_eq!(
510 hello.with_display(Some(&hdr10)).video_codecs,
511 hdr10.video_codecs
512 );
513 let json = r#"{"bit_depth":10,"hdr":null}"#;
514 let display: DisplayCapabilities = serde_json::from_str(json).unwrap();
515 assert_eq!(display.video_codecs, None);
516 }
517
518 #[test]
519 fn a_client_without_deliveries_takes_range_reads() {
520 let caps = ClientCapabilities {
521 video: [VideoCodec::H264].into(),
522 ..ClientCapabilities::default()
523 };
524 assert_eq!(caps.deliveries(), [Delivery::Range]);
525 }
526
527 #[test]
530 fn capabilities_missing_a_field_are_refused() {
531 let caps = ClientCapabilities {
532 max_video: Some(VideoLimits::default()),
533 ..ClientCapabilities::default()
534 };
535 crate::test_support::assert_each_required(
536 &caps,
537 &[
538 "video",
539 "audio",
540 "containers",
541 "subtitles",
542 "delivery",
543 "max_video",
544 "max_audio_channels",
545 "max_bitrate",
546 ],
547 );
548 crate::test_support::assert_each_required(
549 &VideoLimits::default(),
550 &["height", "frame_rate", "bit_depth", "hdr"],
551 );
552 }
553
554 #[test]
555 fn a_delivery_from_a_newer_peer_is_unknown() {
556 assert_eq!(
557 serde_json::from_str::<Delivery>(r#""dash""#).unwrap(),
558 Delivery::Unknown
559 );
560 }
561
562 #[test]
563 fn capabilities_round_trip() {
564 let caps = ClientCapabilities {
565 video: [VideoCodec::H264, VideoCodec::Hevc].into(),
566 audio: [AudioCodec::Aac].into(),
567 containers: [Container::Matroska].into(),
568 subtitles: [SubtitleFormat::Srt].into(),
569 ..ClientCapabilities::default()
570 };
571 let json = serde_json::to_string(&caps).unwrap();
572 assert_eq!(
573 serde_json::from_str::<ClientCapabilities>(&json).unwrap(),
574 caps
575 );
576 }
577}