Shaka Packager SDK
Loading...
Searching...
No Matches
text_readers.cc
1// Copyright 2017 Google LLC. All rights reserved.
2//
3// Use of this source code is governed by a BSD-style
4// license that can be found in the LICENSE file or at
5// https://developers.google.com/open-source/licenses/bsd
6
7#include <packager/media/formats/webvtt/text_readers.h>
8
9#include <cstring>
10
11#include <absl/log/check.h>
12#include <absl/log/log.h>
13
14namespace shaka {
15namespace media {
16
17LineReader::LineReader() : should_flush_(false) {}
18
19void LineReader::PushData(const uint8_t* data, size_t data_size) {
20 buffer_.Push(data, static_cast<int>(data_size));
21 should_flush_ = false;
22}
23
24// Split lines based on https://w3c.github.io/webvtt/#webvtt-line-terminator
25bool LineReader::Next(std::string* out) {
26 DCHECK(out);
27
28 int i;
29 int skip = 0;
30 const uint8_t* data;
31 int data_size;
32 buffer_.Peek(&data, &data_size);
33 for (i = 0; i < data_size; i++) {
34 // Handle \n
35 if (data[i] == '\n') {
36 skip = 1;
37 break;
38 }
39
40 // Handle \r and \r\n
41 if (data[i] == '\r') {
42 // Only read if we can see the next character; this ensures we don't get
43 // the '\n' in the next PushData.
44 if (i + 1 == data_size) {
45 if (!should_flush_)
46 return false;
47 skip = 1;
48 } else {
49 if (data[i + 1] == '\n')
50 skip = 2;
51 else
52 skip = 1;
53 }
54 break;
55 }
56 }
57
58 if (i == data_size && (!should_flush_ || i == 0)) {
59 return false;
60 }
61
62 // TODO(modmaker): Handle character encodings?
63 out->assign(data, data + i);
64 buffer_.Pop(i + skip);
65 return true;
66}
67
68void LineReader::Flush() {
69 should_flush_ = true;
70}
71
72BlockReader::BlockReader() : should_flush_(false) {}
73
74void BlockReader::PushData(const uint8_t* data, size_t data_size) {
75 source_.PushData(data, data_size);
76 should_flush_ = false;
77}
78
79bool BlockReader::Next(std::vector<std::string>* out) {
80 DCHECK(out);
81
82 bool end_block = false;
83 // Read through lines until a non-empty line is found. With a non-empty
84 // line is found, start adding the lines to the output and once an empty
85 // line if found again, stop adding lines and exit.
86 std::string line;
87 while (source_.Next(&line)) {
88 if (!temp_.empty() && line.empty()) {
89 end_block = true;
90 break;
91 }
92 if (!line.empty()) {
93 temp_.emplace_back(std::move(line));
94 }
95 }
96
97 if (!end_block && (!should_flush_ || temp_.empty()))
98 return false;
99
100 *out = std::move(temp_);
101 return true;
102}
103
105 source_.Flush();
106 should_flush_ = true;
107}
108
109} // namespace media
110} // namespace shaka
void PushData(const uint8_t *data, size_t data_size)
Pushes data onto the end of the buffer.
bool Next(std::vector< std::string > *out)
bool Next(std::string *out)
void PushData(const uint8_t *data, size_t data_size)
Pushes data onto the end of the buffer.
All the methods that are virtual are virtual for mocking.