blob: 3f1fa09b51509d835a359d563f86f3155f95ee24 [file] [log] [blame]
Patrik Höglundf715c532017-11-17 11:04:15 +01001/*
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>
Jonas Olssona4d87372019-07-05 19:08:33 +020014
Patrik Höglundf715c532017-11-17 11:04:15 +010015#include <memory>
16
Patrik Höglundf715c532017-11-17 11:04:15 +010017#include "rtc_base/checks.h"
18
19namespace webrtc {
20
Yves Gerey665174f2018-06-19 15:03:05 +020021FIRFilterC::~FIRFilterC() {}
Patrik Höglundf715c532017-11-17 11:04:15 +010022
23FIRFilterC::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
34void 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_) {
Yves Gerey665174f2018-06-19 15:03:05 +020052 memcpy(state_.get(), &in[length - state_length_],
53 state_length_ * sizeof(*in));
Patrik Höglundf715c532017-11-17 11:04:15 +010054 } else {
Yves Gerey665174f2018-06-19 15:03:05 +020055 memmove(state_.get(), &state_[length],
Patrik Höglundf715c532017-11-17 11:04:15 +010056 (state_length_ - length) * sizeof(state_[0]));
57 memcpy(&state_[state_length_ - length], in, length * sizeof(*in));
58 }
59}
60
61} // namespace webrtc