forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

ir.rs298 lines, 10.2 KiBHistoryRawDownload
1//! The one cue model every subtitle parser in the family answers with.
2//!
3//! A cue is a time range and a *tree* of inline runs rather than a string:
4//! italics, colour, a karaoke beat and a line break are all things a renderer
5//! will want and a plain-text caller can drop in one call
6//! ([`plain_text`]). Positioning that the format states — WebVTT cue settings,
7//! ASS `\pos` and `\an` — rides beside the runs instead of inside them, because
8//! it applies to the cue as a whole.
9
10/// How a karaoke syllable is highlighted, after libass.
11#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
12pub enum KaraokeMode {
13 /// `\k`: the syllable is secondary-coloured until `start_cs`, then switches at once to primary.
14 #[default]
15 Fill,
16 /// `\kf` / `\K`: a left-to-right sweep from secondary to primary across the syllable.
17 Sweep,
18 /// `\ko`: like `Fill`, but the switch is of the outline only (the outline stays hidden until the
19 /// syllable starts).
20 Outline,
21}
22
23/// One inline run of a cue body.
24#[derive(Clone, Debug, PartialEq)]
25pub enum Segment {
26 /// Literal text.
27 Text(String),
28 /// Hard line break (SRT/WebVTT newline, ASS `\N`).
29 LineBreak,
30 /// Bold children (`<b>`, ASS `\b1`).
31 Bold(Vec<Segment>),
32 /// Italic children (`<i>`, ASS `\i1`).
33 Italic(Vec<Segment>),
34 /// Underlined children (`<u>`, ASS `\u1`).
35 Underline(Vec<Segment>),
36 /// Struck-through children (`<s>`, ASS `\s1`).
37 Strike(Vec<Segment>),
38 /// Children in an explicit colour (`<font color>`, ASS `\c` / `\1c`).
39 Color {
40 /// Text colour, one byte per channel.
41 rgb: (u8, u8, u8),
42 /// What the colour applies to.
43 children: Vec<Segment>,
44 },
45 /// Children under a font override (`<font face size>`, ASS `\fn` / `\fs`).
46 Font {
47 /// Family name; `None` inherits.
48 family: Option<String>,
49 /// Size in the source format's own units; `None` inherits.
50 size: Option<f32>,
51 /// What the override applies to.
52 children: Vec<Segment>,
53 },
54 /// WebVTT `<v Speaker>`.
55 Voice {
56 /// The speaker the annotation names.
57 name: String,
58 /// What that voice says.
59 children: Vec<Segment>,
60 },
61 /// WebVTT `<c.class>`.
62 Class {
63 /// Class name without the leading dot.
64 name: String,
65 /// What the class applies to.
66 children: Vec<Segment>,
67 },
68 /// ASS karaoke syllable (`\k`, `\K`, `\kf`, `\ko`, `\kt`).
69 ///
70 /// The syllable is highlighted from `start_cs` to `start_cs + cs`, both in
71 /// centiseconds from the cue start. A run split by a style block inside one
72 /// syllable repeats the same `start_cs` and `cs`; a renderer groups by that pair.
73 Karaoke {
74 /// Beat length in centiseconds.
75 cs: u32,
76 /// Syllable start, centiseconds from the cue start (`\kt` sets it absolutely).
77 start_cs: u32,
78 /// How the highlight is drawn.
79 mode: KaraokeMode,
80 /// `\2c` override of the not-yet-sung colour; `None` is the style's secondary.
81 secondary: Option<(u8, u8, u8)>,
82 /// The syllable under the beat.
83 children: Vec<Segment>,
84 },
85 /// WebVTT inline timestamp `<00:00:01.500>`, microseconds from stream start.
86 Timestamp {
87 /// The instant the tag names.
88 offset_us: i64,
89 },
90 /// Markup this parser does not model, kept verbatim so a re-emit stays
91 /// faithful and [`plain_text`] can drop it whole. ASS drawing commands
92 /// (`{\p1}` … `{\p0}`) land here too: they are shapes, not words.
93 Raw(String),
94}
95
96/// Horizontal alignment of a cue or a style row.
97#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
98pub enum TextAlign {
99 /// Start edge of the text direction — left in a left-to-right script.
100 #[default]
101 Start,
102 /// Centred.
103 Center,
104 /// End edge of the text direction.
105 End,
106 /// Left edge whatever the text direction.
107 Left,
108 /// Right edge whatever the text direction.
109 Right,
110}
111
112/// Where the format asked for the cue to be drawn.
113///
114/// The units are the source's own: WebVTT `position`/`line`/`size` are
115/// percentages of the viewport, ASS `\pos` is pixels in the `PlayResX` ×
116/// `PlayResY` canvas.
117#[derive(Clone, Copy, Debug, Default, PartialEq)]
118pub struct CuePosition {
119 /// Horizontal position, or `None` for the format default.
120 pub x: Option<f32>,
121 /// Vertical position, or `None` for the format default.
122 pub y: Option<f32>,
123 /// Horizontal alignment of the cue's lines.
124 pub align: TextAlign,
125 /// WebVTT `size:N%`; meaningless for ASS.
126 pub size: Option<f32>,
127}
128
129/// A named style a cue can reference — an ASS `Style:` row, essentially.
130#[derive(Clone, Debug, Default, PartialEq)]
131pub struct SubtitleStyle {
132 /// Style name, which is what [`SubtitleCue::style_ref`] holds.
133 pub name: String,
134 /// Font family.
135 pub font_family: Option<String>,
136 /// Font size in the source's units.
137 pub font_size: Option<f32>,
138 /// Fill colour, RGBA.
139 pub primary_color: Option<(u8, u8, u8, u8)>,
140 /// Secondary (karaoke, not yet sung) colour, RGBA.
141 pub secondary_color: Option<(u8, u8, u8, u8)>,
142 /// Outline colour, RGBA.
143 pub outline_color: Option<(u8, u8, u8, u8)>,
144 /// Box/shadow colour, RGBA.
145 pub back_color: Option<(u8, u8, u8, u8)>,
146 /// Bold.
147 pub bold: bool,
148 /// Italic.
149 pub italic: bool,
150 /// Underline.
151 pub underline: bool,
152 /// Strikeout.
153 pub strike: bool,
154 /// Alignment of the style's lines.
155 pub align: TextAlign,
156 /// Left margin.
157 pub margin_l: Option<i32>,
158 /// Right margin.
159 pub margin_r: Option<i32>,
160 /// Vertical margin.
161 pub margin_v: Option<i32>,
162 /// Outline thickness.
163 pub outline: Option<f32>,
164 /// Shadow depth.
165 pub shadow: Option<f32>,
166}
167
168impl SubtitleStyle {
169 /// An otherwise defaulted style called `name`.
170 pub fn new(name: impl Into<String>) -> SubtitleStyle {
171 SubtitleStyle {
172 name: name.into(),
173 ..SubtitleStyle::default()
174 }
175 }
176}
177
178/// One cue: when it is up, what it says, and how it was asked to be drawn.
179#[derive(Clone, Debug, Default, PartialEq)]
180pub struct SubtitleCue {
181 /// Start, microseconds from the start of the media.
182 pub start_us: i64,
183 /// End, microseconds from the start of the media. Never before
184 /// [`start_us`](Self::start_us): a backwards pair is clamped at parse.
185 pub end_us: i64,
186 /// The style this cue names, when the format has named styles.
187 pub style_ref: Option<String>,
188 /// Positioning the cue itself states.
189 pub positioning: Option<CuePosition>,
190 /// The body, as runs.
191 pub segments: Vec<Segment>,
192}
193
194/// Which on-disk flavour a track was parsed from.
195#[derive(Clone, Copy, Debug, PartialEq, Eq)]
196pub enum SourceFormat {
197 /// SubRip (`.srt`).
198 Srt,
199 /// WebVTT (`.vtt`).
200 WebVtt,
201 /// Advanced SubStation Alpha or its SSA predecessor.
202 AssOrSsa,
203}
204
205/// A parsed subtitle file: where it came from, its styles, its cues.
206#[derive(Clone, Debug, Default, PartialEq)]
207pub struct SubtitleTrack {
208 /// The flavour, when the parser knows it.
209 pub source: Option<SourceFormat>,
210 /// Named styles, in file order.
211 pub styles: Vec<SubtitleStyle>,
212 /// Cues, in file order — *not* sorted by time, because a file's own order
213 /// is information (an overlapping pair is a pair, not an error).
214 pub cues: Vec<SubtitleCue>,
215 /// Track-level keys: `title`, `play_res_x`, `wrap_style`, `header`, …
216 pub metadata: Vec<(String, String)>,
217 /// Header bytes worth replaying: the ASS script header, the WebVTT
218 /// preamble. What a Matroska `CodecPrivate` holds for this track.
219 pub extradata: Vec<u8>,
220 /// Blocks the parser could not read and skipped. Never an error on its own
221 /// — a file with one torn cue is still a file of cues — but a caller that
222 /// wants to say so has the count.
223 pub skipped: usize,
224}
225
226impl SubtitleTrack {
227 /// An empty track.
228 pub fn new() -> SubtitleTrack {
229 SubtitleTrack::default()
230 }
231
232 /// The same track, tagged with the format it was read from.
233 pub fn with_source(mut self, source: SourceFormat) -> SubtitleTrack {
234 self.source = Some(source);
235 self
236 }
237
238 /// A style by name.
239 pub fn style(&self, name: &str) -> Option<&SubtitleStyle> {
240 self.styles.iter().find(|s| s.name == name)
241 }
242}
243
244/// The words of a cue body, markup resolved and dropped: `\n` between lines,
245/// nothing at all for a run that is a drawing or an override this does not
246/// model.
247pub fn plain_text(segments: &[Segment]) -> String {
248 let mut out = String::new();
249 append_plain(segments, &mut out);
250 out
251}
252
253fn append_plain(segments: &[Segment], out: &mut String) {
254 for segment in segments {
255 match segment {
256 Segment::Text(s) => out.push_str(s),
257 Segment::LineBreak => out.push('\n'),
258 Segment::Bold(children)
259 | Segment::Italic(children)
260 | Segment::Underline(children)
261 | Segment::Strike(children) => append_plain(children, out),
262 Segment::Color { children, .. }
263 | Segment::Font { children, .. }
264 | Segment::Voice { children, .. }
265 | Segment::Class { children, .. }
266 | Segment::Karaoke { children, .. } => append_plain(children, out),
267 Segment::Timestamp { .. } | Segment::Raw(_) => {}
268 }
269 }
270}
271
272#[cfg(test)]
273mod tests {
274 use super::*;
275
276 #[test]
277 fn plain_text_walks_the_tree_and_drops_what_cannot_be_said() {
278 let segments = vec![
279 Segment::Italic(vec![Segment::Text("tilted".into())]),
280 Segment::Text(" and ".into()),
281 Segment::Color {
282 rgb: (255, 0, 0),
283 children: vec![Segment::Text("red".into())],
284 },
285 Segment::LineBreak,
286 Segment::Raw("{\\p1}m 0 0 l 1 1".into()),
287 Segment::Timestamp { offset_us: 5 },
288 Segment::Karaoke {
289 cs: 42,
290 start_cs: 0,
291 mode: KaraokeMode::Fill,
292 secondary: None,
293 children: vec![Segment::Text("ka".into())],
294 },
295 ];
296 assert_eq!(plain_text(&segments), "tilted and red\nka");
297 }
298}