Skip to main content

spoolframe_types/
codec.rs

1//! The words server and client share for formats (ARCHITECTURE ยง8).
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 (P2-01).
105    Delivery {
106        /// Range reads of the file itself (P1-08).
107        Range => "range",
108        /// HLS playlists and segments (P2-05).
109        Hls => "hls",
110        /// One stream written as it is encoded, read by range (P2-04).
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 (PX-15): 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, which is what a Phase 1 client does.
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 Phase 1 default filled in.
251    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    /// A start's display replaces Hello's HDR formats and bit depth, and
265    /// nothing else (PGPU-06); none leaves them as they are.
266    #[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        // A client with no limits at Hello gets the display's.
296        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    /// PGPU-06: a client that leaves `hardware_video` out, as every one
318    /// of revision 14 does, is read, every codec it plays counting as
319    /// hardware; one that says counts only those.
320    #[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    /// The Apple TV of the ticket (plex:movie:1936): its list read as
342    /// `video_codecs`, a string it does not list refused, one the server
343    /// cannot read passed over; a client that left the field out says
344    /// nothing.
345    #[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    /// A start's display may list the strings again (its Dolby Vision
374    /// answer is that mode's); one that does not keeps Hello's.
375    #[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    /// Capabilities were optional field by field, so a client that left
414    /// one out was planned for as if it had none (PX-15).
415    #[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}