Home | History | Annotate | Download | only in lib
      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/pcan_gain_control.h"
     16 
     17 #include "tensorflow/lite/experimental/microfrontend/lib/bits.h"
     18 
     19 int16_t WideDynamicFunction(const uint32_t x, const int16_t* lut) {
     20   if (x <= 2) {
     21     return lut[x];
     22   }
     23 
     24   const int16_t interval = MostSignificantBit32(x);
     25   lut += 4 * interval - 6;
     26 
     27   const int16_t frac = ((interval < 11)
     28                         ? (x << (11 - interval))
     29                         : (x >> (interval - 11))
     30                        ) & 0x3FF;
     31 
     32   int32_t result = ((int32_t) lut[2] * frac) >> 5;
     33   result += ((int32_t) lut[1]) << 5;
     34   result *= frac;
     35   result = (result + (1 << 14)) >> 15;
     36   result += lut[0];
     37   return (int16_t) result;
     38 }
     39 
     40 uint32_t PcanShrink(const uint32_t x) {
     41   if (x < (2 << kPcanSnrBits)) {
     42     return (x * x) >> (2 + 2 * kPcanSnrBits - kPcanOutputBits);
     43   } else {
     44     return (x >> (kPcanSnrBits - kPcanOutputBits)) - (1 << kPcanOutputBits);
     45   }
     46 }
     47 
     48 void PcanGainControlApply(struct PcanGainControlState* state,
     49                           uint32_t* signal) {
     50   int i;
     51   for (i = 0; i < state->num_channels; ++i) {
     52     const uint32_t gain = WideDynamicFunction(state->noise_estimate[i],
     53                                               state->gain_lut);
     54     const uint32_t snr = ((uint64_t) signal[i] * gain) >> state->snr_shift;
     55     signal[i] = PcanShrink(snr);
     56   }
     57 }
     58