DASH Media Packaging SDK
 All Classes Namespaces Functions Variables Typedefs Enumerations Enumerator
webvtt_timestamp.cc
1 // Copyright 2017 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_timestamp.h"
8 
9 #include <ctype.h>
10 
11 #include "packager/base/logging.h"
12 #include "packager/base/strings/string_number_conversions.h"
13 
14 namespace shaka {
15 namespace media {
16 namespace {
17 
18 bool GetTotalMilliseconds(uint64_t hours,
19  uint64_t minutes,
20  uint64_t seconds,
21  uint64_t ms,
22  uint64_t* out) {
23  DCHECK(out);
24  if (minutes > 59 || seconds > 59 || ms > 999) {
25  VLOG(1) << "Hours:" << hours
26  << " Minutes:" << minutes
27  << " Seconds:" << seconds
28  << " MS:" << ms
29  << " shoud have never made it to GetTotalMilliseconds";
30  return false;
31  }
32  *out = 60 * 60 * 1000 * hours +
33  60 * 1000 * minutes +
34  1000 * seconds +
35  ms;
36  return true;
37 }
38 } // namespace
39 
40 bool WebVttTimestampParse(const base::StringPiece& source, uint64_t* out) {
41  DCHECK(out);
42 
43  if (source.length() < 9) {
44  LOG(WARNING) << "Timestamp '" << source << "' is mal-formed";
45  return false;
46  }
47 
48  const size_t minutes_begin = source.length() - 9;
49  const size_t seconds_begin = source.length() - 6;
50  const size_t milliseconds_begin = source.length() - 3;
51 
52  uint64_t hours = 0;
53  uint64_t minutes = 0;
54  uint64_t seconds = 0;
55  uint64_t ms = 0;
56 
57  const bool has_hours = minutes_begin >= 3 &&
58  source[minutes_begin-1] == ':' &&
59  base::StringToUint64(source.substr(0, minutes_begin-1), &hours);
60 
61  if ((minutes_begin == 0 || has_hours) &&
62  source[seconds_begin-1] == ':' &&
63  source[milliseconds_begin-1] == '.' &&
64  base::StringToUint64(source.substr(minutes_begin, 2), &minutes) &&
65  base::StringToUint64(source.substr(seconds_begin, 2), &seconds) &&
66  base::StringToUint64(source.substr(milliseconds_begin, 3), &ms)) {
67  return GetTotalMilliseconds(hours, minutes, seconds, ms, out);
68  }
69 
70  LOG(WARNING) << "Timestamp '" << source << "' is mal-formed";
71  return false;
72 }
73 } // namespace media
74 } // namespace shaka