ref: fc117d05d899d2ad3adc8807f449d6b886b3ff80
parent: 5314432e23a351e56ff5341adb5b6a39265b7342
parent: 88fc249b016fa3176f82f53a4bfbba8d87266ea0
author: Paul Brossier <piem@piem.org>
date: Mon Feb 11 00:06:28 EST 2013
merge from develop
--- a/.gitignore
+++ b/.gitignore
@@ -1,11 +1,3 @@
-Makefile.in
-Makefile
-.deps
-.libs
-*.lo
-*.la
-*.o
-
*.pyc
*.~[0-9]~
*.swp
@@ -21,9 +13,6 @@
RE:tests/src/test-[a-z-_]*$
RE:tests/cpp/test-[a-z-_]*$
-# ignore aubio
-plugins/puredata/aubio.pd_linux
-
# only sgml manpages count
doc/*.1
@@ -31,40 +20,14 @@
**/cachegrind.out.[0-9]*
**/callgrind.out.[0-9]*
-# swig and java stuff
-**/*.class
-java/**/SWIG*.java
-java/**/aubio*.java
-java/**/midi_*.java
-
# waf stuff
-.lock-wscript
+.lock-waf*
+.waf-*
build/
-# autoreconf -f -i will create these
-INSTALL
-aclocal.m4
-aubio.pc
-autom4te.cache/
-compile
-config.guess
-config.log
-config.status
-config.sub
-configure
-depcomp
-mkinstalldirs
-install-sh
-libtool
-ltmain.sh
-missing
-py-compile
-src/config.h
-src/config.h.in
-src/config.h.in~
-src/stamp-h1
-
# doxygen
doc/devel/
doc/user/
doc/examples/
+
+python/*.db
--- a/Makefile.am
+++ /dev/null
@@ -1,45 +1,0 @@
-if DOCBOOKFOUND
-DOC = doc
-endif
-
-if SWIGFOUND
-SWIGDIR = swig
-if PYTHONFOUND
-PYTHONDIR = python
-endif
-endif
-
-ACLOCAL_AMFLAGS = -I m4
-
-SUBDIRS = src examples sounds $(PYTHONDIR) $(SWIGDIR) $(DOC) tests
-EXTRA_DIST = bootstrap VERSION
-
-docs:
- cd doc && make update-docs && cd ..
-
-doc-devel:
- cd doc && make doc-devel && cd ..
-
-doc-user:
- cd doc && make doc-user && cd ..
-
-doc-examples:
- cd doc && make doc-examples && cd ..
-
-install-pkgconfig:
- $(mkinstalldirs) "$(DESTDIR)$(libdir)/pkgconfig"
- $(INSTALL_DATA) aubio.pc "$(DESTDIR)$(libdir)/pkgconfig/aubio.pc"
-
-uninstall-pkgconfig:
- $(RM) "$(DESTDIR)$(libdir)/pkgconfig/aubio.pc"
- -rmdir "$(DESTDIR)$(libdir)/pkgconfig"
-
-install-data-hook: install-pkgconfig
-uninstall-hook: uninstall-pkgconfig
-
-lcov: all
- mkdir -p $(top_builddir)/lcov
- lcov --directory $(top_builddir) --output-file $(top_builddir)/lcov/aubio.info --compat-libtool --zerocounters
- cd tests/python && ./run_all_tests -v || echo "some tests failed"
- lcov --directory $(top_builddir) --output-file $(top_builddir)/lcov/aubio.info --compat-libtool --capture
- genhtml --output-directory $(top_builddir)/lcov $(top_builddir)/lcov/aubio.info
--- a/bootstrap
+++ /dev/null
@@ -1,3 +1,0 @@
-#!/bin/sh
-
-autoreconf -f -i
--- a/configure.ac
+++ /dev/null
@@ -1,314 +1,0 @@
-dnl Process this file with autoconf to produce a configure script
-
-dnl Init autoconf
-AC_INIT(src/aubio.h)
-
-AC_CONFIG_MACRO_DIR([m4])
-
-dnl Package name and version
-PACKAGE=aubio
-. $srcdir/VERSION
-AUBIO_VERSION=${AUBIO_MAJOR_VERSION}.${AUBIO_MINOR_VERSION}.${AUBIO_PATCH_VERSION}${AUBIO_VERSION_STATUS}
-VERSION=${AUBIO_VERSION}
-
-dnl Shared library version
-SHARED_VERSION_INFO=${LIBAUBIO_LT_CUR}:${LIBAUBIO_LT_REV}:${LIBAUBIO_LT_AGE}
-AC_SUBST(SHARED_VERSION_INFO)
-
-dnl Init automake
-AM_INIT_AUTOMAKE(${PACKAGE}, ${VERSION})
-
-dnl Enable silent rules, use with make V=0
-dnl AM_SILENT_RULES
-
-dnl Maintainer mode
-AM_MAINTAINER_MODE
-
-dnl Guess the host
-AC_CANONICAL_HOST
-
-dnl Check for programs
-AC_PROG_CC
-AM_PROG_CC_C_O dnl compiling with per-target flag
-if test "$ac_cv_prog_cc" = "no" ; then
- AC_MSG_ERROR([*** No C compiler found !])
-fi
-AC_PROG_INSTALL
-
-AUBIO_CFLAGS=
-
-AC_CHECK_LIB(m, floorf)
-AUBIO_LIBS="-lm"
-
-dnl Enable double precision (no)
-AC_ARG_ENABLE(double,
- AC_HELP_STRING([--enable-double],[compile in double precision [[default=no]]]),
- with_double_precision="yes",
- with_double_precision="no")
-if test "$with_double_precision" = "yes"
-then
- AC_DEFINE(HAVE_AUBIO_DOUBLE,1,[Define to enable double precision])
-fi
-
-dnl Enable debugging (no)
-AC_ARG_ENABLE(debug,
- AC_HELP_STRING([--enable-debug],[compile in debug mode [[default=no]]]),
- with_debug="yes",
- with_debug="no")
-if test "$with_debug" = "yes"
-then
- AC_DEFINE(DEBUG,1,[Define to enable debug])
- AUBIO_CFLAGS="$AUBIO_CFLAGS -g"
-fi
-
-dnl Enable full warnings (yes)
-AC_ARG_ENABLE(warnings,
- AC_HELP_STRING([--enable-warnings],[compile with all gcc warnings [[default=yes]]]),
- with_warnme="no",
- with_warnme="yes")
-if test "$with_warnme" = "yes"
-then
- dnl Check for -Wextra support to allow compilation on gcc <= 3.4
- AC_CACHE_CHECK([for -Wextra option to $CC], ac_cv_cc_wextra,
- [old_CFLAGS="$CFLAGS"
- CFLAGS="$CFLAGS -Wextra"
- AC_COMPILE_IFELSE([void foo (void) {}],
- ac_cv_cc_wextra=yes, ac_cv_cc_wextra=no)
- CFLAGS="$old_CFLAGS"
- ])
- if test "$ac_cv_cc_wextra" = "yes"
- then
- AUBIO_CFLAGS="$AUBIO_CFLAGS -Wall -Wextra"
- else
- AUBIO_CFLAGS="$AUBIO_CFLAGS -Wall"
- fi
-fi
-
-dnl fail on compilation warnings
-AC_ARG_ENABLE(errorfail,
- AC_HELP_STRING([--enable-errorfail],[fail on compilation warnings [[default=no]]]),
- AUBIO_CFLAGS="$AUBIO_CFLAGS -Werror -Wmissing-prototypes -Wmissing-declarations -Wno-unused-parameter",
- with_errorfail="no")
-
-dnl add gcov/lcov profiling and coverage flags
-AC_ARG_ENABLE(lcov,
- AC_HELP_STRING([--enable-lcov],[compile with gcov/lcov profiling flags [[default=no]]]),
- AUBIO_CFLAGS="$AUBIO_CFLAGS -fprofile-arcs -ftest-coverage",
- with_lcov="no")
-
-dnl Check for libtool
-AC_LIBTOOL_DLOPEN
-dnl AC_DISABLE_STATIC
-dnl allow cross compiling
-AC_LIBTOOL_WIN32_DLL
-AC_PROG_LIBTOOL
-
-AC_CONFIG_HEADERS(src/config.h)
-AC_CONFIG_FILES(aubio.pc)
-
-AM_CONDITIONAL(MINGW, false)
-AM_CONDITIONAL(DARWIN, false)
-case "${host}" in
-*mingw* | *cygwin*)
- mingw32_support="yes"
- AC_CHECK_HEADER(windows.h)
- AM_CONDITIONAL(MINGW, true)
- LDFLAGS="$LDFLAGS -no-undefined"
- ;;
-*darwin* | *rhapsody* | *macosx*)
- AC_ISC_POSIX
- AM_CONDITIONAL(DARWIN, true)
- ;;
-*)
- AC_ISC_POSIX
- ;;
-esac
-
-dnl Check for required libraries
-AC_CHECK_LIB(pthread, pthread_create)
-
-dnl Check for header files
-AC_CHECK_HEADERS([string.h stdlib.h stdio.h math.h limits.h errno.h stdarg.h unistd.h signal.h],,)
-AC_ARG_ENABLE(complex,
- AC_HELP_STRING([--enable-complex],[compile with complex.h [[default=auto]]]),
- [with_complex=$enableval],
- with_complex="no")
-if test "$with_complex" = "yes"; then
- AC_CHECK_HEADERS(complex.h,,AC_MSG_WARN([Ouch! missing complex.h header]))
-fi
-
-dnl Check for __VAR_ARGS__ support
-AC_CACHE_CHECK(for C99 __VA_ARGS__ macro,
- ac_cv_varargs_macros,
-AC_TRY_COMPILE([
- #include <stdio.h>
- #define AUBIO_ERR(...) fprintf(stderr, __VA_ARGS__)
-],
-[
- AUBIO_ERR("%s\n", "ERR");
-],
- ac_cv_varargs_macros=yes,
- ac_cv_varargs_macros=no)
-)
-if test "$ac_cv_varargs_macros" = "yes"; then
- AC_DEFINE(HAVE_C99_VARARGS_MACROS, 1,
- [Defined when c99 style varargs macros are supported])
-fi
-
-AC_ARG_ENABLE(sndfile,
- AC_HELP_STRING([--enable-sndfile],[compile with sndfile [[default=auto]]]),
- [with_sndfile=$enableval],
- with_sndfile="yes")
-if test "$with_sndfile" = "yes"; then
- PKG_CHECK_MODULES(SNDFILE, sndfile >= 1.0.4, HAVE_SNDFILE=1, HAVE_SNDFILE=0)
- if test "${HAVE_SNDFILE}" = "1"; then
- AC_DEFINE(HAVE_SNDFILE,1,[Define to enable libsndfile support])
- fi
-fi
-
-dnl Enable samplerate support (auto)
-AC_ARG_ENABLE(samplerate,
- AC_HELP_STRING([--enable-samplerate],[compile with samplerate [[default=auto]]]),
- [with_samplerate=$enableval],
- with_samplerate="yes")
-if test "$with_samplerate" = "yes"; then
- PKG_CHECK_MODULES(SAMPLERATE, samplerate >= 0.0.15, HAVE_SAMPLERATE=1,
- HAVE_SAMPLERATE=0)
- if test "${HAVE_SAMPLERATE}" = "1"; then
- AC_DEFINE(HAVE_SAMPLERATE,1,[Define to enable libsamplerate support])
- fi
-fi
-
-dnl Check for fftw3 (required)
-dnl if we compile in double precsion, default to fftw3, else fftw3f
-
-AC_ARG_ENABLE(fftw3,
- AC_HELP_STRING([--enable-fftw3],[compile with fftw3 [[default=auto]]]),
- [with_fftw3=$enableval],
- with_fftw3="yes")
-
-if test "$with_double_precision" = "yes"; then
- default_fftw3f="no"
-else
- default_fftw3f=$with_fftw3
-fi
-
-AC_ARG_ENABLE(fftw3f,
- AC_HELP_STRING([--enable-fftw3f],[compile with fftw3f [[default=auto]]]),
- [with_fftw3f=$enableval],
- [with_fftw3f=$default_fftw3f])
-
-# check if we have fftw3f
-if test "$with_fftw3f" = "yes"; then
- PKG_CHECK_MODULES(FFTWLIB, fftw3f >= 3.0.0, HAVE_FFTW3F=1, HAVE_FFTW3F=0)
-else
-# check if we have fftw3
-if test "$with_fftw3" = "yes"; then
- PKG_CHECK_MODULES(FFTWLIB, fftw3 >= 3.0.0, HAVE_FFTW3=1, HAVE_FFTW3=0)
-fi
-fi
-
-if test "${HAVE_FFTW3}" = "1"; then
- AC_DEFINE(HAVE_FFTW3,1,[Define to enable fftw3 support])
-fi
-if test "${HAVE_FFTW3F}" = "1"; then
- AC_DEFINE(HAVE_FFTW3,1,[Define to enable fftw3 support])
- AC_DEFINE(HAVE_FFTW3F,1,[Define to enable fftw3f support])
-fi
-
-dnl Enable jack support (auto)
-AC_ARG_ENABLE(jack,
- AC_HELP_STRING([--enable-jack],[compile with jack [[default=auto]]]),
- [with_jack=$enableval],
- with_jack="yes")
-if test "$with_jack" = "yes"
-then
- PKG_CHECK_MODULES(JACK, jack >= 0.15.0, HAVE_JACK=1, HAVE_JACK=0)
- if test "${HAVE_JACK}" = "1"; then
- AC_DEFINE(HAVE_JACK,1,[Define to enable jack support])
- fi
-fi
-
-dnl Enable lash support
-AC_ARG_ENABLE(lash,
- AC_HELP_STRING([--enable-lash],[compile with lash [[default=auto]]]),
- [with_lash=$enableval],
- with_lash="yes")
-if test "$with_lash" = "yes"
-then
- PKG_CHECK_MODULES(LASH, lash-1.0 >= 0.5.0, HAVE_LASH=1, HAVE_LASH=0)
- if test "${HAVE_LASH}" = "1"; then
- AC_DEFINE(HAVE_LASH,1,[Define to enable lash support])
- fi
-fi
-
-dnl Enable unit tests
-AC_ARG_ENABLE(testprogs,
- AC_HELP_STRING([--enable-testprogs],[compile test programs [[default=yes]]]),
- [with_testprogs=$enableval],
- with_testprogs="yes")
-AM_CONDITIONAL(COMPILE_TESTS,test "${with_testprogs}" != "no")
-
-AC_SUBST(AUBIO_CFLAGS)
-AC_SUBST(AUBIO_LIBS)
-
-dnl Check for swig and python
-dnl should check for swig version and python headers
-AC_PATH_PROG(SWIG,swig,no)
-AM_CONDITIONAL(SWIGFOUND, test "${SWIG}" != "no")
-AM_PATH_PYTHON
-AM_CONDITIONAL(PYTHONFOUND, test "${PYTHON}" != "no")
-
-dnl Check for docbook-to-man
-AC_PATH_PROG(DOCBOOK_TO_MAN,docbook-to-man,no)
-AM_CONDITIONAL(DOCBOOKFOUND, test "${DOCBOOK_TO_MAN}" != "no")
-
-dnl Create Makefiles
-AC_OUTPUT([
- Makefile
- src/Makefile
- examples/Makefile
- tests/Makefile
- tests/src/Makefile
- sounds/Makefile
- swig/Makefile
- python/Makefile
- python/aubio/Makefile
- doc/Makefile
- ])
-
-dnl Print summary
-echo
-echo "**************************************************************"
-echo "Summary:"
-if test "${HAVE_FFTW3F}" = "1"; then
- echo "FFT: using fftw3f"
-else
-if test "${HAVE_FFTW3}" = "1"; then
- echo "Fft: using fftw3"
-else
- echo "Fft: using ooura"
-fi
-fi
-if test "${HAVE_SNDFILE}" = "1"; then
- echo "Libsndfile: yes"
-else
- echo "Libsndfile: no"
-fi
-if test "${HAVE_SAMPLERATE}" = "1"; then
- echo "Libsamplerate: yes"
-else
- echo "Libsamplerate: no"
-fi
-if test "${HAVE_JACK}" = "1"; then
- echo "JACK: yes"
-else
- echo "JACK: no"
-fi
-if test "${HAVE_LASH}" = "1"; then
- echo "Lash: yes"
-else
- echo "Lash: no"
-fi
-echo "**************************************************************"
-echo Configuration completed successfully. Type \'make\' to build ${PACKAGE}
--- a/doc/Makefile.am
+++ /dev/null
@@ -1,52 +1,0 @@
-man_MANS = \
- aubionotes.1 \
- aubioonset.1 \
- aubiocut.1 \
- aubiopitch.1 \
- aubiotrack.1 \
- aubiomfcc.1
-
-EXTRA_DIST = \
- devel.cfg \
- examples.cfg \
- user.cfg \
- aubio.css \
- aubionotes.sgml \
- aubioonset.sgml \
- aubiotrack.sgml \
- aubiomfcc.sgml \
- aubiopitch.sgml \
- aubiocut.sgml \
- $(man_MANS)
-
-CLEANFILES = $(man_MANS)
-
-all:
-
-update-docs: doc-devel
-
-doc-clean:
- -rm -rf devel
-
-PROJECT_NUMBER = `source $(top_srcdir)/VERSION; echo $$AUBIO_MAJOR_VERSION.$$AUBIO_MINOR_VERSION.$$AUBIO_PATCH_VERSION$$AUBIO_VERSION_STATUS`
-maintainer-clean-local: doc-clean
-
-doc-devel:
- (echo PROJECT_NUMBER = $(PROJECT_NUMBER) ; cat $(srcdir)/devel.cfg) | doxygen -
-
-doc-user:
- (echo PROJECT_NUMBER = $(PROJECT_NUMBER) ; cat $(srcdir)/user.cfg) | doxygen -
-
-doc-examples:
- (echo PROJECT_NUMBER = $(PROJECT_NUMBER) ; cat $(srcdir)/examples.cfg) | doxygen -
-
-.sgml.1:
- docbook-to-man $< > $*.1
-
-.sgml.html:
- docbook2html $< && mv index.html $*.html
-
-clean:
- rm -rf devel user examples
-
-distclean-hook: clean
--- a/examples/Makefile.am
+++ /dev/null
@@ -1,32 +1,0 @@
-# global flags
-AM_CFLAGS = -DAUBIO_PREFIX=\"$(prefix)\" -DPACKAGE=\"@PACKAGE@\" -I$(top_srcdir)/src @AUBIO_CFLAGS@ @LASH_CFLAGS@ @SNDFILE_CFLAGS@ @JACK_CFLAGS@
-AM_LDFLAGS = -L$(top_builddir)/src -laubio @AUBIO_LIBS@ @LASH_LIBS@
-
-# add your programs to this list
-bin_PROGRAMS = \
- aubioonset \
- aubiotrack \
- aubionotes \
- aubiomfcc
-
-noinst_PROGRAMS = \
- aubiopitch \
- aubioquiet
-
-EXTRA_DIST = utils.h sndfileio.h jackio.h
-
-# optionally add sources file for these programs
-COMMON_SOURCE_FILES = sndfileio.c jackio.c utils.c
-aubioonset_SOURCES = aubioonset.c $(COMMON_SOURCE_FILES)
-aubionotes_SOURCES = aubionotes.c $(COMMON_SOURCE_FILES)
-aubiotrack_SOURCES = aubiotrack.c $(COMMON_SOURCE_FILES)
-aubiopitch_SOURCES = aubiopitch.c $(COMMON_SOURCE_FILES)
-aubioquiet_SOURCES = aubioquiet.c $(COMMON_SOURCE_FILES)
-aubiomfcc_SOURCES = aubiomfcc.c $(COMMON_SOURCE_FILES)
-
-aubioonset_LDADD = @SNDFILE_LIBS@ @JACK_LIBS@
-aubionotes_LDADD = @SNDFILE_LIBS@ @JACK_LIBS@
-aubiotrack_LDADD = @SNDFILE_LIBS@ @JACK_LIBS@
-aubiopitch_LDADD = @SNDFILE_LIBS@ @JACK_LIBS@
-aubioquiet_LDADD = @SNDFILE_LIBS@ @JACK_LIBS@
-aubiomfcc_LDADD = @SNDFILE_LIBS@ @JACK_LIBS@
--- a/examples/aubiomfcc.c
+++ b/examples/aubiomfcc.c
@@ -65,7 +65,7 @@
*/
uint_t coef_cnt;
- if (output_filename == NULL) {
+ if (sink_uri == NULL) {
outmsg("%f\t",frames*overlap_size/(float)samplerate);
for (coef_cnt = 0; coef_cnt < n_coefs; coef_cnt++) {
outmsg("%f ", fvec_read_sample (mfcc_out, coef_cnt) );
--- a/examples/aubioonset.c
+++ b/examples/aubioonset.c
@@ -26,7 +26,6 @@
fvec_t *onset;
static int aubio_process(smpl_t **input, smpl_t **output, int nframes) {
- unsigned int i; /*channels*/
unsigned int j; /*frames*/
for (j=0;j<(unsigned)nframes;j++) {
if(usejack) {
--- a/examples/aubiotrack.c
+++ b/examples/aubiotrack.c
@@ -56,7 +56,7 @@
}
static void process_print (void) {
- if (output_filename == NULL) {
+ if (sink_uri == NULL) {
if (istactus) {
outmsg("%f\n",((smpl_t)(frames*overlap_size)+(istactus-1.)*overlap_size)/(smpl_t)samplerate);
}
--- a/examples/utils.c
+++ b/examples/utils.c
@@ -41,10 +41,8 @@
#endif /* HAVE_LASH */
/* settings */
-const char *output_filename = NULL;
-const char *input_filename = NULL;
-const char *onset_filename =
- AUBIO_PREFIX "/share/sounds/" PACKAGE "/woodblock.aiff";
+const char *sink_uri = NULL;
+const char *source_uri = NULL;
int frames = 0;
int verbose = 0;
int usejack = 0;
@@ -62,15 +60,9 @@
uint_t overlap_size = 256; //512;
uint_t samplerate = 44100;
+aubio_source_t *this_source = NULL;
+aubio_sink_t *this_sink = NULL;
-#ifdef HAVE_SNDFILE
-aubio_sndfile_t *file = NULL;
-aubio_sndfile_t *fileout = NULL;
-#else
-void *file = NULL;
-void *fileout = NULL;
-#endif
-
fvec_t *ibuf;
fvec_t *obuf;
fvec_t *woodblock;
@@ -135,10 +127,10 @@
next_option = getopt_long (argc, argv, options, long_options, NULL);
switch (next_option) {
case 'o':
- output_filename = optarg;
+ sink_uri = optarg;
break;
case 'i':
- input_filename = optarg;
+ source_uri = optarg;
break;
case 'h': /* help */
usage (stdout, 0);
@@ -182,19 +174,18 @@
}
while (next_option != -1);
- if (input_filename != NULL) {
- debug ("Input file : %s\n", input_filename);
- } else if (input_filename != NULL && output_filename != NULL) {
- debug ("Input file : %s\n", input_filename);
- debug ("Output file : %s\n", output_filename);
+ if (source_uri != NULL) {
+ debug ("Input file : %s\n", source_uri);
+ } else if (source_uri != NULL && sink_uri != NULL) {
+ debug ("Input file : %s\n", source_uri);
+ debug ("Output file : %s\n", sink_uri);
} else {
#if HAVE_JACK
debug ("Jack input output\n");
usejack = 1;
#else
- debug
- ("Error: Could not switch to jack mode\n aubio was compiled without jack support\n");
- exit (1);
+ errmsg("Error: no arguments given (and no available audio input)\n");
+ usage ( stderr, 1 );
#endif
}
@@ -201,30 +192,28 @@
return 0;
}
-#ifdef HAVE_SNDFILE
-
void
examples_common_init (int argc, char **argv)
{
- uint_t found_wood = 0;
-
- aubio_sndfile_t *onsetfile = NULL;
/* parse command line arguments */
parse_args (argc, argv);
if (!usejack) {
debug ("Opening files ...\n");
- file = new_aubio_sndfile_ro (input_filename);
- if (file == NULL) {
- outmsg ("Could not open input file %s.\n", input_filename);
+ this_source = new_aubio_source ((char_t*)source_uri, 0, overlap_size);
+ if (this_source == NULL) {
+ outmsg ("Could not open input file %s.\n", source_uri);
exit (1);
}
- if (verbose)
- aubio_sndfile_info (file);
- samplerate = aubio_sndfile_samplerate (file);
- if (output_filename != NULL)
- fileout = new_aubio_sndfile_wo (file, output_filename);
+ samplerate = aubio_source_get_samplerate(this_source);
+ if (sink_uri != NULL) {
+ this_sink = new_aubio_sink ((char_t*)sink_uri, samplerate);
+ if (this_sink == NULL) {
+ outmsg ("Could not open output file %s.\n", sink_uri);
+ exit (1);
+ }
+ }
}
#ifdef HAVE_LASH
else {
@@ -245,20 +234,7 @@
#endif /* HAVE_LASH */
woodblock = new_fvec (overlap_size);
- if (output_filename || usejack) {
- /* dummy assignement to keep egcs happy */
- found_wood = (onsetfile = new_aubio_sndfile_ro (onset_filename)) ||
- (onsetfile = new_aubio_sndfile_ro ("sounds/woodblock.aiff")) ||
- (onsetfile = new_aubio_sndfile_ro ("../sounds/woodblock.aiff"));
- if (onsetfile == NULL) {
- outmsg ("Could not find woodblock.aiff\n");
- exit (1);
- }
- }
- if (onsetfile) {
- /* read the output sound once */
- aubio_sndfile_read_mono (onsetfile, overlap_size, woodblock);
- }
+ //TODO create woodblock sound
ibuf = new_fvec (overlap_size);
obuf = new_fvec (overlap_size);
@@ -265,26 +241,12 @@
}
-#else /* HAVE_SNDFILE */
-
void
-examples_common_init (int argc, char **argv)
-{
- outmsg ("Error, compiled without sndfile, nothing to do for now!\n");
-}
-
-
-#endif /* HAVE_SNDFILE */
-
-
-void
examples_common_del (void)
{
-#if HAVE_SNDFILE
del_fvec (ibuf);
del_fvec (obuf);
del_fvec (woodblock);
-#endif
aubio_cleanup ();
}
@@ -292,12 +254,12 @@
aubio_jack_t *jack_setup;
#endif
-#if HAVE_SNDFILE
-
void
examples_common_process (aubio_process_func_t process_func,
aubio_print_func_t print)
{
+
+ uint_t read = 0;
if (usejack) {
#if HAVE_JACK
@@ -320,36 +282,24 @@
frames = 0;
- while ((signed) overlap_size ==
- aubio_sndfile_read_mono (file, overlap_size, ibuf)) {
+ do {
+ aubio_source_do (this_source, ibuf, &read);
process_func (&ibuf->data, &obuf->data, overlap_size);
print ();
- if (output_filename != NULL) {
- aubio_sndfile_write (fileout, overlap_size, &obuf);
+ if (this_sink) {
+ aubio_sink_do (this_sink, obuf, overlap_size);
}
frames++;
- }
+ } while (read == overlap_size);
debug ("Processed %d frames of %d samples.\n", frames, buffer_size);
flush_process (process_func, print);
- del_aubio_sndfile (file);
+ del_aubio_source (this_source);
+ del_aubio_sink (this_sink);
- if (output_filename != NULL)
- del_aubio_sndfile (fileout);
-
}
}
-
-#else /* HAVE_SNDFILE */
-
-void
-examples_common_process (aubio_process_func_t process_func,
- aubio_print_func_t print)
-{
-}
-
-#endif /* HAVE_SNDFILE */
void
flush_process (aubio_process_func_t process_func, aubio_print_func_t print)
--- a/examples/utils.h
+++ b/examples/utils.h
@@ -64,7 +64,7 @@
void send_noteon (int pitch, int velo);
-extern const char *output_filename;
+extern const char *sink_uri;
extern char_t * onset_mode;
extern smpl_t threshold;
extern smpl_t silence;
--- a/examples/wscript_build
+++ b/examples/wscript_build
@@ -1,19 +1,19 @@
# vim:set syntax=python:
# build examples
-utilsio = ctx.new_task_gen(name = 'utilsio', features = 'c',
- includes = '../src',
- source = ['utils.c', 'jackio.c'],
- uselib = ['LASH', 'JACK'],
- target = 'utilsio')
+utilsio = bld(
+ name = 'utilsio',
+ features = 'c',
+ includes = '../src',
+ source = ['utils.c', 'jackio.c'],
+ uselib = ['LASH', 'JACK'],
+ target = 'utilsio')
# loop over all *.c filenames in examples to build them all
-for target_name in ctx.path.ant_glob('*.c', excl = ['utils.c', 'jackio.c']):
- ctx.new_task_gen(features = 'c cprogram',
- add_objects = 'utilsio',
+for source_file in ctx.path.ant_glob('*.c', excl = ['utils.c', 'jackio.c']):
+ bld.program(features = 'c cprogram',
includes = '../src',
- uselib = ['LASH', 'JACK', 'SNDFILE'],
- use = 'aubio',
- source = target_name,
- # program name is filename.c without the .c
- target = str(target_name).split('.')[0])
+ use = ['aubio', 'LASH', 'JACK', 'SNDFILE', 'utilsio'],
+ source = str(source_file),
+ target = str(source_file).split('.')[0]
+ )
--- a/interfaces/python/README
+++ /dev/null
@@ -1,5 +1,0 @@
-This module wraps the aubio library for python using the numpy module.
-
-http://docs.python.org/c-api/index.html
-
-http://docs.scipy.org/doc/numpy/reference/c-api.html
--- a/interfaces/python/a_weighting_test_simple.expected
+++ /dev/null
@@ -1,2 +1,0 @@
- 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 5.00000000e-01 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00
- 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 1.27870563e-01 2.58244342e-01 1.18719361e-01 -4.02623805e-02 -5.61812129e-02 -5.24739734e-02 -4.72329276e-02 -4.23394349e-02 -3.79219586e-02 -3.39473148e-02 -3.03724479e-02 -2.71574847e-02 -2.42664433e-02 -2.16669285e-02 -1.93297810e-02 -1.72287543e-02 -1.53402241e-02 -1.36429261e-02 -1.21177207e-02 -1.07473802e-02
--- a/interfaces/python/aubio-types.h
+++ /dev/null
@@ -1,49 +1,0 @@
-#include <Python.h>
-#include <structmember.h>
-#define NO_IMPORT_ARRAY
-#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
-#include <numpy/arrayobject.h>
-#define AUBIO_UNSTABLE 1
-#include <aubio.h>
-
-#define Py_default_vector_length 1024
-#define Py_default_vector_height 1
-
-#define Py_aubio_default_samplerate 44100
-
-#if HAVE_AUBIO_DOUBLE
-#error "Ouch! Python interface for aubio has not been much tested yet."
-#define AUBIO_NPY_SMPL NPY_DOUBLE
-#else
-#define AUBIO_NPY_SMPL NPY_FLOAT
-#endif
-
-// special python type for cvec
-typedef struct
-{
- PyObject_HEAD
- cvec_t * o;
- uint_t length;
- uint_t channels;
-} Py_cvec;
-extern PyTypeObject Py_cvecType;
-
-// defined in aubio-proxy.c
-extern PyObject *PyAubio_CFvecToArray (fvec_t * self);
-extern fvec_t *PyAubio_ArrayToCFvec (PyObject * self);
-
-extern Py_cvec *PyAubio_CCvecToPyCvec (cvec_t * self);
-extern cvec_t *PyAubio_ArrayToCCvec (PyObject *input);
-
-extern PyObject *PyAubio_CFmatToArray (fmat_t * self);
-extern fmat_t *PyAubio_ArrayToCFmat (PyObject *input);
-
-// hand written wrappers
-extern PyTypeObject Py_filterType;
-
-extern PyTypeObject Py_filterbankType;
-
-extern PyTypeObject Py_fftType;
-
-extern PyTypeObject Py_pvocType;
-
--- a/interfaces/python/aubio/__init__.py
+++ /dev/null
@@ -1,9 +1,0 @@
-import numpy
-from _aubio import *
-
-class fvec(numpy.ndarray):
-
- def __new__(self, length = 1024, **kwargs):
- if type(length) == type([]):
- return numpy.array(length, dtype='float32', **kwargs)
- return numpy.zeros(length, dtype='float32', **kwargs)
--- a/interfaces/python/aubioinput.py
+++ /dev/null
@@ -1,141 +1,0 @@
-#! /usr/bin/python
-
-import pygst
-pygst.require('0.10')
-import gst
-import gobject
-gobject.threads_init ()
-
-def gst_buffer_to_numpy_array(buffer, chan):
- import numpy
- samples = numpy.frombuffer(buffer.data, dtype=numpy.float32)
- if chan == 1:
- return samples.T
- else:
- samples.resize([len(samples)/chan, chan])
- return samples.T
-
-class AubioSink(gst.BaseSink):
- _caps = gst.caps_from_string('audio/x-raw-float, \
- rate=[ 1, 2147483647 ], \
- channels=[ 1, 2147483647 ], \
- endianness={ 1234, 4321 }, \
- width=32')
-
- __gsttemplates__ = (
- gst.PadTemplate ("sink",
- gst.PAD_SINK,
- gst.PAD_ALWAYS,
- _caps),
- )
-
- def __init__(self, name, process):
- self.__gobject_init__()
- self.set_name(name)
- self.process = process
- self.adapter = gst.Adapter()
- self.set_property('sync', False)
- self.pos = 0
-
- def set_property(self, name, value):
- if name == 'hopsize':
- # blocksize is in byte, convert from hopsize
- from struct import calcsize
- self.set_property('blocksize', value * calcsize('f'))
- else:
- super(gst.BaseSink, self).set_property(name, value)
-
- def do_render(self, buffer):
- blocksize = self.get_property('blocksize')
- caps = buffer.get_caps()
- chan = caps[0]['channels']
- self.adapter.push(buffer)
- while self.adapter.available() >= blocksize:
- block = self.adapter.take_buffer(blocksize)
- v = gst_buffer_to_numpy_array(block, chan)
- if self.process:
- self.process(v, self.pos)
- self.pos += 1
- remaining = self.adapter.available()
- if remaining < blocksize and remaining > 0:
- block = self.adapter.take_buffer(remaining)
- v = gst_buffer_to_numpy_array(block, chan)
- if self.process:
- self.process(v, self.pos)
- self.pos += 1
- return gst.FLOW_OK
-
-gobject.type_register(AubioSink)
-
-class aubioinput(gst.Bin):
-
- ret = 0
-
- def __init__(self, uri, process = None, hopsize = 512,
- caps = None):
- if uri.startswith('/'):
- from urllib import quote
- uri = 'file://'+quote(uri)
- src = gst.element_factory_make('uridecodebin')
- src.set_property('uri', uri)
- src.connect('pad-added', self.source_pad_added_cb)
- conv = gst.element_factory_make('audioconvert')
- self.conv = conv
- rsmpl = gst.element_factory_make('audioresample')
- capsfilter = gst.element_factory_make('capsfilter')
- if caps:
- capsfilter.set_property('caps', gst.caps_from_string(caps))
- sink = AubioSink("AubioSink", process = process)
- sink.set_property('hopsize', hopsize) # * calcsize('f'))
-
- self.pipeline = gst.Pipeline()
-
- self.bus = self.pipeline.get_bus()
- self.bus.add_signal_watch()
- self.bus.connect('message', self.on_eos)
-
- self.apad = conv.get_pad('sink')
-
- self.pipeline.add(src, conv, rsmpl, capsfilter, sink)
-
- gst.element_link_many(conv, rsmpl, capsfilter, sink)
-
- self.mainloop = gobject.MainLoop()
- self.pipeline.set_state(gst.STATE_PLAYING)
-
- def run(self):
- self.mainloop.run()
- return self.ret
-
- def source_pad_added_cb(self, src, pad):
- name = pad.get_caps()[0].get_name()
- if name == 'audio/x-raw-float' or name == 'audio/x-raw-int':
- pad.link(self.conv.get_pad("sink"))
-
- def source_pad_removed_cb(self, src, pad):
- pad.unlink(self.conv.get_pad("sink"))
-
- def on_eos(self, bus, msg):
- if msg.type == gst.MESSAGE_EOS:
- self.bus.remove_signal_watch()
- self.pipeline.set_state(gst.STATE_PAUSED)
- self.mainloop.quit()
- elif msg.type == gst.MESSAGE_ERROR:
- print "ERROR", msg.parse_error()
- self.bus.remove_signal_watch()
- self.pipeline.set_state(gst.STATE_PAUSED)
- self.mainloop.quit()
- self.ret = 1 # set return value to 1 in case of error
-
-if __name__ == '__main__':
- import sys
- if len(sys.argv) < 2:
- print "Usage: %s <filename>" % sys.argv[0]
- sys.exit(1)
- for filename in sys.argv[1:]:
- peak = [0.] # use a mutable
- def process(buf, hop):
- peak[0] = max( peak[0], abs(buf.max()) )
- a = aubioinput(filename, process = process, hopsize = 512)
- if a.run() == 0: # only display the results if no
- print "Finished reading %s, peak value is %f" % (filename, max(peak))
--- a/interfaces/python/aubiomodule.c
+++ /dev/null
@@ -1,161 +1,0 @@
-#include <Python.h>
-#define PY_ARRAY_UNIQUE_SYMBOL PyArray_API
-#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
-#include <numpy/arrayobject.h>
-
-#include "aubio-types.h"
-#include "generated/aubio-generated.h"
-
-static char Py_alpha_norm_doc[] = "compute alpha normalisation factor";
-
-static PyObject *
-Py_alpha_norm (PyObject * self, PyObject * args)
-{
- PyObject *input;
- fvec_t *vec;
- smpl_t alpha;
- PyObject *result;
-
- if (!PyArg_ParseTuple (args, "Of:alpha_norm", &input, &alpha)) {
- return NULL;
- }
-
- if (input == NULL) {
- return NULL;
- }
-
- vec = PyAubio_ArrayToCFvec (input);
-
- if (vec == NULL) {
- return NULL;
- }
-
- // compute the function
- result = Py_BuildValue ("f", fvec_alpha_norm (vec, alpha));
- if (result == NULL) {
- return NULL;
- }
-
- return result;
-}
-
-static char Py_zero_crossing_rate_doc[] = "compute zero crossing rate";
-
-static PyObject *
-Py_zero_crossing_rate (PyObject * self, PyObject * args)
-{
- PyObject *input;
- fvec_t *vec;
- PyObject *result;
-
- if (!PyArg_ParseTuple (args, "O:zero_crossing_rate", &input)) {
- return NULL;
- }
-
- if (input == NULL) {
- return NULL;
- }
-
- vec = PyAubio_ArrayToCFvec (input);
-
- if (vec == NULL) {
- return NULL;
- }
-
- // compute the function
- result = Py_BuildValue ("f", aubio_zero_crossing_rate (vec));
- if (result == NULL) {
- return NULL;
- }
-
- return result;
-}
-
-static char Py_min_removal_doc[] = "compute zero crossing rate";
-
-static PyObject *
-Py_min_removal(PyObject * self, PyObject * args)
-{
- PyObject *input;
- fvec_t *vec;
-
- if (!PyArg_ParseTuple (args, "O:min_removal", &input)) {
- return NULL;
- }
-
- if (input == NULL) {
- return NULL;
- }
-
- vec = PyAubio_ArrayToCFvec (input);
-
- if (vec == NULL) {
- return NULL;
- }
-
- // compute the function
- fvec_min_removal (vec);
-
- // since this function does not return, we could return None
- //return Py_None;
- // however it is convenient to return the modified vector
- return (PyObject *) PyAubio_CFvecToArray(vec);
- // or even without converting it back to an array
- //Py_INCREF(vec);
- //return (PyObject *)vec;
-}
-
-static PyMethodDef aubio_methods[] = {
- {"alpha_norm", Py_alpha_norm, METH_VARARGS, Py_alpha_norm_doc},
- {"zero_crossing_rate", Py_zero_crossing_rate, METH_VARARGS,
- Py_zero_crossing_rate_doc},
- {"min_removal", Py_min_removal, METH_VARARGS, Py_min_removal_doc},
- {NULL, NULL} /* Sentinel */
-};
-
-static char aubio_module_doc[] = "Python module for the aubio library";
-
-PyMODINIT_FUNC
-init_aubio (void)
-{
- PyObject *m;
- int err;
-
- if ( (PyType_Ready (&Py_cvecType) < 0)
- || (PyType_Ready (&Py_filterType) < 0)
- || (PyType_Ready (&Py_filterbankType) < 0)
- || (PyType_Ready (&Py_fftType) < 0)
- || (PyType_Ready (&Py_pvocType) < 0)
- // generated objects
- || (generated_types_ready() < 0 )
- ) {
- return;
- }
-
- m = Py_InitModule3 ("_aubio", aubio_methods, aubio_module_doc);
-
- if (m == NULL) {
- return;
- }
-
- err = _import_array ();
-
- if (err != 0) {
- fprintf (stderr,
- "Unable to import Numpy C API from aubio module (error %d)\n", err);
- }
-
- Py_INCREF (&Py_cvecType);
- PyModule_AddObject (m, "cvec", (PyObject *) & Py_cvecType);
- Py_INCREF (&Py_filterType);
- PyModule_AddObject (m, "digital_filter", (PyObject *) & Py_filterType);
- Py_INCREF (&Py_filterbankType);
- PyModule_AddObject (m, "filterbank", (PyObject *) & Py_filterbankType);
- Py_INCREF (&Py_fftType);
- PyModule_AddObject (m, "fft", (PyObject *) & Py_fftType);
- Py_INCREF (&Py_pvocType);
- PyModule_AddObject (m, "pvoc", (PyObject *) & Py_pvocType);
-
- // generated objects
- add_generated_objects(m);
-}
--- a/interfaces/python/aubioproxy.c
+++ /dev/null
@@ -1,153 +1,0 @@
-#include "aubio-types.h"
-
-fvec_t *
-PyAubio_ArrayToCFvec (PyObject *input) {
- PyObject *array;
- fvec_t *vec;
- if (input == NULL) {
- PyErr_SetString (PyExc_ValueError, "input array is not a python object");
- goto fail;
- }
- // parsing input object into a Py_fvec
- if (PyArray_Check(input)) {
-
- // we got an array, convert it to an fvec
- if (PyArray_NDIM ((PyArrayObject *)input) == 0) {
- PyErr_SetString (PyExc_ValueError, "input array is a scalar");
- goto fail;
- } else if (PyArray_NDIM ((PyArrayObject *)input) > 1) {
- PyErr_SetString (PyExc_ValueError,
- "input array has more than one dimensions");
- goto fail;
- }
-
- if (!PyArray_ISFLOAT ((PyArrayObject *)input)) {
- PyErr_SetString (PyExc_ValueError, "input array should be float");
- goto fail;
- } else if (PyArray_TYPE ((PyArrayObject *)input) != AUBIO_NPY_SMPL) {
- PyErr_SetString (PyExc_ValueError, "input array should be float32");
- goto fail;
- } else {
- // input data type is float32, nothing else to do
- array = input;
- }
-
- // vec = new_fvec (vec->length);
- // no need to really allocate fvec, just its struct member
- vec = (fvec_t *)malloc(sizeof(fvec_t));
- vec->length = PyArray_SIZE ((PyArrayObject *)array);
- vec->data = (smpl_t *) PyArray_GETPTR1 ((PyArrayObject *)array, 0);
-
- } else if (PyObject_TypeCheck (input, &PyList_Type)) {
- PyErr_SetString (PyExc_ValueError, "does not convert from list yet");
- return NULL;
- } else {
- PyErr_SetString (PyExc_ValueError, "can only accept vector of float as input");
- return NULL;
- }
-
- return vec;
-
-fail:
- return NULL;
-}
-
-PyObject *
-PyAubio_CFvecToArray (fvec_t * self)
-{
- npy_intp dims[] = { self->length, 1 };
- return PyArray_SimpleNewFromData (1, dims, AUBIO_NPY_SMPL, self->data);
-}
-
-Py_cvec *
-PyAubio_CCvecToPyCvec (cvec_t * input) {
- Py_cvec *vec = (Py_cvec*) PyObject_New (Py_cvec, &Py_cvecType);
- vec->length = input->length;
- vec->o = input;
- Py_INCREF(vec);
- return vec;
-}
-
-cvec_t *
-PyAubio_ArrayToCCvec (PyObject *input) {
- if (PyObject_TypeCheck (input, &Py_cvecType)) {
- return ((Py_cvec*)input)->o;
- } else {
- PyErr_SetString (PyExc_ValueError, "input array should be float32");
- return NULL;
- }
-}
-
-PyObject *
-PyAubio_CFmatToArray (fmat_t * input)
-{
- PyObject *array = NULL;
- uint_t i;
- npy_intp dims[] = { input->length, 1 };
- PyObject *concat = PyList_New (0), *tmp = NULL;
- for (i = 0; i < input->height; i++) {
- tmp = PyArray_SimpleNewFromData (1, dims, AUBIO_NPY_SMPL, input->data[i]);
- PyList_Append (concat, tmp);
- Py_DECREF (tmp);
- }
- array = PyArray_FromObject (concat, AUBIO_NPY_SMPL, 2, 2);
- Py_DECREF (concat);
- return array;
-}
-
-fmat_t *
-PyAubio_ArrayToCFmat (PyObject *input) {
- PyObject *array;
- fmat_t *mat;
- uint_t i;
- if (input == NULL) {
- PyErr_SetString (PyExc_ValueError, "input array is not a python object");
- goto fail;
- }
- // parsing input object into a Py_fvec
- if (PyArray_Check(input)) {
-
- // we got an array, convert it to an fvec
- if (PyArray_NDIM ((PyArrayObject *)input) == 0) {
- PyErr_SetString (PyExc_ValueError, "input array is a scalar");
- goto fail;
- } else if (PyArray_NDIM ((PyArrayObject *)input) > 2) {
- PyErr_SetString (PyExc_ValueError,
- "input array has more than two dimensions");
- goto fail;
- }
-
- if (!PyArray_ISFLOAT ((PyArrayObject *)input)) {
- PyErr_SetString (PyExc_ValueError, "input array should be float");
- goto fail;
- } else if (PyArray_TYPE ((PyArrayObject *)input) != AUBIO_NPY_SMPL) {
- PyErr_SetString (PyExc_ValueError, "input array should be float32");
- goto fail;
- } else {
- // input data type is float32, nothing else to do
- array = input;
- }
-
- // no need to really allocate fvec, just its struct member
- mat = (fmat_t *)malloc(sizeof(fmat_t));
- mat->length = PyArray_DIM ((PyArrayObject *)array, 1);
- mat->height = PyArray_DIM ((PyArrayObject *)array, 0);
- mat->data = (smpl_t **)malloc(sizeof(smpl_t*) * mat->height);
- for (i=0; i< mat->height; i++) {
- mat->data[i] = (smpl_t*)PyArray_GETPTR1 ((PyArrayObject *)array, i);
- }
-
- } else if (PyObject_TypeCheck (input, &PyList_Type)) {
- PyErr_SetString (PyExc_ValueError, "can not convert list to fmat");
- return NULL;
- } else {
- PyErr_SetString (PyExc_ValueError, "can only accept matrix of float as input");
- return NULL;
- }
-
- return mat;
-
-fail:
- return NULL;
-}
-
--- a/interfaces/python/aubiowraphell.h
+++ /dev/null
@@ -1,90 +1,0 @@
-#include "aubio-types.h"
-
-#define AUBIO_DECLARE(NAME, PARAMS...) \
-typedef struct { \
- PyObject_HEAD \
- aubio_ ## NAME ## _t * o; \
- PARAMS; \
-} Py_## NAME;
-
-#define AUBIO_INIT(NAME, PARAMS... ) \
-static int \
-Py_ ## NAME ## _init (Py_ ## NAME * self, PyObject * args, PyObject * kwds) \
-{ \
- self->o = new_aubio_## NAME ( PARAMS ); \
- if (self->o == NULL) { \
- PyErr_SetString (PyExc_StandardError, "error creating object"); \
- return -1; \
- } \
-\
- return 0; \
-}
-
-#define AUBIO_DEL(NAME) \
-static void \
-Py_ ## NAME ## _del ( Py_ ## NAME * self) \
-{ \
- del_aubio_ ## NAME (self->o); \
- self->ob_type->tp_free ((PyObject *) self); \
-}
-
-#define AUBIO_MEMBERS_START(NAME) \
-static PyMemberDef Py_ ## NAME ## _members[] = {
-
-#define AUBIO_MEMBERS_STOP(NAME) \
- {NULL} \
-};
-
-#define AUBIO_METHODS(NAME) \
-static PyMethodDef Py_ ## NAME ## _methods[] = { \
- {NULL} \
-};
-
-
-#define AUBIO_TYPEOBJECT(NAME, PYNAME) \
-PyTypeObject Py_ ## NAME ## Type = { \
- PyObject_HEAD_INIT (NULL) \
- 0, \
- PYNAME, \
- sizeof (Py_ ## NAME), \
- 0, \
- (destructor) Py_ ## NAME ## _del, \
- 0, \
- 0, \
- 0, \
- 0, \
- 0, \
- 0, \
- 0, \
- 0, \
- 0, \
- (ternaryfunc)Py_ ## NAME ## _do, \
- 0, \
- 0, \
- 0, \
- 0, \
- Py_TPFLAGS_DEFAULT, \
- Py_ ## NAME ## _doc, \
- 0, \
- 0, \
- 0, \
- 0, \
- 0, \
- 0, \
- Py_ ## NAME ## _methods, \
- Py_ ## NAME ## _members, \
- 0, \
- 0, \
- 0, \
- 0, \
- 0, \
- 0, \
- (initproc) Py_ ## NAME ## _init, \
- 0, \
- Py_ ## NAME ## _new, \
-};
-
-// some more helpers
-#define AUBIO_NEW_VEC(name, type, lengthval) \
- name = (type *) PyObject_New (type, & type ## Type); \
- name->length = lengthval;
--- a/interfaces/python/build_linux
+++ /dev/null
@@ -1,9 +1,0 @@
-#! /bin/sh
-
-set -e
-set -x
-
-python setup.py clean build
-export PYTHONPATH=./build/lib.linux-x86_64-2.7/
-export LD_LIBRARY_PATH=../../build/src/
-./run_all_tests --verbose
--- a/interfaces/python/build_osx
+++ /dev/null
@@ -1,11 +1,0 @@
-#! /bin/sh
-
-set -e
-set -x
-
-export CFLAGS="-I/Users/piem/Library/Python/2.7/site-packages/numpy-1.8.0.dev_436a28f_20120710-py2.7-macosx-10.7-x86_64.egg/numpy/core/include/ -arch i386 -arch x86_64"
-export LDFLAGS=-L../../build/src/
-python setup.py clean build
-export PYTHONPATH=./build/lib.macosx-10.6-intel-2.7:$PYTHONPATH
-export DYLD_LIBRARY_PATH=../../build/src
-./run_all_tests --verbose
--- a/interfaces/python/c_weighting_test_simple.expected
+++ /dev/null
@@ -1,2 +1,0 @@
- 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 5.00000000e-01 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00
- 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 1.08504281e-01 2.31621372e-01 1.38614617e-01 1.58040475e-02 -9.84900252e-04 -2.72686896e-03 -2.87772967e-03 -2.87932142e-03 -2.86783482e-03 -2.85529016e-03 -2.84270413e-03 -2.83016008e-03 -2.81766458e-03 -2.80521796e-03 -2.79282009e-03 -2.78047079e-03 -2.76816989e-03 -2.75591721e-03 -2.74371257e-03 -2.73155579e-03
--- a/interfaces/python/demo_beats_and_tempo.py
+++ /dev/null
@@ -1,39 +1,0 @@
-#! /usr/bin/python
-
-import sys
-from aubio import tempo, source
-
-win_s = 512 # fft size
-hop_s = win_s / 2 # hop size
-samplerate = 44100
-
-if len(sys.argv) < 2:
- print "Usage: %s <filename>" % sys.argv[0]
- sys.exit(1)
-
-filename = sys.argv[1]
-beats = []
-
-s = source(filename, samplerate, hop_s)
-t = tempo("default", win_s, hop_s)
-
-block_read = 0
-while True:
- samples, read = s()
- isbeat = t(samples)
- if isbeat:
- thisbeat = (block_read * hop_s + isbeat[0]) / samplerate
- print "%.4f" % thisbeat
- beats.append (thisbeat)
- block_read += 1
- if read < hop_s: break
-
-periods = [60./(b - a) for a,b in zip(beats[:-1],beats[1:])]
-
-from numpy import mean, median
-print 'mean period:', mean(periods), 'bpm'
-print 'median period:', median(periods), 'bpm'
-
-from pylab import plot, show
-plot(beats[1:], periods)
-show()
--- a/interfaces/python/demo_filterbank_slaney.py
+++ /dev/null
@@ -1,21 +1,0 @@
-#! /usr/bin/python
-
-from aubio import filterbank
-from numpy import array, arange, vstack
-
-win_s = 8192
-samplerate = 16000
-
-f = filterbank(40, win_s)
-f.set_mel_coeffs_slaney(samplerate)
-
-from pylab import loglog, title, show, xlim, ylim, xlabel, ylabel
-xlim([0,samplerate / 2])
-times = vstack([arange(win_s / 2 + 1) * samplerate / win_s] * 40)
-loglog(times.T, f.get_coeffs().T, '.-')
-title('Mel frequency bands coefficients')
-xlim([100, 7500])
-ylim([1.0e-3, 2.0e-2])
-xlabel('Frequency (Hz)')
-ylabel('Amplitude')
-show()
--- a/interfaces/python/demo_filterbank_triangle_bands.py
+++ /dev/null
@@ -1,47 +1,0 @@
-#! /usr/bin/python
-
-from aubio import filterbank, fvec
-from pylab import loglog, show, subplot, xlim, ylim, xlabel, ylabel, title
-from numpy import vstack, arange
-
-win_s = 2048
-samplerate = 48000
-
-freq_list = [60, 80, 200, 400, 800, 1600, 3200, 6400, 12800, 24000]
-n_filters = len(freq_list) - 2
-
-f = filterbank(n_filters, win_s)
-freqs = fvec(freq_list)
-f.set_triangle_bands(freqs, samplerate)
-
-subplot(211)
-title('Examples of filterbank built with set_triangle_bands and set_coeffs')
-times = vstack([arange(win_s / 2 + 1) * samplerate / win_s] * n_filters)
-loglog(times.T, f.get_coeffs().T, '.-')
-xlim([50, samplerate/2])
-ylim([1.0e-6, 2.0e-2])
-ylabel('Amplitude')
-
-## build a new filterbank
-
-freq_list = [60, 80, 200, 400, 800, 1200, 1600, 3200, 6400, 10000, 15000, 24000]
-n_filters = len(freq_list) - 2
-
-f = filterbank(n_filters, win_s)
-freqs = fvec(freq_list)
-f.set_triangle_bands(freqs, samplerate)
-
-coeffs = f.get_coeffs()
-coeffs[4] *= 5.
-
-f.set_coeffs(coeffs)
-
-subplot(212)
-times = vstack([arange(win_s / 2 + 1) * samplerate / win_s] * n_filters)
-loglog(times.T, f.get_coeffs().T, '.-')
-xlim([50, samplerate/2])
-ylim([1.0e-6, 2.0e-2])
-xlabel('Frequency (Hz)')
-ylabel('Amplitude')
-
-show()
--- a/interfaces/python/demo_sink.py
+++ /dev/null
@@ -1,17 +1,0 @@
-#! /usr/bin/python
-
-import sys
-from aubio import source, sink
-
-if __name__ == '__main__':
- if len(sys.argv) < 2:
- print 'usage: %s <inputfile> <outputfile>' % sys.argv[0]
- sys.exit(1)
- f = source(sys.argv[1], 8000, 256)
- g = sink(sys.argv[2], 8000)
- total_frames, read = 0, 256
- while read:
- vec, read = f()
- g(vec, read)
- total_frames += read
- print "read", total_frames / float(f.samplerate), "seconds from", f.uri
--- a/interfaces/python/demo_source.py
+++ /dev/null
@@ -1,16 +1,0 @@
-#! /usr/bin/python
-
-import sys
-from aubio import source
-
-if __name__ == '__main__':
- if len(sys.argv) < 2:
- print 'usage: %s <inputfile>' % sys.argv[0]
- sys.exit(1)
- f = source(sys.argv[1], 1, 256)
- samplerate = f.get_samplerate()
- total_frames, read = 0, 256
- while read:
- vec, read = f()
- total_frames += read
- print "read", total_frames / float(samplerate), "seconds from", f.uri
--- a/interfaces/python/demo_spectrogram.py
+++ /dev/null
@@ -1,45 +1,0 @@
-#! /usr/bin/python
-
-import sys
-from aubio import pvoc, source
-from numpy import array, arange, zeros, shape, log10, vstack
-from pylab import imshow, show, cm, axis, ylabel, xlabel, xticks, yticks
-
-def get_spectrogram(filename):
- samplerate = 44100
- win_s = 512 # fft window size
- hop_s = win_s / 2 # hop size
- fft_s = win_s / 2 + 1 # spectrum bins
-
- a = source(filename, samplerate, hop_s) # source file
- pv = pvoc(win_s, hop_s) # phase vocoder
- specgram = zeros([0, fft_s], dtype='float32') # numpy array to store spectrogram
-
- # analysis
- while True:
- samples, read = a() # read file
- specgram = vstack((specgram,pv(samples).norm)) # store new norm vector
- if read < a.hop_size: break
-
- # plotting
- imshow(log10(specgram.T), origin = 'bottom', aspect = 'auto', cmap=cm.gray_r)
- axis([0, len(specgram), 0, len(specgram[0])])
- ylabel('Frequency (Hz)')
- xlabel('Time (s)')
- # show axes in Hz and seconds
- time_step = hop_s / float(samplerate)
- total_time = len(specgram) * time_step
- ticks = 10
- xticks( arange(ticks) / float(ticks) * len(specgram),
- [x * total_time / float(ticks) for x in range(ticks) ] )
- yticks( arange(ticks) / float(ticks) * len(specgram[0]),
- [x * samplerate / 2. / float(ticks) for x in range(ticks) ] )
-
-if __name__ == '__main__':
- if len(sys.argv) < 2:
- print "Usage: %s <filename>" % sys.argv[0]
- else:
- for soundfile in sys.argv[1:]:
- get_spectrogram(soundfile)
- # display graph
- show()
--- a/interfaces/python/demo_tss.py
+++ /dev/null
@@ -1,47 +1,0 @@
-#! /usr/bin/python
-
-import sys
-from aubio import source, sink, pvoc, tss
-
-if __name__ == '__main__':
- if len(sys.argv) < 2:
- print 'usage: %s <inputfile> <outputfile_transient> <outputfile_steady>' % sys.argv[0]
- sys.exit(1)
-
- samplerate = 44100
- win_s = 512 # fft size
- hop_s = win_s / 2 # block size
- threshold = 0.26
-
- f = source(sys.argv[1], samplerate, hop_s)
- g = sink(sys.argv[2], samplerate)
- h = sink(sys.argv[3], samplerate)
-
- pv = pvoc(win_s, hop_s) # phase vocoder
- pw = pvoc(win_s, hop_s) # another phase vocoder
- t = tss(win_s, hop_s) # transient steady state separation
-
- t.set_threshold(threshold)
-
- read = hop_s
-
- while read:
- samples, read = f() # read file
- spec = pv(samples) # compute spectrum
- trans_spec, stead_spec = t(spec) # transient steady-state separation
- transients = pv.rdo(trans_spec) # overlap-add synthesis of transients
- steadstate = pw.rdo(stead_spec) # overlap-add synthesis of steady states
- g(transients, read) # write transients to output
- h(steadstate, read) # write steady states to output
-
- del f, g, h # finish writing the files now
-
- from demo_spectrogram import get_spectrogram
- from pylab import subplot, show
- subplot(311)
- get_spectrogram(sys.argv[1])
- subplot(312)
- get_spectrogram(sys.argv[2])
- subplot(313)
- get_spectrogram(sys.argv[3])
- show()
--- a/interfaces/python/gen_pyobject.py
+++ /dev/null
@@ -1,527 +1,0 @@
-#! /usr/bin/python
-
-""" This madness of code is used to generate the C code of the python interface
-to aubio. Don't try this at home.
-
-The list of typedefs and functions is obtained from the command line 'cpp
-aubio.h'. This list is then used to parse all the functions about this object.
-
-I hear the ones asking "why not use swig, or cython, or something like that?"
-
-The requirements for this extension are the following:
-
- - aubio vectors can be viewed as numpy arrays, and vice versa
- - aubio 'object' should be python classes, not just a bunch of functions
-
-I haven't met any python interface generator that can meet both these
-requirements. If you know of one, please let me know, it will spare me
-maintaining this bizarre file.
-"""
-
-param_numbers = {
- 'source': [0, 2],
- 'sink': [2, 0],
-}
-
-# TODO
-# do function: for now, only the following pattern is supported:
-# void aubio_<foo>_do (aubio_foo_t * o,
-# [input1_t * input, [output1_t * output, ..., output3_t * output]]);
-# There is no way of knowing that output1 is actually input2. In the future,
-# const could be used for the inputs in the C prototypes.
-
-def write_msg(*args):
- pass
- # uncomment out for debugging
- #print args
-
-def split_type(arg):
- """ arg = 'foo *name'
- return ['foo*', 'name'] """
- l = arg.split()
- type_arg = {'type': l[0], 'name': l[1]}
- # ['foo', '*name'] -> ['foo*', 'name']
- if l[-1].startswith('*'):
- #return [l[0]+'*', l[1][1:]]
- type_arg['type'] = l[0] + '*'
- type_arg['name'] = l[1][1:]
- # ['foo', '*', 'name'] -> ['foo*', 'name']
- if len(l) == 3:
- #return [l[0]+l[1], l[2]]
- type_arg['type'] = l[0]+l[1]
- type_arg['name'] = l[2]
- else:
- #return l
- pass
- return type_arg
-
-def get_params(proto):
- """ get the list of parameters from a function prototype
- example: proto = "int main (int argc, char ** argv)"
- returns: ['int argc', 'char ** argv']
- """
- import re
- paramregex = re.compile('[\(, ](\w+ \*?\*? ?\w+)[, \)]')
- return paramregex.findall(proto)
-
-def get_params_types_names(proto):
- """ get the list of parameters from a function prototype
- example: proto = "int main (int argc, char ** argv)"
- returns: [['int', 'argc'], ['char **','argv']]
- """
- return map(split_type, get_params(proto))
-
-def get_return_type(proto):
- import re
- paramregex = re.compile('(\w+ ?\*?).*')
- outputs = paramregex.findall(proto)
- assert len(outputs) == 1
- return outputs[0].replace(' ', '')
-
-def get_name(proto):
- name = proto.split()[1].split('(')[0]
- return name.replace('*','')
-
-# the important bits: the size of the output for each objects. this data should
-# move into the C library at some point.
-defaultsizes = {
- 'resampler': ['input->length * self->ratio'],
- 'specdesc': ['1'],
- 'onset': ['1'],
- 'pitchyin': ['1'],
- 'pitchyinfft': ['1'],
- 'pitchschmitt': ['1'],
- 'pitchmcomb': ['1'],
- 'pitchfcomb': ['1'],
- 'pitch': ['1'],
- 'tss': ['self->buf_size', 'self->buf_size'],
- 'mfcc': ['self->n_coeffs'],
- 'beattracking': ['self->hop_size'],
- 'tempo': ['1'],
- 'peakpicker': ['1'],
- 'source': ['self->hop_size', '1'],
-}
-
-# default value for variables
-aubioinitvalue = {
- 'uint_t': 0,
- 'smpl_t': 0,
- 'lsmp_t': 0.,
- 'char_t*': 'NULL',
- }
-
-aubiodefvalue = {
- # we have some clean up to do
- 'buf_size': 'Py_default_vector_length',
- # and here too
- 'hop_size': 'Py_default_vector_length / 2',
- # these should be alright
- 'samplerate': 'Py_aubio_default_samplerate',
- # now for the non obvious ones
- 'n_filters': '40',
- 'n_coeffs': '13',
- 'nelems': '10',
- 'flow': '0.',
- 'fhig': '1.',
- 'ilow': '0.',
- 'ihig': '1.',
- 'thrs': '0.5',
- 'ratio': '0.5',
- 'method': '"default"',
- 'uri': '"none"',
- }
-
-# aubio to python
-aubio2pytypes = {
- 'uint_t': 'I',
- 'smpl_t': 'f',
- 'lsmp_t': 'd',
- 'fvec_t*': 'O',
- 'cvec_t*': 'O',
- 'char_t*': 's',
-}
-
-# python to aubio
-aubiovecfrompyobj = {
- 'fvec_t*': 'PyAubio_ArrayToCFvec',
- 'cvec_t*': 'PyAubio_ArrayToCCvec',
- 'uint_t': '(uint_t)PyInt_AsLong',
-}
-
-# aubio to python
-aubiovectopyobj = {
- 'fvec_t*': 'PyAubio_CFvecToArray',
- 'cvec_t*': 'PyAubio_CCvecToPyCvec',
- 'smpl_t': 'PyFloat_FromDouble',
- 'uint_t*': 'PyInt_FromLong',
- 'uint_t': 'PyInt_FromLong',
-}
-
-def gen_new_init(newfunc, name):
- newparams = get_params_types_names(newfunc)
- # self->param1, self->param2, self->param3
- if len(newparams):
- selfparams = ', self->'+', self->'.join([p['name'] for p in newparams])
- else:
- selfparams = ''
- # "param1", "param2", "param3"
- paramnames = ", ".join(["\""+p['name']+"\"" for p in newparams])
- pyparams = "".join(map(lambda p: aubio2pytypes[p['type']], newparams))
- paramrefs = ", ".join(["&" + p['name'] for p in newparams])
- s = """\
-// WARNING: this file is generated, DO NOT EDIT
-
-// WARNING: if you haven't read the first line yet, please do so
-#include "aubiowraphell.h"
-
-typedef struct
-{
- PyObject_HEAD
- aubio_%(name)s_t * o;
-""" % locals()
- for p in newparams:
- ptype = p['type']
- pname = p['name']
- s += """\
- %(ptype)s %(pname)s;
-""" % locals()
- s += """\
-} Py_%(name)s;
-
-static char Py_%(name)s_doc[] = "%(name)s object";
-
-static PyObject *
-Py_%(name)s_new (PyTypeObject * pytype, PyObject * args, PyObject * kwds)
-{
- Py_%(name)s *self;
-""" % locals()
- for p in newparams:
- ptype = p['type']
- pname = p['name']
- initval = aubioinitvalue[ptype]
- s += """\
- %(ptype)s %(pname)s = %(initval)s;
-""" % locals()
- # now the actual PyArg_Parse
- if len(paramnames):
- s += """\
- static char *kwlist[] = { %(paramnames)s, NULL };
-
- if (!PyArg_ParseTupleAndKeywords (args, kwds, "|%(pyparams)s", kwlist,
- %(paramrefs)s)) {
- return NULL;
- }
-""" % locals()
- s += """\
-
- self = (Py_%(name)s *) pytype->tp_alloc (pytype, 0);
-
- if (self == NULL) {
- return NULL;
- }
-""" % locals()
- for p in newparams:
- ptype = p['type']
- pname = p['name']
- defval = aubiodefvalue[pname]
- if ptype == 'char_t*':
- s += """\
-
- self->%(pname)s = %(defval)s;
- if (%(pname)s != NULL) {
- self->%(pname)s = %(pname)s;
- }
-""" % locals()
- elif ptype == 'uint_t':
- s += """\
-
- self->%(pname)s = %(defval)s;
- if (%(pname)s > 0) {
- self->%(pname)s = %(pname)s;
- } else if (%(pname)s < 0) {
- PyErr_SetString (PyExc_ValueError,
- "can not use negative value for %(pname)s");
- return NULL;
- }
-""" % locals()
- elif ptype == 'smpl_t':
- s += """\
-
- self->%(pname)s = %(defval)s;
- if (%(pname)s != %(defval)s) {
- self->%(pname)s = %(pname)s;
- }
-""" % locals()
- else:
- write_msg ("ERROR, unknown type of parameter %s %s" % (ptype, pname) )
- s += """\
-
- return (PyObject *) self;
-}
-
-AUBIO_INIT(%(name)s %(selfparams)s)
-
-AUBIO_DEL(%(name)s)
-
-""" % locals()
- return s
-
-def gen_do_input_params(inputparams):
- inputdefs = ''
- parseinput = ''
- inputrefs = ''
- inputvecs = ''
- pytypes = ''
-
- if len(inputparams):
- # build the parsing string for PyArg_ParseTuple
- pytypes = "".join([aubio2pytypes[p['type']] for p in inputparams])
-
- inputdefs = " /* input vectors python prototypes */\n"
- for p in inputparams:
- if p['type'] != 'uint_t':
- inputdefs += " PyObject * " + p['name'] + "_obj;\n"
-
- inputvecs = " /* input vectors prototypes */\n "
- inputvecs += "\n ".join(map(lambda p: p['type'] + ' ' + p['name'] + ";", inputparams))
-
- parseinput = " /* input vectors parsing */\n "
- for p in inputparams:
- inputvec = p['name']
- if p['type'] != 'uint_t':
- inputdef = p['name'] + "_obj"
- else:
- inputdef = p['name']
- converter = aubiovecfrompyobj[p['type']]
- if p['type'] != 'uint_t':
- parseinput += """%(inputvec)s = %(converter)s (%(inputdef)s);
-
- if (%(inputvec)s == NULL) {
- return NULL;
- }
-
- """ % locals()
-
- # build the string for the input objects references
- inputreflist = []
- for p in inputparams:
- if p['type'] != 'uint_t':
- inputreflist += [ "&" + p['name'] + "_obj" ]
- else:
- inputreflist += [ "&" + p['name'] ]
- inputrefs = ", ".join(inputreflist)
- # end of inputs strings
- return inputdefs, parseinput, inputrefs, inputvecs, pytypes
-
-def gen_do_output_params(outputparams, name):
- outputvecs = ""
- outputcreate = ""
- if len(outputparams):
- outputvecs = " /* output vectors prototypes */\n"
- for p in outputparams:
- params = {
- 'name': p['name'], 'pytype': p['type'], 'autype': p['type'][:-3],
- 'length': defaultsizes[name].pop(0) }
- if (p['type'] == 'uint_t*'):
- outputvecs += ' uint_t' + ' ' + p['name'] + ";\n"
- outputcreate += " %(name)s = 0;\n" % params
- else:
- outputvecs += " " + p['type'] + ' ' + p['name'] + ";\n"
- outputcreate += " /* creating output %(name)s as a new_%(autype)s of length %(length)s */\n" % params
- outputcreate += " %(name)s = new_%(autype)s (%(length)s);\n" % params
-
- returnval = "";
- if len(outputparams) > 1:
- returnval += " PyObject *outputs = PyList_New(0);\n"
- for p in outputparams:
- returnval += " PyList_Append( outputs, (PyObject *)" + aubiovectopyobj[p['type']] + " (" + p['name'] + ")" +");\n"
- returnval += " return outputs;"
- elif len(outputparams) == 1:
- if defaultsizes[name] == '1':
- returnval += " return (PyObject *)PyFloat_FromDouble(" + p['name'] + "->data[0])"
- else:
- returnval += " return (PyObject *)" + aubiovectopyobj[p['type']] + " (" + p['name'] + ")"
- else:
- returnval = " return Py_None;";
- # end of output strings
- return outputvecs, outputcreate, returnval
-
-def gen_do(dofunc, name):
- funcname = dofunc.split()[1].split('(')[0]
- doparams = get_params_types_names(dofunc)
- # make sure the first parameter is the object
- assert doparams[0]['type'] == "aubio_"+name+"_t*", \
- "method is not in 'aubio_<name>_t"
- # and remove it
- doparams = doparams[1:]
-
- n_param = len(doparams)
-
- if name in param_numbers.keys():
- n_input_param, n_output_param = param_numbers[name]
- print name, n_output_param
- else:
- n_input_param, n_output_param = 1, n_param - 1
-
- assert n_output_param + n_input_param == n_param, "n_output_param + n_input_param != n_param for %s" % name
-
- inputparams = doparams[:n_input_param]
- outputparams = doparams[n_input_param:n_input_param + n_output_param]
-
- inputdefs, parseinput, inputrefs, inputvecs, pytypes = gen_do_input_params(inputparams);
- outputvecs, outputcreate, returnval = gen_do_output_params(outputparams, name)
-
- # build strings for outputs
- # build the parameters for the _do() call
- doparams_string = "self->o"
- for p in doparams:
- if p['type'] == 'uint_t*':
- doparams_string += ", &" + p['name']
- else:
- doparams_string += ", " + p['name']
-
- if n_input_param:
- arg_parse_tuple = """\
- if (!PyArg_ParseTuple (args, "%(pytypes)s", %(inputrefs)s)) {
- return NULL;
- }
-""" % locals()
- else:
- arg_parse_tuple = ""
- # put it all together
- s = """\
-/* function Py_%(name)s_do */
-static PyObject *
-Py_%(name)s_do(Py_%(name)s * self, PyObject * args)
-{
-%(inputdefs)s
-%(inputvecs)s
-%(outputvecs)s
-
-%(arg_parse_tuple)s
-
-%(parseinput)s
-
-%(outputcreate)s
-
- /* compute _do function */
- %(funcname)s (%(doparams_string)s);
-
-%(returnval)s;
-}
-""" % locals()
- return s
-
-def gen_members(new_method, name):
- newparams = get_params_types_names(new_method)
- s = """
-AUBIO_MEMBERS_START(%(name)s)""" % locals()
- for param in newparams:
- if param['type'] == 'char_t*':
- s += """
- {"%(pname)s", T_STRING, offsetof (Py_%(name)s, %(pname)s), READONLY, ""},""" \
- % { 'pname': param['name'], 'ptype': param['type'], 'name': name}
- elif param['type'] == 'uint_t':
- s += """
- {"%(pname)s", T_INT, offsetof (Py_%(name)s, %(pname)s), READONLY, ""},""" \
- % { 'pname': param['name'], 'ptype': param['type'], 'name': name}
- elif param['type'] == 'smpl_t':
- s += """
- {"%(pname)s", T_FLOAT, offsetof (Py_%(name)s, %(pname)s), READONLY, ""},""" \
- % { 'pname': param['name'], 'ptype': param['type'], 'name': name}
- else:
- write_msg ("-- ERROR, unknown member type ", param )
- s += """
-AUBIO_MEMBERS_STOP(%(name)s)
-
-""" % locals()
- return s
-
-
-def gen_methods(get_methods, set_methods, name):
- s = ""
- method_defs = ""
- for method in set_methods:
- method_name = get_name(method)
- params = get_params_types_names(method)
- out_type = get_return_type(method)
- assert params[0]['type'] == "aubio_"+name+"_t*", \
- "get method is not in 'aubio_<name>_t"
- write_msg (method )
- write_msg (params[1:])
- setter_args = "self->o, " +",".join([p['name'] for p in params[1:]])
- parse_args = ""
- for p in params[1:]:
- parse_args += p['type'] + " " + p['name'] + ";\n"
- argmap = "".join([aubio2pytypes[p['type']] for p in params[1:]])
- arglist = ", ".join(["&"+p['name'] for p in params[1:]])
- parse_args += """
- if (!PyArg_ParseTuple (args, "%(argmap)s", %(arglist)s)) {
- return NULL;
- } """ % locals()
- s += """
-static PyObject *
-Py%(funcname)s (Py_%(objname)s *self, PyObject *args)
-{
- uint_t err = 0;
-
- %(parse_args)s
-
- err = %(funcname)s (%(setter_args)s);
-
- if (err > 0) {
- PyErr_SetString (PyExc_ValueError,
- "error running %(funcname)s");
- return NULL;
- }
- return Py_None;
-}
-""" % {'funcname': method_name, 'objname': name,
- 'out_type': out_type, 'setter_args': setter_args, 'parse_args': parse_args }
- shortname = method_name.split(name+'_')[-1]
- method_defs += """\
- {"%(shortname)s", (PyCFunction) Py%(method_name)s,
- METH_VARARGS, ""},
-""" % locals()
-
- for method in get_methods:
- method_name = get_name(method)
- params = get_params_types_names(method)
- out_type = get_return_type(method)
- assert params[0]['type'] == "aubio_"+name+"_t*", \
- "get method is not in 'aubio_<name>_t %s" % params[0]['type']
- assert len(params) == 1, \
- "get method has more than one parameter %s" % params
- getter_args = "self->o"
- returnval = "(PyObject *)" + aubiovectopyobj[out_type] + " (tmp)"
- shortname = method_name.split(name+'_')[-1]
- method_defs += """\
- {"%(shortname)s", (PyCFunction) Py%(method_name)s,
- METH_NOARGS, ""},
-""" % locals()
- s += """
-static PyObject *
-Py%(funcname)s (Py_%(objname)s *self, PyObject *unused)
-{
- %(out_type)s tmp = %(funcname)s (%(getter_args)s);
- return %(returnval)s;
-}
-""" % {'funcname': method_name, 'objname': name,
- 'out_type': out_type, 'getter_args': getter_args, 'returnval': returnval }
-
- s += """
-static PyMethodDef Py_%(name)s_methods[] = {
-""" % locals()
- s += method_defs
- s += """\
- {NULL} /* sentinel */
-};
-""" % locals()
- return s
-
-def gen_finish(name):
- s = """\
-
-AUBIO_TYPEOBJECT(%(name)s, "aubio.%(name)s")
-""" % locals()
- return s
--- a/interfaces/python/generator.py
+++ /dev/null
@@ -1,187 +1,0 @@
-#! /usr/bin/python
-
-""" This file generates a c file from a list of cpp prototypes. """
-
-import os, sys, shutil
-from gen_pyobject import write_msg, gen_new_init, gen_do, gen_members, gen_methods, gen_finish
-
-def get_cpp_objects():
-
- cpp_output = [l.strip() for l in os.popen('cpp -DAUBIO_UNSTABLE=1 -I../../build/src ../../src/aubio.h').readlines()]
-
- cpp_output = filter(lambda y: len(y) > 1, cpp_output)
- cpp_output = filter(lambda y: not y.startswith('#'), cpp_output)
-
- i = 1
- while 1:
- if i >= len(cpp_output): break
- if cpp_output[i-1].endswith(',') or cpp_output[i-1].endswith('{') or cpp_output[i].startswith('}'):
- cpp_output[i] = cpp_output[i-1] + ' ' + cpp_output[i]
- cpp_output.pop(i-1)
- else:
- i += 1
-
- typedefs = filter(lambda y: y.startswith ('typedef struct _aubio'), cpp_output)
-
- cpp_objects = [a.split()[3][:-1] for a in typedefs]
-
- return cpp_output, cpp_objects
-
-def generate_object_files():
- if os.path.isdir('generated'): shutil.rmtree('generated')
- os.mkdir('generated')
-
- generated_objects = []
- cpp_output, cpp_objects = get_cpp_objects()
- skip_objects = ['fft',
- 'pvoc',
- 'filter',
- 'filterbank',
- 'resampler',
- 'sndfile',
- 'sink_apple_audio',
- 'sink_sndfile',
- 'source_apple_audio',
- 'source_sndfile']
-
- write_msg("-- INFO: %d objects in total" % len(cpp_objects))
-
- for this_object in cpp_objects:
- lint = 0
-
- if this_object[-2:] == '_t':
- object_name = this_object[:-2]
- else:
- object_name = this_object
- write_msg("-- WARNING: %s does not end in _t" % this_object)
-
- if object_name[:len('aubio_')] != 'aubio_':
- write_msg("-- WARNING: %s does not start n aubio_" % this_object)
-
- write_msg("-- INFO: looking at", object_name)
- object_methods = filter(lambda x: this_object in x, cpp_output)
- object_methods = [a.strip() for a in object_methods]
- object_methods = filter(lambda x: not x.startswith('typedef'), object_methods)
- #for method in object_methods:
- # write_msg(method)
- new_methods = filter(lambda x: 'new_'+object_name in x, object_methods)
- if len(new_methods) > 1:
- write_msg("-- WARNING: more than one new method for", object_name)
- for method in new_methods:
- write_msg(method)
- elif len(new_methods) < 1:
- write_msg("-- WARNING: no new method for", object_name)
- elif 0:
- for method in new_methods:
- write_msg(method)
-
- del_methods = filter(lambda x: 'del_'+object_name in x, object_methods)
- if len(del_methods) > 1:
- write_msg("-- WARNING: more than one del method for", object_name)
- for method in del_methods:
- write_msg(method)
- elif len(del_methods) < 1:
- write_msg("-- WARNING: no del method for", object_name)
-
- do_methods = filter(lambda x: object_name+'_do' in x, object_methods)
- if len(do_methods) > 1:
- pass
- #write_msg("-- WARNING: more than one do method for", object_name)
- #for method in do_methods:
- # write_msg(method)
- elif len(do_methods) < 1:
- write_msg("-- WARNING: no do method for", object_name)
- elif 0:
- for method in do_methods:
- write_msg(method)
-
- # check do methods return void
- for method in do_methods:
- if (method.split()[0] != 'void'):
- write_msg("-- ERROR: _do method does not return void:", method )
-
- get_methods = filter(lambda x: object_name+'_get_' in x, object_methods)
-
- set_methods = filter(lambda x: object_name+'_set_' in x, object_methods)
- for method in set_methods:
- if (method.split()[0] != 'uint_t'):
- write_msg("-- ERROR: _set method does not return uint_t:", method )
-
- other_methods = filter(lambda x: x not in new_methods, object_methods)
- other_methods = filter(lambda x: x not in del_methods, other_methods)
- other_methods = filter(lambda x: x not in do_methods, other_methods)
- other_methods = filter(lambda x: x not in get_methods, other_methods)
- other_methods = filter(lambda x: x not in set_methods, other_methods)
-
- if len(other_methods) > 0:
- write_msg("-- WARNING: some methods for", object_name, "were unidentified")
- for method in other_methods:
- write_msg(method)
-
-
- # generate this_object
- short_name = object_name[len('aubio_'):]
- if short_name in skip_objects:
- write_msg("-- INFO: skipping object", short_name )
- continue
- if 1: #try:
- s = gen_new_init(new_methods[0], short_name)
- s += gen_do(do_methods[0], short_name)
- s += gen_members(new_methods[0], short_name)
- s += gen_methods(get_methods, set_methods, short_name)
- s += gen_finish(short_name)
- generated_filepath = 'generated/gen-'+short_name+'.c'
- fd = open(generated_filepath, 'w')
- fd.write(s)
- #except Exception, e:
- # write_msg("-- ERROR:", type(e), str(e), "in", short_name)
- # continue
- generated_objects += [this_object]
-
- s = """// generated list of objects created with generator.py
-
-"""
-
- for each in generated_objects:
- s += "extern PyTypeObject Py_%sType;\n" % \
- each.replace('aubio_','').replace('_t','')
-
- types_ready = []
- for each in generated_objects:
- types_ready.append(" PyType_Ready (&Py_%sType) < 0" % \
- each.replace('aubio_','').replace('_t','') )
-
- s += """
- int
- generated_types_ready (void)
- {
- return (
- """
- s += ('\n ||').join(types_ready)
- s += """);
- }
- """
-
- s += """
- void
- add_generated_objects ( PyObject *m )
- {"""
- for each in generated_objects:
- s += """ Py_INCREF (&Py_%(name)sType);
- PyModule_AddObject (m, "%(name)s", (PyObject *) & Py_%(name)sType);""" % \
- { 'name': ( each.replace('aubio_','').replace('_t','') ) }
-
- s += """
- }"""
-
- fd = open('generated/aubio-generated.h', 'w')
- fd.write(s)
-
- from os import listdir
- generated_files = listdir('generated')
- generated_files = filter(lambda x: x.endswith('.c'), generated_files)
- generated_files = ['generated/'+f for f in generated_files]
- return generated_files
-
-if __name__ == '__main__':
- generate_object_files()
--- a/interfaces/python/py-cvec.c
+++ /dev/null
@@ -1,302 +1,0 @@
-#include "aubio-types.h"
-
-/* cvec type definition
-
-class cvec():
- def __init__(self, length = 1024):
- self.length = length
- self.norm = array(length)
- self.phas = array(length)
-
-*/
-
-static char Py_cvec_doc[] = "cvec object";
-
-static PyObject *
-Py_cvec_new (PyTypeObject * type, PyObject * args, PyObject * kwds)
-{
- int length= 0;
- Py_cvec *self;
- static char *kwlist[] = { "length", NULL };
-
- if (!PyArg_ParseTupleAndKeywords (args, kwds, "|I", kwlist,
- &length)) {
- return NULL;
- }
-
-
- self = (Py_cvec *) type->tp_alloc (type, 0);
-
- self->length = Py_default_vector_length / 2 + 1;
-
- if (self == NULL) {
- return NULL;
- }
-
- if (length > 0) {
- self->length = length / 2 + 1;
- } else if (length < 0) {
- PyErr_SetString (PyExc_ValueError,
- "can not use negative number of elements");
- return NULL;
- }
-
- return (PyObject *) self;
-}
-
-static int
-Py_cvec_init (Py_cvec * self, PyObject * args, PyObject * kwds)
-{
- self->o = new_cvec ((self->length - 1) * 2);
- if (self->o == NULL) {
- return -1;
- }
-
- return 0;
-}
-
-static void
-Py_cvec_del (Py_cvec * self)
-{
- del_cvec (self->o);
- self->ob_type->tp_free ((PyObject *) self);
-}
-
-static PyObject *
-Py_cvec_repr (Py_cvec * self, PyObject * unused)
-{
- PyObject *format = NULL;
- PyObject *args = NULL;
- PyObject *result = NULL;
-
- format = PyString_FromString ("aubio cvec of %d elements");
- if (format == NULL) {
- goto fail;
- }
-
- args = Py_BuildValue ("I", self->length);
- if (args == NULL) {
- goto fail;
- }
- cvec_print ( self->o );
-
- result = PyString_Format (format, args);
-
-fail:
- Py_XDECREF (format);
- Py_XDECREF (args);
-
- return result;
-}
-
-PyObject *
-PyAubio_CvecNormToArray (Py_cvec * self)
-{
- npy_intp dims[] = { self->o->length, 1 };
- return PyArray_SimpleNewFromData (1, dims, NPY_FLOAT, self->o->norm);
-}
-
-
-PyObject *
-PyAubio_CvecPhasToArray (Py_cvec * self)
-{
- npy_intp dims[] = { self->o->length, 1 };
- return PyArray_SimpleNewFromData (1, dims, NPY_FLOAT, self->o->phas);
-}
-
-PyObject *
-PyAubio_ArrayToCvecPhas (PyObject * self)
-{
- return NULL;
-}
-
-PyObject *
-Py_cvec_get_norm (Py_cvec * self, void *closure)
-{
- return PyAubio_CvecNormToArray(self);
-}
-
-PyObject *
-Py_cvec_get_phas (Py_cvec * self, void *closure)
-{
- return PyAubio_CvecPhasToArray(self);
-}
-
-static int
-Py_cvec_set_norm (Py_cvec * vec, PyObject *input, void * closure)
-{
- PyArrayObject * array;
- if (input == NULL) {
- PyErr_SetString (PyExc_ValueError, "input array is not a python object");
- goto fail;
- }
- if (PyArray_Check(input)) {
-
- // we got an array, convert it to a cvec.norm
- if (PyArray_NDIM ((PyArrayObject *)input) == 0) {
- PyErr_SetString (PyExc_ValueError, "input array is a scalar");
- goto fail;
- } else if (PyArray_NDIM ((PyArrayObject *)input) > 2) {
- PyErr_SetString (PyExc_ValueError,
- "input array has more than two dimensions");
- goto fail;
- }
-
- if (!PyArray_ISFLOAT ((PyArrayObject *)input)) {
- PyErr_SetString (PyExc_ValueError, "input array should be float");
- goto fail;
- } else if (PyArray_TYPE ((PyArrayObject *)input) != AUBIO_NPY_SMPL) {
- PyErr_SetString (PyExc_ValueError, "input array should be float32");
- goto fail;
- }
- array = (PyArrayObject *)input;
-
- // check input array dimensions
- if (PyArray_NDIM (array) != 1) {
- PyErr_Format (PyExc_ValueError,
- "input array has %d dimensions, not 1",
- PyArray_NDIM (array));
- goto fail;
- } else {
- if (vec->o->length != PyArray_SIZE (array)) {
- PyErr_Format (PyExc_ValueError,
- "input array has length %d, but cvec has length %d",
- (int)PyArray_SIZE (array), vec->o->length);
- goto fail;
- }
- }
-
- vec->o->norm = (smpl_t *) PyArray_GETPTR1 (array, 0);
-
- } else {
- PyErr_SetString (PyExc_ValueError, "can only accept array as input");
- return 1;
- }
-
- Py_INCREF(array);
- return 0;
-
-fail:
- return 1;
-}
-
-static int
-Py_cvec_set_phas (Py_cvec * vec, PyObject *input, void * closure)
-{
- PyArrayObject * array;
- if (input == NULL) {
- PyErr_SetString (PyExc_ValueError, "input array is not a python object");
- goto fail;
- }
- if (PyArray_Check(input)) {
-
- // we got an array, convert it to a cvec.phas
- if (PyArray_NDIM ((PyArrayObject *)input) == 0) {
- PyErr_SetString (PyExc_ValueError, "input array is a scalar");
- goto fail;
- } else if (PyArray_NDIM ((PyArrayObject *)input) > 2) {
- PyErr_SetString (PyExc_ValueError,
- "input array has more than two dimensions");
- goto fail;
- }
-
- if (!PyArray_ISFLOAT ((PyArrayObject *)input)) {
- PyErr_SetString (PyExc_ValueError, "input array should be float");
- goto fail;
- } else if (PyArray_TYPE ((PyArrayObject *)input) != AUBIO_NPY_SMPL) {
- PyErr_SetString (PyExc_ValueError, "input array should be float32");
- goto fail;
- }
- array = (PyArrayObject *)input;
-
- // check input array dimensions
- if (PyArray_NDIM (array) != 1) {
- PyErr_Format (PyExc_ValueError,
- "input array has %d dimensions, not 1",
- PyArray_NDIM (array));
- goto fail;
- } else {
- if (vec->o->length != PyArray_SIZE (array)) {
- PyErr_Format (PyExc_ValueError,
- "input array has length %d, but cvec has length %d",
- (int)PyArray_SIZE (array), vec->o->length);
- goto fail;
- }
- }
-
- vec->o->phas = (smpl_t *) PyArray_GETPTR1 (array, 0);
-
- } else {
- PyErr_SetString (PyExc_ValueError, "can only accept array as input");
- return 1;
- }
-
- Py_INCREF(array);
- return 0;
-
-fail:
- return 1;
-}
-
-static PyMemberDef Py_cvec_members[] = {
- // TODO remove READONLY flag and define getter/setter
- {"length", T_INT, offsetof (Py_cvec, length), READONLY,
- "length attribute"},
- {NULL} /* Sentinel */
-};
-
-static PyMethodDef Py_cvec_methods[] = {
- {NULL}
-};
-
-static PyGetSetDef Py_cvec_getseters[] = {
- {"norm", (getter)Py_cvec_get_norm, (setter)Py_cvec_set_norm,
- "Numpy vector of shape (length,) containing the magnitude",
- NULL},
- {"phas", (getter)Py_cvec_get_phas, (setter)Py_cvec_set_phas,
- "Numpy vector of shape (length,) containing the phase",
- NULL},
- {NULL} /* sentinel */
-};
-
-PyTypeObject Py_cvecType = {
- PyObject_HEAD_INIT (NULL)
- 0, /* ob_size */
- "aubio.cvec", /* tp_name */
- sizeof (Py_cvec), /* tp_basicsize */
- 0, /* tp_itemsize */
- (destructor) Py_cvec_del, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- (reprfunc) Py_cvec_repr, /* tp_repr */
- 0, /* tp_as_number */
- 0, //&Py_cvec_tp_as_sequence, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- 0, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT, /* tp_flags */
- Py_cvec_doc, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- Py_cvec_methods, /* tp_methods */
- Py_cvec_members, /* tp_members */
- Py_cvec_getseters, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- (initproc) Py_cvec_init, /* tp_init */
- 0, /* tp_alloc */
- Py_cvec_new, /* tp_new */
-};
--- a/interfaces/python/py-fft.c
+++ /dev/null
@@ -1,107 +1,0 @@
-#include "aubiowraphell.h"
-
-static char Py_fft_doc[] = "fft object";
-
-AUBIO_DECLARE(fft, uint_t win_s)
-
-//AUBIO_NEW(fft)
-static PyObject *
-Py_fft_new (PyTypeObject * type, PyObject * args, PyObject * kwds)
-{
- int win_s = 0;
- Py_fft *self;
- static char *kwlist[] = { "win_s", NULL };
-
- if (!PyArg_ParseTupleAndKeywords (args, kwds, "|I", kwlist,
- &win_s)) {
- return NULL;
- }
-
- self = (Py_fft *) type->tp_alloc (type, 0);
-
- if (self == NULL) {
- return NULL;
- }
-
- self->win_s = Py_default_vector_length;
-
- if (self == NULL) {
- return NULL;
- }
-
- if (win_s > 0) {
- self->win_s = win_s;
- } else if (win_s < 0) {
- PyErr_SetString (PyExc_ValueError,
- "can not use negative window size");
- return NULL;
- }
-
- return (PyObject *) self;
-}
-
-
-AUBIO_INIT(fft, self->win_s)
-
-AUBIO_DEL(fft)
-
-static PyObject *
-Py_fft_do(PyObject * self, PyObject * args)
-{
- PyObject *input;
- fvec_t *vec;
- cvec_t *output;
-
- if (!PyArg_ParseTuple (args, "O", &input)) {
- return NULL;
- }
-
- vec = PyAubio_ArrayToCFvec (input);
-
- if (vec == NULL) {
- return NULL;
- }
-
- output = new_cvec(((Py_fft *) self)->win_s);
-
- // compute the function
- aubio_fft_do (((Py_fft *)self)->o, vec, output);
- return (PyObject *)PyAubio_CCvecToPyCvec(output);
-}
-
-AUBIO_MEMBERS_START(fft)
- {"win_s", T_INT, offsetof (Py_fft, win_s), READONLY,
- "size of the window"},
-AUBIO_MEMBERS_STOP(fft)
-
-static PyObject *
-Py_fft_rdo(Py_fft * self, PyObject * args)
-{
- PyObject *input;
- cvec_t *vec;
- fvec_t *output;
-
- if (!PyArg_ParseTuple (args, "O", &input)) {
- return NULL;
- }
-
- vec = PyAubio_ArrayToCCvec (input);
-
- if (vec == NULL) {
- return NULL;
- }
-
- output = new_fvec(self->win_s);
-
- // compute the function
- aubio_fft_rdo (((Py_fft *)self)->o, vec, output);
- return (PyObject *)PyAubio_CFvecToArray(output);
-}
-
-static PyMethodDef Py_fft_methods[] = {
- {"rdo", (PyCFunction) Py_fft_rdo, METH_VARARGS,
- "synthesis of spectral grain"},
- {NULL}
-};
-
-AUBIO_TYPEOBJECT(fft, "aubio.fft")
--- a/interfaces/python/py-filter.c
+++ /dev/null
@@ -1,198 +1,0 @@
-#include "aubio-types.h"
-
-typedef struct
-{
- PyObject_HEAD
- aubio_filter_t * o;
- uint_t order;
-} Py_filter;
-
-static char Py_filter_doc[] = "filter object";
-
-static PyObject *
-Py_filter_new (PyTypeObject * type, PyObject * args, PyObject * kwds)
-{
- int order= 0;
- Py_filter *self;
- static char *kwlist[] = { "order", NULL };
-
- if (!PyArg_ParseTupleAndKeywords (args, kwds, "|I", kwlist,
- &order)) {
- return NULL;
- }
-
- self = (Py_filter *) type->tp_alloc (type, 0);
-
- if (self == NULL) {
- return NULL;
- }
-
- self->order = 7;
-
- if (order > 0) {
- self->order = order;
- } else if (order < 0) {
- PyErr_SetString (PyExc_ValueError,
- "can not use negative order");
- return NULL;
- }
-
- return (PyObject *) self;
-}
-
-static int
-Py_filter_init (Py_filter * self, PyObject * args, PyObject * kwds)
-{
- self->o = new_aubio_filter (self->order);
- if (self->o == NULL) {
- return -1;
- }
-
- return 0;
-}
-
-static void
-Py_filter_del (Py_filter * self)
-{
- del_aubio_filter (self->o);
- self->ob_type->tp_free ((PyObject *) self);
-}
-
-static PyObject *
-Py_filter_do(Py_filter * self, PyObject * args)
-{
- PyObject *input;
- fvec_t *vec;
-
- if (!PyArg_ParseTuple (args, "O:digital_filter.do", &input)) {
- return NULL;
- }
-
- if (input == NULL) {
- return NULL;
- }
-
- vec = PyAubio_ArrayToCFvec (input);
-
- if (vec == NULL) {
- return NULL;
- }
-
- // compute the function
- fvec_t * out = new_fvec(vec->length);
- aubio_filter_do_outplace (self->o, vec, out);
- return PyAubio_CFvecToArray(out);
-}
-
-static PyObject *
-Py_filter_set_c_weighting (Py_filter * self, PyObject *args)
-{
- uint_t err = 0;
- uint_t samplerate;
- if (!PyArg_ParseTuple (args, "I", &samplerate)) {
- return NULL;
- }
-
- err = aubio_filter_set_c_weighting (self->o, samplerate);
- if (err > 0) {
- PyErr_SetString (PyExc_ValueError,
- "error when setting filter to C-weighting");
- return NULL;
- }
- return Py_None;
-}
-
-static PyObject *
-Py_filter_set_a_weighting (Py_filter * self, PyObject *args)
-{
- uint_t err = 0;
- uint_t samplerate;
- if (!PyArg_ParseTuple (args, "I", &samplerate)) {
- return NULL;
- }
-
- err = aubio_filter_set_a_weighting (self->o, samplerate);
- if (err > 0) {
- PyErr_SetString (PyExc_ValueError,
- "error when setting filter to A-weighting");
- return NULL;
- }
- return Py_None;
-}
-
-static PyObject *
-Py_filter_set_biquad(Py_filter * self, PyObject *args)
-{
- uint_t err = 0;
- lsmp_t b0, b1, b2, a1, a2;
- if (!PyArg_ParseTuple (args, "ddddd", &b0, &b1, &b2, &a1, &a2)) {
- return NULL;
- }
-
- err = aubio_filter_set_biquad (self->o, b0, b1, b2, a1, a2);
- if (err > 0) {
- PyErr_SetString (PyExc_ValueError,
- "error when setting filter with biquad coefficients");
- return NULL;
- }
- return Py_None;
-}
-
-static PyMemberDef Py_filter_members[] = {
- // TODO remove READONLY flag and define getter/setter
- {"order", T_INT, offsetof (Py_filter, order), READONLY,
- "order of the filter"},
- {NULL} /* Sentinel */
-};
-
-static PyMethodDef Py_filter_methods[] = {
- {"set_c_weighting", (PyCFunction) Py_filter_set_c_weighting, METH_VARARGS,
- "set filter coefficients to C-weighting"},
- {"set_a_weighting", (PyCFunction) Py_filter_set_a_weighting, METH_VARARGS,
- "set filter coefficients to A-weighting"},
- {"set_biquad", (PyCFunction) Py_filter_set_biquad, METH_VARARGS,
- "set b0, b1, b2, a1, a2 biquad coefficients"},
- {NULL}
-};
-
-PyTypeObject Py_filterType = {
- PyObject_HEAD_INIT (NULL)
- 0, /* ob_size */
- "aubio.digital_filter", /* tp_name */
- sizeof (Py_filter), /* tp_basicsize */
- 0, /* tp_itemsize */
- (destructor) Py_filter_del, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- 0, //(reprfunc) Py_filter_repr, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- (ternaryfunc)Py_filter_do, /* tp_call */
- 0, /* tp_str */
- 0, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT, /* tp_flags */
- Py_filter_doc, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- Py_filter_methods, /* tp_methods */
- Py_filter_members, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- (initproc) Py_filter_init, /* tp_init */
- 0, /* tp_alloc */
- Py_filter_new, /* tp_new */
-};
--- a/interfaces/python/py-filterbank.c
+++ /dev/null
@@ -1,183 +1,0 @@
-#include "aubiowraphell.h"
-
-static char Py_filterbank_doc[] = "filterbank object";
-
-AUBIO_DECLARE(filterbank, uint_t n_filters; uint_t win_s)
-
-//AUBIO_NEW(filterbank)
-static PyObject *
-Py_filterbank_new (PyTypeObject * type, PyObject * args, PyObject * kwds)
-{
- int win_s = 0, n_filters = 0;
- Py_filterbank *self;
- static char *kwlist[] = { "n_filters", "win_s", NULL };
-
- if (!PyArg_ParseTupleAndKeywords (args, kwds, "|II", kwlist,
- &n_filters, &win_s)) {
- return NULL;
- }
-
- self = (Py_filterbank *) type->tp_alloc (type, 0);
-
- if (self == NULL) {
- return NULL;
- }
-
- self->win_s = Py_default_vector_length;
- if (win_s > 0) {
- self->win_s = win_s;
- } else if (win_s < 0) {
- PyErr_SetString (PyExc_ValueError,
- "can not use negative window size");
- return NULL;
- }
-
- self->n_filters = 40;
- if (n_filters > 0) {
- self->n_filters = n_filters;
- } else if (n_filters < 0) {
- PyErr_SetString (PyExc_ValueError,
- "can not use negative number of filters");
- return NULL;
- }
-
- return (PyObject *) self;
-}
-
-
-AUBIO_INIT(filterbank, self->n_filters, self->win_s)
-
-AUBIO_DEL(filterbank)
-
-static PyObject *
-Py_filterbank_do(Py_filterbank * self, PyObject * args)
-{
- PyObject *input;
- cvec_t *vec;
- fvec_t *out;
-
- if (!PyArg_ParseTuple (args, "O", &input)) {
- return NULL;
- }
-
- vec = PyAubio_ArrayToCCvec (input);
-
- if (vec == NULL) {
- return NULL;
- }
-
- out = new_fvec (self->n_filters);
-
- // compute the function
- aubio_filterbank_do (self->o, vec, out);
- return (PyObject *)PyAubio_CFvecToArray(out);
-}
-
-AUBIO_MEMBERS_START(filterbank)
- {"win_s", T_INT, offsetof (Py_filterbank, win_s), READONLY,
- "size of the window"},
- {"n_filters", T_INT, offsetof (Py_filterbank, n_filters), READONLY,
- "number of filters"},
-AUBIO_MEMBERS_STOP(filterbank)
-
-static PyObject *
-Py_filterbank_set_triangle_bands (Py_filterbank * self, PyObject *args)
-{
- uint_t err = 0;
-
- PyObject *input;
- uint_t samplerate;
- fvec_t *freqs;
- if (!PyArg_ParseTuple (args, "OI", &input, &samplerate)) {
- return NULL;
- }
-
- if (input == NULL) {
- return NULL;
- }
-
- freqs = PyAubio_ArrayToCFvec (input);
-
- if (freqs == NULL) {
- return NULL;
- }
-
- err = aubio_filterbank_set_triangle_bands (self->o,
- freqs, samplerate);
- if (err > 0) {
- PyErr_SetString (PyExc_ValueError,
- "error when setting filter to A-weighting");
- return NULL;
- }
- return Py_None;
-}
-
-static PyObject *
-Py_filterbank_set_mel_coeffs_slaney (Py_filterbank * self, PyObject *args)
-{
- uint_t err = 0;
-
- uint_t samplerate;
- if (!PyArg_ParseTuple (args, "I", &samplerate)) {
- return NULL;
- }
-
- err = aubio_filterbank_set_mel_coeffs_slaney (self->o, samplerate);
- if (err > 0) {
- PyErr_SetString (PyExc_ValueError,
- "error when setting filter to A-weighting");
- return NULL;
- }
- return Py_None;
-}
-
-static PyObject *
-Py_filterbank_set_coeffs (Py_filterbank * self, PyObject *args)
-{
- uint_t err = 0;
-
- PyObject *input;
- fmat_t *coeffs;
-
- if (!PyArg_ParseTuple (args, "O", &input)) {
- return NULL;
- }
-
- coeffs = PyAubio_ArrayToCFmat (input);
-
- if (coeffs == NULL) {
- PyErr_SetString (PyExc_ValueError,
- "unable to parse input array");
- return NULL;
- }
-
- err = aubio_filterbank_set_coeffs (self->o, coeffs);
-
- if (err > 0) {
- PyErr_SetString (PyExc_ValueError,
- "error when setting filter coefficients");
- return NULL;
- }
- return Py_None;
-}
-
-static PyObject *
-Py_filterbank_get_coeffs (Py_filterbank * self, PyObject *unused)
-{
- return (PyObject *)PyAubio_CFmatToArray(
- aubio_filterbank_get_coeffs (self->o) );
-}
-
-static PyMethodDef Py_filterbank_methods[] = {
- {"set_triangle_bands", (PyCFunction) Py_filterbank_set_triangle_bands,
- METH_VARARGS, "set coefficients of filterbanks"},
- {"set_mel_coeffs_slaney", (PyCFunction) Py_filterbank_set_mel_coeffs_slaney,
- METH_VARARGS, "set coefficients of filterbank as in Auditory Toolbox"},
- {"get_coeffs", (PyCFunction) Py_filterbank_get_coeffs,
- METH_NOARGS, "get coefficients of filterbank"},
- {"set_coeffs", (PyCFunction) Py_filterbank_set_coeffs,
- METH_VARARGS, "set coefficients of filterbank"},
- {NULL}
-};
-
-AUBIO_TYPEOBJECT(filterbank, "aubio.filterbank")
--- a/interfaces/python/py-phasevoc.c
+++ /dev/null
@@ -1,118 +1,0 @@
-#include "aubiowraphell.h"
-
-static char Py_pvoc_doc[] = "pvoc object";
-
-AUBIO_DECLARE(pvoc, uint_t win_s; uint_t hop_s)
-
-//AUBIO_NEW(pvoc)
-static PyObject *
-Py_pvoc_new (PyTypeObject * type, PyObject * args, PyObject * kwds)
-{
- int win_s = 0, hop_s = 0;
- Py_pvoc *self;
- static char *kwlist[] = { "win_s", "hop_s", NULL };
-
- if (!PyArg_ParseTupleAndKeywords (args, kwds, "|II", kwlist,
- &win_s, &hop_s)) {
- return NULL;
- }
-
- self = (Py_pvoc *) type->tp_alloc (type, 0);
-
- if (self == NULL) {
- return NULL;
- }
-
- self->win_s = Py_default_vector_length;
- self->hop_s = Py_default_vector_length/2;
-
- if (self == NULL) {
- return NULL;
- }
-
- if (win_s > 0) {
- self->win_s = win_s;
- } else if (win_s < 0) {
- PyErr_SetString (PyExc_ValueError,
- "can not use negative window size");
- return NULL;
- }
-
- if (hop_s > 0) {
- self->hop_s = hop_s;
- } else if (hop_s < 0) {
- PyErr_SetString (PyExc_ValueError,
- "can not use negative hop size");
- return NULL;
- }
-
- return (PyObject *) self;
-}
-
-
-AUBIO_INIT(pvoc, self->win_s, self->hop_s)
-
-AUBIO_DEL(pvoc)
-
-static PyObject *
-Py_pvoc_do(Py_pvoc * self, PyObject * args)
-{
- PyObject *input;
- fvec_t *vec;
- cvec_t *output;
-
- if (!PyArg_ParseTuple (args, "O", &input)) {
- return NULL;
- }
-
- vec = PyAubio_ArrayToCFvec (input);
-
- if (vec == NULL) {
- return NULL;
- }
-
- output = new_cvec(self->win_s);
-
- // compute the function
- aubio_pvoc_do (self->o, vec, output);
- return (PyObject *)PyAubio_CCvecToPyCvec(output);
-}
-
-AUBIO_MEMBERS_START(pvoc)
- {"win_s", T_INT, offsetof (Py_pvoc, win_s), READONLY,
- "size of the window"},
- {"hop_s", T_INT, offsetof (Py_pvoc, hop_s), READONLY,
- "size of the hop"},
-AUBIO_MEMBERS_STOP(pvoc)
-
-static PyObject *
-Py_pvoc_rdo(Py_pvoc * self, PyObject * args)
-{
- PyObject *input;
- cvec_t *vec;
- fvec_t *output;
-
- if (!PyArg_ParseTuple (args, "O", &input)) {
- return NULL;
- }
-
- vec = PyAubio_ArrayToCCvec (input);
-
- if (vec == NULL) {
- return NULL;
- }
-
- output = new_fvec(self->hop_s);
-
- // compute the function
- aubio_pvoc_rdo (self->o, vec, output);
- return (PyObject *)PyAubio_CFvecToArray(output);
-}
-
-static PyMethodDef Py_pvoc_methods[] = {
- {"rdo", (PyCFunction) Py_pvoc_rdo, METH_VARARGS,
- "synthesis of spectral grain"},
- {NULL}
-};
-
-AUBIO_TYPEOBJECT(pvoc, "aubio.pvoc")
--- a/interfaces/python/run_all_tests
+++ /dev/null
@@ -1,20 +1,0 @@
-#! /usr/bin/python
-
-if __name__ == '__main__':
- import os, sys, unittest
- def load_test():
- # get relevant files
- curdir = os.path.dirname(sys.argv[0])
- if curdir == '': curdir = '.'
- files = os.listdir(curdir)
- modfiles = filter (lambda y: y.endswith('.py'), files)
- modfiles = filter (lambda f: f.startswith('test_'), modfiles)
- # get module names
- modnames = map (lambda x: os.path.splitext(x)[0], modfiles)
- # import them
- modules = map (__import__, modnames)
- # create a test suites from the imported module
- load_from_module = unittest.defaultTestLoader.loadTestsFromModule
- tests = map(load_from_module, modules)
- return unittest.TestSuite(tests)
- unittest.main(defaultTest = 'load_test')
--- a/interfaces/python/setup.py
+++ /dev/null
@@ -1,42 +1,0 @@
-#! /usr/bin/python
-
-from distutils.core import setup, Extension
-
-from generator import generate_object_files
-
-import os.path
-
-library_dirs = ['../../build/src', '../../src/.libs']
-include_dirs = ['../../build/src', '../../src', '.' ]
-library_dirs = filter (lambda x: os.path.isdir(x), library_dirs)
-include_dirs = filter (lambda x: os.path.isdir(x), include_dirs)
-
-aubio_extension = Extension("_aubio",
- ["aubiomodule.c",
- "aubioproxy.c",
- "py-cvec.c",
- # example without macro
- "py-filter.c",
- # macroised
- "py-filterbank.c",
- "py-fft.c",
- "py-phasevoc.c",
- # generated files
- ] + generate_object_files(),
- include_dirs = include_dirs,
- library_dirs = library_dirs,
- libraries=['aubio'])
-
-setup(name='aubio',
- version = '0.4.0alpha',
- packages = ['aubio'],
- description = 'interface to the aubio library',
- long_description = 'interface to the aubio library',
- license = 'GNU/GPL version 3',
- author = 'Paul Brossier',
- author_email = 'piem@aubio.org',
- maintainer = 'Paul Brossier',
- maintainer_email = 'piem@aubio.org',
- url = 'http://aubio.org/',
- ext_modules = [aubio_extension])
-
--- a/interfaces/python/test_aubio.py
+++ /dev/null
@@ -1,14 +1,0 @@
-#! /usr/bin/python
-
-from numpy.testing import TestCase, run_module_suite
-
-class aubiomodule_test_case(TestCase):
-
- def test_import(self):
- """ try importing aubio """
- import aubio
-
-if __name__ == '__main__':
- from unittest import main
- main()
-
--- a/interfaces/python/test_cvec.py
+++ /dev/null
@@ -1,50 +1,0 @@
-from numpy.testing import TestCase, run_module_suite
-from numpy.testing import assert_equal, assert_almost_equal
-from aubio import cvec
-from numpy import array, shape, pi
-
-class aubio_cvec_test_case(TestCase):
-
- def test_vector_created_with_zeroes(self):
- a = cvec(10)
- a
- shape(a.norm)
- shape(a.phas)
- a.norm[0]
- assert_equal(a.norm, 0.)
- assert_equal(a.phas, 0.)
-
- def test_vector_assign_element(self):
- a = cvec()
- a.norm[0] = 1
- assert_equal(a.norm[0], 1)
- a.phas[0] = 1
- assert_equal(a.phas[0], 1)
-
- def test_vector_assign_element_end(self):
- a = cvec()
- a.norm[-1] = 1
- assert_equal(a.norm[-1], 1)
- assert_equal(a.norm[len(a.norm)-1], 1)
- a.phas[-1] = 1
- assert_equal(a.phas[-1], 1)
- assert_equal(a.phas[len(a.phas)-1], 1)
-
- def test_assign_cvec_norm_slice(self):
- spec = cvec(1024)
- spec.norm[40:100] = 100
- assert_equal (spec.norm[0:40], 0)
- assert_equal (spec.norm[40:100], 100)
- assert_equal (spec.norm[100:-1], 0)
- assert_equal (spec.phas, 0)
-
- def test_assign_cvec_phas_slice(self):
- spec = cvec(1024)
- spec.phas[39:-1] = -pi
- assert_equal (spec.phas[0:39], 0)
- assert_equal (spec.phas[39:-1], -pi)
- assert_equal (spec.norm, 0)
-
-if __name__ == '__main__':
- from unittest import main
- main()
--- a/interfaces/python/test_fft.py
+++ /dev/null
@@ -1,113 +1,0 @@
-#! /usr/bin/python
-
-from numpy.testing import TestCase, run_module_suite
-from numpy.testing import assert_equal, assert_almost_equal
-# WARNING: numpy also has an fft object
-from aubio import fvec, fft, cvec
-from numpy import array, shape
-from math import pi
-
-class aubio_fft_test_case(TestCase):
-
- def test_members(self):
- f = fft()
- assert_equal (f.win_s, 1024)
-
- def test_output_dimensions(self):
- """ check the dimensions of output """
- win_s = 1024
- timegrain = fvec(win_s)
- f = fft(win_s)
- fftgrain = f (timegrain)
- assert_equal (fftgrain.norm, 0)
- assert_equal (shape(fftgrain.norm), (win_s/2+1,))
- assert_equal (fftgrain.phas, 0)
- assert_equal (shape(fftgrain.phas), (win_s/2+1,))
-
- def test_zeros(self):
- """ check the transform of zeros """
- win_s = 512
- timegrain = fvec(win_s)
- f = fft(win_s)
- fftgrain = f(timegrain)
- assert_equal ( fftgrain.norm == 0, True )
- assert_equal ( fftgrain.phas == 0, True )
-
- def test_impulse(self):
- """ check the transform of one impulse at a random place """
- from random import random
- from math import floor
- win_s = 256
- i = floor(random()*win_s)
- impulse = pi * random()
- f = fft(win_s)
- timegrain = fvec(win_s)
- timegrain[i] = impulse
- fftgrain = f ( timegrain )
- #self.plot_this ( fftgrain.phas )
- assert_almost_equal ( fftgrain.norm, impulse, decimal = 6 )
- assert_equal ( fftgrain.phas <= pi, True)
- assert_equal ( fftgrain.phas >= -pi, True)
-
- def test_impulse_negative(self):
- """ check the transform of one impulse at a random place """
- from random import random
- from math import floor
- win_s = 256
- i = 0
- impulse = -10.
- f = fft(win_s)
- timegrain = fvec(win_s)
- timegrain[i] = impulse
- fftgrain = f ( timegrain )
- #self.plot_this ( fftgrain.phas )
- assert_almost_equal ( fftgrain.norm, abs(impulse), decimal = 6 )
- if impulse < 0:
- # phase can be pi or -pi, as it is not unwrapped
- assert_almost_equal ( abs(fftgrain.phas[1:-1]) , pi, decimal = 6 )
- assert_almost_equal ( fftgrain.phas[0], pi, decimal = 6)
- assert_almost_equal ( fftgrain.phas[-1], pi, decimal = 6)
- else:
- assert_equal ( fftgrain.phas[1:-1] == 0, True)
- assert_equal ( fftgrain.phas[0] == 0, True)
- assert_equal ( fftgrain.phas[-1] == 0, True)
- # now check the resynthesis
- synthgrain = f.rdo ( fftgrain )
- #self.plot_this ( fftgrain.phas.T )
- assert_equal ( fftgrain.phas <= pi, True)
- assert_equal ( fftgrain.phas >= -pi, True)
- #self.plot_this ( synthgrain - timegrain )
- assert_almost_equal ( synthgrain, timegrain, decimal = 6 )
-
- def test_impulse_at_zero(self):
- """ check the transform of one impulse at a index 0 """
- win_s = 1024
- impulse = pi
- f = fft(win_s)
- timegrain = fvec(win_s)
- timegrain[0] = impulse
- fftgrain = f ( timegrain )
- #self.plot_this ( fftgrain.phas )
- assert_equal ( fftgrain.phas[0], 0)
- # could be 0 or -0 depending on fft implementation (0 for fftw3, -0 for ooura)
- assert_almost_equal ( fftgrain.phas[1], 0)
- assert_almost_equal ( fftgrain.norm[0], impulse, decimal = 6 )
-
- def test_rdo_before_do(self):
- """ check running fft.rdo before fft.do works """
- win_s = 1024
- impulse = pi
- f = fft(win_s)
- fftgrain = cvec(win_s)
- t = f.rdo( fftgrain )
- assert_equal ( t, 0 )
-
- def plot_this(self, this):
- from pylab import plot, show
- plot ( this )
- show ()
-
-if __name__ == '__main__':
- from unittest import main
- main()
-
--- a/interfaces/python/test_filter.py
+++ /dev/null
@@ -1,68 +1,0 @@
-#! /usr/bin/python
-
-from numpy.testing import TestCase, assert_equal, assert_almost_equal
-from aubio import fvec, digital_filter
-from numpy import array
-
-def array_from_text_file(filename, dtype = 'float'):
- return array([line.split() for line in open(filename).readlines()],
- dtype = dtype)
-
-class aubio_filter_test_case(TestCase):
-
- def test_members(self):
- f = digital_filter()
- assert_equal (f.order, 7)
- f = digital_filter(5)
- assert_equal (f.order, 5)
- f(fvec())
-
- def test_cweighting_error(self):
- f = digital_filter (2)
- self.assertRaises ( ValueError, f.set_c_weighting, 44100 )
- f = digital_filter (8)
- self.assertRaises ( ValueError, f.set_c_weighting, 44100 )
- f = digital_filter (5)
- self.assertRaises ( ValueError, f.set_c_weighting, 4000 )
- f = digital_filter (5)
- self.assertRaises ( ValueError, f.set_c_weighting, 193000 )
- f = digital_filter (7)
- self.assertRaises ( ValueError, f.set_a_weighting, 193000 )
- f = digital_filter (5)
- self.assertRaises ( ValueError, f.set_a_weighting, 192000 )
-
- def test_c_weighting(self):
- expected = array_from_text_file('c_weighting_test_simple.expected')
- f = digital_filter(5)
- f.set_c_weighting(44100)
- v = fvec(32)
- v[12] = .5
- u = f(v)
- assert_almost_equal (expected[1], u)
-
- def test_a_weighting(self):
- expected = array_from_text_file('a_weighting_test_simple.expected')
- f = digital_filter(7)
- f.set_a_weighting(44100)
- v = fvec(32)
- v[12] = .5
- u = f(v)
- assert_almost_equal (expected[1], u)
-
- def test_a_weighting_parted(self):
- expected = array_from_text_file('a_weighting_test_simple.expected')
- f = digital_filter(7)
- f.set_a_weighting(44100)
- v = fvec(16)
- v[12] = .5
- u = f(v)
- assert_almost_equal (expected[1][:16], u)
- # one more time
- v = fvec(16)
- u = f(v)
- assert_almost_equal (expected[1][16:], u)
-
-if __name__ == '__main__':
- from unittest import main
- main()
-
--- a/interfaces/python/test_filterbank.py
+++ /dev/null
@@ -1,23 +1,0 @@
-#! /usr/bin/python
-
-from numpy.testing import TestCase, run_module_suite
-from numpy.testing import assert_equal, assert_almost_equal
-from numpy import random
-from aubio import cvec, filterbank
-
-class aubio_filterbank_test_case(TestCase):
-
- def test_members(self):
- f = filterbank(40, 512)
- assert_equal ([f.n_filters, f.win_s], [40, 512])
-
- def test_set_coeffs(self):
- f = filterbank(40, 512)
- r = random.random([40, 512 / 2 + 1]).astype('float32')
- f.set_coeffs(r)
- assert_equal (r, f.get_coeffs())
-
-if __name__ == '__main__':
- from unittest import main
- main()
-
--- a/interfaces/python/test_filterbank_mel.py
+++ /dev/null
@@ -1,51 +1,0 @@
-#! /usr/bin/python
-
-from numpy.testing import TestCase, run_module_suite
-from numpy.testing import assert_equal, assert_almost_equal
-from numpy import array, shape
-from aubio import cvec, filterbank
-
-class aubio_filterbank_mel_test_case(TestCase):
-
- def test_slaney(self):
- f = filterbank(40, 512)
- f.set_mel_coeffs_slaney(16000)
- a = f.get_coeffs()
- assert_equal(shape (a), (40, 512/2 + 1) )
-
- def test_other_slaney(self):
- f = filterbank(40, 512*2)
- f.set_mel_coeffs_slaney(44100)
- a = f.get_coeffs()
- #print "sum is", sum(sum(a))
- for win_s in [256, 512, 1024, 2048, 4096]:
- f = filterbank(40, win_s)
- f.set_mel_coeffs_slaney(320000)
- a = f.get_coeffs()
- #print "sum is", sum(sum(a))
-
- def test_triangle_freqs_zeros(self):
- f = filterbank(9, 1024)
- freq_list = [40, 80, 200, 400, 800, 1600, 3200, 6400, 12800, 15000, 24000]
- freqs = array(freq_list, dtype = 'float32')
- f.set_triangle_bands(freqs, 48000)
- f.get_coeffs().T
- assert_equal ( f(cvec(1024)), 0)
-
- def test_triangle_freqs_ones(self):
- f = filterbank(9, 1024)
- freq_list = [40, 80, 200, 400, 800, 1600, 3200, 6400, 12800, 15000, 24000]
- freqs = array(freq_list, dtype = 'float32')
- f.set_triangle_bands(freqs, 48000)
- f.get_coeffs().T
- spec = cvec(1024)
- spec.norm[:] = 1
- assert_almost_equal ( f(spec),
- [ 0.02070313, 0.02138672, 0.02127604, 0.02135417,
- 0.02133301, 0.02133301, 0.02133311, 0.02133334, 0.02133345])
-
-if __name__ == '__main__':
- from unittest import main
- main()
-
-
--- a/interfaces/python/test_fvec.py
+++ /dev/null
@@ -1,135 +1,0 @@
-#! /usr/bin/python
-
-from numpy.testing import TestCase, run_module_suite
-from numpy.testing import assert_equal, assert_almost_equal
-from aubio import fvec, zero_crossing_rate, alpha_norm, min_removal
-from numpy import array, shape
-
-class aubio_fvec_test_case(TestCase):
-
- def test_vector_created_with_zeroes(self):
- a = fvec(10)
- a
- shape(a)
- a[0]
- #del a
- assert_equal(array(a), 0.)
-
- def test_vector_create_with_list(self):
- a = fvec([0,1,2,3])
- assert_equal (range(4), a)
-
- def test_vector_assign_element(self):
- a = fvec()
- a[0] = 1
- assert_equal(a[0], 1)
-
- def test_vector_assign_element_end(self):
- a = fvec()
- a[-1] = 1
- assert_equal(a[-1], 1)
- assert_equal(a[len(a)-1], 1)
-
- def test_vector(self):
- a = fvec()
- a, len(a) #a.length
- a[0]
- array(a)
- a = fvec(10)
- a = fvec(1)
- a.T
- array(a).T
- a = range(len(a))
-
- def test_wrong_values(self):
- self.assertRaises (ValueError, fvec, -10)
-
- a = fvec(2)
- self.assertRaises (IndexError, a.__getitem__, 3)
- self.assertRaises (IndexError, a.__getitem__, 2)
-
- def test_alpha_norm_of_fvec(self):
- a = fvec(2)
- self.assertEquals (alpha_norm(a, 1), 0)
- a[0] = 1
- self.assertEquals (alpha_norm(a, 1), 0.5)
- a[1] = 1
- self.assertEquals (alpha_norm(a, 1), 1)
- a = array([0, 1], dtype='float32')
- from math import sqrt
- assert_almost_equal (alpha_norm(a, 2), sqrt(2)/2.)
-
- def test_alpha_norm_of_none(self):
- self.assertRaises (ValueError, alpha_norm, None, 1)
-
- def test_alpha_norm_of_array_of_float32(self):
- # check scalar fails
- a = array(1, dtype = 'float32')
- self.assertRaises (ValueError, alpha_norm, a, 1)
- # check 2d array fails
- a = array([[2],[4]], dtype = 'float32')
- self.assertRaises (ValueError, alpha_norm, a, 1)
- # check 1d array
- a = array(range(10), dtype = 'float32')
- self.assertEquals (alpha_norm(a, 1), 4.5)
-
- def test_alpha_norm_of_array_of_int(self):
- a = array(1, dtype = 'int')
- self.assertRaises (ValueError, alpha_norm, a, 1)
- a = array([[[1,2],[3,4]]], dtype = 'int')
- self.assertRaises (ValueError, alpha_norm, a, 1)
- a = array(range(10), dtype = 'int')
- self.assertRaises (ValueError, alpha_norm, a, 1)
-
- def test_alpha_norm_of_array_of_string (self):
- a = "hello"
- self.assertRaises (ValueError, alpha_norm, a, 1)
-
- def test_zero_crossing_rate(self):
- a = array([0,1,-1], dtype='float32')
- assert_almost_equal (zero_crossing_rate(a), 1./3. )
- a = array([0.]*100, dtype='float32')
- self.assertEquals (zero_crossing_rate(a), 0 )
- a = array([-1.]*100, dtype='float32')
- self.assertEquals (zero_crossing_rate(a), 0 )
- a = array([1.]*100, dtype='float32')
- self.assertEquals (zero_crossing_rate(a), 0 )
-
- def test_alpha_norm_of_array_of_float64(self):
- # check scalar fail
- a = array(1, dtype = 'float64')
- self.assertRaises (ValueError, alpha_norm, a, 1)
- # check 3d array fail
- a = array([[[1,2],[3,4]]], dtype = 'float64')
- self.assertRaises (ValueError, alpha_norm, a, 1)
- # check float64 1d array fail
- a = array(range(10), dtype = 'float64')
- self.assertRaises (ValueError, alpha_norm, a, 1)
- # check float64 2d array fail
- a = array([range(10), range(10)], dtype = 'float64')
- self.assertRaises (ValueError, alpha_norm, a, 1)
-
- def test_fvec_min_removal_of_array(self):
- a = array([20,1,19], dtype='float32')
- b = min_removal(a)
- assert_equal (array(b), [19, 0, 18])
- assert_equal (b, [19, 0, 18])
- assert_equal (a, b)
- a[0] = 0
- assert_equal (a, b)
-
- def test_fvec_min_removal_of_array_float64(self):
- a = array([20,1,19], dtype='float64')
- self.assertRaises (ValueError, min_removal, a)
-
- def test_fvec_min_removal_of_fvec(self):
- a = fvec(3)
- a = array([20, 1, 19], dtype = 'float32')
- b = min_removal(a)
- assert_equal (array(b), [19, 0, 18])
- assert_equal (b, [19, 0, 18])
- assert_equal (a, b)
-
-if __name__ == '__main__':
- from unittest import main
- main()
--- a/interfaces/python/test_onset.py
+++ /dev/null
@@ -1,20 +1,0 @@
-#! /usr/bin/python
-
-from numpy.testing import TestCase, run_module_suite
-from numpy.testing import assert_equal, assert_almost_equal
-# WARNING: numpy also has an fft object
-from aubio import onset, cvec
-from numpy import array, shape, arange, zeros, log
-from math import pi
-
-class aubio_onset(TestCase):
-
- def test_members(self):
- o = onset()
- assert_equal ([o.buf_size, o.hop_size, o.method, o.samplerate],
- [1024,512,'default',44100])
-
-
-if __name__ == '__main__':
- from unittest import main
- main()
--- a/interfaces/python/test_peakpicker.py
+++ /dev/null
@@ -1,115 +1,0 @@
-#! /usr/bin/python
-
-from numpy.testing import TestCase, assert_equal, assert_almost_equal
-from aubio import peakpicker, fvec
-
-class aubio_peakpicker(TestCase):
-
- def test_members(self):
- o = peakpicker()
-
- def test_peakpicker_zeroes(self):
- o = peakpicker()
- assert_equal(o.get_thresholded_input(), 0.)
-
- def test_peakpick_set_threshold(self):
- o = peakpicker()
- new_threshold = threshold
- o.set_threshold(new_threshold)
- assert_almost_equal(new_threshold, o.get_threshold())
-
- def test_peakpicker_get_threshold(self):
- o = peakpicker()
- new_threshold = o.get_threshold()
- o.set_threshold(new_threshold)
- assert_equal(new_threshold, o.get_threshold())
-
-buf_size = 1024
-slice_size = 5
-delay = 1
-threshold = .9
-
-class aubio_peakpicker_peaks(TestCase):
-
- def setUp(self):
- self.o = peakpicker()
- self.o.set_threshold (threshold)
- self.vec = fvec(buf_size)
-
- def test_peakpicker_impulse(self):
- vec = self.vec; o = self.o
- a = 345
- vec[a] = 1000.
- self.peaks = [a]
-
- def test_peakpicker_ramp_up(self):
- vec = self.vec; o = self.o
- a = 345
- vec[a] = 1000. / 4. * 1.
- vec[a+1] = 1000. / 4. * 2.
- vec[a+2] = 1000. / 4. * 3.
- vec[a+3] = 1000.
- self.peaks = [a+1]
-
- def test_peakpicker_ramp_down(self):
- vec = self.vec; o = self.o
- a = 345
- vec[a] = 1000.
- vec[a+1] = 1000. / 4. * 3.
- vec[a+2] = 1000. / 4. * 2.
- vec[a+3] = 1000. / 4. * 1.
- self.peaks = [a]
-
- def test_peakpicker_plateau(self):
- vec = self.vec; o = self.o
- a = 345
- vec[a] = 1000. / 2
- vec[a+1] = 1000.
- vec[a+2] = 1000.
- vec[a+3] = 1000.
- vec[a+4] = 1000. / 2
- self.peaks = [a+1]
-
- def test_peakpicker_consecutive_peaks(self):
- vec = self.vec; o = self.o
- a = 345
- vec[a] = 1000. / 2
- vec[a+1] = 1000.
- vec[a+3] = 1000.
- vec[a+4] = 1000. / 2
- self.peaks = [a]
-
- def test_peakpicker_distant_peaks(self):
- vec = self.vec; o = self.o
- a = 345
- vec[a] = 1000.
- vec[a+7] = 1000.
- self.peaks = [a, a+7]
-
- def test_peakpicker_very_distant_peaks(self):
- vec = self.vec; o = self.o
- a = 345
- vec[a] = 1000.
- vec[a+67] = 1000.
- self.peaks = [a, a+67]
-
- def tearDown(self):
- fpeaks = []
- for index in range(0,buf_size-slice_size):
- sliced = self.vec[index:index+slice_size]
- findex = self.o(sliced)
- if findex:
- # we found a peak
- fpeak = index - findex - delay
- #print self.peaks, index, '-', findex, '-', delay, '=', fpeak
- if not round(index - findex - delay) in self.peaks:
- self.fail('missing peak ' + str(fpeak))
- fpeaks.append(fpeak)
- if len(fpeaks) != len(self.peaks):
- self.fail('some peaks of ' + str(self.peaks) + 'were not found, got only ' + str(fpeaks))
- #print fpeaks, self.peaks
-
-if __name__ == '__main__':
- from unittest import main
- main()
--- a/interfaces/python/test_phasevoc.py
+++ /dev/null
@@ -1,65 +1,0 @@
-#! /usr/bin/python
-
-from numpy.testing import TestCase, run_module_suite
-from numpy.testing import assert_equal, assert_almost_equal
-from aubio import fvec, cvec, pvoc
-from numpy import array, shape
-
-class aubio_pvoc_test_case(TestCase):
-
- def test_members(self):
- f = pvoc()
- assert_equal ([f.win_s, f.hop_s], [1024, 512])
- f = pvoc(2048, 128)
- assert_equal ([f.win_s, f.hop_s], [2048, 128])
-
- def test_zeros(self):
- win_s, hop_s = 1024, 256
- f = pvoc (win_s, hop_s)
- t = fvec (hop_s)
- for time in range( 4 * win_s / hop_s ):
- s = f(t)
- r = f.rdo(s)
- assert_equal ( array(t), 0)
- assert_equal ( s.norm, 0)
- assert_equal ( s.phas, 0)
- assert_equal ( r, 0)
-
- def test_steps_two_channels(self):
- """ check the resynthesis of steps is correct """
- f = pvoc(1024, 512)
- t1 = fvec(512)
- t2 = fvec(512)
- # positive step in first channel
- t1[100:200] = .1
- # positive step in second channel
- t1[20:50] = -.1
- s1 = f(t1)
- r1 = f.rdo(s1)
- s2 = f(t2)
- r2 = f.rdo(s2)
- #self.plot_this ( s1.norm.T )
- assert_almost_equal ( t1, r2, decimal = 6 )
-
- def test_steps_three_random_channels(self):
- from random import random
- f = pvoc(64, 16)
- t0 = fvec(16)
- t1 = fvec(16)
- for i in xrange(16):
- t1[i] = random() * 2. - 1.
- t2 = f.rdo(f(t1))
- t2 = f.rdo(f(t0))
- t2 = f.rdo(f(t0))
- t2 = f.rdo(f(t0))
- assert_almost_equal( t1, t2, decimal = 6 )
-
- def plot_this( self, this ):
- from pylab import semilogy, show
- semilogy ( this )
- show ()
-
-if __name__ == '__main__':
- from unittest import main
- main()
-
--- a/interfaces/python/test_pitch.py
+++ /dev/null
@@ -1,101 +1,0 @@
-#! /usr/bin/python
-
-from numpy.testing import TestCase
-from numpy.testing import assert_equal, assert_almost_equal
-from numpy import random, sin, arange, mean, median
-from math import pi
-from aubio import fvec, pitch
-
-class aubio_mathutils_test_case(TestCase):
-
- def test_members(self):
- p = pitch()
- assert_equal ( [p.method, p.buf_size, p.hop_size, p.samplerate],
- ['default', 1024, 512, 44100])
-
- def test_members_not_default(self):
- p = pitch('mcomb', 2048, 512, 32000)
- assert_equal ( [p.method, p.buf_size, p.hop_size, p.samplerate],
- ['mcomb', 2048, 512, 32000])
-
- def test_run_on_zeros(self):
- p = pitch('mcomb', 2048, 512, 32000)
- f = fvec (512)
- assert_equal ( p(f), 0. )
-
- def test_run_on_ones(self):
- p = pitch('mcomb', 2048, 512, 32000)
- f = fvec (512)
- f[:] = 1
- assert( p(f) != 0. )
-
- def test_run_default_on_sinusoid(self):
- method = 'default'
- buf_size = 2048
- hop_size = 512
- samplerate = 32000
- freq = 450.
- self.run_pitch_on_sinusoid(method, buf_size, hop_size, samplerate, freq)
-
- def test_run_schmitt_on_sinusoid(self):
- method = 'schmitt'
- buf_size = 4096
- hop_size = 512
- samplerate = 44100
- freq = 800.
- self.run_pitch_on_sinusoid(method, buf_size, hop_size, samplerate, freq)
-
- def test_run_mcomb_on_sinusoid(self):
- method = 'mcomb'
- buf_size = 2048
- hop_size = 512
- samplerate = 44100
- freq = 10000.
- self.run_pitch_on_sinusoid(method, buf_size, hop_size, samplerate, freq)
-
- def test_run_fcomb_on_sinusoid(self):
- method = 'fcomb'
- buf_size = 2048
- hop_size = 512
- samplerate = 32000
- freq = 440.
- self.run_pitch_on_sinusoid(method, buf_size, hop_size, samplerate, freq)
-
- def test_run_yin_on_sinusoid(self):
- method = 'yin'
- buf_size = 4096
- hop_size = 512
- samplerate = 32000
- freq = 880.
- self.run_pitch_on_sinusoid(method, buf_size, hop_size, samplerate, freq)
-
- def test_run_yinfft_on_sinusoid(self):
- method = 'yinfft'
- buf_size = 2048
- hop_size = 512
- samplerate = 32000
- freq = 640.
- self.run_pitch_on_sinusoid(method, buf_size, hop_size, samplerate, freq)
-
- def run_pitch_on_sinusoid(self, method, buf_size, hop_size, samplerate, freq):
- p = pitch(method, buf_size, hop_size, samplerate)
- sinvec = self.build_sinusoid(hop_size * 100, freq, samplerate)
- self.run_pitch(p, sinvec, freq)
-
- def build_sinusoid(self, length, freq, samplerate):
- return sin( 2. * pi * arange(length).astype('float32') * freq / samplerate)
-
- def run_pitch(self, p, input_vec, freq):
- count = 0
- pitches, errors = [], []
- for vec_slice in input_vec.reshape((-1, p.hop_size)):
- pitch = p(vec_slice)
- pitches.append(pitch)
- errors.append(1. - pitch / freq)
- # check that the mean of all relative errors is less than 10%
- assert_almost_equal (mean(errors), 0., decimal = 2)
-
-if __name__ == '__main__':
- from unittest import main
- main()
-
--- a/interfaces/python/test_source.py
+++ /dev/null
@@ -1,27 +1,0 @@
-#! /usr/bin/python
-
-from numpy.testing import TestCase, assert_equal, assert_almost_equal
-from aubio import fvec, source
-from numpy import array
-
-path = "/Users/piem/archives/sounds/loops/drum_Chocolate_Milk_-_Ation_Speaks_Louder_Than_Words.wav"
-
-class aubio_filter_test_case(TestCase):
-
- def test_members(self):
- f = source(path)
- print dir(f)
-
- def test_read(self):
- f = source(path)
- total_frames = 0
- while True:
- vec, read = f()
- total_frames += read
- if read < f.hop_size: break
- print "read", total_frames / float(f.samplerate), " seconds from", path
-
-if __name__ == '__main__':
- from unittest import main
- main()
-
--- a/interfaces/python/test_specdesc.py
+++ /dev/null
@@ -1,238 +1,0 @@
-#! /usr/bin/python
-
-from numpy.testing import TestCase, assert_equal, assert_almost_equal
-from numpy import random, arange, log, zeros
-from aubio import specdesc, cvec
-from math import pi
-
-methods = ["default",
- "energy",
- "hfc",
- "complex",
- "phase",
- "specdiff",
- "kl",
- "mkl",
- "specflux",
- "centroid",
- "spread",
- "skewness",
- "kurtosis",
- "slope",
- "decrease",
- "rolloff"]
-buf_size = 2048
-
-class aubio_specdesc(TestCase):
-
- def test_members(self):
- o = specdesc()
-
- for method in methods:
- o = specdesc(method, buf_size)
- assert_equal ([o.buf_size, o.method], [buf_size, method])
-
- spec = cvec(buf_size)
- spec.norm[0] = 1
- spec.norm[1] = 1./2.
- #print "%20s" % method, str(o(spec))
- o(spec)
- spec.norm = random.random_sample((len(spec.norm),)).astype('float32')
- spec.phas = random.random_sample((len(spec.phas),)).astype('float32')
- #print "%20s" % method, str(o(spec))
- assert (o(spec) != 0.)
-
- def test_hfc(self):
- o = specdesc("hfc", buf_size)
- spec = cvec(buf_size)
- # hfc of zeros is zero
- assert_equal (o(spec), 0.)
- # hfc of ones is sum of all bin numbers
- spec.norm[:] = 1
- expected = sum(range(buf_size/2 + 2))
- assert_equal (o(spec), expected)
- # changing phase doesn't change anything
- spec.phas[:] = 1
- assert_equal (o(spec), sum(range(buf_size/2 + 2)))
-
- def test_phase(self):
- o = specdesc("phase", buf_size)
- spec = cvec(buf_size)
- # phase of zeros is zero
- assert_equal (o(spec), 0.)
- spec.phas = random.random_sample((len(spec.phas),)).astype('float32')
- # phase of random is not zero
- spec.norm[:] = 1
- assert (o(spec) != 0.)
-
- def test_specdiff(self):
- o = specdesc("phase", buf_size)
- spec = cvec(buf_size)
- # specdiff of zeros is zero
- assert_equal (o(spec), 0.)
- spec.phas = random.random_sample((len(spec.phas),)).astype('float32')
- # phase of random is not zero
- spec.norm[:] = 1
- assert (o(spec) != 0.)
-
- def test_hfc(self):
- o = specdesc("hfc")
- c = cvec()
- assert_equal( 0., o(c))
- a = arange(c.length, dtype='float32')
- c.norm = a
- assert_equal (a, c.norm)
- assert_equal ( sum(a*(a+1)), o(c))
-
- def test_complex(self):
- o = specdesc("complex")
- c = cvec()
- assert_equal( 0., o(c))
- a = arange(c.length, dtype='float32')
- c.norm = a
- assert_equal (a, c.norm)
- # the previous run was on zeros, so previous frames are still 0
- # so we have sqrt ( abs ( r2 ^ 2) ) == r2
- assert_equal ( sum(a), o(c))
- # second time. c.norm = a, so, r1 = r2, and the euclidian distance is 0
- assert_equal ( 0, o(c))
-
- def test_kl(self):
- o = specdesc("kl")
- c = cvec()
- assert_equal( 0., o(c))
- a = arange(c.length, dtype='float32')
- c.norm = a
- assert_almost_equal( sum(a * log(1.+ a/1.e-10 ) ) / o(c), 1., decimal=6)
-
- def test_mkl(self):
- o = specdesc("mkl")
- c = cvec()
- assert_equal( 0., o(c))
- a = arange(c.length, dtype='float32')
- c.norm = a
- assert_almost_equal( sum(log(1.+ a/1.e-10 ) ) / o(c), 1, decimal=6)
-
- def test_specflux(self):
- o = specdesc("specflux")
- c = cvec()
- assert_equal( 0., o(c))
- a = arange(c.length, dtype='float32')
- c.norm = a
- assert_equal( sum(a), o(c))
- assert_equal( 0, o(c))
- c.norm = zeros(c.length, dtype='float32')
- assert_equal( 0, o(c))
-
- def test_centroid(self):
- o = specdesc("centroid")
- c = cvec()
- # make sure centroid of zeros is zero
- assert_equal( 0., o(c))
- a = arange(c.length, dtype='float32')
- c.norm = a
- centroid = sum(a*a) / sum(a)
- assert_almost_equal (centroid, o(c), decimal = 2)
-
- c.norm = a * .5
- assert_almost_equal (centroid, o(c), decimal = 2)
-
- def test_spread(self):
- o = specdesc("spread")
- c = cvec(2048)
- ramp = arange(c.length, dtype='float32')
- assert_equal( 0., o(c))
-
- a = ramp
- c.norm = a
- centroid = sum(a*a) / sum(a)
- spread = sum( a * pow(ramp - centroid, 2.) ) / sum(a)
- assert_almost_equal (o(c), spread, decimal = 1)
-
- def test_skewness(self):
- o = specdesc("skewness")
- c = cvec()
- assert_equal( 0., o(c))
- a = arange(c.length, dtype='float32')
- c.norm = a
- centroid = sum(a*a) / sum(a)
- spread = sum( (a - centroid)**2 *a) / sum(a)
- skewness = sum( (a - centroid)**3 *a) / sum(a) / spread **1.5
- assert_almost_equal (skewness, o(c), decimal = 2)
-
- c.norm = a * 3
- assert_almost_equal (skewness, o(c), decimal = 2)
-
- def test_kurtosis(self):
- o = specdesc("kurtosis")
- c = cvec()
- assert_equal( 0., o(c))
- a = arange(c.length, dtype='float32')
- c.norm = a
- centroid = sum(a*a) / sum(a)
- spread = sum( (a - centroid)**2 *a) / sum(a)
- kurtosis = sum( (a - centroid)**4 *a) / sum(a) / spread **2
- assert_almost_equal (kurtosis, o(c), decimal = 2)
-
- def test_slope(self):
- o = specdesc("slope")
- c = cvec()
- assert_equal( 0., o(c))
- a = arange(c.length * 2, 0, -2, dtype='float32')
- k = arange(c.length, dtype='float32')
- c.norm = a
- num = len(a) * sum(k*a) - sum(k)*sum(a)
- den = (len(a) * sum(k**2) - sum(k)**2)
- slope = num/den/sum(a)
- assert_almost_equal (slope, o(c), decimal = 5)
-
- a = arange(0, c.length * 2, +2, dtype='float32')
- c.norm = a
- num = len(a) * sum(k*a) - sum(k)*sum(a)
- den = (len(a) * sum(k**2) - sum(k)**2)
- slope = num/den/sum(a)
- assert_almost_equal (slope, o(c), decimal = 5)
-
- a = arange(0, c.length * 2, +2, dtype='float32')
- c.norm = a * 2
- assert_almost_equal (slope, o(c), decimal = 5)
-
- def test_decrease(self):
- o = specdesc("decrease")
- c = cvec()
- assert_equal( 0., o(c))
- a = arange(c.length * 2, 0, -2, dtype='float32')
- k = arange(c.length, dtype='float32')
- c.norm = a
- decrease = sum((a[1:] - a [0]) / k[1:]) / sum(a[1:])
- assert_almost_equal (decrease, o(c), decimal = 5)
-
- a = arange(0, c.length * 2, +2, dtype='float32')
- c.norm = a
- decrease = sum((a[1:] - a [0]) / k[1:]) / sum(a[1:])
- assert_almost_equal (decrease, o(c), decimal = 5)
-
- a = arange(0, c.length * 2, +2, dtype='float32')
- c.norm = a * 2
- decrease = sum((a[1:] - a [0]) / k[1:]) / sum(a[1:])
- assert_almost_equal (decrease, o(c), decimal = 5)
-
- def test_rolloff(self):
- o = specdesc("rolloff")
- c = cvec()
- assert_equal( 0., o(c))
- a = arange(c.length * 2, 0, -2, dtype='float32')
- k = arange(c.length, dtype='float32')
- c.norm = a
- cumsum = .95*sum(a*a)
- i = 0; rollsum = 0
- while rollsum < cumsum:
- rollsum += a[i]*a[i]
- i+=1
- rolloff = i
- assert_equal (rolloff, o(c))
-
-
-if __name__ == '__main__':
- from unittest import main
- main()
--- /dev/null
+++ b/python.old/README
@@ -1,0 +1,30 @@
+# Here you will find some examples of python scripts and some evaluation
+# routines. The python interface for libaubio is generated using Swig.
+
+# To have it working before installation, you will need to set LD_LIBRARY_PATH.
+# for instance, to run the python script from within aubio/python/, you can use
+# '. README'
+
+export LD_LIBRARY_PATH=../src/.libs:../ext/.libs
+export PYTHONPATH=aubio/.libs
+
+echo """
+
+the aubio/ directory should be organised as follow:
+
+ aubiowrapper.py,_aubiowrapper.so, aubio_wrap.c, aubio_wrap.o
+ swig generated aubio interface
+ aubioclass.py
+ human usable interface
+ plot/
+ everything required to plot
+ web/
+ tools to use aubioweb.py
+ bench/
+ tools to explore a database of sound file and run benchmarks on it
+ eval/
+ tools to evaluate the performance of aubio extractors
+ aubioweb.py
+ a hack to pipe aubio in mod_python
+
+"""
--- /dev/null
+++ b/python.old/aubio/__init__.py
@@ -1,0 +1,28 @@
+"""Copyright (C) 2004 Paul Brossier <piem@altern.org>
+print aubio.__LICENSE__ for the terms of use
+"""
+
+__LICENSE__ = """\
+ Copyright (C) 2004-2009 Paul Brossier <piem@aubio.org>
+
+ This file is part of aubio.
+
+ aubio is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ aubio is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with aubio. If not, see <http://www.gnu.org/licenses/>.
+"""
+
+#from aubioclass import *
+#from onsetcompare import *
+#from median import *
+#from noteroc import *
+#from txtfile import *
--- /dev/null
+++ b/python.old/aubio/aubioclass.py
@@ -1,0 +1,160 @@
+from aubiowrapper import *
+
+class fvec:
+ def __init__(self,size):
+ self.vec = new_fvec(size)
+ def __call__(self):
+ return self.vec
+ def __del__(self):
+ del_fvec(self())
+ def get(self,pos):
+ return fvec_read_sample(self(),pos)
+ def set(self,value,pos):
+ return fvec_write_sample(self(),value,pos)
+ def data(self):
+ return fvec_get_data(self())
+
+class cvec:
+ def __init__(self,size):
+ self.vec = new_cvec(size)
+ def __call__(self):
+ return self.vec
+ def __del__(self):
+ del_cvec(self())
+ def get(self,pos):
+ return self.get_norm(pos)
+ def set(self,val,pos):
+ self.set_norm(val,pos)
+ def get_norm(self,pos):
+ return cvec_read_norm(self(),pos)
+ def set_norm(self,val,pos):
+ cvec_write_norm(self(),val,pos)
+ def get_phas(self,pos):
+ return cvec_read_phas(self(),pos)
+ def set_phas(self,val,pos):
+ cvec_write_phas(self(),val,pos)
+
+class sndfile:
+ def __init__(self,filename,model=None):
+ if (model!=None):
+ self.file = new_aubio_sndfile_wo(model.file,filename)
+ else:
+ self.file = new_aubio_sndfile_ro(filename)
+ if self.file == None:
+ raise IOError, "failed opening file %s" % filename
+ def __del__(self):
+ if self.file != None: del_aubio_sndfile(self.file)
+ def info(self):
+ aubio_sndfile_info(self.file)
+ def samplerate(self):
+ return aubio_sndfile_samplerate(self.file)
+ def channels(self):
+ return aubio_sndfile_channels(self.file)
+ def read(self,nfram,vecread):
+ return aubio_sndfile_read_mono(self.file,nfram,vecread())
+ def write(self,nfram,vecwrite):
+ return aubio_sndfile_write(self.file,nfram,vecwrite())
+
+class pvoc:
+ def __init__(self,buf,hop):
+ self.pv = new_aubio_pvoc(buf,hop)
+ def __del__(self):
+ del_aubio_pvoc(self.pv)
+ def do(self,tf,tc):
+ aubio_pvoc_do(self.pv,tf(),tc())
+ def rdo(self,tc,tf):
+ aubio_pvoc_rdo(self.pv,tc(),tf())
+
+class onsetdetection:
+ """ class for aubio_specdesc """
+ def __init__(self,mode,buf):
+ self.od = new_aubio_specdesc(mode,buf)
+ def do(self,tc,tf):
+ aubio_specdesc_do(self.od,tc(),tf())
+ def __del__(self):
+ del_aubio_specdesc(self.od)
+
+class peakpick:
+ """ class for aubio_peakpicker """
+ def __init__(self,threshold=0.1):
+ self.pp = new_aubio_peakpicker()
+ self.out = new_fvec(1)
+ aubio_peakpicker_set_threshold (self.pp, threshold)
+ def do(self,fv):
+ aubio_peakpicker_do(self.pp, fv(), self.out)
+ return fvec_read_sample(self.out, 0)
+ def getval(self):
+ return aubio_peakpicker_get_adaptive_threshold(self.pp)
+ def __del__(self):
+ del_aubio_peakpicker(self.pp)
+
+class onsetpick:
+ """ superclass for aubio_pvoc + aubio_specdesc + aubio_peakpicker """
+ def __init__(self,bufsize,hopsize,myvec,threshold,mode='dual',derivate=False,dcthreshold=0):
+ self.myfft = cvec(bufsize)
+ self.pv = pvoc(bufsize,hopsize)
+ if mode in ['dual'] :
+ self.myod = onsetdetection("hfc",bufsize)
+ self.myod2 = onsetdetection("mkl",bufsize)
+ self.myonset = fvec(1)
+ self.myonset2 = fvec(1)
+ else:
+ self.myod = onsetdetection(mode,bufsize)
+ self.myonset = fvec(1)
+ self.mode = mode
+ self.pp = peakpick(float(threshold))
+ self.derivate = derivate
+ self.dcthreshold = dcthreshold
+ self.oldval = 0.
+
+ def do(self,myvec):
+ self.pv.do(myvec,self.myfft)
+ self.myod.do(self.myfft,self.myonset)
+ if self.mode == 'dual':
+ self.myod2.do(self.myfft,self.myonset2)
+ self.myonset.set(self.myonset.get(0)*self.myonset2.get(0),0)
+ if self.derivate:
+ val = self.myonset.get(0)
+ dval = val - self.oldval
+ self.oldval = val
+ if dval > 0: self.myonset.set(dval,0)
+ else: self.myonset.set(0.,0,0)
+ isonset, dval = self.pp.do(self.myonset),self.myonset.get(0)
+ if self.dcthreshold:
+ if dval < self.dcthreshold: isonset = 0
+ return isonset, dval
+
+class pitch:
+ def __init__(self,mode="mcomb",bufsize=2048,hopsize=1024,
+ samplerate=44100.,omode="freq",tolerance=0.1):
+ self.pitchp = new_aubio_pitch(mode,bufsize,hopsize,
+ samplerate)
+ self.mypitch = fvec(1)
+ aubio_pitch_set_unit(self.pitchp,omode)
+ aubio_pitch_set_tolerance(self.pitchp,tolerance)
+ #self.filt = filter(srate,"adsgn")
+ def __del__(self):
+ del_aubio_pitch(self.pitchp)
+ def __call__(self,myvec):
+ aubio_pitch_do(self.pitchp,myvec(), self.mypitch())
+ return self.mypitch.get(0)
+
+class filter:
+ def __init__(self,srate,type=None):
+ if (type=="adsgn"):
+ self.filter = new_aubio_adsgn_filter(srate)
+ def __del__(self):
+ #del_aubio_filter(self.filter)
+ pass
+ def __call__(self,myvec):
+ aubio_filter_do(self.filter,myvec())
+
+class beattracking:
+ """ class for aubio_beattracking """
+ def __init__(self,winlen,channels):
+ self.p = new_aubio_beattracking(winlen,channels)
+ def do(self,dfframe,out):
+ return aubio_beattracking_do(self.p,dfframe(),out())
+ def __del__(self):
+ del_aubio_beattracking(self.p)
+
--- /dev/null
+++ b/python.old/aubio/bench/broadcast.py
@@ -1,0 +1,25 @@
+from config import *
+
+class run_broadcast:
+ def __init__(self,command,*args):
+ for host in REMOTEHOSTS:
+ command(host,args[0],args[1:])
+
+def remote_sync(host,path='',options=''):
+ optstring = ''
+ for i in options:
+ optstring = "%s %s" % (optstring,i)
+ print RSYNC_CMD,optstring,RSYNC_OPT,' --delete',
+ print '%s%s%s%s%s' % (path,'/ ',host,':',path)
+
+
+def fetch_results(host,path='',options=''):
+ optstring = ''
+ for i in options:
+ optstring = "%s %s" % (optstring,i)
+ print RSYNC_CMD,optstring,RSYNC_OPT,' --update',
+ print '%s%s%s%s%s' % (host,':',path,'/ ',path)
+
+def remote_queue(host,command,options=''):
+ print 'oarsub -p "hostname = \'',host,'\'',command
+
--- /dev/null
+++ b/python.old/aubio/bench/config.py
@@ -1,0 +1,22 @@
+
+filefound = 0
+try:
+ filename = "/etc/aubio-bench.conf"
+ execfile(filename)
+ filefound = 1
+except IOError:
+ print "no system wide configuration file found in", filename
+
+try:
+ import os
+ filename = "%s%s%s" % (os.getenv('HOME'),os.sep,".aubio-bench.conf")
+ execfile(filename)
+ filefound = 1
+except IOError:
+ #print "no user configuration file found in", filename
+ pass
+
+if filefound == 0:
+ import sys
+ print "error: no configuration file found at all"
+ sys.exit(1)
--- /dev/null
+++ b/python.old/aubio/bench/node.py
@@ -1,0 +1,224 @@
+from config import *
+import commands,sys
+import re
+
+def runcommand(cmd,debug=0):
+ if VERBOSE >= VERBOSE_CMD or debug: print cmd
+ if debug: return
+ status, output = commands.getstatusoutput(cmd)
+ if status == 0 or VERBOSE >= VERBOSE_OUT:
+ output = output.split('\n')
+ if VERBOSE >= VERBOSE_OUT:
+ for i in output:
+ if i: print i
+ if not status == 0:
+ print 'error:',status,output
+ print 'command returning error was',cmd
+ #sys.exit(1)
+ if output == '' or output == ['']: return
+ return output
+
+def list_files(datapath,filter='f', maxdepth = -1):
+ if not os.path.exists(datapath):
+ print "ERR: no directory %s were found" % datapath
+ sys.exit(1)
+ if maxdepth >= 0: maxstring = " -maxdepth %d " % maxdepth
+ else: maxstring = ""
+ cmd = '%s' * 6 % ('find ',datapath,maxstring,' -type ',filter, "| sort -n")
+ return runcommand(cmd)
+
+def list_wav_files(datapath,maxdepth = -1):
+ return list_files(datapath, filter="f -name '*.wav'",maxdepth = maxdepth)
+
+sndfile_filter = "f -name '*.wav' -o -name '*.aif' -o -name '*.aiff'"
+
+def list_snd_files(datapath,maxdepth = -1):
+ return list_files(datapath, filter=sndfile_filter,
+ maxdepth = maxdepth)
+
+def list_res_files(datapath,maxdepth = -1):
+ return list_files(datapath, filter="f -name '*.txt'", maxdepth = maxdepth)
+
+def list_dirs(datapath):
+ return list_files(datapath, filter="d")
+
+def mkdir(path):
+ cmd = '%s%s' % ('mkdir -p ',path)
+ return runcommand(cmd)
+
+def act_on_data (action,datapath,respath=None,suffix='.txt',filter='f',sub='\.wav$',**keywords):
+ """ execute action(datafile,resfile) on all files in datapath """
+ dirlist = list_files(datapath,filter=filter)
+ if dirlist == ['']: dirlist = []
+ if respath:
+ respath_in_datapath = re.split(datapath, respath,maxsplit=1)[1:]
+ if(respath_in_datapath and suffix == ''):
+ print 'error: respath in datapath and no suffix used'
+ for i in dirlist:
+ j = re.split(datapath, i,maxsplit=1)[1]
+ j = re.sub(sub,'',j)
+ #j = "%s%s%s"%(respath,j,suffix)
+ if respath:
+ j = "%s%s"%(respath,j)
+ if sub != '':
+ j = re.sub(sub,suffix,j)
+ else:
+ j = "%s%s" % (j,suffix)
+ action(i,j,**keywords)
+
+def act_on_results (action,datapath,respath,filter='d'):
+ """ execute action(respath) an all subdirectories in respath """
+ dirlist = list_files(datapath,filter='d')
+ respath_in_datapath = re.split(datapath, respath,maxsplit=1)[1:]
+ if(respath_in_datapath and not filter == 'd' and suffix == ''):
+ print 'warning: respath is in datapath'
+ for i in dirlist:
+ s = re.split(datapath, i ,maxsplit=1)[1]
+ action("%s%s%s"%(respath,'/',s))
+
+def act_on_files (action,listfiles,listres=None,suffix='.txt',filter='f',sub='\.wav$',**keywords):
+ """ execute action(respath) an all subdirectories in respath """
+ if listres and len(listfiles) <= len(listres):
+ for i in range(len(listfiles)):
+ action(listfiles[i],listres[i],**keywords)
+ else:
+ for i in listfiles:
+ action(i,None,**keywords)
+
+class bench:
+ """ class to run benchmarks on directories """
+ def __init__(self,datadir,resdir=None,checkres=False,checkanno=False,params=[]):
+ from aubio.task.params import taskparams
+ self.datadir = datadir
+ # path to write results path to
+ self.resdir = resdir
+ # list of annotation files
+ self.reslist = []
+ # list used to gather results
+ self.results = []
+ if not params: self.params = taskparams()
+ else: self.params = params
+ print "Checking data directory", self.datadir
+ self.checkdata()
+ if checkanno: self.checkanno()
+ if checkres: self.checkres()
+
+ def checkdata(self):
+ if os.path.isfile(self.datadir):
+ self.dirlist = os.path.dirname(self.datadir)
+ elif os.path.isdir(self.datadir):
+ self.dirlist = list_dirs(self.datadir)
+ # allow dir* matching through find commands?
+ else:
+ print "ERR: path not understood"
+ sys.exit(1)
+ print "Listing directories in data directory",
+ if self.dirlist:
+ print " (%d elements)" % len(self.dirlist)
+ else:
+ print " (0 elements)"
+ print "ERR: no directory %s were found" % self.datadir
+ sys.exit(1)
+ print "Listing sound files in data directory",
+ self.sndlist = list_snd_files(self.datadir)
+ if self.sndlist:
+ print " (%d elements)" % len(self.sndlist)
+ else:
+ print " (0 elements)"
+ print "ERR: no sound files were found in", self.datadir
+ sys.exit(1)
+
+ def checkanno(self):
+ print "Listing annotations in data directory",
+ self.reslist = list_res_files(self.datadir)
+ print " (%d elements)" % len(self.reslist)
+ #for each in self.reslist: print each
+ if not self.reslist or len(self.reslist) < len (self.sndlist):
+ print "ERR: not enough annotations"
+ return -1
+ else:
+ print "Found enough annotations"
+
+ def checkres(self):
+ print "Creating results directory"
+ act_on_results(mkdir,self.datadir,self.resdir,filter='d')
+
+ def pretty_print(self,sep='|'):
+ for i in self.printnames:
+ print self.formats[i] % self.v[i], sep,
+
+ def pretty_titles(self,sep='|'):
+ for i in self.printnames:
+ print self.formats[i] % i, sep,
+
+ def dir_exec(self):
+ """ run file_exec on every input file """
+ self.l , self.labs = [], []
+ self.v = {}
+ for i in self.valuenames:
+ self.v[i] = []
+ for i in self.valuelists:
+ self.v[i] = []
+ act_on_files(self.file_exec,self.sndlist,self.reslist, \
+ suffix='',filter=sndfile_filter)
+
+ def dir_eval(self):
+ pass
+
+ def file_gettruth(self,input):
+ """ get ground truth filenames """
+ from os.path import isfile
+ ftrulist = []
+ # search for match as filetask.input,".txt"
+ ftru = '.'.join(input.split('.')[:-1])
+ ftru = '.'.join((ftru,'txt'))
+ if isfile(ftru):
+ ftrulist.append(ftru)
+ else:
+ # search for matches for filetask.input in the list of results
+ for i in range(len(self.reslist)):
+ check = '.'.join(self.reslist[i].split('.')[:-1])
+ check = '_'.join(check.split('_')[:-1])
+ if check == '.'.join(input.split('.')[:-1]):
+ ftrulist.append(self.reslist[i])
+ return ftrulist
+
+ def file_exec(self,input,output):
+ """ create filetask, extract data, evaluate """
+ filetask = self.task(input,params=self.params)
+ computed_data = filetask.compute_all()
+ ftrulist = self.file_gettruth(filetask.input)
+ for i in ftrulist:
+ filetask.eval(computed_data,i,mode='rocloc',vmode='')
+ """ append filetask.v to self.v """
+ for i in self.valuenames:
+ self.v[i].append(filetask.v[i])
+ for j in self.valuelists:
+ if filetask.v[j]:
+ for i in range(len(filetask.v[j])):
+ self.v[j].append(filetask.v[j][i])
+
+ def file_eval(self):
+ pass
+
+ def file_plot(self):
+ pass
+
+ def dir_plot(self):
+ pass
+
+ def run_bench(self):
+ for mode in self.modes:
+ self.params.mode = mode
+ self.dir_exec()
+ self.dir_eval()
+ self.dir_plot()
+
+ def dir_eval_print(self):
+ self.dir_exec()
+ self.dir_eval()
+ self.pretty_print()
+
--- /dev/null
+++ b/python.old/aubio/bench/onset.py
@@ -1,0 +1,303 @@
+
+from aubio.bench.node import *
+from os.path import dirname,basename
+
+def mmean(l):
+ return sum(l)/max(float(len(l)),1)
+
+def stdev(l):
+ smean = 0
+ if not len(l): return smean
+ lmean = mmean(l)
+ for i in l:
+ smean += (i-lmean)**2
+ smean *= 1. / len(l)
+ return smean**.5
+
+class benchonset(bench):
+
+ """ list of values to store per file """
+ valuenames = ['orig','missed','Tm','expc','bad','Td']
+ """ list of lists to store per file """
+ valuelists = ['l','labs']
+ """ list of values to print per dir """
+ printnames = [ 'mode', 'thres', 'dist', 'prec', 'recl',
+ 'GD', 'FP',
+ 'Torig', 'Ttrue', 'Tfp', 'Tfn', 'TTm', 'TTd',
+ 'aTtrue', 'aTfp', 'aTfn', 'aTm', 'aTd',
+ 'mean', 'smean', 'amean', 'samean']
+
+ """ per dir """
+ formats = {'mode': "%12s" , 'thres': "%5.4s",
+ 'dist': "%5.4s", 'prec': "%5.4s", 'recl': "%5.4s",
+ 'Torig': "%5.4s", 'Ttrue': "%5.4s", 'Tfp': "%5.4s", 'Tfn': "%5.4s",
+ 'TTm': "%5.4s", 'TTd': "%5.4s",
+ 'aTtrue':"%5.4s", 'aTfp': "%5.4s", 'aTfn': "%5.4s",
+ 'aTm': "%5.4s", 'aTd': "%5.4s",
+ 'mean': "%5.6s", 'smean': "%5.6s",
+ 'amean': "%5.6s", 'samean': "%5.6s",
+ "GD": "%5.4s", "FP": "%5.4s",
+ "GDm": "%5.4s", "FPd": "%5.4s",
+ "bufsize": "%5.4s", "hopsize": "%5.4s",
+ "time": "%5.4s"}
+
+ def dir_eval(self):
+ """ evaluate statistical data over the directory """
+ v = self.v
+
+ v['mode'] = self.params.onsetmode
+ v['thres'] = self.params.threshold
+ v['bufsize'] = self.params.bufsize
+ v['hopsize'] = self.params.hopsize
+ v['silence'] = self.params.silence
+ v['mintol'] = self.params.mintol
+
+ v['Torig'] = sum(v['orig'])
+ v['TTm'] = sum(v['Tm'])
+ v['TTd'] = sum(v['Td'])
+ v['Texpc'] = sum(v['expc'])
+ v['Tbad'] = sum(v['bad'])
+ v['Tmissed'] = sum(v['missed'])
+ v['aTm'] = mmean(v['Tm'])
+ v['aTd'] = mmean(v['Td'])
+
+ v['mean'] = mmean(v['l'])
+ v['smean'] = stdev(v['l'])
+
+ v['amean'] = mmean(v['labs'])
+ v['samean'] = stdev(v['labs'])
+
+ # old type calculations
+ # good detection rate
+ v['GD'] = 100.*(v['Torig']-v['Tmissed']-v['TTm'])/v['Torig']
+ # false positive rate
+ v['FP'] = 100.*(v['Tbad']+v['TTd'])/v['Torig']
+ # good detection counting merged detections as good
+ v['GDm'] = 100.*(v['Torig']-v['Tmissed'])/v['Torig']
+ # false positives counting doubled as good
+ v['FPd'] = 100.*v['Tbad']/v['Torig']
+
+ # mirex type annotations
+ totaltrue = v['Texpc']-v['Tbad']-v['TTd']
+ totalfp = v['Tbad']+v['TTd']
+ totalfn = v['Tmissed']+v['TTm']
+ self.v['Ttrue'] = totaltrue
+ self.v['Tfp'] = totalfp
+ self.v['Tfn'] = totalfn
+ # average over the number of annotation files
+ N = float(len(self.reslist))
+ self.v['aTtrue'] = totaltrue/N
+ self.v['aTfp'] = totalfp/N
+ self.v['aTfn'] = totalfn/N
+
+ # F-measure
+ self.P = 100.*float(totaltrue)/max(totaltrue + totalfp,1)
+ self.R = 100.*float(totaltrue)/max(totaltrue + totalfn,1)
+ #if self.R < 0: self.R = 0
+ self.F = 2.* self.P*self.R / max(float(self.P+self.R),1)
+ self.v['dist'] = self.F
+ self.v['prec'] = self.P
+ self.v['recl'] = self.R
+
+
+ """
+ Plot functions
+ """
+
+ def plotroc(self,d,plottitle=""):
+ import Gnuplot, Gnuplot.funcutils
+ gd = []
+ fp = []
+ for i in self.vlist:
+ gd.append(i['GD'])
+ fp.append(i['FP'])
+ d.append(Gnuplot.Data(fp, gd, with_='linespoints',
+ title="%s %s" % (plottitle,i['mode']) ))
+
+ def plotplotroc(self,d,outplot=0,extension='ps'):
+ import Gnuplot, Gnuplot.funcutils
+ from sys import exit
+ g = Gnuplot.Gnuplot(debug=0, persist=1)
+ if outplot:
+ if extension == 'ps': ext, extension = '.ps' , 'postscript'
+ elif extension == 'png': ext, extension = '.png', 'png'
+ elif extension == 'svg': ext, extension = '.svg', 'svg'
+ else: exit("ERR: unknown plot extension")
+ g('set terminal %s' % extension)
+ g('set output \'roc-%s%s\'' % (outplot,ext))
+ xmax = 30 #max(fp)
+ ymin = 50
+ g('set xrange [0:%f]' % xmax)
+ g('set yrange [%f:100]' % ymin)
+ # grid set
+ g('set grid')
+ g('set xtics 0,5,%f' % xmax)
+ g('set ytics %f,5,100' % ymin)
+ g('set key 27,65')
+ #g('set format \"%g\"')
+ g.title(basename(self.datadir))
+ g.xlabel('false positives (%)')
+ g.ylabel('correct detections (%)')
+ g.plot(*d)
+
+ def plotpr(self,d,plottitle=""):
+ import Gnuplot, Gnuplot.funcutils
+ x = []
+ y = []
+ for i in self.vlist:
+ x.append(i['prec'])
+ y.append(i['recl'])
+ d.append(Gnuplot.Data(x, y, with_='linespoints',
+ title="%s %s" % (plottitle,i['mode']) ))
+
+ def plotplotpr(self,d,outplot=0,extension='ps'):
+ import Gnuplot, Gnuplot.funcutils
+ from sys import exit
+ g = Gnuplot.Gnuplot(debug=0, persist=1)
+ if outplot:
+ if extension == 'ps': ext, extension = '.ps' , 'postscript'
+ elif extension == 'png': ext, extension = '.png', 'png'
+ elif extension == 'svg': ext, extension = '.svg', 'svg'
+ else: exit("ERR: unknown plot extension")
+ g('set terminal %s' % extension)
+ g('set output \'pr-%s%s\'' % (outplot,ext))
+ g.title(basename(self.datadir))
+ g.xlabel('Recall (%)')
+ g.ylabel('Precision (%)')
+ g.plot(*d)
+
+ def plotfmeas(self,d,plottitle=""):
+ import Gnuplot, Gnuplot.funcutils
+ x,y = [],[]
+ for i in self.vlist:
+ x.append(i['thres'])
+ y.append(i['dist'])
+ d.append(Gnuplot.Data(x, y, with_='linespoints',
+ title="%s %s" % (plottitle,i['mode']) ))
+
+ def plotplotfmeas(self,d,outplot="",extension='ps', title="F-measure"):
+ import Gnuplot, Gnuplot.funcutils
+ from sys import exit
+ g = Gnuplot.Gnuplot(debug=0, persist=1)
+ if outplot:
+ if extension == 'ps': terminal = 'postscript'
+ elif extension == 'png': terminal = 'png'
+ elif extension == 'svg': terminal = 'svg'
+ else: exit("ERR: unknown plot extension")
+ g('set terminal %s' % terminal)
+ g('set output \'fmeas-%s.%s\'' % (outplot,extension))
+ g.xlabel('threshold \\delta')
+ g.ylabel('F-measure (%)')
+ g('set xrange [0:1.2]')
+ g('set yrange [0:100]')
+ g.title(basename(self.datadir))
+ # grid set
+ #g('set grid')
+ #g('set xtics 0,5,%f' % xmax)
+ #g('set ytics %f,5,100' % ymin)
+ #g('set key 27,65')
+ #g('set format \"%g\"')
+ g.plot(*d)
+
+ def plotfmeasvar(self,d,var,plottitle=""):
+ import Gnuplot, Gnuplot.funcutils
+ x,y = [],[]
+ for i in self.vlist:
+ x.append(i[var])
+ y.append(i['dist'])
+ d.append(Gnuplot.Data(x, y, with_='linespoints',
+ title="%s %s" % (plottitle,i['mode']) ))
+
+ def plotplotfmeasvar(self,d,var,outplot="",extension='ps', title="F-measure"):
+ import Gnuplot, Gnuplot.funcutils
+ from sys import exit
+ g = Gnuplot.Gnuplot(debug=0, persist=1)
+ if outplot:
+ if extension == 'ps': terminal = 'postscript'
+ elif extension == 'png': terminal = 'png'
+ elif extension == 'svg': terminal = 'svg'
+ else: exit("ERR: unknown plot extension")
+ g('set terminal %s' % terminal)
+ g('set output \'fmeas-%s.%s\'' % (outplot,extension))
+ g.xlabel(var)
+ g.ylabel('F-measure (%)')
+ #g('set xrange [0:1.2]')
+ g('set yrange [0:100]')
+ g.title(basename(self.datadir))
+ g.plot(*d)
+
+ def plotdiffs(self,d,plottitle=""):
+ import Gnuplot, Gnuplot.funcutils
+ v = self.v
+ l = v['l']
+ mean = v['mean']
+ smean = v['smean']
+ amean = v['amean']
+ samean = v['samean']
+ val = []
+ per = [0] * 100
+ for i in range(0,100):
+ val.append(i*.001-.05)
+ for j in l:
+ if abs(j-val[i]) <= 0.001:
+ per[i] += 1
+ total = v['Torig']
+ for i in range(len(per)): per[i] /= total/100.
+
+ d.append(Gnuplot.Data(val, per, with_='fsteps',
+ title="%s %s" % (plottitle,v['mode']) ))
+ #d.append('mean=%f,sigma=%f,eps(x) title \"\"'% (mean,smean))
+ #d.append('mean=%f,sigma=%f,eps(x) title \"\"'% (amean,samean))
+
+
+ def plotplotdiffs(self,d,outplot=0,extension='ps'):
+ import Gnuplot, Gnuplot.funcutils
+ from sys import exit
+ g = Gnuplot.Gnuplot(debug=0, persist=1)
+ if outplot:
+ if extension == 'ps': ext, extension = '.ps' , 'postscript'
+ elif extension == 'png': ext, extension = '.png', 'png'
+ elif extension == 'svg': ext, extension = '.svg', 'svg'
+ else: exit("ERR: unknown plot extension")
+ g('set terminal %s' % extension)
+ g('set output \'diffhist-%s%s\'' % (outplot,ext))
+ g('eps(x) = 1./(sigma*(2.*3.14159)**.5) * exp ( - ( x - mean ) ** 2. / ( 2. * sigma ** 2. ))')
+ g.title(basename(self.datadir))
+ g.xlabel('delay to hand-labelled onset (s)')
+ g.ylabel('% number of correct detections / ms ')
+ g('set xrange [-0.05:0.05]')
+ g('set yrange [0:20]')
+ g.plot(*d)
+
+
+ def plothistcat(self,d,plottitle=""):
+ import Gnuplot, Gnuplot.funcutils
+ total = v['Torig']
+ for i in range(len(per)): per[i] /= total/100.
+
+ d.append(Gnuplot.Data(val, per, with_='fsteps',
+ title="%s %s" % (plottitle,v['mode']) ))
+ #d.append('mean=%f,sigma=%f,eps(x) title \"\"'% (mean,smean))
+ #d.append('mean=%f,sigma=%f,eps(x) title \"\"'% (amean,samean))
+
+
+ def plotplothistcat(self,d,outplot=0,extension='ps'):
+ import Gnuplot, Gnuplot.funcutils
+ from sys import exit
+ g = Gnuplot.Gnuplot(debug=0, persist=1)
+ if outplot:
+ if extension == 'ps': ext, extension = '.ps' , 'postscript'
+ elif extension == 'png': ext, extension = '.png', 'png'
+ elif extension == 'svg': ext, extension = '.svg', 'svg'
+ else: exit("ERR: unknown plot extension")
+ g('set terminal %s' % extension)
+ g('set output \'diffhist-%s%s\'' % (outplot,ext))
+ g('eps(x) = 1./(sigma*(2.*3.14159)**.5) * exp ( - ( x - mean ) ** 2. / ( 2. * sigma ** 2. ))')
+ g.title(basename(self.datadir))
+ g.xlabel('delay to hand-labelled onset (s)')
+ g.ylabel('% number of correct detections / ms ')
+ g('set xrange [-0.05:0.05]')
+ g('set yrange [0:20]')
+ g.plot(*d)
+
+
--- /dev/null
+++ b/python.old/aubio/gnuplot.py
@@ -1,0 +1,222 @@
+"""Copyright (C) 2004 Paul Brossier <piem@altern.org>
+print aubio.__LICENSE__ for the terms of use
+"""
+
+__LICENSE__ = """\
+ Copyright (C) 2004-2009 Paul Brossier <piem@aubio.org>
+
+ This file is part of aubio.
+
+ aubio is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ aubio is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with aubio. If not, see <http://www.gnu.org/licenses/>.
+"""
+
+
+def audio_to_array(filename):
+ import aubio.aubioclass
+ from numpy import arange
+ hopsize = 2048
+ filei = aubio.aubioclass.sndfile(filename)
+ framestep = 1/(filei.samplerate()+0.)
+ channels = filei.channels()
+ myvec = aubio.aubioclass.fvec(hopsize,channels)
+ data = []
+ readsize = hopsize
+ while (readsize==hopsize):
+ readsize = filei.read(hopsize,myvec)
+ #for i in range(channels):
+ i = 0
+ curpos = 0
+ while (curpos < readsize):
+ data.append(myvec.get(curpos,i))
+ curpos+=1
+ time = arange(len(data))*framestep
+ return time,data
+
+def plot_audio(filenames, g, options):
+ todraw = len(filenames)
+ xorig = 0.
+ xratio = 1./todraw
+ g('set multiplot;')
+ while (len(filenames)):
+ time,data = audio_to_array(filenames.pop(0))
+ if todraw==1:
+ if max(time) < 1.:
+ time = [t*1000. for t in time]
+ g.xlabel('Time (ms)')
+ else:
+ g.xlabel('Time (s)')
+ g.ylabel('Amplitude')
+ curplot = make_audio_plot(time,data)
+ g('set size %f,%f;' % (options.xsize*xratio,options.ysize) )
+ g('set origin %f,0.;' % (xorig) )
+ g('set style data lines; \
+ set yrange [-1.:1.]; \
+ set xrange [0:%f]' % time[-1])
+ g.plot(curplot)
+ xorig += options.xsize*xratio
+ g('unset multiplot;')
+
+def audio_to_spec(filename,minf = 0, maxf = 0, lowthres = -20.,
+ bufsize= 8192, hopsize = 1024):
+ from aubioclass import fvec,cvec,pvoc,sndfile
+ from math import log10
+ filei = sndfile(filename)
+ srate = float(filei.samplerate())
+ framestep = hopsize/srate
+ freqstep = srate/bufsize
+ channels = filei.channels()
+ myvec = fvec(hopsize,channels)
+ myfft = cvec(bufsize,channels)
+ pv = pvoc(bufsize,hopsize,channels)
+ data,time,freq = [],[],[]
+
+ if maxf == 0.: maxf = bufsize/2
+ else: maxf = int(maxf/freqstep)
+ if minf: minf = int(minf/freqstep)
+ else: minf = 0
+
+ for f in range(minf,maxf):
+ freq.append(f*freqstep)
+ readsize = hopsize
+ frameread = 0
+ while (readsize==hopsize):
+ readsize = filei.read(hopsize,myvec)
+ pv.do(myvec,myfft)
+ frame = []
+ i = 0 #for i in range(channels):
+ curpos = minf
+ while (curpos < maxf):
+ frame.append(max(lowthres,20.*log10(myfft.get(curpos,i)**2+0.00001)))
+ curpos+=1
+ time.append(frameread*framestep)
+ data.append(frame)
+ frameread += 1
+ # crop data if unfinished frames
+ if len(data[-1]) != len(data[0]):
+ data = data[0:-2]
+ time = time[0:-2]
+ # verify size consistency
+ assert len(data) == len(time)
+ assert len(data[0]) == len(freq)
+ return data,time,freq
+
+def plot_spec(filename, g, options):
+ import Gnuplot
+ data,time,freq = audio_to_spec(filename,
+ minf=options.minf,maxf=options.maxf,
+ bufsize=options.bufsize,hopsize=options.hopsize)
+ xorig = 0.
+ if max(time) < 1.:
+ time = [t*1000. for t in time]
+ g.xlabel('Time (ms)')
+ else:
+ g.xlabel('Time (s)')
+ if options.xsize < 0.5 and not options.log and max(time) > 1.:
+ freq = [f/1000. for f in freq]
+ options.minf /= 1000.
+ options.maxf /= 1000.
+ g.ylabel('Frequency (kHz)')
+ else:
+ g.ylabel('Frequency (Hz)')
+ g('set pm3d map')
+ g('set palette rgbformulae -25,-24,-32')
+ g('set cbtics 20')
+ #g('set colorbox horizontal')
+ g('set xrange [0.:%f]' % time[-1])
+ if options.log:
+ g('set log y')
+ g('set yrange [%f:%f]' % (max(10,options.minf),options.maxf))
+ else:
+ g('set yrange [%f:%f]' % (options.minf,options.maxf))
+ g.splot(Gnuplot.GridData(data,time,freq, binary=1))
+ #xorig += 1./todraw
+
+def downsample_audio(time,data,maxpoints=10000):
+ """ resample audio data to last only maxpoints """
+ from numpy import array, resize
+ length = len(time)
+ downsample = length/maxpoints
+ if downsample == 0: downsample = 1
+ x = resize(array(time),length)[0:-1:downsample]
+ y = resize(array(data),length)[0:-1:downsample]
+ return x,y
+
+def make_audio_plot(time,data,maxpoints=10000):
+ """ create gnuplot plot from an audio file """
+ import Gnuplot, Gnuplot.funcutils
+ x,y = downsample_audio(time,data,maxpoints=maxpoints)
+ return Gnuplot.Data(x,y,with_='lines')
+
+def make_audio_envelope(time,data,maxpoints=10000):
+ """ create gnuplot plot from an audio file """
+ from numpy import array
+ import Gnuplot, Gnuplot.funcutils
+ bufsize = 500
+ x = [i.mean() for i in resize(array(time), (len(time)/bufsize,bufsize))]
+ y = [i.mean() for i in resize(array(data), (len(time)/bufsize,bufsize))]
+ x,y = downsample_audio(x,y,maxpoints=maxpoints)
+ return Gnuplot.Data(x,y,with_='lines')
+
+def gnuplot_addargs(parser):
+ """ add common gnuplot argument to OptParser object """
+ parser.add_option("-x","--xsize",
+ action="store", dest="xsize", default=1.,
+ type='float',help="define xsize for plot")
+ parser.add_option("-y","--ysize",
+ action="store", dest="ysize", default=1.,
+ type='float',help="define ysize for plot")
+ parser.add_option("--debug",
+ action="store_true", dest="debug", default=False,
+ help="use gnuplot debug mode")
+ parser.add_option("--persist",
+ action="store_false", dest="persist", default=True,
+ help="do not use gnuplot persistant mode")
+ parser.add_option("--lmargin",
+ action="store", dest="lmargin", default=None,
+ type='int',help="define left margin for plot")
+ parser.add_option("--rmargin",
+ action="store", dest="rmargin", default=None,
+ type='int',help="define right margin for plot")
+ parser.add_option("--bmargin",
+ action="store", dest="bmargin", default=None,
+ type='int',help="define bottom margin for plot")
+ parser.add_option("--tmargin",
+ action="store", dest="tmargin", default=None,
+ type='int',help="define top margin for plot")
+ parser.add_option("-O","--outplot",
+ action="store", dest="outplot", default=None,
+ help="save plot to output.{ps,png}")
+
+def gnuplot_create(outplot='',extension='', options=None):
+ import Gnuplot
+ if options:
+ g = Gnuplot.Gnuplot(debug=options.debug, persist=options.persist)
+ else:
+ g = Gnuplot.Gnuplot(persist=1)
+ if not extension or not outplot: return g
+ if extension == 'ps': ext, extension = '.ps' , 'postscript'
+ elif extension == 'eps': ext, extension = '.eps' , 'postscript enhanced'
+ elif extension == 'epsc': ext, extension = '.eps' , 'postscript enhanced color'
+ elif extension == 'png': ext, extension = '.png', 'png'
+ elif extension == 'svg': ext, extension = '.svg', 'svg'
+ else: exit("ERR: unknown plot extension")
+ g('set terminal %s' % extension)
+ if options and options.lmargin: g('set lmargin %i' % options.lmargin)
+ if options and options.rmargin: g('set rmargin %i' % options.rmargin)
+ if options and options.bmargin: g('set bmargin %i' % options.bmargin)
+ if options and options.tmargin: g('set tmargin %i' % options.tmargin)
+ if outplot != "stdout":
+ g('set output \'%s%s\'' % (outplot,ext))
+ if options: g('set size %f,%f' % (options.xsize, options.ysize))
+ return g
--- /dev/null
+++ b/python.old/aubio/median.py
@@ -1,0 +1,69 @@
+"""Copyright (C) 2004 Paul Brossier <piem@altern.org>
+print aubio.__LICENSE__ for the terms of use
+"""
+
+__LICENSE__ = """\
+ Copyright (C) 2004-2009 Paul Brossier <piem@aubio.org>
+
+ This file is part of aubio.
+
+ aubio is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ aubio is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with aubio. If not, see <http://www.gnu.org/licenses/>.
+"""
+
+"""
+original author Tim Peters
+modified by Paul Brossier <piem@altern.org>
+inspired from http://www.ics.uci.edu/~eppstein/161/python/peters-selection.py
+"""
+
+def short_find(a, rank):
+ """ find the rank-th value in sorted a """
+ # copy to b before sorting
+ b = a[:]
+ b.sort()
+ return b[rank - 1]
+
+def percental(a, rank):
+ """ Find the rank'th-smallest value in a, in worst-case linear time. """
+ n = len(a)
+ assert 1 <= rank <= n
+ if n <= 7:
+ return short_find(a, rank)
+
+ ## Find median of median-of-7's.
+ ##medians = [short_find(a[i : i+7], 4) for i in xrange(0, n-6, 7)]
+ #median = find(medians, (len(medians) + 1) // 2)
+
+ # modified to Find median
+ median = short_find([a[0], a[-1], a[n//2]], 2)
+
+ # Partition around the median.
+ # a[:i] <= median
+ # a[j+1:] >= median
+ i, j = 0, n-1
+ while i <= j:
+ while a[i] < median:
+ i += 1
+ while a[j] > median:
+ j -= 1
+ if i <= j:
+ a[i], a[j] = a[j], a[i]
+ i += 1
+ j -= 1
+
+ if rank <= i:
+ return percental(a[:i], rank)
+ else:
+ return percental(a[i:], rank - i)
+
--- /dev/null
+++ b/python.old/aubio/onsetcompare.py
@@ -1,0 +1,143 @@
+"""Copyright (C) 2004 Paul Brossier <piem@altern.org>
+print aubio.__LICENSE__ for the terms of use
+"""
+
+__LICENSE__ = """\
+ Copyright (C) 2004-2009 Paul Brossier <piem@aubio.org>
+
+ This file is part of aubio.
+
+ aubio is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ aubio is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with aubio. If not, see <http://www.gnu.org/licenses/>.
+"""
+
+""" this file contains routines to compare two lists of onsets or notes.
+it somewhat implements the Receiver Operating Statistic (ROC).
+see http://en.wikipedia.org/wiki/Receiver_operating_characteristic
+"""
+
+def onset_roc(ltru, lexp, eps):
+ """ compute differences between two lists
+ orig = hits + missed + merged
+ expc = hits + bad + doubled
+ returns orig, missed, merged, expc, bad, doubled
+ """
+ orig, expc = len(ltru), len(lexp)
+ # if lexp is empty
+ if expc == 0 : return orig,orig,0,0,0,0
+ missed, bad, doubled, merged = 0, 0, 0, 0
+ # find missed and doubled ones first
+ for x in ltru:
+ correspond = 0
+ for y in lexp:
+ if abs(x-y) <= eps: correspond += 1
+ if correspond == 0: missed += 1
+ elif correspond > 1: doubled += correspond - 1
+ # then look for bad and merged ones
+ for y in lexp:
+ correspond = 0
+ for x in ltru:
+ if abs(x-y) <= eps: correspond += 1
+ if correspond == 0: bad += 1
+ elif correspond > 1: merged += correspond - 1
+ # check consistancy of the results
+ assert ( orig - missed - merged == expc - bad - doubled)
+ return orig, missed, merged, expc, bad, doubled
+
+def onset_diffs(ltru, lexp, eps):
+ """ compute differences between two lists
+ orig = hits + missed + merged
+ expc = hits + bad + doubled
+ returns orig, missed, merged, expc, bad, doubled
+ """
+ orig, expc = len(ltru), len(lexp)
+ # if lexp is empty
+ l = []
+ if expc == 0 : return l
+ # find missed and doubled ones first
+ for x in ltru:
+ correspond = 0
+ for y in lexp:
+ if abs(x-y) <= eps: l.append(y-x)
+ # return list of diffs
+ return l
+
+def onset_rocloc(ltru, lexp, eps):
+ """ compute differences between two lists
+ orig = hits + missed + merged
+ expc = hits + bad + doubled
+ returns orig, missed, merged, expc, bad, doubled
+ """
+ orig, expc = len(ltru), len(lexp)
+ l = []
+ labs = []
+ mean = 0
+ # if lexp is empty
+ if expc == 0 : return orig,orig,0,0,0,0,l,mean
+ missed, bad, doubled, merged = 0, 0, 0, 0
+ # find missed and doubled ones first
+ for x in ltru:
+ correspond = 0
+ for y in lexp:
+ if abs(x-y) <= eps: correspond += 1
+ if correspond == 0: missed += 1
+ elif correspond > 1: doubled += correspond - 1
+ # then look for bad and merged ones
+ for y in lexp:
+ correspond = 0
+ for x in ltru:
+ if abs(x-y) <= eps:
+ correspond += 1
+ l.append(y-x)
+ labs.append(abs(y-x))
+ if correspond == 0: bad += 1
+ elif correspond > 1: merged += correspond - 1
+ # check consistancy of the results
+ assert ( orig - missed - merged == expc - bad - doubled)
+ return orig, missed, merged, expc, bad, doubled, l, labs
+
+def notes_roc (la, lb, eps):
+ from numpy import transpose, add, resize
+ """ creates a matrix of size len(la)*len(lb) then look for hit and miss
+ in it within eps tolerance windows """
+ gdn,fpw,fpg,fpa,fdo,fdp = 0,0,0,0,0,0
+ m = len(la)
+ n = len(lb)
+ x = resize(la[:][0],(n,m))
+ y = transpose(resize(lb[:][0],(m,n)))
+ teps = (abs(x-y) <= eps[0])
+ x = resize(la[:][1],(n,m))
+ y = transpose(resize(lb[:][1],(m,n)))
+ tpitc = (abs(x-y) <= eps[1])
+ res = teps * tpitc
+ res = add.reduce(res,axis=0)
+ for i in range(len(res)) :
+ if res[i] > 1:
+ gdn+=1
+ fdo+=res[i]-1
+ elif res [i] == 1:
+ gdn+=1
+ fpa = n - gdn - fpa
+ return gdn,fpw,fpg,fpa,fdo,fdp
+
+def load_onsets(filename) :
+ """ load onsets targets / candidates files in arrays """
+ l = [];
+
+ f = open(filename,'ro')
+ while 1:
+ line = f.readline().split()
+ if not line : break
+ l.append(float(line[0]))
+
+ return l
--- /dev/null
+++ b/python.old/aubio/plot/keyboard.py
@@ -1,0 +1,46 @@
+
+def draw_keyboard(firstnote = 21, lastnote = 108, y0 = 0, y1 = 1):
+ import Gnuplot
+ octaves = 10
+
+ # build template of white notes
+ scalew = 12/7.
+ xw_temp = [i*scalew for i in range(0,7)]
+ # build template of black notes
+ scaleb = 6/7.
+ xb_temp = [i*scaleb for i in [1,3,7,9,11]]
+
+ xb,xw = [],[]
+ for octave in range(octaves-1):
+ for i in xb_temp:
+ curnote = i+12*octave
+ if curnote > firstnote-1 and curnote < lastnote+1:
+ xb = xb + [curnote]
+ for octave in range(octaves-1):
+ for i in xw_temp:
+ curnote = i+12*octave
+ if curnote > firstnote-1 and curnote < lastnote+1:
+ xw = xw + [curnote]
+
+ xwdelta = [1/2. * scalew for i in range(len(xw))]
+ yw = [y0+(y1-y0)*1/2. for i in range(len(xw))]
+ ywdelta = [(y1-y0)*1/2. for i in range(len(xw))]
+
+ xbdelta = [2/3. * scaleb for i in range(len(xb))]
+ yb = [y0+(y1-y0)*2/3. for i in range(len(xb))]
+ ybdelta = [(y1-y0)*1/3. for i in range(len(xb))]
+
+ whites = Gnuplot.Data(xw,yw,xwdelta,ywdelta,with_ = 'boxxyerrorbars')
+ blacks = Gnuplot.Data(xb,yb,xbdelta,ybdelta,with_ = 'boxxyerrorbars fill solid')
+
+ return blacks,whites
+
+if __name__ == '__main__':
+ from aubio.gnuplot import gnuplot_create
+ blacks,whites = draw_keyboard(firstnote = 21, lastnote = 108)
+ g = gnuplot_create('','')
+ #g('set style fill solid .5')
+ #g('set xrange [60-.5:72+.5]')
+ #g('set yrange [-0.1:1.1]')
+
+ g.plot(whites,blacks)
--- /dev/null
+++ b/python.old/aubio/plot/notes.py
@@ -1,0 +1,90 @@
+__LICENSE__ = """\
+ Copyright (C) 2004-2009 Paul Brossier <piem@aubio.org>
+
+ This file is part of aubio.
+
+ aubio is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ aubio is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with aubio. If not, see <http://www.gnu.org/licenses/>.
+"""
+
+def plotnote(la,title=None) :
+ if la[0,:].size() == 3:
+ d = plotnote_withends(la, plot_title=title)
+ else:
+ # scale data if in freq (for REF.txt files)
+ if max(la[:,1] > 128 ):
+ print "scaling frequency data to midi range"
+ la[:,1] /= 6.875
+ la[:,1] = log(la[:,1])/0.6931
+ la[:,1] *= 12
+ la[:,1] -= 3
+ d = plotnote_withoutends(la, plot_title=title)
+ return d
+
+def plotnote_multi(lalist,title=None,fileout=None) :
+ d=list()
+ for i in range(len(lalist)):
+ d.append(plotnote(lalist[i], title=title))
+ return d
+
+
+def plotnote_withends(la,plot_title=None) :
+ from numpy import array
+ import Gnuplot, Gnuplot.funcutils
+ d=[]
+ x_widths = array(la[:,1]-la[:,0])/2.
+ d.append(Gnuplot.Data(
+ la[:,0]+x_widths, # x centers
+ la[:,2], # y centers
+ x_widths, # x errors
+ __notesheight*ones(len(la)), # y errors
+ title=plot_title,with_=('boxxyerrorbars fs 3')))
+ return d
+
+
+def plotnote_withoutends(la,plot_title=None) :
+ """ bug: fails drawing last note """
+ from numpy import array
+ import Gnuplot, Gnuplot.funcutils
+ d=[]
+ x_widths = array(la[1:,0]-la[:-1,0])/2;
+ d.append(Gnuplot.Data(
+ la[:-1,0]+x_widths, # x centers
+ la[:-1,1], # y centers
+ x_widths, # x errors
+ __notesheight*ones(len(la)-1), # y errors
+ title=plot_title,with_=('boxxyerrorbars fs 3')))
+ return d
+
+def plotnote_do(d,fileout=None):
+ import Gnuplot, Gnuplot.funcutils
+ g = Gnuplot.Gnuplot(debug=1, persist=1)
+ g.gnuplot('set style fill solid border 1; \
+ set size ratio 1/6; \
+ set boxwidth 0.9 relative; \
+ set mxtics 2.5; \
+ set mytics 2.5; \
+ set xtics 5; \
+ set ytics 1; \
+ set grid xtics ytics mxtics mytics')
+
+ g.xlabel('Time (s)')
+ g.ylabel('Midi pitch')
+ # do the plot
+ #g.gnuplot('set multiplot')
+ #for i in d:
+ g.plot(d[0])
+ #g.gnuplot('set nomultiplot')
+ if fileout != None:
+ g.hardcopy(fileout, enhanced=1, color=0)
+
--- /dev/null
+++ b/python.old/aubio/task/__init__.py
@@ -1,0 +1,9 @@
+from aubio.aubioclass import *
+from aubio.task.task import task
+from aubio.task.params import taskparams
+from aubio.task.silence import tasksilence
+from aubio.task.onset import taskonset
+from aubio.task.beat import taskbeat
+from aubio.task.cut import taskcut
+from aubio.task.pitch import taskpitch
+from aubio.task.notes import tasknotes
--- /dev/null
+++ b/python.old/aubio/task/beat.py
@@ -1,0 +1,262 @@
+from aubio.aubioclass import *
+from onset import taskonset
+
+class taskbeat(taskonset):
+ def __init__(self,input,params=None,output=None):
+ """ open the input file and initialize arguments
+ parameters should be set *before* calling this method.
+ """
+ taskonset.__init__(self,input,output=None,params=params)
+ self.btwinlen = 512**2/self.params.hopsize
+ self.btstep = self.btwinlen/4
+ self.btoutput = fvec(self.btstep,self.channels)
+ self.dfframe = fvec(self.btwinlen,self.channels)
+ self.bt = beattracking(self.btwinlen,self.channels)
+ self.pos2 = 0
+ self.old = -1000
+
+ def __call__(self):
+ taskonset.__call__(self)
+ #results = taskonset.__call__(self)
+ # write to current file
+ if self.pos2 == self.btstep - 1 :
+ self.bt.do(self.dfframe,self.btoutput)
+ for i in range (self.btwinlen - self.btstep):
+ self.dfframe.set(self.dfframe.get(i+self.btstep,0),i,0)
+ for i in range(self.btwinlen - self.btstep, self.btwinlen):
+ self.dfframe.set(0,i,0)
+ self.pos2 = -1;
+ self.pos2 += 1
+ val = self.opick.pp.getval()
+ #if not results: val = 0
+ #else: val = results[1]
+ self.dfframe.set(val,self.btwinlen - self.btstep + self.pos2,0)
+ i=0
+ for i in range(1,int( self.btoutput.get(0,0) ) ):
+ if self.pos2 == self.btoutput.get(i,0) and \
+ aubio_silence_detection(self.myvec(),
+ self.params.silence)!=1:
+ now = self.frameread-0
+ period = (60 * self.params.samplerate) / ((now - self.old) * self.params.hopsize)
+ self.old = now
+ return now,period
+
+ def eval(self,results,tol=0.20,tolcontext=0.25):
+ obeats = self.gettruth()
+ etime = [result[0] for result in results]
+ otime = [obeat[0] for obeat in obeats]
+ CML_tot, CML_max, CML_start, CML_end = 0,0,0,0
+ AML_tot, AML_max, AML_start, AML_end = 0,0,0,0
+ AMLd_tot, AMLd_max, AMLd_start, AMLd_end = 0,0,0,0
+ AMLh_tot, AMLh_max, AMLh_start, AMLh_end = 0,0,0,0
+ AMLo_tot, AMLo_max, AMLo_start, AMLo_end = 0,0,0,0
+ # results iteration
+ j = 1
+ # for each annotation
+ for i in range(2,len(otime)-2):
+ if j+1 >= len(etime): break
+ count = 0
+ # look for next matching beat
+ while otime[i] > etime[j] - (otime[i] - otime[i+1])*tol:
+ if count > 0:
+ #print "spurious etime"
+ if CML_end - CML_start > CML_max:
+ CML_max = CML_end - CML_start
+ CML_start, CML_end = j, j
+ if AMLh_end - AMLh_start > AMLh_max:
+ AMLh_max = AMLh_end - AMLh_start
+ AMLh_start, AMLh_end = j, j
+ if AMLd_end - AMLd_start > AMLd_max:
+ AMLd_max = AMLd_end - AMLd_start
+ AMLd_start, AMLd_end = j, j
+ if AMLo_end - AMLo_start > AMLo_max:
+ AMLo_max = AMLo_end - AMLo_start
+ AMLo_start, AMLo_end = j, j
+ j += 1
+ count += 1
+ if j+1 >= len(etime): break
+ #print otime[i-1],etime[j-1]," ",otime[i],etime[j]," ",otime[i+1],etime[j+1]
+ prevtempo = (otime[i] - otime[i-1])
+ nexttempo = (otime[i+1] - otime[i])
+
+ current0 = (etime[j] > otime[i] - prevtempo*tol)
+ current1 = (etime[j] < otime[i] + prevtempo*tol)
+
+ # check correct tempo
+ prev0 = (etime[j-1] > otime[i-1] - prevtempo*tolcontext)
+ prev1 = (etime[j-1] < otime[i-1] + prevtempo*tolcontext)
+ next0 = (etime[j+1] > otime[i+1] - nexttempo*tolcontext)
+ next1 = (etime[j+1] < otime[i+1] + nexttempo*tolcontext)
+
+ # check for off beat
+ prevoffb0 = (etime[j-1] > otime[i-1] - prevtempo/2 - prevtempo*tolcontext)
+ prevoffb1 = (etime[j-1] < otime[i-1] - prevtempo/2 + prevtempo*tolcontext)
+ nextoffb0 = (etime[j+1] > otime[i+1] - nexttempo/2 - nexttempo*tolcontext)
+ nextoffb1 = (etime[j+1] < otime[i+1] - nexttempo/2 + nexttempo*tolcontext)
+
+ # check half tempo
+ prevhalf0 = (etime[j-1] > otime[i-1] + prevtempo - prevtempo/2*tolcontext)
+ prevhalf1 = (etime[j-1] < otime[i-1] + prevtempo + prevtempo/2*tolcontext)
+ nexthalf0 = (etime[j+1] > otime[i+1] - nexttempo - nexttempo/2*tolcontext)
+ nexthalf1 = (etime[j+1] < otime[i+1] - nexttempo + nexttempo/2*tolcontext)
+
+ # check double tempo
+ prevdoub0 = (etime[j-1] > otime[i-1] - prevtempo - prevtempo*2*tolcontext)
+ prevdoub1 = (etime[j-1] < otime[i-1] - prevtempo + prevtempo*2*tolcontext)
+ nextdoub0 = (etime[j+1] > otime[i+1] + nexttempo - nexttempo*2*tolcontext)
+ nextdoub1 = (etime[j+1] < otime[i+1] + nexttempo + nexttempo*2*tolcontext)
+
+ if current0 and current1 and prev0 and prev1 and next0 and next1:
+ #print "YES!"
+ CML_end = j
+ CML_tot += 1
+ else:
+ if CML_end - CML_start > CML_max:
+ CML_max = CML_end - CML_start
+ CML_start, CML_end = j, j
+ if current0 and current1 and prevhalf0 and prevhalf1 and nexthalf0 and nexthalf1:
+ AMLh_end = j
+ AMLh_tot += 1
+ else:
+ if AMLh_end - AMLh_start > AMLh_max:
+ AMLh_max = AMLh_end - AMLh_start
+ AMLh_start, AMLh_end = j, j
+ if current0 and current1 and prevdoub0 and prevdoub1 and nextdoub0 and nextdoub1:
+ AMLd_end = j
+ AMLd_tot += 1
+ else:
+ if AMLd_end - AMLd_start > AMLd_max:
+ AMLd_max = AMLd_end - AMLd_start
+ AMLd_start, AMLd_end = j, j
+ if current0 and current1 and prevoffb0 and prevoffb1 and nextoffb0 and nextoffb1:
+ AMLo_end = j
+ AMLo_tot += 1
+ else:
+ if AMLo_end - AMLo_start > AMLo_max:
+ AMLo_max = AMLo_end - AMLo_start
+ AMLo_start, AMLo_end = j, j
+ # look for next matching beat
+ count = 0
+ while otime[i] > etime[j] - (otime[i] - otime[i+1])*tolcontext:
+ j += 1
+ if count > 0:
+ #print "spurious etime"
+ start = j
+ count += 1
+ total = float(len(otime))
+ CML_tot /= total
+ AMLh_tot /= total
+ AMLd_tot /= total
+ AMLo_tot /= total
+ CML_cont = CML_max/total
+ AMLh_cont = AMLh_max/total
+ AMLd_cont = AMLd_max/total
+ AMLo_cont = AMLo_max/total
+ return CML_cont, CML_tot, AMLh_cont, AMLh_tot, AMLd_cont, AMLd_tot, AMLo_cont, AMLo_tot
+
+# for i in allfreq:
+# freq.append(float(i) / 2. / N * samplerate )
+# while freq[i]>freqs[j]:
+# j += 1
+# a0 = weight[j-1]
+# a1 = weight[j]
+# f0 = freqs[j-1]
+# f1 = freqs[j]
+# if f0!=0:
+# iweight.append((a1-a0)/(f1-f0)*freq[i] + (a0 - (a1 - a0)/(f1/f0 -1.)))
+# else:
+# iweight.append((a1-a0)/(f1-f0)*freq[i] + a0)
+# while freq[i]>freqs[j]:
+# j += 1
+
+ def eval2(self,results,tol=0.2):
+ truth = self.gettruth()
+ obeats = [i[0] for i in truth]
+ ebeats = [i[0]*self.params.step for i in results]
+ NP = max(len(obeats), len(ebeats))
+ N = int(round(max(max(obeats), max(ebeats))*100.)+100)
+ W = int(round(tol*100.*60./median([i[1] for i in truth], len(truth)/2)))
+ ofunc = [0 for i in range(N+W)]
+ efunc = [0 for i in range(N+W)]
+ for i in obeats: ofunc[int(round(i*100.)+W)] = 1
+ for i in ebeats: efunc[int(round(i*100.)+W)] = 1
+ assert len(obeats) == sum(ofunc)
+ autocor = 0; m =0
+ for m in range (-W, W):
+ for i in range(W,N):
+ autocor += ofunc[i] * efunc[i-m]
+ autocor /= float(NP)
+ return autocor
+
+ def evaluation(self,results,tol=0.2,start=5.):
+
+ """ beat tracking evaluation function
+
+ computes P-score of experimental results (ebeats)
+ against ground truth annotations (obeats) """
+
+ from aubio.median import short_find as median
+ truth = self.gettruth()
+ ebeats = [i[0]*self.params.step for i in results]
+ obeats = [i[0] for i in truth]
+
+ # trim anything found before start
+ while obeats[0] < start: obeats.pop(0)
+ while ebeats[0] < start: ebeats.pop(0)
+ # maximum number of beats found
+ NP = max(len(obeats), len(ebeats))
+ # length of ofunc and efunc vector
+ N = int(round(max(max(obeats), max(ebeats))*100.)+100)
+ # compute W median of ground truth tempi
+ tempi = []
+ for i in range(1,len(obeats)): tempi.append(obeats[i]-obeats[i-1])
+ W = int(round(tol*100.*median(tempi,len(tempi)/2)))
+ # build ofunc and efunc functions, starting with W zeros
+ ofunc = [0 for i in range(N+W)]
+ efunc = [0 for i in range(N+W)]
+ for i in obeats: ofunc[int(round(i*100.)+W)] = 1
+ for i in ebeats: efunc[int(round(i*100.)+W)] = 1
+ # optional: make sure we didn't miss any beats
+ assert len(obeats) == sum(ofunc)
+ assert len(ebeats) == sum(efunc)
+ # compute auto correlation
+ autocor = 0; m =0
+ for m in range (-W, W):
+ for i in range(W,N):
+ autocor += ofunc[i] * efunc[i-m]
+ autocor /= float(NP)
+ return autocor
+
+ def gettruth(self):
+ import os.path
+ from aubio.txtfile import read_datafile
+ datafile = self.input.replace('.wav','.txt')
+ if not os.path.isfile(datafile):
+ print "no ground truth "
+ return False,False
+ else:
+ values = read_datafile(datafile,depth=0)
+ old = -1000
+ for i in range(len(values)):
+ now = values[i]
+ period = 60 / (now - old)
+ old = now
+ values[i] = [now,period]
+ return values
+
+
+ def plot(self,oplots,results):
+ import Gnuplot
+ oplots.append(Gnuplot.Data(results,with_='linespoints',title="auto"))
+
+ def plotplot(self,wplot,oplots,outplot=None,extension=None,xsize=1.,ysize=1.,spectro=False):
+ import Gnuplot
+ from aubio.gnuplot import gnuplot_create, audio_to_array, make_audio_plot
+ import re
+ # audio data
+ #time,data = audio_to_array(self.input)
+ #f = make_audio_plot(time,data)
+
+ g = gnuplot_create(outplot=outplot, extension=extension)
+ oplots = [Gnuplot.Data(self.gettruth(),with_='linespoints',title="orig")] + oplots
+ g.plot(*oplots)
--- /dev/null
+++ b/python.old/aubio/task/cut.py
@@ -1,0 +1,42 @@
+from task import task
+from aubio.aubioclass import *
+
+class taskcut(task):
+ def __init__(self,input,slicetimes,params=None,output=None):
+ """ open the input file and initialize arguments
+ parameters should be set *before* calling this method.
+ """
+ from os.path import basename,splitext
+ task.__init__(self,input,output=None,params=params)
+ self.soundoutbase, self.soundoutext = splitext(basename(self.input))
+ self.newname = "%s%s%09.5f%s%s" % (self.soundoutbase,".",
+ self.frameread*self.params.step,".",self.soundoutext)
+ self.fileo = sndfile(self.newname,model=self.filei)
+ self.myvec = fvec(self.params.hopsize,self.channels)
+ self.mycopy = fvec(self.params.hopsize,self.channels)
+ self.slicetimes = slicetimes
+
+ def __call__(self):
+ task.__call__(self)
+ # write to current file
+ if len(self.slicetimes) and self.frameread >= self.slicetimes[0][0]:
+ self.slicetimes.pop(0)
+ # write up to 1st zero crossing
+ zerocross = 0
+ while ( abs( self.myvec.get(zerocross,0) ) > self.params.zerothres ):
+ zerocross += 1
+ writesize = self.fileo.write(zerocross,self.myvec)
+ fromcross = 0
+ while (zerocross < self.readsize):
+ for i in range(self.channels):
+ self.mycopy.set(self.myvec.get(zerocross,i),fromcross,i)
+ fromcross += 1
+ zerocross += 1
+ del self.fileo
+ self.fileo = sndfile("%s%s%09.5f%s%s" % (self.soundoutbase,".",
+ self.frameread*self.params.step,".",self.soundoutext),model=self.filei)
+ writesize = self.fileo.write(fromcross,self.mycopy)
+ else:
+ writesize = self.fileo.write(self.readsize,self.myvec)
+
+
--- /dev/null
+++ b/python.old/aubio/task/notes.py
@@ -1,0 +1,159 @@
+
+from aubio.task import task
+from aubio.aubioclass import *
+
+class tasknotes(task):
+ def __init__(self,input,output=None,params=None):
+ task.__init__(self,input,params=params)
+ self.opick = onsetpick(self.params.bufsize,
+ self.params.hopsize,
+ self.channels,
+ self.myvec,
+ self.params.threshold,
+ mode=self.params.onsetmode,
+ dcthreshold=self.params.dcthreshold,
+ derivate=self.params.derivate)
+ self.pitchdet = pitch(mode=self.params.pitchmode,
+ bufsize=self.params.pbufsize,
+ hopsize=self.params.phopsize,
+ channels=self.channels,
+ samplerate=self.srate,
+ omode=self.params.omode)
+ self.olist = []
+ self.ofunc = []
+ self.maxofunc = 0
+ self.last = -1000
+ self.oldifreq = 0
+ if self.params.localmin:
+ self.ovalist = [0., 0., 0., 0., 0.]
+
+ def __call__(self):
+ from aubio.median import short_find
+ task.__call__(self)
+ isonset,val = self.opick.do(self.myvec)
+ if (aubio_silence_detection(self.myvec(),self.params.silence)):
+ isonset=0
+ freq = -1.
+ else:
+ freq = self.pitchdet(self.myvec)
+ minpitch = self.params.pitchmin
+ maxpitch = self.params.pitchmax
+ if maxpitch and freq > maxpitch :
+ freq = -1.
+ elif minpitch and freq < minpitch :
+ freq = -1.
+ freq = aubio_freqtomidi(freq)
+ if self.params.pitchsmooth:
+ self.shortlist.append(freq)
+ self.shortlist.pop(0)
+ smoothfreq = short_find(self.shortlist,
+ len(self.shortlist)/2)
+ freq = smoothfreq
+ now = self.frameread
+ ifreq = int(round(freq))
+ if self.oldifreq == ifreq:
+ self.oldifreq = ifreq
+ else:
+ self.oldifreq = ifreq
+ ifreq = 0
+ # take back delay
+ if self.params.delay != 0.: now -= self.params.delay
+ if now < 0 :
+ now = 0
+ if (isonset == 1):
+ if self.params.mintol:
+ # prune doubled
+ if (now - self.last) > self.params.mintol:
+ self.last = now
+ return now, 1, freq, ifreq
+ else:
+ return now, 0, freq, ifreq
+ else:
+ return now, 1, freq, ifreq
+ else:
+ return now, 0, freq, ifreq
+
+
+ def fprint(self,foo):
+ print self.params.step*foo[0], foo[1], foo[2], foo[3]
+
+ def compute_all(self):
+ """ Compute data """
+ now, onset, freq, ifreq = [], [], [], []
+ while(self.readsize==self.params.hopsize):
+ n, o, f, i = self()
+ now.append(n*self.params.step)
+ onset.append(o)
+ freq.append(f)
+ ifreq.append(i)
+ if self.params.verbose:
+ self.fprint((n,o,f,i))
+ return now, onset, freq, ifreq
+
+ def plot(self,now,onset,freq,ifreq,oplots):
+ import Gnuplot
+
+ oplots.append(Gnuplot.Data(now,freq,with_='lines',
+ title=self.params.pitchmode))
+ oplots.append(Gnuplot.Data(now,ifreq,with_='lines',
+ title=self.params.pitchmode))
+
+ temponsets = []
+ for i in onset:
+ temponsets.append(i*1000)
+ oplots.append(Gnuplot.Data(now,temponsets,with_='impulses',
+ title=self.params.pitchmode))
+
+ def plotplot(self,wplot,oplots,outplot=None,multiplot = 0):
+ from aubio.gnuplot import gnuplot_init, audio_to_array, make_audio_plot
+ import re
+ import Gnuplot
+ # audio data
+ time,data = audio_to_array(self.input)
+ f = make_audio_plot(time,data)
+
+ # check if ground truth exists
+ #timet,pitcht = self.gettruth()
+ #if timet and pitcht:
+ # oplots = [Gnuplot.Data(timet,pitcht,with_='lines',
+ # title='ground truth')] + oplots
+
+ t = Gnuplot.Data(0,0,with_='impulses')
+
+ g = gnuplot_init(outplot)
+ g('set title \'%s\'' % (re.sub('.*/','',self.input)))
+ g('set multiplot')
+ # hack to align left axis
+ g('set lmargin 15')
+ # plot waveform and onsets
+ g('set size 1,0.3')
+ g('set origin 0,0.7')
+ g('set xrange [0:%f]' % max(time))
+ g('set yrange [-1:1]')
+ g.ylabel('amplitude')
+ g.plot(f)
+ g('unset title')
+ # plot onset detection function
+
+
+ g('set size 1,0.7')
+ g('set origin 0,0')
+ g('set xrange [0:%f]' % max(time))
+ g('set yrange [20:100]')
+ g('set key right top')
+ g('set noclip one')
+ #g('set format x ""')
+ #g('set log y')
+ #g.xlabel('time (s)')
+ g.ylabel('f0 (Hz)')
+ if multiplot:
+ for i in range(len(oplots)):
+ # plot onset detection functions
+ g('set size 1,%f' % (0.7/(len(oplots))))
+ g('set origin 0,%f' % (float(i)*0.7/(len(oplots))))
+ g('set xrange [0:%f]' % max(time))
+ g.plot(oplots[i])
+ else:
+ g.plot(*oplots)
+ #g('unset multiplot')
+
--- /dev/null
+++ b/python.old/aubio/task/onset.py
@@ -1,0 +1,220 @@
+from aubio.task.task import task
+from aubio.aubioclass import *
+
+class taskonset(task):
+ def __init__(self,input,output=None,params=None):
+ """ open the input file and initialize arguments
+ parameters should be set *before* calling this method.
+ """
+ task.__init__(self,input,params=params)
+ self.opick = onsetpick(self.params.bufsize,
+ self.params.hopsize,
+ self.myvec,
+ self.params.threshold,
+ mode=self.params.onsetmode,
+ dcthreshold=self.params.dcthreshold,
+ derivate=self.params.derivate)
+ self.olist = []
+ self.ofunc = []
+ self.maxofunc = 0
+ self.last = 0
+ if self.params.localmin:
+ self.ovalist = [0., 0., 0., 0., 0.]
+
+ def __call__(self):
+ task.__call__(self)
+ isonset,val = self.opick.do(self.myvec)
+ if (aubio_silence_detection(self.myvec(),self.params.silence)):
+ isonset=0
+ if self.params.storefunc:
+ self.ofunc.append(val)
+ if self.params.localmin:
+ if val > 0: self.ovalist.append(val)
+ else: self.ovalist.append(0)
+ self.ovalist.pop(0)
+ if (isonset > 0.):
+ if self.params.localmin:
+ # find local minima before peak
+ i=len(self.ovalist)-1
+ while self.ovalist[i-1] < self.ovalist[i] and i > 0:
+ i -= 1
+ now = (self.frameread+1-i)
+ else:
+ now = self.frameread
+ # take back delay
+ if self.params.delay != 0.: now -= self.params.delay
+ if now < 0 :
+ now = 0
+ if self.params.mintol:
+ # prune doubled
+ if (now - self.last) > self.params.mintol:
+ self.last = now
+ return now, val
+ else:
+ return now, val
+
+
+ def fprint(self,foo):
+ print self.params.step*foo[0]
+
+ def eval(self,inputdata,ftru,mode='roc',vmode=''):
+ from aubio.txtfile import read_datafile
+ from aubio.onsetcompare import onset_roc, onset_diffs, onset_rocloc
+ ltru = read_datafile(ftru,depth=0)
+ lres = []
+ for i in range(len(inputdata)): lres.append(inputdata[i][0]*self.params.step)
+ if vmode=='verbose':
+ print "Running with mode %s" % self.params.onsetmode,
+ print " and threshold %f" % self.params.threshold,
+ print " on file", self.input
+ #print ltru; print lres
+ if mode == 'local':
+ l = onset_diffs(ltru,lres,self.params.tol)
+ mean = 0
+ for i in l: mean += i
+ if len(l): mean = "%.3f" % (mean/len(l))
+ else: mean = "?0"
+ return l, mean
+ elif mode == 'roc':
+ self.orig, self.missed, self.merged, \
+ self.expc, self.bad, self.doubled = \
+ onset_roc(ltru,lres,self.params.tol)
+ elif mode == 'rocloc':
+ self.v = {}
+ self.v['orig'], self.v['missed'], self.v['Tm'], \
+ self.v['expc'], self.v['bad'], self.v['Td'], \
+ self.v['l'], self.v['labs'] = \
+ onset_rocloc(ltru,lres,self.params.tol)
+
+ def plot(self,onsets,ofunc,wplot,oplots,nplot=False):
+ import Gnuplot, Gnuplot.funcutils
+ import aubio.txtfile
+ import os.path
+ from numpy import arange, array, ones
+ from aubio.onsetcompare import onset_roc
+
+ x1,y1,y1p = [],[],[]
+ oplot = []
+ if self.params.onsetmode in ('mkl','kl'): ofunc[0:10] = [0] * 10
+
+ self.lenofunc = len(ofunc)
+ self.maxofunc = max(ofunc)
+ # onset detection function
+ downtime = arange(len(ofunc))*self.params.step
+ oplot.append(Gnuplot.Data(downtime,ofunc,with_='lines',title=self.params.onsetmode))
+
+ # detected onsets
+ if not nplot:
+ for i in onsets:
+ x1.append(i[0]*self.params.step)
+ y1.append(self.maxofunc)
+ y1p.append(-self.maxofunc)
+ #x1 = array(onsets)*self.params.step
+ #y1 = self.maxofunc*ones(len(onsets))
+ if x1:
+ oplot.append(Gnuplot.Data(x1,y1,with_='impulses'))
+ wplot.append(Gnuplot.Data(x1,y1p,with_='impulses'))
+
+ oplots.append((oplot,self.params.onsetmode,self.maxofunc))
+
+ # check if ground truth datafile exists
+ datafile = self.input.replace('.wav','.txt')
+ if datafile == self.input: datafile = ""
+ if not os.path.isfile(datafile):
+ self.title = "" #"(no ground truth)"
+ else:
+ t_onsets = aubio.txtfile.read_datafile(datafile)
+ x2 = array(t_onsets).resize(len(t_onsets))
+ y2 = self.maxofunc*ones(len(t_onsets))
+ wplot.append(Gnuplot.Data(x2,y2,with_='impulses'))
+
+ tol = 0.050
+
+ orig, missed, merged, expc, bad, doubled = \
+ onset_roc(x2,x1,tol)
+ self.title = "GD %2.3f%% FP %2.3f%%" % \
+ ((100*float(orig-missed-merged)/(orig)),
+ (100*float(bad+doubled)/(orig)))
+
+
+ def plotplot(self,wplot,oplots,outplot=None,extension=None,xsize=1.,ysize=1.,spectro=False):
+ from aubio.gnuplot import gnuplot_create, audio_to_array, make_audio_plot, audio_to_spec
+ import re
+ # prepare the plot
+ g = gnuplot_create(outplot=outplot, extension=extension)
+ g('set title \'%s\'' % (re.sub('.*/','',self.input)))
+ if spectro:
+ g('set size %f,%f' % (xsize,1.3*ysize) )
+ else:
+ g('set size %f,%f' % (xsize,ysize) )
+ g('set multiplot')
+
+ # hack to align left axis
+ g('set lmargin 3')
+ g('set rmargin 6')
+
+ if spectro:
+ import Gnuplot
+ minf = 50
+ maxf = 500
+ data,time,freq = audio_to_spec(self.input,minf=minf,maxf=maxf)
+ g('set size %f,%f' % (1.24*xsize , 0.34*ysize) )
+ g('set origin %f,%f' % (-0.12,0.65*ysize))
+ g('set xrange [0.:%f]' % time[-1])
+ g('set yrange [%f:%f]' % (minf,maxf))
+ g('set pm3d map')
+ g('unset colorbox')
+ g('set lmargin 0')
+ g('set rmargin 0')
+ g('set tmargin 0')
+ g('set palette rgbformulae -25,-24,-32')
+ g.xlabel('time (s)',offset=(0,1.))
+ g.ylabel('freq (Hz)')
+ g('set origin 0,%f' % (1.0*ysize) )
+ g('set format x "%1.1f"')
+ #if log:
+ # g('set yrange [%f:%f]' % (max(10,minf),maxf))
+ # g('set log y')
+ g.splot(Gnuplot.GridData(data,time,freq, binary=1, title=''))
+ else:
+ # plot waveform and onsets
+ time,data = audio_to_array(self.input)
+ wplot = [make_audio_plot(time,data)] + wplot
+ g('set origin 0,%f' % (0.7*ysize) )
+ g('set size %f,%f' % (xsize,0.3*ysize))
+ g('set format y "%1f"')
+ g('set xrange [0:%f]' % max(time))
+ g('set yrange [-1:1]')
+ g('set noytics')
+ g('set y2tics -1,1')
+ g.xlabel('time (s)',offset=(0,0.7))
+ g.ylabel('amplitude')
+ g.plot(*wplot)
+
+ # default settings for next plots
+ g('unset title')
+ g('set format x ""')
+ g('set format y "%3e"')
+ g('set tmargin 0')
+ g.xlabel('')
+
+ N = len(oplots)
+ y = 0.7*ysize # the vertical proportion of the plot taken by onset functions
+ delta = 0.035 # the constant part of y taken by last plot label and data
+ for i in range(N):
+ # plot onset detection functions
+ g('set size %f,%f' % ( xsize, (y-delta)/N))
+ g('set origin 0,%f' % ((N-i-1)*(y-delta)/N + delta ))
+ g('set nokey')
+ g('set xrange [0:%f]' % (self.lenofunc*self.params.step))
+ g('set yrange [0:%f]' % (1.1*oplots[i][2]))
+ g('set y2tics ("0" 0, "%d" %d)' % (round(oplots[i][2]),round(oplots[i][2])))
+ g.ylabel(oplots[i][1])
+ if i == N-1:
+ g('set size %f,%f' % ( xsize, (y-delta)/N + delta ) )
+ g('set origin 0,0')
+ g.xlabel('time (s)', offset=(0,0.7))
+ g('set format x')
+ g.plot(*oplots[i][0])
+
+ g('unset multiplot')
--- /dev/null
+++ b/python.old/aubio/task/params.py
@@ -1,0 +1,33 @@
+
+class taskparams(object):
+ """ default parameters for task classes """
+ def __init__(self,input=None,output=None):
+ self.silence = -90
+ self.derivate = False
+ self.localmin = False
+ self.delay = 4.
+ self.storefunc = False
+ self.bufsize = 512
+ self.hopsize = 256
+ self.pbufsize = 2048
+ self.phopsize = 512
+ self.samplerate = 44100
+ self.tol = 0.05
+ self.mintol = 0.0
+ self.step = float(self.hopsize)/float(self.samplerate)
+ self.threshold = 0.1
+ self.onsetmode = 'dual'
+ self.pitchmode = 'yin'
+ # best threshold for yin monophonic Mirex04 (depth of f0)
+ self.yinthresh = 0.15
+ # best thresh for yinfft monophonic Mirex04 (tradeoff sil/gd)
+ # also best param for yinfft polyphonic Mirex04
+ self.yinfftthresh = 0.85
+ self.pitchsmooth = 0
+ self.pitchmin=20.
+ self.pitchmax=20000.
+ self.pitchdelay = -0.5
+ self.dcthreshold = -1.
+ self.omode = "freq"
+ self.verbose = False
+
--- /dev/null
+++ b/python.old/aubio/task/pitch.py
@@ -1,0 +1,234 @@
+from aubio.task.task import task
+from aubio.task.silence import tasksilence
+from aubio.aubioclass import *
+
+class taskpitch(task):
+ def __init__(self,input,params=None):
+ task.__init__(self,input,params=params)
+ self.shortlist = [0. for i in range(self.params.pitchsmooth)]
+ if self.params.pitchmode == 'yin':
+ tolerance = self.params.yinthresh
+ elif self.params.pitchmode == 'yinfft':
+ tolerance = self.params.yinfftthresh
+ else:
+ tolerance = 0.
+ self.pitchdet = pitch(mode=self.params.pitchmode,
+ bufsize=self.params.bufsize,
+ hopsize=self.params.hopsize,
+ samplerate=self.srate,
+ omode=self.params.omode,
+ tolerance = tolerance)
+
+ def __call__(self):
+ from aubio.median import short_find
+ task.__call__(self)
+ if (aubio_silence_detection(self.myvec(),self.params.silence)==1):
+ freq = -1.
+ else:
+ freq = self.pitchdet(self.myvec)
+ minpitch = self.params.pitchmin
+ maxpitch = self.params.pitchmax
+ if maxpitch and freq > maxpitch :
+ freq = -1.
+ elif minpitch and freq < minpitch :
+ freq = -1.
+ if self.params.pitchsmooth:
+ self.shortlist.append(freq)
+ self.shortlist.pop(0)
+ smoothfreq = short_find(self.shortlist,
+ len(self.shortlist)/2)
+ return smoothfreq
+ else:
+ return freq
+
+ def compute_all(self):
+ """ Compute data """
+ mylist = []
+ while(self.readsize==self.params.hopsize):
+ freq = self()
+ mylist.append(freq)
+ if self.params.verbose:
+ self.fprint("%s\t%s" % (self.frameread*self.params.step,freq))
+ return mylist
+
+ def gettruth(self):
+ """ extract ground truth array in frequency """
+ import os.path
+ """ from wavfile.txt """
+ datafile = self.input.replace('.wav','.txt')
+ if datafile == self.input: datafile = ""
+ """ from file.<midinote>.wav """
+ # FIXME very weak check
+ floatpit = self.input.split('.')[-2]
+ if not os.path.isfile(datafile) and len(self.input.split('.')) < 3:
+ print "no ground truth "
+ return False,False
+ elif floatpit:
+ try:
+ self.truth = float(floatpit)
+ #print "ground truth found in filename:", self.truth
+ tasksil = tasksilence(self.input,params=self.params)
+ time,pitch =[],[]
+ while(tasksil.readsize==tasksil.params.hopsize):
+ tasksil()
+ time.append(tasksil.params.step*(tasksil.frameread))
+ if not tasksil.issilence:
+ pitch.append(self.truth)
+ else:
+ pitch.append(-1.)
+ return time,pitch
+ except ValueError:
+ # FIXME very weak check
+ if not os.path.isfile(datafile):
+ print "no ground truth found"
+ return 0,0
+ else:
+ from aubio.txtfile import read_datafile
+ values = read_datafile(datafile)
+ time, pitch = [], []
+ for i in range(len(values)):
+ time.append(values[i][0])
+ if values[i][1] == 0.0:
+ pitch.append(-1.)
+ else:
+ pitch.append(aubio_freqtomidi(values[i][1]))
+ return time,pitch
+
+ def oldeval(self,results):
+ def mmean(l):
+ return sum(l)/max(float(len(l)),1)
+
+ from aubio.median import percental
+ timet,pitcht = self.gettruth()
+ res = []
+ for i in results:
+ #print i,self.truth
+ if i <= 0: pass
+ else: res.append(self.truth-i)
+ if not res or len(res) < 3:
+ avg = self.truth; med = self.truth
+ else:
+ avg = mmean(res)
+ med = percental(res,len(res)/2)
+ return self.truth, self.truth-med, self.truth-avg
+
+ def eval(self,pitch,tol=0.5):
+ timet,pitcht = self.gettruth()
+ pitch = [aubio_freqtomidi(i) for i in pitch]
+ for i in range(len(pitch)):
+ if pitch[i] == "nan" or pitch[i] == -1:
+ pitch[i] = -1
+ time = [ (i+self.params.pitchdelay)*self.params.step for i in range(len(pitch)) ]
+ #print len(timet),len(pitcht)
+ #print len(time),len(pitch)
+ if len(timet) != len(time):
+ time = time[1:len(timet)+1]
+ pitch = pitch[1:len(pitcht)+1]
+ #pitcht = [aubio_freqtomidi(i) for i in pitcht]
+ for i in range(len(pitcht)):
+ if pitcht[i] == "nan" or pitcht[i] == "-inf" or pitcht[i] == -1:
+ pitcht[i] = -1
+ assert len(timet) == len(time)
+ assert len(pitcht) == len(pitch)
+ osil, esil, opit, epit, echr = 0, 0, 0, 0, 0
+ for i in range(len(pitcht)):
+ if pitcht[i] == -1: # currently silent
+ osil += 1 # count a silence
+ if pitch[i] <= 0. or pitch[i] == "nan":
+ esil += 1 # found a silence
+ else:
+ opit +=1
+ if abs(pitcht[i] - pitch[i]) < tol:
+ epit += 1
+ echr += 1
+ elif abs(pitcht[i] - pitch[i]) % 12. < tol:
+ echr += 1
+ #else:
+ # print timet[i], pitcht[i], time[i], pitch[i]
+ #print "origsilence", "foundsilence", "origpitch", "foundpitch", "orig pitchroma", "found pitchchroma"
+ #print 100.*esil/float(osil), 100.*epit/float(opit), 100.*echr/float(opit)
+ return osil, esil, opit, epit, echr
+
+ def plot(self,pitch,wplot,oplots,titles,outplot=None):
+ import Gnuplot
+
+ time = [ (i+self.params.pitchdelay)*self.params.step for i in range(len(pitch)) ]
+ pitch = [aubio_freqtomidi(i) for i in pitch]
+ oplots.append(Gnuplot.Data(time,pitch,with_='lines',
+ title=self.params.pitchmode))
+ titles.append(self.params.pitchmode)
+
+
+ def plotplot(self,wplot,oplots,titles,outplot=None,extension=None,xsize=1.,ysize=1.,multiplot = 1, midi = 1, truth = 1):
+ from aubio.gnuplot import gnuplot_create , audio_to_array, make_audio_plot
+ import re
+ import Gnuplot
+
+ # check if ground truth exists
+ if truth:
+ timet,pitcht = self.gettruth()
+ if timet and pitcht:
+ oplots = [Gnuplot.Data(timet,pitcht,with_='lines',
+ title='ground truth')] + oplots
+
+ g = gnuplot_create(outplot=outplot, extension=extension)
+ g('set title \'%s\'' % (re.sub('.*/','',self.input)))
+ g('set size %f,%f' % (xsize,ysize) )
+ g('set multiplot')
+ # hack to align left axis
+ g('set lmargin 4')
+ g('set rmargin 4')
+ # plot waveform
+ time,data = audio_to_array(self.input)
+ wplot = [make_audio_plot(time,data)]
+ g('set origin 0,%f' % (0.7*ysize) )
+ g('set size %f,%f' % (xsize,0.3*ysize))
+ #g('set format y "%1f"')
+ g('set xrange [0:%f]' % max(time))
+ g('set yrange [-1:1]')
+ g('set noytics')
+ g('set y2tics -1,1')
+ g.xlabel('time (s)',offset=(0,0.7))
+ g.ylabel('amplitude')
+ g.plot(*wplot)
+
+ # default settings for next plots
+ g('unset title')
+ g('set format x ""')
+ g('set format y "%3e"')
+ g('set tmargin 0')
+ g.xlabel('')
+ g('set noclip one')
+
+ if not midi:
+ g('set log y')
+ #g.xlabel('time (s)')
+ g.ylabel('f0 (Hz)')
+ g('set yrange [100:%f]' % self.params.pitchmax)
+ else:
+ g.ylabel('midi')
+ g('set yrange [%f:%f]' % (aubio_freqtomidi(self.params.pitchmin), aubio_freqtomidi(self.params.pitchmax)))
+ g('set y2tics %f,%f' % (round(aubio_freqtomidi(self.params.pitchmin)+.5),12))
+
+ if multiplot:
+ N = len(oplots)
+ y = 0.7*ysize # the vertical proportion of the plot taken by onset functions
+ delta = 0.035 # the constant part of y taken by last plot label and data
+ for i in range(N):
+ # plot pitch detection functions
+ g('set size %f,%f' % ( xsize, (y-delta)/N))
+ g('set origin 0,%f' % ((N-i-1)*(y-delta)/N + delta ))
+ g('set nokey')
+ g('set xrange [0:%f]' % max(time))
+ g.ylabel(titles[i])
+ if i == N-1:
+ g('set size %f,%f' % (xsize, (y-delta)/N + delta ) )
+ g('set origin 0,0')
+ g.xlabel('time (s)', offset=(0,0.7))
+ g('set format x')
+ g.plot(oplots[i])
+ else:
+ g('set key right top')
+ g.plot(*oplots)
+ g('unset multiplot')
+
--- /dev/null
+++ b/python.old/aubio/task/silence.py
@@ -1,0 +1,28 @@
+from aubio.task.task import task
+from aubio.aubioclass import *
+
+class tasksilence(task):
+ wassilence = 1
+ issilence = 1
+ def __call__(self):
+ task.__call__(self)
+ if (aubio_silence_detection(self.myvec(),self.params.silence)==1):
+ if self.wassilence == 1: self.issilence = 1
+ else: self.issilence = 2
+ self.wassilence = 1
+ else:
+ if self.wassilence <= 0: self.issilence = 0
+ else: self.issilence = -1
+ self.wassilence = 0
+ if self.issilence == -1:
+ return max(self.frameread-self.params.delay,0.), -1
+ elif self.issilence == 2:
+ return max(self.frameread+self.params.delay,0.), 2
+
+ def fprint(self,foo):
+ print self.params.step*foo[0],
+ if foo[1] == 2: print "OFF"
+ else: print "ON"
+
+
+
--- /dev/null
+++ b/python.old/aubio/task/task.py
@@ -1,0 +1,53 @@
+from aubio.aubioclass import *
+from params import taskparams
+
+class task(taskparams):
+ """ default template class to apply tasks on a stream """
+ def __init__(self,input,output=None,params=None):
+ """ open the input file and initialize default argument
+ parameters should be set *before* calling this method.
+ """
+ import time
+ self.tic = time.time()
+ if params == None: self.params = taskparams()
+ else: self.params = params
+ self.frameread = 0
+ self.readsize = self.params.hopsize
+ self.input = input
+ self.filei = sndfile(self.input)
+ self.srate = self.filei.samplerate()
+ self.params.step = float(self.params.hopsize)/float(self.srate)
+ self.myvec = fvec(self.params.hopsize)
+ self.output = output
+
+ def __call__(self):
+ self.readsize = self.filei.read(self.params.hopsize,self.myvec)
+ self.frameread += 1
+
+ def compute_all(self):
+ """ Compute data """
+ mylist = []
+ while(self.readsize==self.params.hopsize):
+ tmp = self()
+ if tmp:
+ mylist.append(tmp)
+ if self.params.verbose:
+ self.fprint(tmp)
+ return mylist
+
+ def fprint(self,foo):
+ print foo
+
+ def eval(self,results):
+ """ Eval data """
+ pass
+
+ def plot(self):
+ """ Plot data """
+ pass
+
+ def time(self):
+ import time
+ #print "CPU time is now %f seconds," % time.clock(),
+ #print "task execution took %f seconds" % (time.time() - self.tic)
+ return time.time() - self.tic
--- /dev/null
+++ b/python.old/aubio/txtfile.py
@@ -1,0 +1,47 @@
+"""Copyright (C) 2004 Paul Brossier <piem@altern.org>
+print aubio.__LICENSE__ for the terms of use
+"""
+
+__LICENSE__ = """\
+ Copyright (C) 2004-2009 Paul Brossier <piem@aubio.org>
+
+ This file is part of aubio.
+
+ aubio is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ aubio is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with aubio. If not, see <http://www.gnu.org/licenses/>.
+"""
+
+def read_datafile(filename,depth=-1):
+ """read list data from a text file (columns of float)"""
+ if filename == '--' or filename == '-':
+ import sys
+ fres = sys.stdin
+ else:
+ fres = open(filename,'ro')
+ l = []
+ while 1:
+ tmp = fres.readline()
+ if not tmp : break
+ else: tmp = tmp.split()
+ if depth > 0:
+ for i in range(min(depth,len(tmp))):
+ tmp[i] = float(tmp[i])
+ l.append(tmp)
+ elif depth == 0:
+ l.append(float(tmp[0]))
+ else:
+ for i in range(len(tmp)):
+ tmp[i] = float(tmp[i])
+ l.append(tmp)
+ return l
+
--- /dev/null
+++ b/python.old/aubio/web/browser.py
@@ -1,0 +1,167 @@
+ #
+ # Copyright 2004 Apache Software Foundation
+ #
+ # Licensed under the Apache License, Version 2.0 (the "License"); you
+ # may not use this file except in compliance with the License. You
+ # may obtain a copy of the License at
+ #
+ # http://www.apache.org/licenses/LICENSE-2.0
+ #
+ # Unless required by applicable law or agreed to in writing, software
+ # distributed under the License is distributed on an "AS IS" BASIS,
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ # implied. See the License for the specific language governing
+ # permissions and limitations under the License.
+ #
+ # Originally developed by Gregory Trubetskoy.
+ #
+ # $Id: publisher.py,v 1.36 2004/02/16 19:47:27 grisha Exp $
+
+"""
+ This handler is conceputally similar to Zope's ZPublisher, except
+ that it:
+
+ 1. Is written specifically for mod_python and is therefore much faster
+ 2. Does not require objects to have a documentation string
+ 3. Passes all arguments as simply string
+ 4. Does not try to match Python errors to HTTP errors
+ 5. Does not give special meaning to '.' and '..'.
+
+ This is a modified version of mod_python.publisher.handler Only the first
+ directory argument is matched, the rest is left for path_info. A default
+ one must be provided.
+
+"""
+
+from mod_python import apache
+from mod_python import util
+from mod_python.publisher import resolve_object,process_auth,imp_suffixes
+
+import sys
+import os
+import re
+
+from types import *
+
+def configure_handler(req,default):
+
+ req.allow_methods(["GET", "POST"])
+ if req.method not in ["GET", "POST"]:
+ raise apache.SERVER_RETURN, apache.HTTP_METHOD_NOT_ALLOWED
+
+ func_path = ""
+ if req.path_info:
+ func_path = req.path_info[1:] # skip first /
+ #func_path = func_path.replace("/", ".")
+ #if func_path[-1:] == ".":
+ # func_path = func_path[:-1]
+ # changed: only keep the first directory
+ func_path = re.sub('/.*','',func_path)
+
+ # default to 'index' if no path_info was given
+ if not func_path:
+ func_path = "index"
+
+ # if any part of the path begins with "_", abort
+ if func_path[0] == '_' or func_path.count("._"):
+ raise apache.SERVER_RETURN, apache.HTTP_NOT_FOUND
+
+ ## import the script
+ path, module_name = os.path.split(req.filename)
+ if not module_name:
+ module_name = "index"
+
+ # get rid of the suffix
+ # explanation: Suffixes that will get stripped off
+ # are those that were specified as an argument to the
+ # AddHandler directive. Everything else will be considered
+ # a package.module rather than module.suffix
+ exts = req.get_addhandler_exts()
+ if not exts:
+ # this is SetHandler, make an exception for Python suffixes
+ exts = imp_suffixes
+ if req.extension: # this exists if we're running in a | .ext handler
+ exts += req.extension[1:]
+ if exts:
+ suffixes = exts.strip().split()
+ exp = "\\." + "$|\\.".join(suffixes)
+ suff_matcher = re.compile(exp) # python caches these, so its fast
+ module_name = suff_matcher.sub("", module_name)
+
+ # import module (or reload if needed)
+ # the [path] argument tells import_module not to allow modules whose
+ # full path is not in [path] or below.
+ config = req.get_config()
+ autoreload=int(config.get("PythonAutoReload", 1))
+ log=int(config.get("PythonDebug", 0))
+ try:
+ module = apache.import_module(module_name,
+ autoreload=autoreload,
+ log=log,
+ path=[path])
+ except ImportError:
+ et, ev, etb = sys.exc_info()
+ # try again, using default module, perhaps this is a
+ # /directory/function (as opposed to /directory/module/function)
+ func_path = module_name
+ module_name = "index"
+ try:
+ module = apache.import_module(module_name,
+ autoreload=autoreload,
+ log=log,
+ path=[path])
+ except ImportError:
+ # raise the original exception
+ raise et, ev, etb
+
+ # does it have an __auth__?
+ realm, user, passwd = process_auth(req, module)
+
+ # resolve the object ('traverse')
+ try:
+ object = resolve_object(req, module, func_path, realm, user, passwd)
+ except AttributeError:
+ # changed, return the default path instead
+ #raise apache.SERVER_RETURN, apache.HTTP_NOT_FOUND
+ object = default
+ # not callable, a class or an unbound method
+ if (not callable(object) or
+ type(object) is ClassType or
+ (hasattr(object, 'im_self') and not object.im_self)):
+
+ result = str(object)
+
+ else:
+ # callable, (but not a class or unbound method)
+
+ # process input, if any
+ req.form = util.FieldStorage(req, keep_blank_values=1)
+
+ result = util.apply_fs_data(object, req.form, req=req)
+
+ if result or req.bytes_sent > 0 or req.next:
+
+ if result is None:
+ result = ""
+ else:
+ result = str(result)
+
+ # unless content_type was manually set, we will attempt
+ # to guess it
+ if not req._content_type_set:
+ # make an attempt to guess content-type
+ if result[:100].strip()[:6].lower() == '<html>' \
+ or result.find('</') > 0:
+ req.content_type = 'text/html'
+ else:
+ req.content_type = 'text/plain'
+
+ if req.method != "HEAD":
+ req.write(result)
+ else:
+ req.write("")
+ return apache.OK
+ else:
+ req.log_error("mod_python.publisher: %s returned nothing." % `object`)
+ return apache.HTTP_INTERNAL_SERVER_ERROR
+
--- /dev/null
+++ b/python.old/aubio/web/html.py
@@ -1,0 +1,286 @@
+from aubio.bench.node import *
+
+def parse_args(req):
+ req.basehref = BASEHREF
+ req.datadir = DATADIR
+ if req.path_info: path_info = req.path_info
+ else: path_info = '/'
+ location = re.sub('^/show_[a-z0-9]*/','',path_info)
+ location = re.sub('^/play_[a-z0-9]*/','',location)
+ location = re.sub('^/index/','',location)
+ location = re.sub('^/','',location)
+ location = re.sub('/$','',location)
+ datapath = "%s/%s" % (DATADIR,location)
+ respath = "%s/%s" % (DATADIR,location)
+ last = re.sub('/$','',location)
+ last = last.split('/')[-1]
+ first = path_info.split('/')[1]
+ # store some of this in the mp_request
+ req.location, req.datapath, req.respath = location, datapath, respath
+ req.first, req.last = first, last
+
+ if location:
+ if not (os.path.isfile(datapath) or
+ os.path.isdir(datapath) or
+ location in ['feedback','email']):
+ # the path was not understood
+ from mod_python import apache
+ req.write("<html> path not found %s</html>" % (datapath))
+ raise apache.SERVER_RETURN, apache.OK
+ #from mod_python import apache
+ #raise apache.SERVER_RETURN, apache.HTTP_NOT_FOUND
+
+def navigation(req):
+ """ main html navigation header """
+ from mod_python import psp
+ req.content_type = "text/html"
+ parse_args(req)
+ datapath = req.datapath
+ location = req.location
+
+ # deal with session
+ if req.sess.is_new():
+ msg = "<b>Welcome %s</b><br>" % req.sess['login']
+ else:
+ msg = "<b>Welcome back %s</b><br>" % req.sess['login']
+
+ # start writing
+ tmpl = psp.PSP(req, filename='header.tmpl')
+ tmpl.run(vars = { 'title': "aubioweb / %s / %s" % (req.first,location),
+ 'basehref': '/~piem/',
+ 'message': msg,
+ 'action': req.first})
+
+ req.write("<h2>Content of ")
+ print_link(req,"","/")
+ y = location.split('/')
+ for i in range(len(y)-1):
+ print_link(req,"/".join(y[:i+1]),y[i])
+ req.write(" / ")
+ req.write("%s</h2>\n" % y[-1])
+
+ a = {'show_info' : 'info',
+ 'show_sound': 'waveform',
+ 'show_onset': 'onset',
+ 'index' : 'index',
+ 'show_pitch': 'pitch',
+ 'play_m3u': 'stream (m3u/ogg)',
+ 'play_ogg': 'save (ogg)',
+ 'play_wav': 'save (wav)',
+ }
+
+ # print task lists (only remaining tasks)
+ print_link(req,re.sub('%s.*'%req.last,'',location),"go up")
+ akeys = a.keys(); akeys.sort();
+ curkey = req.first
+ for akey in akeys:
+ if akey != curkey:
+ req.write(":: ")
+ print_link(req,"/".join((akey,location)),a[akey])
+ else:
+ req.write(":: ")
+ req.write("<b>%s</b>" % a[akey])
+ req.write("<br>")
+
+ # list the content of the directories
+ listdir,listfiles = [],[]
+ if os.path.isdir(datapath):
+ listfiles = list_snd_files(datapath)
+ listdir = list_dirs(datapath)
+ listdir.pop(0) # kick the current dir
+ elif os.path.isfile(datapath):
+ listfiles = [datapath]
+ listdir = [re.sub(req.last,'',location)]
+
+ link_list(req,listdir,title="Subdirectories")
+ link_list(req,listfiles,title="Files")
+
+def footer(req):
+ """ html navigation footer """
+ from mod_python import psp
+ tmpl = psp.PSP(req, filename='footer.tmpl')
+ tmpl.run(vars = { 'time': -req.mtime+req.request_time })
+
+def apply_on_data(req, func,**keywords):
+ # bug: hardcoded snd file filter
+ act_on_data(func,req.datapath,req.respath,
+ filter="f -maxdepth 1 -name '*.wav' -o -name '*.aif'",**keywords)
+
+def print_link(req,target,name,basehref=BASEHREF):
+ req.write("<a href='%s/%s'>%s</a>\n" % (basehref,target,name))
+
+def print_img(req,target,name='',basehref=BASEHREF):
+ if name == '': name = target
+ req.write("<img src='%s/%s' alt='%s' title='%s'>\n" % (basehref,target,name,name))
+
+def link_list(req,targetlist,basehref=BASEHREF,title=None):
+ if len(targetlist) > 1:
+ if title: req.write("<h3>%s</h3>"%title)
+ req.write('<ul>')
+ for i in targetlist:
+ s = re.split('%s/'%DATADIR,i,maxsplit=1)[1]
+ if s:
+ req.write('<li>')
+ print_link(req,s,s)
+ req.write('</li>')
+ req.write('</ul>')
+
+def print_list(req,list):
+ req.write("<pre>\n")
+ for i in list: req.write("%s\n" % i)
+ req.write("</pre>\n")
+
+def print_command(req,command):
+ req.write("<h4>%s</h4>\n" % re.sub('%%','%',command))
+ def print_runcommand(input,output):
+ cmd = re.sub('(%)?%i','%s' % input, command)
+ cmd = re.sub('(%)?%o','%s' % output, cmd)
+ print_list(req,runcommand(cmd))
+ apply_on_data(req,print_runcommand)
+
+def datapath_to_location(input):
+ location = re.sub(DATADIR,'',input)
+ return re.sub('^/*','',location)
+
+## drawing hacks
+def draw_func(req,func):
+ import re
+ req.content_type = "image/png"
+ # build location (strip the func_path, add DATADIR)
+ location = re.sub('^/draw_[a-z]*/','%s/'%DATADIR,req.path_info)
+ location = re.sub('.png$','',location)
+ if not os.path.isfile(location):
+ from mod_python import apache
+ raise apache.SERVER_RETURN, apache.HTTP_NOT_FOUND
+ # replace location in func
+ cmd = re.sub('(%)?%i','%s' % location, func)
+ # add PYTHONPATH at the beginning,
+ cmd = "%s%s 2> /dev/null" % (PYTHONPATH,cmd)
+ for each in runcommand(cmd):
+ req.write("%s\n"%each)
+
+def show_task(req,task):
+ def show_task_file(input,output,task):
+ location = datapath_to_location(input)
+ print_img(req,"draw_%s/%s" % (task,location))
+ navigation(req)
+ req.write("<h3>%s</h3>\n" % task)
+ apply_on_data(req,show_task_file,task=task)
+ footer(req)
+
+## waveform_foo
+def draw_sound(req):
+ draw_func(req,"aubioplot-audio %%i stdout 2> /dev/null")
+
+def show_sound(req):
+ show_task(req,"sound")
+
+## pitch foo
+def draw_pitch(req,threshold='0.3'):
+ draw_func(req,"aubiopitch -i %%i -p -m schmitt,yin,fcomb,mcomb -t %s -O stdout" % threshold)
+
+def show_pitch(req):
+ show_task(req,"pitch")
+
+## onset foo
+def draw_onset(req,threshold='0.3'):
+ draw_func(req,"aubiocut -i %%i -p -m complex -t %s -O stdout" % threshold)
+
+def show_onset(req,threshold='0.3',details=''):
+ def onset_file(input,output):
+ location = datapath_to_location(input)
+ print_img(req,"draw_onset/%s?threshold=%s"%(location,threshold))
+ print_link(req,"?threshold=%s" % (float(threshold)-0.1),"-")
+ req.write("%s\n" % threshold)
+ print_link(req,"?threshold=%s" % (float(threshold)+0.1),"+")
+ # bug: hardcoded sndfile extension
+ anote = re.sub('\.wav$','.txt',input)
+ if anote == input: anote = ""
+ res = get_extract(input,threshold)
+ if os.path.isfile(anote):
+ tru = get_anote(anote)
+ print_list(req,get_results(tru,res,0.05))
+ else:
+ req.write("no ground truth found<br>\n")
+ if details:
+ req.write("<h4>Extraction</h4>\n")
+ print_list(req,res)
+ else:
+ req.write("<a href='%s/show_onset/%s?details=yes&threshold=%s'>details</a><br>\n" %
+ (req.basehref,location,threshold))
+ if details and os.path.isfile(anote):
+ req.write("<h4>Computed differences</h4>\n")
+ ldiffs = get_diffs(tru,res,0.05)
+ print_list(req,ldiffs)
+ req.write("<h4>Annotations</h4>\n")
+ print_list(req,tru)
+ navigation(req)
+ req.write("<h3>Onset</h3>\n")
+ apply_on_data(req,onset_file)
+ footer(req)
+
+def get_anote(anote):
+ import aubio.onsetcompare
+ # FIXME: should import with txtfile.read_datafile
+ return aubio.onsetcompare.load_onsets(anote)
+
+def get_diffs(anote,extract,tol):
+ import aubio.onsetcompare
+ return aubio.onsetcompare.onset_diffs(anote,extract,tol)
+
+def get_extract(datapath,threshold='0.3'):
+ cmd = "%saubiocut -v -m complex -t %s -i %s" % (PYTHONPATH,threshold,datapath)
+ lo = runcommand(cmd)
+ for i in range(len(lo)): lo[i] = float(lo[i])
+ return lo
+
+def get_results(anote,extract,tol):
+ import aubio.onsetcompare
+ orig, missed, merged, expc, bad, doubled = aubio.onsetcompare.onset_roc(anote,extract,tol)
+ s =("GD %2.8f\t" % (100*float(orig-missed-merged)/(orig)),
+ "FP %2.8f\t" % (100*float(bad+doubled)/(orig)) ,
+ "GD-merged %2.8f\t" % (100*float(orig-missed)/(orig)) ,
+ "FP-pruned %2.8f\t" % (100*float(bad)/(orig)) )
+ return s
+
+# play m3u foo
+def play_m3u(req):
+ def show_task_file(input,output,task):
+ location = datapath_to_location(input)
+ req.write("http://%s%s/play_ogg/%s\n" % (HOSTNAME,BASEHREF,re.sub("play_m3u",task,location)))
+ req.content_type = "audio/mpegurl"
+ parse_args(req)
+ apply_on_data(req,show_task_file,task="play_ogg")
+
+# play wav foo
+def play_wav(req):
+ req.content_type = "audio/x-wav"
+ func = "cat %%i"
+ # build location (strip the func_path, add DATADIR)
+ location = re.sub('^/play_wav/','%s/'%DATADIR,req.path_info)
+ if not os.path.isfile(location):
+ from mod_python import apache
+ raise apache.SERVER_RETURN, apache.HTTP_NOT_FOUND
+ # replace location in func
+ cmd = re.sub('(%)?%i','%s' % location, func)
+ # add PYTHONPATH at the beginning,
+ cmd = "%s 2> /dev/null" % cmd
+ for each in runcommand(cmd):
+ req.write("%s\n"%each)
+
+# play ogg foo
+def play_ogg(req):
+ req.content_type = "application/ogg"
+ func = "oggenc -o - %%i"
+ # build location (strip the func_path, add DATADIR)
+ location = re.sub('^/play_ogg/','%s/'%DATADIR,req.path_info)
+ location = re.sub('.ogg$','',location)
+ if not os.path.isfile(location):
+ from mod_python import apache
+ raise apache.SERVER_RETURN, apache.HTTP_NOT_FOUND
+ # replace location in func
+ cmd = re.sub('(%)?%i','%s' % location, func)
+ # add PYTHONPATH at the beginning,
+ cmd = "%s 2> /dev/null" % cmd
+ for each in runcommand(cmd):
+ req.write("%s\n"%each)
--- /dev/null
+++ b/python.old/aubio/wscript_build
@@ -1,0 +1,17 @@
+# vim:set syntax=python:
+
+pyaubio = ctx.new_task_gen(name = 'python-aubio',
+ features = 'c cshlib pyext',
+ source = '../../swig/aubio.i',
+ add_objects = 'sndfileio',
+ target = '_aubiowrapper',
+ use = ['aubio'],
+ uselib = ['SNDFILE'],
+ swig_flags = '-python -Wall',
+ includes = '. ../../src ../../examples')
+pyaubio.install_path = '${PYTHONDIR}/${PACKAGE}'
+
+# install python files
+ctx.install_files('${PYTHONDIR}/${PACKAGE}/', ctx.path.ant_glob('**/*.py'))
+# install swig generated python file
+ctx.install_files('${PYTHONDIR}/${PACKAGE}/', '../../swig/aubiowrapper.py')
--- /dev/null
+++ b/python.old/aubiocompare-onset
@@ -1,0 +1,114 @@
+#! /usr/bin/python
+
+"""Copyright (C) 2004 Paul Brossier <piem@altern.org>
+
+print aubio.__LICENSE__ for the terms of use
+
+or see LICENSE.txt in the aubio installation directory.
+"""
+__LICENSE__ = """\
+ Copyright (C) 2004-2009 Paul Brossier <piem@aubio.org>
+
+ This file is part of aubio.
+
+ aubio is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ aubio is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with aubio. If not, see <http://www.gnu.org/licenses/>.
+"""
+
+
+__HELP__ = """\
+# required arguments
+ -c targetfilename
+ -o detectfilename
+(both must be text files with 1 time a line expressed in seconds)
+
+# optional arguments
+ -D <delay> delay in seconds
+ -v verbose mode
+ -d debug mode
+
+# output
+results:number of correct detections
+ number of incorrect detections
+ number of doubled detections
+ number of total detections
+ number of total targets
+
+# example:
+$ aubioonset-comp -c checked-onsets.txt -o handlab-onsets.txt -v
+( gd fp dd ) tot / real
+( 5 4 0 ) 9 / 9
+55.5555555556 %GD 44.4444444444 %FP 0.0 %OD
+
+# bugs
+does not scale to very long lists
+"""
+
+import sys
+from aubio.onsetcompare import onset_roc, onset_diffs
+from aubio.txtfile import read_datafile
+
+# default values
+fileo=None;filec=None;vmode=None;dmode=None;delay=0.
+# default tolerance is 50 ms
+#tol = 0.050
+tol = 0.048
+# default mode is onset
+mode = 'onset'
+
+while len(sys.argv) >=2:
+ option = sys.argv[1]; del sys.argv[1]
+ if option == '-h': print __HELP__; sys.exit()
+ if option == '-o': fileo = sys.argv[1]; del sys.argv[1]
+ if option == '-c': filec = sys.argv[1]; del sys.argv[1]
+ if option == '-v': vmode = 'verbose'
+ if option == '-d': dmode = 'debug'
+ if option == '-D': delay = float(sys.argv[1]); del sys.argv[1]
+ if option == '-tol': tol = float(sys.argv[1]); del sys.argv[1]
+ if option == '-l': mode = 'localisation'
+
+# arguments required
+if (not fileo) or (not filec):
+ print 'wrong set of arguments. use \'-h\' for help'
+ sys.exit('error: needs at least \'-c targets.txt -o detected.txt\'')
+
+# load files
+ltru, lres = read_datafile(fileo,depth=0),read_datafile(filec,depth=0)
+
+# delay onsets as required with -D
+if delay:
+ for i in range(len(lres)):
+ lres[i] = lres[i] + delay
+# compute errors types
+if mode == 'localisation':
+ l = onset_diffs(ltru,lres,tol)
+ for i in l: print "%.3f" % i
+else:
+ orig, missed, merged, expc, bad, doubled = onset_roc(ltru,lres,tol)
+
+ # print results
+ #print "orig, missed, merged, expc, bad, doubled:"
+ if vmode=='verbose':
+ print "orig", orig
+ print "expc", expc
+ print "missed",missed
+ print "merged", merged
+ print "bad", bad
+ print "doubled", doubled
+ print "correct", orig-missed-merged
+ print "GD %2.8f\t" % (100*float(orig-missed-merged)/(orig)),
+ print "FP %2.8f\t" % (100*float(bad+doubled)/(orig)) ,
+ print "GD-merged %2.8f\t" % (100*float(orig-missed)/(orig)) ,
+ print "FP-pruned %2.8f\t" % (100*float(bad)/(orig))
+ else:
+ print orig, missed, merged, expc, bad, doubled
--- /dev/null
+++ b/python.old/aubiocut
@@ -1,0 +1,156 @@
+#! /usr/bin/python
+
+""" this file was written by Paul Brossier
+ it is released under the GNU/GPL license.
+"""
+
+import sys
+from aubio.task import *
+
+usage = "usage: %s [options] -i soundfile" % sys.argv[0]
+
+def parse_args():
+ from optparse import OptionParser
+ parser = OptionParser(usage=usage)
+ parser.add_option("-i","--input",
+ action="store", dest="filename",
+ help="input sound file")
+ parser.add_option("-m","--mode",
+ action="store", dest="mode", default='dual',
+ help="onset detection mode [default=dual] \
+ complexdomain|hfc|phase|specdiff|energy|kl|mkl|dual")
+ parser.add_option("-B","--bufsize",
+ action="store", dest="bufsize", default=512,
+ help="buffer size [default=512]")
+ parser.add_option("-H","--hopsize",
+ action="store", dest="hopsize", default=256,
+ help="overlap size [default=256]")
+ parser.add_option("-t","--threshold",
+ action="store", dest="threshold", default=0.3,
+ help="onset peak picking threshold [default=0.3]")
+ parser.add_option("-C","--dcthreshold",
+ action="store", dest="dcthreshold", default=1.,
+ help="onset peak picking DC component [default=1.]")
+ parser.add_option("-s","--silence",
+ action="store", dest="silence", default=-70,
+ help="silence threshold [default=-70]")
+ parser.add_option("-M","--mintol",
+ action="store", dest="mintol", default=0.048,
+ help="minimum inter onset interval [default=0.048]")
+ parser.add_option("-D","--delay",
+ action="store", dest="delay",
+ help="number of seconds to take back [default=system]\
+ default system delay is 3*hopsize/samplerate")
+ parser.add_option("-L","--localmin",
+ action="store_true", dest="localmin", default=False,
+ help="use local minima after peak detection")
+ parser.add_option("-c","--cut",
+ action="store_true", dest="cut", default=False,
+ help="cut input sound file at detected labels \
+ best used with option -L")
+ parser.add_option("-d","--derivate",
+ action="store_true", dest="derivate", default=False,
+ help="derivate onset detection function")
+ parser.add_option("-S","--silencecut",
+ action="store_true", dest="silencecut", default=False,
+ help="outputs silence locations")
+ parser.add_option("-z","--zerocross",
+ action="store", dest="zerothres", default=0.008,
+ help="zero-crossing threshold for slicing [default=0.00008]")
+ # plotting functions
+ parser.add_option("-p","--plot",
+ action="store_true", dest="plot", default=False,
+ help="draw plot")
+ parser.add_option("-x","--xsize",
+ action="store", dest="xsize", default=1.,
+ type='float', help="define xsize for plot")
+ parser.add_option("-y","--ysize",
+ action="store", dest="ysize", default=1.,
+ type='float', help="define ysize for plot")
+ parser.add_option("-f","--function",
+ action="store_true", dest="func", default=False,
+ help="print detection function")
+ parser.add_option("-n","--no-onsets",
+ action="store_true", dest="nplot", default=False,
+ help="do not plot detected onsets")
+ parser.add_option("-O","--outplot",
+ action="store", dest="outplot", default=None,
+ help="save plot to output.{ps,png}")
+ parser.add_option("-F","--spectrogram",
+ action="store_true", dest="spectro", default=False,
+ help="add spectrogram to the plot")
+ parser.add_option("-v","--verbose",
+ action="store_true", dest="verbose", default=True,
+ help="make lots of noise [default]")
+ parser.add_option("-q","--quiet",
+ action="store_false", dest="verbose", default=True,
+ help="be quiet")
+ # to be implemented
+ parser.add_option("-b","--beat",
+ action="store_true", dest="beat", default=False,
+ help="output beat locations")
+ (options, args) = parser.parse_args()
+ if not options.filename:
+ print "no file name given\n", usage
+ sys.exit(1)
+ return options, args
+
+options, args = parse_args()
+
+filename = options.filename
+params = taskparams()
+params.hopsize = int(options.hopsize)
+params.bufsize = int(options.bufsize)
+params.threshold = float(options.threshold)
+params.dcthreshold = float(options.dcthreshold)
+params.zerothres = float(options.zerothres)
+params.silence = float(options.silence)
+params.mintol = float(options.mintol)
+params.verbose = options.verbose
+# default take back system delay
+if options.delay: params.delay = int(float(options.delay)/params.step)
+
+dotask = taskonset
+if options.beat:
+ dotask = taskbeat
+elif options.silencecut:
+ dotask = tasksilence
+elif options.plot or options.func:
+ params.storefunc=True
+else:
+ params.storefunc=False
+
+lonsets, lofunc = [], []
+wplot,oplots = [],[]
+modes = options.mode.split(',')
+for i in range(len(modes)):
+ params.onsetmode = modes[i]
+ filetask = dotask(filename,params=params)
+ onsets = filetask.compute_all()
+
+ #lonsets.append(onsets)
+ if not options.silencecut:
+ ofunc = filetask.ofunc
+ lofunc.append(ofunc)
+
+ if options.plot:
+ if options.beat:
+ filetask.plot(oplots, onsets)
+ else:
+ filetask.plot(onsets, ofunc, wplot, oplots, nplot=options.nplot)
+
+ if options.func:
+ for i in ofunc:
+ print i
+
+if options.outplot:
+ extension = options.outplot.split('.')[-1]
+ outplot = '.'.join(options.outplot.split('.')[:-1])
+else:
+ extension,outplot = None,None
+if options.plot: filetask.plotplot(wplot, oplots, outplot=outplot, extension=extension,
+ xsize=options.xsize,ysize=options.ysize,spectro=options.spectro)
+
+if options.cut:
+ a = taskcut(filename,onsets,params=params)
+ a.compute_all()
--- /dev/null
+++ b/python.old/aubiodiffs-onset
@@ -1,0 +1,86 @@
+#! /usr/bin/python
+
+__LICENSE__ = """\
+ Copyright (C) 2004-2009 Paul Brossier <piem@aubio.org>
+
+ This file is part of aubio.
+
+ aubio is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ aubio is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with aubio. If not, see <http://www.gnu.org/licenses/>.
+"""
+
+__HELP__ = """\
+# required arguments
+ -c targetfilename
+ -o detectfilename
+(both must be text files with 1 time a line expressed in seconds)
+
+# optional arguments
+ -D <delay> delay in seconds
+ -v verbose mode
+ -d debug mode
+
+# output
+results:number of correct detections
+ number of incorrect detections
+ number of doubled detections
+ number of total detections
+ number of total targets
+
+# example:
+$ aubioonset-comp -c checked-onsets.txt -o handlab-onsets.txt -v
+( gd fp dd ) tot / real
+( 5 4 0 ) 9 / 9
+55.5555555556 %GD 44.4444444444 %FP 0.0 %OD
+
+# bugs
+does not scale to very long lists
+"""
+
+import sys
+from aubio.onsetcompare import onset_diffs
+from aubio.txtfile import read_datafile
+
+# default values
+fileo=None;filec=None;vmode=None;dmode=None;delay=0.
+# default tolerance is 50 ms
+#tol = 0.050
+tol = 0.048
+
+while len(sys.argv) >=2:
+ option = sys.argv[1]; del sys.argv[1]
+ if option == '-h': print __HELP__; sys.exit()
+ if option == '-o': fileo = sys.argv[1]; del sys.argv[1]
+ if option == '-c': filec = sys.argv[1]; del sys.argv[1]
+ if option == '-v': vmode = 'verbose'
+ if option == '-d': dmode = 'debug'
+ if option == '-D': delay = float(sys.argv[1]); del sys.argv[1]
+ if option == '-tol': tol = float(sys.argv[1]); del sys.argv[1]
+
+# arguments required
+if (not fileo) or (not filec):
+ print 'wrong set of arguments. use \'-h\' for help'
+ sys.exit('error: needs at least \'-c targets.txt -o detected.txt\'')
+
+# load files
+ltru, lres = read_datafile(fileo,depth=0),read_datafile(filec,depth=0)
+
+# delay onsets as required with -D
+if delay:
+ for i in range(len(lres)):
+ lres[i] = lres[i] + delay
+# compute errors types
+l = onset_diffs(ltru,lres,tol)
+# print with 1ms precision
+for i in l: print "%.3f" % float(i)
+
--- /dev/null
+++ b/python.old/aubiofilter-notes
@@ -1,0 +1,94 @@
+#!/usr/bin/python
+
+""" this file is used to get filter the (old) output format of aubionotes """
+
+# default parameters
+__eps = [0.250,0.50] # minimum length, pitch tolerance (ms,midipitch)
+__plot = 0 # -P (command line switch)
+__delay = 0.0 # -D <value> (fixed delay for score alignement)
+__winlength = 10 # -w <value> (window length for pitch estimation in frames)
+
+import getopt
+import sys
+
+def parse_args (sysargs):
+ from getopt import gnu_getopt
+ shortopts ='i:o:t:p:w:D:P:'
+ longopts =('input=','output=','tolpitch=','toltime=','winlength=','delay','plot=')
+ args,tmp = gnu_getopt(sysargs,shortopts,longopts)
+ assert len(args) > 1
+ plot = __plot
+ delay = __delay
+ eps = __eps
+ winlength = __winlength
+ plot = __plot
+ fileout = '/tmp/testprint.ps'
+ args.sort()
+ for i in range(len(args)): # a bad way
+ if args[i][0] == '-i' or args[i][0] == '--input':
+ fileorg = args[i][1]
+ if args[i][0] == '-o' or args[i][0] == '--output':
+ fileerr = args[i][1]
+ if args[i][0] == '-t' or args[i][0] == '--toltime':
+ eps[0] = float(args[i][1])
+ if args[i][0] == '-p' or args[i][0] == '--tolpitch':
+ eps[1] = float(args[i][1])
+ if args[i][0] == '-D' or args[i][0] == '--delay':
+ delay = float(args[i][1])
+ if args[i][0] == '-w' or args[i][0] == '--winlength':
+ winlength = int(args[i][1])
+ if args[i][0] == '-P' or args[i][0] == '--plot':
+ plot = 1
+ fileout = args[i][1]
+ return fileorg,fileerr,eps,winlength,plot,delay,fileout
+
+def usage():
+ print __file__, "with at least some arguments"
+
+def main():
+ try:
+ opts,args = getopt.getopt(sys.argv[1:],
+ "hvo:i:p:P",
+ ["help", "output=", "verbose", "input=", "plot="])
+ except getopt.GetoptError:
+ usage()
+ sys.exit(2)
+
+ input = None
+ output = None
+ verbose = False
+ winlength = __winlength
+ plot = __plot
+ eps = __eps
+
+ for o, a in opts:
+ if o in ("-v", "--verbose"):
+ verbose = True
+ if o in ("-h", "--help"):
+ usage()
+ sys.exit(2)
+ if o in ("--output"):
+ output = a
+ if o in ("-i", "--input"):
+ input = a
+ if o in ("-P", "--plot"):
+ plot = 1
+
+ assert input != None and input != "", "no input file"
+
+ from aubio import notefilter,txtfile,gnuplot
+ """ load midi and raw data """
+ from numpy import array
+ notelist = array(txtfile.read_datafile(input))
+ """ filter it out """
+ notelist_filtered = notefilter.segraw_onsets4(notelist,winlength,eps)
+ if verbose == 1 :
+ for a,b in notelist_filtered:
+ print a,b
+ """ plot results """
+ if plot == 1 :
+ gnuplot.plotnote(notelist_filtered,title=input,fileout=output)
+
+if __name__ == "__main__":
+ main()
+
--- /dev/null
+++ b/python.old/aubionotes
@@ -1,0 +1,79 @@
+#!/usr/bin/python
+
+def do(filein,threshold):
+
+ import aubio.aubioclass
+ import aubio.median
+ from math import floor
+ hopsize = 512
+ bufsize = 4096
+ channels = 1
+ frameread = 0
+ silthres = -80.
+ filei = aubio.aubioclass.sndfile(filein)
+ srate = filei.samplerate()
+ myvec = aubio.aubioclass.fvec(hopsize,channels)
+ readsize = filei.read(hopsize,myvec)
+ ppick = aubio.aubioclass.pitchpick(bufsize,hopsize,channels,myvec,srate)
+ opick = aubio.aubioclass.onsetpick(bufsize,hopsize,channels,myvec,threshold)
+ mylist = list()
+
+ wassilence = 0
+ lastpitch = 0
+ starttime = 0
+ while(readsize==hopsize):
+ readsize = filei.read(hopsize,myvec)
+ val = ppick.do(myvec)
+ midival = aubio.aubioclass.bintomidi(val,srate,bufsize)
+ isonset,onset = opick.do(myvec)
+ now = (frameread)*hopsize/(srate+0.)
+ issilence = aubio.aubioclass.aubio_silence_detection(myvec.vec,silthres)
+
+ estmidival = 0
+ if (issilence == 1):
+ if (wassilence == 0):
+ #outputnow
+ endtime = (frameread-3)*hopsize/(srate+0.)
+ if len(mylist) > 5 :
+ estmidival = aubio.median.percental(mylist,len(mylist)/2)
+ print "sil", starttime, endtime, estmidival
+ #resetnow
+ mylist = list()
+ else:
+ wassilence = 1
+ else:
+ if isonset == 1:
+ if (wassilence == 0):
+ #outputnow
+ endtime = (frameread-3)*hopsize/(srate+0.)
+ #estmidival = aubio.median.percental(around(array(mylist)),len(mylist)//2)
+ if len(mylist) > 5 :
+ estmidival = aubio.median.percental(mylist,len(mylist)/2)
+ print starttime, endtime, estmidival
+ #resetnow
+ mylist = list()
+ #store start time
+ starttime = (frameread-3)*hopsize/(srate+0.)
+ else:
+ """
+ if(listfull):
+ #outputnow
+ endtime = (frameread-3)*hopsize/(srate+0.)
+ print starttime, endtime, estimmidival
+ else:
+ """
+ #bufferize
+ if midival > 50 and midival < 75:
+ mylist.append(floor(midival))
+ wassilence = 0
+
+
+ #elif( midival > 45 ):
+ # mylist.append(( now , midival+12 ))
+ #mylist.append(toappend)
+ frameread += 1
+
+
+if __name__ == "__main__":
+ import sys
+ do(sys.argv[1],sys.argv[2])
--- /dev/null
+++ b/python.old/aubiopitch
@@ -1,0 +1,131 @@
+#!/usr/bin/python
+
+""" this file was written by Paul Brossier
+ it is released under the GNU/GPL license.
+"""
+
+import sys
+from aubio.task import *
+
+usage = "usage: %s [options] -i soundfile" % sys.argv[0]
+
+
+def parse_args():
+ from optparse import OptionParser
+ parser = OptionParser(usage=usage)
+ parser.add_option("-i","--input",
+ action="store", dest="filename",
+ help="input sound file")
+ parser.add_option("-m","--mode",
+ action="store", dest="mode", default='yinfft',
+ help="pitch detection mode [default=mcomb] \
+ mcomb|yin|fcomb|schmitt")
+ parser.add_option("-u","--units",
+ action="store", dest="omode", default="freq",
+ help="output pitch in units [default=Hz] \
+ freq|midi|cent|bin")
+ parser.add_option("-B","--bufsize",
+ action="store", dest="bufsize", default=None,
+ help="buffer size [default=2048]")
+ parser.add_option("-H","--hopsize",
+ action="store", dest="hopsize", default=None,
+ help="overlap size [default=512]")
+ parser.add_option("-t","--threshold",
+ action="store", dest="threshold", default=0.1,
+ help="pitch threshold (for yin) [default=0.1]")
+ parser.add_option("-s","--silence",
+ action="store", dest="silence", default=-70,
+ help="silence threshold [default=-70]")
+ parser.add_option("-D","--delay",
+ action="store", dest="delay",
+ help="number of seconds frames to take back [default=0]")
+ parser.add_option("-S","--smoothing",
+ action="store", dest="smoothing", default=False,
+ help="use a median filter of N frames [default=0]")
+ parser.add_option("-M","--maximum",
+ action="store", dest="pitchmax", default=False,
+ help="maximum pitch value to look for (Hz) [default=20000]")
+ parser.add_option("-l","--minimum",
+ action="store", dest="pitchmin", default=False,
+ help="minimum pitch value to look for (Hz) [default=20]")
+ # to be implemented
+ parser.add_option("-n","--note",
+ action="store_true", dest="note", default=False,
+ help="NOT IMPLEMENTED output notes")
+ # plotting functions
+ parser.add_option("-T","--plottruth",
+ action="store_true", dest="plottruth", default=False,
+ help="draw plot of the ground truth pitch track")
+ parser.add_option("-p","--plot",
+ action="store_true", dest="plot", default=False,
+ help="draw plot of the pitch track")
+ parser.add_option("-x","--xsize",
+ action="store", dest="xsize", default=1.,
+ type='float', help="define xsize for plot")
+ parser.add_option("-y","--ysize",
+ action="store", dest="ysize", default=1.,
+ type='float', help="define ysize for plot")
+ parser.add_option("-O","--outplot",
+ action="store", dest="outplot", default=None,
+ help="save the plot to output.{ps,png,svg} instead of displaying it")
+ parser.add_option("-v","--verbose",
+ action="store_true", dest="verbose", default=True,
+ help="make lots of noise")
+ parser.add_option("-q","--quiet",
+ action="store_false", dest="verbose", default=True,
+ help="be quiet")
+ (options, args) = parser.parse_args()
+ if not options.bufsize:
+ if options.mode == "yin": options.bufsize = 1024
+ if options.mode == "schmitt": options.bufsize = 2048
+ if options.mode == "mcomb": options.bufsize = 4096
+ if options.mode == "fcomb": options.bufsize = 4096
+ else: options.bufsize = 2048
+ if not options.hopsize:
+ options.hopsize = float(options.bufsize) / 2
+ if not options.filename:
+ print "no file name given\n", usage
+ sys.exit(1)
+ return options, args
+
+options, args = parse_args()
+
+#print options.bufsize, options.hopsize
+
+filename = options.filename
+params = taskparams()
+params.samplerate = float(sndfile(filename).samplerate())
+params.hopsize = int(options.hopsize)
+params.bufsize = int(options.bufsize)
+params.step = params.samplerate/float(params.hopsize)
+params.yinthresh = float(options.threshold)
+params.silence = float(options.silence)
+params.verbose = options.verbose
+if options.smoothing: params.pitchsmooth = int(options.smoothing)
+if options.pitchmax: params.pitchmax = int(options.pitchmax)
+if options.pitchmin: params.pitchmin = int(options.pitchmin)
+#mintol = float(options.mintol)*step
+# default take back system delay
+if options.delay: params.pitchdelay = float(options.delay)
+
+if options.note:
+ exit("not implemented yet")
+
+wplot,oplots,titles = [],[],[]
+modes = options.mode.split(',')
+for i in range(len(modes)):
+ pitch = []
+ params.pitchmode = modes[i]
+ filetask = taskpitch(filename,params=params)
+ pitch = filetask.compute_all()
+ #print filetask.eval(pitch[i])
+ if options.plot: filetask.plot(pitch,wplot,oplots,titles)
+
+if options.outplot:
+ extension = options.outplot.split('.')[-1]
+ outplot = '.'.join(options.outplot.split('.')[:-1])
+else:
+ extension,outplot = None,None
+if options.plot:
+ filetask.plotplot(wplot,oplots,titles,outplot=outplot,extension=extension,
+ xsize=options.xsize,ysize=options.ysize,truth=options.plottruth)
--- /dev/null
+++ b/python.old/aubioplot-audio
@@ -1,0 +1,31 @@
+#!/usr/bin/python
+
+import sys
+from aubio.gnuplot import gnuplot_create,gnuplot_addargs,plot_audio
+
+usage = "usage: %s [options] -i soundfile" % sys.argv[0]
+
+def parse_args():
+ from optparse import OptionParser
+ parser = OptionParser(usage=usage)
+ parser.add_option("-i","--input",
+ action="store", dest="filename",
+ help="input sound file")
+ gnuplot_addargs(parser)
+ (options, args) = parser.parse_args()
+ if not options.filename:
+ print "no file name given\n", usage
+ sys.exit(1)
+ return options, args
+
+options, args = parse_args()
+
+if options.outplot:
+ extension = options.outplot.split('.')[-1]
+ outplot = '.'.join(options.outplot.split('.')[:-1])
+else:
+ extension = ''
+ outplot = None
+
+g = gnuplot_create(outplot,extension,options)
+plot_audio(options.filename.split(','), g, options)
--- /dev/null
+++ b/python.old/aubioplot-notes
@@ -1,0 +1,31 @@
+#!/usr/bin/python
+
+def parse_args (sysargs):
+ from getopt import gnu_getopt
+ shortopts ='i:o:'
+ longopts =('input=','output=')
+ args,tmp = gnu_getopt(sysargs,shortopts,longopts)
+ args.sort()
+ filein,fileout= None,None
+ for i in range(len(args)): # a bad way
+ if args[i][0] == '-i' or args[i][0] == '--input':
+ filein = args[i][1]
+ if args[i][0] == '-o' or args[i][0] == '--output':
+ fileout = args[i][1]
+ assert filein != None, 'precise filein'
+ return filein,fileout
+
+def main (sysargs) :
+ from aubio.txtfile import read_datafile
+ from aubio.gnuplot import plotnote,plotnote_do
+ from numpy import array
+ filein,fileout = parse_args(sysargs)
+ #print 'checking', fileerr, 'against', fileorg
+ """ load midi and raw data """
+ d = plotnote(array(read_datafile(filein)),title=filein)
+ plotnote_do(d,fileout=fileout)
+
+if __name__ == "__main__":
+ import sys
+ main(sys.argv[1:])
+
--- /dev/null
+++ b/python.old/aubioplot-spec
@@ -1,0 +1,51 @@
+#! /usr/bin/python
+
+""" this file was written by Paul Brossier
+ it is released under the GNU/GPL license.
+"""
+
+import sys
+from aubio.gnuplot import gnuplot_create,gnuplot_addargs,plot_spec
+
+usage = "usage: %s [options] -i soundfile" % sys.argv[0]
+
+def parse_args():
+ from optparse import OptionParser
+ parser = OptionParser(usage=usage)
+ parser.add_option("-i","--input",
+ action="store", dest="filename",
+ help="input sound file")
+ parser.add_option("-M","--maxf",
+ action="store", dest="maxf", default=10000.,
+ type='float',help="higher frequency limit")
+ parser.add_option("-L","--minf",
+ action="store", dest="minf", default=0.,
+ type='float',help="lower frequency limit")
+ parser.add_option("-l","--log",
+ action="store_true", dest="log", default=False,
+ help="plot on a logarithmic scale")
+ parser.add_option("-B","--bufsize", type='int',
+ action="store", dest="bufsize", default=8192,
+ help="buffer size [default=8192]")
+ parser.add_option("-H","--hopsize", type='int',
+ action="store", dest="hopsize", default=1024,
+ help="overlap size [default=1024]")
+ gnuplot_addargs(parser)
+ (options, args) = parser.parse_args()
+ if not options.filename:
+ print "no file name given\n", usage
+ sys.exit(1)
+ return options, args
+
+options, args = parse_args()
+filename = options.filename
+
+if options.outplot:
+ extension = options.outplot.split('.')[-1]
+ outplot = '.'.join(options.outplot.split('.')[:-1])
+else:
+ extension = ''
+ outplot = None
+
+g = gnuplot_create(outplot,extension,options)
+plot_spec(filename, g, options)
--- /dev/null
+++ b/python.old/aubioplot-yinfft
@@ -1,0 +1,135 @@
+#! /usr/bin/python
+
+""" this file was written by Paul Brossier
+ it is released under the GNU/GPL license.
+"""
+
+import sys,time
+from aubio.task import task,taskparams
+from aubio.aubioclass import fvec
+from aubio.gnuplot import gnuplot_create
+from aubio.aubiowrapper import *
+
+usage = "usage: %s [options] -i soundfile" % sys.argv[0]
+
+def parse_args():
+ from optparse import OptionParser
+ parser = OptionParser(usage=usage)
+ parser.add_option("-i","--input",
+ action="store", dest="filename",
+ help="input sound file")
+ parser.add_option("-n","--printframe",
+ action="store", dest="printframe", default=-1,
+ help="make a plot of the n_th frame")
+ parser.add_option("-x","--xsize",
+ action="store", dest="xsize", default=1.,
+ help="define xsize for plot")
+ parser.add_option("-y","--ysize",
+ action="store", dest="ysize", default=1.,
+ help="define ysize for plot")
+ parser.add_option("-O","--outplot",
+ action="store", dest="outplot", default=None,
+ help="save plot to output.{ps,png}")
+ (options, args) = parser.parse_args()
+ if not options.filename:
+ print "no file name given\n", usage
+ sys.exit(1)
+ return options, args
+
+def plotdata(x,y,plottitle="",**keyw):
+ import Gnuplot
+ return Gnuplot.Data(x, y, title="%s" % plottitle,**keyw)
+
+options, args = parse_args()
+filename = options.filename
+xsize = float(options.xsize)
+ysize = float(options.ysize)*2
+
+printframe = int(options.printframe)
+if printframe == -1:
+ print "Will wait for ^D to skip to next plot"
+ print "Press enter before to print to file"
+
+
+g = gnuplot_create()
+params = taskparams()
+params.hopsize = 2048 # 512
+params.bufsize = params.hopsize #2048
+taskfile = task(filename,params=params)
+
+yin = fvec(params.bufsize/2,1)
+
+t = [i for i in range(params.bufsize)]
+a = [0 for i in range(params.bufsize)]
+
+while (taskfile.readsize == params.hopsize):
+ taskfile()
+
+ n = [i for i in range(params.bufsize/2)]
+ a = [taskfile.myvec.get(i,0) for i in range(params.hopsize/2)]
+ aubio_pitchyin_diff(taskfile.myvec(),yin()) # compute d[t]
+ c = [yin.get(i,0) for i in range(params.bufsize/2)]
+ aubio_pitchyin_getcum(yin()) # compute d'[t]
+ y = [yin.get(i,0) for i in range(params.bufsize/2)]
+ thresh = [0.1 for i in range(params.bufsize/2)]
+ #t.append((i/float(params.hopsize)+taskfile.frameread)*params.step),t.pop(0)
+ d = [plotdata(n,a,plottitle="signal", with_='lines'),
+ plotdata(n,c,plottitle="d[t]",axes='x1y2', with_='lines lt 1'),
+ plotdata(n,y,plottitle="d'[t]",axes='x1y1', with_='lines lt 2'),
+ plotdata(n,thresh,plottitle="threshold",axes='x1y1', with_='lines lt 3')]
+ #g('set xrange [%f:%f]' % (t[0],t[-1]))
+ #time.sleep(.2)
+ g.reset()
+ g('set yrange [-1:3]')
+ g('set xrange [0:%d]' % (params.bufsize/2))
+ g('set title \"%s\"' % "Example of period detection using YIN")
+ if printframe == -1:
+ g.replot(*d)
+ a = sys.stdin.read()
+ if a == "\n" or printframe == taskfile.frameread:
+ from os.path import basename
+ outplot = "_".join([basename(sys.argv[0]),'_'.join(basename(filename).split('.')),"%d" % taskfile.frameread])
+ print outplot
+ f = gnuplot_create(outplot=outplot,extension='ps')
+ f('set size %f,%f;' % (xsize,ysize) )
+ f('set lmargin %f' % (15*xsize))
+ f('set rmargin %f' % (10*xsize))
+ #f('set title \"%s\"' % "Example of period detection using YIN")
+ f('set multiplot')
+ f.ylabel('amplitude',offset=(+.5,0))
+ f.xlabel('time (samples)')
+ f('set size %f,%f;' % (xsize,ysize*0.4) )
+ f('set orig %f,%f;' % (0,ysize*0.6) )
+ sigmax = max(abs(min(a)),abs(max(a)))
+ f('set yrange [%f:%f]' % (-1.3*sigmax,1.3*sigmax))
+ f('set xrange [0:%d]' % (params.bufsize/2))
+ f.plot(d[0])
+
+ f.ylabel('')
+ f.xlabel('lag (samples)')
+ f('set bmargin %f' % (4*ysize))
+ f('set size %f,%f;' % (xsize,ysize*0.6) )
+ f('set orig %f,%f;' % (0,0) )
+ f('set autoscale')
+ f('set xrange [0:%d]' % (params.bufsize/2))
+ f('set notitle')
+ f('set y2tics')
+ f('set ytics nomirror')
+ f('set noytics')
+ f('set key right')
+ f.plot(d[1])
+
+ f.ylabel('amplitude')
+ f.xlabel('')
+ f('set y2tics nomirror')
+ f('set ytics nomirror')
+ f('set noy2tics')
+ f('set noxtics')
+ f('set ytics')
+ f('set key left')
+ f.plot(d[2],d[3])
+ #f('set yrange [-1:3]')
+ #f.plot(*d)
+ print "saved plot", outplot, 'ps'
+ elif printframe < taskfile.frameread:
+ break
--- /dev/null
+++ b/python.old/aubioweb.py
@@ -1,0 +1,113 @@
+#!/usr/bin/python
+
+doc = """
+This script works with mod_python to browse a collection of annotated wav files
+and results.
+
+you will need to have at least the following packages need to be installed (the
+name of the command line tool is precised in parenthesis):
+
+libapache-mod-python (apache2 prefered)
+sndfile-programs (sndfile-info)
+vorbis-tools (oggenc)
+python-gnuplot
+python-numpy
+
+Try the command line tools in aubio/python to test your installation.
+
+NOTE: this script is probably horribly insecure.
+
+example configuration for apache to put in your preferred virtual host.
+
+<Directory /home/piem/public_html/aubioweb>
+ # Minimal config
+ AddHandler mod_python .py
+ # Disable these in production
+ PythonDebug On
+ PythonAutoReload on
+ # Default handler in url
+ PythonHandler aubioweb
+ ## Authentication stuff (optional)
+ #PythonAuthenHandler aubioweb
+ #AuthType Basic
+ #AuthName "Restricted Area"
+ #require valid-user
+ # make default listing
+ DirectoryIndex aubioweb/
+</Directory>
+
+"""
+
+from aubio.web.html import *
+
+def handler(req):
+ from aubio.web.browser import *
+ from mod_python import Session
+ req.sess = Session.Session(req)
+ req.sess['login']='new aubio user'
+ req.sess.save()
+ return configure_handler(req,index)
+
+def index(req,threshold='0.3'):
+ navigation(req)
+ print_command(req,"sfinfo %%i")
+ return footer(req)
+
+def show_info(req,verbose=''):
+ navigation(req)
+ print_command(req,"sndfile-info %%i")
+ return footer(req)
+
+def feedback(req):
+ navigation(req)
+ req.write("""
+ Please provide feedback below:
+ <p>
+ <form action="/~piem/aubioweb/email" method="POST">
+ Name: <input type="text" name="name"><br>
+ Email: <input type="text" name="email"><br>
+ Comment: <textarea name="comment" rows=4 cols=20></textarea><br>
+ <input type="submit">
+ </form>
+ """)
+
+WEBMASTER='piem@calabaza'
+SMTP_SERVER='localhost'
+
+def email(req,name,email,comment):
+ import smtplib
+ # make sure the user provided all the parameters
+ if not (name and email and comment):
+ return "A required parameter is missing, \
+ please go back and correct the error"
+ # create the message text
+ msg = """\
+From: %s
+Subject: feedback
+To: %s
+
+I have the following comment:
+
+%s
+
+Thank You,
+
+%s
+
+""" % (email, WEBMASTER, comment, name)
+ # send it out
+ conn = smtplib.SMTP(SMTP_SERVER)
+ try:
+ conn.sendmail(email, [WEBMASTER], msg)
+ except smtplib.SMTPSenderRefused:
+ return """<html>please provide a valid email</html>"""
+
+ conn.quit()
+ # provide feedback to the user
+ s = """\
+<html>
+Dear %s,<br>
+Thank You for your kind comments, we
+will get back to you shortly.
+</html>""" % name
+ return s
--- /dev/null
+++ b/python.old/bench-cluster-test
@@ -1,0 +1,9 @@
+#! /usr/bin/python
+
+from aubio.bench.broadcast import *
+
+run_broadcast(remote_sync,'/home/testing')
+run_broadcast(remote_sync,'/home/testing','-n')
+run_broadcast(fetch_results,'/home/testing','-n')
+
+run_broadcast(remote_queue,'echo coucou')
--- /dev/null
+++ b/python.old/bench-test
@@ -1,0 +1,13 @@
+#! /usr/bin/python
+
+from aubio.bench.node import *
+
+datapath = '/var/www'
+respath = '/var/tmp'
+
+def my_print(input,output):
+ cmd = "%s %s %s" % ("time sleep 0.3; echo",input,output)
+ return runcommand(cmd,debug=0)
+
+act_on_results(mkdir,datapath,respath,filter='d')
+act_on_data(my_print,datapath,respath,suffix='.txt')
--- /dev/null
+++ b/python.old/wscript_build
@@ -1,0 +1,6 @@
+# vim:set syntax=python:
+
+ctx.add_subdirs('aubio')
+# install headers
+for file in ['aubiocut', 'aubiopitch']:
+ ctx.install_as('${PREFIX}/bin/' + file, file, chmod = 0755)
--- a/python/Makefile.am
+++ /dev/null
@@ -1,5 +1,0 @@
-EXTRA_DIST = README
-SUBDIRS = aubio
-dist_bin_SCRIPTS = aubiocut aubiopitch
-dist_noinst_SCRIPTS = aubiocompare-onset aubioplot-notes \
- aubiofilter-notes aubionotes aubiocompare-onset aubioweb.py
--- a/python/README
+++ /dev/null
@@ -1,30 +1,0 @@
-# Here you will find some examples of python scripts and some evaluation
-# routines. The python interface for libaubio is generated using Swig.
-
-# To have it working before installation, you will need to set LD_LIBRARY_PATH.
-# for instance, to run the python script from within aubio/python/, you can use
-# '. README'
-
-export LD_LIBRARY_PATH=../src/.libs:../ext/.libs
-export PYTHONPATH=aubio/.libs
-
-echo """
-
-the aubio/ directory should be organised as follow:
-
- aubiowrapper.py,_aubiowrapper.so, aubio_wrap.c, aubio_wrap.o
- swig generated aubio interface
- aubioclass.py
- human usable interface
- plot/
- everything required to plot
- web/
- tools to use aubioweb.py
- bench/
- tools to explore a database of sound file and run benchmarks on it
- eval/
- tools to evaluate the performance of aubio extractors
- aubioweb.py
- a hack to pipe aubio in mod_python
-
-"""
--- /dev/null
+++ b/python/README.md
@@ -1,0 +1,24 @@
+Python aubio module
+===================
+
+This module wraps the aubio library for python using the numpy module.
+
+See the [Python/C API Reference
+Manual] (http://docs.python.org/c-api/index.html) and the [Numpy/C API
+Reference](http://docs.scipy.org/doc/numpy/reference/c-api.html)
+
+Compiling python aubio on Mac OS X
+----------------------------------
+
+You should now be able to build the aubio python module out of the box on a
+recent version of OS X (10.8.x). Make sure the variables are correct in the
+file `build_osx` before running it:
+
+ $ ./build_osx
+
+Additionally, you can fetch tools such [matplotlib](http://matplotlib.org/) to
+use the demo scripts. One easy way to do it is to fetch the fully fledged
+[Scipy superpack](http://fonnesbeck.github.com/ScipySuperpack/)
+
+ $ curl -O https://raw.github.com/fonnesbeck/ScipySuperpack/master/install_superpack.sh
+ $ sh install_superpack.sh
--- /dev/null
+++ b/python/a_weighting_test_simple.expected
@@ -1,0 +1,2 @@
+ 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 5.00000000e-01 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00
+ 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 1.27870563e-01 2.58244342e-01 1.18719361e-01 -4.02623805e-02 -5.61812129e-02 -5.24739734e-02 -4.72329276e-02 -4.23394349e-02 -3.79219586e-02 -3.39473148e-02 -3.03724479e-02 -2.71574847e-02 -2.42664433e-02 -2.16669285e-02 -1.93297810e-02 -1.72287543e-02 -1.53402241e-02 -1.36429261e-02 -1.21177207e-02 -1.07473802e-02
--- /dev/null
+++ b/python/aubio-types.h
@@ -1,0 +1,49 @@
+#include <Python.h>
+#include <structmember.h>
+#define NO_IMPORT_ARRAY
+#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
+#include <numpy/arrayobject.h>
+#define AUBIO_UNSTABLE 1
+#include <aubio.h>
+
+#define Py_default_vector_length 1024
+#define Py_default_vector_height 1
+
+#define Py_aubio_default_samplerate 44100
+
+#if HAVE_AUBIO_DOUBLE
+#error "Ouch! Python interface for aubio has not been much tested yet."
+#define AUBIO_NPY_SMPL NPY_DOUBLE
+#else
+#define AUBIO_NPY_SMPL NPY_FLOAT
+#endif
+
+// special python type for cvec
+typedef struct
+{
+ PyObject_HEAD
+ cvec_t * o;
+ uint_t length;
+ uint_t channels;
+} Py_cvec;
+extern PyTypeObject Py_cvecType;
+
+// defined in aubio-proxy.c
+extern PyObject *PyAubio_CFvecToArray (fvec_t * self);
+extern fvec_t *PyAubio_ArrayToCFvec (PyObject * self);
+
+extern Py_cvec *PyAubio_CCvecToPyCvec (cvec_t * self);
+extern cvec_t *PyAubio_ArrayToCCvec (PyObject *input);
+
+extern PyObject *PyAubio_CFmatToArray (fmat_t * self);
+extern fmat_t *PyAubio_ArrayToCFmat (PyObject *input);
+
+// hand written wrappers
+extern PyTypeObject Py_filterType;
+
+extern PyTypeObject Py_filterbankType;
+
+extern PyTypeObject Py_fftType;
+
+extern PyTypeObject Py_pvocType;
+
--- a/python/aubio/Makefile.am
+++ /dev/null
@@ -1,66 +1,0 @@
-nobase_pkgpython_PYTHON = \
- __init__.py \
- onsetcompare.py \
- gnuplot.py \
- median.py \
- txtfile.py \
- aubioclass.py \
- task/__init__.py \
- task/params.py \
- task/onset.py \
- task/silence.py \
- task/cut.py \
- task/beat.py \
- task/task.py \
- task/pitch.py \
- task/notes.py \
- bench/__init__.py \
- bench/broadcast.py \
- bench/config.py \
- bench/node.py \
- bench/onset.py \
- plot/__init__.py \
- plot/keyboard.py \
- web/__init__.py \
- web/browser.py \
- web/html.py
-
-nodist_pkgpython_PYTHON = aubiowrapper.py _aubiowrapper.so
-
-_aubiowrapper.so: _aubiowrapper.la
-
-if MINGW
-SWLDFLAGS = -L${prefix}/bin -lpython${PYTHON_VERSION}
-else
-if DARWIN
-SWLDFLAGS = -bundle -framework Python
-else
-SWLDFLAGS = -shared
-endif
-endif
-
-CLEANFILES = *.pyc *.so *.o aubio_wrap.c aubiowrapper.py
-
-NOWARN_CFLAGS = -Wno-missing-prototypes -Wno-missing-declarations \
- -Wno-strict-aliasing
-
-AM_CFLAGS = @AUBIO_CFLAGS@ @SNDFILE_CFLAGS@ \
- $(NOWARN_CFLAGS) $(SWCFLAGS) \
- -I$(top_builddir)/src -I$(top_srcdir)/src \
- -I$(top_srcdir)/examples \
- -I/usr/include/python${PYTHON_VERSION} \
- -I${prefix}/include/python${PYTHON_VERSION} \
- -I/usr/include \
- -I${prefix}/include
-
-AUBIO_LDFLAGS = $(SWLDFLAGS) \
- @SNDFILE_LIBS@ \
- -L$(top_builddir)/src -laubio
-
-pkgpyexec_LTLIBRARIES = _aubiowrapper.la
-
-_aubiowrapper_la_LDFLAGS = -module -avoid-version $(AUBIO_LDFLAGS)
-_aubiowrapper_la_SOURCES = aubio_wrap.c $(top_srcdir)/examples/sndfileio.c
-
-aubio_wrap.c aubiowrapper.py:
- $(SWIG) -outdir . -o aubio_wrap.c -python $(top_srcdir)/swig/aubio.i
--- a/python/aubio/__init__.py
+++ b/python/aubio/__init__.py
@@ -1,28 +1,9 @@
-"""Copyright (C) 2004 Paul Brossier <piem@altern.org>
-print aubio.__LICENSE__ for the terms of use
-"""
+import numpy
+from _aubio import *
-__LICENSE__ = """\
- Copyright (C) 2004-2009 Paul Brossier <piem@aubio.org>
+class fvec(numpy.ndarray):
- This file is part of aubio.
-
- aubio is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- aubio is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with aubio. If not, see <http://www.gnu.org/licenses/>.
-"""
-
-#from aubioclass import *
-#from onsetcompare import *
-#from median import *
-#from noteroc import *
-#from txtfile import *
+ def __new__(self, length = 1024, **kwargs):
+ if type(length) == type([]):
+ return numpy.array(length, dtype='float32', **kwargs)
+ return numpy.zeros(length, dtype='float32', **kwargs)
--- a/python/aubio/aubioclass.py
+++ /dev/null
@@ -1,160 +1,0 @@
-from aubiowrapper import *
-
-class fvec:
- def __init__(self,size):
- self.vec = new_fvec(size)
- def __call__(self):
- return self.vec
- def __del__(self):
- del_fvec(self())
- def get(self,pos):
- return fvec_read_sample(self(),pos)
- def set(self,value,pos):
- return fvec_write_sample(self(),value,pos)
- def data(self):
- return fvec_get_data(self())
-
-class cvec:
- def __init__(self,size):
- self.vec = new_cvec(size)
- def __call__(self):
- return self.vec
- def __del__(self):
- del_cvec(self())
- def get(self,pos):
- return self.get_norm(pos)
- def set(self,val,pos):
- self.set_norm(val,pos)
- def get_norm(self,pos):
- return cvec_read_norm(self(),pos)
- def set_norm(self,val,pos):
- cvec_write_norm(self(),val,pos)
- def get_phas(self,pos):
- return cvec_read_phas(self(),pos)
- def set_phas(self,val,pos):
- cvec_write_phas(self(),val,pos)
-
-class sndfile:
- def __init__(self,filename,model=None):
- if (model!=None):
- self.file = new_aubio_sndfile_wo(model.file,filename)
- else:
- self.file = new_aubio_sndfile_ro(filename)
- if self.file == None:
- raise IOError, "failed opening file %s" % filename
- def __del__(self):
- if self.file != None: del_aubio_sndfile(self.file)
- def info(self):
- aubio_sndfile_info(self.file)
- def samplerate(self):
- return aubio_sndfile_samplerate(self.file)
- def channels(self):
- return aubio_sndfile_channels(self.file)
- def read(self,nfram,vecread):
- return aubio_sndfile_read_mono(self.file,nfram,vecread())
- def write(self,nfram,vecwrite):
- return aubio_sndfile_write(self.file,nfram,vecwrite())
-
-class pvoc:
- def __init__(self,buf,hop):
- self.pv = new_aubio_pvoc(buf,hop)
- def __del__(self):
- del_aubio_pvoc(self.pv)
- def do(self,tf,tc):
- aubio_pvoc_do(self.pv,tf(),tc())
- def rdo(self,tc,tf):
- aubio_pvoc_rdo(self.pv,tc(),tf())
-
-class onsetdetection:
- """ class for aubio_specdesc """
- def __init__(self,mode,buf):
- self.od = new_aubio_specdesc(mode,buf)
- def do(self,tc,tf):
- aubio_specdesc_do(self.od,tc(),tf())
- def __del__(self):
- del_aubio_specdesc(self.od)
-
-class peakpick:
- """ class for aubio_peakpicker """
- def __init__(self,threshold=0.1):
- self.pp = new_aubio_peakpicker()
- self.out = new_fvec(1)
- aubio_peakpicker_set_threshold (self.pp, threshold)
- def do(self,fv):
- aubio_peakpicker_do(self.pp, fv(), self.out)
- return fvec_read_sample(self.out, 0)
- def getval(self):
- return aubio_peakpicker_get_adaptive_threshold(self.pp)
- def __del__(self):
- del_aubio_peakpicker(self.pp)
-
-class onsetpick:
- """ superclass for aubio_pvoc + aubio_specdesc + aubio_peakpicker """
- def __init__(self,bufsize,hopsize,myvec,threshold,mode='dual',derivate=False,dcthreshold=0):
- self.myfft = cvec(bufsize)
- self.pv = pvoc(bufsize,hopsize)
- if mode in ['dual'] :
- self.myod = onsetdetection("hfc",bufsize)
- self.myod2 = onsetdetection("mkl",bufsize)
- self.myonset = fvec(1)
- self.myonset2 = fvec(1)
- else:
- self.myod = onsetdetection(mode,bufsize)
- self.myonset = fvec(1)
- self.mode = mode
- self.pp = peakpick(float(threshold))
- self.derivate = derivate
- self.dcthreshold = dcthreshold
- self.oldval = 0.
-
- def do(self,myvec):
- self.pv.do(myvec,self.myfft)
- self.myod.do(self.myfft,self.myonset)
- if self.mode == 'dual':
- self.myod2.do(self.myfft,self.myonset2)
- self.myonset.set(self.myonset.get(0)*self.myonset2.get(0),0)
- if self.derivate:
- val = self.myonset.get(0)
- dval = val - self.oldval
- self.oldval = val
- if dval > 0: self.myonset.set(dval,0)
- else: self.myonset.set(0.,0,0)
- isonset, dval = self.pp.do(self.myonset),self.myonset.get(0)
- if self.dcthreshold:
- if dval < self.dcthreshold: isonset = 0
- return isonset, dval
-
-class pitch:
- def __init__(self,mode="mcomb",bufsize=2048,hopsize=1024,
- samplerate=44100.,omode="freq",tolerance=0.1):
- self.pitchp = new_aubio_pitch(mode,bufsize,hopsize,
- samplerate)
- self.mypitch = fvec(1)
- aubio_pitch_set_unit(self.pitchp,omode)
- aubio_pitch_set_tolerance(self.pitchp,tolerance)
- #self.filt = filter(srate,"adsgn")
- def __del__(self):
- del_aubio_pitch(self.pitchp)
- def __call__(self,myvec):
- aubio_pitch_do(self.pitchp,myvec(), self.mypitch())
- return self.mypitch.get(0)
-
-class filter:
- def __init__(self,srate,type=None):
- if (type=="adsgn"):
- self.filter = new_aubio_adsgn_filter(srate)
- def __del__(self):
- #del_aubio_filter(self.filter)
- pass
- def __call__(self,myvec):
- aubio_filter_do(self.filter,myvec())
-
-class beattracking:
- """ class for aubio_beattracking """
- def __init__(self,winlen,channels):
- self.p = new_aubio_beattracking(winlen,channels)
- def do(self,dfframe,out):
- return aubio_beattracking_do(self.p,dfframe(),out())
- def __del__(self):
- del_aubio_beattracking(self.p)
-
--- a/python/aubio/bench/broadcast.py
+++ /dev/null
@@ -1,25 +1,0 @@
-from config import *
-
-class run_broadcast:
- def __init__(self,command,*args):
- for host in REMOTEHOSTS:
- command(host,args[0],args[1:])
-
-def remote_sync(host,path='',options=''):
- optstring = ''
- for i in options:
- optstring = "%s %s" % (optstring,i)
- print RSYNC_CMD,optstring,RSYNC_OPT,' --delete',
- print '%s%s%s%s%s' % (path,'/ ',host,':',path)
-
-
-def fetch_results(host,path='',options=''):
- optstring = ''
- for i in options:
- optstring = "%s %s" % (optstring,i)
- print RSYNC_CMD,optstring,RSYNC_OPT,' --update',
- print '%s%s%s%s%s' % (host,':',path,'/ ',path)
-
-def remote_queue(host,command,options=''):
- print 'oarsub -p "hostname = \'',host,'\'',command
-
--- a/python/aubio/bench/config.py
+++ /dev/null
@@ -1,22 +1,0 @@
-
-filefound = 0
-try:
- filename = "/etc/aubio-bench.conf"
- execfile(filename)
- filefound = 1
-except IOError:
- print "no system wide configuration file found in", filename
-
-try:
- import os
- filename = "%s%s%s" % (os.getenv('HOME'),os.sep,".aubio-bench.conf")
- execfile(filename)
- filefound = 1
-except IOError:
- #print "no user configuration file found in", filename
- pass
-
-if filefound == 0:
- import sys
- print "error: no configuration file found at all"
- sys.exit(1)
--- a/python/aubio/bench/node.py
+++ /dev/null
@@ -1,224 +1,0 @@
-from config import *
-import commands,sys
-import re
-
-def runcommand(cmd,debug=0):
- if VERBOSE >= VERBOSE_CMD or debug: print cmd
- if debug: return
- status, output = commands.getstatusoutput(cmd)
- if status == 0 or VERBOSE >= VERBOSE_OUT:
- output = output.split('\n')
- if VERBOSE >= VERBOSE_OUT:
- for i in output:
- if i: print i
- if not status == 0:
- print 'error:',status,output
- print 'command returning error was',cmd
- #sys.exit(1)
- if output == '' or output == ['']: return
- return output
-
-def list_files(datapath,filter='f', maxdepth = -1):
- if not os.path.exists(datapath):
- print "ERR: no directory %s were found" % datapath
- sys.exit(1)
- if maxdepth >= 0: maxstring = " -maxdepth %d " % maxdepth
- else: maxstring = ""
- cmd = '%s' * 6 % ('find ',datapath,maxstring,' -type ',filter, "| sort -n")
- return runcommand(cmd)
-
-def list_wav_files(datapath,maxdepth = -1):
- return list_files(datapath, filter="f -name '*.wav'",maxdepth = maxdepth)
-
-sndfile_filter = "f -name '*.wav' -o -name '*.aif' -o -name '*.aiff'"
-
-def list_snd_files(datapath,maxdepth = -1):
- return list_files(datapath, filter=sndfile_filter,
- maxdepth = maxdepth)
-
-def list_res_files(datapath,maxdepth = -1):
- return list_files(datapath, filter="f -name '*.txt'", maxdepth = maxdepth)
-
-def list_dirs(datapath):
- return list_files(datapath, filter="d")
-
-def mkdir(path):
- cmd = '%s%s' % ('mkdir -p ',path)
- return runcommand(cmd)
-
-def act_on_data (action,datapath,respath=None,suffix='.txt',filter='f',sub='\.wav$',**keywords):
- """ execute action(datafile,resfile) on all files in datapath """
- dirlist = list_files(datapath,filter=filter)
- if dirlist == ['']: dirlist = []
- if respath:
- respath_in_datapath = re.split(datapath, respath,maxsplit=1)[1:]
- if(respath_in_datapath and suffix == ''):
- print 'error: respath in datapath and no suffix used'
- for i in dirlist:
- j = re.split(datapath, i,maxsplit=1)[1]
- j = re.sub(sub,'',j)
- #j = "%s%s%s"%(respath,j,suffix)
- if respath:
- j = "%s%s"%(respath,j)
- if sub != '':
- j = re.sub(sub,suffix,j)
- else:
- j = "%s%s" % (j,suffix)
- action(i,j,**keywords)
-
-def act_on_results (action,datapath,respath,filter='d'):
- """ execute action(respath) an all subdirectories in respath """
- dirlist = list_files(datapath,filter='d')
- respath_in_datapath = re.split(datapath, respath,maxsplit=1)[1:]
- if(respath_in_datapath and not filter == 'd' and suffix == ''):
- print 'warning: respath is in datapath'
- for i in dirlist:
- s = re.split(datapath, i ,maxsplit=1)[1]
- action("%s%s%s"%(respath,'/',s))
-
-def act_on_files (action,listfiles,listres=None,suffix='.txt',filter='f',sub='\.wav$',**keywords):
- """ execute action(respath) an all subdirectories in respath """
- if listres and len(listfiles) <= len(listres):
- for i in range(len(listfiles)):
- action(listfiles[i],listres[i],**keywords)
- else:
- for i in listfiles:
- action(i,None,**keywords)
-
-class bench:
- """ class to run benchmarks on directories """
- def __init__(self,datadir,resdir=None,checkres=False,checkanno=False,params=[]):
- from aubio.task.params import taskparams
- self.datadir = datadir
- # path to write results path to
- self.resdir = resdir
- # list of annotation files
- self.reslist = []
- # list used to gather results
- self.results = []
- if not params: self.params = taskparams()
- else: self.params = params
- print "Checking data directory", self.datadir
- self.checkdata()
- if checkanno: self.checkanno()
- if checkres: self.checkres()
-
- def checkdata(self):
- if os.path.isfile(self.datadir):
- self.dirlist = os.path.dirname(self.datadir)
- elif os.path.isdir(self.datadir):
- self.dirlist = list_dirs(self.datadir)
- # allow dir* matching through find commands?
- else:
- print "ERR: path not understood"
- sys.exit(1)
- print "Listing directories in data directory",
- if self.dirlist:
- print " (%d elements)" % len(self.dirlist)
- else:
- print " (0 elements)"
- print "ERR: no directory %s were found" % self.datadir
- sys.exit(1)
- print "Listing sound files in data directory",
- self.sndlist = list_snd_files(self.datadir)
- if self.sndlist:
- print " (%d elements)" % len(self.sndlist)
- else:
- print " (0 elements)"
- print "ERR: no sound files were found in", self.datadir
- sys.exit(1)
-
- def checkanno(self):
- print "Listing annotations in data directory",
- self.reslist = list_res_files(self.datadir)
- print " (%d elements)" % len(self.reslist)
- #for each in self.reslist: print each
- if not self.reslist or len(self.reslist) < len (self.sndlist):
- print "ERR: not enough annotations"
- return -1
- else:
- print "Found enough annotations"
-
- def checkres(self):
- print "Creating results directory"
- act_on_results(mkdir,self.datadir,self.resdir,filter='d')
-
- def pretty_print(self,sep='|'):
- for i in self.printnames:
- print self.formats[i] % self.v[i], sep,
-
- def pretty_titles(self,sep='|'):
- for i in self.printnames:
- print self.formats[i] % i, sep,
-
- def dir_exec(self):
- """ run file_exec on every input file """
- self.l , self.labs = [], []
- self.v = {}
- for i in self.valuenames:
- self.v[i] = []
- for i in self.valuelists:
- self.v[i] = []
- act_on_files(self.file_exec,self.sndlist,self.reslist, \
- suffix='',filter=sndfile_filter)
-
- def dir_eval(self):
- pass
-
- def file_gettruth(self,input):
- """ get ground truth filenames """
- from os.path import isfile
- ftrulist = []
- # search for match as filetask.input,".txt"
- ftru = '.'.join(input.split('.')[:-1])
- ftru = '.'.join((ftru,'txt'))
- if isfile(ftru):
- ftrulist.append(ftru)
- else:
- # search for matches for filetask.input in the list of results
- for i in range(len(self.reslist)):
- check = '.'.join(self.reslist[i].split('.')[:-1])
- check = '_'.join(check.split('_')[:-1])
- if check == '.'.join(input.split('.')[:-1]):
- ftrulist.append(self.reslist[i])
- return ftrulist
-
- def file_exec(self,input,output):
- """ create filetask, extract data, evaluate """
- filetask = self.task(input,params=self.params)
- computed_data = filetask.compute_all()
- ftrulist = self.file_gettruth(filetask.input)
- for i in ftrulist:
- filetask.eval(computed_data,i,mode='rocloc',vmode='')
- """ append filetask.v to self.v """
- for i in self.valuenames:
- self.v[i].append(filetask.v[i])
- for j in self.valuelists:
- if filetask.v[j]:
- for i in range(len(filetask.v[j])):
- self.v[j].append(filetask.v[j][i])
-
- def file_eval(self):
- pass
-
- def file_plot(self):
- pass
-
- def dir_plot(self):
- pass
-
- def run_bench(self):
- for mode in self.modes:
- self.params.mode = mode
- self.dir_exec()
- self.dir_eval()
- self.dir_plot()
-
- def dir_eval_print(self):
- self.dir_exec()
- self.dir_eval()
- self.pretty_print()
-
--- a/python/aubio/bench/onset.py
+++ /dev/null
@@ -1,303 +1,0 @@
-
-from aubio.bench.node import *
-from os.path import dirname,basename
-
-def mmean(l):
- return sum(l)/max(float(len(l)),1)
-
-def stdev(l):
- smean = 0
- if not len(l): return smean
- lmean = mmean(l)
- for i in l:
- smean += (i-lmean)**2
- smean *= 1. / len(l)
- return smean**.5
-
-class benchonset(bench):
-
- """ list of values to store per file """
- valuenames = ['orig','missed','Tm','expc','bad','Td']
- """ list of lists to store per file """
- valuelists = ['l','labs']
- """ list of values to print per dir """
- printnames = [ 'mode', 'thres', 'dist', 'prec', 'recl',
- 'GD', 'FP',
- 'Torig', 'Ttrue', 'Tfp', 'Tfn', 'TTm', 'TTd',
- 'aTtrue', 'aTfp', 'aTfn', 'aTm', 'aTd',
- 'mean', 'smean', 'amean', 'samean']
-
- """ per dir """
- formats = {'mode': "%12s" , 'thres': "%5.4s",
- 'dist': "%5.4s", 'prec': "%5.4s", 'recl': "%5.4s",
- 'Torig': "%5.4s", 'Ttrue': "%5.4s", 'Tfp': "%5.4s", 'Tfn': "%5.4s",
- 'TTm': "%5.4s", 'TTd': "%5.4s",
- 'aTtrue':"%5.4s", 'aTfp': "%5.4s", 'aTfn': "%5.4s",
- 'aTm': "%5.4s", 'aTd': "%5.4s",
- 'mean': "%5.6s", 'smean': "%5.6s",
- 'amean': "%5.6s", 'samean': "%5.6s",
- "GD": "%5.4s", "FP": "%5.4s",
- "GDm": "%5.4s", "FPd": "%5.4s",
- "bufsize": "%5.4s", "hopsize": "%5.4s",
- "time": "%5.4s"}
-
- def dir_eval(self):
- """ evaluate statistical data over the directory """
- v = self.v
-
- v['mode'] = self.params.onsetmode
- v['thres'] = self.params.threshold
- v['bufsize'] = self.params.bufsize
- v['hopsize'] = self.params.hopsize
- v['silence'] = self.params.silence
- v['mintol'] = self.params.mintol
-
- v['Torig'] = sum(v['orig'])
- v['TTm'] = sum(v['Tm'])
- v['TTd'] = sum(v['Td'])
- v['Texpc'] = sum(v['expc'])
- v['Tbad'] = sum(v['bad'])
- v['Tmissed'] = sum(v['missed'])
- v['aTm'] = mmean(v['Tm'])
- v['aTd'] = mmean(v['Td'])
-
- v['mean'] = mmean(v['l'])
- v['smean'] = stdev(v['l'])
-
- v['amean'] = mmean(v['labs'])
- v['samean'] = stdev(v['labs'])
-
- # old type calculations
- # good detection rate
- v['GD'] = 100.*(v['Torig']-v['Tmissed']-v['TTm'])/v['Torig']
- # false positive rate
- v['FP'] = 100.*(v['Tbad']+v['TTd'])/v['Torig']
- # good detection counting merged detections as good
- v['GDm'] = 100.*(v['Torig']-v['Tmissed'])/v['Torig']
- # false positives counting doubled as good
- v['FPd'] = 100.*v['Tbad']/v['Torig']
-
- # mirex type annotations
- totaltrue = v['Texpc']-v['Tbad']-v['TTd']
- totalfp = v['Tbad']+v['TTd']
- totalfn = v['Tmissed']+v['TTm']
- self.v['Ttrue'] = totaltrue
- self.v['Tfp'] = totalfp
- self.v['Tfn'] = totalfn
- # average over the number of annotation files
- N = float(len(self.reslist))
- self.v['aTtrue'] = totaltrue/N
- self.v['aTfp'] = totalfp/N
- self.v['aTfn'] = totalfn/N
-
- # F-measure
- self.P = 100.*float(totaltrue)/max(totaltrue + totalfp,1)
- self.R = 100.*float(totaltrue)/max(totaltrue + totalfn,1)
- #if self.R < 0: self.R = 0
- self.F = 2.* self.P*self.R / max(float(self.P+self.R),1)
- self.v['dist'] = self.F
- self.v['prec'] = self.P
- self.v['recl'] = self.R
-
-
- """
- Plot functions
- """
-
- def plotroc(self,d,plottitle=""):
- import Gnuplot, Gnuplot.funcutils
- gd = []
- fp = []
- for i in self.vlist:
- gd.append(i['GD'])
- fp.append(i['FP'])
- d.append(Gnuplot.Data(fp, gd, with_='linespoints',
- title="%s %s" % (plottitle,i['mode']) ))
-
- def plotplotroc(self,d,outplot=0,extension='ps'):
- import Gnuplot, Gnuplot.funcutils
- from sys import exit
- g = Gnuplot.Gnuplot(debug=0, persist=1)
- if outplot:
- if extension == 'ps': ext, extension = '.ps' , 'postscript'
- elif extension == 'png': ext, extension = '.png', 'png'
- elif extension == 'svg': ext, extension = '.svg', 'svg'
- else: exit("ERR: unknown plot extension")
- g('set terminal %s' % extension)
- g('set output \'roc-%s%s\'' % (outplot,ext))
- xmax = 30 #max(fp)
- ymin = 50
- g('set xrange [0:%f]' % xmax)
- g('set yrange [%f:100]' % ymin)
- # grid set
- g('set grid')
- g('set xtics 0,5,%f' % xmax)
- g('set ytics %f,5,100' % ymin)
- g('set key 27,65')
- #g('set format \"%g\"')
- g.title(basename(self.datadir))
- g.xlabel('false positives (%)')
- g.ylabel('correct detections (%)')
- g.plot(*d)
-
- def plotpr(self,d,plottitle=""):
- import Gnuplot, Gnuplot.funcutils
- x = []
- y = []
- for i in self.vlist:
- x.append(i['prec'])
- y.append(i['recl'])
- d.append(Gnuplot.Data(x, y, with_='linespoints',
- title="%s %s" % (plottitle,i['mode']) ))
-
- def plotplotpr(self,d,outplot=0,extension='ps'):
- import Gnuplot, Gnuplot.funcutils
- from sys import exit
- g = Gnuplot.Gnuplot(debug=0, persist=1)
- if outplot:
- if extension == 'ps': ext, extension = '.ps' , 'postscript'
- elif extension == 'png': ext, extension = '.png', 'png'
- elif extension == 'svg': ext, extension = '.svg', 'svg'
- else: exit("ERR: unknown plot extension")
- g('set terminal %s' % extension)
- g('set output \'pr-%s%s\'' % (outplot,ext))
- g.title(basename(self.datadir))
- g.xlabel('Recall (%)')
- g.ylabel('Precision (%)')
- g.plot(*d)
-
- def plotfmeas(self,d,plottitle=""):
- import Gnuplot, Gnuplot.funcutils
- x,y = [],[]
- for i in self.vlist:
- x.append(i['thres'])
- y.append(i['dist'])
- d.append(Gnuplot.Data(x, y, with_='linespoints',
- title="%s %s" % (plottitle,i['mode']) ))
-
- def plotplotfmeas(self,d,outplot="",extension='ps', title="F-measure"):
- import Gnuplot, Gnuplot.funcutils
- from sys import exit
- g = Gnuplot.Gnuplot(debug=0, persist=1)
- if outplot:
- if extension == 'ps': terminal = 'postscript'
- elif extension == 'png': terminal = 'png'
- elif extension == 'svg': terminal = 'svg'
- else: exit("ERR: unknown plot extension")
- g('set terminal %s' % terminal)
- g('set output \'fmeas-%s.%s\'' % (outplot,extension))
- g.xlabel('threshold \\delta')
- g.ylabel('F-measure (%)')
- g('set xrange [0:1.2]')
- g('set yrange [0:100]')
- g.title(basename(self.datadir))
- # grid set
- #g('set grid')
- #g('set xtics 0,5,%f' % xmax)
- #g('set ytics %f,5,100' % ymin)
- #g('set key 27,65')
- #g('set format \"%g\"')
- g.plot(*d)
-
- def plotfmeasvar(self,d,var,plottitle=""):
- import Gnuplot, Gnuplot.funcutils
- x,y = [],[]
- for i in self.vlist:
- x.append(i[var])
- y.append(i['dist'])
- d.append(Gnuplot.Data(x, y, with_='linespoints',
- title="%s %s" % (plottitle,i['mode']) ))
-
- def plotplotfmeasvar(self,d,var,outplot="",extension='ps', title="F-measure"):
- import Gnuplot, Gnuplot.funcutils
- from sys import exit
- g = Gnuplot.Gnuplot(debug=0, persist=1)
- if outplot:
- if extension == 'ps': terminal = 'postscript'
- elif extension == 'png': terminal = 'png'
- elif extension == 'svg': terminal = 'svg'
- else: exit("ERR: unknown plot extension")
- g('set terminal %s' % terminal)
- g('set output \'fmeas-%s.%s\'' % (outplot,extension))
- g.xlabel(var)
- g.ylabel('F-measure (%)')
- #g('set xrange [0:1.2]')
- g('set yrange [0:100]')
- g.title(basename(self.datadir))
- g.plot(*d)
-
- def plotdiffs(self,d,plottitle=""):
- import Gnuplot, Gnuplot.funcutils
- v = self.v
- l = v['l']
- mean = v['mean']
- smean = v['smean']
- amean = v['amean']
- samean = v['samean']
- val = []
- per = [0] * 100
- for i in range(0,100):
- val.append(i*.001-.05)
- for j in l:
- if abs(j-val[i]) <= 0.001:
- per[i] += 1
- total = v['Torig']
- for i in range(len(per)): per[i] /= total/100.
-
- d.append(Gnuplot.Data(val, per, with_='fsteps',
- title="%s %s" % (plottitle,v['mode']) ))
- #d.append('mean=%f,sigma=%f,eps(x) title \"\"'% (mean,smean))
- #d.append('mean=%f,sigma=%f,eps(x) title \"\"'% (amean,samean))
-
-
- def plotplotdiffs(self,d,outplot=0,extension='ps'):
- import Gnuplot, Gnuplot.funcutils
- from sys import exit
- g = Gnuplot.Gnuplot(debug=0, persist=1)
- if outplot:
- if extension == 'ps': ext, extension = '.ps' , 'postscript'
- elif extension == 'png': ext, extension = '.png', 'png'
- elif extension == 'svg': ext, extension = '.svg', 'svg'
- else: exit("ERR: unknown plot extension")
- g('set terminal %s' % extension)
- g('set output \'diffhist-%s%s\'' % (outplot,ext))
- g('eps(x) = 1./(sigma*(2.*3.14159)**.5) * exp ( - ( x - mean ) ** 2. / ( 2. * sigma ** 2. ))')
- g.title(basename(self.datadir))
- g.xlabel('delay to hand-labelled onset (s)')
- g.ylabel('% number of correct detections / ms ')
- g('set xrange [-0.05:0.05]')
- g('set yrange [0:20]')
- g.plot(*d)
-
-
- def plothistcat(self,d,plottitle=""):
- import Gnuplot, Gnuplot.funcutils
- total = v['Torig']
- for i in range(len(per)): per[i] /= total/100.
-
- d.append(Gnuplot.Data(val, per, with_='fsteps',
- title="%s %s" % (plottitle,v['mode']) ))
- #d.append('mean=%f,sigma=%f,eps(x) title \"\"'% (mean,smean))
- #d.append('mean=%f,sigma=%f,eps(x) title \"\"'% (amean,samean))
-
-
- def plotplothistcat(self,d,outplot=0,extension='ps'):
- import Gnuplot, Gnuplot.funcutils
- from sys import exit
- g = Gnuplot.Gnuplot(debug=0, persist=1)
- if outplot:
- if extension == 'ps': ext, extension = '.ps' , 'postscript'
- elif extension == 'png': ext, extension = '.png', 'png'
- elif extension == 'svg': ext, extension = '.svg', 'svg'
- else: exit("ERR: unknown plot extension")
- g('set terminal %s' % extension)
- g('set output \'diffhist-%s%s\'' % (outplot,ext))
- g('eps(x) = 1./(sigma*(2.*3.14159)**.5) * exp ( - ( x - mean ) ** 2. / ( 2. * sigma ** 2. ))')
- g.title(basename(self.datadir))
- g.xlabel('delay to hand-labelled onset (s)')
- g.ylabel('% number of correct detections / ms ')
- g('set xrange [-0.05:0.05]')
- g('set yrange [0:20]')
- g.plot(*d)
-
-
--- a/python/aubio/gnuplot.py
+++ /dev/null
@@ -1,222 +1,0 @@
-"""Copyright (C) 2004 Paul Brossier <piem@altern.org>
-print aubio.__LICENSE__ for the terms of use
-"""
-
-__LICENSE__ = """\
- Copyright (C) 2004-2009 Paul Brossier <piem@aubio.org>
-
- This file is part of aubio.
-
- aubio is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- aubio is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with aubio. If not, see <http://www.gnu.org/licenses/>.
-"""
-
-
-def audio_to_array(filename):
- import aubio.aubioclass
- from numpy import arange
- hopsize = 2048
- filei = aubio.aubioclass.sndfile(filename)
- framestep = 1/(filei.samplerate()+0.)
- channels = filei.channels()
- myvec = aubio.aubioclass.fvec(hopsize,channels)
- data = []
- readsize = hopsize
- while (readsize==hopsize):
- readsize = filei.read(hopsize,myvec)
- #for i in range(channels):
- i = 0
- curpos = 0
- while (curpos < readsize):
- data.append(myvec.get(curpos,i))
- curpos+=1
- time = arange(len(data))*framestep
- return time,data
-
-def plot_audio(filenames, g, options):
- todraw = len(filenames)
- xorig = 0.
- xratio = 1./todraw
- g('set multiplot;')
- while (len(filenames)):
- time,data = audio_to_array(filenames.pop(0))
- if todraw==1:
- if max(time) < 1.:
- time = [t*1000. for t in time]
- g.xlabel('Time (ms)')
- else:
- g.xlabel('Time (s)')
- g.ylabel('Amplitude')
- curplot = make_audio_plot(time,data)
- g('set size %f,%f;' % (options.xsize*xratio,options.ysize) )
- g('set origin %f,0.;' % (xorig) )
- g('set style data lines; \
- set yrange [-1.:1.]; \
- set xrange [0:%f]' % time[-1])
- g.plot(curplot)
- xorig += options.xsize*xratio
- g('unset multiplot;')
-
-def audio_to_spec(filename,minf = 0, maxf = 0, lowthres = -20.,
- bufsize= 8192, hopsize = 1024):
- from aubioclass import fvec,cvec,pvoc,sndfile
- from math import log10
- filei = sndfile(filename)
- srate = float(filei.samplerate())
- framestep = hopsize/srate
- freqstep = srate/bufsize
- channels = filei.channels()
- myvec = fvec(hopsize,channels)
- myfft = cvec(bufsize,channels)
- pv = pvoc(bufsize,hopsize,channels)
- data,time,freq = [],[],[]
-
- if maxf == 0.: maxf = bufsize/2
- else: maxf = int(maxf/freqstep)
- if minf: minf = int(minf/freqstep)
- else: minf = 0
-
- for f in range(minf,maxf):
- freq.append(f*freqstep)
- readsize = hopsize
- frameread = 0
- while (readsize==hopsize):
- readsize = filei.read(hopsize,myvec)
- pv.do(myvec,myfft)
- frame = []
- i = 0 #for i in range(channels):
- curpos = minf
- while (curpos < maxf):
- frame.append(max(lowthres,20.*log10(myfft.get(curpos,i)**2+0.00001)))
- curpos+=1
- time.append(frameread*framestep)
- data.append(frame)
- frameread += 1
- # crop data if unfinished frames
- if len(data[-1]) != len(data[0]):
- data = data[0:-2]
- time = time[0:-2]
- # verify size consistency
- assert len(data) == len(time)
- assert len(data[0]) == len(freq)
- return data,time,freq
-
-def plot_spec(filename, g, options):
- import Gnuplot
- data,time,freq = audio_to_spec(filename,
- minf=options.minf,maxf=options.maxf,
- bufsize=options.bufsize,hopsize=options.hopsize)
- xorig = 0.
- if max(time) < 1.:
- time = [t*1000. for t in time]
- g.xlabel('Time (ms)')
- else:
- g.xlabel('Time (s)')
- if options.xsize < 0.5 and not options.log and max(time) > 1.:
- freq = [f/1000. for f in freq]
- options.minf /= 1000.
- options.maxf /= 1000.
- g.ylabel('Frequency (kHz)')
- else:
- g.ylabel('Frequency (Hz)')
- g('set pm3d map')
- g('set palette rgbformulae -25,-24,-32')
- g('set cbtics 20')
- #g('set colorbox horizontal')
- g('set xrange [0.:%f]' % time[-1])
- if options.log:
- g('set log y')
- g('set yrange [%f:%f]' % (max(10,options.minf),options.maxf))
- else:
- g('set yrange [%f:%f]' % (options.minf,options.maxf))
- g.splot(Gnuplot.GridData(data,time,freq, binary=1))
- #xorig += 1./todraw
-
-def downsample_audio(time,data,maxpoints=10000):
- """ resample audio data to last only maxpoints """
- from numpy import array, resize
- length = len(time)
- downsample = length/maxpoints
- if downsample == 0: downsample = 1
- x = resize(array(time),length)[0:-1:downsample]
- y = resize(array(data),length)[0:-1:downsample]
- return x,y
-
-def make_audio_plot(time,data,maxpoints=10000):
- """ create gnuplot plot from an audio file """
- import Gnuplot, Gnuplot.funcutils
- x,y = downsample_audio(time,data,maxpoints=maxpoints)
- return Gnuplot.Data(x,y,with_='lines')
-
-def make_audio_envelope(time,data,maxpoints=10000):
- """ create gnuplot plot from an audio file """
- from numpy import array
- import Gnuplot, Gnuplot.funcutils
- bufsize = 500
- x = [i.mean() for i in resize(array(time), (len(time)/bufsize,bufsize))]
- y = [i.mean() for i in resize(array(data), (len(time)/bufsize,bufsize))]
- x,y = downsample_audio(x,y,maxpoints=maxpoints)
- return Gnuplot.Data(x,y,with_='lines')
-
-def gnuplot_addargs(parser):
- """ add common gnuplot argument to OptParser object """
- parser.add_option("-x","--xsize",
- action="store", dest="xsize", default=1.,
- type='float',help="define xsize for plot")
- parser.add_option("-y","--ysize",
- action="store", dest="ysize", default=1.,
- type='float',help="define ysize for plot")
- parser.add_option("--debug",
- action="store_true", dest="debug", default=False,
- help="use gnuplot debug mode")
- parser.add_option("--persist",
- action="store_false", dest="persist", default=True,
- help="do not use gnuplot persistant mode")
- parser.add_option("--lmargin",
- action="store", dest="lmargin", default=None,
- type='int',help="define left margin for plot")
- parser.add_option("--rmargin",
- action="store", dest="rmargin", default=None,
- type='int',help="define right margin for plot")
- parser.add_option("--bmargin",
- action="store", dest="bmargin", default=None,
- type='int',help="define bottom margin for plot")
- parser.add_option("--tmargin",
- action="store", dest="tmargin", default=None,
- type='int',help="define top margin for plot")
- parser.add_option("-O","--outplot",
- action="store", dest="outplot", default=None,
- help="save plot to output.{ps,png}")
-
-def gnuplot_create(outplot='',extension='', options=None):
- import Gnuplot
- if options:
- g = Gnuplot.Gnuplot(debug=options.debug, persist=options.persist)
- else:
- g = Gnuplot.Gnuplot(persist=1)
- if not extension or not outplot: return g
- if extension == 'ps': ext, extension = '.ps' , 'postscript'
- elif extension == 'eps': ext, extension = '.eps' , 'postscript enhanced'
- elif extension == 'epsc': ext, extension = '.eps' , 'postscript enhanced color'
- elif extension == 'png': ext, extension = '.png', 'png'
- elif extension == 'svg': ext, extension = '.svg', 'svg'
- else: exit("ERR: unknown plot extension")
- g('set terminal %s' % extension)
- if options and options.lmargin: g('set lmargin %i' % options.lmargin)
- if options and options.rmargin: g('set rmargin %i' % options.rmargin)
- if options and options.bmargin: g('set bmargin %i' % options.bmargin)
- if options and options.tmargin: g('set tmargin %i' % options.tmargin)
- if outplot != "stdout":
- g('set output \'%s%s\'' % (outplot,ext))
- if options: g('set size %f,%f' % (options.xsize, options.ysize))
- return g
--- a/python/aubio/median.py
+++ /dev/null
@@ -1,69 +1,0 @@
-"""Copyright (C) 2004 Paul Brossier <piem@altern.org>
-print aubio.__LICENSE__ for the terms of use
-"""
-
-__LICENSE__ = """\
- Copyright (C) 2004-2009 Paul Brossier <piem@aubio.org>
-
- This file is part of aubio.
-
- aubio is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- aubio is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with aubio. If not, see <http://www.gnu.org/licenses/>.
-"""
-
-"""
-original author Tim Peters
-modified by Paul Brossier <piem@altern.org>
-inspired from http://www.ics.uci.edu/~eppstein/161/python/peters-selection.py
-"""
-
-def short_find(a, rank):
- """ find the rank-th value in sorted a """
- # copy to b before sorting
- b = a[:]
- b.sort()
- return b[rank - 1]
-
-def percental(a, rank):
- """ Find the rank'th-smallest value in a, in worst-case linear time. """
- n = len(a)
- assert 1 <= rank <= n
- if n <= 7:
- return short_find(a, rank)
-
- ## Find median of median-of-7's.
- ##medians = [short_find(a[i : i+7], 4) for i in xrange(0, n-6, 7)]
- #median = find(medians, (len(medians) + 1) // 2)
-
- # modified to Find median
- median = short_find([a[0], a[-1], a[n//2]], 2)
-
- # Partition around the median.
- # a[:i] <= median
- # a[j+1:] >= median
- i, j = 0, n-1
- while i <= j:
- while a[i] < median:
- i += 1
- while a[j] > median:
- j -= 1
- if i <= j:
- a[i], a[j] = a[j], a[i]
- i += 1
- j -= 1
-
- if rank <= i:
- return percental(a[:i], rank)
- else:
- return percental(a[i:], rank - i)
-
--- a/python/aubio/onsetcompare.py
+++ /dev/null
@@ -1,143 +1,0 @@
-"""Copyright (C) 2004 Paul Brossier <piem@altern.org>
-print aubio.__LICENSE__ for the terms of use
-"""
-
-__LICENSE__ = """\
- Copyright (C) 2004-2009 Paul Brossier <piem@aubio.org>
-
- This file is part of aubio.
-
- aubio is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- aubio is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with aubio. If not, see <http://www.gnu.org/licenses/>.
-"""
-
-""" this file contains routines to compare two lists of onsets or notes.
-it somewhat implements the Receiver Operating Statistic (ROC).
-see http://en.wikipedia.org/wiki/Receiver_operating_characteristic
-"""
-
-def onset_roc(ltru, lexp, eps):
- """ compute differences between two lists
- orig = hits + missed + merged
- expc = hits + bad + doubled
- returns orig, missed, merged, expc, bad, doubled
- """
- orig, expc = len(ltru), len(lexp)
- # if lexp is empty
- if expc == 0 : return orig,orig,0,0,0,0
- missed, bad, doubled, merged = 0, 0, 0, 0
- # find missed and doubled ones first
- for x in ltru:
- correspond = 0
- for y in lexp:
- if abs(x-y) <= eps: correspond += 1
- if correspond == 0: missed += 1
- elif correspond > 1: doubled += correspond - 1
- # then look for bad and merged ones
- for y in lexp:
- correspond = 0
- for x in ltru:
- if abs(x-y) <= eps: correspond += 1
- if correspond == 0: bad += 1
- elif correspond > 1: merged += correspond - 1
- # check consistancy of the results
- assert ( orig - missed - merged == expc - bad - doubled)
- return orig, missed, merged, expc, bad, doubled
-
-def onset_diffs(ltru, lexp, eps):
- """ compute differences between two lists
- orig = hits + missed + merged
- expc = hits + bad + doubled
- returns orig, missed, merged, expc, bad, doubled
- """
- orig, expc = len(ltru), len(lexp)
- # if lexp is empty
- l = []
- if expc == 0 : return l
- # find missed and doubled ones first
- for x in ltru:
- correspond = 0
- for y in lexp:
- if abs(x-y) <= eps: l.append(y-x)
- # return list of diffs
- return l
-
-def onset_rocloc(ltru, lexp, eps):
- """ compute differences between two lists
- orig = hits + missed + merged
- expc = hits + bad + doubled
- returns orig, missed, merged, expc, bad, doubled
- """
- orig, expc = len(ltru), len(lexp)
- l = []
- labs = []
- mean = 0
- # if lexp is empty
- if expc == 0 : return orig,orig,0,0,0,0,l,mean
- missed, bad, doubled, merged = 0, 0, 0, 0
- # find missed and doubled ones first
- for x in ltru:
- correspond = 0
- for y in lexp:
- if abs(x-y) <= eps: correspond += 1
- if correspond == 0: missed += 1
- elif correspond > 1: doubled += correspond - 1
- # then look for bad and merged ones
- for y in lexp:
- correspond = 0
- for x in ltru:
- if abs(x-y) <= eps:
- correspond += 1
- l.append(y-x)
- labs.append(abs(y-x))
- if correspond == 0: bad += 1
- elif correspond > 1: merged += correspond - 1
- # check consistancy of the results
- assert ( orig - missed - merged == expc - bad - doubled)
- return orig, missed, merged, expc, bad, doubled, l, labs
-
-def notes_roc (la, lb, eps):
- from numpy import transpose, add, resize
- """ creates a matrix of size len(la)*len(lb) then look for hit and miss
- in it within eps tolerance windows """
- gdn,fpw,fpg,fpa,fdo,fdp = 0,0,0,0,0,0
- m = len(la)
- n = len(lb)
- x = resize(la[:][0],(n,m))
- y = transpose(resize(lb[:][0],(m,n)))
- teps = (abs(x-y) <= eps[0])
- x = resize(la[:][1],(n,m))
- y = transpose(resize(lb[:][1],(m,n)))
- tpitc = (abs(x-y) <= eps[1])
- res = teps * tpitc
- res = add.reduce(res,axis=0)
- for i in range(len(res)) :
- if res[i] > 1:
- gdn+=1
- fdo+=res[i]-1
- elif res [i] == 1:
- gdn+=1
- fpa = n - gdn - fpa
- return gdn,fpw,fpg,fpa,fdo,fdp
-
-def load_onsets(filename) :
- """ load onsets targets / candidates files in arrays """
- l = [];
-
- f = open(filename,'ro')
- while 1:
- line = f.readline().split()
- if not line : break
- l.append(float(line[0]))
-
- return l
--- a/python/aubio/plot/keyboard.py
+++ /dev/null
@@ -1,46 +1,0 @@
-
-def draw_keyboard(firstnote = 21, lastnote = 108, y0 = 0, y1 = 1):
- import Gnuplot
- octaves = 10
-
- # build template of white notes
- scalew = 12/7.
- xw_temp = [i*scalew for i in range(0,7)]
- # build template of black notes
- scaleb = 6/7.
- xb_temp = [i*scaleb for i in [1,3,7,9,11]]
-
- xb,xw = [],[]
- for octave in range(octaves-1):
- for i in xb_temp:
- curnote = i+12*octave
- if curnote > firstnote-1 and curnote < lastnote+1:
- xb = xb + [curnote]
- for octave in range(octaves-1):
- for i in xw_temp:
- curnote = i+12*octave
- if curnote > firstnote-1 and curnote < lastnote+1:
- xw = xw + [curnote]
-
- xwdelta = [1/2. * scalew for i in range(len(xw))]
- yw = [y0+(y1-y0)*1/2. for i in range(len(xw))]
- ywdelta = [(y1-y0)*1/2. for i in range(len(xw))]
-
- xbdelta = [2/3. * scaleb for i in range(len(xb))]
- yb = [y0+(y1-y0)*2/3. for i in range(len(xb))]
- ybdelta = [(y1-y0)*1/3. for i in range(len(xb))]
-
- whites = Gnuplot.Data(xw,yw,xwdelta,ywdelta,with_ = 'boxxyerrorbars')
- blacks = Gnuplot.Data(xb,yb,xbdelta,ybdelta,with_ = 'boxxyerrorbars fill solid')
-
- return blacks,whites
-
-if __name__ == '__main__':
- from aubio.gnuplot import gnuplot_create
- blacks,whites = draw_keyboard(firstnote = 21, lastnote = 108)
- g = gnuplot_create('','')
- #g('set style fill solid .5')
- #g('set xrange [60-.5:72+.5]')
- #g('set yrange [-0.1:1.1]')
-
- g.plot(whites,blacks)
--- a/python/aubio/plot/notes.py
+++ /dev/null
@@ -1,90 +1,0 @@
-__LICENSE__ = """\
- Copyright (C) 2004-2009 Paul Brossier <piem@aubio.org>
-
- This file is part of aubio.
-
- aubio is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- aubio is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with aubio. If not, see <http://www.gnu.org/licenses/>.
-"""
-
-def plotnote(la,title=None) :
- if la[0,:].size() == 3:
- d = plotnote_withends(la, plot_title=title)
- else:
- # scale data if in freq (for REF.txt files)
- if max(la[:,1] > 128 ):
- print "scaling frequency data to midi range"
- la[:,1] /= 6.875
- la[:,1] = log(la[:,1])/0.6931
- la[:,1] *= 12
- la[:,1] -= 3
- d = plotnote_withoutends(la, plot_title=title)
- return d
-
-def plotnote_multi(lalist,title=None,fileout=None) :
- d=list()
- for i in range(len(lalist)):
- d.append(plotnote(lalist[i], title=title))
- return d
-
-
-def plotnote_withends(la,plot_title=None) :
- from numpy import array
- import Gnuplot, Gnuplot.funcutils
- d=[]
- x_widths = array(la[:,1]-la[:,0])/2.
- d.append(Gnuplot.Data(
- la[:,0]+x_widths, # x centers
- la[:,2], # y centers
- x_widths, # x errors
- __notesheight*ones(len(la)), # y errors
- title=plot_title,with_=('boxxyerrorbars fs 3')))
- return d
-
-
-def plotnote_withoutends(la,plot_title=None) :
- """ bug: fails drawing last note """
- from numpy import array
- import Gnuplot, Gnuplot.funcutils
- d=[]
- x_widths = array(la[1:,0]-la[:-1,0])/2;
- d.append(Gnuplot.Data(
- la[:-1,0]+x_widths, # x centers
- la[:-1,1], # y centers
- x_widths, # x errors
- __notesheight*ones(len(la)-1), # y errors
- title=plot_title,with_=('boxxyerrorbars fs 3')))
- return d
-
-def plotnote_do(d,fileout=None):
- import Gnuplot, Gnuplot.funcutils
- g = Gnuplot.Gnuplot(debug=1, persist=1)
- g.gnuplot('set style fill solid border 1; \
- set size ratio 1/6; \
- set boxwidth 0.9 relative; \
- set mxtics 2.5; \
- set mytics 2.5; \
- set xtics 5; \
- set ytics 1; \
- set grid xtics ytics mxtics mytics')
-
- g.xlabel('Time (s)')
- g.ylabel('Midi pitch')
- # do the plot
- #g.gnuplot('set multiplot')
- #for i in d:
- g.plot(d[0])
- #g.gnuplot('set nomultiplot')
- if fileout != None:
- g.hardcopy(fileout, enhanced=1, color=0)
-
--- a/python/aubio/task/__init__.py
+++ /dev/null
@@ -1,9 +1,0 @@
-from aubio.aubioclass import *
-from aubio.task.task import task
-from aubio.task.params import taskparams
-from aubio.task.silence import tasksilence
-from aubio.task.onset import taskonset
-from aubio.task.beat import taskbeat
-from aubio.task.cut import taskcut
-from aubio.task.pitch import taskpitch
-from aubio.task.notes import tasknotes
--- a/python/aubio/task/beat.py
+++ /dev/null
@@ -1,262 +1,0 @@
-from aubio.aubioclass import *
-from onset import taskonset
-
-class taskbeat(taskonset):
- def __init__(self,input,params=None,output=None):
- """ open the input file and initialize arguments
- parameters should be set *before* calling this method.
- """
- taskonset.__init__(self,input,output=None,params=params)
- self.btwinlen = 512**2/self.params.hopsize
- self.btstep = self.btwinlen/4
- self.btoutput = fvec(self.btstep,self.channels)
- self.dfframe = fvec(self.btwinlen,self.channels)
- self.bt = beattracking(self.btwinlen,self.channels)
- self.pos2 = 0
- self.old = -1000
-
- def __call__(self):
- taskonset.__call__(self)
- #results = taskonset.__call__(self)
- # write to current file
- if self.pos2 == self.btstep - 1 :
- self.bt.do(self.dfframe,self.btoutput)
- for i in range (self.btwinlen - self.btstep):
- self.dfframe.set(self.dfframe.get(i+self.btstep,0),i,0)
- for i in range(self.btwinlen - self.btstep, self.btwinlen):
- self.dfframe.set(0,i,0)
- self.pos2 = -1;
- self.pos2 += 1
- val = self.opick.pp.getval()
- #if not results: val = 0
- #else: val = results[1]
- self.dfframe.set(val,self.btwinlen - self.btstep + self.pos2,0)
- i=0
- for i in range(1,int( self.btoutput.get(0,0) ) ):
- if self.pos2 == self.btoutput.get(i,0) and \
- aubio_silence_detection(self.myvec(),
- self.params.silence)!=1:
- now = self.frameread-0
- period = (60 * self.params.samplerate) / ((now - self.old) * self.params.hopsize)
- self.old = now
- return now,period
-
- def eval(self,results,tol=0.20,tolcontext=0.25):
- obeats = self.gettruth()
- etime = [result[0] for result in results]
- otime = [obeat[0] for obeat in obeats]
- CML_tot, CML_max, CML_start, CML_end = 0,0,0,0
- AML_tot, AML_max, AML_start, AML_end = 0,0,0,0
- AMLd_tot, AMLd_max, AMLd_start, AMLd_end = 0,0,0,0
- AMLh_tot, AMLh_max, AMLh_start, AMLh_end = 0,0,0,0
- AMLo_tot, AMLo_max, AMLo_start, AMLo_end = 0,0,0,0
- # results iteration
- j = 1
- # for each annotation
- for i in range(2,len(otime)-2):
- if j+1 >= len(etime): break
- count = 0
- # look for next matching beat
- while otime[i] > etime[j] - (otime[i] - otime[i+1])*tol:
- if count > 0:
- #print "spurious etime"
- if CML_end - CML_start > CML_max:
- CML_max = CML_end - CML_start
- CML_start, CML_end = j, j
- if AMLh_end - AMLh_start > AMLh_max:
- AMLh_max = AMLh_end - AMLh_start
- AMLh_start, AMLh_end = j, j
- if AMLd_end - AMLd_start > AMLd_max:
- AMLd_max = AMLd_end - AMLd_start
- AMLd_start, AMLd_end = j, j
- if AMLo_end - AMLo_start > AMLo_max:
- AMLo_max = AMLo_end - AMLo_start
- AMLo_start, AMLo_end = j, j
- j += 1
- count += 1
- if j+1 >= len(etime): break
- #print otime[i-1],etime[j-1]," ",otime[i],etime[j]," ",otime[i+1],etime[j+1]
- prevtempo = (otime[i] - otime[i-1])
- nexttempo = (otime[i+1] - otime[i])
-
- current0 = (etime[j] > otime[i] - prevtempo*tol)
- current1 = (etime[j] < otime[i] + prevtempo*tol)
-
- # check correct tempo
- prev0 = (etime[j-1] > otime[i-1] - prevtempo*tolcontext)
- prev1 = (etime[j-1] < otime[i-1] + prevtempo*tolcontext)
- next0 = (etime[j+1] > otime[i+1] - nexttempo*tolcontext)
- next1 = (etime[j+1] < otime[i+1] + nexttempo*tolcontext)
-
- # check for off beat
- prevoffb0 = (etime[j-1] > otime[i-1] - prevtempo/2 - prevtempo*tolcontext)
- prevoffb1 = (etime[j-1] < otime[i-1] - prevtempo/2 + prevtempo*tolcontext)
- nextoffb0 = (etime[j+1] > otime[i+1] - nexttempo/2 - nexttempo*tolcontext)
- nextoffb1 = (etime[j+1] < otime[i+1] - nexttempo/2 + nexttempo*tolcontext)
-
- # check half tempo
- prevhalf0 = (etime[j-1] > otime[i-1] + prevtempo - prevtempo/2*tolcontext)
- prevhalf1 = (etime[j-1] < otime[i-1] + prevtempo + prevtempo/2*tolcontext)
- nexthalf0 = (etime[j+1] > otime[i+1] - nexttempo - nexttempo/2*tolcontext)
- nexthalf1 = (etime[j+1] < otime[i+1] - nexttempo + nexttempo/2*tolcontext)
-
- # check double tempo
- prevdoub0 = (etime[j-1] > otime[i-1] - prevtempo - prevtempo*2*tolcontext)
- prevdoub1 = (etime[j-1] < otime[i-1] - prevtempo + prevtempo*2*tolcontext)
- nextdoub0 = (etime[j+1] > otime[i+1] + nexttempo - nexttempo*2*tolcontext)
- nextdoub1 = (etime[j+1] < otime[i+1] + nexttempo + nexttempo*2*tolcontext)
-
- if current0 and current1 and prev0 and prev1 and next0 and next1:
- #print "YES!"
- CML_end = j
- CML_tot += 1
- else:
- if CML_end - CML_start > CML_max:
- CML_max = CML_end - CML_start
- CML_start, CML_end = j, j
- if current0 and current1 and prevhalf0 and prevhalf1 and nexthalf0 and nexthalf1:
- AMLh_end = j
- AMLh_tot += 1
- else:
- if AMLh_end - AMLh_start > AMLh_max:
- AMLh_max = AMLh_end - AMLh_start
- AMLh_start, AMLh_end = j, j
- if current0 and current1 and prevdoub0 and prevdoub1 and nextdoub0 and nextdoub1:
- AMLd_end = j
- AMLd_tot += 1
- else:
- if AMLd_end - AMLd_start > AMLd_max:
- AMLd_max = AMLd_end - AMLd_start
- AMLd_start, AMLd_end = j, j
- if current0 and current1 and prevoffb0 and prevoffb1 and nextoffb0 and nextoffb1:
- AMLo_end = j
- AMLo_tot += 1
- else:
- if AMLo_end - AMLo_start > AMLo_max:
- AMLo_max = AMLo_end - AMLo_start
- AMLo_start, AMLo_end = j, j
- # look for next matching beat
- count = 0
- while otime[i] > etime[j] - (otime[i] - otime[i+1])*tolcontext:
- j += 1
- if count > 0:
- #print "spurious etime"
- start = j
- count += 1
- total = float(len(otime))
- CML_tot /= total
- AMLh_tot /= total
- AMLd_tot /= total
- AMLo_tot /= total
- CML_cont = CML_max/total
- AMLh_cont = AMLh_max/total
- AMLd_cont = AMLd_max/total
- AMLo_cont = AMLo_max/total
- return CML_cont, CML_tot, AMLh_cont, AMLh_tot, AMLd_cont, AMLd_tot, AMLo_cont, AMLo_tot
-
-# for i in allfreq:
-# freq.append(float(i) / 2. / N * samplerate )
-# while freq[i]>freqs[j]:
-# j += 1
-# a0 = weight[j-1]
-# a1 = weight[j]
-# f0 = freqs[j-1]
-# f1 = freqs[j]
-# if f0!=0:
-# iweight.append((a1-a0)/(f1-f0)*freq[i] + (a0 - (a1 - a0)/(f1/f0 -1.)))
-# else:
-# iweight.append((a1-a0)/(f1-f0)*freq[i] + a0)
-# while freq[i]>freqs[j]:
-# j += 1
-
- def eval2(self,results,tol=0.2):
- truth = self.gettruth()
- obeats = [i[0] for i in truth]
- ebeats = [i[0]*self.params.step for i in results]
- NP = max(len(obeats), len(ebeats))
- N = int(round(max(max(obeats), max(ebeats))*100.)+100)
- W = int(round(tol*100.*60./median([i[1] for i in truth], len(truth)/2)))
- ofunc = [0 for i in range(N+W)]
- efunc = [0 for i in range(N+W)]
- for i in obeats: ofunc[int(round(i*100.)+W)] = 1
- for i in ebeats: efunc[int(round(i*100.)+W)] = 1
- assert len(obeats) == sum(ofunc)
- autocor = 0; m =0
- for m in range (-W, W):
- for i in range(W,N):
- autocor += ofunc[i] * efunc[i-m]
- autocor /= float(NP)
- return autocor
-
- def evaluation(self,results,tol=0.2,start=5.):
-
- """ beat tracking evaluation function
-
- computes P-score of experimental results (ebeats)
- against ground truth annotations (obeats) """
-
- from aubio.median import short_find as median
- truth = self.gettruth()
- ebeats = [i[0]*self.params.step for i in results]
- obeats = [i[0] for i in truth]
-
- # trim anything found before start
- while obeats[0] < start: obeats.pop(0)
- while ebeats[0] < start: ebeats.pop(0)
- # maximum number of beats found
- NP = max(len(obeats), len(ebeats))
- # length of ofunc and efunc vector
- N = int(round(max(max(obeats), max(ebeats))*100.)+100)
- # compute W median of ground truth tempi
- tempi = []
- for i in range(1,len(obeats)): tempi.append(obeats[i]-obeats[i-1])
- W = int(round(tol*100.*median(tempi,len(tempi)/2)))
- # build ofunc and efunc functions, starting with W zeros
- ofunc = [0 for i in range(N+W)]
- efunc = [0 for i in range(N+W)]
- for i in obeats: ofunc[int(round(i*100.)+W)] = 1
- for i in ebeats: efunc[int(round(i*100.)+W)] = 1
- # optional: make sure we didn't miss any beats
- assert len(obeats) == sum(ofunc)
- assert len(ebeats) == sum(efunc)
- # compute auto correlation
- autocor = 0; m =0
- for m in range (-W, W):
- for i in range(W,N):
- autocor += ofunc[i] * efunc[i-m]
- autocor /= float(NP)
- return autocor
-
- def gettruth(self):
- import os.path
- from aubio.txtfile import read_datafile
- datafile = self.input.replace('.wav','.txt')
- if not os.path.isfile(datafile):
- print "no ground truth "
- return False,False
- else:
- values = read_datafile(datafile,depth=0)
- old = -1000
- for i in range(len(values)):
- now = values[i]
- period = 60 / (now - old)
- old = now
- values[i] = [now,period]
- return values
-
-
- def plot(self,oplots,results):
- import Gnuplot
- oplots.append(Gnuplot.Data(results,with_='linespoints',title="auto"))
-
- def plotplot(self,wplot,oplots,outplot=None,extension=None,xsize=1.,ysize=1.,spectro=False):
- import Gnuplot
- from aubio.gnuplot import gnuplot_create, audio_to_array, make_audio_plot
- import re
- # audio data
- #time,data = audio_to_array(self.input)
- #f = make_audio_plot(time,data)
-
- g = gnuplot_create(outplot=outplot, extension=extension)
- oplots = [Gnuplot.Data(self.gettruth(),with_='linespoints',title="orig")] + oplots
- g.plot(*oplots)
--- a/python/aubio/task/cut.py
+++ /dev/null
@@ -1,42 +1,0 @@
-from task import task
-from aubio.aubioclass import *
-
-class taskcut(task):
- def __init__(self,input,slicetimes,params=None,output=None):
- """ open the input file and initialize arguments
- parameters should be set *before* calling this method.
- """
- from os.path import basename,splitext
- task.__init__(self,input,output=None,params=params)
- self.soundoutbase, self.soundoutext = splitext(basename(self.input))
- self.newname = "%s%s%09.5f%s%s" % (self.soundoutbase,".",
- self.frameread*self.params.step,".",self.soundoutext)
- self.fileo = sndfile(self.newname,model=self.filei)
- self.myvec = fvec(self.params.hopsize,self.channels)
- self.mycopy = fvec(self.params.hopsize,self.channels)
- self.slicetimes = slicetimes
-
- def __call__(self):
- task.__call__(self)
- # write to current file
- if len(self.slicetimes) and self.frameread >= self.slicetimes[0][0]:
- self.slicetimes.pop(0)
- # write up to 1st zero crossing
- zerocross = 0
- while ( abs( self.myvec.get(zerocross,0) ) > self.params.zerothres ):
- zerocross += 1
- writesize = self.fileo.write(zerocross,self.myvec)
- fromcross = 0
- while (zerocross < self.readsize):
- for i in range(self.channels):
- self.mycopy.set(self.myvec.get(zerocross,i),fromcross,i)
- fromcross += 1
- zerocross += 1
- del self.fileo
- self.fileo = sndfile("%s%s%09.5f%s%s" % (self.soundoutbase,".",
- self.frameread*self.params.step,".",self.soundoutext),model=self.filei)
- writesize = self.fileo.write(fromcross,self.mycopy)
- else:
- writesize = self.fileo.write(self.readsize,self.myvec)
-
-
--- a/python/aubio/task/notes.py
+++ /dev/null
@@ -1,159 +1,0 @@
-
-from aubio.task import task
-from aubio.aubioclass import *
-
-class tasknotes(task):
- def __init__(self,input,output=None,params=None):
- task.__init__(self,input,params=params)
- self.opick = onsetpick(self.params.bufsize,
- self.params.hopsize,
- self.channels,
- self.myvec,
- self.params.threshold,
- mode=self.params.onsetmode,
- dcthreshold=self.params.dcthreshold,
- derivate=self.params.derivate)
- self.pitchdet = pitch(mode=self.params.pitchmode,
- bufsize=self.params.pbufsize,
- hopsize=self.params.phopsize,
- channels=self.channels,
- samplerate=self.srate,
- omode=self.params.omode)
- self.olist = []
- self.ofunc = []
- self.maxofunc = 0
- self.last = -1000
- self.oldifreq = 0
- if self.params.localmin:
- self.ovalist = [0., 0., 0., 0., 0.]
-
- def __call__(self):
- from aubio.median import short_find
- task.__call__(self)
- isonset,val = self.opick.do(self.myvec)
- if (aubio_silence_detection(self.myvec(),self.params.silence)):
- isonset=0
- freq = -1.
- else:
- freq = self.pitchdet(self.myvec)
- minpitch = self.params.pitchmin
- maxpitch = self.params.pitchmax
- if maxpitch and freq > maxpitch :
- freq = -1.
- elif minpitch and freq < minpitch :
- freq = -1.
- freq = aubio_freqtomidi(freq)
- if self.params.pitchsmooth:
- self.shortlist.append(freq)
- self.shortlist.pop(0)
- smoothfreq = short_find(self.shortlist,
- len(self.shortlist)/2)
- freq = smoothfreq
- now = self.frameread
- ifreq = int(round(freq))
- if self.oldifreq == ifreq:
- self.oldifreq = ifreq
- else:
- self.oldifreq = ifreq
- ifreq = 0
- # take back delay
- if self.params.delay != 0.: now -= self.params.delay
- if now < 0 :
- now = 0
- if (isonset == 1):
- if self.params.mintol:
- # prune doubled
- if (now - self.last) > self.params.mintol:
- self.last = now
- return now, 1, freq, ifreq
- else:
- return now, 0, freq, ifreq
- else:
- return now, 1, freq, ifreq
- else:
- return now, 0, freq, ifreq
-
-
- def fprint(self,foo):
- print self.params.step*foo[0], foo[1], foo[2], foo[3]
-
- def compute_all(self):
- """ Compute data """
- now, onset, freq, ifreq = [], [], [], []
- while(self.readsize==self.params.hopsize):
- n, o, f, i = self()
- now.append(n*self.params.step)
- onset.append(o)
- freq.append(f)
- ifreq.append(i)
- if self.params.verbose:
- self.fprint((n,o,f,i))
- return now, onset, freq, ifreq
-
- def plot(self,now,onset,freq,ifreq,oplots):
- import Gnuplot
-
- oplots.append(Gnuplot.Data(now,freq,with_='lines',
- title=self.params.pitchmode))
- oplots.append(Gnuplot.Data(now,ifreq,with_='lines',
- title=self.params.pitchmode))
-
- temponsets = []
- for i in onset:
- temponsets.append(i*1000)
- oplots.append(Gnuplot.Data(now,temponsets,with_='impulses',
- title=self.params.pitchmode))
-
- def plotplot(self,wplot,oplots,outplot=None,multiplot = 0):
- from aubio.gnuplot import gnuplot_init, audio_to_array, make_audio_plot
- import re
- import Gnuplot
- # audio data
- time,data = audio_to_array(self.input)
- f = make_audio_plot(time,data)
-
- # check if ground truth exists
- #timet,pitcht = self.gettruth()
- #if timet and pitcht:
- # oplots = [Gnuplot.Data(timet,pitcht,with_='lines',
- # title='ground truth')] + oplots
-
- t = Gnuplot.Data(0,0,with_='impulses')
-
- g = gnuplot_init(outplot)
- g('set title \'%s\'' % (re.sub('.*/','',self.input)))
- g('set multiplot')
- # hack to align left axis
- g('set lmargin 15')
- # plot waveform and onsets
- g('set size 1,0.3')
- g('set origin 0,0.7')
- g('set xrange [0:%f]' % max(time))
- g('set yrange [-1:1]')
- g.ylabel('amplitude')
- g.plot(f)
- g('unset title')
- # plot onset detection function
-
-
- g('set size 1,0.7')
- g('set origin 0,0')
- g('set xrange [0:%f]' % max(time))
- g('set yrange [20:100]')
- g('set key right top')
- g('set noclip one')
- #g('set format x ""')
- #g('set log y')
- #g.xlabel('time (s)')
- g.ylabel('f0 (Hz)')
- if multiplot:
- for i in range(len(oplots)):
- # plot onset detection functions
- g('set size 1,%f' % (0.7/(len(oplots))))
- g('set origin 0,%f' % (float(i)*0.7/(len(oplots))))
- g('set xrange [0:%f]' % max(time))
- g.plot(oplots[i])
- else:
- g.plot(*oplots)
- #g('unset multiplot')
-
--- a/python/aubio/task/onset.py
+++ /dev/null
@@ -1,220 +1,0 @@
-from aubio.task.task import task
-from aubio.aubioclass import *
-
-class taskonset(task):
- def __init__(self,input,output=None,params=None):
- """ open the input file and initialize arguments
- parameters should be set *before* calling this method.
- """
- task.__init__(self,input,params=params)
- self.opick = onsetpick(self.params.bufsize,
- self.params.hopsize,
- self.myvec,
- self.params.threshold,
- mode=self.params.onsetmode,
- dcthreshold=self.params.dcthreshold,
- derivate=self.params.derivate)
- self.olist = []
- self.ofunc = []
- self.maxofunc = 0
- self.last = 0
- if self.params.localmin:
- self.ovalist = [0., 0., 0., 0., 0.]
-
- def __call__(self):
- task.__call__(self)
- isonset,val = self.opick.do(self.myvec)
- if (aubio_silence_detection(self.myvec(),self.params.silence)):
- isonset=0
- if self.params.storefunc:
- self.ofunc.append(val)
- if self.params.localmin:
- if val > 0: self.ovalist.append(val)
- else: self.ovalist.append(0)
- self.ovalist.pop(0)
- if (isonset > 0.):
- if self.params.localmin:
- # find local minima before peak
- i=len(self.ovalist)-1
- while self.ovalist[i-1] < self.ovalist[i] and i > 0:
- i -= 1
- now = (self.frameread+1-i)
- else:
- now = self.frameread
- # take back delay
- if self.params.delay != 0.: now -= self.params.delay
- if now < 0 :
- now = 0
- if self.params.mintol:
- # prune doubled
- if (now - self.last) > self.params.mintol:
- self.last = now
- return now, val
- else:
- return now, val
-
-
- def fprint(self,foo):
- print self.params.step*foo[0]
-
- def eval(self,inputdata,ftru,mode='roc',vmode=''):
- from aubio.txtfile import read_datafile
- from aubio.onsetcompare import onset_roc, onset_diffs, onset_rocloc
- ltru = read_datafile(ftru,depth=0)
- lres = []
- for i in range(len(inputdata)): lres.append(inputdata[i][0]*self.params.step)
- if vmode=='verbose':
- print "Running with mode %s" % self.params.onsetmode,
- print " and threshold %f" % self.params.threshold,
- print " on file", self.input
- #print ltru; print lres
- if mode == 'local':
- l = onset_diffs(ltru,lres,self.params.tol)
- mean = 0
- for i in l: mean += i
- if len(l): mean = "%.3f" % (mean/len(l))
- else: mean = "?0"
- return l, mean
- elif mode == 'roc':
- self.orig, self.missed, self.merged, \
- self.expc, self.bad, self.doubled = \
- onset_roc(ltru,lres,self.params.tol)
- elif mode == 'rocloc':
- self.v = {}
- self.v['orig'], self.v['missed'], self.v['Tm'], \
- self.v['expc'], self.v['bad'], self.v['Td'], \
- self.v['l'], self.v['labs'] = \
- onset_rocloc(ltru,lres,self.params.tol)
-
- def plot(self,onsets,ofunc,wplot,oplots,nplot=False):
- import Gnuplot, Gnuplot.funcutils
- import aubio.txtfile
- import os.path
- from numpy import arange, array, ones
- from aubio.onsetcompare import onset_roc
-
- x1,y1,y1p = [],[],[]
- oplot = []
- if self.params.onsetmode in ('mkl','kl'): ofunc[0:10] = [0] * 10
-
- self.lenofunc = len(ofunc)
- self.maxofunc = max(ofunc)
- # onset detection function
- downtime = arange(len(ofunc))*self.params.step
- oplot.append(Gnuplot.Data(downtime,ofunc,with_='lines',title=self.params.onsetmode))
-
- # detected onsets
- if not nplot:
- for i in onsets:
- x1.append(i[0]*self.params.step)
- y1.append(self.maxofunc)
- y1p.append(-self.maxofunc)
- #x1 = array(onsets)*self.params.step
- #y1 = self.maxofunc*ones(len(onsets))
- if x1:
- oplot.append(Gnuplot.Data(x1,y1,with_='impulses'))
- wplot.append(Gnuplot.Data(x1,y1p,with_='impulses'))
-
- oplots.append((oplot,self.params.onsetmode,self.maxofunc))
-
- # check if ground truth datafile exists
- datafile = self.input.replace('.wav','.txt')
- if datafile == self.input: datafile = ""
- if not os.path.isfile(datafile):
- self.title = "" #"(no ground truth)"
- else:
- t_onsets = aubio.txtfile.read_datafile(datafile)
- x2 = array(t_onsets).resize(len(t_onsets))
- y2 = self.maxofunc*ones(len(t_onsets))
- wplot.append(Gnuplot.Data(x2,y2,with_='impulses'))
-
- tol = 0.050
-
- orig, missed, merged, expc, bad, doubled = \
- onset_roc(x2,x1,tol)
- self.title = "GD %2.3f%% FP %2.3f%%" % \
- ((100*float(orig-missed-merged)/(orig)),
- (100*float(bad+doubled)/(orig)))
-
-
- def plotplot(self,wplot,oplots,outplot=None,extension=None,xsize=1.,ysize=1.,spectro=False):
- from aubio.gnuplot import gnuplot_create, audio_to_array, make_audio_plot, audio_to_spec
- import re
- # prepare the plot
- g = gnuplot_create(outplot=outplot, extension=extension)
- g('set title \'%s\'' % (re.sub('.*/','',self.input)))
- if spectro:
- g('set size %f,%f' % (xsize,1.3*ysize) )
- else:
- g('set size %f,%f' % (xsize,ysize) )
- g('set multiplot')
-
- # hack to align left axis
- g('set lmargin 3')
- g('set rmargin 6')
-
- if spectro:
- import Gnuplot
- minf = 50
- maxf = 500
- data,time,freq = audio_to_spec(self.input,minf=minf,maxf=maxf)
- g('set size %f,%f' % (1.24*xsize , 0.34*ysize) )
- g('set origin %f,%f' % (-0.12,0.65*ysize))
- g('set xrange [0.:%f]' % time[-1])
- g('set yrange [%f:%f]' % (minf,maxf))
- g('set pm3d map')
- g('unset colorbox')
- g('set lmargin 0')
- g('set rmargin 0')
- g('set tmargin 0')
- g('set palette rgbformulae -25,-24,-32')
- g.xlabel('time (s)',offset=(0,1.))
- g.ylabel('freq (Hz)')
- g('set origin 0,%f' % (1.0*ysize) )
- g('set format x "%1.1f"')
- #if log:
- # g('set yrange [%f:%f]' % (max(10,minf),maxf))
- # g('set log y')
- g.splot(Gnuplot.GridData(data,time,freq, binary=1, title=''))
- else:
- # plot waveform and onsets
- time,data = audio_to_array(self.input)
- wplot = [make_audio_plot(time,data)] + wplot
- g('set origin 0,%f' % (0.7*ysize) )
- g('set size %f,%f' % (xsize,0.3*ysize))
- g('set format y "%1f"')
- g('set xrange [0:%f]' % max(time))
- g('set yrange [-1:1]')
- g('set noytics')
- g('set y2tics -1,1')
- g.xlabel('time (s)',offset=(0,0.7))
- g.ylabel('amplitude')
- g.plot(*wplot)
-
- # default settings for next plots
- g('unset title')
- g('set format x ""')
- g('set format y "%3e"')
- g('set tmargin 0')
- g.xlabel('')
-
- N = len(oplots)
- y = 0.7*ysize # the vertical proportion of the plot taken by onset functions
- delta = 0.035 # the constant part of y taken by last plot label and data
- for i in range(N):
- # plot onset detection functions
- g('set size %f,%f' % ( xsize, (y-delta)/N))
- g('set origin 0,%f' % ((N-i-1)*(y-delta)/N + delta ))
- g('set nokey')
- g('set xrange [0:%f]' % (self.lenofunc*self.params.step))
- g('set yrange [0:%f]' % (1.1*oplots[i][2]))
- g('set y2tics ("0" 0, "%d" %d)' % (round(oplots[i][2]),round(oplots[i][2])))
- g.ylabel(oplots[i][1])
- if i == N-1:
- g('set size %f,%f' % ( xsize, (y-delta)/N + delta ) )
- g('set origin 0,0')
- g.xlabel('time (s)', offset=(0,0.7))
- g('set format x')
- g.plot(*oplots[i][0])
-
- g('unset multiplot')
--- a/python/aubio/task/params.py
+++ /dev/null
@@ -1,33 +1,0 @@
-
-class taskparams(object):
- """ default parameters for task classes """
- def __init__(self,input=None,output=None):
- self.silence = -90
- self.derivate = False
- self.localmin = False
- self.delay = 4.
- self.storefunc = False
- self.bufsize = 512
- self.hopsize = 256
- self.pbufsize = 2048
- self.phopsize = 512
- self.samplerate = 44100
- self.tol = 0.05
- self.mintol = 0.0
- self.step = float(self.hopsize)/float(self.samplerate)
- self.threshold = 0.1
- self.onsetmode = 'dual'
- self.pitchmode = 'yin'
- # best threshold for yin monophonic Mirex04 (depth of f0)
- self.yinthresh = 0.15
- # best thresh for yinfft monophonic Mirex04 (tradeoff sil/gd)
- # also best param for yinfft polyphonic Mirex04
- self.yinfftthresh = 0.85
- self.pitchsmooth = 0
- self.pitchmin=20.
- self.pitchmax=20000.
- self.pitchdelay = -0.5
- self.dcthreshold = -1.
- self.omode = "freq"
- self.verbose = False
-
--- a/python/aubio/task/pitch.py
+++ /dev/null
@@ -1,234 +1,0 @@
-from aubio.task.task import task
-from aubio.task.silence import tasksilence
-from aubio.aubioclass import *
-
-class taskpitch(task):
- def __init__(self,input,params=None):
- task.__init__(self,input,params=params)
- self.shortlist = [0. for i in range(self.params.pitchsmooth)]
- if self.params.pitchmode == 'yin':
- tolerance = self.params.yinthresh
- elif self.params.pitchmode == 'yinfft':
- tolerance = self.params.yinfftthresh
- else:
- tolerance = 0.
- self.pitchdet = pitch(mode=self.params.pitchmode,
- bufsize=self.params.bufsize,
- hopsize=self.params.hopsize,
- samplerate=self.srate,
- omode=self.params.omode,
- tolerance = tolerance)
-
- def __call__(self):
- from aubio.median import short_find
- task.__call__(self)
- if (aubio_silence_detection(self.myvec(),self.params.silence)==1):
- freq = -1.
- else:
- freq = self.pitchdet(self.myvec)
- minpitch = self.params.pitchmin
- maxpitch = self.params.pitchmax
- if maxpitch and freq > maxpitch :
- freq = -1.
- elif minpitch and freq < minpitch :
- freq = -1.
- if self.params.pitchsmooth:
- self.shortlist.append(freq)
- self.shortlist.pop(0)
- smoothfreq = short_find(self.shortlist,
- len(self.shortlist)/2)
- return smoothfreq
- else:
- return freq
-
- def compute_all(self):
- """ Compute data """
- mylist = []
- while(self.readsize==self.params.hopsize):
- freq = self()
- mylist.append(freq)
- if self.params.verbose:
- self.fprint("%s\t%s" % (self.frameread*self.params.step,freq))
- return mylist
-
- def gettruth(self):
- """ extract ground truth array in frequency """
- import os.path
- """ from wavfile.txt """
- datafile = self.input.replace('.wav','.txt')
- if datafile == self.input: datafile = ""
- """ from file.<midinote>.wav """
- # FIXME very weak check
- floatpit = self.input.split('.')[-2]
- if not os.path.isfile(datafile) and len(self.input.split('.')) < 3:
- print "no ground truth "
- return False,False
- elif floatpit:
- try:
- self.truth = float(floatpit)
- #print "ground truth found in filename:", self.truth
- tasksil = tasksilence(self.input,params=self.params)
- time,pitch =[],[]
- while(tasksil.readsize==tasksil.params.hopsize):
- tasksil()
- time.append(tasksil.params.step*(tasksil.frameread))
- if not tasksil.issilence:
- pitch.append(self.truth)
- else:
- pitch.append(-1.)
- return time,pitch
- except ValueError:
- # FIXME very weak check
- if not os.path.isfile(datafile):
- print "no ground truth found"
- return 0,0
- else:
- from aubio.txtfile import read_datafile
- values = read_datafile(datafile)
- time, pitch = [], []
- for i in range(len(values)):
- time.append(values[i][0])
- if values[i][1] == 0.0:
- pitch.append(-1.)
- else:
- pitch.append(aubio_freqtomidi(values[i][1]))
- return time,pitch
-
- def oldeval(self,results):
- def mmean(l):
- return sum(l)/max(float(len(l)),1)
-
- from aubio.median import percental
- timet,pitcht = self.gettruth()
- res = []
- for i in results:
- #print i,self.truth
- if i <= 0: pass
- else: res.append(self.truth-i)
- if not res or len(res) < 3:
- avg = self.truth; med = self.truth
- else:
- avg = mmean(res)
- med = percental(res,len(res)/2)
- return self.truth, self.truth-med, self.truth-avg
-
- def eval(self,pitch,tol=0.5):
- timet,pitcht = self.gettruth()
- pitch = [aubio_freqtomidi(i) for i in pitch]
- for i in range(len(pitch)):
- if pitch[i] == "nan" or pitch[i] == -1:
- pitch[i] = -1
- time = [ (i+self.params.pitchdelay)*self.params.step for i in range(len(pitch)) ]
- #print len(timet),len(pitcht)
- #print len(time),len(pitch)
- if len(timet) != len(time):
- time = time[1:len(timet)+1]
- pitch = pitch[1:len(pitcht)+1]
- #pitcht = [aubio_freqtomidi(i) for i in pitcht]
- for i in range(len(pitcht)):
- if pitcht[i] == "nan" or pitcht[i] == "-inf" or pitcht[i] == -1:
- pitcht[i] = -1
- assert len(timet) == len(time)
- assert len(pitcht) == len(pitch)
- osil, esil, opit, epit, echr = 0, 0, 0, 0, 0
- for i in range(len(pitcht)):
- if pitcht[i] == -1: # currently silent
- osil += 1 # count a silence
- if pitch[i] <= 0. or pitch[i] == "nan":
- esil += 1 # found a silence
- else:
- opit +=1
- if abs(pitcht[i] - pitch[i]) < tol:
- epit += 1
- echr += 1
- elif abs(pitcht[i] - pitch[i]) % 12. < tol:
- echr += 1
- #else:
- # print timet[i], pitcht[i], time[i], pitch[i]
- #print "origsilence", "foundsilence", "origpitch", "foundpitch", "orig pitchroma", "found pitchchroma"
- #print 100.*esil/float(osil), 100.*epit/float(opit), 100.*echr/float(opit)
- return osil, esil, opit, epit, echr
-
- def plot(self,pitch,wplot,oplots,titles,outplot=None):
- import Gnuplot
-
- time = [ (i+self.params.pitchdelay)*self.params.step for i in range(len(pitch)) ]
- pitch = [aubio_freqtomidi(i) for i in pitch]
- oplots.append(Gnuplot.Data(time,pitch,with_='lines',
- title=self.params.pitchmode))
- titles.append(self.params.pitchmode)
-
-
- def plotplot(self,wplot,oplots,titles,outplot=None,extension=None,xsize=1.,ysize=1.,multiplot = 1, midi = 1, truth = 1):
- from aubio.gnuplot import gnuplot_create , audio_to_array, make_audio_plot
- import re
- import Gnuplot
-
- # check if ground truth exists
- if truth:
- timet,pitcht = self.gettruth()
- if timet and pitcht:
- oplots = [Gnuplot.Data(timet,pitcht,with_='lines',
- title='ground truth')] + oplots
-
- g = gnuplot_create(outplot=outplot, extension=extension)
- g('set title \'%s\'' % (re.sub('.*/','',self.input)))
- g('set size %f,%f' % (xsize,ysize) )
- g('set multiplot')
- # hack to align left axis
- g('set lmargin 4')
- g('set rmargin 4')
- # plot waveform
- time,data = audio_to_array(self.input)
- wplot = [make_audio_plot(time,data)]
- g('set origin 0,%f' % (0.7*ysize) )
- g('set size %f,%f' % (xsize,0.3*ysize))
- #g('set format y "%1f"')
- g('set xrange [0:%f]' % max(time))
- g('set yrange [-1:1]')
- g('set noytics')
- g('set y2tics -1,1')
- g.xlabel('time (s)',offset=(0,0.7))
- g.ylabel('amplitude')
- g.plot(*wplot)
-
- # default settings for next plots
- g('unset title')
- g('set format x ""')
- g('set format y "%3e"')
- g('set tmargin 0')
- g.xlabel('')
- g('set noclip one')
-
- if not midi:
- g('set log y')
- #g.xlabel('time (s)')
- g.ylabel('f0 (Hz)')
- g('set yrange [100:%f]' % self.params.pitchmax)
- else:
- g.ylabel('midi')
- g('set yrange [%f:%f]' % (aubio_freqtomidi(self.params.pitchmin), aubio_freqtomidi(self.params.pitchmax)))
- g('set y2tics %f,%f' % (round(aubio_freqtomidi(self.params.pitchmin)+.5),12))
-
- if multiplot:
- N = len(oplots)
- y = 0.7*ysize # the vertical proportion of the plot taken by onset functions
- delta = 0.035 # the constant part of y taken by last plot label and data
- for i in range(N):
- # plot pitch detection functions
- g('set size %f,%f' % ( xsize, (y-delta)/N))
- g('set origin 0,%f' % ((N-i-1)*(y-delta)/N + delta ))
- g('set nokey')
- g('set xrange [0:%f]' % max(time))
- g.ylabel(titles[i])
- if i == N-1:
- g('set size %f,%f' % (xsize, (y-delta)/N + delta ) )
- g('set origin 0,0')
- g.xlabel('time (s)', offset=(0,0.7))
- g('set format x')
- g.plot(oplots[i])
- else:
- g('set key right top')
- g.plot(*oplots)
- g('unset multiplot')
-
--- a/python/aubio/task/silence.py
+++ /dev/null
@@ -1,28 +1,0 @@
-from aubio.task.task import task
-from aubio.aubioclass import *
-
-class tasksilence(task):
- wassilence = 1
- issilence = 1
- def __call__(self):
- task.__call__(self)
- if (aubio_silence_detection(self.myvec(),self.params.silence)==1):
- if self.wassilence == 1: self.issilence = 1
- else: self.issilence = 2
- self.wassilence = 1
- else:
- if self.wassilence <= 0: self.issilence = 0
- else: self.issilence = -1
- self.wassilence = 0
- if self.issilence == -1:
- return max(self.frameread-self.params.delay,0.), -1
- elif self.issilence == 2:
- return max(self.frameread+self.params.delay,0.), 2
-
- def fprint(self,foo):
- print self.params.step*foo[0],
- if foo[1] == 2: print "OFF"
- else: print "ON"
-
-
-
--- a/python/aubio/task/task.py
+++ /dev/null
@@ -1,53 +1,0 @@
-from aubio.aubioclass import *
-from params import taskparams
-
-class task(taskparams):
- """ default template class to apply tasks on a stream """
- def __init__(self,input,output=None,params=None):
- """ open the input file and initialize default argument
- parameters should be set *before* calling this method.
- """
- import time
- self.tic = time.time()
- if params == None: self.params = taskparams()
- else: self.params = params
- self.frameread = 0
- self.readsize = self.params.hopsize
- self.input = input
- self.filei = sndfile(self.input)
- self.srate = self.filei.samplerate()
- self.params.step = float(self.params.hopsize)/float(self.srate)
- self.myvec = fvec(self.params.hopsize)
- self.output = output
-
- def __call__(self):
- self.readsize = self.filei.read(self.params.hopsize,self.myvec)
- self.frameread += 1
-
- def compute_all(self):
- """ Compute data """
- mylist = []
- while(self.readsize==self.params.hopsize):
- tmp = self()
- if tmp:
- mylist.append(tmp)
- if self.params.verbose:
- self.fprint(tmp)
- return mylist
-
- def fprint(self,foo):
- print foo
-
- def eval(self,results):
- """ Eval data """
- pass
-
- def plot(self):
- """ Plot data """
- pass
-
- def time(self):
- import time
- #print "CPU time is now %f seconds," % time.clock(),
- #print "task execution took %f seconds" % (time.time() - self.tic)
- return time.time() - self.tic
--- a/python/aubio/txtfile.py
+++ /dev/null
@@ -1,47 +1,0 @@
-"""Copyright (C) 2004 Paul Brossier <piem@altern.org>
-print aubio.__LICENSE__ for the terms of use
-"""
-
-__LICENSE__ = """\
- Copyright (C) 2004-2009 Paul Brossier <piem@aubio.org>
-
- This file is part of aubio.
-
- aubio is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- aubio is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with aubio. If not, see <http://www.gnu.org/licenses/>.
-"""
-
-def read_datafile(filename,depth=-1):
- """read list data from a text file (columns of float)"""
- if filename == '--' or filename == '-':
- import sys
- fres = sys.stdin
- else:
- fres = open(filename,'ro')
- l = []
- while 1:
- tmp = fres.readline()
- if not tmp : break
- else: tmp = tmp.split()
- if depth > 0:
- for i in range(min(depth,len(tmp))):
- tmp[i] = float(tmp[i])
- l.append(tmp)
- elif depth == 0:
- l.append(float(tmp[0]))
- else:
- for i in range(len(tmp)):
- tmp[i] = float(tmp[i])
- l.append(tmp)
- return l
-
--- a/python/aubio/web/browser.py
+++ /dev/null
@@ -1,167 +1,0 @@
- #
- # Copyright 2004 Apache Software Foundation
- #
- # Licensed under the Apache License, Version 2.0 (the "License"); you
- # may not use this file except in compliance with the License. You
- # may obtain a copy of the License at
- #
- # http://www.apache.org/licenses/LICENSE-2.0
- #
- # Unless required by applicable law or agreed to in writing, software
- # distributed under the License is distributed on an "AS IS" BASIS,
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- # implied. See the License for the specific language governing
- # permissions and limitations under the License.
- #
- # Originally developed by Gregory Trubetskoy.
- #
- # $Id: publisher.py,v 1.36 2004/02/16 19:47:27 grisha Exp $
-
-"""
- This handler is conceputally similar to Zope's ZPublisher, except
- that it:
-
- 1. Is written specifically for mod_python and is therefore much faster
- 2. Does not require objects to have a documentation string
- 3. Passes all arguments as simply string
- 4. Does not try to match Python errors to HTTP errors
- 5. Does not give special meaning to '.' and '..'.
-
- This is a modified version of mod_python.publisher.handler Only the first
- directory argument is matched, the rest is left for path_info. A default
- one must be provided.
-
-"""
-
-from mod_python import apache
-from mod_python import util
-from mod_python.publisher import resolve_object,process_auth,imp_suffixes
-
-import sys
-import os
-import re
-
-from types import *
-
-def configure_handler(req,default):
-
- req.allow_methods(["GET", "POST"])
- if req.method not in ["GET", "POST"]:
- raise apache.SERVER_RETURN, apache.HTTP_METHOD_NOT_ALLOWED
-
- func_path = ""
- if req.path_info:
- func_path = req.path_info[1:] # skip first /
- #func_path = func_path.replace("/", ".")
- #if func_path[-1:] == ".":
- # func_path = func_path[:-1]
- # changed: only keep the first directory
- func_path = re.sub('/.*','',func_path)
-
- # default to 'index' if no path_info was given
- if not func_path:
- func_path = "index"
-
- # if any part of the path begins with "_", abort
- if func_path[0] == '_' or func_path.count("._"):
- raise apache.SERVER_RETURN, apache.HTTP_NOT_FOUND
-
- ## import the script
- path, module_name = os.path.split(req.filename)
- if not module_name:
- module_name = "index"
-
- # get rid of the suffix
- # explanation: Suffixes that will get stripped off
- # are those that were specified as an argument to the
- # AddHandler directive. Everything else will be considered
- # a package.module rather than module.suffix
- exts = req.get_addhandler_exts()
- if not exts:
- # this is SetHandler, make an exception for Python suffixes
- exts = imp_suffixes
- if req.extension: # this exists if we're running in a | .ext handler
- exts += req.extension[1:]
- if exts:
- suffixes = exts.strip().split()
- exp = "\\." + "$|\\.".join(suffixes)
- suff_matcher = re.compile(exp) # python caches these, so its fast
- module_name = suff_matcher.sub("", module_name)
-
- # import module (or reload if needed)
- # the [path] argument tells import_module not to allow modules whose
- # full path is not in [path] or below.
- config = req.get_config()
- autoreload=int(config.get("PythonAutoReload", 1))
- log=int(config.get("PythonDebug", 0))
- try:
- module = apache.import_module(module_name,
- autoreload=autoreload,
- log=log,
- path=[path])
- except ImportError:
- et, ev, etb = sys.exc_info()
- # try again, using default module, perhaps this is a
- # /directory/function (as opposed to /directory/module/function)
- func_path = module_name
- module_name = "index"
- try:
- module = apache.import_module(module_name,
- autoreload=autoreload,
- log=log,
- path=[path])
- except ImportError:
- # raise the original exception
- raise et, ev, etb
-
- # does it have an __auth__?
- realm, user, passwd = process_auth(req, module)
-
- # resolve the object ('traverse')
- try:
- object = resolve_object(req, module, func_path, realm, user, passwd)
- except AttributeError:
- # changed, return the default path instead
- #raise apache.SERVER_RETURN, apache.HTTP_NOT_FOUND
- object = default
- # not callable, a class or an unbound method
- if (not callable(object) or
- type(object) is ClassType or
- (hasattr(object, 'im_self') and not object.im_self)):
-
- result = str(object)
-
- else:
- # callable, (but not a class or unbound method)
-
- # process input, if any
- req.form = util.FieldStorage(req, keep_blank_values=1)
-
- result = util.apply_fs_data(object, req.form, req=req)
-
- if result or req.bytes_sent > 0 or req.next:
-
- if result is None:
- result = ""
- else:
- result = str(result)
-
- # unless content_type was manually set, we will attempt
- # to guess it
- if not req._content_type_set:
- # make an attempt to guess content-type
- if result[:100].strip()[:6].lower() == '<html>' \
- or result.find('</') > 0:
- req.content_type = 'text/html'
- else:
- req.content_type = 'text/plain'
-
- if req.method != "HEAD":
- req.write(result)
- else:
- req.write("")
- return apache.OK
- else:
- req.log_error("mod_python.publisher: %s returned nothing." % `object`)
- return apache.HTTP_INTERNAL_SERVER_ERROR
-
--- a/python/aubio/web/html.py
+++ /dev/null
@@ -1,286 +1,0 @@
-from aubio.bench.node import *
-
-def parse_args(req):
- req.basehref = BASEHREF
- req.datadir = DATADIR
- if req.path_info: path_info = req.path_info
- else: path_info = '/'
- location = re.sub('^/show_[a-z0-9]*/','',path_info)
- location = re.sub('^/play_[a-z0-9]*/','',location)
- location = re.sub('^/index/','',location)
- location = re.sub('^/','',location)
- location = re.sub('/$','',location)
- datapath = "%s/%s" % (DATADIR,location)
- respath = "%s/%s" % (DATADIR,location)
- last = re.sub('/$','',location)
- last = last.split('/')[-1]
- first = path_info.split('/')[1]
- # store some of this in the mp_request
- req.location, req.datapath, req.respath = location, datapath, respath
- req.first, req.last = first, last
-
- if location:
- if not (os.path.isfile(datapath) or
- os.path.isdir(datapath) or
- location in ['feedback','email']):
- # the path was not understood
- from mod_python import apache
- req.write("<html> path not found %s</html>" % (datapath))
- raise apache.SERVER_RETURN, apache.OK
- #from mod_python import apache
- #raise apache.SERVER_RETURN, apache.HTTP_NOT_FOUND
-
-def navigation(req):
- """ main html navigation header """
- from mod_python import psp
- req.content_type = "text/html"
- parse_args(req)
- datapath = req.datapath
- location = req.location
-
- # deal with session
- if req.sess.is_new():
- msg = "<b>Welcome %s</b><br>" % req.sess['login']
- else:
- msg = "<b>Welcome back %s</b><br>" % req.sess['login']
-
- # start writing
- tmpl = psp.PSP(req, filename='header.tmpl')
- tmpl.run(vars = { 'title': "aubioweb / %s / %s" % (req.first,location),
- 'basehref': '/~piem/',
- 'message': msg,
- 'action': req.first})
-
- req.write("<h2>Content of ")
- print_link(req,"","/")
- y = location.split('/')
- for i in range(len(y)-1):
- print_link(req,"/".join(y[:i+1]),y[i])
- req.write(" / ")
- req.write("%s</h2>\n" % y[-1])
-
- a = {'show_info' : 'info',
- 'show_sound': 'waveform',
- 'show_onset': 'onset',
- 'index' : 'index',
- 'show_pitch': 'pitch',
- 'play_m3u': 'stream (m3u/ogg)',
- 'play_ogg': 'save (ogg)',
- 'play_wav': 'save (wav)',
- }
-
- # print task lists (only remaining tasks)
- print_link(req,re.sub('%s.*'%req.last,'',location),"go up")
- akeys = a.keys(); akeys.sort();
- curkey = req.first
- for akey in akeys:
- if akey != curkey:
- req.write(":: ")
- print_link(req,"/".join((akey,location)),a[akey])
- else:
- req.write(":: ")
- req.write("<b>%s</b>" % a[akey])
- req.write("<br>")
-
- # list the content of the directories
- listdir,listfiles = [],[]
- if os.path.isdir(datapath):
- listfiles = list_snd_files(datapath)
- listdir = list_dirs(datapath)
- listdir.pop(0) # kick the current dir
- elif os.path.isfile(datapath):
- listfiles = [datapath]
- listdir = [re.sub(req.last,'',location)]
-
- link_list(req,listdir,title="Subdirectories")
- link_list(req,listfiles,title="Files")
-
-def footer(req):
- """ html navigation footer """
- from mod_python import psp
- tmpl = psp.PSP(req, filename='footer.tmpl')
- tmpl.run(vars = { 'time': -req.mtime+req.request_time })
-
-def apply_on_data(req, func,**keywords):
- # bug: hardcoded snd file filter
- act_on_data(func,req.datapath,req.respath,
- filter="f -maxdepth 1 -name '*.wav' -o -name '*.aif'",**keywords)
-
-def print_link(req,target,name,basehref=BASEHREF):
- req.write("<a href='%s/%s'>%s</a>\n" % (basehref,target,name))
-
-def print_img(req,target,name='',basehref=BASEHREF):
- if name == '': name = target
- req.write("<img src='%s/%s' alt='%s' title='%s'>\n" % (basehref,target,name,name))
-
-def link_list(req,targetlist,basehref=BASEHREF,title=None):
- if len(targetlist) > 1:
- if title: req.write("<h3>%s</h3>"%title)
- req.write('<ul>')
- for i in targetlist:
- s = re.split('%s/'%DATADIR,i,maxsplit=1)[1]
- if s:
- req.write('<li>')
- print_link(req,s,s)
- req.write('</li>')
- req.write('</ul>')
-
-def print_list(req,list):
- req.write("<pre>\n")
- for i in list: req.write("%s\n" % i)
- req.write("</pre>\n")
-
-def print_command(req,command):
- req.write("<h4>%s</h4>\n" % re.sub('%%','%',command))
- def print_runcommand(input,output):
- cmd = re.sub('(%)?%i','%s' % input, command)
- cmd = re.sub('(%)?%o','%s' % output, cmd)
- print_list(req,runcommand(cmd))
- apply_on_data(req,print_runcommand)
-
-def datapath_to_location(input):
- location = re.sub(DATADIR,'',input)
- return re.sub('^/*','',location)
-
-## drawing hacks
-def draw_func(req,func):
- import re
- req.content_type = "image/png"
- # build location (strip the func_path, add DATADIR)
- location = re.sub('^/draw_[a-z]*/','%s/'%DATADIR,req.path_info)
- location = re.sub('.png$','',location)
- if not os.path.isfile(location):
- from mod_python import apache
- raise apache.SERVER_RETURN, apache.HTTP_NOT_FOUND
- # replace location in func
- cmd = re.sub('(%)?%i','%s' % location, func)
- # add PYTHONPATH at the beginning,
- cmd = "%s%s 2> /dev/null" % (PYTHONPATH,cmd)
- for each in runcommand(cmd):
- req.write("%s\n"%each)
-
-def show_task(req,task):
- def show_task_file(input,output,task):
- location = datapath_to_location(input)
- print_img(req,"draw_%s/%s" % (task,location))
- navigation(req)
- req.write("<h3>%s</h3>\n" % task)
- apply_on_data(req,show_task_file,task=task)
- footer(req)
-
-## waveform_foo
-def draw_sound(req):
- draw_func(req,"aubioplot-audio %%i stdout 2> /dev/null")
-
-def show_sound(req):
- show_task(req,"sound")
-
-## pitch foo
-def draw_pitch(req,threshold='0.3'):
- draw_func(req,"aubiopitch -i %%i -p -m schmitt,yin,fcomb,mcomb -t %s -O stdout" % threshold)
-
-def show_pitch(req):
- show_task(req,"pitch")
-
-## onset foo
-def draw_onset(req,threshold='0.3'):
- draw_func(req,"aubiocut -i %%i -p -m complex -t %s -O stdout" % threshold)
-
-def show_onset(req,threshold='0.3',details=''):
- def onset_file(input,output):
- location = datapath_to_location(input)
- print_img(req,"draw_onset/%s?threshold=%s"%(location,threshold))
- print_link(req,"?threshold=%s" % (float(threshold)-0.1),"-")
- req.write("%s\n" % threshold)
- print_link(req,"?threshold=%s" % (float(threshold)+0.1),"+")
- # bug: hardcoded sndfile extension
- anote = re.sub('\.wav$','.txt',input)
- if anote == input: anote = ""
- res = get_extract(input,threshold)
- if os.path.isfile(anote):
- tru = get_anote(anote)
- print_list(req,get_results(tru,res,0.05))
- else:
- req.write("no ground truth found<br>\n")
- if details:
- req.write("<h4>Extraction</h4>\n")
- print_list(req,res)
- else:
- req.write("<a href='%s/show_onset/%s?details=yes&threshold=%s'>details</a><br>\n" %
- (req.basehref,location,threshold))
- if details and os.path.isfile(anote):
- req.write("<h4>Computed differences</h4>\n")
- ldiffs = get_diffs(tru,res,0.05)
- print_list(req,ldiffs)
- req.write("<h4>Annotations</h4>\n")
- print_list(req,tru)
- navigation(req)
- req.write("<h3>Onset</h3>\n")
- apply_on_data(req,onset_file)
- footer(req)
-
-def get_anote(anote):
- import aubio.onsetcompare
- # FIXME: should import with txtfile.read_datafile
- return aubio.onsetcompare.load_onsets(anote)
-
-def get_diffs(anote,extract,tol):
- import aubio.onsetcompare
- return aubio.onsetcompare.onset_diffs(anote,extract,tol)
-
-def get_extract(datapath,threshold='0.3'):
- cmd = "%saubiocut -v -m complex -t %s -i %s" % (PYTHONPATH,threshold,datapath)
- lo = runcommand(cmd)
- for i in range(len(lo)): lo[i] = float(lo[i])
- return lo
-
-def get_results(anote,extract,tol):
- import aubio.onsetcompare
- orig, missed, merged, expc, bad, doubled = aubio.onsetcompare.onset_roc(anote,extract,tol)
- s =("GD %2.8f\t" % (100*float(orig-missed-merged)/(orig)),
- "FP %2.8f\t" % (100*float(bad+doubled)/(orig)) ,
- "GD-merged %2.8f\t" % (100*float(orig-missed)/(orig)) ,
- "FP-pruned %2.8f\t" % (100*float(bad)/(orig)) )
- return s
-
-# play m3u foo
-def play_m3u(req):
- def show_task_file(input,output,task):
- location = datapath_to_location(input)
- req.write("http://%s%s/play_ogg/%s\n" % (HOSTNAME,BASEHREF,re.sub("play_m3u",task,location)))
- req.content_type = "audio/mpegurl"
- parse_args(req)
- apply_on_data(req,show_task_file,task="play_ogg")
-
-# play wav foo
-def play_wav(req):
- req.content_type = "audio/x-wav"
- func = "cat %%i"
- # build location (strip the func_path, add DATADIR)
- location = re.sub('^/play_wav/','%s/'%DATADIR,req.path_info)
- if not os.path.isfile(location):
- from mod_python import apache
- raise apache.SERVER_RETURN, apache.HTTP_NOT_FOUND
- # replace location in func
- cmd = re.sub('(%)?%i','%s' % location, func)
- # add PYTHONPATH at the beginning,
- cmd = "%s 2> /dev/null" % cmd
- for each in runcommand(cmd):
- req.write("%s\n"%each)
-
-# play ogg foo
-def play_ogg(req):
- req.content_type = "application/ogg"
- func = "oggenc -o - %%i"
- # build location (strip the func_path, add DATADIR)
- location = re.sub('^/play_ogg/','%s/'%DATADIR,req.path_info)
- location = re.sub('.ogg$','',location)
- if not os.path.isfile(location):
- from mod_python import apache
- raise apache.SERVER_RETURN, apache.HTTP_NOT_FOUND
- # replace location in func
- cmd = re.sub('(%)?%i','%s' % location, func)
- # add PYTHONPATH at the beginning,
- cmd = "%s 2> /dev/null" % cmd
- for each in runcommand(cmd):
- req.write("%s\n"%each)
--- a/python/aubio/wscript_build
+++ /dev/null
@@ -1,17 +1,0 @@
-# vim:set syntax=python:
-
-pyaubio = ctx.new_task_gen(name = 'python-aubio',
- features = 'c cshlib pyext',
- source = '../../swig/aubio.i',
- add_objects = 'sndfileio',
- target = '_aubiowrapper',
- use = ['aubio'],
- uselib = ['SNDFILE'],
- swig_flags = '-python -Wall',
- includes = '. ../../src ../../examples')
-pyaubio.install_path = '${PYTHONDIR}/${PACKAGE}'
-
-# install python files
-ctx.install_files('${PYTHONDIR}/${PACKAGE}/', ctx.path.ant_glob('**/*.py'))
-# install swig generated python file
-ctx.install_files('${PYTHONDIR}/${PACKAGE}/', '../../swig/aubiowrapper.py')
--- a/python/aubiocompare-onset
+++ /dev/null
@@ -1,114 +1,0 @@
-#! /usr/bin/python
-
-"""Copyright (C) 2004 Paul Brossier <piem@altern.org>
-
-print aubio.__LICENSE__ for the terms of use
-
-or see LICENSE.txt in the aubio installation directory.
-"""
-__LICENSE__ = """\
- Copyright (C) 2004-2009 Paul Brossier <piem@aubio.org>
-
- This file is part of aubio.
-
- aubio is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- aubio is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with aubio. If not, see <http://www.gnu.org/licenses/>.
-"""
-
-
-__HELP__ = """\
-# required arguments
- -c targetfilename
- -o detectfilename
-(both must be text files with 1 time a line expressed in seconds)
-
-# optional arguments
- -D <delay> delay in seconds
- -v verbose mode
- -d debug mode
-
-# output
-results:number of correct detections
- number of incorrect detections
- number of doubled detections
- number of total detections
- number of total targets
-
-# example:
-$ aubioonset-comp -c checked-onsets.txt -o handlab-onsets.txt -v
-( gd fp dd ) tot / real
-( 5 4 0 ) 9 / 9
-55.5555555556 %GD 44.4444444444 %FP 0.0 %OD
-
-# bugs
-does not scale to very long lists
-"""
-
-import sys
-from aubio.onsetcompare import onset_roc, onset_diffs
-from aubio.txtfile import read_datafile
-
-# default values
-fileo=None;filec=None;vmode=None;dmode=None;delay=0.
-# default tolerance is 50 ms
-#tol = 0.050
-tol = 0.048
-# default mode is onset
-mode = 'onset'
-
-while len(sys.argv) >=2:
- option = sys.argv[1]; del sys.argv[1]
- if option == '-h': print __HELP__; sys.exit()
- if option == '-o': fileo = sys.argv[1]; del sys.argv[1]
- if option == '-c': filec = sys.argv[1]; del sys.argv[1]
- if option == '-v': vmode = 'verbose'
- if option == '-d': dmode = 'debug'
- if option == '-D': delay = float(sys.argv[1]); del sys.argv[1]
- if option == '-tol': tol = float(sys.argv[1]); del sys.argv[1]
- if option == '-l': mode = 'localisation'
-
-# arguments required
-if (not fileo) or (not filec):
- print 'wrong set of arguments. use \'-h\' for help'
- sys.exit('error: needs at least \'-c targets.txt -o detected.txt\'')
-
-# load files
-ltru, lres = read_datafile(fileo,depth=0),read_datafile(filec,depth=0)
-
-# delay onsets as required with -D
-if delay:
- for i in range(len(lres)):
- lres[i] = lres[i] + delay
-# compute errors types
-if mode == 'localisation':
- l = onset_diffs(ltru,lres,tol)
- for i in l: print "%.3f" % i
-else:
- orig, missed, merged, expc, bad, doubled = onset_roc(ltru,lres,tol)
-
- # print results
- #print "orig, missed, merged, expc, bad, doubled:"
- if vmode=='verbose':
- print "orig", orig
- print "expc", expc
- print "missed",missed
- print "merged", merged
- print "bad", bad
- print "doubled", doubled
- print "correct", orig-missed-merged
- print "GD %2.8f\t" % (100*float(orig-missed-merged)/(orig)),
- print "FP %2.8f\t" % (100*float(bad+doubled)/(orig)) ,
- print "GD-merged %2.8f\t" % (100*float(orig-missed)/(orig)) ,
- print "FP-pruned %2.8f\t" % (100*float(bad)/(orig))
- else:
- print orig, missed, merged, expc, bad, doubled
--- a/python/aubiocut
+++ /dev/null
@@ -1,156 +1,0 @@
-#! /usr/bin/python
-
-""" this file was written by Paul Brossier
- it is released under the GNU/GPL license.
-"""
-
-import sys
-from aubio.task import *
-
-usage = "usage: %s [options] -i soundfile" % sys.argv[0]
-
-def parse_args():
- from optparse import OptionParser
- parser = OptionParser(usage=usage)
- parser.add_option("-i","--input",
- action="store", dest="filename",
- help="input sound file")
- parser.add_option("-m","--mode",
- action="store", dest="mode", default='dual',
- help="onset detection mode [default=dual] \
- complexdomain|hfc|phase|specdiff|energy|kl|mkl|dual")
- parser.add_option("-B","--bufsize",
- action="store", dest="bufsize", default=512,
- help="buffer size [default=512]")
- parser.add_option("-H","--hopsize",
- action="store", dest="hopsize", default=256,
- help="overlap size [default=256]")
- parser.add_option("-t","--threshold",
- action="store", dest="threshold", default=0.3,
- help="onset peak picking threshold [default=0.3]")
- parser.add_option("-C","--dcthreshold",
- action="store", dest="dcthreshold", default=1.,
- help="onset peak picking DC component [default=1.]")
- parser.add_option("-s","--silence",
- action="store", dest="silence", default=-70,
- help="silence threshold [default=-70]")
- parser.add_option("-M","--mintol",
- action="store", dest="mintol", default=0.048,
- help="minimum inter onset interval [default=0.048]")
- parser.add_option("-D","--delay",
- action="store", dest="delay",
- help="number of seconds to take back [default=system]\
- default system delay is 3*hopsize/samplerate")
- parser.add_option("-L","--localmin",
- action="store_true", dest="localmin", default=False,
- help="use local minima after peak detection")
- parser.add_option("-c","--cut",
- action="store_true", dest="cut", default=False,
- help="cut input sound file at detected labels \
- best used with option -L")
- parser.add_option("-d","--derivate",
- action="store_true", dest="derivate", default=False,
- help="derivate onset detection function")
- parser.add_option("-S","--silencecut",
- action="store_true", dest="silencecut", default=False,
- help="outputs silence locations")
- parser.add_option("-z","--zerocross",
- action="store", dest="zerothres", default=0.008,
- help="zero-crossing threshold for slicing [default=0.00008]")
- # plotting functions
- parser.add_option("-p","--plot",
- action="store_true", dest="plot", default=False,
- help="draw plot")
- parser.add_option("-x","--xsize",
- action="store", dest="xsize", default=1.,
- type='float', help="define xsize for plot")
- parser.add_option("-y","--ysize",
- action="store", dest="ysize", default=1.,
- type='float', help="define ysize for plot")
- parser.add_option("-f","--function",
- action="store_true", dest="func", default=False,
- help="print detection function")
- parser.add_option("-n","--no-onsets",
- action="store_true", dest="nplot", default=False,
- help="do not plot detected onsets")
- parser.add_option("-O","--outplot",
- action="store", dest="outplot", default=None,
- help="save plot to output.{ps,png}")
- parser.add_option("-F","--spectrogram",
- action="store_true", dest="spectro", default=False,
- help="add spectrogram to the plot")
- parser.add_option("-v","--verbose",
- action="store_true", dest="verbose", default=True,
- help="make lots of noise [default]")
- parser.add_option("-q","--quiet",
- action="store_false", dest="verbose", default=True,
- help="be quiet")
- # to be implemented
- parser.add_option("-b","--beat",
- action="store_true", dest="beat", default=False,
- help="output beat locations")
- (options, args) = parser.parse_args()
- if not options.filename:
- print "no file name given\n", usage
- sys.exit(1)
- return options, args
-
-options, args = parse_args()
-
-filename = options.filename
-params = taskparams()
-params.hopsize = int(options.hopsize)
-params.bufsize = int(options.bufsize)
-params.threshold = float(options.threshold)
-params.dcthreshold = float(options.dcthreshold)
-params.zerothres = float(options.zerothres)
-params.silence = float(options.silence)
-params.mintol = float(options.mintol)
-params.verbose = options.verbose
-# default take back system delay
-if options.delay: params.delay = int(float(options.delay)/params.step)
-
-dotask = taskonset
-if options.beat:
- dotask = taskbeat
-elif options.silencecut:
- dotask = tasksilence
-elif options.plot or options.func:
- params.storefunc=True
-else:
- params.storefunc=False
-
-lonsets, lofunc = [], []
-wplot,oplots = [],[]
-modes = options.mode.split(',')
-for i in range(len(modes)):
- params.onsetmode = modes[i]
- filetask = dotask(filename,params=params)
- onsets = filetask.compute_all()
-
- #lonsets.append(onsets)
- if not options.silencecut:
- ofunc = filetask.ofunc
- lofunc.append(ofunc)
-
- if options.plot:
- if options.beat:
- filetask.plot(oplots, onsets)
- else:
- filetask.plot(onsets, ofunc, wplot, oplots, nplot=options.nplot)
-
- if options.func:
- for i in ofunc:
- print i
-
-if options.outplot:
- extension = options.outplot.split('.')[-1]
- outplot = '.'.join(options.outplot.split('.')[:-1])
-else:
- extension,outplot = None,None
-if options.plot: filetask.plotplot(wplot, oplots, outplot=outplot, extension=extension,
- xsize=options.xsize,ysize=options.ysize,spectro=options.spectro)
-
-if options.cut:
- a = taskcut(filename,onsets,params=params)
- a.compute_all()
--- a/python/aubiodiffs-onset
+++ /dev/null
@@ -1,86 +1,0 @@
-#! /usr/bin/python
-
-__LICENSE__ = """\
- Copyright (C) 2004-2009 Paul Brossier <piem@aubio.org>
-
- This file is part of aubio.
-
- aubio is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- aubio is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with aubio. If not, see <http://www.gnu.org/licenses/>.
-"""
-
-__HELP__ = """\
-# required arguments
- -c targetfilename
- -o detectfilename
-(both must be text files with 1 time a line expressed in seconds)
-
-# optional arguments
- -D <delay> delay in seconds
- -v verbose mode
- -d debug mode
-
-# output
-results:number of correct detections
- number of incorrect detections
- number of doubled detections
- number of total detections
- number of total targets
-
-# example:
-$ aubioonset-comp -c checked-onsets.txt -o handlab-onsets.txt -v
-( gd fp dd ) tot / real
-( 5 4 0 ) 9 / 9
-55.5555555556 %GD 44.4444444444 %FP 0.0 %OD
-
-# bugs
-does not scale to very long lists
-"""
-
-import sys
-from aubio.onsetcompare import onset_diffs
-from aubio.txtfile import read_datafile
-
-# default values
-fileo=None;filec=None;vmode=None;dmode=None;delay=0.
-# default tolerance is 50 ms
-#tol = 0.050
-tol = 0.048
-
-while len(sys.argv) >=2:
- option = sys.argv[1]; del sys.argv[1]
- if option == '-h': print __HELP__; sys.exit()
- if option == '-o': fileo = sys.argv[1]; del sys.argv[1]
- if option == '-c': filec = sys.argv[1]; del sys.argv[1]
- if option == '-v': vmode = 'verbose'
- if option == '-d': dmode = 'debug'
- if option == '-D': delay = float(sys.argv[1]); del sys.argv[1]
- if option == '-tol': tol = float(sys.argv[1]); del sys.argv[1]
-
-# arguments required
-if (not fileo) or (not filec):
- print 'wrong set of arguments. use \'-h\' for help'
- sys.exit('error: needs at least \'-c targets.txt -o detected.txt\'')
-
-# load files
-ltru, lres = read_datafile(fileo,depth=0),read_datafile(filec,depth=0)
-
-# delay onsets as required with -D
-if delay:
- for i in range(len(lres)):
- lres[i] = lres[i] + delay
-# compute errors types
-l = onset_diffs(ltru,lres,tol)
-# print with 1ms precision
-for i in l: print "%.3f" % float(i)
-
--- a/python/aubiofilter-notes
+++ /dev/null
@@ -1,94 +1,0 @@
-#!/usr/bin/python
-
-""" this file is used to get filter the (old) output format of aubionotes """
-
-# default parameters
-__eps = [0.250,0.50] # minimum length, pitch tolerance (ms,midipitch)
-__plot = 0 # -P (command line switch)
-__delay = 0.0 # -D <value> (fixed delay for score alignement)
-__winlength = 10 # -w <value> (window length for pitch estimation in frames)
-
-import getopt
-import sys
-
-def parse_args (sysargs):
- from getopt import gnu_getopt
- shortopts ='i:o:t:p:w:D:P:'
- longopts =('input=','output=','tolpitch=','toltime=','winlength=','delay','plot=')
- args,tmp = gnu_getopt(sysargs,shortopts,longopts)
- assert len(args) > 1
- plot = __plot
- delay = __delay
- eps = __eps
- winlength = __winlength
- plot = __plot
- fileout = '/tmp/testprint.ps'
- args.sort()
- for i in range(len(args)): # a bad way
- if args[i][0] == '-i' or args[i][0] == '--input':
- fileorg = args[i][1]
- if args[i][0] == '-o' or args[i][0] == '--output':
- fileerr = args[i][1]
- if args[i][0] == '-t' or args[i][0] == '--toltime':
- eps[0] = float(args[i][1])
- if args[i][0] == '-p' or args[i][0] == '--tolpitch':
- eps[1] = float(args[i][1])
- if args[i][0] == '-D' or args[i][0] == '--delay':
- delay = float(args[i][1])
- if args[i][0] == '-w' or args[i][0] == '--winlength':
- winlength = int(args[i][1])
- if args[i][0] == '-P' or args[i][0] == '--plot':
- plot = 1
- fileout = args[i][1]
- return fileorg,fileerr,eps,winlength,plot,delay,fileout
-
-def usage():
- print __file__, "with at least some arguments"
-
-def main():
- try:
- opts,args = getopt.getopt(sys.argv[1:],
- "hvo:i:p:P",
- ["help", "output=", "verbose", "input=", "plot="])
- except getopt.GetoptError:
- usage()
- sys.exit(2)
-
- input = None
- output = None
- verbose = False
- winlength = __winlength
- plot = __plot
- eps = __eps
-
- for o, a in opts:
- if o in ("-v", "--verbose"):
- verbose = True
- if o in ("-h", "--help"):
- usage()
- sys.exit(2)
- if o in ("--output"):
- output = a
- if o in ("-i", "--input"):
- input = a
- if o in ("-P", "--plot"):
- plot = 1
-
- assert input != None and input != "", "no input file"
-
- from aubio import notefilter,txtfile,gnuplot
- """ load midi and raw data """
- from numpy import array
- notelist = array(txtfile.read_datafile(input))
- """ filter it out """
- notelist_filtered = notefilter.segraw_onsets4(notelist,winlength,eps)
- if verbose == 1 :
- for a,b in notelist_filtered:
- print a,b
- """ plot results """
- if plot == 1 :
- gnuplot.plotnote(notelist_filtered,title=input,fileout=output)
-
-if __name__ == "__main__":
- main()
-
--- /dev/null
+++ b/python/aubioinput.py
@@ -1,0 +1,141 @@
+#! /usr/bin/python
+
+import pygst
+pygst.require('0.10')
+import gst
+import gobject
+gobject.threads_init ()
+
+def gst_buffer_to_numpy_array(buffer, chan):
+ import numpy
+ samples = numpy.frombuffer(buffer.data, dtype=numpy.float32)
+ if chan == 1:
+ return samples.T
+ else:
+ samples.resize([len(samples)/chan, chan])
+ return samples.T
+
+class AubioSink(gst.BaseSink):
+ _caps = gst.caps_from_string('audio/x-raw-float, \
+ rate=[ 1, 2147483647 ], \
+ channels=[ 1, 2147483647 ], \
+ endianness={ 1234, 4321 }, \
+ width=32')
+
+ __gsttemplates__ = (
+ gst.PadTemplate ("sink",
+ gst.PAD_SINK,
+ gst.PAD_ALWAYS,
+ _caps),
+ )
+
+ def __init__(self, name, process):
+ self.__gobject_init__()
+ self.set_name(name)
+ self.process = process
+ self.adapter = gst.Adapter()
+ self.set_property('sync', False)
+ self.pos = 0
+
+ def set_property(self, name, value):
+ if name == 'hopsize':
+ # blocksize is in byte, convert from hopsize
+ from struct import calcsize
+ self.set_property('blocksize', value * calcsize('f'))
+ else:
+ super(gst.BaseSink, self).set_property(name, value)
+
+ def do_render(self, buffer):
+ blocksize = self.get_property('blocksize')
+ caps = buffer.get_caps()
+ chan = caps[0]['channels']
+ self.adapter.push(buffer)
+ while self.adapter.available() >= blocksize:
+ block = self.adapter.take_buffer(blocksize)
+ v = gst_buffer_to_numpy_array(block, chan)
+ if self.process:
+ self.process(v, self.pos)
+ self.pos += 1
+ remaining = self.adapter.available()
+ if remaining < blocksize and remaining > 0:
+ block = self.adapter.take_buffer(remaining)
+ v = gst_buffer_to_numpy_array(block, chan)
+ if self.process:
+ self.process(v, self.pos)
+ self.pos += 1
+ return gst.FLOW_OK
+
+gobject.type_register(AubioSink)
+
+class aubioinput(gst.Bin):
+
+ ret = 0
+
+ def __init__(self, uri, process = None, hopsize = 512,
+ caps = None):
+ if uri.startswith('/'):
+ from urllib import quote
+ uri = 'file://'+quote(uri)
+ src = gst.element_factory_make('uridecodebin')
+ src.set_property('uri', uri)
+ src.connect('pad-added', self.source_pad_added_cb)
+ conv = gst.element_factory_make('audioconvert')
+ self.conv = conv
+ rsmpl = gst.element_factory_make('audioresample')
+ capsfilter = gst.element_factory_make('capsfilter')
+ if caps:
+ capsfilter.set_property('caps', gst.caps_from_string(caps))
+ sink = AubioSink("AubioSink", process = process)
+ sink.set_property('hopsize', hopsize) # * calcsize('f'))
+
+ self.pipeline = gst.Pipeline()
+
+ self.bus = self.pipeline.get_bus()
+ self.bus.add_signal_watch()
+ self.bus.connect('message', self.on_eos)
+
+ self.apad = conv.get_pad('sink')
+
+ self.pipeline.add(src, conv, rsmpl, capsfilter, sink)
+
+ gst.element_link_many(conv, rsmpl, capsfilter, sink)
+
+ self.mainloop = gobject.MainLoop()
+ self.pipeline.set_state(gst.STATE_PLAYING)
+
+ def run(self):
+ self.mainloop.run()
+ return self.ret
+
+ def source_pad_added_cb(self, src, pad):
+ name = pad.get_caps()[0].get_name()
+ if name == 'audio/x-raw-float' or name == 'audio/x-raw-int':
+ pad.link(self.conv.get_pad("sink"))
+
+ def source_pad_removed_cb(self, src, pad):
+ pad.unlink(self.conv.get_pad("sink"))
+
+ def on_eos(self, bus, msg):
+ if msg.type == gst.MESSAGE_EOS:
+ self.bus.remove_signal_watch()
+ self.pipeline.set_state(gst.STATE_PAUSED)
+ self.mainloop.quit()
+ elif msg.type == gst.MESSAGE_ERROR:
+ print "ERROR", msg.parse_error()
+ self.bus.remove_signal_watch()
+ self.pipeline.set_state(gst.STATE_PAUSED)
+ self.mainloop.quit()
+ self.ret = 1 # set return value to 1 in case of error
+
+if __name__ == '__main__':
+ import sys
+ if len(sys.argv) < 2:
+ print "Usage: %s <filename>" % sys.argv[0]
+ sys.exit(1)
+ for filename in sys.argv[1:]:
+ peak = [0.] # use a mutable
+ def process(buf, hop):
+ peak[0] = max( peak[0], abs(buf.max()) )
+ a = aubioinput(filename, process = process, hopsize = 512)
+ if a.run() == 0: # only display the results if no
+ print "Finished reading %s, peak value is %f" % (filename, max(peak))
--- /dev/null
+++ b/python/aubiomodule.c
@@ -1,0 +1,161 @@
+#include <Python.h>
+#define PY_ARRAY_UNIQUE_SYMBOL PyArray_API
+#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
+#include <numpy/arrayobject.h>
+
+#include "aubio-types.h"
+#include "generated/aubio-generated.h"
+
+static char Py_alpha_norm_doc[] = "compute alpha normalisation factor";
+
+static PyObject *
+Py_alpha_norm (PyObject * self, PyObject * args)
+{
+ PyObject *input;
+ fvec_t *vec;
+ smpl_t alpha;
+ PyObject *result;
+
+ if (!PyArg_ParseTuple (args, "Of:alpha_norm", &input, &alpha)) {
+ return NULL;
+ }
+
+ if (input == NULL) {
+ return NULL;
+ }
+
+ vec = PyAubio_ArrayToCFvec (input);
+
+ if (vec == NULL) {
+ return NULL;
+ }
+
+ // compute the function
+ result = Py_BuildValue ("f", fvec_alpha_norm (vec, alpha));
+ if (result == NULL) {
+ return NULL;
+ }
+
+ return result;
+}
+
+static char Py_zero_crossing_rate_doc[] = "compute zero crossing rate";
+
+static PyObject *
+Py_zero_crossing_rate (PyObject * self, PyObject * args)
+{
+ PyObject *input;
+ fvec_t *vec;
+ PyObject *result;
+
+ if (!PyArg_ParseTuple (args, "O:zero_crossing_rate", &input)) {
+ return NULL;
+ }
+
+ if (input == NULL) {
+ return NULL;
+ }
+
+ vec = PyAubio_ArrayToCFvec (input);
+
+ if (vec == NULL) {
+ return NULL;
+ }
+
+ // compute the function
+ result = Py_BuildValue ("f", aubio_zero_crossing_rate (vec));
+ if (result == NULL) {
+ return NULL;
+ }
+
+ return result;
+}
+
+static char Py_min_removal_doc[] = "compute zero crossing rate";
+
+static PyObject *
+Py_min_removal(PyObject * self, PyObject * args)
+{
+ PyObject *input;
+ fvec_t *vec;
+
+ if (!PyArg_ParseTuple (args, "O:min_removal", &input)) {
+ return NULL;
+ }
+
+ if (input == NULL) {
+ return NULL;
+ }
+
+ vec = PyAubio_ArrayToCFvec (input);
+
+ if (vec == NULL) {
+ return NULL;
+ }
+
+ // compute the function
+ fvec_min_removal (vec);
+
+ // since this function does not return, we could return None
+ //return Py_None;
+ // however it is convenient to return the modified vector
+ return (PyObject *) PyAubio_CFvecToArray(vec);
+ // or even without converting it back to an array
+ //Py_INCREF(vec);
+ //return (PyObject *)vec;
+}
+
+static PyMethodDef aubio_methods[] = {
+ {"alpha_norm", Py_alpha_norm, METH_VARARGS, Py_alpha_norm_doc},
+ {"zero_crossing_rate", Py_zero_crossing_rate, METH_VARARGS,
+ Py_zero_crossing_rate_doc},
+ {"min_removal", Py_min_removal, METH_VARARGS, Py_min_removal_doc},
+ {NULL, NULL} /* Sentinel */
+};
+
+static char aubio_module_doc[] = "Python module for the aubio library";
+
+PyMODINIT_FUNC
+init_aubio (void)
+{
+ PyObject *m;
+ int err;
+
+ if ( (PyType_Ready (&Py_cvecType) < 0)
+ || (PyType_Ready (&Py_filterType) < 0)
+ || (PyType_Ready (&Py_filterbankType) < 0)
+ || (PyType_Ready (&Py_fftType) < 0)
+ || (PyType_Ready (&Py_pvocType) < 0)
+ // generated objects
+ || (generated_types_ready() < 0 )
+ ) {
+ return;
+ }
+
+ m = Py_InitModule3 ("_aubio", aubio_methods, aubio_module_doc);
+
+ if (m == NULL) {
+ return;
+ }
+
+ err = _import_array ();
+
+ if (err != 0) {
+ fprintf (stderr,
+ "Unable to import Numpy C API from aubio module (error %d)\n", err);
+ }
+
+ Py_INCREF (&Py_cvecType);
+ PyModule_AddObject (m, "cvec", (PyObject *) & Py_cvecType);
+ Py_INCREF (&Py_filterType);
+ PyModule_AddObject (m, "digital_filter", (PyObject *) & Py_filterType);
+ Py_INCREF (&Py_filterbankType);
+ PyModule_AddObject (m, "filterbank", (PyObject *) & Py_filterbankType);
+ Py_INCREF (&Py_fftType);
+ PyModule_AddObject (m, "fft", (PyObject *) & Py_fftType);
+ Py_INCREF (&Py_pvocType);
+ PyModule_AddObject (m, "pvoc", (PyObject *) & Py_pvocType);
+
+ // generated objects
+ add_generated_objects(m);
+}
--- a/python/aubionotes
+++ /dev/null
@@ -1,79 +1,0 @@
-#!/usr/bin/python
-
-def do(filein,threshold):
-
- import aubio.aubioclass
- import aubio.median
- from math import floor
- hopsize = 512
- bufsize = 4096
- channels = 1
- frameread = 0
- silthres = -80.
- filei = aubio.aubioclass.sndfile(filein)
- srate = filei.samplerate()
- myvec = aubio.aubioclass.fvec(hopsize,channels)
- readsize = filei.read(hopsize,myvec)
- ppick = aubio.aubioclass.pitchpick(bufsize,hopsize,channels,myvec,srate)
- opick = aubio.aubioclass.onsetpick(bufsize,hopsize,channels,myvec,threshold)
- mylist = list()
-
- wassilence = 0
- lastpitch = 0
- starttime = 0
- while(readsize==hopsize):
- readsize = filei.read(hopsize,myvec)
- val = ppick.do(myvec)
- midival = aubio.aubioclass.bintomidi(val,srate,bufsize)
- isonset,onset = opick.do(myvec)
- now = (frameread)*hopsize/(srate+0.)
- issilence = aubio.aubioclass.aubio_silence_detection(myvec.vec,silthres)
-
- estmidival = 0
- if (issilence == 1):
- if (wassilence == 0):
- #outputnow
- endtime = (frameread-3)*hopsize/(srate+0.)
- if len(mylist) > 5 :
- estmidival = aubio.median.percental(mylist,len(mylist)/2)
- print "sil", starttime, endtime, estmidival
- #resetnow
- mylist = list()
- else:
- wassilence = 1
- else:
- if isonset == 1:
- if (wassilence == 0):
- #outputnow
- endtime = (frameread-3)*hopsize/(srate+0.)
- #estmidival = aubio.median.percental(around(array(mylist)),len(mylist)//2)
- if len(mylist) > 5 :
- estmidival = aubio.median.percental(mylist,len(mylist)/2)
- print starttime, endtime, estmidival
- #resetnow
- mylist = list()
- #store start time
- starttime = (frameread-3)*hopsize/(srate+0.)
- else:
- """
- if(listfull):
- #outputnow
- endtime = (frameread-3)*hopsize/(srate+0.)
- print starttime, endtime, estimmidival
- else:
- """
- #bufferize
- if midival > 50 and midival < 75:
- mylist.append(floor(midival))
- wassilence = 0
-
-
- #elif( midival > 45 ):
- # mylist.append(( now , midival+12 ))
- #mylist.append(toappend)
- frameread += 1
-
-
-if __name__ == "__main__":
- import sys
- do(sys.argv[1],sys.argv[2])
--- a/python/aubiopitch
+++ /dev/null
@@ -1,131 +1,0 @@
-#!/usr/bin/python
-
-""" this file was written by Paul Brossier
- it is released under the GNU/GPL license.
-"""
-
-import sys
-from aubio.task import *
-
-usage = "usage: %s [options] -i soundfile" % sys.argv[0]
-
-
-def parse_args():
- from optparse import OptionParser
- parser = OptionParser(usage=usage)
- parser.add_option("-i","--input",
- action="store", dest="filename",
- help="input sound file")
- parser.add_option("-m","--mode",
- action="store", dest="mode", default='yinfft',
- help="pitch detection mode [default=mcomb] \
- mcomb|yin|fcomb|schmitt")
- parser.add_option("-u","--units",
- action="store", dest="omode", default="freq",
- help="output pitch in units [default=Hz] \
- freq|midi|cent|bin")
- parser.add_option("-B","--bufsize",
- action="store", dest="bufsize", default=None,
- help="buffer size [default=2048]")
- parser.add_option("-H","--hopsize",
- action="store", dest="hopsize", default=None,
- help="overlap size [default=512]")
- parser.add_option("-t","--threshold",
- action="store", dest="threshold", default=0.1,
- help="pitch threshold (for yin) [default=0.1]")
- parser.add_option("-s","--silence",
- action="store", dest="silence", default=-70,
- help="silence threshold [default=-70]")
- parser.add_option("-D","--delay",
- action="store", dest="delay",
- help="number of seconds frames to take back [default=0]")
- parser.add_option("-S","--smoothing",
- action="store", dest="smoothing", default=False,
- help="use a median filter of N frames [default=0]")
- parser.add_option("-M","--maximum",
- action="store", dest="pitchmax", default=False,
- help="maximum pitch value to look for (Hz) [default=20000]")
- parser.add_option("-l","--minimum",
- action="store", dest="pitchmin", default=False,
- help="minimum pitch value to look for (Hz) [default=20]")
- # to be implemented
- parser.add_option("-n","--note",
- action="store_true", dest="note", default=False,
- help="NOT IMPLEMENTED output notes")
- # plotting functions
- parser.add_option("-T","--plottruth",
- action="store_true", dest="plottruth", default=False,
- help="draw plot of the ground truth pitch track")
- parser.add_option("-p","--plot",
- action="store_true", dest="plot", default=False,
- help="draw plot of the pitch track")
- parser.add_option("-x","--xsize",
- action="store", dest="xsize", default=1.,
- type='float', help="define xsize for plot")
- parser.add_option("-y","--ysize",
- action="store", dest="ysize", default=1.,
- type='float', help="define ysize for plot")
- parser.add_option("-O","--outplot",
- action="store", dest="outplot", default=None,
- help="save the plot to output.{ps,png,svg} instead of displaying it")
- parser.add_option("-v","--verbose",
- action="store_true", dest="verbose", default=True,
- help="make lots of noise")
- parser.add_option("-q","--quiet",
- action="store_false", dest="verbose", default=True,
- help="be quiet")
- (options, args) = parser.parse_args()
- if not options.bufsize:
- if options.mode == "yin": options.bufsize = 1024
- if options.mode == "schmitt": options.bufsize = 2048
- if options.mode == "mcomb": options.bufsize = 4096
- if options.mode == "fcomb": options.bufsize = 4096
- else: options.bufsize = 2048
- if not options.hopsize:
- options.hopsize = float(options.bufsize) / 2
- if not options.filename:
- print "no file name given\n", usage
- sys.exit(1)
- return options, args
-
-options, args = parse_args()
-
-#print options.bufsize, options.hopsize
-
-filename = options.filename
-params = taskparams()
-params.samplerate = float(sndfile(filename).samplerate())
-params.hopsize = int(options.hopsize)
-params.bufsize = int(options.bufsize)
-params.step = params.samplerate/float(params.hopsize)
-params.yinthresh = float(options.threshold)
-params.silence = float(options.silence)
-params.verbose = options.verbose
-if options.smoothing: params.pitchsmooth = int(options.smoothing)
-if options.pitchmax: params.pitchmax = int(options.pitchmax)
-if options.pitchmin: params.pitchmin = int(options.pitchmin)
-#mintol = float(options.mintol)*step
-# default take back system delay
-if options.delay: params.pitchdelay = float(options.delay)
-
-if options.note:
- exit("not implemented yet")
-
-wplot,oplots,titles = [],[],[]
-modes = options.mode.split(',')
-for i in range(len(modes)):
- pitch = []
- params.pitchmode = modes[i]
- filetask = taskpitch(filename,params=params)
- pitch = filetask.compute_all()
- #print filetask.eval(pitch[i])
- if options.plot: filetask.plot(pitch,wplot,oplots,titles)
-
-if options.outplot:
- extension = options.outplot.split('.')[-1]
- outplot = '.'.join(options.outplot.split('.')[:-1])
-else:
- extension,outplot = None,None
-if options.plot:
- filetask.plotplot(wplot,oplots,titles,outplot=outplot,extension=extension,
- xsize=options.xsize,ysize=options.ysize,truth=options.plottruth)
--- a/python/aubioplot-audio
+++ /dev/null
@@ -1,31 +1,0 @@
-#!/usr/bin/python
-
-import sys
-from aubio.gnuplot import gnuplot_create,gnuplot_addargs,plot_audio
-
-usage = "usage: %s [options] -i soundfile" % sys.argv[0]
-
-def parse_args():
- from optparse import OptionParser
- parser = OptionParser(usage=usage)
- parser.add_option("-i","--input",
- action="store", dest="filename",
- help="input sound file")
- gnuplot_addargs(parser)
- (options, args) = parser.parse_args()
- if not options.filename:
- print "no file name given\n", usage
- sys.exit(1)
- return options, args
-
-options, args = parse_args()
-
-if options.outplot:
- extension = options.outplot.split('.')[-1]
- outplot = '.'.join(options.outplot.split('.')[:-1])
-else:
- extension = ''
- outplot = None
-
-g = gnuplot_create(outplot,extension,options)
-plot_audio(options.filename.split(','), g, options)
--- a/python/aubioplot-notes
+++ /dev/null
@@ -1,31 +1,0 @@
-#!/usr/bin/python
-
-def parse_args (sysargs):
- from getopt import gnu_getopt
- shortopts ='i:o:'
- longopts =('input=','output=')
- args,tmp = gnu_getopt(sysargs,shortopts,longopts)
- args.sort()
- filein,fileout= None,None
- for i in range(len(args)): # a bad way
- if args[i][0] == '-i' or args[i][0] == '--input':
- filein = args[i][1]
- if args[i][0] == '-o' or args[i][0] == '--output':
- fileout = args[i][1]
- assert filein != None, 'precise filein'
- return filein,fileout
-
-def main (sysargs) :
- from aubio.txtfile import read_datafile
- from aubio.gnuplot import plotnote,plotnote_do
- from numpy import array
- filein,fileout = parse_args(sysargs)
- #print 'checking', fileerr, 'against', fileorg
- """ load midi and raw data """
- d = plotnote(array(read_datafile(filein)),title=filein)
- plotnote_do(d,fileout=fileout)
-
-if __name__ == "__main__":
- import sys
- main(sys.argv[1:])
-
--- a/python/aubioplot-spec
+++ /dev/null
@@ -1,51 +1,0 @@
-#! /usr/bin/python
-
-""" this file was written by Paul Brossier
- it is released under the GNU/GPL license.
-"""
-
-import sys
-from aubio.gnuplot import gnuplot_create,gnuplot_addargs,plot_spec
-
-usage = "usage: %s [options] -i soundfile" % sys.argv[0]
-
-def parse_args():
- from optparse import OptionParser
- parser = OptionParser(usage=usage)
- parser.add_option("-i","--input",
- action="store", dest="filename",
- help="input sound file")
- parser.add_option("-M","--maxf",
- action="store", dest="maxf", default=10000.,
- type='float',help="higher frequency limit")
- parser.add_option("-L","--minf",
- action="store", dest="minf", default=0.,
- type='float',help="lower frequency limit")
- parser.add_option("-l","--log",
- action="store_true", dest="log", default=False,
- help="plot on a logarithmic scale")
- parser.add_option("-B","--bufsize", type='int',
- action="store", dest="bufsize", default=8192,
- help="buffer size [default=8192]")
- parser.add_option("-H","--hopsize", type='int',
- action="store", dest="hopsize", default=1024,
- help="overlap size [default=1024]")
- gnuplot_addargs(parser)
- (options, args) = parser.parse_args()
- if not options.filename:
- print "no file name given\n", usage
- sys.exit(1)
- return options, args
-
-options, args = parse_args()
-filename = options.filename
-
-if options.outplot:
- extension = options.outplot.split('.')[-1]
- outplot = '.'.join(options.outplot.split('.')[:-1])
-else:
- extension = ''
- outplot = None
-
-g = gnuplot_create(outplot,extension,options)
-plot_spec(filename, g, options)
--- a/python/aubioplot-yinfft
+++ /dev/null
@@ -1,135 +1,0 @@
-#! /usr/bin/python
-
-""" this file was written by Paul Brossier
- it is released under the GNU/GPL license.
-"""
-
-import sys,time
-from aubio.task import task,taskparams
-from aubio.aubioclass import fvec
-from aubio.gnuplot import gnuplot_create
-from aubio.aubiowrapper import *
-
-usage = "usage: %s [options] -i soundfile" % sys.argv[0]
-
-def parse_args():
- from optparse import OptionParser
- parser = OptionParser(usage=usage)
- parser.add_option("-i","--input",
- action="store", dest="filename",
- help="input sound file")
- parser.add_option("-n","--printframe",
- action="store", dest="printframe", default=-1,
- help="make a plot of the n_th frame")
- parser.add_option("-x","--xsize",
- action="store", dest="xsize", default=1.,
- help="define xsize for plot")
- parser.add_option("-y","--ysize",
- action="store", dest="ysize", default=1.,
- help="define ysize for plot")
- parser.add_option("-O","--outplot",
- action="store", dest="outplot", default=None,
- help="save plot to output.{ps,png}")
- (options, args) = parser.parse_args()
- if not options.filename:
- print "no file name given\n", usage
- sys.exit(1)
- return options, args
-
-def plotdata(x,y,plottitle="",**keyw):
- import Gnuplot
- return Gnuplot.Data(x, y, title="%s" % plottitle,**keyw)
-
-options, args = parse_args()
-filename = options.filename
-xsize = float(options.xsize)
-ysize = float(options.ysize)*2
-
-printframe = int(options.printframe)
-if printframe == -1:
- print "Will wait for ^D to skip to next plot"
- print "Press enter before to print to file"
-
-
-g = gnuplot_create()
-params = taskparams()
-params.hopsize = 2048 # 512
-params.bufsize = params.hopsize #2048
-taskfile = task(filename,params=params)
-
-yin = fvec(params.bufsize/2,1)
-
-t = [i for i in range(params.bufsize)]
-a = [0 for i in range(params.bufsize)]
-
-while (taskfile.readsize == params.hopsize):
- taskfile()
-
- n = [i for i in range(params.bufsize/2)]
- a = [taskfile.myvec.get(i,0) for i in range(params.hopsize/2)]
- aubio_pitchyin_diff(taskfile.myvec(),yin()) # compute d[t]
- c = [yin.get(i,0) for i in range(params.bufsize/2)]
- aubio_pitchyin_getcum(yin()) # compute d'[t]
- y = [yin.get(i,0) for i in range(params.bufsize/2)]
- thresh = [0.1 for i in range(params.bufsize/2)]
- #t.append((i/float(params.hopsize)+taskfile.frameread)*params.step),t.pop(0)
- d = [plotdata(n,a,plottitle="signal", with_='lines'),
- plotdata(n,c,plottitle="d[t]",axes='x1y2', with_='lines lt 1'),
- plotdata(n,y,plottitle="d'[t]",axes='x1y1', with_='lines lt 2'),
- plotdata(n,thresh,plottitle="threshold",axes='x1y1', with_='lines lt 3')]
- #g('set xrange [%f:%f]' % (t[0],t[-1]))
- #time.sleep(.2)
- g.reset()
- g('set yrange [-1:3]')
- g('set xrange [0:%d]' % (params.bufsize/2))
- g('set title \"%s\"' % "Example of period detection using YIN")
- if printframe == -1:
- g.replot(*d)
- a = sys.stdin.read()
- if a == "\n" or printframe == taskfile.frameread:
- from os.path import basename
- outplot = "_".join([basename(sys.argv[0]),'_'.join(basename(filename).split('.')),"%d" % taskfile.frameread])
- print outplot
- f = gnuplot_create(outplot=outplot,extension='ps')
- f('set size %f,%f;' % (xsize,ysize) )
- f('set lmargin %f' % (15*xsize))
- f('set rmargin %f' % (10*xsize))
- #f('set title \"%s\"' % "Example of period detection using YIN")
- f('set multiplot')
- f.ylabel('amplitude',offset=(+.5,0))
- f.xlabel('time (samples)')
- f('set size %f,%f;' % (xsize,ysize*0.4) )
- f('set orig %f,%f;' % (0,ysize*0.6) )
- sigmax = max(abs(min(a)),abs(max(a)))
- f('set yrange [%f:%f]' % (-1.3*sigmax,1.3*sigmax))
- f('set xrange [0:%d]' % (params.bufsize/2))
- f.plot(d[0])
-
- f.ylabel('')
- f.xlabel('lag (samples)')
- f('set bmargin %f' % (4*ysize))
- f('set size %f,%f;' % (xsize,ysize*0.6) )
- f('set orig %f,%f;' % (0,0) )
- f('set autoscale')
- f('set xrange [0:%d]' % (params.bufsize/2))
- f('set notitle')
- f('set y2tics')
- f('set ytics nomirror')
- f('set noytics')
- f('set key right')
- f.plot(d[1])
-
- f.ylabel('amplitude')
- f.xlabel('')
- f('set y2tics nomirror')
- f('set ytics nomirror')
- f('set noy2tics')
- f('set noxtics')
- f('set ytics')
- f('set key left')
- f.plot(d[2],d[3])
- #f('set yrange [-1:3]')
- #f.plot(*d)
- print "saved plot", outplot, 'ps'
- elif printframe < taskfile.frameread:
- break
--- /dev/null
+++ b/python/aubioproxy.c
@@ -1,0 +1,153 @@
+#include "aubio-types.h"
+
+fvec_t *
+PyAubio_ArrayToCFvec (PyObject *input) {
+ PyObject *array;
+ fvec_t *vec;
+ if (input == NULL) {
+ PyErr_SetString (PyExc_ValueError, "input array is not a python object");
+ goto fail;
+ }
+ // parsing input object into a Py_fvec
+ if (PyArray_Check(input)) {
+
+ // we got an array, convert it to an fvec
+ if (PyArray_NDIM ((PyArrayObject *)input) == 0) {
+ PyErr_SetString (PyExc_ValueError, "input array is a scalar");
+ goto fail;
+ } else if (PyArray_NDIM ((PyArrayObject *)input) > 1) {
+ PyErr_SetString (PyExc_ValueError,
+ "input array has more than one dimensions");
+ goto fail;
+ }
+
+ if (!PyArray_ISFLOAT ((PyArrayObject *)input)) {
+ PyErr_SetString (PyExc_ValueError, "input array should be float");
+ goto fail;
+ } else if (PyArray_TYPE ((PyArrayObject *)input) != AUBIO_NPY_SMPL) {
+ PyErr_SetString (PyExc_ValueError, "input array should be float32");
+ goto fail;
+ } else {
+ // input data type is float32, nothing else to do
+ array = input;
+ }
+
+ // vec = new_fvec (vec->length);
+ // no need to really allocate fvec, just its struct member
+ vec = (fvec_t *)malloc(sizeof(fvec_t));
+ vec->length = PyArray_SIZE ((PyArrayObject *)array);
+ vec->data = (smpl_t *) PyArray_GETPTR1 ((PyArrayObject *)array, 0);
+
+ } else if (PyObject_TypeCheck (input, &PyList_Type)) {
+ PyErr_SetString (PyExc_ValueError, "does not convert from list yet");
+ return NULL;
+ } else {
+ PyErr_SetString (PyExc_ValueError, "can only accept vector of float as input");
+ return NULL;
+ }
+
+ return vec;
+
+fail:
+ return NULL;
+}
+
+PyObject *
+PyAubio_CFvecToArray (fvec_t * self)
+{
+ npy_intp dims[] = { self->length, 1 };
+ return PyArray_SimpleNewFromData (1, dims, AUBIO_NPY_SMPL, self->data);
+}
+
+Py_cvec *
+PyAubio_CCvecToPyCvec (cvec_t * input) {
+ Py_cvec *vec = (Py_cvec*) PyObject_New (Py_cvec, &Py_cvecType);
+ vec->length = input->length;
+ vec->o = input;
+ Py_INCREF(vec);
+ return vec;
+}
+
+cvec_t *
+PyAubio_ArrayToCCvec (PyObject *input) {
+ if (PyObject_TypeCheck (input, &Py_cvecType)) {
+ return ((Py_cvec*)input)->o;
+ } else {
+ PyErr_SetString (PyExc_ValueError, "input array should be float32");
+ return NULL;
+ }
+}
+
+PyObject *
+PyAubio_CFmatToArray (fmat_t * input)
+{
+ PyObject *array = NULL;
+ uint_t i;
+ npy_intp dims[] = { input->length, 1 };
+ PyObject *concat = PyList_New (0), *tmp = NULL;
+ for (i = 0; i < input->height; i++) {
+ tmp = PyArray_SimpleNewFromData (1, dims, AUBIO_NPY_SMPL, input->data[i]);
+ PyList_Append (concat, tmp);
+ Py_DECREF (tmp);
+ }
+ array = PyArray_FromObject (concat, AUBIO_NPY_SMPL, 2, 2);
+ Py_DECREF (concat);
+ return array;
+}
+
+fmat_t *
+PyAubio_ArrayToCFmat (PyObject *input) {
+ PyObject *array;
+ fmat_t *mat;
+ uint_t i;
+ if (input == NULL) {
+ PyErr_SetString (PyExc_ValueError, "input array is not a python object");
+ goto fail;
+ }
+ // parsing input object into a Py_fvec
+ if (PyArray_Check(input)) {
+
+ // we got an array, convert it to an fvec
+ if (PyArray_NDIM ((PyArrayObject *)input) == 0) {
+ PyErr_SetString (PyExc_ValueError, "input array is a scalar");
+ goto fail;
+ } else if (PyArray_NDIM ((PyArrayObject *)input) > 2) {
+ PyErr_SetString (PyExc_ValueError,
+ "input array has more than two dimensions");
+ goto fail;
+ }
+
+ if (!PyArray_ISFLOAT ((PyArrayObject *)input)) {
+ PyErr_SetString (PyExc_ValueError, "input array should be float");
+ goto fail;
+ } else if (PyArray_TYPE ((PyArrayObject *)input) != AUBIO_NPY_SMPL) {
+ PyErr_SetString (PyExc_ValueError, "input array should be float32");
+ goto fail;
+ } else {
+ // input data type is float32, nothing else to do
+ array = input;
+ }
+
+ // no need to really allocate fvec, just its struct member
+ mat = (fmat_t *)malloc(sizeof(fmat_t));
+ mat->length = PyArray_DIM ((PyArrayObject *)array, 1);
+ mat->height = PyArray_DIM ((PyArrayObject *)array, 0);
+ mat->data = (smpl_t **)malloc(sizeof(smpl_t*) * mat->height);
+ for (i=0; i< mat->height; i++) {
+ mat->data[i] = (smpl_t*)PyArray_GETPTR1 ((PyArrayObject *)array, i);
+ }
+
+ } else if (PyObject_TypeCheck (input, &PyList_Type)) {
+ PyErr_SetString (PyExc_ValueError, "can not convert list to fmat");
+ return NULL;
+ } else {
+ PyErr_SetString (PyExc_ValueError, "can only accept matrix of float as input");
+ return NULL;
+ }
+
+ return mat;
+
+fail:
+ return NULL;
+}
+
--- a/python/aubioweb.py
+++ /dev/null
@@ -1,113 +1,0 @@
-#!/usr/bin/python
-
-doc = """
-This script works with mod_python to browse a collection of annotated wav files
-and results.
-
-you will need to have at least the following packages need to be installed (the
-name of the command line tool is precised in parenthesis):
-
-libapache-mod-python (apache2 prefered)
-sndfile-programs (sndfile-info)
-vorbis-tools (oggenc)
-python-gnuplot
-python-numpy
-
-Try the command line tools in aubio/python to test your installation.
-
-NOTE: this script is probably horribly insecure.
-
-example configuration for apache to put in your preferred virtual host.
-
-<Directory /home/piem/public_html/aubioweb>
- # Minimal config
- AddHandler mod_python .py
- # Disable these in production
- PythonDebug On
- PythonAutoReload on
- # Default handler in url
- PythonHandler aubioweb
- ## Authentication stuff (optional)
- #PythonAuthenHandler aubioweb
- #AuthType Basic
- #AuthName "Restricted Area"
- #require valid-user
- # make default listing
- DirectoryIndex aubioweb/
-</Directory>
-
-"""
-
-from aubio.web.html import *
-
-def handler(req):
- from aubio.web.browser import *
- from mod_python import Session
- req.sess = Session.Session(req)
- req.sess['login']='new aubio user'
- req.sess.save()
- return configure_handler(req,index)
-
-def index(req,threshold='0.3'):
- navigation(req)
- print_command(req,"sfinfo %%i")
- return footer(req)
-
-def show_info(req,verbose=''):
- navigation(req)
- print_command(req,"sndfile-info %%i")
- return footer(req)
-
-def feedback(req):
- navigation(req)
- req.write("""
- Please provide feedback below:
- <p>
- <form action="/~piem/aubioweb/email" method="POST">
- Name: <input type="text" name="name"><br>
- Email: <input type="text" name="email"><br>
- Comment: <textarea name="comment" rows=4 cols=20></textarea><br>
- <input type="submit">
- </form>
- """)
-
-WEBMASTER='piem@calabaza'
-SMTP_SERVER='localhost'
-
-def email(req,name,email,comment):
- import smtplib
- # make sure the user provided all the parameters
- if not (name and email and comment):
- return "A required parameter is missing, \
- please go back and correct the error"
- # create the message text
- msg = """\
-From: %s
-Subject: feedback
-To: %s
-
-I have the following comment:
-
-%s
-
-Thank You,
-
-%s
-
-""" % (email, WEBMASTER, comment, name)
- # send it out
- conn = smtplib.SMTP(SMTP_SERVER)
- try:
- conn.sendmail(email, [WEBMASTER], msg)
- except smtplib.SMTPSenderRefused:
- return """<html>please provide a valid email</html>"""
-
- conn.quit()
- # provide feedback to the user
- s = """\
-<html>
-Dear %s,<br>
-Thank You for your kind comments, we
-will get back to you shortly.
-</html>""" % name
- return s
--- /dev/null
+++ b/python/aubiowraphell.h
@@ -1,0 +1,90 @@
+#include "aubio-types.h"
+
+#define AUBIO_DECLARE(NAME, PARAMS...) \
+typedef struct { \
+ PyObject_HEAD \
+ aubio_ ## NAME ## _t * o; \
+ PARAMS; \
+} Py_## NAME;
+
+#define AUBIO_INIT(NAME, PARAMS... ) \
+static int \
+Py_ ## NAME ## _init (Py_ ## NAME * self, PyObject * args, PyObject * kwds) \
+{ \
+ self->o = new_aubio_## NAME ( PARAMS ); \
+ if (self->o == NULL) { \
+ PyErr_SetString (PyExc_StandardError, "error creating object"); \
+ return -1; \
+ } \
+\
+ return 0; \
+}
+
+#define AUBIO_DEL(NAME) \
+static void \
+Py_ ## NAME ## _del ( Py_ ## NAME * self) \
+{ \
+ del_aubio_ ## NAME (self->o); \
+ self->ob_type->tp_free ((PyObject *) self); \
+}
+
+#define AUBIO_MEMBERS_START(NAME) \
+static PyMemberDef Py_ ## NAME ## _members[] = {
+
+#define AUBIO_MEMBERS_STOP(NAME) \
+ {NULL} \
+};
+
+#define AUBIO_METHODS(NAME) \
+static PyMethodDef Py_ ## NAME ## _methods[] = { \
+ {NULL} \
+};
+
+
+#define AUBIO_TYPEOBJECT(NAME, PYNAME) \
+PyTypeObject Py_ ## NAME ## Type = { \
+ PyObject_HEAD_INIT (NULL) \
+ 0, \
+ PYNAME, \
+ sizeof (Py_ ## NAME), \
+ 0, \
+ (destructor) Py_ ## NAME ## _del, \
+ 0, \
+ 0, \
+ 0, \
+ 0, \
+ 0, \
+ 0, \
+ 0, \
+ 0, \
+ 0, \
+ (ternaryfunc)Py_ ## NAME ## _do, \
+ 0, \
+ 0, \
+ 0, \
+ 0, \
+ Py_TPFLAGS_DEFAULT, \
+ Py_ ## NAME ## _doc, \
+ 0, \
+ 0, \
+ 0, \
+ 0, \
+ 0, \
+ 0, \
+ Py_ ## NAME ## _methods, \
+ Py_ ## NAME ## _members, \
+ 0, \
+ 0, \
+ 0, \
+ 0, \
+ 0, \
+ 0, \
+ (initproc) Py_ ## NAME ## _init, \
+ 0, \
+ Py_ ## NAME ## _new, \
+};
+
+// some more helpers
+#define AUBIO_NEW_VEC(name, type, lengthval) \
+ name = (type *) PyObject_New (type, & type ## Type); \
+ name->length = lengthval;
--- a/python/bench-cluster-test
+++ /dev/null
@@ -1,9 +1,0 @@
-#! /usr/bin/python
-
-from aubio.bench.broadcast import *
-
-run_broadcast(remote_sync,'/home/testing')
-run_broadcast(remote_sync,'/home/testing','-n')
-run_broadcast(fetch_results,'/home/testing','-n')
-
-run_broadcast(remote_queue,'echo coucou')
--- a/python/bench-test
+++ /dev/null
@@ -1,13 +1,0 @@
-#! /usr/bin/python
-
-from aubio.bench.node import *
-
-datapath = '/var/www'
-respath = '/var/tmp'
-
-def my_print(input,output):
- cmd = "%s %s %s" % ("time sleep 0.3; echo",input,output)
- return runcommand(cmd,debug=0)
-
-act_on_results(mkdir,datapath,respath,filter='d')
-act_on_data(my_print,datapath,respath,suffix='.txt')
--- /dev/null
+++ b/python/build_linux
@@ -1,0 +1,9 @@
+#! /bin/sh
+
+set -e
+set -x
+
+python setup.py clean build
+export PYTHONPATH=./build/lib.linux-x86_64-2.7/:./tests
+export LD_LIBRARY_PATH=../build/src/
+./run_all_tests --verbose
--- /dev/null
+++ b/python/build_osx
@@ -1,0 +1,9 @@
+#! /bin/sh
+
+set -e
+set -x
+
+python setup.py clean build
+export PYTHONPATH=./build/lib.macosx-10.6-intel-2.7:$PYTHONPATH
+export DYLD_LIBRARY_PATH=../build/src
+./run_all_tests --verbose
--- /dev/null
+++ b/python/c_weighting_test_simple.expected
@@ -1,0 +1,2 @@
+ 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 5.00000000e-01 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00
+ 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00 1.08504281e-01 2.31621372e-01 1.38614617e-01 1.58040475e-02 -9.84900252e-04 -2.72686896e-03 -2.87772967e-03 -2.87932142e-03 -2.86783482e-03 -2.85529016e-03 -2.84270413e-03 -2.83016008e-03 -2.81766458e-03 -2.80521796e-03 -2.79282009e-03 -2.78047079e-03 -2.76816989e-03 -2.75591721e-03 -2.74371257e-03 -2.73155579e-03
--- /dev/null
+++ b/python/demos/demo_beats_and_tempo.py
@@ -1,0 +1,39 @@
+#! /usr/bin/env python
+
+import sys
+from aubio import tempo, source
+
+win_s = 512 # fft size
+hop_s = win_s / 2 # hop size
+samplerate = 44100
+
+if len(sys.argv) < 2:
+ print "Usage: %s <filename>" % sys.argv[0]
+ sys.exit(1)
+
+filename = sys.argv[1]
+beats = []
+
+s = source(filename, samplerate, hop_s)
+t = tempo("default", win_s, hop_s)
+
+block_read = 0
+while True:
+ samples, read = s()
+ isbeat = t(samples)
+ if isbeat:
+ thisbeat = (block_read * hop_s + isbeat[0]) / samplerate
+ print "%.4f" % thisbeat
+ beats.append (thisbeat)
+ block_read += 1
+ if read < hop_s: break
+
+periods = [60./(b - a) for a,b in zip(beats[:-1],beats[1:])]
+
+from numpy import mean, median
+print 'mean period:', mean(periods), 'bpm'
+print 'median period:', median(periods), 'bpm'
+
+from pylab import plot, show
+plot(beats[1:], periods)
+show()
--- /dev/null
+++ b/python/demos/demo_filterbank_slaney.py
@@ -1,0 +1,21 @@
+#! /usr/bin/env python
+
+from aubio import filterbank
+from numpy import array, arange, vstack
+
+win_s = 8192
+samplerate = 16000
+
+f = filterbank(40, win_s)
+f.set_mel_coeffs_slaney(samplerate)
+
+from pylab import loglog, title, show, xlim, ylim, xlabel, ylabel
+xlim([0,samplerate / 2])
+times = vstack([arange(win_s / 2 + 1) * samplerate / win_s] * 40)
+loglog(times.T, f.get_coeffs().T, '.-')
+title('Mel frequency bands coefficients')
+xlim([100, 7500])
+ylim([1.0e-3, 2.0e-2])
+xlabel('Frequency (Hz)')
+ylabel('Amplitude')
+show()
--- /dev/null
+++ b/python/demos/demo_filterbank_triangle_bands.py
@@ -1,0 +1,47 @@
+#! /usr/bin/env python
+
+from aubio import filterbank, fvec
+from pylab import loglog, show, subplot, xlim, ylim, xlabel, ylabel, title
+from numpy import vstack, arange
+
+win_s = 2048
+samplerate = 48000
+
+freq_list = [60, 80, 200, 400, 800, 1600, 3200, 6400, 12800, 24000]
+n_filters = len(freq_list) - 2
+
+f = filterbank(n_filters, win_s)
+freqs = fvec(freq_list)
+f.set_triangle_bands(freqs, samplerate)
+
+subplot(211)
+title('Examples of filterbank built with set_triangle_bands and set_coeffs')
+times = vstack([arange(win_s / 2 + 1) * samplerate / win_s] * n_filters)
+loglog(times.T, f.get_coeffs().T, '.-')
+xlim([50, samplerate/2])
+ylim([1.0e-6, 2.0e-2])
+ylabel('Amplitude')
+
+## build a new filterbank
+
+freq_list = [60, 80, 200, 400, 800, 1200, 1600, 3200, 6400, 10000, 15000, 24000]
+n_filters = len(freq_list) - 2
+
+f = filterbank(n_filters, win_s)
+freqs = fvec(freq_list)
+f.set_triangle_bands(freqs, samplerate)
+
+coeffs = f.get_coeffs()
+coeffs[4] *= 5.
+
+f.set_coeffs(coeffs)
+
+subplot(212)
+times = vstack([arange(win_s / 2 + 1) * samplerate / win_s] * n_filters)
+loglog(times.T, f.get_coeffs().T, '.-')
+xlim([50, samplerate/2])
+ylim([1.0e-6, 2.0e-2])
+xlabel('Frequency (Hz)')
+ylabel('Amplitude')
+
+show()
--- /dev/null
+++ b/python/demos/demo_onset_sinusoid.py
@@ -1,0 +1,84 @@
+#! /usr/bin/env python
+
+from numpy import random, sin, arange, ones, zeros
+from math import pi
+from aubio import fvec, onset
+
+def build_sinusoid(length, freqs, samplerate):
+ return sin( 2. * pi * arange(length) * freqs / samplerate)
+
+def run_onset(p, input_vec):
+ f = fvec (p.hop_size)
+ cands = []
+ count = 0
+ for vec_slice in input_vec.reshape((-1, p.hop_size)):
+ f[:] = vec_slice
+ cands.append(o(f))
+ return cands
+
+methods = ['default',
+ 'energy',
+ 'complex',
+ 'phase',
+ 'specdiff',
+ 'kl',
+ 'mkl',
+ 'specflux',
+ 'centroid',
+ 'spread',
+ 'skewness',
+ 'kurtosis',
+ 'slope',
+ 'decrease',
+ 'rolloff',
+ ]
+
+cands = {}
+buf_size = 2048
+hop_size = 512
+samplerate = 44100
+sin_length = (samplerate * 10) % 512 * 512
+freqs = zeros(sin_length)
+
+partition = sin_length / 8
+pointer = 0
+
+pointer += partition
+freqs[pointer: pointer + partition] = 440
+
+pointer += partition
+pointer += partition
+freqs[ pointer : pointer + partition ] = 740
+
+pointer += partition
+freqs[ pointer : pointer + partition ] = 1480
+
+pointer += partition
+pointer += partition
+freqs[ pointer : pointer + partition ] = 400 + 5 * random.random(sin_length/8)
+
+a = build_sinusoid(sin_length, freqs, samplerate)
+
+for method in methods:
+ o = onset(method, buf_size, hop_size, samplerate)
+ cands[method] = run_onset(o, a)
+
+print "done computing"
+
+if 1:
+ from pylab import plot, show, xlabel, ylabel, legend, ylim, subplot
+ subplot (211)
+ legend(methods+['ground truth'], 'upper right')
+ xlabel('time (s)')
+ ylabel('amplitude')
+ ramp = arange(0, sin_length).astype('float') / samplerate
+ plot(ramp, a, ':')
+ subplot (212)
+ ramp = arange(0, sin_length / hop_size).astype('float') * hop_size / samplerate
+ for method in methods:
+ plot(ramp, cands[method],'.-')
+ legend(methods, 'upper right')
+ xlabel('time (s)')
+ ylabel('spectral descriptor value')
+ show()
+
--- /dev/null
+++ b/python/demos/demo_pitch_sinusoid.py
@@ -1,0 +1,68 @@
+#! /usr/bin/env python
+
+from numpy import random, sin, arange, ones, zeros
+from math import pi
+from aubio import fvec, pitch
+
+def build_sinusoid(length, freqs, samplerate):
+ return sin( 2. * pi * arange(length) * freqs / samplerate)
+
+def run_pitch(p, input_vec):
+ f = fvec (p.hop_size)
+ cands = []
+ count = 0
+ for vec_slice in input_vec.reshape((-1, p.hop_size)):
+ f[:] = vec_slice
+ cands.append(p(f))
+ return cands
+
+methods = ['default', 'schmitt', 'fcomb', 'mcomb', 'yin', 'yinfft']
+
+cands = {}
+buf_size = 2048
+hop_size = 512
+samplerate = 44100
+sin_length = (samplerate * 10) % 512 * 512
+freqs = zeros(sin_length)
+
+partition = sin_length / 8
+pointer = 0
+
+pointer += partition
+freqs[pointer: pointer + partition] = 440
+
+pointer += partition
+pointer += partition
+freqs[ pointer : pointer + partition ] = 740
+
+pointer += partition
+freqs[ pointer : pointer + partition ] = 1480
+
+pointer += partition
+pointer += partition
+freqs[ pointer : pointer + partition ] = 400 + 5 * random.random(sin_length/8)
+
+a = build_sinusoid(sin_length, freqs, samplerate)
+
+for method in methods:
+ p = pitch(method, buf_size, hop_size, samplerate)
+ cands[method] = run_pitch(p, a)
+
+print "done computing"
+
+if 1:
+ from pylab import plot, show, xlabel, ylabel, legend, ylim
+ ramp = arange(0, sin_length / hop_size).astype('float') * hop_size / samplerate
+ for method in methods:
+ plot(ramp, cands[method],'.-')
+
+ # plot ground truth
+ ramp = arange(0, sin_length).astype('float') / samplerate
+ plot(ramp, freqs, ':')
+
+ legend(methods+['ground truth'], 'upper right')
+ xlabel('time (s)')
+ ylabel('frequency (Hz)')
+ ylim([0,2000])
+ show()
+
--- /dev/null
+++ b/python/demos/demo_simple_robot_voice.py
@@ -1,0 +1,29 @@
+#! /usr/bin/env python
+
+import sys
+from aubio import source, sink, pvoc
+
+if __name__ == '__main__':
+ if len(sys.argv) < 2:
+ print 'usage: %s <inputfile> <outputfile>' % sys.argv[0]
+ sys.exit(1)
+ samplerate = 44100
+ f = source(sys.argv[1], samplerate, 256)
+ g = sink(sys.argv[2], samplerate)
+ total_frames, read = 0, 256
+
+ win_s = 512 # fft size
+ hop_s = win_s / 2 # hop size
+ pv = pvoc(win_s, hop_s) # phase vocoder
+
+ while read:
+ samples, read = f()
+ spectrum = pv(samples) # compute spectrum
+ spectrum.phas[:] = 0. # zero phase
+ new_samples = pv.rdo(spectrum) # compute modified samples
+ g(new_samples, read) # write to output
+ total_frames += read
+
+ print "wrote", total_frames, "from", f.uri, "to", g.uri
+
+
--- /dev/null
+++ b/python/demos/demo_sink.py
@@ -1,0 +1,17 @@
+#! /usr/bin/env python
+
+import sys
+from aubio import source, sink
+
+if __name__ == '__main__':
+ if len(sys.argv) < 3:
+ print 'usage: %s <inputfile> <outputfile>' % sys.argv[0]
+ sys.exit(1)
+ f = source(sys.argv[1], 8000, 256)
+ g = sink(sys.argv[2], 8000)
+ total_frames, read = 0, 256
+ while read:
+ vec, read = f()
+ g(vec, read)
+ total_frames += read
+ print "read", total_frames / float(f.samplerate), "seconds from", f.uri
--- /dev/null
+++ b/python/demos/demo_sink_create_woodblock.py
@@ -1,0 +1,38 @@
+#! /usr/bin/env python
+
+import sys
+from math import sin, pi
+from aubio import sink
+from numpy import array
+
+if len(sys.argv) != 2:
+ print 'usage: %s <outputfile>' % sys.argv[0]
+ sys.exit(1)
+
+samplerate = 44100 # in Hz
+pitch = 2200 # in Hz
+blocksize = 256 # in samples
+duration = 0.02 # in seconds
+
+twopi = pi * 2.
+
+duration = int ( 44100 * duration ) # convert to samples
+attack = 3
+
+period = int ( float(samplerate) / pitch )
+sinetone = [ 0.7 * sin(twopi * i/ period) for i in range(period) ]
+sinetone *= int ( duration / period )
+sinetone = array(sinetone, dtype = 'float32')
+
+from math import exp, e
+for i in range(len(sinetone)):
+ sinetone[i] *= exp( - e * float(i) / len(sinetone))
+for i in range(attack):
+ sinetone[i] *= exp( e * (float(i) / attack - 1 ) )
+
+my_sink = sink(sys.argv[1], 44100)
+
+i = 0
+while i + blocksize < duration:
+ my_sink(sinetone[i:i+blocksize], blocksize)
+ i += blocksize
--- /dev/null
+++ b/python/demos/demo_source.py
@@ -1,0 +1,16 @@
+#! /usr/bin/env python
+
+import sys
+from aubio import source
+
+if __name__ == '__main__':
+ if len(sys.argv) < 2:
+ print 'usage: %s <inputfile>' % sys.argv[0]
+ sys.exit(1)
+ f = source(sys.argv[1], 1, 256)
+ samplerate = f.get_samplerate()
+ total_frames, read = 0, 256
+ while read:
+ vec, read = f()
+ total_frames += read
+ print "read", total_frames / float(samplerate), "seconds from", f.uri
--- /dev/null
+++ b/python/demos/demo_spectrogram.py
@@ -1,0 +1,63 @@
+#! /usr/bin/env python
+
+import sys
+from aubio import pvoc, source
+from numpy import array, arange, zeros, shape, log10, vstack
+from pylab import imshow, show, cm, axis, ylabel, xlabel, xticks, yticks
+
+def get_spectrogram(filename):
+ samplerate = 44100
+ win_s = 512 # fft window size
+ hop_s = win_s / 2 # hop size
+ fft_s = win_s / 2 + 1 # spectrum bins
+
+ a = source(filename, samplerate, hop_s) # source file
+ pv = pvoc(win_s, hop_s) # phase vocoder
+ specgram = zeros([0, fft_s], dtype='float32') # numpy array to store spectrogram
+
+ # analysis
+ while True:
+ samples, read = a() # read file
+ specgram = vstack((specgram,pv(samples).norm)) # store new norm vector
+ if read < a.hop_size: break
+
+ # plotting
+ imshow(log10(specgram.T + .001), origin = 'bottom', aspect = 'auto', cmap=cm.gray_r)
+ axis([0, len(specgram), 0, len(specgram[0])])
+ # show axes in Hz and seconds
+ time_step = hop_s / float(samplerate)
+ total_time = len(specgram) * time_step
+ print "total time: %0.2fs" % total_time,
+ print ", samplerate: %.2fkHz" % (samplerate / 1000.)
+ n_xticks = 10
+ n_yticks = 10
+
+ def get_rounded_ticks( top_pos, step, n_ticks ):
+ top_label = top_pos * step
+ # get the first label
+ ticks_first_label = top_pos * step / n_ticks
+ # round to the closest .1
+ ticks_first_label = round ( ticks_first_label * 10. ) / 10.
+ # compute all labels from the first rounded one
+ ticks_labels = [ ticks_first_label * n for n in range(n_ticks) ] + [ top_label ]
+ # get the corresponding positions
+ ticks_positions = [ ticks_labels[n] / step for n in range(n_ticks) ] + [ top_pos ]
+ # convert to string
+ ticks_labels = [ "%.1f" % x for x in ticks_labels ]
+ # return position, label tuple to use with x/yticks
+ return ticks_positions, ticks_labels
+
+ # apply to the axis
+ xticks( *get_rounded_ticks ( len(specgram), time_step, n_xticks ) )
+ yticks( *get_rounded_ticks ( len(specgram[0]), (samplerate / 2. / 1000.) / len(specgram[0]), n_yticks ) )
+ ylabel('Frequency (kHz)')
+ xlabel('Time (s)')
+
+if __name__ == '__main__':
+ if len(sys.argv) < 2:
+ print "Usage: %s <filename>" % sys.argv[0]
+ else:
+ for soundfile in sys.argv[1:]:
+ get_spectrogram(soundfile)
+ # display graph
+ show()
--- /dev/null
+++ b/python/demos/demo_tss.py
@@ -1,0 +1,47 @@
+#! /usr/bin/env python
+
+import sys
+from aubio import source, sink, pvoc, tss
+
+if __name__ == '__main__':
+ if len(sys.argv) < 2:
+ print 'usage: %s <inputfile> <outputfile_transient> <outputfile_steady>' % sys.argv[0]
+ sys.exit(1)
+
+ samplerate = 44100
+ win_s = 512 # fft size
+ hop_s = win_s / 2 # block size
+ threshold = 0.26
+
+ f = source(sys.argv[1], samplerate, hop_s)
+ g = sink(sys.argv[2], samplerate)
+ h = sink(sys.argv[3], samplerate)
+
+ pv = pvoc(win_s, hop_s) # phase vocoder
+ pw = pvoc(win_s, hop_s) # another phase vocoder
+ t = tss(win_s, hop_s) # transient steady state separation
+
+ t.set_threshold(threshold)
+
+ read = hop_s
+
+ while read:
+ samples, read = f() # read file
+ spec = pv(samples) # compute spectrum
+ trans_spec, stead_spec = t(spec) # transient steady-state separation
+ transients = pv.rdo(trans_spec) # overlap-add synthesis of transients
+ steadstate = pw.rdo(stead_spec) # overlap-add synthesis of steady states
+ g(transients, read) # write transients to output
+ h(steadstate, read) # write steady states to output
+
+ del f, g, h # finish writing the files now
+
+ from demo_spectrogram import get_spectrogram
+ from pylab import subplot, show
+ subplot(311)
+ get_spectrogram(sys.argv[1])
+ subplot(312)
+ get_spectrogram(sys.argv[2])
+ subplot(313)
+ get_spectrogram(sys.argv[3])
+ show()
--- /dev/null
+++ b/python/gen_pyobject.py
@@ -1,0 +1,526 @@
+#! /usr/bin/python
+
+""" This madness of code is used to generate the C code of the python interface
+to aubio. Don't try this at home.
+
+The list of typedefs and functions is obtained from the command line 'cpp
+aubio.h'. This list is then used to parse all the functions about this object.
+
+I hear the ones asking "why not use swig, or cython, or something like that?"
+
+The requirements for this extension are the following:
+
+ - aubio vectors can be viewed as numpy arrays, and vice versa
+ - aubio 'object' should be python classes, not just a bunch of functions
+
+I haven't met any python interface generator that can meet both these
+requirements. If you know of one, please let me know, it will spare me
+maintaining this bizarre file.
+"""
+
+param_numbers = {
+ 'source': [0, 2],
+ 'sink': [2, 0],
+}
+
+# TODO
+# do function: for now, only the following pattern is supported:
+# void aubio_<foo>_do (aubio_foo_t * o,
+# [input1_t * input, [output1_t * output, ..., output3_t * output]]);
+# There is no way of knowing that output1 is actually input2. In the future,
+# const could be used for the inputs in the C prototypes.
+
+def write_msg(*args):
+ pass
+ # uncomment out for debugging
+ #print args
+
+def split_type(arg):
+ """ arg = 'foo *name'
+ return ['foo*', 'name'] """
+ l = arg.split()
+ type_arg = {'type': l[0], 'name': l[1]}
+ # ['foo', '*name'] -> ['foo*', 'name']
+ if l[-1].startswith('*'):
+ #return [l[0]+'*', l[1][1:]]
+ type_arg['type'] = l[0] + '*'
+ type_arg['name'] = l[1][1:]
+ # ['foo', '*', 'name'] -> ['foo*', 'name']
+ if len(l) == 3:
+ #return [l[0]+l[1], l[2]]
+ type_arg['type'] = l[0]+l[1]
+ type_arg['name'] = l[2]
+ else:
+ #return l
+ pass
+ return type_arg
+
+def get_params(proto):
+ """ get the list of parameters from a function prototype
+ example: proto = "int main (int argc, char ** argv)"
+ returns: ['int argc', 'char ** argv']
+ """
+ import re
+ paramregex = re.compile('[\(, ](\w+ \*?\*? ?\w+)[, \)]')
+ return paramregex.findall(proto)
+
+def get_params_types_names(proto):
+ """ get the list of parameters from a function prototype
+ example: proto = "int main (int argc, char ** argv)"
+ returns: [['int', 'argc'], ['char **','argv']]
+ """
+ return map(split_type, get_params(proto))
+
+def get_return_type(proto):
+ import re
+ paramregex = re.compile('(\w+ ?\*?).*')
+ outputs = paramregex.findall(proto)
+ assert len(outputs) == 1
+ return outputs[0].replace(' ', '')
+
+def get_name(proto):
+ name = proto.split()[1].split('(')[0]
+ return name.replace('*','')
+
+# the important bits: the size of the output for each objects. this data should
+# move into the C library at some point.
+defaultsizes = {
+ 'resampler': ['input->length * self->ratio'],
+ 'specdesc': ['1'],
+ 'onset': ['1'],
+ 'pitchyin': ['1'],
+ 'pitchyinfft': ['1'],
+ 'pitchschmitt': ['1'],
+ 'pitchmcomb': ['1'],
+ 'pitchfcomb': ['1'],
+ 'pitch': ['1'],
+ 'tss': ['self->buf_size', 'self->buf_size'],
+ 'mfcc': ['self->n_coeffs'],
+ 'beattracking': ['self->hop_size'],
+ 'tempo': ['1'],
+ 'peakpicker': ['1'],
+ 'source': ['self->hop_size', '1'],
+}
+
+# default value for variables
+aubioinitvalue = {
+ 'uint_t': 0,
+ 'smpl_t': 0,
+ 'lsmp_t': 0.,
+ 'char_t*': 'NULL',
+ }
+
+aubiodefvalue = {
+ # we have some clean up to do
+ 'buf_size': 'Py_default_vector_length',
+ # and here too
+ 'hop_size': 'Py_default_vector_length / 2',
+ # these should be alright
+ 'samplerate': 'Py_aubio_default_samplerate',
+ # now for the non obvious ones
+ 'n_filters': '40',
+ 'n_coeffs': '13',
+ 'nelems': '10',
+ 'flow': '0.',
+ 'fhig': '1.',
+ 'ilow': '0.',
+ 'ihig': '1.',
+ 'thrs': '0.5',
+ 'ratio': '0.5',
+ 'method': '"default"',
+ 'uri': '"none"',
+ }
+
+# aubio to python
+aubio2pytypes = {
+ 'uint_t': 'I',
+ 'smpl_t': 'f',
+ 'lsmp_t': 'd',
+ 'fvec_t*': 'O',
+ 'cvec_t*': 'O',
+ 'char_t*': 's',
+}
+
+# python to aubio
+aubiovecfrompyobj = {
+ 'fvec_t*': 'PyAubio_ArrayToCFvec',
+ 'cvec_t*': 'PyAubio_ArrayToCCvec',
+ 'uint_t': '(uint_t)PyInt_AsLong',
+}
+
+# aubio to python
+aubiovectopyobj = {
+ 'fvec_t*': 'PyAubio_CFvecToArray',
+ 'cvec_t*': 'PyAubio_CCvecToPyCvec',
+ 'smpl_t': 'PyFloat_FromDouble',
+ 'uint_t*': 'PyInt_FromLong',
+ 'uint_t': 'PyInt_FromLong',
+}
+
+def gen_new_init(newfunc, name):
+ newparams = get_params_types_names(newfunc)
+ # self->param1, self->param2, self->param3
+ if len(newparams):
+ selfparams = ', self->'+', self->'.join([p['name'] for p in newparams])
+ else:
+ selfparams = ''
+ # "param1", "param2", "param3"
+ paramnames = ", ".join(["\""+p['name']+"\"" for p in newparams])
+ pyparams = "".join(map(lambda p: aubio2pytypes[p['type']], newparams))
+ paramrefs = ", ".join(["&" + p['name'] for p in newparams])
+ s = """\
+// WARNING: this file is generated, DO NOT EDIT
+
+// WARNING: if you haven't read the first line yet, please do so
+#include "aubiowraphell.h"
+
+typedef struct
+{
+ PyObject_HEAD
+ aubio_%(name)s_t * o;
+""" % locals()
+ for p in newparams:
+ ptype = p['type']
+ pname = p['name']
+ s += """\
+ %(ptype)s %(pname)s;
+""" % locals()
+ s += """\
+} Py_%(name)s;
+
+static char Py_%(name)s_doc[] = "%(name)s object";
+
+static PyObject *
+Py_%(name)s_new (PyTypeObject * pytype, PyObject * args, PyObject * kwds)
+{
+ Py_%(name)s *self;
+""" % locals()
+ for p in newparams:
+ ptype = p['type']
+ pname = p['name']
+ initval = aubioinitvalue[ptype]
+ s += """\
+ %(ptype)s %(pname)s = %(initval)s;
+""" % locals()
+ # now the actual PyArg_Parse
+ if len(paramnames):
+ s += """\
+ static char *kwlist[] = { %(paramnames)s, NULL };
+
+ if (!PyArg_ParseTupleAndKeywords (args, kwds, "|%(pyparams)s", kwlist,
+ %(paramrefs)s)) {
+ return NULL;
+ }
+""" % locals()
+ s += """\
+
+ self = (Py_%(name)s *) pytype->tp_alloc (pytype, 0);
+
+ if (self == NULL) {
+ return NULL;
+ }
+""" % locals()
+ for p in newparams:
+ ptype = p['type']
+ pname = p['name']
+ defval = aubiodefvalue[pname]
+ if ptype == 'char_t*':
+ s += """\
+
+ self->%(pname)s = %(defval)s;
+ if (%(pname)s != NULL) {
+ self->%(pname)s = %(pname)s;
+ }
+""" % locals()
+ elif ptype == 'uint_t':
+ s += """\
+
+ self->%(pname)s = %(defval)s;
+ if (%(pname)s > 0) {
+ self->%(pname)s = %(pname)s;
+ } else if (%(pname)s < 0) {
+ PyErr_SetString (PyExc_ValueError,
+ "can not use negative value for %(pname)s");
+ return NULL;
+ }
+""" % locals()
+ elif ptype == 'smpl_t':
+ s += """\
+
+ self->%(pname)s = %(defval)s;
+ if (%(pname)s != %(defval)s) {
+ self->%(pname)s = %(pname)s;
+ }
+""" % locals()
+ else:
+ write_msg ("ERROR, unknown type of parameter %s %s" % (ptype, pname) )
+ s += """\
+
+ return (PyObject *) self;
+}
+
+AUBIO_INIT(%(name)s %(selfparams)s)
+
+AUBIO_DEL(%(name)s)
+
+""" % locals()
+ return s
+
+def gen_do_input_params(inputparams):
+ inputdefs = ''
+ parseinput = ''
+ inputrefs = ''
+ inputvecs = ''
+ pytypes = ''
+
+ if len(inputparams):
+ # build the parsing string for PyArg_ParseTuple
+ pytypes = "".join([aubio2pytypes[p['type']] for p in inputparams])
+
+ inputdefs = " /* input vectors python prototypes */\n"
+ for p in inputparams:
+ if p['type'] != 'uint_t':
+ inputdefs += " PyObject * " + p['name'] + "_obj;\n"
+
+ inputvecs = " /* input vectors prototypes */\n "
+ inputvecs += "\n ".join(map(lambda p: p['type'] + ' ' + p['name'] + ";", inputparams))
+
+ parseinput = " /* input vectors parsing */\n "
+ for p in inputparams:
+ inputvec = p['name']
+ if p['type'] != 'uint_t':
+ inputdef = p['name'] + "_obj"
+ else:
+ inputdef = p['name']
+ converter = aubiovecfrompyobj[p['type']]
+ if p['type'] != 'uint_t':
+ parseinput += """%(inputvec)s = %(converter)s (%(inputdef)s);
+
+ if (%(inputvec)s == NULL) {
+ return NULL;
+ }
+
+ """ % locals()
+
+ # build the string for the input objects references
+ inputreflist = []
+ for p in inputparams:
+ if p['type'] != 'uint_t':
+ inputreflist += [ "&" + p['name'] + "_obj" ]
+ else:
+ inputreflist += [ "&" + p['name'] ]
+ inputrefs = ", ".join(inputreflist)
+ # end of inputs strings
+ return inputdefs, parseinput, inputrefs, inputvecs, pytypes
+
+def gen_do_output_params(outputparams, name):
+ outputvecs = ""
+ outputcreate = ""
+ if len(outputparams):
+ outputvecs = " /* output vectors prototypes */\n"
+ for p in outputparams:
+ params = {
+ 'name': p['name'], 'pytype': p['type'], 'autype': p['type'][:-3],
+ 'length': defaultsizes[name].pop(0) }
+ if (p['type'] == 'uint_t*'):
+ outputvecs += ' uint_t' + ' ' + p['name'] + ";\n"
+ outputcreate += " %(name)s = 0;\n" % params
+ else:
+ outputvecs += " " + p['type'] + ' ' + p['name'] + ";\n"
+ outputcreate += " /* creating output %(name)s as a new_%(autype)s of length %(length)s */\n" % params
+ outputcreate += " %(name)s = new_%(autype)s (%(length)s);\n" % params
+
+ returnval = "";
+ if len(outputparams) > 1:
+ returnval += " PyObject *outputs = PyList_New(0);\n"
+ for p in outputparams:
+ returnval += " PyList_Append( outputs, (PyObject *)" + aubiovectopyobj[p['type']] + " (" + p['name'] + ")" +");\n"
+ returnval += " return outputs;"
+ elif len(outputparams) == 1:
+ if defaultsizes[name] == '1':
+ returnval += " return (PyObject *)PyFloat_FromDouble(" + p['name'] + "->data[0])"
+ else:
+ returnval += " return (PyObject *)" + aubiovectopyobj[p['type']] + " (" + p['name'] + ")"
+ else:
+ returnval = " return Py_None;";
+ # end of output strings
+ return outputvecs, outputcreate, returnval
+
+def gen_do(dofunc, name):
+ funcname = dofunc.split()[1].split('(')[0]
+ doparams = get_params_types_names(dofunc)
+ # make sure the first parameter is the object
+ assert doparams[0]['type'] == "aubio_"+name+"_t*", \
+ "method is not in 'aubio_<name>_t"
+ # and remove it
+ doparams = doparams[1:]
+
+ n_param = len(doparams)
+
+ if name in param_numbers.keys():
+ n_input_param, n_output_param = param_numbers[name]
+ else:
+ n_input_param, n_output_param = 1, n_param - 1
+
+ assert n_output_param + n_input_param == n_param, "n_output_param + n_input_param != n_param for %s" % name
+
+ inputparams = doparams[:n_input_param]
+ outputparams = doparams[n_input_param:n_input_param + n_output_param]
+
+ inputdefs, parseinput, inputrefs, inputvecs, pytypes = gen_do_input_params(inputparams);
+ outputvecs, outputcreate, returnval = gen_do_output_params(outputparams, name)
+
+ # build strings for outputs
+ # build the parameters for the _do() call
+ doparams_string = "self->o"
+ for p in doparams:
+ if p['type'] == 'uint_t*':
+ doparams_string += ", &" + p['name']
+ else:
+ doparams_string += ", " + p['name']
+
+ if n_input_param:
+ arg_parse_tuple = """\
+ if (!PyArg_ParseTuple (args, "%(pytypes)s", %(inputrefs)s)) {
+ return NULL;
+ }
+""" % locals()
+ else:
+ arg_parse_tuple = ""
+ # put it all together
+ s = """\
+/* function Py_%(name)s_do */
+static PyObject *
+Py_%(name)s_do(Py_%(name)s * self, PyObject * args)
+{
+%(inputdefs)s
+%(inputvecs)s
+%(outputvecs)s
+
+%(arg_parse_tuple)s
+
+%(parseinput)s
+
+%(outputcreate)s
+
+ /* compute _do function */
+ %(funcname)s (%(doparams_string)s);
+
+%(returnval)s;
+}
+""" % locals()
+ return s
+
+def gen_members(new_method, name):
+ newparams = get_params_types_names(new_method)
+ s = """
+AUBIO_MEMBERS_START(%(name)s)""" % locals()
+ for param in newparams:
+ if param['type'] == 'char_t*':
+ s += """
+ {"%(pname)s", T_STRING, offsetof (Py_%(name)s, %(pname)s), READONLY, ""},""" \
+ % { 'pname': param['name'], 'ptype': param['type'], 'name': name}
+ elif param['type'] == 'uint_t':
+ s += """
+ {"%(pname)s", T_INT, offsetof (Py_%(name)s, %(pname)s), READONLY, ""},""" \
+ % { 'pname': param['name'], 'ptype': param['type'], 'name': name}
+ elif param['type'] == 'smpl_t':
+ s += """
+ {"%(pname)s", T_FLOAT, offsetof (Py_%(name)s, %(pname)s), READONLY, ""},""" \
+ % { 'pname': param['name'], 'ptype': param['type'], 'name': name}
+ else:
+ write_msg ("-- ERROR, unknown member type ", param )
+ s += """
+AUBIO_MEMBERS_STOP(%(name)s)
+
+""" % locals()
+ return s
+
+
+def gen_methods(get_methods, set_methods, name):
+ s = ""
+ method_defs = ""
+ for method in set_methods:
+ method_name = get_name(method)
+ params = get_params_types_names(method)
+ out_type = get_return_type(method)
+ assert params[0]['type'] == "aubio_"+name+"_t*", \
+ "get method is not in 'aubio_<name>_t"
+ write_msg (method )
+ write_msg (params[1:])
+ setter_args = "self->o, " +",".join([p['name'] for p in params[1:]])
+ parse_args = ""
+ for p in params[1:]:
+ parse_args += p['type'] + " " + p['name'] + ";\n"
+ argmap = "".join([aubio2pytypes[p['type']] for p in params[1:]])
+ arglist = ", ".join(["&"+p['name'] for p in params[1:]])
+ parse_args += """
+ if (!PyArg_ParseTuple (args, "%(argmap)s", %(arglist)s)) {
+ return NULL;
+ } """ % locals()
+ s += """
+static PyObject *
+Py%(funcname)s (Py_%(objname)s *self, PyObject *args)
+{
+ uint_t err = 0;
+
+ %(parse_args)s
+
+ err = %(funcname)s (%(setter_args)s);
+
+ if (err > 0) {
+ PyErr_SetString (PyExc_ValueError,
+ "error running %(funcname)s");
+ return NULL;
+ }
+ return Py_None;
+}
+""" % {'funcname': method_name, 'objname': name,
+ 'out_type': out_type, 'setter_args': setter_args, 'parse_args': parse_args }
+ shortname = method_name.split(name+'_')[-1]
+ method_defs += """\
+ {"%(shortname)s", (PyCFunction) Py%(method_name)s,
+ METH_VARARGS, ""},
+""" % locals()
+
+ for method in get_methods:
+ method_name = get_name(method)
+ params = get_params_types_names(method)
+ out_type = get_return_type(method)
+ assert params[0]['type'] == "aubio_"+name+"_t*", \
+ "get method is not in 'aubio_<name>_t %s" % params[0]['type']
+ assert len(params) == 1, \
+ "get method has more than one parameter %s" % params
+ getter_args = "self->o"
+ returnval = "(PyObject *)" + aubiovectopyobj[out_type] + " (tmp)"
+ shortname = method_name.split(name+'_')[-1]
+ method_defs += """\
+ {"%(shortname)s", (PyCFunction) Py%(method_name)s,
+ METH_NOARGS, ""},
+""" % locals()
+ s += """
+static PyObject *
+Py%(funcname)s (Py_%(objname)s *self, PyObject *unused)
+{
+ %(out_type)s tmp = %(funcname)s (%(getter_args)s);
+ return %(returnval)s;
+}
+""" % {'funcname': method_name, 'objname': name,
+ 'out_type': out_type, 'getter_args': getter_args, 'returnval': returnval }
+
+ s += """
+static PyMethodDef Py_%(name)s_methods[] = {
+""" % locals()
+ s += method_defs
+ s += """\
+ {NULL} /* sentinel */
+};
+""" % locals()
+ return s
+
+def gen_finish(name):
+ s = """\
+
+AUBIO_TYPEOBJECT(%(name)s, "aubio.%(name)s")
+""" % locals()
+ return s
--- /dev/null
+++ b/python/generator.py
@@ -1,0 +1,187 @@
+#! /usr/bin/python
+
+""" This file generates a c file from a list of cpp prototypes. """
+
+import os, sys, shutil
+from gen_pyobject import write_msg, gen_new_init, gen_do, gen_members, gen_methods, gen_finish
+
+def get_cpp_objects():
+
+ cpp_output = [l.strip() for l in os.popen('cpp -DAUBIO_UNSTABLE=1 -I../build/src ../src/aubio.h').readlines()]
+
+ cpp_output = filter(lambda y: len(y) > 1, cpp_output)
+ cpp_output = filter(lambda y: not y.startswith('#'), cpp_output)
+
+ i = 1
+ while 1:
+ if i >= len(cpp_output): break
+ if cpp_output[i-1].endswith(',') or cpp_output[i-1].endswith('{') or cpp_output[i].startswith('}'):
+ cpp_output[i] = cpp_output[i-1] + ' ' + cpp_output[i]
+ cpp_output.pop(i-1)
+ else:
+ i += 1
+
+ typedefs = filter(lambda y: y.startswith ('typedef struct _aubio'), cpp_output)
+
+ cpp_objects = [a.split()[3][:-1] for a in typedefs]
+
+ return cpp_output, cpp_objects
+
+def generate_object_files():
+ if os.path.isdir('generated'): shutil.rmtree('generated')
+ os.mkdir('generated')
+
+ generated_objects = []
+ cpp_output, cpp_objects = get_cpp_objects()
+ skip_objects = ['fft',
+ 'pvoc',
+ 'filter',
+ 'filterbank',
+ 'resampler',
+ 'sndfile',
+ 'sink_apple_audio',
+ 'sink_sndfile',
+ 'source_apple_audio',
+ 'source_sndfile']
+
+ write_msg("-- INFO: %d objects in total" % len(cpp_objects))
+
+ for this_object in cpp_objects:
+ lint = 0
+
+ if this_object[-2:] == '_t':
+ object_name = this_object[:-2]
+ else:
+ object_name = this_object
+ write_msg("-- WARNING: %s does not end in _t" % this_object)
+
+ if object_name[:len('aubio_')] != 'aubio_':
+ write_msg("-- WARNING: %s does not start n aubio_" % this_object)
+
+ write_msg("-- INFO: looking at", object_name)
+ object_methods = filter(lambda x: this_object in x, cpp_output)
+ object_methods = [a.strip() for a in object_methods]
+ object_methods = filter(lambda x: not x.startswith('typedef'), object_methods)
+ #for method in object_methods:
+ # write_msg(method)
+ new_methods = filter(lambda x: 'new_'+object_name in x, object_methods)
+ if len(new_methods) > 1:
+ write_msg("-- WARNING: more than one new method for", object_name)
+ for method in new_methods:
+ write_msg(method)
+ elif len(new_methods) < 1:
+ write_msg("-- WARNING: no new method for", object_name)
+ elif 0:
+ for method in new_methods:
+ write_msg(method)
+
+ del_methods = filter(lambda x: 'del_'+object_name in x, object_methods)
+ if len(del_methods) > 1:
+ write_msg("-- WARNING: more than one del method for", object_name)
+ for method in del_methods:
+ write_msg(method)
+ elif len(del_methods) < 1:
+ write_msg("-- WARNING: no del method for", object_name)
+
+ do_methods = filter(lambda x: object_name+'_do' in x, object_methods)
+ if len(do_methods) > 1:
+ pass
+ #write_msg("-- WARNING: more than one do method for", object_name)
+ #for method in do_methods:
+ # write_msg(method)
+ elif len(do_methods) < 1:
+ write_msg("-- WARNING: no do method for", object_name)
+ elif 0:
+ for method in do_methods:
+ write_msg(method)
+
+ # check do methods return void
+ for method in do_methods:
+ if (method.split()[0] != 'void'):
+ write_msg("-- ERROR: _do method does not return void:", method )
+
+ get_methods = filter(lambda x: object_name+'_get_' in x, object_methods)
+
+ set_methods = filter(lambda x: object_name+'_set_' in x, object_methods)
+ for method in set_methods:
+ if (method.split()[0] != 'uint_t'):
+ write_msg("-- ERROR: _set method does not return uint_t:", method )
+
+ other_methods = filter(lambda x: x not in new_methods, object_methods)
+ other_methods = filter(lambda x: x not in del_methods, other_methods)
+ other_methods = filter(lambda x: x not in do_methods, other_methods)
+ other_methods = filter(lambda x: x not in get_methods, other_methods)
+ other_methods = filter(lambda x: x not in set_methods, other_methods)
+
+ if len(other_methods) > 0:
+ write_msg("-- WARNING: some methods for", object_name, "were unidentified")
+ for method in other_methods:
+ write_msg(method)
+
+
+ # generate this_object
+ short_name = object_name[len('aubio_'):]
+ if short_name in skip_objects:
+ write_msg("-- INFO: skipping object", short_name )
+ continue
+ if 1: #try:
+ s = gen_new_init(new_methods[0], short_name)
+ s += gen_do(do_methods[0], short_name)
+ s += gen_members(new_methods[0], short_name)
+ s += gen_methods(get_methods, set_methods, short_name)
+ s += gen_finish(short_name)
+ generated_filepath = 'generated/gen-'+short_name+'.c'
+ fd = open(generated_filepath, 'w')
+ fd.write(s)
+ #except Exception, e:
+ # write_msg("-- ERROR:", type(e), str(e), "in", short_name)
+ # continue
+ generated_objects += [this_object]
+
+ s = """// generated list of objects created with generator.py
+
+"""
+
+ for each in generated_objects:
+ s += "extern PyTypeObject Py_%sType;\n" % \
+ each.replace('aubio_','').replace('_t','')
+
+ types_ready = []
+ for each in generated_objects:
+ types_ready.append(" PyType_Ready (&Py_%sType) < 0" % \
+ each.replace('aubio_','').replace('_t','') )
+
+ s += """
+ int
+ generated_types_ready (void)
+ {
+ return (
+ """
+ s += ('\n ||').join(types_ready)
+ s += """);
+ }
+ """
+
+ s += """
+ void
+ add_generated_objects ( PyObject *m )
+ {"""
+ for each in generated_objects:
+ s += """ Py_INCREF (&Py_%(name)sType);
+ PyModule_AddObject (m, "%(name)s", (PyObject *) & Py_%(name)sType);""" % \
+ { 'name': ( each.replace('aubio_','').replace('_t','') ) }
+
+ s += """
+ }"""
+
+ fd = open('generated/aubio-generated.h', 'w')
+ fd.write(s)
+
+ from os import listdir
+ generated_files = listdir('generated')
+ generated_files = filter(lambda x: x.endswith('.c'), generated_files)
+ generated_files = ['generated/'+f for f in generated_files]
+ return generated_files
+
+if __name__ == '__main__':
+ generate_object_files()
--- /dev/null
+++ b/python/py-cvec.c
@@ -1,0 +1,302 @@
+#include "aubio-types.h"
+
+/* cvec type definition
+
+class cvec():
+ def __init__(self, length = 1024):
+ self.length = length
+ self.norm = array(length)
+ self.phas = array(length)
+
+*/
+
+static char Py_cvec_doc[] = "cvec object";
+
+static PyObject *
+Py_cvec_new (PyTypeObject * type, PyObject * args, PyObject * kwds)
+{
+ int length= 0;
+ Py_cvec *self;
+ static char *kwlist[] = { "length", NULL };
+
+ if (!PyArg_ParseTupleAndKeywords (args, kwds, "|I", kwlist,
+ &length)) {
+ return NULL;
+ }
+
+
+ self = (Py_cvec *) type->tp_alloc (type, 0);
+
+ self->length = Py_default_vector_length / 2 + 1;
+
+ if (self == NULL) {
+ return NULL;
+ }
+
+ if (length > 0) {
+ self->length = length / 2 + 1;
+ } else if (length < 0) {
+ PyErr_SetString (PyExc_ValueError,
+ "can not use negative number of elements");
+ return NULL;
+ }
+
+ return (PyObject *) self;
+}
+
+static int
+Py_cvec_init (Py_cvec * self, PyObject * args, PyObject * kwds)
+{
+ self->o = new_cvec ((self->length - 1) * 2);
+ if (self->o == NULL) {
+ return -1;
+ }
+
+ return 0;
+}
+
+static void
+Py_cvec_del (Py_cvec * self)
+{
+ del_cvec (self->o);
+ self->ob_type->tp_free ((PyObject *) self);
+}
+
+static PyObject *
+Py_cvec_repr (Py_cvec * self, PyObject * unused)
+{
+ PyObject *format = NULL;
+ PyObject *args = NULL;
+ PyObject *result = NULL;
+
+ format = PyString_FromString ("aubio cvec of %d elements");
+ if (format == NULL) {
+ goto fail;
+ }
+
+ args = Py_BuildValue ("I", self->length);
+ if (args == NULL) {
+ goto fail;
+ }
+ cvec_print ( self->o );
+
+ result = PyString_Format (format, args);
+
+fail:
+ Py_XDECREF (format);
+ Py_XDECREF (args);
+
+ return result;
+}
+
+PyObject *
+PyAubio_CvecNormToArray (Py_cvec * self)
+{
+ npy_intp dims[] = { self->o->length, 1 };
+ return PyArray_SimpleNewFromData (1, dims, NPY_FLOAT, self->o->norm);
+}
+
+
+PyObject *
+PyAubio_CvecPhasToArray (Py_cvec * self)
+{
+ npy_intp dims[] = { self->o->length, 1 };
+ return PyArray_SimpleNewFromData (1, dims, NPY_FLOAT, self->o->phas);
+}
+
+PyObject *
+PyAubio_ArrayToCvecPhas (PyObject * self)
+{
+ return NULL;
+}
+
+PyObject *
+Py_cvec_get_norm (Py_cvec * self, void *closure)
+{
+ return PyAubio_CvecNormToArray(self);
+}
+
+PyObject *
+Py_cvec_get_phas (Py_cvec * self, void *closure)
+{
+ return PyAubio_CvecPhasToArray(self);
+}
+
+static int
+Py_cvec_set_norm (Py_cvec * vec, PyObject *input, void * closure)
+{
+ PyArrayObject * array;
+ if (input == NULL) {
+ PyErr_SetString (PyExc_ValueError, "input array is not a python object");
+ goto fail;
+ }
+ if (PyArray_Check(input)) {
+
+ // we got an array, convert it to a cvec.norm
+ if (PyArray_NDIM ((PyArrayObject *)input) == 0) {
+ PyErr_SetString (PyExc_ValueError, "input array is a scalar");
+ goto fail;
+ } else if (PyArray_NDIM ((PyArrayObject *)input) > 2) {
+ PyErr_SetString (PyExc_ValueError,
+ "input array has more than two dimensions");
+ goto fail;
+ }
+
+ if (!PyArray_ISFLOAT ((PyArrayObject *)input)) {
+ PyErr_SetString (PyExc_ValueError, "input array should be float");
+ goto fail;
+ } else if (PyArray_TYPE ((PyArrayObject *)input) != AUBIO_NPY_SMPL) {
+ PyErr_SetString (PyExc_ValueError, "input array should be float32");
+ goto fail;
+ }
+ array = (PyArrayObject *)input;
+
+ // check input array dimensions
+ if (PyArray_NDIM (array) != 1) {
+ PyErr_Format (PyExc_ValueError,
+ "input array has %d dimensions, not 1",
+ PyArray_NDIM (array));
+ goto fail;
+ } else {
+ if (vec->o->length != PyArray_SIZE (array)) {
+ PyErr_Format (PyExc_ValueError,
+ "input array has length %d, but cvec has length %d",
+ (int)PyArray_SIZE (array), vec->o->length);
+ goto fail;
+ }
+ }
+
+ vec->o->norm = (smpl_t *) PyArray_GETPTR1 (array, 0);
+
+ } else {
+ PyErr_SetString (PyExc_ValueError, "can only accept array as input");
+ return 1;
+ }
+
+ Py_INCREF(array);
+ return 0;
+
+fail:
+ return 1;
+}
+
+static int
+Py_cvec_set_phas (Py_cvec * vec, PyObject *input, void * closure)
+{
+ PyArrayObject * array;
+ if (input == NULL) {
+ PyErr_SetString (PyExc_ValueError, "input array is not a python object");
+ goto fail;
+ }
+ if (PyArray_Check(input)) {
+
+ // we got an array, convert it to a cvec.phas
+ if (PyArray_NDIM ((PyArrayObject *)input) == 0) {
+ PyErr_SetString (PyExc_ValueError, "input array is a scalar");
+ goto fail;
+ } else if (PyArray_NDIM ((PyArrayObject *)input) > 2) {
+ PyErr_SetString (PyExc_ValueError,
+ "input array has more than two dimensions");
+ goto fail;
+ }
+
+ if (!PyArray_ISFLOAT ((PyArrayObject *)input)) {
+ PyErr_SetString (PyExc_ValueError, "input array should be float");
+ goto fail;
+ } else if (PyArray_TYPE ((PyArrayObject *)input) != AUBIO_NPY_SMPL) {
+ PyErr_SetString (PyExc_ValueError, "input array should be float32");
+ goto fail;
+ }
+ array = (PyArrayObject *)input;
+
+ // check input array dimensions
+ if (PyArray_NDIM (array) != 1) {
+ PyErr_Format (PyExc_ValueError,
+ "input array has %d dimensions, not 1",
+ PyArray_NDIM (array));
+ goto fail;
+ } else {
+ if (vec->o->length != PyArray_SIZE (array)) {
+ PyErr_Format (PyExc_ValueError,
+ "input array has length %d, but cvec has length %d",
+ (int)PyArray_SIZE (array), vec->o->length);
+ goto fail;
+ }
+ }
+
+ vec->o->phas = (smpl_t *) PyArray_GETPTR1 (array, 0);
+
+ } else {
+ PyErr_SetString (PyExc_ValueError, "can only accept array as input");
+ return 1;
+ }
+
+ Py_INCREF(array);
+ return 0;
+
+fail:
+ return 1;
+}
+
+static PyMemberDef Py_cvec_members[] = {
+ // TODO remove READONLY flag and define getter/setter
+ {"length", T_INT, offsetof (Py_cvec, length), READONLY,
+ "length attribute"},
+ {NULL} /* Sentinel */
+};
+
+static PyMethodDef Py_cvec_methods[] = {
+ {NULL}
+};
+
+static PyGetSetDef Py_cvec_getseters[] = {
+ {"norm", (getter)Py_cvec_get_norm, (setter)Py_cvec_set_norm,
+ "Numpy vector of shape (length,) containing the magnitude",
+ NULL},
+ {"phas", (getter)Py_cvec_get_phas, (setter)Py_cvec_set_phas,
+ "Numpy vector of shape (length,) containing the phase",
+ NULL},
+ {NULL} /* sentinel */
+};
+
+PyTypeObject Py_cvecType = {
+ PyObject_HEAD_INIT (NULL)
+ 0, /* ob_size */
+ "aubio.cvec", /* tp_name */
+ sizeof (Py_cvec), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ (destructor) Py_cvec_del, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ (reprfunc) Py_cvec_repr, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, //&Py_cvec_tp_as_sequence, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ 0, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT, /* tp_flags */
+ Py_cvec_doc, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ Py_cvec_methods, /* tp_methods */
+ Py_cvec_members, /* tp_members */
+ Py_cvec_getseters, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ (initproc) Py_cvec_init, /* tp_init */
+ 0, /* tp_alloc */
+ Py_cvec_new, /* tp_new */
+};
--- /dev/null
+++ b/python/py-fft.c
@@ -1,0 +1,107 @@
+#include "aubiowraphell.h"
+
+static char Py_fft_doc[] = "fft object";
+
+AUBIO_DECLARE(fft, uint_t win_s)
+
+//AUBIO_NEW(fft)
+static PyObject *
+Py_fft_new (PyTypeObject * type, PyObject * args, PyObject * kwds)
+{
+ int win_s = 0;
+ Py_fft *self;
+ static char *kwlist[] = { "win_s", NULL };
+
+ if (!PyArg_ParseTupleAndKeywords (args, kwds, "|I", kwlist,
+ &win_s)) {
+ return NULL;
+ }
+
+ self = (Py_fft *) type->tp_alloc (type, 0);
+
+ if (self == NULL) {
+ return NULL;
+ }
+
+ self->win_s = Py_default_vector_length;
+
+ if (self == NULL) {
+ return NULL;
+ }
+
+ if (win_s > 0) {
+ self->win_s = win_s;
+ } else if (win_s < 0) {
+ PyErr_SetString (PyExc_ValueError,
+ "can not use negative window size");
+ return NULL;
+ }
+
+ return (PyObject *) self;
+}
+
+
+AUBIO_INIT(fft, self->win_s)
+
+AUBIO_DEL(fft)
+
+static PyObject *
+Py_fft_do(PyObject * self, PyObject * args)
+{
+ PyObject *input;
+ fvec_t *vec;
+ cvec_t *output;
+
+ if (!PyArg_ParseTuple (args, "O", &input)) {
+ return NULL;
+ }
+
+ vec = PyAubio_ArrayToCFvec (input);
+
+ if (vec == NULL) {
+ return NULL;
+ }
+
+ output = new_cvec(((Py_fft *) self)->win_s);
+
+ // compute the function
+ aubio_fft_do (((Py_fft *)self)->o, vec, output);
+ return (PyObject *)PyAubio_CCvecToPyCvec(output);
+}
+
+AUBIO_MEMBERS_START(fft)
+ {"win_s", T_INT, offsetof (Py_fft, win_s), READONLY,
+ "size of the window"},
+AUBIO_MEMBERS_STOP(fft)
+
+static PyObject *
+Py_fft_rdo(Py_fft * self, PyObject * args)
+{
+ PyObject *input;
+ cvec_t *vec;
+ fvec_t *output;
+
+ if (!PyArg_ParseTuple (args, "O", &input)) {
+ return NULL;
+ }
+
+ vec = PyAubio_ArrayToCCvec (input);
+
+ if (vec == NULL) {
+ return NULL;
+ }
+
+ output = new_fvec(self->win_s);
+
+ // compute the function
+ aubio_fft_rdo (((Py_fft *)self)->o, vec, output);
+ return (PyObject *)PyAubio_CFvecToArray(output);
+}
+
+static PyMethodDef Py_fft_methods[] = {
+ {"rdo", (PyCFunction) Py_fft_rdo, METH_VARARGS,
+ "synthesis of spectral grain"},
+ {NULL}
+};
+
+AUBIO_TYPEOBJECT(fft, "aubio.fft")
--- /dev/null
+++ b/python/py-filter.c
@@ -1,0 +1,198 @@
+#include "aubio-types.h"
+
+typedef struct
+{
+ PyObject_HEAD
+ aubio_filter_t * o;
+ uint_t order;
+} Py_filter;
+
+static char Py_filter_doc[] = "filter object";
+
+static PyObject *
+Py_filter_new (PyTypeObject * type, PyObject * args, PyObject * kwds)
+{
+ int order= 0;
+ Py_filter *self;
+ static char *kwlist[] = { "order", NULL };
+
+ if (!PyArg_ParseTupleAndKeywords (args, kwds, "|I", kwlist,
+ &order)) {
+ return NULL;
+ }
+
+ self = (Py_filter *) type->tp_alloc (type, 0);
+
+ if (self == NULL) {
+ return NULL;
+ }
+
+ self->order = 7;
+
+ if (order > 0) {
+ self->order = order;
+ } else if (order < 0) {
+ PyErr_SetString (PyExc_ValueError,
+ "can not use negative order");
+ return NULL;
+ }
+
+ return (PyObject *) self;
+}
+
+static int
+Py_filter_init (Py_filter * self, PyObject * args, PyObject * kwds)
+{
+ self->o = new_aubio_filter (self->order);
+ if (self->o == NULL) {
+ return -1;
+ }
+
+ return 0;
+}
+
+static void
+Py_filter_del (Py_filter * self)
+{
+ del_aubio_filter (self->o);
+ self->ob_type->tp_free ((PyObject *) self);
+}
+
+static PyObject *
+Py_filter_do(Py_filter * self, PyObject * args)
+{
+ PyObject *input;
+ fvec_t *vec;
+
+ if (!PyArg_ParseTuple (args, "O:digital_filter.do", &input)) {
+ return NULL;
+ }
+
+ if (input == NULL) {
+ return NULL;
+ }
+
+ vec = PyAubio_ArrayToCFvec (input);
+
+ if (vec == NULL) {
+ return NULL;
+ }
+
+ // compute the function
+ fvec_t * out = new_fvec(vec->length);
+ aubio_filter_do_outplace (self->o, vec, out);
+ return PyAubio_CFvecToArray(out);
+}
+
+static PyObject *
+Py_filter_set_c_weighting (Py_filter * self, PyObject *args)
+{
+ uint_t err = 0;
+ uint_t samplerate;
+ if (!PyArg_ParseTuple (args, "I", &samplerate)) {
+ return NULL;
+ }
+
+ err = aubio_filter_set_c_weighting (self->o, samplerate);
+ if (err > 0) {
+ PyErr_SetString (PyExc_ValueError,
+ "error when setting filter to C-weighting");
+ return NULL;
+ }
+ return Py_None;
+}
+
+static PyObject *
+Py_filter_set_a_weighting (Py_filter * self, PyObject *args)
+{
+ uint_t err = 0;
+ uint_t samplerate;
+ if (!PyArg_ParseTuple (args, "I", &samplerate)) {
+ return NULL;
+ }
+
+ err = aubio_filter_set_a_weighting (self->o, samplerate);
+ if (err > 0) {
+ PyErr_SetString (PyExc_ValueError,
+ "error when setting filter to A-weighting");
+ return NULL;
+ }
+ return Py_None;
+}
+
+static PyObject *
+Py_filter_set_biquad(Py_filter * self, PyObject *args)
+{
+ uint_t err = 0;
+ lsmp_t b0, b1, b2, a1, a2;
+ if (!PyArg_ParseTuple (args, "ddddd", &b0, &b1, &b2, &a1, &a2)) {
+ return NULL;
+ }
+
+ err = aubio_filter_set_biquad (self->o, b0, b1, b2, a1, a2);
+ if (err > 0) {
+ PyErr_SetString (PyExc_ValueError,
+ "error when setting filter with biquad coefficients");
+ return NULL;
+ }
+ return Py_None;
+}
+
+static PyMemberDef Py_filter_members[] = {
+ // TODO remove READONLY flag and define getter/setter
+ {"order", T_INT, offsetof (Py_filter, order), READONLY,
+ "order of the filter"},
+ {NULL} /* Sentinel */
+};
+
+static PyMethodDef Py_filter_methods[] = {
+ {"set_c_weighting", (PyCFunction) Py_filter_set_c_weighting, METH_VARARGS,
+ "set filter coefficients to C-weighting"},
+ {"set_a_weighting", (PyCFunction) Py_filter_set_a_weighting, METH_VARARGS,
+ "set filter coefficients to A-weighting"},
+ {"set_biquad", (PyCFunction) Py_filter_set_biquad, METH_VARARGS,
+ "set b0, b1, b2, a1, a2 biquad coefficients"},
+ {NULL}
+};
+
+PyTypeObject Py_filterType = {
+ PyObject_HEAD_INIT (NULL)
+ 0, /* ob_size */
+ "aubio.digital_filter", /* tp_name */
+ sizeof (Py_filter), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ (destructor) Py_filter_del, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ 0, //(reprfunc) Py_filter_repr, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ (ternaryfunc)Py_filter_do, /* tp_call */
+ 0, /* tp_str */
+ 0, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT, /* tp_flags */
+ Py_filter_doc, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ Py_filter_methods, /* tp_methods */
+ Py_filter_members, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ (initproc) Py_filter_init, /* tp_init */
+ 0, /* tp_alloc */
+ Py_filter_new, /* tp_new */
+};
--- /dev/null
+++ b/python/py-filterbank.c
@@ -1,0 +1,183 @@
+#include "aubiowraphell.h"
+
+static char Py_filterbank_doc[] = "filterbank object";
+
+AUBIO_DECLARE(filterbank, uint_t n_filters; uint_t win_s)
+
+//AUBIO_NEW(filterbank)
+static PyObject *
+Py_filterbank_new (PyTypeObject * type, PyObject * args, PyObject * kwds)
+{
+ int win_s = 0, n_filters = 0;
+ Py_filterbank *self;
+ static char *kwlist[] = { "n_filters", "win_s", NULL };
+
+ if (!PyArg_ParseTupleAndKeywords (args, kwds, "|II", kwlist,
+ &n_filters, &win_s)) {
+ return NULL;
+ }
+
+ self = (Py_filterbank *) type->tp_alloc (type, 0);
+
+ if (self == NULL) {
+ return NULL;
+ }
+
+ self->win_s = Py_default_vector_length;
+ if (win_s > 0) {
+ self->win_s = win_s;
+ } else if (win_s < 0) {
+ PyErr_SetString (PyExc_ValueError,
+ "can not use negative window size");
+ return NULL;
+ }
+
+ self->n_filters = 40;
+ if (n_filters > 0) {
+ self->n_filters = n_filters;
+ } else if (n_filters < 0) {
+ PyErr_SetString (PyExc_ValueError,
+ "can not use negative number of filters");
+ return NULL;
+ }
+
+ return (PyObject *) self;
+}
+
+
+AUBIO_INIT(filterbank, self->n_filters, self->win_s)
+
+AUBIO_DEL(filterbank)
+
+static PyObject *
+Py_filterbank_do(Py_filterbank * self, PyObject * args)
+{
+ PyObject *input;
+ cvec_t *vec;
+ fvec_t *out;
+
+ if (!PyArg_ParseTuple (args, "O", &input)) {
+ return NULL;
+ }
+
+ vec = PyAubio_ArrayToCCvec (input);
+
+ if (vec == NULL) {
+ return NULL;
+ }
+
+ out = new_fvec (self->n_filters);
+
+ // compute the function
+ aubio_filterbank_do (self->o, vec, out);
+ return (PyObject *)PyAubio_CFvecToArray(out);
+}
+
+AUBIO_MEMBERS_START(filterbank)
+ {"win_s", T_INT, offsetof (Py_filterbank, win_s), READONLY,
+ "size of the window"},
+ {"n_filters", T_INT, offsetof (Py_filterbank, n_filters), READONLY,
+ "number of filters"},
+AUBIO_MEMBERS_STOP(filterbank)
+
+static PyObject *
+Py_filterbank_set_triangle_bands (Py_filterbank * self, PyObject *args)
+{
+ uint_t err = 0;
+
+ PyObject *input;
+ uint_t samplerate;
+ fvec_t *freqs;
+ if (!PyArg_ParseTuple (args, "OI", &input, &samplerate)) {
+ return NULL;
+ }
+
+ if (input == NULL) {
+ return NULL;
+ }
+
+ freqs = PyAubio_ArrayToCFvec (input);
+
+ if (freqs == NULL) {
+ return NULL;
+ }
+
+ err = aubio_filterbank_set_triangle_bands (self->o,
+ freqs, samplerate);
+ if (err > 0) {
+ PyErr_SetString (PyExc_ValueError,
+ "error when setting filter to A-weighting");
+ return NULL;
+ }
+ return Py_None;
+}
+
+static PyObject *
+Py_filterbank_set_mel_coeffs_slaney (Py_filterbank * self, PyObject *args)
+{
+ uint_t err = 0;
+
+ uint_t samplerate;
+ if (!PyArg_ParseTuple (args, "I", &samplerate)) {
+ return NULL;
+ }
+
+ err = aubio_filterbank_set_mel_coeffs_slaney (self->o, samplerate);
+ if (err > 0) {
+ PyErr_SetString (PyExc_ValueError,
+ "error when setting filter to A-weighting");
+ return NULL;
+ }
+ return Py_None;
+}
+
+static PyObject *
+Py_filterbank_set_coeffs (Py_filterbank * self, PyObject *args)
+{
+ uint_t err = 0;
+
+ PyObject *input;
+ fmat_t *coeffs;
+
+ if (!PyArg_ParseTuple (args, "O", &input)) {
+ return NULL;
+ }
+
+ coeffs = PyAubio_ArrayToCFmat (input);
+
+ if (coeffs == NULL) {
+ PyErr_SetString (PyExc_ValueError,
+ "unable to parse input array");
+ return NULL;
+ }
+
+ err = aubio_filterbank_set_coeffs (self->o, coeffs);
+
+ if (err > 0) {
+ PyErr_SetString (PyExc_ValueError,
+ "error when setting filter coefficients");
+ return NULL;
+ }
+ return Py_None;
+}
+
+static PyObject *
+Py_filterbank_get_coeffs (Py_filterbank * self, PyObject *unused)
+{
+ return (PyObject *)PyAubio_CFmatToArray(
+ aubio_filterbank_get_coeffs (self->o) );
+}
+
+static PyMethodDef Py_filterbank_methods[] = {
+ {"set_triangle_bands", (PyCFunction) Py_filterbank_set_triangle_bands,
+ METH_VARARGS, "set coefficients of filterbanks"},
+ {"set_mel_coeffs_slaney", (PyCFunction) Py_filterbank_set_mel_coeffs_slaney,
+ METH_VARARGS, "set coefficients of filterbank as in Auditory Toolbox"},
+ {"get_coeffs", (PyCFunction) Py_filterbank_get_coeffs,
+ METH_NOARGS, "get coefficients of filterbank"},
+ {"set_coeffs", (PyCFunction) Py_filterbank_set_coeffs,
+ METH_VARARGS, "set coefficients of filterbank"},
+ {NULL}
+};
+
+AUBIO_TYPEOBJECT(filterbank, "aubio.filterbank")
--- /dev/null
+++ b/python/py-phasevoc.c
@@ -1,0 +1,118 @@
+#include "aubiowraphell.h"
+
+static char Py_pvoc_doc[] = "pvoc object";
+
+AUBIO_DECLARE(pvoc, uint_t win_s; uint_t hop_s)
+
+//AUBIO_NEW(pvoc)
+static PyObject *
+Py_pvoc_new (PyTypeObject * type, PyObject * args, PyObject * kwds)
+{
+ int win_s = 0, hop_s = 0;
+ Py_pvoc *self;
+ static char *kwlist[] = { "win_s", "hop_s", NULL };
+
+ if (!PyArg_ParseTupleAndKeywords (args, kwds, "|II", kwlist,
+ &win_s, &hop_s)) {
+ return NULL;
+ }
+
+ self = (Py_pvoc *) type->tp_alloc (type, 0);
+
+ if (self == NULL) {
+ return NULL;
+ }
+
+ self->win_s = Py_default_vector_length;
+ self->hop_s = Py_default_vector_length/2;
+
+ if (self == NULL) {
+ return NULL;
+ }
+
+ if (win_s > 0) {
+ self->win_s = win_s;
+ } else if (win_s < 0) {
+ PyErr_SetString (PyExc_ValueError,
+ "can not use negative window size");
+ return NULL;
+ }
+
+ if (hop_s > 0) {
+ self->hop_s = hop_s;
+ } else if (hop_s < 0) {
+ PyErr_SetString (PyExc_ValueError,
+ "can not use negative hop size");
+ return NULL;
+ }
+
+ return (PyObject *) self;
+}
+
+
+AUBIO_INIT(pvoc, self->win_s, self->hop_s)
+
+AUBIO_DEL(pvoc)
+
+static PyObject *
+Py_pvoc_do(Py_pvoc * self, PyObject * args)
+{
+ PyObject *input;
+ fvec_t *vec;
+ cvec_t *output;
+
+ if (!PyArg_ParseTuple (args, "O", &input)) {
+ return NULL;
+ }
+
+ vec = PyAubio_ArrayToCFvec (input);
+
+ if (vec == NULL) {
+ return NULL;
+ }
+
+ output = new_cvec(self->win_s);
+
+ // compute the function
+ aubio_pvoc_do (self->o, vec, output);
+ return (PyObject *)PyAubio_CCvecToPyCvec(output);
+}
+
+AUBIO_MEMBERS_START(pvoc)
+ {"win_s", T_INT, offsetof (Py_pvoc, win_s), READONLY,
+ "size of the window"},
+ {"hop_s", T_INT, offsetof (Py_pvoc, hop_s), READONLY,
+ "size of the hop"},
+AUBIO_MEMBERS_STOP(pvoc)
+
+static PyObject *
+Py_pvoc_rdo(Py_pvoc * self, PyObject * args)
+{
+ PyObject *input;
+ cvec_t *vec;
+ fvec_t *output;
+
+ if (!PyArg_ParseTuple (args, "O", &input)) {
+ return NULL;
+ }
+
+ vec = PyAubio_ArrayToCCvec (input);
+
+ if (vec == NULL) {
+ return NULL;
+ }
+
+ output = new_fvec(self->hop_s);
+
+ // compute the function
+ aubio_pvoc_rdo (self->o, vec, output);
+ return (PyObject *)PyAubio_CFvecToArray(output);
+}
+
+static PyMethodDef Py_pvoc_methods[] = {
+ {"rdo", (PyCFunction) Py_pvoc_rdo, METH_VARARGS,
+ "synthesis of spectral grain"},
+ {NULL}
+};
+
+AUBIO_TYPEOBJECT(pvoc, "aubio.pvoc")
--- /dev/null
+++ b/python/run_all_tests
@@ -1,0 +1,20 @@
+#! /usr/bin/env python
+
+if __name__ == '__main__':
+ import os, sys, unittest
+ def load_test():
+ # get relevant files
+ curdir = os.path.dirname(sys.argv[0])
+ if curdir == '': curdir = '.'
+ files = os.listdir(os.path.join(curdir, 'tests'))
+ modfiles = filter (lambda y: y.endswith('.py'), files)
+ modfiles = filter (lambda f: f.startswith('test_'), modfiles)
+ # get module names
+ modnames = map (lambda x: os.path.splitext(x)[0], modfiles)
+ # import them
+ modules = map (__import__, modnames)
+ # create a test suites from the imported module
+ load_from_module = unittest.defaultTestLoader.loadTestsFromModule
+ tests = map(load_from_module, modules)
+ return unittest.TestSuite(tests)
+ unittest.main(defaultTest = 'load_test')
--- /dev/null
+++ b/python/setup.py
@@ -1,0 +1,41 @@
+#! /usr/bin/python
+
+from distutils.core import setup, Extension
+from generator import generate_object_files
+import os.path
+import numpy
+
+library_dirs = ['../build/src', '../src/.libs']
+include_dirs = ['../build/src', '../src', '.' ]
+library_dirs = filter (lambda x: os.path.isdir(x), library_dirs)
+include_dirs = filter (lambda x: os.path.isdir(x), include_dirs)
+
+aubio_extension = Extension("_aubio",
+ ["aubiomodule.c",
+ "aubioproxy.c",
+ "py-cvec.c",
+ # example without macro
+ "py-filter.c",
+ # macroised
+ "py-filterbank.c",
+ "py-fft.c",
+ "py-phasevoc.c",
+ # generated files
+ ] + generate_object_files(),
+ include_dirs = include_dirs + [ numpy.get_include() ],
+ library_dirs = library_dirs,
+ libraries=['aubio'])
+
+setup(name='aubio',
+ version = '0.4.0alpha',
+ packages = ['aubio'],
+ description = 'interface to the aubio library',
+ long_description = 'interface to the aubio library',
+ license = 'GNU/GPL version 3',
+ author = 'Paul Brossier',
+ author_email = 'piem@aubio.org',
+ maintainer = 'Paul Brossier',
+ maintainer_email = 'piem@aubio.org',
+ url = 'http://aubio.org/',
+ ext_modules = [aubio_extension])
+
--- /dev/null
+++ b/python/tests/test_aubio.py
@@ -1,0 +1,14 @@
+#! /usr/bin/env python
+
+from numpy.testing import TestCase, run_module_suite
+
+class aubiomodule_test_case(TestCase):
+
+ def test_import(self):
+ """ try importing aubio """
+ import aubio
+
+if __name__ == '__main__':
+ from unittest import main
+ main()
+
--- /dev/null
+++ b/python/tests/test_cvec.py
@@ -1,0 +1,50 @@
+from numpy.testing import TestCase, run_module_suite
+from numpy.testing import assert_equal, assert_almost_equal
+from aubio import cvec
+from numpy import array, shape, pi
+
+class aubio_cvec_test_case(TestCase):
+
+ def test_vector_created_with_zeroes(self):
+ a = cvec(10)
+ a
+ shape(a.norm)
+ shape(a.phas)
+ a.norm[0]
+ assert_equal(a.norm, 0.)
+ assert_equal(a.phas, 0.)
+
+ def test_vector_assign_element(self):
+ a = cvec()
+ a.norm[0] = 1
+ assert_equal(a.norm[0], 1)
+ a.phas[0] = 1
+ assert_equal(a.phas[0], 1)
+
+ def test_vector_assign_element_end(self):
+ a = cvec()
+ a.norm[-1] = 1
+ assert_equal(a.norm[-1], 1)
+ assert_equal(a.norm[len(a.norm)-1], 1)
+ a.phas[-1] = 1
+ assert_equal(a.phas[-1], 1)
+ assert_equal(a.phas[len(a.phas)-1], 1)
+
+ def test_assign_cvec_norm_slice(self):
+ spec = cvec(1024)
+ spec.norm[40:100] = 100
+ assert_equal (spec.norm[0:40], 0)
+ assert_equal (spec.norm[40:100], 100)
+ assert_equal (spec.norm[100:-1], 0)
+ assert_equal (spec.phas, 0)
+
+ def test_assign_cvec_phas_slice(self):
+ spec = cvec(1024)
+ spec.phas[39:-1] = -pi
+ assert_equal (spec.phas[0:39], 0)
+ assert_equal (spec.phas[39:-1], -pi)
+ assert_equal (spec.norm, 0)
+
+if __name__ == '__main__':
+ from unittest import main
+ main()
--- /dev/null
+++ b/python/tests/test_fft.py
@@ -1,0 +1,113 @@
+#! /usr/bin/env python
+
+from numpy.testing import TestCase, run_module_suite
+from numpy.testing import assert_equal, assert_almost_equal
+# WARNING: numpy also has an fft object
+from aubio import fvec, fft, cvec
+from numpy import array, shape
+from math import pi
+
+class aubio_fft_test_case(TestCase):
+
+ def test_members(self):
+ f = fft()
+ assert_equal (f.win_s, 1024)
+
+ def test_output_dimensions(self):
+ """ check the dimensions of output """
+ win_s = 1024
+ timegrain = fvec(win_s)
+ f = fft(win_s)
+ fftgrain = f (timegrain)
+ assert_equal (fftgrain.norm, 0)
+ assert_equal (shape(fftgrain.norm), (win_s/2+1,))
+ assert_equal (fftgrain.phas, 0)
+ assert_equal (shape(fftgrain.phas), (win_s/2+1,))
+
+ def test_zeros(self):
+ """ check the transform of zeros """
+ win_s = 512
+ timegrain = fvec(win_s)
+ f = fft(win_s)
+ fftgrain = f(timegrain)
+ assert_equal ( fftgrain.norm == 0, True )
+ assert_equal ( fftgrain.phas == 0, True )
+
+ def test_impulse(self):
+ """ check the transform of one impulse at a random place """
+ from random import random
+ from math import floor
+ win_s = 256
+ i = floor(random()*win_s)
+ impulse = pi * random()
+ f = fft(win_s)
+ timegrain = fvec(win_s)
+ timegrain[i] = impulse
+ fftgrain = f ( timegrain )
+ #self.plot_this ( fftgrain.phas )
+ assert_almost_equal ( fftgrain.norm, impulse, decimal = 6 )
+ assert_equal ( fftgrain.phas <= pi, True)
+ assert_equal ( fftgrain.phas >= -pi, True)
+
+ def test_impulse_negative(self):
+ """ check the transform of one impulse at a random place """
+ from random import random
+ from math import floor
+ win_s = 256
+ i = 0
+ impulse = -10.
+ f = fft(win_s)
+ timegrain = fvec(win_s)
+ timegrain[i] = impulse
+ fftgrain = f ( timegrain )
+ #self.plot_this ( fftgrain.phas )
+ assert_almost_equal ( fftgrain.norm, abs(impulse), decimal = 6 )
+ if impulse < 0:
+ # phase can be pi or -pi, as it is not unwrapped
+ assert_almost_equal ( abs(fftgrain.phas[1:-1]) , pi, decimal = 6 )
+ assert_almost_equal ( fftgrain.phas[0], pi, decimal = 6)
+ assert_almost_equal ( fftgrain.phas[-1], pi, decimal = 6)
+ else:
+ assert_equal ( fftgrain.phas[1:-1] == 0, True)
+ assert_equal ( fftgrain.phas[0] == 0, True)
+ assert_equal ( fftgrain.phas[-1] == 0, True)
+ # now check the resynthesis
+ synthgrain = f.rdo ( fftgrain )
+ #self.plot_this ( fftgrain.phas.T )
+ assert_equal ( fftgrain.phas <= pi, True)
+ assert_equal ( fftgrain.phas >= -pi, True)
+ #self.plot_this ( synthgrain - timegrain )
+ assert_almost_equal ( synthgrain, timegrain, decimal = 6 )
+
+ def test_impulse_at_zero(self):
+ """ check the transform of one impulse at a index 0 """
+ win_s = 1024
+ impulse = pi
+ f = fft(win_s)
+ timegrain = fvec(win_s)
+ timegrain[0] = impulse
+ fftgrain = f ( timegrain )
+ #self.plot_this ( fftgrain.phas )
+ assert_equal ( fftgrain.phas[0], 0)
+ # could be 0 or -0 depending on fft implementation (0 for fftw3, -0 for ooura)
+ assert_almost_equal ( fftgrain.phas[1], 0)
+ assert_almost_equal ( fftgrain.norm[0], impulse, decimal = 6 )
+
+ def test_rdo_before_do(self):
+ """ check running fft.rdo before fft.do works """
+ win_s = 1024
+ impulse = pi
+ f = fft(win_s)
+ fftgrain = cvec(win_s)
+ t = f.rdo( fftgrain )
+ assert_equal ( t, 0 )
+
+ def plot_this(self, this):
+ from pylab import plot, show
+ plot ( this )
+ show ()
+
+if __name__ == '__main__':
+ from unittest import main
+ main()
+
--- /dev/null
+++ b/python/tests/test_filter.py
@@ -1,0 +1,68 @@
+#! /usr/bin/env python
+
+from numpy.testing import TestCase, assert_equal, assert_almost_equal
+from aubio import fvec, digital_filter
+from numpy import array
+
+def array_from_text_file(filename, dtype = 'float'):
+ return array([line.split() for line in open(filename).readlines()],
+ dtype = dtype)
+
+class aubio_filter_test_case(TestCase):
+
+ def test_members(self):
+ f = digital_filter()
+ assert_equal (f.order, 7)
+ f = digital_filter(5)
+ assert_equal (f.order, 5)
+ f(fvec())
+
+ def test_cweighting_error(self):
+ f = digital_filter (2)
+ self.assertRaises ( ValueError, f.set_c_weighting, 44100 )
+ f = digital_filter (8)
+ self.assertRaises ( ValueError, f.set_c_weighting, 44100 )
+ f = digital_filter (5)
+ self.assertRaises ( ValueError, f.set_c_weighting, 4000 )
+ f = digital_filter (5)
+ self.assertRaises ( ValueError, f.set_c_weighting, 193000 )
+ f = digital_filter (7)
+ self.assertRaises ( ValueError, f.set_a_weighting, 193000 )
+ f = digital_filter (5)
+ self.assertRaises ( ValueError, f.set_a_weighting, 192000 )
+
+ def test_c_weighting(self):
+ expected = array_from_text_file('c_weighting_test_simple.expected')
+ f = digital_filter(5)
+ f.set_c_weighting(44100)
+ v = fvec(32)
+ v[12] = .5
+ u = f(v)
+ assert_almost_equal (expected[1], u)
+
+ def test_a_weighting(self):
+ expected = array_from_text_file('a_weighting_test_simple.expected')
+ f = digital_filter(7)
+ f.set_a_weighting(44100)
+ v = fvec(32)
+ v[12] = .5
+ u = f(v)
+ assert_almost_equal (expected[1], u)
+
+ def test_a_weighting_parted(self):
+ expected = array_from_text_file('a_weighting_test_simple.expected')
+ f = digital_filter(7)
+ f.set_a_weighting(44100)
+ v = fvec(16)
+ v[12] = .5
+ u = f(v)
+ assert_almost_equal (expected[1][:16], u)
+ # one more time
+ v = fvec(16)
+ u = f(v)
+ assert_almost_equal (expected[1][16:], u)
+
+if __name__ == '__main__':
+ from unittest import main
+ main()
+
--- /dev/null
+++ b/python/tests/test_filterbank.py
@@ -1,0 +1,23 @@
+#! /usr/bin/env python
+
+from numpy.testing import TestCase, run_module_suite
+from numpy.testing import assert_equal, assert_almost_equal
+from numpy import random
+from aubio import cvec, filterbank
+
+class aubio_filterbank_test_case(TestCase):
+
+ def test_members(self):
+ f = filterbank(40, 512)
+ assert_equal ([f.n_filters, f.win_s], [40, 512])
+
+ def test_set_coeffs(self):
+ f = filterbank(40, 512)
+ r = random.random([40, 512 / 2 + 1]).astype('float32')
+ f.set_coeffs(r)
+ assert_equal (r, f.get_coeffs())
+
+if __name__ == '__main__':
+ from unittest import main
+ main()
+
--- /dev/null
+++ b/python/tests/test_filterbank_mel.py
@@ -1,0 +1,51 @@
+#! /usr/bin/env python
+
+from numpy.testing import TestCase, run_module_suite
+from numpy.testing import assert_equal, assert_almost_equal
+from numpy import array, shape
+from aubio import cvec, filterbank
+
+class aubio_filterbank_mel_test_case(TestCase):
+
+ def test_slaney(self):
+ f = filterbank(40, 512)
+ f.set_mel_coeffs_slaney(16000)
+ a = f.get_coeffs()
+ assert_equal(shape (a), (40, 512/2 + 1) )
+
+ def test_other_slaney(self):
+ f = filterbank(40, 512*2)
+ f.set_mel_coeffs_slaney(44100)
+ a = f.get_coeffs()
+ #print "sum is", sum(sum(a))
+ for win_s in [256, 512, 1024, 2048, 4096]:
+ f = filterbank(40, win_s)
+ f.set_mel_coeffs_slaney(320000)
+ a = f.get_coeffs()
+ #print "sum is", sum(sum(a))
+
+ def test_triangle_freqs_zeros(self):
+ f = filterbank(9, 1024)
+ freq_list = [40, 80, 200, 400, 800, 1600, 3200, 6400, 12800, 15000, 24000]
+ freqs = array(freq_list, dtype = 'float32')
+ f.set_triangle_bands(freqs, 48000)
+ f.get_coeffs().T
+ assert_equal ( f(cvec(1024)), 0)
+
+ def test_triangle_freqs_ones(self):
+ f = filterbank(9, 1024)
+ freq_list = [40, 80, 200, 400, 800, 1600, 3200, 6400, 12800, 15000, 24000]
+ freqs = array(freq_list, dtype = 'float32')
+ f.set_triangle_bands(freqs, 48000)
+ f.get_coeffs().T
+ spec = cvec(1024)
+ spec.norm[:] = 1
+ assert_almost_equal ( f(spec),
+ [ 0.02070313, 0.02138672, 0.02127604, 0.02135417,
+ 0.02133301, 0.02133301, 0.02133311, 0.02133334, 0.02133345])
+
+if __name__ == '__main__':
+ from unittest import main
+ main()
+
+
--- /dev/null
+++ b/python/tests/test_fvec.py
@@ -1,0 +1,135 @@
+#! /usr/bin/env python
+
+from numpy.testing import TestCase, run_module_suite
+from numpy.testing import assert_equal, assert_almost_equal
+from aubio import fvec, zero_crossing_rate, alpha_norm, min_removal
+from numpy import array, shape
+
+class aubio_fvec_test_case(TestCase):
+
+ def test_vector_created_with_zeroes(self):
+ a = fvec(10)
+ a
+ shape(a)
+ a[0]
+ #del a
+ assert_equal(array(a), 0.)
+
+ def test_vector_create_with_list(self):
+ a = fvec([0,1,2,3])
+ assert_equal (range(4), a)
+
+ def test_vector_assign_element(self):
+ a = fvec()
+ a[0] = 1
+ assert_equal(a[0], 1)
+
+ def test_vector_assign_element_end(self):
+ a = fvec()
+ a[-1] = 1
+ assert_equal(a[-1], 1)
+ assert_equal(a[len(a)-1], 1)
+
+ def test_vector(self):
+ a = fvec()
+ a, len(a) #a.length
+ a[0]
+ array(a)
+ a = fvec(10)
+ a = fvec(1)
+ a.T
+ array(a).T
+ a = range(len(a))
+
+ def test_wrong_values(self):
+ self.assertRaises (ValueError, fvec, -10)
+
+ a = fvec(2)
+ self.assertRaises (IndexError, a.__getitem__, 3)
+ self.assertRaises (IndexError, a.__getitem__, 2)
+
+ def test_alpha_norm_of_fvec(self):
+ a = fvec(2)
+ self.assertEquals (alpha_norm(a, 1), 0)
+ a[0] = 1
+ self.assertEquals (alpha_norm(a, 1), 0.5)
+ a[1] = 1
+ self.assertEquals (alpha_norm(a, 1), 1)
+ a = array([0, 1], dtype='float32')
+ from math import sqrt
+ assert_almost_equal (alpha_norm(a, 2), sqrt(2)/2.)
+
+ def test_alpha_norm_of_none(self):
+ self.assertRaises (ValueError, alpha_norm, None, 1)
+
+ def test_alpha_norm_of_array_of_float32(self):
+ # check scalar fails
+ a = array(1, dtype = 'float32')
+ self.assertRaises (ValueError, alpha_norm, a, 1)
+ # check 2d array fails
+ a = array([[2],[4]], dtype = 'float32')
+ self.assertRaises (ValueError, alpha_norm, a, 1)
+ # check 1d array
+ a = array(range(10), dtype = 'float32')
+ self.assertEquals (alpha_norm(a, 1), 4.5)
+
+ def test_alpha_norm_of_array_of_int(self):
+ a = array(1, dtype = 'int')
+ self.assertRaises (ValueError, alpha_norm, a, 1)
+ a = array([[[1,2],[3,4]]], dtype = 'int')
+ self.assertRaises (ValueError, alpha_norm, a, 1)
+ a = array(range(10), dtype = 'int')
+ self.assertRaises (ValueError, alpha_norm, a, 1)
+
+ def test_alpha_norm_of_array_of_string (self):
+ a = "hello"
+ self.assertRaises (ValueError, alpha_norm, a, 1)
+
+ def test_zero_crossing_rate(self):
+ a = array([0,1,-1], dtype='float32')
+ assert_almost_equal (zero_crossing_rate(a), 1./3. )
+ a = array([0.]*100, dtype='float32')
+ self.assertEquals (zero_crossing_rate(a), 0 )
+ a = array([-1.]*100, dtype='float32')
+ self.assertEquals (zero_crossing_rate(a), 0 )
+ a = array([1.]*100, dtype='float32')
+ self.assertEquals (zero_crossing_rate(a), 0 )
+
+ def test_alpha_norm_of_array_of_float64(self):
+ # check scalar fail
+ a = array(1, dtype = 'float64')
+ self.assertRaises (ValueError, alpha_norm, a, 1)
+ # check 3d array fail
+ a = array([[[1,2],[3,4]]], dtype = 'float64')
+ self.assertRaises (ValueError, alpha_norm, a, 1)
+ # check float64 1d array fail
+ a = array(range(10), dtype = 'float64')
+ self.assertRaises (ValueError, alpha_norm, a, 1)
+ # check float64 2d array fail
+ a = array([range(10), range(10)], dtype = 'float64')
+ self.assertRaises (ValueError, alpha_norm, a, 1)
+
+ def test_fvec_min_removal_of_array(self):
+ a = array([20,1,19], dtype='float32')
+ b = min_removal(a)
+ assert_equal (array(b), [19, 0, 18])
+ assert_equal (b, [19, 0, 18])
+ assert_equal (a, b)
+ a[0] = 0
+ assert_equal (a, b)
+
+ def test_fvec_min_removal_of_array_float64(self):
+ a = array([20,1,19], dtype='float64')
+ self.assertRaises (ValueError, min_removal, a)
+
+ def test_fvec_min_removal_of_fvec(self):
+ a = fvec(3)
+ a = array([20, 1, 19], dtype = 'float32')
+ b = min_removal(a)
+ assert_equal (array(b), [19, 0, 18])
+ assert_equal (b, [19, 0, 18])
+ assert_equal (a, b)
+
+if __name__ == '__main__':
+ from unittest import main
+ main()
--- /dev/null
+++ b/python/tests/test_onset.py
@@ -1,0 +1,20 @@
+#! /usr/bin/env python
+
+from numpy.testing import TestCase, run_module_suite
+from numpy.testing import assert_equal, assert_almost_equal
+# WARNING: numpy also has an fft object
+from aubio import onset, cvec
+from numpy import array, shape, arange, zeros, log
+from math import pi
+
+class aubio_onset(TestCase):
+
+ def test_members(self):
+ o = onset()
+ assert_equal ([o.buf_size, o.hop_size, o.method, o.samplerate],
+ [1024,512,'default',44100])
+
+
+if __name__ == '__main__':
+ from unittest import main
+ main()
--- /dev/null
+++ b/python/tests/test_peakpicker.py
@@ -1,0 +1,115 @@
+#! /usr/bin/env python
+
+from numpy.testing import TestCase, assert_equal, assert_almost_equal
+from aubio import peakpicker, fvec
+
+class aubio_peakpicker(TestCase):
+
+ def test_members(self):
+ o = peakpicker()
+
+ def test_peakpicker_zeroes(self):
+ o = peakpicker()
+ assert_equal(o.get_thresholded_input(), 0.)
+
+ def test_peakpick_set_threshold(self):
+ o = peakpicker()
+ new_threshold = threshold
+ o.set_threshold(new_threshold)
+ assert_almost_equal(new_threshold, o.get_threshold())
+
+ def test_peakpicker_get_threshold(self):
+ o = peakpicker()
+ new_threshold = o.get_threshold()
+ o.set_threshold(new_threshold)
+ assert_equal(new_threshold, o.get_threshold())
+
+buf_size = 1024
+slice_size = 5
+delay = 1
+threshold = .9
+
+class aubio_peakpicker_peaks(TestCase):
+
+ def setUp(self):
+ self.o = peakpicker()
+ self.o.set_threshold (threshold)
+ self.vec = fvec(buf_size)
+
+ def test_peakpicker_impulse(self):
+ vec = self.vec; o = self.o
+ a = 345
+ vec[a] = 1000.
+ self.peaks = [a]
+
+ def test_peakpicker_ramp_up(self):
+ vec = self.vec; o = self.o
+ a = 345
+ vec[a] = 1000. / 4. * 1.
+ vec[a+1] = 1000. / 4. * 2.
+ vec[a+2] = 1000. / 4. * 3.
+ vec[a+3] = 1000.
+ self.peaks = [a+1]
+
+ def test_peakpicker_ramp_down(self):
+ vec = self.vec; o = self.o
+ a = 345
+ vec[a] = 1000.
+ vec[a+1] = 1000. / 4. * 3.
+ vec[a+2] = 1000. / 4. * 2.
+ vec[a+3] = 1000. / 4. * 1.
+ self.peaks = [a]
+
+ def test_peakpicker_plateau(self):
+ vec = self.vec; o = self.o
+ a = 345
+ vec[a] = 1000. / 2
+ vec[a+1] = 1000.
+ vec[a+2] = 1000.
+ vec[a+3] = 1000.
+ vec[a+4] = 1000. / 2
+ self.peaks = [a+1]
+
+ def test_peakpicker_consecutive_peaks(self):
+ vec = self.vec; o = self.o
+ a = 345
+ vec[a] = 1000. / 2
+ vec[a+1] = 1000.
+ vec[a+3] = 1000.
+ vec[a+4] = 1000. / 2
+ self.peaks = [a]
+
+ def test_peakpicker_distant_peaks(self):
+ vec = self.vec; o = self.o
+ a = 345
+ vec[a] = 1000.
+ vec[a+7] = 1000.
+ self.peaks = [a, a+7]
+
+ def test_peakpicker_very_distant_peaks(self):
+ vec = self.vec; o = self.o
+ a = 345
+ vec[a] = 1000.
+ vec[a+67] = 1000.
+ self.peaks = [a, a+67]
+
+ def tearDown(self):
+ fpeaks = []
+ for index in range(0,buf_size-slice_size):
+ sliced = self.vec[index:index+slice_size]
+ findex = self.o(sliced)
+ if findex:
+ # we found a peak
+ fpeak = index - findex - delay
+ #print self.peaks, index, '-', findex, '-', delay, '=', fpeak
+ if not round(index - findex - delay) in self.peaks:
+ self.fail('missing peak ' + str(fpeak))
+ fpeaks.append(fpeak)
+ if len(fpeaks) != len(self.peaks):
+ self.fail('some peaks of ' + str(self.peaks) + 'were not found, got only ' + str(fpeaks))
+ #print fpeaks, self.peaks
+
+if __name__ == '__main__':
+ from unittest import main
+ main()
--- /dev/null
+++ b/python/tests/test_phasevoc.py
@@ -1,0 +1,65 @@
+#! /usr/bin/env python
+
+from numpy.testing import TestCase, run_module_suite
+from numpy.testing import assert_equal, assert_almost_equal
+from aubio import fvec, cvec, pvoc
+from numpy import array, shape
+
+class aubio_pvoc_test_case(TestCase):
+
+ def test_members(self):
+ f = pvoc()
+ assert_equal ([f.win_s, f.hop_s], [1024, 512])
+ f = pvoc(2048, 128)
+ assert_equal ([f.win_s, f.hop_s], [2048, 128])
+
+ def test_zeros(self):
+ win_s, hop_s = 1024, 256
+ f = pvoc (win_s, hop_s)
+ t = fvec (hop_s)
+ for time in range( 4 * win_s / hop_s ):
+ s = f(t)
+ r = f.rdo(s)
+ assert_equal ( array(t), 0)
+ assert_equal ( s.norm, 0)
+ assert_equal ( s.phas, 0)
+ assert_equal ( r, 0)
+
+ def test_steps_two_channels(self):
+ """ check the resynthesis of steps is correct """
+ f = pvoc(1024, 512)
+ t1 = fvec(512)
+ t2 = fvec(512)
+ # positive step in first channel
+ t1[100:200] = .1
+ # positive step in second channel
+ t1[20:50] = -.1
+ s1 = f(t1)
+ r1 = f.rdo(s1)
+ s2 = f(t2)
+ r2 = f.rdo(s2)
+ #self.plot_this ( s1.norm.T )
+ assert_almost_equal ( t1, r2, decimal = 6 )
+
+ def test_steps_three_random_channels(self):
+ from random import random
+ f = pvoc(64, 16)
+ t0 = fvec(16)
+ t1 = fvec(16)
+ for i in xrange(16):
+ t1[i] = random() * 2. - 1.
+ t2 = f.rdo(f(t1))
+ t2 = f.rdo(f(t0))
+ t2 = f.rdo(f(t0))
+ t2 = f.rdo(f(t0))
+ assert_almost_equal( t1, t2, decimal = 6 )
+
+ def plot_this( self, this ):
+ from pylab import semilogy, show
+ semilogy ( this )
+ show ()
+
+if __name__ == '__main__':
+ from unittest import main
+ main()
+
--- /dev/null
+++ b/python/tests/test_pitch.py
@@ -1,0 +1,101 @@
+#! /usr/bin/env python
+
+from numpy.testing import TestCase
+from numpy.testing import assert_equal, assert_almost_equal
+from numpy import random, sin, arange, mean, median
+from math import pi
+from aubio import fvec, pitch
+
+class aubio_mathutils_test_case(TestCase):
+
+ def test_members(self):
+ p = pitch()
+ assert_equal ( [p.method, p.buf_size, p.hop_size, p.samplerate],
+ ['default', 1024, 512, 44100])
+
+ def test_members_not_default(self):
+ p = pitch('mcomb', 2048, 512, 32000)
+ assert_equal ( [p.method, p.buf_size, p.hop_size, p.samplerate],
+ ['mcomb', 2048, 512, 32000])
+
+ def test_run_on_zeros(self):
+ p = pitch('mcomb', 2048, 512, 32000)
+ f = fvec (512)
+ assert_equal ( p(f), 0. )
+
+ def test_run_on_ones(self):
+ p = pitch('mcomb', 2048, 512, 32000)
+ f = fvec (512)
+ f[:] = 1
+ assert( p(f) != 0. )
+
+ def test_run_default_on_sinusoid(self):
+ method = 'default'
+ buf_size = 2048
+ hop_size = 512
+ samplerate = 32000
+ freq = 450.
+ self.run_pitch_on_sinusoid(method, buf_size, hop_size, samplerate, freq)
+
+ def test_run_schmitt_on_sinusoid(self):
+ method = 'schmitt'
+ buf_size = 4096
+ hop_size = 512
+ samplerate = 44100
+ freq = 800.
+ self.run_pitch_on_sinusoid(method, buf_size, hop_size, samplerate, freq)
+
+ def test_run_mcomb_on_sinusoid(self):
+ method = 'mcomb'
+ buf_size = 2048
+ hop_size = 512
+ samplerate = 44100
+ freq = 10000.
+ self.run_pitch_on_sinusoid(method, buf_size, hop_size, samplerate, freq)
+
+ def test_run_fcomb_on_sinusoid(self):
+ method = 'fcomb'
+ buf_size = 2048
+ hop_size = 512
+ samplerate = 32000
+ freq = 440.
+ self.run_pitch_on_sinusoid(method, buf_size, hop_size, samplerate, freq)
+
+ def test_run_yin_on_sinusoid(self):
+ method = 'yin'
+ buf_size = 4096
+ hop_size = 512
+ samplerate = 32000
+ freq = 880.
+ self.run_pitch_on_sinusoid(method, buf_size, hop_size, samplerate, freq)
+
+ def test_run_yinfft_on_sinusoid(self):
+ method = 'yinfft'
+ buf_size = 2048
+ hop_size = 512
+ samplerate = 32000
+ freq = 640.
+ self.run_pitch_on_sinusoid(method, buf_size, hop_size, samplerate, freq)
+
+ def run_pitch_on_sinusoid(self, method, buf_size, hop_size, samplerate, freq):
+ p = pitch(method, buf_size, hop_size, samplerate)
+ sinvec = self.build_sinusoid(hop_size * 100, freq, samplerate)
+ self.run_pitch(p, sinvec, freq)
+
+ def build_sinusoid(self, length, freq, samplerate):
+ return sin( 2. * pi * arange(length).astype('float32') * freq / samplerate)
+
+ def run_pitch(self, p, input_vec, freq):
+ count = 0
+ pitches, errors = [], []
+ for vec_slice in input_vec.reshape((-1, p.hop_size)):
+ pitch = p(vec_slice)
+ pitches.append(pitch)
+ errors.append(1. - pitch / freq)
+ # check that the mean of all relative errors is less than 10%
+ assert_almost_equal (mean(errors), 0., decimal = 2)
+
+if __name__ == '__main__':
+ from unittest import main
+ main()
+
--- /dev/null
+++ b/python/tests/test_source.py
@@ -1,0 +1,27 @@
+#! /usr/bin/env python
+
+from numpy.testing import TestCase, assert_equal, assert_almost_equal
+from aubio import fvec, source
+from numpy import array
+
+path = "/Users/piem/archives/sounds/loops/drum_Chocolate_Milk_-_Ation_Speaks_Louder_Than_Words.wav"
+
+class aubio_filter_test_case(TestCase):
+
+ def test_members(self):
+ f = source(path)
+ print dir(f)
+
+ def test_read(self):
+ f = source(path)
+ total_frames = 0
+ while True:
+ vec, read = f()
+ total_frames += read
+ if read < f.hop_size: break
+ print "read", total_frames / float(f.samplerate), " seconds from", path
+
+if __name__ == '__main__':
+ from unittest import main
+ main()
+
--- /dev/null
+++ b/python/tests/test_specdesc.py
@@ -1,0 +1,238 @@
+#! /usr/bin/env python
+
+from numpy.testing import TestCase, assert_equal, assert_almost_equal
+from numpy import random, arange, log, zeros
+from aubio import specdesc, cvec
+from math import pi
+
+methods = ["default",
+ "energy",
+ "hfc",
+ "complex",
+ "phase",
+ "specdiff",
+ "kl",
+ "mkl",
+ "specflux",
+ "centroid",
+ "spread",
+ "skewness",
+ "kurtosis",
+ "slope",
+ "decrease",
+ "rolloff"]
+buf_size = 2048
+
+class aubio_specdesc(TestCase):
+
+ def test_members(self):
+ o = specdesc()
+
+ for method in methods:
+ o = specdesc(method, buf_size)
+ assert_equal ([o.buf_size, o.method], [buf_size, method])
+
+ spec = cvec(buf_size)
+ spec.norm[0] = 1
+ spec.norm[1] = 1./2.
+ #print "%20s" % method, str(o(spec))
+ o(spec)
+ spec.norm = random.random_sample((len(spec.norm),)).astype('float32')
+ spec.phas = random.random_sample((len(spec.phas),)).astype('float32')
+ #print "%20s" % method, str(o(spec))
+ assert (o(spec) != 0.)
+
+ def test_hfc(self):
+ o = specdesc("hfc", buf_size)
+ spec = cvec(buf_size)
+ # hfc of zeros is zero
+ assert_equal (o(spec), 0.)
+ # hfc of ones is sum of all bin numbers
+ spec.norm[:] = 1
+ expected = sum(range(buf_size/2 + 2))
+ assert_equal (o(spec), expected)
+ # changing phase doesn't change anything
+ spec.phas[:] = 1
+ assert_equal (o(spec), sum(range(buf_size/2 + 2)))
+
+ def test_phase(self):
+ o = specdesc("phase", buf_size)
+ spec = cvec(buf_size)
+ # phase of zeros is zero
+ assert_equal (o(spec), 0.)
+ spec.phas = random.random_sample((len(spec.phas),)).astype('float32')
+ # phase of random is not zero
+ spec.norm[:] = 1
+ assert (o(spec) != 0.)
+
+ def test_specdiff(self):
+ o = specdesc("phase", buf_size)
+ spec = cvec(buf_size)
+ # specdiff of zeros is zero
+ assert_equal (o(spec), 0.)
+ spec.phas = random.random_sample((len(spec.phas),)).astype('float32')
+ # phase of random is not zero
+ spec.norm[:] = 1
+ assert (o(spec) != 0.)
+
+ def test_hfc(self):
+ o = specdesc("hfc")
+ c = cvec()
+ assert_equal( 0., o(c))
+ a = arange(c.length, dtype='float32')
+ c.norm = a
+ assert_equal (a, c.norm)
+ assert_equal ( sum(a*(a+1)), o(c))
+
+ def test_complex(self):
+ o = specdesc("complex")
+ c = cvec()
+ assert_equal( 0., o(c))
+ a = arange(c.length, dtype='float32')
+ c.norm = a
+ assert_equal (a, c.norm)
+ # the previous run was on zeros, so previous frames are still 0
+ # so we have sqrt ( abs ( r2 ^ 2) ) == r2
+ assert_equal ( sum(a), o(c))
+ # second time. c.norm = a, so, r1 = r2, and the euclidian distance is 0
+ assert_equal ( 0, o(c))
+
+ def test_kl(self):
+ o = specdesc("kl")
+ c = cvec()
+ assert_equal( 0., o(c))
+ a = arange(c.length, dtype='float32')
+ c.norm = a
+ assert_almost_equal( sum(a * log(1.+ a/1.e-10 ) ) / o(c), 1., decimal=6)
+
+ def test_mkl(self):
+ o = specdesc("mkl")
+ c = cvec()
+ assert_equal( 0., o(c))
+ a = arange(c.length, dtype='float32')
+ c.norm = a
+ assert_almost_equal( sum(log(1.+ a/1.e-10 ) ) / o(c), 1, decimal=6)
+
+ def test_specflux(self):
+ o = specdesc("specflux")
+ c = cvec()
+ assert_equal( 0., o(c))
+ a = arange(c.length, dtype='float32')
+ c.norm = a
+ assert_equal( sum(a), o(c))
+ assert_equal( 0, o(c))
+ c.norm = zeros(c.length, dtype='float32')
+ assert_equal( 0, o(c))
+
+ def test_centroid(self):
+ o = specdesc("centroid")
+ c = cvec()
+ # make sure centroid of zeros is zero
+ assert_equal( 0., o(c))
+ a = arange(c.length, dtype='float32')
+ c.norm = a
+ centroid = sum(a*a) / sum(a)
+ assert_almost_equal (centroid, o(c), decimal = 2)
+
+ c.norm = a * .5
+ assert_almost_equal (centroid, o(c), decimal = 2)
+
+ def test_spread(self):
+ o = specdesc("spread")
+ c = cvec(2048)
+ ramp = arange(c.length, dtype='float32')
+ assert_equal( 0., o(c))
+
+ a = ramp
+ c.norm = a
+ centroid = sum(a*a) / sum(a)
+ spread = sum( a * pow(ramp - centroid, 2.) ) / sum(a)
+ assert_almost_equal (o(c), spread, decimal = 1)
+
+ def test_skewness(self):
+ o = specdesc("skewness")
+ c = cvec()
+ assert_equal( 0., o(c))
+ a = arange(c.length, dtype='float32')
+ c.norm = a
+ centroid = sum(a*a) / sum(a)
+ spread = sum( (a - centroid)**2 *a) / sum(a)
+ skewness = sum( (a - centroid)**3 *a) / sum(a) / spread **1.5
+ assert_almost_equal (skewness, o(c), decimal = 2)
+
+ c.norm = a * 3
+ assert_almost_equal (skewness, o(c), decimal = 2)
+
+ def test_kurtosis(self):
+ o = specdesc("kurtosis")
+ c = cvec()
+ assert_equal( 0., o(c))
+ a = arange(c.length, dtype='float32')
+ c.norm = a
+ centroid = sum(a*a) / sum(a)
+ spread = sum( (a - centroid)**2 *a) / sum(a)
+ kurtosis = sum( (a - centroid)**4 *a) / sum(a) / spread **2
+ assert_almost_equal (kurtosis, o(c), decimal = 2)
+
+ def test_slope(self):
+ o = specdesc("slope")
+ c = cvec()
+ assert_equal( 0., o(c))
+ a = arange(c.length * 2, 0, -2, dtype='float32')
+ k = arange(c.length, dtype='float32')
+ c.norm = a
+ num = len(a) * sum(k*a) - sum(k)*sum(a)
+ den = (len(a) * sum(k**2) - sum(k)**2)
+ slope = num/den/sum(a)
+ assert_almost_equal (slope, o(c), decimal = 5)
+
+ a = arange(0, c.length * 2, +2, dtype='float32')
+ c.norm = a
+ num = len(a) * sum(k*a) - sum(k)*sum(a)
+ den = (len(a) * sum(k**2) - sum(k)**2)
+ slope = num/den/sum(a)
+ assert_almost_equal (slope, o(c), decimal = 5)
+
+ a = arange(0, c.length * 2, +2, dtype='float32')
+ c.norm = a * 2
+ assert_almost_equal (slope, o(c), decimal = 5)
+
+ def test_decrease(self):
+ o = specdesc("decrease")
+ c = cvec()
+ assert_equal( 0., o(c))
+ a = arange(c.length * 2, 0, -2, dtype='float32')
+ k = arange(c.length, dtype='float32')
+ c.norm = a
+ decrease = sum((a[1:] - a [0]) / k[1:]) / sum(a[1:])
+ assert_almost_equal (decrease, o(c), decimal = 5)
+
+ a = arange(0, c.length * 2, +2, dtype='float32')
+ c.norm = a
+ decrease = sum((a[1:] - a [0]) / k[1:]) / sum(a[1:])
+ assert_almost_equal (decrease, o(c), decimal = 5)
+
+ a = arange(0, c.length * 2, +2, dtype='float32')
+ c.norm = a * 2
+ decrease = sum((a[1:] - a [0]) / k[1:]) / sum(a[1:])
+ assert_almost_equal (decrease, o(c), decimal = 5)
+
+ def test_rolloff(self):
+ o = specdesc("rolloff")
+ c = cvec()
+ assert_equal( 0., o(c))
+ a = arange(c.length * 2, 0, -2, dtype='float32')
+ k = arange(c.length, dtype='float32')
+ c.norm = a
+ cumsum = .95*sum(a*a)
+ i = 0; rollsum = 0
+ while rollsum < cumsum:
+ rollsum += a[i]*a[i]
+ i+=1
+ rolloff = i
+ assert_equal (rolloff, o(c))
+
+
+if __name__ == '__main__':
+ from unittest import main
+ main()
--- a/python/wscript_build
+++ /dev/null
@@ -1,6 +1,0 @@
-# vim:set syntax=python:
-
-ctx.add_subdirs('aubio')
-# install headers
-for file in ['aubiocut', 'aubiopitch']:
- ctx.install_as('${PREFIX}/bin/' + file, file, chmod = 0755)
--- a/sounds/Makefile.am
+++ /dev/null
@@ -1,5 +1,0 @@
-soundsdir = $(datadir)/sounds/aubio
-
-sounds_DATA = woodblock.aiff
-
-EXTRA_DIST = $(sounds_DATA)
--- a/src/Makefile.am
+++ /dev/null
@@ -1,78 +1,0 @@
-noinst_HEADERS = \
- aubio_priv.h
-
-nobase_pkginclude_HEADERS = \
- aubio.h \
- types.h \
- fvec.h \
- fmat.h \
- lvec.h \
- cvec.h \
- musicutils.h \
- mathutils.h \
- vecutils.h \
- utils/hist.h \
- utils/scale.h \
- temporal/resampler.h \
- temporal/biquad.h \
- temporal/filter.h \
- temporal/a_weighting.h \
- temporal/c_weighting.h \
- spectral/filterbank.h \
- spectral/filterbank_mel.h \
- spectral/mfcc.h \
- spectral/phasevoc.h \
- spectral/fft.h \
- spectral/tss.h \
- spectral/specdesc.h \
- pitch/pitch.h \
- pitch/pitchmcomb.h \
- pitch/pitchyin.h \
- pitch/pitchschmitt.h \
- pitch/pitchfcomb.h \
- pitch/pitchyinfft.h \
- onset/onset.h \
- onset/peakpicker.h \
- tempo/tempo.h \
- tempo/beattracking.h
-
-nodist_noinst_HEADERS = config.h
-
-lib_LTLIBRARIES = libaubio.la
-libaubio_la_SOURCES = \
- fvec.c \
- fmat.c \
- lvec.c \
- cvec.c \
- mathutils.c \
- vecutils.c \
- utils/hist.c \
- utils/scale.c \
- temporal/resampler.c \
- temporal/biquad.c \
- temporal/filter.c \
- temporal/a_weighting.c \
- temporal/c_weighting.c \
- spectral/filterbank.c \
- spectral/filterbank_mel.c \
- spectral/mfcc.c \
- spectral/phasevoc.c \
- spectral/fft.c \
- spectral/ooura_fft8g.c \
- spectral/tss.c \
- spectral/specdesc.c \
- spectral/statistics.c \
- pitch/pitch.c \
- pitch/pitchmcomb.c \
- pitch/pitchyin.c \
- pitch/pitchschmitt.c \
- pitch/pitchfcomb.c \
- pitch/pitchyinfft.c \
- onset/onset.c \
- onset/peakpicker.c \
- tempo/tempo.c \
- tempo/beattracking.c
-
-AM_CFLAGS = @AUBIO_CFLAGS@ @FFTWLIB_CFLAGS@ @SAMPLERATE_CFLAGS@
-libaubio_la_LIBADD = @FFTWLIB_LIBS@ @SAMPLERATE_LIBS@ @LTLIBOBJS@
-libaubio_la_LDFLAGS = -version-info @SHARED_VERSION_INFO@
--- a/src/aubio.h
+++ b/src/aubio.h
@@ -1,5 +1,5 @@
/*
- Copyright (C) 2003-2009 Paul Brossier <piem@aubio.org>
+ Copyright (C) 2003-2013 Paul Brossier <piem@aubio.org>
This file is part of aubio.
--- a/src/io/sink.c
+++ b/src/io/sink.c
@@ -44,7 +44,7 @@
if (s->sink) return s;
#endif /* HAVE_SNDFILE */
#endif /* __APPLE__ */
- AUBIO_ERROR("failed creating aubio sink with %s", uri);
+ AUBIO_ERROR("failed creating aubio sink with %s\n", uri);
AUBIO_FREE(s);
return NULL;
}
--- a/src/io/sink_apple_audio.c
+++ b/src/io/sink_apple_audio.c
@@ -52,13 +52,12 @@
aubio_sink_apple_audio_t * new_aubio_sink_apple_audio(char_t * uri, uint_t samplerate) {
aubio_sink_apple_audio_t * s = AUBIO_NEW(aubio_sink_apple_audio_t);
- s->samplerate;
+ s->samplerate = samplerate;
s->channels = 1;
s->path = uri;
s->max_frames = MAX_SIZE;
AudioStreamBasicDescription clientFormat;
- UInt32 propSize = sizeof(clientFormat);
memset(&clientFormat, 0, sizeof(AudioStreamBasicDescription));
clientFormat.mFormatID = kAudioFormatLinearPCM;
clientFormat.mSampleRate = (Float64)(s->samplerate);
@@ -77,7 +76,7 @@
err = ExtAudioFileCreateWithURL(fileURL, fileType, &clientFormat, NULL,
overwrite ? kAudioFileFlags_EraseFile : 0, &s->audioFile);
if (err) {
- AUBIO_ERR("error when trying to access %s, in ExtAudioFileOpenURL, %d\n", s->path, (int)err);
+ AUBIO_ERR("error when trying to create %s, in ExtAudioFileCreateWithURL, %d\n", s->path, (int)err);
goto beach;
}
if (createAubioBufferList(&s->bufferList, s->channels, s->max_frames * s->channels)) {
--- a/src/io/source.c
+++ b/src/io/source.c
@@ -44,7 +44,7 @@
if (s->source) return s;
#endif /* HAVE_SNDFILE */
#endif /* __APPLE__ */
- AUBIO_ERROR("failed creating aubio source with %s", uri);
+ AUBIO_ERROR("failed creating aubio source with %s\n", uri);
AUBIO_FREE(s);
return NULL;
}
--- a/src/io/source.h
+++ b/src/io/source.h
@@ -37,6 +37,8 @@
uint_t aubio_source_get_samplerate(aubio_source_t * s);
void del_aubio_source(aubio_source_t * s);
+uint_t aubio_source_get_samplerate(aubio_source_t * s);
+
#ifdef __cplusplus
}
#endif
--- a/src/io/source_apple_audio.c
+++ b/src/io/source_apple_audio.c
@@ -54,7 +54,6 @@
aubio_source_apple_audio_t * s = AUBIO_NEW(aubio_source_apple_audio_t);
s->path = path;
- s->samplerate = samplerate;
s->block_size = block_size;
s->channels = 1;
@@ -61,19 +60,6 @@
OSStatus err = noErr;
UInt32 propSize;
- AudioStreamBasicDescription clientFormat;
- propSize = sizeof(clientFormat);
- memset(&clientFormat, 0, sizeof(AudioStreamBasicDescription));
- clientFormat.mFormatID = kAudioFormatLinearPCM;
- clientFormat.mSampleRate = (Float64)(s->samplerate);
- clientFormat.mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked;
- clientFormat.mChannelsPerFrame = s->channels;
- clientFormat.mBitsPerChannel = sizeof(short) * 8;
- clientFormat.mFramesPerPacket = 1;
- clientFormat.mBytesPerFrame = clientFormat.mBitsPerChannel * clientFormat.mChannelsPerFrame / 8;
- clientFormat.mBytesPerPacket = clientFormat.mFramesPerPacket * clientFormat.mBytesPerFrame;
- clientFormat.mReserved = 0;
-
// open the resource url
CFURLRef fileURL = getURLFromPath(path);
err = ExtAudioFileOpenURL(fileURL, &s->audioFile);
@@ -89,10 +75,24 @@
kExtAudioFileProperty_FileDataFormat, &propSize, &fileFormat);
if (err) { AUBIO_ERROR("error in ExtAudioFileGetProperty, %d\n", (int)err); goto beach;}
- if (s->samplerate == 1) {
- clientFormat.mSampleRate = fileFormat.mSampleRate;
- s->samplerate = fileFormat.mSampleRate;
+ if (samplerate == 0) {
+ samplerate = fileFormat.mSampleRate;
+ //AUBIO_DBG("sampling rate set to 0, automagically adjusting to %d\n", samplerate);
}
+ s->samplerate = samplerate;
+
+ AudioStreamBasicDescription clientFormat;
+ propSize = sizeof(clientFormat);
+ memset(&clientFormat, 0, sizeof(AudioStreamBasicDescription));
+ clientFormat.mFormatID = kAudioFormatLinearPCM;
+ clientFormat.mSampleRate = (Float64)(s->samplerate);
+ clientFormat.mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked;
+ clientFormat.mChannelsPerFrame = s->channels;
+ clientFormat.mBitsPerChannel = sizeof(short) * 8;
+ clientFormat.mFramesPerPacket = 1;
+ clientFormat.mBytesPerFrame = clientFormat.mBitsPerChannel * clientFormat.mChannelsPerFrame / 8;
+ clientFormat.mBytesPerPacket = clientFormat.mFramesPerPacket * clientFormat.mBytesPerFrame;
+ clientFormat.mReserved = 0;
// set the client format description
err = ExtAudioFileSetProperty(s->audioFile, kExtAudioFileProperty_ClientDataFormat,
--- a/src/io/source_apple_audio.h
+++ b/src/io/source_apple_audio.h
@@ -27,4 +27,6 @@
uint_t aubio_source_apple_audio_get_samplerate(aubio_source_apple_audio_t * s);
void del_aubio_source_apple_audio(aubio_source_apple_audio_t * s);
+uint_t aubio_source_apple_audio_get_samplerate(aubio_source_apple_audio_t * s);
+
#endif /* _AUBIO_SOURCE_APPLE_AUDIO_H */
--- a/src/io/source_sndfile.c
+++ b/src/io/source_sndfile.c
@@ -69,7 +69,6 @@
}
s->hop_size = hop_size;
- s->samplerate = samplerate;
s->channels = 1;
s->path = path;
@@ -89,8 +88,11 @@
s->input_channels = sfinfo.channels;
s->input_format = sfinfo.format;
- if (s->samplerate == 1) s->samplerate = s->input_samplerate;
-
+ if (samplerate == 0) {
+ samplerate = s->input_samplerate;
+ //AUBIO_DBG("sampling rate set to 0, automagically adjusting to %d\n", samplerate);
+ }
+ s->samplerate = samplerate;
/* compute input block size required before resampling */
s->ratio = s->samplerate/(float)s->input_samplerate;
s->input_hop_size = (uint_t)FLOOR(s->hop_size / s->ratio + .5);
@@ -189,6 +191,10 @@
#endif /* HAVE_SAMPLERATE */
AUBIO_FREE(s->scratch_data);
AUBIO_FREE(s);
+}
+
+uint_t aubio_source_sndfile_get_samplerate(aubio_source_sndfile_t * s) {
+ return s->samplerate;
}
#endif /* HAVE_SNDFILE */
--- a/src/io/source_sndfile.h
+++ b/src/io/source_sndfile.h
@@ -27,4 +27,6 @@
uint_t aubio_source_sndfile_get_samplerate(aubio_source_sndfile_t * s);
void del_aubio_source_sndfile(aubio_source_sndfile_t * s);
+uint_t aubio_source_sndfile_get_samplerate(aubio_source_sndfile_t * s);
+
#endif /* _AUBIO_SOURCE_SNDFILE_H */
--- a/src/tempo/beattracking.c
+++ b/src/tempo/beattracking.c
@@ -135,7 +135,7 @@
smpl_t phase; // beat alignment (step - lastbeat)
smpl_t beat; // beat position
smpl_t bp; // beat period
- uint_t a; sint_t b; // used to build shift invariant comb filterbank
+ uint_t a, b; // used to build shift invariant comb filterbank
uint_t kmax; // number of elements used to find beat phase
/* copy dfframe, apply detection function weighting, and revert */
@@ -159,8 +159,8 @@
/* compute shift invariant comb filterbank */
for (i = 1; i < laglen - 1; i++) {
for (a = 1; a <= numelem; a++) {
- for (b = (1 - a); b < (sint_t)a; b++) {
- bt->acfout->data[i] += bt->acf->data[a * (i + 1) + b - 1]
+ for (b = 1; b < 2 * a; b++) {
+ bt->acfout->data[i] += bt->acf->data[i * a + b - 1]
* 1. / (2. * a - 1.);
}
}
@@ -275,7 +275,7 @@
void
aubio_beattracking_checkstate (aubio_beattracking_t * bt)
{
- uint_t i, j, a; sint_t b;
+ uint_t i, j, a, b;
uint_t flagconst = 0;
sint_t counter = bt->counter;
uint_t flagstep = bt->flagstep;
@@ -299,8 +299,8 @@
fvec_zeros (acfout);
for (i = 1; i < laglen - 1; i++) {
for (a = 1; a <= bt->timesig; a++) {
- for (b = (1 - a); b < (sint_t)a; b++) {
- acfout->data[i] += acf->data[a * (i + 1) + b - 1];
+ for (b = 1; b < 2 * a; b++) {
+ acfout->data[i] += acf->data[i * a + b - 1];
}
}
}
--- a/src/temporal/resampler.c
+++ b/src/temporal/resampler.c
@@ -42,9 +42,12 @@
aubio_resampler_t *s = AUBIO_NEW (aubio_resampler_t);
int error = 0;
s->stat = src_new (type, 1, &error); /* only one channel */
+ if (error) {
+ AUBIO_ERR ("Failed creating resampler: %s\n", src_strerror (error));
+ del_aubio_resampler(s);
+ return NULL;
+ }
s->proc = AUBIO_NEW (SRC_DATA);
- if (error)
- AUBIO_ERR ("%s\n", src_strerror (error));
s->ratio = ratio;
return s;
}
@@ -52,7 +55,7 @@
void
del_aubio_resampler (aubio_resampler_t * s)
{
- src_delete (s->stat);
+ if (s->stat) src_delete (s->stat);
AUBIO_FREE (s->proc);
AUBIO_FREE (s);
}
--- a/src/wscript_build
+++ b/src/wscript_build
@@ -24,6 +24,6 @@
# install headers, except _priv.h ones
ctx.install_files('${PREFIX}/include/aubio/',
- ctx.path.ant_glob('**/*.h',
- exclude = ['_priv.h', 'config.h']),
- relative_trick=True)
+
+ ctx.path.ant_glob('**/*.h', excl = ['**_priv.h', 'config.h']),
+ relative_trick=True)
--- a/swig/Makefile.am
+++ /dev/null
@@ -1,2 +1,0 @@
-# see ../python/Makefile.am
-EXTRA_DIST = aubio.i
--- a/swig/aubio.i
+++ /dev/null
@@ -1,143 +1,0 @@
-%module aubiowrapper
-
-%{
-#include "aubio.h"
-%}
-
-/* type aliases */
-typedef unsigned int uint_t;
-typedef int sint_t;
-typedef float smpl_t;
-typedef char char_t;
-
-/* fvec */
-fvec_t * new_fvec(uint_t length);
-void del_fvec(fvec_t *s);
-smpl_t fvec_read_sample(fvec_t *s, uint_t position);
-void fvec_write_sample(fvec_t *s, smpl_t data, uint_t position);
-smpl_t * fvec_get_data(fvec_t *s);
-
-/* cvec */
-cvec_t * new_cvec(uint_t length);
-void del_cvec(cvec_t *s);
-void cvec_write_norm(cvec_t *s, smpl_t data, uint_t position);
-void cvec_write_phas(cvec_t *s, smpl_t data, uint_t position);
-smpl_t cvec_read_norm(cvec_t *s, uint_t position);
-smpl_t cvec_read_phas(cvec_t *s, uint_t position);
-smpl_t * cvec_get_norm(cvec_t *s);
-smpl_t * cvec_get_phas(cvec_t *s);
-
-
-/* fft */
-aubio_fft_t * new_aubio_fft(uint_t size);
-void del_aubio_fft(aubio_fft_t * s);
-void aubio_fft_do (aubio_fft_t *s, fvec_t * input, cvec_t * spectrum);
-void aubio_fft_rdo (aubio_fft_t *s, cvec_t * spectrum, fvec_t * output);
-void aubio_fft_do_complex (aubio_fft_t *s, fvec_t * input, fvec_t * compspec);
-void aubio_fft_rdo_complex (aubio_fft_t *s, fvec_t * compspec, fvec_t * output);
-void aubio_fft_get_spectrum(fvec_t * compspec, cvec_t * spectrum);
-void aubio_fft_get_realimag(cvec_t * spectrum, fvec_t * compspec);
-void aubio_fft_get_phas(fvec_t * compspec, cvec_t * spectrum);
-void aubio_fft_get_imag(cvec_t * spectrum, fvec_t * compspec);
-void aubio_fft_get_norm(fvec_t * compspec, cvec_t * spectrum);
-void aubio_fft_get_real(cvec_t * spectrum, fvec_t * compspec);
-
-/* filter */
-aubio_filter_t * new_aubio_filter(uint_t order);
-void aubio_filter_do(aubio_filter_t * b, fvec_t * in);
-void aubio_filter_do_outplace(aubio_filter_t * b, fvec_t * in, fvec_t * out);
-void aubio_filter_do_filtfilt(aubio_filter_t * b, fvec_t * in, fvec_t * tmp);
-void del_aubio_filter(aubio_filter_t * b);
-
-/* a_weighting */
-aubio_filter_t * new_aubio_filter_a_weighting (uint_t samplerate);
-uint_t aubio_filter_set_a_weighting (aubio_filter_t * b, uint_t samplerate);
-
-/* c_weighting */
-aubio_filter_t * new_aubio_filter_c_weighting (uint_t samplerate);
-uint_t aubio_filter_set_c_weighting (aubio_filter_t * b, uint_t samplerate);
-
-/* biquad */
-aubio_filter_t * new_aubio_filter_biquad(lsmp_t b1, lsmp_t b2, lsmp_t b3, lsmp_t a2, lsmp_t a3);
-uint_t aubio_filter_set_biquad (aubio_filter_t * b, lsmp_t b1, lsmp_t b2, lsmp_t b3, lsmp_t a2, lsmp_t a3);
-
-/* mathutils */
-fvec_t * new_aubio_window(char * wintype, uint_t size);
-smpl_t aubio_unwrap2pi (smpl_t phase);
-smpl_t aubio_bintomidi(smpl_t bin, smpl_t samplerate, smpl_t fftsize);
-smpl_t aubio_miditobin(smpl_t midi, smpl_t samplerate, smpl_t fftsize);
-smpl_t aubio_bintofreq(smpl_t bin, smpl_t samplerate, smpl_t fftsize);
-smpl_t aubio_freqtobin(smpl_t freq, smpl_t samplerate, smpl_t fftsize);
-smpl_t aubio_freqtomidi(smpl_t freq);
-smpl_t aubio_miditofreq(smpl_t midi);
-uint_t aubio_silence_detection(fvec_t * ibuf, smpl_t threshold);
-smpl_t aubio_level_detection(fvec_t * ibuf, smpl_t threshold);
-smpl_t aubio_zero_crossing_rate(fvec_t * input);
-
-/* mfcc */
-aubio_mfcc_t * new_aubio_mfcc (uint_t win_s, uint_t samplerate, uint_t n_filters, uint_t n_coefs);
-void del_aubio_mfcc(aubio_mfcc_t *mf);
-void aubio_mfcc_do(aubio_mfcc_t *mf, cvec_t *in, fvec_t *out);
-
-/* resampling */
-#if HAVE_SAMPLERATE
-aubio_resampler_t * new_aubio_resampler(float ratio, uint_t type);
-void aubio_resampler_do (aubio_resampler_t *s, fvec_t * input, fvec_t * output);
-void del_aubio_resampler(aubio_resampler_t *s);
-#endif /* HAVE_SAMPLERATE */
-
-/* pvoc */
-aubio_pvoc_t * new_aubio_pvoc (uint_t win_s, uint_t hop_s);
-void del_aubio_pvoc(aubio_pvoc_t *pv);
-void aubio_pvoc_do(aubio_pvoc_t *pv, fvec_t *in, cvec_t * fftgrain);
-void aubio_pvoc_rdo(aubio_pvoc_t *pv, cvec_t * fftgrain, fvec_t *out);
-
-/* pitch detection */
-aubio_pitch_t *new_aubio_pitch (char *pitch_mode,
- uint_t bufsize, uint_t hopsize, uint_t samplerate);
-void aubio_pitch_do (aubio_pitch_t * p, fvec_t * ibuf, fvec_t * obuf);
-uint_t aubio_pitch_set_tolerance(aubio_pitch_t *p, smpl_t thres);
-uint_t aubio_pitch_set_unit(aubio_pitch_t *p, char * pitch_unit);
-void del_aubio_pitch(aubio_pitch_t * p);
-
-/* tempo */
-aubio_tempo_t * new_aubio_tempo (char_t * mode,
- uint_t buf_size, uint_t hop_size, uint_t samplerate);
-void aubio_tempo_do (aubio_tempo_t *o, fvec_t * input, fvec_t * tempo);
-uint_t aubio_tempo_set_silence(aubio_tempo_t * o, smpl_t silence);
-uint_t aubio_tempo_set_threshold(aubio_tempo_t * o, smpl_t threshold);
-smpl_t aubio_tempo_get_bpm(aubio_tempo_t * bt);
-smpl_t aubio_tempo_get_confidence(aubio_tempo_t * bt);
-void del_aubio_tempo(aubio_tempo_t * o);
-
-/* specdesc */
-void aubio_specdesc_do (aubio_specdesc_t * o, cvec_t * fftgrain,
- fvec_t * desc);
-aubio_specdesc_t *new_aubio_specdesc (char_t * method, uint_t buf_size);
-void del_aubio_specdesc (aubio_specdesc_t * o);
-
-/* peak picker */
-aubio_peakpicker_t * new_aubio_peakpicker();
-void aubio_peakpicker_do(aubio_peakpicker_t * p, fvec_t * in, fvec_t * out);
-fvec_t * aubio_peakpicker_get_thresholded_input(aubio_peakpicker_t * p);
-void del_aubio_peakpicker(aubio_peakpicker_t * p);
-uint_t aubio_peakpicker_set_threshold(aubio_peakpicker_t * p, smpl_t threshold);
-
-/* sndfile */
-%{
-#include "config.h"
-#if HAVE_SNDFILE
-#include "sndfileio.h"
-%}
-aubio_sndfile_t * new_aubio_sndfile_ro (const char * inputfile);
-aubio_sndfile_t * new_aubio_sndfile_wo(aubio_sndfile_t * existingfile, const char * outputname);
-void aubio_sndfile_info(aubio_sndfile_t * file);
-int aubio_sndfile_write(aubio_sndfile_t * file, int frames, fvec_t ** write);
-int aubio_sndfile_read(aubio_sndfile_t * file, int frames, fvec_t ** read);
-int aubio_sndfile_read_mono(aubio_sndfile_t * file, int frames, fvec_t * read);
-int del_aubio_sndfile(aubio_sndfile_t * file);
-uint_t aubio_sndfile_channels(aubio_sndfile_t * file);
-uint_t aubio_sndfile_samplerate(aubio_sndfile_t * file);
-%{
-#endif /* HAVE_SNDFILE */
-%}
--- a/swig/swig.py
+++ /dev/null
@@ -1,170 +1,0 @@
-#! /usr/bin/env python
-# encoding: UTF-8
-# Petar Forai
-# Thomas Nagy 2008
-
-import re
-import Task, Utils, Logs
-from TaskGen import extension
-from Configure import conf
-import preproc
-
-SWIG_EXTS = ['.swig', '.i']
-
-swig_str = '${SWIG} ${SWIGFLAGS} ${SRC}'
-cls = Task.simple_task_type('swig', swig_str, color='BLUE', before='cc cxx')
-
-re_module = re.compile('%module(?:\s*\(.*\))?\s+(.+)', re.M)
-
-re_1 = re.compile(r'^%module.*?\s+([\w]+)\s*?$', re.M)
-re_2 = re.compile('%include "(.*)"', re.M)
-re_3 = re.compile('#include "(.*)"', re.M)
-
-def scan(self):
- "scan for swig dependencies, climb the .i files"
- env = self.env
-
- lst_src = []
-
- seen = []
- to_see = [self.inputs[0]]
-
- while to_see:
- node = to_see.pop(0)
- if node.id in seen:
- continue
- seen.append(node.id)
- lst_src.append(node)
-
- # read the file
- code = node.read(env)
- code = preproc.re_nl.sub('', code)
- code = preproc.re_cpp.sub(preproc.repl, code)
-
- # find .i files and project headers
- names = re_2.findall(code) + re_3.findall(code)
- for n in names:
- for d in self.generator.swig_dir_nodes + [node.parent]:
- u = d.find_resource(n)
- if u:
- to_see.append(u)
- break
- else:
- Logs.warn('could not find %r' % n)
-
- # list of nodes this one depends on, and module name if present
- if Logs.verbose:
- Logs.debug('deps: deps for %s: %s' % (str(self), str(lst_src)))
- return (lst_src, [])
-cls.scan = scan
-
-# provide additional language processing
-swig_langs = {}
-def swig(fun):
- swig_langs[fun.__name__.replace('swig_', '')] = fun
-
-@swig
-def swig_python(tsk):
- tsk.set_outputs(tsk.inputs[0].parent.find_or_declare(tsk.module + '.py'))
-
-@swig
-def swig_ocaml(tsk):
- tsk.set_outputs(tsk.inputs[0].parent.find_or_declare(tsk.module + '.ml'))
- tsk.set_outputs(tsk.inputs[0].parent.find_or_declare(tsk.module + '.mli'))
-
-def add_swig_paths(self):
- if getattr(self, 'add_swig_paths_done', None):
- return
- self.add_swig_paths_done = True
-
- self.swig_dir_nodes = []
- for x in self.to_list(self.includes):
- node = self.path.find_dir(x)
- if not node:
- Logs.warn('could not find the include %r' % x)
- continue
- self.swig_dir_nodes.append(node)
-
- # add the top-level, it is likely to be added
- self.swig_dir_nodes.append(self.bld.srcnode)
- for x in self.swig_dir_nodes:
- self.env.append_unique('SWIGFLAGS', '-I%s' % x.abspath(self.env)) # build dir
- self.env.append_unique('SWIGFLAGS', '-I%s' % x.abspath()) # source dir
-
-@extension(SWIG_EXTS)
-def i_file(self, node):
- flags = self.to_list(getattr(self, 'swig_flags', []))
-
- ext = '.swigwrap_%d.c' % self.idx
- if '-c++' in flags:
- ext += 'xx'
-
- # the user might specify the module directly
- module = getattr(self, 'swig_module', None)
- if not module:
- # else, open the files and search
- txt = node.read(self.env)
- m = re_module.search(txt)
- if not m:
- raise "for now we are expecting a module name in the main swig file"
- module = m.group(1)
- out_node = node.parent.find_or_declare(module + ext)
-
- # the task instance
- tsk = self.create_task('swig')
- tsk.set_inputs(node)
- tsk.set_outputs(out_node)
- tsk.module = module
- tsk.env['SWIGFLAGS'] = flags
-
- if not '-outdir' in flags:
- flags.append('-outdir')
- flags.append(node.parent.abspath(self.env))
-
- if not '-o' in flags:
- flags.append('-o')
- flags.append(out_node.abspath(self.env))
-
- # add the language-specific output files as nodes
- # call funs in the dict swig_langs
- for x in flags:
- # obtain the language
- x = x[1:]
- try:
- fun = swig_langs[x]
- except KeyError:
- pass
- else:
- fun(tsk)
-
- self.allnodes.append(out_node)
-
- add_swig_paths(self)
-
-@conf
-def check_swig_version(conf, minver=None):
- """Check for a minimum swig version like conf.check_swig_version('1.3.28')
- or conf.check_swig_version((1,3,28)) """
- reg_swig = re.compile(r'SWIG Version\s(.*)', re.M)
-
- swig_out = Utils.cmd_output('%s -version' % conf.env['SWIG'])
-
- swigver = [int(s) for s in reg_swig.findall(swig_out)[0].split('.')]
- if isinstance(minver, basestring):
- minver = [int(s) for s in minver.split(".")]
- if isinstance(minver, tuple):
- minver = [int(s) for s in minver]
- result = (minver is None) or (minver[:3] <= swigver[:3])
- swigver_full = '.'.join(map(str, swigver))
- if result:
- conf.env['SWIG_VERSION'] = swigver_full
- minver_str = '.'.join(map(str, minver))
- if minver is None:
- conf.check_message_custom('swig version', '', swigver_full)
- else:
- conf.check_message('swig version', '>= %s' % (minver_str,), result, option=swigver_full)
- return result
-
-def detect(conf):
- swig = conf.find_program('swig', var='SWIG', mandatory=True)
-
--- a/tests/Makefile.am
+++ /dev/null
@@ -1,3 +1,0 @@
-if COMPILE_TESTS
-SUBDIRS = src
-endif
--- a/tests/demo/bench/onset/Makefile.am
+++ /dev/null
@@ -1,44 +1,0 @@
-export BASEDIR=../../../..
-export PYTHONPATH=$(BASEDIR)/python
-export LD_LIBRARY_PATH=$(BASEDIR)/src/.libs:$(BASEDIR)/ext/.libs
-
-DETAILSOURCE = \
- /var/tmp/Onset-Mirex2005/poly_pitched \
- /var/tmp/Onset-Mirex2005/solo_bars_and_bells \
- /var/tmp/Onset-Mirex2005/solo_brass \
- /var/tmp/Onset-Mirex2005/solo_drums \
- /var/tmp/Onset-Mirex2005/solo_plucked_strings \
- /var/tmp/Onset-Mirex2005/solo_singing_voice \
- /var/tmp/Onset-Mirex2005/solo_sustained_strings \
- /var/tmp/Onset-Mirex2005/solo_winds \
- /var/tmp/Onset-Mirex2005/complex
-
-SOURCE = /var/tmp/Onset-Mirex2005
-
-TESTSOURCE = \
- /var/tmp/Onset-Mirex2005/solo_bars_and_bells \
- /var/tmp/Onset-Mirex2005/solo_winds \
- /archives/samples/DB/PercussivePhrases/CM18/Samba_Audio
-
-test-aubiocut: $(patsubst %, %.aubiocut, $(TESTSOURCE))
-test-aubiodelay: $(patsubst %, %.aubiodelay, $(TESTSOURCE))
-test-aubiowindow: $(patsubst %, %.aubiowindow, $(TESTSOURCE))
-
-final-aubiocut: $(patsubst %, %.aubiocut, $(DETAILSOURCE) $(SOURCE))
-final-aubiodelay: $(patsubst %, %.aubiodelay, $(SOURCE))
-final-aubiowindow: $(patsubst %, %.aubiowindow, $(SOURCE))
-
-%.aubiocut: %
- rm -f `basename $@`
- ./bench-onset $< | tee `basename $@`
- -diff `basename $@`.ref `basename $@`
-
-%.aubiodelay: %
- rm -f `basename $@`
- ./bench-delay $< | tee `basename $@`
- -diff `basename $@`.ref `basename $@`
-
-%.aubiowindow: %
- rm -f `basename $@`
- ./bench-window $< | tee `basename $@`
- -diff `basename $@`.ref `basename $@`
--- a/tests/demo/bench/pitch/Makefile.am
+++ /dev/null
@@ -1,59 +1,0 @@
-export AUBIODIR=../../../..
-export PYTHONPATH=$(AUBIODIR)/python
-export LD_LIBRARY_PATH=$(AUBIODIR)/src/.libs:$(AUBIODIR)/ext/.libs
-
-CP=cp -a
-
-SOURCE = \
- $(BASEDIR)/isolated/vibraphone \
- $(BASEDIR)/isolated/clavinet \
- $(BASEDIR)/isolated/elecguitar \
- $(BASEDIR)/isolated/piano \
- $(BASEDIR)/isolated/rhodes \
- $(BASEDIR)/isolated
-
-
-MONOSOURCE = \
- $(BASEDIR)/monophonic/Mirex04/daisy \
- $(BASEDIR)/monophonic/Mirex04/midi \
- $(BASEDIR)/monophonic/Mirex04/jazz \
- $(BASEDIR)/monophonic/Mirex04/pop \
- $(BASEDIR)/monophonic/Mirex04/opera \
- $(BASEDIR)/monophonic/Mirex04
-
-POLYSOURCE = \
- $(BASEDIR)/polyphonic/Mirex04/daisy \
- $(BASEDIR)/polyphonic/Mirex04/midi \
- $(BASEDIR)/polyphonic/Mirex04/jazz \
- $(BASEDIR)/polyphonic/Mirex04/pop \
- $(BASEDIR)/polyphonic/Mirex04/opera \
- $(BASEDIR)/polyphonic/Mirex04
-
-test-aubiopitch-isolated: $(patsubst %, %.aubiopitch-isolated, $(SOURCE))
-test-aubiopitch-monophonic: $(patsubst %, %.aubiopitch-monophonic, $(MONOSOURCE))
-test-aubiopitch-polyphonic: $(patsubst %, %.aubiopitch-polyphonic, $(POLYSOURCE))
-
-plotpitch:
- ../../../aubiopitch -m fcomb,mcomb,yinfft,yin,schmitt -i jazz2REF.wav -p -t 0.2 -l 100 -M 600 -O jazz2REF.ps
- ../../../aubiopitch -m fcomb,mcomb,yinfft,yin,schmitt -p -t 0.2 -l 300 -M 900 -i opera_fem2REF.wav -O opera_fem2REF.ps
-
-timings:
- ./bench-timings $(BASEDIR)/polyphonic/Mirex04/opera
-
-%.aubiopitch-isolated: %
- $(CP) isolated/`basename $@` isolated/`basename $@`.old
- ./bench-pitch-isolated $< | tee isolated/`basename $@`
- -diff isolated/`basename $@`.old isolated/`basename $@`
- -diff isolated/`basename $@`.ref isolated/`basename $@`
-
-%.aubiopitch-monophonic: %
- $(CP) monophonic/`basename $@` monophonic/`basename $@`.old
- ./bench-pitch-monophonic $< | tee monophonic/`basename $@`
- -diff monophonic/`basename $@`.ref monophonic/`basename $@`
- -diff monophonic/`basename $@`.old monophonic/`basename $@`
-
-%.aubiopitch-polyphonic: %
- $(CP) polyphonic/`basename $@` polyphonic/`basename $@`.old
- ./bench-pitch-polyphonic $< | tee polyphonic/`basename $@`
- -diff polyphonic/`basename $@`.ref polyphonic/`basename $@`
- -diff polyphonic/`basename $@`.old polyphonic/`basename $@`
--- a/tests/src/Makefile.am
+++ /dev/null
@@ -1,42 +1,0 @@
-AM_CFLAGS = -I$(top_srcdir)/src -I$(top_srcdir)/examples
-AM_LDFLAGS = -L$(top_builddir)/src -laubio @FFTWLIB_LIBS@
-
-spectral_test_phasevoc_jack_CFLAGS = $(AM_CFLAGS) @JACK_CFLAGS@
-spectral_test_phasevoc_jack_LDADD = $(AM_LDFLAGS) @JACK_LIBS@
-
-noinst_PROGRAMS = \
- test-fvec \
- test-cvec \
- test-mathutils \
- test-mathutils-window \
- pitch/test-pitchyin \
- pitch/test-pitchyinfft \
- pitch/test-pitch \
- pitch/test-pitchmcomb \
- pitch/test-pitchfcomb \
- pitch/test-pitchschmitt \
- temporal/test-cweighting \
- temporal/test-resampler \
- temporal/test-filter \
- temporal/test-biquad \
- temporal/test-aweighting \
- onset/test-peakpicker \
- onset/test-onset \
- tempo/test-tempo \
- tempo/test-beattracking \
- spectral/test-fft \
- spectral/test-specdesc \
- spectral/test-phasevoc \
- spectral/test-phasevoc-jack \
- spectral/test-tss \
- spectral/test-filterbank \
- spectral/test-filterbank_mel \
- spectral/test-mfcc \
- utils/test-scale \
- utils/test-hist
-
-run-tests: $(noinst_PROGRAMS)
- @for i in $(noinst_PROGRAMS); do echo -n $$i\ ; ./$$i > /dev/null && echo OK || echo FAILED: $$?; done
-
-run-valgrind-tests: $(noinst_PROGRAMS)
- @for i in $(noinst_PROGRAMS); do echo $$i; valgrind .libs/lt-$$i 2>&1 | grep ERROR\ SUMMARY -A4; echo $$?; done
--- /dev/null
+++ b/tests/wscript_build
@@ -1,0 +1,21 @@
+# vim:set syntax=python:
+
+for target_name in ctx.path.ant_glob('src/**/*.c'):
+ uselib = []
+ includes = ['../src']
+ extra_source = []
+ if str(target_name).endswith('-jack.c') and ctx.env['JACK']:
+ uselib += ['JACK']
+ includes += ['../examples']
+ extra_source += ['../examples/jackio.c']
+
+ bld(features = 'c cprogram test',
+ uselib = uselib,
+ source = [target_name] + extra_source,
+ target = str(target_name).split('.')[0],
+ includes = includes,
+ install_path = None,
+ defines = 'AUBIO_UNSTABLE_API=1',
+ cflags = ['-g'],
+ use = 'aubio')
+
--- a/waf
+++ b/waf
@@ -1,6 +1,6 @@
#!/usr/bin/env python
# encoding: ISO8859-1
-# Thomas Nagy, 2005-2011
+# Thomas Nagy, 2005-2012
"""
Redistribution and use in source and binary forms, with or without
@@ -32,10 +32,10 @@
import os, sys
-VERSION="1.6.11"
-REVISION="9ba72a99056a2dfa53f17212aa3b8606"
+VERSION="1.7.9"
+REVISION="b503f38d25464d88953a601c8cd0ace6"
INSTALL=''
-C1='#2'
+C1='#='
C2='#+'
cwd = os.getcwd()
join = os.path.join
@@ -74,13 +74,13 @@
for x in ['Tools', 'extras']:
os.makedirs(join(dir, 'waflib', x))
except OSError:
- err("Cannot unpack waf lib into %s\nMove waf into a writeable directory" % dir)
+ err("Cannot unpack waf lib into %s\nMove waf in a writable directory" % dir)
os.chdir(dir)
tmp = 't.bz2'
t = open(tmp,'wb')
- t.write(txt)
- t.close()
+ try: t.write(txt)
+ finally: t.close()
try:
t = tarfile.open(tmp)
@@ -95,8 +95,10 @@
except OSError: pass
err("Waf cannot be unpacked, check that bzip2 support is present")
- for x in t: t.extract(x)
- t.close()
+ try:
+ for x in t: t.extract(x)
+ finally:
+ t.close()
for x in ['Tools', 'extras']:
os.chmod(join('waflib',x), 493)
@@ -156,10 +158,10 @@
sys.path.insert(0, wafdir)
if __name__ == '__main__':
- import waflib.extras.compat15
+
from waflib import Scripting
Scripting.waf_entry_point(cwd, VERSION, wafdir)
#==>
-#BZh91AY&SYJq�D���l��������
\ No newline at end of file
+#BZh91AY&SY�i���$�����t��������
\ No newline at end of file
�L�����zV�DR[V���t�媃���� ՚��}���&�2�̴��a���q�i���EF}#ک�#23wj9��6!��h��jqθ}W�:�'M�a�ɸ�v�*����]�龟g�kbdO<;����ꅈ>�H)a���Y�!���A�*,Y┯��獺��~9'��s��#2a�J�$6�E���Y���M���2(�O�!/w�3�L�WK�S#+u�^!�U��P����%�tٸ�������Q����]�������䔘���ʞ\�3��}�_v��}�[�|fY��{Aݏ�=�u�Z"V���<�cb ��i��s`�b������_k*���!d�{�CTgK���e�QFz���V�<+�u3�i���+J�3�~���/�u��0sṥ�;L�"��E#�&o�٨,O��ڕS �DD�9��܊?��k���k�o����I���6���&����h��okN�A�OKVO����{�==���?��̴J6�9J/^0�A_�E>���|�ΛΈcdI��,M"$�Bqm�Ww��L�@��D*R�V�q�9�!~����^�'�̔�m�����sѕ�Z�u8PR�3���eo鏬�;�F�!��dv��_j`�"��9�Zg� ,S�~�g���z��#2�a����B�\����;P4�ӓ�ֿ+�KjBѣ�ZG�)i i�Y��r��_��(}y��լ��f����NR[U})M�T��i-d���6�����%
\ No newline at end of file
--- a/wscript
+++ b/wscript
@@ -52,15 +52,13 @@
ctx.add_option('--with-target-platform', type='string',
help='set target platform for cross-compilation', dest='target_platform')
ctx.load('compiler_c')
- ctx.load('gnu_dirs')
ctx.load('waf_unit_test')
def configure(ctx):
- import Options
- ctx.check_tool('compiler_c')
- ctx.check_tool('gnu_dirs') # helpful for autotools transition and .pc generation
+ from waflib import Options
+ ctx.load('compiler_c')
ctx.load('waf_unit_test')
- ctx.env.CFLAGS = ['-g', '-Wall', '-Wextra']
+ ctx.env.CFLAGS += ['-g', '-Wall', '-Wextra']
if Options.options.target_platform:
Options.platform = Options.options.target_platform
@@ -68,7 +66,7 @@
if Options.platform == 'win32':
ctx.env['shlib_PATTERN'] = 'lib%s.dll'
- if Options.platform == 'macfat':
+ if Options.platform == 'darwin':
ctx.env.CFLAGS += ['-arch', 'i386', '-arch', 'x86_64']
ctx.env.LINKFLAGS += ['-arch', 'i386', '-arch', 'x86_64']
ctx.env.CC = 'llvm-gcc-4.2'
@@ -75,6 +73,19 @@
ctx.env.LINK_CC = 'llvm-gcc-4.2'
ctx.env.FRAMEWORK = ['CoreFoundation', 'AudioToolbox']
+ if Options.platform == 'ios':
+ ctx.env.CC = 'clang'
+ ctx.env.LD = 'clang'
+ ctx.env.LINK_CC = 'clang'
+ SDKVER="6.1"
+ DEVROOT="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer"
+ SDKROOT="%(DEVROOT)s/SDKs/iPhoneOS%(SDKVER)s.sdk" % locals()
+ ctx.env.FRAMEWORK = ['CoreFoundation', 'AudioToolbox']
+ ctx.env.CFLAGS += [ '-miphoneos-version-min=6.1', '-arch', 'armv7',
+ '--sysroot=%s' % SDKROOT]
+ ctx.env.LINKFLAGS += ['-std=c99', '-arch', 'armv7', '--sysroot=%s' %
+ SDKROOT]
+
# check for required headers
ctx.check(header_name='stdlib.h')
ctx.check(header_name='stdio.h')
@@ -179,16 +190,16 @@
except ctx.errors.ConfigurationError:
ctx.to_log('docbook-to-man was not found (ignoring)')
-def build(ctx):
- ctx.env['VERSION'] = VERSION
- ctx.env['LIB_VERSION'] = LIB_VERSION
+def build(bld):
+ bld.env['VERSION'] = VERSION
+ bld.env['LIB_VERSION'] = LIB_VERSION
# add sub directories
- ctx.add_subdirs(['src','examples'])
- if ctx.env['SWIG']:
- if ctx.env['PYTHON']:
- ctx.add_subdirs('python')
+ bld.recurse('src examples')
+ from waflib import Options
+ if Options.platform != 'ios': bld.recurse('tests')
+ """
# create the aubio.pc file for pkg-config
if ctx.env['TARGET_PLATFORM'] == 'linux':
aubiopc = ctx.new_task_gen('subst')
@@ -211,33 +222,6 @@
ctx.install_files('${MANDIR}/man1', ctx.path.ant_glob('doc/*.1'))
# install woodblock sound
- ctx.install_files('${PREFIX}/share/sounds/aubio/',
+ bld.install_files('${PREFIX}/share/sounds/aubio/',
'sounds/woodblock.aiff')
-
- # build and run the unit tests
- build_tests(ctx)
-
-def shutdown(ctx):
- pass
-
-# loop over all *.c filenames in tests/src to build them all
-# target name is filename.c without the .c
-def build_tests(ctx):
- for target_name in ctx.path.ant_glob('tests/src/**/*.c'):
- uselib = []
- includes = ['src']
- extra_source = []
- if str(target_name).endswith('-jack.c') and ctx.env['JACK']:
- uselib += ['JACK']
- includes += ['examples']
- extra_source += ['examples/jackio.c']
-
- this_target = ctx.new_task_gen(
- features = 'c cprogram test',
- uselib = uselib,
- source = [target_name] + extra_source,
- target = str(target_name).split('.')[0],
- includes = includes,
- defines = 'AUBIO_UNSTABLE_API=1',
- cflags = ['-g'],
- use = 'aubio')
+ """