xref: /aosp_15_r20/external/webrtc/common_audio/fir_filter_c.cc (revision d9f758449e529ab9291ac668be2861e7a55c2422)
1 /*
2  *  Copyright (c) 2014 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 "common_audio/fir_filter_c.h"
12 
13 #include <string.h>
14 
15 #include <memory>
16 
17 #include "rtc_base/checks.h"
18 
19 namespace webrtc {
20 
~FIRFilterC()21 FIRFilterC::~FIRFilterC() {}
22 
FIRFilterC(const float * coefficients,size_t coefficients_length)23 FIRFilterC::FIRFilterC(const float* coefficients, size_t coefficients_length)
24     : coefficients_length_(coefficients_length),
25       state_length_(coefficients_length - 1),
26       coefficients_(new float[coefficients_length_]),
27       state_(new float[state_length_]) {
28   for (size_t i = 0; i < coefficients_length_; ++i) {
29     coefficients_[i] = coefficients[coefficients_length_ - i - 1];
30   }
31   memset(state_.get(), 0, state_length_ * sizeof(state_[0]));
32 }
33 
Filter(const float * in,size_t length,float * out)34 void FIRFilterC::Filter(const float* in, size_t length, float* out) {
35   RTC_DCHECK_GT(length, 0);
36 
37   // Convolves the input signal `in` with the filter kernel `coefficients_`
38   // taking into account the previous state.
39   for (size_t i = 0; i < length; ++i) {
40     out[i] = 0.f;
41     size_t j;
42     for (j = 0; state_length_ > i && j < state_length_ - i; ++j) {
43       out[i] += state_[i + j] * coefficients_[j];
44     }
45     for (; j < coefficients_length_; ++j) {
46       out[i] += in[j + i - state_length_] * coefficients_[j];
47     }
48   }
49 
50   // Update current state.
51   if (length >= state_length_) {
52     memcpy(state_.get(), &in[length - state_length_],
53            state_length_ * sizeof(*in));
54   } else {
55     memmove(state_.get(), &state_[length],
56             (state_length_ - length) * sizeof(state_[0]));
57     memcpy(&state_[state_length_ - length], in, length * sizeof(*in));
58   }
59 }
60 
61 }  // namespace webrtc
62