1use 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
14pub const MAX_CAPTION_STYLES: usize = 32;
16
17pub const MAX_CAPTION_NAME_BYTES: usize = 64;
19
20#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
22#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
23#[serde(deny_unknown_fields)]
24pub struct Captions {
25 #[serde(default)]
27 pub style: TextStyle,
28 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
31 pub styles: BTreeMap<String, TextStylePatch>,
32 #[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 #[serde(default, skip_serializing_if = "Option::is_none")]
40 pub from_words: Option<crate::CaptionsFromWords>,
41}
42
43#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
45#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
46#[serde(deny_unknown_fields)]
47pub struct CaptionCue {
48 pub timeline_range: TimeRange,
50 pub text: crate::TextContent,
53 #[serde(default, skip_serializing_if = "Option::is_none")]
56 pub speaker: Option<String>,
57 #[serde(default, skip_serializing_if = "Option::is_none")]
59 pub style: Option<String>,
60}
61
62impl CaptionCue {
63 #[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#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
78#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
79#[serde(deny_unknown_fields)]
80pub struct TextStylePatch {
81 #[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 #[serde(default, skip_serializing_if = "Option::is_none")]
91 pub font_size: Option<f32>,
92 #[serde(default, skip_serializing_if = "Option::is_none")]
94 pub fill: Option<Paint>,
95 #[serde(default, skip_serializing_if = "Option::is_none")]
97 pub line_height: Option<f32>,
98 #[serde(default, skip_serializing_if = "Option::is_none")]
100 pub letter_spacing: Option<f32>,
101 #[serde(default, skip_serializing_if = "Option::is_none")]
103 pub font_weight: Option<u16>,
104 #[serde(default, skip_serializing_if = "Option::is_none")]
106 pub font_style: Option<crate::FontStyle>,
107 #[serde(default, skip_serializing_if = "Option::is_none")]
109 pub underline: Option<bool>,
110 #[serde(default, skip_serializing_if = "Option::is_none")]
112 pub line_through: Option<bool>,
113 #[serde(default, skip_serializing_if = "Option::is_none")]
115 pub align: Option<TextAlign>,
116 #[serde(default, skip_serializing_if = "Option::is_none")]
118 pub max_width: Option<f32>,
119 #[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 #[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 #[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 #[serde(default, skip_serializing_if = "Option::is_none")]
145 pub position: Option<Vec2>,
146 #[serde(default, skip_serializing_if = "Option::is_none")]
148 pub anchor: Option<Vec2>,
149 #[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 #[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 #[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 #[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 #[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 #[serde(default, skip_serializing_if = "Option::is_none")]
184 pub animator_grouping: Option<crate::AnimatorGrouping>,
185 #[serde(default, skip_serializing_if = "Option::is_none")]
187 pub animator_pivot: Option<crate::Vec2>,
188}
189
190impl TextStylePatch {
191 #[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
268pub const MAX_CAPTION_FONT_SIZE: f32 = 0.25;
270
271#[derive(Clone, Debug, PartialEq, Eq)]
273pub(crate) enum CaptionIssue {
274 Invalid,
277 UnknownStyle { cue: usize, name: String },
279 CueStyle { cue: usize },
281}
282
283impl Captions {
284 #[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 #[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
349fn 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#[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
384fn 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
393fn unspaced(character: char) -> bool {
396 matches!(
397 u32::from(character),
398 0x0E00..=0x0EFF | 0x1000..=0x109F | 0x1780..=0x17FF | 0x19E0..=0x19FF | 0x2E80..=0x2FDF | 0x3000..=0x303F | 0x3040..=0x30FF | 0x3100..=0x312F | 0x31F0..=0x31FF | 0x3400..=0x4DBF | 0x4E00..=0x9FFF | 0xA9E0..=0xA9FF | 0xAA60..=0xAA7F | 0xF900..=0xFAFF | 0xFF00..=0xFFEF | 0x20000..=0x3FFFF )
415}
416
417pub const WORD_PAUSE_TICKS: i64 = 72_000;
419
420pub const MAX_DERIVED_CUES: usize = crate::MAX_CAPTION_FILE_CUES;
422
423#[must_use]
436pub fn group_words(words: &[crate::DataWord], max_chars: u32) -> Vec<CaptionCue> {
437 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
526pub 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
541pub 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}