summaryrefslogtreecommitdiffstats
path: root/media/formats/webm/webm_webvtt_parser.cc
blob: 64de1ef4434f127ed0a9363885d0088a5638bb87 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "media/formats/webm/webm_webvtt_parser.h"

namespace media {

void WebMWebVTTParser::Parse(const uint8* payload, int payload_size,
                             std::string* id,
                             std::string* settings,
                             std::string* content) {
  WebMWebVTTParser parser(payload, payload_size);
  parser.Parse(id, settings, content);
}

WebMWebVTTParser::WebMWebVTTParser(const uint8* payload, int payload_size)
    : ptr_(payload),
      ptr_end_(payload + payload_size) {
}

void WebMWebVTTParser::Parse(std::string* id,
                             std::string* settings,
                             std::string* content) {
  ParseLine(id);
  ParseLine(settings);
  content->assign(ptr_, ptr_end_);
}

bool WebMWebVTTParser::GetByte(uint8* byte) {
  if (ptr_ >= ptr_end_)
    return false;  // indicates end-of-stream

  *byte = *ptr_++;
  return true;
}

void WebMWebVTTParser::UngetByte() {
  --ptr_;
}

void WebMWebVTTParser::ParseLine(std::string* line) {
  line->clear();

  // Consume characters from the stream, until we reach end-of-line.

  // The WebVTT spec states that lines may be terminated in any of the following
  // three ways:
  //  LF
  //  CR
  //  CR LF

  // The spec is here:
  //  http://wiki.webmproject.org/webm-metadata/temporal-metadata/webvtt-in-webm

  enum {
    kLF = '\x0A',
    kCR = '\x0D'
  };

  for (;;) {
    uint8 byte;

    if (!GetByte(&byte) || byte == kLF)
      return;

    if (byte == kCR) {
      if (GetByte(&byte) && byte != kLF)
        UngetByte();

      return;
    }

    line->push_back(byte);
  }
}

}  // namespace media