1use std::time::Duration;
9
10use serde::{Deserialize, Serialize};
11
12use crate::codec::{Container, HdrFormat, VideoCodec};
13use crate::duration_ms;
14
15#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
18pub struct MediaTracks {
19 #[serde(with = "duration_ms::option")]
20 pub duration: Option<Duration>,
21 pub container: Option<Container>,
24 pub bit_rate: Option<u64>,
33 pub video: Option<VideoTrack>,
35 pub audio: Vec<AudioTrack>,
36 pub subtitles: Vec<SubtitleTrack>,
37}
38
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
42pub struct VideoTrack {
43 pub codec: VideoCodec,
44 pub width: u32,
47 pub height: u32,
48 pub bit_depth: u32,
50 pub hdr: Option<HdrFormat>,
54 pub bit_rate: Option<u64>,
58}
59
60#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
61pub struct AudioTrack {
62 pub language: Option<String>,
64 pub title: Option<String>,
65 pub channels: Option<u32>,
66 pub default: bool,
68 pub role: AudioRole,
70}
71
72#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
74#[serde(rename_all = "snake_case")]
75pub enum AudioRole {
76 #[default]
78 Main,
79 AudioDescription,
82 Commentary,
83 #[serde(other)]
86 Other,
87}
88
89#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
90pub struct SubtitleTrack {
91 pub language: Option<String>,
93 pub title: Option<String>,
94 pub forced: bool,
97 pub default: bool,
98 pub external: bool,
100 pub role: SubtitleRole,
102 #[serde(default)]
108 pub timing: Option<SubtitleTiming>,
109 #[serde(default)]
114 pub download: Option<SubtitleDownload>,
115}
116
117#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
121pub enum SubtitleSource {
122 OpenSubtitles,
123 SubDl,
124}
125
126impl SubtitleSource {
127 pub const ALL: [SubtitleSource; 2] = [SubtitleSource::OpenSubtitles, SubtitleSource::SubDl];
130
131 pub fn id(self) -> &'static str {
133 match self {
134 SubtitleSource::OpenSubtitles => "opensubtitles",
135 SubtitleSource::SubDl => "subdl",
136 }
137 }
138
139 pub fn name(self) -> &'static str {
141 match self {
142 SubtitleSource::OpenSubtitles => "OpenSubtitles",
143 SubtitleSource::SubDl => "SubDL",
144 }
145 }
146
147 pub fn of(id: &str) -> Option<SubtitleSource> {
149 SubtitleSource::ALL.into_iter().find(|s| s.id() == id)
150 }
151
152 pub fn name_of(id: &str) -> &str {
155 SubtitleSource::of(id).map_or(id, |s| s.name())
156 }
157}
158
159impl std::fmt::Display for SubtitleSource {
160 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
161 f.write_str(self.name())
162 }
163}
164
165#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
168pub struct SubtitleDownload {
169 pub id: String,
171 pub source: String,
174 pub release: String,
176 pub by: String,
178 pub at: i64,
180 pub hash_match: bool,
183 pub origin: SubtitleOrigin,
184 pub can_remove: bool,
187}
188
189#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
191#[serde(rename_all = "snake_case")]
192pub enum SubtitleOrigin {
193 MachineTranslated,
195 Ai,
197 #[default]
200 #[serde(other)]
201 Human,
202}
203
204#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
206pub struct SubtitleResult {
207 pub id: String,
211 pub source: String,
214 pub release: String,
216 pub language: String,
218 pub format: Option<String>,
220 pub fps_milli: Option<u32>,
222 pub downloads: u64,
225 pub rating: Option<u8>,
228 pub hearing_impaired: bool,
229 pub forced: bool,
233 pub origin: SubtitleOrigin,
234 pub hash_match: bool,
237 pub rejected: bool,
239 pub downloaded: bool,
241}
242
243#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
248pub struct SubtitleSearch {
249 pub languages: Vec<String>,
251 pub results: Vec<SubtitleResult>,
252 pub sources: Vec<SubtitleSourceStatus>,
255}
256
257#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
259pub struct SubtitleSourceStatus {
260 pub source: String,
262 #[serde(flatten)]
264 pub state: SubtitleSourceState,
265}
266
267#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
269#[serde(tag = "state", rename_all = "snake_case")]
270pub enum SubtitleSourceState {
271 Found { found: u32 },
273 QuotaExhausted { resets_at: Option<i64> },
276 RateLimited { retry_after_ms: u64 },
278 Failed { message: String },
281 #[serde(other)]
283 Unknown,
284}
285
286#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
289pub struct SubtitleDownloaded {
290 pub track: u32,
292 pub subtitle: SubtitleTrack,
293 #[serde(deserialize_with = "crate::required::option")]
295 pub account_remaining: Option<u32>,
296 #[serde(deserialize_with = "crate::required::option")]
298 pub user_remaining: Option<u32>,
299}
300
301#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
303#[serde(rename_all = "snake_case")]
304pub enum QuotaOf {
305 Account,
308 User,
310 #[serde(other)]
312 Unknown,
313}
314
315#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
319pub struct SubtitleTiming {
320 pub sync: SubtitleSync,
321 pub offset_ms: i64,
325 #[serde(deserialize_with = "crate::required::option")]
327 pub offset_by: Option<String>,
328 #[serde(deserialize_with = "crate::required::option")]
330 pub offset_at: Option<i64>,
331}
332
333#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
335#[serde(tag = "state", rename_all = "snake_case")]
336pub enum SubtitleSync {
337 Original,
340 Syncing,
343 Synced {
345 offset_ms: i64,
347 factor_ppm: u32,
350 splits: u32,
352 score: u8,
354 },
355 Uncertain { score: u8 },
358 Failed { reason: String },
360 #[serde(other)]
362 Unknown,
363}
364
365#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
367#[serde(rename_all = "snake_case")]
368pub enum SubtitleRole {
369 Sdh,
372 Forced,
374 Commentary,
375 #[default]
378 #[serde(other)]
379 Full,
380}
381
382#[cfg(test)]
383mod tests {
384 use super::*;
385
386 #[test]
387 fn a_track_s_role_left_out_is_refused() {
388 let audio = AudioTrack {
389 language: None,
390 title: None,
391 channels: None,
392 default: false,
393 role: AudioRole::Commentary,
394 };
395 crate::test_support::assert_each_required(&audio, &["role"]);
396 let subtitle = SubtitleTrack {
397 language: None,
398 title: None,
399 forced: false,
400 default: false,
401 external: false,
402 role: SubtitleRole::Sdh,
403 timing: None,
404 download: None,
405 };
406 crate::test_support::assert_each_required(&subtitle, &["role"]);
407 }
408
409 fn sidecar(timing: Option<SubtitleTiming>) -> SubtitleTrack {
410 SubtitleTrack {
411 language: Some("eng".into()),
412 title: None,
413 forced: false,
414 default: false,
415 external: true,
416 role: SubtitleRole::Full,
417 timing,
418 download: None,
419 }
420 }
421
422 #[test]
425 fn a_track_s_download_is_null_for_one_not_downloaded() {
426 let mut json = serde_json::to_value(sidecar(None)).unwrap();
427 assert!(json["download"].is_null(), "{json}");
428 json.as_object_mut().unwrap().remove("download");
429 assert_eq!(
430 serde_json::from_value::<SubtitleTrack>(json).unwrap(),
431 sidecar(None)
432 );
433 let mut track = sidecar(None);
434 track.download = Some(SubtitleDownload {
435 id: "d1".into(),
436 source: "opensubtitles".into(),
437 release: "Film.2019.1080p".into(),
438 by: "Alice".into(),
439 at: 1_760_000_000,
440 hash_match: false,
441 origin: SubtitleOrigin::MachineTranslated,
442 can_remove: true,
443 });
444 let json = serde_json::to_value(&track).unwrap();
445 assert_eq!(json["download"]["origin"], "machine_translated");
446 assert_eq!(
447 serde_json::from_value::<SubtitleTrack>(json).unwrap(),
448 track
449 );
450 }
451
452 #[test]
453 fn an_origin_or_quota_this_build_does_not_know_still_decodes() {
454 let origin: SubtitleOrigin = serde_json::from_value(serde_json::json!("dubbed")).unwrap();
455 assert_eq!(origin, SubtitleOrigin::Human);
456 let whose: QuotaOf = serde_json::from_value(serde_json::json!("household")).unwrap();
457 assert_eq!(whose, QuotaOf::Unknown);
458 }
459
460 #[test]
461 fn a_source_is_named_by_its_id() {
462 for source in SubtitleSource::ALL {
463 assert_eq!(SubtitleSource::of(source.id()), Some(source));
464 }
465 assert_eq!(SubtitleSource::of("SubDL"), None);
466 assert_eq!(SubtitleSource::name_of("subdl"), "SubDL");
467 assert_eq!(SubtitleSource::name_of("podnapisi"), "podnapisi");
468 }
469
470 #[test]
474 fn a_result_or_a_search_missing_a_field_is_refused() {
475 let result = serde_json::json!({
476 "id": "opensubtitles:7", "source": "opensubtitles", "release": "R",
477 "language": "en", "format": null, "fps_milli": null, "downloads": 1,
478 "rating": null, "hearing_impaired": false, "forced": false,
479 "origin": "human", "hash_match": false, "rejected": false,
480 "downloaded": false,
481 });
482 let read: SubtitleResult = serde_json::from_value(result.clone()).unwrap();
483 assert_eq!(read.id, "opensubtitles:7");
484 for field in ["id", "source", "forced"] {
485 let mut without = result.clone();
486 without.as_object_mut().unwrap().remove(field);
487 let error = serde_json::from_value::<SubtitleResult>(without).unwrap_err();
488 assert!(
489 error
490 .to_string()
491 .contains(&format!("missing field `{field}`")),
492 "{field}: {error}"
493 );
494 }
495 let mut before_subdl = result.clone();
496 let fields = before_subdl.as_object_mut().unwrap();
497 fields.remove("id");
498 fields.insert("file_id".into(), 7.into());
499 assert!(serde_json::from_value::<SubtitleResult>(before_subdl).is_err());
500 let search = serde_json::json!({"languages": ["en"], "results": [result]});
501 let error = serde_json::from_value::<SubtitleSearch>(search).unwrap_err();
502 assert!(
503 error.to_string().contains("missing field `sources`"),
504 "{error}"
505 );
506 }
507
508 #[test]
509 fn a_download_s_remaining_counts_left_out_are_refused() {
510 let downloaded = SubtitleDownloaded {
511 track: 3,
512 subtitle: sidecar(None),
513 account_remaining: None,
514 user_remaining: None,
515 };
516 crate::test_support::assert_each_required(
517 &downloaded,
518 &["account_remaining", "user_remaining"],
519 );
520 }
521
522 #[test]
526 fn a_track_s_timing_is_null_when_there_is_none() {
527 let mut json = serde_json::to_value(sidecar(None)).unwrap();
528 assert!(json["timing"].is_null(), "{json}");
529 json.as_object_mut().unwrap().remove("timing");
530 assert_eq!(
531 serde_json::from_value::<SubtitleTrack>(json).unwrap(),
532 sidecar(None)
533 );
534 let timing = SubtitleTiming {
535 sync: SubtitleSync::Synced {
536 offset_ms: -3_200,
537 factor_ppm: 1_042_709,
538 splits: 1,
539 score: 87,
540 },
541 offset_ms: 1_500,
542 offset_by: Some("Alice".into()),
543 offset_at: Some(1_760_000_000),
544 };
545 let json = serde_json::to_value(sidecar(Some(timing.clone()))).unwrap();
546 assert_eq!(json["timing"]["sync"]["state"], "synced");
547 assert_eq!(
548 serde_json::from_value::<SubtitleTrack>(json).unwrap(),
549 sidecar(Some(timing))
550 );
551 }
552
553 #[test]
554 fn a_sync_state_this_build_does_not_know_is_unknown() {
555 let sync: SubtitleSync =
556 serde_json::from_value(serde_json::json!({ "state": "transcribing" })).unwrap();
557 assert_eq!(sync, SubtitleSync::Unknown);
558 }
559
560 #[test]
561 fn a_timing_s_offset_author_left_out_is_refused() {
562 let timing = SubtitleTiming {
563 sync: SubtitleSync::Original,
564 offset_ms: 0,
565 offset_by: None,
566 offset_at: None,
567 };
568 crate::test_support::assert_each_required(&timing, &["offset_by", "offset_at"]);
569 }
570
571 #[test]
572 fn tracks_round_trip_with_the_duration_in_milliseconds() {
573 let tracks = MediaTracks {
574 duration: Some(Duration::from_millis(6_106_791)),
575 container: Some(Container::Matroska),
576 bit_rate: Some(42_000_000),
577 video: Some(VideoTrack {
578 codec: VideoCodec::Hevc,
579 width: 3840,
580 height: 1600,
581 bit_depth: 10,
582 hdr: Some(HdrFormat::DolbyVision),
583 bit_rate: Some(38_500_000),
584 }),
585 audio: vec![AudioTrack {
586 language: Some("eng".into()),
587 title: None,
588 channels: Some(6),
589 default: true,
590 role: AudioRole::Main,
591 }],
592 subtitles: vec![SubtitleTrack {
593 language: Some("eng".into()),
594 title: Some("Forced".into()),
595 forced: true,
596 default: false,
597 external: true,
598 role: SubtitleRole::Forced,
599 timing: None,
600 download: None,
601 }],
602 };
603 let json = serde_json::to_value(&tracks).unwrap();
604 assert_eq!(json["duration"], 6_106_791);
605 assert_eq!(serde_json::from_value::<MediaTracks>(json).unwrap(), tracks);
606 }
607
608 #[test]
609 fn tracks_from_a_server_without_bit_rates_still_decode() {
610 let tracks = MediaTracks {
611 bit_rate: Some(42_000_000),
612 video: Some(VideoTrack {
613 codec: VideoCodec::Hevc,
614 width: 3840,
615 height: 2160,
616 bit_depth: 10,
617 hdr: None,
618 bit_rate: Some(38_500_000),
619 }),
620 ..MediaTracks::default()
621 };
622 let mut json = serde_json::to_value(&tracks).unwrap();
623 assert_eq!(json["bit_rate"], 42_000_000);
624 json.as_object_mut().unwrap().remove("bit_rate");
625 json["video"].as_object_mut().unwrap().remove("bit_rate");
626 let older: MediaTracks = serde_json::from_value(json).unwrap();
627 assert_eq!(older.bit_rate, None);
628 assert_eq!(older.video.unwrap().bit_rate, None);
629 }
630
631 #[test]
632 fn a_role_from_a_newer_peer_still_decodes() {
633 let audio: AudioRole = serde_json::from_value(serde_json::json!("karaoke")).unwrap();
636 assert_eq!(audio, AudioRole::Other);
637 let subtitle: SubtitleRole = serde_json::from_value(serde_json::json!("lyrics")).unwrap();
638 assert_eq!(subtitle, SubtitleRole::Full);
639 }
640}