1use 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#[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 pub container: Option<Container>,
26 pub bit_rate: Option<u64>,
35 pub video: Option<VideoTrack>,
37 pub audio: Vec<AudioTrack>,
38 pub subtitles: Vec<SubtitleTrack>,
39}
40
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
44#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
45pub struct VideoTrack {
46 pub codec: VideoCodec,
47 pub width: u32,
50 pub height: u32,
51 pub bit_depth: u32,
53 pub hdr: Option<HdrFormat>,
57 pub bit_rate: Option<u64>,
61}
62
63impl VideoTrack {
64 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 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 pub language: Option<String>,
89 pub title: Option<String>,
90 pub channels: Option<u32>,
91 pub default: bool,
93 pub role: AudioRole,
95}
96
97#[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 #[default]
104 Main,
105 AudioDescription,
108 Commentary,
109 #[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 pub language: Option<String>,
120 pub title: Option<String>,
121 pub forced: bool,
124 pub default: bool,
125 pub external: bool,
127 pub role: SubtitleRole,
129 #[serde(default)]
135 pub timing: Option<SubtitleTiming>,
136 #[serde(default)]
141 pub download: Option<SubtitleDownload>,
142}
143
144#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
148pub enum SubtitleSource {
149 OpenSubtitles,
150 SubDl,
151}
152
153impl SubtitleSource {
154 pub const ALL: [SubtitleSource; 2] = [SubtitleSource::OpenSubtitles, SubtitleSource::SubDl];
157
158 pub fn id(self) -> &'static str {
160 match self {
161 SubtitleSource::OpenSubtitles => "opensubtitles",
162 SubtitleSource::SubDl => "subdl",
163 }
164 }
165
166 pub fn name(self) -> &'static str {
168 match self {
169 SubtitleSource::OpenSubtitles => "OpenSubtitles",
170 SubtitleSource::SubDl => "SubDL",
171 }
172 }
173
174 pub fn of(id: &str) -> Option<SubtitleSource> {
176 SubtitleSource::ALL.into_iter().find(|s| s.id() == id)
177 }
178
179 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
195#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
196pub struct SubtitleDownload {
197 pub id: String,
199 pub source: String,
202 pub release: String,
204 pub by: String,
206 pub at: i64,
208 pub hash_match: bool,
211 pub origin: SubtitleOrigin,
212 pub can_remove: bool,
215}
216
217#[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 MachineTranslated,
224 Ai,
226 #[default]
229 #[serde(other)]
230 Human,
231}
232
233#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
235#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
236pub struct SubtitleResult {
237 pub id: String,
241 pub source: String,
244 pub release: String,
246 pub language: String,
248 pub format: Option<String>,
250 pub fps_milli: Option<u32>,
252 pub downloads: u64,
255 pub rating: Option<u8>,
258 pub hearing_impaired: bool,
259 pub forced: bool,
263 pub origin: SubtitleOrigin,
264 pub hash_match: bool,
267 pub rejected: bool,
269 pub downloaded: bool,
271}
272
273#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
278#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
279pub struct SubtitleSearch {
280 pub languages: Vec<String>,
282 pub results: Vec<SubtitleResult>,
283 pub sources: Vec<SubtitleSourceStatus>,
286}
287
288#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
290#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
291pub struct SubtitleSourceStatus {
292 pub source: String,
294 #[serde(flatten)]
296 pub state: SubtitleSourceState,
297}
298
299#[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 Found { found: u32 },
306 QuotaExhausted { resets_at: Option<i64> },
309 RateLimited { retry_after_ms: u64 },
311 Failed { message: String },
314 #[serde(other)]
316 Unknown,
317}
318
319#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
322#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
323pub struct SubtitleDownloaded {
324 pub track: u32,
326 pub subtitle: SubtitleTrack,
327 #[serde(deserialize_with = "crate::required::option")]
329 pub account_remaining: Option<u32>,
330 #[serde(deserialize_with = "crate::required::option")]
332 pub user_remaining: Option<u32>,
333}
334
335#[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 Account,
343 User,
345 #[serde(other)]
347 Unknown,
348}
349
350#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
354#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
355pub struct SubtitleTiming {
356 pub sync: SubtitleSync,
357 pub offset_ms: i64,
361 #[serde(deserialize_with = "crate::required::option")]
363 pub offset_by: Option<String>,
364 #[serde(deserialize_with = "crate::required::option")]
366 pub offset_at: Option<i64>,
367}
368
369impl SubtitleTiming {
370 pub const MAX_OFFSET_MS: i64 = 10 * 60 * 1000;
372 pub const OFFSET_STEP_MS: i64 = 100;
374
375 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#[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 Original,
393 Syncing,
396 Synced {
398 offset_ms: i64,
400 factor_ppm: u32,
403 splits: u32,
405 score: u8,
407 },
408 Uncertain { score: u8 },
411 Failed { reason: String },
413 #[serde(other)]
415 Unknown,
416}
417
418#[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 Sdh,
426 Forced,
428 Commentary,
429 #[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 #[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 #[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 #[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 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}