Skip to main content

spoolframe_types/
preferences.rs

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