Shaka Packager SDK
webvtt_file_buffer.cc
1 // Copyright 2018 Google LLC 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_file_buffer.h"
8 
9 #include "packager/base/strings/stringprintf.h"
10 #include "packager/media/base/text_sample.h"
11 #include "packager/media/formats/webvtt/webvtt_timestamp.h"
12 
13 namespace shaka {
14 namespace media {
15 namespace {
16 const char* kHeader = "WEBVTT\n";
17 const int kTsTimescale = 90000;
18 }
19 
20 WebVttFileBuffer::WebVttFileBuffer(
21  uint32_t transport_stream_timestamp_offset_ms)
22  : transport_stream_timestamp_offset_(transport_stream_timestamp_offset_ms *
23  kTsTimescale / 1000) {
24  // Make sure we start with the same state that we would end up with if
25  // the caller reset our state.
26  Reset();
27 }
28 
29 void WebVttFileBuffer::Reset() {
30  sample_count_ = 0;
31 
32  buffer_.clear();
33  buffer_.append(kHeader);
34  if (transport_stream_timestamp_offset_ > 0) {
35  // https://tools.ietf.org/html/rfc8216#section-3.5 WebVTT.
36  base::StringAppendF(&buffer_,
37  "X-TIMESTAMP-MAP=LOCAL:00:00:00.000,MPEGTS:%d\n",
38  transport_stream_timestamp_offset_);
39  }
40  buffer_.append("\n"); // end of header.
41 }
42 
43 void WebVttFileBuffer::Append(const TextSample& sample) {
44  DCHECK_GT(buffer_.size(), 0u) << "The buffer should at least have a header";
45 
46  sample_count_++;
47 
48  // Ids are optional
49  if (sample.id().length()) {
50  buffer_.append(sample.id());
51  buffer_.append("\n"); // end of id
52  }
53 
54  // Write the times that the sample elapses.
55  buffer_.append(MsToWebVttTimestamp(sample.start_time()));
56  buffer_.append(" --> ");
57  buffer_.append(MsToWebVttTimestamp(sample.EndTime()));
58 
59  // Settings are optional
60  if (sample.settings().length()) {
61  buffer_.append(" ");
62  buffer_.append(sample.settings());
63  }
64  buffer_.append("\n"); // end of time & settings
65 
66  buffer_.append(sample.payload());
67  buffer_.append("\n"); // end of payload
68  buffer_.append("\n"); // end of sample
69 }
70 
71 bool WebVttFileBuffer::WriteTo(File* file) {
72  DCHECK(file);
73  DCHECK_GT(buffer_.size(), 0u) << "The buffer should at least have a header";
74 
75  const int written = file->Write(buffer_.c_str(), buffer_.size());
76  if (written < 0) {
77  return false;
78  }
79 
80  return static_cast<size_t>(written) == buffer_.size();
81 }
82 } // namespace media
83 } // namespace shaka
All the methods that are virtual are virtual for mocking.