blob: 955af51f6be3069e742cce44f7c40153ba1d1e04 [file] [log] [blame]
Joachim Bauch6f2ef742015-05-21 17:52:01 +02001/*
2 * Copyright 2015 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11#include "webrtc/base/bufferqueue.h"
12
13namespace rtc {
14
15BufferQueue::BufferQueue(size_t capacity, size_t default_size)
16 : capacity_(capacity), default_size_(default_size) {
17}
18
19BufferQueue::~BufferQueue() {
20 CritScope cs(&crit_);
21
22 for (Buffer* buffer : queue_) {
23 delete buffer;
24 }
25 for (Buffer* buffer : free_list_) {
26 delete buffer;
27 }
28}
29
30size_t BufferQueue::size() const {
31 CritScope cs(&crit_);
32 return queue_.size();
33}
34
35bool BufferQueue::ReadFront(void* buffer, size_t bytes, size_t* bytes_read) {
36 CritScope cs(&crit_);
37 if (queue_.empty()) {
38 return false;
39 }
40
41 Buffer* packet = queue_.front();
42 queue_.pop_front();
43
44 size_t next_packet_size = packet->size();
45 if (bytes > next_packet_size) {
46 bytes = next_packet_size;
47 }
48
49 memcpy(buffer, packet->data(), bytes);
50 if (bytes_read) {
51 *bytes_read = bytes;
52 }
53 free_list_.push_back(packet);
54 return true;
55}
56
57bool BufferQueue::WriteBack(const void* buffer, size_t bytes,
58 size_t* bytes_written) {
59 CritScope cs(&crit_);
60 if (queue_.size() == capacity_) {
61 return false;
62 }
63
64 Buffer* packet;
65 if (!free_list_.empty()) {
66 packet = free_list_.back();
67 free_list_.pop_back();
68 } else {
69 packet = new Buffer(bytes, default_size_);
70 }
71
72 packet->SetData(static_cast<const uint8_t*>(buffer), bytes);
73 if (bytes_written) {
74 *bytes_written = bytes;
75 }
76 queue_.push_back(packet);
77 return true;
78}
79
80} // namespace rtc