1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
//! This crate implements a bare-bones WebVTT parser. It is missing a few
//! features, notably support for regions, styles, and most types of settings
//! that are applicable to cues.

use std::{iter::Peekable, time::Duration};

use thiserror::Error;

#[cfg(test)]
mod test;

#[derive(Error, Debug)]
pub enum Error {
    #[error("missing file magic")]
    NoMagic,

    #[error("bad file header")]
    BadHeader,

    #[error("unexpected end-of-file")]
    UnexpectedEof,
}

#[derive(Debug, Clone)]
pub struct File {
    pub description: Option<String>,
    pub blocks: Vec<Block>,
}

#[derive(Debug, Clone)]
pub enum Block {
    Cue(Cue),
}

#[derive(Default, Debug, Clone)]
pub struct Cue {
    pub start: Duration,
    pub end: Duration,
    pub id: String,
    pub text: String,
    pub settings: CueSettings,
}

#[derive(Clone, Debug, PartialEq, Eq, Hash, Default)]
pub struct CueSettings {
    pub region: Option<String>,
    pub writing_direction: WritingDirection,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
pub enum WritingDirection {
    /// horizontal (a line extends horizontally and is offset vertically from
    /// the video viewport’s top edge, with consecutive lines displayed below
    /// each other)
    #[default]
    Horizontal,
    /// vertical growing left (a line extends vertically and is offset
    /// horizontally from the video viewport’s right edge, with consecutive
    /// lines displayed to the left of each other)
    VerticalLeft,
    /// vertical growing right (a line extends vertically and is offset
    /// horizontally from the video viewport’s left edge, with consecutive lines
    /// displayed to the right of each other)
    VerticalRight,
}

struct FileContext {
    seen_cue: bool,
    in_header: bool,
}

/// Parses a string as a WebVTT file.
pub fn parse_file(input: &str) -> Result<File, Error> {
    use Error::*;

    let mut lines = input.split('\n').enumerate().peekable();

    let (_, line) = lines.next().ok_or(NoMagic)?;
    let line = expect_str(line, "WEBVTT", NoMagic)?;

    let description = if line.len() > 0 {
        let line = expect_char(line, &[' ', '\t'], BadHeader)?;
        Some(line.to_owned())
    } else {
        None
    };

    skip_blank_lines(&mut lines);

    let mut file_ctx = FileContext {
        in_header: false,
        seen_cue: false,
    };

    let mut blocks = vec![];

    while lines.peek().is_some() {
        if let Some(block) = parse_block(&mut lines, &mut file_ctx) {
            blocks.push(block);
        }

        skip_blank_lines(&mut lines);
    }

    Ok(File {
        description,
        blocks,
    })
}

struct BlockContext {
    line_count: usize,
    seen_eof: bool,
    seen_arrow: bool,
    cue: Option<Cue>,
    buffer: String,
}

fn parse_block<'a, I: Iterator<Item = (usize, &'a str)>>(
    lines: &mut Peekable<I>,
    file_ctx: &mut FileContext,
) -> Option<Block> {
    let mut block_ctx = BlockContext {
        line_count: 0,
        seen_arrow: false,
        seen_eof: false,

        cue: None,
        buffer: String::new(),
    };

    while let Some((_, line)) = lines.next() {
        block_ctx.line_count += 1;
        block_ctx.seen_eof = lines.peek().is_none();

        if line.contains("-->") {
            if !file_ctx.in_header {
                if (block_ctx.line_count == 1)
                    || (block_ctx.line_count == 2 && !block_ctx.seen_arrow)
                {
                    block_ctx.seen_arrow = true;

                    if let Some((start, end, settings)) = parse_cue_timings_settings(line) {
                        let buffer = std::mem::replace(&mut block_ctx.buffer, String::new());

                        let cue = Cue {
                            id: buffer,
                            start,
                            end,
                            settings,
                            ..Default::default()
                        };

                        block_ctx.cue = Some(cue);
                    }
                }
            }
        } else if line.is_empty() {
            break;
        } else {
            if !file_ctx.in_header && block_ctx.line_count == 2 {
                if !file_ctx.seen_cue {
                    if block_ctx.buffer.starts_with("STYLE") {
                        unimplemented!("WebVTT styles are unimplemented")
                    }

                    if block_ctx.buffer.starts_with("REGION") {
                        unimplemented!("WebVTT regions are unimplemented")
                    }
                }
            }

            if !block_ctx.buffer.is_empty() {
                block_ctx.buffer.push('\n');
            }

            block_ctx.buffer.push_str(line);
        }
    }

    if let Some(mut cue) = block_ctx.cue {
        cue.text = block_ctx.buffer;
        Some(Block::Cue(cue))
    } else {
        None
    }
}

