You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

97 lines
2.2 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  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. #include "rtc_base/buffer_queue.h"
  11. #include <stdint.h>
  12. #include <string.h>
  13. #include <algorithm>
  14. namespace rtc {
  15. BufferQueue::BufferQueue(size_t capacity, size_t default_size)
  16. : capacity_(capacity), default_size_(default_size) {}
  17. BufferQueue::~BufferQueue() {
  18. CritScope cs(&crit_);
  19. for (Buffer* buffer : queue_) {
  20. delete buffer;
  21. }
  22. for (Buffer* buffer : free_list_) {
  23. delete buffer;
  24. }
  25. }
  26. size_t BufferQueue::size() const {
  27. CritScope cs(&crit_);
  28. return queue_.size();
  29. }
  30. void BufferQueue::Clear() {
  31. CritScope cs(&crit_);
  32. while (!queue_.empty()) {
  33. free_list_.push_back(queue_.front());
  34. queue_.pop_front();
  35. }
  36. }
  37. bool BufferQueue::ReadFront(void* buffer, size_t bytes, size_t* bytes_read) {
  38. CritScope cs(&crit_);
  39. if (queue_.empty()) {
  40. return false;
  41. }
  42. bool was_writable = queue_.size() < capacity_;
  43. Buffer* packet = queue_.front();
  44. queue_.pop_front();
  45. bytes = std::min(bytes, packet->size());
  46. memcpy(buffer, packet->data(), bytes);
  47. if (bytes_read) {
  48. *bytes_read = bytes;
  49. }
  50. free_list_.push_back(packet);
  51. if (!was_writable) {
  52. NotifyWritableForTest();
  53. }
  54. return true;
  55. }
  56. bool BufferQueue::WriteBack(const void* buffer,
  57. size_t bytes,
  58. size_t* bytes_written) {
  59. CritScope cs(&crit_);
  60. if (queue_.size() == capacity_) {
  61. return false;
  62. }
  63. bool was_readable = !queue_.empty();
  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. packet->SetData(static_cast<const uint8_t*>(buffer), bytes);
  72. if (bytes_written) {
  73. *bytes_written = bytes;
  74. }
  75. queue_.push_back(packet);
  76. if (!was_readable) {
  77. NotifyReadableForTest();
  78. }
  79. return true;
  80. }
  81. } // namespace rtc