1use 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#[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 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#[cfg_attr(feature = "uniffi", uniffi::export)]
145impl SubtitleTrack {
146 pub fn is_forced(&self) -> bool {
150 self.forced || self.role == SubtitleRole::Forced
151 }
152}
153
154#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
158pub enum SubtitleSource {
159 OpenSubtitles,
160 SubDl,
161}
162
163impl SubtitleSource {
164 pub const ALL: [SubtitleSource; 2] = [SubtitleSource::OpenSubtitles, SubtitleSource::SubDl];
167
168 pub fn id(self) -> &'static str {
170 match self {
171 SubtitleSource::OpenSubtitles => "opensubtitles",
172 SubtitleSource::SubDl => "subdl",
173 }
174 }
175
176 pub fn name(self) -> &'static str {
178 match self {
179 SubtitleSource::OpenSubtitles => "OpenSubtitles",
180 SubtitleSource::SubDl => "SubDL",
181 }
182 }
183
184 pub fn of(id: &str) -> Option<SubtitleSource> {
186 SubtitleSource::ALL.into_iter().find(|s| s.id() == id)
187 }
188
189 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
205#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
206pub struct SubtitleDownload {
207 pub id: String,
209 pub source: String,
212 pub release: String,
214 pub by: String,
216 pub at: i64,
218 pub hash_match: bool,
221 pub origin: SubtitleOrigin,
222 pub can_remove: bool,
225}
226
227#[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 MachineTranslated,
234 Ai,
236 #[default]
239 #[serde(other)]
240 Human,
241}
242
243#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
245#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
246pub struct SubtitleResult {
247 pub id: String,
251 pub source: String,
254 pub release: String,
256 pub language: String,
258 pub format: Option<String>,
260 pub fps_milli: Option<u32>,
262 pub downloads: u64,
265 pub rating: Option<u8>,
268 pub hearing_impaired: bool,
269 pub forced: bool,
273 pub origin: SubtitleOrigin,
274 pub hash_match: bool,
277 pub rejected: bool,
279 pub downloaded: bool,
281}
282
283#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
288#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
289pub struct SubtitleSearch {
290 pub languages: Vec<String>,
292 pub results: Vec<SubtitleResult>,
293 pub sources: Vec<SubtitleSourceStatus>,
296}
297
298#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
300#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
301pub struct SubtitleSourceStatus {
302 pub source: String,
304 #[serde(flatten)]
306 pub state: SubtitleSourceState,
307}
308
309#[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 Found { found: u32 },
316 QuotaExhausted { resets_at: Option<i64> },
319 RateLimited { retry_after_ms: u64 },
321 Failed { message: String },
324 #[serde(other)]
326 Unknown,
327}
328
329#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
332#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
333pub struct SubtitleDownloaded {
334 pub track: u32,
336 pub subtitle: SubtitleTrack,
337 #[serde(deserialize_with = "crate::required::option")]
339 pub account_remaining: Option<u32>,
340 #[serde(deserialize_with = "crate::required::option")]
342 pub user_remaining: Option<u32>,
343}
344
345#[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 Account,
353 User,
355 #[serde(other)]
357 Unknown,
358}
359
360#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
364#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
365pub struct SubtitleTiming {
366 pub sync: SubtitleSync,
367 pub offset_ms: i64,
371 #[serde(deserialize_with = "crate::required::option")]
373 pub offset_by: Option<String>,
374 #[serde(with = "serde_time::unix_seconds::option_required")]
376 pub offset_at: Option<SystemTime>,
377}
378
379impl SubtitleTiming {
380 pub const MAX_OFFSET_MS: i64 = 10 * 60 * 1000;
382 pub const OFFSET_STEP_MS: i64 = 100;
384
385 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 pub fn offset_stepped(&self, steps: i64) -> i64 {
397 Self::step_offset(self.offset_ms, steps)
398 }
399}
400
401#[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 Original,
409 Syncing,
412 Synced {
414 offset_ms: i64,
416 factor_ppm: u32,
419 splits: u32,
421 score: u8,
423 },
424 Uncertain { score: u8 },
427 Failed { reason: String },
429 #[serde(other)]
431 Unknown,
432}
433
434#[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 Sdh,
442 Forced,
444 Commentary,
445 #[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 #[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 #[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 #[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 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}