fn parse_cue_timings_settings(line: &str) -> Option<(Duration, Duration, CueSettings)> {
    let line = line.trim_start();
    let (start_time, line) = parse_timestamp(line)?;

    let line = line.trim_start();
    let line = line.strip_prefix("-->")?;
    let line = line.trim_start();

    let (end_time, line) = parse_timestamp(line)?;
    let settings = parse_settings(line);

    Some((start_time, end_time, settings))
}

fn parse_settings(line: &str) -> CueSettings {
    let mut settings = CueSettings {
        region: None,
        writing_direction: WritingDirection::Horizontal,
    };

    for setting in line.split(' ') {
        if let Some((key, value)) = setting.split_once(':') {
            if key == "" || value == "" {
                continue;
            }

            match key {
                "region" => {
                    settings.region = Some(value.to_owned());
                }
                "vertical" => match value {
                    "lr" => settings.writing_direction = WritingDirection::VerticalLeft,
                    "rl" => settings.writing_direction = WritingDirection::VerticalRight,
                    _ => {}
                },
                _ => {}
            }
        }
    }

    // there are no vertical regions
    if settings.writing_direction != WritingDirection::Horizontal {
        settings.region = None;
    }

    settings
}

/// Parses a timestamp from the given string. Returns a Duration that represents
/// the timestamp's offset from the zero, and the remainder of the string after
/// skipping the timestamp.
fn parse_timestamp(line: &str) -> Option<(Duration, &str)> {
    let mut has_hours = false;
    let mut buf = String::new();
    let mut places: Vec<u64> = vec![];

    let (mut last_idx, mut last_char);
    let mut chars = line.char_indices();

    // parse digits if there are any
    loop {
        let (_, char) = chars.next()?;
        last_char = char;

        if char.is_ascii_digit() {
            buf.push(char);
        } else {
            break;
        }
    }

    // if there were no digits, or we hit something that isn't ':', error
    if buf.is_empty() || last_char != ':' {
        return None;
    }

    let num = buf.parse().unwrap();

    // this could either be the hours place or the minutes place
    places.push(num);

    if num > 59 || buf.len() != 2 {
        has_hours = true;
    }

    buf.clear();

    // parse out some digits again
    loop {
        let (_, char) = chars.next()?;
        last_char = char;

        if char.is_ascii_digit() {
            buf.push(char);
        } else {
            break;
        }
    }

    // if we didn't get a 2-digit number, error
    if buf.len() != 2 {
        return None;
    }

    let num = buf.parse().unwrap();

    if num > 59 {
        return None;
    }

    places.push(num);

    buf.clear();

    // if we have an hours place, or we hit another colon, parse out another
    // 2-digit number
    if has_hours || last_char == ':' {
        // parse out some digits again
        loop {
            let (_, char) = chars.next()?;
            last_char = char;

            if char.is_ascii_digit() {
                buf.push(char);
            } else {
                break;
            }
        }

        // if we didn't get a 2-digit number, error
        if buf.len() != 2 {
            return None;
        }

        let num = buf.parse().unwrap();

        if num > 59 {
            return None;
        }

        places.push(num);

        buf.clear();
    }

    // if we hit a decimal point, we have a fractional number of seconds
    if last_char != '.' {
        return None;
    }

    // parse out some digits again
    loop {
        if let Some((idx, char)) = chars.next() {
            last_idx = idx;

            if char.is_ascii_digit() {
                buf.push(char);
            } else {
                break;
            }
        } else {
            last_idx = line.len();
            break;
        }
    }

    // if we didn't get a 3-digit number, error
    if buf.len() != 3 {
        return None;
    }

    places.push(buf.parse().unwrap());

    Some((
        match &places[..] {
            &[hours, minutes, seconds, millis] => {
                Duration::from_millis(millis + seconds * 1000 + minutes * 60_000 + hours * 3600_000)
            }
            &[minutes, seconds, millis] => {
                Duration::from_millis(millis + seconds * 1000 + minutes * 60_000)
            }
            _ => unreachable!(),
        },
        &line[last_idx..],
    ))
}

fn skip_blank_lines<'a, I: Iterator<Item = (usize, &'a str)>>(lines: &mut Peekable<I>) {
    loop {
        match lines.peek() {
            Some((_, line)) => {
                if !line.is_empty() {
                    break;
                }

                lines.next();
            }
            None => break,
        }
    }
}

fn expect_str<'a>(input: &'a str, pattern: &str, error: Error) -> Result<&'a str, Error> {
    input.strip_prefix(pattern).ok_or(error)
}

fn expect_pred<'a, F: FnMut(char) -> bool>(
    input: &'a str,
    pattern: F,
    error: Error,
) -> Result<&'a str, Error> {
    input.strip_prefix(pattern).ok_or(error)
}

fn expect_char<'a>(input: &'a str, pattern: &[char], error: Error) -> Result<&'a str, Error> {
    input.strip_prefix(pattern).ok_or(error)
}