Home | History | Annotate | Download | only in kernels
      1 /* Copyright 2017 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 
     16 #include <math.h>
     17 
     18 #include "tensorflow/core/kernels/mfcc.h"
     19 
     20 #include "tensorflow/core/platform/logging.h"
     21 
     22 namespace tensorflow {
     23 
     24 const double kDefaultUpperFrequencyLimit = 4000;
     25 const double kDefaultLowerFrequencyLimit = 20;
     26 const double kFilterbankFloor = 1e-12;
     27 const int kDefaultFilterbankChannelCount = 40;
     28 const int kDefaultDCTCoefficientCount = 13;
     29 
     30 Mfcc::Mfcc()
     31     : initialized_(false),
     32       lower_frequency_limit_(kDefaultLowerFrequencyLimit),
     33       upper_frequency_limit_(kDefaultUpperFrequencyLimit),
     34       filterbank_channel_count_(kDefaultFilterbankChannelCount),
     35       dct_coefficient_count_(kDefaultDCTCoefficientCount) {}
     36 
     37 bool Mfcc::Initialize(int input_length, double input_sample_rate) {
     38   bool initialized = mel_filterbank_.Initialize(
     39       input_length, input_sample_rate, filterbank_channel_count_,
     40       lower_frequency_limit_, upper_frequency_limit_);
     41   initialized &=
     42       dct_.Initialize(filterbank_channel_count_, dct_coefficient_count_);
     43   initialized_ = initialized;
     44   return initialized;
     45 }
     46 
     47 void Mfcc::Compute(const std::vector<double>& spectrogram_frame,
     48                    std::vector<double>* output) const {
     49   if (!initialized_) {
     50     LOG(ERROR) << "Mfcc not initialized.";
     51     return;
     52   }
     53   std::vector<double> working;
     54   mel_filterbank_.Compute(spectrogram_frame, &working);
     55   for (int i = 0; i < working.size(); ++i) {
     56     double val = working[i];
     57     if (val < kFilterbankFloor) {
     58       val = kFilterbankFloor;
     59     }
     60     working[i] = log(val);
     61   }
     62   dct_.Compute(working, output);
     63 }
     64 
     65 }  // namespace tensorflow
     66