pub mod legibility;
pub mod srt;
pub mod vtt;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum CaptionAlign {
Left,
#[default]
Center,
Right,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum CaptionAnchor {
Top,
Middle,
#[default]
Bottom,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CaptionFormat {
Srt,
Vtt,
}
impl CaptionFormat {
pub fn extension(self) -> &'static str {
match self {
CaptionFormat::Srt => "srt",
CaptionFormat::Vtt => "vtt",
}
}
pub fn mime_type(self) -> &'static str {
match self {
CaptionFormat::Srt => "application/x-subrip",
CaptionFormat::Vtt => "text/vtt",
}
}
pub fn from_path(path: &str) -> Option<Self> {
let ext = path.rsplit('.').next()?.to_ascii_lowercase();
match ext.as_str() {
"srt" => Some(CaptionFormat::Srt),
"vtt" | "webvtt" => Some(CaptionFormat::Vtt),
_ => None,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum CaptionError {
BadTimestamp {
line: usize,
text: String,
},
MissingTiming {
line: usize,
},
Empty,
NotRecognized,
}
impl std::fmt::Display for CaptionError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
CaptionError::BadTimestamp { line, text } => {
write!(f, "line {line}: malformed cue timing {text:?}")
}
CaptionError::MissingTiming { line } => {
write!(f, "line {line}: cue block has no \"-->\" timing line")
}
CaptionError::Empty => write!(f, "no cues found"),
CaptionError::NotRecognized => write!(f, "input is not SubRip or WebVTT"),
}
}
}
impl std::error::Error for CaptionError {}
#[derive(Clone, Debug, PartialEq)]
pub struct Cue {
pub id: Option<String>,
pub start: f64,
pub end: f64,
pub text: String,
pub align: Option<CaptionAlign>,
pub line: Option<f32>,
pub position: Option<f32>,
}
impl Cue {
pub fn new(start: f64, end: f64, text: impl Into<String>) -> Self {
Self {
id: None,
start,
end,
text: text.into(),
align: None,
line: None,
position: None,
}
}
pub fn id(mut self, id: impl Into<String>) -> Self {
self.id = Some(id.into());
self
}
pub fn align(mut self, align: CaptionAlign) -> Self {
self.align = Some(align);
self
}
pub fn at_line(mut self, line: f32) -> Self {
self.line = Some(line);
self
}
pub fn at_position(mut self, position: f32) -> Self {
self.position = Some(position);
self
}
pub fn duration(&self) -> f64 {
(self.end - self.start).max(0.0)
}
pub fn is_active_at(&self, time: f64) -> bool {
time >= self.start && time < self.end
}
pub fn plain_text(&self) -> String {
strip_markup(&self.text)
}
}
pub fn strip_markup(text: &str) -> String {
let mut out = String::with_capacity(text.len());
let mut chars = text.chars().peekable();
while let Some(c) = chars.next() {
match c {
'<' => {
for t in chars.by_ref() {
if t == '>' {
break;
}
}
}
'{' if matches!(chars.peek(), Some('\\')) => {
for t in chars.by_ref() {
if t == '}' {
break;
}
}
}
'&' => {
let mut name = String::new();
let mut closed = false;
while let Some(&t) = chars.peek() {
if t == ';' {
chars.next();
closed = true;
break;
}
if !t.is_ascii_alphanumeric() && t != '#' || name.len() > 8 {
break;
}
name.push(t);
chars.next();
}
match (closed, name.as_str()) {
(true, "amp") => out.push('&'),
(true, "lt") => out.push('<'),
(true, "gt") => out.push('>'),
(true, "quot") => out.push('"'),
(true, "apos") => out.push('\''),
(true, "nbsp") => out.push(' '),
(true, "lrm") | (true, "rlm") => {}
_ => {
out.push('&');
out.push_str(&name);
if closed {
out.push(';');
}
}
}
}
_ => out.push(c),
}
}
out
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct CaptionTrack {
pub cues: Vec<Cue>,
pub language: String,
pub label: String,
}
impl CaptionTrack {
pub fn new() -> Self {
Self::default()
}
pub fn language(mut self, language: impl Into<String>) -> Self {
self.language = language.into();
self
}
pub fn label(mut self, label: impl Into<String>) -> Self {
self.label = label.into();
self
}
pub fn cue(mut self, start: f64, end: f64, text: impl Into<String>) -> Self {
self.push(Cue::new(start, end, text));
self
}
pub fn push(&mut self, cue: Cue) {
let at = self
.cues
.iter()
.rposition(|c| c.start <= cue.start)
.map(|i| i + 1)
.unwrap_or(0);
self.cues.insert(at, cue);
}
pub fn sort(&mut self) {
self.cues.sort_by(|a, b| {
a.start
.partial_cmp(&b.start)
.unwrap_or(std::cmp::Ordering::Equal)
.then(
a.end
.partial_cmp(&b.end)
.unwrap_or(std::cmp::Ordering::Equal),
)
});
}
pub fn len(&self) -> usize {
self.cues.len()
}
pub fn is_empty(&self) -> bool {
self.cues.is_empty()
}
pub fn duration(&self) -> f64 {
self.cues.iter().fold(0.0f64, |acc, c| acc.max(c.end))
}
pub fn active_at(&self, time: f64) -> Vec<&Cue> {
self.cues.iter().filter(|c| c.is_active_at(time)).collect()
}
pub fn cue_at(&self, time: f64) -> Option<&Cue> {
self.cues.iter().find(|c| c.is_active_at(time))
}
pub fn text_at(&self, time: f64) -> String {
let mut out = String::new();
for c in self.cues.iter().filter(|c| c.is_active_at(time)) {
if !out.is_empty() {
out.push('\n');
}
out.push_str(c.plain_text().trim_end_matches('\n'));
}
out
}
pub fn shift(&mut self, seconds: f64) {
for c in &mut self.cues {
c.start = (c.start + seconds).max(0.0);
c.end = (c.end + seconds).max(0.0);
}
}
pub fn scale(&mut self, factor: f64) {
for c in &mut self.cues {
c.start *= factor;
c.end *= factor;
}
}
pub fn parse_srt(text: &str) -> Result<Self, CaptionError> {
srt::parse(text)
}
pub fn parse_vtt(text: &str) -> Result<Self, CaptionError> {
vtt::parse(text)
}
pub fn parse(text: &str) -> Result<Self, CaptionError> {
if text
.trim_start_matches('\u{feff}')
.trim_start()
.starts_with("WEBVTT")
{
vtt::parse(text)
} else {
srt::parse(text)
}
}
pub fn to_srt(&self) -> String {
srt::write(self)
}
pub fn to_vtt(&self) -> String {
vtt::write(self)
}
pub fn to_format(&self, format: CaptionFormat) -> String {
match format {
CaptionFormat::Srt => self.to_srt(),
CaptionFormat::Vtt => self.to_vtt(),
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct CaptionStyle {
pub font_size: f32,
pub color: [u8; 4],
pub outline_color: [u8; 4],
pub outline_width: f32,
pub shadow_color: [u8; 4],
pub shadow_offset: [f32; 2],
pub background: [u8; 4],
pub padding: f32,
pub line_height: f32,
pub letter_spacing: f32,
pub align: CaptionAlign,
pub anchor: CaptionAnchor,
pub margin: f32,
pub max_width: f32,
}
impl Default for CaptionStyle {
fn default() -> Self {
Self {
font_size: 34.0,
color: [255, 255, 255, 255],
outline_color: [0, 0, 0, 255],
outline_width: 2.0,
shadow_color: [0, 0, 0, 0],
shadow_offset: [2.0, 2.0],
background: [0, 0, 0, 140],
padding: 10.0,
line_height: 1.25,
letter_spacing: 0.0,
align: CaptionAlign::Center,
anchor: CaptionAnchor::Bottom,
margin: 48.0,
max_width: 0.8,
}
}
}
impl CaptionStyle {
pub fn font_size(mut self, px: f32) -> Self {
self.font_size = px.max(1.0);
self
}
pub fn color(mut self, rgba: [u8; 4]) -> Self {
self.color = rgba;
self
}
pub fn outline(mut self, rgba: [u8; 4], width: f32) -> Self {
self.outline_color = rgba;
self.outline_width = width.max(0.0);
self
}
pub fn shadow(mut self, rgba: [u8; 4], dx: f32, dy: f32) -> Self {
self.shadow_color = rgba;
self.shadow_offset = [dx, dy];
self
}
pub fn background(mut self, rgba: [u8; 4]) -> Self {
self.background = rgba;
self
}
pub fn padding(mut self, px: f32) -> Self {
self.padding = px.max(0.0);
self
}
pub fn line_height(mut self, factor: f32) -> Self {
self.line_height = factor.max(0.1);
self
}
pub fn letter_spacing(mut self, px: f32) -> Self {
self.letter_spacing = px;
self
}
pub fn align(mut self, align: CaptionAlign) -> Self {
self.align = align;
self
}
pub fn anchor(mut self, anchor: CaptionAnchor) -> Self {
self.anchor = anchor;
self
}
pub fn margin(mut self, px: f32) -> Self {
self.margin = px.max(0.0);
self
}
pub fn max_width(mut self, fraction: f32) -> Self {
self.max_width = fraction.clamp(0.05, 1.0);
self
}
pub fn scaled(&self, factor: f32) -> Self {
let f = factor.max(0.01);
Self {
font_size: self.font_size * f,
outline_width: self.outline_width * f,
shadow_offset: [self.shadow_offset[0] * f, self.shadow_offset[1] * f],
padding: self.padding * f,
letter_spacing: self.letter_spacing * f,
margin: self.margin * f,
..self.clone()
}
}
pub fn for_height(&self, height: u32) -> Self {
self.scaled(height.max(1) as f32 / 1080.0)
}
}
pub fn iso639_2(language: &str) -> [u8; 3] {
let primary = language
.split(['-', '_'])
.next()
.unwrap_or("")
.to_ascii_lowercase();
let bytes = primary.as_bytes();
if bytes.len() == 3 && bytes.iter().all(|b| b.is_ascii_lowercase()) {
return [bytes[0], bytes[1], bytes[2]];
}
let mapped = match primary.as_str() {
"aa" => "aar",
"ab" => "abk",
"af" => "afr",
"am" => "amh",
"ar" => "ara",
"az" => "aze",
"be" => "bel",
"bg" => "bul",
"bn" => "ben",
"bs" => "bos",
"ca" => "cat",
"cs" => "ces",
"cy" => "cym",
"da" => "dan",
"de" => "deu",
"el" => "ell",
"en" => "eng",
"eo" => "epo",
"es" => "spa",
"et" => "est",
"eu" => "eus",
"fa" => "fas",
"fi" => "fin",
"fr" => "fra",
"ga" => "gle",
"gl" => "glg",
"he" => "heb",
"hi" => "hin",
"hr" => "hrv",
"hu" => "hun",
"hy" => "hye",
"id" => "ind",
"is" => "isl",
"it" => "ita",
"ja" => "jpn",
"ka" => "kat",
"kk" => "kaz",
"km" => "khm",
"kn" => "kan",
"ko" => "kor",
"lt" => "lit",
"lv" => "lav",
"mk" => "mkd",
"ml" => "mal",
"mn" => "mon",
"mr" => "mar",
"ms" => "msa",
"mt" => "mlt",
"my" => "mya",
"nb" => "nob",
"ne" => "nep",
"nl" => "nld",
"nn" => "nno",
"no" => "nor",
"pa" => "pan",
"pl" => "pol",
"ps" => "pus",
"pt" => "por",
"ro" => "ron",
"ru" => "rus",
"si" => "sin",
"sk" => "slk",
"sl" => "slv",
"sq" => "sqi",
"sr" => "srp",
"sv" => "swe",
"sw" => "swa",
"ta" => "tam",
"te" => "tel",
"th" => "tha",
"tl" => "tgl",
"tr" => "tur",
"uk" => "ukr",
"ur" => "urd",
"uz" => "uzb",
"vi" => "vie",
"zh" => "zho",
"zu" => "zul",
_ => "und",
};
let b = mapped.as_bytes();
[b[0], b[1], b[2]]
}
pub(crate) fn format_timestamp(seconds: f64, millis_sep: char) -> String {
let total_ms = (seconds.max(0.0) * 1000.0).round() as u64;
let ms = total_ms % 1000;
let total_s = total_ms / 1000;
let s = total_s % 60;
let m = (total_s / 60) % 60;
let h = total_s / 3600;
format!("{h:02}:{m:02}:{s:02}{millis_sep}{ms:03}")
}
pub(crate) fn parse_timestamp(text: &str) -> Option<f64> {
let text = text.trim();
if text.is_empty() {
return None;
}
let (clock, frac) = match text.rfind([',', '.']) {
Some(i) => (&text[..i], &text[i + 1..]),
None => (text, ""),
};
if !frac.is_empty() && !frac.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
let mut seconds = 0f64;
let mut parts = 0;
for part in clock.split(':') {
if part.is_empty() || !part.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
seconds = seconds * 60.0 + part.parse::<f64>().ok()?;
parts += 1;
if parts > 3 {
return None;
}
}
if parts == 0 {
return None;
}
if !frac.is_empty() {
let mut digits = frac.to_string();
digits.truncate(3);
while digits.len() < 3 {
digits.push('0');
}
seconds += digits.parse::<f64>().ok()? / 1000.0;
}
Some(seconds)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn timestamps_round_trip() {
assert_eq!(parse_timestamp("00:00:01,500"), Some(1.5));
assert_eq!(parse_timestamp("00:00:01.500"), Some(1.5));
assert_eq!(parse_timestamp("01:02:03,004"), Some(3723.004));
assert_eq!(parse_timestamp("02:03.250"), Some(123.25));
assert_eq!(parse_timestamp("00:00:01,5"), Some(1.5));
assert_eq!(parse_timestamp("bogus"), None);
assert_eq!(parse_timestamp("00:xx:01,500"), None);
assert_eq!(format_timestamp(3723.004, ','), "01:02:03,004");
assert_eq!(format_timestamp(1.5, '.'), "00:00:01.500");
assert_eq!(format_timestamp(-4.0, ','), "00:00:00,000");
}
#[test]
fn cues_stay_sorted_and_lookup_by_time() {
let track = CaptionTrack::new()
.cue(4.0, 6.0, "third")
.cue(0.0, 2.0, "first")
.cue(2.0, 4.0, "second");
let order: Vec<&str> = track.cues.iter().map(|c| c.text.as_str()).collect();
assert_eq!(order, ["first", "second", "third"]);
assert_eq!(track.cue_at(0.0).unwrap().text, "first");
assert_eq!(track.cue_at(2.0).unwrap().text, "second");
assert!(track.cue_at(6.0).is_none());
assert_eq!(track.duration(), 6.0);
}
#[test]
fn overlapping_cues_all_report_active() {
let track = CaptionTrack::new()
.cue(0.0, 4.0, "speaker one")
.cue(1.0, 3.0, "speaker two");
assert_eq!(track.active_at(2.0).len(), 2);
assert_eq!(track.text_at(2.0), "speaker one\nspeaker two");
assert_eq!(track.text_at(3.5), "speaker one");
assert_eq!(track.text_at(9.0), "");
}
#[test]
fn markup_and_entities_are_stripped() {
let cue = Cue::new(
0.0,
1.0,
"<i>Ich</i> & <c.yellow>du</c> {\\an8}<v Bob>hi",
);
assert_eq!(cue.plain_text(), "Ich & du hi");
assert_eq!(strip_markup("Tom & Jerry"), "Tom & Jerry");
assert_eq!(strip_markup("a <b> c"), "a <b> c");
assert_eq!(strip_markup("x y"), "x y");
}
#[test]
fn shift_and_scale_retime_the_track() {
let mut track = CaptionTrack::new().cue(1.0, 2.0, "a").cue(10.0, 11.0, "b");
track.shift(-2.0);
assert_eq!(track.cues[0].start, 0.0); assert_eq!(track.cues[1].start, 8.0);
track.scale(0.5);
assert_eq!(track.cues[1].start, 4.0);
}
#[test]
fn style_scaling_is_proportional() {
let base = CaptionStyle::default();
let half = base.scaled(0.5);
assert_eq!(half.font_size, base.font_size * 0.5);
assert_eq!(half.margin, base.margin * 0.5);
assert_eq!(half.padding, base.padding * 0.5);
assert_eq!(half.color, base.color);
assert_eq!(half.max_width, base.max_width);
}
#[test]
fn format_detection_from_path() {
assert_eq!(
CaptionFormat::from_path("a/b.SRT"),
Some(CaptionFormat::Srt)
);
assert_eq!(CaptionFormat::from_path("x.vtt"), Some(CaptionFormat::Vtt));
assert_eq!(CaptionFormat::from_path("x.mp4"), None);
}
}