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, size_t S, size_t 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(size_t delay)48 rtc::ArrayView<const T, S> GetArrayView(size_t delay) const { 49 const int delay_int = static_cast<int>(delay); 50 RTC_DCHECK_LE(0, delay_int); 51 RTC_DCHECK_LT(delay_int, N); 52 int offset = tail_ - 1 - delay_int; 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_ 67