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 #ifndef FLOWGRAPH_LIMITER_H 18 #define FLOWGRAPH_LIMITER_H 19 20 #include <atomic> 21 #include <unistd.h> 22 #include <sys/types.h> 23 24 #include "FlowGraphNode.h" 25 26 namespace FLOWGRAPH_OUTER_NAMESPACE::flowgraph { 27 28 class Limiter : public FlowGraphFilter { 29 public: 30 explicit Limiter(int32_t channelCount); 31 32 int32_t onProcess(int32_t numFrames) override; 33 getName()34 const char *getName() override { 35 return "Limiter"; 36 } 37 38 private: 39 // These numbers are based on a polynomial spline for a quadratic solution Ax^2 + Bx + C 40 // The range is up to 3 dB, (10^(3/20)), to match AudioTrack for float data. 41 static constexpr float kPolynomialSplineA = -0.6035533905; // -(1+sqrt(2))/4 42 static constexpr float kPolynomialSplineB = 2.2071067811; // (3+sqrt(2))/2 43 static constexpr float kPolynomialSplineC = -0.6035533905; // -(1+sqrt(2))/4 44 static constexpr float kXWhenYis3Decibels = 1.8284271247; // -1+2sqrt(2) 45 46 /** 47 * Process an input based on the following: 48 * If between -1 and 1, return the input value. 49 * If above kXWhenYis3Decibels, return sqrt(2). 50 * If below -kXWhenYis3Decibels, return -sqrt(2). 51 * If between 1 and kXWhenYis3Decibels, use a quadratic spline (Ax^2 + Bx + C). 52 * If between -kXWhenYis3Decibels and -1, use the absolute value for the spline and flip it. 53 * The derivative of the spline is 1 at 1 and 0 at kXWhenYis3Decibels. 54 * This way, the graph is both continuous and differentiable. 55 */ 56 float processFloat(float in); 57 58 // Use the previous valid output for NaN inputs 59 float mLastValidOutput = 0.0f; 60 }; 61 62 } /* namespace FLOWGRAPH_OUTER_NAMESPACE::flowgraph */ 63 64 #endif //FLOWGRAPH_LIMITER_H 65