Shaka Packager SDK
byte_queue.cc
1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include <packager/media/base/byte_queue.h>
6 
7 #include <absl/log/check.h>
8 #include <absl/log/log.h>
9 
10 namespace shaka {
11 namespace media {
12 
13 // Default starting size for the queue.
14 enum { kDefaultQueueSize = 1024 };
15 
16 ByteQueue::ByteQueue()
17  : buffer_(new uint8_t[kDefaultQueueSize]),
18  size_(kDefaultQueueSize),
19  offset_(0),
20  used_(0) {
21 }
22 
23 ByteQueue::~ByteQueue() {}
24 
25 void ByteQueue::Reset() {
26  offset_ = 0;
27  used_ = 0;
28 }
29 
30 void ByteQueue::Push(const uint8_t* data, int size) {
31  DCHECK(data);
32 
33  size_t size_needed = used_ + size;
34 
35  // Check to see if we need a bigger buffer.
36  if (size_needed > size_) {
37  size_t new_size = 2 * size_;
38  while (size_needed > new_size && new_size > size_)
39  new_size *= 2;
40 
41  // Sanity check to make sure we didn't overflow.
42  CHECK_GT(new_size, size_);
43 
44  std::unique_ptr<uint8_t[]> new_buffer(new uint8_t[new_size]);
45 
46  // Copy the data from the old buffer to the start of the new one.
47  if (used_ > 0)
48  memcpy(new_buffer.get(), front(), used_);
49 
50  buffer_.reset(new_buffer.release());
51  size_ = new_size;
52  offset_ = 0;
53  } else if ((offset_ + used_ + size) > size_) {
54  // The buffer is big enough, but we need to move the data in the queue.
55  memmove(buffer_.get(), front(), used_);
56  offset_ = 0;
57  }
58 
59  memcpy(front() + used_, data, size);
60  used_ += size;
61 }
62 
63 void ByteQueue::Peek(const uint8_t** data, int* size) const {
64  DCHECK(data);
65  DCHECK(size);
66  *data = front();
67  *size = used_;
68 }
69 
70 void ByteQueue::Pop(int count) {
71  DCHECK_LE(count, used_);
72 
73  offset_ += count;
74  used_ -= count;
75 
76  // Move the offset back to 0 if we have reached the end of the buffer.
77  if (offset_ == size_) {
78  DCHECK_EQ(used_, 0);
79  offset_ = 0;
80  }
81 }
82 
83 uint8_t* ByteQueue::front() const {
84  return buffer_.get() + offset_;
85 }
86 
87 } // namespace media
88 } // namespace shaka
All the methods that are virtual are virtual for mocking.
Definition: crypto_flags.cc:66