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")]
149 pub height: Option<u32>,
150 #[serde(deserialize_with = "crate::required::option")]
152 pub frame_rate: Option<u32>,
153 #[serde(deserialize_with = "crate::required::option")]
155 pub bit_depth: Option<u32>,
156 #[serde(deserialize_with = "crate::required::option")]
159 pub hdr: Option<BTreeSet<HdrFormat>>,
160}
161
162#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
170pub struct ClientCapabilities {
171 pub video: BTreeSet<VideoCodec>,
172 pub audio: BTreeSet<AudioCodec>,
173 pub containers: BTreeSet<Container>,
174 pub subtitles: BTreeSet<SubtitleFormat>,
175 pub delivery: Vec<Delivery>,
178 #[serde(deserialize_with = "crate::required::option")]
179 pub max_video: Option<VideoLimits>,
180 #[serde(deserialize_with = "crate::required::option")]
181 pub max_audio_channels: Option<u32>,
182 #[serde(deserialize_with = "crate::required::option")]
184 pub max_bitrate: Option<u64>,
185 #[serde(default)]
192 pub hardware_video: Option<BTreeSet<VideoCodec>>,
193 #[serde(default)]
201 pub video_codecs: Option<BTreeSet<String>>,
202}
203
204#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
213pub struct DisplayCapabilities {
214 #[serde(deserialize_with = "crate::required::option")]
216 pub bit_depth: Option<u32>,
217 #[serde(deserialize_with = "crate::required::option")]
219 pub hdr: Option<BTreeSet<HdrFormat>>,
220 #[serde(default)]
225 pub video_codecs: Option<BTreeSet<String>>,
226}
227
228impl ClientCapabilities {
229 pub fn with_display(&self, display: Option<&DisplayCapabilities>) -> ClientCapabilities {
233 let mut caps = self.clone();
234 if let Some(display) = display {
235 let limits = caps.max_video.get_or_insert_with(VideoLimits::default);
236 limits.hdr = display.hdr.clone();
237 limits.bit_depth = display.bit_depth;
238 if display.video_codecs.is_some() {
239 caps.video_codecs = display.video_codecs.clone();
240 }
241 }
242 caps
243 }
244
245 pub fn plays_codec_string(&self, source: &CodecString) -> Option<bool> {
250 let listed = self.video_codecs.as_ref()?;
251 Some(
252 listed
253 .iter()
254 .filter_map(|s| s.parse::<CodecString>().ok())
255 .any(|listed| listed.covers(source)),
256 )
257 }
258
259 pub fn decodes_in_hardware(&self, codec: VideoCodec) -> bool {
262 self.video.contains(&codec)
263 && self
264 .hardware_video
265 .as_ref()
266 .is_none_or(|hardware| hardware.contains(&codec))
267 }
268
269 pub fn deliveries(&self) -> Vec<Delivery> {
272 if self.delivery.is_empty() {
273 vec![Delivery::Range]
274 } else {
275 self.delivery.clone()
276 }
277 }
278}
279
280#[cfg(test)]
281mod tests {
282 use super::*;
283
284 #[test]
287 fn a_display_replaces_hdr_and_bit_depth_only() {
288 let hello = ClientCapabilities {
289 video: [VideoCodec::Hevc].into(),
290 max_video: Some(VideoLimits {
291 height: Some(1080),
292 frame_rate: Some(60),
293 bit_depth: Some(10),
294 hdr: Some([HdrFormat::Hdr10, HdrFormat::DolbyVision].into()),
295 }),
296 ..ClientCapabilities::default()
297 };
298 assert_eq!(hello.with_display(None), hello);
299 let sdr = DisplayCapabilities {
300 bit_depth: Some(8),
301 hdr: Some(BTreeSet::new()),
302 video_codecs: None,
303 };
304 let now = hello.with_display(Some(&sdr));
305 assert_eq!(
306 now.max_video,
307 Some(VideoLimits {
308 height: Some(1080),
309 frame_rate: Some(60),
310 bit_depth: Some(8),
311 hdr: Some(BTreeSet::new()),
312 })
313 );
314 assert_eq!(now.video, hello.video);
315 let unlimited = ClientCapabilities::default().with_display(Some(&sdr));
317 assert_eq!(unlimited.max_video.unwrap().hdr, Some(BTreeSet::new()));
318 }
319
320 #[test]
321 fn codecs_are_snake_case_on_the_wire() {
322 assert_eq!(
323 serde_json::to_string(&AudioCodec::TrueHd).unwrap(),
324 r#""true_hd""#
325 );
326 assert_eq!(AudioCodec::TrueHd.as_str(), "true_hd");
327 }
328
329 #[test]
330 fn a_codec_from_a_newer_peer_is_unknown() {
331 assert_eq!(
332 serde_json::from_str::<VideoCodec>(r#""h266""#).unwrap(),
333 VideoCodec::Unknown
334 );
335 }
336
337 #[test]
341 fn hardware_decoders_may_be_left_out() {
342 let old = r#"{"video":["hevc","av1"],"audio":[],"containers":[],"subtitles":[],
343 "delivery":[],"max_video":null,"max_audio_channels":null,"max_bitrate":null}"#;
344 let caps: ClientCapabilities = serde_json::from_str(old).unwrap();
345 assert_eq!(caps.hardware_video, None);
346 assert!(caps.decodes_in_hardware(VideoCodec::Av1));
347 assert!(
348 !caps.decodes_in_hardware(VideoCodec::H264),
349 "not played at all"
350 );
351 let said = ClientCapabilities {
352 hardware_video: Some([VideoCodec::Hevc].into()),
353 ..caps
354 };
355 assert!(said.decodes_in_hardware(VideoCodec::Hevc));
356 assert!(!said.decodes_in_hardware(VideoCodec::Av1));
357 let wire = serde_json::to_value(&said).unwrap();
358 assert_eq!(wire["hardware_video"], serde_json::json!(["hevc"]));
359 }
360
361 #[test]
366 fn a_client_lists_the_codec_strings_it_plays() {
367 let hello = r#"{"video":["hevc"],"audio":[],"containers":[],"subtitles":[],
368 "delivery":[],"max_video":null,"max_audio_channels":null,"max_bitrate":null,
369 "hardware_video":["hevc"],
370 "video_codecs":["hvc1.2.4.L153.B0","dvh1.08.06","vp09.00.10.08","nonsense"]}"#;
371 let caps: ClientCapabilities = serde_json::from_str(hello).unwrap();
372 let judge = |s: &str| caps.plays_codec_string(&s.parse().unwrap());
373 assert_eq!(judge("hvc1.2.4.L150.B0"), Some(true));
374 assert_eq!(judge("hvc1.2.4.L186.B0"), Some(false));
375 assert_eq!(judge("dvh1.08.06"), Some(true));
376 assert_eq!(judge("dvh1.07.06"), Some(false));
377 let wire = serde_json::to_value(&caps).unwrap();
378 assert_eq!(wire["video_codecs"][0], "dvh1.08.06", "a sorted set");
379 let unsaid = ClientCapabilities {
380 video_codecs: None,
381 ..caps.clone()
382 };
383 assert_eq!(
384 unsaid.plays_codec_string(&"hvc1.2.4.L186.B0".parse().unwrap()),
385 None
386 );
387 let old = r#"{"video":["hevc"],"audio":[],"containers":[],"subtitles":[],
388 "delivery":[],"max_video":null,"max_audio_channels":null,"max_bitrate":null}"#;
389 let old: ClientCapabilities = serde_json::from_str(old).unwrap();
390 assert_eq!(old.video_codecs, None);
391 }
392
393 #[test]
396 fn a_display_s_codec_strings_replace_hello_s() {
397 let hello = ClientCapabilities {
398 video: [VideoCodec::Hevc].into(),
399 video_codecs: Some(["dvh1.08.06".to_owned(), "hvc1.2.4.L153.B0".to_owned()].into()),
400 ..ClientCapabilities::default()
401 };
402 let sdr = DisplayCapabilities {
403 bit_depth: Some(8),
404 hdr: Some(BTreeSet::new()),
405 video_codecs: None,
406 };
407 assert_eq!(
408 hello.with_display(Some(&sdr)).video_codecs,
409 hello.video_codecs
410 );
411 let hdr10 = DisplayCapabilities {
412 video_codecs: Some(["hvc1.2.4.L153.B0".to_owned()].into()),
413 ..sdr
414 };
415 assert_eq!(
416 hello.with_display(Some(&hdr10)).video_codecs,
417 hdr10.video_codecs
418 );
419 let json = r#"{"bit_depth":10,"hdr":null}"#;
420 let display: DisplayCapabilities = serde_json::from_str(json).unwrap();
421 assert_eq!(display.video_codecs, None);
422 }
423
424 #[test]
425 fn a_client_without_deliveries_takes_range_reads() {
426 let caps = ClientCapabilities {
427 video: [VideoCodec::H264].into(),
428 ..ClientCapabilities::default()
429 };
430 assert_eq!(caps.deliveries(), [Delivery::Range]);
431 }
432
433 #[test]
436 fn capabilities_missing_a_field_are_refused() {
437 let caps = ClientCapabilities {
438 max_video: Some(VideoLimits::default()),
439 ..ClientCapabilities::default()
440 };
441 crate::test_support::assert_each_required(
442 &caps,
443 &[
444 "video",
445 "audio",
446 "containers",
447 "subtitles",
448 "delivery",
449 "max_video",
450 "max_audio_channels",
451 "max_bitrate",
452 ],
453 );
454 crate::test_support::assert_each_required(
455 &VideoLimits::default(),
456 &["height", "frame_rate", "bit_depth", "hdr"],
457 );
458 }
459
460 #[test]
461 fn a_delivery_from_a_newer_peer_is_unknown() {
462 assert_eq!(
463 serde_json::from_str::<Delivery>(r#""dash""#).unwrap(),
464 Delivery::Unknown
465 );
466 }
467
468 #[test]
469 fn capabilities_round_trip() {
470 let caps = ClientCapabilities {
471 video: [VideoCodec::H264, VideoCodec::Hevc].into(),
472 audio: [AudioCodec::Aac].into(),
473 containers: [Container::Matroska].into(),
474 subtitles: [SubtitleFormat::Srt].into(),
475 ..ClientCapabilities::default()
476 };
477 let json = serde_json::to_string(&caps).unwrap();
478 assert_eq!(
479 serde_json::from_str::<ClientCapabilities>(&json).unwrap(),
480 caps
481 );
482 }
483}