Skip to main content

spoolframe_types/
media.rs

1//! What a client learns about a media file before it plays it: its length,
2//! what it is (container and picture, to show), and the tracks it can
3//! choose between.
4//!
5//! Audio and subtitle codecs stay on the server, where the playback
6//! planner uses them; a client chooses an audio language, not a codec.
7
8use std::time::Duration;
9
10use serde::{Deserialize, Serialize};
11
12use crate::browse::{DynamicRange, Resolution};
13use crate::codec::{Container, HdrFormat, VideoCodec};
14use crate::duration_ms;
15
16/// The tracks of one media file. A track is identified by its position in
17/// its list, which is stable for as long as the file does not change.
18#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
19#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
20pub struct MediaTracks {
21    #[serde(with = "duration_ms::option")]
22    pub duration: Option<Duration>,
23    /// The file's container, from the server's own probe of it. `None`
24    /// only where nothing was probed.
25    pub container: Option<Container>,
26    /// The file's average bits per second, every stream counted, for
27    /// "42 Mbit/s": what the container says, else its size over its
28    /// length. `None` where the server knows neither.
29    ///
30    /// This and `VideoTrack::bit_rate` are not `required::option`, though
31    /// every server sends them: the SDK keeps an item's file and tracks
32    /// with a download, and a download kept by an older SDK lacks the
33    /// keys, which read as `None`.
34    pub bit_rate: Option<u64>,
35    /// The main picture; `None` for audio only (music).
36    pub video: Option<VideoTrack>,
37    pub audio: Vec<AudioTrack>,
38    pub subtitles: Vec<SubtitleTrack>,
39}
40
41/// A file's picture as it is stored, for "4K · HEVC · Dolby Vision ·
42/// 10-bit": what the file is, not how it will play.
43#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
44#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
45pub struct VideoTrack {
46    pub codec: VideoCodec,
47    /// Pixels. A 2.40:1 4K film is 3840 by 1600: go by the width for
48    /// its class.
49    pub width: u32,
50    pub height: u32,
51    /// Bits per sample: 8, 10 or 12.
52    pub bit_depth: u32,
53    /// The HDR format; `None` is SDR. Dolby Vision over an HDR10 base is
54    /// Dolby Vision. HDR10+ is HDR10 here: its metadata is in the frames,
55    /// which the probe does not read.
56    pub hdr: Option<HdrFormat>,
57    /// The picture's own average bits per second, where the file says:
58    /// MP4 does for each stream, Matroska where its muxer wrote
59    /// statistics tags (mkvmerge does). As [`MediaTracks::bit_rate`].
60    pub bit_rate: Option<u64>,
61}
62
63impl VideoTrack {
64    /// Its picture size class, by height and width both, as the server
65    /// classes an item for a filter ([`Resolution::of`]): a 1920×800
66    /// scope film is 1080p. `None` for a track that gives no size.
67    pub fn resolution(&self) -> Option<Resolution> {
68        let size = |n: u32| (n > 0).then_some(n);
69        Resolution::of(size(self.width), size(self.height))
70    }
71
72    /// Its range in a filter's words: Dolby Vision, HDR for HDR10 and
73    /// HLG, else SDR.
74    pub fn dynamic_range(&self) -> DynamicRange {
75        match self.hdr {
76            None => DynamicRange::Sdr,
77            Some(HdrFormat::DolbyVision) => DynamicRange::DolbyVision,
78            Some(HdrFormat::Hdr10 | HdrFormat::Hlg) => DynamicRange::Hdr,
79            Some(HdrFormat::Unknown) => DynamicRange::Unknown,
80        }
81    }
82}
83
84#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
85#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
86pub struct AudioTrack {
87    /// An ISO 639-2 code such as `eng`, when the file says.
88    pub language: Option<String>,
89    pub title: Option<String>,
90    pub channels: Option<u32>,
91    /// The file marks it as the one to play by default.
92    pub default: bool,
93    /// What the track is for, whatever its title says.
94    pub role: AudioRole,
95}
96
97/// What an audio track is for.
98#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
99#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
100#[serde(rename_all = "snake_case")]
101pub enum AudioRole {
102    /// The programme's own sound.
103    #[default]
104    Main,
105    /// Narration of what is on screen, for blind and partially sighted
106    /// viewers.
107    AudioDescription,
108    Commentary,
109    /// Anything else (karaoke, music and effects only), and any role this
110    /// build does not know.
111    #[serde(other)]
112    Other,
113}
114
115#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
116#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
117pub struct SubtitleTrack {
118    /// An ISO 639-2 code such as `eng`, when the file says.
119    pub language: Option<String>,
120    pub title: Option<String>,
121    /// Only for foreign-language parts of the dialogue; shown even when
122    /// subtitles are off. The same as `role == Forced`.
123    pub forced: bool,
124    pub default: bool,
125    /// From a separate file next to the media, not inside it.
126    pub external: bool,
127    /// What the track is for, whatever its title says.
128    pub role: SubtitleRole,
129    /// How the track is timed: an external text track's sync and
130    /// offset, the same for every user. Only for an external text track
131    /// (SRT, WebVTT, ASS), in an item's tracks; `None` for every other
132    /// track, whose timing is the file's. Read as `None` when left out,
133    /// as a download's tracks kept by an older SDK lack it.
134    #[serde(default)]
135    pub timing: Option<SubtitleTiming>,
136    /// Where a track someone downloaded came from: its source,
137    /// who downloaded it and when, in an item's tracks; `None` for every
138    /// track that was not downloaded. Read as `None` when left out, as
139    /// `timing` is.
140    #[serde(default)]
141    pub download: Option<SubtitleDownload>,
142}
143
144/// A subtitle site the server searches and downloads from. On the wire
145/// it is its [`id`](SubtitleSource::id), a string: a client shows a site
146/// this build does not know as that id.
147#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
148pub enum SubtitleSource {
149    OpenSubtitles,
150    SubDl,
151}
152
153impl SubtitleSource {
154    /// Every site, in the order the server asks them unless the admin
155    /// set another.
156    pub const ALL: [SubtitleSource; 2] = [SubtitleSource::OpenSubtitles, SubtitleSource::SubDl];
157
158    /// Its id: `opensubtitles`, `subdl`.
159    pub fn id(self) -> &'static str {
160        match self {
161            SubtitleSource::OpenSubtitles => "opensubtitles",
162            SubtitleSource::SubDl => "subdl",
163        }
164    }
165
166    /// Its name, to show.
167    pub fn name(self) -> &'static str {
168        match self {
169            SubtitleSource::OpenSubtitles => "OpenSubtitles",
170            SubtitleSource::SubDl => "SubDL",
171        }
172    }
173
174    /// The site `id` names, if one.
175    pub fn of(id: &str) -> Option<SubtitleSource> {
176        SubtitleSource::ALL.into_iter().find(|s| s.id() == id)
177    }
178
179    /// The name of the site `id` names; the id itself for one this build
180    /// does not know.
181    pub fn name_of(id: &str) -> &str {
182        SubtitleSource::of(id).map_or(id, |s| s.name())
183    }
184}
185
186impl std::fmt::Display for SubtitleSource {
187    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
188        f.write_str(self.name())
189    }
190}
191
192/// A subtitle track downloaded from a subtitle site, for everyone
193/// on the server.
194#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
195#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
196pub struct SubtitleDownload {
197    /// The download's own id: what `RemoveSubtitleDownload` names.
198    pub id: String,
199    /// The site it came from, by id: `opensubtitles` (OpenSubtitles) or
200    /// `subdl` (SubDL), as [`SubtitleResult::source`].
201    pub source: String,
202    /// The release it was made for, as the site names it.
203    pub release: String,
204    /// Who downloaded it, by display name.
205    pub by: String,
206    /// When, Unix seconds.
207    pub at: i64,
208    /// It was found by the file's hash: made for this very release, so
209    /// it was not synced.
210    pub hash_match: bool,
211    pub origin: SubtitleOrigin,
212    /// Whether the session's user may remove it: the one who downloaded
213    /// it, or an admin.
214    pub can_remove: bool,
215}
216
217/// Who made a subtitle.
218#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
219#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
220#[serde(rename_all = "snake_case")]
221pub enum SubtitleOrigin {
222    /// Machine-translated from another language's subtitle.
223    MachineTranslated,
224    /// Made by an AI, from the speech.
225    Ai,
226    /// A person. Also any origin this build does not know. (Last, as
227    /// serde wants of `other`.)
228    #[default]
229    #[serde(other)]
230    Human,
231}
232
233/// One subtitle a search found, to download by its `id`.
234#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
235#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
236pub struct SubtitleResult {
237    /// What `DownloadSubtitle` names: the site's id and its file's,
238    /// `opensubtitles:5338574`, `subdl:3172974-3188291`. Opaque to a
239    /// client.
240    pub id: String,
241    /// The site it was found on: `opensubtitles` (OpenSubtitles) or
242    /// `subdl` (SubDL); a client shows another as it is.
243    pub source: String,
244    /// The release it was made for, as its uploader named it.
245    pub release: String,
246    /// Its language, as the site says it: `en`, `pt-BR`.
247    pub language: String,
248    /// `srt`, `ass`, `vtt`, or what the site says.
249    pub format: Option<String>,
250    /// The frame rate it was made for, in thousandths: 23 976.
251    pub fps_milli: Option<u32>,
252    /// How many times it was downloaded on the site; 0 where the site
253    /// does not say (SubDL).
254    pub downloads: u64,
255    /// Its rating on the site, 0 to 100 (tenths of its 0 to 10); `None`
256    /// while unrated.
257    pub rating: Option<u8>,
258    pub hearing_impaired: bool,
259    /// Only the parts in another language than the rest (signs, a
260    /// foreign line): a forced subtitle, not the whole dialogue. False
261    /// where the site does not say (SubDL).
262    pub forced: bool,
263    pub origin: SubtitleOrigin,
264    /// Found by the file's hash: made for this very release, and played
265    /// as it is, not synced.
266    pub hash_match: bool,
267    /// Downloaded before and removed as bad: listed last.
268    pub rejected: bool,
269    /// Downloaded already: a download gives the same track.
270    pub downloaded: bool,
271}
272
273/// What a subtitle search found for an item, best first: hash
274/// matches, then the rest by rating and downloads; machine-translated and
275/// AI-made after people's; rejected ones last. Every site the server
276/// searches is asked at once, and their results are one list.
277#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
278#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
279pub struct SubtitleSearch {
280    /// The languages searched.
281    pub languages: Vec<String>,
282    pub results: Vec<SubtitleResult>,
283    /// How each site's search went, in the order the server asks them:
284    /// one that failed or is out of quota leaves the others' results.
285    pub sources: Vec<SubtitleSourceStatus>,
286}
287
288/// How one site's part of a search went.
289#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
290#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
291pub struct SubtitleSourceStatus {
292    /// `opensubtitles` or `subdl`, as [`SubtitleResult::source`].
293    pub source: String,
294    /// Flattened: `{"source": "subdl", "state": "found", "found": 12}`.
295    #[serde(flatten)]
296    pub state: SubtitleSourceState,
297}
298
299/// Whether a site answered a search.
300#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
301#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
302#[serde(tag = "state", rename_all = "snake_case")]
303pub enum SubtitleSourceState {
304    /// It answered, with `found` of the results.
305    Found { found: u32 },
306    /// Its quota is used up until `resets_at` (Unix seconds), when it
307    /// says.
308    QuotaExhausted { resets_at: Option<i64> },
309    /// It asked to wait this long before the next request.
310    RateLimited { retry_after_ms: u64 },
311    /// It could not be reached or refused the request: `message` says
312    /// why, to show.
313    Failed { message: String },
314    /// One this build does not know.
315    #[serde(other)]
316    Unknown,
317}
318
319/// A subtitle downloaded: the item's new track, at once, and the
320/// downloads left today.
321#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
322#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
323pub struct SubtitleDownloaded {
324    /// Its place in the item's `Tracks`' `subtitles`.
325    pub track: u32,
326    pub subtitle: SubtitleTrack,
327    /// The server's account's downloads left today, when the site says.
328    #[serde(deserialize_with = "crate::required::option")]
329    pub account_remaining: Option<u32>,
330    /// The user's own, when the admin set a limit per user.
331    #[serde(deserialize_with = "crate::required::option")]
332    pub user_remaining: Option<u32>,
333}
334
335/// Whose downloads ran out.
336#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
337#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
338#[serde(rename_all = "snake_case")]
339pub enum QuotaOf {
340    /// The server's account at the site: no one can download until it
341    /// resets.
342    Account,
343    /// The user's own daily limit on this server.
344    User,
345    /// One this build does not know.
346    #[serde(other)]
347    Unknown,
348}
349
350/// How an external text subtitle is timed: synced to the file or
351/// as it came, and moved by a manual offset on top. Set for everyone who
352/// plays the item.
353#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
354#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
355pub struct SubtitleTiming {
356    pub sync: SubtitleSync,
357    /// Added to every cue, ms, on top of the synced or original timing:
358    /// positive shows the text later. What the track is served with
359    /// already has it: a client does not add it again.
360    pub offset_ms: i64,
361    /// Who set the offset last, by display name; `None` while no one has.
362    #[serde(deserialize_with = "crate::required::option")]
363    pub offset_by: Option<String>,
364    /// When, Unix seconds.
365    #[serde(deserialize_with = "crate::required::option")]
366    pub offset_at: Option<i64>,
367}
368
369impl SubtitleTiming {
370    /// The most an offset moves a track, ms, either way: ten minutes.
371    pub const MAX_OFFSET_MS: i64 = 10 * 60 * 1000;
372    /// One press of a player's ± control, ms.
373    pub const OFFSET_STEP_MS: i64 = 100;
374
375    /// The offset `steps` presses of the ± control from this one
376    /// (negative: earlier), held within [`SubtitleTiming::MAX_OFFSET_MS`].
377    pub fn offset_stepped(&self, steps: i64) -> i64 {
378        steps
379            .saturating_mul(Self::OFFSET_STEP_MS)
380            .saturating_add(self.offset_ms)
381            .clamp(-Self::MAX_OFFSET_MS, Self::MAX_OFFSET_MS)
382    }
383}
384
385/// Where a subtitle's sync is.
386#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
387#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
388#[serde(tag = "state", rename_all = "snake_case")]
389pub enum SubtitleSync {
390    /// Its own timing, as the file has it: never synced, or put back
391    /// with "Use original timing".
392    Original,
393    /// Being synced, or waiting its turn; it is served as it was until
394    /// the sync is done.
395    Syncing,
396    /// Synced, and served synced.
397    Synced {
398        /// The shift of most of its cues, ms.
399        offset_ms: i64,
400        /// The frame-rate ratio its times were multiplied by, in
401        /// millionths: 1 000 000 for none, 1 042 709 for 23.976 to 25.
402        factor_ppm: u32,
403        /// Where scenes were cut or added: the places its shift changes.
404        splits: u32,
405        /// How well it fell on the file, 0 to 100.
406        score: u8,
407    },
408    /// A sync scored too low to trust: it may be another film's subtitle.
409    /// Served with its original timing.
410    Uncertain { score: u8 },
411    /// The sync could not be made; served as it was.
412    Failed { reason: String },
413    /// A state this build does not know: show the track as it is.
414    #[serde(other)]
415    Unknown,
416}
417
418/// What a subtitle track is for.
419#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
420#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
421#[serde(rename_all = "snake_case")]
422pub enum SubtitleRole {
423    /// For deaf and hard-of-hearing viewers: dialogue plus sounds and
424    /// speakers.
425    Sdh,
426    /// Only foreign-language parts and signs.
427    Forced,
428    Commentary,
429    /// All the dialogue. Also any role this build does not know: showing
430    /// it is the safe guess. (Last, as serde wants of `other`.)
431    #[default]
432    #[serde(other)]
433    Full,
434}
435
436#[cfg(test)]
437mod tests {
438    use super::*;
439
440    fn video(width: u32, height: u32, hdr: Option<HdrFormat>) -> VideoTrack {
441        VideoTrack {
442            codec: VideoCodec::Hevc,
443            width,
444            height,
445            bit_depth: 10,
446            hdr,
447            bit_rate: None,
448        }
449    }
450
451    #[test]
452    fn a_scope_film_is_classed_by_its_width_too() {
453        assert_eq!(video(3840, 1600, None).resolution(), Some(Resolution::Uhd));
454        assert_eq!(
455            video(1920, 800, None).resolution(),
456            Some(Resolution::FullHd)
457        );
458        assert_eq!(video(720, 480, None).resolution(), Some(Resolution::Sd));
459        assert_eq!(video(0, 0, None).resolution(), None);
460    }
461
462    #[test]
463    fn hdr_formats_read_as_a_filters_ranges() {
464        let range = |hdr| video(3840, 2160, hdr).dynamic_range();
465        assert_eq!(range(None), DynamicRange::Sdr);
466        assert_eq!(range(Some(HdrFormat::Hlg)), DynamicRange::Hdr);
467        assert_eq!(
468            range(Some(HdrFormat::DolbyVision)),
469            DynamicRange::DolbyVision
470        );
471    }
472
473    #[test]
474    fn a_track_s_role_left_out_is_refused() {
475        let audio = AudioTrack {
476            language: None,
477            title: None,
478            channels: None,
479            default: false,
480            role: AudioRole::Commentary,
481        };
482        crate::test_support::assert_each_required(&audio, &["role"]);
483        let subtitle = SubtitleTrack {
484            language: None,
485            title: None,
486            forced: false,
487            default: false,
488            external: false,
489            role: SubtitleRole::Sdh,
490            timing: None,
491            download: None,
492        };
493        crate::test_support::assert_each_required(&subtitle, &["role"]);
494    }
495
496    fn sidecar(timing: Option<SubtitleTiming>) -> SubtitleTrack {
497        SubtitleTrack {
498            language: Some("eng".into()),
499            title: None,
500            forced: false,
501            default: false,
502            external: true,
503            role: SubtitleRole::Full,
504            timing,
505            download: None,
506        }
507    }
508
509    /// PX-02: a downloaded track says so, and where from; any other track
510    /// says `null`, and one kept without the key reads as none.
511    #[test]
512    fn a_track_s_download_is_null_for_one_not_downloaded() {
513        let mut json = serde_json::to_value(sidecar(None)).unwrap();
514        assert!(json["download"].is_null(), "{json}");
515        json.as_object_mut().unwrap().remove("download");
516        assert_eq!(
517            serde_json::from_value::<SubtitleTrack>(json).unwrap(),
518            sidecar(None)
519        );
520        let mut track = sidecar(None);
521        track.download = Some(SubtitleDownload {
522            id: "d1".into(),
523            source: "opensubtitles".into(),
524            release: "Film.2019.1080p".into(),
525            by: "Alice".into(),
526            at: 1_760_000_000,
527            hash_match: false,
528            origin: SubtitleOrigin::MachineTranslated,
529            can_remove: true,
530        });
531        let json = serde_json::to_value(&track).unwrap();
532        assert_eq!(json["download"]["origin"], "machine_translated");
533        assert_eq!(
534            serde_json::from_value::<SubtitleTrack>(json).unwrap(),
535            track
536        );
537    }
538
539    #[test]
540    fn an_origin_or_quota_this_build_does_not_know_still_decodes() {
541        let origin: SubtitleOrigin = serde_json::from_value(serde_json::json!("dubbed")).unwrap();
542        assert_eq!(origin, SubtitleOrigin::Human);
543        let whose: QuotaOf = serde_json::from_value(serde_json::json!("household")).unwrap();
544        assert_eq!(whose, QuotaOf::Unknown);
545    }
546
547    #[test]
548    fn a_source_is_named_by_its_id() {
549        for source in SubtitleSource::ALL {
550            assert_eq!(SubtitleSource::of(source.id()), Some(source));
551        }
552        assert_eq!(SubtitleSource::of("SubDL"), None);
553        assert_eq!(SubtitleSource::name_of("subdl"), "SubDL");
554        assert_eq!(SubtitleSource::name_of("podnapisi"), "podnapisi");
555    }
556
557    /// A result as a server before SubDL sent one, named by
558    /// OpenSubtitles' `file_id` with no `id`, `source` or `forced`, is
559    /// refused, as is a search without `sources`: each is required.
560    #[test]
561    fn a_result_or_a_search_missing_a_field_is_refused() {
562        let result = serde_json::json!({
563            "id": "opensubtitles:7", "source": "opensubtitles", "release": "R",
564            "language": "en", "format": null, "fps_milli": null, "downloads": 1,
565            "rating": null, "hearing_impaired": false, "forced": false,
566            "origin": "human", "hash_match": false, "rejected": false,
567            "downloaded": false,
568        });
569        let read: SubtitleResult = serde_json::from_value(result.clone()).unwrap();
570        assert_eq!(read.id, "opensubtitles:7");
571        for field in ["id", "source", "forced"] {
572            let mut without = result.clone();
573            without.as_object_mut().unwrap().remove(field);
574            let error = serde_json::from_value::<SubtitleResult>(without).unwrap_err();
575            assert!(
576                error
577                    .to_string()
578                    .contains(&format!("missing field `{field}`")),
579                "{field}: {error}"
580            );
581        }
582        let mut before_subdl = result.clone();
583        let fields = before_subdl.as_object_mut().unwrap();
584        fields.remove("id");
585        fields.insert("file_id".into(), 7.into());
586        assert!(serde_json::from_value::<SubtitleResult>(before_subdl).is_err());
587        let search = serde_json::json!({"languages": ["en"], "results": [result]});
588        let error = serde_json::from_value::<SubtitleSearch>(search).unwrap_err();
589        assert!(
590            error.to_string().contains("missing field `sources`"),
591            "{error}"
592        );
593    }
594
595    #[test]
596    fn a_download_s_remaining_counts_left_out_are_refused() {
597        let downloaded = SubtitleDownloaded {
598            track: 3,
599            subtitle: sidecar(None),
600            account_remaining: None,
601            user_remaining: None,
602        };
603        crate::test_support::assert_each_required(
604            &downloaded,
605            &["account_remaining", "user_remaining"],
606        );
607    }
608
609    /// PX-03: a track's timing is `null` when there is none, and one kept
610    /// without the key reads as none; one sent reads back as it was, its
611    /// state by name.
612    #[test]
613    fn a_track_s_timing_is_null_when_there_is_none() {
614        let mut json = serde_json::to_value(sidecar(None)).unwrap();
615        assert!(json["timing"].is_null(), "{json}");
616        json.as_object_mut().unwrap().remove("timing");
617        assert_eq!(
618            serde_json::from_value::<SubtitleTrack>(json).unwrap(),
619            sidecar(None)
620        );
621        let timing = SubtitleTiming {
622            sync: SubtitleSync::Synced {
623                offset_ms: -3_200,
624                factor_ppm: 1_042_709,
625                splits: 1,
626                score: 87,
627            },
628            offset_ms: 1_500,
629            offset_by: Some("Alice".into()),
630            offset_at: Some(1_760_000_000),
631        };
632        let json = serde_json::to_value(sidecar(Some(timing.clone()))).unwrap();
633        assert_eq!(json["timing"]["sync"]["state"], "synced");
634        assert_eq!(
635            serde_json::from_value::<SubtitleTrack>(json).unwrap(),
636            sidecar(Some(timing))
637        );
638    }
639
640    #[test]
641    fn the_offset_moves_a_tenth_of_a_second_a_press_and_no_further_than_the_most() {
642        let timing = |offset_ms| SubtitleTiming {
643            sync: SubtitleSync::Original,
644            offset_ms,
645            offset_by: None,
646            offset_at: None,
647        };
648        assert_eq!(timing(1_500).offset_stepped(1), 1_600);
649        assert_eq!(timing(1_500).offset_stepped(-20), -500);
650        assert_eq!(timing(599_950).offset_stepped(1), 600_000);
651        assert_eq!(timing(-599_950).offset_stepped(-3), -600_000);
652        assert_eq!(timing(0).offset_stepped(i64::MAX), 600_000);
653    }
654
655    #[test]
656    fn a_sync_state_this_build_does_not_know_is_unknown() {
657        let sync: SubtitleSync =
658            serde_json::from_value(serde_json::json!({ "state": "transcribing" })).unwrap();
659        assert_eq!(sync, SubtitleSync::Unknown);
660    }
661
662    #[test]
663    fn a_timing_s_offset_author_left_out_is_refused() {
664        let timing = SubtitleTiming {
665            sync: SubtitleSync::Original,
666            offset_ms: 0,
667            offset_by: None,
668            offset_at: None,
669        };
670        crate::test_support::assert_each_required(&timing, &["offset_by", "offset_at"]);
671    }
672
673    #[test]
674    fn tracks_round_trip_with_the_duration_in_milliseconds() {
675        let tracks = MediaTracks {
676            duration: Some(Duration::from_millis(6_106_791)),
677            container: Some(Container::Matroska),
678            bit_rate: Some(42_000_000),
679            video: Some(VideoTrack {
680                codec: VideoCodec::Hevc,
681                width: 3840,
682                height: 1600,
683                bit_depth: 10,
684                hdr: Some(HdrFormat::DolbyVision),
685                bit_rate: Some(38_500_000),
686            }),
687            audio: vec![AudioTrack {
688                language: Some("eng".into()),
689                title: None,
690                channels: Some(6),
691                default: true,
692                role: AudioRole::Main,
693            }],
694            subtitles: vec![SubtitleTrack {
695                language: Some("eng".into()),
696                title: Some("Forced".into()),
697                forced: true,
698                default: false,
699                external: true,
700                role: SubtitleRole::Forced,
701                timing: None,
702                download: None,
703            }],
704        };
705        let json = serde_json::to_value(&tracks).unwrap();
706        assert_eq!(json["duration"], 6_106_791);
707        assert_eq!(serde_json::from_value::<MediaTracks>(json).unwrap(), tracks);
708    }
709
710    #[test]
711    fn tracks_from_a_server_without_bit_rates_still_decode() {
712        let tracks = MediaTracks {
713            bit_rate: Some(42_000_000),
714            video: Some(VideoTrack {
715                codec: VideoCodec::Hevc,
716                width: 3840,
717                height: 2160,
718                bit_depth: 10,
719                hdr: None,
720                bit_rate: Some(38_500_000),
721            }),
722            ..MediaTracks::default()
723        };
724        let mut json = serde_json::to_value(&tracks).unwrap();
725        assert_eq!(json["bit_rate"], 42_000_000);
726        json.as_object_mut().unwrap().remove("bit_rate");
727        json["video"].as_object_mut().unwrap().remove("bit_rate");
728        let older: MediaTracks = serde_json::from_value(json).unwrap();
729        assert_eq!(older.bit_rate, None);
730        assert_eq!(older.video.unwrap().bit_rate, None);
731    }
732
733    #[test]
734    fn a_role_from_a_newer_peer_still_decodes() {
735        // A role this build does not know. (A track with no role at all is
736        // refused: `a_track_s_role_left_out_is_refused`.)
737        let audio: AudioRole = serde_json::from_value(serde_json::json!("karaoke")).unwrap();
738        assert_eq!(audio, AudioRole::Other);
739        let subtitle: SubtitleRole = serde_json::from_value(serde_json::json!("lyrics")).unwrap();
740        assert_eq!(subtitle, SubtitleRole::Full);
741    }
742}