DASH Media Packaging SDK
 All Classes Namespaces Functions Variables Typedefs Enumerations Enumerator
buffer_writer.cc
1 // Copyright 2014 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/base/buffer_writer.h"
8 
9 #include "packager/base/logging.h"
10 #include "packager/base/sys_byteorder.h"
11 #include "packager/file/file.h"
12 
13 namespace shaka {
14 namespace media {
15 
16 BufferWriter::BufferWriter() {
17  const size_t kDefaultReservedCapacity = 0x40000; // 256KB.
18  buf_.reserve(kDefaultReservedCapacity);
19 }
20 BufferWriter::BufferWriter(size_t reserved_size_in_bytes) {
21  buf_.reserve(reserved_size_in_bytes);
22 }
23 BufferWriter::~BufferWriter() {}
24 
25 void BufferWriter::AppendInt(uint8_t v) {
26  buf_.push_back(v);
27 }
28 void BufferWriter::AppendInt(uint16_t v) {
29  AppendInternal(base::HostToNet16(v));
30 }
31 void BufferWriter::AppendInt(uint32_t v) {
32  AppendInternal(base::HostToNet32(v));
33 }
34 void BufferWriter::AppendInt(uint64_t v) {
35  AppendInternal(base::HostToNet64(v));
36 }
37 void BufferWriter::AppendInt(int16_t v) {
38  AppendInternal(base::HostToNet16(v));
39 }
40 void BufferWriter::AppendInt(int32_t v) {
41  AppendInternal(base::HostToNet32(v));
42 }
43 void BufferWriter::AppendInt(int64_t v) {
44  AppendInternal(base::HostToNet64(v));
45 }
46 
47 void BufferWriter::AppendNBytes(uint64_t v, size_t num_bytes) {
48  DCHECK_GE(sizeof(v), num_bytes);
49  v = base::HostToNet64(v);
50  const uint8_t* data = reinterpret_cast<uint8_t*>(&v);
51  AppendArray(&data[sizeof(v) - num_bytes], num_bytes);
52 }
53 
54 void BufferWriter::AppendVector(const std::vector<uint8_t>& v) {
55  buf_.insert(buf_.end(), v.begin(), v.end());
56 }
57 
58 void BufferWriter::AppendArray(const uint8_t* buf, size_t size) {
59  buf_.insert(buf_.end(), buf, buf + size);
60 }
61 
62 void BufferWriter::AppendBuffer(const BufferWriter& buffer) {
63  buf_.insert(buf_.end(), buffer.buf_.begin(), buffer.buf_.end());
64 }
65 
66 Status BufferWriter::WriteToFile(File* file) {
67  DCHECK(file);
68  DCHECK(!buf_.empty());
69 
70  size_t remaining_size = buf_.size();
71  const uint8_t* buf = &buf_[0];
72  while (remaining_size > 0) {
73  int64_t size_written = file->Write(buf, remaining_size);
74  if (size_written <= 0) {
75  return Status(error::FILE_FAILURE,
76  "Fail to write to file in BufferWriter");
77  }
78  remaining_size -= size_written;
79  buf += size_written;
80  }
81  buf_.clear();
82  return Status::OK;
83 }
84 
85 template <typename T>
86 void BufferWriter::AppendInternal(T v) {
87  AppendArray(reinterpret_cast<uint8_t*>(&v), sizeof(T));
88 }
89 
90 } // namespace media
91 } // namespace shaka
void AppendNBytes(uint64_t v, size_t num_bytes)
Status WriteToFile(File *file)