1 /*
2  * Copyright 2020 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 ANALYZER_PEAK_DETECTOR_H
18 #define ANALYZER_PEAK_DETECTOR_H
19 
20 #include <math.h>
21 
22 /**
23  * Measure a peak envelope by rising with the peaks,
24  * and decaying exponentially after each peak.
25  * The absolute value of the input signal is used.
26  */
27 class PeakDetector {
28 public:
29 
reset()30     void reset() {
31         mLevel = 0.0;
32     }
33 
process(double input)34     double process(double input) {
35         mLevel *= mDecay; // exponential decay
36         input = fabs(input);
37         // never fall below the input signal
38         if (input > mLevel) {
39             mLevel = input;
40         }
41         return mLevel;
42     }
43 
getLevel()44     double getLevel() const {
45         return mLevel;
46     }
47 
getDecay()48     double getDecay() const {
49         return mDecay;
50     }
51 
52     /**
53      * Multiply the level by this amount on every iteration.
54      * This provides an exponential decay curve.
55      * A value just under 1.0 is best, for example, 0.99;
56      * @param decay scale level for each input
57      */
setDecay(double decay)58     void setDecay(double decay) {
59         mDecay = decay;
60     }
61 
62 private:
63     static constexpr double kDefaultDecay = 0.99f;
64 
65     double mLevel = 0.0;
66     double mDecay = kDefaultDecay;
67 };
68 #endif //ANALYZER_PEAK_DETECTOR_H
69