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