1 // Copyright 2015 Olivier Gillet.
2 //
3 // Author: Olivier Gillet (ol.gillet@gmail.com)
4 //
5 // Permission is hereby granted, free of charge, to any person obtaining a copy
6 // of this software and associated documentation files (the "Software"), to deal
7 // in the Software without restriction, including without limitation the rights
8 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 // copies of the Software, and to permit persons to whom the Software is
10 // furnished to do so, subject to the following conditions:
11 //
12 // The above copyright notice and this permission notice shall be included in
13 // all copies or substantial portions of the Software.
14 //
15 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 // THE SOFTWARE.
22 //
23 // See http://creativecommons.org/licenses/MIT/ for more information.
24 //
25 // -----------------------------------------------------------------------------
26 //
27 // Quantize a float in [0, 1] to an integer in [0, num_steps[. Apply hysteresis
28 // to prevent jumps near the decision boundary.
29 
30 #ifndef STMLIB_DSP_HYSTERESIS_QUANTIZER_H_
31 #define STMLIB_DSP_HYSTERESIS_QUANTIZER_H_
32 
33 #include "stmlib/stmlib.h"
34 
35 namespace stmlib {
36 
37 class HysteresisQuantizer {
38  public:
HysteresisQuantizer()39   HysteresisQuantizer() { }
~HysteresisQuantizer()40   ~HysteresisQuantizer() { }
41 
Init()42   void Init() {
43     quantized_value_ = 0;
44   }
45 
Process(float value,int num_steps)46   int Process(float value, int num_steps) {
47     return Process(value, num_steps, 0.25f);
48   }
49 
Process(float value,int num_steps,float hysteresis)50   int Process(float value, int num_steps, float hysteresis) {
51     value *= static_cast<float>(num_steps - 1);
52     float hysteresis_feedback = value > static_cast<float>(quantized_value_)
53         ? -hysteresis
54         : hysteresis;
55     int q = static_cast<int>(value + hysteresis_feedback + 0.5f);
56     CONSTRAIN(q, 0, num_steps - 1);
57     quantized_value_ = q;
58     return q;
59   }
60 
61   template<typename T>
Lookup(const T * array,float value,int num_steps)62   const T& Lookup(const T* array, float value, int num_steps) {
63     return array[Process(value, num_steps)];
64   }
65 
66  private:
67   int quantized_value_;
68 
69   DISALLOW_COPY_AND_ASSIGN(HysteresisQuantizer);
70 };
71 
72 }  // namespace stmlib
73 
74 #endif  // STMLIB_DSP_HYSTERESIS_QUANTIZER_H_
75