Welcome to mirror list, hosted at ThFree Co, Russian Federation.

parser.rs « scc_parse « src « closedcaption « video - gitlab.freedesktop.org/gstreamer/gst-plugins-rs.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 26c167e5742ec56d4935b38c007e867c25faa805 (plain)
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
// Copyright (C) 2019,2020 Sebastian Dröge <sebastian@centricular.com>
// Copyright (C) 2019 Jordan Petridis <jordan@centricular.com>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Library General Public License for more details.
//
// You should have received a copy of the GNU Library General Public
// License along with this library; if not, write to the
// Free Software Foundation, Inc., 51 Franklin Street, Suite 500,
// Boston, MA 02110-1335, USA.

use crate::parser_utils::{end_of_line, timecode, TimeCode};
use nom::IResult;

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SccLine {
    Header,
    Empty,
    Caption(TimeCode, Vec<u8>),
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum State {
    Header,
    Empty,
    CaptionOrEmpty,
}

#[derive(Debug)]
pub struct SccParser {
    state: State,
}

/// Parser for the SCC header
fn header(s: &[u8]) -> IResult<&[u8], SccLine> {
    use nom::bytes::complete::tag;
    use nom::combinator::{map, opt};
    use nom::error::context;
    use nom::sequence::tuple;

    context(
        "invalid header",
        map(
            tuple((
                opt(tag(&[0xEFu8, 0xBBu8, 0xBFu8][..])),
                tag("Scenarist_SCC V1.0"),
                end_of_line,
            )),
            |_| SccLine::Header,
        ),
    )(s)
}

/// Parser that accepts only an empty line
fn empty_line(s: &[u8]) -> IResult<&[u8], SccLine> {
    use nom::combinator::map;
    use nom::error::context;

    context("invalid empty line", map(end_of_line, |_| SccLine::Empty))(s)
}

/// A single SCC payload item. This is ASCII hex encoded bytes.
/// It returns an tuple of `(u8, u8)` of the hex encoded bytes.
fn scc_payload_item(s: &[u8]) -> IResult<&[u8], (u8, u8)> {
    use nom::bytes::complete::take_while_m_n;
    use nom::character::is_hex_digit;
    use nom::combinator::map;
    use nom::error::context;

    context(
        "invalid SCC payload item",
        map(take_while_m_n(4, 4, is_hex_digit), |s: &[u8]| {
            let hex_to_u8 = |v: u8| match v {
                v if v >= b'0' && v <= b'9' => v - b'0',
                v if v >= b'A' && v <= b'F' => 10 + v - b'A',
                v if v >= b'a' && v <= b'f' => 10 + v - b'a',
                _ => unreachable!(),
            };

            let val1 = (hex_to_u8(s[0]) << 4) | hex_to_u8(s[1]);
            let val2 = (hex_to_u8(s[2]) << 4) | hex_to_u8(s[3]);

            (val1, val2)
        }),
    )(s)
}

/// Parser for the whole SCC payload with conversion to the underlying byte values.
fn scc_payload(s: &[u8]) -> IResult<&[u8], Vec<u8>> {
    use nom::branch::alt;
    use nom::bytes::complete::tag;
    use nom::combinator::map;
    use nom::error::context;
    use nom::multi::fold_many1;
    use nom::sequence::pair;
    use nom::Parser;

    let parse_item = map(
        pair(scc_payload_item, alt((tag(" ").map(|_| ()), end_of_line))),
        |(item, _)| item,
    );

    context(
        "invalid SCC payload",
        fold_many1(parse_item, Vec::new(), |mut acc: Vec<_>, item| {
            acc.push(item.0);
            acc.push(item.1);
            acc
        }),
    )(s)
}

/// Parser for a SCC caption line in the form `timecode\tpayload`.
fn caption(s: &[u8]) -> IResult<&[u8], SccLine> {
    use nom::bytes::complete::tag;
    use nom::combinator::map;
    use nom::error::context;
    use nom::sequence::tuple;

    context(
        "invalid SCC caption line",
        map(
            tuple((timecode, tag("\t"), scc_payload, end_of_line)),
            |(tc, _, value, _)| SccLine::Caption(tc, value),
        ),
    )(s)
}

/// SCC parser the parses line-by-line and keeps track of the current state in the file.
impl SccParser {
    pub fn new() -> Self {
        Self {
            state: State::Header,
        }
    }

    pub fn new_scan_captions() -> Self {
        Self {
            state: State::CaptionOrEmpty,
        }
    }

    pub fn reset(&mut self) {
        self.state = State::Header;
    }

    pub fn parse_line<'a>(
        &mut self,
        line: &'a [u8],
    ) -> Result<SccLine, nom::error::Error<&'a [u8]>> {
        use nom::branch::alt;

        match self.state {
            State::Header => header(line)
                .map(|v| {
                    self.state = State::Empty;
                    v.1
                })
                .map_err(|err| match err {
                    nom::Err::Incomplete(_) => unreachable!(),
                    nom::Err::Error(e) | nom::Err::Failure(e) => e,
                }),
            State::Empty => empty_line(line)
                .map(|v| {
                    self.state = State::CaptionOrEmpty;
                    v.1
                })
                .map_err(|err| match err {
                    nom::Err::Incomplete(_) => unreachable!(),
                    nom::Err::Error(e) | nom::Err::Failure(e) => e,
                }),
            State::CaptionOrEmpty => alt((caption, empty_line))(line)
                .map(|v| v.1)
                .map_err(|err| match err {
                    nom::Err::Incomplete(_) => unreachable!(),
                    nom::Err::Error(e) | nom::Err::Failure(e) => e,
                }),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_header() {
        assert_eq!(
            header(b"Scenarist_SCC V1.0".as_ref()),
            Ok((b"".as_ref(), SccLine::Header,))
        );

        assert_eq!(
            header(b"Scenarist_SCC V1.0\n".as_ref()),
            Ok((b"".as_ref(), SccLine::Header))
        );

        assert_eq!(
            header(b"Scenarist_SCC V1.0\r\n".as_ref()),
            Ok((b"".as_ref(), SccLine::Header))
        );

        assert_eq!(
            header(b"Scenarist_SCC V1.1".as_ref()),
            Err(nom::Err::Error(nom::error::Error::new(
                b"Scenarist_SCC V1.1".as_ref(),
                nom::error::ErrorKind::Tag
            ))),
        );
    }

    #[test]
    fn test_empty_line() {
        assert_eq!(empty_line(b"".as_ref()), Ok((b"".as_ref(), SccLine::Empty)));

        assert_eq!(
            empty_line(b"\n".as_ref()),
            Ok((b"".as_ref(), SccLine::Empty))
        );

        assert_eq!(
            empty_line(b"\r\n".as_ref()),
            Ok((b"".as_ref(), SccLine::Empty))
        );

        assert_eq!(
            empty_line(b" \r\n".as_ref()),
            Err(nom::Err::Error(nom::error::Error::new(
                b" \r\n".as_ref(),
                nom::error::ErrorKind::Eof
            ))),
        );
    }

    #[test]
    fn test_caption() {
        assert_eq!(
            caption(b"01:02:53:14\t94ae 94ae 9420 9420 947a 947a 97a2 97a2 a820 68ef f26e 2068 ef6e 6be9 6e67 2029 942c 942c 8080 8080 942f 942f".as_ref()),
            Ok((
                b"".as_ref(),
                SccLine::Caption(
                    TimeCode {
                        hours: 1,
                        minutes: 2,
                        seconds: 53,
                        frames: 14,
                        drop_frame: false
                    },

                    vec![
                        0x94, 0xae, 0x94, 0xae, 0x94, 0x20, 0x94, 0x20, 0x94, 0x7a, 0x94, 0x7a, 0x97, 0xa2,
                        0x97, 0xa2, 0xa8, 0x20, 0x68, 0xef, 0xf2, 0x6e, 0x20, 0x68, 0xef, 0x6e, 0x6b, 0xe9,
                        0x6e, 0x67, 0x20, 0x29, 0x94, 0x2c, 0x94, 0x2c, 0x80, 0x80, 0x80, 0x80, 0x94, 0x2f,
                        0x94, 0x2f,
                    ]
                ),
            ))
        );

        assert_eq!(
            caption(b"01:02:55;14	942c 942c".as_ref()),
            Ok((
                b"".as_ref(),
                SccLine::Caption(
                    TimeCode {
                        hours: 1,
                        minutes: 2,
                        seconds: 55,
                        frames: 14,
                        drop_frame: true
                    },
                    vec![0x94, 0x2c, 0x94, 0x2c]
                ),
            ))
        );

        assert_eq!(
            caption(b"01:03:27:29	94ae 94ae 9420 9420 94f2 94f2 c845 d92c 2054 c845 5245 ae80 942c 942c 8080 8080 942f 942f".as_ref()),
            Ok((
                b"".as_ref(),
                SccLine::Caption(
                    TimeCode {
                        hours: 1,
                        minutes: 3,
                        seconds: 27,
                        frames: 29,
                        drop_frame: false
                    },
                    vec![
                        0x94, 0xae, 0x94, 0xae, 0x94, 0x20, 0x94, 0x20, 0x94, 0xf2, 0x94, 0xf2, 0xc8, 0x45,
                        0xd9, 0x2c, 0x20, 0x54, 0xc8, 0x45, 0x52, 0x45, 0xae, 0x80, 0x94, 0x2c, 0x94, 0x2c,
                        0x80, 0x80, 0x80, 0x80, 0x94, 0x2f, 0x94, 0x2f,
                    ]
                ),
            ))
        );

        assert_eq!(
            caption(b"00:00:00;00\t942c 942c".as_ref()),
            Ok((
                b"".as_ref(),
                SccLine::Caption(
                    TimeCode {
                        hours: 0,
                        minutes: 0,
                        seconds: 00,
                        frames: 00,
                        drop_frame: true,
                    },
                    vec![0x94, 0x2c, 0x94, 0x2c],
                ),
            ))
        );

        assert_eq!(
            caption(b"00:00:00;00\t942c 942c\r\n".as_ref()),
            Ok((
                b"".as_ref(),
                SccLine::Caption(
                    TimeCode {
                        hours: 0,
                        minutes: 0,
                        seconds: 00,
                        frames: 00,
                        drop_frame: true,
                    },
                    vec![0x94, 0x2c, 0x94, 0x2c],
                ),
            ))
        );
    }

    #[test]
    fn test_parser() {
        let scc_file = include_bytes!("../../tests/dn2018-1217.scc");
        let mut reader = crate::line_reader::LineReader::new();
        let mut parser = SccParser::new();
        let mut line_cnt = 0;

        reader.push(Vec::from(scc_file.as_ref()));

        while let Some(line) = reader.line() {
            let res = match parser.parse_line(line) {
                Ok(res) => res,
                Err(err) => panic!("Couldn't parse line {}: {:?}", line_cnt, err),
            };

            match line_cnt {
                0 => assert_eq!(res, SccLine::Header),
                x if x % 2 != 0 => assert_eq!(res, SccLine::Empty),
                _ => match res {
                    SccLine::Caption(_, _) => (),
                    res => panic!("Expected caption at line {}, got {:?}", line_cnt, res),
                },
            }

            line_cnt += 1;
        }
    }
}