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)]
122pub enum SubtitleSource {
123 OpenSubtitles,
124 SubDl,
125}
126
127impl SubtitleSource {
128 pub const ALL: [SubtitleSource; 2] = [SubtitleSource::OpenSubtitles, SubtitleSource::SubDl];
131
132 pub fn id(self) -> &'static str {
134 match self {
135 SubtitleSource::OpenSubtitles => "opensubtitles",
136 SubtitleSource::SubDl => "subdl",
137 }
138 }
139
140 pub fn name(self) -> &'static str {
142 match self {
143 SubtitleSource::OpenSubtitles => "OpenSubtitles",
144 SubtitleSource::SubDl => "SubDL",
145 }
146 }
147
148 pub fn of(id: &str) -> Option<SubtitleSource> {
150 SubtitleSource::ALL.into_iter().find(|s| s.id() == id)
151 }
152
153 pub fn name_of(id: &str) -> &str {
156 SubtitleSource::of(id).map_or(id, |s| s.name())
157 }
158}
159
160impl std::fmt::Display for SubtitleSource {
161 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
162 f.write_str(self.name())
163 }
164}
165
166#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
169pub struct SubtitleDownload {
170 pub id: String,
172 pub source: String,
175 pub release: String,
177 pub by: String,
179 pub at: i64,
181 pub hash_match: bool,
184 pub origin: SubtitleOrigin,
185 pub can_remove: bool,
188}
189
190#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
192#[serde(rename_all = "snake_case")]
193pub enum SubtitleOrigin {
194 MachineTranslated,
196 Ai,
198 #[default]
201 #[serde(other)]
202 Human,
203}
204
205#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
207pub struct SubtitleResult {
208 pub id: String,
212 pub source: String,
215 pub release: String,
217 pub language: String,
219 pub format: Option<String>,
221 pub fps_milli: Option<u32>,
223 pub downloads: u64,
226 pub rating: Option<u8>,
229 pub hearing_impaired: bool,
230 pub forced: bool,
234 pub origin: SubtitleOrigin,
235 pub hash_match: bool,
238 pub rejected: bool,
240 pub downloaded: bool,
242}
243
244#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
249pub struct SubtitleSearch {
250 pub languages: Vec<String>,
252 pub results: Vec<SubtitleResult>,
253 pub sources: Vec<SubtitleSourceStatus>,
256}
257
258#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
260pub struct SubtitleSourceStatus {
261 pub source: String,
263 #[serde(flatten)]
265 pub state: SubtitleSourceState,
266}
267
268#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
270#[serde(tag = "state", rename_all = "snake_case")]
271pub enum SubtitleSourceState {
272 Found { found: u32 },
274 QuotaExhausted { resets_at: Option<i64> },
277 RateLimited { retry_after_ms: u64 },
279 Failed { message: String },
282 #[serde(other)]
284 Unknown,
285}
286
287#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
290pub struct SubtitleDownloaded {
291 pub track: u32,
293 pub subtitle: SubtitleTrack,
294 #[serde(deserialize_with = "crate::required::option")]
296 pub account_remaining: Option<u32>,
297 #[serde(deserialize_with = "crate::required::option")]
299 pub user_remaining: Option<u32>,
300}
301
302#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
304#[serde(rename_all = "snake_case")]
305pub enum QuotaOf {
306 Account,
309 User,
311 #[serde(other)]
313 Unknown,
314}
315
316#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
320pub struct SubtitleTiming {
321 pub sync: SubtitleSync,
322 pub offset_ms: i64,
326 #[serde(deserialize_with = "crate::required::option")]
328 pub offset_by: Option<String>,
329 #[serde(deserialize_with = "crate::required::option")]
331 pub offset_at: Option<i64>,
332}
333
334#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
336#[serde(tag = "state", rename_all = "snake_case")]
337pub enum SubtitleSync {
338 Original,
341 Syncing,
344 Synced {
346 offset_ms: i64,
348 factor_ppm: u32,
351 splits: u32,
353 score: u8,
355 },
356 Uncertain { score: u8 },
359 Failed { reason: String },
361 #[serde(other)]
363 Unknown,
364}
365
366#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
368#[serde(rename_all = "snake_case")]
369pub enum SubtitleRole {
370 Sdh,
373 Forced,
375 Commentary,
376 #[default]
379 #[serde(other)]
380 Full,
381}
382
383#[cfg(test)]
384mod tests {
385 use super::*;
386
387 #[test]
388 fn a_track_s_role_left_out_is_refused() {
389 let audio = AudioTrack {
390 language: None,
391 title: None,
392 channels: None,
393 default: false,
394 role: AudioRole::Commentary,
395 };
396 crate::test_support::assert_each_required(&audio, &["role"]);
397 let subtitle = SubtitleTrack {
398 language: None,
399 title: None,
400 forced: false,
401 default: false,
402 external: false,
403 role: SubtitleRole::Sdh,
404 timing: None,
405 download: None,
406 };
407 crate::test_support::assert_each_required(&subtitle, &["role"]);
408 }
409
410 fn sidecar(timing: Option<SubtitleTiming>) -> SubtitleTrack {
411 SubtitleTrack {
412 language: Some("eng".into()),
413 title: None,
414 forced: false,
415 default: false,
416 external: true,
417 role: SubtitleRole::Full,
418 timing,
419 download: None,
420 }
421 }
422
423 #[test]
426 fn a_track_s_download_is_null_for_one_not_downloaded() {
427 let mut json = serde_json::to_value(sidecar(None)).unwrap();
428 assert!(json["download"].is_null(), "{json}");
429 json.as_object_mut().unwrap().remove("download");
430 assert_eq!(
431 serde_json::from_value::<SubtitleTrack>(json).unwrap(),
432 sidecar(None)
433 );
434 let mut track = sidecar(None);
435 track.download = Some(SubtitleDownload {
436 id: "d1".into(),
437 source: "opensubtitles".into(),
438 release: "Film.2019.1080p".into(),
439 by: "Alice".into(),
440 at: 1_760_000_000,
441 hash_match: false,
442 origin: SubtitleOrigin::MachineTranslated,
443 can_remove: true,
444 });
445 let json = serde_json::to_value(&track).unwrap();
446 assert_eq!(json["download"]["origin"], "machine_translated");
447 assert_eq!(
448 serde_json::from_value::<SubtitleTrack>(json).unwrap(),
449 track
450 );
451 }
452
453 #[test]
454 fn an_origin_or_quota_this_build_does_not_know_still_decodes() {
455 let origin: SubtitleOrigin = serde_json::from_value(serde_json::json!("dubbed")).unwrap();
456 assert_eq!(origin, SubtitleOrigin::Human);
457 let whose: QuotaOf = serde_json::from_value(serde_json::json!("household")).unwrap();
458 assert_eq!(whose, QuotaOf::Unknown);
459 }
460
461 #[test]
462 fn a_source_is_named_by_its_id() {
463 for source in SubtitleSource::ALL {
464 assert_eq!(SubtitleSource::of(source.id()), Some(source));
465 }
466 assert_eq!(SubtitleSource::of("SubDL"), None);
467 assert_eq!(SubtitleSource::name_of("subdl"), "SubDL");
468 assert_eq!(SubtitleSource::name_of("podnapisi"), "podnapisi");
469 }
470
471 #[test]
475 fn a_result_or_a_search_missing_a_field_is_refused() {
476 let result = serde_json::json!({
477 "id": "opensubtitles:7", "source": "opensubtitles", "release": "R",
478 "language": "en", "format": null, "fps_milli": null, "downloads": 1,
479 "rating": null, "hearing_impaired": false, "forced": false,
480 "origin": "human", "hash_match": false, "rejected": false,
481 "downloaded": false,
482 });
483 let read: SubtitleResult = serde_json::from_value(result.clone()).unwrap();
484 assert_eq!(read.id, "opensubtitles:7");
485 for field in ["id", "source", "forced"] {
486 let mut without = result.clone();
487 without.as_object_mut().unwrap().remove(field);
488 let error = serde_json::from_value::<SubtitleResult>(without).unwrap_err();
489 assert!(
490 error
491 .to_string()
492 .contains(&format!("missing field `{field}`")),
493 "{field}: {error}"
494 );
495 }
496 let mut before_subdl = result.clone();
497 let fields = before_subdl.as_object_mut().unwrap();
498 fields.remove("id");
499 fields.insert("file_id".into(), 7.into());
500 assert!(serde_json::from_value::<SubtitleResult>(before_subdl).is_err());
501 let search = serde_json::json!({"languages": ["en"], "results": [result]});
502 let error = serde_json::from_value::<SubtitleSearch>(search).unwrap_err();
503 assert!(
504 error.to_string().contains("missing field `sources`"),
505 "{error}"
506 );
507 }
508
509 #[test]
510 fn a_download_s_remaining_counts_left_out_are_refused() {
511 let downloaded = SubtitleDownloaded {
512 track: 3,
513 subtitle: sidecar(None),
514 account_remaining: None,
515 user_remaining: None,
516 };
517 crate::test_support::assert_each_required(
518 &downloaded,
519 &["account_remaining", "user_remaining"],
520 );
521 }
522
523 #[test]
527 fn a_track_s_timing_is_null_when_there_is_none() {
528 let mut json = serde_json::to_value(sidecar(None)).unwrap();
529 assert!(json["timing"].is_null(), "{json}");
530 json.as_object_mut().unwrap().remove("timing");
531 assert_eq!(
532 serde_json::from_value::<SubtitleTrack>(json).unwrap(),
533 sidecar(None)
534 );
535 let timing = SubtitleTiming {
536 sync: SubtitleSync::Synced {
537 offset_ms: -3_200,
538 factor_ppm: 1_042_709,
539 splits: 1,
540 score: 87,
541 },
542 offset_ms: 1_500,
543 offset_by: Some("Alice".into()),
544 offset_at: Some(1_760_000_000),
545 };
546 let json = serde_json::to_value(sidecar(Some(timing.clone()))).unwrap();
547 assert_eq!(json["timing"]["sync"]["state"], "synced");
548 assert_eq!(
549 serde_json::from_value::<SubtitleTrack>(json).unwrap(),
550 sidecar(Some(timing))
551 );
552 }
553
554 #[test]
555 fn a_sync_state_this_build_does_not_know_is_unknown() {
556 let sync: SubtitleSync =
557 serde_json::from_value(serde_json::json!({ "state": "transcribing" })).unwrap();
558 assert_eq!(sync, SubtitleSync::Unknown);
559 }
560
561 #[test]
562 fn a_timing_s_offset_author_left_out_is_refused() {
563 let timing = SubtitleTiming {
564 sync: SubtitleSync::Original,
565 offset_ms: 0,
566 offset_by: None,
567 offset_at: None,
568 };
569 crate::test_support::assert_each_required(&timing, &["offset_by", "offset_at"]);
570 }
571
572 #[test]
573 fn tracks_round_trip_with_the_duration_in_milliseconds() {
574 let tracks = MediaTracks {
575 duration: Some(Duration::from_millis(6_106_791)),
576 container: Some(Container::Matroska),
577 bit_rate: Some(42_000_000),
578 video: Some(VideoTrack {
579 codec: VideoCodec::Hevc,
580 width: 3840,
581 height: 1600,
582 bit_depth: 10,
583 hdr: Some(HdrFormat::DolbyVision),
584 bit_rate: Some(38_500_000),
585 }),
586 audio: vec![AudioTrack {
587 language: Some("eng".into()),
588 title: None,
589 channels: Some(6),
590 default: true,
591 role: AudioRole::Main,
592 }],
593 subtitles: vec![SubtitleTrack {
594 language: Some("eng".into()),
595 title: Some("Forced".into()),
596 forced: true,
597 default: false,
598 external: true,
599 role: SubtitleRole::Forced,
600 timing: None,
601 download: None,
602 }],
603 };
604 let json = serde_json::to_value(&tracks).unwrap();
605 assert_eq!(json["duration"], 6_106_791);
606 assert_eq!(serde_json::from_value::<MediaTracks>(json).unwrap(), tracks);
607 }
608
609 #[test]
610 fn tracks_from_a_server_without_bit_rates_still_decode() {
611 let tracks = MediaTracks {
612 bit_rate: Some(42_000_000),
613 video: Some(VideoTrack {
614 codec: VideoCodec::Hevc,
615 width: 3840,
616 height: 2160,
617 bit_depth: 10,
618 hdr: None,
619 bit_rate: Some(38_500_000),
620 }),
621 ..MediaTracks::default()
622 };
623 let mut json = serde_json::to_value(&tracks).unwrap();
624 assert_eq!(json["bit_rate"], 42_000_000);
625 json.as_object_mut().unwrap().remove("bit_rate");
626 json["video"].as_object_mut().unwrap().remove("bit_rate");
627 let older: MediaTracks = serde_json::from_value(json).unwrap();
628 assert_eq!(older.bit_rate, None);
629 assert_eq!(older.video.unwrap().bit_rate, None);
630 }
631
632 #[test]
633 fn a_role_from_a_newer_peer_still_decodes() {
634 let audio: AudioRole = serde_json::from_value(serde_json::json!("karaoke")).unwrap();
637 assert_eq!(audio, AudioRole::Other);
638 let subtitle: SubtitleRole = serde_json::from_value(serde_json::json!("lyrics")).unwrap();
639 assert_eq!(subtitle, SubtitleRole::Full);
640 }
641}