Skip to main content

alpha2_model/
caption.rs

1//! Caption tracks: timed text drawn in a track's style, each cue in a named style or its
2//! speaker's.
3
4use std::borrow::Cow;
5use std::collections::BTreeMap;
6
7use crate::{
8    FontSizeFit, LineClamp, MAX_TEXT_CONTENT_BYTES, Paint, TextAlign, TextAnimator, TextBackground,
9    TextShadow, TextStroke, TextStyle, Vec2,
10};
11use alpha2_time::TimeRange;
12use serde::{Deserialize, Serialize};
13
14/// Most named styles one caption track holds.
15pub const MAX_CAPTION_STYLES: usize = 32;
16
17/// Most bytes of a caption style's name or a cue's speaker.
18pub const MAX_CAPTION_NAME_BYTES: usize = 64;
19
20/// What a caption track shows: its cues, in its style.
21#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
22#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
23#[serde(deny_unknown_fields)]
24pub struct Captions {
25    /// The style every cue starts from.
26    #[serde(default)]
27    pub style: TextStyle,
28    /// Named changes to `style` for cues that name one or whose speaker has one. At most
29    /// [`MAX_CAPTION_STYLES`], names 1 to 64 bytes.
30    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
31    pub styles: BTreeMap<String, TextStylePatch>,
32    /// Cues in timeline order, none overlapping; a track shows one cue at a time. Empty when
33    /// `from_words` gives the cues.
34    #[serde(default)]
35    #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_CLIPS_PER_TRACK }>")]
36    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_CLIPS_PER_TRACK)))]
37    pub cues: Vec<CaptionCue>,
38    /// Cues built at evaluation from a `words` data set, instead of `cues`.
39    #[serde(default, skip_serializing_if = "Option::is_none")]
40    pub from_words: Option<crate::CaptionsFromWords>,
41}
42
43/// Text shown over one timeline interval.
44#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
45#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
46#[serde(deny_unknown_fields)]
47pub struct CaptionCue {
48    /// When the cue shows. Non-empty and not before zero.
49    pub timeline_range: TimeRange,
50    /// The text, a string or runs; `\n` starts a line. Non-empty, at most
51    /// [`MAX_TEXT_CONTENT_BYTES`] bytes. Run times are from the cue's start and lie within it.
52    pub text: crate::TextContent,
53    /// Who says it, as the source names them (a WebVTT voice), at most 64 bytes. A track style
54    /// of that name applies when the cue names no style.
55    #[serde(default, skip_serializing_if = "Option::is_none")]
56    pub speaker: Option<String>,
57    /// The name of one of the track's `styles`, applied over its style.
58    #[serde(default, skip_serializing_if = "Option::is_none")]
59    pub style: Option<String>,
60}
61
62impl CaptionCue {
63    /// A cue showing `text` over `timeline_range`, with no speaker or style.
64    #[must_use]
65    pub fn new(timeline_range: TimeRange, text: impl Into<crate::TextContent>) -> Self {
66        Self {
67            timeline_range,
68            text: text.into(),
69            speaker: None,
70            style: None,
71        }
72    }
73}
74
75/// Changes to a [`TextStyle`]. Each field set replaces the base's whole value (lists are not
76/// merged); a field left out keeps the base's.
77#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
78#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
79#[serde(deny_unknown_fields)]
80pub struct TextStylePatch {
81    /// The family; `null` draws from the fallback order alone.
82    #[serde(
83        default,
84        skip_serializing_if = "Option::is_none",
85        with = "double_option"
86    )]
87    #[cfg_attr(feature = "schema", schemars(with = "Option<String>"))]
88    pub font_family: Option<Option<String>>,
89    /// See [`TextStyle::font_size`].
90    #[serde(default, skip_serializing_if = "Option::is_none")]
91    pub font_size: Option<f32>,
92    /// See [`TextStyle::fill`].
93    #[serde(default, skip_serializing_if = "Option::is_none")]
94    pub fill: Option<Paint>,
95    /// See [`TextStyle::line_height`].
96    #[serde(default, skip_serializing_if = "Option::is_none")]
97    pub line_height: Option<f32>,
98    /// See [`TextStyle::letter_spacing`].
99    #[serde(default, skip_serializing_if = "Option::is_none")]
100    pub letter_spacing: Option<f32>,
101    /// See [`TextStyle::font_weight`].
102    #[serde(default, skip_serializing_if = "Option::is_none")]
103    pub font_weight: Option<u16>,
104    /// See [`TextStyle::font_style`].
105    #[serde(default, skip_serializing_if = "Option::is_none")]
106    pub font_style: Option<crate::FontStyle>,
107    /// See [`TextStyle::underline`].
108    #[serde(default, skip_serializing_if = "Option::is_none")]
109    pub underline: Option<bool>,
110    /// See [`TextStyle::line_through`].
111    #[serde(default, skip_serializing_if = "Option::is_none")]
112    pub line_through: Option<bool>,
113    /// See [`TextStyle::align`].
114    #[serde(default, skip_serializing_if = "Option::is_none")]
115    pub align: Option<TextAlign>,
116    /// See [`TextStyle::max_width`].
117    #[serde(default, skip_serializing_if = "Option::is_none")]
118    pub max_width: Option<f32>,
119    /// See [`TextStyle::max_height`]; `null` removes the base's.
120    #[serde(
121        default,
122        skip_serializing_if = "Option::is_none",
123        with = "double_option"
124    )]
125    #[cfg_attr(feature = "schema", schemars(with = "Option<f32>"))]
126    pub max_height: Option<Option<f32>>,
127    /// See [`TextStyle::font_size_fit`]; `null` removes the base's.
128    #[serde(
129        default,
130        skip_serializing_if = "Option::is_none",
131        with = "double_option"
132    )]
133    #[cfg_attr(feature = "schema", schemars(with = "Option<FontSizeFit>"))]
134    pub font_size_fit: Option<Option<FontSizeFit>>,
135    /// See [`TextStyle::line_clamp`]; `null` removes the base's.
136    #[serde(
137        default,
138        skip_serializing_if = "Option::is_none",
139        with = "double_option"
140    )]
141    #[cfg_attr(feature = "schema", schemars(with = "Option<LineClamp>"))]
142    pub line_clamp: Option<Option<LineClamp>>,
143    /// See [`TextStyle::position`].
144    #[serde(default, skip_serializing_if = "Option::is_none")]
145    pub position: Option<Vec2>,
146    /// See [`TextStyle::anchor`].
147    #[serde(default, skip_serializing_if = "Option::is_none")]
148    pub anchor: Option<Vec2>,
149    /// See [`TextStyle::strokes`].
150    #[serde(default, skip_serializing_if = "Option::is_none")]
151    #[serde(deserialize_with = "crate::bounded::option_seq::<_, _, { crate::MAX_TEXT_STROKES }>")]
152    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_TEXT_STROKES)))]
153    pub strokes: Option<Vec<TextStroke>>,
154    /// See [`TextStyle::shadows`].
155    #[serde(default, skip_serializing_if = "Option::is_none")]
156    #[serde(deserialize_with = "crate::bounded::option_seq::<_, _, { crate::MAX_TEXT_SHADOWS }>")]
157    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_TEXT_SHADOWS)))]
158    pub shadows: Option<Vec<TextShadow>>,
159    /// The box behind each line; `null` removes the base's.
160    #[serde(
161        default,
162        skip_serializing_if = "Option::is_none",
163        with = "double_option"
164    )]
165    #[cfg_attr(feature = "schema", schemars(with = "Option<TextBackground>"))]
166    pub background: Option<Option<TextBackground>>,
167    /// The box over the timed run being said; `null` removes the base's.
168    #[serde(
169        default,
170        skip_serializing_if = "Option::is_none",
171        with = "double_option"
172    )]
173    #[cfg_attr(feature = "schema", schemars(with = "Option<crate::TextHighlight>"))]
174    pub highlight: Option<Option<crate::TextHighlight>>,
175    /// See [`TextStyle::animators`].
176    #[serde(default, skip_serializing_if = "Option::is_none")]
177    #[serde(
178        deserialize_with = "crate::bounded::option_seq::<_, _, { crate::MAX_TEXT_ANIMATORS }>"
179    )]
180    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_TEXT_ANIMATORS)))]
181    pub animators: Option<Vec<TextAnimator>>,
182    /// See [`TextStyle::animator_grouping`].
183    #[serde(default, skip_serializing_if = "Option::is_none")]
184    pub animator_grouping: Option<crate::AnimatorGrouping>,
185    /// See [`TextStyle::animator_pivot`].
186    #[serde(default, skip_serializing_if = "Option::is_none")]
187    pub animator_pivot: Option<crate::Vec2>,
188}
189
190impl TextStylePatch {
191    /// `base` with every field this patch sets replaced.
192    #[must_use]
193    pub fn apply(&self, base: &TextStyle) -> TextStyle {
194        let mut style = base.clone();
195        if let Some(family) = &self.font_family {
196            style.font_family.clone_from(family);
197        }
198        if let Some(size) = self.font_size {
199            style.font_size = size;
200        }
201        if let Some(fill) = &self.fill {
202            style.fill = fill.clone();
203        }
204        if let Some(height) = self.line_height {
205            style.line_height = height;
206        }
207        if let Some(spacing) = self.letter_spacing {
208            style.letter_spacing = spacing;
209        }
210        if let Some(weight) = self.font_weight {
211            style.font_weight = weight;
212        }
213        if let Some(font_style) = self.font_style {
214            style.font_style = font_style;
215        }
216        if let Some(underline) = self.underline {
217            style.underline = underline;
218        }
219        if let Some(line_through) = self.line_through {
220            style.line_through = line_through;
221        }
222        if let Some(align) = self.align {
223            style.align = align;
224        }
225        if let Some(width) = self.max_width {
226            style.max_width = width;
227        }
228        if let Some(height) = self.max_height {
229            style.max_height = height;
230        }
231        if let Some(fit) = self.font_size_fit {
232            style.font_size_fit = fit;
233        }
234        if let Some(clamp) = &self.line_clamp {
235            style.line_clamp.clone_from(clamp);
236        }
237        if let Some(position) = self.position {
238            style.position = position;
239        }
240        if let Some(anchor) = self.anchor {
241            style.anchor = anchor;
242        }
243        if let Some(strokes) = &self.strokes {
244            style.strokes.clone_from(strokes);
245        }
246        if let Some(shadows) = &self.shadows {
247            style.shadows.clone_from(shadows);
248        }
249        if let Some(background) = &self.background {
250            style.background.clone_from(background);
251        }
252        if let Some(highlight) = &self.highlight {
253            style.highlight.clone_from(highlight);
254        }
255        if let Some(animators) = &self.animators {
256            style.animators.clone_from(animators);
257        }
258        if let Some(grouping) = self.animator_grouping {
259            style.animator_grouping = grouping;
260        }
261        if let Some(pivot) = self.animator_pivot {
262            style.animator_pivot = pivot;
263        }
264        style
265    }
266}
267
268/// Largest caption font size, as a fraction of the frame's shorter side.
269pub const MAX_CAPTION_FONT_SIZE: f32 = 0.25;
270
271/// Why a caption track's cue or style is refused.
272#[derive(Clone, Debug, PartialEq, Eq)]
273pub(crate) enum CaptionIssue {
274    /// The track's style, a style name, a speaker, a cue's range, text or run times, or the
275    /// cues' order.
276    Invalid,
277    /// Cue `cue` names a style the track does not have.
278    UnknownStyle { cue: usize, name: String },
279    /// Cue `cue`'s style, its patch applied, or a run's style over it is out of range.
280    CueStyle { cue: usize },
281}
282
283impl Captions {
284    /// The patch cue `cue` takes: the style it names, else its speaker's if the track has one,
285    /// else none.
286    #[must_use]
287    pub fn cue_patch(&self, cue: &CaptionCue) -> Option<&TextStylePatch> {
288        match &cue.style {
289            Some(name) => self.styles.get(name),
290            None => cue
291                .speaker
292                .as_ref()
293                .and_then(|speaker| self.styles.get(speaker)),
294        }
295    }
296
297    /// The style cue `cue` draws in: the track's, with its patch applied.
298    #[must_use]
299    pub fn cue_style(&self, cue: &CaptionCue) -> Cow<'_, TextStyle> {
300        match self.cue_patch(cue) {
301            Some(patch) => Cow::Owned(patch.apply(&self.style)),
302            None => Cow::Borrowed(&self.style),
303        }
304    }
305
306    pub(crate) fn validate(&self) -> Result<(), CaptionIssue> {
307        let name = |name: &str| !name.is_empty() && name.len() <= MAX_CAPTION_NAME_BYTES;
308        let valid = (self.from_words.is_none() || self.cues.is_empty())
309            && self.style.is_valid(MAX_CAPTION_FONT_SIZE)
310            && self.styles.len() <= MAX_CAPTION_STYLES
311            && self.styles.keys().all(|key| name(key))
312            && self.cues.iter().all(|cue| {
313                !cue.timeline_range.is_empty()
314                    && cue.timeline_range.start().ticks() >= 0
315                    && cue.text.is_valid(MAX_TEXT_CONTENT_BYTES)
316                    && cue.speaker.as_deref().is_none_or(name)
317                    && run_times_lie_in(cue)
318            })
319            && self
320                .cues
321                .windows(2)
322                .all(|pair| pair[0].timeline_range.end() <= pair[1].timeline_range.start());
323        if !valid {
324            return Err(CaptionIssue::Invalid);
325        }
326        for (index, cue) in self.cues.iter().enumerate() {
327            if let Some(style) = &cue.style
328                && !self.styles.contains_key(style)
329            {
330                return Err(CaptionIssue::UnknownStyle {
331                    cue: index,
332                    name: style.clone(),
333                });
334            }
335            let style = self.cue_style(cue);
336            if (self.cue_patch(cue).is_some() && !style.is_valid(MAX_CAPTION_FONT_SIZE))
337                || cue
338                    .text
339                    .invalid_run_style(crate::text_animation::FontSelection::of(&style))
340                    .is_some()
341            {
342                return Err(CaptionIssue::CueStyle { cue: index });
343            }
344        }
345        Ok(())
346    }
347}
348
349/// Whether every run time of `cue` lies within the cue's duration.
350fn run_times_lie_in(cue: &CaptionCue) -> bool {
351    let duration = cue
352        .timeline_range
353        .duration()
354        .map_or(0, alpha2_time::MediaTime::ticks);
355    cue.text.runs().iter().all(|run| {
356        run.time
357            .is_none_or(|time| time.start.ticks() >= 0 && time.end.ticks() <= duration)
358    })
359}
360
361/// A field that is absent (no change), `null` (clear) or a value, read as `Option<Option<T>>`
362/// with `null` kept apart from absent.
363#[allow(clippy::option_option, clippy::ref_option)]
364pub(crate) mod double_option {
365    use serde::{Deserialize, Deserializer, Serialize, Serializer};
366
367    pub(crate) fn serialize<T: Serialize, S: Serializer>(
368        value: &Option<Option<T>>,
369        serializer: S,
370    ) -> Result<S::Ok, S::Error> {
371        match value {
372            Some(inner) => inner.serialize(serializer),
373            None => serializer.serialize_none(),
374        }
375    }
376
377    pub(crate) fn deserialize<'de, T: Deserialize<'de>, D: Deserializer<'de>>(
378        deserializer: D,
379    ) -> Result<Option<Option<T>>, D::Error> {
380        Option::<T>::deserialize(deserializer).map(Some)
381    }
382}
383
384/// What joins word `left` to word `right` in a cue: nothing between two characters of scripts
385/// written without word spaces, else one space.
386fn word_separator(left: &str, right: &str) -> &'static str {
387    match (left.chars().next_back(), right.chars().next()) {
388        (Some(last), Some(first)) if unspaced(last) && unspaced(first) => "",
389        _ => " ",
390    }
391}
392
393/// Whether `character` is of line breaking class ID, CJ or SA (UAX #14), as far as scripts
394/// written without spaces between words go. Hangul is spaced and not included.
395fn unspaced(character: char) -> bool {
396    matches!(
397        u32::from(character),
398        0x0E00..=0x0EFF // Thai, Lao
399            | 0x1000..=0x109F // Myanmar
400            | 0x1780..=0x17FF // Khmer
401            | 0x19E0..=0x19FF // Khmer symbols
402            | 0x2E80..=0x2FDF // CJK and Kangxi radicals
403            | 0x3000..=0x303F // CJK symbols and punctuation
404            | 0x3040..=0x30FF // Hiragana, Katakana
405            | 0x3100..=0x312F // Bopomofo
406            | 0x31F0..=0x31FF // Katakana phonetic extensions
407            | 0x3400..=0x4DBF // CJK extension A
408            | 0x4E00..=0x9FFF // CJK unified ideographs
409            | 0xA9E0..=0xA9FF // Myanmar extended B
410            | 0xAA60..=0xAA7F // Myanmar extended A
411            | 0xF900..=0xFAFF // CJK compatibility ideographs
412            | 0xFF00..=0xFFEF // Halfwidth and fullwidth forms
413            | 0x20000..=0x3FFFF // CJK extensions B and later
414    )
415}
416
417/// The longest gap between two words of one cue, in ticks (0.6 s).
418pub const WORD_PAUSE_TICKS: i64 = 72_000;
419
420/// Most cues a caption track derives from words, as many as one subtitle file holds.
421pub const MAX_DERIVED_CUES: usize = crate::MAX_CAPTION_FILE_CUES;
422
423/// Words grouped into cues that end at `max_chars` characters, a sentence's end, a pause longer
424/// than [`WORD_PAUSE_TICKS`], a change of speaker, or before the text would pass
425/// [`MAX_TEXT_CONTENT_BYTES`] or [`crate::MAX_TEXT_RUNS`] runs. Each cue has one run per word
426/// (with the separator that follows it), timed from the cue's start, so Timing selectors follow
427/// the speech. A word whose text trims to nothing is skipped.
428///
429/// Words are joined by a space, except between two characters of scripts written without word
430/// spaces (line breaking classes ID, CJ and SA of UAX #14).
431///
432/// `words` are in start order, each ending after it starts. Every cue is a valid explicit cue,
433/// and the cues are ordered and disjoint: where words overlap, each cue ends where the next
434/// starts, and of two cues with one start only the later is kept.
435#[must_use]
436pub fn group_words(words: &[crate::DataWord], max_chars: u32) -> Vec<CaptionCue> {
437    // Each cue being built: its start, end, speaker, words with their times, and its length in
438    // characters and in bytes.
439    type Words = (
440        i64,
441        i64,
442        Option<String>,
443        Vec<(String, i64, i64)>,
444        usize,
445        usize,
446    );
447    let mut groups: Vec<Words> = Vec::new();
448    let mut current: Option<Words> = None;
449    for word in words {
450        let (start, end) = (word.start.ticks(), word.end.ticks());
451        let text = word.text.trim().to_owned();
452        if text.is_empty() {
453            continue;
454        }
455        let characters = text.chars().count();
456        if let Some((_, cue_end, speaker, held, held_length, held_bytes)) = &mut current {
457            let last = held.last().map_or("", |(word, ..)| word.as_str());
458            let separator = word_separator(last, &text).len();
459            let length = *held_length + separator + characters;
460            let bytes = *held_bytes + separator + text.len();
461            let sentence_end = last.ends_with([
462                '.', '?', '!', '\u{3002}', '\u{ff01}', '\u{ff0e}', '\u{ff1f}',
463            ]);
464            if length <= max_chars as usize
465                && bytes <= MAX_TEXT_CONTENT_BYTES
466                && held.len() < crate::MAX_TEXT_RUNS
467                && start - *cue_end <= WORD_PAUSE_TICKS
468                && !sentence_end
469                && *speaker == word.speaker
470            {
471                held.push((text, start, end));
472                *cue_end = (*cue_end).max(end);
473                *held_length = length;
474                *held_bytes = bytes;
475                continue;
476            }
477            groups.extend(current.take());
478        }
479        let bytes = text.len();
480        current = Some((
481            start,
482            end,
483            word.speaker.clone(),
484            vec![(text, start, end)],
485            characters,
486            bytes,
487        ));
488    }
489    groups.extend(current);
490    let mut cues = groups
491        .into_iter()
492        .filter_map(|(start, end, speaker, held, _, _)| {
493            let separators = held
494                .windows(2)
495                .map(|pair| word_separator(&pair[0].0, &pair[1].0))
496                .chain([""])
497                .collect::<Vec<_>>();
498            let runs = held
499                .into_iter()
500                .zip(separators)
501                .map(|((mut text, from, to), separator)| {
502                    text.push_str(separator);
503                    crate::TextRun {
504                        text,
505                        class: Vec::new(),
506                        time: Some(crate::RunTime {
507                            start: alpha2_time::MediaTime(from - start),
508                            end: alpha2_time::MediaTime(to - start),
509                        }),
510                        style: None,
511                    }
512                })
513                .collect();
514            let range =
515                TimeRange::new(alpha2_time::MediaTime(start), alpha2_time::MediaTime(end)).ok()?;
516            Some(CaptionCue {
517                speaker,
518                ..CaptionCue::new(range, crate::TextContent::Runs(runs))
519            })
520        })
521        .collect::<Vec<_>>();
522    end_cues_where_the_next_starts(&mut cues);
523    cues
524}
525
526/// Ends each cue of `cues`, sorted by start, where the next starts, and drops a cue left empty.
527pub fn end_cues_where_the_next_starts(cues: &mut Vec<CaptionCue>) {
528    for index in 1..cues.len() {
529        let next = cues[index].timeline_range.start();
530        let previous = &mut cues[index - 1];
531        if previous.timeline_range.end() > next {
532            let start = previous.timeline_range.start().min(next);
533            previous.timeline_range =
534                TimeRange::new(start, next).unwrap_or(previous.timeline_range);
535            clip_runs(previous);
536        }
537    }
538    cues.retain(|cue| !cue.timeline_range.is_empty());
539}
540
541/// Clamps a cue's run times to its range after the range was shortened. A run that would start
542/// at or after the end gets no time.
543pub fn clip_runs(cue: &mut CaptionCue) {
544    let duration = cue
545        .timeline_range
546        .duration()
547        .map_or(0, alpha2_time::MediaTime::ticks);
548    if let crate::TextContent::Runs(runs) = &mut cue.text {
549        for run in runs {
550            run.time = run.time.and_then(|time| {
551                let end = time.end.ticks().min(duration);
552                (time.start.ticks() < end).then_some(crate::RunTime {
553                    start: time.start,
554                    end: alpha2_time::MediaTime(end),
555                })
556            });
557        }
558    }
559}