Robert Wu | 67375a1 | 2022-08-25 22:04:29 +0000 | [diff] [blame] | 1 | /* |
| 2 | * Copyright 2022 The Android Open Source Project |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | #include <algorithm> |
| 18 | #include <math.h> |
| 19 | #include <unistd.h> |
| 20 | #include "FlowGraphNode.h" |
| 21 | #include "Limiter.h" |
| 22 | |
| 23 | using namespace FLOWGRAPH_OUTER_NAMESPACE::flowgraph; |
| 24 | |
| 25 | Limiter::Limiter(int32_t channelCount) |
| 26 | : FlowGraphFilter(channelCount) { |
| 27 | } |
| 28 | |
| 29 | int32_t Limiter::onProcess(int32_t numFrames) { |
| 30 | const float *inputBuffer = input.getBuffer(); |
| 31 | float *outputBuffer = output.getBuffer(); |
| 32 | |
| 33 | int32_t numSamples = numFrames * output.getSamplesPerFrame(); |
| 34 | |
| 35 | // Cache the last valid output to reduce memory read/write |
| 36 | float lastValidOutput = mLastValidOutput; |
| 37 | |
| 38 | for (int32_t i = 0; i < numSamples; i++) { |
| 39 | // Use the previous output if the input is NaN |
| 40 | if (!isnan(*inputBuffer)) { |
| 41 | lastValidOutput = processFloat(*inputBuffer); |
| 42 | } |
| 43 | inputBuffer++; |
| 44 | *outputBuffer++ = lastValidOutput; |
| 45 | } |
| 46 | mLastValidOutput = lastValidOutput; |
| 47 | |
| 48 | return numFrames; |
| 49 | } |
| 50 | |
| 51 | float Limiter::processFloat(float in) |
| 52 | { |
| 53 | float in_abs = fabsf(in); |
| 54 | if (in_abs <= 1) { |
| 55 | return in; |
| 56 | } |
| 57 | float out; |
| 58 | if (in_abs < kXWhenYis3Decibels) { |
| 59 | out = (kPolynomialSplineA * in_abs + kPolynomialSplineB) * in_abs + kPolynomialSplineC; |
| 60 | } else { |
| 61 | out = M_SQRT2; |
| 62 | } |
| 63 | if (in < 0) { |
| 64 | out = -out; |
| 65 | } |
| 66 | return out; |
| 67 | } |