1 /* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
2 
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6 
7     http://www.apache.org/licenses/LICENSE-2.0
8 
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15 #include "tensorflow/lite/experimental/microfrontend/lib/noise_reduction.h"
16 
17 #include <string.h>
18 
NoiseReductionApply(struct NoiseReductionState * state,uint32_t * signal)19 void NoiseReductionApply(struct NoiseReductionState* state, uint32_t* signal) {
20   int i;
21   for (i = 0; i < state->num_channels; ++i) {
22     const uint32_t smoothing =
23         ((i & 1) == 0) ? state->even_smoothing : state->odd_smoothing;
24     const uint32_t one_minus_smoothing = (1 << kNoiseReductionBits) - smoothing;
25 
26     // Update the estimate of the noise.
27     const uint32_t signal_scaled_up = signal[i] << state->smoothing_bits;
28     uint32_t estimate =
29         (((uint64_t)signal_scaled_up * smoothing) +
30          ((uint64_t)state->estimate[i] * one_minus_smoothing)) >>
31         kNoiseReductionBits;
32     state->estimate[i] = estimate;
33 
34     // Make sure that we can't get a negative value for the signal - estimate.
35     if (estimate > signal_scaled_up) {
36       estimate = signal_scaled_up;
37     }
38 
39     const uint32_t floor =
40         ((uint64_t)signal[i] * state->min_signal_remaining) >>
41         kNoiseReductionBits;
42     const uint32_t subtracted =
43         (signal_scaled_up - estimate) >> state->smoothing_bits;
44     const uint32_t output = subtracted > floor ? subtracted : floor;
45     signal[i] = output;
46   }
47 }
48 
NoiseReductionReset(struct NoiseReductionState * state)49 void NoiseReductionReset(struct NoiseReductionState* state) {
50   memset(state->estimate, 0, sizeof(*state->estimate) * state->num_channels);
51 }
52