DASH Media Packaging SDK
 All Classes Namespaces Functions Variables Typedefs Enumerations Enumerator
webvtt_media_parser.cc
1 // Copyright 2015 Google Inc. 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/webvtt_media_parser.h"
8 
9 #include <string>
10 #include <vector>
11 
12 #include "packager/base/logging.h"
13 #include "packager/base/strings/string_number_conversions.h"
14 #include "packager/base/strings/string_split.h"
15 #include "packager/base/strings/string_util.h"
16 #include "packager/media/base/macros.h"
17 #include "packager/media/base/media_sample.h"
18 #include "packager/media/base/text_stream_info.h"
19 
20 namespace shaka {
21 namespace media {
22 
23 namespace {
24 
25 // There's only one track in a WebVTT file.
26 const int kTrackId = 0;
27 
28 const char kCR = 0x0D;
29 const char kLF = 0x0A;
30 
31 // Reads the first line from |data| and removes the line. Returns false if there
32 // isn't a line break. Sets |line| with the content of the first line without
33 // the line break.
34 bool ReadLine(std::string* data, std::string* line) {
35  if (data->size() == 0) {
36  return false;
37  }
38  size_t string_position = 0;
39  // Length of the line break mark. 1 for LF and CR, 2 for CRLF.
40  int line_break_length = 1;
41  bool found_line_break = false;
42  while (string_position < data->size()) {
43  if (data->at(string_position) == kLF) {
44  found_line_break = true;
45  break;
46  }
47 
48  if (data->at(string_position) == kCR) {
49  found_line_break = true;
50  if (string_position + 1 >= data->size())
51  break;
52 
53  if (data->at(string_position + 1) == kLF)
54  line_break_length = 2;
55  break;
56  }
57 
58  ++string_position;
59  }
60 
61  if (!found_line_break)
62  return false;
63 
64  *line = data->substr(0, string_position);
65  data->erase(0, string_position + line_break_length);
66  return true;
67 }
68 
69 bool TimestampToMilliseconds(const std::string& original_str,
70  uint64_t* time_ms) {
71  const size_t kMinimalHoursLength = 2;
72  const size_t kMinutesLength = 2;
73  const size_t kSecondsLength = 2;
74  const size_t kMillisecondsLength = 3;
75 
76  // +2 for a colon and a dot for splitting minutes and seconds AND seconds and
77  // milliseconds, respectively.
78  const size_t kMinimalLength =
79  kMinutesLength + kSecondsLength + kMillisecondsLength + 2;
80 
81  base::StringPiece str(original_str);
82  if (str.size() < kMinimalLength)
83  return false;
84 
85  int hours = 0;
86  int minutes = 0;
87  int seconds = 0;
88  int milliseconds = 0;
89 
90  size_t str_index = 0;
91  if (str.size() > kMinimalLength) {
92  // Check if hours is in the right format, if so get the number.
93  // -1 for excluding colon for splitting hours and minutes.
94  const size_t hours_length = str.size() - kMinimalLength - 1;
95  if (hours_length < kMinimalHoursLength)
96  return false;
97  if (!base::StringToInt(str.substr(0, hours_length), &hours))
98  return false;
99  str_index += hours_length;
100 
101  if (str[str_index] != ':')
102  return false;
103  ++str_index;
104  }
105 
106  DCHECK_EQ(str.size() - str_index, kMinimalLength);
107 
108  if (!base::StringToInt(str.substr(str_index, kMinutesLength), &minutes))
109  return false;
110  if (minutes < 0 || minutes > 60)
111  return false;
112 
113  str_index += kMinutesLength;
114  if (str[str_index] != ':')
115  return false;
116  ++str_index;
117 
118  if (!base::StringToInt(str.substr(str_index, kSecondsLength), &seconds))
119  return false;
120  if (seconds < 0 || seconds > 60)
121  return false;
122 
123  str_index += kSecondsLength;
124  if (str[str_index] != '.')
125  return false;
126  ++str_index;
127 
128  if (!base::StringToInt(str.substr(str_index, kMillisecondsLength),
129  &milliseconds)) {
130  return false;
131  }
132  str_index += kMillisecondsLength;
133 
134  if (milliseconds < 0 || milliseconds > 999)
135  return false;
136 
137  DCHECK_EQ(str.size(), str_index);
138  *time_ms = milliseconds +
139  seconds * 1000 +
140  minutes * 60 * 1000 +
141  hours * 60 * 60 * 1000;
142  return true;
143 }
144 
145 // Clears |settings| and 0s |start_time| and |duration| regardless of the
146 // parsing result.
147 bool ParseTimingAndSettingsLine(const std::string& line,
148  uint64_t* start_time,
149  uint64_t* duration,
150  std::string* settings) {
151  *start_time = 0;
152  *duration = 0;
153  settings->clear();
154  std::vector<std::string> entries = base::SplitString(
155  line, " ", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
156  if (entries.size() < 3) {
157  // The timing is time1 --> time3 so if there aren't 3 entries, this is parse
158  // error.
159  LOG(ERROR) << "Not enough tokens to be a timing " << line;
160  return false;
161  }
162 
163  if (entries[1] != "-->") {
164  LOG(ERROR) << "Cannot find an arrow at the right place " << line;
165  return false;
166  }
167 
168  const std::string& start_time_str = entries[0];
169  if (!TimestampToMilliseconds(start_time_str, start_time)) {
170  LOG(ERROR) << "Failed to parse " << start_time_str << " in " << line;
171  return false;
172  }
173 
174  const std::string& end_time_str = entries[2];
175  uint64_t end_time = 0;
176  if (!TimestampToMilliseconds(end_time_str, &end_time)) {
177  LOG(ERROR) << "Failed to parse " << end_time_str << " in " << line;
178  return false;
179  }
180  *duration = end_time - *start_time;
181 
182  entries.erase(entries.begin(), entries.begin() + 3);
183  *settings = base::JoinString(entries, " ");
184  return true;
185 }
186 
187 } // namespace
188 
189 WebVttMediaParser::WebVttMediaParser() : state_(kHeader) {}
190 WebVttMediaParser::~WebVttMediaParser() {}
191 
192 void WebVttMediaParser::Init(const InitCB& init_cb,
193  const NewSampleCB& new_sample_cb,
194  KeySource* decryption_key_source) {
195  init_cb_ = init_cb;
196  new_sample_cb_ = new_sample_cb;
197 }
198 
200  // If not in one of these states just be ready for more data.
201  if (state_ != kCuePayload && state_ != kComment)
202  return true;
203 
204  if (!data_.empty()) {
205  // If it was in the middle of the payload and the stream finished, then this
206  // is an end of the payload. The rest of the data is part of the payload.
207  if (state_ == kCuePayload) {
208  current_cue_.payload.push_back(data_);
209  } else {
210  current_cue_.comment.push_back(data_);
211  }
212  data_.clear();
213  }
214 
215  bool result = new_sample_cb_.Run(kTrackId, CueToMediaSample(current_cue_));
216  current_cue_ = Cue();
217  state_ = kCueIdentifierOrTimingOrComment;
218  return result;
219 }
220 
221 bool WebVttMediaParser::Parse(const uint8_t* buf, int size) {
222  if (state_ == kParseError) {
223  LOG(WARNING) << "The parser is in an error state, ignoring input.";
224  return false;
225  }
226 
227  data_.insert(data_.end(), buf, buf + size);
228 
229  std::string line;
230  while (ReadLine(&data_, &line)) {
231  // Only kCueIdentifierOrTimingOrComment and kCueTiming states accept -->.
232  // Error otherwise.
233  const bool has_arrow = line.find("-->") != std::string::npos;
234  if (state_ == kCueTiming) {
235  if (!has_arrow) {
236  LOG(ERROR) << "Expected --> in: " << line;
237  state_ = kParseError;
238  return false;
239  }
240  } else if (state_ != kCueIdentifierOrTimingOrComment) {
241  if (has_arrow) {
242  LOG(ERROR) << "Unexpected --> in " << line;
243  state_ = kParseError;
244  return false;
245  }
246  }
247 
248  switch (state_) {
249  case kHeader:
250  // No check. This should be WEBVTT when this object was created.
251  header_.push_back(line);
252  state_ = kMetadata;
253  break;
254  case kMetadata: {
255  if (line.empty()) {
256  std::vector<std::shared_ptr<StreamInfo>> streams;
257  // The resolution of timings are in milliseconds.
258  const int kTimescale = 1000;
259 
260  // The duration passed here is not very important. Also the whole file
261  // must be read before determining the real duration which doesn't
262  // work nicely with the current demuxer.
263  const int kDuration = 0;
264 
265  // There is no one metadata to determine what the language is. Parts
266  // of the text may be annotated as some specific language.
267  const char kLanguage[] = "";
268  streams.emplace_back(
269  new TextStreamInfo(kTrackId, kTimescale, kDuration, "wvtt",
270  base::JoinString(header_, "\n"),
271  0, // Not necessary.
272  0,
273  kLanguage)); // Not necessary.
274 
275  init_cb_.Run(streams);
276  state_ = kCueIdentifierOrTimingOrComment;
277  break;
278  }
279 
280  header_.push_back(line);
281  break;
282  }
283  case kCueIdentifierOrTimingOrComment: {
284  // Note that there can be one or more line breaks before a cue starts;
285  // skip this line.
286  // Or the file could end without a new cue.
287  if (line.empty())
288  break;
289 
290  if (!has_arrow) {
291  if (base::StartsWith(line, "NOTE",
292  base::CompareCase::INSENSITIVE_ASCII)) {
293  state_ = kComment;
294  current_cue_.comment.push_back(line);
295  } else {
296  // A cue can start from a cue identifier.
297  // https://w3c.github.io/webvtt/#webvtt-cue-identifier
298  current_cue_.identifier = line;
299  // The next line must be a timing.
300  state_ = kCueTiming;
301  }
302  break;
303  }
304 
305  // No break statement if the line has an arrow; it should be a WebVTT
306  // timing, so fall thru. Setting state_ to kCueTiming so that the state
307  // always matches the case.
308  state_ = kCueTiming;
309  FALLTHROUGH_INTENDED;
310  }
311  case kCueTiming: {
312  DCHECK(has_arrow);
313  if (!ParseTimingAndSettingsLine(line, &current_cue_.start_time,
314  &current_cue_.duration,
315  &current_cue_.settings)) {
316  state_ = kParseError;
317  return false;
318  }
319  state_ = kCuePayload;
320  break;
321  }
322  case kCuePayload: {
323  if (line.empty()) {
324  state_ = kCueIdentifierOrTimingOrComment;
325  if (!new_sample_cb_.Run(kTrackId, CueToMediaSample(current_cue_))) {
326  state_ = kParseError;
327  return false;
328  }
329  current_cue_ = Cue();
330  break;
331  }
332 
333  current_cue_.payload.push_back(line);
334  break;
335  }
336  case kComment: {
337  if (line.empty()) {
338  state_ = kCueIdentifierOrTimingOrComment;
339  if (!new_sample_cb_.Run(kTrackId, CueToMediaSample(current_cue_))) {
340  state_ = kParseError;
341  return false;
342  }
343  current_cue_ = Cue();
344  break;
345  }
346 
347  current_cue_.comment.push_back(line);
348  break;
349  }
350  case kParseError:
351  NOTREACHED();
352  return false;
353  }
354  }
355 
356  return true;
357 }
358 
359 } // namespace media
360 } // namespace shaka
void Init(const InitCB &init_cb, const NewSampleCB &new_sample_cb, KeySource *decryption_key_source) override
base::Callback< bool(uint32_t track_id, const std::shared_ptr< MediaSample > &media_sample)> NewSampleCB
Definition: media_parser.h:43
bool Parse(const uint8_t *buf, int size) override WARN_UNUSED_RESULT
bool Flush() override WARN_UNUSED_RESULT
KeySource is responsible for encryption key acquisition.
Definition: key_source.h:30