From sumomo @ users.sourceforge.jp Sat Feb 5 16:10:55 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Sat, 05 Feb 2011 16:10:55 +0900 Subject: [Julius-cvs 559] CVS update: julius4/libsent/src/adin/pa/common Message-ID: <1296889855.544392.19953.nullmailer@users.sourceforge.jp> From sumomo @ users.sourceforge.jp Sat Feb 5 16:11:02 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Sat, 05 Feb 2011 16:11:02 +0900 Subject: [Julius-cvs 560] CVS update: julius4/libsent/src/adin/pa/hostapi Message-ID: <1296889862.666847.19995.nullmailer@users.sourceforge.jp> From sumomo @ users.sourceforge.jp Sat Feb 5 16:11:07 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Sat, 05 Feb 2011 16:11:07 +0900 Subject: [Julius-cvs 561] CVS update: julius4/libsent/src/adin/pa/include Message-ID: <1296889867.554597.20033.nullmailer@users.sourceforge.jp> From sumomo @ users.sourceforge.jp Sat Feb 5 16:11:10 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Sat, 05 Feb 2011 16:11:10 +0900 Subject: [Julius-cvs 562] CVS update: julius4/libsent/src/adin/pa/os Message-ID: <1296889870.737739.20059.nullmailer@users.sourceforge.jp> From sumomo @ users.sourceforge.jp Sat Feb 5 16:11:34 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Sat, 05 Feb 2011 16:11:34 +0900 Subject: [Julius-cvs 563] CVS update: julius4/libsent/src/adin/pa/hostapi/alsa Message-ID: <1296889894.138163.20969.nullmailer@users.sourceforge.jp> From sumomo @ users.sourceforge.jp Sat Feb 5 16:11:34 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Sat, 05 Feb 2011 16:11:34 +0900 Subject: [Julius-cvs 564] CVS update: julius4/libsent/src/adin/pa/hostapi/jack Message-ID: <1296889894.745280.21000.nullmailer@users.sourceforge.jp> From sumomo @ users.sourceforge.jp Sat Feb 5 16:11:34 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Sat, 05 Feb 2011 16:11:34 +0900 Subject: [Julius-cvs 565] CVS update: julius4/libsent/src/adin/pa/hostapi/wdmks Message-ID: <1296889894.930323.21015.nullmailer@users.sourceforge.jp> From sumomo @ users.sourceforge.jp Sat Feb 5 16:11:34 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Sat, 05 Feb 2011 16:11:34 +0900 Subject: [Julius-cvs 566] CVS update: julius4/libsent/src/adin/pa/hostapi/wmme Message-ID: <1296889894.993103.21020.nullmailer@users.sourceforge.jp> From sumomo @ users.sourceforge.jp Sat Feb 5 16:11:34 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Sat, 05 Feb 2011 16:11:34 +0900 Subject: [Julius-cvs 567] CVS update: julius4/libsent/src/adin/pa/hostapi/asihpi Message-ID: <1296889894.199339.20975.nullmailer@users.sourceforge.jp> From sumomo @ users.sourceforge.jp Sat Feb 5 16:11:34 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Sat, 05 Feb 2011 16:11:34 +0900 Subject: [Julius-cvs 568] CVS update: julius4/libsent/src/adin/pa/hostapi/asio Message-ID: <1296889894.257219.20980.nullmailer@users.sourceforge.jp> From sumomo @ users.sourceforge.jp Sat Feb 5 16:11:34 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Sat, 05 Feb 2011 16:11:34 +0900 Subject: [Julius-cvs 569] CVS update: julius4/libsent/src/adin/pa/hostapi/dsound Message-ID: <1296889894.682357.20995.nullmailer@users.sourceforge.jp> From sumomo @ users.sourceforge.jp Sat Feb 5 16:11:34 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Sat, 05 Feb 2011 16:11:34 +0900 Subject: [Julius-cvs 570] CVS update: julius4/libsent/src/adin/pa/hostapi/wasapi Message-ID: <1296889894.868942.21010.nullmailer@users.sourceforge.jp> From sumomo @ users.sourceforge.jp Sat Feb 5 16:11:34 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Sat, 05 Feb 2011 16:11:34 +0900 Subject: [Julius-cvs 571] CVS update: julius4/libsent/src/adin/pa/hostapi/coreaudio Message-ID: <1296889894.621840.20990.nullmailer@users.sourceforge.jp> From sumomo @ users.sourceforge.jp Sat Feb 5 16:11:34 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Sat, 05 Feb 2011 16:11:34 +0900 Subject: [Julius-cvs 572] CVS update: julius4/libsent/src/adin/pa/hostapi/oss Message-ID: <1296889894.806551.21005.nullmailer@users.sourceforge.jp> From sumomo @ users.sourceforge.jp Sat Feb 5 16:13:38 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Sat, 05 Feb 2011 16:13:38 +0900 Subject: [Julius-cvs 573] CVS update: julius4/libsent/src/adin/pa/os/mac_osx Message-ID: <1296890018.166022.23768.nullmailer@users.sourceforge.jp> From sumomo @ users.sourceforge.jp Sat Feb 5 16:13:38 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Sat, 05 Feb 2011 16:13:38 +0900 Subject: [Julius-cvs 574] CVS update: julius4/libsent/src/adin/pa/os/unix Message-ID: <1296890018.230192.23774.nullmailer@users.sourceforge.jp> From sumomo @ users.sourceforge.jp Sat Feb 5 16:13:38 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Sat, 05 Feb 2011 16:13:38 +0900 Subject: [Julius-cvs 575] CVS update: julius4/libsent/src/adin/pa/os/win Message-ID: <1296890018.292827.23779.nullmailer@users.sourceforge.jp> From sumomo @ users.sourceforge.jp Sat Feb 5 18:00:01 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Sat, 05 Feb 2011 18:00:01 +0900 Subject: [Julius-cvs 576] CVS update: julius4/libsent Message-ID: <1296896401.665230.27437.nullmailer@users.sourceforge.jp> Index: julius4/libsent/Makefile.in diff -u julius4/libsent/Makefile.in:1.8 julius4/libsent/Makefile.in:1.9 --- julius4/libsent/Makefile.in:1.8 Fri Oct 3 00:01:59 2008 +++ julius4/libsent/Makefile.in Sat Feb 5 18:00:01 2011 @@ -3,7 +3,7 @@ # Copyright (c) 2005-2007 Julius project team, Nagoya Institute of Technology # All rights reserved # -# $Id: Makefile.in,v 1.8 2008/10/02 15:01:59 sumomo Exp $ +# $Id: Makefile.in,v 1.9 2011/02/05 09:00:01 sumomo Exp $ # SHELL=/bin/sh @@ -156,7 +156,7 @@ ${INSTALL_PROGRAM} libsent-config-dist ${bindir}/libsent-config clean: - $(RM) *~ src/*/*~ src/*/*.o src/*/*/*.o include/sent/*~ + $(RM) *~ src/*/*~ src/*/*.o src/*/*/*.o src/*/*/*/*.o src/*/*/*/*/*.o include/sent/*~ $(RM) config.log config.cache distclean: Index: julius4/libsent/configure diff -u julius4/libsent/configure:1.24 julius4/libsent/configure:1.25 --- julius4/libsent/configure:1.24 Mon May 17 18:04:17 2010 +++ julius4/libsent/configure Sat Feb 5 18:00:01 2011 @@ -12,7 +12,7 @@ ac_default_prefix=/usr/local # Any additions from configure.in: ac_help="$ac_help - --with-mictype=TYPE specify mic I/O (oss|alsa|freebsd|coreaudio|sol2|sun4|irix|esd|sp|portaudio|pa-oss|pa-winmm|pa-dsound)" + --with-mictype=TYPE specify mic I/O (oss|alsa|freebsd|coreaudio|sol2|sun4|irix|esd|sp|portaudio|pa-oss|pa-alsa|pa-winmm|pa-dsound)" ac_help="$ac_help --with-netaudio-dir=DIR DatLink/NetAudio include/lib are in DIR" ac_help="$ac_help @@ -2321,12 +2321,13 @@ altype=$with_mictype fi -# if default is portaudio, guess WinMM / DirectSound / OSS / Solaris +# If PortAudio library found at the system, use it. +# if not, V19 codes included in this distribution will be compiled in. case $altype in portaudio) pa_system=no echo $ac_n "checking for Pa_Initialize in -lportaudio""... $ac_c" 1>&6 -echo "configure:2330: checking for Pa_Initialize in -lportaudio" >&5 +echo "configure:2331: checking for Pa_Initialize in -lportaudio" >&5 ac_lib_var=`echo portaudio'_'Pa_Initialize | sed 'y%./+-%__p_%'` if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then echo $ac_n "(cached) $ac_c" 1>&6 @@ -2334,7 +2335,7 @@ ac_save_LIBS="$LIBS" LIBS="-lportaudio $LIBS" cat > conftest.$ac_ext <&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then +if { (eval echo configure:2350: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then rm -rf conftest* eval "ac_cv_lib_$ac_lib_var=yes" else @@ -2364,17 +2365,17 @@ do ac_safe=`echo "$ac_hdr" | sed 'y%./+-%__p_%'` echo $ac_n "checking for $ac_hdr""... $ac_c" 1>&6 -echo "configure:2368: checking for $ac_hdr" >&5 +echo "configure:2369: checking for $ac_hdr" >&5 if eval "test \"`echo '$''{'ac_cv_header_$ac_safe'+set}'`\" = set"; then echo $ac_n "(cached) $ac_c" 1>&6 else cat > conftest.$ac_ext < EOF ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out" -{ (eval echo configure:2378: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } +{ (eval echo configure:2379: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"` if test -z "$ac_err"; then rm -rf conftest* @@ -2407,14 +2408,18 @@ if test "$pa_system" = no; then case "$host_os" in linux*) - altype="pa-oss" + if test "$has_alsa" = yes; then + altype="pa-alsa" + else + altype="pa-oss" + fi ;; solaris*) altype="pa-solaris" ;; cygwin*|mingw*) echo $ac_n "checking for main in -ldsound""... $ac_c" 1>&6 -echo "configure:2418: checking for main in -ldsound" >&5 +echo "configure:2423: checking for main in -ldsound" >&5 ac_lib_var=`echo dsound'_'main | sed 'y%./+-%__p_%'` if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then echo $ac_n "(cached) $ac_c" 1>&6 @@ -2422,14 +2427,14 @@ ac_save_LIBS="$LIBS" LIBS="-ldsound $LIBS" cat > conftest.$ac_ext <&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then +if { (eval echo configure:2438: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then rm -rf conftest* eval "ac_cv_lib_$ac_lib_var=yes" else @@ -2448,17 +2453,17 @@ do ac_safe=`echo "$ac_hdr" | sed 'y%./+-%__p_%'` echo $ac_n "checking for $ac_hdr""... $ac_c" 1>&6 -echo "configure:2452: checking for $ac_hdr" >&5 +echo "configure:2457: checking for $ac_hdr" >&5 if eval "test \"`echo '$''{'ac_cv_header_$ac_safe'+set}'`\" = set"; then echo $ac_n "(cached) $ac_c" 1>&6 else cat > conftest.$ac_ext < EOF ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out" -{ (eval echo configure:2462: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } +{ (eval echo configure:2467: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"` if test -z "$ac_err"; then rm -rf conftest* @@ -2532,7 +2537,7 @@ case "$host_os" in linux*) echo $ac_n "checking for spInitAudio in -lspa.linux""... $ac_c" 1>&6 -echo "configure:2536: checking for spInitAudio in -lspa.linux" >&5 +echo "configure:2541: checking for spInitAudio in -lspa.linux" >&5 ac_lib_var=`echo spa.linux'_'spInitAudio | sed 'y%./+-%__p_%'` if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then echo $ac_n "(cached) $ac_c" 1>&6 @@ -2540,7 +2545,7 @@ ac_save_LIBS="$LIBS" LIBS="-lspa.linux -lspb.linux -lm $LIBS" cat > conftest.$ac_ext <&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then +if { (eval echo configure:2560: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then rm -rf conftest* eval "ac_cv_lib_$ac_lib_var=yes" else @@ -2570,7 +2575,7 @@ else echo "$ac_t""no" 1>&6 echo $ac_n "checking for spInitAudio in -lspa.linux-glibc""... $ac_c" 1>&6 -echo "configure:2574: checking for spInitAudio in -lspa.linux-glibc" >&5 +echo "configure:2579: checking for spInitAudio in -lspa.linux-glibc" >&5 ac_lib_var=`echo spa.linux-glibc'_'spInitAudio | sed 'y%./+-%__p_%'` if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then echo $ac_n "(cached) $ac_c" 1>&6 @@ -2578,7 +2583,7 @@ ac_save_LIBS="$LIBS" LIBS="-lspa.linux-glibc -lspb.linux-glibc -lm $LIBS" cat > conftest.$ac_ext <&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then +if { (eval echo configure:2598: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then rm -rf conftest* eval "ac_cv_lib_$ac_lib_var=yes" else @@ -2641,8 +2646,8 @@ ;; pa-*) aldesc="PortAudio library (internal)" - ADINOBJ="$ADINOBJ src/adin/pa/pa_lib.o src/adin/pa/pa_convert.o src/adin/pa/pa_trace.o src/adin/pa/pablio.o src/adin/pa/ringbuffer.o" - SOUNDINC="-Isrc/adin/pa" + ADINOBJ="$ADINOBJ src/adin/pa/common/pa_allocation.o src/adin/pa/common/pa_converters.o src/adin/pa/common/pa_cpuload.o src/adin/pa/common/pa_debugprint.o src/adin/pa/common/pa_dither.o src/adin/pa/common/pa_front.o src/adin/pa/common/pa_process.o src/adin/pa/common/pa_ringbuffer.o src/adin/pa/common/pa_skeleton.o src/adin/pa/common/pa_stream.o src/adin/pa/common/pa_trace.o" + SOUNDINC="-Isrc/adin/pa/include -Isrc/adin/pa/common" cat >> confdefs.h <<\EOF #define USE_MIC 1 EOF @@ -2650,17 +2655,31 @@ case "$altype" in pa-winmm) aldesc="$aldesc (WinMM)" - ADINOBJ="$ADINOBJ src/adin/pa/pa_win_wmme.o" + SOUNDINC="$SOUNDINC -DPA_NO_DS -DPA_NO_ASIO" + ADINOBJ="$ADINOBJ src/adin/pa/os/win/pa_win_hostapis.o src/adin/pa/os/win/pa_win_util.o src/adin/pa/os/win/pa_win_waveformat.o" + ADINOBJ="$ADINOBJ src/adin/pa/hostapi/wmme/pa_win_wmme.o" SOUNDLIB="$SOUNDLIB -lwinmm" ;; pa-dsound) aldesc="$aldesc (DirectSound)" - ADINOBJ="$ADINOBJ src/adin/pa/dsound_wrapper.o src/adin/pa/pa_dsound.o" - SOUNDLIB="$SOUNDLIB -lwinmm -ldsound" + SOUNDINC="$SOUNDINC -Isrc/adin/pa/os/win -DPA_NO_ASIO" + ADINOBJ="$ADINOBJ src/adin/pa/os/win/pa_win_hostapis.o src/adin/pa/os/win/pa_win_util.o src/adin/pa/os/win/pa_win_waveformat.o" + ADINOBJ="$ADINOBJ src/adin/pa/hostapi/wmme/pa_win_wmme.o" + ADINOBJ="$ADINOBJ src/adin/pa/hostapi/dsound/pa_win_ds.o src/adin/pa/hostapi/dsound/pa_win_ds_dynlink.o" + SOUNDLIB="$SOUNDLIB -lwinmm -ldsound -lole32" + ;; + pa-alsa) + aldesc="$aldesc (Unix/ALSA)" + SOUNDINC="$SOUNDINC -Isrc/adin/pa/os/unix -DPA_USE_ALSA" + ADINOBJ="$ADINOBJ src/adin/pa/os/unix/pa_unix_hostapis.o src/adin/pa/os/unix/pa_unix_util.o" + ADINOBJ="$ADINOBJ src/adin/pa/hostapi/alsa/pa_linux_alsa.o" + SOUNDLIB="$SOUNDLIB -lpthread" ;; pa-oss) aldesc="$aldesc (Unix/OSS)" - ADINOBJ="$ADINOBJ src/adin/pa/pa_unix.o src/adin/pa/pa_unix_oss.o" + SOUNDINC="$SOUNDINC -Isrc/adin/pa/os/unix -DPA_USE_OSS" + ADINOBJ="$ADINOBJ src/adin/pa/os/unix/pa_unix_hostapis.o src/adin/pa/os/unix/pa_unix_util.o" + ADINOBJ="$ADINOBJ src/adin/pa/hostapi/oss/pa_unix_oss.o" SOUNDLIB="$SOUNDLIB -lpthread" ;; pa-solaris) @@ -2765,21 +2784,21 @@ if test "$with_netaudio_dir" = auto ; then echo $ac_n "checking for DatLink/NetAudio support""... $ac_c" 1>&6 -echo "configure:2769: checking for DatLink/NetAudio support" >&5 +echo "configure:2788: checking for DatLink/NetAudio support" >&5 else echo $ac_n "checking for DatLink/NetAudio support on ${with_netaudio_dir}""... $ac_c" 1>&6 -echo "configure:2772: checking for DatLink/NetAudio support on ${with_netaudio_dir}" >&5 +echo "configure:2791: checking for DatLink/NetAudio support on ${with_netaudio_dir}" >&5 fi TMPCPPFLAGS="$CPPFLAGS" CPPFLAGS="$CPPFLAGS -I${with_netaudio_dir}/include" use_netaudio=no cat > conftest.$ac_ext < EOF ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out" -{ (eval echo configure:2783: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } +{ (eval echo configure:2802: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"` if test -z "$ac_err"; then rm -rf conftest* @@ -2804,7 +2823,7 @@ have_zlib=no; if test "$use_zlib" = yes; then echo $ac_n "checking for deflate in -lz""... $ac_c" 1>&6 -echo "configure:2808: checking for deflate in -lz" >&5 +echo "configure:2827: checking for deflate in -lz" >&5 ac_lib_var=`echo z'_'deflate | sed 'y%./+-%__p_%'` if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then echo $ac_n "(cached) $ac_c" 1>&6 @@ -2812,7 +2831,7 @@ ac_save_LIBS="$LIBS" LIBS="-lz $LIBS" cat > conftest.$ac_ext <&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then +if { (eval echo configure:2846: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then rm -rf conftest* eval "ac_cv_lib_$ac_lib_var=yes" else @@ -2842,17 +2861,17 @@ do ac_safe=`echo "$ac_hdr" | sed 'y%./+-%__p_%'` echo $ac_n "checking for $ac_hdr""... $ac_c" 1>&6 -echo "configure:2846: checking for $ac_hdr" >&5 +echo "configure:2865: checking for $ac_hdr" >&5 if eval "test \"`echo '$''{'ac_cv_header_$ac_safe'+set}'`\" = set"; then echo $ac_n "(cached) $ac_c" 1>&6 else cat > conftest.$ac_ext < EOF ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out" -{ (eval echo configure:2856: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } +{ (eval echo configure:2875: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"` if test -z "$ac_err"; then rm -rf conftest* @@ -2897,7 +2916,7 @@ # Extract the first word of "gzip", so it can be a program name with args. set dummy gzip; ac_word=$2 echo $ac_n "checking for $ac_word""... $ac_c" 1>&6 -echo "configure:2901: checking for $ac_word" >&5 +echo "configure:2920: checking for $ac_word" >&5 if eval "test \"`echo '$''{'ac_cv_prog_GZIP'+set}'`\" = set"; then echo $ac_n "(cached) $ac_c" 1>&6 else @@ -2944,7 +2963,7 @@ if test "$with_sndfile" = yes; then have_libsndfile=no echo $ac_n "checking for sf_open in -lsndfile""... $ac_c" 1>&6 -echo "configure:2948: checking for sf_open in -lsndfile" >&5 +echo "configure:2967: checking for sf_open in -lsndfile" >&5 ac_lib_var=`echo sndfile'_'sf_open | sed 'y%./+-%__p_%'` if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then echo $ac_n "(cached) $ac_c" 1>&6 @@ -2952,7 +2971,7 @@ ac_save_LIBS="$LIBS" LIBS="-lsndfile $LIBS" cat > conftest.$ac_ext <&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then +if { (eval echo configure:2986: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then rm -rf conftest* eval "ac_cv_lib_$ac_lib_var=yes" else @@ -2982,17 +3001,17 @@ do ac_safe=`echo "$ac_hdr" | sed 'y%./+-%__p_%'` echo $ac_n "checking for $ac_hdr""... $ac_c" 1>&6 -echo "configure:2986: checking for $ac_hdr" >&5 +echo "configure:3005: checking for $ac_hdr" >&5 if eval "test \"`echo '$''{'ac_cv_header_$ac_safe'+set}'`\" = set"; then echo $ac_n "(cached) $ac_c" 1>&6 else cat > conftest.$ac_ext < EOF ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out" -{ (eval echo configure:2996: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } +{ (eval echo configure:3015: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"` if test -z "$ac_err"; then rm -rf conftest* @@ -3034,7 +3053,7 @@ if test "$have_libsndfile" = no; then echo $ac_n "checking for sf_open_read in -lsndfile""... $ac_c" 1>&6 -echo "configure:3038: checking for sf_open_read in -lsndfile" >&5 +echo "configure:3057: checking for sf_open_read in -lsndfile" >&5 ac_lib_var=`echo sndfile'_'sf_open_read | sed 'y%./+-%__p_%'` if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then echo $ac_n "(cached) $ac_c" 1>&6 @@ -3042,7 +3061,7 @@ ac_save_LIBS="$LIBS" LIBS="-lsndfile $LIBS" cat > conftest.$ac_ext <&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then +if { (eval echo configure:3076: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then rm -rf conftest* eval "ac_cv_lib_$ac_lib_var=yes" else @@ -3072,17 +3091,17 @@ do ac_safe=`echo "$ac_hdr" | sed 'y%./+-%__p_%'` echo $ac_n "checking for $ac_hdr""... $ac_c" 1>&6 -echo "configure:3076: checking for $ac_hdr" >&5 +echo "configure:3095: checking for $ac_hdr" >&5 if eval "test \"`echo '$''{'ac_cv_header_$ac_safe'+set}'`\" = set"; then echo $ac_n "(cached) $ac_c" 1>&6 else cat > conftest.$ac_ext < EOF ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out" -{ (eval echo configure:3086: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } +{ (eval echo configure:3105: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"` if test -z "$ac_err"; then rm -rf conftest* Index: julius4/libsent/configure.in diff -u julius4/libsent/configure.in:1.23 julius4/libsent/configure.in:1.24 --- julius4/libsent/configure.in:1.23 Mon May 17 18:04:17 2010 +++ julius4/libsent/configure.in Sat Feb 5 18:00:01 2011 @@ -3,7 +3,7 @@ dnl Copyright (c) 2005-2007 Julius project team, Nagoya Institute of Technology dnl All rights reserved dnl -dnl $Id: configure.in,v 1.23 2010/05/17 09:04:17 sumomo Exp $ +dnl $Id: configure.in,v 1.24 2011/02/05 09:00:01 sumomo Exp $ dnl dnl Process this file with autoconf to produce a configure script. @@ -16,7 +16,7 @@ dnl Checks for options # specify mic type AC_ARG_WITH(mictype, -[ --with-mictype=TYPE specify mic I/O (oss|alsa|freebsd|coreaudio|sol2|sun4|irix|esd|sp|portaudio|pa-oss|pa-winmm|pa-dsound)],,with_mictype=auto) +[ --with-mictype=TYPE specify mic I/O (oss|alsa|freebsd|coreaudio|sol2|sun4|irix|esd|sp|portaudio|pa-oss|pa-alsa|pa-winmm|pa-dsound)],,with_mictype=auto) # NetAudio support AC_ARG_WITH(netaudio-dir, @@ -251,7 +251,8 @@ altype=$with_mictype fi -# if default is portaudio, guess WinMM / DirectSound / OSS / Solaris +# If PortAudio library found at the system, use it. +# if not, V19 codes included in this distribution will be compiled in. case $altype in portaudio) pa_system=no @@ -259,7 +260,11 @@ if test "$pa_system" = no; then case "$host_os" in linux*) - altype="pa-oss" + if test "$has_alsa" = yes; then + altype="pa-alsa" + else + altype="pa-oss" + fi ;; solaris*) altype="pa-solaris" @@ -338,23 +343,37 @@ ;; pa-*) aldesc="PortAudio library (internal)" - ADINOBJ="$ADINOBJ src/adin/pa/pa_lib.o src/adin/pa/pa_convert.o src/adin/pa/pa_trace.o src/adin/pa/pablio.o src/adin/pa/ringbuffer.o" - SOUNDINC="-Isrc/adin/pa" + ADINOBJ="$ADINOBJ src/adin/pa/common/pa_allocation.o src/adin/pa/common/pa_converters.o src/adin/pa/common/pa_cpuload.o src/adin/pa/common/pa_debugprint.o src/adin/pa/common/pa_dither.o src/adin/pa/common/pa_front.o src/adin/pa/common/pa_process.o src/adin/pa/common/pa_ringbuffer.o src/adin/pa/common/pa_skeleton.o src/adin/pa/common/pa_stream.o src/adin/pa/common/pa_trace.o" + SOUNDINC="-Isrc/adin/pa/include -Isrc/adin/pa/common" AC_DEFINE(USE_MIC) case "$altype" in pa-winmm) aldesc="$aldesc (WinMM)" - ADINOBJ="$ADINOBJ src/adin/pa/pa_win_wmme.o" + SOUNDINC="$SOUNDINC -DPA_NO_DS -DPA_NO_ASIO" + ADINOBJ="$ADINOBJ src/adin/pa/os/win/pa_win_hostapis.o src/adin/pa/os/win/pa_win_util.o src/adin/pa/os/win/pa_win_waveformat.o" + ADINOBJ="$ADINOBJ src/adin/pa/hostapi/wmme/pa_win_wmme.o" SOUNDLIB="$SOUNDLIB -lwinmm" ;; pa-dsound) aldesc="$aldesc (DirectSound)" - ADINOBJ="$ADINOBJ src/adin/pa/dsound_wrapper.o src/adin/pa/pa_dsound.o" - SOUNDLIB="$SOUNDLIB -lwinmm -ldsound" + SOUNDINC="$SOUNDINC -Isrc/adin/pa/os/win -DPA_NO_ASIO" + ADINOBJ="$ADINOBJ src/adin/pa/os/win/pa_win_hostapis.o src/adin/pa/os/win/pa_win_util.o src/adin/pa/os/win/pa_win_waveformat.o" + ADINOBJ="$ADINOBJ src/adin/pa/hostapi/wmme/pa_win_wmme.o" + ADINOBJ="$ADINOBJ src/adin/pa/hostapi/dsound/pa_win_ds.o src/adin/pa/hostapi/dsound/pa_win_ds_dynlink.o" + SOUNDLIB="$SOUNDLIB -lwinmm -ldsound -lole32" + ;; + pa-alsa) + aldesc="$aldesc (Unix/ALSA)" + SOUNDINC="$SOUNDINC -Isrc/adin/pa/os/unix -DPA_USE_ALSA" + ADINOBJ="$ADINOBJ src/adin/pa/os/unix/pa_unix_hostapis.o src/adin/pa/os/unix/pa_unix_util.o" + ADINOBJ="$ADINOBJ src/adin/pa/hostapi/alsa/pa_linux_alsa.o" + SOUNDLIB="$SOUNDLIB -lpthread" ;; pa-oss) aldesc="$aldesc (Unix/OSS)" - ADINOBJ="$ADINOBJ src/adin/pa/pa_unix.o src/adin/pa/pa_unix_oss.o" + SOUNDINC="$SOUNDINC -Isrc/adin/pa/os/unix -DPA_USE_OSS" + ADINOBJ="$ADINOBJ src/adin/pa/os/unix/pa_unix_hostapis.o src/adin/pa/os/unix/pa_unix_util.o" + ADINOBJ="$ADINOBJ src/adin/pa/hostapi/oss/pa_unix_oss.o" SOUNDLIB="$SOUNDLIB -lpthread" ;; pa-solaris) From sumomo @ users.sourceforge.jp Sat Feb 5 18:00:04 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Sat, 05 Feb 2011 18:00:04 +0900 Subject: [Julius-cvs 577] CVS update: julius4/libsent/src/adin/pa/os/unix Message-ID: <1296896404.048976.28800.nullmailer@users.sourceforge.jp> Index: julius4/libsent/src/adin/pa/os/unix/pa_unix_hostapis.c diff -u /dev/null julius4/libsent/src/adin/pa/os/unix/pa_unix_hostapis.c:1.1 --- /dev/null Sat Feb 5 18:00:04 2011 +++ julius4/libsent/src/adin/pa/os/unix/pa_unix_hostapis.c Sat Feb 5 18:00:03 2011 @@ -0,0 +1,78 @@ +/* + * $Id: pa_unix_hostapis.c,v 1.1 2011/02/05 09:00:03 sumomo Exp $ + * Portable Audio I/O Library UNIX initialization table + * + * Based on the Open Source API proposed by Ross Bencina + * Copyright (c) 1999-2002 Ross Bencina, Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/* + * The text above constitutes the entire PortAudio license; however, + * the PortAudio community also makes the following non-binding requests: + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. It is also + * requested that these non-binding requests be included along with the + * license above. + */ + +/** @file + @ingroup unix_src +*/ + +#include "pa_hostapi.h" + +PaError PaJack_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index ); +PaError PaAlsa_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index ); +PaError PaOSS_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index ); +/* Added for IRIX, Pieter, oct 2, 2003: */ +PaError PaSGI_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index ); +/* Linux AudioScience HPI */ +PaError PaAsiHpi_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index ); + + +PaUtilHostApiInitializer *paHostApiInitializers[] = + { +#ifdef PA_USE_OSS + PaOSS_Initialize, +#endif + +#ifdef PA_USE_ALSA + PaAlsa_Initialize, +#endif + +#ifdef PA_USE_JACK + PaJack_Initialize, +#endif + /* Added for IRIX, Pieter, oct 2, 2003: */ +#ifdef PA_USE_SGI + PaSGI_Initialize, +#endif + +#ifdef PA_USE_ASIHPI + PaAsiHpi_Initialize, +#endif + 0 /* NULL terminated array */ + }; + +int paDefaultHostApiIndex = 0; Index: julius4/libsent/src/adin/pa/os/unix/pa_unix_util.c diff -u /dev/null julius4/libsent/src/adin/pa/os/unix/pa_unix_util.c:1.1 --- /dev/null Sat Feb 5 18:00:04 2011 +++ julius4/libsent/src/adin/pa/os/unix/pa_unix_util.c Sat Feb 5 18:00:03 2011 @@ -0,0 +1,666 @@ +/* + * $Id: pa_unix_util.c,v 1.1 2011/02/05 09:00:03 sumomo Exp $ + * Portable Audio I/O Library + * UNIX platform-specific support functions + * + * Based on the Open Source API proposed by Ross Bencina + * Copyright (c) 1999-2000 Ross Bencina + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/* + * The text above constitutes the entire PortAudio license; however, + * the PortAudio community also makes the following non-binding requests: + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. It is also + * requested that these non-binding requests be included along with the + * license above. + */ + +/** @file + @ingroup unix_src +*/ + +#include +#include +#include +#include +#include +#include +#include /* For memset */ +#include +#include + +#include "pa_util.h" +#include "pa_unix_util.h" +#include "pa_debugprint.h" + +/* + Track memory allocations to avoid leaks. + */ + +#if PA_TRACK_MEMORY +static int numAllocations_ = 0; +#endif + + +void *PaUtil_AllocateMemory( long size ) +{ + void *result = malloc( size ); + +#if PA_TRACK_MEMORY + if( result != NULL ) numAllocations_ += 1; +#endif + return result; +} + + +void PaUtil_FreeMemory( void *block ) +{ + if( block != NULL ) + { + free( block ); +#if PA_TRACK_MEMORY + numAllocations_ -= 1; +#endif + + } +} + + +int PaUtil_CountCurrentlyAllocatedBlocks( void ) +{ +#if PA_TRACK_MEMORY + return numAllocations_; +#else + return 0; +#endif +} + + +void Pa_Sleep( long msec ) +{ +#ifdef HAVE_NANOSLEEP + struct timespec req = {0}, rem = {0}; + PaTime time = msec / 1.e3; + req.tv_sec = (time_t)time; + assert(time - req.tv_sec < 1.0); + req.tv_nsec = (long)((time - req.tv_sec) * 1.e9); + nanosleep(&req, &rem); + /* XXX: Try sleeping the remaining time (contained in rem) if interrupted by a signal? */ +#else + while( msec > 999 ) /* For OpenBSD and IRIX, argument */ + { /* to usleep must be < 1000000. */ + usleep( 999000 ); + msec -= 999; + } + usleep( msec * 1000 ); +#endif +} + +/* *** NOT USED YET: *** +static int usePerformanceCounter_; +static double microsecondsPerTick_; +*/ + +void PaUtil_InitializeClock( void ) +{ + /* TODO */ +} + + +PaTime PaUtil_GetTime( void ) +{ +#ifdef HAVE_CLOCK_GETTIME + struct timespec tp; + clock_gettime(CLOCK_REALTIME, &tp); + return (PaTime)(tp.tv_sec + tp.tv_nsec / 1.e9); +#else + struct timeval tv; + gettimeofday( &tv, NULL ); + return (PaTime) tv.tv_usec / 1000000. + tv.tv_sec; +#endif +} + +PaError PaUtil_InitializeThreading( PaUtilThreading *threading ) +{ + (void) paUtilErr_; + return paNoError; +} + +void PaUtil_TerminateThreading( PaUtilThreading *threading ) +{ +} + +PaError PaUtil_StartThreading( PaUtilThreading *threading, void *(*threadRoutine)(void *), void *data ) +{ + pthread_create( &threading->callbackThread, NULL, threadRoutine, data ); + return paNoError; +} + +PaError PaUtil_CancelThreading( PaUtilThreading *threading, int wait, PaError *exitResult ) +{ + PaError result = paNoError; + void *pret; + + if( exitResult ) + *exitResult = paNoError; + + /* Only kill the thread if it isn't in the process of stopping (flushing adaptation buffers) */ + if( !wait ) + pthread_cancel( threading->callbackThread ); /* XXX: Safe to call this if the thread has exited on its own? */ + pthread_join( threading->callbackThread, &pret ); + +#ifdef PTHREAD_CANCELED + if( pret && PTHREAD_CANCELED != pret ) +#else + /* !wait means the thread may have been canceled */ + if( pret && wait ) +#endif + { + if( exitResult ) + *exitResult = *(PaError *) pret; + free( pret ); + } + + return result; +} + +/* Threading */ +/* paUnixMainThread + * We have to be a bit careful with defining this global variable, + * as explained below. */ +#ifdef __apple__ +/* apple/gcc has a "problem" with global vars and dynamic libs. + Initializing it seems to fix the problem. + Described a bit in this thread: + http://gcc.gnu.org/ml/gcc/2005-06/msg00179.html +*/ +pthread_t paUnixMainThread = 0; +#else +/*pthreads are opaque. We don't know that asigning it an int value + always makes sense, so we don't initialize it unless we have to.*/ +pthread_t paUnixMainThread = 0; +#endif + +PaError PaUnixThreading_Initialize() +{ + paUnixMainThread = pthread_self(); + return paNoError; +} + +static PaError BoostPriority( PaUnixThread* self ) +{ + PaError result = paNoError; + struct sched_param spm = { 0 }; + /* Priority should only matter between contending FIFO threads? */ + spm.sched_priority = 1; + + assert( self ); + + if( pthread_setschedparam( self->thread, SCHED_FIFO, &spm ) != 0 ) + { + PA_UNLESS( errno == EPERM, paInternalError ); /* Lack permission to raise priority */ + PA_DEBUG(( "Failed bumping priority\n" )); + result = 0; + } + else + { + result = 1; /* Success */ + } +error: + return result; +} + +PaError PaUnixThread_New( PaUnixThread* self, void* (*threadFunc)( void* ), void* threadArg, PaTime waitForChild, + int rtSched ) +{ + PaError result = paNoError; + pthread_attr_t attr; + int started = 0; + + memset( self, 0, sizeof (PaUnixThread) ); + PaUnixMutex_Initialize( &self->mtx ); + PA_ASSERT_CALL( pthread_cond_init( &self->cond, NULL ), 0 ); + + self->parentWaiting = 0 != waitForChild; + + /* Spawn thread */ + +/* Temporarily disabled since we should test during configuration for presence of required mman.h header */ +#if 0 +#if defined _POSIX_MEMLOCK && (_POSIX_MEMLOCK != -1) + if( rtSched ) + { + if( mlockall( MCL_CURRENT | MCL_FUTURE ) < 0 ) + { + int savedErrno = errno; /* In case errno gets overwritten */ + assert( savedErrno != EINVAL ); /* Most likely a programmer error */ + PA_UNLESS( (savedErrno == EPERM), paInternalError ); + PA_DEBUG(( "%s: Failed locking memory\n", __FUNCTION__ )); + } + else + PA_DEBUG(( "%s: Successfully locked memory\n", __FUNCTION__ )); + } +#endif +#endif + + PA_UNLESS( !pthread_attr_init( &attr ), paInternalError ); + /* Priority relative to other processes */ + PA_UNLESS( !pthread_attr_setscope( &attr, PTHREAD_SCOPE_SYSTEM ), paInternalError ); + + PA_UNLESS( !pthread_create( &self->thread, &attr, threadFunc, threadArg ), paInternalError ); + started = 1; + + if( rtSched ) + { +#if 0 + if( self->useWatchdog ) + { + int err; + struct sched_param wdSpm = { 0 }; + /* Launch watchdog, watchdog sets callback thread priority */ + int prio = PA_MIN( self->rtPrio + 4, sched_get_priority_max( SCHED_FIFO ) ); + wdSpm.sched_priority = prio; + + PA_UNLESS( !pthread_attr_init( &attr ), paInternalError ); + PA_UNLESS( !pthread_attr_setinheritsched( &attr, PTHREAD_EXPLICIT_SCHED ), paInternalError ); + PA_UNLESS( !pthread_attr_setscope( &attr, PTHREAD_SCOPE_SYSTEM ), paInternalError ); + PA_UNLESS( !pthread_attr_setschedpolicy( &attr, SCHED_FIFO ), paInternalError ); + PA_UNLESS( !pthread_attr_setschedparam( &attr, &wdSpm ), paInternalError ); + if( (err = pthread_create( &self->watchdogThread, &attr, &WatchdogFunc, self )) ) + { + PA_UNLESS( err == EPERM, paInternalError ); + /* Permission error, go on without realtime privileges */ + PA_DEBUG(( "Failed bumping priority\n" )); + } + else + { + int policy; + self->watchdogRunning = 1; + PA_ENSURE_SYSTEM( pthread_getschedparam( self->watchdogThread, &policy, &wdSpm ), 0 ); + /* Check if priority is right, policy could potentially differ from SCHED_FIFO (but that's alright) */ + if( wdSpm.sched_priority != prio ) + { + PA_DEBUG(( "Watchdog priority not set correctly (%d)\n", wdSpm.sched_priority )); + PA_ENSURE( paInternalError ); + } + } + } + else +#endif + PA_ENSURE( BoostPriority( self ) ); + + { + int policy; + struct sched_param spm; + pthread_getschedparam(self->thread, &policy, &spm); + } + } + + if( self->parentWaiting ) + { + PaTime till; + struct timespec ts; + int res = 0; + PaTime now; + + PA_ENSURE( PaUnixMutex_Lock( &self->mtx ) ); + + /* Wait for stream to be started */ + now = PaUtil_GetTime(); + till = now + waitForChild; + + while( self->parentWaiting && !res ) + { + if( waitForChild > 0 ) + { + ts.tv_sec = (time_t) floor( till ); + ts.tv_nsec = (long) ((till - floor( till )) * 1e9); + res = pthread_cond_timedwait( &self->cond, &self->mtx.mtx, &ts ); + } + else + { + res = pthread_cond_wait( &self->cond, &self->mtx.mtx ); + } + } + + PA_ENSURE( PaUnixMutex_Unlock( &self->mtx ) ); + + PA_UNLESS( !res || ETIMEDOUT == res, paInternalError ); + PA_DEBUG(( "%s: Waited for %g seconds for stream to start\n", __FUNCTION__, PaUtil_GetTime() - now )); + if( ETIMEDOUT == res ) + { + PA_ENSURE( paTimedOut ); + } + } + +end: + return result; +error: + if( started ) + { + PaUnixThread_Terminate( self, 0, NULL ); + } + + goto end; +} + +PaError PaUnixThread_Terminate( PaUnixThread* self, int wait, PaError* exitResult ) +{ + PaError result = paNoError; + void* pret; + + if( exitResult ) + { + *exitResult = paNoError; + } +#if 0 + if( watchdogExitResult ) + *watchdogExitResult = paNoError; + + if( th->watchdogRunning ) + { + pthread_cancel( th->watchdogThread ); + PA_ENSURE_SYSTEM( pthread_join( th->watchdogThread, &pret ), 0 ); + + if( pret && pret != PTHREAD_CANCELED ) + { + if( watchdogExitResult ) + *watchdogExitResult = *(PaError *) pret; + free( pret ); + } + } +#endif + + /* Only kill the thread if it isn't in the process of stopping (flushing adaptation buffers) */ + /* TODO: Make join time out */ + self->stopRequested = wait; + if( !wait ) + { + PA_DEBUG(( "%s: Canceling thread %d\n", __FUNCTION__, self->thread )); + /* XXX: Safe to call this if the thread has exited on its own? */ + pthread_cancel( self->thread ); + } + PA_DEBUG(( "%s: Joining thread %d\n", __FUNCTION__, self->thread )); + PA_ENSURE_SYSTEM( pthread_join( self->thread, &pret ), 0 ); + + if( pret && PTHREAD_CANCELED != pret ) + { + if( exitResult ) + { + *exitResult = *(PaError*)pret; + } + free( pret ); + } + +error: + PA_ASSERT_CALL( PaUnixMutex_Terminate( &self->mtx ), paNoError ); + PA_ASSERT_CALL( pthread_cond_destroy( &self->cond ), 0 ); + + return result; +} + +PaError PaUnixThread_PrepareNotify( PaUnixThread* self ) +{ + PaError result = paNoError; + PA_UNLESS( self->parentWaiting, paInternalError ); + + PA_ENSURE( PaUnixMutex_Lock( &self->mtx ) ); + self->locked = 1; + +error: + return result; +} + +PaError PaUnixThread_NotifyParent( PaUnixThread* self ) +{ + PaError result = paNoError; + PA_UNLESS( self->parentWaiting, paInternalError ); + + if( !self->locked ) + { + PA_ENSURE( PaUnixMutex_Lock( &self->mtx ) ); + self->locked = 1; + } + self->parentWaiting = 0; + pthread_cond_signal( &self->cond ); + PA_ENSURE( PaUnixMutex_Unlock( &self->mtx ) ); + self->locked = 0; + +error: + return result; +} + +int PaUnixThread_StopRequested( PaUnixThread* self ) +{ + return self->stopRequested; +} + +PaError PaUnixMutex_Initialize( PaUnixMutex* self ) +{ + PaError result = paNoError; + PA_ASSERT_CALL( pthread_mutex_init( &self->mtx, NULL ), 0 ); + return result; +} + +PaError PaUnixMutex_Terminate( PaUnixMutex* self ) +{ + PaError result = paNoError; + PA_ASSERT_CALL( pthread_mutex_destroy( &self->mtx ), 0 ); + return result; +} + +/** Lock mutex. + * + * We're disabling thread cancellation while the thread is holding a lock, so mutexes are + * properly unlocked at termination time. + */ +PaError PaUnixMutex_Lock( PaUnixMutex* self ) +{ + PaError result = paNoError; + int oldState; + + PA_ENSURE_SYSTEM( pthread_setcancelstate( PTHREAD_CANCEL_DISABLE, &oldState ), 0 ); + PA_ENSURE_SYSTEM( pthread_mutex_lock( &self->mtx ), 0 ); + +error: + return result; +} + +/** Unlock mutex. + * + * Thread cancellation is enabled again after the mutex is properly unlocked. + */ +PaError PaUnixMutex_Unlock( PaUnixMutex* self ) +{ + PaError result = paNoError; + int oldState; + + PA_ENSURE_SYSTEM( pthread_mutex_unlock( &self->mtx ), 0 ); + PA_ENSURE_SYSTEM( pthread_setcancelstate( PTHREAD_CANCEL_ENABLE, &oldState ), 0 ); + +error: + return result; +} + + +#if 0 +static void OnWatchdogExit( void *userData ) +{ + PaAlsaThreading *th = (PaAlsaThreading *) userData; + struct sched_param spm = { 0 }; + assert( th ); + + PA_ASSERT_CALL( pthread_setschedparam( th->callbackThread, SCHED_OTHER, &spm ), 0 ); /* Lower before exiting */ + PA_DEBUG(( "Watchdog exiting\n" )); +} + +static void *WatchdogFunc( void *userData ) +{ + PaError result = paNoError, *pres = NULL; + int err; + PaAlsaThreading *th = (PaAlsaThreading *) userData; + unsigned intervalMsec = 500; + const PaTime maxSeconds = 3.; /* Max seconds between callbacks */ + PaTime timeThen = PaUtil_GetTime(), timeNow, timeElapsed, cpuTimeThen, cpuTimeNow, cpuTimeElapsed; + double cpuLoad, avgCpuLoad = 0.; + int throttled = 0; + + assert( th ); + + /* Execute OnWatchdogExit when exiting */ + pthread_cleanup_push( &OnWatchdogExit, th ); + + /* Boost priority of callback thread */ + PA_ENSURE( result = BoostPriority( th ) ); + if( !result ) + { + /* Boost failed, might as well exit */ + pthread_exit( NULL ); + } + + cpuTimeThen = th->callbackCpuTime; + { + int policy; + struct sched_param spm = { 0 }; + pthread_getschedparam( pthread_self(), &policy, &spm ); + PA_DEBUG(( "%s: Watchdog priority is %d\n", __FUNCTION__, spm.sched_priority )); + } + + while( 1 ) + { + double lowpassCoeff = 0.9, lowpassCoeff1 = 0.99999 - lowpassCoeff; + + /* Test before and after in case whatever underlying sleep call isn't interrupted by pthread_cancel */ + pthread_testcancel(); + Pa_Sleep( intervalMsec ); + pthread_testcancel(); + + if( PaUtil_GetTime() - th->callbackTime > maxSeconds ) + { + PA_DEBUG(( "Watchdog: Terminating callback thread\n" )); + /* Tell thread to terminate */ + err = pthread_kill( th->callbackThread, SIGKILL ); + pthread_exit( NULL ); + } + + PA_DEBUG(( "%s: PortAudio reports CPU load: %g\n", __FUNCTION__, PaUtil_GetCpuLoad( th->cpuLoadMeasurer ) )); + + /* Check if we should throttle, or unthrottle :P */ + cpuTimeNow = th->callbackCpuTime; + cpuTimeElapsed = cpuTimeNow - cpuTimeThen; + cpuTimeThen = cpuTimeNow; + + timeNow = PaUtil_GetTime(); + timeElapsed = timeNow - timeThen; + timeThen = timeNow; + cpuLoad = cpuTimeElapsed / timeElapsed; + avgCpuLoad = avgCpuLoad * lowpassCoeff + cpuLoad * lowpassCoeff1; + /* + if( throttled ) + PA_DEBUG(( "Watchdog: CPU load: %g, %g\n", avgCpuLoad, cpuTimeElapsed )); + */ + if( PaUtil_GetCpuLoad( th->cpuLoadMeasurer ) > .925 ) + { + static int policy; + static struct sched_param spm = { 0 }; + static const struct sched_param defaultSpm = { 0 }; + PA_DEBUG(( "%s: Throttling audio thread, priority %d\n", __FUNCTION__, spm.sched_priority )); + + pthread_getschedparam( th->callbackThread, &policy, &spm ); + if( !pthread_setschedparam( th->callbackThread, SCHED_OTHER, &defaultSpm ) ) + { + throttled = 1; + } + else + PA_DEBUG(( "Watchdog: Couldn't lower priority of audio thread: %s\n", strerror( errno ) )); + + /* Give other processes a go, before raising priority again */ + PA_DEBUG(( "%s: Watchdog sleeping for %lu msecs before unthrottling\n", __FUNCTION__, th->throttledSleepTime )); + Pa_Sleep( th->throttledSleepTime ); + + /* Reset callback priority */ + if( pthread_setschedparam( th->callbackThread, SCHED_FIFO, &spm ) != 0 ) + { + PA_DEBUG(( "%s: Couldn't raise priority of audio thread: %s\n", __FUNCTION__, strerror( errno ) )); + } + + if( PaUtil_GetCpuLoad( th->cpuLoadMeasurer ) >= .99 ) + intervalMsec = 50; + else + intervalMsec = 100; + + /* + lowpassCoeff = .97; + lowpassCoeff1 = .99999 - lowpassCoeff; + */ + } + else if( throttled && avgCpuLoad < .8 ) + { + intervalMsec = 500; + throttled = 0; + + /* + lowpassCoeff = .9; + lowpassCoeff1 = .99999 - lowpassCoeff; + */ + } + } + + pthread_cleanup_pop( 1 ); /* Execute cleanup on exit */ + +error: + /* Shouldn't get here in the normal case */ + + /* Pass on error code */ + pres = malloc( sizeof (PaError) ); + *pres = result; + + pthread_exit( pres ); +} + +static void CallbackUpdate( PaAlsaThreading *th ) +{ + th->callbackTime = PaUtil_GetTime(); + th->callbackCpuTime = PaUtil_GetCpuLoad( th->cpuLoadMeasurer ); +} + +/* +static void *CanaryFunc( void *userData ) +{ + const unsigned intervalMsec = 1000; + PaUtilThreading *th = (PaUtilThreading *) userData; + + while( 1 ) + { + th->canaryTime = PaUtil_GetTime(); + + pthread_testcancel(); + Pa_Sleep( intervalMsec ); + } + + pthread_exit( NULL ); +} +*/ +#endif Index: julius4/libsent/src/adin/pa/os/unix/pa_unix_util.h diff -u /dev/null julius4/libsent/src/adin/pa/os/unix/pa_unix_util.h:1.1 --- /dev/null Sat Feb 5 18:00:04 2011 +++ julius4/libsent/src/adin/pa/os/unix/pa_unix_util.h Sat Feb 5 18:00:03 2011 @@ -0,0 +1,224 @@ +/* + * $Id: pa_unix_util.h,v 1.1 2011/02/05 09:00:03 sumomo Exp $ + * Portable Audio I/O Library + * UNIX platform-specific support functions + * + * Based on the Open Source API proposed by Ross Bencina + * Copyright (c) 1999-2000 Ross Bencina + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/* + * The text above constitutes the entire PortAudio license; however, + * the PortAudio community also makes the following non-binding requests: + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. It is also + * requested that these non-binding requests be included along with the + * license above. + */ + +/** @file + @ingroup unix_src +*/ + +#ifndef PA_UNIX_UTIL_H +#define PA_UNIX_UTIL_H + +#include "pa_cpuload.h" +#include +#include +#include + +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +#define PA_MIN(x,y) ( (x) < (y) ? (x) : (y) ) +#define PA_MAX(x,y) ( (x) > (y) ? (x) : (y) ) + +/* Utilize GCC branch prediction for error tests */ +#if defined __GNUC__ && __GNUC__ >= 3 +#define UNLIKELY(expr) __builtin_expect( (expr), 0 ) +#else +#define UNLIKELY(expr) (expr) +#endif + +#define STRINGIZE_HELPER(expr) #expr +#define STRINGIZE(expr) STRINGIZE_HELPER(expr) + +#define PA_UNLESS(expr, code) \ + do { \ + if( UNLIKELY( (expr) == 0 ) ) \ + { \ + PaUtil_DebugPrint(( "Expression '" #expr "' failed in '" __FILE__ "', line: " STRINGIZE( __LINE__ ) "\n" )); \ + result = (code); \ + goto error; \ + } \ + } while (0); + +static PaError paUtilErr_; /* Used with PA_ENSURE */ + +/* Check PaError */ +#define PA_ENSURE(expr) \ + do { \ + if( UNLIKELY( (paUtilErr_ = (expr)) < paNoError ) ) \ + { \ + PaUtil_DebugPrint(( "Expression '" #expr "' failed in '" __FILE__ "', line: " STRINGIZE( __LINE__ ) "\n" )); \ + result = paUtilErr_; \ + goto error; \ + } \ + } while (0); + +#define PA_ASSERT_CALL(expr, success) \ + paUtilErr_ = (expr); \ + assert( success == paUtilErr_ ); + +#define PA_ENSURE_SYSTEM(expr, success) \ + do { \ + if( UNLIKELY( (paUtilErr_ = (expr)) != success ) ) \ + { \ + /* PaUtil_SetLastHostErrorInfo should only be used in the main thread */ \ + if( pthread_equal(pthread_self(), paUnixMainThread) ) \ + { \ + PaUtil_SetLastHostErrorInfo( paALSA, paUtilErr_, strerror( paUtilErr_ ) ); \ + } \ + PaUtil_DebugPrint( "Expression '" #expr "' failed in '" __FILE__ "', line: " STRINGIZE( __LINE__ ) "\n" ); \ + result = paUnanticipatedHostError; \ + goto error; \ + } \ + } while( 0 ); + +typedef struct { + pthread_t callbackThread; +} PaUtilThreading; + +PaError PaUtil_InitializeThreading( PaUtilThreading *threading ); +void PaUtil_TerminateThreading( PaUtilThreading *threading ); +PaError PaUtil_StartThreading( PaUtilThreading *threading, void *(*threadRoutine)(void *), void *data ); +PaError PaUtil_CancelThreading( PaUtilThreading *threading, int wait, PaError *exitResult ); + +/* State accessed by utility functions */ + +/* +void PaUnix_SetRealtimeScheduling( int rt ); + +void PaUtil_InitializeThreading( PaUtilThreading *th, PaUtilCpuLoadMeasurer *clm ); + +PaError PaUtil_CreateCallbackThread( PaUtilThreading *th, void *(*CallbackThreadFunc)( void * ), PaStream *s ); + +PaError PaUtil_KillCallbackThread( PaUtilThreading *th, PaError *exitResult ); + +void PaUtil_CallbackUpdate( PaUtilThreading *th ); +*/ + +extern pthread_t paUnixMainThread; + +typedef struct +{ + pthread_mutex_t mtx; +} PaUnixMutex; + +PaError PaUnixMutex_Initialize( PaUnixMutex* self ); +PaError PaUnixMutex_Terminate( PaUnixMutex* self ); +PaError PaUnixMutex_Lock( PaUnixMutex* self ); +PaError PaUnixMutex_Unlock( PaUnixMutex* self ); + +typedef struct +{ + pthread_t thread; + int parentWaiting; + int stopRequested; + int locked; + PaUnixMutex mtx; + pthread_cond_t cond; + volatile sig_atomic_t stopRequest; +} PaUnixThread; + +/** Initialize global threading state. + */ +PaError PaUnixThreading_Initialize(); + +/** Perish, passing on eventual error code. + * + * A thin wrapper around pthread_exit, will automatically pass on any error code to the joining thread. + * If the result indicates an error, i.e. it is not equal to paNoError, this function will automatically + * allocate a pointer so the error is passed on with pthread_exit. If the result indicates that all is + * well however, only a NULL pointer will be handed to pthread_exit. Thus, the joining thread should + * check whether a non-NULL result pointer is obtained from pthread_join and make sure to free it. + * @param result: The error code to pass on to the joining thread. + */ +#define PaUnixThreading_EXIT(result) \ + do { \ + PaError* pres = NULL; \ + if( paNoError != (result) ) \ + { \ + pres = malloc( sizeof (PaError) ); \ + *pres = (result); \ + } \ + pthread_exit( pres ); \ + } while (0); + +/** Spawn a thread. + * + * Intended for spawning the callback thread from the main thread. This function can even block (for a certain + * time or indefinitely) untill notified by the callback thread (using PaUnixThread_NotifyParent), which can be + * useful in order to make sure that callback has commenced before returning from Pa_StartStream. + * @param threadFunc: The function to be executed in the child thread. + * @param waitForChild: If not 0, wait for child thread to call PaUnixThread_NotifyParent. Less than 0 means + * wait for ever, greater than 0 wait for the specified time. + * @param rtSched: Enable realtime scheduling? + * @return: If timed out waiting on child, paTimedOut. + */ +PaError PaUnixThread_New( PaUnixThread* self, void* (*threadFunc)( void* ), void* threadArg, PaTime waitForChild, + int rtSched ); + +/** Terminate thread. + * + * @param wait: If true, request that background thread stop and wait untill it does, else cancel it. + * @param exitResult: If non-null this will upon return contain the exit status of the thread. + */ +PaError PaUnixThread_Terminate( PaUnixThread* self, int wait, PaError* exitResult ); + +/** Prepare to notify waiting parent thread. + * + * An internal lock must be held before the parent is notified in PaUnixThread_NotifyParent, call this to + * acquire it beforehand. + * @return: If parent is not waiting, paInternalError. + */ +PaError PaUnixThread_PrepareNotify( PaUnixThread* self ); + +/** Notify waiting parent thread. + * + * @return: If parent timed out waiting, paTimedOut. If parent was never waiting, paInternalError. + */ +PaError PaUnixThread_NotifyParent( PaUnixThread* self ); + +/** Has the parent thread requested this thread to stop? + */ +int PaUnixThread_StopRequested( PaUnixThread* self ); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ +#endif From sumomo @ users.sourceforge.jp Sat Feb 5 18:00:03 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Sat, 05 Feb 2011 18:00:03 +0900 Subject: [Julius-cvs 578] CVS update: julius4/libsent/src/adin/pa/os/mac_osx Message-ID: <1296896403.956733.28742.nullmailer@users.sourceforge.jp> Index: julius4/libsent/src/adin/pa/os/mac_osx/pa_mac_hostapis.c diff -u /dev/null julius4/libsent/src/adin/pa/os/mac_osx/pa_mac_hostapis.c:1.1 --- /dev/null Sat Feb 5 18:00:03 2011 +++ julius4/libsent/src/adin/pa/os/mac_osx/pa_mac_hostapis.c Sat Feb 5 18:00:03 2011 @@ -0,0 +1,87 @@ +/* + * $Id: pa_mac_hostapis.c,v 1.1 2011/02/05 09:00:03 sumomo Exp $ + * Portable Audio I/O Library Macintosh initialization table + * + * Based on the Open Source API proposed by Ross Bencina + * Copyright (c) 1999-2002 Ross Bencina, Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/* + * The text above constitutes the entire PortAudio license; however, + * the PortAudio community also makes the following non-binding requests: + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. It is also + * requested that these non-binding requests be included along with the + * license above. + */ + +/** @file + @ingroup macosx_src +Mac OS host API initialization function table. +*/ + + +#include "pa_hostapi.h" + +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + + PaError PaSkeleton_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index ); + PaError PaMacCore_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index ); + PaError PaMacSm_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index ); + PaError PaJack_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index ); + PaError PaMacAsio_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index ); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + + +PaUtilHostApiInitializer *paHostApiInitializers[] = +{ +#ifdef PA_USE_COREAUDIO + PaMacCore_Initialize, +#endif + +#ifdef PA_USE_SM + PaMacSm_Initialize, +#endif + +#ifdef PA_USE_JACK + PaJack_Initialize, +#endif + +#ifdef PA_USE_ASIO + PaMacAsio_Initialize, +#endif + + PaSkeleton_Initialize, /* just for testing */ + + 0 /* NULL terminated array */ +}; + + +int paDefaultHostApiIndex = 0; From sumomo @ users.sourceforge.jp Sat Feb 5 18:00:01 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Sat, 05 Feb 2011 18:00:01 +0900 Subject: [Julius-cvs 579] CVS update: julius4/libsent/src/adin Message-ID: <1296896401.872656.27655.nullmailer@users.sourceforge.jp> Index: julius4/libsent/src/adin/adin_portaudio.c diff -u julius4/libsent/src/adin/adin_portaudio.c:1.12 julius4/libsent/src/adin/adin_portaudio.c:1.13 --- julius4/libsent/src/adin/adin_portaudio.c:1.12 Fri Dec 11 14:30:17 2009 +++ julius4/libsent/src/adin/adin_portaudio.c Sat Feb 5 18:00:01 2011 @@ -56,7 +56,7 @@ * @author Akinobu LEE * @date Mon Feb 14 12:03:48 2005 * - * $Revision: 1.12 $ + * $Revision: 1.13 $ * */ /* @@ -197,6 +197,152 @@ #else static PaStream *stream; ///< Stream information #endif +static int srate; ///< Required sampling rate + + +#ifdef CHOOSE_HOST_API + +// Get device list +// If first argument is NULL, return the maximum number of devices +int +get_device_list(int *devidlist, char **namelist, int maxstrlen, int maxnum) +{ + PaDeviceIndex numDevice = Pa_GetDeviceCount(), i; + const PaDeviceInfo *deviceInfo; + const PaHostApiInfo *apiInfo; + static char buf[256]; + int n; + + n = 0; + for(i=0;imaxInputChannels <= 0) continue; + apiInfo = Pa_GetHostApiInfo(deviceInfo->hostApi); + if (!apiInfo) continue; + if (devidlist != NULL) { + if ( n >= maxnum ) break; + snprintf(buf, 255, "%s: %s", apiInfo->name, deviceInfo->name); + buf[255] = '\0'; + devidlist[n] = i; + strncpy(namelist[n], buf, maxstrlen); + } + n++; + } + + return n; +} + +// Automatically choose a device to open +// +// 1. if the env value of "PORTAUDIO_DEV" is defined and matches any of +// "apiInfo->name: deviceInfo->name" string, use it. +// 2. if the env value "PORTAUDIO_DEV_NUM" is defined, use the (value-1) +// as device id. +// 3. if not yet, default device will be chosen: +// 3.1. in WIN32 environment, search for supported and available API in +// the following order: WASAPI, ASIO, DirectSound, MME. +// Note that only the APIs supported by the linked PortAudio +// library are available. +// 3.2 in other environment, use the default input device. +// +// store the device id to devId_ret and returns 0. +// if devId_ret is -1, tell caller to use default. +// returns -1 on error. +static int +auto_determine_device(int *devId_ret) +{ + int devId; + PaDeviceIndex numDevice = Pa_GetDeviceCount(), i; + const PaDeviceInfo *deviceInfo; + const PaHostApiInfo *apiInfo; + char *devname; + static char buf[256]; +#if defined(_WIN32) || defined(__CYGWIN__) + // at win32, force preference order: iWASAPI > ASIO > DirectSound > MME > Other + int iMME = -1, iDS = -1, iASIO = -1, iWASAPI = -1; +#endif + + // if PORTAUDIO_DEV is specified, match it against available APIs + devname = getenv("PORTAUDIO_DEV"); + devId = -1; + + // get list of available capture devices + jlog("Stat: adin_portaudio: sound capture devices:\n"); + for(i=0;imaxInputChannels <= 0) continue; + apiInfo = Pa_GetHostApiInfo(deviceInfo->hostApi); + if (!apiInfo) continue; + snprintf(buf, 255, "%s: %s", apiInfo->name, deviceInfo->name); + buf[255] = '\0'; + jlog(" %d [%s]\n", i+1, buf); + if (devname && !strncmp(devname, buf, strlen(devname))) { + // device name (partially) matches PORTAUDIO_DEV + devId = i; + } +#if defined(_WIN32) || defined(__CYGWIN__) + // store the device ID for each API + switch(apiInfo->type) { + case paWASAPI: if (iWASAPI < 0) iWASAPI = i; break; + case paMME:if (iMME < 0) iMME = i; break; + case paDirectSound:if (iDS < 0) iDS = i; break; + case paASIO:if (iASIO < 0) iASIO = i; break; + } +#endif + } + if (devname) { + if (devId == -1) { + jlog("Error: adin_portaudio: PORTAUDIO_DEV=\"%s\", but no device matches it\n", devname); + return -1; + } + jlog(" --> #%d matches PORTAUDIO_DEV, use it\n", devId + 1); + *devId_ret = devId; + return 0; + } + if (getenv("PORTAUDIO_DEV_NUM")) { + devId = atoi(getenv("PORTAUDIO_DEV_NUM")) - 1; + if (devId < 0 || devId >= numDevice) { + jlog("Error: PORTAUDIO_DEV_NUM=%d, but device %d not exist\n", devId+1, devId+1); + return -1; + } + jlog(" --> use device %d, specified by PORTAUDIO_DEV_NUM\n", devId + 1); + *devId_ret = devId; + return 0; + } +#if defined(_WIN32) || defined(__CYGWIN__) + jlog("Stat: adin_portaudio: APIs:"); + if (iWASAPI >= 0) jlog(" WASAPI"); + if (iASIO >= 0) jlog(" ASIO"); + if (iDS >= 0) jlog(" DirectSound"); + if (iMME >= 0) jlog(" MME"); + jlog("\n"); + if (iWASAPI >= 0) { + jlog("Stat: adin_portaudio: -- WASAPI selected\n"); + devId = iWASAPI; + } else if (iASIO >= 0) { + jlog("Stat: adin_portaudio: -- ASIO selected\n"); + devId = iASIO; + } else if (iDS >= 0) { + jlog("Stat: adin_portaudio: -- DirectSound selected\n"); + devId = iDS; + } else if (iMME >= 0) { + jlog("Stat: adin_portaudio: -- MME selected\n"); + devId = iMME; + } else { + jlog("Error: adin_portaudio: no device available, try default\n"); + devId = -1; + } + *devId_ret = devId; +#else + jlog("Stat: adin_portaudio: use default device\n"); + *devId_ret = -1; +#endif + return 0; +} + +#endif /** * Device initialization: check device capability and open for recording. @@ -209,6 +355,22 @@ boolean adin_mic_standby(int sfreq, void *dummy) { + /* store required sampling rate for checking after opening device */ + srate = sfreq; + return TRUE; +} + +/** + * Open the portaudio device and check capability of the opening device. + * + * @param arg [in] argument: if number, use it as device ID + * + * @return TRUE on success, FALSE on failure. + */ +static boolean +adin_mic_open(char *arg) +{ + int sfreq = srate; PaError err; #ifdef OLDVER int frames_per_buffer; @@ -216,10 +378,11 @@ #endif int latency; char *p; + int devId; /* set cycle buffer length */ cycle_buffer_len = INPUT_DELAY_SEC * sfreq; - jlog("Stat: adin_portaudio: INPUT_DELAY_SEC = %d\n", INPUT_DELAY_SEC); + //jlog("Stat: adin_portaudio: INPUT_DELAY_SEC = %d\n", INPUT_DELAY_SEC); jlog("Stat: adin_portaudio: audio cycle buffer length = %d bytes\n", cycle_buffer_len * sizeof(SP16)); #ifdef OLDVER @@ -266,114 +429,74 @@ #ifdef CHOOSE_HOST_API - { - // choose a device to open - // For win32, preference order is WASAPI > ASIO > DirectSound > MME - // If several device matches the first found one will be used. - int devId; - PaDeviceIndex numDevice = Pa_GetDeviceCount(), i; - const PaDeviceInfo *deviceInfo; - const PaHostApiInfo *apiInfo; - PaStreamParameters param; - char *devname; - static char buf[256]; -#ifdef _WIN32 - // at win32, force preference order: iWASAPI > ASIO > DirectSound > MME > Other - int iMME = -1, iDS = -1, iASIO = -1, iWASAPI = -1; -#endif - - // if PORTAUDIO_DEV is specified, match it against available APIs - devname = getenv("PORTAUDIO_DEV"); - devId = -1; - - // get list of available capture devices - jlog("Stat: adin_portaudio: available capture devices:\n"); - for(i=0;imaxInputChannels <= 0) continue; - apiInfo = Pa_GetHostApiInfo(deviceInfo->hostApi); - if (!apiInfo) continue; - snprintf(buf, 255, "%s: %s", apiInfo->name, deviceInfo->name); - buf[255] = '\0'; - jlog(" #%d [%s]\n", i+1, buf); - if (devname && !strncmp(devname, buf, strlen(devname))) { - // device name (partially) matches PORTAUDIO_DEV - devId = i; - } -#ifdef _WIN32 - // store the device ID for each API - switch(apiInfo->type) { - case paWASAPI: if (iWASAPI < 0) iWASAPI = i; break; - case paMME:if (iMME < 0) iMME = i; break; - case paDirectSound:if (iDS < 0) iDS = i; break; - case paASIO:if (iASIO < 0) iASIO = i; break; - } -#endif - } - if (devId != -1) { - jlog(" --> #%d matches PORTAUDIO_DEV, use it\n", devId + 1); + if (arg == NULL) { + // first try to determine the best device + if (auto_determine_device(&devId) == -1) { + jlog("Error: adin_portaudio: failed to choose the specified device\n"); + return(FALSE); } if (devId == -1) { - if (getenv("PORTAUDIO_DEV_NUM")) { - devId = atoi(getenv("PORTAUDIO_DEV_NUM")) - 1; - jlog(" --> use #%d, specified by PORTAUDIO_DEV_NUM\n", devId + 1); - } - } -#ifdef _WIN32 - if (devId == -1) { - // if PORTAUDIO_DEV not specified or not matched, use device in the preference order. - if (iWASAPI >= 0) devId = iWASAPI; - else if (iASIO >= 0) devId = iASIO; - else if (iDS >= 0) devId = iDS; - else if (iMME >= 0) devId = iMME; - else devId = -1; - } -#endif - if (devId == -1) { - // No device has been found, try to get the default input device + // No device has been determined, use the default input device devId = Pa_GetDefaultInputDevice(); - if (devId == paNoDevice) { - jlog("Error: adin_portaudio: no default input device is available or an error was encountered\n"); - return FALSE; - } + if (devId == paNoDevice) { + jlog("Error: adin_portaudio: no default input device is available or an error was encountered\n"); + return FALSE; + } } - // output device information + } else { + // use the given number as device id + devId = atoi(arg); + } + // output device information to use + { + const PaDeviceInfo *deviceInfo; + const PaHostApiInfo *apiInfo; + static char buf[256]; deviceInfo = Pa_GetDeviceInfo(devId); + if (deviceInfo == NULL) { + jlog("Error: adin_portaudio: failed to get info for device id %d\n", devId); + return FALSE; + } apiInfo = Pa_GetHostApiInfo(deviceInfo->hostApi); + if (apiInfo == NULL) { + jlog("Error: adin_portaudio: failed to get API info for device id %d\n", devId); + return FALSE; + } snprintf(buf, 255, "%s: %s", apiInfo->name, deviceInfo->name); buf[255] = '\0'; - jlog("Stat: adin_portaudio: get input from: [%s]\n", buf); - jlog("Info: adin_portaudio: set \"PORTAUDIO_DEV\" to the string in \"[]\" above to change\n"); - - // open the device - memset( ¶m, 0, sizeof(param)); - param.channelCount = 1; - param.device = devId; - param.sampleFormat = paInt16; - if (latency == 0) { - param.suggestedLatency = Pa_GetDeviceInfo(devId)->defaultLowInputLatency; - jlog("Stat: adin_portaudio: try to set default low latency from portaudio: %d msec\n", param.suggestedLatency * 1000.0); - } else { - param.suggestedLatency = latency / 1000.0; - jlog("Stat: adin_portaudio: try to set latency to %d msec\n", param.suggestedLatency * 1000.0); - } - err = Pa_OpenStream(&stream, ¶m, NULL, sfreq, - 0, paNoFlag, - Callback, NULL); - if (err != paNoError) { - jlog("Error: adin_portaudio: error in opening stream: %s\n", Pa_GetErrorText(err)); - return(FALSE); - } - { - const PaStreamInfo *stinfo; - stinfo = Pa_GetStreamInfo(stream); - jlog("Stat: adin_portaudio: latency was set to %f msec\n", stinfo->inputLatency * 1000.0); - } + jlog("Stat: adin_portaudio: [%s]\n", buf); + jlog("Stat: adin_portaudio: (you can specify device by \"PORTAUDIO_DEV_NUM=number\"\n"); + } + + // open the device + PaStreamParameters param; + memset( ¶m, 0, sizeof(param)); + param.channelCount = 1; + param.device = devId; + param.sampleFormat = paInt16; + if (latency == 0) { + param.suggestedLatency = Pa_GetDeviceInfo(devId)->defaultLowInputLatency; + jlog("Stat: adin_portaudio: try to set default low latency from portaudio: %d msec\n", param.suggestedLatency * 1000.0); + } else { + param.suggestedLatency = latency / 1000.0; + jlog("Stat: adin_portaudio: try to set latency to %d msec\n", param.suggestedLatency * 1000.0); + } + err = Pa_OpenStream(&stream, ¶m, NULL, sfreq, + 0, paNoFlag, + Callback, NULL); + if (err != paNoError) { + jlog("Error: adin_portaudio: error in opening stream: %s\n", Pa_GetErrorText(err)); + return(FALSE); + } + { + const PaStreamInfo *stinfo; + stinfo = Pa_GetStreamInfo(stream); + jlog("Stat: adin_portaudio: latency was set to %f msec\n", stinfo->inputLatency * 1000.0); } #else + // Just open the default stream err = Pa_OpenDefaultStream(&stream, 1, 0, paInt16, sfreq, #ifdef OLDVER frames_per_buffer, @@ -400,10 +523,14 @@ * @return TRUE on success, FALSE on failure. */ boolean -adin_mic_begin(char *pathname) +adin_mic_begin(char *arg) { PaError err; + /* initialize device and open stream */ + if (adin_mic_open(arg) == FALSE) { + return(FALSE); + } /* start stream */ err = Pa_StartStream(stream); if (err != paNoError) { @@ -424,12 +551,24 @@ { PaError err; - /* stop stream */ - err = Pa_StopStream(stream); + /* stop stream (do not wait callback and buffer flush, stop immediately) */ + err = Pa_AbortStream(stream); if (err != paNoError) { jlog("Error: adin_portaudio: failed to stop stream: %s\n", Pa_GetErrorText(err)); return(FALSE); } + /* close stream */ + err = Pa_CloseStream(stream); + if (err != paNoError) { + jlog("Error: adin_portaudio: failed to close stream: %s\n", Pa_GetErrorText(err)); + return(FALSE); + } + /* terminate library */ + err = Pa_Terminate(); + if (err != paNoError) { + jlog("Error: adin_portaudio: failed to terminate library: %s\n", Pa_GetErrorText(err)); + return(FALSE); + } return TRUE; } From sumomo @ users.sourceforge.jp Sat Feb 5 18:00:42 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Sat, 05 Feb 2011 18:00:42 +0900 Subject: [Julius-cvs 580] CVS update: julius4/libsent/src/voca Message-ID: <1296896442.031231.30005.nullmailer@users.sourceforge.jp> Index: julius4/libsent/src/voca/voca_load_htkdict.c diff -u julius4/libsent/src/voca/voca_load_htkdict.c:1.7 julius4/libsent/src/voca/voca_load_htkdict.c:1.8 --- julius4/libsent/src/voca/voca_load_htkdict.c:1.7 Mon Oct 20 17:40:07 2008 +++ julius4/libsent/src/voca/voca_load_htkdict.c Sat Feb 5 18:00:41 2011 @@ -19,7 +19,7 @@ * @author Akinobu LEE * @date Fri Feb 18 19:43:06 2005 * - * $Revision: 1.7 $ + * $Revision: 1.8 $ * */ /* @@ -651,12 +651,28 @@ for(w=0;wnum;w++) { /* copy data */ dstinfo->wlen[n] = srcinfo->wlen[w]; - if (srcinfo->wname[w]) dstinfo->wname[n] = strcpy((char *)mybmalloc2(strlen(srcinfo->wname[w])+1, &(dstinfo->mroot)), srcinfo->wname[w]); - if (srcinfo->woutput[w]) dstinfo->woutput[n] = strcpy((char *)mybmalloc2(strlen(srcinfo->woutput[w])+1, &(dstinfo->mroot)), srcinfo->woutput[w]); - if (srcinfo->wlen[w] > 0) dstinfo->wseq[n] = (HMM_Logical **)mybmalloc2(sizeof(HMM_Logical *) * srcinfo->wlen[w], &(dstinfo->mroot)); - for(i=0;iwlen[w];i++) { - dstinfo->wseq[n][i] = srcinfo->wseq[w][i]; + if (srcinfo->wname[w]) { + dstinfo->wname[n] = strcpy((char *)mybmalloc2(strlen(srcinfo->wname[w])+1, &(dstinfo->mroot)), srcinfo->wname[w]); + } else { + dstinfo->wname[n] = NULL; + } + if (srcinfo->woutput[w]) { + dstinfo->woutput[n] = strcpy((char *)mybmalloc2(strlen(srcinfo->woutput[w])+1, &(dstinfo->mroot)), srcinfo->woutput[w]); + } else { + dstinfo->woutput[n] = NULL; + } + if (srcinfo->wlen[w] > 0) { + dstinfo->wseq[n] = (HMM_Logical **)mybmalloc2(sizeof(HMM_Logical *) * srcinfo->wlen[w], &(dstinfo->mroot)); + for(i=0;iwlen[w];i++) { + dstinfo->wseq[n][i] = srcinfo->wseq[w][i]; + } + } else { + dstinfo->wseq[n] = NULL; } +#ifdef CLASS_NGRAM + dstinfo->cprob[n] = srcinfo->cprob[w]; + if (dstinfo->cprob[n] != 0.0) dstinfo->cwnum++; +#endif dstinfo->is_transparent[n] = srcinfo->is_transparent[w]; /* offset category ID by coffset */ dstinfo->wton[n] = srcinfo->wton[w] + coffset; From sumomo @ users.sourceforge.jp Sat Feb 5 18:00:41 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Sat, 05 Feb 2011 18:00:41 +0900 Subject: [Julius-cvs 581] CVS update: julius4/libjulius/include/julius Message-ID: <1296896441.836742.29977.nullmailer@users.sourceforge.jp> Index: julius4/libjulius/include/julius/extern.h diff -u julius4/libjulius/include/julius/extern.h:1.16 julius4/libjulius/include/julius/extern.h:1.17 --- julius4/libjulius/include/julius/extern.h:1.16 Fri Sep 18 17:31:08 2009 +++ julius4/libjulius/include/julius/extern.h Sat Feb 5 18:00:41 2011 @@ -12,7 +12,7 @@ * @author Akinobu LEE * @date Mon Mar 7 23:19:14 2005 * - * $Revision: 1.16 $ + * $Revision: 1.17 $ * */ /* @@ -171,6 +171,7 @@ void opt_release(Jconf *jconf); /* m_jconf.c */ void get_dirname(char *path); +boolean config_string_parse(char *str, Jconf *jconf); boolean config_file_parse(char *conffile, Jconf *jconf); /* m_chkparam.c */ boolean checkpath(char *filename); Index: julius4/libjulius/include/julius/jconf.h diff -u julius4/libjulius/include/julius/jconf.h:1.8 julius4/libjulius/include/julius/jconf.h:1.9 --- julius4/libjulius/include/julius/jconf.h:1.8 Tue Feb 10 17:15:48 2009 +++ julius4/libjulius/include/julius/jconf.h Sat Feb 5 18:00:41 2011 @@ -23,7 +23,7 @@ * @author Akinobu Lee * @date Fri Feb 16 13:42:28 2007 * - * $Revision: 1.8 $ + * $Revision: 1.9 $ * */ /* @@ -220,6 +220,22 @@ } JCONF_AM; /** + * Name lister for language model configurations + * + */ +typedef struct __jconf_lm_namelist__ { + /** + * Entry name + */ + char *name; + /** + * Pointer to next object + */ + struct __jconf_lm_namelist__ *next; + +} JCONF_LM_NAMELIST; + +/** * Language models (N-gram / DFA), dictionary, and related parameters. * */ @@ -340,6 +356,16 @@ char unknown_name[UNK_WORD_MAXLEN]; /** + * List of additional dictionary files + */ + JCONF_LM_NAMELIST *additional_dict_files; + + /** + * List of additional dictionary entries + */ + JCONF_LM_NAMELIST *additional_dict_entries; + + /** * Pointer to next instance * */ Index: julius4/libjulius/include/julius/jfunc.h diff -u julius4/libjulius/include/julius/jfunc.h:1.7 julius4/libjulius/include/julius/jfunc.h:1.8 --- julius4/libjulius/include/julius/jfunc.h:1.7 Fri Sep 18 17:31:08 2009 +++ julius4/libjulius/include/julius/jfunc.h Sat Feb 5 18:00:41 2011 @@ -12,7 +12,7 @@ * @author Akinobu Lee * @date Tue Nov 6 22:41:00 2007 * - * $Revision: 1.7 $ + * $Revision: 1.8 $ * */ /* @@ -52,9 +52,13 @@ void j_internal_error(char *fmt, ...); int j_config_load_args(Jconf *jconf, int argc, char *argv[]); +int j_config_load_string(Jconf *jconf, char *string); int j_config_load_file(Jconf *jconf, char *filename); Jconf *j_config_load_args_new(int argc, char *argv[]); +Jconf *j_config_load_string_new(char *string); Jconf *j_config_load_file_new(char *filename); +void j_add_dict(JCONF_LM *lm, char *dictfile); +void j_add_word(JCONF_LM *lm, char *wordentry); boolean j_adin_init(Recog *recog); char *j_get_current_filename(Recog *recog); void j_recog_info(Recog *recog); Index: julius4/libjulius/include/julius/recog.h diff -u julius4/libjulius/include/julius/recog.h:1.11 julius4/libjulius/include/julius/recog.h:1.12 --- julius4/libjulius/include/julius/recog.h:1.11 Sun Jul 5 23:12:18 2009 +++ julius4/libjulius/include/julius/recog.h Sat Feb 5 18:00:41 2011 @@ -70,7 +70,7 @@ * @author Akinobu Lee * @date Fri Feb 16 13:42:28 2007 * - * $Revision: 1.11 $ + * $Revision: 1.12 $ * */ /* @@ -224,6 +224,7 @@ LOGPROB *sentcm = NULL; ///< Confidence score of each sentence LOGPROB *wordcm = NULL; ///< Confidence score of each word voted from @a sentcm int sentnum; ///< Allocated length of @a sentcm + int wordnum; ///< Allocated length of @a wordcm # endif #endif /* CONFIDENCE_MEASURE */ From sumomo @ users.sourceforge.jp Sat Feb 5 18:00:41 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Sat, 05 Feb 2011 18:00:41 +0900 Subject: [Julius-cvs 582] CVS update: julius4/libjulius/src Message-ID: <1296896441.953879.29998.nullmailer@users.sourceforge.jp> Index: julius4/libjulius/src/default.c diff -u julius4/libjulius/src/default.c:1.10 julius4/libjulius/src/default.c:1.11 --- julius4/libjulius/src/default.c:1.10 Tue Feb 10 17:15:48 2009 +++ julius4/libjulius/src/default.c Sat Feb 5 18:00:41 2011 @@ -17,7 +17,7 @@ * @author Akinobu Lee * @date Fri Feb 16 15:05:43 2007 * - * $Revision: 1.10 $ + * $Revision: 1.11 $ * */ /* @@ -194,6 +194,8 @@ strcpy(j->wordrecog_tail_silence_model_name, "silE"); j->wordrecog_silence_context_name[0] = '\0'; strcpy(j->unknown_name, UNK_WORD_DEFAULT); // or UNK_WORD_DEFAULT2 + j->additional_dict_files = NULL; + j->additional_dict_entries = NULL; } /** Index: julius4/libjulius/src/instance.c diff -u julius4/libjulius/src/instance.c:1.4 julius4/libjulius/src/instance.c:1.5 --- julius4/libjulius/src/instance.c:1.4 Sat Jul 4 23:11:42 2009 +++ julius4/libjulius/src/instance.c Sat Feb 5 18:00:41 2011 @@ -12,7 +12,7 @@ * @author Akinobu Lee * @date Sun Oct 28 18:06:20 2007 * - * $Revision: 1.4 $ + * $Revision: 1.5 $ * */ /* @@ -457,6 +457,21 @@ void j_jconf_lm_free(JCONF_LM *lmconf) { + JCONF_LM_NAMELIST *nl, *nltmp; + nl = lmconf->additional_dict_files; + while (nl) { + nltmp = nl->next; + free(nl->name); + free(nl); + nl = nltmp; + } + nl = lmconf->additional_dict_entries; + while (nl) { + nltmp = nl->next; + free(nl->name); + free(nl); + nl = nltmp; + } free(lmconf); } Index: julius4/libjulius/src/jfunc.c diff -u julius4/libjulius/src/jfunc.c:1.6 julius4/libjulius/src/jfunc.c:1.7 --- julius4/libjulius/src/jfunc.c:1.6 Wed Mar 18 16:05:30 2009 +++ julius4/libjulius/src/jfunc.c Sat Feb 5 18:00:41 2011 @@ -19,7 +19,7 @@ * @author Akinobu Lee * @date Wed Aug 8 15:04:28 2007 * - * $Revision: 1.6 $ + * $Revision: 1.7 $ * */ /* @@ -315,36 +315,26 @@ /** * - * Load parameters from command argments, and set to each configuration - * instances in jconf. + * If multiple instances defined from init, remove initial one (id=0) * * - * コマンド引数からパラメータを読み込み,jconf 内の各設定インスタンスに - * 値を格納する. + * 複数インスタンスが定義されている場合、初期インスタンス(id=0)は + * 無効なので消す. * * * @param jconf [i/o] global configuration instance - * @param argc [in] number of arguments - * @param argv [in] list of argument strings - * - * @return 0 on success, or -1 on failure. * * @callgraph * @callergraph * @ingroup jconf */ -int -j_config_load_args(Jconf *jconf, int argc, char *argv[]) +static void +j_config_remove_initial(Jconf *jconf) { JCONF_AM *am; JCONF_LM *lm; JCONF_SEARCH *s; - /* parse options and set variables */ - if (opt_parse(argc, argv, NULL, jconf) == FALSE) { - return -1; - } - /* if multiple instances defined from init, remove initial one (id=0) */ if(jconf->am_root->next != NULL && jconf->am_root->id == 0) { am = jconf->am_root->next; free(jconf->am_root); @@ -360,6 +350,74 @@ free(jconf->search_root); jconf->search_root = s; } +} + +/** + * + * Load parameters from command argments, and set to each configuration + * instances in jconf. + * + * + * コマンド引数からパラメータを読み込み,jconf 内の各設定インスタンスに + * 値を格納する. + * + * + * @param jconf [i/o] global configuration instance + * @param argc [in] number of arguments + * @param argv [in] list of argument strings + * + * @return 0 on success, or -1 on failure. + * + * @callgraph + * @callergraph + * @ingroup jconf + */ +int +j_config_load_args(Jconf *jconf, int argc, char *argv[]) +{ + /* parse options and set variables */ + if (opt_parse(argc, argv, NULL, jconf) == FALSE) { + return -1; + } + /* if multiple instances defined from init, remove initial one (id=0) */ + j_config_remove_initial(jconf); + + return 0; +} + +/** + * + * Load parameters from command argment string, and set to each configuration + * instances in jconf. + * + * + * コマンド引数を含む文字列からパラメータを読み込み,jconf 内の各設定インスタンスに + * 値を格納する. + * + * + * @param jconf [i/o] global configuration instance + * @param argstr [in] argument string + * + * @return 0 on success, or -1 on failure. + * + * @callgraph + * @callergraph + * @ingroup jconf + */ +int +j_config_load_string(Jconf *jconf, char *string) +{ + int argc; + char **argv; + char *buf; + + /* parse options and set variables */ + if (config_string_parse(string, jconf) == FALSE) { + return -1; + } + /* if multiple instances defined from init, remove initial one (id=0) */ + j_config_remove_initial(jconf); + return 0; } @@ -385,30 +443,13 @@ int j_config_load_file(Jconf *jconf, char *filename) { - JCONF_AM *am; - JCONF_LM *lm; - JCONF_SEARCH *s; - /* parse options and set variables */ if (config_file_parse(filename, jconf) == FALSE) { return -1; } /* if multiple instances defined from init, remove initial one (id=0) */ - if(jconf->am_root->next != NULL && jconf->am_root->id == 0) { - am = jconf->am_root->next; - free(jconf->am_root); - jconf->am_root = am; - } - if(jconf->lm_root->next != NULL && jconf->lm_root->id == 0) { - lm = jconf->lm_root->next; - free(jconf->lm_root); - jconf->lm_root = lm; - } - if(jconf->search_root->next != NULL && jconf->search_root->id == 0) { - s = jconf->search_root->next; - free(jconf->search_root); - jconf->search_root = s; - } + j_config_remove_initial(jconf); + return 0; } @@ -435,32 +476,11 @@ j_config_load_args_new(int argc, char *argv[]) { Jconf *jconf; - JCONF_AM *am; - JCONF_LM *lm; - JCONF_SEARCH *s; - jconf = j_jconf_new(); - /* parse options and set variables */ - if (opt_parse(argc, argv, NULL, jconf) == FALSE) { + if (j_config_load_args(jconf, argc, argv) == -1) { j_jconf_free(jconf); return NULL; } - /* if multiple instances defined from init, remove initial one (id=0) */ - if(jconf->am_root->next != NULL && jconf->am_root->id == 0) { - am = jconf->am_root->next; - free(jconf->am_root); - jconf->am_root = am; - } - if(jconf->lm_root->next != NULL && jconf->lm_root->id == 0) { - lm = jconf->lm_root->next; - free(jconf->lm_root); - jconf->lm_root = lm; - } - if(jconf->search_root->next != NULL && jconf->search_root->id == 0) { - s = jconf->search_root->next; - free(jconf->search_root); - jconf->search_root = s; - } return jconf; } @@ -486,37 +506,108 @@ j_config_load_file_new(char *filename) { Jconf *jconf; - JCONF_AM *am; - JCONF_LM *lm; - JCONF_SEARCH *s; - jconf = j_jconf_new(); - /* parse options and set variables */ - if (config_file_parse(filename, jconf) == FALSE) { + if (j_config_load_file(jconf, filename) == -1) { j_jconf_free(jconf); return NULL; } - /* if multiple instances defined from init, remove initial one (id=0) */ - if(jconf->am_root->next != NULL && jconf->am_root->id == 0) { - am = jconf->am_root->next; - free(jconf->am_root); - jconf->am_root = am; - } - if(jconf->lm_root->next != NULL && jconf->lm_root->id == 0) { - lm = jconf->lm_root->next; - free(jconf->lm_root); - jconf->lm_root = lm; - } - if(jconf->search_root->next != NULL && jconf->search_root->id == 0) { - s = jconf->search_root->next; - free(jconf->search_root); - jconf->search_root = s; + return jconf; +} + +/** + * + * Create a new configuration instance and load parameters from string + * file. + * + * + * 新たな設定インスタンスを割り付け,そこに + * 文字列から設定パラメータを読み込んで返す. + * + * + * @param string [in] option string + * + * @return the newly allocated global configuration instance. + * + * @callgraph + * @callergraph + * @ingroup jconf + */ +Jconf * +j_config_load_string_new(char *string) +{ + Jconf *jconf; + jconf = j_jconf_new(); + if (j_config_load_string(jconf, string) == -1) { + j_jconf_free(jconf); + return NULL; } return jconf; } /** * + * Book to read an additional dictionary file to be read. + * when called multiple times, all the file name will be stored and read. + * The file will be read just after the normal dictionary at startup. + * + * + * 追加辞書ファイルの読み込みを指定する. + * 複数回呼ばれた場合、すべて読み込まれる。 + * 指定された辞書は起動時に通常の辞書のあとに続けて読み込まれる. + * + * + * @param lm [i/o] a LM configuration + * @param dictfile [in] dictinoary file name + * + * @return the newly allocated global configuration instance. + * + * @callgraph + * @callergraph + * @ingroup jconf + */ +void +j_add_dict(JCONF_LM *lm, char *dictfile) +{ + JCONF_LM_NAMELIST *nl; + nl = (JCONF_LM_NAMELIST *)mymalloc(sizeof(JCONF_LM_NAMELIST)); + nl->name = (char *)mymalloc(strlen(dictfile) + 1); + strcpy(nl->name, dictfile); + nl->next = lm->additional_dict_files; + lm->additional_dict_files = nl; +} + +/** + * + * Add an additional word entry. + * The string should contain a word entry in as the same format as dictionary. + * If called multiple times, all the specified words will be appended. + * + * + * 追加の単語エントリを指定する. + * 内容は辞書ファイルと同じフォーマット. + * 起動までに複数回呼ばれた場合、そのすべてが起動時に追加される. + * + * + * @param lm [i/o] a LM configuration + * @param wordentry [in] word entry string in dictionary format + * + * @callgraph + * @callergraph + * @ingroup jconf + */ +void +j_add_word(JCONF_LM *lm, char *wordentry) +{ + JCONF_LM_NAMELIST *nl; + nl = (JCONF_LM_NAMELIST *)mymalloc(sizeof(JCONF_LM_NAMELIST)); + nl->name = (char *)mymalloc(strlen(wordentry) + 1); + strcpy(nl->name, wordentry); + nl->next = lm->additional_dict_entries; + lm->additional_dict_entries = nl; +} + +/** + * * Initialize and setup A/D-in device specified by the configuration * for recognition. When threading is enabled for the device, * A/D-in thread will start inside this function. Index: julius4/libjulius/src/m_fusion.c diff -u julius4/libjulius/src/m_fusion.c:1.14 julius4/libjulius/src/m_fusion.c:1.15 --- julius4/libjulius/src/m_fusion.c:1.14 Sat Jul 4 23:11:42 2009 +++ julius4/libjulius/src/m_fusion.c Sat Feb 5 18:00:41 2011 @@ -20,7 +20,7 @@ * @author Akinobu Lee * @date Thu May 12 13:31:47 2005 * - * $Revision: 1.14 $ + * $Revision: 1.15 $ * */ /* @@ -302,6 +302,49 @@ return NULL; } + /* load additional entries */ + JCONF_LM_NAMELIST *nl; + char buf[MAXLINELEN]; + int n; + for (nl = lmconf->additional_dict_files; nl; nl=nl->next) { + FILE *fp; + if ((fp = fopen(nl->name, "rb")) == NULL) { + jlog("ERROR: m_fusion: failed to open %s\n",nl->name); + word_info_free(winfo); + return NULL; + } + n = winfo->num; + while (getl_fp(buf, MAXLINELEN, fp) != NULL) { + if (voca_load_line(buf, winfo, hmminfo) == FALSE) break; + } + if (voca_load_end(winfo) == FALSE) { + jlog("ERROR: m_fusion: failed to read dictionary %s\n", nl->name); + fclose(fp); + word_info_free(winfo); + return NULL; + } + if (fclose(fp) == -1) { + jlog("ERROR: m_fusion: failed to close %s\n", nl->name); + word_info_free(winfo); + return NULL; + } + jlog("STAT: + additional dictionary: %s (%d words)\n", nl->name, winfo->num - n); + } + n = winfo->num; + for (nl = lmconf->additional_dict_entries; nl; nl=nl->next) { + if (voca_load_line(nl->name, winfo, hmminfo) == FALSE) { + jlog("ERROR: m_fusion: failed to set entry: %s\n", nl->name); + } + } + if (lmconf->additional_dict_entries) { + if (voca_load_end(winfo) == FALSE) { + jlog("ERROR: m_fusion: failed to read additinoal word entry\n"); + word_info_free(winfo); + return NULL; + } + jlog("STAT: + additional entries: %d words\n", winfo->num - n); + } + if (lmconf->lmtype == LM_PROB) { /* if necessary, append a IW-sp word to the dict if "-iwspword" specified */ if (lmconf->enable_iwspword) { Index: julius4/libjulius/src/m_info.c diff -u julius4/libjulius/src/m_info.c:1.9 julius4/libjulius/src/m_info.c:1.10 --- julius4/libjulius/src/m_info.c:1.9 Thu Sep 25 14:00:06 2008 +++ julius4/libjulius/src/m_info.c Sat Feb 5 18:00:41 2011 @@ -12,7 +12,7 @@ * @author Akinobu Lee * @date Thu May 12 14:14:01 2005 * - * $Revision: 1.9 $ + * $Revision: 1.10 $ * */ /* @@ -434,6 +434,24 @@ if (lm->config->enable_iwspword) { jlog("\tIW-sp word added to dict= \"%s\"\n", lm->config->iwspentry); } + if (lm->config->additional_dict_files) { + JCONF_LM_NAMELIST *nl; + jlog("\tadditional dictionaries:\n"); + for(nl=lm->config->additional_dict_files;nl;nl=nl->next) { + jlog("\t\t\t%s\n", nl->name); + } + jlog("\n"); + } + if (lm->config->additional_dict_entries) { + JCONF_LM_NAMELIST *nl; + int n = 0; + jlog("\tadditional dict entries:\n"); + for(nl=lm->config->additional_dict_entries;nl;nl=nl->next) { + jlog("\t\t\t%s\n", nl->name); + n++; + } + jlog("--- total %d entries\n", n); + } } if (lm->lmtype == LM_PROB) { Index: julius4/libjulius/src/m_jconf.c diff -u julius4/libjulius/src/m_jconf.c:1.6 julius4/libjulius/src/m_jconf.c:1.7 --- julius4/libjulius/src/m_jconf.c:1.6 Fri Sep 18 17:31:08 2009 +++ julius4/libjulius/src/m_jconf.c Sat Feb 5 18:00:41 2011 @@ -37,7 +37,7 @@ * @author Akinobu Lee * @date Thu May 12 14:16:18 2005 * - * $Revision: 1.6 $ + * $Revision: 1.7 $ * */ /* @@ -54,6 +54,7 @@ #endif #define ISTOKEN(A) (A == ' ' || A == '\t' || A == '\n') ///< Determine token characters +#define BUFLEN 512 /** * @@ -359,13 +360,143 @@ /* read-in and parse jconf file and process those using m_options */ /** * - * jconf 設定ファイルを読み込んで解析し,対応するオプションを設定する. + * @brief オプション文字列を分解して追加格納する. + * + * @param buf [in] 文字列 + * @param argv [i/o] オプション列へのポインタ + * @param argc [i/o] オプション列の数へのポインタ + * @param maxnum [i/o] オプション列の割付最大数 + * + * + * @brief Divide option string into option arguments and append to array. + * + * @param buf [in] option string + * @param argv [i/o] pointer to option array + * @param argc [i/o] pointer to the length of option array + * @param maxnum [i/o] pointer to the allocated length of option array + * + */ +static void +add_to_arglist(char *buf, char ***argv_ret, int *argc_ret, int *maxnum_ret) +{ + char *p = buf; + char cpy[BUFLEN]; + char *dst, *dst_from; + char **argv = *argv_ret; + int argc = *argc_ret; + int maxnum = *maxnum_ret; + + dst = cpy; + while (1) { + while (*p != '\0' && ISTOKEN(*p)) p++; + if (*p == '\0') break; + + dst_from = dst; + + while (*p != '\0' && (!ISTOKEN(*p))) { + if (*p == '\\') { /* escape by '\' */ + if (*(++p) == '\0') break; + *(dst++) = *(p++); + } else { + if (*p == '"') { /* quote by "" */ + p++; + while (*p != '\0' && *p != '"') *(dst++) = *(p++); + if (*p == '\0') break; + p++; + } else if (*p == '\'') { /* quote by '' */ + p++; + while (*p != '\0' && *p != '\'') *(dst++) = *(p++); + if (*p == '\0') break; + p++; + } else if (*p == '#') { /* comment out by '#' */ + *p = '\0'; + break; + } else { /* other */ + *(dst++) = *(p++); + } + } + } + if (dst != dst_from) { + *dst = '\0'; dst++; + if ( argc >= maxnum) { + maxnum += 20; + argv = (char **)myrealloc(argv, sizeof(char *) * maxnum); + } + argv[argc++] = strcpy((char*)mymalloc(strlen(dst_from)+1), dst_from); + } + } + *argv_ret = argv; + *argc_ret = argc; + *maxnum_ret = maxnum; +} + +/** + * + * オプション指定を含む文字列を解析して値をセットする. + * 相対パス名はカレントからの相対として扱われる. + * + * @param str [in] オプション指定を含む文字列 + * @param jconf [out] 値をセットする jconf 設定データ + * + * + * Parse a string and set the specified option values. + * Relative paths will be treated as relative to current directory. + * + * @param str [in] string which contains options + * @param jconf [out] global configuration data to be written. + * + * + * @callgraph + * @callergraph + */ +boolean +config_string_parse(char *str, Jconf *jconf) +{ + int c_argc; + char **c_argv; + int maxnum; + char buf[BUFLEN]; + char *cdir; + int i; + boolean ret; + + jlog("STAT: parsing option string: \"%s\"\n", str); + + /* set the content of jconf file into argument list c_argv[1..c_argc-1] */ + maxnum = 20; + c_argv = (char **)mymalloc(sizeof(char *) * maxnum); + c_argv[0] = strcpy((char *)mymalloc(7), "string"); + c_argc = 1; + add_to_arglist(str, &c_argv, &c_argc, &maxnum); + /* env expansion */ + for (i=1;i 0) { + free(c_argv[c_argc]); + } + free(c_argv); + + return(ret); +} + +/** + * + * jconf 設定ファイルを読み込んで解析し,対応するオプションを設定する. + * オプション内の相対パスは、その jconf 設定ファイルからの相対となる. * * @param conffile [in] jconf ファイルのパス名 * @param jconf [out] 値をセットする jconf 設定データ * * * Read and parse a jconf file, and set the specified option values. + * Relative paths in the file will be treated as relative to the file, + * not the application current. * * @param conffile [in] jconf file path name * @param jconf [out] global configuration data to be written. @@ -380,10 +511,8 @@ int c_argc; char **c_argv; FILE *fp; - int maxnum, step; -#define BUFLEN 512 - char buf[BUFLEN], cpy[BUFLEN]; - char *p, *dst, *dst_from; + int maxnum; + char buf[BUFLEN]; char *cdir; int i; boolean ret; @@ -397,52 +526,13 @@ jlog("ERROR: m_jconf: failed to open jconf file: %s\n", conffile); return FALSE; } - step = 20; - maxnum = step; + maxnum = 20; c_argv = (char **)mymalloc(sizeof(char *) * maxnum); c_argv[0] = strcpy((char *)mymalloc(strlen(conffile)+1), conffile); c_argc = 1; while (fgets_jconf(buf, BUFLEN, fp) != NULL) { if (buf[0] == '\0') continue; - p = buf; dst = cpy; - while (1) { - while (*p != '\0' && ISTOKEN(*p)) p++; - if (*p == '\0') break; - - dst_from = dst; - - while (*p != '\0' && (!ISTOKEN(*p))) { - if (*p == '\\') { /* escape by '\' */ - if (*(++p) == '\0') break; - *(dst++) = *(p++); - } else { - if (*p == '"') { /* quote by "" */ - p++; - while (*p != '\0' && *p != '"') *(dst++) = *(p++); - if (*p == '\0') break; - p++; - } else if (*p == '\'') { /* quote by '' */ - p++; - while (*p != '\0' && *p != '\'') *(dst++) = *(p++); - if (*p == '\0') break; - p++; - } else if (*p == '#') { /* comment out by '#' */ - *p = '\0'; - break; - } else { /* other */ - *(dst++) = *(p++); - } - } - } - if (dst != dst_from) { - *dst = '\0'; dst++; - if (c_argc >= maxnum) { - maxnum += step; - c_argv = (char **)myrealloc(c_argv, sizeof(char *) * maxnum); - } - c_argv[c_argc++] = strcpy((char*)mymalloc(strlen(dst_from)+1), dst_from); - } - } + add_to_arglist(buf, &c_argv, &c_argc, &maxnum); } if (fclose(fp) == -1) { jlog("ERROR: m_jconf: cannot close jconf file\n"); Index: julius4/libjulius/src/m_options.c diff -u julius4/libjulius/src/m_options.c:1.19 julius4/libjulius/src/m_options.c:1.20 --- julius4/libjulius/src/m_options.c:1.19 Sun Apr 4 00:06:15 2010 +++ julius4/libjulius/src/m_options.c Sat Feb 5 18:00:41 2011 @@ -18,7 +18,7 @@ * @author Akinobu Lee * @date Thu May 12 18:52:07 2005 * - * $Revision: 1.19 $ + * $Revision: 1.20 $ * */ /* @@ -1270,6 +1270,18 @@ plugin_load_dirs(tmparg); continue; #endif + } else if (strmatch(argv[i],"-adddict")) { + if (!check_section(jconf, argv[i], JCONF_OPT_LM)) return FALSE; + GET_TMPARG; + char *arg = filepath(tmparg, cwd); + j_add_dict(jconf->lmnow, arg); + free(arg); + continue; + } else if (strmatch(argv[i],"-addentry")) { + if (!check_section(jconf, argv[i], JCONF_OPT_LM)) return FALSE; + GET_TMPARG; + j_add_word(jconf->lmnow, tmparg); + continue; } if (argv[i][0] == '-' && strlen(argv[i]) == 2) { /* 1-letter options */ Index: julius4/libjulius/src/search_bestfirst_main.c diff -u julius4/libjulius/src/search_bestfirst_main.c:1.9 julius4/libjulius/src/search_bestfirst_main.c:1.10 --- julius4/libjulius/src/search_bestfirst_main.c:1.9 Sat Jul 4 23:11:42 2009 +++ julius4/libjulius/src/search_bestfirst_main.c Sat Feb 5 18:00:41 2011 @@ -35,7 +35,7 @@ * @author Akinobu Lee * @date Thu Sep 08 11:51:12 2005 * - * $Revision: 1.9 $ + * $Revision: 1.10 $ * */ /* @@ -658,11 +658,15 @@ sd->sentcm = (LOGPROB *)mymalloc(sizeof(LOGPROB)*stacknum); sd->sentnum = stacknum; } else if (sd->sentnum < stacknum) { /* need expanded */ - sd->sentcm = (LOGPROB *)myrealloc(sentcm, sizeof(LOGPROB)*stacknum); + sd->sentcm = (LOGPROB *)myrealloc(sd->sentcm, sizeof(LOGPROB)*stacknum); sd->sentnum = stacknum; } if (sd->wordcm == NULL) { sd->wordcm = (LOGPROB *)mymalloc(sizeof(LOGPROB) * winfo->num); + sd->wordnum = winfo->num; + } else if (sd->wordnum < winfo->num) { + sd->wordcm = (LOGPROB *)myremalloc(sd->wordcm, sizeof(LOGPROB) * winfo->num); + sd->wordnum = winfo->num; } cm_alpha = jconf->annotate.cm_alpha; @@ -670,7 +674,7 @@ for (j = 0, cm_alpha = jconf->annotate.cm_alpha_bgn; cm_alpha <= jconf->annotate.cm_alpha_end; cm_alpha += jconf->annotate.cm_alpha_step) { #endif /* clear whole word cm buffer */ - for(w=0;wnum;w++) { + for(w=0;wwordnum;w++) { sd->wordcm[w] = 0.0; } /* get best score */ From sumomo @ users.sourceforge.jp Sat Feb 5 18:12:01 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Sat, 05 Feb 2011 18:12:01 +0900 Subject: [Julius-cvs 583] CVS update: julius4/libsent Message-ID: <1296897121.638929.10273.nullmailer@users.sourceforge.jp> Index: julius4/libsent/Makefile.in diff -u julius4/libsent/Makefile.in:1.9 julius4/libsent/Makefile.in:1.10 --- julius4/libsent/Makefile.in:1.9 Sat Feb 5 18:00:01 2011 +++ julius4/libsent/Makefile.in Sat Feb 5 18:12:01 2011 @@ -3,7 +3,7 @@ # Copyright (c) 2005-2007 Julius project team, Nagoya Institute of Technology # All rights reserved # -# $Id: Makefile.in,v 1.9 2011/02/05 09:00:01 sumomo Exp $ +# $Id: Makefile.in,v 1.10 2011/02/05 09:12:01 sumomo Exp $ # SHELL=/bin/sh @@ -160,7 +160,7 @@ $(RM) config.log config.cache distclean: - $(RM) *~ src/*/*~ src/*/*.o src/*/*/*.o include/sent/*~ + $(RM) *~ src/*/*~ src/*/*.o src/*/*/*.o src/*/*/*/*.o src/*/*/*/*/*.o include/sent/*~ $(RM) config.log config.cache $(RM) libsent-config libsent-config-dist $(RM) config.status include/sent/config.h From sumomo @ users.sourceforge.jp Sat Feb 5 22:27:23 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Sat, 05 Feb 2011 22:27:23 +0900 Subject: [Julius-cvs 584] CVS update: julius4/libjulius/src Message-ID: <1296912443.322568.32668.nullmailer@users.sourceforge.jp> Index: julius4/libjulius/src/m_fusion.c diff -u julius4/libjulius/src/m_fusion.c:1.15 julius4/libjulius/src/m_fusion.c:1.16 --- julius4/libjulius/src/m_fusion.c:1.15 Sat Feb 5 18:00:41 2011 +++ julius4/libjulius/src/m_fusion.c Sat Feb 5 22:27:22 2011 @@ -20,7 +20,7 @@ * @author Akinobu Lee * @date Thu May 12 13:31:47 2005 * - * $Revision: 1.15 $ + * $Revision: 1.16 $ * */ /* @@ -1019,7 +1019,9 @@ } p->am->hmminfo->iwsp_penalty = p->am->config->iwsp_penalty; } else { - jlog("Warning: \"-iwsp\" is supported on multi-path mode, ignored\n"); + jlog("ERROR: \"-iwsp\" needs multi-path mode\n"); + jlog("ERROR: you should use multi-path AM, or specify \"-multipath\" with \"-iwsp\"\n"); + return FALSE; } } From sumomo @ users.sourceforge.jp Sat Feb 5 18:00:03 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Sat, 05 Feb 2011 18:00:03 +0900 Subject: [Julius-cvs 585] CVS update: julius4/libsent/src/adin/pa/include Message-ID: <1296896403.880193.28714.nullmailer@users.sourceforge.jp> Index: julius4/libsent/src/adin/pa/include/pa_asio.h diff -u /dev/null julius4/libsent/src/adin/pa/include/pa_asio.h:1.1 --- /dev/null Sat Feb 5 18:00:03 2011 +++ julius4/libsent/src/adin/pa/include/pa_asio.h Sat Feb 5 18:00:03 2011 @@ -0,0 +1,129 @@ +#ifndef PA_ASIO_H +#define PA_ASIO_H +/* + * $Id: pa_asio.h,v 1.1 2011/02/05 09:00:03 sumomo Exp $ + * PortAudio Portable Real-Time Audio Library + * ASIO specific extensions + * + * Copyright (c) 1999-2000 Ross Bencina and Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/* + * The text above constitutes the entire PortAudio license; however, + * the PortAudio community also makes the following non-binding requests: + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. It is also + * requested that these non-binding requests be included along with the + * license above. + */ + + +/** @file + @brief ASIO-specific PortAudio API extension header file. +*/ + + +#include "portaudio.h" + +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + + +/** Retrieve legal latency settings for the specificed device, in samples. + + @param device The global index of the device about which the query is being made. + @param minLatency A pointer to the location which will recieve the minimum latency value. + @param maxLatency A pointer to the location which will recieve the maximum latency value. + @param preferredLatency A pointer to the location which will recieve the preferred latency value. + @param granularity A pointer to the location which will recieve the granularity. This value + determines which values between minLatency and maxLatency are available. ie the step size, + if granularity is -1 then available latency settings are powers of two. + + @see ASIOGetBufferSize in the ASIO SDK. + + @todo This function should have a better name, any suggestions? +*/ +PaError PaAsio_GetAvailableLatencyValues( PaDeviceIndex device, + long *minLatency, long *maxLatency, long *preferredLatency, long *granularity ); + + +/** Display the ASIO control panel for the specified device. + + @param device The global index of the device whose control panel is to be displayed. + @param systemSpecific On Windows, the calling application's main window handle, + on Macintosh this value should be zero. +*/ +PaError PaAsio_ShowControlPanel( PaDeviceIndex device, void* systemSpecific ); + + + + +/** Retrieve a pointer to a string containing the name of the specified + input channel. The string is valid until Pa_Terminate is called. + + The string will be no longer than 32 characters including the null terminator. +*/ +PaError PaAsio_GetInputChannelName( PaDeviceIndex device, int channelIndex, + const char** channelName ); + + +/** Retrieve a pointer to a string containing the name of the specified + input channel. The string is valid until Pa_Terminate is called. + + The string will be no longer than 32 characters including the null terminator. +*/ +PaError PaAsio_GetOutputChannelName( PaDeviceIndex device, int channelIndex, + const char** channelName ); + + +#define paAsioUseChannelSelectors (0x01) + +typedef struct PaAsioStreamInfo{ + unsigned long size; /**< sizeof(PaAsioStreamInfo) */ + PaHostApiTypeId hostApiType; /**< paASIO */ + unsigned long version; /**< 1 */ + + unsigned long flags; + + /* Support for opening only specific channels of an ASIO device. + If the paAsioUseChannelSelectors flag is set, channelSelectors is a + pointer to an array of integers specifying the device channels to use. + When used, the length of the channelSelectors array must match the + corresponding channelCount parameter to Pa_OpenStream() otherwise a + crash may result. + The values in the selectors array must specify channels within the + range of supported channels for the device or paInvalidChannelCount will + result. + */ + int *channelSelectors; +}PaAsioStreamInfo; + + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* PA_ASIO_H */ Index: julius4/libsent/src/adin/pa/include/pa_jack.h diff -u /dev/null julius4/libsent/src/adin/pa/include/pa_jack.h:1.1 --- /dev/null Sat Feb 5 18:00:03 2011 +++ julius4/libsent/src/adin/pa/include/pa_jack.h Sat Feb 5 18:00:03 2011 @@ -0,0 +1,75 @@ +#ifndef PA_JACK_H +#define PA_JACK_H + +/* + * $Id: + * PortAudio Portable Real-Time Audio Library + * JACK-specific extensions + * + * Copyright (c) 1999-2000 Ross Bencina and Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/* + * The text above constitutes the entire PortAudio license; however, + * the PortAudio community also makes the following non-binding requests: + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. It is also + * requested that these non-binding requests be included along with the + * license above. + */ + +/** @file + * JACK-specific PortAudio API extension header file. + */ +#include "portaudio.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** Set the JACK client name. + * + * During Pa_Initialize, When PA JACK connects as a client of the JACK server, it requests a certain + * name, which is for instance prepended to port names. By default this name is "PortAudio". The + * JACK server may append a suffix to the client name, in order to avoid clashes among clients that + * try to connect with the same name (e.g., different PA JACK clients). + * + * This function must be called before Pa_Initialize, otherwise it won't have any effect. Note that + * the string is not copied, but instead referenced directly, so it must not be freed for as long as + * PA might need it. + * @sa PaJack_GetClientName + */ +PaError PaJack_SetClientName( const char* name ); + +/** Get the JACK client name used by PA JACK. + * + * The caller is responsible for freeing the returned pointer. + */ +PaError PaJack_GetClientName(const char** clientName); + +#ifdef __cplusplus +} +#endif + +#endif Index: julius4/libsent/src/adin/pa/include/pa_linux_alsa.h diff -u /dev/null julius4/libsent/src/adin/pa/include/pa_linux_alsa.h:1.1 --- /dev/null Sat Feb 5 18:00:03 2011 +++ julius4/libsent/src/adin/pa/include/pa_linux_alsa.h Sat Feb 5 18:00:03 2011 @@ -0,0 +1,93 @@ +#ifndef PA_LINUX_ALSA_H +#define PA_LINUX_ALSA_H + +/* + * $Id: pa_linux_alsa.h,v 1.1 2011/02/05 09:00:03 sumomo Exp $ + * PortAudio Portable Real-Time Audio Library + * ALSA-specific extensions + * + * Copyright (c) 1999-2000 Ross Bencina and Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/* + * The text above constitutes the entire PortAudio license; however, + * the PortAudio community also makes the following non-binding requests: + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. It is also + * requested that these non-binding requests be included along with the + * license above. + */ + +/** @file + * ALSA-specific PortAudio API extension header file. + */ +#include "portaudio.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct PaAlsaStreamInfo +{ + unsigned long size; + PaHostApiTypeId hostApiType; + unsigned long version; + + const char *deviceString; +} +PaAlsaStreamInfo; + +/** Initialize host API specific structure, call this before setting relevant attributes. */ +void PaAlsa_InitializeStreamInfo( PaAlsaStreamInfo *info ); + +/** Instruct whether to enable real-time priority when starting the audio thread. + * + * If this is turned on by the stream is started, the audio callback thread will be created + * with the FIFO scheduling policy, which is suitable for realtime operation. + **/ +void PaAlsa_EnableRealtimeScheduling( PaStream *s, int enable ); + +#if 0 +void PaAlsa_EnableWatchdog( PaStream *s, int enable ); +#endif + +/** Get the ALSA-lib card index of this stream's input device. */ +PaError PaAlsa_GetStreamInputCard( PaStream *s, int *card ); + +/** Get the ALSA-lib card index of this stream's output device. */ +PaError PaAlsa_GetStreamOutputCard( PaStream *s, int *card ); + +/** Set the number of periods (buffer fragments) to configure devices with. + * + * By default the number of periods is 4, this is the lowest number of periods that works well on + * the author's soundcard. + * @param numPeriods The number of periods. + */ +PaError PaAlsa_SetNumPeriods( int numPeriods ); + +#ifdef __cplusplus +} +#endif + +#endif Index: julius4/libsent/src/adin/pa/include/pa_mac_core.h diff -u /dev/null julius4/libsent/src/adin/pa/include/pa_mac_core.h:1.1 --- /dev/null Sat Feb 5 18:00:03 2011 +++ julius4/libsent/src/adin/pa/include/pa_mac_core.h Sat Feb 5 18:00:03 2011 @@ -0,0 +1,171 @@ +#ifndef PA_MAC_CORE_H +#define PA_MAC_CORE_H +/* + * PortAudio Portable Real-Time Audio Library + * Macintosh Core Audio specific extensions + * portaudio.h should be included before this file. + * + * Copyright (c) 2005-2006 Bjorn Roche + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/* + * The text above constitutes the entire PortAudio license; however, + * the PortAudio community also makes the following non-binding requests: + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. It is also + * requested that these non-binding requests be included along with the + * license above. + */ + +#include +//#include + +#ifdef __cplusplus +extern "C" { +#endif + + +/* + * A pointer to a paMacCoreStreamInfo may be passed as + * the hostApiSpecificStreamInfo in the PaStreamParameters struct + * when opening a stream or querying the format. Use NULL, for the + * defaults. Note that for duplex streams, flags for input and output + * should be the same or behaviour is undefined. + */ +typedef struct +{ + unsigned long size; /**size of whole structure including this header */ + PaHostApiTypeId hostApiType; /**host API for which this data is intended */ + unsigned long version; /**structure version */ + unsigned long flags; /* flags to modify behaviour */ + SInt32 const * channelMap; /* Channel map for HAL channel mapping , if not needed, use NULL;*/ + unsigned long channelMapSize; /* Channel map size for HAL channel mapping , if not needed, use 0;*/ +} PaMacCoreStreamInfo; + +/* + * Functions + */ + + +/* Use this function to initialize a paMacCoreStreamInfo struct + * using the requested flags. Note that channel mapping is turned + * off after a call to this function. + * @param data The datastructure to initialize + * @param flags The flags to initialize the datastructure with. +*/ +void PaMacCore_SetupStreamInfo( PaMacCoreStreamInfo *data, unsigned long flags ); + +/* call this after pa_SetupMacCoreStreamInfo to use channel mapping as described in notes.txt. + * @param data The stream info structure to assign a channel mapping to + * @param channelMap The channel map array, as described in notes.txt. This array pointer will be used directly (ie the underlying data will not be copied), so the caller should not free the array until after the stream has been opened. + * @param channelMapSize The size of the channel map array. + */ +void PaMacCore_SetupChannelMap( PaMacCoreStreamInfo *data, const SInt32 * const channelMap, unsigned long channelMapSize ); + +/* + * Retrieve the AudioDeviceID of the input device assigned to an open stream + * + * @param s The stream to query. + * + * @return A valid AudioDeviceID, or NULL if an error occurred. + */ +AudioDeviceID PaMacCore_GetStreamInputDevice( PaStream* s ); + +/* + * Retrieve the AudioDeviceID of the output device assigned to an open stream + * + * @param s The stream to query. + * + * @return A valid AudioDeviceID, or NULL if an error occurred. + */ +AudioDeviceID PaMacCore_GetStreamOutputDevice( PaStream* s ); + +/* + * Returns a statically allocated string with the device's name + * for the given channel. NULL will be returned on failure. + * + * This function's implemenation is not complete! + * + * @param device The PortAudio device index. + * @param channel The channel number who's name is requested. + * @return a statically allocated string with the name of the device. + * Because this string is statically allocated, it must be + * coppied if it is to be saved and used by the user after + * another call to this function. + * + */ +const char *PaMacCore_GetChannelName( int device, int channelIndex, bool input ); + +/* + * Flags + */ + +/* + * The following flags alter the behaviour of PA on the mac platform. + * they can be ORed together. These should work both for opening and + * checking a device. + */ + +/* Allows PortAudio to change things like the device's frame size, + * which allows for much lower latency, but might disrupt the device + * if other programs are using it, even when you are just Querying + * the device. */ +#define paMacCoreChangeDeviceParameters (0x01) + +/* In combination with the above flag, + * causes the stream opening to fail, unless the exact sample rates + * are supported by the device. */ +#define paMacCoreFailIfConversionRequired (0x02) + +/* These flags set the SR conversion quality, if required. The wierd ordering + * allows Maximum Quality to be the default.*/ +#define paMacCoreConversionQualityMin (0x0100) +#define paMacCoreConversionQualityMedium (0x0200) +#define paMacCoreConversionQualityLow (0x0300) +#define paMacCoreConversionQualityHigh (0x0400) +#define paMacCoreConversionQualityMax (0x0000) + +/* + * Here are some "preset" combinations of flags (above) to get to some + * common configurations. THIS IS OVERKILL, but if more flags are added + * it won't be. + */ + +/*This is the default setting: do as much sample rate conversion as possible + * and as little mucking with the device as possible. */ +#define paMacCorePlayNice (0x00) +/*This setting is tuned for pro audio apps. It allows SR conversion on input + and output, but it tries to set the appropriate SR on the device.*/ +#define paMacCorePro (0x01) +/*This is a setting to minimize CPU usage and still play nice.*/ +#define paMacCoreMinimizeCPUButPlayNice (0x0100) +/*This is a setting to minimize CPU usage, even if that means interrupting the device. */ +#define paMacCoreMinimizeCPU (0x0101) + + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* PA_MAC_CORE_H */ Index: julius4/libsent/src/adin/pa/include/pa_win_ds.h diff -u /dev/null julius4/libsent/src/adin/pa/include/pa_win_ds.h:1.1 --- /dev/null Sat Feb 5 18:00:03 2011 +++ julius4/libsent/src/adin/pa/include/pa_win_ds.h Sat Feb 5 18:00:03 2011 @@ -0,0 +1,100 @@ +#ifndef PA_WIN_DS_H +#define PA_WIN_DS_H +/* + * $Id: pa_win_ds.h,v 1.1 2011/02/05 09:00:03 sumomo Exp $ + * PortAudio Portable Real-Time Audio Library + * DirectSound specific extensions + * + * Copyright (c) 1999-2007 Ross Bencina and Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/* + * The text above constitutes the entire PortAudio license; however, + * the PortAudio community also makes the following non-binding requests: + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. It is also + * requested that these non-binding requests be included along with the + * license above. + */ + +/** @file + @brief DirectSound-specific PortAudio API extension header file. +*/ + + +#include "portaudio.h" +#include "pa_win_waveformat.h" + +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + + +#define paWinDirectSoundUseLowLevelLatencyParameters (0x01) +#define paWinDirectSoundUseChannelMask (0x04) + + +typedef struct PaWinDirectSoundStreamInfo{ + unsigned long size; /**< sizeof(PaWinDirectSoundStreamInfo) */ + PaHostApiTypeId hostApiType; /**< paDirectSound */ + unsigned long version; /**< 1 */ + + unsigned long flags; + + /* low-level latency setting support + TODO ** NOT IMPLEMENTED ** + These settings control the number and size of host buffers in order + to set latency. They will be used instead of the generic parameters + to Pa_OpenStream() if flags contains the paWinDirectSoundUseLowLevelLatencyParameters + flag. + + If PaWinDirectSoundStreamInfo structures with paWinDirectSoundUseLowLevelLatencyParameters + are supplied for both input and output in a full duplex stream, then the + input and output framesPerBuffer must be the same, or the larger of the + two must be a multiple of the smaller, otherwise a + paIncompatibleHostApiSpecificStreamInfo error will be returned from + Pa_OpenStream(). + + unsigned long framesPerBuffer; + */ + + /* + support for WAVEFORMATEXTENSIBLE channel masks. If flags contains + paWinDirectSoundUseChannelMask this allows you to specify which speakers + to address in a multichannel stream. Constants for channelMask + are specified in pa_win_waveformat.h + + */ + PaWinWaveFormatChannelMask channelMask; + +}PaWinDirectSoundStreamInfo; + + + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* PA_WIN_DS_H */ Index: julius4/libsent/src/adin/pa/include/pa_win_waveformat.h diff -u /dev/null julius4/libsent/src/adin/pa/include/pa_win_waveformat.h:1.1 --- /dev/null Sat Feb 5 18:00:03 2011 +++ julius4/libsent/src/adin/pa/include/pa_win_waveformat.h Sat Feb 5 18:00:03 2011 @@ -0,0 +1,180 @@ +#ifndef PA_WIN_WAVEFORMAT_H +#define PA_WIN_WAVEFORMAT_H + +/* + * PortAudio Portable Real-Time Audio Library + * Windows WAVEFORMAT* data structure utilities + * portaudio.h should be included before this file. + * + * Copyright (c) 2007 Ross Bencina + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/* + * The text above constitutes the entire PortAudio license; however, + * the PortAudio community also makes the following non-binding requests: + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. It is also + * requested that these non-binding requests be included along with the + * license above. + */ + +/** @file + @brief Windows specific PortAudio API extension and utilities header file. +*/ + +#ifdef __cplusplus +extern "C" { +#endif + +/* + The following #defines for speaker channel masks are the same + as those in ksmedia.h, except with PAWIN_ prepended, KSAUDIO_ removed + in some cases, and casts to PaWinWaveFormatChannelMask added. +*/ + +typedef unsigned long PaWinWaveFormatChannelMask; + +/* Speaker Positions: */ +#define PAWIN_SPEAKER_FRONT_LEFT ((PaWinWaveFormatChannelMask)0x1) +#define PAWIN_SPEAKER_FRONT_RIGHT ((PaWinWaveFormatChannelMask)0x2) +#define PAWIN_SPEAKER_FRONT_CENTER ((PaWinWaveFormatChannelMask)0x4) +#define PAWIN_SPEAKER_LOW_FREQUENCY ((PaWinWaveFormatChannelMask)0x8) +#define PAWIN_SPEAKER_BACK_LEFT ((PaWinWaveFormatChannelMask)0x10) +#define PAWIN_SPEAKER_BACK_RIGHT ((PaWinWaveFormatChannelMask)0x20) +#define PAWIN_SPEAKER_FRONT_LEFT_OF_CENTER ((PaWinWaveFormatChannelMask)0x40) +#define PAWIN_SPEAKER_FRONT_RIGHT_OF_CENTER ((PaWinWaveFormatChannelMask)0x80) +#define PAWIN_SPEAKER_BACK_CENTER ((PaWinWaveFormatChannelMask)0x100) +#define PAWIN_SPEAKER_SIDE_LEFT ((PaWinWaveFormatChannelMask)0x200) +#define PAWIN_SPEAKER_SIDE_RIGHT ((PaWinWaveFormatChannelMask)0x400) +#define PAWIN_SPEAKER_TOP_CENTER ((PaWinWaveFormatChannelMask)0x800) +#define PAWIN_SPEAKER_TOP_FRONT_LEFT ((PaWinWaveFormatChannelMask)0x1000) +#define PAWIN_SPEAKER_TOP_FRONT_CENTER ((PaWinWaveFormatChannelMask)0x2000) +#define PAWIN_SPEAKER_TOP_FRONT_RIGHT ((PaWinWaveFormatChannelMask)0x4000) +#define PAWIN_SPEAKER_TOP_BACK_LEFT ((PaWinWaveFormatChannelMask)0x8000) +#define PAWIN_SPEAKER_TOP_BACK_CENTER ((PaWinWaveFormatChannelMask)0x10000) +#define PAWIN_SPEAKER_TOP_BACK_RIGHT ((PaWinWaveFormatChannelMask)0x20000) + +/* Bit mask locations reserved for future use */ +#define PAWIN_SPEAKER_RESERVED ((PaWinWaveFormatChannelMask)0x7FFC0000) + +/* Used to specify that any possible permutation of speaker configurations */ +#define PAWIN_SPEAKER_ALL ((PaWinWaveFormatChannelMask)0x80000000) + +/* DirectSound Speaker Config */ +#define PAWIN_SPEAKER_DIRECTOUT 0 +#define PAWIN_SPEAKER_MONO (PAWIN_SPEAKER_FRONT_CENTER) +#define PAWIN_SPEAKER_STEREO (PAWIN_SPEAKER_FRONT_LEFT | PAWIN_SPEAKER_FRONT_RIGHT) +#define PAWIN_SPEAKER_QUAD (PAWIN_SPEAKER_FRONT_LEFT | PAWIN_SPEAKER_FRONT_RIGHT | \ + PAWIN_SPEAKER_BACK_LEFT | PAWIN_SPEAKER_BACK_RIGHT) +#define PAWIN_SPEAKER_SURROUND (PAWIN_SPEAKER_FRONT_LEFT | PAWIN_SPEAKER_FRONT_RIGHT | \ + PAWIN_SPEAKER_FRONT_CENTER | PAWIN_SPEAKER_BACK_CENTER) +#define PAWIN_SPEAKER_5POINT1 (PAWIN_SPEAKER_FRONT_LEFT | PAWIN_SPEAKER_FRONT_RIGHT | \ + PAWIN_SPEAKER_FRONT_CENTER | PAWIN_SPEAKER_LOW_FREQUENCY | \ + PAWIN_SPEAKER_BACK_LEFT | PAWIN_SPEAKER_BACK_RIGHT) +#define PAWIN_SPEAKER_7POINT1 (PAWIN_SPEAKER_FRONT_LEFT | PAWIN_SPEAKER_FRONT_RIGHT | \ + PAWIN_SPEAKER_FRONT_CENTER | PAWIN_SPEAKER_LOW_FREQUENCY | \ + PAWIN_SPEAKER_BACK_LEFT | PAWIN_SPEAKER_BACK_RIGHT | \ + PAWIN_SPEAKER_FRONT_LEFT_OF_CENTER | PAWIN_SPEAKER_FRONT_RIGHT_OF_CENTER) +#define PAWIN_SPEAKER_5POINT1_SURROUND (PAWIN_SPEAKER_FRONT_LEFT | PAWIN_SPEAKER_FRONT_RIGHT | \ + PAWIN_SPEAKER_FRONT_CENTER | PAWIN_SPEAKER_LOW_FREQUENCY | \ + PAWIN_SPEAKER_SIDE_LEFT | PAWIN_SPEAKER_SIDE_RIGHT) +#define PAWIN_SPEAKER_7POINT1_SURROUND (PAWIN_SPEAKER_FRONT_LEFT | PAWIN_SPEAKER_FRONT_RIGHT | \ + PAWIN_SPEAKER_FRONT_CENTER | PAWIN_SPEAKER_LOW_FREQUENCY | \ + PAWIN_SPEAKER_BACK_LEFT | PAWIN_SPEAKER_BACK_RIGHT | \ + PAWIN_SPEAKER_SIDE_LEFT | PAWIN_SPEAKER_SIDE_RIGHT) +/* + According to the Microsoft documentation: + The following are obsolete 5.1 and 7.1 settings (they lack side speakers). Note this means + that the default 5.1 and 7.1 settings (KSAUDIO_SPEAKER_5POINT1 and KSAUDIO_SPEAKER_7POINT1 are + similarly obsolete but are unchanged for compatibility reasons). +*/ +#define PAWIN_SPEAKER_5POINT1_BACK PAWIN_SPEAKER_5POINT1 +#define PAWIN_SPEAKER_7POINT1_WIDE PAWIN_SPEAKER_7POINT1 + +/* DVD Speaker Positions */ +#define PAWIN_SPEAKER_GROUND_FRONT_LEFT PAWIN_SPEAKER_FRONT_LEFT +#define PAWIN_SPEAKER_GROUND_FRONT_CENTER PAWIN_SPEAKER_FRONT_CENTER +#define PAWIN_SPEAKER_GROUND_FRONT_RIGHT PAWIN_SPEAKER_FRONT_RIGHT +#define PAWIN_SPEAKER_GROUND_REAR_LEFT PAWIN_SPEAKER_BACK_LEFT +#define PAWIN_SPEAKER_GROUND_REAR_RIGHT PAWIN_SPEAKER_BACK_RIGHT +#define PAWIN_SPEAKER_TOP_MIDDLE PAWIN_SPEAKER_TOP_CENTER +#define PAWIN_SPEAKER_SUPER_WOOFER PAWIN_SPEAKER_LOW_FREQUENCY + + +/* + PaWinWaveFormat is defined here to provide compatibility with + compilation environments which don't have headers defining + WAVEFORMATEXTENSIBLE (e.g. older versions of MSVC, Borland C++ etc. + + The fields for WAVEFORMATEX and WAVEFORMATEXTENSIBLE are declared as an + unsigned char array here to avoid clients who include this file having + a dependency on windows.h and mmsystem.h, and also to to avoid having + to write separate packing pragmas for each compiler. +*/ +#define PAWIN_SIZEOF_WAVEFORMATEX 18 +#define PAWIN_SIZEOF_WAVEFORMATEXTENSIBLE (PAWIN_SIZEOF_WAVEFORMATEX + 22) + +typedef struct{ + unsigned char fields[ PAWIN_SIZEOF_WAVEFORMATEXTENSIBLE ]; + unsigned long extraLongForAlignment; /* ensure that compiler aligns struct to DWORD */ +} PaWinWaveFormat; + +/* + WAVEFORMATEXTENSIBLE fields: + + union { + WORD wValidBitsPerSample; + WORD wSamplesPerBlock; + WORD wReserved; + } Samples; + DWORD dwChannelMask; + GUID SubFormat; +*/ + +#define PAWIN_INDEXOF_WVALIDBITSPERSAMPLE (PAWIN_SIZEOF_WAVEFORMATEX+0) +#define PAWIN_INDEXOF_DWCHANNELMASK (PAWIN_SIZEOF_WAVEFORMATEX+2) +#define PAWIN_INDEXOF_SUBFORMAT (PAWIN_SIZEOF_WAVEFORMATEX+6) + +/* + Use the following two functions to initialize the waveformat structure. +*/ + +void PaWin_InitializeWaveFormatEx( PaWinWaveFormat *waveFormat, + int numChannels, PaSampleFormat sampleFormat, double sampleRate ); + + +void PaWin_InitializeWaveFormatExtensible( PaWinWaveFormat *waveFormat, + int numChannels, PaSampleFormat sampleFormat, double sampleRate, + PaWinWaveFormatChannelMask channelMask ); + + +/* Map a channel count to a speaker channel mask */ +PaWinWaveFormatChannelMask PaWin_DefaultChannelMask( int numChannels ); + + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* PA_WIN_WAVEFORMAT_H */ Index: julius4/libsent/src/adin/pa/include/pa_win_wmme.h diff -u /dev/null julius4/libsent/src/adin/pa/include/pa_win_wmme.h:1.1 --- /dev/null Sat Feb 5 18:00:03 2011 +++ julius4/libsent/src/adin/pa/include/pa_win_wmme.h Sat Feb 5 18:00:03 2011 @@ -0,0 +1,176 @@ +#ifndef PA_WIN_WMME_H +#define PA_WIN_WMME_H +/* + * $Id: pa_win_wmme.h,v 1.1 2011/02/05 09:00:03 sumomo Exp $ + * PortAudio Portable Real-Time Audio Library + * MME specific extensions + * + * Copyright (c) 1999-2000 Ross Bencina and Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/* + * The text above constitutes the entire PortAudio license; however, + * the PortAudio community also makes the following non-binding requests: + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. It is also + * requested that these non-binding requests be included along with the + * license above. + */ + +/** @file + @brief WMME-specific PortAudio API extension header file. +*/ + + +#include "portaudio.h" +#include "pa_win_waveformat.h" + +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + + +#define paWinMmeUseLowLevelLatencyParameters (0x01) +#define paWinMmeUseMultipleDevices (0x02) /* use mme specific multiple device feature */ +#define paWinMmeUseChannelMask (0x04) + +/* By default, the mme implementation drops the processing thread's priority + to THREAD_PRIORITY_NORMAL and sleeps the thread if the CPU load exceeds 100% + This flag disables any priority throttling. The processing thread will always + run at THREAD_PRIORITY_TIME_CRITICAL. +*/ +#define paWinMmeDontThrottleOverloadedProcessingThread (0x08) + + +typedef struct PaWinMmeDeviceAndChannelCount{ + PaDeviceIndex device; + int channelCount; +}PaWinMmeDeviceAndChannelCount; + + +typedef struct PaWinMmeStreamInfo{ + unsigned long size; /**< sizeof(PaWinMmeStreamInfo) */ + PaHostApiTypeId hostApiType; /**< paMME */ + unsigned long version; /**< 1 */ + + unsigned long flags; + + /* low-level latency setting support + These settings control the number and size of host buffers in order + to set latency. They will be used instead of the generic parameters + to Pa_OpenStream() if flags contains the PaWinMmeUseLowLevelLatencyParameters + flag. + + If PaWinMmeStreamInfo structures with PaWinMmeUseLowLevelLatencyParameters + are supplied for both input and output in a full duplex stream, then the + input and output framesPerBuffer must be the same, or the larger of the + two must be a multiple of the smaller, otherwise a + paIncompatibleHostApiSpecificStreamInfo error will be returned from + Pa_OpenStream(). + */ + unsigned long framesPerBuffer; + unsigned long bufferCount; /* formerly numBuffers */ + + /* multiple devices per direction support + If flags contains the PaWinMmeUseMultipleDevices flag, + this functionality will be used, otherwise the device parameter to + Pa_OpenStream() will be used instead. + If devices are specified here, the corresponding device parameter + to Pa_OpenStream() should be set to paUseHostApiSpecificDeviceSpecification, + otherwise an paInvalidDevice error will result. + The total number of channels accross all specified devices + must agree with the corresponding channelCount parameter to + Pa_OpenStream() otherwise a paInvalidChannelCount error will result. + */ + PaWinMmeDeviceAndChannelCount *devices; + unsigned long deviceCount; + + /* + support for WAVEFORMATEXTENSIBLE channel masks. If flags contains + paWinMmeUseChannelMask this allows you to specify which speakers + to address in a multichannel stream. Constants for channelMask + are specified in pa_win_waveformat.h + + */ + PaWinWaveFormatChannelMask channelMask; + +}PaWinMmeStreamInfo; + + +/** Retrieve the number of wave in handles used by a PortAudio WinMME stream. + Returns zero if the stream is output only. + + @return A non-negative value indicating the number of wave in handles + or, a PaErrorCode (which are always negative) if PortAudio is not initialized + or an error is encountered. + + @see PaWinMME_GetStreamInputHandle +*/ +int PaWinMME_GetStreamInputHandleCount( PaStream* stream ); + + +/** Retrieve a wave in handle used by a PortAudio WinMME stream. + + @param stream The stream to query. + @param handleIndex The zero based index of the wave in handle to retrieve. This + should be in the range [0, PaWinMME_GetStreamInputHandleCount(stream)-1]. + + @return A valid wave in handle, or NULL if an error occurred. + + @see PaWinMME_GetStreamInputHandle +*/ +HWAVEIN PaWinMME_GetStreamInputHandle( PaStream* stream, int handleIndex ); + + +/** Retrieve the number of wave out handles used by a PortAudio WinMME stream. + Returns zero if the stream is input only. + + @return A non-negative value indicating the number of wave out handles + or, a PaErrorCode (which are always negative) if PortAudio is not initialized + or an error is encountered. + + @see PaWinMME_GetStreamOutputHandle +*/ +int PaWinMME_GetStreamOutputHandleCount( PaStream* stream ); + + +/** Retrieve a wave out handle used by a PortAudio WinMME stream. + + @param stream The stream to query. + @param handleIndex The zero based index of the wave out handle to retrieve. + This should be in the range [0, PaWinMME_GetStreamOutputHandleCount(stream)-1]. + + @return A valid wave out handle, or NULL if an error occurred. + + @see PaWinMME_GetStreamOutputHandleCount +*/ +HWAVEOUT PaWinMME_GetStreamOutputHandle( PaStream* stream, int handleIndex ); + + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* PA_WIN_WMME_H */ Index: julius4/libsent/src/adin/pa/include/portaudio.h diff -u /dev/null julius4/libsent/src/adin/pa/include/portaudio.h:1.1 --- /dev/null Sat Feb 5 18:00:03 2011 +++ julius4/libsent/src/adin/pa/include/portaudio.h Sat Feb 5 18:00:03 2011 @@ -0,0 +1,1133 @@ +#ifndef PORTAUDIO_H +#define PORTAUDIO_H +/* + * $Id: portaudio.h,v 1.1 2011/02/05 09:00:03 sumomo Exp $ + * PortAudio Portable Real-Time Audio Library + * PortAudio API Header File + * Latest version available at: http://www.portaudio.com/ + * + * Copyright (c) 1999-2002 Ross Bencina and Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/* + * The text above constitutes the entire PortAudio license; however, + * the PortAudio community also makes the following non-binding requests: + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. It is also + * requested that these non-binding requests be included along with the + * license above. + */ + +/** @file + @brief The PortAudio API. +*/ + + +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + + +/** Retrieve the release number of the currently running PortAudio build, + eg 1900. +*/ +int Pa_GetVersion( void ); + + +/** Retrieve a textual description of the current PortAudio build, + eg "PortAudio V19-devel 13 October 2002". +*/ +const char* Pa_GetVersionText( void ); + + +/** Error codes returned by PortAudio functions. + Note that with the exception of paNoError, all PaErrorCodes are negative. +*/ + +typedef int PaError; +typedef enum PaErrorCode +{ + paNoError = 0, + + paNotInitialized = -10000, + paUnanticipatedHostError, + paInvalidChannelCount, + paInvalidSampleRate, + paInvalidDevice, + paInvalidFlag, + paSampleFormatNotSupported, + paBadIODeviceCombination, + paInsufficientMemory, + paBufferTooBig, + paBufferTooSmall, + paNullCallback, + paBadStreamPtr, + paTimedOut, + paInternalError, + paDeviceUnavailable, + paIncompatibleHostApiSpecificStreamInfo, + paStreamIsStopped, + paStreamIsNotStopped, + paInputOverflowed, + paOutputUnderflowed, + paHostApiNotFound, + paInvalidHostApi, + paCanNotReadFromACallbackStream, /**< @todo review error code name */ + paCanNotWriteToACallbackStream, /**< @todo review error code name */ + paCanNotReadFromAnOutputOnlyStream, /**< @todo review error code name */ + paCanNotWriteToAnInputOnlyStream, /**< @todo review error code name */ + paIncompatibleStreamHostApi, + paBadBufferPtr +} PaErrorCode; + + +/** Translate the supplied PortAudio error code into a human readable + message. +*/ +const char *Pa_GetErrorText( PaError errorCode ); + + +/** Library initialization function - call this before using PortAudio. + This function initialises internal data structures and prepares underlying + host APIs for use. With the exception of Pa_GetVersion(), Pa_GetVersionText(), + and Pa_GetErrorText(), this function MUST be called before using any other + PortAudio API functions. + + If Pa_Initialize() is called multiple times, each successful + call must be matched with a corresponding call to Pa_Terminate(). + Pairs of calls to Pa_Initialize()/Pa_Terminate() may overlap, and are not + required to be fully nested. + + Note that if Pa_Initialize() returns an error code, Pa_Terminate() should + NOT be called. + + @return paNoError if successful, otherwise an error code indicating the cause + of failure. + + @see Pa_Terminate +*/ +PaError Pa_Initialize( void ); + + +/** Library termination function - call this when finished using PortAudio. + This function deallocates all resources allocated by PortAudio since it was + initializied by a call to Pa_Initialize(). In cases where Pa_Initialise() has + been called multiple times, each call must be matched with a corresponding call + to Pa_Terminate(). The final matching call to Pa_Terminate() will automatically + close any PortAudio streams that are still open. + + Pa_Terminate() MUST be called before exiting a program which uses PortAudio. + Failure to do so may result in serious resource leaks, such as audio devices + not being available until the next reboot. + + @return paNoError if successful, otherwise an error code indicating the cause + of failure. + + @see Pa_Initialize +*/ +PaError Pa_Terminate( void ); + + + +/** The type used to refer to audio devices. Values of this type usually + range from 0 to (Pa_GetDeviceCount()-1), and may also take on the PaNoDevice + and paUseHostApiSpecificDeviceSpecification values. + + @see Pa_GetDeviceCount, paNoDevice, paUseHostApiSpecificDeviceSpecification +*/ +typedef int PaDeviceIndex; + + +/** A special PaDeviceIndex value indicating that no device is available, + or should be used. + + @see PaDeviceIndex +*/ +#define paNoDevice ((PaDeviceIndex)-1) + + +/** A special PaDeviceIndex value indicating that the device(s) to be used + are specified in the host api specific stream info structure. + + @see PaDeviceIndex +*/ +#define paUseHostApiSpecificDeviceSpecification ((PaDeviceIndex)-2) + + +/* Host API enumeration mechanism */ + +/** The type used to enumerate to host APIs at runtime. Values of this type + range from 0 to (Pa_GetHostApiCount()-1). + + @see Pa_GetHostApiCount +*/ +typedef int PaHostApiIndex; + + +/** Retrieve the number of available host APIs. Even if a host API is + available it may have no devices available. + + @return A non-negative value indicating the number of available host APIs + or, a PaErrorCode (which are always negative) if PortAudio is not initialized + or an error is encountered. + + @see PaHostApiIndex +*/ +PaHostApiIndex Pa_GetHostApiCount( void ); + + +/** Retrieve the index of the default host API. The default host API will be + the lowest common denominator host API on the current platform and is + unlikely to provide the best performance. + + @return A non-negative value ranging from 0 to (Pa_GetHostApiCount()-1) + indicating the default host API index or, a PaErrorCode (which are always + negative) if PortAudio is not initialized or an error is encountered. +*/ +PaHostApiIndex Pa_GetDefaultHostApi( void ); + + +/** Unchanging unique identifiers for each supported host API. This type + is used in the PaHostApiInfo structure. The values are guaranteed to be + unique and to never change, thus allowing code to be written that + conditionally uses host API specific extensions. + + New type ids will be allocated when support for a host API reaches + "public alpha" status, prior to that developers should use the + paInDevelopment type id. + + @see PaHostApiInfo +*/ +typedef enum PaHostApiTypeId +{ + paInDevelopment=0, /* use while developing support for a new host API */ + paDirectSound=1, + paMME=2, + paASIO=3, + paSoundManager=4, + paCoreAudio=5, + paOSS=7, + paALSA=8, + paAL=9, + paBeOS=10, + paWDMKS=11, + paJACK=12, + paWASAPI=13, + paAudioScienceHPI=14 +} PaHostApiTypeId; + + +/** A structure containing information about a particular host API. */ + +typedef struct PaHostApiInfo +{ + /** this is struct version 1 */ + int structVersion; + /** The well known unique identifier of this host API @see PaHostApiTypeId */ + PaHostApiTypeId type; + /** A textual description of the host API for display on user interfaces. */ + const char *name; + + /** The number of devices belonging to this host API. This field may be + used in conjunction with Pa_HostApiDeviceIndexToDeviceIndex() to enumerate + all devices for this host API. + @see Pa_HostApiDeviceIndexToDeviceIndex + */ + int deviceCount; + + /** The default input device for this host API. The value will be a + device index ranging from 0 to (Pa_GetDeviceCount()-1), or paNoDevice + if no default input device is available. + */ + PaDeviceIndex defaultInputDevice; + + /** The default output device for this host API. The value will be a + device index ranging from 0 to (Pa_GetDeviceCount()-1), or paNoDevice + if no default output device is available. + */ + PaDeviceIndex defaultOutputDevice; + +} PaHostApiInfo; + + +/** Retrieve a pointer to a structure containing information about a specific + host Api. + + @param hostApi A valid host API index ranging from 0 to (Pa_GetHostApiCount()-1) + + @return A pointer to an immutable PaHostApiInfo structure describing + a specific host API. If the hostApi parameter is out of range or an error + is encountered, the function returns NULL. + + The returned structure is owned by the PortAudio implementation and must not + be manipulated or freed. The pointer is only guaranteed to be valid between + calls to Pa_Initialize() and Pa_Terminate(). +*/ +const PaHostApiInfo * Pa_GetHostApiInfo( PaHostApiIndex hostApi ); + + +/** Convert a static host API unique identifier, into a runtime + host API index. + + @param type A unique host API identifier belonging to the PaHostApiTypeId + enumeration. + + @return A valid PaHostApiIndex ranging from 0 to (Pa_GetHostApiCount()-1) or, + a PaErrorCode (which are always negative) if PortAudio is not initialized + or an error is encountered. + + The paHostApiNotFound error code indicates that the host API specified by the + type parameter is not available. + + @see PaHostApiTypeId +*/ +PaHostApiIndex Pa_HostApiTypeIdToHostApiIndex( PaHostApiTypeId type ); + + +/** Convert a host-API-specific device index to standard PortAudio device index. + This function may be used in conjunction with the deviceCount field of + PaHostApiInfo to enumerate all devices for the specified host API. + + @param hostApi A valid host API index ranging from 0 to (Pa_GetHostApiCount()-1) + + @param hostApiDeviceIndex A valid per-host device index in the range + 0 to (Pa_GetHostApiInfo(hostApi)->deviceCount-1) + + @return A non-negative PaDeviceIndex ranging from 0 to (Pa_GetDeviceCount()-1) + or, a PaErrorCode (which are always negative) if PortAudio is not initialized + or an error is encountered. + + A paInvalidHostApi error code indicates that the host API index specified by + the hostApi parameter is out of range. + + A paInvalidDevice error code indicates that the hostApiDeviceIndex parameter + is out of range. + + @see PaHostApiInfo +*/ +PaDeviceIndex Pa_HostApiDeviceIndexToDeviceIndex( PaHostApiIndex hostApi, + int hostApiDeviceIndex ); + + + +/** Structure used to return information about a host error condition. +*/ +typedef struct PaHostErrorInfo{ + PaHostApiTypeId hostApiType; /**< the host API which returned the error code */ + long errorCode; /**< the error code returned */ + const char *errorText; /**< a textual description of the error if available, otherwise a zero-length string */ +}PaHostErrorInfo; + + +/** Return information about the last host error encountered. The error + information returned by Pa_GetLastHostErrorInfo() will never be modified + asyncronously by errors occurring in other PortAudio owned threads + (such as the thread that manages the stream callback.) + + This function is provided as a last resort, primarily to enhance debugging + by providing clients with access to all available error information. + + @return A pointer to an immutable structure constaining information about + the host error. The values in this structure will only be valid if a + PortAudio function has previously returned the paUnanticipatedHostError + error code. +*/ +const PaHostErrorInfo* Pa_GetLastHostErrorInfo( void ); + + + +/* Device enumeration and capabilities */ + +/** Retrieve the number of available devices. The number of available devices + may be zero. + + @return A non-negative value indicating the number of available devices or, + a PaErrorCode (which are always negative) if PortAudio is not initialized + or an error is encountered. +*/ +PaDeviceIndex Pa_GetDeviceCount( void ); + + +/** Retrieve the index of the default input device. The result can be + used in the inputDevice parameter to Pa_OpenStream(). + + @return The default input device index for the default host API, or paNoDevice + if no default input device is available or an error was encountered. +*/ +PaDeviceIndex Pa_GetDefaultInputDevice( void ); + + +/** Retrieve the index of the default output device. The result can be + used in the outputDevice parameter to Pa_OpenStream(). + + @return The default output device index for the defualt host API, or paNoDevice + if no default output device is available or an error was encountered. + + @note + On the PC, the user can specify a default device by + setting an environment variable. For example, to use device #1. +
+ set PA_RECOMMENDED_OUTPUT_DEVICE=1
+
+ The user should first determine the available device ids by using + the supplied application "pa_devs". +*/ +PaDeviceIndex Pa_GetDefaultOutputDevice( void ); + + +/** The type used to represent monotonic time in seconds that can be used + for syncronisation. The type is used for the outTime argument to the + PaStreamCallback and as the result of Pa_GetStreamTime(). + + @see PaStreamCallback, Pa_GetStreamTime +*/ +typedef double PaTime; + + +/** A type used to specify one or more sample formats. Each value indicates + a possible format for sound data passed to and from the stream callback, + Pa_ReadStream and Pa_WriteStream. + + The standard formats paFloat32, paInt16, paInt32, paInt24, paInt8 + and aUInt8 are usually implemented by all implementations. + + The floating point representation (paFloat32) uses +1.0 and -1.0 as the + maximum and minimum respectively. + + paUInt8 is an unsigned 8 bit format where 128 is considered "ground" + + The paNonInterleaved flag indicates that a multichannel buffer is passed + as a set of non-interleaved pointers. + + @see Pa_OpenStream, Pa_OpenDefaultStream, PaDeviceInfo + @see paFloat32, paInt16, paInt32, paInt24, paInt8 + @see paUInt8, paCustomFormat, paNonInterleaved +*/ +typedef unsigned long PaSampleFormat; + + +#define paFloat32 ((PaSampleFormat) 0x00000001) /**< @see PaSampleFormat */ +#define paInt32 ((PaSampleFormat) 0x00000002) /**< @see PaSampleFormat */ +#define paInt24 ((PaSampleFormat) 0x00000004) /**< Packed 24 bit format. @see PaSampleFormat */ +#define paInt16 ((PaSampleFormat) 0x00000008) /**< @see PaSampleFormat */ +#define paInt8 ((PaSampleFormat) 0x00000010) /**< @see PaSampleFormat */ +#define paUInt8 ((PaSampleFormat) 0x00000020) /**< @see PaSampleFormat */ +#define paCustomFormat ((PaSampleFormat) 0x00010000)/**< @see PaSampleFormat */ + +#define paNonInterleaved ((PaSampleFormat) 0x80000000) + +/** A structure providing information and capabilities of PortAudio devices. + Devices may support input, output or both input and output. +*/ +typedef struct PaDeviceInfo +{ + int structVersion; /* this is struct version 2 */ + const char *name; + PaHostApiIndex hostApi; /* note this is a host API index, not a type id*/ + + int maxInputChannels; + int maxOutputChannels; + + /* Default latency values for interactive performance. */ + PaTime defaultLowInputLatency; + PaTime defaultLowOutputLatency; + /* Default latency values for robust non-interactive applications (eg. playing sound files). */ + PaTime defaultHighInputLatency; + PaTime defaultHighOutputLatency; + + double defaultSampleRate; +} PaDeviceInfo; + + +/** Retrieve a pointer to a PaDeviceInfo structure containing information + about the specified device. + @return A pointer to an immutable PaDeviceInfo structure. If the device + parameter is out of range the function returns NULL. + + @param device A valid device index in the range 0 to (Pa_GetDeviceCount()-1) + + @note PortAudio manages the memory referenced by the returned pointer, + the client must not manipulate or free the memory. The pointer is only + guaranteed to be valid between calls to Pa_Initialize() and Pa_Terminate(). + + @see PaDeviceInfo, PaDeviceIndex +*/ +const PaDeviceInfo* Pa_GetDeviceInfo( PaDeviceIndex device ); + + +/** Parameters for one direction (input or output) of a stream. +*/ +typedef struct PaStreamParameters +{ + /** A valid device index in the range 0 to (Pa_GetDeviceCount()-1) + specifying the device to be used or the special constant + paUseHostApiSpecificDeviceSpecification which indicates that the actual + device(s) to use are specified in hostApiSpecificStreamInfo. + This field must not be set to paNoDevice. + */ + PaDeviceIndex device; + + /** The number of channels of sound to be delivered to the + stream callback or accessed by Pa_ReadStream() or Pa_WriteStream(). + It can range from 1 to the value of maxInputChannels in the + PaDeviceInfo record for the device specified by the device parameter. + */ + int channelCount; + + /** The sample format of the buffer provided to the stream callback, + a_ReadStream() or Pa_WriteStream(). It may be any of the formats described + by the PaSampleFormat enumeration. + */ + PaSampleFormat sampleFormat; + + /** The desired latency in seconds. Where practical, implementations should + configure their latency based on these parameters, otherwise they may + choose the closest viable latency instead. Unless the suggested latency + is greater than the absolute upper limit for the device implementations + should round the suggestedLatency up to the next practial value - ie to + provide an equal or higher latency than suggestedLatency wherever possibe. + Actual latency values for an open stream may be retrieved using the + inputLatency and outputLatency fields of the PaStreamInfo structure + returned by Pa_GetStreamInfo(). + @see default*Latency in PaDeviceInfo, *Latency in PaStreamInfo + */ + PaTime suggestedLatency; + + /** An optional pointer to a host api specific data structure + containing additional information for device setup and/or stream processing. + hostApiSpecificStreamInfo is never required for correct operation, + if not used it should be set to NULL. + */ + void *hostApiSpecificStreamInfo; + +} PaStreamParameters; + + +/** Return code for Pa_IsFormatSupported indicating success. */ +#define paFormatIsSupported (0) + +/** Determine whether it would be possible to open a stream with the specified + parameters. + + @param inputParameters A structure that describes the input parameters used to + open a stream. The suggestedLatency field is ignored. See PaStreamParameters + for a description of these parameters. inputParameters must be NULL for + output-only streams. + + @param outputParameters A structure that describes the output parameters used + to open a stream. The suggestedLatency field is ignored. See PaStreamParameters + for a description of these parameters. outputParameters must be NULL for + input-only streams. + + @param sampleRate The required sampleRate. For full-duplex streams it is the + sample rate for both input and output + + @return Returns 0 if the format is supported, and an error code indicating why + the format is not supported otherwise. The constant paFormatIsSupported is + provided to compare with the return value for success. + + @see paFormatIsSupported, PaStreamParameters +*/ +PaError Pa_IsFormatSupported( const PaStreamParameters *inputParameters, + const PaStreamParameters *outputParameters, + double sampleRate ); + + + +/* Streaming types and functions */ + + +/** + A single PaStream can provide multiple channels of real-time + streaming audio input and output to a client application. A stream + provides access to audio hardware represented by one or more + PaDevices. Depending on the underlying Host API, it may be possible + to open multiple streams using the same device, however this behavior + is implementation defined. Portable applications should assume that + a PaDevice may be simultaneously used by at most one PaStream. + + Pointers to PaStream objects are passed between PortAudio functions that + operate on streams. + + @see Pa_OpenStream, Pa_OpenDefaultStream, Pa_OpenDefaultStream, Pa_CloseStream, + Pa_StartStream, Pa_StopStream, Pa_AbortStream, Pa_IsStreamActive, + Pa_GetStreamTime, Pa_GetStreamCpuLoad + +*/ +typedef void PaStream; + + +/** Can be passed as the framesPerBuffer parameter to Pa_OpenStream() + or Pa_OpenDefaultStream() to indicate that the stream callback will + accept buffers of any size. +*/ +#define paFramesPerBufferUnspecified (0) + + +/** Flags used to control the behavior of a stream. They are passed as + parameters to Pa_OpenStream or Pa_OpenDefaultStream. Multiple flags may be + ORed together. + + @see Pa_OpenStream, Pa_OpenDefaultStream + @see paNoFlag, paClipOff, paDitherOff, paNeverDropInput, + paPrimeOutputBuffersUsingStreamCallback, paPlatformSpecificFlags +*/ +typedef unsigned long PaStreamFlags; + +/** @see PaStreamFlags */ +#define paNoFlag ((PaStreamFlags) 0) + +/** Disable default clipping of out of range samples. + @see PaStreamFlags +*/ +#define paClipOff ((PaStreamFlags) 0x00000001) + +/** Disable default dithering. + @see PaStreamFlags +*/ +#define paDitherOff ((PaStreamFlags) 0x00000002) + +/** Flag requests that where possible a full duplex stream will not discard + overflowed input samples without calling the stream callback. This flag is + only valid for full duplex callback streams and only when used in combination + with the paFramesPerBufferUnspecified (0) framesPerBuffer parameter. Using + this flag incorrectly results in a paInvalidFlag error being returned from + Pa_OpenStream and Pa_OpenDefaultStream. + + @see PaStreamFlags, paFramesPerBufferUnspecified +*/ +#define paNeverDropInput ((PaStreamFlags) 0x00000004) + +/** Call the stream callback to fill initial output buffers, rather than the + default behavior of priming the buffers with zeros (silence). This flag has + no effect for input-only and blocking read/write streams. + + @see PaStreamFlags +*/ +#define paPrimeOutputBuffersUsingStreamCallback ((PaStreamFlags) 0x00000008) + +/** A mask specifying the platform specific bits. + @see PaStreamFlags +*/ +#define paPlatformSpecificFlags ((PaStreamFlags)0xFFFF0000) + +/** + Timing information for the buffers passed to the stream callback. +*/ +typedef struct PaStreamCallbackTimeInfo{ + PaTime inputBufferAdcTime; + PaTime currentTime; + PaTime outputBufferDacTime; +} PaStreamCallbackTimeInfo; + + +/** + Flag bit constants for the statusFlags to PaStreamCallback. + + @see paInputUnderflow, paInputOverflow, paOutputUnderflow, paOutputOverflow, + paPrimingOutput +*/ +typedef unsigned long PaStreamCallbackFlags; + +/** In a stream opened with paFramesPerBufferUnspecified, indicates that + input data is all silence (zeros) because no real data is available. In a + stream opened without paFramesPerBufferUnspecified, it indicates that one or + more zero samples have been inserted into the input buffer to compensate + for an input underflow. + @see PaStreamCallbackFlags +*/ +#define paInputUnderflow ((PaStreamCallbackFlags) 0x00000001) + +/** In a stream opened with paFramesPerBufferUnspecified, indicates that data + prior to the first sample of the input buffer was discarded due to an + overflow, possibly because the stream callback is using too much CPU time. + Otherwise indicates that data prior to one or more samples in the + input buffer was discarded. + @see PaStreamCallbackFlags +*/ +#define paInputOverflow ((PaStreamCallbackFlags) 0x00000002) + +/** Indicates that output data (or a gap) was inserted, possibly because the + stream callback is using too much CPU time. + @see PaStreamCallbackFlags +*/ +#define paOutputUnderflow ((PaStreamCallbackFlags) 0x00000004) + +/** Indicates that output data will be discarded because no room is available. + @see PaStreamCallbackFlags +*/ +#define paOutputOverflow ((PaStreamCallbackFlags) 0x00000008) + +/** Some of all of the output data will be used to prime the stream, input + data may be zero. + @see PaStreamCallbackFlags +*/ +#define paPrimingOutput ((PaStreamCallbackFlags) 0x00000010) + +/** + Allowable return values for the PaStreamCallback. + @see PaStreamCallback +*/ +typedef enum PaStreamCallbackResult +{ + paContinue=0, + paComplete=1, + paAbort=2 +} PaStreamCallbackResult; + + +/** + Functions of type PaStreamCallback are implemented by PortAudio clients. + They consume, process or generate audio in response to requests from an + active PortAudio stream. + + @param input and @param output are arrays of interleaved samples, + the format, packing and number of channels used by the buffers are + determined by parameters to Pa_OpenStream(). + + @param frameCount The number of sample frames to be processed by + the stream callback. + + @param timeInfo The time in seconds when the first sample of the input + buffer was received at the audio input, the time in seconds when the first + sample of the output buffer will begin being played at the audio output, and + the time in seconds when the stream callback was called. + See also Pa_GetStreamTime() + + @param statusFlags Flags indicating whether input and/or output buffers + have been inserted or will be dropped to overcome underflow or overflow + conditions. + + @param userData The value of a user supplied pointer passed to + Pa_OpenStream() intended for storing synthesis data etc. + + @return + The stream callback should return one of the values in the + PaStreamCallbackResult enumeration. To ensure that the callback continues + to be called, it should return paContinue (0). Either paComplete or paAbort + can be returned to finish stream processing, after either of these values is + returned the callback will not be called again. If paAbort is returned the + stream will finish as soon as possible. If paComplete is returned, the stream + will continue until all buffers generated by the callback have been played. + This may be useful in applications such as soundfile players where a specific + duration of output is required. However, it is not necessary to utilise this + mechanism as Pa_StopStream(), Pa_AbortStream() or Pa_CloseStream() can also + be used to stop the stream. The callback must always fill the entire output + buffer irrespective of its return value. + + @see Pa_OpenStream, Pa_OpenDefaultStream + + @note With the exception of Pa_GetStreamCpuLoad() it is not permissable to call + PortAudio API functions from within the stream callback. +*/ +typedef int PaStreamCallback( + const void *input, void *output, + unsigned long frameCount, + const PaStreamCallbackTimeInfo* timeInfo, + PaStreamCallbackFlags statusFlags, + void *userData ); + + +/** Opens a stream for either input, output or both. + + @param stream The address of a PaStream pointer which will receive + a pointer to the newly opened stream. + + @param inputParameters A structure that describes the input parameters used by + the opened stream. See PaStreamParameters for a description of these parameters. + inputParameters must be NULL for output-only streams. + + @param outputParameters A structure that describes the output parameters used by + the opened stream. See PaStreamParameters for a description of these parameters. + outputParameters must be NULL for input-only streams. + + @param sampleRate The desired sampleRate. For full-duplex streams it is the + sample rate for both input and output + + @param framesPerBuffer The number of frames passed to the stream callback + function, or the preferred block granularity for a blocking read/write stream. + The special value paFramesPerBufferUnspecified (0) may be used to request that + the stream callback will recieve an optimal (and possibly varying) number of + frames based on host requirements and the requested latency settings. + Note: With some host APIs, the use of non-zero framesPerBuffer for a callback + stream may introduce an additional layer of buffering which could introduce + additional latency. PortAudio guarantees that the additional latency + will be kept to the theoretical minimum however, it is strongly recommended + that a non-zero framesPerBuffer value only be used when your algorithm + requires a fixed number of frames per stream callback. + + @param streamFlags Flags which modify the behaviour of the streaming process. + This parameter may contain a combination of flags ORed together. Some flags may + only be relevant to certain buffer formats. + + @param streamCallback A pointer to a client supplied function that is responsible + for processing and filling input and output buffers. If this parameter is NULL + the stream will be opened in 'blocking read/write' mode. In blocking mode, + the client can receive sample data using Pa_ReadStream and write sample data + using Pa_WriteStream, the number of samples that may be read or written + without blocking is returned by Pa_GetStreamReadAvailable and + Pa_GetStreamWriteAvailable respectively. + + @param userData A client supplied pointer which is passed to the stream callback + function. It could for example, contain a pointer to instance data necessary + for processing the audio buffers. This parameter is ignored if streamCallback + is NULL. + + @return + Upon success Pa_OpenStream() returns paNoError and places a pointer to a + valid PaStream in the stream argument. The stream is inactive (stopped). + If a call to Pa_OpenStream() fails, a non-zero error code is returned (see + PaError for possible error codes) and the value of stream is invalid. + + @see PaStreamParameters, PaStreamCallback, Pa_ReadStream, Pa_WriteStream, + Pa_GetStreamReadAvailable, Pa_GetStreamWriteAvailable +*/ +PaError Pa_OpenStream( PaStream** stream, + const PaStreamParameters *inputParameters, + const PaStreamParameters *outputParameters, + double sampleRate, + unsigned long framesPerBuffer, + PaStreamFlags streamFlags, + PaStreamCallback *streamCallback, + void *userData ); + + +/** A simplified version of Pa_OpenStream() that opens the default input + and/or output devices. + + @param stream The address of a PaStream pointer which will receive + a pointer to the newly opened stream. + + @param numInputChannels The number of channels of sound that will be supplied + to the stream callback or returned by Pa_ReadStream. It can range from 1 to + the value of maxInputChannels in the PaDeviceInfo record for the default input + device. If 0 the stream is opened as an output-only stream. + + @param numOutputChannels The number of channels of sound to be delivered to the + stream callback or passed to Pa_WriteStream. It can range from 1 to the value + of maxOutputChannels in the PaDeviceInfo record for the default output dvice. + If 0 the stream is opened as an output-only stream. + + @param sampleFormat The sample format of both the input and output buffers + provided to the callback or passed to and from Pa_ReadStream and Pa_WriteStream. + sampleFormat may be any of the formats described by the PaSampleFormat + enumeration. + + @param sampleRate Same as Pa_OpenStream parameter of the same name. + @param framesPerBuffer Same as Pa_OpenStream parameter of the same name. + @param streamCallback Same as Pa_OpenStream parameter of the same name. + @param userData Same as Pa_OpenStream parameter of the same name. + + @return As for Pa_OpenStream + + @see Pa_OpenStream, PaStreamCallback +*/ +PaError Pa_OpenDefaultStream( PaStream** stream, + int numInputChannels, + int numOutputChannels, + PaSampleFormat sampleFormat, + double sampleRate, + unsigned long framesPerBuffer, + PaStreamCallback *streamCallback, + void *userData ); + + +/** Closes an audio stream. If the audio stream is active it + discards any pending buffers as if Pa_AbortStream() had been called. +*/ +PaError Pa_CloseStream( PaStream *stream ); + + +/** Functions of type PaStreamFinishedCallback are implemented by PortAudio + clients. They can be registered with a stream using the Pa_SetStreamFinishedCallback + function. Once registered they are called when the stream becomes inactive + (ie once a call to Pa_StopStream() will not block). + A stream will become inactive after the stream callback returns non-zero, + or when Pa_StopStream or Pa_AbortStream is called. For a stream providing audio + output, if the stream callback returns paComplete, or Pa_StopStream is called, + the stream finished callback will not be called until all generated sample data + has been played. + + @param userData The userData parameter supplied to Pa_OpenStream() + + @see Pa_SetStreamFinishedCallback +*/ +typedef void PaStreamFinishedCallback( void *userData ); + + +/** Register a stream finished callback function which will be called when the + stream becomes inactive. See the description of PaStreamFinishedCallback for + further details about when the callback will be called. + + @param stream a pointer to a PaStream that is in the stopped state - if the + stream is not stopped, the stream's finished callback will remain unchanged + and an error code will be returned. + + @param streamFinishedCallback a pointer to a function with the same signature + as PaStreamFinishedCallback, that will be called when the stream becomes + inactive. Passing NULL for this parameter will un-register a previously + registered stream finished callback function. + + @return on success returns paNoError, otherwise an error code indicating the cause + of the error. + + @see PaStreamFinishedCallback +*/ +PaError Pa_SetStreamFinishedCallback( PaStream *stream, PaStreamFinishedCallback* streamFinishedCallback ); + + +/** Commences audio processing. +*/ +PaError Pa_StartStream( PaStream *stream ); + + +/** Terminates audio processing. It waits until all pending + audio buffers have been played before it returns. +*/ +PaError Pa_StopStream( PaStream *stream ); + + +/** Terminates audio processing immediately without waiting for pending + buffers to complete. +*/ +PaError Pa_AbortStream( PaStream *stream ); + + +/** Determine whether the stream is stopped. + A stream is considered to be stopped prior to a successful call to + Pa_StartStream and after a successful call to Pa_StopStream or Pa_AbortStream. + If a stream callback returns a value other than paContinue the stream is NOT + considered to be stopped. + + @return Returns one (1) when the stream is stopped, zero (0) when + the stream is running or, a PaErrorCode (which are always negative) if + PortAudio is not initialized or an error is encountered. + + @see Pa_StopStream, Pa_AbortStream, Pa_IsStreamActive +*/ +PaError Pa_IsStreamStopped( PaStream *stream ); + + +/** Determine whether the stream is active. + A stream is active after a successful call to Pa_StartStream(), until it + becomes inactive either as a result of a call to Pa_StopStream() or + Pa_AbortStream(), or as a result of a return value other than paContinue from + the stream callback. In the latter case, the stream is considered inactive + after the last buffer has finished playing. + + @return Returns one (1) when the stream is active (ie playing or recording + audio), zero (0) when not playing or, a PaErrorCode (which are always negative) + if PortAudio is not initialized or an error is encountered. + + @see Pa_StopStream, Pa_AbortStream, Pa_IsStreamStopped +*/ +PaError Pa_IsStreamActive( PaStream *stream ); + + + +/** A structure containing unchanging information about an open stream. + @see Pa_GetStreamInfo +*/ + +typedef struct PaStreamInfo +{ + /** this is struct version 1 */ + int structVersion; + + /** The input latency of the stream in seconds. This value provides the most + accurate estimate of input latency available to the implementation. It may + differ significantly from the suggestedLatency value passed to Pa_OpenStream(). + The value of this field will be zero (0.) for output-only streams. + @see PaTime + */ + PaTime inputLatency; + + /** The output latency of the stream in seconds. This value provides the most + accurate estimate of output latency available to the implementation. It may + differ significantly from the suggestedLatency value passed to Pa_OpenStream(). + The value of this field will be zero (0.) for input-only streams. + @see PaTime + */ + PaTime outputLatency; + + /** The sample rate of the stream in Hertz (samples per second). In cases + where the hardware sample rate is inaccurate and PortAudio is aware of it, + the value of this field may be different from the sampleRate parameter + passed to Pa_OpenStream(). If information about the actual hardware sample + rate is not available, this field will have the same value as the sampleRate + parameter passed to Pa_OpenStream(). + */ + double sampleRate; + +} PaStreamInfo; + + +/** Retrieve a pointer to a PaStreamInfo structure containing information + about the specified stream. + @return A pointer to an immutable PaStreamInfo structure. If the stream + parameter invalid, or an error is encountered, the function returns NULL. + + @param stream A pointer to an open stream previously created with Pa_OpenStream. + + @note PortAudio manages the memory referenced by the returned pointer, + the client must not manipulate or free the memory. The pointer is only + guaranteed to be valid until the specified stream is closed. + + @see PaStreamInfo +*/ +const PaStreamInfo* Pa_GetStreamInfo( PaStream *stream ); + + +/** Determine the current time for the stream according to the same clock used + to generate buffer timestamps. This time may be used for syncronising other + events to the audio stream, for example synchronizing audio to MIDI. + + @return The stream's current time in seconds, or 0 if an error occurred. + + @see PaTime, PaStreamCallback +*/ +PaTime Pa_GetStreamTime( PaStream *stream ); + + +/** Retrieve CPU usage information for the specified stream. + The "CPU Load" is a fraction of total CPU time consumed by a callback stream's + audio processing routines including, but not limited to the client supplied + stream callback. This function does not work with blocking read/write streams. + + This function may be called from the stream callback function or the + application. + + @return + A floating point value, typically between 0.0 and 1.0, where 1.0 indicates + that the stream callback is consuming the maximum number of CPU cycles possible + to maintain real-time operation. A value of 0.5 would imply that PortAudio and + the stream callback was consuming roughly 50% of the available CPU time. The + return value may exceed 1.0. A value of 0.0 will always be returned for a + blocking read/write stream, or if an error occurrs. +*/ +double Pa_GetStreamCpuLoad( PaStream* stream ); + + +/** Read samples from an input stream. The function doesn't return until + the entire buffer has been filled - this may involve waiting for the operating + system to supply the data. + + @param stream A pointer to an open stream previously created with Pa_OpenStream. + + @param buffer A pointer to a buffer of sample frames. The buffer contains + samples in the format specified by the inputParameters->sampleFormat field + used to open the stream, and the number of channels specified by + inputParameters->numChannels. If non-interleaved samples were requested, + buffer is a pointer to the first element of an array of non-interleaved + buffer pointers, one for each channel. + + @param frames The number of frames to be read into buffer. This parameter + is not constrained to a specific range, however high performance applications + will want to match this parameter to the framesPerBuffer parameter used + when opening the stream. + + @return On success PaNoError will be returned, or PaInputOverflowed if input + data was discarded by PortAudio after the previous call and before this call. +*/ +PaError Pa_ReadStream( PaStream* stream, + void *buffer, + unsigned long frames ); + + +/** Write samples to an output stream. This function doesn't return until the + entire buffer has been consumed - this may involve waiting for the operating + system to consume the data. + + @param stream A pointer to an open stream previously created with Pa_OpenStream. + + @param buffer A pointer to a buffer of sample frames. The buffer contains + samples in the format specified by the outputParameters->sampleFormat field + used to open the stream, and the number of channels specified by + outputParameters->numChannels. If non-interleaved samples were requested, + buffer is a pointer to the first element of an array of non-interleaved + buffer pointers, one for each channel. + + @param frames The number of frames to be written from buffer. This parameter + is not constrained to a specific range, however high performance applications + will want to match this parameter to the framesPerBuffer parameter used + when opening the stream. + + @return On success PaNoError will be returned, or paOutputUnderflowed if + additional output data was inserted after the previous call and before this + call. +*/ +PaError Pa_WriteStream( PaStream* stream, + const void *buffer, + unsigned long frames ); + + +/** Retrieve the number of frames that can be read from the stream without + waiting. + + @return Returns a non-negative value representing the maximum number of frames + that can be read from the stream without blocking or busy waiting or, a + PaErrorCode (which are always negative) if PortAudio is not initialized or an + error is encountered. +*/ +signed long Pa_GetStreamReadAvailable( PaStream* stream ); + + +/** Retrieve the number of frames that can be written to the stream without + waiting. + + @return Returns a non-negative value representing the maximum number of frames + that can be written to the stream without blocking or busy waiting or, a + PaErrorCode (which are always negative) if PortAudio is not initialized or an + error is encountered. +*/ +signed long Pa_GetStreamWriteAvailable( PaStream* stream ); + + +/* Miscellaneous utilities */ + + +/** Retrieve the size of a given sample format in bytes. + + @return The size in bytes of a single sample in the specified format, + or paSampleFormatNotSupported if the format is not supported. +*/ +PaError Pa_GetSampleSize( PaSampleFormat format ); + + +/** Put the caller to sleep for at least 'msec' milliseconds. This function is + provided only as a convenience for authors of portable code (such as the tests + and examples in the PortAudio distribution.) + + The function may sleep longer than requested so don't rely on this for accurate + musical timing. +*/ +void Pa_Sleep( long msec ); + + + +#ifdef __cplusplus +} +#endif /* __cplusplus */ +#endif /* PORTAUDIO_H */ From sumomo @ users.sourceforge.jp Sat Feb 5 18:00:03 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Sat, 05 Feb 2011 18:00:03 +0900 Subject: [Julius-cvs 586] CVS update: julius4/libsent/src/adin/pa/hostapi/oss Message-ID: <1296896403.347592.28590.nullmailer@users.sourceforge.jp> Index: julius4/libsent/src/adin/pa/hostapi/oss/pa_unix_oss.c diff -u /dev/null julius4/libsent/src/adin/pa/hostapi/oss/pa_unix_oss.c:1.1 --- /dev/null Sat Feb 5 18:00:03 2011 +++ julius4/libsent/src/adin/pa/hostapi/oss/pa_unix_oss.c Sat Feb 5 18:00:03 2011 @@ -0,0 +1,1957 @@ +#include + +/* + * $Id: pa_unix_oss.c,v 1.1 2011/02/05 09:00:03 sumomo Exp $ + * PortAudio Portable Real-Time Audio Library + * Latest Version at: http://www.portaudio.com + * OSS implementation by: + * Douglas Repetto + * Phil Burk + * Dominic Mazzoni + * Arve Knudsen + * + * Based on the Open Source API proposed by Ross Bencina + * Copyright (c) 1999-2002 Ross Bencina, Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/* + * The text above constitutes the entire PortAudio license; however, + * the PortAudio community also makes the following non-binding requests: + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. It is also + * requested that these non-binding requests be included along with the + * license above. + */ + +/** + @file + @ingroup hostapi_src +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef HAVE_SYS_SOUNDCARD_H +# include +# define DEVICE_NAME_BASE "/dev/dsp" +#elif defined(HAVE_LINUX_SOUNDCARD_H) +# include +# define DEVICE_NAME_BASE "/dev/dsp" +#elif defined(HAVE_MACHINE_SOUNDCARD_H) +# include /* JH20010905 */ +# define DEVICE_NAME_BASE "/dev/audio" +#else +# error No sound card header file +#endif + +#include "portaudio.h" +#include "pa_util.h" +#include "pa_allocation.h" +#include "pa_hostapi.h" +#include "pa_stream.h" +#include "pa_cpuload.h" +#include "pa_process.h" +#include "pa_unix_util.h" +#include "pa_debugprint.h" + +static int sysErr_; +static pthread_t mainThread_; + +/* Check return value of system call, and map it to PaError */ +#define ENSURE_(expr, code) \ + do { \ + if( UNLIKELY( (sysErr_ = (expr)) < 0 ) ) \ + { \ + /* PaUtil_SetLastHostErrorInfo should only be used in the main thread */ \ + if( (code) == paUnanticipatedHostError && pthread_self() == mainThread_ ) \ + { \ + PaUtil_SetLastHostErrorInfo( paALSA, sysErr_, strerror( errno ) ); \ + } \ + \ + PaUtil_DebugPrint(( "Expression '" #expr "' failed in '" __FILE__ "', line: " STRINGIZE( __LINE__ ) "\n" )); \ + result = (code); \ + goto error; \ + } \ + } while( 0 ); + +#ifndef AFMT_S16_NE +#define AFMT_S16_NE Get_AFMT_S16_NE() +/********************************************************************* + * Some versions of OSS do not define AFMT_S16_NE. So check CPU. + * PowerPC is Big Endian. X86 is Little Endian. + */ +static int Get_AFMT_S16_NE( void ) +{ + long testData = 1; + char *ptr = (char *) &testData; + int isLittle = ( *ptr == 1 ); /* Does address point to least significant byte? */ + return isLittle ? AFMT_S16_LE : AFMT_S16_BE; +} +#endif + +/* PaOSSHostApiRepresentation - host api datastructure specific to this implementation */ + +typedef struct +{ + PaUtilHostApiRepresentation inheritedHostApiRep; + PaUtilStreamInterface callbackStreamInterface; + PaUtilStreamInterface blockingStreamInterface; + + PaUtilAllocationGroup *allocations; + + PaHostApiIndex hostApiIndex; +} +PaOSSHostApiRepresentation; + +/** Per-direction structure for PaOssStream. + * + * Aspect StreamChannels: In case the user requests to open the same device for both capture and playback, + * but with different number of channels we will have to adapt between the number of user and host + * channels for at least one direction, since the configuration space is the same for both directions + * of an OSS device. + */ +typedef struct +{ + int fd; + const char *devName; + int userChannelCount, hostChannelCount; + int userInterleaved; + void *buffer; + PaSampleFormat userFormat, hostFormat; + double latency; + unsigned long hostFrames, numBufs; + void **userBuffers; /* For non-interleaved blocking */ +} PaOssStreamComponent; + +/** Implementation specific representation of a PaStream. + * + */ +typedef struct PaOssStream +{ + PaUtilStreamRepresentation streamRepresentation; + PaUtilCpuLoadMeasurer cpuLoadMeasurer; + PaUtilBufferProcessor bufferProcessor; + + PaUtilThreading threading; + + int sharedDevice; + unsigned long framesPerHostBuffer; + int triggered; /* Have the devices been triggered yet (first start) */ + + int isActive; + int isStopped; + + int lastPosPtr; + double lastStreamBytes; + + int framesProcessed; + + double sampleRate; + + int callbackMode; + int callbackStop, callbackAbort; + + PaOssStreamComponent *capture, *playback; + unsigned long pollTimeout; + sem_t semaphore; +} +PaOssStream; + +typedef enum { + StreamMode_In, + StreamMode_Out +} StreamMode; + +/* prototypes for functions declared in this file */ + +static void Terminate( struct PaUtilHostApiRepresentation *hostApi ); +static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi, + const PaStreamParameters *inputParameters, + const PaStreamParameters *outputParameters, + double sampleRate ); +static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi, + PaStream** s, + const PaStreamParameters *inputParameters, + const PaStreamParameters *outputParameters, + double sampleRate, + unsigned long framesPerBuffer, + PaStreamFlags streamFlags, + PaStreamCallback *streamCallback, + void *userData ); +static PaError CloseStream( PaStream* stream ); +static PaError StartStream( PaStream *stream ); +static PaError StopStream( PaStream *stream ); +static PaError AbortStream( PaStream *stream ); +static PaError IsStreamStopped( PaStream *s ); +static PaError IsStreamActive( PaStream *stream ); +static PaTime GetStreamTime( PaStream *stream ); +static double GetStreamCpuLoad( PaStream* stream ); +static PaError ReadStream( PaStream* stream, void *buffer, unsigned long frames ); +static PaError WriteStream( PaStream* stream, const void *buffer, unsigned long frames ); +static signed long GetStreamReadAvailable( PaStream* stream ); +static signed long GetStreamWriteAvailable( PaStream* stream ); +static PaError BuildDeviceList( PaOSSHostApiRepresentation *hostApi ); + + +/** Initialize the OSS API implementation. + * + * This function will initialize host API datastructures and query host devices for information. + * + * Aspect DeviceCapabilities: Enumeration of host API devices is initiated from here + * + * Aspect FreeResources: If an error is encountered under way we have to free each resource allocated in this function, + * this happens with the usual "error" label. + */ +PaError PaOSS_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex ) +{ + PaError result = paNoError; + PaOSSHostApiRepresentation *ossHostApi = NULL; + + PA_UNLESS( ossHostApi = (PaOSSHostApiRepresentation*)PaUtil_AllocateMemory( sizeof(PaOSSHostApiRepresentation) ), + paInsufficientMemory ); + PA_UNLESS( ossHostApi->allocations = PaUtil_CreateAllocationGroup(), paInsufficientMemory ); + ossHostApi->hostApiIndex = hostApiIndex; + + /* Initialize host API structure */ + *hostApi = &ossHostApi->inheritedHostApiRep; + (*hostApi)->info.structVersion = 1; + (*hostApi)->info.type = paOSS; + (*hostApi)->info.name = "OSS"; + (*hostApi)->Terminate = Terminate; + (*hostApi)->OpenStream = OpenStream; + (*hostApi)->IsFormatSupported = IsFormatSupported; + + PA_ENSURE( BuildDeviceList( ossHostApi ) ); + + PaUtil_InitializeStreamInterface( &ossHostApi->callbackStreamInterface, CloseStream, StartStream, + StopStream, AbortStream, IsStreamStopped, IsStreamActive, + GetStreamTime, GetStreamCpuLoad, + PaUtil_DummyRead, PaUtil_DummyWrite, + PaUtil_DummyGetReadAvailable, + PaUtil_DummyGetWriteAvailable ); + + PaUtil_InitializeStreamInterface( &ossHostApi->blockingStreamInterface, CloseStream, StartStream, + StopStream, AbortStream, IsStreamStopped, IsStreamActive, + GetStreamTime, PaUtil_DummyGetCpuLoad, + ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable ); + + mainThread_ = pthread_self(); + + return result; + +error: + if( ossHostApi ) + { + if( ossHostApi->allocations ) + { + PaUtil_FreeAllAllocations( ossHostApi->allocations ); + PaUtil_DestroyAllocationGroup( ossHostApi->allocations ); + } + + PaUtil_FreeMemory( ossHostApi ); + } + return result; +} + +PaError PaUtil_InitializeDeviceInfo( PaDeviceInfo *deviceInfo, const char *name, PaHostApiIndex hostApiIndex, int maxInputChannels, + int maxOutputChannels, PaTime defaultLowInputLatency, PaTime defaultLowOutputLatency, PaTime defaultHighInputLatency, + PaTime defaultHighOutputLatency, double defaultSampleRate, PaUtilAllocationGroup *allocations ) +{ + PaError result = paNoError; + + deviceInfo->structVersion = 2; + if( allocations ) + { + size_t len = strlen( name ) + 1; + PA_UNLESS( deviceInfo->name = PaUtil_GroupAllocateMemory( allocations, len ), paInsufficientMemory ); + strncpy( (char *)deviceInfo->name, name, len ); + } + else + deviceInfo->name = name; + + deviceInfo->hostApi = hostApiIndex; + deviceInfo->maxInputChannels = maxInputChannels; + deviceInfo->maxOutputChannels = maxOutputChannels; + deviceInfo->defaultLowInputLatency = defaultLowInputLatency; + deviceInfo->defaultLowOutputLatency = defaultLowOutputLatency; + deviceInfo->defaultHighInputLatency = defaultHighInputLatency; + deviceInfo->defaultHighOutputLatency = defaultHighOutputLatency; + deviceInfo->defaultSampleRate = defaultSampleRate; + +error: + return result; +} + +static PaError QueryDirection( const char *deviceName, StreamMode mode, double *defaultSampleRate, int *maxChannelCount, + double *defaultLowLatency, double *defaultHighLatency ) +{ + PaError result = paNoError; + int numChannels, maxNumChannels; + int busy = 0; + int devHandle = -1; + int sr; + *maxChannelCount = 0; /* Default value in case this fails */ + + if ( (devHandle = open( deviceName, (mode == StreamMode_In ? O_RDONLY : O_WRONLY) | O_NONBLOCK )) < 0 ) + { + if( errno == EBUSY || errno == EAGAIN ) + { + PA_DEBUG(( "%s: Device %s busy\n", __FUNCTION__, deviceName )); + } + else + { + PA_DEBUG(( "%s: Can't access device: %s\n", __FUNCTION__, strerror( errno ) )); + } + + return paDeviceUnavailable; + } + + /* Negotiate for the maximum number of channels for this device. PLB20010927 + * Consider up to 16 as the upper number of channels. + * Variable maxNumChannels should contain the actual upper limit after the call. + * Thanks to John Lazzaro and Heiko Purnhagen for suggestions. + */ + maxNumChannels = 0; + for( numChannels = 1; numChannels <= 16; numChannels++ ) + { + int temp = numChannels; + if( ioctl( devHandle, SNDCTL_DSP_CHANNELS, &temp ) < 0 ) + { + busy = EAGAIN == errno || EBUSY == errno; + /* ioctl() failed so bail out if we already have stereo */ + if( maxNumChannels >= 2 ) + break; + } + else + { + /* ioctl() worked but bail out if it does not support numChannels. + * We don't want to leave gaps in the numChannels supported. + */ + if( (numChannels > 2) && (temp != numChannels) ) + break; + if( temp > maxNumChannels ) + maxNumChannels = temp; /* Save maximum. */ + } + } + /* A: We're able to open a device for capture if it's busy playing back and vice versa, + * but we can't configure anything */ + if( 0 == maxNumChannels && busy ) + { + result = paDeviceUnavailable; + goto error; + } + + /* The above negotiation may fail for an old driver so try this older technique. */ + if( maxNumChannels < 1 ) + { + int stereo = 1; + if( ioctl( devHandle, SNDCTL_DSP_STEREO, &stereo ) < 0 ) + { + maxNumChannels = 1; + } + else + { + maxNumChannels = (stereo) ? 2 : 1; + } + PA_DEBUG(( "%s: use SNDCTL_DSP_STEREO, maxNumChannels = %d\n", __FUNCTION__, maxNumChannels )); + } + + /* During channel negotiation, the last ioctl() may have failed. This can + * also cause sample rate negotiation to fail. Hence the following, to return + * to a supported number of channels. SG20011005 */ + { + /* use most reasonable default value */ + int temp = PA_MIN( maxNumChannels, 2 ); + ENSURE_( ioctl( devHandle, SNDCTL_DSP_CHANNELS, &temp ), paUnanticipatedHostError ); + } + + /* Get supported sample rate closest to 44100 Hz */ + if( *defaultSampleRate < 0 ) + { + sr = 44100; + if( ioctl( devHandle, SNDCTL_DSP_SPEED, &sr ) < 0 ) + { + result = paUnanticipatedHostError; + goto error; + } + + *defaultSampleRate = sr; + } + + *maxChannelCount = maxNumChannels; + /* TODO */ + *defaultLowLatency = 512. / *defaultSampleRate; + *defaultHighLatency = 2048. / *defaultSampleRate; + +error: + if( devHandle >= 0 ) + close( devHandle ); + + return result; +} + +/** Query OSS device. + * + * This is where PaDeviceInfo objects are constructed and filled in with relevant information. + * + * Aspect DeviceCapabilities: The inferred device capabilities are recorded in a PaDeviceInfo object that is constructed + * in place. + */ +static PaError QueryDevice( char *deviceName, PaOSSHostApiRepresentation *ossApi, PaDeviceInfo **deviceInfo ) +{ + PaError result = paNoError; + double sampleRate = -1.; + int maxInputChannels, maxOutputChannels; + PaTime defaultLowInputLatency, defaultLowOutputLatency, defaultHighInputLatency, defaultHighOutputLatency; + PaError tmpRes = paNoError; + int busy = 0; + *deviceInfo = NULL; + + /* douglas: + we have to do this querying in a slightly different order. apparently + some sound cards will give you different info based on their settins. + e.g. a card might give you stereo at 22kHz but only mono at 44kHz. + the correct order for OSS is: format, channels, sample rate + */ + + /* Aspect StreamChannels: The number of channels supported for a device may depend on the mode it is + * opened in, it may have more channels available for capture than playback and vice versa. Therefore + * we will open the device in both read- and write-only mode to determine the supported number. + */ + if( (tmpRes = QueryDirection( deviceName, StreamMode_In, &sampleRate, &maxInputChannels, &defaultLowInputLatency, + &defaultHighInputLatency )) != paNoError ) + { + if( tmpRes != paDeviceUnavailable ) + { + PA_DEBUG(( "%s: Querying device %s for capture failed!\n", __FUNCTION__, deviceName )); + /* PA_ENSURE( tmpRes ); */ + } + ++busy; + } + if( (tmpRes = QueryDirection( deviceName, StreamMode_Out, &sampleRate, &maxOutputChannels, &defaultLowOutputLatency, + &defaultHighOutputLatency )) != paNoError ) + { + if( tmpRes != paDeviceUnavailable ) + { + PA_DEBUG(( "%s: Querying device %s for playback failed!\n", __FUNCTION__, deviceName )); + /* PA_ENSURE( tmpRes ); */ + } + ++busy; + } + assert( 0 <= busy && busy <= 2 ); + if( 2 == busy ) /* Both directions are unavailable to us */ + { + result = paDeviceUnavailable; + goto error; + } + + PA_UNLESS( *deviceInfo = PaUtil_GroupAllocateMemory( ossApi->allocations, sizeof (PaDeviceInfo) ), paInsufficientMemory ); + PA_ENSURE( PaUtil_InitializeDeviceInfo( *deviceInfo, deviceName, ossApi->hostApiIndex, maxInputChannels, maxOutputChannels, + defaultLowInputLatency, defaultLowOutputLatency, defaultHighInputLatency, defaultHighOutputLatency, sampleRate, + ossApi->allocations ) ); + +error: + return result; +} + +/** Query host devices. + * + * Loop over host devices and query their capabilitiesu + * + * Aspect DeviceCapabilities: This function calls QueryDevice on each device entry and receives a filled in PaDeviceInfo object + * per device, these are placed in the host api representation's deviceInfos array. + */ +static PaError BuildDeviceList( PaOSSHostApiRepresentation *ossApi ) +{ + PaError result = paNoError; + PaUtilHostApiRepresentation *commonApi = &ossApi->inheritedHostApiRep; + int i; + int numDevices = 0, maxDeviceInfos = 1; + PaDeviceInfo **deviceInfos = NULL; + + /* These two will be set to the first working input and output device, respectively */ + commonApi->info.defaultInputDevice = paNoDevice; + commonApi->info.defaultOutputDevice = paNoDevice; + + /* Find devices by calling QueryDevice on each + * potential device names. When we find a valid one, + * add it to a linked list. + * A: Set an arbitrary of 100 devices, should probably be a smarter way. */ + + for( i = 0; i < 100; i++ ) + { + char deviceName[32]; + PaDeviceInfo *deviceInfo; + int testResult; + struct stat stbuf; + + if( i == 0 ) + snprintf(deviceName, sizeof (deviceName), "%s", DEVICE_NAME_BASE); + else + snprintf(deviceName, sizeof (deviceName), "%s%d", DEVICE_NAME_BASE, i); + + /* PA_DEBUG(("PaOSS BuildDeviceList: trying device %s\n", deviceName )); */ + if( stat( deviceName, &stbuf ) < 0 ) + { + if( ENOENT != errno ) + PA_DEBUG(( "%s: Error stat'ing %s: %s\n", __FUNCTION__, deviceName, strerror( errno ) )); + continue; + } + if( (testResult = QueryDevice( deviceName, ossApi, &deviceInfo )) != paNoError ) + { + if( testResult != paDeviceUnavailable ) + PA_ENSURE( testResult ); + + continue; + } + + ++numDevices; + if( !deviceInfos || numDevices > maxDeviceInfos ) + { + maxDeviceInfos *= 2; + PA_UNLESS( deviceInfos = (PaDeviceInfo **) realloc( deviceInfos, maxDeviceInfos * sizeof (PaDeviceInfo *) ), + paInsufficientMemory ); + } + { + int devIdx = numDevices - 1; + deviceInfos[devIdx] = deviceInfo; + + if( commonApi->info.defaultInputDevice == paNoDevice && deviceInfo->maxInputChannels > 0 ) + commonApi->info.defaultInputDevice = devIdx; + if( commonApi->info.defaultOutputDevice == paNoDevice && deviceInfo->maxOutputChannels > 0 ) + commonApi->info.defaultOutputDevice = devIdx; + } + } + + /* Make an array of PaDeviceInfo pointers out of the linked list */ + + PA_DEBUG(("PaOSS %s: Total number of devices found: %d\n", __FUNCTION__, numDevices)); + + commonApi->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory( + ossApi->allocations, sizeof(PaDeviceInfo*) * numDevices ); + memcpy( commonApi->deviceInfos, deviceInfos, numDevices * sizeof (PaDeviceInfo *) ); + + commonApi->info.deviceCount = numDevices; + +error: + free( deviceInfos ); + + return result; +} + +static void Terminate( struct PaUtilHostApiRepresentation *hostApi ) +{ + PaOSSHostApiRepresentation *ossHostApi = (PaOSSHostApiRepresentation*)hostApi; + + if( ossHostApi->allocations ) + { + PaUtil_FreeAllAllocations( ossHostApi->allocations ); + PaUtil_DestroyAllocationGroup( ossHostApi->allocations ); + } + + PaUtil_FreeMemory( ossHostApi ); +} + +static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi, + const PaStreamParameters *inputParameters, + const PaStreamParameters *outputParameters, + double sampleRate ) +{ + PaError result = paNoError; + PaDeviceIndex device; + PaDeviceInfo *deviceInfo; + char *deviceName; + int inputChannelCount, outputChannelCount; + int tempDevHandle = -1; + int flags; + PaSampleFormat inputSampleFormat, outputSampleFormat; + + if( inputParameters ) + { + inputChannelCount = inputParameters->channelCount; + inputSampleFormat = inputParameters->sampleFormat; + + /* unless alternate device specification is supported, reject the use of + paUseHostApiSpecificDeviceSpecification */ + + if( inputParameters->device == paUseHostApiSpecificDeviceSpecification ) + return paInvalidDevice; + + /* check that input device can support inputChannelCount */ + if( inputChannelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels ) + return paInvalidChannelCount; + + /* validate inputStreamInfo */ + if( inputParameters->hostApiSpecificStreamInfo ) + return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */ + } + else + { + inputChannelCount = 0; + } + + if( outputParameters ) + { + outputChannelCount = outputParameters->channelCount; + outputSampleFormat = outputParameters->sampleFormat; + + /* unless alternate device specification is supported, reject the use of + paUseHostApiSpecificDeviceSpecification */ + + if( outputParameters->device == paUseHostApiSpecificDeviceSpecification ) + return paInvalidDevice; + + /* check that output device can support inputChannelCount */ + if( outputChannelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels ) + return paInvalidChannelCount; + + /* validate outputStreamInfo */ + if( outputParameters->hostApiSpecificStreamInfo ) + return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */ + } + else + { + outputChannelCount = 0; + } + + if (inputChannelCount == 0 && outputChannelCount == 0) + return paInvalidChannelCount; + + /* if full duplex, make sure that they're the same device */ + + if (inputChannelCount > 0 && outputChannelCount > 0 && + inputParameters->device != outputParameters->device) + return paInvalidDevice; + + /* if full duplex, also make sure that they're the same number of channels */ + + if (inputChannelCount > 0 && outputChannelCount > 0 && + inputChannelCount != outputChannelCount) + return paInvalidChannelCount; + + /* open the device so we can do more tests */ + + if( inputChannelCount > 0 ) + { + result = PaUtil_DeviceIndexToHostApiDeviceIndex(&device, inputParameters->device, hostApi); + if (result != paNoError) + return result; + } + else + { + result = PaUtil_DeviceIndexToHostApiDeviceIndex(&device, outputParameters->device, hostApi); + if (result != paNoError) + return result; + } + + deviceInfo = hostApi->deviceInfos[device]; + deviceName = (char *)deviceInfo->name; + + flags = O_NONBLOCK; + if (inputChannelCount > 0 && outputChannelCount > 0) + flags |= O_RDWR; + else if (inputChannelCount > 0) + flags |= O_RDONLY; + else + flags |= O_WRONLY; + + ENSURE_( tempDevHandle = open( deviceInfo->name, flags ), paDeviceUnavailable ); + + /* PaOssStream_Configure will do the rest of the checking for us */ + /* PA_ENSURE( PaOssStream_Configure( tempDevHandle, deviceName, outputChannelCount, &sampleRate ) ); */ + + /* everything succeeded! */ + + error: + if( tempDevHandle >= 0 ) + close( tempDevHandle ); + + return result; +} + +/** Validate stream parameters. + * + * Aspect StreamChannels: We verify that the number of channels is within the allowed range for the device + */ +static PaError ValidateParameters( const PaStreamParameters *parameters, const PaDeviceInfo *deviceInfo, StreamMode mode ) +{ + int maxChans; + + assert( parameters ); + + if( parameters->device == paUseHostApiSpecificDeviceSpecification ) + { + return paInvalidDevice; + } + + maxChans = (mode == StreamMode_In ? deviceInfo->maxInputChannels : + deviceInfo->maxOutputChannels); + if( parameters->channelCount > maxChans ) + { + return paInvalidChannelCount; + } + + return paNoError; +} + +static PaError PaOssStreamComponent_Initialize( PaOssStreamComponent *component, const PaStreamParameters *parameters, + int callbackMode, int fd, const char *deviceName ) +{ + PaError result = paNoError; + assert( component ); + + memset( component, 0, sizeof (PaOssStreamComponent) ); + + component->fd = fd; + component->devName = deviceName; + component->userChannelCount = parameters->channelCount; + component->userFormat = parameters->sampleFormat; + component->latency = parameters->suggestedLatency; + component->userInterleaved = !(parameters->sampleFormat & paNonInterleaved); + + if( !callbackMode && !component->userInterleaved ) + { + /* Pre-allocate non-interleaved user provided buffers */ + PA_UNLESS( component->userBuffers = PaUtil_AllocateMemory( sizeof (void *) * component->userChannelCount ), + paInsufficientMemory ); + } + +error: + return result; +} + +static void PaOssStreamComponent_Terminate( PaOssStreamComponent *component ) +{ + assert( component ); + + if( component->fd >= 0 ) + close( component->fd ); + if( component->buffer ) + PaUtil_FreeMemory( component->buffer ); + + if( component->userBuffers ) + PaUtil_FreeMemory( component->userBuffers ); + + PaUtil_FreeMemory( component ); +} + +static PaError ModifyBlocking( int fd, int blocking ) +{ + PaError result = paNoError; + int fflags; + + ENSURE_( fflags = fcntl( fd, F_GETFL ), paUnanticipatedHostError ); + + if( blocking ) + fflags &= ~O_NONBLOCK; + else + fflags |= O_NONBLOCK; + + ENSURE_( fcntl( fd, F_SETFL, fflags ), paUnanticipatedHostError ); + +error: + return result; +} + +static PaError OpenDevices( const char *idevName, const char *odevName, int *idev, int *odev ) +{ + PaError result = paNoError; + int flags = O_NONBLOCK, duplex = 0; + int enableBits = 0; + *idev = *odev = -1; + + if( idevName && odevName ) + { + duplex = 1; + flags |= O_RDWR; + } + else if( idevName ) + flags |= O_RDONLY; + else + flags |= O_WRONLY; + + /* open first in nonblocking mode, in case it's busy... + * A: then unset the non-blocking attribute */ + assert( flags & O_NONBLOCK ); + if( idevName ) + { + ENSURE_( *idev = open( idevName, flags ), paDeviceUnavailable ); + PA_ENSURE( ModifyBlocking( *idev, 1 ) ); /* Blocking */ + + /* Initially disable */ + enableBits = ~PCM_ENABLE_INPUT; + ENSURE_( ioctl( *idev, SNDCTL_DSP_SETTRIGGER, &enableBits ), paUnanticipatedHostError ); + } + if( odevName ) + { + if( !idevName ) + { + ENSURE_( *odev = open( odevName, flags ), paDeviceUnavailable ); + PA_ENSURE( ModifyBlocking( *odev, 1 ) ); /* Blocking */ + + /* Initially disable */ + enableBits = ~PCM_ENABLE_OUTPUT; + ENSURE_( ioctl( *odev, SNDCTL_DSP_SETTRIGGER, &enableBits ), paUnanticipatedHostError ); + } + else + { + ENSURE_( *odev = dup( *idev ), paUnanticipatedHostError ); + } + } + +error: + return result; +} + +static PaError PaOssStream_Initialize( PaOssStream *stream, const PaStreamParameters *inputParameters, const PaStreamParameters *outputParameters, + PaStreamCallback callback, void *userData, PaStreamFlags streamFlags, + PaOSSHostApiRepresentation *ossApi ) +{ + PaError result = paNoError; + int idev, odev; + PaUtilHostApiRepresentation *hostApi = &ossApi->inheritedHostApiRep; + const char *idevName = NULL, *odevName = NULL; + + assert( stream ); + + memset( stream, 0, sizeof (PaOssStream) ); + stream->isStopped = 1; + + PA_ENSURE( PaUtil_InitializeThreading( &stream->threading ) ); + + if( inputParameters && outputParameters ) + { + if( inputParameters->device == outputParameters->device ) + stream->sharedDevice = 1; + } + + if( inputParameters ) + idevName = hostApi->deviceInfos[inputParameters->device]->name; + if( outputParameters ) + odevName = hostApi->deviceInfos[outputParameters->device]->name; + PA_ENSURE( OpenDevices( idevName, odevName, &idev, &odev ) ); + if( inputParameters ) + { + PA_UNLESS( stream->capture = PaUtil_AllocateMemory( sizeof (PaOssStreamComponent) ), paInsufficientMemory ); + PA_ENSURE( PaOssStreamComponent_Initialize( stream->capture, inputParameters, callback != NULL, idev, idevName ) ); + } + if( outputParameters ) + { + PA_UNLESS( stream->playback = PaUtil_AllocateMemory( sizeof (PaOssStreamComponent) ), paInsufficientMemory ); + PA_ENSURE( PaOssStreamComponent_Initialize( stream->playback, outputParameters, callback != NULL, odev, odevName ) ); + } + + if( callback != NULL ) + { + PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation, + &ossApi->callbackStreamInterface, callback, userData ); + stream->callbackMode = 1; + } + else + { + PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation, + &ossApi->blockingStreamInterface, callback, userData ); + } + + ENSURE_( sem_init( &stream->semaphore, 0, 0 ), paInternalError ); + +error: + return result; +} + +static void PaOssStream_Terminate( PaOssStream *stream ) +{ + assert( stream ); + + PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation ); + PaUtil_TerminateThreading( &stream->threading ); + + if( stream->capture ) + PaOssStreamComponent_Terminate( stream->capture ); + if( stream->playback ) + PaOssStreamComponent_Terminate( stream->playback ); + + sem_destroy( &stream->semaphore ); + + PaUtil_FreeMemory( stream ); +} + +/** Translate from PA format to OSS native. + * + */ +static PaError Pa2OssFormat( PaSampleFormat paFormat, int *ossFormat ) +{ + switch( paFormat ) + { + case paUInt8: + *ossFormat = AFMT_U8; + break; + case paInt8: + *ossFormat = AFMT_S8; + break; + case paInt16: + *ossFormat = AFMT_S16_NE; + break; + default: + return paInternalError; /* This shouldn't happen */ + } + + return paNoError; +} + +/** Return the PA-compatible formats that this device can support. + * + */ +static PaError GetAvailableFormats( PaOssStreamComponent *component, PaSampleFormat *availableFormats ) +{ + PaError result = paNoError; + int mask = 0; + PaSampleFormat frmts = 0; + + ENSURE_( ioctl( component->fd, SNDCTL_DSP_GETFMTS, &mask ), paUnanticipatedHostError ); + if( mask & AFMT_U8 ) + frmts |= paUInt8; + if( mask & AFMT_S8 ) + frmts |= paInt8; + if( mask & AFMT_S16_NE ) + frmts |= paInt16; + else + result = paSampleFormatNotSupported; + + *availableFormats = frmts; + +error: + return result; +} + +static unsigned int PaOssStreamComponent_FrameSize( PaOssStreamComponent *component ) +{ + return Pa_GetSampleSize( component->hostFormat ) * component->hostChannelCount; +} + +/** Buffer size in bytes. + * + */ +static unsigned long PaOssStreamComponent_BufferSize( PaOssStreamComponent *component ) +{ + return PaOssStreamComponent_FrameSize( component ) * component->hostFrames * component->numBufs; +} + +static int CalcHigherLogTwo( int n ) +{ + int log2 = 0; + while( (1<userChannelCount; + int frgmt; + int numBufs; + int bytesPerBuf; + unsigned long bufSz; + unsigned long fragSz; + audio_buf_info bufInfo; + + /* We may have a situation where only one component (the master) is configured, if both point to the same device. + * In that case, the second component will copy settings from the other */ + if( !master ) + { + /* Aspect BufferSettings: If framesPerBuffer is unspecified we have to infer a suitable fragment size. + * The hardware need not respect the requested fragment size, so we may have to adapt. + */ + if( framesPerBuffer == paFramesPerBufferUnspecified ) + { + bufSz = (unsigned long)(component->latency * sampleRate); + fragSz = bufSz / 4; + } + else + { + fragSz = framesPerBuffer; + bufSz = (unsigned long)(component->latency * sampleRate) + fragSz; /* Latency + 1 buffer */ + } + + PA_ENSURE( GetAvailableFormats( component, &availableFormats ) ); + hostFormat = PaUtil_SelectClosestAvailableFormat( availableFormats, component->userFormat ); + + /* OSS demands at least 2 buffers, and 16 bytes per buffer */ + numBufs = (int)PA_MAX( bufSz / fragSz, 2 ); + bytesPerBuf = PA_MAX( fragSz * Pa_GetSampleSize( hostFormat ) * chans, 16 ); + + /* The fragment parameters are encoded like this: + * Most significant byte: number of fragments + * Least significant byte: exponent of fragment size (i.e., for 256, 8) + */ + frgmt = (numBufs << 16) + (CalcHigherLogTwo( bytesPerBuf ) & 0xffff); + ENSURE_( ioctl( component->fd, SNDCTL_DSP_SETFRAGMENT, &frgmt ), paUnanticipatedHostError ); + + /* A: according to the OSS programmer's guide parameters should be set in this order: + * format, channels, rate */ + + /* This format should be deemed good before we get this far */ + PA_ENSURE( Pa2OssFormat( hostFormat, &temp ) ); + nativeFormat = temp; + ENSURE_( ioctl( component->fd, SNDCTL_DSP_SETFMT, &temp ), paUnanticipatedHostError ); + PA_UNLESS( temp == nativeFormat, paInternalError ); + + /* try to set the number of channels */ + ENSURE_( ioctl( component->fd, SNDCTL_DSP_CHANNELS, &chans ), paSampleFormatNotSupported ); /* XXX: Should be paInvalidChannelCount? */ + /* It's possible that the minimum number of host channels is greater than what the user requested */ + PA_UNLESS( chans >= component->userChannelCount, paInvalidChannelCount ); + + /* try to set the sample rate */ + ENSURE_( ioctl( component->fd, SNDCTL_DSP_SPEED, &sr ), paInvalidSampleRate ); + + /* reject if there's no sample rate within 1% of the one requested */ + if( (fabs( sampleRate - sr ) / sampleRate) > 0.01 ) + { + PA_DEBUG(("%s: Wanted %f, closest sample rate was %d\n", __FUNCTION__, sampleRate, sr )); + PA_ENSURE( paInvalidSampleRate ); + } + + ENSURE_( ioctl( component->fd, streamMode == StreamMode_In ? SNDCTL_DSP_GETISPACE : SNDCTL_DSP_GETOSPACE, &bufInfo ), + paUnanticipatedHostError ); + component->numBufs = bufInfo.fragstotal; + + /* This needs to be the last ioctl call before the first read/write, according to the OSS programmer's guide */ + ENSURE_( ioctl( component->fd, SNDCTL_DSP_GETBLKSIZE, &bytesPerBuf ), paUnanticipatedHostError ); + + component->hostFrames = bytesPerBuf / Pa_GetSampleSize( hostFormat ) / chans; + component->hostChannelCount = chans; + component->hostFormat = hostFormat; + } + else + { + component->hostFormat = master->hostFormat; + component->hostFrames = master->hostFrames; + component->hostChannelCount = master->hostChannelCount; + component->numBufs = master->numBufs; + } + + PA_UNLESS( component->buffer = PaUtil_AllocateMemory( PaOssStreamComponent_BufferSize( component ) ), + paInsufficientMemory ); + +error: + return result; +} + +static PaError PaOssStreamComponent_Read( PaOssStreamComponent *component, unsigned long *frames ) +{ + PaError result = paNoError; + size_t len = *frames * PaOssStreamComponent_FrameSize( component ); + ssize_t bytesRead; + + ENSURE_( bytesRead = read( component->fd, component->buffer, len ), paUnanticipatedHostError ); + *frames = bytesRead / PaOssStreamComponent_FrameSize( component ); + /* TODO: Handle condition where number of frames read doesn't equal number of frames requested */ + +error: + return result; +} + +static PaError PaOssStreamComponent_Write( PaOssStreamComponent *component, unsigned long *frames ) +{ + PaError result = paNoError; + size_t len = *frames * PaOssStreamComponent_FrameSize( component ); + ssize_t bytesWritten; + + ENSURE_( bytesWritten = write( component->fd, component->buffer, len ), paUnanticipatedHostError ); + *frames = bytesWritten / PaOssStreamComponent_FrameSize( component ); + /* TODO: Handle condition where number of frames written doesn't equal number of frames requested */ + +error: + return result; +} + +/** Configure the stream according to input/output parameters. + * + * Aspect StreamChannels: The minimum number of channels supported by the device may exceed that requested by + * the user, if so we'll record the actual number of host channels and adapt later. + */ +static PaError PaOssStream_Configure( PaOssStream *stream, double sampleRate, unsigned long framesPerBuffer, + double *inputLatency, double *outputLatency ) +{ + PaError result = paNoError; + int duplex = stream->capture && stream->playback; + unsigned long framesPerHostBuffer = 0; + + /* We should request full duplex first thing after opening the device */ + if( duplex && stream->sharedDevice ) + ENSURE_( ioctl( stream->capture->fd, SNDCTL_DSP_SETDUPLEX, 0 ), paUnanticipatedHostError ); + + if( stream->capture ) + { + PaOssStreamComponent *component = stream->capture; + PA_ENSURE( PaOssStreamComponent_Configure( component, sampleRate, framesPerBuffer, StreamMode_In, + NULL ) ); + + assert( component->hostChannelCount > 0 ); + assert( component->hostFrames > 0 ); + + *inputLatency = component->hostFrames * (component->numBufs - 1) / sampleRate; + } + if( stream->playback ) + { + PaOssStreamComponent *component = stream->playback, *master = stream->sharedDevice ? stream->capture : NULL; + PA_ENSURE( PaOssStreamComponent_Configure( component, sampleRate, framesPerBuffer, StreamMode_Out, + master ) ); + + assert( component->hostChannelCount > 0 ); + assert( component->hostFrames > 0 ); + + *outputLatency = component->hostFrames * (component->numBufs - 1) / sampleRate; + } + + if( duplex ) + framesPerHostBuffer = PA_MIN( stream->capture->hostFrames, stream->playback->hostFrames ); + else if( stream->capture ) + framesPerHostBuffer = stream->capture->hostFrames; + else if( stream->playback ) + framesPerHostBuffer = stream->playback->hostFrames; + + stream->framesPerHostBuffer = framesPerHostBuffer; + stream->pollTimeout = (int) ceil( 1e6 * framesPerHostBuffer / sampleRate ); /* Period in usecs, rounded up */ + + stream->sampleRate = stream->streamRepresentation.streamInfo.sampleRate = sampleRate; + +error: + return result; +} + +/* see pa_hostapi.h for a list of validity guarantees made about OpenStream parameters */ + +/** Open a PA OSS stream. + * + * Aspect StreamChannels: The number of channels is specified per direction (in/out), and can differ between the + * two. However, OSS doesn't support separate configuration spaces for capture and playback so if both + * directions are the same device we will demand the same number of channels. The number of channels can range + * from 1 to the maximum supported by the device. + * + * Aspect BufferSettings: If framesPerBuffer != paFramesPerBufferUnspecified the number of frames per callback + * must reflect this, in addition the host latency per device should approximate the corresponding + * suggestedLatency. Based on these constraints we need to determine a number of frames per host buffer that + * both capture and playback can agree on (they can be different devices), the buffer processor can adapt + * between host and user buffer size, but the ratio should preferably be integral. + */ +static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi, + PaStream** s, + const PaStreamParameters *inputParameters, + const PaStreamParameters *outputParameters, + double sampleRate, + unsigned long framesPerBuffer, + PaStreamFlags streamFlags, + PaStreamCallback *streamCallback, + void *userData ) +{ + PaError result = paNoError; + PaOSSHostApiRepresentation *ossHostApi = (PaOSSHostApiRepresentation*)hostApi; + PaOssStream *stream = NULL; + int inputChannelCount = 0, outputChannelCount = 0; + PaSampleFormat inputSampleFormat = 0, outputSampleFormat = 0, inputHostFormat = 0, outputHostFormat = 0; + const PaDeviceInfo *inputDeviceInfo = 0, *outputDeviceInfo = 0; + int bpInitialized = 0; + double inLatency = 0., outLatency = 0.; + int i = 0; + + /* validate platform specific flags */ + if( (streamFlags & paPlatformSpecificFlags) != 0 ) + return paInvalidFlag; /* unexpected platform specific flag */ + + if( inputParameters ) + { + /* unless alternate device specification is supported, reject the use of + paUseHostApiSpecificDeviceSpecification */ + inputDeviceInfo = hostApi->deviceInfos[inputParameters->device]; + PA_ENSURE( ValidateParameters( inputParameters, inputDeviceInfo, StreamMode_In ) ); + + inputChannelCount = inputParameters->channelCount; + inputSampleFormat = inputParameters->sampleFormat; + } + if( outputParameters ) + { + outputDeviceInfo = hostApi->deviceInfos[outputParameters->device]; + PA_ENSURE( ValidateParameters( outputParameters, outputDeviceInfo, StreamMode_Out ) ); + + outputChannelCount = outputParameters->channelCount; + outputSampleFormat = outputParameters->sampleFormat; + } + + /* Aspect StreamChannels: We currently demand that number of input and output channels are the same, if the same + * device is opened for both directions + */ + if( inputChannelCount > 0 && outputChannelCount > 0 ) + { + if( inputParameters->device == outputParameters->device ) + { + if( inputParameters->channelCount != outputParameters->channelCount ) + return paInvalidChannelCount; + } + } + + /* Round framesPerBuffer to the next power-of-two to make OSS happy. */ + if( framesPerBuffer != paFramesPerBufferUnspecified ) + { + framesPerBuffer &= INT_MAX; + for (i = 1; framesPerBuffer > i; i <<= 1) ; + framesPerBuffer = i; + } + + /* allocate and do basic initialization of the stream structure */ + PA_UNLESS( stream = (PaOssStream*)PaUtil_AllocateMemory( sizeof(PaOssStream) ), paInsufficientMemory ); + PA_ENSURE( PaOssStream_Initialize( stream, inputParameters, outputParameters, streamCallback, userData, streamFlags, ossHostApi ) ); + + PA_ENSURE( PaOssStream_Configure( stream, sampleRate, framesPerBuffer, &inLatency, &outLatency ) ); + + PaUtil_InitializeCpuLoadMeasurer( &stream->cpuLoadMeasurer, sampleRate ); + + if( inputParameters ) + { + inputHostFormat = stream->capture->hostFormat; + stream->streamRepresentation.streamInfo.inputLatency = inLatency + + PaUtil_GetBufferProcessorInputLatency( &stream->bufferProcessor ) / sampleRate; + } + if( outputParameters ) + { + outputHostFormat = stream->playback->hostFormat; + stream->streamRepresentation.streamInfo.outputLatency = outLatency + + PaUtil_GetBufferProcessorOutputLatency( &stream->bufferProcessor ) / sampleRate; + } + + /* Initialize buffer processor with fixed host buffer size. + * Aspect StreamSampleFormat: Here we commit the user and host sample formats, PA infrastructure will + * convert between the two. + */ + PA_ENSURE( PaUtil_InitializeBufferProcessor( &stream->bufferProcessor, + inputChannelCount, inputSampleFormat, inputHostFormat, outputChannelCount, outputSampleFormat, + outputHostFormat, sampleRate, streamFlags, framesPerBuffer, stream->framesPerHostBuffer, + paUtilFixedHostBufferSize, streamCallback, userData ) ); + bpInitialized = 1; + + *s = (PaStream*)stream; + + return result; + +error: + if( bpInitialized ) + PaUtil_TerminateBufferProcessor( &stream->bufferProcessor ); + if( stream ) + PaOssStream_Terminate( stream ); + + return result; +} + +/*! Poll on I/O filedescriptors. + + Poll till we've determined there's data for read or write. In the full-duplex case, + we don't want to hang around forever waiting for either input or output frames, so + whenever we have a timed out filedescriptor we check if we're nearing under/overrun + for the other direction (critical limit set at one buffer). If so, we exit the waiting + state, and go on with what we got. We align the number of frames on a host buffer + boundary because it is possible that the buffer size differs for the two directions and + the host buffer size is a compromise between the two. + */ +static PaError PaOssStream_WaitForFrames( PaOssStream *stream, unsigned long *frames ) +{ + PaError result = paNoError; + int pollPlayback = 0, pollCapture = 0; + int captureAvail = INT_MAX, playbackAvail = INT_MAX, commonAvail; + audio_buf_info bufInfo; + /* int ofs = 0, nfds = stream->nfds; */ + fd_set readFds, writeFds; + int nfds = 0; + struct timeval selectTimeval = {0, 0}; + unsigned long timeout = stream->pollTimeout; /* In usecs */ + int captureFd = -1, playbackFd = -1; + + assert( stream ); + assert( frames ); + + if( stream->capture ) + { + pollCapture = 1; + captureFd = stream->capture->fd; + /* stream->capture->pfd->events = POLLIN; */ + } + if( stream->playback ) + { + pollPlayback = 1; + playbackFd = stream->playback->fd; + /* stream->playback->pfd->events = POLLOUT; */ + } + + FD_ZERO( &readFds ); + FD_ZERO( &writeFds ); + + while( pollPlayback || pollCapture ) + { + pthread_testcancel(); + + /* select may modify the timeout parameter */ + selectTimeval.tv_usec = timeout; + nfds = 0; + + if( pollCapture ) + { + FD_SET( captureFd, &readFds ); + nfds = captureFd + 1; + } + if( pollPlayback ) + { + FD_SET( playbackFd, &writeFds ); + nfds = PA_MAX( nfds, playbackFd + 1 ); + } + ENSURE_( select( nfds, &readFds, &writeFds, NULL, &selectTimeval ), paUnanticipatedHostError ); + /* + if( poll( stream->pfds + ofs, nfds, stream->pollTimeout ) < 0 ) + { + + ENSURE_( -1, paUnanticipatedHostError ); + } + */ + pthread_testcancel(); + + if( pollCapture ) + { + if( FD_ISSET( captureFd, &readFds ) ) + { + FD_CLR( captureFd, &readFds ); + pollCapture = 0; + } + /* + if( stream->capture->pfd->revents & POLLIN ) + { + --nfds; + ++ofs; + pollCapture = 0; + } + */ + else if( stream->playback ) /* Timed out, go on with playback? */ + { + /*PA_DEBUG(( "%s: Trying to poll again for capture frames, pollTimeout: %d\n", + __FUNCTION__, stream->pollTimeout ));*/ + } + } + if( pollPlayback ) + { + if( FD_ISSET( playbackFd, &writeFds ) ) + { + FD_CLR( playbackFd, &writeFds ); + pollPlayback = 0; + } + /* + if( stream->playback->pfd->revents & POLLOUT ) + { + --nfds; + pollPlayback = 0; + } + */ + else if( stream->capture ) /* Timed out, go on with capture? */ + { + /*PA_DEBUG(( "%s: Trying to poll again for playback frames, pollTimeout: %d\n\n", + __FUNCTION__, stream->pollTimeout ));*/ + } + } + } + + if( stream->capture ) + { + ENSURE_( ioctl( captureFd, SNDCTL_DSP_GETISPACE, &bufInfo ), paUnanticipatedHostError ); + captureAvail = bufInfo.fragments * stream->capture->hostFrames; + if( !captureAvail ) + PA_DEBUG(( "%s: captureAvail: 0\n", __FUNCTION__ )); + + captureAvail = captureAvail == 0 ? INT_MAX : captureAvail; /* Disregard if zero */ + } + if( stream->playback ) + { + ENSURE_( ioctl( playbackFd, SNDCTL_DSP_GETOSPACE, &bufInfo ), paUnanticipatedHostError ); + playbackAvail = bufInfo.fragments * stream->playback->hostFrames; + if( !playbackAvail ) + { + PA_DEBUG(( "%s: playbackAvail: 0\n", __FUNCTION__ )); + } + + playbackAvail = playbackAvail == 0 ? INT_MAX : playbackAvail; /* Disregard if zero */ + } + + commonAvail = PA_MIN( captureAvail, playbackAvail ); + if( commonAvail == INT_MAX ) + commonAvail = 0; + commonAvail -= commonAvail % stream->framesPerHostBuffer; + + assert( commonAvail != INT_MAX ); + assert( commonAvail >= 0 ); + *frames = commonAvail; + +error: + return result; +} + +/** Prepare stream for capture/playback. + * + * In order to synchronize capture and playback properly we use the SETTRIGGER command. + */ +static PaError PaOssStream_Prepare( PaOssStream *stream ) +{ + PaError result = paNoError; + int enableBits = 0; + + if( stream->triggered ) + return result; + + if( stream->playback ) + { + size_t bufSz = PaOssStreamComponent_BufferSize( stream->playback ); + memset( stream->playback->buffer, 0, bufSz ); + + /* Looks like we have to turn off blocking before we try this, but if we don't fill the buffer + * OSS will complain. */ + PA_ENSURE( ModifyBlocking( stream->playback->fd, 0 ) ); + while (1) + { + if( write( stream->playback->fd, stream->playback->buffer, bufSz ) < 0 ) + break; + } + PA_ENSURE( ModifyBlocking( stream->playback->fd, 1 ) ); + } + + if( stream->sharedDevice ) + { + enableBits = PCM_ENABLE_INPUT | PCM_ENABLE_OUTPUT; + ENSURE_( ioctl( stream->capture->fd, SNDCTL_DSP_SETTRIGGER, &enableBits ), paUnanticipatedHostError ); + } + else + { + if( stream->capture ) + { + enableBits = PCM_ENABLE_INPUT; + ENSURE_( ioctl( stream->capture->fd, SNDCTL_DSP_SETTRIGGER, &enableBits ), paUnanticipatedHostError ); + } + if( stream->playback ) + { + enableBits = PCM_ENABLE_OUTPUT; + ENSURE_( ioctl( stream->playback->fd, SNDCTL_DSP_SETTRIGGER, &enableBits ), paUnanticipatedHostError ); + } + } + + /* Ok, we have triggered the stream */ + stream->triggered = 1; + +error: + return result; +} + +/** Stop audio processing + * + */ +static PaError PaOssStream_Stop( PaOssStream *stream, int abort ) +{ + PaError result = paNoError; + + /* Looks like the only safe way to stop audio without reopening the device is SNDCTL_DSP_POST. + * Also disable capture/playback till the stream is started again */ + if( stream->capture ) + { + ENSURE_( ioctl( stream->capture->fd, SNDCTL_DSP_POST, 0 ), paUnanticipatedHostError ); + } + if( stream->playback && !stream->sharedDevice ) + { + ENSURE_( ioctl( stream->playback->fd, SNDCTL_DSP_POST, 0 ), paUnanticipatedHostError ); + } + +error: + return result; +} + +/** Clean up after thread exit. + * + * Aspect StreamState: If the user has registered a streamFinishedCallback it will be called here + */ +static void OnExit( void *data ) +{ + PaOssStream *stream = (PaOssStream *) data; + assert( data ); + + PaUtil_ResetCpuLoadMeasurer( &stream->cpuLoadMeasurer ); + + PaOssStream_Stop( stream, stream->callbackAbort ); + + PA_DEBUG(( "OnExit: Stoppage\n" )); + + /* Eventually notify user all buffers have played */ + if( stream->streamRepresentation.streamFinishedCallback ) + stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData ); + + stream->callbackAbort = 0; /* Clear state */ + stream->isActive = 0; +} + +static PaError SetUpBuffers( PaOssStream *stream, unsigned long framesAvail ) +{ + PaError result = paNoError; + + if( stream->capture ) + { + PaUtil_SetInterleavedInputChannels( &stream->bufferProcessor, 0, stream->capture->buffer, + stream->capture->hostChannelCount ); + PaUtil_SetInputFrameCount( &stream->bufferProcessor, framesAvail ); + } + if( stream->playback ) + { + PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor, 0, stream->playback->buffer, + stream->playback->hostChannelCount ); + PaUtil_SetOutputFrameCount( &stream->bufferProcessor, framesAvail ); + } + + return result; +} + +/** Thread procedure for callback processing. + * + * Aspect StreamState: StartStream will wait on this to initiate audio processing, useful in case the + * callback should be used for buffer priming. When the stream is cancelled a separate function will + * take care of the transition to the Callback Finished state (the stream isn't considered Stopped + * before StopStream() or AbortStream() are called). + */ +static void *PaOSS_AudioThreadProc( void *userData ) +{ + PaError result = paNoError; + PaOssStream *stream = (PaOssStream*)userData; + unsigned long framesAvail = 0, framesProcessed = 0; + int callbackResult = paContinue; + int triggered = stream->triggered; /* See if SNDCTL_DSP_TRIGGER has been issued already */ + int initiateProcessing = triggered; /* Already triggered? */ + PaStreamCallbackFlags cbFlags = 0; /* We might want to keep state across iterations */ + PaStreamCallbackTimeInfo timeInfo = {0,0,0}; /* TODO: IMPLEMENT ME */ + + /* +#if ( SOUND_VERSION > 0x030904 ) + audio_errinfo errinfo; +#endif +*/ + + assert( stream ); + + pthread_cleanup_push( &OnExit, stream ); /* Execute OnExit when exiting */ + + /* The first time the stream is started we use SNDCTL_DSP_TRIGGER to accurately start capture and + * playback in sync, when the stream is restarted after being stopped we simply start by reading/ + * writing. + */ + PA_ENSURE( PaOssStream_Prepare( stream ) ); + + /* If we are to initiate processing implicitly by reading/writing data, we start off in blocking mode */ + if( initiateProcessing ) + { + /* Make sure devices are in blocking mode */ + if( stream->capture ) + ModifyBlocking( stream->capture->fd, 1 ); + if( stream->playback ) + ModifyBlocking( stream->playback->fd, 1 ); + } + + while( 1 ) + { + pthread_testcancel(); + + if( stream->callbackStop && callbackResult == paContinue ) + { + PA_DEBUG(( "Setting callbackResult to paComplete\n" )); + callbackResult = paComplete; + } + + /* Aspect StreamState: Because of the messy OSS scheme we can't explicitly trigger device start unless + * the stream has been recently started, we will have to go right ahead and read/write in blocking + * fashion to trigger operation. Therefore we begin with processing one host buffer before we switch + * to non-blocking mode. + */ + if( !initiateProcessing ) + { + /* Wait on available frames */ + PA_ENSURE( PaOssStream_WaitForFrames( stream, &framesAvail ) ); + assert( framesAvail % stream->framesPerHostBuffer == 0 ); + } + else + { + framesAvail = stream->framesPerHostBuffer; + } + + while( framesAvail > 0 ) + { + unsigned long frames = framesAvail; + + pthread_testcancel(); + + PaUtil_BeginCpuLoadMeasurement( &stream->cpuLoadMeasurer ); + + /* Read data */ + if ( stream->capture ) + { + PA_ENSURE( PaOssStreamComponent_Read( stream->capture, &frames ) ); + if( frames < framesAvail ) + { + PA_DEBUG(( "Read %lu less frames than requested\n", framesAvail - frames )); + framesAvail = frames; + } + } + +#if ( SOUND_VERSION >= 0x030904 ) + /* + Check with OSS to see if there have been any under/overruns + since last time we checked. + */ + /* + if( ioctl( stream->deviceHandle, SNDCTL_DSP_GETERROR, &errinfo ) >= 0 ) + { + if( errinfo.play_underruns ) + cbFlags |= paOutputUnderflow ; + if( errinfo.record_underruns ) + cbFlags |= paInputUnderflow ; + } + else + PA_DEBUG(( "SNDCTL_DSP_GETERROR command failed: %s\n", strerror( errno ) )); + */ +#endif + + PaUtil_BeginBufferProcessing( &stream->bufferProcessor, &timeInfo, + cbFlags ); + cbFlags = 0; + PA_ENSURE( SetUpBuffers( stream, framesAvail ) ); + + framesProcessed = PaUtil_EndBufferProcessing( &stream->bufferProcessor, + &callbackResult ); + assert( framesProcessed == framesAvail ); + PaUtil_EndCpuLoadMeasurement( &stream->cpuLoadMeasurer, framesProcessed ); + + if ( stream->playback ) + { + frames = framesAvail; + + PA_ENSURE( PaOssStreamComponent_Write( stream->playback, &frames ) ); + if( frames < framesAvail ) + { + /* TODO: handle bytesWritten != bytesRequested (slippage?) */ + PA_DEBUG(( "Wrote %lu less frames than requested\n", framesAvail - frames )); + } + } + + framesAvail -= framesProcessed; + stream->framesProcessed += framesProcessed; + + if( callbackResult != paContinue ) + break; + } + + if( initiateProcessing || !triggered ) + { + /* Non-blocking */ + if( stream->capture ) + PA_ENSURE( ModifyBlocking( stream->capture->fd, 0 ) ); + if( stream->playback && !stream->sharedDevice ) + PA_ENSURE( ModifyBlocking( stream->playback->fd, 0 ) ); + + initiateProcessing = 0; + sem_post( &stream->semaphore ); + } + + if( callbackResult != paContinue ) + { + stream->callbackAbort = callbackResult == paAbort; + if( stream->callbackAbort || PaUtil_IsBufferProcessorOutputEmpty( &stream->bufferProcessor ) ) + break; + } + } + + pthread_cleanup_pop( 1 ); + +error: + pthread_exit( NULL ); +} + +/** Close the stream. + * + */ +static PaError CloseStream( PaStream* s ) +{ + PaError result = paNoError; + PaOssStream *stream = (PaOssStream*)s; + + assert( stream ); + + PaUtil_TerminateBufferProcessor( &stream->bufferProcessor ); + PaOssStream_Terminate( stream ); + + return result; +} + +/** Start the stream. + * + * Aspect StreamState: After returning, the stream shall be in the Active state, implying that an eventual + * callback will be repeatedly called in a separate thread. If a separate thread is started this function + * will block untill it has started processing audio, otherwise audio processing is started directly. + */ +static PaError StartStream( PaStream *s ) +{ + PaError result = paNoError; + PaOssStream *stream = (PaOssStream*)s; + + stream->isActive = 1; + stream->isStopped = 0; + stream->lastPosPtr = 0; + stream->lastStreamBytes = 0; + stream->framesProcessed = 0; + + /* only use the thread for callback streams */ + if( stream->bufferProcessor.streamCallback ) + { + PA_ENSURE( PaUtil_StartThreading( &stream->threading, &PaOSS_AudioThreadProc, stream ) ); + sem_wait( &stream->semaphore ); + } + else + PA_ENSURE( PaOssStream_Prepare( stream ) ); + +error: + return result; +} + +static PaError RealStop( PaOssStream *stream, int abort ) +{ + PaError result = paNoError; + + if( stream->callbackMode ) + { + if( abort ) + stream->callbackAbort = 1; + else + stream->callbackStop = 1; + + PA_ENSURE( PaUtil_CancelThreading( &stream->threading, !abort, NULL ) ); + + stream->callbackStop = stream->callbackAbort = 0; + } + else + PA_ENSURE( PaOssStream_Stop( stream, abort ) ); + + stream->isStopped = 1; + +error: + return result; +} + +/** Stop the stream. + * + * Aspect StreamState: This will cause the stream to transition to the Stopped state, playing all enqueued + * buffers. + */ +static PaError StopStream( PaStream *s ) +{ + return RealStop( (PaOssStream *)s, 0 ); +} + +/** Abort the stream. + * + * Aspect StreamState: This will cause the stream to transition to the Stopped state, discarding all enqueued + * buffers. Note that the buffers are not currently correctly discarded, this is difficult without closing + * the OSS device. + */ +static PaError AbortStream( PaStream *s ) +{ + return RealStop( (PaOssStream *)s, 1 ); +} + +/** Is the stream in the Stopped state. + * + */ +static PaError IsStreamStopped( PaStream *s ) +{ + PaOssStream *stream = (PaOssStream*)s; + + return (stream->isStopped); +} + +/** Is the stream in the Active state. + * + */ +static PaError IsStreamActive( PaStream *s ) +{ + PaOssStream *stream = (PaOssStream*)s; + + return (stream->isActive); +} + +static PaTime GetStreamTime( PaStream *s ) +{ + PaOssStream *stream = (PaOssStream*)s; + count_info info; + int delta; + + if( stream->playback ) { + if( ioctl( stream->playback->fd, SNDCTL_DSP_GETOPTR, &info) == 0 ) { + delta = ( info.bytes - stream->lastPosPtr ) /* & 0x000FFFFF*/; + return (float)(stream->lastStreamBytes + delta) / PaOssStreamComponent_FrameSize( stream->playback ) / stream->sampleRate; + } + } + else { + if (ioctl( stream->capture->fd, SNDCTL_DSP_GETIPTR, &info) == 0) { + delta = (info.bytes - stream->lastPosPtr) /*& 0x000FFFFF*/; + return (float)(stream->lastStreamBytes + delta) / PaOssStreamComponent_FrameSize( stream->capture ) / stream->sampleRate; + } + } + + /* the ioctl failed, but we can still give a coarse estimate */ + + return stream->framesProcessed / stream->sampleRate; +} + + +static double GetStreamCpuLoad( PaStream* s ) +{ + PaOssStream *stream = (PaOssStream*)s; + + return PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer ); +} + + +/* + As separate stream interfaces are used for blocking and callback + streams, the following functions can be guaranteed to only be called + for blocking streams. +*/ + + +static PaError ReadStream( PaStream* s, + void *buffer, + unsigned long frames ) +{ + PaOssStream *stream = (PaOssStream*)s; + int bytesRequested, bytesRead; + unsigned long framesRequested; + void *userBuffer; + + /* If user input is non-interleaved, PaUtil_CopyInput will manipulate the channel pointers, + * so we copy the user provided pointers */ + if( stream->bufferProcessor.userInputIsInterleaved ) + userBuffer = buffer; + else /* Copy channels into local array */ + { + userBuffer = stream->capture->userBuffers; + memcpy( (void *)userBuffer, buffer, sizeof (void *) * stream->capture->userChannelCount ); + } + + while( frames ) + { + framesRequested = PA_MIN( frames, stream->capture->hostFrames ); + + bytesRequested = framesRequested * PaOssStreamComponent_FrameSize( stream->capture ); + bytesRead = read( stream->capture->fd, stream->capture->buffer, bytesRequested ); + if ( bytesRequested != bytesRead ) + return paUnanticipatedHostError; + + PaUtil_SetInputFrameCount( &stream->bufferProcessor, stream->capture->hostFrames ); + PaUtil_SetInterleavedInputChannels( &stream->bufferProcessor, 0, stream->capture->buffer, stream->capture->hostChannelCount ); + PaUtil_CopyInput( &stream->bufferProcessor, &userBuffer, framesRequested ); + frames -= framesRequested; + } + return paNoError; +} + + +static PaError WriteStream( PaStream *s, const void *buffer, unsigned long frames ) +{ + PaOssStream *stream = (PaOssStream*)s; + int bytesRequested, bytesWritten; + unsigned long framesConverted; + const void *userBuffer; + + /* If user output is non-interleaved, PaUtil_CopyOutput will manipulate the channel pointers, + * so we copy the user provided pointers */ + if( stream->bufferProcessor.userOutputIsInterleaved ) + userBuffer = buffer; + else + { + /* Copy channels into local array */ + userBuffer = stream->playback->userBuffers; + memcpy( (void *)userBuffer, buffer, sizeof (void *) * stream->playback->userChannelCount ); + } + + while( frames ) + { + PaUtil_SetOutputFrameCount( &stream->bufferProcessor, stream->playback->hostFrames ); + PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor, 0, stream->playback->buffer, stream->playback->hostChannelCount ); + + framesConverted = PaUtil_CopyOutput( &stream->bufferProcessor, &userBuffer, frames ); + frames -= framesConverted; + + bytesRequested = framesConverted * PaOssStreamComponent_FrameSize( stream->playback ); + bytesWritten = write( stream->playback->fd, stream->playback->buffer, bytesRequested ); + + if ( bytesRequested != bytesWritten ) + return paUnanticipatedHostError; + } + return paNoError; +} + + +static signed long GetStreamReadAvailable( PaStream* s ) +{ + PaOssStream *stream = (PaOssStream*)s; + audio_buf_info info; + + if( ioctl( stream->capture->fd, SNDCTL_DSP_GETISPACE, &info ) < 0 ) + return paUnanticipatedHostError; + return info.fragments * stream->capture->hostFrames; +} + + +/* TODO: Compute number of allocated bytes somewhere else, can we use ODELAY with capture */ +static signed long GetStreamWriteAvailable( PaStream* s ) +{ + PaOssStream *stream = (PaOssStream*)s; + int delay = 0; + + if( ioctl( stream->playback->fd, SNDCTL_DSP_GETODELAY, &delay ) < 0 ) + return paUnanticipatedHostError; + + return (PaOssStreamComponent_BufferSize( stream->playback ) - delay) / PaOssStreamComponent_FrameSize( stream->playback ); +} + Index: julius4/libsent/src/adin/pa/hostapi/oss/recplay.c diff -u /dev/null julius4/libsent/src/adin/pa/hostapi/oss/recplay.c:1.1 --- /dev/null Sat Feb 5 18:00:03 2011 +++ julius4/libsent/src/adin/pa/hostapi/oss/recplay.c Sat Feb 5 18:00:03 2011 @@ -0,0 +1,114 @@ +/* + * recplay.c + * Phil Burk + * Minimal record and playback test. + * + */ +#include +#include +#include +#ifndef __STDC__ +/* #include */ +#endif /* __STDC__ */ +#include +#ifdef __STDC__ +#include +#else /* __STDC__ */ +#include +#endif /* __STDC__ */ +#include + +#define NUM_BYTES (64*1024) +#define BLOCK_SIZE (4*1024) + +#define AUDIO "/dev/dsp" + +char buffer[NUM_BYTES]; + +int audioDev = 0; + +main (int argc, char *argv[]) +{ + int numLeft; + char *ptr; + int num; + int samplesize; + + /********** RECORD ********************/ + /* Open audio device. */ + audioDev = open (AUDIO, O_RDONLY, 0); + if (audioDev == -1) + { + perror (AUDIO); + exit (-1); + } + + /* Set to 16 bit samples. */ + samplesize = 16; + ioctl(audioDev, SNDCTL_DSP_SAMPLESIZE, &samplesize); + if (samplesize != 16) + { + perror("Unable to set the sample size."); + exit(-1); + } + + /* Record in blocks */ + printf("Begin recording.\n"); + numLeft = NUM_BYTES; + ptr = buffer; + while( numLeft >= BLOCK_SIZE ) + { + if ( (num = read (audioDev, ptr, BLOCK_SIZE)) < 0 ) + { + perror (AUDIO); + exit (-1); + } + else + { + printf("Read %d bytes\n", num); + ptr += num; + numLeft -= num; + } + } + + close( audioDev ); + + /********** PLAYBACK ********************/ + /* Open audio device for writing. */ + audioDev = open (AUDIO, O_WRONLY, 0); + if (audioDev == -1) + { + perror (AUDIO); + exit (-1); + } + + /* Set to 16 bit samples. */ + samplesize = 16; + ioctl(audioDev, SNDCTL_DSP_SAMPLESIZE, &samplesize); + if (samplesize != 16) + { + perror("Unable to set the sample size."); + exit(-1); + } + + /* Play in blocks */ + printf("Begin playing.\n"); + numLeft = NUM_BYTES; + ptr = buffer; + while( numLeft >= BLOCK_SIZE ) + { + if ( (num = write (audioDev, ptr, BLOCK_SIZE)) < 0 ) + { + perror (AUDIO); + exit (-1); + } + else + { + printf("Wrote %d bytes\n", num); + ptr += num; + numLeft -= num; + } + } + + close( audioDev ); +} From sumomo @ users.sourceforge.jp Sat Feb 5 18:00:03 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Sat, 05 Feb 2011 18:00:03 +0900 Subject: [Julius-cvs 587] CVS update: julius4/libsent/src/adin/pa/hostapi/wasapi Message-ID: <1296896403.497458.28602.nullmailer@users.sourceforge.jp> Index: julius4/libsent/src/adin/pa/hostapi/wasapi/pa_win_wasapi.cpp diff -u /dev/null julius4/libsent/src/adin/pa/hostapi/wasapi/pa_win_wasapi.cpp:1.1 --- /dev/null Sat Feb 5 18:00:03 2011 +++ julius4/libsent/src/adin/pa/hostapi/wasapi/pa_win_wasapi.cpp Sat Feb 5 18:00:03 2011 @@ -0,0 +1,1911 @@ +/* + * Portable Audio I/O Library WASAPI implementation + * Copyright (c) 2006-2007 David Viens + * + * Based on the Open Source API proposed by Ross Bencina + * Copyright (c) 1999-2002 Ross Bencina, Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/* + * The text above constitutes the entire PortAudio license; however, + * the PortAudio community also makes the following non-binding requests: + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. It is also + * requested that these non-binding requests be included along with the + * license above. + */ + +/** @file + @ingroup hostaip_src + @brief WASAPI implementation of support for a host API. + + @note pa_wasapi currently requires VC 2005, and the latest Vista SDK +*/ + +#if _MSC_VER >= 1400 +#include +#include //must be before other Wasapi headers +#include +#include +#include +#include +#include + +#include +#include // PKEY_Device_FriendlyName +#endif + +#include "pa_util.h" +#include "pa_allocation.h" +#include "pa_hostapi.h" +#include "pa_stream.h" +#include "pa_cpuload.h" +#include "pa_process.h" +#include "pa_debugprint.h" + + +/* + davidv : work in progress. try using with 48000 , then 44100 + and shared mode FIRST. + */ + +#define PORTAUDIO_SHAREMODE AUDCLNT_SHAREMODE_SHARED +//#define PORTAUDIO_SHAREMODE AUDCLNT_SHAREMODE_EXCLUSIVE + + + +/* prototypes for functions declared in this file */ + +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +PaError PaWinWasapi_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index ); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + + + + +static void Terminate( struct PaUtilHostApiRepresentation *hostApi ); +static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi, + const PaStreamParameters *inputParameters, + const PaStreamParameters *outputParameters, + double sampleRate ); +static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi, + PaStream** s, + const PaStreamParameters *inputParameters, + const PaStreamParameters *outputParameters, + double sampleRate, + unsigned long framesPerBuffer, + PaStreamFlags streamFlags, + PaStreamCallback *streamCallback, + void *userData ); +static PaError CloseStream( PaStream* stream ); +static PaError StartStream( PaStream *stream ); +static PaError StopStream( PaStream *stream ); +static PaError AbortStream( PaStream *stream ); +static PaError IsStreamStopped( PaStream *s ); +static PaError IsStreamActive( PaStream *stream ); +static PaTime GetStreamTime( PaStream *stream ); +static double GetStreamCpuLoad( PaStream* stream ); +static PaError ReadStream( PaStream* stream, void *buffer, unsigned long frames ); +static PaError WriteStream( PaStream* stream, const void *buffer, unsigned long frames ); +static signed long GetStreamReadAvailable( PaStream* stream ); +static signed long GetStreamWriteAvailable( PaStream* stream ); + + +/* IMPLEMENT ME: a macro like the following one should be used for reporting + host errors */ +#define PA_SKELETON_SET_LAST_HOST_ERROR( errorCode, errorText ) \ + PaUtil_SetLastHostErrorInfo( paInDevelopment, errorCode, errorText ) + +/* PaWinWasapiHostApiRepresentation - host api datastructure specific to this implementation */ + + + +//dummy entry point for other compilers and sdks +//currently built using RC1 SDK (5600) +#if _MSC_VER < 1400 + +PaError PaWinWasapi_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex ){ + return paNoError; +} + +#else + + + + +#define MAX_STR_LEN 512 + +/* + These are fields that can be gathered from IDevice + and IAudioDevice PRIOR to Initialize, and done in first pass + i assume that neither of these will cause the Driver to "load", + but again, who knows how they implement their stuff + */ +typedef struct PaWinWasapiDeviceInfo +{ + //hmm is it wise to keep a reference until Terminate? + //TODO Check if that interface requires the driver to be loaded! + IMMDevice * device; + + //Fields filled from IDevice + //from GetId + WCHAR szDeviceID[MAX_STR_LEN]; + //from GetState + DWORD state; + + //Fields filled from IMMEndpoint'sGetDataFlow + EDataFlow flow; + + //Fields filled from IAudioDevice (_prior_ to Initialize) + //from GetDevicePeriod( + REFERENCE_TIME DefaultDevicePeriod; + REFERENCE_TIME MinimumDevicePeriod; + //from GetMixFormat + WAVEFORMATEX *MixFormat;//needs to be CoTaskMemFree'd after use! + +} PaWinWasapiDeviceInfo; + + +typedef struct +{ + PaUtilHostApiRepresentation inheritedHostApiRep; + PaUtilStreamInterface callbackStreamInterface; + PaUtilStreamInterface blockingStreamInterface; + + PaUtilAllocationGroup *allocations; + + /* implementation specific data goes here */ + + //in case we later need the synch + IMMDeviceEnumerator * enumerator; + + //this is the REAL number of devices, whether they are usefull to PA or not! + UINT deviceCount; + + WCHAR defaultRenderer [MAX_STR_LEN]; + WCHAR defaultCapturer [MAX_STR_LEN]; + + PaWinWasapiDeviceInfo *devInfo; +}PaWinWasapiHostApiRepresentation; + + +/* PaWinWasapiStream - a stream data structure specifically for this implementation */ + +typedef struct PaWinWasapiSubStream{ + IAudioClient *client; + WAVEFORMATEXTENSIBLE wavex; + UINT32 bufferSize; + REFERENCE_TIME latency; + REFERENCE_TIME period; + unsigned long framesPerHostCallback; /* just an example */ +}PaWinWasapiSubStream; + +typedef struct PaWinWasapiStream +{ /* IMPLEMENT ME: rename this */ + PaUtilStreamRepresentation streamRepresentation; + PaUtilCpuLoadMeasurer cpuLoadMeasurer; + PaUtilBufferProcessor bufferProcessor; + + /* IMPLEMENT ME: + - implementation specific data goes here + */ + + + //input + PaWinWasapiSubStream in; + IAudioCaptureClient *cclient; + IAudioEndpointVolume *inVol; + //output + PaWinWasapiSubStream out; + IAudioRenderClient *rclient; + IAudioEndpointVolume *outVol; + + bool running; + bool closeRequest; + + DWORD dwThreadId; + HANDLE hThread; + HANDLE hNotificationEvent; + + GUID session; + +}PaWinWasapiStream; + +#define PRINT(x) PA_DEBUG(x); + +void +logAUDCLNT_E(HRESULT res){ + + char *text = 0; + switch(res){ + case S_OK: return; break; + case E_POINTER :text ="E_POINTER"; break; + case E_INVALIDARG :text ="E_INVALIDARG"; break; + + case AUDCLNT_E_NOT_INITIALIZED :text ="AUDCLNT_E_NOT_INITIALIZED"; break; + case AUDCLNT_E_ALREADY_INITIALIZED :text ="AUDCLNT_E_ALREADY_INITIALIZED"; break; + case AUDCLNT_E_WRONG_ENDPOINT_TYPE :text ="AUDCLNT_E_WRONG_ENDPOINT_TYPE"; break; + case AUDCLNT_E_DEVICE_INVALIDATED :text ="AUDCLNT_E_DEVICE_INVALIDATED"; break; + case AUDCLNT_E_NOT_STOPPED :text ="AUDCLNT_E_NOT_STOPPED"; break; + case AUDCLNT_E_BUFFER_TOO_LARGE :text ="AUDCLNT_E_BUFFER_TOO_LARGE"; break; + case AUDCLNT_E_OUT_OF_ORDER :text ="AUDCLNT_E_OUT_OF_ORDER"; break; + case AUDCLNT_E_UNSUPPORTED_FORMAT :text ="AUDCLNT_E_UNSUPPORTED_FORMAT"; break; + case AUDCLNT_E_INVALID_SIZE :text ="AUDCLNT_E_INVALID_SIZE"; break; + case AUDCLNT_E_DEVICE_IN_USE :text ="AUDCLNT_E_DEVICE_IN_USE"; break; + case AUDCLNT_E_BUFFER_OPERATION_PENDING :text ="AUDCLNT_E_BUFFER_OPERATION_PENDING"; break; + case AUDCLNT_E_THREAD_NOT_REGISTERED :text ="AUDCLNT_E_THREAD_NOT_REGISTERED"; break; + case AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED :text ="AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED"; break; + case AUDCLNT_E_ENDPOINT_CREATE_FAILED :text ="AUDCLNT_E_ENDPOINT_CREATE_FAILED"; break; + case AUDCLNT_E_SERVICE_NOT_RUNNING :text ="AUDCLNT_E_SERVICE_NOT_RUNNING"; break; + // case AUDCLNT_E_CPUUSAGE_EXCEEDED :text ="AUDCLNT_E_CPUUSAGE_EXCEEDED"; break; + //Header error? + case AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED :text ="AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED"; break; + case AUDCLNT_E_EXCLUSIVE_MODE_ONLY :text ="AUDCLNT_E_EXCLUSIVE_MODE_ONLY"; break; + case AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL :text ="AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL"; break; + case AUDCLNT_E_EVENTHANDLE_NOT_SET :text ="AUDCLNT_E_EVENTHANDLE_NOT_SET"; break; + case AUDCLNT_E_INCORRECT_BUFFER_SIZE :text ="AUDCLNT_E_INCORRECT_BUFFER_SIZE"; break; + case AUDCLNT_E_BUFFER_SIZE_ERROR :text ="AUDCLNT_E_BUFFER_SIZE_ERROR"; break; + case AUDCLNT_S_BUFFER_EMPTY :text ="AUDCLNT_S_BUFFER_EMPTY"; break; + case AUDCLNT_S_THREAD_ALREADY_REGISTERED :text ="AUDCLNT_S_THREAD_ALREADY_REGISTERED"; break; + default: + text =" dunno!"; + return ; + break; + + } + PRINT(("WASAPI ERROR HRESULT: 0x%X : %s\n",res,text)); +} + +inline double +nano100ToMillis(const REFERENCE_TIME &ref){ + // 1 nano = 0.000000001 seconds + //100 nano = 0.0000001 seconds + //100 nano = 0.0001 milliseconds + return ((double)ref)*0.0001; +} + +inline double +nano100ToSeconds(const REFERENCE_TIME &ref){ + // 1 nano = 0.000000001 seconds + //100 nano = 0.0000001 seconds + //100 nano = 0.0001 milliseconds + return ((double)ref)*0.0000001; +} + +#ifndef IF_FAILED_JUMP +#define IF_FAILED_JUMP(hr, label) if(FAILED(hr)) goto label; +#endif + + + +//AVRT is the new "multimedia schedulling stuff" + +typedef BOOL (WINAPI *FAvRtCreateThreadOrderingGroup) (PHANDLE,PLARGE_INTEGER,GUID*,PLARGE_INTEGER); +typedef BOOL (WINAPI *FAvRtDeleteThreadOrderingGroup) (HANDLE); +typedef BOOL (WINAPI *FAvRtWaitOnThreadOrderingGroup) (HANDLE); +typedef HANDLE (WINAPI *FAvSetMmThreadCharacteristics) (LPCTSTR,LPDWORD); +typedef BOOL (WINAPI *FAvSetMmThreadPriority) (HANDLE,AVRT_PRIORITY); + +HMODULE hDInputDLL = 0; +FAvRtCreateThreadOrderingGroup pAvRtCreateThreadOrderingGroup=0; +FAvRtDeleteThreadOrderingGroup pAvRtDeleteThreadOrderingGroup=0; +FAvRtWaitOnThreadOrderingGroup pAvRtWaitOnThreadOrderingGroup=0; +FAvSetMmThreadCharacteristics pAvSetMmThreadCharacteristics=0; +FAvSetMmThreadPriority pAvSetMmThreadPriority=0; + + + +#define setupPTR(fun, type, name) { \ + fun = (type) GetProcAddress(hDInputDLL,name); \ + if(fun == NULL) { \ + PRINT(("GetProcAddr failed for %s" ,name)); \ + return false; \ + } \ + } \ + +bool +setupAVRT(){ + + hDInputDLL = LoadLibraryA("avrt.dll"); + if(hDInputDLL == NULL) + return false; + + setupPTR(pAvRtCreateThreadOrderingGroup, FAvRtCreateThreadOrderingGroup, "AvRtCreateThreadOrderingGroup"); + setupPTR(pAvRtDeleteThreadOrderingGroup, FAvRtDeleteThreadOrderingGroup, "AvRtDeleteThreadOrderingGroup"); + setupPTR(pAvRtWaitOnThreadOrderingGroup, FAvRtWaitOnThreadOrderingGroup, "AvRtWaitOnThreadOrderingGroup"); + setupPTR(pAvSetMmThreadCharacteristics, FAvSetMmThreadCharacteristics, "AvSetMmThreadCharacteristicsA"); + setupPTR(pAvSetMmThreadPriority, FAvSetMmThreadPriority, "AvSetMmThreadPriority"); + + return true; +} + + + +PaError PaWinWasapi_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex ) +{ + if (!setupAVRT()){ + PRINT(("Windows WASAPI : No AVRT! (not VISTA?)")); + return paNoError; + } + + CoInitialize(NULL); + + PaError result = paNoError; + PaWinWasapiHostApiRepresentation *paWasapi; + PaDeviceInfo *deviceInfoArray; + + paWasapi = (PaWinWasapiHostApiRepresentation*)PaUtil_AllocateMemory( sizeof(PaWinWasapiHostApiRepresentation) ); + if( !paWasapi ){ + result = paInsufficientMemory; + goto error; + } + + paWasapi->allocations = PaUtil_CreateAllocationGroup(); + if( !paWasapi->allocations ){ + result = paInsufficientMemory; + goto error; + } + + *hostApi = &paWasapi->inheritedHostApiRep; + (*hostApi)->info.structVersion = 1; + (*hostApi)->info.type = paWASAPI; + (*hostApi)->info.name = "Windows WASAPI"; + (*hostApi)->info.deviceCount = 0; //so far, we must investigate each + (*hostApi)->info.defaultInputDevice = paNoDevice; /* IMPLEMENT ME */ + (*hostApi)->info.defaultOutputDevice = paNoDevice; /* IMPLEMENT ME */ + + + HRESULT hResult = S_OK; + IMMDeviceCollection* spEndpoints=0; + paWasapi->enumerator = 0; + + hResult = CoCreateInstance( + __uuidof(MMDeviceEnumerator), NULL,CLSCTX_INPROC_SERVER, + __uuidof(IMMDeviceEnumerator), + (void**)&paWasapi->enumerator); + + IF_FAILED_JUMP(hResult, error); + + //getting default device ids in the eMultimedia "role" + { + { + IMMDevice* defaultRenderer=0; + hResult = paWasapi->enumerator->GetDefaultAudioEndpoint(eRender, eMultimedia, &defaultRenderer); + IF_FAILED_JUMP(hResult, error); + WCHAR* pszDeviceId = NULL; + hResult = defaultRenderer->GetId(&pszDeviceId); + IF_FAILED_JUMP(hResult, error); + StringCchCopyW(paWasapi->defaultRenderer, MAX_STR_LEN-1, pszDeviceId); + CoTaskMemFree(pszDeviceId); + defaultRenderer->Release(); + } + + { + IMMDevice* defaultCapturer=0; + hResult = paWasapi->enumerator->GetDefaultAudioEndpoint(eCapture, eMultimedia, &defaultCapturer); + IF_FAILED_JUMP(hResult, error); + WCHAR* pszDeviceId = NULL; + hResult = defaultCapturer->GetId(&pszDeviceId); + IF_FAILED_JUMP(hResult, error); + StringCchCopyW(paWasapi->defaultCapturer, MAX_STR_LEN-1, pszDeviceId); + CoTaskMemFree(pszDeviceId); + defaultCapturer->Release(); + } + } + + + hResult = paWasapi->enumerator->EnumAudioEndpoints(eAll, DEVICE_STATE_ACTIVE, &spEndpoints); + IF_FAILED_JUMP(hResult, error); + + hResult = spEndpoints->GetCount(&paWasapi->deviceCount); + IF_FAILED_JUMP(hResult, error); + + paWasapi->devInfo = new PaWinWasapiDeviceInfo[paWasapi->deviceCount]; + { + for (size_t step=0;stepdeviceCount;++step) + memset(&paWasapi->devInfo[step],0,sizeof(PaWinWasapiDeviceInfo)); + } + + + + if( paWasapi->deviceCount > 0 ) + { + (*hostApi)->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory( + paWasapi->allocations, sizeof(PaDeviceInfo*) * paWasapi->deviceCount ); + if( !(*hostApi)->deviceInfos ){ + result = paInsufficientMemory; + goto error; + } + + /* allocate all device info structs in a contiguous block */ + deviceInfoArray = (PaDeviceInfo*)PaUtil_GroupAllocateMemory( + paWasapi->allocations, sizeof(PaDeviceInfo) * paWasapi->deviceCount ); + if( !deviceInfoArray ){ + result = paInsufficientMemory; + goto error; + } + + for( UINT i=0; i < paWasapi->deviceCount; ++i ){ + + PA_DEBUG(("i:%d\n",i)); + PaDeviceInfo *deviceInfo = &deviceInfoArray[i]; + deviceInfo->structVersion = 2; + deviceInfo->hostApi = hostApiIndex; + + hResult = spEndpoints->Item(i, &paWasapi->devInfo[i].device); + IF_FAILED_JUMP(hResult, error); + + //getting ID + { + WCHAR* pszDeviceId = NULL; + hResult = paWasapi->devInfo[i].device->GetId(&pszDeviceId); + IF_FAILED_JUMP(hResult, error); + StringCchCopyW(paWasapi->devInfo[i].szDeviceID, MAX_STR_LEN-1, pszDeviceId); + CoTaskMemFree(pszDeviceId); + + if (lstrcmpW(paWasapi->devInfo[i].szDeviceID, paWasapi->defaultCapturer)==0){ + //we found the default input! + (*hostApi)->info.defaultInputDevice = (*hostApi)->info.deviceCount; + } + if (lstrcmpW(paWasapi->devInfo[i].szDeviceID, paWasapi->defaultRenderer)==0){ + //we found the default output! + (*hostApi)->info.defaultOutputDevice = (*hostApi)->info.deviceCount; + } + } + + DWORD state=0; + hResult = paWasapi->devInfo[i].device->GetState(&paWasapi->devInfo[i].state); + IF_FAILED_JUMP(hResult, error); + + if (paWasapi->devInfo[i].state != DEVICE_STATE_ACTIVE){ + PRINT(("WASAPI device:%d is not currently available (state:%d)\n",i,state)); + //spDevice->Release(); + //continue; + } + + { + IPropertyStore* spProperties; + hResult = paWasapi->devInfo[i].device->OpenPropertyStore(STGM_READ, &spProperties); + IF_FAILED_JUMP(hResult, error); + + //getting "Friendly" Name + { + PROPVARIANT value; + PropVariantInit(&value); + hResult = spProperties->GetValue(PKEY_Device_FriendlyName, &value); + IF_FAILED_JUMP(hResult, error); + deviceInfo->name = 0; + char* deviceName = (char*)PaUtil_GroupAllocateMemory( paWasapi->allocations, MAX_STR_LEN + 1 ); + if( !deviceName ){ + result = paInsufficientMemory; + goto error; + } + if (value.pwszVal) + wcstombs(deviceName, value.pwszVal,MAX_STR_LEN-1); //todo proper size + else{ + sprintf(deviceName,"baddev%d",i); + } + + deviceInfo->name = deviceName; + PropVariantClear(&value); + } + +#if 0 + DWORD numProps = 0; + hResult = spProperties->GetCount(&numProps); + IF_FAILED_JUMP(hResult, error); + { + for (DWORD i=0;iGetAt(i,&pkey); + + PROPVARIANT value; + PropVariantInit(&value); + hResult = spProperties->GetValue(pkey, &value); + + switch(value.vt){ + case 11: + PRINT(("property*%u*\n",value.ulVal)); + break; + case 19: + PRINT(("property*%d*\n",value.boolVal)); + break; + case 31: + { + char temp[512]; + wcstombs(temp, value.pwszVal,MAX_STR_LEN-1); + PRINT(("property*%s*\n",temp)); + } + break; + default:break; + } + + PropVariantClear(&value); + } + } +#endif + + /* These look interresting... but they are undocumented + PKEY_AudioEndpoint_FormFactor + PKEY_AudioEndpoint_ControlPanelPageProvider + PKEY_AudioEndpoint_Association + PKEY_AudioEndpoint_PhysicalSpeakerConfig + PKEY_AudioEngine_DeviceFormat + */ + spProperties->Release(); + } + + + //getting the Endpoint data + { + IMMEndpoint *endpoint=0; + hResult = paWasapi->devInfo[i].device->QueryInterface(__uuidof(IMMEndpoint),(void **)&endpoint); + if (SUCCEEDED(hResult)){ + hResult = endpoint->GetDataFlow(&paWasapi->devInfo[i].flow); + endpoint->Release(); + } + } + + //Getting a temporary IAudioDevice for more fields + //we make sure NOT to call Initialize yet! + { + IAudioClient *myClient=0; + + hResult = paWasapi->devInfo[i].device->Activate(__uuidof(IAudioClient), CLSCTX_INPROC_SERVER, NULL, (void**)&myClient); + IF_FAILED_JUMP(hResult, error); + + hResult = myClient->GetDevicePeriod( + &paWasapi->devInfo[i].DefaultDevicePeriod, + &paWasapi->devInfo[i].MinimumDevicePeriod); + IF_FAILED_JUMP(hResult, error); + + hResult = myClient->GetMixFormat(&paWasapi->devInfo[i].MixFormat); + + if (hResult != S_OK){ + /*davidv: this happened with my hardware, previously for that same device in DirectSound: + Digital Output (Realtek AC'97 Audio)'s GUID: {0x38f2cf50,0x7b4c,0x4740,0x86,0xeb,0xd4,0x38,0x66,0xd8,0xc8, 0x9f} + so something must be _really_ wrong with this device, TODO handle this better. We kind of need GetMixFormat*/ + logAUDCLNT_E(hResult); + goto error; + } + + myClient->Release(); + } + + //we can now fill in portaudio device data + deviceInfo->maxInputChannels = 0; //for now + deviceInfo->maxOutputChannels = 0; //for now + + switch(paWasapi->devInfo[i].flow){ + case eRender: + //hum not exaclty maximum, more like "default" + deviceInfo->maxOutputChannels = paWasapi->devInfo[i].MixFormat->nChannels; + + deviceInfo->defaultHighOutputLatency = nano100ToSeconds(paWasapi->devInfo[i].DefaultDevicePeriod); + deviceInfo->defaultLowOutputLatency = nano100ToSeconds(paWasapi->devInfo[i].MinimumDevicePeriod); + break; + case eCapture: + //hum not exaclty maximum, more like "default" + deviceInfo->maxInputChannels = paWasapi->devInfo[i].MixFormat->nChannels; + + deviceInfo->defaultHighInputLatency = nano100ToSeconds(paWasapi->devInfo[i].DefaultDevicePeriod); + deviceInfo->defaultLowInputLatency = nano100ToSeconds(paWasapi->devInfo[i].MinimumDevicePeriod); + break; + default: + PRINT(("WASAPI device:%d bad Data FLow! \n",i)); + goto error; + break; + } + + deviceInfo->defaultSampleRate = (double)paWasapi->devInfo[i].MixFormat->nSamplesPerSec; + + (*hostApi)->deviceInfos[i] = deviceInfo; + ++(*hostApi)->info.deviceCount; + } + } + + spEndpoints->Release(); + + (*hostApi)->Terminate = Terminate; + (*hostApi)->OpenStream = OpenStream; + (*hostApi)->IsFormatSupported = IsFormatSupported; + + PaUtil_InitializeStreamInterface( &paWasapi->callbackStreamInterface, CloseStream, StartStream, + StopStream, AbortStream, IsStreamStopped, IsStreamActive, + GetStreamTime, GetStreamCpuLoad, + PaUtil_DummyRead, PaUtil_DummyWrite, + PaUtil_DummyGetReadAvailable, PaUtil_DummyGetWriteAvailable ); + + PaUtil_InitializeStreamInterface( &paWasapi->blockingStreamInterface, CloseStream, StartStream, + StopStream, AbortStream, IsStreamStopped, IsStreamActive, + GetStreamTime, PaUtil_DummyGetCpuLoad, + ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable ); + + return result; + +error: + + if (spEndpoints) + spEndpoints->Release(); + + if (paWasapi->enumerator) + paWasapi->enumerator->Release(); + + if( paWasapi ) + { + if( paWasapi->allocations ) + { + PaUtil_FreeAllAllocations( paWasapi->allocations ); + PaUtil_DestroyAllocationGroup( paWasapi->allocations ); + } + + PaUtil_FreeMemory( paWasapi ); + } + return result; +} + + +static void Terminate( struct PaUtilHostApiRepresentation *hostApi ) +{ + PaWinWasapiHostApiRepresentation *paWasapi = (PaWinWasapiHostApiRepresentation*)hostApi; + + paWasapi->enumerator->Release(); + + for (UINT i=0;ideviceCount;++i){ + PaWinWasapiDeviceInfo *info = &paWasapi->devInfo[i]; + + if (info->device) + info->device->Release(); + + if (info->MixFormat) + CoTaskMemFree(info->MixFormat); + } + delete [] paWasapi->devInfo; + + CoUninitialize(); + + if( paWasapi->allocations ){ + PaUtil_FreeAllAllocations( paWasapi->allocations ); + PaUtil_DestroyAllocationGroup( paWasapi->allocations ); + } + + PaUtil_FreeMemory( paWasapi ); +} + +static void +LogWAVEFORMATEXTENSIBLE(const WAVEFORMATEXTENSIBLE *in){ + + const WAVEFORMATEX *old = (WAVEFORMATEX *)in; + + switch (old->wFormatTag){ + case WAVE_FORMAT_EXTENSIBLE:{ + + PRINT(("wFormatTag=WAVE_FORMAT_EXTENSIBLE\n")); + + if (in->SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT){ + PRINT(("SubFormat=KSDATAFORMAT_SUBTYPE_IEEE_FLOAT\n")); + } + else if (in->SubFormat == KSDATAFORMAT_SUBTYPE_PCM){ + PRINT(("SubFormat=KSDATAFORMAT_SUBTYPE_PCM\n")); + } + else{ + PRINT(("SubFormat=CUSTOM GUID{%d:%d:%d:%d%d%d%d%d%d%d%d}\n", + in->SubFormat.Data1, + in->SubFormat.Data2, + in->SubFormat.Data3, + (int)in->SubFormat.Data4[0], + (int)in->SubFormat.Data4[1], + (int)in->SubFormat.Data4[2], + (int)in->SubFormat.Data4[3], + (int)in->SubFormat.Data4[4], + (int)in->SubFormat.Data4[5], + (int)in->SubFormat.Data4[6], + (int)in->SubFormat.Data4[7])); + } + PRINT(("Samples.wValidBitsPerSample=%d\n", in->Samples.wValidBitsPerSample)); + PRINT(("dwChannelMask=0x%X\n",in->dwChannelMask)); + }break; + + case WAVE_FORMAT_PCM: PRINT(("wFormatTag=WAVE_FORMAT_PCM\n")); break; + case WAVE_FORMAT_IEEE_FLOAT: PRINT(("wFormatTag=WAVE_FORMAT_IEEE_FLOAT\n")); break; + default : PRINT(("wFormatTag=UNKNOWN(%d)\n",old->wFormatTag)); break; + } + + PRINT(("nChannels =%d\n",old->nChannels)); + PRINT(("nSamplesPerSec =%d\n",old->nSamplesPerSec)); + PRINT(("nAvgBytesPerSec=%d\n",old->nAvgBytesPerSec)); + PRINT(("nBlockAlign =%d\n",old->nBlockAlign)); + PRINT(("wBitsPerSample =%d\n",old->wBitsPerSample)); + PRINT(("cbSize =%d\n",old->cbSize)); +} + + + +/* + WAVEFORMATXXX is always interleaved + */ +static PaSampleFormat +waveformatToPaFormat(const WAVEFORMATEXTENSIBLE *in){ + + const WAVEFORMATEX *old = (WAVEFORMATEX*)in; + + switch (old->wFormatTag){ + + case WAVE_FORMAT_EXTENSIBLE: + { + if (in->SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT){ + if (in->Samples.wValidBitsPerSample == 32) + return paFloat32; + else + return paCustomFormat; + } + else if (in->SubFormat == KSDATAFORMAT_SUBTYPE_PCM){ + switch (old->wBitsPerSample){ + case 32: return paInt32; break; + case 24: return paInt24;break; + case 8: return paUInt8;break; + case 16: return paInt16;break; + default: return paCustomFormat;break; + } + } + else + return paCustomFormat; + } + break; + + case WAVE_FORMAT_IEEE_FLOAT: + return paFloat32; + break; + + case WAVE_FORMAT_PCM: + { + switch (old->wBitsPerSample){ + case 32: return paInt32; break; + case 24: return paInt24;break; + case 8: return paUInt8;break; + case 16: return paInt16;break; + default: return paCustomFormat;break; + } + } + break; + + default: + return paCustomFormat; + break; + } + + return paCustomFormat; +} + + + +static PaError +waveformatFromParams(WAVEFORMATEXTENSIBLE*wavex, + const PaStreamParameters * params, + double sampleRate){ + + size_t bytesPerSample = 0; + switch( params->sampleFormat & ~paNonInterleaved ){ + case paFloat32: + case paInt32: bytesPerSample=4;break; + case paInt16: bytesPerSample=2;break; + case paInt24: bytesPerSample=3;break; + case paInt8: + case paUInt8: bytesPerSample=1;break; + case paCustomFormat: + default: return paSampleFormatNotSupported;break; + } + + memset(wavex,0,sizeof(WAVEFORMATEXTENSIBLE)); + + WAVEFORMATEX *old = (WAVEFORMATEX *)wavex; + old->nChannels = (WORD)params->channelCount; + old->nSamplesPerSec = (DWORD)sampleRate; + old->wBitsPerSample = (WORD)(bytesPerSample*8); + old->nAvgBytesPerSec = (DWORD)(old->nSamplesPerSec * old->nChannels * bytesPerSample); + old->nBlockAlign = (WORD)(old->nChannels * bytesPerSample); + + //WAVEFORMATEX + if (params->channelCount <=2 && (bytesPerSample == 2 || bytesPerSample == 1)){ + old->cbSize = 0; + old->wFormatTag = WAVE_FORMAT_PCM; + } + //WAVEFORMATEXTENSIBLE + else{ + old->wFormatTag = WAVE_FORMAT_EXTENSIBLE; + + old->cbSize = sizeof (WAVEFORMATEXTENSIBLE) - sizeof (WAVEFORMATEX); + + if ((params->sampleFormat & ~paNonInterleaved) == paFloat32) + wavex->SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT; + else + wavex->SubFormat = KSDATAFORMAT_SUBTYPE_PCM; + + wavex->Samples.wValidBitsPerSample = old->wBitsPerSample; //no extra padding! + + switch(params->channelCount){ + case 1: wavex->dwChannelMask = SPEAKER_FRONT_CENTER; break; + case 2: wavex->dwChannelMask = 0x1 | 0x2; break; + case 4: wavex->dwChannelMask = 0x1 | 0x2 | 0x10 | 0x20; break; + case 6: wavex->dwChannelMask = 0x1 | 0x2 | 0x4 | 0x8 | 0x10 | 0x20; break; + case 8: wavex->dwChannelMask = 0x1 | 0x2 | 0x4 | 0x8 | 0x10 | 0x20 | 0x40 | 0x80; break; + default: wavex->dwChannelMask = 0; break; + } + } + + return paNoError; +} + + + + + + +/* +#define paFloat32 ((PaSampleFormat) 0x00000001) +#define paInt32 ((PaSampleFormat) 0x00000002) +#define paInt24 ((PaSampleFormat) 0x00000004) +#define paInt16 ((PaSampleFormat) 0x00000008) +*/ +//lifted from pa_wdmks +static void wasapiFillWFEXT( WAVEFORMATEXTENSIBLE* pwfext, PaSampleFormat sampleFormat, double sampleRate, int channelCount) +{ + PA_DEBUG(( "sampleFormat = %lx\n" , sampleFormat )); + PA_DEBUG(( "sampleRate = %f\n" , sampleRate )); + PA_DEBUG(( "chanelCount = %d\n", channelCount )); + + pwfext->Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE; + pwfext->Format.nChannels = channelCount; + pwfext->Format.nSamplesPerSec = (int)sampleRate; + if(channelCount == 1) + pwfext->dwChannelMask = KSAUDIO_SPEAKER_DIRECTOUT; + else + pwfext->dwChannelMask = KSAUDIO_SPEAKER_STEREO; + if(sampleFormat == paFloat32) + { + pwfext->Format.nBlockAlign = channelCount * 4; + pwfext->Format.wBitsPerSample = 32; + pwfext->Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE)-sizeof(WAVEFORMATEX); + pwfext->Samples.wValidBitsPerSample = 32; + pwfext->SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT; + } + else if(sampleFormat == paInt32) + { + pwfext->Format.nBlockAlign = channelCount * 4; + pwfext->Format.wBitsPerSample = 32; + pwfext->Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE)-sizeof(WAVEFORMATEX); + pwfext->Samples.wValidBitsPerSample = 32; + pwfext->SubFormat = KSDATAFORMAT_SUBTYPE_PCM; + } + else if(sampleFormat == paInt24) + { + pwfext->Format.nBlockAlign = channelCount * 3; + pwfext->Format.wBitsPerSample = 24; + pwfext->Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE)-sizeof(WAVEFORMATEX); + pwfext->Samples.wValidBitsPerSample = 24; + pwfext->SubFormat = KSDATAFORMAT_SUBTYPE_PCM; + } + else if(sampleFormat == paInt16) + { + pwfext->Format.nBlockAlign = channelCount * 2; + pwfext->Format.wBitsPerSample = 16; + pwfext->Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE)-sizeof(WAVEFORMATEX); + pwfext->Samples.wValidBitsPerSample = 16; + pwfext->SubFormat = KSDATAFORMAT_SUBTYPE_PCM; + } + pwfext->Format.nAvgBytesPerSec = pwfext->Format.nSamplesPerSec * pwfext->Format.nBlockAlign; +} + + + +/* +#define FORMATTESTS 4 +const int BestToWorst[FORMATTESTS]={paFloat32,paInt32,paInt24,paInt16}; +*/ + +#define FORMATTESTS 3 +const int BestToWorst[FORMATTESTS]={paFloat32,paInt24,paInt16}; + + +static PaError +GetClosestFormat(IAudioClient * myClient, double sampleRate,const PaStreamParameters * params, + AUDCLNT_SHAREMODE *shareMode, WAVEFORMATEXTENSIBLE *outWavex) +{ + //TODO we should try exclusive first and shared after + *shareMode = PORTAUDIO_SHAREMODE; + + PaError answer = paInvalidSampleRate; + + waveformatFromParams(outWavex,params,sampleRate); + WAVEFORMATEX *sharedClosestMatch=0; + HRESULT hResult=!S_OK; + + if (*shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE) + hResult = myClient->IsFormatSupported(AUDCLNT_SHAREMODE_EXCLUSIVE,(WAVEFORMATEX*)outWavex,NULL); + else + hResult = myClient->IsFormatSupported(AUDCLNT_SHAREMODE_SHARED, (WAVEFORMATEX*)&outWavex,&sharedClosestMatch); + + if (hResult == S_OK) + answer = paFormatIsSupported; + else if (sharedClosestMatch){ + WAVEFORMATEXTENSIBLE* ext = (WAVEFORMATEXTENSIBLE*)sharedClosestMatch; + + int closestMatchSR = (int)sharedClosestMatch->nSamplesPerSec; + + if (sharedClosestMatch->wFormatTag == WAVE_FORMAT_EXTENSIBLE) + memcpy(outWavex,sharedClosestMatch,sizeof(WAVEFORMATEXTENSIBLE)); + else + memcpy(outWavex,sharedClosestMatch,sizeof(WAVEFORMATEX)); + + CoTaskMemFree(sharedClosestMatch); + + if ((int)sampleRate == closestMatchSR) + answer = paFormatIsSupported; + else + answer = paInvalidSampleRate; + + }else { + + //it doesnt suggest anything?? ok lets show it the MENU! + + //ok fun time as with pa_win_mme, we know only a refusal of the user-requested + //sampleRate+num Channel is disastrous, as the portaudio buffer processor converts between anything + //so lets only use the number + for (int i=0;ichannelCount); + if (*shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE) + hResult = myClient->IsFormatSupported(AUDCLNT_SHAREMODE_EXCLUSIVE,(WAVEFORMATEX*)&ext,NULL); + else + hResult = myClient->IsFormatSupported(AUDCLNT_SHAREMODE_SHARED, (WAVEFORMATEX*)&ext,&sharedClosestMatch); + + if (hResult == S_OK){ + memcpy(outWavex,&ext,sizeof(WAVEFORMATEXTENSIBLE)); + answer = paFormatIsSupported; + break; + } + } + + if (answer!=paFormatIsSupported) { + //try MIX format? + //why did it HAVE to come to this .... + WAVEFORMATEX pcm16WaveFormat; + memset(&pcm16WaveFormat,0,sizeof(WAVEFORMATEX)); + pcm16WaveFormat.wFormatTag = WAVE_FORMAT_PCM; + pcm16WaveFormat.nChannels = 2; + pcm16WaveFormat.nSamplesPerSec = (DWORD)sampleRate; + pcm16WaveFormat.nBlockAlign = 4; + pcm16WaveFormat.nAvgBytesPerSec = pcm16WaveFormat.nSamplesPerSec*pcm16WaveFormat.nBlockAlign; + pcm16WaveFormat.wBitsPerSample = 16; + pcm16WaveFormat.cbSize = 0; + + if (*shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE) + hResult = myClient->IsFormatSupported(AUDCLNT_SHAREMODE_EXCLUSIVE,(WAVEFORMATEX*)&pcm16WaveFormat,NULL); + else + hResult = myClient->IsFormatSupported(AUDCLNT_SHAREMODE_SHARED, (WAVEFORMATEX*)&pcm16WaveFormat,&sharedClosestMatch); + + if (hResult == S_OK){ + memcpy(outWavex,&pcm16WaveFormat,sizeof(WAVEFORMATEX)); + answer = paFormatIsSupported; + } + } + + logAUDCLNT_E(hResult); + } + + return answer; +} + + +static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi, + const PaStreamParameters *inputParameters, + const PaStreamParameters *outputParameters, + double sampleRate ) +{ + + int inputChannelCount, outputChannelCount; + PaSampleFormat inputSampleFormat, outputSampleFormat; + + if( inputParameters ) + { + inputChannelCount = inputParameters->channelCount; + inputSampleFormat = inputParameters->sampleFormat; + + /* all standard sample formats are supported by the buffer adapter, + this implementation doesn't support any custom sample formats */ + if( inputSampleFormat & paCustomFormat ) + return paSampleFormatNotSupported; + + /* unless alternate device specification is supported, reject the use of + paUseHostApiSpecificDeviceSpecification */ + + if( inputParameters->device == paUseHostApiSpecificDeviceSpecification ) + return paInvalidDevice; + + /* check that input device can support inputChannelCount */ + if( inputChannelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels ) + return paInvalidChannelCount; + + /* validate inputStreamInfo */ + if( inputParameters->hostApiSpecificStreamInfo ) + return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */ + + + PaWinWasapiHostApiRepresentation *paWasapi = (PaWinWasapiHostApiRepresentation*)hostApi; + + + IAudioClient *myClient=0; + HRESULT hResult = paWasapi->devInfo[inputParameters->device].device->Activate( + __uuidof(IAudioClient), CLSCTX_INPROC_SERVER, NULL, (void**)&myClient); + if (hResult != S_OK){ + logAUDCLNT_E(hResult); + return paInvalidDevice; + } + + WAVEFORMATEXTENSIBLE wavex; + AUDCLNT_SHAREMODE shareMode; + PaError answer = GetClosestFormat(myClient,sampleRate,inputParameters,&shareMode,&wavex); + myClient->Release(); + + if (answer !=paFormatIsSupported) + return answer; + } + else + { + inputChannelCount = 0; + } + + if( outputParameters ) + { + outputChannelCount = outputParameters->channelCount; + outputSampleFormat = outputParameters->sampleFormat; + + /* all standard sample formats are supported by the buffer adapter, + this implementation doesn't support any custom sample formats */ + if( outputSampleFormat & paCustomFormat ) + return paSampleFormatNotSupported; + + /* unless alternate device specification is supported, reject the use of + paUseHostApiSpecificDeviceSpecification */ + + if( outputParameters->device == paUseHostApiSpecificDeviceSpecification ) + return paInvalidDevice; + + /* check that output device can support outputChannelCount */ + if( outputChannelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels ) + return paInvalidChannelCount; + + /* validate outputStreamInfo */ + if( outputParameters->hostApiSpecificStreamInfo ) + return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */ + + + PaWinWasapiHostApiRepresentation *paWasapi = (PaWinWasapiHostApiRepresentation*)hostApi; + + IAudioClient *myClient=0; + HRESULT hResult = paWasapi->devInfo[outputParameters->device].device->Activate( + __uuidof(IAudioClient), CLSCTX_INPROC_SERVER, NULL, (void**)&myClient); + if (hResult != S_OK){ + logAUDCLNT_E(hResult); + return paInvalidDevice; + } + + WAVEFORMATEXTENSIBLE wavex; + AUDCLNT_SHAREMODE shareMode; + PaError answer = GetClosestFormat(myClient,sampleRate,outputParameters,&shareMode,&wavex); + myClient->Release(); + + if (answer !=paFormatIsSupported) + return answer; + } + else + { + outputChannelCount = 0; + } + + + return paFormatIsSupported; +} + + + +/* see pa_hostapi.h for a list of validity guarantees made about OpenStream parameters */ + +static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi, + PaStream** s, + const PaStreamParameters *inputParameters, + const PaStreamParameters *outputParameters, + double sampleRate, + unsigned long framesPerBuffer, + PaStreamFlags streamFlags, + PaStreamCallback *streamCallback, + void *userData ) +{ + PaError result = paNoError; + PaWinWasapiHostApiRepresentation *paWasapi = (PaWinWasapiHostApiRepresentation*)hostApi; + PaWinWasapiStream *stream = 0; + int inputChannelCount, outputChannelCount; + PaSampleFormat inputSampleFormat, outputSampleFormat; + PaSampleFormat hostInputSampleFormat, hostOutputSampleFormat; + + + stream = (PaWinWasapiStream*)PaUtil_AllocateMemory( sizeof(PaWinWasapiStream) ); + if( !stream ){ + result = paInsufficientMemory; + goto error; + } + + if( inputParameters ) + { + inputChannelCount = inputParameters->channelCount; + inputSampleFormat = inputParameters->sampleFormat; + + /* unless alternate device specification is supported, reject the use of + paUseHostApiSpecificDeviceSpecification */ + + if( inputParameters->device == paUseHostApiSpecificDeviceSpecification ) + return paInvalidDevice; + + /* check that input device can support inputChannelCount */ + if( inputChannelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels ) + return paInvalidChannelCount; + + /* validate inputStreamInfo */ + if( inputParameters->hostApiSpecificStreamInfo ) + return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */ + + + PaWinWasapiDeviceInfo &info = paWasapi->devInfo[inputParameters->device]; + + HRESULT hResult = info.device->Activate( + __uuidof(IAudioClient), CLSCTX_INPROC_SERVER, NULL, + (void**)&stream->in.client); + + if (hResult != S_OK) + return paInvalidDevice; + + hResult = info.device->Activate( + __uuidof(IAudioEndpointVolume), CLSCTX_INPROC_SERVER, NULL, + (void**)&stream->inVol); + + if (hResult != S_OK) + return paInvalidDevice; + + AUDCLNT_SHAREMODE shareMode; + PaError answer = GetClosestFormat(stream->in.client,sampleRate,inputParameters,&shareMode,&stream->in.wavex); + + if (answer !=paFormatIsSupported) + return answer; + + //stream->out.period = info.DefaultDevicePeriod; + stream->in.period = info.MinimumDevicePeriod; + + hResult = stream->in.client->Initialize( + shareMode, + 0, //no flags + stream->in.period, + 0,//stream->out.period, + (WAVEFORMATEX*)&stream->in.wavex, + &stream->session + ); + + if (hResult != S_OK){ + logAUDCLNT_E(hResult); + return paInvalidDevice; + } + + hResult = stream->in.client->GetBufferSize(&stream->in.bufferSize); + if (hResult != S_OK) + return paInvalidDevice; + + hResult = stream->in.client->GetStreamLatency(&stream->in.latency); + if (hResult != S_OK) + return paInvalidDevice; + + double periodsPerSecond = 1.0/nano100ToSeconds(stream->in.period); + double samplesPerPeriod = (double)(stream->in.wavex.Format.nSamplesPerSec)/periodsPerSecond; + + //this is the number of samples that are required at each period + stream->in.framesPerHostCallback = (unsigned long)samplesPerPeriod;//unrelated to channels + + /* IMPLEMENT ME - establish which host formats are available */ + hostInputSampleFormat = + PaUtil_SelectClosestAvailableFormat( waveformatToPaFormat(&stream->in.wavex), inputSampleFormat ); + } + else + { + inputChannelCount = 0; + inputSampleFormat = hostInputSampleFormat = paInt16; /* Surpress 'uninitialised var' warnings. */ + } + + if( outputParameters ) + { + outputChannelCount = outputParameters->channelCount; + outputSampleFormat = outputParameters->sampleFormat; + + /* unless alternate device specification is supported, reject the use of + paUseHostApiSpecificDeviceSpecification */ + + if( outputParameters->device == paUseHostApiSpecificDeviceSpecification ) + return paInvalidDevice; + + /* check that output device can support inputChannelCount */ + if( outputChannelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels ) + return paInvalidChannelCount; + + /* validate outputStreamInfo */ + if( outputParameters->hostApiSpecificStreamInfo ) + return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */ + + + PaWinWasapiDeviceInfo &info = paWasapi->devInfo[outputParameters->device]; + + HRESULT hResult = info.device->Activate( + __uuidof(IAudioClient), CLSCTX_INPROC_SERVER, NULL, + (void**)&stream->out.client); + + if (hResult != S_OK) + return paInvalidDevice; + + AUDCLNT_SHAREMODE shareMode; + PaError answer = GetClosestFormat(stream->out.client,sampleRate,outputParameters,&shareMode,&stream->out.wavex); + + if (answer !=paFormatIsSupported) + return answer; + LogWAVEFORMATEXTENSIBLE(&stream->out.wavex); + + // stream->out.period = info.DefaultDevicePeriod; + stream->out.period = info.MinimumDevicePeriod; + + /*For an exclusive-mode stream that uses event-driven buffering, + the caller must specify nonzero values for hnsPeriodicity and hnsBufferDuration, + and the values of these two parameters must be equal */ + if (shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE){ + hResult = stream->out.client->Initialize( + shareMode, + AUDCLNT_STREAMFLAGS_EVENTCALLBACK, + stream->out.period, + stream->out.period, + (WAVEFORMATEX*)&stream->out.wavex, + &stream->session + ); + } + else{ + hResult = stream->out.client->Initialize( + shareMode, + AUDCLNT_STREAMFLAGS_EVENTCALLBACK, + 0, + 0, + (WAVEFORMATEX*)&stream->out.wavex, + &stream->session + ); + } + + + if (hResult != S_OK){ + logAUDCLNT_E(hResult); + return paInvalidDevice; + } + + hResult = info.device->Activate( + __uuidof(IAudioEndpointVolume), CLSCTX_INPROC_SERVER, NULL, + (void**)&stream->outVol); + + if (hResult != S_OK) + return paInvalidDevice; + + hResult = stream->out.client->GetBufferSize(&stream->out.bufferSize); + if (hResult != S_OK) + return paInvalidDevice; + + hResult = stream->out.client->GetStreamLatency(&stream->out.latency); + if (hResult != S_OK) + return paInvalidDevice; + + double periodsPerSecond = 1.0/nano100ToSeconds(stream->out.period); + double samplesPerPeriod = (double)(stream->out.wavex.Format.nSamplesPerSec)/periodsPerSecond; + + //this is the number of samples that are required at each period + stream->out.framesPerHostCallback = stream->out.bufferSize; //(unsigned long)samplesPerPeriod;//unrelated to channels + + /* IMPLEMENT ME - establish which host formats are available */ + hostOutputSampleFormat = PaUtil_SelectClosestAvailableFormat( waveformatToPaFormat(&stream->out.wavex), outputSampleFormat ); + } + else + { + outputChannelCount = 0; + outputSampleFormat = hostOutputSampleFormat = paInt16; /* Surpress 'uninitialized var' warnings. */ + } + + + + /* + IMPLEMENT ME: + + ( the following two checks are taken care of by PaUtil_InitializeBufferProcessor() FIXME - checks needed? ) + + - check that input device can support inputSampleFormat, or that + we have the capability to convert from outputSampleFormat to + a native format + + - check that output device can support outputSampleFormat, or that + we have the capability to convert from outputSampleFormat to + a native format + + - if a full duplex stream is requested, check that the combination + of input and output parameters is supported + + - check that the device supports sampleRate + + - alter sampleRate to a close allowable rate if possible / necessary + + - validate suggestedInputLatency and suggestedOutputLatency parameters, + use default values where necessary + */ + + + + /* validate platform specific flags */ + if( (streamFlags & paPlatformSpecificFlags) != 0 ) + return paInvalidFlag; /* unexpected platform specific flag */ + + + + if( streamCallback ) + { + PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation, + &paWasapi->callbackStreamInterface, streamCallback, userData ); + } + else + { + PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation, + &paWasapi->blockingStreamInterface, streamCallback, userData ); + } + + PaUtil_InitializeCpuLoadMeasurer( &stream->cpuLoadMeasurer, sampleRate ); + + + if (outputParameters && inputParameters){ + + //serious problem #1 + if (stream->in.period != stream->out.period){ + PRINT(("OpenStream: period discrepancy\n")); + goto error; + } + + //serious problem #2 + if (stream->out.framesPerHostCallback != stream->in.framesPerHostCallback){ + PRINT(("OpenStream: framesPerHostCallback discrepancy\n")); + goto error; + } + } + + unsigned long framesPerHostCallback = (outputParameters)? + stream->out.framesPerHostCallback: + stream->in.framesPerHostCallback; + + /* we assume a fixed host buffer size in this example, but the buffer processor + can also support bounded and unknown host buffer sizes by passing + paUtilBoundedHostBufferSize or paUtilUnknownHostBufferSize instead of + paUtilFixedHostBufferSize below. */ + + result = PaUtil_InitializeBufferProcessor( &stream->bufferProcessor, + inputChannelCount, inputSampleFormat, hostInputSampleFormat, + outputChannelCount, outputSampleFormat, hostOutputSampleFormat, + sampleRate, streamFlags, framesPerBuffer, + framesPerHostCallback, paUtilFixedHostBufferSize, + streamCallback, userData ); + if( result != paNoError ) + goto error; + + + /* + IMPLEMENT ME: initialise the following fields with estimated or actual + values. + */ + stream->streamRepresentation.streamInfo.inputLatency = + PaUtil_GetBufferProcessorInputLatency(&stream->bufferProcessor) + + ((inputParameters)?nano100ToSeconds(stream->in.latency) :0); + + stream->streamRepresentation.streamInfo.outputLatency = + PaUtil_GetBufferProcessorOutputLatency(&stream->bufferProcessor) + + ((outputParameters)?nano100ToSeconds(stream->out.latency) :0); + + stream->streamRepresentation.streamInfo.sampleRate = sampleRate; + + + *s = (PaStream*)stream; + + + return result; + +error: + if( stream ) + PaUtil_FreeMemory( stream ); + + return result; +} + + + +/* + When CloseStream() is called, the multi-api layer ensures that + the stream has already been stopped or aborted. +*/ + +#define SAFE_RELEASE(punk) \ + if ((punk) != NULL) \ + { (punk)->Release(); (punk) = NULL; } + +static PaError CloseStream( PaStream* s ) +{ + PaError result = paNoError; + PaWinWasapiStream *stream = (PaWinWasapiStream*)s; + + /* + IMPLEMENT ME: + - additional stream closing + cleanup + */ + + SAFE_RELEASE(stream->out.client); + SAFE_RELEASE(stream->in.client); + SAFE_RELEASE(stream->cclient); + SAFE_RELEASE(stream->rclient); + SAFE_RELEASE(stream->inVol); + SAFE_RELEASE(stream->outVol); + CloseHandle(stream->hThread); + CloseHandle(stream->hNotificationEvent); + + PaUtil_TerminateBufferProcessor( &stream->bufferProcessor ); + PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation ); + PaUtil_FreeMemory( stream ); + + return result; +} + +DWORD WINAPI ProcThread(void *client); + +static PaError StartStream( PaStream *s ) +{ + PaError result = paNoError; + PaWinWasapiStream *stream = (PaWinWasapiStream*)s; + + PaUtil_ResetBufferProcessor( &stream->bufferProcessor ); + + HRESULT hResult=S_OK; + + if (stream->out.client){ + hResult = stream->out.client->GetService(__uuidof(IAudioRenderClient),(void**)&stream->rclient); + logAUDCLNT_E(hResult); + if (hResult!=S_OK) + return paUnanticipatedHostError; + } + + if (stream->in.client){ + hResult = stream->in.client->GetService(__uuidof(IAudioCaptureClient),(void**)&stream->cclient); + logAUDCLNT_E(hResult); + if (hResult!=S_OK) + return paUnanticipatedHostError; + } + + // Create a thread for this client. + stream->hThread = CreateThread( + NULL, // no security attribute + 0, // default stack size + ProcThread, + (LPVOID) stream, // thread parameter + 0, // not suspended + &stream->dwThreadId); // returns thread ID + + if (stream->hThread == NULL) + return paUnanticipatedHostError; + + return paNoError; +} + + +static PaError StopStream( PaStream *s ) +{ + PaError result = paNoError; + PaWinWasapiStream *stream = (PaWinWasapiStream*)s; + + /* suppress unused variable warnings */ + stream->closeRequest = true; + //todo something MUCH better than this + while(stream->closeRequest) + Sleep(100); + + /* IMPLEMENT ME, see portaudio.h for required behavior */ + + stream->running = false; + + return result; +} + + +static PaError AbortStream( PaStream *s ) +{ + PaError result = paNoError; + PaWinWasapiStream *stream = (PaWinWasapiStream*)s; + + /* suppress unused variable warnings */ + stream->closeRequest = true; + //todo something MUCH better than this + while(stream->closeRequest) + Sleep(100); + + /* IMPLEMENT ME, see portaudio.h for required behavior */ + + return result; +} + + +static PaError IsStreamStopped( PaStream *s ) +{ + PaWinWasapiStream *stream = (PaWinWasapiStream*)s; + + return !stream->running; +} + + +static PaError IsStreamActive( PaStream *s ) +{ + PaWinWasapiStream *stream = (PaWinWasapiStream*)s; + return stream->running; +} + + +static PaTime GetStreamTime( PaStream *s ) +{ + PaWinWasapiStream *stream = (PaWinWasapiStream*)s; + + /* suppress unused variable warnings */ + (void) stream; + + /* IMPLEMENT ME, see portaudio.h for required behavior*/ + + //this is lame ds and mme does the same thing, quite useless method imho + //why dont we fetch the time in the pa callbacks? + //at least its doing to be clocked to something + return PaUtil_GetTime(); +} + + +static double GetStreamCpuLoad( PaStream* s ) +{ + PaWinWasapiStream *stream = (PaWinWasapiStream*)s; + + return PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer ); +} + + +/* + As separate stream interfaces are used for blocking and callback + streams, the following functions can be guaranteed to only be called + for blocking streams. +*/ + +static PaError ReadStream( PaStream* s, + void *buffer, + unsigned long frames ) +{ + PaWinWasapiStream *stream = (PaWinWasapiStream*)s; + + /* suppress unused variable warnings */ + (void) buffer; + (void) frames; + (void) stream; + + /* IMPLEMENT ME, see portaudio.h for required behavior*/ + + return paNoError; +} + + +static PaError WriteStream( PaStream* s, + const void *buffer, + unsigned long frames ) +{ + PaWinWasapiStream *stream = (PaWinWasapiStream*)s; + + /* suppress unused variable warnings */ + (void) buffer; + (void) frames; + (void) stream; + + /* IMPLEMENT ME, see portaudio.h for required behavior*/ + + return paNoError; +} + + +static signed long GetStreamReadAvailable( PaStream* s ) +{ + PaWinWasapiStream *stream = (PaWinWasapiStream*)s; + + /* suppress unused variable warnings */ + (void) stream; + + /* IMPLEMENT ME, see portaudio.h for required behavior*/ + + return 0; +} + + +static signed long GetStreamWriteAvailable( PaStream* s ) +{ + PaWinWasapiStream *stream = (PaWinWasapiStream*)s; + + /* suppress unused variable warnings */ + (void) stream; + + /* IMPLEMENT ME, see portaudio.h for required behavior*/ + + return 0; +} + + + +/* + ExampleHostProcessingLoop() illustrates the kind of processing which may + occur in a host implementation. + +*/ +static void WaspiHostProcessingLoop( void *inputBuffer, long inputFrames, + void *outputBuffer, long outputFrames, + void *userData ) +{ + PaWinWasapiStream *stream = (PaWinWasapiStream*)userData; + PaStreamCallbackTimeInfo timeInfo = {0,0,0}; /* IMPLEMENT ME */ + int callbackResult; + unsigned long framesProcessed; + + PaUtil_BeginCpuLoadMeasurement( &stream->cpuLoadMeasurer ); + + + /* + IMPLEMENT ME: + - generate timing information + - handle buffer slips + */ + + /* + If you need to byte swap or shift inputBuffer to convert it into a + portaudio format, do it here. + */ + + + + PaUtil_BeginBufferProcessing( &stream->bufferProcessor, &timeInfo, 0 /* IMPLEMENT ME: pass underflow/overflow flags when necessary */ ); + + /* + depending on whether the host buffers are interleaved, non-interleaved + or a mixture, you will want to call PaUtil_SetInterleaved*Channels(), + PaUtil_SetNonInterleaved*Channel() or PaUtil_Set*Channel() here. + */ + + if( stream->bufferProcessor.inputChannelCount > 0 ) + { + PaUtil_SetInputFrameCount( &stream->bufferProcessor, inputFrames ); + PaUtil_SetInterleavedInputChannels( &stream->bufferProcessor, + 0, /* first channel of inputBuffer is channel 0 */ + inputBuffer, + 0 ); /* 0 - use inputChannelCount passed to init buffer processor */ + } + + if( stream->bufferProcessor.outputChannelCount > 0 ) + { + PaUtil_SetOutputFrameCount( &stream->bufferProcessor, outputFrames); + PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor, + 0, /* first channel of outputBuffer is channel 0 */ + outputBuffer, + 0 ); /* 0 - use outputChannelCount passed to init buffer processor */ + } + + /* you must pass a valid value of callback result to PaUtil_EndBufferProcessing() + in general you would pass paContinue for normal operation, and + paComplete to drain the buffer processor's internal output buffer. + You can check whether the buffer processor's output buffer is empty + using PaUtil_IsBufferProcessorOuputEmpty( bufferProcessor ) + */ + callbackResult = paContinue; + framesProcessed = PaUtil_EndBufferProcessing( &stream->bufferProcessor, &callbackResult ); + + + /* + If you need to byte swap or shift outputBuffer to convert it to + host format, do it here. + */ + + PaUtil_EndCpuLoadMeasurement( &stream->cpuLoadMeasurer, framesProcessed ); + + + if( callbackResult == paContinue ) + { + /* nothing special to do */ + } + else if( callbackResult == paAbort ) + { + /* IMPLEMENT ME - finish playback immediately */ + + /* once finished, call the finished callback */ + if( stream->streamRepresentation.streamFinishedCallback != 0 ) + stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData ); + } + else + { + /* User callback has asked us to stop with paComplete or other non-zero value */ + + /* IMPLEMENT ME - finish playback once currently queued audio has completed */ + + /* once finished, call the finished callback */ + if( stream->streamRepresentation.streamFinishedCallback != 0 ) + stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData ); + } +} + + +void +MMCSS_activate(){ + + DWORD stuff=0; + HANDLE thCarac = pAvSetMmThreadCharacteristics("Pro Audio",&stuff); + if (!thCarac){ + PRINT(("AvSetMmThreadCharacteristics failed!\n")); + } + + BOOL prio = pAvSetMmThreadPriority(thCarac,AVRT_PRIORITY_NORMAL); + if (!prio){ + PRINT(("AvSetMmThreadPriority failed!\n")); + } + + //debug + { + HANDLE hh = GetCurrentThread(); + int currprio = GetThreadPriority(hh); + DWORD currclass = GetPriorityClass(GetCurrentProcess()); + PRINT(("currprio 0x%X currclass 0x%X\n",currprio,currclass)); + } +} + + +DWORD WINAPI +ProcThread(void* param){ + HRESULT hResult; + MMCSS_activate(); + + PaWinWasapiStream *stream = (PaWinWasapiStream*)param; + + stream->hNotificationEvent = CreateEvent(NULL, + FALSE, //bManualReset are we sure?? + FALSE, + "PAWASA"); + hResult = stream->out.client->SetEventHandle(stream->hNotificationEvent); + if (hResult != S_OK) + logAUDCLNT_E(hResult); + + if (stream->out.client){ + hResult = stream->out.client->Start(); + if (hResult != S_OK) + logAUDCLNT_E(hResult); + } + + stream->running = true; + bool bOne = false; + + while( !stream->closeRequest ) + { + //lets wait but have a 1 second timeout + DWORD dwResult = WaitForSingleObject(stream->hNotificationEvent, 1000); + switch( dwResult ) { + case WAIT_OBJECT_0: { + + unsigned long usingBS = stream->out.framesPerHostCallback; + + BYTE* indata = 0; + BYTE* outdata = 0; + + hResult = stream->rclient->GetBuffer(usingBS, &outdata); + + if (hResult != S_OK || !outdata) { + //logAUDCLNT_E(hResult); + //most probably shared mode and hResult=AUDCLNT_E_BUFFER_TOO_LARGE + UINT32 padding = 0; + hResult = stream->out.client->GetCurrentPadding(&padding); + if (padding == 0) + break; + usingBS = usingBS-padding; + if (usingBS == 0) + break;//huh? + hResult = stream->rclient->GetBuffer(usingBS, &outdata); + if (hResult != S_OK)//what can we do NOW?? + break; + //logAUDCLNT_E(hResult); + } + + WaspiHostProcessingLoop(indata, usingBS ,outdata, usingBS, stream); + + hResult = stream->rclient->ReleaseBuffer(usingBS, 0); + if (hResult != S_OK) + logAUDCLNT_E(hResult); + + /* This was suggested, but in my tests it doesnt seem to improve the + locking behaviour some drivers have running in exclusive mode. + if(!ResetEvent(stream->hNotificationEvent)){ + logAUDCLNT_E(hResult); + } + */ + + } + break; + + } + } + stream->out.client->Stop(); + stream->closeRequest = false; + + return 0; +} + + + + +#endif //VC 2005 + + + + +#if 0 + if(bFirst) { + float masteur; + hResult = stream->outVol->GetMasterVolumeLevelScalar(&masteur); + if (hResult != S_OK) + logAUDCLNT_E(hResult); + float chan1, chan2; + hResult = stream->outVol->GetChannelVolumeLevelScalar(0, &chan1); + if (hResult != S_OK) + logAUDCLNT_E(hResult); + hResult = stream->outVol->GetChannelVolumeLevelScalar(1, &chan2); + if (hResult != S_OK) + logAUDCLNT_E(hResult); + + BOOL bMute; + hResult = stream->outVol->GetMute(&bMute); + if (hResult != S_OK) + logAUDCLNT_E(hResult); + + stream->outVol->SetMasterVolumeLevelScalar(0.5, NULL); + stream->outVol->SetChannelVolumeLevelScalar(0, 0.5, NULL); + stream->outVol->SetChannelVolumeLevelScalar(1, 0.5, NULL); + stream->outVol->SetMute(FALSE, NULL); + bFirst = false; + } +#endif \ No newline at end of file From sumomo @ users.sourceforge.jp Sat Feb 5 18:00:02 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Sat, 05 Feb 2011 18:00:02 +0900 Subject: [Julius-cvs 588] CVS update: julius4/libsent/src/adin/pa/hostapi/alsa Message-ID: <1296896402.334045.28202.nullmailer@users.sourceforge.jp> Index: julius4/libsent/src/adin/pa/hostapi/alsa/pa_linux_alsa.c diff -u /dev/null julius4/libsent/src/adin/pa/hostapi/alsa/pa_linux_alsa.c:1.1 --- /dev/null Sat Feb 5 18:00:02 2011 +++ julius4/libsent/src/adin/pa/hostapi/alsa/pa_linux_alsa.c Sat Feb 5 18:00:02 2011 @@ -0,0 +1,3563 @@ +/* + * $Id: pa_linux_alsa.c,v 1.1 2011/02/05 09:00:02 sumomo Exp $ + * PortAudio Portable Real-Time Audio Library + * Latest Version at: http://www.portaudio.com + * ALSA implementation by Joshua Haberman and Arve Knudsen + * + * Copyright (c) 2002 Joshua Haberman + * Copyright (c) 2005-2007 Arve Knudsen + * + * Based on the Open Source API proposed by Ross Bencina + * Copyright (c) 1999-2002 Ross Bencina, Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/* + * The text above constitutes the entire PortAudio license; however, + * the PortAudio community also makes the following non-binding requests: + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. It is also + * requested that these non-binding requests be included along with the + * license above. + */ + +/** + @file + @ingroup hostapi_src +*/ + +#define ALSA_PCM_NEW_HW_PARAMS_API +#define ALSA_PCM_NEW_SW_PARAMS_API +#include +#undef ALSA_PCM_NEW_HW_PARAMS_API +#undef ALSA_PCM_NEW_SW_PARAMS_API + +#include +#include /* strlen() */ +#include +#include +#include +#include +#include +#include +#include /* For sig_atomic_t */ + +#include "portaudio.h" +#include "pa_util.h" +#include "pa_unix_util.h" +#include "pa_allocation.h" +#include "pa_hostapi.h" +#include "pa_stream.h" +#include "pa_cpuload.h" +#include "pa_process.h" +#include "pa_endianness.h" +#include "pa_debugprint.h" + +#include "pa_linux_alsa.h" + +/* Check return value of ALSA function, and map it to PaError */ +#define ENSURE_(expr, code) \ + do { \ + if( UNLIKELY( (aErr_ = (expr)) < 0 ) ) \ + { \ + /* PaUtil_SetLastHostErrorInfo should only be used in the main thread */ \ + if( (code) == paUnanticipatedHostError && pthread_equal( pthread_self(), paUnixMainThread) ) \ + { \ + PaUtil_SetLastHostErrorInfo( paALSA, aErr_, snd_strerror( aErr_ ) ); \ + } \ + PaUtil_DebugPrint( "Expression '" #expr "' failed in '" __FILE__ "', line: " STRINGIZE( __LINE__ ) "\n" ); \ + if( (code) == paUnanticipatedHostError ) \ + PA_DEBUG(( "Host error description: %s\n", snd_strerror( aErr_ ) )); \ + result = (code); \ + goto error; \ + } \ + } while( 0 ); + +#define ASSERT_CALL_(expr, success) \ + aErr_ = (expr); \ + assert( success == aErr_ ); + +static int aErr_; /* Used with ENSURE_ */ +static int numPeriods_ = 4; + +int PaAlsa_SetNumPeriods( int numPeriods ) +{ + numPeriods_ = numPeriods; + return paNoError; +} + +typedef enum +{ + StreamDirection_In, + StreamDirection_Out +} StreamDirection; + +typedef struct +{ + PaSampleFormat hostSampleFormat; + unsigned long framesPerBuffer; + int numUserChannels, numHostChannels; + int userInterleaved, hostInterleaved; + PaDeviceIndex device; /* Keep the device index */ + + snd_pcm_t *pcm; + snd_pcm_uframes_t bufferSize; + snd_pcm_format_t nativeFormat; + unsigned int nfds; + int ready; /* Marked ready from poll */ + void **userBuffers; + snd_pcm_uframes_t offset; + StreamDirection streamDir; + + snd_pcm_channel_area_t *channelAreas; /* Needed for channel adaption */ +} PaAlsaStreamComponent; + +/* Implementation specific stream structure */ +typedef struct PaAlsaStream +{ + PaUtilStreamRepresentation streamRepresentation; + PaUtilCpuLoadMeasurer cpuLoadMeasurer; + PaUtilBufferProcessor bufferProcessor; + PaUnixThread thread; + + unsigned long framesPerUserBuffer, maxFramesPerHostBuffer; + + int primeBuffers; + int callbackMode; /* bool: are we running in callback mode? */ + int pcmsSynced; /* Have we successfully synced pcms */ + int rtSched; + + /* the callback thread uses these to poll the sound device(s), waiting + * for data to be ready/available */ + struct pollfd* pfds; + int pollTimeout; + + /* Used in communication between threads */ + volatile sig_atomic_t callback_finished; /* bool: are we in the "callback finished" state? */ + volatile sig_atomic_t callbackAbort; /* Drop frames? */ + volatile sig_atomic_t isActive; /* Is stream in active state? (Between StartStream and StopStream || !paContinue) */ + PaUnixMutex stateMtx; /* Used to synchronize access to stream state */ + + int neverDropInput; + + PaTime underrun; + PaTime overrun; + + PaAlsaStreamComponent capture, playback; +} +PaAlsaStream; + +/* PaAlsaHostApiRepresentation - host api datastructure specific to this implementation */ + +typedef struct PaAlsaHostApiRepresentation +{ + PaUtilHostApiRepresentation baseHostApiRep; + PaUtilStreamInterface callbackStreamInterface; + PaUtilStreamInterface blockingStreamInterface; + + PaUtilAllocationGroup *allocations; + + PaHostApiIndex hostApiIndex; +} +PaAlsaHostApiRepresentation; + +typedef struct PaAlsaDeviceInfo +{ + PaDeviceInfo baseDeviceInfo; + char *alsaName; + int isPlug; + int minInputChannels; + int minOutputChannels; +} +PaAlsaDeviceInfo; + +/* prototypes for functions declared in this file */ + +static void Terminate( struct PaUtilHostApiRepresentation *hostApi ); +static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi, + const PaStreamParameters *inputParameters, + const PaStreamParameters *outputParameters, + double sampleRate ); +static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi, + PaStream** s, + const PaStreamParameters *inputParameters, + const PaStreamParameters *outputParameters, + double sampleRate, + unsigned long framesPerBuffer, + PaStreamFlags streamFlags, + PaStreamCallback *callback, + void *userData ); +static PaError CloseStream( PaStream* stream ); +static PaError StartStream( PaStream *stream ); +static PaError StopStream( PaStream *stream ); +static PaError AbortStream( PaStream *stream ); +static PaError IsStreamStopped( PaStream *s ); +static PaError IsStreamActive( PaStream *stream ); +static PaTime GetStreamTime( PaStream *stream ); +static double GetStreamCpuLoad( PaStream* stream ); +static PaError BuildDeviceList( PaAlsaHostApiRepresentation *hostApi ); +static int SetApproximateSampleRate( snd_pcm_t *pcm, snd_pcm_hw_params_t *hwParams, double sampleRate ); +static int GetExactSampleRate( snd_pcm_hw_params_t *hwParams, double *sampleRate ); + +/* Callback prototypes */ +static void *CallbackThreadFunc( void *userData ); + +/* Blocking prototypes */ +static signed long GetStreamReadAvailable( PaStream* s ); +static signed long GetStreamWriteAvailable( PaStream* s ); +static PaError ReadStream( PaStream* stream, void *buffer, unsigned long frames ); +static PaError WriteStream( PaStream* stream, const void *buffer, unsigned long frames ); + + +static const PaAlsaDeviceInfo *GetDeviceInfo( const PaUtilHostApiRepresentation *hostApi, int device ) +{ + return (const PaAlsaDeviceInfo *)hostApi->deviceInfos[device]; +} + +static void AlsaErrorHandler(const char *file, int line, const char *function, int err, const char *fmt, ...) +{ +} + +PaError PaAlsa_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex ) +{ + PaError result = paNoError; + PaAlsaHostApiRepresentation *alsaHostApi = NULL; + + PA_UNLESS( alsaHostApi = (PaAlsaHostApiRepresentation*) PaUtil_AllocateMemory( + sizeof(PaAlsaHostApiRepresentation) ), paInsufficientMemory ); + PA_UNLESS( alsaHostApi->allocations = PaUtil_CreateAllocationGroup(), paInsufficientMemory ); + alsaHostApi->hostApiIndex = hostApiIndex; + + *hostApi = (PaUtilHostApiRepresentation*)alsaHostApi; + (*hostApi)->info.structVersion = 1; + (*hostApi)->info.type = paALSA; + (*hostApi)->info.name = "ALSA"; + + (*hostApi)->Terminate = Terminate; + (*hostApi)->OpenStream = OpenStream; + (*hostApi)->IsFormatSupported = IsFormatSupported; + + ENSURE_( snd_lib_error_set_handler(AlsaErrorHandler), paUnanticipatedHostError ); + + PA_ENSURE( BuildDeviceList( alsaHostApi ) ); + + PaUtil_InitializeStreamInterface( &alsaHostApi->callbackStreamInterface, + CloseStream, StartStream, + StopStream, AbortStream, + IsStreamStopped, IsStreamActive, + GetStreamTime, GetStreamCpuLoad, + PaUtil_DummyRead, PaUtil_DummyWrite, + PaUtil_DummyGetReadAvailable, + PaUtil_DummyGetWriteAvailable ); + + PaUtil_InitializeStreamInterface( &alsaHostApi->blockingStreamInterface, + CloseStream, StartStream, + StopStream, AbortStream, + IsStreamStopped, IsStreamActive, + GetStreamTime, PaUtil_DummyGetCpuLoad, + ReadStream, WriteStream, + GetStreamReadAvailable, + GetStreamWriteAvailable ); + + PA_ENSURE( PaUnixThreading_Initialize() ); + + return result; + +error: + if( alsaHostApi ) + { + if( alsaHostApi->allocations ) + { + PaUtil_FreeAllAllocations( alsaHostApi->allocations ); + PaUtil_DestroyAllocationGroup( alsaHostApi->allocations ); + } + + PaUtil_FreeMemory( alsaHostApi ); + } + + return result; +} + +static void Terminate( struct PaUtilHostApiRepresentation *hostApi ) +{ + PaAlsaHostApiRepresentation *alsaHostApi = (PaAlsaHostApiRepresentation*)hostApi; + + assert( hostApi ); + + if( alsaHostApi->allocations ) + { + PaUtil_FreeAllAllocations( alsaHostApi->allocations ); + PaUtil_DestroyAllocationGroup( alsaHostApi->allocations ); + } + + PaUtil_FreeMemory( alsaHostApi ); + snd_config_update_free_global(); +} + +/** Determine max channels and default latencies. + * + * This function provides functionality to grope an opened (might be opened for capture or playback) pcm device for + * traits like max channels, suitable default latencies and default sample rate. Upon error, max channels is set to zero, + * and a suitable result returned. The device is closed before returning. + */ +static PaError GropeDevice( snd_pcm_t* pcm, int isPlug, StreamDirection mode, int openBlocking, + PaAlsaDeviceInfo* devInfo, int* canMmap ) +{ + PaError result = paNoError; + snd_pcm_hw_params_t *hwParams; + snd_pcm_uframes_t lowLatency = 512, highLatency = 2048; + unsigned int minChans, maxChans; + int* minChannels, * maxChannels; + double * defaultLowLatency, * defaultHighLatency, * defaultSampleRate = + &devInfo->baseDeviceInfo.defaultSampleRate; + double defaultSr = *defaultSampleRate; + + assert( pcm ); + + if( StreamDirection_In == mode ) + { + minChannels = &devInfo->minInputChannels; + maxChannels = &devInfo->baseDeviceInfo.maxInputChannels; + defaultLowLatency = &devInfo->baseDeviceInfo.defaultLowInputLatency; + defaultHighLatency = &devInfo->baseDeviceInfo.defaultHighInputLatency; + } + else + { + minChannels = &devInfo->minOutputChannels; + maxChannels = &devInfo->baseDeviceInfo.maxOutputChannels; + defaultLowLatency = &devInfo->baseDeviceInfo.defaultLowOutputLatency; + defaultHighLatency = &devInfo->baseDeviceInfo.defaultHighOutputLatency; + } + + ENSURE_( snd_pcm_nonblock( pcm, 0 ), paUnanticipatedHostError ); + + snd_pcm_hw_params_alloca( &hwParams ); + snd_pcm_hw_params_any( pcm, hwParams ); + + *canMmap = snd_pcm_hw_params_test_access( pcm, hwParams, SND_PCM_ACCESS_MMAP_INTERLEAVED ) >= 0 || + snd_pcm_hw_params_test_access( pcm, hwParams, SND_PCM_ACCESS_MMAP_NONINTERLEAVED ) >= 0; + + if( defaultSr >= 0 ) + { + /* Could be that the device opened in one mode supports samplerates that the other mode wont have, + * so try again .. */ + if( SetApproximateSampleRate( pcm, hwParams, defaultSr ) < 0 ) + { + defaultSr = -1.; + PA_DEBUG(( "%s: Original default samplerate failed, trying again ..\n", __FUNCTION__ )); + } + } + + if( defaultSr < 0. ) /* Default sample rate not set */ + { + unsigned int sampleRate = 44100; /* Will contain approximate rate returned by alsa-lib */ + if( snd_pcm_hw_params_set_rate_near( pcm, hwParams, &sampleRate, NULL ) < 0) + { + result = paUnanticipatedHostError; + goto error; + } + ENSURE_( GetExactSampleRate( hwParams, &defaultSr ), paUnanticipatedHostError ); + } + + ENSURE_( snd_pcm_hw_params_get_channels_min( hwParams, &minChans ), paUnanticipatedHostError ); + ENSURE_( snd_pcm_hw_params_get_channels_max( hwParams, &maxChans ), paUnanticipatedHostError ); + assert( maxChans <= INT_MAX ); + assert( maxChans > 0 ); /* Weird linking issue could cause wrong version of ALSA symbols to be called, + resulting in zeroed values */ + + /* XXX: Limit to sensible number (ALSA plugins accept a crazy amount of channels)? */ + if( isPlug && maxChans > 128 ) + { + maxChans = 128; + PA_DEBUG(( "%s: Limiting number of plugin channels to %u\n", __FUNCTION__, maxChans )); + } + + /* TWEAKME: + * + * Giving values for default min and max latency is not + * straightforward. Here are our objectives: + * + * * for low latency, we want to give the lowest value + * that will work reliably. This varies based on the + * sound card, kernel, CPU, etc. I think it is better + * to give sub-optimal latency than to give a number + * too low and cause dropouts. My conservative + * estimate at this point is to base it on 4096-sample + * latency at 44.1 kHz, which gives a latency of 23ms. + * * for high latency we want to give a large enough + * value that dropouts are basically impossible. This + * doesn't really require as much tweaking, since + * providing too large a number will just cause us to + * select the nearest setting that will work at stream + * config time. + */ + ENSURE_( snd_pcm_hw_params_set_buffer_size_near( pcm, hwParams, &lowLatency ), paUnanticipatedHostError ); + + /* Have to reset hwParams, to set new buffer size */ + ENSURE_( snd_pcm_hw_params_any( pcm, hwParams ), paUnanticipatedHostError ); + ENSURE_( snd_pcm_hw_params_set_buffer_size_near( pcm, hwParams, &highLatency ), paUnanticipatedHostError ); + + *minChannels = (int)minChans; + *maxChannels = (int)maxChans; + *defaultSampleRate = defaultSr; + *defaultLowLatency = (double) lowLatency / *defaultSampleRate; + *defaultHighLatency = (double) highLatency / *defaultSampleRate; + +end: + snd_pcm_close( pcm ); + return result; + +error: + goto end; +} + +/* Initialize device info with invalid values (maxInputChannels and maxOutputChannels are set to zero since these indicate + * wether input/output is available) */ +static void InitializeDeviceInfo( PaDeviceInfo *deviceInfo ) +{ + deviceInfo->structVersion = -1; + deviceInfo->name = NULL; + deviceInfo->hostApi = -1; + deviceInfo->maxInputChannels = 0; + deviceInfo->maxOutputChannels = 0; + deviceInfo->defaultLowInputLatency = -1.; + deviceInfo->defaultLowOutputLatency = -1.; + deviceInfo->defaultHighInputLatency = -1.; + deviceInfo->defaultHighOutputLatency = -1.; + deviceInfo->defaultSampleRate = -1.; +} + +/* Helper struct */ +typedef struct +{ + char *alsaName; + char *name; + int isPlug; + int hasPlayback; + int hasCapture; +} HwDevInfo; + + +HwDevInfo predefinedNames[] = { + { "center_lfe", NULL, 0, 1, 0 }, +/* { "default", NULL, 0, 1, 0 }, */ +/* { "dmix", NULL, 0, 1, 0 }, */ +/* { "dpl", NULL, 0, 1, 0 }, */ +/* { "dsnoop", NULL, 0, 1, 0 }, */ + { "front", NULL, 0, 1, 0 }, + { "iec958", NULL, 0, 1, 0 }, +/* { "modem", NULL, 0, 1, 0 }, */ + { "rear", NULL, 0, 1, 0 }, + { "side", NULL, 0, 1, 0 }, +/* { "spdif", NULL, 0, 0, 0 }, */ + { "surround40", NULL, 0, 1, 0 }, + { "surround41", NULL, 0, 1, 0 }, + { "surround50", NULL, 0, 1, 0 }, + { "surround51", NULL, 0, 1, 0 }, + { "surround71", NULL, 0, 1, 0 }, + { NULL, NULL, 0, 1, 0 } +}; + +static const HwDevInfo *FindDeviceName( const char *name ) +{ + int i; + + for( i = 0; predefinedNames[i].alsaName; i++ ) + { + if( strcmp( name, predefinedNames[i].alsaName ) == 0 ) + { + return &predefinedNames[i]; + } + } + + return NULL; +} + +static PaError PaAlsa_StrDup( PaAlsaHostApiRepresentation *alsaApi, + char **dst, + const char *src) +{ + PaError result = paNoError; + int len = strlen( src ) + 1; + + /* PA_DEBUG(("PaStrDup %s %d\n", src, len)); */ + + PA_UNLESS( *dst = (char *)PaUtil_GroupAllocateMemory( alsaApi->allocations, len ), + paInsufficientMemory ); + strncpy( *dst, src, len ); + +error: + return result; +} + +/* Disregard some standard plugins + */ +static int IgnorePlugin( const char *pluginId ) +{ + static const char *ignoredPlugins[] = {"hw", "plughw", "plug", "dsnoop", "tee", + "file", "null", "shm", "cards", "rate_convert", NULL}; + int i = 0; + while( ignoredPlugins[i] ) + { + if( !strcmp( pluginId, ignoredPlugins[i] ) ) + { + return 1; + } + ++i; + } + + return 0; +} + +/** Open PCM device. + * + * Wrapper around snd_pcm_open which may repeatedly retry opening a device if it is busy, for + * a certain time. This is because dmix may temporarily hold on to a device after it (dmix) + * has been opened and closed. + * @param mode: Open mode (e.g., SND_PCM_BLOCKING). + * @param waitOnBusy: Retry opening busy device for up to one second? + **/ +static int OpenPcm( snd_pcm_t **pcmp, const char *name, snd_pcm_stream_t stream, int mode, int waitOnBusy ) +{ + int tries = 0, maxTries = waitOnBusy ? 100 : 0; + int ret = snd_pcm_open( pcmp, name, stream, mode ); + for( tries = 0; tries < maxTries && -EBUSY == ret; ++tries ) + { + Pa_Sleep( 10 ); + ret = snd_pcm_open( pcmp, name, stream, mode ); + if( -EBUSY != ret ) + { + PA_DEBUG(( "%s: Successfully opened initially busy device after %d tries\n", + __FUNCTION__, tries )); + } + } + if( -EBUSY == ret ) + { + PA_DEBUG(( "%s: Failed to open busy device '%s'\n", + __FUNCTION__, name )); + } + + return ret; +} + +static PaError FillInDevInfo( PaAlsaHostApiRepresentation *alsaApi, HwDevInfo* deviceName, int blocking, + PaAlsaDeviceInfo* devInfo, int* devIdx ) +{ + PaError result = 0; + PaDeviceInfo *baseDeviceInfo = &devInfo->baseDeviceInfo; + snd_pcm_t *pcm; + int canMmap = -1; + PaUtilHostApiRepresentation *baseApi = &alsaApi->baseHostApiRep; + + /* Zero fields */ + InitializeDeviceInfo( baseDeviceInfo ); + + /* to determine device capabilities, we must open the device and query the + * hardware parameter configuration space */ + + /* Query capture */ + if( deviceName->hasCapture && + OpenPcm( &pcm, deviceName->alsaName, SND_PCM_STREAM_CAPTURE, blocking, 0 ) + >= 0 ) + { + if( GropeDevice( pcm, deviceName->isPlug, StreamDirection_In, blocking, devInfo, + &canMmap ) != paNoError ) + { + /* Error */ + PA_DEBUG(("%s: Failed groping %s for capture\n", __FUNCTION__, deviceName->alsaName)); + goto end; + } + } + + /* Query playback */ + if( deviceName->hasPlayback && + OpenPcm( &pcm, deviceName->alsaName, SND_PCM_STREAM_PLAYBACK, blocking, 0 ) + >= 0 ) + { + if( GropeDevice( pcm, deviceName->isPlug, StreamDirection_Out, blocking, devInfo, + &canMmap ) != paNoError ) + { + /* Error */ + PA_DEBUG(("%s: Failed groping %s for playback\n", __FUNCTION__, deviceName->alsaName)); + goto end; + } + } + + if( 0 == canMmap ) + { + PA_DEBUG(("%s: Device %s doesn't support mmap\n", __FUNCTION__, deviceName->alsaName)); + goto end; + } + + baseDeviceInfo->structVersion = 2; + baseDeviceInfo->hostApi = alsaApi->hostApiIndex; + baseDeviceInfo->name = deviceName->name; + devInfo->alsaName = deviceName->alsaName; + devInfo->isPlug = deviceName->isPlug; + + /* A: Storing pointer to PaAlsaDeviceInfo object as pointer to PaDeviceInfo object. + * Should now be safe to add device info, unless the device supports neither capture nor playback + */ + if( baseDeviceInfo->maxInputChannels > 0 || baseDeviceInfo->maxOutputChannels > 0 ) + { + /* Make device default if there isn't already one or it is the ALSA "default" device */ + if( (baseApi->info.defaultInputDevice == paNoDevice || !strcmp(deviceName->alsaName, + "default" )) && baseDeviceInfo->maxInputChannels > 0 ) + { + baseApi->info.defaultInputDevice = *devIdx; + PA_DEBUG(("Default input device: %s\n", deviceName->name)); + } + if( (baseApi->info.defaultOutputDevice == paNoDevice || !strcmp(deviceName->alsaName, + "default" )) && baseDeviceInfo->maxOutputChannels > 0 ) + { + baseApi->info.defaultOutputDevice = *devIdx; + PA_DEBUG(("Default output device: %s\n", deviceName->name)); + } + PA_DEBUG(("%s: Adding device %s: %d\n", __FUNCTION__, deviceName->name, *devIdx)); + baseApi->deviceInfos[*devIdx] = (PaDeviceInfo *) devInfo; + (*devIdx) += 1; + } + +end: + return result; +} + +/* Build PaDeviceInfo list, ignore devices for which we cannot determine capabilities (possibly busy, sigh) */ +static PaError BuildDeviceList( PaAlsaHostApiRepresentation *alsaApi ) +{ + PaUtilHostApiRepresentation *baseApi = &alsaApi->baseHostApiRep; + PaAlsaDeviceInfo *deviceInfoArray; + int cardIdx = -1, devIdx = 0; + snd_ctl_card_info_t *cardInfo; + PaError result = paNoError; + size_t numDeviceNames = 0, maxDeviceNames = 1, i; + HwDevInfo *hwDevInfos = NULL; + snd_config_t *topNode = NULL; + snd_pcm_info_t *pcmInfo; + int res; + int blocking = SND_PCM_NONBLOCK; + char alsaCardName[50]; +#ifdef PA_ENABLE_DEBUG_OUTPUT + PaTime startTime = PaUtil_GetTime(); +#endif + + if( getenv( "PA_ALSA_INITIALIZE_BLOCK" ) && atoi( getenv( "PA_ALSA_INITIALIZE_BLOCK" ) ) ) + blocking = 0; + + /* These two will be set to the first working input and output device, respectively */ + baseApi->info.defaultInputDevice = paNoDevice; + baseApi->info.defaultOutputDevice = paNoDevice; + + /* Gather info about hw devices + + * snd_card_next() modifies the integer passed to it to be: + * the index of the first card if the parameter is -1 + * the index of the next card if the parameter is the index of a card + * -1 if there are no more cards + * + * The function itself returns 0 if it succeeded. */ + cardIdx = -1; + snd_ctl_card_info_alloca( &cardInfo ); + snd_pcm_info_alloca( &pcmInfo ); + while( snd_card_next( &cardIdx ) == 0 && cardIdx >= 0 ) + { + char *cardName; + int devIdx = -1; + snd_ctl_t *ctl; + char buf[50]; + + snprintf( alsaCardName, sizeof (alsaCardName), "hw:%d", cardIdx ); + + /* Acquire name of card */ + if( snd_ctl_open( &ctl, alsaCardName, 0 ) < 0 ) + { + /* Unable to open card :( */ + PA_DEBUG(( "%s: Unable to open device %s\n", __FUNCTION__, alsaCardName )); + continue; + } + snd_ctl_card_info( ctl, cardInfo ); + + PA_ENSURE( PaAlsa_StrDup( alsaApi, &cardName, snd_ctl_card_info_get_name( cardInfo )) ); + + while( snd_ctl_pcm_next_device( ctl, &devIdx ) == 0 && devIdx >= 0 ) + { + char *alsaDeviceName, *deviceName; + size_t len; + int hasPlayback = 0, hasCapture = 0; + snprintf( buf, sizeof (buf), "hw:%d,%d", cardIdx, devIdx ); + + /* Obtain info about this particular device */ + snd_pcm_info_set_device( pcmInfo, devIdx ); + snd_pcm_info_set_subdevice( pcmInfo, 0 ); + snd_pcm_info_set_stream( pcmInfo, SND_PCM_STREAM_CAPTURE ); + if( snd_ctl_pcm_info( ctl, pcmInfo ) >= 0 ) + { + hasCapture = 1; + } + + snd_pcm_info_set_stream( pcmInfo, SND_PCM_STREAM_PLAYBACK ); + if( snd_ctl_pcm_info( ctl, pcmInfo ) >= 0 ) + { + hasPlayback = 1; + } + + if( !hasPlayback && !hasCapture ) + { + /* Error */ + continue; + } + + /* The length of the string written by snprintf plus terminating 0 */ + len = snprintf( NULL, 0, "%s: %s (%s)", cardName, snd_pcm_info_get_name( pcmInfo ), buf ) + 1; + PA_UNLESS( deviceName = (char *)PaUtil_GroupAllocateMemory( alsaApi->allocations, len ), + paInsufficientMemory ); + snprintf( deviceName, len, "%s: %s (%s)", cardName, + snd_pcm_info_get_name( pcmInfo ), buf ); + + ++numDeviceNames; + if( !hwDevInfos || numDeviceNames > maxDeviceNames ) + { + maxDeviceNames *= 2; + PA_UNLESS( hwDevInfos = (HwDevInfo *) realloc( hwDevInfos, maxDeviceNames * sizeof (HwDevInfo) ), + paInsufficientMemory ); + } + + PA_ENSURE( PaAlsa_StrDup( alsaApi, &alsaDeviceName, buf ) ); + + hwDevInfos[ numDeviceNames - 1 ].alsaName = alsaDeviceName; + hwDevInfos[ numDeviceNames - 1 ].name = deviceName; + hwDevInfos[ numDeviceNames - 1 ].isPlug = 0; + hwDevInfos[ numDeviceNames - 1 ].hasPlayback = hasPlayback; + hwDevInfos[ numDeviceNames - 1 ].hasCapture = hasCapture; + } + snd_ctl_close( ctl ); + } + + /* Iterate over plugin devices */ + + if( NULL == snd_config ) + { + /* snd_config_update is called implicitly by some functions, if this hasn't happened snd_config will be NULL (bleh) */ + ENSURE_( snd_config_update(), paUnanticipatedHostError ); + PA_DEBUG(( "Updating snd_config\n" )); + } + assert( snd_config ); + if( (res = snd_config_search( snd_config, "pcm", &topNode )) >= 0 ) + { + snd_config_iterator_t i, next; + + snd_config_for_each( i, next, topNode ) + { + const char *tpStr = "unknown", *idStr = NULL; + int err = 0; + + char *alsaDeviceName, *deviceName; + const HwDevInfo *predefined = NULL; + snd_config_t *n = snd_config_iterator_entry( i ), * tp = NULL;; + + if( (err = snd_config_search( n, "type", &tp )) < 0 ) + { + if( -ENOENT != err ) + { + ENSURE_(err, paUnanticipatedHostError); + } + } + else + { + ENSURE_( snd_config_get_string( tp, &tpStr ), paUnanticipatedHostError ); + } + ENSURE_( snd_config_get_id( n, &idStr ), paUnanticipatedHostError ); + if( IgnorePlugin( idStr ) ) + { + PA_DEBUG(( "%s: Ignoring ALSA plugin device %s of type %s\n", __FUNCTION__, idStr, tpStr )); + continue; + } + PA_DEBUG(( "%s: Found plugin %s of type %s\n", __FUNCTION__, idStr, tpStr )); + + PA_UNLESS( alsaDeviceName = (char*)PaUtil_GroupAllocateMemory( alsaApi->allocations, + strlen(idStr) + 6 ), paInsufficientMemory ); + strcpy( alsaDeviceName, idStr ); + PA_UNLESS( deviceName = (char*)PaUtil_GroupAllocateMemory( alsaApi->allocations, + strlen(idStr) + 1 ), paInsufficientMemory ); + strcpy( deviceName, idStr ); + + ++numDeviceNames; + if( !hwDevInfos || numDeviceNames > maxDeviceNames ) + { + maxDeviceNames *= 2; + PA_UNLESS( hwDevInfos = (HwDevInfo *) realloc( hwDevInfos, maxDeviceNames * sizeof (HwDevInfo) ), + paInsufficientMemory ); + } + + predefined = FindDeviceName( alsaDeviceName ); + + hwDevInfos[numDeviceNames - 1].alsaName = alsaDeviceName; + hwDevInfos[numDeviceNames - 1].name = deviceName; + hwDevInfos[numDeviceNames - 1].isPlug = 1; + + if( predefined ) + { + hwDevInfos[numDeviceNames - 1].hasPlayback = + predefined->hasPlayback; + hwDevInfos[numDeviceNames - 1].hasCapture = + predefined->hasCapture; + } + else + { + hwDevInfos[numDeviceNames - 1].hasPlayback = 1; + hwDevInfos[numDeviceNames - 1].hasCapture = 1; + } + } + } + else + PA_DEBUG(( "%s: Iterating over ALSA plugins failed: %s\n", __FUNCTION__, snd_strerror( res ) )); + + /* allocate deviceInfo memory based on the number of devices */ + PA_UNLESS( baseApi->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory( + alsaApi->allocations, sizeof(PaDeviceInfo*) * (numDeviceNames) ), paInsufficientMemory ); + + /* allocate all device info structs in a contiguous block */ + PA_UNLESS( deviceInfoArray = (PaAlsaDeviceInfo*)PaUtil_GroupAllocateMemory( + alsaApi->allocations, sizeof(PaAlsaDeviceInfo) * numDeviceNames ), paInsufficientMemory ); + + /* Loop over list of cards, filling in info. If a device is deemed unavailable (can't get name), + * it's ignored. + * + * Note that we do this in two stages. This is a workaround owing to the fact that the 'dmix' + * plugin may cause the underlying hardware device to be busy for a short while even after it + * (dmix) is closed. The 'default' plugin may also point to the dmix plugin, so the same goes + * for this. + */ + + for( i = 0, devIdx = 0; i < numDeviceNames; ++i ) + { + PaAlsaDeviceInfo* devInfo = &deviceInfoArray[i]; + HwDevInfo* hwInfo = &hwDevInfos[i]; + if( !strcmp( hwInfo->name, "dmix" ) || !strcmp( hwInfo->name, "default" ) ) + { + continue; + } + + PA_ENSURE( FillInDevInfo( alsaApi, hwInfo, blocking, devInfo, &devIdx ) ); + } + assert( devIdx < numDeviceNames ); + /* Now inspect 'dmix' and 'default' plugins */ + for( i = 0; i < numDeviceNames; ++i ) + { + PaAlsaDeviceInfo* devInfo = &deviceInfoArray[i]; + HwDevInfo* hwInfo = &hwDevInfos[i]; + if( strcmp( hwInfo->name, "dmix" ) && strcmp( hwInfo->name, "default" ) ) + { + continue; + } + + PA_ENSURE( FillInDevInfo( alsaApi, hwInfo, blocking, devInfo, + &devIdx ) ); + } + free( hwDevInfos ); + + baseApi->info.deviceCount = devIdx; /* Number of successfully queried devices */ + +#ifdef PA_ENABLE_DEBUG_OUTPUT + PA_DEBUG(( "%s: Building device list took %f seconds\n", __FUNCTION__, PaUtil_GetTime() - startTime )); +#endif + +end: + return result; + +error: + /* No particular action */ + goto end; +} + +/* Check against known device capabilities */ +static PaError ValidateParameters( const PaStreamParameters *parameters, PaUtilHostApiRepresentation *hostApi, StreamDirection mode ) +{ + PaError result = paNoError; + int maxChans; + const PaAlsaDeviceInfo *deviceInfo = NULL; + assert( parameters ); + + if( parameters->device != paUseHostApiSpecificDeviceSpecification ) + { + assert( parameters->device < hostApi->info.deviceCount ); + PA_UNLESS( parameters->hostApiSpecificStreamInfo == NULL, paBadIODeviceCombination ); + deviceInfo = GetDeviceInfo( hostApi, parameters->device ); + } + else + { + const PaAlsaStreamInfo *streamInfo = parameters->hostApiSpecificStreamInfo; + + PA_UNLESS( parameters->device == paUseHostApiSpecificDeviceSpecification, paInvalidDevice ); + PA_UNLESS( streamInfo->size == sizeof (PaAlsaStreamInfo) && streamInfo->version == 1, + paIncompatibleHostApiSpecificStreamInfo ); + PA_UNLESS( streamInfo->deviceString != NULL, paInvalidDevice ); + + /* Skip further checking */ + return paNoError; + } + + assert( deviceInfo ); + assert( parameters->hostApiSpecificStreamInfo == NULL ); + maxChans = (StreamDirection_In == mode ? deviceInfo->baseDeviceInfo.maxInputChannels : + deviceInfo->baseDeviceInfo.maxOutputChannels); + PA_UNLESS( parameters->channelCount <= maxChans, paInvalidChannelCount ); + +error: + return result; +} + +/* Given an open stream, what sample formats are available? */ +static PaSampleFormat GetAvailableFormats( snd_pcm_t *pcm ) +{ + PaSampleFormat available = 0; + snd_pcm_hw_params_t *hwParams; + snd_pcm_hw_params_alloca( &hwParams ); + + snd_pcm_hw_params_any( pcm, hwParams ); + + if( snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_FLOAT ) >= 0) + available |= paFloat32; + + if( snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_S32 ) >= 0) + available |= paInt32; + +#ifdef PA_LITTLE_ENDIAN + if( snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_S24_3LE ) >= 0) + available |= paInt24; +#elif defined PA_BIG_ENDIAN + if( snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_S24_3BE ) >= 0) + available |= paInt24; +#endif + + if( snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_S16 ) >= 0) + available |= paInt16; + + if( snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_U8 ) >= 0) + available |= paUInt8; + + if( snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_S8 ) >= 0) + available |= paInt8; + + return available; +} + +static snd_pcm_format_t Pa2AlsaFormat( PaSampleFormat paFormat ) +{ + switch( paFormat ) + { + case paFloat32: + return SND_PCM_FORMAT_FLOAT; + + case paInt16: + return SND_PCM_FORMAT_S16; + + case paInt24: +#ifdef PA_LITTLE_ENDIAN + return SND_PCM_FORMAT_S24_3LE; +#elif defined PA_BIG_ENDIAN + return SND_PCM_FORMAT_S24_3BE; +#endif + + case paInt32: + return SND_PCM_FORMAT_S32; + + case paInt8: + return SND_PCM_FORMAT_S8; + + case paUInt8: + return SND_PCM_FORMAT_U8; + + default: + return SND_PCM_FORMAT_UNKNOWN; + } +} + +/** Open an ALSA pcm handle. + * + * The device to be open can be specified in a custom PaAlsaStreamInfo struct, or it will be a device number. In case of a + * device number, it maybe specified through an env variable (PA_ALSA_PLUGHW) that we should open the corresponding plugin + * device. + */ +static PaError AlsaOpen( const PaUtilHostApiRepresentation *hostApi, const PaStreamParameters *params, StreamDirection + streamDir, snd_pcm_t **pcm ) +{ + PaError result = paNoError; + int ret; + char dnameArray[50]; + const char* deviceName = dnameArray; + const PaAlsaDeviceInfo *deviceInfo = NULL; + PaAlsaStreamInfo *streamInfo = (PaAlsaStreamInfo *)params->hostApiSpecificStreamInfo; + + if( !streamInfo ) + { + int usePlug = 0; + deviceInfo = GetDeviceInfo( hostApi, params->device ); + + /* If device name starts with hw: and PA_ALSA_PLUGHW is 1, we open the plughw device instead */ + if( !strncmp( "hw:", deviceInfo->alsaName, 3 ) && getenv( "PA_ALSA_PLUGHW" ) ) + usePlug = atoi( getenv( "PA_ALSA_PLUGHW" ) ); + if( usePlug ) + snprintf( dnameArray, 50, "plug%s", deviceInfo->alsaName ); + else + deviceName = deviceInfo->alsaName; + } + else + deviceName = streamInfo->deviceString; + + PA_DEBUG(( "%s: Opening device %s\n", __FUNCTION__, deviceName )); + if( (ret = OpenPcm( pcm, deviceName, streamDir == StreamDirection_In ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK, + SND_PCM_NONBLOCK, 1 )) < 0 ) + { + /* Not to be closed */ + *pcm = NULL; + ENSURE_( ret, -EBUSY == ret ? paDeviceUnavailable : paBadIODeviceCombination ); + } + ENSURE_( snd_pcm_nonblock( *pcm, 0 ), paUnanticipatedHostError ); + +end: + return result; + +error: + goto end; +} + +static PaError TestParameters( const PaUtilHostApiRepresentation *hostApi, const PaStreamParameters *parameters, + double sampleRate, StreamDirection streamDir ) +{ + PaError result = paNoError; + snd_pcm_t *pcm = NULL; + PaSampleFormat availableFormats; + /* We are able to adapt to a number of channels less than what the device supports */ + unsigned int numHostChannels; + PaSampleFormat hostFormat; + snd_pcm_hw_params_t *hwParams; + snd_pcm_hw_params_alloca( &hwParams ); + + if( !parameters->hostApiSpecificStreamInfo ) + { + const PaAlsaDeviceInfo *devInfo = GetDeviceInfo( hostApi, parameters->device ); + numHostChannels = PA_MAX( parameters->channelCount, StreamDirection_In == streamDir ? + devInfo->minInputChannels : devInfo->minOutputChannels ); + } + else + numHostChannels = parameters->channelCount; + + PA_ENSURE( AlsaOpen( hostApi, parameters, streamDir, &pcm ) ); + + snd_pcm_hw_params_any( pcm, hwParams ); + + if( SetApproximateSampleRate( pcm, hwParams, sampleRate ) < 0 ) + { + result = paInvalidSampleRate; + goto error; + } + + if( snd_pcm_hw_params_set_channels( pcm, hwParams, numHostChannels ) < 0 ) + { + result = paInvalidChannelCount; + goto error; + } + + /* See if we can find a best possible match */ + availableFormats = GetAvailableFormats( pcm ); + PA_ENSURE( hostFormat = PaUtil_SelectClosestAvailableFormat( availableFormats, parameters->sampleFormat ) ); + ENSURE_( snd_pcm_hw_params_set_format( pcm, hwParams, Pa2AlsaFormat( hostFormat ) ), paUnanticipatedHostError ); + + { + /* It happens that this call fails because the device is busy */ + int ret = 0; + if( (ret = snd_pcm_hw_params( pcm, hwParams )) < 0) + { + if( -EINVAL == ret ) + { + /* Don't know what to return here */ + result = paBadIODeviceCombination; + goto error; + } + else if( -EBUSY == ret ) + { + result = paDeviceUnavailable; + PA_DEBUG(( "%s: Device is busy\n", __FUNCTION__ )); + } + else + { + result = paUnanticipatedHostError; + } + + ENSURE_( ret, result ); + } + } + +end: + if( pcm ) + { + snd_pcm_close( pcm ); + } + return result; + +error: + goto end; +} + +static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi, + const PaStreamParameters *inputParameters, + const PaStreamParameters *outputParameters, + double sampleRate ) +{ + int inputChannelCount = 0, outputChannelCount = 0; + PaSampleFormat inputSampleFormat, outputSampleFormat; + PaError result = paFormatIsSupported; + + if( inputParameters ) + { + PA_ENSURE( ValidateParameters( inputParameters, hostApi, StreamDirection_In ) ); + + inputChannelCount = inputParameters->channelCount; + inputSampleFormat = inputParameters->sampleFormat; + } + + if( outputParameters ) + { + PA_ENSURE( ValidateParameters( outputParameters, hostApi, StreamDirection_Out ) ); + + outputChannelCount = outputParameters->channelCount; + outputSampleFormat = outputParameters->sampleFormat; + } + + if( inputChannelCount ) + { + if( (result = TestParameters( hostApi, inputParameters, sampleRate, StreamDirection_In )) + != paNoError ) + goto error; + } + if ( outputChannelCount ) + { + if( (result = TestParameters( hostApi, outputParameters, sampleRate, StreamDirection_Out )) + != paNoError ) + goto error; + } + + return paFormatIsSupported; + +error: + return result; +} + +static PaError PaAlsaStreamComponent_Initialize( PaAlsaStreamComponent *self, PaAlsaHostApiRepresentation *alsaApi, + const PaStreamParameters *params, StreamDirection streamDir, int callbackMode ) +{ + PaError result = paNoError; + PaSampleFormat userSampleFormat = params->sampleFormat, hostSampleFormat; + assert( params->channelCount > 0 ); + + /* Make sure things have an initial value */ + memset( self, 0, sizeof (PaAlsaStreamComponent) ); + + if( NULL == params->hostApiSpecificStreamInfo ) + { + const PaAlsaDeviceInfo *devInfo = GetDeviceInfo( &alsaApi->baseHostApiRep, params->device ); + self->numHostChannels = PA_MAX( params->channelCount, StreamDirection_In == streamDir ? devInfo->minInputChannels + : devInfo->minOutputChannels ); + } + else + { + /* We're blissfully unaware of the minimum channelCount */ + self->numHostChannels = params->channelCount; + } + + self->device = params->device; + + PA_ENSURE( AlsaOpen( &alsaApi->baseHostApiRep, params, streamDir, &self->pcm ) ); + self->nfds = snd_pcm_poll_descriptors_count( self->pcm ); + hostSampleFormat = PaUtil_SelectClosestAvailableFormat( GetAvailableFormats( self->pcm ), userSampleFormat ); + + self->hostSampleFormat = hostSampleFormat; + self->nativeFormat = Pa2AlsaFormat( hostSampleFormat ); + self->hostInterleaved = self->userInterleaved = !(userSampleFormat & paNonInterleaved); + self->numUserChannels = params->channelCount; + self->streamDir = streamDir; + + if( !callbackMode && !self->userInterleaved ) + { + /* Pre-allocate non-interleaved user provided buffers */ + PA_UNLESS( self->userBuffers = PaUtil_AllocateMemory( sizeof (void *) * self->numUserChannels ), + paInsufficientMemory ); + } + +error: + return result; +} + +static void PaAlsaStreamComponent_Terminate( PaAlsaStreamComponent *self ) +{ + snd_pcm_close( self->pcm ); + if( self->userBuffers ) + PaUtil_FreeMemory( self->userBuffers ); +} + +/* +static int nearbyint_(float value) { + if( value - (int)value > .5 ) + return (int)ceil( value ); + return (int)floor( value ); +} +*/ + +/** Initiate configuration, preparing for determining a period size suitable for both capture and playback components. + * + */ +static PaError PaAlsaStreamComponent_InitialConfigure( PaAlsaStreamComponent *self, const PaStreamParameters *params, + int primeBuffers, snd_pcm_hw_params_t *hwParams, double *sampleRate ) +{ + /* Configuration consists of setting all of ALSA's parameters. + * These parameters come in two flavors: hardware parameters + * and software paramters. Hardware parameters will affect + * the way the device is initialized, software parameters + * affect the way ALSA interacts with me, the user-level client. + */ + + PaError result = paNoError; + snd_pcm_access_t accessMode, alternateAccessMode; + int dir = 0; + snd_pcm_t *pcm = self->pcm; + double sr = *sampleRate; + unsigned int minPeriods = 2; + + /* self->framesPerBuffer = framesPerHostBuffer; */ + + /* ... fill up the configuration space with all possibile + * combinations of parameters this device will accept */ + ENSURE_( snd_pcm_hw_params_any( pcm, hwParams ), paUnanticipatedHostError ); + + ENSURE_( snd_pcm_hw_params_set_periods_integer( pcm, hwParams ), paUnanticipatedHostError ); + /* I think there should be at least 2 periods (even though ALSA doesn't appear to enforce this) */ + dir = 0; + ENSURE_( snd_pcm_hw_params_set_periods_min( pcm, hwParams, &minPeriods, &dir ), paUnanticipatedHostError ); + + if( self->userInterleaved ) + { + accessMode = SND_PCM_ACCESS_MMAP_INTERLEAVED; + alternateAccessMode = SND_PCM_ACCESS_MMAP_NONINTERLEAVED; + } + else + { + accessMode = SND_PCM_ACCESS_MMAP_NONINTERLEAVED; + alternateAccessMode = SND_PCM_ACCESS_MMAP_INTERLEAVED; + } + /* If requested access mode fails, try alternate mode */ + if( snd_pcm_hw_params_set_access( pcm, hwParams, accessMode ) < 0 ) + { + int err = 0; + if( (err = snd_pcm_hw_params_set_access( pcm, hwParams, alternateAccessMode )) < 0) + { + result = paUnanticipatedHostError; + if( -EINVAL == err ) + { + PaUtil_SetLastHostErrorInfo( paALSA, err, "PA ALSA requires that a device supports mmap access" ); + } + else + { + PaUtil_SetLastHostErrorInfo( paALSA, err, snd_strerror( err ) ); + } + goto error; + } + /* Flip mode */ + self->hostInterleaved = !self->userInterleaved; + } + + ENSURE_( snd_pcm_hw_params_set_format( pcm, hwParams, self->nativeFormat ), paUnanticipatedHostError ); + + ENSURE_( SetApproximateSampleRate( pcm, hwParams, sr ), paInvalidSampleRate ); + ENSURE_( GetExactSampleRate( hwParams, &sr ), paUnanticipatedHostError ); + /* reject if there's no sample rate within 1% of the one requested */ + if( (fabs( *sampleRate - sr ) / *sampleRate) > 0.01 ) + { + PA_DEBUG(("%s: Wanted %f, closest sample rate was %d\n", __FUNCTION__, sampleRate, sr )); + PA_ENSURE( paInvalidSampleRate ); + } + + ENSURE_( snd_pcm_hw_params_set_channels( pcm, hwParams, self->numHostChannels ), paInvalidChannelCount ); + + *sampleRate = sr; + +end: + return result; + +error: + /* No particular action */ + goto end; +} + +/** Finish the configuration of the component's ALSA device. + * + * As part of this method, the component's bufferSize attribute will be set. + * @param latency: The latency for this component. + */ +static PaError PaAlsaStreamComponent_FinishConfigure( PaAlsaStreamComponent *self, snd_pcm_hw_params_t* hwParams, + const PaStreamParameters *params, int primeBuffers, double sampleRate, PaTime* latency ) +{ + PaError result = paNoError; + snd_pcm_sw_params_t* swParams; + snd_pcm_uframes_t bufSz = 0; + *latency = -1.; + + snd_pcm_sw_params_alloca( &swParams ); + + bufSz = params->suggestedLatency * sampleRate; + ENSURE_( snd_pcm_hw_params_set_buffer_size_near( self->pcm, hwParams, &bufSz ), paUnanticipatedHostError ); + + /* Set the parameters! */ + { + int r = snd_pcm_hw_params( self->pcm, hwParams ); +#ifdef PA_ENABLE_DEBUG_OUTPUT + if( r < 0 ) + { + snd_output_t *output = NULL; + snd_output_stdio_attach( &output, stderr, 0 ); + snd_pcm_hw_params_dump( hwParams, output ); + } +#endif + ENSURE_(r, paUnanticipatedHostError ); + } + ENSURE_( snd_pcm_hw_params_get_buffer_size( hwParams, &self->bufferSize ), paUnanticipatedHostError ); + /* Latency in seconds */ + *latency = self->bufferSize / sampleRate; + + /* Now software parameters... */ + ENSURE_( snd_pcm_sw_params_current( self->pcm, swParams ), paUnanticipatedHostError ); + + ENSURE_( snd_pcm_sw_params_set_start_threshold( self->pcm, swParams, self->framesPerBuffer ), paUnanticipatedHostError ); + ENSURE_( snd_pcm_sw_params_set_stop_threshold( self->pcm, swParams, self->bufferSize ), paUnanticipatedHostError ); + + /* Silence buffer in the case of underrun */ + if( !primeBuffers ) /* XXX: Make sense? */ + { + snd_pcm_uframes_t boundary; + ENSURE_( snd_pcm_sw_params_get_boundary( swParams, &boundary ), paUnanticipatedHostError ); + ENSURE_( snd_pcm_sw_params_set_silence_threshold( self->pcm, swParams, 0 ), paUnanticipatedHostError ); + ENSURE_( snd_pcm_sw_params_set_silence_size( self->pcm, swParams, boundary ), paUnanticipatedHostError ); + } + + ENSURE_( snd_pcm_sw_params_set_avail_min( self->pcm, swParams, self->framesPerBuffer ), paUnanticipatedHostError ); + ENSURE_( snd_pcm_sw_params_set_xfer_align( self->pcm, swParams, 1 ), paUnanticipatedHostError ); + ENSURE_( snd_pcm_sw_params_set_tstamp_mode( self->pcm, swParams, SND_PCM_TSTAMP_MMAP ), paUnanticipatedHostError ); + + /* Set the parameters! */ + ENSURE_( snd_pcm_sw_params( self->pcm, swParams ), paUnanticipatedHostError ); + +error: + return result; +} + +static PaError PaAlsaStream_Initialize( PaAlsaStream *self, PaAlsaHostApiRepresentation *alsaApi, const PaStreamParameters *inParams, + const PaStreamParameters *outParams, double sampleRate, unsigned long framesPerUserBuffer, PaStreamCallback callback, + PaStreamFlags streamFlags, void *userData ) +{ + PaError result = paNoError; + assert( self ); + + memset( self, 0, sizeof (PaAlsaStream) ); + + if( NULL != callback ) + { + PaUtil_InitializeStreamRepresentation( &self->streamRepresentation, + &alsaApi->callbackStreamInterface, + callback, userData ); + self->callbackMode = 1; + } + else + { + PaUtil_InitializeStreamRepresentation( &self->streamRepresentation, + &alsaApi->blockingStreamInterface, + NULL, userData ); + } + + self->framesPerUserBuffer = framesPerUserBuffer; + self->neverDropInput = streamFlags & paNeverDropInput; + /* XXX: Ignore paPrimeOutputBuffersUsingStreamCallback untill buffer priming is fully supported in pa_process.c */ + /* + if( outParams & streamFlags & paPrimeOutputBuffersUsingStreamCallback ) + self->primeBuffers = 1; + */ + memset( &self->capture, 0, sizeof (PaAlsaStreamComponent) ); + memset( &self->playback, 0, sizeof (PaAlsaStreamComponent) ); + if( inParams ) + { + PA_ENSURE( PaAlsaStreamComponent_Initialize( &self->capture, alsaApi, inParams, StreamDirection_In, NULL != callback ) ); + } + if( outParams ) + { + PA_ENSURE( PaAlsaStreamComponent_Initialize( &self->playback, alsaApi, outParams, StreamDirection_Out, NULL != callback ) ); + } + + assert( self->capture.nfds || self->playback.nfds ); + + PA_UNLESS( self->pfds = (struct pollfd*)PaUtil_AllocateMemory( (self->capture.nfds + + self->playback.nfds) * sizeof (struct pollfd) ), paInsufficientMemory ); + + PaUtil_InitializeCpuLoadMeasurer( &self->cpuLoadMeasurer, sampleRate ); + ASSERT_CALL_( PaUnixMutex_Initialize( &self->stateMtx ), paNoError ); + +error: + return result; +} + +/** Free resources associated with stream, and eventually stream itself. + * + * Frees allocated memory, and terminates individual StreamComponents. + */ +static void PaAlsaStream_Terminate( PaAlsaStream *self ) +{ + assert( self ); + + if( self->capture.pcm ) + { + PaAlsaStreamComponent_Terminate( &self->capture ); + } + if( self->playback.pcm ) + { + PaAlsaStreamComponent_Terminate( &self->playback ); + } + + PaUtil_FreeMemory( self->pfds ); + ASSERT_CALL_( PaUnixMutex_Terminate( &self->stateMtx ), paNoError ); + + PaUtil_FreeMemory( self ); +} + +/** Calculate polling timeout + * + * @param frames Time to wait + * @return Polling timeout in milliseconds + */ +static int CalculatePollTimeout( const PaAlsaStream *stream, unsigned long frames ) +{ + assert( stream->streamRepresentation.streamInfo.sampleRate > 0.0 ); + /* Period in msecs, rounded up */ + return (int)ceil( 1000 * frames / stream->streamRepresentation.streamInfo.sampleRate ); +} + +/** Determine size per host buffer. + * + * During this method call, the component's framesPerBuffer attribute gets computed, and the corresponding period size + * gets configured for the device. + * @param accurate: If the configured period size is non-integer, this will be set to 0. + */ +static PaError PaAlsaStreamComponent_DetermineFramesPerBuffer( PaAlsaStreamComponent* self, const PaStreamParameters* params, + unsigned long framesPerUserBuffer, double sampleRate, snd_pcm_hw_params_t* hwParams, int* accurate ) +{ + PaError result = paNoError; + unsigned long bufferSize = params->suggestedLatency * sampleRate, framesPerHostBuffer; + int dir = 0; + + { + snd_pcm_uframes_t tmp; + snd_pcm_hw_params_get_buffer_size_min( hwParams, &tmp ); + bufferSize = PA_MAX( bufferSize, tmp ); + snd_pcm_hw_params_get_buffer_size_max( hwParams, &tmp ); + bufferSize = PA_MIN( bufferSize, tmp ); + } + + assert( bufferSize > 0 ); + + if( framesPerUserBuffer != paFramesPerBufferUnspecified ) + { + /* Preferably the host buffer size should be a multiple of the user buffer size */ + + if( bufferSize > framesPerUserBuffer ) + { + snd_pcm_uframes_t remainder = bufferSize % framesPerUserBuffer; + if( remainder > framesPerUserBuffer / 2. ) + bufferSize += framesPerUserBuffer - remainder; + else + bufferSize -= remainder; + + assert( bufferSize % framesPerUserBuffer == 0 ); + } + else if( framesPerUserBuffer % bufferSize != 0 ) + { + /* Find a good compromise between user specified latency and buffer size */ + if( bufferSize > framesPerUserBuffer * .75 ) + { + bufferSize = framesPerUserBuffer; + } + else + { + snd_pcm_uframes_t newSz = framesPerUserBuffer; + while( newSz / 2 >= bufferSize ) + { + if( framesPerUserBuffer % (newSz / 2) != 0 ) + { + /* No use dividing any further */ + break; + } + newSz /= 2; + } + bufferSize = newSz; + } + + assert( framesPerUserBuffer % bufferSize == 0 ); + } + } + + /* Using the base number of periods, we try to approximate the suggested latency (+1 period), + finding a combination of period/buffer size which best fits these constraints */ + { + unsigned numPeriods = numPeriods_, maxPeriods = 0; + /* It may be that the device only supports 2 periods for instance */ + dir = 0; + ENSURE_( snd_pcm_hw_params_get_periods_max( hwParams, &maxPeriods, &dir ), paUnanticipatedHostError ); + assert( maxPeriods > 1 ); + numPeriods = PA_MIN( maxPeriods, numPeriods ); + + if( framesPerUserBuffer != paFramesPerBufferUnspecified ) + { + /* Try to get a power-of-two of the user buffer size. */ + framesPerHostBuffer = framesPerUserBuffer; + if( framesPerHostBuffer < bufferSize ) + { + while( bufferSize / framesPerHostBuffer > numPeriods ) + { + framesPerHostBuffer *= 2; + } + /* One extra period is preferrable to one less (should be more robust) */ + if( bufferSize / framesPerHostBuffer < numPeriods ) + { + framesPerHostBuffer /= 2; + } + } + else + { + while( bufferSize / framesPerHostBuffer < numPeriods ) + { + if( framesPerUserBuffer % (framesPerHostBuffer / 2) != 0 ) + { + /* Can't be divided any further */ + break; + } + framesPerHostBuffer /= 2; + } + } + + if( framesPerHostBuffer < framesPerUserBuffer ) + { + assert( framesPerUserBuffer % framesPerHostBuffer == 0 ); + if( snd_pcm_hw_params_test_period_size( self->pcm, hwParams, framesPerHostBuffer, 0 ) < 0 ) + { + if( snd_pcm_hw_params_test_period_size( self->pcm, hwParams, framesPerHostBuffer * 2, 0 ) == 0 ) + framesPerHostBuffer *= 2; + else if( snd_pcm_hw_params_test_period_size( self->pcm, hwParams, framesPerHostBuffer / 2, 0 ) == 0 ) + framesPerHostBuffer /= 2; + } + } + else + { + assert( framesPerHostBuffer % framesPerUserBuffer == 0 ); + if( snd_pcm_hw_params_test_period_size( self->pcm, hwParams, framesPerHostBuffer, 0 ) < 0 ) + { + if( snd_pcm_hw_params_test_period_size( self->pcm, hwParams, framesPerHostBuffer + framesPerUserBuffer, 0 ) == 0 ) + framesPerHostBuffer += framesPerUserBuffer; + else if( snd_pcm_hw_params_test_period_size( self->pcm, hwParams, framesPerHostBuffer - framesPerUserBuffer, 0 ) == 0 ) + framesPerHostBuffer -= framesPerUserBuffer; + } + } + } + else + { + framesPerHostBuffer = bufferSize / numPeriods; + } + } + + assert( framesPerHostBuffer > 0 ); + { + snd_pcm_uframes_t min = 0, max = 0; + ENSURE_( snd_pcm_hw_params_get_period_size_min( hwParams, &min, NULL ), paUnanticipatedHostError ); + ENSURE_( snd_pcm_hw_params_get_period_size_max( hwParams, &max, NULL ), paUnanticipatedHostError ); + + if( framesPerHostBuffer < min ) + { + PA_DEBUG(( "%s: The determined period size (%lu) is less than minimum (%lu)\n", __FUNCTION__, + framesPerHostBuffer, min )); + framesPerHostBuffer = min; + } + else if( framesPerHostBuffer > max ) + { + PA_DEBUG(( "%s: The determined period size (%lu) is greater than maximum (%lu)\n", __FUNCTION__, + framesPerHostBuffer, max )); + framesPerHostBuffer = max; + } + + assert( framesPerHostBuffer >= min && framesPerHostBuffer <= max ); + dir = 0; + ENSURE_( snd_pcm_hw_params_set_period_size_near( self->pcm, hwParams, &framesPerHostBuffer, &dir ), + paUnanticipatedHostError ); + if( dir != 0 ) + { + PA_DEBUG(( "%s: The configured period size is non-integer.\n", __FUNCTION__, dir )); + *accurate = 0; + } + } + self->framesPerBuffer = framesPerHostBuffer; + +error: + return result; +} + +/* We need to determine how many frames per host buffer (period) to use. Our + * goals are to provide the best possible performance, but also to + * honor the requested latency settings as closely as we can. Therefore this + * decision is based on: + * + * - the period sizes that playback and/or capture support. The + * host buffer size has to be one of these. + * - the number of periods that playback and/or capture support. + * + * We want to make period_size*(num_periods-1) to be as close as possible + * to latency*rate for both playback and capture. + * + * This method will determine suitable period sizes for capture and playback handles, and report the maximum number of + * frames per host buffer. The latter is relevant, in case we should be so unfortunate that the period size differs + * between capture and playback. If this should happen, the stream's hostBufferSizeMode attribute will be set to + * paUtilBoundedHostBufferSize, because the best we can do is limit the size of individual host buffers to the upper + * bound. The size of host buffers scheduled for processing should only matter if the user has specified a buffer size, + * but when he/she does we must strive for an optimal configuration. By default we'll opt for a fixed host buffer size, + * which should be fine if the period size is the same for capture and playback. In general, if there is a specified user + * buffer size, this method tries it best to determine a period size which is a multiple of the user buffer size. + * + * The framesPerBuffer attributes of the individual capture and playback components of the stream are set to corresponding + * values determined here. Since these should be reported as + * + * This is one of those blocks of code that will just take a lot of + * refinement to be any good. + * + * In the full-duplex case it is possible that the routine was unable + * to find a number of frames per buffer acceptable to both devices + * TODO: Implement an algorithm to find the value closest to acceptance + * by both devices, to minimize difference between period sizes? + * + * @param determinedFramesPerHostBuffer: The determined host buffer size. + */ +static PaError PaAlsaStream_DetermineFramesPerBuffer( PaAlsaStream* self, double sampleRate, const PaStreamParameters* inputParameters, + const PaStreamParameters* outputParameters, unsigned long framesPerUserBuffer, snd_pcm_hw_params_t* hwParamsCapture, + snd_pcm_hw_params_t* hwParamsPlayback, PaUtilHostBufferSizeMode* hostBufferSizeMode ) +{ + PaError result = paNoError; + unsigned long framesPerHostBuffer = 0; + int dir = 0; + int accurate = 1; + unsigned numPeriods = numPeriods_; + + if( self->capture.pcm && self->playback.pcm ) + { + if( framesPerUserBuffer == paFramesPerBufferUnspecified ) + { + /* Come up with a common desired latency */ + snd_pcm_uframes_t desiredBufSz, e, minPeriodSize, maxPeriodSize, optimalPeriodSize, periodSize, + minCapture, minPlayback, maxCapture, maxPlayback; + + dir = 0; + ENSURE_( snd_pcm_hw_params_get_period_size_min( hwParamsCapture, &minCapture, &dir ), paUnanticipatedHostError ); + dir = 0; + ENSURE_( snd_pcm_hw_params_get_period_size_min( hwParamsPlayback, &minPlayback, &dir ), paUnanticipatedHostError ); + dir = 0; + ENSURE_( snd_pcm_hw_params_get_period_size_max( hwParamsCapture, &maxCapture, &dir ), paUnanticipatedHostError ); + dir = 0; + ENSURE_( snd_pcm_hw_params_get_period_size_max( hwParamsPlayback, &maxPlayback, &dir ), paUnanticipatedHostError ); + minPeriodSize = PA_MAX( minPlayback, minCapture ); + maxPeriodSize = PA_MIN( maxPlayback, maxCapture ); + PA_UNLESS( minPeriodSize <= maxPeriodSize, paBadIODeviceCombination ); + + desiredBufSz = (snd_pcm_uframes_t)(PA_MIN( outputParameters->suggestedLatency, inputParameters->suggestedLatency ) + * sampleRate); + /* Clamp desiredBufSz */ + { + snd_pcm_uframes_t maxBufferSize; + snd_pcm_uframes_t maxBufferSizeCapture, maxBufferSizePlayback; + ENSURE_( snd_pcm_hw_params_get_buffer_size_max( hwParamsCapture, &maxBufferSizeCapture ), paUnanticipatedHostError ); + ENSURE_( snd_pcm_hw_params_get_buffer_size_max( hwParamsPlayback, &maxBufferSizePlayback ), paUnanticipatedHostError ); + maxBufferSize = PA_MIN( maxBufferSizeCapture, maxBufferSizePlayback ); + + desiredBufSz = PA_MIN( desiredBufSz, maxBufferSize ); + } + + /* Find the closest power of 2 */ + e = ilogb( minPeriodSize ); + if( minPeriodSize & (minPeriodSize - 1) ) + e += 1; + periodSize = (snd_pcm_uframes_t)pow( 2, e ); + + while( periodSize <= maxPeriodSize ) + { + if( snd_pcm_hw_params_test_period_size( self->playback.pcm, hwParamsPlayback, periodSize, 0 ) >= 0 && + snd_pcm_hw_params_test_period_size( self->capture.pcm, hwParamsCapture, periodSize, 0 ) >= 0 ) + { + /* OK! */ + break; + } + + periodSize *= 2; + } + + optimalPeriodSize = PA_MAX( desiredBufSz / numPeriods, minPeriodSize ); + optimalPeriodSize = PA_MIN( optimalPeriodSize, maxPeriodSize ); + + /* Find the closest power of 2 */ + e = ilogb( optimalPeriodSize ); + if( optimalPeriodSize & (optimalPeriodSize - 1) ) + e += 1; + optimalPeriodSize = (snd_pcm_uframes_t)pow( 2, e ); + + while( optimalPeriodSize >= periodSize ) + { + if( snd_pcm_hw_params_test_period_size( self->capture.pcm, hwParamsCapture, optimalPeriodSize, 0 ) + >= 0 && snd_pcm_hw_params_test_period_size( self->playback.pcm, hwParamsPlayback, + optimalPeriodSize, 0 ) >= 0 ) + { + break; + } + optimalPeriodSize /= 2; + } + + if( optimalPeriodSize > periodSize ) + periodSize = optimalPeriodSize; + + if( periodSize <= maxPeriodSize ) + { + /* Looks good, the periodSize _should_ be acceptable by both devices */ + ENSURE_( snd_pcm_hw_params_set_period_size( self->capture.pcm, hwParamsCapture, periodSize, 0 ), + paUnanticipatedHostError ); + ENSURE_( snd_pcm_hw_params_set_period_size( self->playback.pcm, hwParamsPlayback, periodSize, 0 ), + paUnanticipatedHostError ); + self->capture.framesPerBuffer = self->playback.framesPerBuffer = periodSize; + framesPerHostBuffer = periodSize; + } + else + { + /* Unable to find a common period size, oh well */ + optimalPeriodSize = PA_MAX( desiredBufSz / numPeriods, minPeriodSize ); + optimalPeriodSize = PA_MIN( optimalPeriodSize, maxPeriodSize ); + + self->capture.framesPerBuffer = optimalPeriodSize; + dir = 0; + ENSURE_( snd_pcm_hw_params_set_period_size_near( self->capture.pcm, hwParamsCapture, &self->capture.framesPerBuffer, &dir ), + paUnanticipatedHostError ); + self->playback.framesPerBuffer = optimalPeriodSize; + dir = 0; + ENSURE_( snd_pcm_hw_params_set_period_size_near( self->playback.pcm, hwParamsPlayback, &self->playback.framesPerBuffer, &dir ), + paUnanticipatedHostError ); + framesPerHostBuffer = PA_MAX( self->capture.framesPerBuffer, self->playback.framesPerBuffer ); + *hostBufferSizeMode = paUtilBoundedHostBufferSize; + } + } + else + { + /* We choose the simple route and determine a suitable number of frames per buffer for one component of + * the stream, then we hope that this will work for the other component too (it should!). + */ + + unsigned maxPeriods = 0; + PaAlsaStreamComponent* first = &self->capture, * second = &self->playback; + const PaStreamParameters* firstStreamParams = inputParameters; + snd_pcm_hw_params_t* firstHwParams = hwParamsCapture, * secondHwParams = hwParamsPlayback; + + dir = 0; + ENSURE_( snd_pcm_hw_params_get_periods_max( hwParamsPlayback, &maxPeriods, &dir ), paUnanticipatedHostError ); + if( maxPeriods < numPeriods ) + { + /* The playback component is trickier to get right, try that first */ + first = &self->playback; + second = &self->capture; + firstStreamParams = outputParameters; + firstHwParams = hwParamsPlayback; + secondHwParams = hwParamsCapture; + } + + PA_ENSURE( PaAlsaStreamComponent_DetermineFramesPerBuffer( first, firstStreamParams, framesPerUserBuffer, + sampleRate, firstHwParams, &accurate ) ); + + second->framesPerBuffer = first->framesPerBuffer; + dir = 0; + ENSURE_( snd_pcm_hw_params_set_period_size_near( second->pcm, secondHwParams, &second->framesPerBuffer, &dir ), + paUnanticipatedHostError ); + if( self->capture.framesPerBuffer == self->playback.framesPerBuffer ) + { + framesPerHostBuffer = self->capture.framesPerBuffer; + } + else + { + framesPerHostBuffer = PA_MAX( self->capture.framesPerBuffer, self->playback.framesPerBuffer ); + *hostBufferSizeMode = paUtilBoundedHostBufferSize; + } + } + } + else /* half-duplex is a slightly simpler case */ + { + if( self->capture.pcm ) + { + PA_ENSURE( PaAlsaStreamComponent_DetermineFramesPerBuffer( &self->capture, inputParameters, framesPerUserBuffer, + sampleRate, hwParamsCapture, &accurate) ); + framesPerHostBuffer = self->capture.framesPerBuffer; + } + else + { + assert( self->playback.pcm ); + PA_ENSURE( PaAlsaStreamComponent_DetermineFramesPerBuffer( &self->playback, outputParameters, framesPerUserBuffer, + sampleRate, hwParamsPlayback, &accurate ) ); + framesPerHostBuffer = self->playback.framesPerBuffer; + } + } + + PA_UNLESS( framesPerHostBuffer != 0, paInternalError ); + self->maxFramesPerHostBuffer = framesPerHostBuffer; + + if( !accurate ) + { + /* Don't know the exact size per host buffer */ + *hostBufferSizeMode = paUtilBoundedHostBufferSize; + /* Raise upper bound */ + ++self->maxFramesPerHostBuffer; + } + +error: + return result; +} + +/** Set up ALSA stream parameters. + * + */ +static PaError PaAlsaStream_Configure( PaAlsaStream *self, const PaStreamParameters *inParams, const PaStreamParameters* + outParams, double sampleRate, unsigned long framesPerUserBuffer, double* inputLatency, double* outputLatency, + PaUtilHostBufferSizeMode* hostBufferSizeMode ) +{ + PaError result = paNoError; + double realSr = sampleRate; + snd_pcm_hw_params_t* hwParamsCapture, * hwParamsPlayback; + + snd_pcm_hw_params_alloca( &hwParamsCapture ); + snd_pcm_hw_params_alloca( &hwParamsPlayback ); + + if( self->capture.pcm ) + PA_ENSURE( PaAlsaStreamComponent_InitialConfigure( &self->capture, inParams, self->primeBuffers, hwParamsCapture, + &realSr ) ); + if( self->playback.pcm ) + PA_ENSURE( PaAlsaStreamComponent_InitialConfigure( &self->playback, outParams, self->primeBuffers, hwParamsPlayback, + &realSr ) ); + + PA_ENSURE( PaAlsaStream_DetermineFramesPerBuffer( self, realSr, inParams, outParams, framesPerUserBuffer, + hwParamsCapture, hwParamsPlayback, hostBufferSizeMode ) ); + + if( self->capture.pcm ) + { + assert( self->capture.framesPerBuffer != 0 ); + PA_ENSURE( PaAlsaStreamComponent_FinishConfigure( &self->capture, hwParamsCapture, inParams, self->primeBuffers, realSr, + inputLatency ) ); + PA_DEBUG(( "%s: Capture period size: %lu, latency: %f\n", __FUNCTION__, self->capture.framesPerBuffer, *inputLatency )); + } + if( self->playback.pcm ) + { + assert( self->playback.framesPerBuffer != 0 ); + PA_ENSURE( PaAlsaStreamComponent_FinishConfigure( &self->playback, hwParamsPlayback, outParams, self->primeBuffers, realSr, + outputLatency ) ); + PA_DEBUG(( "%s: Playback period size: %lu, latency: %f\n", __FUNCTION__, self->playback.framesPerBuffer, *outputLatency )); + } + + /* Should be exact now */ + self->streamRepresentation.streamInfo.sampleRate = realSr; + + /* this will cause the two streams to automatically start/stop/prepare in sync. + * We only need to execute these operations on one of the pair. + * A: We don't want to do this on a blocking stream. + */ + if( self->callbackMode && self->capture.pcm && self->playback.pcm ) + { + int err = snd_pcm_link( self->capture.pcm, self->playback.pcm ); + if( err == 0 ) + self->pcmsSynced = 1; + else + PA_DEBUG(( "%s: Unable to sync pcms: %s\n", __FUNCTION__, snd_strerror( err ) )); + } + + { + unsigned long minFramesPerHostBuffer = PA_MIN( self->capture.pcm ? self->capture.framesPerBuffer : ULONG_MAX, + self->playback.pcm ? self->playback.framesPerBuffer : ULONG_MAX ); + self->pollTimeout = CalculatePollTimeout( self, minFramesPerHostBuffer ); /* Period in msecs, rounded up */ + + /* Time before watchdog unthrottles realtime thread == 1/4 of period time in msecs */ + /* self->threading.throttledSleepTime = (unsigned long) (minFramesPerHostBuffer / sampleRate / 4 * 1000); */ + } + + if( self->callbackMode ) + { + /* If the user expects a certain number of frames per callback we will either have to rely on block adaption + * (framesPerHostBuffer is not an integer multiple of framesPerBuffer) or we can simply align the number + * of host buffer frames with what the user specified */ + if( self->framesPerUserBuffer != paFramesPerBufferUnspecified ) + { + /* self->alignFrames = 1; */ + + /* Unless the ratio between number of host and user buffer frames is an integer we will have to rely + * on block adaption */ + /* + if( framesPerHostBuffer % framesPerBuffer != 0 || (self->capture.pcm && self->playback.pcm && + self->capture.framesPerBuffer != self->playback.framesPerBuffer) ) + self->useBlockAdaption = 1; + else + self->alignFrames = 1; + */ + } + } + +error: + return result; +} + +static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi, + PaStream** s, + const PaStreamParameters *inputParameters, + const PaStreamParameters *outputParameters, + double sampleRate, + unsigned long framesPerBuffer, + PaStreamFlags streamFlags, + PaStreamCallback* callback, + void *userData ) +{ + PaError result = paNoError; + PaAlsaHostApiRepresentation *alsaHostApi = (PaAlsaHostApiRepresentation*)hostApi; + PaAlsaStream *stream = NULL; + PaSampleFormat hostInputSampleFormat = 0, hostOutputSampleFormat = 0; + PaSampleFormat inputSampleFormat = 0, outputSampleFormat = 0; + int numInputChannels = 0, numOutputChannels = 0; + PaTime inputLatency, outputLatency; + /* Operate with fixed host buffer size by default, since other modes will invariably lead to block adaption */ + /* XXX: Use Bounded by default? Output tends to get stuttery with Fixed ... */ + PaUtilHostBufferSizeMode hostBufferSizeMode = paUtilFixedHostBufferSize; + + if( (streamFlags & paPlatformSpecificFlags) != 0 ) + return paInvalidFlag; + + if( inputParameters ) + { + PA_ENSURE( ValidateParameters( inputParameters, hostApi, StreamDirection_In ) ); + + numInputChannels = inputParameters->channelCount; + inputSampleFormat = inputParameters->sampleFormat; + } + if( outputParameters ) + { + PA_ENSURE( ValidateParameters( outputParameters, hostApi, StreamDirection_Out ) ); + + numOutputChannels = outputParameters->channelCount; + outputSampleFormat = outputParameters->sampleFormat; + } + + /* XXX: Why do we support this anyway? */ + if( framesPerBuffer == paFramesPerBufferUnspecified && getenv( "PA_ALSA_PERIODSIZE" ) != NULL ) + { + PA_DEBUG(( "%s: Getting framesPerBuffer from environment\n", __FUNCTION__ )); + framesPerBuffer = atoi( getenv("PA_ALSA_PERIODSIZE") ); + } + + PA_UNLESS( stream = (PaAlsaStream*)PaUtil_AllocateMemory( sizeof(PaAlsaStream) ), paInsufficientMemory ); + PA_ENSURE( PaAlsaStream_Initialize( stream, alsaHostApi, inputParameters, outputParameters, sampleRate, + framesPerBuffer, callback, streamFlags, userData ) ); + + PA_ENSURE( PaAlsaStream_Configure( stream, inputParameters, outputParameters, sampleRate, framesPerBuffer, + &inputLatency, &outputLatency, &hostBufferSizeMode ) ); + hostInputSampleFormat = stream->capture.hostSampleFormat; + hostOutputSampleFormat = stream->playback.hostSampleFormat; + + PA_ENSURE( PaUtil_InitializeBufferProcessor( &stream->bufferProcessor, + numInputChannels, inputSampleFormat, hostInputSampleFormat, + numOutputChannels, outputSampleFormat, hostOutputSampleFormat, + sampleRate, streamFlags, framesPerBuffer, stream->maxFramesPerHostBuffer, + hostBufferSizeMode, callback, userData ) ); + + /* Ok, buffer processor is initialized, now we can deduce it's latency */ + if( numInputChannels > 0 ) + stream->streamRepresentation.streamInfo.inputLatency = inputLatency + PaUtil_GetBufferProcessorInputLatency( + &stream->bufferProcessor ); + if( numOutputChannels > 0 ) + stream->streamRepresentation.streamInfo.outputLatency = outputLatency + PaUtil_GetBufferProcessorOutputLatency( + &stream->bufferProcessor ); + + *s = (PaStream*)stream; + + return result; + +error: + if( stream ) + { + PA_DEBUG(( "%s: Stream in error, terminating\n", __FUNCTION__ )); + PaAlsaStream_Terminate( stream ); + } + + return result; +} + +static PaError CloseStream( PaStream* s ) +{ + PaError result = paNoError; + PaAlsaStream *stream = (PaAlsaStream*)s; + + PaUtil_TerminateBufferProcessor( &stream->bufferProcessor ); + PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation ); + + PaAlsaStream_Terminate( stream ); + + return result; +} + +static void SilenceBuffer( PaAlsaStream *stream ) +{ + const snd_pcm_channel_area_t *areas; + snd_pcm_uframes_t frames = (snd_pcm_uframes_t)snd_pcm_avail_update( stream->playback.pcm ), offset; + + snd_pcm_mmap_begin( stream->playback.pcm, &areas, &offset, &frames ); + snd_pcm_areas_silence( areas, offset, stream->playback.numHostChannels, frames, stream->playback.nativeFormat ); + snd_pcm_mmap_commit( stream->playback.pcm, offset, frames ); +} + +/** Start/prepare pcm(s) for streaming. + * + * Depending on wether the stream is in callback or blocking mode, we will respectively start or simply + * prepare the playback pcm. If the buffer has _not_ been primed, we will in callback mode prepare and + * silence the buffer before starting playback. In blocking mode we simply prepare, as the playback will + * be started automatically as the user writes to output. + * + * The capture pcm, however, will simply be prepared and started. + */ +static PaError AlsaStart( PaAlsaStream *stream, int priming ) +{ + PaError result = paNoError; + + if( stream->playback.pcm ) + { + if( stream->callbackMode ) + { + if( !priming ) + { + /* Buffer isn't primed, so prepare and silence */ + ENSURE_( snd_pcm_prepare( stream->playback.pcm ), paUnanticipatedHostError ); + SilenceBuffer( stream ); + } + ENSURE_( snd_pcm_start( stream->playback.pcm ), paUnanticipatedHostError ); + } + else + ENSURE_( snd_pcm_prepare( stream->playback.pcm ), paUnanticipatedHostError ); + } + if( stream->capture.pcm && !stream->pcmsSynced ) + { + ENSURE_( snd_pcm_prepare( stream->capture.pcm ), paUnanticipatedHostError ); + /* For a blocking stream we want to start capture as well, since nothing will happen otherwise */ + ENSURE_( snd_pcm_start( stream->capture.pcm ), paUnanticipatedHostError ); + } + +end: + return result; +error: + goto end; +} + +/** Utility function for determining if pcms are in running state. + * + */ +#if 0 +static int IsRunning( PaAlsaStream *stream ) +{ + int result = 0; + + PA_ENSURE( PaUnixMutex_Lock( &stream->stateMtx ) ); + if( stream->capture.pcm ) + { + snd_pcm_state_t capture_state = snd_pcm_state( stream->capture.pcm ); + + if( capture_state == SND_PCM_STATE_RUNNING || capture_state == SND_PCM_STATE_XRUN + || capture_state == SND_PCM_STATE_DRAINING ) + { + result = 1; + goto end; + } + } + + if( stream->playback.pcm ) + { + snd_pcm_state_t playback_state = snd_pcm_state( stream->playback.pcm ); + + if( playback_state == SND_PCM_STATE_RUNNING || playback_state == SND_PCM_STATE_XRUN + || playback_state == SND_PCM_STATE_DRAINING ) + { + result = 1; + goto end; + } + } + +end: + ASSERT_CALL_( PaUnixMutex_Unlock( &stream->stateMtx ), paNoError ); + return result; +error: + goto error; +} +#endif + +static PaError StartStream( PaStream *s ) +{ + PaError result = paNoError; + PaAlsaStream* stream = (PaAlsaStream*)s; + int streamStarted = 0; /* So we can know wether we need to take the stream down */ + + /* Ready the processor */ + PaUtil_ResetBufferProcessor( &stream->bufferProcessor ); + + /* Set now, so we can test for activity further down */ + stream->isActive = 1; + + if( stream->callbackMode ) + { + PA_ENSURE( PaUnixThread_New( &stream->thread, &CallbackThreadFunc, stream, 1., stream->rtSched ) ); + } + else + { + PA_ENSURE( AlsaStart( stream, 0 ) ); + streamStarted = 1; + } + +end: + return result; +error: + if( streamStarted ) + { + AbortStream( stream ); + } + stream->isActive = 0; + + goto end; +} + +/** Stop PCM handle, either softly or abruptly. + */ +static PaError AlsaStop( PaAlsaStream *stream, int abort ) +{ + PaError result = paNoError; + /* XXX: snd_pcm_drain tends to lock up, avoid it until we find out more */ + abort = 1; + /* + if( stream->capture.pcm && !strcmp( Pa_GetDeviceInfo( stream->capture.device )->name, + "dmix" ) ) + { + abort = 1; + } + else if( stream->playback.pcm && !strcmp( Pa_GetDeviceInfo( stream->playback.device )->name, + "dmix" ) ) + { + abort = 1; + } + */ + + if( abort ) + { + if( stream->playback.pcm ) + { + ENSURE_( snd_pcm_drop( stream->playback.pcm ), paUnanticipatedHostError ); + } + if( stream->capture.pcm && !stream->pcmsSynced ) + { + ENSURE_( snd_pcm_drop( stream->capture.pcm ), paUnanticipatedHostError ); + } + + PA_DEBUG(( "%s: Dropped frames\n", __FUNCTION__ )); + } + else + { + if( stream->playback.pcm ) + { + ENSURE_( snd_pcm_nonblock( stream->playback.pcm, 0 ), paUnanticipatedHostError ); + if( snd_pcm_drain( stream->playback.pcm ) < 0 ) + { + PA_DEBUG(( "%s: Draining playback handle failed!\n", __FUNCTION__ )); + } + } + if( stream->capture.pcm && !stream->pcmsSynced ) + { + /* We don't need to retrieve any remaining frames */ + if( snd_pcm_drain( stream->capture.pcm ) < 0 ) + { + PA_DEBUG(( "%s: Draining capture handle failed!\n", __FUNCTION__ )); + } + } + } + +end: + return result; +error: + goto end; +} + +/** Stop or abort stream. + * + * If a stream is in callback mode we will have to inspect wether the background thread has + * finished, or we will have to take it out. In either case we join the thread before + * returning. In blocking mode, we simply tell ALSA to stop abruptly (abort) or finish + * buffers (drain) + * + * Stream will be considered inactive (!PaAlsaStream::isActive) after a call to this function + */ +static PaError RealStop( PaAlsaStream *stream, int abort ) +{ + PaError result = paNoError; + + /* First deal with the callback thread, cancelling and/or joining + * it if necessary + */ + if( stream->callbackMode ) + { + PaError threadRes; + stream->callbackAbort = abort; + + if( !abort ) + { + PA_DEBUG(( "Stopping callback\n" )); + } + PA_ENSURE( PaUnixThread_Terminate( &stream->thread, !abort, &threadRes ) ); + if( threadRes != paNoError ) + { + PA_DEBUG(( "Callback thread returned: %d\n", threadRes )); + } +#if 0 + if( watchdogRes != paNoError ) + PA_DEBUG(( "Watchdog thread returned: %d\n", watchdogRes )); +#endif + + stream->callback_finished = 0; + } + else + { + PA_ENSURE( AlsaStop( stream, abort ) ); + } + + stream->isActive = 0; + +end: + return result; + +error: + goto end; +} + +static PaError StopStream( PaStream *s ) +{ + return RealStop( (PaAlsaStream *) s, 0 ); +} + +static PaError AbortStream( PaStream *s ) +{ + return RealStop( (PaAlsaStream * ) s, 1 ); +} + +/** The stream is considered stopped before StartStream, or AFTER a call to Abort/StopStream (callback + * returning !paContinue is not considered) + * + */ +static PaError IsStreamStopped( PaStream *s ) +{ + PaAlsaStream *stream = (PaAlsaStream *)s; + + /* callback_finished indicates we need to join callback thread (ie. in Abort/StopStream) */ + return !IsStreamActive( s ) && !stream->callback_finished; +} + +static PaError IsStreamActive( PaStream *s ) +{ + PaAlsaStream *stream = (PaAlsaStream*)s; + return stream->isActive; +} + +static PaTime GetStreamTime( PaStream *s ) +{ + PaAlsaStream *stream = (PaAlsaStream*)s; + + snd_timestamp_t timestamp; + snd_pcm_status_t* status; + snd_pcm_status_alloca( &status ); + + /* TODO: what if we have both? does it really matter? */ + + /* TODO: if running in callback mode, this will mean + * libasound routines are being called from multiple threads. + * need to verify that libasound is thread-safe. */ + + if( stream->capture.pcm ) + { + snd_pcm_status( stream->capture.pcm, status ); + } + else if( stream->playback.pcm ) + { + snd_pcm_status( stream->playback.pcm, status ); + } + + snd_pcm_status_get_tstamp( status, ×tamp ); + return timestamp.tv_sec + (PaTime)timestamp.tv_usec / 1e6; +} + +static double GetStreamCpuLoad( PaStream* s ) +{ + PaAlsaStream *stream = (PaAlsaStream*)s; + + return PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer ); +} + +static int SetApproximateSampleRate( snd_pcm_t *pcm, snd_pcm_hw_params_t *hwParams, double sampleRate ) +{ + unsigned long approx = (unsigned long) sampleRate; + int dir = 0; + double fraction = sampleRate - approx; + + assert( pcm && hwParams ); + + if( fraction > 0.0 ) + { + if( fraction > 0.5 ) + { + ++approx; + dir = -1; + } + else + dir = 1; + } + + return snd_pcm_hw_params_set_rate( pcm, hwParams, approx, dir ); +} + +/* Return exact sample rate in param sampleRate */ +static int GetExactSampleRate( snd_pcm_hw_params_t *hwParams, double *sampleRate ) +{ + unsigned int num, den; + int err; + + assert( hwParams ); + + err = snd_pcm_hw_params_get_rate_numden( hwParams, &num, &den ); + *sampleRate = (double) num / den; + + return err; +} + +/* Utility functions for blocking/callback interfaces */ + +/* Atomic restart of stream (we don't want the intermediate state visible) */ +static PaError AlsaRestart( PaAlsaStream *stream ) +{ + PaError result = paNoError; + + PA_ENSURE( PaUnixMutex_Lock( &stream->stateMtx ) ); + PA_ENSURE( AlsaStop( stream, 0 ) ); + PA_ENSURE( AlsaStart( stream, 0 ) ); + + PA_DEBUG(( "%s: Restarted audio\n", __FUNCTION__ )); + +error: + PA_ENSURE( PaUnixMutex_Unlock( &stream->stateMtx ) ); + + return result; +} + +/** Recover from xrun state. + * + */ +static PaError PaAlsaStream_HandleXrun( PaAlsaStream *self ) +{ + PaError result = paNoError; + snd_pcm_status_t *st; + PaTime now = PaUtil_GetTime(); + snd_timestamp_t t; + + snd_pcm_status_alloca( &st ); + + if( self->playback.pcm ) + { + snd_pcm_status( self->playback.pcm, st ); + if( snd_pcm_status_get_state( st ) == SND_PCM_STATE_XRUN ) + { + snd_pcm_status_get_trigger_tstamp( st, &t ); + self->underrun = now * 1000 - ((PaTime) t.tv_sec * 1000 + (PaTime) t.tv_usec / 1000); + } + } + if( self->capture.pcm ) + { + snd_pcm_status( self->capture.pcm, st ); + if( snd_pcm_status_get_state( st ) == SND_PCM_STATE_XRUN ) + { + snd_pcm_status_get_trigger_tstamp( st, &t ); + self->overrun = now * 1000 - ((PaTime) t.tv_sec * 1000 + (PaTime) t.tv_usec / 1000); + } + } + + PA_ENSURE( AlsaRestart( self ) ); + +end: + return result; +error: + goto end; +} + +/** Decide if we should continue polling for specified direction, eventually adjust the poll timeout. + * + */ +static PaError ContinuePoll( const PaAlsaStream *stream, StreamDirection streamDir, int *pollTimeout, int *continuePoll ) +{ + PaError result = paNoError; + snd_pcm_sframes_t delay, margin; + int err; + const PaAlsaStreamComponent *component = NULL, *otherComponent = NULL; + + *continuePoll = 1; + + if( StreamDirection_In == streamDir ) + { + component = &stream->capture; + otherComponent = &stream->playback; + } + else + { + component = &stream->playback; + otherComponent = &stream->capture; + } + + /* ALSA docs say that negative delay should indicate xrun, but in my experience snd_pcm_delay returns -EPIPE */ + if( (err = snd_pcm_delay( otherComponent->pcm, &delay )) < 0 ) + { + if( err == -EPIPE ) + { + /* Xrun */ + *continuePoll = 0; + goto error; + } + + ENSURE_( err, paUnanticipatedHostError ); + } + + if( StreamDirection_Out == streamDir ) + { + /* Number of eligible frames before capture overrun */ + delay = otherComponent->bufferSize - delay; + } + margin = delay - otherComponent->framesPerBuffer / 2; + + if( margin < 0 ) + { + PA_DEBUG(( "%s: Stopping poll for %s\n", __FUNCTION__, StreamDirection_In == streamDir ? "capture" : "playback" )); + *continuePoll = 0; + } + else if( margin < otherComponent->framesPerBuffer ) + { + *pollTimeout = CalculatePollTimeout( stream, margin ); + PA_DEBUG(( "%s: Trying to poll again for %s frames, pollTimeout: %d\n", + __FUNCTION__, StreamDirection_In == streamDir ? "capture" : "playback", *pollTimeout )); + } + +error: + return result; +} + +/* Callback interface */ + +static void OnExit( void *data ) +{ + PaAlsaStream *stream = (PaAlsaStream *) data; + + assert( data ); + + PaUtil_ResetCpuLoadMeasurer( &stream->cpuLoadMeasurer ); + + stream->callback_finished = 1; /* Let the outside world know stream was stopped in callback */ + PA_DEBUG(( "%s: Stopping ALSA handles\n", __FUNCTION__ )); + AlsaStop( stream, stream->callbackAbort ); + + PA_DEBUG(( "%s: Stoppage\n", __FUNCTION__ )); + + /* Eventually notify user all buffers have played */ + if( stream->streamRepresentation.streamFinishedCallback ) + { + stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData ); + } + stream->isActive = 0; +} + +static void CalculateTimeInfo( PaAlsaStream *stream, PaStreamCallbackTimeInfo *timeInfo ) +{ + snd_pcm_status_t *capture_status, *playback_status; + snd_timestamp_t capture_timestamp, playback_timestamp; + PaTime capture_time = 0., playback_time = 0.; + + snd_pcm_status_alloca( &capture_status ); + snd_pcm_status_alloca( &playback_status ); + + if( stream->capture.pcm ) + { + snd_pcm_sframes_t capture_delay; + + snd_pcm_status( stream->capture.pcm, capture_status ); + snd_pcm_status_get_tstamp( capture_status, &capture_timestamp ); + + capture_time = capture_timestamp.tv_sec + + ((PaTime)capture_timestamp.tv_usec / 1000000.0); + timeInfo->currentTime = capture_time; + + capture_delay = snd_pcm_status_get_delay( capture_status ); + timeInfo->inputBufferAdcTime = timeInfo->currentTime - + (PaTime)capture_delay / stream->streamRepresentation.streamInfo.sampleRate; + } + if( stream->playback.pcm ) + { + snd_pcm_sframes_t playback_delay; + + snd_pcm_status( stream->playback.pcm, playback_status ); + snd_pcm_status_get_tstamp( playback_status, &playback_timestamp ); + + playback_time = playback_timestamp.tv_sec + + ((PaTime)playback_timestamp.tv_usec / 1000000.0); + + if( stream->capture.pcm ) /* Full duplex */ + { + /* Hmm, we have both a playback and a capture timestamp. + * Hopefully they are the same... */ + if( fabs( capture_time - playback_time ) > 0.01 ) + PA_DEBUG(("Capture time and playback time differ by %f\n", fabs(capture_time-playback_time))); + } + else + timeInfo->currentTime = playback_time; + + playback_delay = snd_pcm_status_get_delay( playback_status ); + timeInfo->outputBufferDacTime = timeInfo->currentTime + + (PaTime)playback_delay / stream->streamRepresentation.streamInfo.sampleRate; + } +} + +/** Called after buffer processing is finished. + * + * A number of mmapped frames is committed, it is possible that an xrun has occurred in the meantime. + * + * @param numFrames The number of frames that has been processed + * @param xrun Return whether an xrun has occurred + */ +static PaError PaAlsaStreamComponent_EndProcessing( PaAlsaStreamComponent *self, unsigned long numFrames, int *xrun ) +{ + PaError result = paNoError; + int res; + + /* @concern FullDuplex It is possible that only one direction is marked ready after polling, and processed + * afterwards + */ + if( !self->ready ) + goto end; + + res = snd_pcm_mmap_commit( self->pcm, self->offset, numFrames ); + if( res == -EPIPE || res == -ESTRPIPE ) + { + *xrun = 1; + } + else + { + ENSURE_( res, paUnanticipatedHostError ); + } + +end: +error: + return result; +} + +/* Extract buffer from channel area */ +static unsigned char *ExtractAddress( const snd_pcm_channel_area_t *area, snd_pcm_uframes_t offset ) +{ + return (unsigned char *) area->addr + (area->first + offset * area->step) / 8; +} + +/** Do necessary adaption between user and host channels. + * + @concern ChannelAdaption Adapting between user and host channels can involve silencing unused channels and + duplicating mono information if host outputs come in pairs. + */ +static PaError PaAlsaStreamComponent_DoChannelAdaption( PaAlsaStreamComponent *self, PaUtilBufferProcessor *bp, int numFrames ) +{ + PaError result = paNoError; + unsigned char *p; + int i; + int unusedChans = self->numHostChannels - self->numUserChannels; + unsigned char *src, *dst; + int convertMono = (self->numHostChannels % 2) == 0 && (self->numUserChannels % 2) != 0; + + assert( StreamDirection_Out == self->streamDir ); + + if( self->hostInterleaved ) + { + int swidth = snd_pcm_format_size( self->nativeFormat, 1 ); + unsigned char *buffer = ExtractAddress( self->channelAreas, self->offset ); + + /* Start after the last user channel */ + p = buffer + self->numUserChannels * swidth; + + if( convertMono ) + { + /* Convert the last user channel into stereo pair */ + src = buffer + (self->numUserChannels - 1) * swidth; + for( i = 0; i < numFrames; ++i ) + { + dst = src + swidth; + memcpy( dst, src, swidth ); + src += self->numHostChannels * swidth; + } + + /* Don't touch the channel we just wrote to */ + p += swidth; + --unusedChans; + } + + if( unusedChans > 0 ) + { + /* Silence unused output channels */ + for( i = 0; i < numFrames; ++i ) + { + memset( p, 0, swidth * unusedChans ); + p += self->numHostChannels * swidth; + } + } + } + else + { + /* We extract the last user channel */ + if( convertMono ) + { + ENSURE_( snd_pcm_area_copy( self->channelAreas + self->numUserChannels, self->offset, self->channelAreas + + (self->numUserChannels - 1), self->offset, numFrames, self->nativeFormat ), paUnanticipatedHostError ); + --unusedChans; + } + if( unusedChans > 0 ) + { + snd_pcm_areas_silence( self->channelAreas + (self->numHostChannels - unusedChans), self->offset, unusedChans, numFrames, + self->nativeFormat ); + } + } + +error: + return result; +} + +static PaError PaAlsaStream_EndProcessing( PaAlsaStream *self, unsigned long numFrames, int *xrunOccurred ) +{ + PaError result = paNoError; + int xrun = 0; + + if( self->capture.pcm ) + { + PA_ENSURE( PaAlsaStreamComponent_EndProcessing( &self->capture, numFrames, &xrun ) ); + } + if( self->playback.pcm ) + { + if( self->playback.numHostChannels > self->playback.numUserChannels ) + { + PA_ENSURE( PaAlsaStreamComponent_DoChannelAdaption( &self->playback, &self->bufferProcessor, numFrames ) ); + } + PA_ENSURE( PaAlsaStreamComponent_EndProcessing( &self->playback, numFrames, &xrun ) ); + } + +error: + *xrunOccurred = xrun; + return result; +} + +/** Update the number of available frames. + * + */ +static PaError PaAlsaStreamComponent_GetAvailableFrames( PaAlsaStreamComponent *self, unsigned long *numFrames, int *xrunOccurred ) +{ + PaError result = paNoError; + snd_pcm_sframes_t framesAvail = snd_pcm_avail_update( self->pcm ); + *xrunOccurred = 0; + + if( -EPIPE == framesAvail ) + { + *xrunOccurred = 1; + framesAvail = 0; + } + else + { + ENSURE_( framesAvail, paUnanticipatedHostError ); + } + + *numFrames = framesAvail; + +error: + return result; +} + +/** Fill in pollfd objects. + */ +static PaError PaAlsaStreamComponent_BeginPolling( PaAlsaStreamComponent* self, struct pollfd* pfds ) +{ + PaError result = paNoError; + int ret = snd_pcm_poll_descriptors( self->pcm, pfds, self->nfds ); + (void)ret; /* Prevent unused variable warning if asserts are turned off */ + assert( ret == self->nfds ); + + self->ready = 0; + + return result; +} + +/** Examine results from poll(). + * + * @param pfds pollfds to inspect + * @param shouldPoll Should we continue to poll + * @param xrun Has an xrun occurred + */ +static PaError PaAlsaStreamComponent_EndPolling( PaAlsaStreamComponent* self, struct pollfd* pfds, int* shouldPoll, int* xrun ) +{ + PaError result = paNoError; + unsigned short revents; + + ENSURE_( snd_pcm_poll_descriptors_revents( self->pcm, pfds, self->nfds, &revents ), paUnanticipatedHostError ); + if( revents != 0 ) + { + if( revents & POLLERR ) + { + *xrun = 1; + } + else + self->ready = 1; + + *shouldPoll = 0; + } + +error: + return result; +} + +/** Return the number of available frames for this stream. + * + * @concern FullDuplex The minimum available for the two directions is calculated, it might be desirable to ignore + * one direction however (not marked ready from poll), so this is controlled by queryCapture and queryPlayback. + * + * @param queryCapture Check available for capture + * @param queryPlayback Check available for playback + * @param available The returned number of frames + * @param xrunOccurred Return whether an xrun has occurred + */ +static PaError PaAlsaStream_GetAvailableFrames( PaAlsaStream *self, int queryCapture, int queryPlayback, unsigned long + *available, int *xrunOccurred ) +{ + PaError result = paNoError; + unsigned long captureFrames, playbackFrames; + *xrunOccurred = 0; + + assert( queryCapture || queryPlayback ); + + if( queryCapture ) + { + assert( self->capture.pcm ); + PA_ENSURE( PaAlsaStreamComponent_GetAvailableFrames( &self->capture, &captureFrames, xrunOccurred ) ); + if( *xrunOccurred ) + { + goto end; + } + } + if( queryPlayback ) + { + assert( self->playback.pcm ); + PA_ENSURE( PaAlsaStreamComponent_GetAvailableFrames( &self->playback, &playbackFrames, xrunOccurred ) ); + if( *xrunOccurred ) + { + goto end; + } + } + + if( queryCapture && queryPlayback ) + { + *available = PA_MIN( captureFrames, playbackFrames ); + /*PA_DEBUG(("capture: %lu, playback: %lu, combined: %lu\n", captureFrames, playbackFrames, *available));*/ + } + else if( queryCapture ) + { + *available = captureFrames; + } + else + { + *available = playbackFrames; + } + +end: +error: + return result; +} + +/** Wait for and report available buffer space from ALSA. + * + * Unless ALSA reports a minimum of frames available for I/O, we poll the ALSA filedescriptors for more. + * Both of these operations can uncover xrun conditions. + * + * @concern Xruns Both polling and querying available frames can report an xrun condition. + * + * @param framesAvail Return the number of available frames + * @param xrunOccurred Return whether an xrun has occurred + */ +static PaError PaAlsaStream_WaitForFrames( PaAlsaStream *self, unsigned long *framesAvail, int *xrunOccurred ) +{ + PaError result = paNoError; + int pollPlayback = self->playback.pcm != NULL, pollCapture = self->capture.pcm != NULL; + int pollTimeout = self->pollTimeout; + int xrun = 0; + + assert( self ); + assert( framesAvail ); + + if( !self->callbackMode ) + { + /* In blocking mode we will only wait if necessary */ + PA_ENSURE( PaAlsaStream_GetAvailableFrames( self, self->capture.pcm != NULL, self->playback.pcm != NULL, + framesAvail, &xrun ) ); + if( xrun ) + { + goto end; + } + + if( *framesAvail > 0 ) + { + /* Mark pcms ready from poll */ + if( self->capture.pcm ) + self->capture.ready = 1; + if( self->playback.pcm ) + self->playback.ready = 1; + + goto end; + } + } + + while( pollPlayback || pollCapture ) + { + int totalFds = 0; + struct pollfd *capturePfds = NULL, *playbackPfds = NULL; + + pthread_testcancel(); + + if( pollCapture ) + { + capturePfds = self->pfds; + PA_ENSURE( PaAlsaStreamComponent_BeginPolling( &self->capture, capturePfds ) ); + totalFds += self->capture.nfds; + } + if( pollPlayback ) + { + playbackPfds = self->pfds + (self->capture.pcm ? self->capture.nfds : 0); + PA_ENSURE( PaAlsaStreamComponent_BeginPolling( &self->playback, playbackPfds ) ); + totalFds += self->playback.nfds; + } + + if( poll( self->pfds, totalFds, pollTimeout ) < 0 ) + { + /* XXX: Depend on preprocessor condition? */ + if( errno == EINTR ) + { + /* gdb */ + continue; + } + + /* TODO: Add macro for checking system calls */ + PA_ENSURE( paInternalError ); + } + + /* check the return status of our pfds */ + if( pollCapture ) + { + PA_ENSURE( PaAlsaStreamComponent_EndPolling( &self->capture, capturePfds, &pollCapture, &xrun ) ); + } + if( pollPlayback ) + { + PA_ENSURE( PaAlsaStreamComponent_EndPolling( &self->playback, playbackPfds, &pollPlayback, &xrun ) ); + } + if( xrun ) + { + break; + } + + /* @concern FullDuplex If only one of two pcms is ready we may want to compromise between the two. + * If there is less than half a period's worth of samples left of frames in the other pcm's buffer we will + * stop polling. + */ + if( self->capture.pcm && self->playback.pcm ) + { + if( pollCapture && !pollPlayback ) + { + PA_ENSURE( ContinuePoll( self, StreamDirection_In, &pollTimeout, &pollCapture ) ); + } + else if( pollPlayback && !pollCapture ) + { + PA_ENSURE( ContinuePoll( self, StreamDirection_Out, &pollTimeout, &pollPlayback ) ); + } + } + } + + if( !xrun ) + { + /* Get the number of available frames for the pcms that are marked ready. + * @concern FullDuplex If only one direction is marked ready (from poll), the number of frames available for + * the other direction is returned. Output is normally preferred over capture however, so capture frames may be + * discarded to avoid overrun unless paNeverDropInput is specified. + */ + int captureReady = self->capture.pcm ? self->capture.ready : 0, + playbackReady = self->playback.pcm ? self->playback.ready : 0; + PA_ENSURE( PaAlsaStream_GetAvailableFrames( self, captureReady, playbackReady, framesAvail, &xrun ) ); + + if( self->capture.pcm && self->playback.pcm ) + { + if( !self->playback.ready && !self->neverDropInput ) + { + /* Drop input, a period's worth */ + assert( self->capture.ready ); + PaAlsaStreamComponent_EndProcessing( &self->capture, PA_MIN( self->capture.framesPerBuffer, + *framesAvail ), &xrun ); + *framesAvail = 0; + self->capture.ready = 0; + } + } + else if( self->capture.pcm ) + assert( self->capture.ready ); + else + assert( self->playback.ready ); + } + +end: +error: + if( xrun ) + { + /* Recover from the xrun state */ + PA_ENSURE( PaAlsaStream_HandleXrun( self ) ); + *framesAvail = 0; + } + else + { + if( 0 != *framesAvail ) + { + /* If we're reporting frames eligible for processing, one of the handles better be ready */ + PA_UNLESS( self->capture.ready || self->playback.ready, paInternalError ); + } + } + *xrunOccurred = xrun; + + return result; +} + +/** Register per-channel ALSA buffer information with buffer processor. + * + * Mmapped buffer space is acquired from ALSA, and registered with the buffer processor. Differences between the + * number of host and user channels is taken into account. + * + * @param numFrames On entrance the number of requested frames, on exit the number of contiguously accessible frames. + */ +static PaError PaAlsaStreamComponent_RegisterChannels( PaAlsaStreamComponent* self, PaUtilBufferProcessor* bp, + unsigned long* numFrames, int* xrun ) +{ + PaError result = paNoError; + const snd_pcm_channel_area_t *areas, *area; + void (*setChannel)(PaUtilBufferProcessor *, unsigned int, void *, unsigned int) = + StreamDirection_In == self->streamDir ? PaUtil_SetInputChannel : PaUtil_SetOutputChannel; + unsigned char *buffer, *p; + int i; + unsigned long framesAvail; + + /* This _must_ be called before mmap_begin */ + PA_ENSURE( PaAlsaStreamComponent_GetAvailableFrames( self, &framesAvail, xrun ) ); + if( *xrun ) + { + *numFrames = 0; + goto end; + } + + ENSURE_( snd_pcm_mmap_begin( self->pcm, &areas, &self->offset, numFrames ), paUnanticipatedHostError ); + + if( self->hostInterleaved ) + { + int swidth = snd_pcm_format_size( self->nativeFormat, 1 ); + + p = buffer = ExtractAddress( areas, self->offset ); + for( i = 0; i < self->numUserChannels; ++i ) + { + /* We're setting the channels up to userChannels, but the stride will be hostChannels samples */ + setChannel( bp, i, p, self->numHostChannels ); + p += swidth; + } + } + else + { + for( i = 0; i < self->numUserChannels; ++i ) + { + area = areas + i; + buffer = ExtractAddress( area, self->offset ); + setChannel( bp, i, buffer, 1 ); + } + } + + /* @concern ChannelAdaption Buffer address is recorded so we can do some channel adaption later */ + self->channelAreas = (snd_pcm_channel_area_t *)areas; + +end: +error: + return result; +} + +/** Initiate buffer processing. + * + * ALSA buffers are registered with the PA buffer processor and the buffer size (in frames) set. + * + * @concern FullDuplex If both directions are being processed, the minimum amount of frames for the two directions is + * calculated. + * + * @param numFrames On entrance the number of available frames, on exit the number of received frames + * @param xrunOccurred Return whether an xrun has occurred + */ +static PaError PaAlsaStream_SetUpBuffers( PaAlsaStream* self, unsigned long* numFrames, int* xrunOccurred ) +{ + PaError result = paNoError; + unsigned long captureFrames = ULONG_MAX, playbackFrames = ULONG_MAX, commonFrames = 0; + int xrun = 0; + + if( *xrunOccurred ) + { + *numFrames = 0; + return result; + } + /* If we got here at least one of the pcm's should be marked ready */ + PA_UNLESS( self->capture.ready || self->playback.ready, paInternalError ); + + /* Extract per-channel ALSA buffer pointers and register them with the buffer processor. + * It is possible that a direction is not marked ready however, because it is out of sync with the other. + */ + if( self->capture.pcm && self->capture.ready ) + { + captureFrames = *numFrames; + PA_ENSURE( PaAlsaStreamComponent_RegisterChannels( &self->capture, &self->bufferProcessor, &captureFrames, + &xrun ) ); + } + if( self->playback.pcm && self->playback.ready ) + { + playbackFrames = *numFrames; + PA_ENSURE( PaAlsaStreamComponent_RegisterChannels( &self->playback, &self->bufferProcessor, &playbackFrames, + &xrun ) ); + } + if( xrun ) + { + /* Nothing more to do */ + assert( 0 == commonFrames ); + goto end; + } + + commonFrames = PA_MIN( captureFrames, playbackFrames ); + /* assert( commonFrames <= *numFrames ); */ + if( commonFrames > *numFrames ) + { + /* Hmmm ... how come there are more frames available than we requested!? Blah. */ + PA_DEBUG(( "%s: Common available frames are reported to be more than number requested: %lu, %lu, callbackMode: %d\n", __FUNCTION__, + commonFrames, *numFrames, self->callbackMode )); + if( self->capture.pcm ) + { + PA_DEBUG(( "%s: captureFrames: %lu, capture.ready: %d\n", __FUNCTION__, captureFrames, self->capture.ready )); + } + if( self->playback.pcm ) + { + PA_DEBUG(( "%s: playbackFrames: %lu, playback.ready: %d\n", __FUNCTION__, playbackFrames, self->playback.ready )); + } + + commonFrames = 0; + goto end; + } + + /* Inform PortAudio of the number of frames we got. + * @concern FullDuplex We might be experiencing underflow in either end; if its an input underflow, we go on + * with output. If its output underflow however, depending on the paNeverDropInput flag, we may want to simply + * discard the excess input or call the callback with paOutputOverflow flagged. + */ + if( self->capture.pcm ) + { + if( self->capture.ready ) + { + PaUtil_SetInputFrameCount( &self->bufferProcessor, commonFrames ); + } + else + { + /* We have input underflow */ + PaUtil_SetNoInput( &self->bufferProcessor ); + } + } + if( self->playback.pcm ) + { + if( self->playback.ready ) + { + PaUtil_SetOutputFrameCount( &self->bufferProcessor, commonFrames ); + } + else + { + /* We have output underflow, but keeping input data (paNeverDropInput) */ + assert( self->neverDropInput ); + assert( self->capture.pcm != NULL ); + PA_DEBUG(( "%s: Setting output buffers to NULL\n", __FUNCTION__ )); + PaUtil_SetNoOutput( &self->bufferProcessor ); + } + } + +end: + *numFrames = commonFrames; +error: + if( xrun ) + { + PA_ENSURE( PaAlsaStream_HandleXrun( self ) ); + *numFrames = 0; + } + *xrunOccurred = xrun; + + return result; +} + +/** Callback thread's function. + * + * Roughly, the workflow can be described in the following way: The number of available frames that can be processed + * directly is obtained from ALSA, we then request as much directly accessible memory as possible within this amount + * from ALSA. The buffer memory is registered with the PA buffer processor and processing is carried out with + * PaUtil_EndBufferProcessing. Finally, the number of processed frames is reported to ALSA. The processing can + * happen in several iterations untill we have consumed the known number of available frames (or an xrun is detected). + */ +static void *CallbackThreadFunc( void *userData ) +{ + PaError result = paNoError; + PaAlsaStream *stream = (PaAlsaStream*) userData; + PaStreamCallbackTimeInfo timeInfo = {0, 0, 0}; + snd_pcm_sframes_t startThreshold = 0; + int callbackResult = paContinue; + PaStreamCallbackFlags cbFlags = 0; /* We might want to keep state across iterations */ + int streamStarted = 0; + + assert( stream ); + + /* Execute OnExit when exiting */ + pthread_cleanup_push( &OnExit, stream ); + + /* Not implemented */ + assert( !stream->primeBuffers ); + + /* @concern StreamStart If the output is being primed the output pcm needs to be prepared, otherwise the + * stream is started immediately. The latter involves signaling the waiting main thread. + */ + if( stream->primeBuffers ) + { + snd_pcm_sframes_t avail; + + if( stream->playback.pcm ) + ENSURE_( snd_pcm_prepare( stream->playback.pcm ), paUnanticipatedHostError ); + if( stream->capture.pcm && !stream->pcmsSynced ) + ENSURE_( snd_pcm_prepare( stream->capture.pcm ), paUnanticipatedHostError ); + + /* We can't be certain that the whole ring buffer is available for priming, but there should be + * at least one period */ + avail = snd_pcm_avail_update( stream->playback.pcm ); + startThreshold = avail - (avail % stream->playback.framesPerBuffer); + assert( startThreshold >= stream->playback.framesPerBuffer ); + } + else + { + PA_ENSURE( PaUnixThread_PrepareNotify( &stream->thread ) ); + /* Buffer will be zeroed */ + PA_ENSURE( AlsaStart( stream, 0 ) ); + PA_ENSURE( PaUnixThread_NotifyParent( &stream->thread ) ); + + streamStarted = 1; + } + + while( 1 ) + { + unsigned long framesAvail, framesGot; + int xrun = 0; + + pthread_testcancel(); + + /* @concern StreamStop if the main thread has requested a stop and the stream has not been effectively + * stopped we signal this condition by modifying callbackResult (we'll want to flush buffered output). + */ + if( PaUnixThread_StopRequested( &stream->thread ) && paContinue == callbackResult ) + { + PA_DEBUG(( "Setting callbackResult to paComplete\n" )); + callbackResult = paComplete; + } + + if( paContinue != callbackResult ) + { + stream->callbackAbort = (paAbort == callbackResult); + if( stream->callbackAbort || + /** @concern BlockAdaption: Go on if adaption buffers are empty */ + PaUtil_IsBufferProcessorOutputEmpty( &stream->bufferProcessor ) ) + { + goto end; + } + + PA_DEBUG(( "%s: Flushing buffer processor\n", __FUNCTION__ )); + /* There is still buffered output that needs to be processed */ + } + + /* Wait for data to become available, this comes down to polling the ALSA file descriptors untill we have + * a number of available frames. + */ + PA_ENSURE( PaAlsaStream_WaitForFrames( stream, &framesAvail, &xrun ) ); + if( xrun ) + { + assert( 0 == framesAvail ); + continue; + + /* XXX: Report xruns to the user? A situation is conceivable where the callback is never invoked due + * to constant xruns, it might be desirable to notify the user of this. + */ + } + + /* Consume buffer space. Once we have a number of frames available for consumption we must retrieve the + * mmapped buffers from ALSA, this is contiguously accessible memory however, so we may receive smaller + * portions at a time than is available as a whole. Therefore we should be prepared to process several + * chunks successively. The buffers are passed to the PA buffer processor. + */ + while( framesAvail > 0 ) + { + xrun = 0; + + pthread_testcancel(); + + /** @concern Xruns Under/overflows are to be reported to the callback */ + if( stream->underrun > 0.0 ) + { + cbFlags |= paOutputUnderflow; + stream->underrun = 0.0; + } + if( stream->overrun > 0.0 ) + { + cbFlags |= paInputOverflow; + stream->overrun = 0.0; + } + if( stream->capture.pcm && stream->playback.pcm ) + { + /** @concern FullDuplex It's possible that only one direction is being processed to avoid an + * under- or overflow, this should be reported correspondingly */ + if( !stream->capture.ready ) + { + cbFlags |= paInputUnderflow; + PA_DEBUG(( "%s: Input underflow\n", __FUNCTION__ )); + } + else if( !stream->playback.ready ) + { + cbFlags |= paOutputOverflow; + PA_DEBUG(( "%s: Output overflow\n", __FUNCTION__ )); + } + } + +#if 0 + CallbackUpdate( &stream->threading ); +#endif + CalculateTimeInfo( stream, &timeInfo ); + PaUtil_BeginBufferProcessing( &stream->bufferProcessor, &timeInfo, cbFlags ); + cbFlags = 0; + + /* CPU load measurement should include processing activivity external to the stream callback */ + PaUtil_BeginCpuLoadMeasurement( &stream->cpuLoadMeasurer ); + + framesGot = framesAvail; + if( paUtilFixedHostBufferSize == stream->bufferProcessor.hostBufferSizeMode ) + { + /* We've committed to a fixed host buffer size, stick to that */ + framesGot = framesGot >= stream->maxFramesPerHostBuffer ? stream->maxFramesPerHostBuffer : 0; + } + else + { + /* We've committed to an upper bound on the size of host buffers */ + assert( paUtilBoundedHostBufferSize == stream->bufferProcessor.hostBufferSizeMode ); + framesGot = PA_MIN( framesGot, stream->maxFramesPerHostBuffer ); + } + PA_ENSURE( PaAlsaStream_SetUpBuffers( stream, &framesGot, &xrun ) ); + /* Check the host buffer size against the buffer processor configuration */ + framesAvail -= framesGot; + + if( framesGot > 0 ) + { + assert( !xrun ); + PaUtil_EndBufferProcessing( &stream->bufferProcessor, &callbackResult ); + PA_ENSURE( PaAlsaStream_EndProcessing( stream, framesGot, &xrun ) ); + } + PaUtil_EndCpuLoadMeasurement( &stream->cpuLoadMeasurer, framesGot ); + + if( 0 == framesGot ) + { + /* Go back to polling for more frames */ + break; + + } + + if( paContinue != callbackResult ) + break; + } + } + + /* Match pthread_cleanup_push */ + pthread_cleanup_pop( 1 ); + +end: + PA_DEBUG(( "%s: Thread %d exiting\n ", __FUNCTION__, pthread_self() )); + PaUnixThreading_EXIT( result ); +error: + goto end; +} + +/* Blocking interface */ + +static PaError ReadStream( PaStream* s, void *buffer, unsigned long frames ) +{ + PaError result = paNoError; + PaAlsaStream *stream = (PaAlsaStream*)s; + unsigned long framesGot, framesAvail; + void *userBuffer; + snd_pcm_t *save = stream->playback.pcm; + + assert( stream ); + + PA_UNLESS( stream->capture.pcm, paCanNotReadFromAnOutputOnlyStream ); + + /* Disregard playback */ + stream->playback.pcm = NULL; + + if( stream->overrun > 0. ) + { + result = paInputOverflowed; + stream->overrun = 0.0; + } + + if( stream->capture.userInterleaved ) + { + userBuffer = buffer; + } + else + { + /* Copy channels into local array */ + userBuffer = stream->capture.userBuffers; + memcpy( userBuffer, buffer, sizeof (void *) * stream->capture.numUserChannels ); + } + + /* Start stream if in prepared state */ + if( snd_pcm_state( stream->capture.pcm ) == SND_PCM_STATE_PREPARED ) + { + ENSURE_( snd_pcm_start( stream->capture.pcm ), paUnanticipatedHostError ); + } + + while( frames > 0 ) + { + int xrun = 0; + PA_ENSURE( PaAlsaStream_WaitForFrames( stream, &framesAvail, &xrun ) ); + framesGot = PA_MIN( framesAvail, frames ); + + PA_ENSURE( PaAlsaStream_SetUpBuffers( stream, &framesGot, &xrun ) ); + if( framesGot > 0 ) + { + framesGot = PaUtil_CopyInput( &stream->bufferProcessor, &userBuffer, framesGot ); + PA_ENSURE( PaAlsaStream_EndProcessing( stream, framesGot, &xrun ) ); + frames -= framesGot; + } + } + +end: + stream->playback.pcm = save; + return result; +error: + goto end; +} + +static PaError WriteStream( PaStream* s, const void *buffer, unsigned long frames ) +{ + PaError result = paNoError; + signed long err; + PaAlsaStream *stream = (PaAlsaStream*)s; + snd_pcm_uframes_t framesGot, framesAvail; + const void *userBuffer; + snd_pcm_t *save = stream->capture.pcm; + + assert( stream ); + + PA_UNLESS( stream->playback.pcm, paCanNotWriteToAnInputOnlyStream ); + + /* Disregard capture */ + stream->capture.pcm = NULL; + + if( stream->underrun > 0. ) + { + result = paOutputUnderflowed; + stream->underrun = 0.0; + } + + if( stream->playback.userInterleaved ) + userBuffer = buffer; + else /* Copy channels into local array */ + { + userBuffer = stream->playback.userBuffers; + memcpy( (void *)userBuffer, buffer, sizeof (void *) * stream->playback.numUserChannels ); + } + + while( frames > 0 ) + { + int xrun = 0; + snd_pcm_uframes_t hwAvail; + + PA_ENSURE( PaAlsaStream_WaitForFrames( stream, &framesAvail, &xrun ) ); + framesGot = PA_MIN( framesAvail, frames ); + + PA_ENSURE( PaAlsaStream_SetUpBuffers( stream, &framesGot, &xrun ) ); + if( framesGot > 0 ) + { + framesGot = PaUtil_CopyOutput( &stream->bufferProcessor, &userBuffer, framesGot ); + PA_ENSURE( PaAlsaStream_EndProcessing( stream, framesGot, &xrun ) ); + frames -= framesGot; + } + + /* Start stream after one period of samples worth */ + + /* Frames residing in buffer */ + PA_ENSURE( err = GetStreamWriteAvailable( stream ) ); + framesAvail = err; + hwAvail = stream->playback.bufferSize - framesAvail; + + if( snd_pcm_state( stream->playback.pcm ) == SND_PCM_STATE_PREPARED && + hwAvail >= stream->playback.framesPerBuffer ) + { + ENSURE_( snd_pcm_start( stream->playback.pcm ), paUnanticipatedHostError ); + } + } + +end: + stream->capture.pcm = save; + return result; +error: + goto end; +} + +/* Return frames available for reading. In the event of an overflow, the capture pcm will be restarted */ +static signed long GetStreamReadAvailable( PaStream* s ) +{ + PaError result = paNoError; + PaAlsaStream *stream = (PaAlsaStream*)s; + unsigned long avail; + int xrun; + + PA_ENSURE( PaAlsaStreamComponent_GetAvailableFrames( &stream->capture, &avail, &xrun ) ); + if( xrun ) + { + PA_ENSURE( PaAlsaStream_HandleXrun( stream ) ); + PA_ENSURE( PaAlsaStreamComponent_GetAvailableFrames( &stream->capture, &avail, &xrun ) ); + if( xrun ) + PA_ENSURE( paInputOverflowed ); + } + + return (signed long)avail; + +error: + return result; +} + +static signed long GetStreamWriteAvailable( PaStream* s ) +{ + PaError result = paNoError; + PaAlsaStream *stream = (PaAlsaStream*)s; + unsigned long avail; + int xrun; + + PA_ENSURE( PaAlsaStreamComponent_GetAvailableFrames( &stream->playback, &avail, &xrun ) ); + if( xrun ) + { + snd_pcm_sframes_t savail; + + PA_ENSURE( PaAlsaStream_HandleXrun( stream ) ); + savail = snd_pcm_avail_update( stream->playback.pcm ); + + /* savail should not contain -EPIPE now, since PaAlsaStream_HandleXrun will only prepare the pcm */ + ENSURE_( savail, paUnanticipatedHostError ); + + avail = (unsigned long) savail; + } + + return (signed long)avail; + +error: + return result; +} + +/* Extensions */ + +void PaAlsa_InitializeStreamInfo( PaAlsaStreamInfo *info ) +{ + info->size = sizeof (PaAlsaStreamInfo); + info->hostApiType = paALSA; + info->version = 1; + info->deviceString = NULL; +} + +void PaAlsa_EnableRealtimeScheduling( PaStream *s, int enable ) +{ + PaAlsaStream *stream = (PaAlsaStream *) s; + stream->rtSched = enable; +} + +#if 0 +void PaAlsa_EnableWatchdog( PaStream *s, int enable ) +{ + PaAlsaStream *stream = (PaAlsaStream *) s; + stream->thread.useWatchdog = enable; +} +#endif + +PaError PaAlsa_GetStreamInputCard(PaStream* s, int* card) { + PaAlsaStream *stream = (PaAlsaStream *) s; + snd_pcm_info_t* pcmInfo; + PaError result = paNoError; + + /* XXX: More descriptive error? */ + PA_UNLESS( stream->capture.pcm, paDeviceUnavailable ); + + snd_pcm_info_alloca( &pcmInfo ); + PA_ENSURE( snd_pcm_info( stream->capture.pcm, pcmInfo ) ); + *card = snd_pcm_info_get_card( pcmInfo ); + +error: + return result; +} + +PaError PaAlsa_GetStreamOutputCard(PaStream* s, int* card) { + PaAlsaStream *stream = (PaAlsaStream *) s; + snd_pcm_info_t* pcmInfo; + PaError result = paNoError; + + /* XXX: More descriptive error? */ + PA_UNLESS( stream->playback.pcm, paDeviceUnavailable ); + + snd_pcm_info_alloca( &pcmInfo ); + PA_ENSURE( snd_pcm_info( stream->playback.pcm, pcmInfo ) ); + *card = snd_pcm_info_get_card( pcmInfo ); + +error: + return result; +} From sumomo @ users.sourceforge.jp Sat Feb 5 18:00:04 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Sat, 05 Feb 2011 18:00:04 +0900 Subject: [Julius-cvs 589] CVS update: julius4/libsent/src/adin/pa/os/win Message-ID: <1296896404.155537.28847.nullmailer@users.sourceforge.jp> Index: julius4/libsent/src/adin/pa/os/win/pa_win_hostapis.c diff -u /dev/null julius4/libsent/src/adin/pa/os/win/pa_win_hostapis.c:1.1 --- /dev/null Sat Feb 5 18:00:04 2011 +++ julius4/libsent/src/adin/pa/os/win/pa_win_hostapis.c Sat Feb 5 18:00:04 2011 @@ -0,0 +1,100 @@ +/* + * $Id: pa_win_hostapis.c,v 1.1 2011/02/05 09:00:04 sumomo Exp $ + * Portable Audio I/O Library Windows initialization table + * + * Based on the Open Source API proposed by Ross Bencina + * Copyright (c) 1999-2002 Ross Bencina, Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/* + * The text above constitutes the entire PortAudio license; however, + * the PortAudio community also makes the following non-binding requests: + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. It is also + * requested that these non-binding requests be included along with the + * license above. + */ + +/** @file + @ingroup win_src + + Win32 host API initialization function table. + + @todo Consider using PA_USE_WMME etc instead of PA_NO_WMME. This is what + the Unix version does, we should consider being consistent. +*/ + + +#include "pa_hostapi.h" + +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +PaError PaSkeleton_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index ); +PaError PaWinMme_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index ); +PaError PaWinDs_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index ); +PaError PaAsio_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index ); +PaError PaWinWdm_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index ); +PaError PaWinWasapi_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index ); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + + +PaUtilHostApiInitializer *paHostApiInitializers[] = + { + +#ifndef PA_NO_WMME + PaWinMme_Initialize, +#endif + +#ifndef PA_NO_DS + PaWinDs_Initialize, +#endif + +#ifndef PA_NO_ASIO + PaAsio_Initialize, +#endif + +/* +#ifndef PA_NO_WASAPI + PaWinWasapi_Initialize, +#endif + +#ifndef PA_NO_WDMKS + PaWinWdm_Initialize, +#endif +*/ + + PaSkeleton_Initialize, /* just for testing */ + + 0 /* NULL terminated array */ + }; + + +int paDefaultHostApiIndex = 0; + Index: julius4/libsent/src/adin/pa/os/win/pa_win_util.c diff -u /dev/null julius4/libsent/src/adin/pa/os/win/pa_win_util.c:1.1 --- /dev/null Sat Feb 5 18:00:04 2011 +++ julius4/libsent/src/adin/pa/os/win/pa_win_util.c Sat Feb 5 18:00:04 2011 @@ -0,0 +1,147 @@ +/* + * $Id: pa_win_util.c,v 1.1 2011/02/05 09:00:04 sumomo Exp $ + * Portable Audio I/O Library + * Win32 platform-specific support functions + * + * Based on the Open Source API proposed by Ross Bencina + * Copyright (c) 1999-2000 Ross Bencina + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/* + * The text above constitutes the entire PortAudio license; however, + * the PortAudio community also makes the following non-binding requests: + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. It is also + * requested that these non-binding requests be included along with the + * license above. + */ + +/** @file + @ingroup win_src + + Win32 platform-specific support functions. + + @todo Implement workaround for QueryPerformanceCounter() skipping forward + bug. (see msdn kb Q274323). +*/ + +#include +#include /* for timeGetTime() */ + +#include "pa_util.h" + + +/* + Track memory allocations to avoid leaks. + */ + +#if PA_TRACK_MEMORY +static int numAllocations_ = 0; +#endif + + +void *PaUtil_AllocateMemory( long size ) +{ + void *result = GlobalAlloc( GPTR, size ); + +#if PA_TRACK_MEMORY + if( result != NULL ) numAllocations_ += 1; +#endif + return result; +} + + +void PaUtil_FreeMemory( void *block ) +{ + if( block != NULL ) + { + GlobalFree( block ); +#if PA_TRACK_MEMORY + numAllocations_ -= 1; +#endif + + } +} + + +int PaUtil_CountCurrentlyAllocatedBlocks( void ) +{ +#if PA_TRACK_MEMORY + return numAllocations_; +#else + return 0; +#endif +} + + +void Pa_Sleep( long msec ) +{ + Sleep( msec ); +} + +static int usePerformanceCounter_; +static double secondsPerTick_; + +void PaUtil_InitializeClock( void ) +{ + LARGE_INTEGER ticksPerSecond; + + if( QueryPerformanceFrequency( &ticksPerSecond ) != 0 ) + { + usePerformanceCounter_ = 1; + secondsPerTick_ = 1.0 / (double)ticksPerSecond.QuadPart; + } + else + { + usePerformanceCounter_ = 0; + } +} + + +double PaUtil_GetTime( void ) +{ + LARGE_INTEGER time; + + if( usePerformanceCounter_ ) + { + /* FIXME: + according to this knowledge-base article, QueryPerformanceCounter + can skip forward by seconds! + http://support.microsoft.com/default.aspx?scid=KB;EN-US;Q274323& + + it may be better to use the rtdsc instruction using inline asm, + however then a method is needed to calculate a ticks/seconds ratio. + */ + QueryPerformanceCounter( &time ); + return time.QuadPart * secondsPerTick_; + } + else + { +#ifndef UNDER_CE + return timeGetTime() * .001; +#else + return GetTickCount() * .001; +#endif + } +} Index: julius4/libsent/src/adin/pa/os/win/pa_win_waveformat.c diff -u /dev/null julius4/libsent/src/adin/pa/os/win/pa_win_waveformat.c:1.1 --- /dev/null Sat Feb 5 18:00:04 2011 +++ julius4/libsent/src/adin/pa/os/win/pa_win_waveformat.c Sat Feb 5 18:00:04 2011 @@ -0,0 +1,159 @@ +/* + * PortAudio Portable Real-Time Audio Library + * Windows WAVEFORMAT* data structure utilities + * portaudio.h should be included before this file. + * + * Copyright (c) 2007 Ross Bencina + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/* + * The text above constitutes the entire PortAudio license; however, + * the PortAudio community also makes the following non-binding requests: + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. It is also + * requested that these non-binding requests be included along with the + * license above. + */ + +#include +#include + +#include "portaudio.h" +#include "pa_win_waveformat.h" + + +#if !defined(WAVE_FORMAT_EXTENSIBLE) +#define WAVE_FORMAT_EXTENSIBLE 0xFFFE +#endif + +#if !defined(WAVE_FORMAT_IEEE_FLOAT) +#define WAVE_FORMAT_IEEE_FLOAT 0x0003 +#endif + +static GUID pawin_ksDataFormatSubtypePcm = + { (USHORT)(WAVE_FORMAT_PCM), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 }; + +static GUID pawin_ksDataFormatSubtypeIeeeFloat = + { (USHORT)(WAVE_FORMAT_IEEE_FLOAT), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 }; + + + +void PaWin_InitializeWaveFormatEx( PaWinWaveFormat *waveFormat, + int numChannels, PaSampleFormat sampleFormat, double sampleRate ) +{ + WAVEFORMATEX *waveFormatEx = (WAVEFORMATEX*)waveFormat; + int bytesPerSample = Pa_GetSampleSize(sampleFormat); + unsigned long bytesPerFrame = numChannels * bytesPerSample; + + if( sampleFormat == paFloat32 ) + waveFormatEx->wFormatTag = WAVE_FORMAT_IEEE_FLOAT; + else + waveFormatEx->wFormatTag = WAVE_FORMAT_PCM; + + waveFormatEx->nChannels = (WORD)numChannels; + waveFormatEx->nSamplesPerSec = (DWORD)sampleRate; + waveFormatEx->nAvgBytesPerSec = waveFormatEx->nSamplesPerSec * bytesPerFrame; + waveFormatEx->nBlockAlign = (WORD)bytesPerFrame; + waveFormatEx->wBitsPerSample = bytesPerSample * 8; + waveFormatEx->cbSize = 0; +} + + +void PaWin_InitializeWaveFormatExtensible( PaWinWaveFormat *waveFormat, + int numChannels, PaSampleFormat sampleFormat, double sampleRate, + PaWinWaveFormatChannelMask channelMask ) +{ + WAVEFORMATEX *waveFormatEx = (WAVEFORMATEX*)waveFormat; + int bytesPerSample = Pa_GetSampleSize(sampleFormat); + unsigned long bytesPerFrame = numChannels * bytesPerSample; + + waveFormatEx->wFormatTag = WAVE_FORMAT_EXTENSIBLE; + waveFormatEx->nChannels = (WORD)numChannels; + waveFormatEx->nSamplesPerSec = (DWORD)sampleRate; + waveFormatEx->nAvgBytesPerSec = waveFormatEx->nSamplesPerSec * bytesPerFrame; + waveFormatEx->nBlockAlign = (WORD)bytesPerFrame; + waveFormatEx->wBitsPerSample = bytesPerSample * 8; + waveFormatEx->cbSize = 22; + + *((WORD*)&waveFormat->fields[PAWIN_INDEXOF_WVALIDBITSPERSAMPLE]) = + waveFormatEx->wBitsPerSample; + + *((DWORD*)&waveFormat->fields[PAWIN_INDEXOF_DWCHANNELMASK]) = channelMask; + + if( sampleFormat == paFloat32 ) + *((GUID*)&waveFormat->fields[PAWIN_INDEXOF_SUBFORMAT]) = + pawin_ksDataFormatSubtypeIeeeFloat; + else + *((GUID*)&waveFormat->fields[PAWIN_INDEXOF_SUBFORMAT]) = + pawin_ksDataFormatSubtypePcm; +} + + +PaWinWaveFormatChannelMask PaWin_DefaultChannelMask( int numChannels ) +{ + switch( numChannels ){ + case 1: + return PAWIN_SPEAKER_MONO; + case 2: + return PAWIN_SPEAKER_STEREO; + case 3: + return PAWIN_SPEAKER_FRONT_LEFT | PAWIN_SPEAKER_FRONT_CENTER | PAWIN_SPEAKER_FRONT_RIGHT; + case 4: + return PAWIN_SPEAKER_QUAD; + case 5: + return PAWIN_SPEAKER_QUAD | PAWIN_SPEAKER_FRONT_CENTER; + case 6: + /* The meaning of the PAWIN_SPEAKER_5POINT1 flag has changed over time: + http://msdn2.microsoft.com/en-us/library/aa474707.aspx + We use PAWIN_SPEAKER_5POINT1 (not PAWIN_SPEAKER_5POINT1_SURROUND) + because on some cards (eg Audigy) PAWIN_SPEAKER_5POINT1_SURROUND + results in a virtual mixdown placing the rear output in the + front _and_ rear speakers. + */ + return PAWIN_SPEAKER_5POINT1; + /* case 7: */ + case 8: + return PAWIN_SPEAKER_7POINT1; + } + + /* Apparently some Audigy drivers will output silence + if the direct-out constant (0) is used. So this is not ideal. + */ + return PAWIN_SPEAKER_DIRECTOUT; + + /* Note that Alec Rogers proposed the following as an alternate method to + generate the default channel mask, however it doesn't seem to be an improvement + over the above, since some drivers will matrix outputs mapping to non-present + speakers accross multiple physical speakers. + + if(nChannels==1) { + pwfFormat->dwChannelMask = SPEAKER_FRONT_CENTER; + } + else { + pwfFormat->dwChannelMask = 0; + for(i=0; idwChannelMask = (pwfFormat->dwChannelMask << 1) | 0x1; + } + */ +} Index: julius4/libsent/src/adin/pa/os/win/pa_win_wdmks_utils.c diff -u /dev/null julius4/libsent/src/adin/pa/os/win/pa_win_wdmks_utils.c:1.1 --- /dev/null Sat Feb 5 18:00:04 2011 +++ julius4/libsent/src/adin/pa/os/win/pa_win_wdmks_utils.c Sat Feb 5 18:00:04 2011 @@ -0,0 +1,260 @@ +/* + * PortAudio Portable Real-Time Audio Library + * Windows WDM KS utilities + * + * Copyright (c) 1999 - 2007 Andrew Baldwin, Ross Bencina + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/* + * The text above constitutes the entire PortAudio license; however, + * the PortAudio community also makes the following non-binding requests: + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. It is also + * requested that these non-binding requests be included along with the + * license above. + */ + +#include +#include +#include +#include +#include // just for some development printfs + +#include "portaudio.h" +#include "pa_util.h" +#include "pa_win_wdmks_utils.h" + + +static PaError WdmGetPinPropertySimple( + HANDLE handle, + unsigned long pinId, + unsigned long property, + void* value, + unsigned long valueSize ) +{ + DWORD bytesReturned; + KSP_PIN ksPProp; + ksPProp.Property.Set = KSPROPSETID_Pin; + ksPProp.Property.Id = property; + ksPProp.Property.Flags = KSPROPERTY_TYPE_GET; + ksPProp.PinId = pinId; + ksPProp.Reserved = 0; + + if( DeviceIoControl( handle, IOCTL_KS_PROPERTY, &ksPProp, sizeof(KSP_PIN), + value, valueSize, &bytesReturned, NULL ) == 0 || bytesReturned != valueSize ) + { + return paUnanticipatedHostError; + } + else + { + return paNoError; + } +} + + +static PaError WdmGetPinPropertyMulti( + HANDLE handle, + unsigned long pinId, + unsigned long property, + KSMULTIPLE_ITEM** ksMultipleItem) +{ + unsigned long multipleItemSize = 0; + KSP_PIN ksPProp; + DWORD bytesReturned; + + *ksMultipleItem = 0; + + ksPProp.Property.Set = KSPROPSETID_Pin; + ksPProp.Property.Id = property; + ksPProp.Property.Flags = KSPROPERTY_TYPE_GET; + ksPProp.PinId = pinId; + ksPProp.Reserved = 0; + + if( DeviceIoControl( handle, IOCTL_KS_PROPERTY, &ksPProp.Property, + sizeof(KSP_PIN), NULL, 0, &multipleItemSize, NULL ) == 0 && GetLastError() != ERROR_MORE_DATA ) + { + return paUnanticipatedHostError; + } + + *ksMultipleItem = (KSMULTIPLE_ITEM*)PaUtil_AllocateMemory( multipleItemSize ); + if( !*ksMultipleItem ) + { + return paInsufficientMemory; + } + + if( DeviceIoControl( handle, IOCTL_KS_PROPERTY, &ksPProp, sizeof(KSP_PIN), + (void*)*ksMultipleItem, multipleItemSize, &bytesReturned, NULL ) == 0 || bytesReturned != multipleItemSize ) + { + PaUtil_FreeMemory( ksMultipleItem ); + return paUnanticipatedHostError; + } + + return paNoError; +} + + +static int GetKSFilterPinCount( HANDLE deviceHandle ) +{ + DWORD result; + + if( WdmGetPinPropertySimple( deviceHandle, 0, KSPROPERTY_PIN_CTYPES, &result, sizeof(result) ) == paNoError ){ + return result; + }else{ + return 0; + } +} + + +static KSPIN_COMMUNICATION GetKSFilterPinPropertyCommunication( HANDLE deviceHandle, int pinId ) +{ + KSPIN_COMMUNICATION result; + + if( WdmGetPinPropertySimple( deviceHandle, pinId, KSPROPERTY_PIN_COMMUNICATION, &result, sizeof(result) ) == paNoError ){ + return result; + }else{ + return KSPIN_COMMUNICATION_NONE; + } +} + + +static KSPIN_DATAFLOW GetKSFilterPinPropertyDataflow( HANDLE deviceHandle, int pinId ) +{ + KSPIN_DATAFLOW result; + + if( WdmGetPinPropertySimple( deviceHandle, pinId, KSPROPERTY_PIN_DATAFLOW, &result, sizeof(result) ) == paNoError ){ + return result; + }else{ + return (KSPIN_DATAFLOW)0; + } +} + + +static int KSFilterPinPropertyIdentifiersInclude( + HANDLE deviceHandle, int pinId, unsigned long property, const GUID *identifierSet, unsigned long identifierId ) +{ + KSMULTIPLE_ITEM* item = NULL; + KSIDENTIFIER* identifier; + int i; + int result = 0; + + if( WdmGetPinPropertyMulti( deviceHandle, pinId, property, &item) != paNoError ) + return 0; + + identifier = (KSIDENTIFIER*)(item+1); + + for( i = 0; i < (int)item->Count; i++ ) + { + if( !memcmp( (void*)&identifier[i].Set, (void*)identifierSet, sizeof( GUID ) ) && + ( identifier[i].Id == identifierId ) ) + { + result = 1; + break; + } + } + + PaUtil_FreeMemory( item ); + + return result; +} + + +/* return the maximum channel count supported by any pin on the device. + if isInput is non-zero we query input pins, otherwise output pins. +*/ +int PaWin_WDMKS_QueryFilterMaximumChannelCount( void *wcharDevicePath, int isInput ) +{ + HANDLE deviceHandle; + int pinCount, pinId, i; + int result = 0; + KSPIN_DATAFLOW requiredDataflowDirection = (isInput ? KSPIN_DATAFLOW_OUT : KSPIN_DATAFLOW_IN ); + + if( !wcharDevicePath ) + return 0; + + deviceHandle = CreateFileW( (LPCWSTR)wcharDevicePath, FILE_SHARE_READ|FILE_SHARE_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL ); + if( deviceHandle == INVALID_HANDLE_VALUE ) + return 0; + + pinCount = GetKSFilterPinCount( deviceHandle ); + for( pinId = 0; pinId < pinCount; ++pinId ) + { + KSPIN_COMMUNICATION communication = GetKSFilterPinPropertyCommunication( deviceHandle, pinId ); + KSPIN_DATAFLOW dataflow = GetKSFilterPinPropertyDataflow( deviceHandle, pinId ); + if( ( dataflow == requiredDataflowDirection ) && + (( communication == KSPIN_COMMUNICATION_SINK) || + ( communication == KSPIN_COMMUNICATION_BOTH)) + && ( KSFilterPinPropertyIdentifiersInclude( deviceHandle, pinId, + KSPROPERTY_PIN_INTERFACES, &KSINTERFACESETID_Standard, KSINTERFACE_STANDARD_STREAMING ) + || KSFilterPinPropertyIdentifiersInclude( deviceHandle, pinId, + KSPROPERTY_PIN_INTERFACES, &KSINTERFACESETID_Standard, KSINTERFACE_STANDARD_LOOPED_STREAMING ) ) + && KSFilterPinPropertyIdentifiersInclude( deviceHandle, pinId, + KSPROPERTY_PIN_MEDIUMS, &KSMEDIUMSETID_Standard, KSMEDIUM_STANDARD_DEVIO ) ) + { + KSMULTIPLE_ITEM* item = NULL; + if( WdmGetPinPropertyMulti( deviceHandle, pinId, KSPROPERTY_PIN_DATARANGES, &item ) == paNoError ) + { + KSDATARANGE *dataRange = (KSDATARANGE*)(item+1); + + for( i=0; i < item->Count; ++i ){ + + if( IS_VALID_WAVEFORMATEX_GUID(&dataRange->SubFormat) + || memcmp( (void*)&dataRange->SubFormat, (void*)&KSDATAFORMAT_SUBTYPE_PCM, sizeof(GUID) ) == 0 + || memcmp( (void*)&dataRange->SubFormat, (void*)&KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, sizeof(GUID) ) == 0 + || ( ( memcmp( (void*)&dataRange->MajorFormat, (void*)&KSDATAFORMAT_TYPE_AUDIO, sizeof(GUID) ) == 0 ) + && ( memcmp( (void*)&dataRange->SubFormat, (void*)&KSDATAFORMAT_SUBTYPE_WILDCARD, sizeof(GUID) ) == 0 ) ) ) + { + KSDATARANGE_AUDIO *dataRangeAudio = (KSDATARANGE_AUDIO*)dataRange; + + /* + printf( ">>> %d %d %d %d %S\n", isInput, dataflow, communication, dataRangeAudio->MaximumChannels, devicePath ); + + if( memcmp((void*)&dataRange->Specifier, (void*)&KSDATAFORMAT_SPECIFIER_WAVEFORMATEX, sizeof(GUID) ) == 0 ) + printf( "\tspecifier: KSDATAFORMAT_SPECIFIER_WAVEFORMATEX\n" ); + else if( memcmp((void*)&dataRange->Specifier, (void*)&KSDATAFORMAT_SPECIFIER_DSOUND, sizeof(GUID) ) == 0 ) + printf( "\tspecifier: KSDATAFORMAT_SPECIFIER_DSOUND\n" ); + else if( memcmp((void*)&dataRange->Specifier, (void*)&KSDATAFORMAT_SPECIFIER_WILDCARD, sizeof(GUID) ) == 0 ) + printf( "\tspecifier: KSDATAFORMAT_SPECIFIER_WILDCARD\n" ); + else + printf( "\tspecifier: ?\n" ); + */ + + /* + We assume that very high values for MaximumChannels are not useful and indicate + that the driver isn't prepared to tell us the real number of channels which it supports. + */ + if( dataRangeAudio->MaximumChannels < 0xFFFFUL && (int)dataRangeAudio->MaximumChannels > result ) + result = (int)dataRangeAudio->MaximumChannels; + } + + dataRange = (KSDATARANGE*)( ((char*)dataRange) + dataRange->FormatSize); + } + + PaUtil_FreeMemory( item ); + } + } + } + + CloseHandle( deviceHandle ); + return result; +} Index: julius4/libsent/src/adin/pa/os/win/pa_win_wdmks_utils.h diff -u /dev/null julius4/libsent/src/adin/pa/os/win/pa_win_wdmks_utils.h:1.1 --- /dev/null Sat Feb 5 18:00:04 2011 +++ julius4/libsent/src/adin/pa/os/win/pa_win_wdmks_utils.h Sat Feb 5 18:00:04 2011 @@ -0,0 +1,65 @@ +#ifndef PA_WIN_WDMKS_UTILS_H +#define PA_WIN_WDMKS_UTILS_H + +/* + * PortAudio Portable Real-Time Audio Library + * Windows WDM KS utilities + * + * Copyright (c) 1999 - 2007 Ross Bencina, Andrew Baldwin + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/* + * The text above constitutes the entire PortAudio license; however, + * the PortAudio community also makes the following non-binding requests: + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. It is also + * requested that these non-binding requests be included along with the + * license above. + */ + +/** @file + @brief Utilities for working with the Windows WDM KS API +*/ + +#ifdef __cplusplus +extern "C" { +#endif + +/** + Query for the maximum number of channels supported by any pin of the + specified device. Returns 0 if the query fails for any reason. + + @param wcharDevicePath A system level PnP interface path, supplied as a WCHAR unicode string. + Declard as void* to avoid introducing a dependency on wchar_t here. + + @param isInput A flag specifying whether to query for input (non-zero) or output (zero) channels. +*/ +int PaWin_WDMKS_QueryFilterMaximumChannelCount( void *wcharDevicePath, int isInput ); + + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* PA_WIN_WDMKS_UTILS_H */ Index: julius4/libsent/src/adin/pa/os/win/pa_x86_plain_converters.c diff -u /dev/null julius4/libsent/src/adin/pa/os/win/pa_x86_plain_converters.c:1.1 --- /dev/null Sat Feb 5 18:00:04 2011 +++ julius4/libsent/src/adin/pa/os/win/pa_x86_plain_converters.c Sat Feb 5 18:00:04 2011 @@ -0,0 +1,1219 @@ +/* + * Plain Intel IA32 assembly implementations of PortAudio sample converter functions. + * Copyright (c) 1999-2002 Ross Bencina, Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/* + * The text above constitutes the entire PortAudio license; however, + * the PortAudio community also makes the following non-binding requests: + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. It is also + * requested that these non-binding requests be included along with the + * license above. + */ + +/** @file + @ingroup win_src +*/ + +#include "pa_x86_plain_converters.h" + +#include "pa_converters.h" +#include "pa_dither.h" + +/* + the main reason these versions are faster than the equivalent C versions + is that float -> int casting is expensive in C on x86 because the rounding + mode needs to be changed for every cast. these versions only set + the rounding mode once outside the loop. + + small additional speed gains are made by the way that clamping is + implemented. + +TODO: + o- inline dither code + o- implement Dither only (no-clip) versions + o- implement int8 and uint8 versions + o- test thouroughly + + o- the packed 24 bit functions could benefit from unrolling and avoiding + byte and word sized register access. +*/ + +/* -------------------------------------------------------------------------- */ + +/* +#define PA_CLIP_( val, min, max )\ + { val = ((val) < (min)) ? (min) : (((val) > (max)) ? (max) : (val)); } +*/ + +/* + the following notes were used to determine whether a floating point + value should be saturated (ie >1 or <-1) by loading it into an integer + register. these should be rewritten so that they make sense. + + an ieee floating point value + + 1.xxxxxxxxxxxxxxxxxxxx? + + + is less than or equal to 1 and greater than or equal to -1 either: + + if the mantissa is 0 and the unbiased exponent is 0 + + OR + + if the unbiased exponent < 0 + + this translates to: + + if the mantissa is 0 and the biased exponent is 7F + + or + + if the biased exponent is less than 7F + + + therefore the value is greater than 1 or less than -1 if + + the mantissa is not 0 and the biased exponent is 7F + + or + + if the biased exponent is greater than 7F + + + in other words, if we mask out the sign bit, the value is + greater than 1 or less than -1 if its integer representation is greater than: + + 0 01111111 0000 0000 0000 0000 0000 000 + + 0011 1111 1000 0000 0000 0000 0000 0000 => 0x3F800000 +*/ + +/* -------------------------------------------------------------------------- */ + +static const short fpuControlWord_ = 0x033F; /*round to nearest, 64 bit precision, all exceptions masked*/ +static const double int32Scaler_ = 0x7FFFFFFF; +static const double ditheredInt32Scaler_ = 0x7FFFFFFE; +static const double int24Scaler_ = 0x7FFFFF; +static const double ditheredInt24Scaler_ = 0x7FFFFE; +static const double int16Scaler_ = 0x7FFF; +static const double ditheredInt16Scaler_ = 0x7FFE; + +#define PA_DITHER_BITS_ (15) +/* Multiply by PA_FLOAT_DITHER_SCALE_ to get a float between -2.0 and +1.99999 */ +#define PA_FLOAT_DITHER_SCALE_ (1.0 / ((1< source ptr + // eax -> source byte stride + // edi -> destination ptr + // ebx -> destination byte stride + // ecx -> source end ptr + // edx -> temp + + mov esi, sourceBuffer + + mov edx, 4 // sizeof float32 and int32 + mov eax, sourceStride + imul eax, edx + + mov ecx, count + imul ecx, eax + add ecx, esi + + mov edi, destinationBuffer + + mov ebx, destinationStride + imul ebx, edx + + fwait + fstcw savedFpuControlWord + fldcw fpuControlWord_ + + fld int32Scaler_ // stack: (int)0x7FFFFFFF + + Float32_To_Int32_loop: + + // load unscaled value into st(0) + fld dword ptr [esi] // stack: value, (int)0x7FFFFFFF + add esi, eax // increment source ptr + //lea esi, [esi+eax] + fmul st(0), st(1) // st(0) *= st(1), stack: value*0x7FFFFFFF, (int)0x7FFFFFFF + /* + note: we could store to a temporary qword here which would cause + wraparound distortion instead of int indefinite 0x10. that would + be more work, and given that not enabling clipping is only advisable + when you know that your signal isn't going to clip it isn't worth it. + */ + fistp dword ptr [edi] // pop st(0) into dest, stack: (int)0x7FFFFFFF + + add edi, ebx // increment destination ptr + //lea edi, [edi+ebx] + + cmp esi, ecx // has src ptr reached end? + jne Float32_To_Int32_loop + + ffree st(0) + fincstp + + fwait + fnclex + fldcw savedFpuControlWord + } +} + +/* -------------------------------------------------------------------------- */ + +static void Float32_To_Int32_Clip( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, PaUtilTriangularDitherGenerator *ditherGenerator ) +{ +/* + float *src = (float*)sourceBuffer; + signed long *dest = (signed long*)destinationBuffer; + (void) ditherGenerator; // unused parameter + + while( count-- ) + { + // REVIEW + double scaled = *src * 0x7FFFFFFF; + PA_CLIP_( scaled, -2147483648., 2147483647. ); + *dest = (signed long) scaled; + + src += sourceStride; + dest += destinationStride; + } +*/ + + short savedFpuControlWord; + + (void) ditherGenerator; /* unused parameter */ + + __asm{ + // esi -> source ptr + // eax -> source byte stride + // edi -> destination ptr + // ebx -> destination byte stride + // ecx -> source end ptr + // edx -> temp + + mov esi, sourceBuffer + + mov edx, 4 // sizeof float32 and int32 + mov eax, sourceStride + imul eax, edx + + mov ecx, count + imul ecx, eax + add ecx, esi + + mov edi, destinationBuffer + + mov ebx, destinationStride + imul ebx, edx + + fwait + fstcw savedFpuControlWord + fldcw fpuControlWord_ + + fld int32Scaler_ // stack: (int)0x7FFFFFFF + + Float32_To_Int32_Clip_loop: + + mov edx, dword ptr [esi] // load floating point value into integer register + + and edx, 0x7FFFFFFF // mask off sign + cmp edx, 0x3F800000 // greater than 1.0 or less than -1.0 + + jg Float32_To_Int32_Clip_clamp + + // load unscaled value into st(0) + fld dword ptr [esi] // stack: value, (int)0x7FFFFFFF + add esi, eax // increment source ptr + //lea esi, [esi+eax] + fmul st(0), st(1) // st(0) *= st(1), stack: value*0x7FFFFFFF, (int)0x7FFFFFFF + fistp dword ptr [edi] // pop st(0) into dest, stack: (int)0x7FFFFFFF + jmp Float32_To_Int32_Clip_stored + + Float32_To_Int32_Clip_clamp: + mov edx, dword ptr [esi] // load floating point value into integer register + shr edx, 31 // move sign bit into bit 0 + add esi, eax // increment source ptr + //lea esi, [esi+eax] + add edx, 0x7FFFFFFF // convert to maximum range integers + mov dword ptr [edi], edx + + Float32_To_Int32_Clip_stored: + + //add edi, ebx // increment destination ptr + lea edi, [edi+ebx] + + cmp esi, ecx // has src ptr reached end? + jne Float32_To_Int32_Clip_loop + + ffree st(0) + fincstp + + fwait + fnclex + fldcw savedFpuControlWord + } +} + +/* -------------------------------------------------------------------------- */ + +static void Float32_To_Int32_DitherClip( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + /* + float *src = (float*)sourceBuffer; + signed long *dest = (signed long*)destinationBuffer; + + while( count-- ) + { + // REVIEW + double dither = PaUtil_GenerateFloatTriangularDither( ditherGenerator ); + // use smaller scaler to prevent overflow when we add the dither + double dithered = ((double)*src * (2147483646.0)) + dither; + PA_CLIP_( dithered, -2147483648., 2147483647. ); + *dest = (signed long) dithered; + + + src += sourceStride; + dest += destinationStride; + } + */ + + short savedFpuControlWord; + + // spill storage: + signed long sourceByteStride; + signed long highpassedDither; + + // dither state: + unsigned long ditherPrevious = ditherGenerator->previous; + unsigned long ditherRandSeed1 = ditherGenerator->randSeed1; + unsigned long ditherRandSeed2 = ditherGenerator->randSeed2; + + __asm{ + // esi -> source ptr + // eax -> source byte stride + // edi -> destination ptr + // ebx -> destination byte stride + // ecx -> source end ptr + // edx -> temp + + mov esi, sourceBuffer + + mov edx, 4 // sizeof float32 and int32 + mov eax, sourceStride + imul eax, edx + + mov ecx, count + imul ecx, eax + add ecx, esi + + mov edi, destinationBuffer + + mov ebx, destinationStride + imul ebx, edx + + fwait + fstcw savedFpuControlWord + fldcw fpuControlWord_ + + fld ditheredInt32Scaler_ // stack: int scaler + + Float32_To_Int32_DitherClip_loop: + + mov edx, dword ptr [esi] // load floating point value into integer register + + and edx, 0x7FFFFFFF // mask off sign + cmp edx, 0x3F800000 // greater than 1.0 or less than -1.0 + + jg Float32_To_Int32_DitherClip_clamp + + // load unscaled value into st(0) + fld dword ptr [esi] // stack: value, int scaler + add esi, eax // increment source ptr + //lea esi, [esi+eax] + fmul st(0), st(1) // st(0) *= st(1), stack: value*(int scaler), int scaler + + /* + // call PaUtil_GenerateFloatTriangularDither with C calling convention + mov sourceByteStride, eax // save eax + mov sourceEnd, ecx // save ecx + push ditherGenerator // pass ditherGenerator parameter on stack + call PaUtil_GenerateFloatTriangularDither // stack: dither, value*(int scaler), int scaler + pop edx // clear parameter off stack + mov ecx, sourceEnd // restore ecx + mov eax, sourceByteStride // restore eax + */ + + // generate dither + mov sourceByteStride, eax // save eax + mov edx, 196314165 + mov eax, ditherRandSeed1 + mul edx // eax:edx = eax * 196314165 + //add eax, 907633515 + lea eax, [eax+907633515] + mov ditherRandSeed1, eax + mov edx, 196314165 + mov eax, ditherRandSeed2 + mul edx // eax:edx = eax * 196314165 + //add eax, 907633515 + lea eax, [eax+907633515] + mov edx, ditherRandSeed1 + shr edx, PA_DITHER_SHIFT_ + mov ditherRandSeed2, eax + shr eax, PA_DITHER_SHIFT_ + //add eax, edx // eax -> current + lea eax, [eax+edx] + mov edx, ditherPrevious + neg edx + lea edx, [eax+edx] // highpass = current - previous + mov highpassedDither, edx + mov ditherPrevious, eax // previous = current + mov eax, sourceByteStride // restore eax + fild highpassedDither + fmul const_float_dither_scale_ + // end generate dither, dither signal in st(0) + + faddp st(1), st(0) // stack: dither + value*(int scaler), int scaler + fistp dword ptr [edi] // pop st(0) into dest, stack: int scaler + jmp Float32_To_Int32_DitherClip_stored + + Float32_To_Int32_DitherClip_clamp: + mov edx, dword ptr [esi] // load floating point value into integer register + shr edx, 31 // move sign bit into bit 0 + add esi, eax // increment source ptr + //lea esi, [esi+eax] + add edx, 0x7FFFFFFF // convert to maximum range integers + mov dword ptr [edi], edx + + Float32_To_Int32_DitherClip_stored: + + //add edi, ebx // increment destination ptr + lea edi, [edi+ebx] + + cmp esi, ecx // has src ptr reached end? + jne Float32_To_Int32_DitherClip_loop + + ffree st(0) + fincstp + + fwait + fnclex + fldcw savedFpuControlWord + } + + ditherGenerator->previous = ditherPrevious; + ditherGenerator->randSeed1 = ditherRandSeed1; + ditherGenerator->randSeed2 = ditherRandSeed2; +} + +/* -------------------------------------------------------------------------- */ + +static void Float32_To_Int24( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, PaUtilTriangularDitherGenerator *ditherGenerator ) +{ +/* + float *src = (float*)sourceBuffer; + unsigned char *dest = (unsigned char*)destinationBuffer; + signed long temp; + + (void) ditherGenerator; // unused parameter + + while( count-- ) + { + // convert to 32 bit and drop the low 8 bits + double scaled = *src * 0x7FFFFFFF; + temp = (signed long) scaled; + + dest[0] = (unsigned char)(temp >> 8); + dest[1] = (unsigned char)(temp >> 16); + dest[2] = (unsigned char)(temp >> 24); + + src += sourceStride; + dest += destinationStride * 3; + } +*/ + + short savedFpuControlWord; + + signed long tempInt32; + + (void) ditherGenerator; /* unused parameter */ + + __asm{ + // esi -> source ptr + // eax -> source byte stride + // edi -> destination ptr + // ebx -> destination byte stride + // ecx -> source end ptr + // edx -> temp + + mov esi, sourceBuffer + + mov edx, 4 // sizeof float32 + mov eax, sourceStride + imul eax, edx + + mov ecx, count + imul ecx, eax + add ecx, esi + + mov edi, destinationBuffer + + mov edx, 3 // sizeof int24 + mov ebx, destinationStride + imul ebx, edx + + fwait + fstcw savedFpuControlWord + fldcw fpuControlWord_ + + fld int24Scaler_ // stack: (int)0x7FFFFF + + Float32_To_Int24_loop: + + // load unscaled value into st(0) + fld dword ptr [esi] // stack: value, (int)0x7FFFFF + add esi, eax // increment source ptr + //lea esi, [esi+eax] + fmul st(0), st(1) // st(0) *= st(1), stack: value*0x7FFFFF, (int)0x7FFFFF + fistp tempInt32 // pop st(0) into tempInt32, stack: (int)0x7FFFFF + mov edx, tempInt32 + + mov byte ptr [edi], DL + shr edx, 8 + //mov byte ptr [edi+1], DL + //mov byte ptr [edi+2], DH + mov word ptr [edi+1], DX + + //add edi, ebx // increment destination ptr + lea edi, [edi+ebx] + + cmp esi, ecx // has src ptr reached end? + jne Float32_To_Int24_loop + + ffree st(0) + fincstp + + fwait + fnclex + fldcw savedFpuControlWord + } +} + +/* -------------------------------------------------------------------------- */ + +static void Float32_To_Int24_Clip( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, PaUtilTriangularDitherGenerator *ditherGenerator ) +{ +/* + float *src = (float*)sourceBuffer; + unsigned char *dest = (unsigned char*)destinationBuffer; + signed long temp; + + (void) ditherGenerator; // unused parameter + + while( count-- ) + { + // convert to 32 bit and drop the low 8 bits + double scaled = *src * 0x7FFFFFFF; + PA_CLIP_( scaled, -2147483648., 2147483647. ); + temp = (signed long) scaled; + + dest[0] = (unsigned char)(temp >> 8); + dest[1] = (unsigned char)(temp >> 16); + dest[2] = (unsigned char)(temp >> 24); + + src += sourceStride; + dest += destinationStride * 3; + } +*/ + + short savedFpuControlWord; + + signed long tempInt32; + + (void) ditherGenerator; /* unused parameter */ + + __asm{ + // esi -> source ptr + // eax -> source byte stride + // edi -> destination ptr + // ebx -> destination byte stride + // ecx -> source end ptr + // edx -> temp + + mov esi, sourceBuffer + + mov edx, 4 // sizeof float32 + mov eax, sourceStride + imul eax, edx + + mov ecx, count + imul ecx, eax + add ecx, esi + + mov edi, destinationBuffer + + mov edx, 3 // sizeof int24 + mov ebx, destinationStride + imul ebx, edx + + fwait + fstcw savedFpuControlWord + fldcw fpuControlWord_ + + fld int24Scaler_ // stack: (int)0x7FFFFF + + Float32_To_Int24_Clip_loop: + + mov edx, dword ptr [esi] // load floating point value into integer register + + and edx, 0x7FFFFFFF // mask off sign + cmp edx, 0x3F800000 // greater than 1.0 or less than -1.0 + + jg Float32_To_Int24_Clip_clamp + + // load unscaled value into st(0) + fld dword ptr [esi] // stack: value, (int)0x7FFFFF + add esi, eax // increment source ptr + //lea esi, [esi+eax] + fmul st(0), st(1) // st(0) *= st(1), stack: value*0x7FFFFF, (int)0x7FFFFF + fistp tempInt32 // pop st(0) into tempInt32, stack: (int)0x7FFFFF + mov edx, tempInt32 + jmp Float32_To_Int24_Clip_store + + Float32_To_Int24_Clip_clamp: + mov edx, dword ptr [esi] // load floating point value into integer register + shr edx, 31 // move sign bit into bit 0 + add esi, eax // increment source ptr + //lea esi, [esi+eax] + add edx, 0x7FFFFF // convert to maximum range integers + + Float32_To_Int24_Clip_store: + + mov byte ptr [edi], DL + shr edx, 8 + //mov byte ptr [edi+1], DL + //mov byte ptr [edi+2], DH + mov word ptr [edi+1], DX + + //add edi, ebx // increment destination ptr + lea edi, [edi+ebx] + + cmp esi, ecx // has src ptr reached end? + jne Float32_To_Int24_Clip_loop + + ffree st(0) + fincstp + + fwait + fnclex + fldcw savedFpuControlWord + } +} + +/* -------------------------------------------------------------------------- */ + +static void Float32_To_Int24_DitherClip( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, PaUtilTriangularDitherGenerator *ditherGenerator ) +{ +/* + float *src = (float*)sourceBuffer; + unsigned char *dest = (unsigned char*)destinationBuffer; + signed long temp; + + while( count-- ) + { + // convert to 32 bit and drop the low 8 bits + + // FIXME: the dither amplitude here appears to be too small by 8 bits + double dither = PaUtil_GenerateFloatTriangularDither( ditherGenerator ); + // use smaller scaler to prevent overflow when we add the dither + double dithered = ((double)*src * (2147483646.0)) + dither; + PA_CLIP_( dithered, -2147483648., 2147483647. ); + + temp = (signed long) dithered; + + dest[0] = (unsigned char)(temp >> 8); + dest[1] = (unsigned char)(temp >> 16); + dest[2] = (unsigned char)(temp >> 24); + + src += sourceStride; + dest += destinationStride * 3; + } +*/ + + short savedFpuControlWord; + + // spill storage: + signed long sourceByteStride; + signed long highpassedDither; + + // dither state: + unsigned long ditherPrevious = ditherGenerator->previous; + unsigned long ditherRandSeed1 = ditherGenerator->randSeed1; + unsigned long ditherRandSeed2 = ditherGenerator->randSeed2; + + signed long tempInt32; + + __asm{ + // esi -> source ptr + // eax -> source byte stride + // edi -> destination ptr + // ebx -> destination byte stride + // ecx -> source end ptr + // edx -> temp + + mov esi, sourceBuffer + + mov edx, 4 // sizeof float32 + mov eax, sourceStride + imul eax, edx + + mov ecx, count + imul ecx, eax + add ecx, esi + + mov edi, destinationBuffer + + mov edx, 3 // sizeof int24 + mov ebx, destinationStride + imul ebx, edx + + fwait + fstcw savedFpuControlWord + fldcw fpuControlWord_ + + fld ditheredInt24Scaler_ // stack: int scaler + + Float32_To_Int24_DitherClip_loop: + + mov edx, dword ptr [esi] // load floating point value into integer register + + and edx, 0x7FFFFFFF // mask off sign + cmp edx, 0x3F800000 // greater than 1.0 or less than -1.0 + + jg Float32_To_Int24_DitherClip_clamp + + // load unscaled value into st(0) + fld dword ptr [esi] // stack: value, int scaler + add esi, eax // increment source ptr + //lea esi, [esi+eax] + fmul st(0), st(1) // st(0) *= st(1), stack: value*(int scaler), int scaler + + /* + // call PaUtil_GenerateFloatTriangularDither with C calling convention + mov sourceByteStride, eax // save eax + mov sourceEnd, ecx // save ecx + push ditherGenerator // pass ditherGenerator parameter on stack + call PaUtil_GenerateFloatTriangularDither // stack: dither, value*(int scaler), int scaler + pop edx // clear parameter off stack + mov ecx, sourceEnd // restore ecx + mov eax, sourceByteStride // restore eax + */ + + // generate dither + mov sourceByteStride, eax // save eax + mov edx, 196314165 + mov eax, ditherRandSeed1 + mul edx // eax:edx = eax * 196314165 + //add eax, 907633515 + lea eax, [eax+907633515] + mov ditherRandSeed1, eax + mov edx, 196314165 + mov eax, ditherRandSeed2 + mul edx // eax:edx = eax * 196314165 + //add eax, 907633515 + lea eax, [eax+907633515] + mov edx, ditherRandSeed1 + shr edx, PA_DITHER_SHIFT_ + mov ditherRandSeed2, eax + shr eax, PA_DITHER_SHIFT_ + //add eax, edx // eax -> current + lea eax, [eax+edx] + mov edx, ditherPrevious + neg edx + lea edx, [eax+edx] // highpass = current - previous + mov highpassedDither, edx + mov ditherPrevious, eax // previous = current + mov eax, sourceByteStride // restore eax + fild highpassedDither + fmul const_float_dither_scale_ + // end generate dither, dither signal in st(0) + + faddp st(1), st(0) // stack: dither * value*(int scaler), int scaler + fistp tempInt32 // pop st(0) into tempInt32, stack: int scaler + mov edx, tempInt32 + jmp Float32_To_Int24_DitherClip_store + + Float32_To_Int24_DitherClip_clamp: + mov edx, dword ptr [esi] // load floating point value into integer register + shr edx, 31 // move sign bit into bit 0 + add esi, eax // increment source ptr + //lea esi, [esi+eax] + add edx, 0x7FFFFF // convert to maximum range integers + + Float32_To_Int24_DitherClip_store: + + mov byte ptr [edi], DL + shr edx, 8 + //mov byte ptr [edi+1], DL + //mov byte ptr [edi+2], DH + mov word ptr [edi+1], DX + + //add edi, ebx // increment destination ptr + lea edi, [edi+ebx] + + cmp esi, ecx // has src ptr reached end? + jne Float32_To_Int24_DitherClip_loop + + ffree st(0) + fincstp + + fwait + fnclex + fldcw savedFpuControlWord + } + + ditherGenerator->previous = ditherPrevious; + ditherGenerator->randSeed1 = ditherRandSeed1; + ditherGenerator->randSeed2 = ditherRandSeed2; +} + +/* -------------------------------------------------------------------------- */ + +static void Float32_To_Int16( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, PaUtilTriangularDitherGenerator *ditherGenerator ) +{ +/* + float *src = (float*)sourceBuffer; + signed short *dest = (signed short*)destinationBuffer; + (void)ditherGenerator; // unused parameter + + while( count-- ) + { + + short samp = (short) (*src * (32767.0f)); + *dest = samp; + + src += sourceStride; + dest += destinationStride; + } +*/ + + short savedFpuControlWord; + + (void) ditherGenerator; /* unused parameter */ + + __asm{ + // esi -> source ptr + // eax -> source byte stride + // edi -> destination ptr + // ebx -> destination byte stride + // ecx -> source end ptr + // edx -> temp + + mov esi, sourceBuffer + + mov edx, 4 // sizeof float32 + mov eax, sourceStride + imul eax, edx // source byte stride + + mov ecx, count + imul ecx, eax + add ecx, esi // source end ptr = count * source byte stride + source ptr + + mov edi, destinationBuffer + + mov edx, 2 // sizeof int16 + mov ebx, destinationStride + imul ebx, edx // destination byte stride + + fwait + fstcw savedFpuControlWord + fldcw fpuControlWord_ + + fld int16Scaler_ // stack: (int)0x7FFF + + Float32_To_Int16_loop: + + // load unscaled value into st(0) + fld dword ptr [esi] // stack: value, (int)0x7FFF + add esi, eax // increment source ptr + //lea esi, [esi+eax] + fmul st(0), st(1) // st(0) *= st(1), stack: value*0x7FFF, (int)0x7FFF + fistp word ptr [edi] // store scaled int into dest, stack: (int)0x7FFF + + add edi, ebx // increment destination ptr + //lea edi, [edi+ebx] + + cmp esi, ecx // has src ptr reached end? + jne Float32_To_Int16_loop + + ffree st(0) + fincstp + + fwait + fnclex + fldcw savedFpuControlWord + } +} + +/* -------------------------------------------------------------------------- */ + +static void Float32_To_Int16_Clip( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, PaUtilTriangularDitherGenerator *ditherGenerator ) +{ +/* + float *src = (float*)sourceBuffer; + signed short *dest = (signed short*)destinationBuffer; + (void)ditherGenerator; // unused parameter + + while( count-- ) + { + long samp = (signed long) (*src * (32767.0f)); + PA_CLIP_( samp, -0x8000, 0x7FFF ); + *dest = (signed short) samp; + + src += sourceStride; + dest += destinationStride; + } +*/ + + short savedFpuControlWord; + + (void) ditherGenerator; /* unused parameter */ + + __asm{ + // esi -> source ptr + // eax -> source byte stride + // edi -> destination ptr + // ebx -> destination byte stride + // ecx -> source end ptr + // edx -> temp + + mov esi, sourceBuffer + + mov edx, 4 // sizeof float32 + mov eax, sourceStride + imul eax, edx // source byte stride + + mov ecx, count + imul ecx, eax + add ecx, esi // source end ptr = count * source byte stride + source ptr + + mov edi, destinationBuffer + + mov edx, 2 // sizeof int16 + mov ebx, destinationStride + imul ebx, edx // destination byte stride + + fwait + fstcw savedFpuControlWord + fldcw fpuControlWord_ + + fld int16Scaler_ // stack: (int)0x7FFF + + Float32_To_Int16_Clip_loop: + + mov edx, dword ptr [esi] // load floating point value into integer register + + and edx, 0x7FFFFFFF // mask off sign + cmp edx, 0x3F800000 // greater than 1.0 or less than -1.0 + + jg Float32_To_Int16_Clip_clamp + + // load unscaled value into st(0) + fld dword ptr [esi] // stack: value, (int)0x7FFF + add esi, eax // increment source ptr + //lea esi, [esi+eax] + fmul st(0), st(1) // st(0) *= st(1), stack: value*0x7FFF, (int)0x7FFF + fistp word ptr [edi] // store scaled int into dest, stack: (int)0x7FFF + jmp Float32_To_Int16_Clip_stored + + Float32_To_Int16_Clip_clamp: + mov edx, dword ptr [esi] // load floating point value into integer register + shr edx, 31 // move sign bit into bit 0 + add esi, eax // increment source ptr + //lea esi, [esi+eax] + add dx, 0x7FFF // convert to maximum range integers + mov word ptr [edi], dx // store clamped into into dest + + Float32_To_Int16_Clip_stored: + + add edi, ebx // increment destination ptr + //lea edi, [edi+ebx] + + cmp esi, ecx // has src ptr reached end? + jne Float32_To_Int16_Clip_loop + + ffree st(0) + fincstp + + fwait + fnclex + fldcw savedFpuControlWord + } +} + +/* -------------------------------------------------------------------------- */ + +static void Float32_To_Int16_DitherClip( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, PaUtilTriangularDitherGenerator *ditherGenerator ) +{ +/* + float *src = (float*)sourceBuffer; + signed short *dest = (signed short*)destinationBuffer; + (void)ditherGenerator; // unused parameter + + while( count-- ) + { + + float dither = PaUtil_GenerateFloatTriangularDither( ditherGenerator ); + // use smaller scaler to prevent overflow when we add the dither + float dithered = (*src * (32766.0f)) + dither; + signed long samp = (signed long) dithered; + PA_CLIP_( samp, -0x8000, 0x7FFF ); + *dest = (signed short) samp; + + src += sourceStride; + dest += destinationStride; + } +*/ + + short savedFpuControlWord; + + // spill storage: + signed long sourceByteStride; + signed long highpassedDither; + + // dither state: + unsigned long ditherPrevious = ditherGenerator->previous; + unsigned long ditherRandSeed1 = ditherGenerator->randSeed1; + unsigned long ditherRandSeed2 = ditherGenerator->randSeed2; + + __asm{ + // esi -> source ptr + // eax -> source byte stride + // edi -> destination ptr + // ebx -> destination byte stride + // ecx -> source end ptr + // edx -> temp + + mov esi, sourceBuffer + + mov edx, 4 // sizeof float32 + mov eax, sourceStride + imul eax, edx // source byte stride + + mov ecx, count + imul ecx, eax + add ecx, esi // source end ptr = count * source byte stride + source ptr + + mov edi, destinationBuffer + + mov edx, 2 // sizeof int16 + mov ebx, destinationStride + imul ebx, edx // destination byte stride + + fwait + fstcw savedFpuControlWord + fldcw fpuControlWord_ + + fld ditheredInt16Scaler_ // stack: int scaler + + Float32_To_Int16_DitherClip_loop: + + mov edx, dword ptr [esi] // load floating point value into integer register + + and edx, 0x7FFFFFFF // mask off sign + cmp edx, 0x3F800000 // greater than 1.0 or less than -1.0 + + jg Float32_To_Int16_DitherClip_clamp + + // load unscaled value into st(0) + fld dword ptr [esi] // stack: value, int scaler + add esi, eax // increment source ptr + //lea esi, [esi+eax] + fmul st(0), st(1) // st(0) *= st(1), stack: value*(int scaler), int scaler + + /* + // call PaUtil_GenerateFloatTriangularDither with C calling convention + mov sourceByteStride, eax // save eax + mov sourceEnd, ecx // save ecx + push ditherGenerator // pass ditherGenerator parameter on stack + call PaUtil_GenerateFloatTriangularDither // stack: dither, value*(int scaler), int scaler + pop edx // clear parameter off stack + mov ecx, sourceEnd // restore ecx + mov eax, sourceByteStride // restore eax + */ + + // generate dither + mov sourceByteStride, eax // save eax + mov edx, 196314165 + mov eax, ditherRandSeed1 + mul edx // eax:edx = eax * 196314165 + //add eax, 907633515 + lea eax, [eax+907633515] + mov ditherRandSeed1, eax + mov edx, 196314165 + mov eax, ditherRandSeed2 + mul edx // eax:edx = eax * 196314165 + //add eax, 907633515 + lea eax, [eax+907633515] + mov edx, ditherRandSeed1 + shr edx, PA_DITHER_SHIFT_ + mov ditherRandSeed2, eax + shr eax, PA_DITHER_SHIFT_ + //add eax, edx // eax -> current + lea eax, [eax+edx] // current = randSeed1>>x + randSeed2>>x + mov edx, ditherPrevious + neg edx + lea edx, [eax+edx] // highpass = current - previous + mov highpassedDither, edx + mov ditherPrevious, eax // previous = current + mov eax, sourceByteStride // restore eax + fild highpassedDither + fmul const_float_dither_scale_ + // end generate dither, dither signal in st(0) + + faddp st(1), st(0) // stack: dither * value*(int scaler), int scaler + fistp word ptr [edi] // store scaled int into dest, stack: int scaler + jmp Float32_To_Int16_DitherClip_stored + + Float32_To_Int16_DitherClip_clamp: + mov edx, dword ptr [esi] // load floating point value into integer register + shr edx, 31 // move sign bit into bit 0 + add esi, eax // increment source ptr + //lea esi, [esi+eax] + add dx, 0x7FFF // convert to maximum range integers + mov word ptr [edi], dx // store clamped into into dest + + Float32_To_Int16_DitherClip_stored: + + add edi, ebx // increment destination ptr + //lea edi, [edi+ebx] + + cmp esi, ecx // has src ptr reached end? + jne Float32_To_Int16_DitherClip_loop + + ffree st(0) + fincstp + + fwait + fnclex + fldcw savedFpuControlWord + } + + ditherGenerator->previous = ditherPrevious; + ditherGenerator->randSeed1 = ditherRandSeed1; + ditherGenerator->randSeed2 = ditherRandSeed2; +} + +/* -------------------------------------------------------------------------- */ + +void PaUtil_InitializeX86PlainConverters( void ) +{ + paConverters.Float32_To_Int32 = Float32_To_Int32; + paConverters.Float32_To_Int32_Clip = Float32_To_Int32_Clip; + paConverters.Float32_To_Int32_DitherClip = Float32_To_Int32_DitherClip; + + paConverters.Float32_To_Int24 = Float32_To_Int24; + paConverters.Float32_To_Int24_Clip = Float32_To_Int24_Clip; + paConverters.Float32_To_Int24_DitherClip = Float32_To_Int24_DitherClip; + + paConverters.Float32_To_Int16 = Float32_To_Int16; + paConverters.Float32_To_Int16_Clip = Float32_To_Int16_Clip; + paConverters.Float32_To_Int16_DitherClip = Float32_To_Int16_DitherClip; +} + +#endif + +/* -------------------------------------------------------------------------- */ Index: julius4/libsent/src/adin/pa/os/win/pa_x86_plain_converters.h diff -u /dev/null julius4/libsent/src/adin/pa/os/win/pa_x86_plain_converters.h:1.1 --- /dev/null Sat Feb 5 18:00:04 2011 +++ julius4/libsent/src/adin/pa/os/win/pa_x86_plain_converters.h Sat Feb 5 18:00:04 2011 @@ -0,0 +1,60 @@ +/* + * Plain Intel IA32 assembly implementations of PortAudio sample converter functions. + * Copyright (c) 1999-2002 Ross Bencina, Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/* + * The text above constitutes the entire PortAudio license; however, + * the PortAudio community also makes the following non-binding requests: + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. It is also + * requested that these non-binding requests be included along with the + * license above. + */ + +/** @file + @ingroup win_src +*/ + +#ifndef PA_X86_PLAIN_CONVERTERS_H +#define PA_X86_PLAIN_CONVERTERS_H + +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + + +/** + @brief Install optimised converter functions suitable for all IA32 processors + + It is recommended to call PaUtil_InitializeX86PlainConverters prior to calling Pa_Initialize +*/ +void PaUtil_InitializeX86PlainConverters( void ); + + +#ifdef __cplusplus +} +#endif /* __cplusplus */ +#endif /* PA_X86_PLAIN_CONVERTERS_H */ From sumomo @ users.sourceforge.jp Sat Feb 5 18:00:03 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Sat, 05 Feb 2011 18:00:03 +0900 Subject: [Julius-cvs 590] CVS update: julius4/libsent/src/adin/pa/hostapi/wdmks Message-ID: <1296896403.661591.28611.nullmailer@users.sourceforge.jp> Index: julius4/libsent/src/adin/pa/hostapi/wdmks/pa_win_wdmks.c diff -u /dev/null julius4/libsent/src/adin/pa/hostapi/wdmks/pa_win_wdmks.c:1.1 --- /dev/null Sat Feb 5 18:00:03 2011 +++ julius4/libsent/src/adin/pa/hostapi/wdmks/pa_win_wdmks.c Sat Feb 5 18:00:03 2011 @@ -0,0 +1,3283 @@ +/* + * $Id: pa_win_wdmks.c,v 1.1 2011/02/05 09:00:03 sumomo Exp $ + * PortAudio Windows WDM-KS interface + * + * Author: Andrew Baldwin + * Based on the Open Source API proposed by Ross Bencina + * Copyright (c) 1999-2004 Andrew Baldwin, Ross Bencina, Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/* + * The text above constitutes the entire PortAudio license; however, + * the PortAudio community also makes the following non-binding requests: + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. It is also + * requested that these non-binding requests be included along with the + * license above. + */ + +/** @file + @ingroup hostaip_src + @brief Portaudio WDM-KS host API. + + @note This is the implementation of the Portaudio host API using the + Windows WDM/Kernel Streaming API in order to enable very low latency + playback and recording on all modern Windows platforms (e.g. 2K, XP) + Note: This API accesses the device drivers below the usual KMIXER + component which is normally used to enable multi-client mixing and + format conversion. That means that it will lock out all other users + of a device for the duration of active stream using those devices +*/ + +#include + +/* Debugging/tracing support */ + +#define PA_LOGE_ +#define PA_LOGL_ + +#ifdef __GNUC__ + #include + #define _WIN32_WINNT 0x0501 + #define WINVER 0x0501 +#endif + +#include /* strlen() */ +#include + +#include "pa_util.h" +#include "pa_allocation.h" +#include "pa_hostapi.h" +#include "pa_stream.h" +#include "pa_cpuload.h" +#include "pa_process.h" +#include "portaudio.h" +#include "pa_debugprint.h" + +#include +#include + + +#ifdef __GNUC__ + #undef PA_LOGE_ + #define PA_LOGE_ PA_DEBUG(("%s {\n",__FUNCTION__)) + #undef PA_LOGL_ + #define PA_LOGL_ PA_DEBUG(("} %s\n",__FUNCTION__)) + /* These defines are set in order to allow the WIndows DirectX + * headers to compile with a GCC compiler such as MinGW + * NOTE: The headers may generate a few warning in GCC, but + * they should compile */ + #define _INC_MMSYSTEM + #define _INC_MMREG + #define _NTRTL_ /* Turn off default definition of DEFINE_GUIDEX */ + #define DEFINE_GUID_THUNK(name,guid) DEFINE_GUID(name,guid) + #define DEFINE_GUIDEX(n) DEFINE_GUID_THUNK( n, STATIC_##n ) + #if !defined( DEFINE_WAVEFORMATEX_GUID ) + #define DEFINE_WAVEFORMATEX_GUID(x) (USHORT)(x), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 + #endif + #define WAVE_FORMAT_ADPCM 0x0002 + #define WAVE_FORMAT_IEEE_FLOAT 0x0003 + #define WAVE_FORMAT_ALAW 0x0006 + #define WAVE_FORMAT_MULAW 0x0007 + #define WAVE_FORMAT_MPEG 0x0050 + #define WAVE_FORMAT_DRM 0x0009 + #define DYNAMIC_GUID_THUNK(l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) {l,w1,w2,{b1,b2,b3,b4,b5,b6,b7,b8}} + #define DYNAMIC_GUID(data) DYNAMIC_GUID_THUNK(data) +#endif + +#ifdef _MSC_VER + #define DYNAMIC_GUID(data) {data} + #define _INC_MMREG + #define _NTRTL_ /* Turn off default definition of DEFINE_GUIDEX */ + #undef DEFINE_GUID + #define DEFINE_GUID(n,data) EXTERN_C const GUID n = {data} + #define DEFINE_GUID_THUNK(n,data) DEFINE_GUID(n,data) + #define DEFINE_GUIDEX(n) DEFINE_GUID_THUNK(n, STATIC_##n) + #if !defined( DEFINE_WAVEFORMATEX_GUID ) + #define DEFINE_WAVEFORMATEX_GUID(x) (USHORT)(x), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 + #endif + #define WAVE_FORMAT_ADPCM 0x0002 + #define WAVE_FORMAT_IEEE_FLOAT 0x0003 + #define WAVE_FORMAT_ALAW 0x0006 + #define WAVE_FORMAT_MULAW 0x0007 + #define WAVE_FORMAT_MPEG 0x0050 + #define WAVE_FORMAT_DRM 0x0009 +#endif + +#include +#include +#include +#include +#include + +/* These next definitions allow the use of the KSUSER DLL */ +typedef KSDDKAPI DWORD WINAPI KSCREATEPIN(HANDLE, PKSPIN_CONNECT, ACCESS_MASK, PHANDLE); +extern HMODULE DllKsUser; +extern KSCREATEPIN* FunctionKsCreatePin; + +/* Forward definition to break circular type reference between pin and filter */ +struct __PaWinWdmFilter; +typedef struct __PaWinWdmFilter PaWinWdmFilter; + +/* The Pin structure + * A pin is an input or output node, e.g. for audio flow */ +typedef struct __PaWinWdmPin +{ + HANDLE handle; + PaWinWdmFilter* parentFilter; + unsigned long pinId; + KSPIN_CONNECT* pinConnect; + unsigned long pinConnectSize; + KSDATAFORMAT_WAVEFORMATEX* ksDataFormatWfx; + KSPIN_COMMUNICATION communication; + KSDATARANGE* dataRanges; + KSMULTIPLE_ITEM* dataRangesItem; + KSPIN_DATAFLOW dataFlow; + KSPIN_CINSTANCES instances; + unsigned long frameSize; + int maxChannels; + unsigned long formats; + int bestSampleRate; +} +PaWinWdmPin; + +/* The Filter structure + * A filter has a number of pins and a "friendly name" */ +struct __PaWinWdmFilter +{ + HANDLE handle; + int pinCount; + PaWinWdmPin** pins; + TCHAR filterName[MAX_PATH]; + TCHAR friendlyName[MAX_PATH]; + int maxInputChannels; + int maxOutputChannels; + unsigned long formats; + int usageCount; + int bestSampleRate; +}; + +/* PaWinWdmHostApiRepresentation - host api datastructure specific to this implementation */ +typedef struct __PaWinWdmHostApiRepresentation +{ + PaUtilHostApiRepresentation inheritedHostApiRep; + PaUtilStreamInterface callbackStreamInterface; + PaUtilStreamInterface blockingStreamInterface; + + PaUtilAllocationGroup* allocations; + PaWinWdmFilter** filters; + int filterCount; +} +PaWinWdmHostApiRepresentation; + +typedef struct __PaWinWdmDeviceInfo +{ + PaDeviceInfo inheritedDeviceInfo; + PaWinWdmFilter* filter; +} +PaWinWdmDeviceInfo; + +typedef struct __DATAPACKET +{ + KSSTREAM_HEADER Header; + OVERLAPPED Signal; +} DATAPACKET; + +/* PaWinWdmStream - a stream data structure specifically for this implementation */ +typedef struct __PaWinWdmStream +{ + PaUtilStreamRepresentation streamRepresentation; + PaUtilCpuLoadMeasurer cpuLoadMeasurer; + PaUtilBufferProcessor bufferProcessor; + + PaWinWdmPin* recordingPin; + PaWinWdmPin* playbackPin; + char* hostBuffer; + unsigned long framesPerHostIBuffer; + unsigned long framesPerHostOBuffer; + int bytesPerInputFrame; + int bytesPerOutputFrame; + int streamStarted; + int streamActive; + int streamStop; + int streamAbort; + int oldProcessPriority; + HANDLE streamThread; + HANDLE events[5]; /* 2 play + 2 record packets + abort events */ + DATAPACKET packets[4]; /* 2 play + 2 record */ + PaStreamFlags streamFlags; + /* These values handle the case where the user wants to use fewer + * channels than the device has */ + int userInputChannels; + int deviceInputChannels; + int userOutputChannels; + int deviceOutputChannels; + int inputSampleSize; + int outputSampleSize; +} +PaWinWdmStream; + +#include + +HMODULE DllKsUser = NULL; +KSCREATEPIN* FunctionKsCreatePin = NULL; + +/* prototypes for functions declared in this file */ + +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +PaError PaWinWdm_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index ); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +/* Low level I/O functions */ +static PaError WdmSyncIoctl(HANDLE handle, + unsigned long ioctlNumber, + void* inBuffer, + unsigned long inBufferCount, + void* outBuffer, + unsigned long outBufferCount, + unsigned long* bytesReturned); +static PaError WdmGetPropertySimple(HANDLE handle, + const GUID* const guidPropertySet, + unsigned long property, + void* value, + unsigned long valueCount, + void* instance, + unsigned long instanceCount); +static PaError WdmSetPropertySimple(HANDLE handle, + const GUID* const guidPropertySet, + unsigned long property, + void* value, + unsigned long valueCount, + void* instance, + unsigned long instanceCount); +static PaError WdmGetPinPropertySimple(HANDLE handle, + unsigned long pinId, + const GUID* const guidPropertySet, + unsigned long property, + void* value, + unsigned long valueCount); +static PaError WdmGetPinPropertyMulti(HANDLE handle, + unsigned long pinId, + const GUID* const guidPropertySet, + unsigned long property, + KSMULTIPLE_ITEM** ksMultipleItem); + +/** Pin management functions */ +static PaWinWdmPin* PinNew(PaWinWdmFilter* parentFilter, unsigned long pinId, PaError* error); +static void PinFree(PaWinWdmPin* pin); +static void PinClose(PaWinWdmPin* pin); +static PaError PinInstantiate(PaWinWdmPin* pin); +/*static PaError PinGetState(PaWinWdmPin* pin, KSSTATE* state); NOT USED */ +static PaError PinSetState(PaWinWdmPin* pin, KSSTATE state); +static PaError PinSetFormat(PaWinWdmPin* pin, const WAVEFORMATEX* format); +static PaError PinIsFormatSupported(PaWinWdmPin* pin, const WAVEFORMATEX* format); + +/* Filter management functions */ +static PaWinWdmFilter* FilterNew( + TCHAR* filterName, + TCHAR* friendlyName, + PaError* error); +static void FilterFree(PaWinWdmFilter* filter); +static PaWinWdmPin* FilterCreateRenderPin( + PaWinWdmFilter* filter, + const WAVEFORMATEX* wfex, + PaError* error); +static PaWinWdmPin* FilterFindViableRenderPin( + PaWinWdmFilter* filter, + const WAVEFORMATEX* wfex, + PaError* error); +static PaError FilterCanCreateRenderPin( + PaWinWdmFilter* filter, + const WAVEFORMATEX* wfex); +static PaWinWdmPin* FilterCreateCapturePin( + PaWinWdmFilter* filter, + const WAVEFORMATEX* wfex, + PaError* error); +static PaWinWdmPin* FilterFindViableCapturePin( + PaWinWdmFilter* filter, + const WAVEFORMATEX* wfex, + PaError* error); +static PaError FilterCanCreateCapturePin( + PaWinWdmFilter* filter, + const WAVEFORMATEX* pwfx); +static PaError FilterUse( + PaWinWdmFilter* filter); +static void FilterRelease( + PaWinWdmFilter* filter); + +/* Interface functions */ +static void Terminate( struct PaUtilHostApiRepresentation *hostApi ); +static PaError IsFormatSupported( + struct PaUtilHostApiRepresentation *hostApi, + const PaStreamParameters *inputParameters, + const PaStreamParameters *outputParameters, + double sampleRate ); +static PaError OpenStream( + struct PaUtilHostApiRepresentation *hostApi, + PaStream** s, + const PaStreamParameters *inputParameters, + const PaStreamParameters *outputParameters, + double sampleRate, + unsigned long framesPerBuffer, + PaStreamFlags streamFlags, + PaStreamCallback *streamCallback, + void *userData ); +static PaError CloseStream( PaStream* stream ); +static PaError StartStream( PaStream *stream ); +static PaError StopStream( PaStream *stream ); +static PaError AbortStream( PaStream *stream ); +static PaError IsStreamStopped( PaStream *s ); +static PaError IsStreamActive( PaStream *stream ); +static PaTime GetStreamTime( PaStream *stream ); +static double GetStreamCpuLoad( PaStream* stream ); +static PaError ReadStream( + PaStream* stream, + void *buffer, + unsigned long frames ); +static PaError WriteStream( + PaStream* stream, + const void *buffer, + unsigned long frames ); +static signed long GetStreamReadAvailable( PaStream* stream ); +static signed long GetStreamWriteAvailable( PaStream* stream ); + +/* Utility functions */ +static unsigned long GetWfexSize(const WAVEFORMATEX* wfex); +static PaError BuildFilterList(PaWinWdmHostApiRepresentation* wdmHostApi); +static BOOL PinWrite(HANDLE h, DATAPACKET* p); +static BOOL PinRead(HANDLE h, DATAPACKET* p); +static void DuplicateFirstChannelInt16(void* buffer, int channels, int samples); +static void DuplicateFirstChannelInt24(void* buffer, int channels, int samples); +static DWORD WINAPI ProcessingThread(LPVOID pParam); + +/* Function bodies */ + +static unsigned long GetWfexSize(const WAVEFORMATEX* wfex) +{ + if( wfex->wFormatTag == WAVE_FORMAT_PCM ) + { + return sizeof( WAVEFORMATEX ); + } + else + { + return (sizeof( WAVEFORMATEX ) + wfex->cbSize); + } +} + +/* +Low level pin/filter access functions +*/ +static PaError WdmSyncIoctl( + HANDLE handle, + unsigned long ioctlNumber, + void* inBuffer, + unsigned long inBufferCount, + void* outBuffer, + unsigned long outBufferCount, + unsigned long* bytesReturned) +{ + PaError result = paNoError; + OVERLAPPED overlapped; + int boolResult; + unsigned long dummyBytesReturned; + unsigned long error; + + if( !bytesReturned ) + { + /* User a dummy as the caller hasn't supplied one */ + bytesReturned = &dummyBytesReturned; + } + + FillMemory((void *)&overlapped,sizeof(overlapped),0); + overlapped.hEvent = CreateEvent(NULL,FALSE,FALSE,NULL); + if( !overlapped.hEvent ) + { + result = paInsufficientMemory; + goto error; + } + overlapped.hEvent = (HANDLE)((DWORD_PTR)overlapped.hEvent | 0x1); + + boolResult = DeviceIoControl(handle, ioctlNumber, inBuffer, inBufferCount, + outBuffer, outBufferCount, bytesReturned, &overlapped); + if( !boolResult ) + { + error = GetLastError(); + if( error == ERROR_IO_PENDING ) + { + error = WaitForSingleObject(overlapped.hEvent,INFINITE); + if( error != WAIT_OBJECT_0 ) + { + result = paUnanticipatedHostError; + goto error; + } + } + else if((( error == ERROR_INSUFFICIENT_BUFFER ) || + ( error == ERROR_MORE_DATA )) && + ( ioctlNumber == IOCTL_KS_PROPERTY ) && + ( outBufferCount == 0 )) + { + boolResult = TRUE; + } + else + { + result = paUnanticipatedHostError; + } + } + if( !boolResult ) + *bytesReturned = 0; + +error: + if( overlapped.hEvent ) + { + CloseHandle( overlapped.hEvent ); + } + return result; +} + +static PaError WdmGetPropertySimple(HANDLE handle, + const GUID* const guidPropertySet, + unsigned long property, + void* value, + unsigned long valueCount, + void* instance, + unsigned long instanceCount) +{ + PaError result; + KSPROPERTY* ksProperty; + unsigned long propertyCount; + + propertyCount = sizeof(KSPROPERTY) + instanceCount; + ksProperty = (KSPROPERTY*)PaUtil_AllocateMemory( propertyCount ); + if( !ksProperty ) + { + return paInsufficientMemory; + } + + FillMemory((void*)ksProperty,sizeof(ksProperty),0); + ksProperty->Set = *guidPropertySet; + ksProperty->Id = property; + ksProperty->Flags = KSPROPERTY_TYPE_GET; + + if( instance ) + { + memcpy( (void*)(((char*)ksProperty)+sizeof(KSPROPERTY)), instance, instanceCount ); + } + + result = WdmSyncIoctl( + handle, + IOCTL_KS_PROPERTY, + ksProperty, + propertyCount, + value, + valueCount, + NULL); + + PaUtil_FreeMemory( ksProperty ); + return result; +} + +static PaError WdmSetPropertySimple( + HANDLE handle, + const GUID* const guidPropertySet, + unsigned long property, + void* value, + unsigned long valueCount, + void* instance, + unsigned long instanceCount) +{ + PaError result; + KSPROPERTY* ksProperty; + unsigned long propertyCount = 0; + + propertyCount = sizeof(KSPROPERTY) + instanceCount; + ksProperty = (KSPROPERTY*)PaUtil_AllocateMemory( propertyCount ); + if( !ksProperty ) + { + return paInsufficientMemory; + } + + ksProperty->Set = *guidPropertySet; + ksProperty->Id = property; + ksProperty->Flags = KSPROPERTY_TYPE_SET; + + if( instance ) + { + memcpy((void*)((char*)ksProperty + sizeof(KSPROPERTY)), instance, instanceCount); + } + + result = WdmSyncIoctl( + handle, + IOCTL_KS_PROPERTY, + ksProperty, + propertyCount, + value, + valueCount, + NULL); + + PaUtil_FreeMemory( ksProperty ); + return result; +} + +static PaError WdmGetPinPropertySimple( + HANDLE handle, + unsigned long pinId, + const GUID* const guidPropertySet, + unsigned long property, + void* value, + unsigned long valueCount) +{ + PaError result; + + KSP_PIN ksPProp; + ksPProp.Property.Set = *guidPropertySet; + ksPProp.Property.Id = property; + ksPProp.Property.Flags = KSPROPERTY_TYPE_GET; + ksPProp.PinId = pinId; + ksPProp.Reserved = 0; + + result = WdmSyncIoctl( + handle, + IOCTL_KS_PROPERTY, + &ksPProp, + sizeof(KSP_PIN), + value, + valueCount, + NULL); + + return result; +} + +static PaError WdmGetPinPropertyMulti( + HANDLE handle, + unsigned long pinId, + const GUID* const guidPropertySet, + unsigned long property, + KSMULTIPLE_ITEM** ksMultipleItem) +{ + PaError result; + unsigned long multipleItemSize = 0; + KSP_PIN ksPProp; + + ksPProp.Property.Set = *guidPropertySet; + ksPProp.Property.Id = property; + ksPProp.Property.Flags = KSPROPERTY_TYPE_GET; + ksPProp.PinId = pinId; + ksPProp.Reserved = 0; + + result = WdmSyncIoctl( + handle, + IOCTL_KS_PROPERTY, + &ksPProp.Property, + sizeof(KSP_PIN), + NULL, + 0, + &multipleItemSize); + if( result != paNoError ) + { + return result; + } + + *ksMultipleItem = (KSMULTIPLE_ITEM*)PaUtil_AllocateMemory( multipleItemSize ); + if( !*ksMultipleItem ) + { + return paInsufficientMemory; + } + + result = WdmSyncIoctl( + handle, + IOCTL_KS_PROPERTY, + &ksPProp, + sizeof(KSP_PIN), + (void*)*ksMultipleItem, + multipleItemSize, + NULL); + + if( result != paNoError ) + { + PaUtil_FreeMemory( ksMultipleItem ); + } + + return result; +} + + +/* +Create a new pin object belonging to a filter +The pin object holds all the configuration information about the pin +before it is opened, and then the handle of the pin after is opened +*/ +static PaWinWdmPin* PinNew(PaWinWdmFilter* parentFilter, unsigned long pinId, PaError* error) +{ + PaWinWdmPin* pin; + PaError result; + unsigned long i; + KSMULTIPLE_ITEM* item = NULL; + KSIDENTIFIER* identifier; + KSDATARANGE* dataRange; + + PA_LOGE_; + PA_DEBUG(("Creating pin %d:\n",pinId)); + + /* Allocate the new PIN object */ + pin = (PaWinWdmPin*)PaUtil_AllocateMemory( sizeof(PaWinWdmPin) ); + if( !pin ) + { + result = paInsufficientMemory; + goto error; + } + + /* Zero the pin object */ + /* memset( (void*)pin, 0, sizeof(PaWinWdmPin) ); */ + + pin->parentFilter = parentFilter; + pin->pinId = pinId; + + /* Allocate a connect structure */ + pin->pinConnectSize = sizeof(KSPIN_CONNECT) + sizeof(KSDATAFORMAT_WAVEFORMATEX); + pin->pinConnect = (KSPIN_CONNECT*)PaUtil_AllocateMemory( pin->pinConnectSize ); + if( !pin->pinConnect ) + { + result = paInsufficientMemory; + goto error; + } + + /* Configure the connect structure with default values */ + pin->pinConnect->Interface.Set = KSINTERFACESETID_Standard; + pin->pinConnect->Interface.Id = KSINTERFACE_STANDARD_STREAMING; + pin->pinConnect->Interface.Flags = 0; + pin->pinConnect->Medium.Set = KSMEDIUMSETID_Standard; + pin->pinConnect->Medium.Id = KSMEDIUM_TYPE_ANYINSTANCE; + pin->pinConnect->Medium.Flags = 0; + pin->pinConnect->PinId = pinId; + pin->pinConnect->PinToHandle = NULL; + pin->pinConnect->Priority.PriorityClass = KSPRIORITY_NORMAL; + pin->pinConnect->Priority.PrioritySubClass = 1; + pin->ksDataFormatWfx = (KSDATAFORMAT_WAVEFORMATEX*)(pin->pinConnect + 1); + pin->ksDataFormatWfx->DataFormat.FormatSize = sizeof(KSDATAFORMAT_WAVEFORMATEX); + pin->ksDataFormatWfx->DataFormat.Flags = 0; + pin->ksDataFormatWfx->DataFormat.Reserved = 0; + pin->ksDataFormatWfx->DataFormat.MajorFormat = KSDATAFORMAT_TYPE_AUDIO; + pin->ksDataFormatWfx->DataFormat.SubFormat = KSDATAFORMAT_SUBTYPE_PCM; + pin->ksDataFormatWfx->DataFormat.Specifier = KSDATAFORMAT_SPECIFIER_WAVEFORMATEX; + + pin->frameSize = 0; /* Unknown until we instantiate pin */ + + /* Get the COMMUNICATION property */ + result = WdmGetPinPropertySimple( + parentFilter->handle, + pinId, + &KSPROPSETID_Pin, + KSPROPERTY_PIN_COMMUNICATION, + &pin->communication, + sizeof(KSPIN_COMMUNICATION)); + if( result != paNoError ) + goto error; + + if( /*(pin->communication != KSPIN_COMMUNICATION_SOURCE) &&*/ + (pin->communication != KSPIN_COMMUNICATION_SINK) && + (pin->communication != KSPIN_COMMUNICATION_BOTH) ) + { + PA_DEBUG(("Not source/sink\n")); + result = paInvalidDevice; + goto error; + } + + /* Get dataflow information */ + result = WdmGetPinPropertySimple( + parentFilter->handle, + pinId, + &KSPROPSETID_Pin, + KSPROPERTY_PIN_DATAFLOW, + &pin->dataFlow, + sizeof(KSPIN_DATAFLOW)); + + if( result != paNoError ) + goto error; + + /* Get the INTERFACE property list */ + result = WdmGetPinPropertyMulti( + parentFilter->handle, + pinId, + &KSPROPSETID_Pin, + KSPROPERTY_PIN_INTERFACES, + &item); + + if( result != paNoError ) + goto error; + + identifier = (KSIDENTIFIER*)(item+1); + + /* Check that at least one interface is STANDARD_STREAMING */ + result = paUnanticipatedHostError; + for( i = 0; i < item->Count; i++ ) + { + if( !memcmp( (void*)&identifier[i].Set, (void*)&KSINTERFACESETID_Standard, sizeof( GUID ) ) && + ( identifier[i].Id == KSINTERFACE_STANDARD_STREAMING ) ) + { + result = paNoError; + break; + } + } + + if( result != paNoError ) + { + PA_DEBUG(("No standard streaming\n")); + goto error; + } + + /* Don't need interfaces any more */ + PaUtil_FreeMemory( item ); + item = NULL; + + /* Get the MEDIUM properties list */ + result = WdmGetPinPropertyMulti( + parentFilter->handle, + pinId, + &KSPROPSETID_Pin, + KSPROPERTY_PIN_MEDIUMS, + &item); + + if( result != paNoError ) + goto error; + + identifier = (KSIDENTIFIER*)(item+1); /* Not actually necessary... */ + + /* Check that at least one medium is STANDARD_DEVIO */ + result = paUnanticipatedHostError; + for( i = 0; i < item->Count; i++ ) + { + if( !memcmp( (void*)&identifier[i].Set, (void*)&KSMEDIUMSETID_Standard, sizeof( GUID ) ) && + ( identifier[i].Id == KSMEDIUM_STANDARD_DEVIO ) ) + { + result = paNoError; + break; + } + } + + if( result != paNoError ) + { + PA_DEBUG(("No standard devio\n")); + goto error; + } + /* Don't need mediums any more */ + PaUtil_FreeMemory( item ); + item = NULL; + + /* Get DATARANGES */ + result = WdmGetPinPropertyMulti( + parentFilter->handle, + pinId, + &KSPROPSETID_Pin, + KSPROPERTY_PIN_DATARANGES, + &pin->dataRangesItem); + + if( result != paNoError ) + goto error; + + pin->dataRanges = (KSDATARANGE*)(pin->dataRangesItem +1); + + /* Check that at least one datarange supports audio */ + result = paUnanticipatedHostError; + dataRange = pin->dataRanges; + pin->maxChannels = 0; + pin->bestSampleRate = 0; + pin->formats = 0; + for( i = 0; i dataRangesItem->Count; i++) + { + PA_DEBUG(("DR major format %x\n",*(unsigned long*)(&(dataRange->MajorFormat)))); + /* Check that subformat is WAVEFORMATEX, PCM or WILDCARD */ + if( IS_VALID_WAVEFORMATEX_GUID(&dataRange->SubFormat) || + !memcmp((void*)&dataRange->SubFormat, (void*)&KSDATAFORMAT_SUBTYPE_PCM, sizeof ( GUID ) ) || + ( !memcmp((void*)&dataRange->SubFormat, (void*)&KSDATAFORMAT_SUBTYPE_WILDCARD, sizeof ( GUID ) ) && + ( !memcmp((void*)&dataRange->MajorFormat, (void*)&KSDATAFORMAT_TYPE_AUDIO, sizeof ( GUID ) ) ) ) ) + { + result = paNoError; + /* Record the maximum possible channels with this pin */ + PA_DEBUG(("MaxChannel: %d\n",pin->maxChannels)); + if( (int)((KSDATARANGE_AUDIO*)dataRange)->MaximumChannels > pin->maxChannels ) + { + pin->maxChannels = ((KSDATARANGE_AUDIO*)dataRange)->MaximumChannels; + /*PA_DEBUG(("MaxChannel: %d\n",pin->maxChannels));*/ + } + /* Record the formats (bit depths) that are supported */ + if( ((KSDATARANGE_AUDIO*)dataRange)->MinimumBitsPerSample <= 16 ) + { + pin->formats |= paInt16; + PA_DEBUG(("Format 16 bit supported\n")); + } + if( ((KSDATARANGE_AUDIO*)dataRange)->MaximumBitsPerSample >= 24 ) + { + pin->formats |= paInt24; + PA_DEBUG(("Format 24 bit supported\n")); + } + if( ( pin->bestSampleRate != 48000) && + (((KSDATARANGE_AUDIO*)dataRange)->MaximumSampleFrequency >= 48000) && + (((KSDATARANGE_AUDIO*)dataRange)->MinimumSampleFrequency <= 48000) ) + { + pin->bestSampleRate = 48000; + PA_DEBUG(("48kHz supported\n")); + } + else if(( pin->bestSampleRate != 48000) && ( pin->bestSampleRate != 44100 ) && + (((KSDATARANGE_AUDIO*)dataRange)->MaximumSampleFrequency >= 44100) && + (((KSDATARANGE_AUDIO*)dataRange)->MinimumSampleFrequency <= 44100) ) + { + pin->bestSampleRate = 44100; + PA_DEBUG(("44.1kHz supported\n")); + } + else + { + pin->bestSampleRate = ((KSDATARANGE_AUDIO*)dataRange)->MaximumSampleFrequency; + } + } + dataRange = (KSDATARANGE*)( ((char*)dataRange) + dataRange->FormatSize); + } + + if( result != paNoError ) + goto error; + + /* Get instance information */ + result = WdmGetPinPropertySimple( + parentFilter->handle, + pinId, + &KSPROPSETID_Pin, + KSPROPERTY_PIN_CINSTANCES, + &pin->instances, + sizeof(KSPIN_CINSTANCES)); + + if( result != paNoError ) + goto error; + + /* Success */ + *error = paNoError; + PA_DEBUG(("Pin created successfully\n")); + PA_LOGL_; + return pin; + +error: + /* + Error cleanup + */ + PaUtil_FreeMemory( item ); + if( pin ) + { + PaUtil_FreeMemory( pin->pinConnect ); + PaUtil_FreeMemory( pin->dataRangesItem ); + PaUtil_FreeMemory( pin ); + } + *error = result; + PA_LOGL_; + return NULL; +} + +/* +Safely free all resources associated with the pin +*/ +static void PinFree(PaWinWdmPin* pin) +{ + PA_LOGE_; + if( pin ) + { + PinClose(pin); + if( pin->pinConnect ) + { + PaUtil_FreeMemory( pin->pinConnect ); + } + if( pin->dataRangesItem ) + { + PaUtil_FreeMemory( pin->dataRangesItem ); + } + PaUtil_FreeMemory( pin ); + } + PA_LOGL_; +} + +/* +If the pin handle is open, close it +*/ +static void PinClose(PaWinWdmPin* pin) +{ + PA_LOGE_; + if( pin == NULL ) + { + PA_DEBUG(("Closing NULL pin!")); + PA_LOGL_; + return; + } + if( pin->handle != NULL ) + { + PinSetState( pin, KSSTATE_PAUSE ); + PinSetState( pin, KSSTATE_STOP ); + CloseHandle( pin->handle ); + pin->handle = NULL; + FilterRelease(pin->parentFilter); + } + PA_LOGL_; +} + +/* +Set the state of this (instantiated) pin +*/ +static PaError PinSetState(PaWinWdmPin* pin, KSSTATE state) +{ + PaError result; + + PA_LOGE_; + if( pin == NULL ) + return paInternalError; + if( pin->handle == NULL ) + return paInternalError; + + result = WdmSetPropertySimple( + pin->handle, + &KSPROPSETID_Connection, + KSPROPERTY_CONNECTION_STATE, + &state, + sizeof(state), + NULL, + 0); + PA_LOGL_; + return result; +} + +static PaError PinInstantiate(PaWinWdmPin* pin) +{ + PaError result; + unsigned long createResult; + KSALLOCATOR_FRAMING ksaf; + KSALLOCATOR_FRAMING_EX ksafex; + + PA_LOGE_; + + if( pin == NULL ) + return paInternalError; + if(!pin->pinConnect) + return paInternalError; + + FilterUse(pin->parentFilter); + + createResult = FunctionKsCreatePin( + pin->parentFilter->handle, + pin->pinConnect, + GENERIC_WRITE | GENERIC_READ, + &pin->handle + ); + + PA_DEBUG(("Pin create result = %x\n",createResult)); + if( createResult != ERROR_SUCCESS ) + { + FilterRelease(pin->parentFilter); + pin->handle = NULL; + return paInvalidDevice; + } + + result = WdmGetPropertySimple( + pin->handle, + &KSPROPSETID_Connection, + KSPROPERTY_CONNECTION_ALLOCATORFRAMING, + &ksaf, + sizeof(ksaf), + NULL, + 0); + + if( result != paNoError ) + { + result = WdmGetPropertySimple( + pin->handle, + &KSPROPSETID_Connection, + KSPROPERTY_CONNECTION_ALLOCATORFRAMING_EX, + &ksafex, + sizeof(ksafex), + NULL, + 0); + if( result == paNoError ) + { + pin->frameSize = ksafex.FramingItem[0].FramingRange.Range.MinFrameSize; + } + } + else + { + pin->frameSize = ksaf.FrameSize; + } + + PA_LOGL_; + + return paNoError; +} + +/* NOT USED +static PaError PinGetState(PaWinWdmPin* pin, KSSTATE* state) +{ + PaError result; + + if( state == NULL ) + return paInternalError; + if( pin == NULL ) + return paInternalError; + if( pin->handle == NULL ) + return paInternalError; + + result = WdmGetPropertySimple( + pin->handle, + KSPROPSETID_Connection, + KSPROPERTY_CONNECTION_STATE, + state, + sizeof(KSSTATE), + NULL, + 0); + + return result; +} +*/ +static PaError PinSetFormat(PaWinWdmPin* pin, const WAVEFORMATEX* format) +{ + unsigned long size; + void* newConnect; + + PA_LOGE_; + + if( pin == NULL ) + return paInternalError; + if( format == NULL ) + return paInternalError; + + size = GetWfexSize(format) + sizeof(KSPIN_CONNECT) + sizeof(KSDATAFORMAT_WAVEFORMATEX) - sizeof(WAVEFORMATEX); + + if( pin->pinConnectSize != size ) + { + newConnect = PaUtil_AllocateMemory( size ); + if( newConnect == NULL ) + return paInsufficientMemory; + memcpy( newConnect, (void*)pin->pinConnect, min(pin->pinConnectSize,size) ); + PaUtil_FreeMemory( pin->pinConnect ); + pin->pinConnect = (KSPIN_CONNECT*)newConnect; + pin->pinConnectSize = size; + pin->ksDataFormatWfx = (KSDATAFORMAT_WAVEFORMATEX*)((KSPIN_CONNECT*)newConnect + 1); + pin->ksDataFormatWfx->DataFormat.FormatSize = size - sizeof(KSPIN_CONNECT); + } + + memcpy( (void*)&(pin->ksDataFormatWfx->WaveFormatEx), format, GetWfexSize(format) ); + pin->ksDataFormatWfx->DataFormat.SampleSize = (unsigned short)(format->nChannels * (format->wBitsPerSample / 8)); + + PA_LOGL_; + + return paNoError; +} + +static PaError PinIsFormatSupported(PaWinWdmPin* pin, const WAVEFORMATEX* format) +{ + KSDATARANGE_AUDIO* dataRange; + unsigned long count; + GUID guid = DYNAMIC_GUID( DEFINE_WAVEFORMATEX_GUID(format->wFormatTag) ); + PaError result = paInvalidDevice; + + PA_LOGE_; + + if( format->wFormatTag == WAVE_FORMAT_EXTENSIBLE ) + { + guid = ((WAVEFORMATEXTENSIBLE*)format)->SubFormat; + } + dataRange = (KSDATARANGE_AUDIO*)pin->dataRanges; + for(count = 0; countdataRangesItem->Count; count++) + { + if(( !memcmp(&(dataRange->DataRange.MajorFormat),&KSDATAFORMAT_TYPE_AUDIO,sizeof(GUID)) ) || + ( !memcmp(&(dataRange->DataRange.MajorFormat),&KSDATAFORMAT_TYPE_WILDCARD,sizeof(GUID)) )) + { + /* This is an audio or wildcard datarange... */ + if(( !memcmp(&(dataRange->DataRange.SubFormat),&KSDATAFORMAT_SUBTYPE_WILDCARD,sizeof(GUID)) ) || + ( !memcmp(&(dataRange->DataRange.SubFormat),&guid,sizeof(GUID)) )) + { + if(( !memcmp(&(dataRange->DataRange.Specifier),&KSDATAFORMAT_SPECIFIER_WILDCARD,sizeof(GUID)) ) || + ( !memcmp(&(dataRange->DataRange.Specifier),&KSDATAFORMAT_SPECIFIER_WAVEFORMATEX,sizeof(GUID) ))) + { + + PA_DEBUG(("Pin:%x, DataRange:%d\n",(void*)pin,count)); + PA_DEBUG(("\tFormatSize:%d, SampleSize:%d\n",dataRange->DataRange.FormatSize,dataRange->DataRange.SampleSize)); + PA_DEBUG(("\tMaxChannels:%d\n",dataRange->MaximumChannels)); + PA_DEBUG(("\tBits:%d-%d\n",dataRange->MinimumBitsPerSample,dataRange->MaximumBitsPerSample)); + PA_DEBUG(("\tSampleRate:%d-%d\n",dataRange->MinimumSampleFrequency,dataRange->MaximumSampleFrequency)); + + if( dataRange->MaximumChannels < format->nChannels ) + { + result = paInvalidChannelCount; + continue; + } + if( dataRange->MinimumBitsPerSample > format->wBitsPerSample ) + { + result = paSampleFormatNotSupported; + continue; + } + if( dataRange->MaximumBitsPerSample < format->wBitsPerSample ) + { + result = paSampleFormatNotSupported; + continue; + } + if( dataRange->MinimumSampleFrequency > format->nSamplesPerSec ) + { + result = paInvalidSampleRate; + continue; + } + if( dataRange->MaximumSampleFrequency < format->nSamplesPerSec ) + { + result = paInvalidSampleRate; + continue; + } + /* Success! */ + PA_LOGL_; + return paNoError; + } + } + } + dataRange = (KSDATARANGE_AUDIO*)( ((char*)dataRange) + dataRange->DataRange.FormatSize); + } + + PA_LOGL_; + + return result; +} + +/** + * Create a new filter object + */ +static PaWinWdmFilter* FilterNew(TCHAR* filterName, TCHAR* friendlyName, PaError* error) +{ + PaWinWdmFilter* filter; + PaError result; + int pinId; + int valid; + + + /* Allocate the new filter object */ + filter = (PaWinWdmFilter*)PaUtil_AllocateMemory( sizeof(PaWinWdmFilter) ); + if( !filter ) + { + result = paInsufficientMemory; + goto error; + } + + /* Zero the filter object - done by AllocateMemory */ + /* memset( (void*)filter, 0, sizeof(PaWinWdmFilter) ); */ + + /* Copy the filter name */ + _tcsncpy(filter->filterName, filterName, MAX_PATH); + + /* Copy the friendly name */ + _tcsncpy(filter->friendlyName, friendlyName, MAX_PATH); + + /* Open the filter handle */ + result = FilterUse(filter); + if( result != paNoError ) + { + goto error; + } + + /* Get pin count */ + result = WdmGetPinPropertySimple + ( + filter->handle, + 0, + &KSPROPSETID_Pin, + KSPROPERTY_PIN_CTYPES, + &filter->pinCount, + sizeof(filter->pinCount) + ); + + if( result != paNoError) + { + goto error; + } + + /* Allocate pointer array to hold the pins */ + filter->pins = (PaWinWdmPin**)PaUtil_AllocateMemory( sizeof(PaWinWdmPin*) * filter->pinCount ); + if( !filter->pins ) + { + result = paInsufficientMemory; + goto error; + } + + /* Create all the pins we can */ + filter->maxInputChannels = 0; + filter->maxOutputChannels = 0; + filter->bestSampleRate = 0; + + valid = 0; + for(pinId = 0; pinId < filter->pinCount; pinId++) + { + /* Create the pin with this Id */ + PaWinWdmPin* newPin; + newPin = PinNew(filter, pinId, &result); + if( result == paInsufficientMemory ) + goto error; + if( newPin != NULL ) + { + filter->pins[pinId] = newPin; + valid = 1; + + /* Get the max output channel count */ + if(( newPin->dataFlow == KSPIN_DATAFLOW_IN ) && + (( newPin->communication == KSPIN_COMMUNICATION_SINK) || + ( newPin->communication == KSPIN_COMMUNICATION_BOTH))) + { + if(newPin->maxChannels > filter->maxOutputChannels) + filter->maxOutputChannels = newPin->maxChannels; + filter->formats |= newPin->formats; + } + /* Get the max input channel count */ + if(( newPin->dataFlow == KSPIN_DATAFLOW_OUT ) && + (( newPin->communication == KSPIN_COMMUNICATION_SINK) || + ( newPin->communication == KSPIN_COMMUNICATION_BOTH))) + { + if(newPin->maxChannels > filter->maxInputChannels) + filter->maxInputChannels = newPin->maxChannels; + filter->formats |= newPin->formats; + } + + if(newPin->bestSampleRate > filter->bestSampleRate) + { + filter->bestSampleRate = newPin->bestSampleRate; + } + } + } + + if(( filter->maxInputChannels == 0) && ( filter->maxOutputChannels == 0)) + { + /* No input or output... not valid */ + valid = 0; + } + + if( !valid ) + { + /* No valid pin was found on this filter so we destroy it */ + result = paDeviceUnavailable; + goto error; + } + + /* Close the filter handle for now + * It will be opened later when needed */ + FilterRelease(filter); + + *error = paNoError; + return filter; + +error: + /* + Error cleanup + */ + if( filter ) + { + for( pinId = 0; pinId < filter->pinCount; pinId++ ) + PinFree(filter->pins[pinId]); + PaUtil_FreeMemory( filter->pins ); + if( filter->handle ) + CloseHandle( filter->handle ); + PaUtil_FreeMemory( filter ); + } + *error = result; + return NULL; +} + +/** + * Free a previously created filter + */ +static void FilterFree(PaWinWdmFilter* filter) +{ + int pinId; + PA_LOGL_; + if( filter ) + { + for( pinId = 0; pinId < filter->pinCount; pinId++ ) + PinFree(filter->pins[pinId]); + PaUtil_FreeMemory( filter->pins ); + if( filter->handle ) + CloseHandle( filter->handle ); + PaUtil_FreeMemory( filter ); + } + PA_LOGE_; +} + +/** + * Reopen the filter handle if necessary so it can be used + **/ +static PaError FilterUse(PaWinWdmFilter* filter) +{ + assert( filter ); + + PA_LOGE_; + if( filter->handle == NULL ) + { + /* Open the filter */ + filter->handle = CreateFile( + filter->filterName, + GENERIC_READ | GENERIC_WRITE, + 0, + NULL, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, + NULL); + + if( filter->handle == NULL ) + { + return paDeviceUnavailable; + } + } + filter->usageCount++; + PA_LOGL_; + return paNoError; +} + +/** + * Release the filter handle if nobody is using it + **/ +static void FilterRelease(PaWinWdmFilter* filter) +{ + assert( filter ); + assert( filter->usageCount > 0 ); + + PA_LOGE_; + filter->usageCount--; + if( filter->usageCount == 0 ) + { + if( filter->handle != NULL ) + { + CloseHandle( filter->handle ); + filter->handle = NULL; + } + } + PA_LOGL_; +} + +/** + * Create a render (playback) Pin using the supplied format + **/ +static PaWinWdmPin* FilterCreateRenderPin(PaWinWdmFilter* filter, + const WAVEFORMATEX* wfex, + PaError* error) +{ + PaError result; + PaWinWdmPin* pin; + + assert( filter ); + + pin = FilterFindViableRenderPin(filter,wfex,&result); + if(!pin) + { + goto error; + } + result = PinSetFormat(pin,wfex); + if( result != paNoError ) + { + goto error; + } + result = PinInstantiate(pin); + if( result != paNoError ) + { + goto error; + } + + *error = paNoError; + return pin; + +error: + *error = result; + return NULL; +} + +/** + * Find a pin that supports the given format + **/ +static PaWinWdmPin* FilterFindViableRenderPin(PaWinWdmFilter* filter, + const WAVEFORMATEX* wfex, + PaError* error) +{ + int pinId; + PaWinWdmPin* pin; + PaError result = paDeviceUnavailable; + *error = paNoError; + + assert( filter ); + + for( pinId = 0; pinIdpinCount; pinId++ ) + { + pin = filter->pins[pinId]; + if( pin != NULL ) + { + if(( pin->dataFlow == KSPIN_DATAFLOW_IN ) && + (( pin->communication == KSPIN_COMMUNICATION_SINK) || + ( pin->communication == KSPIN_COMMUNICATION_BOTH))) + { + result = PinIsFormatSupported( pin, wfex ); + if( result == paNoError ) + { + return pin; + } + } + } + } + + *error = result; + return NULL; +} + +/** + * Check if there is a pin that should playback + * with the supplied format + **/ +static PaError FilterCanCreateRenderPin(PaWinWdmFilter* filter, + const WAVEFORMATEX* wfex) +{ + PaWinWdmPin* pin; + PaError result; + + assert ( filter ); + + pin = FilterFindViableRenderPin(filter,wfex,&result); + /* result will be paNoError if pin found + * or else an error code indicating what is wrong with the format + **/ + return result; +} + +/** + * Create a capture (record) Pin using the supplied format + **/ +static PaWinWdmPin* FilterCreateCapturePin(PaWinWdmFilter* filter, + const WAVEFORMATEX* wfex, + PaError* error) +{ + PaError result; + PaWinWdmPin* pin; + + assert( filter ); + + pin = FilterFindViableCapturePin(filter,wfex,&result); + if(!pin) + { + goto error; + } + + result = PinSetFormat(pin,wfex); + if( result != paNoError ) + { + goto error; + } + + result = PinInstantiate(pin); + if( result != paNoError ) + { + goto error; + } + + *error = paNoError; + return pin; + +error: + *error = result; + return NULL; +} + +/** + * Find a capture pin that supports the given format + **/ +static PaWinWdmPin* FilterFindViableCapturePin(PaWinWdmFilter* filter, + const WAVEFORMATEX* wfex, + PaError* error) +{ + int pinId; + PaWinWdmPin* pin; + PaError result = paDeviceUnavailable; + *error = paNoError; + + assert( filter ); + + for( pinId = 0; pinIdpinCount; pinId++ ) + { + pin = filter->pins[pinId]; + if( pin != NULL ) + { + if(( pin->dataFlow == KSPIN_DATAFLOW_OUT ) && + (( pin->communication == KSPIN_COMMUNICATION_SINK) || + ( pin->communication == KSPIN_COMMUNICATION_BOTH))) + { + result = PinIsFormatSupported( pin, wfex ); + if( result == paNoError ) + { + return pin; + } + } + } + } + + *error = result; + return NULL; +} + +/** + * Check if there is a pin that should playback + * with the supplied format + **/ +static PaError FilterCanCreateCapturePin(PaWinWdmFilter* filter, + const WAVEFORMATEX* wfex) +{ + PaWinWdmPin* pin; + PaError result; + + assert ( filter ); + + pin = FilterFindViableCapturePin(filter,wfex,&result); + /* result will be paNoError if pin found + * or else an error code indicating what is wrong with the format + **/ + return result; +} + +/** + * Build the list of available filters + * Use the SetupDi API to enumerate all devices in the KSCATEGORY_AUDIO which + * have a KSCATEGORY_RENDER or KSCATEGORY_CAPTURE alias. For each of these + * devices initialise a PaWinWdmFilter structure by calling our NewFilter() + * function. We enumerate devices twice, once to count how many there are, + * and once to initialize the PaWinWdmFilter structures. + */ +static PaError BuildFilterList(PaWinWdmHostApiRepresentation* wdmHostApi) +{ + PaError result = paNoError; + HDEVINFO handle = NULL; + int device; + int invalidDevices; + int slot; + SP_DEVICE_INTERFACE_DATA interfaceData; + SP_DEVICE_INTERFACE_DATA aliasData; + SP_DEVINFO_DATA devInfoData; + int noError; + const int sizeInterface = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA) + (MAX_PATH * sizeof(WCHAR)); + unsigned char interfaceDetailsArray[sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA) + (MAX_PATH * sizeof(WCHAR))]; + SP_DEVICE_INTERFACE_DETAIL_DATA* devInterfaceDetails = (SP_DEVICE_INTERFACE_DETAIL_DATA*)interfaceDetailsArray; + TCHAR friendlyName[MAX_PATH]; + HKEY hkey; + DWORD sizeFriendlyName; + DWORD type; + PaWinWdmFilter* newFilter; + GUID* category = (GUID*)&KSCATEGORY_AUDIO; + GUID* alias_render = (GUID*)&KSCATEGORY_RENDER; + GUID* alias_capture = (GUID*)&KSCATEGORY_CAPTURE; + DWORD hasAlias; + + PA_LOGE_; + + devInterfaceDetails->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA); + + /* Open a handle to search for devices (filters) */ + handle = SetupDiGetClassDevs(category,NULL,NULL,DIGCF_PRESENT | DIGCF_DEVICEINTERFACE); + if( handle == NULL ) + { + return paUnanticipatedHostError; + } + PA_DEBUG(("Setup called\n")); + + /* First let's count the number of devices so we can allocate a list */ + invalidDevices = 0; + for( device = 0;;device++ ) + { + interfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA); + interfaceData.Reserved = 0; + aliasData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA); + aliasData.Reserved = 0; + noError = SetupDiEnumDeviceInterfaces(handle,NULL,category,device,&interfaceData); + PA_DEBUG(("Enum called\n")); + if( !noError ) + break; /* No more devices */ + + /* Check this one has the render or capture alias */ + hasAlias = 0; + noError = SetupDiGetDeviceInterfaceAlias(handle,&interfaceData,alias_render,&aliasData); + PA_DEBUG(("noError = %d\n",noError)); + if(noError) + { + if(aliasData.Flags && (!(aliasData.Flags & SPINT_REMOVED))) + { + PA_DEBUG(("Device %d has render alias\n",device)); + hasAlias |= 1; /* Has render alias */ + } + else + { + PA_DEBUG(("Device %d has no render alias\n",device)); + } + } + noError = SetupDiGetDeviceInterfaceAlias(handle,&interfaceData,alias_capture,&aliasData); + if(noError) + { + if(aliasData.Flags && (!(aliasData.Flags & SPINT_REMOVED))) + { + PA_DEBUG(("Device %d has capture alias\n",device)); + hasAlias |= 2; /* Has capture alias */ + } + else + { + PA_DEBUG(("Device %d has no capture alias\n",device)); + } + } + if(!hasAlias) + invalidDevices++; /* This was not a valid capture or render audio device */ + + } + /* Remember how many there are */ + wdmHostApi->filterCount = device-invalidDevices; + + PA_DEBUG(("Interfaces found: %d\n",device-invalidDevices)); + + /* Now allocate the list of pointers to devices */ + wdmHostApi->filters = (PaWinWdmFilter**)PaUtil_AllocateMemory( sizeof(PaWinWdmFilter*) * device ); + if( !wdmHostApi->filters ) + { + if(handle != NULL) + SetupDiDestroyDeviceInfoList(handle); + return paInsufficientMemory; + } + + /* Now create filter objects for each interface found */ + slot = 0; + for( device = 0;;device++ ) + { + interfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA); + interfaceData.Reserved = 0; + aliasData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA); + aliasData.Reserved = 0; + devInfoData.cbSize = sizeof(SP_DEVINFO_DATA); + devInfoData.Reserved = 0; + + noError = SetupDiEnumDeviceInterfaces(handle,NULL,category,device,&interfaceData); + if( !noError ) + break; /* No more devices */ + + /* Check this one has the render or capture alias */ + hasAlias = 0; + noError = SetupDiGetDeviceInterfaceAlias(handle,&interfaceData,alias_render,&aliasData); + if(noError) + { + if(aliasData.Flags && (!(aliasData.Flags & SPINT_REMOVED))) + { + PA_DEBUG(("Device %d has render alias\n",device)); + hasAlias |= 1; /* Has render alias */ + } + } + noError = SetupDiGetDeviceInterfaceAlias(handle,&interfaceData,alias_capture,&aliasData); + if(noError) + { + if(aliasData.Flags && (!(aliasData.Flags & SPINT_REMOVED))) + { + PA_DEBUG(("Device %d has capture alias\n",device)); + hasAlias |= 2; /* Has capture alias */ + } + } + if(!hasAlias) + continue; /* This was not a valid capture or render audio device */ + + noError = SetupDiGetDeviceInterfaceDetail(handle,&interfaceData,devInterfaceDetails,sizeInterface,NULL,&devInfoData); + if( noError ) + { + /* Try to get the "friendly name" for this interface */ + sizeFriendlyName = sizeof(friendlyName); + /* Fix contributed by Ben Allison + * Removed KEY_SET_VALUE from flags on following call + * as its causes failure when running without admin rights + * and it was not required */ + hkey=SetupDiOpenDeviceInterfaceRegKey(handle,&interfaceData,0,KEY_QUERY_VALUE); + if(hkey!=INVALID_HANDLE_VALUE) + { + noError = RegQueryValueEx(hkey,TEXT("FriendlyName"),0,&type,(BYTE*)friendlyName,&sizeFriendlyName); + if( noError == ERROR_SUCCESS ) + { + PA_DEBUG(("Interface %d, Name: %s\n",device,friendlyName)); + RegCloseKey(hkey); + } + else + { + friendlyName[0] = 0; + } + } + newFilter = FilterNew(devInterfaceDetails->DevicePath,friendlyName,&result); + if( result == paNoError ) + { + PA_DEBUG(("Filter created\n")); + wdmHostApi->filters[slot] = newFilter; + slot++; + } + else + { + PA_DEBUG(("Filter NOT created\n")); + /* As there are now less filters than we initially thought + * we must reduce the count by one */ + wdmHostApi->filterCount--; + } + } + } + + /* Clean up */ + if(handle != NULL) + SetupDiDestroyDeviceInfoList(handle); + + return paNoError; +} + +PaError PaWinWdm_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex ) +{ + PaError result = paNoError; + int i, deviceCount; + PaWinWdmHostApiRepresentation *wdmHostApi; + PaWinWdmDeviceInfo *deviceInfoArray; + PaWinWdmFilter* pFilter; + PaWinWdmDeviceInfo *wdmDeviceInfo; + PaDeviceInfo *deviceInfo; + + PA_LOGE_; + + /* + Attempt to load the KSUSER.DLL without which we cannot create pins + We will unload this on termination + */ + if(DllKsUser == NULL) + { + DllKsUser = LoadLibrary(TEXT("ksuser.dll")); + if(DllKsUser == NULL) + goto error; + } + + FunctionKsCreatePin = (KSCREATEPIN*)GetProcAddress(DllKsUser, "KsCreatePin"); + if(FunctionKsCreatePin == NULL) + goto error; + + wdmHostApi = (PaWinWdmHostApiRepresentation*)PaUtil_AllocateMemory( sizeof(PaWinWdmHostApiRepresentation) ); + if( !wdmHostApi ) + { + result = paInsufficientMemory; + goto error; + } + + wdmHostApi->allocations = PaUtil_CreateAllocationGroup(); + if( !wdmHostApi->allocations ) + { + result = paInsufficientMemory; + goto error; + } + + result = BuildFilterList( wdmHostApi ); + if( result != paNoError ) + { + goto error; + } + deviceCount = wdmHostApi->filterCount; + + *hostApi = &wdmHostApi->inheritedHostApiRep; + (*hostApi)->info.structVersion = 1; + (*hostApi)->info.type = paWDMKS; + (*hostApi)->info.name = "Windows WDM-KS"; + (*hostApi)->info.defaultInputDevice = paNoDevice; + (*hostApi)->info.defaultOutputDevice = paNoDevice; + + if( deviceCount > 0 ) + { + (*hostApi)->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory( + wdmHostApi->allocations, sizeof(PaWinWdmDeviceInfo*) * deviceCount ); + if( !(*hostApi)->deviceInfos ) + { + result = paInsufficientMemory; + goto error; + } + + /* allocate all device info structs in a contiguous block */ + deviceInfoArray = (PaWinWdmDeviceInfo*)PaUtil_GroupAllocateMemory( + wdmHostApi->allocations, sizeof(PaWinWdmDeviceInfo) * deviceCount ); + if( !deviceInfoArray ) + { + result = paInsufficientMemory; + goto error; + } + + for( i=0; i < deviceCount; ++i ) + { + wdmDeviceInfo = &deviceInfoArray[i]; + deviceInfo = &wdmDeviceInfo->inheritedDeviceInfo; + pFilter = wdmHostApi->filters[i]; + if( pFilter == NULL ) + continue; + wdmDeviceInfo->filter = pFilter; + deviceInfo->structVersion = 2; + deviceInfo->hostApi = hostApiIndex; + deviceInfo->name = (char*)pFilter->friendlyName; + PA_DEBUG(("Device found name: %s\n",(char*)pFilter->friendlyName)); + deviceInfo->maxInputChannels = pFilter->maxInputChannels; + if(deviceInfo->maxInputChannels > 0) + { + /* Set the default input device to the first device we find with + * more than zero input channels + **/ + if((*hostApi)->info.defaultInputDevice == paNoDevice) + { + (*hostApi)->info.defaultInputDevice = i; + } + } + + deviceInfo->maxOutputChannels = pFilter->maxOutputChannels; + if(deviceInfo->maxOutputChannels > 0) + { + /* Set the default output device to the first device we find with + * more than zero output channels + **/ + if((*hostApi)->info.defaultOutputDevice == paNoDevice) + { + (*hostApi)->info.defaultOutputDevice = i; + } + } + + /* These low values are not very useful because + * a) The lowest latency we end up with can depend on many factors such + * as the device buffer sizes/granularities, sample rate, channels and format + * b) We cannot know the device buffer sizes until we try to open/use it at + * a particular setting + * So: we give 512x48000Hz frames as the default low input latency + **/ + deviceInfo->defaultLowInputLatency = (512.0/48000.0); + deviceInfo->defaultLowOutputLatency = (512.0/48000.0); + deviceInfo->defaultHighInputLatency = (4096.0/48000.0); + deviceInfo->defaultHighOutputLatency = (4096.0/48000.0); + deviceInfo->defaultSampleRate = (double)(pFilter->bestSampleRate); + + (*hostApi)->deviceInfos[i] = deviceInfo; + } + } + + (*hostApi)->info.deviceCount = deviceCount; + + (*hostApi)->Terminate = Terminate; + (*hostApi)->OpenStream = OpenStream; + (*hostApi)->IsFormatSupported = IsFormatSupported; + + PaUtil_InitializeStreamInterface( &wdmHostApi->callbackStreamInterface, CloseStream, StartStream, + StopStream, AbortStream, IsStreamStopped, IsStreamActive, + GetStreamTime, GetStreamCpuLoad, + PaUtil_DummyRead, PaUtil_DummyWrite, + PaUtil_DummyGetReadAvailable, PaUtil_DummyGetWriteAvailable ); + + PaUtil_InitializeStreamInterface( &wdmHostApi->blockingStreamInterface, CloseStream, StartStream, + StopStream, AbortStream, IsStreamStopped, IsStreamActive, + GetStreamTime, PaUtil_DummyGetCpuLoad, + ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable ); + + PA_LOGL_; + return result; + +error: + if( DllKsUser != NULL ) + { + FreeLibrary( DllKsUser ); + DllKsUser = NULL; + } + + if( wdmHostApi ) + { + PaUtil_FreeMemory( wdmHostApi->filters ); + if( wdmHostApi->allocations ) + { + PaUtil_FreeAllAllocations( wdmHostApi->allocations ); + PaUtil_DestroyAllocationGroup( wdmHostApi->allocations ); + } + PaUtil_FreeMemory( wdmHostApi ); + } + PA_LOGL_; + return result; +} + + +static void Terminate( struct PaUtilHostApiRepresentation *hostApi ) +{ + PaWinWdmHostApiRepresentation *wdmHostApi = (PaWinWdmHostApiRepresentation*)hostApi; + int i; + PA_LOGE_; + + if( wdmHostApi->filters ) + { + for( i=0; ifilterCount; i++) + { + if( wdmHostApi->filters[i] != NULL ) + { + FilterFree( wdmHostApi->filters[i] ); + wdmHostApi->filters[i] = NULL; + } + } + } + PaUtil_FreeMemory( wdmHostApi->filters ); + if( wdmHostApi->allocations ) + { + PaUtil_FreeAllAllocations( wdmHostApi->allocations ); + PaUtil_DestroyAllocationGroup( wdmHostApi->allocations ); + } + PaUtil_FreeMemory( wdmHostApi ); + PA_LOGL_; +} + +static void FillWFEXT( WAVEFORMATEXTENSIBLE* pwfext, PaSampleFormat sampleFormat, double sampleRate, int channelCount) +{ + PA_LOGE_; + PA_DEBUG(( "sampleFormat = %lx\n" , sampleFormat )); + PA_DEBUG(( "sampleRate = %f\n" , sampleRate )); + PA_DEBUG(( "chanelCount = %d\n", channelCount )); + + pwfext->Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE; + pwfext->Format.nChannels = channelCount; + pwfext->Format.nSamplesPerSec = (int)sampleRate; + if(channelCount == 1) + pwfext->dwChannelMask = KSAUDIO_SPEAKER_DIRECTOUT; + else + pwfext->dwChannelMask = KSAUDIO_SPEAKER_STEREO; + if(sampleFormat == paFloat32) + { + pwfext->Format.nBlockAlign = channelCount * 4; + pwfext->Format.wBitsPerSample = 32; + pwfext->Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE)-sizeof(WAVEFORMATEX); + pwfext->Samples.wValidBitsPerSample = 32; + pwfext->SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT; + } + else if(sampleFormat == paInt32) + { + pwfext->Format.nBlockAlign = channelCount * 4; + pwfext->Format.wBitsPerSample = 32; + pwfext->Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE)-sizeof(WAVEFORMATEX); + pwfext->Samples.wValidBitsPerSample = 32; + pwfext->SubFormat = KSDATAFORMAT_SUBTYPE_PCM; + } + else if(sampleFormat == paInt24) + { + pwfext->Format.nBlockAlign = channelCount * 3; + pwfext->Format.wBitsPerSample = 24; + pwfext->Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE)-sizeof(WAVEFORMATEX); + pwfext->Samples.wValidBitsPerSample = 24; + pwfext->SubFormat = KSDATAFORMAT_SUBTYPE_PCM; + } + else if(sampleFormat == paInt16) + { + pwfext->Format.nBlockAlign = channelCount * 2; + pwfext->Format.wBitsPerSample = 16; + pwfext->Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE)-sizeof(WAVEFORMATEX); + pwfext->Samples.wValidBitsPerSample = 16; + pwfext->SubFormat = KSDATAFORMAT_SUBTYPE_PCM; + } + pwfext->Format.nAvgBytesPerSec = pwfext->Format.nSamplesPerSec * pwfext->Format.nBlockAlign; + + PA_LOGL_; +} + +static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi, + const PaStreamParameters *inputParameters, + const PaStreamParameters *outputParameters, + double sampleRate ) +{ + int inputChannelCount, outputChannelCount; + PaSampleFormat inputSampleFormat, outputSampleFormat; + PaWinWdmHostApiRepresentation *wdmHostApi = (PaWinWdmHostApiRepresentation*)hostApi; + PaWinWdmFilter* pFilter; + int result = paFormatIsSupported; + WAVEFORMATEXTENSIBLE wfx; + + PA_LOGE_; + + if( inputParameters ) + { + inputChannelCount = inputParameters->channelCount; + inputSampleFormat = inputParameters->sampleFormat; + + /* all standard sample formats are supported by the buffer adapter, + this implementation doesn't support any custom sample formats */ + if( inputSampleFormat & paCustomFormat ) + return paSampleFormatNotSupported; + + /* unless alternate device specification is supported, reject the use of + paUseHostApiSpecificDeviceSpecification */ + + if( inputParameters->device == paUseHostApiSpecificDeviceSpecification ) + return paInvalidDevice; + + /* check that input device can support inputChannelCount */ + if( inputChannelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels ) + return paInvalidChannelCount; + + /* validate inputStreamInfo */ + if( inputParameters->hostApiSpecificStreamInfo ) + return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */ + + /* Check that the input format is supported */ + FillWFEXT(&wfx,paInt16,sampleRate,inputChannelCount); + + pFilter = wdmHostApi->filters[inputParameters->device]; + result = FilterCanCreateCapturePin(pFilter,(const WAVEFORMATEX*)&wfx); + if( result != paNoError ) + { + /* Try a WAVE_FORMAT_PCM instead */ + wfx.Format.wFormatTag = WAVE_FORMAT_PCM; + wfx.Format.cbSize = 0; + wfx.Samples.wValidBitsPerSample = 0; + wfx.dwChannelMask = 0; + wfx.SubFormat = GUID_NULL; + result = FilterCanCreateCapturePin(pFilter,(const WAVEFORMATEX*)&wfx); + if( result != paNoError ) + return result; + } + } + else + { + inputChannelCount = 0; + } + + if( outputParameters ) + { + outputChannelCount = outputParameters->channelCount; + outputSampleFormat = outputParameters->sampleFormat; + + /* all standard sample formats are supported by the buffer adapter, + this implementation doesn't support any custom sample formats */ + if( outputSampleFormat & paCustomFormat ) + return paSampleFormatNotSupported; + + /* unless alternate device specification is supported, reject the use of + paUseHostApiSpecificDeviceSpecification */ + + if( outputParameters->device == paUseHostApiSpecificDeviceSpecification ) + return paInvalidDevice; + + /* check that output device can support outputChannelCount */ + if( outputChannelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels ) + return paInvalidChannelCount; + + /* validate outputStreamInfo */ + if( outputParameters->hostApiSpecificStreamInfo ) + return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */ + + /* Check that the output format is supported */ + FillWFEXT(&wfx,paInt16,sampleRate,outputChannelCount); + + pFilter = wdmHostApi->filters[outputParameters->device]; + result = FilterCanCreateRenderPin(pFilter,(const WAVEFORMATEX*)&wfx); + if( result != paNoError ) + { + /* Try a WAVE_FORMAT_PCM instead */ + wfx.Format.wFormatTag = WAVE_FORMAT_PCM; + wfx.Format.cbSize = 0; + wfx.Samples.wValidBitsPerSample = 0; + wfx.dwChannelMask = 0; + wfx.SubFormat = GUID_NULL; + result = FilterCanCreateRenderPin(pFilter,(const WAVEFORMATEX*)&wfx); + if( result != paNoError ) + return result; + } + + } + else + { + outputChannelCount = 0; + } + + /* + IMPLEMENT ME: + + - if a full duplex stream is requested, check that the combination + of input and output parameters is supported if necessary + + - check that the device supports sampleRate + + Because the buffer adapter handles conversion between all standard + sample formats, the following checks are only required if paCustomFormat + is implemented, or under some other unusual conditions. + + - check that input device can support inputSampleFormat, or that + we have the capability to convert from inputSampleFormat to + a native format + + - check that output device can support outputSampleFormat, or that + we have the capability to convert from outputSampleFormat to + a native format + */ + if((inputChannelCount == 0)&&(outputChannelCount == 0)) + result = paSampleFormatNotSupported; /* Not right error */ + + PA_LOGL_; + return result; +} + +/* see pa_hostapi.h for a list of validity guarantees made about OpenStream parameters */ + +static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi, + PaStream** s, + const PaStreamParameters *inputParameters, + const PaStreamParameters *outputParameters, + double sampleRate, + unsigned long framesPerBuffer, + PaStreamFlags streamFlags, + PaStreamCallback *streamCallback, + void *userData ) +{ + PaError result = paNoError; + PaWinWdmHostApiRepresentation *wdmHostApi = (PaWinWdmHostApiRepresentation*)hostApi; + PaWinWdmStream *stream = 0; + /* unsigned long framesPerHostBuffer; these may not be equivalent for all implementations */ + PaSampleFormat inputSampleFormat, outputSampleFormat; + PaSampleFormat hostInputSampleFormat, hostOutputSampleFormat; + int userInputChannels,userOutputChannels; + int size; + PaWinWdmFilter* pFilter; + WAVEFORMATEXTENSIBLE wfx; + + PA_LOGE_; + PA_DEBUG(("OpenStream:sampleRate = %f\n",sampleRate)); + PA_DEBUG(("OpenStream:framesPerBuffer = %lu\n",framesPerBuffer)); + + if( inputParameters ) + { + userInputChannels = inputParameters->channelCount; + inputSampleFormat = inputParameters->sampleFormat; + + /* unless alternate device specification is supported, reject the use of + paUseHostApiSpecificDeviceSpecification */ + + if( inputParameters->device == paUseHostApiSpecificDeviceSpecification ) + return paInvalidDevice; + + /* check that input device can support stream->userInputChannels */ + if( userInputChannels > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels ) + return paInvalidChannelCount; + + /* validate inputStreamInfo */ + if( inputParameters->hostApiSpecificStreamInfo ) + return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */ + + } + else + { + userInputChannels = 0; + inputSampleFormat = hostInputSampleFormat = paInt16; /* Surpress 'uninitialised var' warnings. */ + } + + if( outputParameters ) + { + userOutputChannels = outputParameters->channelCount; + outputSampleFormat = outputParameters->sampleFormat; + + /* unless alternate device specification is supported, reject the use of + paUseHostApiSpecificDeviceSpecification */ + + if( outputParameters->device == paUseHostApiSpecificDeviceSpecification ) + return paInvalidDevice; + + /* check that output device can support stream->userInputChannels */ + if( userOutputChannels > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels ) + return paInvalidChannelCount; + + /* validate outputStreamInfo */ + if( outputParameters->hostApiSpecificStreamInfo ) + return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */ + + } + else + { + userOutputChannels = 0; + outputSampleFormat = hostOutputSampleFormat = paInt16; /* Surpress 'uninitialized var' warnings. */ + } + + /* validate platform specific flags */ + if( (streamFlags & paPlatformSpecificFlags) != 0 ) + return paInvalidFlag; /* unexpected platform specific flag */ + + stream = (PaWinWdmStream*)PaUtil_AllocateMemory( sizeof(PaWinWdmStream) ); + if( !stream ) + { + result = paInsufficientMemory; + goto error; + } + /* Zero the stream object */ + /* memset((void*)stream,0,sizeof(PaWinWdmStream)); */ + + if( streamCallback ) + { + PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation, + &wdmHostApi->callbackStreamInterface, streamCallback, userData ); + } + else + { + PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation, + &wdmHostApi->blockingStreamInterface, streamCallback, userData ); + } + + PaUtil_InitializeCpuLoadMeasurer( &stream->cpuLoadMeasurer, sampleRate ); + + /* Instantiate the input pin if necessary */ + if(userInputChannels > 0) + { + result = paSampleFormatNotSupported; + pFilter = wdmHostApi->filters[inputParameters->device]; + stream->userInputChannels = userInputChannels; + + if(((inputSampleFormat & ~paNonInterleaved) & pFilter->formats) != 0) + { /* inputSampleFormat is supported, so try to use it */ + hostInputSampleFormat = inputSampleFormat; + FillWFEXT(&wfx, hostInputSampleFormat, sampleRate, stream->userInputChannels); + stream->bytesPerInputFrame = wfx.Format.nBlockAlign; + stream->recordingPin = FilterCreateCapturePin(pFilter, (const WAVEFORMATEX*)&wfx, &result); + stream->deviceInputChannels = stream->userInputChannels; + } + + if(result != paNoError) + { /* Search through all PaSampleFormats to find one that works */ + hostInputSampleFormat = paFloat32; + + do { + FillWFEXT(&wfx, hostInputSampleFormat, sampleRate, stream->userInputChannels); + stream->bytesPerInputFrame = wfx.Format.nBlockAlign; + stream->recordingPin = FilterCreateCapturePin(pFilter, (const WAVEFORMATEX*)&wfx, &result); + stream->deviceInputChannels = stream->userInputChannels; + + if(stream->recordingPin == NULL) result = paSampleFormatNotSupported; + if(result != paNoError) hostInputSampleFormat <<= 1; + } + while(result != paNoError && hostInputSampleFormat <= paUInt8); + } + + if(result != paNoError) + { /* None of the PaSampleFormats worked. Set the hostInputSampleFormat to the best fit + * and try a PCM format. + **/ + hostInputSampleFormat = + PaUtil_SelectClosestAvailableFormat( pFilter->formats, inputSampleFormat ); + + /* Try a WAVE_FORMAT_PCM instead */ + wfx.Format.wFormatTag = WAVE_FORMAT_PCM; + wfx.Format.cbSize = 0; + wfx.Samples.wValidBitsPerSample = 0; + wfx.dwChannelMask = 0; + wfx.SubFormat = GUID_NULL; + stream->recordingPin = FilterCreateCapturePin(pFilter,(const WAVEFORMATEX*)&wfx,&result); + if(stream->recordingPin == NULL) result = paSampleFormatNotSupported; + } + + if( result != paNoError ) + { + /* Some or all KS devices can only handle the exact number of channels + * they specify. But PortAudio clients expect to be able to + * at least specify mono I/O on a multi-channel device + * If this is the case, then we will do the channel mapping internally + **/ + if( stream->userInputChannels < pFilter->maxInputChannels ) + { + FillWFEXT(&wfx,hostInputSampleFormat,sampleRate,pFilter->maxInputChannels); + stream->bytesPerInputFrame = wfx.Format.nBlockAlign; + stream->recordingPin = FilterCreateCapturePin(pFilter,(const WAVEFORMATEX*)&wfx,&result); + stream->deviceInputChannels = pFilter->maxInputChannels; + + if( result != paNoError ) + { + /* Try a WAVE_FORMAT_PCM instead */ + wfx.Format.wFormatTag = WAVE_FORMAT_PCM; + wfx.Format.cbSize = 0; + wfx.Samples.wValidBitsPerSample = 0; + wfx.dwChannelMask = 0; + wfx.SubFormat = GUID_NULL; + stream->recordingPin = FilterCreateCapturePin(pFilter,(const WAVEFORMATEX*)&wfx,&result); + } + } + } + + if(stream->recordingPin == NULL) + { + goto error; + } + + switch(hostInputSampleFormat) + { + case paInt16: stream->inputSampleSize = 2; break; + case paInt24: stream->inputSampleSize = 3; break; + case paInt32: + case paFloat32: stream->inputSampleSize = 4; break; + } + + stream->recordingPin->frameSize /= stream->bytesPerInputFrame; + PA_DEBUG(("Pin output frames: %d\n",stream->recordingPin->frameSize)); + } + else + { + stream->recordingPin = NULL; + stream->bytesPerInputFrame = 0; + } + + /* Instantiate the output pin if necessary */ + if(userOutputChannels > 0) + { + result = paSampleFormatNotSupported; + pFilter = wdmHostApi->filters[outputParameters->device]; + stream->userOutputChannels = userOutputChannels; + + if(((outputSampleFormat & ~paNonInterleaved) & pFilter->formats) != 0) + { + hostOutputSampleFormat = outputSampleFormat; + FillWFEXT(&wfx,hostOutputSampleFormat,sampleRate,stream->userOutputChannels); + stream->bytesPerOutputFrame = wfx.Format.nBlockAlign; + stream->playbackPin = FilterCreateRenderPin(pFilter,(WAVEFORMATEX*)&wfx,&result); + stream->deviceOutputChannels = stream->userOutputChannels; + } + + if(result != paNoError) + { + hostOutputSampleFormat = paFloat32; + + do { + FillWFEXT(&wfx,hostOutputSampleFormat,sampleRate,stream->userOutputChannels); + stream->bytesPerOutputFrame = wfx.Format.nBlockAlign; + stream->playbackPin = FilterCreateRenderPin(pFilter,(WAVEFORMATEX*)&wfx,&result); + stream->deviceOutputChannels = stream->userOutputChannels; + + if(stream->playbackPin == NULL) result = paSampleFormatNotSupported; + if(result != paNoError) hostOutputSampleFormat <<= 1; + } + while(result != paNoError && hostOutputSampleFormat <= paUInt8); + } + + if(result != paNoError) + { + hostOutputSampleFormat = + PaUtil_SelectClosestAvailableFormat( pFilter->formats, outputSampleFormat ); + + /* Try a WAVE_FORMAT_PCM instead */ + wfx.Format.wFormatTag = WAVE_FORMAT_PCM; + wfx.Format.cbSize = 0; + wfx.Samples.wValidBitsPerSample = 0; + wfx.dwChannelMask = 0; + wfx.SubFormat = GUID_NULL; + stream->playbackPin = FilterCreateRenderPin(pFilter,(WAVEFORMATEX*)&wfx,&result); + if(stream->playbackPin == NULL) result = paSampleFormatNotSupported; + } + + if( result != paNoError ) + { + /* Some or all KS devices can only handle the exact number of channels + * they specify. But PortAudio clients expect to be able to + * at least specify mono I/O on a multi-channel device + * If this is the case, then we will do the channel mapping internally + **/ + if( stream->userOutputChannels < pFilter->maxOutputChannels ) + { + FillWFEXT(&wfx,hostOutputSampleFormat,sampleRate,pFilter->maxOutputChannels); + stream->bytesPerOutputFrame = wfx.Format.nBlockAlign; + stream->playbackPin = FilterCreateRenderPin(pFilter,(const WAVEFORMATEX*)&wfx,&result); + stream->deviceOutputChannels = pFilter->maxOutputChannels; + if( result != paNoError ) + { + /* Try a WAVE_FORMAT_PCM instead */ + wfx.Format.wFormatTag = WAVE_FORMAT_PCM; + wfx.Format.cbSize = 0; + wfx.Samples.wValidBitsPerSample = 0; + wfx.dwChannelMask = 0; + wfx.SubFormat = GUID_NULL; + stream->playbackPin = FilterCreateRenderPin(pFilter,(const WAVEFORMATEX*)&wfx,&result); + } + } + } + + if(stream->playbackPin == NULL) + { + goto error; + } + + switch(hostOutputSampleFormat) + { + case paInt16: stream->outputSampleSize = 2; break; + case paInt24: stream->outputSampleSize = 3; break; + case paInt32: + case paFloat32: stream->outputSampleSize = 4; break; + } + + stream->playbackPin->frameSize /= stream->bytesPerOutputFrame; + PA_DEBUG(("Pin output frames: %d\n",stream->playbackPin->frameSize)); + } + else + { + stream->playbackPin = NULL; + stream->bytesPerOutputFrame = 0; + } + + /* Calculate the framesPerHostXxxxBuffer size based upon the suggested latency values */ + + /* Record the buffer length */ + if(inputParameters) + { + /* Calculate the frames from the user's value - add a bit to round up */ + stream->framesPerHostIBuffer = (unsigned long)((inputParameters->suggestedLatency*sampleRate)+0.0001); + if(stream->framesPerHostIBuffer > (unsigned long)sampleRate) + { /* Upper limit is 1 second */ + stream->framesPerHostIBuffer = (unsigned long)sampleRate; + } + else if(stream->framesPerHostIBuffer < stream->recordingPin->frameSize) + { + stream->framesPerHostIBuffer = stream->recordingPin->frameSize; + } + PA_DEBUG(("Input frames chosen:%ld\n",stream->framesPerHostIBuffer)); + } + + if(outputParameters) + { + /* Calculate the frames from the user's value - add a bit to round up */ + stream->framesPerHostOBuffer = (unsigned long)((outputParameters->suggestedLatency*sampleRate)+0.0001); + if(stream->framesPerHostOBuffer > (unsigned long)sampleRate) + { /* Upper limit is 1 second */ + stream->framesPerHostOBuffer = (unsigned long)sampleRate; + } + else if(stream->framesPerHostOBuffer < stream->playbackPin->frameSize) + { + stream->framesPerHostOBuffer = stream->playbackPin->frameSize; + } + PA_DEBUG(("Output frames chosen:%ld\n",stream->framesPerHostOBuffer)); + } + + /* Host buffer size is bounded to the largest of the input and output + frame sizes */ + + result = PaUtil_InitializeBufferProcessor( &stream->bufferProcessor, + stream->userInputChannels, inputSampleFormat, hostInputSampleFormat, + stream->userOutputChannels, outputSampleFormat, hostOutputSampleFormat, + sampleRate, streamFlags, framesPerBuffer, + max(stream->framesPerHostOBuffer,stream->framesPerHostIBuffer), + paUtilBoundedHostBufferSize, + streamCallback, userData ); + if( result != paNoError ) + goto error; + + stream->streamRepresentation.streamInfo.inputLatency = + ((double)stream->framesPerHostIBuffer) / sampleRate; + stream->streamRepresentation.streamInfo.outputLatency = + ((double)stream->framesPerHostOBuffer) / sampleRate; + stream->streamRepresentation.streamInfo.sampleRate = sampleRate; + + PA_DEBUG(("BytesPerInputFrame = %d\n",stream->bytesPerInputFrame)); + PA_DEBUG(("BytesPerOutputFrame = %d\n",stream->bytesPerOutputFrame)); + + /* Allocate all the buffers for host I/O */ + size = 2 * (stream->framesPerHostIBuffer*stream->bytesPerInputFrame + stream->framesPerHostOBuffer*stream->bytesPerOutputFrame); + PA_DEBUG(("Buffer size = %d\n",size)); + stream->hostBuffer = (char*)PaUtil_AllocateMemory(size); + PA_DEBUG(("Buffer allocated\n")); + if( !stream->hostBuffer ) + { + PA_DEBUG(("Cannot allocate host buffer!\n")); + result = paInsufficientMemory; + goto error; + } + PA_DEBUG(("Buffer start = %p\n",stream->hostBuffer)); + /* memset(stream->hostBuffer,0,size); */ + + /* Set up the packets */ + stream->events[0] = CreateEvent(NULL, FALSE, FALSE, NULL); + ResetEvent(stream->events[0]); /* Record buffer 1 */ + stream->events[1] = CreateEvent(NULL, FALSE, FALSE, NULL); + ResetEvent(stream->events[1]); /* Record buffer 2 */ + stream->events[2] = CreateEvent(NULL, FALSE, FALSE, NULL); + ResetEvent(stream->events[2]); /* Play buffer 1 */ + stream->events[3] = CreateEvent(NULL, FALSE, FALSE, NULL); + ResetEvent(stream->events[3]); /* Play buffer 2 */ + stream->events[4] = CreateEvent(NULL, FALSE, FALSE, NULL); + ResetEvent(stream->events[4]); /* Abort event */ + if(stream->userInputChannels > 0) + { + DATAPACKET *p = &(stream->packets[0]); + p->Signal.hEvent = stream->events[0]; + p->Header.Data = stream->hostBuffer; + p->Header.FrameExtent = stream->framesPerHostIBuffer*stream->bytesPerInputFrame; + p->Header.DataUsed = 0; + p->Header.Size = sizeof(p->Header); + p->Header.PresentationTime.Numerator = 1; + p->Header.PresentationTime.Denominator = 1; + + p = &(stream->packets[1]); + p->Signal.hEvent = stream->events[1]; + p->Header.Data = stream->hostBuffer + stream->framesPerHostIBuffer*stream->bytesPerInputFrame; + p->Header.FrameExtent = stream->framesPerHostIBuffer*stream->bytesPerInputFrame; + p->Header.DataUsed = 0; + p->Header.Size = sizeof(p->Header); + p->Header.PresentationTime.Numerator = 1; + p->Header.PresentationTime.Denominator = 1; + } + if(stream->userOutputChannels > 0) + { + DATAPACKET *p = &(stream->packets[2]); + p->Signal.hEvent = stream->events[2]; + p->Header.Data = stream->hostBuffer + 2*stream->framesPerHostIBuffer*stream->bytesPerInputFrame; + p->Header.FrameExtent = stream->framesPerHostOBuffer*stream->bytesPerOutputFrame; + p->Header.DataUsed = stream->framesPerHostOBuffer*stream->bytesPerOutputFrame; + p->Header.Size = sizeof(p->Header); + p->Header.PresentationTime.Numerator = 1; + p->Header.PresentationTime.Denominator = 1; + + p = &(stream->packets[3]); + p->Signal.hEvent = stream->events[3]; + p->Header.Data = stream->hostBuffer + 2*stream->framesPerHostIBuffer*stream->bytesPerInputFrame + stream->framesPerHostOBuffer*stream->bytesPerOutputFrame; + p->Header.FrameExtent = stream->framesPerHostOBuffer*stream->bytesPerOutputFrame; + p->Header.DataUsed = stream->framesPerHostOBuffer*stream->bytesPerOutputFrame; + p->Header.Size = sizeof(p->Header); + p->Header.PresentationTime.Numerator = 1; + p->Header.PresentationTime.Denominator = 1; + } + + stream->streamStarted = 0; + stream->streamActive = 0; + stream->streamStop = 0; + stream->streamAbort = 0; + stream->streamFlags = streamFlags; + stream->oldProcessPriority = REALTIME_PRIORITY_CLASS; + + *s = (PaStream*)stream; + + PA_LOGL_; + return result; + +error: + size = 5; + while(size--) + { + if(stream->events[size] != NULL) + { + CloseHandle(stream->events[size]); + stream->events[size] = NULL; + } + } + if(stream->hostBuffer) + PaUtil_FreeMemory( stream->hostBuffer ); + + if(stream->playbackPin) + PinClose(stream->playbackPin); + if(stream->recordingPin) + PinClose(stream->recordingPin); + + if( stream ) + PaUtil_FreeMemory( stream ); + + PA_LOGL_; + return result; +} + +/* + When CloseStream() is called, the multi-api layer ensures that + the stream has already been stopped or aborted. +*/ +static PaError CloseStream( PaStream* s ) +{ + PaError result = paNoError; + PaWinWdmStream *stream = (PaWinWdmStream*)s; + int size; + + PA_LOGE_; + + assert(!stream->streamStarted); + assert(!stream->streamActive); + + PaUtil_TerminateBufferProcessor( &stream->bufferProcessor ); + PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation ); + size = 5; + while(size--) + { + if(stream->events[size] != NULL) + { + CloseHandle(stream->events[size]); + stream->events[size] = NULL; + } + } + if(stream->hostBuffer) + PaUtil_FreeMemory( stream->hostBuffer ); + + if(stream->playbackPin) + PinClose(stream->playbackPin); + if(stream->recordingPin) + PinClose(stream->recordingPin); + + PaUtil_FreeMemory( stream ); + + PA_LOGL_; + return result; +} + +/* +Write the supplied packet to the pin +Asynchronous +Should return false on success +*/ +static BOOL PinWrite(HANDLE h, DATAPACKET* p) +{ + unsigned long cbReturned = 0; + return DeviceIoControl(h,IOCTL_KS_WRITE_STREAM,NULL,0, + &p->Header,p->Header.Size,&cbReturned,&p->Signal); +} + +/* +Read to the supplied packet from the pin +Asynchronous +Should return false on success +*/ +static BOOL PinRead(HANDLE h, DATAPACKET* p) +{ + unsigned long cbReturned = 0; + return DeviceIoControl(h,IOCTL_KS_READ_STREAM,NULL,0, + &p->Header,p->Header.Size,&cbReturned,&p->Signal); +} + +/* +Copy the first interleaved channel of 16 bit data to the other channels +*/ +static void DuplicateFirstChannelInt16(void* buffer, int channels, int samples) +{ + unsigned short* data = (unsigned short*)buffer; + int channel; + unsigned short sourceSample; + while( samples-- ) + { + sourceSample = *data++; + channel = channels-1; + while( channel-- ) + { + *data++ = sourceSample; + } + } +} + +/* +Copy the first interleaved channel of 24 bit data to the other channels +*/ +static void DuplicateFirstChannelInt24(void* buffer, int channels, int samples) +{ + unsigned char* data = (unsigned char*)buffer; + int channel; + unsigned char sourceSample[3]; + while( samples-- ) + { + sourceSample[0] = data[0]; + sourceSample[1] = data[1]; + sourceSample[2] = data[2]; + data += 3; + channel = channels-1; + while( channel-- ) + { + data[0] = sourceSample[0]; + data[1] = sourceSample[1]; + data[2] = sourceSample[2]; + data += 3; + } + } +} + +/* +Copy the first interleaved channel of 32 bit data to the other channels +*/ +static void DuplicateFirstChannelInt32(void* buffer, int channels, int samples) +{ + unsigned long* data = (unsigned long*)buffer; + int channel; + unsigned long sourceSample; + while( samples-- ) + { + sourceSample = *data++; + channel = channels-1; + while( channel-- ) + { + *data++ = sourceSample; + } + } +} + +static DWORD WINAPI ProcessingThread(LPVOID pParam) +{ + PaWinWdmStream *stream = (PaWinWdmStream*)pParam; + PaStreamCallbackTimeInfo ti; + int cbResult = paContinue; + int inbuf = 0; + int outbuf = 0; + int pending = 0; + PaError result; + unsigned long wait; + unsigned long eventSignaled; + int fillPlaybuf = 0; + int emptyRecordbuf = 0; + int framesProcessed; + unsigned long timeout; + int i; + int doChannelCopy; + int priming = 0; + PaStreamCallbackFlags underover = 0; + + PA_LOGE_; + + ti.inputBufferAdcTime = 0.0; + ti.currentTime = 0.0; + ti.outputBufferDacTime = 0.0; + + /* Get double buffering going */ + + /* Submit buffers */ + if(stream->playbackPin) + { + result = PinSetState(stream->playbackPin, KSSTATE_RUN); + + PA_DEBUG(("play state run = %d;",(int)result)); + SetEvent(stream->events[outbuf+2]); + outbuf = (outbuf+1)&1; + SetEvent(stream->events[outbuf+2]); + outbuf = (outbuf+1)&1; + pending += 2; + priming += 4; + } + if(stream->recordingPin) + { + result = PinSetState(stream->recordingPin, KSSTATE_RUN); + + PA_DEBUG(("recording state run = %d;",(int)result)); + PinRead(stream->recordingPin->handle,&stream->packets[inbuf]); + inbuf = (inbuf+1)&1; /* Increment and wrap */ + PinRead(stream->recordingPin->handle,&stream->packets[inbuf]); + inbuf = (inbuf+1)&1; /* Increment and wrap */ + /* FIXME - do error checking */ + pending += 2; + } + PA_DEBUG(("Out buffer len:%f\n",(2000*stream->framesPerHostOBuffer) / stream->streamRepresentation.streamInfo.sampleRate)); + PA_DEBUG(("In buffer len:%f\n",(2000*stream->framesPerHostIBuffer) / stream->streamRepresentation.streamInfo.sampleRate)); + timeout = max( + ((2000*(DWORD)stream->framesPerHostOBuffer) / (DWORD)stream->streamRepresentation.streamInfo.sampleRate), + ((2000*(DWORD)stream->framesPerHostIBuffer) / (DWORD)stream->streamRepresentation.streamInfo.sampleRate)); + timeout = max(timeout,1); + PA_DEBUG(("Timeout = %ld\n",timeout)); + + while(!stream->streamAbort) + { + fillPlaybuf = 0; + emptyRecordbuf = 0; + + /* Wait for next input or output buffer to be finished with*/ + assert(pending>0); + + if(stream->streamStop) + { + PA_DEBUG(("ss1:pending=%d ",pending)); + } + wait = WaitForMultipleObjects(5, stream->events, FALSE, 0); + if( wait == WAIT_TIMEOUT ) + { + /* No (under|over)flow has ocurred */ + wait = WaitForMultipleObjects(5, stream->events, FALSE, timeout); + eventSignaled = wait - WAIT_OBJECT_0; + } + else + { + eventSignaled = wait - WAIT_OBJECT_0; + if( eventSignaled < 2 ) + { + underover |= paInputOverflow; + PA_DEBUG(("Input overflow\n")); + } + else if(( eventSignaled < 4 )&&(!priming)) + { + underover |= paOutputUnderflow; + PA_DEBUG(("Output underflow\n")); + } + } + + if(stream->streamStop) + { + PA_DEBUG(("ss2:wait=%ld",wait)); + } + if(wait == WAIT_FAILED) + { + PA_DEBUG(("Wait fail = %ld! ",wait)); + break; + } + if(wait == WAIT_TIMEOUT) + { + continue; + } + + if(eventSignaled < 2) + { /* Recording input buffer has been filled */ + if(stream->playbackPin) + { + /* First check if also the next playback buffer has been signaled */ + wait = WaitForSingleObject(stream->events[outbuf+2],0); + if(wait == WAIT_OBJECT_0) + { + /* Yes, so do both buffers at same time */ + fillPlaybuf = 1; + pending--; + /* Was this an underflow situation? */ + if( underover ) + underover |= paOutputUnderflow; /* Yes! */ + } + } + emptyRecordbuf = 1; + pending--; + } + else if(eventSignaled < 4) + { /* Playback output buffer has been emptied */ + if(stream->recordingPin) + { + /* First check if also the next recording buffer has been signaled */ + wait = WaitForSingleObject(stream->events[inbuf],0); + if(wait == WAIT_OBJECT_0) + { /* Yes, so do both buffers at same time */ + emptyRecordbuf = 1; + pending--; + /* Was this an overflow situation? */ + if( underover ) + underover |= paInputOverflow; /* Yes! */ + } + } + fillPlaybuf = 1; + pending--; + } + else + { + /* Abort event! */ + assert(stream->streamAbort); /* Should have been set */ + PA_DEBUG(("ABORTING ")); + break; + } + ResetEvent(stream->events[eventSignaled]); + + if(stream->streamStop) + { + PA_DEBUG(("Stream stop! pending=%d",pending)); + cbResult = paComplete; /* Stop, but play remaining buffers */ + } + + /* Do necessary buffer processing (which will invoke user callback if necessary */ + doChannelCopy = 0; + if(cbResult==paContinue) + { + PaUtil_BeginCpuLoadMeasurement( &stream->cpuLoadMeasurer ); + if((stream->bufferProcessor.hostInputFrameCount[0] + stream->bufferProcessor.hostInputFrameCount[1]) == + (stream->bufferProcessor.hostOutputFrameCount[0] + stream->bufferProcessor.hostOutputFrameCount[1]) ) + PaUtil_BeginBufferProcessing(&stream->bufferProcessor,&ti,underover); + underover = 0; /* Reset the (under|over)flow status */ + if(fillPlaybuf) + { + PaUtil_SetOutputFrameCount(&stream->bufferProcessor,0); + if( stream->userOutputChannels == 1 ) + { + /* Write the single user channel to the first interleaved block */ + PaUtil_SetOutputChannel(&stream->bufferProcessor,0,stream->packets[outbuf+2].Header.Data,stream->deviceOutputChannels); + /* We will do a copy to the other channels after the data has been written */ + doChannelCopy = 1; + } + else + { + for(i=0;iuserOutputChannels;i++) + { + /* Only write the user output channels. Leave the rest blank */ + PaUtil_SetOutputChannel(&stream->bufferProcessor,i,((unsigned char*)(stream->packets[outbuf+2].Header.Data))+(i*stream->outputSampleSize),stream->deviceOutputChannels); + } + } + } + if(emptyRecordbuf) + { + PaUtil_SetInputFrameCount(&stream->bufferProcessor,stream->packets[inbuf].Header.DataUsed/stream->bytesPerInputFrame); + for(i=0;iuserInputChannels;i++) + { + /* Only read as many channels as the user wants */ + PaUtil_SetInputChannel(&stream->bufferProcessor,i,((unsigned char*)(stream->packets[inbuf].Header.Data))+(i*stream->inputSampleSize),stream->deviceInputChannels); + } + } + /* Only call the EndBufferProcessing function is the total input frames == total output frames */ + if((stream->bufferProcessor.hostInputFrameCount[0] + stream->bufferProcessor.hostInputFrameCount[1]) == + (stream->bufferProcessor.hostOutputFrameCount[0] + stream->bufferProcessor.hostOutputFrameCount[1]) ) + framesProcessed = PaUtil_EndBufferProcessing(&stream->bufferProcessor,&cbResult); + else framesProcessed = 0; + if( doChannelCopy ) + { + /* Copy the first output channel to the other channels */ + switch(stream->outputSampleSize) + { + case 2: + DuplicateFirstChannelInt16(stream->packets[outbuf+2].Header.Data,stream->deviceOutputChannels,stream->framesPerHostOBuffer); + break; + case 3: + DuplicateFirstChannelInt24(stream->packets[outbuf+2].Header.Data,stream->deviceOutputChannels,stream->framesPerHostOBuffer); + break; + case 4: + DuplicateFirstChannelInt32(stream->packets[outbuf+2].Header.Data,stream->deviceOutputChannels,stream->framesPerHostOBuffer); + break; + default: + assert(0); /* Unsupported format! */ + break; + } + } + PaUtil_EndCpuLoadMeasurement( &stream->cpuLoadMeasurer, framesProcessed ); + } + else + { + fillPlaybuf = 0; + emptyRecordbuf = 0; + } + + /* + if(cbResult != paContinue) + { + PA_DEBUG(("cbResult=%d, pending=%d:",cbResult,pending)); + } + */ + /* Submit buffers */ + if((fillPlaybuf)&&(cbResult!=paAbort)) + { + if(!PinWrite(stream->playbackPin->handle,&stream->packets[outbuf+2])) + outbuf = (outbuf+1)&1; /* Increment and wrap */ + pending++; + if( priming ) + priming--; /* Have to prime twice */ + } + if((emptyRecordbuf)&&(cbResult==paContinue)) + { + stream->packets[inbuf].Header.DataUsed = 0; /* Reset for reuse */ + PinRead(stream->recordingPin->handle,&stream->packets[inbuf]); + inbuf = (inbuf+1)&1; /* Increment and wrap */ + pending++; + } + if(pending==0) + { + PA_DEBUG(("pending==0 finished...;")); + break; + } + if((!stream->playbackPin)&&(cbResult!=paContinue)) + { + PA_DEBUG(("record only cbResult=%d...;",cbResult)); + break; + } + } + + PA_DEBUG(("Finished thread")); + + /* Finished, either normally or aborted */ + if(stream->playbackPin) + { + result = PinSetState(stream->playbackPin, KSSTATE_PAUSE); + result = PinSetState(stream->playbackPin, KSSTATE_STOP); + } + if(stream->recordingPin) + { + result = PinSetState(stream->recordingPin, KSSTATE_PAUSE); + result = PinSetState(stream->recordingPin, KSSTATE_STOP); + } + + stream->streamActive = 0; + + if((!stream->streamStop)&&(!stream->streamAbort)) + { + /* Invoke the user stream finished callback */ + /* Only do it from here if not being stopped/aborted by user */ + if( stream->streamRepresentation.streamFinishedCallback != 0 ) + stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData ); + } + stream->streamStop = 0; + stream->streamAbort = 0; + + /* Reset process priority if necessary */ + if(stream->oldProcessPriority != REALTIME_PRIORITY_CLASS) + { + SetPriorityClass(GetCurrentProcess(),stream->oldProcessPriority); + stream->oldProcessPriority = REALTIME_PRIORITY_CLASS; + } + + PA_LOGL_; + ExitThread(0); + return 0; +} + +static PaError StartStream( PaStream *s ) +{ + PaError result = paNoError; + PaWinWdmStream *stream = (PaWinWdmStream*)s; + DWORD dwID; + BOOL ret; + int size; + + PA_LOGE_; + + stream->streamStop = 0; + stream->streamAbort = 0; + size = 5; + while(size--) + { + if(stream->events[size] != NULL) + { + ResetEvent(stream->events[size]); + } + } + + PaUtil_ResetBufferProcessor( &stream->bufferProcessor ); + + stream->oldProcessPriority = GetPriorityClass(GetCurrentProcess()); + /* Uncomment the following line to enable dynamic boosting of the process + * priority to real time for best low latency support + * Disabled by default because RT processes can easily block the OS */ + /*ret = SetPriorityClass(GetCurrentProcess(),REALTIME_PRIORITY_CLASS); + PA_DEBUG(("Class ret = %d;",ret));*/ + + stream->streamStarted = 1; + stream->streamThread = CreateThread(NULL, 0, ProcessingThread, stream, 0, &dwID); + if(stream->streamThread == NULL) + { + stream->streamStarted = 0; + result = paInsufficientMemory; + goto end; + } + ret = SetThreadPriority(stream->streamThread,THREAD_PRIORITY_TIME_CRITICAL); + PA_DEBUG(("Priority ret = %d;",ret)); + /* Make the stream active */ + stream->streamActive = 1; + +end: + PA_LOGL_; + return result; +} + + +static PaError StopStream( PaStream *s ) +{ + PaError result = paNoError; + PaWinWdmStream *stream = (PaWinWdmStream*)s; + int doCb = 0; + + PA_LOGE_; + + if(stream->streamActive) + { + doCb = 1; + stream->streamStop = 1; + while(stream->streamActive) + { + PA_DEBUG(("W.")); + Sleep(10); /* Let thread sleep for 10 msec */ + } + } + + PA_DEBUG(("Terminating thread")); + if(stream->streamStarted && stream->streamThread) + { + TerminateThread(stream->streamThread,0); + stream->streamThread = NULL; + } + + stream->streamStarted = 0; + + if(stream->oldProcessPriority != REALTIME_PRIORITY_CLASS) + { + SetPriorityClass(GetCurrentProcess(),stream->oldProcessPriority); + stream->oldProcessPriority = REALTIME_PRIORITY_CLASS; + } + + if(doCb) + { + /* Do user callback now after all state has been reset */ + /* This means it should be safe for the called function */ + /* to invoke e.g. StartStream */ + if( stream->streamRepresentation.streamFinishedCallback != 0 ) + stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData ); + } + + PA_LOGL_; + return result; +} + +static PaError AbortStream( PaStream *s ) +{ + PaError result = paNoError; + PaWinWdmStream *stream = (PaWinWdmStream*)s; + int doCb = 0; + + PA_LOGE_; + + if(stream->streamActive) + { + doCb = 1; + stream->streamAbort = 1; + SetEvent(stream->events[4]); /* Signal immediately */ + while(stream->streamActive) + { + Sleep(10); + } + } + + if(stream->streamStarted && stream->streamThread) + { + TerminateThread(stream->streamThread,0); + stream->streamThread = NULL; + } + + stream->streamStarted = 0; + + if(stream->oldProcessPriority != REALTIME_PRIORITY_CLASS) + { + SetPriorityClass(GetCurrentProcess(),stream->oldProcessPriority); + stream->oldProcessPriority = REALTIME_PRIORITY_CLASS; + } + + if(doCb) + { + /* Do user callback now after all state has been reset */ + /* This means it should be safe for the called function */ + /* to invoke e.g. StartStream */ + if( stream->streamRepresentation.streamFinishedCallback != 0 ) + stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData ); + } + + stream->streamActive = 0; + stream->streamStarted = 0; + + PA_LOGL_; + return result; +} + + +static PaError IsStreamStopped( PaStream *s ) +{ + PaWinWdmStream *stream = (PaWinWdmStream*)s; + int result = 0; + + PA_LOGE_; + + if(!stream->streamStarted) + result = 1; + + PA_LOGL_; + return result; +} + + +static PaError IsStreamActive( PaStream *s ) +{ + PaWinWdmStream *stream = (PaWinWdmStream*)s; + int result = 0; + + PA_LOGE_; + + if(stream->streamActive) + result = 1; + + PA_LOGL_; + return result; +} + + +static PaTime GetStreamTime( PaStream* s ) +{ + PA_LOGE_; + PA_LOGL_; + (void)s; + return PaUtil_GetTime(); +} + + +static double GetStreamCpuLoad( PaStream* s ) +{ + PaWinWdmStream *stream = (PaWinWdmStream*)s; + double result; + PA_LOGE_; + result = PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer ); + PA_LOGL_; + return result; +} + + +/* + As separate stream interfaces are used for blocking and callback + streams, the following functions can be guaranteed to only be called + for blocking streams. +*/ + +static PaError ReadStream( PaStream* s, + void *buffer, + unsigned long frames ) +{ + PaWinWdmStream *stream = (PaWinWdmStream*)s; + + PA_LOGE_; + + /* suppress unused variable warnings */ + (void) buffer; + (void) frames; + (void) stream; + + /* IMPLEMENT ME, see portaudio.h for required behavior*/ + PA_LOGL_; + return paNoError; +} + + +static PaError WriteStream( PaStream* s, + const void *buffer, + unsigned long frames ) +{ + PaWinWdmStream *stream = (PaWinWdmStream*)s; + + PA_LOGE_; + + /* suppress unused variable warnings */ + (void) buffer; + (void) frames; + (void) stream; + + /* IMPLEMENT ME, see portaudio.h for required behavior*/ + PA_LOGL_; + return paNoError; +} + + +static signed long GetStreamReadAvailable( PaStream* s ) +{ + PaWinWdmStream *stream = (PaWinWdmStream*)s; + + PA_LOGE_; + + /* suppress unused variable warnings */ + (void) stream; + + /* IMPLEMENT ME, see portaudio.h for required behavior*/ + PA_LOGL_; + return 0; +} + + +static signed long GetStreamWriteAvailable( PaStream* s ) +{ + PaWinWdmStream *stream = (PaWinWdmStream*)s; + + PA_LOGE_; + /* suppress unused variable warnings */ + (void) stream; + + /* IMPLEMENT ME, see portaudio.h for required behavior*/ + PA_LOGL_; + return 0; +} \ No newline at end of file Index: julius4/libsent/src/adin/pa/hostapi/wdmks/readme.txt diff -u /dev/null julius4/libsent/src/adin/pa/hostapi/wdmks/readme.txt:1.1 --- /dev/null Sat Feb 5 18:00:03 2011 +++ julius4/libsent/src/adin/pa/hostapi/wdmks/readme.txt Sat Feb 5 18:00:03 2011 @@ -0,0 +1,82 @@ +Notes about WDM-KS host API +--------------------------- + +Status history +-------------- +10th November 2005: +Made following changes: + * OpenStream: Try all PaSampleFormats internally if the the chosen + format is not supported natively. This fixed several problems + with soundcards that soundcards that did not take kindly to + using 24-bit 3-byte formats. + * OpenStream: Make the minimum framesPerHostIBuffer (and framesPerHostOBuffer) + the default frameSize for the playback/recording pin. + * ProcessingThread: Added a switch to only call PaUtil_EndBufferProcessing + if the total input frames equals the total output frames + +5th September 2004: +This is the first public version of the code. It should be considered +an alpha release with zero guarantee not to crash on any particular +system. So far it has only been tested in the author's development +environment, which means a Win2k/SP2 PIII laptop with integrated +SoundMAX driver and USB Tascam US-428 compiled with both MinGW +(GCC 3.3) and MSVC++6 using the MS DirectX 9 SDK. +It has been most widely tested with the MinGW build, with most of the +test programs (particularly paqa_devs and paqa_errs) passing. +There are some notable failures: patest_out_underflow and both of the +blocking I/O tests (as blocking I/O is not implemented). +At this point the code needs to be tested with a much wider variety +of configurations and feedback provided from testers regarding +both working and failing cases. + +What is the WDM-KS host API? +---------------------------- +PortAudio for Windows currently has 3 functional host implementations. +MME uses the oldest Windows audio API which does not offer good +play/record latency. +DirectX improves this, but still imposes a penalty +of 10s of milliseconds due to the system mixing of streams from +multiple applications. +ASIO offers very good latency, but requires special drivers which are +not always available for cheaper audio hardware. Also, when ASIO +drivers are available, they are not always so robust because they +bypass all of the standardised Windows device driver architecture +and hit the hardware their own way. +Alternatively there are a couple of free (but closed source) ASIO +implementations which connect to the lower level Windows +"Kernel Streaming" API, but again these require special installation +by the user, and can be limited in functionality or difficult to use. + +This is where the PortAudio "WDM-KS" host implementation comes in. +It directly connects PortAudio to the same Kernel Streaming API which +those ASIO bridges use. This avoids the mixing penatly of DirectX, +giving at least as good latency as any ASIO driver, but it has the +advantage of working with ANY Windows audio hardware which is available +through the normal MME/DirectX routes without the user requiring +any additional device drivers to be installed, and allowing all +device selection to be done through the normal PortAudio API. + +Note that in general you should only be using this host API if your +application has a real requirement for very low latency audio (<20ms), +either because you are generating sounds in real-time based upon +user input, or you a processing recorded audio in real time. + +The only thing to be aware of is that using the KS interface will +block that device from being used by the rest of system through +the higher level APIs, or conversely, if the system is using +a device, the KS API will not be able to use it. MS recommend that +you should keep the device open only when your application has focus. +In PortAudio terms, this means having a stream Open on a WDMKS device. + +Usage +----- +To add the WDMKS backend to your program which is already using +PortAudio, you must undefine PA_NO_WDMKS from your build file, +and include the pa_win_wdmks\pa_win_wdmks.c into your build. +The file should compile in both C and C++. +You will need a DirectX SDK installed on your system for the +ks.h and ksmedia.h header files. +You will need to link to the system "setupapi" library. +Note that if you use MinGW, you will get more warnings from +the DX header files when using GCC(C), and still a few warnings +with G++(CPP). \ No newline at end of file From sumomo @ users.sourceforge.jp Sat Feb 5 18:00:03 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Sat, 05 Feb 2011 18:00:03 +0900 Subject: [Julius-cvs 591] CVS update: julius4/libsent/src/adin/pa/hostapi/dsound Message-ID: <1296896403.045567.28555.nullmailer@users.sourceforge.jp> Index: julius4/libsent/src/adin/pa/hostapi/dsound/pa_win_ds.c diff -u /dev/null julius4/libsent/src/adin/pa/hostapi/dsound/pa_win_ds.c:1.1 --- /dev/null Sat Feb 5 18:00:03 2011 +++ julius4/libsent/src/adin/pa/hostapi/dsound/pa_win_ds.c Sat Feb 5 18:00:02 2011 @@ -0,0 +1,2510 @@ +/* + * $Id: pa_win_ds.c,v 1.1 2011/02/05 09:00:02 sumomo Exp $ + * Portable Audio I/O Library DirectSound implementation + * + * Authors: Phil Burk, Robert Marsanyi & Ross Bencina + * Based on the Open Source API proposed by Ross Bencina + * Copyright (c) 1999-2007 Ross Bencina, Phil Burk, Robert Marsanyi + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/* + * The text above constitutes the entire PortAudio license; however, + * the PortAudio community also makes the following non-binding requests: + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. It is also + * requested that these non-binding requests be included along with the + * license above. + */ + +/** @file + @ingroup hostaip_src + + @todo implement paInputOverflow callback status flag + + @todo implement paNeverDropInput. + + @todo implement host api specific extension to set i/o buffer sizes in frames + + @todo implement initialisation of PaDeviceInfo default*Latency fields (currently set to 0.) + + @todo implement ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable + + @todo audit handling of DirectSound result codes - in many cases we could convert a HRESULT into + a native portaudio error code. Standard DirectSound result codes are documented at msdn. + + @todo implement IsFormatSupported + + @todo call PaUtil_SetLastHostErrorInfo with a specific error string (currently just "DSound error"). + + @todo make sure all buffers have been played before stopping the stream + when the stream callback returns paComplete + + @todo retrieve default devices using the DRVM_MAPPER_PREFERRED_GET functions used in the wmme api + these wave device ids can be aligned with the directsound devices either by retrieving + the system interface device name using DRV_QUERYDEVICEINTERFACE or by using the wave device + id retrieved in KsPropertySetEnumerateCallback. + + old TODOs from phil, need to work out if these have been done: + O- fix "patest_stop.c" +*/ + + +#include +#include /* strlen() */ +#include +#include + +/* + We are only using DX3 in here, no need to polute the namespace - davidv +*/ +#define DIRECTSOUND_VERSION 0x0300 +#include +#ifdef PAWIN_USE_WDMKS_DEVICE_INFO +#include +#endif /* PAWIN_USE_WDMKS_DEVICE_INFO */ + +#include "pa_util.h" +#include "pa_allocation.h" +#include "pa_hostapi.h" +#include "pa_stream.h" +#include "pa_cpuload.h" +#include "pa_process.h" +#include "pa_debugprint.h" + +#include "pa_win_ds.h" +#include "pa_win_ds_dynlink.h" +#include "pa_win_waveformat.h" +#include "pa_win_wdmks_utils.h" + + +#if (defined(WIN32) && (defined(_MSC_VER) && (_MSC_VER >= 1200))) /* MSC version 6 and above */ +#pragma comment( lib, "dsound.lib" ) +#pragma comment( lib, "winmm.lib" ) +#endif + +/* + provided in newer platform sdks and x64 + */ +#ifndef DWORD_PTR +#define DWORD_PTR DWORD +#endif + +#define PRINT(x) PA_DEBUG(x); +#define ERR_RPT(x) PRINT(x) +#define DBUG(x) PRINT(x) +#define DBUGX(x) PRINT(x) + +#define PA_USE_HIGH_LATENCY (0) +#if PA_USE_HIGH_LATENCY +#define PA_WIN_9X_LATENCY (500) +#define PA_WIN_NT_LATENCY (600) +#else +#define PA_WIN_9X_LATENCY (140) +#define PA_WIN_NT_LATENCY (280) +#endif + +#define PA_WIN_WDM_LATENCY (120) + +#define SECONDS_PER_MSEC (0.001) +#define MSEC_PER_SECOND (1000) + +/* prototypes for functions declared in this file */ + +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +PaError PaWinDs_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index ); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +static void Terminate( struct PaUtilHostApiRepresentation *hostApi ); +static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi, + PaStream** s, + const PaStreamParameters *inputParameters, + const PaStreamParameters *outputParameters, + double sampleRate, + unsigned long framesPerBuffer, + PaStreamFlags streamFlags, + PaStreamCallback *streamCallback, + void *userData ); +static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi, + const PaStreamParameters *inputParameters, + const PaStreamParameters *outputParameters, + double sampleRate ); +static PaError CloseStream( PaStream* stream ); +static PaError StartStream( PaStream *stream ); +static PaError StopStream( PaStream *stream ); +static PaError AbortStream( PaStream *stream ); +static PaError IsStreamStopped( PaStream *s ); +static PaError IsStreamActive( PaStream *stream ); +static PaTime GetStreamTime( PaStream *stream ); +static double GetStreamCpuLoad( PaStream* stream ); +static PaError ReadStream( PaStream* stream, void *buffer, unsigned long frames ); +static PaError WriteStream( PaStream* stream, const void *buffer, unsigned long frames ); +static signed long GetStreamReadAvailable( PaStream* stream ); +static signed long GetStreamWriteAvailable( PaStream* stream ); + + +/* FIXME: should convert hr to a string */ +#define PA_DS_SET_LAST_DIRECTSOUND_ERROR( hr ) \ + PaUtil_SetLastHostErrorInfo( paDirectSound, hr, "DirectSound error" ) + +/************************************************* DX Prototypes **********/ +static BOOL CALLBACK CollectGUIDsProc(LPGUID lpGUID, + LPCTSTR lpszDesc, + LPCTSTR lpszDrvName, + LPVOID lpContext ); + +/************************************************************************************/ +/********************** Structures **************************************************/ +/************************************************************************************/ +/* PaWinDsHostApiRepresentation - host api datastructure specific to this implementation */ + +typedef struct PaWinDsDeviceInfo +{ + PaDeviceInfo inheritedDeviceInfo; + GUID guid; + GUID *lpGUID; + double sampleRates[3]; + char deviceInputChannelCountIsKnown; /**<< if the system returns 0xFFFF then we don't really know the number of supported channels (1=>known, 0=>unknown)*/ + char deviceOutputChannelCountIsKnown; /**<< if the system returns 0xFFFF then we don't really know the number of supported channels (1=>known, 0=>unknown)*/ +} PaWinDsDeviceInfo; + +typedef struct +{ + PaUtilHostApiRepresentation inheritedHostApiRep; + PaUtilStreamInterface callbackStreamInterface; + PaUtilStreamInterface blockingStreamInterface; + + PaUtilAllocationGroup *allocations; + + /* implementation specific data goes here */ + + char comWasInitialized; + +} PaWinDsHostApiRepresentation; + + +/* PaWinDsStream - a stream data structure specifically for this implementation */ + +typedef struct PaWinDsStream +{ + PaUtilStreamRepresentation streamRepresentation; + PaUtilCpuLoadMeasurer cpuLoadMeasurer; + PaUtilBufferProcessor bufferProcessor; + +/* DirectSound specific data. */ + +/* Output */ + LPDIRECTSOUND pDirectSound; + LPDIRECTSOUNDBUFFER pDirectSoundOutputBuffer; + DWORD outputBufferWriteOffsetBytes; /* last write position */ + INT outputBufferSizeBytes; + INT bytesPerOutputFrame; + /* Try to detect play buffer underflows. */ + LARGE_INTEGER perfCounterTicksPerBuffer; /* counter ticks it should take to play a full buffer */ + LARGE_INTEGER previousPlayTime; + UINT previousPlayCursor; + UINT outputUnderflowCount; + BOOL outputIsRunning; + /* use double which lets us can play for several thousand years with enough precision */ + double dsw_framesWritten; + double framesPlayed; +/* Input */ + LPDIRECTSOUNDCAPTURE pDirectSoundCapture; + LPDIRECTSOUNDCAPTUREBUFFER pDirectSoundInputBuffer; + INT bytesPerInputFrame; + UINT readOffset; /* last read position */ + UINT inputSize; + + + MMRESULT timerID; + int framesPerDSBuffer; + double framesWritten; + double secondsPerHostByte; /* Used to optimize latency calculation for outTime */ + + PaStreamCallbackFlags callbackFlags; + +/* FIXME - move all below to PaUtilStreamRepresentation */ + volatile int isStarted; + volatile int isActive; + volatile int stopProcessing; /* stop thread once existing buffers have been returned */ + volatile int abortProcessing; /* stop thread immediately */ +} PaWinDsStream; + + +/************************************************************************************ +** Duplicate the input string using the allocations allocator. +** A NULL string is converted to a zero length string. +** If memory cannot be allocated, NULL is returned. +**/ +static char *DuplicateDeviceNameString( PaUtilAllocationGroup *allocations, const char* src ) +{ + char *result = 0; + + if( src != NULL ) + { + size_t len = strlen(src); + result = (char*)PaUtil_GroupAllocateMemory( allocations, (long)(len + 1) ); + if( result ) + memcpy( (void *) result, src, len+1 ); + } + else + { + result = (char*)PaUtil_GroupAllocateMemory( allocations, 1 ); + if( result ) + result[0] = '\0'; + } + + return result; +} + +/************************************************************************************ +** DSDeviceNameAndGUID, DSDeviceNameAndGUIDVector used for collecting preliminary +** information during device enumeration. +*/ +typedef struct DSDeviceNameAndGUID{ + char *name; // allocated from parent's allocations, never deleted by this structure + GUID guid; + LPGUID lpGUID; + void *pnpInterface; // wchar_t* interface path, allocated using the DS host api's allocation group +} DSDeviceNameAndGUID; + +typedef struct DSDeviceNameAndGUIDVector{ + PaUtilAllocationGroup *allocations; + PaError enumerationError; + + int count; + int free; + DSDeviceNameAndGUID *items; // Allocated using LocalAlloc() +} DSDeviceNameAndGUIDVector; + +typedef struct DSDeviceNamesAndGUIDs{ + PaWinDsHostApiRepresentation *winDsHostApi; + DSDeviceNameAndGUIDVector inputNamesAndGUIDs; + DSDeviceNameAndGUIDVector outputNamesAndGUIDs; +} DSDeviceNamesAndGUIDs; + +static PaError InitializeDSDeviceNameAndGUIDVector( + DSDeviceNameAndGUIDVector *guidVector, PaUtilAllocationGroup *allocations ) +{ + PaError result = paNoError; + + guidVector->allocations = allocations; + guidVector->enumerationError = paNoError; + + guidVector->count = 0; + guidVector->free = 8; + guidVector->items = (DSDeviceNameAndGUID*)LocalAlloc( LMEM_FIXED, sizeof(DSDeviceNameAndGUID) * guidVector->free ); + if( guidVector->items == NULL ) + result = paInsufficientMemory; + + return result; +} + +static PaError ExpandDSDeviceNameAndGUIDVector( DSDeviceNameAndGUIDVector *guidVector ) +{ + PaError result = paNoError; + DSDeviceNameAndGUID *newItems; + int i; + + /* double size of vector */ + int size = guidVector->count + guidVector->free; + guidVector->free += size; + + newItems = (DSDeviceNameAndGUID*)LocalAlloc( LMEM_FIXED, sizeof(DSDeviceNameAndGUID) * size * 2 ); + if( newItems == NULL ) + { + result = paInsufficientMemory; + } + else + { + for( i=0; i < guidVector->count; ++i ) + { + newItems[i].name = guidVector->items[i].name; + if( guidVector->items[i].lpGUID == NULL ) + { + newItems[i].lpGUID = NULL; + } + else + { + newItems[i].lpGUID = &newItems[i].guid; + memcpy( &newItems[i].guid, guidVector->items[i].lpGUID, sizeof(GUID) );; + } + newItems[i].pnpInterface = guidVector->items[i].pnpInterface; + } + + LocalFree( guidVector->items ); + guidVector->items = newItems; + } + + return result; +} + +/* + it's safe to call DSDeviceNameAndGUIDVector multiple times +*/ +static PaError TerminateDSDeviceNameAndGUIDVector( DSDeviceNameAndGUIDVector *guidVector ) +{ + PaError result = paNoError; + + if( guidVector->items != NULL ) + { + if( LocalFree( guidVector->items ) != NULL ) + result = paInsufficientMemory; /** @todo this isn't the correct error to return from a deallocation failure */ + + guidVector->items = NULL; + } + + return result; +} + +/************************************************************************************ +** Collect preliminary device information during DirectSound enumeration +*/ +static BOOL CALLBACK CollectGUIDsProc(LPGUID lpGUID, + LPCTSTR lpszDesc, + LPCTSTR lpszDrvName, + LPVOID lpContext ) +{ + DSDeviceNameAndGUIDVector *namesAndGUIDs = (DSDeviceNameAndGUIDVector*)lpContext; + PaError error; + + (void) lpszDrvName; /* unused variable */ + + if( namesAndGUIDs->free == 0 ) + { + error = ExpandDSDeviceNameAndGUIDVector( namesAndGUIDs ); + if( error != paNoError ) + { + namesAndGUIDs->enumerationError = error; + return FALSE; + } + } + + /* Set GUID pointer, copy GUID to storage in DSDeviceNameAndGUIDVector. */ + if( lpGUID == NULL ) + { + namesAndGUIDs->items[namesAndGUIDs->count].lpGUID = NULL; + } + else + { + namesAndGUIDs->items[namesAndGUIDs->count].lpGUID = + &namesAndGUIDs->items[namesAndGUIDs->count].guid; + + memcpy( &namesAndGUIDs->items[namesAndGUIDs->count].guid, lpGUID, sizeof(GUID) ); + } + + namesAndGUIDs->items[namesAndGUIDs->count].name = + DuplicateDeviceNameString( namesAndGUIDs->allocations, lpszDesc ); + if( namesAndGUIDs->items[namesAndGUIDs->count].name == NULL ) + { + namesAndGUIDs->enumerationError = paInsufficientMemory; + return FALSE; + } + + namesAndGUIDs->items[namesAndGUIDs->count].pnpInterface = 0; + + ++namesAndGUIDs->count; + --namesAndGUIDs->free; + + return TRUE; +} + +#ifdef PAWIN_USE_WDMKS_DEVICE_INFO + +static void *DuplicateWCharString( PaUtilAllocationGroup *allocations, wchar_t *source ) +{ + size_t len; + wchar_t *result; + + len = wcslen( source ); + result = (wchar_t*)PaUtil_GroupAllocateMemory( allocations, (long) ((len+1) * sizeof(wchar_t)) ); + wcscpy( result, source ); + return result; +} + +static BOOL CALLBACK KsPropertySetEnumerateCallback( PDSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION_W_DATA data, LPVOID context ) +{ + int i; + DSDeviceNamesAndGUIDs *deviceNamesAndGUIDs = (DSDeviceNamesAndGUIDs*)context; + + if( data->DataFlow == DIRECTSOUNDDEVICE_DATAFLOW_RENDER ) + { + for( i=0; i < deviceNamesAndGUIDs->outputNamesAndGUIDs.count; ++i ) + { + if( deviceNamesAndGUIDs->outputNamesAndGUIDs.items[i].lpGUID + && memcmp( &data->DeviceId, deviceNamesAndGUIDs->outputNamesAndGUIDs.items[i].lpGUID, sizeof(GUID) ) == 0 ) + { + deviceNamesAndGUIDs->outputNamesAndGUIDs.items[i].pnpInterface = + (char*)DuplicateWCharString( deviceNamesAndGUIDs->winDsHostApi->allocations, data->Interface ); + break; + } + } + } + else if( data->DataFlow == DIRECTSOUNDDEVICE_DATAFLOW_CAPTURE ) + { + for( i=0; i < deviceNamesAndGUIDs->inputNamesAndGUIDs.count; ++i ) + { + if( deviceNamesAndGUIDs->inputNamesAndGUIDs.items[i].lpGUID + && memcmp( &data->DeviceId, deviceNamesAndGUIDs->inputNamesAndGUIDs.items[i].lpGUID, sizeof(GUID) ) == 0 ) + { + deviceNamesAndGUIDs->inputNamesAndGUIDs.items[i].pnpInterface = + (char*)DuplicateWCharString( deviceNamesAndGUIDs->winDsHostApi->allocations, data->Interface ); + break; + } + } + } + + return TRUE; +} + + +static GUID pawin_CLSID_DirectSoundPrivate = +{ 0x11ab3ec0, 0x25ec, 0x11d1, 0xa4, 0xd8, 0x00, 0xc0, 0x4f, 0xc2, 0x8a, 0xca }; + +static GUID pawin_DSPROPSETID_DirectSoundDevice = +{ 0x84624f82, 0x25ec, 0x11d1, 0xa4, 0xd8, 0x00, 0xc0, 0x4f, 0xc2, 0x8a, 0xca }; + +static GUID pawin_IID_IKsPropertySet = +{ 0x31efac30, 0x515c, 0x11d0, 0xa9, 0xaa, 0x00, 0xaa, 0x00, 0x61, 0xbe, 0x93 }; + + +/* + FindDevicePnpInterfaces fills in the pnpInterface fields in deviceNamesAndGUIDs + with UNICODE file paths to the devices. The DS documentation mentions + at least two techniques by which these Interface paths can be found using IKsPropertySet on + the DirectSound class object. One is using the DSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION + property, and the other is using DSPROPERTY_DIRECTSOUNDDEVICE_ENUMERATE. + I tried both methods and only the second worked. I found two postings on the + net from people who had the same problem with the first method, so I think the method used here is + more common/likely to work. The probem is that IKsPropertySet_Get returns S_OK + but the fields of the device description are not filled in. + + The mechanism we use works by registering an enumeration callback which is called for + every DSound device. Our callback searches for a device in our deviceNamesAndGUIDs list + with the matching GUID and copies the pointer to the Interface path. + Note that we could have used this enumeration callback to perform the original + device enumeration, however we choose not to so we can disable this step easily. + + Apparently the IKsPropertySet mechanism was added in DirectSound 9c 2004 + http://www.tech-archive.net/Archive/Development/microsoft.public.win32.programmer.mmedia/2004-12/0099.html + + -- rossb +*/ +static void FindDevicePnpInterfaces( DSDeviceNamesAndGUIDs *deviceNamesAndGUIDs ) +{ + IClassFactory *pClassFactory; + + if( paWinDsDSoundEntryPoints.DllGetClassObject(&pawin_CLSID_DirectSoundPrivate, &IID_IClassFactory, (PVOID *) &pClassFactory) == S_OK ){ + IKsPropertySet *pPropertySet; + if( pClassFactory->lpVtbl->CreateInstance( pClassFactory, NULL, &pawin_IID_IKsPropertySet, (PVOID *) &pPropertySet) == S_OK ){ + + DSPROPERTY_DIRECTSOUNDDEVICE_ENUMERATE_W_DATA data; + ULONG bytesReturned; + + data.Callback = KsPropertySetEnumerateCallback; + data.Context = deviceNamesAndGUIDs; + + IKsPropertySet_Get( pPropertySet, + &pawin_DSPROPSETID_DirectSoundDevice, + DSPROPERTY_DIRECTSOUNDDEVICE_ENUMERATE_W, + NULL, + 0, + &data, + sizeof(data), + &bytesReturned + ); + + IKsPropertySet_Release( pPropertySet ); + } + pClassFactory->lpVtbl->Release( pClassFactory ); + } + + /* + The following code fragment, which I chose not to use, queries for the + device interface for a device with a specific GUID: + + ULONG BytesReturned; + DSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION_W_DATA Property; + + memset (&Property, 0, sizeof(Property)); + Property.DataFlow = DIRECTSOUNDDEVICE_DATAFLOW_RENDER; + Property.DeviceId = *lpGUID; + + hr = IKsPropertySet_Get( pPropertySet, + &pawin_DSPROPSETID_DirectSoundDevice, + DSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION_W, + NULL, + 0, + &Property, + sizeof(Property), + &BytesReturned + ); + + if( hr == S_OK ) + { + //pnpInterface = Property.Interface; + } + */ +} +#endif /* PAWIN_USE_WDMKS_DEVICE_INFO */ + + +/* + GUIDs for emulated devices which we blacklist below. + are there more than two of them?? +*/ + +GUID IID_IRolandVSCEmulated1 = {0xc2ad1800, 0xb243, 0x11ce, 0xa8, 0xa4, 0x00, 0xaa, 0x00, 0x6c, 0x45, 0x01}; +GUID IID_IRolandVSCEmulated2 = {0xc2ad1800, 0xb243, 0x11ce, 0xa8, 0xa4, 0x00, 0xaa, 0x00, 0x6c, 0x45, 0x02}; + + +#define PA_DEFAULTSAMPLERATESEARCHORDER_COUNT_ (13) /* must match array length below */ +static double defaultSampleRateSearchOrder_[] = + { 44100.0, 48000.0, 32000.0, 24000.0, 22050.0, 88200.0, 96000.0, 192000.0, + 16000.0, 12000.0, 11025.0, 9600.0, 8000.0 }; + +/************************************************************************************ +** Extract capabilities from an output device, and add it to the device info list +** if successful. This function assumes that there is enough room in the +** device info list to accomodate all entries. +** +** The device will not be added to the device list if any errors are encountered. +*/ +static PaError AddOutputDeviceInfoFromDirectSound( + PaWinDsHostApiRepresentation *winDsHostApi, char *name, LPGUID lpGUID, char *pnpInterface ) +{ + PaUtilHostApiRepresentation *hostApi = &winDsHostApi->inheritedHostApiRep; + PaWinDsDeviceInfo *winDsDeviceInfo = (PaWinDsDeviceInfo*) hostApi->deviceInfos[hostApi->info.deviceCount]; + PaDeviceInfo *deviceInfo = &winDsDeviceInfo->inheritedDeviceInfo; + HRESULT hr; + LPDIRECTSOUND lpDirectSound; + DSCAPS caps; + int deviceOK = TRUE; + PaError result = paNoError; + int i; + + /* Copy GUID to the device info structure. Set pointer. */ + if( lpGUID == NULL ) + { + winDsDeviceInfo->lpGUID = NULL; + } + else + { + memcpy( &winDsDeviceInfo->guid, lpGUID, sizeof(GUID) ); + winDsDeviceInfo->lpGUID = &winDsDeviceInfo->guid; + } + + if( lpGUID ) + { + if (IsEqualGUID (&IID_IRolandVSCEmulated1,lpGUID) || + IsEqualGUID (&IID_IRolandVSCEmulated2,lpGUID) ) + { + PA_DEBUG(("BLACKLISTED: %s \n",name)); + return paNoError; + } + } + + /* Create a DirectSound object for the specified GUID + Note that using CoCreateInstance doesn't work on windows CE. + */ + hr = paWinDsDSoundEntryPoints.DirectSoundCreate( lpGUID, &lpDirectSound, NULL ); + + /** try using CoCreateInstance because DirectSoundCreate was hanging under + some circumstances - note this was probably related to the + #define BOOL short bug which has now been fixed + @todo delete this comment and the following code once we've ensured + there is no bug. + */ + /* + hr = CoCreateInstance( &CLSID_DirectSound, NULL, CLSCTX_INPROC_SERVER, + &IID_IDirectSound, (void**)&lpDirectSound ); + + if( hr == S_OK ) + { + hr = IDirectSound_Initialize( lpDirectSound, lpGUID ); + } + */ + + if( hr != DS_OK ) + { + if (hr == DSERR_ALLOCATED) + PA_DEBUG(("AddOutputDeviceInfoFromDirectSound %s DSERR_ALLOCATED\n",name)); + DBUG(("Cannot create DirectSound for %s. Result = 0x%x\n", name, hr )); + if (lpGUID) + DBUG(("%s's GUID: {0x%x,0x%x,0x%x,0x%x,0x%x,0x%x,0x%x,0x%x,0x%x,0x%x, 0x%x} \n", + name, + lpGUID->Data1, + lpGUID->Data2, + lpGUID->Data3, + lpGUID->Data4[0], + lpGUID->Data4[1], + lpGUID->Data4[2], + lpGUID->Data4[3], + lpGUID->Data4[4], + lpGUID->Data4[5], + lpGUID->Data4[6], + lpGUID->Data4[7])); + + deviceOK = FALSE; + } + else + { + /* Query device characteristics. */ + memset( &caps, 0, sizeof(caps) ); + caps.dwSize = sizeof(caps); + hr = IDirectSound_GetCaps( lpDirectSound, &caps ); + if( hr != DS_OK ) + { + DBUG(("Cannot GetCaps() for DirectSound device %s. Result = 0x%x\n", name, hr )); + deviceOK = FALSE; + } + else + { + +#ifndef PA_NO_WMME + if( caps.dwFlags & DSCAPS_EMULDRIVER ) + { + /* If WMME supported, then reject Emulated drivers because they are lousy. */ + deviceOK = FALSE; + } +#endif + + if( deviceOK ) + { + deviceInfo->maxInputChannels = 0; + winDsDeviceInfo->deviceInputChannelCountIsKnown = 1; + + /* DS output capabilities only indicate supported number of channels + using two flags which indicate mono and/or stereo. + We assume that stereo devices may support more than 2 channels + (as is the case with 5.1 devices for example) and so + set deviceOutputChannelCountIsKnown to 0 (unknown). + In this case OpenStream will try to open the device + when the user requests more than 2 channels, rather than + returning an error. + */ + if( caps.dwFlags & DSCAPS_PRIMARYSTEREO ) + { + deviceInfo->maxOutputChannels = 2; + winDsDeviceInfo->deviceOutputChannelCountIsKnown = 0; + } + else + { + deviceInfo->maxOutputChannels = 1; + winDsDeviceInfo->deviceOutputChannelCountIsKnown = 1; + } + +#ifdef PAWIN_USE_WDMKS_DEVICE_INFO + if( pnpInterface ) + { + int count = PaWin_WDMKS_QueryFilterMaximumChannelCount( pnpInterface, /* isInput= */ 0 ); + if( count > 0 ) + { + deviceInfo->maxOutputChannels = count; + winDsDeviceInfo->deviceOutputChannelCountIsKnown = 1; + } + } +#endif /* PAWIN_USE_WDMKS_DEVICE_INFO */ + + deviceInfo->defaultLowInputLatency = 0.; /** @todo IMPLEMENT ME */ + deviceInfo->defaultLowOutputLatency = 0.; /** @todo IMPLEMENT ME */ + deviceInfo->defaultHighInputLatency = 0.; /** @todo IMPLEMENT ME */ + deviceInfo->defaultHighOutputLatency = 0.; /** @todo IMPLEMENT ME */ + + /* initialize defaultSampleRate */ + + if( caps.dwFlags & DSCAPS_CONTINUOUSRATE ) + { + /* initialize to caps.dwMaxSecondarySampleRate incase none of the standard rates match */ + deviceInfo->defaultSampleRate = caps.dwMaxSecondarySampleRate; + + for( i = 0; i < PA_DEFAULTSAMPLERATESEARCHORDER_COUNT_; ++i ) + { + if( defaultSampleRateSearchOrder_[i] >= caps.dwMinSecondarySampleRate + && defaultSampleRateSearchOrder_[i] <= caps.dwMaxSecondarySampleRate ) + { + deviceInfo->defaultSampleRate = defaultSampleRateSearchOrder_[i]; + break; + } + } + } + else if( caps.dwMinSecondarySampleRate == caps.dwMaxSecondarySampleRate ) + { + if( caps.dwMinSecondarySampleRate == 0 ) + { + /* + ** On my Thinkpad 380Z, DirectSoundV6 returns min-max=0 !! + ** But it supports continuous sampling. + ** So fake range of rates, and hope it really supports it. + */ + deviceInfo->defaultSampleRate = 44100.0f; + + DBUG(("PA - Reported rates both zero. Setting to fake values for device #%s\n", name )); + } + else + { + deviceInfo->defaultSampleRate = caps.dwMaxSecondarySampleRate; + } + } + else if( (caps.dwMinSecondarySampleRate < 1000.0) && (caps.dwMaxSecondarySampleRate > 50000.0) ) + { + /* The EWS88MT drivers lie, lie, lie. The say they only support two rates, 100 & 100000. + ** But we know that they really support a range of rates! + ** So when we see a ridiculous set of rates, assume it is a range. + */ + deviceInfo->defaultSampleRate = 44100.0f; + DBUG(("PA - Sample rate range used instead of two odd values for device #%s\n", name )); + } + else deviceInfo->defaultSampleRate = caps.dwMaxSecondarySampleRate; + + + //printf( "min %d max %d\n", caps.dwMinSecondarySampleRate, caps.dwMaxSecondarySampleRate ); + // dwFlags | DSCAPS_CONTINUOUSRATE + } + } + + IDirectSound_Release( lpDirectSound ); + } + + if( deviceOK ) + { + deviceInfo->name = name; + + if( lpGUID == NULL ) + hostApi->info.defaultOutputDevice = hostApi->info.deviceCount; + + hostApi->info.deviceCount++; + } + + return result; +} + + +/************************************************************************************ +** Extract capabilities from an input device, and add it to the device info list +** if successful. This function assumes that there is enough room in the +** device info list to accomodate all entries. +** +** The device will not be added to the device list if any errors are encountered. +*/ +static PaError AddInputDeviceInfoFromDirectSoundCapture( + PaWinDsHostApiRepresentation *winDsHostApi, char *name, LPGUID lpGUID, char *pnpInterface ) +{ + PaUtilHostApiRepresentation *hostApi = &winDsHostApi->inheritedHostApiRep; + PaWinDsDeviceInfo *winDsDeviceInfo = (PaWinDsDeviceInfo*) hostApi->deviceInfos[hostApi->info.deviceCount]; + PaDeviceInfo *deviceInfo = &winDsDeviceInfo->inheritedDeviceInfo; + HRESULT hr; + LPDIRECTSOUNDCAPTURE lpDirectSoundCapture; + DSCCAPS caps; + int deviceOK = TRUE; + PaError result = paNoError; + + /* Copy GUID to the device info structure. Set pointer. */ + if( lpGUID == NULL ) + { + winDsDeviceInfo->lpGUID = NULL; + } + else + { + winDsDeviceInfo->lpGUID = &winDsDeviceInfo->guid; + memcpy( &winDsDeviceInfo->guid, lpGUID, sizeof(GUID) ); + } + + hr = paWinDsDSoundEntryPoints.DirectSoundCaptureCreate( lpGUID, &lpDirectSoundCapture, NULL ); + + /** try using CoCreateInstance because DirectSoundCreate was hanging under + some circumstances - note this was probably related to the + #define BOOL short bug which has now been fixed + @todo delete this comment and the following code once we've ensured + there is no bug. + */ + /* + hr = CoCreateInstance( &CLSID_DirectSoundCapture, NULL, CLSCTX_INPROC_SERVER, + &IID_IDirectSoundCapture, (void**)&lpDirectSoundCapture ); + */ + if( hr != DS_OK ) + { + DBUG(("Cannot create Capture for %s. Result = 0x%x\n", name, hr )); + deviceOK = FALSE; + } + else + { + /* Query device characteristics. */ + memset( &caps, 0, sizeof(caps) ); + caps.dwSize = sizeof(caps); + hr = IDirectSoundCapture_GetCaps( lpDirectSoundCapture, &caps ); + if( hr != DS_OK ) + { + DBUG(("Cannot GetCaps() for Capture device %s. Result = 0x%x\n", name, hr )); + deviceOK = FALSE; + } + else + { +#ifndef PA_NO_WMME + if( caps.dwFlags & DSCAPS_EMULDRIVER ) + { + /* If WMME supported, then reject Emulated drivers because they are lousy. */ + deviceOK = FALSE; + } +#endif + + if( deviceOK ) + { + deviceInfo->maxInputChannels = caps.dwChannels; + winDsDeviceInfo->deviceInputChannelCountIsKnown = 1; + + deviceInfo->maxOutputChannels = 0; + winDsDeviceInfo->deviceOutputChannelCountIsKnown = 1; + +#ifdef PAWIN_USE_WDMKS_DEVICE_INFO + if( pnpInterface ) + { + int count = PaWin_WDMKS_QueryFilterMaximumChannelCount( pnpInterface, /* isInput= */ 1 ); + if( count > 0 ) + { + deviceInfo->maxInputChannels = count; + winDsDeviceInfo->deviceInputChannelCountIsKnown = 1; + } + } +#endif /* PAWIN_USE_WDMKS_DEVICE_INFO */ + + deviceInfo->defaultLowInputLatency = 0.; /** @todo IMPLEMENT ME */ + deviceInfo->defaultLowOutputLatency = 0.; /** @todo IMPLEMENT ME */ + deviceInfo->defaultHighInputLatency = 0.; /** @todo IMPLEMENT ME */ + deviceInfo->defaultHighOutputLatency = 0.; /** @todo IMPLEMENT ME */ + +/* constants from a WINE patch by Francois Gouget, see: + http://www.winehq.com/hypermail/wine-patches/2003/01/0290.html + + --- + Date: Fri, 14 May 2004 10:38:12 +0200 (CEST) + From: Francois Gouget + To: Ross Bencina + Subject: Re: Permission to use wine 48/96 wave patch in BSD licensed library + + [snip] + + I give you permission to use the patch below under the BSD license. + http://www.winehq.com/hypermail/wine-patches/2003/01/0290.html + + [snip] +*/ +#ifndef WAVE_FORMAT_48M08 +#define WAVE_FORMAT_48M08 0x00001000 /* 48 kHz, Mono, 8-bit */ +#define WAVE_FORMAT_48S08 0x00002000 /* 48 kHz, Stereo, 8-bit */ +#define WAVE_FORMAT_48M16 0x00004000 /* 48 kHz, Mono, 16-bit */ +#define WAVE_FORMAT_48S16 0x00008000 /* 48 kHz, Stereo, 16-bit */ +#define WAVE_FORMAT_96M08 0x00010000 /* 96 kHz, Mono, 8-bit */ +#define WAVE_FORMAT_96S08 0x00020000 /* 96 kHz, Stereo, 8-bit */ +#define WAVE_FORMAT_96M16 0x00040000 /* 96 kHz, Mono, 16-bit */ +#define WAVE_FORMAT_96S16 0x00080000 /* 96 kHz, Stereo, 16-bit */ +#endif + + /* defaultSampleRate */ + if( caps.dwChannels == 2 ) + { + if( caps.dwFormats & WAVE_FORMAT_4S16 ) + deviceInfo->defaultSampleRate = 44100.0; + else if( caps.dwFormats & WAVE_FORMAT_48S16 ) + deviceInfo->defaultSampleRate = 48000.0; + else if( caps.dwFormats & WAVE_FORMAT_2S16 ) + deviceInfo->defaultSampleRate = 22050.0; + else if( caps.dwFormats & WAVE_FORMAT_1S16 ) + deviceInfo->defaultSampleRate = 11025.0; + else if( caps.dwFormats & WAVE_FORMAT_96S16 ) + deviceInfo->defaultSampleRate = 96000.0; + else + deviceInfo->defaultSampleRate = 0.; + } + else if( caps.dwChannels == 1 ) + { + if( caps.dwFormats & WAVE_FORMAT_4M16 ) + deviceInfo->defaultSampleRate = 44100.0; + else if( caps.dwFormats & WAVE_FORMAT_48M16 ) + deviceInfo->defaultSampleRate = 48000.0; + else if( caps.dwFormats & WAVE_FORMAT_2M16 ) + deviceInfo->defaultSampleRate = 22050.0; + else if( caps.dwFormats & WAVE_FORMAT_1M16 ) + deviceInfo->defaultSampleRate = 11025.0; + else if( caps.dwFormats & WAVE_FORMAT_96M16 ) + deviceInfo->defaultSampleRate = 96000.0; + else + deviceInfo->defaultSampleRate = 0.; + } + else deviceInfo->defaultSampleRate = 0.; + } + } + + IDirectSoundCapture_Release( lpDirectSoundCapture ); + } + + if( deviceOK ) + { + deviceInfo->name = name; + + if( lpGUID == NULL ) + hostApi->info.defaultInputDevice = hostApi->info.deviceCount; + + hostApi->info.deviceCount++; + } + + return result; +} + + +/***********************************************************************************/ +PaError PaWinDs_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex ) +{ + PaError result = paNoError; + int i, deviceCount; + PaWinDsHostApiRepresentation *winDsHostApi; + DSDeviceNamesAndGUIDs deviceNamesAndGUIDs; + + PaWinDsDeviceInfo *deviceInfoArray; + char comWasInitialized = 0; + + /* + If COM is already initialized CoInitialize will either return + FALSE, or RPC_E_CHANGED_MODE if it was initialised in a different + threading mode. In either case we shouldn't consider it an error + but we need to be careful to not call CoUninitialize() if + RPC_E_CHANGED_MODE was returned. + */ + + HRESULT hr = CoInitialize(NULL); + if( FAILED(hr) && hr != RPC_E_CHANGED_MODE ) + return paUnanticipatedHostError; + + if( hr != RPC_E_CHANGED_MODE ) + comWasInitialized = 1; + + /* initialise guid vectors so they can be safely deleted on error */ + deviceNamesAndGUIDs.winDsHostApi = NULL; + deviceNamesAndGUIDs.inputNamesAndGUIDs.items = NULL; + deviceNamesAndGUIDs.outputNamesAndGUIDs.items = NULL; + + PaWinDs_InitializeDSoundEntryPoints(); + + winDsHostApi = (PaWinDsHostApiRepresentation*)PaUtil_AllocateMemory( sizeof(PaWinDsHostApiRepresentation) ); + if( !winDsHostApi ) + { + result = paInsufficientMemory; + goto error; + } + + winDsHostApi->comWasInitialized = comWasInitialized; + + winDsHostApi->allocations = PaUtil_CreateAllocationGroup(); + if( !winDsHostApi->allocations ) + { + result = paInsufficientMemory; + goto error; + } + + *hostApi = &winDsHostApi->inheritedHostApiRep; + (*hostApi)->info.structVersion = 1; + (*hostApi)->info.type = paDirectSound; + (*hostApi)->info.name = "Windows DirectSound"; + + (*hostApi)->info.deviceCount = 0; + (*hostApi)->info.defaultInputDevice = paNoDevice; + (*hostApi)->info.defaultOutputDevice = paNoDevice; + + +/* DSound - enumerate devices to count them and to gather their GUIDs */ + + result = InitializeDSDeviceNameAndGUIDVector( &deviceNamesAndGUIDs.inputNamesAndGUIDs, winDsHostApi->allocations ); + if( result != paNoError ) + goto error; + + result = InitializeDSDeviceNameAndGUIDVector( &deviceNamesAndGUIDs.outputNamesAndGUIDs, winDsHostApi->allocations ); + if( result != paNoError ) + goto error; + + paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerate( (LPDSENUMCALLBACK)CollectGUIDsProc, (void *)&deviceNamesAndGUIDs.inputNamesAndGUIDs ); + + paWinDsDSoundEntryPoints.DirectSoundEnumerate( (LPDSENUMCALLBACK)CollectGUIDsProc, (void *)&deviceNamesAndGUIDs.outputNamesAndGUIDs ); + + if( deviceNamesAndGUIDs.inputNamesAndGUIDs.enumerationError != paNoError ) + { + result = deviceNamesAndGUIDs.inputNamesAndGUIDs.enumerationError; + goto error; + } + + if( deviceNamesAndGUIDs.outputNamesAndGUIDs.enumerationError != paNoError ) + { + result = deviceNamesAndGUIDs.outputNamesAndGUIDs.enumerationError; + goto error; + } + + deviceCount = deviceNamesAndGUIDs.inputNamesAndGUIDs.count + deviceNamesAndGUIDs.outputNamesAndGUIDs.count; + +#ifdef PAWIN_USE_WDMKS_DEVICE_INFO + if( deviceCount > 0 ) + { + deviceNamesAndGUIDs.winDsHostApi = winDsHostApi; + FindDevicePnpInterfaces( &deviceNamesAndGUIDs ); + } +#endif /* PAWIN_USE_WDMKS_DEVICE_INFO */ + + if( deviceCount > 0 ) + { + /* allocate array for pointers to PaDeviceInfo structs */ + (*hostApi)->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory( + winDsHostApi->allocations, sizeof(PaDeviceInfo*) * deviceCount ); + if( !(*hostApi)->deviceInfos ) + { + result = paInsufficientMemory; + goto error; + } + + /* allocate all PaDeviceInfo structs in a contiguous block */ + deviceInfoArray = (PaWinDsDeviceInfo*)PaUtil_GroupAllocateMemory( + winDsHostApi->allocations, sizeof(PaWinDsDeviceInfo) * deviceCount ); + if( !deviceInfoArray ) + { + result = paInsufficientMemory; + goto error; + } + + for( i=0; i < deviceCount; ++i ) + { + PaDeviceInfo *deviceInfo = &deviceInfoArray[i].inheritedDeviceInfo; + deviceInfo->structVersion = 2; + deviceInfo->hostApi = hostApiIndex; + deviceInfo->name = 0; + (*hostApi)->deviceInfos[i] = deviceInfo; + } + + for( i=0; i < deviceNamesAndGUIDs.inputNamesAndGUIDs.count; ++i ) + { + result = AddInputDeviceInfoFromDirectSoundCapture( winDsHostApi, + deviceNamesAndGUIDs.inputNamesAndGUIDs.items[i].name, + deviceNamesAndGUIDs.inputNamesAndGUIDs.items[i].lpGUID, + deviceNamesAndGUIDs.inputNamesAndGUIDs.items[i].pnpInterface ); + if( result != paNoError ) + goto error; + } + + for( i=0; i < deviceNamesAndGUIDs.outputNamesAndGUIDs.count; ++i ) + { + result = AddOutputDeviceInfoFromDirectSound( winDsHostApi, + deviceNamesAndGUIDs.outputNamesAndGUIDs.items[i].name, + deviceNamesAndGUIDs.outputNamesAndGUIDs.items[i].lpGUID, + deviceNamesAndGUIDs.outputNamesAndGUIDs.items[i].pnpInterface ); + if( result != paNoError ) + goto error; + } + } + + result = TerminateDSDeviceNameAndGUIDVector( &deviceNamesAndGUIDs.inputNamesAndGUIDs ); + if( result != paNoError ) + goto error; + + result = TerminateDSDeviceNameAndGUIDVector( &deviceNamesAndGUIDs.outputNamesAndGUIDs ); + if( result != paNoError ) + goto error; + + + (*hostApi)->Terminate = Terminate; + (*hostApi)->OpenStream = OpenStream; + (*hostApi)->IsFormatSupported = IsFormatSupported; + + PaUtil_InitializeStreamInterface( &winDsHostApi->callbackStreamInterface, CloseStream, StartStream, + StopStream, AbortStream, IsStreamStopped, IsStreamActive, + GetStreamTime, GetStreamCpuLoad, + PaUtil_DummyRead, PaUtil_DummyWrite, + PaUtil_DummyGetReadAvailable, PaUtil_DummyGetWriteAvailable ); + + PaUtil_InitializeStreamInterface( &winDsHostApi->blockingStreamInterface, CloseStream, StartStream, + StopStream, AbortStream, IsStreamStopped, IsStreamActive, + GetStreamTime, PaUtil_DummyGetCpuLoad, + ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable ); + + return result; + +error: + if( winDsHostApi ) + { + if( winDsHostApi->allocations ) + { + PaUtil_FreeAllAllocations( winDsHostApi->allocations ); + PaUtil_DestroyAllocationGroup( winDsHostApi->allocations ); + } + + PaUtil_FreeMemory( winDsHostApi ); + } + + TerminateDSDeviceNameAndGUIDVector( &deviceNamesAndGUIDs.inputNamesAndGUIDs ); + TerminateDSDeviceNameAndGUIDVector( &deviceNamesAndGUIDs.outputNamesAndGUIDs ); + + if( comWasInitialized ) + CoUninitialize(); + + return result; +} + + +/***********************************************************************************/ +static void Terminate( struct PaUtilHostApiRepresentation *hostApi ) +{ + PaWinDsHostApiRepresentation *winDsHostApi = (PaWinDsHostApiRepresentation*)hostApi; + char comWasInitialized = winDsHostApi->comWasInitialized; + + /* + IMPLEMENT ME: + - clean up any resources not handled by the allocation group + */ + + if( winDsHostApi->allocations ) + { + PaUtil_FreeAllAllocations( winDsHostApi->allocations ); + PaUtil_DestroyAllocationGroup( winDsHostApi->allocations ); + } + + PaUtil_FreeMemory( winDsHostApi ); + + PaWinDs_TerminateDSoundEntryPoints(); + + if( comWasInitialized ) + CoUninitialize(); +} + + +/* Set minimal latency based on whether NT or Win95. + * NT has higher latency. + */ +static int PaWinDS_GetMinSystemLatency( void ) +{ + int minLatencyMsec; + /* Set minimal latency based on whether NT or other OS. + * NT has higher latency. + */ + OSVERSIONINFO osvi; + osvi.dwOSVersionInfoSize = sizeof( osvi ); + GetVersionEx( &osvi ); + DBUG(("PA - PlatformId = 0x%x\n", osvi.dwPlatformId )); + DBUG(("PA - MajorVersion = 0x%x\n", osvi.dwMajorVersion )); + DBUG(("PA - MinorVersion = 0x%x\n", osvi.dwMinorVersion )); + /* Check for NT */ + if( (osvi.dwMajorVersion == 4) && (osvi.dwPlatformId == 2) ) + { + minLatencyMsec = PA_WIN_NT_LATENCY; + } + else if(osvi.dwMajorVersion >= 5) + { + minLatencyMsec = PA_WIN_WDM_LATENCY; + } + else + { + minLatencyMsec = PA_WIN_9X_LATENCY; + } + return minLatencyMsec; +} + +static PaError ValidateWinDirectSoundSpecificStreamInfo( + const PaStreamParameters *streamParameters, + const PaWinDirectSoundStreamInfo *streamInfo ) +{ + if( streamInfo ) + { + if( streamInfo->size != sizeof( PaWinDirectSoundStreamInfo ) + || streamInfo->version != 1 ) + { + return paIncompatibleHostApiSpecificStreamInfo; + } + } + + return paNoError; +} + +/***********************************************************************************/ +static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi, + const PaStreamParameters *inputParameters, + const PaStreamParameters *outputParameters, + double sampleRate ) +{ + PaError result; + PaWinDsDeviceInfo *inputWinDsDeviceInfo, *outputWinDsDeviceInfo; + PaDeviceInfo *inputDeviceInfo, *outputDeviceInfo; + int inputChannelCount, outputChannelCount; + PaSampleFormat inputSampleFormat, outputSampleFormat; + PaWinDirectSoundStreamInfo *inputStreamInfo, *outputStreamInfo; + + if( inputParameters ) + { + inputWinDsDeviceInfo = (PaWinDsDeviceInfo*) hostApi->deviceInfos[ inputParameters->device ]; + inputDeviceInfo = &inputWinDsDeviceInfo->inheritedDeviceInfo; + + inputChannelCount = inputParameters->channelCount; + inputSampleFormat = inputParameters->sampleFormat; + + /* unless alternate device specification is supported, reject the use of + paUseHostApiSpecificDeviceSpecification */ + + if( inputParameters->device == paUseHostApiSpecificDeviceSpecification ) + return paInvalidDevice; + + /* check that input device can support inputChannelCount */ + if( inputWinDsDeviceInfo->deviceInputChannelCountIsKnown + && inputChannelCount > inputDeviceInfo->maxInputChannels ) + return paInvalidChannelCount; + + /* validate inputStreamInfo */ + inputStreamInfo = (PaWinDirectSoundStreamInfo*)inputParameters->hostApiSpecificStreamInfo; + result = ValidateWinDirectSoundSpecificStreamInfo( inputParameters, inputStreamInfo ); + if( result != paNoError ) return result; + } + else + { + inputChannelCount = 0; + } + + if( outputParameters ) + { + outputWinDsDeviceInfo = (PaWinDsDeviceInfo*) hostApi->deviceInfos[ outputParameters->device ]; + outputDeviceInfo = &outputWinDsDeviceInfo->inheritedDeviceInfo; + + outputChannelCount = outputParameters->channelCount; + outputSampleFormat = outputParameters->sampleFormat; + + /* unless alternate device specification is supported, reject the use of + paUseHostApiSpecificDeviceSpecification */ + + if( outputParameters->device == paUseHostApiSpecificDeviceSpecification ) + return paInvalidDevice; + + /* check that output device can support inputChannelCount */ + if( outputWinDsDeviceInfo->deviceOutputChannelCountIsKnown + && outputChannelCount > outputDeviceInfo->maxOutputChannels ) + return paInvalidChannelCount; + + /* validate outputStreamInfo */ + outputStreamInfo = (PaWinDirectSoundStreamInfo*)outputParameters->hostApiSpecificStreamInfo; + result = ValidateWinDirectSoundSpecificStreamInfo( outputParameters, outputStreamInfo ); + if( result != paNoError ) return result; + } + else + { + outputChannelCount = 0; + } + + /* + IMPLEMENT ME: + + - if a full duplex stream is requested, check that the combination + of input and output parameters is supported if necessary + + - check that the device supports sampleRate + + Because the buffer adapter handles conversion between all standard + sample formats, the following checks are only required if paCustomFormat + is implemented, or under some other unusual conditions. + + - check that input device can support inputSampleFormat, or that + we have the capability to convert from outputSampleFormat to + a native format + + - check that output device can support outputSampleFormat, or that + we have the capability to convert from outputSampleFormat to + a native format + */ + + return paFormatIsSupported; +} + + +/************************************************************************* +** Determine minimum number of buffers required for this host based +** on minimum latency. Latency can be optionally set by user by setting +** an environment variable. For example, to set latency to 200 msec, put: +** +** set PA_MIN_LATENCY_MSEC=200 +** +** in the AUTOEXEC.BAT file and reboot. +** If the environment variable is not set, then the latency will be determined +** based on the OS. Windows NT has higher latency than Win95. +*/ +#define PA_LATENCY_ENV_NAME ("PA_MIN_LATENCY_MSEC") +#define PA_ENV_BUF_SIZE (32) + +static int PaWinDs_GetMinLatencyFrames( double sampleRate ) +{ + char envbuf[PA_ENV_BUF_SIZE]; + DWORD hresult; + int minLatencyMsec = 0; + + /* Let user determine minimal latency by setting environment variable. */ + hresult = GetEnvironmentVariable( PA_LATENCY_ENV_NAME, envbuf, PA_ENV_BUF_SIZE ); + if( (hresult > 0) && (hresult < PA_ENV_BUF_SIZE) ) + { + minLatencyMsec = atoi( envbuf ); + } + else + { + minLatencyMsec = PaWinDS_GetMinSystemLatency(); +#if PA_USE_HIGH_LATENCY + PRINT(("PA - Minimum Latency set to %d msec!\n", minLatencyMsec )); +#endif + + } + + return (int) (minLatencyMsec * sampleRate * SECONDS_PER_MSEC); +} + + +static HRESULT InitInputBuffer( PaWinDsStream *stream, PaSampleFormat sampleFormat, unsigned long nFrameRate, WORD nChannels, int bytesPerBuffer, PaWinWaveFormatChannelMask channelMask ) +{ + DSCBUFFERDESC captureDesc; + PaWinWaveFormat waveFormat; + HRESULT result; + + stream->bytesPerInputFrame = nChannels * Pa_GetSampleSize(sampleFormat); + + stream->inputSize = bytesPerBuffer; + // ---------------------------------------------------------------------- + // Setup the secondary buffer description + ZeroMemory(&captureDesc, sizeof(DSCBUFFERDESC)); + captureDesc.dwSize = sizeof(DSCBUFFERDESC); + captureDesc.dwFlags = 0; + captureDesc.dwBufferBytes = bytesPerBuffer; + captureDesc.lpwfxFormat = (WAVEFORMATEX*)&waveFormat; + + // Create the capture buffer + + // first try WAVEFORMATEXTENSIBLE. if this fails, fall back to WAVEFORMATEX + PaWin_InitializeWaveFormatExtensible( &waveFormat, nChannels, + sampleFormat, nFrameRate, channelMask ); + + if( IDirectSoundCapture_CreateCaptureBuffer( stream->pDirectSoundCapture, + &captureDesc, &stream->pDirectSoundInputBuffer, NULL) != DS_OK ) + { + PaWin_InitializeWaveFormatEx( &waveFormat, nChannels, sampleFormat, nFrameRate ); + + if ((result = IDirectSoundCapture_CreateCaptureBuffer( stream->pDirectSoundCapture, + &captureDesc, &stream->pDirectSoundInputBuffer, NULL)) != DS_OK) return result; + } + + stream->readOffset = 0; // reset last read position to start of buffer + return DS_OK; +} + + +static HRESULT InitOutputBuffer( PaWinDsStream *stream, PaSampleFormat sampleFormat, unsigned long nFrameRate, WORD nChannels, int bytesPerBuffer, PaWinWaveFormatChannelMask channelMask ) +{ + /** @todo FIXME: if InitOutputBuffer returns an error I'm not sure it frees all resources cleanly */ + + DWORD dwDataLen; + DWORD playCursor; + HRESULT result; + LPDIRECTSOUNDBUFFER pPrimaryBuffer; + HWND hWnd; + HRESULT hr; + PaWinWaveFormat waveFormat; + DSBUFFERDESC primaryDesc; + DSBUFFERDESC secondaryDesc; + unsigned char* pDSBuffData; + LARGE_INTEGER counterFrequency; + int bytesPerSample = Pa_GetSampleSize(sampleFormat); + + stream->outputBufferSizeBytes = bytesPerBuffer; + stream->outputIsRunning = FALSE; + stream->outputUnderflowCount = 0; + stream->dsw_framesWritten = 0; + stream->bytesPerOutputFrame = nChannels * bytesPerSample; + + // We were using getForegroundWindow() but sometimes the ForegroundWindow may not be the + // applications's window. Also if that window is closed before the Buffer is closed + // then DirectSound can crash. (Thanks for Scott Patterson for reporting this.) + // So we will use GetDesktopWindow() which was suggested by Miller Puckette. + // hWnd = GetForegroundWindow(); + // + // FIXME: The example code I have on the net creates a hidden window that + // is managed by our code - I think we should do that - one hidden + // window for the whole of Pa_DS + // + hWnd = GetDesktopWindow(); + + // Set cooperative level to DSSCL_EXCLUSIVE so that we can get 16 bit output, 44.1 KHz. + // Exclusize also prevents unexpected sounds from other apps during a performance. + if ((hr = IDirectSound_SetCooperativeLevel( stream->pDirectSound, + hWnd, DSSCL_EXCLUSIVE)) != DS_OK) + { + return hr; + } + + // ----------------------------------------------------------------------- + // Create primary buffer and set format just so we can specify our custom format. + // Otherwise we would be stuck with the default which might be 8 bit or 22050 Hz. + // Setup the primary buffer description + ZeroMemory(&primaryDesc, sizeof(DSBUFFERDESC)); + primaryDesc.dwSize = sizeof(DSBUFFERDESC); + primaryDesc.dwFlags = DSBCAPS_PRIMARYBUFFER; // all panning, mixing, etc done by synth + primaryDesc.dwBufferBytes = 0; + primaryDesc.lpwfxFormat = NULL; + // Create the buffer + if ((result = IDirectSound_CreateSoundBuffer( stream->pDirectSound, + &primaryDesc, &pPrimaryBuffer, NULL)) != DS_OK) return result; + + // Set the primary buffer's format + + // first try WAVEFORMATEXTENSIBLE. if this fails, fall back to WAVEFORMATEX + PaWin_InitializeWaveFormatExtensible( &waveFormat, nChannels, + sampleFormat, nFrameRate, channelMask ); + + if( IDirectSoundBuffer_SetFormat( pPrimaryBuffer, (WAVEFORMATEX*)&waveFormat) != DS_OK ) + { + PaWin_InitializeWaveFormatEx( &waveFormat, nChannels, sampleFormat, nFrameRate ); + + if((result = IDirectSoundBuffer_SetFormat( pPrimaryBuffer, (WAVEFORMATEX*)&waveFormat)) != DS_OK) return result; + } + + // ---------------------------------------------------------------------- + // Setup the secondary buffer description + ZeroMemory(&secondaryDesc, sizeof(DSBUFFERDESC)); + secondaryDesc.dwSize = sizeof(DSBUFFERDESC); + secondaryDesc.dwFlags = DSBCAPS_GLOBALFOCUS | DSBCAPS_GETCURRENTPOSITION2; + secondaryDesc.dwBufferBytes = bytesPerBuffer; + secondaryDesc.lpwfxFormat = (WAVEFORMATEX*)&waveFormat; + // Create the secondary buffer + if ((result = IDirectSound_CreateSoundBuffer( stream->pDirectSound, + &secondaryDesc, &stream->pDirectSoundOutputBuffer, NULL)) != DS_OK) return result; + // Lock the DS buffer + if ((result = IDirectSoundBuffer_Lock( stream->pDirectSoundOutputBuffer, 0, stream->outputBufferSizeBytes, (LPVOID*)&pDSBuffData, + &dwDataLen, NULL, 0, 0)) != DS_OK) return result; + // Zero the DS buffer + ZeroMemory(pDSBuffData, dwDataLen); + // Unlock the DS buffer + if ((result = IDirectSoundBuffer_Unlock( stream->pDirectSoundOutputBuffer, pDSBuffData, dwDataLen, NULL, 0)) != DS_OK) return result; + if( QueryPerformanceFrequency( &counterFrequency ) ) + { + int framesInBuffer = bytesPerBuffer / (nChannels * bytesPerSample); + stream->perfCounterTicksPerBuffer.QuadPart = (counterFrequency.QuadPart * framesInBuffer) / nFrameRate; + } + else + { + stream->perfCounterTicksPerBuffer.QuadPart = 0; + } + // Let DSound set the starting write position because if we set it to zero, it looks like the + // buffer is full to begin with. This causes a long pause before sound starts when using large buffers. + hr = IDirectSoundBuffer_GetCurrentPosition( stream->pDirectSoundOutputBuffer, + &playCursor, &stream->outputBufferWriteOffsetBytes ); + if( hr != DS_OK ) + { + return hr; + } + stream->dsw_framesWritten = stream->outputBufferWriteOffsetBytes / stream->bytesPerOutputFrame; + /* printf("DSW_InitOutputBuffer: playCursor = %d, writeCursor = %d\n", playCursor, dsw->dsw_WriteOffset ); */ + return DS_OK; +} + +/***********************************************************************************/ +/* see pa_hostapi.h for a list of validity guarantees made about OpenStream parameters */ + +static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi, + PaStream** s, + const PaStreamParameters *inputParameters, + const PaStreamParameters *outputParameters, + double sampleRate, + unsigned long framesPerBuffer, + PaStreamFlags streamFlags, + PaStreamCallback *streamCallback, + void *userData ) +{ + PaError result = paNoError; + PaWinDsHostApiRepresentation *winDsHostApi = (PaWinDsHostApiRepresentation*)hostApi; + PaWinDsStream *stream = 0; + PaWinDsDeviceInfo *inputWinDsDeviceInfo, *outputWinDsDeviceInfo; + PaDeviceInfo *inputDeviceInfo, *outputDeviceInfo; + int inputChannelCount, outputChannelCount; + PaSampleFormat inputSampleFormat, outputSampleFormat; + PaSampleFormat hostInputSampleFormat, hostOutputSampleFormat; + unsigned long suggestedInputLatencyFrames, suggestedOutputLatencyFrames; + PaWinDirectSoundStreamInfo *inputStreamInfo, *outputStreamInfo; + PaWinWaveFormatChannelMask inputChannelMask, outputChannelMask; + + if( inputParameters ) + { + inputWinDsDeviceInfo = (PaWinDsDeviceInfo*) hostApi->deviceInfos[ inputParameters->device ]; + inputDeviceInfo = &inputWinDsDeviceInfo->inheritedDeviceInfo; + + inputChannelCount = inputParameters->channelCount; + inputSampleFormat = inputParameters->sampleFormat; + suggestedInputLatencyFrames = (unsigned long)(inputParameters->suggestedLatency * sampleRate); + + /* IDEA: the following 3 checks could be performed by default by pa_front + unless some flag indicated otherwise */ + + /* unless alternate device specification is supported, reject the use of + paUseHostApiSpecificDeviceSpecification */ + if( inputParameters->device == paUseHostApiSpecificDeviceSpecification ) + return paInvalidDevice; + + /* check that input device can support inputChannelCount */ + if( inputWinDsDeviceInfo->deviceInputChannelCountIsKnown + && inputChannelCount > inputDeviceInfo->maxInputChannels ) + return paInvalidChannelCount; + + /* validate hostApiSpecificStreamInfo */ + inputStreamInfo = (PaWinDirectSoundStreamInfo*)inputParameters->hostApiSpecificStreamInfo; + result = ValidateWinDirectSoundSpecificStreamInfo( inputParameters, inputStreamInfo ); + if( result != paNoError ) return result; + + if( inputStreamInfo && inputStreamInfo->flags & paWinDirectSoundUseChannelMask ) + inputChannelMask = inputStreamInfo->channelMask; + else + inputChannelMask = PaWin_DefaultChannelMask( inputChannelCount ); + } + else + { + inputChannelCount = 0; + inputSampleFormat = 0; + suggestedInputLatencyFrames = 0; + } + + + if( outputParameters ) + { + outputWinDsDeviceInfo = (PaWinDsDeviceInfo*) hostApi->deviceInfos[ outputParameters->device ]; + outputDeviceInfo = &outputWinDsDeviceInfo->inheritedDeviceInfo; + + outputChannelCount = outputParameters->channelCount; + outputSampleFormat = outputParameters->sampleFormat; + suggestedOutputLatencyFrames = (unsigned long)(outputParameters->suggestedLatency * sampleRate); + + /* unless alternate device specification is supported, reject the use of + paUseHostApiSpecificDeviceSpecification */ + if( outputParameters->device == paUseHostApiSpecificDeviceSpecification ) + return paInvalidDevice; + + /* check that output device can support outputChannelCount */ + if( outputWinDsDeviceInfo->deviceOutputChannelCountIsKnown + && outputChannelCount > outputDeviceInfo->maxOutputChannels ) + return paInvalidChannelCount; + + /* validate hostApiSpecificStreamInfo */ + outputStreamInfo = (PaWinDirectSoundStreamInfo*)outputParameters->hostApiSpecificStreamInfo; + result = ValidateWinDirectSoundSpecificStreamInfo( outputParameters, outputStreamInfo ); + if( result != paNoError ) return result; + + if( outputStreamInfo && outputStreamInfo->flags & paWinDirectSoundUseChannelMask ) + outputChannelMask = outputStreamInfo->channelMask; + else + outputChannelMask = PaWin_DefaultChannelMask( outputChannelCount ); + } + else + { + outputChannelCount = 0; + outputSampleFormat = 0; + suggestedOutputLatencyFrames = 0; + } + + + /* + IMPLEMENT ME: + + ( the following two checks are taken care of by PaUtil_InitializeBufferProcessor() ) + + - check that input device can support inputSampleFormat, or that + we have the capability to convert from outputSampleFormat to + a native format + + - check that output device can support outputSampleFormat, or that + we have the capability to convert from outputSampleFormat to + a native format + + - if a full duplex stream is requested, check that the combination + of input and output parameters is supported + + - check that the device supports sampleRate + + - alter sampleRate to a close allowable rate if possible / necessary + + - validate suggestedInputLatency and suggestedOutputLatency parameters, + use default values where necessary + */ + + + /* validate platform specific flags */ + if( (streamFlags & paPlatformSpecificFlags) != 0 ) + return paInvalidFlag; /* unexpected platform specific flag */ + + + stream = (PaWinDsStream*)PaUtil_AllocateMemory( sizeof(PaWinDsStream) ); + if( !stream ) + { + result = paInsufficientMemory; + goto error; + } + + memset( stream, 0, sizeof(PaWinDsStream) ); /* initialize all stream variables to 0 */ + + if( streamCallback ) + { + PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation, + &winDsHostApi->callbackStreamInterface, streamCallback, userData ); + } + else + { + PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation, + &winDsHostApi->blockingStreamInterface, streamCallback, userData ); + } + + PaUtil_InitializeCpuLoadMeasurer( &stream->cpuLoadMeasurer, sampleRate ); + + + if( inputParameters ) + { + /* IMPLEMENT ME - establish which host formats are available */ + PaSampleFormat nativeInputFormats = paInt16; + //PaSampleFormat nativeFormats = paUInt8 | paInt16 | paInt24 | paInt32 | paFloat32; + + hostInputSampleFormat = + PaUtil_SelectClosestAvailableFormat( nativeInputFormats, inputParameters->sampleFormat ); + } + else + { + hostInputSampleFormat = 0; + } + + if( outputParameters ) + { + /* IMPLEMENT ME - establish which host formats are available */ + PaSampleFormat nativeOutputFormats = paInt16; + //PaSampleFormat nativeOutputFormats = paUInt8 | paInt16 | paInt24 | paInt32 | paFloat32; + + hostOutputSampleFormat = + PaUtil_SelectClosestAvailableFormat( nativeOutputFormats, outputParameters->sampleFormat ); + } + else + { + hostOutputSampleFormat = 0; + } + + result = PaUtil_InitializeBufferProcessor( &stream->bufferProcessor, + inputChannelCount, inputSampleFormat, hostInputSampleFormat, + outputChannelCount, outputSampleFormat, hostOutputSampleFormat, + sampleRate, streamFlags, framesPerBuffer, + framesPerBuffer, /* ignored in paUtilVariableHostBufferSizePartialUsageAllowed mode. */ + /* This next mode is required because DS can split the host buffer when it wraps around. */ + paUtilVariableHostBufferSizePartialUsageAllowed, + streamCallback, userData ); + if( result != paNoError ) + goto error; + + + stream->streamRepresentation.streamInfo.inputLatency = + PaUtil_GetBufferProcessorInputLatency(&stream->bufferProcessor); /* FIXME: not initialised anywhere else */ + stream->streamRepresentation.streamInfo.outputLatency = + PaUtil_GetBufferProcessorOutputLatency(&stream->bufferProcessor); /* FIXME: not initialised anywhere else */ + stream->streamRepresentation.streamInfo.sampleRate = sampleRate; + + +/* DirectSound specific initialization */ + { + HRESULT hr; + int bytesPerDirectSoundBuffer; + int userLatencyFrames; + int minLatencyFrames; + + stream->timerID = 0; + + /* Get system minimum latency. */ + minLatencyFrames = PaWinDs_GetMinLatencyFrames( sampleRate ); + + /* Let user override latency by passing latency parameter. */ + userLatencyFrames = (suggestedInputLatencyFrames > suggestedOutputLatencyFrames) + ? suggestedInputLatencyFrames + : suggestedOutputLatencyFrames; + if( userLatencyFrames > 0 ) minLatencyFrames = userLatencyFrames; + + /* Calculate stream->framesPerDSBuffer depending on framesPerBuffer */ + if( framesPerBuffer == paFramesPerBufferUnspecified ) + { + /* App support variable framesPerBuffer */ + stream->framesPerDSBuffer = minLatencyFrames; + + stream->streamRepresentation.streamInfo.outputLatency = (double)(minLatencyFrames - 1) / sampleRate; + } + else + { + /* Round up to number of buffers needed to guarantee that latency. */ + int numUserBuffers = (minLatencyFrames + framesPerBuffer - 1) / framesPerBuffer; + if( numUserBuffers < 1 ) numUserBuffers = 1; + numUserBuffers += 1; /* So we have latency worth of buffers ahead of current buffer. */ + stream->framesPerDSBuffer = framesPerBuffer * numUserBuffers; + + stream->streamRepresentation.streamInfo.outputLatency = (double)(framesPerBuffer * (numUserBuffers-1)) / sampleRate; + } + + { + /** @todo REVIEW: this calculation seems incorrect to me - rossb. */ + int msecLatency = (int) ((stream->framesPerDSBuffer * MSEC_PER_SECOND) / sampleRate); + PRINT(("PortAudio on DirectSound - Latency = %d frames, %d msec\n", stream->framesPerDSBuffer, msecLatency )); + } + + + /* ------------------ OUTPUT */ + if( outputParameters ) + { + /* + PaDeviceInfo *deviceInfo = hostApi->deviceInfos[ outputParameters->device ]; + DBUG(("PaHost_OpenStream: deviceID = 0x%x\n", outputParameters->device)); + */ + + int bytesPerSample = Pa_GetSampleSize(hostOutputSampleFormat); + bytesPerDirectSoundBuffer = stream->framesPerDSBuffer * outputParameters->channelCount * bytesPerSample; + if( bytesPerDirectSoundBuffer < DSBSIZE_MIN ) + { + result = paBufferTooSmall; + goto error; + } + else if( bytesPerDirectSoundBuffer > DSBSIZE_MAX ) + { + result = paBufferTooBig; + goto error; + } + + hr = paWinDsDSoundEntryPoints.DirectSoundCreate( + ((PaWinDsDeviceInfo*)hostApi->deviceInfos[outputParameters->device])->lpGUID, + &stream->pDirectSound, NULL ); + + if( hr != DS_OK ) + { + ERR_RPT(("PortAudio: DirectSoundCreate() failed!\n")); + result = paUnanticipatedHostError; + PA_DS_SET_LAST_DIRECTSOUND_ERROR( hr ); + goto error; + } + hr = InitOutputBuffer( stream, + hostOutputSampleFormat, + (unsigned long) (sampleRate + 0.5), + (WORD)outputParameters->channelCount, bytesPerDirectSoundBuffer, + outputChannelMask ); + DBUG(("InitOutputBuffer() returns %x\n", hr)); + if( hr != DS_OK ) + { + result = paUnanticipatedHostError; + PA_DS_SET_LAST_DIRECTSOUND_ERROR( hr ); + goto error; + } + /* Calculate value used in latency calculation to avoid real-time divides. */ + stream->secondsPerHostByte = 1.0 / + (stream->bufferProcessor.bytesPerHostOutputSample * + outputChannelCount * sampleRate); + } + + /* ------------------ INPUT */ + if( inputParameters ) + { + /* + PaDeviceInfo *deviceInfo = hostApi->deviceInfos[ inputParameters->device ]; + DBUG(("PaHost_OpenStream: deviceID = 0x%x\n", inputParameters->device)); + */ + + int bytesPerSample = Pa_GetSampleSize(hostInputSampleFormat); + bytesPerDirectSoundBuffer = stream->framesPerDSBuffer * inputParameters->channelCount * bytesPerSample; + if( bytesPerDirectSoundBuffer < DSBSIZE_MIN ) + { + result = paBufferTooSmall; + goto error; + } + else if( bytesPerDirectSoundBuffer > DSBSIZE_MAX ) + { + result = paBufferTooBig; + goto error; + } + + hr = paWinDsDSoundEntryPoints.DirectSoundCaptureCreate( + ((PaWinDsDeviceInfo*)hostApi->deviceInfos[inputParameters->device])->lpGUID, + &stream->pDirectSoundCapture, NULL ); + if( hr != DS_OK ) + { + ERR_RPT(("PortAudio: DirectSoundCaptureCreate() failed!\n")); + result = paUnanticipatedHostError; + PA_DS_SET_LAST_DIRECTSOUND_ERROR( hr ); + goto error; + } + hr = InitInputBuffer( stream, + hostInputSampleFormat, + (unsigned long) (sampleRate + 0.5), + (WORD)inputParameters->channelCount, bytesPerDirectSoundBuffer, + inputChannelMask ); + DBUG(("InitInputBuffer() returns %x\n", hr)); + if( hr != DS_OK ) + { + ERR_RPT(("PortAudio: DSW_InitInputBuffer() returns %x\n", hr)); + result = paUnanticipatedHostError; + PA_DS_SET_LAST_DIRECTSOUND_ERROR( hr ); + goto error; + } + } + + } + + *s = (PaStream*)stream; + + return result; + +error: + if( stream ) + PaUtil_FreeMemory( stream ); + + return result; +} + + +/************************************************************************************ + * Determine how much space can be safely written to in DS buffer. + * Detect underflows and overflows. + * Does not allow writing into safety gap maintained by DirectSound. + */ +static HRESULT QueryOutputSpace( PaWinDsStream *stream, long *bytesEmpty ) +{ + HRESULT hr; + DWORD playCursor; + DWORD writeCursor; + long numBytesEmpty; + long playWriteGap; + // Query to see how much room is in buffer. + hr = IDirectSoundBuffer_GetCurrentPosition( stream->pDirectSoundOutputBuffer, + &playCursor, &writeCursor ); + if( hr != DS_OK ) + { + return hr; + } + // Determine size of gap between playIndex and WriteIndex that we cannot write into. + playWriteGap = writeCursor - playCursor; + if( playWriteGap < 0 ) playWriteGap += stream->outputBufferSizeBytes; // unwrap + /* DirectSound doesn't have a large enough playCursor so we cannot detect wrap-around. */ + /* Attempt to detect playCursor wrap-around and correct it. */ + if( stream->outputIsRunning && (stream->perfCounterTicksPerBuffer.QuadPart != 0) ) + { + /* How much time has elapsed since last check. */ + LARGE_INTEGER currentTime; + LARGE_INTEGER elapsedTime; + long bytesPlayed; + long bytesExpected; + long buffersWrapped; + QueryPerformanceCounter( ¤tTime ); + elapsedTime.QuadPart = currentTime.QuadPart - stream->previousPlayTime.QuadPart; + stream->previousPlayTime = currentTime; + /* How many bytes does DirectSound say have been played. */ + bytesPlayed = playCursor - stream->previousPlayCursor; + if( bytesPlayed < 0 ) bytesPlayed += stream->outputBufferSizeBytes; // unwrap + stream->previousPlayCursor = playCursor; + /* Calculate how many bytes we would have expected to been played by now. */ + bytesExpected = (long) ((elapsedTime.QuadPart * stream->outputBufferSizeBytes) / stream->perfCounterTicksPerBuffer.QuadPart); + buffersWrapped = (bytesExpected - bytesPlayed) / stream->outputBufferSizeBytes; + if( buffersWrapped > 0 ) + { + playCursor += (buffersWrapped * stream->outputBufferSizeBytes); + bytesPlayed += (buffersWrapped * stream->outputBufferSizeBytes); + } + /* Maintain frame output cursor. */ + stream->framesPlayed += (bytesPlayed / stream->bytesPerOutputFrame); + } + numBytesEmpty = playCursor - stream->outputBufferWriteOffsetBytes; + if( numBytesEmpty < 0 ) numBytesEmpty += stream->outputBufferSizeBytes; // unwrap offset + /* Have we underflowed? */ + if( numBytesEmpty > (stream->outputBufferSizeBytes - playWriteGap) ) + { + if( stream->outputIsRunning ) + { + stream->outputUnderflowCount += 1; + } + stream->outputBufferWriteOffsetBytes = writeCursor; + numBytesEmpty = stream->outputBufferSizeBytes - playWriteGap; + } + *bytesEmpty = numBytesEmpty; + return hr; +} + +/***********************************************************************************/ +static PaError Pa_TimeSlice( PaWinDsStream *stream ) +{ + PaError result = 0; /* FIXME: this should be declared int and this function should also return that type (same as stream callback return type)*/ + long numFrames = 0; + long bytesEmpty = 0; + long bytesFilled = 0; + long bytesToXfer = 0; + long framesToXfer = 0; + long numInFramesReady = 0; + long numOutFramesReady = 0; + long bytesProcessed; + HRESULT hresult; + double outputLatency = 0; + PaStreamCallbackTimeInfo timeInfo = {0,0,0}; /** @todo implement inputBufferAdcTime */ + +/* Input */ + LPBYTE lpInBuf1 = NULL; + LPBYTE lpInBuf2 = NULL; + DWORD dwInSize1 = 0; + DWORD dwInSize2 = 0; +/* Output */ + LPBYTE lpOutBuf1 = NULL; + LPBYTE lpOutBuf2 = NULL; + DWORD dwOutSize1 = 0; + DWORD dwOutSize2 = 0; + + /* How much input data is available? */ + if( stream->bufferProcessor.inputChannelCount > 0 ) + { + HRESULT hr; + DWORD capturePos; + DWORD readPos; + long filled = 0; + // Query to see how much data is in buffer. + // We don't need the capture position but sometimes DirectSound doesn't handle NULLS correctly + // so let's pass a pointer just to be safe. + hr = IDirectSoundCaptureBuffer_GetCurrentPosition( stream->pDirectSoundInputBuffer, &capturePos, &readPos ); + if( hr == DS_OK ) + { + filled = readPos - stream->readOffset; + if( filled < 0 ) filled += stream->inputSize; // unwrap offset + bytesFilled = filled; + } + // FIXME: what happens if IDirectSoundCaptureBuffer_GetCurrentPosition fails? + + framesToXfer = numInFramesReady = bytesFilled / stream->bytesPerInputFrame; + outputLatency = ((double)bytesFilled) * stream->secondsPerHostByte; + + /** @todo Check for overflow */ + } + + /* How much output room is available? */ + if( stream->bufferProcessor.outputChannelCount > 0 ) + { + UINT previousUnderflowCount = stream->outputUnderflowCount; + QueryOutputSpace( stream, &bytesEmpty ); + framesToXfer = numOutFramesReady = bytesEmpty / stream->bytesPerOutputFrame; + + /* Check for underflow */ + if( stream->outputUnderflowCount != previousUnderflowCount ) + stream->callbackFlags |= paOutputUnderflow; + } + + if( (numInFramesReady > 0) && (numOutFramesReady > 0) ) + { + framesToXfer = (numOutFramesReady < numInFramesReady) ? numOutFramesReady : numInFramesReady; + } + + if( framesToXfer > 0 ) + { + + PaUtil_BeginCpuLoadMeasurement( &stream->cpuLoadMeasurer ); + + /* The outputBufferDacTime parameter should indicates the time at which + the first sample of the output buffer is heard at the DACs. */ + timeInfo.currentTime = PaUtil_GetTime(); + timeInfo.outputBufferDacTime = timeInfo.currentTime + outputLatency; + + + PaUtil_BeginBufferProcessing( &stream->bufferProcessor, &timeInfo, stream->callbackFlags ); + stream->callbackFlags = 0; + + /* Input */ + if( stream->bufferProcessor.inputChannelCount > 0 ) + { + bytesToXfer = framesToXfer * stream->bytesPerInputFrame; + hresult = IDirectSoundCaptureBuffer_Lock ( stream->pDirectSoundInputBuffer, + stream->readOffset, bytesToXfer, + (void **) &lpInBuf1, &dwInSize1, + (void **) &lpInBuf2, &dwInSize2, 0); + if (hresult != DS_OK) + { + ERR_RPT(("DirectSound IDirectSoundCaptureBuffer_Lock failed, hresult = 0x%x\n",hresult)); + result = paUnanticipatedHostError; + PA_DS_SET_LAST_DIRECTSOUND_ERROR( hresult ); + goto error2; + } + + numFrames = dwInSize1 / stream->bytesPerInputFrame; + PaUtil_SetInputFrameCount( &stream->bufferProcessor, numFrames ); + PaUtil_SetInterleavedInputChannels( &stream->bufferProcessor, 0, lpInBuf1, 0 ); + /* Is input split into two regions. */ + if( dwInSize2 > 0 ) + { + numFrames = dwInSize2 / stream->bytesPerInputFrame; + PaUtil_Set2ndInputFrameCount( &stream->bufferProcessor, numFrames ); + PaUtil_Set2ndInterleavedInputChannels( &stream->bufferProcessor, 0, lpInBuf2, 0 ); + } + } + + /* Output */ + if( stream->bufferProcessor.outputChannelCount > 0 ) + { + bytesToXfer = framesToXfer * stream->bytesPerOutputFrame; + hresult = IDirectSoundBuffer_Lock ( stream->pDirectSoundOutputBuffer, + stream->outputBufferWriteOffsetBytes, bytesToXfer, + (void **) &lpOutBuf1, &dwOutSize1, + (void **) &lpOutBuf2, &dwOutSize2, 0); + if (hresult != DS_OK) + { + ERR_RPT(("DirectSound IDirectSoundBuffer_Lock failed, hresult = 0x%x\n",hresult)); + result = paUnanticipatedHostError; + PA_DS_SET_LAST_DIRECTSOUND_ERROR( hresult ); + goto error1; + } + + numFrames = dwOutSize1 / stream->bytesPerOutputFrame; + PaUtil_SetOutputFrameCount( &stream->bufferProcessor, numFrames ); + PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor, 0, lpOutBuf1, 0 ); + + /* Is output split into two regions. */ + if( dwOutSize2 > 0 ) + { + numFrames = dwOutSize2 / stream->bytesPerOutputFrame; + PaUtil_Set2ndOutputFrameCount( &stream->bufferProcessor, numFrames ); + PaUtil_Set2ndInterleavedOutputChannels( &stream->bufferProcessor, 0, lpOutBuf2, 0 ); + } + } + + result = paContinue; + numFrames = PaUtil_EndBufferProcessing( &stream->bufferProcessor, &result ); + stream->framesWritten += numFrames; + + if( stream->bufferProcessor.outputChannelCount > 0 ) + { + /* FIXME: an underflow could happen here */ + + /* Update our buffer offset and unlock sound buffer */ + bytesProcessed = numFrames * stream->bytesPerOutputFrame; + stream->outputBufferWriteOffsetBytes = (stream->outputBufferWriteOffsetBytes + bytesProcessed) % stream->outputBufferSizeBytes; + IDirectSoundBuffer_Unlock( stream->pDirectSoundOutputBuffer, lpOutBuf1, dwOutSize1, lpOutBuf2, dwOutSize2); + stream->dsw_framesWritten += numFrames; + } + +error1: + if( stream->bufferProcessor.inputChannelCount > 0 ) + { + /* FIXME: an overflow could happen here */ + + /* Update our buffer offset and unlock sound buffer */ + bytesProcessed = numFrames * stream->bytesPerInputFrame; + stream->readOffset = (stream->readOffset + bytesProcessed) % stream->inputSize; + IDirectSoundCaptureBuffer_Unlock( stream->pDirectSoundInputBuffer, lpInBuf1, dwInSize1, lpInBuf2, dwInSize2); + } +error2: + + PaUtil_EndCpuLoadMeasurement( &stream->cpuLoadMeasurer, numFrames ); + + } + + return result; +} +/*******************************************************************/ + +static HRESULT ZeroAvailableOutputSpace( PaWinDsStream *stream ) +{ + HRESULT hr; + LPBYTE lpbuf1 = NULL; + LPBYTE lpbuf2 = NULL; + DWORD dwsize1 = 0; + DWORD dwsize2 = 0; + long bytesEmpty; + hr = QueryOutputSpace( stream, &bytesEmpty ); // updates framesPlayed + if (hr != DS_OK) return hr; + if( bytesEmpty == 0 ) return DS_OK; + // Lock free space in the DS + hr = IDirectSoundBuffer_Lock( stream->pDirectSoundOutputBuffer, stream->outputBufferWriteOffsetBytes, + bytesEmpty, (void **) &lpbuf1, &dwsize1, + (void **) &lpbuf2, &dwsize2, 0); + if (hr == DS_OK) + { + // Copy the buffer into the DS + ZeroMemory(lpbuf1, dwsize1); + if(lpbuf2 != NULL) + { + ZeroMemory(lpbuf2, dwsize2); + } + // Update our buffer offset and unlock sound buffer + stream->outputBufferWriteOffsetBytes = (stream->outputBufferWriteOffsetBytes + dwsize1 + dwsize2) % stream->outputBufferSizeBytes; + IDirectSoundBuffer_Unlock( stream->pDirectSoundOutputBuffer, lpbuf1, dwsize1, lpbuf2, dwsize2); + stream->dsw_framesWritten += bytesEmpty / stream->bytesPerOutputFrame; + } + return hr; +} + + +static void CALLBACK Pa_TimerCallback(UINT uID, UINT uMsg, DWORD_PTR dwUser, DWORD dw1, DWORD dw2) +{ + PaWinDsStream *stream; + + /* suppress unused variable warnings */ + (void) uID; + (void) uMsg; + (void) dw1; + (void) dw2; + + stream = (PaWinDsStream *) dwUser; + if( stream == NULL ) return; + + if( stream->isActive ) + { + if( stream->abortProcessing ) + { + stream->isActive = 0; + } + else if( stream->stopProcessing ) + { + if( stream->bufferProcessor.outputChannelCount > 0 ) + { + ZeroAvailableOutputSpace( stream ); + /* clear isActive when all sound played */ + if( stream->framesPlayed >= stream->framesWritten ) + { + stream->isActive = 0; + } + } + else + { + stream->isActive = 0; + } + } + else + { + if( Pa_TimeSlice( stream ) != 0) /* Call time slice independant of timing method. */ + { + /* FIXME implement handling of paComplete and paAbort if possible */ + stream->stopProcessing = 1; + } + } + + if( !stream->isActive ) + { + if( stream->streamRepresentation.streamFinishedCallback != 0 ) + stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData ); + } + } +} + +/*********************************************************************************** + When CloseStream() is called, the multi-api layer ensures that + the stream has already been stopped or aborted. +*/ +static PaError CloseStream( PaStream* s ) +{ + PaError result = paNoError; + PaWinDsStream *stream = (PaWinDsStream*)s; + + // Cleanup the sound buffers + if( stream->pDirectSoundOutputBuffer ) + { + IDirectSoundBuffer_Stop( stream->pDirectSoundOutputBuffer ); + IDirectSoundBuffer_Release( stream->pDirectSoundOutputBuffer ); + stream->pDirectSoundOutputBuffer = NULL; + } + + if( stream->pDirectSoundInputBuffer ) + { + IDirectSoundCaptureBuffer_Stop( stream->pDirectSoundInputBuffer ); + IDirectSoundCaptureBuffer_Release( stream->pDirectSoundInputBuffer ); + stream->pDirectSoundInputBuffer = NULL; + } + + if( stream->pDirectSoundCapture ) + { + IDirectSoundCapture_Release( stream->pDirectSoundCapture ); + stream->pDirectSoundCapture = NULL; + } + + if( stream->pDirectSound ) + { + IDirectSound_Release( stream->pDirectSound ); + stream->pDirectSound = NULL; + } + + PaUtil_TerminateBufferProcessor( &stream->bufferProcessor ); + PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation ); + PaUtil_FreeMemory( stream ); + + return result; +} + +/***********************************************************************************/ +static PaError StartStream( PaStream *s ) +{ + PaError result = paNoError; + PaWinDsStream *stream = (PaWinDsStream*)s; + HRESULT hr; + + PaUtil_ResetBufferProcessor( &stream->bufferProcessor ); + + if( stream->bufferProcessor.inputChannelCount > 0 ) + { + // Start the buffer playback + if( stream->pDirectSoundInputBuffer != NULL ) // FIXME: not sure this check is necessary + { + hr = IDirectSoundCaptureBuffer_Start( stream->pDirectSoundInputBuffer, DSCBSTART_LOOPING ); + } + + DBUG(("StartStream: DSW_StartInput returned = 0x%X.\n", hr)); + if( hr != DS_OK ) + { + result = paUnanticipatedHostError; + PA_DS_SET_LAST_DIRECTSOUND_ERROR( hr ); + goto error; + } + } + + stream->framesWritten = 0; + stream->callbackFlags = 0; + + stream->abortProcessing = 0; + stream->stopProcessing = 0; + stream->isActive = 1; + + if( stream->bufferProcessor.outputChannelCount > 0 ) + { + /* Give user callback a chance to pre-fill buffer. REVIEW - i thought we weren't pre-filling, rb. */ + result = Pa_TimeSlice( stream ); + if( result != paNoError ) return result; // FIXME - what if finished? + + QueryPerformanceCounter( &stream->previousPlayTime ); + stream->previousPlayCursor = 0; + stream->framesPlayed = 0; + hr = IDirectSoundBuffer_SetCurrentPosition( stream->pDirectSoundOutputBuffer, 0 ); + DBUG(("PaHost_StartOutput: IDirectSoundBuffer_SetCurrentPosition returned = 0x%X.\n", hr)); + if( hr != DS_OK ) + { + result = paUnanticipatedHostError; + PA_DS_SET_LAST_DIRECTSOUND_ERROR( hr ); + goto error; + } + + // Start the buffer playback in a loop. + if( stream->pDirectSoundOutputBuffer != NULL ) // FIXME: not sure this needs to be checked here + { + hr = IDirectSoundBuffer_Play( stream->pDirectSoundOutputBuffer, 0, 0, DSBPLAY_LOOPING ); + DBUG(("PaHost_StartOutput: IDirectSoundBuffer_Play returned = 0x%X.\n", hr)); + if( hr != DS_OK ) + { + result = paUnanticipatedHostError; + PA_DS_SET_LAST_DIRECTSOUND_ERROR( hr ); + goto error; + } + stream->outputIsRunning = TRUE; + } + } + + + /* Create timer that will wake us up so we can fill the DSound buffer. */ + { + int resolution; + int framesPerWakeup = stream->framesPerDSBuffer / 4; + int msecPerWakeup = MSEC_PER_SECOND * framesPerWakeup / (int) stream->streamRepresentation.streamInfo.sampleRate; + if( msecPerWakeup < 10 ) msecPerWakeup = 10; + else if( msecPerWakeup > 100 ) msecPerWakeup = 100; + resolution = msecPerWakeup/4; + stream->timerID = timeSetEvent( msecPerWakeup, resolution, (LPTIMECALLBACK) Pa_TimerCallback, + (DWORD_PTR) stream, TIME_PERIODIC ); + } + if( stream->timerID == 0 ) + { + stream->isActive = 0; + result = paUnanticipatedHostError; + PA_DS_SET_LAST_DIRECTSOUND_ERROR( hr ); + goto error; + } + + stream->isStarted = TRUE; + +error: + return result; +} + + +/***********************************************************************************/ +static PaError StopStream( PaStream *s ) +{ + PaError result = paNoError; + PaWinDsStream *stream = (PaWinDsStream*)s; + HRESULT hr; + int timeoutMsec; + + stream->stopProcessing = 1; + /* Set timeout at 20% beyond maximum time we might wait. */ + timeoutMsec = (int) (1200.0 * stream->framesPerDSBuffer / stream->streamRepresentation.streamInfo.sampleRate); + while( stream->isActive && (timeoutMsec > 0) ) + { + Sleep(10); + timeoutMsec -= 10; + } + if( stream->timerID != 0 ) + { + timeKillEvent(stream->timerID); /* Stop callback timer. */ + stream->timerID = 0; + } + + + if( stream->bufferProcessor.outputChannelCount > 0 ) + { + // Stop the buffer playback + if( stream->pDirectSoundOutputBuffer != NULL ) + { + stream->outputIsRunning = FALSE; + // FIXME: what happens if IDirectSoundBuffer_Stop returns an error? + hr = IDirectSoundBuffer_Stop( stream->pDirectSoundOutputBuffer ); + } + } + + if( stream->bufferProcessor.inputChannelCount > 0 ) + { + // Stop the buffer capture + if( stream->pDirectSoundInputBuffer != NULL ) + { + // FIXME: what happens if IDirectSoundCaptureBuffer_Stop returns an error? + hr = IDirectSoundCaptureBuffer_Stop( stream->pDirectSoundInputBuffer ); + } + } + + stream->isStarted = FALSE; + + return result; +} + + +/***********************************************************************************/ +static PaError AbortStream( PaStream *s ) +{ + PaWinDsStream *stream = (PaWinDsStream*)s; + + stream->abortProcessing = 1; + return StopStream( s ); +} + + +/***********************************************************************************/ +static PaError IsStreamStopped( PaStream *s ) +{ + PaWinDsStream *stream = (PaWinDsStream*)s; + + return !stream->isStarted; +} + + +/***********************************************************************************/ +static PaError IsStreamActive( PaStream *s ) +{ + PaWinDsStream *stream = (PaWinDsStream*)s; + + return stream->isActive; +} + +/***********************************************************************************/ +static PaTime GetStreamTime( PaStream *s ) +{ + /* suppress unused variable warnings */ + (void) s; + + return PaUtil_GetTime(); +} + + +/***********************************************************************************/ +static double GetStreamCpuLoad( PaStream* s ) +{ + PaWinDsStream *stream = (PaWinDsStream*)s; + + return PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer ); +} + + +/*********************************************************************************** + As separate stream interfaces are used for blocking and callback + streams, the following functions can be guaranteed to only be called + for blocking streams. +*/ + +static PaError ReadStream( PaStream* s, + void *buffer, + unsigned long frames ) +{ + PaWinDsStream *stream = (PaWinDsStream*)s; + + /* suppress unused variable warnings */ + (void) buffer; + (void) frames; + (void) stream; + + /* IMPLEMENT ME, see portaudio.h for required behavior*/ + + return paNoError; +} + + +/***********************************************************************************/ +static PaError WriteStream( PaStream* s, + const void *buffer, + unsigned long frames ) +{ + PaWinDsStream *stream = (PaWinDsStream*)s; + + /* suppress unused variable warnings */ + (void) buffer; + (void) frames; + (void) stream; + + /* IMPLEMENT ME, see portaudio.h for required behavior*/ + + return paNoError; +} + + +/***********************************************************************************/ +static signed long GetStreamReadAvailable( PaStream* s ) +{ + PaWinDsStream *stream = (PaWinDsStream*)s; + + /* suppress unused variable warnings */ + (void) stream; + + /* IMPLEMENT ME, see portaudio.h for required behavior*/ + + return 0; +} + + +/***********************************************************************************/ +static signed long GetStreamWriteAvailable( PaStream* s ) +{ + PaWinDsStream *stream = (PaWinDsStream*)s; + + /* suppress unused variable warnings */ + (void) stream; + + /* IMPLEMENT ME, see portaudio.h for required behavior*/ + + return 0; +} + + + Index: julius4/libsent/src/adin/pa/hostapi/dsound/pa_win_ds_dynlink.c diff -u /dev/null julius4/libsent/src/adin/pa/hostapi/dsound/pa_win_ds_dynlink.c:1.1 --- /dev/null Sat Feb 5 18:00:03 2011 +++ julius4/libsent/src/adin/pa/hostapi/dsound/pa_win_ds_dynlink.c Sat Feb 5 18:00:02 2011 @@ -0,0 +1,180 @@ +/* + * Interface for dynamically loading directsound and providing a dummy + * implementation if it isn't present. + * + * Author: Ross Bencina (some portions Phil Burk & Robert Marsanyi) + * + * For PortAudio Portable Real-Time Audio Library + * For more information see: http://www.portaudio.com + * Copyright (c) 1999-2006 Phil Burk, Robert Marsanyi and Ross Bencina + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/* + * The text above constitutes the entire PortAudio license; however, + * the PortAudio community also makes the following non-binding requests: + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. It is also + * requested that these non-binding requests be included along with the + * license above. + */ + +/** + @file + @ingroup hostaip_src +*/ + +#include "pa_win_ds_dynlink.h" + +PaWinDsDSoundEntryPoints paWinDsDSoundEntryPoints = { 0, 0, 0, 0, 0, 0, 0 }; + + +static HRESULT WINAPI DummyDllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppv) +{ + (void)rclsid; /* unused parameter */ + (void)riid; /* unused parameter */ + (void)ppv; /* unused parameter */ + return CLASS_E_CLASSNOTAVAILABLE; +} + +static HRESULT WINAPI DummyDirectSoundCreate(LPGUID lpcGuidDevice, LPDIRECTSOUND *ppDS, LPUNKNOWN pUnkOuter) +{ + (void)lpcGuidDevice; /* unused parameter */ + (void)ppDS; /* unused parameter */ + (void)pUnkOuter; /* unused parameter */ + return E_NOTIMPL; +} + +static HRESULT WINAPI DummyDirectSoundEnumerateW(LPDSENUMCALLBACKW lpDSEnumCallback, LPVOID lpContext) +{ + (void)lpDSEnumCallback; /* unused parameter */ + (void)lpContext; /* unused parameter */ + return E_NOTIMPL; +} + +static HRESULT WINAPI DummyDirectSoundEnumerateA(LPDSENUMCALLBACKA lpDSEnumCallback, LPVOID lpContext) +{ + (void)lpDSEnumCallback; /* unused parameter */ + (void)lpContext; /* unused parameter */ + return E_NOTIMPL; +} + +static HRESULT WINAPI DummyDirectSoundCaptureCreate(LPGUID lpcGUID, LPDIRECTSOUNDCAPTURE *lplpDSC, LPUNKNOWN pUnkOuter) +{ + (void)lpcGUID; /* unused parameter */ + (void)lplpDSC; /* unused parameter */ + (void)pUnkOuter; /* unused parameter */ + return E_NOTIMPL; +} + +static HRESULT WINAPI DummyDirectSoundCaptureEnumerateW(LPDSENUMCALLBACKW lpDSCEnumCallback, LPVOID lpContext) +{ + (void)lpDSCEnumCallback; /* unused parameter */ + (void)lpContext; /* unused parameter */ + return E_NOTIMPL; +} + +static HRESULT WINAPI DummyDirectSoundCaptureEnumerateA(LPDSENUMCALLBACKA lpDSCEnumCallback, LPVOID lpContext) +{ + (void)lpDSCEnumCallback; /* unused parameter */ + (void)lpContext; /* unused parameter */ + return E_NOTIMPL; +} + + +void PaWinDs_InitializeDSoundEntryPoints(void) +{ + paWinDsDSoundEntryPoints.hInstance_ = LoadLibrary("dsound.dll"); + if( paWinDsDSoundEntryPoints.hInstance_ != NULL ) + { + paWinDsDSoundEntryPoints.DllGetClassObject = + (HRESULT (WINAPI *)(REFCLSID, REFIID , LPVOID *)) + GetProcAddress( paWinDsDSoundEntryPoints.hInstance_, "DllGetClassObject" ); + if( paWinDsDSoundEntryPoints.DllGetClassObject == NULL ) + paWinDsDSoundEntryPoints.DllGetClassObject = DummyDllGetClassObject; + + paWinDsDSoundEntryPoints.DirectSoundCreate = + (HRESULT (WINAPI *)(LPGUID, LPDIRECTSOUND *, LPUNKNOWN)) + GetProcAddress( paWinDsDSoundEntryPoints.hInstance_, "DirectSoundCreate" ); + if( paWinDsDSoundEntryPoints.DirectSoundCreate == NULL ) + paWinDsDSoundEntryPoints.DirectSoundCreate = DummyDirectSoundCreate; + + paWinDsDSoundEntryPoints.DirectSoundEnumerateW = + (HRESULT (WINAPI *)(LPDSENUMCALLBACKW, LPVOID)) + GetProcAddress( paWinDsDSoundEntryPoints.hInstance_, "DirectSoundEnumerateW" ); + if( paWinDsDSoundEntryPoints.DirectSoundEnumerateW == NULL ) + paWinDsDSoundEntryPoints.DirectSoundEnumerateW = DummyDirectSoundEnumerateW; + + paWinDsDSoundEntryPoints.DirectSoundEnumerateA = + (HRESULT (WINAPI *)(LPDSENUMCALLBACKA, LPVOID)) + GetProcAddress( paWinDsDSoundEntryPoints.hInstance_, "DirectSoundEnumerateA" ); + if( paWinDsDSoundEntryPoints.DirectSoundEnumerateA == NULL ) + paWinDsDSoundEntryPoints.DirectSoundEnumerateA = DummyDirectSoundEnumerateA; + + paWinDsDSoundEntryPoints.DirectSoundCaptureCreate = + (HRESULT (WINAPI *)(LPGUID, LPDIRECTSOUNDCAPTURE *, LPUNKNOWN)) + GetProcAddress( paWinDsDSoundEntryPoints.hInstance_, "DirectSoundCaptureCreate" ); + if( paWinDsDSoundEntryPoints.DirectSoundCaptureCreate == NULL ) + paWinDsDSoundEntryPoints.DirectSoundCaptureCreate = DummyDirectSoundCaptureCreate; + + paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateW = + (HRESULT (WINAPI *)(LPDSENUMCALLBACKW, LPVOID)) + GetProcAddress( paWinDsDSoundEntryPoints.hInstance_, "DirectSoundCaptureEnumerateW" ); + if( paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateW == NULL ) + paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateW = DummyDirectSoundCaptureEnumerateW; + + paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateA = + (HRESULT (WINAPI *)(LPDSENUMCALLBACKA, LPVOID)) + GetProcAddress( paWinDsDSoundEntryPoints.hInstance_, "DirectSoundCaptureEnumerateA" ); + if( paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateA == NULL ) + paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateA = DummyDirectSoundCaptureEnumerateA; + } + else + { + /* initialize with dummy entry points to make live easy when ds isn't present */ + paWinDsDSoundEntryPoints.DirectSoundCreate = DummyDirectSoundCreate; + paWinDsDSoundEntryPoints.DirectSoundEnumerateW = DummyDirectSoundEnumerateW; + paWinDsDSoundEntryPoints.DirectSoundEnumerateA = DummyDirectSoundEnumerateA; + paWinDsDSoundEntryPoints.DirectSoundCaptureCreate = DummyDirectSoundCaptureCreate; + paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateW = DummyDirectSoundCaptureEnumerateW; + paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateA = DummyDirectSoundCaptureEnumerateA; + } +} + + +void PaWinDs_TerminateDSoundEntryPoints(void) +{ + if( paWinDsDSoundEntryPoints.hInstance_ != NULL ) + { + /* ensure that we crash reliably if the entry points arent initialised */ + paWinDsDSoundEntryPoints.DirectSoundCreate = 0; + paWinDsDSoundEntryPoints.DirectSoundEnumerateW = 0; + paWinDsDSoundEntryPoints.DirectSoundEnumerateA = 0; + paWinDsDSoundEntryPoints.DirectSoundCaptureCreate = 0; + paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateW = 0; + paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateA = 0; + + FreeLibrary( paWinDsDSoundEntryPoints.hInstance_ ); + paWinDsDSoundEntryPoints.hInstance_ = NULL; + } +} Index: julius4/libsent/src/adin/pa/hostapi/dsound/pa_win_ds_dynlink.h diff -u /dev/null julius4/libsent/src/adin/pa/hostapi/dsound/pa_win_ds_dynlink.h:1.1 --- /dev/null Sat Feb 5 18:00:03 2011 +++ julius4/libsent/src/adin/pa/hostapi/dsound/pa_win_ds_dynlink.h Sat Feb 5 18:00:02 2011 @@ -0,0 +1,95 @@ +/* + * Interface for dynamically loading directsound and providing a dummy + * implementation if it isn't present. + * + * Author: Ross Bencina (some portions Phil Burk & Robert Marsanyi) + * + * For PortAudio Portable Real-Time Audio Library + * For more information see: http://www.portaudio.com + * Copyright (c) 1999-2006 Phil Burk, Robert Marsanyi and Ross Bencina + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/* + * The text above constitutes the entire PortAudio license; however, + * the PortAudio community also makes the following non-binding requests: + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. It is also + * requested that these non-binding requests be included along with the + * license above. + */ + +/** + @file + @ingroup hostaip_src +*/ + +#ifndef INCLUDED_PA_DSOUND_DYNLINK_H +#define INCLUDED_PA_DSOUND_DYNLINK_H + +/* on Borland compilers, WIN32 doesn't seem to be defined by default, which + breaks dsound.h. Adding the define here fixes the problem. - rossb. */ +#ifdef __BORLANDC__ +#if !defined(WIN32) +#define WIN32 +#endif +#endif + +/* + We are only using DX3 in here, no need to polute the namespace - davidv +*/ +#define DIRECTSOUND_VERSION 0x0300 +#include + +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + + +typedef struct +{ + HINSTANCE hInstance_; + + HRESULT (WINAPI *DllGetClassObject)(REFCLSID , REFIID , LPVOID *); + + HRESULT (WINAPI *DirectSoundCreate)(LPGUID, LPDIRECTSOUND *, LPUNKNOWN); + HRESULT (WINAPI *DirectSoundEnumerateW)(LPDSENUMCALLBACKW, LPVOID); + HRESULT (WINAPI *DirectSoundEnumerateA)(LPDSENUMCALLBACKA, LPVOID); + + HRESULT (WINAPI *DirectSoundCaptureCreate)(LPGUID, LPDIRECTSOUNDCAPTURE *, LPUNKNOWN); + HRESULT (WINAPI *DirectSoundCaptureEnumerateW)(LPDSENUMCALLBACKW, LPVOID); + HRESULT (WINAPI *DirectSoundCaptureEnumerateA)(LPDSENUMCALLBACKA, LPVOID); +}PaWinDsDSoundEntryPoints; + +extern PaWinDsDSoundEntryPoints paWinDsDSoundEntryPoints; + +void PaWinDs_InitializeDSoundEntryPoints(void); +void PaWinDs_TerminateDSoundEntryPoints(void); + + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* INCLUDED_PA_DSOUND_DYNLINK_H */ From sumomo @ users.sourceforge.jp Sat Feb 5 18:00:03 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Sat, 05 Feb 2011 18:00:03 +0900 Subject: [Julius-cvs 592] CVS update: julius4/libsent/src/adin/pa/hostapi/jack Message-ID: <1296896403.185687.28576.nullmailer@users.sourceforge.jp> Index: julius4/libsent/src/adin/pa/hostapi/jack/pa_jack.c diff -u /dev/null julius4/libsent/src/adin/pa/hostapi/jack/pa_jack.c:1.1 --- /dev/null Sat Feb 5 18:00:03 2011 +++ julius4/libsent/src/adin/pa/hostapi/jack/pa_jack.c Sat Feb 5 18:00:03 2011 @@ -0,0 +1,1761 @@ +/* + * $Id: pa_jack.c,v 1.1 2011/02/05 09:00:03 sumomo Exp $ + * PortAudio Portable Real-Time Audio Library + * Latest Version at: http://www.portaudio.com + * JACK Implementation by Joshua Haberman + * + * Copyright (c) 2004 Stefan Westerfeld + * Copyright (c) 2004 Arve Knudsen + * Copyright (c) 2002 Joshua Haberman + * + * Based on the Open Source API proposed by Ross Bencina + * Copyright (c) 1999-2002 Ross Bencina, Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/* + * The text above constitutes the entire PortAudio license; however, + * the PortAudio community also makes the following non-binding requests: + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. It is also + * requested that these non-binding requests be included along with the + * license above. + */ + +/** + @file + @ingroup hostapi_src +*/ + +#include +#include +#include +#include +#include +#include +#include +#include /* EBUSY */ +#include /* sig_atomic_t */ +#include +#include + +#include +#include + +#include "pa_util.h" +#include "pa_hostapi.h" +#include "pa_stream.h" +#include "pa_process.h" +#include "pa_allocation.h" +#include "pa_cpuload.h" +#include "pa_ringbuffer.h" +#include "pa_debugprint.h" + +static int aErr_; +static PaError paErr_; /* For use with ENSURE_PA */ +static pthread_t mainThread_; +static char *jackErr_ = NULL; +static const char* clientName_ = "PortAudio"; + +#define STRINGIZE_HELPER(expr) #expr +#define STRINGIZE(expr) STRINGIZE_HELPER(expr) + +/* Check PaError */ +#define ENSURE_PA(expr) \ + do { \ + if( (paErr_ = (expr)) < paNoError ) \ + { \ + if( (paErr_) == paUnanticipatedHostError && pthread_self() == mainThread_ ) \ + { \ + if (! jackErr_ ) jackErr_ = "unknown error";\ + PaUtil_SetLastHostErrorInfo( paJACK, -1, jackErr_ ); \ + } \ + PaUtil_DebugPrint(( "Expression '" #expr "' failed in '" __FILE__ "', line: " STRINGIZE( __LINE__ ) "\n" )); \ + result = paErr_; \ + goto error; \ + } \ + } while( 0 ) + +#define UNLESS(expr, code) \ + do { \ + if( (expr) == 0 ) \ + { \ + if( (code) == paUnanticipatedHostError && pthread_self() == mainThread_ ) \ + { \ + if (!jackErr_) jackErr_ = "unknown error";\ + PaUtil_SetLastHostErrorInfo( paJACK, -1, jackErr_ ); \ + } \ + PaUtil_DebugPrint(( "Expression '" #expr "' failed in '" __FILE__ "', line: " STRINGIZE( __LINE__ ) "\n" )); \ + result = (code); \ + goto error; \ + } \ + } while( 0 ) + +#define ASSERT_CALL(expr, success) \ + aErr_ = (expr); \ + assert( aErr_ == success ); + +/* + * Functions that directly map to the PortAudio stream interface + */ + +static void Terminate( struct PaUtilHostApiRepresentation *hostApi ); +static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi, + const PaStreamParameters *inputParameters, + const PaStreamParameters *outputParameters, + double sampleRate ); +static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi, + PaStream** s, + const PaStreamParameters *inputParameters, + const PaStreamParameters *outputParameters, + double sampleRate, + unsigned long framesPerBuffer, + PaStreamFlags streamFlags, + PaStreamCallback *streamCallback, + void *userData ); +static PaError CloseStream( PaStream* stream ); +static PaError StartStream( PaStream *stream ); +static PaError StopStream( PaStream *stream ); +static PaError AbortStream( PaStream *stream ); +static PaError IsStreamStopped( PaStream *s ); +static PaError IsStreamActive( PaStream *stream ); +/*static PaTime GetStreamInputLatency( PaStream *stream );*/ +/*static PaTime GetStreamOutputLatency( PaStream *stream );*/ +static PaTime GetStreamTime( PaStream *stream ); +static double GetStreamCpuLoad( PaStream* stream ); + + +/* + * Data specific to this API + */ + +struct PaJackStream; + +typedef struct +{ + PaUtilHostApiRepresentation commonHostApiRep; + PaUtilStreamInterface callbackStreamInterface; + PaUtilStreamInterface blockingStreamInterface; + + PaUtilAllocationGroup *deviceInfoMemory; + + jack_client_t *jack_client; + int jack_buffer_size; + PaHostApiIndex hostApiIndex; + + pthread_mutex_t mtx; + pthread_cond_t cond; + unsigned long inputBase, outputBase; + + /* For dealing with the process thread */ + volatile int xrun; /* Received xrun notification from JACK? */ + struct PaJackStream * volatile toAdd, * volatile toRemove; + struct PaJackStream *processQueue; + volatile sig_atomic_t jackIsDown; +} +PaJackHostApiRepresentation; + +/* PaJackStream - a stream data structure specifically for this implementation */ + +typedef struct PaJackStream +{ + PaUtilStreamRepresentation streamRepresentation; + PaUtilBufferProcessor bufferProcessor; + PaUtilCpuLoadMeasurer cpuLoadMeasurer; + PaJackHostApiRepresentation *hostApi; + + /* our input and output ports */ + jack_port_t **local_input_ports; + jack_port_t **local_output_ports; + + /* the input and output ports of the client we are connecting to */ + jack_port_t **remote_input_ports; + jack_port_t **remote_output_ports; + + int num_incoming_connections; + int num_outgoing_connections; + + jack_client_t *jack_client; + + /* The stream is running if it's still producing samples. + * The stream is active if samples it produced are still being heard. + */ + volatile sig_atomic_t is_running; + volatile sig_atomic_t is_active; + /* Used to signal processing thread that stream should start or stop, respectively */ + volatile sig_atomic_t doStart, doStop, doAbort; + + jack_nframes_t t0; + + PaUtilAllocationGroup *stream_memory; + + /* These are useful in the process callback */ + + int callbackResult; + int isSilenced; + int xrun; + + /* These are useful for the blocking API */ + + int isBlockingStream; + PaUtilRingBuffer inFIFO; + PaUtilRingBuffer outFIFO; + volatile sig_atomic_t data_available; + sem_t data_semaphore; + int bytesPerFrame; + int samplesPerFrame; + + struct PaJackStream *next; +} +PaJackStream; + +#define TRUE 1 +#define FALSE 0 + +/* + * Functions specific to this API + */ + +static int JackCallback( jack_nframes_t frames, void *userData ); + + +/* + * + * Implementation + * + */ + +/* ---- blocking emulation layer ---- */ + +/* Allocate buffer. */ +static PaError BlockingInitFIFO( PaUtilRingBuffer *rbuf, long numFrames, long bytesPerFrame ) +{ + long numBytes = numFrames * bytesPerFrame; + char *buffer = (char *) malloc( numBytes ); + if( buffer == NULL ) return paInsufficientMemory; + memset( buffer, 0, numBytes ); + return (PaError) PaUtil_InitializeRingBuffer( rbuf, numBytes, buffer ); +} + +/* Free buffer. */ +static PaError BlockingTermFIFO( PaUtilRingBuffer *rbuf ) +{ + if( rbuf->buffer ) free( rbuf->buffer ); + rbuf->buffer = NULL; + return paNoError; +} + +static int +BlockingCallback( const void *inputBuffer, + void *outputBuffer, + unsigned long framesPerBuffer, + const PaStreamCallbackTimeInfo* timeInfo, + PaStreamCallbackFlags statusFlags, + void *userData ) +{ + struct PaJackStream *stream = (PaJackStream *)userData; + long numBytes = stream->bytesPerFrame * framesPerBuffer; + + /* This may get called with NULL inputBuffer during initial setup. */ + if( inputBuffer != NULL ) + { + PaUtil_WriteRingBuffer( &stream->inFIFO, inputBuffer, numBytes ); + } + if( outputBuffer != NULL ) + { + int numRead = PaUtil_ReadRingBuffer( &stream->outFIFO, outputBuffer, numBytes ); + /* Zero out remainder of buffer if we run out of data. */ + memset( (char *)outputBuffer + numRead, 0, numBytes - numRead ); + } + + if( !stream->data_available ) + { + stream->data_available = 1; + sem_post( &stream->data_semaphore ); + } + return paContinue; +} + +static PaError +BlockingBegin( PaJackStream *stream, int minimum_buffer_size ) +{ + long doRead = 0; + long doWrite = 0; + PaError result = paNoError; + long numFrames; + + doRead = stream->local_input_ports != NULL; + doWrite = stream->local_output_ports != NULL; + /* */ + stream->samplesPerFrame = 2; + stream->bytesPerFrame = sizeof(float) * stream->samplesPerFrame; + /* */ + numFrames = 32; + while (numFrames < minimum_buffer_size) + numFrames *= 2; + + if( doRead ) + { + ENSURE_PA( BlockingInitFIFO( &stream->inFIFO, numFrames, stream->bytesPerFrame ) ); + } + if( doWrite ) + { + long numBytes; + + ENSURE_PA( BlockingInitFIFO( &stream->outFIFO, numFrames, stream->bytesPerFrame ) ); + + /* Make Write FIFO appear full initially. */ + numBytes = PaUtil_GetRingBufferWriteAvailable( &stream->outFIFO ); + PaUtil_AdvanceRingBufferWriteIndex( &stream->outFIFO, numBytes ); + } + + stream->data_available = 0; + sem_init( &stream->data_semaphore, 0, 0 ); + +error: + return result; +} + +static void +BlockingEnd( PaJackStream *stream ) +{ + BlockingTermFIFO( &stream->inFIFO ); + BlockingTermFIFO( &stream->outFIFO ); + + sem_destroy( &stream->data_semaphore ); +} + +static PaError BlockingReadStream( PaStream* s, void *data, unsigned long numFrames ) +{ + PaError result = paNoError; + PaJackStream *stream = (PaJackStream *)s; + + long bytesRead; + char *p = (char *) data; + long numBytes = stream->bytesPerFrame * numFrames; + while( numBytes > 0 ) + { + bytesRead = PaUtil_ReadRingBuffer( &stream->inFIFO, p, numBytes ); + numBytes -= bytesRead; + p += bytesRead; + if( numBytes > 0 ) + { + /* see write for an explanation */ + if( stream->data_available ) + stream->data_available = 0; + else + sem_wait( &stream->data_semaphore ); + } + } + + return result; +} + +static PaError BlockingWriteStream( PaStream* s, const void *data, unsigned long numFrames ) +{ + PaError result = paNoError; + PaJackStream *stream = (PaJackStream *)s; + long bytesWritten; + char *p = (char *) data; + long numBytes = stream->bytesPerFrame * numFrames; + while( numBytes > 0 ) + { + bytesWritten = PaUtil_WriteRingBuffer( &stream->outFIFO, p, numBytes ); + numBytes -= bytesWritten; + p += bytesWritten; + if( numBytes > 0 ) + { + /* we use the following algorithm: + * (1) write data + * (2) if some data didn't fit into the ringbuffer, set data_available to 0 + * to indicate to the audio that if space becomes available, we want to know + * (3) retry to write data (because it might be that between (1) and (2) + * new space in the buffer became available) + * (4) if this failed, we are sure that the buffer is really empty and + * we will definitely receive a notification when it becomes available + * thus we can safely sleep + * + * if the algorithm bailed out in step (3) before, it leaks a count of 1 + * on the semaphore; however, it doesn't matter, because if we block in (4), + * we also do it in a loop + */ + if( stream->data_available ) + stream->data_available = 0; + else + sem_wait( &stream->data_semaphore ); + } + } + + return result; +} + +static signed long +BlockingGetStreamReadAvailable( PaStream* s ) +{ + PaJackStream *stream = (PaJackStream *)s; + + int bytesFull = PaUtil_GetRingBufferReadAvailable( &stream->inFIFO ); + return bytesFull / stream->bytesPerFrame; +} + +static signed long +BlockingGetStreamWriteAvailable( PaStream* s ) +{ + PaJackStream *stream = (PaJackStream *)s; + + int bytesEmpty = PaUtil_GetRingBufferWriteAvailable( &stream->outFIFO ); + return bytesEmpty / stream->bytesPerFrame; +} + +static PaError +BlockingWaitEmpty( PaStream *s ) +{ + PaJackStream *stream = (PaJackStream *)s; + + while( PaUtil_GetRingBufferReadAvailable( &stream->outFIFO ) > 0 ) + { + stream->data_available = 0; + sem_wait( &stream->data_semaphore ); + } + return 0; +} + +/* ---- jack driver ---- */ + +/* BuildDeviceList(): + * + * The process of determining a list of PortAudio "devices" from + * JACK's client/port system is fairly involved, so it is separated + * into its own routine. + */ + +static PaError BuildDeviceList( PaJackHostApiRepresentation *jackApi ) +{ + /* Utility macros for the repetitive process of allocating memory */ + + /* JACK has no concept of a device. To JACK, there are clients + * which have an arbitrary number of ports. To make this + * intelligible to PortAudio clients, we will group each JACK client + * into a device, and make each port of that client a channel */ + + PaError result = paNoError; + PaUtilHostApiRepresentation *commonApi = &jackApi->commonHostApiRep; + + const char **jack_ports = NULL; + char **client_names = NULL; + char *regex_pattern = NULL; + int port_index, client_index, i; + double globalSampleRate; + regex_t port_regex; + unsigned long numClients = 0, numPorts = 0; + char *tmp_client_name = NULL; + + commonApi->info.defaultInputDevice = paNoDevice; + commonApi->info.defaultOutputDevice = paNoDevice; + commonApi->info.deviceCount = 0; + + /* Parse the list of ports, using a regex to grab the client names */ + ASSERT_CALL( regcomp( &port_regex, "^[^:]*", REG_EXTENDED ), 0 ); + + /* since we are rebuilding the list of devices, free all memory + * associated with the previous list */ + PaUtil_FreeAllAllocations( jackApi->deviceInfoMemory ); + + regex_pattern = PaUtil_GroupAllocateMemory( jackApi->deviceInfoMemory, jack_client_name_size() + 3 ); + tmp_client_name = PaUtil_GroupAllocateMemory( jackApi->deviceInfoMemory, jack_client_name_size() ); + + /* We can only retrieve the list of clients indirectly, by first + * asking for a list of all ports, then parsing the port names + * according to the client_name:port_name convention (which is + * enforced by jackd) + * A: If jack_get_ports returns NULL, there's nothing for us to do */ + UNLESS( (jack_ports = jack_get_ports( jackApi->jack_client, "", "", 0 )) && jack_ports[0], paNoError ); + /* Find number of ports */ + while( jack_ports[numPorts] ) + ++numPorts; + /* At least there will be one port per client :) */ + UNLESS( client_names = PaUtil_GroupAllocateMemory( jackApi->deviceInfoMemory, numPorts * + sizeof (char *) ), paInsufficientMemory ); + + /* Build a list of clients from the list of ports */ + for( numClients = 0, port_index = 0; jack_ports[port_index] != NULL; port_index++ ) + { + int client_seen = FALSE; + regmatch_t match_info; + const char *port = jack_ports[port_index]; + + /* extract the client name from the port name, using a regex + * that parses the clientname:portname syntax */ + UNLESS( !regexec( &port_regex, port, 1, &match_info, 0 ), paInternalError ); + assert(match_info.rm_eo - match_info.rm_so < jack_client_name_size()); + memcpy( tmp_client_name, port + match_info.rm_so, + match_info.rm_eo - match_info.rm_so ); + tmp_client_name[match_info.rm_eo - match_info.rm_so] = '\0'; + + /* do we know about this port's client yet? */ + for( i = 0; i < numClients; i++ ) + { + if( strcmp( tmp_client_name, client_names[i] ) == 0 ) + client_seen = TRUE; + } + + if (client_seen) + continue; /* A: Nothing to see here, move along */ + + UNLESS( client_names[numClients] = (char*)PaUtil_GroupAllocateMemory( jackApi->deviceInfoMemory, + strlen(tmp_client_name) + 1), paInsufficientMemory ); + + /* The alsa_pcm client should go in spot 0. If this + * is the alsa_pcm client AND we are NOT about to put + * it in spot 0 put it in spot 0 and move whatever + * was already in spot 0 to the end. */ + if( strcmp( "alsa_pcm", tmp_client_name ) == 0 && numClients > 0 ) + { + /* alsa_pcm goes in spot 0 */ + strcpy( client_names[ numClients ], client_names[0] ); + strcpy( client_names[0], tmp_client_name ); + } + else + { + /* put the new client at the end of the client list */ + strcpy( client_names[ numClients ], tmp_client_name ); + } + ++numClients; + } + + /* Now we have a list of clients, which will become the list of + * PortAudio devices. */ + + /* there is one global sample rate all clients must conform to */ + + globalSampleRate = jack_get_sample_rate( jackApi->jack_client ); + UNLESS( commonApi->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory( jackApi->deviceInfoMemory, + sizeof(PaDeviceInfo*) * numClients ), paInsufficientMemory ); + + assert( commonApi->info.deviceCount == 0 ); + + /* Create a PaDeviceInfo structure for every client */ + for( client_index = 0; client_index < numClients; client_index++ ) + { + PaDeviceInfo *curDevInfo; + const char **clientPorts = NULL; + + UNLESS( curDevInfo = (PaDeviceInfo*)PaUtil_GroupAllocateMemory( jackApi->deviceInfoMemory, + sizeof(PaDeviceInfo) ), paInsufficientMemory ); + UNLESS( curDevInfo->name = (char*)PaUtil_GroupAllocateMemory( jackApi->deviceInfoMemory, + strlen(client_names[client_index]) + 1 ), paInsufficientMemory ); + strcpy( (char *)curDevInfo->name, client_names[client_index] ); + + curDevInfo->structVersion = 2; + curDevInfo->hostApi = jackApi->hostApiIndex; + + /* JACK is very inflexible: there is one sample rate the whole + * system must run at, and all clients must speak IEEE float. */ + curDevInfo->defaultSampleRate = globalSampleRate; + + /* To determine how many input and output channels are available, + * we re-query jackd with more specific parameters. */ + + sprintf( regex_pattern, "%s:.*", client_names[client_index] ); + + /* ... what are your output ports (that we could input from)? */ + clientPorts = jack_get_ports( jackApi->jack_client, regex_pattern, + NULL, JackPortIsOutput); + curDevInfo->maxInputChannels = 0; + curDevInfo->defaultLowInputLatency = 0.; + curDevInfo->defaultHighInputLatency = 0.; + if( clientPorts ) + { + jack_port_t *p = jack_port_by_name( jackApi->jack_client, clientPorts[0] ); + curDevInfo->defaultLowInputLatency = curDevInfo->defaultHighInputLatency = + jack_port_get_latency( p ) / globalSampleRate; + + for( i = 0; clientPorts[i] != NULL; i++) + { + /* The number of ports returned is the number of output channels. + * We don't care what they are, we just care how many */ + curDevInfo->maxInputChannels++; + } + free(clientPorts); + } + + /* ... what are your input ports (that we could output to)? */ + clientPorts = jack_get_ports( jackApi->jack_client, regex_pattern, + NULL, JackPortIsInput); + curDevInfo->maxOutputChannels = 0; + curDevInfo->defaultLowOutputLatency = 0.; + curDevInfo->defaultHighOutputLatency = 0.; + if( clientPorts ) + { + jack_port_t *p = jack_port_by_name( jackApi->jack_client, clientPorts[0] ); + curDevInfo->defaultLowOutputLatency = curDevInfo->defaultHighOutputLatency = + jack_port_get_latency( p ) / globalSampleRate; + + for( i = 0; clientPorts[i] != NULL; i++) + { + /* The number of ports returned is the number of input channels. + * We don't care what they are, we just care how many */ + curDevInfo->maxOutputChannels++; + } + free(clientPorts); + } + + /* Add this client to the list of devices */ + commonApi->deviceInfos[client_index] = curDevInfo; + ++commonApi->info.deviceCount; + if( commonApi->info.defaultInputDevice == paNoDevice && curDevInfo->maxInputChannels > 0 ) + commonApi->info.defaultInputDevice = client_index; + if( commonApi->info.defaultOutputDevice == paNoDevice && curDevInfo->maxOutputChannels > 0 ) + commonApi->info.defaultOutputDevice = client_index; + } + +error: + regfree( &port_regex ); + free( jack_ports ); + return result; +} + +static void UpdateSampleRate( PaJackStream *stream, double sampleRate ) +{ + /* XXX: Maybe not the cleanest way of going about this? */ + stream->cpuLoadMeasurer.samplingPeriod = stream->bufferProcessor.samplePeriod = 1. / sampleRate; + stream->streamRepresentation.streamInfo.sampleRate = sampleRate; +} + +static void JackErrorCallback( const char *msg ) +{ + if( pthread_self() == mainThread_ ) + { + assert( msg ); + jackErr_ = realloc( jackErr_, strlen( msg ) + 1 ); + strcpy( jackErr_, msg ); + } +} + +static void JackOnShutdown( void *arg ) +{ + PaJackHostApiRepresentation *jackApi = (PaJackHostApiRepresentation *)arg; + PaJackStream *stream = jackApi->processQueue; + + PA_DEBUG(( "%s: JACK server is shutting down\n", __FUNCTION__ )); + for( ; stream; stream = stream->next ) + { + stream->is_active = 0; + } + + /* Make sure that the main thread doesn't get stuck waiting on the condition */ + ASSERT_CALL( pthread_mutex_lock( &jackApi->mtx ), 0 ); + jackApi->jackIsDown = 1; + ASSERT_CALL( pthread_cond_signal( &jackApi->cond ), 0 ); + ASSERT_CALL( pthread_mutex_unlock( &jackApi->mtx ), 0 ); + +} + +static int JackSrCb( jack_nframes_t nframes, void *arg ) +{ + PaJackHostApiRepresentation *jackApi = (PaJackHostApiRepresentation *)arg; + double sampleRate = (double)nframes; + PaJackStream *stream = jackApi->processQueue; + + /* Update all streams in process queue */ + PA_DEBUG(( "%s: Acting on change in JACK samplerate: %f\n", __FUNCTION__, sampleRate )); + for( ; stream; stream = stream->next ) + { + if( stream->streamRepresentation.streamInfo.sampleRate != sampleRate ) + { + PA_DEBUG(( "%s: Updating samplerate\n", __FUNCTION__ )); + UpdateSampleRate( stream, sampleRate ); + } + } + + return 0; +} + +static int JackXRunCb(void *arg) { + PaJackHostApiRepresentation *hostApi = (PaJackHostApiRepresentation *)arg; + assert( hostApi ); + hostApi->xrun = TRUE; + PA_DEBUG(( "%s: JACK signalled xrun\n", __FUNCTION__ )); + return 0; +} + +PaError PaJack_Initialize( PaUtilHostApiRepresentation **hostApi, + PaHostApiIndex hostApiIndex ) +{ + PaError result = paNoError; + PaJackHostApiRepresentation *jackHostApi; + int activated = 0; + jack_status_t jackStatus = 0; + *hostApi = NULL; /* Initialize to NULL */ + + UNLESS( jackHostApi = (PaJackHostApiRepresentation*) + PaUtil_AllocateMemory( sizeof(PaJackHostApiRepresentation) ), paInsufficientMemory ); + UNLESS( jackHostApi->deviceInfoMemory = PaUtil_CreateAllocationGroup(), paInsufficientMemory ); + + mainThread_ = pthread_self(); + ASSERT_CALL( pthread_mutex_init( &jackHostApi->mtx, NULL ), 0 ); + ASSERT_CALL( pthread_cond_init( &jackHostApi->cond, NULL ), 0 ); + + /* Try to become a client of the JACK server. If we cannot do + * this, then this API cannot be used. + * + * Without the JackNoStartServer option, the jackd server is started + * automatically which we do not want. + */ + + jackHostApi->jack_client = jack_client_open( clientName_, JackNoStartServer, &jackStatus ); + if( !jackHostApi->jack_client ) + { + /* the V19 development docs say that if an implementation + * detects that it cannot be used, it should return a NULL + * interface and paNoError */ + PA_DEBUG(( "%s: Couldn't connect to JACK, status: %d\n", __FUNCTION__, jackStatus )); + result = paNoError; + goto error; + } + + jackHostApi->hostApiIndex = hostApiIndex; + + *hostApi = &jackHostApi->commonHostApiRep; + (*hostApi)->info.structVersion = 1; + (*hostApi)->info.type = paJACK; + (*hostApi)->info.name = "JACK Audio Connection Kit"; + + /* Build a device list by querying the JACK server */ + ENSURE_PA( BuildDeviceList( jackHostApi ) ); + + /* Register functions */ + + (*hostApi)->Terminate = Terminate; + (*hostApi)->OpenStream = OpenStream; + (*hostApi)->IsFormatSupported = IsFormatSupported; + + PaUtil_InitializeStreamInterface( &jackHostApi->callbackStreamInterface, + CloseStream, StartStream, + StopStream, AbortStream, + IsStreamStopped, IsStreamActive, + GetStreamTime, GetStreamCpuLoad, + PaUtil_DummyRead, PaUtil_DummyWrite, + PaUtil_DummyGetReadAvailable, + PaUtil_DummyGetWriteAvailable ); + + PaUtil_InitializeStreamInterface( &jackHostApi->blockingStreamInterface, CloseStream, StartStream, + StopStream, AbortStream, IsStreamStopped, IsStreamActive, + GetStreamTime, PaUtil_DummyGetCpuLoad, + BlockingReadStream, BlockingWriteStream, + BlockingGetStreamReadAvailable, BlockingGetStreamWriteAvailable ); + + jackHostApi->inputBase = jackHostApi->outputBase = 0; + jackHostApi->xrun = 0; + jackHostApi->toAdd = jackHostApi->toRemove = NULL; + jackHostApi->processQueue = NULL; + jackHostApi->jackIsDown = 0; + + jack_on_shutdown( jackHostApi->jack_client, JackOnShutdown, jackHostApi ); + jack_set_error_function( JackErrorCallback ); + jackHostApi->jack_buffer_size = jack_get_buffer_size ( jackHostApi->jack_client ); + /* Don't check for error, may not be supported (deprecated in at least jackdmp) */ + jack_set_sample_rate_callback( jackHostApi->jack_client, JackSrCb, jackHostApi ); + UNLESS( !jack_set_xrun_callback( jackHostApi->jack_client, JackXRunCb, jackHostApi ), paUnanticipatedHostError ); + UNLESS( !jack_set_process_callback( jackHostApi->jack_client, JackCallback, jackHostApi ), paUnanticipatedHostError ); + UNLESS( !jack_activate( jackHostApi->jack_client ), paUnanticipatedHostError ); + activated = 1; + + return result; + +error: + if( activated ) + ASSERT_CALL( jack_deactivate( jackHostApi->jack_client ), 0 ); + + if( jackHostApi ) + { + if( jackHostApi->jack_client ) + ASSERT_CALL( jack_client_close( jackHostApi->jack_client ), 0 ); + + if( jackHostApi->deviceInfoMemory ) + { + PaUtil_FreeAllAllocations( jackHostApi->deviceInfoMemory ); + PaUtil_DestroyAllocationGroup( jackHostApi->deviceInfoMemory ); + } + + PaUtil_FreeMemory( jackHostApi ); + } + return result; +} + + +static void Terminate( struct PaUtilHostApiRepresentation *hostApi ) +{ + PaJackHostApiRepresentation *jackHostApi = (PaJackHostApiRepresentation*)hostApi; + + /* note: this automatically disconnects all ports, since a deactivated + * client is not allowed to have any ports connected */ + ASSERT_CALL( jack_deactivate( jackHostApi->jack_client ), 0 ); + + ASSERT_CALL( pthread_mutex_destroy( &jackHostApi->mtx ), 0 ); + ASSERT_CALL( pthread_cond_destroy( &jackHostApi->cond ), 0 ); + + ASSERT_CALL( jack_client_close( jackHostApi->jack_client ), 0 ); + + if( jackHostApi->deviceInfoMemory ) + { + PaUtil_FreeAllAllocations( jackHostApi->deviceInfoMemory ); + PaUtil_DestroyAllocationGroup( jackHostApi->deviceInfoMemory ); + } + + PaUtil_FreeMemory( jackHostApi ); + + free( jackErr_ ); +} + +static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi, + const PaStreamParameters *inputParameters, + const PaStreamParameters *outputParameters, + double sampleRate ) +{ + int inputChannelCount = 0, outputChannelCount = 0; + PaSampleFormat inputSampleFormat, outputSampleFormat; + + if( inputParameters ) + { + inputChannelCount = inputParameters->channelCount; + inputSampleFormat = inputParameters->sampleFormat; + + /* unless alternate device specification is supported, reject the use of + paUseHostApiSpecificDeviceSpecification */ + + if( inputParameters->device == paUseHostApiSpecificDeviceSpecification ) + return paInvalidDevice; + + /* check that input device can support inputChannelCount */ + if( inputChannelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels ) + return paInvalidChannelCount; + + /* validate inputStreamInfo */ + if( inputParameters->hostApiSpecificStreamInfo ) + return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */ + } + else + { + inputChannelCount = 0; + } + + if( outputParameters ) + { + outputChannelCount = outputParameters->channelCount; + outputSampleFormat = outputParameters->sampleFormat; + + /* unless alternate device specification is supported, reject the use of + paUseHostApiSpecificDeviceSpecification */ + + if( outputParameters->device == paUseHostApiSpecificDeviceSpecification ) + return paInvalidDevice; + + /* check that output device can support inputChannelCount */ + if( outputChannelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels ) + return paInvalidChannelCount; + + /* validate outputStreamInfo */ + if( outputParameters->hostApiSpecificStreamInfo ) + return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */ + } + else + { + outputChannelCount = 0; + } + + /* + The following check is not necessary for JACK. + + - if a full duplex stream is requested, check that the combination + of input and output parameters is supported + + + Because the buffer adapter handles conversion between all standard + sample formats, the following checks are only required if paCustomFormat + is implemented, or under some other unusual conditions. + + - check that input device can support inputSampleFormat, or that + we have the capability to convert from outputSampleFormat to + a native format + + - check that output device can support outputSampleFormat, or that + we have the capability to convert from outputSampleFormat to + a native format + */ + + /* check that the device supports sampleRate */ + +#define ABS(x) ( (x) > 0 ? (x) : -(x) ) + if( ABS(sampleRate - jack_get_sample_rate(((PaJackHostApiRepresentation *) hostApi)->jack_client )) > 1 ) + return paInvalidSampleRate; +#undef ABS + + return paFormatIsSupported; +} + +/* Basic stream initialization */ +static PaError InitializeStream( PaJackStream *stream, PaJackHostApiRepresentation *hostApi, int numInputChannels, + int numOutputChannels ) +{ + PaError result = paNoError; + assert( stream ); + + memset( stream, 0, sizeof (PaJackStream) ); + UNLESS( stream->stream_memory = PaUtil_CreateAllocationGroup(), paInsufficientMemory ); + stream->jack_client = hostApi->jack_client; + stream->hostApi = hostApi; + + if( numInputChannels > 0 ) + { + UNLESS( stream->local_input_ports = + (jack_port_t**) PaUtil_GroupAllocateMemory( stream->stream_memory, sizeof(jack_port_t*) * numInputChannels ), + paInsufficientMemory ); + memset( stream->local_input_ports, 0, sizeof(jack_port_t*) * numInputChannels ); + UNLESS( stream->remote_output_ports = + (jack_port_t**) PaUtil_GroupAllocateMemory( stream->stream_memory, sizeof(jack_port_t*) * numInputChannels ), + paInsufficientMemory ); + memset( stream->remote_output_ports, 0, sizeof(jack_port_t*) * numInputChannels ); + } + if( numOutputChannels > 0 ) + { + UNLESS( stream->local_output_ports = + (jack_port_t**) PaUtil_GroupAllocateMemory( stream->stream_memory, sizeof(jack_port_t*) * numOutputChannels ), + paInsufficientMemory ); + memset( stream->local_output_ports, 0, sizeof(jack_port_t*) * numOutputChannels ); + UNLESS( stream->remote_input_ports = + (jack_port_t**) PaUtil_GroupAllocateMemory( stream->stream_memory, sizeof(jack_port_t*) * numOutputChannels ), + paInsufficientMemory ); + memset( stream->remote_input_ports, 0, sizeof(jack_port_t*) * numOutputChannels ); + } + + stream->num_incoming_connections = numInputChannels; + stream->num_outgoing_connections = numOutputChannels; + +error: + return result; +} + +/*! + * Free resources associated with stream, and eventually stream itself. + * + * Frees allocated memory, and closes opened pcms. + */ +static void CleanUpStream( PaJackStream *stream, int terminateStreamRepresentation, int terminateBufferProcessor ) +{ + int i; + assert( stream ); + + if( stream->isBlockingStream ) + BlockingEnd( stream ); + + for( i = 0; i < stream->num_incoming_connections; ++i ) + { + if( stream->local_input_ports[i] ) + ASSERT_CALL( jack_port_unregister( stream->jack_client, stream->local_input_ports[i] ), 0 ); + } + for( i = 0; i < stream->num_outgoing_connections; ++i ) + { + if( stream->local_output_ports[i] ) + ASSERT_CALL( jack_port_unregister( stream->jack_client, stream->local_output_ports[i] ), 0 ); + } + + if( terminateStreamRepresentation ) + PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation ); + if( terminateBufferProcessor ) + PaUtil_TerminateBufferProcessor( &stream->bufferProcessor ); + + if( stream->stream_memory ) + { + PaUtil_FreeAllAllocations( stream->stream_memory ); + PaUtil_DestroyAllocationGroup( stream->stream_memory ); + } + PaUtil_FreeMemory( stream ); +} + +static PaError WaitCondition( PaJackHostApiRepresentation *hostApi ) +{ + PaError result = paNoError; + int err = 0; + PaTime pt = PaUtil_GetTime(); + struct timespec ts; + + ts.tv_sec = (time_t) floor( pt + 1 ); + ts.tv_nsec = (long) ((pt - floor( pt )) * 1000000000); + /* XXX: Best enclose in loop, in case of spurious wakeups? */ + err = pthread_cond_timedwait( &hostApi->cond, &hostApi->mtx, &ts ); + + /* Make sure we didn't time out */ + UNLESS( err != ETIMEDOUT, paTimedOut ); + UNLESS( !err, paInternalError ); + +error: + return result; +} + +static PaError AddStream( PaJackStream *stream ) +{ + PaError result = paNoError; + PaJackHostApiRepresentation *hostApi = stream->hostApi; + /* Add to queue of streams that should be processed */ + ASSERT_CALL( pthread_mutex_lock( &hostApi->mtx ), 0 ); + if( !hostApi->jackIsDown ) + { + hostApi->toAdd = stream; + /* Unlock mutex and await signal from processing thread */ + result = WaitCondition( stream->hostApi ); + } + ASSERT_CALL( pthread_mutex_unlock( &hostApi->mtx ), 0 ); + ENSURE_PA( result ); + + UNLESS( !hostApi->jackIsDown, paDeviceUnavailable ); + +error: + return result; +} + +/* Remove stream from processing queue */ +static PaError RemoveStream( PaJackStream *stream ) +{ + PaError result = paNoError; + PaJackHostApiRepresentation *hostApi = stream->hostApi; + + /* Add to queue over streams that should be processed */ + ASSERT_CALL( pthread_mutex_lock( &hostApi->mtx ), 0 ); + if( !hostApi->jackIsDown ) + { + hostApi->toRemove = stream; + /* Unlock mutex and await signal from processing thread */ + result = WaitCondition( stream->hostApi ); + } + ASSERT_CALL( pthread_mutex_unlock( &hostApi->mtx ), 0 ); + ENSURE_PA( result ); + +error: + return result; +} + +/* Add stream to JACK callback processing queue */ +static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi, + PaStream** s, + const PaStreamParameters *inputParameters, + const PaStreamParameters *outputParameters, + double sampleRate, + unsigned long framesPerBuffer, + PaStreamFlags streamFlags, + PaStreamCallback *streamCallback, + void *userData ) +{ + PaError result = paNoError; + PaJackHostApiRepresentation *jackHostApi = (PaJackHostApiRepresentation*)hostApi; + PaJackStream *stream = NULL; + char *port_string = PaUtil_GroupAllocateMemory( jackHostApi->deviceInfoMemory, jack_port_name_size() ); + unsigned long regexSz = jack_client_name_size() + 3; + char *regex_pattern = PaUtil_GroupAllocateMemory( jackHostApi->deviceInfoMemory, regexSz ); + const char **jack_ports = NULL; + /* int jack_max_buffer_size = jack_get_buffer_size( jackHostApi->jack_client ); */ + int i; + int inputChannelCount, outputChannelCount; + const double jackSr = jack_get_sample_rate( jackHostApi->jack_client ); + PaSampleFormat inputSampleFormat = 0, outputSampleFormat = 0; + int bpInitialized = 0, srInitialized = 0; /* Initialized buffer processor and stream representation? */ + unsigned long ofs; + + /* validate platform specific flags */ + if( (streamFlags & paPlatformSpecificFlags) != 0 ) + return paInvalidFlag; /* unexpected platform specific flag */ + if( (streamFlags & paPrimeOutputBuffersUsingStreamCallback) != 0 ) + { + streamFlags &= ~paPrimeOutputBuffersUsingStreamCallback; + /*return paInvalidFlag;*/ /* This implementation does not support buffer priming */ + } + + if( framesPerBuffer != paFramesPerBufferUnspecified ) + { + /* Jack operates with power of two buffers, and we don't support non-integer buffer adaption (yet) */ + /*UNLESS( !(framesPerBuffer & (framesPerBuffer - 1)), paBufferTooBig );*/ /* TODO: Add descriptive error code? */ + } + + /* Preliminary checks */ + + if( inputParameters ) + { + inputChannelCount = inputParameters->channelCount; + inputSampleFormat = inputParameters->sampleFormat; + + /* unless alternate device specification is supported, reject the use of + paUseHostApiSpecificDeviceSpecification */ + + if( inputParameters->device == paUseHostApiSpecificDeviceSpecification ) + return paInvalidDevice; + + /* check that input device can support inputChannelCount */ + if( inputChannelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels ) + return paInvalidChannelCount; + + /* validate inputStreamInfo */ + if( inputParameters->hostApiSpecificStreamInfo ) + return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */ + } + else + { + inputChannelCount = 0; + } + + if( outputParameters ) + { + outputChannelCount = outputParameters->channelCount; + outputSampleFormat = outputParameters->sampleFormat; + + /* unless alternate device specification is supported, reject the use of + paUseHostApiSpecificDeviceSpecification */ + + if( outputParameters->device == paUseHostApiSpecificDeviceSpecification ) + return paInvalidDevice; + + /* check that output device can support inputChannelCount */ + if( outputChannelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels ) + return paInvalidChannelCount; + + /* validate outputStreamInfo */ + if( outputParameters->hostApiSpecificStreamInfo ) + return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */ + } + else + { + outputChannelCount = 0; + } + + /* ... check that the sample rate exactly matches the ONE acceptable rate + * A: This rate isn't necessarily constant though? */ + +#define ABS(x) ( (x) > 0 ? (x) : -(x) ) + if( ABS(sampleRate - jackSr) > 1 ) + return paInvalidSampleRate; +#undef ABS + + UNLESS( stream = (PaJackStream*)PaUtil_AllocateMemory( sizeof(PaJackStream) ), paInsufficientMemory ); + ENSURE_PA( InitializeStream( stream, jackHostApi, inputChannelCount, outputChannelCount ) ); + + /* the blocking emulation, if necessary */ + stream->isBlockingStream = !streamCallback; + if( stream->isBlockingStream ) + { + float latency = 0.001; /* 1ms is the absolute minimum we support */ + int minimum_buffer_frames = 0; + + if( inputParameters && inputParameters->suggestedLatency > latency ) + latency = inputParameters->suggestedLatency; + else if( outputParameters && outputParameters->suggestedLatency > latency ) + latency = outputParameters->suggestedLatency; + + /* the latency the user asked for indicates the minimum buffer size in frames */ + minimum_buffer_frames = (int) (latency * jack_get_sample_rate( jackHostApi->jack_client )); + + /* we also need to be able to store at least three full jack buffers to avoid dropouts */ + if( jackHostApi->jack_buffer_size * 3 > minimum_buffer_frames ) + minimum_buffer_frames = jackHostApi->jack_buffer_size * 3; + + /* setup blocking API data structures (FIXME: can fail) */ + BlockingBegin( stream, minimum_buffer_frames ); + + /* install our own callback for the blocking API */ + streamCallback = BlockingCallback; + userData = stream; + + PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation, + &jackHostApi->blockingStreamInterface, streamCallback, userData ); + } + else + { + PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation, + &jackHostApi->callbackStreamInterface, streamCallback, userData ); + } + srInitialized = 1; + PaUtil_InitializeCpuLoadMeasurer( &stream->cpuLoadMeasurer, jackSr ); + + /* create the JACK ports. We cannot connect them until audio + * processing begins */ + + /* Register a unique set of ports for this stream + * TODO: Robust allocation of new port names */ + + ofs = jackHostApi->inputBase; + for( i = 0; i < inputChannelCount; i++ ) + { + snprintf( port_string, jack_port_name_size(), "in_%lu", ofs + i ); + UNLESS( stream->local_input_ports[i] = jack_port_register( + jackHostApi->jack_client, port_string, + JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0 ), paInsufficientMemory ); + } + jackHostApi->inputBase += inputChannelCount; + + ofs = jackHostApi->outputBase; + for( i = 0; i < outputChannelCount; i++ ) + { + snprintf( port_string, jack_port_name_size(), "out_%lu", ofs + i ); + UNLESS( stream->local_output_ports[i] = jack_port_register( + jackHostApi->jack_client, port_string, + JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0 ), paInsufficientMemory ); + } + jackHostApi->outputBase += outputChannelCount; + + /* look up the jack_port_t's for the remote ports. We could do + * this at stream start time, but doing it here ensures the + * name lookup only happens once. */ + + if( inputChannelCount > 0 ) + { + int err = 0; + + /* Get output ports of our capture device */ + snprintf( regex_pattern, regexSz, "%s:.*", hostApi->deviceInfos[ inputParameters->device ]->name ); + UNLESS( jack_ports = jack_get_ports( jackHostApi->jack_client, regex_pattern, + NULL, JackPortIsOutput ), paUnanticipatedHostError ); + for( i = 0; i < inputChannelCount && jack_ports[i]; i++ ) + { + if( (stream->remote_output_ports[i] = jack_port_by_name( + jackHostApi->jack_client, jack_ports[i] )) == NULL ) + { + err = 1; + break; + } + } + free( jack_ports ); + UNLESS( !err, paInsufficientMemory ); + + /* Fewer ports than expected? */ + UNLESS( i == inputChannelCount, paInternalError ); + } + + if( outputChannelCount > 0 ) + { + int err = 0; + + /* Get input ports of our playback device */ + snprintf( regex_pattern, regexSz, "%s:.*", hostApi->deviceInfos[ outputParameters->device ]->name ); + UNLESS( jack_ports = jack_get_ports( jackHostApi->jack_client, regex_pattern, + NULL, JackPortIsInput ), paUnanticipatedHostError ); + for( i = 0; i < outputChannelCount && jack_ports[i]; i++ ) + { + if( (stream->remote_input_ports[i] = jack_port_by_name( + jackHostApi->jack_client, jack_ports[i] )) == 0 ) + { + err = 1; + break; + } + } + free( jack_ports ); + UNLESS( !err , paInsufficientMemory ); + + /* Fewer ports than expected? */ + UNLESS( i == outputChannelCount, paInternalError ); + } + + ENSURE_PA( PaUtil_InitializeBufferProcessor( + &stream->bufferProcessor, + inputChannelCount, + inputSampleFormat, + paFloat32, /* hostInputSampleFormat */ + outputChannelCount, + outputSampleFormat, + paFloat32, /* hostOutputSampleFormat */ + jackSr, + streamFlags, + framesPerBuffer, + 0, /* Ignored */ + paUtilUnknownHostBufferSize, /* Buffer size may vary on JACK's discretion */ + streamCallback, + userData ) ); + bpInitialized = 1; + + if( stream->num_incoming_connections > 0 ) + stream->streamRepresentation.streamInfo.inputLatency = (jack_port_get_latency( stream->remote_output_ports[0] ) + - jack_get_buffer_size( jackHostApi->jack_client ) /* One buffer is not counted as latency */ + + PaUtil_GetBufferProcessorInputLatency( &stream->bufferProcessor )) / sampleRate; + if( stream->num_outgoing_connections > 0 ) + stream->streamRepresentation.streamInfo.outputLatency = (jack_port_get_latency( stream->remote_input_ports[0] ) + - jack_get_buffer_size( jackHostApi->jack_client ) /* One buffer is not counted as latency */ + + PaUtil_GetBufferProcessorOutputLatency( &stream->bufferProcessor )) / sampleRate; + + stream->streamRepresentation.streamInfo.sampleRate = jackSr; + stream->t0 = jack_frame_time( jackHostApi->jack_client ); /* A: Time should run from Pa_OpenStream */ + + /* Add to queue of opened streams */ + ENSURE_PA( AddStream( stream ) ); + + *s = (PaStream*)stream; + + return result; + +error: + if( stream ) + CleanUpStream( stream, srInitialized, bpInitialized ); + + return result; +} + +/* + When CloseStream() is called, the multi-api layer ensures that + the stream has already been stopped or aborted. +*/ +static PaError CloseStream( PaStream* s ) +{ + PaError result = paNoError; + PaJackStream *stream = (PaJackStream*)s; + + /* Remove this stream from the processing queue */ + ENSURE_PA( RemoveStream( stream ) ); + +error: + CleanUpStream( stream, 1, 1 ); + return result; +} + +static PaError RealProcess( PaJackStream *stream, jack_nframes_t frames ) +{ + PaError result = paNoError; + PaStreamCallbackTimeInfo timeInfo = {0,0,0}; + int chn; + int framesProcessed; + const double sr = jack_get_sample_rate( stream->jack_client ); /* Shouldn't change during the process callback */ + PaStreamCallbackFlags cbFlags = 0; + + /* If the user has returned !paContinue from the callback we'll want to flush the internal buffers, + * when these are empty we can finally mark the stream as inactive */ + if( stream->callbackResult != paContinue && + PaUtil_IsBufferProcessorOutputEmpty( &stream->bufferProcessor ) ) + { + stream->is_active = 0; + if( stream->streamRepresentation.streamFinishedCallback ) + stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData ); + PA_DEBUG(( "%s: Callback finished\n", __FUNCTION__ )); + + goto end; + } + + timeInfo.currentTime = (jack_frame_time( stream->jack_client ) - stream->t0) / sr; + if( stream->num_incoming_connections > 0 ) + timeInfo.inputBufferAdcTime = timeInfo.currentTime - jack_port_get_latency( stream->remote_output_ports[0] ) + / sr; + if( stream->num_outgoing_connections > 0 ) + timeInfo.outputBufferDacTime = timeInfo.currentTime + jack_port_get_latency( stream->remote_input_ports[0] ) + / sr; + + PaUtil_BeginCpuLoadMeasurement( &stream->cpuLoadMeasurer ); + + if( stream->xrun ) + { + /* XXX: Any way to tell which of these occurred? */ + cbFlags = paOutputUnderflow | paInputOverflow; + stream->xrun = FALSE; + } + PaUtil_BeginBufferProcessing( &stream->bufferProcessor, &timeInfo, + cbFlags ); + + if( stream->num_incoming_connections > 0 ) + PaUtil_SetInputFrameCount( &stream->bufferProcessor, frames ); + if( stream->num_outgoing_connections > 0 ) + PaUtil_SetOutputFrameCount( &stream->bufferProcessor, frames ); + + for( chn = 0; chn < stream->num_incoming_connections; chn++ ) + { + jack_default_audio_sample_t *channel_buf = (jack_default_audio_sample_t*) + jack_port_get_buffer( stream->local_input_ports[chn], + frames ); + + PaUtil_SetNonInterleavedInputChannel( &stream->bufferProcessor, + chn, + channel_buf ); + } + + for( chn = 0; chn < stream->num_outgoing_connections; chn++ ) + { + jack_default_audio_sample_t *channel_buf = (jack_default_audio_sample_t*) + jack_port_get_buffer( stream->local_output_ports[chn], + frames ); + + PaUtil_SetNonInterleavedOutputChannel( &stream->bufferProcessor, + chn, + channel_buf ); + } + + framesProcessed = PaUtil_EndBufferProcessing( &stream->bufferProcessor, + &stream->callbackResult ); + /* We've specified a host buffer size mode where every frame should be consumed by the buffer processor */ + assert( framesProcessed == frames ); + + PaUtil_EndCpuLoadMeasurement( &stream->cpuLoadMeasurer, framesProcessed ); + +end: + return result; +} + +/* Update the JACK callback's stream processing queue. */ +static PaError UpdateQueue( PaJackHostApiRepresentation *hostApi ) +{ + PaError result = paNoError; + int queueModified = 0; + const double jackSr = jack_get_sample_rate( hostApi->jack_client ); + int err; + + if( (err = pthread_mutex_trylock( &hostApi->mtx )) != 0 ) + { + assert( err == EBUSY ); + return paNoError; + } + + if( hostApi->toAdd ) + { + if( hostApi->processQueue ) + { + PaJackStream *node = hostApi->processQueue; + /* Advance to end of queue */ + while( node->next ) + node = node->next; + + node->next = hostApi->toAdd; + } + else + { + /* The only queue entry. */ + hostApi->processQueue = (PaJackStream *)hostApi->toAdd; + } + + /* If necessary, update stream state */ + if( hostApi->toAdd->streamRepresentation.streamInfo.sampleRate != jackSr ) + UpdateSampleRate( hostApi->toAdd, jackSr ); + + hostApi->toAdd = NULL; + queueModified = 1; + } + if( hostApi->toRemove ) + { + int removed = 0; + PaJackStream *node = hostApi->processQueue, *prev = NULL; + assert( hostApi->processQueue ); + + while( node ) + { + if( node == hostApi->toRemove ) + { + if( prev ) + prev->next = node->next; + else + hostApi->processQueue = (PaJackStream *)node->next; + + removed = 1; + break; + } + + prev = node; + node = node->next; + } + UNLESS( removed, paInternalError ); + hostApi->toRemove = NULL; + PA_DEBUG(( "%s: Removed stream from processing queue\n", __FUNCTION__ )); + queueModified = 1; + } + + if( queueModified ) + { + /* Signal that we've done what was asked of us */ + ASSERT_CALL( pthread_cond_signal( &hostApi->cond ), 0 ); + } + +error: + ASSERT_CALL( pthread_mutex_unlock( &hostApi->mtx ), 0 ); + + return result; +} + +/* Audio processing callback invoked periodically from JACK. */ +static int JackCallback( jack_nframes_t frames, void *userData ) +{ + PaError result = paNoError; + PaJackHostApiRepresentation *hostApi = (PaJackHostApiRepresentation *)userData; + PaJackStream *stream = NULL; + int xrun = hostApi->xrun; + hostApi->xrun = 0; + + assert( hostApi ); + + ENSURE_PA( UpdateQueue( hostApi ) ); + + /* Process each stream */ + stream = hostApi->processQueue; + for( ; stream; stream = stream->next ) + { + if( xrun ) /* Don't override if already set */ + stream->xrun = 1; + + /* See if this stream is to be started */ + if( stream->doStart ) + { + /* If we can't obtain a lock, we'll try next time */ + int err = pthread_mutex_trylock( &stream->hostApi->mtx ); + if( !err ) + { + if( stream->doStart ) /* Could potentially change before obtaining the lock */ + { + stream->is_active = 1; + stream->doStart = 0; + PA_DEBUG(( "%s: Starting stream\n", __FUNCTION__ )); + ASSERT_CALL( pthread_cond_signal( &stream->hostApi->cond ), 0 ); + stream->callbackResult = paContinue; + stream->isSilenced = 0; + } + + ASSERT_CALL( pthread_mutex_unlock( &stream->hostApi->mtx ), 0 ); + } + else + assert( err == EBUSY ); + } + else if( stream->doStop || stream->doAbort ) /* Should we stop/abort stream? */ + { + if( stream->callbackResult == paContinue ) /* Ok, make it stop */ + { + PA_DEBUG(( "%s: Stopping stream\n", __FUNCTION__ )); + stream->callbackResult = stream->doStop ? paComplete : paAbort; + } + } + + if( stream->is_active ) + ENSURE_PA( RealProcess( stream, frames ) ); + /* If we have just entered inactive state, silence output */ + if( !stream->is_active && !stream->isSilenced ) + { + int i; + + /* Silence buffer after entering inactive state */ + PA_DEBUG(( "Silencing the output\n" )); + for( i = 0; i < stream->num_outgoing_connections; ++i ) + { + jack_default_audio_sample_t *buffer = jack_port_get_buffer( stream->local_output_ports[i], frames ); + memset( buffer, 0, sizeof (jack_default_audio_sample_t) * frames ); + } + + stream->isSilenced = 1; + } + + if( stream->doStop || stream->doAbort ) + { + /* See if RealProcess has acted on the request */ + if( !stream->is_active ) /* Ok, signal to the main thread that we've carried out the operation */ + { + /* If we can't obtain a lock, we'll try next time */ + int err = pthread_mutex_trylock( &stream->hostApi->mtx ); + if( !err ) + { + stream->doStop = stream->doAbort = 0; + ASSERT_CALL( pthread_cond_signal( &stream->hostApi->cond ), 0 ); + ASSERT_CALL( pthread_mutex_unlock( &stream->hostApi->mtx ), 0 ); + } + else + assert( err == EBUSY ); + } + } + } + + return 0; +error: + return -1; +} + +static PaError StartStream( PaStream *s ) +{ + PaError result = paNoError; + PaJackStream *stream = (PaJackStream*)s; + int i; + + /* Ready the processor */ + PaUtil_ResetBufferProcessor( &stream->bufferProcessor ); + + /* Connect the ports. Note that the ports may already have been connected by someone else in + * the meantime, in which case JACK returns EEXIST. */ + + if( stream->num_incoming_connections > 0 ) + { + for( i = 0; i < stream->num_incoming_connections; i++ ) + { + int r = jack_connect( stream->jack_client, jack_port_name( stream->remote_output_ports[i] ), + jack_port_name( stream->local_input_ports[i] ) ); + UNLESS( 0 == r || EEXIST == r, paUnanticipatedHostError ); + } + } + + if( stream->num_outgoing_connections > 0 ) + { + for( i = 0; i < stream->num_outgoing_connections; i++ ) + { + int r = jack_connect( stream->jack_client, jack_port_name( stream->local_output_ports[i] ), + jack_port_name( stream->remote_input_ports[i] ) ); + UNLESS( 0 == r || EEXIST == r, paUnanticipatedHostError ); + } + } + + stream->xrun = FALSE; + + /* Enable processing */ + + ASSERT_CALL( pthread_mutex_lock( &stream->hostApi->mtx ), 0 ); + stream->doStart = 1; + + /* Wait for stream to be started */ + result = WaitCondition( stream->hostApi ); + /* + do + { + err = pthread_cond_timedwait( &stream->hostApi->cond, &stream->hostApi->mtx, &ts ); + } while( !stream->is_active && !err ); + */ + if( result != paNoError ) /* Something went wrong, call off the stream start */ + { + stream->doStart = 0; + stream->is_active = 0; /* Cancel any processing */ + } + ASSERT_CALL( pthread_mutex_unlock( &stream->hostApi->mtx ), 0 ); + + ENSURE_PA( result ); + + stream->is_running = TRUE; + PA_DEBUG(( "%s: Stream started\n", __FUNCTION__ )); + +error: + return result; +} + +static PaError RealStop( PaJackStream *stream, int abort ) +{ + PaError result = paNoError; + int i; + + if( stream->isBlockingStream ) + BlockingWaitEmpty ( stream ); + + ASSERT_CALL( pthread_mutex_lock( &stream->hostApi->mtx ), 0 ); + if( abort ) + stream->doAbort = 1; + else + stream->doStop = 1; + + /* Wait for stream to be stopped */ + result = WaitCondition( stream->hostApi ); + ASSERT_CALL( pthread_mutex_unlock( &stream->hostApi->mtx ), 0 ); + ENSURE_PA( result ); + + UNLESS( !stream->is_active, paInternalError ); + + PA_DEBUG(( "%s: Stream stopped\n", __FUNCTION__ )); + +error: + stream->is_running = FALSE; + + /* Disconnect ports belonging to this stream */ + + if( !stream->hostApi->jackIsDown ) /* XXX: Well? */ + { + for( i = 0; i < stream->num_incoming_connections; i++ ) + { + if( jack_port_connected( stream->local_input_ports[i] ) ) + { + UNLESS( !jack_port_disconnect( stream->jack_client, stream->local_input_ports[i] ), + paUnanticipatedHostError ); + } + } + for( i = 0; i < stream->num_outgoing_connections; i++ ) + { + if( jack_port_connected( stream->local_output_ports[i] ) ) + { + UNLESS( !jack_port_disconnect( stream->jack_client, stream->local_output_ports[i] ), + paUnanticipatedHostError ); + } + } + } + + return result; +} + +static PaError StopStream( PaStream *s ) +{ + assert(s); + return RealStop( (PaJackStream *)s, 0 ); +} + +static PaError AbortStream( PaStream *s ) +{ + assert(s); + return RealStop( (PaJackStream *)s, 1 ); +} + +static PaError IsStreamStopped( PaStream *s ) +{ + PaJackStream *stream = (PaJackStream*)s; + return !stream->is_running; +} + + +static PaError IsStreamActive( PaStream *s ) +{ + PaJackStream *stream = (PaJackStream*)s; + return stream->is_active; +} + + +static PaTime GetStreamTime( PaStream *s ) +{ + PaJackStream *stream = (PaJackStream*)s; + + /* A: Is this relevant?? --> TODO: what if we're recording-only? */ + return (jack_frame_time( stream->jack_client ) - stream->t0) / (PaTime)jack_get_sample_rate( stream->jack_client ); +} + + +static double GetStreamCpuLoad( PaStream* s ) +{ + PaJackStream *stream = (PaJackStream*)s; + return PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer ); +} + +PaError PaJack_SetClientName( const char* name ) +{ + if( strlen( name ) > jack_client_name_size() ) + { + /* OK, I don't know any better error code */ + return paInvalidFlag; + } + clientName_ = name; + return paNoError; +} + +PaError PaJack_GetClientName(const char** clientName) +{ + PaError result = paNoError; + PaJackHostApiRepresentation* jackHostApi = NULL; + PaJackHostApiRepresentation** ref = &jackHostApi; + ENSURE_PA( PaUtil_GetHostApiRepresentation( (PaUtilHostApiRepresentation**)ref, paJACK ) ); + *clientName = jack_get_client_name( jackHostApi->jack_client ); + +error: + return result; +} From sumomo @ users.sourceforge.jp Sat Feb 5 18:00:02 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Sat, 05 Feb 2011 18:00:02 +0900 Subject: [Julius-cvs 593] CVS update: julius4/libsent/src/adin/pa/hostapi/asihpi Message-ID: <1296896402.768239.28420.nullmailer@users.sourceforge.jp> Index: julius4/libsent/src/adin/pa/hostapi/asihpi/pa_linux_asihpi.c diff -u /dev/null julius4/libsent/src/adin/pa/hostapi/asihpi/pa_linux_asihpi.c:1.1 --- /dev/null Sat Feb 5 18:00:02 2011 +++ julius4/libsent/src/adin/pa/hostapi/asihpi/pa_linux_asihpi.c Sat Feb 5 18:00:02 2011 @@ -0,0 +1,2910 @@ +/* + * PortAudio Portable Real-Time Audio Library + * Latest Version at: http://www.portaudio.com + * + * PortAudio v18 version of AudioScience HPI driver by Fred Gleason + * PortAudio v19 version of AudioScience HPI driver by Ludwig Schwardt + * + * Copyright (c) 2003 Fred Gleason + * Copyright (c) 2005,2006 Ludwig Schwardt + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/* + * The text above constitutes the entire PortAudio license; however, + * the PortAudio community also makes the following non-binding requests: + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. It is also + * requested that these non-binding requests be included along with the + * license above. + */ + +/* + * Modification History + * 12/2003 - Initial version + * 09/2005 - v19 version [rewrite] + */ + +/** @file + @ingroup hostapi_src + @brief Host API implementation supporting AudioScience cards + via the Linux HPI interface. + +

Overview

+ + This is a PortAudio implementation for the AudioScience HPI Audio API + on the Linux platform. AudioScience makes a range of audio adapters customised + for the broadcasting industry, with support for both Windows and Linux. + More information on their products can be found on their website: + + http://www.audioscience.com + + Documentation for the HPI API can be found at: + + http://www.audioscience.com/internet/download/sdk/spchpi.pdf + + The Linux HPI driver itself (a kernel module + library) can be downloaded from: + + http://www.audioscience.com/internet/download/linux_drivers.htm + +

Implementation strategy

+ + *Note* Ideally, AudioScience cards should be handled by the PortAudio ALSA + implementation on Linux, as ALSA is the preferred Linux soundcard API. The existence + of this host API implementation might therefore seem a bit flawed. Unfortunately, at + the time of the creation of this implementation (June 2006), the PA ALSA implementation + could not make use of the existing AudioScience ALSA driver. PA ALSA uses the + "memory-mapped" (mmap) ALSA access mode to interact with the ALSA library, while the + AudioScience ALSA driver only supports the "read-write" access mode. The appropriate + solution to this problem is to add "read-write" support to PortAudio ALSA, thereby + extending the range of soundcards it supports (AudioScience cards are not the only + ones with this problem). Given the author's limited knowledge of ALSA and the + simplicity of the HPI API, the second-best solution was born... + + The following mapping between HPI and PA was followed: + HPI subsystem => PortAudio host API + HPI adapter => nothing specific + HPI stream => PortAudio device + + Each HPI stream is either input or output (not both), and can support + different channel counts, sampling rates and sample formats. It is therefore + a more natural fit to a PA device. A PA stream can therefore combine two + HPI streams (one input and one output) into a "full-duplex" stream. These + HPI streams can even be on different physical adapters. The two streams ought to be + sample-synchronised when they reside on the same adapter, as most AudioScience adapters + derive their ADC and DAC clocks from one master clock. When combining two adapters + into one full-duplex stream, however, the use of a word clock connection between the + adapters is strongly recommended. + + The HPI interface is inherently blocking, making use of read and write calls to + transfer data between user buffers and driver buffers. The callback interface therefore + requires a helper thread ("callback engine") which periodically transfers data (one thread + per PA stream, in fact). The current implementation explicitly sleeps via Pa_Sleep() until + enough samples can be transferred (select() or poll() would be better, but currently seems + impossible...). The thread implementation makes use of the Unix thread helper functions + and some pthread calls here and there. If a unified PA thread exists, this host API + implementation might also compile on Windows, as this is the only real Linux-specific + part of the code. + + There is no inherent fixed buffer size in the HPI interface, as in some other host APIs. + The PortAudio implementation contains a buffer that is allocated during OpenStream and + used to transfer data between the callback and the HPI driver buffer. The size of this + buffer is quite flexible and is derived from latency suggestions and matched to the + requested callback buffer size as far as possible. It can become quite huge, as the + AudioScience cards are typically geared towards higher-latency applications and contain + large hardware buffers. + + The HPI interface natively supports most common sample formats and sample rates (some + conversion is done on the adapter itself). + + Stream time is measured based on the number of processed frames, which is adjusted by the + number of frames currently buffered by the HPI driver. + + There is basic support for detecting overflow and underflow. The HPI interface does not + explicitly indicate this, so thresholds on buffer levels are used in combination with + stream state. Recovery from overflow and underflow is left to the PA client. + + Blocking streams are also implemented. It makes use of the same polling routines that + the callback interface uses, in order to prevent the allocation of variable-sized + buffers during reading and writing. The framesPerBuffer parameter is therefore still + relevant, and this can be increased in the blocking case to improve efficiency. + + The implementation contains extensive reporting macros (slightly modified PA_ENSURE and + PA_UNLESS versions) and a useful stream dump routine to provide debugging feedback. + + Output buffer priming via the user callback (i.e. paPrimeOutputBuffersUsingStreamCallback + and friends) is not implemented yet. All output is primed with silence. + + Please send bug reports etc. to Ludwig Schwardt + */ + +#include +#include +#include +#include /* strlen() */ +#include /* pthreads and friends */ +#include /* assert */ +#include /* ceil, floor */ + +#include /* HPI API */ + +#include "portaudio.h" /* PortAudio API */ +#include "pa_util.h" /* PA_DEBUG, other small utilities */ +#include "pa_unix_util.h" /* Unix threading utilities */ +#include "pa_allocation.h" /* Group memory allocation */ +#include "pa_hostapi.h" /* Host API structs */ +#include "pa_stream.h" /* Stream interface structs */ +#include "pa_cpuload.h" /* CPU load measurer */ +#include "pa_process.h" /* Buffer processor */ +#include "pa_converters.h" /* PaUtilZeroer */ +#include "pa_debugprint.h" + +/* -------------------------------------------------------------------------- */ + +/* + * Defines + */ + +/* Error reporting and assertions */ + +/** Evaluate expression, and return on any PortAudio errors */ +#define PA_ENSURE_(expr) \ + do { \ + PaError paError = (expr); \ + if( UNLIKELY( paError < paNoError ) ) \ + { \ + PA_DEBUG(( "Expression '" #expr "' failed in '" __FILE__ "', line: " STRINGIZE( __LINE__ ) "\n" )); \ + result = paError; \ + goto error; \ + } \ + } while (0); + +/** Assert expression, else return the provided PaError */ +#define PA_UNLESS_(expr, paError) \ + do { \ + if( UNLIKELY( (expr) == 0 ) ) \ + { \ + PA_DEBUG(( "Expression '" #expr "' failed in '" __FILE__ "', line: " STRINGIZE( __LINE__ ) "\n" )); \ + result = (paError); \ + goto error; \ + } \ + } while( 0 ); + +/** Check return value of HPI function, and map it to PaError */ +#define PA_ASIHPI_UNLESS_(expr, paError) \ + do { \ + HW16 hpiError = (expr); \ + /* If HPI error occurred */ \ + if( UNLIKELY( hpiError ) ) \ + { \ + char szError[256]; \ + HPI_GetErrorText( hpiError, szError ); \ + PA_DEBUG(( "HPI error %d occurred: %s\n", hpiError, szError )); \ + /* This message will always be displayed, even if debug info is disabled */ \ + PA_DEBUG(( "Expression '" #expr "' failed in '" __FILE__ "', line: " STRINGIZE( __LINE__ ) "\n" )); \ + if( (paError) == paUnanticipatedHostError ) \ + { \ + PA_DEBUG(( "Host error description: %s\n", szError )); \ + /* PaUtil_SetLastHostErrorInfo should only be used in the main thread */ \ + if( pthread_equal( pthread_self(), paUnixMainThread ) ) \ + { \ + PaUtil_SetLastHostErrorInfo( paInDevelopment, hpiError, szError ); \ + } \ + } \ + /* If paNoError is specified, continue as usual */ \ + /* (useful if you only want to print out the debug messages above) */ \ + if( (paError) < 0 ) \ + { \ + result = (paError); \ + goto error; \ + } \ + } \ + } while( 0 ); + +/** Report HPI error code and text */ +#define PA_ASIHPI_REPORT_ERROR_(hpiErrorCode) \ + do { \ + char szError[256]; \ + HPI_GetErrorText( hpiError, szError ); \ + PA_DEBUG(( "HPI error %d occurred: %s\n", hpiError, szError )); \ + /* PaUtil_SetLastHostErrorInfo should only be used in the main thread */ \ + if( pthread_equal( pthread_self(), paUnixMainThread ) ) \ + { \ + PaUtil_SetLastHostErrorInfo( paInDevelopment, (hpiErrorCode), szError ); \ + } \ + } while( 0 ); + +/* Defaults */ + +/** Sample formats available natively on AudioScience hardware */ +#define PA_ASIHPI_AVAILABLE_FORMATS_ (paFloat32 | paInt32 | paInt24 | paInt16 | paUInt8) +/** Enable background bus mastering (BBM) for buffer transfers, if available (see HPI docs) */ +#define PA_ASIHPI_USE_BBM_ 1 +/** Minimum number of frames in HPI buffer (for either data or available space). + If buffer contains less data/space, it indicates xrun or completion. */ +#define PA_ASIHPI_MIN_FRAMES_ 1152 +/** Minimum polling interval in milliseconds, which determines minimum host buffer size */ +#define PA_ASIHPI_MIN_POLLING_INTERVAL_ 10 + +/* -------------------------------------------------------------------------- */ + +/* + * Structures + */ + +/** Host API global data */ +typedef struct PaAsiHpiHostApiRepresentation +{ + /* PortAudio "base class" - keep the baseRep first! (C-style inheritance) */ + PaUtilHostApiRepresentation baseHostApiRep; + PaUtilStreamInterface callbackStreamInterface; + PaUtilStreamInterface blockingStreamInterface; + + PaUtilAllocationGroup *allocations; + + /* implementation specific data goes here */ + + PaHostApiIndex hostApiIndex; + /** HPI subsystem pointer */ + HPI_HSUBSYS *subSys; +} +PaAsiHpiHostApiRepresentation; + + +/** Device data */ +typedef struct PaAsiHpiDeviceInfo +{ + /* PortAudio "base class" - keep the baseRep first! (C-style inheritance) */ + /** Common PortAudio device information */ + PaDeviceInfo baseDeviceInfo; + + /* implementation specific data goes here */ + + /** HPI subsystem (required for most HPI calls) */ + HPI_HSUBSYS *subSys; + /** Adapter index */ + HW16 adapterIndex; + /** Adapter model number (hex) */ + HW16 adapterType; + /** Adapter HW/SW version */ + HW16 adapterVersion; + /** Adapter serial number */ + HW32 adapterSerialNumber; + /** Stream number */ + HW16 streamIndex; + /** 0=Input, 1=Output (HPI streams are either input or output but not both) */ + HW16 streamIsOutput; +} +PaAsiHpiDeviceInfo; + + +/** Stream state as defined by PortAudio. + It seems that the host API implementation has to keep track of the PortAudio stream state. + Please note that this is NOT the same as the state of the underlying HPI stream. By separating + these two concepts, a lot of flexibility is gained. There is a rough match between the two, + of course, but forcing a precise match is difficult. For example, HPI_STATE_DRAINED can occur + during the Active state of PortAudio (due to underruns) and also during CallBackFinished in + the case of an output stream. Similarly, HPI_STATE_STOPPED mostly coincides with the Stopped + PortAudio state, by may also occur in the CallbackFinished state when recording is finished. + + Here is a rough match-up: + + PortAudio state => HPI state + --------------- --------- + Active => HPI_STATE_RECORDING, HPI_STATE_PLAYING, (HPI_STATE_DRAINED) + Stopped => HPI_STATE_STOPPED + CallbackFinished => HPI_STATE_STOPPED, HPI_STATE_DRAINED */ +typedef enum PaAsiHpiStreamState +{ + paAsiHpiStoppedState=0, + paAsiHpiActiveState=1, + paAsiHpiCallbackFinishedState=2 +} +PaAsiHpiStreamState; + + +/** Stream component data (associated with one direction, i.e. either input or output) */ +typedef struct PaAsiHpiStreamComponent +{ + /** Device information (HPI handles, etc) */ + PaAsiHpiDeviceInfo *hpiDevice; + /** Stream handle, as passed to HPI interface. + HACK: we assume types HPI_HISTREAM and HPI_HOSTREAM are the same... + (both are HW32 up to version 3.00 of ASIHPI, and hopefully they stay that way) */ + HPI_HISTREAM hpiStream; + /** Stream format, as passed to HPI interface */ + HPI_FORMAT hpiFormat; + /** Number of bytes per frame, derived from hpiFormat and saved for convenience */ + HW32 bytesPerFrame; + /** Size of hardware (on-card) buffer of stream in bytes */ + HW32 hardwareBufferSize; + /** Size of host (BBM) buffer of stream in bytes (if used) */ + HW32 hostBufferSize; + /** Upper limit on the utilization of output stream buffer (both hardware and host). + This prevents large latencies in an output-only stream with a potentially huge buffer + and a fast data generator, which would otherwise keep the hardware buffer filled to + capacity. See also the "Hardware Buffering=off" option in the AudioScience WAV driver. */ + HW32 outputBufferCap; + /** Sample buffer (halfway station between HPI and buffer processor) */ + HW8 *tempBuffer; + /** Sample buffer size, in bytes */ + HW32 tempBufferSize; +} +PaAsiHpiStreamComponent; + + +/** Stream data */ +typedef struct PaAsiHpiStream +{ + /* PortAudio "base class" - keep the baseRep first! (C-style inheritance) */ + PaUtilStreamRepresentation baseStreamRep; + PaUtilCpuLoadMeasurer cpuLoadMeasurer; + PaUtilBufferProcessor bufferProcessor; + + PaUtilAllocationGroup *allocations; + + /* implementation specific data goes here */ + + /** Separate structs for input and output sides of stream */ + PaAsiHpiStreamComponent *input, *output; + + /** Polling interval (in milliseconds) */ + HW32 pollingInterval; + /** Are we running in callback mode? */ + int callbackMode; + /** Number of frames to transfer at a time to/from HPI */ + unsigned long maxFramesPerHostBuffer; + /** Indicates that the stream is in the paNeverDropInput mode */ + int neverDropInput; + /** Contains copy of user buffers, used by blocking interface to transfer non-interleaved data. + It went here instead of to each stream component, as the stream component buffer setup in + PaAsiHpi_SetupBuffers doesn't know the stream details such as callbackMode. + (Maybe a problem later if ReadStream and WriteStream happens concurrently on same stream.) */ + void **blockingUserBufferCopy; + + /* Thread-related variables */ + + /** Helper thread which will deliver data to user callback */ + PaUnixThread thread; + /** PortAudio stream state (Active/Stopped/CallbackFinished) */ + volatile sig_atomic_t state; + /** Hard abort, i.e. drop frames? */ + volatile sig_atomic_t callbackAbort; + /** True if stream stopped via exiting callback with paComplete/paAbort flag + (as opposed to explicit call to StopStream/AbortStream) */ + volatile sig_atomic_t callbackFinished; +} +PaAsiHpiStream; + + +/** Stream state information, collected together for convenience */ +typedef struct PaAsiHpiStreamInfo +{ + /** HPI stream state (HPI_STATE_STOPPED, HPI_STATE_PLAYING, etc.) */ + HW16 state; + /** Size (in bytes) of recording/playback data buffer in HPI driver */ + HW32 bufferSize; + /** Amount of data (in bytes) available in the buffer */ + HW32 dataSize; + /** Number of frames played/recorded since last stream reset */ + HW32 frameCounter; + /** Amount of data (in bytes) in hardware (on-card) buffer. + This differs from dataSize if bus mastering (BBM) is used, which introduces another + driver-level buffer to which dataSize/bufferSize then refers. */ + HW32 auxDataSize; + /** Total number of data frames currently buffered by HPI driver (host + hw buffers) */ + HW32 totalBufferedData; + /** Size of immediately available data (for input) or space (for output) in frames. + This only checks the first-level buffer (typically host buffer). This amount can be + transferred immediately. */ + HW32 availableFrames; + /** Indicates that hardware buffer is getting too full */ + int overflow; + /** Indicates that hardware buffer is getting too empty */ + int underflow; +} +PaAsiHpiStreamInfo; + +/* -------------------------------------------------------------------------- */ + +/* + * Function prototypes + */ + +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + + /* The only exposed function in the entire host API implementation */ + PaError PaAsiHpi_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index ); + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +static void Terminate( struct PaUtilHostApiRepresentation *hostApi ); +static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi, + const PaStreamParameters *inputParameters, + const PaStreamParameters *outputParameters, + double sampleRate ); + +/* Stream prototypes */ +static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi, + PaStream **s, + const PaStreamParameters *inputParameters, + const PaStreamParameters *outputParameters, + double sampleRate, + unsigned long framesPerBuffer, + PaStreamFlags streamFlags, + PaStreamCallback *streamCallback, + void *userData ); +static PaError CloseStream( PaStream *s ); +static PaError StartStream( PaStream *s ); +static PaError StopStream( PaStream *s ); +static PaError AbortStream( PaStream *s ); +static PaError IsStreamStopped( PaStream *s ); +static PaError IsStreamActive( PaStream *s ); +static PaTime GetStreamTime( PaStream *s ); +static double GetStreamCpuLoad( PaStream *s ); + +/* Blocking prototypes */ +static PaError ReadStream( PaStream *s, void *buffer, unsigned long frames ); +static PaError WriteStream( PaStream *s, const void *buffer, unsigned long frames ); +static signed long GetStreamReadAvailable( PaStream *s ); +static signed long GetStreamWriteAvailable( PaStream *s ); + +/* Callback prototypes */ +static void *CallbackThreadFunc( void *userData ); + +/* Functions specific to this API */ +static PaError PaAsiHpi_BuildDeviceList( PaAsiHpiHostApiRepresentation *hpiHostApi ); +static HW16 PaAsiHpi_PaToHpiFormat( PaSampleFormat paFormat ); +static PaSampleFormat PaAsiHpi_HpiToPaFormat( HW16 hpiFormat ); +static PaError PaAsiHpi_CreateFormat( struct PaUtilHostApiRepresentation *hostApi, + const PaStreamParameters *parameters, double sampleRate, + PaAsiHpiDeviceInfo **hpiDevice, HPI_FORMAT *hpiFormat ); +static PaError PaAsiHpi_OpenInput( struct PaUtilHostApiRepresentation *hostApi, + const PaAsiHpiDeviceInfo *hpiDevice, const HPI_FORMAT *hpiFormat, + HPI_HISTREAM *hpiStream ); +static PaError PaAsiHpi_OpenOutput( struct PaUtilHostApiRepresentation *hostApi, + const PaAsiHpiDeviceInfo *hpiDevice, const HPI_FORMAT *hpiFormat, + HPI_HOSTREAM *hpiStream ); +static PaError PaAsiHpi_GetStreamInfo( PaAsiHpiStreamComponent *streamComp, PaAsiHpiStreamInfo *info ); +static void PaAsiHpi_StreamComponentDump( PaAsiHpiStreamComponent *streamComp, PaAsiHpiStream *stream ); +static void PaAsiHpi_StreamDump( PaAsiHpiStream *stream ); +static PaError PaAsiHpi_SetupBuffers( PaAsiHpiStreamComponent *streamComp, HW32 pollingInterval, + unsigned long framesPerPaHostBuffer, PaTime suggestedLatency ); +static PaError PaAsiHpi_PrimeOutputWithSilence( PaAsiHpiStream *stream ); +static PaError PaAsiHpi_StartStream( PaAsiHpiStream *stream, int outputPrimed ); +static PaError PaAsiHpi_StopStream( PaAsiHpiStream *stream, int abort ); +static PaError PaAsiHpi_ExplicitStop( PaAsiHpiStream *stream, int abort ); +static void PaAsiHpi_OnThreadExit( void *userData ); +static PaError PaAsiHpi_WaitForFrames( PaAsiHpiStream *stream, unsigned long *framesAvail, + PaStreamCallbackFlags *cbFlags ); +static void PaAsiHpi_CalculateTimeInfo( PaAsiHpiStream *stream, PaStreamCallbackTimeInfo *timeInfo ); +static PaError PaAsiHpi_BeginProcessing( PaAsiHpiStream* stream, unsigned long* numFrames, + PaStreamCallbackFlags *cbFlags ); +static PaError PaAsiHpi_EndProcessing( PaAsiHpiStream *stream, unsigned long numFrames, + PaStreamCallbackFlags *cbFlags ); + +/* ========================================================================== + * ============================= IMPLEMENTATION ============================= + * ========================================================================== */ + +/* --------------------------- Host API Interface --------------------------- */ + +/** Enumerate all PA devices (= HPI streams). + This compiles a list of all HPI adapters, and registers a PA device for each input and + output stream it finds. Most errors are ignored, as missing or erroneous devices are + simply skipped. + + @param hpiHostApi Pointer to HPI host API struct + + @return PortAudio error code (only paInsufficientMemory in practice) + */ +static PaError PaAsiHpi_BuildDeviceList( PaAsiHpiHostApiRepresentation *hpiHostApi ) +{ + PaError result = paNoError; + PaUtilHostApiRepresentation *hostApi = &hpiHostApi->baseHostApiRep; + PaHostApiInfo *baseApiInfo = &hostApi->info; + PaAsiHpiDeviceInfo *hpiDeviceList; + HW16 adapterList[ HPI_MAX_ADAPTERS ]; + HW16 numAdapters; + HW16 hpiError = 0; + int i, j, deviceCount = 0, deviceIndex = 0; + + assert( hpiHostApi ); + assert( hpiHostApi->subSys ); + + /* Look for adapters (not strictly necessary, as AdapterOpen can do the same, but this */ + /* way we have less errors since we do not try to open adapters we know aren't there) */ + /* Errors not considered critical here (subsystem may report 0 devices), but report them */ + /* in debug mode. */ + PA_ASIHPI_UNLESS_( HPI_SubSysFindAdapters( hpiHostApi->subSys, &numAdapters, + adapterList, HPI_MAX_ADAPTERS ), paNoError ); + + /* First open and count the number of devices (= number of streams), to ease memory allocation */ + for( i=0; i < HPI_MAX_ADAPTERS; ++i ) + { + HW16 inStreams, outStreams; + HW16 version; + HW32 serial; + HW16 type; + + /* If no adapter found at this index, skip it */ + if( adapterList[i] == 0 ) + continue; + + /* Try to open adapter */ + hpiError = HPI_AdapterOpen( hpiHostApi->subSys, i ); + /* Report error and skip to next device on failure */ + if( hpiError ) + { + PA_ASIHPI_REPORT_ERROR_( hpiError ); + continue; + } + hpiError = HPI_AdapterGetInfo( hpiHostApi->subSys, i, + &outStreams, &inStreams, &version, &serial, &type ); + /* Skip to next device on failure */ + if( hpiError ) + { + PA_ASIHPI_REPORT_ERROR_( hpiError ); + continue; + } + else + { + /* Assign default devices if available and increment device count */ + if( (baseApiInfo->defaultInputDevice == paNoDevice) && (inStreams > 0) ) + baseApiInfo->defaultInputDevice = deviceCount; + deviceCount += inStreams; + if( (baseApiInfo->defaultOutputDevice == paNoDevice) && (outStreams > 0) ) + baseApiInfo->defaultOutputDevice = deviceCount; + deviceCount += outStreams; + } + } + + /* Register any discovered devices */ + if( deviceCount > 0 ) + { + /* Memory allocation */ + PA_UNLESS_( hostApi->deviceInfos = (PaDeviceInfo**) PaUtil_GroupAllocateMemory( + hpiHostApi->allocations, sizeof(PaDeviceInfo*) * deviceCount ), + paInsufficientMemory ); + /* Allocate all device info structs in a contiguous block */ + PA_UNLESS_( hpiDeviceList = (PaAsiHpiDeviceInfo*) PaUtil_GroupAllocateMemory( + hpiHostApi->allocations, sizeof(PaAsiHpiDeviceInfo) * deviceCount ), + paInsufficientMemory ); + + /* Now query devices again for information */ + for( i=0; i < HPI_MAX_ADAPTERS; ++i ) + { + HW16 inStreams, outStreams; + HW16 version; + HW32 serial; + HW16 type; + + /* If no adapter found at this index, skip it */ + if( adapterList[i] == 0 ) + continue; + + /* Assume adapter is still open from previous round */ + hpiError = HPI_AdapterGetInfo( hpiHostApi->subSys, i, + &outStreams, &inStreams, &version, &serial, &type ); + /* Report error and skip to next device on failure */ + if( hpiError ) + { + PA_ASIHPI_REPORT_ERROR_( hpiError ); + continue; + } + else + { + PA_DEBUG(( "Found HPI Adapter ID=%4X Idx=%d #In=%d #Out=%d S/N=%d HWver=%c%d DSPver=%03d\n", + type, i, inStreams, outStreams, serial, + ((version>>3)&0xf)+'A', /* Hw version major */ + version&0x7, /* Hw version minor */ + ((version>>13)*100)+((version>>7)&0x3f) /* DSP code version */ + )); + } + + /* First add all input streams as devices */ + for( j=0; j < inStreams; ++j ) + { + PaAsiHpiDeviceInfo *hpiDevice = &hpiDeviceList[deviceIndex]; + PaDeviceInfo *baseDeviceInfo = &hpiDevice->baseDeviceInfo; + char srcName[72]; + char *deviceName; + + memset( hpiDevice, 0, sizeof(PaAsiHpiDeviceInfo) ); + /* Set implementation-specific device details */ + hpiDevice->subSys = hpiHostApi->subSys; + hpiDevice->adapterIndex = i; + hpiDevice->adapterType = type; + hpiDevice->adapterVersion = version; + hpiDevice->adapterSerialNumber = serial; + hpiDevice->streamIndex = j; + hpiDevice->streamIsOutput = 0; + /* Set common PortAudio device stats */ + baseDeviceInfo->structVersion = 2; + /* Make sure name string is owned by API info structure */ + sprintf( srcName, + "Adapter %d (%4X) - Input Stream %d", i+1, type, j+1 ); + PA_UNLESS_( deviceName = (char *) PaUtil_GroupAllocateMemory( + hpiHostApi->allocations, strlen(srcName) + 1 ), paInsufficientMemory ); + strcpy( deviceName, srcName ); + baseDeviceInfo->name = deviceName; + baseDeviceInfo->hostApi = hpiHostApi->hostApiIndex; + baseDeviceInfo->maxInputChannels = HPI_MAX_CHANNELS; + baseDeviceInfo->maxOutputChannels = 0; + /* Default latency values for interactive performance */ + baseDeviceInfo->defaultLowInputLatency = 0.01; + baseDeviceInfo->defaultLowOutputLatency = -1.0; + /* Default latency values for robust non-interactive applications (eg. playing sound files) */ + baseDeviceInfo->defaultHighInputLatency = 0.2; + baseDeviceInfo->defaultHighOutputLatency = -1.0; + /* HPI interface can actually handle any sampling rate to 1 Hz accuracy, + * so this default is as good as any */ + baseDeviceInfo->defaultSampleRate = 44100; + + /* Store device in global PortAudio list */ + hostApi->deviceInfos[deviceIndex++] = (PaDeviceInfo *) hpiDevice; + } + + /* Now add all output streams as devices (I know, the repetition is painful) */ + for( j=0; j < outStreams; ++j ) + { + PaAsiHpiDeviceInfo *hpiDevice = &hpiDeviceList[deviceIndex]; + PaDeviceInfo *baseDeviceInfo = &hpiDevice->baseDeviceInfo; + char srcName[72]; + char *deviceName; + + memset( hpiDevice, 0, sizeof(PaAsiHpiDeviceInfo) ); + /* Set implementation-specific device details */ + hpiDevice->subSys = hpiHostApi->subSys; + hpiDevice->adapterIndex = i; + hpiDevice->adapterType = type; + hpiDevice->adapterVersion = version; + hpiDevice->adapterSerialNumber = serial; + hpiDevice->streamIndex = j; + hpiDevice->streamIsOutput = 1; + /* Set common PortAudio device stats */ + baseDeviceInfo->structVersion = 2; + /* Make sure name string is owned by API info structure */ + sprintf( srcName, + "Adapter %d (%4X) - Output Stream %d", i+1, type, j+1 ); + PA_UNLESS_( deviceName = (char *) PaUtil_GroupAllocateMemory( + hpiHostApi->allocations, strlen(srcName) + 1 ), paInsufficientMemory ); + strcpy( deviceName, srcName ); + baseDeviceInfo->name = deviceName; + baseDeviceInfo->hostApi = hpiHostApi->hostApiIndex; + baseDeviceInfo->maxInputChannels = 0; + baseDeviceInfo->maxOutputChannels = HPI_MAX_CHANNELS; + /* Default latency values for interactive performance. */ + baseDeviceInfo->defaultLowInputLatency = -1.0; + baseDeviceInfo->defaultLowOutputLatency = 0.01; + /* Default latency values for robust non-interactive applications (eg. playing sound files). */ + baseDeviceInfo->defaultHighInputLatency = -1.0; + baseDeviceInfo->defaultHighOutputLatency = 0.2; + /* HPI interface can actually handle any sampling rate to 1 Hz accuracy, + * so this default is as good as any */ + baseDeviceInfo->defaultSampleRate = 44100; + + /* Store device in global PortAudio list */ + hostApi->deviceInfos[deviceIndex++] = (PaDeviceInfo *) hpiDevice; + } + } + } + + /* Finally acknowledge checked devices */ + baseApiInfo->deviceCount = deviceIndex; + +error: + return result; +} + + +/** Initialize host API implementation. + This is the only function exported beyond this file. It is called by PortAudio to initialize + the host API. It stores API info, finds and registers all devices, and sets up callback and + blocking interfaces. + + @param hostApi Pointer to host API struct + + @param hostApiIndex Index of current (HPI) host API + + @return PortAudio error code + */ +PaError PaAsiHpi_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex ) +{ + PaError result = paNoError; + PaAsiHpiHostApiRepresentation *hpiHostApi = NULL; + PaHostApiInfo *baseApiInfo; + + /* Allocate host API structure */ + PA_UNLESS_( hpiHostApi = (PaAsiHpiHostApiRepresentation*) PaUtil_AllocateMemory( + sizeof(PaAsiHpiHostApiRepresentation) ), paInsufficientMemory ); + PA_UNLESS_( hpiHostApi->allocations = PaUtil_CreateAllocationGroup(), paInsufficientMemory ); + + hpiHostApi->hostApiIndex = hostApiIndex; + hpiHostApi->subSys = NULL; + + /* Try to initialize HPI subsystem */ + if( ( hpiHostApi->subSys = HPI_SubSysCreate() ) == NULL) + { + /* the V19 development docs say that if an implementation + * detects that it cannot be used, it should return a NULL + * interface and paNoError */ + PA_DEBUG(( "Could not open HPI interface\n" )); + result = paNoError; + *hostApi = NULL; + goto error; + } + else + { + HW32 hpiVersion; + PA_ASIHPI_UNLESS_( HPI_SubSysGetVersion( hpiHostApi->subSys, &hpiVersion ), paUnanticipatedHostError ); + PA_DEBUG(( "HPI interface v%d.%02d\n", + hpiVersion >> 8, 10*((hpiVersion & 0xF0) >> 4) + (hpiVersion & 0x0F) )); + } + + *hostApi = &hpiHostApi->baseHostApiRep; + baseApiInfo = &((*hostApi)->info); + /* Fill in common API details */ + baseApiInfo->structVersion = 1; + baseApiInfo->type = paAudioScienceHPI; + baseApiInfo->name = "AudioScience HPI"; + baseApiInfo->deviceCount = 0; + baseApiInfo->defaultInputDevice = paNoDevice; + baseApiInfo->defaultOutputDevice = paNoDevice; + + PA_ENSURE_( PaAsiHpi_BuildDeviceList( hpiHostApi ) ); + + (*hostApi)->Terminate = Terminate; + (*hostApi)->OpenStream = OpenStream; + (*hostApi)->IsFormatSupported = IsFormatSupported; + + PaUtil_InitializeStreamInterface( &hpiHostApi->callbackStreamInterface, CloseStream, StartStream, + StopStream, AbortStream, IsStreamStopped, IsStreamActive, + GetStreamTime, GetStreamCpuLoad, + PaUtil_DummyRead, PaUtil_DummyWrite, + PaUtil_DummyGetReadAvailable, PaUtil_DummyGetWriteAvailable ); + + PaUtil_InitializeStreamInterface( &hpiHostApi->blockingStreamInterface, CloseStream, StartStream, + StopStream, AbortStream, IsStreamStopped, IsStreamActive, + GetStreamTime, PaUtil_DummyGetCpuLoad, + ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable ); + + /* Store identity of main thread */ + PA_ENSURE_( PaUnixThreading_Initialize() ); + + return result; +error: + /* Clean up memory */ + Terminate( (PaUtilHostApiRepresentation *)hpiHostApi ); + return result; +} + + +/** Terminate host API implementation. + This closes all HPI adapters and frees the HPI subsystem. It also frees the host API struct + memory. It should be called once for every PaAsiHpi_Initialize call. + + @param Pointer to host API struct + */ +static void Terminate( struct PaUtilHostApiRepresentation *hostApi ) +{ + PaAsiHpiHostApiRepresentation *hpiHostApi = (PaAsiHpiHostApiRepresentation*)hostApi; + int i; + PaError result = paNoError; + + if( hpiHostApi ) + { + /* Get rid of HPI-specific structures */ + if( hpiHostApi->subSys ) + { + HW16 lastAdapterIndex = HPI_MAX_ADAPTERS; + /* Iterate through device list and close adapters */ + for( i=0; i < hostApi->info.deviceCount; ++i ) + { + PaAsiHpiDeviceInfo *hpiDevice = (PaAsiHpiDeviceInfo *) hostApi->deviceInfos[ i ]; + /* Close adapter only if it differs from previous one */ + if( hpiDevice->adapterIndex != lastAdapterIndex ) + { + /* Ignore errors (report only during debugging) */ + PA_ASIHPI_UNLESS_( HPI_AdapterClose( hpiHostApi->subSys, + hpiDevice->adapterIndex ), paNoError ); + lastAdapterIndex = hpiDevice->adapterIndex; + } + } + /* Finally dismantle HPI subsystem */ + HPI_SubSysFree( hpiHostApi->subSys ); + } + + if( hpiHostApi->allocations ) + { + PaUtil_FreeAllAllocations( hpiHostApi->allocations ); + PaUtil_DestroyAllocationGroup( hpiHostApi->allocations ); + } + + PaUtil_FreeMemory( hpiHostApi ); + } +error: + return; +} + + +/** Converts PortAudio sample format to equivalent HPI format. + + @param paFormat PortAudio sample format + + @return HPI sample format + */ +static HW16 PaAsiHpi_PaToHpiFormat( PaSampleFormat paFormat ) +{ + /* Ignore interleaving flag */ + switch( paFormat & ~paNonInterleaved ) + { + case paFloat32: + return HPI_FORMAT_PCM32_FLOAT; + + case paInt32: + return HPI_FORMAT_PCM32_SIGNED; + + case paInt24: + return HPI_FORMAT_PCM24_SIGNED; + + case paInt16: + return HPI_FORMAT_PCM16_SIGNED; + + case paUInt8: + return HPI_FORMAT_PCM8_UNSIGNED; + + /* Default is 16-bit signed */ + case paInt8: + default: + return HPI_FORMAT_PCM16_SIGNED; + } +} + + +/** Converts HPI sample format to equivalent PortAudio format. + + @param paFormat HPI sample format + + @return PortAudio sample format + */ +static PaSampleFormat PaAsiHpi_HpiToPaFormat( HW16 hpiFormat ) +{ + switch( hpiFormat ) + { + case HPI_FORMAT_PCM32_FLOAT: + return paFloat32; + + case HPI_FORMAT_PCM32_SIGNED: + return paInt32; + + case HPI_FORMAT_PCM24_SIGNED: + return paInt24; + + case HPI_FORMAT_PCM16_SIGNED: + return paInt16; + + case HPI_FORMAT_PCM8_UNSIGNED: + return paUInt8; + + /* Default is custom format (e.g. for HPI MP3 format) */ + default: + return paCustomFormat; + } +} + + +/** Creates HPI format struct based on PortAudio parameters. + This also does some checks to see whether the desired format is valid, and whether + the device allows it. This only checks the format of one half (input or output) of the + PortAudio stream. + + @param hostApi Pointer to host API struct + + @param parameters Pointer to stream parameter struct + + @param sampleRate Desired sample rate + + @param hpiDevice Pointer to HPI device struct + + @param hpiFormat Resulting HPI format returned here + + @return PortAudio error code (typically indicating a problem with stream format) + */ +static PaError PaAsiHpi_CreateFormat( struct PaUtilHostApiRepresentation *hostApi, + const PaStreamParameters *parameters, double sampleRate, + PaAsiHpiDeviceInfo **hpiDevice, HPI_FORMAT *hpiFormat ) +{ + int maxChannelCount = 0; + PaSampleFormat hostSampleFormat = 0; + HW16 hpiError = 0; + + /* Unless alternate device specification is supported, reject the use of + paUseHostApiSpecificDeviceSpecification */ + if( parameters->device == paUseHostApiSpecificDeviceSpecification ) + return paInvalidDevice; + else + { + assert( parameters->device < hostApi->info.deviceCount ); + *hpiDevice = (PaAsiHpiDeviceInfo*) hostApi->deviceInfos[ parameters->device ]; + } + + /* Validate streamInfo - this implementation doesn't use custom stream info */ + if( parameters->hostApiSpecificStreamInfo ) + return paIncompatibleHostApiSpecificStreamInfo; + + /* Check that device can support channel count */ + if( (*hpiDevice)->streamIsOutput ) + { + maxChannelCount = (*hpiDevice)->baseDeviceInfo.maxOutputChannels; + } + else + { + maxChannelCount = (*hpiDevice)->baseDeviceInfo.maxInputChannels; + } + if( (maxChannelCount == 0) || (parameters->channelCount > maxChannelCount) ) + return paInvalidChannelCount; + + /* All standard sample formats are supported by the buffer adapter, + and this implementation doesn't support any custom sample formats */ + if( parameters->sampleFormat & paCustomFormat ) + return paSampleFormatNotSupported; + + /* Switch to closest HPI native format */ + hostSampleFormat = PaUtil_SelectClosestAvailableFormat(PA_ASIHPI_AVAILABLE_FORMATS_, + parameters->sampleFormat ); + /* Setup format + info objects */ + hpiError = HPI_FormatCreate( hpiFormat, (HW16)parameters->channelCount, + PaAsiHpi_PaToHpiFormat( hostSampleFormat ), + (HW32)sampleRate, 0, 0 ); + if( hpiError ) + { + PA_ASIHPI_REPORT_ERROR_( hpiError ); + switch( hpiError ) + { + case HPI_ERROR_INVALID_FORMAT: + return paSampleFormatNotSupported; + + case HPI_ERROR_INVALID_SAMPLERATE: + case HPI_ERROR_INCOMPATIBLE_SAMPLERATE: + return paInvalidSampleRate; + + case HPI_ERROR_INVALID_CHANNELS: + return paInvalidChannelCount; + } + } + + return paNoError; +} + + +/** Open HPI input stream with given format. + This attempts to open HPI input stream with desired format. If the format is not supported + or the device is unavailable, the stream is closed and a PortAudio error code is returned. + + @param hostApi Pointer to host API struct + + @param hpiDevice Pointer to HPI device struct + + @param hpiFormat Pointer to HPI format struct + + @return PortAudio error code (typically indicating a problem with stream format or device) +*/ +static PaError PaAsiHpi_OpenInput( struct PaUtilHostApiRepresentation *hostApi, + const PaAsiHpiDeviceInfo *hpiDevice, const HPI_FORMAT *hpiFormat, + HPI_HISTREAM *hpiStream ) +{ + PaAsiHpiHostApiRepresentation *hpiHostApi = (PaAsiHpiHostApiRepresentation*)hostApi; + PaError result = paNoError; + HW16 hpiError = 0; + + /* Catch misplaced output devices, as they typically have 0 input channels */ + PA_UNLESS_( !hpiDevice->streamIsOutput, paInvalidChannelCount ); + /* Try to open input stream */ + PA_ASIHPI_UNLESS_( HPI_InStreamOpen( hpiHostApi->subSys, hpiDevice->adapterIndex, + hpiDevice->streamIndex, hpiStream ), paDeviceUnavailable ); + /* Set input format (checking it in the process) */ + /* Could also use HPI_InStreamQueryFormat, but this economizes the process */ + hpiError = HPI_InStreamSetFormat( hpiHostApi->subSys, *hpiStream, (HPI_FORMAT*)hpiFormat ); + if( hpiError ) + { + PA_ASIHPI_REPORT_ERROR_( hpiError ); + PA_ASIHPI_UNLESS_( HPI_InStreamClose( hpiHostApi->subSys, *hpiStream ), paNoError ); + switch( hpiError ) + { + case HPI_ERROR_INVALID_FORMAT: + return paSampleFormatNotSupported; + + case HPI_ERROR_INVALID_SAMPLERATE: + case HPI_ERROR_INCOMPATIBLE_SAMPLERATE: + return paInvalidSampleRate; + + case HPI_ERROR_INVALID_CHANNELS: + return paInvalidChannelCount; + + default: + /* In case anything else went wrong */ + return paInvalidDevice; + } + } + +error: + return result; +} + + +/** Open HPI output stream with given format. + This attempts to open HPI output stream with desired format. If the format is not supported + or the device is unavailable, the stream is closed and a PortAudio error code is returned. + + @param hostApi Pointer to host API struct + + @param hpiDevice Pointer to HPI device struct + + @param hpiFormat Pointer to HPI format struct + + @return PortAudio error code (typically indicating a problem with stream format or device) +*/ +static PaError PaAsiHpi_OpenOutput( struct PaUtilHostApiRepresentation *hostApi, + const PaAsiHpiDeviceInfo *hpiDevice, const HPI_FORMAT *hpiFormat, + HPI_HOSTREAM *hpiStream ) +{ + PaAsiHpiHostApiRepresentation *hpiHostApi = (PaAsiHpiHostApiRepresentation*)hostApi; + PaError result = paNoError; + HW16 hpiError = 0; + + /* Catch misplaced input devices, as they typically have 0 output channels */ + PA_UNLESS_( hpiDevice->streamIsOutput, paInvalidChannelCount ); + /* Try to open output stream */ + PA_ASIHPI_UNLESS_( HPI_OutStreamOpen( hpiHostApi->subSys, hpiDevice->adapterIndex, + hpiDevice->streamIndex, hpiStream ), paDeviceUnavailable ); + + /* Check output format (format is set on first write to output stream) */ + hpiError = HPI_OutStreamQueryFormat( hpiHostApi->subSys, *hpiStream, (HPI_FORMAT*)hpiFormat ); + if( hpiError ) + { + PA_ASIHPI_REPORT_ERROR_( hpiError ); + PA_ASIHPI_UNLESS_( HPI_OutStreamClose( hpiHostApi->subSys, *hpiStream ), paNoError ); + switch( hpiError ) + { + case HPI_ERROR_INVALID_FORMAT: + return paSampleFormatNotSupported; + + case HPI_ERROR_INVALID_SAMPLERATE: + case HPI_ERROR_INCOMPATIBLE_SAMPLERATE: + return paInvalidSampleRate; + + case HPI_ERROR_INVALID_CHANNELS: + return paInvalidChannelCount; + + default: + /* In case anything else went wrong */ + return paInvalidDevice; + } + } + +error: + return result; +} + + +/** Checks whether the desired stream formats and devices are supported + (for both input and output). + This is done by actually opening the appropriate HPI streams and closing them again. + + @param hostApi Pointer to host API struct + + @param inputParameters Pointer to stream parameter struct for input side of stream + + @param outputParameters Pointer to stream parameter struct for output side of stream + + @param sampleRate Desired sample rate + + @return PortAudio error code (paFormatIsSupported on success) + */ +static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi, + const PaStreamParameters *inputParameters, + const PaStreamParameters *outputParameters, + double sampleRate ) +{ + PaError result = paFormatIsSupported; + PaAsiHpiHostApiRepresentation *hpiHostApi = (PaAsiHpiHostApiRepresentation*)hostApi; + PaAsiHpiDeviceInfo *hpiDevice = NULL; + HPI_FORMAT hpiFormat; + + /* Input stream */ + if( inputParameters ) + { + HPI_HISTREAM hpiStream; + PA_DEBUG(( "%s: Checking input params: dev=%d, sr=%d, chans=%d, fmt=%d\n", + __FUNCTION__, inputParameters->device, (int)sampleRate, + inputParameters->channelCount, inputParameters->sampleFormat )); + /* Create and validate format */ + PA_ENSURE_( PaAsiHpi_CreateFormat( hostApi, inputParameters, sampleRate, + &hpiDevice, &hpiFormat ) ); + /* Open stream to further check format */ + PA_ENSURE_( PaAsiHpi_OpenInput( hostApi, hpiDevice, &hpiFormat, &hpiStream ) ); + /* Close stream again */ + PA_ASIHPI_UNLESS_( HPI_InStreamClose( hpiHostApi->subSys, hpiStream ), paNoError ); + } + + /* Output stream */ + if( outputParameters ) + { + HPI_HOSTREAM hpiStream; + PA_DEBUG(( "%s: Checking output params: dev=%d, sr=%d, chans=%d, fmt=%d\n", + __FUNCTION__, outputParameters->device, (int)sampleRate, + outputParameters->channelCount, outputParameters->sampleFormat )); + /* Create and validate format */ + PA_ENSURE_( PaAsiHpi_CreateFormat( hostApi, outputParameters, sampleRate, + &hpiDevice, &hpiFormat ) ); + /* Open stream to further check format */ + PA_ENSURE_( PaAsiHpi_OpenOutput( hostApi, hpiDevice, &hpiFormat, &hpiStream ) ); + /* Close stream again */ + PA_ASIHPI_UNLESS_( HPI_OutStreamClose( hpiHostApi->subSys, hpiStream ), paNoError ); + } + +error: + return result; +} + +/* ---------------------------- Stream Interface ---------------------------- */ + +/** Obtain HPI stream information. + This obtains info such as stream state and available data/space in buffers. It also + estimates whether an underflow or overflow occurred. + + @param streamComp Pointer to stream component (input or output) to query + + @param info Pointer to stream info struct that will contain result + + @return PortAudio error code (either paNoError, paDeviceUnavailable or paUnanticipatedHostError) + */ +static PaError PaAsiHpi_GetStreamInfo( PaAsiHpiStreamComponent *streamComp, PaAsiHpiStreamInfo *info ) +{ + PaError result = paDeviceUnavailable; + HW16 state; + HW32 bufferSize, dataSize, frameCounter, auxDataSize, threshold; + HW32 hwBufferSize, hwDataSize; + + assert( streamComp ); + assert( info ); + + /* First blank the stream info struct, in case something goes wrong below. + This saves the caller from initializing the struct. */ + info->state = 0; + info->bufferSize = 0; + info->dataSize = 0; + info->frameCounter = 0; + info->auxDataSize = 0; + info->totalBufferedData = 0; + info->availableFrames = 0; + info->underflow = 0; + info->overflow = 0; + + if( streamComp->hpiDevice && streamComp->hpiStream ) + { + /* Obtain detailed stream info (either input or output) */ + if( streamComp->hpiDevice->streamIsOutput ) + { + PA_ASIHPI_UNLESS_( HPI_OutStreamGetInfoEx( streamComp->hpiDevice->subSys, + streamComp->hpiStream, + &state, &bufferSize, &dataSize, &frameCounter, + &auxDataSize ), paUnanticipatedHostError ); + } + else + { + PA_ASIHPI_UNLESS_( HPI_InStreamGetInfoEx( streamComp->hpiDevice->subSys, + streamComp->hpiStream, + &state, &bufferSize, &dataSize, &frameCounter, + &auxDataSize ), paUnanticipatedHostError ); + } + /* Load stream info */ + info->state = state; + info->bufferSize = bufferSize; + info->dataSize = dataSize; + info->frameCounter = frameCounter; + info->auxDataSize = auxDataSize; + /* Determine total buffered data */ + info->totalBufferedData = dataSize; + if( streamComp->hostBufferSize > 0 ) + info->totalBufferedData += auxDataSize; + info->totalBufferedData /= streamComp->bytesPerFrame; + /* Determine immediately available frames */ + info->availableFrames = streamComp->hpiDevice->streamIsOutput ? + bufferSize - dataSize : dataSize; + info->availableFrames /= streamComp->bytesPerFrame; + /* Minimum space/data required in buffers */ + threshold = PA_MIN( streamComp->tempBufferSize, + streamComp->bytesPerFrame * PA_ASIHPI_MIN_FRAMES_ ); + /* Obtain hardware buffer stats first, to simplify things */ + hwBufferSize = streamComp->hardwareBufferSize; + hwDataSize = streamComp->hostBufferSize > 0 ? auxDataSize : dataSize; + /* Underflow is a bit tricky */ + info->underflow = streamComp->hpiDevice->streamIsOutput ? + /* Stream seems to start in drained state sometimes, so ignore initial underflow */ + (frameCounter > 0) && ( (state == HPI_STATE_DRAINED) || (hwDataSize == 0) ) : + /* Input streams check the first-level (host) buffer for underflow */ + (state != HPI_STATE_STOPPED) && (dataSize < threshold); + /* Check for overflow in second-level (hardware) buffer for both input and output */ + info->overflow = (state != HPI_STATE_STOPPED) && (hwBufferSize - hwDataSize < threshold); + + return paNoError; + } + +error: + return result; +} + + +/** Display stream component information for debugging purposes. + + @param streamComp Pointer to stream component (input or output) to query + + @param stream Pointer to stream struct which contains the component above + */ +static void PaAsiHpi_StreamComponentDump( PaAsiHpiStreamComponent *streamComp, + PaAsiHpiStream *stream ) +{ + PaAsiHpiStreamInfo streamInfo; + + assert( streamComp ); + assert( stream ); + + /* Name of soundcard/device used by component */ + PA_DEBUG(( "device: %s\n", streamComp->hpiDevice->baseDeviceInfo.name )); + /* Unfortunately some overlap between input and output here */ + if( streamComp->hpiDevice->streamIsOutput ) + { + /* Settings on the user side (as experienced by user callback) */ + PA_DEBUG(( "user: %d-bit, %d ", + 8*stream->bufferProcessor.bytesPerUserOutputSample, + stream->bufferProcessor.outputChannelCount)); + if( stream->bufferProcessor.userOutputIsInterleaved ) + { + PA_DEBUG(( "interleaved channels, " )); + } + else + { + PA_DEBUG(( "non-interleaved channels, " )); + } + PA_DEBUG(( "%d frames/buffer, latency = %5.1f ms\n", + stream->bufferProcessor.framesPerUserBuffer, + 1000*stream->baseStreamRep.streamInfo.outputLatency )); + /* Settings on the host side (internal to PortAudio host API) */ + PA_DEBUG(( "host: %d-bit, %d interleaved channels, %d frames/buffer ", + 8*stream->bufferProcessor.bytesPerHostOutputSample, + stream->bufferProcessor.outputChannelCount, + stream->bufferProcessor.framesPerHostBuffer )); + } + else + { + /* Settings on the user side (as experienced by user callback) */ + PA_DEBUG(( "user: %d-bit, %d ", + 8*stream->bufferProcessor.bytesPerUserInputSample, + stream->bufferProcessor.inputChannelCount)); + if( stream->bufferProcessor.userInputIsInterleaved ) + { + PA_DEBUG(( "interleaved channels, " )); + } + else + { + PA_DEBUG(( "non-interleaved channels, " )); + } + PA_DEBUG(( "%d frames/buffer, latency = %5.1f ms\n", + stream->bufferProcessor.framesPerUserBuffer, + 1000*stream->baseStreamRep.streamInfo.inputLatency )); + /* Settings on the host side (internal to PortAudio host API) */ + PA_DEBUG(( "host: %d-bit, %d interleaved channels, %d frames/buffer ", + 8*stream->bufferProcessor.bytesPerHostInputSample, + stream->bufferProcessor.inputChannelCount, + stream->bufferProcessor.framesPerHostBuffer )); + } + switch( stream->bufferProcessor.hostBufferSizeMode ) + { + case paUtilFixedHostBufferSize: + PA_DEBUG(( "[fixed] " )); + break; + case paUtilBoundedHostBufferSize: + PA_DEBUG(( "[bounded] " )); + break; + case paUtilUnknownHostBufferSize: + PA_DEBUG(( "[unknown] " )); + break; + case paUtilVariableHostBufferSizePartialUsageAllowed: + PA_DEBUG(( "[variable] " )); + break; + } + PA_DEBUG(( "(%d max)\n", streamComp->tempBufferSize / streamComp->bytesPerFrame )); + /* HPI hardware settings */ + PA_DEBUG(( "HPI: adapter %d stream %d, %d-bit, %d-channel, %d Hz\n", + streamComp->hpiDevice->adapterIndex, streamComp->hpiDevice->streamIndex, + 8 * streamComp->bytesPerFrame / streamComp->hpiFormat.wChannels, + streamComp->hpiFormat.wChannels, + streamComp->hpiFormat.dwSampleRate )); + /* Stream state and buffer levels */ + PA_DEBUG(( "HPI: " )); + PaAsiHpi_GetStreamInfo( streamComp, &streamInfo ); + switch( streamInfo.state ) + { + case HPI_STATE_STOPPED: + PA_DEBUG(( "[STOPPED] " )); + break; + case HPI_STATE_PLAYING: + PA_DEBUG(( "[PLAYING] " )); + break; + case HPI_STATE_RECORDING: + PA_DEBUG(( "[RECORDING] " )); + break; + case HPI_STATE_DRAINED: + PA_DEBUG(( "[DRAINED] " )); + break; + default: + PA_DEBUG(( "[unknown state] " )); + break; + } + if( streamComp->hostBufferSize ) + { + PA_DEBUG(( "host = %d/%d B, ", streamInfo.dataSize, streamComp->hostBufferSize )); + PA_DEBUG(( "hw = %d/%d (%d) B, ", streamInfo.auxDataSize, + streamComp->hardwareBufferSize, streamComp->outputBufferCap )); + } + else + { + PA_DEBUG(( "hw = %d/%d B, ", streamInfo.dataSize, streamComp->hardwareBufferSize )); + } + PA_DEBUG(( "count = %d", streamInfo.frameCounter )); + if( streamInfo.overflow ) + { + PA_DEBUG(( " [overflow]" )); + } + else if( streamInfo.underflow ) + { + PA_DEBUG(( " [underflow]" )); + } + PA_DEBUG(( "\n" )); +} + + +/** Display stream information for debugging purposes. + + @param stream Pointer to stream to query + */ +static void PaAsiHpi_StreamDump( PaAsiHpiStream *stream ) +{ + assert( stream ); + + PA_DEBUG(( "\n------------------------- STREAM INFO FOR %p ---------------------------\n", stream )); + /* General stream info (input+output) */ + if( stream->baseStreamRep.streamCallback ) + { + PA_DEBUG(( "[callback] " )); + } + else + { + PA_DEBUG(( "[blocking] " )); + } + PA_DEBUG(( "sr=%d Hz, poll=%d ms, max %d frames/buf ", + (int)stream->baseStreamRep.streamInfo.sampleRate, + stream->pollingInterval, stream->maxFramesPerHostBuffer )); + switch( stream->state ) + { + case paAsiHpiStoppedState: + PA_DEBUG(( "[stopped]\n" )); + break; + case paAsiHpiActiveState: + PA_DEBUG(( "[active]\n" )); + break; + case paAsiHpiCallbackFinishedState: + PA_DEBUG(( "[cb fin]\n" )); + break; + default: + PA_DEBUG(( "[unknown state]\n" )); + break; + } + if( stream->callbackMode ) + { + PA_DEBUG(( "cb info: thread=%p, cbAbort=%d, cbFinished=%d\n", + stream->thread.thread, stream->callbackAbort, stream->callbackFinished )); + } + + PA_DEBUG(( "----------------------------------- Input ------------------------------------\n" )); + if( stream->input ) + { + PaAsiHpi_StreamComponentDump( stream->input, stream ); + } + else + { + PA_DEBUG(( "*none*\n" )); + } + + PA_DEBUG(( "----------------------------------- Output ------------------------------------\n" )); + if( stream->output ) + { + PaAsiHpi_StreamComponentDump( stream->output, stream ); + } + else + { + PA_DEBUG(( "*none*\n" )); + } + PA_DEBUG(( "-------------------------------------------------------------------------------\n\n" )); + +} + + +/** Determine buffer sizes and allocate appropriate stream buffers. + This attempts to allocate a BBM (host) buffer for the HPI stream component (either input + or output, as both have similar buffer needs). Not all AudioScience adapters support BBM, + in which case the hardware buffer has to suffice. The size of the HPI host buffer is chosen + as a multiple of framesPerPaHostBuffer, and also influenced by the suggested latency and the + estimated minimum polling interval. The HPI host and hardware buffer sizes are stored, and an + appropriate cap for the hardware buffer is also calculated. Finally, the temporary stream + buffer which serves as the PortAudio host buffer for this implementation is allocated. + This buffer contains an integer number of user buffers, to simplify buffer adaption in the + buffer processor. The function returns paBufferTooBig if the HPI interface cannot allocate + an HPI host buffer of the desired size. + + @param streamComp Pointer to stream component struct + + @param pollingInterval Polling interval for stream, in milliseconds + + @param framesPerPaHostBuffer Size of PortAudio host buffer, in frames + + @param suggestedLatency Suggested latency for stream component, in seconds + + @return PortAudio error code (possibly paBufferTooBig or paInsufficientMemory) + */ +static PaError PaAsiHpi_SetupBuffers( PaAsiHpiStreamComponent *streamComp, HW32 pollingInterval, + unsigned long framesPerPaHostBuffer, PaTime suggestedLatency ) +{ + PaError result = paNoError; + PaAsiHpiStreamInfo streamInfo; + unsigned long hpiBufferSize = 0, paHostBufferSize = 0; + + assert( streamComp ); + assert( streamComp->hpiDevice ); + + /* Obtain size of hardware buffer of HPI stream, since we will be activating BBM shortly + and afterwards the buffer size will refer to the BBM (host-side) buffer. + This is necessary to enable reliable detection of xruns. */ + PA_ENSURE_( PaAsiHpi_GetStreamInfo( streamComp, &streamInfo ) ); + streamComp->hardwareBufferSize = streamInfo.bufferSize; + hpiBufferSize = streamInfo.bufferSize; + + /* Check if BBM (background bus mastering) is to be enabled */ + if( PA_ASIHPI_USE_BBM_ ) + { + HW32 bbmBufferSize = 0, preLatencyBufferSize = 0; + HW16 hpiError = 0; + PaTime pollingOverhead; + + /* Check overhead of Pa_Sleep() call (minimum sleep duration in ms -> OS dependent) */ + pollingOverhead = PaUtil_GetTime(); + Pa_Sleep( 0 ); + pollingOverhead = 1000*(PaUtil_GetTime() - pollingOverhead); + PA_DEBUG(( "polling overhead = %f ms (length of 0-second sleep)\n", pollingOverhead )); + /* Obtain minimum recommended size for host buffer (in bytes) */ + PA_ASIHPI_UNLESS_( HPI_StreamEstimateBufferSize( &streamComp->hpiFormat, + pollingInterval + (HW32)ceil( pollingOverhead ), + &bbmBufferSize ), paUnanticipatedHostError ); + /* BBM places more stringent requirements on buffer size (see description */ + /* of HPI_StreamEstimateBufferSize in HPI API document) */ + bbmBufferSize *= 3; + /* Make sure the BBM buffer contains multiple PA host buffers */ + if( bbmBufferSize < 3 * streamComp->bytesPerFrame * framesPerPaHostBuffer ) + bbmBufferSize = 3 * streamComp->bytesPerFrame * framesPerPaHostBuffer; + /* Try to honor latency suggested by user by growing buffer (no decrease possible) */ + if( suggestedLatency > 0.0 ) + { + PaTime bufferDuration = ((PaTime)bbmBufferSize) / streamComp->bytesPerFrame + / streamComp->hpiFormat.dwSampleRate; + /* Don't decrease buffer */ + if( bufferDuration < suggestedLatency ) + { + /* Save old buffer size, to be retried if new size proves too big */ + preLatencyBufferSize = bbmBufferSize; + bbmBufferSize = (HW32)ceil( suggestedLatency * streamComp->bytesPerFrame + * streamComp->hpiFormat.dwSampleRate ); + } + } + /* Choose closest memory block boundary (HPI API document states that + "a buffer size of Nx4096 - 20 makes the best use of memory" + (under the entry for HPI_StreamEstimateBufferSize)) */ + bbmBufferSize = ((HW32)ceil((bbmBufferSize + 20)/4096.0))*4096 - 20; + streamComp->hostBufferSize = bbmBufferSize; + /* Allocate BBM host buffer (this enables bus mastering transfers in background) */ + if( streamComp->hpiDevice->streamIsOutput ) + hpiError = HPI_OutStreamHostBufferAllocate( streamComp->hpiDevice->subSys, + streamComp->hpiStream, + bbmBufferSize ); + else + hpiError = HPI_InStreamHostBufferAllocate( streamComp->hpiDevice->subSys, + streamComp->hpiStream, + bbmBufferSize ); + if( hpiError ) + { + PA_ASIHPI_REPORT_ERROR_( hpiError ); + /* Indicate that BBM is disabled */ + streamComp->hostBufferSize = 0; + /* Retry with smaller buffer size (transfers will still work, but not via BBM) */ + if( hpiError == HPI_ERROR_INVALID_DATASIZE ) + { + /* Retry BBM allocation with smaller size if requested latency proved too big */ + if( preLatencyBufferSize > 0 ) + { + PA_DEBUG(( "Retrying BBM allocation with smaller size (%d vs. %d bytes)\n", + preLatencyBufferSize, bbmBufferSize )); + bbmBufferSize = preLatencyBufferSize; + if( streamComp->hpiDevice->streamIsOutput ) + hpiError = HPI_OutStreamHostBufferAllocate( streamComp->hpiDevice->subSys, + streamComp->hpiStream, + bbmBufferSize ); + else + hpiError = HPI_InStreamHostBufferAllocate( streamComp->hpiDevice->subSys, + streamComp->hpiStream, + bbmBufferSize ); + /* Another round of error checking */ + if( hpiError ) + { + PA_ASIHPI_REPORT_ERROR_( hpiError ); + /* No escapes this time */ + if( hpiError == HPI_ERROR_INVALID_DATASIZE ) + { + result = paBufferTooBig; + goto error; + } + else if( hpiError != HPI_ERROR_INVALID_OPERATION ) + { + result = paUnanticipatedHostError; + goto error; + } + } + else + { + streamComp->hostBufferSize = bbmBufferSize; + hpiBufferSize = bbmBufferSize; + } + } + else + { + result = paBufferTooBig; + goto error; + } + } + /* If BBM not supported, foreground transfers will be used, but not a show-stopper */ + /* Anything else is an error */ + else if( hpiError != HPI_ERROR_INVALID_OPERATION ) + { + result = paUnanticipatedHostError; + goto error; + } + } + else + { + hpiBufferSize = bbmBufferSize; + } + } + + /* Final check of buffer size */ + paHostBufferSize = streamComp->bytesPerFrame * framesPerPaHostBuffer; + if( hpiBufferSize < 3*paHostBufferSize ) + { + result = paBufferTooBig; + goto error; + } + /* Set cap on output buffer size, based on latency suggestions */ + if( streamComp->hpiDevice->streamIsOutput ) + { + PaTime latency = suggestedLatency > 0.0 ? suggestedLatency : + streamComp->hpiDevice->baseDeviceInfo.defaultHighOutputLatency; + streamComp->outputBufferCap = + (HW32)ceil( latency * streamComp->bytesPerFrame * streamComp->hpiFormat.dwSampleRate ); + /* The cap should not be too small, to prevent underflow */ + if( streamComp->outputBufferCap < 4*paHostBufferSize ) + streamComp->outputBufferCap = 4*paHostBufferSize; + } + else + { + streamComp->outputBufferCap = 0; + } + /* Temp buffer size should be multiple of PA host buffer size (or 1x, if using fixed blocks) */ + streamComp->tempBufferSize = paHostBufferSize; + /* Allocate temp buffer */ + PA_UNLESS_( streamComp->tempBuffer = (HW8 *)PaUtil_AllocateMemory( streamComp->tempBufferSize ), + paInsufficientMemory ); +error: + return result; +} + + +/** Opens PortAudio stream. + This determines a suitable value for framesPerBuffer, if the user didn't specify it, + based on the suggested latency. It then opens each requested stream direction with the + appropriate stream format, and allocates the required stream buffers. It sets up the + various PortAudio structures dealing with streams, and estimates the stream latency. + + See pa_hostapi.h for a list of validity guarantees made about OpenStream parameters. + + @param hostApi Pointer to host API struct + + @param s List of open streams, where successfully opened stream will go + + @param inputParameters Pointer to stream parameter struct for input side of stream + + @param outputParameters Pointer to stream parameter struct for output side of stream + + @param sampleRate Desired sample rate + + @param framesPerBuffer Desired number of frames per buffer passed to user callback + (or chunk size for blocking stream) + + @param streamFlags Stream flags + + @param streamCallback Pointer to user callback function (zero for blocking interface) + + @param userData Pointer to user data that will be passed to callback function along with data + + @return PortAudio error code +*/ +static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi, + PaStream **s, + const PaStreamParameters *inputParameters, + const PaStreamParameters *outputParameters, + double sampleRate, + unsigned long framesPerBuffer, + PaStreamFlags streamFlags, + PaStreamCallback *streamCallback, + void *userData ) +{ + PaError result = paNoError; + PaAsiHpiHostApiRepresentation *hpiHostApi = (PaAsiHpiHostApiRepresentation*)hostApi; + PaAsiHpiStream *stream = NULL; + unsigned long framesPerHostBuffer = framesPerBuffer; + int inputChannelCount = 0, outputChannelCount = 0; + PaSampleFormat inputSampleFormat = 0, outputSampleFormat = 0; + PaSampleFormat hostInputSampleFormat = 0, hostOutputSampleFormat = 0; + PaTime maxSuggestedLatency = 0.0; + + /* Validate platform-specific flags -> none expected for HPI */ + if( (streamFlags & paPlatformSpecificFlags) != 0 ) + return paInvalidFlag; /* unexpected platform-specific flag */ + + /* Create blank stream structure */ + PA_UNLESS_( stream = (PaAsiHpiStream *)PaUtil_AllocateMemory( sizeof(PaAsiHpiStream) ), + paInsufficientMemory ); + memset( stream, 0, sizeof(PaAsiHpiStream) ); + + /* If the number of frames per buffer is unspecified, we have to come up with one. */ + if( framesPerHostBuffer == paFramesPerBufferUnspecified ) + { + if( inputParameters ) + maxSuggestedLatency = inputParameters->suggestedLatency; + if( outputParameters && (outputParameters->suggestedLatency > maxSuggestedLatency) ) + maxSuggestedLatency = outputParameters->suggestedLatency; + /* Use suggested latency if available */ + if( maxSuggestedLatency > 0.0 ) + framesPerHostBuffer = (unsigned long)ceil( maxSuggestedLatency * sampleRate ); + else + /* AudioScience cards like BIG buffers by default */ + framesPerHostBuffer = 4096; + } + /* Lower bounds on host buffer size, due to polling and HPI constraints */ + if( 1000.0*framesPerHostBuffer/sampleRate < PA_ASIHPI_MIN_POLLING_INTERVAL_ ) + framesPerHostBuffer = (unsigned long)ceil( sampleRate * PA_ASIHPI_MIN_POLLING_INTERVAL_ / 1000.0 ); + /* if( framesPerHostBuffer < PA_ASIHPI_MIN_FRAMES_ ) + framesPerHostBuffer = PA_ASIHPI_MIN_FRAMES_; */ + /* Efficient if host buffer size is integer multiple of user buffer size */ + if( framesPerBuffer > 0 ) + framesPerHostBuffer = (unsigned long)ceil( (double)framesPerHostBuffer / framesPerBuffer ) * framesPerBuffer; + /* Buffer should always be a multiple of 4 bytes to facilitate 32-bit PCI transfers. + By keeping the frames a multiple of 4, this is ensured even for 8-bit mono sound. */ + framesPerHostBuffer = (framesPerHostBuffer / 4) * 4; + /* Polling is based on time length (in milliseconds) of user-requested block size */ + stream->pollingInterval = (HW32)ceil( 1000.0*framesPerHostBuffer/sampleRate ); + assert( framesPerHostBuffer > 0 ); + + /* Open underlying streams, check formats and allocate buffers */ + if( inputParameters ) + { + /* Create blank stream component structure */ + PA_UNLESS_( stream->input = (PaAsiHpiStreamComponent *)PaUtil_AllocateMemory( sizeof(PaAsiHpiStreamComponent) ), + paInsufficientMemory ); + memset( stream->input, 0, sizeof(PaAsiHpiStreamComponent) ); + /* Create/validate format */ + PA_ENSURE_( PaAsiHpi_CreateFormat( hostApi, inputParameters, sampleRate, + &stream->input->hpiDevice, &stream->input->hpiFormat ) ); + /* Open stream and set format */ + PA_ENSURE_( PaAsiHpi_OpenInput( hostApi, stream->input->hpiDevice, &stream->input->hpiFormat, + &stream->input->hpiStream ) ); + inputChannelCount = inputParameters->channelCount; + inputSampleFormat = inputParameters->sampleFormat; + hostInputSampleFormat = PaAsiHpi_HpiToPaFormat( stream->input->hpiFormat.wFormat ); + stream->input->bytesPerFrame = inputChannelCount * Pa_GetSampleSize( hostInputSampleFormat ); + assert( stream->input->bytesPerFrame > 0 ); + /* Allocate host and temp buffers of appropriate size */ + PA_ENSURE_( PaAsiHpi_SetupBuffers( stream->input, stream->pollingInterval, + framesPerHostBuffer, inputParameters->suggestedLatency ) ); + } + if( outputParameters ) + { + /* Create blank stream component structure */ + PA_UNLESS_( stream->output = (PaAsiHpiStreamComponent *)PaUtil_AllocateMemory( sizeof(PaAsiHpiStreamComponent) ), + paInsufficientMemory ); + memset( stream->output, 0, sizeof(PaAsiHpiStreamComponent) ); + /* Create/validate format */ + PA_ENSURE_( PaAsiHpi_CreateFormat( hostApi, outputParameters, sampleRate, + &stream->output->hpiDevice, &stream->output->hpiFormat ) ); + /* Open stream and check format */ + PA_ENSURE_( PaAsiHpi_OpenOutput( hostApi, stream->output->hpiDevice, + &stream->output->hpiFormat, + &stream->output->hpiStream ) ); + outputChannelCount = outputParameters->channelCount; + outputSampleFormat = outputParameters->sampleFormat; + hostOutputSampleFormat = PaAsiHpi_HpiToPaFormat( stream->output->hpiFormat.wFormat ); + stream->output->bytesPerFrame = outputChannelCount * Pa_GetSampleSize( hostOutputSampleFormat ); + /* Allocate host and temp buffers of appropriate size */ + PA_ENSURE_( PaAsiHpi_SetupBuffers( stream->output, stream->pollingInterval, + framesPerHostBuffer, outputParameters->suggestedLatency ) ); + } + + /* Determine maximum frames per host buffer (least common denominator of input/output) */ + if( inputParameters && outputParameters ) + { + stream->maxFramesPerHostBuffer = PA_MIN( stream->input->tempBufferSize / stream->input->bytesPerFrame, + stream->output->tempBufferSize / stream->output->bytesPerFrame ); + } + else + { + stream->maxFramesPerHostBuffer = inputParameters ? stream->input->tempBufferSize / stream->input->bytesPerFrame + : stream->output->tempBufferSize / stream->output->bytesPerFrame; + } + assert( stream->maxFramesPerHostBuffer > 0 ); + /* Initialize various other stream parameters */ + stream->neverDropInput = streamFlags & paNeverDropInput; + stream->state = paAsiHpiStoppedState; + + /* Initialize either callback or blocking interface */ + if( streamCallback ) + { + PaUtil_InitializeStreamRepresentation( &stream->baseStreamRep, + &hpiHostApi->callbackStreamInterface, + streamCallback, userData ); + stream->callbackMode = 1; + } + else + { + PaUtil_InitializeStreamRepresentation( &stream->baseStreamRep, + &hpiHostApi->blockingStreamInterface, + streamCallback, userData ); + /* Pre-allocate non-interleaved user buffer pointers for blocking interface */ + PA_UNLESS_( stream->blockingUserBufferCopy = + PaUtil_AllocateMemory( sizeof(void *) * PA_MAX( inputChannelCount, outputChannelCount ) ), + paInsufficientMemory ); + stream->callbackMode = 0; + } + PaUtil_InitializeCpuLoadMeasurer( &stream->cpuLoadMeasurer, sampleRate ); + + /* Following pa_linux_alsa's lead, we operate with fixed host buffer size by default, */ + /* since other modes will invariably lead to block adaption (maybe Bounded better?) */ + PA_ENSURE_( PaUtil_InitializeBufferProcessor( &stream->bufferProcessor, + inputChannelCount, inputSampleFormat, hostInputSampleFormat, + outputChannelCount, outputSampleFormat, hostOutputSampleFormat, + sampleRate, streamFlags, + framesPerBuffer, framesPerHostBuffer, paUtilFixedHostBufferSize, + streamCallback, userData ) ); + + stream->baseStreamRep.streamInfo.structVersion = 1; + stream->baseStreamRep.streamInfo.sampleRate = sampleRate; + /* Determine input latency from buffer processor and buffer sizes */ + if( stream->input ) + { + PaTime bufferDuration = ( stream->input->hostBufferSize + stream->input->hardwareBufferSize ) + / sampleRate / stream->input->bytesPerFrame; + stream->baseStreamRep.streamInfo.inputLatency = + PaUtil_GetBufferProcessorInputLatency( &stream->bufferProcessor ) + + bufferDuration - stream->maxFramesPerHostBuffer / sampleRate; + assert( stream->baseStreamRep.streamInfo.inputLatency > 0.0 ); + } + /* Determine output latency from buffer processor and buffer sizes */ + if( stream->output ) + { + PaTime bufferDuration = ( stream->output->hostBufferSize + stream->output->hardwareBufferSize ) + / sampleRate / stream->output->bytesPerFrame; + /* Take buffer size cap into account (see PaAsiHpi_WaitForFrames) */ + if( !stream->input && (stream->output->outputBufferCap > 0) ) + { + bufferDuration = PA_MIN( bufferDuration, + stream->output->outputBufferCap / sampleRate / stream->output->bytesPerFrame ); + } + stream->baseStreamRep.streamInfo.outputLatency = + PaUtil_GetBufferProcessorOutputLatency( &stream->bufferProcessor ) + + bufferDuration - stream->maxFramesPerHostBuffer / sampleRate; + assert( stream->baseStreamRep.streamInfo.outputLatency > 0.0 ); + } + + /* Report stream info, for debugging purposes */ + PaAsiHpi_StreamDump( stream ); + + /* Save initialized stream to PA stream list */ + *s = (PaStream*)stream; + return result; + +error: + CloseStream( (PaStream*)stream ); + return result; +} + + +/** Close PortAudio stream. + When CloseStream() is called, the multi-api layer ensures that the stream has already + been stopped or aborted. This closes the underlying HPI streams and deallocates stream + buffers and structs. + + @param s Pointer to PortAudio stream + + @return PortAudio error code +*/ +static PaError CloseStream( PaStream *s ) +{ + PaError result = paNoError; + PaAsiHpiStream *stream = (PaAsiHpiStream*)s; + + /* If stream is already gone, all is well */ + if( stream == NULL ) + return paNoError; + + /* Generic stream cleanup */ + PaUtil_TerminateBufferProcessor( &stream->bufferProcessor ); + PaUtil_TerminateStreamRepresentation( &stream->baseStreamRep ); + + /* Implementation-specific details - close internal streams */ + if( stream->input ) + { + /* Close HPI stream (freeing BBM host buffer in the process, if used) */ + if( stream->input->hpiStream ) + { + PA_ASIHPI_UNLESS_( HPI_InStreamClose( stream->input->hpiDevice->subSys, + stream->input->hpiStream ), paUnanticipatedHostError ); + } + /* Free temp buffer and stream component */ + PaUtil_FreeMemory( stream->input->tempBuffer ); + PaUtil_FreeMemory( stream->input ); + } + if( stream->output ) + { + /* Close HPI stream (freeing BBM host buffer in the process, if used) */ + if( stream->output->hpiStream ) + { + PA_ASIHPI_UNLESS_( HPI_OutStreamClose( stream->output->hpiDevice->subSys, + stream->output->hpiStream ), paUnanticipatedHostError ); + } + /* Free temp buffer and stream component */ + PaUtil_FreeMemory( stream->output->tempBuffer ); + PaUtil_FreeMemory( stream->output ); + } + + PaUtil_FreeMemory( stream->blockingUserBufferCopy ); + PaUtil_FreeMemory( stream ); + +error: + return result; +} + + +/** Prime HPI output stream with silence. + This resets the output stream and uses PortAudio helper routines to fill the + temp buffer with silence. It then writes two host buffers to the stream. This is supposed + to be called before the stream is started. It has no effect on input-only streams. + + @param stream Pointer to stream struct + + @return PortAudio error code + */ +static PaError PaAsiHpi_PrimeOutputWithSilence( PaAsiHpiStream *stream ) +{ + PaError result = paNoError; + PaAsiHpiStreamComponent *out; + PaUtilZeroer *zeroer; + PaSampleFormat outputFormat; + HPI_DATA data; + + assert( stream ); + out = stream->output; + /* Only continue if stream has output channels */ + if( !out ) + return result; + assert( out->tempBuffer ); + + /* Clear all existing data in hardware playback buffer */ + PA_ASIHPI_UNLESS_( HPI_OutStreamReset( out->hpiDevice->subSys, + out->hpiStream ), paUnanticipatedHostError ); + /* Fill temp buffer with silence */ + outputFormat = PaAsiHpi_HpiToPaFormat( out->hpiFormat.wFormat ); + zeroer = PaUtil_SelectZeroer( outputFormat ); + zeroer(out->tempBuffer, 1, out->tempBufferSize / Pa_GetSampleSize(outputFormat) ); + /* Write temp buffer to hardware fifo twice, to get started */ + PA_ASIHPI_UNLESS_( HPI_DataCreate( &data, &out->hpiFormat, out->tempBuffer, out->tempBufferSize ), + paUnanticipatedHostError ); + PA_ASIHPI_UNLESS_( HPI_OutStreamWrite( out->hpiDevice->subSys, + out->hpiStream, &data ), paUnanticipatedHostError ); + PA_ASIHPI_UNLESS_( HPI_OutStreamWrite( out->hpiDevice->subSys, + out->hpiStream, &data ), paUnanticipatedHostError ); + +error: + return result; +} + + +/** Start HPI streams (both input + output). + This starts all HPI streams in the PortAudio stream. Output streams are first primed with + silence, if required. After this call the PA stream is in the Active state. + + @todo Implement priming via the user callback + + @param stream Pointer to stream struct + + @param outputPrimed True if output is already primed (if false, silence will be loaded before starting) + + @return PortAudio error code + */ +static PaError PaAsiHpi_StartStream( PaAsiHpiStream *stream, int outputPrimed ) +{ + PaError result = paNoError; + + if( stream->input ) + { + PA_ASIHPI_UNLESS_( HPI_InStreamStart( stream->input->hpiDevice->subSys, + stream->input->hpiStream ), paUnanticipatedHostError ); + } + if( stream->output ) + { + if( !outputPrimed ) + { + /* Buffer isn't primed, so load stream with silence */ + PA_ENSURE_( PaAsiHpi_PrimeOutputWithSilence( stream ) ); + } + PA_ASIHPI_UNLESS_( HPI_OutStreamStart( stream->output->hpiDevice->subSys, + stream->output->hpiStream ), paUnanticipatedHostError ); + } + stream->state = paAsiHpiActiveState; + stream->callbackFinished = 0; + + /* Report stream info for debugging purposes */ + /* PaAsiHpi_StreamDump( stream ); */ + +error: + return result; +} + + +/** Start PortAudio stream. + If the stream has a callback interface, this starts a helper thread to feed the user callback. + The thread will then take care of starting the HPI streams, and this function will block + until the streams actually start. In the case of a blocking interface, the HPI streams + are simply started. + + @param s Pointer to PortAudio stream + + @return PortAudio error code +*/ +static PaError StartStream( PaStream *s ) +{ + PaError result = paNoError; + PaAsiHpiStream *stream = (PaAsiHpiStream*)s; + + assert( stream ); + + /* Ready the processor */ + PaUtil_ResetBufferProcessor( &stream->bufferProcessor ); + + if( stream->callbackMode ) + { + /* Create and start callback engine thread */ + /* Also waits 1 second for stream to be started by engine thread (otherwise aborts) */ + PA_ENSURE_( PaUnixThread_New( &stream->thread, &CallbackThreadFunc, stream, 1., 0 ) ); + } + else + { + PA_ENSURE_( PaAsiHpi_StartStream( stream, 0 ) ); + } + +error: + return result; +} + + +/** Stop HPI streams (input + output), either softly or abruptly. + If abort is false, the function blocks until the output stream is drained, otherwise it + stops immediately and discards data in the stream hardware buffers. + + This function is safe to call from the callback engine thread as well as the main thread. + + @param stream Pointer to stream struct + + @param abort True if samples in output buffer should be discarded (otherwise blocks until stream is done) + + @return PortAudio error code + + */ +static PaError PaAsiHpi_StopStream( PaAsiHpiStream *stream, int abort ) +{ + PaError result = paNoError; + + assert( stream ); + + /* Input channels */ + if( stream->input ) + { + PA_ASIHPI_UNLESS_( HPI_InStreamReset( stream->input->hpiDevice->subSys, + stream->input->hpiStream ), paUnanticipatedHostError ); + } + /* Output channels */ + if( stream->output ) + { + if( !abort ) + { + /* Wait until HPI output stream is drained */ + while( 1 ) + { + PaAsiHpiStreamInfo streamInfo; + PaTime timeLeft; + + /* Obtain number of samples waiting to be played */ + PA_ENSURE_( PaAsiHpi_GetStreamInfo( stream->output, &streamInfo ) ); + /* Check if stream is drained */ + if( (streamInfo.state != HPI_STATE_PLAYING) && + (streamInfo.dataSize < stream->output->bytesPerFrame * PA_ASIHPI_MIN_FRAMES_) ) + break; + /* Sleep amount of time represented by remaining samples */ + timeLeft = 1000.0 * streamInfo.dataSize / stream->output->bytesPerFrame + / stream->baseStreamRep.streamInfo.sampleRate; + Pa_Sleep( (long)ceil( timeLeft ) ); + } + } + PA_ASIHPI_UNLESS_( HPI_OutStreamReset( stream->output->hpiDevice->subSys, + stream->output->hpiStream ), paUnanticipatedHostError ); + } + + /* Report stream info for debugging purposes */ + /* PaAsiHpi_StreamDump( stream ); */ + +error: + return result; +} + + +/** Stop or abort PortAudio stream. + + This function is used to explicitly stop the PortAudio stream (via StopStream/AbortStream), + as opposed to the situation when the callback finishes with a result other than paContinue. + If a stream is in callback mode we will have to inspect whether the background thread has + finished, or we will have to take it out. In either case we join the thread before returning. + In blocking mode, we simply tell HPI to stop abruptly (abort) or finish buffers (drain). + The PortAudio stream will be in the Stopped state after a call to this function. + + Don't call this from the callback engine thread! + + @param stream Pointer to stream struct + + @param abort True if samples in output buffer should be discarded (otherwise blocks until stream is done) + + @return PortAudio error code +*/ +static PaError PaAsiHpi_ExplicitStop( PaAsiHpiStream *stream, int abort ) +{ + PaError result = paNoError; + + /* First deal with the callback thread, cancelling and/or joining it if necessary */ + if( stream->callbackMode ) + { + PaError threadRes; + stream->callbackAbort = abort; + if( abort ) + { + PA_DEBUG(( "Aborting callback\n" )); + } + else + { + PA_DEBUG(( "Stopping callback\n" )); + } + PA_ENSURE_( PaUnixThread_Terminate( &stream->thread, !abort, &threadRes ) ); + if( threadRes != paNoError ) + { + PA_DEBUG(( "Callback thread returned: %d\n", threadRes )); + } + } + else + { + PA_ENSURE_( PaAsiHpi_StopStream( stream, abort ) ); + } + + stream->state = paAsiHpiStoppedState; + +error: + return result; +} + + +/** Stop PortAudio stream. + This blocks until the output buffers are drained. + + @param s Pointer to PortAudio stream + + @return PortAudio error code +*/ +static PaError StopStream( PaStream *s ) +{ + return PaAsiHpi_ExplicitStop( (PaAsiHpiStream *) s, 0 ); +} + + +/** Abort PortAudio stream. + This discards any existing data in output buffers and stops the stream immediately. + + @param s Pointer to PortAudio stream + + @return PortAudio error code +*/ +static PaError AbortStream( PaStream *s ) +{ + return PaAsiHpi_ExplicitStop( (PaAsiHpiStream * ) s, 1 ); +} + + +/** Determine whether the stream is stopped. + A stream is considered to be stopped prior to a successful call to StartStream and after + a successful call to StopStream or AbortStream. If a stream callback returns a value other + than paContinue the stream is NOT considered to be stopped (it is in CallbackFinished state). + + @param s Pointer to PortAudio stream + + @return Returns one (1) when the stream is stopped, zero (0) when the stream is running, or + a PaErrorCode (which are always negative) if PortAudio is not initialized or an + error is encountered. +*/ +static PaError IsStreamStopped( PaStream *s ) +{ + PaAsiHpiStream *stream = (PaAsiHpiStream*)s; + + assert( stream ); + return stream->state == paAsiHpiStoppedState ? 1 : 0; +} + + +/** Determine whether the stream is active. + A stream is active after a successful call to StartStream(), until it becomes inactive either + as a result of a call to StopStream() or AbortStream(), or as a result of a return value + other than paContinue from the stream callback. In the latter case, the stream is considered + inactive after the last buffer has finished playing. + + @param s Pointer to PortAudio stream + + @return Returns one (1) when the stream is active (i.e. playing or recording audio), + zero (0) when not playing, or a PaErrorCode (which are always negative) + if PortAudio is not initialized or an error is encountered. +*/ +static PaError IsStreamActive( PaStream *s ) +{ + PaAsiHpiStream *stream = (PaAsiHpiStream*)s; + + assert( stream ); + return stream->state == paAsiHpiActiveState ? 1 : 0; +} + + +/** Returns current stream time. + This corresponds to the system clock. The clock should run continuously while the stream + is open, i.e. between calls to OpenStream() and CloseStream(), therefore a frame counter + is not good enough. + + @param s Pointer to PortAudio stream + + @return Stream time, in seconds + */ +static PaTime GetStreamTime( PaStream *s ) +{ + return PaUtil_GetTime(); +} + + +/** Returns CPU load. + + @param s Pointer to PortAudio stream + + @return CPU load (0.0 if blocking interface is used) + */ +static double GetStreamCpuLoad( PaStream *s ) +{ + PaAsiHpiStream *stream = (PaAsiHpiStream*)s; + + return stream->callbackMode ? PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer ) : 0.0; +} + +/* --------------------------- Callback Interface --------------------------- */ + +/** Exit routine which is called when callback thread quits. + This takes care of stopping the HPI streams (either waiting for output to finish, or + abruptly). It also calls the user-supplied StreamFinished callback, and sets the + stream state to CallbackFinished if it was reached via a non-paContinue return from + the user callback function. + + @param userData A pointer to an open stream previously created with Pa_OpenStream + */ +static void PaAsiHpi_OnThreadExit( void *userData ) +{ + PaAsiHpiStream *stream = (PaAsiHpiStream *) userData; + + assert( stream ); + + PaUtil_ResetCpuLoadMeasurer( &stream->cpuLoadMeasurer ); + + PA_DEBUG(( "%s: Stopping HPI streams\n", __FUNCTION__ )); + PaAsiHpi_StopStream( stream, stream->callbackAbort ); + PA_DEBUG(( "%s: Stoppage\n", __FUNCTION__ )); + + /* Eventually notify user all buffers have played */ + if( stream->baseStreamRep.streamFinishedCallback ) + { + stream->baseStreamRep.streamFinishedCallback( stream->baseStreamRep.userData ); + } + + /* Unfortunately both explicit calls to Stop/AbortStream (leading to Stopped state) + and implicit stops via paComplete/paAbort (leading to CallbackFinished state) + end up here - need another flag to remind us which is the case */ + if( stream->callbackFinished ) + stream->state = paAsiHpiCallbackFinishedState; +} + + +/** Wait until there is enough frames to fill a host buffer. + The routine attempts to sleep until at least a full host buffer can be retrieved from the + input HPI stream and passed to the output HPI stream. It will first sleep until enough + output space is available, as this is usually easily achievable. If it is an output-only + stream, it will also sleep if the hardware buffer is too full, thereby throttling the + filling of the output buffer and reducing output latency. The routine then blocks until + enough input samples are available, unless this will cause an output underflow. In the + process, input overflows and output underflows are indicated. + + @param stream Pointer to stream struct + + @param framesAvail Returns the number of available frames + + @param cbFlags Overflows and underflows indicated in here + + @return PortAudio error code (only paUnanticipatedHostError expected) + */ +static PaError PaAsiHpi_WaitForFrames( PaAsiHpiStream *stream, unsigned long *framesAvail, + PaStreamCallbackFlags *cbFlags ) +{ + PaError result = paNoError; + double sampleRate; + unsigned long framesTarget; + HW32 outputData = 0, outputSpace = 0, inputData = 0, framesLeft = 0; + + assert( stream ); + assert( stream->input || stream->output ); + + sampleRate = stream->baseStreamRep.streamInfo.sampleRate; + /* We have to come up with this much frames on both input and output */ + framesTarget = stream->bufferProcessor.framesPerHostBuffer; + assert( framesTarget > 0 ); + + while( 1 ) + { + PaAsiHpiStreamInfo info; + /* Check output first, as this takes priority in the default full-duplex mode */ + if( stream->output ) + { + PA_ENSURE_( PaAsiHpi_GetStreamInfo( stream->output, &info ) ); + /* Wait until enough space is available in output buffer to receive a full block */ + if( info.availableFrames < framesTarget ) + { + framesLeft = framesTarget - info.availableFrames; + Pa_Sleep( (long)ceil( 1000 * framesLeft / sampleRate ) ); + continue; + } + /* Wait until the data in hardware buffer has dropped to a sensible level. + Without this, the hardware buffer quickly fills up in the absence of an input + stream to regulate its data rate (if data generation is fast). This leads to + large latencies, as the AudioScience hardware buffers are humongous. + This is similar to the default "Hardware Buffering=off" option in the + AudioScience WAV driver. */ + if( !stream->input && (stream->output->outputBufferCap > 0) && + ( info.totalBufferedData > stream->output->outputBufferCap / stream->output->bytesPerFrame ) ) + { + framesLeft = info.totalBufferedData - stream->output->outputBufferCap / stream->output->bytesPerFrame; + Pa_Sleep( (long)ceil( 1000 * framesLeft / sampleRate ) ); + continue; + } + outputData = info.totalBufferedData; + outputSpace = info.availableFrames; + /* Report output underflow to callback */ + if( info.underflow ) + { + *cbFlags |= paOutputUnderflow; + } + } + + /* Now check input side */ + if( stream->input ) + { + PA_ENSURE_( PaAsiHpi_GetStreamInfo( stream->input, &info ) ); + /* If a full block of samples hasn't been recorded yet, wait for it if possible */ + if( info.availableFrames < framesTarget ) + { + framesLeft = framesTarget - info.availableFrames; + /* As long as output is not disrupted in the process, wait for a full + block of input samples */ + if( !stream->output || (outputData > framesLeft) ) + { + Pa_Sleep( (long)ceil( 1000 * framesLeft / sampleRate ) ); + continue; + } + } + inputData = info.availableFrames; + /** @todo The paInputOverflow flag should be set in the callback containing the + first input sample following the overflow. That means the block currently sitting + at the fore-front of recording, i.e. typically the one containing the newest (last) + sample in the HPI buffer system. This is most likely not the same as the current + block of data being passed to the callback. The current overflow should ideally + be noted in an overflow list of sorts, with an indication of when it should be + reported. The trouble starts if there are several separate overflow incidents, + given a big input buffer. Oh well, something to try out later... */ + if( info.overflow ) + { + *cbFlags |= paInputOverflow; + } + } + break; + } + /* Full-duplex stream */ + if( stream->input && stream->output ) + { + if( outputSpace >= framesTarget ) + *framesAvail = outputSpace; + /* If input didn't make the target, keep the output count instead (input underflow) */ + if( (inputData >= framesTarget) && (inputData < outputSpace) ) + *framesAvail = inputData; + } + else + { + *framesAvail = stream->input ? inputData : outputSpace; + } + +error: + return result; +} + + +/** Obtain recording, current and playback timestamps of stream. + The current time is determined by the system clock. This "now" timestamp occurs at the + forefront of recording (and playback in the full-duplex case), which happens later than the + input timestamp by an amount equal to the total number of recorded frames in the input buffer. + The output timestamp indicates when the next generated sample will actually be played. This + happens after all the samples currently in the output buffer are played. The output timestamp + therefore follows the current timestamp by an amount equal to the number of frames yet to be + played back in the output buffer. + + If the current timestamp is the present, the input timestamp is in the past and the output + timestamp is in the future. + + @param stream Pointer to stream struct + + @param timeInfo Pointer to timeInfo struct that will contain timestamps + */ +static void PaAsiHpi_CalculateTimeInfo( PaAsiHpiStream *stream, PaStreamCallbackTimeInfo *timeInfo ) +{ + PaAsiHpiStreamInfo streamInfo; + double sampleRate; + + assert( stream ); + assert( timeInfo ); + sampleRate = stream->baseStreamRep.streamInfo.sampleRate; + + /* The current time ("now") is at the forefront of both recording and playback */ + timeInfo->currentTime = GetStreamTime( (PaStream *)stream ); + /* The last sample in the input buffer was recorded just now, so the first sample + happened (number of recorded samples)/sampleRate ago */ + timeInfo->inputBufferAdcTime = timeInfo->currentTime; + if( stream->input ) + { + PaAsiHpi_GetStreamInfo( stream->input, &streamInfo ); + timeInfo->inputBufferAdcTime -= streamInfo.totalBufferedData / sampleRate; + } + /* The first of the outgoing samples will be played after all the samples in the output + buffer is done */ + timeInfo->outputBufferDacTime = timeInfo->currentTime; + if( stream->output ) + { + PaAsiHpi_GetStreamInfo( stream->output, &streamInfo ); + timeInfo->outputBufferDacTime += streamInfo.totalBufferedData / sampleRate; + } +} + + +/** Read from HPI input stream and register buffers. + This reads data from the HPI input stream (if it exists) and registers the temp stream + buffers of both input and output streams with the buffer processor. In the process it also + handles input underflows in the full-duplex case. + + @param stream Pointer to stream struct + + @param numFrames On entrance the number of available frames, on exit the number of + received frames + + @param cbFlags Indicates overflows and underflows + + @return PortAudio error code + */ +static PaError PaAsiHpi_BeginProcessing( PaAsiHpiStream *stream, unsigned long *numFrames, + PaStreamCallbackFlags *cbFlags ) +{ + PaError result = paNoError; + + assert( stream ); + if( *numFrames > stream->maxFramesPerHostBuffer ) + *numFrames = stream->maxFramesPerHostBuffer; + + if( stream->input ) + { + PaAsiHpiStreamInfo info; + HPI_DATA data; + HW32 framesToGet = *numFrames; + + /* Check for overflows and underflows yet again */ + PA_ENSURE_( PaAsiHpi_GetStreamInfo( stream->input, &info ) ); + if( info.overflow ) + { + *cbFlags |= paInputOverflow; + } + /* Input underflow if less than expected number of samples pitch up */ + if( framesToGet > info.availableFrames ) + { + PaUtilZeroer *zeroer; + PaSampleFormat inputFormat; + + /* Never call an input-only stream with InputUnderflow set */ + if( stream->output ) + *cbFlags |= paInputUnderflow; + framesToGet = info.availableFrames; + /* Fill temp buffer with silence (to make up for missing input samples) */ + inputFormat = PaAsiHpi_HpiToPaFormat( stream->input->hpiFormat.wFormat ); + zeroer = PaUtil_SelectZeroer( inputFormat ); + zeroer(stream->input->tempBuffer, 1, + stream->input->tempBufferSize / Pa_GetSampleSize(inputFormat) ); + } + + /* Setup HPI data structure around temp buffer */ + HPI_DataCreate( &data, &stream->input->hpiFormat, stream->input->tempBuffer, + framesToGet * stream->input->bytesPerFrame ); + /* Read block of data into temp buffer */ + PA_ASIHPI_UNLESS_( HPI_InStreamRead( stream->input->hpiDevice->subSys, + stream->input->hpiStream, &data ), + paUnanticipatedHostError ); + /* Register temp buffer with buffer processor (always FULL buffer) */ + PaUtil_SetInputFrameCount( &stream->bufferProcessor, *numFrames ); + /* HPI interface only allows interleaved channels */ + PaUtil_SetInterleavedInputChannels( &stream->bufferProcessor, + 0, stream->input->tempBuffer, + stream->input->hpiFormat.wChannels ); + } + if( stream->output ) + { + /* Register temp buffer with buffer processor */ + PaUtil_SetOutputFrameCount( &stream->bufferProcessor, *numFrames ); + /* HPI interface only allows interleaved channels */ + PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor, + 0, stream->output->tempBuffer, + stream->output->hpiFormat.wChannels ); + } + +error: + return result; +} + + +/** Flush output buffers to HPI output stream. + This completes the processing cycle by writing the temp buffer to the HPI interface. + Additional output underflows are caught before data is written to the stream, as this + action typically remedies the underflow and hides it in the process. + + @param stream Pointer to stream struct + + @param numFrames The number of frames to write to the output stream + + @param cbFlags Indicates overflows and underflows + */ +static PaError PaAsiHpi_EndProcessing( PaAsiHpiStream *stream, unsigned long numFrames, + PaStreamCallbackFlags *cbFlags ) +{ + PaError result = paNoError; + + assert( stream ); + + if( stream->output ) + { + PaAsiHpiStreamInfo info; + HPI_DATA data; + + /* Check for underflows after the (potentially time-consuming) callback */ + PA_ENSURE_( PaAsiHpi_GetStreamInfo( stream->output, &info ) ); + if( info.underflow ) + { + *cbFlags |= paOutputUnderflow; + } + + /* Setup HPI data structure around temp buffer */ + HPI_DataCreate( &data, &stream->output->hpiFormat, stream->output->tempBuffer, + numFrames * stream->output->bytesPerFrame ); + /* Write temp buffer to HPI stream */ + PA_ASIHPI_UNLESS_( HPI_OutStreamWrite( stream->output->hpiDevice->subSys, + stream->output->hpiStream, &data ), + paUnanticipatedHostError ); + } + +error: + return result; +} + + +/** Main callback engine. + This function runs in a separate thread and does all the work of fetching audio data from + the AudioScience card via the HPI interface, feeding it to the user callback via the buffer + processor, and delivering the resulting output data back to the card via HPI calls. + It is started and terminated when the PortAudio stream is started and stopped, and starts + the HPI streams on startup. + + @param userData A pointer to an open stream previously created with Pa_OpenStream. +*/ +static void *CallbackThreadFunc( void *userData ) +{ + PaError result = paNoError; + PaAsiHpiStream *stream = (PaAsiHpiStream *) userData; + int callbackResult = paContinue; + + assert( stream ); + + /* Cleanup routine stops streams on thread exit */ + pthread_cleanup_push( &PaAsiHpi_OnThreadExit, stream ); + + /* Start HPI streams and notify parent when we're done */ + PA_ENSURE_( PaUnixThread_PrepareNotify( &stream->thread ) ); + /* Buffer will be primed with silence */ + PA_ENSURE_( PaAsiHpi_StartStream( stream, 0 ) ); + PA_ENSURE_( PaUnixThread_NotifyParent( &stream->thread ) ); + + /* MAIN LOOP */ + while( 1 ) + { + PaStreamCallbackFlags cbFlags = 0; + unsigned long framesAvail, framesGot; + + pthread_testcancel(); + + /** @concern StreamStop if the main thread has requested a stop and the stream has not + * been effectively stopped we signal this condition by modifying callbackResult + * (we'll want to flush buffered output). */ + if( PaUnixThread_StopRequested( &stream->thread ) && (callbackResult == paContinue) ) + { + PA_DEBUG(( "Setting callbackResult to paComplete\n" )); + callbackResult = paComplete; + } + + /* Start winding down thread if requested */ + if( callbackResult != paContinue ) + { + stream->callbackAbort = (callbackResult == paAbort); + if( stream->callbackAbort || + /** @concern BlockAdaption: Go on if adaption buffers are empty */ + PaUtil_IsBufferProcessorOutputEmpty( &stream->bufferProcessor ) ) + { + goto end; + } + PA_DEBUG(( "%s: Flushing buffer processor\n", __FUNCTION__ )); + /* There is still buffered output that needs to be processed */ + } + + /* SLEEP */ + /* Wait for data (or buffer space) to become available. This basically sleeps and + polls the HPI interface until a full block of frames can be moved. */ + PA_ENSURE_( PaAsiHpi_WaitForFrames( stream, &framesAvail, &cbFlags ) ); + + /* Consume buffer space. Once we have a number of frames available for consumption we + must retrieve the data from the HPI interface and pass it to the PA buffer processor. + We should be prepared to process several chunks successively. */ + while( framesAvail > 0 ) + { + PaStreamCallbackTimeInfo timeInfo = {0, 0, 0}; + + pthread_testcancel(); + + framesGot = framesAvail; + if( stream->bufferProcessor.hostBufferSizeMode == paUtilFixedHostBufferSize ) + { + /* We've committed to a fixed host buffer size, stick to that */ + framesGot = framesGot >= stream->maxFramesPerHostBuffer ? stream->maxFramesPerHostBuffer : 0; + } + else + { + /* We've committed to an upper bound on the size of host buffers */ + assert( stream->bufferProcessor.hostBufferSizeMode == paUtilBoundedHostBufferSize ); + framesGot = PA_MIN( framesGot, stream->maxFramesPerHostBuffer ); + } + + /* Obtain buffer timestamps */ + PaAsiHpi_CalculateTimeInfo( stream, &timeInfo ); + PaUtil_BeginBufferProcessing( &stream->bufferProcessor, &timeInfo, cbFlags ); + /* CPU load measurement should include processing activivity external to the stream callback */ + PaUtil_BeginCpuLoadMeasurement( &stream->cpuLoadMeasurer ); + if( framesGot > 0 ) + { + /* READ FROM HPI INPUT STREAM */ + PA_ENSURE_( PaAsiHpi_BeginProcessing( stream, &framesGot, &cbFlags ) ); + /* Input overflow in a full-duplex stream makes for interesting times */ + if( stream->input && stream->output && (cbFlags & paInputOverflow) ) + { + /* Special full-duplex paNeverDropInput mode */ + if( stream->neverDropInput ) + { + PaUtil_SetNoOutput( &stream->bufferProcessor ); + cbFlags |= paOutputOverflow; + } + } + /* CALL USER CALLBACK WITH INPUT DATA, AND OBTAIN OUTPUT DATA */ + PaUtil_EndBufferProcessing( &stream->bufferProcessor, &callbackResult ); + /* Clear overflow and underflow information (but PaAsiHpi_EndProcessing might + still show up output underflow that will carry over to next round) */ + cbFlags = 0; + /* WRITE TO HPI OUTPUT STREAM */ + PA_ENSURE_( PaAsiHpi_EndProcessing( stream, framesGot, &cbFlags ) ); + /* Advance frame counter */ + framesAvail -= framesGot; + } + PaUtil_EndCpuLoadMeasurement( &stream->cpuLoadMeasurer, framesGot ); + + if( framesGot == 0 ) + { + /* Go back to polling for more frames */ + break; + + } + if( callbackResult != paContinue ) + break; + } + } + + /* This code is unreachable, but important to include regardless because it + * is possibly a macro with a closing brace to match the opening brace in + * pthread_cleanup_push() above. The documentation states that they must + * always occur in pairs. */ + pthread_cleanup_pop( 1 ); + +end: + /* Indicates normal exit of callback, as opposed to the thread getting killed explicitly */ + stream->callbackFinished = 1; + PA_DEBUG(( "%s: Thread %d exiting (callbackResult = %d)\n ", + __FUNCTION__, pthread_self(), callbackResult )); + /* Exit from thread and report any PortAudio error in the process */ + PaUnixThreading_EXIT( result ); +error: + goto end; +} + +/* --------------------------- Blocking Interface --------------------------- */ + +/* As separate stream interfaces are used for blocking and callback streams, the following + functions can be guaranteed to only be called for blocking streams. */ + +/** Read data from input stream. + This reads the indicated number of frames into the supplied buffer from an input stream, + and blocks until this is done. + + @param s Pointer to PortAudio stream + + @param buffer Pointer to buffer that will receive interleaved data (or an array of pointers + to a buffer for each non-interleaved channel) + + @param frames Number of frames to read from stream + + @return PortAudio error code (also indicates overflow via paInputOverflowed) + */ +static PaError ReadStream( PaStream *s, + void *buffer, + unsigned long frames ) +{ + PaError result = paNoError; + PaAsiHpiStream *stream = (PaAsiHpiStream*)s; + PaAsiHpiStreamInfo info; + void *userBuffer; + + assert( stream ); + PA_UNLESS_( stream->input, paCanNotReadFromAnOutputOnlyStream ); + + /* Check for input overflow since previous call to ReadStream */ + PA_ENSURE_( PaAsiHpi_GetStreamInfo( stream->input, &info ) ); + if( info.overflow ) + { + result = paInputOverflowed; + } + + /* NB Make copy of user buffer pointers, since they are advanced by buffer processor */ + if( stream->bufferProcessor.userInputIsInterleaved ) + { + userBuffer = buffer; + } + else + { + /* Copy channels into local array */ + userBuffer = stream->blockingUserBufferCopy; + memcpy( userBuffer, buffer, sizeof (void *) * stream->input->hpiFormat.wChannels ); + } + + while( frames > 0 ) + { + unsigned long framesGot, framesAvail; + PaStreamCallbackFlags cbFlags = 0; + + PA_ENSURE_( PaAsiHpi_WaitForFrames( stream, &framesAvail, &cbFlags ) ); + framesGot = PA_MIN( framesAvail, frames ); + PA_ENSURE_( PaAsiHpi_BeginProcessing( stream, &framesGot, &cbFlags ) ); + + if( framesGot > 0 ) + { + framesGot = PaUtil_CopyInput( &stream->bufferProcessor, &userBuffer, framesGot ); + PA_ENSURE_( PaAsiHpi_EndProcessing( stream, framesGot, &cbFlags ) ); + /* Advance frame counter */ + frames -= framesGot; + } + } + +error: + return result; +} + + +/** Write data to output stream. + This writes the indicated number of frames from the supplied buffer to an output stream, + and blocks until this is done. + + @param s Pointer to PortAudio stream + + @param buffer Pointer to buffer that provides interleaved data (or an array of pointers + to a buffer for each non-interleaved channel) + + @param frames Number of frames to write to stream + + @return PortAudio error code (also indicates underflow via paOutputUnderflowed) + */ +static PaError WriteStream( PaStream *s, + const void *buffer, + unsigned long frames ) +{ + PaError result = paNoError; + PaAsiHpiStream *stream = (PaAsiHpiStream*)s; + PaAsiHpiStreamInfo info; + const void *userBuffer; + + assert( stream ); + PA_UNLESS_( stream->output, paCanNotWriteToAnInputOnlyStream ); + + /* Check for output underflow since previous call to WriteStream */ + PA_ENSURE_( PaAsiHpi_GetStreamInfo( stream->output, &info ) ); + if( info.underflow ) + { + result = paOutputUnderflowed; + } + + /* NB Make copy of user buffer pointers, since they are advanced by buffer processor */ + if( stream->bufferProcessor.userOutputIsInterleaved ) + { + userBuffer = buffer; + } + else + { + /* Copy channels into local array */ + userBuffer = stream->blockingUserBufferCopy; + memcpy( (void *)userBuffer, buffer, sizeof (void *) * stream->output->hpiFormat.wChannels ); + } + + while( frames > 0 ) + { + unsigned long framesGot, framesAvail; + PaStreamCallbackFlags cbFlags = 0; + + PA_ENSURE_( PaAsiHpi_WaitForFrames( stream, &framesAvail, &cbFlags ) ); + framesGot = PA_MIN( framesAvail, frames ); + PA_ENSURE_( PaAsiHpi_BeginProcessing( stream, &framesGot, &cbFlags ) ); + + if( framesGot > 0 ) + { + framesGot = PaUtil_CopyOutput( &stream->bufferProcessor, &userBuffer, framesGot ); + PA_ENSURE_( PaAsiHpi_EndProcessing( stream, framesGot, &cbFlags ) ); + /* Advance frame counter */ + frames -= framesGot; + } + } + +error: + return result; +} + + +/** Number of frames that can be read from input stream without blocking. + + @param s Pointer to PortAudio stream + + @return Number of frames, or PortAudio error code + */ +static signed long GetStreamReadAvailable( PaStream *s ) +{ + PaError result = paNoError; + PaAsiHpiStream *stream = (PaAsiHpiStream*)s; + PaAsiHpiStreamInfo info; + + assert( stream ); + PA_UNLESS_( stream->input, paCanNotReadFromAnOutputOnlyStream ); + + PA_ENSURE_( PaAsiHpi_GetStreamInfo( stream->input, &info ) ); + /* Round down to the nearest host buffer multiple */ + result = (info.availableFrames / stream->maxFramesPerHostBuffer) * stream->maxFramesPerHostBuffer; + if( info.overflow ) + { + result = paInputOverflowed; + } + +error: + return result; +} + + +/** Number of frames that can be written to output stream without blocking. + + @param s Pointer to PortAudio stream + + @return Number of frames, or PortAudio error code + */ +static signed long GetStreamWriteAvailable( PaStream *s ) +{ + PaError result = paNoError; + PaAsiHpiStream *stream = (PaAsiHpiStream*)s; + PaAsiHpiStreamInfo info; + + assert( stream ); + PA_UNLESS_( stream->output, paCanNotWriteToAnInputOnlyStream ); + + PA_ENSURE_( PaAsiHpi_GetStreamInfo( stream->output, &info ) ); + /* Round down to the nearest host buffer multiple */ + result = (info.availableFrames / stream->maxFramesPerHostBuffer) * stream->maxFramesPerHostBuffer; + if( info.underflow ) + { + result = paOutputUnderflowed; + } + +error: + return result; +} From sumomo @ users.sourceforge.jp Mon Feb 7 13:56:14 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Mon, 07 Feb 2011 13:56:14 +0900 Subject: [Julius-cvs 594] CVS update: julius4/libjulius/src Message-ID: <1297054574.756007.21433.nullmailer@users.sourceforge.jp> Index: julius4/libjulius/src/m_fusion.c diff -u julius4/libjulius/src/m_fusion.c:1.16 julius4/libjulius/src/m_fusion.c:1.17 --- julius4/libjulius/src/m_fusion.c:1.16 Sat Feb 5 22:27:22 2011 +++ julius4/libjulius/src/m_fusion.c Mon Feb 7 13:56:14 2011 @@ -20,7 +20,7 @@ * @author Akinobu Lee * @date Thu May 12 13:31:47 2005 * - * $Revision: 1.16 $ + * $Revision: 1.17 $ * */ /* @@ -285,6 +285,9 @@ initialize_dict(JCONF_LM *lmconf, HTK_HMM_INFO *hmminfo) { WORD_INFO *winfo; + JCONF_LM_NAMELIST *nl; + char buf[MAXLINELEN]; + int n; /* allocate new word dictionary */ winfo = word_info_new(); @@ -303,9 +306,6 @@ } /* load additional entries */ - JCONF_LM_NAMELIST *nl; - char buf[MAXLINELEN]; - int n; for (nl = lmconf->additional_dict_files; nl; nl=nl->next) { FILE *fp; if ((fp = fopen(nl->name, "rb")) == NULL) { Index: julius4/libjulius/src/m_options.c diff -u julius4/libjulius/src/m_options.c:1.20 julius4/libjulius/src/m_options.c:1.21 --- julius4/libjulius/src/m_options.c:1.20 Sat Feb 5 18:00:41 2011 +++ julius4/libjulius/src/m_options.c Mon Feb 7 13:56:14 2011 @@ -18,7 +18,7 @@ * @author Akinobu Lee * @date Thu May 12 18:52:07 2005 * - * $Revision: 1.20 $ + * $Revision: 1.21 $ * */ /* @@ -1273,9 +1273,9 @@ } else if (strmatch(argv[i],"-adddict")) { if (!check_section(jconf, argv[i], JCONF_OPT_LM)) return FALSE; GET_TMPARG; - char *arg = filepath(tmparg, cwd); - j_add_dict(jconf->lmnow, arg); - free(arg); + tmparg = filepath(tmparg, cwd); + j_add_dict(jconf->lmnow, tmparg); + free(tmparg); continue; } else if (strmatch(argv[i],"-addentry")) { if (!check_section(jconf, argv[i], JCONF_OPT_LM)) return FALSE; From sumomo @ users.sourceforge.jp Mon Feb 7 13:56:14 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Mon, 07 Feb 2011 13:56:14 +0900 Subject: [Julius-cvs 595] CVS update: julius4/libsent/src/adin Message-ID: <1297054574.832861.21441.nullmailer@users.sourceforge.jp> Index: julius4/libsent/src/adin/adin_portaudio.c diff -u julius4/libsent/src/adin/adin_portaudio.c:1.13 julius4/libsent/src/adin/adin_portaudio.c:1.14 --- julius4/libsent/src/adin/adin_portaudio.c:1.13 Sat Feb 5 18:00:01 2011 +++ julius4/libsent/src/adin/adin_portaudio.c Mon Feb 7 13:56:14 2011 @@ -56,7 +56,7 @@ * @author Akinobu LEE * @date Mon Feb 14 12:03:48 2005 * - * $Revision: 1.13 $ + * $Revision: 1.14 $ * */ /* @@ -469,24 +469,26 @@ } // open the device - PaStreamParameters param; - memset( ¶m, 0, sizeof(param)); - param.channelCount = 1; - param.device = devId; - param.sampleFormat = paInt16; - if (latency == 0) { - param.suggestedLatency = Pa_GetDeviceInfo(devId)->defaultLowInputLatency; - jlog("Stat: adin_portaudio: try to set default low latency from portaudio: %d msec\n", param.suggestedLatency * 1000.0); - } else { - param.suggestedLatency = latency / 1000.0; - jlog("Stat: adin_portaudio: try to set latency to %d msec\n", param.suggestedLatency * 1000.0); - } - err = Pa_OpenStream(&stream, ¶m, NULL, sfreq, - 0, paNoFlag, - Callback, NULL); - if (err != paNoError) { - jlog("Error: adin_portaudio: error in opening stream: %s\n", Pa_GetErrorText(err)); - return(FALSE); + { + PaStreamParameters param; + memset( ¶m, 0, sizeof(param)); + param.channelCount = 1; + param.device = devId; + param.sampleFormat = paInt16; + if (latency == 0) { + param.suggestedLatency = Pa_GetDeviceInfo(devId)->defaultLowInputLatency; + jlog("Stat: adin_portaudio: try to set default low latency from portaudio: %d msec\n", param.suggestedLatency * 1000.0); + } else { + param.suggestedLatency = latency / 1000.0; + jlog("Stat: adin_portaudio: try to set latency to %d msec\n", param.suggestedLatency * 1000.0); + } + err = Pa_OpenStream(&stream, ¶m, NULL, sfreq, + 0, paNoFlag, + Callback, NULL); + if (err != paNoError) { + jlog("Error: adin_portaudio: error in opening stream: %s\n", Pa_GetErrorText(err)); + return(FALSE); + } } { const PaStreamInfo *stinfo; From sumomo @ users.sourceforge.jp Tue Feb 8 00:15:30 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Tue, 08 Feb 2011 00:15:30 +0900 Subject: [Julius-cvs 596] CVS update: julius4/libsent/src/adin Message-ID: <1297091730.731625.13317.nullmailer@users.sourceforge.jp> Index: julius4/libsent/src/adin/adin_portaudio.c diff -u julius4/libsent/src/adin/adin_portaudio.c:1.14 julius4/libsent/src/adin/adin_portaudio.c:1.15 --- julius4/libsent/src/adin/adin_portaudio.c:1.14 Mon Feb 7 13:56:14 2011 +++ julius4/libsent/src/adin/adin_portaudio.c Tue Feb 8 00:15:30 2011 @@ -56,7 +56,7 @@ * @author Akinobu LEE * @date Mon Feb 14 12:03:48 2005 * - * $Revision: 1.14 $ + * $Revision: 1.15 $ * */ /* @@ -193,9 +193,9 @@ } #ifdef OLDVER -static PortAudioStream *stream; ///< Stream information +static PortAudioStream *stream = NULL; ///< Stream information #else -static PaStream *stream; ///< Stream information +static PaStream *stream = NULL; ///< Stream information #endif static int srate; ///< Required sampling rate @@ -531,12 +531,14 @@ /* initialize device and open stream */ if (adin_mic_open(arg) == FALSE) { + stream = NULL; return(FALSE); } /* start stream */ err = Pa_StartStream(stream); if (err != paNoError) { jlog("Error: adin_portaudio: failed to begin stream: %s\n", Pa_GetErrorText(err)); + stream = NULL; return(FALSE); } @@ -553,6 +555,8 @@ { PaError err; + if (stream == NULL) return(TRUE); + /* stop stream (do not wait callback and buffer flush, stop immediately) */ err = Pa_AbortStream(stream); if (err != paNoError) { @@ -572,6 +576,8 @@ return(FALSE); } + stream = NULL; + return TRUE; } @@ -594,6 +600,11 @@ int avail; int len; + if (stream == NULL) { + // stream closed, return error + return(-2); + } + if (buffer_overflowed) { jlog("Error: adin_portaudio: input buffer OVERFLOW, increase INPUT_DELAY_SEC in sent/speech.h\n"); buffer_overflowed = FALSE; From sumomo @ users.sourceforge.jp Thu Feb 10 01:17:45 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Thu, 10 Feb 2011 01:17:45 +0900 Subject: [Julius-cvs 597] CVS update: julius4/libsent/src/adin Message-ID: <1297268265.479542.16681.nullmailer@users.sourceforge.jp> Index: julius4/libsent/src/adin/adin_portaudio.c diff -u julius4/libsent/src/adin/adin_portaudio.c:1.15 julius4/libsent/src/adin/adin_portaudio.c:1.16 --- julius4/libsent/src/adin/adin_portaudio.c:1.15 Tue Feb 8 00:15:30 2011 +++ julius4/libsent/src/adin/adin_portaudio.c Thu Feb 10 01:17:45 2011 @@ -56,7 +56,7 @@ * @author Akinobu LEE * @date Mon Feb 14 12:03:48 2005 * - * $Revision: 1.15 $ + * $Revision: 1.16 $ * */ /* @@ -554,17 +554,25 @@ adin_mic_end() { PaError err; +#ifdef OLDVER + PortAudioStream *stream_local; +#else + PaStream *stream_local; +#endif if (stream == NULL) return(TRUE); + stream_local = stream; + stream = NULL; + /* stop stream (do not wait callback and buffer flush, stop immediately) */ - err = Pa_AbortStream(stream); + err = Pa_AbortStream(stream_local); if (err != paNoError) { jlog("Error: adin_portaudio: failed to stop stream: %s\n", Pa_GetErrorText(err)); return(FALSE); } /* close stream */ - err = Pa_CloseStream(stream); + err = Pa_CloseStream(stream_local); if (err != paNoError) { jlog("Error: adin_portaudio: failed to close stream: %s\n", Pa_GetErrorText(err)); return(FALSE); @@ -576,8 +584,6 @@ return(FALSE); } - stream = NULL; - return TRUE; } @@ -600,11 +606,6 @@ int avail; int len; - if (stream == NULL) { - // stream closed, return error - return(-2); - } - if (buffer_overflowed) { jlog("Error: adin_portaudio: input buffer OVERFLOW, increase INPUT_DELAY_SEC in sent/speech.h\n"); buffer_overflowed = FALSE; @@ -615,6 +616,7 @@ printf("process : current == processed: %d: wait\n", current); #endif Pa_Sleep(20); /* wait till some input comes */ + if (stream == NULL) return(-1); } current_local = current; From sumomo @ users.sourceforge.jp Fri Feb 11 00:23:52 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Fri, 11 Feb 2011 00:23:52 +0900 Subject: [Julius-cvs 598] CVS update: julius4/libjulius/src Message-ID: <1297351432.042111.22682.nullmailer@users.sourceforge.jp> Index: julius4/libjulius/src/instance.c diff -u julius4/libjulius/src/instance.c:1.5 julius4/libjulius/src/instance.c:1.6 --- julius4/libjulius/src/instance.c:1.5 Sat Feb 5 18:00:41 2011 +++ julius4/libjulius/src/instance.c Fri Feb 11 00:23:51 2011 @@ -12,7 +12,7 @@ * @author Akinobu Lee * @date Sun Oct 28 18:06:20 2007 * - * $Revision: 1.5 $ + * $Revision: 1.6 $ * */ /* @@ -160,11 +160,11 @@ void j_process_am_free(PROCESS_AM *am) { + /* HMMWork hmmwrk */ + outprob_free(&(am->hmmwrk)); if (am->hmminfo) hmminfo_free(am->hmminfo); if (am->hmm_gs) hmminfo_free(am->hmm_gs); /* not free am->jconf */ - /* HMMWork hmmwrk */ - outprob_free(&(am->hmmwrk)); free(am); } @@ -300,6 +300,10 @@ /* not free jconf, am, lm here */ /* free part of StackDecode work area */ wchmm_fbs_free(process); + /* free cache */ + if (process->lmtype == LM_PROB) { + max_successor_cache_free(process->wchmm); + } /* free wchmm */ if (process->wchmm) wchmm_free(process->wchmm); /* free backtrellis */ Index: julius4/libjulius/src/useropt.c diff -u julius4/libjulius/src/useropt.c:1.2 julius4/libjulius/src/useropt.c:1.3 --- julius4/libjulius/src/useropt.c:1.2 Tue Dec 18 17:45:49 2007 +++ julius4/libjulius/src/useropt.c Fri Feb 11 00:23:51 2011 @@ -12,7 +12,7 @@ * @author Akinobu Lee * @date Sun Sep 02 19:44:37 2007 * - * $Revision: 1.2 $ + * $Revision: 1.3 $ * */ /* @@ -139,6 +139,9 @@ return FALSE; } + /* if this is first time, register free function at app exit */ + if (useropt_root == NULL) atexit(useropt_free_all); + /* allocate new */ new = useropt_new(); /* set option string */ From sumomo @ users.sourceforge.jp Fri Feb 11 00:23:52 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Fri, 11 Feb 2011 00:23:52 +0900 Subject: [Julius-cvs 599] CVS update: julius4/libsent/include/sent Message-ID: <1297351432.109998.22690.nullmailer@users.sourceforge.jp> Index: julius4/libsent/include/sent/vocabulary.h diff -u julius4/libsent/include/sent/vocabulary.h:1.6 julius4/libsent/include/sent/vocabulary.h:1.7 --- julius4/libsent/include/sent/vocabulary.h:1.6 Fri Sep 18 17:31:08 2009 +++ julius4/libsent/include/sent/vocabulary.h Fri Feb 11 00:23:52 2011 @@ -30,7 +30,7 @@ * @author Akinobu LEE * @date Sat Feb 12 12:38:13 2005 * - * $Revision: 1.6 $ + * $Revision: 1.7 $ * */ /* @@ -78,6 +78,8 @@ boolean *is_transparent; ///< TRUE if the word can be treated as transparent [wid] APATNODE *errph_root; ///< Root node of index tree for gathering error %HMM name appeared when reading the dictionary BMALLOC_BASE *mroot; ///< Pointer for block memory allocation + void *work; ///< Work buffer for dictionary reading + int work_num; ///< Num of elements in work } WORD_INFO; #ifdef __cplusplus From sumomo @ users.sourceforge.jp Fri Feb 11 00:23:52 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Fri, 11 Feb 2011 00:23:52 +0900 Subject: [Julius-cvs 600] CVS update: julius4/libsent/src/voca Message-ID: <1297351432.269043.22712.nullmailer@users.sourceforge.jp> Index: julius4/libsent/src/voca/voca_load_htkdict.c diff -u julius4/libsent/src/voca/voca_load_htkdict.c:1.8 julius4/libsent/src/voca/voca_load_htkdict.c:1.9 --- julius4/libsent/src/voca/voca_load_htkdict.c:1.8 Sat Feb 5 18:00:41 2011 +++ julius4/libsent/src/voca/voca_load_htkdict.c Fri Feb 11 00:23:52 2011 @@ -19,7 +19,7 @@ * @author Akinobu LEE * @date Fri Feb 18 19:43:06 2005 * - * $Revision: 1.8 $ + * $Revision: 1.9 $ * */ /* @@ -375,8 +375,7 @@ { char *ptmp, *lp = NULL, *p; static char cbuf[MAX_HMMNAME_LEN]; - static HMM_Logical **tmpwseq = NULL; - static int tmpmaxlen; + HMM_Logical **tmpwseq; int len; HMM_Logical *tmplg; boolean pok; @@ -387,10 +386,11 @@ if (strmatch(buf, "DICEND")) return FALSE; /* allocate temporal work area for the first call */ - if (tmpwseq == NULL) { - tmpmaxlen = PHONEMELEN_STEP; - tmpwseq = (HMM_Logical **)mymalloc(sizeof(HMM_Logical *) * tmpmaxlen); + if (winfo->work == NULL) { + winfo->work_num = PHONEMELEN_STEP; + winfo->work = (void *)mybmalloc2(sizeof(HMM_Logical *) * winfo->work_num, &(winfo->mroot)); } + tmpwseq = (HMM_Logical **)winfo->work; /* backup whole line for debug output */ strcpy(bufbak, buf); @@ -551,10 +551,12 @@ pok = FALSE; } else { /* found */ - if (len >= tmpmaxlen) { + if (len >= winfo->work_num) { /* expand wseq area by PHONEMELEN_STEP */ - tmpmaxlen += PHONEMELEN_STEP; - tmpwseq = (HMM_Logical **)myrealloc(tmpwseq, sizeof(HMM_Logical *) * tmpmaxlen); + winfo->work_num += PHONEMELEN_STEP; + winfo->work = (void *)mybmalloc2(sizeof(HMM_Logical *) * winfo->work_num, &(winfo->mroot)); + memcpy(winfo->work, tmpwseq, sizeof(HMM_Logical *) * (winfo->work_num - PHONEMELEN_STEP)); + tmpwseq = (HMM_Logical **)winfo->work; } /* store to temporal buffer */ tmpwseq[len] = tmplg; Index: julius4/libsent/src/voca/voca_malloc.c diff -u julius4/libsent/src/voca/voca_malloc.c:1.2 julius4/libsent/src/voca/voca_malloc.c:1.3 --- julius4/libsent/src/voca/voca_malloc.c:1.2 Tue Dec 18 17:45:54 2007 +++ julius4/libsent/src/voca/voca_malloc.c Fri Feb 11 00:23:52 2011 @@ -12,7 +12,7 @@ * @author Akinobu LEE * @date Fri Feb 18 21:33:29 2005 * - * $Revision: 1.2 $ + * $Revision: 1.3 $ * */ /* @@ -38,6 +38,7 @@ new = (WORD_INFO *)mymalloc(sizeof(WORD_INFO)); new->mroot = NULL; + new->work = NULL; return(new); } From sumomo @ users.sourceforge.jp Fri Feb 11 00:23:52 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Fri, 11 Feb 2011 00:23:52 +0900 Subject: [Julius-cvs 601] CVS update: julius4/libsent/src/hmminfo Message-ID: <1297351432.195263.22698.nullmailer@users.sourceforge.jp> Index: julius4/libsent/src/hmminfo/rdhmmdef.c diff -u julius4/libsent/src/hmminfo/rdhmmdef.c:1.3 julius4/libsent/src/hmminfo/rdhmmdef.c:1.4 --- julius4/libsent/src/hmminfo/rdhmmdef.c:1.3 Mon Jul 7 14:50:11 2008 +++ julius4/libsent/src/hmminfo/rdhmmdef.c Fri Feb 11 00:23:52 2011 @@ -30,7 +30,7 @@ * @author Akinobu LEE * @date Wed Feb 16 00:17:18 2005 * - * $Revision: 1.3 $ + * $Revision: 1.4 $ * */ /* @@ -47,7 +47,7 @@ #define MAXBUFLEN 4096 ///< Maximum length of a line in the input char *rdhmmdef_token; ///< Current token string (GLOBAL) -static char *buf = NULL; ///< Local work area for token reading +static char buf[MAXBUFLEN]; ///< Local work area for token reading static int line; ///< Input Line count /* global functions for rdhmmdef_*.c */ @@ -79,16 +79,9 @@ char * read_token(FILE *fp) { - if (buf != NULL) { - /* already have buffer */ - if ((rdhmmdef_token = mystrtok_quote(NULL, HMMDEF_DELM)) != NULL) { - /* return next token */ - return rdhmmdef_token; - } - } else { - /* init: allocate buffer for the first time */ - buf = (char *)mymalloc(MAXBUFLEN); - line = 1; + if ((rdhmmdef_token = mystrtok_quote(NULL, HMMDEF_DELM)) != NULL) { + /* return next token */ + return rdhmmdef_token; } /* read new 1 line */ if (getl(buf, MAXBUFLEN, fp) == NULL) { @@ -190,7 +183,13 @@ hmm->variance_inversed = FALSE; /* read the first token */ - read_token(fp); + /* read new 1 line */ + line = 1; + if (getl(buf, MAXBUFLEN, fp) == NULL) { + rdhmmdef_token = NULL; + } else { + rdhmmdef_token = mystrtok_quote(buf, HMMDEF_DELM); + } /* the toplevel loop */ while (rdhmmdef_token != NULL) {/* break on EOF */ From sumomo @ users.sourceforge.jp Fri Feb 11 20:16:04 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Fri, 11 Feb 2011 20:16:04 +0900 Subject: [Julius-cvs 602] CVS update: julius4/libjulius/include/julius Message-ID: <1297422964.709593.25558.nullmailer@users.sourceforge.jp> Index: julius4/libjulius/include/julius/wchmm.h diff -u julius4/libjulius/include/julius/wchmm.h:1.4 julius4/libjulius/include/julius/wchmm.h:1.5 --- julius4/libjulius/include/julius/wchmm.h:1.4 Tue Sep 30 12:58:17 2008 +++ julius4/libjulius/include/julius/wchmm.h Fri Feb 11 20:16:04 2011 @@ -28,7 +28,7 @@ * @author Akinobu Lee * @date Sun Sep 18 21:31:32 2005 * - * $Revision: 1.4 $ + * $Revision: 1.5 $ * */ /* @@ -43,16 +43,6 @@ //#define MAXWCNSTEP 40000 ///< Number of states to be allocated at once -/** - * Element of successor word list for LM factoring computation. - * - */ -typedef struct s_cell { - WORD_ID word; ///< N-gram word ID - struct s_cell *next; ///< Pointer to next element, or NULL if terminated -} S_CELL; - - #ifdef PASS1_IWCD /* Cross-word triphone handling */ @@ -251,13 +241,16 @@ #endif /* Successor lists on the tree are stored on sequencial list at @a sclist, and each node has index to the list */ - S_CELL **sclist; ///< List of successor list [scid] - int *sclist2node; ///< Mapping successor list [scid] to node - int scnum; ///< Number of factoring nodes that has successor list + /* sclist and sclen are used at 2-gram factoring only */ + /* scword is used at 1-gram factoring only */ #ifdef UNIGRAM_FACTORING + WORD_ID *scword; ///< successor word[scid] LOGPROB *fscore; ///< List of 1-gram factoring score [-scid] int fsnum; ///< Number of @a fscore #endif + WORD_ID **sclist; ///< List of successor list [scid] + WORD_ID *sclen; ///< Length of each succcessor list [scid] + int scnum; ///< Total number of factoring nodes that has successor list BMALLOC_BASE *malloc_root; ///< Pointer for block memory allocation #ifdef PASS1_IWCD APATNODE *lcdset_category_root; ///< Index of lexicon-dependent category-aware pseudo phone set when used on Julian From sumomo @ users.sourceforge.jp Fri Feb 11 20:16:05 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Fri, 11 Feb 2011 20:16:05 +0900 Subject: [Julius-cvs 603] CVS update: julius4/libjulius/src Message-ID: <1297422965.130677.25580.nullmailer@users.sourceforge.jp> Index: julius4/libjulius/src/factoring_sub.c diff -u julius4/libjulius/src/factoring_sub.c:1.3 julius4/libjulius/src/factoring_sub.c:1.4 --- julius4/libjulius/src/factoring_sub.c:1.3 Wed Jan 28 14:05:52 2009 +++ julius4/libjulius/src/factoring_sub.c Fri Feb 11 20:16:05 2011 @@ -152,7 +152,7 @@ * @author Akinobu LEE * @date Mon Mar 7 23:20:26 2005 * - * $Revision: 1.3 $ + * $Revision: 1.4 $ * */ @@ -169,193 +169,6 @@ /** * - * @brief 木構造化辞書上のあるノードの successor list に単語を追加する. - * - * すでに同じ単語が登録されていれば,新たに登録はされない. - * 単語はIDで昇順に保存される. - * - * @param wchmm [i/o] 木構造化辞書 - * @param node [in] ノード番号 - * @param w [in] 単語ID - * - * - * @brief Add a word to the successor list on a node in tree lexicon. - * Words in lists should be ordered by ID. - * - * @param wchmm [i/o] tree lexicon - * @param node [in] node id - * @param w [in] word id - * - */ -static void -add_successor(WCHMM_INFO *wchmm, int node, WORD_ID w) -{ - S_CELL *sctmp, *sc; - - /* malloc a new successor list element */ - sctmp=(S_CELL *) mymalloc(sizeof(S_CELL)); - /* assign word ID to the new element */ - sctmp->word = w; - /* add the new element to existing list (keeping order) */ - if (wchmm->state[node].scid == 0) { - j_internal_error("add_successor: sclist id not assigned to branch node?\n"); - } - sc = wchmm->sclist[wchmm->state[node].scid]; - if (sc == NULL || sctmp->word < sc->word) { - sctmp->next = sc; - wchmm->sclist[wchmm->state[node].scid] = sctmp; - } else { - for(;sc;sc=sc->next) { - if (sc->next == NULL || sctmp->word < (sc->next)->word) { - if (sctmp->word == sc->word) break; /* avoid duplication */ - sctmp->next = sc->next; - sc->next = sctmp; - break; - } - } - } -} - -/** - * - * 2つのノード上の successor list が一致するかどうかチェックする - * - * @param wchmm [in] 木構造化辞書 - * @param node1 [in] 1つめのノードID - * @param node2 [in] 2つめのノードID - * - * @return 完全に一致すれば TRUE,一致しなければ FALSE. - * - * - * Check if successor lists on two nodes are the same. - * - * @param wchmm [in] tree lexicon - * @param node1 [in] 1st node id - * @param node2 [in] 2nd node id - * - * @return TRUE if they have the same successor list, or FALSE if they differ. - * - */ -static boolean -match_successor(WCHMM_INFO *wchmm, int node1, int node2) -{ - S_CELL *sc1,*sc2; - - /* assume successor is sorted by ID */ - if (wchmm->state[node1].scid == 0 || wchmm->state[node2].scid == 0) { - j_internal_error("match_successor: sclist id not assigned to branch node?\n"); - } - sc1 = wchmm->sclist[wchmm->state[node1].scid]; - sc2 = wchmm->sclist[wchmm->state[node2].scid]; - for (;;) { - if (sc1 == NULL || sc2 == NULL) { - if (sc1 == NULL && sc2 == NULL) { - return TRUE; - } else { - return FALSE; - } - } else if (sc1->word != sc2->word) { - return FALSE; - } - sc1 = sc1->next; - sc2 = sc2->next; - } -} - -/** - * - * 指定ノード上の successor list を空にする. - * - * @param wchmm [i/o] 木構造化辞書 - * @param scid [in] node id - * - * - * Free successor list at the node - * - * @param wchmm [i/o] tree lexicon - * @param scid [in] node id - * - */ -static void -free_successor(WCHMM_INFO *wchmm, int scid) -{ - S_CELL *sc; - S_CELL *sctmp; - - /* free sclist */ - sc = wchmm->sclist[scid]; - while (sc != NULL) { - sctmp = sc; - sc = sc->next; - free(sctmp); - } -} - -/** - * - * 木構造化辞書上からリンクが消された successor list について, - * その実体を削除してリストを詰めるガーベージコレクションを行う. - * - * @param wchmm [i/o] 木構造化辞書 - * - * - * Garbage collection of the successor list, by deleting successor lists - * to which the link was deleted on the lexicon tree. - * - * @param wchmm [i/o] tree lexiton - * - */ -static void -compaction_successor(WCHMM_INFO *wchmm) -{ - int src, dst; - - dst = 1; - for(src=1;srcscnum;src++) { - if (wchmm->state[wchmm->sclist2node[src]].scid <= 0) { - /* already freed, skip */ - continue; - } - if (dst != src) { - wchmm->sclist[dst] = wchmm->sclist[src]; - wchmm->sclist2node[dst] = wchmm->sclist2node[src]; - wchmm->state[wchmm->sclist2node[dst]].scid = dst; - } - dst++; - } - if (debug2_flag) { - jlog("DEBUG: successor list shrinked from %d to %d\n", wchmm->scnum, dst); - } - wchmm->scnum = dst; -} - -/** - * - * successor list 用に割り付けられたメモリ領域を有効な長さに縮める. - * 初期構築時や,1-gram factoring のために削除された successor list 分の - * メモリを解放する. - * - * @param wchmm [i/o] 木構造化辞書 - * - * - * Shrink the memory area that has been allocated for building successor list. - * - * @param wchmm [i/o] tree lexicon - * - */ -static void -shrink_successor(WCHMM_INFO *wchmm) -{ - if (wchmm->sclist) { - wchmm->sclist = (S_CELL **)myrealloc(wchmm->sclist, sizeof(S_CELL *) * wchmm->scnum); - } - if (wchmm->sclist2node) { - wchmm->sclist2node = (int *)myrealloc(wchmm->sclist2node, sizeof(int) * wchmm->scnum); - } -} - -/** - * * 木構造化辞書上の全ノードに successor list を構築するメイン関数 * * @param wchmm [i/o] 木構造化辞書 @@ -375,9 +188,13 @@ { int node; WORD_ID w; - int i; - boolean *freemark; + int i, j; int s; + WORD_ID *scnumlist; + WORD_ID *sclen; + int scnum, new_scnum; + int *scidmap; + boolean *freemark; jlog("STAT: make successor lists for factoring\n"); @@ -385,49 +202,38 @@ /* initialize node->sclist index on wchmm tree */ for (node=0;noden;node++) wchmm->state[node].scid = 0; - /* parse the tree to get the maximum size of successor list */ - s = 1; + /* parse the tree to assign unique scid and get the maximum size of + successor list */ + scnum = 1; for (w=0;wwinfo->num;w++) { for (i=0;iwinfo->wlen[w];i++) { if (wchmm->state[wchmm->offset[w][i]].scid == 0) { - wchmm->state[wchmm->offset[w][i]].scid = s; - s++; + wchmm->state[wchmm->offset[w][i]].scid = scnum; + scnum++; } } if (wchmm->state[wchmm->wordend[w]].scid == 0) { - wchmm->state[wchmm->wordend[w]].scid = s; - s++; + wchmm->state[wchmm->wordend[w]].scid = scnum; + scnum++; } } - wchmm->scnum = s; if (debug2_flag) { - jlog("DEBUG: initial successor list size = %d\n", wchmm->scnum); + jlog("DEBUG: initial successor list size = %d\n", scnum); } - /* allocate successor list for the maximum size */ - wchmm->sclist = (S_CELL **)mymalloc(sizeof(S_CELL *) * wchmm->scnum); - for (i=1;iscnum;i++) wchmm->sclist[i] = NULL; - wchmm->sclist2node = (int *)mymalloc(sizeof(int) * wchmm->scnum); - - /* allocate misc. work area */ - freemark = (boolean *)mymalloc(sizeof(boolean) * wchmm->scnum); - for (i=1;iscnum;i++) freemark[i] = FALSE; - - /* 2. make initial successor list: assign at all possible nodes */ + /* 2. count number of each successor */ + sclen = (WORD_ID *)mymalloc(sizeof(WORD_ID) * scnum); + for (i=1;iwinfo->num;w++) { - /* at each start node of phonemes */ for (i=0;iwinfo->wlen[w];i++) { - wchmm->sclist2node[wchmm->state[wchmm->offset[w][i]].scid] = wchmm->offset[w][i]; - add_successor(wchmm, wchmm->offset[w][i], w); + sclen[wchmm->state[wchmm->offset[w][i]].scid]++; } - /* at word end */ - wchmm->sclist2node[wchmm->state[wchmm->wordend[w]].scid] = wchmm->wordend[w]; - add_successor(wchmm, wchmm->wordend[w], w); + sclen[wchmm->state[wchmm->wordend[w]].scid]++; } - - /* 3. erase unnecessary successor list */ - /* sucessor list same as the previous node is not needed, so */ - /* parse lexicon tree from every leaf to find the same succesor list */ + + /* 3. delete bogus successor lists */ + freemark = (boolean *)mymalloc(sizeof(boolean) * scnum); + for (i=1;iwinfo->num;w++) { node = wchmm->wordend[w]; /* begin from the word end node */ i = wchmm->winfo->wlen[w]-1; @@ -437,30 +243,82 @@ i--; continue; } - if (match_successor(wchmm, node, wchmm->offset[w][i])) { + if (wchmm->state[node].scid == 0) break; /* already parsed */ + if (sclen[wchmm->state[node].scid] == sclen[wchmm->state[wchmm->offset[w][i]].scid]) { freemark[wchmm->state[node].scid] = TRUE; /* mark the node */ + wchmm->state[node].scid = 0; } -/* - * if (freemark[wchmm->offset[w][i]] != FALSE) { - * break; - * } - */ node = wchmm->offset[w][i]; i--; } } - /* really free */ - for (i=1;iscnum;i++) { - if (freemark[i] == TRUE) { - free_successor(wchmm, i); - /* reset node -> sclist link */ - wchmm->state[wchmm->sclist2node[i]].scid = 0; + /* build compaction map */ + scidmap = (int *)mymalloc(sizeof(int) * scnum); + scidmap[0] = 0; + j = 1; + for (i=1;in;node++) { + if (wchmm->state[node].scid > 0) { + wchmm->state[node].scid = scidmap[wchmm->state[node].scid]; + } + } + wchmm->sclen = (WORD_ID *)mybmalloc2(sizeof(WORD_ID) * new_scnum, &(wchmm->malloc_root)); + for (i=1;isclen[scidmap[i]] = sclen[i]; + } + wchmm->scnum = new_scnum; + + free(scidmap); free(freemark); + free(sclen); + + /* 5. now index completed, make word list for each list */ + wchmm->sclist = (WORD_ID **)mybmalloc2(sizeof(WORD_ID *) * wchmm->scnum, &(wchmm->malloc_root)); + scnumlist = (WORD_ID *)mymalloc(sizeof(WORD_ID) * wchmm->scnum); + for(i=1;iscnum;i++) { + wchmm->sclist[i] = (WORD_ID *)mybmalloc2(sizeof(WORD_ID) * wchmm->sclen[i], &(wchmm->malloc_root)); + scnumlist[i] = 0; + } + { + int scid; + for (w=0;wwinfo->num;w++) { + for (i=0;iwinfo->wlen[w];i++) { + scid = wchmm->state[wchmm->offset[w][i]].scid; + if (scid != 0) { + wchmm->sclist[scid][scnumlist[scid]] = w; + scnumlist[scid]++; + if (scnumlist[scid] > wchmm->sclen[scid]) { + jlog("hogohohoho\n"); + exit(1); + } + } + } + /* at word end */ + scid = wchmm->state[wchmm->wordend[w]].scid; + if (scid != 0) { + wchmm->sclist[scid][scnumlist[scid]] = w; + scnumlist[scid]++; + if (scnumlist[scid] > wchmm->sclen[scid]) { + jlog("hogohohoho\n"); + exit(1); + } + } + } + } + free(scnumlist); jlog("STAT: done\n"); } @@ -502,6 +360,7 @@ int i, j, n, f; int s; LOGPROB tmpprob; + WORD_ID *mtmp; jlog("STAT: make successor lists for unigram factoring\n"); @@ -515,10 +374,8 @@ jlog("DEBUG: successor list size = %d\n", wchmm->scnum); } - /* allocate successor list */ - wchmm->sclist = (S_CELL **)mymalloc(sizeof(S_CELL *) * wchmm->scnum); - for (i=1;iscnum;i++) wchmm->sclist[i] = NULL; - /* sclist2node is not used */ + /* allocate successor list for 1-gram factoring */ + wchmm->scword = (WORD_ID *)mybmalloc2(sizeof(WORD_ID) * wchmm->scnum, &(wchmm->malloc_root)); /* 2. make successor list, and count needed fscore num */ f = 1; @@ -532,17 +389,18 @@ } if (wchmm->state[node].scid == 0) { /* not assigned */ /* new node found, assign new and exit here */ - wchmm->state[node].scid = s++; + wchmm->state[node].scid = s; + wchmm->scword[s] = w; + s++; if (s > wchmm->scnum) { jlog("InternalError: make_successor_list_unigram_factoring: scid num exceeded?\n"); return; } - add_successor(wchmm, node, w); break; } else if (wchmm->state[node].scid > 0) { - /* that node has sclist */ + /* that node has successor */ /* move it to the current first isolated node in that word */ - w2 = wchmm->sclist[wchmm->state[node].scid]->word; + w2 = wchmm->scword[wchmm->state[node].scid]; for(j=i+1;jwinfo->wlen[w2] + 1;j++) { if (j < wchmm->winfo->wlen[w2]) { node2 = wchmm->offset[w2][j]; @@ -550,7 +408,7 @@ node2 = wchmm->wordend[w2]; } if (wchmm->state[node2].scid == 0) { /* not assigned */ - /* move sclist to there */ + /* move successor to there */ wchmm->state[node2].scid = wchmm->state[node].scid; break; } @@ -732,9 +590,6 @@ LM_PROB_CACHE *l; WORD_ID wnum; - /* finally shrink the memory area of successor list here */ - shrink_successor(wchmm); - /* for word-internal */ l = &(wchmm->lmcache); @@ -880,6 +735,8 @@ wchmm->isolatenum = num; } +#ifndef FAST_FACTOR1_SUCCESSOR_LIST + /** * * @brief 木構造化辞書上の 1-gram factoring 値を計算して格納する. @@ -977,6 +834,8 @@ compaction_successor(wchmm); } +#endif + #else /* ~UNIGRAM_FACTORING */ /** @@ -1004,27 +863,31 @@ static LOGPROB calc_successor_prob(WCHMM_INFO *wchmm, WORD_ID lastword, int node) { - S_CELL *sc; LOGPROB tmpprob, maxprob; - WORD_ID lw; + WORD_ID lw, w; + int i; + int scid; maxprob = LOG_ZERO; if (wchmm->ngram) { lw = wchmm->winfo->wton[lastword]; } - for (sc = wchmm->sclist[wchmm->state[node].scid]; sc; sc = sc->next) { + scid = wchmm->state[node].scid; + + for (i = 0; i < wchmm->sclen[scid]; i++) { + w = wchmm->sclist[scid][i]; if (wchmm->ngram) { - tmpprob = (*(wchmm->ngram->bigram_prob))(wchmm->ngram, lw , wchmm->winfo->wton[sc->word]) + tmpprob = (*(wchmm->ngram->bigram_prob))(wchmm->ngram, lw , wchmm->winfo->wton[w]) #ifdef CLASS_NGRAM - + wchmm->winfo->cprob[sc->word] + + wchmm->winfo->cprob[w] #endif ; } else { tmpprob = LOG_ZERO; } if (wchmm->lmvar == LM_NGRAM_USER) { - tmpprob = (*(wchmm->bi_prob_user))(wchmm->winfo, lastword, sc->word, tmpprob); + tmpprob = (*(wchmm->bi_prob_user))(wchmm->winfo, lastword, w, tmpprob); } if (maxprob < tmpprob) maxprob = tmpprob; } @@ -1102,7 +965,7 @@ /* return precise 2-gram score */ if (last_nword != l->lastwcache[scid]) { /* calc and cache */ - w = (wchmm->sclist[scid])->word; + w = wchmm->scword[scid]; if (wchmm->ngram) { maxprob = (*(wchmm->ngram->bigram_prob))(wchmm->ngram, last_nword, wchmm->winfo->wton[w]) #ifdef CLASS_NGRAM @@ -1251,7 +1114,7 @@ /* should not happen!!! below is just for debugging */ j_internal_error("max_successor_prob_iw: isolated (not shared) tree root node has unigram factoring value??\n"); } else { - w = (wchmm->sclist[wchmm->state[node].scid])->word; + w = wchmm->scword[wchmm->state[node].scid]; if (wchmm->ngram) { p = (*(wchmm->ngram->bigram_prob))(wchmm->ngram, last_nword, wchmm->winfo->wton[w]) #ifdef CLASS_NGRAM @@ -1333,19 +1196,22 @@ can_succeed(WCHMM_INFO *wchmm, WORD_ID lastword, int node) { int lc; - S_CELL *sc; + int i; + int s; /* return TRUE if at least one subtree word can connect */ + s = wchmm->state[node].scid; + if (lastword == WORD_INVALID) { /* case at beginning-of-word */ - for (sc=wchmm->sclist[wchmm->state[node].scid];sc;sc=sc->next) { - if (dfa_cp_begin(wchmm->dfa, sc->word) == TRUE) return(TRUE); + for (i = 0; i < wchmm->sclen[s]; i++) { + if (dfa_cp_begin(wchmm->dfa, wchmm->sclist[s][i]) == TRUE) return(TRUE); } return(FALSE); } else { lc = wchmm->winfo->wton[lastword]; - for (sc=wchmm->sclist[wchmm->state[node].scid];sc;sc=sc->next) { - if (dfa_cp(wchmm->dfa, lc, sc->word) == TRUE) return(TRUE); + for (i = 0; i < wchmm->sclen[s]; i++) { + if (dfa_cp(wchmm->dfa, lc, wchmm->sclist[s][i]) == TRUE) return(TRUE); } return(FALSE); } Index: julius4/libjulius/src/wchmm.c diff -u julius4/libjulius/src/wchmm.c:1.7 julius4/libjulius/src/wchmm.c:1.8 --- julius4/libjulius/src/wchmm.c:1.7 Wed Jan 28 14:05:52 2009 +++ julius4/libjulius/src/wchmm.c Fri Feb 11 20:16:05 2011 @@ -31,7 +31,7 @@ * @author Akinobu Lee * @date Mon Sep 19 23:39:15 2005 * - * $Revision: 1.7 $ + * $Revision: 1.8 $ * */ /* @@ -136,11 +136,12 @@ wchmm->isolatenum = 0; #endif if (!wchmm->category_tree) { - wchmm->sclist = NULL; - wchmm->sclist2node = NULL; #ifdef UNIGRAM_FACTORING + wchmm->scword = NULL; wchmm->fscore = NULL; #endif + wchmm->sclist = NULL; + wchmm->sclen = NULL; } wchmm->n = 0; @@ -212,28 +213,16 @@ void wchmm_free(WCHMM_INFO *w) { - S_CELL *sc, *sctmp; int i; /* wchmm->state[i].ac malloced by mybmalloc2() */ /* wchmm->offset[][] malloced by mybmalloc2() */ #ifdef PASS1_IWCD /* LRC_INFO, RC_INFO in wchmm->state[i].outsty malloced by mybmalloc2() */ #endif + /* wchmm->sclist[][] and wchmm->sclen[] malloced by mybmalloc2() */ /* they all will be freed by a single mybfree2() call */ mybfree2(&(w->malloc_root)); if (!w->category_tree) { - if (w->sclist != NULL) { - for(i=1;iscnum;i++) { - sc = w->sclist[i]; - while(sc) { - sctmp = sc->next; - free(sc); - sc = sctmp; - } - } - free(w->sclist); - } - if (w->sclist2node != NULL) free(w->sclist2node); #ifdef UNIGRAM_FACTORING if (w->fscore != NULL) free(w->fscore); #endif @@ -1724,12 +1713,6 @@ } #endif /* UNIGRAM_FACTORING */ - /* sclist2node is no longer used */ - if (wchmm->sclist2node != NULL) { - free(wchmm->sclist2node); - wchmm->sclist2node = NULL; - } - } jlog("STAT: done\n"); @@ -1976,12 +1959,6 @@ } #endif /* UNIGRAM_FACTORING */ - /* sclist2node is no longer used */ - if (wchmm->sclist2node != NULL) { - free(wchmm->sclist2node); - wchmm->sclist2node = NULL; - } - } //jlog("STAT: done\n"); @@ -2049,8 +2026,16 @@ } #endif if (!wchmm->category_tree) { - jlog("STAT: %9d bytes: wchmm->sclist[]\n", wchmm->scnum * sizeof(S_CELL *)); - jlog("STAT: %9d bytes: wchmm->sclist2node[]\n", wchmm->scnum * sizeof(int)); + int c = 0; +#ifdef UNIGRAM_FACTORING + jlog("STAT: %9d bytes: wchmm->scword[]\n", sizeof(WORD_ID) * wchmm->scnum); +#else + for(i=1;iscnum;i++) { + c += wchmm->sclen[i]; + } + jlog("STAT: %9d bytes: wchmm->sclist[]\n", c * sizeof(WORD_ID) + wchmm->scnum * sizeof(WORD_ID *)); + jlog("STAT: %9d bytes: wchmm->sclen[]\n", wchmm->scnum * sizeof(WORD_ID)); +#endif #ifdef UNIGRAM_FACTORING if (wchmm->lmtype == LM_PROB) { jlog("STAT: %9d bytes: wchmm->fscore[]\n", wchmm->fsnum * sizeof(LOGPROB)); @@ -2069,11 +2054,6 @@ } jlog("STAT: %9d bytes: A_CELL2\n", count); } - if (!wchmm->category_tree) { - jlog("STAT: %9d bytes: sclist\n", wchmm->scnum * sizeof(S_CELL *)); - jlog("STAT: %9d bytes: sclist2node\n", wchmm->scnum * sizeof(int)); - } - } #endif /* WCHMM_SIZE_CHECK */ Index: julius4/libjulius/src/wchmm_check.c diff -u julius4/libjulius/src/wchmm_check.c:1.3 julius4/libjulius/src/wchmm_check.c:1.4 --- julius4/libjulius/src/wchmm_check.c:1.3 Fri Sep 18 17:31:08 2009 +++ julius4/libjulius/src/wchmm_check.c Fri Feb 11 20:16:05 2011 @@ -24,7 +24,7 @@ * @author Akinobu Lee * @date Sat Sep 24 15:45:06 2005 * - * $Revision: 1.3 $ + * $Revision: 1.4 $ * */ /* @@ -235,8 +235,7 @@ static void print_wchmm_s_successor(WCHMM_INFO *wchmm, int node) { - S_CELL *sc; - int i = 0; + int i = 0, j; int scid; scid = wchmm->state[node].scid; @@ -250,12 +249,17 @@ } #endif } else { +#ifdef UNIGRAM_FACTORING printf("successor id: %d\n", scid); - for (sc=wchmm->sclist[scid];sc;sc=sc->next) { - printf(" %d\n",sc->word); + printf(" %d\n", wchmm->scword[scid]); +#else + printf("successor id: %d\n", scid); + for (j = 0; j < wchmm->sclen[scid]; j++) { + printf(" %d\n", wchmm->sclist[scid][j]); i++; } printf(" total %d successors\n",i); +#endif } } From sumomo @ users.sourceforge.jp Sat Feb 12 16:44:09 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Sat, 12 Feb 2011 16:44:09 +0900 Subject: [Julius-cvs 604] CVS update: julius4/libjulius/include/julius Message-ID: <1297496649.665790.11044.nullmailer@users.sourceforge.jp> Index: julius4/libjulius/include/julius/define.h diff -u julius4/libjulius/include/julius/define.h:1.4 julius4/libjulius/include/julius/define.h:1.5 --- julius4/libjulius/include/julius/define.h:1.4 Wed Jan 28 14:05:52 2009 +++ julius4/libjulius/include/julius/define.h Sat Feb 12 16:44:09 2011 @@ -27,7 +27,7 @@ * @author Akinobu LEE * @date Mon Mar 7 15:17:26 2005 * - * $Revision: 1.4 $ + * $Revision: 1.5 $ * */ /* @@ -282,6 +282,11 @@ */ #define FAST_FACTOR1_SUCCESSOR_LIST +/** + * Enable score based pruning at the 1st pass. + * + */ +#define SCORE_PRUNING #endif /* __J_DEFINE_H__ */ Index: julius4/libjulius/include/julius/jconf.h diff -u julius4/libjulius/include/julius/jconf.h:1.9 julius4/libjulius/include/julius/jconf.h:1.10 --- julius4/libjulius/include/julius/jconf.h:1.9 Sat Feb 5 18:00:41 2011 +++ julius4/libjulius/include/julius/jconf.h Sat Feb 12 16:44:09 2011 @@ -23,7 +23,7 @@ * @author Akinobu Lee * @date Fri Feb 16 13:42:28 2007 * - * $Revision: 1.9 $ + * $Revision: 1.10 $ * */ /* @@ -470,11 +470,20 @@ */ struct { /** - * Beam width of 1st pass. If value is -1 (not specified), system - * will guess the value from dictionary size. If 0, a possible - * maximum value will be assigned to do full search. + * Beam width of rank pruning for the 1st pass. If value is -1 + * (not specified), system will guess the value from dictionary + * size. If 0, a possible maximum value will be assigned to do + * full search. */ int specified_trellis_beam_width; + +#ifdef SCORE_PRUNING + /** + * Another beam width for score pruning at the 1st pass. If value + * is -1, or not specified, score pruning will be disabled. + */ +#endif + LOGPROB score_pruning_width; #if defined(WPAIR) && defined(WPAIR_KEEP_NLIMIT) /** Index: julius4/libjulius/include/julius/recog.h diff -u julius4/libjulius/include/julius/recog.h:1.12 julius4/libjulius/include/julius/recog.h:1.13 --- julius4/libjulius/include/julius/recog.h:1.12 Sat Feb 5 18:00:41 2011 +++ julius4/libjulius/include/julius/recog.h Sat Feb 12 16:44:09 2011 @@ -70,7 +70,7 @@ * @author Akinobu Lee * @date Fri Feb 16 13:42:28 2007 * - * $Revision: 1.12 $ + * $Revision: 1.13 $ * */ /* @@ -123,6 +123,11 @@ int n_end; ///< end index of in-beam nodes on @a tindex int tl; ///< Current work area id (0 or 1, swapped for each frame) int tn; ///< Next work area id (0 or 1, swapped for each frame) +#ifdef SCORE_PRUNING + LOGPROB score_pruning_max; ///< Maximum score at current frame + LOGPROB score_pruning_threshold;///< Score threshold for score pruning + int score_pruning_count; ///< Number of tokens pruned by score (debug) +#endif /* Active token list */ TOKENID *token; ///< Active token list that holds currently assigned tokens for each tree node From sumomo @ users.sourceforge.jp Sat Feb 12 16:44:09 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Sat, 12 Feb 2011 16:44:09 +0900 Subject: [Julius-cvs 605] CVS update: julius4/libjulius/src Message-ID: <1297496649.844149.11060.nullmailer@users.sourceforge.jp> Index: julius4/libjulius/src/beam.c diff -u julius4/libjulius/src/beam.c:1.14 julius4/libjulius/src/beam.c:1.15 --- julius4/libjulius/src/beam.c:1.14 Fri Jan 8 17:29:11 2010 +++ julius4/libjulius/src/beam.c Sat Feb 12 16:44:09 2011 @@ -42,7 +42,7 @@ * @author Akinobu LEE * @date Tue Feb 22 17:00:45 2005 * - * $Revision: 1.14 $ + * $Revision: 1.15 $ * */ /* @@ -1875,6 +1875,11 @@ } #endif +#ifdef SCORE_PRUNING + d->score_pruning_threshold = LOG_ZERO; + d->score_pruning_count = 0; +#endif + return TRUE; } @@ -2514,7 +2519,12 @@ if (wchmm->winfo->is_transparent[sword] && wchmm->winfo->is_transparent[d->wordend_best_last_cword]) { tmpsum += d->lm_penalty_trans; } - +#ifdef SCORE_PRUNING + if (tmpsum < d->score_pruning_threshold) { + d->score_pruning_count++; + continue; + } +#endif if (wchmm->hmminfo->multipath) { /* since top node has no ouput, we should go one more step further */ if (wchmm->self_a[next_node] != LOG_ZERO) { @@ -2605,6 +2615,7 @@ FSBeam *d; int j; TOKEN2 *tk; + LOGPROB minscore; /* local copied variables */ int tn, tl; @@ -2686,6 +2697,12 @@ /* tk: token data node: lexicon tree node ID that holds the 'tk' */ tk = &(d->tlist[tl][d->tindex[tl][j]]); if (tk->score <= LOG_ZERO) continue; /* invalid node */ +#ifdef SCORE_PRUNING + if (tk->score < d->score_pruning_threshold) { + d->score_pruning_count++; + continue; + } +#endif node = tk->node; /*********************************/ /* 2.1. 単語内遷移 */ @@ -2706,7 +2723,12 @@ for(j = d->n_start; j <= d->n_end; j++) { tk = &(d->tlist[tn][d->tindex[tn][j]]); node = tk->node; - +#ifdef SCORE_PRUNING + if (tk->score < d->score_pruning_threshold) { + d->score_pruning_count++; + continue; + } +#endif /* 遷移元ノードが単語終端ならば */ /* if source node is end state of a word, */ if (wchmm->stend[node] != WORD_INVALID) { @@ -2761,6 +2783,12 @@ /* tk: token data node: lexicon tree node ID that holds the 'tk' */ tk = &(d->tlist[tl][d->tindex[tl][j]]); if (tk->score <= LOG_ZERO) continue; /* invalid node */ +#ifdef SCORE_PRUNING + if (tk->score < d->score_pruning_threshold) { + d->score_pruning_count++; + continue; + } +#endif node = tk->node; /*********************************/ @@ -2838,6 +2866,10 @@ /* 今扱っているのが入力の最終フレームの場合出力確率は計算しない */ /* don't calculate the last frame (transition only) */ +#ifdef SCORE_PRUNING + d->score_pruning_max = LOG_ZERO; + minscore = 0.0; +#endif if (wchmm->hmminfo->multipath) { if (! final_for_multipath) { for (j = 0; j < d->tnum[tn]; j++) { @@ -2845,15 +2877,31 @@ /* skip non-output state */ if (wchmm->state[tk->node].out.state == NULL) continue; tk->score += outprob_style(wchmm, tk->node, tk->last_tre->wid, t, param); +#ifdef SCORE_PRUNING + if (d->score_pruning_max < tk->score) d->score_pruning_max = tk->score; + if (minscore > tk->score) minscore = tk->score; +#endif } } } else { for (j = 0; j < d->tnum[tn]; j++) { tk = &(d->tlist[tn][d->tindex[tn][j]]); tk->score += outprob_style(wchmm, tk->node, tk->last_tre->wid, t, param); +#ifdef SCORE_PRUNING + if (d->score_pruning_max < tk->score) d->score_pruning_max = tk->score; + if (minscore > tk->score) minscore = tk->score; +#endif } } - +#ifdef SCORE_PRUNING + if (r->config->pass1.score_pruning_width >= 0.0) { + d->score_pruning_threshold = d->score_pruning_max - r->config->pass1.score_pruning_width; + //printf("width=%f, tnum=%d\n", d->score_pruning_max - minscore, d->tnum[tn]); + } else { + // disable score pruning + d->score_pruning_threshold = LOG_ZERO; + } +#endif /*******************************************************/ /* 4. スコアでトークンをソートしビーム幅分の上位を決定 */ /* sort tokens by score up to beam width */ @@ -2980,6 +3028,10 @@ } } +#ifdef SCORE_PRUNING + printf("--- %d tokens pruned by score beam\n", d->score_pruning_count); + d->score_pruning_threshold = d->score_pruning_max - 100.0; +#endif } Index: julius4/libjulius/src/default.c diff -u julius4/libjulius/src/default.c:1.11 julius4/libjulius/src/default.c:1.12 --- julius4/libjulius/src/default.c:1.11 Sat Feb 5 18:00:41 2011 +++ julius4/libjulius/src/default.c Sat Feb 12 16:44:09 2011 @@ -17,7 +17,7 @@ * @author Akinobu Lee * @date Fri Feb 16 15:05:43 2007 * - * $Revision: 1.11 $ + * $Revision: 1.12 $ * */ /* @@ -235,6 +235,9 @@ j->lmp.lmp_specified = FALSE; j->pass1.specified_trellis_beam_width = -1; +#ifdef SCORE_PRUNING + j->pass1.score_pruning_width = -1.0; +#endif #if defined(WPAIR) && defined(WPAIR_KEEP_NLIMIT) j->pass1.wpair_keep_nlimit = 3; #endif Index: julius4/libjulius/src/m_info.c diff -u julius4/libjulius/src/m_info.c:1.10 julius4/libjulius/src/m_info.c:1.11 --- julius4/libjulius/src/m_info.c:1.10 Sat Feb 5 18:00:41 2011 +++ julius4/libjulius/src/m_info.c Sat Feb 12 16:44:09 2011 @@ -12,7 +12,7 @@ * @author Akinobu Lee * @date Thu May 12 14:14:01 2005 * - * $Revision: 1.10 $ + * $Revision: 1.11 $ * */ /* @@ -575,6 +575,13 @@ } else { jlog("\n"); } +#ifdef SCORE_PRUNING + if (r->config->pass1.score_pruning_width < 0.0) { + jlog("\t(-bs)score pruning thres= disabled\n"); + } else { + jlog("\t(-bs)score pruning thres= %f\n", r->config->pass1.score_pruning_width); + } +#endif jlog("\t(-n)search candidate num= %d\n", r->config->pass2.nbest); jlog("\t(-s) search stack size = %d\n", r->config->pass2.stack_size); jlog("\t(-m) search overflow = after %d hypothesis poped\n", r->config->pass2.hypo_overflow); Index: julius4/libjulius/src/m_options.c diff -u julius4/libjulius/src/m_options.c:1.21 julius4/libjulius/src/m_options.c:1.22 --- julius4/libjulius/src/m_options.c:1.21 Mon Feb 7 13:56:14 2011 +++ julius4/libjulius/src/m_options.c Sat Feb 12 16:44:09 2011 @@ -18,7 +18,7 @@ * @author Akinobu Lee * @date Thu May 12 18:52:07 2005 * - * $Revision: 1.21 $ + * $Revision: 1.22 $ * */ /* @@ -559,6 +559,13 @@ jlog("WARNING: m_options: SCAN_BEAM disabled, \"-sb\" ignored\n"); #endif continue; +#ifdef SCORE_PRUNING + } else if (strmatch(argv[i],"-bs")) { /* score beam width for 1st pass */ + if (!check_section(jconf, argv[i], JCONF_OPT_SR)) return FALSE; + GET_TMPARG; + jconf->searchnow->pass1.score_pruning_width = atof(tmparg); + continue; +#endif } else if (strmatch(argv[i],"-discount")) { /* (bogus) */ jlog("WARNING: m_options: option \"-discount\" is now bogus, ignored\n"); continue; Index: julius4/libjulius/src/m_usage.c diff -u julius4/libjulius/src/m_usage.c:1.12 julius4/libjulius/src/m_usage.c:1.13 --- julius4/libjulius/src/m_usage.c:1.12 Tue Feb 10 17:15:48 2009 +++ julius4/libjulius/src/m_usage.c Sat Feb 12 16:44:09 2011 @@ -12,7 +12,7 @@ * @author Akinobu Lee * @date Fri May 13 15:04:34 2005 * - * $Revision: 1.12 $ + * $Revision: 1.13 $ * */ /* @@ -263,6 +263,8 @@ fprintf(fp, " [-forcedict] ignore error entry and keep running\n"); fprintf(fp, " [-iwspword] (n-gram) add short-pause word for inter-word CD sp\n"); fprintf(fp, " [-iwspentry entry] (n-gram) word entry for \"-iwspword\" (%s)\n", IWSPENTRY_DEFAULT); + fprintf(fp, " [-adddict dictfile] (n-gram) load extra dictionary\n"); + fprintf(fp, " [-addentry entry] (n-gram) load extra word entry\n"); fprintf(fp, "\n Isolated Word Recognition:\n"); fprintf(fp, " -w file[,file2...] (list of) wordlist file name(s)\n"); @@ -283,6 +285,10 @@ fprintf(fp, "\n Search Parameters for the First Pass:\n"); fprintf(fp, " [-b beamwidth] beam width (by state num) (guessed)\n"); fprintf(fp, " (0: full search, -1: force guess)\n"); +#ifdef SCORE_PRUNING + fprintf(fp, " [-bs score_width] beam width (by score offset) (disabled)\n"); + fprintf(fp, " (-1: disable)\n"); +#endif #ifdef WPAIR # ifdef WPAIR_KEEP_NLIMIT fprintf(fp, " [-nlimit N] keeps only N tokens on each state (%d)\n", jconf->search_root->pass1.wpair_keep_nlimit); From sumomo @ users.sourceforge.jp Sun Feb 13 14:02:00 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Sun, 13 Feb 2011 14:02:00 +0900 Subject: [Julius-cvs 606] CVS update: julius4/libjulius/src Message-ID: <1297573320.658930.7755.nullmailer@users.sourceforge.jp> Index: julius4/libjulius/src/beam.c diff -u julius4/libjulius/src/beam.c:1.15 julius4/libjulius/src/beam.c:1.16 --- julius4/libjulius/src/beam.c:1.15 Sat Feb 12 16:44:09 2011 +++ julius4/libjulius/src/beam.c Sun Feb 13 14:02:00 2011 @@ -42,7 +42,7 @@ * @author Akinobu LEE * @date Tue Feb 22 17:00:45 2005 * - * $Revision: 1.15 $ + * $Revision: 1.16 $ * */ /* @@ -3029,8 +3029,7 @@ } #ifdef SCORE_PRUNING - printf("--- %d tokens pruned by score beam\n", d->score_pruning_count); - d->score_pruning_threshold = d->score_pruning_max - 100.0; + if (debug2_flag) jlog("STAT: %d tokens pruned by score beam\n", d->score_pruning_count); #endif } Index: julius4/libjulius/src/m_fusion.c diff -u julius4/libjulius/src/m_fusion.c:1.17 julius4/libjulius/src/m_fusion.c:1.18 --- julius4/libjulius/src/m_fusion.c:1.17 Mon Feb 7 13:56:14 2011 +++ julius4/libjulius/src/m_fusion.c Sun Feb 13 14:02:00 2011 @@ -20,7 +20,7 @@ * @author Akinobu Lee * @date Thu May 12 13:31:47 2005 * - * $Revision: 1.17 $ + * $Revision: 1.18 $ * */ /* @@ -122,12 +122,17 @@ #ifdef PASS1_IWCD /* make state clusters of same context for inter-word triphone approx. */ if (hmminfo->is_triphone) { - jlog("STAT: making pseudo bi/mono-phone for IW-triphone\n"); - if (make_cdset(hmminfo) == FALSE) { - jlog("ERROR: m_fusion: failed to make context-dependent state set\n"); - hmminfo_free(hmminfo); - return NULL; + if (hmminfo->cdset_root == NULL) { + jlog("STAT: making pseudo bi/mono-phone for IW-triphone\n"); + if (make_cdset(hmminfo) == FALSE) { + jlog("ERROR: m_fusion: failed to make context-dependent state set\n"); + hmminfo_free(hmminfo); + return NULL; + } + } else { + jlog("STAT: pseudo phones are loaded from binary hmmlist file\n"); } + /* add those `pseudo' biphone and monophone to the logical HMM names */ /* they points not to the defined HMM, but to the CD_Set structure */ hmm_add_pseudo_phones(hmminfo); From sumomo @ users.sourceforge.jp Sun Feb 13 14:02:00 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Sun, 13 Feb 2011 14:02:00 +0900 Subject: [Julius-cvs 607] CVS update: julius4/libsent/include/sent Message-ID: <1297573320.738394.7763.nullmailer@users.sourceforge.jp> Index: julius4/libsent/include/sent/htk_hmm.h diff -u julius4/libsent/include/sent/htk_hmm.h:1.7 julius4/libsent/include/sent/htk_hmm.h:1.8 --- julius4/libsent/include/sent/htk_hmm.h:1.7 Fri Sep 18 17:31:08 2009 +++ julius4/libsent/include/sent/htk_hmm.h Sun Feb 13 14:02:00 2011 @@ -16,7 +16,7 @@ * @author Akinobu LEE * @date Thu Feb 10 19:36:47 2005 * - * $Revision: 1.7 $ + * $Revision: 1.8 $ * */ /* @@ -112,6 +112,7 @@ char *name; ///< Name (NULL if not defined as Macro) short statenum; ///< Number of state PROB **a; ///< Matrix of transition probabilities + int id; ///< Uniq transition id starting from 0 struct _HTK_HMM_trans *next; ///< Pointer to next data, NULL if last } HTK_HMM_Trans; @@ -266,6 +267,7 @@ } CD_Set; /// Top structure to hold all the %HMM sets typedef struct { + boolean binary_malloc; ///< TRUE if read from binary APATNODE *cdtree; ///< Root of index tree for name lookup } HMM_CDSET_INFO; //@} @@ -389,6 +391,7 @@ LOGPROB iwsp_penalty; ///< Extra ransition penalty for interword skippable short pause insertion for multi-path mode boolean variance_inversed; ///< TRUE if variances are inversed + int totaltransnum; ///< Total number of transitions int totalmixnum; ///< Total number of defined mixtures int totalstatenum; ///< Total number of states int totalhmmnum; ///< Total number of physical %HMM @@ -410,6 +413,8 @@ boolean has_msd; ///< TRUE if this model contains MSD part #endif + void *hook; ///< General purpose hook + //@} } HTK_HMM_INFO; From sumomo @ users.sourceforge.jp Sun Feb 13 14:02:00 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Sun, 13 Feb 2011 14:02:00 +0900 Subject: [Julius-cvs 608] CVS update: julius4/libsent/src/hmminfo Message-ID: <1297573320.845040.7780.nullmailer@users.sourceforge.jp> Index: julius4/libsent/src/hmminfo/cdset.c diff -u julius4/libsent/src/hmminfo/cdset.c:1.4 julius4/libsent/src/hmminfo/cdset.c:1.5 --- julius4/libsent/src/hmminfo/cdset.c:1.4 Tue Sep 30 12:58:18 2008 +++ julius4/libsent/src/hmminfo/cdset.c Sun Feb 13 14:02:00 2011 @@ -60,7 +60,7 @@ * @author Akinobu LEE * @date Tue Feb 15 17:58:54 2005 * - * $Revision: 1.4 $ + * $Revision: 1.5 $ * */ /* @@ -87,6 +87,7 @@ static void cdset_init(HTK_HMM_INFO *hmminfo) { + hmminfo->cdset_info.binary_malloc = FALSE; hmminfo->cdset_info.cdtree = NULL; } @@ -164,6 +165,7 @@ { int i; CD_Set *a; + int j; a = ptr; printf("name: %s\n", a->name); @@ -174,11 +176,13 @@ } else { printf("\t[state %d] %d variants\n", i, a->stateset[i].num); } - /* - for(j=0;jstateset[i].num;j++) { - put_htk_state(stdout, a->stateset[i].s[j]); + for(j=0;jstateset[i].num;j++) { + if (a->stateset[i].s[j]->name) { + printf("\t\t%s %d\n", a->stateset[i].s[j]->name, a->stateset[i].s[j]->id); + } else { + printf("\t\t(NULL) %d\n", a->stateset[i].s[j]->id); } - */ + } } } @@ -344,6 +348,7 @@ } /* now that cdset is completely built */ + hmminfo->cdset_info.binary_malloc = FALSE; return(TRUE); } Index: julius4/libsent/src/hmminfo/init_phmm.c diff -u julius4/libsent/src/hmminfo/init_phmm.c:1.4 julius4/libsent/src/hmminfo/init_phmm.c:1.5 --- julius4/libsent/src/hmminfo/init_phmm.c:1.4 Tue Sep 30 12:58:18 2008 +++ julius4/libsent/src/hmminfo/init_phmm.c Sun Feb 13 14:02:00 2011 @@ -12,7 +12,7 @@ * @author Akinobu LEE * @date Tue Feb 15 23:05:33 2005 * - * $Revision: 1.4 $ + * $Revision: 1.5 $ * */ /* @@ -96,8 +96,13 @@ boolean hmminfo_free(HTK_HMM_INFO *hmm) { - /* cdset does not use bmalloc, so free them separately */ - free_cdset(&(hmm->cdset_info.cdtree), &(hmm->cdset_root)); + if (hmm->cdset_info.binary_malloc) { + /* cdset are allocated by bmalloc (in case read from binary hmmlist) */ + if (hmm->cdset_root != NULL) mybfree2(&(hmm->cdset_root)); + } else { + /* cdset does not use bmalloc, so free them separately */ + free_cdset(&(hmm->cdset_info.cdtree), &(hmm->cdset_root)); + } /* free all memory that has been allocated by bmalloc2() */ if (hmm->mroot != NULL) mybfree2(&(hmm->mroot)); Index: julius4/libsent/src/hmminfo/rdhmmdef.c diff -u julius4/libsent/src/hmminfo/rdhmmdef.c:1.4 julius4/libsent/src/hmminfo/rdhmmdef.c:1.5 --- julius4/libsent/src/hmminfo/rdhmmdef.c:1.4 Fri Feb 11 00:23:52 2011 +++ julius4/libsent/src/hmminfo/rdhmmdef.c Sun Feb 13 14:02:00 2011 @@ -30,7 +30,7 @@ * @author Akinobu LEE * @date Wed Feb 16 00:17:18 2005 * - * $Revision: 1.4 $ + * $Revision: 1.5 $ * */ /* @@ -349,6 +349,15 @@ } hmm->totalpdfnum = n; } + /* assign ID number for all HTK_HMM_Trans */ + { + HTK_HMM_Trans *ttmp; + int n = 0; + for (ttmp = hmm->trstart; ttmp; ttmp = ttmp->next) { + ttmp->id = n++; + } + hmm->totaltransnum = n; + } #ifdef ENABLE_MSD /* check if MSD-HMM */ htk_hmm_check_msd(hmm); Index: julius4/libsent/src/hmminfo/read_binhmm.c diff -u julius4/libsent/src/hmminfo/read_binhmm.c:1.5 julius4/libsent/src/hmminfo/read_binhmm.c:1.6 --- julius4/libsent/src/hmminfo/read_binhmm.c:1.5 Sun Jul 20 01:51:35 2008 +++ julius4/libsent/src/hmminfo/read_binhmm.c Sun Feb 13 14:02:00 2011 @@ -22,7 +22,7 @@ * @author Akinobu LEE * @date Wed Feb 16 05:23:59 2005 * - * $Revision: 1.5 $ + * $Revision: 1.6 $ * */ /* @@ -850,6 +850,24 @@ hmm->totalpdfnum = n; } + /* re-number state id */ + { + HTK_HMM_State *stmp; + int n = 0; + for (stmp = hmm->ststart; stmp; stmp = stmp->next) { + stmp->id = n++; + } + } + /* assign ID number for all HTK_HMM_Trans */ + { + HTK_HMM_Trans *ttmp; + int n = 0; + for (ttmp = hmm->trstart; ttmp; ttmp = ttmp->next) { + ttmp->id = n++; + } + hmm->totaltransnum = n; + } + /* determine whether this model needs multi-path handling */ hmm->need_multipath = htk_hmm_has_several_arc_on_edge(hmm); if (hmm->need_multipath) { Index: julius4/libsent/src/hmminfo/read_binhmmlist.c diff -u julius4/libsent/src/hmminfo/read_binhmmlist.c:1.1 julius4/libsent/src/hmminfo/read_binhmmlist.c:1.2 --- julius4/libsent/src/hmminfo/read_binhmmlist.c:1.1 Tue Sep 30 12:58:18 2008 +++ julius4/libsent/src/hmminfo/read_binhmmlist.c Sun Feb 13 14:02:00 2011 @@ -41,7 +41,7 @@ * @author Akinobu LEE * @date Wed Feb 16 04:04:23 2005 * - * $Revision: 1.1 $ + * $Revision: 1.2 $ * */ /* @@ -55,6 +55,15 @@ #include #include +/** + * Callback to read hmmlist data from file. + * + * @param data_p [out] pointer to index tree node to store the leaf content + * @param data [in] user data + * @param fp [in] file pointer to read + * + * @return TRUE on success, FALSE on failure. + */ static boolean load_hmmlist_callback(void **data_p, void *data, FILE *fp) { @@ -90,16 +99,105 @@ return TRUE; } +typedef struct { + HTK_HMM_Trans **tr; + HTK_HMM_State **st; +} ListData; + +/** + * Callback to read cdset data from file. + * + * @param data_p [out] pointer to index tree node to store the leaf content + * @param data [in] user data + * @param fp [in] file pointer to read + * + * @return TRUE on success, FALSE on failure. + */ +static boolean +load_cdset_callback(void **data_p, void *data, FILE *fp) +{ + HTK_HMM_INFO *hmminfo = data; + ListData *ld = (ListData *)hmminfo->hook; + CD_Set *new; + int len; + int id; + int i, j; + HTK_HMM_Trans *ttmp; + + new = (CD_Set *)mybmalloc2(sizeof(CD_Set), &(hmminfo->cdset_root)); + if (myfread(&len, sizeof(int), 1, fp) < 1) return FALSE; + new->name = (char *)mybmalloc2(len, &(hmminfo->cdset_root)); + if (myfread(new->name, len, 1, fp) < 1) return FALSE; + if (myfread(&id, sizeof(int), 1, fp) < 1) return FALSE; + new->tr = ld->tr[id]; + if (myfread(&(new->state_num), sizeof(unsigned short), 1, fp) < 1) return FALSE; + new->stateset = (CD_State_Set *)mybmalloc2(sizeof(CD_State_Set) * new->state_num, &(hmminfo->cdset_root)); + for(i=0;istate_num;i++) { + if (myfread(&(new->stateset[i].num), sizeof(unsigned short), 1, fp) < 1) return FALSE; + new->stateset[i].maxnum = new->stateset[i].num; + new->stateset[i].s = (HTK_HMM_State **)mybmalloc2(sizeof(HTK_HMM_State *) * new->stateset[i].num, &(hmminfo->cdset_root)); + for(j=0;jstateset[i].num;j++) { + if (myfread(&id, sizeof(int), 1, fp) < 1) return FALSE; + new->stateset[i].s[j] = ld->st[id]; + } + } + + *data_p = new; + + return TRUE; +} + +/** + * Load HMMList and CDSet data from binary file. + * + * @param fp [in] file pointer to read + * @param hmminfo [in] HMM definition + * + * @return TRUE on success, FALSE on failure. + */ boolean load_hmmlist_bin(FILE *fp, HTK_HMM_INFO *hmminfo) { HMM_Logical *l; int n; + HTK_HMM_Trans *t; + HTK_HMM_State *s; + ListData ld; + + /* build id->entity list */ + ld.tr = (HTK_HMM_Trans **)mymalloc(sizeof(HTK_HMM_Trans *) * hmminfo->totaltransnum); + n = 0; + for (t = hmminfo->trstart; t; t = t->next) { + ld.tr[n++] = t; + } + ld.st = (HTK_HMM_State **)mymalloc(sizeof(HTK_HMM_State *) * hmminfo->totalstatenum); + n = 0; + for (s = hmminfo->ststart; s; s = s->next) { + ld.st[n++] = s; + } + /* set it to hook */ + hmminfo->hook = &ld; + /* load hmmlist */ + jlog("Stat: load_hmmlist_bin: reading hmmlist\n"); if (aptree_read(fp, &(hmminfo->logical_root), &(hmminfo->lroot), hmminfo, load_hmmlist_callback) == FALSE) { jlog("Error: load_hmmlist_bin: failed to read hmmlist from binary file\n"); return FALSE; } + /* load cdset */ + jlog("Stat: load_hmmlist_bin: reading pseudo phone set\n"); + if (aptree_read(fp, &(hmminfo->cdset_info.cdtree), &(hmminfo->cdset_root), hmminfo, load_cdset_callback) == FALSE) { + jlog("Warning: load_hmmlist_bin: cdset not in binary file, skip reading\n"); + } else { + hmminfo->cdset_info.binary_malloc = TRUE; + } + + /* remove data */ + free(ld.st); + free(ld.tr); + hmminfo->hook = NULL; + + /* form other data */ n = 0; for(l=hmminfo->lgstart;l;l=l->next) n++; hmminfo->totallogicalnum = n; Index: julius4/libsent/src/hmminfo/write_binhmmlist.c diff -u julius4/libsent/src/hmminfo/write_binhmmlist.c:1.1 julius4/libsent/src/hmminfo/write_binhmmlist.c:1.2 --- julius4/libsent/src/hmminfo/write_binhmmlist.c:1.1 Tue Sep 30 12:58:18 2008 +++ julius4/libsent/src/hmminfo/write_binhmmlist.c Sun Feb 13 14:02:00 2011 @@ -13,7 +13,7 @@ * @author Akinobu LEE * @date Wed Feb 16 04:04:23 2005 * - * $Revision: 1.1 $ + * $Revision: 1.2 $ * */ /* @@ -27,6 +27,14 @@ #include #include +/** + * Callback to write hmmlist data into file. + * + * @param data [in] hmmlist node data + * @param fp [in] file pointer to write + * + * @return TRUE on success, FALSE on failure. + */ static boolean save_hmmlist_callback(void *data, FILE *fp) { @@ -50,18 +58,65 @@ return TRUE; } +/** + * Callback to write cdset data into file. + * + * @param data [in] cdset node data + * @param fp [in] file pointer to write + * + * @return TRUE on success, FALSE on failure. + */ +static boolean +save_cdset_callback(void *data, FILE *fp) +{ + CD_Set *cd = data; + int len; + int i, j; + + len = strlen(cd->name) + 1; + if (myfwrite(&len, sizeof(int), 1, fp) < 1) return FALSE; + if (myfwrite(cd->name, len, 1, fp) < 1) return FALSE; + if (myfwrite(&(cd->tr->id), sizeof(int), 1, fp) < 1) return FALSE; + if (myfwrite(&(cd->state_num), sizeof(unsigned short), 1, fp) < 1) return FALSE; + for(i=0;istate_num;i++) { + if (myfwrite(&(cd->stateset[i].num), sizeof(unsigned short), 1, fp) < 1) return FALSE; + for(j=0;jstateset[i].num;j++) { + if (myfwrite(&(cd->stateset[i].s[j]->id), sizeof(int), 1, fp) < 1) return FALSE; + + } + } + + return TRUE; +} + +/** + * Write hmmlist (logical-to-physical mapping table) and + * cdset (pseudo phone set) to file. + * + * @param fp [in] file pointer to write + * @param hmminfo [in] HMM definition data + * + * @return TRUE on success, FALSE on failure. + */ boolean save_hmmlist_bin(FILE *fp, HTK_HMM_INFO *hmminfo) { - /* set mark */ + /* write 4 byte as NULL to auto detect file format at read time */ + /* this mark will be read in init_hmminfo() */ int x = 0; if (myfwrite(&x, sizeof(int), 1, fp) < 1) { jlog("Error: save_hmmlist_bin: failed to write hmmlist to binary file\n"); return FALSE; } + /* write hmmlist */ if (aptree_write(fp, hmminfo->logical_root, save_hmmlist_callback) == FALSE) { jlog("Error: save_hmmlist_bin: failed to write hmmlist to binary file\n"); return FALSE; } + /* write cdset */ + if (aptree_write(fp, hmminfo->cdset_info.cdtree, save_cdset_callback) == FALSE) { + jlog("Error: save_hmmlist_bin: failed to write cdset to binary file\n"); + return FALSE; + } return TRUE; } From sumomo @ users.sourceforge.jp Sun Feb 13 14:02:00 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Sun, 13 Feb 2011 14:02:00 +0900 Subject: [Julius-cvs 609] CVS update: julius4/mkbinhmm Message-ID: <1297573320.922522.7787.nullmailer@users.sourceforge.jp> Index: julius4/mkbinhmm/mkbinhmmlist.c diff -u julius4/mkbinhmm/mkbinhmmlist.c:1.1 julius4/mkbinhmm/mkbinhmmlist.c:1.2 --- julius4/mkbinhmm/mkbinhmmlist.c:1.1 Tue Sep 30 12:58:18 2008 +++ julius4/mkbinhmm/mkbinhmmlist.c Sun Feb 13 14:02:00 2011 @@ -7,7 +7,7 @@ /* mkbinhmmlist --- read in ascii hmmlist file and write in binary format */ -/* $Id: mkbinhmmlist.c,v 1.1 2008/09/30 03:58:18 sumomo Exp $ */ +/* $Id: mkbinhmmlist.c,v 1.2 2011/02/13 05:02:00 sumomo Exp $ */ #include #include @@ -68,13 +68,21 @@ return -1; } + if (hmminfo->is_triphone) { + fprintf(stderr, "making pseudo bi/mono-phone for IW-triphone\n"); + if (make_cdset(hmminfo) == FALSE) { + fprintf(stderr, "ERROR: m_fusion: failed to make context-dependent state set\n"); + return -1; + } + } + printf("\n------------------------------------------------------------\n"); print_hmmdef_info(stdout, hmminfo); printf("\n"); printf("------------------------------------------------------------\n"); - printf("---- writing ----\n"); + printf("---- writing logical-to-physical mapping and pseudo phone info ----\n"); printf("filename: %s\n", outfile); if ((fp = fopen_writefile(outfile)) == NULL) { @@ -91,7 +99,7 @@ } printf("\n"); - printf("binary HMMList written to \"%s\"\n", outfile); + printf("binary HMMList and pseudo phone definitions are written to \"%s\"\n", outfile); return 0; } From sumomo @ users.sourceforge.jp Sun Feb 13 19:45:56 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Sun, 13 Feb 2011 19:45:56 +0900 Subject: [Julius-cvs 610] CVS update: julius4/libsent/include/sent Message-ID: <1297593956.127005.21036.nullmailer@users.sourceforge.jp> Index: julius4/libsent/include/sent/ngram2.h diff -u julius4/libsent/include/sent/ngram2.h:1.8 julius4/libsent/include/sent/ngram2.h:1.9 --- julius4/libsent/include/sent/ngram2.h:1.8 Fri Sep 18 17:31:08 2009 +++ julius4/libsent/include/sent/ngram2.h Sun Feb 13 19:45:56 2011 @@ -95,7 +95,7 @@ * @author Akinobu LEE * @date Fri Feb 11 15:04:02 2005 * - * $Revision: 1.8 $ + * $Revision: 1.9 $ * */ /* @@ -182,6 +182,9 @@ LOGPROB *bo_wt_1; ///< back-off weights for 2-gram on 1st pass LOGPROB *p_2; ///< 2-gram prob for the 1st pass LOGPROB (*bigram_prob)(struct __ngram_info__ *, WORD_ID, WORD_ID); ///< Pointer of a function to compite bigram probability on the 1st pass. See bi_prob_func_set() for details + + BMALLOC_BASE *mroot; ///< Pointer for block memory allocation for lookup index + } NGRAM_INFO; Index: julius4/libsent/include/sent/ptree.h diff -u julius4/libsent/include/sent/ptree.h:1.5 julius4/libsent/include/sent/ptree.h:1.6 --- julius4/libsent/include/sent/ptree.h:1.5 Fri Sep 18 17:31:08 2009 +++ julius4/libsent/include/sent/ptree.h Sun Feb 13 19:45:56 2011 @@ -17,7 +17,7 @@ * @author Akinobu LEE * @date Fri Feb 11 17:27:24 2005 * - * $Revision: 1.5 $ + * $Revision: 1.6 $ * */ /* @@ -72,13 +72,12 @@ int testbit(char *str, int slen, int bitplace); int testbit_max(char *str, int bitplace, int maxbitplace); int where_the_bit_differ(char *str1, char *str2); -PATNODE *make_ptree(char **words, int *data, int wordsnum, int bitplace); +PATNODE *make_ptree(char **words, int *data, int wordsnum, int bitplace, BMALLOC_BASE **mroot); void disp_ptree(PATNODE *node, int level); int ptree_search_data(char *str, PATNODE *rootnode); int ptree_replace_data(char *str, int val, PATNODE *node); -PATNODE *ptree_make_root_node(int data); -void ptree_add_entry(char *str, int data, char *matchstr, PATNODE **rootnode); -void free_ptree(PATNODE *rootnode); +PATNODE *ptree_make_root_node(int data, BMALLOC_BASE **mroot); +void ptree_add_entry(char *str, int data, char *matchstr, PATNODE **rootnode, BMALLOC_BASE **mroot); void *aptree_search_data(char *str, APATNODE *rootnode); APATNODE *aptree_make_root_node(void *data, BMALLOC_BASE **mroot); From sumomo @ users.sourceforge.jp Sun Feb 13 19:45:56 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Sun, 13 Feb 2011 19:45:56 +0900 Subject: [Julius-cvs 611] CVS update: julius4/libsent/src/ngram Message-ID: <1297593956.218201.21048.nullmailer@users.sourceforge.jp> Index: julius4/libsent/src/ngram/ngram_lookup.c diff -u julius4/libsent/src/ngram/ngram_lookup.c:1.3 julius4/libsent/src/ngram/ngram_lookup.c:1.4 --- julius4/libsent/src/ngram/ngram_lookup.c:1.3 Tue Feb 10 02:27:46 2009 +++ julius4/libsent/src/ngram/ngram_lookup.c Sun Feb 13 19:45:56 2011 @@ -12,7 +12,7 @@ * @author Akinobu LEE * @date Wed Feb 16 16:42:38 2005 * - * $Revision: 1.3 $ + * $Revision: 1.4 $ * */ /* @@ -47,7 +47,7 @@ wnameindex[i] = ndata->wname[i]; } - ndata->root = make_ptree(wnameindex, windex, ndata->max_word_num, 0); + ndata->root = make_ptree(wnameindex, windex, ndata->max_word_num, 0, &(ndata->mroot)); free(windex); free(wnameindex); Index: julius4/libsent/src/ngram/ngram_malloc.c diff -u julius4/libsent/src/ngram/ngram_malloc.c:1.4 julius4/libsent/src/ngram/ngram_malloc.c:1.5 --- julius4/libsent/src/ngram/ngram_malloc.c:1.4 Sat Jul 4 23:11:43 2009 +++ julius4/libsent/src/ngram/ngram_malloc.c Sun Feb 13 19:45:56 2011 @@ -12,7 +12,7 @@ * @author Akinobu LEE * @date Wed Feb 16 16:48:56 2005 * - * $Revision: 1.4 $ + * $Revision: 1.5 $ * */ /* @@ -41,6 +41,7 @@ new->bo_wt_1 = NULL; new->p_2 = NULL; new->bos_eos_swap = FALSE; + new->mroot = NULL; return(new); } @@ -93,7 +94,7 @@ free(ndata->d); } /* free name index tree */ - free_ptree(ndata->root); + if (ndata->mroot) mybfree2(&(ndata->mroot)); /* free whole */ free(ndata); } Index: julius4/libsent/src/ngram/ngram_read_arpa.c diff -u julius4/libsent/src/ngram/ngram_read_arpa.c:1.16 julius4/libsent/src/ngram/ngram_read_arpa.c:1.17 --- julius4/libsent/src/ngram/ngram_read_arpa.c:1.16 Sat Jul 4 23:11:43 2009 +++ julius4/libsent/src/ngram/ngram_read_arpa.c Sun Feb 13 19:45:56 2011 @@ -20,7 +20,7 @@ * @author Akinobu LEE * @date Wed Feb 16 16:52:24 2005 * - * $Revision: 1.16 $ + * $Revision: 1.17 $ * */ /* @@ -30,7 +30,7 @@ * All rights reserved */ -/* $Id: ngram_read_arpa.c,v 1.16 2009/07/04 14:11:43 sumomo Exp $ */ +/* $Id: ngram_read_arpa.c,v 1.17 2011/02/13 10:45:56 sumomo Exp $ */ /* words should be alphabetically sorted */ @@ -152,7 +152,7 @@ /* add entry name to index tree */ if (ndata->root == NULL) { - ndata->root = ptree_make_root_node(nid); + ndata->root = ptree_make_root_node(nid, &(ndata->mroot)); } else { resid = ptree_search_data(name, ndata->root); if (resid != -1 && strmatch(name, ndata->wname[resid])) { /* already exist */ @@ -160,7 +160,7 @@ ok_p = FALSE; continue; } else { - ptree_add_entry(name, nid, ndata->wname[resid], &(ndata->root)); + ptree_add_entry(name, nid, ndata->wname[resid], &(ndata->root), &(ndata->mroot)); } } From sumomo @ users.sourceforge.jp Sun Feb 13 19:45:56 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Sun, 13 Feb 2011 19:45:56 +0900 Subject: [Julius-cvs 612] CVS update: julius4/libsent/src/util Message-ID: <1297593956.286607.21055.nullmailer@users.sourceforge.jp> Index: julius4/libsent/src/util/ptree.c diff -u julius4/libsent/src/util/ptree.c:1.4 julius4/libsent/src/util/ptree.c:1.5 --- julius4/libsent/src/util/ptree.c:1.4 Tue Feb 10 02:27:48 2009 +++ julius4/libsent/src/util/ptree.c Sun Feb 13 19:45:56 2011 @@ -12,7 +12,7 @@ * @author Akinobu LEE * @date Thu Feb 17 15:34:39 2005 * - * $Revision: 1.4 $ + * $Revision: 1.5 $ * */ /* @@ -89,15 +89,16 @@ /** * Allocate a new node. * + * @param mroot [i/o] base pointer for block malloc * * @return pointer to the new node. */ static PATNODE * -new_node() +new_node(BMALLOC_BASE **mroot) { PATNODE *tmp; - tmp = (PATNODE *)mymalloc(sizeof(PATNODE)); + tmp = (PATNODE *)mybmalloc2(sizeof(PATNODE), mroot); tmp->left0 = NULL; tmp->right1 = NULL; @@ -112,11 +113,12 @@ * @param data [in] integer value corresponding to each string in @a words * @param wordsnum [in] number of above * @param bitplace [in] current scan bit. + * @param mroot [i/o] base pointer for block malloc * * @return pointer to the root node index. */ PATNODE * -make_ptree(char **words, int *data, int wordsnum, int bitplace) +make_ptree(char **words, int *data, int wordsnum, int bitplace, BMALLOC_BASE **mroot) { int i,j, tmp; char *p; @@ -134,7 +136,7 @@ if (wordsnum == 1) { /* word identified: this is leaf node */ - ntmp = new_node(); + ntmp = new_node(mroot); ntmp->value.data = data[0]; return(ntmp); } @@ -147,7 +149,7 @@ } if (newnum == 0 || newnum == wordsnum) { /* all words has same bit, continue to descend */ - return(make_ptree(words, data, wordsnum, bitplace + 1)); + return(make_ptree(words, data, wordsnum, bitplace + 1, mroot)); } else { /* sort word pointers by tested bit */ j = wordsnum-1; @@ -163,10 +165,10 @@ } } /* create node and descend for each node */ - ntmp = new_node(); + ntmp = new_node(mroot); ntmp->value.thres_bit = bitplace; - ntmp->right1 = make_ptree(words, data, newnum, bitplace+1); - ntmp->left0 = make_ptree(&(words[newnum]), &(data[newnum]), wordsnum-newnum, bitplace+1); + ntmp->right1 = make_ptree(words, data, newnum, bitplace+1, mroot); + ntmp->left0 = make_ptree(&(words[newnum]), &(data[newnum]), wordsnum-newnum, bitplace+1, mroot); return(ntmp); } } @@ -293,15 +295,16 @@ * Make a root node of a index tree. * * @param data [in] the first data + * @param mroot [i/o] base pointer for block malloc * * @return the newly allocated root node. */ PATNODE * -ptree_make_root_node(int data) +ptree_make_root_node(int data, BMALLOC_BASE **mroot) { PATNODE *nnew; /* make new leaf node for newstr */ - nnew = new_node(); + nnew = new_node(mroot); nnew->value.data = data; return(nnew); } @@ -313,9 +316,10 @@ * @param bitloc [in] bit branch to which this node will be added * @param data [in] new data integer value * @param parentlink [i/o] the parent node to which this node will be added + * @param mroot [i/o] base pointer for block malloc */ static void -ptree_add_entry_at(char *str, int slen, int bitloc, int data, PATNODE **parentlink) +ptree_add_entry_at(char *str, int slen, int bitloc, int data, PATNODE **parentlink, BMALLOC_BASE **mroot) { PATNODE *node; node = *parentlink; @@ -323,9 +327,9 @@ (node->left0 == NULL && node->right1 == NULL)) { PATNODE *newleaf, *newbranch; /* insert between [parent] and [node] */ - newleaf = new_node(); + newleaf = new_node(mroot); newleaf->value.data = data; - newbranch = new_node(); + newbranch = new_node(mroot); newbranch->value.thres_bit = bitloc; *parentlink = newbranch; if (testbit(str, slen, bitloc) ==0) { @@ -338,9 +342,9 @@ return; } else { if (testbit(str, slen, node->value.thres_bit) != 0) { - ptree_add_entry_at(str, slen, bitloc, data, &(node->right1)); + ptree_add_entry_at(str, slen, bitloc, data, &(node->right1), mroot); } else { - ptree_add_entry_at(str, slen, bitloc, data, &(node->left0)); + ptree_add_entry_at(str, slen, bitloc, data, &(node->left0), mroot); } } } @@ -353,31 +357,18 @@ * @param matchstr [in] the most matching data already exist in the index tree, * as obtained by aptree_search_data() * @param rootnode [i/o] pointer to root index node + * @param mroot [i/o] base pointer for block malloc */ void -ptree_add_entry(char *str, int data, char *matchstr, PATNODE **rootnode) +ptree_add_entry(char *str, int data, char *matchstr, PATNODE **rootnode, BMALLOC_BASE **mroot) { int bitloc; bitloc = where_the_bit_differ(str, matchstr); if (*rootnode == NULL) { - *rootnode = ptree_make_root_node(data); + *rootnode = ptree_make_root_node(data, mroot); } else { - ptree_add_entry_at(str, strlen(str), bitloc, data, rootnode); + ptree_add_entry_at(str, strlen(str), bitloc, data, rootnode, mroot); } } - -/** - * Free all the sub nodes from specified node. - * - * @param node [in] current node. - */ -void -free_ptree(PATNODE *node) -{ - if (node == NULL) return; - if (node->left0 != NULL) free_ptree(node->left0); - if (node->right1 != NULL) free_ptree(node->right1); - free(node); -} From sumomo @ users.sourceforge.jp Mon Feb 14 14:10:22 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Mon, 14 Feb 2011 14:10:22 +0900 Subject: [Julius-cvs 613] CVS update: julius4/libsent/src/adin/pa Message-ID: <1297660222.848067.13957.nullmailer@users.sourceforge.jp> Index: julius4/libsent/src/adin/pa/COPYRIGHT.txt diff -u /dev/null julius4/libsent/src/adin/pa/COPYRIGHT.txt:1.1 --- /dev/null Mon Feb 14 14:10:22 2011 +++ julius4/libsent/src/adin/pa/COPYRIGHT.txt Mon Feb 14 14:10:22 2011 @@ -0,0 +1,25 @@ +PortAudio Portable Real-Time Audio Library +Copyright (c) 1999-2000 Ross Bencina and Phil Burk + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files +(the "Software"), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of the Software, +and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +Any person wishing to distribute modifications to the Software is +requested to send the modifications to the original developer so that +they can be incorporated into the canonical version. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR +ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF +CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. From sumomo @ users.sourceforge.jp Tue Feb 22 21:36:53 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Tue, 22 Feb 2011 21:36:53 +0900 Subject: [Julius-cvs 614] CVS update: julius4/libsent/src/adin Message-ID: <1298378213.604991.11097.nullmailer@users.sourceforge.jp> Index: julius4/libsent/src/adin/adin_portaudio.c diff -u julius4/libsent/src/adin/adin_portaudio.c:1.16 julius4/libsent/src/adin/adin_portaudio.c:1.17 --- julius4/libsent/src/adin/adin_portaudio.c:1.16 Thu Feb 10 01:17:45 2011 +++ julius4/libsent/src/adin/adin_portaudio.c Tue Feb 22 21:36:53 2011 @@ -56,7 +56,7 @@ * @author Akinobu LEE * @date Mon Feb 14 12:03:48 2005 * - * $Revision: 1.16 $ + * $Revision: 1.17 $ * */ /* @@ -554,25 +554,17 @@ adin_mic_end() { PaError err; -#ifdef OLDVER - PortAudioStream *stream_local; -#else - PaStream *stream_local; -#endif if (stream == NULL) return(TRUE); - stream_local = stream; - stream = NULL; - /* stop stream (do not wait callback and buffer flush, stop immediately) */ - err = Pa_AbortStream(stream_local); + err = Pa_AbortStream(stream); if (err != paNoError) { jlog("Error: adin_portaudio: failed to stop stream: %s\n", Pa_GetErrorText(err)); return(FALSE); } /* close stream */ - err = Pa_CloseStream(stream_local); + err = Pa_CloseStream(stream); if (err != paNoError) { jlog("Error: adin_portaudio: failed to close stream: %s\n", Pa_GetErrorText(err)); return(FALSE); @@ -584,6 +576,8 @@ return(FALSE); } + stream = NULL; + return TRUE; } From sumomo @ users.sourceforge.jp Tue Feb 22 22:46:26 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Tue, 22 Feb 2011 22:46:26 +0900 Subject: [Julius-cvs 615] CVS update: julius4/libjulius/include/julius Message-ID: <1298382386.640634.28600.nullmailer@users.sourceforge.jp> Index: julius4/libjulius/include/julius/define.h diff -u julius4/libjulius/include/julius/define.h:1.5 julius4/libjulius/include/julius/define.h:1.6 --- julius4/libjulius/include/julius/define.h:1.5 Sat Feb 12 16:44:09 2011 +++ julius4/libjulius/include/julius/define.h Tue Feb 22 22:46:26 2011 @@ -27,7 +27,7 @@ * @author Akinobu LEE * @date Mon Mar 7 15:17:26 2005 * - * $Revision: 1.5 $ + * $Revision: 1.6 $ * */ /* @@ -57,6 +57,7 @@ #define LM_NGRAM_USER 3 ///< User-defined statistical LM /* recognition status */ +#define J_RESULT_STATUS_BUFFER_OVERFLOW -7 ///< Input buffer overflow #define J_RESULT_STATUS_REJECT_POWER -6 ///< Input rejected by power #define J_RESULT_STATUS_TERMINATE -5 ///< Input was terminated by app. request #define J_RESULT_STATUS_ONLY_SILENCE -4 ///< Input contains only silence From sumomo @ users.sourceforge.jp Tue Feb 22 22:46:26 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Tue, 22 Feb 2011 22:46:26 +0900 Subject: [Julius-cvs 616] CVS update: julius4/libjulius/src Message-ID: <1298382386.753972.28612.nullmailer@users.sourceforge.jp> Index: julius4/libjulius/src/adin-cut.c diff -u julius4/libjulius/src/adin-cut.c:1.12 julius4/libjulius/src/adin-cut.c:1.13 --- julius4/libjulius/src/adin-cut.c:1.12 Sun Jul 5 23:12:18 2009 +++ julius4/libjulius/src/adin-cut.c Tue Feb 22 22:46:26 2011 @@ -95,7 +95,7 @@ * @author Akinobu LEE * @date Sat Feb 12 13:20:53 2005 * - * $Revision: 1.12 $ + * $Revision: 1.13 $ * */ /* @@ -1084,6 +1084,7 @@ #ifdef THREAD_DEBUG jlog("DEBUG: process: reset, speechlen = %d, online=%d\n", a->speechlen, a->transfer_online); #endif + a->adinthread_buffer_overflowed = FALSE; pthread_mutex_unlock(&(a->mutex)); /* main processing loop */ @@ -1106,7 +1107,6 @@ jlog("WARNING: adin_thread_process: too long input (> %d samples), segmented now\n", MAXSPEECHLEN); /* segment input here */ pthread_mutex_lock(&(a->mutex)); - a->adinthread_buffer_overflowed = FALSE; a->speechlen = 0; a->transfer_online = transfer_online_local = FALSE; pthread_mutex_unlock(&(a->mutex)); Index: julius4/libjulius/src/realtime-1stpass.c diff -u julius4/libjulius/src/realtime-1stpass.c:1.6 julius4/libjulius/src/realtime-1stpass.c:1.7 --- julius4/libjulius/src/realtime-1stpass.c:1.6 Tue Jun 16 19:57:43 2009 +++ julius4/libjulius/src/realtime-1stpass.c Tue Feb 22 22:46:26 2011 @@ -111,7 +111,7 @@ * @author Akinobu Lee * @date Tue Aug 23 11:44:14 2005 * - * $Revision: 1.6 $ + * $Revision: 1.7 $ * */ /* @@ -774,9 +774,10 @@ * @param nowlen [in] length of above * @param recog [i/o] engine instance * - * @return -1 on error (tell caller to terminate), 0 on success (allow caller - * to call me for the next segment). It returns 1 when telling the caller to - * terminate input and go on to the next pass. + * @return -1 on error (will close stream and terminate recognition), + * 0 on success (allow caller to call me for the next segment). It + * returns 1 when telling the caller to segment now at the middle of + * input , and 2 when input length overflow is detected. *
* * @callgraph Index: julius4/libjulius/src/recogmain.c diff -u julius4/libjulius/src/recogmain.c:1.14 julius4/libjulius/src/recogmain.c:1.15 --- julius4/libjulius/src/recogmain.c:1.14 Fri Sep 18 17:27:33 2009 +++ julius4/libjulius/src/recogmain.c Tue Feb 22 22:46:26 2011 @@ -12,7 +12,7 @@ * @author Akinobu Lee * @date Wed Aug 8 14:53:53 2007 * - * $Revision: 1.14 $ + * $Revision: 1.15 $ * */ @@ -957,6 +957,25 @@ /******************************************************************/ /* speech stream has been processed on-the-fly, and 1st pass ends */ /******************************************************************/ + if (ret == 1 || ret == 2) { /* segmented */ +#ifdef HAVE_PTHREAD + if (recog->adin->adinthread_buffer_overflowed) { + jlog("Warning: input buffer overflow, disgard the input\n"); + result_error(recog, J_RESULT_STATUS_BUFFER_OVERFLOW); + /* skip 2nd pass */ + goto end_recog; + } +#endif + /* check for audio overflow */ + for (mfcc = recog->mfcclist; mfcc; mfcc = mfcc->next) { + if (mfcc->f >= recog->real.maxframelen) { + jlog("Warning: input buffer overflow, disgard the input\n"); + result_error(recog, J_RESULT_STATUS_BUFFER_OVERFLOW); + /* skip 2nd pass */ + goto end_recog; + } + } + } /* last procedure of 1st-pass */ if (RealTimeParam(recog) == FALSE) { jlog("ERROR: fatal error occured, program terminates now\n"); From sumomo @ users.sourceforge.jp Thu Feb 24 19:07:03 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Thu, 24 Feb 2011 19:07:03 +0900 Subject: [Julius-cvs 617] CVS update: julius4/adinrec Message-ID: <1298542023.196918.8292.nullmailer@users.sourceforge.jp> Index: julius4/adinrec/adinrec.c diff -u julius4/adinrec/adinrec.c:1.4 julius4/adinrec/adinrec.c:1.5 --- julius4/adinrec/adinrec.c:1.4 Fri May 15 12:22:53 2009 +++ julius4/adinrec/adinrec.c Thu Feb 24 19:07:02 2011 @@ -12,7 +12,7 @@ * @author Akinobu LEE * @date Wed Mar 23 20:33:01 2005 * - * $Revision: 1.4 $ + * $Revision: 1.5 $ * */ /* @@ -44,7 +44,7 @@ { fprintf(stderr, "adinrec --- record one sentence input to a file\n"); fprintf(stderr, "Usage: adinrec [options..] filename\n"); - fprintf(stderr, " [-input mic|alsa|oss|esd|...] input source (mic)\n"); + fprintf(stderr, " [-input mic|pulseaudio|alsa|oss|esd|...] input source (mic)\n"); fprintf(stderr, " [-freq frequency] sampling frequency in Hz (%ld)\n", jconf->am_root->analysis.para_default.smp_freq); fprintf(stderr, " [-48] 48000Hz recording with down sampling (16kHz only)\n"); fprintf(stderr, " [-lv unsignedshort] silence cut level threshold (%d)\n", jconf->detect.level_thres); From sumomo @ users.sourceforge.jp Thu Feb 24 19:07:03 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Thu, 24 Feb 2011 19:07:03 +0900 Subject: [Julius-cvs 618] CVS update: julius4/libjulius/src Message-ID: <1298542023.411431.8322.nullmailer@users.sourceforge.jp> Index: julius4/libjulius/src/adin-cut.c diff -u julius4/libjulius/src/adin-cut.c:1.13 julius4/libjulius/src/adin-cut.c:1.14 --- julius4/libjulius/src/adin-cut.c:1.13 Tue Feb 22 22:46:26 2011 +++ julius4/libjulius/src/adin-cut.c Thu Feb 24 19:07:03 2011 @@ -95,7 +95,7 @@ * @author Akinobu LEE * @date Sat Feb 12 13:20:53 2005 * - * $Revision: 1.13 $ + * $Revision: 1.14 $ * */ /* @@ -299,7 +299,7 @@ int ad_process_ret; int imax, len, cnt; int wstep; - int end_status; /* return value */ + int end_status = 0; /* return value */ boolean transfer_online_local; /* local repository of transfer_online */ int zc; /* count of zero cross */ @@ -363,7 +363,7 @@ If no data exists in the device (in case of mic input), ad_read() will return 0. If reached end of stream (in case end of file or receive end ack from tcpip client), it will return -1. - If error, returns -2. + If error, returns -2. If the device requests segmentation, returns -3. */ if (a->down_sample) { /* get 48kHz samples to temporal buffer */ @@ -875,7 +875,9 @@ /* reset status */ a->need_init = TRUE; /* bufer status shoule be reset at next call */ } - end_status = (a->bp) ? 1 : 0; + if (end_status >= 0) { + end_status = (a->bp) ? 1 : 0; + } } return(end_status); @@ -948,7 +950,9 @@ ret = adin_cut(adin_store_buffer, NULL, recog); - if (ret == -1) { /* error */ + if (ret == -2) { /* termination request by ad_check? */ + jlog("Error: adin thread exit with termination request by checker\n"); + } else if (ret == -1) { /* error */ jlog("Error: adin thread exit with error\n"); } else if (ret == 0) { /* EOF */ jlog("Stat: adin thread end with EOF\n"); Index: julius4/libjulius/src/m_adin.c diff -u julius4/libjulius/src/m_adin.c:1.11 julius4/libjulius/src/m_adin.c:1.12 --- julius4/libjulius/src/m_adin.c:1.11 Tue Oct 27 14:06:52 2009 +++ julius4/libjulius/src/m_adin.c Thu Feb 24 19:07:03 2011 @@ -12,7 +12,7 @@ * @author Akinobu LEE * @date Fri Mar 18 16:17:23 2005 * - * $Revision: 1.11 $ + * $Revision: 1.12 $ * */ /* @@ -107,6 +107,15 @@ a->ad_input_name = adin_esd_input_name; break; #endif +#ifdef HAS_PULSEAUDIO + case SP_INPUT_PULSEAUDIO: + a->ad_standby = adin_pulseaudio_standby; + a->ad_begin = adin_pulseaudio_begin; + a->ad_end = adin_pulseaudio_end; + a->ad_read = adin_pulseaudio_read; + a->ad_input_name = adin_pulseaudio_input_name; + break; +#endif default: jlog("ERROR: m_adin: invalid input device specified\n"); } Index: julius4/libjulius/src/m_info.c diff -u julius4/libjulius/src/m_info.c:1.11 julius4/libjulius/src/m_info.c:1.12 --- julius4/libjulius/src/m_info.c:1.11 Sat Feb 12 16:44:09 2011 +++ julius4/libjulius/src/m_info.c Thu Feb 24 19:07:03 2011 @@ -12,7 +12,7 @@ * @author Akinobu Lee * @date Thu May 12 14:14:01 2005 * - * $Revision: 1.11 $ + * $Revision: 1.12 $ * */ /* @@ -836,6 +836,7 @@ case SP_INPUT_ALSA: jlog("alsa\n"); break; case SP_INPUT_OSS: jlog("oss\n"); break; case SP_INPUT_ESD: jlog("esd\n"); break; + case SP_INPUT_PULSEAUDIO: jlog("pulseaudio\n"); break; } } if (jconf->input.type == INPUT_WAVEFORM) { Index: julius4/libjulius/src/m_options.c diff -u julius4/libjulius/src/m_options.c:1.22 julius4/libjulius/src/m_options.c:1.23 --- julius4/libjulius/src/m_options.c:1.22 Sat Feb 12 16:44:09 2011 +++ julius4/libjulius/src/m_options.c Thu Feb 24 19:07:03 2011 @@ -18,7 +18,7 @@ * @author Akinobu Lee * @date Thu May 12 18:52:07 2005 * - * $Revision: 1.22 $ + * $Revision: 1.23 $ * */ /* @@ -374,7 +374,17 @@ jconf->input.device = SP_INPUT_ESD; jconf->decodeopt.realtime_flag = TRUE; #else - jlog("ERROR: m_options: \"-input oss\": OSS support is not built-in\n"); + jlog("ERROR: m_options: \"-input esd\": ESounD support is not built-in\n"); + return FALSE; +#endif + } else if (strmatch(tmparg,"pulseaudio")) { +#ifdef HAS_PULSEAUDIO + jconf->input.type = INPUT_WAVEFORM; + jconf->input.speech_input = SP_MIC; + jconf->input.device = SP_INPUT_PULSEAUDIO; + jconf->decodeopt.realtime_flag = TRUE; +#else + jlog("ERROR: m_options: \"-input pulseaudio\": PulseAudio support is not built-in\n"); return FALSE; #endif #endif Index: julius4/libjulius/src/m_usage.c diff -u julius4/libjulius/src/m_usage.c:1.13 julius4/libjulius/src/m_usage.c:1.14 --- julius4/libjulius/src/m_usage.c:1.13 Sat Feb 12 16:44:09 2011 +++ julius4/libjulius/src/m_usage.c Thu Feb 24 19:07:03 2011 @@ -12,7 +12,7 @@ * @author Akinobu Lee * @date Fri May 13 15:04:34 2005 * - * $Revision: 1.13 $ + * $Revision: 1.14 $ * */ /* @@ -77,6 +77,9 @@ # ifdef HAS_ESD fprintf(fp, " esd use ESounD interface\n"); # endif +# ifdef HAS_PULSEAUDIO + fprintf(fp, " pulseaudio use PulseAudio interface\n"); +# endif #endif #ifdef USE_NETAUDIO fprintf(fp, " netaudio DatLink/NetAudio server\n"); Index: julius4/libjulius/src/recogmain.c diff -u julius4/libjulius/src/recogmain.c:1.15 julius4/libjulius/src/recogmain.c:1.16 --- julius4/libjulius/src/recogmain.c:1.15 Tue Feb 22 22:46:26 2011 +++ julius4/libjulius/src/recogmain.c Thu Feb 24 19:07:03 2011 @@ -12,7 +12,7 @@ * @author Akinobu Lee * @date Wed Aug 8 14:53:53 2007 * - * $Revision: 1.15 $ + * $Revision: 1.16 $ * */ @@ -595,10 +595,6 @@ recog->adin->end_of_stream = TRUE; } #endif - /* end A/D input */ - if (adin_end(recog->adin) == FALSE) { - return -2; - } } else { switch(jconf->input.speech_input) { case SP_MFCMODULE: From sumomo @ users.sourceforge.jp Thu Feb 24 19:07:03 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Thu, 24 Feb 2011 19:07:03 +0900 Subject: [Julius-cvs 619] CVS update: julius4/msvc/config Message-ID: <1298542023.835768.8368.nullmailer@users.sourceforge.jp> Index: julius4/msvc/config/config-msvc-libsent.h diff -u julius4/msvc/config/config-msvc-libsent.h:1.2 julius4/msvc/config/config-msvc-libsent.h:1.3 --- julius4/msvc/config/config-msvc-libsent.h:1.2 Fri Dec 24 13:33:42 2010 +++ julius4/msvc/config/config-msvc-libsent.h Thu Feb 24 19:07:03 2011 @@ -100,5 +100,8 @@ /* Define if exist */ #undef HAVE_ESD_H +/* Define if exist */ +#undef HAVE_PULSE_SIMPLE_H + /* Define if MSD-HMM support is enabled */ #undef ENABLE_MSD From sumomo @ users.sourceforge.jp Thu Feb 24 19:07:03 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Thu, 24 Feb 2011 19:07:03 +0900 Subject: [Julius-cvs 620] CVS update: julius4/libsent/src/util Message-ID: <1298542023.744221.8361.nullmailer@users.sourceforge.jp> Index: julius4/libsent/src/util/confout.c diff -u julius4/libsent/src/util/confout.c:1.6 julius4/libsent/src/util/confout.c:1.7 --- julius4/libsent/src/util/confout.c:1.6 Sat Jul 4 23:11:43 2009 +++ julius4/libsent/src/util/confout.c Thu Feb 24 19:07:03 2011 @@ -12,7 +12,7 @@ * @author Akinobu LEE * @date Thu Feb 17 15:34:39 2005 * - * $Revision: 1.6 $ + * $Revision: 1.7 $ * */ /* @@ -63,6 +63,9 @@ #ifdef HAS_ESD fprintf(strm, " esd"); #endif +#ifdef HAS_PULSEAUDIO + fprintf(strm, " pulseaudio"); +#endif #ifdef USE_NETAUDIO fprintf(strm, " DATLink/NetAudio"); #endif From sumomo @ users.sourceforge.jp Thu Feb 24 19:07:03 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Thu, 24 Feb 2011 19:07:03 +0900 Subject: [Julius-cvs 621] CVS update: julius4/libsent/src/adin Message-ID: <1298542023.663787.8354.nullmailer@users.sourceforge.jp> Index: julius4/libsent/src/adin/adin_mic_linux.c diff -u julius4/libsent/src/adin/adin_mic_linux.c:1.4 julius4/libsent/src/adin/adin_mic_linux.c:1.5 --- julius4/libsent/src/adin/adin_mic_linux.c:1.4 Fri Jul 3 02:05:20 2009 +++ julius4/libsent/src/adin/adin_mic_linux.c Thu Feb 24 19:07:03 2011 @@ -5,22 +5,25 @@ * @brief マイク入力 (Linux) - デフォルトデバイス * * マイク入力のための低レベル関数です. - * インタフェースを指定しない場合に呼ばれます. - * 実際には,ALSA, OSS, ESD の順で最初に見つかったものが使用されます. + * インタフェースを明示指定しない (-input mic) 場合に呼ばれます. + * ALSA, OSS, PulesAudio, ESD の順で最初に見つかったものが使用されます. + * それぞれの API を明示的に指定したい場合は "-input" にそれぞれ + * "alsa", "oss", "pulseaudio", "esd" を指定してください。 *
* * @brief Microphone input on Linux - default device * * Low level I/O functions for microphone input on Linux. - * This will be called when no device was explicitly specified. - * A call to the functions in this file will be redirected to - * ALSA, OSS or ESD. + * This will be called when no device was explicitly specified ("-input mic"). + * ALSA, OSS, PulseAudio, ESD will be chosen at compilation time. + * "-input alsa", "-input oss", "-input pulseaudio" or "-input esd" to + * specify which API to use. * * * @author Akinobu LEE * @date Sun Feb 13 16:18:26 2005 * - * $Revision: 1.4 $ + * $Revision: 1.5 $ * */ /* @@ -48,10 +51,12 @@ return(adin_alsa_standby(sfreq, dummy)); #elif defined(HAS_OSS) return(adin_oss_standby(sfreq, dummy)); +#elif defined(HAS_PULSEAUDIO) + return(adin_pulseaudio_standby(sfreq, dummy)); #elif defined(HAS_ESD) return(adin_esd_standby(sfreq, dummy)); #else /* other than Linux */ - jlog("Error: neither of alsa/oss/esd device is available\n"); + jlog("Error: neither of pulseaudio/alsa/oss/esd device is available\n"); return FALSE; #endif } @@ -70,10 +75,12 @@ return(adin_alsa_begin(pathname)); #elif defined(HAS_OSS) return(adin_oss_begin(pathname)); +#elif defined(HAS_PULSEAUDIO) + return(adin_pulseaudio_begin(pathname)); #elif defined(HAS_ESD) return(adin_esd_begin(pathname)); #else /* other than Linux */ - jlog("Error: neither of alsa/oss/esd device is available\n"); + jlog("Error: neither of pulseaudio/alsa/oss/esd device is available\n"); return FALSE; #endif } @@ -90,10 +97,12 @@ return(adin_alsa_end()); #elif defined(HAS_OSS) return(adin_oss_end()); +#elif defined(HAS_PULSEAUDIO) + return(adin_pulseaudio_end()); #elif defined(HAS_ESD) return(adin_esd_end()); #else /* other than Linux */ - jlog("Error: neither of alsa/oss/esd device is available\n"); + jlog("Error: neither of pulseaudio/alsa/oss/esd device is available\n"); return FALSE; #endif } @@ -117,10 +126,12 @@ return(adin_alsa_read(buf, sampnum)); #elif defined(HAS_OSS) return(adin_oss_read(buf, sampnum)); +#elif defined(HAS_PULSEAUDIO) + return(adin_pulseaudio_read(buf, sampnum)); #elif defined(HAS_ESD) return(adin_esd_read(buf, sampnum)); #else /* other than Linux */ - jlog("Error: neither of alsa/oss/esd device is available\n"); + jlog("Error: neither of pulseaudio/alsa/oss/esd device is available\n"); return -2; #endif } @@ -139,9 +150,11 @@ return(adin_alsa_input_name()); #elif defined(HAS_OSS) return(adin_oss_input_name()); +#elif defined(HAS_PULSEAUDIO) + return(adin_pulseaudio_input_name()); #elif defined(HAS_ESD) return(adin_esd_input_name()); #else /* other than Linux */ - return("Error: neither of alsa/oss/esd device is available\n"); + return("Error: neither of pulseaudio/alsa/oss/esd device is available\n"); #endif } Index: julius4/libsent/src/adin/adin_pulseaudio.c diff -u /dev/null julius4/libsent/src/adin/adin_pulseaudio.c:1.1 --- /dev/null Thu Feb 24 19:07:03 2011 +++ julius4/libsent/src/adin/adin_pulseaudio.c Thu Feb 24 19:07:03 2011 @@ -0,0 +1,167 @@ +/** + * @file adin_pulseaudio.c + * + * + * @brief PulseAudio入力 + * + * 入力ソースとして PulseAudio API を使用します。 + * PulseAudio はコンパイル時にライブラリが存在する場合、 + * デフォルトのマイク入力APIとして "-input mic" あるいは "-input pulseaudio" + * で使用できます。 + * + * + * @brief Audio input via PulseAudio API + * + * Low level I/O functions for audio input via PulseAudio API. + * This API will be the default API when compiled with PulseAudio library, + * i.e. if development files exist at compilation, "-input mic" will use + * This API. Or you can explicitly specify "-input pulseaudio" to use it. + * + * + * @author Akinobu LEE + * @date Thu Feb 24 00:18:22 2011 + * + * $Revision: 1.1 $ + * + */ +/* + * Copyright (c) 2010-2011 Julius project team, Nagoya Institute of Technology + * All rights reserved + */ + +#include +#include + +#ifdef HAS_PULSEAUDIO +#include +#include + +#define BUFSIZE 512 +static pa_simple *s = NULL; +static int srate; +static char name_buf[] = "PulseAudio default device"; +#endif + +/** + * Connection initialization: check connectivity and open for recording. + * + * @param sfreq [in] required sampling frequency + * @param dummy [in] a dummy data + * + * @return TRUE on success, FALSE on failure. + */ +boolean +adin_pulseaudio_standby(int sfreq, void *dummy) +{ +#ifndef HAS_PULSEAUDIO + jlog("Error: PulseAudio not compiled in\n"); + return FALSE; +#else + srate = sfreq; + return TRUE; +#endif +} + +/** + * Start recording. + * @a pathname is dummy. + * + * @param arg [in] argument + * + * @return TRUE on success, FALSE on failure. + */ +boolean +adin_pulseaudio_begin(char *arg) +{ +#ifndef HAS_PULSEAUDIO + jlog("Error: PulseAudio not compiled in\n"); + return FALSE; +#else + pa_sample_spec ss; + int error; + + ss.format = PA_SAMPLE_S16LE; + ss.rate = srate; + ss.channels = 1; + + if (!(s = pa_simple_new(NULL, "Julius", PA_STREAM_RECORD, NULL, "record", &ss, NULL, NULL, &error))) { + jlog("Error: adin_pulseaudio: pa_simple_new() failed: %s\n", pa_strerror(error)); + return FALSE; + } + return TRUE; +#endif +} + +/** + * Stop recording. + * + * @return TRUE on success, FALSE on failure. + */ +boolean +adin_pulseaudio_end() +{ +#ifndef HAS_PULSEAUDIO + jlog("Error: PulseAudio not compiled in\n"); + return FALSE; +#else + if (s != NULL) { + pa_simple_free(s); + s = NULL; + } + return TRUE; +#endif +} + +/** + * @brief Read samples from device + * + * Try to read @a sampnum samples and returns actual number of recorded + * samples currently available. This function will block until + * at least one sample was obtained. + * + * @param buf [out] samples obtained in this function + * @param sampnum [in] wanted number of samples to be read + * + * @return actural number of read samples, -2 if an error occured. + */ +int +adin_pulseaudio_read(SP16 *buf, int sampnum) +{ +#ifndef HAS_PULSEAUDIO + return -2; +#else + + int error; + int cnt, bufsize; + + bufsize = sampnum * sizeof(SP16); + if (bufsize > BUFSIZE) bufsize = BUFSIZE; + + if (pa_simple_read(s, buf, bufsize, &error) < 0) { + jlog("Error: adin_pulseaudio: pa_simple_read() failed: %s\n", pa_strerror(error)); + return (-2); + } + + cnt = bufsize / sizeof(SP16); + + return(cnt); + +#endif +} + +/** + * + * Function to return current input source device name + * + * @return string of current input device name. + * + */ +char * +adin_pulseaudio_input_name() +{ +#ifndef HAS_PULSEAUDIO + return NULL; +#else + return(name_buf); +#endif +} From sumomo @ users.sourceforge.jp Thu Feb 24 19:07:03 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Thu, 24 Feb 2011 19:07:03 +0900 Subject: [Julius-cvs 622] CVS update: julius4/libsent/include/sent Message-ID: <1298542023.588608.8344.nullmailer@users.sourceforge.jp> Index: julius4/libsent/include/sent/adin.h diff -u julius4/libsent/include/sent/adin.h:1.7 julius4/libsent/include/sent/adin.h:1.8 --- julius4/libsent/include/sent/adin.h:1.7 Fri Sep 18 17:31:08 2009 +++ julius4/libsent/include/sent/adin.h Thu Feb 24 19:07:03 2011 @@ -19,7 +19,7 @@ * @author Akinobu LEE * @date Thu Feb 10 17:22:36 2005 * - * $Revision: 1.7 $ + * $Revision: 1.8 $ */ /* * Copyright (c) 1991-2007 Kawahara Lab., Kyoto University @@ -45,6 +45,9 @@ #ifdef HAVE_ESD_H #define HAS_ESD #endif +#ifdef HAVE_PULSE_SIMPLE_H +#define HAS_PULSEAUDIO +#endif /// Speech input type enum { @@ -69,6 +72,7 @@ SP_INPUT_ALSA, SP_INPUT_OSS, SP_INPUT_ESD, + SP_INPUT_PULSEAUDIO }; /// Default unit size of speech input segment in bytes @@ -173,6 +177,12 @@ boolean adin_esd_end(); int adin_esd_read(SP16 *buf, int sampnum); char *adin_esd_input_name(); +/* adin/adin_pulseaudio.c */ +boolean adin_pulseaudio_standby(int freq, void *arg); +boolean adin_pulseaudio_begin(char *pathname); +boolean adin_pulseaudio_end(); +int adin_pulseaudio_read(SP16 *buf, int sampnum); +char *adin_pulseaudio_input_name(); /* adin/adin_netaudio.c and adin/adin_na.c */ boolean adin_netaudio_standby(int freq, void *arg); boolean adin_netaudio_begin(char *pathname); Index: julius4/libsent/include/sent/config.h.in diff -u julius4/libsent/include/sent/config.h.in:1.6 julius4/libsent/include/sent/config.h.in:1.7 --- julius4/libsent/include/sent/config.h.in:1.6 Mon Jul 7 14:50:11 2008 +++ julius4/libsent/include/sent/config.h.in Thu Feb 24 19:07:03 2011 @@ -33,7 +33,7 @@ * @author Akinobu LEE * @date Thu Feb 10 17:48:32 2005 * - * $Revision: 1.6 $ + * $Revision: 1.7 $ * */ @@ -139,5 +139,8 @@ /* Define if exist */ #undef HAVE_ESD_H +/* Define if exist */ +#undef HAVE_PULSE_SIMPLE_H + /* Define if MSD-HMM support is enabled */ #undef ENABLE_MSD From sumomo @ users.sourceforge.jp Thu Feb 24 19:07:03 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Thu, 24 Feb 2011 19:07:03 +0900 Subject: [Julius-cvs 623] CVS update: julius4/adintool Message-ID: <1298542023.279757.8304.nullmailer@users.sourceforge.jp> Index: julius4/adintool/adintool.c diff -u julius4/adintool/adintool.c:1.8 julius4/adintool/adintool.c:1.9 --- julius4/adintool/adintool.c:1.8 Tue Jun 16 20:03:37 2009 +++ julius4/adintool/adintool.c Thu Feb 24 19:07:03 2011 @@ -35,7 +35,7 @@ * @author Akinobu LEE * @date Wed Mar 23 20:43:32 2005 * - * $Revision: 1.8 $ + * $Revision: 1.9 $ * */ /* @@ -377,6 +377,7 @@ case SP_INPUT_ALSA: fprintf(stderr, "alsa\n"); break; case SP_INPUT_OSS: fprintf(stderr, "oss\n"); break; case SP_INPUT_ESD: fprintf(stderr, "esd\n"); break; + case SP_INPUT_PULSEAUDIO: fprintf(stderr, "pulseaudio\n"); break; } } From sumomo @ users.sourceforge.jp Thu Feb 24 19:07:03 2011 From: sumomo @ users.sourceforge.jp (sumomo @ users.sourceforge.jp) Date: Thu, 24 Feb 2011 19:07:03 +0900 Subject: [Julius-cvs 624] CVS update: julius4/libsent Message-ID: <1298542023.499480.8335.nullmailer@users.sourceforge.jp> Index: julius4/libsent/configure diff -u julius4/libsent/configure:1.25 julius4/libsent/configure:1.26 --- julius4/libsent/configure:1.25 Sat Feb 5 18:00:01 2011 +++ julius4/libsent/configure Thu Feb 24 19:07:03 2011 @@ -12,7 +12,7 @@ ac_default_prefix=/usr/local # Any additions from configure.in: ac_help="$ac_help - --with-mictype=TYPE specify mic I/O (oss|alsa|freebsd|coreaudio|sol2|sun4|irix|esd|sp|portaudio|pa-oss|pa-alsa|pa-winmm|pa-dsound)" + --with-mictype=TYPE specify mic I/O (oss|alsa|freebsd|coreaudio|sol2|sun4|irix|esd|sp|portaudio|pa-oss|pa-alsa|pa-winmm|pa-dsound|pulseaudio)" ac_help="$ac_help --with-netaudio-dir=DIR DatLink/NetAudio include/lib are in DIR" ac_help="$ac_help @@ -1986,6 +1986,7 @@ # avoid ALSA/OSS detection for Windows environment has_alsa=no has_oss=no + has_pulseaudio=no ;; *) # ALSA @@ -1994,17 +1995,17 @@ do ac_safe=`echo "$ac_hdr" | sed 'y%./+-%__p_%'` echo $ac_n "checking for $ac_hdr""... $ac_c" 1>&6 -echo "configure:1998: checking for $ac_hdr" >&5 +echo "configure:1999: checking for $ac_hdr" >&5 if eval "test \"`echo '$''{'ac_cv_header_$ac_safe'+set}'`\" = set"; then echo $ac_n "(cached) $ac_c" 1>&6 else cat > conftest.$ac_ext < EOF ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out" -{ (eval echo configure:2008: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } +{ (eval echo configure:2009: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"` if test -z "$ac_err"; then rm -rf conftest* @@ -2031,17 +2032,17 @@ do ac_safe=`echo "$ac_hdr" | sed 'y%./+-%__p_%'` echo $ac_n "checking for $ac_hdr""... $ac_c" 1>&6 -echo "configure:2035: checking for $ac_hdr" >&5 +echo "configure:2036: checking for $ac_hdr" >&5 if eval "test \"`echo '$''{'ac_cv_header_$ac_safe'+set}'`\" = set"; then echo $ac_n "(cached) $ac_c" 1>&6 else cat > conftest.$ac_ext < EOF ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out" -{ (eval echo configure:2045: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } +{ (eval echo configure:2046: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"` if test -z "$ac_err"; then rm -rf conftest* @@ -2078,17 +2079,17 @@ do ac_safe=`echo "$ac_hdr" | sed 'y%./+-%__p_%'` echo $ac_n "checking for $ac_hdr""... $ac_c" 1>&6 -echo "configure:2082: checking for $ac_hdr" >&5 +echo "configure:2083: checking for $ac_hdr" >&5 if eval "test \"`echo '$''{'ac_cv_header_$ac_safe'+set}'`\" = set"; then echo $ac_n "(cached) $ac_c" 1>&6 else cat > conftest.$ac_ext < EOF ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out" -{ (eval echo configure:2092: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } +{ (eval echo configure:2093: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"` if test -z "$ac_err"; then rm -rf conftest* @@ -2115,17 +2116,17 @@ do ac_safe=`echo "$ac_hdr" | sed 'y%./+-%__p_%'` echo $ac_n "checking for $ac_hdr""... $ac_c" 1>&6 -echo "configure:2119: checking for $ac_hdr" >&5 +echo "configure:2120: checking for $ac_hdr" >&5 if eval "test \"`echo '$''{'ac_cv_header_$ac_safe'+set}'`\" = set"; then echo $ac_n "(cached) $ac_c" 1>&6 else cat > conftest.$ac_ext < EOF ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out" -{ (eval echo configure:2129: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } +{ (eval echo configure:2130: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"` if test -z "$ac_err"; then rm -rf conftest* @@ -2158,23 +2159,24 @@ ;; esac + # ESounD has_esd=yes for ac_hdr in esd.h do ac_safe=`echo "$ac_hdr" | sed 'y%./+-%__p_%'` echo $ac_n "checking for $ac_hdr""... $ac_c" 1>&6 -echo "configure:2168: checking for $ac_hdr" >&5 +echo "configure:2170: checking for $ac_hdr" >&5 if eval "test \"`echo '$''{'ac_cv_header_$ac_safe'+set}'`\" = set"; then echo $ac_n "(cached) $ac_c" 1>&6 else cat > conftest.$ac_ext < EOF ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out" -{ (eval echo configure:2178: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } +{ (eval echo configure:2180: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"` if test -z "$ac_err"; then rm -rf conftest* @@ -2202,9 +2204,91 @@ done +# PulseAudio +has_pulseaudio=no +echo $ac_n "checking for pa_simple_new in -lpulse-simple""... $ac_c" 1>&6 +echo "configure:2211: checking for pa_simple_new in -lpulse-simple" >&5 +ac_lib_var=`echo pulse-simple'_'pa_simple_new | sed 'y%./+-%__p_%'` +if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then + echo $ac_n "(cached) $ac_c" 1>&6 +else + ac_save_LIBS="$LIBS" +LIBS="-lpulse-simple $LIBS" +cat > conftest.$ac_ext <&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then + rm -rf conftest* + eval "ac_cv_lib_$ac_lib_var=yes" +else + echo "configure: failed program was:" >&5 + cat conftest.$ac_ext >&5 + rm -rf conftest* + eval "ac_cv_lib_$ac_lib_var=no" +fi +rm -f conftest* +LIBS="$ac_save_LIBS" + +fi +if eval "test \"`echo '$ac_cv_lib_'$ac_lib_var`\" = yes"; then + echo "$ac_t""yes" 1>&6 + for ac_hdr in pulse/simple.h +do +ac_safe=`echo "$ac_hdr" | sed 'y%./+-%__p_%'` +echo $ac_n "checking for $ac_hdr""... $ac_c" 1>&6 +echo "configure:2249: checking for $ac_hdr" >&5 +if eval "test \"`echo '$''{'ac_cv_header_$ac_safe'+set}'`\" = set"; then + echo $ac_n "(cached) $ac_c" 1>&6 +else + cat > conftest.$ac_ext < +EOF +ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out" +{ (eval echo configure:2259: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } +ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"` +if test -z "$ac_err"; then + rm -rf conftest* + eval "ac_cv_header_$ac_safe=yes" +else + echo "$ac_err" >&5 + echo "configure: failed program was:" >&5 + cat conftest.$ac_ext >&5 + rm -rf conftest* + eval "ac_cv_header_$ac_safe=no" +fi +rm -f conftest* +fi +if eval "test \"`echo '$ac_cv_header_'$ac_safe`\" = yes"; then + echo "$ac_t""yes" 1>&6 + ac_tr_hdr=HAVE_`echo $ac_hdr | sed 'y%abcdefghijklmnopqrstuvwxyz./-%ABCDEFGHIJKLMNOPQRSTUVWXYZ___%'` + cat >> confdefs.h <&6 +fi +done + +else + echo "$ac_t""no" 1>&6 +fi + + if test "$with_mictype" = auto; then echo $ac_n "checking for input device type""... $ac_c" 1>&6 -echo "configure:2208: checking for input device type" >&5 +echo "configure:2292: checking for input device type" >&5 altype=no case "$host_os" in linux*) @@ -2213,29 +2297,33 @@ altype=alsa elif test "$has_oss" = yes; then altype=oss + elif test "$has_pulseaudio" = yes; then + altype=pulseaudio elif test "$has_esd" = yes; then altype=esd else - { echo "configure: error: no audio io avaiable!" 1>&2; exit 1; } + { echo "configure: error: none of alsa/oss/pulseaudio/esd header/lib found!" 1>&2; exit 1; } fi ;; freebsd*) # FreeBSD (snd driver) if test "$has_oss" = yes; then altype=freebsd + elif test "$has_pulseaudio" = yes; then + altype=pulseaudio else - { echo "configure: error: no soundcard.h found" 1>&2; exit 1; } + { echo "configure: error: no soundcard.h or pulseaudio header/lib found!" 1>&2; exit 1; } fi ;; darwin*) # MacOSX (CoreAudio) cat > conftest.$ac_ext < EOF ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out" -{ (eval echo configure:2239: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } +{ (eval echo configure:2327: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"` if test -z "$ac_err"; then rm -rf conftest* @@ -2250,12 +2338,12 @@ solaris2*) # Solaris2.x Built-in Audio cat > conftest.$ac_ext < EOF ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out" -{ (eval echo configure:2259: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } +{ (eval echo configure:2347: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"` if test -z "$ac_err"; then rm -rf conftest* @@ -2270,12 +2358,12 @@ sunos4*) # SunOS4 Audio cat > conftest.$ac_ext < EOF ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out" -{ (eval echo configure:2279: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } +{ (eval echo configure:2367: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"` if test -z "$ac_err"; then rm -rf conftest* @@ -2290,12 +2378,12 @@ irix6*) # O2 (SGI IRIX6.3) cat > conftest.$ac_ext < EOF ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out" -{ (eval echo configure:2299: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } +{ (eval echo configure:2387: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"` if test -z "$ac_err"; then rm -rf conftest* @@ -2312,9 +2400,9 @@ # AC_TRY_CPP([#include ],altype=osf1) # ;; cygwin*|mingw*) - # minGW - portaudio (auto select winmm / dsound) - altype=portaudio - ;; + # minGW - portaudio (auto select winmm / dsound) + altype=portaudio + ;; esac echo "$ac_t""$altype" 1>&6 else @@ -2327,7 +2415,7 @@ portaudio) pa_system=no echo $ac_n "checking for Pa_Initialize in -lportaudio""... $ac_c" 1>&6 -echo "configure:2331: checking for Pa_Initialize in -lportaudio" >&5 +echo "configure:2419: checking for Pa_Initialize in -lportaudio" >&5 ac_lib_var=`echo portaudio'_'Pa_Initialize | sed 'y%./+-%__p_%'` if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then echo $ac_n "(cached) $ac_c" 1>&6 @@ -2335,7 +2423,7 @@ ac_save_LIBS="$LIBS" LIBS="-lportaudio $LIBS" cat > conftest.$ac_ext <&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then +if { (eval echo configure:2438: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then rm -rf conftest* eval "ac_cv_lib_$ac_lib_var=yes" else @@ -2365,17 +2453,17 @@ do ac_safe=`echo "$ac_hdr" | sed 'y%./+-%__p_%'` echo $ac_n "checking for $ac_hdr""... $ac_c" 1>&6 -echo "configure:2369: checking for $ac_hdr" >&5 +echo "configure:2457: checking for $ac_hdr" >&5 if eval "test \"`echo '$''{'ac_cv_header_$ac_safe'+set}'`\" = set"; then echo $ac_n "(cached) $ac_c" 1>&6 else cat > conftest.$ac_ext < EOF ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out" -{ (eval echo configure:2379: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } +{ (eval echo configure:2467: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"` if test -z "$ac_err"; then rm -rf conftest* @@ -2419,7 +2507,7 @@ ;; cygwin*|mingw*) echo $ac_n "checking for main in -ldsound""... $ac_c" 1>&6 -echo "configure:2423: checking for main in -ldsound" >&5 +echo "configure:2511: checking for main in -ldsound" >&5 ac_lib_var=`echo dsound'_'main | sed 'y%./+-%__p_%'` if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then echo $ac_n "(cached) $ac_c" 1>&6 @@ -2427,14 +2515,14 @@ ac_save_LIBS="$LIBS" LIBS="-ldsound $LIBS" cat > conftest.$ac_ext <&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then +if { (eval echo configure:2526: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then rm -rf conftest* eval "ac_cv_lib_$ac_lib_var=yes" else @@ -2453,17 +2541,17 @@ do ac_safe=`echo "$ac_hdr" | sed 'y%./+-%__p_%'` echo $ac_n "checking for $ac_hdr""... $ac_c" 1>&6 -echo "configure:2457: checking for $ac_hdr" >&5 +echo "configure:2545: checking for $ac_hdr" >&5 if eval "test \"`echo '$''{'ac_cv_header_$ac_safe'+set}'`\" = set"; then echo $ac_n "(cached) $ac_c" 1>&6 else cat > conftest.$ac_ext < EOF ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out" -{ (eval echo configure:2467: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } +{ (eval echo configure:2555: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"` if test -z "$ac_err"; then rm -rf conftest* @@ -2506,6 +2594,11 @@ # set appropritate parameters for the determined API SOUNDLIB="" ADINOBJ="" +# if PulseAudio exist, include it +if test "$has_pulseaudio" = yes; then + SOUNDLIB="$SOUNDLIB -lpulse-simple -lpulse" + ADINOBJ="$ADINOBJ src/adin/adin_pulseaudio.o" +fi # if esd exist, include it if test "$has_esd" = yes; then SOUNDLIB="$SOUNDLIB -lesd" @@ -2537,7 +2630,7 @@ case "$host_os" in linux*) echo $ac_n "checking for spInitAudio in -lspa.linux""... $ac_c" 1>&6 -echo "configure:2541: checking for spInitAudio in -lspa.linux" >&5 +echo "configure:2634: checking for spInitAudio in -lspa.linux" >&5 ac_lib_var=`echo spa.linux'_'spInitAudio | sed 'y%./+-%__p_%'` if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then echo $ac_n "(cached) $ac_c" 1>&6 @@ -2545,7 +2638,7 @@ ac_save_LIBS="$LIBS" LIBS="-lspa.linux -lspb.linux -lm $LIBS" cat > conftest.$ac_ext <&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then +if { (eval echo configure:2653: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then rm -rf conftest* eval "ac_cv_lib_$ac_lib_var=yes" else @@ -2575,7 +2668,7 @@ else echo "$ac_t""no" 1>&6 echo $ac_n "checking for spInitAudio in -lspa.linux-glibc""... $ac_c" 1>&6 -echo "configure:2579: checking for spInitAudio in -lspa.linux-glibc" >&5 +echo "configure:2672: checking for spInitAudio in -lspa.linux-glibc" >&5 ac_lib_var=`echo spa.linux-glibc'_'spInitAudio | sed 'y%./+-%__p_%'` if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then echo $ac_n "(cached) $ac_c" 1>&6 @@ -2583,7 +2676,7 @@ ac_save_LIBS="$LIBS" LIBS="-lspa.linux-glibc -lspb.linux-glibc -lm $LIBS" cat > conftest.$ac_ext <&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then +if { (eval echo configure:2691: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then rm -rf conftest* eval "ac_cv_lib_$ac_lib_var=yes" else @@ -2723,7 +2816,17 @@ ADINOBJ="$ADINOBJ src/adin/adin_mic_linux.o" ;; + pulseaudio) + if test "$has_pulseaudio" = no; then + { echo "configure: error: no PulseAudio header!" 1>&2; exit 1; } + fi + aldesc="PulseAudio" + cat >> confdefs.h <<\EOF +#define USE_MIC 1 +EOF + ADINOBJ="$ADINOBJ src/adin/adin_mic_linux.o" + ;; freebsd) if test "$has_oss" = no; then { echo "configure: error: neither sys/soundcard.h nor machine/soundcard.h exist" 1>&2; exit 1; } @@ -2784,21 +2887,21 @@ if test "$with_netaudio_dir" = auto ; then echo $ac_n "checking for DatLink/NetAudio support""... $ac_c" 1>&6 -echo "configure:2788: checking for DatLink/NetAudio support" >&5 +echo "configure:2891: checking for DatLink/NetAudio support" >&5 else echo $ac_n "checking for DatLink/NetAudio support on ${with_netaudio_dir}""... $ac_c" 1>&6 -echo "configure:2791: checking for DatLink/NetAudio support on ${with_netaudio_dir}" >&5 +echo "configure:2894: checking for DatLink/NetAudio support on ${with_netaudio_dir}" >&5 fi TMPCPPFLAGS="$CPPFLAGS" CPPFLAGS="$CPPFLAGS -I${with_netaudio_dir}/include" use_netaudio=no cat > conftest.$ac_ext < EOF ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out" -{ (eval echo configure:2802: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } +{ (eval echo configure:2905: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"` if test -z "$ac_err"; then rm -rf conftest* @@ -2823,7 +2926,7 @@ have_zlib=no; if test "$use_zlib" = yes; then echo $ac_n "checking for deflate in -lz""... $ac_c" 1>&6 -echo "configure:2827: checking for deflate in -lz" >&5 +echo "configure:2930: checking for deflate in -lz" >&5 ac_lib_var=`echo z'_'deflate | sed 'y%./+-%__p_%'` if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then echo $ac_n "(cached) $ac_c" 1>&6 @@ -2831,7 +2934,7 @@ ac_save_LIBS="$LIBS" LIBS="-lz $LIBS" cat > conftest.$ac_ext <&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then +if { (eval echo configure:2949: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then rm -rf conftest* eval "ac_cv_lib_$ac_lib_var=yes" else @@ -2861,17 +2964,17 @@ do ac_safe=`echo "$ac_hdr" | sed 'y%./+-%__p_%'` echo $ac_n "checking for $ac_hdr""... $ac_c" 1>&6 -echo "configure:2865: checking for $ac_hdr" >&5 +echo "configure:2968: checking for $ac_hdr" >&5 if eval "test \"`echo '$''{'ac_cv_header_$ac_safe'+set}'`\" = set"; then echo $ac_n "(cached) $ac_c" 1>&6 else cat > conftest.$ac_ext < EOF ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out" -{ (eval echo configure:2875: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } +{ (eval echo configure:2978: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"` if test -z "$ac_err"; then rm -rf conftest* @@ -2916,7 +3019,7 @@ # Extract the first word of "gzip", so it can be a program name with args. set dummy gzip; ac_word=$2 echo $ac_n "checking for $ac_word""... $ac_c" 1>&6 -echo "configure:2920: checking for $ac_word" >&5 +echo "configure:3023: checking for $ac_word" >&5 if eval "test \"`echo '$''{'ac_cv_prog_GZIP'+set}'`\" = set"; then echo $ac_n "(cached) $ac_c" 1>&6 else @@ -2963,7 +3066,7 @@ if test "$with_sndfile" = yes; then have_libsndfile=no echo $ac_n "checking for sf_open in -lsndfile""... $ac_c" 1>&6 -echo "configure:2967: checking for sf_open in -lsndfile" >&5 +echo "configure:3070: checking for sf_open in -lsndfile" >&5 ac_lib_var=`echo sndfile'_'sf_open | sed 'y%./+-%__p_%'` if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then echo $ac_n "(cached) $ac_c" 1>&6 @@ -2971,7 +3074,7 @@ ac_save_LIBS="$LIBS" LIBS="-lsndfile $LIBS" cat > conftest.$ac_ext <&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then +if { (eval echo configure:3089: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then rm -rf conftest* eval "ac_cv_lib_$ac_lib_var=yes" else @@ -3001,17 +3104,17 @@ do ac_safe=`echo "$ac_hdr" | sed 'y%./+-%__p_%'` echo $ac_n "checking for $ac_hdr""... $ac_c" 1>&6 -echo "configure:3005: checking for $ac_hdr" >&5 +echo "configure:3108: checking for $ac_hdr" >&5 if eval "test \"`echo '$''{'ac_cv_header_$ac_safe'+set}'`\" = set"; then echo $ac_n "(cached) $ac_c" 1>&6 else cat > conftest.$ac_ext < EOF ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out" -{ (eval echo configure:3015: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } +{ (eval echo configure:3118: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"` if test -z "$ac_err"; then rm -rf conftest* @@ -3053,7 +3156,7 @@ if test "$have_libsndfile" = no; then echo $ac_n "checking for sf_open_read in -lsndfile""... $ac_c" 1>&6 -echo "configure:3057: checking for sf_open_read in -lsndfile" >&5 +echo "configure:3160: checking for sf_open_read in -lsndfile" >&5 ac_lib_var=`echo sndfile'_'sf_open_read | sed 'y%./+-%__p_%'` if eval "test \"`echo '$''{'ac_cv_lib_$ac_lib_var'+set}'`\" = set"; then echo $ac_n "(cached) $ac_c" 1>&6 @@ -3061,7 +3164,7 @@ ac_save_LIBS="$LIBS" LIBS="-lsndfile $LIBS" cat > conftest.$ac_ext <&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then +if { (eval echo configure:3179: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then rm -rf conftest* eval "ac_cv_lib_$ac_lib_var=yes" else @@ -3091,17 +3194,17 @@ do ac_safe=`echo "$ac_hdr" | sed 'y%./+-%__p_%'` echo $ac_n "checking for $ac_hdr""... $ac_c" 1>&6 -echo "configure:3095: checking for $ac_hdr" >&5 +echo "configure:3198: checking for $ac_hdr" >&5 if eval "test \"`echo '$''{'ac_cv_header_$ac_safe'+set}'`\" = set"; then echo $ac_n "(cached) $ac_c" 1>&6 else cat > conftest.$ac_ext < EOF ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out" -{ (eval echo configure:3105: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } +{ (eval echo configure:3208: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; } ac_err=`grep -v '^ *+' conftest.out | grep -v "^conftest.${ac_ext}\$"` if test -z "$ac_err"; then rm -rf conftest* Index: julius4/libsent/configure.in diff -u julius4/libsent/configure.in:1.24 julius4/libsent/configure.in:1.25 --- julius4/libsent/configure.in:1.24 Sat Feb 5 18:00:01 2011 +++ julius4/libsent/configure.in Thu Feb 24 19:07:03 2011 @@ -3,7 +3,7 @@ dnl Copyright (c) 2005-2007 Julius project team, Nagoya Institute of Technology dnl All rights reserved dnl -dnl $Id: configure.in,v 1.24 2011/02/05 09:00:01 sumomo Exp $ +dnl $Id: configure.in,v 1.25 2011/02/24 10:07:03 sumomo Exp $ dnl dnl Process this file with autoconf to produce a configure script. @@ -16,7 +16,7 @@ dnl Checks for options # specify mic type AC_ARG_WITH(mictype, -[ --with-mictype=TYPE specify mic I/O (oss|alsa|freebsd|coreaudio|sol2|sun4|irix|esd|sp|portaudio|pa-oss|pa-alsa|pa-winmm|pa-dsound)],,with_mictype=auto) +[ --with-mictype=TYPE specify mic I/O (oss|alsa|freebsd|coreaudio|sol2|sun4|irix|esd|sp|portaudio|pa-oss|pa-alsa|pa-winmm|pa-dsound|pulseaudio)],,with_mictype=auto) # NetAudio support AC_ARG_WITH(netaudio-dir, @@ -176,6 +176,7 @@ # avoid ALSA/OSS detection for Windows environment has_alsa=no has_oss=no + has_pulseaudio=no ;; *) # ALSA @@ -192,10 +193,15 @@ )) ;; esac + # ESounD has_esd=yes AC_CHECK_HEADERS(esd.h,,has_esd=no) +# PulseAudio +has_pulseaudio=no +AC_CHECK_LIB(pulse-simple,pa_simple_new,AC_CHECK_HEADERS(pulse/simple.h, has_pulseaudio=yes)) + dnl Checks for default audio input API (order is important) if test "$with_mictype" = auto; then AC_MSG_CHECKING(for input device type) @@ -207,18 +213,22 @@ altype=alsa elif test "$has_oss" = yes; then altype=oss + elif test "$has_pulseaudio" = yes; then + altype=pulseaudio elif test "$has_esd" = yes; then altype=esd else - AC_MSG_ERROR([no audio io avaiable!]) + AC_MSG_ERROR([none of alsa/oss/pulseaudio/esd header/lib found!]) fi ;; freebsd*) # FreeBSD (snd driver) if test "$has_oss" = yes; then altype=freebsd + elif test "$has_pulseaudio" = yes; then + altype=pulseaudio else - AC_MSG_ERROR([no soundcard.h found]) + AC_MSG_ERROR([no soundcard.h or pulseaudio header/lib found!]) fi ;; darwin*) @@ -242,9 +252,9 @@ # AC_TRY_CPP([#include ],altype=osf1) # ;; cygwin*|mingw*) - # minGW - portaudio (auto select winmm / dsound) - altype=portaudio - ;; + # minGW - portaudio (auto select winmm / dsound) + altype=portaudio + ;; esac AC_MSG_RESULT($altype) else @@ -286,6 +296,11 @@ # set appropritate parameters for the determined API SOUNDLIB="" ADINOBJ="" +# if PulseAudio exist, include it +if test "$has_pulseaudio" = yes; then + SOUNDLIB="$SOUNDLIB -lpulse-simple -lpulse" + ADINOBJ="$ADINOBJ src/adin/adin_pulseaudio.o" +fi # if esd exist, include it if test "$has_esd" = yes; then SOUNDLIB="$SOUNDLIB -lesd" @@ -408,7 +423,14 @@ AC_DEFINE(USE_MIC) ADINOBJ="$ADINOBJ src/adin/adin_mic_linux.o" ;; - + pulseaudio) + if test "$has_pulseaudio" = no; then + AC_MSG_ERROR([no PulseAudio header!]) + fi + aldesc="PulseAudio" + AC_DEFINE(USE_MIC) + ADINOBJ="$ADINOBJ src/adin/adin_mic_linux.o" + ;; freebsd) if test "$has_oss" = no; then AC_MSG_ERROR([neither sys/soundcard.h nor machine/soundcard.h exist])