Changes in / [c03d191:088760e]


Ignore:
Files:
2 added
3 deleted
42 edited

Legend:

Unmodified
Added
Removed
  • .gitignore

    rc03d191 r088760e  
    4949python/tests/sounds
    5050aubio.egg-info
    51 .eggs
    52 .cache
  • MANIFEST.in

    rc03d191 r088760e  
    22include python/README.md
    33include this_version.py
    4 include waf
    5 recursive-include waflib *.py
    64include Makefile wscript */wscript_build
     5include waf waflib/* waflib/*/*
     6exclude waflib/__pycache__/*
    77include aubio.pc.in
    88include nose2.cfg
     
    1313include tests/*.h tests/*/*.c tests/*/*/*.c
    1414include python/ext/*.h
    15 recursive-include python *.py
    16 include python/README.md
     15include python/__init__.py
     16include python/lib/__init__.py
     17include python/lib/moresetuptools.py
     18include python/lib/gen_external.py
     19include python/lib/gen_code.py
    1720include python/tests/run_all_tests
     21include python/tests/*.py
    1822include python/tests/eval_pitch
     23include python/demos/*.py
    1924include python/tests/*.expected
    2025include doc/*.txt doc/*.rst doc/*.cfg doc/Makefile doc/make.bat doc/conf.py
  • Makefile

    rc03d191 r088760e  
    234234        uninstall_python \
    235235        check_clean_python
    236 
    237 coverage_cycle: coverage_zero_counters coverage_report
    238 
    239 coverage_zero_counters:
    240         lcov --zerocounters --directory .
    241236
    242237coverage: export CFLAGS=--coverage
     
    252247        lcov -a build/coverage_python.info -a build/coverage_lib.info -o build/coverage.info
    253248
    254 # make sure we don't build the doc, which builds a temporary python module
    255 coverage_report: export WAFOPTS += --disable-docs
    256249coverage_report: coverage
    257250        genhtml build/coverage.info --output-directory lcov_html
  • doc/py_io.rst

    rc03d191 r088760e  
    4040    down-mixed to produce the new samples.
    4141
    42     :returns: A tuple of one array of samples and one integer.
     42    return: A tuple of one array of samples and one integer.
    4343    :rtype: (array, int)
    4444
  • doc/py_utils.rst

    rc03d191 r088760e  
    2828
    2929.. autofunction:: miditofreq
    30 
    31 .. python/ext/py-musicutils.h
    32 
    33 .. autofunction:: meltohz
    34 
    35 .. autofunction:: hztomel
    3630
    3731.. python/ext/aubiomodule.c
  • python/demos/demo_filter.py

    rc03d191 r088760e  
    44import os.path
    55import aubio
    6 
    76
    87def apply_filter(path, target):
     
    2928        total_frames += read
    3029        # end of file reached
    31         if read < s.hop_size:
    32             break
     30        if read < s.hop_size: break
    3331
    3432    # print some info
     
    3634    input_str = "input: {:s} ({:.2f} s, {:d} Hz)"
    3735    output_str = "output: {:s}, A-weighting filtered ({:d} frames total)"
    38     print(input_str.format(s.uri, duration, samplerate))
    39     print(output_str.format(o.uri, total_frames))
     36    print (input_str.format(s.uri, duration, samplerate))
     37    print (output_str.format(o.uri, total_frames))
    4038
    4139if __name__ == '__main__':
    4240    usage = "{:s} <input_file> [output_file]".format(sys.argv[0])
    4341    if not 1 < len(sys.argv) < 4:
    44         print(usage)
     42        print (usage)
    4543        sys.exit(1)
    4644    if len(sys.argv) < 3:
  • python/demos/demo_filterbank.py

    rc03d191 r088760e  
    11#! /usr/bin/env python
    22
    3 """Create a filterbank from a list of frequencies.
     3from aubio import filterbank, fvec
     4from pylab import loglog, show, xlim, ylim, xlabel, ylabel, title
     5from numpy import vstack, arange
    46
    5 This demo uses `aubio.filterbank.set_triangle_bands` to build a set of
    6 triangular filters from a list of frequencies.
     7win_s = 2048
     8samplerate = 48000
    79
    8 The filterbank coefficients are then modified before being displayed."""
    9 
    10 import aubio
    11 import numpy as np
    12 import matplotlib.pyplot as plt
    13 
    14 # sampling rate and size of the fft
    15 samplerate = 48000
    16 win_s = 2048
    17 
    18 # define a list of custom frequency
    1910freq_list = [60, 80, 200, 400, 800, 1600, 3200, 6400, 12800, 24000]
    20 # number of filters to create
    2111n_filters = len(freq_list) - 2
    2212
    23 # create a new filterbank
    24 f = aubio.filterbank(n_filters, win_s)
    25 freqs = aubio.fvec(freq_list)
     13f = filterbank(n_filters, win_s)
     14freqs = fvec(freq_list)
    2615f.set_triangle_bands(freqs, samplerate)
    2716
    28 # get the coefficients from the filterbank
    2917coeffs = f.get_coeffs()
    30 # apply a gain to fifth band
    31 coeffs[4] *= 6.
    32 # load the modified coeffs into the filterbank
     18coeffs[4] *= 5.
     19
    3320f.set_coeffs(coeffs)
    3421
    35 # display the band gains in a loglog plot
    36 freqs = np.vstack([np.arange(win_s // 2 + 1) * samplerate / win_s] * n_filters)
    37 plt.title('filterbank built from a list of frequencies\n'
    38           'The 5th band has been amplified by a factor 6.')
    39 plt.loglog(freqs.T, f.get_coeffs().T, '.-')
    40 plt.xlim([50, samplerate/2])
    41 plt.ylim([1.0e-6, 2.0e-2])
    42 plt.xlabel('log frequency (Hz)')
    43 plt.ylabel('log amplitude')
    44 plt.show()
     22times = vstack([arange(win_s // 2 + 1) * samplerate / win_s] * n_filters)
     23title('Bank of filters built using a simple list of boundaries\nThe middle band has been amplified by 2.')
     24loglog(times.T, f.get_coeffs().T, '.-')
     25xlim([50, samplerate/2])
     26ylim([1.0e-6, 2.0e-2])
     27xlabel('log frequency (Hz)')
     28ylabel('log amplitude')
     29
     30show()
  • python/demos/demo_source_simple.py

    rc03d191 r088760e  
    11#! /usr/bin/env python
    2 
    3 """A simple example using aubio.source."""
    4 
    52import sys
    63import aubio
    74
    8 samplerate = 0  # use original source samplerate
    9 hop_size = 256  # number of frames to read in one block
     5samplerate = 0 # use original source samplerate
     6hop_size = 256 # number of frames to read in one block
    107src = aubio.source(sys.argv[1], samplerate, hop_size)
    118total_frames = 0
    129
    1310while True:
    14     samples, read = src()  # read hop_size new samples from source
    15     total_frames += read   # increment total number of frames
    16     if read < hop_size:    # end of file reached
    17         break
     11    samples, read = src()     # read hop_size new samples from source
     12    total_frames += read      # increment total number of frames
     13    if read < hop_size: break # end of file reached
    1814
    1915fmt_string = "read {:d} frames at {:d}Hz from {:s}"
    20 print(fmt_string.format(total_frames, src.samplerate, src.uri))
     16print (fmt_string.format(total_frames, src.samplerate, src.uri))
  • python/ext/aubiomodule.c

    rc03d191 r088760e  
    373373  {"shift", Py_aubio_shift, METH_VARARGS, Py_aubio_shift_doc},
    374374  {"ishift", Py_aubio_ishift, METH_VARARGS, Py_aubio_ishift_doc},
    375   {"hztomel", Py_aubio_hztomel, METH_VARARGS|METH_KEYWORDS, Py_aubio_hztomel_doc},
    376   {"meltohz", Py_aubio_meltohz, METH_VARARGS|METH_KEYWORDS, Py_aubio_meltohz_doc},
    377   {"hztomel_htk", Py_aubio_hztomel_htk, METH_VARARGS, Py_aubio_hztomel_htk_doc},
    378   {"meltohz_htk", Py_aubio_meltohz_htk, METH_VARARGS, Py_aubio_meltohz_htk_doc},
    379375  {NULL, NULL, 0, NULL} /* Sentinel */
    380376};
  • python/ext/py-filterbank.c

    rc03d191 r088760e  
    139139      &(self->freqs), samplerate);
    140140  if (err > 0) {
    141     if (PyErr_Occurred() == NULL) {
    142       PyErr_SetString (PyExc_ValueError, "error running set_triangle_bands");
    143     } else {
    144       // change the RuntimeError into ValueError
    145       PyObject *type, *value, *traceback;
    146       PyErr_Fetch(&type, &value, &traceback);
    147       PyErr_Restore(PyExc_ValueError, value, traceback);
    148     }
     141    PyErr_SetString (PyExc_ValueError,
     142        "error when running set_triangle_bands");
    149143    return NULL;
    150144  }
     
    157151  uint_t err = 0;
    158152
    159   smpl_t samplerate;
    160   if (!PyArg_ParseTuple (args, AUBIO_NPY_SMPL_CHR, &samplerate)) {
     153  uint_t samplerate;
     154  if (!PyArg_ParseTuple (args, "I", &samplerate)) {
    161155    return NULL;
    162156  }
     
    164158  err = aubio_filterbank_set_mel_coeffs_slaney (self->o, samplerate);
    165159  if (err > 0) {
    166     if (PyErr_Occurred() == NULL) {
    167       PyErr_SetString (PyExc_ValueError, "error running set_mel_coeffs_slaney");
    168     } else {
    169       // change the RuntimeError into ValueError
    170       PyObject *type, *value, *traceback;
    171       PyErr_Fetch(&type, &value, &traceback);
    172       PyErr_Restore(PyExc_ValueError, value, traceback);
    173     }
    174     return NULL;
    175   }
    176   Py_RETURN_NONE;
    177 }
    178 
    179 static PyObject *
    180 Py_filterbank_set_mel_coeffs (Py_filterbank * self, PyObject *args)
    181 {
    182   uint_t err = 0;
    183 
    184   smpl_t samplerate;
    185   smpl_t freq_min;
    186   smpl_t freq_max;
    187   if (!PyArg_ParseTuple (args, AUBIO_NPY_SMPL_CHR AUBIO_NPY_SMPL_CHR
    188         AUBIO_NPY_SMPL_CHR, &samplerate, &freq_min, &freq_max)) {
    189     return NULL;
    190   }
    191 
    192   err = aubio_filterbank_set_mel_coeffs (self->o, samplerate,
    193       freq_min, freq_max);
    194   if (err > 0) {
    195     if (PyErr_Occurred() == NULL) {
    196       PyErr_SetString (PyExc_ValueError, "error running set_mel_coeffs");
    197     } else {
    198       // change the RuntimeError into ValueError
    199       PyObject *type, *value, *traceback;
    200       PyErr_Fetch(&type, &value, &traceback);
    201       PyErr_Restore(PyExc_ValueError, value, traceback);
    202     }
    203     return NULL;
    204   }
    205   Py_RETURN_NONE;
    206 }
    207 
    208 static PyObject *
    209 Py_filterbank_set_mel_coeffs_htk (Py_filterbank * self, PyObject *args)
    210 {
    211   uint_t err = 0;
    212 
    213   smpl_t samplerate;
    214   smpl_t freq_min;
    215   smpl_t freq_max;
    216   if (!PyArg_ParseTuple (args, AUBIO_NPY_SMPL_CHR AUBIO_NPY_SMPL_CHR
    217         AUBIO_NPY_SMPL_CHR, &samplerate, &freq_min, &freq_max)) {
    218     return NULL;
    219   }
    220 
    221   err = aubio_filterbank_set_mel_coeffs_htk (self->o, samplerate,
    222       freq_min, freq_max);
    223   if (err > 0) {
    224     if (PyErr_Occurred() == NULL) {
    225       PyErr_SetString (PyExc_ValueError, "error running set_mel_coeffs_htk");
    226     } else {
    227       // change the RuntimeError into ValueError
    228       PyObject *type, *value, *traceback;
    229       PyErr_Fetch(&type, &value, &traceback);
    230       PyErr_Restore(PyExc_ValueError, value, traceback);
    231     }
     160    PyErr_SetString (PyExc_ValueError,
     161        "error when running set_mel_coeffs_slaney");
    232162    return NULL;
    233163  }
     
    264194  return (PyObject *)PyAubio_CFmatToArray(
    265195      aubio_filterbank_get_coeffs (self->o) );
    266 }
    267 
    268 static PyObject *
    269 Py_filterbank_set_power(Py_filterbank *self, PyObject *args)
    270 {
    271   uint_t power;
    272 
    273   if (!PyArg_ParseTuple (args, "I", &power)) {
    274     return NULL;
    275   }
    276   if(aubio_filterbank_set_power (self->o, power)) {
    277     if (PyErr_Occurred() == NULL) {
    278       PyErr_SetString (PyExc_ValueError,
    279           "error running filterbank.set_power");
    280     } else {
    281       // change the RuntimeError into ValueError
    282       PyObject *type, *value, *traceback;
    283       PyErr_Fetch(&type, &value, &traceback);
    284       PyErr_Restore(PyExc_ValueError, value, traceback);
    285     }
    286     return NULL;
    287   }
    288   Py_RETURN_NONE;
    289 }
    290 
    291 static PyObject *
    292 Py_filterbank_set_norm(Py_filterbank *self, PyObject *args)
    293 {
    294   uint_t playing;
    295 
    296   if (!PyArg_ParseTuple (args, "I", &playing)) {
    297     return NULL;
    298   }
    299   if(aubio_filterbank_set_norm (self->o, playing)) {
    300     if (PyErr_Occurred() == NULL) {
    301       PyErr_SetString (PyExc_ValueError,
    302           "error running filterbank.set_power");
    303     } else {
    304       // change the RuntimeError into ValueError
    305       PyObject *type, *value, *traceback;
    306       PyErr_Fetch(&type, &value, &traceback);
    307       PyErr_Restore(PyExc_ValueError, value, traceback);
    308     }
    309     return NULL;
    310   }
    311   Py_RETURN_NONE;
    312196}
    313197
     
    317201  {"set_mel_coeffs_slaney", (PyCFunction) Py_filterbank_set_mel_coeffs_slaney,
    318202    METH_VARARGS, "set coefficients of filterbank as in Auditory Toolbox"},
    319   {"set_mel_coeffs", (PyCFunction) Py_filterbank_set_mel_coeffs,
    320     METH_VARARGS, "set coefficients of filterbank to linearly spaced mel scale"},
    321   {"set_mel_coeffs_htk", (PyCFunction) Py_filterbank_set_mel_coeffs_htk,
    322     METH_VARARGS, "set coefficients of filterbank to linearly spaced mel scale"},
    323203  {"get_coeffs", (PyCFunction) Py_filterbank_get_coeffs,
    324204    METH_NOARGS, "get coefficients of filterbank"},
    325205  {"set_coeffs", (PyCFunction) Py_filterbank_set_coeffs,
    326206    METH_VARARGS, "set coefficients of filterbank"},
    327   {"set_power", (PyCFunction) Py_filterbank_set_power,
    328     METH_VARARGS, "set power applied to filterbank input spectrum"},
    329   {"set_norm", (PyCFunction) Py_filterbank_set_norm,
    330     METH_VARARGS, "set norm applied to filterbank input spectrum"},
    331207  {NULL}
    332208};
  • python/ext/py-musicutils.c

    rc03d191 r088760e  
    182182  return (PyObject *) PyAubio_CFvecToArray(&vec);
    183183}
    184 
    185 PyObject*
    186 Py_aubio_hztomel(PyObject *self, PyObject *args, PyObject *kwds)
    187 {
    188   smpl_t v;
    189   PyObject *htk = NULL;
    190   static char *kwlist[] = {"f", "htk", NULL};
    191   if (!PyArg_ParseTupleAndKeywords(args, kwds, AUBIO_NPY_SMPL_CHR "|O",
    192         kwlist, &v, &htk))
    193   {
    194     return NULL;
    195   }
    196   if (htk != NULL && PyObject_IsTrue(htk) == 1)
    197     return Py_BuildValue(AUBIO_NPY_SMPL_CHR, aubio_hztomel_htk(v));
    198   else
    199     return Py_BuildValue(AUBIO_NPY_SMPL_CHR, aubio_hztomel(v));
    200 }
    201 
    202 PyObject*
    203 Py_aubio_meltohz(PyObject *self, PyObject *args, PyObject *kwds)
    204 {
    205   smpl_t v;
    206   PyObject *htk = NULL;
    207   static char *kwlist[] = {"m", "htk", NULL};
    208   if (!PyArg_ParseTupleAndKeywords(args, kwds, AUBIO_NPY_SMPL_CHR "|O",
    209         kwlist, &v, &htk))
    210   {
    211     return NULL;
    212   }
    213   if (htk != NULL && PyObject_IsTrue(htk) == 1)
    214     return Py_BuildValue(AUBIO_NPY_SMPL_CHR, aubio_meltohz_htk(v));
    215   else
    216     return Py_BuildValue(AUBIO_NPY_SMPL_CHR, aubio_meltohz(v));
    217 }
    218 
    219 PyObject*
    220 Py_aubio_hztomel_htk(PyObject *self, PyObject *args)
    221 {
    222   smpl_t v;
    223   if (!PyArg_ParseTuple(args, AUBIO_NPY_SMPL_CHR, &v)) {
    224     return NULL;
    225   }
    226   return Py_BuildValue(AUBIO_NPY_SMPL_CHR, aubio_hztomel_htk(v));
    227 }
    228 
    229 PyObject*
    230 Py_aubio_meltohz_htk(PyObject *self, PyObject *args)
    231 {
    232   smpl_t v;
    233   if (!PyArg_ParseTuple(args, AUBIO_NPY_SMPL_CHR, &v)) {
    234     return NULL;
    235   }
    236   return Py_BuildValue(AUBIO_NPY_SMPL_CHR, aubio_meltohz_htk(v));
    237 }
  • python/ext/py-musicutils.h

    rc03d191 r088760e  
    301301PyObject * Py_aubio_ishift(PyObject *self, PyObject *args);
    302302
    303 static char Py_aubio_hztomel_doc[] = ""
    304 "hztomel(f, htk=False)\n"
    305 "\n"
    306 "Convert a scalar from frequency to mel scale.\n"
    307 "\n"
    308 "Parameters\n"
    309 "----------\n"
    310 "m : float\n"
    311 "   input frequency, in Hz\n"
    312 "htk : bool\n"
    313 "   if `True`, use Htk mel scale instead of Slaney.\n"
    314 "\n"
    315 "Returns\n"
    316 "-------\n"
    317 "float\n"
    318 "   output mel\n"
    319 "\n"
    320 "See Also\n"
    321 "--------\n"
    322 "meltohz\n"
    323 "";
    324 PyObject * Py_aubio_hztomel(PyObject *self, PyObject *args);
    325 
    326 static char Py_aubio_meltohz_doc[] = ""
    327 "meltohz(m, htk=False)\n"
    328 "\n"
    329 "Convert a scalar from mel scale to frequency.\n"
    330 "\n"
    331 "Parameters\n"
    332 "----------\n"
    333 "m : float\n"
    334 "   input mel\n"
    335 "htk : bool\n"
    336 "   if `True`, use Htk mel scale instead of Slaney.\n"
    337 "\n"
    338 "Returns\n"
    339 "-------\n"
    340 "float\n"
    341 "   output frequency, in Hz\n"
    342 "\n"
    343 "See Also\n"
    344 "--------\n"
    345 "hztomel\n"
    346 "";
    347 PyObject * Py_aubio_meltohz(PyObject *self, PyObject *args);
    348 
    349 static char Py_aubio_hztomel_htk_doc[] = ""
    350 "hztomel_htk(m)\n"
    351 "\n"
    352 "Same as `hztomel(m, htk=True)`\n"
    353 "\n"
    354 "See Also\n"
    355 "--------\n"
    356 "hztomel\n"
    357 "";
    358 PyObject * Py_aubio_hztomel_htk(PyObject *self, PyObject *args);
    359 
    360 static char Py_aubio_meltohz_htk_doc[] = ""
    361 "meltohz_htk(m)\n"
    362 "\n"
    363 "Same as `meltohz(m, htk=True)`\n"
    364 "\n"
    365 "See Also\n"
    366 "--------\n"
    367 "meltohz\n"
    368 "";
    369 PyObject * Py_aubio_meltohz_htk(PyObject *self, PyObject *args);
    370 
    371303#endif /* PY_AUBIO_MUSICUTILS_H */
  • python/ext/py-sink.c

    rc03d191 r088760e  
    1515"sink(path, samplerate=44100, channels=1)\n"
    1616"\n"
    17 "Write audio samples to file.\n"
     17"Open `path` to write a WAV file.\n"
    1818"\n"
    1919"Parameters\n"
  • python/ext/py-source.c

    rc03d191 r088760e  
    1919"source(path, samplerate=0, hop_size=512, channels=0)\n"
    2020"\n"
    21 "Read audio samples from a media file.\n"
     21"Create a new source, opening the given pathname for reading.\n"
    2222"\n"
    2323"`source` open the file specified in `path` and creates a callable\n"
     
    248248"Returns\n"
    249249"-------\n"
    250 "samples : numpy.ndarray\n"
     250"samples : numpy.ndarray, shape `(hop_size,)`, dtype aubio.float_type\n"
    251251"    `fvec` of size `hop_size` containing the new samples.\n"
    252252"read : int\n"
     
    284284"Returns\n"
    285285"-------\n"
    286 "samples : numpy.ndarray\n"
     286"samples : np.ndarray([hop_size, channels], dtype=aubio.float_type)\n"
    287287"    NumPy array of shape `(hop_size, channels)` containing the new\n"
    288288"    audio samples.\n"
  • python/lib/aubio/__init__.py

    rc03d191 r088760e  
    2929from .midiconv import *
    3030from .slicing import *
    31 
    3231
    3332class fvec(numpy.ndarray):
  • python/lib/aubio/cmd.py

    rc03d191 r088760e  
    1212import sys
    1313import argparse
    14 import warnings
    1514import aubio
    1615
     
    170169
    171170    def add_verbose_help(self):
    172         self.add_argument("-v", "--verbose",
     171        self.add_argument("-v","--verbose",
    173172                action="count", dest="verbose", default=1,
    174173                help="make lots of noise [default]")
    175         self.add_argument("-q", "--quiet",
     174        self.add_argument("-q","--quiet",
    176175                action="store_const", dest="verbose", const=0,
    177176                help="be quiet")
     
    182181
    183182    def add_buf_size(self, buf_size=512):
    184         self.add_argument("-B", "--bufsize",
     183        self.add_argument("-B","--bufsize",
    185184                action="store", dest="buf_size", default=buf_size,
    186185                metavar = "<size>", type=int,
     
    188187
    189188    def add_hop_size(self, hop_size=256):
    190         self.add_argument("-H", "--hopsize",
     189        self.add_argument("-H","--hopsize",
    191190                metavar = "<size>", type=int,
    192191                action="store", dest="hop_size", default=hop_size,
     
    194193
    195194    def add_method(self, method='default', helpstr='method'):
    196         self.add_argument("-m", "--method",
     195        self.add_argument("-m","--method",
    197196                metavar = "<method>", type=str,
    198197                action="store", dest="method", default=method,
     
    200199
    201200    def add_threshold(self, default=None):
    202         self.add_argument("-t", "--threshold",
     201        self.add_argument("-t","--threshold",
    203202                metavar = "<threshold>", type=float,
    204203                action="store", dest="threshold", default=default,
     
    241240
    242241    def add_slicer_options(self):
    243         self.add_argument("-o", "--output", type = str,
     242        self.add_argument("-o","--output", type = str,
    244243                metavar = "<outputdir>",
    245244                action="store", dest="output_directory", default=None,
    246                 help="specify path where slices of the original file should"
    247                 " be created")
     245                help="specify path where slices of the original file should be created")
    248246        self.add_argument("--cut-until-nsamples", type = int,
    249247                metavar = "<samples>",
    250248                action = "store", dest = "cut_until_nsamples", default = None,
    251                 help="how many extra samples should be added at the end of"
    252                 " each slice")
     249                help="how many extra samples should be added at the end of each slice")
    253250        self.add_argument("--cut-every-nslices", type = int,
    254251                metavar = "<samples>",
     
    258255                metavar = "<slices>",
    259256                action = "store", dest = "cut_until_nslices", default = None,
    260                 help="how many extra slices should be added at the end of"
    261                 " each slice")
     257                help="how many extra slices should be added at the end of each slice")
    262258        self.add_argument("--create-first",
    263259                action = "store_true", dest = "create_first", default = False,
     
    293289        if args.verbose > 2 and hasattr(self, 'options'):
    294290            name = type(self).__name__.split('_')[1]
    295             optstr = ' '.join(['running', name, 'with options',
    296                 repr(self.options), '\n'])
     291            optstr = ' '.join(['running', name, 'with options', repr(self.options), '\n'])
    297292            sys.stderr.write(optstr)
    298293    def flush(self, frames_read, samplerate):
     
    302297    def parse_options(self, args, valid_opts):
    303298        # get any valid options found in a dictionnary of arguments
    304         options = {k: v for k, v in vars(args).items() if k in valid_opts}
     299        options = {k :v for k,v in vars(args).items() if k in valid_opts}
    305300        self.options = options
    306301
     
    383378            outstr = "unknown bpm"
    384379        else:
    385             bpms = 60. / np.diff(self.beat_locations)
     380            bpms = 60./ np.diff(self.beat_locations)
    386381            median_bpm = np.mean(bpms)
    387382            if len(self.beat_locations) < 10:
     
    404399        return self.notes(block)
    405400    def repr_res(self, res, frames_read, samplerate):
    406         if res[2] != 0:  # note off
     401        if res[2] != 0: # note off
    407402            fmt_out = self.time2string(frames_read, samplerate)
    408403            sys.stdout.write(fmt_out + '\n')
    409         if res[0] != 0:  # note on
     404        if res[0] != 0: # note on
    410405            lastmidi = res[0]
    411406            fmt_out = "%f\t" % lastmidi
    412407            fmt_out += self.time2string(frames_read, samplerate)
    413             sys.stdout.write(fmt_out)  # + '\t')
     408            sys.stdout.write(fmt_out) # + '\t')
    414409    def flush(self, frames_read, samplerate):
    415410        eof = self.time2string(frames_read, samplerate)
     
    478473            if self.wassilence != 1:
    479474                self.wassilence = 1
    480                 return 2   # newly found silence
    481             return 1       # silence again
     475                return 2 # newly found silence
     476            return 1 # silence again
    482477        else:
    483478            if self.wassilence != 0:
    484479                self.wassilence = 0
    485                 return -1  # newly found noise
    486             return 0       # noise again
     480                return -1 # newly found noise
     481            return 0 # noise again
    487482
    488483    def repr_res(self, res, frames_read, samplerate):
     
    504499    def __call__(self, block):
    505500        ret = super(process_cut, self).__call__(block)
    506         if ret:
    507             self.slices.append(self.onset.get_last())
     501        if ret: self.slices.append(self.onset.get_last())
    508502        return ret
    509503
    510504    def flush(self, frames_read, samplerate):
     505        from aubio.cut import _cut_slice
    511506        _cut_slice(self.options, self.slices)
    512         duration = float(frames_read) / float(samplerate)
    513         base_info = '%(source_file)s' % \
    514                     {'source_file': self.options.source_uri}
     507        duration = float (frames_read) / float(samplerate)
     508        base_info = '%(source_file)s' % {'source_file': self.options.source_uri}
    515509        base_info += ' (total %(duration).2fs at %(samplerate)dHz)\n' % \
    516                      {'duration': duration, 'samplerate': samplerate}
     510                {'duration': duration, 'samplerate': samplerate}
    517511        info = "created %d slices from " % len(self.slices)
    518512        info += base_info
    519513        sys.stderr.write(info)
    520 
    521 def _cut_slice(options, timestamps):
    522     # cutting pass
    523     nstamps = len(timestamps)
    524     if nstamps > 0:
    525         # generate output files
    526         timestamps_end = None
    527         if options.cut_every_nslices:
    528             timestamps = timestamps[::options.cut_every_nslices]
    529             nstamps = len(timestamps)
    530         if options.cut_until_nslices and options.cut_until_nsamples:
    531             msg = "using cut_until_nslices, but cut_until_nsamples is set"
    532             warnings.warn(msg)
    533         if options.cut_until_nsamples:
    534             lag = options.cut_until_nsamples
    535             timestamps_end = [t + lag for t in timestamps[1:]]
    536             timestamps_end += [1e120]
    537         if options.cut_until_nslices:
    538             slice_lag = options.cut_until_nslices
    539             timestamps_end = [t for t in timestamps[1 + slice_lag:]]
    540             timestamps_end += [1e120] * (options.cut_until_nslices + 1)
    541         aubio.slice_source_at_stamps(options.source_uri,
    542                 timestamps, timestamps_end = timestamps_end,
    543                 output_dir = options.output_directory,
    544                 samplerate = options.samplerate,
    545                 create_first = options.create_first)
    546514
    547515def main():
     
    558526                action="store_true", dest="show_version")
    559527        args, extras = parser_root.parse_known_args()
    560         if not args.show_version: # no -V, forward to parser
     528        if args.show_version == False: # no -V, forward to parser
    561529            args = parser.parse_args(extras, namespace=args)
    562         elif len(extras) != 0:     # -V with other arguments, print help
     530        elif len(extras) != 0: # -V with other arguments, print help
    563531            parser.print_help()
    564532            sys.exit(1)
    565     else:  # in py3, we can simply use parser directly
     533    else: # in py3, we can simply use parser directly
    566534        args = parser.parse_args()
    567535    if 'show_version' in args and args.show_version:
     
    570538    elif 'verbose' in args and args.verbose > 3:
    571539        sys.stderr.write('aubio version ' + aubio.version + '\n')
    572     if 'command' not in args or args.command is None \
    573             or args.command in ['help']:
     540    if 'command' not in args or args.command is None or args.command in ['help']:
    574541        # no command given, print help and return 1
    575542        parser.print_help()
     
    605572                frames_read += read
    606573                # exit loop at end of file
    607                 if read < a_source.hop_size:
    608                     break
     574                if read < a_source.hop_size: break
    609575            # flush the processor if needed
    610576            processor.flush(frames_read, a_source.samplerate)
     
    614580                fmt_string += " from {:s} at {:d}Hz\n"
    615581                sys.stderr.write(fmt_string.format(
    616                         frames_read / float(a_source.samplerate),
     582                        frames_read/float(a_source.samplerate),
    617583                        frames_read,
    618584                        frames_read // a_source.hop_size + 1,
  • python/lib/aubio/cut.py

    rc03d191 r088760e  
    66
    77import sys
    8 from aubio.cmd import AubioArgumentParser, _cut_slice
     8from aubio.cmd import AubioArgumentParser
    99
    1010def aubio_cut_parser():
    1111    parser = AubioArgumentParser()
    1212    parser.add_input()
    13     parser.add_argument("-O", "--onset-method",
     13    parser.add_argument("-O","--onset-method",
    1414            action="store", dest="onset_method", default='default',
    1515            metavar = "<onset_method>",
     
    1717                    complexdomain|hfc|phase|specdiff|energy|kl|mkl")
    1818    # cutting methods
    19     parser.add_argument("-b", "--beat",
     19    parser.add_argument("-b","--beat",
    2020            action="store_true", dest="beat", default=False,
    2121            help="slice at beat locations")
    2222    """
    23     parser.add_argument("-S", "--silencecut",
     23    parser.add_argument("-S","--silencecut",
    2424            action="store_true", dest="silencecut", default=False,
    2525            help="use silence locations")
    26     parser.add_argument("-s", "--silence",
     26    parser.add_argument("-s","--silence",
    2727            metavar = "<value>",
    2828            action="store", dest="silence", default=-70,
     
    3131    # algorithm parameters
    3232    parser.add_buf_hop_size()
    33     parser.add_argument("-t", "--threshold", "--onset-threshold",
     33    parser.add_argument("-t","--threshold", "--onset-threshold",
    3434            metavar = "<threshold>", type=float,
    3535            action="store", dest="threshold", default=0.3,
    3636            help="onset peak picking threshold [default=0.3]")
    37     parser.add_argument("-c", "--cut",
     37    parser.add_argument("-c","--cut",
    3838            action="store_true", dest="cut", default=False,
    3939            help="cut input sound file at detected labels")
     
    4141
    4242    """
    43     parser.add_argument("-D", "--delay",
     43    parser.add_argument("-D","--delay",
    4444            action = "store", dest = "delay", type = float,
    4545            metavar = "<seconds>", default=0,
    4646            help="number of seconds to take back [default=system]\
    4747                    default system delay is 3*hopsize/samplerate")
    48     parser.add_argument("-C", "--dcthreshold",
     48    parser.add_argument("-C","--dcthreshold",
    4949            metavar = "<value>",
    5050            action="store", dest="dcthreshold", default=1.,
    5151            help="onset peak picking DC component [default=1.]")
    52     parser.add_argument("-L", "--localmin",
     52    parser.add_argument("-L","--localmin",
    5353            action="store_true", dest="localmin", default=False,
    5454            help="use local minima after peak detection")
    55     parser.add_argument("-d", "--derivate",
     55    parser.add_argument("-d","--derivate",
    5656            action="store_true", dest="derivate", default=False,
    5757            help="derivate onset detection function")
    58     parser.add_argument("-z", "--zerocross",
     58    parser.add_argument("-z","--zerocross",
    5959            metavar = "<value>",
    6060            action="store", dest="zerothres", default=0.008,
    6161            help="zero-crossing threshold for slicing [default=0.00008]")
    6262    # plotting functions
    63     parser.add_argument("-p", "--plot",
     63    parser.add_argument("-p","--plot",
    6464            action="store_true", dest="plot", default=False,
    6565            help="draw plot")
    66     parser.add_argument("-x", "--xsize",
     66    parser.add_argument("-x","--xsize",
    6767            metavar = "<size>",
    6868            action="store", dest="xsize", default=1.,
    6969            type=float, help="define xsize for plot")
    70     parser.add_argument("-y", "--ysize",
     70    parser.add_argument("-y","--ysize",
    7171            metavar = "<size>",
    7272            action="store", dest="ysize", default=1.,
    7373            type=float, help="define ysize for plot")
    74     parser.add_argument("-f", "--function",
     74    parser.add_argument("-f","--function",
    7575            action="store_true", dest="func", default=False,
    7676            help="print detection function")
    77     parser.add_argument("-n", "--no-onsets",
     77    parser.add_argument("-n","--no-onsets",
    7878            action="store_true", dest="nplot", default=False,
    7979            help="do not plot detected onsets")
    80     parser.add_argument("-O", "--outplot",
     80    parser.add_argument("-O","--outplot",
    8181            metavar = "<output_image>",
    8282            action="store", dest="outplot", default=None,
    8383            help="save plot to output.{ps,png}")
    84     parser.add_argument("-F", "--spectrogram",
     84    parser.add_argument("-F","--spectrogram",
    8585            action="store_true", dest="spectro", default=False,
    8686            help="add spectrogram to the plot")
     
    106106
    107107    if options.beat:
    108         o = tempo(options.onset_method, bufsize, hopsize,
    109                 samplerate=samplerate)
     108        o = tempo(options.onset_method, bufsize, hopsize, samplerate=samplerate)
    110109    else:
    111         o = onset(options.onset_method, bufsize, hopsize,
    112                 samplerate=samplerate)
     110        o = onset(options.onset_method, bufsize, hopsize, samplerate=samplerate)
    113111        if options.minioi:
    114112            if options.minioi.endswith('ms'):
     
    125123        samples, read = s()
    126124        if o(samples):
    127             timestamps.append(o.get_last())
    128             if options.verbose:
    129                 print("%.4f" % o.get_last_s())
     125            timestamps.append (o.get_last())
     126            if options.verbose: print ("%.4f" % o.get_last_s())
    130127        total_frames += read
    131         if read < hopsize:
    132             break
     128        if read < hopsize: break
    133129    del s
    134130    return timestamps, total_frames
     131
     132def _cut_slice(options, timestamps):
     133    # cutting pass
     134    nstamps = len(timestamps)
     135    if nstamps > 0:
     136        # generate output files
     137        from aubio.slicing import slice_source_at_stamps
     138        timestamps_end = None
     139        if options.cut_every_nslices:
     140            timestamps = timestamps[::options.cut_every_nslices]
     141            nstamps = len(timestamps)
     142        if options.cut_until_nslices and options.cut_until_nsamples:
     143            print ("warning: using cut_until_nslices, but cut_until_nsamples is set")
     144        if options.cut_until_nsamples:
     145            timestamps_end = [t + options.cut_until_nsamples for t in timestamps[1:]]
     146            timestamps_end += [ 1e120 ]
     147        if options.cut_until_nslices:
     148            timestamps_end = [t for t in timestamps[1 + options.cut_until_nslices:]]
     149            timestamps_end += [ 1e120 ] * (options.cut_until_nslices + 1)
     150        slice_source_at_stamps(options.source_uri,
     151                timestamps, timestamps_end = timestamps_end,
     152                output_dir = options.output_directory,
     153                samplerate = options.samplerate,
     154                create_first = options.create_first)
    135155
    136156def main():
     
    148168
    149169    # print some info
    150     duration = float(total_frames) / float(options.samplerate)
     170    duration = float (total_frames) / float(options.samplerate)
    151171    base_info = '%(source_uri)s' % {'source_uri': options.source_uri}
    152172    base_info += ' (total %(duration).2fs at %(samplerate)dHz)\n' % \
  • python/lib/aubio/midiconv.py

    rc03d191 r088760e  
    22""" utilities to convert midi note number to and from note names """
    33
     4__all__ = ['note2midi', 'midi2note', 'freq2note', 'note2freq']
     5
    46import sys
    57from ._aubio import freqtomidi, miditofreq
    6 
    7 __all__ = ['note2midi', 'midi2note', 'freq2note', 'note2freq']
    88
    99py3 = sys.version_info[0] == 3
     
    1414    str_instances = (str, unicode)
    1515    int_instances = (int, long)
    16 
    1716
    1817def note2midi(note):
     
    5756    midi2note, freqtomidi, miditofreq
    5857    """
    59     _valid_notenames = {'C': 0, 'D': 2, 'E': 4, 'F': 5, 'G': 7,
    60                         'A': 9, 'B': 11}
     58    _valid_notenames = {'C': 0, 'D': 2, 'E': 4, 'F': 5, 'G': 7, 'A': 9, 'B': 11}
    6159    _valid_modifiers = {
    62             u'𝄫': -2,                         # double flat
    63             u'♭': -1, 'b': -1, '\u266d': -1,  # simple flat
    64             u'♮': 0, '\u266e': 0, None: 0,    # natural
    65             '#': +1, u'♯': +1, '\u266f': +1,  # sharp
    66             u'𝄪': +2,                         # double sharp
     60            u'𝄫': -2,                        # double flat
     61            u'♭': -1, 'b': -1, '\u266d': -1, # simple flat
     62            u'♮': 0, '\u266e': 0, None: 0,   # natural
     63            '#': +1, u'♯': +1, '\u266f': +1, # sharp
     64            u'𝄪': +2,                        # double sharp
    6765            }
    6866    _valid_octaves = range(-1, 10)
     
    7371        msg = "string of 2 to 4 characters expected, got {:d} ({:s})"
    7472        raise ValueError(msg.format(len(note), note))
    75     notename, modifier, octave = [None] * 3
     73    notename, modifier, octave = [None]*3
    7674
    7775    if len(note) == 4:
     
    9694        raise ValueError("%s is not a valid octave" % octave)
    9795
    98     midi = (octave + 1) * 12 + _valid_notenames[notename] \
    99                              + _valid_modifiers[modifier]
     96    midi = 12 + octave * 12 + _valid_notenames[notename] \
     97            + _valid_modifiers[modifier]
    10098    if midi > 127:
    10199        raise ValueError("%s is outside of the range C-2 to G8" % note)
    102100    return midi
    103 
    104101
    105102def midi2note(midi):
     
    140137        raise ValueError(msg.format(midi))
    141138    _valid_notenames = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#',
    142                         'A', 'A#', 'B']
     139            'A', 'A#', 'B']
    143140    return _valid_notenames[midi % 12] + str(int(midi / 12) - 1)
    144 
    145141
    146142def freq2note(freq):
     
    167163    return midi2note(nearest_note)
    168164
    169 
    170165def note2freq(note):
    171166    """Convert note name to corresponding frequency, in Hz.
  • python/lib/aubio/slicing.py

    rc03d191 r088760e  
    55
    66_max_timestamp = 1e120
    7 
    87
    98def slice_source_at_stamps(source_file, timestamps, timestamps_end=None,
     
    7473    """
    7574
    76     if not timestamps:
     75    if timestamps is None or len(timestamps) == 0:
    7776        raise ValueError("no timestamps given")
    7877
     
    9190
    9291    regions = list(zip(timestamps, timestamps_end))
     92    #print regions
    9393
    9494    source_base_name, _ = os.path.splitext(os.path.basename(source_file))
     
    9898        source_base_name = os.path.join(output_dir, source_base_name)
    9999
    100     def _new_sink_name(source_base_name, timestamp, samplerate):
    101         # create name based on a timestamp in samples, converted in seconds
     100    def new_sink_name(source_base_name, timestamp, samplerate):
     101        """ create a sink based on a timestamp in samples, converted in seconds """
    102102        timestamp_seconds = timestamp / float(samplerate)
    103103        return source_base_name + "_%011.6f" % timestamp_seconds + '.wav'
     
    114114        vec, read = _source.do_multi()
    115115        # if the total number of frames read will exceed the next region start
    116         while regions and total_frames + read >= regions[0][0]:
     116        while len(regions) and total_frames + read >= regions[0][0]:
     117            #print "getting", regions[0], "at", total_frames
    117118            # get next region
    118119            start_stamp, end_stamp = regions.pop(0)
    119120            # create a name for the sink
    120             new_sink_path = _new_sink_name(source_base_name, start_stamp,
    121                                            samplerate)
     121            new_sink_path = new_sink_name(source_base_name, start_stamp, samplerate)
    122122            # create its sink
    123123            _sink = sink(new_sink_path, samplerate, _source.channels)
    124124            # create a dictionary containing all this
    125             new_slice = {'start_stamp': start_stamp, 'end_stamp': end_stamp,
    126                          'sink': _sink}
     125            new_slice = {'start_stamp': start_stamp, 'end_stamp': end_stamp, 'sink': _sink}
    127126            # append the dictionary to the current list of slices
    128127            slices.append(new_slice)
     
    136135            # number of samples yet to written be until end of region
    137136            remaining = end_stamp - total_frames + 1
     137            #print current_slice, remaining, start
    138138            # not enough frames remaining, time to split
    139139            if remaining < read:
     
    141141                    # write remaining samples from current region
    142142                    _sink.do_multi(vec[:, start:remaining], remaining - start)
     143                    #print("closing region", "remaining", remaining)
    143144                    # close this file
    144145                    _sink.close()
     
    149150        # remove old slices
    150151        slices = list(filter(lambda s: s['end_stamp'] > total_frames,
    151                              slices))
     152            slices))
    152153        if read < hopsize:
    153154            break
  • python/lib/gen_code.py

    rc03d191 r088760e  
    465465""".format(**self.__dict__)
    466466        for set_param in self.prototypes['set']:
    467             params = get_params_types_names(set_param)[1:]
    468             param = self.shortname.split('_set_')[-1]
    469             paramdecls = "".join(["""
    470    {0} {1};""".format(p['type'], p['name']) for p in params])
     467            params = get_params_types_names(set_param)[1]
     468            paramtype = params['type']
    471469            method_name = get_name(set_param)
    472470            param = method_name.split('aubio_'+self.shortname+'_set_')[-1]
    473             refs = ", ".join(["&%s" % p['name'] for p in params])
    474             paramlist = ", ".join(["%s" % p['name'] for p in params])
    475             if len(params):
    476                 paramlist = "," + paramlist
    477             pyparamtypes = ''.join([pyargparse_chars[p['type']] for p in params])
     471            pyparamtype = pyargparse_chars[paramtype]
    478472            out += """
    479473static PyObject *
     
    481475{{
    482476  uint_t err = 0;
    483   {paramdecls}
    484 """.format(param = param, paramdecls = paramdecls, **self.__dict__)
    485 
    486             if len(refs) and len(pyparamtypes):
    487                 out += """
    488 
    489   if (!PyArg_ParseTuple (args, "{pyparamtypes}", {refs})) {{
     477  {paramtype} {param};
     478
     479  if (!PyArg_ParseTuple (args, "{pyparamtype}", &{param})) {{
    490480    return NULL;
    491481  }}
    492 """.format(pyparamtypes = pyparamtypes, refs = refs)
    493 
    494             out += """
    495   err = aubio_{shortname}_set_{param} (self->o {paramlist});
     482  err = aubio_{shortname}_set_{param} (self->o, {param});
    496483
    497484  if (err > 0) {{
     
    508495  Py_RETURN_NONE;
    509496}}
    510 """.format(param = param, refs = refs, paramdecls = paramdecls,
    511         pyparamtypes = pyparamtypes, paramlist = paramlist, **self.__dict__)
     497""".format(param = param, paramtype = paramtype, pyparamtype = pyparamtype, **self.__dict__)
    512498        return out
    513499
  • python/lib/gen_external.py

    rc03d191 r088760e  
    44import subprocess
    55import glob
    6 from distutils.sysconfig import customize_compiler
    7 from gen_code import MappedObject
    86
    97header = os.path.join('src', 'aubio.h')
     
    5250def get_preprocessor():
    5351    # findout which compiler to use
     52    from distutils.sysconfig import customize_compiler
    5453    compiler_name = distutils.ccompiler.get_default_compiler()
    5554    compiler = distutils.ccompiler.new_compiler(compiler=compiler_name)
     
    264263
    265264    sources_list = []
     265    try:
     266        from .gen_code import MappedObject
     267    except (SystemError, ValueError):
     268        from gen_code import MappedObject
    266269    for o in lib:
    267270        out = source_header
  • python/lib/moresetuptools.py

    rc03d191 r088760e  
    33import sys, os, glob, subprocess
    44import distutils, distutils.command.clean, distutils.dir_util
    5 from gen_external import generate_external, header, output_path
     5from .gen_external import generate_external, header, output_path
    66
    77from this_version import get_aubio_version
  • python/tests/test_fft.py

    rc03d191 r088760e  
    143143        assert_almost_equal ( r[1:], 0)
    144144
    145 class aubio_fft_odd_sizes(TestCase):
    146 
    147     def test_reconstruct_with_odd_size(self):
    148         win_s = 29
    149         self.recontruct(win_s, 'odd sizes not supported')
    150 
    151     def test_reconstruct_with_radix15(self):
    152         win_s = 2 ** 4 * 15
    153         self.recontruct(win_s, 'radix 15 supported')
    154 
    155     def test_reconstruct_with_radix5(self):
    156         win_s = 2 ** 4 * 5
    157         self.recontruct(win_s, 'radix 5 supported')
    158 
    159     def test_reconstruct_with_radix3(self):
    160         win_s = 2 ** 4 * 3
    161         self.recontruct(win_s, 'radix 3 supported')
    162 
    163     def recontruct(self, win_s, skipMessage):
    164         try:
    165             f = fft(win_s)
    166         except RuntimeError:
    167             self.skipTest(skipMessage)
    168         input_signal = fvec(win_s)
    169         input_signal[win_s//2] = 1
    170         c = f(input_signal)
    171         output_signal = f.rdo(c)
    172         assert_almost_equal(input_signal, output_signal)
    173 
    174 class aubio_fft_wrong_params(TestCase):
    175 
    176145    def test_large_input_timegrain(self):
    177146        win_s = 1024
     
    202171            f.rdo(s)
    203172
     173class aubio_fft_wrong_params(TestCase):
     174
    204175    def test_wrong_buf_size(self):
    205176        win_s = -1
    206177        with self.assertRaises(ValueError):
    207178            fft(win_s)
     179
     180    def test_buf_size_not_power_of_two(self):
     181        # when compiled with fftw3, aubio supports non power of two fft sizes
     182        win_s = 320
     183        try:
     184            with self.assertRaises(RuntimeError):
     185                fft(win_s)
     186        except AssertionError:
     187            self.skipTest('creating aubio.fft with size %d did not fail' % win_s)
    208188
    209189    def test_buf_size_too_small(self):
  • python/tests/test_filter.py

    rc03d191 r088760e  
    7878            f.set_biquad(0., 0., 0, 0., 0.)
    7979
    80     def test_all_available_presets(self):
    81         f = digital_filter(7)
    82         for sr in [8000, 11025, 16000, 22050, 24000, 32000,
    83                 44100, 48000, 88200, 96000, 192000]:
    84             f.set_a_weighting(sr)
    85         f = digital_filter(5)
    86         for sr in [8000, 11025, 16000, 22050, 24000, 32000,
    87                 44100, 48000, 88200, 96000, 192000]:
    88             f.set_c_weighting(sr)
    89 
    9080class aubio_filter_wrong_params(TestCase):
    9181
  • python/tests/test_filterbank_mel.py

    rc03d191 r088760e  
    44from numpy.testing import TestCase, assert_equal, assert_almost_equal
    55
    6 from aubio import fvec, cvec, filterbank, float_type
     6from aubio import cvec, filterbank, float_type
    77
    88import warnings
     
    4848                    0.02133301, 0.02133301, 0.02133311, 0.02133334, 0.02133345])
    4949
    50     def test_triangle_freqs_with_zeros(self):
    51         """make sure set_triangle_bands works when list starts with 0"""
    52         freq_list = [0, 40, 80]
    53         freqs = np.array(freq_list, dtype = float_type)
    54         f = filterbank(len(freqs)-2, 1024)
    55         f.set_triangle_bands(freqs, 48000)
    56         assert_equal ( f(cvec(1024)), 0)
    57         self.assertIsInstance(f.get_coeffs(), np.ndarray)
    58 
    59     def test_triangle_freqs_with_wrong_negative(self):
    60         """make sure set_triangle_bands fails when list contains a negative"""
    61         freq_list = [-10, 0, 80]
    62         f = filterbank(len(freq_list)-2, 1024)
    63         with self.assertRaises(ValueError):
    64             f.set_triangle_bands(fvec(freq_list), 48000)
    65 
    66     def test_triangle_freqs_with_wrong_ordering(self):
    67         """make sure set_triangle_bands fails when list not ordered"""
    68         freq_list = [0, 80, 40]
    69         f = filterbank(len(freq_list)-2, 1024)
    70         with self.assertRaises(ValueError):
    71             f.set_triangle_bands(fvec(freq_list), 48000)
    72 
    73     def test_triangle_freqs_with_large_freq(self):
    74         """make sure set_triangle_bands warns when freq > nyquist"""
    75         samplerate = 22050
    76         freq_list = [0, samplerate//4, samplerate // 2 + 1]
    77         f = filterbank(len(freq_list)-2, 1024)
    78         # TODO add assert_warns
    79         f.set_triangle_bands(fvec(freq_list), samplerate)
    80 
    81     def test_triangle_freqs_with_not_enough_filters(self):
    82         """make sure set_triangle_bands warns when not enough filters"""
    83         samplerate = 22050
    84         freq_list = [0, 100, 1000, 4000, 8000, 10000]
    85         f = filterbank(len(freq_list)-3, 1024)
    86         # TODO add assert_warns
    87         f.set_triangle_bands(fvec(freq_list), samplerate)
    88 
    89     def test_triangle_freqs_with_too_many_filters(self):
    90         """make sure set_triangle_bands warns when too many filters"""
    91         samplerate = 22050
    92         freq_list = [0, 100, 1000, 4000, 8000, 10000]
    93         f = filterbank(len(freq_list)-1, 1024)
    94         # TODO add assert_warns
    95         f.set_triangle_bands(fvec(freq_list), samplerate)
    96 
    97     def test_triangle_freqs_with_double_value(self):
    98         """make sure set_triangle_bands works with 2 duplicate freqs"""
    99         samplerate = 22050
    100         freq_list = [0, 100, 1000, 4000, 4000, 4000, 10000]
    101         f = filterbank(len(freq_list)-2, 1024)
    102         # TODO add assert_warns
    103         f.set_triangle_bands(fvec(freq_list), samplerate)
    104 
    105     def test_triangle_freqs_with_triple(self):
    106         """make sure set_triangle_bands works with 3 duplicate freqs"""
    107         samplerate = 22050
    108         freq_list = [0, 100, 1000, 4000, 4000, 4000, 10000]
    109         f = filterbank(len(freq_list)-2, 1024)
    110         # TODO add assert_warns
    111         f.set_triangle_bands(fvec(freq_list), samplerate)
    112 
    113     def test_triangle_freqs_without_norm(self):
    114         """make sure set_triangle_bands works without """
    115         samplerate = 22050
    116         freq_list = fvec([0, 100, 1000, 10000])
    117         f = filterbank(len(freq_list) - 2, 1024)
    118         f.set_norm(0)
    119         f.set_triangle_bands(freq_list, samplerate)
    120         expected = f.get_coeffs()
    121         f.set_norm(1)
    122         f.set_triangle_bands(fvec(freq_list), samplerate)
    123         assert_almost_equal(f.get_coeffs().T,
    124                 expected.T * 2. / (freq_list[2:] - freq_list[:-2]))
    125 
    126     def test_triangle_freqs_wrong_norm(self):
    127         f = filterbank(10, 1024)
    128         with self.assertRaises(ValueError):
    129             f.set_norm(-1)
    130 
    131     def test_triangle_freqs_with_power(self):
    132         f = filterbank(9, 1024)
    133         freqs = fvec([40, 80, 200, 400, 800, 1600, 3200, 6400, 12800, 15000,
    134             24000])
    135         f.set_power(2)
    136         f.set_triangle_bands(freqs, 48000)
    137         spec = cvec(1024)
    138         spec.norm[:] = .1
    139         expected = fvec([0.02070313, 0.02138672, 0.02127604, 0.02135417,
    140             0.02133301, 0.02133301, 0.02133311, 0.02133334, 0.02133345])
    141         expected /= 100.
    142         assert_almost_equal(f(spec), expected)
    143 
    144     def test_mel_coeffs(self):
    145         f = filterbank(40, 1024)
    146         f.set_mel_coeffs(44100, 0, 44100 / 2)
    147 
    148     def test_zero_fmax(self):
    149         f = filterbank(40, 1024)
    150         f.set_mel_coeffs(44100, 0, 0)
    151 
    152     def test_wrong_mel_coeffs(self):
    153         f = filterbank(40, 1024)
    154         with self.assertRaises(ValueError):
    155             f.set_mel_coeffs_slaney(0)
    156         with self.assertRaises(ValueError):
    157             f.set_mel_coeffs(44100, 0, -44100 / 2)
    158         with self.assertRaises(ValueError):
    159             f.set_mel_coeffs(44100, -0.1, 44100 / 2)
    160         with self.assertRaises(ValueError):
    161             f.set_mel_coeffs(-44100, 0.1, 44100 / 2)
    162         with self.assertRaises(ValueError):
    163             f.set_mel_coeffs_htk(-1, 0, 0)
    164 
    165     def test_mel_coeffs_htk(self):
    166         f = filterbank(40, 1024)
    167         f.set_mel_coeffs_htk(44100, 0, 44100 / 2)
    168 
    169 
    17050if __name__ == '__main__':
    17151    import nose2
  • python/tests/test_mfcc.py

    rc03d191 r088760e  
    111111        #print coeffs
    112112
    113 
    114 class aubio_mfcc_fb_params(TestCase):
    115 
    116     def test_set_scale(self):
    117         buf_size, n_filters, n_coeffs, samplerate = 512, 20, 10, 16000
    118         m = mfcc(buf_size, n_filters, n_coeffs, samplerate)
    119         m.set_scale(10.)
    120         m(cvec(buf_size))
    121 
    122     def test_set_power(self):
    123         buf_size, n_filters, n_coeffs, samplerate = 512, 20, 10, 16000
    124         m = mfcc(buf_size, n_filters, n_coeffs, samplerate)
    125         m.set_power(2.)
    126         m(cvec(buf_size))
    127 
    128     def test_set_mel_coeffs(self):
    129         buf_size, n_filters, n_coeffs, samplerate = 512, 20, 10, 16000
    130         m = mfcc(buf_size, n_filters, n_coeffs, samplerate)
    131         m.set_mel_coeffs(0., samplerate/2.)
    132         m(cvec(buf_size))
    133 
    134     def test_set_mel_coeffs_htk(self):
    135         buf_size, n_filters, n_coeffs, samplerate = 512, 20, 10, 16000
    136         m = mfcc(buf_size, n_filters, n_coeffs, samplerate)
    137         m.set_mel_coeffs_htk(0., samplerate/2.)
    138         m(cvec(buf_size))
    139 
    140     def test_set_mel_coeffs_slaney(self):
    141         buf_size, n_filters, n_coeffs, samplerate = 512, 40, 10, 16000
    142         m = mfcc(buf_size, n_filters, n_coeffs, samplerate)
    143         m.set_mel_coeffs_slaney(samplerate)
    144         m(cvec(buf_size))
    145         assert m.get_power() == 1
    146         assert m.get_scale() == 1
    147 
    148113if __name__ == '__main__':
    149114    main()
  • python/tests/test_onset.py

    rc03d191 r088760e  
    33from unittest import main
    44from numpy.testing import TestCase, assert_equal, assert_almost_equal
    5 from aubio import onset, fvec
     5from aubio import onset
    66
    77class aubio_onset_default(TestCase):
     
    8484    samplerate = 8000
    8585
    86 class aubio_onset_coverate(TestCase):
    87     # extra tests to execute the C routines and improve coverage
    88 
    89     def test_all_methods(self):
    90         for method in ['default', 'energy', 'hfc', 'complexdomain', 'complex',
    91                 'phase', 'wphase', 'mkl', 'kl', 'specflux', 'specdiff',
    92                 'old_default']:
    93             o = onset(method=method, buf_size=512, hop_size=256)
    94             o(fvec(256))
    95 
    96     def test_get_methods(self):
    97         o = onset(method='default', buf_size=512, hop_size=256)
    98 
    99         assert o.get_silence() == -70
    100         o.set_silence(-20)
    101         assert_almost_equal(o.get_silence(), -20)
    102 
    103         assert o.get_compression() == 1
    104         o.set_compression(.99)
    105         assert_almost_equal(o.get_compression(), .99)
    106 
    107         assert o.get_awhitening() == 0
    108         o.set_awhitening(1)
    109         assert o.get_awhitening() == 1
    110 
    111         o.get_last()
    112         o.get_last_ms()
    113         o.get_last_s()
    114         o.get_descriptor()
    115         o.get_thresholded_descriptor()
    116 
    117 
    11886if __name__ == '__main__':
    11987    main()
  • setup.py

    rc03d191 r088760e  
    11#! /usr/bin/env python
    22
    3 import sys
    4 import os.path
    5 import glob
     3import sys, os.path, glob
    64from setuptools import setup, Extension
    7 
    8 # add ./python/lib to current path
    9 sys.path.append(os.path.join('python', 'lib'))  # noqa
    10 from moresetuptools import build_ext, CleanGenerated
    11 
     5from python.lib.moresetuptools import build_ext, CleanGenerated
    126# function to generate gen/*.{c,h}
    137from this_version import get_aubio_version, get_aubio_pyversion
     
    2115extra_link_args = []
    2216
    23 include_dirs += ['python/ext']
     17include_dirs += [ 'python/ext' ]
    2418try:
    2519    import numpy
    26     include_dirs += [numpy.get_include()]
     20    include_dirs += [ numpy.get_include() ]
    2721except ImportError:
    2822    pass
    2923
    3024if sys.platform.startswith('darwin'):
    31     extra_link_args += ['-framework', 'CoreFoundation',
    32             '-framework', 'AudioToolbox']
     25    extra_link_args += ['-framework','CoreFoundation', '-framework','AudioToolbox']
    3326
    3427sources = sorted(glob.glob(os.path.join('python', 'ext', '*.c')))
     
    4134    define_macros = define_macros)
    4235
    43 # TODO: find a way to track if package is built against libaubio
    44 # if os.path.isfile('src/aubio.h'):
    45 #     if not os.path.isdir(os.path.join('build','src')):
    46 #         pass
    47 #         #__version__ += 'a2' # python only version
     36if os.path.isfile('src/aubio.h'):
     37    if not os.path.isdir(os.path.join('build','src')):
     38        pass
     39        #__version__ += 'a2' # python only version
    4840
    4941classifiers = [
     
    5951    'Programming Language :: C',
    6052    'Programming Language :: Python',
    61     'License :: OSI Approved :: '
    62     'GNU General Public License v3 or later (GPLv3+)',
     53    'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',
    6354    ]
    6455
     
    6657    version = __version__,
    6758    packages = ['aubio'],
    68     package_dir = {'aubio': 'python/lib/aubio'},
     59    package_dir = {'aubio':'python/lib/aubio'},
    6960    ext_modules = [aubio_extension],
    7061    description = 'a collection of tools for music analysis',
  • src/io/source_avcodec.c

    rc03d191 r088760e  
    9090  sint_t selected_stream;
    9191  uint_t eof;
     92  uint_t multi;
    9293};
    9394
    9495// create or re-create the context when _do or _do_multi is called
    95 void aubio_source_avcodec_reset_resampler(aubio_source_avcodec_t * s);
     96void aubio_source_avcodec_reset_resampler(aubio_source_avcodec_t * s,
     97    uint_t multi);
    9698// actually read a frame
    9799void aubio_source_avcodec_readframe(aubio_source_avcodec_t *s,
     
    283285  s->avFrame = avFrame;
    284286
    285   aubio_source_avcodec_reset_resampler(s);
     287  // default to mono output
     288  aubio_source_avcodec_reset_resampler(s, 0);
    286289
    287290  if (s->avr == NULL) goto beach;
    288291
    289292  s->eof = 0;
     293  s->multi = 0;
    290294
    291295  //av_log_set_level(AV_LOG_QUIET);
     
    300304}
    301305
    302 void aubio_source_avcodec_reset_resampler(aubio_source_avcodec_t * s)
     306void aubio_source_avcodec_reset_resampler(aubio_source_avcodec_t * s,
     307    uint_t multi)
    303308{
    304309  // create or reset resampler to/from mono/multi-channel
    305   if ( s->avr == NULL ) {
     310  if ( (multi != s->multi) || (s->avr == NULL) ) {
    306311    int err;
    307312    int64_t input_layout = av_get_default_channel_layout(s->input_channels);
    308     int64_t output_layout = av_get_default_channel_layout(s->input_channels);
     313    uint_t output_channels = multi ? s->input_channels : 1;
     314    int64_t output_layout = av_get_default_channel_layout(output_channels);
    309315#ifdef HAVE_AVRESAMPLE
    310316    AVAudioResampleContext *avr = avresample_alloc_context();
     317    AVAudioResampleContext *oldavr = s->avr;
    311318#elif defined(HAVE_SWRESAMPLE)
    312319    SwrContext *avr = swr_alloc();
     320    SwrContext *oldavr = s->avr;
    313321#endif /* HAVE_AVRESAMPLE || HAVE_SWRESAMPLE */
    314322
     
    338346    }
    339347    s->avr = avr;
     348    if (oldavr != NULL) {
     349#ifdef HAVE_AVRESAMPLE
     350      avresample_close( oldavr );
     351#elif defined(HAVE_SWRESAMPLE)
     352      swr_close ( oldavr );
     353#endif /* HAVE_AVRESAMPLE || HAVE_SWRESAMPLE */
     354      av_free ( oldavr );
     355      oldavr = NULL;
     356    }
     357    s->multi = multi;
    340358  }
    341359}
     
    478496void aubio_source_avcodec_do(aubio_source_avcodec_t * s, fvec_t * read_data,
    479497    uint_t * read) {
    480   uint_t i, j;
     498  uint_t i;
    481499  uint_t end = 0;
    482500  uint_t total_wrote = 0;
     501  // switch from multi
     502  if (s->multi == 1) aubio_source_avcodec_reset_resampler(s, 0);
    483503  while (total_wrote < s->hop_size) {
    484504    end = MIN(s->read_samples - s->read_index, s->hop_size - total_wrote);
    485505    for (i = 0; i < end; i++) {
    486       read_data->data[i + total_wrote] = 0.;
    487       for (j = 0; j < s->input_channels; j++) {
    488         read_data->data[i + total_wrote] +=
    489           s->output[(i + s->read_index) * s->input_channels + j];
    490       }
    491       read_data->data[i + total_wrote] *= 1./s->input_channels;
     506      read_data->data[i + total_wrote] = s->output[i + s->read_index];
    492507    }
    493508    total_wrote += end;
     
    517532  uint_t end = 0;
    518533  uint_t total_wrote = 0;
     534  // switch from mono
     535  if (s->multi == 0) aubio_source_avcodec_reset_resampler(s, 1);
    519536  while (total_wrote < s->hop_size) {
    520537    end = MIN(s->read_samples - s->read_index, s->hop_size - total_wrote);
  • src/mathutils.c

    rc03d191 r088760e  
    388388}
    389389
    390 void
    391 fvec_mul (fvec_t *o, smpl_t val)
    392 {
    393   uint_t j;
    394   for (j = 0; j < o->length; j++) {
    395     o->data[j] *= val;
    396   }
    397 }
    398 
    399390void fvec_adapt_thres(fvec_t * vec, fvec_t * tmp,
    400391    uint_t post, uint_t pre) {
  • src/mathutils.h

    rc03d191 r088760e  
    193193*/
    194194void fvec_add (fvec_t * v, smpl_t c);
    195 
    196 /** multiply each elements of a vector by a scalar
    197 
    198   \param v vector to add constant to
    199   \param s constant to scale v with
    200 
    201 */
    202 void fvec_mul (fvec_t * v, smpl_t s);
    203195
    204196/** remove the minimum value of the vector to each elements
  • src/musicutils.h

    rc03d191 r088760e  
    8787smpl_t aubio_freqtobin (smpl_t freq, smpl_t samplerate, smpl_t fftsize);
    8888
    89 /** convert frequency (Hz) to mel
    90 
    91   \param freq input frequency, in Hz
    92 
    93   \return output mel
    94 
    95   Converts a scalar from the frequency domain to the mel scale using Slaney
    96   Auditory Toolbox's implementation:
    97 
    98   If \f$ f < 1000 \f$, \f$ m = 3 f / 200 \f$.
    99 
    100   If \f$ f >= 1000 \f$, \f$ m = 1000 + 27 \frac{{ln}(f) - ln(1000))}
    101   {{ln}(6400) - ln(1000)}
    102   \f$
    103 
    104   See also
    105   --------
    106 
    107   aubio_meltohz(), aubio_hztomel_htk().
    108 
    109 */
    110 smpl_t aubio_hztomel (smpl_t freq);
    111 
    112 /** convert mel to frequency (Hz)
    113 
    114   \param mel input mel
    115 
    116   \return output frequency, in Hz
    117 
    118   Converts a scalar from the mel scale to the frequency domain using Slaney
    119   Auditory Toolbox's implementation:
    120 
    121   If \f$ f < 1000 \f$, \f$ f = 200 m/3 \f$.
    122 
    123   If \f$ f \geq 1000 \f$, \f$ f = 1000 + \left(\frac{6400}{1000}\right)
    124   ^{\frac{m - 1000}{27}} \f$
    125 
    126   See also
    127   --------
    128 
    129   aubio_hztomel(), aubio_meltohz_htk().
    130 
    131   References
    132   ----------
    133 
    134   Malcolm Slaney, *Auditory Toolbox Version 2, Technical Report #1998-010*
    135   https://engineering.purdue.edu/~malcolm/interval/1998-010/
    136 
    137 */
    138 smpl_t aubio_meltohz (smpl_t mel);
    139 
    140 /** convert frequency (Hz) to mel
    141 
    142   \param freq input frequency, in Hz
    143 
    144   \return output mel
    145 
    146   Converts a scalar from the frequency domain to the mel scale, using the
    147   equation defined by O'Shaughnessy, as implemented in the HTK speech
    148   recognition toolkit:
    149 
    150   \f$ m = 1127 + ln(1 + \frac{f}{700}) \f$
    151 
    152   See also
    153   --------
    154 
    155   aubio_meltohz_htk(), aubio_hztomel().
    156 
    157   References
    158   ----------
    159 
    160   Douglas O'Shaughnessy (1987). *Speech communication: human and machine*.
    161   Addison-Wesley. p. 150. ISBN 978-0-201-16520-3.
    162 
    163   HTK Speech Recognition Toolkit: http://htk.eng.cam.ac.uk/
    164 
    165  */
    166 smpl_t aubio_hztomel_htk (smpl_t freq);
    167 
    168 /** convert mel to frequency (Hz)
    169 
    170   \param mel input mel
    171 
    172   \return output frequency, in Hz
    173 
    174   Converts a scalar from the mel scale to the frequency domain, using the
    175   equation defined by O'Shaughnessy, as implemented in the HTK speech
    176   recognition toolkit:
    177 
    178   \f$ f = 700 * {e}^\left(\frac{f}{1127} - 1\right) \f$
    179 
    180   See also
    181   --------
    182 
    183   aubio_hztomel_htk(), aubio_meltohz().
    184 
    185 */
    186 smpl_t aubio_meltohz_htk (smpl_t mel);
    187 
    18889/** convert frequency (Hz) to midi value (0-128) */
    18990smpl_t aubio_freqtomidi (smpl_t freq);
  • src/spectral/fft.c

    rc03d191 r088760e  
    9090#define aubio_vDSP_vsadd               vDSP_vsadd
    9191#define aubio_vDSP_vsmul               vDSP_vsmul
     92#define aubio_vDSP_create_fftsetup     vDSP_create_fftsetup
     93#define aubio_vDSP_destroy_fftsetup    vDSP_destroy_fftsetup
    9294#define aubio_DSPComplex               DSPComplex
    9395#define aubio_DSPSplitComplex          DSPSplitComplex
    94 #define aubio_vDSP_DFT_Setup           vDSP_DFT_Setup
    95 #define aubio_vDSP_DFT_zrop_CreateSetup vDSP_DFT_zrop_CreateSetup
    96 #define aubio_vDSP_DFT_Execute         vDSP_DFT_Execute
    97 #define aubio_vDSP_DFT_DestroySetup    vDSP_DFT_DestroySetup
     96#define aubio_FFTSetup                 FFTSetup
    9897#define aubio_vvsqrt                   vvsqrtf
    9998#else
     
    105104#define aubio_vDSP_vsadd               vDSP_vsaddD
    106105#define aubio_vDSP_vsmul               vDSP_vsmulD
     106#define aubio_vDSP_create_fftsetup     vDSP_create_fftsetupD
     107#define aubio_vDSP_destroy_fftsetup    vDSP_destroy_fftsetupD
    107108#define aubio_DSPComplex               DSPDoubleComplex
    108109#define aubio_DSPSplitComplex          DSPDoubleSplitComplex
    109 #define aubio_vDSP_DFT_Setup           vDSP_DFT_SetupD
    110 #define aubio_vDSP_DFT_zrop_CreateSetup vDSP_DFT_zrop_CreateSetupD
    111 #define aubio_vDSP_DFT_Execute         vDSP_DFT_ExecuteD
    112 #define aubio_vDSP_DFT_DestroySetup    vDSP_DFT_DestroySetupD
     110#define aubio_FFTSetup                 FFTSetupD
    113111#define aubio_vvsqrt                   vvsqrt
    114112#endif /* HAVE_AUBIO_DOUBLE */
     
    155153
    156154#elif defined HAVE_ACCELERATE  // using ACCELERATE
    157   aubio_vDSP_DFT_Setup fftSetupFwd;
    158   aubio_vDSP_DFT_Setup fftSetupBwd;
     155  int log2fftsize;
     156  aubio_FFTSetup fftSetup;
    159157  aubio_DSPSplitComplex spec;
    160158  smpl_t *in, *out;
     
    213211
    214212#elif defined HAVE_ACCELERATE  // using ACCELERATE
    215   {
    216     uint_t radix = winsize;
    217     uint_t order = 0;
    218     while ((radix / 2) * 2 == radix) {
    219       radix /= 2;
    220       order++;
    221     }
    222     if (order < 4 || (radix != 1 && radix != 3 && radix != 5 && radix != 15)) {
    223       AUBIO_ERR("fft: vDSP/Accelerate supports FFT with sizes = "
    224           "f * 2 ** n, where n > 4 and f in [1, 3, 5, 15], but requested %d. "
    225           "Use the closest power of two, or try recompiling aubio with "
    226           "--enable-fftw3.\n", winsize);
    227       goto beach;
    228     }
    229   }
    230213  s->winsize = winsize;
    231214  s->fft_size = winsize;
    232215  s->compspec = new_fvec(winsize);
     216  s->log2fftsize = aubio_power_of_two_order(s->fft_size);
    233217  s->in = AUBIO_ARRAY(smpl_t, s->fft_size);
    234218  s->out = AUBIO_ARRAY(smpl_t, s->fft_size);
    235219  s->spec.realp = AUBIO_ARRAY(smpl_t, s->fft_size/2);
    236220  s->spec.imagp = AUBIO_ARRAY(smpl_t, s->fft_size/2);
    237   s->fftSetupFwd = aubio_vDSP_DFT_zrop_CreateSetup(NULL,
    238       s->fft_size, vDSP_DFT_FORWARD);
    239   s->fftSetupBwd = aubio_vDSP_DFT_zrop_CreateSetup(s->fftSetupFwd,
    240       s->fft_size, vDSP_DFT_INVERSE);
     221  s->fftSetup = aubio_vDSP_create_fftsetup(s->log2fftsize, FFT_RADIX2);
    241222
    242223#elif defined HAVE_INTEL_IPP  // using Intel IPP
     
    312293  AUBIO_FREE(s->spec.realp);
    313294  AUBIO_FREE(s->spec.imagp);
    314   aubio_vDSP_DFT_DestroySetup(s->fftSetupBwd);
    315   aubio_vDSP_DFT_DestroySetup(s->fftSetupFwd);
     295  aubio_vDSP_destroy_fftsetup(s->fftSetup);
    316296
    317297#elif defined HAVE_INTEL_IPP  // using Intel IPP
     
    371351  aubio_vDSP_ctoz((aubio_DSPComplex*)s->in, 2, &s->spec, 1, s->fft_size/2);
    372352  // compute the FFT
    373   aubio_vDSP_DFT_Execute(s->fftSetupFwd, s->spec.realp, s->spec.imagp,
    374       s->spec.realp, s->spec.imagp);
     353  aubio_vDSP_fft_zrip(s->fftSetup, &s->spec, 1, s->log2fftsize, FFT_FORWARD);
    375354  // convert from vDSP complex split to [ r0, r1, ..., rN, iN-1, .., i2, i1]
    376355  compspec->data[0] = s->spec.realp[0];
     
    440419  aubio_vDSP_ctoz((aubio_DSPComplex*)s->out, 2, &s->spec, 1, s->fft_size/2);
    441420  // compute the FFT
    442   aubio_vDSP_DFT_Execute(s->fftSetupBwd, s->spec.realp, s->spec.imagp,
    443       s->spec.realp, s->spec.imagp);
     421  aubio_vDSP_fft_zrip(s->fftSetup, &s->spec, 1, s->log2fftsize, FFT_INVERSE);
    444422  // convert result to real output
    445423  aubio_vDSP_ztoc(&s->spec, 1, (aubio_DSPComplex*)output->data, 2, s->fft_size/2);
     
    516494  }
    517495#endif
    518 #ifdef HAVE_FFTW3
    519   // for even length only, make sure last element is 0 or PI
    520   if (2 * (compspec->length / 2) == compspec->length) {
    521 #endif
    522     if (compspec->data[compspec->length/2] < 0) {
    523       spectrum->phas[spectrum->length - 1] = PI;
    524     } else {
    525       spectrum->phas[spectrum->length - 1] = 0.;
    526     }
    527 #ifdef HAVE_FFTW3
     496  if (compspec->data[compspec->length/2] < 0) {
     497    spectrum->phas[spectrum->length - 1] = PI;
    528498  } else {
    529     i = spectrum->length - 1;
    530     spectrum->phas[i] = ATAN2(compspec->data[compspec->length-i],
    531         compspec->data[i]);
    532   }
    533 #endif
     499    spectrum->phas[spectrum->length - 1] = 0.;
     500  }
    534501}
    535502
     
    541508        + SQR(compspec->data[compspec->length - i]) );
    542509  }
    543 #ifdef HAVE_FFTW3
    544   // for even length, make sure last element is > 0
    545   if (2 * (compspec->length / 2) == compspec->length) {
    546 #endif
    547     spectrum->norm[spectrum->length-1] =
    548       ABS(compspec->data[compspec->length/2]);
    549 #ifdef HAVE_FFTW3
    550   } else {
    551     i = spectrum->length - 1;
    552     spectrum->norm[i] = SQRT(SQR(compspec->data[i])
    553         + SQR(compspec->data[compspec->length - i]) );
    554   }
    555 #endif
     510  spectrum->norm[spectrum->length-1] =
     511    ABS(compspec->data[compspec->length/2]);
    556512}
    557513
  • src/spectral/filterbank.c

    rc03d191 r088760e  
    2424#include "fmat.h"
    2525#include "cvec.h"
    26 #include "vecutils.h"
    2726#include "spectral/filterbank.h"
    2827#include "mathutils.h"
     
    3433  uint_t n_filters;
    3534  fmat_t *filters;
    36   smpl_t norm;
    37   smpl_t power;
    3835};
    3936
     
    4845  /* allocate filter tables, a matrix of length win_s and of height n_filters */
    4946  fb->filters = new_fmat (n_filters, win_s / 2 + 1);
    50 
    51   fb->norm = 1;
    52 
    53   fb->power = 1;
    5447
    5548  return fb;
     
    7568  tmp.data = in->norm;
    7669
    77   if (f->power != 1.) fvec_pow(&tmp, f->power);
    78 
    7970  fmat_vecmul(f->filters, &tmp, out);
    8071
     
    9485  return 0;
    9586}
    96 
    97 uint_t
    98 aubio_filterbank_set_norm (aubio_filterbank_t *f, smpl_t norm)
    99 {
    100   if (norm != 0 && norm != 1) return AUBIO_FAIL;
    101   f->norm = norm;
    102   return AUBIO_OK;
    103 }
    104 
    105 smpl_t
    106 aubio_filterbank_get_norm (aubio_filterbank_t *f)
    107 {
    108   return f->norm;
    109 }
    110 
    111 uint_t
    112 aubio_filterbank_set_power (aubio_filterbank_t *f, smpl_t power)
    113 {
    114   f->power = power;
    115   return AUBIO_OK;
    116 }
    117 
    118 smpl_t
    119 aubio_filterbank_get_power (aubio_filterbank_t *f)
    120 {
    121   return f->norm;
    122 }
  • src/spectral/filterbank.h

    rc03d191 r088760e  
    8484uint_t aubio_filterbank_set_coeffs (aubio_filterbank_t * f, const fmat_t * filters);
    8585
    86 /** set norm parameter
    87 
    88   \param f filterbank object, as returned by new_aubio_filterbank()
    89   \param norm `1` to norm the filters, `0` otherwise.
    90 
    91   If set to `0`, the filters will not be normalized. If set to `1`,
    92   each filter will be normalized to one. Defaults to `1`.
    93 
    94   This function should be called *before* setting the filters with one of
    95   aubio_filterbank_set_triangle_bands(), aubio_filterbank_set_mel_coeffs(),
    96   aubio_filterbank_set_mel_coeffs_htk(), or
    97   aubio_filterbank_set_mel_coeffs_slaney().
    98 
    99  */
    100 uint_t aubio_filterbank_set_norm (aubio_filterbank_t *f, smpl_t norm);
    101 
    102 /** get norm parameter
    103 
    104   \param f filterbank object, as returned by new_aubio_filterbank()
    105   \returns `1` if norm is set, `0` otherwise. Defaults to `1`.
    106 
    107  */
    108 smpl_t aubio_filterbank_get_norm (aubio_filterbank_t *f);
    109 
    110 /** set power parameter
    111 
    112   \param f filterbank object, as returned by new_aubio_filterbank()
    113   \param power Raise norm of the input spectrum norm to this power before
    114   computing filterbank.  Defaults to `1`.
    115 
    116  */
    117 uint_t aubio_filterbank_set_power (aubio_filterbank_t *f, smpl_t power);
    118 
    119 /** get power parameter
    120 
    121   \param f filterbank object, as returned by new_aubio_filterbank()
    122   \return current power parameter. Defaults to `1`.
    123 
    124  */
    125 smpl_t aubio_filterbank_get_power (aubio_filterbank_t *f);
    126 
    12786#ifdef __cplusplus
    12887}
  • src/spectral/filterbank_mel.c

    rc03d191 r088760e  
    5555  }
    5656
    57   for (fn = 0; fn < freqs->length; fn++) {
    58     if (freqs->data[fn] < 0) {
    59       AUBIO_ERR("filterbank_mel: freqs must contain only positive values.\n");
    60       return AUBIO_FAIL;
    61     } else if (freqs->data[fn] > samplerate / 2) {
    62       AUBIO_WRN("filterbank_mel: freqs should contain only "
    63           "values < samplerate / 2.\n");
    64     } else if (fn > 0 && freqs->data[fn] < freqs->data[fn-1]) {
    65       AUBIO_ERR("filterbank_mel: freqs should be a list of frequencies "
    66           "sorted from low to high, but freq[%d] < freq[%d-1]\n", fn, fn);
    67       return AUBIO_FAIL;
    68     } else if (fn > 0 && freqs->data[fn] == freqs->data[fn-1]) {
    69       AUBIO_WRN("filterbank_mel: set_triangle_bands received a list "
    70           "with twice the frequency %f\n", freqs->data[fn]);
    71     }
     57  if (freqs->data[freqs->length - 1] > samplerate / 2) {
     58    AUBIO_WRN ("Nyquist frequency is %fHz, but highest frequency band ends at \
     59%fHz\n", samplerate / 2, freqs->data[freqs->length - 1]);
    7260  }
    7361
     
    9179
    9280  /* compute triangle heights so that each triangle has unit area */
    93   if (aubio_filterbank_get_norm(fb)) {
    94     for (fn = 0; fn < n_filters; fn++) {
    95       triangle_heights->data[fn] =
    96           2. / (upper_freqs->data[fn] - lower_freqs->data[fn]);
    97     }
    98   } else {
    99     fvec_ones (triangle_heights);
     81  for (fn = 0; fn < n_filters; fn++) {
     82    triangle_heights->data[fn] =
     83        2. / (upper_freqs->data[fn] - lower_freqs->data[fn]);
    10084  }
    10185
     
    10892  /* zeroing of all filters */
    10993  fmat_zeros (filters);
     94
     95  if (fft_freqs->data[1] >= lower_freqs->data[0]) {
     96    /* - 1 to make sure we don't miss the smallest power of two */
     97    uint_t min_win_s =
     98        (uint_t) FLOOR (samplerate / lower_freqs->data[0]) - 1;
     99    AUBIO_WRN ("Lowest frequency bin (%.2fHz) is higher than lowest frequency \
     100band (%.2f-%.2fHz). Consider increasing the window size from %d to %d.\n",
     101        fft_freqs->data[1], lower_freqs->data[0],
     102        upper_freqs->data[0], (win_s - 1) * 2,
     103        aubio_next_power_of_two (min_win_s));
     104  }
    110105
    111106  /* building each filter table */
     
    122117
    123118    /* compute positive slope step size */
    124     riseInc = triangle_heights->data[fn]
    125       / (center_freqs->data[fn] - lower_freqs->data[fn]);
     119    riseInc =
     120        triangle_heights->data[fn] /
     121        (center_freqs->data[fn] - lower_freqs->data[fn]);
    126122
    127123    /* compute coefficients in positive slope */
     
    137133
    138134    /* compute negative slope step size */
    139     downInc = triangle_heights->data[fn]
    140       / (upper_freqs->data[fn] - center_freqs->data[fn]);
     135    downInc =
     136        triangle_heights->data[fn] /
     137        (upper_freqs->data[fn] - center_freqs->data[fn]);
    141138
    142139    /* compute coefficents in negative slope */
     
    164161  del_fvec (fft_freqs);
    165162
    166   return AUBIO_OK;
     163  return 0;
    167164}
    168165
     
    171168    smpl_t samplerate)
    172169{
     170  uint_t retval;
     171
    173172  /* Malcolm Slaney parameters */
    174   const smpl_t lowestFrequency = 133.3333;
    175   const smpl_t linearSpacing = 66.66666666;
    176   const smpl_t logSpacing = 1.0711703;
    177 
    178   const uint_t linearFilters = 13;
    179   const uint_t logFilters = 27;
    180   const uint_t n_filters = linearFilters + logFilters;
    181 
    182   uint_t fn, retval;
     173  smpl_t lowestFrequency = 133.3333;
     174  smpl_t linearSpacing = 66.66666666;
     175  smpl_t logSpacing = 1.0711703;
     176
     177  uint_t linearFilters = 13;
     178  uint_t logFilters = 27;
     179  uint_t n_filters = linearFilters + logFilters;
     180
     181  uint_t fn;                    /* filter counter */
     182
    183183  smpl_t lastlinearCF;
    184184
    185185  /* buffers to compute filter frequencies */
    186   fvec_t *freqs;
    187 
    188   if (samplerate <= 0) {
    189     AUBIO_ERR("filterbank: set_mel_coeffs_slaney samplerate should be > 0\n");
    190     return AUBIO_FAIL;
    191   }
    192 
    193   freqs = new_fvec (n_filters + 2);
     186  fvec_t *freqs = new_fvec (n_filters + 2);
    194187
    195188  /* first step: fill all the linear filter frequencies */
     
    213206  return retval;
    214207}
    215 
    216 static uint_t aubio_filterbank_check_freqs (aubio_filterbank_t *fb UNUSED,
    217     smpl_t samplerate, smpl_t *freq_min, smpl_t *freq_max)
    218 {
    219   if (samplerate <= 0) {
    220     AUBIO_ERR("filterbank: set_mel_coeffs samplerate should be > 0\n");
    221     return AUBIO_FAIL;
    222   }
    223   if (*freq_max < 0) {
    224     AUBIO_ERR("filterbank: set_mel_coeffs freq_max should be > 0\n");
    225     return AUBIO_FAIL;
    226   } else if (*freq_max == 0) {
    227     *freq_max = samplerate / 2.;
    228   }
    229   if (*freq_min < 0) {
    230     AUBIO_ERR("filterbank: set_mel_coeffs freq_min should be > 0\n");
    231     return AUBIO_FAIL;
    232   }
    233   return AUBIO_OK;
    234 }
    235 
    236 uint_t
    237 aubio_filterbank_set_mel_coeffs (aubio_filterbank_t * fb, smpl_t samplerate,
    238     smpl_t freq_min, smpl_t freq_max)
    239 {
    240   uint_t m, retval;
    241   smpl_t start = freq_min, end = freq_max, step;
    242   fvec_t *freqs;
    243   fmat_t *coeffs = aubio_filterbank_get_coeffs(fb);
    244   uint_t n_bands = coeffs->height;
    245 
    246   if (aubio_filterbank_check_freqs(fb, samplerate, &start, &end)) {
    247     return AUBIO_FAIL;
    248   }
    249 
    250   start = aubio_hztomel(start);
    251   end = aubio_hztomel(end);
    252 
    253   freqs = new_fvec(n_bands + 2);
    254   step = (end - start) / (n_bands + 1);
    255 
    256   for (m = 0; m < n_bands + 2; m++)
    257   {
    258     freqs->data[m] = MIN(aubio_meltohz(start + step * m), samplerate/2.);
    259   }
    260 
    261   retval = aubio_filterbank_set_triangle_bands (fb, freqs, samplerate);
    262 
    263   /* destroy vector used to store frequency limits */
    264   del_fvec (freqs);
    265   return retval;
    266 }
    267 
    268 uint_t
    269 aubio_filterbank_set_mel_coeffs_htk (aubio_filterbank_t * fb, smpl_t samplerate,
    270     smpl_t freq_min, smpl_t freq_max)
    271 {
    272   uint_t m, retval;
    273   smpl_t start = freq_min, end = freq_max, step;
    274   fvec_t *freqs;
    275   fmat_t *coeffs = aubio_filterbank_get_coeffs(fb);
    276   uint_t n_bands = coeffs->height;
    277 
    278   if (aubio_filterbank_check_freqs(fb, samplerate, &start, &end)) {
    279     return AUBIO_FAIL;
    280   }
    281 
    282   start = aubio_hztomel_htk(start);
    283   end = aubio_hztomel_htk(end);
    284 
    285   freqs = new_fvec (n_bands + 2);
    286   step = (end - start) / (n_bands + 1);
    287 
    288   for (m = 0; m < n_bands + 2; m++)
    289   {
    290     freqs->data[m] = MIN(aubio_meltohz_htk(start + step * m), samplerate/2.);
    291   }
    292 
    293   retval = aubio_filterbank_set_triangle_bands (fb, freqs, samplerate);
    294 
    295   /* destroy vector used to store frequency limits */
    296   del_fvec (freqs);
    297   return retval;
    298 }
  • src/spectral/filterbank_mel.h

    rc03d191 r088760e  
    5656
    5757  \param fb filterbank object
    58   \param samplerate audio sampling rate, in Hz
     58  \param samplerate audio sampling rate
    5959
    60   The filter coefficients are built to match exactly Malcolm Slaney's Auditory
    61   Toolbox implementation (see file mfcc.m). The number of filters should be 40.
     60  The filter coefficients are built according to Malcolm Slaney's Auditory
     61  Toolbox, available online at the following address (see file mfcc.m):
    6262
    63   References
    64   ----------
    65 
    66   Malcolm Slaney, *Auditory Toolbox Version 2, Technical Report #1998-010*
    6763  https://engineering.purdue.edu/~malcolm/interval/1998-010/
    6864
     
    7167    smpl_t samplerate);
    7268
    73 /** Mel filterbank initialization
    74 
    75   \param fb filterbank object
    76   \param samplerate audio sampling rate
    77   \param fmin start frequency, in Hz
    78   \param fmax end frequency, in Hz
    79 
    80   The filterbank will be initialized with bands linearly spaced in the mel
    81   scale, from `fmin` to `fmax`.
    82 
    83   References
    84   ----------
    85 
    86   Malcolm Slaney, *Auditory Toolbox Version 2, Technical Report #1998-010*
    87   https://engineering.purdue.edu/~malcolm/interval/1998-010/
    88 
    89 */
    90 uint_t aubio_filterbank_set_mel_coeffs(aubio_filterbank_t * fb,
    91     smpl_t samplerate, smpl_t fmin, smpl_t fmax);
    92 
    93 /** Mel filterbank initialization
    94 
    95   \param fb filterbank object
    96   \param samplerate audio sampling rate
    97   \param fmin start frequency, in Hz
    98   \param fmax end frequency, in Hz
    99 
    100   The bank of filters will be initalized to to cover linearly spaced bands in
    101   the Htk mel scale, from `fmin` to `fmax`.
    102 
    103   References
    104   ----------
    105 
    106   Douglas O'Shaughnessy (1987). *Speech communication: human and machine*.
    107   Addison-Wesley. p. 150. ISBN 978-0-201-16520-3.
    108 
    109   HTK Speech Recognition Toolkit: http://htk.eng.cam.ac.uk/
    110 
    111 */
    112 uint_t aubio_filterbank_set_mel_coeffs_htk(aubio_filterbank_t * fb,
    113     smpl_t samplerate, smpl_t fmin, smpl_t fmax);
    114 
    11569#ifdef __cplusplus
    11670}
  • src/spectral/mfcc.c

    rc03d191 r088760e  
    5252  fvec_t *output;
    5353#endif
    54   smpl_t scale;
    5554};
    5655
     
    7675  /* filterbank allocation */
    7776  mfcc->fb = new_aubio_filterbank (n_filters, mfcc->win_s);
    78   if (n_filters == 40)
    79     aubio_filterbank_set_mel_coeffs_slaney (mfcc->fb, samplerate);
    80   else
    81     aubio_filterbank_set_mel_coeffs(mfcc->fb, samplerate,
    82         0, samplerate/2.);
     77  aubio_filterbank_set_mel_coeffs_slaney (mfcc->fb, samplerate);
    8378
    8479  /* allocating buffers */
     
    10297  mfcc->output = new_fvec (n_filters);
    10398#endif
    104 
    105   mfcc->scale = 1.;
    10699
    107100  return mfcc;
     
    135128  fvec_t tmp;
    136129#endif
    137 
    138130  /* compute filterbank */
    139131  aubio_filterbank_do (mf->fb, in, mf->in_dct);
     
    142134  fvec_log10 (mf->in_dct);
    143135
    144   if (mf->scale != 1) fvec_mul (mf->in_dct, mf->scale);
     136  /* raise power */
     137  //fvec_pow (mf->in_dct, 3.);
    145138
    146139  /* compute mfccs */
     
    158151  return;
    159152}
    160 
    161 uint_t aubio_mfcc_set_power (aubio_mfcc_t *mf, smpl_t power)
    162 {
    163   return aubio_filterbank_set_power(mf->fb, power);
    164 }
    165 
    166 uint_t aubio_mfcc_get_power (aubio_mfcc_t *mf)
    167 {
    168   return aubio_filterbank_get_power(mf->fb);
    169 }
    170 
    171 uint_t aubio_mfcc_set_scale (aubio_mfcc_t *mf, smpl_t scale)
    172 {
    173   mf->scale = scale;
    174   return AUBIO_OK;
    175 }
    176 
    177 uint_t aubio_mfcc_get_scale (aubio_mfcc_t *mf)
    178 {
    179   return mf->scale;
    180 }
    181 
    182 uint_t aubio_mfcc_set_mel_coeffs (aubio_mfcc_t *mf, smpl_t freq_min,
    183     smpl_t freq_max)
    184 {
    185   return aubio_filterbank_set_mel_coeffs(mf->fb, mf->samplerate,
    186       freq_min, freq_max);
    187 }
    188 
    189 uint_t aubio_mfcc_set_mel_coeffs_htk (aubio_mfcc_t *mf, smpl_t freq_min,
    190     smpl_t freq_max)
    191 {
    192   return aubio_filterbank_set_mel_coeffs_htk(mf->fb, mf->samplerate,
    193       freq_min, freq_max);
    194 }
    195 
    196 uint_t aubio_mfcc_set_mel_coeffs_slaney (aubio_mfcc_t *mf)
    197 {
    198   return aubio_filterbank_set_mel_coeffs_slaney (mf->fb, mf->samplerate);
    199 }
  • src/spectral/mfcc.h

    rc03d191 r088760e  
    7474void aubio_mfcc_do (aubio_mfcc_t * mf, const cvec_t * in, fvec_t * out);
    7575
    76 /** set power parameter
    77 
    78   \param mf mfcc object, as returned by new_aubio_mfcc()
    79   \param power Raise norm of the input spectrum norm to this power before
    80   computing filterbank.  Defaults to `1`.
    81 
    82   See aubio_filterbank_set_power().
    83 
    84  */
    85 uint_t aubio_mfcc_set_power (aubio_mfcc_t *mf, smpl_t power);
    86 
    87 /** get power parameter
    88 
    89   \param mf mfcc object, as returned by new_aubio_mfcc()
    90   \return current power parameter. Defaults to `1`.
    91 
    92   See aubio_filterbank_get_power().
    93 
    94  */
    95 uint_t aubio_mfcc_get_power (aubio_mfcc_t *mf);
    96 
    97 /** set scaling parameter
    98 
    99   \param mf mfcc object, as returned by new_aubio_mfcc()
    100   \param scale Scaling value to apply.
    101 
    102   Scales the output of the filterbank after taking its logarithm and before
    103   computing the DCT. Defaults to `1`.
    104 
    105 */
    106 uint_t aubio_mfcc_set_scale (aubio_mfcc_t *mf, smpl_t scale);
    107 
    108 /** get scaling parameter
    109 
    110   \param mf mfcc object, as returned by new_aubio_mfcc()
    111   \return current scaling parameter. Defaults to `1`.
    112 
    113  */
    114 uint_t aubio_mfcc_get_scale (aubio_mfcc_t *mf);
    115 
    116 /** Mel filterbank initialization
    117 
    118   \param mf mfcc object
    119   \param fmin start frequency, in Hz
    120   \param fmax end frequency, in Hz
    121 
    122   The filterbank will be initialized with bands linearly spaced in the mel
    123   scale, from `fmin` to `fmax`.
    124 
    125   See also
    126   --------
    127 
    128   aubio_filterbank_set_mel_coeffs()
    129 
    130 */
    131 uint_t aubio_mfcc_set_mel_coeffs (aubio_mfcc_t *mf,
    132         smpl_t fmin, smpl_t fmax);
    133 
    134 /** Mel filterbank initialization
    135 
    136   \param mf mfcc object
    137   \param fmin start frequency, in Hz
    138   \param fmax end frequency, in Hz
    139 
    140   The bank of filters will be initalized to to cover linearly spaced bands in
    141   the Htk mel scale, from `fmin` to `fmax`.
    142 
    143   See also
    144   --------
    145 
    146   aubio_filterbank_set_mel_coeffs_htk()
    147 
    148 */
    149 uint_t aubio_mfcc_set_mel_coeffs_htk (aubio_mfcc_t *mf,
    150         smpl_t fmin, smpl_t fmax);
    151 
    152 /** Mel filterbank initialization (Auditory Toolbox's parameters)
    153 
    154   \param mf mfcc object
    155   \param samplerate audio sampling rate, in Hz
    156 
    157   The filter coefficients are built to match exactly Malcolm Slaney's Auditory
    158   Toolbox implementation. The number of filters should be 40.
    159 
    160   This is the default filterbank when `mf` was created with `n_filters = 40`.
    161 
    162   See also
    163   --------
    164 
    165   aubio_filterbank_set_mel_coeffs_slaney()
    166 
    167 */
    168 uint_t aubio_mfcc_set_mel_coeffs_slaney (aubio_mfcc_t *mf);
    169 
    17076#ifdef __cplusplus
    17177}
  • tests/src/spectral/test-filterbank.c

    rc03d191 r088760e  
    1111  // create filterbank object
    1212  aubio_filterbank_t *o = new_aubio_filterbank (n_filters, win_s);
    13 
    14   smpl_t power = aubio_filterbank_get_power(o);
    15   smpl_t norm = aubio_filterbank_get_norm(o);
    16   if (aubio_filterbank_set_power(o, power)) {
    17     return 1;
    18   }
    19   if (aubio_filterbank_set_norm(o, norm)) {
    20     return 1;
    21   }
    2213
    2314  // apply filterbank ten times
  • tests/src/temporal/test-filter.c

    rc03d191 r088760e  
    99
    1010  aubio_filter_t *o = new_aubio_filter_c_weighting (44100);
    11 
    12   if (new_aubio_filter(0))
    13     return 1;
    14 
    15   if (aubio_filter_get_samplerate(o) != 44100)
    16     return 1;
    17 
    18   if (aubio_filter_set_c_weighting (o, -1) == 0)
    19     return 1;
    20 
    21   if (aubio_filter_set_c_weighting (0, 32000) == 0)
    22     return 1;
    23 
    2411  in->data[impulse_at] = 0.5;
    2512  fvec_print (in);
     
    2916
    3017  o = new_aubio_filter_a_weighting (32000);
    31 
    32   if (aubio_filter_set_a_weighting (o, -1) == 0)
    33     return 1;
    34   if (aubio_filter_set_a_weighting (0, 32000) == 0)
    35     return 1;
    36 
    3718  in->data[impulse_at] = 0.5;
    3819  fvec_print (in);
  • wscript

    rc03d191 r088760e  
    4343            choices = ('debug', 'release'),
    4444            dest = 'build_type',
    45             help = 'whether to compile with (--build-type=release)' \
    46                     ' or without (--build-type=debug)' \
    47                     ' compiler opimizations [default: release]')
     45            help = 'whether to compile with (--build-type=release) or without (--build-type=debug) '\
     46              ' compiler opimizations [default: release]')
    4847    add_option_enable_disable(ctx, 'fftw3f', default = False,
    4948            help_str = 'compile with fftw3f instead of ooura (recommended)',
     
    111110
    112111    ctx.add_option('--with-target-platform', type='string',
    113             help='set target platform for cross-compilation',
    114             dest='target_platform')
     112            help='set target platform for cross-compilation', dest='target_platform')
    115113
    116114    ctx.load('compiler_c')
     
    208206            ctx.msg('Checking for AudioToolbox.framework', 'yes')
    209207        else:
    210             ctx.msg('Checking for AudioToolbox.framework', 'no (disabled)',
    211                     color = 'YELLOW')
     208            ctx.msg('Checking for AudioToolbox.framework', 'no (disabled)', color = 'YELLOW')
    212209        if (ctx.options.enable_accelerate != False):
    213210            ctx.define('HAVE_ACCELERATE', 1)
     
    215212            ctx.msg('Checking for Accelerate framework', 'yes')
    216213        else:
    217             ctx.msg('Checking for Accelerate framework', 'no (disabled)',
    218                     color = 'YELLOW')
     214            ctx.msg('Checking for Accelerate framework', 'no (disabled)', color = 'YELLOW')
    219215
    220216    if target_platform in [ 'ios', 'iosimulator' ]:
     
    270266        # tell emscripten functions we want to expose
    271267        from python.lib.gen_external import get_c_declarations, \
    272                 get_cpp_objects_from_c_declarations, \
    273                 get_all_func_names_from_lib, \
     268                get_cpp_objects_from_c_declarations, get_all_func_names_from_lib, \
    274269                generate_lib_from_c_declarations
    275         # emscripten can't use double
    276         c_decls = get_c_declarations(usedouble=False)
     270        c_decls = get_c_declarations(usedouble=False)  # emscripten can't use double
    277271        objects = list(get_cpp_objects_from_c_declarations(c_decls))
    278272        # ensure that aubio structs are exported
     
    281275        exported_funcnames = get_all_func_names_from_lib(lib)
    282276        c_mangled_names = ['_' + s for s in exported_funcnames]
    283         ctx.env.LINKFLAGS_cshlib += ['-s',
    284                 'EXPORTED_FUNCTIONS=%s' % c_mangled_names]
     277        ctx.env.LINKFLAGS_cshlib += ['-s', 'EXPORTED_FUNCTIONS=%s' % c_mangled_names]
    285278
    286279    # check support for C99 __VA_ARGS__ macros
     
    312305    # check for Intel IPP
    313306    if (ctx.options.enable_intelipp != False):
    314         has_ipp_headers = ctx.check(header_name=['ippcore.h', 'ippvm.h',
    315             'ipps.h'], mandatory = False)
     307        has_ipp_headers = ctx.check(header_name=['ippcore.h', 'ippvm.h', 'ipps.h'],
     308                mandatory = False)
    316309        has_ipp_libs = ctx.check(lib=['ippcore', 'ippvm', 'ipps'],
    317310                uselib_store='INTEL_IPP', mandatory = False)
     
    320313            ctx.define('HAVE_INTEL_IPP', 1)
    321314            if ctx.env.CC_NAME == 'msvc':
    322                 # force linking multi-threaded static IPP libraries on Windows
    323                 # with msvc
     315                # force linking multi-threaded static IPP libraries on Windows with msvc
    324316                ctx.define('_IPP_SEQUENTIAL_STATIC', 1)
    325317        else:
     
    370362    if (ctx.options.enable_double):
    371363        if (ctx.options.enable_samplerate):
    372             ctx.fatal("Could not compile aubio in double precision mode' \
    373                     ' with libsamplerate")
     364            ctx.fatal("Could not compile aubio in double precision mode with libsamplerate")
    374365        else:
    375366            ctx.options.enable_samplerate = False
    376             ctx.msg('Checking if using samplerate',
    377                     'no (disabled in double precision mode)', color = 'YELLOW')
     367            ctx.msg('Checking if using samplerate', 'no (disabled in double precision mode)',
     368                    color = 'YELLOW')
    378369    if (ctx.options.enable_samplerate != False):
    379370        ctx.check_cfg(package = 'samplerate',
     
    418409        elif 'HAVE_AVUTIL' not in ctx.env:
    419410            ctx.msg(msg_check, 'not found (missing avutil)', color = 'YELLOW')
    420         elif 'HAVE_SWRESAMPLE' not in ctx.env \
    421                 and 'HAVE_AVRESAMPLE' not in ctx.env:
     411        elif 'HAVE_SWRESAMPLE' not in ctx.env and 'HAVE_AVRESAMPLE' not in ctx.env:
    422412            resample_missing = 'not found (avresample or swresample required)'
    423413            ctx.msg(msg_check, resample_missing, color = 'YELLOW')
     
    432422    if (ctx.options.enable_wavread != False):
    433423        ctx.define('HAVE_WAVREAD', 1)
    434     ctx.msg('Checking if using source_wavread',
    435             ctx.options.enable_wavread and 'yes' or 'no')
     424    ctx.msg('Checking if using source_wavread', ctx.options.enable_wavread and 'yes' or 'no')
    436425    if (ctx.options.enable_wavwrite!= False):
    437426        ctx.define('HAVE_WAVWRITE', 1)
    438     ctx.msg('Checking if using sink_wavwrite',
    439             ctx.options.enable_wavwrite and 'yes' or 'no')
     427    ctx.msg('Checking if using sink_wavwrite', ctx.options.enable_wavwrite and 'yes' or 'no')
    440428
    441429    # use BLAS/ATLAS
     
    555543
    556544def sphinx(bld):
    557     # build documentation from source files using sphinx-build note: build in
    558     # ../doc/_build/html, otherwise waf wont install unsigned files
     545    # build documentation from source files using sphinx-build
     546    # note: build in ../doc/_build/html, otherwise waf wont install unsigned files
    559547    if bld.env['SPHINX']:
    560548        bld.env.VERSION = VERSION
    561549        bld( name = 'sphinx',
    562                 rule = '${SPHINX} -b html -D release=${VERSION}' \
    563                         ' -D version=${VERSION} -a -q' \
    564                         ' `dirname ${SRC}` `dirname ${TGT}`',
     550                rule = '${SPHINX} -b html -D release=${VERSION} -D version=${VERSION} -a -q `dirname ${SRC}` `dirname ${TGT}`',
    565551                source = 'doc/conf.py',
    566552                target = '../doc/_build/html/index.html')
     
    592578    from waflib import Logs
    593579    if bld.options.target_platform in ['ios', 'iosimulator']:
    594         msg ='building for %s, contact the author for a commercial license' \
    595                 % bld.options.target_platform
     580        msg ='building for %s, contact the author for a commercial license' % bld.options.target_platform
    596581        Logs.pprint('RED', msg)
    597582        msg ='   Paul Brossier <piem@aubio.org>'
     
    599584
    600585def dist(ctx):
    601     ctx.excl  = ' **/.waf*'
    602     ctx.excl += ' **/.git*'
    603     ctx.excl += ' **/*~ **/*.pyc **/*.swp **/*.swo **/*.swn **/.lock-w*'
     586    ctx.excl  = ' **/.waf* **/*~ **/*.pyc **/*.swp **/*.swo **/*.swn **/.lock-w* **/.git*'
    604587    ctx.excl += ' **/build/*'
    605588    ctx.excl += ' doc/_build'
     
    609592    ctx.excl += ' **/python/lib/aubio/_aubio.so'
    610593    ctx.excl += ' **.egg-info'
    611     ctx.excl += ' **/.eggs'
    612     ctx.excl += ' **/.pytest_cache'
    613     ctx.excl += ' **/.cache'
    614594    ctx.excl += ' **/**.zip **/**.tar.bz2'
    615595    ctx.excl += ' **.tar.bz2'
Note: See TracChangeset for help on using the changeset viewer.