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        #[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
21        #[serde(rename_all = "snake_case")]
22        pub enum $name {
23            $($(#[$vdoc])* $variant,)*
24            /// A format this build does not know.
25            #[serde(other)]
26            Unknown,
27        }
28
29        impl $name {
30            /// The name on the wire.
31            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    /// A video codec.
49    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    /// An audio codec. `Dts` covers DTS-HD MA too: the core is DTS.
63    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    /// A container. `Matroska` covers WebM, which is a subset of it.
80    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    /// The MIME type a file in it is served as, by HTTP or to a player
93    /// that reads bytes. One a player has no type for is
94    /// `application/octet-stream`: the player sniffs it.
95    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    /// A subtitle format.
111    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    /// How a client takes media in.
124    Delivery {
125        /// Range reads of the file itself.
126        Range => "range",
127        /// HLS playlists and segments.
128        Hls => "hls",
129        /// One stream written as it is encoded, read by range.
130        Progressive => "progressive",
131    }
132);
133
134vocabulary!(
135    /// A high dynamic range format.
136    HdrFormat {
137        Hdr10 => "hdr10",
138        Hlg => "hlg",
139        DolbyVision => "dolby_vision",
140    }
141);
142
143/// The most video a client can show. Each limit that is `None` is no
144/// limit.
145#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
146pub struct VideoLimits {
147    /// Lines, e.g. 1080.
148    #[serde(deserialize_with = "crate::required::option")]
149    pub height: Option<u32>,
150    /// Frames per second.
151    #[serde(deserialize_with = "crate::required::option")]
152    pub frame_rate: Option<u32>,
153    /// Bits per sample, e.g. 8 for a client without 10-bit decoding.
154    #[serde(deserialize_with = "crate::required::option")]
155    pub bit_depth: Option<u32>,
156    /// The HDR formats it shows as HDR; anything else is tone-mapped to
157    /// SDR. `None`: all of them.
158    #[serde(deserialize_with = "crate::required::option")]
159    pub hdr: Option<BTreeSet<HdrFormat>>,
160}
161
162/// What a client can play. Belongs to the endpoint, not to a session: two
163/// profiles on one device have the same decoders. A client builds it from
164/// what it actually has (the Linux client from the GStreamer registry),
165/// not from a fixed list.
166///
167/// Every field is required on the wire: an empty set or `null`
168/// says "none", and a client that leaves a field out is refused.
169#[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    /// How it takes media in, preferred first. Empty means range reads
176    /// only.
177    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    /// Bits per second, from the client's settings. `None`: no limit.
183    #[serde(deserialize_with = "crate::required::option")]
184    pub max_bitrate: Option<u64>,
185    /// The video codecs of [`ClientCapabilities::video`] it decodes in
186    /// hardware (PGPU-06): a conversion goes to a codec the GPU encodes
187    /// only if the device decodes it in hardware, so AV1 is not sent to a
188    /// device that would decode it in software, draining its battery.
189    /// `None`: it does not say, and every codec it plays counts. Unlike
190    /// the fields above it may be left out, and is `None` then.
191    #[serde(default)]
192    pub hardware_video: Option<BTreeSet<VideoCodec>>,
193    /// The RFC 6381 codec strings it plays (`hvc1.2.4.L153.B0`,
194    /// `dvh1.08.06`; [`CodecString`]), as its player answers for each:
195    /// a video is copied only where one of them covers the source's own
196    /// string (its profile, tier and level, its Dolby Vision profile).
197    /// One the server does not read is passed over. `None`: it does not
198    /// say, and [`ClientCapabilities::video`] and `max_video` alone
199    /// decide. It may be left out, and is `None` then.
200    #[serde(default)]
201    pub video_codecs: Option<BTreeSet<String>>,
202}
203
204/// What the screen shows now, as a playback starts: [`VideoLimits::hdr`]
205/// and [`VideoLimits::bit_depth`] for that playback only, over what the
206/// client said at Hello. A TV's display mode changes while the app runs
207/// (Match Dynamic Range, another TV or receiver, HDR turned off), and
208/// capabilities from Hello would send HDR to an SDR mode or tone map for
209/// an HDR one.
210///
211/// Both fields are required, as in [`VideoLimits`]: `None` is no limit.
212#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
213pub struct DisplayCapabilities {
214    /// As [`VideoLimits::bit_depth`].
215    #[serde(deserialize_with = "crate::required::option")]
216    pub bit_depth: Option<u32>,
217    /// As [`VideoLimits::hdr`].
218    #[serde(deserialize_with = "crate::required::option")]
219    pub hdr: Option<BTreeSet<HdrFormat>>,
220    /// As [`ClientCapabilities::video_codecs`], asked again for this
221    /// display: a Dolby Vision string may be played on one mode and not
222    /// on another. `None` keeps Hello's. It may be left out, and is
223    /// `None` then.
224    #[serde(default)]
225    pub video_codecs: Option<BTreeSet<String>>,
226}
227
228impl ClientCapabilities {
229    /// These capabilities with `display`'s HDR formats and bit depth in
230    /// place of [`ClientCapabilities::max_video`]'s; unchanged without a
231    /// `display`.
232    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    /// Whether it plays a video whose own codec string is `source`, by
246    /// [`ClientCapabilities::video_codecs`]: some string listed there
247    /// [covers](CodecString::covers) it. `None` when it lists none (it
248    /// does not say), and nothing is known of it here.
249    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    /// Whether it decodes `codec` in hardware, as it says; every codec it
260    /// plays when it does not say (PGPU-06).
261    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    /// [`ClientCapabilities::delivery`], with the default (range reads
270    /// only) filled in when it is empty.
271    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    /// A start's display replaces Hello's HDR formats and bit depth, and
285    /// nothing else (PGPU-06); none leaves them as they are.
286    #[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        // A client with no limits at Hello gets the display's.
316        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    /// PGPU-06: a client that leaves `hardware_video` out, as every one
338    /// of revision 14 does, is read, every codec it plays counting as
339    /// hardware; one that says counts only those.
340    #[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    /// The Apple TV of the ticket (plex:movie:1936): its list read as
362    /// `video_codecs`, a string it does not list refused, one the server
363    /// cannot read passed over; a client that left the field out says
364    /// nothing.
365    #[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    /// A start's display may list the strings again (its Dolby Vision
394    /// answer is that mode's); one that does not keeps Hello's.
395    #[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    /// Capabilities were optional field by field, so a client that left
434    /// one out was planned for as if it had none (PX-15).
435    #[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}