Skip to main content

spoolframe_types/
codec.rs

1//! The words server and client share for formats.
2//!
3//! The server knows streams by ffprobe's names (`hevc`, `hdmv_pgs_subtitle`)
4//! and a GStreamer client knows its decoders by caps (`video/x-h265`);
5//! compared as strings they never match. Each side maps its own names to
6//! these enums instead. A format either side does not know is `Unknown`,
7//! which no client supports, so a plan says so rather than guessing.
8
9use 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            /// A format this build does not know.
24            #[serde(other)]
25            Unknown,
26        }
27
28        impl $name {
29            /// The name on the wire.
30            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    /// A video codec.
48    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    /// An audio codec. `Dts` covers DTS-HD MA too: the core is DTS.
62    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    /// A container. `Matroska` covers WebM, which is a subset of it.
79    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    /// A subtitle format.
92    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    /// How a client takes media in.
105    Delivery {
106        /// Range reads of the file itself.
107        Range => "range",
108        /// HLS playlists and segments.
109        Hls => "hls",
110        /// One stream written as it is encoded, read by range.
111        Progressive => "progressive",
112    }
113);
114
115vocabulary!(
116    /// A high dynamic range format.
117    HdrFormat {
118        Hdr10 => "hdr10",
119        Hlg => "hlg",
120        DolbyVision => "dolby_vision",
121    }
122);
123
124/// The most video a client can show. Each limit that is `None` is no
125/// limit.
126#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
127pub struct VideoLimits {
128    /// Lines, e.g. 1080.
129    #[serde(deserialize_with = "crate::required::option")]
130    pub height: Option<u32>,
131    /// Frames per second.
132    #[serde(deserialize_with = "crate::required::option")]
133    pub frame_rate: Option<u32>,
134    /// Bits per sample, e.g. 8 for a client without 10-bit decoding.
135    #[serde(deserialize_with = "crate::required::option")]
136    pub bit_depth: Option<u32>,
137    /// The HDR formats it shows as HDR; anything else is tone-mapped to
138    /// SDR. `None`: all of them.
139    #[serde(deserialize_with = "crate::required::option")]
140    pub hdr: Option<BTreeSet<HdrFormat>>,
141}
142
143/// What a client can play. Belongs to the endpoint, not to a session: two
144/// profiles on one device have the same decoders. A client builds it from
145/// what it actually has (the Linux client from the GStreamer registry),
146/// not from a fixed list.
147///
148/// Every field is required on the wire: an empty set or `null`
149/// says "none", and a client that leaves a field out is refused.
150#[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    /// How it takes media in, preferred first. Empty means range reads
157    /// only.
158    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    /// Bits per second, from the client's settings. `None`: no limit.
164    #[serde(deserialize_with = "crate::required::option")]
165    pub max_bitrate: Option<u64>,
166    /// The video codecs of [`ClientCapabilities::video`] it decodes in
167    /// hardware (PGPU-06): a conversion goes to a codec the GPU encodes
168    /// only if the device decodes it in hardware, so AV1 is not sent to a
169    /// device that would decode it in software, draining its battery.
170    /// `None`: it does not say, and every codec it plays counts. Unlike
171    /// the fields above it may be left out, and is `None` then.
172    #[serde(default)]
173    pub hardware_video: Option<BTreeSet<VideoCodec>>,
174    /// The RFC 6381 codec strings it plays (`hvc1.2.4.L153.B0`,
175    /// `dvh1.08.06`; [`CodecString`]), as its player answers for each:
176    /// a video is copied only where one of them covers the source's own
177    /// string (its profile, tier and level, its Dolby Vision profile).
178    /// One the server does not read is passed over. `None`: it does not
179    /// say, and [`ClientCapabilities::video`] and `max_video` alone
180    /// decide. It may be left out, and is `None` then.
181    #[serde(default)]
182    pub video_codecs: Option<BTreeSet<String>>,
183}
184
185/// What the screen shows now, as a playback starts: [`VideoLimits::hdr`]
186/// and [`VideoLimits::bit_depth`] for that playback only, over what the
187/// client said at Hello. A TV's display mode changes while the app runs
188/// (Match Dynamic Range, another TV or receiver, HDR turned off), and
189/// capabilities from Hello would send HDR to an SDR mode or tone map for
190/// an HDR one.
191///
192/// Both fields are required, as in [`VideoLimits`]: `None` is no limit.
193#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
194pub struct DisplayCapabilities {
195    /// As [`VideoLimits::bit_depth`].
196    #[serde(deserialize_with = "crate::required::option")]
197    pub bit_depth: Option<u32>,
198    /// As [`VideoLimits::hdr`].
199    #[serde(deserialize_with = "crate::required::option")]
200    pub hdr: Option<BTreeSet<HdrFormat>>,
201    /// As [`ClientCapabilities::video_codecs`], asked again for this
202    /// display: a Dolby Vision string may be played on one mode and not
203    /// on another. `None` keeps Hello's. It may be left out, and is
204    /// `None` then.
205    #[serde(default)]
206    pub video_codecs: Option<BTreeSet<String>>,
207}
208
209impl ClientCapabilities {
210    /// These capabilities with `display`'s HDR formats and bit depth in
211    /// place of [`ClientCapabilities::max_video`]'s; unchanged without a
212    /// `display`.
213    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    /// Whether it plays a video whose own codec string is `source`, by
227    /// [`ClientCapabilities::video_codecs`]: some string listed there
228    /// [covers](CodecString::covers) it. `None` when it lists none (it
229    /// does not say), and nothing is known of it here.
230    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    /// Whether it decodes `codec` in hardware, as it says; every codec it
241    /// plays when it does not say (PGPU-06).
242    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    /// [`ClientCapabilities::delivery`], with the default (range reads
251    /// only) filled in when it is empty.
252    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    /// A start's display replaces Hello's HDR formats and bit depth, and
266    /// nothing else (PGPU-06); none leaves them as they are.
267    #[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        // A client with no limits at Hello gets the display's.
297        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    /// PGPU-06: a client that leaves `hardware_video` out, as every one
319    /// of revision 14 does, is read, every codec it plays counting as
320    /// hardware; one that says counts only those.
321    #[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    /// The Apple TV of the ticket (plex:movie:1936): its list read as
343    /// `video_codecs`, a string it does not list refused, one the server
344    /// cannot read passed over; a client that left the field out says
345    /// nothing.
346    #[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    /// A start's display may list the strings again (its Dolby Vision
375    /// answer is that mode's); one that does not keeps Hello's.
376    #[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    /// Capabilities were optional field by field, so a client that left
415    /// one out was planned for as if it had none (PX-15).
416    #[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}