xref: /aosp_15_r20/external/webrtc/modules/audio_processing/echo_detector/circular_buffer.cc (revision d9f758449e529ab9291ac668be2861e7a55c2422)
1 /*
2  *  Copyright (c) 2016 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 "modules/audio_processing/echo_detector/circular_buffer.h"
12 
13 #include <algorithm>
14 
15 #include "rtc_base/checks.h"
16 
17 namespace webrtc {
18 
CircularBuffer(size_t size)19 CircularBuffer::CircularBuffer(size_t size) : buffer_(size) {}
20 CircularBuffer::~CircularBuffer() = default;
21 
Push(float value)22 void CircularBuffer::Push(float value) {
23   buffer_[next_insertion_index_] = value;
24   ++next_insertion_index_;
25   next_insertion_index_ %= buffer_.size();
26   RTC_DCHECK_LT(next_insertion_index_, buffer_.size());
27   nr_elements_in_buffer_ = std::min(nr_elements_in_buffer_ + 1, buffer_.size());
28   RTC_DCHECK_LE(nr_elements_in_buffer_, buffer_.size());
29 }
30 
Pop()31 absl::optional<float> CircularBuffer::Pop() {
32   if (nr_elements_in_buffer_ == 0) {
33     return absl::nullopt;
34   }
35   const size_t index =
36       (buffer_.size() + next_insertion_index_ - nr_elements_in_buffer_) %
37       buffer_.size();
38   RTC_DCHECK_LT(index, buffer_.size());
39   --nr_elements_in_buffer_;
40   return buffer_[index];
41 }
42 
Clear()43 void CircularBuffer::Clear() {
44   std::fill(buffer_.begin(), buffer_.end(), 0.f);
45   next_insertion_index_ = 0;
46   nr_elements_in_buffer_ = 0;
47 }
48 
49 }  // namespace webrtc
50