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 // Mapping:
188 // comment --> side data (and side data only sample)
189 // settings --> side data
190 // start_time --> pts
191 scoped_refptr<MediaSample> CueToMediaSample(const Cue& cue) {
192  const bool kKeyFrame = true;
193  if (!cue.comment.empty()) {
194  const std::string comment = base::JoinString(cue.comment, "\n");
196  reinterpret_cast<const uint8_t*>(comment.data()), comment.size());
197  }
198 
199  const std::string payload = base::JoinString(cue.payload, "\n");
200  scoped_refptr<MediaSample> media_sample = MediaSample::CopyFrom(
201  reinterpret_cast<const uint8_t*>(payload.data()),
202  payload.size(),
203  reinterpret_cast<const uint8_t*>(cue.settings.data()),
204  cue.settings.size(),
205  !kKeyFrame);
206 
207  media_sample->set_config_id(cue.identifier);
208  media_sample->set_pts(cue.start_time);
209  media_sample->set_duration(cue.duration);
210  return media_sample;
211 }
212 
213 } // namespace
214 
215 Cue::Cue() : start_time(0), duration(0) {}
216 Cue::~Cue() {}
217 
218 WebVttMediaParser::WebVttMediaParser() : state_(kHeader) {}
219 WebVttMediaParser::~WebVttMediaParser() {}
220 
221 void WebVttMediaParser::Init(const InitCB& init_cb,
222  const NewSampleCB& new_sample_cb,
223  KeySource* decryption_key_source) {
224  init_cb_ = init_cb;
225  new_sample_cb_ = new_sample_cb;
226 }
227 
229  // If not in one of these states just be ready for more data.
230  if (state_ != kCuePayload && state_ != kComment)
231  return true;
232 
233  if (!data_.empty()) {
234  // If it was in the middle of the payload and the stream finished, then this
235  // is an end of the payload. The rest of the data is part of the payload.
236  if (state_ == kCuePayload) {
237  current_cue_.payload.push_back(data_);
238  } else {
239  current_cue_.comment.push_back(data_);
240  }
241  data_.clear();
242  }
243 
244  bool result = new_sample_cb_.Run(kTrackId, CueToMediaSample(current_cue_));
245  current_cue_ = Cue();
246  state_ = kCueIdentifierOrTimingOrComment;
247  return result;
248 }
249 
250 bool WebVttMediaParser::Parse(const uint8_t* buf, int size) {
251  if (state_ == kParseError) {
252  LOG(WARNING) << "The parser is in an error state, ignoring input.";
253  return false;
254  }
255 
256  data_.insert(data_.end(), buf, buf + size);
257 
258  std::string line;
259  while (ReadLine(&data_, &line)) {
260  // Only kCueIdentifierOrTimingOrComment and kCueTiming states accept -->.
261  // Error otherwise.
262  const bool has_arrow = line.find("-->") != std::string::npos;
263  if (state_ == kCueTiming) {
264  if (!has_arrow) {
265  LOG(ERROR) << "Expected --> in: " << line;
266  state_ = kParseError;
267  return false;
268  }
269  } else if (state_ != kCueIdentifierOrTimingOrComment) {
270  if (has_arrow) {
271  LOG(ERROR) << "Unexpected --> in " << line;
272  state_ = kParseError;
273  return false;
274  }
275  }
276 
277  switch (state_) {
278  case kHeader:
279  // No check. This should be WEBVTT when this object was created.
280  header_.push_back(line);
281  state_ = kMetadata;
282  break;
283  case kMetadata: {
284  if (line.empty()) {
285  std::vector<scoped_refptr<StreamInfo> > streams;
286  // The resolution of timings are in milliseconds.
287  const int kTimescale = 1000;
288 
289  // The duration passed here is not very important. Also the whole file
290  // must be read before determining the real duration which doesn't
291  // work nicely with the current demuxer.
292  const int kDuration = 0;
293 
294  // There is no one metadata to determine what the language is. Parts
295  // of the text may be annotated as some specific language.
296  const char kLanguage[] = "";
297  streams.push_back(new TextStreamInfo(kTrackId, kTimescale, kDuration,
298  "wvtt",
299  base::JoinString(header_, "\n"),
300  0, // Not necessary.
301  0,
302  kLanguage)); // Not necessary.
303 
304  init_cb_.Run(streams);
305  state_ = kCueIdentifierOrTimingOrComment;
306  break;
307  }
308 
309  header_.push_back(line);
310  break;
311  }
312  case kCueIdentifierOrTimingOrComment: {
313  // Note that there can be one or more line breaks before a cue starts;
314  // skip this line.
315  // Or the file could end without a new cue.
316  if (line.empty())
317  break;
318 
319  if (!has_arrow) {
320  if (base::StartsWith(line, "NOTE",
321  base::CompareCase::INSENSITIVE_ASCII)) {
322  state_ = kComment;
323  current_cue_.comment.push_back(line);
324  } else {
325  // A cue can start from a cue identifier.
326  // https://w3c.github.io/webvtt/#webvtt-cue-identifier
327  current_cue_.identifier = line;
328  // The next line must be a timing.
329  state_ = kCueTiming;
330  }
331  break;
332  }
333 
334  // No break statement if the line has an arrow; it should be a WebVTT
335  // timing, so fall thru. Setting state_ to kCueTiming so that the state
336  // always matches the case.
337  state_ = kCueTiming;
338  FALLTHROUGH_INTENDED;
339  }
340  case kCueTiming: {
341  DCHECK(has_arrow);
342  if (!ParseTimingAndSettingsLine(line, &current_cue_.start_time,
343  &current_cue_.duration,
344  &current_cue_.settings)) {
345  state_ = kParseError;
346  return false;
347  }
348  state_ = kCuePayload;
349  break;
350  }
351  case kCuePayload: {
352  if (line.empty()) {
353  state_ = kCueIdentifierOrTimingOrComment;
354  if (!new_sample_cb_.Run(kTrackId, CueToMediaSample(current_cue_))) {
355  state_ = kParseError;
356  return false;
357  }
358  current_cue_ = Cue();
359  break;
360  }
361 
362  current_cue_.payload.push_back(line);
363  break;
364  }
365  case kComment: {
366  if (line.empty()) {
367  state_ = kCueIdentifierOrTimingOrComment;
368  if (!new_sample_cb_.Run(kTrackId, CueToMediaSample(current_cue_))) {
369  state_ = kParseError;
370  return false;
371  }
372  current_cue_ = Cue();
373  break;
374  }
375 
376  current_cue_.comment.push_back(line);
377  break;
378  }
379  case kParseError:
380  NOTREACHED();
381  return false;
382  }
383  }
384 
385  return true;
386 }
387 
388 } // namespace media
389 } // namespace shaka
static scoped_refptr< MediaSample > FromMetadata(const uint8_t *metadata, size_t metadata_size)
Definition: media_sample.cc:67
void Init(const InitCB &init_cb, const NewSampleCB &new_sample_cb, KeySource *decryption_key_source) override
bool Parse(const uint8_t *buf, int size) override WARN_UNUSED_RESULT
bool Flush() override WARN_UNUSED_RESULT
base::Callback< bool(uint32_t track_id, const scoped_refptr< MediaSample > &media_sample)> NewSampleCB
Definition: media_parser.h:43
KeySource is responsible for encryption key acquisition.
Definition: key_source.h:30
static scoped_refptr< MediaSample > CopyFrom(const uint8_t *data, size_t size, bool is_key_frame)
Definition: media_sample.cc:45