forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB00c1b3fTahinli2 months ago1999 commits

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