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
309pub fn parse_captions_json(text: &str, format: &str) -> Result<String, String> {
320 let imported = match format {
321 "srt" => parse_srt(text),
322 "webvtt" => parse_webvtt(text),
323 other => return Err(format!("caption format must be srt or webvtt, not {other}")),
324 }
325 .map_err(|error| error.to_string())?;
326 let rows = caption_rows(&imported.cues).map_err(|error| error.to_string())?;
327 let notes = imported.notes;
328 Ok(serde_json::json!({
329 "rows": rows,
330 "skipped": imported.skipped,
331 "notes": {
332 "extraVoices": notes.extra_voices,
333 "droppedTimestamps": notes.dropped_timestamps,
334 "droppedClasses": notes.dropped_classes,
335 "flattened": notes.flattened,
336 },
337 })
338 .to_string())
339}
340
341struct Blocks<'a> {
344 lines: Lines<'a>,
345}
346
347impl<'a> Blocks<'a> {
348 fn new(text: &'a str) -> Self {
349 Self {
350 lines: Lines {
351 text: text.strip_prefix('\u{feff}').unwrap_or(text),
352 at: 0,
353 pending_blanks: 0,
354 done: false,
355 },
356 }
357 }
358}
359
360impl<'a> Iterator for Blocks<'a> {
361 type Item = Option<Vec<&'a str>>;
362
363 fn next(&mut self) -> Option<Self::Item> {
364 let mut block = Vec::new();
365 let mut bytes = 0_usize;
366 let mut oversized = false;
367 for line in self.lines.by_ref() {
368 if line.trim().is_empty() {
369 if oversized || !block.is_empty() {
370 break;
371 }
372 continue;
373 }
374 if oversized {
375 continue;
376 }
377 bytes += line.len() + 1;
378 if bytes > MAX_CUE_BLOCK_BYTES || block.len() == MAX_CUE_BLOCK_LINES {
379 oversized = true;
380 block = Vec::new();
381 continue;
382 }
383 block.push(line);
384 }
385 if oversized {
386 Some(None)
387 } else {
388 (!block.is_empty()).then_some(Some(block))
389 }
390 }
391}
392
393struct Lines<'a> {
396 text: &'a str,
397 at: usize,
398 pending_blanks: usize,
400 done: bool,
401}
402
403impl<'a> Iterator for Lines<'a> {
404 type Item = &'a str;
405
406 fn next(&mut self) -> Option<&'a str> {
407 if self.pending_blanks > 0 {
408 self.pending_blanks -= 1;
409 return Some("");
410 }
411 if self.done {
412 return None;
413 }
414 let bytes = self.text.as_bytes();
415 let start = self.at;
416 let Some(end) = bytes[start..]
417 .iter()
418 .position(|&byte| matches!(byte, b'\n' | b'\r'))
419 .map(|offset| start + offset)
420 else {
421 self.done = true;
422 return Some(&self.text[start..]);
423 };
424 if bytes[end] == b'\n' {
425 self.at = end + 1;
426 } else {
427 let returns = bytes[end..]
428 .iter()
429 .take_while(|&&byte| byte == b'\r')
430 .count();
431 self.at = end + returns;
432 if bytes.get(self.at) == Some(&b'\n') {
433 self.at += 1;
434 } else {
435 self.pending_blanks = returns - 1;
436 }
437 }
438 Some(&self.text[start..end])
439 }
440}
441
442fn timing(line: &str) -> Option<TimeRange> {
444 let (start, rest) = line.split_once("-->")?;
445 let end = rest.split_whitespace().next()?;
446 let (start, end) = (timestamp(start.trim())?, timestamp(end)?);
447 TimeRange::new(start, end)
448 .ok()
449 .filter(|range| !range.is_empty())
450}
451
452fn timestamp(text: &str) -> Option<MediaTime> {
455 let (clock, millis) = text.split_once([',', '.'])?;
456 if millis.len() != 3 || !millis.bytes().all(|byte| byte.is_ascii_digit()) {
457 return None;
458 }
459 let fields = clock.split(':').collect::<Vec<_>>();
460 let number = |field: &str| {
461 (!field.is_empty() && field.bytes().all(|byte| byte.is_ascii_digit()))
462 .then(|| field.parse::<i64>().ok())
463 .flatten()
464 };
465 let (hours, minutes, seconds) = match fields.as_slice() {
466 [hours, minutes, seconds] => (number(hours)?, number(minutes)?, number(seconds)?),
467 [minutes, seconds] => (0, number(minutes)?, number(seconds)?),
468 _ => return None,
469 };
470 if minutes > 59 || seconds > 59 {
471 return None;
472 }
473 let milliseconds = ((hours.checked_mul(60)?.checked_add(minutes)?)
474 .checked_mul(60)?
475 .checked_add(seconds)?)
476 .checked_mul(1_000)?
477 .checked_add(millis.parse::<i64>().ok()?)?;
478 let ticks = milliseconds.checked_mul(TICKS_PER_MILLISECOND)?;
479 (ticks <= alpha2_time::MAX_SERIALIZED_TICKS).then(|| MediaTime::from_ticks(ticks))
480}
481
482fn cue_text(text: &str) -> Option<String> {
484 let text = text.trim_matches('\n').to_owned();
485 (!text.trim().is_empty() && text.len() <= MAX_TEXT_CONTENT_BYTES).then_some(text)
486}
487
488fn decode_references(text: &str) -> String {
493 let mut output = String::with_capacity(text.len());
494 let mut rest = text;
495 while let Some(start) = rest.find('&') {
496 output.push_str(&rest[..start]);
497 rest = &rest[start + 1..];
498 let length = rest
499 .bytes()
500 .take_while(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'#' | b'+'))
501 .count();
502 let decoded = (rest.as_bytes().get(length) == Some(&b';'))
503 .then(|| reference(&rest[..length]))
504 .flatten();
505 match decoded {
506 Some(character) => {
507 output.push(character);
508 rest = &rest[length + 1..];
509 }
510 None => output.push('&'),
511 }
512 }
513 output.push_str(rest);
514 output
515}
516
517fn reference(name: &str) -> Option<char> {
519 match name {
520 "amp" => Some('&'),
521 "lt" => Some('<'),
522 "gt" => Some('>'),
523 "nbsp" => Some('\u{a0}'),
524 "lrm" => Some('\u{200e}'),
525 "rlm" => Some('\u{200f}'),
526 _ => name
527 .strip_prefix("#x")
528 .or_else(|| name.strip_prefix("#X"))
529 .and_then(|hex| u32::from_str_radix(hex, 16).ok())
530 .or_else(|| name.strip_prefix('#').and_then(|dec| dec.parse().ok()))
531 .and_then(char::from_u32),
532 }
533}
534
535struct Marked {
538 text: String,
539 speaker: Option<String>,
540 runs: Option<Vec<TextRun>>,
541 notes: ImportNotes,
542}
543
544#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
547struct Emphasis {
548 bold: bool,
549 italic: bool,
550 underline: bool,
551}
552
553impl Emphasis {
554 fn of<'n>(names: impl IntoIterator<Item = &'n str>) -> Self {
555 let mut emphasis = Self::default();
556 for name in names {
557 match name {
558 "b" => emphasis.bold = true,
559 "i" => emphasis.italic = true,
560 "u" => emphasis.underline = true,
561 _ => {}
562 }
563 }
564 emphasis
565 }
566
567 fn of_open(open: &[String]) -> Self {
568 Self::of(open.iter().map(String::as_str))
569 }
570
571 fn style(self) -> Option<crate::TextRunStyle> {
572 (self != Self::default()).then(|| crate::TextRunStyle {
573 font_weight: self.bold.then_some(700),
574 font_style: self.italic.then_some(crate::FontStyle::Italic),
575 underline: self.underline.then_some(true),
576 ..crate::TextRunStyle::default()
577 })
578 }
579}
580
581struct Runs {
585 text: String,
586 pieces: Vec<(String, Vec<String>, usize, Emphasis)>,
587 tracking: bool,
588 notes: ImportNotes,
589}
590
591impl Runs {
592 fn new() -> Self {
593 Self {
594 text: String::new(),
595 pieces: Vec::new(),
596 tracking: true,
597 notes: ImportNotes::default(),
598 }
599 }
600
601 fn flatten(&mut self) {
603 if self.tracking {
604 self.tracking = false;
605 self.pieces = Vec::new();
606 self.notes.flattened += 1;
607 }
608 }
609
610 fn push(&mut self, text: &str, classes: &[String], segment: usize, emphasis: Emphasis) {
611 self.text.push_str(text);
612 if !self.tracking {
613 return;
614 }
615 let text = if self.pieces.is_empty() {
617 text.trim_start_matches('\n')
618 } else {
619 text
620 };
621 if text.is_empty() {
622 return;
623 }
624 match self.pieces.last_mut() {
625 Some((held, open, at, emphasized))
626 if open.as_slice() == classes && *at == segment && *emphasized == emphasis =>
627 {
628 held.push_str(text);
629 }
630 _ => {
631 if self.pieces.len() > MAX_TEXT_RUNS + 1 {
633 self.flatten();
634 return;
635 }
636 self.pieces
637 .push((text.to_owned(), classes.to_vec(), segment, emphasis));
638 }
639 }
640 }
641
642 fn finish(mut self, speaker: Option<String>, bounds: &[i64]) -> Marked {
646 while let Some(last) = self.pieces.last_mut() {
647 let kept = last.0.trim_end_matches('\n').len();
648 last.0.truncate(kept);
649 if last.0.is_empty() {
650 self.pieces.pop();
651 } else {
652 break;
653 }
654 }
655 if self.pieces.len() > MAX_TEXT_RUNS {
656 self.flatten();
657 }
658 let timed = bounds.len() > 2;
659 let runs = (self.tracking
660 && (timed
661 || self
662 .pieces
663 .iter()
664 .any(|(_, classes, ..)| !classes.is_empty())))
665 .then(|| {
666 self.pieces
667 .into_iter()
668 .map(|(text, mut class, segment, emphasis)| {
669 if class.len() > MAX_RUN_CLASSES {
670 self.notes.dropped_classes += class.len() - MAX_RUN_CLASSES;
671 class.truncate(MAX_RUN_CLASSES);
672 }
673 TextRun {
674 text,
675 class,
676 time: timed.then(|| RunTime {
677 start: MediaTime(bounds[segment]),
678 end: MediaTime(bounds[segment + 1]),
679 }),
680 style: emphasis.style(),
681 }
682 })
683 .collect()
684 });
685 Marked {
686 text: self.text,
687 speaker,
688 runs,
689 notes: self.notes,
690 }
691 }
692}
693
694fn tag_classes(names: &str, notes: &mut ImportNotes) -> Vec<String> {
697 names
698 .split('.')
699 .filter(|name| !name.is_empty())
700 .filter_map(|name| {
701 if valid_class_name(name) {
702 Some(name.to_owned())
703 } else {
704 notes.dropped_classes += 1;
705 None
706 }
707 })
708 .collect()
709}
710
711fn vtt_markup(body: &str, range: TimeRange) -> Marked {
716 let start = range.start().ticks();
717 let duration = range.duration().map_or(0, MediaTime::ticks);
718 let mut runs = Runs::new();
719 let mut speaker = None;
720 let mut open: Vec<(&str, usize)> = Vec::new();
722 let mut classes: Vec<String> = Vec::new();
724 let mut bounds = vec![0_i64];
725 let mut rest = body;
726 loop {
727 let emphasis = Emphasis::of(open.iter().map(|(name, _)| *name));
728 let Some(at) = rest.find('<') else {
729 runs.push(
730 &decode_references(rest),
731 &classes,
732 bounds.len() - 1,
733 emphasis,
734 );
735 break;
736 };
737 runs.push(
738 &decode_references(&rest[..at]),
739 &classes,
740 bounds.len() - 1,
741 emphasis,
742 );
743 let Some(end) = rest[at..].find('>') else {
744 break;
745 };
746 let tag = &rest[at + 1..at + end];
747 rest = &rest[at + end + 1..];
748 if let Some(name) = tag.strip_prefix('/') {
749 let name = name.trim();
750 if let Some(index) = open.iter().rposition(|(open, _)| *open == name) {
751 classes.truncate(open[index].1);
752 open.truncate(index);
753 }
754 continue;
755 }
756 if tag.starts_with(|character: char| character.is_ascii_digit()) {
757 match timestamp(tag.trim()) {
759 Some(time)
760 if time.ticks() - start > *bounds.last().unwrap_or(&0)
761 && time.ticks() - start < duration =>
762 {
763 if runs.tracking {
764 bounds.push(time.ticks() - start);
765 }
766 }
767 _ => runs.notes.dropped_timestamps += 1,
768 }
769 continue;
770 }
771 let (head, annotation) = tag
773 .split_once([' ', '\t'])
774 .map_or((tag, ""), |(head, annotation)| (head, annotation.trim()));
775 let (name, names) = head.split_once('.').unwrap_or((head, ""));
776 let given = match name {
777 "v" => {
778 if speaker.is_none() && !annotation.is_empty() {
779 speaker = Some(annotation.to_owned());
780 } else if !annotation.is_empty() {
781 runs.notes.extra_voices += 1;
782 }
783 let mut given = vec!["voice".to_owned()];
784 given.extend(tag_classes(names, &mut runs.notes));
785 given
786 }
787 "c" => tag_classes(names, &mut runs.notes),
788 "b" | "i" | "u" => {
789 let mut given = vec![name.to_owned()];
790 given.extend(tag_classes(names, &mut runs.notes));
791 given
792 }
793 _ => Vec::new(),
794 };
795 if !runs.tracking {
796 continue;
797 }
798 if open.len() == MAX_OPEN_TAGS {
799 runs.flatten();
800 continue;
801 }
802 open.push((name, classes.len()));
803 for class in given {
804 if !classes.contains(&class) {
805 if classes.len() == MAX_HELD_CLASSES {
806 runs.flatten();
807 break;
808 }
809 classes.push(class);
810 }
811 }
812 }
813 bounds.push(duration);
814 let speaker = speaker.filter(|speaker| speaker.len() <= crate::MAX_CAPTION_NAME_BYTES);
815 runs.finish(speaker, &bounds)
816}
817
818fn srt_markup(body: &[&str]) -> Marked {
821 let mut runs = Runs::new();
822 let mut open: Vec<String> = Vec::new();
823 for (index, line) in body.iter().enumerate() {
824 if index > 0 {
825 runs.push("\n", &open, 0, Emphasis::of_open(&open));
826 }
827 let line = strip_overrides(line);
828 let mut rest = line.as_str();
829 while let Some(start) = rest.find('<') {
830 runs.push(&rest[..start], &open, 0, Emphasis::of_open(&open));
831 let tag = &rest[start + 1..];
832 let closing = tag.starts_with('/');
833 let name = tag.strip_prefix('/').unwrap_or(tag);
834 match tag.find(['<', '>']) {
835 Some(end)
836 if tag.as_bytes()[end] == b'>'
837 && name.starts_with(|character: char| character.is_ascii_alphabetic()) =>
838 {
839 let tag_name = name[..name.len().min(end - usize::from(closing))]
840 .split([' ', '\t'])
841 .next()
842 .unwrap_or_default()
843 .to_ascii_lowercase();
844 if matches!(tag_name.as_str(), "b" | "i" | "u") {
845 if closing {
846 if let Some(index) = open.iter().rposition(|open| *open == tag_name) {
847 open.remove(index);
848 }
849 } else if !open.contains(&tag_name) {
850 open.push(tag_name);
851 }
852 }
853 rest = &tag[end + 1..];
854 }
855 _ => {
856 runs.push("<", &open, 0, Emphasis::of_open(&open));
857 rest = tag;
858 }
859 }
860 }
861 runs.push(rest, &open, 0, Emphasis::of_open(&open));
862 }
863 runs.finish(None, &[0, 0])
864}
865
866fn strip_overrides(line: &str) -> String {
868 let mut output = String::with_capacity(line.len());
869 let mut rest = line;
870 while let Some(start) = rest.find("{\\") {
871 output.push_str(&rest[..start]);
872 match rest[start..].find('}') {
873 Some(end) => rest = &rest[start + end + 1..],
874 None => {
875 rest = "";
876 }
877 }
878 }
879 output.push_str(rest);
880 output
881}
882
883#[cfg(test)]
884#[path = "caption_import_tests.rs"]
885mod tests;