xref: /aosp_15_r20/external/webrtc/modules/audio_processing/agc2/rnn_vad/ring_buffer.h (revision d9f758449e529ab9291ac668be2861e7a55c2422)
1 /*
2  *  Copyright (c) 2018 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 #ifndef MODULES_AUDIO_PROCESSING_AGC2_RNN_VAD_RING_BUFFER_H_
12 #define MODULES_AUDIO_PROCESSING_AGC2_RNN_VAD_RING_BUFFER_H_
13 
14 #include <array>
15 #include <cstring>
16 #include <type_traits>
17 
18 #include "api/array_view.h"
19 
20 namespace webrtc {
21 namespace rnn_vad {
22 
23 // Ring buffer for N arrays of type T each one with size S.
24 template <typename T, int S, int N>
25 class RingBuffer {
26   static_assert(S > 0, "");
27   static_assert(N > 0, "");
28   static_assert(std::is_arithmetic<T>::value,
29                 "Integral or floating point required.");
30 
31  public:
RingBuffer()32   RingBuffer() : tail_(0) {}
33   RingBuffer(const RingBuffer&) = delete;
34   RingBuffer& operator=(const RingBuffer&) = delete;
35   ~RingBuffer() = default;
36   // Set the ring buffer values to zero.
Reset()37   void Reset() { buffer_.fill(0); }
38   // Replace the least recently pushed array in the buffer with `new_values`.
Push(rtc::ArrayView<const T,S> new_values)39   void Push(rtc::ArrayView<const T, S> new_values) {
40     std::memcpy(buffer_.data() + S * tail_, new_values.data(), S * sizeof(T));
41     tail_ += 1;
42     if (tail_ == N)
43       tail_ = 0;
44   }
45   // Return an array view onto the array with a given delay. A view on the last
46   // and least recently push array is returned when `delay` is 0 and N - 1
47   // respectively.
GetArrayView(int delay)48   rtc::ArrayView<const T, S> GetArrayView(int delay) const {
49     RTC_DCHECK_LE(0, delay);
50     RTC_DCHECK_LT(delay, N);
51     int offset = tail_ - 1 - delay;
52     if (offset < 0)
53       offset += N;
54     return {buffer_.data() + S * offset, S};
55   }
56 
57  private:
58   int tail_;  // Index of the least recently pushed sub-array.
59   std::array<T, S * N> buffer_{};
60 };
61 
62 }  // namespace rnn_vad
63 }  // namespace webrtc
64 
65 #endif  // MODULES_AUDIO_PROCESSING_AGC2_RNN_VAD_RING_BUFFER_H_
66