use std::time::Duration;
use serde::{Deserialize, Serialize};
use crate::browse::{DynamicRange, Resolution};
use crate::codec::{Container, HdrFormat, VideoCodec};
use crate::duration_ms;
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
pub struct MediaTracks {
#[serde(with = "duration_ms::option")]
pub duration: Option<Duration>,
pub container: Option<Container>,
pub bit_rate: Option<u64>,
pub video: Option<VideoTrack>,
pub audio: Vec<AudioTrack>,
pub subtitles: Vec<SubtitleTrack>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
pub struct VideoTrack {
pub codec: VideoCodec,
pub width: u32,
pub height: u32,
pub bit_depth: u32,
pub hdr: Option<HdrFormat>,
pub bit_rate: Option<u64>,
}
impl VideoTrack {
pub fn resolution(&self) -> Option<Resolution> {
let size = |n: u32| (n > 0).then_some(n);
Resolution::of(size(self.width), size(self.height))
}
pub fn dynamic_range(&self) -> DynamicRange {
match self.hdr {
None => DynamicRange::Sdr,
Some(HdrFormat::DolbyVision) => DynamicRange::DolbyVision,
Some(HdrFormat::Hdr10 | HdrFormat::Hlg) => DynamicRange::Hdr,
Some(HdrFormat::Unknown) => DynamicRange::Unknown,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
pub struct AudioTrack {
pub language: Option<String>,
pub title: Option<String>,
pub channels: Option<u32>,
pub default: bool,
pub role: AudioRole,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
#[serde(rename_all = "snake_case")]
pub enum AudioRole {
#[default]
Main,
AudioDescription,
Commentary,
#[serde(other)]
Other,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
pub struct SubtitleTrack {
pub language: Option<String>,
pub title: Option<String>,
pub forced: bool,
pub default: bool,
pub external: bool,
pub role: SubtitleRole,
#[serde(default)]
pub timing: Option<SubtitleTiming>,
#[serde(default)]
pub download: Option<SubtitleDownload>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum SubtitleSource {
OpenSubtitles,
SubDl,
}
impl SubtitleSource {
pub const ALL: [SubtitleSource; 2] = [SubtitleSource::OpenSubtitles, SubtitleSource::SubDl];
pub fn id(self) -> &'static str {
match self {
SubtitleSource::OpenSubtitles => "opensubtitles",
SubtitleSource::SubDl => "subdl",
}
}
pub fn name(self) -> &'static str {
match self {
SubtitleSource::OpenSubtitles => "OpenSubtitles",
SubtitleSource::SubDl => "SubDL",
}
}
pub fn of(id: &str) -> Option<SubtitleSource> {
SubtitleSource::ALL.into_iter().find(|s| s.id() == id)
}
pub fn name_of(id: &str) -> &str {
SubtitleSource::of(id).map_or(id, |s| s.name())
}
}
impl std::fmt::Display for SubtitleSource {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.name())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
pub struct SubtitleDownload {
pub id: String,
pub source: String,
pub release: String,
pub by: String,
pub at: i64,
pub hash_match: bool,
pub origin: SubtitleOrigin,
pub can_remove: bool,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
#[serde(rename_all = "snake_case")]
pub enum SubtitleOrigin {
MachineTranslated,
Ai,
#[default]
#[serde(other)]
Human,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
pub struct SubtitleResult {
pub id: String,
pub source: String,
pub release: String,
pub language: String,
pub format: Option<String>,
pub fps_milli: Option<u32>,
pub downloads: u64,
pub rating: Option<u8>,
pub hearing_impaired: bool,
pub forced: bool,
pub origin: SubtitleOrigin,
pub hash_match: bool,
pub rejected: bool,
pub downloaded: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
pub struct SubtitleSearch {
pub languages: Vec<String>,
pub results: Vec<SubtitleResult>,
pub sources: Vec<SubtitleSourceStatus>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
pub struct SubtitleSourceStatus {
pub source: String,
#[serde(flatten)]
pub state: SubtitleSourceState,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
#[serde(tag = "state", rename_all = "snake_case")]
pub enum SubtitleSourceState {
Found { found: u32 },
QuotaExhausted { resets_at: Option<i64> },
RateLimited { retry_after_ms: u64 },
Failed { message: String },
#[serde(other)]
Unknown,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
pub struct SubtitleDownloaded {
pub track: u32,
pub subtitle: SubtitleTrack,
#[serde(deserialize_with = "crate::required::option")]
pub account_remaining: Option<u32>,
#[serde(deserialize_with = "crate::required::option")]
pub user_remaining: Option<u32>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
#[serde(rename_all = "snake_case")]
pub enum QuotaOf {
Account,
User,
#[serde(other)]
Unknown,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
pub struct SubtitleTiming {
pub sync: SubtitleSync,
pub offset_ms: i64,
#[serde(deserialize_with = "crate::required::option")]
pub offset_by: Option<String>,
#[serde(deserialize_with = "crate::required::option")]
pub offset_at: Option<i64>,
}
impl SubtitleTiming {
pub const MAX_OFFSET_MS: i64 = 10 * 60 * 1000;
pub const OFFSET_STEP_MS: i64 = 100;
pub fn offset_stepped(&self, steps: i64) -> i64 {
steps
.saturating_mul(Self::OFFSET_STEP_MS)
.saturating_add(self.offset_ms)
.clamp(-Self::MAX_OFFSET_MS, Self::MAX_OFFSET_MS)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
#[serde(tag = "state", rename_all = "snake_case")]
pub enum SubtitleSync {
Original,
Syncing,
Synced {
offset_ms: i64,
factor_ppm: u32,
splits: u32,
score: u8,
},
Uncertain { score: u8 },
Failed { reason: String },
#[serde(other)]
Unknown,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
#[serde(rename_all = "snake_case")]
pub enum SubtitleRole {
Sdh,
Forced,
Commentary,
#[default]
#[serde(other)]
Full,
}
#[cfg(test)]
mod tests {
use super::*;
fn video(width: u32, height: u32, hdr: Option<HdrFormat>) -> VideoTrack {
VideoTrack {
codec: VideoCodec::Hevc,
width,
height,
bit_depth: 10,
hdr,
bit_rate: None,
}
}
#[test]
fn a_scope_film_is_classed_by_its_width_too() {
assert_eq!(video(3840, 1600, None).resolution(), Some(Resolution::Uhd));
assert_eq!(
video(1920, 800, None).resolution(),
Some(Resolution::FullHd)
);
assert_eq!(video(720, 480, None).resolution(), Some(Resolution::Sd));
assert_eq!(video(0, 0, None).resolution(), None);
}
#[test]
fn hdr_formats_read_as_a_filters_ranges() {
let range = |hdr| video(3840, 2160, hdr).dynamic_range();
assert_eq!(range(None), DynamicRange::Sdr);
assert_eq!(range(Some(HdrFormat::Hlg)), DynamicRange::Hdr);
assert_eq!(
range(Some(HdrFormat::DolbyVision)),
DynamicRange::DolbyVision
);
}
#[test]
fn a_track_s_role_left_out_is_refused() {
let audio = AudioTrack {
language: None,
title: None,
channels: None,
default: false,
role: AudioRole::Commentary,
};
crate::test_support::assert_each_required(&audio, &["role"]);
let subtitle = SubtitleTrack {
language: None,
title: None,
forced: false,
default: false,
external: false,
role: SubtitleRole::Sdh,
timing: None,
download: None,
};
crate::test_support::assert_each_required(&subtitle, &["role"]);
}
fn sidecar(timing: Option<SubtitleTiming>) -> SubtitleTrack {
SubtitleTrack {
language: Some("eng".into()),
title: None,
forced: false,
default: false,
external: true,
role: SubtitleRole::Full,
timing,
download: None,
}
}
#[test]
fn a_track_s_download_is_null_for_one_not_downloaded() {
let mut json = serde_json::to_value(sidecar(None)).unwrap();
assert!(json["download"].is_null(), "{json}");
json.as_object_mut().unwrap().remove("download");
assert_eq!(
serde_json::from_value::<SubtitleTrack>(json).unwrap(),
sidecar(None)
);
let mut track = sidecar(None);
track.download = Some(SubtitleDownload {
id: "d1".into(),
source: "opensubtitles".into(),
release: "Film.2019.1080p".into(),
by: "Alice".into(),
at: 1_760_000_000,
hash_match: false,
origin: SubtitleOrigin::MachineTranslated,
can_remove: true,
});
let json = serde_json::to_value(&track).unwrap();
assert_eq!(json["download"]["origin"], "machine_translated");
assert_eq!(
serde_json::from_value::<SubtitleTrack>(json).unwrap(),
track
);
}
#[test]
fn an_origin_or_quota_this_build_does_not_know_still_decodes() {
let origin: SubtitleOrigin = serde_json::from_value(serde_json::json!("dubbed")).unwrap();
assert_eq!(origin, SubtitleOrigin::Human);
let whose: QuotaOf = serde_json::from_value(serde_json::json!("household")).unwrap();
assert_eq!(whose, QuotaOf::Unknown);
}
#[test]
fn a_source_is_named_by_its_id() {
for source in SubtitleSource::ALL {
assert_eq!(SubtitleSource::of(source.id()), Some(source));
}
assert_eq!(SubtitleSource::of("SubDL"), None);
assert_eq!(SubtitleSource::name_of("subdl"), "SubDL");
assert_eq!(SubtitleSource::name_of("podnapisi"), "podnapisi");
}
#[test]
fn a_result_or_a_search_missing_a_field_is_refused() {
let result = serde_json::json!({
"id": "opensubtitles:7", "source": "opensubtitles", "release": "R",
"language": "en", "format": null, "fps_milli": null, "downloads": 1,
"rating": null, "hearing_impaired": false, "forced": false,
"origin": "human", "hash_match": false, "rejected": false,
"downloaded": false,
});
let read: SubtitleResult = serde_json::from_value(result.clone()).unwrap();
assert_eq!(read.id, "opensubtitles:7");
for field in ["id", "source", "forced"] {
let mut without = result.clone();
without.as_object_mut().unwrap().remove(field);
let error = serde_json::from_value::<SubtitleResult>(without).unwrap_err();
assert!(
error
.to_string()
.contains(&format!("missing field `{field}`")),
"{field}: {error}"
);
}
let mut before_subdl = result.clone();
let fields = before_subdl.as_object_mut().unwrap();
fields.remove("id");
fields.insert("file_id".into(), 7.into());
assert!(serde_json::from_value::<SubtitleResult>(before_subdl).is_err());
let search = serde_json::json!({"languages": ["en"], "results": [result]});
let error = serde_json::from_value::<SubtitleSearch>(search).unwrap_err();
assert!(
error.to_string().contains("missing field `sources`"),
"{error}"
);
}
#[test]
fn a_download_s_remaining_counts_left_out_are_refused() {
let downloaded = SubtitleDownloaded {
track: 3,
subtitle: sidecar(None),
account_remaining: None,
user_remaining: None,
};
crate::test_support::assert_each_required(
&downloaded,
&["account_remaining", "user_remaining"],
);
}
#[test]
fn a_track_s_timing_is_null_when_there_is_none() {
let mut json = serde_json::to_value(sidecar(None)).unwrap();
assert!(json["timing"].is_null(), "{json}");
json.as_object_mut().unwrap().remove("timing");
assert_eq!(
serde_json::from_value::<SubtitleTrack>(json).unwrap(),
sidecar(None)
);
let timing = SubtitleTiming {
sync: SubtitleSync::Synced {
offset_ms: -3_200,
factor_ppm: 1_042_709,
splits: 1,
score: 87,
},
offset_ms: 1_500,
offset_by: Some("Alice".into()),
offset_at: Some(1_760_000_000),
};
let json = serde_json::to_value(sidecar(Some(timing.clone()))).unwrap();
assert_eq!(json["timing"]["sync"]["state"], "synced");
assert_eq!(
serde_json::from_value::<SubtitleTrack>(json).unwrap(),
sidecar(Some(timing))
);
}
#[test]
fn the_offset_moves_a_tenth_of_a_second_a_press_and_no_further_than_the_most() {
let timing = |offset_ms| SubtitleTiming {
sync: SubtitleSync::Original,
offset_ms,
offset_by: None,
offset_at: None,
};
assert_eq!(timing(1_500).offset_stepped(1), 1_600);
assert_eq!(timing(1_500).offset_stepped(-20), -500);
assert_eq!(timing(599_950).offset_stepped(1), 600_000);
assert_eq!(timing(-599_950).offset_stepped(-3), -600_000);
assert_eq!(timing(0).offset_stepped(i64::MAX), 600_000);
}
#[test]
fn a_sync_state_this_build_does_not_know_is_unknown() {
let sync: SubtitleSync =
serde_json::from_value(serde_json::json!({ "state": "transcribing" })).unwrap();
assert_eq!(sync, SubtitleSync::Unknown);
}
#[test]
fn a_timing_s_offset_author_left_out_is_refused() {
let timing = SubtitleTiming {
sync: SubtitleSync::Original,
offset_ms: 0,
offset_by: None,
offset_at: None,
};
crate::test_support::assert_each_required(&timing, &["offset_by", "offset_at"]);
}
#[test]
fn tracks_round_trip_with_the_duration_in_milliseconds() {
let tracks = MediaTracks {
duration: Some(Duration::from_millis(6_106_791)),
container: Some(Container::Matroska),
bit_rate: Some(42_000_000),
video: Some(VideoTrack {
codec: VideoCodec::Hevc,
width: 3840,
height: 1600,
bit_depth: 10,
hdr: Some(HdrFormat::DolbyVision),
bit_rate: Some(38_500_000),
}),
audio: vec![AudioTrack {
language: Some("eng".into()),
title: None,
channels: Some(6),
default: true,
role: AudioRole::Main,
}],
subtitles: vec![SubtitleTrack {
language: Some("eng".into()),
title: Some("Forced".into()),
forced: true,
default: false,
external: true,
role: SubtitleRole::Forced,
timing: None,
download: None,
}],
};
let json = serde_json::to_value(&tracks).unwrap();
assert_eq!(json["duration"], 6_106_791);
assert_eq!(serde_json::from_value::<MediaTracks>(json).unwrap(), tracks);
}
#[test]
fn tracks_from_a_server_without_bit_rates_still_decode() {
let tracks = MediaTracks {
bit_rate: Some(42_000_000),
video: Some(VideoTrack {
codec: VideoCodec::Hevc,
width: 3840,
height: 2160,
bit_depth: 10,
hdr: None,
bit_rate: Some(38_500_000),
}),
..MediaTracks::default()
};
let mut json = serde_json::to_value(&tracks).unwrap();
assert_eq!(json["bit_rate"], 42_000_000);
json.as_object_mut().unwrap().remove("bit_rate");
json["video"].as_object_mut().unwrap().remove("bit_rate");
let older: MediaTracks = serde_json::from_value(json).unwrap();
assert_eq!(older.bit_rate, None);
assert_eq!(older.video.unwrap().bit_rate, None);
}
#[test]
fn a_role_from_a_newer_peer_still_decodes() {
let audio: AudioRole = serde_json::from_value(serde_json::json!("karaoke")).unwrap();
assert_eq!(audio, AudioRole::Other);
let subtitle: SubtitleRole = serde_json::from_value(serde_json::json!("lyrics")).unwrap();
assert_eq!(subtitle, SubtitleRole::Full);
}
}