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