1pub mod contrast;
20pub mod legibility;
21pub mod srt;
22pub mod vtt;
23
24#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
26pub enum CaptionAlign {
27 Left,
29 #[default]
31 Center,
32 Right,
34}
35
36#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
38pub enum CaptionAnchor {
39 Top,
41 Middle,
43 #[default]
45 Bottom,
46}
47
48#[derive(Clone, Copy, Debug, PartialEq, Eq)]
50pub enum CaptionFormat {
51 Srt,
53 Vtt,
55}
56
57impl CaptionFormat {
58 pub fn extension(self) -> &'static str {
60 match self {
61 CaptionFormat::Srt => "srt",
62 CaptionFormat::Vtt => "vtt",
63 }
64 }
65
66 pub fn mime_type(self) -> &'static str {
68 match self {
69 CaptionFormat::Srt => "application/x-subrip",
70 CaptionFormat::Vtt => "text/vtt",
71 }
72 }
73
74 pub fn from_path(path: &str) -> Option<Self> {
76 let ext = path.rsplit('.').next()?.to_ascii_lowercase();
77 match ext.as_str() {
78 "srt" => Some(CaptionFormat::Srt),
79 "vtt" | "webvtt" => Some(CaptionFormat::Vtt),
80 _ => None,
81 }
82 }
83}
84
85#[derive(Clone, Debug, PartialEq, Eq)]
87pub enum CaptionError {
88 BadTimestamp {
90 line: usize,
92 text: String,
94 },
95 MissingTiming {
97 line: usize,
99 },
100 Empty,
102 NotRecognized,
104}
105
106impl std::fmt::Display for CaptionError {
107 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
108 match self {
109 CaptionError::BadTimestamp { line, text } => {
110 write!(f, "line {line}: malformed cue timing {text:?}")
111 }
112 CaptionError::MissingTiming { line } => {
113 write!(f, "line {line}: cue block has no \"-->\" timing line")
114 }
115 CaptionError::Empty => write!(f, "no cues found"),
116 CaptionError::NotRecognized => write!(f, "input is not SubRip or WebVTT"),
117 }
118 }
119}
120impl std::error::Error for CaptionError {}
121
122#[derive(Clone, Debug, PartialEq)]
128pub struct Cue {
129 pub id: Option<String>,
132 pub start: f64,
134 pub end: f64,
136 pub text: String,
138 pub align: Option<CaptionAlign>,
140 pub line: Option<f32>,
143 pub position: Option<f32>,
146}
147
148impl Cue {
149 pub fn new(start: f64, end: f64, text: impl Into<String>) -> Self {
151 Self {
152 id: None,
153 start,
154 end,
155 text: text.into(),
156 align: None,
157 line: None,
158 position: None,
159 }
160 }
161
162 pub fn id(mut self, id: impl Into<String>) -> Self {
164 self.id = Some(id.into());
165 self
166 }
167
168 pub fn align(mut self, align: CaptionAlign) -> Self {
170 self.align = Some(align);
171 self
172 }
173
174 pub fn at_line(mut self, line: f32) -> Self {
176 self.line = Some(line);
177 self
178 }
179
180 pub fn at_position(mut self, position: f32) -> Self {
182 self.position = Some(position);
183 self
184 }
185
186 pub fn duration(&self) -> f64 {
188 (self.end - self.start).max(0.0)
189 }
190
191 pub fn is_active_at(&self, time: f64) -> bool {
194 time >= self.start && time < self.end
195 }
196
197 pub fn plain_text(&self) -> String {
204 strip_markup(&self.text)
205 }
206}
207
208pub fn strip_markup(text: &str) -> String {
210 let mut out = String::with_capacity(text.len());
211 let mut chars = text.chars().peekable();
212 while let Some(c) = chars.next() {
213 match c {
214 '<' => {
216 for t in chars.by_ref() {
217 if t == '>' {
218 break;
219 }
220 }
221 }
222 '{' if matches!(chars.peek(), Some('\\')) => {
224 for t in chars.by_ref() {
225 if t == '}' {
226 break;
227 }
228 }
229 }
230 '&' => {
231 let mut name = String::new();
232 let mut closed = false;
233 while let Some(&t) = chars.peek() {
235 if t == ';' {
236 chars.next();
237 closed = true;
238 break;
239 }
240 if !t.is_ascii_alphanumeric() && t != '#' || name.len() > 8 {
241 break;
242 }
243 name.push(t);
244 chars.next();
245 }
246 match (closed, name.as_str()) {
247 (true, "amp") => out.push('&'),
248 (true, "lt") => out.push('<'),
249 (true, "gt") => out.push('>'),
250 (true, "quot") => out.push('"'),
251 (true, "apos") => out.push('\''),
252 (true, "nbsp") => out.push(' '),
253 (true, "lrm") | (true, "rlm") => {}
255 _ => {
256 out.push('&');
257 out.push_str(&name);
258 if closed {
259 out.push(';');
260 }
261 }
262 }
263 }
264 _ => out.push(c),
265 }
266 }
267 out
268}
269
270#[derive(Clone, Debug, Default, PartialEq)]
283pub struct CaptionTrack {
284 pub cues: Vec<Cue>,
286 pub language: String,
288 pub label: String,
290}
291
292impl CaptionTrack {
293 pub fn new() -> Self {
295 Self::default()
296 }
297
298 pub fn language(mut self, language: impl Into<String>) -> Self {
300 self.language = language.into();
301 self
302 }
303
304 pub fn label(mut self, label: impl Into<String>) -> Self {
306 self.label = label.into();
307 self
308 }
309
310 pub fn cue(mut self, start: f64, end: f64, text: impl Into<String>) -> Self {
312 self.push(Cue::new(start, end, text));
313 self
314 }
315
316 pub fn push(&mut self, cue: Cue) {
318 let at = self
319 .cues
320 .iter()
321 .rposition(|c| c.start <= cue.start)
322 .map(|i| i + 1)
323 .unwrap_or(0);
324 self.cues.insert(at, cue);
325 }
326
327 pub fn sort(&mut self) {
330 self.cues.sort_by(|a, b| {
331 a.start
332 .partial_cmp(&b.start)
333 .unwrap_or(std::cmp::Ordering::Equal)
334 .then(
335 a.end
336 .partial_cmp(&b.end)
337 .unwrap_or(std::cmp::Ordering::Equal),
338 )
339 });
340 }
341
342 pub fn len(&self) -> usize {
344 self.cues.len()
345 }
346
347 pub fn is_empty(&self) -> bool {
349 self.cues.is_empty()
350 }
351
352 pub fn duration(&self) -> f64 {
354 self.cues.iter().fold(0.0f64, |acc, c| acc.max(c.end))
355 }
356
357 pub fn active_at(&self, time: f64) -> Vec<&Cue> {
359 self.cues.iter().filter(|c| c.is_active_at(time)).collect()
360 }
361
362 pub fn cue_at(&self, time: f64) -> Option<&Cue> {
365 self.cues.iter().find(|c| c.is_active_at(time))
366 }
367
368 pub fn text_at(&self, time: f64) -> String {
371 let mut out = String::new();
372 for c in self.cues.iter().filter(|c| c.is_active_at(time)) {
373 if !out.is_empty() {
374 out.push('\n');
375 }
376 out.push_str(c.plain_text().trim_end_matches('\n'));
377 }
378 out
379 }
380
381 pub fn shift(&mut self, seconds: f64) {
384 for c in &mut self.cues {
385 c.start = (c.start + seconds).max(0.0);
386 c.end = (c.end + seconds).max(0.0);
387 }
388 }
389
390 pub fn scale(&mut self, factor: f64) {
393 for c in &mut self.cues {
394 c.start *= factor;
395 c.end *= factor;
396 }
397 }
398
399 pub fn parse_srt(text: &str) -> Result<Self, CaptionError> {
401 srt::parse(text)
402 }
403
404 pub fn parse_vtt(text: &str) -> Result<Self, CaptionError> {
406 vtt::parse(text)
407 }
408
409 pub fn parse(text: &str) -> Result<Self, CaptionError> {
411 if text
412 .trim_start_matches('\u{feff}')
413 .trim_start()
414 .starts_with("WEBVTT")
415 {
416 vtt::parse(text)
417 } else {
418 srt::parse(text)
419 }
420 }
421
422 pub fn to_srt(&self) -> String {
424 srt::write(self)
425 }
426
427 pub fn to_vtt(&self) -> String {
429 vtt::write(self)
430 }
431
432 pub fn to_format(&self, format: CaptionFormat) -> String {
434 match format {
435 CaptionFormat::Srt => self.to_srt(),
436 CaptionFormat::Vtt => self.to_vtt(),
437 }
438 }
439}
440
441#[derive(Clone, Debug, PartialEq)]
446pub struct CaptionStyle {
447 pub font_size: f32,
449 pub color: [u8; 4],
451 pub outline_color: [u8; 4],
453 pub outline_width: f32,
455 pub shadow_color: [u8; 4],
457 pub shadow_offset: [f32; 2],
459 pub background: [u8; 4],
461 pub padding: f32,
463 pub line_height: f32,
465 pub letter_spacing: f32,
467 pub align: CaptionAlign,
469 pub anchor: CaptionAnchor,
471 pub margin: f32,
474 pub max_width: f32,
476}
477
478impl Default for CaptionStyle {
479 fn default() -> Self {
482 Self {
483 font_size: 34.0,
484 color: [255, 255, 255, 255],
485 outline_color: [0, 0, 0, 255],
486 outline_width: 2.0,
487 shadow_color: [0, 0, 0, 0],
488 shadow_offset: [2.0, 2.0],
489 background: [0, 0, 0, 140],
490 padding: 10.0,
491 line_height: 1.25,
492 letter_spacing: 0.0,
493 align: CaptionAlign::Center,
494 anchor: CaptionAnchor::Bottom,
495 margin: 48.0,
496 max_width: 0.8,
497 }
498 }
499}
500
501impl CaptionStyle {
502 pub fn font_size(mut self, px: f32) -> Self {
504 self.font_size = px.max(1.0);
505 self
506 }
507
508 pub fn color(mut self, rgba: [u8; 4]) -> Self {
510 self.color = rgba;
511 self
512 }
513
514 pub fn outline(mut self, rgba: [u8; 4], width: f32) -> Self {
516 self.outline_color = rgba;
517 self.outline_width = width.max(0.0);
518 self
519 }
520
521 pub fn shadow(mut self, rgba: [u8; 4], dx: f32, dy: f32) -> Self {
523 self.shadow_color = rgba;
524 self.shadow_offset = [dx, dy];
525 self
526 }
527
528 pub fn background(mut self, rgba: [u8; 4]) -> Self {
530 self.background = rgba;
531 self
532 }
533
534 pub fn padding(mut self, px: f32) -> Self {
536 self.padding = px.max(0.0);
537 self
538 }
539
540 pub fn line_height(mut self, factor: f32) -> Self {
542 self.line_height = factor.max(0.1);
543 self
544 }
545
546 pub fn letter_spacing(mut self, px: f32) -> Self {
548 self.letter_spacing = px;
549 self
550 }
551
552 pub fn align(mut self, align: CaptionAlign) -> Self {
554 self.align = align;
555 self
556 }
557
558 pub fn anchor(mut self, anchor: CaptionAnchor) -> Self {
560 self.anchor = anchor;
561 self
562 }
563
564 pub fn margin(mut self, px: f32) -> Self {
566 self.margin = px.max(0.0);
567 self
568 }
569
570 pub fn max_width(mut self, fraction: f32) -> Self {
572 self.max_width = fraction.clamp(0.05, 1.0);
573 self
574 }
575
576 pub fn scaled(&self, factor: f32) -> Self {
586 let f = factor.max(0.01);
587 Self {
588 font_size: self.font_size * f,
589 outline_width: self.outline_width * f,
590 shadow_offset: [self.shadow_offset[0] * f, self.shadow_offset[1] * f],
591 padding: self.padding * f,
592 letter_spacing: self.letter_spacing * f,
593 margin: self.margin * f,
594 ..self.clone()
595 }
596 }
597
598 pub fn for_height(&self, height: u32) -> Self {
607 self.scaled(height.max(1) as f32 / 1080.0)
608 }
609}
610
611pub fn iso639_2(language: &str) -> [u8; 3] {
624 let primary = language
625 .split(['-', '_'])
626 .next()
627 .unwrap_or("")
628 .to_ascii_lowercase();
629 let bytes = primary.as_bytes();
630 if bytes.len() == 3 && bytes.iter().all(|b| b.is_ascii_lowercase()) {
631 return [bytes[0], bytes[1], bytes[2]];
632 }
633 let mapped = match primary.as_str() {
634 "aa" => "aar",
635 "ab" => "abk",
636 "af" => "afr",
637 "am" => "amh",
638 "ar" => "ara",
639 "az" => "aze",
640 "be" => "bel",
641 "bg" => "bul",
642 "bn" => "ben",
643 "bs" => "bos",
644 "ca" => "cat",
645 "cs" => "ces",
646 "cy" => "cym",
647 "da" => "dan",
648 "de" => "deu",
649 "el" => "ell",
650 "en" => "eng",
651 "eo" => "epo",
652 "es" => "spa",
653 "et" => "est",
654 "eu" => "eus",
655 "fa" => "fas",
656 "fi" => "fin",
657 "fr" => "fra",
658 "ga" => "gle",
659 "gl" => "glg",
660 "he" => "heb",
661 "hi" => "hin",
662 "hr" => "hrv",
663 "hu" => "hun",
664 "hy" => "hye",
665 "id" => "ind",
666 "is" => "isl",
667 "it" => "ita",
668 "ja" => "jpn",
669 "ka" => "kat",
670 "kk" => "kaz",
671 "km" => "khm",
672 "kn" => "kan",
673 "ko" => "kor",
674 "lt" => "lit",
675 "lv" => "lav",
676 "mk" => "mkd",
677 "ml" => "mal",
678 "mn" => "mon",
679 "mr" => "mar",
680 "ms" => "msa",
681 "mt" => "mlt",
682 "my" => "mya",
683 "nb" => "nob",
684 "ne" => "nep",
685 "nl" => "nld",
686 "nn" => "nno",
687 "no" => "nor",
688 "pa" => "pan",
689 "pl" => "pol",
690 "ps" => "pus",
691 "pt" => "por",
692 "ro" => "ron",
693 "ru" => "rus",
694 "si" => "sin",
695 "sk" => "slk",
696 "sl" => "slv",
697 "sq" => "sqi",
698 "sr" => "srp",
699 "sv" => "swe",
700 "sw" => "swa",
701 "ta" => "tam",
702 "te" => "tel",
703 "th" => "tha",
704 "tl" => "tgl",
705 "tr" => "tur",
706 "uk" => "ukr",
707 "ur" => "urd",
708 "uz" => "uzb",
709 "vi" => "vie",
710 "zh" => "zho",
711 "zu" => "zul",
712 _ => "und",
713 };
714 let b = mapped.as_bytes();
715 [b[0], b[1], b[2]]
716}
717
718pub(crate) fn format_timestamp(seconds: f64, millis_sep: char) -> String {
720 let total_ms = (seconds.max(0.0) * 1000.0).round() as u64;
721 let ms = total_ms % 1000;
722 let total_s = total_ms / 1000;
723 let s = total_s % 60;
724 let m = (total_s / 60) % 60;
725 let h = total_s / 3600;
726 format!("{h:02}:{m:02}:{s:02}{millis_sep}{ms:03}")
727}
728
729pub(crate) fn parse_timestamp(text: &str) -> Option<f64> {
731 let text = text.trim();
732 if text.is_empty() {
733 return None;
734 }
735 let (clock, frac) = match text.rfind([',', '.']) {
737 Some(i) => (&text[..i], &text[i + 1..]),
738 None => (text, ""),
739 };
740 if !frac.is_empty() && !frac.bytes().all(|b| b.is_ascii_digit()) {
741 return None;
742 }
743 let mut seconds = 0f64;
744 let mut parts = 0;
745 for part in clock.split(':') {
746 if part.is_empty() || !part.bytes().all(|b| b.is_ascii_digit()) {
747 return None;
748 }
749 seconds = seconds * 60.0 + part.parse::<f64>().ok()?;
750 parts += 1;
751 if parts > 3 {
752 return None;
753 }
754 }
755 if parts == 0 {
756 return None;
757 }
758 if !frac.is_empty() {
759 let mut digits = frac.to_string();
761 digits.truncate(3);
762 while digits.len() < 3 {
763 digits.push('0');
764 }
765 seconds += digits.parse::<f64>().ok()? / 1000.0;
766 }
767 Some(seconds)
768}
769
770#[cfg(test)]
771mod tests {
772 use super::*;
773
774 #[test]
775 fn timestamps_round_trip() {
776 assert_eq!(parse_timestamp("00:00:01,500"), Some(1.5));
777 assert_eq!(parse_timestamp("00:00:01.500"), Some(1.5));
778 assert_eq!(parse_timestamp("01:02:03,004"), Some(3723.004));
779 assert_eq!(parse_timestamp("02:03.250"), Some(123.25));
780 assert_eq!(parse_timestamp("00:00:01,5"), Some(1.5));
781 assert_eq!(parse_timestamp("bogus"), None);
782 assert_eq!(parse_timestamp("00:xx:01,500"), None);
783 assert_eq!(format_timestamp(3723.004, ','), "01:02:03,004");
784 assert_eq!(format_timestamp(1.5, '.'), "00:00:01.500");
785 assert_eq!(format_timestamp(-4.0, ','), "00:00:00,000");
786 }
787
788 #[test]
789 fn cues_stay_sorted_and_lookup_by_time() {
790 let track = CaptionTrack::new()
791 .cue(4.0, 6.0, "third")
792 .cue(0.0, 2.0, "first")
793 .cue(2.0, 4.0, "second");
794 let order: Vec<&str> = track.cues.iter().map(|c| c.text.as_str()).collect();
795 assert_eq!(order, ["first", "second", "third"]);
796 assert_eq!(track.cue_at(0.0).unwrap().text, "first");
797 assert_eq!(track.cue_at(2.0).unwrap().text, "second");
799 assert!(track.cue_at(6.0).is_none());
800 assert_eq!(track.duration(), 6.0);
801 }
802
803 #[test]
804 fn overlapping_cues_all_report_active() {
805 let track = CaptionTrack::new()
806 .cue(0.0, 4.0, "speaker one")
807 .cue(1.0, 3.0, "speaker two");
808 assert_eq!(track.active_at(2.0).len(), 2);
809 assert_eq!(track.text_at(2.0), "speaker one\nspeaker two");
810 assert_eq!(track.text_at(3.5), "speaker one");
811 assert_eq!(track.text_at(9.0), "");
812 }
813
814 #[test]
815 fn markup_and_entities_are_stripped() {
816 let cue = Cue::new(
817 0.0,
818 1.0,
819 "<i>Ich</i> & <c.yellow>du</c> {\\an8}<v Bob>hi",
820 );
821 assert_eq!(cue.plain_text(), "Ich & du hi");
822 assert_eq!(strip_markup("Tom & Jerry"), "Tom & Jerry");
824 assert_eq!(strip_markup("a <b> c"), "a <b> c");
825 assert_eq!(strip_markup("x y"), "x y");
826 }
827
828 #[test]
829 fn shift_and_scale_retime_the_track() {
830 let mut track = CaptionTrack::new().cue(1.0, 2.0, "a").cue(10.0, 11.0, "b");
831 track.shift(-2.0);
832 assert_eq!(track.cues[0].start, 0.0); assert_eq!(track.cues[1].start, 8.0);
834 track.scale(0.5);
835 assert_eq!(track.cues[1].start, 4.0);
836 }
837
838 #[test]
839 fn style_scaling_is_proportional() {
840 let base = CaptionStyle::default();
841 let half = base.scaled(0.5);
842 assert_eq!(half.font_size, base.font_size * 0.5);
843 assert_eq!(half.margin, base.margin * 0.5);
844 assert_eq!(half.padding, base.padding * 0.5);
845 assert_eq!(half.color, base.color);
847 assert_eq!(half.max_width, base.max_width);
848 }
849
850 #[test]
851 fn format_detection_from_path() {
852 assert_eq!(
853 CaptionFormat::from_path("a/b.SRT"),
854 Some(CaptionFormat::Srt)
855 );
856 assert_eq!(CaptionFormat::from_path("x.vtt"), Some(CaptionFormat::Vtt));
857 assert_eq!(CaptionFormat::from_path("x.mp4"), None);
858 }
859}