-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebvttparser.cc
702 lines (492 loc) · 15 KB
/
webvttparser.cc
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
// Copyright (c) 2012 The WebM project authors. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS. All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.
#include "./webvttparser.h" // NOLINT
#include <climits>
namespace libwebvtt {
// NOLINT'ing this enum because clang-format puts it in a single line which
// makes it look really unreadable.
enum {
kNUL = '\x00',
kSPACE = ' ',
kTAB = '\x09',
kLF = '\x0A',
kCR = '\x0D'
}; // NOLINT
Reader::~Reader() {}
LineReader::~LineReader() {}
int LineReader::GetLine(std::string* line_ptr) {
if (line_ptr == NULL)
return -1;
std::string& ln = *line_ptr;
ln.clear();
// Consume characters from the stream, until we
// reach end-of-line (or end-of-stream).
// The WebVTT spec states that lines may be
// terminated in any of these three ways:
// LF
// CR
// CR LF
// We interrogate each character as we read it from the stream.
// If we detect an end-of-line character, we consume the full
// end-of-line indication, and we're done; otherwise, accumulate
// the character and repeat.
for (;;) {
char c;
const int e = GetChar(&c);
if (e < 0) // error
return e;
if (e > 0) // EOF
return (ln.empty()) ? 1 : 0;
// We have a character, so we must first determine
// whether we have reached end-of-line.
if (c == kLF)
return 0; // handle the easy end-of-line case immediately
if (c == kCR)
break; // handle the hard end-of-line case outside of loop
if (c == '\xFE' || c == '\xFF') // not UTF-8
return -1;
// To defend against pathological or malicious streams, we
// cap the line length at some arbitrarily-large value:
enum { kMaxLineLength = 10000 }; // arbitrary
if (ln.length() >= kMaxLineLength)
return -1;
// We don't have an end-of-line character, so accumulate
// the character in our line buffer.
ln.push_back(c);
}
// We detected a CR. We must interrogate the next character
// in the stream, to determine whether we have a LF (which
// would make it part of this same line).
char c;
const int e = GetChar(&c);
if (e < 0) // error
return e;
if (e > 0) // EOF
return 0;
// If next character in the stream is not a LF, return it
// to the stream (because it's part of the next line).
if (c != kLF)
UngetChar(c);
return 0;
}
Parser::Parser(Reader* r) : reader_(r), unget_(-1) {}
Parser::~Parser() {}
int Parser::Init() {
int e = ParseBOM();
if (e < 0) // error
return e;
if (e > 0) // EOF
return -1;
// Parse "WEBVTT". We read from the stream one character at-a-time, in
// order to defend against non-WebVTT streams (e.g. binary files) that don't
// happen to comprise lines of text demarcated with line terminators.
const char kId[] = "WEBVTT";
for (const char* p = kId; *p; ++p) {
char c;
e = GetChar(&c);
if (e < 0) // error
return e;
if (e > 0) // EOF
return -1;
if (c != *p)
return -1;
}
std::string line;
e = GetLine(&line);
if (e < 0) // error
return e;
if (e > 0) // EOF
return 0; // weird but valid
if (!line.empty()) {
// Parse optional characters that follow "WEBVTT"
const char c = line[0];
if (c != kSPACE && c != kTAB)
return -1;
}
// The WebVTT spec requires that the "WEBVTT" line
// be followed by an empty line (to separate it from
// first cue).
e = GetLine(&line);
if (e < 0) // error
return e;
if (e > 0) // EOF
return 0; // weird but we allow it
if (!line.empty())
return -1;
return 0; // success
}
int Parser::Parse(Cue* cue) {
if (cue == NULL)
return -1;
// Parse first non-blank line
std::string line;
int e;
for (;;) {
e = GetLine(&line);
if (e) // EOF is OK here
return e;
if (!line.empty())
break;
}
// A WebVTT cue comprises an optional cue identifier line followed
// by a (non-optional) timings line. You determine whether you have
// a timings line by scanning for the arrow token, the lexeme of which
// may not appear in the cue identifier line.
const char kArrow[] = "-->";
std::string::size_type arrow_pos = line.find(kArrow);
if (arrow_pos != std::string::npos) {
// We found a timings line, which implies that we don't have a cue
// identifier.
cue->identifier.clear();
} else {
// We did not find a timings line, so we assume that we have a cue
// identifier line, and then try again to find the cue timings on
// the next line.
cue->identifier.swap(line);
e = GetLine(&line);
if (e < 0) // error
return e;
if (e > 0) // EOF
return -1;
arrow_pos = line.find(kArrow);
if (arrow_pos == std::string::npos) // not a timings line
return -1;
}
e = ParseTimingsLine(&line, arrow_pos, &cue->start_time, &cue->stop_time,
&cue->settings);
if (e) // error
return e;
// The cue payload comprises all the non-empty
// lines that follow the timings line.
Cue::payload_t& p = cue->payload;
p.clear();
for (;;) {
e = GetLine(&line);
if (e < 0) // error
return e;
if (line.empty())
break;
p.push_back(line);
}
if (p.empty())
return -1;
return 0; // success
}
int Parser::GetChar(char* c) {
if (unget_ >= 0) {
*c = static_cast<char>(unget_);
unget_ = -1;
return 0;
}
return reader_->GetChar(c);
}
void Parser::UngetChar(char c) { unget_ = static_cast<unsigned char>(c); }
int Parser::ParseBOM() {
// Explanation of UTF-8 BOM:
// http://en.wikipedia.org/wiki/Byte_order_mark
static const char BOM[] = "\xEF\xBB\xBF"; // UTF-8 BOM
for (int i = 0; i < 3; ++i) {
char c;
int e = GetChar(&c);
if (e < 0) // error
return e;
if (e > 0) // EOF
return 1;
if (c != BOM[i]) {
if (i == 0) { // we don't have a BOM
UngetChar(c);
return 0; // success
}
// We started a BOM, so we must finish the BOM.
return -1; // error
}
}
return 0; // success
}
int Parser::ParseTimingsLine(std::string* line_ptr,
std::string::size_type arrow_pos, Time* start_time,
Time* stop_time, Cue::settings_t* settings) {
if (line_ptr == NULL)
return -1;
std::string& line = *line_ptr;
if (arrow_pos == std::string::npos || arrow_pos >= line.length())
return -1;
// Place a NUL character at the start of the arrow token, in
// order to demarcate the start time from remainder of line.
line[arrow_pos] = kNUL;
std::string::size_type idx = 0;
int e = ParseTime(line, &idx, start_time);
if (e) // error
return e;
// Detect any junk that follows the start time,
// but precedes the arrow symbol.
while (char c = line[idx]) {
if (c != kSPACE && c != kTAB)
return -1;
++idx;
}
// Place a NUL character at the end of the line,
// so the scanner has a place to stop, and begin
// the scan just beyond the arrow token.
line.push_back(kNUL);
idx = arrow_pos + 3;
e = ParseTime(line, &idx, stop_time);
if (e) // error
return e;
e = ParseSettings(line, idx, settings);
if (e) // error
return e;
return 0; // success
}
int Parser::ParseTime(const std::string& line, std::string::size_type* idx_ptr,
Time* time) {
if (idx_ptr == NULL)
return -1;
std::string::size_type& idx = *idx_ptr;
if (idx == std::string::npos || idx >= line.length())
return -1;
if (time == NULL)
return -1;
// Consume any whitespace that precedes the timestamp.
while (char c = line[idx]) {
if (c != kSPACE && c != kTAB)
break;
++idx;
}
// WebVTT timestamp syntax comes in three flavors:
// SS[.sss]
// MM:SS[.sss]
// HH:MM:SS[.sss]
// Parse a generic number value. We don't know which component
// of the time we have yet, until we do more parsing.
int val = ParseNumber(line, &idx);
if (val < 0) // error
return val;
Time& t = *time;
// The presence of a colon character indicates that we have
// an [HH:]MM:SS style syntax.
if (line[idx] == ':') {
// We have either HH:MM:SS or MM:SS
// The value we just parsed is either the hours or minutes.
// It must be followed by another number value (that is
// either minutes or seconds).
const int first_val = val;
++idx; // consume colon
// Parse second value
val = ParseNumber(line, &idx);
if (val < 0)
return val;
if (val >= 60) // either MM or SS
return -1;
if (line[idx] == ':') {
// We have HH:MM:SS
t.hours = first_val;
t.minutes = val; // vetted above
++idx; // consume MM:SS colon
// We have parsed the hours and minutes.
// We must now parse the seconds.
val = ParseNumber(line, &idx);
if (val < 0)
return val;
if (val >= 60) // SS part of HH:MM:SS
return -1;
t.seconds = val;
} else {
// We have MM:SS
// The implication here is that the hour value was omitted
// from the timestamp (because it was 0).
if (first_val >= 60) // minutes
return -1;
t.hours = 0;
t.minutes = first_val;
t.seconds = val; // vetted above
}
} else {
// We have SS (only)
// The time is expressed as total number of seconds,
// so the seconds value has no upper bound.
t.seconds = val;
// Convert SS to HH:MM:SS
t.minutes = t.seconds / 60;
t.seconds -= t.minutes * 60;
t.hours = t.minutes / 60;
t.minutes -= t.hours * 60;
}
// We have parsed the hours, minutes, and seconds.
// We must now parse the milliseconds.
char c = line[idx];
// TODO(matthewjheaney): one option here is to slightly relax the
// syntax rules for WebVTT timestamps, to permit the comma character
// to also be used as the seconds/milliseconds separator. This
// would handle streams that use localization conventions for
// countries in Western Europe. For now we obey the rules specified
// in the WebVTT spec (allow "full stop" only).
const bool have_milliseconds = (c == '.');
if (!have_milliseconds) {
t.milliseconds = 0;
} else {
++idx; // consume FULL STOP
val = ParseNumber(line, &idx);
if (val < 0)
return val;
if (val >= 1000)
return -1;
if (val < 10)
t.milliseconds = val * 100;
else if (val < 100)
t.milliseconds = val * 10;
else
t.milliseconds = val;
}
// We have parsed the time proper. We must check for any
// junk that immediately follows the time specifier.
c = line[idx];
if (c != kNUL && c != kSPACE && c != kTAB)
return -1;
return 0; // success
}
int Parser::ParseSettings(const std::string& line, std::string::size_type idx,
Cue::settings_t* settings) {
settings->clear();
if (idx == std::string::npos || idx >= line.length())
return -1;
for (;;) {
// We must parse a line comprising a sequence of 0 or more
// NAME:VALUE pairs, separated by whitespace. The line iself is
// terminated with a NUL char (indicating end-of-line).
for (;;) {
const char c = line[idx];
if (c == kNUL) // end-of-line
return 0; // success
if (c != kSPACE && c != kTAB)
break;
++idx; // consume whitespace
}
// We have consumed the whitespace, and have not yet reached
// end-of-line, so there is something on the line for us to parse.
settings->push_back(Setting());
Setting& s = settings->back();
// Parse the NAME part of the settings pair.
for (;;) {
const char c = line[idx];
if (c == ':') // we have reached end of NAME part
break;
if (c == kNUL || c == kSPACE || c == kTAB)
return -1;
s.name.push_back(c);
++idx;
}
if (s.name.empty())
return -1;
++idx; // consume colon
// Parse the VALUE part of the settings pair.
for (;;) {
const char c = line[idx];
if (c == kNUL || c == kSPACE || c == kTAB)
break;
if (c == ':') // suspicious when part of VALUE
return -1; // TODO(matthewjheaney): verify this behavior
s.value.push_back(c);
++idx;
}
if (s.value.empty())
return -1;
}
}
int Parser::ParseNumber(const std::string& line,
std::string::size_type* idx_ptr) {
if (idx_ptr == NULL)
return -1;
std::string::size_type& idx = *idx_ptr;
if (idx == std::string::npos || idx >= line.length())
return -1;
if (!isdigit(line[idx]))
return -1;
int result = 0;
while (isdigit(line[idx])) {
const char c = line[idx];
const int i = c - '0';
if (result > INT_MAX / 10)
return -1;
result *= 10;
if (result > INT_MAX - i)
return -1;
result += i;
++idx;
}
return result;
}
bool Time::operator==(const Time& rhs) const {
if (hours != rhs.hours)
return false;
if (minutes != rhs.minutes)
return false;
if (seconds != rhs.seconds)
return false;
return (milliseconds == rhs.milliseconds);
}
bool Time::operator<(const Time& rhs) const {
if (hours < rhs.hours)
return true;
if (hours > rhs.hours)
return false;
if (minutes < rhs.minutes)
return true;
if (minutes > rhs.minutes)
return false;
if (seconds < rhs.seconds)
return true;
if (seconds > rhs.seconds)
return false;
return (milliseconds < rhs.milliseconds);
}
bool Time::operator>(const Time& rhs) const { return rhs.operator<(*this); }
bool Time::operator<=(const Time& rhs) const { return !this->operator>(rhs); }
bool Time::operator>=(const Time& rhs) const { return !this->operator<(rhs); }
presentation_t Time::presentation() const {
const presentation_t h = 1000LL * 3600LL * presentation_t(hours);
const presentation_t m = 1000LL * 60LL * presentation_t(minutes);
const presentation_t s = 1000LL * presentation_t(seconds);
const presentation_t result = h + m + s + milliseconds;
return result;
}
Time& Time::presentation(presentation_t d) {
if (d < 0) { // error
hours = 0;
minutes = 0;
seconds = 0;
milliseconds = 0;
return *this;
}
seconds = static_cast<int>(d / 1000);
milliseconds = static_cast<int>(d - 1000 * seconds);
minutes = seconds / 60;
seconds -= 60 * minutes;
hours = minutes / 60;
minutes -= 60 * hours;
return *this;
}
Time& Time::operator+=(presentation_t rhs) {
const presentation_t d = this->presentation();
const presentation_t dd = d + rhs;
this->presentation(dd);
return *this;
}
Time Time::operator+(presentation_t d) const {
Time t(*this);
t += d;
return t;
}
Time& Time::operator-=(presentation_t d) { return this->operator+=(-d); }
presentation_t Time::operator-(const Time& t) const {
const presentation_t rhs = t.presentation();
const presentation_t lhs = this->presentation();
const presentation_t result = lhs - rhs;
return result;
}
} // namespace libwebvtt