Line data Source code
1 : /*
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 :
13 : #include <algorithm>
14 :
15 : namespace rtc {
16 :
17 0 : BufferQueue::BufferQueue(size_t capacity, size_t default_size)
18 0 : : capacity_(capacity), default_size_(default_size) {
19 0 : }
20 :
21 0 : BufferQueue::~BufferQueue() {
22 0 : CritScope cs(&crit_);
23 :
24 0 : for (Buffer* buffer : queue_) {
25 0 : delete buffer;
26 : }
27 0 : for (Buffer* buffer : free_list_) {
28 0 : delete buffer;
29 : }
30 0 : }
31 :
32 0 : size_t BufferQueue::size() const {
33 0 : CritScope cs(&crit_);
34 0 : return queue_.size();
35 : }
36 :
37 0 : void BufferQueue::Clear() {
38 0 : CritScope cs(&crit_);
39 0 : while (!queue_.empty()) {
40 0 : free_list_.push_back(queue_.front());
41 0 : queue_.pop_front();
42 : }
43 0 : }
44 :
45 0 : bool BufferQueue::ReadFront(void* buffer, size_t bytes, size_t* bytes_read) {
46 0 : CritScope cs(&crit_);
47 0 : if (queue_.empty()) {
48 0 : return false;
49 : }
50 :
51 0 : bool was_writable = queue_.size() < capacity_;
52 0 : Buffer* packet = queue_.front();
53 0 : queue_.pop_front();
54 :
55 0 : bytes = std::min(bytes, packet->size());
56 0 : memcpy(buffer, packet->data(), bytes);
57 0 : if (bytes_read) {
58 0 : *bytes_read = bytes;
59 : }
60 0 : free_list_.push_back(packet);
61 0 : if (!was_writable) {
62 0 : NotifyWritableForTest();
63 : }
64 0 : return true;
65 : }
66 :
67 0 : bool BufferQueue::WriteBack(const void* buffer, size_t bytes,
68 : size_t* bytes_written) {
69 0 : CritScope cs(&crit_);
70 0 : if (queue_.size() == capacity_) {
71 0 : return false;
72 : }
73 :
74 0 : bool was_readable = !queue_.empty();
75 : Buffer* packet;
76 0 : if (!free_list_.empty()) {
77 0 : packet = free_list_.back();
78 0 : free_list_.pop_back();
79 : } else {
80 0 : packet = new Buffer(bytes, default_size_);
81 : }
82 :
83 0 : packet->SetData(static_cast<const uint8_t*>(buffer), bytes);
84 0 : if (bytes_written) {
85 0 : *bytes_written = bytes;
86 : }
87 0 : queue_.push_back(packet);
88 0 : if (!was_readable) {
89 0 : NotifyReadableForTest();
90 : }
91 0 : return true;
92 : }
93 :
94 : } // namespace rtc
|