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 #[serde(rename_all = "snake_case")]
21 pub enum $name {
22 $($(#[$vdoc])* $variant,)*
23 #[serde(other)]
25 Unknown,
26 }
27
28 impl $name {
29 pub fn as_str(self) -> &'static str {
31 match self {
32 $($name::$variant => $wire,)*
33 $name::Unknown => "unknown",
34 }
35 }
36 }
37
38 impl fmt::Display for $name {
39 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40 f.write_str(self.as_str())
41 }
42 }
43 };
44}
45
46vocabulary!(
47 VideoCodec {
49 H264 => "h264",
50 Hevc => "hevc",
51 Av1 => "av1",
52 Vp9 => "vp9",
53 Vp8 => "vp8",
54 Mpeg2 => "mpeg2",
55 Mpeg4 => "mpeg4",
56 Vc1 => "vc1",
57 }
58);
59
60vocabulary!(
61 AudioCodec {
63 Aac => "aac",
64 Ac3 => "ac3",
65 Eac3 => "eac3",
66 Dts => "dts",
67 TrueHd => "true_hd",
68 Flac => "flac",
69 Alac => "alac",
70 Opus => "opus",
71 Vorbis => "vorbis",
72 Mp3 => "mp3",
73 Pcm => "pcm",
74 }
75);
76
77vocabulary!(
78 Container {
80 Matroska => "matroska",
81 Mp4 => "mp4",
82 MpegTs => "mpeg_ts",
83 Avi => "avi",
84 Flac => "flac",
85 Mp3 => "mp3",
86 Ogg => "ogg",
87 }
88);
89
90vocabulary!(
91 SubtitleFormat {
93 Srt => "srt",
94 Ass => "ass",
95 WebVtt => "web_vtt",
96 MovText => "mov_text",
97 Pgs => "pgs",
98 VobSub => "vob_sub",
99 DvbSub => "dvb_sub",
100 }
101);
102
103vocabulary!(
104 Delivery {
106 Range => "range",
108 Hls => "hls",
110 Progressive => "progressive",
112 }
113);
114
115vocabulary!(
116 HdrFormat {
118 Hdr10 => "hdr10",
119 Hlg => "hlg",
120 DolbyVision => "dolby_vision",
121 }
122);
123
124#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
127pub struct VideoLimits {
128 #[serde(deserialize_with = "crate::required::option")]
130 pub height: Option<u32>,
131 #[serde(deserialize_with = "crate::required::option")]
133 pub frame_rate: Option<u32>,
134 #[serde(deserialize_with = "crate::required::option")]
136 pub bit_depth: Option<u32>,
137 #[serde(deserialize_with = "crate::required::option")]
140 pub hdr: Option<BTreeSet<HdrFormat>>,
141}
142
143#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
151pub struct ClientCapabilities {
152 pub video: BTreeSet<VideoCodec>,
153 pub audio: BTreeSet<AudioCodec>,
154 pub containers: BTreeSet<Container>,
155 pub subtitles: BTreeSet<SubtitleFormat>,
156 pub delivery: Vec<Delivery>,
159 #[serde(deserialize_with = "crate::required::option")]
160 pub max_video: Option<VideoLimits>,
161 #[serde(deserialize_with = "crate::required::option")]
162 pub max_audio_channels: Option<u32>,
163 #[serde(deserialize_with = "crate::required::option")]
165 pub max_bitrate: Option<u64>,
166 #[serde(default)]
173 pub hardware_video: Option<BTreeSet<VideoCodec>>,
174 #[serde(default)]
182 pub video_codecs: Option<BTreeSet<String>>,
183}
184
185#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
194pub struct DisplayCapabilities {
195 #[serde(deserialize_with = "crate::required::option")]
197 pub bit_depth: Option<u32>,
198 #[serde(deserialize_with = "crate::required::option")]
200 pub hdr: Option<BTreeSet<HdrFormat>>,
201 #[serde(default)]
206 pub video_codecs: Option<BTreeSet<String>>,
207}
208
209impl ClientCapabilities {
210 pub fn with_display(&self, display: Option<&DisplayCapabilities>) -> ClientCapabilities {
214 let mut caps = self.clone();
215 if let Some(display) = display {
216 let limits = caps.max_video.get_or_insert_with(VideoLimits::default);
217 limits.hdr = display.hdr.clone();
218 limits.bit_depth = display.bit_depth;
219 if display.video_codecs.is_some() {
220 caps.video_codecs = display.video_codecs.clone();
221 }
222 }
223 caps
224 }
225
226 pub fn plays_codec_string(&self, source: &CodecString) -> Option<bool> {
231 let listed = self.video_codecs.as_ref()?;
232 Some(
233 listed
234 .iter()
235 .filter_map(|s| s.parse::<CodecString>().ok())
236 .any(|listed| listed.covers(source)),
237 )
238 }
239
240 pub fn decodes_in_hardware(&self, codec: VideoCodec) -> bool {
243 self.video.contains(&codec)
244 && self
245 .hardware_video
246 .as_ref()
247 .is_none_or(|hardware| hardware.contains(&codec))
248 }
249
250 pub fn deliveries(&self) -> Vec<Delivery> {
252 if self.delivery.is_empty() {
253 vec![Delivery::Range]
254 } else {
255 self.delivery.clone()
256 }
257 }
258}
259
260#[cfg(test)]
261mod tests {
262 use super::*;
263
264 #[test]
267 fn a_display_replaces_hdr_and_bit_depth_only() {
268 let hello = ClientCapabilities {
269 video: [VideoCodec::Hevc].into(),
270 max_video: Some(VideoLimits {
271 height: Some(1080),
272 frame_rate: Some(60),
273 bit_depth: Some(10),
274 hdr: Some([HdrFormat::Hdr10, HdrFormat::DolbyVision].into()),
275 }),
276 ..ClientCapabilities::default()
277 };
278 assert_eq!(hello.with_display(None), hello);
279 let sdr = DisplayCapabilities {
280 bit_depth: Some(8),
281 hdr: Some(BTreeSet::new()),
282 video_codecs: None,
283 };
284 let now = hello.with_display(Some(&sdr));
285 assert_eq!(
286 now.max_video,
287 Some(VideoLimits {
288 height: Some(1080),
289 frame_rate: Some(60),
290 bit_depth: Some(8),
291 hdr: Some(BTreeSet::new()),
292 })
293 );
294 assert_eq!(now.video, hello.video);
295 let unlimited = ClientCapabilities::default().with_display(Some(&sdr));
297 assert_eq!(unlimited.max_video.unwrap().hdr, Some(BTreeSet::new()));
298 }
299
300 #[test]
301 fn codecs_are_snake_case_on_the_wire() {
302 assert_eq!(
303 serde_json::to_string(&AudioCodec::TrueHd).unwrap(),
304 r#""true_hd""#
305 );
306 assert_eq!(AudioCodec::TrueHd.as_str(), "true_hd");
307 }
308
309 #[test]
310 fn a_codec_from_a_newer_peer_is_unknown() {
311 assert_eq!(
312 serde_json::from_str::<VideoCodec>(r#""h266""#).unwrap(),
313 VideoCodec::Unknown
314 );
315 }
316
317 #[test]
321 fn hardware_decoders_may_be_left_out() {
322 let old = r#"{"video":["hevc","av1"],"audio":[],"containers":[],"subtitles":[],
323 "delivery":[],"max_video":null,"max_audio_channels":null,"max_bitrate":null}"#;
324 let caps: ClientCapabilities = serde_json::from_str(old).unwrap();
325 assert_eq!(caps.hardware_video, None);
326 assert!(caps.decodes_in_hardware(VideoCodec::Av1));
327 assert!(
328 !caps.decodes_in_hardware(VideoCodec::H264),
329 "not played at all"
330 );
331 let said = ClientCapabilities {
332 hardware_video: Some([VideoCodec::Hevc].into()),
333 ..caps
334 };
335 assert!(said.decodes_in_hardware(VideoCodec::Hevc));
336 assert!(!said.decodes_in_hardware(VideoCodec::Av1));
337 let wire = serde_json::to_value(&said).unwrap();
338 assert_eq!(wire["hardware_video"], serde_json::json!(["hevc"]));
339 }
340
341 #[test]
346 fn a_client_lists_the_codec_strings_it_plays() {
347 let hello = r#"{"video":["hevc"],"audio":[],"containers":[],"subtitles":[],
348 "delivery":[],"max_video":null,"max_audio_channels":null,"max_bitrate":null,
349 "hardware_video":["hevc"],
350 "video_codecs":["hvc1.2.4.L153.B0","dvh1.08.06","vp09.00.10.08","nonsense"]}"#;
351 let caps: ClientCapabilities = serde_json::from_str(hello).unwrap();
352 let judge = |s: &str| caps.plays_codec_string(&s.parse().unwrap());
353 assert_eq!(judge("hvc1.2.4.L150.B0"), Some(true));
354 assert_eq!(judge("hvc1.2.4.L186.B0"), Some(false));
355 assert_eq!(judge("dvh1.08.06"), Some(true));
356 assert_eq!(judge("dvh1.07.06"), Some(false));
357 let wire = serde_json::to_value(&caps).unwrap();
358 assert_eq!(wire["video_codecs"][0], "dvh1.08.06", "a sorted set");
359 let unsaid = ClientCapabilities {
360 video_codecs: None,
361 ..caps.clone()
362 };
363 assert_eq!(
364 unsaid.plays_codec_string(&"hvc1.2.4.L186.B0".parse().unwrap()),
365 None
366 );
367 let old = r#"{"video":["hevc"],"audio":[],"containers":[],"subtitles":[],
368 "delivery":[],"max_video":null,"max_audio_channels":null,"max_bitrate":null}"#;
369 let old: ClientCapabilities = serde_json::from_str(old).unwrap();
370 assert_eq!(old.video_codecs, None);
371 }
372
373 #[test]
376 fn a_display_s_codec_strings_replace_hello_s() {
377 let hello = ClientCapabilities {
378 video: [VideoCodec::Hevc].into(),
379 video_codecs: Some(["dvh1.08.06".to_owned(), "hvc1.2.4.L153.B0".to_owned()].into()),
380 ..ClientCapabilities::default()
381 };
382 let sdr = DisplayCapabilities {
383 bit_depth: Some(8),
384 hdr: Some(BTreeSet::new()),
385 video_codecs: None,
386 };
387 assert_eq!(
388 hello.with_display(Some(&sdr)).video_codecs,
389 hello.video_codecs
390 );
391 let hdr10 = DisplayCapabilities {
392 video_codecs: Some(["hvc1.2.4.L153.B0".to_owned()].into()),
393 ..sdr
394 };
395 assert_eq!(
396 hello.with_display(Some(&hdr10)).video_codecs,
397 hdr10.video_codecs
398 );
399 let json = r#"{"bit_depth":10,"hdr":null}"#;
400 let display: DisplayCapabilities = serde_json::from_str(json).unwrap();
401 assert_eq!(display.video_codecs, None);
402 }
403
404 #[test]
405 fn a_client_without_deliveries_takes_range_reads() {
406 let caps = ClientCapabilities {
407 video: [VideoCodec::H264].into(),
408 ..ClientCapabilities::default()
409 };
410 assert_eq!(caps.deliveries(), [Delivery::Range]);
411 }
412
413 #[test]
416 fn capabilities_missing_a_field_are_refused() {
417 let caps = ClientCapabilities {
418 max_video: Some(VideoLimits::default()),
419 ..ClientCapabilities::default()
420 };
421 crate::test_support::assert_each_required(
422 &caps,
423 &[
424 "video",
425 "audio",
426 "containers",
427 "subtitles",
428 "delivery",
429 "max_video",
430 "max_audio_channels",
431 "max_bitrate",
432 ],
433 );
434 crate::test_support::assert_each_required(
435 &VideoLimits::default(),
436 &["height", "frame_rate", "bit_depth", "hdr"],
437 );
438 }
439
440 #[test]
441 fn a_delivery_from_a_newer_peer_is_unknown() {
442 assert_eq!(
443 serde_json::from_str::<Delivery>(r#""dash""#).unwrap(),
444 Delivery::Unknown
445 );
446 }
447
448 #[test]
449 fn capabilities_round_trip() {
450 let caps = ClientCapabilities {
451 video: [VideoCodec::H264, VideoCodec::Hevc].into(),
452 audio: [AudioCodec::Aac].into(),
453 containers: [Container::Matroska].into(),
454 subtitles: [SubtitleFormat::Srt].into(),
455 ..ClientCapabilities::default()
456 };
457 let json = serde_json::to_string(&caps).unwrap();
458 assert_eq!(
459 serde_json::from_str::<ClientCapabilities>(&json).unwrap(),
460 caps
461 );
462 }
463}