Skip to main content

spoolframe_types/
preferences.rs

1//! How a viewer wants tracks chosen (P1-20). Kept per user on the server,
2//! so a TV and a laptop choose the same.
3
4use serde::{Deserialize, Serialize};
5
6use crate::media::AudioRole;
7
8/// A language code that stands for the item's original language: the
9/// language of the file's default audio track.
10pub const ORIGINAL_LANGUAGE: &str = "original";
11
12/// Every field is required on the wire (PX-15): a peer that leaves one out
13/// is refused, not filled in. The server keeps these as JSON and reads its
14/// older rows with the defaults filled in itself (`store::tracks`).
15#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
16pub struct TrackPreferences {
17    pub audio: AudioPreferences,
18    pub subtitles: SubtitlePreferences,
19}
20
21#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
22pub struct AudioPreferences {
23    /// ISO 639 codes in order of preference, or [`ORIGINAL_LANGUAGE`].
24    /// Empty: the file's default track.
25    pub languages: Vec<String>,
26    /// Roles never chosen while another track is left.
27    pub avoid: Vec<AudioRole>,
28}
29
30impl Default for AudioPreferences {
31    fn default() -> Self {
32        Self {
33            languages: Vec::new(),
34            avoid: vec![AudioRole::AudioDescription, AudioRole::Commentary],
35        }
36    }
37}
38
39#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
40pub struct SubtitlePreferences {
41    pub mode: SubtitleMode,
42    /// ISO 639 codes in order of preference. Empty: the audio's language.
43    pub languages: Vec<String>,
44    pub sdh: SdhPreference,
45    /// How picture subtitles (PGS, VobSub, DVB) are shown when the app
46    /// leaves it to the server. It has no effect on a server that does not
47    /// read them as text.
48    pub bitmap: BitmapPreference,
49    /// Forced subtitles (only the parts in another language) among a
50    /// subtitle search's results (PX-02). Playback follows `mode`.
51    pub forced: ForcedPreference,
52}
53
54/// When subtitles are shown.
55#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
56#[serde(rename_all = "snake_case")]
57pub enum SubtitleMode {
58    /// Always, in a preferred language.
59    Always,
60    /// Only when the audio is not in a preferred subtitle language.
61    ForeignOnly,
62    Off,
63    /// Only forced subtitles (foreign parts, signs) in the audio's
64    /// language. Also any mode this build does not know. (Last, as serde
65    /// wants of `other`.)
66    #[default]
67    #[serde(other)]
68    ForcedOnly,
69}
70
71/// What to do with subtitles for the deaf and hard of hearing: in
72/// playback, which track is chosen; in a subtitle search (PX-02), the
73/// results' order, or which are listed at all.
74#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
75#[serde(rename_all = "snake_case")]
76pub enum SdhPreference {
77    /// SDH before plain subtitles.
78    Prefer,
79    /// Never SDH: a search lists none.
80    Avoid,
81    /// Only SDH: no subtitles where there is none, and a search lists no
82    /// plain ones. A build before it reads it as `Accept`.
83    Only,
84    /// Plain subtitles first, SDH when there are none. Also any value this
85    /// build does not know. (Last, as serde wants of `other`.)
86    #[default]
87    #[serde(other)]
88    Accept,
89}
90
91/// What to do with forced subtitles (only the parts in another language:
92/// signs, a foreign line) in a subtitle search's results (PX-02): the
93/// same four ways as [`SdhPreference`].
94#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
95#[serde(rename_all = "snake_case")]
96pub enum ForcedPreference {
97    /// Forced ones before the rest.
98    Prefer,
99    /// None forced.
100    Avoid,
101    /// Only forced ones.
102    Only,
103    /// The rest first, forced ones after. Also any value this build does
104    /// not know. (Last, as serde wants of `other`.)
105    #[default]
106    #[serde(other)]
107    Accept,
108}
109
110/// How a viewer wants picture subtitles shown: read as text by the
111/// server, so any device shows them styled and sized, or as the pictures
112/// they are.
113#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
114#[serde(rename_all = "snake_case")]
115pub enum BitmapPreference {
116    /// Drawn by the device if it can, else burned into the video.
117    Pictures,
118    /// Read as text when the server can read the track; else as
119    /// `Pictures`. Also any value this build does not know. (Last, as
120    /// serde wants of `other`.)
121    #[default]
122    #[serde(other)]
123    Text,
124}
125
126#[cfg(test)]
127mod tests {
128    use super::*;
129
130    #[test]
131    fn a_new_user_follows_the_file_avoids_description_and_shows_only_forced() {
132        let p = TrackPreferences::default();
133        assert!(p.audio.languages.is_empty());
134        assert_eq!(
135            p.audio.avoid,
136            [AudioRole::AudioDescription, AudioRole::Commentary]
137        );
138        assert_eq!(p.subtitles.mode, SubtitleMode::ForcedOnly);
139    }
140
141    /// The defaults as JSON, with `edit` applied.
142    fn full(edit: impl FnOnce(&mut serde_json::Value)) -> serde_json::Value {
143        let mut json = serde_json::to_value(TrackPreferences::default()).unwrap();
144        edit(&mut json);
145        json
146    }
147
148    #[test]
149    fn picture_subtitles_are_read_as_text_unless_the_viewer_wants_pictures() {
150        assert_eq!(
151            TrackPreferences::default().subtitles.bitmap,
152            BitmapPreference::Text
153        );
154        let p: TrackPreferences =
155            serde_json::from_value(full(|j| j["subtitles"]["bitmap"] = "pictures".into())).unwrap();
156        assert_eq!(p.subtitles.bitmap, BitmapPreference::Pictures);
157    }
158
159    #[test]
160    fn a_picture_subtitle_preference_this_build_does_not_know_reads_as_text() {
161        let p: TrackPreferences =
162            serde_json::from_value(full(|j| j["subtitles"]["bitmap"] = "hologram".into())).unwrap();
163        assert_eq!(p.subtitles.bitmap, BitmapPreference::Text);
164    }
165
166    #[test]
167    fn every_field_round_trips() {
168        let p: TrackPreferences = serde_json::from_value(full(|_| {})).unwrap();
169        assert_eq!(p, TrackPreferences::default());
170    }
171
172    #[test]
173    fn only_sdh_reads_and_an_unknown_sdh_preference_is_accept() {
174        let p: TrackPreferences =
175            serde_json::from_value(full(|j| j["subtitles"]["sdh"] = "only".into())).unwrap();
176        assert_eq!(p.subtitles.sdh, SdhPreference::Only);
177        let p: TrackPreferences =
178            serde_json::from_value(full(|j| j["subtitles"]["sdh"] = "sometimes".into())).unwrap();
179        assert_eq!(p.subtitles.sdh, SdhPreference::Accept);
180    }
181
182    #[test]
183    fn a_forced_preference_reads_by_name_and_an_unknown_one_is_accept() {
184        assert_eq!(
185            TrackPreferences::default().subtitles.forced,
186            ForcedPreference::Accept
187        );
188        for (name, wanted) in [
189            ("prefer", ForcedPreference::Prefer),
190            ("avoid", ForcedPreference::Avoid),
191            ("only", ForcedPreference::Only),
192            ("accept", ForcedPreference::Accept),
193            ("hologram", ForcedPreference::Accept),
194        ] {
195            let p: TrackPreferences =
196                serde_json::from_value(full(|j| j["subtitles"]["forced"] = name.into())).unwrap();
197            assert_eq!(p.subtitles.forced, wanted, "{name}");
198        }
199    }
200
201    /// Preferences without the forced preference, as a peer before the
202    /// reset to revision 1 could send them, are refused.
203    #[test]
204    fn preferences_without_the_forced_preference_are_refused() {
205        let error = serde_json::from_value::<TrackPreferences>(full(|j| {
206            j["subtitles"].as_object_mut().unwrap().remove("forced");
207        }))
208        .unwrap_err();
209        assert!(
210            error.to_string().contains("missing field `forced`"),
211            "{error}"
212        );
213    }
214
215    /// Each field in turn, by its JSON path, left out of the defaults.
216    /// (Not `subtitles.forced`, which a peer before it leaves out.)
217    #[test]
218    fn preferences_missing_any_field_are_refused() {
219        for (section, field) in [
220            (None, "audio"),
221            (None, "subtitles"),
222            (Some("audio"), "languages"),
223            (Some("audio"), "avoid"),
224            (Some("subtitles"), "mode"),
225            (Some("subtitles"), "languages"),
226            (Some("subtitles"), "sdh"),
227            (Some("subtitles"), "bitmap"),
228        ] {
229            let json = full(|j| {
230                let object = match section {
231                    Some(section) => &mut j[section],
232                    None => j,
233                };
234                object.as_object_mut().unwrap().remove(field);
235            });
236            let error = serde_json::from_value::<TrackPreferences>(json).unwrap_err();
237            assert!(
238                error
239                    .to_string()
240                    .contains(&format!("missing field `{field}`")),
241                "{section:?}.{field}: {error}"
242            );
243        }
244    }
245}