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