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> {
253 if self.delivery.is_empty() {
254 vec![Delivery::Range]
255 } else {
256 self.delivery.clone()
257 }
258 }
259}
260
261#[cfg(test)]
262mod tests {
263 use super::*;
264
265 #[test]
268 fn a_display_replaces_hdr_and_bit_depth_only() {
269 let hello = ClientCapabilities {
270 video: [VideoCodec::Hevc].into(),
271 max_video: Some(VideoLimits {
272 height: Some(1080),
273 frame_rate: Some(60),
274 bit_depth: Some(10),
275 hdr: Some([HdrFormat::Hdr10, HdrFormat::DolbyVision].into()),
276 }),
277 ..ClientCapabilities::default()
278 };
279 assert_eq!(hello.with_display(None), hello);
280 let sdr = DisplayCapabilities {
281 bit_depth: Some(8),
282 hdr: Some(BTreeSet::new()),
283 video_codecs: None,
284 };
285 let now = hello.with_display(Some(&sdr));
286 assert_eq!(
287 now.max_video,
288 Some(VideoLimits {
289 height: Some(1080),
290 frame_rate: Some(60),
291 bit_depth: Some(8),
292 hdr: Some(BTreeSet::new()),
293 })
294 );
295 assert_eq!(now.video, hello.video);
296 let unlimited = ClientCapabilities::default().with_display(Some(&sdr));
298 assert_eq!(unlimited.max_video.unwrap().hdr, Some(BTreeSet::new()));
299 }
300
301 #[test]
302 fn codecs_are_snake_case_on_the_wire() {
303 assert_eq!(
304 serde_json::to_string(&AudioCodec::TrueHd).unwrap(),
305 r#""true_hd""#
306 );
307 assert_eq!(AudioCodec::TrueHd.as_str(), "true_hd");
308 }
309
310 #[test]
311 fn a_codec_from_a_newer_peer_is_unknown() {
312 assert_eq!(
313 serde_json::from_str::<VideoCodec>(r#""h266""#).unwrap(),
314 VideoCodec::Unknown
315 );
316 }
317
318 #[test]
322 fn hardware_decoders_may_be_left_out() {
323 let old = r#"{"video":["hevc","av1"],"audio":[],"containers":[],"subtitles":[],
324 "delivery":[],"max_video":null,"max_audio_channels":null,"max_bitrate":null}"#;
325 let caps: ClientCapabilities = serde_json::from_str(old).unwrap();
326 assert_eq!(caps.hardware_video, None);
327 assert!(caps.decodes_in_hardware(VideoCodec::Av1));
328 assert!(
329 !caps.decodes_in_hardware(VideoCodec::H264),
330 "not played at all"
331 );
332 let said = ClientCapabilities {
333 hardware_video: Some([VideoCodec::Hevc].into()),
334 ..caps
335 };
336 assert!(said.decodes_in_hardware(VideoCodec::Hevc));
337 assert!(!said.decodes_in_hardware(VideoCodec::Av1));
338 let wire = serde_json::to_value(&said).unwrap();
339 assert_eq!(wire["hardware_video"], serde_json::json!(["hevc"]));
340 }
341
342 #[test]
347 fn a_client_lists_the_codec_strings_it_plays() {
348 let hello = r#"{"video":["hevc"],"audio":[],"containers":[],"subtitles":[],
349 "delivery":[],"max_video":null,"max_audio_channels":null,"max_bitrate":null,
350 "hardware_video":["hevc"],
351 "video_codecs":["hvc1.2.4.L153.B0","dvh1.08.06","vp09.00.10.08","nonsense"]}"#;
352 let caps: ClientCapabilities = serde_json::from_str(hello).unwrap();
353 let judge = |s: &str| caps.plays_codec_string(&s.parse().unwrap());
354 assert_eq!(judge("hvc1.2.4.L150.B0"), Some(true));
355 assert_eq!(judge("hvc1.2.4.L186.B0"), Some(false));
356 assert_eq!(judge("dvh1.08.06"), Some(true));
357 assert_eq!(judge("dvh1.07.06"), Some(false));
358 let wire = serde_json::to_value(&caps).unwrap();
359 assert_eq!(wire["video_codecs"][0], "dvh1.08.06", "a sorted set");
360 let unsaid = ClientCapabilities {
361 video_codecs: None,
362 ..caps.clone()
363 };
364 assert_eq!(
365 unsaid.plays_codec_string(&"hvc1.2.4.L186.B0".parse().unwrap()),
366 None
367 );
368 let old = r#"{"video":["hevc"],"audio":[],"containers":[],"subtitles":[],
369 "delivery":[],"max_video":null,"max_audio_channels":null,"max_bitrate":null}"#;
370 let old: ClientCapabilities = serde_json::from_str(old).unwrap();
371 assert_eq!(old.video_codecs, None);
372 }
373
374 #[test]
377 fn a_display_s_codec_strings_replace_hello_s() {
378 let hello = ClientCapabilities {
379 video: [VideoCodec::Hevc].into(),
380 video_codecs: Some(["dvh1.08.06".to_owned(), "hvc1.2.4.L153.B0".to_owned()].into()),
381 ..ClientCapabilities::default()
382 };
383 let sdr = DisplayCapabilities {
384 bit_depth: Some(8),
385 hdr: Some(BTreeSet::new()),
386 video_codecs: None,
387 };
388 assert_eq!(
389 hello.with_display(Some(&sdr)).video_codecs,
390 hello.video_codecs
391 );
392 let hdr10 = DisplayCapabilities {
393 video_codecs: Some(["hvc1.2.4.L153.B0".to_owned()].into()),
394 ..sdr
395 };
396 assert_eq!(
397 hello.with_display(Some(&hdr10)).video_codecs,
398 hdr10.video_codecs
399 );
400 let json = r#"{"bit_depth":10,"hdr":null}"#;
401 let display: DisplayCapabilities = serde_json::from_str(json).unwrap();
402 assert_eq!(display.video_codecs, None);
403 }
404
405 #[test]
406 fn a_client_without_deliveries_takes_range_reads() {
407 let caps = ClientCapabilities {
408 video: [VideoCodec::H264].into(),
409 ..ClientCapabilities::default()
410 };
411 assert_eq!(caps.deliveries(), [Delivery::Range]);
412 }
413
414 #[test]
417 fn capabilities_missing_a_field_are_refused() {
418 let caps = ClientCapabilities {
419 max_video: Some(VideoLimits::default()),
420 ..ClientCapabilities::default()
421 };
422 crate::test_support::assert_each_required(
423 &caps,
424 &[
425 "video",
426 "audio",
427 "containers",
428 "subtitles",
429 "delivery",
430 "max_video",
431 "max_audio_channels",
432 "max_bitrate",
433 ],
434 );
435 crate::test_support::assert_each_required(
436 &VideoLimits::default(),
437 &["height", "frame_rate", "bit_depth", "hdr"],
438 );
439 }
440
441 #[test]
442 fn a_delivery_from_a_newer_peer_is_unknown() {
443 assert_eq!(
444 serde_json::from_str::<Delivery>(r#""dash""#).unwrap(),
445 Delivery::Unknown
446 );
447 }
448
449 #[test]
450 fn capabilities_round_trip() {
451 let caps = ClientCapabilities {
452 video: [VideoCodec::H264, VideoCodec::Hevc].into(),
453 audio: [AudioCodec::Aac].into(),
454 containers: [Container::Matroska].into(),
455 subtitles: [SubtitleFormat::Srt].into(),
456 ..ClientCapabilities::default()
457 };
458 let json = serde_json::to_string(&caps).unwrap();
459 assert_eq!(
460 serde_json::from_str::<ClientCapabilities>(&json).unwrap(),
461 caps
462 );
463 }
464}