blob: 9c2324e7688b43eba29320e587a2a6a474ccc2dc [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
ossub01c7812016-02-24 01:05:56 -080013#include <algorithm>
14
Joachim Bauch6f2ef742015-05-21 17:52:01 +020015namespace rtc {
16
17BufferQueue::BufferQueue(size_t capacity, size_t default_size)
18 : capacity_(capacity), default_size_(default_size) {
19}
20
21BufferQueue::~BufferQueue() {
22 CritScope cs(&crit_);
23
24 for (Buffer* buffer : queue_) {
25 delete buffer;
26 }
27 for (Buffer* buffer : free_list_) {
28 delete buffer;
29 }
30}
31
32size_t BufferQueue::size() const {
33 CritScope cs(&crit_);
34 return queue_.size();
35}
36
37bool BufferQueue::ReadFront(void* buffer, size_t bytes, size_t* bytes_read) {
38 CritScope cs(&crit_);
39 if (queue_.empty()) {
40 return false;
41 }
42
jbauche488a0d2015-11-19 05:17:58 -080043 bool was_writable = queue_.size() < capacity_;
Joachim Bauch6f2ef742015-05-21 17:52:01 +020044 Buffer* packet = queue_.front();
45 queue_.pop_front();
46
jbauche488a0d2015-11-19 05:17:58 -080047 bytes = std::min(bytes, packet->size());
Joachim Bauch6f2ef742015-05-21 17:52:01 +020048 memcpy(buffer, packet->data(), bytes);
49 if (bytes_read) {
50 *bytes_read = bytes;
51 }
52 free_list_.push_back(packet);
jbauche488a0d2015-11-19 05:17:58 -080053 if (!was_writable) {
54 NotifyWritableForTest();
55 }
Joachim Bauch6f2ef742015-05-21 17:52:01 +020056 return true;
57}
58
59bool BufferQueue::WriteBack(const void* buffer, size_t bytes,
60 size_t* bytes_written) {
61 CritScope cs(&crit_);
62 if (queue_.size() == capacity_) {
63 return false;
64 }
65
jbauche488a0d2015-11-19 05:17:58 -080066 bool was_readable = !queue_.empty();
Joachim Bauch6f2ef742015-05-21 17:52:01 +020067 Buffer* packet;
68 if (!free_list_.empty()) {
69 packet = free_list_.back();
70 free_list_.pop_back();
71 } else {
72 packet = new Buffer(bytes, default_size_);
73 }
74
75 packet->SetData(static_cast<const uint8_t*>(buffer), bytes);
76 if (bytes_written) {
77 *bytes_written = bytes;
78 }
79 queue_.push_back(packet);
jbauche488a0d2015-11-19 05:17:58 -080080 if (!was_readable) {
81 NotifyReadableForTest();
82 }
Joachim Bauch6f2ef742015-05-21 17:52:01 +020083 return true;
84}
85
86} // namespace rtc