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 <cstdint>
10#include <cstring>
11#include <string>
12#include <utility>
13#include <vector>
14
15#include <absl/log/check.h>
16
17namespace shaka {
18namespace media {
19
20LineReader::LineReader() : should_flush_(false) {}
21
22void LineReader::PushData(const uint8_t* data, size_t data_size) {
23 buffer_.Push(data, static_cast<int>(data_size));
24 should_flush_ = false;
25}
26
27// Split lines based on https://w3c.github.io/webvtt/#webvtt-line-terminator
28bool LineReader::Next(std::string* out) {
29 DCHECK(out);
30
31 int i;
32 int skip = 0;
33 const uint8_t* data;
34 int data_size;
35 buffer_.Peek(&data, &data_size);
36 for (i = 0; i < data_size; i++) {
37 // Handle \n
38 if (data[i] == '\n') {
39 skip = 1;
40 break;
41 }
42
43 // Handle \r and \r\n
44 if (data[i] == '\r') {
45 // Only read if we can see the next character; this ensures we don't get
46 // the '\n' in the next PushData.
47 if (i + 1 == data_size) {
48 if (!should_flush_)
49 return false;
50 skip = 1;
51 } else {
52 if (data[i + 1] == '\n')
53 skip = 2;
54 else
55 skip = 1;
56 }
57 break;
58 }
59 }
60
61 if (i == data_size && (!should_flush_ || i == 0)) {
62 return false;
63 }
64
65 // TODO(modmaker): Handle character encodings?
66 out->assign(data, data + i);
67 buffer_.Pop(i + skip);
68 return true;
69}
70
71void LineReader::Flush() {
72 should_flush_ = true;
73}
74
75BlockReader::BlockReader() : should_flush_(false) {}
76
77void BlockReader::PushData(const uint8_t* data, size_t data_size) {
78 source_.PushData(data, data_size);
79 should_flush_ = false;
80}
81
82bool BlockReader::Next(std::vector<std::string>* out) {
83 DCHECK(out);
84
85 bool end_block = false;
86 // Read through lines until a non-empty line is found. With a non-empty
87 // line is found, start adding the lines to the output and once an empty
88 // line if found again, stop adding lines and exit.
89 std::string line;
90 while (source_.Next(&line)) {
91 if (!temp_.empty() && line.empty()) {
92 end_block = true;
93 break;
94 }
95 if (!line.empty()) {
96 temp_.emplace_back(std::move(line));
97 }
98 }
99
100 if (!end_block && (!should_flush_ || temp_.empty()))
101 return false;
102
103 *out = std::move(temp_);
104 return true;
105}
106
108 source_.Flush();
109 should_flush_ = true;
110}
111
112} // namespace media
113} // 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.