Changes in / [60fc05b:f264b17]


Ignore:
Files:
24 added
7 deleted
177 edited

Legend:

Unmodified
Added
Removed
  • .gitignore

    r60fc05b rf264b17  
    4040aubio-*.tar.bz2
    4141aubio-*.zip
     42
     43# test sounds
     44python/tests/sounds
     45aubio.egg-info
  • .travis.yml

    r60fc05b rf264b17  
    1 language: c
     1language: python
    22
    3 sudo: false
    4 
    5 compiler:
    6   - gcc
    7   - clang
    8 
    9 env:
    10   - ARCH=i386
    11   - ARCH=x86_64
     3matrix:
     4  include:
     5    - python: 2.7
     6      os: linux
     7      compiler: gcc
     8      env: ARCH=x86_64
     9    - python: 2.7
     10      os: linux
     11      compiler: gcc
     12      env: ARCH=i386
     13    - python: 3.4
     14      os: linux
     15      compiler: gcc
     16      env: ARCH=x86_64
     17    - python: 3.4
     18      os: linux
     19      compiler: gcc
     20      env: ARCH=i386 WAFOPTS=--enable-fftw3f
     21    - language: C
     22      os: osx
     23      compiler: clang
     24      env: ARCH=x86_64
     25    - language: C
     26      os: osx
     27      compiler: clang
     28      env: ARCH=i386
     29    - python: 2.7
     30      os: linux
     31      compiler: gcc
     32      env: ARCH=x86_64 HAVE_DOUBLE=1 WAFOPTS=--enable-fftw3
     33    - python: 2.7
     34      os: linux
     35      compiler: gcc
     36      env: ARCH=i386 HAVE_DOUBLE=1
     37    - python: 3.4
     38      os: linux
     39      compiler: gcc
     40      env: ARCH=x86_64 HAVE_DOUBLE=1
     41    - python: 3.4
     42      os: linux
     43      compiler: gcc
     44      env: ARCH=i386 HAVE_DOUBLE=1
     45    - language: C
     46      os: osx
     47      compiler: clang
     48      env: ARCH=x86_64 HAVE_DOUBLE=1
     49    - language: C
     50      os: osx
     51      compiler: clang
     52      env: ARCH=i386 HAVE_DOUBLE=1
     53    - language: C
     54      os: osx
     55      compiler: clang
     56      env: ARCH=x86_64 WAFOPTS=--enable-fat
     57    - language: C
     58      os: osx
     59      compiler: clang
     60      env: ARCH=i386 WAFOPTS=--enable-fat
    1261
    1362addons:
     
    2069    - libasound2-dev
    2170    - libfftw3-dev
    22     - python-dev
    23     - python-numpy
     71    - sox
     72
     73before_install:
     74   - |
     75     if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then
     76       brew update
     77       brew install sox
     78       export PATH="$HOME/Library/Python/2.7/bin/:$PATH"
     79     fi;
     80
     81
     82install:
     83  - if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then travis_retry pip install nose2; fi
     84  - if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then travis_retry pip install --user nose2; fi
    2485
    2586script:
     87  - make create_test_sounds
    2688  - make build
    2789  - make build_python
     90  - if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then make test_python; fi
     91  - if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then make test_python_osx; fi
    2892  - make clean_python
    2993  - make clean
    3094  - make distcheck
     95  - make test_pure_python
     96
     97notifications:
     98    irc:
     99        channels:
     100            - "irc.freenode.org#aubio"
     101        use_notice: true
  • Makefile

    r60fc05b rf264b17  
     1WAFCMD=python waf
     2
     3SOX=sox
     4
     5ENABLE_DOUBLE := $(shell [ -z $(HAVE_DOUBLE) ] || echo --enable-double )
     6TESTSOUNDS := python/tests/sounds
     7
    18all: build
    29
     
    512
    613getwaf:
    7         curl https://waf.io/waf-1.8.12 > waf
     14        curl https://waf.io/waf-1.8.20 > waf
     15        @chmod +x waf
     16
     17expandwaf:
    818        @[ -d wafilb ] || rm -fr waflib
    9         @chmod +x waf && ./waf --help > /dev/null
    10         @mv .waf*/waflib . && rm -fr .waf-*
     19        @$(WAFCMD) --help > /dev/null
     20        @mv .waf*/waflib . && rm -fr .waf*
    1121        @sed '/^#==>$$/,$$d' waf > waf2 && mv waf2 waf
    1222        @chmod +x waf
    1323
    14 build: checkwaf
    15         ./waf configure
    16         ./waf build
     24configure: checkwaf
     25        $(WAFCMD) configure $(WAFOPTS) $(ENABLE_DOUBLE)
     26
     27build: configure
     28        $(WAFCMD) build $(WAFOPTS)
    1729
    1830build_python:
    19         cd python && ./setup.py build
     31        python ./setup.py generate $(ENABLE_DOUBLE) build
     32
     33test_python: export LD_LIBRARY_PATH=$(PWD)/build/src
     34test_python:
     35        pip install -v -r requirements.txt
     36        pip install -v .
     37        nose2 --verbose
     38        pip uninstall -y -v aubio
     39
     40test_python_osx:
     41        # create links from ~/lib/lib* to build/src/lib*
     42        [ -f build/src/libaubio.[0-9].dylib ] && ( mkdir -p ~/lib && cp -prv build/src/libaubio.4.dylib ~/lib ) || true
     43        # then run the tests
     44        pip install --user -v -r requirements.txt
     45        pip install --user -v .
     46        nose2 --verbose
     47        pip uninstall -y -v aubio
    2048
    2149clean_python:
    22         cd python && ./setup.py clean
     50        ./setup.py clean
     51
     52test_pure_python:
     53        -pip uninstall -v -y aubio
     54        -rm -rf build/ python/gen/
     55        -rm -f dist/*.egg
     56        -pip install -v -r requirements.txt
     57        CFLAGS=-Os python setup.py bdist_egg
     58        [ "$(TRAVIS_OS_NAME)" == "osx" ] && easy_install --user dist/*.egg || \
     59                easy_install dist/*.egg
     60        nose2 -N 4
     61        pip uninstall -v -y aubio
     62
     63test_pure_python_wheel:
     64        -pip uninstall -v -y aubio
     65        -rm -rf build/ python/gen/
     66        -rm -f dist/*.whl
     67        -pip install -v -r requirements.txt
     68        -pip install -v wheel
     69        CFLAGS=-Os python setup.py bdist_wheel --universal
     70        wheel install dist/*.whl
     71        nose2 -N 4
     72        pip uninstall -v -y aubio
     73
     74build_python3:
     75        python3 ./setup.py generate $(ENABLE_DOUBLE) build
     76
     77clean_python3:
     78        python3 ./setup.py clean
    2379
    2480clean:
    25         ./waf clean
     81        $(WAFCMD) clean
    2682
    27 distcheck: build
    28         ./waf distcheck
     83distcheck: checkwaf
     84        $(WAFCMD) distcheck $(WAFOPTS) $(ENABLE_DOUBLE)
    2985
    3086help:
    31         ./waf --help
     87        $(WAFCMD) --help
     88
     89create_test_sounds:
     90        -[ -z `which $(SOX)` ] && ( echo $(SOX) could not be found) || true
     91        -mkdir -p $(TESTSOUNDS)
     92        -$(SOX) -r 44100 -b 16 -n "$(TESTSOUNDS)/44100Hz_1f_silence.wav"      synth 1s   silence 0
     93        -$(SOX) -r 22050 -b 16 -n "$(TESTSOUNDS)/22050Hz_5s_brownnoise.wav"   synth 5    brownnoise      vol 0.9
     94        -$(SOX) -r 32000 -b 16 -n "$(TESTSOUNDS)/32000Hz_127f_sine440.wav"    synth 127s sine 440        vol 0.9
     95        -$(SOX) -r  8000 -b 16 -n "$(TESTSOUNDS)/8000Hz_30s_silence.wav"      synth 30   silence 0       vol 0.9
     96        -$(SOX) -r 48000 -b 32 -n "$(TESTSOUNDS)/48000Hz_60s_sweep.wav"       synth 60   sine 100-20000  vol 0.9
  • README.md

    r60fc05b rf264b17  
    6969The latest version of the documentation can be found at:
    7070
    71   http://aubio.org/documentation
     71  https://aubio.org/documentation
    7272
    73 Installation and Build Instructions
    74 -----------------------------------
     73Build Instructions
     74------------------
    7575
    7676A number of distributions already include aubio. Check your favorite package
    7777management system, or have a look at the [download
    78 page](http://aubio.org/download).
     78page](https://aubio.org/download).
    7979
    8080aubio uses [waf](https://waf.io/) to configure, compile, and test the source:
     
    8282    ./waf configure
    8383    ./waf build
    84     sudo ./waf install
    8584
    8685If waf is not found in the directory, you can download and install it with:
     
    8988
    9089aubio compiles on Linux, Mac OS X, Cygwin, and iOS.
     90
     91Installation
     92------------
     93
     94To install aubio library and headers on your system, use:
     95
     96    sudo ./waf install
     97
     98To uninstall:
     99
     100    sudo ./waf uninstall
     101
     102If you don't have root access to install libaubio on your system, you can use
     103libaubio without installing libaubio either by setting `LD_LIBRARY_PATH`, or by
     104copying it to `~/lib`.
     105
     106On Linux, you should be able to set `LD_LIBRARY_PATH` with:
     107
     108    $ export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$PWD/build/src
     109
     110On Mac OS X, a copy or a symlink can be made in `~/lib`:
     111
     112    $ mkdir -p ~/lib
     113    $ ln -sf $PWD/build/src/libaubio*.dylib ~/lib/
     114
     115Note on Mac OS X systems older than El Capitan (10.11), the `DYLD_LIBRARY_PATH`
     116variable can be set as follows:
     117
     118    $ export DYLD_LIBRARY_PATH=$DYLD_LIBRARY_PATH:$PWD/build/src
    91119
    92120Credits and Publications
     
    108136
    109137  - Paul Brossier, _[Automatic annotation of musical audio for interactive
    110     systems](http://aubio.org/phd)_, PhD thesis, Centre for Digital music,
     138    systems](https://aubio.org/phd)_, PhD thesis, Centre for Digital music,
    111139Queen Mary University of London, London, UK, 2006.
    112140
     
    115143
    116144  - P. M. Brossier and J. P. Bello and M. D. Plumbley, [Real-time temporal
    117     segmentation of note objects in music signals](http://aubio.org/articles/brossier04fastnotes.pdf),
     145    segmentation of note objects in music signals](https://aubio.org/articles/brossier04fastnotes.pdf),
    118146in _Proceedings of the International Computer Music Conference_, 2004, Miami,
    119147Florida, ICMA
    120148
    121149  -  P. M. Brossier and J. P. Bello and M. D. Plumbley, [Fast labelling of note
    122      objects in music signals] (http://aubio.org/articles/brossier04fastnotes.pdf),
     150     objects in music signals] (https://aubio.org/articles/brossier04fastnotes.pdf),
    123151in _Proceedings of the International Symposium on Music Information Retrieval_,
    1241522004, Barcelona, Spain
     
    128156-----------------------------
    129157
    130 The home page of this project can be found at: http://aubio.org/
     158The home page of this project can be found at: https://aubio.org/
    131159
    132160Questions, comments, suggestions, and contributions are welcome. Use the
  • examples/aubiotrack.c

    r60fc05b rf264b17  
    2121#include "utils.h"
    2222#define PROG_HAS_TEMPO 1
     23#define PROG_HAS_ONSET 1
    2324#define PROG_HAS_OUTPUT 1
    2425#define PROG_HAS_JACK 1
  • examples/jackio.c

    r60fc05b rf264b17  
    2222#include "config.h"
    2323
    24 #if HAVE_JACK
     24#ifdef HAVE_JACK
    2525#include "utils.h" // for aubio_process_func_t
    2626#include "jackio.h"
  • examples/parse_args.h

    r60fc05b rf264b17  
    1818
    1919*/
     20
     21#include "config.h"
     22
     23#ifdef HAVE_GETOPT_H
     24#include <getopt.h>
     25#endif
    2026
    2127extern int verbose;
     
    6470void usage (FILE * stream, int exit_code)
    6571{
     72#ifdef HAVE_GETOPT_H
    6673  fprintf (stream, "usage: %s [ options ] \n", prog_name);
    6774  fprintf (stream,
     
    107114      "       -h      --help             display this message\n"
    108115      );
     116#else /* HAVE_GETOPT_H */
     117  fprintf (stream, "warning: compiled with getopt.h, no argument parsing\n");
     118  fprintf (stream, "usage: %s <filename> \n", prog_name);
     119#endif /* HAVE_GETOPT_H */
    109120  exit (exit_code);
    110121}
     
    113124parse_args (int argc, char **argv)
    114125{
     126#ifdef HAVE_GETOPT_H
    115127  const char *options = "hv"
    116128    "i:r:B:H:"
     
    158170    {NULL,                    0, NULL, 0}
    159171  };
     172#endif /* HAVE_GETOPT_H */
    160173  prog_name = argv[0];
    161174  if (argc < 1) {
     
    163176    return -1;
    164177  }
     178#ifdef HAVE_GETOPT_H
    165179  do {
    166180    next_option = getopt_long (argc, argv, options, long_options, NULL);
     
    236250  }
    237251  while (next_option != -1);
     252#else /* HAVE_GETOPT_H */
     253  int optind = 1;
     254#endif /* HAVE_GETOPT_H */
    238255
    239256  // if unique, use the non option argument as the source
  • examples/utils.c

    r60fc05b rf264b17  
    7373#if HAVE_JACK
    7474aubio_jack_t *jack_setup;
    75 #endif
     75#endif /* HAVE_JACK */
    7676
    7777void examples_common_init (int argc, char **argv);
     
    115115    samplerate = aubio_jack_get_samplerate (jack_setup);
    116116    source_uri = "jack";
    117 #endif
     117#endif /* HAVE_JACK */
    118118  }
    119119  ibuf = new_fvec (hop_size);
     
    138138  if (usejack) {
    139139
    140 #if HAVE_JACK
     140#ifdef HAVE_JACK
    141141    debug ("Jack activation ...\n");
    142142    aubio_jack_activate (jack_setup, process_func);
     
    144144    pause ();
    145145    aubio_jack_close (jack_setup);
    146 #else
     146#else /* HAVE_JACK */
    147147    usage (stderr, 1);
    148148    outmsg ("Compiled without jack output, exiting.\n");
    149 #endif
     149#endif /* HAVE_JACK */
    150150
    151151  } else {
     
    182182{
    183183  smpl_t mpitch = floor (aubio_freqtomidi (pitch) + .5);
    184 #if HAVE_JACK
     184#ifdef HAVE_JACK
    185185  jack_midi_event_t ev;
    186186  ev.size = 3;
  • examples/utils.h

    r60fc05b rf264b17  
    1919*/
    2020
    21 #include <stdio.h>
    22 #include <stdlib.h>
    23 #include <stdarg.h>
    24 #include <getopt.h>
    25 #include <unistd.h>
    26 #include <math.h>               /* for isfinite */
    27 #include <string.h>             /* for strcmp */
    2821#include <aubio.h>
     22
    2923#include "config.h"
     24
     25#ifdef HAVE_STDIO_H
     26#include <stdio.h>              // for fprintf
     27#endif
     28#ifdef HAVE_STDLIB_H
     29#include <stdlib.h>             // for exit
     30#endif
     31#ifdef HAVE_UNISTD_H
     32#include <unistd.h>             // for access
     33#elif defined(HAVE_WIN_HACKS)
     34#include <io.h>
     35#define access _access
     36#define F_OK   0
     37#endif
     38#ifdef HAVE_MATH_H
     39#include <math.h>               // for isfinite
     40#endif
     41#ifdef HAVE_STRING_H
     42#include <string.h>             // for strcmp
     43#endif
    3044
    3145#ifdef HAVE_C99_VARARGS_MACROS
  • examples/wscript_build

    r60fc05b rf264b17  
    11# vim:set syntax=python:
    22
    3 uselib = []
    4 uselib += ['FFTW3', 'FFTW3F']
    5 uselib += ['SAMPLERATE']
    6 uselib += ['SNDFILE']
    7 uselib += ['AVCODEC']
    8 uselib += ['AVFORMAT']
    9 uselib += ['AVRESAMPLE']
    10 uselib += ['AVUTIL']
     3uselib = ['aubio']
    114uselib += ['JACK']
    125
     6includes = ['../src']
    137utils_source = ['utils.c', 'jackio.c']
    148programs_source = ctx.path.ant_glob('*.c', excl = utils_source)
     
    1711bld(features = 'c',
    1812        source = utils_source,
    19         includes = ['../src'],
    20         uselib = uselib,
     13        includes = includes,
     14        use = uselib,
    2115        target = 'utilsio')
    2216
     
    2418for source_file in programs_source:
    2519    bld(features = 'c cprogram',
    26             includes = '../src',
    27             lib = 'm',
    28             use = ['aubio', 'utilsio'],
    29             uselib = uselib,
    3020            source = source_file,
    31             target = str(source_file).split('.')[0]
    32             )
     21            target = str(source_file).split('.')[0],
     22            includes = includes,
     23            use = uselib + ['utilsio'],
     24       )
  • python/README

    r60fc05b rf264b17  
    4646    $ export PYTHONPATH=$PYTHONPATH:$PWD/`ls -rtd build/lib.* | head -1`:$PWD/tests
    4747
    48 Similarly, you can use the aubio module without installing libaubio by pointing
    49 LD_LIBRARY_PATH to the path libaubio can be found at:
    50 
    51     $ export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:PWD/../build/src
    52 
    53 Or on Mac OS X systems, setting DYLD_LIBRARY_PATH:
    54 
    55     $ export DYLD_LIBRARY_PATH=$DYLD_LIBRARY_PATH:$PWD/../build/src
    56 
    5748Testing the Python module
    5849-------------------------
  • python/demos/demo_bpm_extract.py

    r60fc05b rf264b17  
    44from numpy import median, diff
    55
    6 def get_file_bpm(path, params = {}):
     6def get_file_bpm(path, params = None):
    77    """ Calculate the beats per minute (bpm) of a given file.
    88        path: path to the file
    99        param: dictionary of parameters
    1010    """
     11    if params is None:
     12        params = {}
    1113    try:
    1214        win_s = params['win_s']
    1315        samplerate = params['samplerate']
    1416        hop_s = params['hop_s']
    15     except:
     17    except KeyError:
    1618        """
    1719        # super fast
     
    4446
    4547    # Convert to periods and to bpm
    46     bpms = 60./diff(beats)
    47     b = median(bpms)
     48    if len(beats) > 1:
     49        if len(beats) < 4:
     50            print("few beats found in {:s}".format(path))
     51        bpms = 60./diff(beats)
     52        b = median(bpms)
     53    else:
     54        b = 0
     55        print("not enough beats found in {:s}".format(path))
    4856    return b
    4957
     
    5260    for f in sys.argv[1:]:
    5361        bpm = get_file_bpm(f)
    54         print "%6s" % ("%.2f" % bpm), f
     62        print("{:6s} {:s}".format("{:2f}".format(bpm), f))
  • python/demos/demo_filterbank.py

    r60fc05b rf264b17  
    22
    33from aubio import filterbank, fvec
    4 from pylab import loglog, show, subplot, xlim, ylim, xlabel, ylabel, title
     4from pylab import loglog, show, xlim, ylim, xlabel, ylabel, title
    55from numpy import vstack, arange
    66
     
    2020f.set_coeffs(coeffs)
    2121
    22 times = vstack([arange(win_s / 2 + 1) * samplerate / win_s] * n_filters)
     22times = vstack([arange(win_s // 2 + 1) * samplerate / win_s] * n_filters)
    2323title('Bank of filters built using a simple list of boundaries\nThe middle band has been amplified by 2.')
    2424loglog(times.T, f.get_coeffs().T, '.-')
  • python/demos/demo_filterbank_slaney.py

    r60fc05b rf264b17  
    22
    33from aubio import filterbank
    4 from numpy import array, arange, vstack
     4from numpy import arange, vstack
    55
    66win_s = 8192
     
    1212from pylab import loglog, title, show, xlim, ylim, xlabel, ylabel
    1313xlim([0,samplerate / 2])
    14 times = vstack([arange(win_s / 2 + 1) * samplerate / win_s] * 40)
     14times = vstack([arange(win_s // 2 + 1) * samplerate / win_s] * 40)
    1515loglog(times.T, f.get_coeffs().T, '.-')
    1616title('Mel frequency bands coefficients')
  • python/demos/demo_filterbank_triangle_bands.py

    r60fc05b rf264b17  
    1717subplot(211)
    1818title('Examples of filterbank built with set_triangle_bands and set_coeffs')
    19 times = vstack([arange(win_s / 2 + 1) * samplerate / win_s] * n_filters)
     19times = vstack([arange(win_s // 2 + 1) * samplerate / win_s] * n_filters)
    2020loglog(times.T, f.get_coeffs().T, '.-')
    2121xlim([50, samplerate/2])
     
    3838
    3939subplot(212)
    40 times = vstack([arange(win_s / 2 + 1) * samplerate / win_s] * n_filters)
     40times = vstack([arange(win_s // 2 + 1) * samplerate / win_s] * n_filters)
    4141loglog(times.T, f.get_coeffs().T, '.-')
    4242xlim([50, samplerate/2])
  • python/demos/demo_keyboard.py

    r60fc05b rf264b17  
    2626
    2727def create_keyboard_patches(firstnote, lastnote, ax = None):
    28     import numpy as np
    2928    import matplotlib.pyplot as plt
    3029    from matplotlib.path import Path
  • python/demos/demo_mel-energy.py

    r60fc05b rf264b17  
    22
    33import sys
    4 from aubio import fvec, source, pvoc, filterbank
     4from aubio import source, pvoc, filterbank
    55from numpy import vstack, zeros
    66
    77win_s = 512                 # fft size
    8 hop_s = win_s / 4           # hop size
     8hop_s = win_s // 4          # hop size
    99
    1010if len(sys.argv) < 2:
    11     print "Usage: %s <filename> [samplerate]" % sys.argv[0]
     11    print("Usage: %s <filename> [samplerate]" % sys.argv[0])
    1212    sys.exit(1)
    1313
     
    3535    fftgrain = pv(samples)
    3636    new_energies = f(fftgrain)
    37     print '%f' % (total_frames / float(samplerate) ),
    38     print ' '.join(['%f' % b for b in new_energies])
     37    timestr = '%f' % (total_frames / float(samplerate) )
     38    print('{:s} {:s}'.format(timestr, ' '.join(['%f' % b for b in new_energies])))
    3939    energies = vstack( [energies, new_energies] )
    4040    total_frames += read
     
    4242
    4343if 1:
    44     print "done computing, now plotting"
     44    print("done computing, now plotting")
    4545    import matplotlib.pyplot as plt
    4646    from demo_waveform_plot import get_waveform_plot
  • python/demos/demo_mfcc.py

    r60fc05b rf264b17  
    33import sys
    44from aubio import source, pvoc, mfcc
    5 from numpy import array, vstack, zeros
     5from numpy import vstack, zeros
    66
    77win_s = 512                 # fft size
    8 hop_s = win_s / 4           # hop size
     8hop_s = win_s // 4          # hop size
    99n_filters = 40              # must be 40 for mfcc
    1010n_coeffs = 13
     
    1212
    1313if len(sys.argv) < 2:
    14     print "Usage: %s <source_filename>" % sys.argv[0]
     14    print("Usage: %s <source_filename>" % sys.argv[0])
    1515    sys.exit(1)
    1616
  • python/demos/demo_onset.py

    r60fc05b rf264b17  
    55
    66win_s = 512                 # fft size
    7 hop_s = win_s / 2           # hop size
     7hop_s = win_s // 2          # hop size
    88
    99if len(sys.argv) < 2:
    10     print "Usage: %s <filename> [samplerate]" % sys.argv[0]
     10    print("Usage: %s <filename> [samplerate]" % sys.argv[0])
    1111    sys.exit(1)
    1212
     
    2929    samples, read = s()
    3030    if o(samples):
    31         print "%f" % o.get_last_s()
     31        print("%f" % o.get_last_s())
    3232        onsets.append(o.get_last())
    3333    total_frames += read
  • python/demos/demo_onset_plot.py

    r60fc05b rf264b17  
    33import sys
    44from aubio import onset, source
    5 from numpy import array, hstack, zeros
     5from numpy import hstack, zeros
    66
    77win_s = 512                 # fft size
    8 hop_s = win_s / 2           # hop size
     8hop_s = win_s // 2          # hop size
    99
    1010if len(sys.argv) < 2:
    11     print "Usage: %s <filename> [samplerate]" % sys.argv[0]
     11    print("Usage: %s <filename> [samplerate]" % sys.argv[0])
    1212    sys.exit(1)
    1313
     
    3535    samples, read = s()
    3636    if o(samples):
    37         print "%f" % (o.get_last_s())
     37        print("%f" % (o.get_last_s()))
    3838        onsets.append(o.get_last())
    3939    # keep some data to plot it later
    40     new_maxes = (abs(samples.reshape(hop_s/downsample, downsample))).max(axis=0)
     40    new_maxes = (abs(samples.reshape(hop_s//downsample, downsample))).max(axis=0)
    4141    allsamples_max = hstack([allsamples_max, new_maxes])
    4242    desc.append(o.get_descriptor())
     
    4747if 1:
    4848    # do plotting
    49     from numpy import arange
    5049    import matplotlib.pyplot as plt
    5150    allsamples_max = (allsamples_max > 0) * allsamples_max
     
    6362    plt1.yaxis.set_visible(False)
    6463    desc_times = [ float(t) * hop_s / samplerate for t in range(len(desc)) ]
    65     desc_plot = [d / max(desc) for d in desc]
     64    desc_max = max(desc) if max(desc) != 0 else 1.
     65    desc_plot = [d / desc_max for d in desc]
    6666    plt2.plot(desc_times, desc_plot, '-g')
    67     tdesc_plot = [d / max(desc) for d in tdesc]
     67    tdesc_plot = [d / desc_max for d in tdesc]
    6868    for stamp in onsets:
    6969        stamp /= float(samplerate)
  • python/demos/demo_pitch.py

    r60fc05b rf264b17  
    22
    33import sys
    4 from aubio import source, pitch, freqtomidi
     4from aubio import source, pitch
    55
    66if len(sys.argv) < 2:
    7     print "Usage: %s <filename> [samplerate]" % sys.argv[0]
     7    print("Usage: %s <filename> [samplerate]" % sys.argv[0])
    88    sys.exit(1)
    99
     
    1111
    1212downsample = 1
    13 samplerate = 44100 / downsample
     13samplerate = 44100 // downsample
    1414if len( sys.argv ) > 2: samplerate = int(sys.argv[2])
    1515
    16 win_s = 4096 / downsample # fft size
    17 hop_s = 512  / downsample # hop size
     16win_s = 4096 // downsample # fft size
     17hop_s = 512  // downsample # hop size
    1818
    1919s = source(filename, samplerate, hop_s)
     
    3737    confidence = pitch_o.get_confidence()
    3838    #if confidence < 0.8: pitch = 0.
    39     #print "%f %f %f" % (total_frames / float(samplerate), pitch, confidence)
     39    print("%f %f %f" % (total_frames / float(samplerate), pitch, confidence))
    4040    pitches += [pitch]
    4141    confidences += [confidence]
     
    4646
    4747#print pitches
     48import os.path
    4849from numpy import array, ma
    4950import matplotlib.pyplot as plt
     
    6465
    6566def array_from_text_file(filename, dtype = 'float'):
    66     import os.path
    67     from numpy import array
    6867    filename = os.path.join(os.path.dirname(__file__), filename)
    6968    return array([line.split() for line in open(filename).readlines()],
     
    7170
    7271ax2 = fig.add_subplot(312, sharex = ax1)
    73 import sys, os.path
    7472ground_truth = os.path.splitext(filename)[0] + '.f0.Corrected'
    7573if os.path.isfile(ground_truth):
  • python/demos/demo_pitch_sinusoid.py

    r60fc05b rf264b17  
    11#! /usr/bin/env python
    22
    3 from numpy import random, sin, arange, ones, zeros
    4 from math import pi
    5 from aubio import fvec, pitch
     3import numpy as np
     4import aubio
    65
    76def build_sinusoid(length, freqs, samplerate):
    8   return sin( 2. * pi * arange(length) * freqs / samplerate)
     7    return np.sin( 2. * np.pi * np.arange(length) * freqs / samplerate).astype(aubio.float_type)
    98
    109def run_pitch(p, input_vec):
    11   f = fvec (p.hop_size)
    12   cands = []
    13   count = 0
    14   for vec_slice in input_vec.reshape((-1, p.hop_size)):
    15     f[:] = vec_slice
    16     cands.append(p(f))
    17   return cands
     10    cands = []
     11    for vec_slice in input_vec.reshape((-1, p.hop_size)):
     12        a = p(vec_slice)[0]
     13        cands.append(a)
     14    return cands
    1815
    1916methods = ['default', 'schmitt', 'fcomb', 'mcomb', 'yin', 'yinfft']
     
    2421samplerate = 44100
    2522sin_length = (samplerate * 10) % 512 * 512
    26 freqs = zeros(sin_length)
     23freqs = np.zeros(sin_length)
    2724
    28 partition = sin_length / 8
     25partition = sin_length // 8
    2926pointer = 0
    3027
     
    4138pointer += partition
    4239pointer += partition
    43 freqs[ pointer : pointer + partition ] = 400 + 5 * random.random(sin_length/8)
     40freqs[ pointer : pointer + partition ] = 400 + 5 * np.random.random(sin_length/8)
    4441
    4542a = build_sinusoid(sin_length, freqs, samplerate)
    4643
    4744for method in methods:
    48   p = pitch(method, buf_size, hop_size, samplerate)
    49   cands[method] = run_pitch(p, a)
     45    p = aubio.pitch(method, buf_size, hop_size, samplerate)
     46    cands[method] = run_pitch(p, a)
     47    print(method)
     48    print(cands[method])
    5049
    51 print "done computing"
     50print("done computing")
    5251
    5352if 1:
    54   from pylab import plot, show, xlabel, ylabel, legend, ylim
    55   ramp = arange(0, sin_length / hop_size).astype('float') * hop_size / samplerate
    56   for method in methods:
    57     plot(ramp, cands[method],'.-')
     53    import matplotlib.pyplot as plt
    5854
    59   # plot ground truth
    60   ramp = arange(0, sin_length).astype('float') / samplerate
    61   plot(ramp, freqs, ':')
     55    # times
     56    ramp = np.arange(0, sin_length / hop_size).astype('float') * hop_size / samplerate
    6257
    63   legend(methods+['ground truth'], 'upper right')
    64   xlabel('time (s)')
    65   ylabel('frequency (Hz)')
    66   ylim([0,2000])
    67   show()
     58    # plot each result
     59    for method in methods:
     60        plt.plot(ramp, cands[method], '.-', label=method)
    6861
     62    # plot ground truth
     63    ramp = np.arange(0, sin_length).astype('float') / samplerate
     64    plt.plot(ramp, freqs, ':', label = 'ground truth')
     65
     66    plt.legend(loc='upper left')
     67
     68    plt.xlabel('time (s)')
     69    plt.ylabel('frequency (Hz)')
     70    plt.ylim([0,2000])
     71    plt.show()
  • python/demos/demo_pysoundcard_play.py

    r60fc05b rf264b17  
    1111    samplerate = f.samplerate
    1212
    13     s = Stream(sample_rate = samplerate, block_length = hop_size)
     13    s = Stream(samplerate = samplerate, blocksize = hop_size)
    1414    s.start()
    1515    read = 0
  • python/demos/demo_pysoundcard_record.py

    r60fc05b rf264b17  
    99    hop_size = 256
    1010    duration = 5 # in seconds
    11     s = Stream(block_length = hop_size)
    12     g = sink(sink_path, samplerate = s.sample_rate)
     11    s = Stream(blocksize = hop_size, channels = 1)
     12    g = sink(sink_path, samplerate = int(s.samplerate))
    1313
    1414    s.start()
    1515    total_frames = 0
    16     while total_frames < duration * s.sample_rate:
    17         vec = s.read(hop_size)
    18         # mix down to mono
    19         mono_vec = vec.sum(-1) / float(s.input_channels)
    20         g(mono_vec, hop_size)
    21         total_frames += hop_size
     16    try:
     17        while total_frames < duration * s.samplerate:
     18            vec = s.read(hop_size)
     19            # mix down to mono
     20            mono_vec = vec.sum(-1) / float(s.channels[0])
     21            g(mono_vec, hop_size)
     22            total_frames += hop_size
     23    except KeyboardInterrupt:
     24        duration = total_frames / float(s.samplerate)
     25        print("stopped after %.2f seconds" % duration)
    2226    s.stop()
    2327
  • python/demos/demo_simple_robot_voice.py

    r60fc05b rf264b17  
    55
    66if __name__ == '__main__':
    7   if len(sys.argv) < 2:
    8     print 'usage: %s <inputfile> <outputfile>' % sys.argv[0]
    9     sys.exit(1)
    10   samplerate = 44100
    11   f = source(sys.argv[1], samplerate, 256)
    12   g = sink(sys.argv[2], samplerate)
    13   total_frames, read = 0, 256
     7    if len(sys.argv) < 2:
     8        print('usage: %s <inputfile> <outputfile>' % sys.argv[0])
     9        sys.exit(1)
     10    samplerate = 44100
     11    f = source(sys.argv[1], samplerate, 256)
     12    g = sink(sys.argv[2], samplerate)
     13    total_frames, read = 0, 256
    1414
    15   win_s = 512                 # fft size
    16   hop_s = win_s / 2           # hop size
    17   pv = pvoc(win_s, hop_s)                            # phase vocoder
     15    win_s = 512                          # fft size
     16    hop_s = win_s // 2                   # hop size
     17    pv = pvoc(win_s, hop_s)              # phase vocoder
    1818
    19   while read:
    20     samples, read = f()
    21     spectrum = pv(samples)            # compute spectrum
    22     #spectrum.norm *= .8               # reduce amplitude a bit
    23     spectrum.phas[:] = 0.             # zero phase
    24     new_samples = pv.rdo(spectrum)    # compute modified samples
    25     g(new_samples, read)              # write to output
    26     total_frames += read
     19    while read:
     20        samples, read = f()
     21        spectrum = pv(samples)           # compute spectrum
     22        #spectrum.norm *= .8             # reduce amplitude a bit
     23        spectrum.phas[:] = 0.            # zero phase
     24        new_samples = pv.rdo(spectrum)   # compute modified samples
     25        g(new_samples, read)             # write to output
     26        total_frames += read
    2727
    28   print "wrote", total_frames, "from", f.uri, "to", g.uri
    29 
    30  
     28    format_str = "read {:d} samples from {:s}, written to {:s}"
     29    print(format_str.format(total_frames, f.uri, g.uri))
  • python/demos/demo_simple_spectral_weighting.py

    r60fc05b rf264b17  
    1414if __name__ == '__main__':
    1515    if len(sys.argv) < 2:
    16         print 'usage: %s <inputfile> <outputfile>' % sys.argv[0]
     16        print('usage: %s <inputfile> <outputfile>' % sys.argv[0])
    1717        sys.exit(1)
    1818    samplerate = 0
     
    2323
    2424    win_s = 512 # fft size
    25     hop_s = win_s / 2 # hop size
     25    hop_s = win_s // 2 # hop size
    2626    pv = pvoc(win_s, hop_s) # phase vocoder
    2727
     
    3131        zeros( 50 ),
    3232        1.3 * hanningz(100),
    33         zeros (win_s / 2 + 1 - 40 - 50 - 100),
     33        zeros (win_s // 2 + 1 - 40 - 50 - 100),
    3434        ] )
    3535
     
    5353        total_frames += read
    5454
    55     print "read", total_frames / float(samplerate), "seconds from", f.uri
     55    duration = total_frames / float(samplerate)
     56    print("read {:.3f}s from {:s}".format(duration, f.uri))
  • python/demos/demo_sink.py

    r60fc05b rf264b17  
    66if __name__ == '__main__':
    77    if len(sys.argv) < 3:
    8         print 'usage: %s <inputfile> <outputfile> [samplerate] [hop_size]' % sys.argv[0]
     8        print('usage: %s <inputfile> <outputfile> [samplerate] [hop_size]' % sys.argv[0])
    99        sys.exit(1)
    1010
     
    2323        g(vec, read)
    2424        total_frames += read
    25     print "wrote", "%.2fs" % (total_frames / float(samplerate) ),
    26     print "(", total_frames, "frames", "in",
    27     print total_frames / f.hop_size, "blocks", "at", "%dHz" % f.samplerate, ")",
    28     print "from", f.uri,
    29     print "to", g.uri
     25    outstr = "wrote %.2fs" % (total_frames / float(samplerate))
     26    outstr += " (%d frames in" % total_frames
     27    outstr += " %d blocks" % (total_frames // f.hop_size)
     28    outstr += " at %dHz)" % f.samplerate
     29    outstr += " from " + f.uri
     30    outstr += " to " + g.uri
     31    print(outstr)
  • python/demos/demo_sink_create_woodblock.py

    r60fc05b rf264b17  
    33import sys
    44from math import pi, e
    5 from aubio import sink
    6 from numpy import arange, resize, sin, exp, zeros
     5from aubio import sink, float_type
     6from numpy import arange, sin, exp, zeros
    77
    88if len(sys.argv) < 2:
    9     print 'usage: %s <outputfile> [samplerate]' % sys.argv[0]
     9    print('usage: %s <outputfile> [samplerate]' % sys.argv[0])
    1010    sys.exit(1)
    1111
     
    2626# create a sine lookup table
    2727tablelen = 1000
    28 sinetable = arange(tablelen + 1, dtype = 'float32')
     28sinetable = arange(tablelen + 1, dtype = float_type)
    2929sinetable = 0.7 * sin(twopi * sinetable/tablelen)
    30 sinetone = zeros((duration,), dtype = 'float32')
     30sinetone = zeros((duration,), dtype = float_type)
    3131
    3232# compute sinetone at floating point period
     
    4040
    4141# apply some envelope
    42 float_ramp = arange(duration, dtype = 'float32')
     42float_ramp = arange(duration, dtype = float_type)
    4343sinetone *= exp( - e * float_ramp / duration / decay)
    4444sinetone[:attack] *= exp( e * ( float_ramp[:attack] / attack - 1 ) )
  • python/demos/demo_sink_multi.py

    r60fc05b rf264b17  
    66if __name__ == '__main__':
    77    if len(sys.argv) < 3:
    8         print 'usage: %s <inputfile> <outputfile> [samplerate] [hop_size]' % sys.argv[0]
     8        print('usage: %s <inputfile> <outputfile> [samplerate] [hop_size]' % sys.argv[0])
    99        sys.exit(1)
    1010
     
    2323        g.do_multi(vec, read)
    2424        total_frames += read
    25     print "wrote", "%.2fs" % (total_frames / float(samplerate) ),
    26     print "(", total_frames, "frames", "in",
    27     print total_frames / f.hop_size, "blocks",
    28     print "of", f.channels, "channels",
    29     print "at", "%dHz" % f.samplerate, ")",
    30     print "from", f.uri,
    31     print "to", g.uri
     25    outstr = "wrote %.2fs" % (total_frames / float(samplerate))
     26    outstr += " (%d frames in" % total_frames
     27    outstr += " %d blocks" % (total_frames // f.hop_size)
     28    outstr += " of %d channels" % f.channels
     29    outstr += " at %dHz)" % f.samplerate
     30    outstr += " from " + f.uri
     31    outstr += " to " + g.uri
     32    print(outstr)
  • python/demos/demo_slicing.py

    r60fc05b rf264b17  
    77if __name__ == '__main__':
    88    if len(sys.argv) < 3:
    9         print 'usage: %s <inputfile> <duration>' % sys.argv[0]
     9        print('usage: %s <inputfile> <duration>' % sys.argv[0])
    1010        sys.exit(1)
    1111    source_file = sys.argv[1]
     
    4545    total_duration = total_frames_written / float(samplerate)
    4646    slice_n += 1
    47     print 'created %(slice_n)s slices from %(source_base_name)s%(source_ext)s' % locals(),
    48     print ' (total duration %(total_duration).2fs)' % locals()
     47    outstr = 'created %(slice_n)s slices from %(source_base_name)s%(source_ext)s' % locals()
     48    outstr += ' (total duration %(total_duration).2fs)' % locals()
     49    print(outstr)
    4950    # close source and sink files
    5051    del f, g
  • python/demos/demo_source.py

    r60fc05b rf264b17  
    66if __name__ == '__main__':
    77    if len(sys.argv) < 2:
    8         print 'usage: %s <inputfile> [samplerate] [hop_size]' % sys.argv[0]
     8        print('usage: %s <inputfile> [samplerate] [hop_size]' % sys.argv[0])
    99        sys.exit(1)
    1010    samplerate = 0
     
    2121        total_frames += read
    2222        if read < f.hop_size: break
    23     print "read", "%.2fs" % (total_frames / float(samplerate) ),
    24     print "(", total_frames, "frames", "in",
    25     print total_frames / f.hop_size, "blocks", "at", "%dHz" % f.samplerate, ")",
    26     print "from", f.uri
     23    outstr = "read %.2fs" % (total_frames / float(samplerate))
     24    outstr += " (%d frames in" % total_frames
     25    outstr += " %d blocks" % (total_frames // f.hop_size)
     26    outstr += " at %dHz)" % f.samplerate
     27    outstr += " from " + f.uri
     28    print(outstr)
  • python/demos/demo_specdesc.py

    r60fc05b rf264b17  
    22
    33import sys
    4 from aubio import fvec, source, pvoc, specdesc
    5 from numpy import hstack
     4import numpy as np
     5from aubio import source, pvoc, specdesc
    66
    77win_s = 512                 # fft size
    8 hop_s = win_s / 4           # hop size
     8hop_s = win_s // 4          # hop size
    99
    1010if len(sys.argv) < 2:
    11     print "Usage: %s <filename> [samplerate]" % sys.argv[0]
     11    print("Usage: %s <filename> [samplerate]" % sys.argv[0])
    1212    sys.exit(1)
    1313
     
    3131for method in methods:
    3232    cands = []
    33     all_descs[method] = fvec(0)
     33    all_descs[method] = np.array([])
    3434    o[method] = specdesc(method, win_s)
    3535
     
    4040    samples, read = s()
    4141    fftgrain = pv(samples)
    42     #print "%f" % ( total_frames / float(samplerate) ),
     42    #outstr = "%f" % ( total_frames / float(samplerate) )
    4343    for method in methods:
    4444        specdesc_val = o[method](fftgrain)[0]
    45         all_descs[method] = hstack ( [all_descs[method], specdesc_val] )
    46         #print "%f" % specdesc_val,
    47     #print
     45        all_descs[method] = np.append(all_descs[method], specdesc_val)
     46        #outstr += " %f" % specdesc_val
     47    #print(outstr)
    4848    total_frames += read
    4949    if read < hop_s: break
    5050
    5151if 1:
    52     print "done computing, now plotting"
     52    print("done computing, now plotting")
    5353    import matplotlib.pyplot as plt
    5454    from demo_waveform_plot import get_waveform_plot
  • python/demos/demo_spectrogram.py

    r60fc05b rf264b17  
    11#! /usr/bin/env python
    22
    3 import sys
    4 from aubio import pvoc, source
    5 from numpy import array, arange, zeros, shape, log10, vstack
    6 from pylab import imshow, show, cm, axis, ylabel, xlabel, xticks, yticks
     3import sys, os.path
     4from aubio import pvoc, source, float_type
     5from numpy import zeros, log10, vstack
     6import matplotlib.pyplot as plt
    77
    88def get_spectrogram(filename, samplerate = 0):
    9   win_s = 512                                        # fft window size
    10   hop_s = win_s / 2                                  # hop size
    11   fft_s = win_s / 2 + 1                              # spectrum bins
     9    win_s = 512                                        # fft window size
     10    hop_s = win_s // 2                                 # hop size
     11    fft_s = win_s // 2 + 1                             # spectrum bins
    1212
    13   a = source(filename, samplerate, hop_s)            # source file
    14   if samplerate == 0: samplerate = a.samplerate
    15   pv = pvoc(win_s, hop_s)                            # phase vocoder
    16   specgram = zeros([0, fft_s], dtype='float32')      # numpy array to store spectrogram
     13    a = source(filename, samplerate, hop_s)            # source file
     14    if samplerate == 0: samplerate = a.samplerate
     15    pv = pvoc(win_s, hop_s)                            # phase vocoder
     16    specgram = zeros([0, fft_s], dtype=float_type)     # numpy array to store spectrogram
    1717
    18   # analysis
    19   while True:
    20     samples, read = a()                              # read file
    21     specgram = vstack((specgram,pv(samples).norm))   # store new norm vector
    22     if read < a.hop_size: break
     18    # analysis
     19    while True:
     20        samples, read = a()                              # read file
     21        specgram = vstack((specgram,pv(samples).norm))   # store new norm vector
     22        if read < a.hop_size: break
    2323
    24   # plotting
    25   imshow(log10(specgram.T + .001), origin = 'bottom', aspect = 'auto', cmap=cm.gray_r)
    26   axis([0, len(specgram), 0, len(specgram[0])])
    27   # show axes in Hz and seconds
    28   time_step = hop_s / float(samplerate)
    29   total_time = len(specgram) * time_step
    30   print "total time: %0.2fs" % total_time,
    31   print ", samplerate: %.2fkHz" % (samplerate / 1000.)
    32   n_xticks = 10
    33   n_yticks = 10
     24    # plotting
     25    fig = plt.imshow(log10(specgram.T + .001), origin = 'bottom', aspect = 'auto', cmap=plt.cm.gray_r)
     26    ax = fig.axes
     27    ax.axis([0, len(specgram), 0, len(specgram[0])])
     28    # show axes in Hz and seconds
     29    time_step = hop_s / float(samplerate)
     30    total_time = len(specgram) * time_step
     31    outstr = "total time: %0.2fs" % total_time
     32    print(outstr + ", samplerate: %.2fkHz" % (samplerate / 1000.))
     33    n_xticks = 10
     34    n_yticks = 10
    3435
    35   def get_rounded_ticks( top_pos, step, n_ticks ):
    36       top_label = top_pos * step
    37       # get the first label
    38       ticks_first_label = top_pos * step / n_ticks
    39       # round to the closest .1
    40       ticks_first_label = round ( ticks_first_label * 10. ) / 10.
    41       # compute all labels from the first rounded one
    42       ticks_labels = [ ticks_first_label * n for n in range(n_ticks) ] + [ top_label ]
    43       # get the corresponding positions
    44       ticks_positions = [ ticks_labels[n] / step for n in range(n_ticks) ] + [ top_pos ]
    45       # convert to string
    46       ticks_labels = [  "%.1f" % x for x in ticks_labels ]
    47       # return position, label tuple to use with x/yticks
    48       return ticks_positions, ticks_labels
    49 
    50   # apply to the axis
    51   xticks( *get_rounded_ticks ( len(specgram), time_step, n_xticks ) )
    52   yticks( *get_rounded_ticks ( len(specgram[0]), (samplerate / 2. / 1000.) / len(specgram[0]), n_yticks ) )
    53   ylabel('Frequency (kHz)')
    54   xlabel('Time (s)')
     36    def get_rounded_ticks( top_pos, step, n_ticks ):
     37        top_label = top_pos * step
     38        # get the first label
     39        ticks_first_label = top_pos * step / n_ticks
     40        # round to the closest .1
     41        ticks_first_label = round ( ticks_first_label * 10. ) / 10.
     42        # compute all labels from the first rounded one
     43        ticks_labels = [ ticks_first_label * n for n in range(n_ticks) ] + [ top_label ]
     44        # get the corresponding positions
     45        ticks_positions = [ ticks_labels[n] / step for n in range(n_ticks) ] + [ top_pos ]
     46        # convert to string
     47        ticks_labels = [  "%.1f" % x for x in ticks_labels ]
     48        # return position, label tuple to use with x/yticks
     49        return ticks_positions, ticks_labels
     50 
     51    # apply to the axis
     52    x_ticks, x_labels = get_rounded_ticks ( len(specgram), time_step, n_xticks )
     53    y_ticks, y_labels = get_rounded_ticks ( len(specgram[0]), (samplerate / 1000. / 2.) / len(specgram[0]), n_yticks )
     54    ax.set_xticks( x_ticks )
     55    ax.set_yticks ( y_ticks )
     56    ax.set_xticklabels( x_labels )
     57    ax.set_yticklabels ( y_labels )
     58    ax.set_ylabel('Frequency (kHz)')
     59    ax.set_xlabel('Time (s)')
     60    ax.set_title(os.path.basename(filename))
     61    for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] +
     62            ax.get_xticklabels() + ax.get_yticklabels()):
     63        item.set_fontsize('x-small')
     64    return fig
    5565
    5666if __name__ == '__main__':
    57   if len(sys.argv) < 2:
    58     print "Usage: %s <filename>" % sys.argv[0]
    59   else:
    60     for soundfile in sys.argv[1:]:
    61       get_spectrogram(soundfile)
    62       # display graph
    63       show()
     67    if len(sys.argv) < 2:
     68        print("Usage: %s <filename>" % sys.argv[0])
     69    else:
     70        for soundfile in sys.argv[1:]:
     71            fig = get_spectrogram(soundfile)
     72            # display graph
     73            plt.show()
     74            #outimage = os.path.basename(soundfile) + '.png'
     75            #print ("writing: " + outimage)
     76            #plt.savefig(outimage)
     77            plt.close()
  • python/demos/demo_tempo.py

    r60fc05b rf264b17  
    55
    66win_s = 512                 # fft size
    7 hop_s = win_s / 2           # hop size
     7hop_s = win_s // 2          # hop size
    88
    99if len(sys.argv) < 2:
    10     print "Usage: %s <filename> [samplerate]" % sys.argv[0]
     10    print("Usage: %s <filename> [samplerate]" % sys.argv[0])
    1111    sys.exit(1)
    1212
     
    3434    if is_beat:
    3535        this_beat = int(total_frames - delay + is_beat[0] * hop_s)
    36         print "%f" % (this_beat / float(samplerate))
     36        print("%f" % (this_beat / float(samplerate)))
    3737        beats.append(this_beat)
    3838    total_frames += read
  • python/demos/demo_tempo_plot.py

    r60fc05b rf264b17  
    55
    66win_s = 512                 # fft size
    7 hop_s = win_s / 2           # hop size
     7hop_s = win_s // 2          # hop size
    88
    99if len(sys.argv) < 2:
    10     print "Usage: %s <filename> [samplerate]" % sys.argv[0]
     10    print("Usage: %s <filename> [samplerate]" % sys.argv[0])
    1111    sys.exit(1)
    1212
     
    4040if len(beats) > 1:
    4141    # do plotting
    42     from numpy import array, arange, mean, median, diff
     42    from numpy import mean, median, diff
    4343    import matplotlib.pyplot as plt
    4444    bpms = 60./ diff(beats)
    45     print 'mean period:', "%.2f" % mean(bpms), 'bpm', 'median', "%.2f" % median(bpms), 'bpm'
    46     print 'plotting', filename
     45    print('mean period: %.2fbpm, median: %.2fbpm' % (mean(bpms), median(bpms)))
     46    print('plotting %s' % filename)
    4747    plt1 = plt.axes([0.1, 0.75, 0.8, 0.19])
    4848    plt2 = plt.axes([0.1, 0.1, 0.8, 0.65], sharex = plt1)
     
    7676
    7777else:
    78     print 'mean period:', "%.2f" % 0, 'bpm', 'median', "%.2f" % 0, 'bpm',
    79     print 'nothing to plot, file too short?'
     78    print('mean period: %.2fbpm, median: %.2fbpm' % (0, 0))
     79    print('plotting %s' % filename)
  • python/demos/demo_tss.py

    r60fc05b rf264b17  
    55
    66if __name__ == '__main__':
    7   if len(sys.argv) < 2:
    8     print 'usage: %s <inputfile> <outputfile_transient> <outputfile_steady>' % sys.argv[0]
    9     sys.exit(1)
     7    if len(sys.argv) < 2:
     8        print('usage: %s <inputfile> <outputfile_transient> <outputfile_steady>' % sys.argv[0])
     9        sys.exit(1)
    1010
    11   samplerate = 44100
    12   win_s = 1024      # fft size
    13   hop_s = win_s / 4 # block size
    14   threshold = 0.5
     11    samplerate = 44100
     12    win_s = 1024       # fft size
     13    hop_s = win_s // 4 # block size
     14    threshold = 0.5
    1515
    16   f = source(sys.argv[1], samplerate, hop_s)
    17   g = sink(sys.argv[2], samplerate)
    18   h = sink(sys.argv[3], samplerate)
     16    f = source(sys.argv[1], samplerate, hop_s)
     17    g = sink(sys.argv[2], samplerate)
     18    h = sink(sys.argv[3], samplerate)
    1919
    20   pva = pvoc(win_s, hop_s)    # a phase vocoder
    21   pvb = pvoc(win_s, hop_s)    # another phase vocoder
    22   t = tss(win_s, hop_s)       # transient steady state separation
     20    pva = pvoc(win_s, hop_s)    # a phase vocoder
     21    pvb = pvoc(win_s, hop_s)    # another phase vocoder
     22    t = tss(win_s, hop_s)       # transient steady state separation
    2323
    24   t.set_threshold(threshold)
     24    t.set_threshold(threshold)
    2525
    26   read = hop_s
     26    read = hop_s
    2727
    28   while read:
    29     samples, read = f()               # read file
    30     spec = pva(samples)                # compute spectrum
    31     trans_spec, stead_spec = t(spec)  # transient steady-state separation
    32     transients = pva.rdo(trans_spec)   # overlap-add synthesis of transients
    33     steadstate = pvb.rdo(stead_spec)   # overlap-add synthesis of steady states
    34     g(transients, read)               # write transients to output
    35     h(steadstate, read)               # write steady states to output
     28    while read:
     29        samples, read = f()               # read file
     30        spec = pva(samples)               # compute spectrum
     31        trans_spec, stead_spec = t(spec)  # transient steady-state separation
     32        transients = pva.rdo(trans_spec)  # overlap-add synthesis of transients
     33        steadstate = pvb.rdo(stead_spec)  # overlap-add synthesis of steady states
     34        g(transients, read)               # write transients to output
     35        h(steadstate, read)               # write steady states to output
    3636
    37   del f, g, h                         # finish writing the files now
     37    del f, g, h                           # finish writing the files now
    3838
    39   from demo_spectrogram import get_spectrogram
    40   from pylab import subplot, show
    41   subplot(311)
    42   get_spectrogram(sys.argv[1])
    43   subplot(312)
    44   get_spectrogram(sys.argv[2])
    45   subplot(313)
    46   get_spectrogram(sys.argv[3])
    47   show()
     39    from demo_spectrogram import get_spectrogram
     40    from pylab import subplot, show
     41    subplot(311)
     42    get_spectrogram(sys.argv[1])
     43    subplot(312)
     44    get_spectrogram(sys.argv[2])
     45    subplot(313)
     46    get_spectrogram(sys.argv[3])
     47    show()
  • python/demos/demo_waveform_plot.py

    r60fc05b rf264b17  
    22
    33import sys
    4 from aubio import pvoc, source
     4from aubio import source
    55from numpy import zeros, hstack
    66
     
    2222        samples, read = a()
    2323        # keep some data to plot it later
    24         new_maxes = (abs(samples.reshape(hop_s/downsample, downsample))).max(axis=0)
     24        new_maxes = (abs(samples.reshape(hop_s//downsample, downsample))).max(axis=0)
    2525        allsamples_max = hstack([allsamples_max, new_maxes])
    2626        total_frames += read
     
    4949    import matplotlib.pyplot as plt
    5050    if len(sys.argv) < 2:
    51         print "Usage: %s <filename>" % sys.argv[0]
     51        print("Usage: %s <filename>" % sys.argv[0])
    5252    else:
    5353        for soundfile in sys.argv[1:]:
  • python/ext/aubio-types.h

    r60fc05b rf264b17  
    11#include <Python.h>
    22#include <structmember.h>
     3
     4#include "aubio-generated.h"
    35
    46#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
     
    3436
    3537#if HAVE_AUBIO_DOUBLE
    36 #error "Ouch! Python interface for aubio has not been much tested yet."
     38// 64 bit precision with HAVE_AUBIO_DOUBLE=1
    3739#define AUBIO_NPY_SMPL NPY_DOUBLE
     40#define AUBIO_NPY_SMPL_STR "float64"
     41#define AUBIO_NPY_SMPL_CHR "d"
    3842#else
     43// default is 32 bit precision
    3944#define AUBIO_NPY_SMPL NPY_FLOAT
     45#define AUBIO_NPY_SMPL_STR "float32"
     46#define AUBIO_NPY_SMPL_CHR "f"
    4047#endif
    4148
    42 // special python type for cvec
    43 typedef struct
    44 {
    45   PyObject_HEAD
    46   cvec_t * o;
    47   uint_t length;
    48   uint_t channels;
    49 } Py_cvec;
     49// compat with Python < 2.6
     50#ifndef Py_TYPE
     51#define Py_TYPE(ob) (((PyObject*)(ob))->ob_type)
     52#endif
     53
    5054extern PyTypeObject Py_cvecType;
    5155
     56PyObject * new_py_fvec(uint_t length);
     57PyObject * new_py_cvec(uint_t length);
     58PyObject * new_py_fmat(uint_t height, uint_t length);
     59
    5260// defined in aubio-proxy.c
     61extern int PyAubio_IsValidVector (PyObject *input);
     62
    5363extern PyObject *PyAubio_CFvecToArray (fvec_t * self);
    54 extern fvec_t *PyAubio_ArrayToCFvec (PyObject * self);
     64extern int PyAubio_ArrayToCFvec (PyObject * self, fvec_t *out);
    5565
    56 extern Py_cvec *PyAubio_CCvecToPyCvec (cvec_t * self);
    57 extern cvec_t *PyAubio_ArrayToCCvec (PyObject *input);
     66extern int PyAubio_PyCvecToCCvec (PyObject *input, cvec_t *i);
    5867
    5968extern PyObject *PyAubio_CFmatToArray (fmat_t * self);
    60 extern fmat_t *PyAubio_ArrayToCFmat (PyObject *input);
     69extern int PyAubio_ArrayToCFmat (PyObject *input, fmat_t *out);
    6170
    6271// hand written wrappers
  • python/ext/aubiomodule.c

    r60fc05b rf264b17  
    11#define PY_AUBIO_MODULE_MAIN
    22#include "aubio-types.h"
    3 #include "aubio-generated.h"
    43#include "py-musicutils.h"
    54
     
    8483{
    8584  PyObject *input;
    86   fvec_t *vec;
     85  fvec_t vec;
    8786  smpl_t alpha;
    8887  PyObject *result;
    8988
    90   if (!PyArg_ParseTuple (args, "Of:alpha_norm", &input, &alpha)) {
     89  if (!PyArg_ParseTuple (args, "O" AUBIO_NPY_SMPL_CHR ":alpha_norm", &input, &alpha)) {
    9190    return NULL;
    9291  }
     
    9695  }
    9796
    98   vec = PyAubio_ArrayToCFvec (input);
    99 
    100   if (vec == NULL) {
     97  if (!PyAubio_ArrayToCFvec(input, &vec)) {
    10198    return NULL;
    10299  }
    103100
    104101  // compute the function
    105   result = Py_BuildValue ("f", fvec_alpha_norm (vec, alpha));
     102  result = Py_BuildValue (AUBIO_NPY_SMPL_CHR, fvec_alpha_norm (&vec, alpha));
    106103  if (result == NULL) {
    107104    return NULL;
     
    117114  smpl_t output;
    118115
    119   if (!PyArg_ParseTuple (args, "|fff", &input, &samplerate, &fftsize)) {
     116  if (!PyArg_ParseTuple (args, "|" AUBIO_NPY_SMPL_CHR AUBIO_NPY_SMPL_CHR AUBIO_NPY_SMPL_CHR , &input, &samplerate, &fftsize)) {
    120117    return NULL;
    121118  }
     
    132129  smpl_t output;
    133130
    134   if (!PyArg_ParseTuple (args, "|fff", &input, &samplerate, &fftsize)) {
     131  if (!PyArg_ParseTuple (args, "|" AUBIO_NPY_SMPL_CHR AUBIO_NPY_SMPL_CHR AUBIO_NPY_SMPL_CHR , &input, &samplerate, &fftsize)) {
    135132    return NULL;
    136133  }
     
    147144  smpl_t output;
    148145
    149   if (!PyArg_ParseTuple (args, "|fff", &input, &samplerate, &fftsize)) {
     146  if (!PyArg_ParseTuple (args, "|" AUBIO_NPY_SMPL_CHR AUBIO_NPY_SMPL_CHR AUBIO_NPY_SMPL_CHR, &input, &samplerate, &fftsize)) {
    150147    return NULL;
    151148  }
     
    162159  smpl_t output;
    163160
    164   if (!PyArg_ParseTuple (args, "|fff", &input, &samplerate, &fftsize)) {
     161  if (!PyArg_ParseTuple (args, "|" AUBIO_NPY_SMPL_CHR AUBIO_NPY_SMPL_CHR AUBIO_NPY_SMPL_CHR, &input, &samplerate, &fftsize)) {
    165162    return NULL;
    166163  }
     
    175172{
    176173  PyObject *input;
    177   fvec_t *vec;
     174  fvec_t vec;
    178175  PyObject *result;
    179176
     
    186183  }
    187184
    188   vec = PyAubio_ArrayToCFvec (input);
    189 
    190   if (vec == NULL) {
     185  if (!PyAubio_ArrayToCFvec(input, &vec)) {
    191186    return NULL;
    192187  }
    193188
    194189  // compute the function
    195   result = Py_BuildValue ("f", aubio_zero_crossing_rate (vec));
     190  result = Py_BuildValue (AUBIO_NPY_SMPL_CHR, aubio_zero_crossing_rate (&vec));
    196191  if (result == NULL) {
    197192    return NULL;
     
    205200{
    206201  PyObject *input;
    207   fvec_t *vec;
     202  fvec_t vec;
    208203
    209204  if (!PyArg_ParseTuple (args, "O:min_removal", &input)) {
     
    215210  }
    216211
    217   vec = PyAubio_ArrayToCFvec (input);
    218 
    219   if (vec == NULL) {
     212  if (!PyAubio_ArrayToCFvec(input, &vec)) {
    220213    return NULL;
    221214  }
    222215
    223216  // compute the function
    224   fvec_min_removal (vec);
     217  fvec_min_removal (&vec);
    225218
    226219  // since this function does not return, we could return None
    227220  //Py_RETURN_NONE;
    228221  // however it is convenient to return the modified vector
    229   return (PyObject *) PyAubio_CFvecToArray(vec);
     222  return (PyObject *) PyAubio_CFvecToArray(&vec);
    230223  // or even without converting it back to an array
    231224  //Py_INCREF(vec);
     
    246239  {"level_detection", Py_aubio_level_detection, METH_VARARGS, Py_aubio_level_detection_doc},
    247240  {"window", Py_aubio_window, METH_VARARGS, Py_aubio_window_doc},
    248   {NULL, NULL} /* Sentinel */
     241  {NULL, NULL, 0, NULL} /* Sentinel */
    249242};
    250243
    251 PyMODINIT_FUNC
    252 init_aubio (void)
    253 {
    254   PyObject *m;
     244#if PY_MAJOR_VERSION >= 3
     245// Python3 module definition
     246static struct PyModuleDef moduledef = {
     247   PyModuleDef_HEAD_INIT,
     248   "_aubio",          /* m_name */
     249   aubio_module_doc,  /* m_doc */
     250   -1,                /* m_size */
     251   aubio_methods,     /* m_methods */
     252   NULL,              /* m_reload */
     253   NULL,              /* m_traverse */
     254   NULL,              /* m_clear */
     255   NULL,              /* m_free */
     256};
     257#endif
     258
     259static PyObject *
     260initaubio (void)
     261{
     262  PyObject *m = NULL;
    255263  int err;
    256264
     
    266274      || (generated_types_ready() < 0 )
    267275  ) {
    268     return;
    269   }
    270 
     276    return m;
     277  }
     278
     279#if PY_MAJOR_VERSION >= 3
     280  m = PyModule_Create(&moduledef);
     281#else
    271282  m = Py_InitModule3 ("_aubio", aubio_methods, aubio_module_doc);
     283#endif
    272284
    273285  if (m == NULL) {
    274     return;
     286    return m;
    275287  }
    276288
     
    296308  PyModule_AddObject (m, "sink", (PyObject *) & Py_sinkType);
    297309
     310  PyModule_AddStringConstant(m, "float_type", AUBIO_NPY_SMPL_STR);
     311
    298312  // add generated objects
    299313  add_generated_objects(m);
     
    301315  // add ufunc
    302316  add_ufuncs(m);
    303 }
     317
     318  return m;
     319}
     320
     321#if PY_MAJOR_VERSION >= 3
     322    // Python3 init
     323    PyMODINIT_FUNC PyInit__aubio(void)
     324    {
     325        return initaubio();
     326    }
     327#else
     328    // Python 2 init
     329    PyMODINIT_FUNC init_aubio(void)
     330    {
     331        initaubio();
     332    }
     333#endif
  • python/ext/aubioproxy.c

    r60fc05b rf264b17  
    11#include "aubio-types.h"
    22
    3 fvec_t *
    4 PyAubio_ArrayToCFvec (PyObject *input) {
    5   PyObject *array;
    6   fvec_t *vec;
    7   if (input == NULL) {
    8     PyErr_SetString (PyExc_ValueError, "input array is not a python object");
    9     goto fail;
    10   }
    11   // parsing input object into a Py_fvec
    12   if (PyArray_Check(input)) {
     3PyObject *
     4new_py_fvec(uint_t length) {
     5    npy_intp dims[] = { length, 1 };
     6    return PyArray_ZEROS(1, dims, AUBIO_NPY_SMPL, 0);
     7}
    138
    14     // we got an array, convert it to an fvec
    15     if (PyArray_NDIM ((PyArrayObject *)input) == 0) {
    16       PyErr_SetString (PyExc_ValueError, "input array is a scalar");
    17       goto fail;
    18     } else if (PyArray_NDIM ((PyArrayObject *)input) > 1) {
    19       PyErr_SetString (PyExc_ValueError,
    20           "input array has more than one dimensions");
    21       goto fail;
    22     }
    23 
    24     if (!PyArray_ISFLOAT ((PyArrayObject *)input)) {
    25       PyErr_SetString (PyExc_ValueError, "input array should be float");
    26       goto fail;
    27     } else if (PyArray_TYPE ((PyArrayObject *)input) != AUBIO_NPY_SMPL) {
    28       PyErr_SetString (PyExc_ValueError, "input array should be float32");
    29       goto fail;
    30     } else {
    31       // input data type is float32, nothing else to do
    32       array = input;
    33     }
    34 
    35     // vec = new_fvec (vec->length);
    36     // no need to really allocate fvec, just its struct member
    37     vec = (fvec_t *)malloc(sizeof(fvec_t));
    38     long length = PyArray_SIZE ((PyArrayObject *)array);
    39     if (length > 0) {
    40       vec->length = (uint_t)length;
    41     } else {
    42       PyErr_SetString (PyExc_ValueError, "input array size should be greater than 0");
    43       goto fail;
    44     }
    45     vec->data = (smpl_t *) PyArray_GETPTR1 ((PyArrayObject *)array, 0);
    46 
    47   } else if (PyObject_TypeCheck (input, &PyList_Type)) {
    48     PyErr_SetString (PyExc_ValueError, "does not convert from list yet");
    49     return NULL;
    50   } else {
    51     PyErr_SetString (PyExc_ValueError, "can only accept vector of float as input");
    52     return NULL;
    53   }
    54 
    55   return vec;
    56 
    57 fail:
    58   return NULL;
     9PyObject *
     10new_py_fmat(uint_t height, uint_t length) {
     11    npy_intp dims[] = { height, length, 1 };
     12    return PyArray_ZEROS(2, dims, AUBIO_NPY_SMPL, 0);
    5913}
    6014
     
    6620}
    6721
    68 Py_cvec *
    69 PyAubio_CCvecToPyCvec (cvec_t * input) {
    70   Py_cvec *vec = (Py_cvec*) PyObject_New (Py_cvec, &Py_cvecType);
    71   vec->length = input->length;
    72   vec->o = input;
    73   Py_INCREF(vec);
    74   return vec;
     22int
     23PyAubio_IsValidVector (PyObject * input) {
     24  npy_intp length;
     25  if (input == NULL) {
     26    PyErr_SetString (PyExc_ValueError, "input array is not a python object");
     27    return 0;
     28  }
     29  // parsing input object into a Py_fvec
     30  if (PyArray_Check(input)) {
     31
     32    // we got an array, convert it to an fvec
     33    if (PyArray_NDIM ((PyArrayObject *)input) == 0) {
     34      PyErr_SetString (PyExc_ValueError, "input array is a scalar");
     35      return 0;
     36    } else if (PyArray_NDIM ((PyArrayObject *)input) > 1) {
     37      PyErr_SetString (PyExc_ValueError,
     38          "input array has more than one dimensions");
     39      return 0;
     40    }
     41
     42    if (!PyArray_ISFLOAT ((PyArrayObject *)input)) {
     43      PyErr_SetString (PyExc_ValueError, "input array should be float");
     44      return 0;
     45    } else if (PyArray_TYPE ((PyArrayObject *)input) != AUBIO_NPY_SMPL) {
     46      PyErr_SetString (PyExc_ValueError, "input array should be " AUBIO_NPY_SMPL_STR);
     47      return 0;
     48    }
     49
     50    length = PyArray_SIZE ((PyArrayObject *)input);
     51    if (length <= 0) {
     52      PyErr_SetString (PyExc_ValueError, "input array size should be greater than 0");
     53      return 0;
     54    }
     55
     56  } else if (PyObject_TypeCheck (input, &PyList_Type)) {
     57    PyErr_SetString (PyExc_ValueError, "does not convert from list yet");
     58    return 0;
     59  } else {
     60    PyErr_SetString (PyExc_ValueError, "can only accept vector of float as input");
     61    return 0;
     62  }
     63  return 1;
    7564}
    7665
    77 cvec_t *
    78 PyAubio_ArrayToCCvec (PyObject *input) {
    79   if (PyObject_TypeCheck (input, &Py_cvecType)) {
    80       return ((Py_cvec*)input)->o;
    81   } else {
    82       PyErr_SetString (PyExc_ValueError, "input array should be float32");
    83       return NULL;
     66int
     67PyAubio_ArrayToCFvec (PyObject *input, fvec_t *out) {
     68
     69  if (!PyAubio_IsValidVector(input)){
     70    return 0;
    8471  }
     72
     73  out->length = (uint_t) PyArray_SIZE ((PyArrayObject *)input);
     74  out->data = (smpl_t *) PyArray_GETPTR1 ((PyArrayObject *)input, 0);
     75  return 1;
    8576}
    8677
     
    10293}
    10394
    104 fmat_t *
    105 PyAubio_ArrayToCFmat (PyObject *input) {
    106   PyObject *array;
    107   fmat_t *mat;
    108   uint_t i;
     95int
     96PyAubio_ArrayToCFmat (PyObject *input, fmat_t *mat) {
     97  uint_t i, new_height;
     98  npy_intp length, height;
    10999  if (input == NULL) {
    110100    PyErr_SetString (PyExc_ValueError, "input array is not a python object");
    111     goto fail;
     101    return 0;
    112102  }
    113103  // parsing input object into a Py_fvec
     
    117107    if (PyArray_NDIM ((PyArrayObject *)input) == 0) {
    118108      PyErr_SetString (PyExc_ValueError, "input array is a scalar");
    119       goto fail;
     109      return 0;
    120110    } else if (PyArray_NDIM ((PyArrayObject *)input) > 2) {
    121111      PyErr_SetString (PyExc_ValueError,
    122112          "input array has more than two dimensions");
    123       goto fail;
     113      return 0;
    124114    }
    125115
    126116    if (!PyArray_ISFLOAT ((PyArrayObject *)input)) {
    127117      PyErr_SetString (PyExc_ValueError, "input array should be float");
    128       goto fail;
     118      return 0;
    129119    } else if (PyArray_TYPE ((PyArrayObject *)input) != AUBIO_NPY_SMPL) {
    130       PyErr_SetString (PyExc_ValueError, "input array should be float32");
    131       goto fail;
    132     } else {
    133       // input data type is float32, nothing else to do
    134       array = input;
     120      PyErr_SetString (PyExc_ValueError, "input array should be " AUBIO_NPY_SMPL_STR);
     121      return 0;
    135122    }
    136123
    137124    // no need to really allocate fvec, just its struct member
    138     mat = (fmat_t *)malloc(sizeof(fmat_t));
    139     long length = PyArray_DIM ((PyArrayObject *)array, 1);
    140     if (length > 0) {
    141       mat->length = (uint_t)length;
    142     } else {
     125    length = PyArray_DIM ((PyArrayObject *)input, 1);
     126    if (length <= 0) {
    143127      PyErr_SetString (PyExc_ValueError, "input array dimension 1 should be greater than 0");
    144       goto fail;
     128      return 0;
    145129    }
    146     long height = PyArray_DIM ((PyArrayObject *)array, 0);
    147     if (height > 0) {
    148       mat->height = (uint_t)height;
    149     } else {
     130    height = PyArray_DIM ((PyArrayObject *)input, 0);
     131    if (height <= 0) {
    150132      PyErr_SetString (PyExc_ValueError, "input array dimension 0 should be greater than 0");
    151       goto fail;
    152     }
    153     mat->data = (smpl_t **)malloc(sizeof(smpl_t*) * mat->height);
    154     for (i=0; i< mat->height; i++) {
    155       mat->data[i] = (smpl_t*)PyArray_GETPTR1 ((PyArrayObject *)array, i);
     133      return 0;
    156134    }
    157135
    158136  } else if (PyObject_TypeCheck (input, &PyList_Type)) {
    159137    PyErr_SetString (PyExc_ValueError, "can not convert list to fmat");
    160     return NULL;
     138    return 0;
    161139  } else {
    162140    PyErr_SetString (PyExc_ValueError, "can only accept matrix of float as input");
    163     return NULL;
     141    return 0;
    164142  }
    165143
    166   return mat;
     144  new_height = (uint_t)PyArray_DIM ((PyArrayObject *)input, 0);
     145  if (mat->height != new_height) {
     146    if (mat->data) {
     147      free(mat->data);
     148    }
     149    mat->data = (smpl_t **)malloc(sizeof(smpl_t*) * new_height);
     150  }
    167151
    168 fail:
    169   return NULL;
     152  mat->height = new_height;
     153  mat->length = (uint_t)PyArray_DIM ((PyArrayObject *)input, 1);
     154  for (i=0; i< mat->height; i++) {
     155    mat->data[i] = (smpl_t*)PyArray_GETPTR1 ((PyArrayObject *)input, i);
     156  }
     157  return 1;
    170158}
    171 
  • python/ext/py-cvec.c

    r60fc05b rf264b17  
    11#include "aubio-types.h"
    22
    3 /* cvec type definition 
     3/* cvec type definition
    44
    55class cvec():
    6     def __init__(self, length = 1024):
    7         self.length = length
    8         self.norm = array(length)
    9         self.phas = array(length)
     6    def __new__(self, length = 1024):
     7        self.length = length / 2 + 1
     8        self.norm = np.zeros(length / 2 + 1)
     9        self.phas = np.zeros(length / 2 + 1)
    1010
    1111*/
    1212
     13// special python type for cvec
     14typedef struct
     15{
     16  PyObject_HEAD
     17  PyObject *norm;
     18  PyObject *phas;
     19  uint_t length;
     20} Py_cvec;
     21
    1322static char Py_cvec_doc[] = "cvec object";
     23
     24
     25PyObject *
     26new_py_cvec(uint_t length) {
     27  Py_cvec* vec = (Py_cvec*) PyObject_New (Py_cvec, &Py_cvecType);
     28  npy_intp dims[] = { length / 2 + 1, 1 };
     29  vec->norm = PyArray_ZEROS(1, dims, AUBIO_NPY_SMPL, 0);
     30  vec->phas = PyArray_ZEROS(1, dims, AUBIO_NPY_SMPL, 0);
     31  vec->length = length / 2 + 1;
     32  return (PyObject*)vec;
     33}
     34
     35int
     36PyAubio_PyCvecToCCvec (PyObject *input, cvec_t *i) {
     37  if (PyObject_TypeCheck (input, &Py_cvecType)) {
     38      Py_cvec * in = (Py_cvec *)input;
     39      i->norm = (smpl_t *) PyArray_GETPTR1 ((PyArrayObject *)(in->norm), 0);
     40      i->phas = (smpl_t *) PyArray_GETPTR1 ((PyArrayObject *)(in->phas), 0);
     41      i->length = ((Py_cvec*)input)->length;
     42      return 1;
     43  } else {
     44      PyErr_SetString (PyExc_ValueError, "input array should be aubio.cvec");
     45      return 0;
     46  }
     47}
    1448
    1549static PyObject *
     
    2458    return NULL;
    2559  }
    26 
    2760
    2861  self = (Py_cvec *) type->tp_alloc (type, 0);
     
    4881Py_cvec_init (Py_cvec * self, PyObject * args, PyObject * kwds)
    4982{
    50   self->o = new_cvec ((self->length - 1) * 2);
    51   if (self->o == NULL) {
    52     return -1;
    53   }
    54 
     83  npy_intp dims[] = { self->length, 1 };
     84  self->phas = PyArray_ZEROS(1, dims, AUBIO_NPY_SMPL, 0);
     85  self->norm = PyArray_ZEROS(1, dims, AUBIO_NPY_SMPL, 0);
    5586  return 0;
    5687}
     
    5990Py_cvec_del (Py_cvec * self)
    6091{
    61   del_cvec (self->o);
    62   self->ob_type->tp_free ((PyObject *) self);
     92  Py_DECREF(self->norm);
     93  Py_DECREF(self->phas);
     94  Py_TYPE(self)->tp_free ((PyObject *) self);
    6395}
    6496
     
    70102  PyObject *result = NULL;
    71103
    72   format = PyString_FromString ("aubio cvec of %d elements");
     104  format = PyUnicode_FromString ("aubio cvec of %d elements");
    73105  if (format == NULL) {
    74106    goto fail;
     
    79111    goto fail;
    80112  }
    81   cvec_print ( self->o );
    82 
    83   result = PyString_Format (format, args);
     113  // hide actual norm / phas content
     114
     115  result = PyUnicode_Format (format, args);
    84116
    85117fail:
     
    91123
    92124PyObject *
    93 PyAubio_CvecNormToArray (Py_cvec * self)
    94 {
    95   npy_intp dims[] = { self->o->length, 1 };
    96   return PyArray_SimpleNewFromData (1, dims, NPY_FLOAT, self->o->norm);
    97 }
    98 
    99 
    100 PyObject *
    101 PyAubio_CvecPhasToArray (Py_cvec * self)
    102 {
    103   npy_intp dims[] = { self->o->length, 1 };
    104   return PyArray_SimpleNewFromData (1, dims, NPY_FLOAT, self->o->phas);
    105 }
    106 
    107 PyObject *
    108 PyAubio_ArrayToCvecPhas (PyObject * self)
    109 {
    110   return NULL;
    111 }
    112 
    113 PyObject *
    114125Py_cvec_get_norm (Py_cvec * self, void *closure)
    115126{
    116   return PyAubio_CvecNormToArray(self);
     127  // we want self->norm to still exist after our caller return it
     128  Py_INCREF(self->norm);
     129  return (PyObject*)(self->norm);
    117130}
    118131
     
    120133Py_cvec_get_phas (Py_cvec * self, void *closure)
    121134{
    122   return PyAubio_CvecPhasToArray(self);
     135  // we want self->phas to still exist after our caller return it
     136  Py_INCREF(self->phas);
     137  return (PyObject *)(self->phas);
    123138}
    124139
     
    126141Py_cvec_set_norm (Py_cvec * vec, PyObject *input, void * closure)
    127142{
    128   PyArrayObject * array;
    129   if (input == NULL) {
    130     PyErr_SetString (PyExc_ValueError, "input array is not a python object");
    131     goto fail;
    132   }
    133   if (PyArray_Check(input)) {
    134 
    135     // we got an array, convert it to a cvec.norm
    136     if (PyArray_NDIM ((PyArrayObject *)input) == 0) {
    137       PyErr_SetString (PyExc_ValueError, "input array is a scalar");
    138       goto fail;
    139     } else if (PyArray_NDIM ((PyArrayObject *)input) > 2) {
    140       PyErr_SetString (PyExc_ValueError,
    141           "input array has more than two dimensions");
    142       goto fail;
    143     }
    144 
    145     if (!PyArray_ISFLOAT ((PyArrayObject *)input)) {
    146       PyErr_SetString (PyExc_ValueError, "input array should be float");
    147       goto fail;
    148     } else if (PyArray_TYPE ((PyArrayObject *)input) != AUBIO_NPY_SMPL) {
    149       PyErr_SetString (PyExc_ValueError, "input array should be float32");
    150       goto fail;
    151     }
    152     array = (PyArrayObject *)input;
    153 
    154     // check input array dimensions
    155     if (PyArray_NDIM (array) != 1) {
    156       PyErr_Format (PyExc_ValueError,
    157           "input array has %d dimensions, not 1",
    158           PyArray_NDIM (array));
    159       goto fail;
    160     } else {
    161       if (vec->o->length != PyArray_SIZE (array)) {
    162           PyErr_Format (PyExc_ValueError,
    163                   "input array has length %d, but cvec has length %d",
    164                   (int)PyArray_SIZE (array), vec->o->length);
    165           goto fail;
    166       }
    167     }
    168 
    169     vec->o->norm = (smpl_t *) PyArray_GETPTR1 (array, 0);
    170 
    171   } else {
    172     PyErr_SetString (PyExc_ValueError, "can only accept array as input");
    173     return 1;
    174   }
    175 
    176   Py_INCREF(array);
     143  npy_intp length;
     144  if (!PyAubio_IsValidVector(input)) {
     145    return 1;
     146  }
     147  length = PyArray_SIZE ((PyArrayObject *)input);
     148  if (length != vec->length) {
     149    PyErr_Format (PyExc_ValueError,
     150        "input array has length %ld, but cvec has length %d", length,
     151        vec->length);
     152    return 1;
     153  }
     154
     155  Py_XDECREF(vec->norm);
     156  vec->norm = input;
     157  Py_INCREF(vec->norm);
    177158  return 0;
    178 
    179 fail:
    180   return 1;
    181159}
    182160
     
    184162Py_cvec_set_phas (Py_cvec * vec, PyObject *input, void * closure)
    185163{
    186   PyArrayObject * array;
    187   if (input == NULL) {
    188     PyErr_SetString (PyExc_ValueError, "input array is not a python object");
    189     goto fail;
    190   }
    191   if (PyArray_Check(input)) {
    192 
    193     // we got an array, convert it to a cvec.phas
    194     if (PyArray_NDIM ((PyArrayObject *)input) == 0) {
    195       PyErr_SetString (PyExc_ValueError, "input array is a scalar");
    196       goto fail;
    197     } else if (PyArray_NDIM ((PyArrayObject *)input) > 2) {
    198       PyErr_SetString (PyExc_ValueError,
    199           "input array has more than two dimensions");
    200       goto fail;
    201     }
    202 
    203     if (!PyArray_ISFLOAT ((PyArrayObject *)input)) {
    204       PyErr_SetString (PyExc_ValueError, "input array should be float");
    205       goto fail;
    206     } else if (PyArray_TYPE ((PyArrayObject *)input) != AUBIO_NPY_SMPL) {
    207       PyErr_SetString (PyExc_ValueError, "input array should be float32");
    208       goto fail;
    209     }
    210     array = (PyArrayObject *)input;
    211 
    212     // check input array dimensions
    213     if (PyArray_NDIM (array) != 1) {
    214       PyErr_Format (PyExc_ValueError,
    215           "input array has %d dimensions, not 1",
    216           PyArray_NDIM (array));
    217       goto fail;
    218     } else {
    219       if (vec->o->length != PyArray_SIZE (array)) {
    220           PyErr_Format (PyExc_ValueError,
    221                   "input array has length %d, but cvec has length %d",
    222                   (int)PyArray_SIZE (array), vec->o->length);
    223           goto fail;
    224       }
    225     }
    226 
    227     vec->o->phas = (smpl_t *) PyArray_GETPTR1 (array, 0);
    228 
    229   } else {
    230     PyErr_SetString (PyExc_ValueError, "can only accept array as input");
    231     return 1;
    232   }
    233 
    234   Py_INCREF(array);
     164  npy_intp length;
     165  if (!PyAubio_IsValidVector(input)) {
     166    return 1;
     167  }
     168  length = PyArray_SIZE ((PyArrayObject *)input);
     169  if (length != vec->length) {
     170    PyErr_Format (PyExc_ValueError,
     171        "input array has length %ld, but cvec has length %d", length,
     172        vec->length);
     173    return 1;
     174  }
     175
     176  Py_XDECREF(vec->phas);
     177  vec->phas = input;
     178  Py_INCREF(vec->phas);
    235179  return 0;
    236 
    237 fail:
    238   return 1;
    239180}
    240181
     
    261202
    262203PyTypeObject Py_cvecType = {
    263   PyObject_HEAD_INIT (NULL)
    264   0,                            /* ob_size           */
     204  PyVarObject_HEAD_INIT(NULL, 0)
    265205  "aubio.cvec",                 /* tp_name           */
    266206  sizeof (Py_cvec),             /* tp_basicsize      */
     
    273213  (reprfunc) Py_cvec_repr,      /* tp_repr           */
    274214  0,                            /* tp_as_number      */
    275   0, //&Py_cvec_tp_as_sequence,      /* tp_as_sequence    */
     215  0, //&Py_cvec_tp_as_sequence, /* tp_as_sequence    */
    276216  0,                            /* tp_as_mapping     */
    277217  0,                            /* tp_hash           */
     
    300240  0,                            /* tp_alloc          */
    301241  Py_cvec_new,                  /* tp_new            */
    302 };
     242  0,
     243  0,
     244  0,
     245  0,
     246  0,
     247  0,
     248  0,
     249  0,
     250  0,
     251};
  • python/ext/py-fft.c

    r60fc05b rf264b17  
    1 #include "aubiowraphell.h"
     1#include "aubio-types.h"
    22
    33static char Py_fft_doc[] = "fft object";
    44
    5 AUBIO_DECLARE(fft, uint_t win_s)
     5typedef struct
     6{
     7  PyObject_HEAD
     8  aubio_fft_t * o;
     9  uint_t win_s;
     10  // do / rdo input vectors
     11  fvec_t vecin;
     12  cvec_t cvecin;
     13  // do / rdo output results
     14  PyObject *doout;
     15  PyObject *rdoout;
     16} Py_fft;
    617
    7 //AUBIO_NEW(fft)
    818static PyObject *
    919Py_fft_new (PyTypeObject * type, PyObject * args, PyObject * kwds)
     
    3747}
    3848
     49static int
     50Py_fft_init (Py_fft * self, PyObject * args, PyObject * kwds)
     51{
     52  self->o = new_aubio_fft (self->win_s);
     53  if (self->o == NULL) {
     54    PyErr_Format(PyExc_RuntimeError,
     55        "error creating fft with win_s=%d "
     56        "(should be a power of 2 greater than 1; "
     57        "try recompiling aubio with --enable-fftw3)",
     58        self->win_s);
     59    return -1;
     60  }
    3961
    40 AUBIO_INIT(fft, self->win_s)
     62  self->doout = new_py_cvec(self->win_s);
     63  self->rdoout = new_py_fvec(self->win_s);
    4164
    42 AUBIO_DEL(fft)
     65  return 0;
     66}
    4367
    44 static PyObject *
    45 Py_fft_do(PyObject * self, PyObject * args)
     68static void
     69Py_fft_del (Py_fft *self, PyObject *unused)
     70{
     71  Py_XDECREF(self->doout);
     72  Py_XDECREF(self->rdoout);
     73  if (self->o) {
     74    del_aubio_fft(self->o);
     75  }
     76  Py_TYPE(self)->tp_free((PyObject *) self);
     77}
     78
     79static PyObject *
     80Py_fft_do(Py_fft * self, PyObject * args)
    4681{
    4782  PyObject *input;
    48   fvec_t *vec;
    49   cvec_t *output;
     83  cvec_t c_out;
    5084
    5185  if (!PyArg_ParseTuple (args, "O", &input)) {
     
    5387  }
    5488
    55   vec = PyAubio_ArrayToCFvec (input);
    56 
    57   if (vec == NULL) {
     89  if (!PyAubio_ArrayToCFvec(input, &(self->vecin))) {
    5890    return NULL;
    5991  }
    6092
    61   output = new_cvec(((Py_fft *) self)->win_s);
     93  if (self->vecin.length != self->win_s) {
     94    PyErr_Format(PyExc_ValueError,
     95                 "input array has length %d, but fft expects length %d",
     96                 self->vecin.length, self->win_s);
     97    return NULL;
     98  }
    6299
     100  Py_INCREF(self->doout);
     101  if (!PyAubio_PyCvecToCCvec(self->doout, &c_out)) {
     102    return NULL;
     103  }
    63104  // compute the function
    64   aubio_fft_do (((Py_fft *)self)->o, vec, output);
    65   return (PyObject *)PyAubio_CCvecToPyCvec(output);
     105  aubio_fft_do (self->o, &(self->vecin), &c_out);
     106  return self->doout;
    66107}
    67108
    68 AUBIO_MEMBERS_START(fft)
     109static PyMemberDef Py_fft_members[] = {
    69110  {"win_s", T_INT, offsetof (Py_fft, win_s), READONLY,
    70111    "size of the window"},
    71 AUBIO_MEMBERS_STOP(fft)
     112  {NULL}
     113};
    72114
    73 static PyObject * 
     115static PyObject *
    74116Py_fft_rdo(Py_fft * self, PyObject * args)
    75117{
    76118  PyObject *input;
    77   cvec_t *vec;
    78   fvec_t *output;
     119  fvec_t out;
    79120
    80121  if (!PyArg_ParseTuple (args, "O", &input)) {
     
    82123  }
    83124
    84   vec = PyAubio_ArrayToCCvec (input);
    85 
    86   if (vec == NULL) {
     125  if (!PyAubio_PyCvecToCCvec (input, &(self->cvecin)) ) {
    87126    return NULL;
    88127  }
    89128
    90   output = new_fvec(self->win_s);
     129  if (self->cvecin.length != self->win_s / 2 + 1) {
     130    PyErr_Format(PyExc_ValueError,
     131                 "input cvec has length %d, but fft expects length %d",
     132                 self->cvecin.length, self->win_s / 2 + 1);
     133    return NULL;
     134  }
    91135
     136  Py_INCREF(self->rdoout);
     137  if (!PyAubio_ArrayToCFvec(self->rdoout, &out) ) {
     138    return NULL;
     139  }
    92140  // compute the function
    93   aubio_fft_rdo (((Py_fft *)self)->o, vec, output);
    94   return (PyObject *)PyAubio_CFvecToArray(output);
     141  aubio_fft_rdo (self->o, &(self->cvecin), &out);
     142  return self->rdoout;
    95143}
    96144
     
    101149};
    102150
    103 AUBIO_TYPEOBJECT(fft, "aubio.fft")
     151PyTypeObject Py_fftType = {
     152  PyVarObject_HEAD_INIT (NULL, 0)
     153  "aubio.fft",
     154  sizeof (Py_fft),
     155  0,
     156  (destructor) Py_fft_del,
     157  0,
     158  0,
     159  0,
     160  0,
     161  0,
     162  0,
     163  0,
     164  0,
     165  0,
     166  (ternaryfunc)Py_fft_do,
     167  0,
     168  0,
     169  0,
     170  0,
     171  Py_TPFLAGS_DEFAULT,
     172  Py_fft_doc,
     173  0,
     174  0,
     175  0,
     176  0,
     177  0,
     178  0,
     179  Py_fft_methods,
     180  Py_fft_members,
     181  0,
     182  0,
     183  0,
     184  0,
     185  0,
     186  0,
     187  (initproc) Py_fft_init,
     188  0,
     189  Py_fft_new,
     190  0,
     191  0,
     192  0,
     193  0,
     194  0,
     195  0,
     196  0,
     197  0,
     198  0,
     199};
  • python/ext/py-filter.c

    r60fc05b rf264b17  
    66  aubio_filter_t * o;
    77  uint_t order;
     8  fvec_t vec;
     9  PyObject *out;
     10  fvec_t c_out;
    811} Py_filter;
    912
     
    4851    return -1;
    4952  }
    50 
     53  self->out = NULL;
    5154  return 0;
    5255}
     
    5558Py_filter_del (Py_filter * self)
    5659{
     60  Py_XDECREF(self->out);
    5761  del_aubio_filter (self->o);
    58   self->ob_type->tp_free ((PyObject *) self);
    59 }
    60 
    61 static PyObject * 
     62  Py_TYPE(self)->tp_free ((PyObject *) self);
     63}
     64
     65static PyObject *
    6266Py_filter_do(Py_filter * self, PyObject * args)
    6367{
    6468  PyObject *input;
    65   fvec_t *vec;
    6669
    6770  if (!PyArg_ParseTuple (args, "O:digital_filter.do", &input)) {
     
    7376  }
    7477
    75   vec = PyAubio_ArrayToCFvec (input);
    76 
    77   if (vec == NULL) {
    78     return NULL;
    79   }
    80 
     78  if (!PyAubio_ArrayToCFvec(input, &(self->vec))) {
     79    return NULL;
     80  }
     81
     82  // initialize output now
     83  if (self->out == NULL) {
     84    self->out = new_py_fvec(self->vec.length);
     85  }
     86
     87  Py_INCREF(self->out);
     88  if (!PyAubio_ArrayToCFvec(self->out, &(self->c_out)) ) {
     89    return NULL;
     90  }
    8191  // compute the function
    82   fvec_t * out = new_fvec(vec->length);
    83   aubio_filter_do_outplace (self->o, vec, out);
    84   return PyAubio_CFvecToArray(out);
    85 }
    86 
    87 static PyObject *
     92  aubio_filter_do_outplace (self->o, &(self->vec), &(self->c_out));
     93  return self->out;
     94}
     95
     96static PyObject *
    8897Py_filter_set_c_weighting (Py_filter * self, PyObject *args)
    8998{
     
    103112}
    104113
    105 static PyObject * 
     114static PyObject *
    106115Py_filter_set_a_weighting (Py_filter * self, PyObject *args)
    107116{
     
    157166
    158167PyTypeObject Py_filterType = {
    159   PyObject_HEAD_INIT (NULL)
    160   0,                            /* ob_size           */
     168  PyVarObject_HEAD_INIT(NULL, 0)
    161169  "aubio.digital_filter",       /* tp_name           */
    162170  sizeof (Py_filter),           /* tp_basicsize      */
     
    196204  0,                            /* tp_alloc          */
    197205  Py_filter_new,                /* tp_new            */
     206  0,
     207  0,
     208  0,
     209  0,
     210  0,
     211  0,
     212  0,
     213  0,
     214  0,
    198215};
  • python/ext/py-filterbank.c

    r60fc05b rf264b17  
    1 #include "aubiowraphell.h"
     1#include "aubio-types.h"
    22
    33static char Py_filterbank_doc[] = "filterbank object";
    44
    5 AUBIO_DECLARE(filterbank, uint_t n_filters; uint_t win_s)
    6 
    7 //AUBIO_NEW(filterbank)
     5typedef struct
     6{
     7  PyObject_HEAD
     8  aubio_filterbank_t * o;
     9  uint_t n_filters;
     10  uint_t win_s;
     11  cvec_t vec;
     12  fvec_t freqs;
     13  fmat_t coeffs;
     14  PyObject *out;
     15  fvec_t c_out;
     16} Py_filterbank;
     17
    818static PyObject *
    919Py_filterbank_new (PyTypeObject * type, PyObject * args, PyObject * kwds)
     
    4555}
    4656
    47 
    48 AUBIO_INIT(filterbank, self->n_filters, self->win_s)
    49 
    50 AUBIO_DEL(filterbank)
     57static int
     58Py_filterbank_init (Py_filterbank * self, PyObject * args, PyObject * kwds)
     59{
     60  self->o = new_aubio_filterbank (self->n_filters, self->win_s);
     61  if (self->o == NULL) {
     62    PyErr_Format(PyExc_RuntimeError, "error creating filterbank with"
     63        " n_filters=%d, win_s=%d", self->n_filters, self->win_s);
     64    return -1;
     65  }
     66  self->out = new_py_fvec(self->n_filters);
     67
     68  return 0;
     69}
     70
     71static void
     72Py_filterbank_del (Py_filterbank *self, PyObject *unused)
     73{
     74  if (self->o) {
     75    free(self->coeffs.data);
     76    del_aubio_filterbank(self->o);
     77  }
     78  Py_XDECREF(self->out);
     79  Py_TYPE(self)->tp_free((PyObject *) self);
     80}
    5181
    5282static PyObject *
     
    5484{
    5585  PyObject *input;
    56   cvec_t *vec;
    57   fvec_t *out;
    5886
    5987  if (!PyArg_ParseTuple (args, "O", &input)) {
     
    6189  }
    6290
    63   vec = PyAubio_ArrayToCCvec (input);
    64 
    65   if (vec == NULL) {
    66     return NULL;
    67   }
    68 
    69   out = new_fvec (self->n_filters);
    70 
     91  if (!PyAubio_PyCvecToCCvec(input, &(self->vec) )) {
     92    return NULL;
     93  }
     94
     95  if (self->vec.length != self->win_s / 2 + 1) {
     96    PyErr_Format(PyExc_ValueError,
     97                 "input cvec has length %d, but fft expects length %d",
     98                 self->vec.length, self->win_s / 2 + 1);
     99    return NULL;
     100  }
     101
     102  Py_INCREF(self->out);
     103  if (!PyAubio_ArrayToCFvec(self->out, &(self->c_out))) {
     104    return NULL;
     105  }
    71106  // compute the function
    72   aubio_filterbank_do (self->o, vec, out);
    73   return (PyObject *)PyAubio_CFvecToArray(out);
    74 }
    75 
    76 AUBIO_MEMBERS_START(filterbank)
     107  aubio_filterbank_do (self->o, &(self->vec), &(self->c_out));
     108  return self->out;
     109}
     110
     111static PyMemberDef Py_filterbank_members[] = {
    77112  {"win_s", T_INT, offsetof (Py_filterbank, win_s), READONLY,
    78113    "size of the window"},
    79114  {"n_filters", T_INT, offsetof (Py_filterbank, n_filters), READONLY,
    80115    "number of filters"},
    81 AUBIO_MEMBERS_STOP(filterbank)
     116  {NULL} /* sentinel */
     117};
    82118
    83119static PyObject *
     
    88124  PyObject *input;
    89125  uint_t samplerate;
    90   fvec_t *freqs;
    91126  if (!PyArg_ParseTuple (args, "OI", &input, &samplerate)) {
    92127    return NULL;
     
    97132  }
    98133
    99   freqs = PyAubio_ArrayToCFvec (input);
    100 
    101   if (freqs == NULL) {
     134  if (!PyAubio_ArrayToCFvec(input, &(self->freqs) )) {
    102135    return NULL;
    103136  }
    104137
    105138  err = aubio_filterbank_set_triangle_bands (self->o,
    106       freqs, samplerate);
     139      &(self->freqs), samplerate);
    107140  if (err > 0) {
    108141    PyErr_SetString (PyExc_ValueError,
     
    138171
    139172  PyObject *input;
    140   fmat_t *coeffs;
    141 
    142173  if (!PyArg_ParseTuple (args, "O", &input)) {
    143174    return NULL;
    144175  }
    145176
    146   coeffs = PyAubio_ArrayToCFmat (input);
    147 
    148   if (coeffs == NULL) {
    149     PyErr_SetString (PyExc_ValueError,
    150         "unable to parse input array");
    151     return NULL;
    152   }
    153 
    154   err = aubio_filterbank_set_coeffs (self->o, coeffs);
     177  if (!PyAubio_ArrayToCFmat(input, &(self->coeffs))) {
     178    return NULL;
     179  }
     180
     181  err = aubio_filterbank_set_coeffs (self->o, &(self->coeffs));
    155182
    156183  if (err > 0) {
     
    181208};
    182209
    183 AUBIO_TYPEOBJECT(filterbank, "aubio.filterbank")
     210PyTypeObject Py_filterbankType = {
     211  PyVarObject_HEAD_INIT (NULL, 0)
     212  "aubio.filterbank",
     213  sizeof (Py_filterbank),
     214  0,
     215  (destructor) Py_filterbank_del,
     216  0,
     217  0,
     218  0,
     219  0,
     220  0,
     221  0,
     222  0,
     223  0,
     224  0,
     225  (ternaryfunc)Py_filterbank_do,
     226  0,
     227  0,
     228  0,
     229  0,
     230  Py_TPFLAGS_DEFAULT,
     231  Py_filterbank_doc,
     232  0,
     233  0,
     234  0,
     235  0,
     236  0,
     237  0,
     238  Py_filterbank_methods,
     239  Py_filterbank_members,
     240  0,
     241  0,
     242  0,
     243  0,
     244  0,
     245  0,
     246  (initproc) Py_filterbank_init,
     247  0,
     248  Py_filterbank_new,
     249  0,
     250  0,
     251  0,
     252  0,
     253  0,
     254  0,
     255  0,
     256  0,
     257  0,
     258};
  • python/ext/py-musicutils.c

    r60fc05b rf264b17  
    99
    1010  if (!PyArg_ParseTuple (args, "|sI", &wintype, &winlen)) {
    11     PyErr_SetString (PyExc_ValueError, "failed parsing arguments");
    1211    return NULL;
    1312  }
     
    2625{
    2726  PyObject *input;
    28   fvec_t *vec;
     27  fvec_t vec;
    2928  PyObject *level_lin;
    3029
    3130  if (!PyArg_ParseTuple (args, "O:level_lin", &input)) {
    32     PyErr_SetString (PyExc_ValueError, "failed parsing arguments");
    3331    return NULL;
    3432  }
     
    3836  }
    3937
    40   vec = PyAubio_ArrayToCFvec (input);
    41   if (vec == NULL) {
     38  if (!PyAubio_ArrayToCFvec(input, &vec)) {
    4239    return NULL;
    4340  }
    4441
    45   level_lin = Py_BuildValue("f", aubio_level_lin(vec));
     42  level_lin = Py_BuildValue(AUBIO_NPY_SMPL_CHR, aubio_level_lin(&vec));
    4643  if (level_lin == NULL) {
    4744    PyErr_SetString (PyExc_ValueError, "failed computing level_lin");
     
    5653{
    5754  PyObject *input;
    58   fvec_t *vec;
     55  fvec_t vec;
    5956  PyObject *db_spl;
    6057
    6158  if (!PyArg_ParseTuple (args, "O:db_spl", &input)) {
    62     PyErr_SetString (PyExc_ValueError, "failed parsing arguments");
    6359    return NULL;
    6460  }
     
    6864  }
    6965
    70   vec = PyAubio_ArrayToCFvec (input);
    71   if (vec == NULL) {
     66  if (!PyAubio_ArrayToCFvec(input, &vec)) {
    7267    return NULL;
    7368  }
    7469
    75   db_spl = Py_BuildValue("f", aubio_db_spl(vec));
     70  db_spl = Py_BuildValue(AUBIO_NPY_SMPL_CHR, aubio_db_spl(&vec));
    7671  if (db_spl == NULL) {
    7772    PyErr_SetString (PyExc_ValueError, "failed computing db_spl");
     
    8681{
    8782  PyObject *input;
    88   fvec_t *vec;
     83  fvec_t vec;
    8984  PyObject *silence_detection;
    9085  smpl_t threshold;
    9186
    92   if (!PyArg_ParseTuple (args, "Of:silence_detection", &input, &threshold)) {
    93     PyErr_SetString (PyExc_ValueError, "failed parsing arguments");
     87  if (!PyArg_ParseTuple (args, "O" AUBIO_NPY_SMPL_CHR ":silence_detection", &input, &threshold)) {
    9488    return NULL;
    9589  }
     
    9993  }
    10094
    101   vec = PyAubio_ArrayToCFvec (input);
    102   if (vec == NULL) {
     95  if (!PyAubio_ArrayToCFvec(input, &vec)) {
    10396    return NULL;
    10497  }
    10598
    106   silence_detection = Py_BuildValue("I", aubio_silence_detection(vec, threshold));
     99  silence_detection = Py_BuildValue("I", aubio_silence_detection(&vec, threshold));
    107100  if (silence_detection == NULL) {
    108101    PyErr_SetString (PyExc_ValueError, "failed computing silence_detection");
     
    117110{
    118111  PyObject *input;
    119   fvec_t *vec;
     112  fvec_t vec;
    120113  PyObject *level_detection;
    121114  smpl_t threshold;
    122115
    123   if (!PyArg_ParseTuple (args, "Of:level_detection", &input, &threshold)) {
    124     PyErr_SetString (PyExc_ValueError, "failed parsing arguments");
     116  if (!PyArg_ParseTuple (args, "O" AUBIO_NPY_SMPL_CHR ":level_detection", &input, &threshold)) {
    125117    return NULL;
    126118  }
     
    130122  }
    131123
    132   vec = PyAubio_ArrayToCFvec (input);
    133   if (vec == NULL) {
     124  if (!PyAubio_ArrayToCFvec(input, &vec)) {
    134125    return NULL;
    135126  }
    136127
    137   level_detection = Py_BuildValue("f", aubio_level_detection(vec, threshold));
     128  level_detection = Py_BuildValue(AUBIO_NPY_SMPL_CHR, aubio_level_detection(&vec, threshold));
    138129  if (level_detection == NULL) {
    139130    PyErr_SetString (PyExc_ValueError, "failed computing level_detection");
  • python/ext/py-musicutils.h

    r60fc05b rf264b17  
    1 #ifndef _PY_AUBIO_MUSICUTILS_H_
    2 #define _PY_AUBIO_MUSICUTILS_H_
     1#ifndef PY_AUBIO_MUSICUTILS_H
     2#define PY_AUBIO_MUSICUTILS_H
    33
    44static char Py_aubio_window_doc[] = ""
     
    7272PyObject * Py_aubio_level_detection(PyObject *self, PyObject *args);
    7373
    74 #endif /* _PY_AUBIO_MUSICUTILS_H_ */
     74#endif /* PY_AUBIO_MUSICUTILS_H */
  • python/ext/py-phasevoc.c

    r60fc05b rf264b17  
    1 #include "aubiowraphell.h"
     1#include "aubio-types.h"
    22
    33static char Py_pvoc_doc[] = "pvoc object";
    44
    5 AUBIO_DECLARE(pvoc, uint_t win_s; uint_t hop_s)
    6 
    7 //AUBIO_NEW(pvoc)
     5typedef struct
     6{
     7  PyObject_HEAD
     8  aubio_pvoc_t * o;
     9  uint_t win_s;
     10  uint_t hop_s;
     11  fvec_t vecin;
     12  cvec_t cvecin;
     13  PyObject *output;
     14  cvec_t c_output;
     15  PyObject *routput;
     16  fvec_t c_routput;
     17} Py_pvoc;
     18
     19
    820static PyObject *
    921Py_pvoc_new (PyTypeObject * type, PyObject * args, PyObject * kwds)
     
    5062}
    5163
    52 
    53 AUBIO_INIT(pvoc, self->win_s, self->hop_s)
    54 
    55 AUBIO_DEL(pvoc)
    56 
    57 static PyObject *
     64static int
     65Py_pvoc_init (Py_pvoc * self, PyObject * args, PyObject * kwds)
     66{
     67  self->o = new_aubio_pvoc ( self->win_s, self->hop_s);
     68  if (self->o == NULL) {
     69    PyErr_Format(PyExc_RuntimeError,
     70        "failed creating pvoc with win_s=%d, hop_s=%d",
     71        self->win_s, self->hop_s);
     72    return -1;
     73  }
     74
     75  self->output = new_py_cvec(self->win_s);
     76  self->routput = new_py_fvec(self->hop_s);
     77
     78  return 0;
     79}
     80
     81
     82static void
     83Py_pvoc_del (Py_pvoc *self, PyObject *unused)
     84{
     85  Py_XDECREF(self->output);
     86  Py_XDECREF(self->routput);
     87  if (self->o) {
     88    del_aubio_pvoc(self->o);
     89  }
     90  Py_TYPE(self)->tp_free((PyObject *) self);
     91}
     92
     93
     94static PyObject *
    5895Py_pvoc_do(Py_pvoc * self, PyObject * args)
    5996{
    6097  PyObject *input;
    61   fvec_t *vec;
    62   cvec_t *output;
    6398
    6499  if (!PyArg_ParseTuple (args, "O", &input)) {
     
    66101  }
    67102
    68   vec = PyAubio_ArrayToCFvec (input);
    69 
    70   if (vec == NULL) {
    71     return NULL;
    72   }
    73 
    74   output = new_cvec(self->win_s);
    75 
     103  if (!PyAubio_ArrayToCFvec (input, &(self->vecin) )) {
     104    return NULL;
     105  }
     106
     107  if (self->vecin.length != self->hop_s) {
     108    PyErr_Format(PyExc_ValueError,
     109                 "input fvec has length %d, but pvoc expects length %d",
     110                 self->vecin.length, self->hop_s);
     111    return NULL;
     112  }
     113
     114  Py_INCREF(self->output);
     115  if (!PyAubio_PyCvecToCCvec (self->output, &(self->c_output))) {
     116    return NULL;
     117  }
    76118  // compute the function
    77   aubio_pvoc_do (self->o, vec, output);
    78   return (PyObject *)PyAubio_CCvecToPyCvec(output);
    79 }
    80 
    81 AUBIO_MEMBERS_START(pvoc)
     119  aubio_pvoc_do (self->o, &(self->vecin), &(self->c_output));
     120  return self->output;
     121}
     122
     123static PyMemberDef Py_pvoc_members[] = {
    82124  {"win_s", T_INT, offsetof (Py_pvoc, win_s), READONLY,
    83125    "size of the window"},
    84126  {"hop_s", T_INT, offsetof (Py_pvoc, hop_s), READONLY,
    85127    "size of the hop"},
    86 AUBIO_MEMBERS_STOP(pvoc)
    87 
    88 static PyObject *
     128  { NULL } // sentinel
     129};
     130
     131static PyObject *
    89132Py_pvoc_rdo(Py_pvoc * self, PyObject * args)
    90133{
    91134  PyObject *input;
    92   cvec_t *vec;
    93   fvec_t *output;
    94 
    95135  if (!PyArg_ParseTuple (args, "O", &input)) {
    96136    return NULL;
    97137  }
    98138
    99   vec = PyAubio_ArrayToCCvec (input);
    100 
    101   if (vec == NULL) {
    102     return NULL;
    103   }
    104 
    105   output = new_fvec(self->hop_s);
    106 
     139  if (!PyAubio_PyCvecToCCvec (input, &(self->cvecin) )) {
     140    return NULL;
     141  }
     142
     143  if (self->cvecin.length != self->win_s / 2 + 1) {
     144    PyErr_Format(PyExc_ValueError,
     145                 "input cvec has length %d, but pvoc expects length %d",
     146                 self->cvecin.length, self->win_s / 2 + 1);
     147    return NULL;
     148  }
     149
     150  Py_INCREF(self->routput);
     151  if (!PyAubio_ArrayToCFvec(self->routput, &(self->c_routput)) ) {
     152    return NULL;
     153  }
    107154  // compute the function
    108   aubio_pvoc_rdo (self->o, vec, output);
    109   return (PyObject *)PyAubio_CFvecToArray(output);
     155  aubio_pvoc_rdo (self->o, &(self->cvecin), &(self->c_routput));
     156  return self->routput;
    110157}
    111158
     
    116163};
    117164
    118 AUBIO_TYPEOBJECT(pvoc, "aubio.pvoc")
     165PyTypeObject Py_pvocType = {
     166  PyVarObject_HEAD_INIT (NULL, 0)
     167  "aubio.pvoc",
     168  sizeof (Py_pvoc),
     169  0,
     170  (destructor) Py_pvoc_del,
     171  0,
     172  0,
     173  0,
     174  0,
     175  0,
     176  0,
     177  0,
     178  0,
     179  0,
     180  (ternaryfunc)Py_pvoc_do,
     181  0,
     182  0,
     183  0,
     184  0,
     185  Py_TPFLAGS_DEFAULT,
     186  Py_pvoc_doc,
     187  0,
     188  0,
     189  0,
     190  0,
     191  0,
     192  0,
     193  Py_pvoc_methods,
     194  Py_pvoc_members,
     195  0,
     196  0,
     197  0,
     198  0,
     199  0,
     200  0,
     201  (initproc) Py_pvoc_init,
     202  0,
     203  Py_pvoc_new,
     204  0,
     205  0,
     206  0,
     207  0,
     208  0,
     209  0,
     210  0,
     211  0,
     212  0,
     213};
  • python/ext/py-sink.c

    r60fc05b rf264b17  
    1 #include "aubiowraphell.h"
     1#include "aubio-types.h"
    22
    33typedef struct
     
    88  uint_t samplerate;
    99  uint_t channels;
     10  fvec_t write_data;
     11  fmat_t mwrite_data;
    1012} Py_sink;
    1113
     
    116118  }
    117119  if (self->o == NULL) {
    118     PyErr_SetString (PyExc_StandardError, "error creating sink with this uri");
     120    PyErr_SetString (PyExc_RuntimeError, "error creating sink with this uri");
    119121    return -1;
    120122  }
     
    125127}
    126128
    127 AUBIO_DEL(sink)
     129static void
     130Py_sink_del (Py_sink *self, PyObject *unused)
     131{
     132  del_aubio_sink(self->o);
     133  free(self->mwrite_data.data);
     134  Py_TYPE(self)->tp_free((PyObject *) self);
     135}
    128136
    129137/* function Py_sink_do */
     
    135143
    136144  /* input vectors prototypes */
    137   fvec_t* write_data;
    138145  uint_t write;
    139146
     
    143150  }
    144151
    145 
    146152  /* input vectors parsing */
    147   write_data = PyAubio_ArrayToCFvec (write_data_obj);
    148 
    149   if (write_data == NULL) {
    150     return NULL;
    151   }
    152 
    153 
    154 
     153  if (!PyAubio_ArrayToCFvec(write_data_obj, &(self->write_data))) {
     154    return NULL;
     155  }
    155156
    156157
    157158  /* compute _do function */
    158   aubio_sink_do (self->o, write_data, write);
     159  aubio_sink_do (self->o, &(self->write_data), write);
    159160
    160161  Py_RETURN_NONE;
     
    169170
    170171  /* input vectors prototypes */
    171   fmat_t * write_data;
    172172  uint_t write;
    173173
     
    179179
    180180  /* input vectors parsing */
    181   write_data = PyAubio_ArrayToCFmat (write_data_obj);
    182 
    183   if (write_data == NULL) {
    184     return NULL;
    185   }
    186 
    187 
    188 
    189 
     181  if (!PyAubio_ArrayToCFmat(write_data_obj, &(self->mwrite_data))) {
     182    return NULL;
     183  }
    190184
    191185  /* compute _do function */
    192   aubio_sink_do_multi (self->o, write_data, write);
     186  aubio_sink_do_multi (self->o, &(self->mwrite_data), write);
    193187  Py_RETURN_NONE;
    194188}
    195189
    196 AUBIO_MEMBERS_START(sink)
     190static PyMemberDef Py_sink_members[] = {
    197191  {"uri", T_STRING, offsetof (Py_sink, uri), READONLY,
    198192    "path at which the sink was created"},
     
    201195  {"channels", T_INT, offsetof (Py_sink, channels), READONLY,
    202196    "number of channels with which the sink was created"},
    203 AUBIO_MEMBERS_STOP(sink)
     197  { NULL } // sentinel
     198};
    204199
    205200static PyObject *
     
    217212};
    218213
    219 AUBIO_TYPEOBJECT(sink, "aubio.sink")
     214PyTypeObject Py_sinkType = {
     215  PyVarObject_HEAD_INIT (NULL, 0)
     216  "aubio.sink",
     217  sizeof (Py_sink),
     218  0,
     219  (destructor) Py_sink_del,
     220  0,
     221  0,
     222  0,
     223  0,
     224  0,
     225  0,
     226  0,
     227  0,
     228  0,
     229  (ternaryfunc)Py_sink_do,
     230  0,
     231  0,
     232  0,
     233  0,
     234  Py_TPFLAGS_DEFAULT,
     235  Py_sink_doc,
     236  0,
     237  0,
     238  0,
     239  0,
     240  0,
     241  0,
     242  Py_sink_methods,
     243  Py_sink_members,
     244  0,
     245  0,
     246  0,
     247  0,
     248  0,
     249  0,
     250  (initproc) Py_sink_init,
     251  0,
     252  Py_sink_new,
     253  0,
     254  0,
     255  0,
     256  0,
     257  0,
     258  0,
     259  0,
     260  0,
     261  0,
     262};
  • python/ext/py-source.c

    r60fc05b rf264b17  
    1 #include "aubiowraphell.h"
     1#include "aubio-types.h"
    22
    33typedef struct
     
    99  uint_t channels;
    1010  uint_t hop_size;
     11  uint_t duration;
     12  PyObject *read_to;
     13  fvec_t c_read_to;
     14  PyObject *mread_to;
     15  fmat_t c_mread_to;
    1116} Py_source;
    1217
     
    136141  self->o = new_aubio_source ( self->uri, self->samplerate, self->hop_size );
    137142  if (self->o == NULL) {
    138     char_t errstr[30 + strlen(self->uri)];
    139     sprintf(errstr, "error creating source with %s", self->uri);
    140     PyErr_SetString (PyExc_StandardError, errstr);
     143    PyErr_Format (PyExc_RuntimeError, "error creating source with \"%s\"",
     144        self->uri);
    141145    return -1;
    142146  }
     
    145149    self->channels = aubio_source_get_channels ( self->o );
    146150  }
     151  self->duration = aubio_source_get_duration ( self->o );
     152
     153  self->read_to = new_py_fvec(self->hop_size);
     154  self->mread_to = new_py_fmat(self->channels, self->hop_size);
    147155
    148156  return 0;
    149157}
    150158
    151 AUBIO_DEL(source)
     159static void
     160Py_source_del (Py_source *self, PyObject *unused)
     161{
     162  if (self->o) {
     163    del_aubio_source(self->o);
     164    free(self->c_mread_to.data);
     165  }
     166  Py_XDECREF(self->read_to);
     167  Py_XDECREF(self->mread_to);
     168  Py_TYPE(self)->tp_free((PyObject *) self);
     169}
     170
    152171
    153172/* function Py_source_do */
     
    155174Py_source_do(Py_source * self, PyObject * args)
    156175{
    157 
    158 
    159   /* output vectors prototypes */
    160   fvec_t* read_to;
     176  PyObject *outputs;
    161177  uint_t read;
    162 
    163 
    164 
    165 
    166 
    167 
    168   /* creating output read_to as a new_fvec of length self->hop_size */
    169   read_to = new_fvec (self->hop_size);
    170178  read = 0;
    171179
    172 
     180  Py_INCREF(self->read_to);
     181  if (!PyAubio_ArrayToCFvec(self->read_to, &(self->c_read_to))) {
     182    return NULL;
     183  }
    173184  /* compute _do function */
    174   aubio_source_do (self->o, read_to, &read);
    175 
    176   PyObject *outputs = PyList_New(0);
    177   PyList_Append( outputs, (PyObject *)PyAubio_CFvecToArray (read_to));
    178   //del_fvec (read_to);
    179   PyList_Append( outputs, (PyObject *)PyInt_FromLong (read));
     185  aubio_source_do (self->o, &(self->c_read_to), &read);
     186
     187  outputs = PyTuple_New(2);
     188  PyTuple_SetItem( outputs, 0, self->read_to );
     189  PyTuple_SetItem( outputs, 1, (PyObject *)PyLong_FromLong(read));
    180190  return outputs;
    181191}
     
    185195Py_source_do_multi(Py_source * self, PyObject * args)
    186196{
    187 
    188 
    189   /* output vectors prototypes */
    190   fmat_t* read_to;
     197  PyObject *outputs;
    191198  uint_t read;
    192 
    193 
    194 
    195 
    196 
    197 
    198   /* creating output read_to as a new_fvec of length self->hop_size */
    199   read_to = new_fmat (self->channels, self->hop_size);
    200199  read = 0;
    201200
    202 
     201  Py_INCREF(self->mread_to);
     202  if (!PyAubio_ArrayToCFmat(self->mread_to,  &(self->c_mread_to))) {
     203    return NULL;
     204  }
    203205  /* compute _do function */
    204   aubio_source_do_multi (self->o, read_to, &read);
    205 
    206   PyObject *outputs = PyList_New(0);
    207   PyList_Append( outputs, (PyObject *)PyAubio_CFmatToArray (read_to));
    208   //del_fvec (read_to);
    209   PyList_Append( outputs, (PyObject *)PyInt_FromLong (read));
     206  aubio_source_do_multi (self->o, &(self->c_mread_to), &read);
     207
     208  outputs = PyTuple_New(2);
     209  PyTuple_SetItem( outputs, 0, self->mread_to);
     210  PyTuple_SetItem( outputs, 1, (PyObject *)PyLong_FromLong(read));
    210211  return outputs;
    211212}
    212213
    213 AUBIO_MEMBERS_START(source)
     214static PyMemberDef Py_source_members[] = {
    214215  {"uri", T_STRING, offsetof (Py_source, uri), READONLY,
    215216    "path at which the source was created"},
     
    220221  {"hop_size", T_INT, offsetof (Py_source, hop_size), READONLY,
    221222    "number of consecutive frames that will be read at each do or do_multi call"},
    222 AUBIO_MEMBERS_STOP(source)
    223 
     223  {"duration", T_INT, offsetof (Py_source, duration), READONLY,
     224    "total number of frames in the source (estimated)"},
     225  { NULL } // sentinel
     226};
    224227
    225228static PyObject *
     
    227230{
    228231  uint_t tmp = aubio_source_get_samplerate (self->o);
    229   return (PyObject *)PyInt_FromLong (tmp);
     232  return (PyObject *)PyLong_FromLong (tmp);
    230233}
    231234
     
    234237{
    235238  uint_t tmp = aubio_source_get_channels (self->o);
    236   return (PyObject *)PyInt_FromLong (tmp);
     239  return (PyObject *)PyLong_FromLong (tmp);
    237240}
    238241
     
    249252  uint_t err = 0;
    250253
    251   uint_t position;
     254  int position;
    252255  if (!PyArg_ParseTuple (args, "I", &position)) {
     256    return NULL;
     257  }
     258
     259  if (position < 0) {
     260    PyErr_Format(PyExc_ValueError,
     261        "error when seeking in source: can not seek to negative value %d",
     262        position);
    253263    return NULL;
    254264  }
     
    279289};
    280290
    281 AUBIO_TYPEOBJECT(source, "aubio.source")
     291PyTypeObject Py_sourceType = {
     292  PyVarObject_HEAD_INIT (NULL, 0)
     293  "aubio.source",
     294  sizeof (Py_source),
     295  0,
     296  (destructor) Py_source_del,
     297  0,
     298  0,
     299  0,
     300  0,
     301  0,
     302  0,
     303  0,
     304  0,
     305  0,
     306  (ternaryfunc)Py_source_do,
     307  0,
     308  0,
     309  0,
     310  0,
     311  Py_TPFLAGS_DEFAULT,
     312  Py_source_doc,
     313  0,
     314  0,
     315  0,
     316  0,
     317  0,
     318  0,
     319  Py_source_methods,
     320  Py_source_members,
     321  0,
     322  0,
     323  0,
     324  0,
     325  0,
     326  0,
     327  (initproc) Py_source_init,
     328  0,
     329  Py_source_new,
     330  0,
     331  0,
     332  0,
     333  0,
     334  0,
     335  0,
     336  0,
     337  0,
     338  0,
     339};
  • python/ext/ufuncs.c

    r60fc05b rf264b17  
    8585{
    8686  int err = 0;
     87  PyObject *dict, *f, *g, *h;
    8788
    8889  err = _import_umath ();
     
    9293  }
    9394
    94   PyObject *f, *dict;
    9595  dict = PyModule_GetDict(m);
    9696  f = PyUFunc_FromFuncAndData(Py_aubio_unary_functions, Py_unwrap2pi_data, Py_aubio_unary_types,
     
    100100  Py_DECREF(f);
    101101
    102   PyObject *g;
    103102  g = PyUFunc_FromFuncAndData(Py_aubio_unary_functions, Py_freqtomidi_data, Py_aubio_unary_types,
    104103          Py_aubio_unary_n_types, Py_aubio_unary_n_inputs, Py_aubio_unary_n_outputs,
     
    107106  Py_DECREF(g);
    108107
    109   PyObject *h;
    110108  h = PyUFunc_FromFuncAndData(Py_aubio_unary_functions, Py_miditofreq_data, Py_aubio_unary_types,
    111109          Py_aubio_unary_n_types, Py_aubio_unary_n_inputs, Py_aubio_unary_n_outputs,
  • python/lib/aubio/__init__.py

    r60fc05b rf264b17  
    22
    33import numpy
    4 from _aubio import *
    5 from midiconv import *
    6 from slicing import *
     4from ._aubio import *
     5from ._aubio import float_type
     6from .midiconv import *
     7from .slicing import *
    78
    89class fvec(numpy.ndarray):
    9     " a simple numpy array holding a vector of float32 "
    10     def __new__(self, length = 1024, **kwargs):
    11         self.length = length
    12         if type(length) == type([]):
    13             return numpy.array(length, dtype='float32', **kwargs)
    14         return numpy.zeros(length, dtype='float32', **kwargs)
     10    """a numpy vector holding audio samples"""
     11
     12    def __new__(cls, input_arg=1024, **kwargs):
     13        if isinstance(input_arg, int):
     14            if input_arg == 0:
     15                raise ValueError("vector length of 1 or more expected")
     16            return numpy.zeros(input_arg, dtype=float_type, **kwargs)
     17        else:
     18            return numpy.array(input_arg, dtype=float_type, **kwargs)
  • python/lib/aubio/midiconv.py

    r60fc05b rf264b17  
    11# -*- coding: utf-8 -*-
     2""" utilities to convert midi note number to and from note names """
     3
     4__all__ = ['note2midi', 'midi2note', 'freq2note']
     5
     6import sys
     7py3 = sys.version_info[0] == 3
     8if py3:
     9    str_instances = str
     10    int_instances = int
     11else:
     12    str_instances = (str, unicode)
     13    int_instances = (int, long)
    214
    315def note2midi(note):
    416    " convert note name to midi note number, e.g. [C-1, G9] -> [0, 127] "
    517    _valid_notenames = {'C': 0, 'D': 2, 'E': 4, 'F': 5, 'G': 7, 'A': 9, 'B': 11}
    6     _valid_modifiers = {None: 0, u'♮': 0, '#': +1, u'♯': +1, u'\udd2a': +2, 'b': -1, u'♭': -1, u'\ufffd': -2}
     18    _valid_modifiers = {None: 0, u'♮': 0, '#': +1, u'♯': +1, u'\udd2a': +2,
     19                        'b': -1, u'♭': -1, u'\ufffd': -2}
    720    _valid_octaves = range(-1, 10)
    8     if type(note) not in (str, unicode):
    9         raise TypeError, "a string is required, got %s" % note
    10     if not (1 < len(note) < 5):
    11         raise ValueError, "string of 2 to 4 characters expected, got %d (%s)" % (len(note), note)
     21    if not isinstance(note, str_instances):
     22        raise TypeError("a string is required, got %s (%s)" % (note, str(type(note))))
     23    if len(note) not in range(2, 5):
     24        raise ValueError("string of 2 to 4 characters expected, got %d (%s)" \
     25                         % (len(note), note))
    1226    notename, modifier, octave = [None]*3
    1327
     
    2741
    2842    if notename not in _valid_notenames:
    29         raise ValueError, "%s is not a valid note name" % notename
     43        raise ValueError("%s is not a valid note name" % notename)
    3044    if modifier not in _valid_modifiers:
    31         raise ValueError, "%s is not a valid modifier" % modifier
     45        raise ValueError("%s is not a valid modifier" % modifier)
    3246    if octave not in _valid_octaves:
    33         raise ValueError, "%s is not a valid octave" % octave
     47        raise ValueError("%s is not a valid octave" % octave)
    3448
    3549    midi = 12 + octave * 12 + _valid_notenames[notename] + _valid_modifiers[modifier]
    3650    if midi > 127:
    37         raise ValueError, "%s is outside of the range C-2 to G8" % note
     51        raise ValueError("%s is outside of the range C-2 to G8" % note)
    3852    return midi
    3953
    4054def midi2note(midi):
    4155    " convert midi note number to note name, e.g. [0, 127] -> [C-1, G9] "
    42     if type(midi) != int:
    43         raise TypeError, "an integer is required, got %s" % midi
    44     if not (-1 < midi < 128):
    45         raise ValueError, "an integer between 0 and 127 is excepted, got %d" % midi
    46     midi = int(midi)
     56    if not isinstance(midi, int_instances):
     57        raise TypeError("an integer is required, got %s" % midi)
     58    if midi not in range(0, 128):
     59        raise ValueError("an integer between 0 and 127 is excepted, got %d" % midi)
    4760    _valid_notenames = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']
    48     return _valid_notenames[midi % 12] + str( midi / 12 - 1)
     61    return _valid_notenames[midi % 12] + str(int(midi / 12) - 1)
    4962
    5063def freq2note(freq):
     64    " convert frequency in Hz to nearest note name, e.g. [0, 22050.] -> [C-1, G9] "
    5165    from aubio import freqtomidi
    5266    return midi2note(int(freqtomidi(freq)))
  • python/lib/aubio/slicing.py

    r60fc05b rf264b17  
     1"""utility routines to slice sound files at given timestamps"""
     2
     3import os
    14from aubio import source, sink
    2 import os
    35
    4 max_timestamp = 1e120
     6_max_timestamp = 1e120
    57
    6 def slice_source_at_stamps(source_file, timestamps, timestamps_end = None,
    7         output_dir = None,
    8         samplerate = 0,
    9         hopsize = 256):
     8def slice_source_at_stamps(source_file, timestamps, timestamps_end=None,
     9                           output_dir=None, samplerate=0, hopsize=256):
     10    """ slice a sound file at given timestamps """
    1011
    11     if timestamps == None or len(timestamps) == 0:
    12         raise ValueError ("no timestamps given")
     12    if timestamps is None or len(timestamps) == 0:
     13        raise ValueError("no timestamps given")
    1314
    1415    if timestamps[0] != 0:
    1516        timestamps = [0] + timestamps
    16         if timestamps_end != None:
     17        if timestamps_end is not None:
    1718            timestamps_end = [timestamps[1] - 1] + timestamps_end
    1819
    19     if timestamps_end != None:
     20    if timestamps_end is not None:
    2021        if len(timestamps_end) != len(timestamps):
    21             raise ValueError ("len(timestamps_end) != len(timestamps)")
     22            raise ValueError("len(timestamps_end) != len(timestamps)")
    2223    else:
    23         timestamps_end = [t - 1 for t in timestamps[1:] ] + [ max_timestamp ]
     24        timestamps_end = [t - 1 for t in timestamps[1:]] + [_max_timestamp]
    2425
    25     regions = zip(timestamps, timestamps_end)
     26    regions = list(zip(timestamps, timestamps_end))
    2627    #print regions
    2728
    28     source_base_name, source_ext = os.path.splitext(os.path.basename(source_file))
    29     if output_dir != None:
     29    source_base_name, _ = os.path.splitext(os.path.basename(source_file))
     30    if output_dir is not None:
    3031        if not os.path.isdir(output_dir):
    3132            os.makedirs(output_dir)
     
    3334
    3435    def new_sink_name(source_base_name, timestamp, samplerate):
     36        """ create a sink based on a timestamp in samples, converted in seconds """
    3537        timestamp_seconds = timestamp / float(samplerate)
    3638        return source_base_name + "_%011.6f" % timestamp_seconds + '.wav'
    3739
    38     # reopen source file
    39     s = source(source_file, samplerate, hopsize)
    40     samplerate = s.get_samplerate()
     40    # open source file
     41    _source = source(source_file, samplerate, hopsize)
     42    samplerate = _source.samplerate
    4143
    4244    total_frames = 0
     
    4547    while True:
    4648        # get hopsize new samples from source
    47         vec, read = s.do_multi()
     49        vec, read = _source.do_multi()
    4850        # if the total number of frames read will exceed the next region start
    4951        if len(regions) and total_frames + read >= regions[0][0]:
     
    5456            new_sink_path = new_sink_name(source_base_name, start_stamp, samplerate)
    5557            # create its sink
    56             g = sink(new_sink_path, samplerate, s.channels)
     58            _sink = sink(new_sink_path, samplerate, _source.channels)
    5759            # create a dictionary containing all this
    58             new_slice = {'start_stamp': start_stamp, 'end_stamp': end_stamp, 'sink': g}
     60            new_slice = {'start_stamp': start_stamp, 'end_stamp': end_stamp, 'sink': _sink}
    5961            # append the dictionary to the current list of slices
    6062            slices.append(new_slice)
     
    6365            start_stamp = current_slice['start_stamp']
    6466            end_stamp = current_slice['end_stamp']
    65             g = current_slice['sink']
     67            _sink = current_slice['sink']
    6668            # sample index to start writing from new source vector
    6769            start = max(start_stamp - total_frames, 0)
     
    7375                if remaining > start:
    7476                    # write remaining samples from current region
    75                     g.do_multi(vec[:,start:remaining], remaining - start)
     77                    _sink.do_multi(vec[:, start:remaining], remaining - start)
    7678                    #print "closing region", "remaining", remaining
    7779                    # close this file
    78                     g.close()
     80                    _sink.close()
    7981            elif read > start:
    8082                # write all the samples
    81                 g.do_multi(vec[:,start:read], read - start)
     83                _sink.do_multi(vec[:, start:read], read - start)
    8284        total_frames += read
    83         if read < hopsize: break
     85        if read < hopsize:
     86            break
  • python/scripts/aubiocut

    r60fc05b rf264b17  
    135135            options.source_file = args[0]
    136136        else:
    137             print "no file name given\n", usage
     137            print ("no file name given\n" + usage)
    138138            sys.exit(1)
    139139    return options, args
     
    172172        if o(samples):
    173173            timestamps.append (o.get_last())
    174             if options.verbose: print "%.4f" % o.get_last_s()
     174            if options.verbose: print ("%.4f" % o.get_last_s())
    175175        total_frames += read
    176176        if read < hopsize: break
     
    189189        timestamps_end = None
    190190        if options.cut_until_nslices and options.cut_until_nsamples:
    191             print "warning: using cut_until_nslices, but cut_until_nsamples is set"
     191            print ("warning: using cut_until_nslices, but cut_until_nsamples is set")
    192192        if options.cut_until_nsamples:
    193193            timestamps_end = [t + options.cut_until_nsamples for t in timestamps[1:]]
  • python/tests/run_all_tests

    r60fc05b rf264b17  
    22
    33if __name__ == '__main__':
    4   import os, sys, unittest
    5   def load_test():
    6     # get relevant files
    7     curdir = os.path.dirname(sys.argv[0])
    8     if curdir == '': curdir = '.'
    9     files = os.listdir(curdir)
    10     modfiles = filter (lambda y: y.endswith('.py'), files)
    11     modfiles = filter (lambda f: f.startswith('test_'), modfiles)
    12     modfiles = filter (lambda y: not 'beattracking' in y, modfiles)
    13     modfiles = filter (lambda y: not 'hist' in y, modfiles)
    14     modfiles = filter (lambda y: not 'scale' in y, modfiles)
    15     modfiles = filter (lambda y: not 'peakpicker' in y, modfiles)
    16     # get module names
    17     modnames = map (lambda x: os.path.splitext(x)[0], modfiles)
    18     # import them
    19     modules = map (__import__, modnames)
    20     # create a test suites from the imported module
    21     load_from_module = unittest.defaultTestLoader.loadTestsFromModule
    22     tests = map(load_from_module, modules)
    23     return unittest.TestSuite(tests)
    24   unittest.main(defaultTest = 'load_test')
     4    import nose2.main
     5    nose2.discover()
  • python/tests/test_aubio.py

    r60fc05b rf264b17  
    11#! /usr/bin/env python
    22
    3 from numpy.testing import TestCase, run_module_suite
     3from unittest import main
     4from numpy.testing import TestCase
    45
    56class aubiomodule_test_case(TestCase):
    67
    7   def test_import(self):
    8     """ try importing aubio """
    9     import aubio
     8    def test_import(self):
     9        """ try importing aubio """
     10        import aubio
    1011
    1112if __name__ == '__main__':
    12   from unittest import main
    13   main()
     13    main()
    1414
  • python/tests/test_cvec.py

    r60fc05b rf264b17  
    11#! /usr/bin/env python
    22
    3 from numpy.testing import TestCase, run_module_suite
    4 from numpy.testing import assert_equal, assert_almost_equal
    5 from aubio import cvec
    6 from numpy import array, shape, pi
     3from unittest import main
     4import numpy as np
     5from numpy.testing import TestCase, assert_equal
     6from aubio import cvec, fvec, float_type
     7
     8wrong_type = 'float32' if float_type == 'float64' else 'float64'
    79
    810class aubio_cvec_test_case(TestCase):
     
    1012    def test_vector_created_with_zeroes(self):
    1113        a = cvec(10)
    12         shape(a.norm)
    13         shape(a.phas)
    14         a.norm[0]
     14        assert_equal(a.norm.shape[0], 10 / 2 + 1)
     15        assert_equal(a.phas.shape[0], 10 / 2 + 1)
     16        _ = a.norm[0]
    1517        assert_equal(a.norm, 0.)
    1618        assert_equal(a.phas, 0.)
     
    4244    def test_assign_cvec_phas_slice(self):
    4345        spec = cvec(1024)
    44         spec.phas[39:-1] = -pi
     46        spec.phas[39:-1] = -np.pi
    4547        assert_equal(spec.phas[0:39], 0)
    46         assert_equal(spec.phas[39:-1], -pi)
     48        assert_equal(spec.phas[39:-1], -np.pi)
    4749        assert_equal(spec.norm, 0)
    4850
     51    def test_assign_cvec_with_other_cvec(self):
     52        """ check dest cvec is still reachable after source was deleted """
     53        spec = cvec(1024)
     54        a = np.random.rand(1024//2+1).astype(float_type)
     55        b = np.random.rand(1024//2+1).astype(float_type)
     56        spec.norm = a
     57        spec.phas = b
     58        new_spec = spec
     59        del spec
     60        assert_equal(a, new_spec.norm)
     61        assert_equal(b, new_spec.phas)
     62        assert_equal(id(a), id(new_spec.norm))
     63        assert_equal(id(b), id(new_spec.phas))
     64
     65    def test_pass_to_numpy(self):
     66        spec = cvec(1024)
     67        norm = spec.norm
     68        phas = spec.phas
     69        del spec
     70        new_spec = cvec(1024)
     71        new_spec.norm = norm
     72        new_spec.phas = phas
     73        assert_equal(norm, new_spec.norm)
     74        assert_equal(phas, new_spec.phas)
     75        assert_equal(id(norm), id(new_spec.norm))
     76        assert_equal(id(phas), id(new_spec.phas))
     77        del norm
     78        del phas
     79        assert_equal(new_spec.norm, 0.)
     80        assert_equal(new_spec.phas, 0.)
     81        del new_spec
     82
     83    def test_assign_norm_too_large(self):
     84        a = cvec(512)
     85        b = fvec(512//2+1 + 4)
     86        with self.assertRaises(ValueError):
     87            a.norm = b
     88
     89    def test_assign_norm_too_small(self):
     90        a = cvec(512)
     91        b = fvec(512//2+1 - 4)
     92        with self.assertRaises(ValueError):
     93            a.norm = b
     94
     95    def test_assign_phas_too_large(self):
     96        a = cvec(512)
     97        b = fvec(512//2+1 + 4)
     98        with self.assertRaises(ValueError):
     99            a.phas = b
     100
     101    def test_assign_phas_too_small(self):
     102        a = cvec(512)
     103        b = fvec(512//2+1 - 4)
     104        with self.assertRaises(ValueError):
     105            a.phas = b
     106
     107    def test_cvec_repr(self):
     108        win_s = 512
     109        c = cvec(win_s)
     110        expected_repr = "aubio cvec of {:d} elements".format(win_s//2+1)
     111        self.assertEqual(repr(c), expected_repr)
     112
     113class aubio_cvec_wrong_norm_input(TestCase):
     114
     115    def test_wrong_length(self):
     116        with self.assertRaises(ValueError):
     117            cvec(-1)
     118
     119    def test_set_norm_with_scalar(self):
     120        a = cvec(512)
     121        with self.assertRaises(ValueError):
     122            a.norm = 1
     123
     124    def test_set_norm_with_scalar_array(self):
     125        a = cvec(512)
     126        with self.assertRaises(ValueError):
     127            a.norm = np.ndarray(1, dtype = 'int')
     128
     129    def test_set_norm_with_int_array(self):
     130        a = cvec(512)
     131        with self.assertRaises(ValueError):
     132            a.norm = np.zeros(512//2+1, dtype = 'int')
     133
     134    def test_set_norm_with_wrong_float_array(self):
     135        a = cvec(512)
     136        with self.assertRaises(ValueError):
     137            a.norm = np.zeros(512//2+1, dtype = wrong_type)
     138
     139    def test_set_norm_with_wrong_2d_array(self):
     140        a = cvec(512)
     141        with self.assertRaises(ValueError):
     142            a.norm = np.zeros((512//2+1, 2), dtype = float_type)
     143
    49144if __name__ == '__main__':
    50     from unittest import main
    51145    main()
  • python/tests/test_fft.py

    r60fc05b rf264b17  
    11#! /usr/bin/env python
    22
    3 from numpy.testing import TestCase, run_module_suite
     3from unittest import main
     4from numpy.testing import TestCase
    45from numpy.testing import assert_equal, assert_almost_equal
     6import numpy as np
    57from aubio import fvec, fft, cvec
    6 from numpy import array, shape
    7 from math import pi
     8from math import pi, floor
     9from random import random
    810
    911class aubio_fft_test_case(TestCase):
     
    2123        f = fft (win_s)
    2224        fftgrain = f (timegrain)
    23         assert_equal (shape(fftgrain.norm), (win_s/2+1,))
    24         assert_equal (shape(fftgrain.phas), (win_s/2+1,))
     25        del f
     26        assert_equal (fftgrain.norm.shape, (win_s/2+1,))
     27        assert_equal (fftgrain.phas.shape, (win_s/2+1,))
    2528
    2629    def test_zeros(self):
     
    3538    def test_impulse(self):
    3639        """ check the transform of one impulse at a random place """
    37         from random import random
    38         from math import floor
    3940        win_s = 256
    40         i = floor(random()*win_s)
     41        i = int(floor(random()*win_s))
    4142        impulse = pi * random()
    4243        f = fft(win_s)
     
    5051
    5152    def test_impulse_negative(self):
    52         """ check the transform of one impulse at a random place """
    53         from random import random
    54         from math import floor
     53        """ check the transform of a negative impulse at a random place """
    5554        win_s = 256
    56         i = 0
    57         impulse = -10.
     55        i = int(floor(random()*win_s))
     56        impulse = -.1
    5857        f = fft(win_s)
    5958        timegrain = fvec(win_s)
     59        timegrain[0] = 0
    6060        timegrain[i] = impulse
    6161        fftgrain = f ( timegrain )
    6262        #self.plot_this ( fftgrain.phas )
    63         assert_almost_equal ( fftgrain.norm, abs(impulse), decimal = 6 )
     63        assert_almost_equal ( fftgrain.norm, abs(impulse), decimal = 5 )
    6464        if impulse < 0:
    6565            # phase can be pi or -pi, as it is not unwrapped
    66             assert_almost_equal ( abs(fftgrain.phas[1:-1]) , pi, decimal = 6 )
     66            #assert_almost_equal ( abs(fftgrain.phas[1:-1]) , pi, decimal = 6 )
    6767            assert_almost_equal ( fftgrain.phas[0], pi, decimal = 6)
    68             assert_almost_equal ( fftgrain.phas[-1], pi, decimal = 6)
     68            assert_almost_equal ( np.fmod(fftgrain.phas[-1], pi), 0, decimal = 6)
    6969        else:
    70             assert_equal ( fftgrain.phas[1:-1] == 0, True)
    71             assert_equal ( fftgrain.phas[0] == 0, True)
    72             assert_equal ( fftgrain.phas[-1] == 0, True)
     70            #assert_equal ( fftgrain.phas[1:-1] == 0, True)
     71            assert_equal ( fftgrain.phas[0], 0)
     72            assert_almost_equal ( np.fmod(fftgrain.phas[-1], pi), 0, decimal = 6)
    7373        # now check the resynthesis
    7474        synthgrain = f.rdo ( fftgrain )
     
    9696        """ check running fft.rdo before fft.do works """
    9797        win_s = 1024
    98         impulse = pi
    9998        f = fft(win_s)
    10099        fftgrain = cvec(win_s)
     
    107106        show ()
    108107
     108    def test_local_fftgrain(self):
     109        """ check aubio.fft() result can be accessed after deletion """
     110        def compute_grain(impulse):
     111            win_s = 1024
     112            timegrain = fvec(win_s)
     113            timegrain[0] = impulse
     114            f = fft(win_s)
     115            fftgrain = f ( timegrain )
     116            return fftgrain
     117        impulse = pi
     118        fftgrain = compute_grain(impulse)
     119        assert_equal ( fftgrain.phas[0], 0)
     120        assert_almost_equal ( fftgrain.phas[1], 0)
     121        assert_almost_equal ( fftgrain.norm[0], impulse, decimal = 6 )
     122
     123    def test_local_reconstruct(self):
     124        """ check aubio.fft.rdo() result can be accessed after deletion """
     125        def compute_grain(impulse):
     126            win_s = 1024
     127            timegrain = fvec(win_s)
     128            timegrain[0] = impulse
     129            f = fft(win_s)
     130            fftgrain = f ( timegrain )
     131            r = f.rdo(fftgrain)
     132            return r
     133        impulse = pi
     134        r = compute_grain(impulse)
     135        assert_almost_equal ( r[0], impulse, decimal = 6)
     136        assert_almost_equal ( r[1:], 0)
     137
     138    def test_large_input_timegrain(self):
     139        win_s = 1024
     140        f = fft(win_s)
     141        t = fvec(win_s + 1)
     142        with self.assertRaises(ValueError):
     143            f(t)
     144
     145    def test_small_input_timegrain(self):
     146        win_s = 1024
     147        f = fft(win_s)
     148        t = fvec(1)
     149        with self.assertRaises(ValueError):
     150            f(t)
     151
     152    def test_large_input_fftgrain(self):
     153        win_s = 1024
     154        f = fft(win_s)
     155        s = cvec(win_s + 5)
     156        with self.assertRaises(ValueError):
     157            f.rdo(s)
     158
     159    def test_small_input_fftgrain(self):
     160        win_s = 1024
     161        f = fft(win_s)
     162        s = cvec(16)
     163        with self.assertRaises(ValueError):
     164            f.rdo(s)
     165
     166class aubio_fft_wrong_params(TestCase):
     167
     168    def test_wrong_buf_size(self):
     169        win_s = -1
     170        with self.assertRaises(ValueError):
     171            fft(win_s)
     172
     173    def test_buf_size_not_power_of_two(self):
     174        # when compiled with fftw3, aubio supports non power of two fft sizes
     175        win_s = 320
     176        try:
     177            with self.assertRaises(RuntimeError):
     178                fft(win_s)
     179        except AssertionError:
     180            self.skipTest('creating aubio.fft with size %d did not fail' % win_s)
     181
     182    def test_buf_size_too_small(self):
     183        win_s = 1
     184        with self.assertRaises(RuntimeError):
     185            fft(win_s)
     186
    109187if __name__ == '__main__':
    110     from unittest import main
    111188    main()
    112 
  • python/tests/test_filter.py

    r60fc05b rf264b17  
    11#! /usr/bin/env python
    22
     3from unittest import main
    34from numpy.testing import TestCase, assert_equal, assert_almost_equal
    45from aubio import fvec, digital_filter
    5 from numpy import array
    66from utils import array_from_text_file
    77
    88class aubio_filter_test_case(TestCase):
    99
    10   def test_members(self):
    11     f = digital_filter()
    12     assert_equal (f.order, 7)
    13     f = digital_filter(5)
    14     assert_equal (f.order, 5)
    15     f(fvec())
    16  
    17   def test_cweighting_error(self):
    18     f = digital_filter (2)
    19     self.assertRaises ( ValueError, f.set_c_weighting, 44100 )
    20     f = digital_filter (8)
    21     self.assertRaises ( ValueError, f.set_c_weighting, 44100 )
    22     f = digital_filter (5)
    23     self.assertRaises ( ValueError, f.set_c_weighting, 4000 )
    24     f = digital_filter (5)
    25     self.assertRaises ( ValueError, f.set_c_weighting, 193000 )
    26     f = digital_filter (7)
    27     self.assertRaises ( ValueError, f.set_a_weighting, 193000 )
    28     f = digital_filter (5)
    29     self.assertRaises ( ValueError, f.set_a_weighting, 192000 )
     10    def test_members(self):
     11        f = digital_filter()
     12        assert_equal (f.order, 7)
     13        f = digital_filter(5)
     14        assert_equal (f.order, 5)
     15        f(fvec())
    3016
    31   def test_c_weighting(self):
    32     expected = array_from_text_file('c_weighting_test_simple.expected')
    33     f = digital_filter(5)
    34     f.set_c_weighting(44100)
    35     v = fvec(32)
    36     v[12] = .5
    37     u = f(v)
    38     assert_almost_equal (expected[1], u)
     17    def test_cweighting_error(self):
     18        f = digital_filter (2)
     19        self.assertRaises ( ValueError, f.set_c_weighting, 44100 )
     20        f = digital_filter (8)
     21        self.assertRaises ( ValueError, f.set_c_weighting, 44100 )
     22        f = digital_filter (5)
     23        self.assertRaises ( ValueError, f.set_c_weighting, 4000 )
     24        f = digital_filter (5)
     25        self.assertRaises ( ValueError, f.set_c_weighting, 193000 )
     26        f = digital_filter (7)
     27        self.assertRaises ( ValueError, f.set_a_weighting, 193000 )
     28        f = digital_filter (5)
     29        self.assertRaises ( ValueError, f.set_a_weighting, 192000 )
    3930
    40   def test_c_weighting_8000(self):
    41     expected = array_from_text_file('c_weighting_test_simple_8000.expected')
    42     f = digital_filter(5)
    43     f.set_c_weighting(8000)
    44     v = fvec(32)
    45     v[12] = .5
    46     u = f(v)
    47     assert_almost_equal (expected[1], u)
     31    def test_c_weighting(self):
     32        expected = array_from_text_file('c_weighting_test_simple.expected')
     33        f = digital_filter(5)
     34        f.set_c_weighting(44100)
     35        v = fvec(32)
     36        v[12] = .5
     37        u = f(v)
     38        assert_almost_equal (expected[1], u)
    4839
    49   def test_a_weighting(self):
    50     expected = array_from_text_file('a_weighting_test_simple.expected')
    51     f = digital_filter(7)
    52     f.set_a_weighting(44100)
    53     v = fvec(32)
    54     v[12] = .5
    55     u = f(v)
    56     assert_almost_equal (expected[1], u)
     40    def test_c_weighting_8000(self):
     41        expected = array_from_text_file('c_weighting_test_simple_8000.expected')
     42        f = digital_filter(5)
     43        f.set_c_weighting(8000)
     44        v = fvec(32)
     45        v[12] = .5
     46        u = f(v)
     47        assert_almost_equal (expected[1], u)
    5748
    58   def test_a_weighting_parted(self):
    59     expected = array_from_text_file('a_weighting_test_simple.expected')
    60     f = digital_filter(7)
    61     f.set_a_weighting(44100)
    62     v = fvec(16)
    63     v[12] = .5
    64     u = f(v)
    65     assert_almost_equal (expected[1][:16], u)
    66     # one more time
    67     v = fvec(16)
    68     u = f(v)
    69     assert_almost_equal (expected[1][16:], u)
     49    def test_a_weighting(self):
     50        expected = array_from_text_file('a_weighting_test_simple.expected')
     51        f = digital_filter(7)
     52        f.set_a_weighting(44100)
     53        v = fvec(32)
     54        v[12] = .5
     55        u = f(v)
     56        assert_almost_equal (expected[1], u)
     57
     58    def test_a_weighting_parted(self):
     59        expected = array_from_text_file('a_weighting_test_simple.expected')
     60        f = digital_filter(7)
     61        f.set_a_weighting(44100)
     62        v = fvec(16)
     63        v[12] = .5
     64        u = f(v)
     65        assert_almost_equal (expected[1][:16], u)
     66        # one more time
     67        v = fvec(16)
     68        u = f(v)
     69        assert_almost_equal (expected[1][16:], u)
     70
     71    def test_set_biquad(self):
     72        f = digital_filter(3)
     73        f.set_biquad(0., 0., 0, 0., 0.)
     74
     75    def test_set_biquad_wrong_order(self):
     76        f = digital_filter(4)
     77        with self.assertRaises(ValueError):
     78            f.set_biquad(0., 0., 0, 0., 0.)
     79
     80class aubio_filter_wrong_params(TestCase):
     81
     82    def test_negative_order(self):
     83        with self.assertRaises(ValueError):
     84            digital_filter(-1)
    7085
    7186if __name__ == '__main__':
    72   from unittest import main
    73   main()
    74 
     87    main()
  • python/tests/test_filterbank.py

    r60fc05b rf264b17  
    11#! /usr/bin/env python
    22
    3 from numpy.testing import TestCase, run_module_suite
     3from unittest import main
     4from numpy.testing import TestCase
    45from numpy.testing import assert_equal, assert_almost_equal
    5 from numpy import random
    6 from math import pi
    7 from numpy import array
    8 from aubio import cvec, filterbank
     6import numpy as np
     7from aubio import cvec, filterbank, float_type
    98from utils import array_from_text_file
    109
    1110class aubio_filterbank_test_case(TestCase):
    1211
    13   def test_members(self):
    14     f = filterbank(40, 512)
    15     assert_equal ([f.n_filters, f.win_s], [40, 512])
     12    def test_members(self):
     13        f = filterbank(40, 512)
     14        assert_equal ([f.n_filters, f.win_s], [40, 512])
    1615
    17   def test_set_coeffs(self):
    18     f = filterbank(40, 512)
    19     r = random.random([40, 512 / 2 + 1]).astype('float32')
    20     f.set_coeffs(r)
    21     assert_equal (r, f.get_coeffs())
     16    def test_set_coeffs(self):
     17        f = filterbank(40, 512)
     18        r = np.random.random([40, int(512 / 2) + 1]).astype(float_type)
     19        f.set_coeffs(r)
     20        assert_equal (r, f.get_coeffs())
    2221
    23   def test_phase(self):
    24     f = filterbank(40, 512)
    25     c = cvec(512)
    26     c.phas[:] = pi
    27     assert_equal( f(c), 0);
     22    def test_phase(self):
     23        f = filterbank(40, 512)
     24        c = cvec(512)
     25        c.phas[:] = np.pi
     26        assert_equal( f(c), 0);
    2827
    29   def test_norm(self):
    30     f = filterbank(40, 512)
    31     c = cvec(512)
    32     c.norm[:] = 1
    33     assert_equal( f(c), 0);
     28    def test_norm(self):
     29        f = filterbank(40, 512)
     30        c = cvec(512)
     31        c.norm[:] = 1
     32        assert_equal( f(c), 0);
    3433
    35   def test_random_norm(self):
    36     f = filterbank(40, 512)
    37     c = cvec(512)
    38     c.norm[:] = random.random((512 / 2 + 1,)).astype('float32')
    39     assert_equal( f(c), 0)
     34    def test_random_norm(self):
     35        f = filterbank(40, 512)
     36        c = cvec(512)
     37        c.norm[:] = np.random.random((int(512 / 2) + 1,)).astype(float_type)
     38        assert_equal( f(c), 0)
    4039
    41   def test_random_coeffs(self):
    42     f = filterbank(40, 512)
    43     c = cvec(512)
    44     r = random.random([40, 512 / 2 + 1]).astype('float32')
    45     r /= r.sum()
    46     f.set_coeffs(r)
    47     c.norm[:] = random.random((512 / 2 + 1,)).astype('float32')
    48     assert_equal ( f(c) < 1., True )
    49     assert_equal ( f(c) > 0., True )
     40    def test_random_coeffs(self):
     41        win_s = 128
     42        f = filterbank(40, win_s)
     43        c = cvec(win_s)
     44        r = np.random.random([40, int(win_s / 2) + 1]).astype(float_type)
     45        r /= r.sum()
     46        f.set_coeffs(r)
     47        c.norm[:] = np.random.random((int(win_s / 2) + 1,)).astype(float_type)
     48        assert_equal ( f(c) < 1., True )
     49        assert_equal ( f(c) > 0., True )
    5050
    51   def test_mfcc_coeffs(self):
    52     f = filterbank(40, 512)
    53     c = cvec(512)
    54     f.set_mel_coeffs_slaney(44100)
    55     c.norm[:] = random.random((512 / 2 + 1,)).astype('float32')
    56     assert_equal ( f(c) < 1., True )
    57     assert_equal ( f(c) > 0., True )
     51    def test_mfcc_coeffs(self):
     52        f = filterbank(40, 512)
     53        c = cvec(512)
     54        f.set_mel_coeffs_slaney(44100)
     55        c.norm[:] = np.random.random((int(512 / 2) + 1,)).astype(float_type)
     56        assert_equal ( f(c) < 1., True )
     57        assert_equal ( f(c) > 0., True )
    5858
    59   def test_mfcc_coeffs_16000(self):
    60     expected = array_from_text_file('filterbank_mfcc_16000_512.expected')
    61     f = filterbank(40, 512)
    62     f.set_mel_coeffs_slaney(16000)
    63     assert_almost_equal ( expected, f.get_coeffs() )
     59    def test_mfcc_coeffs_16000(self):
     60        expected = array_from_text_file('filterbank_mfcc_16000_512.expected')
     61        f = filterbank(40, 512)
     62        f.set_mel_coeffs_slaney(16000)
     63        assert_almost_equal ( expected, f.get_coeffs() )
     64
     65class aubio_filterbank_wrong_values(TestCase):
     66
     67    def test_negative_window(self):
     68        self.assertRaises(ValueError, filterbank, 40, -20)
     69
     70    def test_negative_filters(self):
     71        self.assertRaises(ValueError, filterbank, -40, 1024)
     72
     73    def test_filterbank_long_cvec(self):
     74        f = filterbank(40, 512)
     75        with self.assertRaises(ValueError):
     76            f(cvec(1024))
     77
     78    def test_filterbank_short_cvec(self):
     79        f = filterbank(40, 512)
     80        with self.assertRaises(ValueError):
     81            f(cvec(256))
    6482
    6583if __name__ == '__main__':
    66   from unittest import main
    67   main()
    68 
     84    main()
  • python/tests/test_filterbank_mel.py

    r60fc05b rf264b17  
    11#! /usr/bin/env python
    22
    3 from numpy.testing import TestCase, run_module_suite
     3from unittest import main
     4from numpy.testing import TestCase
    45from numpy.testing import assert_equal, assert_almost_equal
    56from numpy import array, shape
    6 from aubio import cvec, filterbank
     7from aubio import cvec, filterbank, float_type
    78
    89class aubio_filterbank_mel_test_case(TestCase):
    910
    10   def test_slaney(self):
    11     f = filterbank(40, 512)
    12     f.set_mel_coeffs_slaney(16000)
    13     a = f.get_coeffs()
    14     assert_equal(shape (a), (40, 512/2 + 1) )
     11    def test_slaney(self):
     12        f = filterbank(40, 512)
     13        f.set_mel_coeffs_slaney(16000)
     14        a = f.get_coeffs()
     15        assert_equal(shape (a), (40, 512/2 + 1) )
    1516
    16   def test_other_slaney(self):
    17     f = filterbank(40, 512*2)
    18     f.set_mel_coeffs_slaney(44100)
    19     a = f.get_coeffs()
    20     #print "sum is", sum(sum(a))
    21     for win_s in [256, 512, 1024, 2048, 4096]:
    22       f = filterbank(40, win_s)
    23       f.set_mel_coeffs_slaney(320000)
    24       a = f.get_coeffs()
    25       #print "sum is", sum(sum(a))
     17    def test_other_slaney(self):
     18        f = filterbank(40, 512*2)
     19        f.set_mel_coeffs_slaney(44100)
     20        _ = f.get_coeffs()
     21        #print "sum is", sum(sum(a))
     22        for win_s in [256, 512, 1024, 2048, 4096]:
     23            f = filterbank(40, win_s)
     24            f.set_mel_coeffs_slaney(32000)
     25            _ = f.get_coeffs()
     26            #print "sum is", sum(sum(a))
    2627
    27   def test_triangle_freqs_zeros(self):
    28     f = filterbank(9, 1024)
    29     freq_list = [40, 80, 200, 400, 800, 1600, 3200, 6400, 12800, 15000, 24000]
    30     freqs = array(freq_list, dtype = 'float32')
    31     f.set_triangle_bands(freqs, 48000)
    32     f.get_coeffs().T
    33     assert_equal ( f(cvec(1024)), 0)
     28    def test_triangle_freqs_zeros(self):
     29        f = filterbank(9, 1024)
     30        freq_list = [40, 80, 200, 400, 800, 1600, 3200, 6400, 12800, 15000, 24000]
     31        freqs = array(freq_list, dtype = float_type)
     32        f.set_triangle_bands(freqs, 48000)
     33        _ = f.get_coeffs().T
     34        assert_equal ( f(cvec(1024)), 0)
    3435
    35   def test_triangle_freqs_ones(self):
    36     f = filterbank(9, 1024)
    37     freq_list = [40, 80, 200, 400, 800, 1600, 3200, 6400, 12800, 15000, 24000]
    38     freqs = array(freq_list, dtype = 'float32')
    39     f.set_triangle_bands(freqs, 48000)
    40     f.get_coeffs().T
    41     spec = cvec(1024)
    42     spec.norm[:] = 1
    43     assert_almost_equal ( f(spec),
    44             [ 0.02070313,  0.02138672,  0.02127604,  0.02135417,
    45         0.02133301, 0.02133301,  0.02133311,  0.02133334, 0.02133345])
     36    def test_triangle_freqs_ones(self):
     37        f = filterbank(9, 1024)
     38        freq_list = [40, 80, 200, 400, 800, 1600, 3200, 6400, 12800, 15000, 24000]
     39        freqs = array(freq_list, dtype = float_type)
     40        f.set_triangle_bands(freqs, 48000)
     41        _ = f.get_coeffs().T
     42        spec = cvec(1024)
     43        spec.norm[:] = 1
     44        assert_almost_equal ( f(spec),
     45                [ 0.02070313, 0.02138672, 0.02127604, 0.02135417,
     46                    0.02133301, 0.02133301, 0.02133311, 0.02133334, 0.02133345])
    4647
    4748if __name__ == '__main__':
    48   from unittest import main
    49   main()
    50 
    51 
     49    main()
  • python/tests/test_fvec.py

    r60fc05b rf264b17  
    11#! /usr/bin/env python
    22
    3 from numpy.testing import TestCase, run_module_suite
    4 from numpy.testing import assert_equal, assert_almost_equal
     3from unittest import main
     4import numpy as np
     5from numpy.testing import TestCase, assert_equal, assert_almost_equal
    56from aubio import fvec, zero_crossing_rate, alpha_norm, min_removal
    6 from numpy import array, shape
     7from aubio import float_type
     8
     9wrong_type = 'float32' if float_type == 'float64' else 'float64'
    710
    811default_size = 512
     
    1215    def test_vector_created_with_zeroes(self):
    1316        a = fvec(10)
    14         assert a.dtype == 'float32'
     17        assert a.dtype == float_type
    1518        assert a.shape == (10,)
    16         assert_equal (a, 0)
     19        assert_equal(a, 0)
    1720
    1821    def test_vector_create_with_list(self):
    19         a = fvec([0,1,2,3])
    20         assert a.dtype == 'float32'
     22        a = fvec([0, 1, 2, 3])
     23        assert a.dtype == float_type
    2124        assert a.shape == (4,)
    22         assert_equal (range(4), a)
     25        assert_equal(list(range(4)), a)
    2326
    2427    def test_vector_assign_element(self):
     
    3538    def test_vector(self):
    3639        a = fvec()
    37         a, len(a) #a.length
    38         a[0]
    39         array(a)
     40        len(a)
     41        _ = a[0]
     42        np.array(a)
     43        a = fvec(1)
    4044        a = fvec(10)
    41         a = fvec(1)
    42         a.T
    43         array(a).T
    44         a = range(len(a))
     45        _ = a.T
    4546
    46     def test_wrong_values(self):
    47         self.assertRaises (ValueError, fvec, -10)
    48  
     47class aubio_fvec_wrong_values(TestCase):
     48
     49    def test_negative_length(self):
     50        """ test creating fvec with negative length fails (pure python) """
     51        self.assertRaises(ValueError, fvec, -10)
     52
     53    def test_zero_length(self):
     54        """ test creating fvec with zero length fails (pure python) """
     55        self.assertRaises(ValueError, fvec, 0)
     56
     57    def test_out_of_bound(self):
     58        """ test assiging fvec out of bounds fails (pure python) """
    4959        a = fvec(2)
    50         self.assertRaises (IndexError, a.__getitem__, 3)
    51         self.assertRaises (IndexError, a.__getitem__, 2)
     60        self.assertRaises(IndexError, a.__getitem__, 3)
     61        self.assertRaises(IndexError, a.__getitem__, 2)
    5262
    53     def test_alpha_norm_of_fvec(self):
    54         a = fvec(2)
    55         self.assertEquals (alpha_norm(a, 1), 0)
    56         a[0] = 1
    57         self.assertEquals (alpha_norm(a, 1), 0.5)
    58         a[1] = 1
    59         self.assertEquals (alpha_norm(a, 1), 1)
    60         a = array([0, 1], dtype='float32')
    61         from math import sqrt
    62         assert_almost_equal (alpha_norm(a, 2), sqrt(2)/2.)
     63class aubio_wrong_fvec_input(TestCase):
     64    """ uses min_removal to test PyAubio_IsValidVector """
    6365
    64     def test_alpha_norm_of_none(self):
    65         self.assertRaises (ValueError, alpha_norm, None, 1)
     66    def test_no_input(self):
     67        self.assertRaises(TypeError, min_removal)
    6668
    67     def test_alpha_norm_of_array_of_float32(self):
    68         # check scalar fails
    69         a = array(1, dtype = 'float32')
    70         self.assertRaises (ValueError, alpha_norm, a, 1)
    71         # check 2d array fails
    72         a = array([[2],[4]], dtype = 'float32')
    73         self.assertRaises (ValueError, alpha_norm, a, 1)
    74         # check 1d array
    75         a = array(range(10), dtype = 'float32')
    76         self.assertEquals (alpha_norm(a, 1), 4.5)
     69    def test_none(self):
     70        self.assertRaises(ValueError, min_removal, None)
    7771
    78     def test_alpha_norm_of_array_of_int(self):
    79         a = array(1, dtype = 'int')
    80         self.assertRaises (ValueError, alpha_norm, a, 1)
    81         a = array([[[1,2],[3,4]]], dtype = 'int')
    82         self.assertRaises (ValueError, alpha_norm, a, 1)
    83         a = array(range(10), dtype = 'int')
    84         self.assertRaises (ValueError, alpha_norm, a, 1)
     72    def test_wrong_scalar(self):
     73        a = np.array(10, dtype=float_type)
     74        self.assertRaises(ValueError, min_removal, a)
    8575
    86     def test_alpha_norm_of_array_of_string (self):
    87         a = "hello"
    88         self.assertRaises (ValueError, alpha_norm, a, 1)
     76    def test_wrong_dimensions(self):
     77        a = np.array([[[1, 2], [3, 4]]], dtype=float_type)
     78        self.assertRaises(ValueError, min_removal, a)
     79
     80    def test_wrong_array_size(self):
     81        x = np.array([], dtype=float_type)
     82        self.assertRaises(ValueError, min_removal, x)
     83
     84    def test_wrong_type(self):
     85        a = np.zeros(10, dtype=wrong_type)
     86        self.assertRaises(ValueError, min_removal, a)
     87
     88    def test_wrong_list_input(self):
     89        self.assertRaises(ValueError, min_removal, [0., 1.])
     90
     91    def test_good_input(self):
     92        a = np.zeros(10, dtype=float_type)
     93        assert_equal(np.zeros(10, dtype=float_type), min_removal(a))
     94
     95class aubio_alpha_norm(TestCase):
     96
     97    def test_alpha_norm_of_random(self):
     98        x = np.random.rand(1024).astype(float_type)
     99        alpha = np.random.rand() * 5.
     100        x_alpha_norm = (np.sum(np.abs(x)**alpha)/len(x))**(1/alpha)
     101        assert_almost_equal(alpha_norm(x, alpha), x_alpha_norm, decimal = 5)
     102
     103class aubio_zero_crossing_rate_test(TestCase):
    89104
    90105    def test_zero_crossing_rate(self):
    91         a = array([0,1,-1], dtype='float32')
    92         assert_almost_equal (zero_crossing_rate(a), 1./3. )
    93         a = array([0.]*100, dtype='float32')
    94         self.assertEquals (zero_crossing_rate(a), 0 )
    95         a = array([-1.]*100, dtype='float32')
    96         self.assertEquals (zero_crossing_rate(a), 0 )
    97         a = array([1.]*100, dtype='float32')
    98         self.assertEquals (zero_crossing_rate(a), 0 )
     106        a = np.array([0, 1, -1], dtype=float_type)
     107        assert_almost_equal(zero_crossing_rate(a), 1./3.)
    99108
    100     def test_alpha_norm_of_array_of_float64(self):
    101         # check scalar fail
    102         a = array(1, dtype = 'float64')
    103         self.assertRaises (ValueError, alpha_norm, a, 1)
    104         # check 3d array fail
    105         a = array([[[1,2],[3,4]]], dtype = 'float64')
    106         self.assertRaises (ValueError, alpha_norm, a, 1)
    107         # check float64 1d array fail
    108         a = array(range(10), dtype = 'float64')
    109         self.assertRaises (ValueError, alpha_norm, a, 1)
    110         # check float64 2d array fail
    111         a = array([range(10), range(10)], dtype = 'float64')
    112         self.assertRaises (ValueError, alpha_norm, a, 1)
     109    def test_zero_crossing_rate_zeros(self):
     110        a = np.zeros(100, dtype=float_type)
     111        self.assertEqual(zero_crossing_rate(a), 0)
     112
     113    def test_zero_crossing_rate_minus_ones(self):
     114        a = np.ones(100, dtype=float_type)
     115        self.assertEqual(zero_crossing_rate(a), 0)
     116
     117    def test_zero_crossing_rate_plus_ones(self):
     118        a = np.ones(100, dtype=float_type)
     119        self.assertEqual(zero_crossing_rate(a), 0)
     120
     121class aubio_fvec_min_removal(TestCase):
    113122
    114123    def test_fvec_min_removal_of_array(self):
    115         a = array([20,1,19], dtype='float32')
     124        a = np.array([20, 1, 19], dtype=float_type)
    116125        b = min_removal(a)
    117         assert_equal (array(b), [19, 0, 18])
    118         assert_equal (b, [19, 0, 18])
    119         assert_equal (a, b)
    120         a[0] = 0
    121         assert_equal (a, b)
     126        assert_equal(b, [19, 0, 18])
    122127
    123     def test_fvec_min_removal_of_array_float64(self):
    124         a = array([20,1,19], dtype='float64')
    125         self.assertRaises (ValueError, min_removal, a)
     128class aubio_fvec_test_memory(TestCase):
    126129
    127     def test_fvec_min_removal_of_fvec(self):
    128         a = fvec(3)
    129         a = array([20, 1, 19], dtype = 'float32')
    130         b = min_removal(a)
    131         assert_equal (array(b), [19, 0, 18])
    132         assert_equal (b, [19, 0, 18])
    133         assert_equal (a, b)
     130    def test_pass_to_numpy(self):
     131        a = fvec(10)
     132        a[:] = 1.
     133        b = a
     134        del a
     135        assert_equal(b, 1.)
     136        c = fvec(10)
     137        c = b
     138        del b
     139        assert_equal(c, 1.)
     140        del c
    134141
    135142if __name__ == '__main__':
    136     from unittest import main
    137143    main()
  • python/tests/test_mathutils.py

    r60fc05b rf264b17  
    11#! /usr/bin/env python
    22
     3from unittest import main
    34from numpy.testing import TestCase, assert_equal
    45from numpy import array, arange, isnan, isinf
     
    1314        unwrap2pi(int(23))
    1415        unwrap2pi(float(23.))
    15         unwrap2pi(long(23.))
     16        unwrap2pi(int(23.))
    1617        unwrap2pi(arange(10))
    1718        unwrap2pi(arange(10).astype("int"))
     
    2425        unwrap2pi(a)
    2526        a = pi/100. * arange(-600,600).astype("float")
    26         b = unwrap2pi (a)
     27        unwrap2pi(a)
    2728        #print zip(a, b)
    2829
    29         try:
    30             print unwrap2pi(["23.","24.",25.])
    31         except Exception, e:
    32             pass
     30    def test_unwrap2pi_fails_on_list(self):
     31        with self.assertRaises((TypeError, NotImplementedError)):
     32            unwrap2pi(["23.","24.",25.])
    3333
    3434    def test_unwrap2pi_takes_fvec(self):
     
    5454
    5555    def test_freqtomidi(self):
    56         a = array(range(-20, 50000, 100) + [ -1e32, 1e32 ])
     56        a = array(list(range(-20, 50000, 100)) + [ -1e32, 1e32 ])
    5757        b = freqtomidi(a)
    5858        #print zip(a, b)
     
    6262
    6363    def test_miditofreq(self):
    64         a = range(-30, 200) + [-100000, 10000]
     64        a = list(range(-30, 200)) + [-100000, 10000]
    6565        b = miditofreq(a)
    6666        #print zip(a, b)
     
    7070
    7171    def test_miditobin(self):
    72         a = range(-30, 200) + [-100000, 10000]
    73         b = [ bintomidi(x, 44100, 512) for x in a ]
     72        a = list(range(-30, 200)) + [-100000, 10000]
     73        b = [ miditobin(x, 44100, 512) for x in a ]
    7474        #print zip(a, b)
    7575        assert_equal ( isnan(array(b)), False )
     
    7878
    7979    def test_bintomidi(self):
    80         a = range(-100, 512)
     80        a = list(range(-100, 512))
    8181        b = [ bintomidi(x, 44100, 512) for x in a ]
    8282        #print zip(a, b)
     
    8686
    8787    def test_freqtobin(self):
    88         a = range(-20, 50000, 100) + [ -1e32, 1e32 ]
     88        a = list(range(-20, 50000, 100)) + [ -1e32, 1e32 ]
    8989        b = [ freqtobin(x, 44100, 512) for x in a ]
    9090        #print zip(a, b)
     
    9494
    9595    def test_bintofreq(self):
    96         a = range(-20, 148)
     96        a = list(range(-20, 148))
    9797        b = [ bintofreq(x, 44100, 512) for x in a ]
    9898        #print zip(a, b)
     
    102102
    103103if __name__ == '__main__':
    104     from unittest import main
    105104    main()
  • python/tests/test_midi2note.py

    r60fc05b rf264b17  
    2828        self.assertRaises(ValueError, midi2note, -2)
    2929
    30     def test_midi2note_negative_value(self):
     30    def test_midi2note_large(self):
    3131        " fails when passed a value greater than 127 "
    3232        self.assertRaises(ValueError, midi2note, 128)
  • python/tests/test_musicutils.py

    r60fc05b rf264b17  
    11#! /usr/bin/env python
    22
     3from unittest import main
     4import numpy as np
    35from numpy.testing import TestCase
    46from numpy.testing.utils import assert_equal, assert_almost_equal
    5 from numpy import cos, arange
    6 from math import pi
    7 
    87from aubio import window, level_lin, db_spl, silence_detection, level_detection
    9 
    10 from aubio import fvec
     8from aubio import fvec, float_type
    119
    1210class aubio_window(TestCase):
     
    1614
    1715    def test_fail_name_not_string(self):
    18         try:
     16        with self.assertRaises(TypeError):
    1917            window(10, 1024)
    20         except ValueError, e:
    21             pass
    22         else:
    23             self.fail('non-string window type does not raise a ValueError')
    2418
    2519    def test_fail_size_not_int(self):
    26         try:
     20        with self.assertRaises(TypeError):
    2721            window("default", "default")
    28         except ValueError, e:
    29             pass
    30         else:
    31             self.fail('non-integer window length does not raise a ValueError')
    3222
    3323    def test_compute_hanning_1024(self):
    3424        size = 1024
    3525        aubio_window = window("hanning", size)
    36         numpy_window = .5 - .5 * cos(2. * pi * arange(size) / size)
     26        numpy_window = .5 - .5 * np.cos(2. * np.pi * np.arange(size) / size)
    3727        assert_almost_equal(aubio_window, numpy_window)
    3828
     
    4232
    4333    def test_fail_not_fvec(self):
    44         try:
     34        with self.assertRaises(ValueError):
    4535            level_lin("default")
    46         except ValueError, e:
    47             pass
    48         else:
    49             self.fail('non-number input phase does not raise a TypeError')
    5036
    5137    def test_zeros_is_zeros(self):
     
    5339
    5440    def test_minus_ones_is_one(self):
    55         from numpy import ones
    56         assert_equal(level_lin(-ones(1024, dtype="float32")), 1.)
     41        assert_equal(level_lin(-np.ones(1024, dtype = float_type)), 1.)
    5742
    5843class aubio_db_spl(TestCase):
     
    6146
    6247    def test_fail_not_fvec(self):
    63         try:
     48        with self.assertRaises(ValueError):
    6449            db_spl("default")
    65         except ValueError, e:
    66             pass
    67         else:
    68             self.fail('non-number input phase does not raise a TypeError')
    6950
    7051    def test_zeros_is_inf(self):
    71         from math import isinf
    72         assert isinf(db_spl(fvec(1024)))
     52        assert np.isinf(db_spl(fvec(1024)))
    7353
    7454    def test_minus_ones_is_zero(self):
    75         from numpy import ones
    76         assert_equal(db_spl(-ones(1024, dtype="float32")), 0.)
     55        assert_equal(db_spl(-np.ones(1024, dtype = float_type)), 0.)
    7756
    7857class aubio_silence_detection(TestCase):
     
    8160
    8261    def test_fail_not_fvec(self):
    83         try:
     62        with self.assertRaises(ValueError):
    8463            silence_detection("default", -70)
    85         except ValueError, e:
    86             pass
    87         else:
    88             self.fail('non-number input phase does not raise a TypeError')
    8964
    9065    def test_zeros_is_one(self):
    91         from math import isinf
    9266        assert silence_detection(fvec(1024), -70) == 1
    9367
    9468    def test_minus_ones_is_zero(self):
    9569        from numpy import ones
    96         assert silence_detection(ones(1024, dtype="float32"), -70) == 0
     70        assert silence_detection(ones(1024, dtype = float_type), -70) == 0
    9771
    9872class aubio_level_detection(TestCase):
     
    10175
    10276    def test_fail_not_fvec(self):
    103         try:
     77        with self.assertRaises(ValueError):
    10478            level_detection("default", -70)
    105         except ValueError, e:
    106             pass
    107         else:
    108             self.fail('non-number input phase does not raise a TypeError')
    10979
    11080    def test_zeros_is_one(self):
    111         from math import isinf
    11281        assert level_detection(fvec(1024), -70) == 1
    11382
    11483    def test_minus_ones_is_zero(self):
    11584        from numpy import ones
    116         assert level_detection(ones(1024, dtype="float32"), -70) == 0
     85        assert level_detection(ones(1024, dtype = float_type), -70) == 0
    11786
    11887if __name__ == '__main__':
    119     from unittest import main
    12088    main()
  • python/tests/test_note2midi.py

    r60fc05b rf264b17  
    22# -*- coding: utf-8 -*-
    33
    4 from aubio import note2midi
     4from __future__ import unicode_literals
     5
     6from aubio import note2midi, freq2note
    57import unittest
    68
     
    1517        ( 'A#4', 70 ),
    1618        ( 'Bb4', 70 ),
    17         ( u'B♭4', 70 ),
     19        ( 'B♭4', 70 ),
    1820        ( 'G8', 115 ),
    19         ( u'G♯8', 116 ),
     21        ( 'G♯8', 116 ),
    2022        ( 'G9', 127 ),
    21         ( u'G\udd2a2', 45 ),
    22         ( u'B\ufffd2', 45 ),
    23         ( u'A♮2', 45 ),
     23        ( 'G\udd2a2', 45 ),
     24        ( 'B\ufffd2', 45 ),
     25        ( 'A♮2', 45 ),
    2426        )
    2527
     
    5052
    5153    def test_note2midi_out_of_range(self):
    52         " fails when passed a out of range note"
     54        " fails when passed a note out of range"
    5355        self.assertRaises(ValueError, note2midi, 'A9')
     56
     57    def test_note2midi_wrong_note_name(self):
     58        " fails when passed a note with a wrong name"
     59        self.assertRaises(ValueError, note2midi, 'W9')
     60
     61    def test_note2midi_low_octave(self):
     62        " fails when passed a note with a too low octave"
     63        self.assertRaises(ValueError, note2midi, 'C-9')
    5464
    5565    def test_note2midi_wrong_data_type(self):
     
    5767        self.assertRaises(TypeError, note2midi, 123)
    5868
     69
     70class freq2note_simple_test(unittest.TestCase):
     71
     72    def test_freq2note(self):
     73        " make sure freq2note(441) == A4 "
     74        self.assertEqual("A4", freq2note(441))
     75
    5976if __name__ == '__main__':
    6077    unittest.main()
  • python/tests/test_onset.py

    r60fc05b rf264b17  
    11#! /usr/bin/env python
    22
    3 from numpy.testing import TestCase, run_module_suite
    4 from numpy.testing import assert_equal, assert_almost_equal
     3from unittest import main
     4from numpy.testing import TestCase, assert_equal, assert_almost_equal
    55from aubio import onset
    66
     
    8585
    8686if __name__ == '__main__':
    87     from unittest import main
    8887    main()
  • python/tests/test_phasevoc.py

    r60fc05b rf264b17  
    11#! /usr/bin/env python
    22
    3 from numpy.testing import TestCase, assert_equal, assert_almost_equal
    4 from aubio import fvec, cvec, pvoc
    5 from numpy import array, shape
    6 from numpy.random import random
     3from numpy.testing import TestCase, assert_equal, assert_array_less
     4from aubio import fvec, cvec, pvoc, float_type
     5from nose2 import main
     6from nose2.tools import params
     7import numpy as np
    78
    8 precision = 6
     9if float_type == 'float32':
     10    max_sq_error = 1.e-12
     11else:
     12    max_sq_error = 1.e-29
     13
     14def create_sine(hop_s, freq, samplerate):
     15    t = np.arange(hop_s).astype(float_type)
     16    return np.sin( 2. * np.pi * freq * t / float(samplerate))
     17
     18def create_noise(hop_s):
     19    return np.random.rand(hop_s).astype(float_type) * 2. - 1.
    920
    1021class aubio_pvoc_test_case(TestCase):
     
    3142        f = pvoc (win_s, hop_s)
    3243        t = fvec (hop_s)
    33         for time in range( 4 * win_s / hop_s ):
     44        for _ in range( int ( 4 * win_s / hop_s ) ):
    3445            s = f(t)
    3546            r = f.rdo(s)
    36             assert_equal ( array(t), 0)
    37             assert_equal ( s.norm, 0)
    38             assert_equal ( s.phas, 0)
    39             assert_equal ( r, 0)
     47            assert_equal ( t, 0.)
     48            assert_equal ( s.norm, 0.)
     49            assert_equal ( s.phas, 0.)
     50            assert_equal ( r, 0.)
    4051
    41     def test_resynth_two_steps(self):
    42         """ check the resynthesis of steps is correct with 50% overlap """
    43         hop_s = 512
    44         buf_s = hop_s * 2
     52    @params(
     53            ( 256, 8),
     54            ( 256, 4),
     55            ( 256, 2),
     56            ( 512, 8),
     57            ( 512, 4),
     58            ( 512, 2),
     59            #( 129, 2),
     60            #( 320, 4),
     61            #(  13, 8),
     62            (1024, 8),
     63            (1024, 4),
     64            (1024, 2),
     65            (2048, 8),
     66            (2048, 4),
     67            (2048, 2),
     68            (4096, 8),
     69            (4096, 4),
     70            (4096, 2),
     71            (8192, 8),
     72            (8192, 4),
     73            (8192, 2),
     74            )
     75    def test_resynth_steps_noise(self, hop_s, ratio):
     76        """ check the resynthesis of a random signal is correct """
     77        sigin = create_noise(hop_s)
     78        self.reconstruction(sigin, hop_s, ratio)
     79
     80    @params(
     81            (44100,  256, 8,   441),
     82            (44100,  256, 4,  1203),
     83            (44100,  256, 2,  3045),
     84            (44100,  512, 8,   445),
     85            (44100,  512, 4,   445),
     86            (44100,  512, 2,   445),
     87            (44100, 1024, 8,   445),
     88            (44100, 1024, 4,   445),
     89            (44100, 1024, 2,   445),
     90            ( 8000, 1024, 2,   445),
     91            (22050, 1024, 2,   445),
     92            (22050,  256, 8,   445),
     93            (96000, 1024, 8, 47000),
     94            (96000, 1024, 8,    20),
     95            )
     96    def test_resynth_steps_sine(self, samplerate, hop_s, ratio, freq):
     97        """ check the resynthesis of a sine is correct """
     98        sigin = create_sine(hop_s, freq, samplerate)
     99        self.reconstruction(sigin, hop_s, ratio)
     100
     101    def reconstruction(self, sigin, hop_s, ratio):
     102        buf_s = hop_s * ratio
    45103        f = pvoc(buf_s, hop_s)
    46         sigin = fvec(hop_s)
    47104        zeros = fvec(hop_s)
    48         # negative step
    49         sigin[20:50] = -.1
    50         # positive step
    51         sigin[100:200] = .1
    52         s1 = f(sigin)
    53         r1 = f.rdo(s1)
    54         s2 = f(zeros)
    55         r2 = f.rdo(s2)
    56         #self.plot_this ( s2.norm.T )
    57         assert_almost_equal ( r2, sigin, decimal = precision )
    58    
    59     def test_resynth_three_steps(self):
    60         """ check the resynthesis of steps is correct with 25% overlap """
    61         hop_s = 16
    62         buf_s = hop_s * 4
    63         sigin = fvec(hop_s)
    64         zeros = fvec(hop_s)
    65         f = pvoc(buf_s, hop_s)
    66         for i in xrange(hop_s):
    67             sigin[i] = random() * 2. - 1.
    68         t2 = f.rdo( f(sigin) )
    69         t2 = f.rdo( f(zeros) )
    70         t2 = f.rdo( f(zeros) )
    71         t2 = f.rdo( f(zeros) )
    72         assert_almost_equal( sigin, t2, decimal = precision )
    73    
    74     def plot_this( self, this ):
    75         from pylab import semilogy, show
    76         semilogy ( this )
    77         show ()
     105        r2 = f.rdo( f(sigin) )
     106        for _ in range(1, ratio):
     107            r2 = f.rdo( f(zeros) )
     108        # compute square errors
     109        sq_error = (r2 - sigin)**2
     110        # make sure all square errors are less than desired precision
     111        assert_array_less(sq_error, max_sq_error)
     112
     113class aubio_pvoc_strange_params(TestCase):
     114
     115    def test_win_size_short(self):
     116        with self.assertRaises(RuntimeError):
     117            pvoc(1, 1)
     118
     119    def test_hop_size_long(self):
     120        with self.assertRaises(RuntimeError):
     121            pvoc(1024, 1025)
     122
     123    def test_large_input_timegrain(self):
     124        win_s = 1024
     125        f = pvoc(win_s)
     126        t = fvec(win_s + 1)
     127        with self.assertRaises(ValueError):
     128            f(t)
     129
     130    def test_small_input_timegrain(self):
     131        win_s = 1024
     132        f = pvoc(win_s)
     133        t = fvec(1)
     134        with self.assertRaises(ValueError):
     135            f(t)
     136
     137    def test_large_input_fftgrain(self):
     138        win_s = 1024
     139        f = pvoc(win_s)
     140        s = cvec(win_s + 5)
     141        with self.assertRaises(ValueError):
     142            f.rdo(s)
     143
     144    def test_small_input_fftgrain(self):
     145        win_s = 1024
     146        f = pvoc(win_s)
     147        s = cvec(16)
     148        with self.assertRaises(ValueError):
     149            f.rdo(s)
     150
     151class aubio_pvoc_wrong_params(TestCase):
     152
     153    def test_wrong_buf_size(self):
     154        win_s = -1
     155        with self.assertRaises(ValueError):
     156            pvoc(win_s)
     157
     158    def test_buf_size_too_small(self):
     159        win_s = 1
     160        with self.assertRaises(RuntimeError):
     161            pvoc(win_s)
     162
     163    def test_hop_size_negative(self):
     164        win_s = 512
     165        hop_s = -2
     166        with self.assertRaises(ValueError):
     167            pvoc(win_s, hop_s)
     168
     169    def test_hop_size_too_small(self):
     170        win_s = 1
     171        hop_s = 1
     172        with self.assertRaises(RuntimeError):
     173            pvoc(win_s, hop_s)
     174
     175    def test_buf_size_not_power_of_two(self):
     176        win_s = 320
     177        hop_s = win_s // 2
     178        try:
     179            with self.assertRaises(RuntimeError):
     180                pvoc(win_s, hop_s)
     181        except AssertionError:
     182            # when compiled with fftw3, aubio supports non power of two fft sizes
     183            self.skipTest('creating aubio.pvoc with size %d did not fail' % win_s)
    78184
    79185if __name__ == '__main__':
    80   from unittest import main
    81   main()
     186    main()
    82187
  • python/tests/test_pitch.py

    r60fc05b rf264b17  
    11#! /usr/bin/env python
    22
    3 from unittest import TestCase
    4 from numpy.testing import assert_equal, assert_almost_equal
    5 from numpy import random, sin, arange, mean, median, isnan
    6 from math import pi
    7 from aubio import fvec, pitch, freqtomidi
     3from unittest import TestCase, main
     4from numpy.testing import assert_equal
     5from numpy import sin, arange, mean, median, isnan, pi
     6from aubio import fvec, pitch, freqtomidi, float_type
    87
    98class aubio_pitch_Good_Values(TestCase):
     
    2524        p = pitch('default', 2048, 512, 32000)
    2625        f = fvec (512)
    27         for i in xrange(10): assert_equal (p(f), 0.)
     26        for _ in range(10): assert_equal (p(f), 0.)
    2827
    2928    def test_run_on_ones(self):
     
    3231        f = fvec (512)
    3332        f[:] = 1
    34         for i in xrange(10): assert_equal (p(f), 0.)
     33        for _ in range(10): assert_equal (p(f), 0.)
    3534
    3635class aubio_pitch_Sinusoid(TestCase):
     
    5150
    5251    def build_sinusoid(self, length, freq, samplerate):
    53         return sin( 2. * pi * arange(length).astype('float32') * freq / samplerate)
     52        return sin( 2. * pi * arange(length).astype(float_type) * freq / samplerate)
    5453
    5554    def run_pitch(self, p, input_vec, freq):
    56         count = 0
    5755        pitches, errors = [], []
    5856        input_blocks = input_vec.reshape((-1, p.hop_size))
     
    6462        assert_equal ( isnan(pitches), False )
    6563        # cut the first candidates
    66         cut = ( p.buf_size - p.hop_size ) / p.hop_size
     64        #cut = ( p.buf_size - p.hop_size ) / p.hop_size
    6765        pitches = pitches[2:]
    6866        errors = errors[2:]
     
    125123
    126124if __name__ == '__main__':
    127     from unittest import main
    128125    main()
  • python/tests/test_sink.py

    r60fc05b rf264b17  
    11#! /usr/bin/env python
    22
    3 from numpy.testing import TestCase, assert_equal, assert_almost_equal
     3from nose2 import main
     4from nose2.tools import params
     5from numpy.testing import TestCase
    46from aubio import fvec, source, sink
    5 from numpy import array
    67from utils import list_all_sounds, get_tmp_sink_path, del_tmp_sink_path
    78
    89list_of_sounds = list_all_sounds('sounds')
     10samplerates = [0, 44100, 8000, 32000]
     11hop_sizes = [512, 1024, 64]
     12
    913path = None
    1014
    1115many_files = 300 # 256 opened files is too much
    1216
     17all_params = []
     18for soundfile in list_of_sounds:
     19    for hop_size in hop_sizes:
     20        for samplerate in samplerates:
     21            all_params.append((hop_size, samplerate, soundfile))
     22
    1323class aubio_sink_test_case(TestCase):
     24
     25    def setUp(self):
     26        if not len(list_of_sounds):
     27            self.skipTest('add some sound files in \'python/tests/sounds\'')
    1428
    1529    def test_many_sinks(self):
     
    2438            sink_list.append(g)
    2539            write = 32
    26             for n in range(200):
     40            for _ in range(200):
    2741                vec = fvec(write)
    2842                g(vec, write)
     
    3044        shutil.rmtree(tmpdir)
    3145
    32     def test_many_sinks_not_closed(self):
    33         from tempfile import mkdtemp
    34         import os.path
    35         import shutil
    36         tmpdir = mkdtemp()
    37         sink_list = []
     46    @params(*all_params)
     47    def test_read_and_write(self, hop_size, samplerate, path):
     48
    3849        try:
    39             for i in range(many_files):
    40                 path = os.path.join(tmpdir, 'f-' + str(i) + '.wav')
    41                 g = sink(path, 0)
    42                 sink_list.append(g)
    43                 write = 256
    44                 for n in range(200):
    45                     vec = fvec(write)
    46                     g(vec, write)
    47         except StandardError:
    48             pass
    49         else:
    50             self.fail("does not fail on too many files open")
    51         for g in sink_list:
    52             g.close()
    53         shutil.rmtree(tmpdir)
     50            f = source(path, samplerate, hop_size)
     51        except RuntimeError as e:
     52            self.skipTest('failed opening with hop_s = {:d}, samplerate = {:d} ({:s})'.format(hop_size, samplerate, str(e)))
     53        if samplerate == 0: samplerate = f.samplerate
     54        sink_path = get_tmp_sink_path()
     55        g = sink(sink_path, samplerate)
     56        total_frames = 0
     57        while True:
     58            vec, read = f()
     59            g(vec, read)
     60            total_frames += read
     61            if read < f.hop_size: break
     62        del_tmp_sink_path(sink_path)
    5463
    55     def test_read_and_write(self):
    56 
    57         if not len(list_of_sounds):
    58             self.skipTest('add some sound files in \'python/tests/sounds\'')
    59 
    60         for path in list_of_sounds:
    61             for samplerate, hop_size in zip([0, 44100, 8000, 32000], [512, 1024, 64, 256]):
    62                 f = source(path, samplerate, hop_size)
    63                 if samplerate == 0: samplerate = f.samplerate
    64                 sink_path = get_tmp_sink_path()
    65                 g = sink(sink_path, samplerate)
    66                 total_frames = 0
    67                 while True:
    68                     vec, read = f()
    69                     g(vec, read)
    70                     total_frames += read
    71                     if read < f.hop_size: break
    72                 if 0:
    73                     print "read", "%.2fs" % (total_frames / float(f.samplerate) ),
    74                     print "(", total_frames, "frames", "in",
    75                     print total_frames / f.hop_size, "blocks", "at", "%dHz" % f.samplerate, ")",
    76                     print "from", f.uri,
    77                     print "to", g.uri
    78                 del_tmp_sink_path(sink_path)
    79 
    80     def test_read_and_write_multi(self):
    81 
    82         if not len(list_of_sounds):
    83             self.skipTest('add some sound files in \'python/tests/sounds\'')
    84 
    85         for path in list_of_sounds:
    86             for samplerate, hop_size in zip([0, 44100, 8000, 32000], [512, 1024, 64, 256]):
    87                 f = source(path, samplerate, hop_size)
    88                 if samplerate == 0: samplerate = f.samplerate
    89                 sink_path = get_tmp_sink_path()
    90                 g = sink(sink_path, samplerate, channels = f.channels)
    91                 total_frames = 0
    92                 while True:
    93                     vec, read = f.do_multi()
    94                     g.do_multi(vec, read)
    95                     total_frames += read
    96                     if read < f.hop_size: break
    97                 if 0:
    98                     print "read", "%.2fs" % (total_frames / float(f.samplerate) ),
    99                     print "(", total_frames, "frames", "in",
    100                     print f.channels, "channels", "in",
    101                     print total_frames / f.hop_size, "blocks", "at", "%dHz" % f.samplerate, ")",
    102                     print "from", f.uri,
    103                     print "to", g.uri,
    104                     print "in", g.channels, "channels"
    105                 del_tmp_sink_path(sink_path)
     64    @params(*all_params)
     65    def test_read_and_write_multi(self, hop_size, samplerate, path):
     66        try:
     67            f = source(path, samplerate, hop_size)
     68        except RuntimeError as e:
     69            self.skipTest('failed opening with hop_s = {:d}, samplerate = {:d} ({:s})'.format(hop_size, samplerate, str(e)))
     70        if samplerate == 0: samplerate = f.samplerate
     71        sink_path = get_tmp_sink_path()
     72        g = sink(sink_path, samplerate, channels = f.channels)
     73        total_frames = 0
     74        while True:
     75            vec, read = f.do_multi()
     76            g.do_multi(vec, read)
     77            total_frames += read
     78            if read < f.hop_size: break
     79        del_tmp_sink_path(sink_path)
    10680
    10781    def test_close_file(self):
     
    12195
    12296if __name__ == '__main__':
    123     from unittest import main
    12497    main()
  • python/tests/test_slicing.py

    r60fc05b rf264b17  
    11#! /usr/bin/env python
    22
    3 from numpy.testing import TestCase, run_module_suite
    4 from numpy.testing import assert_equal, assert_almost_equal
    5 
     3from unittest import main
     4from numpy.testing import TestCase, assert_equal
    65from aubio import slice_source_at_stamps
    7 from utils import *
     6from utils import count_files_in_directory, get_default_test_sound
     7from utils import count_samples_in_directory, count_samples_in_file
    88
    99import tempfile
     
    147147
    148148if __name__ == '__main__':
    149     from unittest import main
    150149    main()
  • python/tests/test_source.py

    r60fc05b rf264b17  
    11#! /usr/bin/env python
    22
    3 from numpy.testing import TestCase, assert_equal, assert_almost_equal
    4 from aubio import fvec, source
    5 from numpy import array
     3from nose2 import main
     4from nose2.tools import params
     5from numpy.testing import TestCase
     6from aubio import source
    67from utils import list_all_sounds
    78
    89list_of_sounds = list_all_sounds('sounds')
     10samplerates = [0, 44100, 8000, 32000]
     11hop_sizes = [512, 1024, 64]
     12
    913path = None
     14
     15all_params = []
     16for soundfile in list_of_sounds:
     17    for hop_size in hop_sizes:
     18        for samplerate in samplerates:
     19            all_params.append((hop_size, samplerate, soundfile))
     20
    1021
    1122class aubio_source_test_case_base(TestCase):
     
    1324    def setUp(self):
    1425        if not len(list_of_sounds): self.skipTest('add some sound files in \'python/tests/sounds\'')
     26        self.default_test_sound = list_of_sounds[0]
    1527
    1628class aubio_source_test_case(aubio_source_test_case_base):
     
    3648        total_frames = 0
    3749        while True:
    38             vec, read = f()
     50            _ , read = f()
    3951            total_frames += read
    4052            if read < f.hop_size: break
    41         print "read", "%.2fs" % (total_frames / float(f.samplerate) ),
    42         print "(", total_frames, "frames", "in",
    43         print total_frames / f.hop_size, "blocks", "at", "%dHz" % f.samplerate, ")",
    44         print "from", f.uri
     53        #result_str = "read {:.2f}s ({:d} frames in {:d} blocks at {:d}Hz) from {:s}"
     54        #result_params = total_frames / float(f.samplerate), total_frames, total_frames//f.hop_size, f.samplerate, f.uri
     55        #print (result_str.format(*result_params))
    4556        return total_frames
    4657
    47     def test_samplerate_hopsize(self):
    48         for p in list_of_sounds:
    49             for samplerate, hop_size in zip([0, 44100, 8000, 32000], [ 512, 512, 64, 256]):
    50                 f = source(p, samplerate, hop_size)
    51                 assert f.samplerate != 0
    52                 self.read_from_source(f)
     58    @params(*all_params)
     59    def test_samplerate_hopsize(self, hop_size, samplerate, soundfile):
     60        try:
     61            f = source(soundfile, samplerate, hop_size)
     62        except RuntimeError as e:
     63            self.skipTest('failed opening with hop_s = {:d}, samplerate = {:d} ({:s})'.format(hop_size, samplerate, str(e)))
     64        assert f.samplerate != 0
     65        self.read_from_source(f)
    5366
    54     def test_samplerate_none(self):
    55         for p in list_of_sounds:
    56             f = source(p)
    57             assert f.samplerate != 0
    58             self.read_from_source(f)
     67    @params(*list_of_sounds)
     68    def test_samplerate_none(self, p):
     69        f = source(p)
     70        assert f.samplerate != 0
     71        self.read_from_source(f)
    5972
    60     def test_samplerate_0(self):
    61         for p in list_of_sounds:
    62             f = source(p, 0)
    63             assert f.samplerate != 0
    64             self.read_from_source(f)
     73    @params(*list_of_sounds)
     74    def test_samplerate_0(self, p):
     75        f = source(p, 0)
     76        assert f.samplerate != 0
     77        self.read_from_source(f)
     78
     79    @params(*list_of_sounds)
     80    def test_zero_hop_size(self, p):
     81        f = source(p, 0, 0)
     82        assert f.samplerate != 0
     83        assert f.hop_size != 0
     84        self.read_from_source(f)
     85
     86    @params(*list_of_sounds)
     87    def test_seek_to_half(self, p):
     88        from random import randint
     89        f = source(p, 0, 0)
     90        assert f.samplerate != 0
     91        assert f.hop_size != 0
     92        a = self.read_from_source(f)
     93        c = randint(0, a)
     94        f.seek(c)
     95        b = self.read_from_source(f)
     96        assert a == b + c
     97
     98    @params(*list_of_sounds)
     99    def test_duration(self, p):
     100        total_frames = 0
     101        f = source(p)
     102        duration = f.duration
     103        while True:
     104            _, read = f()
     105            total_frames += read
     106            if read < f.hop_size: break
     107        self.assertEqual(duration, total_frames)
     108
     109
     110class aubio_source_test_wrong_params(TestCase):
     111
     112    def test_wrong_file(self):
     113        with self.assertRaises(RuntimeError):
     114            source('path_to/unexisting file.mp3')
     115
     116class aubio_source_test_wrong_params_with_file(aubio_source_test_case_base):
    65117
    66118    def test_wrong_samplerate(self):
    67         for p in list_of_sounds:
    68             try:
    69                 f = source(p, -1)
    70             except ValueError, e:
    71                 pass
    72             else:
    73                 self.fail('negative samplerate does not raise ValueError')
     119        with self.assertRaises(ValueError):
     120            source(self.default_test_sound, -1)
    74121
    75122    def test_wrong_hop_size(self):
    76         for p in list_of_sounds:
    77             try:
    78                 f = source(p, 0, -1)
    79             except ValueError, e:
    80                 pass
    81             else:
    82                 self.fail('negative hop_size does not raise ValueError')
     123        with self.assertRaises(ValueError):
     124            source(self.default_test_sound, 0, -1)
    83125
    84     def test_zero_hop_size(self):
    85         for p in list_of_sounds:
    86             f = source(p, 0, 0)
    87             assert f.samplerate != 0
    88             assert f.hop_size != 0
    89             self.read_from_source(f)
     126    def test_wrong_channels(self):
     127        with self.assertRaises(ValueError):
     128            source(self.default_test_sound, 0, 0, -1)
    90129
    91     def test_seek_to_half(self):
    92         from random import randint
    93         for p in list_of_sounds:
    94             f = source(p, 0, 0)
    95             assert f.samplerate != 0
    96             assert f.hop_size != 0
    97             a = self.read_from_source(f)
    98             c = randint(0, a)
    99             f.seek(c)
    100             b = self.read_from_source(f)
    101             assert a == b + c
     130    def test_wrong_seek(self):
     131        f = source(self.default_test_sound)
     132        with self.assertRaises(ValueError):
     133            f.seek(-1)
     134
     135    def test_wrong_seek_too_large(self):
     136        f = source(self.default_test_sound)
     137        try:
     138            with self.assertRaises(ValueError):
     139                f.seek(f.duration + f.samplerate * 10)
     140        except AssertionError:
     141            self.skipTest('seeking after end of stream failed raising ValueError')
    102142
    103143class aubio_source_readmulti_test_case(aubio_source_read_test_case):
     
    106146        total_frames = 0
    107147        while True:
    108             vec, read = f.do_multi()
     148            _, read = f.do_multi()
    109149            total_frames += read
    110150            if read < f.hop_size: break
    111         print "read", "%.2fs" % (total_frames / float(f.samplerate) ),
    112         print "(", total_frames, "frames", "in",
    113         print f.channels, "channels and",
    114         print total_frames / f.hop_size, "blocks", "at", "%dHz" % f.samplerate, ")",
    115         print "from", f.uri
     151        #result_str = "read {:.2f}s ({:d} frames in {:d} channels and {:d} blocks at {:d}Hz) from {:s}"
     152        #result_params = total_frames / float(f.samplerate), total_frames, f.channels, int(total_frames/f.hop_size), f.samplerate, f.uri
     153        #print (result_str.format(*result_params))
    116154        return total_frames
    117155
    118156if __name__ == '__main__':
    119     from unittest import main
    120157    main()
  • python/tests/test_specdesc.py

    r60fc05b rf264b17  
    11#! /usr/bin/env python
    22
     3from unittest import main
    34from numpy.testing import TestCase, assert_equal, assert_almost_equal
    45from numpy import random, arange, log, zeros
    5 from aubio import specdesc, cvec
    6 from math import pi
     6from aubio import specdesc, cvec, float_type
    77
    88methods = ["default",
     
    3030
    3131        for method in methods:
    32           o = specdesc(method, buf_size)
    33           assert_equal ([o.buf_size, o.method], [buf_size, method])
    34 
    35           spec = cvec(buf_size)
    36           spec.norm[0] = 1
    37           spec.norm[1] = 1./2.
    38           #print "%20s" % method, str(o(spec))
    39           o(spec)
    40           spec.norm = random.random_sample((len(spec.norm),)).astype('float32')
    41           spec.phas = random.random_sample((len(spec.phas),)).astype('float32')
    42           #print "%20s" % method, str(o(spec))
    43           assert (o(spec) != 0.)
    44 
    45     def test_hfc(self):
    46         o = specdesc("hfc", buf_size)
    47         spec = cvec(buf_size)
    48         # hfc of zeros is zero
    49         assert_equal (o(spec), 0.)
    50         # hfc of ones is sum of all bin numbers
    51         spec.norm[:] = 1
    52         expected = sum(range(buf_size/2 + 2))
    53         assert_equal (o(spec), expected)
    54         # changing phase doesn't change anything
    55         spec.phas[:] = 1
    56         assert_equal (o(spec), sum(range(buf_size/2 + 2)))
     32            o = specdesc(method, buf_size)
     33            assert_equal ([o.buf_size, o.method], [buf_size, method])
     34
     35            spec = cvec(buf_size)
     36            spec.norm[0] = 1
     37            spec.norm[1] = 1./2.
     38            #print "%20s" % method, str(o(spec))
     39            o(spec)
     40            spec.norm = random.random_sample((len(spec.norm),)).astype(float_type)
     41            spec.phas = random.random_sample((len(spec.phas),)).astype(float_type)
     42            #print "%20s" % method, str(o(spec))
     43            assert (o(spec) != 0.)
    5744
    5845    def test_phase(self):
     
    6148        # phase of zeros is zero
    6249        assert_equal (o(spec), 0.)
    63         spec.phas = random.random_sample((len(spec.phas),)).astype('float32')
     50        spec.phas = random.random_sample((len(spec.phas),)).astype(float_type)
    6451        # phase of random is not zero
    6552        spec.norm[:] = 1
     
    7158        # specdiff of zeros is zero
    7259        assert_equal (o(spec), 0.)
    73         spec.phas = random.random_sample((len(spec.phas),)).astype('float32')
     60        spec.phas = random.random_sample((len(spec.phas),)).astype(float_type)
    7461        # phase of random is not zero
    7562        spec.norm[:] = 1
     
    8067        c = cvec()
    8168        assert_equal( 0., o(c))
    82         a = arange(c.length, dtype='float32')
     69        a = arange(c.length, dtype=float_type)
    8370        c.norm = a
    8471        assert_equal (a, c.norm)
     
    8976        c = cvec()
    9077        assert_equal( 0., o(c))
    91         a = arange(c.length, dtype='float32')
     78        a = arange(c.length, dtype=float_type)
    9279        c.norm = a
    9380        assert_equal (a, c.norm)
     
    10289        c = cvec()
    10390        assert_equal( 0., o(c))
    104         a = arange(c.length, dtype='float32')
     91        a = arange(c.length, dtype=float_type)
    10592        c.norm = a
    10693        assert_almost_equal( sum(a * log(1.+ a/1.e-1 ) ) / o(c), 1., decimal=6)
     
    11097        c = cvec()
    11198        assert_equal( 0., o(c))
    112         a = arange(c.length, dtype='float32')
     99        a = arange(c.length, dtype=float_type)
    113100        c.norm = a
    114101        assert_almost_equal( sum(log(1.+ a/1.e-1 ) ) / o(c), 1, decimal=6)
     
    118105        c = cvec()
    119106        assert_equal( 0., o(c))
    120         a = arange(c.length, dtype='float32')
     107        a = arange(c.length, dtype=float_type)
    121108        c.norm = a
    122109        assert_equal( sum(a), o(c))
    123110        assert_equal( 0, o(c))
    124         c.norm = zeros(c.length, dtype='float32')
     111        c.norm = zeros(c.length, dtype=float_type)
    125112        assert_equal( 0, o(c))
    126113
     
    130117        # make sure centroid of zeros is zero
    131118        assert_equal( 0., o(c))
    132         a = arange(c.length, dtype='float32')
     119        a = arange(c.length, dtype=float_type)
    133120        c.norm = a
    134121        centroid = sum(a*a) / sum(a)
     
    141128        o = specdesc("spread")
    142129        c = cvec(2048)
    143         ramp = arange(c.length, dtype='float32')
     130        ramp = arange(c.length, dtype=float_type)
    144131        assert_equal( 0., o(c))
    145132
     
    154141        c = cvec()
    155142        assert_equal( 0., o(c))
    156         a = arange(c.length, dtype='float32')
     143        a = arange(c.length, dtype=float_type)
    157144        c.norm = a
    158145        centroid = sum(a*a) / sum(a)
     
    168155        c = cvec()
    169156        assert_equal( 0., o(c))
    170         a = arange(c.length, dtype='float32')
     157        a = arange(c.length, dtype=float_type)
    171158        c.norm = a
    172159        centroid = sum(a*a) / sum(a)
     
    179166        c = cvec()
    180167        assert_equal( 0., o(c))
    181         a = arange(c.length * 2, 0, -2, dtype='float32')
    182         k = arange(c.length, dtype='float32')
     168        a = arange(c.length * 2, 0, -2, dtype=float_type)
     169        k = arange(c.length, dtype=float_type)
    183170        c.norm = a
    184171        num = len(a) * sum(k*a) - sum(k)*sum(a)
     
    187174        assert_almost_equal (slope, o(c), decimal = 5)
    188175
    189         a = arange(0, c.length * 2, +2, dtype='float32')
     176        a = arange(0, c.length * 2, +2, dtype=float_type)
    190177        c.norm = a
    191178        num = len(a) * sum(k*a) - sum(k)*sum(a)
     
    194181        assert_almost_equal (slope, o(c), decimal = 5)
    195182
    196         a = arange(0, c.length * 2, +2, dtype='float32')
     183        a = arange(0, c.length * 2, +2, dtype=float_type)
    197184        c.norm = a * 2
    198185        assert_almost_equal (slope, o(c), decimal = 5)
     
    202189        c = cvec()
    203190        assert_equal( 0., o(c))
    204         a = arange(c.length * 2, 0, -2, dtype='float32')
    205         k = arange(c.length, dtype='float32')
     191        a = arange(c.length * 2, 0, -2, dtype=float_type)
     192        k = arange(c.length, dtype=float_type)
    206193        c.norm = a
    207194        decrease = sum((a[1:] - a [0]) / k[1:]) / sum(a[1:])
    208195        assert_almost_equal (decrease, o(c), decimal = 5)
    209196
    210         a = arange(0, c.length * 2, +2, dtype='float32')
     197        a = arange(0, c.length * 2, +2, dtype=float_type)
    211198        c.norm = a
    212199        decrease = sum((a[1:] - a [0]) / k[1:]) / sum(a[1:])
    213200        assert_almost_equal (decrease, o(c), decimal = 5)
    214201
    215         a = arange(0, c.length * 2, +2, dtype='float32')
     202        a = arange(0, c.length * 2, +2, dtype=float_type)
    216203        c.norm = a * 2
    217204        decrease = sum((a[1:] - a [0]) / k[1:]) / sum(a[1:])
     
    222209        c = cvec()
    223210        assert_equal( 0., o(c))
    224         a = arange(c.length * 2, 0, -2, dtype='float32')
    225         k = arange(c.length, dtype='float32')
     211        a = arange(c.length * 2, 0, -2, dtype=float_type)
    226212        c.norm = a
    227213        cumsum = .95*sum(a*a)
    228214        i = 0; rollsum = 0
    229215        while rollsum < cumsum:
    230           rollsum += a[i]*a[i]
    231           i+=1
     216            rollsum += a[i]*a[i]
     217            i+=1
    232218        rolloff = i
    233219        assert_equal (rolloff, o(c))
    234220
     221class aubio_specdesc_wrong(TestCase):
     222
     223    def test_negative(self):
     224        with self.assertRaises(ValueError):
     225            specdesc("default", -10)
     226
     227    def test_unknown(self):
     228        # FIXME should fail?
     229        with self.assertRaises(ValueError):
     230            specdesc("unknown", 512)
     231            self.skipTest('todo: new_specdesc should fail on wrong method')
    235232
    236233if __name__ == '__main__':
    237     from unittest import main
    238234    main()
  • python/tests/test_zero_crossing_rate.py

    r60fc05b rf264b17  
    11#! /usr/bin/env python
    22
     3from unittest import main
    34from numpy.testing import TestCase
    4 
    55from aubio import fvec, zero_crossing_rate
    66
     
    2323    def test_impulse(self):
    2424        """ check zero crossing rate on a buffer with an impulse """
    25         self.vector[buf_size / 2] = 1.
     25        self.vector[int(buf_size / 2)] = 1.
    2626        self.assertEqual(0., zero_crossing_rate(self.vector))
    2727
    2828    def test_negative_impulse(self):
    2929        """ check zero crossing rate on a buffer with a negative impulse """
    30         self.vector[buf_size / 2] = -1.
     30        self.vector[int(buf_size / 2)] = -1.
    3131        self.assertEqual(2./buf_size, zero_crossing_rate(self.vector))
    3232
    3333    def test_single(self):
    3434        """ check zero crossing rate on single crossing """
    35         self.vector[buf_size / 2 - 1] = 1.
    36         self.vector[buf_size / 2] = -1.
     35        self.vector[int(buf_size / 2) - 1] = 1.
     36        self.vector[int(buf_size / 2)] = -1.
    3737        self.assertEqual(2./buf_size, zero_crossing_rate(self.vector))
    3838
    3939    def test_single_with_gap(self):
    4040        """ check zero crossing rate on single crossing with a gap"""
    41         self.vector[buf_size / 2 - 2] = 1.
    42         self.vector[buf_size / 2] = -1.
     41        self.vector[int(buf_size / 2) - 2] = 1.
     42        self.vector[int(buf_size / 2)] = -1.
    4343        self.assertEqual(2./buf_size, zero_crossing_rate(self.vector))
    4444
    4545if __name__ == '__main__':
    46     from unittest import main
    4746    main()
  • python/tests/utils.py

    r60fc05b rf264b17  
    11#! /usr/bin/env python
    22
     3import os
     4import glob
     5import numpy as np
     6from tempfile import mkstemp
     7
    38def array_from_text_file(filename, dtype = 'float'):
    4     import os.path
    5     from numpy import array
    69    filename = os.path.join(os.path.dirname(__file__), filename)
    7     return array([line.split() for line in open(filename).readlines()],
    8         dtype = dtype)
     10    with open(filename) as f:
     11        lines = f.readlines()
     12    return np.array([line.split() for line in lines],
     13            dtype = dtype)
    914
    1015def list_all_sounds(rel_dir):
    11     import os.path, glob
    1216    datadir = os.path.join(os.path.dirname(__file__), rel_dir)
    1317    return glob.glob(os.path.join(datadir,'*.*'))
     
    2125
    2226def get_tmp_sink_path():
    23     from tempfile import mkstemp
    24     import os
    2527    fd, path = mkstemp()
    2628    os.close(fd)
     
    2830
    2931def del_tmp_sink_path(path):
    30     import os
    31     os.unlink(path)
     32    try:
     33        os.unlink(path)
     34    except WindowsError as e:
     35        print("deleting {:s} failed ({:s}), reopening".format(path, repr(e)))
     36        with open(path, 'wb') as f:
     37            f.close()
     38        try:
     39            os.unlink(path)
     40        except WindowsError as f:
     41            print("deleting {:s} failed ({:s}), aborting".format(path, repr(e)))
    3242
    3343def array_from_yaml_file(filename):
     
    4454    total_frames = 0
    4555    while True:
    46         samples, read = s()
     56        _, read = s()
    4757        total_frames += read
    4858        if read < hopsize: break
     
    5060
    5161def count_samples_in_directory(samples_dir):
    52     import os
    5362    total_frames = 0
    5463    for f in os.walk(samples_dir):
     
    6170
    6271def count_files_in_directory(samples_dir):
    63     import os
    6472    total_files = 0
    6573    for f in os.walk(samples_dir):
  • src/aubio_priv.h

    r60fc05b rf264b17  
    2525 */
    2626
    27 #ifndef _AUBIO__PRIV_H
    28 #define _AUBIO__PRIV_H
     27#ifndef AUBIO_PRIV_H
     28#define AUBIO_PRIV_H
    2929
    3030/*********************
     
    3636#include "config.h"
    3737
    38 #if HAVE_STDLIB_H
     38#ifdef HAVE_STDLIB_H
    3939#include <stdlib.h>
    4040#endif
    4141
    42 #if HAVE_STDIO_H
     42#ifdef HAVE_STDIO_H
    4343#include <stdio.h>
    4444#endif
     
    6363#ifdef HAVE_LIMITS_H
    6464#include <limits.h> // for CHAR_BIT, in C99 standard
     65#endif
     66
     67#ifdef HAVE_ACCELERATE
     68#define HAVE_ATLAS 1
     69#include <Accelerate/Accelerate.h>
     70#elif defined(HAVE_ATLAS_CBLAS_H)
     71#define HAVE_ATLAS 1
     72#include <atlas/cblas.h>
     73#else
     74#undef HAVE_ATLAS
     75#endif
     76
     77#ifdef HAVE_ACCELERATE
     78#include <Accelerate/Accelerate.h>
     79#ifndef HAVE_AUBIO_DOUBLE
     80#define aubio_vDSP_mmov       vDSP_mmov
     81#define aubio_vDSP_vmul       vDSP_vmul
     82#define aubio_vDSP_vfill      vDSP_vfill
     83#define aubio_vDSP_meanv      vDSP_meanv
     84#define aubio_vDSP_sve        vDSP_sve
     85#define aubio_vDSP_maxv       vDSP_maxv
     86#define aubio_vDSP_maxvi      vDSP_maxvi
     87#define aubio_vDSP_minv       vDSP_minv
     88#define aubio_vDSP_minvi      vDSP_minvi
     89#define aubio_vDSP_dotpr      vDSP_dotpr
     90#else /* HAVE_AUBIO_DOUBLE */
     91#define aubio_vDSP_mmov       vDSP_mmovD
     92#define aubio_vDSP_vmul       vDSP_vmulD
     93#define aubio_vDSP_vfill      vDSP_vfillD
     94#define aubio_vDSP_meanv      vDSP_meanvD
     95#define aubio_vDSP_sve        vDSP_sveD
     96#define aubio_vDSP_maxv       vDSP_maxvD
     97#define aubio_vDSP_maxvi      vDSP_maxviD
     98#define aubio_vDSP_minv       vDSP_minvD
     99#define aubio_vDSP_minvi      vDSP_minviD
     100#define aubio_vDSP_dotpr      vDSP_dotprD
     101#endif /* HAVE_AUBIO_DOUBLE */
     102#endif /* HAVE_ACCELERATE */
     103
     104#ifdef HAVE_ATLAS
     105#ifndef HAVE_AUBIO_DOUBLE
     106#define aubio_catlas_set      catlas_sset
     107#define aubio_cblas_copy      cblas_scopy
     108#define aubio_cblas_swap      cblas_sswap
     109#define aubio_cblas_dot       cblas_sdot
     110#else /* HAVE_AUBIO_DOUBLE */
     111#define aubio_catlas_set      catlas_dset
     112#define aubio_cblas_copy      cblas_dcopy
     113#define aubio_cblas_swap      cblas_dswap
     114#define aubio_cblas_dot       cblas_ddot
     115#endif /* HAVE_AUBIO_DOUBLE */
     116#endif /* HAVE_ATLAS */
     117
     118#if !defined(HAVE_MEMCPY_HACKS) && !defined(HAVE_ACCELERATE) && !defined(HAVE_ATLAS)
     119#define HAVE_NOOPT 1
     120#else
     121#undef HAVE_NOOPT
    65122#endif
    66123
     
    136193#endif
    137194#define TWO_PI     (PI*2.)
     195
     196#ifndef PATH_MAX
     197#define PATH_MAX 1024
     198#endif
    138199
    139200/* aliases to math.h functions */
     
    194255#endif
    195256
     257/* avoid unresolved symbol with msvc 9 */
     258#if defined(_MSC_VER) && (_MSC_VER < 1900)
     259#define isnan _isnan
     260#endif
     261
    196262/* handy shortcuts */
    197263#define DB2LIN(g) (POW(10.0,(g)*0.05f))
     
    229295#endif
    230296
    231 #endif /* _AUBIO__PRIV_H */
     297/* are we using gcc -std=c99 ? */
     298#if defined(__STRICT_ANSI__)
     299#define strnlen(a,b) MIN(strlen(a),b)
     300#if !HAVE_AUBIO_DOUBLE
     301#define floorf floor
     302#endif
     303#endif /* __STRICT_ANSI__ */
     304
     305#endif /* AUBIO_PRIV_H */
  • src/cvec.c

    r60fc05b rf264b17  
    2222#include "cvec.h"
    2323
    24 cvec_t * new_cvec( uint_t length) {
     24cvec_t * new_cvec(uint_t length) {
    2525  cvec_t * s;
    2626  if ((sint_t)length <= 0) {
     
    5656}
    5757
    58 smpl_t * cvec_norm_get_data (cvec_t *s) {
     58smpl_t * cvec_norm_get_data (const cvec_t *s) {
    5959  return s->norm;
    6060}
    6161
    62 smpl_t * cvec_phas_get_data (cvec_t *s) {
     62smpl_t * cvec_phas_get_data (const cvec_t *s) {
    6363  return s->phas;
    6464}
     
    6666/* helper functions */
    6767
    68 void cvec_print(cvec_t *s) {
     68void cvec_print(const cvec_t *s) {
    6969  uint_t j;
    7070  AUBIO_MSG("norm: ");
     
    8080}
    8181
    82 void cvec_copy(cvec_t *s, cvec_t *t) {
     82void cvec_copy(const cvec_t *s, cvec_t *t) {
    8383  if (s->length != t->length) {
    8484    AUBIO_ERR("trying to copy %d elements to %d elements \n",
     
    8686    return;
    8787  }
    88 #if HAVE_MEMCPY_HACKS
     88#ifdef HAVE_MEMCPY_HACKS
    8989  memcpy(t->norm, s->norm, t->length * sizeof(smpl_t));
    9090  memcpy(t->phas, s->phas, t->length * sizeof(smpl_t));
    91 #else
     91#else /* HAVE_MEMCPY_HACKS */
    9292  uint_t j;
    9393  for (j=0; j< t->length; j++) {
     
    9595    t->phas[j] = s->phas[j];
    9696  }
    97 #endif
     97#endif /* HAVE_MEMCPY_HACKS */
    9898}
    9999
     
    106106
    107107void cvec_norm_zeros(cvec_t *s) {
    108 #if HAVE_MEMCPY_HACKS
     108#ifdef HAVE_MEMCPY_HACKS
    109109  memset(s->norm, 0, s->length * sizeof(smpl_t));
    110 #else
     110#else /* HAVE_MEMCPY_HACKS */
    111111  cvec_norm_set_all (s, 0.);
    112 #endif
     112#endif /* HAVE_MEMCPY_HACKS */
    113113}
    114114
     
    125125
    126126void cvec_phas_zeros(cvec_t *s) {
    127 #if HAVE_MEMCPY_HACKS
     127#ifdef HAVE_MEMCPY_HACKS
    128128  memset(s->phas, 0, s->length * sizeof(smpl_t));
    129129#else
  • src/cvec.h

    r60fc05b rf264b17  
    1919*/
    2020
    21 #ifndef _AUBIO__CVEC_H
    22 #define _AUBIO__CVEC_H
     21#ifndef AUBIO_CVEC_H
     22#define AUBIO_CVEC_H
    2323
    2424#ifdef __cplusplus
     
    151151
    152152*/
    153 smpl_t * cvec_norm_get_data (cvec_t *s);
     153smpl_t * cvec_norm_get_data (const cvec_t *s);
    154154
    155155/** read phase data from a complex buffer
     
    163163
    164164*/
    165 smpl_t * cvec_phas_get_data (cvec_t *s);
     165smpl_t * cvec_phas_get_data (const cvec_t *s);
    166166
    167167/** print out cvec data
     
    170170
    171171*/
    172 void cvec_print(cvec_t *s);
     172void cvec_print(const cvec_t *s);
    173173
    174174/** make a copy of a vector
     
    178178
    179179*/
    180 void cvec_copy(cvec_t *s, cvec_t *t);
     180void cvec_copy(const cvec_t *s, cvec_t *t);
    181181
    182182/** set all norm elements to a given value
     
    235235#endif
    236236
    237 #endif /* _AUBIO__CVEC_H */
     237#endif /* AUBIO_CVEC_H */
  • src/fmat.c

    r60fc05b rf264b17  
    5454}
    5555
    56 smpl_t fmat_get_sample(fmat_t *s, uint_t channel, uint_t position) {
     56smpl_t fmat_get_sample(const fmat_t *s, uint_t channel, uint_t position) {
    5757  return s->data[channel][position];
    5858}
    5959
    60 void fmat_get_channel(fmat_t *s, uint_t channel, fvec_t *output) {
     60void fmat_get_channel(const fmat_t *s, uint_t channel, fvec_t *output) {
    6161  output->data = s->data[channel];
    6262  output->length = s->length;
     
    6464}
    6565
    66 smpl_t * fmat_get_channel_data(fmat_t *s, uint_t channel) {
     66smpl_t * fmat_get_channel_data(const fmat_t *s, uint_t channel) {
    6767  return s->data[channel];
    6868}
    6969
    70 smpl_t ** fmat_get_data(fmat_t *s) {
     70smpl_t ** fmat_get_data(const fmat_t *s) {
    7171  return s->data;
    7272}
     
    7474/* helper functions */
    7575
    76 void fmat_print(fmat_t *s) {
     76void fmat_print(const fmat_t *s) {
    7777  uint_t i,j;
    7878  for (i=0; i< s->height; i++) {
     
    9494
    9595void fmat_zeros(fmat_t *s) {
    96 #if HAVE_MEMCPY_HACKS
     96#ifdef HAVE_MEMCPY_HACKS
    9797  uint_t i;
    9898  for (i=0; i< s->height; i++) {
    9999    memset(s->data[i], 0, s->length * sizeof(smpl_t));
    100100  }
    101 #else
     101#else /* HAVE_MEMCPY_HACKS */
    102102  fmat_set(s, 0.);
    103 #endif
     103#endif /* HAVE_MEMCPY_HACKS */
    104104}
    105105
     
    117117}
    118118
    119 void fmat_weight(fmat_t *s, fmat_t *weight) {
     119void fmat_weight(fmat_t *s, const fmat_t *weight) {
    120120  uint_t i,j;
    121121  uint_t length = MIN(s->length, weight->length);
     
    127127}
    128128
    129 void fmat_copy(fmat_t *s, fmat_t *t) {
     129void fmat_copy(const fmat_t *s, fmat_t *t) {
    130130  uint_t i;
    131 #if !HAVE_MEMCPY_HACKS
     131#ifndef HAVE_MEMCPY_HACKS
    132132  uint_t j;
    133 #endif
     133#endif /* HAVE_MEMCPY_HACKS */
    134134  if (s->height != t->height) {
    135135    AUBIO_ERR("trying to copy %d rows to %d rows \n",
     
    142142    return;
    143143  }
    144 #if HAVE_MEMCPY_HACKS
     144#ifdef HAVE_MEMCPY_HACKS
    145145  for (i=0; i< s->height; i++) {
    146146    memcpy(t->data[i], s->data[i], t->length * sizeof(smpl_t));
    147147  }
    148 #else
     148#else /* HAVE_MEMCPY_HACKS */
    149149  for (i=0; i< t->height; i++) {
    150150    for (j=0; j< t->length; j++) {
     
    152152    }
    153153  }
     154#endif /* HAVE_MEMCPY_HACKS */
     155}
     156
     157void fmat_vecmul(const fmat_t *s, const fvec_t *scale, fvec_t *output) {
     158  uint_t k;
     159#if 0
     160  assert(s->height == output->length);
     161  assert(s->length == scale->length);
     162#endif
     163#if !defined(HAVE_ACCELERATE) && !defined(HAVE_ATLAS)
     164  uint_t j;
     165  fvec_zeros(output);
     166  for (j = 0; j < s->length; j++) {
     167    for (k = 0; k < s->height; k++) {
     168      output->data[k] += scale->data[j]
     169          * s->data[k][j];
     170    }
     171  }
     172#elif defined(HAVE_ATLAS)
     173  for (k = 0; k < s->height; k++) {
     174    output->data[k] = aubio_cblas_dot( s->length, scale->data, 1, s->data[k], 1);
     175  }
     176#elif defined(HAVE_ACCELERATE)
     177#if 0
     178  // seems slower and less precise (and dangerous?)
     179  vDSP_mmul (s->data[0], 1, scale->data, 1, output->data, 1, s->height, 1, s->length);
     180#else
     181  for (k = 0; k < s->height; k++) {
     182    aubio_vDSP_dotpr( scale->data, 1, s->data[k], 1, &(output->data[k]), s->length);
     183  }
     184#endif
    154185#endif
    155186}
    156 
  • src/fmat.h

    r60fc05b rf264b17  
    1919*/
    2020
    21 #ifndef _AUBIO__FMAT_H
    22 #define _AUBIO__FMAT_H
     21#ifndef AUBIO_FMAT_H
     22#define AUBIO_FMAT_H
    2323
    2424#ifdef __cplusplus
     
    6666
    6767*/
    68 smpl_t fmat_get_sample(fmat_t *s, uint_t channel, uint_t position);
     68smpl_t fmat_get_sample(const fmat_t *s, uint_t channel, uint_t position);
    6969
    7070/** write sample value in a buffer
     
    8585
    8686*/
    87 void fmat_get_channel (fmat_t *s, uint_t channel, fvec_t *output);
     87void fmat_get_channel (const fmat_t *s, uint_t channel, fvec_t *output);
    8888
    8989/** get vector buffer from an fmat data
     
    9393
    9494*/
    95 smpl_t * fmat_get_channel_data (fmat_t *s, uint_t channel);
     95smpl_t * fmat_get_channel_data (const fmat_t *s, uint_t channel);
    9696
    9797/** read data from a buffer
     
    100100
    101101*/
    102 smpl_t ** fmat_get_data(fmat_t *s);
     102smpl_t ** fmat_get_data(const fmat_t *s);
    103103
    104104/** print out fmat data
     
    107107
    108108*/
    109 void fmat_print(fmat_t *s);
     109void fmat_print(const fmat_t *s);
    110110
    111111/** set all elements to a given value
     
    147147
    148148*/
    149 void fmat_weight(fmat_t *s, fmat_t *weight);
     149void fmat_weight(fmat_t *s, const fmat_t *weight);
    150150
    151151/** make a copy of a matrix
     
    155155
    156156*/
    157 void fmat_copy(fmat_t *s, fmat_t *t);
     157void fmat_copy(const fmat_t *s, fmat_t *t);
     158
     159/* compute the product of a matrix by a vector
     160
     161   \param s matrix to compute product with
     162   \param scale vector to compute product with
     163   \param output vector to store restults in
     164
     165*/
     166void fmat_vecmul(const fmat_t *s, const fvec_t *scale, fvec_t *output);
    158167
    159168#ifdef __cplusplus
     
    161170#endif
    162171
    163 #endif /* _AUBIO__FMAT_H */
     172#endif /* AUBIO_FMAT_H */
  • src/fvec.c

    r60fc05b rf264b17  
    2222#include "fvec.h"
    2323
    24 #ifdef HAVE_ACCELERATE
    25 #include <Accelerate/Accelerate.h>
    26 #if !HAVE_AUBIO_DOUBLE
    27 #define aubio_vDSP_mmov       vDSP_mmov
    28 #define aubio_vDSP_vmul       vDSP_vmul
    29 #define aubio_vDSP_vfill      vDSP_vfill
    30 #else /* HAVE_AUBIO_DOUBLE */
    31 #define aubio_vDSP_mmov       vDSP_mmovD
    32 #define aubio_vDSP_vmul       vDSP_vmulD
    33 #define aubio_vDSP_vfill      vDSP_vfillD
    34 #endif /* HAVE_AUBIO_DOUBLE */
    35 #endif
    36 
    37 fvec_t * new_fvec( uint_t length) {
     24fvec_t * new_fvec(uint_t length) {
    3825  fvec_t * s;
    3926  if ((sint_t)length <= 0) {
     
    5542}
    5643
    57 smpl_t fvec_get_sample(fvec_t *s, uint_t position) {
     44smpl_t fvec_get_sample(const fvec_t *s, uint_t position) {
    5845  return s->data[position];
    5946}
    6047
    61 smpl_t * fvec_get_data(fvec_t *s) {
     48smpl_t * fvec_get_data(const fvec_t *s) {
    6249  return s->data;
    6350}
     
    6552/* helper functions */
    6653
    67 void fvec_print(fvec_t *s) {
     54void fvec_print(const fvec_t *s) {
    6855  uint_t j;
    6956  for (j=0; j< s->length; j++) {
     
    7461
    7562void fvec_set_all (fvec_t *s, smpl_t val) {
    76 #ifndef HAVE_ACCELERATE
     63#if !defined(HAVE_ACCELERATE) && !defined(HAVE_ATLAS)
    7764  uint_t j;
    7865  for (j=0; j< s->length; j++) {
    7966    s->data[j] = val;
    8067  }
    81 #else
     68#elif defined(HAVE_ATLAS)
     69  aubio_catlas_set(s->length, val, s->data, 1);
     70#elif defined(HAVE_ACCELERATE)
    8271  aubio_vDSP_vfill(&val, s->data, 1, s->length);
    8372#endif
     
    10796}
    10897
    109 void fvec_weight(fvec_t *s, fvec_t *weight) {
     98void fvec_weight(fvec_t *s, const fvec_t *weight) {
    11099#ifndef HAVE_ACCELERATE
    111100  uint_t j;
     
    119108}
    120109
    121 void fvec_copy(fvec_t *s, fvec_t *t) {
     110void fvec_weighted_copy(const fvec_t *in, const fvec_t *weight, fvec_t *out) {
     111#ifndef HAVE_ACCELERATE
     112  uint_t j;
     113  uint_t length = MIN(out->length, weight->length);
     114  for (j=0; j< length; j++) {
     115    out->data[j] = in->data[j] * weight->data[j];
     116  }
     117#else
     118  aubio_vDSP_vmul(in->data, 1, weight->data, 1, out->data, 1, out->length);
     119#endif /* HAVE_ACCELERATE */
     120}
     121
     122void fvec_copy(const fvec_t *s, fvec_t *t) {
    122123  if (s->length != t->length) {
    123124    AUBIO_ERR("trying to copy %d elements to %d elements \n",
     
    125126    return;
    126127  }
    127 #if !defined(HAVE_MEMCPY_HACKS) && !defined(HAVE_ACCELERATE)
     128#ifdef HAVE_NOOPT
    128129  uint_t j;
    129130  for (j=0; j< t->length; j++) {
    130131    t->data[j] = s->data[j];
    131132  }
    132 #else
    133 #if defined(HAVE_MEMCPY_HACKS)
     133#elif defined(HAVE_MEMCPY_HACKS)
    134134  memcpy(t->data, s->data, t->length * sizeof(smpl_t));
    135 #else
     135#elif defined(HAVE_ATLAS)
     136  aubio_cblas_copy(s->length, s->data, 1, t->data, 1);
     137#elif defined(HAVE_ACCELERATE)
    136138  aubio_vDSP_mmov(s->data, t->data, 1, s->length, 1, 1);
    137139#endif
    138 #endif
    139140}
  • src/fvec.h

    r60fc05b rf264b17  
    1919*/
    2020
    21 #ifndef _AUBIO__FVEC_H
    22 #define _AUBIO__FVEC_H
     21#ifndef AUBIO_FVEC_H
     22#define AUBIO_FVEC_H
    2323
    2424#ifdef __cplusplus
     
    9090
    9191*/
    92 smpl_t fvec_get_sample(fvec_t *s, uint_t position);
     92smpl_t fvec_get_sample(const fvec_t *s, uint_t position);
    9393
    9494/** write sample value in a buffer
     
    106106
    107107*/
    108 smpl_t * fvec_get_data(fvec_t *s);
     108smpl_t * fvec_get_data(const fvec_t *s);
    109109
    110110/** print out fvec data
     
    113113
    114114*/
    115 void fvec_print(fvec_t *s);
     115void fvec_print(const fvec_t *s);
    116116
    117117/** set all elements to a given value
     
    153153
    154154*/
    155 void fvec_weight(fvec_t *s, fvec_t *weight);
     155void fvec_weight(fvec_t *s, const fvec_t *weight);
    156156
    157157/** make a copy of a vector
     
    161161
    162162*/
    163 void fvec_copy(fvec_t *s, fvec_t *t);
     163void fvec_copy(const fvec_t *s, fvec_t *t);
     164
     165/** make a copy of a vector, applying weights to each element
     166
     167  \param in input vector
     168  \param weight weights vector
     169  \param out output vector
     170
     171*/
     172void fvec_weighted_copy(const fvec_t *in, const fvec_t *weight, fvec_t *out);
    164173
    165174#ifdef __cplusplus
     
    167176#endif
    168177
    169 #endif /* _AUBIO__FVEC_H */
     178#endif /* AUBIO_FVEC_H */
  • src/io/audio_unit.h

    r60fc05b rf264b17  
    1919*/
    2020
    21 #ifndef _AUBIO_AUDIO_UNIT_H
    22 #define _AUBIO_AUDIO_UNIT_H
     21#ifndef AUBIO_AUDIO_UNIT_H
     22#define AUBIO_AUDIO_UNIT_H
    2323
    2424/** \file
     
    5959#endif
    6060
    61 #endif /* _AUBIO_AUDIO_UNIT_H */
     61#endif /* AUBIO_AUDIO_UNIT_H */
  • src/io/sink.c

    r60fc05b rf264b17  
    5555};
    5656
    57 aubio_sink_t * new_aubio_sink(char_t * uri, uint_t samplerate) {
     57aubio_sink_t * new_aubio_sink(const char_t * uri, uint_t samplerate) {
    5858  aubio_sink_t * s = AUBIO_NEW(aubio_sink_t);
    5959#ifdef HAVE_SINK_APPLE_AUDIO
     
    7171  }
    7272#endif /* HAVE_SINK_APPLE_AUDIO */
    73 #if HAVE_SNDFILE
     73#ifdef HAVE_SNDFILE
    7474  s->sink = (void *)new_aubio_sink_sndfile(uri, samplerate);
    7575  if (s->sink) {
     
    8585  }
    8686#endif /* HAVE_SNDFILE */
    87 #if HAVE_WAVWRITE
     87#ifdef HAVE_WAVWRITE
    8888  s->sink = (void *)new_aubio_sink_wavwrite(uri, samplerate);
    8989  if (s->sink) {
     
    121121}
    122122
    123 uint_t aubio_sink_get_samplerate(aubio_sink_t * s) {
     123uint_t aubio_sink_get_samplerate(const aubio_sink_t * s) {
    124124  return s->s_get_samplerate((void *)s->sink);
    125125}
    126126
    127 uint_t aubio_sink_get_channels(aubio_sink_t * s) {
     127uint_t aubio_sink_get_channels(const aubio_sink_t * s) {
    128128  return s->s_get_channels((void *)s->sink);
    129129}
  • src/io/sink.h

    r60fc05b rf264b17  
    1919*/
    2020
    21 #ifndef _AUBIO_SINK_H
    22 #define _AUBIO_SINK_H
     21#ifndef AUBIO_SINK_H
     22#define AUBIO_SINK_H
    2323
    2424/** \file
     
    7777
    7878*/
    79 aubio_sink_t * new_aubio_sink(char_t * uri, uint_t samplerate);
     79aubio_sink_t * new_aubio_sink(const char_t * uri, uint_t samplerate);
    8080
    8181/**
     
    121121
    122122*/
    123 uint_t aubio_sink_get_samplerate(aubio_sink_t *s);
     123uint_t aubio_sink_get_samplerate(const aubio_sink_t *s);
    124124
    125125/**
     
    131131
    132132*/
    133 uint_t aubio_sink_get_channels(aubio_sink_t *s);
     133uint_t aubio_sink_get_channels(const aubio_sink_t *s);
    134134
    135135/**
     
    179179#endif
    180180
    181 #endif /* _AUBIO_SINK_H */
     181#endif /* AUBIO_SINK_H */
  • src/io/sink_apple_audio.c

    r60fc05b rf264b17  
    3737extern int createAubioBufferList(AudioBufferList *bufferList, int channels, int segmentSize);
    3838extern void freeAudioBufferList(AudioBufferList *bufferList);
    39 extern CFURLRef getURLFromPath(const char * path);
     39extern CFURLRef createURLFromPath(const char * path);
    4040char_t *getPrintableOSStatusError(char_t *str, OSStatus error);
    4141
     
    4343
    4444#define MAX_SIZE 4096 // the maximum number of frames that can be written at a time
     45
     46void aubio_sink_apple_audio_write(aubio_sink_apple_audio_t *s, uint_t write);
    4547
    4648struct _aubio_sink_apple_audio_t {
     
    5658};
    5759
    58 aubio_sink_apple_audio_t * new_aubio_sink_apple_audio(char_t * uri, uint_t samplerate) {
     60aubio_sink_apple_audio_t * new_aubio_sink_apple_audio(const char_t * uri, uint_t samplerate) {
    5961  aubio_sink_apple_audio_t * s = AUBIO_NEW(aubio_sink_apple_audio_t);
    60   s->path = uri;
    6162  s->max_frames = MAX_SIZE;
    62   s->async = true;
     63  s->async = false;
    6364
    6465  if (uri == NULL) {
     
    6667    goto beach;
    6768  }
     69  if (s->path != NULL) AUBIO_FREE(s->path);
     70  s->path = AUBIO_ARRAY(char_t, strnlen(uri, PATH_MAX) + 1);
     71  strncpy(s->path, uri, strnlen(uri, PATH_MAX) + 1);
    6872
    6973  s->samplerate = 0;
     
    111115}
    112116
    113 uint_t aubio_sink_apple_audio_get_samplerate(aubio_sink_apple_audio_t *s)
     117uint_t aubio_sink_apple_audio_get_samplerate(const aubio_sink_apple_audio_t *s)
    114118{
    115119  return s->samplerate;
    116120}
    117121
    118 uint_t aubio_sink_apple_audio_get_channels(aubio_sink_apple_audio_t *s)
     122uint_t aubio_sink_apple_audio_get_channels(const aubio_sink_apple_audio_t *s)
    119123{
    120124  return s->channels;
     
    138142
    139143  AudioFileTypeID fileType = kAudioFileWAVEType;
    140   CFURLRef fileURL = getURLFromPath(s->path);
     144  CFURLRef fileURL = createURLFromPath(s->path);
    141145  bool overwrite = true;
    142146  OSStatus err = noErr;
    143147  err = ExtAudioFileCreateWithURL(fileURL, fileType, &clientFormat, NULL,
    144148     overwrite ? kAudioFileFlags_EraseFile : 0, &s->audioFile);
     149  CFRelease(fileURL);
    145150  if (err) {
    146151    char_t errorstr[20];
     
    162167
    163168void aubio_sink_apple_audio_do(aubio_sink_apple_audio_t * s, fvec_t * write_data, uint_t write) {
    164   OSStatus err = noErr;
    165169  UInt32 c, v;
    166170  short *data = (short*)s->bufferList.mBuffers[0].mData;
     
    179183      }
    180184  }
    181   if (s->async) {
    182     err = ExtAudioFileWriteAsync(s->audioFile, write, &s->bufferList);
    183 
    184     if (err) {
    185       char_t errorstr[20];
    186       AUBIO_ERROR("sink_apple_audio: error while writing %s "
    187           "in ExtAudioFileWriteAsync (%s), switching to sync\n", s->path,
    188           getPrintableOSStatusError(errorstr, err));
    189       s->async = false;
    190     } else {
    191       return;
    192     }
    193 
    194   } else {
    195     err = ExtAudioFileWrite(s->audioFile, write, &s->bufferList);
    196 
    197     if (err) {
    198       char_t errorstr[20];
    199       AUBIO_ERROR("sink_apple_audio: error while writing %s "
    200           "in ExtAudioFileWrite (%s)\n", s->path,
    201           getPrintableOSStatusError(errorstr, err));
    202     }
    203   }
    204   return;
     185  aubio_sink_apple_audio_write(s, write);
    205186}
    206187
    207188void aubio_sink_apple_audio_do_multi(aubio_sink_apple_audio_t * s, fmat_t * write_data, uint_t write) {
    208   OSStatus err = noErr;
    209189  UInt32 c, v;
    210190  short *data = (short*)s->bufferList.mBuffers[0].mData;
     
    223203      }
    224204  }
     205  aubio_sink_apple_audio_write(s, write);
     206}
     207
     208void aubio_sink_apple_audio_write(aubio_sink_apple_audio_t *s, uint_t write) {
     209  OSStatus err = noErr;
    225210  if (s->async) {
    226211    err = ExtAudioFileWriteAsync(s->audioFile, write, &s->bufferList);
    227 
    228212    if (err) {
    229213      char_t errorstr[20];
     214      if (err == kExtAudioFileError_AsyncWriteBufferOverflow) {
     215        sprintf(errorstr,"buffer overflow");
     216      } else if (err == kExtAudioFileError_AsyncWriteTooLarge) {
     217        sprintf(errorstr,"write too large");
     218      } else {
     219        // unknown error
     220        getPrintableOSStatusError(errorstr, err);
     221      }
    230222      AUBIO_ERROR("sink_apple_audio: error while writing %s "
    231           "in ExtAudioFileWriteAsync (%s), switching to sync\n", s->path,
    232           getPrintableOSStatusError(errorstr, err));
    233       s->async = false;
    234     } else {
    235       return;
     223                  "in ExtAudioFileWriteAsync (%s)\n", s->path, errorstr);
    236224    }
    237 
    238225  } else {
    239226    err = ExtAudioFileWrite(s->audioFile, write, &s->bufferList);
    240 
    241227    if (err) {
    242228      char_t errorstr[20];
     
    246232    }
    247233  }
    248   return;
    249234}
    250235
     
    267252void del_aubio_sink_apple_audio(aubio_sink_apple_audio_t * s) {
    268253  if (s->audioFile) aubio_sink_apple_audio_close (s);
     254  if (s->path) AUBIO_FREE(s->path);
    269255  freeAudioBufferList(&s->bufferList);
    270256  AUBIO_FREE(s);
  • src/io/sink_apple_audio.h

    r60fc05b rf264b17  
    1919*/
    2020
    21 #ifndef _AUBIO_SINK_APPLE_AUDIO_H
    22 #define _AUBIO_SINK_APPLE_AUDIO_H
     21#ifndef AUBIO_SINK_APPLE_AUDIO_H
     22#define AUBIO_SINK_APPLE_AUDIO_H
    2323
    2424/** \file
     
    5959
    6060*/
    61 aubio_sink_apple_audio_t * new_aubio_sink_apple_audio(char_t * uri, uint_t samplerate);
     61aubio_sink_apple_audio_t * new_aubio_sink_apple_audio(const char_t * uri, uint_t samplerate);
    6262
    6363/**
     
    103103
    104104*/
    105 uint_t aubio_sink_apple_audio_get_samplerate(aubio_sink_apple_audio_t *s);
     105uint_t aubio_sink_apple_audio_get_samplerate(const aubio_sink_apple_audio_t *s);
    106106
    107107/**
     
    113113
    114114*/
    115 uint_t aubio_sink_apple_audio_get_channels(aubio_sink_apple_audio_t *s);
     115uint_t aubio_sink_apple_audio_get_channels(const aubio_sink_apple_audio_t *s);
    116116
    117117/**
     
    161161#endif
    162162
    163 #endif /* _AUBIO_SINK_APPLE_AUDIO_H */
     163#endif /* AUBIO_SINK_APPLE_AUDIO_H */
  • src/io/sink_sndfile.c

    r60fc05b rf264b17  
    5454uint_t aubio_sink_sndfile_open(aubio_sink_sndfile_t *s);
    5555
    56 aubio_sink_sndfile_t * new_aubio_sink_sndfile(char_t * path, uint_t samplerate) {
     56aubio_sink_sndfile_t * new_aubio_sink_sndfile(const char_t * path, uint_t samplerate) {
    5757  aubio_sink_sndfile_t * s = AUBIO_NEW(aubio_sink_sndfile_t);
    5858  s->max_size = MAX_SIZE;
    59   s->path = path;
    6059
    6160  if (path == NULL) {
     
    6362    return NULL;
    6463  }
     64
     65  if (s->path) AUBIO_FREE(s->path);
     66  s->path = AUBIO_ARRAY(char_t, strnlen(path, PATH_MAX) + 1);
     67  strncpy(s->path, path, strnlen(path, PATH_MAX) + 1);
    6568
    6669  s->samplerate = 0;
     
    107110}
    108111
    109 uint_t aubio_sink_sndfile_get_samplerate(aubio_sink_sndfile_t *s)
     112uint_t aubio_sink_sndfile_get_samplerate(const aubio_sink_sndfile_t *s)
    110113{
    111114  return s->samplerate;
    112115}
    113116
    114 uint_t aubio_sink_sndfile_get_channels(aubio_sink_sndfile_t *s)
     117uint_t aubio_sink_sndfile_get_channels(const aubio_sink_sndfile_t *s)
    115118{
    116119  return s->channels;
     
    220223void del_aubio_sink_sndfile(aubio_sink_sndfile_t * s){
    221224  if (!s) return;
     225  if (s->path) AUBIO_FREE(s->path);
    222226  aubio_sink_sndfile_close(s);
    223227  AUBIO_FREE(s->scratch_data);
  • src/io/sink_sndfile.h

    r60fc05b rf264b17  
    1919*/
    2020
    21 #ifndef _AUBIO_SINK_SNDFILE_H
    22 #define _AUBIO_SINK_SNDFILE_H
     21#ifndef AUBIO_SINK_SNDFILE_H
     22#define AUBIO_SINK_SNDFILE_H
    2323
    2424/** \file
     
    5858
    5959*/
    60 aubio_sink_sndfile_t * new_aubio_sink_sndfile(char_t * uri, uint_t samplerate);
     60aubio_sink_sndfile_t * new_aubio_sink_sndfile(const char_t * uri, uint_t samplerate);
    6161
    6262/**
     
    102102
    103103*/
    104 uint_t aubio_sink_sndfile_get_samplerate(aubio_sink_sndfile_t *s);
     104uint_t aubio_sink_sndfile_get_samplerate(const aubio_sink_sndfile_t *s);
    105105
    106106/**
     
    112112
    113113*/
    114 uint_t aubio_sink_sndfile_get_channels(aubio_sink_sndfile_t *s);
     114uint_t aubio_sink_sndfile_get_channels(const aubio_sink_sndfile_t *s);
    115115
    116116/**
     
    160160#endif
    161161
    162 #endif /* _AUBIO_SINK_SNDFILE_H */
     162#endif /* AUBIO_SINK_SNDFILE_H */
  • src/io/sink_wavwrite.c

    r60fc05b rf264b17  
    7878}
    7979
    80 aubio_sink_wavwrite_t * new_aubio_sink_wavwrite(char_t * path, uint_t samplerate) {
     80aubio_sink_wavwrite_t * new_aubio_sink_wavwrite(const char_t * path, uint_t samplerate) {
    8181  aubio_sink_wavwrite_t * s = AUBIO_NEW(aubio_sink_wavwrite_t);
    8282
     
    9090  }
    9191
    92   s->path = path;
     92  if (s->path) AUBIO_FREE(s->path);
     93  s->path = AUBIO_ARRAY(char_t, strnlen(path, PATH_MAX) + 1);
     94  strncpy(s->path, path, strnlen(path, PATH_MAX) + 1);
     95
    9396  s->max_size = MAX_SIZE;
    9497  s->bitspersample = 16;
     
    143146}
    144147
    145 uint_t aubio_sink_wavwrite_get_samplerate(aubio_sink_wavwrite_t *s)
     148uint_t aubio_sink_wavwrite_get_samplerate(const aubio_sink_wavwrite_t *s)
    146149{
    147150  return s->samplerate;
    148151}
    149152
    150 uint_t aubio_sink_wavwrite_get_channels(aubio_sink_wavwrite_t *s)
     153uint_t aubio_sink_wavwrite_get_channels(const aubio_sink_wavwrite_t *s)
    151154{
    152155  return s->channels;
     
    288291  if (!s) return;
    289292  aubio_sink_wavwrite_close(s);
     293  if (s->path) AUBIO_FREE(s->path);
    290294  AUBIO_FREE(s->scratch_data);
    291295  AUBIO_FREE(s);
  • src/io/sink_wavwrite.h

    r60fc05b rf264b17  
    1919*/
    2020
    21 #ifndef _AUBIO_SINK_WAVWRITE_H
    22 #define _AUBIO_SINK_WAVWRITE_H
     21#ifndef AUBIO_SINK_WAVWRITE_H
     22#define AUBIO_SINK_WAVWRITE_H
    2323
    2424/** \file
     
    5858
    5959*/
    60 aubio_sink_wavwrite_t * new_aubio_sink_wavwrite(char_t * uri, uint_t samplerate);
     60aubio_sink_wavwrite_t * new_aubio_sink_wavwrite(const char_t * uri, uint_t samplerate);
    6161
    6262/**
     
    102102
    103103*/
    104 uint_t aubio_sink_wavwrite_get_samplerate(aubio_sink_wavwrite_t *s);
     104uint_t aubio_sink_wavwrite_get_samplerate(const aubio_sink_wavwrite_t *s);
    105105
    106106/**
     
    112112
    113113*/
    114 uint_t aubio_sink_wavwrite_get_channels(aubio_sink_wavwrite_t *s);
     114uint_t aubio_sink_wavwrite_get_channels(const aubio_sink_wavwrite_t *s);
    115115
    116116/**
     
    160160#endif
    161161
    162 #endif /* _AUBIO_SINK_WAVWRITE_H */
     162#endif /* AUBIO_SINK_WAVWRITE_H */
  • src/io/source.c

    r60fc05b rf264b17  
    4141typedef uint_t (*aubio_source_get_samplerate_t)(aubio_source_t * s);
    4242typedef uint_t (*aubio_source_get_channels_t)(aubio_source_t * s);
     43typedef uint_t (*aubio_source_get_duration_t)(aubio_source_t * s);
    4344typedef uint_t (*aubio_source_seek_t)(aubio_source_t * s, uint_t seek);
    4445typedef uint_t (*aubio_source_close_t)(aubio_source_t * s);
     
    5152  aubio_source_get_samplerate_t s_get_samplerate;
    5253  aubio_source_get_channels_t s_get_channels;
     54  aubio_source_get_duration_t s_get_duration;
    5355  aubio_source_seek_t s_seek;
    5456  aubio_source_close_t s_close;
     
    5658};
    5759
    58 aubio_source_t * new_aubio_source(char_t * uri, uint_t samplerate, uint_t hop_size) {
     60aubio_source_t * new_aubio_source(const char_t * uri, uint_t samplerate, uint_t hop_size) {
    5961  aubio_source_t * s = AUBIO_NEW(aubio_source_t);
    60 #if HAVE_LIBAV
     62#ifdef HAVE_LIBAV
    6163  s->source = (void *)new_aubio_source_avcodec(uri, samplerate, hop_size);
    6264  if (s->source) {
     
    6567    s->s_get_channels = (aubio_source_get_channels_t)(aubio_source_avcodec_get_channels);
    6668    s->s_get_samplerate = (aubio_source_get_samplerate_t)(aubio_source_avcodec_get_samplerate);
     69    s->s_get_duration = (aubio_source_get_duration_t)(aubio_source_avcodec_get_duration);
    6770    s->s_seek = (aubio_source_seek_t)(aubio_source_avcodec_seek);
    6871    s->s_close = (aubio_source_close_t)(aubio_source_avcodec_close);
     
    7881    s->s_get_channels = (aubio_source_get_channels_t)(aubio_source_apple_audio_get_channels);
    7982    s->s_get_samplerate = (aubio_source_get_samplerate_t)(aubio_source_apple_audio_get_samplerate);
     83    s->s_get_duration = (aubio_source_get_duration_t)(aubio_source_apple_audio_get_duration);
    8084    s->s_seek = (aubio_source_seek_t)(aubio_source_apple_audio_seek);
    8185    s->s_close = (aubio_source_close_t)(aubio_source_apple_audio_close);
     
    8488  }
    8589#endif /* HAVE_SOURCE_APPLE_AUDIO */
    86 #if HAVE_SNDFILE
     90#ifdef HAVE_SNDFILE
    8791  s->source = (void *)new_aubio_source_sndfile(uri, samplerate, hop_size);
    8892  if (s->source) {
     
    9195    s->s_get_channels = (aubio_source_get_channels_t)(aubio_source_sndfile_get_channels);
    9296    s->s_get_samplerate = (aubio_source_get_samplerate_t)(aubio_source_sndfile_get_samplerate);
     97    s->s_get_duration = (aubio_source_get_duration_t)(aubio_source_sndfile_get_duration);
    9398    s->s_seek = (aubio_source_seek_t)(aubio_source_sndfile_seek);
    9499    s->s_close = (aubio_source_close_t)(aubio_source_sndfile_close);
     
    97102  }
    98103#endif /* HAVE_SNDFILE */
    99 #if HAVE_WAVREAD
     104#ifdef HAVE_WAVREAD
    100105  s->source = (void *)new_aubio_source_wavread(uri, samplerate, hop_size);
    101106  if (s->source) {
     
    104109    s->s_get_channels = (aubio_source_get_channels_t)(aubio_source_wavread_get_channels);
    105110    s->s_get_samplerate = (aubio_source_get_samplerate_t)(aubio_source_wavread_get_samplerate);
     111    s->s_get_duration = (aubio_source_get_duration_t)(aubio_source_wavread_get_duration);
    106112    s->s_seek = (aubio_source_seek_t)(aubio_source_wavread_seek);
    107113    s->s_close = (aubio_source_close_t)(aubio_source_wavread_close);
     
    142148}
    143149
     150uint_t aubio_source_get_duration(aubio_source_t *s) {
     151  return s->s_get_duration((void *)s->source);
     152}
     153
    144154uint_t aubio_source_seek (aubio_source_t * s, uint_t seek ) {
    145155  return s->s_seek((void *)s->source, seek);
  • src/io/source.h

    r60fc05b rf264b17  
    1919*/
    2020
    21 #ifndef _AUBIO_SOURCE_H
    22 #define _AUBIO_SOURCE_H
     21#ifndef AUBIO_SOURCE_H
     22#define AUBIO_SOURCE_H
    2323
    2424/** \file
     
    8686
    8787*/
    88 aubio_source_t * new_aubio_source(char_t * uri, uint_t samplerate, uint_t hop_size);
     88aubio_source_t * new_aubio_source(const char_t * uri, uint_t samplerate, uint_t hop_size);
    8989
    9090/**
     
    150150/**
    151151
     152  get the duration of source object, in frames
     153
     154  \param s source object, created with ::new_aubio_source
     155  \return number of frames in file
     156
     157*/
     158uint_t aubio_source_get_duration (aubio_source_t * s);
     159
     160/**
     161
    152162  close source object
    153163
     
    172182#endif
    173183
    174 #endif /* _AUBIO_SOURCE_H */
     184#endif /* AUBIO_SOURCE_H */
  • src/io/source_apple_audio.c

    r60fc05b rf264b17  
    5252extern int createAubioBufferList(AudioBufferList *bufferList, int channels, int max_source_samples);
    5353extern void freeAudioBufferList(AudioBufferList *bufferList);
    54 extern CFURLRef getURLFromPath(const char * path);
     54extern CFURLRef createURLFromPath(const char * path);
    5555char_t *getPrintableOSStatusError(char_t *str, OSStatus error);
    5656
    57 uint_t aubio_source_apple_audio_open (aubio_source_apple_audio_t *s, char_t * path);
    58 
    59 aubio_source_apple_audio_t * new_aubio_source_apple_audio(char_t * path, uint_t samplerate, uint_t block_size)
     57uint_t aubio_source_apple_audio_open (aubio_source_apple_audio_t *s, const char_t * path);
     58
     59aubio_source_apple_audio_t * new_aubio_source_apple_audio(const char_t * path, uint_t samplerate, uint_t block_size)
    6060{
    6161  aubio_source_apple_audio_t * s = AUBIO_NEW(aubio_source_apple_audio_t);
     
    8080  s->block_size = block_size;
    8181  s->samplerate = samplerate;
    82   s->path = path;
    8382
    8483  if ( aubio_source_apple_audio_open ( s, path ) ) {
     
    9291}
    9392
    94 uint_t aubio_source_apple_audio_open (aubio_source_apple_audio_t *s, char_t * path)
     93uint_t aubio_source_apple_audio_open (aubio_source_apple_audio_t *s, const char_t * path)
    9594{
    9695  OSStatus err = noErr;
    9796  UInt32 propSize;
    98   s->path = path;
     97
     98  if (s->path) AUBIO_FREE(s->path);
     99  s->path = AUBIO_ARRAY(char_t, strnlen(path, PATH_MAX) + 1);
     100  strncpy(s->path, path, strnlen(path, PATH_MAX) + 1);
    99101
    100102  // open the resource url
    101   CFURLRef fileURL = getURLFromPath(path);
     103  CFURLRef fileURL = createURLFromPath(s->path);
    102104  err = ExtAudioFileOpenURL(fileURL, &s->audioFile);
     105  CFRelease(fileURL);
    103106  if (err == -43) {
    104107    AUBIO_ERR("source_apple_audio: Failed opening %s, "
     
    293296void del_aubio_source_apple_audio(aubio_source_apple_audio_t * s){
    294297  aubio_source_apple_audio_close (s);
     298  if (s->path) AUBIO_FREE(s->path);
    295299  freeAudioBufferList(&s->bufferList);
    296300  AUBIO_FREE(s);
     
    308312  }
    309313  // check if we are not seeking out of the file
    310   SInt64 fileLengthFrames = 0;
    311   UInt32 propSize = sizeof(fileLengthFrames);
    312   ExtAudioFileGetProperty(s->audioFile,
    313       kExtAudioFileProperty_FileLengthFrames, &propSize, &fileLengthFrames);
     314  uint_t fileLengthFrames = aubio_source_apple_audio_get_duration(s);
    314315  // compute position in the source file, before resampling
    315316  smpl_t ratio = s->source_samplerate * 1. / s->samplerate;
     
    352353}
    353354
    354 uint_t aubio_source_apple_audio_get_samplerate(aubio_source_apple_audio_t * s) {
     355uint_t aubio_source_apple_audio_get_samplerate(const aubio_source_apple_audio_t * s) {
    355356  return s->samplerate;
    356357}
    357358
    358 uint_t aubio_source_apple_audio_get_channels(aubio_source_apple_audio_t * s) {
     359uint_t aubio_source_apple_audio_get_channels(const aubio_source_apple_audio_t * s) {
    359360  return s->channels;
    360361}
    361362
     363uint_t aubio_source_apple_audio_get_duration(const aubio_source_apple_audio_t * s) {
     364  SInt64 fileLengthFrames = 0;
     365  UInt32 propSize = sizeof(fileLengthFrames);
     366  OSStatus err = ExtAudioFileGetProperty(s->audioFile,
     367      kExtAudioFileProperty_FileLengthFrames, &propSize, &fileLengthFrames);
     368  if (err) {
     369    char_t errorstr[20];
     370    AUBIO_ERROR("source_apple_audio: Failed getting %s duration, "
     371        "error in ExtAudioFileGetProperty (%s)\n", s->path,
     372        getPrintableOSStatusError(errorstr, err));
     373    return err;
     374  }
     375  return (uint_t)fileLengthFrames;
     376}
     377
    362378#endif /* HAVE_SOURCE_APPLE_AUDIO */
  • src/io/source_apple_audio.h

    r60fc05b rf264b17  
    1919*/
    2020
    21 #ifndef _AUBIO_SOURCE_APPLE_AUDIO_H
    22 #define _AUBIO_SOURCE_APPLE_AUDIO_H
     21#ifndef AUBIO_SOURCE_APPLE_AUDIO_H
     22#define AUBIO_SOURCE_APPLE_AUDIO_H
    2323
    2424/** \file
     
    5858
    5959*/
    60 aubio_source_apple_audio_t * new_aubio_source_apple_audio(char_t * uri, uint_t samplerate, uint_t hop_size);
     60aubio_source_apple_audio_t * new_aubio_source_apple_audio(const char_t * uri, uint_t samplerate, uint_t hop_size);
    6161
    6262/**
     
    9696
    9797*/
    98 uint_t aubio_source_apple_audio_get_samplerate(aubio_source_apple_audio_t * s);
     98uint_t aubio_source_apple_audio_get_samplerate(const aubio_source_apple_audio_t * s);
    9999
    100100/**
     
    106106
    107107*/
    108 uint_t aubio_source_apple_audio_get_channels(aubio_source_apple_audio_t * s);
     108uint_t aubio_source_apple_audio_get_channels(const aubio_source_apple_audio_t * s);
     109
     110/**
     111
     112  get the duration of source object, in frames
     113
     114  \param s source object, created with ::new_aubio_source_apple_audio
     115  \return number of frames in file
     116
     117*/
     118uint_t aubio_source_apple_audio_get_duration(const aubio_source_apple_audio_t * s);
    109119
    110120/**
     
    144154#endif
    145155
    146 #endif /* _AUBIO_SOURCE_APPLE_AUDIO_H */
     156#endif /* AUBIO_SOURCE_APPLE_AUDIO_H */
  • src/io/source_avcodec.c

    r60fc05b rf264b17  
    2424#ifdef HAVE_LIBAV
    2525
    26 // determine whether we use libavformat from ffmpe or libav
    27 #define FFMPEG_LIBAVFORMAT (LIBAVFORMAT_VERSION_MICRO > 99)
     26// determine whether we use libavformat from ffmpeg or from libav
     27#define FFMPEG_LIBAVFORMAT (LIBAVFORMAT_VERSION_MICRO > 99 )
     28// max_analyze_duration2 was used from ffmpeg libavformat 55.43.100 through 57.2.100
     29#define FFMPEG_LIBAVFORMAT_MAX_DUR2 FFMPEG_LIBAVFORMAT && ( \
     30      (LIBAVFORMAT_VERSION_MAJOR == 55 && LIBAVFORMAT_VERSION_MINOR >= 43) \
     31      || (LIBAVFORMAT_VERSION_MAJOR == 56) \
     32      || (LIBAVFORMAT_VERSION_MAJOR == 57 && LIBAVFORMAT_VERSION_MINOR < 2) \
     33      )
    2834
    2935#include <libavcodec/avcodec.h>
     
    6773void aubio_source_avcodec_readframe(aubio_source_avcodec_t *s, uint_t * read_samples);
    6874
    69 aubio_source_avcodec_t * new_aubio_source_avcodec(char_t * path, uint_t samplerate, uint_t hop_size) {
     75uint_t aubio_source_avcodec_has_network_url(aubio_source_avcodec_t *s);
     76
     77uint_t aubio_source_avcodec_has_network_url(aubio_source_avcodec_t *s) {
     78  char proto[20], authorization[256], hostname[128], uripath[256];
     79  int proto_size = 20, authorization_size = 256, hostname_size = 128,
     80      *port_ptr = 0, path_size = 256;
     81  av_url_split(proto, proto_size, authorization, authorization_size, hostname,
     82      hostname_size, port_ptr, uripath, path_size, s->path);
     83  if (strlen(proto)) {
     84    return 1;
     85  }
     86  return 0;
     87}
     88
     89
     90aubio_source_avcodec_t * new_aubio_source_avcodec(const char_t * path, uint_t samplerate, uint_t hop_size) {
    7091  aubio_source_avcodec_t * s = AUBIO_NEW(aubio_source_avcodec_t);
    7192  int err;
     
    85106  s->hop_size = hop_size;
    86107  s->channels = 1;
    87   s->path = path;
     108
     109  if (s->path) AUBIO_FREE(s->path);
     110  s->path = AUBIO_ARRAY(char_t, strnlen(path, PATH_MAX) + 1);
     111  strncpy(s->path, path, strnlen(path, PATH_MAX) + 1);
    88112
    89113  // register all formats and codecs
    90114  av_register_all();
    91115
    92   // if path[0] != '/'
    93   //avformat_network_init();
     116  if (aubio_source_avcodec_has_network_url(s)) {
     117    avformat_network_init();
     118  }
    94119
    95120  // try opening the file and get some info about it
     
    104129
    105130  // try to make sure max_analyze_duration is big enough for most songs
    106 #if FFMPEG_LIBAVFORMAT
     131#if FFMPEG_LIBAVFORMAT_MAX_DUR2
    107132  avFormatCtx->max_analyze_duration2 *= 100;
    108133#else
     
    164189
    165190  if (samplerate == 0) {
    166     samplerate = s->input_samplerate;
    167     //AUBIO_DBG("sampling rate set to 0, automagically adjusting to %d\n", samplerate);
    168   }
    169   s->samplerate = samplerate;
     191    s->samplerate = s->input_samplerate;
     192  } else {
     193    s->samplerate = samplerate;
     194  }
    170195
    171196  if (s->samplerate >  s->input_samplerate) {
     
    300325  s->output = output;
    301326
    302   av_free_packet(&avPacket);
     327  av_packet_unref(&avPacket);
    303328}
    304329
     
    370395}
    371396
    372 uint_t aubio_source_avcodec_get_samplerate(aubio_source_avcodec_t * s) {
     397uint_t aubio_source_avcodec_get_samplerate(const aubio_source_avcodec_t * s) {
    373398  return s->samplerate;
    374399}
    375400
    376 uint_t aubio_source_avcodec_get_channels(aubio_source_avcodec_t * s) {
     401uint_t aubio_source_avcodec_get_channels(const aubio_source_avcodec_t * s) {
    377402  return s->input_channels;
    378403}
     
    398423}
    399424
     425uint_t aubio_source_avcodec_get_duration (aubio_source_avcodec_t * s) {
     426  if (s && &(s->avFormatCtx) != NULL) {
     427    int64_t duration = s->avFormatCtx->duration;
     428    return s->samplerate * ((uint_t)duration / 1e6 );
     429  }
     430  return 0;
     431}
     432
    400433uint_t aubio_source_avcodec_close(aubio_source_avcodec_t * s) {
    401434  if (s->avr != NULL) {
     
    425458    av_frame_free( &(s->avFrame) );
    426459  }
     460  if (s->path) AUBIO_FREE(s->path);
    427461  s->avFrame = NULL;
    428462  AUBIO_FREE(s);
  • src/io/source_avcodec.h

    r60fc05b rf264b17  
    1919*/
    2020
    21 #ifndef _AUBIO_SOURCE_AVCODEC_H
    22 #define _AUBIO_SOURCE_AVCODEC_H
     21#ifndef AUBIO_SOURCE_AVCODEC_H
     22#define AUBIO_SOURCE_AVCODEC_H
    2323
    2424/** \file
     
    5757
    5858*/
    59 aubio_source_avcodec_t * new_aubio_source_avcodec(char_t * uri, uint_t samplerate, uint_t hop_size);
     59aubio_source_avcodec_t * new_aubio_source_avcodec(const char_t * uri, uint_t samplerate, uint_t hop_size);
    6060
    6161/**
     
    9595
    9696*/
    97 uint_t aubio_source_avcodec_get_samplerate(aubio_source_avcodec_t * s);
     97uint_t aubio_source_avcodec_get_samplerate(const aubio_source_avcodec_t * s);
    9898
    9999/**
     
    105105
    106106*/
    107 uint_t aubio_source_avcodec_get_channels (aubio_source_avcodec_t * s);
     107uint_t aubio_source_avcodec_get_channels (const aubio_source_avcodec_t * s);
    108108
    109109/**
     
    118118*/
    119119uint_t aubio_source_avcodec_seek (aubio_source_avcodec_t *s, uint_t pos);
     120
     121/**
     122
     123  get the duration of source object, in frames
     124
     125  \param s source object, created with ::new_aubio_source_avcodec
     126  \return number of frames in file
     127
     128*/
     129uint_t aubio_source_avcodec_get_duration (aubio_source_avcodec_t * s);
    120130
    121131/**
     
    143153#endif
    144154
    145 #endif /* _AUBIO_SOURCE_AVCODEC_H */
     155#endif /* AUBIO_SOURCE_AVCODEC_H */
  • src/io/source_sndfile.c

    r60fc05b rf264b17  
    3636#define MAX_SIZE 4096
    3737#define MAX_SAMPLES MAX_CHANNELS * MAX_SIZE
     38
     39#if !HAVE_AUBIO_DOUBLE
     40#define aubio_sf_read_smpl sf_read_float
     41#else /* HAVE_AUBIO_DOUBLE */
     42#define aubio_sf_read_smpl sf_read_double
     43#endif /* HAVE_AUBIO_DOUBLE */
    3844
    3945struct _aubio_source_sndfile_t {
     
    4854  int input_channels;
    4955  int input_format;
     56  int duration;
    5057
    5158  // resampling stuff
     
    5966  // some temporary memory for sndfile to write at
    6067  uint_t scratch_size;
    61   float *scratch_data;
     68  smpl_t *scratch_data;
    6269};
    6370
    64 aubio_source_sndfile_t * new_aubio_source_sndfile(char_t * path, uint_t samplerate, uint_t hop_size) {
     71aubio_source_sndfile_t * new_aubio_source_sndfile(const char_t * path, uint_t samplerate, uint_t hop_size) {
    6572  aubio_source_sndfile_t * s = AUBIO_NEW(aubio_source_sndfile_t);
    6673  SF_INFO sfinfo;
     
    8188  s->hop_size = hop_size;
    8289  s->channels = 1;
    83   s->path = path;
     90
     91  if (s->path) AUBIO_FREE(s->path);
     92  s->path = AUBIO_ARRAY(char_t, strnlen(path, PATH_MAX) + 1);
     93  strncpy(s->path, path, strnlen(path, PATH_MAX) + 1);
    8494
    8595  // try opening the file, getting the info in sfinfo
     
    97107  s->input_channels   = sfinfo.channels;
    98108  s->input_format     = sfinfo.format;
     109  s->duration         = sfinfo.frames;
    99110
    100111  if (samplerate == 0) {
    101     samplerate = s->input_samplerate;
     112    s->samplerate = s->input_samplerate;
    102113    //AUBIO_DBG("sampling rate set to 0, automagically adjusting to %d\n", samplerate);
    103   }
    104   s->samplerate = samplerate;
     114  } else {
     115    s->samplerate = samplerate;
     116  }
    105117  /* compute input block size required before resampling */
    106   s->ratio = s->samplerate/(float)s->input_samplerate;
     118  s->ratio = s->samplerate/(smpl_t)s->input_samplerate;
    107119  s->input_hop_size = (uint_t)FLOOR(s->hop_size / s->ratio + .5);
    108120
     
    129141          s->input_samplerate, s->samplerate);
    130142    }
     143    s->duration = (uint_t)FLOOR(s->duration * s->ratio);
    131144  }
    132145#else
     
    139152  /* allocate data for de/interleaving reallocated when needed. */
    140153  s->scratch_size = s->input_hop_size * s->input_channels;
    141   s->scratch_data = AUBIO_ARRAY(float,s->scratch_size);
     154  s->scratch_data = AUBIO_ARRAY(smpl_t, s->scratch_size);
    142155
    143156  return s;
     
    153166  uint_t i,j, input_channels = s->input_channels;
    154167  /* read from file into scratch_data */
    155   sf_count_t read_samples = sf_read_float (s->handle, s->scratch_data, s->scratch_size);
     168  sf_count_t read_samples = aubio_sf_read_smpl (s->handle, s->scratch_data, s->scratch_size);
    156169
    157170  /* where to store de-interleaved data */
     
    194207  uint_t i,j, input_channels = s->input_channels;
    195208  /* do actual reading */
    196   sf_count_t read_samples = sf_read_float (s->handle, s->scratch_data, s->scratch_size);
     209  sf_count_t read_samples = aubio_sf_read_smpl (s->handle, s->scratch_data, s->scratch_size);
    197210
    198211  /* where to store de-interleaved data */
     
    214227    for (j = 0; j < read_samples / input_channels; j++) {
    215228      for (i = 0; i < read_data->height; i++) {
    216         ptr_data[i][j] = (smpl_t)s->scratch_data[j * input_channels + i];
     229        ptr_data[i][j] = s->scratch_data[j * input_channels + i];
    217230      }
    218231    }
     
    222235    for (j = 0; j < read_samples / input_channels; j++) {
    223236      for (i = 0; i < input_channels; i++) {
    224         ptr_data[i][j] = (smpl_t)s->scratch_data[j * input_channels + i];
     237        ptr_data[i][j] = s->scratch_data[j * input_channels + i];
    225238      }
    226239    }
     
    232245    for (j = 0; j < read_samples / input_channels; j++) {
    233246      for (i = input_channels; i < read_data->height; i++) {
    234         ptr_data[i][j] = (smpl_t)s->scratch_data[j * input_channels + (input_channels - 1)];
     247        ptr_data[i][j] = s->scratch_data[j * input_channels + (input_channels - 1)];
    235248      }
    236249    }
     
    261274uint_t aubio_source_sndfile_get_channels(aubio_source_sndfile_t * s) {
    262275  return s->input_channels;
     276}
     277
     278uint_t aubio_source_sndfile_get_duration (const aubio_source_sndfile_t * s) {
     279  if (s && s->duration) {
     280    return s->duration;
     281  }
     282  return 0;
    263283}
    264284
     
    300320  }
    301321#endif /* HAVE_SAMPLERATE */
     322  if (s->path) AUBIO_FREE(s->path);
    302323  AUBIO_FREE(s->scratch_data);
    303324  AUBIO_FREE(s);
  • src/io/source_sndfile.h

    r60fc05b rf264b17  
    1919*/
    2020
    21 #ifndef _AUBIO_SOURCE_SNDFILE_H
    22 #define _AUBIO_SOURCE_SNDFILE_H
     21#ifndef AUBIO_SOURCE_SNDFILE_H
     22#define AUBIO_SOURCE_SNDFILE_H
    2323
    2424/** \file
     
    5757
    5858*/
    59 aubio_source_sndfile_t * new_aubio_source_sndfile(char_t * uri, uint_t samplerate, uint_t hop_size);
     59aubio_source_sndfile_t * new_aubio_source_sndfile(const char_t * uri, uint_t samplerate, uint_t hop_size);
    6060
    6161/**
     
    121121/**
    122122
     123  get the duration of source object, in frames
     124
     125  \param s source object, created with ::new_aubio_source_sndfile
     126  \return number of frames in file
     127
     128*/
     129uint_t aubio_source_sndfile_get_duration (const aubio_source_sndfile_t *s);
     130
     131/**
     132
    123133  close source
    124134
     
    143153#endif
    144154
    145 #endif /* _AUBIO_SOURCE_SNDFILE_H */
     155#endif /* AUBIO_SOURCE_SNDFILE_H */
  • src/io/source_wavread.c

    r60fc05b rf264b17  
    5353  uint_t eof;
    5454
     55  uint_t duration;
     56
    5557  size_t seek_start;
    5658
     
    6870}
    6971
    70 aubio_source_wavread_t * new_aubio_source_wavread(char_t * path, uint_t samplerate, uint_t hop_size) {
     72aubio_source_wavread_t * new_aubio_source_wavread(const char_t * path, uint_t samplerate, uint_t hop_size) {
    7173  aubio_source_wavread_t * s = AUBIO_NEW(aubio_source_wavread_t);
    7274  size_t bytes_read = 0, bytes_expected = 44;
    7375  unsigned char buf[5];
    74   unsigned int format, channels, sr, byterate, blockalign, bitspersample;//, data_size;
     76  unsigned int format, channels, sr, byterate, blockalign, duration, bitspersample;//, data_size;
    7577
    7678  if (path == NULL) {
     
    8789  }
    8890
    89   s->path = path;
     91  if (s->path) AUBIO_FREE(s->path);
     92  s->path = AUBIO_ARRAY(char_t, strnlen(path, PATH_MAX) + 1);
     93  strncpy(s->path, path, strnlen(path, PATH_MAX) + 1);
     94
    9095  s->samplerate = samplerate;
    9196  s->hop_size = hop_size;
     
    213218  // Subchunk2Size
    214219  bytes_read += fread(buf, 1, 4, s->fid);
     220  duration = read_little_endian(buf, 4) / blockalign;
     221
    215222  //data_size = buf[0] + (buf[1] << 8) + (buf[2] << 16) + (buf[3] << 24);
    216223  //AUBIO_MSG("found %d frames in %s\n", 8 * data_size / bitspersample / channels, s->path);
     
    232239  s->blockalign= blockalign;
    233240  s->bitspersample = bitspersample;
     241
     242  s->duration = duration;
    234243
    235244  s->short_output = (unsigned char *)calloc(s->blockalign, AUBIO_WAVREAD_BUFSIZE);
     
    372381}
    373382
     383uint_t aubio_source_wavread_get_duration (const aubio_source_wavread_t * s) {
     384  if (s && s->duration) {
     385    return s->duration;
     386  }
     387  return 0;
     388}
     389
    374390uint_t aubio_source_wavread_close (aubio_source_wavread_t * s) {
    375391  if (!s->fid) {
     
    389405  if (s->short_output) AUBIO_FREE(s->short_output);
    390406  if (s->output) del_fmat(s->output);
     407  if (s->path) AUBIO_FREE(s->path);
    391408  AUBIO_FREE(s);
    392409}
  • src/io/source_wavread.h

    r60fc05b rf264b17  
    1919*/
    2020
    21 #ifndef _AUBIO_SOURCE_WAVREAD_H
    22 #define _AUBIO_SOURCE_WAVREAD_H
     21#ifndef AUBIO_SOURCE_WAVREAD_H
     22#define AUBIO_SOURCE_WAVREAD_H
    2323
    2424/** \file
     
    6262
    6363*/
    64 aubio_source_wavread_t * new_aubio_source_wavread(char_t * uri, uint_t samplerate, uint_t hop_size);
     64aubio_source_wavread_t * new_aubio_source_wavread(const char_t * uri, uint_t samplerate, uint_t hop_size);
    6565
    6666/**
     
    126126/**
    127127
     128  get the duration of source object, in frames
     129
     130  \param s source object, created with ::new_aubio_source_sndfile
     131  \return number of frames in file
     132
     133*/
     134uint_t aubio_source_wavread_get_duration (const aubio_source_wavread_t *s);
     135
     136/**
     137
    128138  close source
    129139
     
    148158#endif
    149159
    150 #endif /* _AUBIO_SOURCE_WAVREAD_H */
     160#endif /* AUBIO_SOURCE_WAVREAD_H */
  • src/io/utils_apple_audio.c

    r60fc05b rf264b17  
    3434}
    3535
    36 CFURLRef getURLFromPath(const char * path) {
     36CFURLRef createURLFromPath(const char * path) {
    3737  CFStringRef cfTotalPath = CFStringCreateWithCString (kCFAllocatorDefault,
    3838      path, kCFStringEncodingUTF8);
    3939
    40   return CFURLCreateWithFileSystemPath(kCFAllocatorDefault, cfTotalPath,
     40  CFURLRef url = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, cfTotalPath,
    4141      kCFURLPOSIXPathStyle, false);
     42  CFRelease(cfTotalPath);
     43  return url;
    4244}
    4345
  • src/lvec.c

    r60fc05b rf264b17  
    2222#include "lvec.h"
    2323
    24 lvec_t * new_lvec( uint_t length) {
     24lvec_t * new_lvec(uint_t length) {
    2525  lvec_t * s;
    2626  if ((sint_t)length <= 0) {
     
    4646}
    4747
    48 lsmp_t * lvec_get_data(lvec_t *s) {
     48lsmp_t * lvec_get_data(const lvec_t *s) {
    4949  return s->data;
    5050}
     
    5252/* helper functions */
    5353
    54 void lvec_print(lvec_t *s) {
     54void lvec_print(const lvec_t *s) {
    5555  uint_t j;
    5656  for (j=0; j< s->length; j++) {
  • src/lvec.h

    r60fc05b rf264b17  
    1919*/
    2020
    21 #ifndef _AUBIO__LVEC_H
    22 #define _AUBIO__LVEC_H
     21#ifndef AUBIO_LVEC_H
     22#define AUBIO_LVEC_H
    2323
    2424#ifdef __cplusplus
     
    8181
    8282*/
    83 lsmp_t * lvec_get_data(lvec_t *s);
     83lsmp_t * lvec_get_data(const lvec_t *s);
    8484
    8585/** print out lvec data
     
    8888
    8989*/
    90 void lvec_print(lvec_t *s);
     90void lvec_print(const lvec_t *s);
    9191
    9292/** set all elements to a given value
     
    116116#endif
    117117
    118 #endif /* _AUBIO__LVEC_H */
     118#endif /* AUBIO_LVEC_H */
  • src/mathutils.c

    r60fc05b rf264b17  
    2626#include "musicutils.h"
    2727#include "config.h"
    28 
    29 #ifdef HAVE_ACCELERATE
    30 #include <Accelerate/Accelerate.h>
    31 #endif
    3228
    3329/** Window types */
     
    167163  return tmp / (smpl_t) (s->length);
    168164#else
    169 #if !HAVE_AUBIO_DOUBLE
    170   vDSP_meanv(s->data, 1, &tmp, s->length);
    171 #else /* HAVE_AUBIO_DOUBLE */
    172   vDSP_meanvD(s->data, 1, &tmp, s->length);
    173 #endif /* HAVE_AUBIO_DOUBLE */
     165  aubio_vDSP_meanv(s->data, 1, &tmp, s->length);
    174166  return tmp;
    175167#endif /* HAVE_ACCELERATE */
     
    186178  }
    187179#else
    188 #if !HAVE_AUBIO_DOUBLE
    189   vDSP_sve(s->data, 1, &tmp, s->length);
    190 #else /* HAVE_AUBIO_DOUBLE */
    191   vDSP_sveD(s->data, 1, &tmp, s->length);
    192 #endif /* HAVE_AUBIO_DOUBLE */
     180  aubio_vDSP_sve(s->data, 1, &tmp, s->length);
    193181#endif /* HAVE_ACCELERATE */
    194182  return tmp;
     
    206194#else
    207195  smpl_t tmp = 0.;
    208 #if !HAVE_AUBIO_DOUBLE
    209   vDSP_maxv(s->data, 1, &tmp, s->length);
    210 #else
    211   vDSP_maxvD(s->data, 1, &tmp, s->length);
    212 #endif
     196  aubio_vDSP_maxv(s->data, 1, &tmp, s->length);
    213197#endif
    214198  return tmp;
     
    226210#else
    227211  smpl_t tmp = 0.;
    228 #if !HAVE_AUBIO_DOUBLE
    229   vDSP_minv(s->data, 1, &tmp, s->length);
    230 #else
    231   vDSP_minvD(s->data, 1, &tmp, s->length);
    232 #endif
     212  aubio_vDSP_minv(s->data, 1, &tmp, s->length);
    233213#endif
    234214  return tmp;
     
    248228  smpl_t tmp = 0.;
    249229  uint_t pos = 0.;
    250 #if !HAVE_AUBIO_DOUBLE
    251   vDSP_minvi(s->data, 1, &tmp, (vDSP_Length *)&pos, s->length);
    252 #else
    253   vDSP_minviD(s->data, 1, &tmp, (vDSP_Length *)&pos, s->length);
    254 #endif
     230  aubio_vDSP_minvi(s->data, 1, &tmp, (vDSP_Length *)&pos, s->length);
    255231#endif
    256232  return pos;
     
    270246  smpl_t tmp = 0.;
    271247  uint_t pos = 0.;
    272 #if !HAVE_AUBIO_DOUBLE
    273   vDSP_maxvi(s->data, 1, &tmp, (vDSP_Length *)&pos, s->length);
    274 #else
    275   vDSP_maxviD(s->data, 1, &tmp, (vDSP_Length *)&pos, s->length);
    276 #endif
     248  aubio_vDSP_maxvi(s->data, 1, &tmp, (vDSP_Length *)&pos, s->length);
    277249#endif
    278250  return pos;
     
    282254fvec_shift (fvec_t * s)
    283255{
    284   uint_t j;
    285   for (j = 0; j < s->length / 2; j++) {
    286     ELEM_SWAP (s->data[j], s->data[j + s->length / 2]);
    287   }
    288 }
    289 
    290 smpl_t
    291 aubio_level_lin (fvec_t * f)
     256  uint_t half = s->length / 2, start = half, j;
     257  // if length is odd, middle element is moved to the end
     258  if (2 * half < s->length) start ++;
     259#ifndef HAVE_ATLAS
     260  for (j = 0; j < half; j++) {
     261    ELEM_SWAP (s->data[j], s->data[j + start]);
     262  }
     263#else
     264  aubio_cblas_swap(half, s->data, 1, s->data + start, 1);
     265#endif
     266  if (start != half) {
     267    for (j = 0; j < half; j++) {
     268      ELEM_SWAP (s->data[j + start - 1], s->data[j + start]);
     269    }
     270  }
     271}
     272
     273void
     274fvec_ishift (fvec_t * s)
     275{
     276  uint_t half = s->length / 2, start = half, j;
     277  // if length is odd, middle element is moved to the beginning
     278  if (2 * half < s->length) start ++;
     279#ifndef HAVE_ATLAS
     280  for (j = 0; j < half; j++) {
     281    ELEM_SWAP (s->data[j], s->data[j + start]);
     282  }
     283#else
     284  aubio_cblas_swap(half, s->data, 1, s->data + start, 1);
     285#endif
     286  if (start != half) {
     287    for (j = 0; j < half; j++) {
     288      ELEM_SWAP (s->data[half], s->data[j]);
     289    }
     290  }
     291}
     292
     293smpl_t
     294aubio_level_lin (const fvec_t * f)
    292295{
    293296  smpl_t energy = 0.;
     297#ifndef HAVE_ATLAS
    294298  uint_t j;
    295299  for (j = 0; j < f->length; j++) {
    296300    energy += SQR (f->data[j]);
    297301  }
     302#else
     303  energy = aubio_cblas_dot(f->length, f->data, 1, f->data, 1);
     304#endif
    298305  return energy / f->length;
    299306}
     
    434441}
    435442
    436 smpl_t fvec_quadratic_peak_pos (fvec_t * x, uint_t pos) {
     443smpl_t fvec_quadratic_peak_pos (const fvec_t * x, uint_t pos) {
    437444  smpl_t s0, s1, s2; uint_t x0, x2;
     445  smpl_t half = .5, two = 2.;
    438446  if (pos == 0 || pos == x->length - 1) return pos;
    439447  x0 = (pos < 1) ? pos : pos - 1;
     
    444452  s1 = x->data[pos];
    445453  s2 = x->data[x2];
    446   return pos + 0.5 * (s0 - s2 ) / (s0 - 2.* s1 + s2);
     454  return pos + half * (s0 - s2 ) / (s0 - two * s1 + s2);
    447455}
    448456
     
    458466}
    459467
    460 uint_t fvec_peakpick(fvec_t * onset, uint_t pos) {
     468uint_t fvec_peakpick(const fvec_t * onset, uint_t pos) {
    461469  uint_t tmp=0;
    462470  tmp = (onset->data[pos] > onset->data[pos-1]
     
    545553
    546554smpl_t
    547 aubio_db_spl (fvec_t * o)
     555aubio_db_spl (const fvec_t * o)
    548556{
    549557  return 10. * LOG10 (aubio_level_lin (o));
     
    551559
    552560uint_t
    553 aubio_silence_detection (fvec_t * o, smpl_t threshold)
     561aubio_silence_detection (const fvec_t * o, smpl_t threshold)
    554562{
    555563  return (aubio_db_spl (o) < threshold);
     
    591599
    592600void
    593 aubio_autocorr (fvec_t * input, fvec_t * output)
     601aubio_autocorr (const fvec_t * input, fvec_t * output)
    594602{
    595603  uint_t i, j, length = input->length;
  • src/mathutils.h

    r60fc05b rf264b17  
    2828 */
    2929
    30 #ifndef _AUBIO_MATHUTILS_H
    31 #define _AUBIO_MATHUTILS_H
     30#ifndef AUBIO_MATHUTILS_H
     31#define AUBIO_MATHUTILS_H
    3232
    3333#include "fvec.h"
     
    9999*/
    100100void fvec_shift (fvec_t * v);
     101
     102/** swap the left and right halves of a vector
     103
     104  This function swaps the left part of the signal with the right part of the
     105signal. Therefore
     106
     107  \f$ a[0], a[1], ..., a[\frac{N}{2}], a[\frac{N}{2}+1], ..., a[N-1], a[N] \f$
     108
     109  becomes
     110
     111  \f$ a[\frac{N}{2}+1], ..., a[N-1], a[N], a[0], a[1], ..., a[\frac{N}{2}] \f$
     112
     113  This operation, known as 'ifftshift' in the Matlab Signal Processing Toolbox,
     114can be used after computing the inverse FFT to simplify the phase relationship
     115of the resulting spectrum. See Amalia de Götzen's paper referred to above.
     116
     117*/
     118void fvec_ishift (fvec_t * v);
    101119
    102120/** compute the sum of all elements of a vector
     
    233251
    234252*/
    235 smpl_t fvec_quadratic_peak_pos (fvec_t * x, uint_t p);
     253smpl_t fvec_quadratic_peak_pos (const fvec_t * x, uint_t p);
    236254
    237255/** finds magnitude of peak by quadratic interpolation
     
    276294
    277295*/
    278 uint_t fvec_peakpick (fvec_t * v, uint_t p);
     296uint_t fvec_peakpick (const fvec_t * v, uint_t p);
    279297
    280298/** return 1 if a is a power of 2, 0 otherwise */
     
    290308
    291309*/
    292 void aubio_autocorr (fvec_t * input, fvec_t * output);
     310void aubio_autocorr (const fvec_t * input, fvec_t * output);
    293311
    294312#ifdef __cplusplus
     
    296314#endif
    297315
    298 #endif /* _AUBIO_MATHUTILS_H */
     316#endif /* AUBIO_MATHUTILS_H */
  • src/musicutils.h

    r60fc05b rf264b17  
    2323 */
    2424
    25 #ifndef _AUBIO__MUSICUTILS_H
    26 #define _AUBIO__MUSICUTILS_H
     25#ifndef AUBIO_MUSICUTILS_H
     26#define AUBIO_MUSICUTILS_H
    2727
    2828#ifdef __cplusplus
     
    5757the International Conference on Digital Audio Effects (DAFx-00), pages 37–44,
    5858Uni- versity of Verona, Italy, 2000.
    59   (<a href="http://profs.sci.univr.it/%7Edafx/Final-Papers/ps/Bernardini.ps.gz">
    60   ps.gz</a>)
     59  (<a href="http://www.cs.princeton.edu/courses/archive/spr09/cos325/Bernardini.pdf">
     60  pdf</a>)
    6161
    6262 */
     
    122122
    123123*/
    124 smpl_t aubio_level_lin (fvec_t * v);
     124smpl_t aubio_level_lin (const fvec_t * v);
    125125
    126126/** compute sound pressure level (SPL) in dB
     
    135135
    136136*/
    137 smpl_t aubio_db_spl (fvec_t * v);
     137smpl_t aubio_db_spl (const fvec_t * v);
    138138
    139139/** check if buffer level in dB SPL is under a given threshold
     
    145145
    146146*/
    147 uint_t aubio_silence_detection (fvec_t * v, smpl_t threshold);
     147uint_t aubio_silence_detection (const fvec_t * v, smpl_t threshold);
    148148
    149149/** get buffer level if level >= threshold, 1. otherwise
     
    161161#endif
    162162
    163 #endif /* _AUBIO__MUSICUTILS_H */
     163#endif /* AUBIO_MUSICUTILS_H */
  • src/onset/onset.c

    r60fc05b rf264b17  
    4646
    4747/* execute onset detection function on iput buffer */
    48 void aubio_onset_do (aubio_onset_t *o, fvec_t * input, fvec_t * onset)
     48void aubio_onset_do (aubio_onset_t *o, const fvec_t * input, fvec_t * onset)
    4949{
    5050  smpl_t isonset = 0;
     
    8585}
    8686
    87 uint_t aubio_onset_get_last (aubio_onset_t *o)
     87uint_t aubio_onset_get_last (const aubio_onset_t *o)
    8888{
    8989  return o->last_onset - o->delay;
    9090}
    9191
    92 smpl_t aubio_onset_get_last_s (aubio_onset_t *o)
     92smpl_t aubio_onset_get_last_s (const aubio_onset_t *o)
    9393{
    9494  return aubio_onset_get_last (o) / (smpl_t) (o->samplerate);
    9595}
    9696
    97 smpl_t aubio_onset_get_last_ms (aubio_onset_t *o)
     97smpl_t aubio_onset_get_last_ms (const aubio_onset_t *o)
    9898{
    9999  return aubio_onset_get_last_s (o) * 1000.;
     
    105105}
    106106
    107 smpl_t aubio_onset_get_silence(aubio_onset_t * o) {
     107smpl_t aubio_onset_get_silence(const aubio_onset_t * o) {
    108108  return o->silence;
    109109}
     
    114114}
    115115
    116 smpl_t aubio_onset_get_threshold(aubio_onset_t * o) {
     116smpl_t aubio_onset_get_threshold(const aubio_onset_t * o) {
    117117  return aubio_peakpicker_get_threshold(o->pp);
    118118}
     
    123123}
    124124
    125 uint_t aubio_onset_get_minioi(aubio_onset_t * o) {
     125uint_t aubio_onset_get_minioi(const aubio_onset_t * o) {
    126126  return o->minioi;
    127127}
    128128
    129129uint_t aubio_onset_set_minioi_s(aubio_onset_t * o, smpl_t minioi) {
    130   return aubio_onset_set_minioi (o, minioi * o->samplerate);
    131 }
    132 
    133 smpl_t aubio_onset_get_minioi_s(aubio_onset_t * o) {
     130  return aubio_onset_set_minioi (o, (uint_t)ROUND(minioi * o->samplerate));
     131}
     132
     133smpl_t aubio_onset_get_minioi_s(const aubio_onset_t * o) {
    134134  return aubio_onset_get_minioi (o) / (smpl_t) o->samplerate;
    135135}
     
    139139}
    140140
    141 smpl_t aubio_onset_get_minioi_ms(aubio_onset_t * o) {
     141smpl_t aubio_onset_get_minioi_ms(const aubio_onset_t * o) {
    142142  return aubio_onset_get_minioi_s (o) * 1000.;
    143143}
     
    148148}
    149149
    150 uint_t aubio_onset_get_delay(aubio_onset_t * o) {
     150uint_t aubio_onset_get_delay(const aubio_onset_t * o) {
    151151  return o->delay;
    152152}
     
    156156}
    157157
    158 smpl_t aubio_onset_get_delay_s(aubio_onset_t * o) {
     158smpl_t aubio_onset_get_delay_s(const aubio_onset_t * o) {
    159159  return aubio_onset_get_delay (o) / (smpl_t) o->samplerate;
    160160}
     
    164164}
    165165
    166 smpl_t aubio_onset_get_delay_ms(aubio_onset_t * o) {
     166smpl_t aubio_onset_get_delay_ms(const aubio_onset_t * o) {
    167167  return aubio_onset_get_delay_s (o) * 1000.;
    168168}
    169169
    170 smpl_t aubio_onset_get_descriptor(aubio_onset_t * o) {
     170smpl_t aubio_onset_get_descriptor(const aubio_onset_t * o) {
    171171  return o->desc->data[0];
    172172}
    173173
    174 smpl_t aubio_onset_get_thresholded_descriptor(aubio_onset_t * o) {
     174smpl_t aubio_onset_get_thresholded_descriptor(const aubio_onset_t * o) {
    175175  fvec_t * thresholded = aubio_peakpicker_get_thresholded_input(o->pp);
    176176  return thresholded->data[0];
     
    178178
    179179/* Allocate memory for an onset detection */
    180 aubio_onset_t * new_aubio_onset (char_t * onset_mode,
     180aubio_onset_t * new_aubio_onset (const char_t * onset_mode,
    181181    uint_t buf_size, uint_t hop_size, uint_t samplerate)
    182182{
     
    187187    AUBIO_ERR("onset: got hop_size %d, but can not be < 1\n", hop_size);
    188188    goto beach;
    189   } else if ((sint_t)buf_size < 1) {
    190     AUBIO_ERR("onset: got buffer_size %d, but can not be < 1\n", buf_size);
     189  } else if ((sint_t)buf_size < 2) {
     190    AUBIO_ERR("onset: got buffer_size %d, but can not be < 2\n", buf_size);
    191191    goto beach;
    192192  } else if (buf_size < hop_size) {
  • src/onset/onset.h

    r60fc05b rf264b17  
    4040
    4141
    42 #ifndef _AUBIO_ONSET_H
    43 #define _AUBIO_ONSET_H
     42#ifndef AUBIO_ONSET_H
     43#define AUBIO_ONSET_H
    4444
    4545#ifdef __cplusplus
     
    6060
    6161*/
    62 aubio_onset_t * new_aubio_onset (char_t * method,
     62aubio_onset_t * new_aubio_onset (const char_t * method,
    6363    uint_t buf_size, uint_t hop_size, uint_t samplerate);
    6464
     
    8989
    9090*/
    91 void aubio_onset_do (aubio_onset_t *o, fvec_t * input, fvec_t * onset);
     91void aubio_onset_do (aubio_onset_t *o, const fvec_t * input, fvec_t * onset);
    9292
    9393/** get the time of the latest onset detected, in samples
     
    9898
    9999*/
    100 uint_t aubio_onset_get_last (aubio_onset_t *o);
     100uint_t aubio_onset_get_last (const aubio_onset_t *o);
    101101
    102102/** get the time of the latest onset detected, in seconds
     
    107107
    108108*/
    109 smpl_t aubio_onset_get_last_s (aubio_onset_t *o);
     109smpl_t aubio_onset_get_last_s (const aubio_onset_t *o);
    110110
    111111/** get the time of the latest onset detected, in milliseconds
     
    116116
    117117*/
    118 smpl_t aubio_onset_get_last_ms (aubio_onset_t *o);
     118smpl_t aubio_onset_get_last_ms (const aubio_onset_t *o);
    119119
    120120/** set onset detection silence threshold
     
    133133
    134134*/
    135 smpl_t aubio_onset_get_silence(aubio_onset_t * o);
     135smpl_t aubio_onset_get_silence(const aubio_onset_t * o);
    136136
    137137/** get onset detection function
     
    141141
    142142*/
    143 smpl_t aubio_onset_get_descriptor ( aubio_onset_t *o);
     143smpl_t aubio_onset_get_descriptor (const aubio_onset_t *o);
    144144
    145145/** get thresholded onset detection function
     
    149149
    150150*/
    151 smpl_t aubio_onset_get_thresholded_descriptor ( aubio_onset_t *o);
     151smpl_t aubio_onset_get_thresholded_descriptor (const aubio_onset_t *o);
    152152
    153153/** set onset detection peak picking threshold
     
    220220
    221221*/
    222 uint_t aubio_onset_get_minioi(aubio_onset_t * o);
     222uint_t aubio_onset_get_minioi(const aubio_onset_t * o);
    223223
    224224/** get minimum inter onset interval in seconds
     
    229229
    230230*/
    231 smpl_t aubio_onset_get_minioi_s(aubio_onset_t * o);
     231smpl_t aubio_onset_get_minioi_s(const aubio_onset_t * o);
    232232
    233233/** get minimum inter onset interval in milliseconds
     
    238238
    239239*/
    240 smpl_t aubio_onset_get_minioi_ms(aubio_onset_t * o);
     240smpl_t aubio_onset_get_minioi_ms(const aubio_onset_t * o);
    241241
    242242/** get delay in samples
     
    247247
    248248*/
    249 uint_t aubio_onset_get_delay(aubio_onset_t * o);
     249uint_t aubio_onset_get_delay(const aubio_onset_t * o);
    250250
    251251/** get delay in seconds
     
    256256
    257257*/
    258 smpl_t aubio_onset_get_delay_s(aubio_onset_t * o);
     258smpl_t aubio_onset_get_delay_s(const aubio_onset_t * o);
    259259
    260260/** get delay in milliseconds
     
    265265
    266266*/
    267 smpl_t aubio_onset_get_delay_ms(aubio_onset_t * o);
     267smpl_t aubio_onset_get_delay_ms(const aubio_onset_t * o);
    268268
    269269/** get onset peak picking threshold
     
    273273
    274274*/
    275 smpl_t aubio_onset_get_threshold(aubio_onset_t * o);
     275smpl_t aubio_onset_get_threshold(const aubio_onset_t * o);
    276276
    277277/** delete onset detection object
     
    286286#endif
    287287
    288 #endif /* _AUBIO_ONSET_H */
     288#endif /* AUBIO_ONSET_H */
  • src/onset/peakpicker.h

    r60fc05b rf264b17  
    2727*/
    2828
    29 #ifndef _AUBIO_PEAKPICK_H
    30 #define _AUBIO_PEAKPICK_H
     29#ifndef AUBIO_PEAKPICK_H
     30#define AUBIO_PEAKPICK_H
    3131
    3232#ifdef __cplusplus
     
    5555#endif
    5656
    57 #endif /* _AUBIO_PEAKPICK_H */
     57#endif /* AUBIO_PEAKPICK_H */
  • src/pitch/pitch.c

    r60fc05b rf264b17  
    6262
    6363/** callback to get pitch candidate, defined below */
    64 typedef void (*aubio_pitch_detect_t) (aubio_pitch_t * p, fvec_t * ibuf, fvec_t * obuf);
     64typedef void (*aubio_pitch_detect_t) (aubio_pitch_t * p, const fvec_t * ibuf, fvec_t * obuf);
    6565
    6666/** callback to convert pitch from one unit to another, defined below */
     
    7979  void *p_object;                 /**< pointer to pitch object */
    8080  aubio_filter_t *filter;         /**< filter */
     81  fvec_t *filtered;               /**< filtered input */
    8182  aubio_pvoc_t *pv;               /**< phase vocoder for mcomb */
    8283  cvec_t *fftgrain;               /**< spectral frame for mcomb */
     
    8990
    9091/* callback functions for pitch detection */
    91 static void aubio_pitch_do_mcomb (aubio_pitch_t * p, fvec_t * ibuf, fvec_t * obuf);
    92 static void aubio_pitch_do_yin (aubio_pitch_t * p, fvec_t * ibuf, fvec_t * obuf);
    93 static void aubio_pitch_do_schmitt (aubio_pitch_t * p, fvec_t * ibuf, fvec_t * obuf);
    94 static void aubio_pitch_do_fcomb (aubio_pitch_t * p, fvec_t * ibuf, fvec_t * obuf);
    95 static void aubio_pitch_do_yinfft (aubio_pitch_t * p, fvec_t * ibuf, fvec_t * obuf);
    96 static void aubio_pitch_do_specacf (aubio_pitch_t * p, fvec_t * ibuf, fvec_t * obuf);
     92static void aubio_pitch_do_mcomb (aubio_pitch_t * p, const fvec_t * ibuf, fvec_t * obuf);
     93static void aubio_pitch_do_yin (aubio_pitch_t * p, const fvec_t * ibuf, fvec_t * obuf);
     94static void aubio_pitch_do_schmitt (aubio_pitch_t * p, const fvec_t * ibuf, fvec_t * obuf);
     95static void aubio_pitch_do_fcomb (aubio_pitch_t * p, const fvec_t * ibuf, fvec_t * obuf);
     96static void aubio_pitch_do_yinfft (aubio_pitch_t * p, const fvec_t * ibuf, fvec_t * obuf);
     97static void aubio_pitch_do_specacf (aubio_pitch_t * p, const fvec_t * ibuf, fvec_t * obuf);
    9798
    9899/* conversion functions for frequency conversions */
     
    102103
    103104/* adapter to stack ibuf new samples at the end of buf, and trim `buf` to `bufsize` */
    104 void aubio_pitch_slideblock (aubio_pitch_t * p, fvec_t * ibuf);
     105void aubio_pitch_slideblock (aubio_pitch_t * p, const fvec_t * ibuf);
    105106
    106107
    107108aubio_pitch_t *
    108 new_aubio_pitch (char_t * pitch_mode,
     109new_aubio_pitch (const char_t * pitch_mode,
    109110    uint_t bufsize, uint_t hopsize, uint_t samplerate)
    110111{
     
    133134  // check parameters are valid
    134135  if ((sint_t)hopsize < 1) {
    135     AUBIO_ERR("onset: got hopsize %d, but can not be < 1\n", hopsize);
     136    AUBIO_ERR("pitch: got hopsize %d, but can not be < 1\n", hopsize);
    136137    goto beach;
    137138  } else if ((sint_t)bufsize < 1) {
    138     AUBIO_ERR("onset: got buffer_size %d, but can not be < 1\n", bufsize);
     139    AUBIO_ERR("pitch: got buffer_size %d, but can not be < 1\n", bufsize);
    139140    goto beach;
    140141  } else if (bufsize < hopsize) {
    141     AUBIO_ERR("onset: hop size (%d) is larger than win size (%d)\n", bufsize, hopsize);
     142    AUBIO_ERR("pitch: hop size (%d) is larger than win size (%d)\n", bufsize, hopsize);
    142143    goto beach;
    143144  } else if ((sint_t)samplerate < 1) {
    144     AUBIO_ERR("onset: samplerate (%d) can not be < 1\n", samplerate);
     145    AUBIO_ERR("pitch: samplerate (%d) can not be < 1\n", samplerate);
    145146    goto beach;
    146147  }
     
    161162      break;
    162163    case aubio_pitcht_mcomb:
     164      p->filtered = new_fvec (hopsize);
    163165      p->pv = new_aubio_pvoc (bufsize, hopsize);
    164166      p->fftgrain = new_cvec (bufsize);
     
    210212      break;
    211213    case aubio_pitcht_mcomb:
     214      del_fvec (p->filtered);
    212215      del_aubio_pvoc (p->pv);
    213216      del_cvec (p->fftgrain);
     
    238241
    239242void
    240 aubio_pitch_slideblock (aubio_pitch_t * p, fvec_t * ibuf)
    241 {
    242   uint_t j = 0, overlap_size = 0;
    243   overlap_size = p->buf->length - ibuf->length;
     243aubio_pitch_slideblock (aubio_pitch_t * p, const fvec_t * ibuf)
     244{
     245  uint_t overlap_size = p->buf->length - ibuf->length;
     246#if 1 //!HAVE_MEMCPY_HACKS
     247  uint_t j;
    244248  for (j = 0; j < overlap_size; j++) {
    245249    p->buf->data[j] = p->buf->data[j + ibuf->length];
     
    248252    p->buf->data[j + overlap_size] = ibuf->data[j];
    249253  }
     254#else
     255  smpl_t *data = p->buf->data;
     256  smpl_t *newdata = ibuf->data;
     257  memmove(data, data + ibuf->length, overlap_size);
     258  memcpy(data + overlap_size, newdata, ibuf->length);
     259#endif
    250260}
    251261
    252262uint_t
    253 aubio_pitch_set_unit (aubio_pitch_t * p, char_t * pitch_unit)
     263aubio_pitch_set_unit (aubio_pitch_t * p, const char_t * pitch_unit)
    254264{
    255265  uint_t err = AUBIO_OK;
     
    336346/* do method, calling the detection callback, then the conversion callback */
    337347void
    338 aubio_pitch_do (aubio_pitch_t * p, fvec_t * ibuf, fvec_t * obuf)
     348aubio_pitch_do (aubio_pitch_t * p, const fvec_t * ibuf, fvec_t * obuf)
    339349{
    340350  p->detect_cb (p, ibuf, obuf);
     
    347357/* do method for each algorithm */
    348358void
    349 aubio_pitch_do_mcomb (aubio_pitch_t * p, fvec_t * ibuf, fvec_t * obuf)
    350 {
    351   aubio_filter_do (p->filter, ibuf);
     359aubio_pitch_do_mcomb (aubio_pitch_t * p, const fvec_t * ibuf, fvec_t * obuf)
     360{
     361  aubio_filter_do_outplace (p->filter, ibuf, p->filtered);
    352362  aubio_pvoc_do (p->pv, ibuf, p->fftgrain);
    353363  aubio_pitchmcomb_do (p->p_object, p->fftgrain, obuf);
     
    356366
    357367void
    358 aubio_pitch_do_yin (aubio_pitch_t * p, fvec_t * ibuf, fvec_t * obuf)
     368aubio_pitch_do_yin (aubio_pitch_t * p, const fvec_t * ibuf, fvec_t * obuf)
    359369{
    360370  smpl_t pitch = 0.;
     
    372382
    373383void
    374 aubio_pitch_do_yinfft (aubio_pitch_t * p, fvec_t * ibuf, fvec_t * obuf)
     384aubio_pitch_do_yinfft (aubio_pitch_t * p, const fvec_t * ibuf, fvec_t * obuf)
    375385{
    376386  smpl_t pitch = 0.;
     
    387397
    388398void
    389 aubio_pitch_do_specacf (aubio_pitch_t * p, fvec_t * ibuf, fvec_t * out)
     399aubio_pitch_do_specacf (aubio_pitch_t * p, const fvec_t * ibuf, fvec_t * out)
    390400{
    391401  smpl_t pitch = 0., period;
     
    403413
    404414void
    405 aubio_pitch_do_fcomb (aubio_pitch_t * p, fvec_t * ibuf, fvec_t * out)
     415aubio_pitch_do_fcomb (aubio_pitch_t * p, const fvec_t * ibuf, fvec_t * out)
    406416{
    407417  aubio_pitch_slideblock (p, ibuf);
     
    411421
    412422void
    413 aubio_pitch_do_schmitt (aubio_pitch_t * p, fvec_t * ibuf, fvec_t * out)
     423aubio_pitch_do_schmitt (aubio_pitch_t * p, const fvec_t * ibuf, fvec_t * out)
    414424{
    415425  smpl_t period, pitch = 0.;
  • src/pitch/pitch.h

    r60fc05b rf264b17  
    1919*/
    2020
    21 #ifndef _AUBIO_PITCH_H
    22 #define _AUBIO_PITCH_H
     21#ifndef AUBIO_PITCH_H
     22#define AUBIO_PITCH_H
    2323
    2424#ifdef __cplusplus
     
    108108
    109109*/
    110 void aubio_pitch_do (aubio_pitch_t * o, fvec_t * in, fvec_t * out);
     110void aubio_pitch_do (aubio_pitch_t * o, const fvec_t * in, fvec_t * out);
    111111
    112112/** change yin or yinfft tolerance threshold
     
    135135
    136136*/
    137 aubio_pitch_t *new_aubio_pitch (char_t * method,
     137aubio_pitch_t *new_aubio_pitch (const char_t * method,
    138138    uint_t buf_size, uint_t hop_size, uint_t samplerate);
    139139
     
    146146
    147147*/
    148 uint_t aubio_pitch_set_unit (aubio_pitch_t * o, char_t * mode);
     148uint_t aubio_pitch_set_unit (aubio_pitch_t * o, const char_t * mode);
    149149
    150150/** set the silence threshold of the pitch detection object
     
    180180#endif
    181181
    182 #endif /* _AUBIO_PITCH_H */
     182#endif /* AUBIO_PITCH_H */
  • src/pitch/pitchfcomb.c

    r60fc05b rf264b17  
    6464/* input must be stepsize long */
    6565void
    66 aubio_pitchfcomb_do (aubio_pitchfcomb_t * p, fvec_t * input, fvec_t * output)
     66aubio_pitchfcomb_do (aubio_pitchfcomb_t * p, const fvec_t * input, fvec_t * output)
    6767{
    6868  uint_t k, l, maxharm = 0;
  • src/pitch/pitchfcomb.h

    r60fc05b rf264b17  
    3535*/
    3636
    37 #ifndef _AUBIO_PITCHFCOMB_H
    38 #define _AUBIO_PITCHFCOMB_H
     37#ifndef AUBIO_PITCHFCOMB_H
     38#define AUBIO_PITCHFCOMB_H
    3939
    4040#ifdef __cplusplus
     
    5252
    5353*/
    54 void aubio_pitchfcomb_do (aubio_pitchfcomb_t * p, fvec_t * input,
     54void aubio_pitchfcomb_do (aubio_pitchfcomb_t * p, const fvec_t * input,
    5555    fvec_t * output);
    5656
     
    7474#endif
    7575
    76 #endif /* _AUBIO_PITCHFCOMB_H */
     76#endif /* AUBIO_PITCHFCOMB_H */
  • src/pitch/pitchmcomb.c

    r60fc05b rf264b17  
    3232    uint_t length);
    3333uint_t aubio_pitchmcomb_quadpick (aubio_spectralpeak_t * spectral_peaks,
    34     fvec_t * X);
    35 void aubio_pitchmcomb_spectral_pp (aubio_pitchmcomb_t * p, fvec_t * oldmag);
    36 void aubio_pitchmcomb_combdet (aubio_pitchmcomb_t * p, fvec_t * newmag);
     34    const fvec_t * X);
     35void aubio_pitchmcomb_spectral_pp (aubio_pitchmcomb_t * p, const fvec_t * oldmag);
     36void aubio_pitchmcomb_combdet (aubio_pitchmcomb_t * p, const fvec_t * newmag);
    3737/* not used but useful : sort by amplitudes (or anything else)
    3838 * sort_pitchpeak(peaks, length);
     
    4343void aubio_pitchmcomb_sort_peak (aubio_spectralpeak_t * peaks, uint_t nbins);
    4444/** select the best candidates */
    45 uint_t aubio_pitch_cands (aubio_pitchmcomb_t * p, cvec_t * fftgrain,
     45uint_t aubio_pitch_cands (aubio_pitchmcomb_t * p, const cvec_t * fftgrain,
    4646    smpl_t * cands);
    4747
     
    102102
    103103void
    104 aubio_pitchmcomb_do (aubio_pitchmcomb_t * p, cvec_t * fftgrain, fvec_t * output)
     104aubio_pitchmcomb_do (aubio_pitchmcomb_t * p, const cvec_t * fftgrain, fvec_t * output)
    105105{
    106106  uint_t j;
     
    135135
    136136uint_t
    137 aubio_pitch_cands (aubio_pitchmcomb_t * p, cvec_t * fftgrain, smpl_t * cands)
     137aubio_pitch_cands (aubio_pitchmcomb_t * p, const cvec_t * fftgrain, smpl_t * cands)
    138138{
    139139  uint_t j;
     
    166166
    167167void
    168 aubio_pitchmcomb_spectral_pp (aubio_pitchmcomb_t * p, fvec_t * newmag)
     168aubio_pitchmcomb_spectral_pp (aubio_pitchmcomb_t * p, const fvec_t * newmag)
    169169{
    170170  fvec_t *mag = (fvec_t *) p->scratch;
     
    198198
    199199void
    200 aubio_pitchmcomb_combdet (aubio_pitchmcomb_t * p, fvec_t * newmag)
     200aubio_pitchmcomb_combdet (aubio_pitchmcomb_t * p, const fvec_t * newmag)
    201201{
    202202  aubio_spectralpeak_t *peaks = (aubio_spectralpeak_t *) p->peaks;
     
    286286 */
    287287uint_t
    288 aubio_pitchmcomb_quadpick (aubio_spectralpeak_t * spectral_peaks, fvec_t * X)
     288aubio_pitchmcomb_quadpick (aubio_spectralpeak_t * spectral_peaks, const fvec_t * X)
    289289{
    290290  uint_t j, ispeak, count = 0;
     
    336336  uint_t run = 0;
    337337  for (cur = 0; cur < nbins; cur++) {
    338     run = cur + 1;
    339     for (run = cur; run < nbins; run++) {
     338    for (run = cur + 1; run < nbins; run++) {
    340339      if (candidates[run]->ene > candidates[cur]->ene)
    341340        CAND_SWAP (candidates[run], candidates[cur]);
     
    352351  uint_t run = 0;
    353352  for (cur = 0; cur < nbins; cur++) {
    354     run = cur + 1;
    355     for (run = cur; run < nbins; run++) {
     353    for (run = cur + 1; run < nbins; run++) {
    356354      if (candidates[run]->ebin < candidates[cur]->ebin)
    357355        CAND_SWAP (candidates[run], candidates[cur]);
     
    367365  uint_t i, j;
    368366  uint_t spec_size;
    369   p->spec_partition = 4;
     367  p->spec_partition = 2;
    370368  p->ncand = 5;
    371369  p->npartials = 5;
     
    379377  p->phasefreq = bufsize / hopsize / TWO_PI;
    380378  p->phasediff = TWO_PI * hopsize / bufsize;
    381   spec_size = bufsize / p->spec_partition;
     379  spec_size = bufsize / p->spec_partition + 1;
    382380  //p->pickerfn = quadpick;
    383381  //p->biquad = new_biquad(0.1600,0.3200,0.1600, -0.5949, 0.2348);
  • src/pitch/pitchmcomb.h

    r60fc05b rf264b17  
    3636*/
    3737
    38 #ifndef _AUBIO_PITCHMCOMB_H
    39 #define _AUBIO_PITCHMCOMB_H
     38#ifndef AUBIO_PITCHMCOMB_H
     39#define AUBIO_PITCHMCOMB_H
    4040
    4141#ifdef __cplusplus
     
    5353
    5454*/
    55 void aubio_pitchmcomb_do (aubio_pitchmcomb_t * p, cvec_t * in_fftgrain,
     55void aubio_pitchmcomb_do (aubio_pitchmcomb_t * p, const cvec_t * in_fftgrain,
    5656    fvec_t * out_cands);
    5757
     
    7575#endif
    7676
    77 #endif /* _AUBIO_PITCHMCOMB_H */
     77#endif /* AUBIO_PITCHMCOMB_H */
  • src/pitch/pitchschmitt.c

    r60fc05b rf264b17  
    4848
    4949void
    50 aubio_pitchschmitt_do (aubio_pitchschmitt_t * p, fvec_t * input,
     50aubio_pitchschmitt_do (aubio_pitchschmitt_t * p, const fvec_t * input,
    5151    fvec_t * output)
    5252{
  • src/pitch/pitchschmitt.h

    r60fc05b rf264b17  
    3535*/
    3636
    37 #ifndef _AUBIO_PITCHSCHMITT_H
    38 #define _AUBIO_PITCHSCHMITT_H
     37#ifndef AUBIO_PITCHSCHMITT_H
     38#define AUBIO_PITCHSCHMITT_H
    3939
    4040#ifdef __cplusplus
     
    5252
    5353*/
    54 void aubio_pitchschmitt_do (aubio_pitchschmitt_t * p, fvec_t * samples_in,
     54void aubio_pitchschmitt_do (aubio_pitchschmitt_t * p, const fvec_t * samples_in,
    5555    fvec_t * cands_out);
    5656
     
    7373#endif
    7474
    75 #endif /* _AUBIO_PITCHSCHMITT_H */
    76 
     75#endif /* AUBIO_PITCHSCHMITT_H */
  • src/pitch/pitchspecacf.c

    r60fc05b rf264b17  
    5555
    5656void
    57 aubio_pitchspecacf_do (aubio_pitchspecacf_t * p, fvec_t * input, fvec_t * output)
     57aubio_pitchspecacf_do (aubio_pitchspecacf_t * p, const fvec_t * input, fvec_t * output)
    5858{
    5959  uint_t l, tau;
     
    9292
    9393smpl_t
    94 aubio_pitchspecacf_get_confidence (aubio_pitchspecacf_t * o) {
     94aubio_pitchspecacf_get_confidence (const aubio_pitchspecacf_t * o) {
    9595  // no confidence for now
    9696  return o->confidence;
     
    105105
    106106smpl_t
    107 aubio_pitchspecacf_get_tolerance (aubio_pitchspecacf_t * p)
     107aubio_pitchspecacf_get_tolerance (const aubio_pitchspecacf_t * p)
    108108{
    109109  return p->tol;
  • src/pitch/pitchspecacf.h

    r60fc05b rf264b17  
    3939*/
    4040
    41 #ifndef _AUBIO_PITCHSPECACF_H
    42 #define _AUBIO_PITCHSPECACF_H
     41#ifndef AUBIO_PITCHSPECACF_H
     42#define AUBIO_PITCHSPECACF_H
    4343
    4444#ifdef __cplusplus
     
    5656
    5757*/
    58 void aubio_pitchspecacf_do (aubio_pitchspecacf_t * o, fvec_t * samples_in, fvec_t * cands_out);
     58void aubio_pitchspecacf_do (aubio_pitchspecacf_t * o, const fvec_t * samples_in, fvec_t * cands_out);
    5959/** creation of the pitch detection object
    6060
     
    7777
    7878*/
    79 smpl_t aubio_pitchspecacf_get_tolerance (aubio_pitchspecacf_t * o);
     79smpl_t aubio_pitchspecacf_get_tolerance (const aubio_pitchspecacf_t * o);
    8080
    8181/** set tolerance parameter for `specacf` pitch detection object
     
    9595
    9696*/
    97 smpl_t aubio_pitchspecacf_get_confidence (aubio_pitchspecacf_t * o);
     97smpl_t aubio_pitchspecacf_get_confidence (const aubio_pitchspecacf_t * o);
    9898
    9999#ifdef __cplusplus
     
    101101#endif
    102102
    103 #endif /* _AUBIO_PITCHSPECACF_H */
     103#endif /* AUBIO_PITCHSPECACF_H */
  • src/pitch/pitchyin.c

    r60fc05b rf264b17  
    4141
    4242/** compute difference function
    43  
    44   \param input input signal 
     43
     44  \param input input signal
    4545  \param yinbuf output buffer to store difference function (half shorter than input)
    4646
     
    4848void aubio_pitchyin_diff (fvec_t * input, fvec_t * yinbuf);
    4949
    50 /** in place computation of the YIN cumulative normalised function 
    51  
    52   \param yinbuf input signal (a square difference function), also used to store function 
     50/** in place computation of the YIN cumulative normalised function
     51
     52  \param yinbuf input signal (a square difference function), also used to store function
    5353
    5454*/
     
    5656
    5757/** detect pitch in a YIN function
    58  
     58
    5959  \param yinbuf input buffer as computed by aubio_pitchyin_getcum
    6060
    6161*/
    62 uint_t aubio_pitchyin_getpitch (fvec_t * yinbuf);
     62uint_t aubio_pitchyin_getpitch (const fvec_t * yinbuf);
    6363
    6464aubio_pitchyin_t *
     
    112112
    113113uint_t
    114 aubio_pitchyin_getpitch (fvec_t * yin)
     114aubio_pitchyin_getpitch (const fvec_t * yin)
    115115{
    116116  uint_t tau = 1;
     
    131131/* all the above in one */
    132132void
    133 aubio_pitchyin_do (aubio_pitchyin_t * o, fvec_t * input, fvec_t * out)
     133aubio_pitchyin_do (aubio_pitchyin_t * o, const fvec_t * input, fvec_t * out)
    134134{
    135135  smpl_t tol = o->tol;
  • src/pitch/pitchyin.h

    r60fc05b rf264b17  
    3636*/
    3737
    38 #ifndef _AUBIO_PITCHYIN_H
    39 #define _AUBIO_PITCHYIN_H
     38#ifndef AUBIO_PITCHYIN_H
     39#define AUBIO_PITCHYIN_H
    4040
    4141#ifdef __cplusplus
     
    6767
    6868*/
    69 void aubio_pitchyin_do (aubio_pitchyin_t * o, fvec_t * samples_in, fvec_t * cands_out);
     69void aubio_pitchyin_do (aubio_pitchyin_t * o, const fvec_t * samples_in, fvec_t * cands_out);
    7070
    7171
     
    9898#endif
    9999
    100 #endif /* _AUBIO_PITCHYIN_H */
     100#endif /* AUBIO_PITCHYIN_H */
  • src/pitch/pitchyinfft.c

    r60fc05b rf264b17  
    9999
    100100void
    101 aubio_pitchyinfft_do (aubio_pitchyinfft_t * p, fvec_t * input, fvec_t * output)
     101aubio_pitchyinfft_do (aubio_pitchyinfft_t * p, const fvec_t * input, fvec_t * output)
    102102{
    103103  uint_t tau, l;
     
    108108  smpl_t tmp = 0., sum = 0.;
    109109  // window the input
    110   for (l = 0; l < input->length; l++) {
    111     p->winput->data[l] = p->win->data[l] * input->data[l];
    112   }
     110  fvec_weighted_copy(input, p->win, p->winput);
    113111  // get the real / imag parts of its fft
    114112  aubio_fft_do_complex (p->fft, p->winput, fftout);
  • src/pitch/pitchyinfft.h

    r60fc05b rf264b17  
    3636*/
    3737
    38 #ifndef _AUBIO_PITCHYINFFT_H
    39 #define _AUBIO_PITCHYINFFT_H
     38#ifndef AUBIO_PITCHYINFFT_H
     39#define AUBIO_PITCHYINFFT_H
    4040
    4141#ifdef __cplusplus
     
    5353
    5454*/
    55 void aubio_pitchyinfft_do (aubio_pitchyinfft_t * o, fvec_t * samples_in, fvec_t * cands_out);
     55void aubio_pitchyinfft_do (aubio_pitchyinfft_t * o, const fvec_t * samples_in, fvec_t * cands_out);
    5656/** creation of the pitch detection object
    5757
     
    9797#endif
    9898
    99 #endif /* _AUBIO_PITCHYINFFT_H */
     99#endif /* AUBIO_PITCHYINFFT_H */
  • src/spectral/fft.c

    r60fc05b rf264b17  
    6565#ifdef HAVE_FFTW3F
    6666#if HAVE_AUBIO_DOUBLE
    67 #warning "Using aubio in double precision with fftw3 in single precision"
     67#error "Using aubio in double precision with fftw3 in single precision"
    6868#endif /* HAVE_AUBIO_DOUBLE */
    6969#define real_t float
    70 #else /* HAVE_FFTW3F */
     70#elif defined (HAVE_FFTW3) /* HAVE_FFTW3F */
    7171#if !HAVE_AUBIO_DOUBLE
    72 #warning "Using aubio in single precision with fftw3 in double precision"
     72#error "Using aubio in single precision with fftw3 in double precision"
    7373#endif /* HAVE_AUBIO_DOUBLE */
    7474#define real_t double
     
    144144aubio_fft_t * new_aubio_fft (uint_t winsize) {
    145145  aubio_fft_t * s = AUBIO_NEW(aubio_fft_t);
    146   if ((sint_t)winsize < 1) {
    147     AUBIO_ERR("fft: got winsize %d, but can not be < 1\n", winsize);
     146  if ((sint_t)winsize < 2) {
     147    AUBIO_ERR("fft: got winsize %d, but can not be < 2\n", winsize);
    148148    goto beach;
    149149  }
     
    231231}
    232232
    233 void aubio_fft_do(aubio_fft_t * s, fvec_t * input, cvec_t * spectrum) {
     233void aubio_fft_do(aubio_fft_t * s, const fvec_t * input, cvec_t * spectrum) {
    234234  aubio_fft_do_complex(s, input, s->compspec);
    235235  aubio_fft_get_spectrum(s->compspec, spectrum);
    236236}
    237237
    238 void aubio_fft_rdo(aubio_fft_t * s, cvec_t * spectrum, fvec_t * output) {
     238void aubio_fft_rdo(aubio_fft_t * s, const cvec_t * spectrum, fvec_t * output) {
    239239  aubio_fft_get_realimag(spectrum, s->compspec);
    240240  aubio_fft_rdo_complex(s, s->compspec, output);
    241241}
    242242
    243 void aubio_fft_do_complex(aubio_fft_t * s, fvec_t * input, fvec_t * compspec) {
     243void aubio_fft_do_complex(aubio_fft_t * s, const fvec_t * input, fvec_t * compspec) {
    244244  uint_t i;
    245245#ifndef HAVE_MEMCPY_HACKS
     
    292292}
    293293
    294 void aubio_fft_rdo_complex(aubio_fft_t * s, fvec_t * compspec, fvec_t * output) {
     294void aubio_fft_rdo_complex(aubio_fft_t * s, const fvec_t * compspec, fvec_t * output) {
    295295  uint_t i;
    296296#ifdef HAVE_FFTW3
     
    347347}
    348348
    349 void aubio_fft_get_spectrum(fvec_t * compspec, cvec_t * spectrum) {
     349void aubio_fft_get_spectrum(const fvec_t * compspec, cvec_t * spectrum) {
    350350  aubio_fft_get_phas(compspec, spectrum);
    351351  aubio_fft_get_norm(compspec, spectrum);
    352352}
    353353
    354 void aubio_fft_get_realimag(cvec_t * spectrum, fvec_t * compspec) {
     354void aubio_fft_get_realimag(const cvec_t * spectrum, fvec_t * compspec) {
    355355  aubio_fft_get_imag(spectrum, compspec);
    356356  aubio_fft_get_real(spectrum, compspec);
    357357}
    358358
    359 void aubio_fft_get_phas(fvec_t * compspec, cvec_t * spectrum) {
     359void aubio_fft_get_phas(const fvec_t * compspec, cvec_t * spectrum) {
    360360  uint_t i;
    361361  if (compspec->data[0] < 0) {
     
    375375}
    376376
    377 void aubio_fft_get_norm(fvec_t * compspec, cvec_t * spectrum) {
     377void aubio_fft_get_norm(const fvec_t * compspec, cvec_t * spectrum) {
    378378  uint_t i = 0;
    379379  spectrum->norm[0] = ABS(compspec->data[0]);
     
    386386}
    387387
    388 void aubio_fft_get_imag(cvec_t * spectrum, fvec_t * compspec) {
     388void aubio_fft_get_imag(const cvec_t * spectrum, fvec_t * compspec) {
    389389  uint_t i;
    390390  for (i = 1; i < ( compspec->length + 1 ) / 2 /*- 1 + 1*/; i++) {
     
    394394}
    395395
    396 void aubio_fft_get_real(cvec_t * spectrum, fvec_t * compspec) {
     396void aubio_fft_get_real(const cvec_t * spectrum, fvec_t * compspec) {
    397397  uint_t i;
    398398  for (i = 0; i < compspec->length / 2 + 1; i++) {
  • src/spectral/fft.h

    r60fc05b rf264b17  
    3232*/
    3333
    34 #ifndef _AUBIO_FFT_H
    35 #define _AUBIO_FFT_H
     34#ifndef AUBIO_FFT_H
     35#define AUBIO_FFT_H
    3636
    3737#ifdef __cplusplus
     
    6666
    6767*/
    68 void aubio_fft_do (aubio_fft_t *s, fvec_t * input, cvec_t * spectrum);
     68void aubio_fft_do (aubio_fft_t *s, const fvec_t * input, cvec_t * spectrum);
    6969/** compute backward (inverse) FFT
    7070
     
    7474
    7575*/
    76 void aubio_fft_rdo (aubio_fft_t *s, cvec_t * spectrum, fvec_t * output);
     76void aubio_fft_rdo (aubio_fft_t *s, const cvec_t * spectrum, fvec_t * output);
    7777
    7878/** compute forward FFT
     
    8383
    8484*/
    85 void aubio_fft_do_complex (aubio_fft_t *s, fvec_t * input, fvec_t * compspec);
     85void aubio_fft_do_complex (aubio_fft_t *s, const fvec_t * input, fvec_t * compspec);
    8686/** compute backward (inverse) FFT from real/imag
    8787
     
    9191
    9292*/
    93 void aubio_fft_rdo_complex (aubio_fft_t *s, fvec_t * compspec, fvec_t * output);
     93void aubio_fft_rdo_complex (aubio_fft_t *s, const fvec_t * compspec, fvec_t * output);
    9494
    9595/** convert real/imag spectrum to norm/phas spectrum
     
    9999
    100100*/
    101 void aubio_fft_get_spectrum(fvec_t * compspec, cvec_t * spectrum);
     101void aubio_fft_get_spectrum(const fvec_t * compspec, cvec_t * spectrum);
    102102/** convert real/imag spectrum to norm/phas spectrum
    103103
     
    106106
    107107*/
    108 void aubio_fft_get_realimag(cvec_t * spectrum, fvec_t * compspec);
     108void aubio_fft_get_realimag(const cvec_t * spectrum, fvec_t * compspec);
    109109
    110110/** compute phas spectrum from real/imag parts
     
    114114
    115115*/
    116 void aubio_fft_get_phas(fvec_t * compspec, cvec_t * spectrum);
     116void aubio_fft_get_phas(const fvec_t * compspec, cvec_t * spectrum);
    117117/** compute imaginary part from the norm/phas cvec
    118118
     
    121121
    122122*/
    123 void aubio_fft_get_imag(cvec_t * spectrum, fvec_t * compspec);
     123void aubio_fft_get_imag(const cvec_t * spectrum, fvec_t * compspec);
    124124
    125125/** compute norm component from real/imag parts
     
    129129
    130130*/
    131 void aubio_fft_get_norm(fvec_t * compspec, cvec_t * spectrum);
     131void aubio_fft_get_norm(const fvec_t * compspec, cvec_t * spectrum);
    132132/** compute real part from norm/phas components
    133133
     
    136136
    137137*/
    138 void aubio_fft_get_real(cvec_t * spectrum, fvec_t * compspec);
     138void aubio_fft_get_real(const cvec_t * spectrum, fvec_t * compspec);
    139139
    140140#ifdef __cplusplus
     
    142142#endif
    143143
    144 #endif /* _AUBIO_FFT_H */
     144#endif /* AUBIO_FFT_H */
  • src/spectral/filterbank.c

    r60fc05b rf264b17  
    5757
    5858void
    59 aubio_filterbank_do (aubio_filterbank_t * f, cvec_t * in, fvec_t * out)
     59aubio_filterbank_do (aubio_filterbank_t * f, const cvec_t * in, fvec_t * out)
    6060{
    61   uint_t j, fn;
     61  /* apply filter to all input channel, provided out has enough channels */
     62  //uint_t max_filters = MIN (f->n_filters, out->length);
     63  //uint_t max_length = MIN (in->length, f->filters->length);
    6264
    63   /* apply filter to all input channel, provided out has enough channels */
    64   uint_t max_filters = MIN (f->n_filters, out->length);
    65   uint_t max_length = MIN (in->length, f->filters->length);
     65  // view cvec->norm as fvec->data
     66  fvec_t tmp;
     67  tmp.length = in->length;
     68  tmp.data = in->norm;
    6669
    67   /* reset all values in output vector */
    68   fvec_zeros (out);
    69 
    70   /* for each filter */
    71   for (fn = 0; fn < max_filters; fn++) {
    72     /* for each sample */
    73     for (j = 0; j < max_length; j++) {
    74       out->data[fn] += in->norm[j] * f->filters->data[fn][j];
    75     }
    76   }
     70  fmat_vecmul(f->filters, &tmp, out);
    7771
    7872  return;
     
    8074
    8175fmat_t *
    82 aubio_filterbank_get_coeffs (aubio_filterbank_t * f)
     76aubio_filterbank_get_coeffs (const aubio_filterbank_t * f)
    8377{
    8478  return f->filters;
     
    8680
    8781uint_t
    88 aubio_filterbank_set_coeffs (aubio_filterbank_t * f, fmat_t * filter_coeffs)
     82aubio_filterbank_set_coeffs (aubio_filterbank_t * f, const fmat_t * filter_coeffs)
    8983{
    9084  fmat_copy(filter_coeffs, f->filters);
  • src/spectral/filterbank.h

    r60fc05b rf264b17  
    3030*/
    3131
    32 #ifndef _AUBIO_FILTERBANK_H
    33 #define _AUBIO_FILTERBANK_H
     32#ifndef AUBIO_FILTERBANK_H
     33#define AUBIO_FILTERBANK_H
    3434
    3535#ifdef __cplusplus
     
    6767
    6868*/
    69 void aubio_filterbank_do (aubio_filterbank_t * f, cvec_t * in, fvec_t * out);
     69void aubio_filterbank_do (aubio_filterbank_t * f, const cvec_t * in, fvec_t * out);
    7070
    7171/** return a pointer to the matrix object containing all filter coefficients
     
    7474
    7575 */
    76 fmat_t *aubio_filterbank_get_coeffs (aubio_filterbank_t * f);
     76fmat_t *aubio_filterbank_get_coeffs (const aubio_filterbank_t * f);
    7777
    7878/** copy filter coefficients to the filterbank
     
    8282
    8383 */
    84 uint_t aubio_filterbank_set_coeffs (aubio_filterbank_t * f, fmat_t * filters);
     84uint_t aubio_filterbank_set_coeffs (aubio_filterbank_t * f, const fmat_t * filters);
    8585
    8686#ifdef __cplusplus
     
    8888#endif
    8989
    90 #endif /* _AUBIO_FILTERBANK_H */
     90#endif /* AUBIO_FILTERBANK_H */
  • src/spectral/filterbank_mel.c

    r60fc05b rf264b17  
    3030uint_t
    3131aubio_filterbank_set_triangle_bands (aubio_filterbank_t * fb,
    32     fvec_t * freqs, smpl_t samplerate)
     32    const fvec_t * freqs, smpl_t samplerate)
    3333{
    3434
  • src/spectral/filterbank_mel.h

    r60fc05b rf264b17  
    3232*/
    3333
    34 #ifndef _AUBIO_FILTERBANK_MEL_H
    35 #define _AUBIO_FILTERBANK_MEL_H
     34#ifndef AUBIO_FILTERBANK_MEL_H
     35#define AUBIO_FILTERBANK_MEL_H
    3636
    3737#ifdef __cplusplus
     
    5151*/
    5252uint_t aubio_filterbank_set_triangle_bands (aubio_filterbank_t * fb,
    53     fvec_t * freqs, smpl_t samplerate);
     53    const fvec_t * freqs, smpl_t samplerate);
    5454
    5555/** filterbank initialization for Mel filters using Slaney's coefficients
     
    7070#endif
    7171
    72 #endif /* _AUBIO_FILTERBANK_MEL_H */
     72#endif /* AUBIO_FILTERBANK_MEL_H */
  • src/spectral/mfcc.c

    r60fc05b rf264b17  
    6868  mfcc->in_dct = new_fvec (n_filters);
    6969
    70   mfcc->dct_coeffs = new_fmat (n_filters, n_coefs);
     70  mfcc->dct_coeffs = new_fmat (n_coefs, n_filters);
    7171
    72   /* compute DCT transform dct_coeffs[i][j] as
     72  /* compute DCT transform dct_coeffs[j][i] as
    7373     cos ( j * (i+.5) * PI / n_filters ) */
    7474  scaling = 1. / SQRT (n_filters / 2.);
    7575  for (i = 0; i < n_filters; i++) {
    7676    for (j = 0; j < n_coefs; j++) {
    77       mfcc->dct_coeffs->data[i][j] =
     77      mfcc->dct_coeffs->data[j][i] =
    7878          scaling * COS (j * (i + 0.5) * PI / n_filters);
    7979    }
    80     mfcc->dct_coeffs->data[i][0] *= SQRT (2.) / 2.;
     80    mfcc->dct_coeffs->data[0][i] *= SQRT (2.) / 2.;
    8181  }
    8282
    8383  return mfcc;
    84 };
     84}
    8585
    8686void
     
    101101
    102102void
    103 aubio_mfcc_do (aubio_mfcc_t * mf, cvec_t * in, fvec_t * out)
     103aubio_mfcc_do (aubio_mfcc_t * mf, const cvec_t * in, fvec_t * out)
    104104{
    105   uint_t j, k;
    106 
    107105  /* compute filterbank */
    108106  aubio_filterbank_do (mf->fb, in, mf->in_dct);
     
    114112  //fvec_pow (mf->in_dct, 3.);
    115113
    116   /* zeros output */
    117   fvec_zeros(out);
    118 
    119   /* compute discrete cosine transform */
    120   for (j = 0; j < mf->n_filters; j++) {
    121     for (k = 0; k < mf->n_coefs; k++) {
    122       out->data[k] += mf->in_dct->data[j]
    123           * mf->dct_coeffs->data[j][k];
    124     }
    125   }
     114  /* compute mfccs */
     115  fmat_vecmul(mf->dct_coeffs, mf->in_dct, out);
    126116
    127117  return;
  • src/spectral/mfcc.h

    r60fc05b rf264b17  
    3535*/
    3636
    37 #ifndef _AUBIO_MFCC_H
    38 #define _AUBIO_MFCC_H
     37#ifndef AUBIO_MFCC_H
     38#define AUBIO_MFCC_H
    3939
    4040#ifdef __cplusplus
     
    7171
    7272*/
    73 void aubio_mfcc_do (aubio_mfcc_t * mf, cvec_t * in, fvec_t * out);
     73void aubio_mfcc_do (aubio_mfcc_t * mf, const cvec_t * in, fvec_t * out);
    7474
    7575#ifdef __cplusplus
     
    7777#endif
    7878
    79 #endif /* _AUBIO_MFCC_H */
     79#endif /* AUBIO_MFCC_H */
  • src/spectral/phasevoc.c

    r60fc05b rf264b17  
    4545
    4646/** returns data and dataold slided by hop_s */
    47 static void aubio_pvoc_swapbuffers(aubio_pvoc_t *pv, fvec_t *new);
     47static void aubio_pvoc_swapbuffers(aubio_pvoc_t *pv, const fvec_t *new);
    4848
    4949/** do additive synthesis from 'old' and 'cur' */
    5050static void aubio_pvoc_addsynth(aubio_pvoc_t *pv, fvec_t * synthnew);
    5151
    52 void aubio_pvoc_do(aubio_pvoc_t *pv, fvec_t * datanew, cvec_t *fftgrain) {
     52void aubio_pvoc_do(aubio_pvoc_t *pv, const fvec_t * datanew, cvec_t *fftgrain) {
    5353  /* slide  */
    5454  aubio_pvoc_swapbuffers(pv, datanew);
     
    6565  aubio_fft_rdo(pv->fft,fftgrain,pv->synth);
    6666  /* unshift */
    67   fvec_shift(pv->synth);
     67  fvec_ishift(pv->synth);
     68  /* windowing */
     69  // if overlap = 50%, do not apply window (identity)
     70  if (pv->hop_s * 2 < pv->win_s) {
     71    fvec_weight(pv->synth, pv->w);
     72  }
    6873  /* additive synthesis */
    6974  aubio_pvoc_addsynth(pv, synthnew);
     
    8085    AUBIO_ERR("pvoc: got hop_size %d, but can not be < 1\n", hop_s);
    8186    goto beach;
    82   } else if ((sint_t)win_s < 1) {
    83     AUBIO_ERR("pvoc: got buffer_size %d, but can not be < 1\n", win_s);
     87  } else if ((sint_t)win_s < 2) {
     88    AUBIO_ERR("pvoc: got buffer_size %d, but can not be < 2\n", win_s);
    8489    goto beach;
    8590  } else if (win_s < hop_s) {
     
    8994
    9095  pv->fft      = new_aubio_fft (win_s);
     96  if (pv->fft == NULL) {
     97    goto beach;
     98  }
    9199
    92100  /* remember old */
     
    118126  pv->hop_datasize = pv->hop_s * sizeof(smpl_t);
    119127
    120   pv->scale = pv->hop_s * 2. / pv->win_s;
     128  // for reconstruction with 75% overlap
     129  if (win_s == hop_s * 4) {
     130    pv->scale = 2./3.;
     131  } else if (win_s == hop_s * 8) {
     132    pv->scale = 1./3.;
     133  } else if (win_s == hop_s * 2) {
     134    pv->scale = 1.;
     135  } else {
     136    pv->scale = .5;
     137  }
    121138
    122139  return pv;
     
    137154}
    138155
    139 static void aubio_pvoc_swapbuffers(aubio_pvoc_t *pv, fvec_t *new)
     156static void aubio_pvoc_swapbuffers(aubio_pvoc_t *pv, const fvec_t *new)
    140157{
    141158  /* some convenience pointers */
     
    143160  smpl_t * dataold = pv->dataold->data;
    144161  smpl_t * datanew = new->data;
    145 #if !HAVE_MEMCPY_HACKS
     162#ifndef HAVE_MEMCPY_HACKS
    146163  uint_t i;
    147164  for (i = 0; i < pv->end; i++)
  • src/spectral/phasevoc.h

    r60fc05b rf264b17  
    3232*/
    3333
    34 #ifndef _AUBIO_PHASEVOC_H
    35 #define _AUBIO_PHASEVOC_H
     34#ifndef AUBIO_PHASEVOC_H
     35#define AUBIO_PHASEVOC_H
    3636
    3737#ifdef __cplusplus
     
    6868
    6969*/
    70 void aubio_pvoc_do(aubio_pvoc_t *pv, fvec_t *in, cvec_t * fftgrain);
     70void aubio_pvoc_do(aubio_pvoc_t *pv, const fvec_t *in, cvec_t * fftgrain);
    7171/** compute signal from spectral frame
    7272
     
    100100#endif
    101101
    102 #endif /* _AUBIO_PHASEVOC_H */
     102#endif /* AUBIO_PHASEVOC_H */
  • src/spectral/specdesc.c

    r60fc05b rf264b17  
    2727#include "utils/hist.h"
    2828
    29 void aubio_specdesc_energy(aubio_specdesc_t *o, cvec_t * fftgrain, fvec_t * onset);
    30 void aubio_specdesc_hfc(aubio_specdesc_t *o, cvec_t * fftgrain, fvec_t * onset);
    31 void aubio_specdesc_complex(aubio_specdesc_t *o, cvec_t * fftgrain, fvec_t * onset);
    32 void aubio_specdesc_phase(aubio_specdesc_t *o, cvec_t * fftgrain, fvec_t * onset);
    33 void aubio_specdesc_specdiff(aubio_specdesc_t *o, cvec_t * fftgrain, fvec_t * onset);
    34 void aubio_specdesc_kl(aubio_specdesc_t *o, cvec_t * fftgrain, fvec_t * onset);
    35 void aubio_specdesc_mkl(aubio_specdesc_t *o, cvec_t * fftgrain, fvec_t * onset);
    36 void aubio_specdesc_specflux(aubio_specdesc_t *o, cvec_t * fftgrain, fvec_t * onset);
    37 
    38 extern void aubio_specdesc_centroid (aubio_specdesc_t * o, cvec_t * spec,
    39     fvec_t * desc);
    40 extern void aubio_specdesc_spread (aubio_specdesc_t * o, cvec_t * spec,
    41     fvec_t * desc);
    42 extern void aubio_specdesc_skewness (aubio_specdesc_t * o, cvec_t * spec,
    43     fvec_t * desc);
    44 extern void aubio_specdesc_kurtosis (aubio_specdesc_t * o, cvec_t * spec,
    45     fvec_t * desc);
    46 extern void aubio_specdesc_slope (aubio_specdesc_t * o, cvec_t * spec,
    47     fvec_t * desc);
    48 extern void aubio_specdesc_decrease (aubio_specdesc_t * o, cvec_t * spec,
    49     fvec_t * desc);
    50 extern void aubio_specdesc_rolloff (aubio_specdesc_t * o, cvec_t * spec,
     29void aubio_specdesc_energy(aubio_specdesc_t *o, const cvec_t * fftgrain, fvec_t * onset);
     30void aubio_specdesc_hfc(aubio_specdesc_t *o, const cvec_t * fftgrain, fvec_t * onset);
     31void aubio_specdesc_complex(aubio_specdesc_t *o, const cvec_t * fftgrain, fvec_t * onset);
     32void aubio_specdesc_phase(aubio_specdesc_t *o, const cvec_t * fftgrain, fvec_t * onset);
     33void aubio_specdesc_specdiff(aubio_specdesc_t *o, const cvec_t * fftgrain, fvec_t * onset);
     34void aubio_specdesc_kl(aubio_specdesc_t *o, const cvec_t * fftgrain, fvec_t * onset);
     35void aubio_specdesc_mkl(aubio_specdesc_t *o, const cvec_t * fftgrain, fvec_t * onset);
     36void aubio_specdesc_specflux(aubio_specdesc_t *o, const cvec_t * fftgrain, fvec_t * onset);
     37
     38extern void aubio_specdesc_centroid (aubio_specdesc_t * o, const cvec_t * spec,
     39    fvec_t * desc);
     40extern void aubio_specdesc_spread (aubio_specdesc_t * o, const cvec_t * spec,
     41    fvec_t * desc);
     42extern void aubio_specdesc_skewness (aubio_specdesc_t * o, const cvec_t * spec,
     43    fvec_t * desc);
     44extern void aubio_specdesc_kurtosis (aubio_specdesc_t * o, const cvec_t * spec,
     45    fvec_t * desc);
     46extern void aubio_specdesc_slope (aubio_specdesc_t * o, const cvec_t * spec,
     47    fvec_t * desc);
     48extern void aubio_specdesc_decrease (aubio_specdesc_t * o, const cvec_t * spec,
     49    fvec_t * desc);
     50extern void aubio_specdesc_rolloff (aubio_specdesc_t * o, const cvec_t * spec,
    5151    fvec_t * desc);
    5252
     
    7676  /** Pointer to aubio_specdesc_<type> function */
    7777  void (*funcpointer)(aubio_specdesc_t *o,
    78       cvec_t * fftgrain, fvec_t * onset);
     78      const cvec_t * fftgrain, fvec_t * onset);
    7979  smpl_t threshold;      /**< minimum norm threshold for phase and specdiff */
    8080  fvec_t *oldmag;        /**< previous norm vector */
     
    8888/* Energy based onset detection function */
    8989void aubio_specdesc_energy  (aubio_specdesc_t *o UNUSED,
    90     cvec_t * fftgrain, fvec_t * onset) {
     90    const cvec_t * fftgrain, fvec_t * onset) {
    9191  uint_t j;
    9292  onset->data[0] = 0.;
     
    9898/* High Frequency Content onset detection function */
    9999void aubio_specdesc_hfc(aubio_specdesc_t *o UNUSED,
    100     cvec_t * fftgrain, fvec_t * onset){
     100    const cvec_t * fftgrain, fvec_t * onset){
    101101  uint_t j;
    102102  onset->data[0] = 0.;
     
    108108
    109109/* Complex Domain Method onset detection function */
    110 void aubio_specdesc_complex (aubio_specdesc_t *o, cvec_t * fftgrain, fvec_t * onset) {
     110void aubio_specdesc_complex (aubio_specdesc_t *o, const cvec_t * fftgrain, fvec_t * onset) {
    111111  uint_t j;
    112112  uint_t nbins = fftgrain->length;
     
    132132/* Phase Based Method onset detection function */
    133133void aubio_specdesc_phase(aubio_specdesc_t *o,
    134     cvec_t * fftgrain, fvec_t * onset){
     134    const cvec_t * fftgrain, fvec_t * onset){
    135135  uint_t j;
    136136  uint_t nbins = fftgrain->length;
     
    162162/* Spectral difference method onset detection function */
    163163void aubio_specdesc_specdiff(aubio_specdesc_t *o,
    164     cvec_t * fftgrain, fvec_t * onset){
     164    const cvec_t * fftgrain, fvec_t * onset){
    165165  uint_t j;
    166166  uint_t nbins = fftgrain->length;
     
    189189 * note we use ln(1+Xn/(Xn-1+0.0001)) to avoid
    190190 * negative (1.+) and infinite values (+1.e-10) */
    191 void aubio_specdesc_kl(aubio_specdesc_t *o, cvec_t * fftgrain, fvec_t * onset){
     191void aubio_specdesc_kl(aubio_specdesc_t *o, const cvec_t * fftgrain, fvec_t * onset){
    192192  uint_t j;
    193193    onset->data[0] = 0.;
     
    203203 * note we use ln(1+Xn/(Xn-1+0.0001)) to avoid
    204204 * negative (1.+) and infinite values (+1.e-10) */
    205 void aubio_specdesc_mkl(aubio_specdesc_t *o, cvec_t * fftgrain, fvec_t * onset){
     205void aubio_specdesc_mkl(aubio_specdesc_t *o, const cvec_t * fftgrain, fvec_t * onset){
    206206  uint_t j;
    207207    onset->data[0] = 0.;
     
    214214
    215215/* Spectral flux */
    216 void aubio_specdesc_specflux(aubio_specdesc_t *o, cvec_t * fftgrain, fvec_t * onset){
     216void aubio_specdesc_specflux(aubio_specdesc_t *o, const cvec_t * fftgrain, fvec_t * onset){
    217217  uint_t j;
    218218  onset->data[0] = 0.;
     
    226226/* Generic function pointing to the choosen one */
    227227void
    228 aubio_specdesc_do (aubio_specdesc_t *o, cvec_t * fftgrain,
     228aubio_specdesc_do (aubio_specdesc_t *o, const cvec_t * fftgrain,
    229229    fvec_t * onset) {
    230230  o->funcpointer(o,fftgrain,onset);
     
    235235 */
    236236aubio_specdesc_t *
    237 new_aubio_specdesc (char_t * onset_mode, uint_t size){
     237new_aubio_specdesc (const char_t * onset_mode, uint_t size){
    238238  aubio_specdesc_t * o = AUBIO_NEW(aubio_specdesc_t);
    239239  uint_t rsize = size/2+1;
  • src/spectral/specdesc.h

    r60fc05b rf264b17  
    146146
    147147
    148 #ifndef _AUBIO_SPECDESC_H
    149 #define _AUBIO_SPECDESC_H
     148#ifndef AUBIO_SPECDESC_H
     149#define AUBIO_SPECDESC_H
    150150
    151151#ifdef __cplusplus
     
    165165
    166166*/
    167 void aubio_specdesc_do (aubio_specdesc_t * o, cvec_t * fftgrain,
     167void aubio_specdesc_do (aubio_specdesc_t * o, const cvec_t * fftgrain,
    168168    fvec_t * desc);
    169169
     
    179179
    180180*/
    181 aubio_specdesc_t *new_aubio_specdesc (char_t * method, uint_t buf_size);
     181aubio_specdesc_t *new_aubio_specdesc (const char_t * method, uint_t buf_size);
    182182
    183183/** deletion of a spectral descriptor
     
    192192#endif
    193193
    194 #endif /* _AUBIO_SPECDESC_H */
     194#endif /* AUBIO_SPECDESC_H */
  • src/spectral/statistics.c

    r60fc05b rf264b17  
    2323#include "spectral/specdesc.h"
    2424
    25 void aubio_specdesc_centroid (aubio_specdesc_t * o, cvec_t * spec,
    26     fvec_t * desc);
    27 void aubio_specdesc_spread (aubio_specdesc_t * o, cvec_t * spec,
    28     fvec_t * desc);
    29 void aubio_specdesc_skewness (aubio_specdesc_t * o, cvec_t * spec,
    30     fvec_t * desc);
    31 void aubio_specdesc_kurtosis (aubio_specdesc_t * o, cvec_t * spec,
    32     fvec_t * desc);
    33 void aubio_specdesc_slope (aubio_specdesc_t * o, cvec_t * spec,
    34     fvec_t * desc);
    35 void aubio_specdesc_decrease (aubio_specdesc_t * o, cvec_t * spec,
    36     fvec_t * desc);
    37 void aubio_specdesc_rolloff (aubio_specdesc_t * o, cvec_t * spec,
    38     fvec_t * desc);
    39 
    40 
    41 smpl_t cvec_sum (cvec_t * s);
    42 smpl_t cvec_mean (cvec_t * s);
    43 smpl_t cvec_centroid (cvec_t * s);
    44 smpl_t cvec_moment (cvec_t * s, uint_t moment);
    45 
    46 smpl_t
    47 cvec_sum (cvec_t * s)
     25void aubio_specdesc_centroid (aubio_specdesc_t * o, const cvec_t * spec,
     26    fvec_t * desc);
     27void aubio_specdesc_spread (aubio_specdesc_t * o, const cvec_t * spec,
     28    fvec_t * desc);
     29void aubio_specdesc_skewness (aubio_specdesc_t * o, const cvec_t * spec,
     30    fvec_t * desc);
     31void aubio_specdesc_kurtosis (aubio_specdesc_t * o, const cvec_t * spec,
     32    fvec_t * desc);
     33void aubio_specdesc_slope (aubio_specdesc_t * o, const cvec_t * spec,
     34    fvec_t * desc);
     35void aubio_specdesc_decrease (aubio_specdesc_t * o, const cvec_t * spec,
     36    fvec_t * desc);
     37void aubio_specdesc_rolloff (aubio_specdesc_t * o, const cvec_t * spec,
     38    fvec_t * desc);
     39
     40
     41smpl_t cvec_sum (const cvec_t * s);
     42smpl_t cvec_mean (const cvec_t * s);
     43smpl_t cvec_centroid (const cvec_t * s);
     44smpl_t cvec_moment (const cvec_t * s, uint_t moment);
     45
     46smpl_t
     47cvec_sum (const cvec_t * s)
    4848{
    4949  uint_t j;
     
    5656
    5757smpl_t
    58 cvec_mean (cvec_t * s)
     58cvec_mean (const cvec_t * s)
    5959{
    6060  return cvec_sum (s) / (smpl_t) (s->length);
     
    6262
    6363smpl_t
    64 cvec_centroid (cvec_t * spec)
     64cvec_centroid (const cvec_t * spec)
    6565{
    6666  smpl_t sum = 0., sc = 0.;
     
    7878
    7979smpl_t
    80 cvec_moment (cvec_t * spec, uint_t order)
     80cvec_moment (const cvec_t * spec, uint_t order)
    8181{
    8282  smpl_t sum = 0., centroid = 0., sc = 0.;
     
    9595
    9696void
    97 aubio_specdesc_centroid (aubio_specdesc_t * o UNUSED, cvec_t * spec,
     97aubio_specdesc_centroid (aubio_specdesc_t * o UNUSED, const cvec_t * spec,
    9898    fvec_t * desc)
    9999{
     
    102102
    103103void
    104 aubio_specdesc_spread (aubio_specdesc_t * o UNUSED, cvec_t * spec,
     104aubio_specdesc_spread (aubio_specdesc_t * o UNUSED, const cvec_t * spec,
    105105    fvec_t * desc)
    106106{
     
    109109
    110110void
    111 aubio_specdesc_skewness (aubio_specdesc_t * o UNUSED, cvec_t * spec,
     111aubio_specdesc_skewness (aubio_specdesc_t * o UNUSED, const cvec_t * spec,
    112112    fvec_t * desc)
    113113{
     
    123123
    124124void
    125 aubio_specdesc_kurtosis (aubio_specdesc_t * o UNUSED, cvec_t * spec,
     125aubio_specdesc_kurtosis (aubio_specdesc_t * o UNUSED, const cvec_t * spec,
    126126    fvec_t * desc)
    127127{
     
    137137
    138138void
    139 aubio_specdesc_slope (aubio_specdesc_t * o UNUSED, cvec_t * spec,
     139aubio_specdesc_slope (aubio_specdesc_t * o UNUSED, const cvec_t * spec,
    140140    fvec_t * desc)
    141141{
     
    165165
    166166void
    167 aubio_specdesc_decrease (aubio_specdesc_t *o UNUSED, cvec_t * spec,
     167aubio_specdesc_decrease (aubio_specdesc_t *o UNUSED, const cvec_t * spec,
    168168    fvec_t * desc)
    169169{
     
    183183
    184184void
    185 aubio_specdesc_rolloff (aubio_specdesc_t *o UNUSED, cvec_t * spec,
     185aubio_specdesc_rolloff (aubio_specdesc_t *o UNUSED, const cvec_t * spec,
    186186    fvec_t *desc)
    187187{
  • src/spectral/tss.c

    r60fc05b rf264b17  
    4141};
    4242
    43 void aubio_tss_do(aubio_tss_t *o, cvec_t * input,
     43void aubio_tss_do(aubio_tss_t *o, const cvec_t * input,
    4444    cvec_t * trans, cvec_t * stead)
    4545{
  • src/spectral/tss.h

    r60fc05b rf264b17  
    3737*/
    3838
    39 #ifndef _AUBIO_TSS_H
    40 #define _AUBIO_TSS_H
     39#ifndef AUBIO_TSS_H
     40#define AUBIO_TSS_H
    4141
    4242#ifdef __cplusplus
     
    7070
    7171*/
    72 void aubio_tss_do (aubio_tss_t * o, cvec_t * input, cvec_t * trans,
     72void aubio_tss_do (aubio_tss_t * o, const cvec_t * input, cvec_t * trans,
    7373    cvec_t * stead);
    7474
     
    101101#endif
    102102
    103 #endif /* _AUBIO_TSS_H */
     103#endif /* AUBIO_TSS_H */
  • src/synth/sampler.c

    r60fc05b rf264b17  
    5656}
    5757
    58 uint_t aubio_sampler_load( aubio_sampler_t * o, char_t * uri )
     58uint_t aubio_sampler_load( aubio_sampler_t * o, const char_t * uri )
    5959{
    6060  if (o->source) del_aubio_source(o->source);
    61   o->uri = uri;
     61
     62  if (o->uri) AUBIO_FREE(o->uri);
     63  o->uri = AUBIO_ARRAY(char_t, strnlen(uri, PATH_MAX));
     64  strncpy(o->uri, uri, strnlen(uri, PATH_MAX));
     65
    6266  o->source = new_aubio_source(uri, o->samplerate, o->blocksize);
    6367  if (o->source) return 0;
     
    6670}
    6771
    68 void aubio_sampler_do ( aubio_sampler_t * o, fvec_t * input, fvec_t * output)
     72void aubio_sampler_do ( aubio_sampler_t * o, const fvec_t * input, fvec_t * output)
    6973{
    7074  uint_t read = 0, i;
     
    8387}
    8488
    85 void aubio_sampler_do_multi ( aubio_sampler_t * o, fmat_t * input, fmat_t * output)
     89void aubio_sampler_do_multi ( aubio_sampler_t * o, const fmat_t * input, fmat_t * output)
    8690{
    8791  uint_t read = 0, i, j;
     
    104108}
    105109
    106 uint_t aubio_sampler_get_playing ( aubio_sampler_t * o )
     110uint_t aubio_sampler_get_playing ( const aubio_sampler_t * o )
    107111{
    108112  return o->playing;
     
    131135    del_aubio_source(o->source);
    132136  }
     137  if (o->uri) AUBIO_FREE(o->uri);
    133138  del_fvec(o->source_output);
    134139  del_fmat(o->source_output_multi);
  • src/synth/sampler.h

    r60fc05b rf264b17  
    1919*/
    2020
    21 #ifndef _AUBIO_SAMPLER_H
    22 #define _AUBIO_SAMPLER_H
     21#ifndef AUBIO_SAMPLER_H
     22#define AUBIO_SAMPLER_H
    2323
    2424/** \file
     
    6060
    6161*/
    62 uint_t aubio_sampler_load( aubio_sampler_t * o, char_t * uri );
     62uint_t aubio_sampler_load( aubio_sampler_t * o, const char_t * uri );
    6363
    6464/** process sampler function
     
    7474
    7575*/
    76 void aubio_sampler_do ( aubio_sampler_t * o, fvec_t * input, fvec_t * output);
     76void aubio_sampler_do ( aubio_sampler_t * o, const fvec_t * input, fvec_t * output);
    7777
    7878/** process sampler function, multiple channels
     
    8888
    8989*/
    90 void aubio_sampler_do_multi ( aubio_sampler_t * o, fmat_t * input, fmat_t * output);
     90void aubio_sampler_do_multi ( aubio_sampler_t * o, const fmat_t * input, fmat_t * output);
    9191
    9292/** get current playing state
     
    9797
    9898*/
    99 uint_t aubio_sampler_get_playing ( aubio_sampler_t * o );
     99uint_t aubio_sampler_get_playing ( const aubio_sampler_t * o );
    100100
    101101/** set current playing state
     
    138138#endif
    139139
    140 #endif /* _AUBIO_SAMPLER_H */
     140#endif /* AUBIO_SAMPLER_H */
  • src/synth/wavetable.c

    r60fc05b rf264b17  
    6969}
    7070
    71 static smpl_t interp_2(fvec_t *input, smpl_t pos) {
     71static smpl_t interp_2(const fvec_t *input, smpl_t pos) {
    7272  uint_t idx = (uint_t)FLOOR(pos);
    7373  smpl_t frac = pos - (smpl_t)idx;
     
    7777}
    7878
    79 void aubio_wavetable_do ( aubio_wavetable_t * s, fvec_t * input, fvec_t * output)
     79void aubio_wavetable_do ( aubio_wavetable_t * s, const fvec_t * input, fvec_t * output)
    8080{
    8181  uint_t i;
     
    108108}
    109109
    110 void aubio_wavetable_do_multi ( aubio_wavetable_t * s, fmat_t * input, fmat_t * output)
     110void aubio_wavetable_do_multi ( aubio_wavetable_t * s, const fmat_t * input, fmat_t * output)
    111111{
    112112  uint_t i, j;
     
    143143}
    144144
    145 uint_t aubio_wavetable_get_playing ( aubio_wavetable_t * s )
     145uint_t aubio_wavetable_get_playing ( const aubio_wavetable_t * s )
    146146{
    147147  return s->playing;
     
    173173}
    174174
    175 smpl_t aubio_wavetable_get_freq ( aubio_wavetable_t * s) {
     175smpl_t aubio_wavetable_get_freq ( const aubio_wavetable_t * s) {
    176176  return aubio_parameter_get_current_value ( s->freq);
    177177}
     
    182182}
    183183
    184 smpl_t aubio_wavetable_get_amp ( aubio_wavetable_t * s) {
     184smpl_t aubio_wavetable_get_amp ( const aubio_wavetable_t * s) {
    185185  return aubio_parameter_get_current_value ( s->amp );
    186186}
  • src/synth/wavetable.h

    r60fc05b rf264b17  
    1919*/
    2020
    21 #ifndef _AUBIO_WAVETABLE_H
    22 #define _AUBIO_WAVETABLE_H
     21#ifndef AUBIO_WAVETABLE_H
     22#define AUBIO_WAVETABLE_H
    2323
    2424/** \file
     
    6060
    6161*/
    62 uint_t aubio_wavetable_load( aubio_wavetable_t * o, char_t * uri );
     62uint_t aubio_wavetable_load( aubio_wavetable_t * o, const char_t * uri );
    6363
    6464/** process wavetable function
     
    7474
    7575*/
    76 void aubio_wavetable_do ( aubio_wavetable_t * o, fvec_t * input, fvec_t * output);
     76void aubio_wavetable_do ( aubio_wavetable_t * o, const fvec_t * input, fvec_t * output);
    7777
    7878/** process wavetable function, multiple channels
     
    8888
    8989*/
    90 void aubio_wavetable_do_multi ( aubio_wavetable_t * o, fmat_t * input, fmat_t * output);
     90void aubio_wavetable_do_multi ( aubio_wavetable_t * o, const fmat_t * input, fmat_t * output);
    9191
    9292/** get current playing state
     
    9797
    9898*/
    99 uint_t aubio_wavetable_get_playing ( aubio_wavetable_t * o );
     99uint_t aubio_wavetable_get_playing ( const aubio_wavetable_t * o );
    100100
    101101/** set current playing state
     
    144144
    145145*/
    146 smpl_t aubio_wavetable_get_freq ( aubio_wavetable_t * o);
     146smpl_t aubio_wavetable_get_freq ( const aubio_wavetable_t * o);
    147147
    148148/** set wavetable amplitude
     
    163163
    164164*/
    165 smpl_t aubio_wavetable_get_amp ( aubio_wavetable_t * o);
     165smpl_t aubio_wavetable_get_amp ( const aubio_wavetable_t * o);
    166166
    167167/** destroy aubio_wavetable_t object
     
    176176#endif
    177177
    178 #endif /* _AUBIO_WAVETABLE_H */
     178#endif /* AUBIO_WAVETABLE_H */
  • src/tempo/beattracking.c

    r60fc05b rf264b17  
    124124
    125125void
    126 aubio_beattracking_do (aubio_beattracking_t * bt, fvec_t * dfframe,
     126aubio_beattracking_do (aubio_beattracking_t * bt, const fvec_t * dfframe,
    127127    fvec_t * output)
    128128{
     
    410410
    411411smpl_t
    412 aubio_beattracking_get_bpm (aubio_beattracking_t * bt)
     412aubio_beattracking_get_period (const aubio_beattracking_t * bt)
     413{
     414  return bt->hop_size * bt->bp;
     415}
     416
     417smpl_t
     418aubio_beattracking_get_period_s (const aubio_beattracking_t * bt)
     419{
     420  return aubio_beattracking_get_period(bt) / (smpl_t) bt->samplerate;
     421}
     422
     423smpl_t
     424aubio_beattracking_get_bpm (const aubio_beattracking_t * bt)
    413425{
    414426  if (bt->bp != 0) {
    415     return 60. * bt->samplerate/ bt->bp / bt->hop_size;
     427    return 60. / aubio_beattracking_get_period_s(bt);
    416428  } else {
    417429    return 0.;
     
    420432
    421433smpl_t
    422 aubio_beattracking_get_confidence (aubio_beattracking_t * bt)
     434aubio_beattracking_get_confidence (const aubio_beattracking_t * bt)
    423435{
    424436  if (bt->gp) {
  • src/tempo/beattracking.h

    r60fc05b rf264b17  
    3737
    3838*/
    39 #ifndef _AUBIO_BEATTRACKING_H
    40 #define _AUBIO_BEATTRACKING_H
     39#ifndef AUBIO_BEATTRACKING_H
     40#define AUBIO_BEATTRACKING_H
    4141
    4242#ifdef __cplusplus
     
    6565
    6666*/
    67 void aubio_beattracking_do (aubio_beattracking_t * bt, fvec_t * dfframes,
     67void aubio_beattracking_do (aubio_beattracking_t * bt, const fvec_t * dfframes,
    6868    fvec_t * out);
     69
     70/** get current beat period in samples
     71
     72  \param bt beat tracking object
     73
     74  Returns the currently observed period, in samples, or 0 if no consistent
     75  value is found.
     76
     77*/
     78smpl_t aubio_beattracking_get_period (const aubio_beattracking_t * bt);
     79
     80/** get current beat period in seconds
     81
     82  \param bt beat tracking object
     83
     84  Returns the currently observed period, in seconds, or 0 if no consistent
     85  value is found.
     86
     87*/
     88smpl_t aubio_beattracking_get_period_s (const aubio_beattracking_t * bt);
    6989
    7090/** get current tempo in bpm
     
    7696
    7797*/
    78 smpl_t aubio_beattracking_get_bpm(aubio_beattracking_t * bt);
     98smpl_t aubio_beattracking_get_bpm(const aubio_beattracking_t * bt);
    7999
    80100/** get current tempo confidence
     
    86106
    87107*/
    88 smpl_t aubio_beattracking_get_confidence(aubio_beattracking_t * bt);
     108smpl_t aubio_beattracking_get_confidence(const aubio_beattracking_t * bt);
    89109
    90110/** delete beat tracking object
     
    99119#endif
    100120
    101 #endif /* _AUBIO_BEATTRACKING_H */
     121#endif /* AUBIO_BEATTRACKING_H */
  • src/tempo/tempo.c

    r60fc05b rf264b17  
    2828#include "mathutils.h"
    2929#include "tempo/tempo.h"
    30 
    31 // TODO implement get/set_delay
    32 
    33 /** set current delay
    34 
    35   \param o beat tracking object
    36 
    37   \return current delay, in samples
    38 
    39  */
    40 uint_t aubio_tempo_get_delay(aubio_tempo_t * o);
    41 
    42 /** set current delay
    43 
    44   \param o beat tracking object
    45   \param delay delay to set tempo to, in samples
    46 
    47   \return `0` if successful, non-zero otherwise
    48 
    49  */
    50 uint_t aubio_tempo_set_delay(aubio_tempo_t * o, uint_t delay);
    5130
    5231/* structure to store object state */
     
    6544  sint_t blockpos;               /** current position in dfframe */
    6645  uint_t winlen;                 /** dfframe bufsize */
    67   uint_t step;                   /** dfframe hopsize */ 
    68   uint_t samplerate;             /** sampling rate of the signal */ 
     46  uint_t step;                   /** dfframe hopsize */
     47  uint_t samplerate;             /** sampling rate of the signal */
    6948  uint_t hop_size;               /** get hop_size */
    7049  uint_t total_frames;           /** total frames since beginning */
    7150  uint_t last_beat;              /** time of latest detected beat, in samples */
    72   uint_t delay;                  /** delay to remove to last beat, in samples */
     51  sint_t delay;                  /** delay to remove to last beat, in samples */
     52  uint_t last_tatum;             /** time of latest detected tatum, in samples */
     53  uint_t tatum_signature;        /** number of tatum between each beats */
    7354};
    7455
    7556/* execute tempo detection function on iput buffer */
    76 void aubio_tempo_do(aubio_tempo_t *o, fvec_t * input, fvec_t * tempo)
     57void aubio_tempo_do(aubio_tempo_t *o, const fvec_t * input, fvec_t * tempo)
    7758{
    7859  uint_t i;
     
    9172    aubio_beattracking_do(o->bt,o->dfframe,o->out);
    9273    /* rotate dfframe */
    93     for (i = 0 ; i < winlen - step; i++ ) 
     74    for (i = 0 ; i < winlen - step; i++ )
    9475      o->dfframe->data[i] = o->dfframe->data[i+step];
    95     for (i = winlen - step ; i < winlen; i++ ) 
     76    for (i = winlen - step ; i < winlen; i++ )
    9677      o->dfframe->data[i] = 0.;
    9778    o->blockpos = -1;
     
    9980  o->blockpos++;
    10081  aubio_peakpicker_do (o->pp, o->of, o->onset);
    101   tempo->data[1] = o->onset->data[0];
     82  // store onset detection function in second sample of vector
     83  //tempo->data[1] = o->onset->data[0];
    10284  thresholded = aubio_peakpicker_get_thresholded_input(o->pp);
    10385  o->dfframe->data[winlen - step + o->blockpos] = thresholded->data[0];
    10486  /* end of second level loop */
    10587  tempo->data[0] = 0; /* reset tactus */
    106   i=0;
     88  //i=0;
    10789  for (i = 1; i < o->out->data[0]; i++ ) {
    10890    /* if current frame is a predicted tactus */
     
    11496      }
    11597      o->last_beat = o->total_frames + (uint_t)ROUND(tempo->data[0] * o->hop_size);
     98      o->last_tatum = o->last_beat;
    11699    }
    117100  }
     
    122105uint_t aubio_tempo_get_last (aubio_tempo_t *o)
    123106{
    124   return o->last_beat - o->delay;
     107  return o->last_beat + o->delay;
    125108}
    126109
     
    135118}
    136119
    137 uint_t aubio_tempo_set_delay(aubio_tempo_t * o, uint_t delay) {
     120uint_t aubio_tempo_set_delay(aubio_tempo_t * o, sint_t delay) {
    138121  o->delay = delay;
     122  return AUBIO_OK;
     123}
     124
     125uint_t aubio_tempo_set_delay_s(aubio_tempo_t * o, smpl_t delay) {
     126  o->delay = delay * o->samplerate;
     127  return AUBIO_OK;
     128}
     129
     130uint_t aubio_tempo_set_delay_ms(aubio_tempo_t * o, smpl_t delay) {
     131  o->delay = 1000. * delay * o->samplerate;
    139132  return AUBIO_OK;
    140133}
     
    142135uint_t aubio_tempo_get_delay(aubio_tempo_t * o) {
    143136  return o->delay;
     137}
     138
     139smpl_t aubio_tempo_get_delay_s(aubio_tempo_t * o) {
     140  return o->delay / (smpl_t)(o->samplerate);
     141}
     142
     143smpl_t aubio_tempo_get_delay_ms(aubio_tempo_t * o) {
     144  return o->delay / (smpl_t)(o->samplerate) / 1000.;
    144145}
    145146
     
    164165
    165166/* Allocate memory for an tempo detection */
    166 aubio_tempo_t * new_aubio_tempo (char_t * tempo_mode,
     167aubio_tempo_t * new_aubio_tempo (const char_t * tempo_mode,
    167168    uint_t buf_size, uint_t hop_size, uint_t samplerate)
    168169{
     
    174175    AUBIO_ERR("tempo: got hop size %d, but can not be < 1\n", hop_size);
    175176    goto beach;
    176   } else if ((sint_t)buf_size < 1) {
    177     AUBIO_ERR("tempo: got window size %d, but can not be < 1\n", buf_size);
     177  } else if ((sint_t)buf_size < 2) {
     178    AUBIO_ERR("tempo: got window size %d, but can not be < 2\n", buf_size);
    178179    goto beach;
    179180  } else if (buf_size < hop_size) {
     
    215216    onset2 = new_fvec(1);
    216217  }*/
     218  o->last_tatum = 0;
     219  o->tatum_signature = 4;
    217220  return o;
    218221
     
    226229}
    227230
     231smpl_t aubio_tempo_get_period (aubio_tempo_t *o)
     232{
     233  return aubio_beattracking_get_period (o->bt);
     234}
     235
     236smpl_t aubio_tempo_get_period_s (aubio_tempo_t *o)
     237{
     238  return aubio_beattracking_get_period_s (o->bt);
     239}
     240
    228241smpl_t aubio_tempo_get_confidence(aubio_tempo_t *o) {
    229242  return aubio_beattracking_get_confidence(o->bt);
     243}
     244
     245uint_t aubio_tempo_was_tatum (aubio_tempo_t *o)
     246{
     247  uint_t last_tatum_distance = o->total_frames - o->last_tatum;
     248  smpl_t beat_period = aubio_tempo_get_period(o);
     249  smpl_t tatum_period = beat_period / o->tatum_signature;
     250  if (last_tatum_distance < o->hop_size) {
     251    o->last_tatum = o->last_beat;
     252    return 2;
     253  }
     254  else if (last_tatum_distance > tatum_period) {
     255    if ( last_tatum_distance + o->hop_size > beat_period ) {
     256      // next beat is too close, pass
     257      return 0;
     258    }
     259    o->last_tatum = o->total_frames;
     260    return 1;
     261  }
     262  return 0;
     263}
     264
     265smpl_t aubio_tempo_get_last_tatum (aubio_tempo_t *o) {
     266  return (smpl_t)o->last_tatum - o->delay;
     267}
     268
     269uint_t aubio_tempo_set_tatum_signature (aubio_tempo_t *o, uint_t signature) {
     270  if (signature < 1 || signature > 64) {
     271    return AUBIO_FAIL;
     272  } else {
     273    o->tatum_signature = signature;
     274    return AUBIO_OK;
     275  }
    230276}
    231277
  • src/tempo/tempo.h

    r60fc05b rf264b17  
    3131*/
    3232
    33 #ifndef _AUBIO_TEMPO_H
    34 #define _AUBIO_TEMPO_H
     33#ifndef AUBIO_TEMPO_H
     34#define AUBIO_TEMPO_H
    3535
    3636#ifdef __cplusplus
     
    5151
    5252*/
    53 aubio_tempo_t * new_aubio_tempo (char_t * method,
     53aubio_tempo_t * new_aubio_tempo (const char_t * method,
    5454    uint_t buf_size, uint_t hop_size, uint_t samplerate);
    5555
     
    6161
    6262*/
    63 void aubio_tempo_do (aubio_tempo_t *o, fvec_t * input, fvec_t * tempo);
     63void aubio_tempo_do (aubio_tempo_t *o, const fvec_t * input, fvec_t * tempo);
    6464
    6565/** get the time of the latest beat detected, in samples
     
    121121*/
    122122smpl_t aubio_tempo_get_threshold(aubio_tempo_t * o);
     123
     124/** get current beat period in samples
     125
     126  \param bt beat tracking object
     127
     128  Returns the currently observed period, in samples, or 0 if no consistent
     129  value is found.
     130
     131*/
     132smpl_t aubio_tempo_get_period (aubio_tempo_t * bt);
     133
     134/** get current beat period in seconds
     135
     136  \param bt beat tracking object
     137
     138  Returns the currently observed period, in seconds, or 0 if no consistent
     139  value is found.
     140
     141*/
     142smpl_t aubio_tempo_get_period_s (aubio_tempo_t * bt);
    123143
    124144/** get current tempo
     
    140160*/
    141161smpl_t aubio_tempo_get_confidence(aubio_tempo_t * o);
     162
     163/* set number of tatum per beat
     164
     165   \param o beat tracking object
     166   \param signature number of tatum per beat (between 1 and 64)
     167
     168*/
     169uint_t aubio_tempo_set_tatum_signature(aubio_tempo_t *o, uint_t signature);
     170
     171/* check whether a tatum was detected in the current frame
     172
     173   \param o beat tracking object
     174
     175   \return 2 if a beat was detected, 1 if a tatum was detected, 0 otherwise
     176
     177*/
     178uint_t aubio_tempo_was_tatum(aubio_tempo_t *o);
     179
     180/* get position of last_tatum, in samples
     181
     182   \param o beat tracking object
     183
     184*/
     185smpl_t aubio_tempo_get_last_tatum(aubio_tempo_t *o);
     186
     187/** get current delay
     188
     189  \param o beat tracking object
     190
     191  \return current delay, in samples
     192
     193 */
     194uint_t aubio_tempo_get_delay(aubio_tempo_t * o);
     195
     196/** get current delay in seconds
     197
     198  \param o beat tracking object
     199
     200  \return current delay, in seconds
     201
     202 */
     203smpl_t aubio_tempo_get_delay_s(aubio_tempo_t * o);
     204
     205/** get current delay in ms
     206
     207  \param o beat tracking object
     208
     209  \return current delay, in milliseconds
     210
     211 */
     212smpl_t aubio_tempo_get_delay_ms(aubio_tempo_t * o);
     213
     214/** set current delay
     215
     216  \param o beat tracking object
     217  \param delay delay to set tempo to, in samples
     218
     219  \return `0` if successful, non-zero otherwise
     220
     221 */
     222uint_t aubio_tempo_set_delay(aubio_tempo_t * o, sint_t delay);
     223
     224/** set current delay in seconds
     225
     226  \param o beat tracking object
     227  \param delay delay to set tempo to, in seconds
     228
     229  \return `0` if successful, non-zero otherwise
     230
     231 */
     232uint_t aubio_tempo_set_delay_s(aubio_tempo_t * o, smpl_t delay);
     233
     234/** set current delay
     235
     236  \param o beat tracking object
     237  \param delay delay to set tempo to, in samples
     238
     239  \return `0` if successful, non-zero otherwise
     240
     241 */
     242uint_t aubio_tempo_set_delay_ms(aubio_tempo_t * o, smpl_t delay);
    142243
    143244/** delete tempo detection object
     
    152253#endif
    153254
    154 #endif /* _AUBIO_TEMPO_H */
     255#endif /* AUBIO_TEMPO_H */
  • src/temporal/a_weighting.c

    r60fc05b rf264b17  
    3030{
    3131  uint_t order; lsmp_t *a, *b; lvec_t *as, *bs;
     32
     33  if ((sint_t)samplerate <= 0) {
     34    AUBIO_ERROR("aubio_filter: failed setting A-weighting with samplerate %d\n", samplerate);
     35    return AUBIO_FAIL;
     36  }
     37  if (f == NULL) {
     38    AUBIO_ERROR("aubio_filter: failed setting A-weighting with filter NULL\n");
     39    return AUBIO_FAIL;
     40  }
     41
     42  order = aubio_filter_get_order (f);
     43  if (order != 7) {
     44    AUBIO_ERROR ("aubio_filter: order of A-weighting filter must be 7, not %d\n", order);
     45    return 1;
     46  }
     47
    3248  aubio_filter_set_samplerate (f, samplerate);
    3349  bs = aubio_filter_get_feedforward (f);
    3450  as = aubio_filter_get_feedback (f);
    3551  b = bs->data, a = as->data;
    36   order = aubio_filter_get_order (f);
    37 
    38   if (order != 7) {
    39     AUBIO_ERROR ("order of A-weighting filter must be 7, not %d\n", order);
    40     return 1;
    41   }
    4252
    4353  /* select coefficients according to sampling frequency */
     
    245255{
    246256  aubio_filter_t *f = new_aubio_filter (7);
    247   aubio_filter_set_a_weighting (f, samplerate);
     257  if (aubio_filter_set_a_weighting(f,samplerate) != AUBIO_OK) {
     258    del_aubio_filter(f);
     259    return NULL;
     260  }
    248261  return f;
    249262}
  • src/temporal/a_weighting.h

    r60fc05b rf264b17  
    1919*/
    2020
    21 #ifndef _AUBIO_FILTER_A_DESIGN_H
    22 #define _AUBIO_FILTER_A_DESIGN_H
     21#ifndef AUBIO_FILTER_A_DESIGN_H
     22#define AUBIO_FILTER_A_DESIGN_H
    2323
    2424/** \file
     
    8686#endif
    8787
    88 #endif /* _AUBIO_FILTER_A_DESIGN_H */
     88#endif /* AUBIO_FILTER_A_DESIGN_H */
  • src/temporal/biquad.h

    r60fc05b rf264b17  
    1919*/
    2020
    21 #ifndef _AUBIO_FILTER_BIQUAD_H
    22 #define _AUBIO_FILTER_BIQUAD_H
     21#ifndef AUBIO_FILTER_BIQUAD_H
     22#define AUBIO_FILTER_BIQUAD_H
    2323
    2424/** \file
     
    7373#endif
    7474
    75 #endif /* _AUBIO_FILTER_BIQUAD_H */
     75#endif /* AUBIO_FILTER_BIQUAD_H */
  • src/temporal/c_weighting.c

    r60fc05b rf264b17  
    3030{
    3131  uint_t order; lsmp_t *a, *b; lvec_t *as, *bs;
     32
     33  if ((sint_t)samplerate <= 0) {
     34    AUBIO_ERROR("aubio_filter: failed setting C-weighting with samplerate %d\n", samplerate);
     35    return AUBIO_FAIL;
     36  }
     37  if (f == NULL) {
     38    AUBIO_ERROR("aubio_filter: failed setting C-weighting with filter NULL\n");
     39    return AUBIO_FAIL;
     40  }
     41
     42  order = aubio_filter_get_order (f);
     43  if ( order != 5 ) {
     44    AUBIO_ERROR ("aubio_filter: order of C-weighting filter must be 5, not %d\n", order);
     45    return 1;
     46  }
     47
    3248  aubio_filter_set_samplerate (f, samplerate);
    3349  bs = aubio_filter_get_feedforward (f);
    3450  as = aubio_filter_get_feedback (f);
    3551  b = bs->data, a = as->data;
    36   order = aubio_filter_get_order (f);
    37 
    38   if ( order != 5 ) {
    39     AUBIO_ERROR ("order of C-weighting filter must be 5, not %d\n", order);
    40     return 1;
    41   }
    4252
    4353  /* select coefficients according to sampling frequency */
     
    200210aubio_filter_t * new_aubio_filter_c_weighting (uint_t samplerate) {
    201211  aubio_filter_t * f = new_aubio_filter(5);
    202   aubio_filter_set_c_weighting (f, samplerate);
     212  if (aubio_filter_set_c_weighting(f,samplerate) != AUBIO_OK) {
     213    del_aubio_filter(f);
     214    return NULL;
     215  }
    203216  return f;
    204217}
    205 
  • src/temporal/c_weighting.h

    r60fc05b rf264b17  
    1919*/
    2020
    21 #ifndef _AUBIO_FILTER_C_DESIGN_H
    22 #define _AUBIO_FILTER_C_DESIGN_H
     21#ifndef AUBIO_FILTER_C_DESIGN_H
     22#define AUBIO_FILTER_C_DESIGN_H
    2323
    2424/** \file
     
    8686#endif
    8787
    88 #endif /* _AUBIO_FILTER_C_DESIGN_H */
     88#endif /* AUBIO_FILTER_C_DESIGN_H */
  • src/temporal/filter.c

    r60fc05b rf264b17  
    4040
    4141void
    42 aubio_filter_do_outplace (aubio_filter_t * f, fvec_t * in, fvec_t * out)
     42aubio_filter_do_outplace (aubio_filter_t * f, const fvec_t * in, fvec_t * out)
    4343{
    4444  fvec_copy (in, out);
     
    9494
    9595lvec_t *
    96 aubio_filter_get_feedback (aubio_filter_t * f)
     96aubio_filter_get_feedback (const aubio_filter_t * f)
    9797{
    9898  return f->a;
     
    100100
    101101lvec_t *
    102 aubio_filter_get_feedforward (aubio_filter_t * f)
     102aubio_filter_get_feedforward (const aubio_filter_t * f)
    103103{
    104104  return f->b;
     
    106106
    107107uint_t
    108 aubio_filter_get_order (aubio_filter_t * f)
     108aubio_filter_get_order (const aubio_filter_t * f)
    109109{
    110110  return f->order;
     
    112112
    113113uint_t
    114 aubio_filter_get_samplerate (aubio_filter_t * f)
     114aubio_filter_get_samplerate (const aubio_filter_t * f)
    115115{
    116116  return f->samplerate;
     
    135135{
    136136  aubio_filter_t *f = AUBIO_NEW (aubio_filter_t);
     137  if ((sint_t)order < 1) {
     138    AUBIO_FREE(f);
     139    return NULL;
     140  }
    137141  f->x = new_lvec (order);
    138142  f->y = new_lvec (order);
     
    143147  f->order = order;
    144148  /* set default to identity */
    145   f->a->data[1] = 1.;
     149  f->a->data[0] = 1.;
     150  f->b->data[0] = 1.;
    146151  return f;
    147152}
  • src/temporal/filter.h

    r60fc05b rf264b17  
    1919*/
    2020
    21 #ifndef _AUBIO_FILTER_H
    22 #define _AUBIO_FILTER_H
     21#ifndef AUBIO_FILTER_H
     22#define AUBIO_FILTER_H
    2323
    2424/** \file
     
    8787
    8888*/
    89 void aubio_filter_do_outplace (aubio_filter_t * f, fvec_t * in, fvec_t * out);
     89void aubio_filter_do_outplace (aubio_filter_t * f, const fvec_t * in, fvec_t * out);
    9090
    9191/** filter input vector forward and backward
     
    105105
    106106*/
    107 lvec_t *aubio_filter_get_feedback (aubio_filter_t * f);
     107lvec_t *aubio_filter_get_feedback (const aubio_filter_t * f);
    108108
    109109/** returns a pointer to feedforward coefficients \f$ b_i \f$
     
    114114
    115115*/
    116 lvec_t *aubio_filter_get_feedforward (aubio_filter_t * f);
     116lvec_t *aubio_filter_get_feedforward (const aubio_filter_t * f);
    117117
    118118/** get order of the filter
     
    123123
    124124*/
    125 uint_t aubio_filter_get_order (aubio_filter_t * f);
     125uint_t aubio_filter_get_order (const aubio_filter_t * f);
    126126
    127127/** get sampling rate of the filter
     
    132132
    133133*/
    134 uint_t aubio_filter_get_samplerate (aubio_filter_t * f);
     134uint_t aubio_filter_get_samplerate (const aubio_filter_t * f);
    135135
    136136/** get sampling rate of the filter
     
    174174#endif
    175175
    176 #endif /* _AUBIO_FILTER_H */
     176#endif /* AUBIO_FILTER_H */
  • src/temporal/resampler.c

    r60fc05b rf264b17  
    2525#include "temporal/resampler.h"
    2626
    27 #if HAVE_SAMPLERATE
     27#ifdef HAVE_SAMPLERATE
    2828
    2929#include <samplerate.h>         /* from libsamplerate */
     
    6262
    6363void
    64 aubio_resampler_do (aubio_resampler_t * s, fvec_t * input, fvec_t * output)
     64aubio_resampler_do (aubio_resampler_t * s, const fvec_t * input, fvec_t * output)
    6565{
    6666  s->proc->input_frames = input->length;
     
    9393
    9494void
    95 aubio_resampler_do (aubio_resampler_t * s UNUSED, fvec_t * input UNUSED, fvec_t * output UNUSED)
     95aubio_resampler_do (aubio_resampler_t * s UNUSED, const fvec_t * input UNUSED, fvec_t * output UNUSED)
    9696{
    9797}
  • src/temporal/resampler.h

    r60fc05b rf264b17  
    1919*/
    2020
    21 #ifndef _AUBIO_RESAMPLER_H
    22 #define _AUBIO_RESAMPLER_H
     21#ifndef AUBIO_RESAMPLER_H
     22#define AUBIO_RESAMPLER_H
    2323
    2424/** \file
     
    5656
    5757*/
    58 void aubio_resampler_do (aubio_resampler_t * s, fvec_t * input,
     58void aubio_resampler_do (aubio_resampler_t * s, const fvec_t * input,
    5959    fvec_t * output);
    6060
     
    6363#endif
    6464
    65 #endif /* _AUBIO_RESAMPLER_H */
     65#endif /* AUBIO_RESAMPLER_H */
  • src/types.h

    r60fc05b rf264b17  
    1919*/
    2020
    21 #ifndef _AUBIO__TYPES_H
    22 #define _AUBIO__TYPES_H
     21#ifndef AUBIO_TYPES_H
     22#define AUBIO_TYPES_H
    2323
    2424/** \file
     
    6868#endif
    6969
    70 #endif /* _AUBIO__TYPES_H */
     70#endif /* AUBIO_TYPES_H */
  • src/utils/hist.c

    r60fc05b rf264b17  
    138138}
    139139
    140 smpl_t aubio_hist_mean (aubio_hist_t *s) {
     140smpl_t aubio_hist_mean (const aubio_hist_t *s) {
    141141  uint_t j;
    142142  smpl_t tmp = 0.0;
  • src/utils/hist.h

    r60fc05b rf264b17  
    2626 */
    2727
    28 #ifndef _AUBIO_HIST_H
    29 #define _AUBIO_HIST_H
     28#ifndef AUBIO_HIST_H
     29#define AUBIO_HIST_H
    3030
    3131#ifdef __cplusplus
     
    5151void aubio_hist_do_notnull(aubio_hist_t *s, fvec_t * input);
    5252/** compute the mean of the histogram */
    53 smpl_t aubio_hist_mean(aubio_hist_t *s);
     53smpl_t aubio_hist_mean(const aubio_hist_t *s);
    5454/** weight the histogram */
    5555void aubio_hist_weight(aubio_hist_t *s);
     
    6161#endif
    6262
    63 #endif /* _AUBIO_HIST_H */
     63#endif /* AUBIO_HIST_H */
  • src/utils/parameter.c

    r60fc05b rf264b17  
    8585}
    8686
    87 smpl_t aubio_parameter_get_current_value ( aubio_parameter_t * s )
     87smpl_t aubio_parameter_get_current_value ( const aubio_parameter_t * s )
    8888{
    8989  return s->current_value;
     
    110110}
    111111
    112 uint_t aubio_parameter_get_steps ( aubio_parameter_t * param )
     112uint_t aubio_parameter_get_steps ( const aubio_parameter_t * param )
    113113{
    114114  return param->steps;
     
    121121}
    122122
    123 smpl_t aubio_parameter_get_min_value ( aubio_parameter_t * param )
     123smpl_t aubio_parameter_get_min_value ( const aubio_parameter_t * param )
    124124{
    125125  return param->min_value;
     
    132132}
    133133
    134 smpl_t aubio_parameter_get_max_value ( aubio_parameter_t * param )
     134smpl_t aubio_parameter_get_max_value ( const aubio_parameter_t * param )
    135135{
    136136  return param->max_value;
  • src/utils/parameter.h

    r60fc05b rf264b17  
    1919*/
    2020
    21 #ifndef _AUBIO_PARAMETER_H
    22 #define _AUBIO_PARAMETER_H
     21#ifndef AUBIO_PARAMETER_H
     22#define AUBIO_PARAMETER_H
    2323
    2424/** \file
     
    7777
    7878*/
    79 smpl_t aubio_parameter_get_current_value ( aubio_parameter_t * param );
     79smpl_t aubio_parameter_get_current_value ( const aubio_parameter_t * param );
    8080
    8181/** set current parameter value, skipping interpolation
     
    106106
    107107*/
    108 uint_t aubio_parameter_get_steps ( aubio_parameter_t * param);
     108uint_t aubio_parameter_get_steps ( const aubio_parameter_t * param);
    109109
    110110/** set minimum value of this parameter
     
    125125
    126126*/
    127 smpl_t aubio_parameter_get_min_value ( aubio_parameter_t * param );
     127smpl_t aubio_parameter_get_min_value ( const aubio_parameter_t * param );
    128128
    129129/** set maximum value of this parameter
     
    144144
    145145*/
    146 smpl_t aubio_parameter_get_max_value ( aubio_parameter_t * param );
     146smpl_t aubio_parameter_get_max_value ( const aubio_parameter_t * param );
    147147
    148148/** destroy ::aubio_parameter_t object
     
    157157#endif
    158158
    159 #endif /* _AUBIO_PARAMETER_H */
     159#endif /* AUBIO_PARAMETER_H */
  • src/utils/scale.c

    r60fc05b rf264b17  
    3838};
    3939
    40 aubio_scale_t * new_aubio_scale (smpl_t ilow, smpl_t ihig, 
     40aubio_scale_t * new_aubio_scale (smpl_t ilow, smpl_t ihig,
    4141    smpl_t olow, smpl_t ohig) {
    4242  aubio_scale_t * s = AUBIO_NEW(aubio_scale_t);
  • src/utils/scale.h

    r60fc05b rf264b17  
    2929
    3030*/
    31 #ifndef _AUBIO_SCALE_H
    32 #define _AUBIO_SCALE_H
     31#ifndef AUBIO_SCALE_H
     32#define AUBIO_SCALE_H
    3333
    3434#ifdef __cplusplus
     
    7878#endif
    7979
    80 #endif /* _AUBIO_SCALE_H */
     80#endif /* AUBIO_SCALE_H */
  • src/vecutils.h

    r60fc05b rf264b17  
    2525 */
    2626
    27 #ifndef _AUBIO__VECUTILS_H
    28 #define _AUBIO__VECUTILS_H
     27#ifndef AUBIO_VECUTILS_H
     28#define AUBIO_VECUTILS_H
    2929
    3030#ifdef __cplusplus
     
    114114#endif
    115115
    116 #endif /* _AUBIO__VECUTILS_H */
     116#endif /* AUBIO_VECUTILS_H */
  • src/wscript_build

    r60fc05b rf264b17  
    22
    33uselib = []
     4uselib += ['M']
    45uselib += ['FFTW3', 'FFTW3F']
    56uselib += ['SAMPLERATE']
     
    910uselib += ['AVRESAMPLE']
    1011uselib += ['AVUTIL']
     12uselib += ['BLAS']
    1113
    12 # build each source files
    1314source = ctx.path.ant_glob('*.c **/*.c')
     15
    1416ctx(features = 'c',
    1517        source = source,
    1618        includes = ['.'],
    17         uselib = uselib,
    18         lib = 'm',
     19        use = uselib,
    1920        target = 'lib_objects')
    2021
     
    2324    build_features = ['cstlib', 'cshlib']
    2425elif ctx.env['DEST_OS'] in ['win32', 'win64']:
    25     build_features = ['cshlib']
     26    build_features = ['cstlib', 'cshlib']
     27elif ctx.env['DEST_OS'] in ['emscripten']:
     28    build_features = ['cstlib']
    2629else: #linux, darwin, android, mingw, ...
    27     build_features = ['cshlib', 'cstlib']
     30    build_features = ['cstlib', 'cshlib']
    2831
    2932for target in build_features:
    3033    ctx(features = 'c ' + target,
    31             use = ['lib_objects'],
    32             uselib = uselib,
    33             lib = 'm',
     34            use = uselib + ['lib_objects'],
    3435            target = 'aubio',
    3536            vnum = ctx.env['LIB_VERSION'])
  • tests/src/io/test-source.c

    r60fc05b rf264b17  
    3434  fvec_t *vec = new_fvec(hop_size);
    3535
     36  uint_t n_frames_expected = aubio_source_get_duration(s);
     37
    3638  samplerate = aubio_source_get_samplerate(s);
    3739
     
    4244  } while ( read == hop_size );
    4345
    44   PRINT_MSG("read %d frames at %dHz (%d blocks) from %s\n", n_frames, samplerate,
    45     n_frames / hop_size, source_path);
     46  PRINT_MSG("read %d frames (expected %d) at %dHz (%d blocks) from %s\n",
     47            n_frames, n_frames_expected, samplerate, n_frames / hop_size,
     48            source_path);
    4649
    4750  // close the file (optional)
  • tests/src/io/test-source_apple_audio.c

    r60fc05b rf264b17  
    3939  fvec_t *vec = new_fvec(hop_size);
    4040
     41  uint_t n_frames_expected = aubio_source_apple_audio_get_duration(s);
     42
    4143  samplerate = aubio_source_apple_audio_get_samplerate(s);
    4244
     
    4749  } while ( read == hop_size );
    4850
    49   PRINT_MSG("read %d frames at %dHz (%d blocks) from %s\n", n_frames, samplerate,
    50     n_frames / hop_size, source_path);
     51  PRINT_MSG("read %d frames (expected %d) at %dHz (%d blocks) from %s\n",
     52            n_frames, n_frames_expected, samplerate, n_frames / hop_size,
     53            source_path);
    5154
    5255  del_fvec (vec);
  • tests/src/io/test-source_avcodec.c

    r60fc05b rf264b17  
    3939  fvec_t *vec = new_fvec(hop_size);
    4040
     41  uint_t n_frames_expected = aubio_source_avcodec_get_duration(s);
     42
    4143  samplerate = aubio_source_avcodec_get_samplerate(s);
    4244
     
    4749  } while ( read == hop_size );
    4850
    49   PRINT_MSG("read %d frames at %dHz (%d blocks) from %s\n", n_frames, samplerate,
    50     n_frames / hop_size, source_path);
     51  PRINT_MSG("read %d frames (expected %d) at %dHz (%d blocks) from %s\n",
     52            n_frames, n_frames_expected, samplerate, n_frames / hop_size,
     53            source_path);
    5154
    5255  del_fvec (vec);
  • tests/src/io/test-source_sndfile.c

    r60fc05b rf264b17  
    3939  fvec_t *vec = new_fvec(hop_size);
    4040
     41  uint_t n_frames_expected = aubio_source_sndfile_get_duration(s);
     42
    4143  samplerate = aubio_source_sndfile_get_samplerate(s);
    4244
     
    4749  } while ( read == hop_size );
    4850
    49   PRINT_MSG("read %d frames at %dHz (%d blocks) from %s\n", n_frames, samplerate,
    50     n_frames / hop_size, source_path);
     51  PRINT_MSG("read %d frames (expected %d) at %dHz (%d blocks) from %s\n",
     52            n_frames, n_frames_expected, samplerate, n_frames / hop_size,
     53            source_path);
    5154
    5255  del_fvec (vec);
  • tests/src/io/test-source_wavread.c

    r60fc05b rf264b17  
    3636  aubio_source_wavread_t * s =
    3737    new_aubio_source_wavread(source_path, samplerate, hop_size);
     38
    3839  if (!s) { err = 1; goto beach; }
    3940  fvec_t *vec = new_fvec(hop_size);
     41
     42  uint_t n_frames_expected = aubio_source_wavread_get_duration(s);
    4043
    4144  samplerate = aubio_source_wavread_get_samplerate(s);
     
    4750  } while ( read == hop_size );
    4851
    49   PRINT_MSG("read %d frames at %dHz (%d blocks) from %s\n", n_frames, samplerate,
    50     n_frames / hop_size, source_path);
     52  PRINT_MSG("read %d frames (expected %d) at %dHz (%d blocks) from %s\n",
     53            n_frames, n_frames_expected, samplerate, n_frames / hop_size,
     54            source_path);
    5155
    5256  del_fvec (vec);
  • tests/src/tempo/test-tempo.c

    r60fc05b rf264b17  
    2828  // create some vectors
    2929  fvec_t * in = new_fvec (hop_size); // input audio buffer
    30   fvec_t * out = new_fvec (2); // output position
     30  fvec_t * out = new_fvec (1); // output position
    3131
    3232  // create tempo object
  • tests/src/temporal/test-a_weighting.c

    r60fc05b rf264b17  
    2121  // samplerate unknown
    2222  f = new_aubio_filter_a_weighting (4200);
    23   del_aubio_filter (f);
     23  if (!f) {
     24    //PRINT_MSG ("failed creating A-weighting filter with samplerate=4200Hz\n");
     25  }
    2426
    2527  // order to small
    2628  f = new_aubio_filter (2);
    27   aubio_filter_set_a_weighting (f, samplerate);
     29  if (aubio_filter_set_a_weighting (f, samplerate) != 0) {
     30    //PRINT_MSG ("failed setting filter to A-weighting\n");
     31  }
    2832  del_aubio_filter (f);
    2933
    3034  // order to big
    3135  f = new_aubio_filter (12);
    32   aubio_filter_set_a_weighting (f, samplerate);
     36  if (aubio_filter_set_a_weighting (f, samplerate) != 0) {
     37    //PRINT_MSG ("failed setting filter to A-weighting\n");
     38  }
    3339  del_aubio_filter (f);
    3440
  • tests/src/temporal/test-c_weighting.c

    r60fc05b rf264b17  
    2020  // samplerate unknown
    2121  f = new_aubio_filter_c_weighting (4200);
    22   del_aubio_filter (f);
     22  if (!f) {
     23    //PRINT_WRN ("failed creating C-weighting filter with samplerate=4200Hz");
     24  }
    2325
    2426  // order to small
    2527  f = new_aubio_filter (2);
    26   aubio_filter_set_c_weighting (f, samplerate);
     28  if (aubio_filter_set_c_weighting (f, samplerate) != 0) {
     29    //PRINT_WRN ("failed setting filter to C-weighting");
     30  }
    2731  del_aubio_filter (f);
    2832
    2933  // order to big
    3034  f = new_aubio_filter (12);
    31   aubio_filter_set_c_weighting (f, samplerate);
     35  if (aubio_filter_set_c_weighting (f, samplerate) != 0) {
     36    //PRINT_WRN ("failed setting filter to C-weighting");
     37  }
    3238  del_aubio_filter (f);
    3339
  • tests/src/test-lvec.c

    r60fc05b rf264b17  
    77  lvec_t * sp = new_lvec (win_s); // input buffer
    88  lvec_set_sample (sp, 2./3., 0);
    9   PRINT_MSG("%lf\n", lvec_get_sample (sp, 0));
     9  PRINT_MSG(AUBIO_LSMP_FMT "\n", lvec_get_sample (sp, 0));
    1010  lvec_print (sp);
    1111  lvec_ones (sp);
  • tests/utils_tests.h

    r60fc05b rf264b17  
    66#include "config.h"
    77
     8#ifdef HAVE_C99_VARARGS_MACROS
     9#define PRINT_ERR(...)   fprintf(stderr, "AUBIO-TESTS ERROR: " __VA_ARGS__)
     10#define PRINT_MSG(...)   fprintf(stdout, __VA_ARGS__)
     11#define PRINT_DBG(...)   fprintf(stderr, __VA_ARGS__)
     12#define PRINT_WRN(...)   fprintf(stderr, "AUBIO-TESTS WARNING: " __VA_ARGS__)
     13#else
    814#define PRINT_ERR(format, args...)   fprintf(stderr, "AUBIO-TESTS ERROR: " format , ##args)
    915#define PRINT_MSG(format, args...)   fprintf(stdout, format , ##args)
    1016#define PRINT_DBG(format, args...)   fprintf(stderr, format , ##args)
    1117#define PRINT_WRN(format, args...)   fprintf(stderr, "AUBIO-TESTS WARNING: " format, ##args)
     18#endif
    1219
    13 #ifdef HAVE_WIN_HACKS
     20#ifndef M_PI
     21#define M_PI         (3.14159265358979323846)
     22#endif
     23
     24#ifndef RAND_MAX
     25#define RAND_MAX 32767
     26#endif
     27
     28// are we on windows ? or are we using -std=c99 ?
     29#if defined(HAVE_WIN_HACKS) || defined(__STRICT_ANSI__)
    1430// http://en.wikipedia.org/wiki/Linear_congruential_generator
    1531// no srandom/random on win32
  • tests/wscript_build

    r60fc05b rf264b17  
    11# vim:set syntax=python:
    22
    3 for target_name in ctx.path.ant_glob('src/**/*.c'):
    4     uselib = []
    5     uselib += ['FFTW3', 'FFTW3F']
    6     uselib += ['SAMPLERATE']
    7     uselib += ['SNDFILE']
    8     uselib += ['AVCODEC']
    9     uselib += ['AVFORMAT']
    10     uselib += ['AVRESAMPLE']
    11     uselib += ['AVUTIL']
    12     uselib += ['JACK']
    13     includes = ['../src', '.']
    14     extra_source = []
     3uselib = ['aubio']
    154
     5includes = ['../src', '.']
     6programs_sources = ctx.path.ant_glob('src/**/*.c')
     7
     8for source_file in programs_sources:
    169    bld(features = 'c cprogram test',
    17             lib = 'm',
    18             uselib = uselib,
    19             source = [target_name] + extra_source,
    20             target = str(target_name).split('.')[0],
     10            source = source_file,
     11            target = str(source_file).split('.')[0],
    2112            includes = includes,
     13            use = uselib,
    2214            install_path = None,
    2315            defines = 'AUBIO_UNSTABLE_API=1',
    24             cflags = ['-g'],
    25             use = 'aubio')
     16       )
  • wscript

    r60fc05b rf264b17  
    8282            help_str = 'use CoreFoundation (darwin only) (auto)',
    8383            help_disable_str = 'do not use CoreFoundation framework')
     84    add_option_enable_disable(ctx, 'atlas', default = None,
     85            help_str = 'use Atlas library (auto)',
     86            help_disable_str = 'do not use Atlas library')
     87
     88    add_option_enable_disable(ctx, 'docs', default = None,
     89            help_str = 'build documentation (auto)',
     90            help_disable_str = 'do not build documentation')
    8491
    8592    ctx.add_option('--with-target-platform', type='string',
     
    96103    ctx.load('gnu_dirs')
    97104
     105    # check for common headers
     106    ctx.check(header_name='stdlib.h')
     107    ctx.check(header_name='stdio.h')
     108    ctx.check(header_name='math.h')
     109    ctx.check(header_name='string.h')
     110    ctx.check(header_name='limits.h')
     111    ctx.check(header_name='getopt.h', mandatory = False)
     112    ctx.check(header_name='unistd.h', mandatory = False)
     113
    98114    target_platform = Options.platform
    99115    if ctx.options.target_platform:
     
    101117    ctx.env['DEST_OS'] = target_platform
    102118
    103     if 'CL.exe' not in ctx.env.CC[0]:
     119    if ctx.env.CC_NAME != 'msvc':
    104120        ctx.env.CFLAGS += ['-g', '-Wall', '-Wextra']
    105121    else:
    106         ctx.env.CFLAGS += ['-Wall']
     122        ctx.env.CFLAGS += ['/W4', '/MD']
     123        ctx.env.CFLAGS += ['/D_CRT_SECURE_NO_WARNINGS']
     124
     125    ctx.check_cc(lib='m', uselib_store='M', mandatory=False)
    107126
    108127    if target_platform not in ['win32', 'win64']:
     
    115134        ctx.env.CFLAGS += ['-arch', 'i386', '-arch', 'x86_64']
    116135        ctx.env.LINKFLAGS += ['-arch', 'i386', '-arch', 'x86_64']
     136        MINSDKVER="10.4"
     137        ctx.env.CFLAGS += [ '-mmacosx-version-min=' + MINSDKVER ]
     138        ctx.env.LINKFLAGS += [ '-mmacosx-version-min=' + MINSDKVER ]
    117139
    118140    if target_platform in [ 'darwin', 'ios', 'iosimulator']:
     
    128150        MINSDKVER="6.1"
    129151        ctx.env.CFLAGS += ['-std=c99']
    130         if (ctx.options.enable_audio_unit != False):
     152        if (ctx.options.enable_apple_audio != False):
    131153            ctx.define('HAVE_AUDIO_UNIT', 1)
    132154            #ctx.env.FRAMEWORK += ['CoreFoundation', 'AudioToolbox']
     
    135157            DEVROOT += "/Developer/Platforms/iPhoneOS.platform/Developer"
    136158            SDKROOT = "%(DEVROOT)s/SDKs/iPhoneOS.sdk" % locals()
     159            ctx.env.CFLAGS += [ '-fembed-bitcode' ]
    137160            ctx.env.CFLAGS += [ '-arch', 'arm64' ]
    138161            ctx.env.CFLAGS += [ '-arch', 'armv7' ]
     
    156179        ctx.env.LINKFLAGS += [ '-isysroot' , SDKROOT]
    157180
    158     # check for required headers
    159     ctx.check(header_name='stdlib.h')
    160     ctx.check(header_name='stdio.h')
    161     ctx.check(header_name='math.h')
    162     ctx.check(header_name='string.h')
    163     ctx.check(header_name='limits.h')
     181    if target_platform == 'emscripten':
     182        import os.path
     183        ctx.env.CFLAGS += [ '-I' + os.path.join(os.environ['EMSCRIPTEN'], 'system', 'include') ]
     184        ctx.env.CFLAGS += ['-Oz']
     185        ctx.env.cprogram_PATTERN = "%s.js"
     186        if (ctx.options.enable_atlas != True):
     187            ctx.options.enable_atlas = False
    164188
    165189    # check support for C99 __VA_ARGS__ macros
     
    175199        ctx.define('HAVE_C99_VARARGS_MACROS', 1)
    176200
    177     # double precision mode
     201    # show a message about enable_double status
    178202    if (ctx.options.enable_double == True):
    179         ctx.define('HAVE_AUBIO_DOUBLE', 1)
    180     else:
    181         ctx.define('HAVE_AUBIO_DOUBLE', 0)
     203        ctx.msg('Checking for size of smpl_t', 'double')
     204        ctx.msg('Checking for size of lsmp_t', 'long double')
     205    else:
     206        ctx.msg('Checking for size of smpl_t', 'float')
     207        ctx.msg('Checking for size of lsmp_t', 'double')
    182208
    183209    # optionally use complex.h
    184210    if (ctx.options.enable_complex == True):
    185211        ctx.check(header_name='complex.h')
     212    else:
     213        ctx.msg('Checking if complex.h is enabled', 'no')
    186214
    187215    # check for fftw3
     
    260288    ctx.define('HAVE_WAVWRITE', 1)
    261289
     290    # use ATLAS
     291    if (ctx.options.enable_atlas != False):
     292        ctx.check(header_name = 'atlas/cblas.h', mandatory = ctx.options.enable_atlas)
     293        #ctx.check(lib = 'lapack', uselib_store = 'LAPACK', mandatory = ctx.options.enable_atlas)
     294        ctx.check(lib = 'cblas', uselib_store = 'BLAS', mandatory = ctx.options.enable_atlas)
     295
    262296    # use memcpy hacks
    263297    if (ctx.options.enable_memcpy == True):
    264298        ctx.define('HAVE_MEMCPY_HACKS', 1)
    265     else:
    266         ctx.define('HAVE_MEMCPY_HACKS', 0)
    267299
    268300    # write configuration header
    269301    ctx.write_config_header('src/config.h')
     302
     303    # the following defines will be passed as arguments to the compiler
     304    # instead of being written to src/config.h
    270305
    271306    # add some defines used in examples
     
    273308    ctx.define('PACKAGE', APPNAME)
    274309
    275     # check if txt2man is installed, optional
    276     try:
    277       ctx.find_program('txt2man', var='TXT2MAN')
    278     except ctx.errors.ConfigurationError:
    279       ctx.to_log('txt2man was not found (ignoring)')
    280 
    281     # check if doxygen is installed, optional
    282     try:
    283       ctx.find_program('doxygen', var='DOXYGEN')
    284     except ctx.errors.ConfigurationError:
    285       ctx.to_log('doxygen was not found (ignoring)')
     310    # double precision mode
     311    if (ctx.options.enable_double == True):
     312        ctx.define('HAVE_AUBIO_DOUBLE', 1)
     313
     314    if (ctx.options.enable_docs != False):
     315        # check if txt2man is installed, optional
     316        try:
     317          ctx.find_program('txt2man', var='TXT2MAN')
     318        except ctx.errors.ConfigurationError:
     319          ctx.to_log('txt2man was not found (ignoring)')
     320
     321        # check if doxygen is installed, optional
     322        try:
     323          ctx.find_program('doxygen', var='DOXYGEN')
     324        except ctx.errors.ConfigurationError:
     325          ctx.to_log('doxygen was not found (ignoring)')
    286326
    287327def build(bld):
     
    291331    # add sub directories
    292332    bld.recurse('src')
    293     if bld.env['DEST_OS'] not in ['ios', 'iosimulator']:
    294         pass
    295333    if bld.env['DEST_OS'] not in ['ios', 'iosimulator', 'android']:
    296334        bld.recurse('examples')
     
    340378    ctx.excl += ' **/build/*'
    341379    ctx.excl += ' **/python/gen **/python/build **/python/dist'
     380    ctx.excl += ' **/python/ext/config.h'
    342381    ctx.excl += ' **/**.zip **/**.tar.bz2'
    343382    ctx.excl += ' **/doc/full/* **/doc/web/*'
    344383    ctx.excl += ' **/python/*.db'
    345384    ctx.excl += ' **/python.old/*'
     385    ctx.excl += ' **/python/*/*.old'
    346386    ctx.excl += ' **/python/tests/sounds'
    347387    ctx.excl += ' **/**.asc'
     388    ctx.excl += ' **/.DS_Store'
     389    ctx.excl += ' **/.travis.yml'
     390    ctx.excl += ' **/dist*'
     391    ctx.excl += ' **/appveyor.yml'
Note: See TracChangeset for help on using the changeset viewer.