Source

jackpipe-dev / src / aat / aat.cxx

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
/*
 * Copyright © 2011 Aleksey Kunitskiy <alexey.kv@gmail.com>
 * 
 * This file is part of JackPipe
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <iostream>
#include <string>
#include <vector>
#include <memory>

#include <tclap/CmdLine.h>
#include <tclap/Constraint.h>

#include <jackaudioio.hpp>

#include "Util.h"
#include "WindowingFunction.h"
#include "FftSineGenerator.h"
#include "LinearFftAnalizer.h"
#include "JackLoopBufferManager.h"

const char app_name[]     = "JackPipe Audio Analizing Tool";
unsigned   version        = 0x000001;
const char version_str[]  = "0.0.1";

namespace TP = TCLAP;

struct invalidPort : public std::range_error {
  const unsigned ports;
  explicit invalidPort(const unsigned p)
    : std::range_error("Invalid port number"),
    ports(p) {} };

    
template<typename T>
class AatFrequencyResponseLoop : public JackCpp::AudioIO {

  std::auto_ptr< JackPipe::FftSineGenerator<T> >  _lFftG;
  std::auto_ptr< JackPipe::LinearFftAnalizer<T> > _lFftA;
  std::auto_ptr< JackPipe::JackLoopBufferManager<T> > _jlbm;
  JackPipe::WindowingFunction<T>  _wF;
  
  typename JackPipe::Vector<T>::vec16_t _b;
  typename JackPipe::Vector<T>::vec16_t _ob;
  typename JackPipe::Vector<T>::vec16_t _fr;

  T _signalNormFactor;
  bool _rms;

  bool _verbose;
  std::ostream& _vOutput;

  unsigned _popSkip;

  float _obSizeParam;

  unsigned _jackPhysicalInPort;
  unsigned _jackPhysicalOutPort;

  protected:
    virtual int audioCallback(jack_nframes_t nframes, 
        audioBufVector inBufs,
        audioBufVector outBufs)
    {
      static int popBufferStatus = -1;
      static int pushBufferStatus = -1;

      if (_popSkip > 0)
      {
        // fill output with zeros to avoid nonzero shit on input
        std::fill_n(outBufs[0], nframes, 0.0f);
        _popSkip--;
        return 0;
      }

      if (_rms)
      {
        popBufferStatus = _jlbm->pop(outBufs[0], nframes);
        if (popBufferStatus == JackPipe::JackLoopBufferManager<T>::ib_end)
          std::fill_n(outBufs[0], nframes, 0.0f);
        float rms = JackPipe::rmsPower<float>(inBufs[0], nframes);
        if (_verbose)
          _vOutput << "rms " << rms << std::endl;
        if (rms > _obSizeParam)
        {
          if (_verbose)
            _vOutput << "push ok" <<  std::endl;
          pushBufferStatus = _jlbm->push(inBufs[0], nframes);
          if (pushBufferStatus == JackPipe::JackLoopBufferManager<T>::ob_full)
          {
            if (_verbose)
              _vOutput << "ob_end" << std::endl;
            return 1;
          }
          return 0;
        }
        else if (pushBufferStatus != -1)
        {
          _jlbm->push(inBufs[0], nframes);
          return 1; // rms <= noise, maybe xrun
        }
        else return 0;
      }
      return 1;
    }

  public:
  AatFrequencyResponseLoop(
      const T f0,
      const T f1,
      const unsigned uB,
      const bool base2,
      std::string const& window,
      float obSizeParam,
      unsigned jackPhysicalInPort = 0,
      unsigned jackPhysicalOutPort = 0,
      bool rms = true,
      bool verbose = false,
      std::ostream& vOutput = std::cerr ) :
    JackCpp::AudioIO("AAT frequency response loop", 1, 1, false),
    _wF(window.c_str()),
    _rms(rms),
    _verbose(verbose),
    _vOutput(vOutput),
    _popSkip(5),
    _obSizeParam(obSizeParam),
    _jackPhysicalInPort(jackPhysicalInPort),
    _jackPhysicalOutPort(jackPhysicalOutPort)
  {
    _lFftG = std::auto_ptr< JackPipe::FftSineGenerator<T> >
      ( new JackPipe::FftSineGenerator<T>(f0, f1, getSampleRate(), uB, base2, getTime()) );
    _lFftA = std::auto_ptr< JackPipe::LinearFftAnalizer<T> >
      ( new JackPipe::LinearFftAnalizer<T>(*_lFftG) );
    _wF.pokeCache(_lFftG->getBufferSize());

    _lFftG->generateSignal(_b);
    _wF.apply(_b, _lFftG->getBufferSize());

    _signalNormFactor = 
      JackPipe::Vector<T>::normalize(_b, _lFftG->getBufferSize());

    if (rms)
    {
      _jlbm = std::auto_ptr< JackPipe::JackLoopBufferManager<T> >
        ( new JackPipe::JackLoopBufferManager<T>(_b, _ob, _lFftG->getBufferSize() + 4096u) );
    }
    else
    {
      unsigned obSize = static_cast<unsigned>
        ( static_cast<float>(_lFftG->getBufferSize()) * _obSizeParam + 0.5f );

      _jlbm = std::auto_ptr< JackPipe::JackLoopBufferManager<T> >
        ( new JackPipe::JackLoopBufferManager<T>(_b, _ob, obSize) );
    }
  }

  typename JackPipe::Vector<T>::vec16_t const&
    getFR() { return _fr; }

  unsigned getFRSize() { return _lFftA->getTransformSize(); }

  void run() {
    start();
    try {
      connectFromPhysical(0, _jackPhysicalInPort);
    }
    catch (std::range_error) {
      throw(invalidPort(numPhysicalSourcePorts()));
    }
    try {
      connectToPhysical(0, _jackPhysicalOutPort);
    }
    catch (std::range_error) {
      throw(invalidPort(numPhysicalDestinationPorts()));
    }
    wait();
    close();

    _lFftA->analize(_ob, _jlbm->getPushedSize());

    _lFftA->getResult(_fr);
    JackPipe::Vector<T>::scaleVecMul(_fr, _signalNormFactor / _wF.getDensityFactor());

    // debug stuff
    if (_verbose)
    {
      _vOutput << "buffer size " << _lFftG->getBufferSize() << std::endl;
      _vOutput << "pushed size " << _jlbm->getPushedSize() << std::endl;
    }
    //JackPipe::Vector<T>::saveAscii("b.dat", _b, _lFftG->getBufferSize());
    //JackPipe::Vector<T>::saveAscii("ob.dat", _ob, _jlbm->getPushedSize());
  }

};

class AatJackNoiseMeasureLoop : public JackCpp::AudioIO {

  unsigned _samplesMax;
  unsigned _samplesAnalized;
  unsigned _jackPhysicalInPort;
  float _maxRMS;
  float _prevRMS;

  static const unsigned silenceFrames = 1;
  unsigned _framesToSkip;

  protected:
    virtual int audioCallback(jack_nframes_t nframes, 
        audioBufVector inBufs,
        audioBufVector outBufs) {
      if (_framesToSkip > 0)
      {
        --_framesToSkip;
        std::fill_n(outBufs[0], nframes, 0.0f);
        return 0;
      }
      else
      {
        if (_samplesAnalized + nframes > _samplesMax)
          return 1;
        else {
          _maxRMS = std::max(
              JackPipe::rmsPower<float>(inBufs[0], nframes),
              _prevRMS );
          _prevRMS = _maxRMS;
          _samplesAnalized += nframes;
          return 0;
        }
      }
    }
  public:

    explicit
    AatJackNoiseMeasureLoop(unsigned samplesMax, unsigned inPort)
      : JackCpp::AudioIO("AAT noise measure loop", 1, 1, false),
        _samplesMax(samplesMax),
        _jackPhysicalInPort(inPort)
    {}

    explicit
    AatJackNoiseMeasureLoop(float measureTime, unsigned inPort)
      : JackCpp::AudioIO("AAT noise measure loop", 1, 1, false),
        _jackPhysicalInPort(inPort)
    {
      _samplesMax = static_cast<unsigned>(
          static_cast<float>(getSampleRate()) * measureTime );
    }

    float measure() {
      _maxRMS = 0.0f;
      _prevRMS = 0.0f;
      _samplesAnalized = 0;
      _framesToSkip = silenceFrames;
      start();
      try {
        connectFromPhysical(0, _jackPhysicalInPort);
      }
      catch (std::range_error) {
        throw(invalidPort(numPhysicalSourcePorts()));
      }
      wait();
      close();
      return _maxRMS;
    }

    virtual ~AatJackNoiseMeasureLoop(){};

};

//{{{ TODO class FloatingTypeConstraint
class FloatingTypeConstraint : public TP::Constraint<char>
{
  public:
    std::string description() const { 
      std::string descString = "supported floating-point types:";
      return descString;
    }

    std::string shortID() const { return "string"; }

    bool check(char const& value) const {
      return true;
    }
};
//}}}

class WindowingFunctionConstraint : public TP::Constraint<std::string>
{
  static const char _constraint_str[];
  public:
    std::string description() const { 
      std::string descString = "supported windowing functions:";
      for (unsigned i = 0;
          i < JackPipe::WindowingFunctionStatic::windowCount;
          i++ ) {
        descString += ' ' + JackPipe::WindowingFunctionStatic::windowList[i];
      }
      return descString;
    }

    std::string shortID() const { return "string"; }

    bool check(std::string const& value) const {
      for (unsigned i = 0;
          i < JackPipe::WindowingFunctionStatic::windowCount;
          i++ ) {
        if (value == JackPipe::WindowingFunctionStatic::windowList[i])
          return true;
      }
      return false;
    }
};

int main(int argc, const char *argv[])
{
  TP::CmdLine cmd(app_name, ' ', version_str);

  FloatingTypeConstraint fpc;
  WindowingFunctionConstraint wfc;
  TP::ValueArg<float> f0
    ( "B", "fbase", "Base/step frequency", true, 20.0f, "number" );
  TP::ValueArg<float> f1
    ( "S", "fstop", "Stop frequency", true, 20000.0f, "number" );
  TP::ValueArg<unsigned> uB
    ( "l", "blocks", "Number of logical blocks", false, 8, "number" );
  TP::SwitchArg base2
    ( "p", "base2approx", "Make signal/input buffers sizes power-of-2", false );
  TP::SwitchArg rmsStartStop
    ( "r", "rmsstartstop", "Signal start/stop markers calculated by maximum noise RMS value", false );
  TP::SwitchArg bVerbose
    ( "v", "verbose", "Verbose mode", false );
  TP::ValueArg<float> outBufferSize
    ( "b", "outbuffer", "Output buffer size in case if --rmsstartstop not set, otherwise time in seconds to measure noise RMS",
      false, 1.0f, "number" );
  TP::ValueArg<char> floatingPointType
    ( "t", "fptype", "Transformation size", false, 'f', &fpc );
  TP::ValueArg<unsigned> jackInPortPhysical
    ( "i", "inputport", "Jack physical input port number", false, 0, "number" );
  TP::ValueArg<unsigned> jackOutPortPhysical
    ( "o", "outputport", "Jack physical output port number", false, 0, "number" );
  TP::ValueArg<std::string> windowingFunctionType
    ( "w", "window", "Windowing function type", false, "hanning", &wfc );
  TP::ValueArg<std::string> recalibrationFilePath
    ( "R", "recal", "Recalibration file path", false, "", "path");
  TP::ValueArg<std::string> frOutputFilePath
    ( "O", "froutput", "Recalibration file path", true, "", "path");

  try {
    //cmd.add(floatingPointType);
    cmd.add(rmsStartStop);
    cmd.add(outBufferSize);
    cmd.add(f0);
    cmd.add(f1);
    cmd.add(uB);
    cmd.add(base2);
    cmd.add(windowingFunctionType);
    cmd.add(jackInPortPhysical);
    cmd.add(jackOutPortPhysical);
    cmd.add(recalibrationFilePath);
    cmd.add(frOutputFilePath);
    cmd.add(bVerbose);

    cmd.parse(argc, argv);

    if (rmsStartStop.getValue())
    {
      AatJackNoiseMeasureLoop aatml
        (outBufferSize.getValue(), jackInPortPhysical.getValue());
      float rms = aatml.measure();
      std::cout << "measured noise RMS: " << rms << std::endl;

      AatFrequencyResponseLoop<double> aatfrl(
          f0.getValue(),
          f1.getValue(),
          uB.getValue(),
          base2.getValue(),
          windowingFunctionType.getValue(),
          rms,
          jackInPortPhysical.getValue(),
          jackOutPortPhysical.getValue(),
          true,
          bVerbose.getValue()
         );

      aatfrl.run();

      if (recalibrationFilePath.getValue() != "")
      {
        typename JackPipe::Vector<double>::vec16_t rec;
        typename JackPipe::Vector<double>::vec16_t fr = aatfrl.getFR();

        unsigned N = 
          JackPipe::Vector<double>::loadAscii
          ( recalibrationFilePath.getValue().c_str(), rec );

        if (N != aatfrl.getFRSize())
          throw std::invalid_argument("recalibration vector and fr vector size are different");
        else
          JackPipe::Vector<double>::vecDiv(fr, rec);

        JackPipe::Vector<double>::saveAscii(frOutputFilePath.getValue().c_str(), fr);
      }
      else
        JackPipe::Vector<double>::saveAscii(frOutputFilePath.getValue().c_str(), aatfrl.getFR());

    }
  } catch (TP::ArgException &ae) {
    std::cerr << "Error: " << ae.error() << " for arg " << ae.argId() << std::endl;
    return 1;
  } catch (invalidPort &ip) {
    std::cerr << "Invalid source port, total availible ports: "
      << ip.ports << std::endl;
    return 2;
  }
  return 0;
}

//  vim:set ts=2 sw=2 tw=78 et: