Shaka Packager SDK
 All Classes Namespaces Functions Variables Typedefs Enumerations Enumerator Friends
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 "packager/base/logging.h"
8 
9 namespace shaka {
10 namespace media {
11 
12 // Default starting size for the queue.
13 enum { kDefaultQueueSize = 1024 };
14 
15 ByteQueue::ByteQueue()
16  : buffer_(new uint8_t[kDefaultQueueSize]),
17  size_(kDefaultQueueSize),
18  offset_(0),
19  used_(0) {
20 }
21 
22 ByteQueue::~ByteQueue() {}
23 
25  offset_ = 0;
26  used_ = 0;
27 }
28 
29 void ByteQueue::Push(const uint8_t* data, int size) {
30  DCHECK(data);
31  DCHECK_GT(size, 0);
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
void Push(const uint8_t *data, int size)
Append new bytes to the end of the queue.
Definition: byte_queue.cc:29
void Pop(int count)
Definition: byte_queue.cc:70
void Reset()
Reset the queue to the empty state.
Definition: byte_queue.cc:24
void Peek(const uint8_t **data, int *size) const
Definition: byte_queue.cc:63