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