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/media/base/text_sample.h"
10 #include "packager/media/formats/webvtt/webvtt_timestamp.h"
11 
12 namespace shaka {
13 namespace media {
14 namespace {
15 const char* kHeader = "WEBVTT\n\n";
16 }
17 
18 WebVttFileBuffer::WebVttFileBuffer() {
19  // Make sure we start with the same state that we would end up with if
20  // the caller reset our state.
21  Reset();
22 }
23 
24 void WebVttFileBuffer::Reset() {
25  sample_count_ = 0;
26 
27  buffer_.clear();
28  buffer_.append(kHeader);
29 }
30 
31 void WebVttFileBuffer::Append(const TextSample& sample) {
32  DCHECK_GT(buffer_.size(), 0u) << "The buffer should at least have a header";
33 
34  sample_count_++;
35 
36  // Ids are optional
37  if (sample.id().length()) {
38  buffer_.append(sample.id());
39  buffer_.append("\n"); // end of id
40  }
41 
42  // Write the times that the sample elapses.
43  buffer_.append(MsToWebVttTimestamp(sample.start_time()));
44  buffer_.append(" --> ");
45  buffer_.append(MsToWebVttTimestamp(sample.EndTime()));
46 
47  // Settings are optional
48  if (sample.settings().length()) {
49  buffer_.append(" ");
50  buffer_.append(sample.settings());
51  }
52  buffer_.append("\n"); // end of time & settings
53 
54  buffer_.append(sample.payload());
55  buffer_.append("\n"); // end of payload
56  buffer_.append("\n"); // end of sample
57 }
58 
59 bool WebVttFileBuffer::WriteTo(File* file) {
60  DCHECK(file);
61  DCHECK_GT(buffer_.size(), 0u) << "The buffer should at least have a header";
62 
63  const int written = file->Write(buffer_.c_str(), buffer_.size());
64  if (written < 0) {
65  return false;
66  }
67 
68  return static_cast<size_t>(written) == buffer_.size();
69 }
70 } // namespace media
71 } // namespace shaka
All the methods that are virtual are virtual for mocking.