compute-mfcc-feats.cc
Go to the documentation of this file.
1 // featbin/compute-mfcc-feats.cc
2 
3 // Copyright 2009-2012 Microsoft Corporation
4 // Johns Hopkins University (author: Daniel Povey)
5 
6 // See ../../COPYING for clarification regarding multiple authors
7 //
8 // Licensed under the Apache License, Version 2.0 (the "License");
9 // you may not use this file except in compliance with the License.
10 // You may obtain a copy of the License at
11 //
12 // http://www.apache.org/licenses/LICENSE-2.0
13 //
14 // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
16 // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
17 // MERCHANTABLITY OR NON-INFRINGEMENT.
18 // See the Apache 2 License for the specific language governing permissions and
19 // limitations under the License.
20 
21 #include "base/kaldi-common.h"
22 #include "feat/feature-mfcc.h"
23 #include "feat/wave-reader.h"
24 #include "util/common-utils.h"
25 
26 int main(int argc, char *argv[]) {
27  try {
28  using namespace kaldi;
29  const char *usage =
30  "Create MFCC feature files.\n"
31  "Usage: compute-mfcc-feats [options...] <wav-rspecifier> "
32  "<feats-wspecifier>\n";
33 
34  // Construct all the global objects.
35  ParseOptions po(usage);
36  MfccOptions mfcc_opts;
37  // Define defaults for global options.
38  bool subtract_mean = false;
39  BaseFloat vtln_warp = 1.0;
40  std::string vtln_map_rspecifier;
41  std::string utt2spk_rspecifier;
42  int32 channel = -1;
43  BaseFloat min_duration = 0.0;
44  std::string output_format = "kaldi";
45  std::string utt2dur_wspecifier;
46 
47  // Register the MFCC option struct.
48  mfcc_opts.Register(&po);
49 
50  // Register the options.
51  po.Register("output-format", &output_format, "Format of the output "
52  "files [kaldi, htk]");
53  po.Register("subtract-mean", &subtract_mean, "Subtract mean of each "
54  "feature file [CMS]; not recommended to do it this way. ");
55  po.Register("vtln-warp", &vtln_warp, "Vtln warp factor (only applicable "
56  "if vtln-map not specified)");
57  po.Register("vtln-map", &vtln_map_rspecifier, "Map from utterance or "
58  "speaker-id to vtln warp factor (rspecifier)");
59  po.Register("utt2spk", &utt2spk_rspecifier, "Utterance to speaker-id map "
60  "rspecifier (if doing VTLN and you have warps per speaker)");
61  po.Register("channel", &channel, "Channel to extract (-1 -> expect mono, "
62  "0 -> left, 1 -> right)");
63  po.Register("min-duration", &min_duration, "Minimum duration of segments "
64  "to process (in seconds).");
65  po.Register("write-utt2dur", &utt2dur_wspecifier, "Wspecifier to write "
66  "duration of each utterance in seconds, e.g. 'ark,t:utt2dur'.");
67 
68  po.Read(argc, argv);
69 
70  if (po.NumArgs() != 2) {
71  po.PrintUsage();
72  exit(1);
73  }
74 
75  std::string wav_rspecifier = po.GetArg(1);
76 
77  std::string output_wspecifier = po.GetArg(2);
78 
79  Mfcc mfcc(mfcc_opts);
80 
81  if (utt2spk_rspecifier != "" && vtln_map_rspecifier == "")
82  KALDI_ERR << ("The --utt2spk option is only needed if "
83  "the --vtln-map option is used.");
84  RandomAccessBaseFloatReaderMapped vtln_map_reader(vtln_map_rspecifier,
85  utt2spk_rspecifier);
86 
87  SequentialTableReader<WaveHolder> reader(wav_rspecifier);
88  BaseFloatMatrixWriter kaldi_writer; // typedef to TableWriter<something>.
90 
91  if (output_format == "kaldi") {
92  if (!kaldi_writer.Open(output_wspecifier))
93  KALDI_ERR << "Could not initialize output with wspecifier "
94  << output_wspecifier;
95  } else if (output_format == "htk") {
96  if (!htk_writer.Open(output_wspecifier))
97  KALDI_ERR << "Could not initialize output with wspecifier "
98  << output_wspecifier;
99  } else {
100  KALDI_ERR << "Invalid output_format string " << output_format;
101  }
102 
103  DoubleWriter utt2dur_writer(utt2dur_wspecifier);
104 
105  int32 num_utts = 0, num_success = 0;
106  for (; !reader.Done(); reader.Next()) {
107  num_utts++;
108  std::string utt = reader.Key();
109  const WaveData &wave_data = reader.Value();
110  if (wave_data.Duration() < min_duration) {
111  KALDI_WARN << "File: " << utt << " is too short ("
112  << wave_data.Duration() << " sec): producing no output.";
113  continue;
114  }
115  int32 num_chan = wave_data.Data().NumRows(), this_chan = channel;
116  { // This block works out the channel (0=left, 1=right...)
117  KALDI_ASSERT(num_chan > 0); // should have been caught in
118  // reading code if no channels.
119  if (channel == -1) {
120  this_chan = 0;
121  if (num_chan != 1)
122  KALDI_WARN << "Channel not specified but you have data with "
123  << num_chan << " channels; defaulting to zero";
124  } else {
125  if (this_chan >= num_chan) {
126  KALDI_WARN << "File with id " << utt << " has "
127  << num_chan << " channels but you specified channel "
128  << channel << ", producing no output.";
129  continue;
130  }
131  }
132  }
133  BaseFloat vtln_warp_local; // Work out VTLN warp factor.
134  if (vtln_map_rspecifier != "") {
135  if (!vtln_map_reader.HasKey(utt)) {
136  KALDI_WARN << "No vtln-map entry for utterance-id (or speaker-id) "
137  << utt;
138  continue;
139  }
140  vtln_warp_local = vtln_map_reader.Value(utt);
141  } else {
142  vtln_warp_local = vtln_warp;
143  }
144 
145  SubVector<BaseFloat> waveform(wave_data.Data(), this_chan);
146  Matrix<BaseFloat> features;
147  try {
148  mfcc.ComputeFeatures(waveform, wave_data.SampFreq(),
149  vtln_warp_local, &features);
150  } catch (...) {
151  KALDI_WARN << "Failed to compute features for utterance " << utt;
152  continue;
153  }
154  if (subtract_mean) {
155  Vector<BaseFloat> mean(features.NumCols());
156  mean.AddRowSumMat(1.0, features);
157  mean.Scale(1.0 / features.NumRows());
158  for (int32 i = 0; i < features.NumRows(); i++)
159  features.Row(i).AddVec(-1.0, mean);
160  }
161  if (output_format == "kaldi") {
162  kaldi_writer.Write(utt, features);
163  } else {
164  std::pair<Matrix<BaseFloat>, HtkHeader> p;
165  p.first.Resize(features.NumRows(), features.NumCols());
166  p.first.CopyFromMat(features);
167  HtkHeader header = {
168  features.NumRows(),
169  100000, // 10ms shift
170  static_cast<int16>(sizeof(float)*(features.NumCols())),
171  static_cast<uint16>( 006 | // MFCC
172  (mfcc_opts.use_energy ? 0100 : 020000)) // energy; otherwise c0
173  };
174  p.second = header;
175  htk_writer.Write(utt, p);
176  }
177  if (utt2dur_writer.IsOpen()) {
178  utt2dur_writer.Write(utt, wave_data.Duration());
179  }
180  if (num_utts % 10 == 0)
181  KALDI_LOG << "Processed " << num_utts << " utterances";
182  KALDI_VLOG(2) << "Processed features for key " << utt;
183  num_success++;
184  }
185  KALDI_LOG << " Done " << num_success << " out of " << num_utts
186  << " utterances.";
187  return (num_success != 0 ? 0 : 1);
188  } catch(const std::exception &e) {
189  std::cerr << e.what();
190  return -1;
191  }
192 }
This code computes Goodness of Pronunciation (GOP) and extracts phone-level pronunciation feature for...
Definition: chain.dox:20
bool Open(const std::string &wspecifier)
void AddRowSumMat(Real alpha, const MatrixBase< Real > &M, Real beta=1.0)
Does *this = alpha * (sum of rows of M) + beta * *this.
void ComputeFeatures(const VectorBase< BaseFloat > &wave, BaseFloat sample_freq, BaseFloat vtln_warp, Matrix< BaseFloat > *output)
Computes the features for one file (one sequence of features).
MfccOptions contains basic options for computing MFCC features.
Definition: feature-mfcc.h:38
void PrintUsage(bool print_command_line=false)
Prints the usage documentation [provided in the constructor].
This class is for when you are reading something in random access, but it may actually be stored per-...
Definition: kaldi-table.h:432
A templated class for writing objects to an archive or script file; see The Table concept...
Definition: kaldi-table.h:368
kaldi::int32 int32
BaseFloat SampFreq() const
Definition: wave-reader.h:126
const Matrix< BaseFloat > & Data() const
Definition: wave-reader.h:124
void Write(const std::string &key, const T &value) const
void Register(const std::string &name, bool *ptr, const std::string &doc)
float BaseFloat
Definition: kaldi-types.h:29
The class ParseOptions is for parsing command-line options; see Parsing command-line options for more...
Definition: parse-options.h:36
A templated class for reading objects sequentially from an archive or script file; see The Table conc...
Definition: kaldi-table.h:287
int Read(int argc, const char *const *argv)
Parses the command line options and fills the ParseOptions-registered variables.
#define KALDI_ERR
Definition: kaldi-error.h:147
int main(int argc, char *argv[])
#define KALDI_WARN
Definition: kaldi-error.h:150
std::string GetArg(int param) const
Returns one of the positional parameters; 1-based indexing for argc/argv compatibility.
This class&#39;s purpose is to read in Wave files.
Definition: wave-reader.h:106
int NumArgs() const
Number of positional parameters (c.f. argc-1).
A class representing a vector.
Definition: kaldi-vector.h:406
#define KALDI_ASSERT(cond)
Definition: kaldi-error.h:185
MatrixIndexT NumRows() const
Returns number of rows (or zero for empty matrix).
Definition: kaldi-matrix.h:64
#define KALDI_VLOG(v)
Definition: kaldi-error.h:156
void Register(OptionsItf *opts)
Definition: feature-mfcc.h:62
BaseFloat Duration() const
Definition: wave-reader.h:129
This templated class is intended for offline feature extraction, i.e.
#define KALDI_LOG
Definition: kaldi-error.h:153
void AddVec(const Real alpha, const VectorBase< OtherReal > &v)
Add vector : *this = *this + alpha * rv (with casting between floats and doubles) ...
A structure containing the HTK header.
Definition: kaldi-matrix.h:955
Represents a non-allocating general vector which can be defined as a sub-vector of higher-level vecto...
Definition: kaldi-vector.h:501