1use std::cmp::Reverse;
23use std::collections::{BTreeSet, BinaryHeap};
24
25use crate::{
26 CaptionCue, MAX_CLIPS_PER_TRACK, MAX_PROJECT_JSON_BYTES, MAX_RUN_CLASSES,
27 MAX_TEXT_CONTENT_BYTES, MAX_TEXT_RUNS, MAX_TRACKS, RunTime, TextContent, TextRun,
28 valid_class_name,
29};
30use alpha2_time::{MediaTime, TICKS_PER_SECOND, TimeRange};
31
32pub const MAX_CAPTION_FILE_BYTES: usize = MAX_PROJECT_JSON_BYTES;
35
36pub const MAX_CAPTION_FILE_CUES: usize = 65_536;
39
40pub const MAX_CUE_BLOCK_BYTES: usize = 65_536;
42
43pub const MAX_CUE_BLOCK_LINES: usize = 1_024;
45
46pub const MAX_OPEN_TAGS: usize = 32;
48
49pub const MAX_HELD_CLASSES: usize = 64;
51
52#[derive(Clone, Debug, Default, PartialEq)]
54pub struct ImportedCaptions {
55 pub cues: Vec<CaptionCue>,
57 pub skipped: usize,
59 pub notes: ImportNotes,
61}
62
63#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
65pub struct ImportNotes {
66 pub extra_voices: usize,
69 pub dropped_timestamps: usize,
71 pub dropped_classes: usize,
74 pub flattened: usize,
77}
78
79#[derive(Clone, Copy, Debug, Eq, PartialEq)]
81#[non_exhaustive]
82pub enum CaptionImportError {
83 MissingWebVttHeader,
85 FileTooLarge {
87 bytes: usize,
89 maximum: usize,
91 },
92 TooManyCues {
94 maximum: usize,
96 },
97 TooManyRows {
100 rows: usize,
102 maximum: usize,
104 },
105}
106
107impl std::fmt::Display for CaptionImportError {
108 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
109 match self {
110 Self::MissingWebVttHeader => formatter.write_str("a WebVTT file begins with WEBVTT"),
111 Self::FileTooLarge { bytes, maximum } => write!(
112 formatter,
113 "the subtitle file is {bytes} bytes; at most {maximum} are read"
114 ),
115 Self::TooManyCues { maximum } => write!(
116 formatter,
117 "the subtitle file holds more than {maximum} cues"
118 ),
119 Self::TooManyRows { rows, maximum } => write!(
120 formatter,
121 "the captions need {rows} caption tracks; a project holds at most {maximum} tracks"
122 ),
123 }
124 }
125}
126
127impl std::error::Error for CaptionImportError {}
128
129const TICKS_PER_MILLISECOND: i64 = TICKS_PER_SECOND / 1_000;
130
131pub fn parse_srt(text: &str) -> Result<ImportedCaptions, CaptionImportError> {
137 check_file_size(text)?;
138 let mut imported = ImportedCaptions::default();
139 for block in Blocks::new(text) {
140 let Some(block) = block else {
141 imported.skipped += 1;
142 continue;
143 };
144 let mut lines = block.iter().copied();
145 let Some(mut first) = lines.next() else {
146 continue;
147 };
148 if !first.contains("-->") {
150 match lines.next() {
151 Some(line) if first.trim().chars().all(|c| c.is_ascii_digit()) => first = line,
152 _ => {
153 imported.skipped += 1;
154 continue;
155 }
156 }
157 }
158 let body = lines.collect::<Vec<_>>();
159 let range = timing(first);
160 let marked = range.map(|_| srt_markup(&body));
161 imported.read(range, marked)?;
162 }
163 imported.cues.sort_by_key(|cue| cue.timeline_range.start());
164 Ok(imported)
165}
166
167pub fn parse_webvtt(text: &str) -> Result<ImportedCaptions, CaptionImportError> {
174 check_file_size(text)?;
175 let text = text.strip_prefix('\u{feff}').unwrap_or(text);
176 let header_ok = text
177 .strip_prefix("WEBVTT")
178 .is_some_and(|rest| rest.is_empty() || rest.starts_with([' ', '\t', '\n', '\r']));
179 if !header_ok {
180 return Err(CaptionImportError::MissingWebVttHeader);
181 }
182 let mut imported = ImportedCaptions::default();
183 let mut blocks = Blocks::new(text);
184 let header = blocks.next().flatten().unwrap_or_default();
187 let cue_under_header = header
188 .iter()
189 .position(|line| line.contains("-->"))
190 .map(|start| Some(header[start..].to_vec()));
191 for block in cue_under_header.into_iter().chain(blocks) {
192 let Some(block) = block else {
193 imported.skipped += 1;
194 continue;
195 };
196 let first = block[0];
197 if ["NOTE", "STYLE", "REGION"].iter().any(|keyword| {
198 first
199 .strip_prefix(keyword)
200 .is_some_and(|rest| rest.is_empty() || rest.starts_with([' ', '\t']))
201 }) {
202 continue;
203 }
204 let (timing_line, body) = if first.contains("-->") {
206 (first, &block[1..])
207 } else if block.len() > 1 && block[1].contains("-->") {
208 (block[1], &block[2..])
209 } else {
210 imported.skipped += 1;
211 continue;
212 };
213 let range = timing(timing_line);
214 let marked = range.map(|range| vtt_markup(&body.join("\n"), range));
215 imported.read(range, marked)?;
216 }
217 imported.cues.sort_by_key(|cue| cue.timeline_range.start());
218 Ok(imported)
219}
220
221impl ImportedCaptions {
222 fn read(
225 &mut self,
226 range: Option<TimeRange>,
227 marked: Option<Marked>,
228 ) -> Result<(), CaptionImportError> {
229 let (Some(range), Some(marked)) = (range, marked) else {
230 self.skipped += 1;
231 return Ok(());
232 };
233 let Some(text) = cue_text(&marked.text) else {
234 self.skipped += 1;
235 return Ok(());
236 };
237 if self.cues.len() == MAX_CAPTION_FILE_CUES {
238 return Err(CaptionImportError::TooManyCues {
239 maximum: MAX_CAPTION_FILE_CUES,
240 });
241 }
242 let mut cue = CaptionCue::new(range, text);
243 let notes = &mut self.notes;
244 notes.extra_voices += marked.notes.extra_voices;
245 notes.dropped_timestamps += marked.notes.dropped_timestamps;
246 notes.dropped_classes += marked.notes.dropped_classes;
247 notes.flattened += marked.notes.flattened;
248 cue.speaker = marked.speaker;
249 if let Some(runs) = marked.runs.filter(|runs| !runs.is_empty()) {
250 cue.text = TextContent::Runs(runs);
251 }
252 self.cues.push(cue);
253 Ok(())
254 }
255}
256
257fn check_file_size(text: &str) -> Result<(), CaptionImportError> {
258 if text.len() > MAX_CAPTION_FILE_BYTES {
259 return Err(CaptionImportError::FileTooLarge {
260 bytes: text.len(),
261 maximum: MAX_CAPTION_FILE_BYTES,
262 });
263 }
264 Ok(())
265}
266
267pub fn caption_rows(cues: &[CaptionCue]) -> Result<Vec<Vec<CaptionCue>>, CaptionImportError> {
275 let mut sorted = cues.to_vec();
276 sorted.sort_by_key(|cue| cue.timeline_range.start());
277 let mut rows: Vec<Vec<CaptionCue>> = Vec::new();
278 let mut ended = BTreeSet::<usize>::new();
281 let mut ending = BinaryHeap::<Reverse<(MediaTime, usize)>>::new();
282 for cue in sorted {
283 let start = cue.timeline_range.start();
284 while let Some(&Reverse((end, row))) = ending.peek()
285 && end <= start
286 {
287 ending.pop();
288 ended.insert(row);
289 }
290 let row = ended.pop_first().unwrap_or_else(|| {
291 rows.push(Vec::new());
292 rows.len() - 1
293 });
294 let end = cue.timeline_range.end();
295 rows[row].push(cue);
296 if rows[row].len() < MAX_CLIPS_PER_TRACK {
297 ending.push(Reverse((end, row)));
298 }
299 }
300 if rows.len() > MAX_TRACKS {
301 return Err(CaptionImportError::TooManyRows {
302 rows: rows.len(),
303 maximum: MAX_TRACKS,
304 });
305 }
306 Ok(rows)
307}
308
309struct Blocks<'a> {
312 lines: Lines<'a>,
313}
314
315impl<'a> Blocks<'a> {
316 fn new(text: &'a str) -> Self {
317 Self {
318 lines: Lines {
319 text: text.strip_prefix('\u{feff}').unwrap_or(text),
320 at: 0,
321 pending_blanks: 0,
322 done: false,
323 },
324 }
325 }
326}
327
328impl<'a> Iterator for Blocks<'a> {
329 type Item = Option<Vec<&'a str>>;
330
331 fn next(&mut self) -> Option<Self::Item> {
332 let mut block = Vec::new();
333 let mut bytes = 0_usize;
334 let mut oversized = false;
335 for line in self.lines.by_ref() {
336 if line.trim().is_empty() {
337 if oversized || !block.is_empty() {
338 break;
339 }
340 continue;
341 }
342 if oversized {
343 continue;
344 }
345 bytes += line.len() + 1;
346 if bytes > MAX_CUE_BLOCK_BYTES || block.len() == MAX_CUE_BLOCK_LINES {
347 oversized = true;
348 block = Vec::new();
349 continue;
350 }
351 block.push(line);
352 }
353 if oversized {
354 Some(None)
355 } else {
356 (!block.is_empty()).then_some(Some(block))
357 }
358 }
359}
360
361struct Lines<'a> {
364 text: &'a str,
365 at: usize,
366 pending_blanks: usize,
368 done: bool,
369}
370
371impl<'a> Iterator for Lines<'a> {
372 type Item = &'a str;
373
374 fn next(&mut self) -> Option<&'a str> {
375 if self.pending_blanks > 0 {
376 self.pending_blanks -= 1;
377 return Some("");
378 }
379 if self.done {
380 return None;
381 }
382 let bytes = self.text.as_bytes();
383 let start = self.at;
384 let Some(end) = bytes[start..]
385 .iter()
386 .position(|&byte| matches!(byte, b'\n' | b'\r'))
387 .map(|offset| start + offset)
388 else {
389 self.done = true;
390 return Some(&self.text[start..]);
391 };
392 if bytes[end] == b'\n' {
393 self.at = end + 1;
394 } else {
395 let returns = bytes[end..]
396 .iter()
397 .take_while(|&&byte| byte == b'\r')
398 .count();
399 self.at = end + returns;
400 if bytes.get(self.at) == Some(&b'\n') {
401 self.at += 1;
402 } else {
403 self.pending_blanks = returns - 1;
404 }
405 }
406 Some(&self.text[start..end])
407 }
408}
409
410fn timing(line: &str) -> Option<TimeRange> {
412 let (start, rest) = line.split_once("-->")?;
413 let end = rest.split_whitespace().next()?;
414 let (start, end) = (timestamp(start.trim())?, timestamp(end)?);
415 TimeRange::new(start, end)
416 .ok()
417 .filter(|range| !range.is_empty())
418}
419
420fn timestamp(text: &str) -> Option<MediaTime> {
423 let (clock, millis) = text.split_once([',', '.'])?;
424 if millis.len() != 3 || !millis.bytes().all(|byte| byte.is_ascii_digit()) {
425 return None;
426 }
427 let fields = clock.split(':').collect::<Vec<_>>();
428 let number = |field: &str| {
429 (!field.is_empty() && field.bytes().all(|byte| byte.is_ascii_digit()))
430 .then(|| field.parse::<i64>().ok())
431 .flatten()
432 };
433 let (hours, minutes, seconds) = match fields.as_slice() {
434 [hours, minutes, seconds] => (number(hours)?, number(minutes)?, number(seconds)?),
435 [minutes, seconds] => (0, number(minutes)?, number(seconds)?),
436 _ => return None,
437 };
438 if minutes > 59 || seconds > 59 {
439 return None;
440 }
441 let milliseconds = ((hours.checked_mul(60)?.checked_add(minutes)?)
442 .checked_mul(60)?
443 .checked_add(seconds)?)
444 .checked_mul(1_000)?
445 .checked_add(millis.parse::<i64>().ok()?)?;
446 let ticks = milliseconds.checked_mul(TICKS_PER_MILLISECOND)?;
447 (ticks <= alpha2_time::MAX_SERIALIZED_TICKS).then(|| MediaTime::from_ticks(ticks))
448}
449
450fn cue_text(text: &str) -> Option<String> {
452 let text = text.trim_matches('\n').to_owned();
453 (!text.trim().is_empty() && text.len() <= MAX_TEXT_CONTENT_BYTES).then_some(text)
454}
455
456fn decode_references(text: &str) -> String {
461 let mut output = String::with_capacity(text.len());
462 let mut rest = text;
463 while let Some(start) = rest.find('&') {
464 output.push_str(&rest[..start]);
465 rest = &rest[start + 1..];
466 let length = rest
467 .bytes()
468 .take_while(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'#' | b'+'))
469 .count();
470 let decoded = (rest.as_bytes().get(length) == Some(&b';'))
471 .then(|| reference(&rest[..length]))
472 .flatten();
473 match decoded {
474 Some(character) => {
475 output.push(character);
476 rest = &rest[length + 1..];
477 }
478 None => output.push('&'),
479 }
480 }
481 output.push_str(rest);
482 output
483}
484
485fn reference(name: &str) -> Option<char> {
487 match name {
488 "amp" => Some('&'),
489 "lt" => Some('<'),
490 "gt" => Some('>'),
491 "nbsp" => Some('\u{a0}'),
492 "lrm" => Some('\u{200e}'),
493 "rlm" => Some('\u{200f}'),
494 _ => name
495 .strip_prefix("#x")
496 .or_else(|| name.strip_prefix("#X"))
497 .and_then(|hex| u32::from_str_radix(hex, 16).ok())
498 .or_else(|| name.strip_prefix('#').and_then(|dec| dec.parse().ok()))
499 .and_then(char::from_u32),
500 }
501}
502
503struct Marked {
506 text: String,
507 speaker: Option<String>,
508 runs: Option<Vec<TextRun>>,
509 notes: ImportNotes,
510}
511
512#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
515struct Emphasis {
516 bold: bool,
517 italic: bool,
518 underline: bool,
519}
520
521impl Emphasis {
522 fn of<'n>(names: impl IntoIterator<Item = &'n str>) -> Self {
523 let mut emphasis = Self::default();
524 for name in names {
525 match name {
526 "b" => emphasis.bold = true,
527 "i" => emphasis.italic = true,
528 "u" => emphasis.underline = true,
529 _ => {}
530 }
531 }
532 emphasis
533 }
534
535 fn of_open(open: &[String]) -> Self {
536 Self::of(open.iter().map(String::as_str))
537 }
538
539 fn style(self) -> Option<crate::TextRunStyle> {
540 (self != Self::default()).then(|| crate::TextRunStyle {
541 font_weight: self.bold.then_some(700),
542 font_style: self.italic.then_some(crate::FontStyle::Italic),
543 underline: self.underline.then_some(true),
544 ..crate::TextRunStyle::default()
545 })
546 }
547}
548
549struct Runs {
553 text: String,
554 pieces: Vec<(String, Vec<String>, usize, Emphasis)>,
555 tracking: bool,
556 notes: ImportNotes,
557}
558
559impl Runs {
560 fn new() -> Self {
561 Self {
562 text: String::new(),
563 pieces: Vec::new(),
564 tracking: true,
565 notes: ImportNotes::default(),
566 }
567 }
568
569 fn flatten(&mut self) {
571 if self.tracking {
572 self.tracking = false;
573 self.pieces = Vec::new();
574 self.notes.flattened += 1;
575 }
576 }
577
578 fn push(&mut self, text: &str, classes: &[String], segment: usize, emphasis: Emphasis) {
579 self.text.push_str(text);
580 if !self.tracking {
581 return;
582 }
583 let text = if self.pieces.is_empty() {
585 text.trim_start_matches('\n')
586 } else {
587 text
588 };
589 if text.is_empty() {
590 return;
591 }
592 match self.pieces.last_mut() {
593 Some((held, open, at, emphasized))
594 if open.as_slice() == classes && *at == segment && *emphasized == emphasis =>
595 {
596 held.push_str(text);
597 }
598 _ => {
599 if self.pieces.len() > MAX_TEXT_RUNS + 1 {
601 self.flatten();
602 return;
603 }
604 self.pieces
605 .push((text.to_owned(), classes.to_vec(), segment, emphasis));
606 }
607 }
608 }
609
610 fn finish(mut self, speaker: Option<String>, bounds: &[i64]) -> Marked {
614 while let Some(last) = self.pieces.last_mut() {
615 let kept = last.0.trim_end_matches('\n').len();
616 last.0.truncate(kept);
617 if last.0.is_empty() {
618 self.pieces.pop();
619 } else {
620 break;
621 }
622 }
623 if self.pieces.len() > MAX_TEXT_RUNS {
624 self.flatten();
625 }
626 let timed = bounds.len() > 2;
627 let runs = (self.tracking
628 && (timed
629 || self
630 .pieces
631 .iter()
632 .any(|(_, classes, ..)| !classes.is_empty())))
633 .then(|| {
634 self.pieces
635 .into_iter()
636 .map(|(text, mut class, segment, emphasis)| {
637 if class.len() > MAX_RUN_CLASSES {
638 self.notes.dropped_classes += class.len() - MAX_RUN_CLASSES;
639 class.truncate(MAX_RUN_CLASSES);
640 }
641 TextRun {
642 text,
643 class,
644 time: timed.then(|| RunTime {
645 start: MediaTime(bounds[segment]),
646 end: MediaTime(bounds[segment + 1]),
647 }),
648 style: emphasis.style(),
649 }
650 })
651 .collect()
652 });
653 Marked {
654 text: self.text,
655 speaker,
656 runs,
657 notes: self.notes,
658 }
659 }
660}
661
662fn tag_classes(names: &str, notes: &mut ImportNotes) -> Vec<String> {
665 names
666 .split('.')
667 .filter(|name| !name.is_empty())
668 .filter_map(|name| {
669 if valid_class_name(name) {
670 Some(name.to_owned())
671 } else {
672 notes.dropped_classes += 1;
673 None
674 }
675 })
676 .collect()
677}
678
679fn vtt_markup(body: &str, range: TimeRange) -> Marked {
684 let start = range.start().ticks();
685 let duration = range.duration().map_or(0, MediaTime::ticks);
686 let mut runs = Runs::new();
687 let mut speaker = None;
688 let mut open: Vec<(&str, usize)> = Vec::new();
690 let mut classes: Vec<String> = Vec::new();
692 let mut bounds = vec![0_i64];
693 let mut rest = body;
694 loop {
695 let emphasis = Emphasis::of(open.iter().map(|(name, _)| *name));
696 let Some(at) = rest.find('<') else {
697 runs.push(
698 &decode_references(rest),
699 &classes,
700 bounds.len() - 1,
701 emphasis,
702 );
703 break;
704 };
705 runs.push(
706 &decode_references(&rest[..at]),
707 &classes,
708 bounds.len() - 1,
709 emphasis,
710 );
711 let Some(end) = rest[at..].find('>') else {
712 break;
713 };
714 let tag = &rest[at + 1..at + end];
715 rest = &rest[at + end + 1..];
716 if let Some(name) = tag.strip_prefix('/') {
717 let name = name.trim();
718 if let Some(index) = open.iter().rposition(|(open, _)| *open == name) {
719 classes.truncate(open[index].1);
720 open.truncate(index);
721 }
722 continue;
723 }
724 if tag.starts_with(|character: char| character.is_ascii_digit()) {
725 match timestamp(tag.trim()) {
727 Some(time)
728 if time.ticks() - start > *bounds.last().unwrap_or(&0)
729 && time.ticks() - start < duration =>
730 {
731 if runs.tracking {
732 bounds.push(time.ticks() - start);
733 }
734 }
735 _ => runs.notes.dropped_timestamps += 1,
736 }
737 continue;
738 }
739 let (head, annotation) = tag
741 .split_once([' ', '\t'])
742 .map_or((tag, ""), |(head, annotation)| (head, annotation.trim()));
743 let (name, names) = head.split_once('.').unwrap_or((head, ""));
744 let given = match name {
745 "v" => {
746 if speaker.is_none() && !annotation.is_empty() {
747 speaker = Some(annotation.to_owned());
748 } else if !annotation.is_empty() {
749 runs.notes.extra_voices += 1;
750 }
751 let mut given = vec!["voice".to_owned()];
752 given.extend(tag_classes(names, &mut runs.notes));
753 given
754 }
755 "c" => tag_classes(names, &mut runs.notes),
756 "b" | "i" | "u" => {
757 let mut given = vec![name.to_owned()];
758 given.extend(tag_classes(names, &mut runs.notes));
759 given
760 }
761 _ => Vec::new(),
762 };
763 if !runs.tracking {
764 continue;
765 }
766 if open.len() == MAX_OPEN_TAGS {
767 runs.flatten();
768 continue;
769 }
770 open.push((name, classes.len()));
771 for class in given {
772 if !classes.contains(&class) {
773 if classes.len() == MAX_HELD_CLASSES {
774 runs.flatten();
775 break;
776 }
777 classes.push(class);
778 }
779 }
780 }
781 bounds.push(duration);
782 let speaker = speaker.filter(|speaker| speaker.len() <= crate::MAX_CAPTION_NAME_BYTES);
783 runs.finish(speaker, &bounds)
784}
785
786fn srt_markup(body: &[&str]) -> Marked {
789 let mut runs = Runs::new();
790 let mut open: Vec<String> = Vec::new();
791 for (index, line) in body.iter().enumerate() {
792 if index > 0 {
793 runs.push("\n", &open, 0, Emphasis::of_open(&open));
794 }
795 let line = strip_overrides(line);
796 let mut rest = line.as_str();
797 while let Some(start) = rest.find('<') {
798 runs.push(&rest[..start], &open, 0, Emphasis::of_open(&open));
799 let tag = &rest[start + 1..];
800 let closing = tag.starts_with('/');
801 let name = tag.strip_prefix('/').unwrap_or(tag);
802 match tag.find(['<', '>']) {
803 Some(end)
804 if tag.as_bytes()[end] == b'>'
805 && name.starts_with(|character: char| character.is_ascii_alphabetic()) =>
806 {
807 let tag_name = name[..name.len().min(end - usize::from(closing))]
808 .split([' ', '\t'])
809 .next()
810 .unwrap_or_default()
811 .to_ascii_lowercase();
812 if matches!(tag_name.as_str(), "b" | "i" | "u") {
813 if closing {
814 if let Some(index) = open.iter().rposition(|open| *open == tag_name) {
815 open.remove(index);
816 }
817 } else if !open.contains(&tag_name) {
818 open.push(tag_name);
819 }
820 }
821 rest = &tag[end + 1..];
822 }
823 _ => {
824 runs.push("<", &open, 0, Emphasis::of_open(&open));
825 rest = tag;
826 }
827 }
828 }
829 runs.push(rest, &open, 0, Emphasis::of_open(&open));
830 }
831 runs.finish(None, &[0, 0])
832}
833
834fn strip_overrides(line: &str) -> String {
836 let mut output = String::with_capacity(line.len());
837 let mut rest = line;
838 while let Some(start) = rest.find("{\\") {
839 output.push_str(&rest[..start]);
840 match rest[start..].find('}') {
841 Some(end) => rest = &rest[start + end + 1..],
842 None => {
843 rest = "";
844 }
845 }
846 }
847 output.push_str(rest);
848 output
849}
850
851#[cfg(test)]
852#[path = "caption_import_tests.rs"]
853mod tests;