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. At Hello, what the decoders take: the screen's
148    /// mode goes with each plan ([`DisplayCapabilities::height`]).
149    #[serde(deserialize_with = "crate::required::option")]
150    pub height: Option<u32>,
151    /// Frames per second. At Hello, what the decoders take, as `height`.
152    #[serde(deserialize_with = "crate::required::option")]
153    pub frame_rate: Option<u32>,
154    /// Bits per sample, e.g. 8 for a client without 10-bit decoding.
155    #[serde(deserialize_with = "crate::required::option")]
156    pub bit_depth: Option<u32>,
157    /// The HDR formats it shows as HDR; anything else is tone-mapped to
158    /// SDR. `None`: all of them.
159    #[serde(deserialize_with = "crate::required::option")]
160    pub hdr: Option<BTreeSet<HdrFormat>>,
161}
162
163/// What a client can play. Belongs to the endpoint, not to a session: two
164/// profiles on one device have the same decoders. A client builds it from
165/// what it actually has (the Linux client from the GStreamer registry),
166/// not from a fixed list.
167///
168/// Every field is required on the wire: an empty set or `null`
169/// says "none", and a client that leaves a field out is refused.
170#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
171pub struct ClientCapabilities {
172    pub video: BTreeSet<VideoCodec>,
173    pub audio: BTreeSet<AudioCodec>,
174    pub containers: BTreeSet<Container>,
175    pub subtitles: BTreeSet<SubtitleFormat>,
176    /// How it takes media in, preferred first. Empty means range reads
177    /// only.
178    pub delivery: Vec<Delivery>,
179    #[serde(deserialize_with = "crate::required::option")]
180    pub max_video: Option<VideoLimits>,
181    #[serde(deserialize_with = "crate::required::option")]
182    pub max_audio_channels: Option<u32>,
183    /// Bits per second, from the client's settings. `None`: no limit.
184    #[serde(deserialize_with = "crate::required::option")]
185    pub max_bitrate: Option<u64>,
186    /// The video codecs of [`ClientCapabilities::video`] it decodes in
187    /// hardware (PGPU-06): a conversion goes to a codec the GPU encodes
188    /// only if the device decodes it in hardware, so AV1 is not sent to a
189    /// device that would decode it in software, draining its battery.
190    /// `None`: it does not say, and every codec it plays counts. Unlike
191    /// the fields above it may be left out, and is `None` then.
192    #[serde(default)]
193    pub hardware_video: Option<BTreeSet<VideoCodec>>,
194    /// The RFC 6381 codec strings it plays (`hvc1.2.4.L153.B0`,
195    /// `dvh1.08.06`; [`CodecString`]), as its player answers for each:
196    /// a video is copied only where one of them covers the source's own
197    /// string (its profile, tier and level, its Dolby Vision profile).
198    /// One the server does not read is passed over. `None`: it does not
199    /// say, and [`ClientCapabilities::video`] and `max_video` alone
200    /// decide. It may be left out, and is `None` then.
201    #[serde(default)]
202    pub video_codecs: Option<BTreeSet<String>>,
203}
204
205/// What the screen shows now, as a playback starts: [`VideoLimits::hdr`]
206/// and [`VideoLimits::bit_depth`] for that playback only, over what the
207/// client said at Hello. A TV's display mode changes while the app runs
208/// (Match Dynamic Range, another TV or receiver, HDR turned off), and
209/// capabilities from Hello would send HDR to an SDR mode or tone map for
210/// an HDR one.
211///
212/// Both fields are required, as in [`VideoLimits`]: `None` is no limit.
213#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
214pub struct DisplayCapabilities {
215    /// As [`VideoLimits::bit_depth`].
216    #[serde(deserialize_with = "crate::required::option")]
217    pub bit_depth: Option<u32>,
218    /// As [`VideoLimits::hdr`].
219    #[serde(deserialize_with = "crate::required::option")]
220    pub hdr: Option<BTreeSet<HdrFormat>>,
221    /// As [`ClientCapabilities::video_codecs`], asked again for this
222    /// display: a Dolby Vision string may be played on one mode and not
223    /// on another. `None` keeps Hello's. It may be left out, and is
224    /// `None` then.
225    #[serde(default)]
226    pub video_codecs: Option<BTreeSet<String>>,
227    /// As [`VideoLimits::height`], the screen's mode now: a TV set to
228    /// 1080p is not sent 4K. It lowers Hello's (the decoders') limit,
229    /// never raises it; `None` keeps Hello's. It may be left out.
230    #[serde(default)]
231    pub height: Option<u32>,
232    /// As [`VideoLimits::frame_rate`], the mode's refresh rate. `None`
233    /// keeps Hello's. It may be left out.
234    #[serde(default)]
235    pub frame_rate: Option<u32>,
236}
237
238/// A height or frame rate as a limit: 0 lines or 0 frames a second is a
239/// value not said, not a cap, which would convert everything to nothing.
240fn said(limit: Option<u32>) -> Option<u32> {
241    limit.filter(|v| *v > 0)
242}
243
244/// The lower of two limits, `None` being none: either one where only one
245/// is set.
246fn lower(a: Option<u32>, b: Option<u32>) -> Option<u32> {
247    match (said(a), said(b)) {
248        (Some(a), Some(b)) => Some(a.min(b)),
249        (a, b) => a.or(b),
250    }
251}
252
253impl ClientCapabilities {
254    /// The capabilities a plan reads: these, with `display`'s HDR formats
255    /// and bit depth in place of [`ClientCapabilities::max_video`]'s, and
256    /// its height and frame rate as limits where it says them, never above
257    /// Hello's. With or without a `display`, a height or frame rate of 0
258    /// is read as not said: the limits it gives never hold a 0.
259    pub fn with_display(&self, display: Option<&DisplayCapabilities>) -> ClientCapabilities {
260        let mut caps = self.clone();
261        if let Some(display) = display {
262            let limits = caps.max_video.get_or_insert_with(VideoLimits::default);
263            limits.hdr = display.hdr.clone();
264            limits.bit_depth = display.bit_depth;
265            // The screen's mode lowers Hello's limits, never raises them:
266            // a 4K TV does not lift a 1080p decoder's cap.
267            limits.height = lower(limits.height, display.height);
268            limits.frame_rate = lower(limits.frame_rate, display.frame_rate);
269            if display.video_codecs.is_some() {
270                caps.video_codecs = display.video_codecs.clone();
271            }
272        }
273        if let Some(limits) = caps.max_video.as_mut() {
274            limits.height = said(limits.height);
275            limits.frame_rate = said(limits.frame_rate);
276        }
277        caps
278    }
279
280    /// Whether it plays a video whose own codec string is `source`, by
281    /// [`ClientCapabilities::video_codecs`]: some string listed there
282    /// [covers](CodecString::covers) it. `None` when it lists none (it
283    /// does not say), and nothing is known of it here.
284    pub fn plays_codec_string(&self, source: &CodecString) -> Option<bool> {
285        let listed = self.video_codecs.as_ref()?;
286        Some(
287            listed
288                .iter()
289                .filter_map(|s| s.parse::<CodecString>().ok())
290                .any(|listed| listed.covers(source)),
291        )
292    }
293
294    /// Whether it decodes `codec` in hardware, as it says; every codec it
295    /// plays when it does not say (PGPU-06).
296    pub fn decodes_in_hardware(&self, codec: VideoCodec) -> bool {
297        self.video.contains(&codec)
298            && self
299                .hardware_video
300                .as_ref()
301                .is_none_or(|hardware| hardware.contains(&codec))
302    }
303
304    /// [`ClientCapabilities::delivery`], with the default (range reads
305    /// only) filled in when it is empty.
306    pub fn deliveries(&self) -> Vec<Delivery> {
307        if self.delivery.is_empty() {
308            vec![Delivery::Range]
309        } else {
310            self.delivery.clone()
311        }
312    }
313}
314
315#[cfg(test)]
316mod tests {
317    use super::*;
318
319    /// A start's display replaces Hello's HDR formats and bit depth, and
320    /// nothing else (PGPU-06); none leaves them as they are.
321    #[test]
322    fn a_display_replaces_hdr_and_bit_depth_only() {
323        let hello = ClientCapabilities {
324            video: [VideoCodec::Hevc].into(),
325            max_video: Some(VideoLimits {
326                height: Some(1080),
327                frame_rate: Some(60),
328                bit_depth: Some(10),
329                hdr: Some([HdrFormat::Hdr10, HdrFormat::DolbyVision].into()),
330            }),
331            ..ClientCapabilities::default()
332        };
333        assert_eq!(hello.with_display(None), hello);
334        let sdr = DisplayCapabilities {
335            bit_depth: Some(8),
336            hdr: Some(BTreeSet::new()),
337            video_codecs: None,
338            height: None,
339            frame_rate: None,
340        };
341        let now = hello.with_display(Some(&sdr));
342        assert_eq!(
343            now.max_video,
344            Some(VideoLimits {
345                height: Some(1080),
346                frame_rate: Some(60),
347                bit_depth: Some(8),
348                hdr: Some(BTreeSet::new()),
349            })
350        );
351        assert_eq!(now.video, hello.video);
352        // A client with no limits at Hello gets the display's.
353        let unlimited = ClientCapabilities::default().with_display(Some(&sdr));
354        assert_eq!(unlimited.max_video.unwrap().hdr, Some(BTreeSet::new()));
355    }
356
357    /// Hello's height or frame rate of 0, with no display, is not said
358    /// either: the limits a plan reads never hold a 0.
359    #[test]
360    fn hello_at_zero_with_no_display_is_no_limit() {
361        let hello = ClientCapabilities {
362            max_video: Some(VideoLimits {
363                height: Some(0),
364                frame_rate: Some(0),
365                bit_depth: Some(10),
366                hdr: None,
367            }),
368            ..ClientCapabilities::default()
369        };
370        assert_eq!(
371            hello.with_display(None).max_video,
372            Some(VideoLimits {
373                height: None,
374                frame_rate: None,
375                bit_depth: Some(10),
376                hdr: None,
377            })
378        );
379    }
380
381    /// A height or frame rate of 0 is a screen that did not say, on
382    /// either side: it caps nothing, rather than every plan at 0 lines.
383    #[test]
384    fn a_display_at_zero_changes_no_limit() {
385        let limits = |height, frame_rate| ClientCapabilities {
386            max_video: Some(VideoLimits {
387                height,
388                frame_rate,
389                ..VideoLimits::default()
390            }),
391            ..ClientCapabilities::default()
392        };
393        let mode = |height, frame_rate| DisplayCapabilities {
394            height,
395            frame_rate,
396            ..DisplayCapabilities::default()
397        };
398        let limited = |caps: ClientCapabilities, display| {
399            let video = caps.with_display(Some(&display)).max_video.unwrap();
400            (video.height, video.frame_rate)
401        };
402        assert_eq!(
403            [
404                limited(limits(Some(2160), Some(60)), mode(Some(0), Some(0))),
405                limited(limits(None, None), mode(Some(0), Some(0))),
406                limited(limits(Some(0), Some(0)), mode(Some(1080), Some(30))),
407            ],
408            [(Some(2160), Some(60)), (None, None), (Some(1080), Some(30))]
409        );
410    }
411
412    #[test]
413    fn codecs_are_snake_case_on_the_wire() {
414        assert_eq!(
415            serde_json::to_string(&AudioCodec::TrueHd).unwrap(),
416            r#""true_hd""#
417        );
418        assert_eq!(AudioCodec::TrueHd.as_str(), "true_hd");
419    }
420
421    #[test]
422    fn a_codec_from_a_newer_peer_is_unknown() {
423        assert_eq!(
424            serde_json::from_str::<VideoCodec>(r#""h266""#).unwrap(),
425            VideoCodec::Unknown
426        );
427    }
428
429    /// PGPU-06: a client that leaves `hardware_video` out, as every one
430    /// of revision 14 does, is read, every codec it plays counting as
431    /// hardware; one that says counts only those.
432    #[test]
433    fn hardware_decoders_may_be_left_out() {
434        let old = r#"{"video":["hevc","av1"],"audio":[],"containers":[],"subtitles":[],
435            "delivery":[],"max_video":null,"max_audio_channels":null,"max_bitrate":null}"#;
436        let caps: ClientCapabilities = serde_json::from_str(old).unwrap();
437        assert_eq!(caps.hardware_video, None);
438        assert!(caps.decodes_in_hardware(VideoCodec::Av1));
439        assert!(
440            !caps.decodes_in_hardware(VideoCodec::H264),
441            "not played at all"
442        );
443        let said = ClientCapabilities {
444            hardware_video: Some([VideoCodec::Hevc].into()),
445            ..caps
446        };
447        assert!(said.decodes_in_hardware(VideoCodec::Hevc));
448        assert!(!said.decodes_in_hardware(VideoCodec::Av1));
449        let wire = serde_json::to_value(&said).unwrap();
450        assert_eq!(wire["hardware_video"], serde_json::json!(["hevc"]));
451    }
452
453    /// The Apple TV of the ticket (plex:movie:1936): its list read as
454    /// `video_codecs`, a string it does not list refused, one the server
455    /// cannot read passed over; a client that left the field out says
456    /// nothing.
457    #[test]
458    fn a_client_lists_the_codec_strings_it_plays() {
459        let hello = r#"{"video":["hevc"],"audio":[],"containers":[],"subtitles":[],
460            "delivery":[],"max_video":null,"max_audio_channels":null,"max_bitrate":null,
461            "hardware_video":["hevc"],
462            "video_codecs":["hvc1.2.4.L153.B0","dvh1.08.06","vp09.00.10.08","nonsense"]}"#;
463        let caps: ClientCapabilities = serde_json::from_str(hello).unwrap();
464        let judge = |s: &str| caps.plays_codec_string(&s.parse().unwrap());
465        assert_eq!(judge("hvc1.2.4.L150.B0"), Some(true));
466        assert_eq!(judge("hvc1.2.4.L186.B0"), Some(false));
467        assert_eq!(judge("dvh1.08.06"), Some(true));
468        assert_eq!(judge("dvh1.07.06"), Some(false));
469        let wire = serde_json::to_value(&caps).unwrap();
470        assert_eq!(wire["video_codecs"][0], "dvh1.08.06", "a sorted set");
471        let unsaid = ClientCapabilities {
472            video_codecs: None,
473            ..caps.clone()
474        };
475        assert_eq!(
476            unsaid.plays_codec_string(&"hvc1.2.4.L186.B0".parse().unwrap()),
477            None
478        );
479        let old = r#"{"video":["hevc"],"audio":[],"containers":[],"subtitles":[],
480            "delivery":[],"max_video":null,"max_audio_channels":null,"max_bitrate":null}"#;
481        let old: ClientCapabilities = serde_json::from_str(old).unwrap();
482        assert_eq!(old.video_codecs, None);
483    }
484
485    /// A start's display may list the strings again (its Dolby Vision
486    /// answer is that mode's); one that does not keeps Hello's.
487    #[test]
488    fn a_display_s_codec_strings_replace_hello_s() {
489        let hello = ClientCapabilities {
490            video: [VideoCodec::Hevc].into(),
491            video_codecs: Some(["dvh1.08.06".to_owned(), "hvc1.2.4.L153.B0".to_owned()].into()),
492            ..ClientCapabilities::default()
493        };
494        let sdr = DisplayCapabilities {
495            bit_depth: Some(8),
496            hdr: Some(BTreeSet::new()),
497            video_codecs: None,
498            height: None,
499            frame_rate: None,
500        };
501        assert_eq!(
502            hello.with_display(Some(&sdr)).video_codecs,
503            hello.video_codecs
504        );
505        let hdr10 = DisplayCapabilities {
506            video_codecs: Some(["hvc1.2.4.L153.B0".to_owned()].into()),
507            ..sdr
508        };
509        assert_eq!(
510            hello.with_display(Some(&hdr10)).video_codecs,
511            hdr10.video_codecs
512        );
513        let json = r#"{"bit_depth":10,"hdr":null}"#;
514        let display: DisplayCapabilities = serde_json::from_str(json).unwrap();
515        assert_eq!(display.video_codecs, None);
516    }
517
518    #[test]
519    fn a_client_without_deliveries_takes_range_reads() {
520        let caps = ClientCapabilities {
521            video: [VideoCodec::H264].into(),
522            ..ClientCapabilities::default()
523        };
524        assert_eq!(caps.deliveries(), [Delivery::Range]);
525    }
526
527    /// Capabilities were optional field by field, so a client that left
528    /// one out was planned for as if it had none (PX-15).
529    #[test]
530    fn capabilities_missing_a_field_are_refused() {
531        let caps = ClientCapabilities {
532            max_video: Some(VideoLimits::default()),
533            ..ClientCapabilities::default()
534        };
535        crate::test_support::assert_each_required(
536            &caps,
537            &[
538                "video",
539                "audio",
540                "containers",
541                "subtitles",
542                "delivery",
543                "max_video",
544                "max_audio_channels",
545                "max_bitrate",
546            ],
547        );
548        crate::test_support::assert_each_required(
549            &VideoLimits::default(),
550            &["height", "frame_rate", "bit_depth", "hdr"],
551        );
552    }
553
554    #[test]
555    fn a_delivery_from_a_newer_peer_is_unknown() {
556        assert_eq!(
557            serde_json::from_str::<Delivery>(r#""dash""#).unwrap(),
558            Delivery::Unknown
559        );
560    }
561
562    #[test]
563    fn capabilities_round_trip() {
564        let caps = ClientCapabilities {
565            video: [VideoCodec::H264, VideoCodec::Hevc].into(),
566            audio: [AudioCodec::Aac].into(),
567            containers: [Container::Matroska].into(),
568            subtitles: [SubtitleFormat::Srt].into(),
569            ..ClientCapabilities::default()
570        };
571        let json = serde_json::to_string(&caps).unwrap();
572        assert_eq!(
573            serde_json::from_str::<ClientCapabilities>(&json).unwrap(),
574            caps
575        );
576    }
577}