From 61f17cde172c8f84c73f5618a88cf207520195eb Mon Sep 17 00:00:00 2001 From: rossb Date: Mon, 15 May 2006 03:58:09 +0000 Subject: [PATCH] tagging before directory restructure --- Makefile.darwin | 194 + Makefile.in | 109 +- Makefile.linux | 59 - Makefile.mingw | 57 - README.txt | 2 +- SConscript | 268 + SConstruct | 31 + V19-devel-readme.txt | 222 + aclocal.m4 | 57 + config.doxy | 185 + config.sub | Bin 28332 -> 31743 bytes configure | Bin 81647 -> 176975 bytes configure.in | 241 +- docs/index.html | 14 +- docs/proposals.html | Bin 1085 -> 1084 bytes docs/style.html | 156 - pa_asio/ASIO-README.txt | 137 + pa_asio/borland_asio_readme.txt | 6 - pa_asio/iasiothiscallresolver.cpp | 563 +++ pa_asio/iasiothiscallresolver.h | 197 + pa_asio/pa_asio.cpp | 5222 ++++++++++---------- pa_asio/pa_asio.h | 122 + pa_asio/readme_asio_sdk_patch.txt | 25 - pa_common/pa_allocation.c | 234 + pa_common/pa_allocation.h | 95 + pa_common/pa_convert.c | 402 -- pa_common/pa_converters.c | 1926 ++++++++ pa_common/pa_converters.h | 254 + pa_common/pa_cpuload.c | 96 + pa_common/pa_cpuload.h | 63 + pa_common/pa_dither.c | 204 + pa_common/pa_dither.h | 91 + pa_common/pa_endianness.h | 130 + pa_common/pa_front.c | 1981 ++++++++ pa_common/pa_host.h | 185 - pa_common/pa_hostapi.h | 244 + pa_common/pa_lib.c | 806 --- pa_common/pa_process.c | 1763 +++++++ pa_common/pa_process.h | 741 +++ pa_common/pa_skeleton.c | 807 +++ pa_common/pa_stream.c | 141 + pa_common/pa_stream.h | 196 + pa_common/pa_trace.c | 31 +- pa_common/pa_trace.h | 31 +- pa_common/pa_types.h | 65 + pa_common/pa_util.h | 167 + pa_common/portaudio.h | 1254 +++-- pa_jack/pa_jack.c | 1714 +++++++ pa_linux_alsa/pa_linux_alsa.c | 3309 +++++++++++++ pa_linux_alsa/pa_linux_alsa.h | 64 + pa_mac/pa_mac_hostapis.c | 79 + pa_mac_core/notes.txt | 117 +- pa_mac_core/pa_mac_core.c | 2900 +++++++---- pa_mac_core/pa_mac_core.h | 69 + pa_mac_core/pa_mac_core_blocking.c | 484 ++ pa_mac_core/pa_mac_core_blocking.h | 82 + pa_mac_core/pa_mac_core_old.c | 907 ++++ pa_mac_core/pa_mac_core_utilities.c | 571 +++ pa_mac/pa_mac.c => pa_mac_sm/pa_mac_sm.c | 0 pa_sgi/Makefile | 53 - pa_sgi/pa_sgi.c | 2159 ++++---- pa_sgi/pthread-Makefile | 52 - pa_sgi/pthread-pa_sgi.c | 908 ---- pa_tests/README.txt | 60 + pa_tests/pa_devs.c | 204 +- pa_tests/pa_fuzz.c | 57 +- pa_tests/pa_minlat.c | 95 +- pa_tests/paqa_devs.c | 216 +- pa_tests/paqa_errs.c | 490 +- pa_tests/patest1.c | 202 +- pa_tests/patest_buffer.c | 77 +- pa_tests/patest_callbackstop.c | 221 + pa_tests/patest_clip.c | 78 +- pa_tests/patest_dither.c | 162 +- pa_tests/patest_hang.c | 79 +- pa_tests/patest_in_overflow.c | 224 + pa_tests/patest_latency.c | 66 +- pa_tests/patest_leftright.c | 65 +- pa_tests/patest_longsine.c | 55 +- pa_tests/patest_many.c | 46 +- pa_tests/patest_maxsines.c | 102 +- pa_tests/patest_mono.c | 145 + pa_tests/patest_mono_asio_channel_select.c | 155 + pa_tests/patest_multi_sine.c | 202 +- pa_tests/patest_out_underflow.c | 217 + pa_tests/patest_pink.c | 112 +- pa_tests/patest_prime.c | 223 + pa_tests/patest_read_record.c | 229 + pa_tests/patest_read_write_wire.c | 178 + pa_tests/patest_record.c | 191 +- pa_tests/patest_ringmix.c | 56 +- pa_tests/patest_saw.c | 45 +- pa_tests/patest_sine.c | 60 +- pa_tests/patest_sine8.c | 118 +- pa_tests/patest_sine_formats.c | 59 +- pa_tests/patest_sine_time.c | 175 +- pa_tests/patest_start_stop.c | 162 + pa_tests/patest_stop.c | 134 +- pa_tests/patest_stop_playout.c | 432 ++ pa_tests/patest_sync.c | 124 +- pa_tests/patest_toomanysines.c | 55 +- pa_tests/patest_two_rates.c | 168 + pa_tests/patest_underflow.c | 44 +- pa_tests/patest_wire.c | 270 +- pa_tests/patest_write_sine.c | 147 + pa_unix/pa_unix_hostapis.c | 64 + pa_unix/pa_unix_util.c | 672 +++ pa_unix/pa_unix_util.h | 179 + pa_unix_oss/Makefile | 43 - pa_unix_oss/Makefile_freebsd | 36 - pa_unix_oss/pa_unix_oss.c | 2569 ++++++---- pa_win/dev-cpp/Makefile-dll | 78 + pa_win/dev-cpp/Makefile-static | 75 + pa_win/dev-cpp/portaudio-dll.dev | 209 + pa_win/dev-cpp/portaudio-static.dev | 209 + pa_win/dev-cpp/readme.txt | 23 + pa_win/msvc/Makefile.msvc | 159 + pa_win/msvc/clean.bat | 7 + pa_win/msvc/make.bat | 8 + pa_win/msvc/portaudio.def | 43 + pa_win/msvc/readme.txt | 56 + pa_win/msvc/setenv.bat | 1 + pa_win/pa_win_hostapis.c | 91 + pa_win/pa_win_util.c | 134 + pa_win/pa_x86_plain_converters.c | 1167 +++++ pa_win/pa_x86_plain_converters.h | 19 + pa_win_ds/dsound_wrapper.c | 91 +- pa_win_ds/dsound_wrapper.h | 37 +- pa_win_ds/pa_dsound.c | 1021 ---- pa_win_ds/pa_win_ds.c | 2178 ++++++++ pa_win_ds/pa_win_ds_dynlink.c | 121 + pa_win_ds/pa_win_ds_dynlink.h | 82 + pa_win_ds/portaudio.def | 28 - pa_win_wasapi/pa_win_wasapi.cpp | 1770 +++++++ pa_win_wdmks/pa_win_wdmks.c | 3269 ++++++++++++ pa_win_wdmks/readme.txt | 82 + pa_win_wmme/Makefile.cygwin | 34 - pa_win_wmme/pa_win_wmme.c | 4655 ++++++++++++----- pa_win_wmme/pa_win_wmme.h | 160 + portaudio-2.0.pc.in | 11 + scons/SConscript_common | 23 + scons/SConscript_opts | 85 + testcvs/changeme.txt | 3 +- testcvs/stuff/info.txt | 1 - 144 files changed, 46285 insertions(+), 12650 deletions(-) create mode 100644 Makefile.darwin delete mode 100644 Makefile.linux delete mode 100644 Makefile.mingw create mode 100644 SConscript create mode 100644 SConstruct create mode 100644 V19-devel-readme.txt create mode 100644 aclocal.m4 create mode 100644 config.doxy delete mode 100644 docs/style.html create mode 100644 pa_asio/ASIO-README.txt delete mode 100644 pa_asio/borland_asio_readme.txt create mode 100644 pa_asio/iasiothiscallresolver.cpp create mode 100644 pa_asio/iasiothiscallresolver.h create mode 100644 pa_asio/pa_asio.h delete mode 100755 pa_asio/readme_asio_sdk_patch.txt create mode 100644 pa_common/pa_allocation.c create mode 100644 pa_common/pa_allocation.h delete mode 100644 pa_common/pa_convert.c create mode 100644 pa_common/pa_converters.c create mode 100644 pa_common/pa_converters.h create mode 100644 pa_common/pa_cpuload.c create mode 100644 pa_common/pa_cpuload.h create mode 100644 pa_common/pa_dither.c create mode 100644 pa_common/pa_dither.h create mode 100644 pa_common/pa_endianness.h create mode 100644 pa_common/pa_front.c delete mode 100644 pa_common/pa_host.h create mode 100644 pa_common/pa_hostapi.h delete mode 100644 pa_common/pa_lib.c create mode 100644 pa_common/pa_process.c create mode 100644 pa_common/pa_process.h create mode 100644 pa_common/pa_skeleton.c create mode 100644 pa_common/pa_stream.c create mode 100644 pa_common/pa_stream.h create mode 100644 pa_common/pa_types.h create mode 100644 pa_common/pa_util.h create mode 100644 pa_jack/pa_jack.c create mode 100644 pa_linux_alsa/pa_linux_alsa.c create mode 100644 pa_linux_alsa/pa_linux_alsa.h create mode 100644 pa_mac/pa_mac_hostapis.c create mode 100644 pa_mac_core/pa_mac_core.h create mode 100644 pa_mac_core/pa_mac_core_blocking.c create mode 100644 pa_mac_core/pa_mac_core_blocking.h create mode 100644 pa_mac_core/pa_mac_core_old.c create mode 100644 pa_mac_core/pa_mac_core_utilities.c rename pa_mac/pa_mac.c => pa_mac_sm/pa_mac_sm.c (100%) delete mode 100644 pa_sgi/Makefile delete mode 100644 pa_sgi/pthread-Makefile delete mode 100644 pa_sgi/pthread-pa_sgi.c create mode 100644 pa_tests/README.txt create mode 100644 pa_tests/patest_callbackstop.c create mode 100644 pa_tests/patest_in_overflow.c create mode 100644 pa_tests/patest_mono.c create mode 100644 pa_tests/patest_mono_asio_channel_select.c create mode 100644 pa_tests/patest_out_underflow.c create mode 100644 pa_tests/patest_prime.c create mode 100644 pa_tests/patest_read_record.c create mode 100644 pa_tests/patest_read_write_wire.c create mode 100644 pa_tests/patest_start_stop.c create mode 100644 pa_tests/patest_stop_playout.c create mode 100644 pa_tests/patest_two_rates.c create mode 100644 pa_tests/patest_write_sine.c create mode 100644 pa_unix/pa_unix_hostapis.c create mode 100644 pa_unix/pa_unix_util.c create mode 100644 pa_unix/pa_unix_util.h delete mode 100644 pa_unix_oss/Makefile delete mode 100644 pa_unix_oss/Makefile_freebsd create mode 100644 pa_win/dev-cpp/Makefile-dll create mode 100644 pa_win/dev-cpp/Makefile-static create mode 100644 pa_win/dev-cpp/portaudio-dll.dev create mode 100644 pa_win/dev-cpp/portaudio-static.dev create mode 100644 pa_win/dev-cpp/readme.txt create mode 100644 pa_win/msvc/Makefile.msvc create mode 100755 pa_win/msvc/clean.bat create mode 100755 pa_win/msvc/make.bat create mode 100644 pa_win/msvc/portaudio.def create mode 100644 pa_win/msvc/readme.txt create mode 100755 pa_win/msvc/setenv.bat create mode 100644 pa_win/pa_win_hostapis.c create mode 100644 pa_win/pa_win_util.c create mode 100644 pa_win/pa_x86_plain_converters.c create mode 100644 pa_win/pa_x86_plain_converters.h delete mode 100644 pa_win_ds/pa_dsound.c create mode 100644 pa_win_ds/pa_win_ds.c create mode 100644 pa_win_ds/pa_win_ds_dynlink.c create mode 100644 pa_win_ds/pa_win_ds_dynlink.h delete mode 100644 pa_win_ds/portaudio.def create mode 100644 pa_win_wasapi/pa_win_wasapi.cpp create mode 100644 pa_win_wdmks/pa_win_wdmks.c create mode 100644 pa_win_wdmks/readme.txt delete mode 100644 pa_win_wmme/Makefile.cygwin create mode 100644 pa_win_wmme/pa_win_wmme.h create mode 100644 portaudio-2.0.pc.in create mode 100644 scons/SConscript_common create mode 100644 scons/SConscript_opts delete mode 100644 testcvs/stuff/info.txt diff --git a/Makefile.darwin b/Makefile.darwin new file mode 100644 index 0000000..827e6eb --- /dev/null +++ b/Makefile.darwin @@ -0,0 +1,194 @@ +# +# PortAudio V19 Makefile.darwin +# +# Bjorn Roche of XO Audio (www.xoaudio.com) +# Based on autoconf's makefile, created from Makefile.in by Dominic Mazzoni +# + + +PREFIX = /usr/local +CC = gcc +CFLAGS = -g -arch i386 -arch ppc -isysroot /Developer/SDKs/MacOSX10.4u.sdk -mmacosx-version-min=10.3 -O2 -Wall -pedantic -pipe -fPIC -DPA_BIG_ENDIAN -Ipa_common -DPACKAGE_NAME=\"\" -DPACKAGE_TARNAME=\"\" -DPACKAGE_VERSION=\"\" -DPACKAGE_STRING=\"\" -DPACKAGE_BUGREPORT=\"\" -DSTDC_HEADERS=1 -DHAVE_SYS_TYPES_H=1 -DHAVE_SYS_STAT_H=1 -DHAVE_STDLIB_H=1 -DHAVE_STRING_H=1 -DHAVE_MEMORY_H=1 -DHAVE_STRINGS_H=1 -DHAVE_INTTYPES_H=1 -DHAVE_STDINT_H=1 -DHAVE_UNISTD_H=1 -DSIZEOF_SHORT=2 -DSIZEOF_INT=4 -DSIZEOF_LONG=4 -DPA_USE_COREAUDIO=1 +LIBS = -framework CoreAudio -framework AudioToolbox -framework AudioUnit -framework Carbon +AR = /usr/bin/ar +RANLIB = ranlib +INSTALL = /usr/bin/install -c +SHARED_FLAGS = -framework CoreAudio -framework AudioToolbox -framework AudioUnit -framework Carbon -dynamiclib -arch i386 -arch ppc -isysroot /Developer/SDKs/MacOSX10.4u.sdk -mmacosx-version-min=10.3 +DLL_LIBS = +CXXFLAGS = +NASM = +NASMOPT = + +OTHER_OBJS = pa_mac/pa_mac_hostapis.o pa_unix/pa_unix_util.o pa_mac_core/pa_mac_core.o + +PALIB = libportaudio.a +PADLL = libportaudio +PADLLV_MIN = 19 +PADLLV = 0.0.19 +PADLLEXT = .dylib +PASHLIBNAME = $(PADLL).$(PADLLV)$(PADLLEXT) +PAINC = pa_common/portaudio.h + +COMMON_OBJS = \ + pa_common/pa_allocation.o \ + pa_common/pa_converters.o \ + pa_common/pa_cpuload.o \ + pa_common/pa_dither.o \ + pa_common/pa_front.o \ + pa_common/pa_process.o \ + pa_common/pa_skeleton.o \ + pa_common/pa_stream.o \ + pa_common/pa_trace.o + +TESTS = \ + bin/paqa_devs \ + bin/paqa_errs \ + bin/patest1 \ + bin/patest_buffer \ + bin/patest_callbackstop \ + bin/patest_clip \ + bin/patest_dither \ + bin/patest_hang \ + bin/patest_in_overflow \ + bin/patest_latency \ + bin/patest_leftright \ + bin/patest_longsine \ + bin/patest_many \ + bin/patest_maxsines \ + bin/patest_multi_sine \ + bin/patest_out_underflow \ + bin/patest_pink \ + bin/patest_prime \ + bin/patest_read_record \ + bin/patest_read_write_wire \ + bin/patest_record \ + bin/patest_ringmix \ + bin/patest_saw \ + bin/patest_sine8 \ + bin/patest_sine \ + bin/patest_sine_formats \ + bin/patest_sine_time \ + bin/patest_start_stop \ + bin/patest_stop \ + bin/patest_sync \ + bin/patest_toomanysines \ + bin/patest_underflow \ + bin/patest_wire \ + bin/patest_write_sine \ + bin/pa_devs \ + bin/pa_fuzz \ + bin/pa_minlat + +# Most of these don't compile yet. Put them in TESTS, above, if +# you want to try to compile them... +ALL_TESTS = \ + bin/debug_convert \ + bin/debug_dither_calc \ + bin/debug_dual \ + bin/debug_multi_in \ + bin/debug_multi_out \ + bin/debug_record \ + bin/debug_record_reuse \ + bin/debug_sine_amp \ + bin/debug_sine \ + bin/debug_sine_formats \ + bin/debug_srate \ + bin/debug_test1 \ + bin/pa_devs \ + bin/pa_fuzz \ + bin/pa_minlat \ + bin/paqa_devs \ + bin/paqa_errs \ + bin/patest1 \ + bin/patest_buffer \ + bin/patest_clip \ + bin/patest_dither \ + bin/patest_hang \ + bin/patest_in_overflow \ + bin/patest_latency \ + bin/patest_leftright \ + bin/patest_longsine \ + bin/patest_many \ + bin/patest_maxsines \ + bin/patest_multi_sine \ + bin/patest_out_underflow \ + bin/patest_pink \ + bin/patest_read_record \ + bin/patest_record \ + bin/patest_ringmix \ + bin/patest_saw \ + bin/patest_sine8 \ + bin/patest_sine \ + bin/patest_sine_formats \ + bin/patest_sine_time \ + bin/patest_start_stop \ + bin/patest_stop \ + bin/patest_sync \ + bin/patest_toomanysines \ + bin/patest_underflow \ + bin/patest_wire \ + bin/patest_write_sine + +OBJS = $(COMMON_OBJS) $(OTHER_OBJS) + +all: lib/$(PALIB) lib/$(PASHLIBNAME) tests + +tests: bin/ $(TESTS) + +lib/$(PALIB): lib/ $(OBJS) Makefile.darwin $(PAINC) + -rm lib/$(PALIB) + $(AR) ruv lib/$(PALIB) $(OBJS) + $(RANLIB) lib/$(PALIB) + +lib/$(PASHLIBNAME): lib/ $(OBJS) Makefile.darwin $(PAINC) + $(CC) $(SHARED_FLAGS) -o lib/$(PASHLIBNAME) $(OBJS) $(DLL_LIBS) -install_name $(PREFIX)/lib/$(PASHLIBNAME) -compatibility_version $(PADLLV) -current_version $(PADLLV) + +$(TESTS): bin/%: lib/$(PALIB) Makefile.darwin $(PAINC) pa_tests/%.c + $(CC) -o $@ $(CFLAGS) pa_tests/$*.c lib/$(PALIB) $(LIBS) + +install: lib/$(PALIB) lib/$(PASHLIBNAME) portaudio-2.0.pc + $(INSTALL) -d $(PREFIX)/lib + $(INSTALL) -m 644 lib/$(PASHLIBNAME) $(PREFIX)/lib/$(PASHLIBNAME) + $(INSTALL) -m 644 lib/$(PALIB) $(PREFIX)/lib/$(PALIB) + cd $(PREFIX)/lib && rm -f $(PADLL)$(PADLLEXT) && ln -s $(PASHLIBNAME) $(PADLL)$(PADLLEXT) + $(INSTALL) -d $(PREFIX)/include + $(INSTALL) -m 644 pa_common/portaudio.h $(PREFIX)/include/portaudio.h + $(INSTALL) -d $(PREFIX)/lib/pkgconfig + $(INSTALL) -m 644 portaudio-2.0.pc $(PREFIX)/lib/pkgconfig/portaudio-2.0.pc + @echo "" + @echo "------------------------------------------------------------" + @echo "PortAudio was successfully installed." + @echo "" + @echo "On some systems (e.g. Linux) you should run 'ldconfig' now" + @echo "to make the shared object available. You may also need to" + @echo "modify your LD_LIBRARY_PATH environment variable to include" + @echo "the directory $(PREFIX)/lib" + @echo "------------------------------------------------------------" + @echo "" + +uninstall: + rm -f $(PREFIX)/lib/$(PASHLIBNAME) + rm -f $(PREFIX)/lib/$(PALIB) + rm -f $(PREFIX)/lib/$(PADLL)$(PADLLEXT) + rm -f $(PREFIX)/include/portaudio.h + +clean: + rm -f $(OBJS) $(TESTS) lib/$(PALIB) lib/$(PASHLIBNAME) + +%.o: %.c Makefile.darwin $(PAINC) + $(CC) -c $(CFLAGS) $< -o $@ + +%.o: %.cpp Makefile.darwin $(PAINC) + $(CXX) -c $(CXXFLAGS) $< -o $@ + +%.o: %.asm + $(NASM) $(NASMOPT) -o $@ $< + +bin: + mkdir bin + +lib: + mkdir lib + + + diff --git a/Makefile.in b/Makefile.in index 2a3cc34..9ca01ce 100644 --- a/Makefile.in +++ b/Makefile.in @@ -1,42 +1,61 @@ # -# PortAudio Makefile.in +# PortAudio V19 Makefile.in # # Dominic Mazzoni # PREFIX = @prefix@ CC = @CC@ -CFLAGS = @CFLAGS@ -Ipa_common +CFLAGS = @CFLAGS@ -Ipa_common @DEFS@ LIBS = @LIBS@ AR = @AR@ RANLIB = @RANLIB@ INSTALL = @INSTALL@ SHARED_FLAGS = @SHARED_FLAGS@ DLL_LIBS = @DLL_LIBS@ +CXXFLAGS = @CXXFLAGS@ +NASM = @NASM@ +NASMOPT = @NASMOPT@ OTHER_OBJS = @OTHER_OBJS@ PALIB = libportaudio.a PADLL = @PADLL@ -PADLLV = $(PADLL).0.0.18 +PADLLV = $(PADLL).0.0.19 PAINC = pa_common/portaudio.h COMMON_OBJS = \ - pa_common/pa_convert.o \ - pa_common/pa_lib.o + pa_common/pa_allocation.o \ + pa_common/pa_converters.o \ + pa_common/pa_cpuload.o \ + pa_common/pa_dither.o \ + pa_common/pa_front.o \ + pa_common/pa_process.o \ + pa_common/pa_skeleton.o \ + pa_common/pa_stream.o \ + pa_common/pa_trace.o TESTS = \ + bin/paqa_devs \ + bin/paqa_errs \ + bin/patest1 \ bin/patest_buffer \ + bin/patest_callbackstop \ bin/patest_clip \ bin/patest_dither \ bin/patest_hang \ + bin/patest_in_overflow \ bin/patest_latency \ bin/patest_leftright \ bin/patest_longsine \ bin/patest_many \ bin/patest_maxsines \ bin/patest_multi_sine \ + bin/patest_out_underflow \ bin/patest_pink \ + bin/patest_prime \ + bin/patest_read_record \ + bin/patest_read_write_wire \ bin/patest_record \ bin/patest_ringmix \ bin/patest_saw \ @@ -44,11 +63,66 @@ TESTS = \ bin/patest_sine \ bin/patest_sine_formats \ bin/patest_sine_time \ + bin/patest_start_stop \ bin/patest_stop \ bin/patest_sync \ bin/patest_toomanysines \ bin/patest_underflow \ - bin/patest_wire + bin/patest_wire \ + bin/patest_write_sine \ + bin/pa_devs \ + bin/pa_fuzz \ + bin/pa_minlat + +# Most of these don't compile yet. Put them in TESTS, above, if +# you want to try to compile them... +ALL_TESTS = \ + bin/debug_convert \ + bin/debug_dither_calc \ + bin/debug_dual \ + bin/debug_multi_in \ + bin/debug_multi_out \ + bin/debug_record \ + bin/debug_record_reuse \ + bin/debug_sine_amp \ + bin/debug_sine \ + bin/debug_sine_formats \ + bin/debug_srate \ + bin/debug_test1 \ + bin/pa_devs \ + bin/pa_fuzz \ + bin/pa_minlat \ + bin/paqa_devs \ + bin/paqa_errs \ + bin/patest1 \ + bin/patest_buffer \ + bin/patest_clip \ + bin/patest_dither \ + bin/patest_hang \ + bin/patest_in_overflow \ + bin/patest_latency \ + bin/patest_leftright \ + bin/patest_longsine \ + bin/patest_many \ + bin/patest_maxsines \ + bin/patest_multi_sine \ + bin/patest_out_underflow \ + bin/patest_pink \ + bin/patest_read_record \ + bin/patest_record \ + bin/patest_ringmix \ + bin/patest_saw \ + bin/patest_sine8 \ + bin/patest_sine \ + bin/patest_sine_formats \ + bin/patest_sine_time \ + bin/patest_start_stop \ + bin/patest_stop \ + bin/patest_sync \ + bin/patest_toomanysines \ + bin/patest_underflow \ + bin/patest_wire \ + bin/patest_write_sine OBJS = $(COMMON_OBJS) $(OTHER_OBJS) @@ -66,11 +140,15 @@ lib/$(PADLLV): lib/ $(OBJS) Makefile $(PAINC) $(TESTS): bin/%: lib/$(PALIB) Makefile $(PAINC) pa_tests/%.c $(CC) -o $@ $(CFLAGS) pa_tests/$*.c lib/$(PALIB) $(LIBS) -install: lib/$(PALIB) lib/$(PADLLV) +install: lib/$(PALIB) lib/$(PADLLV) portaudio-2.0.pc + $(INSTALL) -d $(PREFIX)/lib $(INSTALL) -m 644 lib/$(PADLLV) $(PREFIX)/lib/$(PADLLV) $(INSTALL) -m 644 lib/$(PALIB) $(PREFIX)/lib/$(PALIB) cd $(PREFIX)/lib && rm -f $(PADLL) && ln -s $(PADLLV) $(PADLL) + $(INSTALL) -d $(PREFIX)/include $(INSTALL) -m 644 pa_common/portaudio.h $(PREFIX)/include/portaudio.h + $(INSTALL) -d $(PREFIX)/lib/pkgconfig + $(INSTALL) -m 644 portaudio-2.0.pc $(PREFIX)/lib/pkgconfig/portaudio-2.0.pc @echo "" @echo "------------------------------------------------------------" @echo "PortAudio was successfully installed." @@ -82,14 +160,29 @@ install: lib/$(PALIB) lib/$(PADLLV) @echo "------------------------------------------------------------" @echo "" +uninstall: + rm -f $(PREFIX)/lib/$(PADLLV) + rm -f $(PREFIX)/lib/$(PALIB) + rm -f $(PREFIX)/lib/$(PADLL) + rm -f $(PREFIX)/include/portaudio.h + clean: - rm -f $(OBJS) $(TESTS) lib/$(PALIB) + rm -f $(OBJS) $(TESTS) lib/$(PALIB) lib/$(PADLLV) %.o: %.c Makefile $(PAINC) $(CC) -c $(CFLAGS) $< -o $@ +%.o: %.cpp Makefile $(PAINC) + $(CXX) -c $(CXXFLAGS) $< -o $@ + +%.o: %.asm + $(NASM) $(NASMOPT) -o $@ $< + bin: mkdir bin lib: mkdir lib + + + diff --git a/Makefile.linux b/Makefile.linux deleted file mode 100644 index 4deee60..0000000 --- a/Makefile.linux +++ /dev/null @@ -1,59 +0,0 @@ -# Make PortAudio for Linux -# Updated 2001/08/25 Bill Eldridge bill@rfa.org -# Updated 2001/10/16, philburk@softsynth.com, s/unix_oss/unix_oss/ -# Updated 2002/04/30 Bill Eldridge bill@rfa.org -# Made the libinstall and tests compile a bit cleaner - -# A pretty bare makefile, that figures out all the test files -# and compiles them against the library in the pa_unix_oss directory. - -# Do "make all" and then when happy, "make libinstall" -# (if not happy, "make clean") - -# The ldconfig stuff in libinstall is the wrong way to do it - -# someone tell me the right way, please - - -LIBS = -lm -lpthread - -CDEFINES = -I../pa_common -CFLAGS = -g -LIBINST = /usr/local/lib - -TESTS:= $(wildcard pa_tests/pa*.c pa_tests/debug*.c) -TESTO:= $(wildcard pa_tests/pa*.o pa_tests/debug*.o) - -LIBFILES:= ./pa_common/pa_lib.c ./pa_unix_oss/pa_unix_oss.c - -#all: sharedlib libinstall tests -all: sharedlib libinstall testo testq - -.c.o: - -gcc -c -I./pa_common $< -o $*.o - -.o: - -gcc $*.o -o $* -Lpa_unix_oss $(LIBS) -lportaudio - -#.c.o: -# -gcc -c -I./pa_common $< -o $*.o -# -gcc $*.o -o $* -Lpa_unix_oss $(LIBS) -lportaudio - - -sharedlib: $(LIBFILES:.c=.o) - gcc -shared -o ./pa_unix_oss/libportaudio.so ./pa_common/pa_lib.o ./pa_unix_oss/pa_unix_oss.o - -libinstall: ./pa_unix_oss/libportaudio.so - @cp -f ./pa_unix_oss/libportaudio.so $(LIBINST) - @/sbin/ldconfig - -testo: $(TESTS:.c=.o) - -testq: $(TESTO:.o=) - -clean: - -@rm -f $(TESTS:.c=.o) - -@rm -f $(TESTS:.c=) - -@rm -f $(LIBFILES:.c=.o) - -@rm -f ./pa_unix_oss/libportaudio.so - - diff --git a/Makefile.mingw b/Makefile.mingw deleted file mode 100644 index 2043a16..0000000 --- a/Makefile.mingw +++ /dev/null @@ -1,57 +0,0 @@ - -# Makefile for PortAudio on mingw (http://mingw.sourceforge.net) - -# Contributed by Bill Eldridge, bill@rfa.org, Radio Free Asia -# Copyright 2002/02/20, GPL - -# Uses a common mingw32 cross-compiler that defaults -# to everything in /usr/local/cross-tools - -# First edit your path with -# export PATH=/usr/local/cross-tools/bin:$PATH - -# Usage: make -f Makefile.mingw all -# or make -f Makefile.mingw sharedlib -# make -f Makefile.mingw tests -# -# Then copy executables & portaudio.dll to your Windows machine -# -# To make work with pa_win_ds, you'll have to substitue -# all the pa_win_wmme files with pa_win_ds files, no biggie. - -CC= i586-mingw32msvc-gcc -DLLTOOL= i586-mingw32msvc-dlltool -DLLWRAP= i586-mingw32msvc-dllwrap - -ARCH= pa_win_wmme - -TESTS:= $(wildcard pa_tests/pa*.c pa_tests/debug*.c) - -.c.o: - -$(CC) -c -I./pa_common $< -o $*.o - -$(CC) $*.o -o $*.exe -L/usr/local/lib -L$(ARCH) -lportaudio.dll -lwinmm - -all: sharedlib tests - -sharedlib: ./pa_common/pa_lib.c - $(CC) -c -I./pa_common pa_common/pa_lib.c -o pa_common/pa_lib.o - $(CC) -c -I./pa_common pa_win_wmme/pa_win_wmme.c -o pa_win_wmme/pa_win_wmme.o - $(CC) -shared -mthreads -o portaudio.dll pa_common/pa_lib.o pa_win_wmme/pa_win_wmme.o -L/usr/local/cross-tools/i586-win32msvc/lib -lwinmm -lm - $(DLLWRAP) --export-all --output-def=libportaudio.def --output-lib=libportaudio.a --dllname=portaudio.dll --drivername=i586-mingw32msvc-gcc pa_common/pa_lib.o pa_win_wmme/pa_win_wmme.o -L/usr/local/cross-tools/i586-win32msvc/lib -lwinmm -lm - $(CC) -shared -Wl,--enable-auto-image-base -o portaudio.dll -Wl,--out-implib=pa_win_wmme/libportaudio.dll.a pa_common/pa_lib.o pa_win_wmme/pa_win_wmme.o -L/usr/local/cross-tools/i586-win32msvc/lib -lwinmm - - -tests: $(TESTS:.c=.o) - -sine: - $(CC) -c -I./pa_common pa_tests/patest_sine.c -o pa_tests/patest_sine.o - $(CC) pa_tests/patest_sine.o -o pa_tests/patest_sine.exe -L/usr/local/lib -lportaudio.dll -lwinmm - -clean: - -rm ./pa_tests/*.exe - -rm ./pa_tests/*.o - -nothing: - $(CC) pa_tests/patest_sine.o -L/usr/lib/w32api -L./pa_win_wmme -lportaudio.dll -lwinmm - - diff --git a/README.txt b/README.txt index d1e5d7d..4cfc616 100644 --- a/README.txt +++ b/README.txt @@ -58,7 +58,7 @@ Important Files and Folders: Platform Implementations pa_asio = ASIO for Windows and Macintosh pa_beos = BeOS - pa_mac = Macintosh Sound Manager for OS 8,9 and Carbon + pa_mac_sm = Macintosh Sound Manager for OS 8,9 and Carbon pa_mac_core = Macintosh Core Audio for OS X pa_sgi = Silicon Graphics AL pa_unix_oss = OSS implementation for various Unixes diff --git a/SConscript b/SConscript new file mode 100644 index 0000000..1677876 --- /dev/null +++ b/SConscript @@ -0,0 +1,268 @@ +import os.path, copy, sys + +# Inspired by the versioning scheme followed by Qt, it seems sensible enough. There are three components: major, minor +# and micro. Major changes with each subtraction from the API (backward-incompatible, i.e. V19 vs. V18), minor changes +# with each addition to the API (backward-compatible), micro changes with each revision of the source code. +ApiVer = "2.0.0" + +def checkSymbol(conf, header, library=None, symbol=None, autoAdd=True, critical=False, pkgName=None): + """ Check for symbol in library, optionally look only for header. + @param conf: Configure instance. + @param header: The header file where the symbol is declared. + @param library: The library in which the symbol exists, if None it is taken to be the standard C library. + @param symbol: The symbol to look for, if None only the header will be looked up. + @param autoAdd: Automatically link with this library if check is positive. + @param critical: Raise on error? + @param pkgName: Optional name of pkg-config entry for library, to determine build parameters. + @return: True/False + """ + origEnv = conf.env.Copy() # Copy unmodified environment so we can restore it upon error + env = conf.env + if library is None: + library = "c" # Standard library + autoAdd = False + + if pkgName is not None: + origLibs = copy.copy(env.get("LIBS", None)) + + try: env.ParseConfig("pkg-config --silence-errors %s --cflags --libs" % pkgName) + except: pass + else: + # I see no other way of checking that the parsing succeeded, if it did add no more linking parameters + if env.get("LIBS", None) != origLibs: + autoAdd = False + + try: + if not conf.CheckCHeader(header, include_quotes="<>"): + raise ConfigurationError("missing header %s" % header) + if symbol is not None and not conf.CheckLib(library, symbol, language="C", autoadd=autoAdd): + raise ConfigurationError("missing symbol %s in library %s" % (symbol, library)) + except ConfigurationError: + conf.env = origEnv + if not critical: + return False + raise + + return True + +import SCons.Errors + +# Import common variables + +try: + Import("Platform", "Posix", "ConfigurationError") +except SCons.Errors.UserError: + # The common objects must be exported first + SConscript(os.path.join("scons", "SConscript_common")) + Import("Platform", "Posix", "ConfigurationError") + +Import("env") + +# This will be manipulated +env = env.Copy() + +env.Append(CPPPATH="pa_common") + +# Store all signatures in one file, otherwise .sconsign files will get installed along with our own files +env.SConsignFile(os.path.join("scons", ".sconsign")) + +# We operate with a set of needed libraries and optional libraries, the latter stemming from host API implementations. +# For libraries of both types we record a set of values that is used to look for the library in question, during +# configuration. If the corresponding library for a host API implementation isn't found, the implementation is left out. +neededLibs = [] +optionalImpls = {} +if Platform in Posix: + neededLibs += [("pthread", "pthread.h", "pthread_create"), ("m", "math.h", "sin")] + if env["useALSA"]: + optionalImpls["ALSA"] = ("asound", "alsa/asoundlib.h", "snd_pcm_open") + if env["useJACK"]: + optionalImpls["JACK"] = ("jack", "jack/jack.h", "jack_client_new") + if env["useOSS"]: + # TODO: It looks like the prefix for soundcard.h depends on the platform + optionalImpls["OSS"] = ("oss", "sys/soundcard.h", None) +else: + raise ConfigurationError("unknown platform %s" % Platform) + +if Platform == "darwin": + env.Append(LINKFLAGS=["-framework CoreAudio", "-framework AudioToolBox"]) + env.Append(CPPDEFINES=["PA_USE_COREAUDIO"]) +elif Platform == "cygwin": + env.Append(LIBS=["winmm"]) +elif Platform == "irix": + neededLibs += [("audio", "dmedia/audio.h", "alOpenPort"), ("dmedia", "dmedia/dmedia.h", "dmGetUST")] + env.Append(CPPDEFINES=["PA_USE_SGI"]) + +def CheckCTypeSize(context, tp): + """ Check size of C type. + @param context: A configuration context. + @param tp: The type to check. + @return: Size of type, in bytes. + """ + context.Message("Checking the size of C type %s..." % tp) + ret = context.TryRun(""" +#include + +int main() { + printf("%%d", sizeof(%s)); + return 0; +} +""" % tp, ".c") + if not ret[0]: + print "Hihi" + context.Result(" Couldn't obtain size of type %s!" % tp) + return None + + assert ret[1] + sz = int(ret[1]) + context.Result("%d" % sz) + return sz + +if sys.byteorder == "little": + env.Append(CPPDEFINES=["PA_LITTLE_ENDIAN"]) +elif sys.byteorder == "big": + env.Append(CPPDEFINES=["PA_BIG_ENDIAN"]) +else: + raise ConfigurationError("unknown byte order: %s" % sys.byteorder) +if env["enableDebugOutput"]: + env.Append(CPPDEFINES=["PA_ENABLE_DEBUG_OUTPUT"]) + +# Start configuration + +# Use an absolute path for conf_dir, otherwise it gets created both relative to current directory and build directory +conf = env.Configure(log_file=os.path.join("scons", "sconf.log"), custom_tests={"CheckCTypeSize": CheckCTypeSize}, + conf_dir=os.path.join(os.getcwd(), "scons", ".sconf_temp")) +assert os.path.exists(os.path.join("scons", ".sconf_temp")) +env.Append(CPPDEFINES=["SIZEOF_SHORT=%d" % conf.CheckCTypeSize("short")]) +env.Append(CPPDEFINES=["SIZEOF_INT=%d" % conf.CheckCTypeSize("int")]) +env.Append(CPPDEFINES=["SIZEOF_LONG=%d" % conf.CheckCTypeSize("long")]) +if checkSymbol(conf, "time.h", "rt", "clock_gettime"): + env.Append(CPPDEFINES=["HAVE_CLOCK_GETTIME"]) +if checkSymbol(conf, "time.h", symbol="nanosleep"): + env.Append(CPPDEFINES=["HAVE_NANOSLEEP"]) + +# Look for needed libraries and link with them +for lib, hdr, sym in neededLibs: + checkSymbol(conf, hdr, lib, sym, critical=True) +# Look for host API libraries, if a library isn't found disable corresponding host API implementation. +for name, val in optionalImpls.items(): + lib, hdr, sym = val + if checkSymbol(conf, hdr, lib, sym, critical=False, pkgName=name.lower()): + env.Append(CPPDEFINES=["PA_USE_%s=1" % name.upper()]) + else: + del optionalImpls[name] + +# Configuration finished +env = conf.Finish() + +# PA infrastructure +CommonSources = [os.path.join("pa_common", f) for f in "pa_allocation.c pa_converters.c pa_cpuload.c pa_dither.c pa_front.c \ + pa_process.c pa_skeleton.c pa_stream.c pa_trace.c".split()] + +# Host API implementations +ImplSources = [] +if Platform in Posix: + ThreadCFlags = "-pthread" + env.AppendUnique(LINKFLAGS=[ThreadCFlags]) + BaseCFlags = "-Wall -pedantic -pipe %s" % ThreadCFlags + DebugCFlags = "-g" + OptCFlags = "-O2" + ImplSources += [os.path.join("pa_unix", f) for f in "pa_unix_hostapis.c pa_unix_util.c".split()] + +if "ALSA" in optionalImpls: + ImplSources.append(os.path.join("pa_linux_alsa", "pa_linux_alsa.c")) +if "JACK" in optionalImpls: + ImplSources.append(os.path.join("pa_jack", "pa_jack.c")) +if "OSS" in optionalImpls: + ImplSources.append(os.path.join("pa_unix_oss", "pa_unix_oss.c")) + +env["CCFLAGS"] = BaseCFlags +if env["enableDebug"]: + env["CCFLAGS"] += " " + DebugCFlags +if env["enableOptimize"]: + env["CCFLAGS"] += " " + OptCFlags +if not env["enableAsserts"]: + env.Append(CPPDEFINES=["-DNDEBUG"]) +if env["customCFlags"]: + env["CCFLAGS"] += " " + env["customCFlags"] +if env["customLinkFlags"]: + env["LINKFLAGS"] += " " + env["customLinkFlags"] + +sources = CommonSources + ImplSources + +if env["enableShared"]: + sharedLibEnv = env.Copy() + if Platform in Posix: + # Add soname to library, this is so a reference is made to the versioned library in programs linking against libportaudio.so + sharedLibEnv.AppendUnique(SHLINKFLAGS="-Wl,-soname=libportaudio.so.%d" % int(ApiVer.split(".")[0])) + sharedLib = sharedLibEnv.SharedLibrary(target="portaudio", source=sources) +else: + sharedLib = None +staticLib = env.StaticLibrary(target="portaudio", source=sources) + +if Platform in Posix: + prefix = env["prefix"] + includeDir = os.path.join(prefix, "include") + env.Alias("install", env.Install(includeDir, os.path.join("pa_common", "portaudio.h"))) + libDir = os.path.join(prefix, "lib") + + if env["enableStatic"]: + env.Alias("install", env.Install(libDir, staticLib)) + + def symlink(env, target, source): + trgt = str(target[0]) + src = str(source[0]) + + if os.path.lexists(trgt): + os.remove(trgt) + os.symlink(os.path.basename(src), trgt) + + if env["enableShared"]: + major, minor, micro = [int(c) for c in ApiVer.split(".")] + + soFile = "%s.%s" % (sharedLib[0], ApiVer) + env.Alias("install", env.InstallAs(target=os.path.join(libDir, soFile), source=sharedLib)) + # Install symlinks + symTrgt = os.path.join(libDir, soFile) + env.Alias("install", env.Command(os.path.join(libDir, "libportaudio.so.%d.%d" % (major, minor)), + symTrgt, symlink)) + symTrgt = symTrgt.rsplit(".", 1)[0] + env.Alias("install", env.Command(os.path.join(libDir, "libportaudio.so.%d" % major), symTrgt, symlink)) + symTrgt = symTrgt.rsplit(".", 1)[0] + env.Alias("install", env.Command(os.path.join(libDir, "libportaudio.so"), symTrgt, symlink)) + + # pkg-config + + def installPkgconfig(env, target, source): + tgt = str(target[0]) + src = str(source[0]) + f = open(src) + try: txt = f.read() + finally: f.close() + txt = txt.replace("@prefix@", prefix) + txt = txt.replace("@libdir@", libDir) + txt = txt.replace("@includedir@", includeDir) + txt = txt.replace("@LIBS@", " ".join(["-l%s" % l for l in env["LIBS"]])) + txt = txt.replace("@THREAD_CFLAGS@", ThreadCFlags) + + f = open(tgt, "w") + try: f.write(txt) + finally: f.close() + + pkgconfigTgt = "portaudio-%d.0.pc" % int(ApiVer.split(".", 1)[0]) + env.Alias("install", env.Command(os.path.join(libDir, "pkgconfig", pkgconfigTgt), + pkgconfigTgt + ".in", installPkgconfig)) + +testNames = ["patest_sine", "paqa_devs", "paqa_errs", "patest1", "patest_buffer", "patest_callbackstop", "patest_clip", \ + "patest_dither", "patest_hang", "patest_in_overflow", "patest_latency", "patest_leftright", "patest_longsine", \ + "patest_many", "patest_maxsines", "patest_multi_sine", "patest_out_underflow", "patest_pink", "patest_prime", \ + "patest_read_record", "patest_record", "patest_ringmix", "patest_saw", "patest_sine8", "patest_sine", \ + "patest_sine_time", "patest_start_stop", "patest_stop", "patest_sync", \ + "patest_toomanysines", "patest_underflow", "patest_wire", "patest_write_sine", "pa_devs", "pa_fuzz", "pa_minlat"] + +# The test directory ("bin") should be in the top-level PA directory, the calling script should ensure that SCons doesn't +# switch current directory by calling SConscriptChdir(False). Specifying an absolute directory for each target means it won't +# be relative to the build directory +tests = [env.Program(target=os.path.join(os.getcwd(), "bin", name), source=[os.path.join("pa_tests", name + ".c"), + staticLib]) for name in testNames] + +Return("sources", "sharedLib", "staticLib", "tests", "env") diff --git a/SConstruct b/SConstruct new file mode 100644 index 0000000..f7a262d --- /dev/null +++ b/SConstruct @@ -0,0 +1,31 @@ +import sys, os.path + +# SConscript_opts exports PortAudio options +optsDict = SConscript(os.path.join("scons", "SConscript_opts")) +optionsCache = os.path.join("scons", "options.cache") # Save options between runs in this cache +options = Options(optionsCache, args=ARGUMENTS) +for k in ("Installation Dirs", "Library Types", "Host APIs", "Build Parameters"): + options.AddOptions(*optsDict[k]) +# Propagate options into environment +env = Environment(options=options) +# Save options for next run +options.Save(optionsCache, env) +# Generate help text for options +env.Help(options.GenerateHelpText(env)) + +buildDir = os.path.join("#", "scons", "build") + +# Don't change directory when running the SConscript +env.SConscriptChdir(False) +sources, sharedLib, staticLib, tests, portEnv = env.SConscript("SConscript", build_dir=buildDir, duplicate=False, exports=["env"]) +# Build these by default +env.Default(sharedLib, staticLib, tests) + +""" +if env["enablePython"]: + env.SConscriptChdir(True) + pyEnv = env.Copy() + pyEnv["CCFLAGS"] = portEnv["CCFLAGS"].replace("-pedantic", "") + module = env.SConscript("python/SConscript", exports={"env": pyEnv, "BuildDir": BuildDir}) + env.Default(module) + """ diff --git a/V19-devel-readme.txt b/V19-devel-readme.txt new file mode 100644 index 0000000..ae5570e --- /dev/null +++ b/V19-devel-readme.txt @@ -0,0 +1,222 @@ +STATUS: + +MME, DirectSound and ASIO versions are more-or-less working. See FIXMEs @todos +and the proposals matrix at portaudio.com for further status. + +The pa_tests directory contains tests. pa_tests/README.txt notes which tests +currently build. + +The PaUtil support code is finished enough for other implementations to be +ported. No changes are expected to be made to the definition of the PaUtil +functions. + +Note that it's not yet 100% clear how the current support functions +will interact with blocking read/write streams. + +BUILD INSTRUCTIONS + +to build tests/patest_sine.c you will need to compile and link the following +files (MME) +pa_common\pa_process.c +pa_common\pa_skeleton.c +pa_common\pa_stream.c +pa_common\pa_trace.c +pa_common\pa_converters.c +pa_common\pa_cpuload.c +pa_common\pa_dither.c +pa_common\pa_front.c +pa_common\pa_allocation.h +pa_win\pa_win_util.c +pa_win\pa_win_hostapis.c +pa_win_wmme\pa_win_wmme.c + +see below for a description of these files. + + +FILES: + +portaudio.h + public api header file + +pa_front.c + implements the interface defined in portaudio.h. manages multiple host apis. + validates function parameters before calling through to host apis. tracks + open streams and closes them at Pa_Terminate(). + +pa_util.h + declares utility functions for use my implementations. including utility + functions which must be implemented separately for each platform. + +pa_hostapi.h + hostapi representation structure used to interface between pa_front.c + and implementations + +pa_stream.c/h + stream interface and representation structures and helper functions + used to interface between pa_front.c and implementations + +pa_cpuload.c/h + source and header for cpu load calculation facility + +pa_trace.c/h + source and header for debug trace log facility + +pa_converters.c/h + sample buffer conversion facility + +pa_dither.c/h + dither noise generator + +pa_process.c/h + callback buffer processing facility including interleave and block adaption + +pa_allocation.c/h + allocation context for tracking groups of allocations + +pa_skeleton.c + an skeleton implementation showing how the common code can be used. + +pa_win_util.c + Win32 implementation of platform specific PaUtil functions (memory allocation, + usec clock, Pa_Sleep().) The file will be used with all Win32 host APIs. + +pa_win_hostapis.c + contains the paHostApiInitializers array and an implementation of + Pa_GetDefaultHostApi() for win32 builds. + +pa_win_wmme.c + Win32 host api implementation for the windows multimedia extensions audio API. + +pa_win_wmme.h + public header file containing interfaces to mme-specific functions and the + deviceInfo data structure. + + +CODING GUIDELINES: + +naming conventions: + #defines begin with PA_ + #defines local to a file end with _ + global utility variables begin with paUtil + global utility types begin with PaUtil (including function types) + global utility functions begin with PaUtil_ + static variables end with _ + static constants begin with const and end with _ + static funtions have no special prefix/suffix + +In general, implementations should declare all of their members static, +except for their initializer which should be exported. All exported names +should be preceeded by Pa_ where MN is the module name, for example +the windows mme initializer should be named PaWinWmme_Initialize(). + +Every host api should define an initializer which returns an error code +and a PaHostApiInterface*. The initializer should only return an error other +than paNoError if it encounters an unexpected and fatal error (memory allocation +error for example). In general, there may be conditions under which it returns +a NULL interface pointer and also returns paNoError. For example, if the ASIO +implementation detects that ASIO is not installed, it should return a +NULL interface, and paNoError. + +Platform-specific shared functions should begin with Pa_ where PN is the +platform name. eg. PaWin_ for windows, PaUnix_ for unix. + +The above two conventions should also be followed whenever it is necessary to +share functions accross multiple source files. + +Two utilities for debug messages are provided. The PA_DEBUG macro defined in +pa_implementation.h provides a simple way to print debug messages to stderr. +Due to real-time performance issues, PA_DEBUG may not be suitable for use +within the portaudio processing callback, or in other threads. In such cases +the event tracing facility provided in pa_trace.h may be more appropriate. + +If PA_LOG_API_CALLS is defined, all calls to the public PortAudio API +will be logged to stderr along with parameter and return values. + + +TODO: + (this list is totally out of date) + + finish coding converter functions in pa_converters.c (anyone?) + + implement block adaption in pa_process.c (phil?) + + fix all current tests to work with new code. this should mostly involve + changing PortAudioStream to PaStream, and GetDefaultDeviceID to GetDefaultDevice etc. + + write some new tests to exercise the multi-api functions + + write (doxygen) documentation for pa_trace (phil?) + + remove unused typeids from PaHostAPITypeID + + create a global configuration file which documents which PA_ defines can be + used for configuration + + need a coding standard for comment formatting + + migrate directx (phil) + + migrate asio (ross?, stephane?) + + see top of pa_win_wmme.c for MME todo items (ross) + + write style guide document (ross) + + +DESIGN ISSUES: + (this list is totally out of date) + + consider removing Pa_ConvertHostApiDeviceIndexToGlobalDeviceIndex() from the API + + switch to new latency parameter mechanism now (?) + + question: if input or outputDriverInfo structures are passed for a different + hostApi from the one being called, do we return an error or just ignore + them? (i think return error) + + consider renaming PortAudioCallback to PaStreamCallback + + consider renaming PaError, PaResult + + +ASSORTED DISORGANISED NOTES: + + NOTE: + pa_lib.c performs the following validations for Pa_OpenStream() which we do not currently do: + - checks the device info to make sure that the device supports the requested sample rate, + it may also change the sample rate to the "closest available" sample rate if it + is within a particular error margin + + rationale for breaking up internalPortAudioStream: + each implementation has its own requirements and behavior, and should be + able to choose the best way to operate without being limited by the + constraints imposed by a common infrastructure. in other words the + implementations should be able to pick and choose services from the + common infrastructure. currently identified services include: + + - cpu load tracking + - buffering and conversion service (same code works for input and output) + - should support buffer multiplexing (non-integer length input and output buffers) + - in-place conversion where possible (only for callback, read/write always copies) + - should manage allocation of temporary buffers if necessary + - instrumentation (should be able to be disabled): callback count, framesProcessed + - common data: magic, streamInterface, callback, userdata + + +- conversion functions: + - should handle temp buffer allocation + - dithering (random number state per-stream) + - buffer size mismatches + - with new buffer slip rules, temp buffers may always be needed + - we should aim for in-place conversion wherever possible + - does phil's code support in-place conversion? (yes) + +- dicuss relationship between user and host buffer sizes + - completely independent.. individual implementations may constrain + host buffer sizes if necessary + + +- discuss device capabilities: + - i'd like to be able to request certain information: + - channel count for example + diff --git a/aclocal.m4 b/aclocal.m4 new file mode 100644 index 0000000..c80e0ac --- /dev/null +++ b/aclocal.m4 @@ -0,0 +1,57 @@ + +dnl PKG_CHECK_MODULES(GSTUFF, gtk+-2.0 >= 1.3 glib = 1.3.4, action-if, action-not) +dnl defines GSTUFF_LIBS, GSTUFF_CFLAGS, see pkg-config man page +dnl also defines GSTUFF_PKG_ERRORS on error +AC_DEFUN(PKG_CHECK_MODULES, [ + succeeded=no + + if test -z "$PKG_CONFIG"; then + AC_PATH_PROG(PKG_CONFIG, pkg-config, no) + fi + + if test "$PKG_CONFIG" = "no" ; then + echo "*** The pkg-config script could not be found. Make sure it is" + echo "*** in your path, or set the PKG_CONFIG environment variable" + echo "*** to the full path to pkg-config." + echo "*** Or see http://www.freedesktop.org/software/pkgconfig to get pkg-config." + else + PKG_CONFIG_MIN_VERSION=0.9.0 + if $PKG_CONFIG --atleast-pkgconfig-version $PKG_CONFIG_MIN_VERSION; then + AC_MSG_CHECKING(for $2) + + if $PKG_CONFIG --exists "$2" ; then + AC_MSG_RESULT(yes) + succeeded=yes + + AC_MSG_CHECKING($1_CFLAGS) + $1_CFLAGS=`$PKG_CONFIG --cflags "$2"` + AC_MSG_RESULT($$1_CFLAGS) + + AC_MSG_CHECKING($1_LIBS) + $1_LIBS=`$PKG_CONFIG --libs "$2"` + AC_MSG_RESULT($$1_LIBS) + else + $1_CFLAGS="" + $1_LIBS="" + ## If we have a custom action on failure, don't print errors, but + ## do set a variable so people can do so. + $1_PKG_ERRORS=`$PKG_CONFIG --errors-to-stdout --print-errors "$2"` + ifelse([$4], ,echo $$1_PKG_ERRORS,) + fi + + AC_SUBST($1_CFLAGS) + AC_SUBST($1_LIBS) + else + echo "*** Your version of pkg-config is too old. You need version $PKG_CONFIG_MIN_VERSION or newer." + echo "*** See http://www.freedesktop.org/software/pkgconfig" + fi + fi + + if test $succeeded = yes; then + ifelse([$3], , :, [$3]) + else + ifelse([$4], , AC_MSG_ERROR([Library requirements ($2) not met; consider adjusting the PKG_CONFIG_PATH environment variable if your libraries are in a nonstandard prefix so pkg-config can find them.]), [$4]) + fi +]) + + diff --git a/config.doxy b/config.doxy new file mode 100644 index 0000000..f6509a3 --- /dev/null +++ b/config.doxy @@ -0,0 +1,185 @@ +# Doxyfile 1.2.13-20020210 + +#--------------------------------------------------------------------------- +# General configuration options +#--------------------------------------------------------------------------- +PROJECT_NAME = PortAudio +PROJECT_NUMBER = 2.0 +OUTPUT_DIRECTORY = "./docs/" +OUTPUT_LANGUAGE = English +EXTRACT_ALL = YES +EXTRACT_PRIVATE = NO +EXTRACT_STATIC = NO +EXTRACT_LOCAL_CLASSES = YES +HIDE_UNDOC_MEMBERS = NO +HIDE_UNDOC_CLASSES = NO +BRIEF_MEMBER_DESC = YES +REPEAT_BRIEF = YES +ALWAYS_DETAILED_SEC = NO +INLINE_INHERITED_MEMB = NO +FULL_PATH_NAMES = NO +STRIP_FROM_PATH = +INTERNAL_DOCS = NO +STRIP_CODE_COMMENTS = YES +CASE_SENSE_NAMES = YES +SHORT_NAMES = NO +HIDE_SCOPE_NAMES = NO +VERBATIM_HEADERS = YES +SHOW_INCLUDE_FILES = YES +JAVADOC_AUTOBRIEF = NO +DETAILS_AT_TOP = NO +INHERIT_DOCS = YES +INLINE_INFO = YES +SORT_MEMBER_DOCS = YES +DISTRIBUTE_GROUP_DOC = NO +TAB_SIZE = 8 +GENERATE_TODOLIST = YES +GENERATE_TESTLIST = YES +GENERATE_BUGLIST = YES +ALIASES = +ENABLED_SECTIONS = +MAX_INITIALIZER_LINES = 30 +OPTIMIZE_OUTPUT_FOR_C = YES +OPTIMIZE_OUTPUT_JAVA = NO +SHOW_USED_FILES = YES +#--------------------------------------------------------------------------- +# configuration options related to warning and progress messages +#--------------------------------------------------------------------------- +QUIET = NO +WARNINGS = YES +WARN_IF_UNDOCUMENTED = YES +WARN_FORMAT = "$file:$line: $text" +WARN_LOGFILE = +#--------------------------------------------------------------------------- +# configuration options related to the input files +#--------------------------------------------------------------------------- +INPUT = ./pa_common ./pa_win_wmme ./pa_asio ./pa_win_ds ./pa_linux_alsa ./pa_unix_oss ./pa_jack ./pa_tests +FILE_PATTERNS = *.h *.c *.cpp +RECURSIVE = YES +EXCLUDE = +EXCLUDE_SYMLINKS = NO +EXCLUDE_PATTERNS = +EXAMPLE_PATH = +EXAMPLE_PATTERNS = +EXAMPLE_RECURSIVE = NO +IMAGE_PATH = +INPUT_FILTER = +FILTER_SOURCE_FILES = NO +#--------------------------------------------------------------------------- +# configuration options related to source browsing +#--------------------------------------------------------------------------- +SOURCE_BROWSER = NO +INLINE_SOURCES = NO +REFERENCED_BY_RELATION = YES +REFERENCES_RELATION = YES +#--------------------------------------------------------------------------- +# configuration options related to the alphabetical class index +#--------------------------------------------------------------------------- +ALPHABETICAL_INDEX = NO +COLS_IN_ALPHA_INDEX = 5 +IGNORE_PREFIX = +#--------------------------------------------------------------------------- +# configuration options related to the HTML output +#--------------------------------------------------------------------------- +GENERATE_HTML = YES +HTML_OUTPUT = doxygen_html +HTML_FILE_EXTENSION = .html +HTML_HEADER = +HTML_FOOTER = +HTML_STYLESHEET = +HTML_ALIGN_MEMBERS = YES +GENERATE_HTMLHELP = NO +GENERATE_CHI = NO +BINARY_TOC = NO +TOC_EXPAND = NO +DISABLE_INDEX = NO +ENUM_VALUES_PER_LINE = 4 +GENERATE_TREEVIEW = NO +TREEVIEW_WIDTH = 250 +#--------------------------------------------------------------------------- +# configuration options related to the LaTeX output +#--------------------------------------------------------------------------- +GENERATE_LATEX = NO +LATEX_OUTPUT = latex +LATEX_CMD_NAME = latex +MAKEINDEX_CMD_NAME = makeindex +COMPACT_LATEX = NO +PAPER_TYPE = a4wide +EXTRA_PACKAGES = +LATEX_HEADER = +PDF_HYPERLINKS = NO +USE_PDFLATEX = NO +LATEX_BATCHMODE = NO +#--------------------------------------------------------------------------- +# configuration options related to the RTF output +#--------------------------------------------------------------------------- +GENERATE_RTF = NO +RTF_OUTPUT = rtf +COMPACT_RTF = NO +RTF_HYPERLINKS = NO +RTF_STYLESHEET_FILE = +RTF_EXTENSIONS_FILE = +#--------------------------------------------------------------------------- +# configuration options related to the man page output +#--------------------------------------------------------------------------- +GENERATE_MAN = NO +MAN_OUTPUT = man +MAN_EXTENSION = .3 +MAN_LINKS = NO +#--------------------------------------------------------------------------- +# configuration options related to the XML output +#--------------------------------------------------------------------------- +GENERATE_XML = NO +#--------------------------------------------------------------------------- +# configuration options for the AutoGen Definitions output +#--------------------------------------------------------------------------- +GENERATE_AUTOGEN_DEF = NO +#--------------------------------------------------------------------------- +# Configuration options related to the preprocessor +#--------------------------------------------------------------------------- +ENABLE_PREPROCESSING = YES +MACRO_EXPANSION = NO +EXPAND_ONLY_PREDEF = NO +SEARCH_INCLUDES = YES +INCLUDE_PATH = +INCLUDE_FILE_PATTERNS = +PREDEFINED = +EXPAND_AS_DEFINED = +SKIP_FUNCTION_MACROS = YES +#--------------------------------------------------------------------------- +# Configuration::addtions related to external references +#--------------------------------------------------------------------------- +TAGFILES = +GENERATE_TAGFILE = +ALLEXTERNALS = NO +EXTERNAL_GROUPS = YES +PERL_PATH = /usr/bin/perl +#--------------------------------------------------------------------------- +# Configuration options related to the dot tool +#--------------------------------------------------------------------------- +CLASS_DIAGRAMS = NO +HIDE_UNDOC_RELATIONS = NO +HAVE_DOT = NO +CLASS_GRAPH = YES +COLLABORATION_GRAPH = YES +TEMPLATE_RELATIONS = YES +INCLUDE_GRAPH = YES +INCLUDED_BY_GRAPH = YES +GRAPHICAL_HIERARCHY = YES +DOT_IMAGE_FORMAT = png +DOT_PATH = +DOTFILE_DIRS = +MAX_DOT_GRAPH_WIDTH = 1024 +MAX_DOT_GRAPH_HEIGHT = 1024 +GENERATE_LEGEND = YES +DOT_CLEANUP = YES +#--------------------------------------------------------------------------- +# Configuration::addtions related to the search engine +#--------------------------------------------------------------------------- +SEARCHENGINE = NO +CGI_NAME = search.cgi +CGI_URL = +DOC_URL = +DOC_ABSPATH = +BIN_ABSPATH = /usr/local/bin/ +EXT_DOC_PATHS = diff --git a/config.sub b/config.sub index 791bcded7c3bf807b4ecb7521fcd2ef9ad175b2c..1c366dfde9ab35fe6474af49933455433951457f 100755 GIT binary patch delta 4625 zcmZ`-Yit}>71r!-oUD_$ao3I?Sv%u6PGZNK?(Ac{ZkoiKw6SWEfSXWg9M_qho%K$3 z9-Eoj^|-jQklG)lLTxyTP!WO#gn+0Z%19s)iAwyUJpO=qNGK8o3H~90K=3DmbMDNn zckL1>JLi4Rz4v_Q-s^WCasT}{_tq;Xy2p8*&!p4oY5En|Z-)J5*>8^h=6U$)UjFWb zp56IWdM1@Fy!ZZ<=$yb`v?QaZsRn=5u@uGOQ~X7>;#B#InrT|o{CU%MOk@c)hLePwTzgFX92nA<<&t?xg;d3Sog&TZnD z4L4O*6-QG`GQYw5f`&}&6!Juo$xg|t(IA5x-8^5bVAdtOJe3NBHA8XQ`E4xD#?n)A zRRZxqZ`^Y9TFNk+lDBx^akLj>rfNn5XODzzN$cK~zNfoh)aq49%%M#3DW$oTOBI&e z1$nWZ6PIS%)pc3QFNrhDm~b3}=-KQ_=2RL!JA5Tps;CBhFnl7Zxfq~q*9FmaeY=X4 zO{1)0HGw;%FRJxS4O#Uz?X+*9XEPRx=%Xn_hy~Iyf^79dfqf+RHgU3PDS@L}w|SUN z9xbwrbYul_OU33&LNTXk?cydIjwza!uY&I%DjsV^5pzu|m-TZ9%!mz44<;u!$s#}7 zVL@#BII1mWGn6n!VDt{9)uFaB+YDOyqj%>N)G|rh-HF@bZkL3u@x>gnJ58(^fi13| zBpQ*xH-qKm=utyR<4#c+q-aU}MY4sEsOPfqcJffv%4XnUQol(>XIGbmOg2ZQg=8kT zECp0{nKl?@s8mXfEcp_)^PykBWECXXcy^U727O>@^if0*b14FJC%!sGd9j^`U-L)0d^Eye`9ee~!NAyP7orKR zAT#!qm~)xEoNp2NKqAtY<%|ucURNyN5aDh#;nlGtyAX()3tt|~MG$*G8@qdqu*Zyi z^o8yOJSO%L2rEZMI1x6EoE<{M`3k~Z%N$DumdA(Swej9ftwSu(~tiscA7EtwkN?b+p-A| zyu-lCYd_w!?(u&xLIW(LQIAXp}9pPoF4NF8#;Nh;T%=Y`o)7(086Aogc2EG6iJ5C4IZfi`CtHebz(3^y$9Z$ z5T3y!E2u=j)v#pRx=uJ~tM&K>e)IYL1Rq1t%HH25G%k+UCq6EfBpHPHz8)ePcB*02 z40FwZYsddEDdr}-n}b_Wn89&qZ$evRh0x62ZRn_kqL&>p<+@fiX?{4CbK9rmfe5 zA!JJsWwJa-M3`Yh*S)n+c_U@cL z&2e$~<+-=JF_h#~HPcw3Re*Qr`r-3)`v*{rV>xO=S5Tvf0OBVFFMeg6gMWQ|B1Y#1Tb@U= z`*zc!TDAydXZj)Yi9hE)`r5a3+4J?`T`z;jho->vqQDj4+M?JMm)FadL`a4Qi;uh? zzOd5uMEDTGq*A(SLC;IcOV~xJ+3_S(YBiG{N<_C_QN)BVDxwKLs>^J&b;C7n)`?jN z@7hZjxqa0@Q0-* z8WXnOYK&V`jk0QQi%~b%6ib)Lah^|=jUaQwrF&<}aA)X)^~fUNf~}fHMO)vR5>waK zgOsb1T5G_)rH8$#+lD(urAynEG8_}my*S!~-wpgv%8lbU;pUCk_F#D5>rXe{INW;M zk|)(m=ZhC^E`OM0D~UfT)@s-oWXU)<{qomDY&Qz#6Nd2FFcW)S)1;E7wA7&he)IB$ z34GSJ6s^SzT@5?KQ&2dz^6kM^7Fhc&7s9~@D-kXdPr+Q_Ak685*Mh2d!YGo}o*Ocu zq9(N|hzS+1G<8!6XTun;SJI-_DTTH>0o@KJ@pRn_M8hVAgO zsVjU*sn81-7mS~xqlw3sY^|Syjq(U~$ou8XTrX?=tr=oS_>1zzkFhNab7D-8?G&|z zP$8+VFQ%O0Q~nW$+o5XUe~r~PJq8xT5sesd*Dvkc92UB0u=`&2JFC@NW5M9;|y zK}0kf$w{V&c%JDb@NJr5YHBCiJBS#LWl15=ba$fBk-<$qESA+$c(!~;1-`vJO;HSN zsqQ9ky}E~D@P+DH62jMN-lyQEf3xx}p{xcKHcIHY@7HokN12$a7HFx*qylS(s^k zt;`k;+S`J#y=?$qZ)+}RV+095v^BLBWYBa;QwwaaWKKwwZDe2jFf6pKYA&iIi_WKP zpo_S=aUDF~`0ZA*Whdk8y})Or-I%lgf0<%($w|6&MjD2~t&k7bz?PRhrT7WG#A1%@Mz^&sSw@|3poB2m8erZRPT85S$xH9w>ytjKLEbJ-=ZD$b9>}n*dAAa5W2tFUO z<1skDJ5wsC9{!-@;Ni0+XZs#pbnv4+V-#H4$HC10IR0b*b+4Dq4jzmghOZ7Dh4|>^ zirl2c^=9DyXydt<4;Dukdkal1txpKrpW+#oPUWU0)5!V$gT!~AZ=x!fZWfs6Uf*20 zWfWsZ(9IGy06CI5P=ocgl94rz$gD%>gwe2 zP5wgG=29fp#IGu{7Y-Z?6k%9BwwHoi`h1O)R0^L>NEZIs@OX+SxSVS)Ip5@B?FHsA mZA?jpI!Tu-cUpxsUOhA7h5394Zsu3w2l+|LgBTb+@!>y$lO!Mj diff --git a/configure b/configure index 105c7ede3273821ca43cf317c0a2430a87aa420e..1c278a92fba96cc9dd3da6f0f47f818bb2f127f0 100755 GIT binary patch literal 176975 zcmeFadqZ2t@jv{x^(rPS5keB6Shwn8piX|T{rP-m zcK7T#IznJ@f)mlk+OwD0`|RxOT<(8iibu^(ad4WsZ=R1DgMoQpZQ<7(cl%~=F&H-5 z`Ff+*=+qmXA=3KI>QM{H)lS{i`i<(aVP00>HIAEzED%Pc)953%ZjLU@^X*q=bu{eO zx}9V5pz!s#$bmd--QGpNd2%{5^J@#{!SeD~=2^edF#Fx(;aRocFweT9PQ5y8b~{UE zvr{A7gVW}~5Ki-CgdBrfzu6la#2vHbz?OVshNmb#0T{rXG~c7~qfV>YZnBZRM!(%0 z3{aC9b^*V4v1IDa!LZ*v8lh|KWxHE%9$%Q|5Y4!6@@aqOKDu?^ynHw~MSGjWX0_G) zpR~VVY+72eJk!vqrw#M8JL-2DXh6G%av0%E^VkdyP0paM=j34;B>)!U#vIY7dxX?%RKo0?<+DAos2P29(-)S+S*!sxn6pV z@O|?iH215*x%BcOelZxB_4dG=b^CQQ=(U=|VY72$FgSA`R=&*6{a^OCC3AM#ter}E zosnU`+P~oFp$ld-sGc;?>GkG->jcxmDZ(|DwZ# z2FJw39#=IW%KH%&295;a9YUBxx!{+`$uVp z{Ik1y@FKIjzf#K0nH&NSO1bYP@UWEo5&^*9-r6^v5vHkA02VelD=MQ|TdUj8 z<)2rp&o|80T4i;8eQ#rbUxHg({8`)C+FCu3#I=Ke?@C~EePjDz^V#Ow>H!w3LRzc5 z+*sXzwYTvSX)O2>Z~#?cz1-Q}I9T2LH{-WgUkZ@zS1&jAHrE)nySlrv=fE6nY;Ekm zKmn#4Y`)yc)VpXZ=Y-Sn?BRR^sLXJL(5up#pLZJr%!7S$m|gH&1)Js4 z5~#^enGvu$_ZA!yF?029r@_(PYy5ZA>;u7IUyKF~b5tEPI@PwWAFMwNws~xF<@suP zAvbaFqUp?A;y=M^k+^8Fu=ftWDUPi^VhS0Q?CZlQo9(S}xO6ZvB0$&05HqINh(U5z;kO8oEqjbmtas`3Qmb2I>vT$V_P&=bA7=^`RdH&7M z#kc%#vAj@RoXeT=ubBIL=C#Z8x;$SjmKP?ZgbBbx_>(~{aF8Da7!nO=)K0s`R{kp{ z&zJ$GD_8uvuvm__ql|_WKbQgPT`4{>|9xV9L;icl6n}ortoV;Dnv!J!-Ae;9C?cUi zxVb~w_}sgu(`eKOW^Hdtkn`5&_Qv*(kCZrODOWwJ)f>krr_Ep9wc4F-@4x-QaPs-S#>E}>;Ma#gNgvj^rV2z|AQp5)jNJtD?Zd4L1m7}IZ? z{Bcx)o*r_hw3?kpr(0Pm&FS(%X3UR`eUKXaRS8Iw$cY2*%9}6E3UQ^UFAf1o$ND_X zmo*sUY#8-`R7z^*uP~qvYSrez;8Rp;&G#DrcoJQU5JDyC$F(8pniSv<& zksVeM-2p+s*y<4Lq9ri;4bVm)_Y6+9P8ZahF*RUeGq(&l_%LSiO}PwAV-`3t?TbO9 zbzDN~lP8)g(Sz#yMrHHaerXQ>JTVfA&y+hl>rFX2=a{O;l4J&G2LoXJ>BNyk38CXO zSYit`y$>|0kwxN0AaH!S2KofXAAtmaXHOk=34hZ3#-LgQIFJzy(6e<80M-iz6+{~P z2_kq2ge}O+UcY+;Y<#1>+n9uUMN2uM4cA_ixcjs z0SbzQN-#m}4dy6VDB6K6CZ5MMs4C=;HR*b`j0joOuG|+~+cFfkY*6llZcsA=x@6_5iO0Gd}!FHO>= zv$nJSZ1Z_#|HTFfAX!DZ+=AQSE;LLJt7AIWlg>YLNdfDpAn|X#SofZRqSg>*vb8a zWHr!|F5|fmE-rSe2;MR-spJVw7sF+g1fGD4&lHe|jiBKp0u(MpIW&Pwio_Y58(SGL zIj=ckR-e+SVPAzQS*6VUtxR$rH-Sv<8H-G0c!a=}e=JG?xL9#RMu*dV+@+ele*zix8@*Pw26_xk1Y&%G!)>K~)ac_ZAQf=j z1jS-U-Wd$?hx(h}()p=xW;9kxwLx@wO+6;#@|l}lA(E@&j^3z&*`S*j8DyLQm&o_Nncu7aQZ;+# z1-LdHo{odj35Y@RJ%rXR<+Lrk)ltiAAPKAGtltG{M5DD8;UMV%U{Id6Nbqlg@3K)a zFKaKWr)VRQ499W+t`W}UbL4xRCvLP=neU?cHvz$o9Q@n1zk{W@rTmipcx+nTZqKLu zjO#&;P(WlVO_<|7p*#x> z!P3tu)pTq+Zfo&1E+mep2;*tEXRvdZpH-HP7AqM)w9M|#{^n~S>qe_J{lr3*_sx2@ zlN(}n31^0vGVVp3Z?#jo5SY0)%Ws#kZbkzxKF~~9WSD+zQ&I%2MtdM&=DB=kM49^tAN^aOijBSrQvT#|r zx5znK;5sgtf?zg}Rit4XJgf&pFqY6Q?p>^Ydj)M(ff>L_YlC}706fk!zu|5rXZWF# z{zT~LdASDiTw+$19xQ!zxTMKoy4eh|R6X(+Yl}yBD=^UH{nblRxB6U?#x&*!_lPvlq- zmZ6-t)dg}Q-wn*s0_V6*EPg`%a#Lwr;Xxx$6RWr1X!9Nb{tc+zE_hl-Kmz3nFOOKM z4eSVD^P2FWu>4Tgmm@Z#YZN-}n;h*WvT@K`y({ql3}v1gsf_YAXcHtIQ}DQu`e*F8Lnz zS#Zbm{pWGc9F-oJ#`ZQUlasGwU!oW;A^kQ%@C)4u3PemIL`IAufXXU}<18=r`#6ud zobmWz`S9&(kB1w$@WOotHmKT}UEAF?%0~mpVZT!A0hn;@pFkym=Yta+ zbkC9j2Tc%Wr*US91}tt2QLTyF8)+hW`11$Xx$-ATO32?C7 znG_!{0S*xTNZ_0_K$!9RHSBiL)>_5Y09Jzwl780Q`A&>5H@^z?u<~DU#^elp1dc71 z3`Z^Y%)+N90tZhEw9K%AkveXkm*h6p>efKhA(6YQc>=!1QTONUpz0YFmnrClX0A zoKGMYLGoe}v95WH8#yxT-P))PE)j=bUby_K8Z>YOn=bFFjUgEzn>g-H1$Fu>JFeY8 zd)@bqy3lce(d}SypsVfbc?BCncsM|PS`OKP!*C=%#&eF%#8zmo(pUeG9&GZVuQ?Qo zT~IL=B;WUe$Jp(%vqy+GRons7O73*IgDutCnoI*}# ztR(Y|px(<$NtcGD7%TY21)eh@uw?ZKM4=r-- zJXqh_d@41@vU?b|jmf6U1ZYE#%@<)~h`wbAUT(bH+52|_bQ`Oyf1%B@FvEH|9f^+W za7um2!4zzsI+UB+2Pvc9>a{c1F5e{+X_7IUqd>U|Tqs`zy>|XHSb}RUA-3k8FZv$lHn)) zY8!`KwKL$gxFYxzEF&Ja1N)1aXIVz!!MrL-7XxBC3E~+5?+93r4SotHjJ}%0b8bEv z?6xp~vU4=y7%$&_LoymaN26w|UeWhkB5oTTR{KEl_5<$(`fu?HOCK%-D#OOFAe|MK}V4!RcsyD5MEN;!X+}r%9V#+e^OFR0w=mV zVsI|t$rKEhZjVd`hdGtH$}Rd1mBG771Zz8sJ^iNT(+r+|NHkVD@c=G%Do&EP>pugfI{K@WkQ z&BkTyi7%Pl)=7&SjE+ee#PY?rSZT0yj{ju_7{ku6gx_HU|Mt1bN*RpCQFnldbAQSx zuyYa?5QS)B-~~E*yxGBSYw;NZ3=$M?@C*wETm}=@3d+2+8plIWK_G;&-$)3`!!gb` zaI{Uf4H+A3RRI@bi&F8p+vWMlyAW^j9QbHbWGJAv( z2t7s5I3kKQ`wR0uH3)yLSXAIGo+xidL4F+;@uc$6BsWe@)vPS<%Ll)qw3P3 zFg5su=*#o{{`}3)rMHVEW%KcooOkk7zno07Ewm!U)7CCdI_Q=X`V7j|x? zdb4`c!45VcF1kQ^fTnLdzEUh~#^&u2`zvI=l0jTdG|~m^uYC)${k5fpQEow$7F`Lh zm*67^M?oJd;VFiLrx3yLcVkALkhGPjvx1I=T$KGyv@bZ)Z6g`uYE6WrXdm*;iU6gw zO)z_2m>L|mNuSb0mnZ^1LGB*kApL_cc0Rl;IXM!*<72jcbU`i;qZri5>V@P>hvSU) z`})8d$+|_Qsdg6J$2BIw7U4?`Fgt{^wCdS3MAMLRCUJHkw1Qm{J2N?}a`@t~!zl{s zI+@n&pqMM>%JwgpE1qNzW!nmn5X1#&Ih*2Ndi6+8Sp|4mb7xO3S`WB_=9SbEv=I<> z{yUkj-+uSAh(yH-gdagT3dYL2X#49Iq)rzQPZL%K@Y)$%hl_Z8AeqvDr5~Cy^8taFv z!1u*QM9rQMk;oAL#8=s_F>Oki9E5`ran+=ZN_e%`o?IG}%n~)l7mH_!eT5&1l2MWm zxq$sm46m<`GipaTjB_I~C2l+$V#;oOec@!b#CQA?U*#BtFgXZEK_Bvy=4<9%d3@e1 zW12`H8I<8-qzl+z{fUpFEvv()AGRsuA3;JC^dT2;9kAucTi!X=LpA!}N=ld;$XTe z`v|_j^#t(wG@{f`ED~`kjX56AIu?_Rh(<1KT?%q{_3L|0tfP~n#xjjH8YL5%;-Bdw zXzO$9M@LX26WyB}iHzmMbTadJ`LUQ}L~;aeos-v~f8EN<12RtuH@JzUWD8@-v5^W> z#yS=xPAD|FNNRye*;6v7XC2EJ&z47v6ItS)>FdJxQ(xxe>%%9?s3#_IEb-Ejzoamd zE-5;(;AO=o6q;NlwZNq8DVdX5IU8fyk`c*W;73&EA_brPmoo~TTs(Pm2gE}z%Kqw) z8(Dn^mbhflN4kJ66#H@gtZ+rnd2)g3zmmQ(BuP`YHBUrXL z38j338(Ifx9J9oqO0|ix*VFN+sHPxeGF#$1{y7FAOb)_P(1*gJHZn1wL8JUlD&9*s zJh7Zh)?j795gZYl11qU9kU>i7(J%g zwMbbBB_Kp>!UuhQ%#gC8M7l!jNd$eQ3)tU88?=;dh01E!%Evxj1CbB~eaN>|%cZo{ z%MfTwCVa*c!;fe_q-2!jLoQ%{6FrUUv%U2Zt`8F<5*gy3_$s@VA`rslARGmK$d6f6 z^Z2-_q?q(68T64ZV1M-|-v5}unT~))+18AI1PM{lhg`t*A%vf@Qs1*pRtQL%Hy)0n zeMr0DWQT%-0Z}6K&Vyk*?8*y`Y(C4?ZyqCO>N`X)G zFlTGO)%Q^gGk72MwOsLiG#V54K5Ao9pGWV+yPUk#aEH0Jr@qQD7kNj~N|3K>E(VtQ z6p!V8nr`v2+`{}6ivjy?;$!*PbOcZ3`Ewobbk<(}JYegcha9YPJZz{CyKMbQpRvU7 z!{c%-8729U3q9xni2tjAK&G~X$oXDlWef$y>(FD(|&68j22f^Za! z1~Y2H_!$k+f(g2+qYfCY-IGr9e-s=Q$zByl(QxJfa;@b*@28B z8CyhX$4mLV&b*xd$OB|#&!q~)xKxO1!WI@ohg9~qQofW0PwDSOODGiA6=Q`1iq@jA zYQBc%R3J%0I{;`d7CILNUtQyhEh>vFi&3(*N^?<

P~pp2(ssnl;u#TRn4cNz453 z*xK#+)lkqLF}WNxtOe-;Z9tQH!T>;24?=#xUletA&BoJ%70Va)D4U|{)pEzYc=Jy*3 zYMxeti24r5YVqVj*D7eL=1skN0o4Z)tDXxGN`@7bq#D(u%Gf*XT!=!r_bveo6+zLd zh9qi)k;EidWNazO6I7ox$dpuxZC5XjD6Ma;qCwO!fkvTKK$Lz~?Qm}aFHosD8hi{)IZ{fx2tHij7zOT5tbb>s7K()eJXk+al}Cnafp?ijTsaBQZi}ET6OQrF z#G7srm?uc|2nIu7v^ZLwGy+&CI6MIYVWPD+Z*lR)wQC2jQm5jY`C8pg5OITI8rszu z>sw%`1GW<|Qxn?iMhDwf#zR}A*0;)sQFX99MFUvGC^Wb-y~zs5UqW0@9WDAdUdU)$ z5oVdh#NyoF$}4}v-3$|gi$x_s%`j7dvoEBt#SU6pPS9Z^JRSsvnXC5x8X!|Lr$c2c zBLr_78AZg}7)66-lqN41Jf~=_!*}9N6umHoTSPR1h*Tyg|Xk{3E8CcuW zSa#diFwV{6+L{Hnwias{;%%w5wV)Mg*=>!<5*!QF#dbA_u5`Q>iSjkcS6G`S>q=Bu zzPPJ(0tD7>mDz3e_R9kZbJ(uhEI|t{2VvXbGL1u#F|exiZWQcitQ}6>-j9UM6tu)= zv7?a$L)~`5g4;@1)u~v%ttgp!nAl=IMXXmhm?e^XkoLy7Hmd9V;e*(l}~9xjpwDc z;bL1MX34r;5N)KRMD5z!G{WITFssE^uVI0I1?&)(2XSY<`>wLOwz2ap1NkkE>g+Hu#yz8~~E){9^i={ceY5X#!31`9|TSumlqh_)qo%N-Zo|0#pddHUMNi zRFGQxFc5guXm!to7YK7K;E97hw+RK%+naOYbZsSFW2%vn3 zfq0wA*!>8YvHh89+X2QOWZ5~DvE985+}T~-7#}s@Q0>=FAqWBM3UKIv9qaw8Nb5O_ zS}=3(9#}hXNdH;84E7!>*eVg3#N0hRN0OI>6TwAJW+*9x(Av2Xg=Ye-Imm;;N3 zmsYMPEss2O%Y-p!DGxzL$pKK z3_>*)dBqy)F42A=SdIN)1!6S-I_$<`_S93tz`U`O!Qs-mb<$U{f@+KnD8G#*l3Jd{ z6hOp6EJZM^;AeVSTSALF9qgzq+70Wt^}N~`o3w&i&b-mpq*ga7ENxyb7?+&4WfKL7S>cEve^RTN zH=$V(SGVe`MHQprJVAh0)hL~AJvWz3(vnuKC03Bs$Ap4Nc{_$g%MPpVi;F2?5n9wK z_q)>5SDRbw9LtFI5i&wjW%qTA=6Q2Mw^jD6ktd|mi=F)gDT~r%9pdy6)}oMM!jiNb zK@9WJIw3f~Qs|Aq^z9`F&{2}k`bk7gT2_TW8GNU976?;Zr%>*td)*U!H}-i1tN zpENW!CYTN|s)O~GO1qOHSzEKK4L@txQkK(>0CzJp2vM(@f(*y4>IsQJd-s%d+PTH~ zB}uUGgnNO>Z+!=(M#|}XG939FAdiC)^232e^X%atkQ2xuIC_J#F_g5ga2^mFWp9-% zwN_mF@=F@W!`6lMDOjtHw_x)-xAK#%NL1_WMzTdjkZElQL1{aD!`EVM;Ppx<1^nx; zFGMr2%GvKXf&WQG;2pe4i&<@0tfY~xLr-kxNNFNFuK^icLlG1TH5xcxOgy&Y>W{Tq z46YU3y8!P%7O{qyOW3Uu+TtD9-%7%Z@TQoD!u?9_SZW4!35UMBW@GL8JCELOcxwf5 z+Uxc(=%vHnS)I?fJb6g6%IhQ8?WFyzRaHE2wdiodKUQfzd4qaPt|uulYaYsZLjhOR zLW7;ySURHRJYePMy2I4cU&P7tSHUxs6$n})7T}731cl^v%*&;p%LU| zcPSibye|M!81q{JprQ_@q$j%?mKF)1uxe@GB|VQ9PHl_`uGoQ!XHSe?F{QB|GeCAP za*Q)#ie-3;z9{h71B5NtqhlP+Up9hKIae z@T?=c!#~#YxtBvC+pE|Y}fuuGa{EBoFl`_o@? zukXeAfZTT1Eik}8%7^pKJUCnGSe?S4zZeyf!TDPJnlw)et?mhq$sydreI32UNW;nJ zWa}v!gJ%dlw%CUrJje9A^^tW~d|gjXh? zj5GTkPVOpv>ELGa4tDo5F#S(~A7yllPb^(8))zAqGvXIzvfpj^59qvi(nI#v2i6o= zZ7hs6GRFs^x&QO`hYvCee2v_msnV_mPw*5?lj&$?rPdv(910X6uJ#`d2G62+ItvR_1+J=KYj18M)_!F`Cdd*ePJd&4h)ZPYN8LSZo{ukpXT@BK+(JDkBBRDP?l>=V38v9FEU82GDmyVCLW1 zoC41}Gc4MqG_dLLup8bt&Wm&&asf6hn35jeSW+D77(6n41cL8^1PIS1#UaG=jlq-g zbA0M3uOB~~GzsQ7JU2+)L96k;(Xt?Yf4OdKQX0&0c)HNw_!N#lQ`(2O3rR`?hU{bT zz)-LlfSzWq?c?%ho-0*wpRO0kMNp5a*4ycCMA7u=mB7`Ilf93#*8f@Dv_|JqJpTq` z*eahFeC0UOxJLb}(Vzn&7!|;qk$vU~ktRia_unx~y?^2Yi<$(cs@b^OxZse{UkN9**zdB&~fI&e6>;E0m zb05zo$R*1;>x4Mfcx}5etma{SUmZhBxtFvmKRlx&LvYZA84mu8eXz%&1{?11N!V*O zG0Kg+7k8#HdF!o7+^zVttHPSab3i<5IVEmI;sy=%G|+}Su*y3Odj%Hoht9pY@{!m$ z50nn-^+_| zKfX}@Q2q^eUVkk=DSub~zWhTuTZUsq2M^>N#>C6&>8Im9rCEt}J(o+Cw8)LEoe60u zd_n_Ma-N0qOhg({G(sEHU@RdDpPPX(5G$n=5Gw%)J4%i@MQSy^cyLq<`y=PU?cP|r zE-o;6o~w1|5!`JZ@j(H*tV2z;mR^29Bhu;2y@=VMD+?C_sHVxRX-5N-+>CXvJeno? z5;YB^+b0-J4nMrrR$ZjtMjRCZQ7MWhm!f2hFD!}jO6pNjc{kBIqaZ`n?~UT4FX*lE z>Vs!_Y^;70l7ysu=ja{bg}4MRrQ}B({mLcPudsR?ML&s-0OjcVqaGO#z~Pib%E3oj4P)CG^)LwZ*iePufyj=i z6I$Mz=;{nGbYyrHQ=YXd86q05ZykskxkD0X-I)k+HT3Y4QvzpgpFqyUSDN}G!BHkI zP1zWDeSK#}CoQPrptVjX@hPsOJW(kE4Lm>wtUmuIA=5R63Jc1qIuK`fBT&SU!RrLv27^Tl!U6;U|1~)dP6anTI5I8G{ea~Kx_}-f zA(Z8K02~P?pve1{as(P7p~#Ejdbw zj(DQStQ2y|=LTs=Sloo3^`j1gj=Q8IxQ{qPAfe9sP3(Lsl+X$f;@FdQNjVq znYzhCA4H%O!^-B*V=ItO{W}(~?E@y}aGu){B9M(zE{p#e`S*#a9sO!f@Lt88BN?>t zp(6+uU3{qwJwbt}{)zFn4;;(GkO1{xT27ZwjXM$iG$=x@ef~{c>2#4o=*hTpd7*@? za7_&LmU4MT+gdI^P;k8jCP{D3M^}b=ipeU7te(ITuAeSDq!c;@S7*|)5b78-^^OYI z`B%DV~YX-7RcnGSXLCfF$cvUT~Uu{*|&j1*5D73K>@B-kzfv2<)y1ezTW z49vaD#^j#flXL_o4u>)V!vP5zLiQjB){l&G>L4ZomwlcE$Q+jqi5(Cka4nfK9G49S z6|SCAUfs!6tBcuDu&SS$CeK#~TH@7I2%26mjFR2Hp zbth}n_UFi@)Qga9v|feG%2#IPYrdr;pB^QC2;djWhjULrNu+2y<$})ZmD(36E%PLg zCec*icbgC^-`STln0H)Z9l}4_3FHx4O$g9aFdbKM@c>9k&c=BS?raOnASDEZOeC`zV(`#LKPBy`0UM47ACzUnzc1Ki?4H(8Hq;_@~xo!%pnN z{~_EdcCfBuq9fRDA~Q&d2`=dGh5u`po0q}AuVtO!l6XGF^4JZ0KW3f4#dY8~KamkA z8}m`noR`T6nvMA=Xx2w%1WY473RdLcG6Lu00*Lp`7HD3Q24ZfGbC1)!MHxygh-yo; zGQiwW!ac}TSj1|{uV@a%ojgHc>ZJt8DVnGt^#oULVKR;htOJkv zs6gu+{B9m>Lp6|HPlDtmdDl$=86VpOaXCjYjb;J zd*?AWw!KZEkbCe^+~j}=8_%6zig&M6=+P6UWJE_7WLfc7Q_Lk>D8PA06p|?zW(i>G-JmV)nT()3({c-65E z6{$HR9_a+L0*5PU48Ot1><9dKLUX1Mw{DcMFP98+YGyaQ%KeB2#gWobOAyUYoXvqq zPQe6q+B>p5baM{I{tDD>jX=lm)R-N+4-(3)er?Hn7zZx317GWT;1Bc5b8C0M4_YJA zRqiES&NkvFZ0DM|PV@%|9G}7gH}_6-wGr9Jch=pdct!<&l8cSME#SmGP!YLu5%P0C21q|~$NP^I63)&js${y1cx*>l}&lb47! zY?Is?M0=OqEpE~x0Uv@^JXBo-y@V1AFYr8Wx;ECfKj-EUbFA($!CvR}pz zc`5TMu^hyXBR9(uufLcP{#~zsVjBW|w5#&tdNc*d75lJYx3$0EI`pPK^X%ZuNvbiN zWGn-By4<^Z&rkVC4xYjZ_9M7Ac)PJ%)=%f-tIg*X0dWK-HcxJLZ4e}~q#xsj9Shj^ zc6?P$%Ri+uI6|gP4p*DoEgZ;{C5&6#rTL{Yv{#XHgsCV>&cEZP%&KL7g7)GQO$u&| zSXj#83XeA-ChU%;{4W-JKt=ieZN4Jrwt`g4XeC(@d*yEmg0IDoHTjo8$i^bmm-oBn96Dm z>`V(N31FHevXWsC0-|c#bv*P^PV!d=06p?%{LEZJ!K_ z0;e4Ch%}@qwLNS(2rX|GM5v_xYF6Q-Yh$&whJ_Y@lIL{~gKz_0|A5e8NJ@Day9OaN=iY`&2Qr?-&_S7@Ts>54VeMPAZWo8>CawOQF@8;n|f={#GF zvRKn>+$Am399Lxf2O(hbRQl}<=T z-v#+f?|>$S%~!QU+xT(RmZDm!$is<1gi5Cqu!zC{n+uY$6<~0vyQFqX^C^Z-DZ~D` zYsUGU&&-E`b9&C>y`YoIuyxYS5$CtEvAz0qYooHh0nTM*=heaPs{_yTRg#PU@+4Md z@Mk`c-JrU6v%oZ>yRVViwQ)|-IpydcH~V1I!>pJ{Sg7bjQ0zCTr)Py5M)p1kL)dhz zQlR>zUu}yacR6)Mrmc|Sy}dqaw=ZCL7vr3O^Mr4Ptf@5jAkO`Xct%u=AkT=*Pf{_= z9#C*|8*49iD%&Ot4$XK*8qU!iYb^7~a}KRU$9tIP=$=%pjjQCPMwpzwf_b5<>kDy! z7H7xCd2KBkTeKKdlC1^g3DPj$j(ZNV1(+@YP3kpIh5S+?<@cA~v>s(e zQS7d4W!KyEQ;09iAF-hw(DL<~WMILs&5jt3`m)cs3w#n^#< zOLW2A!6h@YfL0oW&rL$@E|CSl7xr*_&66l`j1lgrDY)V@rV2i8W8a;9?C|=GCQzb0 zOB)p$yaW5&%}y!%du?i8<6n{_NM0L49Cqn}|GA@qyLp@oeJoebeuG8`;phQ|`msBI zXU)w&;O_5e(94+xcxhIq=BRd5#2WPPnY`1JE{PAGddZM93ZHt@RAl(s0wF`@)8ic1 zOCpYhNj)=7iFR#HN=7V4%QC?EGl@uewJXaTE@2ri;n zpfPdUJf@_OZ_0fUx%O3)D}c&zJI3p76$XipA(%;t~>IGzwJF%?G;v3x92VA;EZ z1>A7VE|GWp66p`3-vueSRS|nTa*=Ufk&BH8*mR8L-;sQQ-<7)@A&jVgk2X~OBEf3LOLS z6*fWg`?jl@Cgmr}P2KmjCOohfpS>1%^$21TLe)Cr+A6}yEhu=~%!)f{pz!$9c3|rn zWH;Yo^`VfnWhL=Shoqrjt1zg>JrR9xGxy*yL)ki<37v0&#%<^7pIAz?yIBUALk;@$jZmKZ0aqjf*1XzJRw#;>K7N6MmDlUl z`|EWlnf=c63 zevcwE@jUkNElM}l0=Id!fJYN^#Bdf!K|FUtC>MeVV)-d>>mfojERv@|aY*36|7vs4 zZ=BHBx&Wif{xNZl+#xRwBX_=g|Gtv~Y6NV!gb?9~g z33BOZ8iX+>U>`680(qJM=~#_M!gTI?%tfl*TE=LoY|>ShSL9xcSez* zUd3@+bj$6{&*tr7u?UmYxB_1VGlZ3-qP8%@r`t82Ap_6Bm^wKnbezHdq5QfCLOE7U z8;0_r%l)na($;$yooE`=Sm|Q^yyN};u#j8A@}aKH3GAFfrx6Z+ zYglCPvQRBRPeQ%L(4J)r>e_$f1xC8j>3mQ^MBL`fT2*RXNZb6 z+A6v{Uur3cf-5iv~rQqSl>y3@q z2RH{9iS}0wZJ<#(Q#JG8Oj4F{34mpv(TiJPc(eKKqh-&=g3_?P#;8g%z)@&XHmPn^ zw}NaGH;#+KE>xT)NM})NQ~PF0Gg12!3zndg7L7kCFK&x`K=itu@@dwdL4 zmc_ylbHU%b{M)M^$?y68zh6q=NWYJcPUN$z{~rBfVE@UgZn-A=3Xo)d-C=ZuLl=1} zF8E?^sz+}HZAo^|jbwhe>-h$(K9JNYsU3Vsi2*PdBrB>l`c(Rd#&*96+YP8dE}c%V z48w>Dh(P`19m3PQ)mGNwgUjDHKNp}LIbSZoBFh4{G5}k5+MAF$Y&F4kB)bqLu{=pp zcyJ;sxYax&t6+)cjxdc_jcQ?tYY_=t`{KEQa||>Ai$@q5n61KITBmbW7%MvJ)-PC| zhX#9OEYKf7;Z)x>+vr(J^@;AXvr+#=Wk<+pD>)dWeGGMzvGRHGr8p%7h^+=(Tx)u4 zf=P;j2AZPc6QFTOZW2M*qbQozLFQ(p_H9;?AhW;u29%!Ae&2ipk}sxC!;{S2!E{Yd zkS7gqSGv?vr0k+?Oqo$&mNhZY&5htrSWXd52t%*SZwaVc5YKgJ<`JuC^O!go4p*R? z(&z(9tUUIM9@;@DPd_KRK+`eqfD8@Nj0Epr)N*RhBJz*zf#7krN--VA#JX<M$Y^*JQbLp}!v zCMM87Ic{M1fD6W6x-giOUWWUKBX3ACk#7CRTToDgoq{YZhM-EEUtk_H;UvYB(rr*1 zgtF*nOLcC4s6#$_@1q6|oc7%etNbBtNuZw~?y#2^Wp5VULZ+FA)xNr57E; zU6;?t`0nvFLpQ*QY$vu5XAm=$4moz&QJ+QjmgT%g1`A-kcSM@0rN%lY7;ZWbhgX(V zRK|o)iOVb^6Qq9x-xcaTOQ>d?m8y+<=+-tqu?!BOijLRfVb08-HCk}z31`lY{(Eu- z7qE=M5`e)*Uxvha4hQTr44F9dnO-4{uS#|UTKudhId;{+L}xoHbFqH=M$0qE#^jOxAW=|ggh9+Xmd#$ys&Ld7b( zQg|L*-M4eveA>FFoi606JCk*)l^r_sPUnuQ1BG`tuVOGAv7G@=#}y3gF_6BH7!t_mXN=G?A!gA(I5 zGEv!;z)E+ClbM*%$R0oeLvvN;n7#6(o+UQzcQ{TGDEDwaK=Flm$DWul4Lq#}-}}c4 zXJF|Qab#!)M43Adv+5d5#jId#6vW^x*&C!L@plQ%jFBCmm{SlS);RhNH((O~ek!zk z8+BeE-O5h)NF+MViH3ny_~aRzkuj3r;%i+1m*L7(|>~B>2R&4@UcNdr8!NX zP_xIi2~t_TtdmvneEU^&n+q+Wj3eGF!kCVQfr{;OB29#RiMPq$ZlGy<=dtnq=5Ysy zfvHq5*lU%F+u1m9;Jl*^Q|EY`Y93$m{*=JlTt{{xT#@v@BF6S-TBE;$R-&5lQC947 z=ii&$&t?(gl3`{e##fc1@6&}{qQwf&J>S!qAam4h5mb7%F7&^dfA_J4Ywi85od;~5#7{+rx$~=dR@}aDFIbVVn zs607k{G=J+EFH4x%v(|OQShs(0YSn{6eRH&@m{_LJQcWC(CrM|AyyM6mb^+W&ksK32pY@pV2eQkS zox{mO;NfE$Bt6CMU zP2}L}0c2LU_cslC;`#aGXV8?gS3isf!+Pze=Mg3j)P{%U+DE|fF4Rg*%yUerAtqriI z=NJ360p0;R3-DMJFZ1u0dT1(i{jh~kq>ac(--<|KHzW~Jl#HBzFJHEafC^7w82g?5XXYV%VXc9v ztp3;3Y82`b0cJ{oaaO7=%J}4Eiygs3rg}G^tb-{3p?Y|_?9^mOVnq+TGU39P9}Gvw z$0{^LmVK^#{^CUrl4$4BHy9toGYses^adUx3WRhZG6#^A!Rrfvz325A!WDA6gCk*V z;vu~24k7-=frHcZDkLSjM8H$-(4E9kVbTe}1VfrTpgTBzNCH|bexr>wCA!}E0j@e9oBRq^s$`Yx z#XJi&A%@x=Q8@n`OUCVv74w0K^NYt=ybM(ro?v&mdpbhyg08wVfQ8~`3j``WdRorhUqh9$GSKrL8?-z>is zN4h3VhQCag%z>Fml;4NA7?&uBK?AEsCSQehG#;;*R*DwW`@}INA)&L1mosNPjhh1R ziNf!7yX*psxIN&msMfK{EtpDgy>FFR1EOEG;L`S7b{Dp8apj)O zI1*m$=3l)wE6ark%aRJW-;Msg{3_k-X&S^XQGu21A0Vk}^6QlsyRTkX_IF(2H*cv_YlkHN#%GubR$U51Ub8wfR;>^N+AWlRH_Rbfii z*!9PsC;*@y(ipS*&&WQOrE5W?-wT{=xEW)NZ+>^|D(C6&6f%&MJ63*1aD=n;6=N~o z>=o$BEHQPvld}7O&f@Gc%cr(_^vYdYQ}r-;aZ`^G33^xj(i(IAD{Q?gT@~x(*uzSP zZUQ^-R@MkDfkqdqMEWCrle7LTE(e{sERh-yZW2)y6Y@RcX-orcRJT?At2k*dru#)2 zf(VwnVZBC|l8$s>S~Y85eo2ynrr$*<#fHrqj`4jFs)z6svqDe<0?YJe3iQiTi06oq zJg7HnEz&_S3ju-xD*bc_OnQOChQfi323Hs05TlEdtqz(Wz0ND|P+RSv21SX)si zwA}!PDcS&adMbJ*O&s%1CxBAc$Ro-N^+p>tuqrr}Y4*Dvx{EDLQyq#PSZcl2Xu$t4 z?8)a9tILzJXlHLJ_ML}{bF(8OaCx9BlQYBGd-wtVh7_a2w-Q$e#YzXEg z&J}4jkI3nWUrw}F4_oL7w$rNkK`o6)`$J5NX0pZBBi<4-``f|sPmzphN>#wl4o z{HpKdNZ5fpnN3r}z+P&m?{Yg^Nv|3GY6pboN15G92X$AhaP6&b!zJBKpIl=jt{|gbhqdPTQb_0Fv~p(=qNX3o+Spc63oA=d3o(&7$g2lqlqiZ~Z>yCboO*g#)|9JA$lWHD4sIR5+U_ zm6H)9Z?J;)UutfC%a7zBHynUpk{PKyLe!F%x2gi2 z_6|(FX#uqsS=b?a`_DVs#2L3s50iI!7Du^mr}F5b)^L&m7lU*N0Zpi3L> zW>D)ldyw*hpc8y96BvH0kk5j_8o+r9(@0g}yYtD;+L-Iolnve@DI_**QZ&ekkvvAi z{>9)&Q)~=tZs#o-ai}^tYIa-{vyD1C`?7< zMPnak0_-A$d7W-|c+~3BMhyf+k6Ybd4xq*nkqfe_9Qo zJQeLkK}rUmD4|$H2+wQ>s>g$~LD)P80?yJ;@xBQSXBYzNfXR>Hr?6E2ge{2A2^- zdA_%z1ZR+Pp=n0AbZx>K0^ams$q%xWSQ%z__22~#J{SoUDNCybt?m(!j?=VIgh9DN zk^dHJYsE$U@+DEWG(V!2K^%U2yIG;dbJhh;L3ltB0>uLYddCV{eae{V3rD&;jm{wc684=Vw`dy<74YA z2+iQc_9#tZ6R`VrQBx4s$t$=->@P~N5<&KXSS*Y{2v%b3lPpm&hx^1r2BPgU=zv+W zhqQ|=K`UbNwt!MoeXicaGQQm9DjPrw$$@q2A67ct7GScpv*cQ(PfKW%sD9Q5z4qWl z<)uiFx%@G(Ceo~jmi^yh8VLj6p)n9%M2TeGpgS31Oc&yU{a*vM!c~d`?mbo|g!y4s zkL4fpCnC~Z{g7{Vqbho!$SLjZolz3xM(wpHXnxRxILk3azFkH3oWxpzp|cCfP#Uc* zpI7l@B*Ys%XlNhCkqpVx$Q?;?o`h_Z-V2p#z9JZqZujsX$HYJ!7k2w&0c?rLzKY0N zMU#AWJcs#FROxijL(GT@z1jz+l_v_VgW{cK6}1z`f<8ql9QWJ-+aAc+M~ zQFdqYUPZ@;)m@wwM~gN2X{!_KBT*k8nr6-smRpQ0Ir3hVz%T=9v;XYTizP16AOHj4RjNm1$wC8fY5C7y>)XF4vk$CxM=_irUn0> za8Ou=wa zJ)9BstW#^LkzkadX=F`u_F7?F=V&l&4oAB8T;|rE^SuG;c^WH+ear$4h>*0OgPV0M+~p-K?%ef znUp6ftOd`Qn1boJY|=R88h?B2Dzxv7!6F4MkR==It?@0Sna?SfEz8+8FrliO&CYn z(|;dqRCe~(H}+uX6qXsM3JT-GK&}a3K<5yY$nRj8E6{+PtnO$#_q`}v1v*N2={H{l zy@U<%FP?5buWW3uZ?10Bj>#8Wn+FG58#X3GmwF(1b*^<#z**qu%)E^76Fn>ZI-)V@ z5_aw#VWvfMm$hibMFv@SPrxz5RRkEtp*a|US8O6m62ZR09Rw%ApAwq{$OO8KQJ*vH zF^>t0J7!2DRWs}w4v1z*9iW~JSJ^A?ws4`%uN;e&_YLh1bc;Wv-I=I^78 zhY#iV+ea(<{q`=CA6paj}xtxv#SscrESu_2L&ZbGFURxG4zjU&A2*D67a{_*X)w0+~N4f*}Y z*Wb$Tw_mSGi~jNLnzZ!Wum8cmMt!rOf?-;FuqMN__RT+}C_qTje|#%N&%gb8;{iLr z`VaYyI;Wr}_RiOo=$`Kk`xh6cH-5mLn2HB~i79}%l&=^Nohcj6lnryrQvJMjbZ|G7 zXBH5Vjm|oF3;P%Qa=m8ff~6k52zjPV`Uwl(lY_d|JUD1IHU#jMp`x&itdmO$4hR~u zvS);EgyV7s*%H20papF`=7}aW?3v(b!l8sm1;|s=(Hhx9r_~-z2dOC=zP0is8vGzE zzVUuW2bFy)XyIun!3(_EnGLuJyhCLeGCq!v>t3RcN$B$-UJa z4ndJnS>4}Wet;_oI>mcY?H@G<-Ok_lhYh@OE62xR?&$Imd_kF_Ru|Mpi%8sBRjR$A z5gzEN&ogO3OuhVOM$9oPw6Km=7*rL_Q6Z5Ve8UwS@W=$+P47T5J|FhMlmm_xdle@{ z^kI-{Zk-9A&el5aFlZjuuvpbCh{zMyP}G6XMm2hTBZAaUrI#&HD-(>@U9p@*V_o2@ zvELeuakVY~_eQST=5;|uHNZ>Uc$;C0kBnfqoUj8H3$-qOPTF`Sr$Extk^H!w9nI9$ z5P;$&2j60hE29sTp7I_r)}`1$dN(_%*&e|T1l~f~B|J?8NL!z=Fg6RBz!j`=d7+wF zww536E4Rn|1eWoB1;>_UqpmnNuliu+OpXN4S66sKuxQ<~Pk5Wjhzpycxab^fGR_$@ z51hqDV~OE;oE}_bgAspKxHb4w9vawdc?Zf|&8<pEwQ#Ac`2 zCHVuM8^mfK#4r1FH4cZBG(h%%muT30fQxV7HZ{RVvPA_sakr*SAEi6-95Sw3n87h+ z4MsSoAo>M?Qp#V*rO^pvpcaTDz`rLR9_XHlPc+tU0j>Utxj<GyP4h@I!lSo# zWIGfMRpptn{X6)Ckj}u3?rhPL_{@l)2?+F)@;E2ec`be?Wk31nc1|<{KFWDxQjE0vmlTOiI7_?U%Sn@RlHrCCnp~#zYNgs5RKp31B6S2Q@PH|1VDPxeQ3QSmUK&&7RG&VGG3g*%> zQ>c=uv1BDXmV3_Sl6+> z-NhgnwZkhe=U@!e0a=F3B|W_kh-sa?GJcY-#u}BtMn1!%j0BxrmwaecrPdq485s{? z>4ROLkimBz#>?|>e$K=5`a(Vo(FyxpvAj}*t12L9YmL8gAv^L z(6TC7 zL83j_6P-;+bw~N5y*!1R8x#rUp*;~2Prp5BZ&9-ea8Z2WTM_VJuGJn^c5!jh9Dpem zArYtV43$Y-A4CL>-XOqRECkmn2nsd_YAPUr1m@KR6q7{TK@^7I$5MD+QLn)b_EwA` z(9&`uJ~8y*-LTs$ zbo(d8LHBrg28+){fKgmanDi2nfa`U*Ow{Pg%gyb|j~jcm>|a_gd|Oz?NaGKPKfo_0 zpReNG4LV4Yfdp zooEv~n%*wwvkzDEphc11mW@|~-vqdkJ(C-y38$it)Y#@4SQCB(S%nOr$AVLbUNdUBZ7YK#63>=E0H3+LaPCgRTp)Xk%}0XKz2bq_nd9uuBIde3s1Tdk~!%<~6}?K3viqOq^Hvldsqq=@KF0{x@;0 zLoj%pk1!dmkz=cVH+0^d6%Nnfp5EoHkpwob7SchLxcT^b_Pp*Yu?bM+g$+KzB zN=>>Ynp@l5wN?YFk=Ae|^(snn$Rp&L2q5L_P&;Rg zKVI+wQ%DJ0Zm}HhV&zq-D2Px&mYd!yxT|Q~K)g2nchp4-y&^Hd%XZ-o67wGCJs2oy zh>I*y#%2akI_S-s$#1|>j|NO0#w6-ZVw`F#U+dxNI$H!TEix$kxXyLUKdf3iS(Wa) z(lI#M4QCT7N&&Uf5eLnz4CW4aTnYp@HNrb%HS~al6#(sR7z{u^L^=a+oSZJp>xTC& z2=ttwF*UT{zEesCjRbXRXo(F5Vr)b_YT$zKPJD~qH@j*d=et(3ji*SMWao%{R~-x* zeY&C}`BSOvAFRWHHxZ829I{i3vgmeMUcK;@N_h4p_OZ7we5Hdb{!Z z0Isj#S!si-Tov4Ea43dUSa&(m=Tuh~#$BK@hNdk^%_LlZAy?Mr#Viy|cK@O?tez|8 zhf9?K1`&?~=oaL=^2%-@BO1umrUdcC8%Zo1B}eG^Qy7>hvU%EvQ^L+;A;HAT z6x0}+w8#bfJ5VUQh6#E~2cnlakp2bBO~g~gB!eo9baBrPAg{5FLs6(@uhIsiPcj3KqKz8t(YKnyM6=P)z_buis5Lqag0Mu=*4h=4 z&v>EaBPi|R0Qp2bMawo*A>f2;)Fm zw_njTAtch%pppNy%=@Xbc6_F7P+K^dmhq=NpKFXQ@3>BJ-nc-#DR&&82<%$utwc8>X+|k$%TgIYc~&WTB&+7YnwWkWO4bq#UvM)@ z%Y`?`jpw*FIzcsgOpxlQOGa`YR=4*z@ywz;Br&@YK6|InT}qkhGpRK|t+HOb=~UiD z9=79Tp?`RhAO|b32sf<5^m{Un&lmAHSgNn`4I*hC4l9kC$TQ!t8{0dN&CH^k5T2@^ zOi$i_Qjd;`?EczyEOE+Wmjn{K6WhH-sCZ|o9`R)+2(s)4+5|RPV8^*)JIc&@; zK7bGgIF5YiQ_qkM({8jE@nVQ41)3z~vmWv9UFYb#{s5UptbDyTsnw2@ds9{|92lx5 z&B>`|vgm#7lrR6qdgFbuL)p2&+&pc?2aiMVE5Tq>ju|I!ob$0L>`ZUw_6k$9xxZ!} z6qXAQ=pkKD`}h=5F7I=kB6n2XY>L?XKX8J?0Sg|~AyBZ{Z=UBLVzR!b5TrO?$qTVk z6UAgP9xEnYXoO77#pkP?L6e)w?b_^|$PU0S5TEaHM$@7Uo*O;u+^@L1Oom8@mAZg^ zllh#0Z0Yzn(rqx%@$jd$2m|AZWFl-h>L%8#~ zU(%Y_AImmK%Z6TDr5ncu%|*=0B9M7A+K?I1md^RHrTM&6oU zY^=ga`M&X%W=Mbl%R=@`+?#z}fN?}xIp=Xie`}N&8OjGtoES4zs9Ek+UCi9iei?5ja0tn8v7dw?Tt{<~7suCA4yJoNVjxIjbF@Lf8<3=UIM!^{Y(ayuf2`R44 zuJpJdc8G&+dpsUHUnE!Bc_Dk-KQ8d##gPT0&3`_Qbm~EYV?OXYf*bGryc%|1Trju} zhAd_#I`f#42e*wdea4b*JdUv8%wGW4+h2qw9ifd+%8?GLN#kVR;xWUygV<+OVSr%A zo*(16py?SqWBr!!_?Sq9CIJPB1c1jecP!_0?5)`8cJOz^{2L#NIQNfUxVD%F1XR{v9|+*AvI{jLTB$aNK=7ve)tfgS zb^8X=kRq5<--Flm_U)4#IiA+xxHNOXChqT<&ZvC^UeZ4vEkAnj;H$45J-ilc6xwGE z7zh>hr%?~$+Uz^$iOlgfR3oV61XIrR^Z+rkCM2sdRFG%=OfFjS^ONXKT*YE3KsdZo z?f0t}=FJLNpAXEU`2u`FF)TfHkm@wh;B;7Snf@Y{DUdyT?Dc45_SpNEdF*XRuKxMa^LH+jnD{dR^ct}C_t=N0G$DdfqdPe{1| zB`M{WgXEj7(Bu|!blT-8ILJjguAj@{sJK(Oyab=B1G?lP|p>8!#n4swYph~yk+I% zvUm8JpFS1^9`JbZ3Q7^r zxH-b$5j5#X<+@;|^w+K5&*W@V53TUUO5+OiT$fhmal$(q=;Vxl;FQ86{(Ftmk>DhS zV7qa3OeanIeL{dA#KN=9tqrqyj0d}8@rXE|^=e?K9S#q&XIYWArx?u_P!d2HCwxzb zu`1j@`F-#^6~}R|YmL4yQ&S-7AffP&RWwNkO#}x$0pUo@Yt<}tEM|I9@)&LXTdQ8~ zpwUffnZc-{tG|k(cxb-ARJe72^FJFq&no*bcJ>bB?wFvfoFe5^sVHhe;II$cH!crl^Guh7 z5|J!G`|C=vqVooX?j(oxRt9Y~lH@lB$2r_ZlbZi5>CjB>H?IS zF1u>;TwQWC4s;w(^EylkSLBZ{KrRtJ-n`DYTVmrJZ- zokD|M#D-^b53{$-kGcg;bFdz$q<&6p;+ec^1Bc$c#Sk-T)fhj6I-oQ8sB5Uj{dr{` zqUWTUv}(lg<1K8GUi2puclb=+L4Z;NHQnp0899_ZlU1F`pM50f{!dD?&16-RzWsa*D-&9N9NPyWFYsaz!=Bae!5mx(4tazV^>4O!I9?W80s zYPyyjDi5`wY2yM;6hvjF>C#OigT$;i6>j=0Uuvj{A*w1)u_Ta1lMO`sg6N96NQ?ILU|vS zKorsI(M&8g5_BLBb0(IWNqzhvU#VS%HIw;;%!kbN#Zn#F#s`F%4b_=l#E-EkF_TN3 z_=tHY9!PHsN6Z9MXLQ?4Fjbyg@!}fNZ8O2tnP4hJVZvho9)@QoRLzxzcy8;An(-E9 zXVmPBN;{(>-ol?zGL`q(+YwEb8}X+T!nrp1nQ*ERLzyc=bN%KP?`I;6!s!m|gHAS| zD(m87rBkEAcT7B08+KdrsTSH@5Kz5xQ)UvXe{u;`u7tmkh^j37&*yl&Lqe*uP(DUV zl?5-8SPEo?t|_OwwX^*^VKSAKMUtwS@Nai@eQWE-%FE5|Qg-FrY(~FJ+2z7=VJ=F{ zW-@EfwpO3-m$La2lizt@@;_BuEtBsx>eUXt^X7ZaUc=;%cQ@CN86r4uTqA0gqvi>n z6<0eD#LHeZ23hmgcvg#Xfaf$|^6R^+m8YA}D;wMEo2%PdM;)YR+}b=i*xK-Up>+yH z6d0_A4A^NG&Vsvx-?FsN4~5xk|E$?rGz*!`J)tz>7HG>>(d9lgT$-JRK_g!6Z&cQH z_BK{ut#9s_6+eXcb`D-_>{WK2{uATTt5(|8T2X&0th3r{4hmg^m{F&B&J_MuM#E-H zqmdt$^7;)|h~Yvv`y_L3Yx60G__$wfH|XUWzO4I=)e%glV`zP(L>zRxt)uSwSp2IF zjCco`*Q))aZim2SI!oDB^QZ@Z0#!mS)GzSK#QhhmdmHN&H_1_Dx77lZuU~Yk?Pg6Y zq;Yiq=}I|k4o^9Z7&@+z>YxdaGvOl9%<=rpRd4pw^BJ?czqzx%xmU{033Qtqef6*q z@aET}NMEiv8uW{;ZmrrXvhbk(?m?n7R$EjKz{FvyE&tfe*$@iFvW2V1EqW{x)=_No z-{EObhUoD9 zw7I>yyNS`0S;LOSn#lU`3zmx}ak*d-z*+nG^c7P-zhu3vzYbQ5a>o%8 z%D4nYM~Q}7{L@0db{pPS`JYyRK)2QSD!BtJP6-f7s|A?%*o%V~K%MIqx3==_;VE2o z)CcjtCJ@iywAydf6V1XIRY_^uR-vfFUBsH6*3$bwu6_HDQns8e){49R?g_A|c?Qqd zgW}63v^&PsR$ z*})8>qFrQHs+?WXP6>DB`hFD89fU8OKwVA|j(Q{zKZBF#YEAz09ZA7%N*sA4p0N1u8#%&o$EuE6 z!x+*_A$rc*ZMh_o)M5A&EUr6@Rufxe40VQ>k#}Yg9f|ReqqYEEK#(dmUb{HKAnWD$ zN)rKK?zS3Hi;SFf22G|0lXp)~0^S>=`&fZCxY=)>OLJqkSiG+qIE1Uc!wmy|!}_MD zglDA&@^jdrpSXO>#sxf>arLe#Wv6R=fh?`K%H6Lv;-(5<JJII@FlY`sKnn{%~-&mFQ5KA46nyn!gPPJ1Pm&K+z9GGhVWYlf| zOw`V^?xEhb$?QV<+A! zFoV8-^0(Qp?|9+ByAme-@mk-DjA#o-#s2lhQOcp_&s6*~wCz*M_Mg^%-p~oQ<6J^P z*PbNPr&&16qFLa^uLW-IZazzfgS7hw$}I&{LdQq?5PE+whCe`i_C;w{{GQhMF~Co) zeuGbkmhO|jR@d%58Fu4LwS<(M|^ z=M0B65oPDkV>i6&=kpmKtM{*BFitKWb;eKk_MN>rx#-}TQCODQ{Kc$FpT=Hz0|ybn z{|R^DZT`+){5IH&xb!oai&EC_ti|uF#lP;W!T+yWiz%Y{Z|5wg+xzV^7E?Vg9AGo~ ziW$XcvK3S1el=I|;PD2|i!=2Y-o&rtD^9v+-7y|2c4+?!J;tZh|0F&GspK=9DEA(1 z7N%m3y3^L62M4Pm@nz zt>+9^ZVt)~STJw7S5s=MJ}X z^Q+xWsb2eC`?Jt_&Dl1ag0@UGHXgmj6O-?xf2CWEy}S^M^u^?^r}A2~N?rr*^FEn7 zL;Dkrwei>O`u}!LEjAZ_L$kkqhAnnD{(8r6;@e{B_?y?7$-c#6@z;z0YA){IVU7}C z5$sT(WPiH0{HO70?ge}<50Q2+Z8H@y0*9|l5ToO<5z6_3tp0V*!LnXD17+qn9BA6+ zcRmkim3!$_;$tbl=ucG1U*uxj>-HyatYhNu@;5wUgUM74``-*J;x#clYg>Co*87%B zZ?_5)@%Q%etJxD_Iaekk@{T_A%AeQP|6=Yo*A2d0V%l%Zb3IiM@)^OQI)Bmhs5_b% z{r+=PqCOW`@Zyvh1`N{lDgu18Zx+);HT5q(tB;=}7d+Y9o9fgR!657v;Fi%(Tzt&? ze5M^=V+E=e0(0_-zp@G?k>X})W3H37kF#*O7#>h5Nj%6n5v_~AvMq4uO!w^IRFMhv zWGW?j+juJT7>59k+2E;JZuN?nw3tC`zmvzwIPF@8F)49*?@i zF*b31_D)sO-~yH6nVBZIKY3p!qYf9}h(}42(WIXY`ji7s`ZgVRE|PShYHtD2$F&OB zir?UAeA(&rOCY>KI)D#V23jD~$6Xq#)jY9g9jw!jP0Zq{S?=-S zI-T^?9RjBC6!-q5I9zR>;+`dNV{TET(;Xkt+rcC`8T6}Tz+4iwD5tVloz8GMQO-sC zEhR4ouR94YgDAymXiSR~_CC~|tDwQ&TQ=ug1~MMw{iS{aN$z7l^FGn12K9^}E#PPZ z$*;C$n(|>(%Iv7-w*X>caeFRD*3%Eh6gUniIyqH|d z(Tr)Q+j62iVahMhJAK;g4caGifV8zzmzKjkEm_s2B(!1hBbauYcF+2(AH4;}>7dse z;1_yE2YQoETA#~eAa8?IokD?2rVo_49CdM%Q>$?{F1nyZ|3rQ7cP=6EJm5&@0GDax zXfjSNJISm5;8GC!gG7;!?U5WafCF|4*}4})4Z+Z!iC8u)>YSc-kGrgaFk^49?8}=B zfmm$ImnEA+O{b6McJj10#*q}P1q0~@z1KDv;K6soggUCWK^e_4cx{1ZOpibG-m3pX zXDa*dIme+eITG$@m&7?RjF|M9gH%KHS&m3UznIu};%9A1VPjX4_eLKqlJ#&w9PO}u z+-X*m>OJe|dv~^r8OHmr9MY&&TZ-w;7GFpSl;(DF2>2>fq?N$)<(J6-XINrS6+FjK zw3FK>C!P+XoeU;Sbj^xoFw)5p&W&RfE5iE8i0#$lkCvIVR?C+q6#|94kh541Ae2|@ zC#|_#^J$~nsH%3g+Bk!TCrR3P*=j93Kagqtcm!Y2pIp3H(oUF8Yqb`e6s<4u&}g+* zngF_6Z44vZfRnHY>y^>lXk>p5qh>8w*Iy$-rhQpOKj(_|^TT zyH|RvgX7-Z2U~p2lWgMrLCSia_Q+pWi!Yk5h37AuFP1bN%*OL~A6_sgiZ`g4teW_T0Bwg!uE*c@G^yCD zonc1UeEIO)7@^d}H3p}31w$?ClrS4nLbgfEK#GRcd1knh?2n*#KC<5}Khfamqe zG#B_L!;`jAB5%A{$;KRgO+()b`DAC2o(@a9C4)EVi%N(X2XbGiD(r*V$gxPD9gLNQbaV{uTNK@^ zyz`e2Mgi~p%l+hZG`I-hSy4|F1)s0a0}X0BOu%M4nivpp#-nzZW8n-`;i3X(4?ppqaSzNhZ6AHx?q@58t z1`6tOLQZC1 zaW5psNh&19smhY#CT<$Q)*>0Ll>njAu!onn%e{alv5XRHIEF{5wuD6OA6 z(S5M-a8Cy#(XL}ie9}G>J2VdLpCJ^HkzyFcPzqTf>#Re@V~!@AShFBxB?t!}4IDQG zin6q~$wn4$&>g8U=ve8{02RC`G8SkW&->nB@CyDEuEyZ$ByAhZB*c$S_9^RWu)mu@%+dZ!}f^lKqfr`EwsmKM|j*?AdW&H*r9}|3u(a* z0yRc$R>Jr@-b>LZMa7K!Z0TI6^qk3~}M&LUeL48N&sF3~Pn5 zM&00%Zo^LY&mwP=X4qgiZiMiVWf2;eb6idWZ(W;o!tP4i02%h$W7~Mfq#}-hxR(P9 zGO>X=N*BAj(5au*my-ui_JqtMV0gTUO;UXhDzo+QfbJhWc(UI-)Esj<>QagN;hc7J z6Bf?cr*JiE5lbaOgx!y~;K*GGb8z!XHK|t*3kOr7GIlH4M$?4OK5g3bID6B+B)6+! zb6o*qxGp}q$E;;1va*e0uIfCaC(w~ehr{r8vQkfW{qWEdDLAJuO5u!R<*8=5%|#dO zlefS}!s_)pC*rgO(x<>j0{r)|h{hJBjaKDptKO(L?(tY3h#=a-(cgJwkZSmDJz0aB zrPYf7FOJBh>hNOz23^1vB4~7qYdW$i@CxzOtISua(;HOhkSIHH+PB+aB(Dd^b8}n! zrQ}#&*Y7Zo@7AAeKjfC1z5TWQr+ZERyleL?NSPnB2x9yCt_m=tnz0Cl#HlhtU65Bw zDy25&=iXhTTsOql{++5|dUof5g14*hf!RgBzxTljXczE?oj$>i99 z$HK^rL1iF}KIt4y&dwMJjTTC<%RzHbV0q7kpGb4uR*3oo@z<&~Pf?|IZ1&TGAkml7 zQu@N@OTCzlxY^1VTr*JfiTDr+t54hyS7t8L;oL@fFyk+|&53(EdHgLB>?Sw=blbh| zKYUu)1eQ0WR;{KyM*d?b`Eh`xCOPn8NIiJKj2S{qLxA|(-cJWVZ|rh`#deS+*y0PF z3rIZTV|tD;CgZ;gj6HiOFT>0B)2*%b#}AsTwmJVscfYB>G0yQ@e!00sloaWBFoItg z_PS$ZMc_^JIx#t?7M6Zhy z>vW;!^_@bXHkeKOH#)Ossg9{)DCxw1>*A@Pe_@l@j(~BleN(@aJmqqP8_CxC!P)E<%&KPG<*UWP@C{(Qv z7&Z$!DNdGaYEUGTN%M&h#mQvl>>OftccV6geW5VdBW^?E-Yv%;@Q=fsW4zj0Xtx#- z->=!bbVOyF`lo;`mX;%nMjzoPjVstEX29j%XNP$)BNB&V7v`Te=CdiF#aN~p9||qU zq(D>ys%|qdDGi;skN~5-4=0r#Ty&a;nxI$_T6PB>;=LiR%>%6~iOHxVaKWE9;H(>B ztQ$*}YSMbo+TTi^#X`?o3ylW4kl8uK45$!)Hpz8O^4-EL(*ZkBL*uUJGp?rb5|NyS!8&#fTRsF;GvRVV41WrO()RrbWYM_ zeb+fO|CSfpR8KU5tztT>*DN6Wq(iuxiSv^opa1*WU;maB4N$evc_ZO1zzI;z^^NxLtla(P+wZ>r!+-oS0x>lsyp@4K;i7(q zH?O3**@yjLJ3*t+Q1sAtqc>FWctLkid8e5<*xT4y+g;m#vKx*|%!wQc8J;^k1uN7z z;xexE91FPEjY_4?5x_PVyPwS4^~fM+5)^DP`}q7~aFTre##oe?sBNgGoAZr6+^BdJ z*pGX4HdhAv%I3^El-RoG-ELOzN%5G`oARLS0B83VL%6*kwk6@5Q`vDl{lNh$Lq{J9 z=c#vRrhe0eXo@&#;$!{f>tsc=GNV!A?4u&BP%fwe3svt*6F9T*H_R!N=S{h=4p3>} zZ*wIW(j)37)6>H_a2iR2z{w;U1B--m1v7^jCNnR|USX-&DG*)^#;5~tB*PD9JGw)0 zAEwE#+yM?R=%t^xT2Pu~Q4@3VHtqCIo8)F%YbD#Q4x0#l75=%G*i(5e;?b$Ay67PH zb#nIFv1Ek{FlaP8oiuW4n6A_xo9dzGo7`ym4besjI7MOyy)+q0H<>k@IvNsx)_t>n zY9`SXoN!@-IXP%jVbU1q>kdlA3obDfkA4KTHgz2VZzvhz{bA7#;SJZHJbt{k{Xlql zTSId_kxe2~kA=~|a>8Mju?XJc0%&5jfJXQ58X2SzP+(5>r^i(dulCby6< zP)EopA4()~+^kmJU_?JY8v#Yp3<+~$VmBjRP5$RlHE@hN*|qNA3y4(K zBW4|9=bNMQE~b^vDx-!;%xY%rYfKRvG7WqRF0V5{lA1%~B?nYQL_3O$YZDsde30-| zESlwXj@hlnoO$Q>GFi_`o^~Now~|1jjAj|zZ2#oc%c#z}s~wC4bn1>0B2R57|IlpR zIdxceBerZO`H^=U39T!s781wJC_N0grtHu;B5=q+GCy#_h_`TUc@<8u3Qogl=zbaN zh|1Qytk*m002N&tJ{y)`%MFjgiG@epjG}HI?ZY@mC2dlzVQZd@q+t;eFWCUhXM_VYOjh*hXe0S| zj!|Lw=B0qm6L3Y+vGDA+|K3h^lb`U0=<6g-QQ;tT(GlaIn^o`24tI+s8)Shkmok3n z?Dk$1C&?#(N%^rSF=7iBl#P1w`1o=A97a||Msq1g7f$*&lv}NdHio8>KjrHm%=MN- z3H@z{-*maMTw4w=t1?FnvmDuds)7RR>YQd((ubL~7oS&NIQJyUB$hH(wR-RZ(?M&c zb(jCXiLjZhBJ5gaIp)Zu5CP=P^g})}U>V1aamx72avsu)2KT8aU{KwaV3dzSH@HK# z@kqM)9Q=HEH=TwI=XUZyPC;PqTkQcEr?k)IL4@N9_?1+i-+8eNPEKSt5SNEl6x2fQ z6c5wuT%-nOL0bd5C23oksuodOSw;e+)M4|&#rWM*n2g-pMjaU-Qh?b#6SLSPX3koh zj0a-l1*#J^2qXom-ts~hH$%Ba;UIt0Fk8nNP?a{)wOd2mIQ*zo_-o_UU5}zhVi(2Cgoec(D z)kt&$xl~zzns*SV_>7_;=ByJs<4K0;Lwofsz4XiHFU!tYUmkpUR{iXrMAy4gchd8z-hBP# zaQLw{89s6?{~}pRAqBSpPlX}1ePjd^m%qS}fZR;cF)jcQN+)+C{P|25)$fV;%t=C? zPi|?%{hkeIojWw8*iw=+%$`C_pN@p@@mbOe=yoRY6CAf^#$It4$ezi>%b7H38QIr% zGXhSiX1mYQ;Hv7($#?(|_(7c@?y&-;l*ghwC5kWyKK9|}7JBN=__!{PaIBlFoN9Mv zIS$3!e4!Gvm$}QP>@PemX$@v&YhdOr%trc5fRM!@rOA`O)O|?bx$_oAN5*0vh@$S` zrQydpHdXKx*E~GJxa*;Tok@099xDy(M~!>KdvEk#)hv8_KR$UTQxq0Fjo0K3jv*PE z4%RI5gP9Y}jsL6fRA+r}#u^(Y~WB|=hO2L24o zO$mx6goc1=5$S8m0UKDUj4 zZ`TbcW|v!vsn<5(DoiNs(iHn}^-v&i~O>2A4S5ZjmpK z@q=|Iar2~_yT-mg_f)o3d=~B`&!6nbxVHBqd9Drf0%D+TRXbmX(7?nGwH^2yavTNr zM5)1b%eYHQ|E$uHEM=u*f=icERen(w{B$wF+Fx+b^>$#xxqKAoYWxA!RdE)z6V)(# zeXJo4BzQ6sxc~*$C4l0?oD-o==ATa$^Z4up8YF7OiDFyBgjz_lodT(tebR{+fW}(G zHGynudY-TDZ#>?Sq4EWBF~Bqz7he;r9RWJQGL}&F_}WrvDbGk(=PF*@x8~g3t{)<1 zqUH4Y6A!g^5EkyA^(Xbg=78@|~Pj(*~OH`T5pitMUTBZrsxvXVpWJG$q5g zW^zdu)**#=?tGIx93ivs@#T(7se~UYV!$SBnPcF%?gvY06fx)p4*67d_04OM8!0IyU!jy}_J%Ito6&jzWF$>@>rOn`4I=8uv z&(GEt?mFS=#wE(UK;&DA!NCwkLpE{nwCigkrbH&HuybI#jY|SG*dMQT!!m|9yLLTr z4^n-Y`aPDj7z}8&?FqQ{>sl~ZHB~wY5K|al4r$y-jajYSmSgrEw?()jb_LwmuBEM&rOk>i zFfKx_+>Hrd+y1pAQw$=)$_NPJ@PBFd(c*je%||-UJsenSS^=|c2yfuK-r&!2j9je- zfs%Q&O5o-%pNP;YrIcsaq=S-zGN`xX9Qy3uMm6RPV3hB}=Bq~{a19NJ2*v^heB;f)T-JO7xIgb@4r?`~oY2v!psd^IYp;l3e)kpvv3$`C+bmbhC#nkbJf1!Yju+Wni8KnPQ8`6ea;CE);k8P zH>{d+&_wKRA0CSP!{vuoV8q;Vl-qIsNvJnyu?#W7h&892xSF2xSu<*k!j<{-V^Vcb zY%xwkRd;vG7S8C7O7UO|aN6~sP+Y5)@0%j84Y4b}a;nBH?GZa4!T7j-zT#TS>?uBc ztogvT=N*Wg{pWPy7q#TvhlXE%vR;rBe*MS%hA8Wm?g%C@asRt9TfZtZ5=@4 zoDeC%!EVDR6&jb^h~AUFxR|qk_aB@Y|4I!1=KM^D{a9AC*Ef_6~4Qb9v%M)miPkJr@xe_4rMW8QPN5sYypcF)$ zat^5DQ0Gl53Y^z9G&$tbp;qWoAf$Phkn!{xo*$2gtZ=`CYts=Lp2qM`>dMKS{nKd@UMqnoCS2w(mIc?2#^I~N7~P<HSvE!Un({uBY6X_Fc->@ljmc;i}7W`wbQqlcG+F&tAv8N~{h_IEZ z4-Q!wFxB|}l30+B6ud*8OIZX$yMHLku2YnLV#0uW0tdT?L}($|V{|5JM@nZHS982E zU14lqpTX71ePPG9+6~+*dRT=$+owE2_=or>5m!h<=K?JvojJm>8uxSb?$Wd3s@s3E zmwa1asefZS6it4KY0I{$vBY>%7x5?<$IUfN=JsMC1I}&SV2bB$4f9WA@BgmBB|fPD22d3Ge;RuD{W@#N@eLIsjocO zS^|kkSd($JFh(n+<#SQzwH{q)uxOmd_+lt8804#q&bX^6J#Q`A%j7<|?gsXmWAaAN zW9*hbwqk-irm+x4ZJdex_fgme?&ZCyFrnqcq$+kXzXk}KBlks&AnocHT6p6oD}_Q; zq!oOitnNG9+r@3J;GgRc_$gGAmE>-+@=dbxo$O|A&3##Kvj8p=- zsEp}x%{@XBSZY=RqUqw(#`68f{rmXprj7f{@oD)UDz;XoabLgW`2z{2MNw#9rbDrC zc5DuJD$Xzy?LEH<|uWNVm_=Vv`G@y9d(nTe(>oSv~yd*rk;7hb%qK zGQv}qLoAv)=C$&dEFX0lq1XZ$p0XTnQxPh9X8w}r+dVI$RJs)d0DkdHOvuXh^!@CZ zO0m*=UaEVP^^u1xJ$(Px^YWK0f6zmHZ6E0MBBl4Nl!WvM!k)4m#fn<*{UJ-Y6O;QV z2pQ6J>-_Y$tb`0SS%Lf|%Xj89D^YyS$|$50@cPNp+~a{%e<-JK$Mo%Tx)9aM?`P?{ zEs0e9WNGW`q^z&!@AjE)rP)K4zV#qxgr_VAlXA?8k6E6W&+&n^5g)U>jb|Gh&#agB zkfjqe>FNHErE^Nrb9&|vS-Jzxa*MB7nV?iX*x7yZXm{-~K&Dczl-yh2-P}>{VnI*1 zQtrXp{#v1wUb8Z5yX36xX77eGB-w8{6+`?a=ID7U7e4M}V7uJV&R?g>405y_q*=!#ar|!5FfL=_!(mI;$xP#y|yQG*H0-8n_WoeDa&EH6|+oE zc*=8P;Ii`Kv*#Kkkg;%zYxt`Ku<1)=>p1_E`@B*5}o>D2u$G z_C=#|Bccgm3;0}GQU7(3gsJFky`qx<_HDawj?T4@xbiI+kdRlU39PQl#MHR|yj}apTJ3KK zFXF?U+8tP WilzR>=KYzLUVrg}G89T5r zO1U2?y;@&VQMXAhSy%q;tuS0ex;Pf$l%AO|?}xiAiyEzSAA@`e;$>0G$^G$Qco1&c za{bu-P4^_Y?}z3@GL-2AyNbKDmPkS4#J}c4W~y+TwUS;*`W|@=*mCY1H@ESy%k zn8(svqVWrnV=%se^Hyp?&xUqew5Vn`R)~4l72u|kQioyU;=q?_Wf?!W7&K4<+!UKq0&8YdKV0MeihU-f&go)`ajeXC zO=B?dLq74Cmmb_Y<_ES%BdODNP6QVZ*UA(FsHaB}9PP^MV;b-{m7%|(VBi77 zi|oeGeFbJ;fjialneD_GEev~lz=dZ0z*h*GIhDy&d3byR!VSc#4=+y+W#NGTH)fy| zHjeNcjChzcBr`9?U0MXTTzqQw8Z$ckYbGe-KH&YaJR@21^h6Zu zea;jVs%6a;$6UxSf+dWx&_CFn&&PrSWKC?=dSUr#BhQ*1aGvw4*8RHXi-Z426E*>P z{*{&1G3eVNNCDn`A!CJ`MM?ydVTM9nCgL(fM)Qh!VLIaZRW9qKN=FQL z!o6SeKO_)mffK(wj#H(vBrT32TFyD#N>>SnbXlAx`WC=agNEXP_QoiS2|z^Tyr~t= zvaI9Cn9y1&+Ol(OIxm9)e6h!-1DGxpoH*nFW)SD|Zknj;yn(PhNQ1iHl0Q3EHE7O5 zL=Tfu2|mcc<4ehbmyD5%U+FmCR*$$2Y+W7^=HC3g`F&4hDp0aGwje zqt?>#Tf5^wwQFxyRn~nRbScZJaj~Duu3CU~J~QY=sGmhlv6R!!pS^hc39x@Ym5MiBnzN_6P>0eSe+IV{(dE z<+wv#JpEAB`X&D5HoU!MF3gxsExCU3NN1N4!MDDinek*`yG*n9#J8z58D~V zMDq#?IRfP*^b;}q;i@l!Qahf+dFB^;MPIBNtbE)n>^tyI^qAv% z((G#6{3?;4koFso%?CTbtJqkq!rjJp`xG9*h1+>$ugShIBcaGR0792t8!E9Bj;Po3 zD;BbFS9yDdvd$HtA<+TJDhw|5l>wKVaCQcc-D0C{Z&FumKp>tf(ql|4?ihDa4pU5y z_=ED;!F;Pp+Mw+cKvZWG>a&aifGojGfZA$a&ebu%h2&rLp=BR{&=ii|(*ag!}$ z&3kQqf|Zl+Cf&dSMyMMl7w~V?5M+3=k2d&3Ict^;DmcqY-(YJoush+8^tH8YI^l$yKbi#hOGa1f?)68o=*a&9x;jw*47raf2}WmvG#>+QTy_5t;he)e7l?75DKUNe|kLs zY0k-hGk0e0%)N8(ojZ5#>0hZo{7iMnhGtJR67q$D9mHa=TMX(#bs?z@_4J1Wn>r)J z>~>r9{MRaeZQ|E1ejVc1C4Sv{VlkOa;@7M$qz%`R{YQ7v=dSpO-Z(=~EAsMGvg9Xp zeO^8toUvG`oSxxE8oC4Z(OdC)x^S#!uH@?s5slWQAp^X7iL5v1*0r`8*X#8q8`bnn zW15G?P5T6~9X)t1ot8ne7q3`R1^<;K8kD67fg&?qjc3weM%iE?Szg~vg3*BN4f-V6 zpw@cjHl<&^XZe+6V1Ps%R1uB|8n+S-uBxphQeRIf91+z@vMm)) zZJVdQJ`IzAa9o2Uk%^X6bOLYz!j`2Cbt5ox&}hr6ZR0KJC^c){+ z1#EP*qA4A(0F78IuxFL$%5=PO*gSb~RCeLNBstWk>@1 zAm6d%kP9YQzN(?FX=&{UPRF66PY`cROrYS8124eeu&S=P8HjBjF+)QfJo*%g*7P|N zP?&@c=JhQ|MOnM3(bKYI6l_XERYg*K6#&Qa-+3P&m{o`f)z11I-9Ecy=xo7988maY zJoJ+yPxerr>)cFLk2lguGn>CPj>P}yi_I@2pv&klTY6}CRV{Ti77o3%>idWuSaWi) zCmh;Tr8TJu@%q}hN%055RU6|<4IthQstpRpb-PGt_PPyRzm;E|wx|g7oW%9APdki8 zL#l{I02Cy}#i?@`V2m85r?37iee0Sox^|sy$k{qmMPnP^89L~_En`yMip6T^oyqIYxTv(L|JFl8=z?uuw9wmD@#Nx zhkdX>5(o;Ip^QCq1Uu%4Sz%pmN^@1BTV*A5qn<6(stSpxT@H0cBNE~Aqb&6z!%|2h z3WiL1rt^Z%zzR-ie69-y5hBT6pPIh1WdjE8>igXMB~&-$fSow2U?5wM1(o+8VW*<_;84`#|->gyjLqUl)>^{Ms--UDN9k*PSC9DP~3c3le zfM(u0eX>T-ISks9lLh=43B7fCRvL(-p^bZ<9=2tZ_7WA>4_dxAI9|~dLNwI0x01fG zch(p&3%zY$-lS?SE?h1QU7=0vnIM`z2!%=#>68@ZNLgoMS$wxr{!$j0(nFX>sY5n& z8p!B9Qc#qq^q3z63TwzId~pu06c^ z;>}L_y~C?9Y~g~tXHwHWHCGd|G(!9#Ne-4oNVhip@xpiW_pS-rle` z5(-z9RFR*uQ8FQS$pz!p0P#n=yZZq-pG}jnV9KE-?6+vI1bKjkE?wNrH;9^# zP0xXm{ODEu2Pjs-Aw~B;l{;HBi1TGjDC`F}Wq_|wIhW}x$BL|q8A`C)X00F{p(scT zrwEL%B z{z6fF_B*+*O+KGSoldqBB<#{;J7a4y+#va9zjqaU-9WaHPJ2R6jVDg4%qElNi@M3g zbpgd@li7JWB*RVvX%;)*YF==q?)4skSe;+ojUI(+yXA7IhK&Z&945ZgykL!Qbqp#_ zM{=9#t4~h*7fZK&q*A8pGuY1f)qjNU(vP2-Nq_QWR(8K6gW*UT05EIR^X;j&G-WWG z+>Xm&($J&dz77@hpn|YT+**%Zn|7;to<>`v*+!>5lTRC-S*kLd;mj4HWVV>ODACMk z{|r#;7gTr7KVLe6IcD4C>y6nS*Bi6lHT3zZi3liln!l*}l2;+_py`$o_Um$lfeMW= zyKRcbnB7jHF-^y((#Q)X^qv@`96Y`2LMhu$bt{mlpAYh1y=~lK)>*6HSD+jNJsrYTtT1w;nA^Xi``T~ z=+|E^X78;<1@x(x^XQqEuZ0Q0TU`F5Yk0wt@H-9<#&0AY0U#P^-Pk1)uR-eLE?V3J z;uTA^(J%EHgVC-oeg#ec6GKALNOH(!bl1f@tH9saQQLdY@gWFT=nSFuYw4$N7i95E zkeJA8;F!w@?R>>;N}acm_@r>e8whsw6A?j8+<}!&idV4co$8e3(obKpXTy!byE)LE z(wkK}&ea&9|U};x*ayk3Zd{GFwd! z>V17Rmog1Iu?(qb^!0^+QcL&#Y&JB5L_PkqX4ZKe7g7BiHvq(97PzV57gx~JZ*+2q zl~%vmtc3z7h_6%fZ4LxCfgFb+t}6MWie$^tj*dW|kd3Shz;ypFa_HE%ayc>=+kYck z1|@6KO&w1kd+Qt>_uk}87+FbR;}cRsweMY-zJ+w*J2lA*AGv_X)qvRMWTu~^8Ds0# z*43?Tp%c&Kaq@L3b-{phXUd^7Nbj8g+Do7SI-5ou$c*HRkQBlurGbDb4K06HN+^}p zVZS`3a?`4_B`~$q$xfP(k=}i_0BSB%LVK>De?7a8-v8dteav}di!Iw}Pb}N%;>)g~@1CDOyzB)ZrY`%o4>JKZ+#0|7 z;bJuOgU=3urrOQ+l$q?{A&kx-J1C)|(RN@d*Jw5oqd9r4+?*GoR0qeQD6G_$$`iZ&Vmz_i6FjloU3{f0+1Zy+UXm&7 zvk;o4Y-Z1&Q4R}Tf$|f3WOukOy~Ox(Ks$zY#qP3RjB&1nDYUy3Q^@isAX{=dwCTg_ zq-cFIIygJ_mx<^w?3Tmq77j4`d@}mlzu5czhqqa_Cll#Mcxw);?J`_hHYp3OoMLv^ z;Bt`ACM|m}7tLn3W+4JJ+w9y~<#*gCp=P(m;Bs4pzEIS!%td+g!`>i>{)pSH+2H^y ze#z@Cn_P-!viZ5_HXspH`ITJM3?&!$(~YsKr=gixWp37ZLX2Y~(`Z;2d;Ml3%rORY(uOfC|T*qeQTSM?m6%j%28# zP4@OmZ4mc>?rh>*w9wA|k7Qhzhbt1%eIs}{2IYtU8hy1!9TAp-46rS8QB6U-LX1&4 zY>fKap*`sc>B{&FrxjVxS=OYK*e=KkE@U4gY&&)|s zS<uMu?p=q;-YP$)lr3@L|@g*f1at3@pAqXIOOI(Fs83N&a3 zsHM~Ch&@t>-sVM6a*$6SJ70vJK>zo_rfjjcv|tmx;U$Yu({MBycH7shY`7;L zIZKNy0Xs*yd@j=^ZXGZ}aDqqXc$6Iim~2`p>di7kR5wM7Jxy>TPGjFHMc~)DlshLI zTLzk~-Hfw1$iXVh&`CCK8Cnljs}&r>9JYNKitw5<_USSN{-N1rbFlh)^cyJIP3-yx zWMX24p}=pg$48giDkqW>|q*I3~CO!uWi)u@TO4 zsR6l^(w`a;c(X3pM(0YTMeIMO;6kR&#M!JP6I*dtH~Y+uXRz~`xIE9_AM|zyd|cHl z)#Jf=2M%_F`?-bveJ*Zgaz4&glk)CJCq(P~GTWVx^VwhK;`UKnrh~ALxb(TrU2d3KEkA5fXyR(IU7b=xjHEZHe72G`VWOPrQ&oA4kO zvAc@!(&RbBZZEkb8a$N+i}8X7QZ|G*KkJt+gf8r%I$Sdz>f$9% z%?1`@T`aa3kHxWPm*8V~Ha9)|Pa_*kj3uq`S5ji!q+F!n0cHVv;wl_YI_1e%7o>rF^}0gw3lr2u+J^}{aR`rN zzg>%a|D9Nq%=l4qWl}RIAUWjUi8UhoDVZfRN*c*<3QZy><^OMD%~h%5p`^=ch>D0I;MV zue1MC33rf5pkuH1 zY{v!|;B->5JfAh}zK6en!#1G9T99A z&+{+DRD$d5&`$giyXi)pqq11d*4U97@h1q?viw_sO*ieruVq#MlUo`Z7cFh7GDf<4 zwy`z4aj{yffQ&ww?b?l(rPklxjeS?d+o`8~u1dX4trj8^+j$E>_Gq-#mm*=O<)XWSeM#5+ei>;<-Z5#{PB} zHV-@Y`n$1-{pBufPXiqt#~)H5u`i!`Q;0ivAh<(LPxs8pAY?1ekL1$YExCjIK=p9~ZJ7Lw-8fgZAGMKke-1HF>mBl$$bf{HSdx=`_Gom`2a zj}UQn}k|}I(J5o{; zls>?DCHz{I7*YjD;3C9Po%+(W34kb`%VuDi3{RiT(Lz#0JiCY1glEBYah!BxIDb0t zkj!Az8?_=a8L-_G&gaID{y1Dl>%y7rcMo7IWHrGe=RJt^xxAE?F2}jS9{w6$BQR>0 zE^lt(nZ(1KVy_+r^Z4$gI9~-%Bo;R2F?y8sa^1<5wg-fQGWp52q6ze>hpH@ KbU~uKM*TnOI_e_; diff --git a/configure.in b/configure.in index f5b31a0..b811554 100644 --- a/configure.in +++ b/configure.in @@ -1,7 +1,7 @@ dnl -dnl PortAudio configure.in script +dnl portaudio V19 configure.in script dnl -dnl Dominic Mazzoni +dnl Dominic Mazzoni, Arve Knudsen dnl dnl Require autoconf >= 2.13 @@ -11,43 +11,183 @@ dnl Init autoconf and make sure configure is being called dnl from the right directory AC_INIT([pa_common/portaudio.h]) -dnl Checks for programs +dnl Specify options + +AC_ARG_WITH(alsa, + [ --with-alsa (default=yes)], + with_alsa=$withval, with_alsa="yes") + +AC_ARG_WITH(jack, + [ --with-jack (default=yes)], + with_jack=$withval, with_jack="yes") + +AC_ARG_WITH(oss, + [ --with-oss (default=yes)], + with_oss=$withval, with_oss="yes") + +AC_ARG_WITH(host_os, + [ --with-host_os (no default)], + host_os=$withval) + +AC_ARG_WITH(winapi, + [ --with-winapi ((wmme/directx/asio) default=wmme)], + with_winapi=$withval, with_winapi="wmme") + +dnl Mac API added for ASIO, can have other api's listed +AC_ARG_WITH(macapi, + [ --with-macapi ((asio/core/sm) default=core)], + with_macapi=$withval, with_macapi="core") + +AC_ARG_WITH(asiodir, + [ --with-asiodir (default=/usr/local/asiosdk2)], + with_asiodir=$withval, with_asiodir="/usr/local/asiosdk2") + +AC_ARG_WITH(dxdir, + [ --with-dxdir (default=/usr/local/dx7sdk)], + with_dxdir=$withval, with_dxdir="/usr/local/dx7sdk") + +AC_ARG_ENABLE(debug-output, + [ --enable-debug-output], + [if test x$enableval != xno ; then + AC_DEFINE(PA_ENABLE_DEBUG_OUTPUT,,[Enable debugging messages]) + fi + ]) + +dnl Checks for programs. + AC_PROG_CC AC_PROG_RANLIB AC_PROG_INSTALL AC_PATH_PROG(AR, ar, no) if [[ $AR = "no" ]] ; then - AC_MSG_ERROR("Could not find ar - needed to create a library"); + AC_MSG_ERROR("Could not find ar - needed to create a library"); fi -dnl Extra variables we want to substitute +dnl This must be one of the first tests we do or it will fail... +AC_C_BIGENDIAN + +dnl checks for various host APIs and arguments to configure that +dnl turn them on or off + +AC_CHECK_LIB(asound, snd_pcm_open, have_alsa=yes, have_alsa=no) + +dnl Determine the host description for the subsequent test. +dnl PKG_CHECK_MODULES seems to check and set the host variable also, but +dnl that then requires pkg-config availability which is not standard on +dnl MinGW systems and can be a pain to install. +AC_CANONICAL_HOST + +PKG_CHECK_MODULES(JACK, jack, have_jack=yes, have_jack=no) + +dnl sizeof checks: we will need a 16-bit and a 32-bit type + +AC_CHECK_SIZEOF(short) +AC_CHECK_SIZEOF(int) +AC_CHECK_SIZEOF(long) + +dnl extra variables AC_SUBST(OTHER_OBJS) AC_SUBST(PADLL) AC_SUBST(SHARED_FLAGS) +AC_SUBST(THREAD_CFLAGS) AC_SUBST(DLL_LIBS) +AC_SUBST(CXXFLAGS) +AC_SUBST(NASM) +AC_SUBST(NASMOPT) -dnl Determine the host operating system / platform -AC_CANONICAL_HOST +CFLAGS="-g -O2 -Wall -pedantic -pipe -fPIC" + +if [[ $ac_cv_c_bigendian = "yes" ]] ; then + CFLAGS="$CFLAGS -DPA_BIG_ENDIAN" +else + CFLAGS="$CFLAGS -DPA_LITTLE_ENDIAN" +fi case "${host_os}" in darwin* ) dnl Mac OS X configuration - OTHER_OBJS="pa_mac_core/pa_mac_core.o"; - LIBS="-framework CoreAudio -lm"; + AC_DEFINE(PA_USE_COREAUDIO) + OTHER_OBJS="pa_mac/pa_mac_hostapis.o pa_unix/pa_unix_util.o pa_mac_core/pa_mac_core.o"; + LIBS="-framework CoreAudio -framework AudioToolbox -framework AudioUnit -framework Carbon"; PADLL="libportaudio.dylib"; - SHARED_FLAGS="-framework CoreAudio -dynamiclib"; + SHARED_FLAGS="-framework CoreAudio -framework AudioToolbox -framework AudioUnit -framework Carbon -dynamiclib"; + if [[ $with_macapi = "asio" ]] ; then + if [[ $with_asiodir ]] ; then + ASIODIR="$with_asiodir"; + else + ASIODIR="/usr/local/asiosdk2"; + fi + echo "ASIODIR: $ASIODIR"; + + OTHER_OBJS="$CFLAGS pa_asio/iasiothiscallresolver.o $ASIODIR/host/asiodrivers.o $ASIODIR/common/asio.o $ASIODIR/host/mac/asioshlib.o"; + CFLAGS="$CFLAGS -Ipa_asio -I$ASIDIR/host/mac -I$ASIODIR/common"; + CXXFLAGS="$CFLAGS"; + fi ;; mingw* ) - dnl MingW configuration + dnl MingW configuration - OTHER_OBJS="pa_win_wmme/pa_win_wmme.o"; - LIBS="-lwinmm -lm"; - PADLL="portaudio.dll"; - SHARED_FLAGS="-shared -mthreads"; - DLL_LIBS="-lwinmm"; - ;; + echo "WINAPI: $with_winapi" + if [[ $with_winapi = "directx" ]] ; then + if [[ $with_dxdir ]] ; then + DXDIR="$with_dxdir"; + else + DXDIR="/usr/local/dx7sdk"; + fi + echo "DXDIR: $DXDIR" + OTHER_OBJS="pa_win_ds/pa_win_ds.o pa_win_ds/dsound_wrapper.o pa_win/pa_win_hostapis.o pa_win/pa_win_util.o"; + LIBS="-lwinmm -lm -ldsound -lole32"; + PADLL="portaudio.dll"; + THREAD_CFLAGS="-mthreads" + SHARED_FLAGS="-shared"; + DLL_LIBS="-lwinmm -lm -L./dx7sdk/lib -ldsound -lole32"; + #VC98="\"/c/Program Files/Microsoft Visual Studio/VC98/Include\""; + #CFLAGS="$CFLAGS -I$VC98 -DPA_NO_WMME -DPA_NO_ASIO"; + CFLAGS="$CFLAGS -Ipa_common -I$DXDIR/include -DPA_NO_WMME -DPA_NO_ASIO" -DPA_NO_WDMKS; + elif [[ $with_winapi = "asio" ]] ; then + if [[ $with_asiodir ]] ; then + ASIODIR="$with_asiodir"; + else + ASIODIR="/usr/local/asiosdk2"; + fi + echo "ASIODIR: $ASIODIR" + + OTHER_OBJS="pa_asio/pa_asio.o pa_win/pa_win_hostapis.o pa_win/pa_win_util.o pa_asio/iasiothiscallresolver.o $ASIODIR/common/asio.o $ASIODIR/host/asiodrivers.o $ASIODIR/host/pc/asiolist.o"; + LIBS="-lwinmm -lm -lstdc++ -lole32 -luuid"; + PADLL="portaudio.dll"; + THREAD_CFLAGS="-mthreads" + SHARED_FLAGS="-shared"; + DLL_LIBS="-lwinmm -lm -lstdc++ -lole32 -luuid"; + CFLAGS="$CFLAGS -ffast-math -fomit-frame-pointer -Ipa_common -Ipa_asio -I$ASIODIR/host/pc -I$ASIODIR/common -I$ASIODIR/host -DPA_NO_WMME -DPA_NO_DS -DPA_NO_WDMKS -DWINDOWS"; + CXXFLAGS="$CFLAGS"; + elif [[ $with_winapi = "wdmks" ]] ; then + if [[ $with_dxdir ]] ; then + DXDIR="$with_dxdir"; + else + DXDIR="/usr/local/dx7sdk"; + fi + echo "DXDIR: $DXDIR" + OTHER_OBJS="pa_win_wdmks/pa_win_wdmks.o pa_win/pa_win_hostapis.o pa_win/pa_win_util.o"; + LIBS="-lwinmm -lm -luuid -lsetupapi -lole32"; + PADLL="portaudio.dll"; + THREAD_CFLAGS="-mthreads" + SHARED_FLAGS="-shared"; + DLL_LIBS="-lwinmm -lm -L./dx7sdk/lib -luuid -lsetupapi -lole32"; + #VC98="\"/c/Program Files/Microsoft Visual Studio/VC98/Include\""; + #CFLAGS="$CFLAGS -I$VC98 -DPA_NO_WMME -DPA_NO_ASIO"; + CFLAGS="$CFLAGS -Ipa_common -I$DXDIR/include -DPA_NO_WMME -DPA_NO_DS -DPA_NO_ASIO"; + else # WMME default + OTHER_OBJS="pa_win_wmme/pa_win_wmme.o pa_win/pa_win_hostapis.o pa_win/pa_win_util.o"; + LIBS="-lwinmm -lm -lstdc++ -lole32 -luuid"; + PADLL="portaudio.dll"; + THREAD_CFLAGS="-mthreads" + SHARED_FLAGS="-shared"; + DLL_LIBS="-lwinmm"; + CFLAGS="$CFLAGS -Ipa_common -DPA_NO_DS -DPA_NO_ASIO -DPA_NO_WDMKS"; + fi + ;; cygwin* ) dnl Cygwin configuration @@ -55,27 +195,70 @@ case "${host_os}" in OTHER_OBJS="pa_win_wmme/pa_win_wmme.o"; LIBS="-lwinmm -lm"; PADLL="portaudio.dll"; - SHARED_FLAGS="-shared -mthreads"; + THREAD_CFLAGS="-mthreads" + SHARED_FLAGS="-shared"; DLL_LIBS="-lwinmm"; ;; + irix* ) + dnl SGI IRIX audio library (AL) configuration (Pieter, oct 2-13, 2003). + dnl The 'dmedia' library is needed to read the Unadjusted System Time (UST). + dnl + AC_CHECK_LIB(pthread, pthread_create, , AC_MSG_ERROR([IRIX posix thread library not found!])) + AC_CHECK_LIB(audio, alOpenPort, , AC_MSG_ERROR([IRIX audio library not found!])) + AC_CHECK_LIB(dmedia, dmGetUST, , AC_MSG_ERROR([IRIX digital media library not found!])) + + dnl See the '#ifdef PA_USE_SGI' in file pa_unix/pa_unix_hostapis.c + dnl which selects the appropriate PaXXX_Initialize() function. + dnl + AC_DEFINE(PA_USE_SGI) + + dnl The _REENTRANT option for pthread safety. Perhaps not necessary but it 'll do no harm. + dnl + THREAD_CFLAGS="-D_REENTRANT" + + OTHER_OBJS="pa_sgi/pa_sgi.o pa_unix/pa_unix_hostapis.o pa_unix/pa_unix_util.o"; + + dnl SGI books say -lpthread should be the last of the libs mentioned. + dnl + LIBS="-lm -ldmedia -laudio -lpthread"; + PADLL="libportaudio.so"; + SHARED_FLAGS="-shared"; + ;; + *) - dnl Unix OSS configuration + dnl Unix configuration AC_CHECK_LIB(pthread, pthread_create, , AC_MSG_ERROR([libpthread not found!])) - OTHER_OBJS="pa_unix_oss/pa_unix_oss.o"; - LIBS="-lm -lpthread"; - PADLL="libportaudio.so"; - SHARED_FLAGS="-shared"; -esac + if [[ $have_alsa = "yes" ] && [ $with_alsa != "no" ]] ; then + LIBS="$LIBS -lasound" + DLL_LIBS="$DLL_LIBS -lasound" + OTHER_OBJS="$OTHER_OBJS pa_linux_alsa/pa_linux_alsa.o" + AC_DEFINE(PA_USE_ALSA) + fi -AC_OUTPUT([Makefile]) + if [[ $have_jack = "yes" ] && [ $with_jack != "no" ]] ; then + LIBS="$LIBS $JACK_LIBS" + DLL_LIBS="$DLL_LIBS $JACK_LIBS" + CFLAGS="$CFLAGS $JACK_CFLAGS" + OTHER_OBJS="$OTHER_OBJS pa_jack/pa_jack.o" + AC_DEFINE(PA_USE_JACK) + fi -echo "" -echo "Finished configure." + if [[ $with_oss != "no" ]] ; then + OTHER_OBJS="$OTHER_OBJS pa_unix_oss/pa_unix_oss.o" + AC_DEFINE(PA_USE_OSS) + fi + THREAD_CFLAGS="-pthread" + LIBS="$LIBS -lm -lpthread"; + PADLL="libportaudio.so"; + SHARED_FLAGS="-shared -fPIC"; + + OTHER_OBJS="$OTHER_OBJS pa_unix/pa_unix_hostapis.o pa_unix/pa_unix_util.o" +esac +CFLAGS="$CFLAGS $THREAD_CFLAGS" -echo "" -echo "Type 'make' to build PortAudio and examples." +AC_OUTPUT([Makefile portaudio-2.0.pc]) diff --git a/docs/index.html b/docs/index.html index dfd648e..7d9b248 100644 --- a/docs/index.html +++ b/docs/index.html @@ -21,22 +21,16 @@ PortAudio Documentation

Copyright 2000 Phil Burk and Ross Bencina -

-Tutorial

- -
-
Describes how to write audio programs using the PortAudio API.
- +
 

API Reference

-
The Application Programmer Interface is documented in "portaudio.h".
+
The Application Programmer Interface is documented in "portaudio.h".

-Release Notes

+Tutorial -
What changed since the last release?
-
+
Describes how to write audio programs using the PortAudio API.

Implementation Guide

diff --git a/docs/proposals.html b/docs/proposals.html index 88dd2d07ce3ed33b6d0f92cc99ae31fb2c5a16b7..0f9b8cb641c4ad31176eaec56bc03663abbaf937 100644 GIT binary patch delta 14 VcmdnXv4>-W3^OCwW?5!=MgSmY16Ke5 delta 16 XcmdnPv6o|m3^OD5W?5!=Mn(nzCmaJ= diff --git a/docs/style.html b/docs/style.html deleted file mode 100644 index 8f0937c..0000000 --- a/docs/style.html +++ /dev/null @@ -1,156 +0,0 @@ - - -Coding Style Guidelines for PortAudio Implementors - - - - - -  -
- - - -
-
-

Coding Style Guidelines for PortAudio Implementors

-
-
-

PortAudio Home Page

- -

Updated: June 12, 2002

- -

Introduction

-

-This document provides coding guidelines for PortAudio implementors. Some of the guildelines pertain to mechanical style, others to quality of implementation issues. Since the PortAudio code is commonly edited on many different platforms using different editors these guideline should be followed to improve readability and consistency. -

- -

PortAudio API Design Guidelines

-

-The design guidelines of the PortAudio project are stated here -as some of them apply to implementation as well as to API design. -

-
    -
  • - Implementation should be possible on all common computer - music platforms. -
  • -
  • - Clients of PortAudio should be able to gain efficient, - and ideally optimal use of the audio services - on all target platforms. -
  • -
  • - The API should be simple enough to be used by music - students with minimal experience in C programming. -
  • -
  • - The API should seek to provide only low-level audio - services, and to only support those services directly - available on the host platform. -
  • -
- -

-Note that the final guideline has been bent with regard to audio -sample formats and user buffer sizes - PortAudio can convert between -a number of sample formats and can adapt to the user's buffer size requirements. -

- -

Formatting Conventions

- -

-The following formatting conventions should be adhered to in all PortAudio code: -

- -
    -
  • TABs should not be used in .c and .h files; instead 4 spaces should be used. Makefiles should continue to use TABs since this is required by Make
  • -
  • Line-emd characters will be consistent with the platform on which the source has been checked out of CVS (CVS handles this.)
  • -
  • Brace placement will follow ANSI style, eg: -
    -if( aCondition )
    -{
    -	DoSomething();
    -}
    -else
    -{
    -	DoSomethingElse();
    -}
    -
    -
  • -
- -

AStyle ( http://astyle.sourceforge.net/ ) has been proposed as helpful tool for cleaning code, however we don't intend to use it on an ongoing basis. It is expected that contributors of each implementation will take responsibility for keeping their code clean.

- - -

Quality of Implementation Guidelines

- -

The following coding guidelines should be followed in order to establish a quality baseline for our implementations:

- -
    -
  • All code should be written in C++-compatible plain ANSI-C (i.e. no // comments). It has been suggested that all implementations should compile silently with both "gcc -ansi -pedantic -Wall" and "g++ -ansi -pedantic -Wall"
  • -
  • Think of PortAudio as a heavyweight library rather than a lightweight wrapper. Always code defensively. Efficiency is important where it matters (eg in real-time callbacks) but safety is important everywhere.
  • -
  • All parameters passed to PortAudio by the user should be validated, and error codes returned where necessary. All reasonable efforts should be made to minimise the risk of a crash resulting from passing incorrect parameters to PortAudio.
  • -
  • Error handling should be complete. Every host function that can return an error condition should have its status checked. PortAudio may attempt to recover from errors in some cases, but generally error codes should be returned to the client.
  • -
  • In almost all cases, a PortAudio error code should be preferred to returning PaHostError. If a new PortAudio error code is needed it should be discussed with the maintainer to coordinate updating portaudio.h
  • -
  • PortAudio code should not cause resource leaks. After Pa_Terminate() is called, implementations should guarantee that all dynamically allocated resources have been freed.
  • -
  • The definition of the PortAudio API should minimise "implementation defined behaviour". For example, calling functions such as Pa_Initialize() after PortAudio is initialised, or Pa_Terminate() after PortAudio has been terminated has well defined behaviour.
  • -
  • Minimise dependence on ANSI C runtime on platforms where it would have to be loaded separately (eg on Win32 prefer Win32 API functions such as GlobalAlloc() to ANSI C functions such as malloc().)
- -

It has been suggested that we make an effort to minimise the use of global and static data in PortAudio implementations. Another related goal is to reduce name pollution in the global scope. Some possible guidelines in this regard are:

- -
    -
  • Implementations should avoid exporting any symbols except where absolutely necessary. Specifically, global data must be declared statically. The next section documents naming conventions for all PortAudio symbols.
  • -
  • Implementations should minimise their use of static data.
- -

Naming Conventions

- -
    -
  • All #defines begin with PA_
  • -
  • All #defines local to a file end with _
  • -
  • All global utility variables begin with paUtil
  • -
  • All global utility types begin with PaUtil (including function types)
  • -
  • All global utility functions begin with PaUtil_
  • -
  • All static variables end with _
  • -
  • All static constants begin with const and end with _ (eg: constMyMagicNumber_)
  • -
  • All static funtions have no special prefix/suffix
  • -
  • -Platform-specific shared functions should begin with Pa_ where PN is the -platform name. eg. PaWin_ for windows, PaUnix_ for unix. -
  • -
- -

-In general, implementations should declare all of their members static, -except for their initializer which should be exported. All exported names -should be preceeded by Pa_ where is the module name, for example -the windows mme initializer should be named PaWinMme_Initialize(). -

- -

-If it is necessary for implementations to define non-static symbols, they should -use the following naming conventions, where is the module name such as WinMme. -

- -
    -
  • global variables should begin with pa
  • -
  • global types should begin with Pa
  • -
  • global utility functions should begin with Pa_
  • -
- -

-Two utilities for debug messages are provided. The PA_DEBUG macro defined in -pa_implementation.h provides a simple way to print debug messages to stderr. -Due to real-time performance issues, PA_DEBUG may not be suitable for use -within the portaudio processing callback, or in other threads. In such cases -the event tracing facility provided in pa_trace.h may be more appropriate. -

-

-If PA_LOG_API_CALLS is defined, all calls to the public PortAudio API -will be logged to stderr along with parameter and return values. -

- - - \ No newline at end of file diff --git a/pa_asio/ASIO-README.txt b/pa_asio/ASIO-README.txt new file mode 100644 index 0000000..9fb74ae --- /dev/null +++ b/pa_asio/ASIO-README.txt @@ -0,0 +1,137 @@ +ASIO-README.txt + +This document contains information to help you compile PortAudio with +ASIO support. If you find any omissions or errors in this document +please notify Ross Bencina . + + +Building PortAudio with ASIO support +------------------------------------ + +To build PortAudio with ASIO support you need to compile and link with +pa_asio.c, and files from the ASIO SDK (see below), along with the common +files from pa_common/ and platform specific files from pa_win/ (for Win32) +or pa_mac/ (for Macintosh). + +If you are compiling with a non-Microsoft compiler on windows, also +compile and link with iasiothiscallresolver.cpp (see below for +an explanation). + +For some platforms (MingW, possibly Mac), you may simply +be able to type: + +./configure --with-host_os=mingw --with-winapi=asio [--with-asiodir=/usr/local/asiosdk2] +make + +./configure --with-host_os=darwin --with-winapi=asio [--with-asiodir=/usr/local/asiosdk2] +make + +and life will be good. + + +Obtaining the ASIO SDK +---------------------- + +In order to build PortAudio with ASIO support, you need to download +the ASIO SDK (version 2.0) from Steinberg. Steinberg makes the ASIO +SDK available to anyone free of charge, however they do not permit its +source code to be distributed. + +NOTE: In some cases the ASIO SDK may require patching, see below +for further details. + +http://www.steinberg.net/en/ps/support/3rdparty/asio_sdk/ + +If the above link is broken search Google for: +"download steinberg ASIO SDK" + + + +Building the ASIO SDK on Macintosh +---------------------------------- + +To build the ASIO SDK on Macintosh you need to compile and link with the +following files from the ASIO SDK: + +host/asiodrivers.cpp +host/mac/asioshlib.cpp +host/mac/codefragements.cpp + + + +Building the ASIO SDK on Windows +-------------------------------- + +To build the ASIO SDK on Windows you need to compile and link with the +following files from the ASIO SDK: + +asio_sdk\common\asio.cpp +asio_sdk\host\asiodrivers.cpp +asio_sdk\host\pc\asiolist.cpp + +You may also need to adjust your include paths to support inclusion of +header files from the above directories. + +The ASIO SDK depends on the following COM API functions: +CoInitialize, CoUninitialize, CoCreateInstance, CLSIDFromString +For compilation with MinGW you will need to link with -lole32, for +Borland link with Import32.lib. + + + +Non-Microsoft (MSVC) Compilers on Windows including Borland and GCC +------------------------------------------------------------------- + +Steinberg did not specify a calling convention in the IASIO interface +definition. This causes the Microsoft compiler to use the proprietary +thiscall convention which is not compatible with other compilers, such +as compilers from Borland (BCC and C++Builder) and GNU (gcc). +Steinberg's ASIO SDK will compile but crash on initialization if +compiled with a non-Microsoft compiler on Windows. + +PortAudio solves this problem using the iasiothiscallresolver library +which is included in the distribution. When building ASIO support for +non-Microsoft compilers, be sure to compile and link with +iasiothiscallresolver.cpp. Note that iasiothiscallresolver includes +conditional directives which cause it to have no effect if it is +compiled with a Microsoft compiler, or on the Macintosh. + +If you use configure and make (see above), this should be handled +automatically for you. + +For further information about the IASIO thiscall problem see this page: +http://www.audiomulch.com/~rossb/code/calliasio + + + +Macintosh ASIO SDK Bug Patch +---------------------------- + +There is a bug in the ASIO SDK that causes the Macintosh version to +often fail during initialization. Below is a patch that you can apply. + +In codefragments.cpp replace getFrontProcessDirectory function with +the following one (GetFrontProcess replaced by GetCurrentProcess). + + +bool CodeFragments::getFrontProcessDirectory(void *specs) +{ + FSSpec *fss = (FSSpec *)specs; + ProcessInfoRec pif; + ProcessSerialNumber psn; + + memset(&psn,0,(long)sizeof(ProcessSerialNumber)); + // if(GetFrontProcess(&psn) == noErr) // wrong !!! + if(GetCurrentProcess(&psn) == noErr) // correct !!! + { + pif.processName = 0; + pif.processAppSpec = fss; + pif.processInfoLength = sizeof(ProcessInfoRec); + if(GetProcessInformation(&psn, &pif) == noErr) + return true; + } + return false; +} + + +--- diff --git a/pa_asio/borland_asio_readme.txt b/pa_asio/borland_asio_readme.txt deleted file mode 100644 index 56e472b..0000000 --- a/pa_asio/borland_asio_readme.txt +++ /dev/null @@ -1,6 +0,0 @@ -Steinberg's ASIO 2 SDK will compile but crash on -initialization if compiled with a Borland compiler. - -The problem is described, and a solution provided on -the following page: -http://www.audiomulch.com/~rossb/code/calliasio \ No newline at end of file diff --git a/pa_asio/iasiothiscallresolver.cpp b/pa_asio/iasiothiscallresolver.cpp new file mode 100644 index 0000000..8dfefbd --- /dev/null +++ b/pa_asio/iasiothiscallresolver.cpp @@ -0,0 +1,563 @@ +/* + IASIOThiscallResolver.cpp see the comments in iasiothiscallresolver.h for + the top level description - this comment describes the technical details of + the implementation. + + The latest version of this file is available from: + http://www.audiomulch.com/~rossb/code/calliasio + + please email comments to Ross Bencina + + BACKGROUND + + The IASIO interface declared in the Steinberg ASIO 2 SDK declares + functions with no explicit calling convention. This causes MSVC++ to default + to using the thiscall convention, which is a proprietary convention not + implemented by some non-microsoft compilers - notably borland BCC, + C++Builder, and gcc. MSVC++ is the defacto standard compiler used by + Steinberg. As a result of this situation, the ASIO sdk will compile with + any compiler, however attempting to execute the compiled code will cause a + crash due to different default calling conventions on non-Microsoft + compilers. + + IASIOThiscallResolver solves the problem by providing an adapter class that + delegates to the IASIO interface using the correct calling convention + (thiscall). Due to the lack of support for thiscall in the Borland and GCC + compilers, the calls have been implemented in assembly language. + + A number of macros are defined for thiscall function calls with different + numbers of parameters, with and without return values - it may be possible + to modify the format of these macros to make them work with other inline + assemblers. + + + THISCALL DEFINITION + + A number of definitions of the thiscall calling convention are floating + around the internet. The following definition has been validated against + output from the MSVC++ compiler: + + For non-vararg functions, thiscall works as follows: the object (this) + pointer is passed in ECX. All arguments are passed on the stack in + right to left order. The return value is placed in EAX. The callee + clears the passed arguments from the stack. + + + FINDING FUNCTION POINTERS FROM AN IASIO POINTER + + The first field of a COM object is a pointer to its vtble. Thus a pointer + to an object implementing the IASIO interface also points to a pointer to + that object's vtbl. The vtble is a table of function pointers for all of + the virtual functions exposed by the implemented interfaces. + + If we consider a variable declared as a pointer to IASO: + + IASIO *theAsioDriver + + theAsioDriver points to: + + object implementing IASIO + { + IASIOvtbl *vtbl + other data + } + + in other words, theAsioDriver points to a pointer to an IASIOvtbl + + vtbl points to a table of function pointers: + + IASIOvtbl ( interface IASIO : public IUnknown ) + { + (IUnknown functions) + 0 virtual HRESULT STDMETHODCALLTYPE (*QueryInterface)(REFIID riid, void **ppv) = 0; + 4 virtual ULONG STDMETHODCALLTYPE (*AddRef)() = 0; + 8 virtual ULONG STDMETHODCALLTYPE (*Release)() = 0; + + (IASIO functions) + 12 virtual ASIOBool (*init)(void *sysHandle) = 0; + 16 virtual void (*getDriverName)(char *name) = 0; + 20 virtual long (*getDriverVersion)() = 0; + 24 virtual void (*getErrorMessage)(char *string) = 0; + 28 virtual ASIOError (*start)() = 0; + 32 virtual ASIOError (*stop)() = 0; + 36 virtual ASIOError (*getChannels)(long *numInputChannels, long *numOutputChannels) = 0; + 40 virtual ASIOError (*getLatencies)(long *inputLatency, long *outputLatency) = 0; + 44 virtual ASIOError (*getBufferSize)(long *minSize, long *maxSize, + long *preferredSize, long *granularity) = 0; + 48 virtual ASIOError (*canSampleRate)(ASIOSampleRate sampleRate) = 0; + 52 virtual ASIOError (*getSampleRate)(ASIOSampleRate *sampleRate) = 0; + 56 virtual ASIOError (*setSampleRate)(ASIOSampleRate sampleRate) = 0; + 60 virtual ASIOError (*getClockSources)(ASIOClockSource *clocks, long *numSources) = 0; + 64 virtual ASIOError (*setClockSource)(long reference) = 0; + 68 virtual ASIOError (*getSamplePosition)(ASIOSamples *sPos, ASIOTimeStamp *tStamp) = 0; + 72 virtual ASIOError (*getChannelInfo)(ASIOChannelInfo *info) = 0; + 76 virtual ASIOError (*createBuffers)(ASIOBufferInfo *bufferInfos, long numChannels, + long bufferSize, ASIOCallbacks *callbacks) = 0; + 80 virtual ASIOError (*disposeBuffers)() = 0; + 84 virtual ASIOError (*controlPanel)() = 0; + 88 virtual ASIOError (*future)(long selector,void *opt) = 0; + 92 virtual ASIOError (*outputReady)() = 0; + }; + + The numbers in the left column show the byte offset of each function ptr + from the beginning of the vtbl. These numbers are used in the code below + to select different functions. + + In order to find the address of a particular function, theAsioDriver + must first be dereferenced to find the value of the vtbl pointer: + + mov eax, theAsioDriver + mov edx, [theAsioDriver] // edx now points to vtbl[0] + + Then an offset must be added to the vtbl pointer to select a + particular function, for example vtbl+44 points to the slot containing + a pointer to the getBufferSize function. + + Finally vtbl+x must be dereferenced to obtain the value of the function + pointer stored in that address: + + call [edx+44] // call the function pointed to by + // the value in the getBufferSize field of the vtbl + + + SEE ALSO + + Martin Fay's OpenASIO DLL at http://www.martinfay.com solves the same + problem by providing a new COM interface which wraps IASIO with an + interface that uses portable calling conventions. OpenASIO must be compiled + with MSVC, and requires that you ship the OpenASIO DLL with your + application. + + + ACKNOWLEDGEMENTS + + Ross Bencina: worked out the thiscall details above, wrote the original + Borland asm macros, and a patch for asio.cpp (which is no longer needed). + Thanks to Martin Fay for introducing me to the issues discussed here, + and to Rene G. Ceballos for assisting with asm dumps from MSVC++. + + Antti Silvast: converted the original calliasio to work with gcc and NASM + by implementing the asm code in a separate file. + + Fraser Adams: modified the original calliasio containing the Borland inline + asm to add inline asm for gcc i.e. Intel syntax for Borland and AT&T syntax + for gcc. This seems a neater approach for gcc than to have a separate .asm + file and it means that we only need one version of the thiscall patch. + + Fraser Adams: rewrote the original calliasio patch in the form of the + IASIOThiscallResolver class in order to avoid modifications to files from + the Steinberg SDK, which may have had potential licence issues. + + Andrew Baldwin: contributed fixes for compatibility problems with more + recent versions of the gcc assembler. +*/ + + +// We only need IASIOThiscallResolver at all if we are on Win32. For other +// platforms we simply bypass the IASIOThiscallResolver definition to allow us +// to be safely #include'd whatever the platform to keep client code portable +#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) + + +// If microsoft compiler we can call IASIO directly so IASIOThiscallResolver +// is not used. +#if !defined(_MSC_VER) + + +#include +#include + +// We have a mechanism in iasiothiscallresolver.h to ensure that asio.h is +// #include'd before it in client code, we do NOT want to do this test here. +#define iasiothiscallresolver_sourcefile 1 +#include "iasiothiscallresolver.h" +#undef iasiothiscallresolver_sourcefile + +// iasiothiscallresolver.h redefines ASIOInit for clients, but we don't want +// this macro defined in this translation unit. +#undef ASIOInit + + +// theAsioDriver is a global pointer to the current IASIO instance which the +// ASIO SDK uses to perform all actions on the IASIO interface. We substitute +// our own forwarding interface into this pointer. +extern IASIO* theAsioDriver; + + +// The following macros define the inline assembler for BORLAND first then gcc + +#if defined(__BCPLUSPLUS__) || defined(__BORLANDC__) + + +#define CALL_THISCALL_0( resultName, thisPtr, funcOffset )\ + void *this_ = (thisPtr); \ + __asm { \ + mov ecx, this_ ; \ + mov eax, [ecx] ; \ + call [eax+funcOffset] ; \ + mov resultName, eax ; \ + } + + +#define CALL_VOID_THISCALL_1( thisPtr, funcOffset, param1 )\ + void *this_ = (thisPtr); \ + __asm { \ + mov eax, param1 ; \ + push eax ; \ + mov ecx, this_ ; \ + mov eax, [ecx] ; \ + call [eax+funcOffset] ; \ + } + + +#define CALL_THISCALL_1( resultName, thisPtr, funcOffset, param1 )\ + void *this_ = (thisPtr); \ + __asm { \ + mov eax, param1 ; \ + push eax ; \ + mov ecx, this_ ; \ + mov eax, [ecx] ; \ + call [eax+funcOffset] ; \ + mov resultName, eax ; \ + } + + +#define CALL_THISCALL_1_DOUBLE( resultName, thisPtr, funcOffset, param1 )\ + void *this_ = (thisPtr); \ + void *doubleParamPtr_ (¶m1); \ + __asm { \ + mov eax, doubleParamPtr_ ; \ + push [eax+4] ; \ + push [eax] ; \ + mov ecx, this_ ; \ + mov eax, [ecx] ; \ + call [eax+funcOffset] ; \ + mov resultName, eax ; \ + } + + +#define CALL_THISCALL_2( resultName, thisPtr, funcOffset, param1, param2 )\ + void *this_ = (thisPtr); \ + __asm { \ + mov eax, param2 ; \ + push eax ; \ + mov eax, param1 ; \ + push eax ; \ + mov ecx, this_ ; \ + mov eax, [ecx] ; \ + call [eax+funcOffset] ; \ + mov resultName, eax ; \ + } + + +#define CALL_THISCALL_4( resultName, thisPtr, funcOffset, param1, param2, param3, param4 )\ + void *this_ = (thisPtr); \ + __asm { \ + mov eax, param4 ; \ + push eax ; \ + mov eax, param3 ; \ + push eax ; \ + mov eax, param2 ; \ + push eax ; \ + mov eax, param1 ; \ + push eax ; \ + mov ecx, this_ ; \ + mov eax, [ecx] ; \ + call [eax+funcOffset] ; \ + mov resultName, eax ; \ + } + + +#elif defined(__GNUC__) + + +#define CALL_THISCALL_0( resultName, thisPtr, funcOffset ) \ + __asm__ __volatile__ ("movl (%1), %%edx\n\t" \ + "call *"#funcOffset"(%%edx)\n\t" \ + :"=a"(resultName) /* Output Operands */ \ + :"c"(thisPtr) /* Input Operands */ \ + ); \ + + +#define CALL_VOID_THISCALL_1( thisPtr, funcOffset, param1 ) \ + __asm__ __volatile__ ("pushl %0\n\t" \ + "movl (%1), %%edx\n\t" \ + "call *"#funcOffset"(%%edx)\n\t" \ + : /* Output Operands */ \ + :"r"(param1), /* Input Operands */ \ + "c"(thisPtr) \ + ); \ + + +#define CALL_THISCALL_1( resultName, thisPtr, funcOffset, param1 ) \ + __asm__ __volatile__ ("pushl %1\n\t" \ + "movl (%2), %%edx\n\t" \ + "call *"#funcOffset"(%%edx)\n\t" \ + :"=a"(resultName) /* Output Operands */ \ + :"r"(param1), /* Input Operands */ \ + "c"(thisPtr) \ + ); \ + + +#define CALL_THISCALL_1_DOUBLE( resultName, thisPtr, funcOffset, param1 ) \ + __asm__ __volatile__ ("pushl 4(%1)\n\t" \ + "pushl (%1)\n\t" \ + "movl (%2), %%edx\n\t" \ + "call *"#funcOffset"(%%edx);\n\t" \ + :"=a"(resultName) /* Output Operands */ \ + :"a"(¶m1), /* Input Operands */ \ + /* Note: Using "r" above instead of "a" fails */ \ + /* when using GCC 3.3.3, and maybe later versions*/\ + "c"(thisPtr) \ + ); \ + + +#define CALL_THISCALL_2( resultName, thisPtr, funcOffset, param1, param2 ) \ + __asm__ __volatile__ ("pushl %1\n\t" \ + "pushl %2\n\t" \ + "movl (%3), %%edx\n\t" \ + "call *"#funcOffset"(%%edx)\n\t" \ + :"=a"(resultName) /* Output Operands */ \ + :"r"(param2), /* Input Operands */ \ + "r"(param1), \ + "c"(thisPtr) \ + ); \ + + +#define CALL_THISCALL_4( resultName, thisPtr, funcOffset, param1, param2, param3, param4 )\ + __asm__ __volatile__ ("pushl %1\n\t" \ + "pushl %2\n\t" \ + "pushl %3\n\t" \ + "pushl %4\n\t" \ + "movl (%5), %%edx\n\t" \ + "call *"#funcOffset"(%%edx)\n\t" \ + :"=a"(resultName) /* Output Operands */ \ + :"r"(param4), /* Input Operands */ \ + "r"(param3), \ + "r"(param2), \ + "r"(param1), \ + "c"(thisPtr) \ + ); \ + +#endif + + + +// Our static singleton instance. +IASIOThiscallResolver IASIOThiscallResolver::instance; + +// Constructor called to initialize static Singleton instance above. Note that +// it is important not to clear that_ incase it has already been set by the call +// to placement new in ASIOInit(). +IASIOThiscallResolver::IASIOThiscallResolver() +{ +} + +// Constructor called from ASIOInit() below +IASIOThiscallResolver::IASIOThiscallResolver(IASIO* that) +: that_( that ) +{ +} + +// Implement IUnknown methods as assert(false). IASIOThiscallResolver is not +// really a COM object, just a wrapper which will work with the ASIO SDK. +// If you wanted to use ASIO without the SDK you might want to implement COM +// aggregation in these methods. +HRESULT STDMETHODCALLTYPE IASIOThiscallResolver::QueryInterface(REFIID riid, void **ppv) +{ + (void)riid; // suppress unused variable warning + + assert( false ); // this function should never be called by the ASIO SDK. + + *ppv = NULL; + return E_NOINTERFACE; +} + +ULONG STDMETHODCALLTYPE IASIOThiscallResolver::AddRef() +{ + assert( false ); // this function should never be called by the ASIO SDK. + + return 1; +} + +ULONG STDMETHODCALLTYPE IASIOThiscallResolver::Release() +{ + assert( false ); // this function should never be called by the ASIO SDK. + + return 1; +} + + +// Implement the IASIO interface methods by performing the vptr manipulation +// described above then delegating to the real implementation. +ASIOBool IASIOThiscallResolver::init(void *sysHandle) +{ + ASIOBool result; + CALL_THISCALL_1( result, that_, 12, sysHandle ); + return result; +} + +void IASIOThiscallResolver::getDriverName(char *name) +{ + CALL_VOID_THISCALL_1( that_, 16, name ); +} + +long IASIOThiscallResolver::getDriverVersion() +{ + ASIOBool result; + CALL_THISCALL_0( result, that_, 20 ); + return result; +} + +void IASIOThiscallResolver::getErrorMessage(char *string) +{ + CALL_VOID_THISCALL_1( that_, 24, string ); +} + +ASIOError IASIOThiscallResolver::start() +{ + ASIOBool result; + CALL_THISCALL_0( result, that_, 28 ); + return result; +} + +ASIOError IASIOThiscallResolver::stop() +{ + ASIOBool result; + CALL_THISCALL_0( result, that_, 32 ); + return result; +} + +ASIOError IASIOThiscallResolver::getChannels(long *numInputChannels, long *numOutputChannels) +{ + ASIOBool result; + CALL_THISCALL_2( result, that_, 36, numInputChannels, numOutputChannels ); + return result; +} + +ASIOError IASIOThiscallResolver::getLatencies(long *inputLatency, long *outputLatency) +{ + ASIOBool result; + CALL_THISCALL_2( result, that_, 40, inputLatency, outputLatency ); + return result; +} + +ASIOError IASIOThiscallResolver::getBufferSize(long *minSize, long *maxSize, + long *preferredSize, long *granularity) +{ + ASIOBool result; + CALL_THISCALL_4( result, that_, 44, minSize, maxSize, preferredSize, granularity ); + return result; +} + +ASIOError IASIOThiscallResolver::canSampleRate(ASIOSampleRate sampleRate) +{ + ASIOBool result; + CALL_THISCALL_1_DOUBLE( result, that_, 48, sampleRate ); + return result; +} + +ASIOError IASIOThiscallResolver::getSampleRate(ASIOSampleRate *sampleRate) +{ + ASIOBool result; + CALL_THISCALL_1( result, that_, 52, sampleRate ); + return result; +} + +ASIOError IASIOThiscallResolver::setSampleRate(ASIOSampleRate sampleRate) +{ + ASIOBool result; + CALL_THISCALL_1_DOUBLE( result, that_, 56, sampleRate ); + return result; +} + +ASIOError IASIOThiscallResolver::getClockSources(ASIOClockSource *clocks, long *numSources) +{ + ASIOBool result; + CALL_THISCALL_2( result, that_, 60, clocks, numSources ); + return result; +} + +ASIOError IASIOThiscallResolver::setClockSource(long reference) +{ + ASIOBool result; + CALL_THISCALL_1( result, that_, 64, reference ); + return result; +} + +ASIOError IASIOThiscallResolver::getSamplePosition(ASIOSamples *sPos, ASIOTimeStamp *tStamp) +{ + ASIOBool result; + CALL_THISCALL_2( result, that_, 68, sPos, tStamp ); + return result; +} + +ASIOError IASIOThiscallResolver::getChannelInfo(ASIOChannelInfo *info) +{ + ASIOBool result; + CALL_THISCALL_1( result, that_, 72, info ); + return result; +} + +ASIOError IASIOThiscallResolver::createBuffers(ASIOBufferInfo *bufferInfos, + long numChannels, long bufferSize, ASIOCallbacks *callbacks) +{ + ASIOBool result; + CALL_THISCALL_4( result, that_, 76, bufferInfos, numChannels, bufferSize, callbacks ); + return result; +} + +ASIOError IASIOThiscallResolver::disposeBuffers() +{ + ASIOBool result; + CALL_THISCALL_0( result, that_, 80 ); + return result; +} + +ASIOError IASIOThiscallResolver::controlPanel() +{ + ASIOBool result; + CALL_THISCALL_0( result, that_, 84 ); + return result; +} + +ASIOError IASIOThiscallResolver::future(long selector,void *opt) +{ + ASIOBool result; + CALL_THISCALL_2( result, that_, 88, selector, opt ); + return result; +} + +ASIOError IASIOThiscallResolver::outputReady() +{ + ASIOBool result; + CALL_THISCALL_0( result, that_, 92 ); + return result; +} + + +// Implement our substitute ASIOInit() method +ASIOError IASIOThiscallResolver::ASIOInit(ASIODriverInfo *info) +{ + // To ensure that our instance's vptr is correctly constructed, even if + // ASIOInit is called prior to main(), we explicitly call its constructor + // (potentially over the top of an existing instance). Note that this is + // pretty ugly, and is only safe because IASIOThiscallResolver has no + // destructor and contains no objects with destructors. + new((void*)&instance) IASIOThiscallResolver( theAsioDriver ); + + // Interpose between ASIO client code and the real driver. + theAsioDriver = &instance; + + // Note that we never need to switch theAsioDriver back to point to the + // real driver because theAsioDriver is reset to zero in ASIOExit(). + + // Delegate to the real ASIOInit + return ::ASIOInit(info); +} + + +#endif /* !defined(_MSC_VER) */ + +#endif /* Win32 */ + diff --git a/pa_asio/iasiothiscallresolver.h b/pa_asio/iasiothiscallresolver.h new file mode 100644 index 0000000..2ecfed7 --- /dev/null +++ b/pa_asio/iasiothiscallresolver.h @@ -0,0 +1,197 @@ +// **************************************************************************** +// File: IASIOThiscallResolver.h +// Description: The IASIOThiscallResolver class implements the IASIO +// interface and acts as a proxy to the real IASIO interface by +// calling through its vptr table using the thiscall calling +// convention. To put it another way, we interpose +// IASIOThiscallResolver between ASIO SDK code and the driver. +// This is necessary because most non-Microsoft compilers don't +// implement the thiscall calling convention used by IASIO. +// +// iasiothiscallresolver.cpp contains the background of this +// problem plus a technical description of the vptr +// manipulations. +// +// In order to use this mechanism one simply has to add +// iasiothiscallresolver.cpp to the list of files to compile +// and #include +// +// Note that this #include must come after the other ASIO SDK +// #includes, for example: +// +// #include +// #include +// #include +// #include +// #include +// +// Actually the important thing is to #include +// after . We have +// incorporated a test to enforce this ordering. +// +// The code transparently takes care of the interposition by +// using macro substitution to intercept calls to ASIOInit() +// and ASIOExit(). We save the original ASIO global +// "theAsioDriver" in our "that" variable, and then set +// "theAsioDriver" to equal our IASIOThiscallResolver instance. +// +// Whilst this method of resolving the thiscall problem requires +// the addition of #include to client +// code it has the advantage that it does not break the terms +// of the ASIO licence by publishing it. We are NOT modifying +// any Steinberg code here, we are merely implementing the IASIO +// interface in the same way that we would need to do if we +// wished to provide an open source ASIO driver. +// +// For compilation with MinGW -lole32 needs to be added to the +// linker options. For BORLAND, linking with Import32.lib is +// sufficient. +// +// The dependencies are with: CoInitialize, CoUninitialize, +// CoCreateInstance, CLSIDFromString - used by asiolist.cpp +// and are required on Windows whether ThiscallResolver is used +// or not. +// +// Searching for the above strings in the root library path +// of your compiler should enable the correct libraries to be +// identified if they aren't immediately obvious. +// +// Note that the current implementation of IASIOThiscallResolver +// is not COM compliant - it does not correctly implement the +// IUnknown interface. Implementing it is not necessary because +// it is not called by parts of the ASIO SDK which call through +// theAsioDriver ptr. The IUnknown methods are implemented as +// assert(false) to ensure that the code fails if they are +// ever called. +// Restrictions: None. Public Domain & Open Source distribute freely +// You may use IASIOThiscallResolver commercially as well as +// privately. +// You the user assume the responsibility for the use of the +// files, binary or text, and there is no guarantee or warranty, +// expressed or implied, including but not limited to the +// implied warranties of merchantability and fitness for a +// particular purpose. You assume all responsibility and agree +// to hold no entity, copyright holder or distributors liable +// for any loss of data or inaccurate representations of data +// as a result of using IASIOThiscallResolver. +// Version: 1.4 Added separate macro CALL_THISCALL_1_DOUBLE from +// Andrew Baldwin, and volatile for whole gcc asm blocks, +// both for compatibility with newer gcc versions. Cleaned up +// Borland asm to use one less register. +// 1.3 Switched to including assert.h for better compatibility. +// Wrapped entire .h and .cpp contents with a check for +// _MSC_VER to provide better compatibility with MS compilers. +// Changed Singleton implementation to use static instance +// instead of freestore allocated instance. Removed ASIOExit +// macro as it is no longer needed. +// 1.2 Removed semicolons from ASIOInit and ASIOExit macros to +// allow them to be embedded in expressions (if statements). +// Cleaned up some comments. Removed combase.c dependency (it +// doesn't compile with BCB anyway) by stubbing IUnknown. +// 1.1 Incorporated comments from Ross Bencina including things +// such as changing name from ThiscallResolver to +// IASIOThiscallResolver, tidying up the constructor, fixing +// a bug in IASIOThiscallResolver::ASIOExit() and improving +// portability through the use of conditional compilation +// 1.0 Initial working version. +// Created: 6/09/2003 +// Authors: Fraser Adams +// Ross Bencina +// Rene G. Ceballos +// Martin Fay +// Antti Silvast +// Andrew Baldwin +// +// **************************************************************************** + + +#ifndef included_iasiothiscallresolver_h +#define included_iasiothiscallresolver_h + +// We only need IASIOThiscallResolver at all if we are on Win32. For other +// platforms we simply bypass the IASIOThiscallResolver definition to allow us +// to be safely #include'd whatever the platform to keep client code portable +#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) + + +// If microsoft compiler we can call IASIO directly so IASIOThiscallResolver +// is not used. +#if !defined(_MSC_VER) + + +// The following is in order to ensure that this header is only included after +// the other ASIO headers (except for the case of iasiothiscallresolver.cpp). +// We need to do this because IASIOThiscallResolver works by eclipsing the +// original definition of ASIOInit() with a macro (see below). +#if !defined(iasiothiscallresolver_sourcefile) + #if !defined(__ASIO_H) + #error iasiothiscallresolver.h must be included AFTER asio.h + #endif +#endif + +#include +#include /* From ASIO SDK */ + + +class IASIOThiscallResolver : public IASIO { +private: + IASIO* that_; // Points to the real IASIO + + static IASIOThiscallResolver instance; // Singleton instance + + // Constructors - declared private so construction is limited to + // our Singleton instance + IASIOThiscallResolver(); + IASIOThiscallResolver(IASIO* that); +public: + + // Methods from the IUnknown interface. We don't fully implement IUnknown + // because the ASIO SDK never calls these methods through theAsioDriver ptr. + // These methods are implemented as assert(false). + virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppv); + virtual ULONG STDMETHODCALLTYPE AddRef(); + virtual ULONG STDMETHODCALLTYPE Release(); + + // Methods from the IASIO interface, implemented as forwarning calls to that. + virtual ASIOBool init(void *sysHandle); + virtual void getDriverName(char *name); + virtual long getDriverVersion(); + virtual void getErrorMessage(char *string); + virtual ASIOError start(); + virtual ASIOError stop(); + virtual ASIOError getChannels(long *numInputChannels, long *numOutputChannels); + virtual ASIOError getLatencies(long *inputLatency, long *outputLatency); + virtual ASIOError getBufferSize(long *minSize, long *maxSize, long *preferredSize, long *granularity); + virtual ASIOError canSampleRate(ASIOSampleRate sampleRate); + virtual ASIOError getSampleRate(ASIOSampleRate *sampleRate); + virtual ASIOError setSampleRate(ASIOSampleRate sampleRate); + virtual ASIOError getClockSources(ASIOClockSource *clocks, long *numSources); + virtual ASIOError setClockSource(long reference); + virtual ASIOError getSamplePosition(ASIOSamples *sPos, ASIOTimeStamp *tStamp); + virtual ASIOError getChannelInfo(ASIOChannelInfo *info); + virtual ASIOError createBuffers(ASIOBufferInfo *bufferInfos, long numChannels, long bufferSize, ASIOCallbacks *callbacks); + virtual ASIOError disposeBuffers(); + virtual ASIOError controlPanel(); + virtual ASIOError future(long selector,void *opt); + virtual ASIOError outputReady(); + + // Class method, see ASIOInit() macro below. + static ASIOError ASIOInit(ASIODriverInfo *info); // Delegates to ::ASIOInit +}; + + +// Replace calls to ASIOInit with our interposing version. +// This macro enables us to perform thiscall resolution simply by #including +// after the asio #includes (this file _must_ be +// included _after_ the asio #includes) + +#define ASIOInit(name) IASIOThiscallResolver::ASIOInit((name)) + + +#endif /* !defined(_MSC_VER) */ + +#endif /* Win32 */ + +#endif /* included_iasiothiscallresolver_h */ + + diff --git a/pa_asio/pa_asio.cpp b/pa_asio/pa_asio.cpp index a2d7d82..6593e72 100644 --- a/pa_asio/pa_asio.cpp +++ b/pa_asio/pa_asio.cpp @@ -4,7 +4,7 @@ * * Author: Stephane Letz * Based on the Open Source API proposed by Ross Bencina - * Copyright (c) 2000-2001 Stephane Letz, Phil Burk + * Copyright (c) 2000-2002 Stephane Letz, Phil Burk, Ross Bencina * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files @@ -29,7 +29,7 @@ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ - + /* Modification History 08-03-01 First version : Stephane Letz @@ -39,16 +39,16 @@ 08-24-01 MAX_INT32_FP hack, another Uint8 fix : Stephane and Phil 08-27-01 Implementation of hostBufferSize < userBufferSize case, better management of the ouput buffer when the stream is stopped : Stephane Letz - 08-28-01 Check the stream pointer for null in bufferSwitchTimeInfo, correct bug in bufferSwitchTimeInfo when + 08-28-01 Check the stream pointer for null in bufferSwitchTimeInfo, correct bug in bufferSwitchTimeInfo when the stream is stopped : Stephane Letz 10-12-01 Correct the PaHost_CalcNumHostBuffers function: computes FramesPerHostBuffer to be the lowest that respect requested FramesPerUserBuffer and userBuffersPerHostBuffer : Stephane Letz 10-26-01 Management of hostBufferSize and userBufferSize of any size : Stephane Letz 10-27-01 Improve calculus of hostBufferSize to be multiple or divisor of userBufferSize if possible : Stephane and Phil 10-29-01 Change MAX_INT32_FP to (2147483520.0f) to prevent roundup to 0x80000000 : Phil Burk - 10-31-01 Clear the ouput buffer and user buffers in PaHost_StartOutput, correct bug in GetFirstMultiple : Stephane Letz - 11-06-01 Rename functions : Stephane Letz - 11-08-01 New Pa_ASIO_Adaptor_Init function to init Callback adpatation variables, cleanup of Pa_ASIO_Callback_Input: Stephane Letz + 10-31-01 Clear the ouput buffer and user buffers in PaHost_StartOutput, correct bug in GetFirstMultiple : Stephane Letz + 11-06-01 Rename functions : Stephane Letz + 11-08-01 New Pa_ASIO_Adaptor_Init function to init Callback adpatation variables, cleanup of Pa_ASIO_Callback_Input: Stephane Letz 11-29-01 Break apart device loading to debug random failure in Pa_ASIO_QueryDeviceInfo ; Phil Burk 01-03-02 Desallocate all resources in PaHost_Term for cases where Pa_CloseStream is not called properly : Stephane Letz 02-01-02 Cleanup, test of multiple-stream opening : Stephane Letz @@ -57,2942 +57,2902 @@ 12-04-02 Add Mac includes for and : Phil Burk 13-04-02 Removes another compiler warning : Stephane Letz 30-04-02 Pa_ASIO_QueryDeviceInfo bug correction, memory allocation checking, better error handling : D Viens, P Burk, S Letz - - TO DO : - - - Check Pa_StopSteam and Pa_AbortStream - - Optimization for Input only or Ouput only (really necessary ??) + 12-06-02 Rehashed into new multi-api infrastructure, added support for all ASIO sample formats : Ross Bencina + 18-06-02 Added pa_asio.h, PaAsio_GetAvailableLatencyValues() : Ross B. + 21-06-02 Added SelectHostBufferSize() which selects host buffer size based on user latency parameters : Ross Bencina + ** NOTE maintanance history is now stored in CVS ** */ +/** @file -#include -#include -#include + Note that specific support for paInputUnderflow, paOutputOverflow and + paNeverDropInput is not necessary or possible with this driver due to the + synchronous full duplex double-buffered architecture of ASIO. -#include "portaudio.h" -#include "pa_host.h" -#include "pa_trace.h" + @todo check that CoInitialize()/CoUninitialize() are always correctly + paired, even in error cases. -#include "asiosys.h" -#include "asio.h" -#include "asiodrivers.h" + @todo implement host api specific extension to set i/o buffer sizes in frames + @todo implement ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable -#if MAC -#include -#include -#include -#else -#include -#include -#include -#endif + @todo implement IsFormatSupported -enum { - // number of input and outputs supported by the host application - // you can change these to higher or lower values - kMaxInputChannels = 32, - kMaxOutputChannels = 32 -}; + @todo work out how to implement stream stoppage from callback and + implement IsStreamActive properly. Stream stoppage could be implemented + using a high-priority thread blocked on an Event which is signalled + by the callback. Or, we could just call ASIO stop from the callback + and see what happens. -/* ASIO specific device information. */ -typedef struct internalPortAudioDevice -{ - PaDeviceInfo pad_Info; -} internalPortAudioDevice; + @todo rigorously check asio return codes and convert to pa error codes + @todo Different channels of a multichannel stream can have different sample + formats, but we assume that all are the same as the first channel for now. + Fixing this will require the block processor to maintain per-channel + conversion functions - could get nasty. -/* ASIO driver internal data storage */ -typedef struct PaHostSoundControl -{ - // ASIOInit() - ASIODriverInfo pahsc_driverInfo; + @todo investigate whether the asio processNow flag needs to be honoured - // ASIOGetChannels() - int32 pahsc_NumInputChannels; - int32 pahsc_NumOutputChannels; + @todo handle asioMessages() callbacks in a useful way, or at least document + what cases we don't handle. - // ASIOGetBufferSize() - sizes in frames per buffer - int32 pahsc_minSize; - int32 pahsc_maxSize; - int32 pahsc_preferredSize; - int32 pahsc_granularity; + @todo miscellaneous other FIXMEs - // ASIOGetSampleRate() - ASIOSampleRate pahsc_sampleRate; + @todo provide an asio-specific method for setting the systems specific + value (aka main window handle) - check that this matches the value + passed to PaAsio_ShowControlPanel, or remove it entirely from + PaAsio_ShowControlPanel. - this would allow PaAsio_ShowControlPanel + to be called for the currently open stream (at present all streams + must be closed). +*/ - // ASIOOutputReady() - bool pahsc_postOutput; - // ASIOGetLatencies () - int32 pahsc_inputLatency; - int32 pahsc_outputLatency; - // ASIOCreateBuffers () - ASIOBufferInfo bufferInfos[kMaxInputChannels + kMaxOutputChannels]; // buffer info's +#include +#include +#include +//#include - // ASIOGetChannelInfo() - ASIOChannelInfo pahsc_channelInfos[kMaxInputChannels + kMaxOutputChannels]; // channel info's - // The above two arrays share the same indexing, as the data in them are linked together +#include +#include - // Information from ASIOGetSamplePosition() - // data is converted to double floats for easier use, however 64 bit integer can be used, too - double nanoSeconds; - double samples; - double tcSamples; // time code samples +#include "portaudio.h" +#include "pa_asio.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" - // bufferSwitchTimeInfo() - ASIOTime tInfo; // time info state - unsigned long sysRefTime; // system reference time, when bufferSwitch() was called +#include "asiosys.h" +#include "asio.h" +#include "asiodrivers.h" +#include "iasiothiscallresolver.h" - // Signal the end of processing in this example - bool stopped; - - ASIOCallbacks pahsc_asioCallbacks; - - - int32 pahsc_userInputBufferFrameOffset; // Position in Input user buffer - int32 pahsc_userOutputBufferFrameOffset; // Position in Output user buffer - int32 pahsc_hostOutputBufferFrameOffset; // Position in Output ASIO buffer - - int32 past_FramesPerHostBuffer; // Number of frames in ASIO buffer - - int32 pahsc_InputBufferOffset; // Number of null frames for input buffer alignement - int32 pahsc_OutputBufferOffset; // Number of null frames for ouput buffer alignement - +/* #if MAC - UInt64 pahsc_EntryCount; - UInt64 pahsc_LastExitCount; -#elif WINDOWS - LARGE_INTEGER pahsc_EntryCount; - LARGE_INTEGER pahsc_LastExitCount; -#endif - - PaTimestamp pahsc_NumFramesDone; - - internalPortAudioStream *past; - -} PaHostSoundControl; - +#include +#include +#include +#else +*/ +/* +#include +#include +#include +*/ +/* +#endif +*/ -//---------------------------------------------------------- -#define PRINT(x) { printf x; fflush(stdout); } -#define ERR_RPT(x) PRINT(x) +/* external references */ +extern AsioDrivers* asioDrivers ; +bool loadAsioDriver(char *name); -#define DBUG(x) /* PRINT(x) */ -#define DBUGX(x) /* PRINT(x) /**/ /* We are trying to be compatible with CARBON but this has not been thoroughly tested. */ +/* not tested at all since new code was introduced. */ #define CARBON_COMPATIBLE (0) -#define PA_MAX_DEVICE_INFO (32) -#define MIN_INT8 (-0x80) -#define MAX_INT8 (0x7F) -#define MIN_INT8_FP ((float)-0x80) -#define MAX_INT8_FP ((float)0x7F) -#define MIN_INT16_FP ((float)-0x8000) -#define MAX_INT16_FP ((float)0x7FFF) -#define MIN_INT16 (-0x8000) -#define MAX_INT16 (0x7FFF) +/* prototypes for functions declared in this file */ + +extern "C" PaError PaAsio_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex ); +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 ); + +/* our ASIO callback functions */ -#define MAX_INT32_FP (2147483520.0f) /* 0x0x7FFFFF80 - seems safe */ - -/************************************************************************************/ -/****************** Data ************************************************************/ -/************************************************************************************/ -static int sNumDevices = 0; -static internalPortAudioDevice sDevices[PA_MAX_DEVICE_INFO] = { 0 }; -static int32 sPaHostError = 0; -static int sDefaultOutputDeviceID = 0; -static int sDefaultInputDeviceID = 0; - -PaHostSoundControl asioDriverInfo = {0}; - -#ifdef MAC -static bool swap = true; -#elif WINDOWS -static bool swap = false; -#endif - -// Prototypes static void bufferSwitch(long index, ASIOBool processNow); static ASIOTime *bufferSwitchTimeInfo(ASIOTime *timeInfo, long index, ASIOBool processNow); static void sampleRateChanged(ASIOSampleRate sRate); static long asioMessages(long selector, long value, void* message, double* opt); -static void Pa_StartUsageCalculation( internalPortAudioStream *past ); -static void Pa_EndUsageCalculation( internalPortAudioStream *past ); - -static void Pa_ASIO_Convert_Inter_Input( - ASIOBufferInfo* nativeBuffer, - void* inputBuffer, - long NumInputChannels, - long NumOuputChannels, - long framePerBuffer, - long hostFrameOffset, - long userFrameOffset, - ASIOSampleType nativeFormat, - PaSampleFormat paFormat, - PaStreamFlags flags, - long index); - -static void Pa_ASIO_Convert_Inter_Output( - ASIOBufferInfo* nativeBuffer, - void* outputBuffer, - long NumInputChannels, - long NumOuputChannels, - long framePerBuffer, - long hostFrameOffset, - long userFrameOffset, - ASIOSampleType nativeFormat, - PaSampleFormat paFormat, - PaStreamFlags flags, - long index); - -static void Pa_ASIO_Clear_Output(ASIOBufferInfo* nativeBuffer, - ASIOSampleType nativeFormat, - long NumInputChannels, - long NumOuputChannels, - long index, - long hostFrameOffset, - long frames); - -static void Pa_ASIO_Callback_Input(long index); -static void Pa_ASIO_Callback_Output(long index, long framePerBuffer); -static void Pa_ASIO_Callback_End(); -static void Pa_ASIO_Clear_User_Buffers(); - -// Some external references -extern AsioDrivers* asioDrivers ; -bool loadAsioDriver(char *name); -unsigned long get_sys_reference_time(); - -/************************************************************************************/ -/****************** Macro ************************************************************/ -/************************************************************************************/ +static ASIOCallbacks asioCallbacks_ = + { bufferSwitch, sampleRateChanged, asioMessages, bufferSwitchTimeInfo }; -#define SwapLong(v) ((((v)>>24)&0xFF)|(((v)>>8)&0xFF00)|(((v)&0xFF00)<<8)|(((v)&0xFF)<<24)) ; -#define SwapShort(v) ((((v)>>8)&0xFF)|(((v)&0xFF)<<8)) ; -#define ClipShort(v) (((v)MAX_INT16)?MAX_INT16:(v))) -#define ClipChar(v) (((v)MAX_INT8)?MAX_INT8:(v))) -#define ClipFloat(v) (((v)<-1.0f)?-1.0f:(((v)>1.0f)?1.0f:(v))) - -#ifndef min -#define min(a,b) ((a)<(b)?(a):(b)) -#endif - -#ifndef max -#define max(a,b) ((a)>=(b)?(a):(b)) -#endif +#define PA_ASIO_SET_LAST_HOST_ERROR( errorCode, errorText ) \ + PaUtil_SetLastHostErrorInfo( paASIO, errorCode, errorText ) -static bool Pa_ASIO_loadAsioDriver(char *name) +static void PaAsio_SetLastSystemError( DWORD errorCode ) { - #ifdef WINDOWS - CoInitialize(0); - #endif - return loadAsioDriver(name); + LPVOID lpMsgBuf; + FormatMessage( + FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, + NULL, + errorCode, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + (LPTSTR) &lpMsgBuf, + 0, + NULL + ); + PaUtil_SetLastHostErrorInfo( paASIO, errorCode, (const char*)lpMsgBuf ); + LocalFree( lpMsgBuf ); } - +#define PA_ASIO_SET_LAST_SYSTEM_ERROR( errorCode ) \ + PaAsio_SetLastSystemError( errorCode ) -// Utilities for alignement buffer size computation -static int PGCD (int a, int b) {return (b == 0) ? a : PGCD (b,a%b);} -static int PPCM (int a, int b) {return (a*b) / PGCD (a,b);} -// Takes the size of host buffer and user buffer : returns the number of frames needed for buffer alignement -static int Pa_ASIO_CalcFrameShift (int M, int N) +static const char* PaAsio_GetAsioErrorText( ASIOError asioError ) { - int res = 0; - for (int i = M; i < PPCM (M,N) ; i+=M) { res = max (res, i%N); } - return res; -} + const char *result; -// We have the following relation : -// Pa_ASIO_CalcFrameShift (M,N) + M = Pa_ASIO_CalcFrameShift (N,M) + N - -/* ASIO sample type to PortAudio sample type conversion */ -static PaSampleFormat Pa_ASIO_Convert_SampleFormat(ASIOSampleType type) -{ - switch (type) { - - case ASIOSTInt16MSB: - case ASIOSTInt16LSB: - case ASIOSTInt32MSB16: - case ASIOSTInt32LSB16: - return paInt16; - - case ASIOSTFloat32MSB: - case ASIOSTFloat32LSB: - case ASIOSTFloat64MSB: - case ASIOSTFloat64LSB: - return paFloat32; - - case ASIOSTInt32MSB: - case ASIOSTInt32LSB: - case ASIOSTInt32MSB18: - case ASIOSTInt32MSB20: - case ASIOSTInt32MSB24: - case ASIOSTInt32LSB18: - case ASIOSTInt32LSB20: - case ASIOSTInt32LSB24: - return paInt32; - - case ASIOSTInt24MSB: - case ASIOSTInt24LSB: - return paInt24; - - default: - return paCustomFormat; - } + switch( asioError ){ + case ASE_OK: + case ASE_SUCCESS: result = "Success"; break; + case ASE_NotPresent: result = "Hardware input or output is not present or available"; break; + case ASE_HWMalfunction: result = "Hardware is malfunctioning"; break; + case ASE_InvalidParameter: result = "Input parameter invalid"; break; + case ASE_InvalidMode: result = "Hardware is in a bad mode or used in a bad mode"; break; + case ASE_SPNotAdvancing: result = "Hardware is not running when sample position is inquired"; break; + case ASE_NoClock: result = "Sample clock or rate cannot be determined or is not present"; break; + case ASE_NoMemory: result = "Not enough memory for completing the request"; break; + default: result = "Unknown ASIO error"; break; + } + + return result; } -/* Allocate ASIO buffers, initialise channels */ -static ASIOError Pa_ASIO_CreateBuffers (PaHostSoundControl *asioDriverInfo, long InputChannels, - long OutputChannels, long framesPerBuffer) -{ - ASIOError err; - int i; - - ASIOBufferInfo *info = asioDriverInfo->bufferInfos; - - // Check parameters - if ((InputChannels > kMaxInputChannels) || (OutputChannels > kMaxInputChannels)) return ASE_InvalidParameter; - - for(i = 0; i < InputChannels; i++, info++){ - info->isInput = ASIOTrue; - info->channelNum = i; - info->buffers[0] = info->buffers[1] = 0; - } - - for(i = 0; i < OutputChannels; i++, info++){ - info->isInput = ASIOFalse; - info->channelNum = i; - info->buffers[0] = info->buffers[1] = 0; - } - - // Set up the asioCallback structure and create the ASIO data buffer - asioDriverInfo->pahsc_asioCallbacks.bufferSwitch = &bufferSwitch; - asioDriverInfo->pahsc_asioCallbacks.sampleRateDidChange = &sampleRateChanged; - asioDriverInfo->pahsc_asioCallbacks.asioMessage = &asioMessages; - asioDriverInfo->pahsc_asioCallbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfo; - - DBUG(("PortAudio : ASIOCreateBuffers with size = %ld \n", framesPerBuffer)); - - err = ASIOCreateBuffers( asioDriverInfo->bufferInfos, InputChannels+OutputChannels, - framesPerBuffer, &asioDriverInfo->pahsc_asioCallbacks); - if (err != ASE_OK) return err; - - // Initialise buffers - for (i = 0; i < InputChannels + OutputChannels; i++) - { - asioDriverInfo->pahsc_channelInfos[i].channel = asioDriverInfo->bufferInfos[i].channelNum; - asioDriverInfo->pahsc_channelInfos[i].isInput = asioDriverInfo->bufferInfos[i].isInput; - err = ASIOGetChannelInfo(&asioDriverInfo->pahsc_channelInfos[i]); - if (err != ASE_OK) break; - } - err = ASIOGetLatencies(&asioDriverInfo->pahsc_inputLatency, &asioDriverInfo->pahsc_outputLatency); - - DBUG(("PortAudio : InputLatency = %ld latency = %ld msec \n", - asioDriverInfo->pahsc_inputLatency, - (long)((asioDriverInfo->pahsc_inputLatency*1000)/ asioDriverInfo->past->past_SampleRate))); - DBUG(("PortAudio : OuputLatency = %ld latency = %ld msec \n", - asioDriverInfo->pahsc_outputLatency, - (long)((asioDriverInfo->pahsc_outputLatency*1000)/ asioDriverInfo->past->past_SampleRate))); - - return err; -} +#define PA_ASIO_SET_LAST_ASIO_ERROR( asioError ) \ + PaUtil_SetLastHostErrorInfo( paASIO, asioError, PaAsio_GetAsioErrorText( asioError ) ) -/* - Query ASIO driver info : - - First we get all available ASIO drivers located in the ASIO folder, - then try to load each one. For each loaded driver, get all needed informations. -*/ -static PaError Pa_ASIO_QueryDeviceInfo( internalPortAudioDevice * ipad ) -{ -#define NUM_STANDARDSAMPLINGRATES 3 /* 11.025, 22.05, 44.1 */ -#define NUM_CUSTOMSAMPLINGRATES 9 /* must be the same number of elements as in the array below */ -#define MAX_NUMSAMPLINGRATES (NUM_STANDARDSAMPLINGRATES+NUM_CUSTOMSAMPLINGRATES) - ASIOSampleRate possibleSampleRates[] - = {8000.0, 9600.0, 11025.0, 12000.0, 16000.0, 22050.0, 24000.0, 32000.0, 44100.0, 48000.0, 88200.0, 96000.0}; - - ASIOChannelInfo channelInfos; - long InputChannels,OutputChannels; - double *sampleRates; - char* names[PA_MAX_DEVICE_INFO] ; - PaDeviceInfo *dev; - int i; - int numDrivers; - ASIOError asioError; - - /* Allocate names */ - for (i = 0 ; i < PA_MAX_DEVICE_INFO ; i++) { - names[i] = (char*)PaHost_AllocateFastMemory(32); - /* check memory */ - if(!names[i]) return paInsufficientMemory; - } - - /* MUST BE CHECKED : to force fragments loading on Mac */ - Pa_ASIO_loadAsioDriver("dummy"); - - /* Get names of all available ASIO drivers */ - asioDrivers->getDriverNames(names,PA_MAX_DEVICE_INFO); - - /* Check all available ASIO drivers */ +// Atomic increment and decrement operations #if MAC - numDrivers = asioDrivers->getNumFragments(); + /* need to be implemented on Mac */ + inline long PaAsio_AtomicIncrement(volatile long* v) {return ++(*const_cast(v));} + inline long PaAsio_AtomicDecrement(volatile long* v) {return --(*const_cast(v));} #elif WINDOWS - numDrivers = asioDrivers->asioGetNumDev(); + inline long PaAsio_AtomicIncrement(volatile long* v) {return InterlockedIncrement(const_cast(v));} + inline long PaAsio_AtomicDecrement(volatile long* v) {return InterlockedDecrement(const_cast(v));} #endif - DBUG(("PaASIO_QueryDeviceInfo: numDrivers = %d\n", numDrivers )); - for (int driver = 0 ; driver < numDrivers ; driver++) - { - #if WINDOWS - asioDriverInfo.pahsc_driverInfo.asioVersion = 2; // FIXME - is this right? PLB - asioDriverInfo.pahsc_driverInfo.sysRef = GetDesktopWindow(); // FIXME - is this right? PLB - #endif - - /* If the driver can be loaded : */ - if ( !Pa_ASIO_loadAsioDriver(names[driver]) ) - { - DBUG(("PaASIO_QueryDeviceInfo could not loadAsioDriver %s\n", names[driver])); - } - else if( (asioError = ASIOInit(&asioDriverInfo.pahsc_driverInfo)) != ASE_OK ) - { - DBUG(("PaASIO_QueryDeviceInfo: ASIOInit returned %d for %s\n", asioError, names[driver])); - } - else if( (ASIOGetChannels(&InputChannels, &OutputChannels) != ASE_OK)) - { - DBUG(("PaASIO_QueryDeviceInfo could not ASIOGetChannels for %s\n", names[driver])); - } - else - { - /* Gets the name */ - dev = &(ipad[sNumDevices].pad_Info); - dev->name = names[driver]; - names[driver] = 0; - - /* Gets Input and Output channels number */ - dev->maxInputChannels = InputChannels; - dev->maxOutputChannels = OutputChannels; - - DBUG(("PaASIO_QueryDeviceInfo: InputChannels = %d\n", InputChannels )); - DBUG(("PaASIO_QueryDeviceInfo: OutputChannels = %d\n", OutputChannels )); - - /* Make room in case device supports all rates. */ - sampleRates = (double*)PaHost_AllocateFastMemory(MAX_NUMSAMPLINGRATES * sizeof(double)); - /* check memory */ - if (!sampleRates) { - ASIOExit(); - return paInsufficientMemory; - } - dev->sampleRates = sampleRates; - dev->numSampleRates = 0; - - /* Loop through the possible sampling rates and check each to see if the device supports it. */ - for (int index = 0; index < MAX_NUMSAMPLINGRATES; index++) { - if (ASIOCanSampleRate(possibleSampleRates[index]) != ASE_NoClock) { - DBUG(("PortAudio : possible sample rate = %d\n", (long)possibleSampleRates[index])); - dev->numSampleRates += 1; - *sampleRates = possibleSampleRates[index]; - sampleRates++; - } - } - - /* We assume that all channels have the same SampleType, so check the first */ - channelInfos.channel = 0; - channelInfos.isInput = 1; - ASIOGetChannelInfo(&channelInfos); - - dev->nativeSampleFormats = Pa_ASIO_Convert_SampleFormat(channelInfos.type); - - /* unload the driver */ - ASIOExit(); - sNumDevices++; - } - } - - /* free only unused names */ - for (i = 0 ; i < PA_MAX_DEVICE_INFO ; i++) if (names[i]) PaHost_FreeFastMemory(names[i],32); - - return paNoError; -} -//---------------------------------------------------------------------------------- -// TAKEN FROM THE ASIO SDK: -static void sampleRateChanged(ASIOSampleRate sRate) +typedef struct PaAsioDriverInfo { - // do whatever you need to do if the sample rate changed - // usually this only happens during external sync. - // Audio processing is not stopped by the driver, actual sample rate - // might not have even changed, maybe only the sample rate status of an - // AES/EBU or S/PDIF digital input at the audio device. - // You might have to update time/sample related conversion routines, etc. + ASIODriverInfo asioDriverInfo; + long inputChannelCount, outputChannelCount; + long bufferMinSize, bufferMaxSize, bufferPreferredSize, bufferGranularity; + bool postOutput; } +PaAsioDriverInfo; + + +/* PaAsioHostApiRepresentation - host api datastructure specific to this implementation */ -//---------------------------------------------------------------------------------- -// TAKEN FROM THE ASIO SDK: -long asioMessages(long selector, long value, void* message, double* opt) +typedef struct { - // currently the parameters "value", "message" and "opt" are not used. - long ret = 0; - switch(selector) - { - case kAsioSelectorSupported: - if(value == kAsioResetRequest - || value == kAsioEngineVersion - || value == kAsioResyncRequest - || value == kAsioLatenciesChanged - // the following three were added for ASIO 2.0, you don't necessarily have to support them - || value == kAsioSupportsTimeInfo - || value == kAsioSupportsTimeCode - || value == kAsioSupportsInputMonitor) - ret = 1L; - break; - - case kAsioBufferSizeChange: - //printf("kAsioBufferSizeChange \n"); - break; - - case kAsioResetRequest: - // defer the task and perform the reset of the driver during the next "safe" situation - // You cannot reset the driver right now, as this code is called from the driver. - // Reset the driver is done by completely destruct is. I.e. ASIOStop(), ASIODisposeBuffers(), Destruction - // Afterwards you initialize the driver again. - asioDriverInfo.stopped; // In this sample the processing will just stop - ret = 1L; - break; - case kAsioResyncRequest: - // This informs the application, that the driver encountered some non fatal data loss. - // It is used for synchronization purposes of different media. - // Added mainly to work around the Win16Mutex problems in Windows 95/98 with the - // Windows Multimedia system, which could loose data because the Mutex was hold too long - // by another thread. - // However a driver can issue it in other situations, too. - ret = 1L; - break; - case kAsioLatenciesChanged: - // This will inform the host application that the drivers were latencies changed. - // Beware, it this does not mean that the buffer sizes have changed! - // You might need to update internal delay data. - ret = 1L; - //printf("kAsioLatenciesChanged \n"); - break; - case kAsioEngineVersion: - // return the supported ASIO version of the host application - // If a host applications does not implement this selector, ASIO 1.0 is assumed - // by the driver - ret = 2L; - break; - case kAsioSupportsTimeInfo: - // informs the driver wether the asioCallbacks.bufferSwitchTimeInfo() callback - // is supported. - // For compatibility with ASIO 1.0 drivers the host application should always support - // the "old" bufferSwitch method, too. - ret = 1; - break; - case kAsioSupportsTimeCode: - // informs the driver wether application is interested in time code info. - // If an application does not need to know about time code, the driver has less work - // to do. - ret = 0; - break; - } - return ret; -} + PaUtilHostApiRepresentation inheritedHostApiRep; + PaUtilStreamInterface callbackStreamInterface; + PaUtilStreamInterface blockingStreamInterface; + PaUtilAllocationGroup *allocations; -//---------------------------------------------------------------------------------- -// conversion from 64 bit ASIOSample/ASIOTimeStamp to double float -#if NATIVE_INT64 - #define ASIO64toDouble(a) (a) -#else - const double twoRaisedTo32 = 4294967296.; - #define ASIO64toDouble(a) ((a).lo + (a).hi * twoRaisedTo32) -#endif + void *systemSpecific; + + /* the ASIO C API only allows one ASIO driver to be open at a time, + so we keep track of whether we have the driver open here, and + use this information to return errors from OpenStream if the + driver is already open. + openAsioDeviceIndex will be PaNoDevice if there is no device open + and a valid pa_asio (not global) device index otherwise. -static ASIOTime *bufferSwitchTimeInfo(ASIOTime *timeInfo, long index, ASIOBool processNow) -{ - // the actual processing callback. - // Beware that this is normally in a seperate thread, hence be sure that you take care - // about thread synchronization. This is omitted here for simplicity. - - // static processedSamples = 0; - int result = 0; - - // store the timeInfo for later use - asioDriverInfo.tInfo = *timeInfo; + openAsioDriverInfo is populated with the driver info for the + currently open device (if any) + */ + PaDeviceIndex openAsioDeviceIndex; + PaAsioDriverInfo openAsioDriverInfo; +} +PaAsioHostApiRepresentation; - // get the time stamp of the buffer, not necessary if no - // synchronization to other media is required - - if (timeInfo->timeInfo.flags & kSystemTimeValid) - asioDriverInfo.nanoSeconds = ASIO64toDouble(timeInfo->timeInfo.systemTime); - else - asioDriverInfo.nanoSeconds = 0; - if (timeInfo->timeInfo.flags & kSamplePositionValid) - asioDriverInfo.samples = ASIO64toDouble(timeInfo->timeInfo.samplePosition); - else - asioDriverInfo.samples = 0; +/* + Retrieve driver names from ASIO, returned in a char** + allocated in . +*/ +static char **GetAsioDriverNames( PaUtilAllocationGroup *group, long driverCount ) +{ + char **result = 0; + int i; - if (timeInfo->timeCode.flags & kTcValid) - asioDriverInfo.tcSamples = ASIO64toDouble(timeInfo->timeCode.timeCodeSamples); - else - asioDriverInfo.tcSamples = 0; + result =(char**)PaUtil_GroupAllocateMemory( + group, sizeof(char*) * driverCount ); + if( !result ) + goto error; - // get the system reference time - asioDriverInfo.sysRefTime = get_sys_reference_time(); + result[0] = (char*)PaUtil_GroupAllocateMemory( + group, 32 * driverCount ); + if( !result[0] ) + goto error; -#if 0 - // a few debug messages for the Windows device driver developer - // tells you the time when driver got its interrupt and the delay until the app receives - // the event notification. - static double last_samples = 0; - char tmp[128]; - sprintf (tmp, "diff: %d / %d ms / %d ms / %d samples \n", asioDriverInfo.sysRefTime - (long)(asioDriverInfo.nanoSeconds / 1000000.0), asioDriverInfo.sysRefTime, (long)(asioDriverInfo.nanoSeconds / 1000000.0), (long)(asioDriverInfo.samples - last_samples)); - OutputDebugString (tmp); - last_samples = asioDriverInfo.samples; -#endif + for( i=0; igetDriverNames( result, driverCount ); - // Keep sample position - asioDriverInfo.pahsc_NumFramesDone = timeInfo->timeInfo.samplePosition.lo; +error: + return result; +} + + +static PaSampleFormat AsioSampleTypeToPaNativeSampleFormat(ASIOSampleType type) +{ + switch (type) { + case ASIOSTInt16MSB: + case ASIOSTInt16LSB: + return paInt16; + + case ASIOSTFloat32MSB: + case ASIOSTFloat32LSB: + case ASIOSTFloat64MSB: + case ASIOSTFloat64LSB: + return paFloat32; + + case ASIOSTInt32MSB: + case ASIOSTInt32LSB: + case ASIOSTInt32MSB16: + case ASIOSTInt32LSB16: + case ASIOSTInt32MSB18: + case ASIOSTInt32MSB20: + case ASIOSTInt32MSB24: + case ASIOSTInt32LSB18: + case ASIOSTInt32LSB20: + case ASIOSTInt32LSB24: + return paInt32; + + case ASIOSTInt24MSB: + case ASIOSTInt24LSB: + return paInt24; + + default: + return paCustomFormat; + } +} + +void AsioSampleTypeLOG(ASIOSampleType type) +{ + switch (type) { + case ASIOSTInt16MSB: PA_DEBUG(("ASIOSTInt16MSB\n")); break; + case ASIOSTInt16LSB: PA_DEBUG(("ASIOSTInt16LSB\n")); break; + case ASIOSTFloat32MSB:PA_DEBUG(("ASIOSTFloat32MSB\n"));break; + case ASIOSTFloat32LSB:PA_DEBUG(("ASIOSTFloat32LSB\n"));break; + case ASIOSTFloat64MSB:PA_DEBUG(("ASIOSTFloat64MSB\n"));break; + case ASIOSTFloat64LSB:PA_DEBUG(("ASIOSTFloat64LSB\n"));break; + case ASIOSTInt32MSB: PA_DEBUG(("ASIOSTInt32MSB\n")); break; + case ASIOSTInt32LSB: PA_DEBUG(("ASIOSTInt32LSB\n")); break; + case ASIOSTInt32MSB16:PA_DEBUG(("ASIOSTInt32MSB16\n"));break; + case ASIOSTInt32LSB16:PA_DEBUG(("ASIOSTInt32LSB16\n"));break; + case ASIOSTInt32MSB18:PA_DEBUG(("ASIOSTInt32MSB18\n"));break; + case ASIOSTInt32MSB20:PA_DEBUG(("ASIOSTInt32MSB20\n"));break; + case ASIOSTInt32MSB24:PA_DEBUG(("ASIOSTInt32MSB24\n"));break; + case ASIOSTInt32LSB18:PA_DEBUG(("ASIOSTInt32LSB18\n"));break; + case ASIOSTInt32LSB20:PA_DEBUG(("ASIOSTInt32LSB20\n"));break; + case ASIOSTInt32LSB24:PA_DEBUG(("ASIOSTInt32LSB24\n"));break; + case ASIOSTInt24MSB: PA_DEBUG(("ASIOSTInt24MSB\n")); break; + case ASIOSTInt24LSB: PA_DEBUG(("ASIOSTInt24LSB\n")); break; + default: PA_DEBUG(("Custom Format%d\n",type));break; - /* Has a user callback returned '1' to indicate finished at the last ASIO callback? */ - if( asioDriverInfo.past->past_StopSoon ) { - - Pa_ASIO_Clear_Output(asioDriverInfo.bufferInfos, - asioDriverInfo.pahsc_channelInfos[0].type, - asioDriverInfo.pahsc_NumInputChannels , - asioDriverInfo.pahsc_NumOutputChannels, - index, - 0, - asioDriverInfo.past_FramesPerHostBuffer); - - asioDriverInfo.past->past_IsActive = 0; - - // Finally if the driver supports the ASIOOutputReady() optimization, do it here, all data are in place - if (asioDriverInfo.pahsc_postOutput) ASIOOutputReady(); - - }else { - - /* CPU usage */ - Pa_StartUsageCalculation(asioDriverInfo.past); - - Pa_ASIO_Callback_Input(index); - - // Finally if the driver supports the ASIOOutputReady() optimization, do it here, all data are in place - if (asioDriverInfo.pahsc_postOutput) ASIOOutputReady(); - - Pa_ASIO_Callback_End(); - - /* CPU usage */ - Pa_EndUsageCalculation(asioDriverInfo.past); - } - - return 0L; + } } +static int BytesPerAsioSample( ASIOSampleType sampleType ) +{ + switch (sampleType) { + case ASIOSTInt16MSB: + case ASIOSTInt16LSB: + return 2; -//---------------------------------------------------------------------------------- -void bufferSwitch(long index, ASIOBool processNow) -{ - // the actual processing callback. - // Beware that this is normally in a seperate thread, hence be sure that you take care - // about thread synchronization. This is omitted here for simplicity. + case ASIOSTFloat64MSB: + case ASIOSTFloat64LSB: + return 8; - // as this is a "back door" into the bufferSwitchTimeInfo a timeInfo needs to be created - // though it will only set the timeInfo.samplePosition and timeInfo.systemTime fields and the according flags - - ASIOTime timeInfo; - memset (&timeInfo, 0, sizeof (timeInfo)); + case ASIOSTFloat32MSB: + case ASIOSTFloat32LSB: + case ASIOSTInt32MSB: + case ASIOSTInt32LSB: + case ASIOSTInt32MSB16: + case ASIOSTInt32LSB16: + case ASIOSTInt32MSB18: + case ASIOSTInt32MSB20: + case ASIOSTInt32MSB24: + case ASIOSTInt32LSB18: + case ASIOSTInt32LSB20: + case ASIOSTInt32LSB24: + return 4; - // get the time stamp of the buffer, not necessary if no - // synchronization to other media is required - if(ASIOGetSamplePosition(&timeInfo.timeInfo.samplePosition, &timeInfo.timeInfo.systemTime) == ASE_OK) - timeInfo.timeInfo.flags = kSystemTimeValid | kSamplePositionValid; - - // Call the real callback - bufferSwitchTimeInfo (&timeInfo, index, processNow); -} + case ASIOSTInt24MSB: + case ASIOSTInt24LSB: + return 3; -//---------------------------------------------------------------------------------- -unsigned long get_sys_reference_time() -{ - // get the system reference time - #if WINDOWS - return timeGetTime(); - #elif MAC - static const double twoRaisedTo32 = 4294967296.; - UnsignedWide ys; - Microseconds(&ys); - double r = ((double)ys.hi * twoRaisedTo32 + (double)ys.lo); - return (unsigned long)(r / 1000.); - #endif + default: + return 0; + } } -/************************************************************* -** Calculate 2 LSB dither signal with a triangular distribution. -** Ranged properly for adding to a 32 bit integer prior to >>15. -*/ -#define DITHER_BITS (15) -#define DITHER_SCALE (1.0f / ((1<>(32-DITHER_BITS)) + (((long)randSeed2)>>(32-DITHER_BITS)); - /* High pass filter to reduce audibility. */ - highPass = current - previous; - previous = current; - return highPass; -} + unsigned short *p = (unsigned short*)buffer; + unsigned short temp; + (void) shift; /* unused parameter */ -// TO BE COMPLETED WITH ALL SUPPORTED PA SAMPLE TYPES + while( count-- ) + { + temp = *p; + *p++ = (unsigned short)((temp<<8) | (temp>>8)); + } +} -//------------------------------------------------------------------------------------------------------------------------------------------------------- -static void Input_Int16_Float32 (ASIOBufferInfo* nativeBuffer, float *inBufPtr, int framePerBuffer, int NumInputChannels, int index, int hostFrameOffset,int userFrameOffset, bool swap) +static void Swap24( void *buffer, long shift, long count ) { - long temp; - int i,j; - - for( j=0; j>24) | ((x>>8)&0xFF00) | ((x<<8)&0xFF0000) | (x<<24)); + +static void Swap32( void *buffer, long shift, long count ) { - long temp; - int i,j; - - for( j=0; j> shift; + *p++ = PA_SWAP32_( temp); + } } -//------------------------------------------------------------------------------------------------------------------------------------------------------- -static void Input_Int32_Int32 (ASIOBufferInfo* nativeBuffer, long *inBufPtr, int framePerBuffer, int NumInputChannels, int index, int hostFrameOffset,int userFrameOffset,bool swap) +static void ShiftLeft32( void *buffer, long shift, long count ) { - long temp; - int i,j; - - for( j=0; j> shift; + } } +#define PA_SWAP_( x, y ) temp=x; x = y; y = temp; -//------------------------------------------------------------------------------------------------------------------------------------------------------- -static void Input_Int16_Int16 (ASIOBufferInfo* nativeBuffer, short *inBufPtr, int framePerBuffer, int NumInputChannels, int index, int hostFrameOffset,int userFrameOffset,bool swap) -{ - long temp; - int i,j; - - for( j=0; j>16); - userBufPtr += NumInputChannels; - } - } - } - else - { - for( j=0; j> 1) + Pa_TriangularDither(); - temp = temp >> 15; - temp = (short) ClipShort(temp); - *userBufPtr = (short)temp; - userBufPtr += NumInputChannels; - } - } - - } + double *in = (double*)buffer; + float *out = (float*)buffer; + unsigned char *p; + unsigned char temp; + (void) shift; /* unused parameter */ + + while( count-- ) + { + p = (unsigned char*)in; + PA_SWAP_( p[0], p[7] ); + PA_SWAP_( p[1], p[6] ); + PA_SWAP_( p[2], p[5] ); + PA_SWAP_( p[3], p[4] ); + + *out++ = (float) (*in++); + } } -//------------------------------------------------------------------------------------------------------------------------------------------------------- -// MUST BE TESTED -static void Input_Float32_Int16 (ASIOBufferInfo* nativeBuffer, short *inBufPtr, int framePerBuffer, int NumInputChannels, int index, int hostFrameOffset,int userFrameOffset,uint32 flags,bool swap) +static void ConvertFloat64ToFloat32( void *buffer, long shift, long count ) { - unsigned long temp; - int i,j; - - if( flags & paDitherOff ) - { - for( j=0; j>8); - userBufPtr += NumInputChannels; - } - } - } - else - { - for( j=0; j> 8; - temp = ClipShort(temp); - *userBufPtr = (char)(temp>>8); - userBufPtr += NumInputChannels; - } - } - } + float *in = ((float*)buffer) + (count-1); + double *out = ((double*)buffer) + (count-1); + unsigned char *p; + unsigned char temp; + (void) shift; /* unused parameter */ + + while( count-- ) + { + *out = *in--; + + p = (unsigned char*)out; + PA_SWAP_( p[0], p[7] ); + PA_SWAP_( p[1], p[6] ); + PA_SWAP_( p[2], p[5] ); + PA_SWAP_( p[3], p[4] ); + + out--; + } } -//------------------------------------------------------------------------------------------------------------------------------------------------------- -static void Input_Int32_Int8 (ASIOBufferInfo* nativeBuffer, char *inBufPtr, int framePerBuffer, int NumInputChannels, int index, int hostFrameOffset, int userFrameOffset, uint32 flags,bool swap) +static void ConvertFloat32ToFloat64( void *buffer, long shift, long count ) { - long temp; - int i,j; - - if( flags & paDitherOff ) - { - for( j=0; j>24); - userBufPtr += NumInputChannels; - } - } - } - else - { - for( j=0; j>16; // Shift to get a 16 bit value, then use the 16 bits to 8 bits code (MUST BE CHECHED) - temp += Pa_TriangularDither() >> 8; - temp = ClipShort(temp); - *userBufPtr = (char)(temp >> 8); - userBufPtr += NumInputChannels; - } - } - } + float *in = ((float*)buffer) + (count-1); + double *out = ((double*)buffer) + (count-1); + (void) shift; /* unused parameter */ + + while( count-- ) + *out-- = *in--; } -//------------------------------------------------------------------------------------------------------------------------------------------------------- -// MUST BE TESTED +#ifdef MAC +#define PA_MSB_IS_NATIVE_ +#undef PA_LSB_IS_NATIVE_ +#endif -static void Input_Float32_Int8 (ASIOBufferInfo* nativeBuffer, char *inBufPtr, int framePerBuffer, int NumInputChannels, int index, int hostFrameOffset,int userFrameOffset, uint32 flags,bool swap) -{ - unsigned long temp; - int i,j; - - if( flags & paDitherOff ) - { - for( j=0; j>8) + 0x80); - userBufPtr += NumInputChannels; - } - } - } - else + switch (type) { + case ASIOSTInt16MSB: + /* dest: paInt16, no conversion necessary, possible byte swap*/ + #ifdef PA_LSB_IS_NATIVE_ + *converter = Swap16; + #endif + break; + case ASIOSTInt16LSB: + /* dest: paInt16, no conversion necessary, possible byte swap*/ + #ifdef PA_MSB_IS_NATIVE_ + *converter = Swap16; + #endif + break; + case ASIOSTFloat32MSB: + /* dest: paFloat32, no conversion necessary, possible byte swap*/ + #ifdef PA_LSB_IS_NATIVE_ + *converter = Swap32; + #endif + break; + case ASIOSTFloat32LSB: + /* dest: paFloat32, no conversion necessary, possible byte swap*/ + #ifdef PA_MSB_IS_NATIVE_ + *converter = Swap32; + #endif + break; + case ASIOSTFloat64MSB: + /* dest: paFloat32, in-place conversion to/from float32, possible byte swap*/ + #ifdef PA_LSB_IS_NATIVE_ + *converter = Swap64ConvertFloat64ToFloat32; + #else + *converter = ConvertFloat64ToFloat32; + #endif + break; + case ASIOSTFloat64LSB: + /* dest: paFloat32, in-place conversion to/from float32, possible byte swap*/ + #ifdef PA_MSB_IS_NATIVE_ + *converter = Swap64ConvertFloat64ToFloat32; + #else + *converter = ConvertFloat64ToFloat32; + #endif + break; + case ASIOSTInt32MSB: + /* dest: paInt32, no conversion necessary, possible byte swap */ + #ifdef PA_LSB_IS_NATIVE_ + *converter = Swap32; + #endif + break; + case ASIOSTInt32LSB: + /* dest: paInt32, no conversion necessary, possible byte swap */ + #ifdef PA_MSB_IS_NATIVE_ + *converter = Swap32; + #endif + break; + case ASIOSTInt32MSB16: + /* dest: paInt32, 16 bit shift, possible byte swap */ + #ifdef PA_LSB_IS_NATIVE_ + *converter = SwapShiftLeft32; + #else + *converter = ShiftLeft32; + #endif + *shift = 16; + break; + case ASIOSTInt32MSB18: + /* dest: paInt32, 14 bit shift, possible byte swap */ + #ifdef PA_LSB_IS_NATIVE_ + *converter = SwapShiftLeft32; + #else + *converter = ShiftLeft32; + #endif + *shift = 14; + break; + case ASIOSTInt32MSB20: + /* dest: paInt32, 12 bit shift, possible byte swap */ + #ifdef PA_LSB_IS_NATIVE_ + *converter = SwapShiftLeft32; + #else + *converter = ShiftLeft32; + #endif + *shift = 12; + break; + case ASIOSTInt32MSB24: + /* dest: paInt32, 8 bit shift, possible byte swap */ + #ifdef PA_LSB_IS_NATIVE_ + *converter = SwapShiftLeft32; + #else + *converter = ShiftLeft32; + #endif + *shift = 8; + break; + case ASIOSTInt32LSB16: + /* dest: paInt32, 16 bit shift, possible byte swap */ + #ifdef PA_MSB_IS_NATIVE_ + *converter = SwapShiftLeft32; + #else + *converter = ShiftLeft32; + #endif + *shift = 16; + break; + case ASIOSTInt32LSB18: + /* dest: paInt32, 14 bit shift, possible byte swap */ + #ifdef PA_MSB_IS_NATIVE_ + *converter = SwapShiftLeft32; + #else + *converter = ShiftLeft32; + #endif + *shift = 14; + break; + case ASIOSTInt32LSB20: + /* dest: paInt32, 12 bit shift, possible byte swap */ + #ifdef PA_MSB_IS_NATIVE_ + *converter = SwapShiftLeft32; + #else + *converter = ShiftLeft32; + #endif + *shift = 12; + break; + case ASIOSTInt32LSB24: + /* dest: paInt32, 8 bit shift, possible byte swap */ + #ifdef PA_MSB_IS_NATIVE_ + *converter = SwapShiftLeft32; + #else + *converter = ShiftLeft32; + #endif + *shift = 8; + break; + case ASIOSTInt24MSB: + /* dest: paInt24, no conversion necessary, possible byte swap */ + #ifdef PA_LSB_IS_NATIVE_ + *converter = Swap24; + #endif + break; + case ASIOSTInt24LSB: + /* dest: paInt24, no conversion necessary, possible byte swap */ + #ifdef PA_MSB_IS_NATIVE_ + *converter = Swap24; + #endif + break; + } +} + + +static void SelectPaToAsioConverter( ASIOSampleType type, PaAsioBufferConverter **converter, long *shift ) +{ + *shift = 0; + *converter = 0; + + switch (type) { + case ASIOSTInt16MSB: + /* src: paInt16, no conversion necessary, possible byte swap*/ + #ifdef PA_LSB_IS_NATIVE_ + *converter = Swap16; + #endif + break; + case ASIOSTInt16LSB: + /* src: paInt16, no conversion necessary, possible byte swap*/ + #ifdef PA_MSB_IS_NATIVE_ + *converter = Swap16; + #endif + break; + case ASIOSTFloat32MSB: + /* src: paFloat32, no conversion necessary, possible byte swap*/ + #ifdef PA_LSB_IS_NATIVE_ + *converter = Swap32; + #endif + break; + case ASIOSTFloat32LSB: + /* src: paFloat32, no conversion necessary, possible byte swap*/ + #ifdef PA_MSB_IS_NATIVE_ + *converter = Swap32; + #endif + break; + case ASIOSTFloat64MSB: + /* src: paFloat32, in-place conversion to/from float32, possible byte swap*/ + #ifdef PA_LSB_IS_NATIVE_ + *converter = ConvertFloat32ToFloat64Swap64; + #else + *converter = ConvertFloat32ToFloat64; + #endif + break; + case ASIOSTFloat64LSB: + /* src: paFloat32, in-place conversion to/from float32, possible byte swap*/ + #ifdef PA_MSB_IS_NATIVE_ + *converter = ConvertFloat32ToFloat64Swap64; + #else + *converter = ConvertFloat32ToFloat64; + #endif + break; + case ASIOSTInt32MSB: + /* src: paInt32, no conversion necessary, possible byte swap */ + #ifdef PA_LSB_IS_NATIVE_ + *converter = Swap32; + #endif + break; + case ASIOSTInt32LSB: + /* src: paInt32, no conversion necessary, possible byte swap */ + #ifdef PA_MSB_IS_NATIVE_ + *converter = Swap32; + #endif + break; + case ASIOSTInt32MSB16: + /* src: paInt32, 16 bit shift, possible byte swap */ + #ifdef PA_LSB_IS_NATIVE_ + *converter = ShiftRightSwap32; + #else + *converter = ShiftRight32; + #endif + *shift = 16; + break; + case ASIOSTInt32MSB18: + /* src: paInt32, 14 bit shift, possible byte swap */ + #ifdef PA_LSB_IS_NATIVE_ + *converter = ShiftRightSwap32; + #else + *converter = ShiftRight32; + #endif + *shift = 14; + break; + case ASIOSTInt32MSB20: + /* src: paInt32, 12 bit shift, possible byte swap */ + #ifdef PA_LSB_IS_NATIVE_ + *converter = ShiftRightSwap32; + #else + *converter = ShiftRight32; + #endif + *shift = 12; + break; + case ASIOSTInt32MSB24: + /* src: paInt32, 8 bit shift, possible byte swap */ + #ifdef PA_LSB_IS_NATIVE_ + *converter = ShiftRightSwap32; + #else + *converter = ShiftRight32; + #endif + *shift = 8; + break; + case ASIOSTInt32LSB16: + /* src: paInt32, 16 bit shift, possible byte swap */ + #ifdef PA_MSB_IS_NATIVE_ + *converter = ShiftRightSwap32; + #else + *converter = ShiftRight32; + #endif + *shift = 16; + break; + case ASIOSTInt32LSB18: + /* src: paInt32, 14 bit shift, possible byte swap */ + #ifdef PA_MSB_IS_NATIVE_ + *converter = ShiftRightSwap32; + #else + *converter = ShiftRight32; + #endif + *shift = 14; + break; + case ASIOSTInt32LSB20: + /* src: paInt32, 12 bit shift, possible byte swap */ + #ifdef PA_MSB_IS_NATIVE_ + *converter = ShiftRightSwap32; + #else + *converter = ShiftRight32; + #endif + *shift = 12; + break; + case ASIOSTInt32LSB24: + /* src: paInt32, 8 bit shift, possible byte swap */ + #ifdef PA_MSB_IS_NATIVE_ + *converter = ShiftRightSwap32; + #else + *converter = ShiftRight32; + #endif + *shift = 8; + break; + case ASIOSTInt24MSB: + /* src: paInt24, no conversion necessary, possible byte swap */ + #ifdef PA_LSB_IS_NATIVE_ + *converter = Swap24; + #endif + break; + case ASIOSTInt24LSB: + /* src: paInt24, no conversion necessary, possible byte swap */ + #ifdef PA_MSB_IS_NATIVE_ + *converter = Swap24; + #endif + break; + } +} + + +typedef struct PaAsioDeviceInfo +{ + PaDeviceInfo commonDeviceInfo; + long minBufferSize; + long maxBufferSize; + long preferredBufferSize; + long bufferGranularity; + + ASIOChannelInfo *asioChannelInfos; +} +PaAsioDeviceInfo; + + +PaError PaAsio_GetAvailableLatencyValues( PaDeviceIndex device, + long *minLatency, long *maxLatency, long *preferredLatency, long *granularity ) +{ + PaError result; + PaUtilHostApiRepresentation *hostApi; + PaDeviceIndex hostApiDevice; + + result = PaUtil_GetHostApiRepresentation( &hostApi, paASIO ); + + if( result == paNoError ) + { + result = PaUtil_DeviceIndexToHostApiDeviceIndex( &hostApiDevice, device, hostApi ); + + if( result == paNoError ) { - for( j=0; j> 8; - temp = ClipShort(temp); - *userBufPtr = (unsigned char)((temp>>8) + 0x80); - userBufPtr += NumInputChannels; - } - } + PaAsioDeviceInfo *asioDeviceInfo = + (PaAsioDeviceInfo*)hostApi->deviceInfos[hostApiDevice]; + + *minLatency = asioDeviceInfo->minBufferSize; + *maxLatency = asioDeviceInfo->maxBufferSize; + *preferredLatency = asioDeviceInfo->preferredBufferSize; + *granularity = asioDeviceInfo->bufferGranularity; } + } + + return result; +} + + + +/* + load the asio driver named by and return statistics about + the driver in info. If no error occurred, the driver will remain open + and must be closed by the called by calling ASIOExit() - if an error + is returned the driver will already be closed. +*/ +static PaError LoadAsioDriver( const char *driverName, + PaAsioDriverInfo *driverInfo, void *systemSpecific ) +{ + PaError result = paNoError; + ASIOError asioError; + int asioIsInitialized = 0; + + if( !loadAsioDriver( const_cast(driverName) ) ) + { + result = paUnanticipatedHostError; + PA_ASIO_SET_LAST_HOST_ERROR( 0, "Failed to load ASIO driver" ); + goto error; + } + + memset( &driverInfo->asioDriverInfo, 0, sizeof(ASIODriverInfo) ); + driverInfo->asioDriverInfo.asioVersion = 2; + driverInfo->asioDriverInfo.sysRef = systemSpecific; + if( (asioError = ASIOInit( &driverInfo->asioDriverInfo )) != ASE_OK ) + { + result = paUnanticipatedHostError; + PA_ASIO_SET_LAST_ASIO_ERROR( asioError ); + goto error; + } + else + { + asioIsInitialized = 1; + } + + if( (asioError = ASIOGetChannels(&driverInfo->inputChannelCount, + &driverInfo->outputChannelCount)) != ASE_OK ) + { + result = paUnanticipatedHostError; + PA_ASIO_SET_LAST_ASIO_ERROR( asioError ); + goto error; + } + + if( (asioError = ASIOGetBufferSize(&driverInfo->bufferMinSize, + &driverInfo->bufferMaxSize, &driverInfo->bufferPreferredSize, + &driverInfo->bufferGranularity)) != ASE_OK ) + { + result = paUnanticipatedHostError; + PA_ASIO_SET_LAST_ASIO_ERROR( asioError ); + goto error; + } + + if( ASIOOutputReady() == ASE_OK ) + driverInfo->postOutput = true; + else + driverInfo->postOutput = false; + + return result; + +error: + if( asioIsInitialized ) + ASIOExit(); + + return result; } -//------------------------------------------------------------------------------------------------------------------------------------------------------- -static void Input_Int32_IntU8 (ASIOBufferInfo* nativeBuffer, unsigned char *inBufPtr, int framePerBuffer, int NumInputChannels, int index, int hostFrameOffset, int userFrameOffset,uint32 flags,bool swap) + +#define PA_DEFAULTSAMPLERATESEARCHORDER_COUNT_ 13 /* must be the same number of elements as in the array below */ +static ASIOSampleRate 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 }; + + +PaError PaAsio_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex ) { - long temp; - int i,j; - - if( flags & paDitherOff ) + PaError result = paNoError; + int i, driverCount; + PaAsioHostApiRepresentation *asioHostApi; + PaAsioDeviceInfo *deviceInfoArray; + char **names; + PaAsioDriverInfo paAsioDriverInfo; + + asioHostApi = (PaAsioHostApiRepresentation*)PaUtil_AllocateMemory( sizeof(PaAsioHostApiRepresentation) ); + if( !asioHostApi ) + { + result = paInsufficientMemory; + goto error; + } + + asioHostApi->allocations = PaUtil_CreateAllocationGroup(); + if( !asioHostApi->allocations ) + { + result = paInsufficientMemory; + goto error; + } + + asioHostApi->systemSpecific = 0; + asioHostApi->openAsioDeviceIndex = paNoDevice; + + *hostApi = &asioHostApi->inheritedHostApiRep; + (*hostApi)->info.structVersion = 1; + + (*hostApi)->info.type = paASIO; + (*hostApi)->info.name = "ASIO"; + (*hostApi)->info.deviceCount = 0; + + #ifdef WINDOWS + /* use desktop window as system specific ptr */ + asioHostApi->systemSpecific = GetDesktopWindow(); + CoInitialize(NULL); + #endif + + /* MUST BE CHECKED : to force fragments loading on Mac */ + loadAsioDriver( "dummy" ); + + /* driverCount is the number of installed drivers - not necessarily + the number of installed physical devices. */ + #if MAC + driverCount = asioDrivers->getNumFragments(); + #elif WINDOWS + driverCount = asioDrivers->asioGetNumDev(); + #endif + + if( driverCount > 0 ) + { + names = GetAsioDriverNames( asioHostApi->allocations, driverCount ); + if( !names ) { - for( j=0; j>24) + 0x80); - userBufPtr += NumInputChannels; - } - } + result = paInsufficientMemory; + goto error; } - else + + + /* allocate enough space for all drivers, even if some aren't installed */ + + (*hostApi)->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory( + asioHostApi->allocations, sizeof(PaDeviceInfo*) * driverCount ); + if( !(*hostApi)->deviceInfos ) { - for( j=0; j>16; // Shift to get a 16 bit value, then use the 16 bits to 8 bits code (MUST BE CHECHED) - temp += Pa_TriangularDither() >> 8; - temp = ClipShort(temp); - *userBufPtr = (unsigned char)((temp>>8) + 0x80); - userBufPtr += NumInputChannels; - } - } + result = paInsufficientMemory; + goto error; } -} -//------------------------------------------------------------------------------------------------------------------------------------------------------- -// MUST BE TESTED + /* allocate all device info structs in a contiguous block */ + deviceInfoArray = (PaAsioDeviceInfo*)PaUtil_GroupAllocateMemory( + asioHostApi->allocations, sizeof(PaAsioDeviceInfo) * driverCount ); + if( !deviceInfoArray ) + { + result = paInsufficientMemory; + goto error; + } -static void Input_Float32_IntU8 (ASIOBufferInfo* nativeBuffer, unsigned char *inBufPtr, int framePerBuffer, int NumInputChannels, int index, int hostFrameOffset,int userFrameOffset, uint32 flags,bool swap) -{ - unsigned long temp; - int i,j; - - if( flags & paDitherOff ) + for( i=0; i < driverCount; ++i ) { - for( j=0; jsystemSpecific ) == paNoError ) + { + PaAsioDeviceInfo *asioDeviceInfo = &deviceInfoArray[ (*hostApi)->info.deviceCount ]; + PaDeviceInfo *deviceInfo = &asioDeviceInfo->commonDeviceInfo; + + deviceInfo->structVersion = 2; + deviceInfo->hostApi = hostApiIndex; + + deviceInfo->name = names[i]; + PA_DEBUG(("PaAsio_Initialize: drv:%d name = %s\n", i,deviceInfo->name)); + PA_DEBUG(("PaAsio_Initialize: drv:%d inputChannels = %d\n", i, paAsioDriverInfo.inputChannelCount)); + PA_DEBUG(("PaAsio_Initialize: drv:%d outputChannels = %d\n", i, paAsioDriverInfo.outputChannelCount)); + PA_DEBUG(("PaAsio_Initialize: drv:%d bufferMinSize = %d\n", i, paAsioDriverInfo.bufferMinSize)); + PA_DEBUG(("PaAsio_Initialize: drv:%d bufferMaxSize = %d\n", i, paAsioDriverInfo.bufferMaxSize)); + PA_DEBUG(("PaAsio_Initialize: drv:%d bufferPreferredSize = %d\n", i, paAsioDriverInfo.bufferPreferredSize)); + PA_DEBUG(("PaAsio_Initialize: drv:%d bufferGranularity = %d\n", i, paAsioDriverInfo.bufferGranularity)); + + deviceInfo->maxInputChannels = paAsioDriverInfo.inputChannelCount; + deviceInfo->maxOutputChannels = paAsioDriverInfo.outputChannelCount; + + deviceInfo->defaultSampleRate = 0.; + bool foundDefaultSampleRate = false; + for( int j=0; j < PA_DEFAULTSAMPLERATESEARCHORDER_COUNT_; ++j ) + { + ASIOError asioError = ASIOCanSampleRate( defaultSampleRateSearchOrder_[j] ); + if( asioError != ASE_NoClock && asioError != ASE_NotPresent ) + { + deviceInfo->defaultSampleRate = defaultSampleRateSearchOrder_[j]; + foundDefaultSampleRate = true; + break; + } } - } - else - { - for( j=0; jdefaultSampleRate)); + + if( foundDefaultSampleRate ){ + + /* calculate default latency values from bufferPreferredSize + for default low latency, and bufferPreferredSize * 3 + for default high latency. + use the default sample rate to convert from samples to + seconds. Without knowing what sample rate the user will + use this is the best we can do. + */ + + double defaultLowLatency = + paAsioDriverInfo.bufferPreferredSize / deviceInfo->defaultSampleRate; + + deviceInfo->defaultLowInputLatency = defaultLowLatency; + deviceInfo->defaultLowOutputLatency = defaultLowLatency; + + long defaultHighLatencyBufferSize = + paAsioDriverInfo.bufferPreferredSize * 3; + + if( defaultHighLatencyBufferSize > paAsioDriverInfo.bufferMaxSize ) + defaultHighLatencyBufferSize = paAsioDriverInfo.bufferMaxSize; + + double defaultHighLatency = + defaultHighLatencyBufferSize / deviceInfo->defaultSampleRate; + + if( defaultHighLatency < defaultLowLatency ) + defaultHighLatency = defaultLowLatency; /* just incase the driver returns something strange */ + + deviceInfo->defaultHighInputLatency = defaultHighLatency; + deviceInfo->defaultHighOutputLatency = defaultHighLatency; + + }else{ + + deviceInfo->defaultLowInputLatency = 0.; + deviceInfo->defaultLowOutputLatency = 0.; + deviceInfo->defaultHighInputLatency = 0.; + deviceInfo->defaultHighOutputLatency = 0.; } - } -} - -// OUPUT -//------------------------------------------------------------------------------------------------------------------------------------------------------- -static void Output_Float32_Int16 (ASIOBufferInfo* nativeBuffer, float *outBufPtr, int framePerBuffer, int NumInputChannels, int NumOuputChannels, int index, int hostFrameOffset, int userFrameOffset,uint32 flags, bool swap) -{ - long temp; - int i,j; + PA_DEBUG(("PaAsio_Initialize: drv:%d defaultLowInputLatency = %f\n", i, deviceInfo->defaultLowInputLatency)); + PA_DEBUG(("PaAsio_Initialize: drv:%d defaultLowOutputLatency = %f\n", i, deviceInfo->defaultLowOutputLatency)); + PA_DEBUG(("PaAsio_Initialize: drv:%d defaultHighInputLatency = %f\n", i, deviceInfo->defaultHighInputLatency)); + PA_DEBUG(("PaAsio_Initialize: drv:%d defaultHighOutputLatency = %f\n", i, deviceInfo->defaultHighOutputLatency)); + + asioDeviceInfo->minBufferSize = paAsioDriverInfo.bufferMinSize; + asioDeviceInfo->maxBufferSize = paAsioDriverInfo.bufferMaxSize; + asioDeviceInfo->preferredBufferSize = paAsioDriverInfo.bufferPreferredSize; + asioDeviceInfo->bufferGranularity = paAsioDriverInfo.bufferGranularity; - if( flags & paDitherOff ) + + asioDeviceInfo->asioChannelInfos = (ASIOChannelInfo*)PaUtil_GroupAllocateMemory( + asioHostApi->allocations, + sizeof(ASIOChannelInfo) * (deviceInfo->maxInputChannels + + deviceInfo->maxOutputChannels) ); + if( !asioDeviceInfo->asioChannelInfos ) { - if( flags & paClipOff ) /* NOTHING */ - { - for( j=0; jmaxInputChannels; ++a ){ + asioDeviceInfo->asioChannelInfos[a].channel = a; + asioDeviceInfo->asioChannelInfos[a].isInput = ASIOTrue; + ASIOError asioError = ASIOGetChannelInfo( &asioDeviceInfo->asioChannelInfos[a] ); + if( asioError != ASE_OK ) + { + result = paUnanticipatedHostError; + PA_ASIO_SET_LAST_ASIO_ERROR( asioError ); + goto error; + } } -} -//------------------------------------------------------------------------------------------------------------------------------------------------------- -static void Output_Float32_Int32 (ASIOBufferInfo* nativeBuffer, float *outBufPtr, int framePerBuffer, int NumInputChannels, int NumOuputChannels, int index, int hostFrameOffset, int userFrameOffset,uint32 flags,bool swap) -{ - long temp; - int i,j; - - if( flags & paClipOff ) - { - for (j= 0; j < NumOuputChannels; j++) - { - long *asioBufPtr = &((long*)nativeBuffer[j+NumInputChannels].buffers[index])[hostFrameOffset]; - float *userBufPtr = &outBufPtr[j+(userFrameOffset*NumOuputChannels)]; - for( i=0; imaxOutputChannels; ++a ){ + int b = deviceInfo->maxInputChannels + a; + asioDeviceInfo->asioChannelInfos[b].channel = a; + asioDeviceInfo->asioChannelInfos[b].isInput = ASIOFalse; + ASIOError asioError = ASIOGetChannelInfo( &asioDeviceInfo->asioChannelInfos[b] ); + if( asioError != ASE_OK ) + { + result = paUnanticipatedHostError; + PA_ASIO_SET_LAST_ASIO_ERROR( asioError ); + goto error; + } } + + + /* unload the driver */ + ASIOExit(); + + (*hostApi)->deviceInfos[ (*hostApi)->info.deviceCount ] = deviceInfo; + ++(*hostApi)->info.deviceCount; + } } - else // CLIP * + } + + if( (*hostApi)->info.deviceCount > 0 ) + { + (*hostApi)->info.defaultInputDevice = 0; + (*hostApi)->info.defaultOutputDevice = 0; + } + else + { + (*hostApi)->info.defaultInputDevice = paNoDevice; + (*hostApi)->info.defaultOutputDevice = paNoDevice; + } + + + (*hostApi)->Terminate = Terminate; + (*hostApi)->OpenStream = OpenStream; + (*hostApi)->IsFormatSupported = IsFormatSupported; + + PaUtil_InitializeStreamInterface( &asioHostApi->callbackStreamInterface, CloseStream, StartStream, + StopStream, AbortStream, IsStreamStopped, IsStreamActive, + GetStreamTime, GetStreamCpuLoad, + PaUtil_DummyRead, PaUtil_DummyWrite, + PaUtil_DummyGetReadAvailable, PaUtil_DummyGetWriteAvailable ); + + PaUtil_InitializeStreamInterface( &asioHostApi->blockingStreamInterface, CloseStream, StartStream, + StopStream, AbortStream, IsStreamStopped, IsStreamActive, + GetStreamTime, PaUtil_DummyGetCpuLoad, + ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable ); + + return result; + +error: + if( asioHostApi ) + { + if( asioHostApi->allocations ) { - for (j= 0; j < NumOuputChannels; j++) - { - long *asioBufPtr = &((long*)nativeBuffer[j+NumInputChannels].buffers[index])[hostFrameOffset]; - float *userBufPtr = &outBufPtr[j+(userFrameOffset*NumOuputChannels)]; - for( i=0; iallocations ); + PaUtil_DestroyAllocationGroup( asioHostApi->allocations ); } - + + PaUtil_FreeMemory( asioHostApi ); + } + return result; } -//------------------------------------------------------------------------------------------------------------------------------------------------------- -// MUST BE TESTED +static void Terminate( struct PaUtilHostApiRepresentation *hostApi ) +{ + PaAsioHostApiRepresentation *asioHostApi = (PaAsioHostApiRepresentation*)hostApi; + + /* + IMPLEMENT ME: + - clean up any resources not handled by the allocation group + */ + + if( asioHostApi->allocations ) + { + PaUtil_FreeAllAllocations( asioHostApi->allocations ); + PaUtil_DestroyAllocationGroup( asioHostApi->allocations ); + } + + PaUtil_FreeMemory( asioHostApi ); +} + - static void Output_Float32_Float32 (ASIOBufferInfo* nativeBuffer, float *outBufPtr, int framePerBuffer, int NumInputChannels, int NumOuputChannels, int index, int hostFrameOffset, int userFrameOffset,uint32 flags,bool swap) +static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi, + const PaStreamParameters *inputParameters, + const PaStreamParameters *outputParameters, + double sampleRate ) { - long temp; - int i,j; - - if( flags & paClipOff ) + PaError result = paNoError; + PaAsioHostApiRepresentation *asioHostApi = (PaAsioHostApiRepresentation*)hostApi; + PaAsioDriverInfo *driverInfo = &asioHostApi->openAsioDriverInfo; + int inputChannelCount, outputChannelCount; + PaSampleFormat inputSampleFormat, outputSampleFormat; + PaDeviceIndex asioDeviceIndex; + ASIOError asioError; + + if( inputParameters && outputParameters ) + { + /* full duplex ASIO stream must use the same device for input and output */ + + if( inputParameters->device != outputParameters->device ) + return paBadIODeviceCombination; + } + + 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; + + asioDeviceIndex = inputParameters->device; + + /* validate inputStreamInfo */ + /** @todo do more validation here */ + // if( inputParameters->hostApiSpecificStreamInfo ) + // return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */ + } + 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; + + asioDeviceIndex = outputParameters->device; + + /* validate outputStreamInfo */ + /** @todo do more validation here */ + // if( outputParameters->hostApiSpecificStreamInfo ) + // return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */ + } + else + { + outputChannelCount = 0; + } + + + + /* if an ASIO device is open we can only get format information for the currently open device */ + + if( asioHostApi->openAsioDeviceIndex != paNoDevice + && asioHostApi->openAsioDeviceIndex != asioDeviceIndex ) + { + return paDeviceUnavailable; + } + + + /* NOTE: we load the driver and use its current settings + rather than the ones in our device info structure which may be stale */ + + /* open the device if it's not already open */ + if( asioHostApi->openAsioDeviceIndex == paNoDevice ) + { + result = LoadAsioDriver( asioHostApi->inheritedHostApiRep.deviceInfos[ asioDeviceIndex ]->name, + driverInfo, asioHostApi->systemSpecific ); + if( result != paNoError ) + return result; + } + + /* check that input device can support inputChannelCount */ + if( inputChannelCount > 0 ) + { + if( inputChannelCount > driverInfo->inputChannelCount ) { - for (j= 0; j < NumOuputChannels; j++) - { - float *asioBufPtr = &((float*)nativeBuffer[j+NumInputChannels].buffers[index])[hostFrameOffset]; - float *userBufPtr = &outBufPtr[j+(userFrameOffset*NumOuputChannels)]; - for( i=0; i driverInfo->outputChannelCount ) { - for (j= 0; j < NumOuputChannels; j++) - { - float *asioBufPtr = &((float*)nativeBuffer[j+NumInputChannels].buffers[index])[hostFrameOffset]; - float *userBufPtr = &outBufPtr[j+(userFrameOffset*NumOuputChannels)]; - for( i=0; iopenAsioDeviceIndex == paNoDevice ) + { + ASIOExit(); /* not sure if we should check for errors here */ + } + + if( result == paNoError ) + return paFormatIsSupported; + else + return result; } -//------------------------------------------------------------------------------------------------------------------------------------------------------- -static void Output_Int32_Int16(ASIOBufferInfo* nativeBuffer, long *outBufPtr, int framePerBuffer, int NumInputChannels, int NumOuputChannels, int index, int hostFrameOffset,int userFrameOffset,uint32 flags,bool swap) + + +/* PaAsioStream - a stream data structure specifically for this implementation */ + +typedef struct PaAsioStream { - long temp; - int i,j; - - if( flags & paDitherOff ) - { - for (j= 0; j < NumOuputChannels; j++) - { - short *asioBufPtr = &((short*)nativeBuffer[j+NumInputChannels].buffers[index])[hostFrameOffset]; - long *userBufPtr = &outBufPtr[j+(userFrameOffset*NumOuputChannels)]; - for( i=0; i> 16); - if (swap) temp = SwapShort(temp); - asioBufPtr[i] = (short)temp; - userBufPtr += NumOuputChannels; - } - } - } - else - { - for (j= 0; j < NumOuputChannels; j++) - { - short *asioBufPtr = &((short*)nativeBuffer[j+NumInputChannels].buffers[index])[hostFrameOffset]; - long *userBufPtr = &outBufPtr[j+(userFrameOffset*NumOuputChannels)]; - for( i=0; i> 1) + Pa_TriangularDither(); - temp = temp >> 15; - temp = (short) ClipShort(temp); - if (swap) temp = SwapShort(temp); - asioBufPtr[i] = (short)temp; - userBufPtr += NumOuputChannels; - } - } - } + PaUtilStreamRepresentation streamRepresentation; + PaUtilCpuLoadMeasurer cpuLoadMeasurer; + PaUtilBufferProcessor bufferProcessor; + + PaAsioHostApiRepresentation *asioHostApi; + unsigned long framesPerHostCallback; + + /* ASIO driver info - these may not be needed for the life of the stream, + but store them here until we work out how format conversion is going + to work. */ + + ASIOBufferInfo *asioBufferInfos; + ASIOChannelInfo *asioChannelInfos; + long inputLatency, outputLatency; // actual latencies returned by asio + + long inputChannelCount, outputChannelCount; + bool postOutput; + + void **bufferPtrs; /* this is carved up for inputBufferPtrs and outputBufferPtrs */ + void **inputBufferPtrs[2]; + void **outputBufferPtrs[2]; + + PaAsioBufferConverter *inputBufferConverter; + long inputShift; + PaAsioBufferConverter *outputBufferConverter; + long outputShift; + + volatile bool stopProcessing; + int stopPlayoutCount; + HANDLE completedBuffersPlayedEvent; + + bool streamFinishedCallbackCalled; + volatile int isActive; + volatile bool zeroOutput; /* all future calls to the callback will output silence */ + + volatile long reenterCount; + volatile long reenterError; + + PaStreamCallbackFlags callbackFlags; } +PaAsioStream; + +static PaAsioStream *theAsioStream = 0; /* due to ASIO sdk limitations there can be only one stream */ -//------------------------------------------------------------------------------------------------------------------------------------------------------- -static void Output_Int32_Int32(ASIOBufferInfo* nativeBuffer, long *outBufPtr, int framePerBuffer, int NumInputChannels, int NumOuputChannels, int index, int hostFrameOffset,int userFrameOffset,uint32 flags,bool swap) + +static void ZeroOutputBuffers( PaAsioStream *stream, long index ) { - long temp; - int i,j; - - for (j= 0; j < NumOuputChannels; j++) - { - long *asioBufPtr = &((long*)nativeBuffer[j+NumInputChannels].buffers[index])[hostFrameOffset]; - long *userBufPtr = &outBufPtr[j+(userFrameOffset*NumOuputChannels)]; - for( i=0; ioutputChannelCount; ++i ) + { + void *buffer = stream->asioBufferInfos[ i + stream->inputChannelCount ].buffers[index]; + + int bytesPerSample = BytesPerAsioSample( stream->asioChannelInfos[ i + stream->inputChannelCount ].type ); + + memset( buffer, 0, stream->framesPerHostCallback * bytesPerSample ); + } } -//------------------------------------------------------------------------------------------------------------------------------------------------------- -// MUST BE CHECKED -static void Output_Int32_Float32(ASIOBufferInfo* nativeBuffer, long *outBufPtr, int framePerBuffer, int NumInputChannels, int NumOuputChannels, int index, int hostFrameOffset,int userFrameOffset,uint32 flags,bool swap) +static unsigned long SelectHostBufferSize( unsigned long suggestedLatencyFrames, + PaAsioDriverInfo *driverInfo ) { - long temp; - int i,j; - - for (j= 0; j < NumOuputChannels; j++) + unsigned long result; + + if( suggestedLatencyFrames == 0 ) + { + result = driverInfo->bufferPreferredSize; + } + else{ + if( suggestedLatencyFrames <= (unsigned long)driverInfo->bufferMinSize ) + { + result = driverInfo->bufferMinSize; + } + else if( suggestedLatencyFrames >= (unsigned long)driverInfo->bufferMaxSize ) + { + result = driverInfo->bufferMaxSize; + } + else { - float *asioBufPtr = &((float*)nativeBuffer[j+NumInputChannels].buffers[index])[hostFrameOffset]; - long *userBufPtr = &outBufPtr[j+(userFrameOffset*NumOuputChannels)]; - for( i=0; ibufferGranularity == -1 ) + { + /* power-of-two */ + result = 2; + + while( result < suggestedLatencyFrames ) + result *= 2; + + if( result < (unsigned long)driverInfo->bufferMinSize ) + result = driverInfo->bufferMinSize; + + if( result > (unsigned long)driverInfo->bufferMaxSize ) + result = driverInfo->bufferMaxSize; + } + else if( driverInfo->bufferGranularity == 0 ) + { + /* the documentation states that bufferGranularity should be + zero when bufferMinSize, bufferMaxSize and + bufferPreferredSize are the same. We assume that is the case. + */ + + result = driverInfo->bufferPreferredSize; + } + else + { + /* modulo granularity */ + + unsigned long remainder = + suggestedLatencyFrames % driverInfo->bufferGranularity; + + if( remainder == 0 ) { - temp = *userBufPtr; - if (swap) temp = SwapLong(temp); - asioBufPtr[i] = ((float)temp) * (1.0f / MAX_INT32_FP); - userBufPtr += NumOuputChannels; + result = suggestedLatencyFrames; + } + else + { + result = suggestedLatencyFrames + + (driverInfo->bufferGranularity - remainder); + + if( result > (unsigned long)driverInfo->bufferMaxSize ) + result = driverInfo->bufferMaxSize; } + } } + } + + return result; } -//------------------------------------------------------------------------------------------------------------------------------------------------------- -static void Output_Int16_Int16(ASIOBufferInfo* nativeBuffer, short *outBufPtr, int framePerBuffer, int NumInputChannels, int NumOuputChannels, int index, int hostFrameOffset, int userFrameOffset,bool swap) + +/* returns channelSelectors if present */ + +static PaError ValidateAsioSpecificStreamInfo( + const PaStreamParameters *streamParameters, + const PaAsioStreamInfo *streamInfo, + int deviceChannelCount, + int **channelSelectors ) { - long temp; - int i,j; + if( streamInfo ) + { + if( streamInfo->size != sizeof( PaAsioStreamInfo ) + || streamInfo->version != 1 ) + { + return paIncompatibleHostApiSpecificStreamInfo; + } - for (j= 0; j < NumOuputChannels; j++) + if( streamInfo->flags & paAsioUseChannelSelectors ) + *channelSelectors = streamInfo->channelSelectors; + + if( !(*channelSelectors) ) + return paIncompatibleHostApiSpecificStreamInfo; + + for( int i=0; i < streamParameters->channelCount; ++i ){ + if( (*channelSelectors)[i] < 0 + || (*channelSelectors)[i] >= deviceChannelCount ){ + return paInvalidChannelCount; + } + } + } + + return paNoError; +} + + +/* 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; + PaAsioHostApiRepresentation *asioHostApi = (PaAsioHostApiRepresentation*)hostApi; + PaAsioStream *stream = 0; + PaAsioStreamInfo *inputStreamInfo, *outputStreamInfo; + unsigned long framesPerHostBuffer; + int inputChannelCount, outputChannelCount; + PaSampleFormat inputSampleFormat, outputSampleFormat; + PaSampleFormat hostInputSampleFormat, hostOutputSampleFormat; + unsigned long suggestedInputLatencyFrames; + unsigned long suggestedOutputLatencyFrames; + PaDeviceIndex asioDeviceIndex; + ASIOError asioError; + int asioIsInitialized = 0; + int asioBuffersCreated = 0; + int completedBuffersPlayedEventInited = 0; + int i; + PaAsioDriverInfo *driverInfo; + int *inputChannelSelectors = 0; + int *outputChannelSelectors = 0; + + /* unless we move to using lower level ASIO calls, we can only have + one device open at a time */ + if( asioHostApi->openAsioDeviceIndex != paNoDevice ){ + PA_DEBUG(("OpenStream paDeviceUnavailable\n")); + return paDeviceUnavailable; + } + + if( inputParameters && outputParameters ) + { + /* full duplex ASIO stream must use the same device for input and output */ + + if( inputParameters->device != outputParameters->device ){ + PA_DEBUG(("OpenStream paBadIODeviceCombination\n")); + return paBadIODeviceCombination; + } + } + + if( inputParameters ) + { + inputChannelCount = inputParameters->channelCount; + inputSampleFormat = inputParameters->sampleFormat; + suggestedInputLatencyFrames = (unsigned long)((inputParameters->suggestedLatency * sampleRate)+0.5f); + + /* unless alternate device specification is supported, reject the use of + paUseHostApiSpecificDeviceSpecification */ + if( inputParameters->device == paUseHostApiSpecificDeviceSpecification ) + return paInvalidDevice; + + asioDeviceIndex = inputParameters->device; + + PaAsioDeviceInfo *asioDeviceInfo = (PaAsioDeviceInfo*)hostApi->deviceInfos[asioDeviceIndex]; + + /* validate hostApiSpecificStreamInfo */ + inputStreamInfo = (PaAsioStreamInfo*)inputParameters->hostApiSpecificStreamInfo; + result = ValidateAsioSpecificStreamInfo( inputParameters, inputStreamInfo, + asioDeviceInfo->commonDeviceInfo.maxInputChannels, + &inputChannelSelectors + ); + if( result != paNoError ) return result; + } + else + { + inputChannelCount = 0; + inputSampleFormat = 0; + suggestedInputLatencyFrames = 0; + } + + if( outputParameters ) + { + outputChannelCount = outputParameters->channelCount; + outputSampleFormat = outputParameters->sampleFormat; + suggestedOutputLatencyFrames = (unsigned long)((outputParameters->suggestedLatency * sampleRate)+0.5f); + + /* unless alternate device specification is supported, reject the use of + paUseHostApiSpecificDeviceSpecification */ + if( outputParameters->device == paUseHostApiSpecificDeviceSpecification ) + return paInvalidDevice; + + asioDeviceIndex = outputParameters->device; + + PaAsioDeviceInfo *asioDeviceInfo = (PaAsioDeviceInfo*)hostApi->deviceInfos[asioDeviceIndex]; + + /* validate hostApiSpecificStreamInfo */ + outputStreamInfo = (PaAsioStreamInfo*)outputParameters->hostApiSpecificStreamInfo; + result = ValidateAsioSpecificStreamInfo( outputParameters, outputStreamInfo, + asioDeviceInfo->commonDeviceInfo.maxOutputChannels, + &outputChannelSelectors + ); + if( result != paNoError ) return result; + } + else + { + outputChannelCount = 0; + outputSampleFormat = 0; + suggestedOutputLatencyFrames = 0; + } + + driverInfo = &asioHostApi->openAsioDriverInfo; + + /* NOTE: we load the driver and use its current settings + rather than the ones in our device info structure which may be stale */ + + result = LoadAsioDriver( asioHostApi->inheritedHostApiRep.deviceInfos[ asioDeviceIndex ]->name, + driverInfo, asioHostApi->systemSpecific ); + if( result == paNoError ) + asioIsInitialized = 1; + else{ + PA_DEBUG(("OpenStream ERROR1\n")); + goto error; + } + + /* check that input device can support inputChannelCount */ + if( inputChannelCount > 0 ) + { + if( inputChannelCount > driverInfo->inputChannelCount ) { - short *asioBufPtr = &((short*)nativeBuffer[j+NumInputChannels].buffers[index])[hostFrameOffset]; - short *userBufPtr = &outBufPtr[j+(userFrameOffset*NumOuputChannels)]; - for( i=0; i driverInfo->outputChannelCount ) { - long *asioBufPtr = &((long*)nativeBuffer[j+NumInputChannels].buffers[index])[hostFrameOffset]; - short *userBufPtr = &outBufPtr[j+(userFrameOffset*NumOuputChannels)]; - for( i=0; icompletedBuffersPlayedEvent = CreateEvent( NULL, TRUE, FALSE, NULL ); + if( stream->completedBuffersPlayedEvent == NULL ) + { + result = paUnanticipatedHostError; + PA_ASIO_SET_LAST_SYSTEM_ERROR( GetLastError() ); + PA_DEBUG(("OpenStream ERROR6\n")); + goto error; + } + completedBuffersPlayedEventInited = 1; + + + stream->asioBufferInfos = 0; /* for deallocation in error */ + stream->asioChannelInfos = 0; /* for deallocation in error */ + stream->bufferPtrs = 0; /* for deallocation in error */ + + if( streamCallback ) + { + PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation, + &asioHostApi->callbackStreamInterface, streamCallback, userData ); + } + else + { + PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation, + &asioHostApi->blockingStreamInterface, streamCallback, userData ); + } + + + PaUtil_InitializeCpuLoadMeasurer( &stream->cpuLoadMeasurer, sampleRate ); + + + stream->asioBufferInfos = (ASIOBufferInfo*)PaUtil_AllocateMemory( + sizeof(ASIOBufferInfo) * (inputChannelCount + outputChannelCount) ); + if( !stream->asioBufferInfos ) + { + result = paInsufficientMemory; + PA_DEBUG(("OpenStream ERROR7\n")); + goto error; + } + + + for( i=0; i < inputChannelCount; ++i ) + { + ASIOBufferInfo *info = &stream->asioBufferInfos[i]; + + info->isInput = ASIOTrue; + + if( inputChannelSelectors ){ + // inputChannelSelectors values have already been validated in + // ValidateAsioSpecificStreamInfo() above + info->channelNum = inputChannelSelectors[i]; + }else{ + info->channelNum = i; } + + info->buffers[0] = info->buffers[1] = 0; + } + + for( i=0; i < outputChannelCount; ++i ){ + ASIOBufferInfo *info = &stream->asioBufferInfos[inputChannelCount+i]; + + info->isInput = ASIOFalse; + + if( outputChannelSelectors ){ + // outputChannelSelectors values have already been validated in + // ValidateAsioSpecificStreamInfo() above + info->channelNum = outputChannelSelectors[i]; + }else{ + info->channelNum = i; + } + + info->buffers[0] = info->buffers[1] = 0; + } + + + framesPerHostBuffer = SelectHostBufferSize( + (( suggestedInputLatencyFrames > suggestedOutputLatencyFrames ) + ? suggestedInputLatencyFrames : suggestedOutputLatencyFrames), + driverInfo ); + + + PA_DEBUG(("PaAsioOpenStream: framesPerHostBuffer :%d\n", framesPerHostBuffer)); + + asioError = ASIOCreateBuffers( stream->asioBufferInfos, + inputChannelCount+outputChannelCount, + framesPerHostBuffer, &asioCallbacks_ ); + + if( asioError != ASE_OK + && framesPerHostBuffer != (unsigned long)driverInfo->bufferPreferredSize ) + { + PA_DEBUG(("ERROR: ASIOCreateBuffers: %s\n", PaAsio_GetAsioErrorText(asioError) )); + /* + Some buggy drivers (like the Hoontech DSP24) give incorrect + [min, preferred, max] values They should work with the preferred size + value, thus if Pa_ASIO_CreateBuffers fails with the hostBufferSize + computed in SelectHostBufferSize, we try again with the preferred size. + */ + + framesPerHostBuffer = driverInfo->bufferPreferredSize; + + PA_DEBUG(("PaAsioOpenStream: CORRECTED framesPerHostBuffer :%d\n", framesPerHostBuffer)); + + ASIOError asioError2 = ASIOCreateBuffers( stream->asioBufferInfos, + inputChannelCount+outputChannelCount, + framesPerHostBuffer, &asioCallbacks_ ); + if( asioError2 == ASE_OK ) + asioError = ASE_OK; + } + + if( asioError != ASE_OK ) + { + result = paUnanticipatedHostError; + PA_ASIO_SET_LAST_ASIO_ERROR( asioError ); + PA_DEBUG(("OpenStream ERROR9\n")); + goto error; + } + + asioBuffersCreated = 1; + + stream->asioChannelInfos = (ASIOChannelInfo*)PaUtil_AllocateMemory( + sizeof(ASIOChannelInfo) * (inputChannelCount + outputChannelCount) ); + if( !stream->asioChannelInfos ) + { + result = paInsufficientMemory; + PA_DEBUG(("OpenStream ERROR10\n")); + goto error; + } + + for( i=0; i < inputChannelCount + outputChannelCount; ++i ) + { + stream->asioChannelInfos[i].channel = stream->asioBufferInfos[i].channelNum; + stream->asioChannelInfos[i].isInput = stream->asioBufferInfos[i].isInput; + asioError = ASIOGetChannelInfo( &stream->asioChannelInfos[i] ); + if( asioError != ASE_OK ) + { + result = paUnanticipatedHostError; + PA_ASIO_SET_LAST_ASIO_ERROR( asioError ); + PA_DEBUG(("OpenStream ERROR11\n")); + goto error; + } + } + + stream->bufferPtrs = (void**)PaUtil_AllocateMemory( + 2 * sizeof(void*) * (inputChannelCount + outputChannelCount) ); + if( !stream->bufferPtrs ) + { + result = paInsufficientMemory; + PA_DEBUG(("OpenStream ERROR12\n")); + goto error; + } + + if( inputChannelCount > 0 ) + { + stream->inputBufferPtrs[0] = stream-> bufferPtrs; + stream->inputBufferPtrs[1] = &stream->bufferPtrs[inputChannelCount]; + + for( i=0; iinputBufferPtrs[0][i] = stream->asioBufferInfos[i].buffers[0]; + stream->inputBufferPtrs[1][i] = stream->asioBufferInfos[i].buffers[1]; + } + } + else + { + stream->inputBufferPtrs[0] = 0; + stream->inputBufferPtrs[1] = 0; + } + + if( outputChannelCount > 0 ) + { + stream->outputBufferPtrs[0] = &stream->bufferPtrs[inputChannelCount*2]; + stream->outputBufferPtrs[1] = &stream->bufferPtrs[inputChannelCount*2 + outputChannelCount]; + + for( i=0; ioutputBufferPtrs[0][i] = stream->asioBufferInfos[inputChannelCount+i].buffers[0]; + stream->outputBufferPtrs[1][i] = stream->asioBufferInfos[inputChannelCount+i].buffers[1]; + } + } + else + { + stream->outputBufferPtrs[0] = 0; + stream->outputBufferPtrs[1] = 0; + } + + if( inputChannelCount > 0 ) + { + /* FIXME: assume all channels use the same type for now */ + ASIOSampleType inputType = stream->asioChannelInfos[0].type; + + PA_DEBUG(("ASIO Input type:%d",inputType)); + AsioSampleTypeLOG(inputType); + hostInputSampleFormat = AsioSampleTypeToPaNativeSampleFormat( inputType ); + + SelectAsioToPaConverter( inputType, &stream->inputBufferConverter, &stream->inputShift ); + } + else + { + hostInputSampleFormat = 0; + stream->inputBufferConverter = 0; + } + + if( outputChannelCount > 0 ) + { + /* FIXME: assume all channels use the same type for now */ + ASIOSampleType outputType = stream->asioChannelInfos[inputChannelCount].type; + + PA_DEBUG(("ASIO Output type:%d",outputType)); + AsioSampleTypeLOG(outputType); + hostOutputSampleFormat = AsioSampleTypeToPaNativeSampleFormat( outputType ); + + SelectPaToAsioConverter( outputType, &stream->outputBufferConverter, &stream->outputShift ); + } + else + { + hostOutputSampleFormat = 0; + stream->outputBufferConverter = 0; + } + + result = PaUtil_InitializeBufferProcessor( &stream->bufferProcessor, + inputChannelCount, inputSampleFormat, hostInputSampleFormat, + outputChannelCount, outputSampleFormat, hostOutputSampleFormat, + sampleRate, streamFlags, framesPerBuffer, + framesPerHostBuffer, paUtilFixedHostBufferSize, + streamCallback, userData ); + if( result != paNoError ){ + PA_DEBUG(("OpenStream ERROR13\n")); + goto error; + } + + + ASIOGetLatencies( &stream->inputLatency, &stream->outputLatency ); + + stream->streamRepresentation.streamInfo.inputLatency = + (double)( PaUtil_GetBufferProcessorInputLatency(&stream->bufferProcessor) + + stream->inputLatency) / sampleRate; // seconds + stream->streamRepresentation.streamInfo.outputLatency = + (double)( PaUtil_GetBufferProcessorOutputLatency(&stream->bufferProcessor) + + stream->outputLatency) / sampleRate; // seconds + stream->streamRepresentation.streamInfo.sampleRate = sampleRate; + + // the code below prints the ASIO latency which doesn't include the + // buffer processor latency. it reports the added latency separately + PA_DEBUG(("PaAsio : ASIO InputLatency = %ld (%ld ms), added buffProc:%ld (%ld ms)\n", + stream->inputLatency, + (long)((stream->inputLatency*1000)/ sampleRate), + PaUtil_GetBufferProcessorInputLatency(&stream->bufferProcessor), + (long)((PaUtil_GetBufferProcessorInputLatency(&stream->bufferProcessor)*1000)/ sampleRate) + )); + + PA_DEBUG(("PaAsio : ASIO OuputLatency = %ld (%ld ms), added buffProc:%ld (%ld ms)\n", + stream->outputLatency, + (long)((stream->outputLatency*1000)/ sampleRate), + PaUtil_GetBufferProcessorOutputLatency(&stream->bufferProcessor), + (long)((PaUtil_GetBufferProcessorOutputLatency(&stream->bufferProcessor)*1000)/ sampleRate) + )); + + stream->asioHostApi = asioHostApi; + stream->framesPerHostCallback = framesPerHostBuffer; + + stream->inputChannelCount = inputChannelCount; + stream->outputChannelCount = outputChannelCount; + stream->postOutput = driverInfo->postOutput; + stream->isActive = 0; + + asioHostApi->openAsioDeviceIndex = asioDeviceIndex; + + *s = (PaStream*)stream; + + return result; + +error: + PA_DEBUG(("goto errored\n")); + if( stream ) + { + if( completedBuffersPlayedEventInited ) + CloseHandle( stream->completedBuffersPlayedEvent ); + + if( stream->asioBufferInfos ) + PaUtil_FreeMemory( stream->asioBufferInfos ); + + if( stream->asioChannelInfos ) + PaUtil_FreeMemory( stream->asioChannelInfos ); + + if( stream->bufferPtrs ) + PaUtil_FreeMemory( stream->bufferPtrs ); + + PaUtil_FreeMemory( stream ); + } + + if( asioBuffersCreated ) + ASIODisposeBuffers(); + + if( asioIsInitialized ) + ASIOExit(); + + return result; } -//------------------------------------------------------------------------------------------------------------------------------------------------------- -static void Output_Int8_Int16(ASIOBufferInfo* nativeBuffer, char *outBufPtr, int framePerBuffer, int NumInputChannels, int NumOuputChannels, int index, int hostFrameOffset,int userFrameOffset, bool swap) + + +/* + When CloseStream() is called, the multi-api layer ensures that + the stream has already been stopped or aborted. +*/ +static PaError CloseStream( PaStream* s ) { - long temp; - int i,j; + PaError result = paNoError; + PaAsioStream *stream = (PaAsioStream*)s; - for (j= 0; j < NumOuputChannels; j++) - { - short *asioBufPtr = &((short*)nativeBuffer[j+NumInputChannels].buffers[index])[hostFrameOffset]; - char *userBufPtr = &outBufPtr[j+(userFrameOffset*NumOuputChannels)]; - for( i=0; ibufferProcessor ); + PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation ); + + stream->asioHostApi->openAsioDeviceIndex = paNoDevice; + + CloseHandle( stream->completedBuffersPlayedEvent ); + + PaUtil_FreeMemory( stream->asioBufferInfos ); + PaUtil_FreeMemory( stream->asioChannelInfos ); + PaUtil_FreeMemory( stream->bufferPtrs ); + PaUtil_FreeMemory( stream ); + + ASIODisposeBuffers(); + ASIOExit(); + + return result; } -//------------------------------------------------------------------------------------------------------------------------------------------------------- -static void Output_Int8_Int32(ASIOBufferInfo* nativeBuffer, char *outBufPtr, int framePerBuffer, int NumInputChannels, int NumOuputChannels, int index, int hostFrameOffset,int userFrameOffset, bool swap) + +static void bufferSwitch(long index, ASIOBool directProcess) { - long temp; - int i,j; +//TAKEN FROM THE ASIO SDK - for (j= 0; j < NumOuputChannels; j++) - { - long *asioBufPtr = &((long*)nativeBuffer[j+NumInputChannels].buffers[index])[hostFrameOffset]; - char *userBufPtr = &outBufPtr[j+(userFrameOffset*NumOuputChannels)]; - for( i=0; itimeInfo.flags & kSystemTimeValid) + asioDriverInfo.nanoSeconds = ASIO64toDouble(timeInfo->timeInfo.systemTime); + else + asioDriverInfo.nanoSeconds = 0; + + if (timeInfo->timeInfo.flags & kSamplePositionValid) + asioDriverInfo.samples = ASIO64toDouble(timeInfo->timeInfo.samplePosition); + else + asioDriverInfo.samples = 0; + + if (timeInfo->timeCode.flags & kTcValid) + asioDriverInfo.tcSamples = ASIO64toDouble(timeInfo->timeCode.timeCodeSamples); + else + asioDriverInfo.tcSamples = 0; + + // get the system reference time + asioDriverInfo.sysRefTime = get_sys_reference_time(); +#endif + +#if 0 + // a few debug messages for the Windows device driver developer + // tells you the time when driver got its interrupt and the delay until the app receives + // the event notification. + static double last_samples = 0; + char tmp[128]; + sprintf (tmp, "diff: %d / %d ms / %d ms / %d samples \n", asioDriverInfo.sysRefTime - (long)(asioDriverInfo.nanoSeconds / 1000000.0), asioDriverInfo.sysRefTime, (long)(asioDriverInfo.nanoSeconds / 1000000.0), (long)(asioDriverInfo.samples - last_samples)); + OutputDebugString (tmp); + last_samples = asioDriverInfo.samples; +#endif + + + if( !theAsioStream ) + return 0L; -//------------------------------------------------------------------------------------------------------------------------------------------------------- -static void Output_IntU8_Int16(ASIOBufferInfo* nativeBuffer, unsigned char *outBufPtr, int framePerBuffer, int NumInputChannels, int NumOuputChannels, int index, int hostFrameOffset,int userFrameOffset, bool swap) -{ - long temp; - int i,j; + // Keep sample position + // FIXME: asioDriverInfo.pahsc_NumFramesDone = timeInfo->timeInfo.samplePosition.lo; - for (j= 0; j < NumOuputChannels; j++) - { - short *asioBufPtr = &((short*)nativeBuffer[j+NumInputChannels].buffers[index])[hostFrameOffset]; - unsigned char *userBufPtr = &outBufPtr[j+(userFrameOffset*NumOuputChannels)]; - for( i=0; ireenterCount) ) + { + theAsioStream->reenterError++; + //DBUG(("bufferSwitchTimeInfo : reentrancy detection = %d\n", asioDriverInfo.reenterError)); + return 0L; + } + + int buffersDone = 0; + + do + { + if( buffersDone > 0 ) { - long *asioBufPtr = &((long*)nativeBuffer[j+NumInputChannels].buffers[index])[hostFrameOffset]; - unsigned char *userBufPtr = &outBufPtr[j+(userFrameOffset*NumOuputChannels)]; - for( i=0; iinputChannelCount > 0 ) + theAsioStream->callbackFlags |= paInputOverflow; + + if( theAsioStream->outputChannelCount > 0 ) + theAsioStream->callbackFlags |= paOutputUnderflow; } -} + else + { + if( theAsioStream->zeroOutput ) + { + ZeroOutputBuffers( theAsioStream, index ); -//------------------------------------------------------------------------------------------------------------------------------------------------------- -// MUST BE CHECKED + // Finally if the driver supports the ASIOOutputReady() optimization, + // do it here, all data are in place + if( theAsioStream->postOutput ) + ASIOOutputReady(); -static void Output_IntU8_Float32(ASIOBufferInfo* nativeBuffer, unsigned char *outBufPtr, int framePerBuffer, int NumInputChannels, int NumOuputChannels, int index, int hostFrameOffset,int userFrameOffset, bool swap) -{ - long temp; - int i,j; - - for (j= 0; j < NumOuputChannels; j++) - { - float *asioBufPtr = &((float*)nativeBuffer[j+NumInputChannels].buffers[index])[hostFrameOffset]; - unsigned char *userBufPtr = &outBufPtr[j+(userFrameOffset*NumOuputChannels)]; - for( i=0; istopProcessing ) { - temp = ((short)((*userBufPtr) - 0x80)) << 24; - asioBufPtr[i] = ((float)temp) * (1.0f / MAX_INT32_FP); - userBufPtr += NumOuputChannels; + if( theAsioStream->stopPlayoutCount < 2 ) + { + ++theAsioStream->stopPlayoutCount; + if( theAsioStream->stopPlayoutCount == 2 ) + { + theAsioStream->isActive = 0; + if( theAsioStream->streamRepresentation.streamFinishedCallback != 0 ) + theAsioStream->streamRepresentation.streamFinishedCallback( theAsioStream->streamRepresentation.userData ); + theAsioStream->streamFinishedCallbackCalled = true; + SetEvent( theAsioStream->completedBuffersPlayedEvent ); + } + } } - } -} + } + else + { -//------------------------------------------------------------------------------------------------------------------------------------------------------- -static void Pa_ASIO_Clear_Output_16 (ASIOBufferInfo* nativeBuffer, long frames, long NumInputChannels, long NumOuputChannels, long index, long hostFrameOffset) -{ - int i,j; +#if 0 +// test code to try to detect slip conditions... these may work on some systems +// but neither of them work on the RME Digi96 - for( j=0; jtimeCode.flags & kTcValid ) +// samples = ASIO64toDouble(timeInfo->timeCode.timeCodeSamples); +//else + samples = ASIO64toDouble(timeInfo->timeInfo.samplePosition); +int delta = samples - last_samples; +//printf( "%d\n", delta); +last_samples = samples; -//------------------------------------------------------------------------------------------------------------------------------------------------------- -static void Pa_ASIO_Clear_Output_32 (ASIOBufferInfo* nativeBuffer, long frames, long NumInputChannels, long NumOuputChannels, long index, long hostFrameOffset) +if( delta > theAsioStream->framesPerHostCallback ) { - int i,j; - - for( j=0; jinputChannelCount > 0 ) + theAsioStream->callbackFlags |= paInputOverflow; -//------------------------------------------------------------------------------------------------------------------------------------------------------- -static void Pa_ASIO_Adaptor_Init() -{ - if (asioDriverInfo.past->past_FramesPerUserBuffer <= asioDriverInfo.past_FramesPerHostBuffer) { - asioDriverInfo.pahsc_hostOutputBufferFrameOffset = asioDriverInfo.pahsc_OutputBufferOffset; - asioDriverInfo.pahsc_userInputBufferFrameOffset = 0; // empty - asioDriverInfo.pahsc_userOutputBufferFrameOffset = asioDriverInfo.past->past_FramesPerUserBuffer; // empty - }else { - asioDriverInfo.pahsc_hostOutputBufferFrameOffset = 0; // empty - asioDriverInfo.pahsc_userInputBufferFrameOffset = asioDriverInfo.pahsc_InputBufferOffset; - asioDriverInfo.pahsc_userOutputBufferFrameOffset = asioDriverInfo.past->past_FramesPerUserBuffer; // empty - } + if( theAsioStream->outputChannelCount > 0 ) + theAsioStream->callbackFlags |= paOutputUnderflow; } - -//------------------------------------------------------------------------------------------------------------------------------------------------------- -// FIXME : optimization for Input only or output only modes (really necessary ??) -static void Pa_ASIO_Callback_Input( long index) +// check that the buffer index is not the previous index (which would indicate +// that a buffer was skipped. +static int previousIndex = 1; +if( index == previousIndex ) { - internalPortAudioStream *past = asioDriverInfo.past; - long framesInputHostBuffer = asioDriverInfo.past_FramesPerHostBuffer; // number of frames available into the host input buffer - long framesInputUserBuffer; // number of frames needed to complete the user input buffer - long framesOutputHostBuffer; // number of frames needed to complete the host output buffer - long framesOuputUserBuffer; // number of frames available into the user output buffer - long userResult; - long tmp; - - /* Fill host ASIO output with remaining frames in user output */ - framesOutputHostBuffer = asioDriverInfo.past_FramesPerHostBuffer; - framesOuputUserBuffer = asioDriverInfo.past->past_FramesPerUserBuffer - asioDriverInfo.pahsc_userOutputBufferFrameOffset; - tmp = min(framesOutputHostBuffer, framesOuputUserBuffer); - framesOutputHostBuffer -= tmp; - Pa_ASIO_Callback_Output(index,tmp); - - /* Available frames in hostInputBuffer */ - while (framesInputHostBuffer > 0) { - - /* Number of frames needed to complete an user input buffer */ - framesInputUserBuffer = asioDriverInfo.past->past_FramesPerUserBuffer - asioDriverInfo.pahsc_userInputBufferFrameOffset; - - if (framesInputHostBuffer >= framesInputUserBuffer) { - - /* Convert ASIO input to user input */ - Pa_ASIO_Convert_Inter_Input (asioDriverInfo.bufferInfos, - past->past_InputBuffer, - asioDriverInfo.pahsc_NumInputChannels , - asioDriverInfo.pahsc_NumOutputChannels, - framesInputUserBuffer, - asioDriverInfo.past_FramesPerHostBuffer - framesInputHostBuffer, - asioDriverInfo.pahsc_userInputBufferFrameOffset, - asioDriverInfo.pahsc_channelInfos[0].type, - past->past_InputSampleFormat, - past->past_Flags, - index); - - /* Call PortAudio callback */ - userResult = asioDriverInfo.past->past_Callback(past->past_InputBuffer, past->past_OutputBuffer, - past->past_FramesPerUserBuffer,past->past_FrameCount,past->past_UserData ); - - /* User callback has asked us to stop in the middle of the host buffer */ - if( userResult != 0) { - - /* Put 0 in the end of the output buffer */ - Pa_ASIO_Clear_Output(asioDriverInfo.bufferInfos, - asioDriverInfo.pahsc_channelInfos[0].type, - asioDriverInfo.pahsc_NumInputChannels , - asioDriverInfo.pahsc_NumOutputChannels, - index, - asioDriverInfo.pahsc_hostOutputBufferFrameOffset, - asioDriverInfo.past_FramesPerHostBuffer - asioDriverInfo.pahsc_hostOutputBufferFrameOffset); - - past->past_StopSoon = 1; - return; - } - - - /* Full user ouput buffer : write offset */ - asioDriverInfo.pahsc_userOutputBufferFrameOffset = 0; - - /* Empty user input buffer : read offset */ - asioDriverInfo.pahsc_userInputBufferFrameOffset = 0; - - /* Fill host ASIO output */ - tmp = min (past->past_FramesPerUserBuffer,framesOutputHostBuffer); - Pa_ASIO_Callback_Output(index,tmp); - - framesOutputHostBuffer -= tmp; - framesInputHostBuffer -= framesInputUserBuffer; - - }else { - - /* Convert ASIO input to user input */ - Pa_ASIO_Convert_Inter_Input (asioDriverInfo.bufferInfos, - past->past_InputBuffer, - asioDriverInfo.pahsc_NumInputChannels , - asioDriverInfo.pahsc_NumOutputChannels, - framesInputHostBuffer, - asioDriverInfo.past_FramesPerHostBuffer - framesInputHostBuffer, - asioDriverInfo.pahsc_userInputBufferFrameOffset, - asioDriverInfo.pahsc_channelInfos[0].type, - past->past_InputSampleFormat, - past->past_Flags, - index); - - /* Update pahsc_userInputBufferFrameOffset */ - asioDriverInfo.pahsc_userInputBufferFrameOffset += framesInputHostBuffer; - - /* Update framesInputHostBuffer */ - framesInputHostBuffer = 0; - } - } + if( theAsioStream->inputChannelCount > 0 ) + theAsioStream->callbackFlags |= paInputOverflow; + if( theAsioStream->outputChannelCount > 0 ) + theAsioStream->callbackFlags |= paOutputUnderflow; } +previousIndex = index; +#endif -//------------------------------------------------------------------------------------------------------------------------------------------------------- -static void Pa_ASIO_Callback_Output(long index, long framePerBuffer) -{ - internalPortAudioStream *past = asioDriverInfo.past; - - if (framePerBuffer > 0) { - - /* Convert user output to ASIO ouput */ - Pa_ASIO_Convert_Inter_Output (asioDriverInfo.bufferInfos, - past->past_OutputBuffer, - asioDriverInfo.pahsc_NumInputChannels, - asioDriverInfo.pahsc_NumOutputChannels, - framePerBuffer, - asioDriverInfo.pahsc_hostOutputBufferFrameOffset, - asioDriverInfo.pahsc_userOutputBufferFrameOffset, - asioDriverInfo.pahsc_channelInfos[0].type, - past->past_InputSampleFormat, - past->past_Flags, - index); - - /* Update hostOuputFrameOffset */ - asioDriverInfo.pahsc_hostOutputBufferFrameOffset += framePerBuffer; + int i; - /* Update userOutputFrameOffset */ - asioDriverInfo.pahsc_userOutputBufferFrameOffset += framePerBuffer; - } -} -//------------------------------------------------------------------------------------------------------------------------------------------------------- -static void Pa_ASIO_Callback_End() - { - /* Empty ASIO ouput : write offset */ - asioDriverInfo.pahsc_hostOutputBufferFrameOffset = 0; - } - -//------------------------------------------------------------------------------------------------------------------------------------------------------- -static void Pa_ASIO_Clear_User_Buffers() -{ - if( asioDriverInfo.past->past_InputBuffer != NULL ) - { - memset( asioDriverInfo.past->past_InputBuffer, 0, asioDriverInfo.past->past_InputBufferSize ); - } - if( asioDriverInfo.past->past_OutputBuffer != NULL ) - { - memset( asioDriverInfo.past->past_OutputBuffer, 0, asioDriverInfo.past->past_OutputBufferSize ); - } -} + PaUtil_BeginCpuLoadMeasurement( &theAsioStream->cpuLoadMeasurer ); -//------------------------------------------------------------------------------------------------------------------------------------------------------- - static void Pa_ASIO_Clear_Output(ASIOBufferInfo* nativeBuffer, - ASIOSampleType nativeFormat, - long NumInputChannels, - long NumOuputChannels, - long index, - long hostFrameOffset, - long frames) -{ - - switch (nativeFormat) { - - case ASIOSTInt16MSB: - case ASIOSTInt16LSB: - case ASIOSTInt32MSB16: - case ASIOSTInt32LSB16: - Pa_ASIO_Clear_Output_16(nativeBuffer, frames, NumInputChannels, NumOuputChannels, index, hostFrameOffset); - break; - - case ASIOSTFloat64MSB: - case ASIOSTFloat64LSB: - break; - - case ASIOSTFloat32MSB: - case ASIOSTFloat32LSB: - case ASIOSTInt32MSB: - case ASIOSTInt32LSB: - case ASIOSTInt32MSB18: - case ASIOSTInt32MSB20: - case ASIOSTInt32MSB24: - case ASIOSTInt32LSB18: - case ASIOSTInt32LSB20: - case ASIOSTInt32LSB24: - Pa_ASIO_Clear_Output_32(nativeBuffer, frames, NumInputChannels, NumOuputChannels, index, hostFrameOffset); - break; - - case ASIOSTInt24MSB: - case ASIOSTInt24LSB: - break; - - default: - break; - } -} + PaStreamCallbackTimeInfo paTimeInfo; + // asio systemTime is supposed to be measured according to the same + // clock as timeGetTime + paTimeInfo.currentTime = (ASIO64toDouble( timeInfo->timeInfo.systemTime ) * .000000001); -//--------------------------------------------------------------------------------------- -static void Pa_ASIO_Convert_Inter_Input( - ASIOBufferInfo* nativeBuffer, - void* inputBuffer, - long NumInputChannels, - long NumOuputChannels, - long framePerBuffer, - long hostFrameOffset, - long userFrameOffset, - ASIOSampleType nativeFormat, - PaSampleFormat paFormat, - PaStreamFlags flags, - long index) -{ - - if((NumInputChannels > 0) && (nativeBuffer != NULL)) - { - /* Convert from native format to PA format. */ - switch(paFormat) - { - case paFloat32: - { - float *inBufPtr = (float *) inputBuffer; - - switch (nativeFormat) { - case ASIOSTInt16LSB: - Input_Int16_Float32(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset, userFrameOffset, swap); - break; - case ASIOSTInt16MSB: - Input_Int16_Float32(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset, userFrameOffset,!swap); - break; - case ASIOSTInt32LSB: - Input_Int32_Float32(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset, userFrameOffset,swap); - break; - case ASIOSTInt32MSB: - Input_Int32_Float32(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset, userFrameOffset,!swap); - break; - case ASIOSTFloat32LSB: // IEEE 754 32 bit float, as found on Intel x86 architecture - Input_Float32_Float32(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset, userFrameOffset,swap); - break; - case ASIOSTFloat32MSB: // IEEE 754 32 bit float, as found on Intel x86 architecture - Input_Float32_Float32(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset, userFrameOffset,!swap); - break; - - case ASIOSTInt24LSB: // used for 20 bits as well - case ASIOSTInt24MSB: // used for 20 bits as well - - case ASIOSTFloat64LSB: // IEEE 754 64 bit double float, as found on Intel x86 architecture - case ASIOSTFloat64MSB: // IEEE 754 64 bit double float, as found on Intel x86 architecture - - // these are used for 32 bit data buffer, with different alignment of the data inside - // 32 bit PCI bus systems can more easily used with these - - case ASIOSTInt32LSB16: // 32 bit data with 16 bit alignment - case ASIOSTInt32LSB18: // 32 bit data with 18 bit alignment - case ASIOSTInt32LSB20: // 32 bit data with 20 bit alignment - case ASIOSTInt32LSB24: // 32 bit data with 24 bit alignment - - - case ASIOSTInt32MSB16: // 32 bit data with 16 bit alignment - case ASIOSTInt32MSB18: // 32 bit data with 18 bit alignment - case ASIOSTInt32MSB20: // 32 bit data with 20 bit alignment - case ASIOSTInt32MSB24: // 32 bit data with 24 bit alignment - DBUG(("Not yet implemented : please report the problem\n")); - break; - } - - break; - } - - case paInt32: - { - long *inBufPtr = (long *)inputBuffer; - - switch (nativeFormat) { - case ASIOSTInt16LSB: - Input_Int16_Int32(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset,userFrameOffset, swap); - break; - case ASIOSTInt16MSB: - Input_Int16_Int32(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset,userFrameOffset, !swap); - break; - case ASIOSTInt32LSB: - Input_Int32_Int32(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset,userFrameOffset, swap); - break; - case ASIOSTInt32MSB: - Input_Int32_Int32(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset,userFrameOffset, !swap); - break; - case ASIOSTFloat32LSB: // IEEE 754 32 bit float, as found on Intel x86 architecture - Input_Float32_Int32(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset,userFrameOffset, swap); - break; - case ASIOSTFloat32MSB: // IEEE 754 32 bit float, as found on Intel x86 architecture - Input_Float32_Int32(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset,userFrameOffset, !swap); - break; - - case ASIOSTInt24LSB: // used for 20 bits as well - case ASIOSTInt24MSB: // used for 20 bits as well - - case ASIOSTFloat64LSB: // IEEE 754 64 bit double float, as found on Intel x86 architecture - case ASIOSTFloat64MSB: // IEEE 754 64 bit double float, as found on Intel x86 architecture - - // these are used for 32 bit data buffer, with different alignment of the data inside - // 32 bit PCI bus systems can more easily used with these - - case ASIOSTInt32LSB16: // 32 bit data with 16 bit alignment - case ASIOSTInt32LSB18: // 32 bit data with 18 bit alignment - case ASIOSTInt32LSB20: // 32 bit data with 20 bit alignment - case ASIOSTInt32LSB24: // 32 bit data with 24 bit alignment - - - case ASIOSTInt32MSB16: // 32 bit data with 16 bit alignment - case ASIOSTInt32MSB18: // 32 bit data with 18 bit alignment - case ASIOSTInt32MSB20: // 32 bit data with 20 bit alignment - case ASIOSTInt32MSB24: // 32 bit data with 24 bit alignment - DBUG(("Not yet implemented : please report the problem\n")); - break; - - } - break; - } - - case paInt16: - { - short *inBufPtr = (short *) inputBuffer; - - switch (nativeFormat) { - case ASIOSTInt16LSB: - Input_Int16_Int16(nativeBuffer, inBufPtr, framePerBuffer , NumInputChannels, index , hostFrameOffset,userFrameOffset, swap); - break; - case ASIOSTInt16MSB: - Input_Int16_Int16(nativeBuffer, inBufPtr, framePerBuffer , NumInputChannels, index , hostFrameOffset,userFrameOffset, !swap); - break; - case ASIOSTInt32LSB: - Input_Int32_Int16(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset,userFrameOffset, flags,swap); - break; - case ASIOSTInt32MSB: - Input_Int32_Int16(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset,userFrameOffset, flags,!swap); - break; - case ASIOSTFloat32LSB: // IEEE 754 32 bit float, as found on Intel x86 architecture - Input_Float32_Int16(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset,userFrameOffset, flags,swap); - break; - case ASIOSTFloat32MSB: // IEEE 754 32 bit float, as found on Intel x86 architecture - Input_Float32_Int16(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset,userFrameOffset, flags,!swap); - break; - - case ASIOSTInt24LSB: // used for 20 bits as well - case ASIOSTInt24MSB: // used for 20 bits as well - - case ASIOSTFloat64LSB: // IEEE 754 64 bit double float, as found on Intel x86 architecture - case ASIOSTFloat64MSB: // IEEE 754 64 bit double float, as found on Intel x86 architecture - - // these are used for 32 bit data buffer, with different alignment of the data inside - // 32 bit PCI bus systems can more easily used with these - - case ASIOSTInt32LSB16: // 32 bit data with 16 bit alignment - case ASIOSTInt32LSB18: // 32 bit data with 18 bit alignment - case ASIOSTInt32LSB20: // 32 bit data with 20 bit alignment - case ASIOSTInt32LSB24: // 32 bit data with 24 bit alignment - - - case ASIOSTInt32MSB16: // 32 bit data with 16 bit alignment - case ASIOSTInt32MSB18: // 32 bit data with 18 bit alignment - case ASIOSTInt32MSB20: // 32 bit data with 20 bit alignment - case ASIOSTInt32MSB24: // 32 bit data with 24 bit alignment - DBUG(("Not yet implemented : please report the problem\n")); - break; - - } - break; - } + /* patch from Paul Boege */ + paTimeInfo.inputBufferAdcTime = paTimeInfo.currentTime - + ((double)theAsioStream->inputLatency/theAsioStream->streamRepresentation.streamInfo.sampleRate); - case paInt8: - { - /* Convert 16 bit data to 8 bit chars */ - - char *inBufPtr = (char *) inputBuffer; - - switch (nativeFormat) { - case ASIOSTInt16LSB: - Input_Int16_Int8(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset,userFrameOffset,flags,swap); - break; - case ASIOSTInt16MSB: - Input_Int16_Int8(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset,userFrameOffset, flags,!swap); - break; - case ASIOSTInt32LSB: - Input_Int32_Int8(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset,userFrameOffset, flags,swap); - break; - case ASIOSTInt32MSB: - Input_Int32_Int8(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset,userFrameOffset, flags,!swap); - break; - case ASIOSTFloat32LSB: // IEEE 754 32 bit float, as found on Intel x86 architecture - Input_Float32_Int8(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset,userFrameOffset, flags,swap); - break; - case ASIOSTFloat32MSB: // IEEE 754 32 bit float, as found on Intel x86 architecture - Input_Float32_Int8(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset,userFrameOffset, flags,!swap); - break; - - case ASIOSTInt24LSB: // used for 20 bits as well - case ASIOSTInt24MSB: // used for 20 bits as well - - case ASIOSTFloat64LSB: // IEEE 754 64 bit double float, as found on Intel x86 architecture - case ASIOSTFloat64MSB: // IEEE 754 64 bit double float, as found on Intel x86 architecture - - // these are used for 32 bit data buffer, with different alignment of the data inside - // 32 bit PCI bus systems can more easily used with these - - case ASIOSTInt32LSB16: // 32 bit data with 16 bit alignment - case ASIOSTInt32LSB18: // 32 bit data with 18 bit alignment - case ASIOSTInt32LSB20: // 32 bit data with 20 bit alignment - case ASIOSTInt32LSB24: // 32 bit data with 24 bit alignment - - - case ASIOSTInt32MSB16: // 32 bit data with 16 bit alignment - case ASIOSTInt32MSB18: // 32 bit data with 18 bit alignment - case ASIOSTInt32MSB20: // 32 bit data with 20 bit alignment - case ASIOSTInt32MSB24: // 32 bit data with 24 bit alignment - DBUG(("Not yet implemented : please report the problem\n")); - break; - } - break; - } + paTimeInfo.outputBufferDacTime = paTimeInfo.currentTime + + ((double)theAsioStream->outputLatency/theAsioStream->streamRepresentation.streamInfo.sampleRate); - case paUInt8: - { - /* Convert 16 bit data to 8 bit unsigned chars */ - - unsigned char *inBufPtr = (unsigned char *)inputBuffer; - - switch (nativeFormat) { - case ASIOSTInt16LSB: - Input_Int16_IntU8(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset,userFrameOffset, flags,swap); - break; - case ASIOSTInt16MSB: - Input_Int16_IntU8(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset,userFrameOffset, flags,!swap); - break; - case ASIOSTInt32LSB: - Input_Int32_IntU8(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset,userFrameOffset,flags,swap); - break; - case ASIOSTInt32MSB: - Input_Int32_IntU8(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset,userFrameOffset, flags,!swap); - break; - case ASIOSTFloat32LSB: // IEEE 754 32 bit float, as found on Intel x86 architecture - Input_Float32_IntU8(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset,userFrameOffset,flags,swap); - break; - case ASIOSTFloat32MSB: // IEEE 754 32 bit float, as found on Intel x86 architecture - Input_Float32_IntU8(nativeBuffer, inBufPtr, framePerBuffer, NumInputChannels, index, hostFrameOffset,userFrameOffset,flags,!swap); - break; - - case ASIOSTInt24LSB: // used for 20 bits as well - case ASIOSTInt24MSB: // used for 20 bits as well - - case ASIOSTFloat64LSB: // IEEE 754 64 bit double float, as found on Intel x86 architecture - case ASIOSTFloat64MSB: // IEEE 754 64 bit double float, as found on Intel x86 architecture - - // these are used for 32 bit data buffer, with different alignment of the data inside - // 32 bit PCI bus systems can more easily used with these - - case ASIOSTInt32LSB16: // 32 bit data with 16 bit alignment - case ASIOSTInt32LSB18: // 32 bit data with 18 bit alignment - case ASIOSTInt32LSB20: // 32 bit data with 20 bit alignment - case ASIOSTInt32LSB24: // 32 bit data with 24 bit alignment - - - case ASIOSTInt32MSB16: // 32 bit data with 16 bit alignment - case ASIOSTInt32MSB18: // 32 bit data with 18 bit alignment - case ASIOSTInt32MSB20: // 32 bit data with 20 bit alignment - case ASIOSTInt32MSB24: // 32 bit data with 24 bit alignment - DBUG(("Not yet implemented : please report the problem\n")); - break; - - } - break; - } - - default: - break; - } - } -} + /* old version is buggy because the buffer processor also adds in its latency to the time parameters + paTimeInfo.inputBufferAdcTime = paTimeInfo.currentTime - theAsioStream->streamRepresentation.streamInfo.inputLatency; + paTimeInfo.outputBufferDacTime = paTimeInfo.currentTime + theAsioStream->streamRepresentation.streamInfo.outputLatency; + */ +#if 1 +// detect underflows by checking inter-callback time > 2 buffer period +static double previousTime = -1; +if( previousTime > 0 ){ + double delta = paTimeInfo.currentTime - previousTime; -//--------------------------------------------------------------------------------------- -static void Pa_ASIO_Convert_Inter_Output(ASIOBufferInfo* nativeBuffer, - void* outputBuffer, - long NumInputChannels, - long NumOuputChannels, - long framePerBuffer, - long hostFrameOffset, - long userFrameOffset, - ASIOSampleType nativeFormat, - PaSampleFormat paFormat, - PaStreamFlags flags, - long index) -{ - - if((NumOuputChannels > 0) && (nativeBuffer != NULL)) - { - /* Convert from PA format to native format */ - - switch(paFormat) - { - case paFloat32: - { - float *outBufPtr = (float *) outputBuffer; - - switch (nativeFormat) { - case ASIOSTInt16LSB: - Output_Float32_Int16(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset, userFrameOffset, flags, swap); - break; - case ASIOSTInt16MSB: - Output_Float32_Int16(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset, userFrameOffset, flags,!swap); - break; - case ASIOSTInt32LSB: - Output_Float32_Int32(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset, userFrameOffset, flags,swap); - break; - case ASIOSTInt32MSB: - Output_Float32_Int32(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset,userFrameOffset, flags,!swap); - break; - case ASIOSTFloat32LSB: - Output_Float32_Float32(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset,userFrameOffset,flags,swap); - break; - case ASIOSTFloat32MSB: - Output_Float32_Float32(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset,userFrameOffset, flags,!swap); - break; - - case ASIOSTInt24LSB: // used for 20 bits as well - case ASIOSTInt24MSB: // used for 20 bits as well - - case ASIOSTFloat64LSB: // IEEE 754 64 bit double float, as found on Intel x86 architecture - case ASIOSTFloat64MSB: // IEEE 754 64 bit double float, as found on Intel x86 architecture - - // these are used for 32 bit data buffer, with different alignment of the data inside - // 32 bit PCI bus systems can more easily used with these - - case ASIOSTInt32LSB16: // 32 bit data with 16 bit alignment - case ASIOSTInt32LSB18: // 32 bit data with 18 bit alignment - case ASIOSTInt32LSB20: // 32 bit data with 20 bit alignment - case ASIOSTInt32LSB24: // 32 bit data with 24 bit alignment - - - case ASIOSTInt32MSB16: // 32 bit data with 16 bit alignment - case ASIOSTInt32MSB18: // 32 bit data with 18 bit alignment - case ASIOSTInt32MSB20: // 32 bit data with 20 bit alignment - case ASIOSTInt32MSB24: // 32 bit data with 24 bit alignment - DBUG(("Not yet implemented : please report the problem\n")); - break; - } - break; - } - - case paInt32: - { - long *outBufPtr = (long *) outputBuffer; - - switch (nativeFormat) { - case ASIOSTInt16LSB: - Output_Int32_Int16(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset,userFrameOffset, flags,swap); - break; - case ASIOSTInt16MSB: - Output_Int32_Int16(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset,userFrameOffset, flags,!swap); - break; - case ASIOSTInt32LSB: - Output_Int32_Int32(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset,userFrameOffset, flags,swap); - break; - case ASIOSTInt32MSB: - Output_Int32_Int32(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset,userFrameOffset, flags,!swap); - break; - case ASIOSTFloat32LSB: - Output_Int32_Float32(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset,userFrameOffset, flags,swap); - break; - case ASIOSTFloat32MSB: - Output_Int32_Float32(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset,userFrameOffset, flags,!swap); - break; - - case ASIOSTInt24LSB: // used for 20 bits as well - case ASIOSTInt24MSB: // used for 20 bits as well - - case ASIOSTFloat64LSB: // IEEE 754 64 bit double float, as found on Intel x86 architecture - case ASIOSTFloat64MSB: // IEEE 754 64 bit double float, as found on Intel x86 architecture - - // these are used for 32 bit data buffer, with different alignment of the data inside - // 32 bit PCI bus systems can more easily used with these - - case ASIOSTInt32LSB16: // 32 bit data with 16 bit alignment - case ASIOSTInt32LSB18: // 32 bit data with 18 bit alignment - case ASIOSTInt32LSB20: // 32 bit data with 20 bit alignment - case ASIOSTInt32LSB24: // 32 bit data with 24 bit alignment - - - case ASIOSTInt32MSB16: // 32 bit data with 16 bit alignment - case ASIOSTInt32MSB18: // 32 bit data with 18 bit alignment - case ASIOSTInt32MSB20: // 32 bit data with 20 bit alignment - case ASIOSTInt32MSB24: // 32 bit data with 24 bit alignment - DBUG(("Not yet implemented : please report the problem\n")); - break; - } - break; - } - - case paInt16: - { - short *outBufPtr = (short *) outputBuffer; - - switch (nativeFormat) { - case ASIOSTInt16LSB: - Output_Int16_Int16(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset,userFrameOffset, swap); - break; - case ASIOSTInt16MSB: - Output_Int16_Int16(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset,userFrameOffset, !swap); - break; - case ASIOSTInt32LSB: - Output_Int16_Int32(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset,userFrameOffset, swap); - break; - case ASIOSTInt32MSB: - Output_Int16_Int32(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset,userFrameOffset, !swap); - break; - case ASIOSTFloat32LSB: - Output_Int16_Float32(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset,userFrameOffset, swap); - break; - case ASIOSTFloat32MSB: - Output_Int16_Float32(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset,userFrameOffset, !swap); - break; - - case ASIOSTInt24LSB: // used for 20 bits as well - case ASIOSTInt24MSB: // used for 20 bits as well - - case ASIOSTFloat64LSB: // IEEE 754 64 bit double float, as found on Intel x86 architecture - case ASIOSTFloat64MSB: // IEEE 754 64 bit double float, as found on Intel x86 architecture - - // these are used for 32 bit data buffer, with different alignment of the data inside - // 32 bit PCI bus systems can more easily used with these - - case ASIOSTInt32LSB16: // 32 bit data with 16 bit alignment - case ASIOSTInt32LSB18: // 32 bit data with 18 bit alignment - case ASIOSTInt32LSB20: // 32 bit data with 20 bit alignment - case ASIOSTInt32LSB24: // 32 bit data with 24 bit alignment - - - case ASIOSTInt32MSB16: // 32 bit data with 16 bit alignment - case ASIOSTInt32MSB18: // 32 bit data with 18 bit alignment - case ASIOSTInt32MSB20: // 32 bit data with 20 bit alignment - case ASIOSTInt32MSB24: // 32 bit data with 24 bit alignment - DBUG(("Not yet implemented : please report the problem\n")); - break; - - } - break; - } - - - case paInt8: - { - char *outBufPtr = (char *) outputBuffer; - - switch (nativeFormat) { - case ASIOSTInt16LSB: - Output_Int8_Int16(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset,userFrameOffset, swap); - break; - case ASIOSTInt16MSB: - Output_Int8_Int16(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset,userFrameOffset, !swap); - break; - case ASIOSTInt32LSB: - Output_Int8_Int32(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset,userFrameOffset, swap); - break; - case ASIOSTInt32MSB: - Output_Int8_Int32(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset,userFrameOffset, !swap); - break; - case ASIOSTFloat32LSB: - Output_Int8_Float32(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset,userFrameOffset, swap); - break; - case ASIOSTFloat32MSB: - Output_Int8_Float32(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset,userFrameOffset, !swap); - break; - - case ASIOSTInt24LSB: // used for 20 bits as well - case ASIOSTInt24MSB: // used for 20 bits as well - - case ASIOSTFloat64LSB: // IEEE 754 64 bit double float, as found on Intel x86 architecture - case ASIOSTFloat64MSB: // IEEE 754 64 bit double float, as found on Intel x86 architecture - - // these are used for 32 bit data buffer, with different alignment of the data inside - // 32 bit PCI bus systems can more easily used with these - - case ASIOSTInt32LSB16: // 32 bit data with 16 bit alignment - case ASIOSTInt32LSB18: // 32 bit data with 18 bit alignment - case ASIOSTInt32LSB20: // 32 bit data with 20 bit alignment - case ASIOSTInt32LSB24: // 32 bit data with 24 bit alignment - - - case ASIOSTInt32MSB16: // 32 bit data with 16 bit alignment - case ASIOSTInt32MSB18: // 32 bit data with 18 bit alignment - case ASIOSTInt32MSB20: // 32 bit data with 20 bit alignment - case ASIOSTInt32MSB24: // 32 bit data with 24 bit alignment - DBUG(("Not yet implemented : please report the problem\n")); - break; - } - break; - } - - case paUInt8: - { - unsigned char *outBufPtr = (unsigned char *) outputBuffer; - - switch (nativeFormat) { - case ASIOSTInt16LSB: - Output_IntU8_Int16(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset,userFrameOffset, swap); - break; - case ASIOSTInt16MSB: - Output_IntU8_Int16(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset,userFrameOffset, !swap); - break; - case ASIOSTInt32LSB: - Output_IntU8_Int32(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset,userFrameOffset, swap); - break; - case ASIOSTInt32MSB: - Output_IntU8_Int32(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset,userFrameOffset, !swap); - break; - case ASIOSTFloat32LSB: - Output_IntU8_Float32(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset,userFrameOffset, swap); - break; - case ASIOSTFloat32MSB: - Output_IntU8_Float32(nativeBuffer, outBufPtr, framePerBuffer, NumInputChannels, NumOuputChannels, index, hostFrameOffset,userFrameOffset, !swap); - break; - - case ASIOSTInt24LSB: // used for 20 bits as well - case ASIOSTInt24MSB: // used for 20 bits as well - - case ASIOSTFloat64LSB: // IEEE 754 64 bit double float, as found on Intel x86 architecture - case ASIOSTFloat64MSB: // IEEE 754 64 bit double float, as found on Intel x86 architecture - - // these are used for 32 bit data buffer, with different alignment of the data inside - // 32 bit PCI bus systems can more easily used with these - - case ASIOSTInt32LSB16: // 32 bit data with 16 bit alignment - case ASIOSTInt32LSB18: // 32 bit data with 18 bit alignment - case ASIOSTInt32LSB20: // 32 bit data with 20 bit alignment - case ASIOSTInt32LSB24: // 32 bit data with 24 bit alignment - - - case ASIOSTInt32MSB16: // 32 bit data with 16 bit alignment - case ASIOSTInt32MSB18: // 32 bit data with 18 bit alignment - case ASIOSTInt32MSB20: // 32 bit data with 20 bit alignment - case ASIOSTInt32MSB24: // 32 bit data with 24 bit alignment - DBUG(("Not yet implemented : please report the problem\n")); - break; - } - break; - } - - default: - break; - } - } + if( delta >= 2. * (theAsioStream->framesPerHostCallback / theAsioStream->streamRepresentation.streamInfo.sampleRate) ){ + if( theAsioStream->inputChannelCount > 0 ) + theAsioStream->callbackFlags |= paInputOverflow; + if( theAsioStream->outputChannelCount > 0 ) + theAsioStream->callbackFlags |= paOutputUnderflow; + } } +previousTime = paTimeInfo.currentTime; +#endif + // note that the above input and output times do not need to be + // adjusted for the latency of the buffer processor -- the buffer + // processor handles that. + if( theAsioStream->inputBufferConverter ) + { + for( i=0; iinputChannelCount; i++ ) + { + theAsioStream->inputBufferConverter( theAsioStream->inputBufferPtrs[index][i], + theAsioStream->inputShift, theAsioStream->framesPerHostCallback ); + } + } -/* Load a ASIO driver corresponding to the required device */ -static PaError Pa_ASIO_loadDevice (long device) -{ - PaDeviceInfo * dev = &(sDevices[device].pad_Info); + PaUtil_BeginBufferProcessing( &theAsioStream->bufferProcessor, &paTimeInfo, theAsioStream->callbackFlags ); - if (!Pa_ASIO_loadAsioDriver((char *) dev->name)) return paHostError; - if (ASIOInit(&asioDriverInfo.pahsc_driverInfo) != ASE_OK) return paHostError; - if (ASIOGetChannels(&asioDriverInfo.pahsc_NumInputChannels, &asioDriverInfo.pahsc_NumOutputChannels) != ASE_OK) return paHostError; - if (ASIOGetBufferSize(&asioDriverInfo.pahsc_minSize, &asioDriverInfo.pahsc_maxSize, &asioDriverInfo.pahsc_preferredSize, &asioDriverInfo.pahsc_granularity) != ASE_OK) return paHostError; - - if(ASIOOutputReady() == ASE_OK) - asioDriverInfo.pahsc_postOutput = true; - else - asioDriverInfo.pahsc_postOutput = false; - - return paNoError; -} + /* reset status flags once they've been passed to the callback */ + theAsioStream->callbackFlags = 0; -//--------------------------------------------------- -static int GetHighestBitPosition (unsigned long n) -{ - int pos = -1; - while( n != 0 ) - { - pos++; - n = n >> 1; - } - return pos; -} + PaUtil_SetInputFrameCount( &theAsioStream->bufferProcessor, 0 /* default to host buffer size */ ); + for( i=0; iinputChannelCount; ++i ) + PaUtil_SetNonInterleavedInputChannel( &theAsioStream->bufferProcessor, i, theAsioStream->inputBufferPtrs[index][i] ); -//------------------------------------------------------------------------------------------ -static int GetFirstMultiple(long min, long val ){ return ((min + val - 1) / val) * val; } + PaUtil_SetOutputFrameCount( &theAsioStream->bufferProcessor, 0 /* default to host buffer size */ ); + for( i=0; ioutputChannelCount; ++i ) + PaUtil_SetNonInterleavedOutputChannel( &theAsioStream->bufferProcessor, i, theAsioStream->outputBufferPtrs[index][i] ); -//------------------------------------------------------------------------------------------ -static int GetFirstPossibleDivisor(long max, long val ) -{ - for (int i = 2; i < 20; i++) {if (((val%i) == 0) && ((val/i) <= max)) return (val/i); } - return val; -} + int callbackResult; + if( theAsioStream->stopProcessing ) + callbackResult = paComplete; + else + callbackResult = paContinue; + unsigned long framesProcessed = PaUtil_EndBufferProcessing( &theAsioStream->bufferProcessor, &callbackResult ); -//------------------------------------------------------------------------ -static int IsPowerOfTwo( unsigned long n ) { return ((n & (n-1)) == 0); } + if( theAsioStream->outputBufferConverter ) + { + for( i=0; ioutputChannelCount; i++ ) + { + theAsioStream->outputBufferConverter( theAsioStream->outputBufferPtrs[index][i], + theAsioStream->outputShift, theAsioStream->framesPerHostCallback ); + } + } + PaUtil_EndCpuLoadMeasurement( &theAsioStream->cpuLoadMeasurer, framesProcessed ); -/******************************************************************* -* Determine size of native ASIO audio buffer size -* Input parameters : FramesPerUserBuffer, NumUserBuffers -* Output values : FramesPerHostBuffer, OutputBufferOffset or InputtBufferOffset -*/ + // Finally if the driver supports the ASIOOutputReady() optimization, + // do it here, all data are in place + if( theAsioStream->postOutput ) + ASIOOutputReady(); -static PaError PaHost_CalcNumHostBuffers( internalPortAudioStream *past ) -{ - PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; - long requestedBufferSize; - long firstMultiple, firstDivisor; - - // Compute requestedBufferSize - if( past->past_NumUserBuffers < 1 ){ - requestedBufferSize = past->past_FramesPerUserBuffer; - }else{ - requestedBufferSize = past->past_NumUserBuffers * past->past_FramesPerUserBuffer; - } - - // Adjust FramesPerHostBuffer using requestedBufferSize, ASIO minSize and maxSize, - if (requestedBufferSize < asioDriverInfo.pahsc_minSize){ - - firstMultiple = GetFirstMultiple(asioDriverInfo.pahsc_minSize, requestedBufferSize); - - if (firstMultiple <= asioDriverInfo.pahsc_maxSize) - asioDriverInfo.past_FramesPerHostBuffer = firstMultiple; - else - asioDriverInfo.past_FramesPerHostBuffer = asioDriverInfo.pahsc_minSize; - - }else if (requestedBufferSize > asioDriverInfo.pahsc_maxSize){ - - firstDivisor = GetFirstPossibleDivisor(asioDriverInfo.pahsc_maxSize, requestedBufferSize); - - if ((firstDivisor >= asioDriverInfo.pahsc_minSize) && (firstDivisor <= asioDriverInfo.pahsc_maxSize)) - asioDriverInfo.past_FramesPerHostBuffer = firstDivisor; - else - asioDriverInfo.past_FramesPerHostBuffer = asioDriverInfo.pahsc_maxSize; - }else{ - asioDriverInfo.past_FramesPerHostBuffer = requestedBufferSize; - } - - // If ASIO buffer size needs to be a power of two - if( asioDriverInfo.pahsc_granularity < 0 ){ - // Needs to be a power of two. - - if( !IsPowerOfTwo( asioDriverInfo.past_FramesPerHostBuffer ) ) + if( callbackResult == paContinue ) { - int highestBit = GetHighestBitPosition(asioDriverInfo.past_FramesPerHostBuffer); - asioDriverInfo.past_FramesPerHostBuffer = 1 << (highestBit + 1); + /* nothing special to do */ } + else if( callbackResult == paAbort ) + { + /* finish playback immediately */ + theAsioStream->isActive = 0; + if( theAsioStream->streamRepresentation.streamFinishedCallback != 0 ) + theAsioStream->streamRepresentation.streamFinishedCallback( theAsioStream->streamRepresentation.userData ); + theAsioStream->streamFinishedCallbackCalled = true; + SetEvent( theAsioStream->completedBuffersPlayedEvent ); + theAsioStream->zeroOutput = true; + } + else /* paComplete or other non-zero value indicating complete */ + { + /* Finish playback once currently queued audio has completed. */ + theAsioStream->stopProcessing = true; + + if( PaUtil_IsBufferProcessorOutputEmpty( &theAsioStream->bufferProcessor ) ) + { + theAsioStream->zeroOutput = true; + theAsioStream->stopPlayoutCount = 0; + } + } + } } - DBUG(("----------------------------------\n")); - DBUG(("PortAudio : minSize = %ld \n",asioDriverInfo.pahsc_minSize)); - DBUG(("PortAudio : preferredSize = %ld \n",asioDriverInfo.pahsc_preferredSize)); - DBUG(("PortAudio : maxSize = %ld \n",asioDriverInfo.pahsc_maxSize)); - DBUG(("PortAudio : granularity = %ld \n",asioDriverInfo.pahsc_granularity)); - DBUG(("PortAudio : User buffer size = %d\n", asioDriverInfo.past->past_FramesPerUserBuffer )); - DBUG(("PortAudio : ASIO buffer size = %d\n", asioDriverInfo.past_FramesPerHostBuffer )); - - if (asioDriverInfo.past_FramesPerHostBuffer > past->past_FramesPerUserBuffer){ - - // Computes the MINIMUM value of null frames shift for the output buffer alignement - asioDriverInfo.pahsc_OutputBufferOffset = Pa_ASIO_CalcFrameShift (asioDriverInfo.past_FramesPerHostBuffer,past->past_FramesPerUserBuffer); - asioDriverInfo.pahsc_InputBufferOffset = 0; - DBUG(("PortAudio : Minimum BufferOffset for Output = %d\n", asioDriverInfo.pahsc_OutputBufferOffset)); - }else{ - - //Computes the MINIMUM value of null frames shift for the input buffer alignement - asioDriverInfo.pahsc_InputBufferOffset = Pa_ASIO_CalcFrameShift (asioDriverInfo.past_FramesPerHostBuffer,past->past_FramesPerUserBuffer); - asioDriverInfo.pahsc_OutputBufferOffset = 0; - DBUG(("PortAudio : Minimum BufferOffset for Input = %d\n", asioDriverInfo.pahsc_InputBufferOffset)); - } - - return paNoError; + ++buffersDone; + }while( PaAsio_AtomicDecrement(&theAsioStream->reenterCount) >= 0 ); + + return 0L; } -/***********************************************************************/ -int Pa_CountDevices() +static void sampleRateChanged(ASIOSampleRate sRate) { - PaError err ; - - if( sNumDevices <= 0 ) + // TAKEN FROM THE ASIO SDK + // do whatever you need to do if the sample rate changed + // usually this only happens during external sync. + // Audio processing is not stopped by the driver, actual sample rate + // might not have even changed, maybe only the sample rate status of an + // AES/EBU or S/PDIF digital input at the audio device. + // You might have to update time/sample related conversion routines, etc. + + (void) sRate; /* unused parameter */ + PA_DEBUG( ("sampleRateChanged : %d \n", sRate)); +} + +static long asioMessages(long selector, long value, void* message, double* opt) +{ +// TAKEN FROM THE ASIO SDK + // currently the parameters "value", "message" and "opt" are not used. + long ret = 0; + + (void) message; /* unused parameters */ + (void) opt; + + PA_DEBUG( ("asioMessages : %d , %d \n", selector, value)); + + switch(selector) + { + case kAsioSelectorSupported: + if(value == kAsioResetRequest + || value == kAsioEngineVersion + || value == kAsioResyncRequest + || value == kAsioLatenciesChanged + // the following three were added for ASIO 2.0, you don't necessarily have to support them + || value == kAsioSupportsTimeInfo + || value == kAsioSupportsTimeCode + || value == kAsioSupportsInputMonitor) + ret = 1L; + break; + + case kAsioBufferSizeChange: + //printf("kAsioBufferSizeChange \n"); + break; + + case kAsioResetRequest: + // defer the task and perform the reset of the driver during the next "safe" situation + // You cannot reset the driver right now, as this code is called from the driver. + // Reset the driver is done by completely destruct is. I.e. ASIOStop(), ASIODisposeBuffers(), Destruction + // Afterwards you initialize the driver again. + + /*FIXME: commented the next line out */ + //asioDriverInfo.stopped; // In this sample the processing will just stop + ret = 1L; + break; + + case kAsioResyncRequest: + // This informs the application, that the driver encountered some non fatal data loss. + // It is used for synchronization purposes of different media. + // Added mainly to work around the Win16Mutex problems in Windows 95/98 with the + // Windows Multimedia system, which could loose data because the Mutex was hold too long + // by another thread. + // However a driver can issue it in other situations, too. + ret = 1L; + break; + + case kAsioLatenciesChanged: + // This will inform the host application that the drivers were latencies changed. + // Beware, it this does not mean that the buffer sizes have changed! + // You might need to update internal delay data. + ret = 1L; + //printf("kAsioLatenciesChanged \n"); + break; + + case kAsioEngineVersion: + // return the supported ASIO version of the host application + // If a host applications does not implement this selector, ASIO 1.0 is assumed + // by the driver + ret = 2L; + break; + + case kAsioSupportsTimeInfo: + // informs the driver wether the asioCallbacks.bufferSwitchTimeInfo() callback + // is supported. + // For compatibility with ASIO 1.0 drivers the host application should always support + // the "old" bufferSwitch method, too. + ret = 1; + break; + + case kAsioSupportsTimeCode: + // informs the driver wether application is interested in time code info. + // If an application does not need to know about time code, the driver has less work + // to do. + ret = 0; + break; + } + return ret; +} + + +static PaError StartStream( PaStream *s ) +{ + PaError result = paNoError; + PaAsioStream *stream = (PaAsioStream*)s; + ASIOError asioError; + + if( stream->outputChannelCount > 0 ) + { + ZeroOutputBuffers( stream, 0 ); + ZeroOutputBuffers( stream, 1 ); + } + + PaUtil_ResetBufferProcessor( &stream->bufferProcessor ); + stream->stopProcessing = false; + stream->zeroOutput = false; + + /* Reentrancy counter initialisation */ + stream->reenterCount = -1; + stream->reenterError = 0; + + stream->callbackFlags = 0; + + if( ResetEvent( stream->completedBuffersPlayedEvent ) == 0 ) + { + result = paUnanticipatedHostError; + PA_ASIO_SET_LAST_SYSTEM_ERROR( GetLastError() ); + } + + if( result == paNoError ) + { + theAsioStream = stream; + asioError = ASIOStart(); + if( asioError == ASE_OK ) { - /* Force loading of ASIO drivers */ - err = Pa_ASIO_QueryDeviceInfo(sDevices); - if( err != paNoError ) goto error; + stream->isActive = 1; + stream->streamFinishedCallbackCalled = false; } - - return sNumDevices; - -error: - PaHost_Term(); - DBUG(("Pa_CountDevices: returns %d\n", err )); - return err; + else + { + theAsioStream = 0; + result = paUnanticipatedHostError; + PA_ASIO_SET_LAST_ASIO_ERROR( asioError ); + } + } + + return result; } -/***********************************************************************/ -PaError PaHost_Init( void ) + +static PaError StopStream( PaStream *s ) { - /* Have we already initialized the device info? */ - PaError err = (PaError) Pa_CountDevices(); - return ( err < 0 ) ? err : paNoError; -} + PaError result = paNoError; + PaAsioStream *stream = (PaAsioStream*)s; + ASIOError asioError; -/***********************************************************************/ -PaError PaHost_Term( void ) -{ - int i; - PaDeviceInfo *dev; - double *rates; - PaError result = paNoError; - - if (sNumDevices > 0) { - - /* Free allocated sample rate arrays and names*/ - for( i=0; isampleRates; - if ((rates != NULL)) PaHost_FreeFastMemory(rates, MAX_NUMSAMPLINGRATES * sizeof(double)); - dev->sampleRates = NULL; - if(dev->name != NULL) PaHost_FreeFastMemory((void *) dev->name, 32); - dev->name = NULL; - - } - - sNumDevices = 0; - - /* Dispose : if not done by Pa_CloseStream */ - if(ASIODisposeBuffers() != ASE_OK) result = paHostError; - if(ASIOExit() != ASE_OK) result = paHostError; - - /* remove the loaded ASIO driver */ - asioDrivers->removeCurrentDriver(); - } + if( stream->isActive ) + { + stream->stopProcessing = true; - return result; -} + /* wait for the stream to finish playing out enqueued buffers. + timeout after four times the stream latency. -/***********************************************************************/ -PaError PaHost_OpenStream( internalPortAudioStream *past ) -{ - PaError result = paNoError; - ASIOError err; - int32 device; - - /* Check if a stream already runs */ - if (asioDriverInfo.past != NULL) return paHostError; - - /* Check the device number */ - if ((past->past_InputDeviceID != paNoDevice) - &&(past->past_OutputDeviceID != paNoDevice) - &&(past->past_InputDeviceID != past->past_OutputDeviceID)) + @todo should use a better time out value - if the user buffer + length is longer than the asio buffer size then that should + be taken into account. + */ + if( WaitForSingleObject( theAsioStream->completedBuffersPlayedEvent, + (DWORD)(stream->streamRepresentation.streamInfo.outputLatency * 1000. * 4.) ) + == WAIT_TIMEOUT ) { - return paInvalidDeviceId; + PA_DEBUG(("WaitForSingleObject() timed out in StopStream()\n" )); } + } - /* Allocation */ - memset(&asioDriverInfo, 0, sizeof(PaHostSoundControl)); - past->past_DeviceData = (void*) &asioDriverInfo; - + asioError = ASIOStop(); + if( asioError != ASE_OK ) + { + result = paUnanticipatedHostError; + PA_ASIO_SET_LAST_ASIO_ERROR( asioError ); + } - /* FIXME */ - asioDriverInfo.past = past; - - /* load the ASIO device */ - device = (past->past_InputDeviceID < 0) ? past->past_OutputDeviceID : past->past_InputDeviceID; - result = Pa_ASIO_loadDevice(device); - if (result != paNoError) goto error; - - /* Check ASIO parameters and input parameters */ - if ((past->past_NumInputChannels > asioDriverInfo.pahsc_NumInputChannels) - || (past->past_NumOutputChannels > asioDriverInfo.pahsc_NumOutputChannels)) { - result = paInvalidChannelCount; - goto error; - } - - /* Set sample rate */ - if (ASIOSetSampleRate(past->past_SampleRate) != ASE_OK) { - result = paInvalidSampleRate; - goto error; - } - - /* if OK calc buffer size */ - result = PaHost_CalcNumHostBuffers( past ); - if (result != paNoError) goto error; - - - /* - Allocating input and output buffers number for the real past_NumInputChannels and past_NumOutputChannels - optimize the data transfer. - */ - - asioDriverInfo.pahsc_NumInputChannels = past->past_NumInputChannels; - asioDriverInfo.pahsc_NumOutputChannels = past->past_NumOutputChannels; - - /* Allocate ASIO buffers and callback*/ - err = Pa_ASIO_CreateBuffers(&asioDriverInfo, - asioDriverInfo.pahsc_NumInputChannels, - asioDriverInfo.pahsc_NumOutputChannels, - asioDriverInfo.past_FramesPerHostBuffer); - - if (err == ASE_OK) - return paNoError; - else if (err == ASE_NoMemory) - result = paInsufficientMemory; - else if (err == ASE_InvalidParameter) - result = paInvalidChannelCount; - else if (err == ASE_InvalidMode) - result = paBufferTooBig; - else - result = paHostError; - -error: - ASIOExit(); - return result; + theAsioStream = 0; + stream->isActive = 0; + + if( !stream->streamFinishedCallbackCalled ) + { + if( stream->streamRepresentation.streamFinishedCallback != 0 ) + stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData ); + } + return result; } -/***********************************************************************/ -PaError PaHost_CloseStream( internalPortAudioStream *past ) + +static PaError AbortStream( PaStream *s ) { - PaHostSoundControl *pahsc; - PaError result = paNoError; + PaError result = paNoError; + PaAsioStream *stream = (PaAsioStream*)s; + ASIOError asioError; - if( past == NULL ) return paBadStreamPtr; - pahsc = (PaHostSoundControl *) past->past_DeviceData; - if( pahsc == NULL ) return paNoError; + stream->zeroOutput = true; - #if PA_TRACE_START_STOP - AddTraceMessage( "PaHost_CloseStream: pahsc_HWaveOut ", (int) pahsc->pahsc_HWaveOut ); - #endif - - /* Dispose */ - if(ASIODisposeBuffers() != ASE_OK) result = paHostError; - if(ASIOExit() != ASE_OK) result = paHostError; - - /* Free data and device for output. */ - past->past_DeviceData = NULL; - asioDriverInfo.past = NULL; - - return result; -} + asioError = ASIOStop(); + if( asioError != ASE_OK ) + { + result = paUnanticipatedHostError; + PA_ASIO_SET_LAST_ASIO_ERROR( asioError ); + } + else + { + // make sure that the callback is not still in-flight when ASIOStop() + // returns. This has been observed to happen on the Hoontech DSP24 for + // example. + int count = 2000; // only wait for 2 seconds, rather than hanging. + while( theAsioStream->reenterCount != -1 && count > 0 ) + { + Sleep(1); + --count; + } + } -/***********************************************************************/ -PaError PaHost_StartOutput( internalPortAudioStream *past ) -{ - /* Clear the index 0 host output buffer */ - Pa_ASIO_Clear_Output(asioDriverInfo.bufferInfos, - asioDriverInfo.pahsc_channelInfos[0].type, - asioDriverInfo.pahsc_NumInputChannels, - asioDriverInfo.pahsc_NumOutputChannels, - 0, - 0, - asioDriverInfo.past_FramesPerHostBuffer); - - /* Clear the index 1 host output buffer */ - Pa_ASIO_Clear_Output(asioDriverInfo.bufferInfos, - asioDriverInfo.pahsc_channelInfos[0].type, - asioDriverInfo.pahsc_NumInputChannels, - asioDriverInfo.pahsc_NumOutputChannels, - 1, - 0, - asioDriverInfo.past_FramesPerHostBuffer); - - Pa_ASIO_Clear_User_Buffers(); + /* it is questionable whether we should zero theAsioStream if ASIOStop() + returns an error, because the callback could still be active. We assume + not - this is based on the fact that ASIOStop is unlikely to fail + if the callback is running - it's more likely to fail because the + callback is not running. */ - Pa_ASIO_Adaptor_Init(); + theAsioStream = 0; + stream->isActive = 0; - return paNoError; -} + if( !stream->streamFinishedCallbackCalled ) + { + if( stream->streamRepresentation.streamFinishedCallback != 0 ) + stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData ); + } -/***********************************************************************/ -PaError PaHost_StopOutput( internalPortAudioStream *past, int abort ) -{ - /* Nothing to do ?? */ - return paNoError; + return result; } -/***********************************************************************/ -PaError PaHost_StartInput( internalPortAudioStream *past ) -{ - /* Nothing to do ?? */ - return paNoError; -} -/***********************************************************************/ -PaError PaHost_StopInput( internalPortAudioStream *past, int abort ) +static PaError IsStreamStopped( PaStream *s ) { - /* Nothing to do */ - return paNoError; + //PaAsioStream *stream = (PaAsioStream*)s; + (void) s; /* unused parameter */ + return theAsioStream == 0; } -/***********************************************************************/ -PaError PaHost_StartEngine( internalPortAudioStream *past ) -{ - // TO DO : count of samples - past->past_IsActive = 1; - return (ASIOStart() == ASE_OK) ? paNoError : paHostError; -} -/***********************************************************************/ -PaError PaHost_StopEngine( internalPortAudioStream *past, int abort ) +static PaError IsStreamActive( PaStream *s ) { - // TO DO : count of samples - past->past_IsActive = 0; - return (ASIOStop() == ASE_OK) ? paNoError : paHostError; -} + PaAsioStream *stream = (PaAsioStream*)s; -/***********************************************************************/ -// TO BE CHECKED -PaError PaHost_StreamActive( internalPortAudioStream *past ) -{ - PaHostSoundControl *pahsc; - if( past == NULL ) return paBadStreamPtr; - pahsc = (PaHostSoundControl *) past->past_DeviceData; - if( pahsc == NULL ) return paInternalError; - return (PaError) past->past_IsActive; + return stream->isActive; } -/*************************************************************************/ -PaTimestamp Pa_StreamTime( PortAudioStream *stream ) -{ - PaHostSoundControl *pahsc; - internalPortAudioStream *past = (internalPortAudioStream *) stream; - if( past == NULL ) return paBadStreamPtr; - pahsc = (PaHostSoundControl *) past->past_DeviceData; - return pahsc->pahsc_NumFramesDone; -} -/************************************************************************* - * Allocate memory that can be accessed in real-time. - * This may need to be held in physical memory so that it is not - * paged to virtual memory. - * This call MUST be balanced with a call to PaHost_FreeFastMemory(). - */ -void *PaHost_AllocateFastMemory( long numBytes ) +static PaTime GetStreamTime( PaStream *s ) { - #if MAC - void *addr = NewPtrClear( numBytes ); - if( (addr == NULL) || (MemError () != 0) ) return NULL; - - #if (CARBON_COMPATIBLE == 0) - if( HoldMemory( addr, numBytes ) != noErr ) - { - DisposePtr( (Ptr) addr ); - return NULL; - } - #endif - return addr; - #elif WINDOWS - void *addr = malloc( numBytes ); /* FIXME - do we need physical memory? */ - if( addr != NULL ) memset( addr, 0, numBytes ); - return addr; - #endif + (void) s; /* unused parameter */ + return (double)timeGetTime() * .001; } -/************************************************************************* - * Free memory that could be accessed in real-time. - * This call MUST be balanced with a call to PaHost_AllocateFastMemory(). - */ -void PaHost_FreeFastMemory( void *addr, long numBytes ) + +static double GetStreamCpuLoad( PaStream* s ) { - #if MAC - if( addr == NULL ) return; - #if CARBON_COMPATIBLE - (void) numBytes; - #else - UnholdMemory( addr, numBytes ); - #endif - DisposePtr( (Ptr) addr ); - #elif WINDOWS - if( addr != NULL ) free( addr ); - #endif + PaAsioStream *stream = (PaAsioStream*)s; + + return PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer ); } -/*************************************************************************/ -void Pa_Sleep( long msec ) -{ - #if MAC - int32 sleepTime, endTime; - /* Convert to ticks. Round up so we sleep a MINIMUM of msec time. */ - sleepTime = ((msec * 60) + 999) / 1000; - if( sleepTime < 1 ) sleepTime = 1; - endTime = TickCount() + sleepTime; - do{ - DBUGX(("Sleep for %d ticks.\n", sleepTime )); - WaitNextEvent( 0, NULL, sleepTime, NULL ); /* Use this just to sleep without getting events. */ - sleepTime = endTime - TickCount(); - } while( sleepTime > 0 ); - #elif WINDOWS - Sleep( msec ); - #endif -} +/* + As separate stream interfaces are used for blocking and callback + streams, the following functions can be guaranteed to only be called + for blocking streams. +*/ -/*************************************************************************/ -const PaDeviceInfo* Pa_GetDeviceInfo( PaDeviceID id ) +static PaError ReadStream( PaStream* s, + void *buffer, + unsigned long frames ) { - if( (id < 0) || ( id >= Pa_CountDevices()) ) return NULL; - return &sDevices[id].pad_Info; + PaAsioStream *stream = (PaAsioStream*)s; + + /* IMPLEMENT ME, see portaudio.h for required behavior*/ + (void) stream; /* unused parameters */ + (void) buffer; + (void) frames; + + return paNoError; } -/*************************************************************************/ -PaDeviceID Pa_GetDefaultInputDeviceID( void ) + +static PaError WriteStream( PaStream* s, + const void *buffer, + unsigned long frames ) { - return sDefaultInputDeviceID; + PaAsioStream *stream = (PaAsioStream*)s; + + /* IMPLEMENT ME, see portaudio.h for required behavior*/ + (void) stream; /* unused parameters */ + (void) buffer; + (void) frames; + + return paNoError; } -/*************************************************************************/ -PaDeviceID Pa_GetDefaultOutputDeviceID( void ) + +static signed long GetStreamReadAvailable( PaStream* s ) { - return sDefaultOutputDeviceID; + PaAsioStream *stream = (PaAsioStream*)s; + + /* IMPLEMENT ME, see portaudio.h for required behavior*/ + (void) stream; /* unused parameter */ + + return 0; } -/*************************************************************************/ -int Pa_GetMinNumBuffers( int framesPerUserBuffer, double sampleRate ) + +static signed long GetStreamWriteAvailable( PaStream* s ) { - // TO BE IMPLEMENTED : using the ASIOGetLatency call?? - return 2; + PaAsioStream *stream = (PaAsioStream*)s; + + /* IMPLEMENT ME, see portaudio.h for required behavior*/ + (void) stream; /* unused parameter */ + + return 0; } -/*************************************************************************/ -int32 Pa_GetHostError( void ) + +PaError PaAsio_ShowControlPanel( PaDeviceIndex device, void* systemSpecific ) { - int32 err = sPaHostError; - sPaHostError = 0; - return err; -} + PaError result = paNoError; + PaUtilHostApiRepresentation *hostApi; + PaDeviceIndex hostApiDevice; + ASIODriverInfo asioDriverInfo; + ASIOError asioError; + int asioIsInitialized = 0; + PaAsioHostApiRepresentation *asioHostApi; + PaAsioDeviceInfo *asioDeviceInfo; -#ifdef MAC + result = PaUtil_GetHostApiRepresentation( &hostApi, paASIO ); + if( result != paNoError ) + goto error; -/**************************************************************************/ -static void Pa_StartUsageCalculation( internalPortAudioStream *past ) -{ - PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; - UnsignedWide widePad; - if( pahsc == NULL ) return; -/* Query system timer for usage analysis and to prevent overuse of CPU. */ - Microseconds( &widePad ); - pahsc->pahsc_EntryCount = UnsignedWideToUInt64( widePad ); -} -/**************************************************************************/ -static void Pa_EndUsageCalculation( internalPortAudioStream *past ) -{ - UnsignedWide widePad; - UInt64 CurrentCount; - long InsideCount; - long TotalCount; - PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; - if( pahsc == NULL ) return; -/* Measure CPU utilization during this callback. Note that this calculation -** assumes that we had the processor the whole time. -*/ -#define LOWPASS_COEFFICIENT_0 (0.9) -#define LOWPASS_COEFFICIENT_1 (0.99999 - LOWPASS_COEFFICIENT_0) - Microseconds( &widePad ); - CurrentCount = UnsignedWideToUInt64( widePad ); - if( past->past_IfLastExitValid ) - { - InsideCount = (long) U64Subtract(CurrentCount, pahsc->pahsc_EntryCount); - TotalCount = (long) U64Subtract(CurrentCount, pahsc->pahsc_LastExitCount); -/* Low pass filter the result because sometimes we get called several times in a row. -* That can cause the TotalCount to be very low which can cause the usage to appear -* unnaturally high. So we must filter numerator and denominator separately!!! -*/ - past->past_AverageInsideCount = (( LOWPASS_COEFFICIENT_0 * past->past_AverageInsideCount) + - (LOWPASS_COEFFICIENT_1 * InsideCount)); - past->past_AverageTotalCount = (( LOWPASS_COEFFICIENT_0 * past->past_AverageTotalCount) + - (LOWPASS_COEFFICIENT_1 * TotalCount)); - past->past_Usage = past->past_AverageInsideCount / past->past_AverageTotalCount; - } - pahsc->pahsc_LastExitCount = CurrentCount; - past->past_IfLastExitValid = 1; + result = PaUtil_DeviceIndexToHostApiDeviceIndex( &hostApiDevice, device, hostApi ); + if( result != paNoError ) + goto error; + + /* + In theory we could proceed if the currently open device was the same + one for which the control panel was requested, however because the + window pointer is not available until this function is called we + currently need to call ASIOInit() again here, which of course can't be + done safely while a stream is open. + */ + + asioHostApi = (PaAsioHostApiRepresentation*)hostApi; + if( asioHostApi->openAsioDeviceIndex != paNoDevice ) + { + result = paDeviceUnavailable; + goto error; + } + + asioDeviceInfo = (PaAsioDeviceInfo*)hostApi->deviceInfos[hostApiDevice]; + + if( !loadAsioDriver( const_cast(asioDeviceInfo->commonDeviceInfo.name) ) ) + { + result = paUnanticipatedHostError; + goto error; + } + + /* CRUCIAL!!! */ + memset( &asioDriverInfo, 0, sizeof(ASIODriverInfo) ); + asioDriverInfo.asioVersion = 2; + asioDriverInfo.sysRef = systemSpecific; + asioError = ASIOInit( &asioDriverInfo ); + if( asioError != ASE_OK ) + { + result = paUnanticipatedHostError; + PA_ASIO_SET_LAST_ASIO_ERROR( asioError ); + goto error; + } + else + { + asioIsInitialized = 1; + } + +PA_DEBUG(("PaAsio_ShowControlPanel: ASIOInit(): %s\n", PaAsio_GetAsioErrorText(asioError) )); +PA_DEBUG(("asioVersion: ASIOInit(): %ld\n", asioDriverInfo.asioVersion )); +PA_DEBUG(("driverVersion: ASIOInit(): %ld\n", asioDriverInfo.driverVersion )); +PA_DEBUG(("Name: ASIOInit(): %s\n", asioDriverInfo.name )); +PA_DEBUG(("ErrorMessage: ASIOInit(): %s\n", asioDriverInfo.errorMessage )); + + asioError = ASIOControlPanel(); + if( asioError != ASE_OK ) + { + PA_DEBUG(("PaAsio_ShowControlPanel: ASIOControlPanel(): %s\n", PaAsio_GetAsioErrorText(asioError) )); + result = paUnanticipatedHostError; + PA_ASIO_SET_LAST_ASIO_ERROR( asioError ); + goto error; + } + +PA_DEBUG(("PaAsio_ShowControlPanel: ASIOControlPanel(): %s\n", PaAsio_GetAsioErrorText(asioError) )); + + asioError = ASIOExit(); + if( asioError != ASE_OK ) + { + result = paUnanticipatedHostError; + PA_ASIO_SET_LAST_ASIO_ERROR( asioError ); + asioIsInitialized = 0; + goto error; + } + +PA_DEBUG(("PaAsio_ShowControlPanel: ASIOExit(): %s\n", PaAsio_GetAsioErrorText(asioError) )); + + return result; + +error: + if( asioIsInitialized ) + ASIOExit(); + + return result; } -#elif WINDOWS -/********************************* BEGIN CPU UTILIZATION MEASUREMENT ****/ -static void Pa_StartUsageCalculation( internalPortAudioStream *past ) +PaError PaAsio_GetInputChannelName( PaDeviceIndex device, int channelIndex, + const char** channelName ) { - PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; - if( pahsc == NULL ) return; -/* Query system timer for usage analysis and to prevent overuse of CPU. */ - QueryPerformanceCounter( &pahsc->pahsc_EntryCount ); + PaError result = paNoError; + PaUtilHostApiRepresentation *hostApi; + PaDeviceIndex hostApiDevice; + PaAsioDeviceInfo *asioDeviceInfo; + + + result = PaUtil_GetHostApiRepresentation( &hostApi, paASIO ); + if( result != paNoError ) + goto error; + + result = PaUtil_DeviceIndexToHostApiDeviceIndex( &hostApiDevice, device, hostApi ); + if( result != paNoError ) + goto error; + + asioDeviceInfo = (PaAsioDeviceInfo*)hostApi->deviceInfos[hostApiDevice]; + + if( channelIndex < 0 || channelIndex >= asioDeviceInfo->commonDeviceInfo.maxInputChannels ){ + result = paInvalidChannelCount; + goto error; + } + + *channelName = asioDeviceInfo->asioChannelInfos[channelIndex].name; + + return paNoError; + +error: + return result; } -static void Pa_EndUsageCalculation( internalPortAudioStream *past ) + +PaError PaAsio_GetOutputChannelName( PaDeviceIndex device, int channelIndex, + const char** channelName ) { - LARGE_INTEGER CurrentCount = { 0, 0 }; - LONGLONG InsideCount; - LONGLONG TotalCount; -/* -** Measure CPU utilization during this callback. Note that this calculation -** assumes that we had the processor the whole time. -*/ -#define LOWPASS_COEFFICIENT_0 (0.9) -#define LOWPASS_COEFFICIENT_1 (0.99999 - LOWPASS_COEFFICIENT_0) + PaError result = paNoError; + PaUtilHostApiRepresentation *hostApi; + PaDeviceIndex hostApiDevice; + PaAsioDeviceInfo *asioDeviceInfo; - PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; - if( pahsc == NULL ) return; - if( QueryPerformanceCounter( &CurrentCount ) ) - { - if( past->past_IfLastExitValid ) - { - InsideCount = CurrentCount.QuadPart - pahsc->pahsc_EntryCount.QuadPart; - TotalCount = CurrentCount.QuadPart - pahsc->pahsc_LastExitCount.QuadPart; -/* Low pass filter the result because sometimes we get called several times in a row. - * That can cause the TotalCount to be very low which can cause the usage to appear - * unnaturally high. So we must filter numerator and denominator separately!!! - */ - past->past_AverageInsideCount = (( LOWPASS_COEFFICIENT_0 * past->past_AverageInsideCount) + - (LOWPASS_COEFFICIENT_1 * InsideCount)); - past->past_AverageTotalCount = (( LOWPASS_COEFFICIENT_0 * past->past_AverageTotalCount) + - (LOWPASS_COEFFICIENT_1 * TotalCount)); - past->past_Usage = past->past_AverageInsideCount / past->past_AverageTotalCount; - } - pahsc->pahsc_LastExitCount = CurrentCount; - past->past_IfLastExitValid = 1; - } -} + result = PaUtil_GetHostApiRepresentation( &hostApi, paASIO ); + if( result != paNoError ) + goto error; -#endif + result = PaUtil_DeviceIndexToHostApiDeviceIndex( &hostApiDevice, device, hostApi ); + if( result != paNoError ) + goto error; + asioDeviceInfo = (PaAsioDeviceInfo*)hostApi->deviceInfos[hostApiDevice]; + if( channelIndex < 0 || channelIndex >= asioDeviceInfo->commonDeviceInfo.maxOutputChannels ){ + result = paInvalidChannelCount; + goto error; + } + *channelName = asioDeviceInfo->asioChannelInfos[ + asioDeviceInfo->commonDeviceInfo.maxInputChannels + channelIndex].name; + return paNoError; + +error: + return result; +} diff --git a/pa_asio/pa_asio.h b/pa_asio/pa_asio.h new file mode 100644 index 0000000..5739305 --- /dev/null +++ b/pa_asio/pa_asio.h @@ -0,0 +1,122 @@ +#ifndef PA_ASIO_H +#define PA_ASIO_H +/* + * $Id$ + * 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. + * + * 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. + * + */ + +/** @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 */ diff --git a/pa_asio/readme_asio_sdk_patch.txt b/pa_asio/readme_asio_sdk_patch.txt deleted file mode 100755 index c0fdca7..0000000 --- a/pa_asio/readme_asio_sdk_patch.txt +++ /dev/null @@ -1,25 +0,0 @@ -There is a bug in the ASIO SDK that causes the Macintosh version to often fail during initialization. Here is a patch that you can apply. - -In codefragments.cpp replace getFrontProcessDirectory function with -the following one (GetFrontProcess replaced by GetCurrentProcess) - - -bool CodeFragments::getFrontProcessDirectory(void *specs) -{ - FSSpec *fss = (FSSpec *)specs; - ProcessInfoRec pif; - ProcessSerialNumber psn; - - memset(&psn,0,(long)sizeof(ProcessSerialNumber)); - // if(GetFrontProcess(&psn) == noErr) // wrong !!! - if(GetCurrentProcess(&psn) == noErr) // correct !!! - { - pif.processName = 0; - pif.processAppSpec = fss; - pif.processInfoLength = sizeof(ProcessInfoRec); - if(GetProcessInformation(&psn, &pif) == noErr) - return true; - } - return false; -} - diff --git a/pa_common/pa_allocation.c b/pa_common/pa_allocation.c new file mode 100644 index 0000000..98239c4 --- /dev/null +++ b/pa_common/pa_allocation.c @@ -0,0 +1,234 @@ +/* + * $Id$ + * Portable Audio I/O Library allocation group implementation + * memory allocation group for tracking allocation groups + * + * 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. + * + * 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. + */ + +/** @file + @brief Allocation Group implementation. +*/ + + +#include "pa_allocation.h" +#include "pa_util.h" + + +/* + Maintain 3 singly linked lists... + linkBlocks: the buffers used to allocate the links + spareLinks: links available for use in the allocations list + allocations: the buffers currently allocated using PaUtil_ContextAllocateMemory() + + Link block size is doubled every time new links are allocated. +*/ + + +#define PA_INITIAL_LINK_COUNT_ 16 + +struct PaUtilAllocationGroupLink +{ + struct PaUtilAllocationGroupLink *next; + void *buffer; +}; + +/* + Allocate a block of links. The first link will have it's buffer member + pointing to the block, and it's next member set to . The remaining + links will have NULL buffer members, and each link will point to + the next link except the last, which will point to +*/ +static struct PaUtilAllocationGroupLink *AllocateLinks( long count, + struct PaUtilAllocationGroupLink *nextBlock, + struct PaUtilAllocationGroupLink *nextSpare ) +{ + struct PaUtilAllocationGroupLink *result; + int i; + + result = (struct PaUtilAllocationGroupLink *)PaUtil_AllocateMemory( + sizeof(struct PaUtilAllocationGroupLink) * count ); + if( result ) + { + /* the block link */ + result[0].buffer = result; + result[0].next = nextBlock; + + /* the spare links */ + for( i=1; ilinkCount = PA_INITIAL_LINK_COUNT_; + result->linkBlocks = &links[0]; + result->spareLinks = &links[1]; + result->allocations = 0; + } + else + { + PaUtil_FreeMemory( links ); + } + } + + return result; +} + + +void PaUtil_DestroyAllocationGroup( PaUtilAllocationGroup* group ) +{ + struct PaUtilAllocationGroupLink *current = group->linkBlocks; + struct PaUtilAllocationGroupLink *next; + + while( current ) + { + next = current->next; + PaUtil_FreeMemory( current->buffer ); + current = next; + } + + PaUtil_FreeMemory( group ); +} + + +void* PaUtil_GroupAllocateMemory( PaUtilAllocationGroup* group, long size ) +{ + struct PaUtilAllocationGroupLink *links, *link; + void *result = 0; + + /* allocate more links if necessary */ + if( !group->spareLinks ) + { + /* double the link count on each block allocation */ + links = AllocateLinks( group->linkCount, group->linkBlocks, group->spareLinks ); + if( links ) + { + group->linkCount += group->linkCount; + group->linkBlocks = &links[0]; + group->spareLinks = &links[1]; + } + } + + if( group->spareLinks ) + { + result = PaUtil_AllocateMemory( size ); + if( result ) + { + link = group->spareLinks; + group->spareLinks = link->next; + + link->buffer = result; + link->next = group->allocations; + + group->allocations = link; + } + } + + return result; +} + + +void PaUtil_GroupFreeMemory( PaUtilAllocationGroup* group, void *buffer ) +{ + struct PaUtilAllocationGroupLink *current = group->allocations; + struct PaUtilAllocationGroupLink *previous = 0; + + if( buffer == 0 ) + return; + + /* find the right link and remove it */ + while( current ) + { + if( current->buffer == buffer ) + { + if( previous ) + { + previous->next = current->next; + } + else + { + group->allocations = current->next; + } + + current->buffer = 0; + current->next = group->spareLinks; + group->spareLinks = current; + + break; + } + + previous = current; + current = current->next; + } + + PaUtil_FreeMemory( buffer ); /* free the memory whether we found it in the list or not */ +} + + +void PaUtil_FreeAllAllocations( PaUtilAllocationGroup* group ) +{ + struct PaUtilAllocationGroupLink *current = group->allocations; + struct PaUtilAllocationGroupLink *previous = 0; + + /* free all buffers in the allocations list */ + while( current ) + { + PaUtil_FreeMemory( current->buffer ); + current->buffer = 0; + + previous = current; + current = current->next; + } + + /* link the former allocations list onto the front of the spareLinks list */ + if( previous ) + { + previous->next = group->spareLinks; + group->spareLinks = group->allocations; + group->allocations = 0; + } +} + diff --git a/pa_common/pa_allocation.h b/pa_common/pa_allocation.h new file mode 100644 index 0000000..5bcfe75 --- /dev/null +++ b/pa_common/pa_allocation.h @@ -0,0 +1,95 @@ +#ifndef PA_ALLOCATION_H +#define PA_ALLOCATION_H +/* + * $Id$ + * Portable Audio I/O Library allocation context header + * memory allocation context for tracking allocation groups + * + * 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. + * + * 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. + */ + +/** @file + @brief Allocation Group prototypes. An Allocation Group makes it easy to + allocate multiple blocks of memory and free them all simultanously. + + An allocation group is useful for keeping track of multiple blocks + of memory which are allocated at the same time (such as during initialization) + and need to be deallocated at the same time. The allocation group maintains + a list of allocated blocks, and can deallocate them all simultaneously which + can be usefull for cleaning up after a partially initialized object fails. + + The allocation group implementation is built on top of the lower + level allocation functions defined in pa_util.h +*/ + + +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + + +typedef struct +{ + long linkCount; + struct PaUtilAllocationGroupLink *linkBlocks; + struct PaUtilAllocationGroupLink *spareLinks; + struct PaUtilAllocationGroupLink *allocations; +}PaUtilAllocationGroup; + + + +/** Create an allocation group. +*/ +PaUtilAllocationGroup* PaUtil_CreateAllocationGroup( void ); + +/** Destroy an allocation group, but not the memory allocated through the group. +*/ +void PaUtil_DestroyAllocationGroup( PaUtilAllocationGroup* group ); + +/** Allocate a block of memory though an allocation group. +*/ +void* PaUtil_GroupAllocateMemory( PaUtilAllocationGroup* group, long size ); + +/** Free a block of memory that was previously allocated though an allocation + group. Calling this function is a relatively time consuming operation. + Under normal circumstances clients should call PaUtil_FreeAllAllocations to + free all allocated blocks simultaneously. + @see PaUtil_FreeAllAllocations +*/ +void PaUtil_GroupFreeMemory( PaUtilAllocationGroup* group, void *buffer ); + +/** Free all blocks of memory which have been allocated through the allocation + group. This function doesn't destroy the group itself. +*/ +void PaUtil_FreeAllAllocations( PaUtilAllocationGroup* group ); + + +#ifdef __cplusplus +} +#endif /* __cplusplus */ +#endif /* PA_ALLOCATION_H */ diff --git a/pa_common/pa_convert.c b/pa_common/pa_convert.c deleted file mode 100644 index 377a955..0000000 --- a/pa_common/pa_convert.c +++ /dev/null @@ -1,402 +0,0 @@ -/* - * pa_conversions.c - * portaudio - * - * Created by Phil Burk on Mon Mar 18 2002. - * - */ -#include - -#include "portaudio.h" -#include "pa_host.h" - -#define CLIP( val, min, max ) { val = ((val) < (min)) ? min : (((val) < (max)) ? (max) : (val)); } - -/*************************************************************************/ -static void PaConvert_Float32_Int16( - float *sourceBuffer, int sourceStride, - short *targetBuffer, int targetStride, - int numSamples ) -{ - int i; - for( i=0; ipast_NativeInputSampleFormat = nativeInputSampleFormat; - past->past_InputConversionSourceStride = 1; - past->past_InputConversionTargetStride = 1; - - if( nativeInputSampleFormat != past->past_InputSampleFormat ) - { - int ifDither = (past->past_Flags & paDitherOff) == 0; - past->past_InputConversionProc = PaConvert_SelectProc( nativeInputSampleFormat, - past->past_InputSampleFormat, 0, ifDither ); - if( past->past_InputConversionProc == NULL ) return paSampleFormatNotSupported; - } - else - { - past->past_InputConversionProc = NULL; /* no conversion necessary */ - } - - return paNoError; -} - -/*************************************************************************/ -PaError PaConvert_SetupOutput( internalPortAudioStream *past, - PaSampleFormat nativeOutputSampleFormat ) -{ - - past->past_NativeOutputSampleFormat = nativeOutputSampleFormat; - past->past_OutputConversionSourceStride = 1; - past->past_OutputConversionTargetStride = 1; - - if( nativeOutputSampleFormat != past->past_OutputSampleFormat ) - { - int ifDither = (past->past_Flags & paDitherOff) == 0; - int ifClip = (past->past_Flags & paClipOff) == 0; - - past->past_OutputConversionProc = PaConvert_SelectProc( past->past_OutputSampleFormat, - nativeOutputSampleFormat, ifClip, ifDither ); - if( past->past_OutputConversionProc == NULL ) return paSampleFormatNotSupported; - } - else - { - past->past_OutputConversionProc = NULL; /* no conversion necessary */ - } - - return paNoError; -} - -/************************************************************************* -** Called by host code. -** Convert input from native format to user format, -** call user code, -** then convert output to native format. -** Returns result from user callback. -*/ -long PaConvert_Process( internalPortAudioStream *past, - void *nativeInputBuffer, - void *nativeOutputBuffer ) -{ - int userResult; - void *inputBuffer = NULL; - void *outputBuffer = NULL; - - /* Get native input data. */ - if( (past->past_NumInputChannels > 0) && (nativeInputBuffer != NULL) ) - { - if( past->past_InputSampleFormat == past->past_NativeInputSampleFormat ) - { - /* Already in native format so just read directly from native buffer. */ - inputBuffer = nativeInputBuffer; - } - else - { - inputBuffer = past->past_InputBuffer; - /* Convert input data to user format. */ - (*past->past_InputConversionProc)(nativeInputBuffer, past->past_InputConversionSourceStride, - inputBuffer, past->past_InputConversionTargetStride, - past->past_FramesPerUserBuffer * past->past_NumInputChannels ); - } - } - - /* Are we doing output? */ - if( (past->past_NumOutputChannels > 0) && (nativeOutputBuffer != NULL) ) - { - outputBuffer = (past->past_OutputConversionProc == NULL) ? - nativeOutputBuffer : past->past_OutputBuffer; - } - /* - AddTraceMessage("Pa_CallConvertInt16: inputBuffer = ", (int) inputBuffer ); - AddTraceMessage("Pa_CallConvertInt16: outputBuffer = ", (int) outputBuffer ); - */ - /* Call user callback routine. */ - userResult = past->past_Callback( - inputBuffer, - outputBuffer, - past->past_FramesPerUserBuffer, - past->past_FrameCount, - past->past_UserData ); - - /* Advance frame counter for timestamp. */ - past->past_FrameCount += past->past_FramesPerUserBuffer; // FIXME - should this be in here? - - /* Convert to native format if necessary. */ - if( (past->past_OutputConversionProc != NULL ) && (outputBuffer != NULL) ) - { - (*past->past_OutputConversionProc)( outputBuffer, past->past_OutputConversionSourceStride, - nativeOutputBuffer, past->past_OutputConversionTargetStride, - past->past_FramesPerUserBuffer * past->past_NumOutputChannels ); - } - - return userResult; -} diff --git a/pa_common/pa_converters.c b/pa_common/pa_converters.c new file mode 100644 index 0000000..39f83e4 --- /dev/null +++ b/pa_common/pa_converters.c @@ -0,0 +1,1926 @@ +/* + * $Id$ + * Portable Audio I/O Library sample conversion mechanism + * + * Based on the Open Source API proposed by Ross Bencina + * Copyright (c) 1999-2002 Phil Burk, 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. + * + * 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. + */ + +/** @file + @brief Conversion functions implementations. + + If the C9x function lrintf() is available, define PA_USE_C99_LRINTF to use it + + @todo Consider whether functions which dither but don't clip should exist, + V18 automatically enabled clipping whenever dithering was selected. Perhaps + we should do the same. + + @todo implement the converters marked IMPLEMENT ME: Float32_To_UInt8_Dither, + Float32_To_UInt8_Clip, Float32_To_UInt8_DitherClip, Int32_To_Int24_Dither, + Int32_To_UInt8_Dither, Int24_To_Int16_Dither, Int24_To_Int8_Dither, + Int24_To_UInt8_Dither, Int16_To_Int8_Dither, Int16_To_UInt8_Dither, + + @todo review the converters marked REVIEW: Float32_To_Int32, + Float32_To_Int32_Dither, Float32_To_Int32_Clip, Float32_To_Int32_DitherClip, + Int32_To_Int16_Dither, Int32_To_Int8_Dither, Int16_To_Int32 +*/ + + +#include "pa_converters.h" +#include "pa_dither.h" +#include "pa_endianness.h" +#include "pa_types.h" + + +PaSampleFormat PaUtil_SelectClosestAvailableFormat( + PaSampleFormat availableFormats, PaSampleFormat format ) +{ + PaSampleFormat result; + + format &= ~paNonInterleaved; + availableFormats &= ~paNonInterleaved; + + if( (format & availableFormats) == 0 ) + { + /* NOTE: this code depends on the sample format constants being in + descending order of quality - ie best quality is 0 + FIXME: should write an assert which checks that all of the + known constants conform to that requirement. + */ + + if( format != 0x01 ) + { + /* scan for better formats */ + result = format; + do + { + result >>= 1; + } + while( (result & availableFormats) == 0 && result != 0 ); + } + else + { + result = 0; + } + + if( result == 0 ){ + /* scan for worse formats */ + result = format; + do + { + result <<= 1; + } + while( (result & availableFormats) == 0 && result != paCustomFormat ); + + if( (result & availableFormats) == 0 ) + result = paSampleFormatNotSupported; + } + + }else{ + result = format; + } + + return result; +} + +/* -------------------------------------------------------------------------- */ + +#define PA_SELECT_FORMAT_( format, float32, int32, int24, int16, int8, uint8 ) \ + switch( format & ~paNonInterleaved ){ \ + case paFloat32: \ + float32 \ + case paInt32: \ + int32 \ + case paInt24: \ + int24 \ + case paInt16: \ + int16 \ + case paInt8: \ + int8 \ + case paUInt8: \ + uint8 \ + default: return 0; \ + } + +/* -------------------------------------------------------------------------- */ + +#define PA_SELECT_CONVERTER_DITHER_CLIP_( flags, source, destination ) \ + if( flags & paClipOff ){ /* no clip */ \ + if( flags & paDitherOff ){ /* no dither */ \ + return paConverters. source ## _To_ ## destination; \ + }else{ /* dither */ \ + return paConverters. source ## _To_ ## destination ## _Dither; \ + } \ + }else{ /* clip */ \ + if( flags & paDitherOff ){ /* no dither */ \ + return paConverters. source ## _To_ ## destination ## _Clip; \ + }else{ /* dither */ \ + return paConverters. source ## _To_ ## destination ## _DitherClip; \ + } \ + } + +/* -------------------------------------------------------------------------- */ + +#define PA_SELECT_CONVERTER_DITHER_( flags, source, destination ) \ + if( flags & paDitherOff ){ /* no dither */ \ + return paConverters. source ## _To_ ## destination; \ + }else{ /* dither */ \ + return paConverters. source ## _To_ ## destination ## _Dither; \ + } + +/* -------------------------------------------------------------------------- */ + +#define PA_USE_CONVERTER_( source, destination )\ + return paConverters. source ## _To_ ## destination; + +/* -------------------------------------------------------------------------- */ + +#define PA_UNITY_CONVERSION_( wordlength )\ + return paConverters. Copy_ ## wordlength ## _To_ ## wordlength; + +/* -------------------------------------------------------------------------- */ + +PaUtilConverter* PaUtil_SelectConverter( PaSampleFormat sourceFormat, + PaSampleFormat destinationFormat, PaStreamFlags flags ) +{ + PA_SELECT_FORMAT_( sourceFormat, + /* paFloat32: */ + PA_SELECT_FORMAT_( destinationFormat, + /* paFloat32: */ PA_UNITY_CONVERSION_( 32 ), + /* paInt32: */ PA_SELECT_CONVERTER_DITHER_CLIP_( flags, Float32, Int32 ), + /* paInt24: */ PA_SELECT_CONVERTER_DITHER_CLIP_( flags, Float32, Int24 ), + /* paInt16: */ PA_SELECT_CONVERTER_DITHER_CLIP_( flags, Float32, Int16 ), + /* paInt8: */ PA_SELECT_CONVERTER_DITHER_CLIP_( flags, Float32, Int8 ), + /* paUInt8: */ PA_SELECT_CONVERTER_DITHER_CLIP_( flags, Float32, UInt8 ) + ), + /* paInt32: */ + PA_SELECT_FORMAT_( destinationFormat, + /* paFloat32: */ PA_USE_CONVERTER_( Int32, Float32 ), + /* paInt32: */ PA_UNITY_CONVERSION_( 32 ), + /* paInt24: */ PA_SELECT_CONVERTER_DITHER_( flags, Int32, Int24 ), + /* paInt16: */ PA_SELECT_CONVERTER_DITHER_( flags, Int32, Int16 ), + /* paInt8: */ PA_SELECT_CONVERTER_DITHER_( flags, Int32, Int8 ), + /* paUInt8: */ PA_SELECT_CONVERTER_DITHER_( flags, Int32, UInt8 ) + ), + /* paInt24: */ + PA_SELECT_FORMAT_( destinationFormat, + /* paFloat32: */ PA_USE_CONVERTER_( Int24, Float32 ), + /* paInt32: */ PA_USE_CONVERTER_( Int24, Int32 ), + /* paInt24: */ PA_UNITY_CONVERSION_( 24 ), + /* paInt16: */ PA_SELECT_CONVERTER_DITHER_( flags, Int24, Int16 ), + /* paInt8: */ PA_SELECT_CONVERTER_DITHER_( flags, Int24, Int8 ), + /* paUInt8: */ PA_SELECT_CONVERTER_DITHER_( flags, Int24, UInt8 ) + ), + /* paInt16: */ + PA_SELECT_FORMAT_( destinationFormat, + /* paFloat32: */ PA_USE_CONVERTER_( Int16, Float32 ), + /* paInt32: */ PA_USE_CONVERTER_( Int16, Int32 ), + /* paInt24: */ PA_USE_CONVERTER_( Int16, Int24 ), + /* paInt16: */ PA_UNITY_CONVERSION_( 16 ), + /* paInt8: */ PA_SELECT_CONVERTER_DITHER_( flags, Int16, Int8 ), + /* paUInt8: */ PA_SELECT_CONVERTER_DITHER_( flags, Int16, UInt8 ) + ), + /* paInt8: */ + PA_SELECT_FORMAT_( destinationFormat, + /* paFloat32: */ PA_USE_CONVERTER_( Int8, Float32 ), + /* paInt32: */ PA_USE_CONVERTER_( Int8, Int32 ), + /* paInt24: */ PA_USE_CONVERTER_( Int8, Int24 ), + /* paInt16: */ PA_USE_CONVERTER_( Int8, Int16 ), + /* paInt8: */ PA_UNITY_CONVERSION_( 8 ), + /* paUInt8: */ PA_USE_CONVERTER_( Int8, UInt8 ) + ), + /* paUInt8: */ + PA_SELECT_FORMAT_( destinationFormat, + /* paFloat32: */ PA_USE_CONVERTER_( UInt8, Float32 ), + /* paInt32: */ PA_USE_CONVERTER_( UInt8, Int32 ), + /* paInt24: */ PA_USE_CONVERTER_( UInt8, Int24 ), + /* paInt16: */ PA_USE_CONVERTER_( UInt8, Int16 ), + /* paInt8: */ PA_USE_CONVERTER_( UInt8, Int8 ), + /* paUInt8: */ PA_UNITY_CONVERSION_( 8 ) + ) + ) +} + +/* -------------------------------------------------------------------------- */ + +#ifdef PA_NO_STANDARD_CONVERTERS + +/* -------------------------------------------------------------------------- */ + +PaUtilConverterTable paConverters = { + 0, /* PaUtilConverter *Float32_To_Int32; */ + 0, /* PaUtilConverter *Float32_To_Int32_Dither; */ + 0, /* PaUtilConverter *Float32_To_Int32_Clip; */ + 0, /* PaUtilConverter *Float32_To_Int32_DitherClip; */ + + 0, /* PaUtilConverter *Float32_To_Int24; */ + 0, /* PaUtilConverter *Float32_To_Int24_Dither; */ + 0, /* PaUtilConverter *Float32_To_Int24_Clip; */ + 0, /* PaUtilConverter *Float32_To_Int24_DitherClip; */ + + 0, /* PaUtilConverter *Float32_To_Int16; */ + 0, /* PaUtilConverter *Float32_To_Int16_Dither; */ + 0, /* PaUtilConverter *Float32_To_Int16_Clip; */ + 0, /* PaUtilConverter *Float32_To_Int16_DitherClip; */ + + 0, /* PaUtilConverter *Float32_To_Int8; */ + 0, /* PaUtilConverter *Float32_To_Int8_Dither; */ + 0, /* PaUtilConverter *Float32_To_Int8_Clip; */ + 0, /* PaUtilConverter *Float32_To_Int8_DitherClip; */ + + 0, /* PaUtilConverter *Float32_To_UInt8; */ + 0, /* PaUtilConverter *Float32_To_UInt8_Dither; */ + 0, /* PaUtilConverter *Float32_To_UInt8_Clip; */ + 0, /* PaUtilConverter *Float32_To_UInt8_DitherClip; */ + + 0, /* PaUtilConverter *Int32_To_Float32; */ + 0, /* PaUtilConverter *Int32_To_Int24; */ + 0, /* PaUtilConverter *Int32_To_Int24_Dither; */ + 0, /* PaUtilConverter *Int32_To_Int16; */ + 0, /* PaUtilConverter *Int32_To_Int16_Dither; */ + 0, /* PaUtilConverter *Int32_To_Int8; */ + 0, /* PaUtilConverter *Int32_To_Int8_Dither; */ + 0, /* PaUtilConverter *Int32_To_UInt8; */ + 0, /* PaUtilConverter *Int32_To_UInt8_Dither; */ + + 0, /* PaUtilConverter *Int24_To_Float32; */ + 0, /* PaUtilConverter *Int24_To_Int32; */ + 0, /* PaUtilConverter *Int24_To_Int16; */ + 0, /* PaUtilConverter *Int24_To_Int16_Dither; */ + 0, /* PaUtilConverter *Int24_To_Int8; */ + 0, /* PaUtilConverter *Int24_To_Int8_Dither; */ + 0, /* PaUtilConverter *Int24_To_UInt8; */ + 0, /* PaUtilConverter *Int24_To_UInt8_Dither; */ + + 0, /* PaUtilConverter *Int16_To_Float32; */ + 0, /* PaUtilConverter *Int16_To_Int32; */ + 0, /* PaUtilConverter *Int16_To_Int24; */ + 0, /* PaUtilConverter *Int16_To_Int8; */ + 0, /* PaUtilConverter *Int16_To_Int8_Dither; */ + 0, /* PaUtilConverter *Int16_To_UInt8; */ + 0, /* PaUtilConverter *Int16_To_UInt8_Dither; */ + + 0, /* PaUtilConverter *Int8_To_Float32; */ + 0, /* PaUtilConverter *Int8_To_Int32; */ + 0, /* PaUtilConverter *Int8_To_Int24 */ + 0, /* PaUtilConverter *Int8_To_Int16; */ + 0, /* PaUtilConverter *Int8_To_UInt8; */ + + 0, /* PaUtilConverter *UInt8_To_Float32; */ + 0, /* PaUtilConverter *UInt8_To_Int32; */ + 0, /* PaUtilConverter *UInt8_To_Int24; */ + 0, /* PaUtilConverter *UInt8_To_Int16; */ + 0, /* PaUtilConverter *UInt8_To_Int8; */ + + 0, /* PaUtilConverter *Copy_8_To_8; */ + 0, /* PaUtilConverter *Copy_16_To_16; */ + 0, /* PaUtilConverter *Copy_24_To_24; */ + 0 /* PaUtilConverter *Copy_32_To_32; */ +}; + +/* -------------------------------------------------------------------------- */ + +#else /* PA_NO_STANDARD_CONVERTERS is not defined */ + +/* -------------------------------------------------------------------------- */ + +#define PA_CLIP_( val, min, max )\ + { val = ((val) < (min)) ? (min) : (((val) > (max)) ? (max) : (val)); } + + +static const float const_1_div_128_ = 1.0f / 128.0f; /* 8 bit multiplier */ + +static const float const_1_div_32768_ = 1.0f / 32768.f; /* 16 bit multiplier */ + +static const double const_1_div_2147483648_ = 1.0 / 2147483648.0; /* 32 bit multiplier */ + +/* -------------------------------------------------------------------------- */ + +static void Float32_To_Int32( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + float *src = (float*)sourceBuffer; + PaInt32 *dest = (PaInt32*)destinationBuffer; + (void)ditherGenerator; /* unused parameter */ + + while( count-- ) + { + /* REVIEW */ +#ifdef PA_USE_C99_LRINTF + float scaled = *src * 0x7FFFFFFF; + *dest = lrintf(scaled-0.5f); +#else + double scaled = *src * 0x7FFFFFFF; + *dest = (PaInt32) scaled; +#endif + + src += sourceStride; + dest += destinationStride; + } +} + +/* -------------------------------------------------------------------------- */ + +static void Float32_To_Int32_Dither( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + float *src = (float*)sourceBuffer; + PaInt32 *dest = (PaInt32*)destinationBuffer; + + while( count-- ) + { + /* REVIEW */ +#ifdef PA_USE_C99_LRINTF + float dither = PaUtil_GenerateFloatTriangularDither( ditherGenerator ); + /* use smaller scaler to prevent overflow when we add the dither */ + float dithered = ((float)*src * (2147483646.0f)) + dither; + *dest = lrintf(dithered - 0.5f); +#else + double dither = PaUtil_GenerateFloatTriangularDither( ditherGenerator ); + /* use smaller scaler to prevent overflow when we add the dither */ + double dithered = ((double)*src * (2147483646.0)) + dither; + *dest = (PaInt32) dithered; +#endif + src += sourceStride; + dest += destinationStride; + } +} + +/* -------------------------------------------------------------------------- */ + +static void Float32_To_Int32_Clip( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + float *src = (float*)sourceBuffer; + PaInt32 *dest = (PaInt32*)destinationBuffer; + (void) ditherGenerator; /* unused parameter */ + + while( count-- ) + { + /* REVIEW */ +#ifdef PA_USE_C99_LRINTF + float scaled = *src * 0x7FFFFFFF; + PA_CLIP_( scaled, -2147483648.f, 2147483647.f ); + *dest = lrintf(scaled-0.5f); +#else + double scaled = *src * 0x7FFFFFFF; + PA_CLIP_( scaled, -2147483648., 2147483647. ); + *dest = (PaInt32) scaled; +#endif + + src += sourceStride; + dest += destinationStride; + } +} + +/* -------------------------------------------------------------------------- */ + +static void Float32_To_Int32_DitherClip( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + float *src = (float*)sourceBuffer; + PaInt32 *dest = (PaInt32*)destinationBuffer; + + while( count-- ) + { + /* REVIEW */ +#ifdef PA_USE_C99_LRINTF + float dither = PaUtil_GenerateFloatTriangularDither( ditherGenerator ); + /* use smaller scaler to prevent overflow when we add the dither */ + float dithered = ((float)*src * (2147483646.0f)) + dither; + PA_CLIP_( dithered, -2147483648.f, 2147483647.f ); + *dest = lrintf(dithered-0.5f); +#else + 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 = (PaInt32) dithered; +#endif + + src += sourceStride; + dest += destinationStride; + } +} + +/* -------------------------------------------------------------------------- */ + +static void Float32_To_Int24( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + float *src = (float*)sourceBuffer; + unsigned char *dest = (unsigned char*)destinationBuffer; + PaInt32 temp; + + (void) ditherGenerator; /* unused parameter */ + + while( count-- ) + { + /* convert to 32 bit and drop the low 8 bits */ + double scaled = *src * 0x7FFFFFFF; + temp = (PaInt32) scaled; + +#if defined(PA_LITTLE_ENDIAN) + dest[0] = (unsigned char)(temp >> 8); + dest[1] = (unsigned char)(temp >> 16); + dest[2] = (unsigned char)(temp >> 24); +#elif defined(PA_BIG_ENDIAN) + dest[0] = (unsigned char)(temp >> 24); + dest[1] = (unsigned char)(temp >> 16); + dest[2] = (unsigned char)(temp >> 8); +#endif + + src += sourceStride; + dest += destinationStride * 3; + } +} + +/* -------------------------------------------------------------------------- */ + +static void Float32_To_Int24_Dither( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + float *src = (float*)sourceBuffer; + unsigned char *dest = (unsigned char*)destinationBuffer; + PaInt32 temp; + + while( count-- ) + { + /* convert to 32 bit and drop the low 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; + + temp = (PaInt32) dithered; + +#if defined(PA_LITTLE_ENDIAN) + dest[0] = (unsigned char)(temp >> 8); + dest[1] = (unsigned char)(temp >> 16); + dest[2] = (unsigned char)(temp >> 24); +#elif defined(PA_BIG_ENDIAN) + dest[0] = (unsigned char)(temp >> 24); + dest[1] = (unsigned char)(temp >> 16); + dest[2] = (unsigned char)(temp >> 8); +#endif + + src += sourceStride; + dest += destinationStride * 3; + } +} + +/* -------------------------------------------------------------------------- */ + +static void Float32_To_Int24_Clip( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + float *src = (float*)sourceBuffer; + unsigned char *dest = (unsigned char*)destinationBuffer; + PaInt32 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 = (PaInt32) scaled; + +#if defined(PA_LITTLE_ENDIAN) + dest[0] = (unsigned char)(temp >> 8); + dest[1] = (unsigned char)(temp >> 16); + dest[2] = (unsigned char)(temp >> 24); +#elif defined(PA_BIG_ENDIAN) + dest[0] = (unsigned char)(temp >> 24); + dest[1] = (unsigned char)(temp >> 16); + dest[2] = (unsigned char)(temp >> 8); +#endif + + src += sourceStride; + dest += destinationStride * 3; + } +} + +/* -------------------------------------------------------------------------- */ + +static void Float32_To_Int24_DitherClip( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + float *src = (float*)sourceBuffer; + unsigned char *dest = (unsigned char*)destinationBuffer; + PaInt32 temp; + + while( count-- ) + { + /* convert to 32 bit and drop the low 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 = (PaInt32) dithered; + +#if defined(PA_LITTLE_ENDIAN) + dest[0] = (unsigned char)(temp >> 8); + dest[1] = (unsigned char)(temp >> 16); + dest[2] = (unsigned char)(temp >> 24); +#elif defined(PA_BIG_ENDIAN) + dest[0] = (unsigned char)(temp >> 24); + dest[1] = (unsigned char)(temp >> 16); + dest[2] = (unsigned char)(temp >> 8); +#endif + + src += sourceStride; + dest += destinationStride * 3; + } +} + +/* -------------------------------------------------------------------------- */ + +static void Float32_To_Int16( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + float *src = (float*)sourceBuffer; + PaInt16 *dest = (PaInt16*)destinationBuffer; + (void)ditherGenerator; /* unused parameter */ + + while( count-- ) + { +#ifdef PA_USE_C99_LRINTF + float tempf = (*src * (32767.0f)) ; + *dest = lrintf(tempf-0.5f); +#else + short samp = (short) (*src * (32767.0f)); + *dest = samp; +#endif + + src += sourceStride; + dest += destinationStride; + } +} + +/* -------------------------------------------------------------------------- */ + +static void Float32_To_Int16_Dither( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + float *src = (float*)sourceBuffer; + PaInt16 *dest = (PaInt16*)destinationBuffer; + + while( count-- ) + { + + float dither = PaUtil_GenerateFloatTriangularDither( ditherGenerator ); + /* use smaller scaler to prevent overflow when we add the dither */ + float dithered = (*src * (32766.0f)) + dither; + +#ifdef PA_USE_C99_LRINTF + *dest = lrintf(dithered-0.5f); +#else + *dest = (PaInt16) dithered; +#endif + + src += sourceStride; + dest += destinationStride; + } +} + +/* -------------------------------------------------------------------------- */ + +static void Float32_To_Int16_Clip( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + float *src = (float*)sourceBuffer; + PaInt16 *dest = (PaInt16*)destinationBuffer; + (void)ditherGenerator; /* unused parameter */ + + while( count-- ) + { +#ifdef PA_USE_C99_LRINTF + long samp = lrintf((*src * (32767.0f)) -0.5f); +#else + long samp = (PaInt32) (*src * (32767.0f)); +#endif + PA_CLIP_( samp, -0x8000, 0x7FFF ); + *dest = (PaInt16) samp; + + src += sourceStride; + dest += destinationStride; + } +} + +/* -------------------------------------------------------------------------- */ + +static void Float32_To_Int16_DitherClip( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + float *src = (float*)sourceBuffer; + PaInt16 *dest = (PaInt16*)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; + PaInt32 samp = (PaInt32) dithered; + PA_CLIP_( samp, -0x8000, 0x7FFF ); +#ifdef PA_USE_C99_LRINTF + *dest = lrintf(samp-0.5f); +#else + *dest = (PaInt16) samp; +#endif + + src += sourceStride; + dest += destinationStride; + } +} + +/* -------------------------------------------------------------------------- */ + +static void Float32_To_Int8( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + float *src = (float*)sourceBuffer; + signed char *dest = (signed char*)destinationBuffer; + (void)ditherGenerator; /* unused parameter */ + + while( count-- ) + { + signed char samp = (signed char) (*src * (127.0f)); + *dest = samp; + + src += sourceStride; + dest += destinationStride; + } +} + +/* -------------------------------------------------------------------------- */ + +static void Float32_To_Int8_Dither( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + float *src = (float*)sourceBuffer; + signed char *dest = (signed char*)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 * (126.0f)) + dither; + PaInt32 samp = (PaInt32) dithered; + *dest = (signed char) samp; + + src += sourceStride; + dest += destinationStride; + } +} + +/* -------------------------------------------------------------------------- */ + +static void Float32_To_Int8_Clip( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + float *src = (float*)sourceBuffer; + signed char *dest = (signed char*)destinationBuffer; + (void)ditherGenerator; /* unused parameter */ + + while( count-- ) + { + PaInt32 samp = (PaInt32)(*src * (127.0f)); + PA_CLIP_( samp, -0x80, 0x7F ); + *dest = (signed char) samp; + + src += sourceStride; + dest += destinationStride; + } +} + +/* -------------------------------------------------------------------------- */ + +static void Float32_To_Int8_DitherClip( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + float *src = (float*)sourceBuffer; + signed char *dest = (signed char*)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 * (126.0f)) + dither; + PaInt32 samp = (PaInt32) dithered; + PA_CLIP_( samp, -0x80, 0x7F ); + *dest = (signed char) samp; + + src += sourceStride; + dest += destinationStride; + } +} + +/* -------------------------------------------------------------------------- */ + +static void Float32_To_UInt8( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + float *src = (float*)sourceBuffer; + unsigned char *dest = (unsigned char*)destinationBuffer; + (void)ditherGenerator; /* unused parameter */ + + while( count-- ) + { + unsigned char samp = (unsigned char)(128 + ((unsigned char) (*src * (127.0f)))); + *dest = samp; + + src += sourceStride; + dest += destinationStride; + } +} + +/* -------------------------------------------------------------------------- */ + +static void Float32_To_UInt8_Dither( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + float *src = (float*)sourceBuffer; + unsigned char *dest = (unsigned char*)destinationBuffer; + (void)ditherGenerator; /* unused parameter */ + + while( count-- ) + { + /* IMPLEMENT ME */ + + src += sourceStride; + dest += destinationStride; + } +} + +/* -------------------------------------------------------------------------- */ + +static void Float32_To_UInt8_Clip( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + float *src = (float*)sourceBuffer; + unsigned char *dest = (unsigned char*)destinationBuffer; + (void)ditherGenerator; /* unused parameter */ + + while( count-- ) + { + /* IMPLEMENT ME */ + + src += sourceStride; + dest += destinationStride; + } +} + +/* -------------------------------------------------------------------------- */ + +static void Float32_To_UInt8_DitherClip( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + float *src = (float*)sourceBuffer; + unsigned char *dest = (unsigned char*)destinationBuffer; + (void)ditherGenerator; /* unused parameter */ + + while( count-- ) + { + /* IMPLEMENT ME */ + + src += sourceStride; + dest += destinationStride; + } +} + +/* -------------------------------------------------------------------------- */ + +static void Int32_To_Float32( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + PaInt32 *src = (PaInt32*)sourceBuffer; + float *dest = (float*)destinationBuffer; + (void)ditherGenerator; /* unused parameter */ + + while( count-- ) + { + *dest = (float) ((double)*src * const_1_div_2147483648_); + + src += sourceStride; + dest += destinationStride; + } +} + +/* -------------------------------------------------------------------------- */ + +static void Int32_To_Int24( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + PaInt32 *src = (PaInt32*)sourceBuffer; + unsigned char *dest = (unsigned char*)destinationBuffer; + (void) ditherGenerator; /* unused parameter */ + + while( count-- ) + { + /* REVIEW */ +#if defined(PA_LITTLE_ENDIAN) + dest[0] = (unsigned char)(*src >> 8); + dest[1] = (unsigned char)(*src >> 16); + dest[2] = (unsigned char)(*src >> 24); +#elif defined(PA_BIG_ENDIAN) + dest[0] = (unsigned char)(*src >> 24); + dest[1] = (unsigned char)(*src >> 16); + dest[2] = (unsigned char)(*src >> 8); +#endif + src += sourceStride; + dest += destinationStride * 3; + } +} + +/* -------------------------------------------------------------------------- */ + +static void Int32_To_Int24_Dither( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + (void) destinationBuffer; /* unused parameters */ + (void) destinationStride; /* unused parameters */ + (void) sourceBuffer; /* unused parameters */ + (void) sourceStride; /* unused parameters */ + (void) count; /* unused parameters */ + (void) ditherGenerator; /* unused parameters */ + /* IMPLEMENT ME */ +} + +/* -------------------------------------------------------------------------- */ + +static void Int32_To_Int16( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + PaInt32 *src = (PaInt32*)sourceBuffer; + PaInt16 *dest = (PaInt16*)destinationBuffer; + (void)ditherGenerator; /* unused parameter */ + + while( count-- ) + { + *dest = (PaInt16) ((*src) >> 16); + + src += sourceStride; + dest += destinationStride; + } +} + +/* -------------------------------------------------------------------------- */ + +static void Int32_To_Int16_Dither( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + PaInt32 *src = (PaInt32*)sourceBuffer; + PaInt16 *dest = (PaInt16*)destinationBuffer; + PaInt32 dither; + + while( count-- ) + { + /* REVIEW */ + dither = PaUtil_Generate16BitTriangularDither( ditherGenerator ); + *dest = (PaInt16) ((((*src)>>1) + dither) >> 15); + + src += sourceStride; + dest += destinationStride; + } +} + +/* -------------------------------------------------------------------------- */ + +static void Int32_To_Int8( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + PaInt32 *src = (PaInt32*)sourceBuffer; + signed char *dest = (signed char*)destinationBuffer; + (void)ditherGenerator; /* unused parameter */ + + while( count-- ) + { + *dest = (signed char) ((*src) >> 24); + + src += sourceStride; + dest += destinationStride; + } +} + +/* -------------------------------------------------------------------------- */ + +static void Int32_To_Int8_Dither( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + PaInt32 *src = (PaInt32*)sourceBuffer; + signed char *dest = (signed char*)destinationBuffer; + PaInt32 dither; + + while( count-- ) + { + /* REVIEW */ + dither = PaUtil_Generate16BitTriangularDither( ditherGenerator ); + *dest = (signed char) ((((*src)>>1) + dither) >> 23); + + src += sourceStride; + dest += destinationStride; + } +} + +/* -------------------------------------------------------------------------- */ + +static void Int32_To_UInt8( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + PaInt32 *src = (PaInt32*)sourceBuffer; + unsigned char *dest = (unsigned char*)destinationBuffer; + (void)ditherGenerator; /* unused parameter */ + + while( count-- ) + { + (*dest) = (unsigned char)(((*src) >> 24) + 128); + + src += sourceStride; + dest += destinationStride; + } +} + +/* -------------------------------------------------------------------------- */ + +static void Int32_To_UInt8_Dither( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + PaInt32 *src = (PaInt32*)sourceBuffer; + unsigned char *dest = (unsigned char*)destinationBuffer; + (void)ditherGenerator; /* unused parameter */ + + while( count-- ) + { + /* IMPLEMENT ME */ + + src += sourceStride; + dest += destinationStride; + } +} + +/* -------------------------------------------------------------------------- */ + +static void Int24_To_Float32( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + unsigned char *src = (unsigned char*)sourceBuffer; + float *dest = (float*)destinationBuffer; + PaInt32 temp; + + (void) ditherGenerator; /* unused parameter */ + + while( count-- ) + { + +#if defined(PA_LITTLE_ENDIAN) + temp = (((long)src[0]) << 8); + temp = temp | (((long)src[1]) << 16); + temp = temp | (((long)src[2]) << 24); +#elif defined(PA_BIG_ENDIAN) + temp = (((long)src[0]) << 24); + temp = temp | (((long)src[1]) << 16); + temp = temp | (((long)src[2]) << 8); +#endif + + *dest = (float) ((double)temp * const_1_div_2147483648_); + + src += sourceStride * 3; + dest += destinationStride; + } +} + +/* -------------------------------------------------------------------------- */ + +static void Int24_To_Int32( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + unsigned char *src = (unsigned char*)sourceBuffer; + PaInt32 *dest = (PaInt32*) destinationBuffer; + PaInt32 temp; + + (void) ditherGenerator; /* unused parameter */ + + while( count-- ) + { + +#if defined(PA_LITTLE_ENDIAN) + temp = (((long)src[0]) << 8); + temp = temp | (((long)src[1]) << 16); + temp = temp | (((long)src[2]) << 24); +#elif defined(PA_BIG_ENDIAN) + temp = (((long)src[0]) << 24); + temp = temp | (((long)src[1]) << 16); + temp = temp | (((long)src[2]) << 8); +#endif + + *dest = temp; + + src += sourceStride * 3; + dest += destinationStride; + } +} + +/* -------------------------------------------------------------------------- */ + +static void Int24_To_Int16( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + unsigned char *src = (unsigned char*)sourceBuffer; + PaInt16 *dest = (PaInt16*)destinationBuffer; + + PaInt16 temp; + + (void) ditherGenerator; /* unused parameter */ + + while( count-- ) + { + +#if defined(PA_LITTLE_ENDIAN) + /* src[0] is discarded */ + temp = (((PaInt16)src[1])); + temp = temp | (PaInt16)(((PaInt16)src[2]) << 8); +#elif defined(PA_BIG_ENDIAN) + /* src[2] is discarded */ + temp = (PaInt16)(((PaInt16)src[0]) << 8); + temp = temp | (((PaInt16)src[1])); +#endif + + *dest = temp; + + src += sourceStride * 3; + dest += destinationStride; + } +} + +/* -------------------------------------------------------------------------- */ + +static void Int24_To_Int16_Dither( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + (void) destinationBuffer; /* unused parameters */ + (void) destinationStride; /* unused parameters */ + (void) sourceBuffer; /* unused parameters */ + (void) sourceStride; /* unused parameters */ + (void) count; /* unused parameters */ + (void) ditherGenerator; /* unused parameters */ + /* IMPLEMENT ME */ +} + +/* -------------------------------------------------------------------------- */ + +static void Int24_To_Int8( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + unsigned char *src = (unsigned char*)sourceBuffer; + signed char *dest = (signed char*)destinationBuffer; + + (void) ditherGenerator; /* unused parameter */ + + while( count-- ) + { + +#if defined(PA_LITTLE_ENDIAN) + /* src[0] is discarded */ + /* src[1] is discarded */ + *dest = src[2]; +#elif defined(PA_BIG_ENDIAN) + /* src[2] is discarded */ + /* src[1] is discarded */ + *dest = src[0]; +#endif + + src += sourceStride * 3; + dest += destinationStride; + } +} + +/* -------------------------------------------------------------------------- */ + +static void Int24_To_Int8_Dither( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + (void) destinationBuffer; /* unused parameters */ + (void) destinationStride; /* unused parameters */ + (void) sourceBuffer; /* unused parameters */ + (void) sourceStride; /* unused parameters */ + (void) count; /* unused parameters */ + (void) ditherGenerator; /* unused parameters */ + /* IMPLEMENT ME */ +} + +/* -------------------------------------------------------------------------- */ + +static void Int24_To_UInt8( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + unsigned char *src = (unsigned char*)sourceBuffer; + unsigned char *dest = (unsigned char*)destinationBuffer; + + (void) ditherGenerator; /* unused parameter */ + + while( count-- ) + { + +#if defined(PA_LITTLE_ENDIAN) + /* src[0] is discarded */ + /* src[1] is discarded */ + *dest = (unsigned char)(src[2] + 128); +#elif defined(PA_BIG_ENDIAN) + *dest = (unsigned char)(src[0] + 128); + /* src[1] is discarded */ + /* src[2] is discarded */ +#endif + + src += sourceStride * 3; + dest += destinationStride; + } +} + +/* -------------------------------------------------------------------------- */ + +static void Int24_To_UInt8_Dither( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + (void) destinationBuffer; /* unused parameters */ + (void) destinationStride; /* unused parameters */ + (void) sourceBuffer; /* unused parameters */ + (void) sourceStride; /* unused parameters */ + (void) count; /* unused parameters */ + (void) ditherGenerator; /* unused parameters */ + /* IMPLEMENT ME */ +} + +/* -------------------------------------------------------------------------- */ + +static void Int16_To_Float32( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + PaInt16 *src = (PaInt16*)sourceBuffer; + float *dest = (float*)destinationBuffer; + (void)ditherGenerator; /* unused parameter */ + + while( count-- ) + { + float samp = *src * const_1_div_32768_; /* FIXME: i'm concerned about this being asymetrical with float->int16 -rb */ + *dest = samp; + + src += sourceStride; + dest += destinationStride; + } +} + +/* -------------------------------------------------------------------------- */ + +static void Int16_To_Int32( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + PaInt16 *src = (PaInt16*)sourceBuffer; + PaInt32 *dest = (PaInt32*)destinationBuffer; + (void)ditherGenerator; /* unused parameter */ + + while( count-- ) + { + /* REVIEW: we should consider something like + (*src << 16) | (*src & 0xFFFF) + */ + + *dest = *src << 16; + + src += sourceStride; + dest += destinationStride; + } +} + +/* -------------------------------------------------------------------------- */ + +static void Int16_To_Int24( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + PaInt16 *src = (PaInt16*) sourceBuffer; + unsigned char *dest = (unsigned char*)destinationBuffer; + PaInt16 temp; + + (void) ditherGenerator; /* unused parameter */ + + while( count-- ) + { + temp = *src; + +#if defined(PA_LITTLE_ENDIAN) + dest[0] = 0; + dest[1] = (unsigned char)(temp); + dest[2] = (unsigned char)(temp >> 8); +#elif defined(PA_BIG_ENDIAN) + dest[0] = (unsigned char)(temp >> 8); + dest[1] = (unsigned char)(temp); + dest[2] = 0; +#endif + + src += sourceStride; + dest += destinationStride * 3; + } +} + +/* -------------------------------------------------------------------------- */ + +static void Int16_To_Int8( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + PaInt16 *src = (PaInt16*)sourceBuffer; + signed char *dest = (signed char*)destinationBuffer; + (void)ditherGenerator; /* unused parameter */ + + while( count-- ) + { + (*dest) = (signed char)((*src) >> 8); + + src += sourceStride; + dest += destinationStride; + } +} + +/* -------------------------------------------------------------------------- */ + +static void Int16_To_Int8_Dither( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + PaInt16 *src = (PaInt16*)sourceBuffer; + signed char *dest = (signed char*)destinationBuffer; + (void)ditherGenerator; /* unused parameter */ + + while( count-- ) + { + /* IMPLEMENT ME */ + + src += sourceStride; + dest += destinationStride; + } +} + +/* -------------------------------------------------------------------------- */ + +static void Int16_To_UInt8( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + PaInt16 *src = (PaInt16*)sourceBuffer; + unsigned char *dest = (unsigned char*)destinationBuffer; + (void)ditherGenerator; /* unused parameter */ + + while( count-- ) + { + (*dest) = (unsigned char)(((*src) >> 8) + 128); + + src += sourceStride; + dest += destinationStride; + } +} + +/* -------------------------------------------------------------------------- */ + +static void Int16_To_UInt8_Dither( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + PaInt16 *src = (PaInt16*)sourceBuffer; + unsigned char *dest = (unsigned char*)destinationBuffer; + (void)ditherGenerator; /* unused parameter */ + + while( count-- ) + { + /* IMPLEMENT ME */ + + src += sourceStride; + dest += destinationStride; + } +} + +/* -------------------------------------------------------------------------- */ + +static void Int8_To_Float32( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + signed char *src = (signed char*)sourceBuffer; + float *dest = (float*)destinationBuffer; + (void)ditherGenerator; /* unused parameter */ + + while( count-- ) + { + float samp = *src * const_1_div_128_; + *dest = samp; + + src += sourceStride; + dest += destinationStride; + } +} + +/* -------------------------------------------------------------------------- */ + +static void Int8_To_Int32( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + signed char *src = (signed char*)sourceBuffer; + PaInt32 *dest = (PaInt32*)destinationBuffer; + (void)ditherGenerator; /* unused parameter */ + + while( count-- ) + { + (*dest) = (*src) << 24; + + src += sourceStride; + dest += destinationStride; + } +} + +/* -------------------------------------------------------------------------- */ + +static void Int8_To_Int24( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + signed char *src = (signed char*)sourceBuffer; + unsigned char *dest = (unsigned char*)destinationBuffer; + (void)ditherGenerator; /* unused parameter */ + + while( count-- ) + { + +#if defined(PA_LITTLE_ENDIAN) + dest[0] = 0; + dest[1] = 0; + dest[2] = (*src); +#elif defined(PA_BIG_ENDIAN) + dest[0] = (*src); + dest[1] = 0; + dest[2] = 0; +#endif + + src += sourceStride; + dest += destinationStride * 3; + } +} + +/* -------------------------------------------------------------------------- */ + +static void Int8_To_Int16( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + signed char *src = (signed char*)sourceBuffer; + PaInt16 *dest = (PaInt16*)destinationBuffer; + (void)ditherGenerator; /* unused parameter */ + + while( count-- ) + { + (*dest) = (PaInt16)((*src) << 8); + + src += sourceStride; + dest += destinationStride; + } +} + +/* -------------------------------------------------------------------------- */ + +static void Int8_To_UInt8( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + signed char *src = (signed char*)sourceBuffer; + unsigned char *dest = (unsigned char*)destinationBuffer; + (void)ditherGenerator; /* unused parameter */ + + while( count-- ) + { + (*dest) = (unsigned char)(*src + 128); + + src += sourceStride; + dest += destinationStride; + } +} + +/* -------------------------------------------------------------------------- */ + +static void UInt8_To_Float32( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + unsigned char *src = (unsigned char*)sourceBuffer; + float *dest = (float*)destinationBuffer; + (void)ditherGenerator; /* unused parameter */ + + while( count-- ) + { + float samp = (*src - 128) * const_1_div_128_; + *dest = samp; + + src += sourceStride; + dest += destinationStride; + } +} + +/* -------------------------------------------------------------------------- */ + +static void UInt8_To_Int32( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + unsigned char *src = (unsigned char*)sourceBuffer; + PaInt32 *dest = (PaInt32*)destinationBuffer; + (void)ditherGenerator; /* unused parameter */ + + while( count-- ) + { + (*dest) = (*src - 128) << 24; + + src += sourceStride; + dest += destinationStride; + } +} + +/* -------------------------------------------------------------------------- */ + +static void UInt8_To_Int24( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + unsigned char *src = (unsigned char*)sourceBuffer; + unsigned char *dest = (unsigned char*)destinationBuffer; + (void) ditherGenerator; /* unused parameters */ + + while( count-- ) + { + +#if defined(PA_LITTLE_ENDIAN) + dest[0] = 0; + dest[1] = 0; + dest[2] = (unsigned char)(*src - 128); +#elif defined(PA_BIG_ENDIAN) + dest[0] = (unsigned char)(*src - 128); + dest[1] = 0; + dest[2] = 0; +#endif + + src += sourceStride; + dest += destinationStride * 3; + } +} + +/* -------------------------------------------------------------------------- */ + +static void UInt8_To_Int16( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + unsigned char *src = (unsigned char*)sourceBuffer; + PaInt16 *dest = (PaInt16*)destinationBuffer; + (void)ditherGenerator; /* unused parameter */ + + while( count-- ) + { + (*dest) = (PaInt16)((*src - 128) << 8); + + src += sourceStride; + dest += destinationStride; + } +} + +/* -------------------------------------------------------------------------- */ + +static void UInt8_To_Int8( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + unsigned char *src = (unsigned char*)sourceBuffer; + signed char *dest = (signed char*)destinationBuffer; + (void)ditherGenerator; /* unused parameter */ + + while( count-- ) + { + (*dest) = (signed char)(*src - 128); + + src += sourceStride; + dest += destinationStride; + } +} + +/* -------------------------------------------------------------------------- */ + +static void Copy_8_To_8( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + unsigned char *src = (unsigned char*)sourceBuffer; + unsigned char *dest = (unsigned char*)destinationBuffer; + + (void) ditherGenerator; /* unused parameter */ + + while( count-- ) + { + *dest = *src; + + src += sourceStride; + dest += destinationStride; + } +} + +/* -------------------------------------------------------------------------- */ + +static void Copy_16_To_16( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + PaUint16 *src = (PaUint16 *)sourceBuffer; + PaUint16 *dest = (PaUint16 *)destinationBuffer; + + (void) ditherGenerator; /* unused parameter */ + + while( count-- ) + { + *dest = *src; + + src += sourceStride; + dest += destinationStride; + } +} + +/* -------------------------------------------------------------------------- */ + +static void Copy_24_To_24( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + unsigned char *src = (unsigned char*)sourceBuffer; + unsigned char *dest = (unsigned char*)destinationBuffer; + + (void) ditherGenerator; /* unused parameter */ + + while( count-- ) + { + dest[0] = src[0]; + dest[1] = src[1]; + dest[2] = src[2]; + + src += sourceStride * 3; + dest += destinationStride * 3; + } +} + +/* -------------------------------------------------------------------------- */ + +static void Copy_32_To_32( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ) +{ + PaUint32 *dest = (PaUint32 *)destinationBuffer; + PaUint32 *src = (PaUint32 *)sourceBuffer; + + (void) ditherGenerator; /* unused parameter */ + + while( count-- ) + { + *dest = *src; + + src += sourceStride; + dest += destinationStride; + } +} + +/* -------------------------------------------------------------------------- */ + +PaUtilConverterTable paConverters = { + Float32_To_Int32, /* PaUtilConverter *Float32_To_Int32; */ + Float32_To_Int32_Dither, /* PaUtilConverter *Float32_To_Int32_Dither; */ + Float32_To_Int32_Clip, /* PaUtilConverter *Float32_To_Int32_Clip; */ + Float32_To_Int32_DitherClip, /* PaUtilConverter *Float32_To_Int32_DitherClip; */ + + Float32_To_Int24, /* PaUtilConverter *Float32_To_Int24; */ + Float32_To_Int24_Dither, /* PaUtilConverter *Float32_To_Int24_Dither; */ + Float32_To_Int24_Clip, /* PaUtilConverter *Float32_To_Int24_Clip; */ + Float32_To_Int24_DitherClip, /* PaUtilConverter *Float32_To_Int24_DitherClip; */ + + Float32_To_Int16, /* PaUtilConverter *Float32_To_Int16; */ + Float32_To_Int16_Dither, /* PaUtilConverter *Float32_To_Int16_Dither; */ + Float32_To_Int16_Clip, /* PaUtilConverter *Float32_To_Int16_Clip; */ + Float32_To_Int16_DitherClip, /* PaUtilConverter *Float32_To_Int16_DitherClip; */ + + Float32_To_Int8, /* PaUtilConverter *Float32_To_Int8; */ + Float32_To_Int8_Dither, /* PaUtilConverter *Float32_To_Int8_Dither; */ + Float32_To_Int8_Clip, /* PaUtilConverter *Float32_To_Int8_Clip; */ + Float32_To_Int8_DitherClip, /* PaUtilConverter *Float32_To_Int8_DitherClip; */ + + Float32_To_UInt8, /* PaUtilConverter *Float32_To_UInt8; */ + Float32_To_UInt8_Dither, /* PaUtilConverter *Float32_To_UInt8_Dither; */ + Float32_To_UInt8_Clip, /* PaUtilConverter *Float32_To_UInt8_Clip; */ + Float32_To_UInt8_DitherClip, /* PaUtilConverter *Float32_To_UInt8_DitherClip; */ + + Int32_To_Float32, /* PaUtilConverter *Int32_To_Float32; */ + Int32_To_Int24, /* PaUtilConverter *Int32_To_Int24; */ + Int32_To_Int24_Dither, /* PaUtilConverter *Int32_To_Int24_Dither; */ + Int32_To_Int16, /* PaUtilConverter *Int32_To_Int16; */ + Int32_To_Int16_Dither, /* PaUtilConverter *Int32_To_Int16_Dither; */ + Int32_To_Int8, /* PaUtilConverter *Int32_To_Int8; */ + Int32_To_Int8_Dither, /* PaUtilConverter *Int32_To_Int8_Dither; */ + Int32_To_UInt8, /* PaUtilConverter *Int32_To_UInt8; */ + Int32_To_UInt8_Dither, /* PaUtilConverter *Int32_To_UInt8_Dither; */ + + Int24_To_Float32, /* PaUtilConverter *Int24_To_Float32; */ + Int24_To_Int32, /* PaUtilConverter *Int24_To_Int32; */ + Int24_To_Int16, /* PaUtilConverter *Int24_To_Int16; */ + Int24_To_Int16_Dither, /* PaUtilConverter *Int24_To_Int16_Dither; */ + Int24_To_Int8, /* PaUtilConverter *Int24_To_Int8; */ + Int24_To_Int8_Dither, /* PaUtilConverter *Int24_To_Int8_Dither; */ + Int24_To_UInt8, /* PaUtilConverter *Int24_To_UInt8; */ + Int24_To_UInt8_Dither, /* PaUtilConverter *Int24_To_UInt8_Dither; */ + + Int16_To_Float32, /* PaUtilConverter *Int16_To_Float32; */ + Int16_To_Int32, /* PaUtilConverter *Int16_To_Int32; */ + Int16_To_Int24, /* PaUtilConverter *Int16_To_Int24; */ + Int16_To_Int8, /* PaUtilConverter *Int16_To_Int8; */ + Int16_To_Int8_Dither, /* PaUtilConverter *Int16_To_Int8_Dither; */ + Int16_To_UInt8, /* PaUtilConverter *Int16_To_UInt8; */ + Int16_To_UInt8_Dither, /* PaUtilConverter *Int16_To_UInt8_Dither; */ + + Int8_To_Float32, /* PaUtilConverter *Int8_To_Float32; */ + Int8_To_Int32, /* PaUtilConverter *Int8_To_Int32; */ + Int8_To_Int24, /* PaUtilConverter *Int8_To_Int24 */ + Int8_To_Int16, /* PaUtilConverter *Int8_To_Int16; */ + Int8_To_UInt8, /* PaUtilConverter *Int8_To_UInt8; */ + + UInt8_To_Float32, /* PaUtilConverter *UInt8_To_Float32; */ + UInt8_To_Int32, /* PaUtilConverter *UInt8_To_Int32; */ + UInt8_To_Int24, /* PaUtilConverter *UInt8_To_Int24; */ + UInt8_To_Int16, /* PaUtilConverter *UInt8_To_Int16; */ + UInt8_To_Int8, /* PaUtilConverter *UInt8_To_Int8; */ + + Copy_8_To_8, /* PaUtilConverter *Copy_8_To_8; */ + Copy_16_To_16, /* PaUtilConverter *Copy_16_To_16; */ + Copy_24_To_24, /* PaUtilConverter *Copy_24_To_24; */ + Copy_32_To_32 /* PaUtilConverter *Copy_32_To_32; */ +}; + +/* -------------------------------------------------------------------------- */ + +#endif /* PA_NO_STANDARD_CONVERTERS */ + +/* -------------------------------------------------------------------------- */ + +PaUtilZeroer* PaUtil_SelectZeroer( PaSampleFormat destinationFormat ) +{ + switch( destinationFormat & ~paNonInterleaved ){ + case paFloat32: + return paZeroers.Zero32; + case paInt32: + return paZeroers.Zero32; + case paInt24: + return paZeroers.Zero24; + case paInt16: + return paZeroers.Zero16; + case paInt8: + return paZeroers.Zero8; + case paUInt8: + return paZeroers.ZeroU8; + default: return 0; + } +} + +/* -------------------------------------------------------------------------- */ + +#ifdef PA_NO_STANDARD_ZEROERS + +/* -------------------------------------------------------------------------- */ + +PaUtilZeroerTable paZeroers = { + 0, /* PaUtilZeroer *ZeroU8; */ + 0, /* PaUtilZeroer *Zero8; */ + 0, /* PaUtilZeroer *Zero16; */ + 0, /* PaUtilZeroer *Zero24; */ + 0, /* PaUtilZeroer *Zero32; */ +}; + +/* -------------------------------------------------------------------------- */ + +#else /* PA_NO_STANDARD_ZEROERS is not defined */ + +/* -------------------------------------------------------------------------- */ + +static void ZeroU8( void *destinationBuffer, signed int destinationStride, + unsigned int count ) +{ + unsigned char *dest = (unsigned char*)destinationBuffer; + + while( count-- ) + { + *dest = 128; + + dest += destinationStride; + } +} + +/* -------------------------------------------------------------------------- */ + +static void Zero8( void *destinationBuffer, signed int destinationStride, + unsigned int count ) +{ + unsigned char *dest = (unsigned char*)destinationBuffer; + + while( count-- ) + { + *dest = 0; + + dest += destinationStride; + } +} + +/* -------------------------------------------------------------------------- */ + +static void Zero16( void *destinationBuffer, signed int destinationStride, + unsigned int count ) +{ + PaUint16 *dest = (PaUint16 *)destinationBuffer; + + while( count-- ) + { + *dest = 0; + + dest += destinationStride; + } +} + +/* -------------------------------------------------------------------------- */ + +static void Zero24( void *destinationBuffer, signed int destinationStride, + unsigned int count ) +{ + unsigned char *dest = (unsigned char*)destinationBuffer; + + while( count-- ) + { + dest[0] = 0; + dest[1] = 0; + dest[2] = 0; + + dest += destinationStride * 3; + } +} + +/* -------------------------------------------------------------------------- */ + +static void Zero32( void *destinationBuffer, signed int destinationStride, + unsigned int count ) +{ + PaUint32 *dest = (PaUint32 *)destinationBuffer; + + while( count-- ) + { + *dest = 0; + + dest += destinationStride; + } +} + +/* -------------------------------------------------------------------------- */ + +PaUtilZeroerTable paZeroers = { + ZeroU8, /* PaUtilZeroer *ZeroU8; */ + Zero8, /* PaUtilZeroer *Zero8; */ + Zero16, /* PaUtilZeroer *Zero16; */ + Zero24, /* PaUtilZeroer *Zero24; */ + Zero32, /* PaUtilZeroer *Zero32; */ +}; + +/* -------------------------------------------------------------------------- */ + +#endif /* PA_NO_STANDARD_ZEROERS */ diff --git a/pa_common/pa_converters.h b/pa_common/pa_converters.h new file mode 100644 index 0000000..1d83c99 --- /dev/null +++ b/pa_common/pa_converters.h @@ -0,0 +1,254 @@ +#ifndef PA_CONVERTERS_H +#define PA_CONVERTERS_H +/* + * $Id$ + * Portable Audio I/O Library sample conversion mechanism + * + * Based on the Open Source API proposed by Ross Bencina + * Copyright (c) 1999-2002 Phil Burk, 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. + * + * 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. + */ + +/** @file + @brief Conversion functions used to convert buffers of samples from one + format to another. +*/ + + +#include "portaudio.h" /* for PaSampleFormat */ + +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + + +struct PaUtilTriangularDitherGenerator; + + +/** Choose an available sample format which is most appropriate for + representing the requested format. If the requested format is not available + higher quality formats are considered before lower quality formates. + @param availableFormats A variable containing the logical OR of all available + formats. + @param format The desired format. + @return The most appropriate available format for representing the requested + format. +*/ +PaSampleFormat PaUtil_SelectClosestAvailableFormat( + PaSampleFormat availableFormats, PaSampleFormat format ); + + +/* high level conversions functions for use by implementations */ + + +/** The generic sample converter prototype. Sample converters convert count + samples from sourceBuffer to destinationBuffer. The actual type of the data + pointed to by these parameters varys for different converter functions. + @param destinationBuffer A pointer to the first sample of the destination. + @param destinationStride An offset between successive destination samples + expressed in samples (not bytes.) It may be negative. + @param sourceBuffer A pointer to the first sample of the source. + @param sourceStride An offset between successive source samples + expressed in samples (not bytes.) It may be negative. + @param count The number of samples to convert. + @param ditherState State information used to calculate dither. Converters + that do not perform dithering will ignore this parameter, in which case + NULL or invalid dither state may be passed. +*/ +typedef void PaUtilConverter( + void *destinationBuffer, signed int destinationStride, + void *sourceBuffer, signed int sourceStride, + unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator ); + + +/** Find a sample converter function for the given source and destinations + formats and flags (clip and dither.) + @return + A pointer to a PaUtilConverter which will perform the requested + conversion, or NULL if the given format conversion is not supported. + For conversions where clipping or dithering is not necessary, the + clip and dither flags are ignored and a non-clipping or dithering + version is returned. + If the source and destination formats are the same, a function which + copies data of the appropriate size will be returned. +*/ +PaUtilConverter* PaUtil_SelectConverter( PaSampleFormat sourceFormat, + PaSampleFormat destinationFormat, PaStreamFlags flags ); + + +/** The generic buffer zeroer prototype. Buffer zeroers copy count zeros to + destinationBuffer. The actual type of the data pointed to varys for + different zeroer functions. + @param destinationBuffer A pointer to the first sample of the destination. + @param destinationStride An offset between successive destination samples + expressed in samples (not bytes.) It may be negative. + @param count The number of samples to zero. +*/ +typedef void PaUtilZeroer( + void *destinationBuffer, signed int destinationStride, unsigned int count ); + + +/** Find a buffer zeroer function for the given destination format. + @return + A pointer to a PaUtilZeroer which will perform the requested + zeroing. +*/ +PaUtilZeroer* PaUtil_SelectZeroer( PaSampleFormat destinationFormat ); + +/*----------------------------------------------------------------------------*/ +/* low level functions and data structures which may be used for + substituting conversion functions */ + + +/** The type used to store all sample conversion functions. + @see paConverters; +*/ +typedef struct{ + PaUtilConverter *Float32_To_Int32; + PaUtilConverter *Float32_To_Int32_Dither; + PaUtilConverter *Float32_To_Int32_Clip; + PaUtilConverter *Float32_To_Int32_DitherClip; + + PaUtilConverter *Float32_To_Int24; + PaUtilConverter *Float32_To_Int24_Dither; + PaUtilConverter *Float32_To_Int24_Clip; + PaUtilConverter *Float32_To_Int24_DitherClip; + + PaUtilConverter *Float32_To_Int16; + PaUtilConverter *Float32_To_Int16_Dither; + PaUtilConverter *Float32_To_Int16_Clip; + PaUtilConverter *Float32_To_Int16_DitherClip; + + PaUtilConverter *Float32_To_Int8; + PaUtilConverter *Float32_To_Int8_Dither; + PaUtilConverter *Float32_To_Int8_Clip; + PaUtilConverter *Float32_To_Int8_DitherClip; + + PaUtilConverter *Float32_To_UInt8; + PaUtilConverter *Float32_To_UInt8_Dither; + PaUtilConverter *Float32_To_UInt8_Clip; + PaUtilConverter *Float32_To_UInt8_DitherClip; + + PaUtilConverter *Int32_To_Float32; + PaUtilConverter *Int32_To_Int24; + PaUtilConverter *Int32_To_Int24_Dither; + PaUtilConverter *Int32_To_Int16; + PaUtilConverter *Int32_To_Int16_Dither; + PaUtilConverter *Int32_To_Int8; + PaUtilConverter *Int32_To_Int8_Dither; + PaUtilConverter *Int32_To_UInt8; + PaUtilConverter *Int32_To_UInt8_Dither; + + PaUtilConverter *Int24_To_Float32; + PaUtilConverter *Int24_To_Int32; + PaUtilConverter *Int24_To_Int16; + PaUtilConverter *Int24_To_Int16_Dither; + PaUtilConverter *Int24_To_Int8; + PaUtilConverter *Int24_To_Int8_Dither; + PaUtilConverter *Int24_To_UInt8; + PaUtilConverter *Int24_To_UInt8_Dither; + + PaUtilConverter *Int16_To_Float32; + PaUtilConverter *Int16_To_Int32; + PaUtilConverter *Int16_To_Int24; + PaUtilConverter *Int16_To_Int8; + PaUtilConverter *Int16_To_Int8_Dither; + PaUtilConverter *Int16_To_UInt8; + PaUtilConverter *Int16_To_UInt8_Dither; + + PaUtilConverter *Int8_To_Float32; + PaUtilConverter *Int8_To_Int32; + PaUtilConverter *Int8_To_Int24; + PaUtilConverter *Int8_To_Int16; + PaUtilConverter *Int8_To_UInt8; + + PaUtilConverter *UInt8_To_Float32; + PaUtilConverter *UInt8_To_Int32; + PaUtilConverter *UInt8_To_Int24; + PaUtilConverter *UInt8_To_Int16; + PaUtilConverter *UInt8_To_Int8; + + PaUtilConverter *Copy_8_To_8; /* copy without any conversion */ + PaUtilConverter *Copy_16_To_16; /* copy without any conversion */ + PaUtilConverter *Copy_24_To_24; /* copy without any conversion */ + PaUtilConverter *Copy_32_To_32; /* copy without any conversion */ +} PaUtilConverterTable; + + +/** A table of pointers to all required converter functions. + PaUtil_SelectConverter() uses this table to lookup the appropriate + conversion functions. The fields of this structure are initialized + with default conversion functions. Fields may be NULL, indicating that + no conversion function is available. User code may substitue optimised + conversion functions by assigning different function pointers to + these fields. + + @note + If the PA_NO_STANDARD_CONVERTERS preprocessor variable is defined, + PortAudio's standard converters will not be compiled, and all fields + of this structure will be initialized to NULL. In such cases, users + should supply their own conversion functions if the require PortAudio + to open a stream that requires sample conversion. + + @see PaUtilConverterTable, PaUtilConverter, PaUtil_SelectConverter +*/ +extern PaUtilConverterTable paConverters; + + +/** The type used to store all buffer zeroing functions. + @see paZeroers; +*/ +typedef struct{ + PaUtilZeroer *ZeroU8; /* unsigned 8 bit, zero == 128 */ + PaUtilZeroer *Zero8; + PaUtilZeroer *Zero16; + PaUtilZeroer *Zero24; + PaUtilZeroer *Zero32; +} PaUtilZeroerTable; + + +/** A table of pointers to all required zeroer functions. + PaUtil_SelectZeroer() uses this table to lookup the appropriate + conversion functions. The fields of this structure are initialized + with default conversion functions. User code may substitue optimised + conversion functions by assigning different function pointers to + these fields. + + @note + If the PA_NO_STANDARD_ZEROERS preprocessor variable is defined, + PortAudio's standard zeroers will not be compiled, and all fields + of this structure will be initialized to NULL. In such cases, users + should supply their own zeroing functions for the sample sizes which + they intend to use. + + @see PaUtilZeroerTable, PaUtilZeroer, PaUtil_SelectZeroer +*/ +extern PaUtilZeroerTable paZeroers; + +#ifdef __cplusplus +} +#endif /* __cplusplus */ +#endif /* PA_CONVERTERS_H */ diff --git a/pa_common/pa_cpuload.c b/pa_common/pa_cpuload.c new file mode 100644 index 0000000..ee2147d --- /dev/null +++ b/pa_common/pa_cpuload.c @@ -0,0 +1,96 @@ +/* + * $Id$ + * Portable Audio I/O Library CPU Load measurement functions + * Portable CPU load measurement facility. + * + * Based on the Open Source API proposed by Ross Bencina + * Copyright (c) 2002 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. + * + * 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. + */ + +/** @file + @brief Functions to assist in measuring the CPU utilization of a callback + stream. Used to implement the Pa_GetStreamCpuLoad() function. + + @todo Dynamically calculate the coefficients used to smooth the CPU Load + Measurements over time to provide a uniform characterisation of CPU Load + independent of rate at which PaUtil_BeginCpuLoadMeasurement / + PaUtil_EndCpuLoadMeasurement are called. +*/ + + +#include "pa_cpuload.h" + +#include + +#include "pa_util.h" /* for PaUtil_GetTime() */ + + +void PaUtil_InitializeCpuLoadMeasurer( PaUtilCpuLoadMeasurer* measurer, double sampleRate ) +{ + assert( sampleRate > 0 ); + + measurer->samplingPeriod = 1. / sampleRate; + measurer->averageLoad = 0.; +} + +void PaUtil_ResetCpuLoadMeasurer( PaUtilCpuLoadMeasurer* measurer ) +{ + measurer->averageLoad = 0.; +} + +void PaUtil_BeginCpuLoadMeasurement( PaUtilCpuLoadMeasurer* measurer ) +{ + measurer->measurementStartTime = PaUtil_GetTime(); +} + + +void PaUtil_EndCpuLoadMeasurement( PaUtilCpuLoadMeasurer* measurer, unsigned long framesProcessed ) +{ + double measurementEndTime, secondsFor100Percent, measuredLoad; + + if( framesProcessed > 0 ){ + measurementEndTime = PaUtil_GetTime(); + + assert( framesProcessed > 0 ); + secondsFor100Percent = framesProcessed * measurer->samplingPeriod; + + measuredLoad = (measurementEndTime - measurer->measurementStartTime) / secondsFor100Percent; + + /* Low pass filter the calculated CPU load to reduce jitter using a simple IIR low pass filter. */ + /** FIXME @todo these coefficients shouldn't be hardwired */ +#define LOWPASS_COEFFICIENT_0 (0.9) +#define LOWPASS_COEFFICIENT_1 (0.99999 - LOWPASS_COEFFICIENT_0) + + measurer->averageLoad = (LOWPASS_COEFFICIENT_0 * measurer->averageLoad) + + (LOWPASS_COEFFICIENT_1 * measuredLoad); + } +} + + +double PaUtil_GetCpuLoad( PaUtilCpuLoadMeasurer* measurer ) +{ + return measurer->averageLoad; +} diff --git a/pa_common/pa_cpuload.h b/pa_common/pa_cpuload.h new file mode 100644 index 0000000..131ad10 --- /dev/null +++ b/pa_common/pa_cpuload.h @@ -0,0 +1,63 @@ +#ifndef PA_CPULOAD_H +#define PA_CPULOAD_H +/* + * $Id$ + * Portable Audio I/O Library CPU Load measurement functions + * Portable CPU load measurement facility. + * + * Based on the Open Source API proposed by Ross Bencina + * Copyright (c) 2002 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. + * + * 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. + */ + +/** @file + @brief Functions to assist in measuring the CPU utilization of a callback + stream. Used to implement the Pa_GetStreamCpuLoad() function. +*/ + + +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + + +typedef struct { + double samplingPeriod; + double measurementStartTime; + double averageLoad; +} PaUtilCpuLoadMeasurer; /**< @todo need better name than measurer */ + +void PaUtil_InitializeCpuLoadMeasurer( PaUtilCpuLoadMeasurer* measurer, double sampleRate ); +void PaUtil_BeginCpuLoadMeasurement( PaUtilCpuLoadMeasurer* measurer ); +void PaUtil_EndCpuLoadMeasurement( PaUtilCpuLoadMeasurer* measurer, unsigned long framesProcessed ); +void PaUtil_ResetCpuLoadMeasurer( PaUtilCpuLoadMeasurer* measurer ); +double PaUtil_GetCpuLoad( PaUtilCpuLoadMeasurer* measurer ); + + +#ifdef __cplusplus +} +#endif /* __cplusplus */ +#endif /* PA_CPULOAD_H */ diff --git a/pa_common/pa_dither.c b/pa_common/pa_dither.c new file mode 100644 index 0000000..d44a060 --- /dev/null +++ b/pa_common/pa_dither.c @@ -0,0 +1,204 @@ +/* + * $Id$ + * Portable Audio I/O Library triangular dither generator + * + * Based on the Open Source API proposed by Ross Bencina + * Copyright (c) 1999-2002 Phil Burk, 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. + * + * 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. + */ + +/** @file + @brief Functions for generating dither noise +*/ + + +#include "pa_dither.h" +#include "pa_types.h" + +#define PA_DITHER_BITS_ (15) + + +void PaUtil_InitializeTriangularDitherState( PaUtilTriangularDitherGenerator *state ) +{ + state->previous = 0; + state->randSeed1 = 22222; + state->randSeed2 = 5555555; +} + + +signed long PaUtil_Generate16BitTriangularDither( PaUtilTriangularDitherGenerator *state ) +{ + signed long current, highPass; + + /* Generate two random numbers. */ + state->randSeed1 = (state->randSeed1 * 196314165) + 907633515; + state->randSeed2 = (state->randSeed2 * 196314165) + 907633515; + + /* Generate triangular distribution about 0. + * Shift before adding to prevent overflow which would skew the distribution. + * Also shift an extra bit for the high pass filter. + */ +#define DITHER_SHIFT_ ((SIZEOF_LONG*8 - PA_DITHER_BITS_) + 1) + current = (((signed long)state->randSeed1)>>DITHER_SHIFT_) + + (((signed long)state->randSeed2)>>DITHER_SHIFT_); + + /* High pass filter to reduce audibility. */ + highPass = current - state->previous; + state->previous = current; + return highPass; +} + + +/* Multiply by PA_FLOAT_DITHER_SCALE_ to get a float between -2.0 and +1.99999 */ +#define PA_FLOAT_DITHER_SCALE_ (1.0f / ((1<randSeed1 = (state->randSeed1 * 196314165) + 907633515; + state->randSeed2 = (state->randSeed2 * 196314165) + 907633515; + + /* Generate triangular distribution about 0. + * Shift before adding to prevent overflow which would skew the distribution. + * Also shift an extra bit for the high pass filter. + */ +#define DITHER_SHIFT_ ((SIZEOF_LONG*8 - PA_DITHER_BITS_) + 1) + current = (((signed long)state->randSeed1)>>DITHER_SHIFT_) + + (((signed long)state->randSeed2)>>DITHER_SHIFT_); + + /* High pass filter to reduce audibility. */ + highPass = current - state->previous; + state->previous = current; + return ((float)highPass) * const_float_dither_scale_; +} + + +/* +The following alternate dither algorithms (from musicdsp.org) could be +considered +*/ + +/*Noise shaped dither (March 2000) +------------------- + +This is a simple implementation of highpass triangular-PDF dither with +2nd-order noise shaping, for use when truncating floating point audio +data to fixed point. + +The noise shaping lowers the noise floor by 11dB below 5kHz (@ 44100Hz +sample rate) compared to triangular-PDF dither. The code below assumes +input data is in the range +1 to -1 and doesn't check for overloads! + +To save time when generating dither for multiple channels you can do +things like this: r3=(r1 & 0x7F)<<8; instead of calling rand() again. + + + + int r1, r2; //rectangular-PDF random numbers + float s1, s2; //error feedback buffers + float s = 0.5f; //set to 0.0f for no noise shaping + float w = pow(2.0,bits-1); //word length (usually bits=16) + float wi= 1.0f/w; + float d = wi / RAND_MAX; //dither amplitude (2 lsb) + float o = wi * 0.5f; //remove dc offset + float in, tmp; + int out; + + +//for each sample... + + r2=r1; //can make HP-TRI dither by + r1=rand(); //subtracting previous rand() + + in += s * (s1 + s1 - s2); //error feedback + tmp = in + o + d * (float)(r1 - r2); //dc offset and dither + + out = (int)(w * tmp); //truncate downwards + if(tmp<0.0f) out--; //this is faster than floor() + + s2 = s1; + s1 = in - wi * (float)out; //error + + + +-- +paul.kellett@maxim.abel.co.uk +http://www.maxim.abel.co.uk +*/ + + +/* +16-to-8-bit first-order dither + +Type : First order error feedforward dithering code +References : Posted by Jon Watte + +Notes : +This is about as simple a dithering algorithm as you can implement, but it's +likely to sound better than just truncating to N bits. + +Note that you might not want to carry forward the full difference for infinity. +It's probably likely that the worst performance hit comes from the saturation +conditionals, which can be avoided with appropriate instructions on many DSPs +and integer SIMD type instructions, or CMOV. + +Last, if sound quality is paramount (such as when going from > 16 bits to 16 +bits) you probably want to use a higher-order dither function found elsewhere +on this site. + + +Code : +// This code will down-convert and dither a 16-bit signed short +// mono signal into an 8-bit unsigned char signal, using a first +// order forward-feeding error term dither. + +#define uchar unsigned char + +void dither_one_channel_16_to_8( short * input, uchar * output, int count, int * memory ) +{ + int m = *memory; + while( count-- > 0 ) { + int i = *input++; + i += m; + int j = i + 32768 - 128; + uchar o; + if( j < 0 ) { + o = 0; + } + else if( j > 65535 ) { + o = 255; + } + else { + o = (uchar)((j>>8)&0xff); + } + m = ((j-32768+128)-i); + *output++ = o; + } + *memory = m; +} +*/ diff --git a/pa_common/pa_dither.h b/pa_common/pa_dither.h new file mode 100644 index 0000000..148db27 --- /dev/null +++ b/pa_common/pa_dither.h @@ -0,0 +1,91 @@ +#ifndef PA_DITHER_H +#define PA_DITHER_H +/* + * $Id$ + * Portable Audio I/O Library triangular dither generator + * + * Based on the Open Source API proposed by Ross Bencina + * Copyright (c) 1999-2002 Phil Burk, 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. + * + * 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. + */ + +/** @file + @brief Functions for generating dither noise +*/ + + +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + + +/** @brief State needed to generate a dither signal */ +typedef struct PaUtilTriangularDitherGenerator{ + unsigned long previous; + unsigned long randSeed1; + unsigned long randSeed2; +} PaUtilTriangularDitherGenerator; + + +/** @brief Initialize dither state */ +void PaUtil_InitializeTriangularDitherState( PaUtilTriangularDitherGenerator *ditherState ); + + +/** + @brief Calculate 2 LSB dither signal with a triangular distribution. + Ranged for adding to a 1 bit right-shifted 32 bit integer + prior to >>15. eg: +
+    signed long in = *
+    signed long dither = PaUtil_Generate16BitTriangularDither( ditherState );
+    signed short out = (signed short)(((in>>1) + dither) >> 15);
+
+ @return + A signed long with a range of +32767 to -32768 +*/ +signed long PaUtil_Generate16BitTriangularDither( PaUtilTriangularDitherGenerator *ditherState ); + + +/** + @brief Calculate 2 LSB dither signal with a triangular distribution. + Ranged for adding to a pre-scaled float. +
+    float in = *
+    float dither = PaUtil_GenerateFloatTriangularDither( ditherState );
+    // use smaller scaler to prevent overflow when we add the dither
+    signed short out = (signed short)(in*(32766.0f) + dither );
+
+ @return + A float with a range of -2.0 to +1.99999. +*/ +float PaUtil_GenerateFloatTriangularDither( PaUtilTriangularDitherGenerator *ditherState ); + + + +#ifdef __cplusplus +} +#endif /* __cplusplus */ +#endif /* PA_DITHER_H */ diff --git a/pa_common/pa_endianness.h b/pa_common/pa_endianness.h new file mode 100644 index 0000000..a49be96 --- /dev/null +++ b/pa_common/pa_endianness.h @@ -0,0 +1,130 @@ +#ifndef PA_ENDIANNESS_H +#define PA_ENDIANNESS_H +/* + * $Id$ + * Portable Audio I/O Library current platform endianness macros + * + * Based on the Open Source API proposed by Ross Bencina + * Copyright (c) 1999-2002 Phil Burk, 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. + * + * 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. + */ + +/** @file + @brief Configure endianness symbols for the target processor. + + Arrange for either the PA_LITTLE_ENDIAN or PA_BIG_ENDIAN preprocessor symbols + to be defined. The one that is defined reflects the endianness of the target + platform and may be used to implement conditional compilation of byte-order + dependent code. + + If either PA_LITTLE_ENDIAN or PA_BIG_ENDIAN is defined already, then no attempt + is made to override that setting. This may be useful if you have a better way + of determining the platform's endianness. The autoconf mechanism uses this for + example. + + A PA_VALIDATE_ENDIANNESS macro is provided to compare the compile time + and runtime endiannes and raise an assertion if they don't match. +*/ + + +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +/* If this is an apple, we need to do detect endianness this way */ +#if defined(__APPLE__) + /* we need to do some endian detection that is sensitive to harware arch */ + #if defined(__LITTLE_ENDIAN__) + #if !defined( PA_LITTLE_ENDIAN ) + #define PA_LITTLE_ENDIAN + #endif + #if defined( PA_BIG_ENDIAN ) + #undef PA_BIG_ENDIAN + #endif + #else + #if !defined( PA_BIG_ENDIAN ) + #define PA_BIG_ENDIAN + #endif + #if defined( PA_LITTLE_ENDIAN ) + #undef PA_LITTLE_ENDIAN + #endif + #endif +#else + /* this is not an apple, so first check the existing defines, and, failing that, + detect well-known architechtures. */ + + #if defined(PA_LITTLE_ENDIAN) || defined(PA_BIG_ENDIAN) + /* endianness define has been set externally, such as by autoconf */ + + #if defined(PA_LITTLE_ENDIAN) && defined(PA_BIG_ENDIAN) + #error both PA_LITTLE_ENDIAN and PA_BIG_ENDIAN have been defined externally to pa_endianness.h - only one endianness at a time please + #endif + + #endif + /* endianness define has not been set externally */ + + /* set PA_LITTLE_ENDIAN or PA_BIG_ENDIAN by testing well known platform specific defines */ + + #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__) || defined(LITTLE_ENDIAN) || defined(__i386) || defined(_M_IX86) + #define PA_LITTLE_ENDIAN /* win32, assume intel byte order */ + #else + #define PA_BIG_ENDIAN + #endif + + #if !defined(PA_LITTLE_ENDIAN) && !defined(PA_BIG_ENDIAN) + /* + If the following error is raised, you either need to modify the code above + to automatically determine the endianness from other symbols defined on your + platform, or define either PA_LITTLE_ENDIAN or PA_BIG_ENDIAN externally. + */ + #error pa_endianness.h was unable to automatically determine the endianness of the target platform + #endif + +#endif + +/* PA_VALIDATE_ENDIANNESS compares the compile time and runtime endianness, + and raises an assertion if they don't match. must be included in + the context in which this macro is used. +*/ +#if defined(PA_LITTLE_ENDIAN) + #define PA_VALIDATE_ENDIANNESS \ + { \ + const long nativeOne = 1; \ + assert( "PortAudio: compile time and runtime endianness don't match" && (((char *)&nativeOne)[0]) == 1 ); \ + } +#elif defined(PA_BIG_ENDIAN) + #define PA_VALIDATE_ENDIANNESS \ + { \ + const long nativeOne = 1; \ + assert( "PortAudio: compile time and runtime endianness don't match" && (((char *)&nativeOne)[0]) == 0 ); \ + } +#endif + + +#ifdef __cplusplus +} +#endif /* __cplusplus */ +#endif /* PA_ENDIANNESS_H */ diff --git a/pa_common/pa_front.c b/pa_common/pa_front.c new file mode 100644 index 0000000..e80b207 --- /dev/null +++ b/pa_common/pa_front.c @@ -0,0 +1,1981 @@ +/* + * $Id$ + * Portable Audio I/O Library Multi-Host API front end + * Validate function parameters and manage multiple host APIs. + * + * 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. + * + * 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. + */ + +/* doxygen index page */ +/** @mainpage + +PortAudio is an open-source cross-platform ‘C’ library for audio input +and output. It is designed to simplify the porting of audio applications +between various platforms, and also to simplify the development of audio +software in general by hiding the complexities of device interfacing. + +See the PortAudio website for further information http://www.portaudio.com/ + +This documentation pertains to PortAudio V19, API version 2.0 which is +currently under development. API version 2.0 differs in a number of ways from +previous versions, please consult the enhancement proposals for further details: +http://www.portaudio.com/docs/proposals/index.html + +This documentation is under construction. Things you might be interested in +include: + +- The PortAudio API 2.0, as documented in portaudio.h + +- The TODO List + +Feel free to pick an item off TODO list and fix/implement it. You may want to +enquire about status on the PortAudio mailing list first. +*/ + + +/** @file + @brief Implements public PortAudio API, checks some errors, forwards to + host API implementations. + + Implements the functions defined in the PortAudio API, checks for + some parameter and state inconsistencies and forwards API requests to + specific Host API implementations (via the interface declared in + pa_hostapi.h), and Streams (via the interface declared in pa_stream.h). + + This file handles initialization and termination of Host API + implementations via initializers stored in the paHostApiInitializers + global variable. + + Some utility functions declared in pa_util.h are implemented in this file. + + All PortAudio API functions can be conditionally compiled with logging code. + To compile with logging, define the PA_LOG_API_CALLS precompiler symbol. + + @todo Consider adding host API specific error text in Pa_GetErrorText() for + paUnanticipatedHostError + + @todo Consider adding a new error code for when (inputParameters == NULL) + && (outputParameters == NULL) + + @todo review whether Pa_CloseStream() should call the interface's + CloseStream function if aborting the stream returns an error code. + + @todo Create new error codes if a NULL buffer pointer, or a + zero frame count is passed to Pa_ReadStream or Pa_WriteStream. +*/ + + +#include +#include +#include +#include +#include /* needed by PA_VALIDATE_ENDIANNESS */ + +#include "portaudio.h" +#include "pa_util.h" +#include "pa_endianness.h" +#include "pa_types.h" +#include "pa_hostapi.h" +#include "pa_stream.h" + +#include "pa_trace.h" + + +#define PA_VERSION_ 1899 +#define PA_VERSION_TEXT_ "PortAudio V19-devel" + + + +/* #define PA_LOG_API_CALLS */ + +/* + The basic format for log messages is described below. If you need to + add any log messages, please follow this format. + + Function entry (void function): + + "FunctionName called.\n" + + Function entry (non void function): + + "FunctionName called:\n" + "\tParam1Type param1: param1Value\n" + "\tParam2Type param2: param2Value\n" (etc...) + + + Function exit (no return value): + + "FunctionName returned.\n" + + Function exit (simple return value): + + "FunctionName returned:\n" + "\tReturnType: returnValue\n\n" + + If the return type is an error code, the error text is displayed in () + + If the return type is not an error code, but has taken a special value + because an error occurred, then the reason for the error is shown in [] + + If the return type is a struct ptr, the struct is dumped. + + See the code below for examples +*/ + + +int Pa_GetVersion( void ) +{ + return PA_VERSION_; +} + + +const char* Pa_GetVersionText( void ) +{ + return PA_VERSION_TEXT_; +} + + + +#define PA_LAST_HOST_ERROR_TEXT_LENGTH_ 1024 + +static char lastHostErrorText_[ PA_LAST_HOST_ERROR_TEXT_LENGTH_ + 1 ] = {0}; + +static PaHostErrorInfo lastHostErrorInfo_ = { (PaHostApiTypeId)-1, 0, lastHostErrorText_ }; + + +void PaUtil_SetLastHostErrorInfo( PaHostApiTypeId hostApiType, long errorCode, + const char *errorText ) +{ + lastHostErrorInfo_.hostApiType = hostApiType; + lastHostErrorInfo_.errorCode = errorCode; + + strncpy( lastHostErrorText_, errorText, PA_LAST_HOST_ERROR_TEXT_LENGTH_ ); +} + + +void PaUtil_DebugPrint( const char *format, ... ) +{ + va_list ap; + + va_start( ap, format ); + vfprintf( stderr, format, ap ); + va_end( ap ); + + fflush( stderr ); +} + + +static PaUtilHostApiRepresentation **hostApis_ = 0; +static int hostApisCount_ = 0; +static int initializationCount_ = 0; +static int deviceCount_ = 0; + +PaUtilStreamRepresentation *firstOpenStream_ = NULL; + + +#define PA_IS_INITIALISED_ (initializationCount_ != 0) + + +static int CountHostApiInitializers( void ) +{ + int result = 0; + + while( paHostApiInitializers[ result ] != 0 ) + ++result; + return result; +} + + +static void TerminateHostApis( void ) +{ + /* terminate in reverse order from initialization */ + + while( hostApisCount_ > 0 ) + { + --hostApisCount_; + hostApis_[hostApisCount_]->Terminate( hostApis_[hostApisCount_] ); + } + hostApisCount_ = 0; + deviceCount_ = 0; + + if( hostApis_ != 0 ) + PaUtil_FreeMemory( hostApis_ ); + hostApis_ = 0; +} + + +static PaError InitializeHostApis( void ) +{ + PaError result = paNoError; + int i, initializerCount, baseDeviceIndex; + + initializerCount = CountHostApiInitializers(); + + hostApis_ = (PaUtilHostApiRepresentation**)PaUtil_AllocateMemory( + sizeof(PaUtilHostApiRepresentation*) * initializerCount ); + if( !hostApis_ ) + { + result = paInsufficientMemory; + goto error; + } + + hostApisCount_ = 0; + deviceCount_ = 0; + baseDeviceIndex = 0; + + for( i=0; i< initializerCount; ++i ) + { + hostApis_[hostApisCount_] = NULL; + result = paHostApiInitializers[i]( &hostApis_[hostApisCount_], hostApisCount_ ); + if( result != paNoError ) + goto error; + + if( hostApis_[hostApisCount_] ) + { + PaUtilHostApiRepresentation* hostApi = hostApis_[hostApisCount_]; + assert( hostApi->info.defaultInputDevice < hostApi->info.deviceCount ); + assert( hostApi->info.defaultOutputDevice < hostApi->info.deviceCount ); + + hostApis_[hostApisCount_]->privatePaFrontInfo.baseDeviceIndex = baseDeviceIndex; + + if( hostApis_[hostApisCount_]->info.defaultInputDevice != paNoDevice ) + hostApis_[hostApisCount_]->info.defaultInputDevice += baseDeviceIndex; + + if( hostApis_[hostApisCount_]->info.defaultOutputDevice != paNoDevice ) + hostApis_[hostApisCount_]->info.defaultOutputDevice += baseDeviceIndex; + + baseDeviceIndex += hostApis_[hostApisCount_]->info.deviceCount; + deviceCount_ += hostApis_[hostApisCount_]->info.deviceCount; + + ++hostApisCount_; + } + } + + return result; + +error: + TerminateHostApis(); + return result; +} + + +/* + FindHostApi() finds the index of the host api to which + belongs and returns it. if is + non-null, the host specific device index is returned in it. + returns -1 if is out of range. + +*/ +static int FindHostApi( PaDeviceIndex device, int *hostSpecificDeviceIndex ) +{ + int i=0; + + if( !PA_IS_INITIALISED_ ) + return -1; + + if( device < 0 ) + return -1; + + while( i < hostApisCount_ + && device >= hostApis_[i]->info.deviceCount ) + { + + device -= hostApis_[i]->info.deviceCount; + ++i; + } + + if( i >= hostApisCount_ ) + return -1; + + if( hostSpecificDeviceIndex ) + *hostSpecificDeviceIndex = device; + + return i; +} + + +static void AddOpenStream( PaStream* stream ) +{ + ((PaUtilStreamRepresentation*)stream)->nextOpenStream = firstOpenStream_; + firstOpenStream_ = (PaUtilStreamRepresentation*)stream; +} + + +static void RemoveOpenStream( PaStream* stream ) +{ + PaUtilStreamRepresentation *previous = NULL; + PaUtilStreamRepresentation *current = firstOpenStream_; + + while( current != NULL ) + { + if( ((PaStream*)current) == stream ) + { + if( previous == NULL ) + { + firstOpenStream_ = current->nextOpenStream; + } + else + { + previous->nextOpenStream = current->nextOpenStream; + } + return; + } + else + { + previous = current; + current = current->nextOpenStream; + } + } +} + + +static void CloseOpenStreams( void ) +{ + /* we call Pa_CloseStream() here to ensure that the same destruction + logic is used for automatically closed streams */ + + while( firstOpenStream_ != NULL ) + Pa_CloseStream( firstOpenStream_ ); +} + + +PaError Pa_Initialize( void ) +{ + PaError result; + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint( "Pa_Initialize called.\n" ); +#endif + + if( PA_IS_INITIALISED_ ) + { + ++initializationCount_; + result = paNoError; + } + else + { + PA_VALIDATE_TYPE_SIZES; + PA_VALIDATE_ENDIANNESS; + + PaUtil_InitializeClock(); + PaUtil_ResetTraceMessages(); + + result = InitializeHostApis(); + if( result == paNoError ) + ++initializationCount_; + } + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint( "Pa_Initialize returned:\n" ); + PaUtil_DebugPrint( "\tPaError: %d ( %s )\n\n", result, Pa_GetErrorText( result ) ); +#endif + + return result; +} + + +PaError Pa_Terminate( void ) +{ + PaError result; + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_Terminate called.\n" ); +#endif + + if( PA_IS_INITIALISED_ ) + { + if( --initializationCount_ == 0 ) + { + CloseOpenStreams(); + + TerminateHostApis(); + + PaUtil_DumpTraceMessages(); + } + result = paNoError; + } + else + { + result= paNotInitialized; + } + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_Terminate returned:\n" ); + PaUtil_DebugPrint("\tPaError: %d ( %s )\n\n", result, Pa_GetErrorText( result ) ); +#endif + + return result; +} + + +const PaHostErrorInfo* Pa_GetLastHostErrorInfo( void ) +{ + return &lastHostErrorInfo_; +} + + +const char *Pa_GetErrorText( PaError errorCode ) +{ + const char *result; + + switch( errorCode ) + { + case paNoError: result = "Success"; break; + case paNotInitialized: result = "PortAudio not initialized"; break; + /** @todo could catenate the last host error text to result in the case of paUnanticipatedHostError */ + case paUnanticipatedHostError: result = "Unanticipated host error"; break; + case paInvalidChannelCount: result = "Invalid number of channels"; break; + case paInvalidSampleRate: result = "Invalid sample rate"; break; + case paInvalidDevice: result = "Invalid device"; break; + case paInvalidFlag: result = "Invalid flag"; break; + case paSampleFormatNotSupported: result = "Sample format not supported"; break; + case paBadIODeviceCombination: result = "Illegal combination of I/O devices"; break; + case paInsufficientMemory: result = "Insufficient memory"; break; + case paBufferTooBig: result = "Buffer too big"; break; + case paBufferTooSmall: result = "Buffer too small"; break; + case paNullCallback: result = "No callback routine specified"; break; + case paBadStreamPtr: result = "Invalid stream pointer"; break; + case paTimedOut: result = "Wait timed out"; break; + case paInternalError: result = "Internal PortAudio error"; break; + case paDeviceUnavailable: result = "Device unavailable"; break; + case paIncompatibleHostApiSpecificStreamInfo: result = "Incompatible host API specific stream info"; break; + case paStreamIsStopped: result = "Stream is stopped"; break; + case paStreamIsNotStopped: result = "Stream is not stopped"; break; + case paInputOverflowed: result = "Input overflowed"; break; + case paOutputUnderflowed: result = "Output underflowed"; break; + case paHostApiNotFound: result = "Host API not found"; break; + case paInvalidHostApi: result = "Invalid host API"; break; + case paCanNotReadFromACallbackStream: result = "Can't read from a callback stream"; break; + case paCanNotWriteToACallbackStream: result = "Can't write to a callback stream"; break; + case paCanNotReadFromAnOutputOnlyStream: result = "Can't read from an output only stream"; break; + case paCanNotWriteToAnInputOnlyStream: result = "Can't write to an input only stream"; break; + default: result = "Illegal error number"; break; + } + return result; +} + + +PaHostApiIndex Pa_HostApiTypeIdToHostApiIndex( PaHostApiTypeId type ) +{ + PaHostApiIndex result; + int i; + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_HostApiTypeIdToHostApiIndex called:\n" ); + PaUtil_DebugPrint("\tPaHostApiTypeId type: %d\n", type ); +#endif + + if( !PA_IS_INITIALISED_ ) + { + result = paNotInitialized; + } + else + { + result = paHostApiNotFound; + + for( i=0; i < hostApisCount_; ++i ) + { + if( hostApis_[i]->info.type == type ) + { + result = i; + break; + } + } + } + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_HostApiTypeIdToHostApiIndex returned:\n" ); + if( result < 0 ) + PaUtil_DebugPrint("\tPaError: %d ( %s )\n\n", result, Pa_GetErrorText( result ) ); + else + PaUtil_DebugPrint("\tPaHostApiIndex: %d\n\n", result ); +#endif + + return result; +} + + +PaError PaUtil_GetHostApiRepresentation( struct PaUtilHostApiRepresentation **hostApi, + PaHostApiTypeId type ) +{ + PaError result; + int i; + + if( !PA_IS_INITIALISED_ ) + { + result = paNotInitialized; + } + else + { + result = paHostApiNotFound; + + for( i=0; i < hostApisCount_; ++i ) + { + if( hostApis_[i]->info.type == type ) + { + *hostApi = hostApis_[i]; + result = paNoError; + break; + } + } + } + + return result; +} + + +PaError PaUtil_DeviceIndexToHostApiDeviceIndex( + PaDeviceIndex *hostApiDevice, PaDeviceIndex device, struct PaUtilHostApiRepresentation *hostApi ) +{ + PaError result; + PaDeviceIndex x; + + x = device - hostApi->privatePaFrontInfo.baseDeviceIndex; + + if( x < 0 || x >= hostApi->info.deviceCount ) + { + result = paInvalidDevice; + } + else + { + *hostApiDevice = x; + result = paNoError; + } + + return result; +} + + +PaHostApiIndex Pa_GetHostApiCount( void ) +{ + int result; + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_GetHostApiCount called.\n" ); +#endif + + if( !PA_IS_INITIALISED_ ) + { + result = paNotInitialized; + } + else + { + result = hostApisCount_; + } + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_GetHostApiCount returned:\n" ); + if( result < 0 ) + PaUtil_DebugPrint("\tPaError: %d ( %s )\n\n", result, Pa_GetErrorText( result ) ); + else + PaUtil_DebugPrint("\tPaHostApiIndex %d\n\n", result ); +#endif + + return result; +} + + +PaHostApiIndex Pa_GetDefaultHostApi( void ) +{ + int result; + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_GetDefaultHostApi called.\n" ); +#endif + + if( !PA_IS_INITIALISED_ ) + { + result = paNotInitialized; + } + else + { + result = paDefaultHostApiIndex; + + /* internal consistency check: make sure that the default host api + index is within range */ + + if( result < 0 || result >= hostApisCount_ ) + { + result = paInternalError; + } + } + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_GetDefaultHostApi returned:\n" ); + if( result < 0 ) + PaUtil_DebugPrint("\tPaError: %d ( %s )\n\n", result, Pa_GetErrorText( result ) ); + else + PaUtil_DebugPrint("\tPaHostApiIndex %d\n\n", result ); +#endif + + return result; +} + + +const PaHostApiInfo* Pa_GetHostApiInfo( PaHostApiIndex hostApi ) +{ + PaHostApiInfo *info; + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_GetHostApiInfo called:\n" ); + PaUtil_DebugPrint("\tPaHostApiIndex hostApi: %d\n", hostApi ); +#endif + + if( !PA_IS_INITIALISED_ ) + { + info = NULL; + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_GetHostApiInfo returned:\n" ); + PaUtil_DebugPrint("\tPaHostApiInfo*: NULL [ PortAudio not initialized ]\n\n" ); +#endif + + } + else if( hostApi < 0 || hostApi >= hostApisCount_ ) + { + info = NULL; + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_GetHostApiInfo returned:\n" ); + PaUtil_DebugPrint("\tPaHostApiInfo*: NULL [ hostApi out of range ]\n\n" ); +#endif + + } + else + { + info = &hostApis_[hostApi]->info; + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_GetHostApiInfo returned:\n" ); + PaUtil_DebugPrint("\tPaHostApiInfo*: 0x%p\n", info ); + PaUtil_DebugPrint("\t{" ); + PaUtil_DebugPrint("\t\tint structVersion: %d\n", info->structVersion ); + PaUtil_DebugPrint("\t\tPaHostApiTypeId type: %d\n", info->type ); + PaUtil_DebugPrint("\t\tconst char *name: %s\n\n", info->name ); + PaUtil_DebugPrint("\t}\n\n" ); +#endif + + } + + return info; +} + + +PaDeviceIndex Pa_HostApiDeviceIndexToDeviceIndex( PaHostApiIndex hostApi, int hostApiDeviceIndex ) +{ + PaDeviceIndex result; + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_HostApiDeviceIndexToPaDeviceIndex called:\n" ); + PaUtil_DebugPrint("\tPaHostApiIndex hostApi: %d\n", hostApi ); + PaUtil_DebugPrint("\tint hostApiDeviceIndex: %d\n", hostApiDeviceIndex ); +#endif + + if( !PA_IS_INITIALISED_ ) + { + result = paNotInitialized; + } + else + { + if( hostApi < 0 || hostApi >= hostApisCount_ ) + { + result = paInvalidHostApi; + } + else + { + if( hostApiDeviceIndex < 0 || + hostApiDeviceIndex >= hostApis_[hostApi]->info.deviceCount ) + { + result = paInvalidDevice; + } + else + { + result = hostApis_[hostApi]->privatePaFrontInfo.baseDeviceIndex + hostApiDeviceIndex; + } + } + } + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_HostApiDeviceIndexToPaDeviceIndex returned:\n" ); + if( result < 0 ) + PaUtil_DebugPrint("\tPaError: %d ( %s )\n\n", result, Pa_GetErrorText( result ) ); + else + PaUtil_DebugPrint("\tPaDeviceIndex: %d\n\n", result ); +#endif + + return result; +} + + +PaDeviceIndex Pa_GetDeviceCount( void ) +{ + PaDeviceIndex result; + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_GetDeviceCount called.\n" ); +#endif + + if( !PA_IS_INITIALISED_ ) + { + result = paNotInitialized; + } + else + { + result = deviceCount_; + } + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_GetDeviceCount returned:\n" ); + if( result < 0 ) + PaUtil_DebugPrint("\tPaError: %d ( %s )\n\n", result, Pa_GetErrorText( result ) ); + else + PaUtil_DebugPrint("\tPaDeviceIndex: %d\n\n", result ); +#endif + + return result; +} + + +PaDeviceIndex Pa_GetDefaultInputDevice( void ) +{ + PaHostApiIndex hostApi; + PaDeviceIndex result; + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_GetDefaultInputDevice called.\n" ); +#endif + + hostApi = Pa_GetDefaultHostApi(); + if( hostApi < 0 ) + { + result = paNoDevice; + } + else + { + result = hostApis_[hostApi]->info.defaultInputDevice; + } + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_GetDefaultInputDevice returned:\n" ); + PaUtil_DebugPrint("\tPaDeviceIndex: %d\n\n", result ); +#endif + + return result; +} + + +PaDeviceIndex Pa_GetDefaultOutputDevice( void ) +{ + PaHostApiIndex hostApi; + PaDeviceIndex result; + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_GetDefaultOutputDevice called.\n" ); +#endif + + hostApi = Pa_GetDefaultHostApi(); + if( hostApi < 0 ) + { + result = paNoDevice; + } + else + { + result = hostApis_[hostApi]->info.defaultOutputDevice; + } + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_GetDefaultOutputDevice returned:\n" ); + PaUtil_DebugPrint("\tPaDeviceIndex: %d\n\n", result ); +#endif + + return result; +} + + +const PaDeviceInfo* Pa_GetDeviceInfo( PaDeviceIndex device ) +{ + int hostSpecificDeviceIndex; + int hostApiIndex = FindHostApi( device, &hostSpecificDeviceIndex ); + PaDeviceInfo *result; + + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_GetDeviceInfo called:\n" ); + PaUtil_DebugPrint("\tPaDeviceIndex device: %d\n", device ); +#endif + + if( hostApiIndex < 0 ) + { + result = NULL; + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_GetDeviceInfo returned:\n" ); + PaUtil_DebugPrint("\tPaDeviceInfo* NULL [ invalid device index ]\n\n" ); +#endif + + } + else + { + result = hostApis_[hostApiIndex]->deviceInfos[ hostSpecificDeviceIndex ]; + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_GetDeviceInfo returned:\n" ); + PaUtil_DebugPrint("\tPaDeviceInfo*: 0x%p:\n", result ); + PaUtil_DebugPrint("\t{\n" ); + + PaUtil_DebugPrint("\t\tint structVersion: %d\n", result->structVersion ); + PaUtil_DebugPrint("\t\tconst char *name: %s\n", result->name ); + PaUtil_DebugPrint("\t\tPaHostApiIndex hostApi: %d\n", result->hostApi ); + PaUtil_DebugPrint("\t\tint maxInputChannels: %d\n", result->maxInputChannels ); + PaUtil_DebugPrint("\t\tint maxOutputChannels: %d\n", result->maxOutputChannels ); + PaUtil_DebugPrint("\t}\n\n" ); +#endif + + } + + return result; +} + + +/* + SampleFormatIsValid() returns 1 if sampleFormat is a sample format + defined in portaudio.h, or 0 otherwise. +*/ +static int SampleFormatIsValid( PaSampleFormat format ) +{ + switch( format & ~paNonInterleaved ) + { + case paFloat32: return 1; + case paInt16: return 1; + case paInt32: return 1; + case paInt24: return 1; + case paInt8: return 1; + case paUInt8: return 1; + case paCustomFormat: return 1; + default: return 0; + } +} + +/* + NOTE: make sure this validation list is kept syncronised with the one in + pa_hostapi.h + + ValidateOpenStreamParameters() checks that parameters to Pa_OpenStream() + conform to the expected values as described below. This function is + also designed to be used with the proposed Pa_IsFormatSupported() function. + + There are basically two types of validation that could be performed: + Generic conformance validation, and device capability mismatch + validation. This function performs only generic conformance validation. + Validation that would require knowledge of device capabilities is + not performed because of potentially complex relationships between + combinations of parameters - for example, even if the sampleRate + seems ok, it might not be for a duplex stream - we have no way of + checking this in an API-neutral way, so we don't try. + + On success the function returns PaNoError and fills in hostApi, + hostApiInputDeviceID, and hostApiOutputDeviceID fields. On failure + the function returns an error code indicating the first encountered + parameter error. + + + If ValidateOpenStreamParameters() returns paNoError, the following + assertions are guaranteed to be true. + + - at least one of inputParameters & outputParmeters is valid (not NULL) + + - if inputParameters & outputParameters are both valid, that + inputParameters->device & outputParameters->device both use the same host api + + PaDeviceIndex inputParameters->device + - is within range (0 to Pa_GetDeviceCount-1) Or: + - is paUseHostApiSpecificDeviceSpecification and + inputParameters->hostApiSpecificStreamInfo is non-NULL and refers + to a valid host api + + int inputParameters->channelCount + - if inputParameters->device is not paUseHostApiSpecificDeviceSpecification, channelCount is > 0 + - upper bound is NOT validated against device capabilities + + PaSampleFormat inputParameters->sampleFormat + - is one of the sample formats defined in portaudio.h + + void *inputParameters->hostApiSpecificStreamInfo + - if supplied its hostApi field matches the input device's host Api + + PaDeviceIndex outputParmeters->device + - is within range (0 to Pa_GetDeviceCount-1) + + int outputParmeters->channelCount + - if inputDevice is valid, channelCount is > 0 + - upper bound is NOT validated against device capabilities + + PaSampleFormat outputParmeters->sampleFormat + - is one of the sample formats defined in portaudio.h + + void *outputParmeters->hostApiSpecificStreamInfo + - if supplied its hostApi field matches the output device's host Api + + double sampleRate + - is not an 'absurd' rate (less than 1000. or greater than 200000.) + - sampleRate is NOT validated against device capabilities + + PaStreamFlags streamFlags + - unused platform neutral flags are zero + - paNeverDropInput is only used for full-duplex callback streams with + variable buffer size (paFramesPerBufferUnspecified) +*/ +static PaError ValidateOpenStreamParameters( + const PaStreamParameters *inputParameters, + const PaStreamParameters *outputParameters, + double sampleRate, + unsigned long framesPerBuffer, + PaStreamFlags streamFlags, + PaStreamCallback *streamCallback, + PaUtilHostApiRepresentation **hostApi, + PaDeviceIndex *hostApiInputDevice, + PaDeviceIndex *hostApiOutputDevice ) +{ + int inputHostApiIndex = -1, /* Surpress uninitialised var warnings: compiler does */ + outputHostApiIndex = -1; /* not see that if inputParameters and outputParame- */ + /* ters are both nonzero, these indices are set. */ + + if( (inputParameters == NULL) && (outputParameters == NULL) ) + { + return paInvalidDevice; /** @todo should be a new error code "invalid device parameters" or something */ + } + else + { + if( inputParameters == NULL ) + { + *hostApiInputDevice = paNoDevice; + } + else if( inputParameters->device == paUseHostApiSpecificDeviceSpecification ) + { + if( inputParameters->hostApiSpecificStreamInfo ) + { + inputHostApiIndex = Pa_HostApiTypeIdToHostApiIndex( + ((PaUtilHostApiSpecificStreamInfoHeader*)inputParameters->hostApiSpecificStreamInfo)->hostApiType ); + + if( inputHostApiIndex != -1 ) + { + *hostApiInputDevice = paUseHostApiSpecificDeviceSpecification; + *hostApi = hostApis_[inputHostApiIndex]; + } + else + { + return paInvalidDevice; + } + } + else + { + return paInvalidDevice; + } + } + else + { + if( inputParameters->device < 0 || inputParameters->device >= deviceCount_ ) + return paInvalidDevice; + + inputHostApiIndex = FindHostApi( inputParameters->device, hostApiInputDevice ); + if( inputHostApiIndex < 0 ) + return paInternalError; + + *hostApi = hostApis_[inputHostApiIndex]; + + if( inputParameters->channelCount <= 0 ) + return paInvalidChannelCount; + + if( !SampleFormatIsValid( inputParameters->sampleFormat ) ) + return paSampleFormatNotSupported; + + if( inputParameters->hostApiSpecificStreamInfo != NULL ) + { + if( ((PaUtilHostApiSpecificStreamInfoHeader*)inputParameters->hostApiSpecificStreamInfo)->hostApiType + != (*hostApi)->info.type ) + return paIncompatibleHostApiSpecificStreamInfo; + } + } + + if( outputParameters == NULL ) + { + *hostApiOutputDevice = paNoDevice; + } + else if( outputParameters->device == paUseHostApiSpecificDeviceSpecification ) + { + if( outputParameters->hostApiSpecificStreamInfo ) + { + outputHostApiIndex = Pa_HostApiTypeIdToHostApiIndex( + ((PaUtilHostApiSpecificStreamInfoHeader*)outputParameters->hostApiSpecificStreamInfo)->hostApiType ); + + if( outputHostApiIndex != -1 ) + { + *hostApiOutputDevice = paUseHostApiSpecificDeviceSpecification; + *hostApi = hostApis_[outputHostApiIndex]; + } + else + { + return paInvalidDevice; + } + } + else + { + return paInvalidDevice; + } + } + else + { + if( outputParameters->device < 0 || outputParameters->device >= deviceCount_ ) + return paInvalidDevice; + + outputHostApiIndex = FindHostApi( outputParameters->device, hostApiOutputDevice ); + if( outputHostApiIndex < 0 ) + return paInternalError; + + *hostApi = hostApis_[outputHostApiIndex]; + + if( outputParameters->channelCount <= 0 ) + return paInvalidChannelCount; + + if( !SampleFormatIsValid( outputParameters->sampleFormat ) ) + return paSampleFormatNotSupported; + + if( outputParameters->hostApiSpecificStreamInfo != NULL ) + { + if( ((PaUtilHostApiSpecificStreamInfoHeader*)outputParameters->hostApiSpecificStreamInfo)->hostApiType + != (*hostApi)->info.type ) + return paIncompatibleHostApiSpecificStreamInfo; + } + } + + if( (inputParameters != NULL) && (outputParameters != NULL) ) + { + /* ensure that both devices use the same API */ + if( inputHostApiIndex != outputHostApiIndex ) + return paBadIODeviceCombination; + } + } + + + /* Check for absurd sample rates. */ + if( (sampleRate < 1000.0) || (sampleRate > 200000.0) ) + return paInvalidSampleRate; + + if( ((streamFlags & ~paPlatformSpecificFlags) & ~(paClipOff | paDitherOff | paNeverDropInput | paPrimeOutputBuffersUsingStreamCallback ) ) != 0 ) + return paInvalidFlag; + + if( streamFlags & paNeverDropInput ) + { + /* must be a callback stream */ + if( !streamCallback ) + return paInvalidFlag; + + /* must be a full duplex stream */ + if( (inputParameters == NULL) || (outputParameters == NULL) ) + return paInvalidFlag; + + /* must use paFramesPerBufferUnspecified */ + if( framesPerBuffer != paFramesPerBufferUnspecified ) + return paInvalidFlag; + } + + return paNoError; +} + + +PaError Pa_IsFormatSupported( const PaStreamParameters *inputParameters, + const PaStreamParameters *outputParameters, + double sampleRate ) +{ + PaError result; + PaUtilHostApiRepresentation *hostApi; + PaDeviceIndex hostApiInputDevice, hostApiOutputDevice; + PaStreamParameters hostApiInputParameters, hostApiOutputParameters; + PaStreamParameters *hostApiInputParametersPtr, *hostApiOutputParametersPtr; + + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_IsFormatSupported called:\n" ); + + if( inputParameters == NULL ){ + PaUtil_DebugPrint("\tPaStreamParameters *inputParameters: NULL\n" ); + }else{ + PaUtil_DebugPrint("\tPaStreamParameters *inputParameters: 0x%p\n", inputParameters ); + PaUtil_DebugPrint("\tPaDeviceIndex inputParameters->device: %d\n", inputParameters->device ); + PaUtil_DebugPrint("\tint inputParameters->channelCount: %d\n", inputParameters->channelCount ); + PaUtil_DebugPrint("\tPaSampleFormat inputParameters->sampleFormat: %d\n", inputParameters->sampleFormat ); + PaUtil_DebugPrint("\tPaTime inputParameters->suggestedLatency: %f\n", inputParameters->suggestedLatency ); + PaUtil_DebugPrint("\tvoid *inputParameters->hostApiSpecificStreamInfo: 0x%p\n", inputParameters->hostApiSpecificStreamInfo ); + } + + if( outputParameters == NULL ){ + PaUtil_DebugPrint("\tPaStreamParameters *outputParameters: NULL\n" ); + }else{ + PaUtil_DebugPrint("\tPaStreamParameters *outputParameters: 0x%p\n", outputParameters ); + PaUtil_DebugPrint("\tPaDeviceIndex outputParameters->device: %d\n", outputParameters->device ); + PaUtil_DebugPrint("\tint outputParameters->channelCount: %d\n", outputParameters->channelCount ); + PaUtil_DebugPrint("\tPaSampleFormat outputParameters->sampleFormat: %d\n", outputParameters->sampleFormat ); + PaUtil_DebugPrint("\tPaTime outputParameters->suggestedLatency: %f\n", outputParameters->suggestedLatency ); + PaUtil_DebugPrint("\tvoid *outputParameters->hostApiSpecificStreamInfo: 0x%p\n", outputParameters->hostApiSpecificStreamInfo ); + } + + PaUtil_DebugPrint("\tdouble sampleRate: %g\n", sampleRate ); +#endif + + if( !PA_IS_INITIALISED_ ) + { + result = paNotInitialized; + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_IsFormatSupported returned:\n" ); + PaUtil_DebugPrint("\tPaError: %d ( %s )\n\n", result, Pa_GetErrorText( result ) ); +#endif + return result; + } + + result = ValidateOpenStreamParameters( inputParameters, + outputParameters, + sampleRate, 0, paNoFlag, 0, + &hostApi, + &hostApiInputDevice, + &hostApiOutputDevice ); + if( result != paNoError ) + { +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_IsFormatSupported returned:\n" ); + PaUtil_DebugPrint("\tPaError: %d ( %s )\n\n", result, Pa_GetErrorText( result ) ); +#endif + return result; + } + + + if( inputParameters ) + { + hostApiInputParameters.device = hostApiInputDevice; + hostApiInputParameters.channelCount = inputParameters->channelCount; + hostApiInputParameters.sampleFormat = inputParameters->sampleFormat; + hostApiInputParameters.suggestedLatency = inputParameters->suggestedLatency; + hostApiInputParameters.hostApiSpecificStreamInfo = inputParameters->hostApiSpecificStreamInfo; + hostApiInputParametersPtr = &hostApiInputParameters; + } + else + { + hostApiInputParametersPtr = NULL; + } + + if( outputParameters ) + { + hostApiOutputParameters.device = hostApiOutputDevice; + hostApiOutputParameters.channelCount = outputParameters->channelCount; + hostApiOutputParameters.sampleFormat = outputParameters->sampleFormat; + hostApiOutputParameters.suggestedLatency = outputParameters->suggestedLatency; + hostApiOutputParameters.hostApiSpecificStreamInfo = outputParameters->hostApiSpecificStreamInfo; + hostApiOutputParametersPtr = &hostApiOutputParameters; + } + else + { + hostApiOutputParametersPtr = NULL; + } + + result = hostApi->IsFormatSupported( hostApi, + hostApiInputParametersPtr, hostApiOutputParametersPtr, + sampleRate ); + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_OpenStream returned:\n" ); + if( result == paFormatIsSupported ) + PaUtil_DebugPrint("\tPaError: 0 [ paFormatIsSupported ]\n\n" ); + else + PaUtil_DebugPrint("\tPaError: %d ( %s )\n\n", result, Pa_GetErrorText( result ) ); +#endif + + return result; +} + + +PaError Pa_OpenStream( PaStream** stream, + const PaStreamParameters *inputParameters, + const PaStreamParameters *outputParameters, + double sampleRate, + unsigned long framesPerBuffer, + PaStreamFlags streamFlags, + PaStreamCallback *streamCallback, + void *userData ) +{ + PaError result; + PaUtilHostApiRepresentation *hostApi; + PaDeviceIndex hostApiInputDevice, hostApiOutputDevice; + PaStreamParameters hostApiInputParameters, hostApiOutputParameters; + PaStreamParameters *hostApiInputParametersPtr, *hostApiOutputParametersPtr; + + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_OpenStream called:\n" ); + PaUtil_DebugPrint("\tPaStream** stream: 0x%p\n", stream ); + + if( inputParameters == NULL ){ + PaUtil_DebugPrint("\tPaStreamParameters *inputParameters: NULL\n" ); + }else{ + PaUtil_DebugPrint("\tPaStreamParameters *inputParameters: 0x%p\n", inputParameters ); + PaUtil_DebugPrint("\tPaDeviceIndex inputParameters->device: %d\n", inputParameters->device ); + PaUtil_DebugPrint("\tint inputParameters->channelCount: %d\n", inputParameters->channelCount ); + PaUtil_DebugPrint("\tPaSampleFormat inputParameters->sampleFormat: %d\n", inputParameters->sampleFormat ); + PaUtil_DebugPrint("\tPaTime inputParameters->suggestedLatency: %f\n", inputParameters->suggestedLatency ); + PaUtil_DebugPrint("\tvoid *inputParameters->hostApiSpecificStreamInfo: 0x%p\n", inputParameters->hostApiSpecificStreamInfo ); + } + + if( outputParameters == NULL ){ + PaUtil_DebugPrint("\tPaStreamParameters *outputParameters: NULL\n" ); + }else{ + PaUtil_DebugPrint("\tPaStreamParameters *outputParameters: 0x%p\n", outputParameters ); + PaUtil_DebugPrint("\tPaDeviceIndex outputParameters->device: %d\n", outputParameters->device ); + PaUtil_DebugPrint("\tint outputParameters->channelCount: %d\n", outputParameters->channelCount ); + PaUtil_DebugPrint("\tPaSampleFormat outputParameters->sampleFormat: %d\n", outputParameters->sampleFormat ); + PaUtil_DebugPrint("\tPaTime outputParameters->suggestedLatency: %f\n", outputParameters->suggestedLatency ); + PaUtil_DebugPrint("\tvoid *outputParameters->hostApiSpecificStreamInfo: 0x%p\n", outputParameters->hostApiSpecificStreamInfo ); + } + + PaUtil_DebugPrint("\tdouble sampleRate: %g\n", sampleRate ); + PaUtil_DebugPrint("\tunsigned long framesPerBuffer: %d\n", framesPerBuffer ); + PaUtil_DebugPrint("\tPaStreamFlags streamFlags: 0x%x\n", streamFlags ); + PaUtil_DebugPrint("\tPaStreamCallback *streamCallback: 0x%p\n", streamCallback ); + PaUtil_DebugPrint("\tvoid *userData: 0x%p\n", userData ); +#endif + + if( !PA_IS_INITIALISED_ ) + { + result = paNotInitialized; + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_OpenStream returned:\n" ); + PaUtil_DebugPrint("\t*(PaStream** stream): undefined\n" ); + PaUtil_DebugPrint("\tPaError: %d ( %s )\n\n", result, Pa_GetErrorText( result ) ); +#endif + return result; + } + + /* Check for parameter errors. + NOTE: make sure this validation list is kept syncronised with the one + in pa_hostapi.h + */ + + if( stream == NULL ) + { + result = paBadStreamPtr; + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_OpenStream returned:\n" ); + PaUtil_DebugPrint("\t*(PaStream** stream): undefined\n" ); + PaUtil_DebugPrint("\tPaError: %d ( %s )\n\n", result, Pa_GetErrorText( result ) ); +#endif + return result; + } + + result = ValidateOpenStreamParameters( inputParameters, + outputParameters, + sampleRate, framesPerBuffer, + streamFlags, streamCallback, + &hostApi, + &hostApiInputDevice, + &hostApiOutputDevice ); + if( result != paNoError ) + { +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_OpenStream returned:\n" ); + PaUtil_DebugPrint("\t*(PaStream** stream): undefined\n" ); + PaUtil_DebugPrint("\tPaError: %d ( %s )\n\n", result, Pa_GetErrorText( result ) ); +#endif + return result; + } + + + if( inputParameters ) + { + hostApiInputParameters.device = hostApiInputDevice; + hostApiInputParameters.channelCount = inputParameters->channelCount; + hostApiInputParameters.sampleFormat = inputParameters->sampleFormat; + hostApiInputParameters.suggestedLatency = inputParameters->suggestedLatency; + hostApiInputParameters.hostApiSpecificStreamInfo = inputParameters->hostApiSpecificStreamInfo; + hostApiInputParametersPtr = &hostApiInputParameters; + } + else + { + hostApiInputParametersPtr = NULL; + } + + if( outputParameters ) + { + hostApiOutputParameters.device = hostApiOutputDevice; + hostApiOutputParameters.channelCount = outputParameters->channelCount; + hostApiOutputParameters.sampleFormat = outputParameters->sampleFormat; + hostApiOutputParameters.suggestedLatency = outputParameters->suggestedLatency; + hostApiOutputParameters.hostApiSpecificStreamInfo = outputParameters->hostApiSpecificStreamInfo; + hostApiOutputParametersPtr = &hostApiOutputParameters; + } + else + { + hostApiOutputParametersPtr = NULL; + } + + result = hostApi->OpenStream( hostApi, stream, + hostApiInputParametersPtr, hostApiOutputParametersPtr, + sampleRate, framesPerBuffer, streamFlags, streamCallback, userData ); + + if( result == paNoError ) + AddOpenStream( *stream ); + + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_OpenStream returned:\n" ); + PaUtil_DebugPrint("\t*(PaStream** stream): 0x%p\n", *stream ); + PaUtil_DebugPrint("\tPaError: %d ( %s )\n\n", result, Pa_GetErrorText( result ) ); +#endif + + return result; +} + + +PaError Pa_OpenDefaultStream( PaStream** stream, + int inputChannelCount, + int outputChannelCount, + PaSampleFormat sampleFormat, + double sampleRate, + unsigned long framesPerBuffer, + PaStreamCallback *streamCallback, + void *userData ) +{ + PaError result; + PaStreamParameters hostApiInputParameters, hostApiOutputParameters; + PaStreamParameters *hostApiInputParametersPtr, *hostApiOutputParametersPtr; + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_OpenDefaultStream called:\n" ); + PaUtil_DebugPrint("\tPaStream** stream: 0x%p\n", stream ); + PaUtil_DebugPrint("\tint inputChannelCount: %d\n", inputChannelCount ); + PaUtil_DebugPrint("\tint outputChannelCount: %d\n", outputChannelCount ); + PaUtil_DebugPrint("\tPaSampleFormat sampleFormat: %d\n", sampleFormat ); + PaUtil_DebugPrint("\tdouble sampleRate: %g\n", sampleRate ); + PaUtil_DebugPrint("\tunsigned long framesPerBuffer: %d\n", framesPerBuffer ); + PaUtil_DebugPrint("\tPaStreamCallback *streamCallback: 0x%p\n", streamCallback ); + PaUtil_DebugPrint("\tvoid *userData: 0x%p\n", userData ); +#endif + + + if( inputChannelCount > 0 ) + { + hostApiInputParameters.device = Pa_GetDefaultInputDevice(); + hostApiInputParameters.channelCount = inputChannelCount; + hostApiInputParameters.sampleFormat = sampleFormat; + /* defaultHighInputLatency is used below instead of + defaultLowInputLatency because it is more important for the default + stream to work reliably than it is for it to work with the lowest + latency. + */ + hostApiInputParameters.suggestedLatency = + Pa_GetDeviceInfo( hostApiInputParameters.device )->defaultHighInputLatency; + hostApiInputParameters.hostApiSpecificStreamInfo = NULL; + hostApiInputParametersPtr = &hostApiInputParameters; + } + else + { + hostApiInputParametersPtr = NULL; + } + + if( outputChannelCount > 0 ) + { + hostApiOutputParameters.device = Pa_GetDefaultOutputDevice(); + hostApiOutputParameters.channelCount = outputChannelCount; + hostApiOutputParameters.sampleFormat = sampleFormat; + /* defaultHighOutputLatency is used below instead of + defaultLowOutputLatency because it is more important for the default + stream to work reliably than it is for it to work with the lowest + latency. + */ + hostApiOutputParameters.suggestedLatency = + Pa_GetDeviceInfo( hostApiOutputParameters.device )->defaultHighOutputLatency; + hostApiOutputParameters.hostApiSpecificStreamInfo = NULL; + hostApiOutputParametersPtr = &hostApiOutputParameters; + } + else + { + hostApiOutputParametersPtr = NULL; + } + + + result = Pa_OpenStream( + stream, hostApiInputParametersPtr, hostApiOutputParametersPtr, + sampleRate, framesPerBuffer, paNoFlag, streamCallback, userData ); + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_OpenDefaultStream returned:\n" ); + PaUtil_DebugPrint("\t*(PaStream** stream): 0x%p", *stream ); + PaUtil_DebugPrint("\tPaError: %d ( %s )\n\n", result, Pa_GetErrorText( result ) ); +#endif + + return result; +} + + +PaError PaUtil_ValidateStreamPointer( PaStream* stream ) +{ + if( !PA_IS_INITIALISED_ ) return paNotInitialized; + + if( stream == NULL ) return paBadStreamPtr; + + if( ((PaUtilStreamRepresentation*)stream)->magic != PA_STREAM_MAGIC ) + return paBadStreamPtr; + + return paNoError; +} + + +PaError Pa_CloseStream( PaStream* stream ) +{ + PaUtilStreamInterface *interface; + PaError result = PaUtil_ValidateStreamPointer( stream ); + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_CloseStream called:\n" ); + PaUtil_DebugPrint("\tPaStream* stream: 0x%p\n", stream ); +#endif + + /* always remove the open stream from our list, even if this function + eventually returns an error. Otherwise CloseOpenStreams() will + get stuck in an infinite loop */ + RemoveOpenStream( stream ); /* be sure to call this _before_ closing the stream */ + + if( result == paNoError ) + { + interface = PA_STREAM_INTERFACE(stream); + + /* abort the stream if it isn't stopped */ + result = interface->IsStopped( stream ); + if( result == 1 ) + result = paNoError; + else if( result == 0 ) + result = interface->Abort( stream ); + + if( result == paNoError ) /** @todo REVIEW: shouldn't we close anyway? */ + result = interface->Close( stream ); + } + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_CloseStream returned:\n" ); + PaUtil_DebugPrint("\tPaError: %d ( %s )\n\n", result, Pa_GetErrorText( result ) ); +#endif + + return result; +} + + +PaError Pa_SetStreamFinishedCallback( PaStream *stream, PaStreamFinishedCallback* streamFinishedCallback ) +{ + PaError result = PaUtil_ValidateStreamPointer( stream ); + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_SetStreamFinishedCallback called:\n" ); + PaUtil_DebugPrint("\tPaStream* stream: 0x%p\n", stream ); + PaUtil_DebugPrint("\tPaStreamFinishedCallback* streamFinishedCallback: 0x%p\n", streamFinishedCallback ); +#endif + + if( result == paNoError ) + { + result = PA_STREAM_INTERFACE(stream)->IsStopped( stream ); + if( result == 0 ) + { + result = paStreamIsNotStopped ; + } + if( result == 1 ) + { + PA_STREAM_REP( stream )->streamFinishedCallback = streamFinishedCallback; + result = paNoError; + } + } + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_SetStreamFinishedCallback returned:\n" ); + PaUtil_DebugPrint("\tPaError: %d ( %s )\n\n", result, Pa_GetErrorText( result ) ); +#endif + + return result; + +} + + +PaError Pa_StartStream( PaStream *stream ) +{ + PaError result = PaUtil_ValidateStreamPointer( stream ); + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_StartStream called:\n" ); + PaUtil_DebugPrint("\tPaStream* stream: 0x%p\n", stream ); +#endif + + if( result == paNoError ) + { + result = PA_STREAM_INTERFACE(stream)->IsStopped( stream ); + if( result == 0 ) + { + result = paStreamIsNotStopped ; + } + else if( result == 1 ) + { + result = PA_STREAM_INTERFACE(stream)->Start( stream ); + } + } + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_StartStream returned:\n" ); + PaUtil_DebugPrint("\tPaError: %d ( %s )\n\n", result, Pa_GetErrorText( result ) ); +#endif + + return result; +} + + +PaError Pa_StopStream( PaStream *stream ) +{ + PaError result = PaUtil_ValidateStreamPointer( stream ); + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_StopStream called\n" ); + PaUtil_DebugPrint("\tPaStream* stream: 0x%p\n", stream ); +#endif + + if( result == paNoError ) + { + result = PA_STREAM_INTERFACE(stream)->IsStopped( stream ); + if( result == 0 ) + { + result = PA_STREAM_INTERFACE(stream)->Stop( stream ); + } + else if( result == 1 ) + { + result = paStreamIsStopped; + } + } + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_StopStream returned:\n" ); + PaUtil_DebugPrint("\tPaError: %d ( %s )\n\n", result, Pa_GetErrorText( result ) ); +#endif + + return result; +} + + +PaError Pa_AbortStream( PaStream *stream ) +{ + PaError result = PaUtil_ValidateStreamPointer( stream ); + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_AbortStream called:\n" ); + PaUtil_DebugPrint("\tPaStream* stream: 0x%p\n", stream ); +#endif + + if( result == paNoError ) + { + result = PA_STREAM_INTERFACE(stream)->IsStopped( stream ); + if( result == 0 ) + { + result = PA_STREAM_INTERFACE(stream)->Abort( stream ); + } + else if( result == 1 ) + { + result = paStreamIsStopped; + } + } + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_AbortStream returned:\n" ); + PaUtil_DebugPrint("\tPaError: %d ( %s )\n\n", result, Pa_GetErrorText( result ) ); +#endif + + return result; +} + + +PaError Pa_IsStreamStopped( PaStream *stream ) +{ + PaError result = PaUtil_ValidateStreamPointer( stream ); + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_IsStreamStopped called:\n" ); + PaUtil_DebugPrint("\tPaStream* stream: 0x%p\n", stream ); +#endif + + if( result == paNoError ) + result = PA_STREAM_INTERFACE(stream)->IsStopped( stream ); + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_IsStreamStopped returned:\n" ); + PaUtil_DebugPrint("\tPaError: %d ( %s )\n\n", result, Pa_GetErrorText( result ) ); +#endif + + return result; +} + + +PaError Pa_IsStreamActive( PaStream *stream ) +{ + PaError result = PaUtil_ValidateStreamPointer( stream ); + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_IsStreamActive called:\n" ); + PaUtil_DebugPrint("\tPaStream* stream: 0x%p\n", stream ); +#endif + + if( result == paNoError ) + result = PA_STREAM_INTERFACE(stream)->IsActive( stream ); + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_IsStreamActive returned:\n" ); + PaUtil_DebugPrint("\tPaError: %d ( %s )\n\n", result, Pa_GetErrorText( result ) ); +#endif + + return result; +} + + +const PaStreamInfo* Pa_GetStreamInfo( PaStream *stream ) +{ + PaError error = PaUtil_ValidateStreamPointer( stream ); + const PaStreamInfo *result; + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_GetStreamInfo called:\n" ); + PaUtil_DebugPrint("\tPaStream* stream: 0x%p\n", stream ); +#endif + + if( error != paNoError ) + { + result = 0; + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_GetStreamInfo returned:\n" ); + PaUtil_DebugPrint("\tconst PaStreamInfo*: 0 [PaError error:%d ( %s )]\n\n", result, error, Pa_GetErrorText( error ) ); +#endif + + } + else + { + result = &PA_STREAM_REP( stream )->streamInfo; + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_GetStreamInfo returned:\n" ); + PaUtil_DebugPrint("\tconst PaStreamInfo*: 0x%p:\n", result ); + PaUtil_DebugPrint("\t{" ); + + PaUtil_DebugPrint("\t\tint structVersion: %d\n", result->structVersion ); + PaUtil_DebugPrint("\t\tPaTime inputLatency: %f\n", result->inputLatency ); + PaUtil_DebugPrint("\t\tPaTime outputLatency: %f\n", result->outputLatency ); + PaUtil_DebugPrint("\t\tdouble sampleRate: %f\n", result->sampleRate ); + PaUtil_DebugPrint("\t}\n\n" ); +#endif + + } + + return result; +} + + +PaTime Pa_GetStreamTime( PaStream *stream ) +{ + PaError error = PaUtil_ValidateStreamPointer( stream ); + PaTime result; + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_GetStreamTime called:\n" ); + PaUtil_DebugPrint("\tPaStream* stream: 0x%p\n", stream ); +#endif + + if( error != paNoError ) + { + result = 0; + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_GetStreamTime returned:\n" ); + PaUtil_DebugPrint("\tPaTime: 0 [PaError error:%d ( %s )]\n\n", result, error, Pa_GetErrorText( error ) ); +#endif + + } + else + { + result = PA_STREAM_INTERFACE(stream)->GetTime( stream ); + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_GetStreamTime returned:\n" ); + PaUtil_DebugPrint("\tPaTime: %g\n\n", result ); +#endif + + } + + return result; +} + + +double Pa_GetStreamCpuLoad( PaStream* stream ) +{ + PaError error = PaUtil_ValidateStreamPointer( stream ); + double result; + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_GetStreamCpuLoad called:\n" ); + PaUtil_DebugPrint("\tPaStream* stream: 0x%p\n", stream ); +#endif + + if( error != paNoError ) + { + + result = 0.0; + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_GetStreamCpuLoad returned:\n" ); + PaUtil_DebugPrint("\tdouble: 0.0 [PaError error: %d ( %s )]\n\n", error, Pa_GetErrorText( error ) ); +#endif + + } + else + { + result = PA_STREAM_INTERFACE(stream)->GetCpuLoad( stream ); + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_GetStreamCpuLoad returned:\n" ); + PaUtil_DebugPrint("\tdouble: %g\n\n", result ); +#endif + + } + + return result; +} + + +PaError Pa_ReadStream( PaStream* stream, + void *buffer, + unsigned long frames ) +{ + PaError result = PaUtil_ValidateStreamPointer( stream ); + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_ReadStream called:\n" ); + PaUtil_DebugPrint("\tPaStream* stream: 0x%p\n", stream ); +#endif + + if( result == paNoError ) + { + if( frames == 0 ) + { + /* XXX: Should we not allow the implementation to signal any overflow condition? */ + result = paNoError; + } + else if( buffer == 0 ) + { + result = paBadBufferPtr; + } + else + { + result = PA_STREAM_INTERFACE(stream)->IsStopped( stream ); + if( result == 0 ) + { + result = PA_STREAM_INTERFACE(stream)->Read( stream, buffer, frames ); + } + else if( result == 1 ) + { + result = paStreamIsStopped; + } + } + } + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_ReadStream returned:\n" ); + PaUtil_DebugPrint("\tPaError: %d ( %s )\n\n", result, Pa_GetErrorText( result ) ); +#endif + + return result; +} + + +PaError Pa_WriteStream( PaStream* stream, + const void *buffer, + unsigned long frames ) +{ + PaError result = PaUtil_ValidateStreamPointer( stream ); + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_WriteStream called:\n" ); + PaUtil_DebugPrint("\tPaStream* stream: 0x%p\n", stream ); +#endif + + if( result == paNoError ) + { + if( frames == 0 ) + { + /* XXX: Should we not allow the implementation to signal any underflow condition? */ + result = paNoError; + } + else if( buffer == 0 ) + { + result = paBadBufferPtr; + } + else + { + result = PA_STREAM_INTERFACE(stream)->IsStopped( stream ); + if( result == 0 ) + { + result = PA_STREAM_INTERFACE(stream)->Write( stream, buffer, frames ); + } + else if( result == 1 ) + { + result = paStreamIsStopped; + } + } + } + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_WriteStream returned:\n" ); + PaUtil_DebugPrint("\tPaError: %d ( %s )\n\n", result, Pa_GetErrorText( result ) ); +#endif + + return result; +} + +signed long Pa_GetStreamReadAvailable( PaStream* stream ) +{ + PaError error = PaUtil_ValidateStreamPointer( stream ); + signed long result; + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_GetStreamReadAvailable called:\n" ); + PaUtil_DebugPrint("\tPaStream* stream: 0x%p\n", stream ); +#endif + + if( error != paNoError ) + { + result = 0; + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_GetStreamReadAvailable returned:\n" ); + PaUtil_DebugPrint("\tunsigned long: 0 [ PaError error: %d ( %s ) ]\n\n", error, Pa_GetErrorText( error ) ); +#endif + + } + else + { + result = PA_STREAM_INTERFACE(stream)->GetReadAvailable( stream ); + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_GetStreamReadAvailable returned:\n" ); + PaUtil_DebugPrint("\tPaError: %d ( %s )\n\n", result, Pa_GetErrorText( result ) ); +#endif + + } + + return result; +} + + +signed long Pa_GetStreamWriteAvailable( PaStream* stream ) +{ + PaError error = PaUtil_ValidateStreamPointer( stream ); + signed long result; + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_GetStreamWriteAvailable called:\n" ); + PaUtil_DebugPrint("\tPaStream* stream: 0x%p\n", stream ); +#endif + + if( error != paNoError ) + { + result = 0; + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_GetStreamWriteAvailable returned:\n" ); + PaUtil_DebugPrint("\tunsigned long: 0 [ PaError error: %d ( %s ) ]\n\n", error, Pa_GetErrorText( error ) ); +#endif + + } + else + { + result = PA_STREAM_INTERFACE(stream)->GetWriteAvailable( stream ); + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_GetStreamWriteAvailable returned:\n" ); + PaUtil_DebugPrint("\tPaError: %d ( %s )\n\n", result, Pa_GetErrorText( result ) ); +#endif + + } + + return result; +} + + +PaError Pa_GetSampleSize( PaSampleFormat format ) +{ + int result; + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_GetSampleSize called:\n" ); + PaUtil_DebugPrint("\tPaSampleFormat format: %d\n", format ); +#endif + + switch( format & ~paNonInterleaved ) + { + + case paUInt8: + case paInt8: + result = 1; + break; + + case paInt16: + result = 2; + break; + + case paInt24: + result = 3; + break; + + case paFloat32: + case paInt32: + result = 4; + break; + + default: + result = paSampleFormatNotSupported; + break; + } + +#ifdef PA_LOG_API_CALLS + PaUtil_DebugPrint("Pa_GetSampleSize returned:\n" ); + if( result > 0 ) + PaUtil_DebugPrint("\tint: %d\n\n", result ); + else + PaUtil_DebugPrint("\tPaError: %d ( %s )\n\n", result, Pa_GetErrorText( result ) ); +#endif + + return (PaError) result; +} + diff --git a/pa_common/pa_host.h b/pa_common/pa_host.h deleted file mode 100644 index 94651a2..0000000 --- a/pa_common/pa_host.h +++ /dev/null @@ -1,185 +0,0 @@ -#ifndef PA_HOST_H -#define PA_HOST_H - -/* - * $Id$ - * Host dependant internal API for PortAudio - * - * Author: Phil Burk - * - * PortAudio Portable Real-Time Audio Library - * Latest Version at: http://www.softsynth.com/portaudio/ - * DirectSound and Macintosh Implementation - * Copyright (c) 1999-2000 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. - * - */ - -#include "portaudio.h" - -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -#ifndef SUPPORT_AUDIO_CAPTURE -#define SUPPORT_AUDIO_CAPTURE (1) -#endif - -#ifndef int32 - typedef long int32; -#endif -#ifndef uint32 - typedef unsigned long uint32; -#endif -#ifndef int16 - typedef short int16; -#endif -#ifndef uint16 - typedef unsigned short uint16; -#endif - -/* Used to convert between various sample formats. */ -typedef void (PortAudioConverter)( - void *inputBuffer, int inputStride, - void *outputBuffer, int outputStride, - int numSamples ); - -#define PA_MAGIC (0x18273645) - -/************************************************************************************/ -/****************** Structures ******************************************************/ -/************************************************************************************/ - -typedef struct internalPortAudioStream -{ - uint32 past_Magic; /* ID for struct to catch bugs. */ - /* User specified information. */ - uint32 past_FramesPerUserBuffer; - uint32 past_NumUserBuffers; - double past_SampleRate; /* Closest supported sample rate. */ - int past_NumInputChannels; - int past_NumOutputChannels; - PaDeviceID past_InputDeviceID; - PaDeviceID past_OutputDeviceID; - PaSampleFormat past_NativeInputSampleFormat; - PaSampleFormat past_InputSampleFormat; - PaSampleFormat past_NativeOutputSampleFormat; - PaSampleFormat past_OutputSampleFormat; - void *past_DeviceData; - PortAudioCallback *past_Callback; - void *past_UserData; - uint32 past_Flags; - /* Flags for communicating between foreground and background. */ - volatile int past_IsActive; /* Background is still playing. */ - volatile int past_StopSoon; /* Background should keep playing when buffers empty. */ - volatile int past_StopNow; /* Background should stop playing now. */ - /* These buffers are used when the native format does not match the user format. */ - void *past_InputBuffer; - uint32 past_InputBufferSize; - void *past_OutputBuffer; - uint32 past_OutputBufferSize; - /* Measurements */ - uint32 past_NumCallbacks; - PaTimestamp past_FrameCount; /* Frames output to buffer. */ - /* For measuring CPU utilization. */ - double past_AverageInsideCount; - double past_AverageTotalCount; - double past_Usage; - int past_IfLastExitValid; - /* Format Conversion */ - /* These are setup by PaConversion_Setup() */ - PortAudioConverter *past_InputConversionProc; - int past_InputConversionSourceStride; - int past_InputConversionTargetStride; - PortAudioConverter *past_OutputConversionProc; - int past_OutputConversionSourceStride; - int past_OutputConversionTargetStride; -} -internalPortAudioStream; - -/************************************************************************************/ -/******** These functions must be provided by a platform implementation. ************/ -/************************************************************************************/ - -PaError PaHost_Init( void ); -PaError PaHost_Term( void ); - -PaError PaHost_OpenStream( internalPortAudioStream *past ); -PaError PaHost_CloseStream( internalPortAudioStream *past ); - -PaError PaHost_StartOutput( internalPortAudioStream *past ); -PaError PaHost_StopOutput( internalPortAudioStream *past, int abort ); -PaError PaHost_StartInput( internalPortAudioStream *past ); -PaError PaHost_StopInput( internalPortAudioStream *past, int abort ); -PaError PaHost_StartEngine( internalPortAudioStream *past ); -PaError PaHost_StopEngine( internalPortAudioStream *past, int abort ); -PaError PaHost_StreamActive( internalPortAudioStream *past ); - -void *PaHost_AllocateFastMemory( long numBytes ); -void PaHost_FreeFastMemory( void *addr, long numBytes ); - -/* This only called if PA_VALIDATE_RATE IS CALLED. */ -PaError PaHost_ValidateSampleRate( PaDeviceID id, double requestedFrameRate, - double *closestFrameRatePtr ); - -/**********************************************************************/ -/************ Common Utility Routines provided by PA ******************/ -/**********************************************************************/ - -/* PaHost_IsInitialized() returns non-zero if PA is initialized, 0 otherwise */ -int PaHost_IsInitialized( void ); - -internalPortAudioStream* PaHost_GetStreamRepresentation( PortAudioStream *stream ); - -int PaHost_FindClosestTableEntry( double allowableError, const double *rateTable, - int numRates, double frameRate ); - -long Pa_CallConvertInt16( internalPortAudioStream *past, - short *nativeInputBuffer, - short *nativeOutputBuffer ); - -/* Calculate 2 LSB dither signal with a triangular distribution. -** Ranged properly for adding to a 32 bit 1.31 fixed point value prior to >>15. -** Range of output is +/- 65535 -** Multiply by PA_DITHER_SCALE to get a float between -2.0 and 2.0. */ -#define PA_DITHER_BITS (15) -#define PA_DITHER_SCALE (1.0f / ((1< + parameter, which was previously returned from the same implementation's + initializer. + */ + void (*Terminate)( struct PaUtilHostApiRepresentation *hostApi ); + + /** + The inputParameters and outputParameters pointers should not be saved + as they will not remain valid after OpenStream is called. + + + The following guarantees are made about parameters to (*OpenStream)(): + + [NOTE: the following list up to *END PA FRONT VALIDATIONS* should be + kept in sync with the one for ValidateOpenStreamParameters and + Pa_OpenStream in pa_front.c] + + PaHostApiRepresentation *hostApi + - is valid for this implementation + + PaStream** stream + - is non-null + + - at least one of inputParameters & outputParmeters is valid (not NULL) + + - if inputParameters & outputParmeters are both valid, that + inputParameters->device & outputParmeters->device both use the same host api + + PaDeviceIndex inputParameters->device + - is within range (0 to Pa_CountDevices-1) Or: + - is paUseHostApiSpecificDeviceSpecification and + inputParameters->hostApiSpecificStreamInfo is non-NULL and refers + to a valid host api + + int inputParameters->numChannels + - if inputParameters->device is not paUseHostApiSpecificDeviceSpecification, numInputChannels is > 0 + - upper bound is NOT validated against device capabilities + + PaSampleFormat inputParameters->sampleFormat + - is one of the sample formats defined in portaudio.h + + void *inputParameters->hostApiSpecificStreamInfo + - if supplied its hostApi field matches the input device's host Api + + PaDeviceIndex outputParmeters->device + - is within range (0 to Pa_CountDevices-1) + + int outputParmeters->numChannels + - if inputDevice is valid, numInputChannels is > 0 + - upper bound is NOT validated against device capabilities + + PaSampleFormat outputParmeters->sampleFormat + - is one of the sample formats defined in portaudio.h + + void *outputParmeters->hostApiSpecificStreamInfo + - if supplied its hostApi field matches the output device's host Api + + double sampleRate + - is not an 'absurd' rate (less than 1000. or greater than 200000.) + - sampleRate is NOT validated against device capabilities + + PaStreamFlags streamFlags + - unused platform neutral flags are zero + - paNeverDropInput is only used for full-duplex callback streams + with variable buffer size (paFramesPerBufferUnspecified) + + [*END PA FRONT VALIDATIONS*] + + + The following validations MUST be performed by (*OpenStream)(): + + - check that input device can support numInputChannels + + - check that input device can support inputSampleFormat, or that + we have the capability to convert from outputSampleFormat to + a native format + + - if inputStreamInfo is supplied, validate its contents, + or return an error if no inputStreamInfo is expected + + - check that output device can support numOutputChannels + + - check that output device can support outputSampleFormat, or that + we have the capability to convert from outputSampleFormat to + a native format + + - if outputStreamInfo is supplied, validate its contents, + or return an error if no outputStreamInfo is expected + + - 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 necessary + + - validate inputLatency and outputLatency + + - validate any platform specific flags, if flags are supplied they + must be valid. + */ + PaError (*OpenStream)( struct PaUtilHostApiRepresentation *hostApi, + PaStream** stream, + const PaStreamParameters *inputParameters, + const PaStreamParameters *outputParameters, + double sampleRate, + unsigned long framesPerCallback, + PaStreamFlags streamFlags, + PaStreamCallback *streamCallback, + void *userData ); + + + PaError (*IsFormatSupported)( struct PaUtilHostApiRepresentation *hostApi, + const PaStreamParameters *inputParameters, + const PaStreamParameters *outputParameters, + double sampleRate ); +} PaUtilHostApiRepresentation; + + +/** Prototype for the initialization function which must be implemented by every + host API. + + @see paHostApiInitializers +*/ +typedef PaError PaUtilHostApiInitializer( PaUtilHostApiRepresentation**, PaHostApiIndex ); + + +/** paHostApiInitializers is a NULL-terminated array of host API initialization + functions. These functions are called by pa_front to initialize the host APIs + when the client calls Pa_Initialize(). + + There is a platform specific file which defines paHostApiInitializers for that + platform, pa_win/pa_win_hostapis.c contains the Win32 definitions for example. +*/ +extern PaUtilHostApiInitializer *paHostApiInitializers[]; + + +/** The index of the default host API in the paHostApiInitializers array. + + There is a platform specific file which defines paDefaultHostApiIndex for that + platform, see pa_win/pa_win_hostapis.c for example. +*/ +extern int paDefaultHostApiIndex; + + +#ifdef __cplusplus +} +#endif /* __cplusplus */ +#endif /* PA_HOSTAPI_H */ diff --git a/pa_common/pa_lib.c b/pa_common/pa_lib.c deleted file mode 100644 index 3df5ec5..0000000 --- a/pa_common/pa_lib.c +++ /dev/null @@ -1,806 +0,0 @@ -/* - * $Id$ - * Portable Audio I/O Library - * Host Independant Layer - * - * Based on the Open Source API proposed by Ross Bencina - * Copyright (c) 1999-2000 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. - * - */ - -/* Modification History: - PLB20010422 - apply Mike Berry's changes for CodeWarrior on PC - PLB20010820 - fix dither and shift for recording PaUInt8 format -*/ - -#include -#include -#include -#include - -/* PLB20010422 - "memory.h" doesn't work on CodeWarrior for PC. Thanks Mike Berry for the mod. */ -#ifdef _WIN32 -#ifndef __MWERKS__ -#include -#endif /* __MWERKS__ */ -#else /* !_WIN32 */ -#include -#endif /* _WIN32 */ - -#include "portaudio.h" -#include "pa_host.h" -#include "pa_trace.h" - -/* The reason we might NOT want to validate the rate before opening the stream - * is because many DirectSound drivers lie about the rates they actually support. - */ -#define PA_VALIDATE_RATE (0) /* If true validate sample rate against driver info. */ - -/* -O- maybe not allocate past_InputBuffer and past_OutputBuffer if not needed for conversion -*/ - -#ifndef FALSE - #define FALSE (0) - #define TRUE (!FALSE) -#endif - -#define PRINT(x) { printf x; fflush(stdout); } -#define ERR_RPT(x) PRINT(x) -#define DBUG(x) /* PRINT(x) /**/ -#define DBUGX(x) /* PRINT(x) /**/ - -static int gInitCount = 0; /* Count number of times Pa_Initialize() called to allow nesting and overlapping. */ - -static PaError Pa_KillStream( PortAudioStream *stream, int abort ); - -/***********************************************************************/ -int PaHost_FindClosestTableEntry( double allowableError, const double *rateTable, int numRates, double frameRate ) -{ - double err, minErr = allowableError; - int i, bestFit = -1; - - for( i=0; inumSampleRates == -1 ) - { - /* Is it out of range? */ - if( (requestedFrameRate < pdi->sampleRates[0]) || - (requestedFrameRate > pdi->sampleRates[1]) ) - { - return paInvalidSampleRate; - } - - *closestFrameRatePtr = requestedFrameRate; - } - else - { - bestRateIndex = PaHost_FindClosestTableEntry( 1.0, pdi->sampleRates, pdi->numSampleRates, requestedFrameRate ); - if( bestRateIndex < 0 ) return paInvalidSampleRate; - *closestFrameRatePtr = pdi->sampleRates[bestRateIndex]; - } - return paNoError; -} - -/*************************************************************************/ -PaError Pa_OpenStream( - PortAudioStream** streamPtrPtr, - PaDeviceID inputDeviceID, - int numInputChannels, - PaSampleFormat inputSampleFormat, - void *inputDriverInfo, - PaDeviceID outputDeviceID, - int numOutputChannels, - PaSampleFormat outputSampleFormat, - void *outputDriverInfo, - double sampleRate, - unsigned long framesPerBuffer, - unsigned long numberOfBuffers, - unsigned long streamFlags, - PortAudioCallback *callback, - void *userData ) -{ - internalPortAudioStream *past = NULL; - PaError result = paNoError; - int bitsPerInputSample; - int bitsPerOutputSample; - /* Print passed parameters. */ - DBUG(("Pa_OpenStream( %p, dev=%d, numChan=%d, format=%d, info=%p, /* input */ \n", - streamPtrPtr, inputDeviceID, numInputChannels, - inputSampleFormat, inputDriverInfo )); - DBUG((" dev=%d, numChan=%d, format=%d, info=%p, /* output */\n", - outputDeviceID, numOutputChannels, - outputSampleFormat, outputDriverInfo )); - DBUG((" %g, %d, %d, 0x%x, , %p )\n", - sampleRate, framesPerBuffer, numberOfBuffers, - streamFlags, userData )); - - /* Check for parameter errors. */ - if( (streamFlags & ~(paClipOff | paDitherOff)) != 0 ) return paInvalidFlag; - if( streamPtrPtr == NULL ) return paBadStreamPtr; - if( inputDriverInfo != NULL ) return paHostError; /* REVIEW */ - if( outputDriverInfo != NULL ) return paHostError; /* REVIEW */ - if( (inputDeviceID < 0) && ( outputDeviceID < 0) ) return paInvalidDeviceId; - if( (outputDeviceID >= Pa_CountDevices()) || (inputDeviceID >= Pa_CountDevices()) ) - { - return paInvalidDeviceId; - } - if( (numInputChannels <= 0) && ( numOutputChannels <= 0) ) return paInvalidChannelCount; - -#if SUPPORT_AUDIO_CAPTURE - if( inputDeviceID >= 0 ) - { - PaError size = Pa_GetSampleSize( inputSampleFormat ); - if( size < 0 ) return size; - bitsPerInputSample = 8 * size; - if( (numInputChannels <= 0) ) return paInvalidChannelCount; - } -#else - if( inputDeviceID >= 0 ) - { - return paInvalidChannelCount; - } -#endif /* SUPPORT_AUDIO_CAPTURE */ - else - { - if( numInputChannels > 0 ) return paInvalidChannelCount; - bitsPerInputSample = 0; - } - - if( outputDeviceID >= 0 ) - { - PaError size = Pa_GetSampleSize( outputSampleFormat ); - if( size < 0 ) return size; - bitsPerOutputSample = 8 * size; - if( (numOutputChannels <= 0) ) return paInvalidChannelCount; - } - else - { - if( numOutputChannels > 0 ) return paInvalidChannelCount; - bitsPerOutputSample = 0; - } - - if( callback == NULL ) return paNullCallback; - - /* Allocate and clear stream structure. */ - past = (internalPortAudioStream *) PaHost_AllocateFastMemory( sizeof(internalPortAudioStream) ); - if( past == NULL ) return paInsufficientMemory; - memset( past, 0, sizeof(internalPortAudioStream) ); - AddTraceMessage("Pa_OpenStream: past", (long) past ); - - past->past_Magic = PA_MAGIC; /* Set ID to catch bugs. */ - past->past_FramesPerUserBuffer = framesPerBuffer; - past->past_NumUserBuffers = numberOfBuffers; /* NOTE - PaHost_OpenStream() MUST CHECK FOR ZERO! */ - past->past_Callback = callback; - past->past_UserData = userData; - past->past_OutputSampleFormat = outputSampleFormat; - past->past_InputSampleFormat = inputSampleFormat; - past->past_OutputDeviceID = outputDeviceID; - past->past_InputDeviceID = inputDeviceID; - past->past_NumInputChannels = numInputChannels; - past->past_NumOutputChannels = numOutputChannels; - past->past_Flags = streamFlags; - - /* Check for absurd sample rates. */ - if( (sampleRate < 1000.0) || (sampleRate > 200000.0) ) - { - result = paInvalidSampleRate; - goto cleanup; - } - - /* Allocate buffers that may be used for format conversion from user to native buffers. */ - if( numInputChannels > 0 ) - { - -#if PA_VALIDATE_RATE - result = PaHost_ValidateSampleRate( inputDeviceID, sampleRate, &past->past_SampleRate ); - if( result < 0 ) - { - goto cleanup; - } -#else - past->past_SampleRate = sampleRate; -#endif - /* Allocate single Input buffer for passing formatted samples to user callback. */ - past->past_InputBufferSize = framesPerBuffer * numInputChannels * ((bitsPerInputSample+7) / 8); - past->past_InputBuffer = PaHost_AllocateFastMemory(past->past_InputBufferSize); - if( past->past_InputBuffer == NULL ) - { - result = paInsufficientMemory; - goto cleanup; - } - } - else - { - past->past_InputBuffer = NULL; - } - - /* Allocate single Output buffer. */ - if( numOutputChannels > 0 ) - { -#if PA_VALIDATE_RATE - result = PaHost_ValidateSampleRate( outputDeviceID, sampleRate, &past->past_SampleRate ); - if( result < 0 ) - { - goto cleanup; - } -#else - past->past_SampleRate = sampleRate; -#endif - past->past_OutputBufferSize = framesPerBuffer * numOutputChannels * ((bitsPerOutputSample+7) / 8); - past->past_OutputBuffer = PaHost_AllocateFastMemory(past->past_OutputBufferSize); - if( past->past_OutputBuffer == NULL ) - { - result = paInsufficientMemory; - goto cleanup; - } - } - else - { - past->past_OutputBuffer = NULL; - } - - result = PaHost_OpenStream( past ); - if( result < 0 ) goto cleanup; - - *streamPtrPtr = (void *) past; - - return result; - -cleanup: - if( past != NULL ) Pa_CloseStream( past ); - *streamPtrPtr = NULL; - return result; -} - - -/*************************************************************************/ -PaError Pa_OpenDefaultStream( PortAudioStream** stream, - int numInputChannels, - int numOutputChannels, - PaSampleFormat sampleFormat, - double sampleRate, - unsigned long framesPerBuffer, - unsigned long numberOfBuffers, - PortAudioCallback *callback, - void *userData ) -{ - return Pa_OpenStream( - stream, - ((numInputChannels > 0) ? Pa_GetDefaultInputDeviceID() : paNoDevice), - numInputChannels, sampleFormat, NULL, - ((numOutputChannels > 0) ? Pa_GetDefaultOutputDeviceID() : paNoDevice), - numOutputChannels, sampleFormat, NULL, - sampleRate, framesPerBuffer, numberOfBuffers, paNoFlag, callback, userData ); -} - -/*************************************************************************/ -PaError Pa_CloseStream( PortAudioStream* stream) -{ - PaError result; - internalPortAudioStream *past; - - DBUG(("Pa_CloseStream()\n")); - if( stream == NULL ) return paBadStreamPtr; - past = (internalPortAudioStream *) stream; - - Pa_AbortStream( past ); - result = PaHost_CloseStream( past ); - - if( past->past_InputBuffer ) PaHost_FreeFastMemory( past->past_InputBuffer, past->past_InputBufferSize ); - if( past->past_OutputBuffer ) PaHost_FreeFastMemory( past->past_OutputBuffer, past->past_OutputBufferSize ); - PaHost_FreeFastMemory( past, sizeof(internalPortAudioStream) ); - - return result; -} - -/*************************************************************************/ -PaError Pa_StartStream( PortAudioStream *stream ) -{ - PaError result = paHostError; - internalPortAudioStream *past; - - if( stream == NULL ) return paBadStreamPtr; - past = (internalPortAudioStream *) stream; - - past->past_FrameCount = 0.0; - - if( past->past_NumInputChannels > 0 ) - { - result = PaHost_StartInput( past ); - DBUG(("Pa_StartStream: PaHost_StartInput returned = 0x%X.\n", result)); - if( result < 0 ) goto error; - } - - if( past->past_NumOutputChannels > 0 ) - { - result = PaHost_StartOutput( past ); - DBUG(("Pa_StartStream: PaHost_StartOutput returned = 0x%X.\n", result)); - if( result < 0 ) goto error; - } - - result = PaHost_StartEngine( past ); - DBUG(("Pa_StartStream: PaHost_StartEngine returned = 0x%X.\n", result)); - if( result < 0 ) goto error; - - return paNoError; - -error: - return result; -} - -/*************************************************************************/ -PaError Pa_StopStream( PortAudioStream *stream ) -{ - return Pa_KillStream( stream, 0 ); -} - -/*************************************************************************/ -PaError Pa_AbortStream( PortAudioStream *stream ) -{ - return Pa_KillStream( stream, 1 ); -} - -/*************************************************************************/ -static PaError Pa_KillStream( PortAudioStream *stream, int abort ) -{ - PaError result = paNoError; - internalPortAudioStream *past; - - DBUG(("Pa_StopStream().\n")); - if( stream == NULL ) return paBadStreamPtr; - past = (internalPortAudioStream *) stream; - - if( (past->past_NumInputChannels > 0) || (past->past_NumOutputChannels > 0) ) - { - result = PaHost_StopEngine( past, abort ); - DBUG(("Pa_StopStream: PaHost_StopEngine returned = 0x%X.\n", result)); - if( result < 0 ) goto error; - } - - if( past->past_NumInputChannels > 0 ) - { - result = PaHost_StopInput( past, abort ); - DBUG(("Pa_StopStream: PaHost_StopInput returned = 0x%X.\n", result)); - if( result != paNoError ) goto error; - } - - if( past->past_NumOutputChannels > 0 ) - { - result = PaHost_StopOutput( past, abort ); - DBUG(("Pa_StopStream: PaHost_StopOutput returned = 0x%X.\n", result)); - if( result != paNoError ) goto error; - } - -error: - past->past_Usage = 0; - past->past_IfLastExitValid = 0; - - return result; -} - -/*************************************************************************/ -PaError Pa_StreamActive( PortAudioStream *stream ) -{ - internalPortAudioStream *past; - if( stream == NULL ) return paBadStreamPtr; - past = (internalPortAudioStream *) stream; - return PaHost_StreamActive( past ); -} - -/*************************************************************************/ -const char *Pa_GetErrorText( PaError errnum ) -{ - const char *msg; - - switch(errnum) - { - case paNoError: msg = "Success"; break; - case paHostError: msg = "Host error."; break; - case paInvalidChannelCount: msg = "Invalid number of channels."; break; - case paInvalidSampleRate: msg = "Invalid sample rate."; break; - case paInvalidDeviceId: msg = "Invalid device ID."; break; - case paInvalidFlag: msg = "Invalid flag."; break; - case paSampleFormatNotSupported: msg = "Sample format not supported"; break; - case paBadIODeviceCombination: msg = "Illegal combination of I/O devices."; break; - case paInsufficientMemory: msg = "Insufficient memory."; break; - case paBufferTooBig: msg = "Buffer too big."; break; - case paBufferTooSmall: msg = "Buffer too small."; break; - case paNullCallback: msg = "No callback routine specified."; break; - case paBadStreamPtr: msg = "Invalid stream pointer."; break; - case paTimedOut : msg = "Wait Timed Out."; break; - case paInternalError: msg = "Internal PortAudio Error."; break; - case paDeviceUnavailable: msg = "Device Unavailable."; break; - default: msg = "Illegal error number."; break; - } - return msg; -} - -/* - Get CPU Load as a fraction of total CPU time. - A value of 0.5 would imply that PortAudio and the sound generating - callback was consuming roughly 50% of the available CPU time. - The amount may vary depending on CPU load. - This function may be called from the callback function. -*/ -double Pa_GetCPULoad( PortAudioStream* stream) -{ - internalPortAudioStream *past; - if( stream == NULL ) return (double) paBadStreamPtr; - past = (internalPortAudioStream *) stream; - return past->past_Usage; -} - -/*************************************************************************/ -internalPortAudioStream* PaHost_GetStreamRepresentation( PortAudioStream *stream ) -{ - internalPortAudioStream* result = (internalPortAudioStream*) stream; - - if( result == NULL || result->past_Magic != PA_MAGIC ) - return NULL; - else - return result; -} - -/************************************************************* -** Calculate 2 LSB dither signal with a triangular distribution. -** Ranged properly for adding to a 32 bit integer prior to >>15. -** Range of output is +/- 32767 -*/ -#define PA_DITHER_BITS (15) -#define PA_DITHER_SCALE (1.0f / ((1<>DITHER_SHIFT) + (((long)randSeed2)>>DITHER_SHIFT); - /* High pass filter to reduce audibility. */ - highPass = current - previous; - previous = current; - return highPass; -} - -/************************************************************************* -** Called by host code. -** Convert input from Int16, call user code, then convert output -** to Int16 format for native use. -** Assumes host native format is paInt16. -** Returns result from user callback. -*/ -long Pa_CallConvertInt16( internalPortAudioStream *past, - short *nativeInputBuffer, - short *nativeOutputBuffer ) -{ - long temp; - int userResult; - unsigned int i; - void *inputBuffer = NULL; - void *outputBuffer = NULL; - -#if SUPPORT_AUDIO_CAPTURE - /* Get native data from DirectSound. */ - if( (past->past_NumInputChannels > 0) && (nativeInputBuffer != NULL) ) - { - /* Convert from native format to PA format. */ - unsigned int samplesPerBuffer = past->past_FramesPerUserBuffer * past->past_NumInputChannels; - switch(past->past_InputSampleFormat) - { - - case paFloat32: - { - float *inBufPtr = (float *) past->past_InputBuffer; - inputBuffer = past->past_InputBuffer; - for( i=0; ipast_InputBuffer; - inputBuffer = past->past_InputBuffer; - for( i=0; ipast_InputBuffer; - inputBuffer = past->past_InputBuffer; - if( past->past_Flags & paDitherOff ) - { - for( i=0; i> 8); - } - } - else - { - for( i=0; i> 8; /* PLB20010820 */ - temp = ((temp < -0x8000) ? -0x8000 : ((temp > 0x7FFF) ? 0x7FFF : temp)); - inBufPtr[i] = (char)(temp >> 8); - } - } - break; - } - - case paUInt8: - { - /* Convert 16 bit data to 8 bit unsigned chars */ - unsigned char *inBufPtr = (unsigned char *) past->past_InputBuffer; - inputBuffer = past->past_InputBuffer; - if( past->past_Flags & paDitherOff ) - { - for( i=0; i> 8)) + 0x80; - } - } - else - { - /* If you dither then you have to clip because dithering could push the signal out of range! */ - for( i=0; i> 8; /* PLB20010820 */ - temp = ((temp < -0x8000) ? -0x8000 : ((temp > 0x7FFF) ? 0x7FFF : temp)); - inBufPtr[i] = (unsigned char)((temp>>8) + 0x80); /* PLB20010820 */ - } - } - break; - } - - default: - break; - } - } -#endif /* SUPPORT_AUDIO_CAPTURE */ - - /* Are we doing output time? */ - if( (past->past_NumOutputChannels > 0) && (nativeOutputBuffer != NULL) ) - { - /* May already be in native format so just write directly to native buffer. */ - outputBuffer = (past->past_OutputSampleFormat == paInt16) ? - nativeOutputBuffer : past->past_OutputBuffer; - } - /* - AddTraceMessage("Pa_CallConvertInt16: inputBuffer = ", (int) inputBuffer ); - AddTraceMessage("Pa_CallConvertInt16: outputBuffer = ", (int) outputBuffer ); - */ - /* Call user callback routine. */ - userResult = past->past_Callback( - inputBuffer, - outputBuffer, - past->past_FramesPerUserBuffer, - past->past_FrameCount, - past->past_UserData ); - - past->past_FrameCount += (PaTimestamp) past->past_FramesPerUserBuffer; - - /* Convert to native format if necessary. */ - if( outputBuffer != NULL ) - { - unsigned int samplesPerBuffer = past->past_FramesPerUserBuffer * past->past_NumOutputChannels; - switch(past->past_OutputSampleFormat) - { - case paFloat32: - { - float *outBufPtr = (float *) past->past_OutputBuffer; - if( past->past_Flags & paDitherOff ) - { - if( past->past_Flags & paClipOff ) /* NOTHING */ - { - for( i=0; i 0x7FFF) ? 0x7FFF : temp)); - } - } - } - else - { - /* If you dither then you have to clip because dithering could push the signal out of range! */ - for( i=0; i 0x7FFF) ? 0x7FFF : temp)); - } - } - break; - } - - case paInt32: - { - int *outBufPtr = (int *) past->past_OutputBuffer; - if( past->past_Flags & paDitherOff ) - { - for( i=0; i> 16 ); - } - } - else - { - for( i=0; i> 1) + PaConvert_TriangularDither(); - temp = temp >> 15; - *nativeOutputBuffer++ = (short)((temp < -0x8000) ? -0x8000 : ((temp > 0x7FFF) ? 0x7FFF : temp)); - } - } - break; - } - - case paInt8: - { - char *outBufPtr = (char *) past->past_OutputBuffer; - for( i=0; ipast_OutputBuffer; - for( i=0; i 0 ) return paNoError; - ResetTraceMessages(); - return PaHost_Init(); -} - -PaError Pa_Terminate( void ) -{ - PaError result = paNoError; - - if( gInitCount == 0 ) return paNoError; - else if( --gInitCount == 0 ) - { - result = PaHost_Term(); - DumpTraceMessages(); - } - return result; -} - -int PaHost_IsInitialized() -{ - return gInitCount; -} - -/*************************************************************************/ -PaError Pa_GetSampleSize( PaSampleFormat format ) -{ - int size; - switch(format ) - { - - case paUInt8: - case paInt8: - size = 1; - break; - - case paInt16: - size = 2; - break; - - case paPackedInt24: - size = 3; - break; - - case paFloat32: - case paInt32: - case paInt24: - size = 4; - break; - - default: - size = paSampleFormatNotSupported; - break; - } - return (PaError) size; -} - - diff --git a/pa_common/pa_process.c b/pa_common/pa_process.c new file mode 100644 index 0000000..837bbef --- /dev/null +++ b/pa_common/pa_process.c @@ -0,0 +1,1763 @@ +/* + * $Id$ + * Portable Audio I/O Library + * streamCallback <-> host buffer processing adapter + * + * 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. + * + * 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. + */ + +/** @file + @brief Buffer Processor implementation. + + The code in this file is not optimised yet - although it's not clear that + it needs to be. there may appear to be redundancies + that could be factored into common functions, but the redundanceis are left + intentionally as each appearance may have different optimisation possibilities. + + The optimisations which are planned involve only converting data in-place + where possible, rather than copying to the temp buffer(s). + + Note that in the extreme case of being able to convert in-place, and there + being no conversion necessary there should be some code which short-circuits + the operation. + + @todo Consider cache tilings for intereave<->deinterleave. + + @todo implement timeInfo->currentTime int PaUtil_BeginBufferProcessing() + + @todo specify and implement some kind of logical policy for handling the + underflow and overflow stream flags when the underflow/overflow overlaps + multiple user buffers/callbacks. + + @todo provide support for priming the buffers with data from the callback. + The client interface is now implemented through PaUtil_SetNoInput() + which sets bp->hostInputChannels[0][0].data to zero. However this is + currently only implemented in NonAdaptingProcess(). It shouldn't be + needed for AdaptingInputOnlyProcess() (no priming should ever be + requested for AdaptingInputOnlyProcess()). + Not sure if additional work should be required to make it work with + AdaptingOutputOnlyProcess, but it definitely is required for + AdaptingProcess. + + @todo implement PaUtil_SetNoOutput for AdaptingProcess + + @todo don't allocate temp buffers for blocking streams unless they are + needed. At the moment they are needed, but perhaps for host APIs + where the implementation passes a buffer to the host they could be + used. +*/ + + +#include +#include /* memset() */ + +#include "pa_process.h" +#include "pa_util.h" + + +#define PA_FRAMES_PER_TEMP_BUFFER_WHEN_HOST_BUFFER_SIZE_IS_UNKNOWN_ 1024 + +#define PA_MIN_( a, b ) ( ((a)<(b)) ? (a) : (b) ) + + +/* greatest common divisor - PGCD in French */ +static unsigned long GCD( unsigned long a, unsigned long b ) +{ + return (b==0) ? a : GCD( b, a%b); +} + +/* least common multiple - PPCM in French */ +static unsigned long LCM( unsigned long a, unsigned long b ) +{ + return (a*b) / GCD(a,b); +} + +#define PA_MAX_( a, b ) (((a) > (b)) ? (a) : (b)) + +static unsigned long CalculateFrameShift( unsigned long M, unsigned long N ) +{ + unsigned long result = 0; + unsigned long i; + unsigned long lcm; + + assert( M > 0 ); + assert( N > 0 ); + + lcm = LCM( M, N ); + for( i = M; i < lcm; i += M ) + result = PA_MAX_( result, i % N ); + + return result; +} + + +PaError PaUtil_InitializeBufferProcessor( PaUtilBufferProcessor* bp, + int inputChannelCount, PaSampleFormat userInputSampleFormat, + PaSampleFormat hostInputSampleFormat, + int outputChannelCount, PaSampleFormat userOutputSampleFormat, + PaSampleFormat hostOutputSampleFormat, + double sampleRate, + PaStreamFlags streamFlags, + unsigned long framesPerUserBuffer, + unsigned long framesPerHostBuffer, + PaUtilHostBufferSizeMode hostBufferSizeMode, + PaStreamCallback *streamCallback, void *userData ) +{ + PaError result = paNoError; + PaError bytesPerSample; + unsigned long tempInputBufferSize, tempOutputBufferSize; + + if( streamFlags & paNeverDropInput ) + { + /* paNeverDropInput is only valid for full-duplex callback streams, with an unspecified number of frames per buffer. */ + if( !streamCallback || !(inputChannelCount > 0 && outputChannelCount > 0) || + framesPerUserBuffer != paFramesPerBufferUnspecified ) + return paInvalidFlag; + } + + /* initialize buffer ptrs to zero so they can be freed if necessary in error */ + bp->tempInputBuffer = 0; + bp->tempInputBufferPtrs = 0; + bp->tempOutputBuffer = 0; + bp->tempOutputBufferPtrs = 0; + + bp->framesPerUserBuffer = framesPerUserBuffer; + bp->framesPerHostBuffer = framesPerHostBuffer; + + bp->inputChannelCount = inputChannelCount; + bp->outputChannelCount = outputChannelCount; + + bp->hostBufferSizeMode = hostBufferSizeMode; + + bp->hostInputChannels[0] = bp->hostInputChannels[1] = 0; + bp->hostOutputChannels[0] = bp->hostOutputChannels[1] = 0; + + if( framesPerUserBuffer == 0 ) /* streamCallback will accept any buffer size */ + { + bp->useNonAdaptingProcess = 1; + bp->initialFramesInTempInputBuffer = 0; + bp->initialFramesInTempOutputBuffer = 0; + + if( hostBufferSizeMode == paUtilFixedHostBufferSize + || hostBufferSizeMode == paUtilBoundedHostBufferSize ) + { + bp->framesPerTempBuffer = framesPerHostBuffer; + } + else /* unknown host buffer size */ + { + bp->framesPerTempBuffer = PA_FRAMES_PER_TEMP_BUFFER_WHEN_HOST_BUFFER_SIZE_IS_UNKNOWN_; + } + } + else + { + bp->framesPerTempBuffer = framesPerUserBuffer; + + if( hostBufferSizeMode == paUtilFixedHostBufferSize + && framesPerHostBuffer % framesPerUserBuffer == 0 ) + { + bp->useNonAdaptingProcess = 1; + bp->initialFramesInTempInputBuffer = 0; + bp->initialFramesInTempOutputBuffer = 0; + } + else + { + bp->useNonAdaptingProcess = 0; + + if( inputChannelCount > 0 && outputChannelCount > 0 ) + { + /* full duplex */ + if( hostBufferSizeMode == paUtilFixedHostBufferSize ) + { + unsigned long frameShift = + CalculateFrameShift( framesPerHostBuffer, framesPerUserBuffer ); + + if( framesPerUserBuffer > framesPerHostBuffer ) + { + bp->initialFramesInTempInputBuffer = frameShift; + bp->initialFramesInTempOutputBuffer = 0; + } + else + { + bp->initialFramesInTempInputBuffer = 0; + bp->initialFramesInTempOutputBuffer = frameShift; + } + } + else /* variable host buffer size, add framesPerUserBuffer latency */ + { + bp->initialFramesInTempInputBuffer = 0; + bp->initialFramesInTempOutputBuffer = framesPerUserBuffer; + } + } + else + { + /* half duplex */ + bp->initialFramesInTempInputBuffer = 0; + bp->initialFramesInTempOutputBuffer = 0; + } + } + } + + + bp->framesInTempInputBuffer = bp->initialFramesInTempInputBuffer; + bp->framesInTempOutputBuffer = bp->initialFramesInTempOutputBuffer; + + + if( inputChannelCount > 0 ) + { + bytesPerSample = Pa_GetSampleSize( hostInputSampleFormat ); + if( bytesPerSample > 0 ) + { + bp->bytesPerHostInputSample = bytesPerSample; + } + else + { + result = bytesPerSample; + goto error; + } + + bytesPerSample = Pa_GetSampleSize( userInputSampleFormat ); + if( bytesPerSample > 0 ) + { + bp->bytesPerUserInputSample = bytesPerSample; + } + else + { + result = bytesPerSample; + goto error; + } + + bp->inputConverter = + PaUtil_SelectConverter( hostInputSampleFormat, userInputSampleFormat, streamFlags ); + + bp->inputZeroer = PaUtil_SelectZeroer( hostInputSampleFormat ); + + bp->userInputIsInterleaved = (userInputSampleFormat & paNonInterleaved)?0:1; + + + tempInputBufferSize = + bp->framesPerTempBuffer * bp->bytesPerUserInputSample * inputChannelCount; + + bp->tempInputBuffer = PaUtil_AllocateMemory( tempInputBufferSize ); + if( bp->tempInputBuffer == 0 ) + { + result = paInsufficientMemory; + goto error; + } + + if( bp->framesInTempInputBuffer > 0 ) + memset( bp->tempInputBuffer, 0, tempInputBufferSize ); + + if( userInputSampleFormat & paNonInterleaved ) + { + bp->tempInputBufferPtrs = + (void **)PaUtil_AllocateMemory( sizeof(void*)*inputChannelCount ); + if( bp->tempInputBufferPtrs == 0 ) + { + result = paInsufficientMemory; + goto error; + } + } + + bp->hostInputChannels[0] = (PaUtilChannelDescriptor*) + PaUtil_AllocateMemory( sizeof(PaUtilChannelDescriptor) * inputChannelCount * 2); + if( bp->hostInputChannels[0] == 0 ) + { + result = paInsufficientMemory; + goto error; + } + + bp->hostInputChannels[1] = &bp->hostInputChannels[0][inputChannelCount]; + } + + if( outputChannelCount > 0 ) + { + bytesPerSample = Pa_GetSampleSize( hostOutputSampleFormat ); + if( bytesPerSample > 0 ) + { + bp->bytesPerHostOutputSample = bytesPerSample; + } + else + { + result = bytesPerSample; + goto error; + } + + bytesPerSample = Pa_GetSampleSize( userOutputSampleFormat ); + if( bytesPerSample > 0 ) + { + bp->bytesPerUserOutputSample = bytesPerSample; + } + else + { + result = bytesPerSample; + goto error; + } + + bp->outputConverter = + PaUtil_SelectConverter( userOutputSampleFormat, hostOutputSampleFormat, streamFlags ); + + bp->outputZeroer = PaUtil_SelectZeroer( hostOutputSampleFormat ); + + bp->userOutputIsInterleaved = (userOutputSampleFormat & paNonInterleaved)?0:1; + + tempOutputBufferSize = + bp->framesPerTempBuffer * bp->bytesPerUserOutputSample * outputChannelCount; + + bp->tempOutputBuffer = PaUtil_AllocateMemory( tempOutputBufferSize ); + if( bp->tempOutputBuffer == 0 ) + { + result = paInsufficientMemory; + goto error; + } + + if( bp->framesInTempOutputBuffer > 0 ) + memset( bp->tempOutputBuffer, 0, tempOutputBufferSize ); + + if( userOutputSampleFormat & paNonInterleaved ) + { + bp->tempOutputBufferPtrs = + (void **)PaUtil_AllocateMemory( sizeof(void*)*outputChannelCount ); + if( bp->tempOutputBufferPtrs == 0 ) + { + result = paInsufficientMemory; + goto error; + } + } + + bp->hostOutputChannels[0] = (PaUtilChannelDescriptor*) + PaUtil_AllocateMemory( sizeof(PaUtilChannelDescriptor)*outputChannelCount * 2 ); + if( bp->hostOutputChannels[0] == 0 ) + { + result = paInsufficientMemory; + goto error; + } + + bp->hostOutputChannels[1] = &bp->hostOutputChannels[0][outputChannelCount]; + } + + PaUtil_InitializeTriangularDitherState( &bp->ditherGenerator ); + + bp->samplePeriod = 1. / sampleRate; + + bp->streamCallback = streamCallback; + bp->userData = userData; + + return result; + +error: + if( bp->tempInputBuffer ) + PaUtil_FreeMemory( bp->tempInputBuffer ); + + if( bp->tempInputBufferPtrs ) + PaUtil_FreeMemory( bp->tempInputBufferPtrs ); + + if( bp->hostInputChannels[0] ) + PaUtil_FreeMemory( bp->hostInputChannels[0] ); + + if( bp->tempOutputBuffer ) + PaUtil_FreeMemory( bp->tempOutputBuffer ); + + if( bp->tempOutputBufferPtrs ) + PaUtil_FreeMemory( bp->tempOutputBufferPtrs ); + + if( bp->hostOutputChannels[0] ) + PaUtil_FreeMemory( bp->hostOutputChannels[0] ); + + return result; +} + + +void PaUtil_TerminateBufferProcessor( PaUtilBufferProcessor* bp ) +{ + if( bp->tempInputBuffer ) + PaUtil_FreeMemory( bp->tempInputBuffer ); + + if( bp->tempInputBufferPtrs ) + PaUtil_FreeMemory( bp->tempInputBufferPtrs ); + + if( bp->hostInputChannels[0] ) + PaUtil_FreeMemory( bp->hostInputChannels[0] ); + + if( bp->tempOutputBuffer ) + PaUtil_FreeMemory( bp->tempOutputBuffer ); + + if( bp->tempOutputBufferPtrs ) + PaUtil_FreeMemory( bp->tempOutputBufferPtrs ); + + if( bp->hostOutputChannels[0] ) + PaUtil_FreeMemory( bp->hostOutputChannels[0] ); +} + + +void PaUtil_ResetBufferProcessor( PaUtilBufferProcessor* bp ) +{ + unsigned long tempInputBufferSize, tempOutputBufferSize; + + bp->framesInTempInputBuffer = bp->initialFramesInTempInputBuffer; + bp->framesInTempOutputBuffer = bp->initialFramesInTempOutputBuffer; + + if( bp->framesInTempInputBuffer > 0 ) + { + tempInputBufferSize = + bp->framesPerTempBuffer * bp->bytesPerUserInputSample * bp->inputChannelCount; + memset( bp->tempInputBuffer, 0, tempInputBufferSize ); + } + + if( bp->framesInTempOutputBuffer > 0 ) + { + tempOutputBufferSize = + bp->framesPerTempBuffer * bp->bytesPerUserOutputSample * bp->outputChannelCount; + memset( bp->tempOutputBuffer, 0, tempOutputBufferSize ); + } +} + + +unsigned long PaUtil_GetBufferProcessorInputLatency( PaUtilBufferProcessor* bp ) +{ + return bp->initialFramesInTempInputBuffer; +} + + +unsigned long PaUtil_GetBufferProcessorOutputLatency( PaUtilBufferProcessor* bp ) +{ + return bp->initialFramesInTempOutputBuffer; +} + + +void PaUtil_SetInputFrameCount( PaUtilBufferProcessor* bp, + unsigned long frameCount ) +{ + if( frameCount == 0 ) + bp->hostInputFrameCount[0] = bp->framesPerHostBuffer; + else + bp->hostInputFrameCount[0] = frameCount; +} + + +void PaUtil_SetNoInput( PaUtilBufferProcessor* bp ) +{ + assert( bp->inputChannelCount > 0 ); + + bp->hostInputChannels[0][0].data = 0; +} + + +void PaUtil_SetInputChannel( PaUtilBufferProcessor* bp, + unsigned int channel, void *data, unsigned int stride ) +{ + assert( channel < bp->inputChannelCount ); + + bp->hostInputChannels[0][channel].data = data; + bp->hostInputChannels[0][channel].stride = stride; +} + + +void PaUtil_SetInterleavedInputChannels( PaUtilBufferProcessor* bp, + unsigned int firstChannel, void *data, unsigned int channelCount ) +{ + unsigned int i; + unsigned int channel = firstChannel; + unsigned char *p = (unsigned char*)data; + + if( channelCount == 0 ) + channelCount = bp->inputChannelCount; + + assert( firstChannel < bp->inputChannelCount ); + assert( firstChannel + channelCount <= bp->inputChannelCount ); + + for( i=0; i< channelCount; ++i ) + { + bp->hostInputChannels[0][channel+i].data = p; + p += bp->bytesPerHostInputSample; + bp->hostInputChannels[0][channel+i].stride = channelCount; + } +} + + +void PaUtil_SetNonInterleavedInputChannel( PaUtilBufferProcessor* bp, + unsigned int channel, void *data ) +{ + assert( channel < bp->inputChannelCount ); + + bp->hostInputChannels[0][channel].data = data; + bp->hostInputChannels[0][channel].stride = 1; +} + + +void PaUtil_Set2ndInputFrameCount( PaUtilBufferProcessor* bp, + unsigned long frameCount ) +{ + bp->hostInputFrameCount[1] = frameCount; +} + + +void PaUtil_Set2ndInputChannel( PaUtilBufferProcessor* bp, + unsigned int channel, void *data, unsigned int stride ) +{ + assert( channel < bp->inputChannelCount ); + + bp->hostInputChannels[1][channel].data = data; + bp->hostInputChannels[1][channel].stride = stride; +} + + +void PaUtil_Set2ndInterleavedInputChannels( PaUtilBufferProcessor* bp, + unsigned int firstChannel, void *data, unsigned int channelCount ) +{ + unsigned int i; + unsigned int channel = firstChannel; + unsigned char *p = (unsigned char*)data; + + if( channelCount == 0 ) + channelCount = bp->inputChannelCount; + + assert( firstChannel < bp->inputChannelCount ); + assert( firstChannel + channelCount <= bp->inputChannelCount ); + + for( i=0; i< channelCount; ++i ) + { + bp->hostInputChannels[1][channel+i].data = p; + p += bp->bytesPerHostInputSample; + bp->hostInputChannels[1][channel+i].stride = channelCount; + } +} + + +void PaUtil_Set2ndNonInterleavedInputChannel( PaUtilBufferProcessor* bp, + unsigned int channel, void *data ) +{ + assert( channel < bp->inputChannelCount ); + + bp->hostInputChannels[1][channel].data = data; + bp->hostInputChannels[1][channel].stride = 1; +} + + +void PaUtil_SetOutputFrameCount( PaUtilBufferProcessor* bp, + unsigned long frameCount ) +{ + if( frameCount == 0 ) + bp->hostOutputFrameCount[0] = bp->framesPerHostBuffer; + else + bp->hostOutputFrameCount[0] = frameCount; +} + + +void PaUtil_SetNoOutput( PaUtilBufferProcessor* bp ) +{ + assert( bp->outputChannelCount > 0 ); + + bp->hostOutputChannels[0][0].data = 0; +} + + +void PaUtil_SetOutputChannel( PaUtilBufferProcessor* bp, + unsigned int channel, void *data, unsigned int stride ) +{ + assert( channel < bp->outputChannelCount ); + assert( data != NULL ); + + bp->hostOutputChannels[0][channel].data = data; + bp->hostOutputChannels[0][channel].stride = stride; +} + + +void PaUtil_SetInterleavedOutputChannels( PaUtilBufferProcessor* bp, + unsigned int firstChannel, void *data, unsigned int channelCount ) +{ + unsigned int i; + unsigned int channel = firstChannel; + unsigned char *p = (unsigned char*)data; + + if( channelCount == 0 ) + channelCount = bp->outputChannelCount; + + assert( firstChannel < bp->outputChannelCount ); + assert( firstChannel + channelCount <= bp->outputChannelCount ); + + for( i=0; i< channelCount; ++i ) + { + PaUtil_SetOutputChannel( bp, channel + i, p, channelCount ); + p += bp->bytesPerHostOutputSample; + } +} + + +void PaUtil_SetNonInterleavedOutputChannel( PaUtilBufferProcessor* bp, + unsigned int channel, void *data ) +{ + assert( channel < bp->outputChannelCount ); + + PaUtil_SetOutputChannel( bp, channel, data, 1 ); +} + + +void PaUtil_Set2ndOutputFrameCount( PaUtilBufferProcessor* bp, + unsigned long frameCount ) +{ + bp->hostOutputFrameCount[1] = frameCount; +} + + +void PaUtil_Set2ndOutputChannel( PaUtilBufferProcessor* bp, + unsigned int channel, void *data, unsigned int stride ) +{ + assert( channel < bp->outputChannelCount ); + assert( data != NULL ); + + bp->hostOutputChannels[1][channel].data = data; + bp->hostOutputChannels[1][channel].stride = stride; +} + + +void PaUtil_Set2ndInterleavedOutputChannels( PaUtilBufferProcessor* bp, + unsigned int firstChannel, void *data, unsigned int channelCount ) +{ + unsigned int i; + unsigned int channel = firstChannel; + unsigned char *p = (unsigned char*)data; + + if( channelCount == 0 ) + channelCount = bp->outputChannelCount; + + assert( firstChannel < bp->outputChannelCount ); + assert( firstChannel + channelCount <= bp->outputChannelCount ); + + for( i=0; i< channelCount; ++i ) + { + PaUtil_Set2ndOutputChannel( bp, channel + i, p, channelCount ); + p += bp->bytesPerHostOutputSample; + } +} + + +void PaUtil_Set2ndNonInterleavedOutputChannel( PaUtilBufferProcessor* bp, + unsigned int channel, void *data ) +{ + assert( channel < bp->outputChannelCount ); + + PaUtil_Set2ndOutputChannel( bp, channel, data, 1 ); +} + + +void PaUtil_BeginBufferProcessing( PaUtilBufferProcessor* bp, + PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags callbackStatusFlags ) +{ + bp->timeInfo = timeInfo; + + /* the first streamCallback will be called to process samples which are + currently in the input buffer before the ones starting at the timeInfo time */ + + bp->timeInfo->inputBufferAdcTime -= bp->framesInTempInputBuffer * bp->samplePeriod; + + bp->timeInfo->currentTime = 0; /** FIXME: @todo time info currentTime not implemented */ + + /* the first streamCallback will be called to generate samples which will be + outputted after the frames currently in the output buffer have been + outputted. */ + bp->timeInfo->outputBufferDacTime += bp->framesInTempOutputBuffer * bp->samplePeriod; + + bp->callbackStatusFlags = callbackStatusFlags; + + bp->hostInputFrameCount[1] = 0; + bp->hostOutputFrameCount[1] = 0; +} + + +/* + NonAdaptingProcess() is a simple buffer copying adaptor that can handle + both full and half duplex copies. It processes framesToProcess frames, + broken into blocks bp->framesPerTempBuffer long. + This routine can be used when the streamCallback doesn't care what length + the buffers are, or when framesToProcess is an integer multiple of + bp->framesPerTempBuffer, in which case streamCallback will always be called + with bp->framesPerTempBuffer samples. +*/ +static unsigned long NonAdaptingProcess( PaUtilBufferProcessor *bp, + int *streamCallbackResult, + PaUtilChannelDescriptor *hostInputChannels, + PaUtilChannelDescriptor *hostOutputChannels, + unsigned long framesToProcess ) +{ + void *userInput, *userOutput; + unsigned char *srcBytePtr, *destBytePtr; + unsigned int srcSampleStrideSamples; /* stride from one sample to the next within a channel, in samples */ + unsigned int srcChannelStrideBytes; /* stride from one channel to the next, in bytes */ + unsigned int destSampleStrideSamples; /* stride from one sample to the next within a channel, in samples */ + unsigned int destChannelStrideBytes; /* stride from one channel to the next, in bytes */ + unsigned int i; + unsigned long frameCount; + unsigned long framesToGo = framesToProcess; + unsigned long framesProcessed = 0; + + + if( *streamCallbackResult == paContinue ) + { + do + { + frameCount = PA_MIN_( bp->framesPerTempBuffer, framesToGo ); + + /* configure user input buffer and convert input data (host -> user) */ + if( bp->inputChannelCount == 0 ) + { + /* no input */ + userInput = 0; + } + else /* there are input channels */ + { + /* + could use more elaborate logic here and sometimes process + buffers in-place. + */ + + destBytePtr = (unsigned char *)bp->tempInputBuffer; + + if( bp->userInputIsInterleaved ) + { + destSampleStrideSamples = bp->inputChannelCount; + destChannelStrideBytes = bp->bytesPerUserInputSample; + userInput = bp->tempInputBuffer; + } + else /* user input is not interleaved */ + { + destSampleStrideSamples = 1; + destChannelStrideBytes = frameCount * bp->bytesPerUserInputSample; + + /* setup non-interleaved ptrs */ + for( i=0; iinputChannelCount; ++i ) + { + bp->tempInputBufferPtrs[i] = ((unsigned char*)bp->tempInputBuffer) + + i * bp->bytesPerUserInputSample * frameCount; + } + + userInput = bp->tempInputBufferPtrs; + } + + if( !bp->hostInputChannels[0][0].data ) + { + /* no input was supplied (see PaUtil_SetNoInput), so + zero the input buffer */ + + for( i=0; iinputChannelCount; ++i ) + { + bp->inputZeroer( destBytePtr, destSampleStrideSamples, frameCount ); + destBytePtr += destChannelStrideBytes; /* skip to next destination channel */ + } + } + else + { + for( i=0; iinputChannelCount; ++i ) + { + bp->inputConverter( destBytePtr, destSampleStrideSamples, + hostInputChannels[i].data, + hostInputChannels[i].stride, + frameCount, &bp->ditherGenerator ); + + destBytePtr += destChannelStrideBytes; /* skip to next destination channel */ + + /* advance src ptr for next iteration */ + hostInputChannels[i].data = ((unsigned char*)hostInputChannels[i].data) + + frameCount * hostInputChannels[i].stride * bp->bytesPerHostInputSample; + } + } + } + + /* configure user output buffer */ + if( bp->outputChannelCount == 0 ) + { + /* no output */ + userOutput = 0; + } + else /* there are output channels */ + { + if( bp->userOutputIsInterleaved ) + { + userOutput = bp->tempOutputBuffer; + } + else /* user output is not interleaved */ + { + for( i = 0; i < bp->outputChannelCount; ++i ) + { + bp->tempOutputBufferPtrs[i] = ((unsigned char*)bp->tempOutputBuffer) + + i * bp->bytesPerUserOutputSample * frameCount; + } + + userOutput = bp->tempOutputBufferPtrs; + } + } + + *streamCallbackResult = bp->streamCallback( userInput, userOutput, + frameCount, bp->timeInfo, bp->callbackStatusFlags, bp->userData ); + + if( *streamCallbackResult == paAbort ) + { + /* callback returned paAbort, don't advance framesProcessed + and framesToGo, they will be handled below */ + } + else + { + bp->timeInfo->inputBufferAdcTime += frameCount * bp->samplePeriod; + bp->timeInfo->outputBufferDacTime += frameCount * bp->samplePeriod; + + /* convert output data (user -> host) */ + + if( bp->outputChannelCount != 0 && bp->hostOutputChannels[0][0].data ) + { + /* + could use more elaborate logic here and sometimes process + buffers in-place. + */ + + srcBytePtr = (unsigned char *)bp->tempOutputBuffer; + + if( bp->userOutputIsInterleaved ) + { + srcSampleStrideSamples = bp->outputChannelCount; + srcChannelStrideBytes = bp->bytesPerUserOutputSample; + } + else /* user output is not interleaved */ + { + srcSampleStrideSamples = 1; + srcChannelStrideBytes = frameCount * bp->bytesPerUserOutputSample; + } + + for( i=0; ioutputChannelCount; ++i ) + { + bp->outputConverter( hostOutputChannels[i].data, + hostOutputChannels[i].stride, + srcBytePtr, srcSampleStrideSamples, + frameCount, &bp->ditherGenerator ); + + srcBytePtr += srcChannelStrideBytes; /* skip to next source channel */ + + /* advance dest ptr for next iteration */ + hostOutputChannels[i].data = ((unsigned char*)hostOutputChannels[i].data) + + frameCount * hostOutputChannels[i].stride * bp->bytesPerHostOutputSample; + } + } + + framesProcessed += frameCount; + + framesToGo -= frameCount; + } + } + while( framesToGo > 0 && *streamCallbackResult == paContinue ); + } + + if( framesToGo > 0 ) + { + /* zero any remaining frames output. There will only be remaining frames + if the callback has returned paComplete or paAbort */ + + frameCount = framesToGo; + + if( bp->outputChannelCount != 0 && bp->hostOutputChannels[0][0].data ) + { + for( i=0; ioutputChannelCount; ++i ) + { + bp->outputZeroer( hostOutputChannels[i].data, + hostOutputChannels[i].stride, + frameCount ); + + /* advance dest ptr for next iteration */ + hostOutputChannels[i].data = ((unsigned char*)hostOutputChannels[i].data) + + frameCount * hostOutputChannels[i].stride * bp->bytesPerHostOutputSample; + } + } + + framesProcessed += frameCount; + } + + return framesProcessed; +} + + +/* + AdaptingInputOnlyProcess() is a half duplex input buffer processor. It + converts data from the input buffers into the temporary input buffer, + when the temporary input buffer is full, it calls the streamCallback. +*/ +static unsigned long AdaptingInputOnlyProcess( PaUtilBufferProcessor *bp, + int *streamCallbackResult, + PaUtilChannelDescriptor *hostInputChannels, + unsigned long framesToProcess ) +{ + void *userInput, *userOutput; + unsigned char *destBytePtr; + unsigned int destSampleStrideSamples; /* stride from one sample to the next within a channel, in samples */ + unsigned int destChannelStrideBytes; /* stride from one channel to the next, in bytes */ + unsigned int i; + unsigned long frameCount; + unsigned long framesToGo = framesToProcess; + unsigned long framesProcessed = 0; + + userOutput = 0; + + do + { + frameCount = ( bp->framesInTempInputBuffer + framesToGo > bp->framesPerUserBuffer ) + ? ( bp->framesPerUserBuffer - bp->framesInTempInputBuffer ) + : framesToGo; + + /* convert frameCount samples into temp buffer */ + + if( bp->userInputIsInterleaved ) + { + destBytePtr = ((unsigned char*)bp->tempInputBuffer) + + bp->bytesPerUserInputSample * bp->inputChannelCount * + bp->framesInTempInputBuffer; + + destSampleStrideSamples = bp->inputChannelCount; + destChannelStrideBytes = bp->bytesPerUserInputSample; + + userInput = bp->tempInputBuffer; + } + else /* user input is not interleaved */ + { + destBytePtr = ((unsigned char*)bp->tempInputBuffer) + + bp->bytesPerUserInputSample * bp->framesInTempInputBuffer; + + destSampleStrideSamples = 1; + destChannelStrideBytes = bp->framesPerUserBuffer * bp->bytesPerUserInputSample; + + /* setup non-interleaved ptrs */ + for( i=0; iinputChannelCount; ++i ) + { + bp->tempInputBufferPtrs[i] = ((unsigned char*)bp->tempInputBuffer) + + i * bp->bytesPerUserInputSample * bp->framesPerUserBuffer; + } + + userInput = bp->tempInputBufferPtrs; + } + + for( i=0; iinputChannelCount; ++i ) + { + bp->inputConverter( destBytePtr, destSampleStrideSamples, + hostInputChannels[i].data, + hostInputChannels[i].stride, + frameCount, &bp->ditherGenerator ); + + destBytePtr += destChannelStrideBytes; /* skip to next destination channel */ + + /* advance src ptr for next iteration */ + hostInputChannels[i].data = ((unsigned char*)hostInputChannels[i].data) + + frameCount * hostInputChannels[i].stride * bp->bytesPerHostInputSample; + } + + bp->framesInTempInputBuffer += frameCount; + + if( bp->framesInTempInputBuffer == bp->framesPerUserBuffer ) + { + /** + @todo (non-critical optimisation) + The conditional below implements the continue/complete/abort mechanism + simply by continuing on iterating through the input buffer, but not + passing the data to the callback. With care, the outer loop could be + terminated earlier, thus some unneeded conversion cycles would be + saved. + */ + if( *streamCallbackResult == paContinue ) + { + bp->timeInfo->outputBufferDacTime = 0; + + *streamCallbackResult = bp->streamCallback( userInput, userOutput, + bp->framesPerUserBuffer, bp->timeInfo, + bp->callbackStatusFlags, bp->userData ); + + bp->timeInfo->inputBufferAdcTime += frameCount * bp->samplePeriod; + } + + bp->framesInTempInputBuffer = 0; + } + + framesProcessed += frameCount; + + framesToGo -= frameCount; + }while( framesToGo > 0 ); + + return framesProcessed; +} + + +/* + AdaptingOutputOnlyProcess() is a half duplex output buffer processor. + It converts data from the temporary output buffer, to the output buffers, + when the temporary output buffer is empty, it calls the streamCallback. +*/ +static unsigned long AdaptingOutputOnlyProcess( PaUtilBufferProcessor *bp, + int *streamCallbackResult, + PaUtilChannelDescriptor *hostOutputChannels, + unsigned long framesToProcess ) +{ + void *userInput, *userOutput; + unsigned char *srcBytePtr; + unsigned int srcSampleStrideSamples; /* stride from one sample to the next within a channel, in samples */ + unsigned int srcChannelStrideBytes; /* stride from one channel to the next, in bytes */ + unsigned int i; + unsigned long frameCount; + unsigned long framesToGo = framesToProcess; + unsigned long framesProcessed = 0; + + do + { + if( bp->framesInTempOutputBuffer == 0 && *streamCallbackResult == paContinue ) + { + userInput = 0; + + /* setup userOutput */ + if( bp->userOutputIsInterleaved ) + { + userOutput = bp->tempOutputBuffer; + } + else /* user output is not interleaved */ + { + for( i = 0; i < bp->outputChannelCount; ++i ) + { + bp->tempOutputBufferPtrs[i] = ((unsigned char*)bp->tempOutputBuffer) + + i * bp->framesPerUserBuffer * bp->bytesPerUserOutputSample; + } + + userOutput = bp->tempOutputBufferPtrs; + } + + bp->timeInfo->inputBufferAdcTime = 0; + + *streamCallbackResult = bp->streamCallback( userInput, userOutput, + bp->framesPerUserBuffer, bp->timeInfo, + bp->callbackStatusFlags, bp->userData ); + + if( *streamCallbackResult == paAbort ) + { + /* if the callback returned paAbort, we disregard its output */ + } + else + { + bp->timeInfo->outputBufferDacTime += bp->framesPerUserBuffer * bp->samplePeriod; + + bp->framesInTempOutputBuffer = bp->framesPerUserBuffer; + } + } + + if( bp->framesInTempOutputBuffer > 0 ) + { + /* convert frameCount frames from user buffer to host buffer */ + + frameCount = PA_MIN_( bp->framesInTempOutputBuffer, framesToGo ); + + if( bp->userOutputIsInterleaved ) + { + srcBytePtr = ((unsigned char*)bp->tempOutputBuffer) + + bp->bytesPerUserOutputSample * bp->outputChannelCount * + (bp->framesPerUserBuffer - bp->framesInTempOutputBuffer); + + srcSampleStrideSamples = bp->outputChannelCount; + srcChannelStrideBytes = bp->bytesPerUserOutputSample; + } + else /* user output is not interleaved */ + { + srcBytePtr = ((unsigned char*)bp->tempOutputBuffer) + + bp->bytesPerUserOutputSample * + (bp->framesPerUserBuffer - bp->framesInTempOutputBuffer); + + srcSampleStrideSamples = 1; + srcChannelStrideBytes = bp->framesPerUserBuffer * bp->bytesPerUserOutputSample; + } + + for( i=0; ioutputChannelCount; ++i ) + { + bp->outputConverter( hostOutputChannels[i].data, + hostOutputChannels[i].stride, + srcBytePtr, srcSampleStrideSamples, + frameCount, &bp->ditherGenerator ); + + srcBytePtr += srcChannelStrideBytes; /* skip to next source channel */ + + /* advance dest ptr for next iteration */ + hostOutputChannels[i].data = ((unsigned char*)hostOutputChannels[i].data) + + frameCount * hostOutputChannels[i].stride * bp->bytesPerHostOutputSample; + } + + bp->framesInTempOutputBuffer -= frameCount; + } + else + { + /* no more user data is available because the callback has returned + paComplete or paAbort. Fill the remainder of the host buffer + with zeros. + */ + + frameCount = framesToGo; + + for( i=0; ioutputChannelCount; ++i ) + { + bp->outputZeroer( hostOutputChannels[i].data, + hostOutputChannels[i].stride, + frameCount ); + + /* advance dest ptr for next iteration */ + hostOutputChannels[i].data = ((unsigned char*)hostOutputChannels[i].data) + + frameCount * hostOutputChannels[i].stride * bp->bytesPerHostOutputSample; + } + } + + framesProcessed += frameCount; + + framesToGo -= frameCount; + + }while( framesToGo > 0 ); + + return framesProcessed; +} + +/* CopyTempOutputBuffersToHostOutputBuffers is called from AdaptingProcess to copy frames from + tempOutputBuffer to hostOutputChannels. This includes data conversion + and interleaving. +*/ +static void CopyTempOutputBuffersToHostOutputBuffers( PaUtilBufferProcessor *bp) +{ + unsigned long maxFramesToCopy; + PaUtilChannelDescriptor *hostOutputChannels; + unsigned int frameCount; + unsigned char *srcBytePtr; + unsigned int srcSampleStrideSamples; /* stride from one sample to the next within a channel, in samples */ + unsigned int srcChannelStrideBytes; /* stride from one channel to the next, in bytes */ + unsigned int i; + + /* copy frames from user to host output buffers */ + while( bp->framesInTempOutputBuffer > 0 && + ((bp->hostOutputFrameCount[0] + bp->hostOutputFrameCount[1]) > 0) ) + { + maxFramesToCopy = bp->framesInTempOutputBuffer; + + /* select the output buffer set (1st or 2nd) */ + if( bp->hostOutputFrameCount[0] > 0 ) + { + hostOutputChannels = bp->hostOutputChannels[0]; + frameCount = PA_MIN_( bp->hostOutputFrameCount[0], maxFramesToCopy ); + } + else + { + hostOutputChannels = bp->hostOutputChannels[1]; + frameCount = PA_MIN_( bp->hostOutputFrameCount[1], maxFramesToCopy ); + } + + if( bp->userOutputIsInterleaved ) + { + srcBytePtr = ((unsigned char*)bp->tempOutputBuffer) + + bp->bytesPerUserOutputSample * bp->outputChannelCount * + (bp->framesPerUserBuffer - bp->framesInTempOutputBuffer); + + srcSampleStrideSamples = bp->outputChannelCount; + srcChannelStrideBytes = bp->bytesPerUserOutputSample; + } + else /* user output is not interleaved */ + { + srcBytePtr = ((unsigned char*)bp->tempOutputBuffer) + + bp->bytesPerUserOutputSample * + (bp->framesPerUserBuffer - bp->framesInTempOutputBuffer); + + srcSampleStrideSamples = 1; + srcChannelStrideBytes = bp->framesPerUserBuffer * bp->bytesPerUserOutputSample; + } + + for( i=0; ioutputChannelCount; ++i ) + { + assert( hostOutputChannels[i].data != NULL ); + bp->outputConverter( hostOutputChannels[i].data, + hostOutputChannels[i].stride, + srcBytePtr, srcSampleStrideSamples, + frameCount, &bp->ditherGenerator ); + + srcBytePtr += srcChannelStrideBytes; /* skip to next source channel */ + + /* advance dest ptr for next iteration */ + hostOutputChannels[i].data = ((unsigned char*)hostOutputChannels[i].data) + + frameCount * hostOutputChannels[i].stride * bp->bytesPerHostOutputSample; + } + + if( bp->hostOutputFrameCount[0] > 0 ) + bp->hostOutputFrameCount[0] -= frameCount; + else + bp->hostOutputFrameCount[1] -= frameCount; + + bp->framesInTempOutputBuffer -= frameCount; + } +} + +/* + AdaptingProcess is a full duplex adapting buffer processor. It converts + data from the temporary output buffer into the host output buffers, then + from the host input buffers into the temporary input buffers. Calling the + streamCallback when necessary. + When processPartialUserBuffers is 0, all available input data will be + consumed and all available output space will be filled. When + processPartialUserBuffers is non-zero, as many full user buffers + as possible will be processed, but partial buffers will not be consumed. +*/ +static unsigned long AdaptingProcess( PaUtilBufferProcessor *bp, + int *streamCallbackResult, int processPartialUserBuffers ) +{ + void *userInput, *userOutput; + unsigned long framesProcessed = 0; + unsigned long framesAvailable; + unsigned long endProcessingMinFrameCount; + unsigned long maxFramesToCopy; + PaUtilChannelDescriptor *hostInputChannels, *hostOutputChannels; + unsigned int frameCount; + unsigned char *destBytePtr; + unsigned int destSampleStrideSamples; /* stride from one sample to the next within a channel, in samples */ + unsigned int destChannelStrideBytes; /* stride from one channel to the next, in bytes */ + unsigned int i, j; + + + framesAvailable = bp->hostInputFrameCount[0] + bp->hostInputFrameCount[1];/* this is assumed to be the same as the output buffer's frame count */ + + if( processPartialUserBuffers ) + endProcessingMinFrameCount = 0; + else + endProcessingMinFrameCount = (bp->framesPerUserBuffer - 1); + + /* Fill host output with remaining frames in user output (tempOutputBuffer) */ + CopyTempOutputBuffersToHostOutputBuffers( bp ); + + while( framesAvailable > endProcessingMinFrameCount ) + { + + if( bp->framesInTempOutputBuffer == 0 && *streamCallbackResult != paContinue ) + { + /* the callback will not be called any more, so zero what remains + of the host output buffers */ + + for( i=0; i<2; ++i ) + { + frameCount = bp->hostOutputFrameCount[i]; + if( frameCount > 0 ) + { + hostOutputChannels = bp->hostOutputChannels[i]; + + for( j=0; joutputChannelCount; ++j ) + { + bp->outputZeroer( hostOutputChannels[j].data, + hostOutputChannels[j].stride, + frameCount ); + + /* advance dest ptr for next iteration */ + hostOutputChannels[j].data = ((unsigned char*)hostOutputChannels[j].data) + + frameCount * hostOutputChannels[j].stride * bp->bytesPerHostOutputSample; + } + bp->hostOutputFrameCount[i] = 0; + } + } + } + + + /* copy frames from host to user input buffers */ + while( bp->framesInTempInputBuffer < bp->framesPerUserBuffer && + ((bp->hostInputFrameCount[0] + bp->hostInputFrameCount[1]) > 0) ) + { + maxFramesToCopy = bp->framesPerUserBuffer - bp->framesInTempInputBuffer; + + /* select the input buffer set (1st or 2nd) */ + if( bp->hostInputFrameCount[0] > 0 ) + { + hostInputChannels = bp->hostInputChannels[0]; + frameCount = PA_MIN_( bp->hostInputFrameCount[0], maxFramesToCopy ); + } + else + { + hostInputChannels = bp->hostInputChannels[1]; + frameCount = PA_MIN_( bp->hostInputFrameCount[1], maxFramesToCopy ); + } + + /* configure conversion destination pointers */ + if( bp->userInputIsInterleaved ) + { + destBytePtr = ((unsigned char*)bp->tempInputBuffer) + + bp->bytesPerUserInputSample * bp->inputChannelCount * + bp->framesInTempInputBuffer; + + destSampleStrideSamples = bp->inputChannelCount; + destChannelStrideBytes = bp->bytesPerUserInputSample; + } + else /* user input is not interleaved */ + { + destBytePtr = ((unsigned char*)bp->tempInputBuffer) + + bp->bytesPerUserInputSample * bp->framesInTempInputBuffer; + + destSampleStrideSamples = 1; + destChannelStrideBytes = bp->framesPerUserBuffer * bp->bytesPerUserInputSample; + } + + for( i=0; iinputChannelCount; ++i ) + { + bp->inputConverter( destBytePtr, destSampleStrideSamples, + hostInputChannels[i].data, + hostInputChannels[i].stride, + frameCount, &bp->ditherGenerator ); + + destBytePtr += destChannelStrideBytes; /* skip to next destination channel */ + + /* advance src ptr for next iteration */ + hostInputChannels[i].data = ((unsigned char*)hostInputChannels[i].data) + + frameCount * hostInputChannels[i].stride * bp->bytesPerHostInputSample; + } + + if( bp->hostInputFrameCount[0] > 0 ) + bp->hostInputFrameCount[0] -= frameCount; + else + bp->hostInputFrameCount[1] -= frameCount; + + bp->framesInTempInputBuffer += frameCount; + + /* update framesAvailable and framesProcessed based on input consumed + unless something is very wrong this will also correspond to the + amount of output generated */ + framesAvailable -= frameCount; + framesProcessed += frameCount; + } + + /* call streamCallback */ + if( bp->framesInTempInputBuffer == bp->framesPerUserBuffer && + bp->framesInTempOutputBuffer == 0 ) + { + if( *streamCallbackResult == paContinue ) + { + /* setup userInput */ + if( bp->userInputIsInterleaved ) + { + userInput = bp->tempInputBuffer; + } + else /* user input is not interleaved */ + { + for( i = 0; i < bp->inputChannelCount; ++i ) + { + bp->tempInputBufferPtrs[i] = ((unsigned char*)bp->tempInputBuffer) + + i * bp->framesPerUserBuffer * bp->bytesPerUserInputSample; + } + + userInput = bp->tempInputBufferPtrs; + } + + /* setup userOutput */ + if( bp->userOutputIsInterleaved ) + { + userOutput = bp->tempOutputBuffer; + } + else /* user output is not interleaved */ + { + for( i = 0; i < bp->outputChannelCount; ++i ) + { + bp->tempOutputBufferPtrs[i] = ((unsigned char*)bp->tempOutputBuffer) + + i * bp->framesPerUserBuffer * bp->bytesPerUserOutputSample; + } + + userOutput = bp->tempOutputBufferPtrs; + } + + /* call streamCallback */ + + *streamCallbackResult = bp->streamCallback( userInput, userOutput, + bp->framesPerUserBuffer, bp->timeInfo, + bp->callbackStatusFlags, bp->userData ); + + bp->timeInfo->inputBufferAdcTime += bp->framesPerUserBuffer * bp->samplePeriod; + bp->timeInfo->outputBufferDacTime += bp->framesPerUserBuffer * bp->samplePeriod; + + bp->framesInTempInputBuffer = 0; + + if( *streamCallbackResult == paAbort ) + bp->framesInTempOutputBuffer = 0; + else + bp->framesInTempOutputBuffer = bp->framesPerUserBuffer; + } + else + { + /* paComplete or paAbort has already been called. */ + + bp->framesInTempInputBuffer = 0; + } + } + + /* copy frames from user (tempOutputBuffer) to host output buffers (hostOutputChannels) + Means to process the user output provided by the callback. Has to be called after + each callback. */ + CopyTempOutputBuffersToHostOutputBuffers( bp ); + + } + + return framesProcessed; +} + + +unsigned long PaUtil_EndBufferProcessing( PaUtilBufferProcessor* bp, int *streamCallbackResult ) +{ + unsigned long framesToProcess, framesToGo; + unsigned long framesProcessed = 0; + + if( bp->inputChannelCount != 0 && bp->outputChannelCount != 0 + && bp->hostInputChannels[0][0].data /* input was supplied (see PaUtil_SetNoInput) */ + && bp->hostOutputChannels[0][0].data /* output was supplied (see PaUtil_SetNoOutput) */ ) + { + assert( (bp->hostInputFrameCount[0] + bp->hostInputFrameCount[1]) == + (bp->hostOutputFrameCount[0] + bp->hostOutputFrameCount[1]) ); + } + + assert( *streamCallbackResult == paContinue + || *streamCallbackResult == paComplete + || *streamCallbackResult == paAbort ); /* don't forget to pass in a valid callback result value */ + + if( bp->useNonAdaptingProcess ) + { + if( bp->inputChannelCount != 0 && bp->outputChannelCount != 0 ) + { + /* full duplex non-adapting process, splice buffers if they are + different lengths */ + + framesToGo = bp->hostOutputFrameCount[0] + bp->hostOutputFrameCount[1]; /* relies on assert above for input/output equivalence */ + + do{ + unsigned long noInputInputFrameCount; + unsigned long *hostInputFrameCount; + PaUtilChannelDescriptor *hostInputChannels; + unsigned long noOutputOutputFrameCount; + unsigned long *hostOutputFrameCount; + PaUtilChannelDescriptor *hostOutputChannels; + unsigned long framesProcessedThisIteration; + + if( !bp->hostInputChannels[0][0].data ) + { + /* no input was supplied (see PaUtil_SetNoInput) + NonAdaptingProcess knows how to deal with this + */ + noInputInputFrameCount = framesToGo; + hostInputFrameCount = &noInputInputFrameCount; + hostInputChannels = 0; + } + else if( bp->hostInputFrameCount[0] != 0 ) + { + hostInputFrameCount = &bp->hostInputFrameCount[0]; + hostInputChannels = bp->hostInputChannels[0]; + } + else + { + hostInputFrameCount = &bp->hostInputFrameCount[1]; + hostInputChannels = bp->hostInputChannels[1]; + } + + if( !bp->hostOutputChannels[0][0].data ) + { + /* no output was supplied (see PaUtil_SetNoOutput) + NonAdaptingProcess knows how to deal with this + */ + noOutputOutputFrameCount = framesToGo; + hostOutputFrameCount = &noOutputOutputFrameCount; + hostOutputChannels = 0; + } + if( bp->hostOutputFrameCount[0] != 0 ) + { + hostOutputFrameCount = &bp->hostOutputFrameCount[0]; + hostOutputChannels = bp->hostOutputChannels[0]; + } + else + { + hostOutputFrameCount = &bp->hostOutputFrameCount[1]; + hostOutputChannels = bp->hostOutputChannels[1]; + } + + framesToProcess = PA_MIN_( *hostInputFrameCount, + *hostOutputFrameCount ); + + assert( framesToProcess != 0 ); + + framesProcessedThisIteration = NonAdaptingProcess( bp, streamCallbackResult, + hostInputChannels, hostOutputChannels, + framesToProcess ); + + *hostInputFrameCount -= framesProcessedThisIteration; + *hostOutputFrameCount -= framesProcessedThisIteration; + + framesProcessed += framesProcessedThisIteration; + framesToGo -= framesProcessedThisIteration; + + }while( framesToGo > 0 ); + } + else + { + /* half duplex non-adapting process, just process 1st and 2nd buffer */ + /* process first buffer */ + + framesToProcess = (bp->inputChannelCount != 0) + ? bp->hostInputFrameCount[0] + : bp->hostOutputFrameCount[0]; + + framesProcessed = NonAdaptingProcess( bp, streamCallbackResult, + bp->hostInputChannels[0], bp->hostOutputChannels[0], + framesToProcess ); + + /* process second buffer if provided */ + + framesToProcess = (bp->inputChannelCount != 0) + ? bp->hostInputFrameCount[1] + : bp->hostOutputFrameCount[1]; + if( framesToProcess > 0 ) + { + framesProcessed += NonAdaptingProcess( bp, streamCallbackResult, + bp->hostInputChannels[1], bp->hostOutputChannels[1], + framesToProcess ); + } + } + } + else /* block adaption necessary*/ + { + + if( bp->inputChannelCount != 0 && bp->outputChannelCount != 0 ) + { + /* full duplex */ + + if( bp->hostBufferSizeMode == paUtilVariableHostBufferSizePartialUsageAllowed ) + { + framesProcessed = AdaptingProcess( bp, streamCallbackResult, + 0 /* dont process partial user buffers */ ); + } + else + { + framesProcessed = AdaptingProcess( bp, streamCallbackResult, + 1 /* process partial user buffers */ ); + } + } + else if( bp->inputChannelCount != 0 ) + { + /* input only */ + framesToProcess = bp->hostInputFrameCount[0]; + + framesProcessed = AdaptingInputOnlyProcess( bp, streamCallbackResult, + bp->hostInputChannels[0], framesToProcess ); + + framesToProcess = bp->hostInputFrameCount[1]; + if( framesToProcess > 0 ) + { + framesProcessed += AdaptingInputOnlyProcess( bp, streamCallbackResult, + bp->hostInputChannels[1], framesToProcess ); + } + } + else + { + /* output only */ + framesToProcess = bp->hostOutputFrameCount[0]; + + framesProcessed = AdaptingOutputOnlyProcess( bp, streamCallbackResult, + bp->hostOutputChannels[0], framesToProcess ); + + framesToProcess = bp->hostOutputFrameCount[1]; + if( framesToProcess > 0 ) + { + framesProcessed += AdaptingOutputOnlyProcess( bp, streamCallbackResult, + bp->hostOutputChannels[1], framesToProcess ); + } + } + } + + return framesProcessed; +} + + +int PaUtil_IsBufferProcessorOutputEmpty( PaUtilBufferProcessor* bp ) +{ + return (bp->framesInTempOutputBuffer) ? 0 : 1; +} + + +unsigned long PaUtil_CopyInput( PaUtilBufferProcessor* bp, + void **buffer, unsigned long frameCount ) +{ + PaUtilChannelDescriptor *hostInputChannels; + unsigned int framesToCopy; + unsigned char *destBytePtr; + void **nonInterleavedDestPtrs; + unsigned int destSampleStrideSamples; /* stride from one sample to the next within a channel, in samples */ + unsigned int destChannelStrideBytes; /* stride from one channel to the next, in bytes */ + unsigned int i; + + hostInputChannels = bp->hostInputChannels[0]; + framesToCopy = PA_MIN_( bp->hostInputFrameCount[0], frameCount ); + + if( bp->userInputIsInterleaved ) + { + destBytePtr = (unsigned char*)*buffer; + + destSampleStrideSamples = bp->inputChannelCount; + destChannelStrideBytes = bp->bytesPerUserInputSample; + + for( i=0; iinputChannelCount; ++i ) + { + bp->inputConverter( destBytePtr, destSampleStrideSamples, + hostInputChannels[i].data, + hostInputChannels[i].stride, + framesToCopy, &bp->ditherGenerator ); + + destBytePtr += destChannelStrideBytes; /* skip to next source channel */ + + /* advance dest ptr for next iteration */ + hostInputChannels[i].data = ((unsigned char*)hostInputChannels[i].data) + + framesToCopy * hostInputChannels[i].stride * bp->bytesPerHostInputSample; + } + + /* advance callers dest pointer (buffer) */ + *buffer = ((unsigned char *)*buffer) + + framesToCopy * bp->inputChannelCount * bp->bytesPerUserInputSample; + } + else + { + /* user input is not interleaved */ + + nonInterleavedDestPtrs = (void**)*buffer; + + destSampleStrideSamples = 1; + + for( i=0; iinputChannelCount; ++i ) + { + destBytePtr = (unsigned char*)nonInterleavedDestPtrs[i]; + + bp->inputConverter( destBytePtr, destSampleStrideSamples, + hostInputChannels[i].data, + hostInputChannels[i].stride, + framesToCopy, &bp->ditherGenerator ); + + /* advance callers dest pointer (nonInterleavedDestPtrs[i]) */ + destBytePtr += bp->bytesPerUserInputSample * framesToCopy; + nonInterleavedDestPtrs[i] = destBytePtr; + + /* advance dest ptr for next iteration */ + hostInputChannels[i].data = ((unsigned char*)hostInputChannels[i].data) + + framesToCopy * hostInputChannels[i].stride * bp->bytesPerHostInputSample; + } + } + + bp->hostInputFrameCount[0] -= framesToCopy; + + return framesToCopy; +} + +unsigned long PaUtil_CopyOutput( PaUtilBufferProcessor* bp, + const void ** buffer, unsigned long frameCount ) +{ + PaUtilChannelDescriptor *hostOutputChannels; + unsigned int framesToCopy; + unsigned char *srcBytePtr; + void **nonInterleavedSrcPtrs; + unsigned int srcSampleStrideSamples; /* stride from one sample to the next within a channel, in samples */ + unsigned int srcChannelStrideBytes; /* stride from one channel to the next, in bytes */ + unsigned int i; + + hostOutputChannels = bp->hostOutputChannels[0]; + framesToCopy = PA_MIN_( bp->hostOutputFrameCount[0], frameCount ); + + if( bp->userOutputIsInterleaved ) + { + srcBytePtr = (unsigned char*)*buffer; + + srcSampleStrideSamples = bp->outputChannelCount; + srcChannelStrideBytes = bp->bytesPerUserOutputSample; + + for( i=0; ioutputChannelCount; ++i ) + { + bp->outputConverter( hostOutputChannels[i].data, + hostOutputChannels[i].stride, + srcBytePtr, srcSampleStrideSamples, + framesToCopy, &bp->ditherGenerator ); + + srcBytePtr += srcChannelStrideBytes; /* skip to next source channel */ + + /* advance dest ptr for next iteration */ + hostOutputChannels[i].data = ((unsigned char*)hostOutputChannels[i].data) + + framesToCopy * hostOutputChannels[i].stride * bp->bytesPerHostOutputSample; + } + + /* advance callers source pointer (buffer) */ + *buffer = ((unsigned char *)*buffer) + + framesToCopy * bp->outputChannelCount * bp->bytesPerUserOutputSample; + + } + else + { + /* user output is not interleaved */ + + nonInterleavedSrcPtrs = (void**)*buffer; + + srcSampleStrideSamples = 1; + + for( i=0; ioutputChannelCount; ++i ) + { + srcBytePtr = (unsigned char*)nonInterleavedSrcPtrs[i]; + + bp->outputConverter( hostOutputChannels[i].data, + hostOutputChannels[i].stride, + srcBytePtr, srcSampleStrideSamples, + framesToCopy, &bp->ditherGenerator ); + + + /* advance callers source pointer (nonInterleavedSrcPtrs[i]) */ + srcBytePtr += bp->bytesPerUserOutputSample * framesToCopy; + nonInterleavedSrcPtrs[i] = srcBytePtr; + + /* advance dest ptr for next iteration */ + hostOutputChannels[i].data = ((unsigned char*)hostOutputChannels[i].data) + + framesToCopy * hostOutputChannels[i].stride * bp->bytesPerHostOutputSample; + } + } + + bp->hostOutputFrameCount[0] += framesToCopy; + + return framesToCopy; +} + + +unsigned long PaUtil_ZeroOutput( PaUtilBufferProcessor* bp, unsigned long frameCount ) +{ + PaUtilChannelDescriptor *hostOutputChannels; + unsigned int framesToZero; + unsigned int i; + + hostOutputChannels = bp->hostOutputChannels[0]; + framesToZero = PA_MIN_( bp->hostOutputFrameCount[0], frameCount ); + + for( i=0; ioutputChannelCount; ++i ) + { + bp->outputZeroer( hostOutputChannels[i].data, + hostOutputChannels[i].stride, + framesToZero ); + + + /* advance dest ptr for next iteration */ + hostOutputChannels[i].data = ((unsigned char*)hostOutputChannels[i].data) + + framesToZero * hostOutputChannels[i].stride * bp->bytesPerHostOutputSample; + } + + bp->hostOutputFrameCount[0] += framesToZero; + + return framesToZero; +} diff --git a/pa_common/pa_process.h b/pa_common/pa_process.h new file mode 100644 index 0000000..8d13d90 --- /dev/null +++ b/pa_common/pa_process.h @@ -0,0 +1,741 @@ +#ifndef PA_PROCESS_H +#define PA_PROCESS_H +/* + * $Id$ + * Portable Audio I/O Library callback buffer processing adapters + * + * Based on the Open Source API proposed by Ross Bencina + * Copyright (c) 1999-2002 Phil Burk, 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. + * + * 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. + */ + +/** @file + @brief Buffer Processor prototypes. A Buffer Processor performs buffer length + adaption, coordinates sample format conversion, and interleaves/deinterleaves + channels. + +

Overview

+ + The "Buffer Processor" (PaUtilBufferProcessor) manages conversion of audio + data from host buffers to user buffers and back again. Where required, the + buffer processor takes care of converting between host and user sample formats, + interleaving and deinterleaving multichannel buffers, and adapting between host + and user buffers with different lengths. The buffer processor may be used with + full and half duplex streams, for both callback streams and blocking read/write + streams. + + One of the important capabilities provided by the buffer processor is + the ability to adapt between user and host buffer sizes of different lengths + with minimum latency. Although this task is relatively easy to perform when + the host buffer size is an integer multiple of the user buffer size, the + problem is more complicated when this is not the case - especially for + full-duplex callback streams. Where necessary the adaption is implemented by + internally buffering some input and/or output data. The buffer adation + algorithm used by the buffer processor was originally implemented by + Stephan Letz for the ASIO version of PortAudio, and is described in his + Callback_adaption_.pdf which is included in the distribution. + + The buffer processor performs sample conversion using the functions provided + by pa_converters.c. + + The following sections provide an overview of how to use the buffer processor. + Interested readers are advised to consult the host API implementations for + examples of buffer processor usage. + + +

Initialization, resetting and termination

+ + When a stream is opened, the buffer processor should be initialized using + PaUtil_InitializeBufferProcessor. This function initializes internal state + and allocates temporary buffers as neccesary according to the supplied + configuration parameters. Some of the parameters correspond to those requested + by the user in their call to Pa_OpenStream(), others reflect the requirements + of the host API implementation - they indicate host buffer sizes, formats, + and the type of buffering which the Host API uses. The buffer processor should + be initialized for callback streams and blocking read/write streams. + + Call PaUtil_ResetBufferProcessor to clear any sample data which is present + in the buffer processor before starting to use it (for example when + Pa_StartStream is called). + + When the buffer processor is no longer used call + PaUtil_TerminateBufferProcessor. + + +

Using the buffer processor for a callback stream

+ + The buffer processor's role in a callback stream is to take host input buffers + process them with the stream callback, and fill host output buffers. For a + full duplex stream, the buffer processor handles input and output simultaneously + due to the requirements of the minimum-latency buffer adation algorithm. + + When a host buffer becomes available, the implementation should call + the buffer processor to process the buffer. The buffer processor calls the + stream callback to consume and/or produce audio data as necessary. The buffer + processor will convert sample formats, interleave/deinterleave channels, + and slice or chunk the data to the appropriate buffer lengths according to + the requirements of the stream callback and the host API. + + To process a host buffer (or a pair of host buffers for a full-duplex stream) + use the following calling sequence: + + -# Call PaUtil_BeginBufferProcessing + -# For a stream which takes input: + - Call PaUtil_SetInputFrameCount with the number of frames in the host input + buffer. + - Call one of the following functions one or more times to tell the + buffer processor about the host input buffer(s): PaUtil_SetInputChannel, + PaUtil_SetInterleavedInputChannels, PaUtil_SetNonInterleavedInputChannel. + Which function you call will depend on whether the host buffer(s) are + interleaved or not. + - If the available host data is split accross two buffers (for example a + data range at the end of a circular buffer and another range at the + beginning of the circular buffer), also call + PaUtil_Set2ndInputFrameCount, PaUtil_Set2ndInputChannel, + PaUtil_Set2ndInterleavedInputChannels, + PaUtil_Set2ndNonInterleavedInputChannel as necessary to tell the buffer + processor about the second buffer. + -# For a stream which generates output: + - Call PaUtil_SetOutputFrameCount with the number of frames in the host + output buffer. + - Call one of the following functions one or more times to tell the + buffer processor about the host output buffer(s): PaUtil_SetOutputChannel, + PaUtil_SetInterleavedOutputChannels, PaUtil_SetNonInterleavedOutputChannel. + Which function you call will depend on whether the host buffer(s) are + interleaved or not. + - If the available host output buffer space is split accross two buffers + (for example a data range at the end of a circular buffer and another + range at the beginning of the circular buffer), call + PaUtil_Set2ndOutputFrameCount, PaUtil_Set2ndOutputChannel, + PaUtil_Set2ndInterleavedOutputChannels, + PaUtil_Set2ndNonInterleavedOutputChannel as necessary to tell the buffer + processor about the second buffer. + -# Call PaUtil_EndBufferProcessing, this function performs the actual data + conversion and processing. + + +

Using the buffer processor for a blocking read/write stream

+ + Blocking read/write streams use the buffer processor to convert and copy user + output data to a host buffer, and to convert and copy host input data to + the user's buffer. The buffer processor does not perform any buffer adaption. + When using the buffer processor in a blocking read/write stream the input and + output conversion are performed separately by the PaUtil_CopyInput and + PaUtil_CopyOutput functions. + + To copy data from a host input buffer to the buffer(s) which the user supplies + to Pa_ReadStream, use the following calling sequence. + + - Repeat the following three steps until the user buffer(s) have been filled + with samples from the host input buffers: + -# Call PaUtil_SetInputFrameCount with the number of frames in the host + input buffer. + -# Call one of the following functions one or more times to tell the + buffer processor about the host input buffer(s): PaUtil_SetInputChannel, + PaUtil_SetInterleavedInputChannels, PaUtil_SetNonInterleavedInputChannel. + Which function you call will depend on whether the host buffer(s) are + interleaved or not. + -# Call PaUtil_CopyInput with the user buffer pointer (or a copy of the + array of buffer pointers for a non-interleaved stream) passed to + Pa_ReadStream, along with the number of frames in the user buffer(s). + Be careful to pass a copy of the user buffer pointers to + PaUtil_CopyInput because PaUtil_CopyInput advances the pointers to + the start of the next region to copy. + - PaUtil_CopyInput will not copy more data than is available in the + host buffer(s), so the above steps need to be repeated until the user + buffer(s) are full. + + + To copy data to the host output buffer from the user buffers(s) supplied + to Pa_WriteStream use the following calling sequence. + + - Repeat the following three steps until all frames from the user buffer(s) + have been copied to the host API: + -# Call PaUtil_SetOutputFrameCount with the number of frames in the host + output buffer. + -# Call one of the following functions one or more times to tell the + buffer processor about the host output buffer(s): PaUtil_SetOutputChannel, + PaUtil_SetInterleavedOutputChannels, PaUtil_SetNonInterleavedOutputChannel. + Which function you call will depend on whether the host buffer(s) are + interleaved or not. + -# Call PaUtil_CopyOutput with the user buffer pointer (or a copy of the + array of buffer pointers for a non-interleaved stream) passed to + Pa_WriteStream, along with the number of frames in the user buffer(s). + Be careful to pass a copy of the user buffer pointers to + PaUtil_CopyOutput because PaUtil_CopyOutput advances the pointers to + the start of the next region to copy. + - PaUtil_CopyOutput will not copy more data than fits in the host buffer(s), + so the above steps need to be repeated until all user data is copied. +*/ + + +#include "portaudio.h" +#include "pa_converters.h" +#include "pa_dither.h" + +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + + +/** @brief Mode flag passed to PaUtil_InitializeBufferProcessor indicating the type + of buffering that the host API uses. + + The mode used depends on whether the host API or the implementation manages + the buffers, and how these buffers are used (scatter gather, circular buffer). +*/ +typedef enum { +/** The host buffer size is a fixed known size. */ + paUtilFixedHostBufferSize, + +/** The host buffer size may vary, but has a known maximum size. */ + paUtilBoundedHostBufferSize, + +/** Nothing is known about the host buffer size. */ + paUtilUnknownHostBufferSize, + +/** The host buffer size varies, and the client does not require the buffer + processor to consume all of the input and fill all of the output buffer. This + is useful when the implementation has access to the host API's circular buffer + and only needs to consume/fill some of it, not necessarily all of it, with each + call to the buffer processor. This is the only mode where + PaUtil_EndBufferProcessing() may not consume the whole buffer. +*/ + paUtilVariableHostBufferSizePartialUsageAllowed +}PaUtilHostBufferSizeMode; + + +/** @brief An auxilliary data structure used internally by the buffer processor + to represent host input and output buffers. */ +typedef struct PaUtilChannelDescriptor{ + void *data; + unsigned int stride; /**< stride in samples, not bytes */ +}PaUtilChannelDescriptor; + + +/** @brief The main buffer processor data structure. + + Allocate one of these, initialize it with PaUtil_InitializeBufferProcessor + and terminate it with PaUtil_TerminateBufferProcessor. +*/ +typedef struct { + unsigned long framesPerUserBuffer; + unsigned long framesPerHostBuffer; + + PaUtilHostBufferSizeMode hostBufferSizeMode; + int useNonAdaptingProcess; + unsigned long framesPerTempBuffer; + + unsigned int inputChannelCount; + unsigned int bytesPerHostInputSample; + unsigned int bytesPerUserInputSample; + int userInputIsInterleaved; + PaUtilConverter *inputConverter; + PaUtilZeroer *inputZeroer; + + unsigned int outputChannelCount; + unsigned int bytesPerHostOutputSample; + unsigned int bytesPerUserOutputSample; + int userOutputIsInterleaved; + PaUtilConverter *outputConverter; + PaUtilZeroer *outputZeroer; + + unsigned long initialFramesInTempInputBuffer; + unsigned long initialFramesInTempOutputBuffer; + + void *tempInputBuffer; /**< used for slips, block adaption, and conversion. */ + void **tempInputBufferPtrs; /**< storage for non-interleaved buffer pointers, NULL for interleaved user input */ + unsigned long framesInTempInputBuffer; /**< frames remaining in input buffer from previous adaption iteration */ + + void *tempOutputBuffer; /**< used for slips, block adaption, and conversion. */ + void **tempOutputBufferPtrs; /**< storage for non-interleaved buffer pointers, NULL for interleaved user output */ + unsigned long framesInTempOutputBuffer; /**< frames remaining in input buffer from previous adaption iteration */ + + PaStreamCallbackTimeInfo *timeInfo; + + PaStreamCallbackFlags callbackStatusFlags; + + unsigned long hostInputFrameCount[2]; + PaUtilChannelDescriptor *hostInputChannels[2]; /**< pointers to arrays of channel descriptors. + pointers are NULL for half-duplex output processing. + hostInputChannels[i].data is NULL when the caller + calls PaUtil_SetNoInput() + */ + unsigned long hostOutputFrameCount[2]; + PaUtilChannelDescriptor *hostOutputChannels[2]; /**< pointers to arrays of channel descriptors. + pointers are NULL for half-duplex input processing. + hostOutputChannels[i].data is NULL when the caller + calls PaUtil_SetNoOutput() + */ + + PaUtilTriangularDitherGenerator ditherGenerator; + + double samplePeriod; + + PaStreamCallback *streamCallback; + void *userData; +} PaUtilBufferProcessor; + + +/** @name Initialization, termination, resetting and info */ +/*@{*/ + +/** Initialize a buffer processor's representation stored in a + PaUtilBufferProcessor structure. Be sure to call + PaUtil_TerminateBufferProcessor after finishing with a buffer processor. + + @param bufferProcessor The buffer processor structure to initialize. + + @param inputChannelCount The number of input channels as passed to + Pa_OpenStream or 0 for an output-only stream. + + @param userInputSampleFormat Format of user input samples, as passed to + Pa_OpenStream. This parameter is ignored for ouput-only streams. + + @param hostInputSampleFormat Format of host input samples. This parameter is + ignored for output-only streams. See note about host buffer interleave below. + + @param outputChannelCount The number of output channels as passed to + Pa_OpenStream or 0 for an input-only stream. + + @param userOutputSampleFormat Format of user output samples, as passed to + Pa_OpenStream. This parameter is ignored for input-only streams. + + @param hostOutputSampleFormat Format of host output samples. This parameter is + ignored for input-only streams. See note about host buffer interleave below. + + @param sampleRate Sample rate of the stream. The more accurate this is the + better - it is used for updating time stamps when adapting buffers. + + @param streamFlags Stream flags as passed to Pa_OpenStream, this parameter is + used for selecting special sample conversion options such as clipping and + dithering. + + @param framesPerUserBuffer Number of frames per user buffer, as requested + by the framesPerBuffer parameter to Pa_OpenStream. This parameter may be + zero to indicate that the user will accept any (and varying) buffer sizes. + + @param framesPerHostBuffer Specifies the number of frames per host buffer + for the fixed buffer size mode, and the maximum number of frames + per host buffer for the bounded host buffer size mode. It is ignored for + the other modes. + + @param hostBufferSizeMode A mode flag indicating the size variability of + host buffers that will be passed to the buffer processor. See + PaUtilHostBufferSizeMode for further details. + + @param streamCallback The user stream callback passed to Pa_OpenStream. + + @param userData The user data field passed to Pa_OpenStream. + + @note The interleave flag is ignored for host buffer formats. Host + interleave is determined by the use of different SetInput and SetOutput + functions. + + @return An error code indicating whether the initialization was successful. + If the error code is not PaNoError, the buffer processor was not initialized + and should not be used. + + @see Pa_OpenStream, PaUtilHostBufferSizeMode, PaUtil_TerminateBufferProcessor +*/ +PaError PaUtil_InitializeBufferProcessor( PaUtilBufferProcessor* bufferProcessor, + int inputChannelCount, PaSampleFormat userInputSampleFormat, + PaSampleFormat hostInputSampleFormat, + int outputChannelCount, PaSampleFormat userOutputSampleFormat, + PaSampleFormat hostOutputSampleFormat, + double sampleRate, + PaStreamFlags streamFlags, + unsigned long framesPerUserBuffer, /* 0 indicates don't care */ + unsigned long framesPerHostBuffer, + PaUtilHostBufferSizeMode hostBufferSizeMode, + PaStreamCallback *streamCallback, void *userData ); + + +/** Terminate a buffer processor's representation. Deallocates any temporary + buffers allocated by PaUtil_InitializeBufferProcessor. + + @param bufferProcessor The buffer processor structure to terminate. + + @see PaUtil_InitializeBufferProcessor. +*/ +void PaUtil_TerminateBufferProcessor( PaUtilBufferProcessor* bufferProcessor ); + + +/** Clear any internally buffered data. If you call + PaUtil_InitializeBufferProcessor in your OpenStream routine, make sure you + call PaUtil_ResetBufferProcessor in your StartStream call. + + @param bufferProcessor The buffer processor to reset. +*/ +void PaUtil_ResetBufferProcessor( PaUtilBufferProcessor* bufferProcessor ); + + +/** Retrieve the input latency of a buffer processor. + + @param bufferProcessor The buffer processor examine. + + @return The input latency introduced by the buffer processor, in frames. + + @see PaUtil_GetBufferProcessorOutputLatency +*/ +unsigned long PaUtil_GetBufferProcessorInputLatency( PaUtilBufferProcessor* bufferProcessor ); + +/** Retrieve the output latency of a buffer processor. + + @param bufferProcessor The buffer processor examine. + + @return The output latency introduced by the buffer processor, in frames. + + @see PaUtil_GetBufferProcessorInputLatency +*/ +unsigned long PaUtil_GetBufferProcessorOutputLatency( PaUtilBufferProcessor* bufferProcessor ); + +/*@}*/ + + +/** @name Host buffer pointer configuration + + Functions to set host input and output buffers, used by both callback streams + and blocking read/write streams. +*/ +/*@{*/ + + +/** Set the number of frames in the input host buffer(s) specified by the + PaUtil_Set*InputChannel functions. + + @param bufferProcessor The buffer processor. + + @param frameCount The number of host input frames. A 0 frameCount indicates to + use the framesPerHostBuffer value passed to PaUtil_InitializeBufferProcessor. + + @see PaUtil_SetNoInput, PaUtil_SetInputChannel, + PaUtil_SetInterleavedInputChannels, PaUtil_SetNonInterleavedInputChannel +*/ +void PaUtil_SetInputFrameCount( PaUtilBufferProcessor* bufferProcessor, + unsigned long frameCount ); + + +/** Indicate that no input is avalable. This function should be used when + priming the output of a full-duplex stream opened with the + paPrimeOutputBuffersUsingStreamCallback flag. Note that it is not necessary + to call this or any othe PaUtil_Set*Input* functions for ouput-only streams. + + @param bufferProcessor The buffer processor. +*/ +void PaUtil_SetNoInput( PaUtilBufferProcessor* bufferProcessor ); + + +/** Provide the buffer processor with a pointer to a host input channel. + + @param bufferProcessor The buffer processor. + @param channel The channel number. + @param data The buffer. + @param stride The stride from one sample to the next, in samples. For + interleaved host buffers, the stride will usually be the same as the number of + channels in the buffer. +*/ +void PaUtil_SetInputChannel( PaUtilBufferProcessor* bufferProcessor, + unsigned int channel, void *data, unsigned int stride ); + + +/** Provide the buffer processor with a pointer to an number of interleaved + host input channels. + + @param bufferProcessor The buffer processor. + @param firstChannel The first channel number. + @param data The buffer. + @param channelCount The number of interleaved channels in the buffer. If + channelCount is zero, the number of channels specified to + PaUtil_InitializeBufferProcessor will be used. +*/ +void PaUtil_SetInterleavedInputChannels( PaUtilBufferProcessor* bufferProcessor, + unsigned int firstChannel, void *data, unsigned int channelCount ); + + +/** Provide the buffer processor with a pointer to one non-interleaved host + output channel. + + @param bufferProcessor The buffer processor. + @param channel The channel number. + @param data The buffer. +*/ +void PaUtil_SetNonInterleavedInputChannel( PaUtilBufferProcessor* bufferProcessor, + unsigned int channel, void *data ); + + +/** Use for the second buffer half when the input buffer is split in two halves. + @see PaUtil_SetInputFrameCount +*/ +void PaUtil_Set2ndInputFrameCount( PaUtilBufferProcessor* bufferProcessor, + unsigned long frameCount ); + +/** Use for the second buffer half when the input buffer is split in two halves. + @see PaUtil_SetInputChannel +*/ +void PaUtil_Set2ndInputChannel( PaUtilBufferProcessor* bufferProcessor, + unsigned int channel, void *data, unsigned int stride ); + +/** Use for the second buffer half when the input buffer is split in two halves. + @see PaUtil_SetInterleavedInputChannels +*/ +void PaUtil_Set2ndInterleavedInputChannels( PaUtilBufferProcessor* bufferProcessor, + unsigned int firstChannel, void *data, unsigned int channelCount ); + +/** Use for the second buffer half when the input buffer is split in two halves. + @see PaUtil_SetNonInterleavedInputChannel +*/ +void PaUtil_Set2ndNonInterleavedInputChannel( PaUtilBufferProcessor* bufferProcessor, + unsigned int channel, void *data ); + + +/** Set the number of frames in the output host buffer(s) specified by the + PaUtil_Set*OutputChannel functions. + + @param bufferProcessor The buffer processor. + + @param frameCount The number of host output frames. A 0 frameCount indicates to + use the framesPerHostBuffer value passed to PaUtil_InitializeBufferProcessor. + + @see PaUtil_SetOutputChannel, PaUtil_SetInterleavedOutputChannels, + PaUtil_SetNonInterleavedOutputChannel +*/ +void PaUtil_SetOutputFrameCount( PaUtilBufferProcessor* bufferProcessor, + unsigned long frameCount ); + + +/** Indicate that the output will be discarded. This function should be used + when implementing the paNeverDropInput mode for full duplex streams. + + @param bufferProcessor The buffer processor. +*/ +void PaUtil_SetNoOutput( PaUtilBufferProcessor* bufferProcessor ); + + +/** Provide the buffer processor with a pointer to a host output channel. + + @param bufferProcessor The buffer processor. + @param channel The channel number. + @param data The buffer. + @param stride The stride from one sample to the next, in samples. For + interleaved host buffers, the stride will usually be the same as the number of + channels in the buffer. +*/ +void PaUtil_SetOutputChannel( PaUtilBufferProcessor* bufferProcessor, + unsigned int channel, void *data, unsigned int stride ); + + +/** Provide the buffer processor with a pointer to a number of interleaved + host output channels. + + @param bufferProcessor The buffer processor. + @param firstChannel The first channel number. + @param data The buffer. + @param channelCount The number of interleaved channels in the buffer. If + channelCount is zero, the number of channels specified to + PaUtil_InitializeBufferProcessor will be used. +*/ +void PaUtil_SetInterleavedOutputChannels( PaUtilBufferProcessor* bufferProcessor, + unsigned int firstChannel, void *data, unsigned int channelCount ); + + +/** Provide the buffer processor with a pointer to one non-interleaved host + output channel. + + @param bufferProcessor The buffer processor. + @param channel The channel number. + @param data The buffer. +*/ +void PaUtil_SetNonInterleavedOutputChannel( PaUtilBufferProcessor* bufferProcessor, + unsigned int channel, void *data ); + + +/** Use for the second buffer half when the output buffer is split in two halves. + @see PaUtil_SetOutputFrameCount +*/ +void PaUtil_Set2ndOutputFrameCount( PaUtilBufferProcessor* bufferProcessor, + unsigned long frameCount ); + +/** Use for the second buffer half when the output buffer is split in two halves. + @see PaUtil_SetOutputChannel +*/ +void PaUtil_Set2ndOutputChannel( PaUtilBufferProcessor* bufferProcessor, + unsigned int channel, void *data, unsigned int stride ); + +/** Use for the second buffer half when the output buffer is split in two halves. + @see PaUtil_SetInterleavedOutputChannels +*/ +void PaUtil_Set2ndInterleavedOutputChannels( PaUtilBufferProcessor* bufferProcessor, + unsigned int firstChannel, void *data, unsigned int channelCount ); + +/** Use for the second buffer half when the output buffer is split in two halves. + @see PaUtil_SetNonInterleavedOutputChannel +*/ +void PaUtil_Set2ndNonInterleavedOutputChannel( PaUtilBufferProcessor* bufferProcessor, + unsigned int channel, void *data ); + +/*@}*/ + + +/** @name Buffer processing functions for callback streams +*/ +/*@{*/ + +/** Commence processing a host buffer (or a pair of host buffers in the + full-duplex case) for a callback stream. + + @param bufferProcessor The buffer processor. + + @param timeInfo Timing information for the first sample of the host + buffer(s). This information may be adjusted when buffer adaption is being + performed. + + @param callbackStatusFlags Flags indicating whether underruns and overruns + have occurred since the last time the buffer processor was called. +*/ +void PaUtil_BeginBufferProcessing( PaUtilBufferProcessor* bufferProcessor, + PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags callbackStatusFlags ); + + +/** Finish processing a host buffer (or a pair of host buffers in the + full-duplex case) for a callback stream. + + @param bufferProcessor The buffer processor. + + @param callbackResult On input, indicates a previous callback result, and on + exit, the result of the user stream callback, if it is called. + On entry callbackResult should contain one of { paContinue, paComplete, or + paAbort}. If paComplete is passed, the stream callback will not be called + but any audio that was generated by previous stream callbacks will be copied + to the output buffer(s). You can check whether the buffer processor's internal + buffer is empty by calling PaUtil_IsBufferProcessorOutputEmpty. + + If the stream callback is called its result is stored in *callbackResult. If + the stream callback returns paComplete or paAbort, all output buffers will be + full of valid data - some of which may be zeros to acount for data that + wasn't generated by the terminating callback. + + @return The number of frames processed. This usually corresponds to the + number of frames specified by the PaUtil_Set*FrameCount functions, exept in + the paUtilVariableHostBufferSizePartialUsageAllowed buffer size mode when a + smaller value may be returned. +*/ +unsigned long PaUtil_EndBufferProcessing( PaUtilBufferProcessor* bufferProcessor, + int *callbackResult ); + + +/** Determine whether any callback generated output remains in the bufffer + processor's internal buffers. This method may be used to determine when to + continue calling PaUtil_EndBufferProcessing() after the callback has returned + a callbackResult of paComplete. + + @param bufferProcessor The buffer processor. + + @return Returns non-zero when callback generated output remains in the internal + buffer and zero (0) when there internal buffer contains no callback generated + data. +*/ +int PaUtil_IsBufferProcessorOutputEmpty( PaUtilBufferProcessor* bufferProcessor ); + +/*@}*/ + + +/** @name Buffer processing functions for blocking read/write streams +*/ +/*@{*/ + +/** Copy samples from host input channels set up by the PaUtil_Set*InputChannels + functions to a user supplied buffer. This function is intended for use with + blocking read/write streams. Copies the minimum of the number of + user frames (specified by the frameCount parameter) and the number of available + host frames (specified in a previous call to SetInputFrameCount()). + + @param bufferProcessor The buffer processor. + + @param buffer A pointer to the user buffer pointer, or a pointer to a pointer + to an array of user buffer pointers for a non-interleaved stream. It is + important that this parameter points to a copy of the user buffer pointers, + not to the actual user buffer pointers, because this function updates the + pointers before returning. + + @param frameCount The number of frames of data in the buffer(s) pointed to by + the buffer parameter. + + @return The number of frames copied. The buffer pointer(s) pointed to by the + buffer parameter are advanced to point to the frame(s) following the last one + filled. +*/ +unsigned long PaUtil_CopyInput( PaUtilBufferProcessor* bufferProcessor, + void **buffer, unsigned long frameCount ); + + +/* Copy samples from a user supplied buffer to host output channels set up by + the PaUtil_Set*OutputChannels functions. This function is intended for use with + blocking read/write streams. Copies the minimum of the number of + user frames (specified by the frameCount parameter) and the number of + host frames (specified in a previous call to SetOutputFrameCount()). + + @param bufferProcessor The buffer processor. + + @param buffer A pointer to the user buffer pointer, or a pointer to a pointer + to an array of user buffer pointers for a non-interleaved stream. It is + important that this parameter points to a copy of the user buffer pointers, + not to the actual user buffer pointers, because this function updates the + pointers before returning. + + @param frameCount The number of frames of data in the buffer(s) pointed to by + the buffer parameter. + + @return The number of frames copied. The buffer pointer(s) pointed to by the + buffer parameter are advanced to point to the frame(s) following the last one + copied. +*/ +unsigned long PaUtil_CopyOutput( PaUtilBufferProcessor* bufferProcessor, + const void ** buffer, unsigned long frameCount ); + + +/* Zero samples in host output channels set up by the PaUtil_Set*OutputChannels + functions. This function is useful for flushing streams. + Zeros the minimum of frameCount and the number of host frames specified in a + previous call to SetOutputFrameCount(). + + @param bufferProcessor The buffer processor. + + @param frameCount The maximum number of frames to zero. + + @return The number of frames zeroed. +*/ +unsigned long PaUtil_ZeroOutput( PaUtilBufferProcessor* bufferProcessor, + unsigned long frameCount ); + + +/*@}*/ + + +#ifdef __cplusplus +} +#endif /* __cplusplus */ +#endif /* PA_PROCESS_H */ diff --git a/pa_common/pa_skeleton.c b/pa_common/pa_skeleton.c new file mode 100644 index 0000000..51f95c8 --- /dev/null +++ b/pa_common/pa_skeleton.c @@ -0,0 +1,807 @@ +/* + * $Id$ + * Portable Audio I/O Library skeleton implementation + * demonstrates how to use the common functions to implement support + * for a host API + * + * 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. + * + * 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. + */ + +/** @file + @brief Skeleton implementation of support for a host API. + + @note This file is provided as a starting point for implementing support for + a new host API. IMPLEMENT ME comments are used to indicate functionality + which much be customised for each implementation. +*/ + + +#include /* strlen() */ + +#include "pa_util.h" +#include "pa_allocation.h" +#include "pa_hostapi.h" +#include "pa_stream.h" +#include "pa_cpuload.h" +#include "pa_process.h" + + +/* prototypes for functions declared in this file */ + +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +PaError PaSkeleton_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 ) + +/* PaSkeletonHostApiRepresentation - host api datastructure specific to this implementation */ + +typedef struct +{ + PaUtilHostApiRepresentation inheritedHostApiRep; + PaUtilStreamInterface callbackStreamInterface; + PaUtilStreamInterface blockingStreamInterface; + + PaUtilAllocationGroup *allocations; + + /* implementation specific data goes here */ +} +PaSkeletonHostApiRepresentation; /* IMPLEMENT ME: rename this */ + + +PaError PaSkeleton_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex ) +{ + PaError result = paNoError; + int i, deviceCount; + PaSkeletonHostApiRepresentation *skeletonHostApi; + PaDeviceInfo *deviceInfoArray; + + skeletonHostApi = (PaSkeletonHostApiRepresentation*)PaUtil_AllocateMemory( sizeof(PaSkeletonHostApiRepresentation) ); + if( !skeletonHostApi ) + { + result = paInsufficientMemory; + goto error; + } + + skeletonHostApi->allocations = PaUtil_CreateAllocationGroup(); + if( !skeletonHostApi->allocations ) + { + result = paInsufficientMemory; + goto error; + } + + *hostApi = &skeletonHostApi->inheritedHostApiRep; + (*hostApi)->info.structVersion = 1; + (*hostApi)->info.type = paInDevelopment; /* IMPLEMENT ME: change to correct type id */ + (*hostApi)->info.name = "skeleton implementation"; /* IMPLEMENT ME: change to correct name */ + + (*hostApi)->info.defaultInputDevice = paNoDevice; /* IMPLEMENT ME */ + (*hostApi)->info.defaultOutputDevice = paNoDevice; /* IMPLEMENT ME */ + + (*hostApi)->info.deviceCount = 0; + + deviceCount = 0; /* IMPLEMENT ME */ + + if( deviceCount > 0 ) + { + (*hostApi)->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory( + skeletonHostApi->allocations, sizeof(PaDeviceInfo*) * deviceCount ); + if( !(*hostApi)->deviceInfos ) + { + result = paInsufficientMemory; + goto error; + } + + /* allocate all device info structs in a contiguous block */ + deviceInfoArray = (PaDeviceInfo*)PaUtil_GroupAllocateMemory( + skeletonHostApi->allocations, sizeof(PaDeviceInfo) * deviceCount ); + if( !deviceInfoArray ) + { + result = paInsufficientMemory; + goto error; + } + + for( i=0; i < deviceCount; ++i ) + { + PaDeviceInfo *deviceInfo = &deviceInfoArray[i]; + deviceInfo->structVersion = 2; + deviceInfo->hostApi = hostApiIndex; + deviceInfo->name = 0; /* IMPLEMENT ME: allocate block and copy name eg: + deviceName = (char*)PaUtil_GroupAllocateMemory( skeletonHostApi->allocations, strlen(srcName) + 1 ); + if( !deviceName ) + { + result = paInsufficientMemory; + goto error; + } + strcpy( deviceName, srcName ); + deviceInfo->name = deviceName; + */ + + deviceInfo->maxInputChannels = 0; /* IMPLEMENT ME */ + deviceInfo->maxOutputChannels = 0; /* IMPLEMENT ME */ + + deviceInfo->defaultLowInputLatency = 0.; /* IMPLEMENT ME */ + deviceInfo->defaultLowOutputLatency = 0.; /* IMPLEMENT ME */ + deviceInfo->defaultHighInputLatency = 0.; /* IMPLEMENT ME */ + deviceInfo->defaultHighOutputLatency = 0.; /* IMPLEMENT ME */ + + deviceInfo->defaultSampleRate = 0.; /* IMPLEMENT ME */ + + (*hostApi)->deviceInfos[i] = deviceInfo; + ++(*hostApi)->info.deviceCount; + } + } + + (*hostApi)->Terminate = Terminate; + (*hostApi)->OpenStream = OpenStream; + (*hostApi)->IsFormatSupported = IsFormatSupported; + + PaUtil_InitializeStreamInterface( &skeletonHostApi->callbackStreamInterface, CloseStream, StartStream, + StopStream, AbortStream, IsStreamStopped, IsStreamActive, + GetStreamTime, GetStreamCpuLoad, + PaUtil_DummyRead, PaUtil_DummyWrite, + PaUtil_DummyGetReadAvailable, PaUtil_DummyGetWriteAvailable ); + + PaUtil_InitializeStreamInterface( &skeletonHostApi->blockingStreamInterface, CloseStream, StartStream, + StopStream, AbortStream, IsStreamStopped, IsStreamActive, + GetStreamTime, PaUtil_DummyGetCpuLoad, + ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable ); + + return result; + +error: + if( skeletonHostApi ) + { + if( skeletonHostApi->allocations ) + { + PaUtil_FreeAllAllocations( skeletonHostApi->allocations ); + PaUtil_DestroyAllocationGroup( skeletonHostApi->allocations ); + } + + PaUtil_FreeMemory( skeletonHostApi ); + } + return result; +} + + +static void Terminate( struct PaUtilHostApiRepresentation *hostApi ) +{ + PaSkeletonHostApiRepresentation *skeletonHostApi = (PaSkeletonHostApiRepresentation*)hostApi; + + /* + IMPLEMENT ME: + - clean up any resources not handled by the allocation group + */ + + if( skeletonHostApi->allocations ) + { + PaUtil_FreeAllAllocations( skeletonHostApi->allocations ); + PaUtil_DestroyAllocationGroup( skeletonHostApi->allocations ); + } + + PaUtil_FreeMemory( skeletonHostApi ); +} + + +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 */ + } + 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 */ + } + 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 + */ + + + /* suppress unused variable warnings */ + (void) sampleRate; + + return paFormatIsSupported; +} + +/* PaSkeletonStream - a stream data structure specifically for this implementation */ + +typedef struct PaSkeletonStream +{ /* IMPLEMENT ME: rename this */ + PaUtilStreamRepresentation streamRepresentation; + PaUtilCpuLoadMeasurer cpuLoadMeasurer; + PaUtilBufferProcessor bufferProcessor; + + /* IMPLEMENT ME: + - implementation specific data goes here + */ + unsigned long framesPerHostCallback; /* just an example */ +} +PaSkeletonStream; + +/* 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; + PaSkeletonHostApiRepresentation *skeletonHostApi = (PaSkeletonHostApiRepresentation*)hostApi; + PaSkeletonStream *stream = 0; + unsigned long framesPerHostBuffer = framesPerBuffer; /* these may not be equivalent for all implementations */ + int inputChannelCount, outputChannelCount; + PaSampleFormat inputSampleFormat, outputSampleFormat; + PaSampleFormat hostInputSampleFormat, hostOutputSampleFormat; + + + 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 */ + + /* IMPLEMENT ME - establish which host formats are available */ + hostInputSampleFormat = + PaUtil_SelectClosestAvailableFormat( paInt16 /* native formats */, 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 */ + + /* IMPLEMENT ME - establish which host formats are available */ + hostOutputSampleFormat = + PaUtil_SelectClosestAvailableFormat( paInt16 /* native formats */, 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 */ + + + stream = (PaSkeletonStream*)PaUtil_AllocateMemory( sizeof(PaSkeletonStream) ); + if( !stream ) + { + result = paInsufficientMemory; + goto error; + } + + if( streamCallback ) + { + PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation, + &skeletonHostApi->callbackStreamInterface, streamCallback, userData ); + } + else + { + PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation, + &skeletonHostApi->blockingStreamInterface, streamCallback, userData ); + } + + PaUtil_InitializeCpuLoadMeasurer( &stream->cpuLoadMeasurer, sampleRate ); + + + /* 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, + framesPerHostBuffer, 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); + stream->streamRepresentation.streamInfo.outputLatency = + PaUtil_GetBufferProcessorOutputLatency(&stream->bufferProcessor); + stream->streamRepresentation.streamInfo.sampleRate = sampleRate; + + + /* + IMPLEMENT ME: + - additional stream setup + opening + */ + + stream->framesPerHostCallback = framesPerHostBuffer; + + *s = (PaStream*)stream; + + return result; + +error: + if( stream ) + PaUtil_FreeMemory( stream ); + + return result; +} + +/* + ExampleHostProcessingLoop() illustrates the kind of processing which may + occur in a host implementation. + +*/ +static void ExampleHostProcessingLoop( void *inputBuffer, void *outputBuffer, void *userData ) +{ + PaSkeletonStream *stream = (PaSkeletonStream*)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. + */ + + PaUtil_SetInputFrameCount( &stream->bufferProcessor, 0 /* default to host buffer size */ ); + PaUtil_SetInterleavedInputChannels( &stream->bufferProcessor, + 0, /* first channel of inputBuffer is channel 0 */ + inputBuffer, + 0 ); /* 0 - use inputChannelCount passed to init buffer processor */ + + PaUtil_SetOutputFrameCount( &stream->bufferProcessor, 0 /* default to host buffer size */ ); + 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 ); + } +} + + +/* + 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; + PaSkeletonStream *stream = (PaSkeletonStream*)s; + + /* + IMPLEMENT ME: + - additional stream closing + cleanup + */ + + PaUtil_TerminateBufferProcessor( &stream->bufferProcessor ); + PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation ); + PaUtil_FreeMemory( stream ); + + return result; +} + + +static PaError StartStream( PaStream *s ) +{ + PaError result = paNoError; + PaSkeletonStream *stream = (PaSkeletonStream*)s; + + PaUtil_ResetBufferProcessor( &stream->bufferProcessor ); + + /* IMPLEMENT ME, see portaudio.h for required behavior */ + + /* suppress unused function warning. the code in ExampleHostProcessingLoop or + something similar should be implemented to feed samples to and from the + host after StartStream() is called. + */ + (void) ExampleHostProcessingLoop; + + return result; +} + + +static PaError StopStream( PaStream *s ) +{ + PaError result = paNoError; + PaSkeletonStream *stream = (PaSkeletonStream*)s; + + /* suppress unused variable warnings */ + (void) stream; + + /* IMPLEMENT ME, see portaudio.h for required behavior */ + + return result; +} + + +static PaError AbortStream( PaStream *s ) +{ + PaError result = paNoError; + PaSkeletonStream *stream = (PaSkeletonStream*)s; + + /* suppress unused variable warnings */ + (void) stream; + + /* IMPLEMENT ME, see portaudio.h for required behavior */ + + return result; +} + + +static PaError IsStreamStopped( PaStream *s ) +{ + PaSkeletonStream *stream = (PaSkeletonStream*)s; + + /* suppress unused variable warnings */ + (void) stream; + + /* IMPLEMENT ME, see portaudio.h for required behavior */ + + return 0; +} + + +static PaError IsStreamActive( PaStream *s ) +{ + PaSkeletonStream *stream = (PaSkeletonStream*)s; + + /* suppress unused variable warnings */ + (void) stream; + + /* IMPLEMENT ME, see portaudio.h for required behavior */ + + return 0; +} + + +static PaTime GetStreamTime( PaStream *s ) +{ + PaSkeletonStream *stream = (PaSkeletonStream*)s; + + /* suppress unused variable warnings */ + (void) stream; + + /* IMPLEMENT ME, see portaudio.h for required behavior*/ + + return 0; +} + + +static double GetStreamCpuLoad( PaStream* s ) +{ + PaSkeletonStream *stream = (PaSkeletonStream*)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 ) +{ + PaSkeletonStream *stream = (PaSkeletonStream*)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 ) +{ + PaSkeletonStream *stream = (PaSkeletonStream*)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 ) +{ + PaSkeletonStream *stream = (PaSkeletonStream*)s; + + /* suppress unused variable warnings */ + (void) stream; + + /* IMPLEMENT ME, see portaudio.h for required behavior*/ + + return 0; +} + + +static signed long GetStreamWriteAvailable( PaStream* s ) +{ + PaSkeletonStream *stream = (PaSkeletonStream*)s; + + /* suppress unused variable warnings */ + (void) stream; + + /* IMPLEMENT ME, see portaudio.h for required behavior*/ + + return 0; +} + + + + diff --git a/pa_common/pa_stream.c b/pa_common/pa_stream.c new file mode 100644 index 0000000..e820671 --- /dev/null +++ b/pa_common/pa_stream.c @@ -0,0 +1,141 @@ +/* + * $Id$ + * Portable Audio I/O Library + * + * + * Based on the Open Source API proposed by Ross Bencina + * Copyright (c) 2002 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. + * + * 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. + */ + +/** @file + @brief Interface used by pa_front to virtualize functions which operate on + streams. +*/ + + +#include "pa_stream.h" + + +void PaUtil_InitializeStreamInterface( PaUtilStreamInterface *streamInterface, + PaError (*Close)( PaStream* ), + PaError (*Start)( PaStream* ), + PaError (*Stop)( PaStream* ), + PaError (*Abort)( PaStream* ), + PaError (*IsStopped)( PaStream* ), + PaError (*IsActive)( PaStream* ), + PaTime (*GetTime)( PaStream* ), + double (*GetCpuLoad)( PaStream* ), + PaError (*Read)( PaStream*, void *, unsigned long ), + PaError (*Write)( PaStream*, const void *, unsigned long ), + signed long (*GetReadAvailable)( PaStream* ), + signed long (*GetWriteAvailable)( PaStream* ) ) +{ + streamInterface->Close = Close; + streamInterface->Start = Start; + streamInterface->Stop = Stop; + streamInterface->Abort = Abort; + streamInterface->IsStopped = IsStopped; + streamInterface->IsActive = IsActive; + streamInterface->GetTime = GetTime; + streamInterface->GetCpuLoad = GetCpuLoad; + streamInterface->Read = Read; + streamInterface->Write = Write; + streamInterface->GetReadAvailable = GetReadAvailable; + streamInterface->GetWriteAvailable = GetWriteAvailable; +} + + +void PaUtil_InitializeStreamRepresentation( PaUtilStreamRepresentation *streamRepresentation, + PaUtilStreamInterface *streamInterface, + PaStreamCallback *streamCallback, + void *userData ) +{ + streamRepresentation->magic = PA_STREAM_MAGIC; + streamRepresentation->nextOpenStream = 0; + streamRepresentation->streamInterface = streamInterface; + streamRepresentation->streamCallback = streamCallback; + streamRepresentation->streamFinishedCallback = 0; + + streamRepresentation->userData = userData; + + streamRepresentation->streamInfo.inputLatency = 0.; + streamRepresentation->streamInfo.outputLatency = 0.; + streamRepresentation->streamInfo.sampleRate = 0.; +} + + +void PaUtil_TerminateStreamRepresentation( PaUtilStreamRepresentation *streamRepresentation ) +{ + streamRepresentation->magic = 0; +} + + +PaError PaUtil_DummyRead( PaStream* stream, + void *buffer, + unsigned long frames ) +{ + (void)stream; /* unused parameter */ + (void)buffer; /* unused parameter */ + (void)frames; /* unused parameter */ + + return paCanNotReadFromACallbackStream; +} + + +PaError PaUtil_DummyWrite( PaStream* stream, + const void *buffer, + unsigned long frames ) +{ + (void)stream; /* unused parameter */ + (void)buffer; /* unused parameter */ + (void)frames; /* unused parameter */ + + return paCanNotWriteToACallbackStream; +} + + +signed long PaUtil_DummyGetReadAvailable( PaStream* stream ) +{ + (void)stream; /* unused parameter */ + + return paCanNotReadFromACallbackStream; +} + + +signed long PaUtil_DummyGetWriteAvailable( PaStream* stream ) +{ + (void)stream; /* unused parameter */ + + return paCanNotWriteToACallbackStream; +} + + +double PaUtil_DummyGetCpuLoad( PaStream* stream ) +{ + (void)stream; /* unused parameter */ + + return 0.0; +} diff --git a/pa_common/pa_stream.h b/pa_common/pa_stream.h new file mode 100644 index 0000000..aaf89cf --- /dev/null +++ b/pa_common/pa_stream.h @@ -0,0 +1,196 @@ +#ifndef PA_STREAM_H +#define PA_STREAM_H +/* + * $Id$ + * Portable Audio I/O Library + * stream interface + * + * 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. + * + * 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. + */ + +/** @file + @brief Interface used by pa_front to virtualize functions which operate on + streams. +*/ + + +#include "portaudio.h" + +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + + +#define PA_STREAM_MAGIC (0x18273645) + + +/** A structure representing an (abstract) interface to a host API. Contains + pointers to functions which implement the interface. + + All PaStreamInterface functions are guaranteed to be called with a non-null, + valid stream parameter. +*/ +typedef struct { + PaError (*Close)( PaStream* stream ); + PaError (*Start)( PaStream *stream ); + PaError (*Stop)( PaStream *stream ); + PaError (*Abort)( PaStream *stream ); + PaError (*IsStopped)( PaStream *stream ); + PaError (*IsActive)( PaStream *stream ); + PaTime (*GetTime)( PaStream *stream ); + double (*GetCpuLoad)( PaStream* stream ); + PaError (*Read)( PaStream* stream, void *buffer, unsigned long frames ); + PaError (*Write)( PaStream* stream, const void *buffer, unsigned long frames ); + signed long (*GetReadAvailable)( PaStream* stream ); + signed long (*GetWriteAvailable)( PaStream* stream ); +} PaUtilStreamInterface; + + +/** Initialize the fields of a PaUtilStreamInterface structure. +*/ +void PaUtil_InitializeStreamInterface( PaUtilStreamInterface *streamInterface, + PaError (*Close)( PaStream* ), + PaError (*Start)( PaStream* ), + PaError (*Stop)( PaStream* ), + PaError (*Abort)( PaStream* ), + PaError (*IsStopped)( PaStream* ), + PaError (*IsActive)( PaStream* ), + PaTime (*GetTime)( PaStream* ), + double (*GetCpuLoad)( PaStream* ), + PaError (*Read)( PaStream* stream, void *buffer, unsigned long frames ), + PaError (*Write)( PaStream* stream, const void *buffer, unsigned long frames ), + signed long (*GetReadAvailable)( PaStream* stream ), + signed long (*GetWriteAvailable)( PaStream* stream ) ); + + +/** Dummy Read function for use in interfaces to a callback based streams. + Pass to the Read parameter of PaUtil_InitializeStreamInterface. + @return An error code indicating that the function has no effect + because the stream is a callback stream. +*/ +PaError PaUtil_DummyRead( PaStream* stream, + void *buffer, + unsigned long frames ); + + +/** Dummy Write function for use in an interfaces to callback based streams. + Pass to the Write parameter of PaUtil_InitializeStreamInterface. + @return An error code indicating that the function has no effect + because the stream is a callback stream. +*/ +PaError PaUtil_DummyWrite( PaStream* stream, + const void *buffer, + unsigned long frames ); + + +/** Dummy GetReadAvailable function for use in interfaces to callback based + streams. Pass to the GetReadAvailable parameter of PaUtil_InitializeStreamInterface. + @return An error code indicating that the function has no effect + because the stream is a callback stream. +*/ +signed long PaUtil_DummyGetReadAvailable( PaStream* stream ); + + +/** Dummy GetWriteAvailable function for use in interfaces to callback based + streams. Pass to the GetWriteAvailable parameter of PaUtil_InitializeStreamInterface. + @return An error code indicating that the function has no effect + because the stream is a callback stream. +*/ +signed long PaUtil_DummyGetWriteAvailable( PaStream* stream ); + + + +/** Dummy GetCpuLoad function for use in an interface to a read/write stream. + Pass to the GetCpuLoad parameter of PaUtil_InitializeStreamInterface. + @return Returns 0. +*/ +double PaUtil_DummyGetCpuLoad( PaStream* stream ); + + +/** Non host specific data for a stream. This data is used by pa_front to + forward to the appropriate functions in the streamInterface structure. +*/ +typedef struct PaUtilStreamRepresentation { + unsigned long magic; /**< set to PA_STREAM_MAGIC */ + struct PaUtilStreamRepresentation *nextOpenStream; /**< field used by multi-api code */ + PaUtilStreamInterface *streamInterface; + PaStreamCallback *streamCallback; + PaStreamFinishedCallback *streamFinishedCallback; + void *userData; + PaStreamInfo streamInfo; +} PaUtilStreamRepresentation; + + +/** Initialize a PaUtilStreamRepresentation structure. + + @see PaUtil_InitializeStreamRepresentation +*/ +void PaUtil_InitializeStreamRepresentation( + PaUtilStreamRepresentation *streamRepresentation, + PaUtilStreamInterface *streamInterface, + PaStreamCallback *streamCallback, + void *userData ); + + +/** Clean up a PaUtilStreamRepresentation structure previously initialized + by a call to PaUtil_InitializeStreamRepresentation. + + @see PaUtil_InitializeStreamRepresentation +*/ +void PaUtil_TerminateStreamRepresentation( PaUtilStreamRepresentation *streamRepresentation ); + + +/** Check that the stream pointer is valid. + + @return Returns paNoError if the stream pointer appears to be OK, otherwise + returns an error indicating the cause of failure. +*/ +PaError PaUtil_ValidateStreamPointer( PaStream *stream ); + + +/** Cast an opaque stream pointer into a pointer to a PaUtilStreamRepresentation. + + @see PaUtilStreamRepresentation +*/ +#define PA_STREAM_REP( stream )\ + ((PaUtilStreamRepresentation*) (stream) ) + + +/** Cast an opaque stream pointer into a pointer to a PaUtilStreamInterface. + + @see PaUtilStreamRepresentation, PaUtilStreamInterface +*/ +#define PA_STREAM_INTERFACE( stream )\ + PA_STREAM_REP( (stream) )->streamInterface + + + +#ifdef __cplusplus +} +#endif /* __cplusplus */ +#endif /* PA_STREAM_H */ diff --git a/pa_common/pa_trace.c b/pa_common/pa_trace.c index 08e68f5..6619d42 100644 --- a/pa_common/pa_trace.c +++ b/pa_common/pa_trace.c @@ -30,49 +30,54 @@ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/** @file + @brief Event trace mechanism for debugging. +*/ + + #include #include #include #include "pa_trace.h" -#if TRACE_REALTIME_EVENTS +#if PA_TRACE_REALTIME_EVENTS -static char *traceTextArray[MAX_TRACE_RECORDS]; -static int traceIntArray[MAX_TRACE_RECORDS]; +static char *traceTextArray[PA_MAX_TRACE_RECORDS]; +static int traceIntArray[PA_MAX_TRACE_RECORDS]; static int traceIndex = 0; static int traceBlock = 0; /*********************************************************************/ -void ResetTraceMessages() +void PaUtil_ResetTraceMessages() { traceIndex = 0; } /*********************************************************************/ -void DumpTraceMessages() +void PaUtil_DumpTraceMessages() { int i; - int numDump = (traceIndex < MAX_TRACE_RECORDS) ? traceIndex : MAX_TRACE_RECORDS; + int messageCount = (traceIndex < PA_MAX_TRACE_RECORDS) ? traceIndex : PA_MAX_TRACE_RECORDS; printf("DumpTraceMessages: traceIndex = %d\n", traceIndex ); - for( i=0; i must be included in the + context in which this macro is used. +*/ +#define PA_VALIDATE_TYPE_SIZES \ + { \ + assert( "PortAudio: type sizes are not correct in pa_types.h" && sizeof( PaUint16 ) == 2 ); \ + assert( "PortAudio: type sizes are not correct in pa_types.h" && sizeof( PaInt16 ) == 2 ); \ + assert( "PortAudio: type sizes are not correct in pa_types.h" && sizeof( PaUint32 ) == 4 ); \ + assert( "PortAudio: type sizes are not correct in pa_types.h" && sizeof( PaInt32 ) == 4 ); \ + } + + +#endif /* PA_TYPES_H */ diff --git a/pa_common/pa_util.h b/pa_common/pa_util.h new file mode 100644 index 0000000..ab8dbe0 --- /dev/null +++ b/pa_common/pa_util.h @@ -0,0 +1,167 @@ +#ifndef PA_UTIL_H +#define PA_UTIL_H +/* + * $Id$ + * Portable Audio I/O Library implementation utilities header + * common implementation utilities and interfaces + * + * 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. + * + * 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. + */ + +/** @file + @brief Prototypes for utility functions used by PortAudio implementations. + + @todo Document and adhere to the alignment guarantees provided by + PaUtil_AllocateMemory(). +*/ + + +#include "portaudio.h" + +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + + +struct PaUtilHostApiRepresentation; + + +/** Retrieve a specific host API representation. This function can be used + by implementations to retrieve a pointer to their representation in + host api specific extension functions which aren't passed a rep pointer + by pa_front.c. + + @param hostApi A pointer to a host API represenation pointer. Apon success + this will receive the requested representation pointer. + + @param type A valid host API type identifier. + + @returns An error code. If the result is PaNoError then a pointer to the + requested host API representation will be stored in *hostApi. If the host API + specified by type is not found, this function returns paHostApiNotFound. +*/ +PaError PaUtil_GetHostApiRepresentation( struct PaUtilHostApiRepresentation **hostApi, + PaHostApiTypeId type ); + + +/** Convert a PortAudio device index into a host API specific device index. + @param hostApiDevice Pointer to a device index, on success this will recieve the + converted device index value. + @param device The PortAudio device index to convert. + @param hostApi The host api which the index should be converted for. + + @returns On success returns PaNoError and places the converted index in the + hostApiDevice parameter. +*/ +PaError PaUtil_DeviceIndexToHostApiDeviceIndex( + PaDeviceIndex *hostApiDevice, PaDeviceIndex device, + struct PaUtilHostApiRepresentation *hostApi ); + + +/** Set the host error information returned by Pa_GetLastHostErrorInfo. This + function and the paUnanticipatedHostError error code should be used as a + last resort. Implementors should use existing PA error codes where possible, + or nominate new ones. Note that at it is always better to use + PaUtil_SetLastHostErrorInfo() and paUnanticipatedHostError than to return an + ambiguous or inaccurate PaError code. + + @param hostApiType The host API which encountered the error (ie of the caller) + + @param errorCode The error code returned by the native API function. + + @param errorText A string describing the error. PaUtil_SetLastHostErrorInfo + makes a copy of the string, so it is not necessary for the pointer to remain + valid after the call to PaUtil_SetLastHostErrorInfo() returns. + +*/ +void PaUtil_SetLastHostErrorInfo( PaHostApiTypeId hostApiType, long errorCode, + const char *errorText ); + + + +/** PA_DEBUG() provides a simple debug message printing facility. The macro + passes it's argument to a printf-like function called PaUtil_DebugPrint() + which prints to stderr and always flushes the stream after printing. + Because preprocessor macros cannot directly accept variable length argument + lists, calls to the macro must include an additional set of parenthesis, eg: + PA_DEBUG(("errorno: %d", 1001 )); +*/ + +void PaUtil_DebugPrint( const char *format, ... ); + +#ifdef PA_ENABLE_DEBUG_OUTPUT +#define PA_DEBUG(x) PaUtil_DebugPrint x ; +#else +#define PA_DEBUG(x) +#endif + + +/* the following functions are implemented in a platform platform specific + .c file +*/ + +/** Allocate size bytes, guaranteed to be aligned to a FIXME byte boundary */ +void *PaUtil_AllocateMemory( long size ); + + +/** Realease block if non-NULL. block may be NULL */ +void PaUtil_FreeMemory( void *block ); + + +/** Return the number of currently allocated blocks. This function can be + used for detecting memory leaks. + + @note Allocations will only be tracked if PA_TRACK_MEMORY is #defined. If + it isn't, this function will always return 0. +*/ +int PaUtil_CountCurrentlyAllocatedBlocks( void ); + + +/** Initialize the clock used by PaUtil_GetTime(). Call this before calling + PaUtil_GetTime. + + @see PaUtil_GetTime +*/ +void PaUtil_InitializeClock( void ); + + +/** Return the system time in seconds. Used to implement CPU load functions + + @see PaUtil_InitializeClock +*/ +double PaUtil_GetTime( void ); + + +/* void Pa_Sleep( long msec ); must also be implemented in per-platform .c file */ + + + +#ifdef __cplusplus +} +#endif /* __cplusplus */ +#endif /* PA_UTIL_H */ diff --git a/pa_common/portaudio.h b/pa_common/portaudio.h index fe05829..cb709bf 100644 --- a/pa_common/portaudio.h +++ b/pa_common/portaudio.h @@ -1,18 +1,13 @@ -#ifndef PORT_AUDIO_H -#define PORT_AUDIO_H - -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ +#ifndef PORTAUDIO_H +#define PORTAUDIO_H /* * $Id$ * PortAudio Portable Real-Time Audio Library * PortAudio API Header File - * Latest version available at: http://www.audiomulch.com/portaudio/ + * Latest version available at: http://www.portaudio.com/ * - * Copyright (c) 1999-2000 Ross Bencina and Phil Burk + * 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 @@ -36,17 +31,45 @@ extern "C" * 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. - * */ +/** @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 { +typedef enum PaErrorCode +{ paNoError = 0, - paHostError = -10000, + paNotInitialized = -10000, + paUnanticipatedHostError, paInvalidChannelCount, paInvalidSampleRate, - paInvalidDeviceId, + paInvalidDevice, paInvalidFlag, paSampleFormatNotSupported, paBadIODeviceCombination, @@ -57,407 +80,1046 @@ typedef enum { paBadStreamPtr, paTimedOut, paInternalError, - paDeviceUnavailable -} PaErrorNum; + 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 ); -/* - Pa_Initialize() is the library initialisation function - call this before - using the library. -*/ +/** Library initialization function - call this before using PortAudio. + This function initialises internal data structures and prepares underlying + host APIs for use. This function MUST be called before using any other + PortAudio API functions. -PaError Pa_Initialize( void ); + 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. -/* - Pa_Terminate() is the library termination function - call this after - using the library. + 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 ); -/* - Pa_GetHostError() returns a host specific error code. - This can be called after receiving a PortAudio error code of paHostError. + +/** The type used to refer to audio devices. Values of this type usually + range from 0 to (Pa_DeviceCount-1), and may also take on the PaNoDevice + and paUseHostApiSpecificDeviceSpecification values. + + @see Pa_DeviceCount, paNoDevice, paUseHostApiSpecificDeviceSpecification */ +typedef int PaDeviceIndex; -long Pa_GetHostError( void ); -/* - Pa_GetErrorText() translates the supplied PortAudio error number - into a human readable message. - +/** A special PaDeviceIndex value indicating that no device is available, + or should be used. + + @see PaDeviceIndex */ +#define paNoDevice ((PaDeviceIndex)-1) -const char *Pa_GetErrorText( PaError errnum ); -/* - Sample formats - - These are formats used to pass sound data between the callback and the - stream. Each device has a "native" format which may be used when optimum - efficiency or control over conversion is required. - - Formats marked "always available" are supported (emulated) by all - PortAudio implementations. - - The floating point representation (paFloat32) uses +1.0 and -1.0 as the - maximum and minimum respectively. +/** 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) - paUInt8 is an unsigned 8 bit format where 128 is considered "ground" +/* 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; -typedef unsigned long PaSampleFormat; -#define paFloat32 ((PaSampleFormat) (1<<0)) /*always available*/ -#define paInt16 ((PaSampleFormat) (1<<1)) /*always available*/ -#define paInt32 ((PaSampleFormat) (1<<2)) /*always available*/ -#define paInt24 ((PaSampleFormat) (1<<3)) -#define paPackedInt24 ((PaSampleFormat) (1<<4)) -#define paInt8 ((PaSampleFormat) (1<<5)) -#define paUInt8 ((PaSampleFormat) (1<<6)) -#define paCustomFormat ((PaSampleFormat) (1<<16)) -/* - Device enumeration mechanism. - - Device ids range from 0 to Pa_CountDevices()-1. - - Devices may support input, output or both. +/** 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 ); -typedef int PaDeviceID; -#define paNoDevice -1 -int Pa_CountDevices( 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 ); -typedef struct + +/** 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 +} 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; - int maxInputChannels; - int maxOutputChannels; - /* Number of discrete rates, or -1 if range supported. */ - int numSampleRates; - /* Array of supported sample rates, or {min,max} if range supported. */ - const double *sampleRates; - PaSampleFormat nativeSampleFormats; -} -PaDeviceInfo; -/* - Pa_GetDefaultInputDeviceID(), Pa_GetDefaultOutputDeviceID() return the - default device ids for input and output respectively, or paNoDevice if - no device is available. - The result can be passed to Pa_OpenStream(). + /** 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 - +
+ 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; -PaDeviceID Pa_GetDefaultInputDeviceID( void ); -PaDeviceID Pa_GetDefaultOutputDeviceID( void ); +/** 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. -/* - Pa_GetDeviceInfo() returns a pointer to an immutable PaDeviceInfo structure - for the device specified. - If the device parameter is out of range the function returns NULL. + The floating point representation (paFloat32) uses +1.0 and -1.0 as the + maximum and minimum respectively. - 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(). + 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; -const PaDeviceInfo* Pa_GetDeviceInfo( PaDeviceID device ); -/* - PaTimestamp is used to represent a continuous sample clock with arbitrary - start time that can be used for syncronization. The type is used for the - outTime argument to the PortAudioCallback and as the result of Pa_StreamTime() +#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; -typedef double PaTimestamp; + /* 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 ); -/* - PortAudioCallback is implemented by PortAudio clients. - - inputBuffer and outputBuffer are arrays of interleaved samples, - the format, packing and number of channels used by the buffers are - determined by parameters to Pa_OpenStream() (see below). - - framesPerBuffer is the number of sample frames to be processed by the callback. - - outTime is the time in samples when the buffer(s) processed by - this callback will begin being played at the audio output. - See also Pa_StreamTime() - - userData is the value of a user supplied pointer passed to Pa_OpenStream() - intended for storing synthesis data etc. - - return value: - The callback can return a non-zero value to stop the stream. 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 StopStream() will also terminate the stream. A callback returning a - non-zero value must fill the entire outputBuffer. - - NOTE: None of the other stream functions may be called from within the - callback function except for Pa_GetCPULoad(). +/** 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 -typedef int (PortAudioCallback)( - void *inputBuffer, void *outputBuffer, - unsigned long framesPerBuffer, - PaTimestamp outTime, void *userData ); + @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 */ -/* - Stream flags - - These flags may be supplied (ored together) in the streamFlags argument to - the Pa_OpenStream() function. + +/** + 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; -#define paNoFlag (0) -#define paClipOff (1<<0) /* disable default clipping of out of range samples */ -#define paDitherOff (1<<1) /* disable default dithering */ -#define paPlatformSpecificFlags (0x00010000) -typedef unsigned long PaStreamFlags; -/* - A single PortAudioStream provides multiple channels of real-time - input and output audio streaming to a client application. - Pointers to PortAudioStream objects are passed between PortAudio functions. +/** 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) -typedef void PortAudioStream; -#define PaStream PortAudioStream -/* - Pa_OpenStream() opens a stream for either input, output or both. +/** 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. - stream is the address of a PortAudioStream pointer which will receive + @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. - inputDevice is the id of the device used for input (see PaDeviceID above.) - inputDevice may be paNoDevice to indicate that an input device is not required. - - numInputChannels is the number of channels of sound to be delivered to the - callback. It can range from 1 to the value of maxInputChannels in the - PaDeviceInfo record for the device specified by the inputDevice parameter. - If inputDevice is paNoDevice numInputChannels is ignored. - - inputSampleFormat is the sample format of inputBuffer provided to the callback - function. inputSampleFormat may be any of the formats described by the - PaSampleFormat enumeration (see above). PortAudio guarantees support for - the device's native formats (nativeSampleFormats in the device info record) - and additionally 16 and 32 bit integer and 32 bit floating point formats. - Support for other formats is implementation defined. - - inputDriverInfo is a pointer to an optional driver specific data structure - containing additional information for device setup or stream processing. - inputDriverInfo is never required for correct operation. If not used - inputDriverInfo should be NULL. - - outputDevice is the id of the device used for output (see PaDeviceID above.) - outputDevice may be paNoDevice to indicate that an output device is not required. - - numOutputChannels is the number of channels of sound to be supplied by the - callback. See the definition of numInputChannels above for more details. - - outputSampleFormat is the sample format of the outputBuffer filled by the - callback function. See the definition of inputSampleFormat above for more - details. - - outputDriverInfo is a pointer to an optional driver specific data structure - containing additional information for device setup or stream processing. - outputDriverInfo is never required for correct operation. If not used - outputDriverInfo should be NULL. - - sampleRate is the desired sampleRate. For full-duplex streams it is the + @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. - framesPerBuffer is the length in sample frames of all internal sample buffers - used for communication with platform specific audio routines. Wherever - possible this corresponds to the framesPerBuffer parameter passed to the - callback function. - - numberOfBuffers is the number of buffers used for multibuffered communication - with the platform specific audio routines. If you pass zero, then an optimum - value will be chosen for you internally. This parameter is provided only - as a guide - and does not imply that an implementation must use multibuffered - i/o when reliable double buffering is available (such as SndPlayDoubleBuffer() - on the Macintosh.) - - streamFlags may contain a combination of flags ORed together. - These flags modify the behaviour of the streaming process. Some flags may only - be relevant to certain buffer formats. - - callback is a pointer to a client supplied function that is responsible - for processing and filling input and output buffers (see above for details.) - - userData is a client supplied pointer which is passed to the 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. - - return value: - Upon success Pa_OpenStream() returns PaNoError and places a pointer to a - valid PortAudioStream 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 above) and the value of stream is invalid. - + 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( PortAudioStream** stream, - PaDeviceID inputDevice, - int numInputChannels, - PaSampleFormat inputSampleFormat, - void *inputDriverInfo, - PaDeviceID outputDevice, - int numOutputChannels, - PaSampleFormat outputSampleFormat, - void *outputDriverInfo, +PaError Pa_OpenStream( PaStream** stream, + const PaStreamParameters *inputParameters, + const PaStreamParameters *outputParameters, double sampleRate, unsigned long framesPerBuffer, - unsigned long numberOfBuffers, PaStreamFlags streamFlags, - PortAudioCallback *callback, + PaStreamCallback *streamCallback, void *userData ); -/* - Pa_OpenDefaultStream() is a simplified version of Pa_OpenStream() that opens - the default input and/or output devices. Most parameters have identical meaning - to their Pa_OpenStream() counterparts, with the following exceptions: +/** 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. - If either numInputChannels or numOutputChannels is 0 the respective device - is not opened. This has the same effect as passing paNoDevice in the device - arguments to Pa_OpenStream(). + @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. - sampleFormat applies to both the input and output buffers. + @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 -PaError Pa_OpenDefaultStream( PortAudioStream** stream, + @see Pa_OpenStream, PaStreamCallback +*/ +PaError Pa_OpenDefaultStream( PaStream** stream, int numInputChannels, int numOutputChannels, PaSampleFormat sampleFormat, double sampleRate, unsigned long framesPerBuffer, - unsigned long numberOfBuffers, - PortAudioCallback *callback, + PaStreamCallback *streamCallback, void *userData ); -/* - Pa_CloseStream() closes an audio stream, flushing any pending buffers. +/** 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 ); -PaError Pa_CloseStream( PortAudioStream* ); -/* - Pa_StartStream() and Pa_StopStream() begin and terminate audio processing. - Pa_StopStream() waits until all pending audio buffers have been played. - Pa_AbortStream() stops playing immediately without waiting for pending +/** 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 ); -PaError Pa_StartStream( PortAudioStream *stream ); -PaError Pa_StopStream( PortAudioStream *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. -PaError Pa_AbortStream( PortAudioStream *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. -/* - Pa_StreamActive() returns one (1) when the stream is active (ie playing - or recording audio), zero (0) when not playing, or a negative error number - if the stream is invalid. - The stream is active between calls to Pa_StartStream() and Pa_StopStream(), - but may also become inactive if the callback returns a non-zero value. - In the latter case, the stream is considered inactive after the last - buffer has finished playing. - + @see Pa_StopStream, Pa_AbortStream, Pa_IsStreamActive */ +PaError Pa_IsStreamStopped( PaStream *stream ); -PaError Pa_StreamActive( PortAudioStream *stream ); -/* - Pa_StreamTime() returns the current output time in samples for the stream. - This time may be used as a time reference (for example synchronizing audio to - MIDI). - +/** 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 ); -PaTimestamp Pa_StreamTime( PortAudioStream *stream ); -/* - Pa_GetCPULoad() returns the CPU Load for the stream. - The "CPU Load" is a fraction of total CPU time consumed by the stream's + +/** 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 - callback. - A value of 0.5 would imply that PortAudio and the sound generating - callback was consuming roughly 50% of the available CPU time. - This function may be called from the callback function or the application. - + 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 ); -double Pa_GetCPULoad( PortAudioStream* stream ); -/* - Pa_GetMinNumBuffers() returns the minimum number of buffers required by - the current host based on minimum latency. - On the PC, for the DirectSound implementation, 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. +/** 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 ); -int Pa_GetMinNumBuffers( int framesPerBuffer, double sampleRate ); -/* - Pa_Sleep() puts the caller to sleep for at least 'msec' milliseconds. - You may sleep longer than the requested time so don't rely on this for - accurate musical timing. - - Pa_Sleep() is provided as a convenience for authors of portable code (such as - the tests and examples in the PortAudio distribution.) - +/** 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 ); -void Pa_Sleep( long msec ); -/* - Pa_GetSampleSize() returns the size in bytes of a single sample in the - supplied PaSampleFormat, or paSampleFormatNotSupported if the format is - no supported. - +/** 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 /* PORT_AUDIO_H */ +#endif /* PORTAUDIO_H */ diff --git a/pa_jack/pa_jack.c b/pa_jack/pa_jack.c new file mode 100644 index 0000000..17bf3d3 --- /dev/null +++ b/pa_jack/pa_jack.c @@ -0,0 +1,1714 @@ +/* + * $Id$ + * 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. + * + * 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. + */ + +#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 "../pablio/ringbuffer.c" + +static int aErr_; +static PaError paErr_; /* For use with ENSURE_PA */ +static pthread_t mainThread_; +static char *jackErr_ = NULL; + +#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_ ) \ + { \ + assert( jackErr_ ); \ + 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_ ) \ + { \ + assert( jackErr_ ); \ + 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; + RingBuffer inFIFO; + RingBuffer 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( RingBuffer *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) RingBuffer_Init( rbuf, numBytes, buffer ); +} + +/* Free buffer. */ +static PaError BlockingTermFIFO( RingBuffer *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 ) + { + RingBuffer_Write( &stream->inFIFO, inputBuffer, numBytes ); + } + if( outputBuffer != NULL ) + { + int numRead = RingBuffer_Read( &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 = RingBuffer_GetWriteAvailable( &stream->outFIFO ); + RingBuffer_AdvanceWriteIndex( &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 = RingBuffer_Read( &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 = RingBuffer_Write( &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 = RingBuffer_GetReadAvailable( &stream->inFIFO ); + return bytesFull / stream->bytesPerFrame; +} + +static signed long +BlockingGetStreamWriteAvailable( PaStream* s ) +{ + PaJackStream *stream = (PaJackStream *)s; + + int bytesEmpty = RingBuffer_GetWriteAvailable( &stream->outFIFO ); + return bytesEmpty / stream->bytesPerFrame; +} + +static PaError +BlockingWaitEmpty( PaStream *s ) +{ + PaJackStream *stream = (PaJackStream *)s; + + while( RingBuffer_GetReadAvailable( &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 */ + + /* ... MALLOC: allocate memory as part of the device list + * allocation group */ +#define MALLOC(size) \ + (PaUtil_GroupAllocateMemory( jackApi->deviceInfoMemory, (size) )) + + /* 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 = alloca( jack_client_name_size() + 3 ); + int port_index, client_index, i; + double globalSampleRate; + regex_t port_regex; + unsigned long numClients = 0, numPorts = 0; + char *tmp_client_name = alloca( jack_client_name_size() ); + + 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 ); + + /* 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 = alloca( 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*)MALLOC(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**)MALLOC( 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*)MALLOC( sizeof(PaDeviceInfo) ), paInsufficientMemory ); + UNLESS( curDevInfo->name = (char*)MALLOC( 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; +} +#undef MALLOC + +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 ); + free( jackErr_ ); + jackErr_ = malloc( strlen( msg ) ); + sprintf( 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; + char *clientName; + int written; + *hostApi = NULL; /* Initialize to NULL */ + + UNLESS( jackHostApi = (PaJackHostApiRepresentation*) + PaUtil_AllocateMemory( sizeof(PaJackHostApiRepresentation) ), paInsufficientMemory ); + jackHostApi->deviceInfoMemory = NULL; + + 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. */ + + clientName = alloca( jack_client_name_size() ); + written = snprintf( clientName, jack_client_name_size(), "PortAudio-%d", getpid() ); + assert( written < jack_client_name_size() ); + jackHostApi->jack_client = jack_client_new( clientName ); + if( jackHostApi->jack_client == NULL ) + { + /* the V19 development docs say that if an implementation + * detects that it cannot be used, it should return a NULL + * interface and paNoError */ + result = paNoError; + goto error; + } + + UNLESS( jackHostApi->deviceInfoMemory = PaUtil_CreateAllocationGroup(), paInsufficientMemory ); + 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 ); + UNLESS( !jack_set_sample_rate_callback( jackHostApi->jack_client, JackSrCb, jackHostApi ), paUnanticipatedHostError ); + 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 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 = alloca( jack_port_name_size() ); + unsigned long regexSz = jack_client_name_size() + 3; + char *regex_pattern = alloca( 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; + + /* ... remote output ports (that we input from) */ + 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; + + /* ... remote input ports (that we output to) */ + 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 */ + + ENSURE_PA( AddStream( stream ) ); /* Add to queue over opened streams */ + + *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; +} + +/* Alter the processing queue if necessary */ +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 + 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; +} + +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: I would rather use jack_port_connect which uses jack_port_t's + * instead of port names, but it is not implemented yet. */ + if( stream->num_incoming_connections > 0 ) + { + for( i = 0; i < stream->num_incoming_connections; i++ ) + UNLESS( jack_connect( stream->jack_client, + jack_port_name( stream->remote_output_ports[i] ), + jack_port_name( stream->local_input_ports[i] ) ) == 0, paUnanticipatedHostError ); + } + + if( stream->num_outgoing_connections > 0 ) + { + for( i = 0; i < stream->num_outgoing_connections; i++ ) + UNLESS( jack_connect( stream->jack_client, + jack_port_name( stream->local_output_ports[i] ), + jack_port_name( stream->remote_input_ports[i] ) ) == 0, 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? */ + { + if( stream->num_incoming_connections > 0 ) + { + for( i = 0; i < stream->num_incoming_connections; i++ ) + UNLESS( !jack_disconnect( stream->jack_client, + jack_port_name( stream->remote_output_ports[i] ), + jack_port_name( stream->local_input_ports[i] ) ), paUnanticipatedHostError ); + } + if( stream->num_outgoing_connections > 0 ) + { + for( i = 0; i < stream->num_outgoing_connections; i++ ) + UNLESS( !jack_disconnect( stream->jack_client, + jack_port_name( stream->local_output_ports[i] ), + jack_port_name( stream->remote_input_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 ); +} diff --git a/pa_linux_alsa/pa_linux_alsa.c b/pa_linux_alsa/pa_linux_alsa.c new file mode 100644 index 0000000..5defb4d --- /dev/null +++ b/pa_linux_alsa/pa_linux_alsa.c @@ -0,0 +1,3309 @@ +/* + * $Id$ + * 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-2006 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. + * + * 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. + */ + +#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/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_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_ */ + +typedef enum +{ + StreamDirection_In, + StreamDirection_Out +} StreamDirection; + +typedef struct +{ + PaSampleFormat hostSampleFormat; + unsigned long framesPerBuffer; + int numUserChannels, numHostChannels; + int userInterleaved, hostInterleaved; + + 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 */ + + /* 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; +} DeviceNames; + +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 ) +{ + /* XXX: dmix and default ignored because after opening and closing, they seem to keep hogging resources. + */ + static const char *ignoredPlugins[] = {"hw", "plughw", "plug", "dsnoop", "tee", + "file", "null", "shm", "cards", "dmix", "default", NULL}; + int i = 0; + while( ignoredPlugins[i] ) + { + if( !strcmp( pluginId, ignoredPlugins[i] ) ) + { + return 1; + } + ++i; + } + + return 0; +} + +/* 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; + DeviceNames *deviceNames = NULL; + snd_config_t *topNode = NULL; + snd_pcm_info_t *pcmInfo; + int res; + int blocking = SND_PCM_NONBLOCK; + char alsaCardName[50]; + 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; + + /* count the devices by enumerating all the card numbers */ + + /* 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 :( */ + 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), "%s:%d,%d", "hw", 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 ) + { + continue; /* Error */ + } + + /* 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( !deviceNames || numDeviceNames > maxDeviceNames ) + { + maxDeviceNames *= 2; + PA_UNLESS( deviceNames = (DeviceNames *) realloc( deviceNames, maxDeviceNames * sizeof (DeviceNames) ), + paInsufficientMemory ); + } + + PA_ENSURE( PaAlsa_StrDup( alsaApi, &alsaDeviceName, buf ) ); + + deviceNames[ numDeviceNames - 1 ].alsaName = alsaDeviceName; + deviceNames[ numDeviceNames - 1 ].name = deviceName; + deviceNames[ numDeviceNames - 1 ].isPlug = 0; + deviceNames[ numDeviceNames - 1 ].hasPlayback = hasPlayback; + deviceNames[ 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; + 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( !deviceNames || numDeviceNames > maxDeviceNames ) + { + maxDeviceNames *= 2; + PA_UNLESS( deviceNames = (DeviceNames *) realloc( deviceNames, maxDeviceNames * sizeof (DeviceNames) ), + paInsufficientMemory ); + } + + deviceNames[numDeviceNames - 1].alsaName = alsaDeviceName; + deviceNames[numDeviceNames - 1].name = deviceName; + deviceNames[numDeviceNames - 1].isPlug = 1; + deviceNames[numDeviceNames - 1].hasPlayback = 1; + deviceNames[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. + */ + /* while( snd_card_next( &cardIdx ) == 0 && cardIdx >= 0 ) */ + for( i = 0, devIdx = 0; i < numDeviceNames; ++i ) + { + snd_pcm_t *pcm; + PaAlsaDeviceInfo *deviceInfo = &deviceInfoArray[devIdx]; + PaDeviceInfo *baseDeviceInfo = &deviceInfo->baseDeviceInfo; + int canMmap = -1; + + /* Zero fields */ + InitializeDeviceInfo( baseDeviceInfo ); + + /* to determine device capabilities, we must open the device and query the + * hardware parameter configuration space */ + + /* Query capture */ + if( deviceNames[i].hasCapture && + snd_pcm_open( &pcm, deviceNames[i].alsaName, SND_PCM_STREAM_CAPTURE, blocking ) >= 0 ) + { + if( GropeDevice( pcm, deviceNames[i].isPlug, StreamDirection_In, blocking, deviceInfo, + &canMmap ) != paNoError ) + { + /* Error */ + PA_DEBUG(("%s: Failed groping %s for capture\n", __FUNCTION__, deviceNames[i].alsaName)); + continue; + } + } + + /* Query playback */ + if( deviceNames[i].hasPlayback && + snd_pcm_open( &pcm, deviceNames[i].alsaName, SND_PCM_STREAM_PLAYBACK, blocking ) >= 0 ) + { + if( GropeDevice( pcm, deviceNames[i].isPlug, StreamDirection_Out, blocking, deviceInfo, + &canMmap ) != paNoError ) + { + /* Error */ + PA_DEBUG(("%s: Failed groping %s for playback\n", __FUNCTION__, deviceNames[i].alsaName)); + continue; + } + } + + if( 0 == canMmap ) + { + PA_DEBUG(("%s: Device %s doesn't support mmap\n", __FUNCTION__, deviceNames[i].alsaName)); + continue; + } + + baseDeviceInfo->structVersion = 2; + baseDeviceInfo->hostApi = alsaApi->hostApiIndex; + baseDeviceInfo->name = deviceNames[i].name; + deviceInfo->alsaName = deviceNames[i].alsaName; + deviceInfo->isPlug = deviceNames[i].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 ) + { + if( baseApi->info.defaultInputDevice == paNoDevice && baseDeviceInfo->maxInputChannels > 0 ) + baseApi->info.defaultInputDevice = devIdx; + if( baseApi->info.defaultOutputDevice == paNoDevice && baseDeviceInfo->maxOutputChannels > 0 ) + baseApi->info.defaultOutputDevice = devIdx; + PA_DEBUG(("%s: Adding device %s\n", __FUNCTION__, deviceNames[i].name)); + baseApi->deviceInfos[devIdx++] = (PaDeviceInfo *) deviceInfo; + } + } + free( deviceNames ); + + baseApi->info.deviceCount = devIdx; /* Number of successfully queried devices */ + +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; + + if( snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_S24 ) >= 0) + available |= paInt24; + + 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: + return SND_PCM_FORMAT_S24; + + 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; + const char *deviceName = alloca( 50 ); + 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( (char *) deviceName, 50, "plug%s", deviceInfo->alsaName ); + else + deviceName = deviceInfo->alsaName; + } + else + deviceName = streamInfo->deviceString; + + PA_DEBUG(( "%s: Opening device %s\n", __FUNCTION__, deviceName )); + if( (ret = snd_pcm_open( pcm, deviceName, streamDir == StreamDirection_In ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK, + SND_PCM_NONBLOCK )) < 0 ) + { + /* Not to be closed */ + *pcm = NULL; + ENSURE_( ret, ret == -EBUSY ? 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) + { + ENSURE_( ret, ret == -EBUSY ? paDeviceUnavailable : paUnanticipatedHostError ); + } + } + +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; + } + + 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 ); +} + +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) + self->framesPerBuffer; /* One period does not count as latency */ + ENSURE_( snd_pcm_hw_params_set_buffer_size_near( self->pcm, hwParams, &bufSz ), paUnanticipatedHostError ); + + /* Set the parameters! */ + ENSURE_( snd_pcm_hw_params( self->pcm, hwParams ), paUnanticipatedHostError ); + ENSURE_( snd_pcm_hw_params_get_buffer_size( hwParams, &self->bufferSize ), paUnanticipatedHostError ); + /* Latency in seconds, one period is not counted as latency */ + *latency = (self->bufferSize - self->framesPerBuffer) / 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 5 as a 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 = 4, 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 ); + /* One period is not counted as latency */ + maxPeriods -= 1; + numPeriods = PA_MIN( maxPeriods, numPeriods ); + + if( framesPerUserBuffer != paFramesPerBufferUnspecified ) + { + framesPerHostBuffer = framesPerUserBuffer; + if( framesPerHostBuffer < bufferSize ) + { + while( 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 ) + { + framesPerHostBuffer = min; + PA_DEBUG(( "%s: The determined period size (%lu) is less than minimum (%lu)\n", __FUNCTION__, + framesPerHostBuffer, min )); + } + else if( framesPerHostBuffer > max ) + { + framesPerHostBuffer = max; + PA_DEBUG(( "%s: The determined period size (%lu) is greater than maximum (%lu)\n", __FUNCTION__, + 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; + + if( self->capture.pcm && self->playback.pcm ) + { + if( framesPerUserBuffer == paFramesPerBufferUnspecified ) + { + snd_pcm_uframes_t desiredLatency, e, minPeriodSize, maxPeriodSize, optimalPeriodSize, periodSize, + minCapture, minPlayback, maxCapture, maxPlayback; + + /* Come up with a common desired latency */ + + 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 ); + + desiredLatency = (snd_pcm_uframes_t)(PA_MIN( outputParameters->suggestedLatency, inputParameters->suggestedLatency ) + * sampleRate); + /* Clamp desiredLatency */ + { + 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 ); + + desiredLatency = PA_MIN( desiredLatency, 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 ) + break; /* Ok! */ + + periodSize *= 2; + } + + /* 4 periods considered optimal */ + optimalPeriodSize = PA_MAX( desiredLatency / 4, 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 ) + continue; + if( 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( desiredLatency / 4, 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 < 4 ) + { + /* 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. ) ); + } + 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; + + 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_drop( 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 */ + +/* Initialize host api specific structure */ +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 ) +{ +#if 0 + PaAlsaStream *stream = (PaAlsaStream *) s; + stream->threading.rtSched = enable; +#endif +} + +void PaAlsa_EnableWatchdog( PaStream *s, int enable ) +{ +#if 0 + PaAlsaStream *stream = (PaAlsaStream *) s; + stream->threading.useWatchdog = enable; +#endif +} diff --git a/pa_linux_alsa/pa_linux_alsa.h b/pa_linux_alsa/pa_linux_alsa.h new file mode 100644 index 0000000..b9d43c9 --- /dev/null +++ b/pa_linux_alsa/pa_linux_alsa.h @@ -0,0 +1,64 @@ +#ifndef PA_LINUX_ALSA_H +#define PA_LINUX_ALSA_H + +/* + * $Id$ + * 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. + * + * 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. + * + */ + +/** @file + * ALSA-specific PortAudio API extension header file. + */ + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct PaAlsaStreamInfo +{ + unsigned long size; + PaHostApiTypeId hostApiType; + unsigned long version; + + const char *deviceString; +} +PaAlsaStreamInfo; + +void PaAlsa_InitializeStreamInfo( PaAlsaStreamInfo *info ); + +void PaAlsa_EnableRealtimeScheduling( PaStream *s, int enable ); + +void PaAlsa_EnableWatchdog( PaStream *s, int enable ); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/pa_mac/pa_mac_hostapis.c b/pa_mac/pa_mac_hostapis.c new file mode 100644 index 0000000..f8306c3 --- /dev/null +++ b/pa_mac/pa_mac_hostapis.c @@ -0,0 +1,79 @@ +/* + * $Id$ + * 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. + * + * 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. + */ + +/** @file +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; diff --git a/pa_mac_core/notes.txt b/pa_mac_core/notes.txt index c79b90e..ad66f35 100644 --- a/pa_mac_core/notes.txt +++ b/pa_mac_core/notes.txt @@ -1,8 +1,23 @@ -Notes on Core Audio Implementation of PortAudio +Notes on status of CoreAudio Implementation of PortAudio + +Document Last Updated December 9, 2005 + +There are currently two implementations of PortAudio for Mac Core Audio. + +The original is in pa_mac_core_old.c, and the newer, default implementation +is in pa_mac_core.c. +Only pa_mac_core.c is currently developed and supported as it uses apple's +current core audio technology. To select use the old implementation, replace +pa_mac_core.c with pa_mac_core_old.c (eg. "cp pa_mac_core_auhal.c +pa_mac_core.c"), then run configure and make as usual. + +---------------------------------------- + +Notes on Original implementation: by Phil Burk and Darren Gibbs -Document last updated March 20, 2002 +Last updated March 20, 2002 WHAT WORKS @@ -18,7 +33,7 @@ KNOWN BUGS OR LIMITATIONS We do not yet support simultaneous input and output on different devices. Note that some CoreAudio devices like the Roland UH30 look like one device but are actually two different CoreAudio devices. The -BuiltIn audio is typically one CoreAudio device. +Built-In audio is typically one CoreAudio device. Mono doesn't work. @@ -32,3 +47,99 @@ input, output or both. When we query devices, we first get a list of CoreAudio devices. Then we scan the list and add a PortAudio device for each CoreAudio device that supports input. Then we make a scan for output devices. + +------------------------------------------- + +Notes on Newer/Default AUHAL implementation: + +by Bjorn Roche + +Last Updated December 9, 2005 + +Principle of Operation: + +This implementation uses AUHAL for audio I/O. To some extent, it also +operates at the "HAL" Layer, though this behavior can be limited by +platform specific flags (see pa_mac_core.h for details). The default +settings should be reasonable: they don't change the SR of the device and +don't cause interruptions if other devices are using the device. + +Major Software Elements Used: Apple's HAL AUs provide output SR +conversion transparently, however, only on output, so this +implementation uses AudioConverters to convert the sample rate on input. +A PortAudio ring buffer is used to buffer input when sample rate +conversion is required or when separate audio units are used for duplex +IO. Finally, a PortAudio buffer processor is used to convert formats and +provide additional buffers if needed. Internally, interleaved floating +point data streams are used exclusively - the audio unit converts from +the audio hardware's native format to interleaved float PCM and +PortAudio's Buffer processor is used for conversion to user formats. + +Simplex Input: Simplex input uses a single callback. If sample rate +conversion is required, a ring buffer and AudioConverter are used as +well. + +Simplex output: Simplex output uses a single callback. No ring buffer or +audio converter is used because AUHAL does its own output SR conversion. + +Duplex, one device (no SR conversion): When one device is used, a single +callback is used. This achieves very low latency. + +Duplex, separate devices or SR conversion: When SR conversion is +required, data must be buffered before it is converted and data is not +always available at the same times on input and output, so SR conversion +requires the same treatment as separate devices. The input callback +reads data and puts it in the ring buffer. The output callback reads the +data off the ring buffer, into an audio converter and finally to the +buffer processor. + +Platform Specific Options: + +By using the flags in pa_mac_core.h, the user may specify several options. +For example, the user can specify the sample-rate conversion quality, and +the extent to which PA will attempt to "play nice" and to what extent it +will interrupt other apps to improve performance. For example, if 44100 Hz +sample rate is requested but the device is set at 48000 Hz, PA can either +change the device for optimal playback ("Pro" mode), which may interrupt +other programs playing back audio, or simple use a sample-rate coversion, +which allows for friendlier sharing of the device ("Play Nice" mode). + + +Known issues: + +- Latency: Latency settings are ignored in most cases. Exceptions are when +doing I/O between different devices and as a hint for selecting a realtively +low or relatively high latency in conjunction with +paHostFramesPerBufferUnspecified. Latency settings are always automatically +bound to "safe" values, however, so setting extreme values here should not be +an issue. + +- Buffer Size: paHostFramesPerBufferUnspecified and specific host buffer sizes +are supported. paHostFramesPerBufferUnspecified works best in "pro" mode, +where the buffer size and sample rate of the audio device is most likely +to match the expected values. + +- Timing info. It reports on stream time, but I'm probably doing something +wrong since patest_sine_time often reports negative latency numbers. + +- xrun detection: The only xrun detection performed is when reading +and writing the ring buffer. There is probably more that can be done. + +- abort/stop issues: stopping a stream is always a complete operation, +but latency should be low enough to make the lack of a separate abort +unnecessary. Apple clarifies its AudioOutputUnitStop() call here: +http://lists.apple.com/archives/coreaudio-api/2005/Dec/msg00055.html + +- blocking interface: Not implemented. + +- multichannel: It has been tested successfully on multichannel hardware +from MOTU: traveler and 896HD. + +- sample rate conversion quality: By default, SR conversion is the maximum +available. This can be tweaked using flags pa_mac_core.h. Note that the AU +render quyality property is used to set the sample rat conversion quality +as "documented" here: +http://lists.apple.com/archives/coreaudio-api/2004/Jan/msg00141.html + +- x86: I haven't tested it on an x86 Mac myself, but users have reported +being able to comiple and run it. diff --git a/pa_mac_core/pa_mac_core.c b/pa_mac_core/pa_mac_core.c index e608402..04a2be3 100644 --- a/pa_mac_core/pa_mac_core.c +++ b/pa_mac_core/pa_mac_core.c @@ -1,13 +1,19 @@ /* - * $Id$ - * pa_mac_core.c - * Implementation of PortAudio for Mac OS X Core Audio + * This is the AUHAL implementation of portaudio. Hopefully this will + * one day replace pa_mac_core. * - * PortAudio Portable Real-Time Audio Library - * Latest Version at: http://www.portaudio.com + * Written by Bjorn Roche of XO Audio LLC, from PA skeleton code. + * Portions copied from code by Dominic Mazzoni (who wrote a HAL implementation) * - * Authors: Ross Bencina and Phil Burk - * Copyright (c) 1999-2000 Ross Bencina and Phil Burk + * Dominic's code was based on code by Phil Burk, Darren Gibbs, + * Gord Peters, Stephane Letz, and Greg Pfiel. + * + * Bjorn Roche and XO Audio LLC reserve no rights to this code. + * The maintainers of PortAudio may redistribute and modify the code and + * licenses as they deam appropriate. + * + * 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 @@ -31,1231 +37,2073 @@ * 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. - * - * CHANGE HISTORY: - - 3.29.2001 - Phil Burk - First pass... converted from Window MME code with help from Darren. - 3.30.2001 - Darren Gibbs - Added more support for dynamically querying device info. - 12.7.2001 - Gord Peters - Tweaks to compile on PA V17 and OS X 10.1 - 2.7.2002 - Darren and Phil - fixed isInput so GetProperty works better, - fixed device queries for numChannels and sampleRates, - one CoreAudio device now maps to separate input and output PaDevices, - audio input works if using same CoreAudio device (some HW devices make separate CoreAudio devices). - 2.22.2002 - Stephane Letz - Explicit cast needed for compilation with Code Warrior 7 - 3.19.2002 - Phil Burk - Added paInt16, paInt8, format using new "pa_common/pa_convert.c" file. - Return error if opened in mono mode cuz not supported. - Add support for Pa_GetCPULoad(); - Fixed timestamp in callback and Pa_StreamTime() (Thanks n++k for the advice!) - Check for invalid sample rates and return an error. - Check for getenv("PA_MIN_LATEWNCY_MSEC") to set latency externally. - Better error checking for invalid channel counts and invalid devices. - 3.29.2002 - Phil Burk - Fixed Pa_GetCPULoad() for small buffers. - 3.31.2002 - Phil Burk - Use getrusage() instead of gettimeofday() for CPU Load calculation. - -TODO: -O- how do mono output? -O- FIFO between input and output callbacks if different devices, like in pa_mac.c + */ + +/** + @file pa_mac_core + @author Bjorn Roche + @brief AUHAL implementation of PortAudio */ -#include -#include -#include -#include -#include +/* FIXME: not all error conditions call PaUtil_SetLastHostErrorInfo() + * PaMacCore_SetError() will do this. + */ -#include "portaudio.h" -#include "pa_host.h" -#include "pa_trace.h" +#include /* strlen(), memcmp() etc. */ -/************************************************* Constants ********/ +#include +#include -/* To trace program, enable TRACE_REALTIME_EVENTS in pa_trace.h */ -#define PA_TRACE_RUN (0) -#define PA_TRACE_START_STOP (1) -#define PA_MIN_LATENCY_MSEC (8) -#define MIN_TIMEOUT_MSEC (1000) +#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 "../pablio/ringbuffer.h" +#include "pa_mac_core.h" +#include "pa_mac_core_blocking.h" -#define PRINT(x) { printf x; fflush(stdout); } -#define ERR_RPT(x) PRINT(x) -#define DBUG(x) /* PRINT(x) /**/ -#define DBUGX(x) /* PRINT(x) /**/ +#ifndef MIN +#define MIN(a, b) (((a)<(b))?(a):(b)) +#endif -// define value of isInput passed to CoreAudio routines -#define IS_INPUT (true) -#define IS_OUTPUT (false) +#ifndef MAX +#define MAX(a, b) (((a)<(b))?(b):(a)) +#endif -/************************************************************** - * Structure for internal host specific stream data. - * This is allocated on a per stream basis. - */ -typedef struct PaHostSoundControl -{ - AudioDeviceID pahsc_AudioDeviceID; // Must be the same for input and output for now. - /* Input -------------- */ - int pahsc_BytesPerUserNativeInputBuffer; /* native buffer size in bytes per user chunk */ - /* Output -------------- */ - int pahsc_BytesPerUserNativeOutputBuffer; /* native buffer size in bytes per user chunk */ - /* Init Time -------------- */ - int pahsc_FramesPerHostBuffer; - int pahsc_UserBuffersPerHostBuffer; - /* For measuring CPU utilization. */ - struct rusage pahsc_EntryRusage; - double pahsc_InverseMicrosPerHostBuffer; /* 1/Microseconds of real-time audio per user buffer. */ -} -PaHostSoundControl; +/* prototypes for functions declared in this file */ -/************************************************************** - * Structure for internal extended device info. - * There will be one or two PortAudio devices for each Core Audio device: - * one input and or one output. - */ -typedef struct PaHostDeviceInfo +#ifdef __cplusplus +extern "C" { - PaDeviceInfo paInfo; - AudioDeviceID audioDeviceID; -} -PaHostDeviceInfo; - -/************************************************* Shared Data ********/ -/* FIXME - put Mutex around this shared data. */ -static int sNumPaDevices = 0; /* Total number of PaDeviceInfos */ -static int sNumInputDevices = 0; /* Total number of input PaDeviceInfos */ -static int sNumOutputDevices = 0; -static PaHostDeviceInfo *sDeviceInfos = NULL; -static int sDefaultInputDeviceID = paNoDevice; -static int sDefaultOutputDeviceID = paNoDevice; -static int sPaHostError = 0; - -static int sNumCoreDevices = 0; -static AudioDeviceID *sCoreDeviceIDs; // Array of Core AudioDeviceIDs +#endif /* __cplusplus */ -static const char sMapperSuffixInput[] = " - Input"; -static const char sMapperSuffixOutput[] = " - Output"; +PaError PaMacCore_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index ); -/* We index the input devices first, then the output devices. */ -#define LOWEST_INPUT_DEVID (0) -#define HIGHEST_INPUT_DEVID (sNumInputDevices - 1) -#define LOWEST_OUTPUT_DEVID (sNumInputDevices) -#define HIGHEST_OUTPUT_DEVID (sNumPaDevices - 1) - -/************************************************* Macros ********/ - -/************************************************* Prototypes **********/ +#ifdef __cplusplus +} +#endif /* __cplusplus */ -static PaError Pa_QueryDevices( void ); -PaError PaHost_GetTotalBufferFrames( internalPortAudioStream *past ); +#define ERR(mac_error) PaMacCore_SetError(mac_error, __LINE__, 1 ) +#define WARNING(mac_error) PaMacCore_SetError(mac_error, __LINE__, 0 ) -static int PaHost_ScanDevices( Boolean isInput ); -static int PaHost_QueryDeviceInfo( PaHostDeviceInfo *hostDeviceInfo, int coreDeviceIndex, Boolean isInput ); +/* Help keep track of AUHAL element numbers */ +#define INPUT_ELEMENT (1) +#define OUTPUT_ELEMENT (0) -static PaDeviceID Pa_QueryDefaultInputDevice( void ); -static PaDeviceID Pa_QueryDefaultOutputDevice( void ); -static void PaHost_CalcHostBufferSize( internalPortAudioStream *past ); +/* Normal level of debugging: fine for most apps that don't mind the occational warning being printf'ed */ +/* + */ +#define MAC_CORE_DEBUG +#ifdef MAC_CORE_DEBUG +# define DBUG(MSG) do { printf("||PaMacCore (AUHAL)|| "); printf MSG ; fflush(stdout); } while(0) +#else +# define DBUG(MSG) +#endif -/********************************* BEGIN CPU UTILIZATION MEASUREMENT ****/ -static void Pa_StartUsageCalculation( internalPortAudioStream *past ) -{ - PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; - if( pahsc == NULL ) return; - /* Query user CPU timer for usage analysis and to prevent overuse of CPU. */ - getrusage( RUSAGE_SELF, &pahsc->pahsc_EntryRusage ); -} +/* Verbose Debugging: useful for developement */ +/* +#define MAC_CORE_VERBOSE_DEBUG +*/ +#ifdef MAC_CORE_VERBOSE_DEBUG +# define VDBUG(MSG) do { printf("||PaMacCore (v )|| "); printf MSG ; fflush(stdout); } while(0) +#else +# define VDBUG(MSG) +#endif -static long SubtractTime_AminusB( struct timeval *timeA, struct timeval *timeB ) -{ - long secs = timeA->tv_sec - timeB->tv_sec; - long usecs = secs * 1000000; - usecs += (timeA->tv_usec - timeB->tv_usec); - return usecs; -} +/* Very Verbose Debugging: Traces every call. */ +/* +#define MAC_CORE_VERY_VERBOSE_DEBUG + */ +#ifdef MAC_CORE_VERY_VERBOSE_DEBUG +# define VVDBUG(MSG) do { printf("||PaMacCore (vv)|| "); printf MSG ; fflush(stdout); } while(0) +#else +# define VVDBUG(MSG) +#endif -/****************************************************************************** -** Measure fractional CPU load based on real-time it took to calculate -** buffers worth of output. -*/ -static void Pa_EndUsageCalculation( internalPortAudioStream *past ) +#define RING_BUFFER_ADVANCE_DENOMINATOR (4) + +/* Special purpose ring buffer just for pa_mac_core input processing. */ +/* #include "pa_mac_core_input_ring_buffer.c" */ +#include "../pablio/ringbuffer.c" + +/* Some utilities that sort of belong here, but were getting too unweildy */ +#include "pa_mac_core_utilities.c" + + +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 void setStreamStartTime( PaStream *stream ); +static OSStatus AudioIOProc( void *inRefCon, + AudioUnitRenderActionFlags *ioActionFlags, + const AudioTimeStamp *inTimeStamp, + UInt32 inBusNumber, + UInt32 inNumberFrames, + AudioBufferList *ioData ); +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 ); +/* PaMacAUHAL - host api datastructure specific to this implementation */ +typedef struct { - struct rusage currentRusage; - long usecsElapsed; - double newUsage; + PaUtilHostApiRepresentation inheritedHostApiRep; + PaUtilStreamInterface callbackStreamInterface; + PaUtilStreamInterface blockingStreamInterface; -#define LOWPASS_COEFFICIENT_0 (0.95) -#define LOWPASS_COEFFICIENT_1 (0.99999 - LOWPASS_COEFFICIENT_0) + PaUtilAllocationGroup *allocations; - PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; - if( pahsc == NULL ) return; - - if( getrusage( RUSAGE_SELF, ¤tRusage ) == 0 ) - { - usecsElapsed = SubtractTime_AminusB( ¤tRusage.ru_utime, &pahsc->pahsc_EntryRusage.ru_utime ); - - /* Use inverse because it is faster than the divide. */ - newUsage = usecsElapsed * pahsc->pahsc_InverseMicrosPerHostBuffer; - - past->past_Usage = (LOWPASS_COEFFICIENT_0 * past->past_Usage) + - (LOWPASS_COEFFICIENT_1 * newUsage); - } + /* implementation specific data goes here */ + long devCount; + AudioDeviceID *devIds; /*array of all audio devices*/ + AudioDeviceID defaultIn; + AudioDeviceID defaultOut; } -/****************************************** END CPU UTILIZATION *******/ +PaMacAUHAL; -/************************************************************************/ -static PaDeviceID Pa_QueryDefaultInputDevice( void ) +/* stream data structure specifically for this implementation */ +typedef struct PaMacCoreStream { - OSStatus err = noErr; - UInt32 count; - int i; - AudioDeviceID tempDeviceID = kAudioDeviceUnknown; - PaDeviceID defaultDeviceID = paNoDevice; - - // get the default output device for the HAL - // it is required to pass the size of the data to be returned - count = sizeof(tempDeviceID); - err = AudioHardwareGetProperty( kAudioHardwarePropertyDefaultInputDevice, &count, (void *) &tempDeviceID); - if (err != noErr) goto Bail; - - // scan input devices to see which one matches this device - defaultDeviceID = paNoDevice; - for( i=LOWEST_INPUT_DEVID; i<=HIGHEST_INPUT_DEVID; i++ ) - { - DBUG(("Pa_QueryDefaultInputDevice: i = %d, aDevId = %d\n", i, sDeviceInfos[i].audioDeviceID )); - if( sDeviceInfos[i].audioDeviceID == tempDeviceID ) - { - defaultDeviceID = i; - break; - } - } -Bail: - return defaultDeviceID; + PaUtilStreamRepresentation streamRepresentation; + PaUtilCpuLoadMeasurer cpuLoadMeasurer; + PaUtilBufferProcessor bufferProcessor; + + /* implementation specific data goes here */ + bool bufferProcessorIsInitialized; + AudioUnit inputUnit; + AudioUnit outputUnit; + AudioDeviceID inputDevice; + AudioDeviceID outputDevice; + size_t userInChan; + size_t userOutChan; + size_t inputFramesPerBuffer; + size_t outputFramesPerBuffer; + PaMacBlio blio; + /* We use this ring buffer when input and out devs are different. */ + RingBuffer inputRingBuffer; + /* We may need to do SR conversion on input. */ + AudioConverterRef inputSRConverter; + /* We need to preallocate an inputBuffer for reading data. */ + AudioBufferList inputAudioBufferList; + AudioTimeStamp startTime; + volatile PaStreamCallbackFlags xrunFlags; + volatile enum { + STOPPED = 0, /* playback is completely stopped, + and the user has called StopStream(). */ + CALLBACK_STOPPED = 1, /* callback has requested stop, + but user has not yet called StopStream(). */ + STOPPING = 2, /* The stream is in the process of closing. + This state is just used internally; + externally it is indistinguishable from + ACTIVE.*/ + ACTIVE = 3 /* The stream is active and running. */ + } state; + double sampleRate; } - -/************************************************************************/ -static PaDeviceID Pa_QueryDefaultOutputDevice( void ) +PaMacCoreStream; + +static PaError GetChannelInfo( PaMacAUHAL *auhalHostApi, + PaDeviceInfo *deviceInfo, + AudioDeviceID macCoreDeviceId, + int isInput); + +static PaError OpenAndSetupOneAudioUnit( + const PaStreamParameters *inStreamParams, + const PaStreamParameters *outStreamParams, + const unsigned long requestedFramesPerBuffer, + unsigned long *actualInputFramesPerBuffer, + unsigned long *actualOutputFramesPerBuffer, + const PaMacAUHAL *auhalHostApi, + AudioUnit *audioUnit, + AudioConverterRef *srConverter, + AudioDeviceID *audioDevice, + const double sampleRate, + void *refCon ); + +/* for setting errors. */ +#define PA_AUHAL_SET_LAST_HOST_ERROR( errorCode, errorText ) \ + PaUtil_SetLastHostErrorInfo( paInDevelopment, errorCode, errorText ) + + +/*currently, this is only used in initialization, but it might be modified + to be used when the list of devices changes.*/ +static PaError gatherDeviceInfo(PaMacAUHAL *auhalHostApi) { - OSStatus err = noErr; - UInt32 count; - int i; - AudioDeviceID tempDeviceID = kAudioDeviceUnknown; - PaDeviceID defaultDeviceID = paNoDevice; - - // get the default output device for the HAL - // it is required to pass the size of the data to be returned - count = sizeof(tempDeviceID); - err = AudioHardwareGetProperty( kAudioHardwarePropertyDefaultOutputDevice, &count, (void *) &tempDeviceID); - if (err != noErr) goto Bail; - - // scan output devices to see which one matches this device - defaultDeviceID = paNoDevice; - for( i=LOWEST_OUTPUT_DEVID; i<=HIGHEST_OUTPUT_DEVID; i++ ) + UInt32 size; + UInt32 propsize; + VVDBUG(("gatherDeviceInfo()\n")); + /* -- free any previous allocations -- */ + if( auhalHostApi->devIds ) + PaUtil_GroupFreeMemory(auhalHostApi->allocations, auhalHostApi->devIds); + auhalHostApi->devIds = NULL; + + /* -- figure out how many devices there are -- */ + AudioHardwareGetPropertyInfo( kAudioHardwarePropertyDevices, + &propsize, + NULL ); + auhalHostApi->devCount = propsize / sizeof( AudioDeviceID ); + + VDBUG( ( "Found %ld device(s).\n", auhalHostApi->devCount ) ); + + /* -- copy the device IDs -- */ + auhalHostApi->devIds = (AudioDeviceID *)PaUtil_GroupAllocateMemory( + auhalHostApi->allocations, + propsize ); + if( !auhalHostApi->devIds ) + return paInsufficientMemory; + AudioHardwareGetProperty( kAudioHardwarePropertyDevices, + &propsize, + auhalHostApi->devIds ); +#ifdef MAC_CORE_VERBOSE_DEBUG { - DBUG(("Pa_QueryDefaultOutputDevice: i = %d, aDevId = %d\n", i, sDeviceInfos[i].audioDeviceID )); - if( sDeviceInfos[i].audioDeviceID == tempDeviceID ) - { - defaultDeviceID = i; - break; - } + int i; + for( i=0; idevCount; ++i ) + printf( "Device %d\t: %ld\n", i, auhalHostApi->devIds[i] ); } -Bail: - return defaultDeviceID; -} +#endif -/******************************************************************/ -static PaError Pa_QueryDevices( void ) -{ - OSStatus err = noErr; - UInt32 outSize; - Boolean outWritable; - int numBytes; - - // find out how many Core Audio devices there are, if any - err = AudioHardwareGetPropertyInfo(kAudioHardwarePropertyDevices, &outSize, &outWritable); - if (err != noErr) - ERR_RPT(("Couldn't get info about list of audio devices\n")); - - // calculate the number of device available - sNumCoreDevices = outSize / sizeof(AudioDeviceID); - - // Bail if there aren't any devices - if (sNumCoreDevices < 1) - ERR_RPT(("No Devices Available\n")); - - // make space for the devices we are about to get - sCoreDeviceIDs = (AudioDeviceID *)malloc(outSize); - - // get an array of AudioDeviceIDs - err = AudioHardwareGetProperty(kAudioHardwarePropertyDevices, &outSize, (void *)sCoreDeviceIDs); - if (err != noErr) - ERR_RPT(("Couldn't get list of audio device IDs\n")); - - // Allocate structures to hold device info pointers. - // There will be a maximum of two Pa devices per Core Audio device, input and/or output. - numBytes = sNumCoreDevices * 2 * sizeof(PaHostDeviceInfo); - sDeviceInfos = (PaHostDeviceInfo *) PaHost_AllocateFastMemory( numBytes ); - if( sDeviceInfos == NULL ) return paInsufficientMemory; - - // Scan all the Core Audio devices to see which support input and allocate a - // PaHostDeviceInfo structure for each one. - PaHost_ScanDevices( IS_INPUT ); - sNumInputDevices = sNumPaDevices; - // Now scan all the output devices. - PaHost_ScanDevices( IS_OUTPUT ); - sNumOutputDevices = sNumPaDevices - sNumInputDevices; - - // Figure out which of the devices that we scanned is the default device. - sDefaultInputDeviceID = Pa_QueryDefaultInputDevice(); - sDefaultOutputDeviceID = Pa_QueryDefaultOutputDevice(); + size = sizeof(AudioDeviceID); + auhalHostApi->defaultIn = kAudioDeviceUnknown; + auhalHostApi->defaultOut = kAudioDeviceUnknown; + + /* determine the default device. */ + /* I am not sure how these calls to AudioHardwareGetProperty() + could fail, but in case they do, we use the first available + device as the default. */ + if( 0 != AudioHardwareGetProperty(kAudioHardwarePropertyDefaultInputDevice, + &size, + &auhalHostApi->defaultIn) ) { + int i; + auhalHostApi->defaultIn = kAudioDeviceUnknown; + VDBUG(("Failed to get default input device from OS.")); + VDBUG((" I will substitute the first available input Device.")); + for( i=0; idevCount; ++i ) { + PaDeviceInfo devInfo; + if( 0 != GetChannelInfo( auhalHostApi, &devInfo, + auhalHostApi->devIds[i], TRUE ) ) + if( devInfo.maxInputChannels ) { + auhalHostApi->defaultIn = auhalHostApi->devIds[i]; + break; + } + } + } + if( 0 != AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, + &size, + &auhalHostApi->defaultOut) ) { + int i; + auhalHostApi->defaultIn = kAudioDeviceUnknown; + VDBUG(("Failed to get default output device from OS.")); + VDBUG((" I will substitute the first available output Device.")); + for( i=0; idevCount; ++i ) { + PaDeviceInfo devInfo; + if( 0 != GetChannelInfo( auhalHostApi, &devInfo, + auhalHostApi->devIds[i], FALSE ) ) + if( devInfo.maxOutputChannels ) { + auhalHostApi->defaultOut = auhalHostApi->devIds[i]; + break; + } + } + } + + VDBUG( ( "Default in : %ld\n", auhalHostApi->defaultIn ) ); + VDBUG( ( "Default out: %ld\n", auhalHostApi->defaultOut ) ); return paNoError; } -/************************************************************************************/ -long Pa_GetHostError() +static PaError GetChannelInfo( PaMacAUHAL *auhalHostApi, + PaDeviceInfo *deviceInfo, + AudioDeviceID macCoreDeviceId, + int isInput) { - return sPaHostError; -} + UInt32 propSize; + PaError err = paNoError; + UInt32 i; + int numChannels = 0; + AudioBufferList *buflist; + UInt32 frameLatency; -/*************************************************************************/ -int Pa_CountDevices() -{ - if( sNumPaDevices <= 0 ) Pa_Initialize(); - return sNumPaDevices; -} + VVDBUG(("GetChannelInfo()\n")); -/*************************************************************************/ -/* Allocate a string containing the device name. */ -static char *PaHost_DeviceNameFromID(AudioDeviceID deviceID, Boolean isInput ) -{ - OSStatus err = noErr; - UInt32 outSize; - Boolean outWritable; - char *deviceName = nil; - - // query size of name - err = AudioDeviceGetPropertyInfo(deviceID, 0, isInput, kAudioDevicePropertyDeviceName, &outSize, &outWritable); - if (err == noErr) - { - deviceName = (char*)malloc( outSize + 1); - if( deviceName ) - { - err = AudioDeviceGetProperty(deviceID, 0, isInput, kAudioDevicePropertyDeviceName, &outSize, deviceName); - if (err != noErr) - ERR_RPT(("Couldn't get audio device name.\n")); - } - } + /* Get the number of channels from the stream configuration. + Fail if we can't get this. */ - return deviceName; -} + err = ERR(AudioDeviceGetPropertyInfo(macCoreDeviceId, 0, isInput, kAudioDevicePropertyStreamConfiguration, &propSize, NULL)); + if (err) + return err; -/*************************************************************************/ -// An AudioStreamBasicDescription is passed in to query whether or not -// the format is supported. A kAudioDeviceUnsupportedFormatError will -// be returned if the format is not supported and kAudioHardwareNoError -// will be returned if it is supported. AudioStreamBasicDescription -// fields set to 0 will be ignored in the query, but otherwise values -// must match exactly. + buflist = PaUtil_AllocateMemory(propSize); + err = ERR(AudioDeviceGetProperty(macCoreDeviceId, 0, isInput, kAudioDevicePropertyStreamConfiguration, &propSize, buflist)); + if (err) + return err; -Boolean deviceDoesSupportFormat(AudioDeviceID deviceID, AudioStreamBasicDescription *desc, Boolean isInput ) -{ - OSStatus err = noErr; - UInt32 outSize; + /*FIXME: dealocate buflist*/ - outSize = sizeof(*desc); - err = AudioDeviceGetProperty(deviceID, 0, isInput, kAudioDevicePropertyStreamFormatSupported, &outSize, desc); + for (i = 0; i < buflist->mNumberBuffers; ++i) + numChannels += buflist->mBuffers[i].mNumberChannels; - if (err == kAudioHardwareNoError) - return true; + if (isInput) + deviceInfo->maxInputChannels = numChannels; else - return false; -} - -/*************************************************************************/ -// return an error string -char* coreAudioErrorString (int errCode ) -{ - char *str; - - switch (errCode) + deviceInfo->maxOutputChannels = numChannels; + + if (numChannels > 0) /* do not try to retrieve the latency if there is no channels. */ { - case kAudioHardwareUnspecifiedError: - str = "kAudioHardwareUnspecifiedError"; - break; - case kAudioHardwareNotRunningError: - str = "kAudioHardwareNotRunningError"; - break; - case kAudioHardwareUnknownPropertyError: - str = "kAudioHardwareUnknownPropertyError"; - break; - case kAudioDeviceUnsupportedFormatError: - str = "kAudioDeviceUnsupportedFormatError"; - break; - case kAudioHardwareBadPropertySizeError: - str = "kAudioHardwareBadPropertySizeError"; - break; - case kAudioHardwareIllegalOperationError: - str = "kAudioHardwareIllegalOperationError"; - break; - default: - str = "Unknown CoreAudio Error!"; - break; + /* Get the latency. Don't fail if we can't get this. */ + /* default to something reasonable */ + deviceInfo->defaultLowInputLatency = .01; + deviceInfo->defaultHighInputLatency = .10; + deviceInfo->defaultLowOutputLatency = .01; + deviceInfo->defaultHighOutputLatency = .10; + propSize = sizeof(UInt32); + err = WARNING(AudioDeviceGetProperty(macCoreDeviceId, 0, isInput, kAudioDevicePropertyLatency, &propSize, &frameLatency)); + if (!err) + { + double secondLatency = frameLatency / deviceInfo->defaultSampleRate; + if (isInput) + { + deviceInfo->defaultLowInputLatency = 3 * secondLatency; + deviceInfo->defaultHighInputLatency = 3 * 10 * secondLatency; + } + else + { + deviceInfo->defaultLowOutputLatency = 3 * secondLatency; + deviceInfo->defaultHighOutputLatency = 3 * 10 * secondLatency; + } + } } - - return str; + return paNoError; } -/************************************************************************* -** PaDeviceInfo structures have already been created -** so just return the pointer. -** -*/ -const PaDeviceInfo* Pa_GetDeviceInfo( PaDeviceID id ) +static PaError InitializeDeviceInfo( PaMacAUHAL *auhalHostApi, + PaDeviceInfo *deviceInfo, + AudioDeviceID macCoreDeviceId, + PaHostApiIndex hostApiIndex ) { - if( id < 0 || id >= sNumPaDevices ) - return NULL; + Float64 sampleRate; + char *name; + PaError err = paNoError; + UInt32 propSize; + + VVDBUG(("InitializeDeviceInfo(): macCoreDeviceId=%ld\n", macCoreDeviceId)); + + memset(deviceInfo, 0, sizeof(deviceInfo)); + + deviceInfo->structVersion = 2; + deviceInfo->hostApi = hostApiIndex; + + /* Get the device name. Fail if we can't get it. */ + err = ERR(AudioDeviceGetPropertyInfo(macCoreDeviceId, 0, 0, kAudioDevicePropertyDeviceName, &propSize, NULL)); + if (err) + return err; + + name = PaUtil_GroupAllocateMemory(auhalHostApi->allocations,propSize); + if ( !name ) + return paInsufficientMemory; + err = ERR(AudioDeviceGetProperty(macCoreDeviceId, 0, 0, kAudioDevicePropertyDeviceName, &propSize, name)); + if (err) + return err; + deviceInfo->name = name; + + /* Try to get the default sample rate. Don't fail if we can't get this. */ + propSize = sizeof(Float64); + err = ERR(AudioDeviceGetProperty(macCoreDeviceId, 0, 0, kAudioDevicePropertyNominalSampleRate, &propSize, &sampleRate)); + if (err) + deviceInfo->defaultSampleRate = 0.0; + else + deviceInfo->defaultSampleRate = sampleRate; - return &sDeviceInfos[id].paInfo; -} + /* Get the maximum number of input and output channels. Fail if we can't get this. */ -/************************************************************************* -** Scan all of the Core Audio devices to see which support input or output. -** Changes sNumDevices, and fills in sDeviceInfos. -*/ -static int PaHost_ScanDevices( Boolean isInput ) -{ - int coreDeviceIndex; - int result; - PaHostDeviceInfo *hostDeviceInfo; - int numAdded = 0; + err = GetChannelInfo(auhalHostApi, deviceInfo, macCoreDeviceId, 1); + if (err) + return err; - for( coreDeviceIndex=0; coreDeviceIndexaudioDeviceID )); - if( result > 0 ) - { - sNumPaDevices += 1; // bump global counter if we got one - numAdded += 1; - } - else if( result < 0 ) return result; - } - return numAdded; + err = GetChannelInfo(auhalHostApi, deviceInfo, macCoreDeviceId, 0); + if (err) + return err; + + return paNoError; } -/************************************************************************* -** Try to fill in the device info for this device. -** Return 1 if a good device that PA can use. -** Return 0 if not appropriate -** or return negative error. -** -*/ -static int PaHost_QueryDeviceInfo( PaHostDeviceInfo *hostDeviceInfo, int coreDeviceIndex, Boolean isInput ) +PaError PaMacCore_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex ) { - OSErr err; - int index; - UInt32 outSize; - AudioStreamBasicDescription formatDesc; - Boolean result; - AudioDeviceID devID; - double *sampleRates = NULL; /* non-const ptr */ - - PaDeviceInfo *deviceInfo = &hostDeviceInfo->paInfo; - double possibleSampleRates[] = {8000.0, 11025.0, 22050.0, 44100.0, 48000.0, 88200.0, 96000.0}; - int maxNumSampleRates = sizeof( possibleSampleRates ) / sizeof( double ); - - deviceInfo->structVersion = 1; - deviceInfo->maxInputChannels = 0; - deviceInfo->maxOutputChannels = 0; - deviceInfo->numSampleRates = -1; - - devID = sCoreDeviceIDs[ coreDeviceIndex ]; - hostDeviceInfo->audioDeviceID = devID; - - // Figure out supported sample rates - // Make room in case device supports all rates. - sampleRates = (double*)PaHost_AllocateFastMemory( maxNumSampleRates * sizeof(double) ); - if( sampleRates == NULL ) return paInsufficientMemory; - - deviceInfo->sampleRates = sampleRates; - deviceInfo->numSampleRates = 0; - - // Loop through the possible sampling rates and check each to see if the device supports it. - for (index = 0; index < maxNumSampleRates; index ++) - { - memset( &formatDesc, 0, sizeof(AudioStreamBasicDescription) ); - formatDesc.mSampleRate = possibleSampleRates[index]; - result = deviceDoesSupportFormat( devID, &formatDesc, isInput ); - - if (result == true) - { - deviceInfo->numSampleRates += 1; - *sampleRates = possibleSampleRates[index]; - sampleRates++; - } - } - // If no sample rates supported, then not a very good device. - if( deviceInfo->numSampleRates == 0 ) goto error; - - // Get data format info from the device. - outSize = sizeof(formatDesc); - err = AudioDeviceGetProperty(devID, 0, isInput, kAudioDevicePropertyStreamFormat, &outSize, &formatDesc); + PaError result = paNoError; + int i; + PaMacAUHAL *auhalHostApi; + PaDeviceInfo *deviceInfoArray; - // If no channels supported, then not a very good device. - if( (err != noErr) || (formatDesc.mChannelsPerFrame == 0) ) goto error; + VVDBUG(("PaMacCore_Initialize(): hostApiIndex=%d\n", hostApiIndex)); - if( isInput ) + auhalHostApi = (PaMacAUHAL*)PaUtil_AllocateMemory( sizeof(PaMacAUHAL) ); + if( !auhalHostApi ) { - deviceInfo->maxInputChannels = formatDesc.mChannelsPerFrame; + result = paInsufficientMemory; + goto error; } - else + + auhalHostApi->allocations = PaUtil_CreateAllocationGroup(); + if( !auhalHostApi->allocations ) { - deviceInfo->maxOutputChannels = formatDesc.mChannelsPerFrame; + result = paInsufficientMemory; + goto error; } - // FIXME - where to put current sample rate?: formatDesc.mSampleRate + auhalHostApi->devIds = NULL; + auhalHostApi->devCount = 0; - // Right now the Core Audio headers only define one formatID: LinearPCM - // Apparently LinearPCM must be Float32 for now. - switch (formatDesc.mFormatID) - { - case kAudioFormatLinearPCM: - deviceInfo->nativeSampleFormats = paFloat32; - - // FIXME - details about the format are in these flags. - // formatDesc.mFormatFlags - - // here are the possibilities - // kLinearPCMFormatFlagIsFloat // set for floating point, clear for integer - // kLinearPCMFormatFlagIsBigEndian // set for big endian, clear for little - // kLinearPCMFormatFlagIsSignedInteger // set for signed integer, clear for unsigned integer, - // only valid if kLinearPCMFormatFlagIsFloat is clear - // kLinearPCMFormatFlagIsPacked // set if the sample bits are packed as closely together as possible, - // clear if they are high or low aligned within the channel - // kLinearPCMFormatFlagIsAlignedHigh // set if the sample bits are placed - break; - - default: - deviceInfo->nativeSampleFormats = paFloat32; // FIXME - break; - } + /* get the info we need about the devices */ + result = gatherDeviceInfo( auhalHostApi ); + if( result != paNoError ) + goto error; - // Get the device name - deviceInfo->name = PaHost_DeviceNameFromID( devID, isInput ); - return 1; + *hostApi = &auhalHostApi->inheritedHostApiRep; + (*hostApi)->info.structVersion = 1; + (*hostApi)->info.type = paCoreAudio; + (*hostApi)->info.name = "Core Audio"; -error: - if( sampleRates != NULL ) free( sampleRates ); - return 0; -} + (*hostApi)->info.defaultInputDevice = paNoDevice; + (*hostApi)->info.defaultOutputDevice = paNoDevice; -/************************************************************************* -** Returns recommended device ID. -** On the PC, the recommended device can be specified by the user 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 ID by using -** the supplied application "pa_devs". -*/ -#define PA_ENV_BUF_SIZE (32) -#define PA_REC_IN_DEV_ENV_NAME ("PA_RECOMMENDED_INPUT_DEVICE") -#define PA_REC_OUT_DEV_ENV_NAME ("PA_RECOMMENDED_OUTPUT_DEVICE") + (*hostApi)->info.deviceCount = 0; -static PaDeviceID PaHost_GetEnvDefaultDeviceID( char *envName ) -{ -#if 0 - UInt32 hresult; - char envbuf[PA_ENV_BUF_SIZE]; - PaDeviceID recommendedID = paNoDevice; - - /* Let user determine default device by setting environment variable. */ - hresult = GetEnvironmentVariable( envName, envbuf, PA_ENV_BUF_SIZE ); - if( (hresult > 0) && (hresult < PA_ENV_BUF_SIZE) ) + if( auhalHostApi->devCount > 0 ) { - recommendedID = atoi( envbuf ); - } + (*hostApi)->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory( + auhalHostApi->allocations, sizeof(PaDeviceInfo*) * auhalHostApi->devCount); + if( !(*hostApi)->deviceInfos ) + { + result = paInsufficientMemory; + goto error; + } - return recommendedID; -#endif - return paNoDevice; -} + /* allocate all device info structs in a contiguous block */ + deviceInfoArray = (PaDeviceInfo*)PaUtil_GroupAllocateMemory( + auhalHostApi->allocations, sizeof(PaDeviceInfo) * auhalHostApi->devCount ); + if( !deviceInfoArray ) + { + result = paInsufficientMemory; + goto error; + } -static PaError Pa_MaybeQueryDevices( void ) -{ - if( sNumPaDevices == 0 ) - { - return Pa_QueryDevices(); + for( i=0; i < auhalHostApi->devCount; ++i ) + { + int err; + err = InitializeDeviceInfo( auhalHostApi, &deviceInfoArray[i], + auhalHostApi->devIds[i], + hostApiIndex ); + if (err == paNoError) + { /* copy some info and set the defaults */ + (*hostApi)->deviceInfos[(*hostApi)->info.deviceCount] = &deviceInfoArray[i]; + if (auhalHostApi->devIds[i] == auhalHostApi->defaultIn) + (*hostApi)->info.defaultInputDevice = (*hostApi)->info.deviceCount; + if (auhalHostApi->devIds[i] == auhalHostApi->defaultOut) + (*hostApi)->info.defaultOutputDevice = (*hostApi)->info.deviceCount; + (*hostApi)->info.deviceCount++; + } + else + { /* there was an error. we need to shift the devices down, so we ignore this one */ + int j; + auhalHostApi->devCount--; + for( j=i; jdevCount; ++j ) + auhalHostApi->devIds[j] = auhalHostApi->devIds[j+1]; + i--; + } + } } - return 0; -} -/********************************************************************** -** Check for environment variable, else query devices and use result. -*/ -PaDeviceID Pa_GetDefaultInputDeviceID( void ) -{ - PaError result; - result = PaHost_GetEnvDefaultDeviceID( PA_REC_IN_DEV_ENV_NAME ); - if( result < 0 ) - { - result = Pa_MaybeQueryDevices(); - if( result < 0 ) return result; - result = sDefaultInputDeviceID; - } + (*hostApi)->Terminate = Terminate; + (*hostApi)->OpenStream = OpenStream; + (*hostApi)->IsFormatSupported = IsFormatSupported; + + PaUtil_InitializeStreamInterface( &auhalHostApi->callbackStreamInterface, + CloseStream, StartStream, + StopStream, AbortStream, IsStreamStopped, + IsStreamActive, + GetStreamTime, GetStreamCpuLoad, + PaUtil_DummyRead, PaUtil_DummyWrite, + PaUtil_DummyGetReadAvailable, + PaUtil_DummyGetWriteAvailable ); + + PaUtil_InitializeStreamInterface( &auhalHostApi->blockingStreamInterface, + CloseStream, StartStream, + StopStream, AbortStream, IsStreamStopped, + IsStreamActive, + GetStreamTime, PaUtil_DummyGetCpuLoad, + ReadStream, WriteStream, + GetStreamReadAvailable, + GetStreamWriteAvailable ); + return result; -} -PaDeviceID Pa_GetDefaultOutputDeviceID( void ) -{ - PaError result; - result = PaHost_GetEnvDefaultDeviceID( PA_REC_OUT_DEV_ENV_NAME ); - if( result < 0 ) +error: + if( auhalHostApi ) { - result = Pa_MaybeQueryDevices(); - if( result < 0 ) return result; - result = sDefaultOutputDeviceID; + if( auhalHostApi->allocations ) + { + PaUtil_FreeAllAllocations( auhalHostApi->allocations ); + PaUtil_DestroyAllocationGroup( auhalHostApi->allocations ); + } + + PaUtil_FreeMemory( auhalHostApi ); } return result; } -/********************************************************************** -** Initialize Host dependant part of API. -*/ -PaError PaHost_Init( void ) +static void Terminate( struct PaUtilHostApiRepresentation *hostApi ) { - return Pa_MaybeQueryDevices(); -} + PaMacAUHAL *auhalHostApi = (PaMacAUHAL*)hostApi; -/********************************************************************** -** Fill any available output buffers and use any available -** input buffers by calling user callback. -*/ -static PaError Pa_TimeSlice( internalPortAudioStream *past, const AudioBufferList* inInputData, - AudioBufferList* outOutputData ) -{ - PaError result = 0; - char *inputNativeBufferfPtr = NULL; - char *outputNativeBufferfPtr = NULL; - int i; - int buffersProcessed = 0; - int done = 0; - PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; - if( pahsc == NULL ) return paInternalError; - - past->past_NumCallbacks += 1; - -#if PA_TRACE_RUN - AddTraceMessage("Pa_TimeSlice: past_NumCallbacks ", past->past_NumCallbacks ); -#endif + VVDBUG(("Terminate()\n")); - Pa_StartUsageCalculation( past ); + /* + IMPLEMENT ME: + - clean up any resources not handled by the allocation group + TODO: Double check that everything is handled by alloc group + */ - /* If we are using output, then we need an empty output buffer. */ - if( past->past_NumOutputChannels > 0 ) + if( auhalHostApi->allocations ) { - outputNativeBufferfPtr = (char*)outOutputData->mBuffers[0].mData; + PaUtil_FreeAllAllocations( auhalHostApi->allocations ); + PaUtil_DestroyAllocationGroup( auhalHostApi->allocations ); } - /* If we are using input, then we need a full input buffer. */ - if( past->past_NumInputChannels > 0 ) - { - inputNativeBufferfPtr = (char*)inInputData->mBuffers[0].mData; - } + PaUtil_FreeMemory( auhalHostApi ); +} - buffersProcessed += 1; - /* Each host buffer contains multiple user buffers so do them all now. */ - for( i=0; ipahsc_UserBuffersPerHostBuffer; i++ ) +static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi, + const PaStreamParameters *inputParameters, + const PaStreamParameters *outputParameters, + double sampleRate ) +{ + int inputChannelCount, outputChannelCount; + PaSampleFormat inputSampleFormat, outputSampleFormat; + + VVDBUG(("IsFormatSupported(): in chan=%d, in fmt=%ld, out chan=%d, out fmt=%ld sampleRate=%g\n", + inputParameters ? inputParameters->channelCount : -1, + inputParameters ? inputParameters->sampleFormat : -1, + outputParameters ? outputParameters->channelCount : -1, + outputParameters ? outputParameters->sampleFormat : -1, + (float) sampleRate )); + + /** These first checks are standard PA checks. We do some fancier checks + later. */ + if( inputParameters ) { - if( done ) - { - if( outputNativeBufferfPtr ) - { - /* Clear remainder of wave buffer if we are waiting for stop. */ - AddTraceMessage("Pa_TimeSlice: zero rest of wave buffer ", i ); - memset( outputNativeBufferfPtr, 0, pahsc->pahsc_BytesPerUserNativeOutputBuffer ); - } - } - else - { - /* Convert 32 bit native data to user data and call user routine. */ - result = PaConvert_Process( past, inputNativeBufferfPtr, outputNativeBufferfPtr ); - if( result != 0) done = 1; - } - if( inputNativeBufferfPtr ) inputNativeBufferfPtr += pahsc->pahsc_BytesPerUserNativeInputBuffer; - if( outputNativeBufferfPtr) outputNativeBufferfPtr += pahsc->pahsc_BytesPerUserNativeOutputBuffer; + 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; + } + else + { + inputChannelCount = 0; } - Pa_EndUsageCalculation( past ); - -#if PA_TRACE_RUN - AddTraceMessage("Pa_TimeSlice: buffersProcessed ", buffersProcessed ); -#endif - - return (result != 0) ? result : done; -} + if( outputParameters ) + { + outputChannelCount = outputParameters->channelCount; + outputSampleFormat = outputParameters->sampleFormat; -OSStatus appIOProc (AudioDeviceID inDevice, const AudioTimeStamp* inNow, - const AudioBufferList* inInputData, const AudioTimeStamp* inInputTime, - AudioBufferList* outOutputData, const AudioTimeStamp* inOutputTime, - void* contextPtr) -{ + /* 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 */ - PaError result = 0; - internalPortAudioStream *past; - PaHostSoundControl *pahsc; - past = (internalPortAudioStream *) contextPtr; - pahsc = (PaHostSoundControl *) past->past_DeviceData; + if( outputParameters->device == paUseHostApiSpecificDeviceSpecification ) + return paInvalidDevice; -// printf("Num input Buffers: %d; Num output Buffers: %d.\n", inInputData->mNumberBuffers, outOutputData->mNumberBuffers); + /* check that output device can support outputChannelCount */ + if( outputChannelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels ) + return paInvalidChannelCount; - /* Has someone asked us to abort by calling Pa_AbortStream()? */ - if( past->past_StopNow ) - { - past->past_IsActive = 0; /* Will cause thread to return. */ } - /* Has someone asked us to stop by calling Pa_StopStream() - * OR has a user callback returned '1' to indicate finished. - */ - else if( past->past_StopSoon ) + else { - // FIXME - pretend all done - past->past_IsActive = 0; /* Will cause thread to return. */ + outputChannelCount = 0; } - else + + /* FEEDBACK */ + /* I think the only way to check a given format SR combo is */ + /* to try opening it. This could be disruptive, is that Okay? */ + /* The alternative is to just read off available sample rates, */ + /* but this will not work %100 of the time (eg, a device that */ + /* supports N output at one rate but only N/2 at a higher rate.)*/ + + /* The following code opens the device with the requested parameters to + see if it works. */ { - /* use time stamp from CoreAudio if valid */ - if( inOutputTime->mFlags & kAudioTimeStampSampleTimeValid) - { - past->past_FrameCount = inOutputTime->mSampleTime; - } - - /* Process full input buffer and fill up empty output buffers. */ - if( (result = Pa_TimeSlice( past, inInputData, outOutputData )) != 0) - { - /* User callback has asked us to stop. */ -#if PA_TRACE_START_STOP - AddTraceMessage( "Pa_OutputThreadProc: TimeSlice() returned ", result ); -#endif - past->past_StopSoon = 1; /* Request that audio play out then stop. */ - result = paNoError; - } + PaError err; + PaStream *s; + err = OpenStream( hostApi, &s, inputParameters, outputParameters, + sampleRate, 1024, 0, (PaStreamCallback *)1, NULL ); + if( err != paNoError && err != paInvalidSampleRate ) + DBUG( ( "OpenStream @ %g returned: %d: %s\n", + (float) sampleRate, err, Pa_GetErrorText( err ) ) ); + if( err ) + return err; + err = CloseStream( s ); + if( err ) { + /* FEEDBACK: is this more serious? should we assert? */ + DBUG( ( "WARNING: could not close Stream. %d: %s\n", + err, Pa_GetErrorText( err ) ) ); + } } - // FIXME PaHost_UpdateStreamTime( pahsc ); - - return result; + return paFormatIsSupported; } -#if 0 -static int PaHost_CalcTimeOut( internalPortAudioStream *past ) +static PaError OpenAndSetupOneAudioUnit( + const PaStreamParameters *inStreamParams, + const PaStreamParameters *outStreamParams, + const unsigned long requestedFramesPerBuffer, + unsigned long *actualInputFramesPerBuffer, + unsigned long *actualOutputFramesPerBuffer, + const PaMacAUHAL *auhalHostApi, + AudioUnit *audioUnit, + AudioConverterRef *srConverter, + AudioDeviceID *audioDevice, + const double sampleRate, + void *refCon ) { - /* Calculate timeOut longer than longest time it could take to play all buffers. */ - int timeOut = (UInt32) (1500.0 * PaHost_GetTotalBufferFrames( past ) / past->past_SampleRate); - if( timeOut < MIN_TIMEOUT_MSEC ) timeOut = MIN_TIMEOUT_MSEC; - return timeOut; -} -#endif - + ComponentDescription desc; + Component comp; + /*An Apple TN suggests using CAStreamBasicDescription, but that is C++*/ + AudioStreamBasicDescription desiredFormat; + OSErr result = noErr; + PaError paResult = paNoError; + int line = 0; + UInt32 callbackKey; + AURenderCallbackStruct rcbs; + unsigned long macInputStreamFlags = paMacCorePlayNice; + unsigned long macOutputStreamFlags = paMacCorePlayNice; + + VVDBUG(("OpenAndSetupOneAudioUnit(): in chan=%d, in fmt=%ld, out chan=%d, out fmt=%ld, requestedFramesPerBuffer=%ld\n", + inStreamParams ? inStreamParams->channelCount : -1, + inStreamParams ? inStreamParams->sampleFormat : -1, + outStreamParams ? outStreamParams->channelCount : -1, + outStreamParams ? outStreamParams->sampleFormat : -1, + requestedFramesPerBuffer )); + + /* -- handle the degenerate case -- */ + if( !inStreamParams && !outStreamParams ) { + *audioUnit = NULL; + *audioDevice = kAudioDeviceUnknown; + return paNoError; + } -/*******************************************************************/ -/* Attempt to set device sample rate. */ -static PaError PaHost_SetSampleRate( AudioDeviceID devID, Boolean isInput, double sampleRate ) -{ - AudioStreamBasicDescription formatDesc; - OSStatus err; - memset( &formatDesc, 0, sizeof(AudioStreamBasicDescription) ); - formatDesc.mSampleRate = sampleRate; - err = AudioDeviceSetProperty( devID, 0, 0, - isInput, kAudioDevicePropertyStreamFormat, sizeof(formatDesc), &formatDesc); - - if (err != kAudioHardwareNoError) return paInvalidSampleRate; - else return paNoError; -} + /* -- get the user's api specific info, if they set any -- */ + if( inStreamParams && inStreamParams->hostApiSpecificStreamInfo ) + macInputStreamFlags= + ((paMacCoreStreamInfo*)inStreamParams->hostApiSpecificStreamInfo) + ->flags; + if( outStreamParams && outStreamParams->hostApiSpecificStreamInfo ) + macOutputStreamFlags= + ((paMacCoreStreamInfo*)outStreamParams->hostApiSpecificStreamInfo) + ->flags; + /* Override user's flags here, if desired for testing. */ + + /* + * The HAL AU is a Mac OS style "component". + * the first few steps deal with that. + * Later steps work on a combination of Mac OS + * components and the slightly lower level + * HAL. + */ -/*******************************************************************/ -PaError PaHost_OpenInputStream( internalPortAudioStream *past ) -{ - PaHostSoundControl *pahsc; - const PaHostDeviceInfo *hostDeviceInfo; - PaError result = paNoError; - UInt32 bytesPerHostBuffer; - UInt32 dataSize; - OSStatus err = noErr; - int bytesPerInputFrame; - - pahsc = (PaHostSoundControl *) past->past_DeviceData; - - DBUG(("PaHost_OpenStream: deviceID = 0x%x\n", past->past_InputDeviceID)); - if( (past->past_InputDeviceID < LOWEST_INPUT_DEVID) || - (past->past_InputDeviceID > HIGHEST_INPUT_DEVID) ) + /* -- describe the output type AudioUnit -- */ + /* Note: for the default AudioUnit, we could use the + * componentSubType value kAudioUnitSubType_DefaultOutput; + * but I don't think that's relevant here. + */ + desc.componentType = kAudioUnitType_Output; + desc.componentSubType = kAudioUnitSubType_HALOutput; + desc.componentManufacturer = kAudioUnitManufacturer_Apple; + desc.componentFlags = 0; + desc.componentFlagsMask = 0; + /* -- find the component -- */ + comp = FindNextComponent( NULL, &desc ); + if( !comp ) { - return paInvalidDeviceId; + DBUG( ( "AUHAL component not found." ) ); + *audioUnit = NULL; + *audioDevice = kAudioDeviceUnknown; + return paUnanticipatedHostError; } - hostDeviceInfo = &sDeviceInfos[past->past_InputDeviceID]; - - /* Try to set sample rate. */ - result = PaHost_SetSampleRate( hostDeviceInfo->audioDeviceID, IS_INPUT, past->past_SampleRate ); - if( result != paNoError ) return result; - - if( past->past_NumInputChannels != hostDeviceInfo->paInfo.maxInputChannels ) + /* -- open it -- */ + result = OpenAComponent( comp, audioUnit ); + if( result ) { -#if 1 - return paInvalidChannelCount; // FIXME - how support mono? -#else -FIXME - should this be set on a stream basis? Is it possible to change? - /* Attempt to set number of channels. */ - AudioStreamBasicDescription formatDesc; - OSStatus err; - memset( &formatDesc, 0, sizeof(AudioStreamBasicDescription) ); - formatDesc.mChannelsPerFrame = past->past_NumInputChannels; - - err = AudioDeviceSetProperty( hostDeviceInfo->audioDeviceID, 0, 0, - IS_INPUT, kAudioDevicePropertyStreamFormat, sizeof(formatDesc), &formatDesc); - if (err != kAudioHardwareNoError) - { - result = paInvalidChannelCount; - goto error; - } -#endif + DBUG( ( "Failed to open AUHAL component." ) ); + *audioUnit = NULL; + *audioDevice = kAudioDeviceUnknown; + return ERR( result ); } + /* -- prepare a little error handling logic / hackery -- */ +#define ERR_WRAP(mac_err) do { result = mac_err ; line = __LINE__ ; if ( result != noErr ) goto error ; } while(0) - // calculate native buffer sizes in bytes - bytesPerInputFrame = Pa_GetSampleSize(paFloat32) * past->past_NumInputChannels; - pahsc->pahsc_BytesPerUserNativeInputBuffer = past->past_FramesPerUserBuffer * bytesPerInputFrame; - bytesPerHostBuffer = pahsc->pahsc_FramesPerHostBuffer * bytesPerInputFrame; - - // Change the bufferSize of the device! Is this per device or just for our stream? - dataSize = sizeof(UInt32); - err = AudioDeviceSetProperty( hostDeviceInfo->audioDeviceID, 0, 0, IS_INPUT, - kAudioDevicePropertyBufferSize, dataSize, &bytesPerHostBuffer); - if( err != noErr ) + /* -- if there is input, we have to explicitly enable input -- */ + if( inStreamParams ) { - ERR_RPT(("Could not force buffer size!")); - result = paHostError; - goto error; + UInt32 enableIO; + enableIO = 1; + ERR_WRAP( AudioUnitSetProperty( *audioUnit, + kAudioOutputUnitProperty_EnableIO, + kAudioUnitScope_Input, + INPUT_ELEMENT, + &enableIO, + sizeof(enableIO) ) ); + } + /* -- if there is no output, we must explicitly disable output -- */ + if( !outStreamParams ) + { + UInt32 enableIO; + enableIO = 0; + ERR_WRAP( AudioUnitSetProperty( *audioUnit, + kAudioOutputUnitProperty_EnableIO, + kAudioUnitScope_Output, + OUTPUT_ELEMENT, + &enableIO, + sizeof(enableIO) ) ); + } + /* -- set the devices -- */ + /* make sure input and output are the same device if we are doing input and + output. */ + if( inStreamParams && outStreamParams ) + assert( outStreamParams->device == inStreamParams->device ); + if( inStreamParams ) + { + *audioDevice = auhalHostApi->devIds[inStreamParams->device] ; + ERR_WRAP( AudioUnitSetProperty( *audioUnit, + kAudioOutputUnitProperty_CurrentDevice, + kAudioUnitScope_Global, + INPUT_ELEMENT, + audioDevice, + sizeof(AudioDeviceID) ) ); + } + if( outStreamParams ) + { + *audioDevice = auhalHostApi->devIds[outStreamParams->device] ; + ERR_WRAP( AudioUnitSetProperty( *audioUnit, + kAudioOutputUnitProperty_CurrentDevice, + kAudioUnitScope_Global, + OUTPUT_ELEMENT, + audioDevice, + sizeof(AudioDeviceID) ) ); } - // setup conversion procedure - result = PaConvert_SetupInput( past, paFloat32 ); + /* -- set format -- */ + bzero( &desiredFormat, sizeof(desiredFormat) ); + desiredFormat.mFormatID = kAudioFormatLinearPCM ; + desiredFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked; + desiredFormat.mFramesPerPacket = 1; + desiredFormat.mBitsPerChannel = sizeof( float ) * 8; + + result = 0; + /* set device format first, but only touch the device if the user asked */ + if( inStreamParams ) { + /*The callback never calls back if we don't set the FPB */ + /*This seems wierd, because I would think setting anything on the device + would be disruptive.*/ + paResult = setBestFramesPerBuffer( *audioDevice, FALSE, + requestedFramesPerBuffer, + actualInputFramesPerBuffer ); + if( paResult ) goto error; + if( macInputStreamFlags & paMacCore_ChangeDeviceParameters ) { + bool requireExact; + requireExact=macInputStreamFlags&paMacCore_FailIfConversionRequired; + paResult = setBestSampleRateForDevice( *audioDevice, FALSE, + requireExact, sampleRate ); + if( paResult ) goto error; + } + if( actualInputFramesPerBuffer && actualOutputFramesPerBuffer ) + *actualOutputFramesPerBuffer = *actualInputFramesPerBuffer ; + } + if( outStreamParams && !inStreamParams ) { + /*The callback never calls back if we don't set the FPB */ + /*This seems wierd, because I would think setting anything on the device + would be disruptive.*/ + paResult = setBestFramesPerBuffer( *audioDevice, TRUE, + requestedFramesPerBuffer, + actualOutputFramesPerBuffer ); + if( paResult ) goto error; + if( macOutputStreamFlags & paMacCore_ChangeDeviceParameters ) { + bool requireExact; + requireExact=macOutputStreamFlags&paMacCore_FailIfConversionRequired; + paResult = setBestSampleRateForDevice( *audioDevice, TRUE, + requireExact, sampleRate ); + if( paResult ) goto error; + } + } - return result; + /* -- set the quality of the output converter -- */ + if( outStreamParams ) { + UInt32 value = kAudioConverterQuality_Max; + switch( macOutputStreamFlags & 0x0700 ) { + case 0x0100: /*paMacCore_ConversionQualityMin:*/ + value=kRenderQuality_Min; + break; + case 0x0200: /*paMacCore_ConversionQualityLow:*/ + value=kRenderQuality_Low; + break; + case 0x0300: /*paMacCore_ConversionQualityMedium:*/ + value=kRenderQuality_Medium; + break; + case 0x0400: /*paMacCore_ConversionQualityHigh:*/ + value=kRenderQuality_High; + break; + } + ERR_WRAP( AudioUnitSetProperty( *audioUnit, + kAudioUnitProperty_RenderQuality, + kAudioUnitScope_Global, + OUTPUT_ELEMENT, + &value, + sizeof(value) ) ); + } + /* now set the format on the Audio Units. */ + if( outStreamParams ) + { + desiredFormat.mSampleRate =sampleRate; + desiredFormat.mBytesPerPacket=sizeof(float)*outStreamParams->channelCount; + desiredFormat.mBytesPerFrame =sizeof(float)*outStreamParams->channelCount; + desiredFormat.mChannelsPerFrame = outStreamParams->channelCount; + ERR_WRAP( AudioUnitSetProperty( *audioUnit, + kAudioUnitProperty_StreamFormat, + kAudioUnitScope_Input, + OUTPUT_ELEMENT, + &desiredFormat, + sizeof(AudioStreamBasicDescription) ) ); + } + if( inStreamParams ) + { + AudioStreamBasicDescription sourceFormat; + UInt32 size = sizeof( AudioStreamBasicDescription ); + + /* keep the sample rate of the device, or we confuse AUHAL */ + ERR_WRAP( AudioUnitGetProperty( *audioUnit, + kAudioUnitProperty_StreamFormat, + kAudioUnitScope_Input, + INPUT_ELEMENT, + &sourceFormat, + &size ) ); + desiredFormat.mSampleRate = sourceFormat.mSampleRate; + desiredFormat.mBytesPerPacket=sizeof(float)*inStreamParams->channelCount; + desiredFormat.mBytesPerFrame =sizeof(float)*inStreamParams->channelCount; + desiredFormat.mChannelsPerFrame = inStreamParams->channelCount; + ERR_WRAP( AudioUnitSetProperty( *audioUnit, + kAudioUnitProperty_StreamFormat, + kAudioUnitScope_Output, + INPUT_ELEMENT, + &desiredFormat, + sizeof(AudioStreamBasicDescription) ) ); + } + /* set the maximumFramesPerSlice */ + /* not doing this causes real problems + (eg. the callback might not be called). The idea of setting both this + and the frames per buffer on the device is that we'll be most likely + to actually get the frame size we requested in the callback with the + minimum latency. */ + if( outStreamParams ) { + UInt32 size = sizeof( *actualOutputFramesPerBuffer ); + ERR_WRAP( AudioUnitSetProperty( *audioUnit, + kAudioUnitProperty_MaximumFramesPerSlice, + kAudioUnitScope_Input, + OUTPUT_ELEMENT, + actualOutputFramesPerBuffer, + sizeof(unsigned long) ) ); + ERR_WRAP( AudioUnitGetProperty( *audioUnit, + kAudioUnitProperty_MaximumFramesPerSlice, + kAudioUnitScope_Global, + OUTPUT_ELEMENT, + actualOutputFramesPerBuffer, + &size ) ); + } + if( inStreamParams ) { + /*UInt32 size = sizeof( *actualInputFramesPerBuffer );*/ + ERR_WRAP( AudioUnitSetProperty( *audioUnit, + kAudioUnitProperty_MaximumFramesPerSlice, + kAudioUnitScope_Output, + INPUT_ELEMENT, + actualInputFramesPerBuffer, + sizeof(unsigned long) ) ); +/* Don't know why this causes problems + ERR_WRAP( AudioUnitGetProperty( *audioUnit, + kAudioUnitProperty_MaximumFramesPerSlice, + kAudioUnitScope_Global, //Output, + INPUT_ELEMENT, + actualInputFramesPerBuffer, + &size ) ); +*/ + } -error: - return result; + /* -- if we have input, we may need to setup an SR converter -- */ + /* even if we got the sample rate we asked for, we need to do + the conversion in case another program changes the underlying SR. */ + /* FIXME: I think we need to monitor stream and change the converter if the incoming format changes. */ + if( inStreamParams ) { + AudioStreamBasicDescription desiredFormat; + AudioStreamBasicDescription sourceFormat; + UInt32 sourceSize = sizeof( sourceFormat ); + bzero( &desiredFormat, sizeof(desiredFormat) ); + desiredFormat.mSampleRate = sampleRate; + desiredFormat.mFormatID = kAudioFormatLinearPCM ; + desiredFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked; + desiredFormat.mFramesPerPacket = 1; + desiredFormat.mBitsPerChannel = sizeof( float ) * 8; + desiredFormat.mBytesPerPacket=sizeof(float)*inStreamParams->channelCount; + desiredFormat.mBytesPerFrame =sizeof(float)*inStreamParams->channelCount; + desiredFormat.mChannelsPerFrame = inStreamParams->channelCount; + + /* get the source format */ + ERR_WRAP( AudioUnitGetProperty( + *audioUnit, + kAudioUnitProperty_StreamFormat, + kAudioUnitScope_Output, + INPUT_ELEMENT, + &sourceFormat, + &sourceSize ) ); + + if( desiredFormat.mSampleRate != sourceFormat.mSampleRate ) + { + UInt32 value = kAudioConverterQuality_Max; + switch( macInputStreamFlags & 0x0700 ) { + case 0x0100: /*paMacCore_ConversionQualityMin:*/ + value=kAudioConverterQuality_Min; + break; + case 0x0200: /*paMacCore_ConversionQualityLow:*/ + value=kAudioConverterQuality_Low; + break; + case 0x0300: /*paMacCore_ConversionQualityMedium:*/ + value=kAudioConverterQuality_Medium; + break; + case 0x0400: /*paMacCore_ConversionQualityHigh:*/ + value=kAudioConverterQuality_High; + break; + } + VDBUG(( "Creating sample rate converter for input" + " to convert from %g to %g\n", + (float)sourceFormat.mSampleRate, + (float)desiredFormat.mSampleRate ) ); + /* create our converter */ + ERR_WRAP( AudioConverterNew( + &sourceFormat, + &desiredFormat, + srConverter ) ); + /* Set quality */ + ERR_WRAP( AudioConverterSetProperty( + *srConverter, + kAudioConverterSampleRateConverterQuality, + sizeof( value ), + &value ) ); + } + } + /* -- set IOProc (callback) -- */ + callbackKey = outStreamParams ? kAudioUnitProperty_SetRenderCallback + : kAudioOutputUnitProperty_SetInputCallback ; + rcbs.inputProc = AudioIOProc; + rcbs.inputProcRefCon = refCon; + ERR_WRAP( AudioUnitSetProperty( + *audioUnit, + callbackKey, + kAudioUnitScope_Output, + outStreamParams ? OUTPUT_ELEMENT : INPUT_ELEMENT, + &rcbs, + sizeof(rcbs)) ); + + if( inStreamParams && outStreamParams && *srConverter ) + ERR_WRAP( AudioUnitSetProperty( + *audioUnit, + kAudioOutputUnitProperty_SetInputCallback, + kAudioUnitScope_Output, + INPUT_ELEMENT, + &rcbs, + sizeof(rcbs)) ); + + /*IMPLEMENTME: may need to worry about channel mapping.*/ + + /* initialize the audio unit */ + ERR_WRAP( AudioUnitInitialize(*audioUnit) ); + + if( inStreamParams && outStreamParams ) + VDBUG( ("Opened device %ld for input and output.\n", *audioDevice ) ); + else if( inStreamParams ) + VDBUG( ("Opened device %ld for input.\n", *audioDevice ) ); + else if( outStreamParams ) + VDBUG( ("Opened device %ld for output.\n", *audioDevice ) ); + return paNoError; +#undef ERR_WRAP + + error: + CloseComponent( *audioUnit ); + *audioUnit = NULL; + if( result ) + return PaMacCore_SetError( result, line, 1 ); + return paResult; } -/*******************************************************************/ -PaError PaHost_OpenOutputStream( internalPortAudioStream *past ) +/* 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 ) { - PaHostSoundControl *pahsc; - const PaHostDeviceInfo *hostDeviceInfo; - PaError result = paNoError; - UInt32 bytesPerHostBuffer; - UInt32 dataSize; - OSStatus err = noErr; - int bytesPerOutputFrame; - - pahsc = (PaHostSoundControl *) past->past_DeviceData; - - DBUG(("PaHost_OpenStream: deviceID = 0x%x\n", past->past_OutputDeviceID)); - if( (past->past_OutputDeviceID < LOWEST_OUTPUT_DEVID) || - (past->past_OutputDeviceID > HIGHEST_OUTPUT_DEVID) ) + PaError result = paNoError; + PaMacAUHAL *auhalHostApi = (PaMacAUHAL*)hostApi; + PaMacCoreStream *stream = 0; + int inputChannelCount, outputChannelCount; + PaSampleFormat inputSampleFormat, outputSampleFormat; + PaSampleFormat hostInputSampleFormat, hostOutputSampleFormat; + VVDBUG(("OpenStream(): in chan=%d, in fmt=%ld, out chan=%d, out fmt=%ld SR=%g, FPB=%ld\n", + inputParameters ? inputParameters->channelCount : -1, + inputParameters ? inputParameters->sampleFormat : -1, + outputParameters ? outputParameters->channelCount : -1, + outputParameters ? outputParameters->sampleFormat : -1, + (float) sampleRate, + framesPerBuffer )); + VDBUG( ("Opening Stream.\n") ); + + /*These first few bits of code are from paSkeleton with few modifications.*/ + if( inputParameters ) { - return paInvalidDeviceId; - } - hostDeviceInfo = &sDeviceInfos[past->past_OutputDeviceID]; + inputChannelCount = inputParameters->channelCount; + inputSampleFormat = inputParameters->sampleFormat; - /* Try to set sample rate. */ - result = PaHost_SetSampleRate( hostDeviceInfo->audioDeviceID, IS_OUTPUT, past->past_SampleRate ); - if( result != paNoError ) return result; + /* unless alternate device specification is supported, reject the use of + paUseHostApiSpecificDeviceSpecification */ - if( past->past_NumOutputChannels != hostDeviceInfo->paInfo.maxOutputChannels ) - { -#if 1 - return paInvalidChannelCount; // FIXME - how support mono? -#else - /* Attempt to set number of channels. */ - AudioStreamBasicDescription formatDesc; - OSStatus err; - memset( &formatDesc, 0, sizeof(AudioStreamBasicDescription) ); - formatDesc.mChannelsPerFrame = past->past_NumOutputChannels; - err = AudioDeviceSetProperty( hostDeviceInfo->audioDeviceID, 0, 0, - IS_OUTPUT, kAudioDevicePropertyStreamFormat, sizeof(formatDesc), &formatDesc); - - if (err != kAudioHardwareNoError) - { - result = paInvalidChannelCount; - goto error; - } -#endif - } + if( inputParameters->device == paUseHostApiSpecificDeviceSpecification ) + return paInvalidDevice; - // calculate buffer sizes in bytes - bytesPerOutputFrame = Pa_GetSampleSize(paFloat32) * past->past_NumOutputChannels; - pahsc->pahsc_BytesPerUserNativeOutputBuffer = past->past_FramesPerUserBuffer * bytesPerOutputFrame; - bytesPerHostBuffer = pahsc->pahsc_FramesPerHostBuffer * bytesPerOutputFrame; + /* check that input device can support inputChannelCount */ + if( inputChannelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels ) + return paInvalidChannelCount; - // Change the bufferSize of the device! Is this per device or just for our stream? - dataSize = sizeof(bytesPerHostBuffer); - err = AudioDeviceSetProperty( hostDeviceInfo->audioDeviceID, 0, 0, IS_OUTPUT, - kAudioDevicePropertyBufferSize, dataSize, &bytesPerHostBuffer); - if( err != noErr ) + /* Host supports interleaved float32 */ + hostInputSampleFormat = paFloat32; + } + else { - ERR_RPT(("Could not force buffer size!")); - result = paHostError; - goto error; + inputChannelCount = 0; + inputSampleFormat = hostInputSampleFormat = paFloat32; /* Surpress 'uninitialised var' warnings. */ } - - // setup conversion procedure - result = PaConvert_SetupOutput( past, paFloat32 ); - - return result; -error: - return result; -} + if( outputParameters ) + { + outputChannelCount = outputParameters->channelCount; + outputSampleFormat = outputParameters->sampleFormat; + + /* unless alternate device specification is supported, reject the use of + paUseHostApiSpecificDeviceSpecification */ -/*******************************************************************/ -PaError PaHost_GetTotalBufferFrames( internalPortAudioStream *past ) -{ - PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; - return pahsc->pahsc_FramesPerHostBuffer; -} + if( outputParameters->device == paUseHostApiSpecificDeviceSpecification ) + return paInvalidDevice; + /* check that output device can support inputChannelCount */ + if( outputChannelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels ) + return paInvalidChannelCount; -/******************************************************************* -* Determine how many User Buffers we can put into our CoreAudio stream buffer. -* Uses: -* past->past_FramesPerUserBuffer, etc. -* Sets: -* past->past_NumUserBuffers -* pahsc->pahsc_UserBuffersPerHostBuffer -* pahsc->pahsc_FramesPerHostBuffer -*/ -static void PaHost_CalcHostBufferSize( internalPortAudioStream *past ) -{ - PaHostSoundControl *pahsc = ( PaHostSoundControl *)past->past_DeviceData; - unsigned int minNumUserBuffers; - - // Determine number of user buffers based on minimum latency. - minNumUserBuffers = Pa_GetMinNumBuffers( past->past_FramesPerUserBuffer, past->past_SampleRate ); - // Compare to user requested number in user wants more than the minimum. - past->past_NumUserBuffers = ( minNumUserBuffers > past->past_NumUserBuffers ) ? - minNumUserBuffers : past->past_NumUserBuffers; - DBUG(("PaHost_CalcNumHostBuffers: min past_NumUserBuffers = %d\n", past->past_NumUserBuffers )); - - // For CoreAudio, we only have one Host buffer, so... - pahsc->pahsc_UserBuffersPerHostBuffer = past->past_NumUserBuffers; - // Calculate size of CoreAudio buffer. - pahsc->pahsc_FramesPerHostBuffer = past->past_FramesPerUserBuffer * past->past_NumUserBuffers; - - DBUG(("PaHost_CalcNumHostBuffers: pahsc_UserBuffersPerHostBuffer = %d\n", pahsc->pahsc_UserBuffersPerHostBuffer )); - DBUG(("PaHost_CalcNumHostBuffers: pahsc_FramesPerHostBuffer = %d\n", pahsc->pahsc_FramesPerHostBuffer )); -} + /* Host supports interleaved float32 */ + hostOutputSampleFormat = paFloat32; + } + else + { + outputChannelCount = 0; + outputSampleFormat = hostOutputSampleFormat = paFloat32; /* Surpress 'uninitialized var' warnings. */ + } -/*******************************************************************/ -PaError PaHost_OpenStream( internalPortAudioStream *past ) -{ - PaError result = paNoError; - PaHostSoundControl *pahsc; + /* validate platform specific flags */ + if( (streamFlags & paPlatformSpecificFlags) != 0 ) + return paInvalidFlag; /* unexpected platform specific flag */ - /* Allocate and initialize host data. */ - pahsc = (PaHostSoundControl *) malloc(sizeof(PaHostSoundControl)); - if( pahsc == NULL ) + stream = (PaMacCoreStream*)PaUtil_AllocateMemory( sizeof(PaMacCoreStream) ); + if( !stream ) { result = paInsufficientMemory; goto error; } - memset( pahsc, 0, sizeof(PaHostSoundControl) ); - past->past_DeviceData = (void *) pahsc; - // If we are using both input and out, then they must be on the same CoreAudio device, - // until we implement a FIFO between two devices. - if( (past->past_OutputDeviceID != paNoDevice) && (past->past_InputDeviceID != paNoDevice) ) + /* If we fail after this point, we my be left in a bad state, with + some data structures setup and others not. So, first thing we + do is initialize everything so that if we fail, we know what hasn't + been touched. + */ + + stream->inputAudioBufferList.mBuffers[0].mData = NULL; + stream->inputRingBuffer.buffer = NULL; + bzero( &stream->blio, sizeof( PaMacBlio ) ); +/* + stream->blio.inputRingBuffer.buffer = NULL; + stream->blio.outputRingBuffer.buffer = NULL; + stream->blio.inputSampleFormat = inputParameters?inputParameters->sampleFormat:0; + stream->blio.inputSampleSize = computeSampleSizeFromFormat(stream->blio.inputSampleFormat); + stream->blio.outputSampleFormat=outputParameters?outputParameters->sampleFormat:0; + stream->blio.outputSampleSize = computeSampleSizeFromFormat(stream->blio.outputSampleFormat); +*/ + stream->inputSRConverter = NULL; + stream->inputUnit = NULL; + stream->outputUnit = NULL; + stream->inputFramesPerBuffer = 0; + stream->outputFramesPerBuffer = 0; + stream->bufferProcessorIsInitialized = FALSE; + + /* assert( streamCallback ) ; */ /* only callback mode is implemented */ + if( streamCallback ) { - AudioDeviceID inputID = sDeviceInfos[past->past_InputDeviceID].audioDeviceID; - AudioDeviceID outputID = sDeviceInfos[past->past_OutputDeviceID].audioDeviceID; - if( inputID != outputID ) - { - ERR_RPT(("PortAudio: input and output must use same CoreAudio device!\n")); - return paInvalidDeviceId; - } + PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation, + &auhalHostApi->callbackStreamInterface, + streamCallback, userData ); + } + else + { + PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation, + &auhalHostApi->blockingStreamInterface, + BlioCallback, &stream->blio ); + } + + PaUtil_InitializeCpuLoadMeasurer( &stream->cpuLoadMeasurer, sampleRate ); + + /* -- handle paFramesPerBufferUnspecified -- */ + if( framesPerBuffer == paFramesPerBufferUnspecified ) { + long requested = 64; + if( inputParameters ) + requested = MAX( requested, inputParameters->suggestedLatency * sampleRate / 2 ); + if( outputParameters ) + requested = MAX( requested, outputParameters->suggestedLatency *sampleRate / 2 ); + VDBUG( ("Block Size unspecified. Based on Latency, the user wants a Block Size near: %ld.\n", + requested ) ); + if( requested <= 64 ) { + /*requested a realtively low latency. make sure this is in range of devices */ + /*try to get the device's min natural buffer size and use that (but no smaller than 64).*/ + AudioValueRange audioRange; + size_t size = sizeof( audioRange ); + if( inputParameters ) { + WARNING( result = AudioDeviceGetProperty( auhalHostApi->devIds[inputParameters->device], + 0, + false, + kAudioDevicePropertyBufferFrameSizeRange, + &size, &audioRange ) ); + if( result ) + requested = MAX( requested, audioRange.mMinimum ); + } + if( outputParameters ) { + WARNING( result = AudioDeviceGetProperty( auhalHostApi->devIds[outputParameters->device], + 0, + false, + kAudioDevicePropertyBufferFrameSizeRange, + &size, &audioRange ) ); + if( result ) + requested = MAX( requested, audioRange.mMinimum ); + } + } else { + /* requested a realtively high latency. make sure this is in range of devices */ + /*try to get the device's max natural buffer size and use that (but no larger than 1024).*/ + AudioValueRange audioRange; + size_t size = sizeof( audioRange ); + requested = MIN( requested, 1024 ); + if( inputParameters ) { + WARNING( result = AudioDeviceGetProperty( auhalHostApi->devIds[inputParameters->device], + 0, + false, + kAudioDevicePropertyBufferFrameSizeRange, + &size, &audioRange ) ); + if( result ) + requested = MIN( requested, audioRange.mMaximum ); + } + if( outputParameters ) { + WARNING( result = AudioDeviceGetProperty( auhalHostApi->devIds[outputParameters->device], + 0, + false, + kAudioDevicePropertyBufferFrameSizeRange, + &size, &audioRange ) ); + if( result ) + requested = MIN( requested, audioRange.mMaximum ); + } + } + /* -- double check ranges -- */ + if( requested > 1024 ) requested = 1024; + if( requested < 64 ) requested = 64; + VDBUG(("After querying hardware, setting block size to %ld.\n", requested)); + framesPerBuffer = requested; } - PaHost_CalcHostBufferSize( past ); + /* -- Now we actually open and setup streams. -- */ + if( inputParameters && outputParameters && outputParameters->device == inputParameters->device ) + { /* full duplex. One device. */ + result = OpenAndSetupOneAudioUnit( inputParameters, + outputParameters, + framesPerBuffer, + &(stream->inputFramesPerBuffer), + &(stream->outputFramesPerBuffer), + auhalHostApi, + &(stream->inputUnit), + &(stream->inputSRConverter), + &(stream->inputDevice), + sampleRate, + stream ); + stream->outputUnit = stream->inputUnit; + stream->outputDevice = stream->inputDevice; + if( result != paNoError ) + goto error; + } + else + { /* full duplex, different devices OR simplex */ + result = OpenAndSetupOneAudioUnit( NULL, + outputParameters, + framesPerBuffer, + NULL, + &(stream->outputFramesPerBuffer), + auhalHostApi, + &(stream->outputUnit), + NULL, + &(stream->outputDevice), + sampleRate, + stream ); + if( result != paNoError ) + goto error; + result = OpenAndSetupOneAudioUnit( inputParameters, + NULL, + framesPerBuffer, + &(stream->inputFramesPerBuffer), + NULL, + auhalHostApi, + &(stream->inputUnit), + &(stream->inputSRConverter), + &(stream->inputDevice), + sampleRate, + stream ); + if( result != paNoError ) + goto error; + } - { - int msecLatency = (int) ((PaHost_GetTotalBufferFrames(past) * 1000) / past->past_SampleRate); - PRINT(("PortAudio on OS X - Latency = %d frames, %d msec\n", PaHost_GetTotalBufferFrames(past), msecLatency )); + if( stream->inputUnit ) { + const size_t szfl = sizeof(float); + /* setup the AudioBufferList used for input */ + bzero( &stream->inputAudioBufferList, sizeof( AudioBufferList ) ); + stream->inputAudioBufferList.mNumberBuffers = 1; + stream->inputAudioBufferList.mBuffers[0].mNumberChannels + = inputChannelCount; + stream->inputAudioBufferList.mBuffers[0].mDataByteSize + = stream->inputFramesPerBuffer*inputChannelCount*szfl; + stream->inputAudioBufferList.mBuffers[0].mData + = (float *) calloc( + stream->inputFramesPerBuffer*inputChannelCount, + szfl ); + if( !stream->inputAudioBufferList.mBuffers[0].mData ) + { + result = paInsufficientMemory; + goto error; + } + + /* + * If input and output devs are different or we are doing SR conversion, + * we also need a + * ring buffer to store inpt data while waiting for output + * data. + */ + if( (stream->outputUnit && stream->inputUnit != stream->outputUnit) + || stream->inputSRConverter ) + { + /* May want the ringSize ot initial position in + ring buffer to depend somewhat on sample rate change */ + + void *data; + long ringSize; + + ringSize = computeRingBufferSize( inputParameters, + outputParameters, + stream->inputFramesPerBuffer, + stream->outputFramesPerBuffer, + sampleRate ); + /*ringSize <<= 4; *//*16x bigger, for testing */ + + + /*now, we need to allocate memory for the ring buffer*/ + data = calloc( ringSize, szfl ); + if( !data ) + { + result = paInsufficientMemory; + goto error; + } + + /* now we can initialize the ring buffer */ + assert( 0 == + RingBuffer_Init( &stream->inputRingBuffer, + ringSize*szfl, data ) ); + /* advance the read point a little, so we are reading from the + middle of the buffer */ + if( stream->outputUnit ) + RingBuffer_AdvanceWriteIndex( &stream->inputRingBuffer, ringSize*szfl / RING_BUFFER_ADVANCE_DENOMINATOR ); + } } - - /* Setup constants for CPU load measurement. */ - pahsc->pahsc_InverseMicrosPerHostBuffer = past->past_SampleRate / (1000000.0 * pahsc->pahsc_FramesPerHostBuffer); - /* ------------------ OUTPUT */ - if( (past->past_OutputDeviceID != paNoDevice) && (past->past_NumOutputChannels > 0) ) + /* -- initialize Blio Buffer Processors -- */ + if( !streamCallback ) { - pahsc->pahsc_AudioDeviceID = sDeviceInfos[past->past_OutputDeviceID].audioDeviceID; - result = PaHost_OpenOutputStream( past ); - if( result < 0 ) goto error; + long ringSize; + + ringSize = computeRingBufferSize( inputParameters, + outputParameters, + stream->inputFramesPerBuffer, + stream->outputFramesPerBuffer, + sampleRate ); + result = initializeBlioRingBuffers( &stream->blio, + inputParameters?inputParameters->sampleFormat:0 , + outputParameters?outputParameters->sampleFormat:0 , + MAX(stream->inputFramesPerBuffer,stream->outputFramesPerBuffer), + ringSize, + inputParameters?inputChannelCount:0 , + outputParameters?outputChannelCount:0 ) ; + if( result != paNoError ) + goto error; } - /* ------------------ INPUT */ - if( (past->past_InputDeviceID != paNoDevice) && (past->past_NumInputChannels > 0) ) + /* -- initialize Buffer Processor -- */ { - pahsc->pahsc_AudioDeviceID = sDeviceInfos[past->past_InputDeviceID].audioDeviceID; - result = PaHost_OpenInputStream( past ); - if( result < 0 ) goto error; + unsigned long maxHostFrames = stream->inputFramesPerBuffer; + if( stream->outputFramesPerBuffer > maxHostFrames ) + maxHostFrames = stream->outputFramesPerBuffer; + result = PaUtil_InitializeBufferProcessor( &stream->bufferProcessor, + inputChannelCount, inputSampleFormat, + hostInputSampleFormat, + outputChannelCount, outputSampleFormat, + hostOutputSampleFormat, + sampleRate, + streamFlags, + framesPerBuffer, + /* If sample rate conversion takes place, the buffer size + will not be known. */ + maxHostFrames, + stream->inputSRConverter + ? paUtilUnknownHostBufferSize + : paUtilBoundedHostBufferSize, + streamCallback ? streamCallback : BlioCallback, + streamCallback ? userData : &stream->blio ); + if( result != paNoError ) + goto error; } + stream->bufferProcessorIsInitialized = TRUE; - return result; + /* + IMPLEMENT ME: initialise the following fields with estimated or actual + values. + I think this is okay the way it is br 12/1/05 + maybe need to change input latency estimate if IO devs differ + */ + stream->streamRepresentation.streamInfo.inputLatency = + PaUtil_GetBufferProcessorInputLatency(&stream->bufferProcessor); + stream->streamRepresentation.streamInfo.outputLatency = + PaUtil_GetBufferProcessorOutputLatency(&stream->bufferProcessor); + stream->streamRepresentation.streamInfo.sampleRate = sampleRate; -error: - PaHost_CloseStream( past ); - return result; -} + stream->sampleRate = sampleRate; + stream->userInChan = inputChannelCount; + stream->userOutChan = outputChannelCount; -/*************************************************************************/ -PaError PaHost_StartOutput( internalPortAudioStream *past ) -{ - return 0; -} + /*stream->isTimeSet = FALSE;*/ + stream->state = STOPPED; + stream->xrunFlags = 0; -/*************************************************************************/ -PaError PaHost_StartInput( internalPortAudioStream *past ) -{ - return 0; -} + *s = (PaStream*)stream; -/*************************************************************************/ -PaError PaHost_StartEngine( internalPortAudioStream *past ) -{ - OSStatus err = noErr; - PaError result = paNoError; - PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; - - past->past_StopSoon = 0; - past->past_StopNow = 0; - past->past_IsActive = 1; - - // Associate an IO proc with the device and pass a pointer to the audio data context - err = AudioDeviceAddIOProc(pahsc->pahsc_AudioDeviceID, (AudioDeviceIOProc)appIOProc, past); - if (err != noErr) goto error; - - // start playing sound through the device - err = AudioDeviceStart(pahsc->pahsc_AudioDeviceID, (AudioDeviceIOProc)appIOProc); - if (err != noErr) goto error; - return result; + setStreamStartTime( stream ); -#if PA_TRACE_START_STOP - AddTraceMessage( "PaHost_StartEngine: TimeSlice() returned ", result ); -#endif + return result; error: - return paHostError; // FIXME - save host error + CloseStream( stream ); + return result; } -/*************************************************************************/ -PaError PaHost_StopEngine( internalPortAudioStream *past, int abort ) +PaTime GetStreamTime( PaStream *s ) { - OSStatus err = noErr; - PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; - if( pahsc == NULL ) return paNoError; - (void) abort; - - /* Tell background thread to stop generating more data and to let current data play out. */ - past->past_StopSoon = 1; - /* If aborting, tell background thread to stop NOW! */ - if( abort ) past->past_StopNow = 1; - past->past_IsActive = 0; - -#if PA_TRACE_START_STOP - AddTraceMessage( "PaHost_StopOutput: pahsc_HWaveOut ", (int) pahsc->pahsc_HWaveOut ); -#endif + /* FIXME: I am not at all sure this timing info stuff is right. + patest_sine_time reports negative latencies, which is wierd.*/ + PaMacCoreStream *stream = (PaMacCoreStream*)s; + AudioTimeStamp timeStamp; - // FIXME - we should ask proc to stop instead of stopping abruptly - err = AudioDeviceStop(pahsc->pahsc_AudioDeviceID, (AudioDeviceIOProc)appIOProc); - if (err != noErr) goto Bail; + VVDBUG(("GetStreamTime()\n")); - err = AudioDeviceRemoveIOProc(pahsc->pahsc_AudioDeviceID, (AudioDeviceIOProc)appIOProc); - if (err != noErr) goto Bail; +/* + //if ( !stream->isTimeSet ) + // return (PaTime)0; +*/ - return paNoError; + if ( stream->outputDevice ) + AudioDeviceGetCurrentTime( stream->outputDevice, &timeStamp); + else if ( stream->inputDevice ) + AudioDeviceGetCurrentTime( stream->inputDevice, &timeStamp); + else + return (PaTime)0; -Bail: - return paHostError; // FIXME - save err + return (PaTime)(timeStamp.mSampleTime - stream->startTime.mSampleTime)/stream->sampleRate; } -/*************************************************************************/ -PaError PaHost_StopInput( internalPortAudioStream *past, int abort ) +static void setStreamStartTime( PaStream *stream ) { - return paNoError; + /* FIXME: I am not at all sure this timing info stuff is right. + patest_sine_time reports negative latencies, which is wierd.*/ + PaMacCoreStream *s = (PaMacCoreStream *) stream; + VVDBUG(("setStreamStartTime()\n")); + if( s->inputDevice ) + AudioDeviceGetCurrentTime( s->inputDevice, &s->startTime); + else + AudioDeviceGetCurrentTime( s->outputDevice, &s->startTime); } -/*************************************************************************/ -PaError PaHost_StopOutput( internalPortAudioStream *past, int abort ) + +static PaTime TimeStampToSecs(PaMacCoreStream *stream, const AudioTimeStamp* timeStamp) { - return paNoError; + VVDBUG(("TimeStampToSecs()\n")); + if (timeStamp->mFlags & kAudioTimeStampSampleTimeValid) + return (timeStamp->mSampleTime / stream->sampleRate); + else + return 0; } -/*******************************************************************/ -PaError PaHost_CloseStream( internalPortAudioStream *past ) +#define RING_BUFFER_EMPTY (1000) + +static OSStatus ringBufferIOProc( AudioConverterRef inAudioConverter, + UInt32*ioDataSize, + void** outData, + void*inUserData ) { - PaHostSoundControl *pahsc; + void *dummyData; + long dummySize; + RingBuffer *rb = (RingBuffer *) inUserData; + + VVDBUG(("ringBufferIOProc()\n")); + + assert( sizeof( UInt32 ) == sizeof( long ) ); + if( RingBuffer_GetReadAvailable( rb ) == 0 ) { + *outData = NULL; + *ioDataSize = 0; + return RING_BUFFER_EMPTY; + } + RingBuffer_GetReadRegions( rb, *ioDataSize, + outData, (long *)ioDataSize, + &dummyData, &dummySize ); + + assert( *ioDataSize ); + RingBuffer_AdvanceReadIndex( rb, *ioDataSize ); + + return noErr; +} - if( past == NULL ) return paBadStreamPtr; - pahsc = (PaHostSoundControl *) past->past_DeviceData; - if( pahsc == NULL ) return paNoError; +/* + * Called by the AudioUnit API to process audio from the sound card. + * This is where the magic happens. + */ +/* FEEDBACK: there is a lot of redundant code here because of how all the cases differ. This makes it hard to maintain, so if there are suggestinos for cleaning it up, I'm all ears. */ +static OSStatus AudioIOProc( void *inRefCon, + AudioUnitRenderActionFlags *ioActionFlags, + const AudioTimeStamp *inTimeStamp, + UInt32 inBusNumber, + UInt32 inNumberFrames, + AudioBufferList *ioData ) +{ + unsigned long framesProcessed = 0; + PaStreamCallbackTimeInfo timeInfo = {0,0,0}; + PaMacCoreStream *stream = (PaMacCoreStream*)inRefCon; + const bool isRender = inBusNumber == OUTPUT_ELEMENT; + int callbackResult = paContinue ; -#if PA_TRACE_START_STOP - AddTraceMessage( "PaHost_CloseStream: pahsc_HWaveOut ", (int) pahsc->pahsc_HWaveOut ); -#endif + VVDBUG(("AudioIOProc()\n")); - free( pahsc ); - past->past_DeviceData = NULL; + PaUtil_BeginCpuLoadMeasurement( &stream->cpuLoadMeasurer ); - return paNoError; +/* + //if( !stream->isTimeSet ) + // setStreamStartTime( stream ); + //stream->isTimeSet = TRUE; +*/ + + + /* -----------------------------------------------------------------*\ + This output may be useful for debugging, + But printing durring the callback is a bad enough idea that + this is not enabled by enableing the usual debugging calls. + \* -----------------------------------------------------------------*/ + /* + static int renderCount = 0; + static int inputCount = 0; + printf( "------------------- starting reder/input\n" ); + if( isRender ) + printf("Render callback (%d):\t", ++renderCount); + else + printf("Input callback (%d):\t", ++inputCount); + printf( "Call totals: %d (input), %d (render)\n", inputCount, renderCount ); + + printf( "--- inBusNumber: %lu\n", inBusNumber ); + printf( "--- inNumberFrames: %lu\n", inNumberFrames ); + printf( "--- %x ioData\n", (unsigned) ioData ); + if( ioData ) + { + int i=0; + printf( "--- ioData.mNumBuffers %lu: \n", ioData->mNumberBuffers ); + for( i=0; imNumberBuffers; ++i ) + printf( "--- ioData buffer %d size: %lu.\n", i, ioData->mBuffers[i].mDataByteSize ); + } + ----------------------------------------------------------------- */ + + if( isRender ) { + AudioTimeStamp currentTime; + timeInfo.outputBufferDacTime = TimeStampToSecs(stream, inTimeStamp); + AudioDeviceGetCurrentTime(stream->outputDevice, ¤tTime); + timeInfo.currentTime = TimeStampToSecs(stream, ¤tTime); + } + if( isRender && stream->inputUnit == stream->outputUnit ) + timeInfo.inputBufferAdcTime = TimeStampToSecs(stream, inTimeStamp); + if( !isRender ) { + AudioTimeStamp currentTime; + timeInfo.inputBufferAdcTime = TimeStampToSecs(stream, inTimeStamp); + AudioDeviceGetCurrentTime(stream->inputDevice, ¤tTime); + timeInfo.currentTime = TimeStampToSecs(stream, ¤tTime); + } + + + if( isRender && stream->inputUnit == stream->outputUnit + && !stream->inputSRConverter ) + { + /* --------- Full Duplex, One Device, no SR Conversion ------- + * + * This is the lowest latency case, and also the simplest. + * Input data and output data are available at the same time. + * we do not use the input SR converter or the input ring buffer. + * + */ + OSErr err = 0; + unsigned long frames; + + /* -- start processing -- */ + PaUtil_BeginBufferProcessing( &(stream->bufferProcessor), + &timeInfo, + stream->xrunFlags ); + stream->xrunFlags = 0; + + /* -- compute frames. do some checks -- */ + assert( ioData->mNumberBuffers == 1 ); + assert( ioData->mBuffers[0].mNumberChannels == stream->userOutChan ); + frames = ioData->mBuffers[0].mDataByteSize; + frames /= sizeof( float ) * ioData->mBuffers[0].mNumberChannels; + /* -- copy and process input data -- */ + err= AudioUnitRender(stream->inputUnit, + ioActionFlags, + inTimeStamp, + INPUT_ELEMENT, + inNumberFrames, + &stream->inputAudioBufferList ); + /* FEEDBACK: I'm not sure what to do when this call fails */ + assert( !err ); + + PaUtil_SetInputFrameCount( &(stream->bufferProcessor), frames ); + PaUtil_SetInterleavedInputChannels( &(stream->bufferProcessor), + 0, + stream->inputAudioBufferList.mBuffers[0].mData, + stream->inputAudioBufferList.mBuffers[0].mNumberChannels); + /* -- Copy and process output data -- */ + PaUtil_SetOutputFrameCount( &(stream->bufferProcessor), frames ); + PaUtil_SetInterleavedOutputChannels( &(stream->bufferProcessor), + 0, + ioData->mBuffers[0].mData, + ioData->mBuffers[0].mNumberChannels); + /* -- complete processing -- */ + framesProcessed = + PaUtil_EndBufferProcessing( &(stream->bufferProcessor), + &callbackResult ); + } + else if( isRender ) + { + /* -------- Output Side of Full Duplex (Separate Devices or SR Conversion) + * -- OR Simplex Output + * + * This case handles output data as in the full duplex case, + * and, if there is input data, reads it off the ring buffer + * and into the PA buffer processor. If sample rate conversion + * is required on input, that is done here as well. + */ + unsigned long frames; + + /* Sometimes, when stopping a duplex stream we get erroneous + xrun flags, so if this is our last run, clear the flags. */ + int xrunFlags = stream->xrunFlags; + if( xrunFlags & paInputUnderflow ) + printf( "input underflow.\n" ); + if( xrunFlags & paInputOverflow ) + printf( "input overflow.\n" ); + if( stream->state == STOPPING || stream->state == CALLBACK_STOPPED ) + xrunFlags = 0; + + /* -- start processing -- */ + PaUtil_BeginBufferProcessing( &(stream->bufferProcessor), + &timeInfo, + xrunFlags ); + stream->xrunFlags = 0; /* FEEDBACK: we only send flags to Buf Proc once */ + + /* -- Copy and process output data -- */ + assert( ioData->mNumberBuffers == 1 ); + frames = ioData->mBuffers[0].mDataByteSize; + frames /= sizeof( float ) * ioData->mBuffers[0].mNumberChannels; + assert( ioData->mBuffers[0].mNumberChannels == stream->userOutChan ); + PaUtil_SetOutputFrameCount( &(stream->bufferProcessor), frames ); + PaUtil_SetInterleavedOutputChannels( &(stream->bufferProcessor), + 0, + ioData->mBuffers[0].mData, + ioData->mBuffers[0].mNumberChannels); + + /* -- copy and process input data, and complete processing -- */ + if( stream->inputUnit ) { + const int flsz = sizeof( float ); + /* Here, we read the data out of the ring buffer, through the + audio converter. */ + int inChan = stream->inputAudioBufferList.mBuffers[0].mNumberChannels; + if( stream->inputSRConverter ) + { + OSStatus err; + UInt32 size; + float data[ inChan * frames ]; + size = sizeof( data ); + err = AudioConverterFillBuffer( + stream->inputSRConverter, + ringBufferIOProc, + &stream->inputRingBuffer, + &size, + (void *)&data ); + if( err == RING_BUFFER_EMPTY ) + { /*the ring buffer callback underflowed */ + err = 0; + bzero( ((char *)data) + size, sizeof(data)-size ); + stream->xrunFlags |= paInputUnderflow; + } + ERR( err ); + assert( !err ); + + PaUtil_SetInputFrameCount( &(stream->bufferProcessor), frames ); + PaUtil_SetInterleavedInputChannels( &(stream->bufferProcessor), + 0, + data, + inChan ); + framesProcessed = + PaUtil_EndBufferProcessing( &(stream->bufferProcessor), + &callbackResult ); + } + else + { + /* Without the AudioConverter is actually a bit more complex + because we have to do a little buffer processing that the + AudioConverter would otherwise handle for us. */ + void *data1, *data2; + long size1, size2; + RingBuffer_GetReadRegions( &stream->inputRingBuffer, + inChan*frames*flsz, + &data1, &size1, + &data2, &size2 ); + if( size1 / ( flsz * inChan ) == frames ) { + /* simplest case: all in first buffer */ + PaUtil_SetInputFrameCount( &(stream->bufferProcessor), frames ); + PaUtil_SetInterleavedInputChannels( &(stream->bufferProcessor), + 0, + data1, + inChan ); + framesProcessed = + PaUtil_EndBufferProcessing( &(stream->bufferProcessor), + &callbackResult ); + RingBuffer_AdvanceReadIndex(&stream->inputRingBuffer, size1 ); + } else if( ( size1 + size2 ) / ( flsz * inChan ) < frames ) { + /*we underflowed. take what data we can, zero the rest.*/ + float data[frames*inChan]; + if( size1 ) + memcpy( data, data1, size1 ); + if( size2 ) + memcpy( data+size1, data2, size2 ); + bzero( data+size1+size2, frames*flsz*inChan - size1 - size2 ); + + PaUtil_SetInputFrameCount( &(stream->bufferProcessor), frames ); + PaUtil_SetInterleavedInputChannels( &(stream->bufferProcessor), + 0, + data, + inChan ); + framesProcessed = + PaUtil_EndBufferProcessing( &(stream->bufferProcessor), + &callbackResult ); + RingBuffer_AdvanceReadIndex( &stream->inputRingBuffer, + size1+size2 ); + /* flag underflow */ + stream->xrunFlags |= paInputUnderflow; + } else { + /*we got all the data, but split between buffers*/ + PaUtil_SetInputFrameCount( &(stream->bufferProcessor), + size1 / ( flsz * inChan ) ); + PaUtil_SetInterleavedInputChannels( &(stream->bufferProcessor), + 0, + data1, + inChan ); + PaUtil_Set2ndInputFrameCount( &(stream->bufferProcessor), + size2 / ( flsz * inChan ) ); + PaUtil_Set2ndInterleavedInputChannels( &(stream->bufferProcessor), + 0, + data2, + inChan ); + framesProcessed = + PaUtil_EndBufferProcessing( &(stream->bufferProcessor), + &callbackResult ); + RingBuffer_AdvanceReadIndex(&stream->inputRingBuffer, size1+size2 ); + } + } + } else { + framesProcessed = + PaUtil_EndBufferProcessing( &(stream->bufferProcessor), + &callbackResult ); + } + + } + else + { + /* ------------------ Input + * + * First, we read off the audio data and put it in the ring buffer. + * if this is an input-only stream, we need to process it more, + * otherwise, we let the output case deal with it. + */ + OSErr err = 0; + int chan = stream->inputAudioBufferList.mBuffers[0].mNumberChannels ; + /* FIXME: looping here may not actually be necessary, but it was something I tried in testing. */ + do { + err= AudioUnitRender(stream->inputUnit, + ioActionFlags, + inTimeStamp, + INPUT_ELEMENT, + inNumberFrames, + &stream->inputAudioBufferList ); + if( err == -10874 ) + inNumberFrames /= 2; + } while( err == -10874 && inNumberFrames > 1 ); + /* FEEDBACK: I'm not sure what to do when this call fails */ + ERR( err ); + assert( !err ); + if( stream->inputSRConverter || stream->outputUnit ) + { + /* If this is duplex or we use a converter, put the data + into the ring buffer. */ + long bytesIn, bytesOut; + bytesIn = sizeof( float ) * inNumberFrames * chan; + bytesOut = RingBuffer_Write( &stream->inputRingBuffer, + stream->inputAudioBufferList.mBuffers[0].mData, + bytesIn ); + if( bytesIn != bytesOut ) + stream->xrunFlags |= paInputOverflow ; + } + else + { + /* for simplex input w/o SR conversion, + just pop the data into the buffer processor.*/ + PaUtil_BeginBufferProcessing( &(stream->bufferProcessor), + &timeInfo, + stream->xrunFlags ); + stream->xrunFlags = 0; + + PaUtil_SetInputFrameCount( &(stream->bufferProcessor), inNumberFrames); + PaUtil_SetInterleavedInputChannels( &(stream->bufferProcessor), + 0, + stream->inputAudioBufferList.mBuffers[0].mData, + chan ); + framesProcessed = + PaUtil_EndBufferProcessing( &(stream->bufferProcessor), + &callbackResult ); + } + if( !stream->outputUnit && stream->inputSRConverter ) + { + /* ------------------ Simplex Input w/ SR Conversion + * + * if this is a simplex input stream, we need to read off the buffer, + * do our sample rate conversion and pass the results to the buffer + * processor. + * The logic here is complicated somewhat by the fact that we don't + * know how much data is available, so we loop on reasonably sized + * chunks, and let the BufferProcessor deal with the rest. + * + */ + /*This might be too big or small depending on SR conversion*/ + float data[ chan * inNumberFrames ]; + OSStatus err; + do + { /*Run the buffer processor until we are out of data*/ + UInt32 size; + long f; + + size = sizeof( data ); + err = AudioConverterFillBuffer( + stream->inputSRConverter, + ringBufferIOProc, + &stream->inputRingBuffer, + &size, + (void *)data ); + if( err != RING_BUFFER_EMPTY ) + ERR( err ); + assert( err == 0 || err == RING_BUFFER_EMPTY ); + + f = size / ( chan * sizeof(float) ); + PaUtil_SetInputFrameCount( &(stream->bufferProcessor), f ); + if( f ) + { + PaUtil_BeginBufferProcessing( &(stream->bufferProcessor), + &timeInfo, + stream->xrunFlags ); + stream->xrunFlags = 0; + + PaUtil_SetInterleavedInputChannels( &(stream->bufferProcessor), + 0, + data, + chan ); + framesProcessed = + PaUtil_EndBufferProcessing( &(stream->bufferProcessor), + &callbackResult ); + } + } while( callbackResult == paContinue && !err ); + } + } + + switch( callbackResult ) + { + case paContinue: break; + case paComplete: + case paAbort: + stream->state = CALLBACK_STOPPED ; + if( stream->outputUnit ) + AudioOutputUnitStop(stream->outputUnit); + if( stream->inputUnit ) + AudioOutputUnitStop(stream->inputUnit); + break; + } + + PaUtil_EndCpuLoadMeasurement( &stream->cpuLoadMeasurer, framesProcessed ); + return noErr; } -/************************************************************************* -** 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 cshrc file. -*/ -#define PA_LATENCY_ENV_NAME ("PA_MIN_LATENCY_MSEC") -#if 1 -int Pa_GetMinNumBuffers( int framesPerBuffer, double framesPerSecond ) +/* + When CloseStream() is called, the multi-api layer ensures that + the stream has already been stopped or aborted. +*/ +static PaError CloseStream( PaStream* s ) { - int minBuffers; - int denominator; - int minLatencyMsec = PA_MIN_LATENCY_MSEC; - char *minLatencyText = getenv(PA_LATENCY_ENV_NAME); - if( minLatencyText != NULL ) - { - PRINT(("PA_MIN_LATENCY_MSEC = %s\n", minLatencyText )); - minLatencyMsec = atoi( minLatencyText ); - if( minLatencyMsec < 1 ) minLatencyMsec = 1; - else if( minLatencyMsec > 5000 ) minLatencyMsec = 5000; + /* This may be called from a failed OpenStream. + Therefore, each piece of info is treated seperately. */ + PaError result = paNoError; + PaMacCoreStream *stream = (PaMacCoreStream*)s; + + VVDBUG(("CloseStream()\n")); + VDBUG( ( "Closing stream.\n" ) ); + + if( stream ) { + if( stream->outputUnit && stream->outputUnit != stream->inputUnit ) { + AudioUnitUninitialize( stream->outputUnit ); + CloseComponent( stream->outputUnit ); + } + stream->outputUnit = NULL; + if( stream->inputUnit ) + { + AudioUnitUninitialize( stream->inputUnit ); + CloseComponent( stream->inputUnit ); + stream->inputUnit = NULL; + } + if( stream->inputRingBuffer.buffer ) + free( stream->inputRingBuffer.buffer ); + stream->inputRingBuffer.buffer = NULL; + /*TODO: is there more that needs to be done on error + from AudioConverterDispose?*/ + if( stream->inputSRConverter ) + ERR( AudioConverterDispose( stream->inputSRConverter ) ); + stream->inputSRConverter = NULL; + if( stream->inputAudioBufferList.mBuffers[0].mData ) + free( stream->inputAudioBufferList.mBuffers[0].mData ); + stream->inputAudioBufferList.mBuffers[0].mData = NULL; + + result = destroyBlioRingBuffers( &stream->blio ); + if( result ) + return result; + if( stream->bufferProcessorIsInitialized ) + PaUtil_TerminateBufferProcessor( &stream->bufferProcessor ); + PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation ); + PaUtil_FreeMemory( stream ); } - denominator = 1000.0 * framesPerBuffer; - minBuffers = (int) (((minLatencyMsec * framesPerSecond) + denominator - 1) / denominator ); - if( minBuffers < 1 ) minBuffers = 1; - return minBuffers; + return result; } -#else -/************************************************************************* -** Determine minimum number of buffers required for this host based -** on minimum latency. -*/ -int Pa_GetMinNumBuffers( int framesPerUserBuffer, double sampleRate ) -{ - int minUserBuffers; - int minFramesPerHostBuffer; - // Calculate minimum and maximum sizes based on timing and sample rate. - minFramesPerHostBuffer = (int) (PA_MIN_LATENCY_MSEC * sampleRate / 1000.0); - // round up to nearest multiple of 8 - minFramesPerHostBuffer = (minFramesPerHostBuffer + 7) & ~7; - DBUG(("Pa_GetMinNumBuffers: minFramesPerHostBuffer = %d\n", minFramesPerHostBuffer )); - minUserBuffers = (minFramesPerHostBuffer + framesPerUserBuffer - 1) / framesPerUserBuffer; - if( minUserBuffers < 1 ) minUserBuffers = 1; +static PaError StartStream( PaStream *s ) +{ + PaMacCoreStream *stream = (PaMacCoreStream*)s; + OSErr result = noErr; + VVDBUG(("StartStream()\n")); + VDBUG( ( "Starting stream.\n" ) ); + +#define ERR_WRAP(mac_err) do { result = mac_err ; if ( result != noErr ) return ERR(result) ; } while(0) + + /*FIXME: maybe want to do this on close/abort for faster start? */ + PaUtil_ResetBufferProcessor( &stream->bufferProcessor ); + if( stream->inputSRConverter ) + ERR_WRAP( AudioConverterReset( stream->inputSRConverter ) ); + + /* -- start -- */ + stream->state = ACTIVE; + if( stream->inputUnit ) { + ERR_WRAP( AudioOutputUnitStart(stream->inputUnit) ); + } + if( stream->outputUnit && stream->outputUnit != stream->inputUnit ) { + ERR_WRAP( AudioOutputUnitStart(stream->outputUnit) ); + } - return minUserBuffers; + return paNoError; +#undef ERR_WRAP } -#endif -/************************************************************************* -** Cleanup device info. -*/ -PaError PaHost_Term( void ) + +static PaError StopStream( PaStream *s ) { - int i; + PaMacCoreStream *stream = (PaMacCoreStream*)s; + OSErr result = noErr; + PaError paErr; + VVDBUG(("StopStream()\n")); + + VDBUG( ("Waiting for BLIO.\n") ); + waitUntilBlioWriteBufferIsFlushed( &stream->blio ); + VDBUG( ( "Stopping stream.\n" ) ); + + stream->state = STOPPING; - if( sDeviceInfos != NULL ) +#define ERR_WRAP(mac_err) do { result = mac_err ; if ( result != noErr ) return ERR(result) ; } while(0) + /* -- stop and reset -- */ + if( stream->inputUnit == stream->outputUnit && stream->inputUnit ) { - for( i=0; iinputUnit) ); + ERR_WRAP( AudioUnitReset(stream->inputUnit, kAudioUnitScope_Global, 1) ); + ERR_WRAP( AudioUnitReset(stream->inputUnit, kAudioUnitScope_Global, 0) ); + } + else + { + if( stream->inputUnit ) + { + ERR_WRAP(AudioOutputUnitStop(stream->inputUnit) ); + ERR_WRAP(AudioUnitReset(stream->inputUnit,kAudioUnitScope_Global,1)); + } + if( stream->outputUnit ) + { + ERR_WRAP(AudioOutputUnitStop(stream->outputUnit)); + ERR_WRAP(AudioUnitReset(stream->outputUnit,kAudioUnitScope_Global,0)); + } } + if( stream->inputRingBuffer.buffer ) { + RingBuffer_Flush( &stream->inputRingBuffer ); + bzero(stream->inputRingBuffer.buffer,stream->inputRingBuffer.bufferSize); + /* advance the write point a little, so we are reading from the + middle of the buffer. We'll need extra at the end because + testing has shown that this helps. */ + if( stream->outputUnit ) + RingBuffer_AdvanceWriteIndex( &stream->inputRingBuffer, + stream->inputRingBuffer.bufferSize + / RING_BUFFER_ADVANCE_DENOMINATOR ); + } + + stream->xrunFlags = 0; + stream->state = STOPPED; + + paErr = resetBlioRingBuffers( &stream->blio ); + if( paErr ) + return paErr; + +/* + //stream->isTimeSet = FALSE; +*/ - sNumPaDevices = 0; + VDBUG( ( "Stream Stopped.\n" ) ); return paNoError; +#undef ERR_WRAP } -/*************************************************************************/ -void Pa_Sleep( long msec ) +static PaError AbortStream( PaStream *s ) { -#if 0 - struct timeval timeout; - timeout.tv_sec = msec / 1000; - timeout.tv_usec = (msec % 1000) * 1000; - select( 0, NULL, NULL, NULL, &timeout ); -#else - usleep( msec * 1000 ); -#endif + VVDBUG(("AbortStream()->StopStream()\n")); + VDBUG( ( "Aborting stream.\n" ) ); + /* We have nothing faster than StopStream. */ + return StopStream(s); } -/************************************************************************* - * Allocate memory that can be accessed in real-time. - * This may need to be held in physical memory so that it is not - * paged to virtual memory. - * This call MUST be balanced with a call to PaHost_FreeFastMemory(). - */ -void *PaHost_AllocateFastMemory( long numBytes ) -{ - void *addr = malloc( numBytes ); /* FIXME - do we need physical memory? */ - if( addr != NULL ) memset( addr, 0, numBytes ); - return addr; -} -/************************************************************************* - * Free memory that could be accessed in real-time. - * This call MUST be balanced with a call to PaHost_AllocateFastMemory(). - */ -void PaHost_FreeFastMemory( void *addr, long numBytes ) +static PaError IsStreamStopped( PaStream *s ) { - if( addr != NULL ) free( addr ); + PaMacCoreStream *stream = (PaMacCoreStream*)s; + VVDBUG(("IsStreamStopped()\n")); + + return stream->state == STOPPED ? 1 : 0; } -/***********************************************************************/ -PaError PaHost_StreamActive( internalPortAudioStream *past ) +static PaError IsStreamActive( PaStream *s ) { - PaHostSoundControl *pahsc; - if( past == NULL ) return paBadStreamPtr; - pahsc = (PaHostSoundControl *) past->past_DeviceData; - if( pahsc == NULL ) return paInternalError; - return (PaError) past->past_IsActive; + PaMacCoreStream *stream = (PaMacCoreStream*)s; + VVDBUG(("IsStreamActive()\n")); + return ( stream->state == ACTIVE || stream->state == STOPPING ); } -/*************************************************************************/ -PaTimestamp Pa_StreamTime( PortAudioStream *stream ) + +static double GetStreamCpuLoad( PaStream* s ) { - AudioTimeStamp timeStamp; - PaTimestamp streamTime; - PaHostSoundControl *pahsc; - internalPortAudioStream *past = (internalPortAudioStream *) stream; - if( past == NULL ) return paBadStreamPtr; - pahsc = (PaHostSoundControl *) past->past_DeviceData; - - AudioDeviceGetCurrentTime(pahsc->pahsc_AudioDeviceID, &timeStamp); - - streamTime = ( timeStamp.mFlags & kAudioTimeStampSampleTimeValid) ? - timeStamp.mSampleTime : past->past_FrameCount; - - return streamTime; + PaMacCoreStream *stream = (PaMacCoreStream*)s; + VVDBUG(("GetStreamCpuLoad()\n")); + + 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. IMPLEMENTME: no blocking interface yet! +*/ +#include "pa_mac_core_blocking.c" diff --git a/pa_mac_core/pa_mac_core.h b/pa_mac_core/pa_mac_core.h new file mode 100644 index 0000000..5994294 --- /dev/null +++ b/pa_mac_core/pa_mac_core.h @@ -0,0 +1,69 @@ +/* + * Mac spcific flags for PA. + * portaudio.h should be included before this file. + */ + +/* + * A pointer to a paMacCoreStreamInfo may be passed as + * the hostApiSpecificStreamInfo in the PaStreamParameters struct + * when opening a stream. Use NULL, for the defaults. Note that for + * duplex streams, both infos should be the same or behaviour + * is undefined. + */ +typedef struct paMacCoreStreamInfo +{ + 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 */ +} paMacCoreStreamInfo; + +/* Use this function to initialize a paMacCoreStreamInfo struct + using the requested flags. */ +void paSetupMacCoreStreamInfo( paMacCoreStreamInfo *data, unsigned long flags ) +{ + bzero( data, sizeof( paMacCoreStreamInfo ) ); + data->size = sizeof( paMacCoreStreamInfo ); + data->hostApiType = paCoreAudio; + data->version = 0x01; + data->flags = 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. */ +const unsigned long paMacCore_ChangeDeviceParameters = 0x01; + +/* In combination with the above flag, + * causes the stream opening to fail, unless the exact sample rates + * are supported by the device. */ +const unsigned long paMacCore_FailIfConversionRequired = 0x02; + +/* These flags set the SR conversion quality, if required. The wierd ordering + * allows Maximum Quality to be the default.*/ +const unsigned long paMacCore_ConversionQualityMin = 0x0100; +const unsigned long paMacCore_ConversionQualityMedium = 0x0200; +const unsigned long paMacCore_ConversionQualityLow = 0x0300; +const unsigned long paMacCore_ConversionQualityHigh = 0x0400; +const unsigned long paMacCore_ConversionQualityMax = 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. */ +const unsigned long 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.*/ +const unsigned long paMacCorePro = 0x01; +/*This is a setting to minimize CPU usage and still play nice.*/ +const unsigned long paMacCoreMinimizeCPUButPlayNice = 0x0100; +/*This is a setting to minimize CPU usage, even if that means interrupting the device. */ +const unsigned long paMacCoreMinimizeCPU = 0x0101; diff --git a/pa_mac_core/pa_mac_core_blocking.c b/pa_mac_core/pa_mac_core_blocking.c new file mode 100644 index 0000000..7fa5993 --- /dev/null +++ b/pa_mac_core/pa_mac_core_blocking.c @@ -0,0 +1,484 @@ +/* This file is included in pa_mac_core.c. It contains the implementation + * required for blocking I/O. It is separated from pa_mac_core.c simply to ease + * development. */ + +/* + * Functions for initializing, resetting, and destroying BLIO structures. + * + */ + +/* This should be called with the relevant info when initializing a stream for + callback. */ +static PaError initializeBlioRingBuffers( + PaMacBlio *blio, + PaSampleFormat inputSampleFormat, + PaSampleFormat outputSampleFormat, + size_t framesPerBuffer, + long ringBufferSize, + int inChan, + int outChan ) +{ + void *data; + int result; + + /* zeroify things */ + bzero( blio, sizeof( PaMacBlio ) ); + /* this is redundant, but the buffers are used to check + if the bufffers have been initialized, so we do it explicitly. */ + blio->inputRingBuffer.buffer = NULL; + blio->outputRingBuffer.buffer = NULL; + + /* initialize simple data */ + blio->inputSampleFormat = inputSampleFormat; + blio->inputSampleSize = computeSampleSizeFromFormat(inputSampleFormat); + blio->outputSampleFormat = outputSampleFormat; + blio->outputSampleSize = computeSampleSizeFromFormat(outputSampleFormat); + blio->framesPerBuffer = framesPerBuffer; + blio->inChan = inChan; + blio->outChan = outChan; + blio->statusFlags = 0; + blio->errors = paNoError; +#ifdef PA_MAC_BLIO_MUTEX + blio->isInputEmpty = false; + blio->isOutputFull = false; +#endif + + /* setup ring buffers */ +#ifdef PA_MAC_BLIO_MUTEX + result = PaMacCore_SetUnixError( pthread_mutex_init(&(blio->inputMutex),NULL), 0 ); + if( result ) + goto error; + result = UNIX_ERR( pthread_cond_init( &(blio->inputCond), NULL ) ); + if( result ) + goto error; + result = UNIX_ERR( pthread_mutex_init(&(blio->outputMutex),NULL) ); + if( result ) + goto error; + result = UNIX_ERR( pthread_cond_init( &(blio->outputCond), NULL ) ); +#endif + if( inChan ) { + data = calloc( ringBufferSize, blio->inputSampleSize ); + if( !data ) + { + result = paInsufficientMemory; + goto error; + } + + assert( 0 == RingBuffer_Init( + &blio->inputRingBuffer, + ringBufferSize*blio->inputSampleSize, + data ) ); + } + if( outChan ) { + data = calloc( ringBufferSize, blio->outputSampleSize ); + if( !data ) + { + result = paInsufficientMemory; + goto error; + } + + assert( 0 == RingBuffer_Init( + &blio->outputRingBuffer, + ringBufferSize*blio->outputSampleSize, + data ) ); + } + + result = resetBlioRingBuffers( blio ); + if( result ) + goto error; + + return 0; + + error: + destroyBlioRingBuffers( blio ); + return result; +} + +#ifdef PA_MAC_BLIO_MUTEX +static PaError blioSetIsInputEmpty( PaMacBlio *blio, bool isEmpty ) +{ + PaError result = paNoError; + if( isEmpty == blio->isInputEmpty ) + goto done; + + /* we need to update the value. Here's what we do: + * - Lock the mutex, so noone else can write. + * - update the value. + * - unlock. + * - broadcast to all listeners. + */ + result = UNIX_ERR( pthread_mutex_lock( &blio->inputMutex ) ); + if( result ) + goto done; + blio->isInputEmpty = isEmpty; + result = UNIX_ERR( pthread_mutex_unlock( &blio->inputMutex ) ); + if( result ) + goto done; + result = UNIX_ERR( pthread_cond_broadcast( &blio->inputCond ) ); + if( result ) + goto done; + + done: + return result; +} +static PaError blioSetIsOutputFull( PaMacBlio *blio, bool isFull ) +{ + PaError result = paNoError; + if( isFull == blio->isOutputFull ) + goto done; + + /* we need to update the value. Here's what we do: + * - Lock the mutex, so noone else can write. + * - update the value. + * - unlock. + * - broadcast to all listeners. + */ + result = UNIX_ERR( pthread_mutex_lock( &blio->outputMutex ) ); + if( result ) + goto done; + blio->isOutputFull = isFull; + result = UNIX_ERR( pthread_mutex_unlock( &blio->outputMutex ) ); + if( result ) + goto done; + result = UNIX_ERR( pthread_cond_broadcast( &blio->outputCond ) ); + if( result ) + goto done; + + done: + return result; +} +#endif + +/* This should be called after stopping or aborting the stream, so that on next + start, the buffers will be ready. */ +static PaError resetBlioRingBuffers( PaMacBlio *blio ) +{ + int result; + if( blio->outputRingBuffer.buffer ) { + //const int toAdvance = blio->framesPerBuffer*blio->outChan*blio->outputSampleSize; + RingBuffer_Flush( &blio->outputRingBuffer ); + bzero( blio->outputRingBuffer.buffer, + blio->outputRingBuffer.bufferSize ); + /* Advance buffer */ + //if( toAdvance > blio->outputRingBuffer.bufferSize ) { + // result = paInternalError; + // PaUtil_SetLastHostErrorInfo( paCoreAudio, paInternalError, "Output buffer cannot advance more than buffer size." ); + // goto error; + //} + RingBuffer_AdvanceWriteIndex( &blio->outputRingBuffer, blio->outputRingBuffer.bufferSize ); //toAdvance ); + + /* Update isOutputFull. */ +#ifdef PA_MAC__BLIO_MUTEX + result = blioSetIsOutputFull( blio, toAdvance == blio->outputRingBuffer.bufferSize ); + if( result ) + goto error; +#endif +/* + printf( "------%d\n" , blio->framesPerBuffer ); + printf( "------%d\n" , blio->outChan ); + printf( "------%d\n" , blio->outputSampleSize ); + printf( "------%d\n" , blio->framesPerBuffer*blio->outChan*blio->outputSampleSize ); +*/ + } + if( blio->inputRingBuffer.buffer ) { + RingBuffer_Flush( &blio->inputRingBuffer ); + bzero( blio->inputRingBuffer.buffer, + blio->inputRingBuffer.bufferSize ); + /* Update isInputEmpty. */ +#ifdef PA_MAC__BLIO_MUTEX + result = blioSetIsInputEmpty( blio, true ); + if( result ) + goto error; +#endif + } + return paNoError; + error: + return result; +} + +/*This should be called when you are done with the blio. It can safely be called + multiple times if there are no exceptions. */ +static PaError destroyBlioRingBuffers( PaMacBlio *blio ) +{ + PaError result = paNoError; + if( blio->inputRingBuffer.buffer ) { + free( blio->inputRingBuffer.buffer ); +#ifdef PA_MAC__BLIO_MUTEX + result = UNIX_ERR( pthread_mutex_destroy( & blio->inputMutex ) ); + if( result ) return result; + result = UNIX_ERR( pthread_cond_destroy( & blio->inputCond ) ); + if( result ) return result; +#endif + } + blio->inputRingBuffer.buffer = NULL; + if( blio->outputRingBuffer.buffer ) { + free( blio->outputRingBuffer.buffer ); +#ifdef PA_MAC__BLIO_MUTEX + result = UNIX_ERR( pthread_mutex_destroy( & blio->outputMutex ) ); + if( result ) return result; + result = UNIX_ERR( pthread_cond_destroy( & blio->outputCond ) ); + if( result ) return result; +#endif + } + blio->outputRingBuffer.buffer = NULL; + + return result; +} + +/* + * this is the BlioCallback function. It expects to recieve a PaMacBlio Object + * pointer as userData. + * + */ +static int BlioCallback( const void *input, void *output, unsigned long frameCount, + const PaStreamCallbackTimeInfo* timeInfo, + PaStreamCallbackFlags statusFlags, + void *userData ) +{ + PaMacBlio *blio = (PaMacBlio*)userData; + long avail; + long toRead; + long toWrite; + + /* set flags returned by OS: */ + blio->statusFlags |= statusFlags ; + + /* --- Handle Input Buffer --- */ + if( blio->inChan ) { + avail = RingBuffer_GetWriteAvailable( &blio->inputRingBuffer ); + + /* check for underflow */ + if( avail < frameCount * blio->inputSampleSize * blio->inChan ) + blio->statusFlags |= paInputOverflow; + + toRead = MIN( avail, frameCount * blio->inputSampleSize * blio->inChan ); + + /* copy the data */ + /*printf( "reading %d\n", toRead );*/ + assert( toRead == RingBuffer_Write( &blio->inputRingBuffer, input, toRead ) ); +#ifdef PA_MAC__BLIO_MUTEX + /* Priority inversion. See notes below. */ + blioSetIsInputEmpty( blio, false ); +#endif + } + + + /* --- Handle Output Buffer --- */ + if( blio->outChan ) { + avail = RingBuffer_GetReadAvailable( &blio->outputRingBuffer ); + + /* check for underflow */ + if( avail < frameCount * blio->outputSampleSize * blio->outChan ) + blio->statusFlags |= paOutputUnderflow; + + toWrite = MIN( avail, frameCount * blio->outputSampleSize * blio->outChan ); + + if( toWrite != frameCount * blio->outputSampleSize * blio->outChan ) + bzero( ((char *)output)+toWrite, + frameCount * blio->outputSampleSize * blio->outChan - toWrite ); + /* copy the data */ + /*printf( "writing %d\n", toWrite );*/ + assert( toWrite == RingBuffer_Read( &blio->outputRingBuffer, output, toWrite ) ); +#ifdef PA_MAC__BLIO_MUTEX + /* We have a priority inversion here. However, we will only have to + wait if this was true and is now false, which means we've got + some room in the buffer. + Hopefully problems will be minimized. */ + blioSetIsOutputFull( blio, false ); +#endif + } + + return paContinue; +} + +/* FIXME: test that buffer is fully played out on stop */ + +static PaError ReadStream( PaStream* stream, + void *buffer, + unsigned long frames ) +{ + PaMacBlio *blio = & ((PaMacCoreStream*)stream) -> blio; + char *cbuf = (char *) buffer; + PaError ret = paNoError; + VVDBUG(("ReadStream()\n")); + + while( frames > 0 ) { + long avail; + long toRead; + do { + avail = RingBuffer_GetReadAvailable( &blio->inputRingBuffer ); +/* + printf( "Read Buffer is %%%g full: %ld of %ld.\n", + 100 * (float)avail / (float) blio->inputRingBuffer.bufferSize, + avail, blio->inputRingBuffer.bufferSize ); +*/ + if( avail == 0 ) { +#ifdef PA_MAC_BLIO_MUTEX + /**block when empty*/ + ret = UNIX_ERR( pthread_mutex_lock( &blio->inputMutex ) ); + if( ret ) + return ret; + while( blio->isInputEmpty ) { + ret = UNIX_ERR( pthread_cond_wait( &blio->inputCond, &blio->inputMutex ) ); + if( ret ) + return ret; + } + ret = UNIX_ERR( pthread_mutex_unlock( &blio->inputMutex ) ); + if( ret ) + return ret; +#else + Pa_Sleep( PA_MAC_BLIO_BUSY_WAIT_SLEEP_INTERVAL ); +#endif + } + } while( avail == 0 ); + toRead = MIN( avail, frames * blio->inputSampleSize * blio->inChan ); + toRead -= toRead % blio->inputSampleSize * blio->inChan ; + RingBuffer_Read( &blio->inputRingBuffer, (void *)cbuf, toRead ); + cbuf += toRead; + frames -= toRead / ( blio->inputSampleSize * blio->inChan ); + + if( toRead == avail ) { +#ifdef PA_MAC_BLIO_MUTEX + /* we just emptied the buffer, so we need to mark it as empty. */ + ret = blioSetIsInputEmpty( blio, true ); + if( ret ) + return ret; + /* of course, in the meantime, the callback may have put some sats + in, so + so check for that, too, to avoid a race condition. */ + if( RingBuffer_GetReadAvailable( &blio->inputRingBuffer ) ) { + blioSetIsInputEmpty( blio, false ); + if( ret ) + return ret; + } +#endif + } + } + + /* Report either paNoError or paInputOverflowed. */ + /* may also want to report other errors, but this is non-standard. */ + ret = blio->statusFlags & paInputOverflow; + + /* report overflow only once: */ + blio->statusFlags &= ~paInputOverflow; + + if (ret) + ret = paInputOverflowed; + + return ret; +} + + +static PaError WriteStream( PaStream* stream, + const void *buffer, + unsigned long frames ) +{ + PaMacBlio *blio = & ((PaMacCoreStream*)stream) -> blio; + char *cbuf = (char *) buffer; + PaError ret = paNoError; + VVDBUG(("WriteStream()\n")); + + while( frames > 0 ) { + long avail = 0; + long toWrite; + + do { + avail = RingBuffer_GetWriteAvailable( &blio->outputRingBuffer ); +/* + printf( "Write Buffer is %%%g full: %ld of %ld.\n", + 100 - 100 * (float)avail / (float) blio->outputRingBuffer.bufferSize, + avail, blio->outputRingBuffer.bufferSize ); +*/ + if( avail == 0 ) { +#ifdef PA_MAC_BLIO_MUTEX + /*block while full*/ + ret = UNIX_ERR( pthread_mutex_lock( &blio->outputMutex ) ); + if( ret ) + return ret; + while( blio->isOutputFull ) { + ret = UNIX_ERR( pthread_cond_wait( &blio->outputCond, &blio->outputMutex ) ); + if( ret ) + return ret; + } + ret = UNIX_ERR( pthread_mutex_unlock( &blio->outputMutex ) ); + if( ret ) + return ret; +#else + Pa_Sleep( PA_MAC_BLIO_BUSY_WAIT_SLEEP_INTERVAL ); +#endif + } + } while( avail == 0 ); + + toWrite = MIN( avail, frames * blio->outputSampleSize * blio->outChan ); + toWrite -= toWrite % blio->outputSampleSize * blio->outChan ; + RingBuffer_Write( &blio->outputRingBuffer, (void *)cbuf, toWrite ); + cbuf += toWrite; + frames -= toWrite / ( blio->outputSampleSize * blio->outChan ); + +#ifdef PA_MAC_BLIO_MUTEX + if( toWrite == avail ) { + /* we just filled up the buffer, so we need to mark it as filled. */ + ret = blioSetIsOutputFull( blio, true ); + if( ret ) + return ret; + /* of course, in the meantime, we may have emptied the buffer, so + so check for that, too, to avoid a race condition. */ + if( RingBuffer_GetWriteAvailable( &blio->outputRingBuffer ) ) { + blioSetIsOutputFull( blio, false ); + if( ret ) + return ret; + } + } +#endif + } + + /* Report either paNoError or paOutputUnderflowed. */ + /* may also want to report other errors, but this is non-standard. */ + ret = blio->statusFlags & paOutputUnderflow; + + /* FIXME: restting this flag is not MP/SMP safe. use compare_and_Swap wherever these flags are changed. */ + /* report underflow only once: */ + blio->statusFlags &= ~paOutputUnderflow; + + if (ret) + ret = paOutputUnderflowed; + + return ret; +} + +/* + * + */ +static void waitUntilBlioWriteBufferIsFlushed( PaMacBlio *blio ) +{ + if( blio->outputRingBuffer.buffer ) { + long avail = RingBuffer_GetWriteAvailable( &blio->outputRingBuffer ); + while( avail != blio->outputRingBuffer.bufferSize ) { + /*FIXME: do a true block.*/ + if( avail == 0 ) + Pa_Sleep( PA_MAC_BLIO_BUSY_WAIT_SLEEP_INTERVAL ); + avail = RingBuffer_GetWriteAvailable( &blio->outputRingBuffer ); + } + } +} + + +static signed long GetStreamReadAvailable( PaStream* stream ) +{ + PaMacBlio *blio = & ((PaMacCoreStream*)stream) -> blio; + VVDBUG(("GetStreamReadAvailable()\n")); + + return RingBuffer_GetReadAvailable( &blio->inputRingBuffer ) + / ( blio->outputSampleSize * blio->outChan ); +} + + +static signed long GetStreamWriteAvailable( PaStream* stream ) +{ + PaMacBlio *blio = & ((PaMacCoreStream*)stream) -> blio; + VVDBUG(("GetStreamWriteAvailable()\n")); + + return RingBuffer_GetWriteAvailable( &blio->outputRingBuffer ) + / ( blio->outputSampleSize * blio->outChan ); +} + diff --git a/pa_mac_core/pa_mac_core_blocking.h b/pa_mac_core/pa_mac_core_blocking.h new file mode 100644 index 0000000..67c42d9 --- /dev/null +++ b/pa_mac_core/pa_mac_core_blocking.h @@ -0,0 +1,82 @@ + +/* + * Number of miliseconds to busy wait whil waiting for data in blocking calls. + */ +#define PA_MAC_BLIO_BUSY_WAIT_SLEEP_INTERVAL (5) +/* + *Define exactly one of these blocking methods + */ +#define PA_MAC_BLIO_BUSY_WAIT +/* +#define PA_MAC_BLIO_MUTEX +*/ + +typedef struct { + RingBuffer inputRingBuffer; + RingBuffer outputRingBuffer; + PaSampleFormat inputSampleFormat; + size_t inputSampleSize; + PaSampleFormat outputSampleFormat; + size_t outputSampleSize; + + size_t framesPerBuffer; + + int inChan; + int outChan; + + PaStreamCallbackFlags statusFlags; + PaError errors; + + /* Here we handle blocking, using condition variables. */ +#ifdef PA_MAC_BLIO_MUTEX + volatile bool isInputEmpty; + pthread_mutex_t inputMutex; + pthread_cond_t inputCond; + + volatile bool isOutputFull; + pthread_mutex_t outputMutex; + pthread_cond_t outputCond; +#endif +} +PaMacBlio; + +/* + * These functions operate on condition and related variables. + */ + +/* + * This fnuction determines the size of a particular sample format. + * if the format is not recognized, this returns zero. + */ +static size_t computeSampleSizeFromFormat( PaSampleFormat format ) +{ + switch( format ) { + case paFloat32: return 4; + case paInt32: return 4; + case paInt24: return 3; + case paInt16: return 2; + case paInt8: case paUInt8: return 1; + default: return 0; + } +} + + +static PaError initializeBlioRingBuffers( + PaMacBlio *blio, + PaSampleFormat inputSampleFormat, + PaSampleFormat outputSampleFormat, + size_t framesPerBuffer, + long ringBufferSize, + int inChan, + int outChan ); +static PaError destroyBlioRingBuffers( PaMacBlio *blio ); +static PaError resetBlioRingBuffers( PaMacBlio *blio ); + +static int BlioCallback( + const void *input, void *output, + unsigned long frameCount, + const PaStreamCallbackTimeInfo* timeInfo, + PaStreamCallbackFlags statusFlags, + void *userData ); + +static void waitUntilBlioWriteBufferIsFlushed( PaMacBlio *blio ); diff --git a/pa_mac_core/pa_mac_core_old.c b/pa_mac_core/pa_mac_core_old.c new file mode 100644 index 0000000..d9a2df2 --- /dev/null +++ b/pa_mac_core/pa_mac_core_old.c @@ -0,0 +1,907 @@ +/* + * $Id$ + * pa_mac_core.c + * Implementation of PortAudio for Mac OS X CoreAudio + * + * PortAudio Portable Real-Time Audio Library + * Latest Version at: http://www.portaudio.com + * + * Authors: Ross Bencina and Phil Burk + * 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. + * + */ + +#include +#include +#include +#include +#include +#include + +#include "portaudio.h" +#include "pa_trace.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" + +// ===== constants ===== + +// ===== structs ===== +#pragma mark structs + +// PaMacCoreHostApiRepresentation - host api datastructure specific to this implementation +typedef struct PaMacCore_HAR +{ + PaUtilHostApiRepresentation inheritedHostApiRep; + PaUtilStreamInterface callbackStreamInterface; + PaUtilStreamInterface blockingStreamInterface; + + PaUtilAllocationGroup *allocations; + AudioDeviceID *macCoreDeviceIds; +} +PaMacCoreHostApiRepresentation; + +typedef struct PaMacCore_DI +{ + PaDeviceInfo inheritedDeviceInfo; +} +PaMacCoreDeviceInfo; + +// PaMacCoreStream - a stream data structure specifically for this implementation +typedef struct PaMacCore_S +{ + PaUtilStreamRepresentation streamRepresentation; + PaUtilCpuLoadMeasurer cpuLoadMeasurer; + PaUtilBufferProcessor bufferProcessor; + + int primeStreamUsingCallback; + + AudioDeviceID inputDevice; + AudioDeviceID outputDevice; + + // Processing thread management -------------- +// HANDLE abortEvent; +// HANDLE processingThread; +// DWORD processingThreadId; + + char throttleProcessingThreadOnOverload; // 0 -> don't throtte, non-0 -> throttle + int processingThreadPriority; + int highThreadPriority; + int throttledThreadPriority; + unsigned long throttledSleepMsecs; + + int isStopped; + volatile int isActive; + volatile int stopProcessing; // stop thread once existing buffers have been returned + volatile int abortProcessing; // stop thread immediately + +// DWORD allBuffersDurationMs; // used to calculate timeouts +} +PaMacCoreStream; + +// Data needed by the CoreAudio callback functions +typedef struct PaMacCore_CD +{ + PaMacCoreStream *stream; + PaStreamCallback *callback; + void *userData; + PaUtilConverter *inputConverter; + PaUtilConverter *outputConverter; + void *inputBuffer; + void *outputBuffer; + int inputChannelCount; + int outputChannelCount; + PaSampleFormat inputSampleFormat; + PaSampleFormat outputSampleFormat; + PaUtilTriangularDitherGenerator *ditherGenerator; +} +PaMacClientData; + +// ===== CoreAudio-PortAudio bridge functions ===== +#pragma mark CoreAudio-PortAudio bridge functions + +// Maps CoreAudio OSStatus codes to PortAudio PaError codes +static PaError conv_err(OSStatus error) +{ + PaError result; + + switch (error) { + case kAudioHardwareNoError: + result = paNoError; break; + case kAudioHardwareNotRunningError: + result = paInternalError; break; + case kAudioHardwareUnspecifiedError: + result = paInternalError; break; + case kAudioHardwareUnknownPropertyError: + result = paInternalError; break; + case kAudioHardwareBadPropertySizeError: + result = paInternalError; break; + case kAudioHardwareIllegalOperationError: + result = paInternalError; break; + case kAudioHardwareBadDeviceError: + result = paInvalidDevice; break; + case kAudioHardwareBadStreamError: + result = paBadStreamPtr; break; + case kAudioHardwareUnsupportedOperationError: + result = paInternalError; break; + case kAudioDeviceUnsupportedFormatError: + result = paSampleFormatNotSupported; break; + case kAudioDevicePermissionsError: + result = paDeviceUnavailable; break; + default: + result = paInternalError; + } + + return result; +} + +/* This function is unused +static AudioStreamBasicDescription *InitializeStreamDescription(const PaStreamParameters *parameters, double sampleRate) +{ + struct AudioStreamBasicDescription *streamDescription = PaUtil_AllocateMemory(sizeof(AudioStreamBasicDescription)); + streamDescription->mSampleRate = sampleRate; + streamDescription->mFormatID = kAudioFormatLinearPCM; + streamDescription->mFormatFlags = 0; + streamDescription->mFramesPerPacket = 1; + + if (parameters->sampleFormat & paNonInterleaved) { + streamDescription->mFormatFlags |= kLinearPCMFormatFlagIsNonInterleaved; + streamDescription->mChannelsPerFrame = 1; + streamDescription->mBytesPerFrame = Pa_GetSampleSize(parameters->sampleFormat); + streamDescription->mBytesPerPacket = Pa_GetSampleSize(parameters->sampleFormat); + } + else { + streamDescription->mChannelsPerFrame = parameters->channelCount; + } + + streamDescription->mBytesPerFrame = Pa_GetSampleSize(parameters->sampleFormat) * streamDescription->mChannelsPerFrame; + streamDescription->mBytesPerPacket = streamDescription->mBytesPerFrame * streamDescription->mFramesPerPacket; + + if (parameters->sampleFormat & paFloat32) { + streamDescription->mFormatFlags |= kLinearPCMFormatFlagIsFloat; + streamDescription->mBitsPerChannel = 32; + } + else if (parameters->sampleFormat & paInt32) { + streamDescription->mFormatFlags |= kLinearPCMFormatFlagIsSignedInteger; + streamDescription->mBitsPerChannel = 32; + } + else if (parameters->sampleFormat & paInt24) { + streamDescription->mFormatFlags |= kLinearPCMFormatFlagIsSignedInteger; + streamDescription->mBitsPerChannel = 24; + } + else if (parameters->sampleFormat & paInt16) { + streamDescription->mFormatFlags |= kLinearPCMFormatFlagIsSignedInteger; + streamDescription->mBitsPerChannel = 16; + } + else if (parameters->sampleFormat & paInt8) { + streamDescription->mFormatFlags |= kLinearPCMFormatFlagIsSignedInteger; + streamDescription->mBitsPerChannel = 8; + } + else if (parameters->sampleFormat & paInt32) { + streamDescription->mBitsPerChannel = 8; + } + + return streamDescription; +} +*/ + +static PaStreamCallbackTimeInfo *InitializeTimeInfo(const AudioTimeStamp* now, const AudioTimeStamp* inputTime, const AudioTimeStamp* outputTime) +{ + PaStreamCallbackTimeInfo *timeInfo = PaUtil_AllocateMemory(sizeof(PaStreamCallbackTimeInfo)); + + timeInfo->inputBufferAdcTime = inputTime->mSampleTime; + timeInfo->currentTime = now->mSampleTime; + timeInfo->outputBufferDacTime = outputTime->mSampleTime; + + return timeInfo; +} + +// ===== support functions ===== +#pragma mark support functions + +static void CleanUp(PaMacCoreHostApiRepresentation *macCoreHostApi) +{ + if( macCoreHostApi->allocations ) + { + PaUtil_FreeAllAllocations( macCoreHostApi->allocations ); + PaUtil_DestroyAllocationGroup( macCoreHostApi->allocations ); + } + + PaUtil_FreeMemory( macCoreHostApi ); +} + +static PaError GetChannelInfo(PaDeviceInfo *deviceInfo, AudioDeviceID macCoreDeviceId, int isInput) +{ + UInt32 propSize; + PaError err = paNoError; + UInt32 i; + int numChannels = 0; + AudioBufferList *buflist; + + err = conv_err(AudioDeviceGetPropertyInfo(macCoreDeviceId, 0, isInput, kAudioDevicePropertyStreamConfiguration, &propSize, NULL)); + buflist = PaUtil_AllocateMemory(propSize); + err = conv_err(AudioDeviceGetProperty(macCoreDeviceId, 0, isInput, kAudioDevicePropertyStreamConfiguration, &propSize, buflist)); + if (!err) { + for (i = 0; i < buflist->mNumberBuffers; ++i) { + numChannels += buflist->mBuffers[i].mNumberChannels; + } + + if (isInput) + deviceInfo->maxInputChannels = numChannels; + else + deviceInfo->maxOutputChannels = numChannels; + + int frameLatency; + propSize = sizeof(UInt32); + err = conv_err(AudioDeviceGetProperty(macCoreDeviceId, 0, isInput, kAudioDevicePropertyLatency, &propSize, &frameLatency)); + if (!err) { + double secondLatency = frameLatency / deviceInfo->defaultSampleRate; + if (isInput) { + deviceInfo->defaultLowInputLatency = secondLatency; + deviceInfo->defaultHighInputLatency = secondLatency; + } + else { + deviceInfo->defaultLowOutputLatency = secondLatency; + deviceInfo->defaultHighOutputLatency = secondLatency; + } + } + } + PaUtil_FreeMemory(buflist); + + return err; +} + +static PaError InitializeDeviceInfo(PaMacCoreDeviceInfo *macCoreDeviceInfo, AudioDeviceID macCoreDeviceId, PaHostApiIndex hostApiIndex ) +{ + PaDeviceInfo *deviceInfo = &macCoreDeviceInfo->inheritedDeviceInfo; + deviceInfo->structVersion = 2; + deviceInfo->hostApi = hostApiIndex; + + PaError err = paNoError; + UInt32 propSize; + + err = conv_err(AudioDeviceGetPropertyInfo(macCoreDeviceId, 0, 0, kAudioDevicePropertyDeviceName, &propSize, NULL)); + // FIXME: this allocation should be part of the allocations group + char *name = PaUtil_AllocateMemory(propSize); + err = conv_err(AudioDeviceGetProperty(macCoreDeviceId, 0, 0, kAudioDevicePropertyDeviceName, &propSize, name)); + if (!err) { + deviceInfo->name = name; + } + + Float64 sampleRate; + propSize = sizeof(Float64); + err = conv_err(AudioDeviceGetProperty(macCoreDeviceId, 0, 0, kAudioDevicePropertyNominalSampleRate, &propSize, &sampleRate)); + if (!err) { + deviceInfo->defaultSampleRate = sampleRate; + } + + + // Get channel info + err = GetChannelInfo(deviceInfo, macCoreDeviceId, 1); + err = GetChannelInfo(deviceInfo, macCoreDeviceId, 0); + + return err; +} + +static PaError InitializeDeviceInfos( PaMacCoreHostApiRepresentation *macCoreHostApi, PaHostApiIndex hostApiIndex ) +{ + PaError result = paNoError; + PaUtilHostApiRepresentation *hostApi; + PaMacCoreDeviceInfo *deviceInfoArray; + + // initialise device counts and default devices under the assumption that there are no devices. These values are incremented below if and when devices are successfully initialized. + hostApi = &macCoreHostApi->inheritedHostApiRep; + hostApi->info.deviceCount = 0; + hostApi->info.defaultInputDevice = paNoDevice; + hostApi->info.defaultOutputDevice = paNoDevice; + + UInt32 propsize; + AudioHardwareGetPropertyInfo(kAudioHardwarePropertyDevices, &propsize, NULL); + int numDevices = propsize / sizeof(AudioDeviceID); + hostApi->info.deviceCount = numDevices; + if (numDevices > 0) { + hostApi->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory( + macCoreHostApi->allocations, sizeof(PaDeviceInfo*) * numDevices ); + if( !hostApi->deviceInfos ) + { + return paInsufficientMemory; + } + + // allocate all device info structs in a contiguous block + deviceInfoArray = (PaMacCoreDeviceInfo*)PaUtil_GroupAllocateMemory( + macCoreHostApi->allocations, sizeof(PaMacCoreDeviceInfo) * numDevices ); + if( !deviceInfoArray ) + { + return paInsufficientMemory; + } + + macCoreHostApi->macCoreDeviceIds = PaUtil_GroupAllocateMemory(macCoreHostApi->allocations, propsize); + AudioHardwareGetProperty(kAudioHardwarePropertyDevices, &propsize, macCoreHostApi->macCoreDeviceIds); + + AudioDeviceID defaultInputDevice, defaultOutputDevice; + propsize = sizeof(AudioDeviceID); + AudioHardwareGetProperty(kAudioHardwarePropertyDefaultInputDevice, &propsize, &defaultInputDevice); + AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, &propsize, &defaultOutputDevice); + + UInt32 i; + for (i = 0; i < numDevices; ++i) { + if (macCoreHostApi->macCoreDeviceIds[i] == defaultInputDevice) { + hostApi->info.defaultInputDevice = i; + } + if (macCoreHostApi->macCoreDeviceIds[i] == defaultOutputDevice) { + hostApi->info.defaultOutputDevice = i; + } + InitializeDeviceInfo(&deviceInfoArray[i], macCoreHostApi->macCoreDeviceIds[i], hostApiIndex); + hostApi->deviceInfos[i] = &(deviceInfoArray[i].inheritedDeviceInfo); + } + } + + return result; +} + +static OSStatus CheckFormat(AudioDeviceID macCoreDeviceId, const PaStreamParameters *parameters, double sampleRate, int isInput) +{ + UInt32 propSize = sizeof(AudioStreamBasicDescription); + AudioStreamBasicDescription *streamDescription = PaUtil_AllocateMemory(propSize); + + streamDescription->mSampleRate = sampleRate; + streamDescription->mFormatID = 0; + streamDescription->mFormatFlags = 0; + streamDescription->mBytesPerPacket = 0; + streamDescription->mFramesPerPacket = 0; + streamDescription->mBytesPerFrame = 0; + streamDescription->mChannelsPerFrame = 0; + streamDescription->mBitsPerChannel = 0; + streamDescription->mReserved = 0; + + OSStatus result = AudioDeviceGetProperty(macCoreDeviceId, 0, isInput, kAudioDevicePropertyStreamFormatSupported, &propSize, streamDescription); + PaUtil_FreeMemory(streamDescription); + return result; +} + +static OSStatus CopyInputData(PaMacClientData* destination, const AudioBufferList *source, unsigned long frameCount) +{ + int frameSpacing, channelSpacing; + if (destination->inputSampleFormat & paNonInterleaved) { + frameSpacing = 1; + channelSpacing = destination->inputChannelCount; + } + else { + frameSpacing = destination->inputChannelCount; + channelSpacing = 1; + } + + AudioBuffer const *inputBuffer = &source->mBuffers[0]; + void *coreAudioBuffer = inputBuffer->mData; + void *portAudioBuffer = destination->inputBuffer; + UInt32 i, streamNumber, streamChannel; + for (i = streamNumber = streamChannel = 0; i < destination->inputChannelCount; ++i, ++streamChannel) { + if (streamChannel >= inputBuffer->mNumberChannels) { + ++streamNumber; + inputBuffer = &source->mBuffers[streamNumber]; + coreAudioBuffer = inputBuffer->mData; + streamChannel = 0; + } + destination->inputConverter(portAudioBuffer, frameSpacing, coreAudioBuffer, inputBuffer->mNumberChannels, frameCount, destination->ditherGenerator); + coreAudioBuffer += sizeof(Float32); + portAudioBuffer += Pa_GetSampleSize(destination->inputSampleFormat) * channelSpacing; + } + return noErr; +} + +static OSStatus CopyOutputData(AudioBufferList* destination, PaMacClientData *source, unsigned long frameCount) +{ + int frameSpacing, channelSpacing; + if (source->outputSampleFormat & paNonInterleaved) { + frameSpacing = 1; + channelSpacing = source->outputChannelCount; + } + else { + frameSpacing = source->outputChannelCount; + channelSpacing = 1; + } + + AudioBuffer *outputBuffer = &destination->mBuffers[0]; + void *coreAudioBuffer = outputBuffer->mData; + void *portAudioBuffer = source->outputBuffer; + UInt32 i, streamNumber, streamChannel; + for (i = streamNumber = streamChannel = 0; i < source->outputChannelCount; ++i, ++streamChannel) { + if (streamChannel >= outputBuffer->mNumberChannels) { + ++streamNumber; + outputBuffer = &destination->mBuffers[streamNumber]; + coreAudioBuffer = outputBuffer->mData; + streamChannel = 0; + } + source->outputConverter(coreAudioBuffer, outputBuffer->mNumberChannels, portAudioBuffer, frameSpacing, frameCount, NULL); + coreAudioBuffer += sizeof(Float32); + portAudioBuffer += Pa_GetSampleSize(source->outputSampleFormat) * channelSpacing; + } + return noErr; +} + +static OSStatus AudioIOProc( AudioDeviceID inDevice, + const AudioTimeStamp* inNow, + const AudioBufferList* inInputData, + const AudioTimeStamp* inInputTime, + AudioBufferList* outOutputData, + const AudioTimeStamp* inOutputTime, + void* inClientData) +{ + PaMacClientData *clientData = (PaMacClientData *)inClientData; + PaStreamCallbackTimeInfo *timeInfo = InitializeTimeInfo(inNow, inInputTime, inOutputTime); + + PaUtil_BeginCpuLoadMeasurement( &clientData->stream->cpuLoadMeasurer ); + + AudioBuffer *outputBuffer = &outOutputData->mBuffers[0]; + unsigned long frameCount = outputBuffer->mDataByteSize / (outputBuffer->mNumberChannels * sizeof(Float32)); + + if (clientData->inputBuffer) { + CopyInputData(clientData, inInputData, frameCount); + } + PaStreamCallbackResult result = clientData->callback(clientData->inputBuffer, clientData->outputBuffer, frameCount, timeInfo, paNoFlag, clientData->userData); + if (clientData->outputBuffer) { + CopyOutputData(outOutputData, clientData, frameCount); + } + + PaUtil_EndCpuLoadMeasurement( &clientData->stream->cpuLoadMeasurer, frameCount ); + + if (result == paComplete || result == paAbort) { + Pa_StopStream(clientData->stream); + } + + PaUtil_FreeMemory( timeInfo ); + return noErr; +} + +// This is not for input-only streams, this is for streams where the input device is different from the output device +static OSStatus AudioInputProc( AudioDeviceID inDevice, + const AudioTimeStamp* inNow, + const AudioBufferList* inInputData, + const AudioTimeStamp* inInputTime, + AudioBufferList* outOutputData, + const AudioTimeStamp* inOutputTime, + void* inClientData) +{ + PaMacClientData *clientData = (PaMacClientData *)inClientData; + PaStreamCallbackTimeInfo *timeInfo = InitializeTimeInfo(inNow, inInputTime, inOutputTime); + + PaUtil_BeginCpuLoadMeasurement( &clientData->stream->cpuLoadMeasurer ); + + AudioBuffer const *inputBuffer = &inInputData->mBuffers[0]; + unsigned long frameCount = inputBuffer->mDataByteSize / (inputBuffer->mNumberChannels * sizeof(Float32)); + + CopyInputData(clientData, inInputData, frameCount); + PaStreamCallbackResult result = clientData->callback(clientData->inputBuffer, clientData->outputBuffer, frameCount, timeInfo, paNoFlag, clientData->userData); + + PaUtil_EndCpuLoadMeasurement( &clientData->stream->cpuLoadMeasurer, frameCount ); + if( result == paComplete || result == paAbort ) + Pa_StopStream(clientData->stream); + PaUtil_FreeMemory( timeInfo ); + return noErr; +} + +// This is not for output-only streams, this is for streams where the input device is different from the output device +static OSStatus AudioOutputProc( AudioDeviceID inDevice, + const AudioTimeStamp* inNow, + const AudioBufferList* inInputData, + const AudioTimeStamp* inInputTime, + AudioBufferList* outOutputData, + const AudioTimeStamp* inOutputTime, + void* inClientData) +{ + PaMacClientData *clientData = (PaMacClientData *)inClientData; + //PaStreamCallbackTimeInfo *timeInfo = InitializeTimeInfo(inNow, inInputTime, inOutputTime); + + PaUtil_BeginCpuLoadMeasurement( &clientData->stream->cpuLoadMeasurer ); + + AudioBuffer *outputBuffer = &outOutputData->mBuffers[0]; + unsigned long frameCount = outputBuffer->mDataByteSize / (outputBuffer->mNumberChannels * sizeof(Float32)); + + //clientData->callback(NULL, clientData->outputBuffer, frameCount, timeInfo, paNoFlag, clientData->userData); + + CopyOutputData(outOutputData, clientData, frameCount); + + PaUtil_EndCpuLoadMeasurement( &clientData->stream->cpuLoadMeasurer, frameCount ); + return noErr; +} + +static PaError SetSampleRate(AudioDeviceID device, double sampleRate, int isInput) +{ + PaError result = paNoError; + + double actualSampleRate; + UInt32 propSize = sizeof(double); + result = conv_err(AudioDeviceSetProperty(device, NULL, 0, isInput, kAudioDevicePropertyNominalSampleRate, propSize, &sampleRate)); + + result = conv_err(AudioDeviceGetProperty(device, 0, isInput, kAudioDevicePropertyNominalSampleRate, &propSize, &actualSampleRate)); + + if (result == paNoError && actualSampleRate != sampleRate) { + result = paInvalidSampleRate; + } + + return result; +} + +static PaError SetFramesPerBuffer(AudioDeviceID device, unsigned long framesPerBuffer, int isInput) +{ + PaError result = paNoError; + UInt32 preferredFramesPerBuffer = framesPerBuffer; + // while (preferredFramesPerBuffer > UINT32_MAX) { + // preferredFramesPerBuffer /= 2; + // } + + UInt32 actualFramesPerBuffer; + UInt32 propSize = sizeof(UInt32); + result = conv_err(AudioDeviceSetProperty(device, NULL, 0, isInput, kAudioDevicePropertyBufferFrameSize, propSize, &preferredFramesPerBuffer)); + + result = conv_err(AudioDeviceGetProperty(device, 0, isInput, kAudioDevicePropertyBufferFrameSize, &propSize, &actualFramesPerBuffer)); + + if (result != paNoError) { + // do nothing + } + else if (actualFramesPerBuffer > framesPerBuffer) { + result = paBufferTooSmall; + } + else if (actualFramesPerBuffer < framesPerBuffer) { + result = paBufferTooBig; + } + + return result; +} + +static PaError SetUpUnidirectionalStream(AudioDeviceID device, double sampleRate, unsigned long framesPerBuffer, int isInput) +{ + PaError err = paNoError; + err = SetSampleRate(device, sampleRate, isInput); + if( err == paNoError ) + err = SetFramesPerBuffer(device, framesPerBuffer, isInput); + return err; +} + +// ===== PortAudio functions ===== +#pragma mark PortAudio functions + +#ifdef __cplusplus +extern "C" +{ +#endif // __cplusplus + + PaError PaMacCore_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index ); + +#ifdef __cplusplus +} +#endif // __cplusplus + +static void Terminate( struct PaUtilHostApiRepresentation *hostApi ) +{ + PaMacCoreHostApiRepresentation *macCoreHostApi = (PaMacCoreHostApiRepresentation*)hostApi; + + CleanUp(macCoreHostApi); +} + +static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi, + const PaStreamParameters *inputParameters, + const PaStreamParameters *outputParameters, + double sampleRate ) +{ + PaMacCoreHostApiRepresentation *macCoreHostApi = (PaMacCoreHostApiRepresentation*)hostApi; + PaDeviceInfo *deviceInfo; + + PaError result = paNoError; + if (inputParameters) { + deviceInfo = macCoreHostApi->inheritedHostApiRep.deviceInfos[inputParameters->device]; + if (inputParameters->channelCount > deviceInfo->maxInputChannels) + result = paInvalidChannelCount; + else if (CheckFormat(macCoreHostApi->macCoreDeviceIds[inputParameters->device], inputParameters, sampleRate, 1) != kAudioHardwareNoError) { + result = paInvalidSampleRate; + } + } + if (outputParameters && result == paNoError) { + deviceInfo = macCoreHostApi->inheritedHostApiRep.deviceInfos[outputParameters->device]; + if (outputParameters->channelCount > deviceInfo->maxOutputChannels) + result = paInvalidChannelCount; + else if (CheckFormat(macCoreHostApi->macCoreDeviceIds[outputParameters->device], outputParameters, sampleRate, 0) != kAudioHardwareNoError) { + result = paInvalidSampleRate; + } + } + + return result; +} + +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 err = paNoError; + PaMacCoreHostApiRepresentation *macCoreHostApi = (PaMacCoreHostApiRepresentation *)hostApi; + PaMacCoreStream *stream = PaUtil_AllocateMemory(sizeof(PaMacCoreStream)); + stream->isActive = 0; + stream->isStopped = 1; + stream->inputDevice = kAudioDeviceUnknown; + stream->outputDevice = kAudioDeviceUnknown; + + PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation, + ( (streamCallback) + ? &macCoreHostApi->callbackStreamInterface + : &macCoreHostApi->blockingStreamInterface ), + streamCallback, userData ); + PaUtil_InitializeCpuLoadMeasurer( &stream->cpuLoadMeasurer, sampleRate ); + + *s = (PaStream*)stream; + PaMacClientData *clientData = PaUtil_AllocateMemory(sizeof(PaMacClientData)); + clientData->stream = stream; + clientData->callback = streamCallback; + clientData->userData = userData; + clientData->inputBuffer = 0; + clientData->outputBuffer = 0; + clientData->ditherGenerator = PaUtil_AllocateMemory(sizeof(PaUtilTriangularDitherGenerator)); + PaUtil_InitializeTriangularDitherState(clientData->ditherGenerator); + + if (inputParameters != NULL) { + stream->inputDevice = macCoreHostApi->macCoreDeviceIds[inputParameters->device]; + clientData->inputConverter = PaUtil_SelectConverter(paFloat32, inputParameters->sampleFormat, streamFlags); + clientData->inputBuffer = PaUtil_AllocateMemory(Pa_GetSampleSize(inputParameters->sampleFormat) * framesPerBuffer * inputParameters->channelCount); + clientData->inputChannelCount = inputParameters->channelCount; + clientData->inputSampleFormat = inputParameters->sampleFormat; + err = SetUpUnidirectionalStream(stream->inputDevice, sampleRate, framesPerBuffer, 1); + } + + if (err == paNoError && outputParameters != NULL) { + stream->outputDevice = macCoreHostApi->macCoreDeviceIds[outputParameters->device]; + clientData->outputConverter = PaUtil_SelectConverter(outputParameters->sampleFormat, paFloat32, streamFlags); + clientData->outputBuffer = PaUtil_AllocateMemory(Pa_GetSampleSize(outputParameters->sampleFormat) * framesPerBuffer * outputParameters->channelCount); + clientData->outputChannelCount = outputParameters->channelCount; + clientData->outputSampleFormat = outputParameters->sampleFormat; + err = SetUpUnidirectionalStream(stream->outputDevice, sampleRate, framesPerBuffer, 0); + } + + if (inputParameters == NULL || outputParameters == NULL || stream->inputDevice == stream->outputDevice) { + AudioDeviceID device = (inputParameters == NULL) ? stream->outputDevice : stream->inputDevice; + + AudioDeviceAddIOProc(device, AudioIOProc, clientData); + } + else { + // using different devices for input and output + AudioDeviceAddIOProc(stream->inputDevice, AudioInputProc, clientData); + AudioDeviceAddIOProc(stream->outputDevice, AudioOutputProc, clientData); + } + + return err; +} + +// Note: When CloseStream() is called, the multi-api layer ensures that the stream has already been stopped or aborted. +static PaError CloseStream( PaStream* s ) +{ + PaError err = paNoError; + PaMacCoreStream *stream = (PaMacCoreStream*)s; + + PaUtil_ResetCpuLoadMeasurer( &stream->cpuLoadMeasurer ); + + if (stream->inputDevice != kAudioDeviceUnknown) { + if (stream->outputDevice == kAudioDeviceUnknown || stream->outputDevice == stream->inputDevice) { + err = conv_err(AudioDeviceRemoveIOProc(stream->inputDevice, AudioIOProc)); + } + else { + err = conv_err(AudioDeviceRemoveIOProc(stream->inputDevice, AudioInputProc)); + err = conv_err(AudioDeviceRemoveIOProc(stream->outputDevice, AudioOutputProc)); + } + } + else { + err = conv_err(AudioDeviceRemoveIOProc(stream->outputDevice, AudioIOProc)); + } + + return err; +} + + +static PaError StartStream( PaStream *s ) +{ + PaError err = paNoError; + PaMacCoreStream *stream = (PaMacCoreStream*)s; + + if (stream->inputDevice != kAudioDeviceUnknown) { + if (stream->outputDevice == kAudioDeviceUnknown || stream->outputDevice == stream->inputDevice) { + err = conv_err(AudioDeviceStart(stream->inputDevice, AudioIOProc)); + } + else { + err = conv_err(AudioDeviceStart(stream->inputDevice, AudioInputProc)); + err = conv_err(AudioDeviceStart(stream->outputDevice, AudioOutputProc)); + } + } + else { + err = conv_err(AudioDeviceStart(stream->outputDevice, AudioIOProc)); + } + + stream->isActive = 1; + stream->isStopped = 0; + return err; +} + +static PaError AbortStream( PaStream *s ) +{ + PaError err = paNoError; + PaMacCoreStream *stream = (PaMacCoreStream*)s; + + if (stream->inputDevice != kAudioDeviceUnknown) { + if (stream->outputDevice == kAudioDeviceUnknown || stream->outputDevice == stream->inputDevice) { + err = conv_err(AudioDeviceStop(stream->inputDevice, AudioIOProc)); + } + else { + err = conv_err(AudioDeviceStop(stream->inputDevice, AudioInputProc)); + err = conv_err(AudioDeviceStop(stream->outputDevice, AudioOutputProc)); + } + } + else { + err = conv_err(AudioDeviceStop(stream->outputDevice, AudioIOProc)); + } + + stream->isActive = 0; + stream->isStopped = 1; + return err; +} + +static PaError StopStream( PaStream *s ) +{ + // TODO: this should be nicer than abort + return AbortStream(s); +} + +static PaError IsStreamStopped( PaStream *s ) +{ + PaMacCoreStream *stream = (PaMacCoreStream*)s; + + return stream->isStopped; +} + + +static PaError IsStreamActive( PaStream *s ) +{ + PaMacCoreStream *stream = (PaMacCoreStream*)s; + + return stream->isActive; +} + + +static PaTime GetStreamTime( PaStream *s ) +{ + OSStatus err; + PaTime result; + PaMacCoreStream *stream = (PaMacCoreStream*)s; + + AudioTimeStamp *timeStamp = PaUtil_AllocateMemory(sizeof(AudioTimeStamp)); + if (stream->inputDevice != kAudioDeviceUnknown) { + err = AudioDeviceGetCurrentTime(stream->inputDevice, timeStamp); + } + else { + err = AudioDeviceGetCurrentTime(stream->outputDevice, timeStamp); + } + + result = err ? 0 : timeStamp->mSampleTime; + PaUtil_FreeMemory(timeStamp); + + return result; +} + + +static double GetStreamCpuLoad( PaStream* s ) +{ + PaMacCoreStream *stream = (PaMacCoreStream*)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 ) +{ + return paInternalError; +} + + +static PaError WriteStream( PaStream* s, + const void *buffer, + unsigned long frames ) +{ + return paInternalError; +} + + +static signed long GetStreamReadAvailable( PaStream* s ) +{ + return paInternalError; +} + + +static signed long GetStreamWriteAvailable( PaStream* s ) +{ + return paInternalError; +} + +// HostAPI-specific initialization function +PaError PaMacCore_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex ) +{ + PaError result = paNoError; + PaMacCoreHostApiRepresentation *macCoreHostApi = (PaMacCoreHostApiRepresentation *)PaUtil_AllocateMemory( sizeof(PaMacCoreHostApiRepresentation) ); + if( !macCoreHostApi ) + { + result = paInsufficientMemory; + goto error; + } + + macCoreHostApi->allocations = PaUtil_CreateAllocationGroup(); + if( !macCoreHostApi->allocations ) + { + result = paInsufficientMemory; + goto error; + } + + *hostApi = &macCoreHostApi->inheritedHostApiRep; + (*hostApi)->info.structVersion = 1; + (*hostApi)->info.type = paCoreAudio; + (*hostApi)->info.name = "CoreAudio"; + + result = InitializeDeviceInfos(macCoreHostApi, hostApiIndex); + if (result != paNoError) { + goto error; + } + + // Set up the proper callbacks to this HostApi's functions + (*hostApi)->Terminate = Terminate; + (*hostApi)->OpenStream = OpenStream; + (*hostApi)->IsFormatSupported = IsFormatSupported; + + PaUtil_InitializeStreamInterface( &macCoreHostApi->callbackStreamInterface, CloseStream, StartStream, + StopStream, AbortStream, IsStreamStopped, IsStreamActive, + GetStreamTime, GetStreamCpuLoad, + PaUtil_DummyRead, PaUtil_DummyWrite, + PaUtil_DummyGetReadAvailable, PaUtil_DummyGetWriteAvailable ); + + PaUtil_InitializeStreamInterface( &macCoreHostApi->blockingStreamInterface, CloseStream, StartStream, + StopStream, AbortStream, IsStreamStopped, IsStreamActive, + GetStreamTime, PaUtil_DummyGetCpuLoad, + ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable ); + + return result; + +error: + if( macCoreHostApi ) { + CleanUp(macCoreHostApi); + } + + return result; +} diff --git a/pa_mac_core/pa_mac_core_utilities.c b/pa_mac_core/pa_mac_core_utilities.c new file mode 100644 index 0000000..5e211fd --- /dev/null +++ b/pa_mac_core/pa_mac_core_utilities.c @@ -0,0 +1,571 @@ +/* + * + * pa_mac_core_utilities.c + * + * utilitiy functions for pa_mac_core.c + * + * This functions are more like helper functions than part of the core, + * so I moved them to a separate file so the core code would be cleaner. + * + * by Bjorn Roche. + */ + +#define UNIX_ERR(err) PaMacCore_SetUnixError( err, __LINE__ ) + +static PaError PaMacCore_SetUnixError( int err, int line ) +{ + PaError ret; + const char *errorText; + + if( err == 0 ) + { + return paNoError; + } + + ret = paNoError; + errorText = strerror( err ); + + /** Map Unix error to PaError. Pretty much the only one that maps + is ENOMEM. */ + if( err == ENOMEM ) + ret = paInsufficientMemory; + else + ret = paInternalError; + + DBUG(("%d on line %d: msg='%s'\n", err, line, errorText)); + PaUtil_SetLastHostErrorInfo( paCoreAudio, err, errorText ); + + return ret; +} + +/* + * Translates MacOS generated errors into PaErrors + */ +static PaError PaMacCore_SetError(OSStatus error, int line, int isError) +{ + /*FIXME: still need to handle possible ComponentResult values.*/ + /* unfortunately, they don't seem to be documented anywhere.*/ + PaError result; + const char *errorType; + const char *errorText; + + switch (error) { + case kAudioHardwareNoError: + return paNoError; + case kAudioHardwareNotRunningError: + errorText = "Audio Hardware Not Running"; + result = paInternalError; break; + case kAudioHardwareUnspecifiedError: + errorText = "Unspecified Audio Hardware Error"; + result = paInternalError; break; + case kAudioHardwareUnknownPropertyError: + errorText = "Audio Hardware: Unknown Property"; + result = paInternalError; break; + case kAudioHardwareBadPropertySizeError: + errorText = "Audio Hardware: Bad Property Size"; + result = paInternalError; break; + case kAudioHardwareIllegalOperationError: + errorText = "Audio Hardware: Illegal Operation"; + result = paInternalError; break; + case kAudioHardwareBadDeviceError: + errorText = "Audio Hardware: Bad Device"; + result = paInvalidDevice; break; + case kAudioHardwareBadStreamError: + errorText = "Audio Hardware: BadStream"; + result = paBadStreamPtr; break; + case kAudioHardwareUnsupportedOperationError: + errorText = "Audio Hardware: Unsupported Operation"; + result = paInternalError; break; + case kAudioDeviceUnsupportedFormatError: + errorText = "Audio Device: Unsupported Format"; + result = paSampleFormatNotSupported; break; + case kAudioDevicePermissionsError: + errorText = "Audio Device: Permissions Error"; + result = paDeviceUnavailable; break; + /* Audio Unit Errors: http://developer.apple.com/documentation/MusicAudio/Reference/CoreAudio/audio_units/chapter_5_section_3.html */ + case kAudioUnitErr_InvalidProperty: + errorText = "Audio Unit: Invalid Property"; + result = paInternalError; break; + case kAudioUnitErr_InvalidParameter: + errorText = "Audio Unit: Invalid Parameter"; + result = paInternalError; break; + case kAudioUnitErr_NoConnection: + errorText = "Audio Unit: No Connection"; + result = paInternalError; break; + case kAudioUnitErr_FailedInitialization: + errorText = "Audio Unit: Initialization Failed"; + result = paInternalError; break; + case kAudioUnitErr_TooManyFramesToProcess: + errorText = "Audio Unit: Too Many Frames"; + result = paInternalError; break; + case kAudioUnitErr_IllegalInstrument: + errorText = "Audio Unit: Illegal Instrument"; + result = paInternalError; break; + case kAudioUnitErr_InstrumentTypeNotFound: + errorText = "Audio Unit: Instrument Type Not Found"; + result = paInternalError; break; + case kAudioUnitErr_InvalidFile: + errorText = "Audio Unit: Invalid File"; + result = paInternalError; break; + case kAudioUnitErr_UnknownFileType: + errorText = "Audio Unit: Unknown File Type"; + result = paInternalError; break; + case kAudioUnitErr_FileNotSpecified: + errorText = "Audio Unit: File Not Specified"; + result = paInternalError; break; + case kAudioUnitErr_FormatNotSupported: + errorText = "Audio Unit: Format Not Supported"; + result = paInternalError; break; + case kAudioUnitErr_Uninitialized: + errorText = "Audio Unit: Unitialized"; + result = paInternalError; break; + case kAudioUnitErr_InvalidScope: + errorText = "Audio Unit: Invalid Scope"; + result = paInternalError; break; + case kAudioUnitErr_PropertyNotWritable: + errorText = "Audio Unit: PropertyNotWritable"; + result = paInternalError; break; + case kAudioUnitErr_InvalidPropertyValue: + errorText = "Audio Unit: Invalid Property Value"; + result = paInternalError; break; + case kAudioUnitErr_PropertyNotInUse: + errorText = "Audio Unit: Property Not In Use"; + result = paInternalError; break; + case kAudioUnitErr_Initialized: + errorText = "Audio Unit: Initialized"; + result = paInternalError; break; + case kAudioUnitErr_InvalidOfflineRender: + errorText = "Audio Unit: Invalid Offline Render"; + result = paInternalError; break; + case kAudioUnitErr_Unauthorized: + errorText = "Audio Unit: Unauthorized"; + result = paInternalError; break; + case kAudioUnitErr_CannotDoInCurrentContext: + errorText = "Audio Unit: cannot do in current context"; + result = paInternalError; break; + default: + errorText = "Unknown Error"; + result = paInternalError; + } + + if (isError) + errorType = "Error"; + else + errorType = "Warning"; + + if ((int)error < -99999 || (int)error > 99999) + DBUG(("%s on line %d: err='%4s', msg='%s'\n", errorType, line, (const char *)&error, errorText)); + else + DBUG(("%s on line %d: err=%d, 0x%x, msg='%s'\n", errorType, line, (int)error, (unsigned)error, errorText)); + + PaUtil_SetLastHostErrorInfo( paCoreAudio, error, errorText ); + + return result; +} + +/* + * This function computes an appropriate ring buffer size given + * a requested latency (in seconds), sample rate and framesPerBuffer. + * + * The returned ringBufferSize is computed using the following + * constraints: + * - it must be at least 4. + * - it must be at least 3x framesPerBuffer. + * - it must be at least 2x the suggestedLatency. + * - it must be a power of 2. + * This function attempts to compute the minimum such size. + * + * FEEDBACK: too liberal/conservative/another way? + */ +static long computeRingBufferSize( const PaStreamParameters *inputParameters, + const PaStreamParameters *outputParameters, + long inputFramesPerBuffer, + long outputFramesPerBuffer, + double sampleRate ) +{ + long ringSize; + int index; + int i; + double latencyTimesChannelCount ; + long framesPerBufferTimesChannelCount ; + + VVDBUG(( "computeRingBufferSize()\n" )); + + assert( inputParameters || outputParameters ); + + if( outputParameters && inputParameters ) + { + latencyTimesChannelCount = MAX( + inputParameters->suggestedLatency * inputParameters->channelCount, + outputParameters->suggestedLatency * outputParameters->channelCount ); + framesPerBufferTimesChannelCount = MAX( + inputFramesPerBuffer * inputParameters->channelCount, + outputFramesPerBuffer * outputParameters->channelCount ); + } + else if( outputParameters ) + { + latencyTimesChannelCount + = outputParameters->suggestedLatency * outputParameters->channelCount; + framesPerBufferTimesChannelCount + = outputFramesPerBuffer * outputParameters->channelCount; + } + else /* we have inputParameters */ + { + latencyTimesChannelCount + = inputParameters->suggestedLatency * inputParameters->channelCount; + framesPerBufferTimesChannelCount + = inputFramesPerBuffer * inputParameters->channelCount; + } + + ringSize = (long) ( latencyTimesChannelCount * sampleRate * 2 + .5); + VDBUG( ( "suggested latency * channelCount: %d\n", (int) (latencyTimesChannelCount*sampleRate) ) ); + if( ringSize < framesPerBufferTimesChannelCount * 3 ) + ringSize = framesPerBufferTimesChannelCount * 3 ; + VDBUG(("framesPerBuffer*channelCount:%d\n",(int)framesPerBufferTimesChannelCount)); + VDBUG(("Ringbuffer size (1): %d\n", (int)ringSize )); + + /* make sure it's at least 4 */ + ringSize = MAX( ringSize, 4 ); + + /* round up to the next power of 2 */ + index = -1; + for( i=0; i> i & 0x01 ) + index = i; + assert( index > 0 ); + if( ringSize <= ( 0x01 << index ) ) + ringSize = 0x01 << index ; + else + ringSize = 0x01 << ( index + 1 ); + + VDBUG(( "Final Ringbuffer size (2): %d\n", (int)ringSize )); + return ringSize; +} + + +/* + * Durring testing of core audio, I found that serious crashes could occur + * if properties such as sample rate were changed multiple times in rapid + * succession. The function below has some fancy logic to make sure that changes + * are acknowledged before another is requested. That seems to help a lot. + */ + +#include +typedef struct { + bool once; /* I didn't end up using this. bdr */ + pthread_mutex_t mutex; +} MutexAndBool ; + +static OSStatus propertyProc( + AudioDeviceID inDevice, + UInt32 inChannel, + Boolean isInput, + AudioDevicePropertyID inPropertyID, + void* inClientData ) +{ + MutexAndBool *mab = (MutexAndBool *) inClientData; + mab->once = TRUE; + pthread_mutex_unlock( &(mab->mutex) ); + return noErr; +} + +/* sets the value of the given property and waits for the change to + be acknowledged, and returns the final value, which is not guaranteed + by this function to be the same as the desired value. Obviously, this + function can only be used for data whose input and output are the + same size and format, and their size and format are known in advance.*/ +PaError AudioDeviceSetPropertyNowAndWaitForChange( + AudioDeviceID inDevice, + UInt32 inChannel, + Boolean isInput, + AudioDevicePropertyID inPropertyID, + UInt32 inPropertyDataSize, + const void *inPropertyData, + void *outPropertyData ) +{ + OSStatus macErr; + int unixErr; + MutexAndBool mab; + UInt32 outPropertyDataSize = inPropertyDataSize; + + /* First, see if it already has that value. If so, return. */ + macErr = AudioDeviceGetProperty( inDevice, inChannel, + isInput, inPropertyID, + &outPropertyDataSize, outPropertyData ); + if( macErr ) + goto failMac2; + if( inPropertyDataSize!=outPropertyDataSize ) + return paInternalError; + if( 0==memcmp( outPropertyData, inPropertyData, outPropertyDataSize ) ) + return paNoError; + + /* setup and lock mutex */ + mab.once = FALSE; + unixErr = pthread_mutex_init( &mab.mutex, NULL ); + if( unixErr ) + goto failUnix2; + unixErr = pthread_mutex_lock( &mab.mutex ); + if( unixErr ) + goto failUnix; + + /* add property listener */ + macErr = AudioDeviceAddPropertyListener( inDevice, inChannel, isInput, + inPropertyID, propertyProc, + &mab ); + if( macErr ) + goto failMac; + /* set property */ + macErr = AudioDeviceSetProperty( inDevice, NULL, inChannel, + isInput, inPropertyID, + inPropertyDataSize, inPropertyData ); + if( macErr ) { + /* we couldn't set the property, so we'll just unlock the mutex + and move on. */ + pthread_mutex_unlock( &mab.mutex ); + } + + /* wait for property to change */ + unixErr = pthread_mutex_lock( &mab.mutex ); + if( unixErr ) + goto failUnix; + + /* now read the property back out */ + macErr = AudioDeviceGetProperty( inDevice, inChannel, + isInput, inPropertyID, + &outPropertyDataSize, outPropertyData ); + if( macErr ) + goto failMac; + /* cleanup */ + AudioDeviceRemovePropertyListener( inDevice, inChannel, isInput, + inPropertyID, propertyProc ); + unixErr = pthread_mutex_unlock( &mab.mutex ); + if( unixErr ) + goto failUnix2; + unixErr = pthread_mutex_destroy( &mab.mutex ); + if( unixErr ) + goto failUnix2; + + return paNoError; + + failUnix: + pthread_mutex_destroy( &mab.mutex ); + AudioDeviceRemovePropertyListener( inDevice, inChannel, isInput, + inPropertyID, propertyProc ); + + failUnix2: + DBUG( ("Error #%d while setting a device property: %s\n", unixErr, strerror( unixErr ) ) ); + return paUnanticipatedHostError; + + failMac: + pthread_mutex_destroy( &mab.mutex ); + AudioDeviceRemovePropertyListener( inDevice, inChannel, isInput, + inPropertyID, propertyProc ); + failMac2: + return ERR( macErr ); +} + +/* + * Sets the sample rate the HAL device. + * if requireExact: set the sample rate or fail. + * + * otherwise : set the exact sample rate. + * If that fails, check for available sample rates, and choose one + * higher than the requested rate. If there isn't a higher one, + * just use the highest available. + */ +static PaError setBestSampleRateForDevice( const AudioDeviceID device, + const bool isOutput, + const bool requireExact, + const Float64 desiredSrate ) +{ + /*FIXME: changing the sample rate is disruptive to other programs using the + device, so it might be good to offer a custom flag to not change the + sample rate and just do conversion. (in my casual tests, there is + no disruption unless the sample rate really does need to change) */ + const bool isInput = isOutput ? 0 : 1; + Float64 srate; + UInt32 propsize = sizeof( Float64 ); + OSErr err; + AudioValueRange *ranges; + int i=0; + Float64 max = -1; /*the maximum rate available*/ + Float64 best = -1; /*the lowest sample rate still greater than desired rate*/ + VDBUG(("Setting sample rate for device %ld to %g.\n",device,(float)desiredSrate)); + + /* -- try setting the sample rate -- */ + err = AudioDeviceSetPropertyNowAndWaitForChange( + device, 0, isInput, + kAudioDevicePropertyNominalSampleRate, + propsize, &desiredSrate, &srate ); + if( err ) + return err; + + /* -- if the rate agrees, and we got no errors, we are done -- */ + if( !err && srate == desiredSrate ) + return paNoError; + /* -- we've failed if the rates disagree and we are setting input -- */ + if( requireExact ) + return paInvalidSampleRate; + + /* -- generate a list of available sample rates -- */ + err = AudioDeviceGetPropertyInfo( device, 0, isInput, + kAudioDevicePropertyAvailableNominalSampleRates, + &propsize, NULL ); + if( err ) + return ERR( err ); + ranges = (AudioValueRange *)calloc( 1, propsize ); + if( !ranges ) + return paInsufficientMemory; + err = AudioDeviceGetProperty( device, 0, isInput, + kAudioDevicePropertyAvailableNominalSampleRates, + &propsize, ranges ); + if( err ) + { + free( ranges ); + return ERR( err ); + } + VDBUG(("Requested sample rate of %g was not available.\n", (float)desiredSrate)); + VDBUG(("%lu Available Sample Rates are:\n",propsize/sizeof(AudioValueRange))); +#ifdef MAC_CORE_VERBOSE_DEBUG + for( i=0; i max ) max = ranges[i].mMaximum; + if( ranges[i].mMinimum > desiredSrate ) { + if( best < 0 ) + best = ranges[i].mMinimum; + else if( ranges[i].mMinimum < best ) + best = ranges[i].mMinimum; + } + } + if( best < 0 ) + best = max; + VDBUG( ("Maximum Rate %g. best is %g.\n", max, best ) ); + free( ranges ); + + /* -- set the sample rate -- */ + propsize = sizeof( best ); + err = AudioDeviceSetPropertyNowAndWaitForChange( + device, 0, isInput, + kAudioDevicePropertyNominalSampleRate, + propsize, &best, &srate ); + if( err ) + return err; + + if( err ) + return ERR( err ); + /* -- if the set rate matches, we are done -- */ + if( srate == best ) + return paNoError; + + /* -- otherwise, something wierd happened: we didn't set the rate, and we got no errors. Just bail. */ + return paInternalError; +} + + +/* + Attempts to set the requestedFramesPerBuffer. If it can't set the exact + value, it settles for something smaller if available. If nothing smaller + is available, it uses the smallest available size. + actualFramesPerBuffer will be set to the actual value on successful return. + OK to pass NULL to actualFramesPerBuffer. + The logic is very simmilar too setBestSampleRate only failure here is + not usually catastrophic. +*/ +static PaError setBestFramesPerBuffer( const AudioDeviceID device, + const bool isOutput, + unsigned long requestedFramesPerBuffer, + unsigned long *actualFramesPerBuffer ) +{ + UInt32 afpb; + const bool isInput = !isOutput; + UInt32 propsize = sizeof(UInt32); + OSErr err; + Float64 min = -1; /*the min blocksize*/ + Float64 best = -1; /*the best blocksize*/ + int i=0; + AudioValueRange *ranges; + + if( actualFramesPerBuffer == NULL ) + actualFramesPerBuffer = &afpb; + + + /* -- try and set exact FPB -- */ + err = AudioDeviceSetProperty( device, NULL, 0, isInput, + kAudioDevicePropertyBufferFrameSize, + propsize, &requestedFramesPerBuffer); + err = AudioDeviceGetProperty( device, 0, isInput, + kAudioDevicePropertyBufferFrameSize, + &propsize, actualFramesPerBuffer); + if( err ) + return ERR( err ); + if( *actualFramesPerBuffer == requestedFramesPerBuffer ) + return paNoError; /* we are done */ + + /* -- fetch available block sizes -- */ + err = AudioDeviceGetPropertyInfo( device, 0, isInput, + kAudioDevicePropertyBufferSizeRange, + &propsize, NULL ); + if( err ) + return ERR( err ); + ranges = (AudioValueRange *)calloc( 1, propsize ); + if( !ranges ) + return paInsufficientMemory; + err = AudioDeviceGetProperty( device, 0, isInput, + kAudioDevicePropertyBufferSizeRange, + &propsize, ranges ); + if( err ) + { + free( ranges ); + return ERR( err ); + } + VDBUG(("Requested block size of %lu was not available.\n", + requestedFramesPerBuffer )); + VDBUG(("%lu Available block sizes are:\n",propsize/sizeof(AudioValueRange))); +#ifdef MAC_CORE_VERBOSE_DEBUG + for( i=0; i best ) + best = ranges[i].mMaximum; + } + } + if( best == -1 ) + best = min; + VDBUG( ("Minimum FPB %g. best is %g.\n", min, best ) ); + free( ranges ); + + /* --- set the buffer size (ignore errors) -- */ + requestedFramesPerBuffer = (UInt32) best ; + propsize = sizeof( UInt32 ); + err = AudioDeviceSetProperty( device, NULL, 0, isInput, + kAudioDevicePropertyBufferSize, + propsize, &requestedFramesPerBuffer ); + /* --- read the property to check that it was set -- */ + err = AudioDeviceGetProperty( device, 0, isInput, + kAudioDevicePropertyBufferSize, + &propsize, actualFramesPerBuffer ); + + if( err ) + return ERR( err ); + + return paNoError; +} diff --git a/pa_mac/pa_mac.c b/pa_mac_sm/pa_mac_sm.c similarity index 100% rename from pa_mac/pa_mac.c rename to pa_mac_sm/pa_mac_sm.c diff --git a/pa_sgi/Makefile b/pa_sgi/Makefile deleted file mode 100644 index 34fcee6..0000000 --- a/pa_sgi/Makefile +++ /dev/null @@ -1,53 +0,0 @@ -# Make PortAudio for Silicon Graphics IRIX 6.2 - 6.5. -# Pieter suurmond, july 4, 2002. (for PA v18.) -# Based on SGI-specific sproc()-method to spawn children, not on POSIX-threads. - -# Instead of "-lpthread", as with linux, -# just the audio- and math-library for SGI: -LIBS = -laudio -lm - -CDEFINES = -I../pa_common - -# Possible CFLAGS with MIPSpro compiler are: -32, -o32, -n32, -64, -# -mips1, -mips2, -mips3, -mips4, etc. Use -g, -g2, -g3 for debugging. -# And use for example -O2 or -O3 for better optimization: -CFLAGS = -O2 -PASRC = ../pa_common/pa_lib.c pa_sgi.c -PAINC = ../pa_common/portaudio.h - -# Tests that work (on SGI Indy with R5000 @ 180MHz running IRIX 6.2): -#TESTC = $(PASRC) ../pa_tests/patest_record.c # TODO probably ok. -#TESTC = $(PASRC) ../pa_tests/patest_many.c # v18 ok (with PA_MIN_LATENCY_MSEC=250). -#TESTC = $(PASRC) ../pa_tests/patest_latency.c # v18 ok (with PA_MIN_LATENCY_MSEC=250) patest_latency.c contained // -#TESTC = $(PASRC) ../pa_tests/patest_longsine.c # v18 ok (with PA_MIN_LATENCY_MSEC=250). - -TESTC = $(PASRC) ../pa_tests/patest_saw.c # v18 ok (with PA_MIN_LATENCY_MSEC=250). -#TESTC = $(PASRC) ../pa_tests/patest_wire.c # v18 seems ok. - -#TESTC = $(PASRC) ../pa_tests/pa_devs.c # TODO probably ok. -#TESTC = $(PASRC) ../pa_tests/patest_sine.c # TODO probably ok. -#TESTC = $(PASRC) ../pa_tests/patest_sine_time.c # TODO probably ok. -#TESTC = $(PASRC) ../pa_tests/patest_sine8.c # TODO probably ok. -#TESTC = $(PASRC) ../pa_tests/patest_leftright.c # TODO probably ok. -#TESTC = $(PASRC) ../pa_tests/patest_pink.c # TODO probably ok. -#TESTC = $(PASRC) ../pa_tests/patest_clip.c # TODO probably ok. -#TESTC = $(PASRC) ../pa_tests/patest_stop.c # TODO probably ok. -#TESTC = $(PASRC) ../pa_tests/patest_dither.c # TODO probably ok. -#TESTC = $(PASRC) ../pa_tests/patest_sync.c # BEEPS and delta's, no crashes anymore with v15. - -# Tests that were not yet performed: -#TESTC = $(PASRC) ../pa_tests/paqa_devs.c # test?? -#TESTC = $(PASRC) ../pa_tests/paqa_errs.c # test?? -#TESTC = $(PASRC) ../pa_tests/pa_fuzz.c # test?? - -TESTH = $(PAINC) - -all: patest - -# "cc" for the MIPSpro compiler, may be changed to "gcc": -patest: $(TESTC) $(TESTH) Makefile - cc $(CFLAGS) $(TESTC) $(CDEFINES) $(LIBS) -o patest - -run: patest - ./patest - diff --git a/pa_sgi/pa_sgi.c b/pa_sgi/pa_sgi.c index 0f56237..8b742d1 100644 --- a/pa_sgi/pa_sgi.c +++ b/pa_sgi/pa_sgi.c @@ -1,10 +1,11 @@ /* * $Id$ - * PortAudio Portable Real-Time Audio Library. Copyright (c) 1999-2001 Phil Burk. - * Latest Version at: http://www.portaudio.com - * + * PortAudio Portable Real-Time Audio Library. + * Latest Version at: http://www.portaudio.com. * Silicon Graphics (SGI) IRIX implementation by Pieter Suurmond. - * This implementation uses sproc()-spawning, not the POSIX-threads. + * + * 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 @@ -29,1030 +30,1388 @@ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * -MODIFICATIONS: - 8/12/2001 - Pieter Suurmond - took the v15 pa_linux_oss.c file and started to adapt for IRIX 6.2. - 8/17/2001 - v15, first unstable alpha release for IRIX, sent to Phil & Ross. - 9/23/2001 - Many fixes and changes: POLLIN for input, not POLLOUT! - 7/04/2002 - Implemented multiple user buffers per host buffer to allow clients that - request smaller buffersizes. - - [v18-0.05] Try to use CVS via the Mac now to upload instead of e-mailing to Phil & Ross. - -TODO: - - Dynamically switch to 32 bit float as native format when appropriate (let SGI do the conversion), - and maybe also the other natively supported formats? (might increase performance) - - Implement fancy callback block adapter as described in the PDF by Stephane Letz in the ASIO dir. - - Do some more tests... (see Makefile). - -REFERENCES: - - IRIX 6.2 man pages regarding SGI AL library. - - IRIS Digital Media Programming Guide (online books and man-pages come - with IRIX 6.2 and may not be publically available on the internet). + */ +/** @file + @brief SGI IRIX AL implementation (according to V19 API version 2.0). + + @note This file started as a copy of pa_skeleton.c (v 1.1.2.35 2003/09/20), it + has nothing to do with the old V18 pa_sgi version: this implementation uses the + newer IRIX AL calls and uses pthreads instead of sproc. + + On IRIX, one may type './configure' followed by 'gmake' from the portaudio root + directory to build the static and shared libraries, as well as all the tests. + + On IRIX 6.5, using 'make' instead of 'gmake' may cause Makefile to fail. (This + happens on my machine: make does not understand syntax with 2 colons on a line, + like this: + $(TESTS): bin/%: [snip] + + Maybe this is due to an old make version(?), my only solution is: use gmake. + Anyway, all the tests compile well now, with GCC 3.3, as well as with MIPSpro 7.2.1. + Tested: + - paqa_devs ok, but at a certain point digital i/o fails: + TestAdvance: INPUT, device = 2, rate = 32000, numChannels = 1, format = 1 + Possibly, this is an illegal sr or number of channels for digital i/o. + - paqa_errs 13 of the tests run ok, but 5 of them give weird results. + + patest1 ok. + + patest_buffer ok. + + patest_callbackstop ok. + - patest_clip ok, but hear no difference between dithering turned OFF and ON. + + patest_hang ok. + + patest_latency ok. + + patest_leftright ok. + + patest_maxsines ok. + + patest_many ok. + + patest_multi_sine ok. + + patest_pink ok. + + patest_prime ok. + - patest_read_record ok, but playback stops a little earlier than 5 seconds it seems(?). + + patest_record ok. + + patest_ringmix ok. + + patest_saw ok. + + patest_sine ok. + + patest_sine8 ok. + - patest_sine_formats ok, FLOAT32 + INT16 + INT18 are OK, but UINT8 IS NOT OK! + + patest_sine_time ok. + + patest_start_stop ok, but under/overflow errors of course in the AL queue monitor. + + patest_stop ok. + - patest_sync ok? + + patest_toomanysines ok. + - patest_underflow ok? (stopping after SleepTime = 91: err=Stream is stopped) + - patest_wire ok. + + patest_write_sine ok. + + pa_devs ok. + Ok on an Indy, in both stereo and quadrophonic mode. + + pa_fuzz ok. + + pa_minlat ok. + + Worked on (or checked) proposals: + + 003: Improve Latency Specification OK, but not 100% sure: plus or minus 1 host buffer? + 004 OK: Allow Callbacks to Accept Variable Number of Frames per Buffer. + Simply using a fixed host buffer size. Very roughly implemented now, the adaption + to limited-requested latencies and samplerate may be improved. At least this + implementation chooses its own internal host buffer size (no coredumps any longer). + 005 OK: Blocking Read/Write Interface. + 006: Non-interleaved buffers seems OK? Covered by the buffer-processor and such?.... + 009 OK: Host error reporting should now be. + 010 OK: State Machine and State Querying Functions. + 011 OK: Renaming done. + 014 Implementation Style Guidelines (sorry, my braces are not ANSI style). + 015 OK: Callback Timestamps (During priming, though, these are still null!). + 016 OK: Use Structs for Pa_OpenStream() Parameters. + 019: Notify Client When All Buffers Have Played (Ok, covered by the buffer processor?) + 020 OK: Allow Callback to prime output stream (StartStream() should do the priming) + Should be tested more thoroughly for full duplex streams. (patest_prime seems ok). + + + @todo Underrun or overflow flags at some more places. + + @todo Callback Timestamps during priming. + + @todo Improve adaption to number of channels, samplerate and such when inventing + some frames per host buffer (when client requests 0). + + @todo Make a complete new version to support 'sproc'-applications. + Or could we manage that with some clever if-defs? + It must be clear which version we use (especially when using pa as lib!): + an irix-sproc() version or pthread version. + + @todo In Makefile.in: 'make clean' does not remove lib/libportaudio.so.0.0.19. + + Note: Even when mono-output is requested, with ALv7, the audio library opens + a outputs stereo. One can observe this in SGI's 'Audio Queue Monitor'. */ -#include /* Standard libraries. */ -#include - -#include "../pa_common/portaudio.h" /* (Makefile fails to find in subdirs, -I doesn't work?). */ -#include "../pa_common/pa_host.h" -#include "../pa_common/pa_trace.h" - -#include -#include -#include -#include /* For schedctl(NDPRI, NDPHIMIN). */ -#include /* fcntl.h needed. */ -#include /* For streams, ioctl(), etc. */ -#include -#include -#include /* System specific (IRIX 6.2-6.5). */ - -/*----------------- MACROS --------------------*/ -#define PRINT(x) { printf x; fflush(stdout); } -#define ERR_RPT(x) PRINT(x) -#define DBUG(x) /* PRINT(x) */ -#define DBUGX(x) /* PRINT(x) */ - -#define MAX_CHARS_DEVNAME (16) -#define MAX_SAMPLE_RATES (8) /* Known from SGI AL there are 7. */ - /* Constants used in 'Pa_GetMinNumBuffers()' below: */ -#define MIN_LATENCY_MSEC (200) /* Used if 'getenv("PA_MIN_LATENCY_MSEC")' fails. */ -#define PA_LATENCY_ENV_NAME ("PA_MIN_LATENCY_MSEC") /* Same names as in file pa_unix.h. */ - -/*------------------------------- IRIX AL specific device info: --------------------------------------*/ -typedef struct internalPortAudioDevice -{ - PaDeviceID pad_DeviceID; /* THIS "ID" IS NEW HERE. */ - long pad_ALdevice; /* SGI-number! */ - double pad_SampleRates[MAX_SAMPLE_RATES]; /* For pointing to from pad_Info */ - char pad_DeviceName[MAX_CHARS_DEVNAME+1]; /* +1 for \0, one more than OSS. */ - PaDeviceInfo pad_Info; /* pad_Info (v15) contains: */ - struct internalPortAudioDevice* pad_Next; /* Singly linked list (NULL=end). */ -} internalPortAudioDevice; - -/*----------------- Structure containing all SGI IRIX specific data: ---------------------------------------*/ -typedef struct PaHostSoundControl -{ - ALconfig pahsc_ALconfigIN, /* IRIX-audio-library-datatype. Configuration */ - pahsc_ALconfigOUT; /* stucts separate for input and output ports. */ - ALport pahsc_ALportIN, /* IRIX-audio-library-datatype. ALports can only be */ - pahsc_ALportOUT; /* unidirectional, so we sometimes need 2 of them. */ - int pahsc_threadPID; /* Sproc()-result, written by PaHost_StartEngine(). */ - - unsigned int pahsc_UserBuffersPerHostBuffer, - pahsc_SamplesPerInputHostBuffer, /* Channels per frame are accounted for. */ - pahsc_SamplesPerOutputHostBuffer, - pahsc_BytesPerInputHostBuffer, /* Size per sample are accounted for. */ - pahsc_BytesPerOutputHostBuffer; - short *pahsc_InputHostBuffer, /* Allocated here, in this file, if necessary. */ - *pahsc_OutputHostBuffer; - - struct itimerval pahsc_EntryTime, /* For measuring CPU utilization (same as linux). */ - pahsc_LastExitTime; - long pahsc_InsideCountSum, - pahsc_TotalCountSum; -} PaHostSoundControl; - -/*-------------------------------------------------------- Shared Data -------------------------------*/ -static internalPortAudioDevice* sDeviceList = NULL; /* FIXME - put Mutex around this shared data. */ -static int sPaHostError = 0; /* Maybe more than one process writing errs!? */ -usema_t *SendSema, /* These variables are shared between the */ - *RcvSema; /* audio handling process and main process. */ -/*--------------------------*/ -long Pa_GetHostError(void) -{ - return (long)sPaHostError; -} +#include /* For strlen() but also for strerror()! */ +#include /* printf() */ +#include /* fabs() */ + +#include /* IRIX AL (audio library). Link with -laudio. */ +#include /* IRIX DL (digital media library), solely for */ + /* function dmGetUST(). Link with -ldmedia. */ +#include /* To catch 'oserror' after AL-calls. */ +#include /* POSIX threads. */ +#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" + + /* Uncomment for diagnostics: */ +#define DBUG(x) /*{ printf x; fflush(stdout); }*/ + -/*----------------------------- BEGIN CPU UTILIZATION MEASUREMENT -----------------*/ -/* (copied from source pa_linux_oss/pa_linux_oss.c) */ -static void Pa_StartUsageCalculation( internalPortAudioStream *past ) +/* prototypes for functions declared in this file */ + +#ifdef __cplusplus +extern "C" { - struct itimerval itimer; - PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; - if( pahsc == NULL ) return; -/* Query system timer for usage analysis and to prevent overuse of CPU. */ - getitimer( ITIMER_REAL, &pahsc->pahsc_EntryTime ); +#endif /* __cplusplus */ + +PaError PaSGI_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index ); + +#ifdef __cplusplus } +#endif /* __cplusplus */ + -static long SubtractTime_AminusB( struct itimerval *timeA, struct itimerval *timeB ) +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 *ipp, + const PaStreamParameters *opp, + 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 ); + + +/* + Apparently, we must use macros for reporting unanticipated host errors. + Only in case we return paUnanticipatedHostError from an Portaudio call, + we have to call one of the following three macro's. + (Constant paAL is defined in pa_common/portaudio.h. See also proposal 009.) + + After an AL error, use this to translate the AL error code to human text: +*/ +#define PA_SGI_SET_LAST_AL_ERROR() \ + {\ + int ee = oserror();\ + PaUtil_SetLastHostErrorInfo(paAL, ee, alGetErrorString(ee));\ + } +/* + But after a generic IRIX error, let strerror() translate the error code from + the operating system and use this (strerror() gives the same as perror()): +*/ +#define PA_SGI_SET_LAST_IRIX_ERROR() \ + {\ + int ee = oserror();\ + PaUtil_SetLastHostErrorInfo(paAL, ee, strerror(ee));\ + } + +/* GOT RID OF calling PaUtil_SetLastHostErrorInfo() with 0 as error number. +- Weird samplerate difference became: paInvalidSampleRate. +- Failing to set AL queue size became: paInternalError + (Because I cannot decide between paBufferTooBig and paBufferTooSmall + because it may even the 'default AL queue size that failed... Or + should we introduce another error-code like 'paInvalidQueueSize'?... NO) +*/ + +/* PaSGIHostApiRepresentation - host api datastructure specific to this implementation */ + +typedef struct { - long secs = timeA->it_value.tv_sec - timeB->it_value.tv_sec; - long usecs = secs * 1000000; - usecs += (timeA->it_value.tv_usec - timeB->it_value.tv_usec); - return usecs; + PaUtilHostApiRepresentation inheritedHostApiRep; + PaUtilStreamInterface callbackStreamInterface; + PaUtilStreamInterface blockingStreamInterface; + PaUtilAllocationGroup* allocations; + /* implementation specific data goes here. */ + ALvalue* sgiDeviceIDs; /* Array of AL resource device numbers. */ + /* PaHostApiIndex hostApiIndex; Hu? As in the linux and oss files? */ } +PaSGIHostApiRepresentation; -static void Pa_EndUsageCalculation( internalPortAudioStream *past ) +/* + Initialises sgiDeviceIDs array. +*/ +PaError PaSGI_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex ) { - struct itimerval currentTime; - long insideCount; - long totalCount; /* Measure CPU utilization during this callback. */ - -#define LOWPASS_COEFFICIENT_0 (0.95) -#define LOWPASS_COEFFICIENT_1 (0.99999 - LOWPASS_COEFFICIENT_0) + PaError result = paNoError; + int e, i, deviceCount, def_in, def_out; + PaSGIHostApiRepresentation* SGIHostApi; + PaDeviceInfo* deviceInfoArray; + static const short numParams = 4; /* Array with name, samplerate, channels */ + ALpv y[numParams]; /* and type. */ + static const short maxDevNameChars = 32; /* Including the terminating null char. */ + char devName[maxDevNameChars]; /* Too lazy for dynamic alloc. */ - PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; - if (pahsc == NULL) - return; - if (getitimer( ITIMER_REAL, ¤tTime ) == 0 ) + /* DBUG(("PaSGI_Initialize() started.\n")); */ + SGIHostApi = (PaSGIHostApiRepresentation*)PaUtil_AllocateMemory(sizeof(PaSGIHostApiRepresentation)); + if( !SGIHostApi ) + { result = paInsufficientMemory; goto cleanup; } + SGIHostApi->allocations = PaUtil_CreateAllocationGroup(); + if( !SGIHostApi->allocations ) + { result = paInsufficientMemory; goto cleanup; } + *hostApi = &SGIHostApi->inheritedHostApiRep; + (*hostApi)->info.structVersion = 1; + (*hostApi)->info.type = paAL; /* IRIX AL type id, was paInDevelopment. */ + (*hostApi)->info.name = "SGI IRIX AL"; + (*hostApi)->info.defaultInputDevice = paNoDevice; /* Set later. */ + (*hostApi)->info.defaultOutputDevice = paNoDevice; /* Set later. */ + (*hostApi)->info.deviceCount = 0; /* We 'll increment in the loop below. */ + + /* Determine the total number of input and output devices (thanks to Gary Scavone). */ + deviceCount = alQueryValues(AL_SYSTEM, AL_DEVICES, 0, 0, 0, 0); + if (deviceCount < 0) /* Returns -1 in case of failure. */ + { + DBUG(("Failed to count devices: alQueryValues()=%d; %s.\n", + deviceCount, alGetErrorString(oserror()))); + result = paDeviceUnavailable; /* Is this an appropriate error return code? */ + goto cleanup; + } + if (deviceCount > 0) { - if (past->past_IfLastExitValid) + (*hostApi)->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory( + SGIHostApi->allocations, sizeof(PaDeviceInfo*) * deviceCount); + if (!(*hostApi)->deviceInfos) + { result = paInsufficientMemory; goto cleanup; } + + /* Allocate all device info structs in a contiguous block. */ + deviceInfoArray = (PaDeviceInfo*)PaUtil_GroupAllocateMemory( + SGIHostApi->allocations, sizeof(PaDeviceInfo) * deviceCount); + if (!deviceInfoArray) + { result = paInsufficientMemory; goto cleanup; } + /* Store all AL device IDs in an array. */ + SGIHostApi->sgiDeviceIDs = (ALvalue*)PaUtil_GroupAllocateMemory(SGIHostApi->allocations, + deviceCount * sizeof(ALvalue)); + if (!SGIHostApi->sgiDeviceIDs) + { result = paInsufficientMemory; goto cleanup; } + /* Same query again, but now store all IDs in array sgiDeviceIDs (still using no qualifiers).*/ + e = alQueryValues(AL_SYSTEM, AL_DEVICES, SGIHostApi->sgiDeviceIDs, deviceCount, 0, 0); + if (e != deviceCount) { - insideCount = SubtractTime_AminusB( &pahsc->pahsc_EntryTime, ¤tTime ); - pahsc->pahsc_InsideCountSum += insideCount; - totalCount = SubtractTime_AminusB( &pahsc->pahsc_LastExitTime, ¤tTime ); - pahsc->pahsc_TotalCountSum += totalCount; - /* DBUG(("insideCount = %d, totalCount = %d\n", insideCount, totalCount )); */ - /* Low pass filter the result because sometimes we get called several times in a row. */ - /* That can cause the TotalCount to be very low which can cause the usage to appear */ - /* unnaturally high. So we must filter numerator and denominator separately!!! */ - if (pahsc->pahsc_InsideCountSum > 0) + if (e < 0) /* Sure an AL error really occurred. */ + { PA_SGI_SET_LAST_AL_ERROR() result = paUnanticipatedHostError; } + else /* Seems we lost some devices. */ + { DBUG(("Number of devices suddenly changed!\n")); result = paDeviceUnavailable; } + goto cleanup; + } + y[0].param = AL_DEFAULT_INPUT; + y[1].param = AL_DEFAULT_OUTPUT; + e = alGetParams(AL_SYSTEM, y, 2); /* Get params global to the AL system. */ + if (e != 2) + { + if (e < 0) + { + PA_SGI_SET_LAST_AL_ERROR() /* Calls oserror() and alGetErrorString(). */ + result = paUnanticipatedHostError; /* Sure an AL error really occurred. */ + } + else { - past->past_AverageInsideCount = ((LOWPASS_COEFFICIENT_0 * past->past_AverageInsideCount) + - (LOWPASS_COEFFICIENT_1 * pahsc->pahsc_InsideCountSum)); - past->past_AverageTotalCount = ((LOWPASS_COEFFICIENT_0 * past->past_AverageTotalCount) + - (LOWPASS_COEFFICIENT_1 * pahsc->pahsc_TotalCountSum)); - past->past_Usage = past->past_AverageInsideCount / past->past_AverageTotalCount; - pahsc->pahsc_InsideCountSum = 0; - pahsc->pahsc_TotalCountSum = 0; + DBUG(("Default input and/or output could not be found!\n")); + result = paDeviceUnavailable; /* FIX: What if only in or out are available? */ } + goto cleanup; } - past->past_IfLastExitValid = 1; - } - pahsc->pahsc_LastExitTime.it_value.tv_sec = 100; - pahsc->pahsc_LastExitTime.it_value.tv_usec = 0; - setitimer( ITIMER_REAL, &pahsc->pahsc_LastExitTime, NULL ); - past->past_IfLastExitValid = 1; -} /*----------- END OF CPU UTILIZATION CODE (from pa_linux_oss/pa_linux_oss.c v15)--------------------*/ - - -/*--------------------------------------------------------------------------------------*/ -PaError translateSGIerror(void) /* Calls oserror(), may be used after an SGI AL-library */ -{ /* call to report via ERR_RPT(), yields a PaError-num. */ - const char* a = "SGI AL "; /* (Not absolutely sure errno came from THIS thread! */ - switch(oserror()) /* Read IRIX man-pages about the _SGI_MP_SOURCE macro.) */ - { - case AL_BAD_OUT_OF_MEM: - ERR_RPT(("%sout of memory.\n", a)); - return paInsufficientMemory; /* Known PaError. */ - case AL_BAD_CONFIG: - ERR_RPT(("%sconfiguration invalid or NULL.\n", a)); - return paHostError; /* Generic PaError. */ - case AL_BAD_CHANNELS: - ERR_RPT(("%schannels not 1,2 or 4.\n", a)); - return paHostError; /* Generic PaError. */ - case AL_BAD_NO_PORTS: - ERR_RPT(("%sout of audio ports.\n", a)); - return paHostError; /* Generic PaError. */ - case AL_BAD_DEVICE: - ERR_RPT(("%swrong device number.\n", a)); - return paHostError; /* Generic PaError. */ - case AL_BAD_DEVICE_ACCESS: - ERR_RPT(("%swrong device access.\n", a)); - return paHostError; /* Generic PaError. */ - case AL_BAD_DIRECTION: - ERR_RPT(("%sinvalid direction.\n", a)); - return paHostError; /* Generic PaError. */ - case AL_BAD_SAMPFMT: - ERR_RPT(("%sdoesn't accept sampleformat.\n", a)); - return paHostError; /* Generic PaError. */ - case AL_BAD_FLOATMAX: - ERR_RPT(("%smax float value is zero.\n", a)); - return paHostError; /* Generic PaError. */ - case AL_BAD_WIDTH: - ERR_RPT(("%sunsupported samplewidth.\n", a)); - return paHostError; /* Generic PaError. */ - case AL_BAD_QSIZE: - ERR_RPT(("%sinvalid queue size.\n", a)); - return paHostError; /* Generic PaError. */ - case AL_BAD_PVBUFFER: - ERR_RPT(("%sPVbuffer null.\n", a)); - return paHostError; /* Generic PaError. */ - case AL_BAD_BUFFERLENGTH_NEG: - ERR_RPT(("%snegative bufferlength.\n", a)); - return paHostError; /* Generic PaError. */ - case AL_BAD_BUFFERLENGTH_ODD: - ERR_RPT(("%sodd bufferlength.\n", a)); - return paHostError; /* Generic PaError. */ - case AL_BAD_PARAM: - ERR_RPT(("%sparameter not valid for device.\n", a)); - return paHostError; /* Generic PaError. */ - default: - ERR_RPT(("%sunknown error.\n", a)); - return paHostError; /* Generic PaError. */ - } -} + def_in = y[0].value.i; /* Remember both AL devices for a while. */ + def_out = y[1].value.i; + y[0].param = AL_NAME; + y[0].value.ptr = devName; + y[0].sizeIn = maxDevNameChars; /* Including terminating null char. */ + y[1].param = AL_RATE; + y[2].param = AL_CHANNELS; + y[3].param = AL_TYPE; /* Subtype of AL_INPUT_DEVICE_TYPE or AL_OUTPUT_DEVICE_TYPE? */ + for (i=0; i < deviceCount; ++i) /* Fill allocated deviceInfo structs. */ + { + PaDeviceInfo *deviceInfo = &deviceInfoArray[i]; + deviceInfo->structVersion = 2; + deviceInfo->hostApi = hostApiIndex; /* Retrieve name, samplerate, channels and type. */ + e = alGetParams(SGIHostApi->sgiDeviceIDs[i].i, y, numParams); + if (e != numParams) + { + if (e < 0) /* Calls oserror() and alGetErrorString(). */ + { PA_SGI_SET_LAST_AL_ERROR() result = paUnanticipatedHostError; } + else + { DBUG(("alGetParams() could not get all params!\n")); result = paInternalError; } + goto cleanup; + } + deviceInfo->name = (char*)PaUtil_GroupAllocateMemory(SGIHostApi->allocations, strlen(devName) + 1); + if (!deviceInfo->name) + { result = paInsufficientMemory; goto cleanup; } + strcpy((char*)deviceInfo->name, devName); -/*------------------------------------------------------------------------------------------*/ -/* Tries to set various rates and formats and fill in the device info structure. */ -static PaError Pa_sgiQueryDevice(long ALdev, /* (AL_DEFAULT_DEVICE) */ - PaDeviceID id, /* (DefaultI|ODeviceID()) */ - char* name, /* (for example "SGI AL") */ - internalPortAudioDevice* pad) /* Result written to pad. */ -{ - int format; - long min, max; /* To catch hardware characteristics. */ - ALseterrorhandler(0); /* 0 = turn off the default error handler. */ - /*--------------------------------------------------------------------------------------*/ - pad->pad_ALdevice = ALdev; /* Set the AL device number. */ - pad->pad_DeviceID = id; /* Set the PA device number. */ - if (strlen(name) > MAX_CHARS_DEVNAME) /* MAX_CHARS defined above. */ - { - ERR_RPT(("Pa_QueryDevice(): name too long (%s).\n", name)); - return paHostError; + /* Determine whether the received number of channels belongs to input or output device. */ + if (alIsSubtype(AL_INPUT_DEVICE_TYPE, y[3].value.i)) + { + deviceInfo->maxInputChannels = y[2].value.i; + deviceInfo->maxOutputChannels = 0; + } + else if (alIsSubtype(AL_OUTPUT_DEVICE_TYPE, y[3].value.i)) + { + deviceInfo->maxInputChannels = 0; + deviceInfo->maxOutputChannels = y[2].value.i; + } + else /* Should never occur. */ + { + DBUG(("AL device is neither input nor output!\n")); + result = paInternalError; + goto cleanup; + } + + /* Determine if this device is the default (in or out). If so, assign. */ + if (def_in == SGIHostApi->sgiDeviceIDs[i].i) + { + if ((*hostApi)->info.defaultInputDevice != paNoDevice) + { + DBUG(("Default input already assigned!\n")); + result = paInternalError; + goto cleanup; + } + (*hostApi)->info.defaultInputDevice = i; + /* DBUG(("Default input assigned to pa device %d (%s).\n", i, deviceInfo->name)); */ + } + else if (def_out == SGIHostApi->sgiDeviceIDs[i].i) + { + if ((*hostApi)->info.defaultOutputDevice != paNoDevice) + { + DBUG(("Default output already assigned!\n")); + result = paInternalError; + goto cleanup; + } + (*hostApi)->info.defaultOutputDevice = i; + /* DBUG(("Default output assigned to pa device %d (%s).\n", i, deviceInfo->name)); */ + } + /*---------------------------------------------- Default latencies set to 'reasonable' values. */ + deviceInfo->defaultLowInputLatency = 0.050; /* 50 milliseconds seems ok. */ + deviceInfo->defaultLowOutputLatency = 0.050; /* These are ALSO ABSOLUTE MINIMA in OpenStream(). */ + deviceInfo->defaultHighInputLatency = 0.500; /* 500 milliseconds a reasonable value? */ + deviceInfo->defaultHighOutputLatency = 0.500; /* Ten times these are ABSOLUTE MAX in OpenStream()). */ + + deviceInfo->defaultSampleRate = alFixedToDouble(y[1].value.ll); /* Read current sr. */ + (*hostApi)->deviceInfos[i] = deviceInfo; + ++(*hostApi)->info.deviceCount; + } } - strcpy(pad->pad_DeviceName, name); /* Write name-string. */ - pad->pad_Info.name = pad->pad_DeviceName; /* Set pointer,..hmmm. */ - /*--------------------------------- natively supported sample formats: -----------------*/ - pad->pad_Info.nativeSampleFormats = paInt16; /* Later also include paFloat32 | ..| etc. */ - /* Then also choose other CallConvertXX()! */ - /*--------------------------------- number of available i/o channels: ------------------*/ - if (ALgetminmax(ALdev, AL_INPUT_COUNT, &min, &max)) - return translateSGIerror(); - pad->pad_Info.maxInputChannels = max; - DBUG(("Pa_QueryDevice: maxInputChannels = %d\n", pad->pad_Info.maxInputChannels)) - if (ALgetminmax(ALdev, AL_OUTPUT_COUNT, &min, &max)) - return translateSGIerror(); - pad->pad_Info.maxOutputChannels = max; - DBUG(("Pa_QueryDevice: maxOutputChannels = %d\n", pad->pad_Info.maxOutputChannels)) - /*--------------------------------- supported samplerates: ----------------------*/ - pad->pad_Info.numSampleRates = 7; - pad->pad_Info.sampleRates = pad->pad_SampleRates; - pad->pad_SampleRates[0] = (double)AL_RATE_8000; /* long -> double. */ - pad->pad_SampleRates[1] = (double)AL_RATE_11025; - pad->pad_SampleRates[2] = (double)AL_RATE_16000; - pad->pad_SampleRates[3] = (double)AL_RATE_22050; - pad->pad_SampleRates[4] = (double)AL_RATE_32000; - pad->pad_SampleRates[5] = (double)AL_RATE_44100; - pad->pad_SampleRates[6] = (double)AL_RATE_48000; - if (ALgetminmax(ALdev, AL_INPUT_RATE, &min, &max)) /* Ask INPUT rate-max. */ - return translateSGIerror(); /* double -> long. */ - if (max != (long)(0.5 + pad->pad_SampleRates[6])) /* FP-compare not recommndd. */ - goto weird; - if (ALgetminmax(ALdev, AL_OUTPUT_RATE, &min, &max)) /* Ask OUTPUT rate-max. */ - return translateSGIerror(); - if (max != (long)(0.5 + pad->pad_SampleRates[6])) + /* What if (deviceCount==0)? */ + (*hostApi)->Terminate = Terminate; + (*hostApi)->OpenStream = OpenStream; + (*hostApi)->IsFormatSupported = IsFormatSupported; + + PaUtil_InitializeStreamInterface(&SGIHostApi->callbackStreamInterface, CloseStream, StartStream, + StopStream, AbortStream, IsStreamStopped, IsStreamActive, + GetStreamTime, GetStreamCpuLoad, + PaUtil_DummyRead, PaUtil_DummyWrite, + PaUtil_DummyGetReadAvailable, PaUtil_DummyGetWriteAvailable ); + + PaUtil_InitializeStreamInterface(&SGIHostApi->blockingStreamInterface, CloseStream, StartStream, + StopStream, AbortStream, IsStreamStopped, IsStreamActive, + GetStreamTime, PaUtil_DummyGetCpuLoad, + ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable ); +cleanup: + if (result != paNoError) { -weird: ERR_RPT(("Pa_sgiQueryDevice() did not confirm max samplerate (%ld)\n",max)); - return paHostError; /* Or make it a warning and just carry on... */ + if (SGIHostApi) + { + if (SGIHostApi->allocations) + { + PaUtil_FreeAllAllocations(SGIHostApi->allocations); + PaUtil_DestroyAllocationGroup(SGIHostApi->allocations); + } + PaUtil_FreeMemory(SGIHostApi); + } } - /*-------------------------------------------------------------------------------*/ - return paNoError; + return result; } -/*--------------------------------------------------------------------------------*/ -int Pa_CountDevices() /* Name of this function suggests it only counts and */ -{ /* is NOT destructive, it however resets whole PA ! */ - int numDevices = 0; /* Let 's not do that here. */ - internalPortAudioDevice* currentDevice = sDeviceList; /* COPY GLOBAL VAR. */ -#if 0 /* Remains from linux_oss v15: Pa_Initialize(), on */ - if (!currentDevice) /* its turn, calls PaHost_Init() via file pa_lib.c. */ - Pa_Initialize(); /* Isn't that a bit too 'rude'? Don't be too */ -#endif /* friendly to clients that forgot to initialize PA. */ - while (currentDevice) /* Slower but more elegant than the sNumDevices-way: */ - { - numDevices++; - currentDevice = currentDevice->pad_Next; - } - return numDevices; +static void Terminate( struct PaUtilHostApiRepresentation *hostApi ) +{ + PaSGIHostApiRepresentation *SGIHostApi = (PaSGIHostApiRepresentation*)hostApi; + + /* Clean up any resources not handled by the allocation group. */ + if( SGIHostApi->allocations ) + { + PaUtil_FreeAllAllocations( SGIHostApi->allocations ); + PaUtil_DestroyAllocationGroup( SGIHostApi->allocations ); + } + PaUtil_FreeMemory( SGIHostApi ); } -/*-------------------------------------------------------------------------------*/ -static internalPortAudioDevice *Pa_GetInternalDevice(PaDeviceID id) +/* + Check if samplerate is supported for this output device. Called once + or twice by function IsFormatSupported() and one time by OpenStream(). + When paUnanticipatedHostError is returned, the caller does NOT have + to call PA_SGI_SET_LAST_AL_ERROR() or such. +*/ +static PaError sr_supported(int al_device, double sr) { - int numDevices = 0; - internalPortAudioDevice *res = (internalPortAudioDevice*)NULL; - internalPortAudioDevice *pad = sDeviceList; /* COPY GLOBAL VAR. */ - while (pad) /* pad may be NULL, that's ok, return 0. */ - { /* (Added ->pad_DeviceID field to the pad-struct, Pieter, 2001.) */ - if (pad->pad_DeviceID == id) /* This the device we were looking for? */ - res = pad; /* But keep on(!) counting so we don't */ - numDevices++; /* have to call Pa_CountDevices() later. */ - pad = pad->pad_Next; /* Advance to the next device or NULL. */ - } /* No assumptions about order of ID's in */ - if (!res) /* the list. */ - ERR_RPT(("Pa_GetInternalDevice() could not find specified ID (%d).\n",id)); - if ((id < 0) || (id >= numDevices)) + int e; + PaError result; + ALparamInfo pinfo; + long long lsr; /* 64 bit fixed point internal AL samplerate. */ + + if (alGetParamInfo(al_device, AL_RATE, &pinfo)) { - ERR_RPT(("Pa_GetInternalDevice() supplied with an illegal ID (%d).\n",id)); -#if 1 /* Be strict, even when found, */ - res = (internalPortAudioDevice*)NULL; /* do not accept illegal ID's. */ -#endif + e = oserror(); + DBUG(("alGetParamInfo(AL_RATE) failed: %s.\n", alGetErrorString(e))); + if (e == AL_BAD_RESOURCE) + result = paInvalidDevice; + else + { + PA_SGI_SET_LAST_AL_ERROR() /* Sure an AL error occured. */ + result = paUnanticipatedHostError; + } + } + else + { + lsr = alDoubleToFixed(sr); /* Within the range? */ + if ((pinfo.min.ll <= lsr) && (lsr <= pinfo.max.ll)) + result = paFormatIsSupported; + else + result = paInvalidSampleRate; } - return res; + /* DBUG(("sr_supported()=%d.\n", result)); */ + return result; } -/*----------------------------------------------------------------------*/ -const PaDeviceInfo* Pa_GetDeviceInfo(PaDeviceID id) + +/* + See common/portaudio.h (suggestedLatency field is ignored). +*/ +static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi, + const PaStreamParameters *inputParameters, + const PaStreamParameters *outputParameters, + double sampleRate ) { - PaDeviceInfo* res = (PaDeviceInfo*)NULL; - internalPortAudioDevice* pad = Pa_GetInternalDevice(id); /* Call. */ - if (pad) - res = &pad->pad_Info; /* Not finding the specified ID is not */ - if (!res) /* the same as &pad->pad_Info == NULL. */ - ERR_RPT(("Pa_GetDeviceInfo() could not find it (ID=%d).\n", id)); - return res; /* So (maybe) a second/third ERR_RPT(). */ + PaSGIHostApiRepresentation* SGIHostApi = (PaSGIHostApiRepresentation*)hostApi; + int inputChannelCount, outputChannelCount, result; + 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 */ + /* Check if samplerate is supported for this input device. */ + result = sr_supported(SGIHostApi->sgiDeviceIDs[inputParameters->device].i, sampleRate); + if (result != paFormatIsSupported) /* PA_SGI_SET_LAST_AL_ERROR() may already be called. */ + return result; + } + else + { + inputChannelCount = 0; + } + if( outputParameters ) /* As with input above. */ + { + outputChannelCount = outputParameters->channelCount; + outputSampleFormat = outputParameters->sampleFormat; + if( outputParameters->device == paUseHostApiSpecificDeviceSpecification ) + return paInvalidDevice; + if( outputChannelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels ) + return paInvalidChannelCount; + if( outputParameters->hostApiSpecificStreamInfo ) + return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */ + /* Check if samplerate is supported for this output device. */ + result = sr_supported(SGIHostApi->sgiDeviceIDs[outputParameters->device].i, sampleRate); + if (result != paFormatIsSupported) + return result; + } + else + { + outputChannelCount = 0; + } + /* IMPLEMENT ME: + 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 + */ + /* suppress unused variable warnings */ + (void) inputSampleFormat; + (void) outputSampleFormat; + return paFormatIsSupported; } -/*------------------------------------------------*/ -PaDeviceID Pa_GetDefaultInputDeviceID(void) +/** Auxilary struct, embedded twice in the struct below, for inputs and outputs. */ +typedef struct PaSGIhostPortBuffer { - return 0; /* 0 is the default device ID. */ + /** NULL means IRIX AL port closed. */ + ALport port; + /** NULL means memory not allocated. */ + void* buffer; } -/*------------------------------------------------*/ -PaDeviceID Pa_GetDefaultOutputDeviceID(void) + PaSGIhostPortBuffer; + +/** Stream data structure specifically for this IRIX AL implementation. */ +typedef struct PaSGIStream { - return 0; + PaUtilStreamRepresentation streamRepresentation; + PaUtilCpuLoadMeasurer cpuLoadMeasurer; + PaUtilBufferProcessor bufferProcessor; + unsigned long framesPerHostCallback; + /** Allocated host buffers and AL ports. */ + PaSGIhostPortBuffer hostPortBuffIn, + hostPortBuffOut; + /** Copy of stream flags given to OpenStream(). */ + PaStreamFlags streamFlags; + /** Stream state may be 0 or 1 or 2, but never 3. */ + unsigned char state; + /** Requests to stop or abort may come from the parent, + or from the child itself (user callback result). */ + unsigned char stopAbort; + pthread_t thread; } + PaSGIStream; + +/** Stream can be in only one of the following three states: stopped (1), active (2), or + callback finshed (0). To prevent 'state 3' from occurring, Setting and testing of the + state bits is done atomically. +*/ +#define PA_SGI_STREAM_FLAG_FINISHED_ (0) /* After callback finished or cancelled queued buffers. */ +#define PA_SGI_STREAM_FLAG_STOPPED_ (1) /* Set by OpenStream(), StopStream() and AbortStream(). */ +#define PA_SGI_STREAM_FLAG_ACTIVE_ (2) /* Set by StartStream. Reset by OpenStream(), */ + /* StopStream() and AbortStream(). */ + +/** Stop requests, via the 'stopAbort' field can be either 1, meaning 'stop' or 2, meaning 'abort'. + When both occur at the same time, 'abort' takes precedence, even after a first 'stop'. +*/ +#define PA_SGI_REQ_CONT_ (0) /* Reset by OpenStream(), StopStream and AbortStream. */ +#define PA_SGI_REQ_STOP_ (1) /* Set by StopStream(). */ +#define PA_SGI_REQ_ABORT_ (2) /* Set by AbortStream(). */ + + +/** Called by OpenStream() once or twice. First, the number of channels, sampleformat, and + queue size are configured. The configuration is then bound to the specified AL device. + Then an AL port is opened. Finally, the samplerate of the device is altered (or at least + set again). + + After successful return, actual latency is written in *latency, and actual samplerate + in *samplerate. -/*-------------------------------------------------------------------------------------------------*/ -/* Build linked a list with all the available audio devices on this SGI machine (only 1 for now). */ -PaError PaHost_Init(void) /* Called by Pa_Initialize() from pa_lib.c. */ + @param pa_params may be NULL and pa_params->channelCount may also be null, in both + cases the function immediately returns. + @return paNoError if configuration was skipped or if it succeeded. +*/ +static PaError set_sgi_device(ALvalue* sgiDeviceIDs, /* Array built by PaSGI_Initialize(). */ + const PaStreamParameters* pa_params, /* read device and channels. */ + double* latency, /* Read and write in seconds. */ + + PaSampleFormat pasfmt, /* Don't read from pa_params!. */ + char* direction, /* "r" or "w". */ + char* name, + long framesPerHostBuffer, + double* samplerate, /* Also writes back here. */ + PaSGIhostPortBuffer* hostPortBuff) /* Receive pointers here. */ { - internalPortAudioDevice* pad; - PaError r = paNoError; - int audioLibFileID; /* To test for the presence of audio. */ + int bytesPerFrame, sgiDevice, alErr, d, dd, iq_size, default_iq_size; + ALpv pvs[2]; + ALconfig alc = NULL; + PaError result = paNoError; - if (sDeviceList) /* Allow re-init, only warn, no error. */ + if (!pa_params) + goto cleanup; /* Not errors, just not full duplex, skip all. */ + if (!pa_params->channelCount) + goto cleanup; + alc = alNewConfig(); /* Create default config. This defaults to stereo, 16-bit integer data. */ + if (!alc) /* Call alFreeConfig() later, when done with it. */ + { result = paInsufficientMemory; goto cleanup; } + /*----------------------- CONFIGURE NUMBER OF CHANNELS: ---------------------------*/ + if (alSetChannels(alc, pa_params->channelCount)) /* Returns 0 on success. */ { - ERR_RPT(("Warning: PaHost_Init() did not really re-init PA.\n")); - return r; - } - /*------------- ADD THE SGI DEFAULT DEVICE TO THE LIST: ---------------------------------------*/ - audioLibFileID = open("/dev/hdsp/hdsp0master", O_RDONLY); /* Try to open Indigo style audio */ - if (audioLibFileID < 0) /* IO port. On failure, machine */ - { /* has no audio ability. */ - ERR_RPT(("PaHost_Init(): This machine has no (Indigo-style) audio abilities.\n")); - return paHostError; + if (oserror() == AL_BAD_CHANNELS) + result = paInvalidChannelCount; + else + { + PA_SGI_SET_LAST_AL_ERROR() + result = paUnanticipatedHostError; + } + goto cleanup; } - close(audioLibFileID); /* Allocate fast mem to hold device info. */ - pad = PaHost_AllocateFastMemory(sizeof(internalPortAudioDevice)); - if (pad == NULL) - return paInsufficientMemory; - memset(pad, 0, sizeof(internalPortAudioDevice)); /* "pad->pad_Next = NULL" is more elegant. */ - r = Pa_sgiQueryDevice(AL_DEFAULT_DEVICE, /* Set AL device num (AL_DEFAULT_DEVICE). */ - Pa_GetDefaultOutputDeviceID(),/* Set PA device num (or InputDeviceID()). */ - "AL default", /* A suitable name. */ - pad); /* Write args and queried info into pad. */ - if (r != paNoError) + bytesPerFrame = pa_params->channelCount; /* Is multiplied by width below. */ + /*----------------------- CONFIGURE SAMPLE FORMAT: --------------------------------*/ + if (pasfmt == paFloat32) { - ERR_RPT(("Pa_QueryDevice for '%s' returned: %d\n", pad->pad_DeviceName, r)); - PaHost_FreeFastMemory(pad, sizeof(internalPortAudioDevice)); /* sDeviceList still NULL ! */ + if (alSetSampFmt(alc, AL_SAMPFMT_FLOAT)) + { + if (oserror() == AL_BAD_SAMPFMT) + result = paSampleFormatNotSupported; + else + { + PA_SGI_SET_LAST_AL_ERROR() + result = paUnanticipatedHostError; + } + goto cleanup; + } + bytesPerFrame *= 4; /* No need to set width for floats. */ } else - sDeviceList = pad; /* First element in linked list. pad->pad_Next already NULL. */ - /*------------- QUERY AND ADD MORE POSSIBLE SGI DEVICES TO THE LINKED LIST: -------------------*/ - /*---------------------------------------------------------------------------------------------*/ - return r; -} - -/*--------------------------------------------------------------------------------------------*/ -#define MIN(a,b) ((a)<(b)?(a):(b)) /* MIN()-function is used below. */ -#define kPollSEMA 0 /* To index the pollfd-array, reads nicer than just */ -#define kPollOUT 1 /* numbers. */ -#define kPollIN 2 -void Pa_SgiAudioProcess(void *v) /* This function is sproc-ed by PaHost_StartEngine() */ -{ /* as a separate thread. (Argument must be void*). */ - short evtLoop; /* Reset by parent indirectly, or at local errors. */ - PaError result; - struct pollfd PollFD[3]; /* To catch kPollSEMA-, kPollOUT- and kPollIN-events. */ - internalPortAudioStream *past = (internalPortAudioStream*)v; /* Copy void-ptr-argument. */ - PaHostSoundControl *pahsc; - short n, inputEvent, outputEvent, semaEvent; /* .revents are shorts. */ - short *inBuffer, *outBuffer; /* FIX: Only 16 bit for now, may change... */ - unsigned int samplesPerInputUserBuffer, samplesPerOutputUserBuffer; - - DBUG(("Entering sproc-thread.\n")); - if (!past) - { - sPaHostError = paInternalError; /* Or paBadStreamPtr ? */ - ERR_RPT(("argument NULL!\n")); - goto skip; - } - pahsc = (PaHostSoundControl*)past->past_DeviceData; - if (!pahsc) { - sPaHostError = paInternalError; /* The only way is to signal error to shared area?! */ - ERR_RPT(("past_DeviceData NULL!\n")); - goto skip; /* Sproc-ed threads MAY NOT RETURN paInternalError. */ - } - /*----------------------------- open AL-ports here, after sproc(): -----------------------*/ - if (past->past_NumInputChannels > 0) /* Open input port. */ - { - pahsc->pahsc_ALportIN = ALopenport("PA sgi in", "r", pahsc->pahsc_ALconfigIN); - if (!pahsc->pahsc_ALportIN) + if (alSetSampFmt(alc, AL_SAMPFMT_TWOSCOMP)) { - ERR_RPT(("Failed to open AL input port.\n")); - sPaHostError = paInternalError; - goto skip; + if (oserror() == AL_BAD_SAMPFMT) + result = paSampleFormatNotSupported; + else + { + PA_SGI_SET_LAST_AL_ERROR() + result = paUnanticipatedHostError; + } + goto cleanup; } - DBUG(("Opened %d input channel(s).\n", past->past_NumInputChannels)); - samplesPerInputUserBuffer = pahsc->pahsc_SamplesPerInputHostBuffer / - pahsc->pahsc_UserBuffersPerHostBuffer; - } - if (past->past_NumOutputChannels > 0) /* Open output port. */ - { - pahsc->pahsc_ALportOUT = ALopenport("PA sgi out", "w", pahsc->pahsc_ALconfigOUT); - if (!pahsc->pahsc_ALportOUT) + if (pasfmt == paInt8) { - ERR_RPT(("Failed to open AL output port.\n")); - sPaHostError = paInternalError; /* Assume pahsc_ALconfigs are the */ - goto skip; /* same for IN and OUT in case */ - } /* both ports are opened (bidir). */ - DBUG(("Opened %d output channel(s).\n", past->past_NumOutputChannels)); - samplesPerOutputUserBuffer = pahsc->pahsc_SamplesPerOutputHostBuffer / - pahsc->pahsc_UserBuffersPerHostBuffer; - DBUG(("samplesPerOutputUserBuffer = %d\n", samplesPerOutputUserBuffer)); - } - /*-----------------------------------------------------------------------*/ - past->past_IsActive = 1; /* Wasn't this already done by the calling parent?! */ - PollFD[kPollIN].fd = ALgetfd(pahsc->pahsc_ALportIN); /* ALgetfd returns -1 on failures */ - PollFD[kPollIN].events = POLLIN; /* such as ALport not there. */ - PollFD[kPollOUT].fd = ALgetfd(pahsc->pahsc_ALportOUT); - PollFD[kPollOUT].events = POLLOUT; /* .events = POLLOUT is OK. */ - schedctl(NDPRI, NDPHIMIN); /* Sets non-degrading priority for this process. */ - PollFD[kPollSEMA].fd = usopenpollsema(SendSema, 0777); /* To communicate with parent. */ - PollFD[kPollSEMA].events = POLLIN; /* .events = POLLIN is OK. */ - uspsema(SendSema); /* Blocks until ... MUST be here, this uspsema(). */ - evtLoop = ((past->past_StopNow | past->past_StopSoon) == 0); - while (evtLoop) - { - /*---------------------------- SET FILLPOINTS AND WAIT UNTIL SOMETHING HAPPENS: ----------*/ - if (pahsc->pahsc_InputHostBuffer) /* Then pahsc_ALportIN should also be there! */ - /* For input port, fill point is number of locations in the sample queue that must be */ - /* filled in order to trigger a return from select(). (or poll()) */ - /* Notice IRIX docs mention number of samples as argument, not number of sampleframes.*/ - if (ALsetfillpoint(pahsc->pahsc_ALportIN, pahsc->pahsc_SamplesPerInputHostBuffer)) - { /* Multiple amount as transferred per time. */ - ERR_RPT(("ALsetfillpoint() for ALportIN failed.\n")); - sPaHostError = paInternalError; /* (Using exit(-1) would be a bit rude.) */ - goto skip; - } - if (pahsc->pahsc_OutputHostBuffer) /* Then pahsc_ALportOUT should also be there! */ - /* For output port, fill point is number of locations that must be free in order to */ - /* wake up from select(). (or poll()) */ - if (ALsetfillpoint(pahsc->pahsc_ALportOUT, pahsc->pahsc_SamplesPerOutputHostBuffer)) + if (alSetWidth(alc, AL_SAMPLE_8)) { - ERR_RPT(("ALsetfillpoint() for ALportOUT failed.\n")); - sPaHostError = paInternalError; /* (Using exit(-1) would be a bit rude.) */ - goto skip; - } /* poll() with timeout=-1 makes it block until a requested */ - poll(PollFD, 3, -1); /* event occurs or until call is interrupted. If fd-value in */ - /* array <0, events is ignored and revents is set to 0. */ - /*---------------------------- MESSAGE-EVENT FROM PARENT THREAD: -------------------------*/ - semaEvent = PollFD[kPollSEMA].revents & POLLIN; - if (semaEvent) - { - if (past->past_StopSoon) - evtLoop = 0; - if (past->past_StopNow) - goto skip; + if (oserror() == AL_BAD_WIDTH) + result = paSampleFormatNotSupported; + else + { + PA_SGI_SET_LAST_AL_ERROR() + result = paUnanticipatedHostError; + } + goto cleanup; + } + /* bytesPerFrame *= 1; */ } - /*------------------------------------- FILLED-EVENT FROM INPUT BUFFER: --------------------------*/ - inputEvent = PollFD[kPollIN].revents & POLLIN; - if (inputEvent) /* Don't need to check (pahsc->pahsc_InputHostBuffer): */ - { /* if buffer was not there, ALport not there, no events! */ - if (ALreadsamps(pahsc->pahsc_ALportIN, (void*)pahsc->pahsc_InputHostBuffer, - pahsc->pahsc_SamplesPerInputHostBuffer)) - { /* Here again: number of samples instead of number of frames. */ - ERR_RPT(("ALreadsamps() failed.\n")); - sPaHostError = paInternalError; - goto skip; + else if (pasfmt == paInt16) + { + if (alSetWidth(alc, AL_SAMPLE_16)) + { + if (oserror() == AL_BAD_WIDTH) + result = paSampleFormatNotSupported; + else + { + PA_SGI_SET_LAST_AL_ERROR() + result = paUnanticipatedHostError; + } + goto cleanup; } + bytesPerFrame *= 2; } - outputEvent = PollFD[kPollOUT].revents & POLLOUT; - /*------------------------------------- USER-CALLBACK-ROUTINE: -----------------------------------*/ - if (inputEvent | outputEvent) /* (Bitwise is ok.) */ - { /* To be sure we that really DID input-transfer or gonna DO output-transfer, and that it is */ - /* not just "sema"- (i.e. user)-event, or some other system-event that awakened the poll(). */ - Pa_StartUsageCalculation(past); /* Convert 16 bit native data to */ - /* user data and call user routine. */ - inBuffer = pahsc->pahsc_InputHostBuffer; /* Short pointers for now, care! */ - outBuffer = pahsc->pahsc_OutputHostBuffer; - n = pahsc->pahsc_UserBuffersPerHostBuffer; /* 'n' may never start at NULL ! */ - do { - result = Pa_CallConvertInt16(past, inBuffer, outBuffer); - if (result) /* This is apparently NOT an error! Just letting the userCallBack stop us. */ - { DBUG(("Pa_CallConvertInt16() returned %d, stopping...\n", result)); goto skip; } - inBuffer += samplesPerInputUserBuffer; /* Num channels is accounted for. */ - outBuffer += samplesPerOutputUserBuffer; - } while (--n); - Pa_EndUsageCalculation(past); - } - /*------------------------------------- FREE-EVENT FROM OUTPUT BUFFER: ---------------------------*/ - if (outputEvent) /* Don't need to check (pahsc->pahsc_OutputHostBuffer) */ - { /* because if filedescriptor not there, no event for it. */ - if (ALwritesamps(pahsc->pahsc_ALportOUT, (void*)pahsc->pahsc_OutputHostBuffer, - pahsc->pahsc_SamplesPerOutputHostBuffer)) + else if (pasfmt == paInt24) + { + if (alSetWidth(alc, AL_SAMPLE_24)) { - ERR_RPT(("ALwritesamps() failed.\n")); /* Better use SEMAS for messaging back to parent! */ - sPaHostError = paInternalError; - goto skip; + if (oserror() == AL_BAD_WIDTH) + result = paSampleFormatNotSupported; + else + { + PA_SGI_SET_LAST_AL_ERROR() + result = paUnanticipatedHostError; + } + goto cleanup; } + bytesPerFrame *= 3; /* OR 4 ???????! */ } + else return paSampleFormatNotSupported; } -skip: - /*------------------------------- close AL-ports ----------------------------*/ - if (pahsc->pahsc_ALportIN) - { - if (ALcloseport(pahsc->pahsc_ALportIN)) - translateSGIerror(); /* Translates SGI AL-code to PA-code and ERR_RPTs string. */ - else /* But go on anyway... to release other stuff... */ - pahsc->pahsc_ALportIN = (ALport)0; + /*----------------------- SET INTERNAL AL QUEUE SIZE: -------------------------------*/ + /* The AL API doesn't provide a means for querying minimum and maximum buffer sizes. + So, if the requested size fails, try again with a value that is closer to the AL's + default queue size. In this implementation, 'Portaudio latency' corresponds to + the AL queue size minus one buffersize: + AL queue size - framesPerHostBuffer + PA latency = ----------------------------------- + sample rate */ + default_iq_size = alGetQueueSize(alc); + if (default_iq_size < 0) /* So let's first get that 'default size'. */ + { /* Default internal queue size could not be determined. */ + PA_SGI_SET_LAST_AL_ERROR() + result = paUnanticipatedHostError; + goto cleanup; + } + /* AL buffer becomes somewhat bigger than the suggested latency, notice this is */ + /* based on requsted samplerate, not in the actual rate, which is measured later. */ + /* Do NOT read pa_params->suggestedLatency, but use the limited *latency param! */ + + iq_size = (int)(0.5 + ((*latency) * (*samplerate))) + (int)framesPerHostBuffer; + /* The AL buffer becomes somewhat */ + /* bigger than the suggested latency. */ + if (iq_size < (framesPerHostBuffer << 1)) /* Make sure the minimum is twice */ + { /* framesPerHostBuffer. */ + DBUG(("Setting minimum queue size.\n")); + iq_size = (framesPerHostBuffer << 1); } - if (pahsc->pahsc_ALportOUT) + d = iq_size - default_iq_size; /* Determine whether we'll decrease */ + while (alSetQueueSize(alc, iq_size)) /* or increase after failing. */ + { /* Size in sample frames. */ + if (oserror() != AL_BAD_QSIZE) /* Stop at AL_BAD_CONFIG. */ + { + PA_SGI_SET_LAST_AL_ERROR() + result = paUnanticipatedHostError; + goto cleanup; + } + dd = iq_size - default_iq_size; /* Stop when even the default size failed */ + if (((d >= 0) && (dd <= 0)) || /* (dd=0) or when difference flipped sign. */ + ((d <= 0) && (dd >= 0)) || + (iq_size <= framesPerHostBuffer)) /* Also guarentee that framesPerHostBuffer */ + { /* can be subtracted (res>0) after return. */ + DBUG(("Could not set AL queue size to %d sample frames!\n", iq_size)); + result = paInternalError; /* FIX: PROBABLY AN INAPROPRIATE ERROR CODE HERE. */ + goto cleanup; /* As inapropriate as paUnanticipatedHostError was? */ + } + DBUG(("Failed to set internal queue size to %d frames, ", iq_size)); + if (d > 0) + iq_size -= framesPerHostBuffer; /* Try lesser multiple. */ + else + iq_size += framesPerHostBuffer; /* Try larger multiple. */ + DBUG(("trying %d frames now...\n", iq_size)); + } + /* Note: Actual latency is written back to *latency after meausuring actual (not + the requested) samplerate. See below. + */ + /*----------------------- ALLOCATE HOST BUFFER: --------------------------------------*/ + hostPortBuff->buffer = PaUtil_AllocateMemory((long)bytesPerFrame * framesPerHostBuffer); + if (!hostPortBuff->buffer) /* Caller is responsible for cleanup+close after failures! */ + { result = paInsufficientMemory; goto cleanup; } + /*----------------------- BIND CONFIGURATION TO DEVICE: ------------------------------*/ + sgiDevice = sgiDeviceIDs[pa_params->device].i; + if (alSetDevice(alc, sgiDevice)) /* Try to switch the hardware. */ { - if (ALcloseport(pahsc->pahsc_ALportOUT)) - translateSGIerror(); + if (oserror() == AL_BAD_DEVICE) + result = paInvalidDevice; else - pahsc->pahsc_ALportOUT = (ALport)0; + { + PA_SGI_SET_LAST_AL_ERROR() + result = paUnanticipatedHostError; + } + goto cleanup; + } + /*----------------------- OPEN PORT: ----------------------------------------------*/ + hostPortBuff->port = alOpenPort(name, direction, alc); /* Caller is responsible */ + if (!hostPortBuff->port) /* for closing after fail. */ + { + PA_SGI_SET_LAST_AL_ERROR() + result = paUnanticipatedHostError; + goto cleanup; + } /* Maybe set SR earlier? */ + /*----------------------- SET SAMPLERATE: -----------------------------------------*/ + pvs[0].param = AL_MASTER_CLOCK; /* Attempt to set a crystal-based sample- */ + pvs[0].value.i = AL_CRYSTAL_MCLK_TYPE; /* rate on input or output device. */ + pvs[1].param = AL_RATE; + pvs[1].value.ll = alDoubleToFixed(*samplerate); + if (2 != alSetParams(sgiDevice, pvs, 2)) + { + DBUG(("alSetParams() failed to set samplerate to %.4f Hz!\n", *samplerate)); + result = paInvalidSampleRate; + goto cleanup; } - past->past_IsActive = 0; - if (semaEvent) + /*----------------------- GET ACTUAL SAMPLERATE: ---------------------------*/ + alErr = alGetParams(sgiDevice, &pvs[1], 1); /* SEE WHAT WE REALY SET IT TO. */ + if (alErr != 1) /* And return that to caller. */ { - uspsema(SendSema); /* StopEngine() was still waiting for this acknowledgement. */ - usvsema(RcvSema); /* (semaEvent initialized with 0.) */ + DBUG(("alGetParams() failed to read samplerate!\n")); + result = paInvalidSampleRate; + goto cleanup; } - DBUG(("Leaving sproc-thread.\n")); + *samplerate = alFixedToDouble(pvs[1].value.ll); /* Between 1 Hz and 1 MHz. */ + if ((*samplerate < 1.0) || (*samplerate > 1000000.0)) + { + DBUG(("alFixedToDouble() resulted a weird samplerate: %.6f Hz!\n", *samplerate)); + result = paInvalidSampleRate; + goto cleanup; + } + /*----------------------- CALC ACTUAL LATENCY (based on actual SR): -----------------------*/ + *latency = (iq_size - framesPerHostBuffer) / (*samplerate); /* FIX: SURE > 0!???? */ +cleanup: + if (alc) + alFreeConfig(alc); /* We no longer need configuration. */ + return result; } +/** + Called by OpenStream() if it fails and by CloseStream. Only used here, in this file. + Fields MUST be set to NULL or to a valid value, prior to call. +*/ +static void streamCleanupAndClose(PaSGIStream* stream) +{ + if (stream->hostPortBuffIn.port) alClosePort(stream->hostPortBuffIn.port); /* Close AL ports. */ + if (stream->hostPortBuffIn.buffer) PaUtil_FreeMemory(stream->hostPortBuffIn.buffer); /* Release buffers. */ + if (stream->hostPortBuffOut.port) alClosePort(stream->hostPortBuffOut.port); + if (stream->hostPortBuffOut.buffer) PaUtil_FreeMemory(stream->hostPortBuffOut.buffer); +} -/*--------------------------------------------------------------------------------------*/ -PaError PaHost_OpenStream(internalPortAudioStream *past) + +/* See pa_hostapi.h for a list of validity guarantees made about OpenStream parameters. */ +static PaError OpenStream(struct PaUtilHostApiRepresentation* hostApi, + PaStream** s, + const PaStreamParameters* ipp, + const PaStreamParameters* opp, + double sampleRate, /* Common to both i and o. */ + unsigned long framesPerBuffer, + PaStreamFlags streamFlags, + PaStreamCallback* streamCallback, + void* userData) { - PaError result = paNoError; - PaHostSoundControl *pahsc; - unsigned int minNumBuffers; - internalPortAudioDevice *padIN, *padOUT; /* For looking up native AL-numbers. */ - long pvbuf[8], sr, alq; /* To get/set hardware configs. */ - - DBUG(("PaHost_OpenStream() called.\n")); /* Alloc FASTMEM and init host data. */ - if (!past) + PaError result = paNoError; + PaSGIHostApiRepresentation* SGIHostApi = (PaSGIHostApiRepresentation*)hostApi; + PaSGIStream* stream = 0; + unsigned long framesPerHostBuffer; /* Not necessarily the same as framesPerBuffer. */ + int inputChannelCount, outputChannelCount; + PaSampleFormat inputSampleFormat, outputSampleFormat, + hostInputSampleFormat, hostOutputSampleFormat; + double sr_in, sr_out, + latency_in, latency_out; + static const PaSampleFormat irixFormats = (paInt8 | paInt16 | paInt24 | paFloat32); + /* Constant used by PaUtil_SelectClosestAvailableFormat(). Because IRIX AL does not + provide a way to query for possible formats for a given device, interface or port, + just add together the formats we know that are supported in general by IRIX AL + (at the end of the year 2003): AL_SAMPFMT_TWOSCOMP with AL_SAMPLE_8(=paInt8), + AL_SAMPLE_16(=paInt16) or AL_SAMPLE_24(=paInt24); AL_SAMPFMT_FLOAT(=paFloat32); + AL_SAMPFMT_DOUBLE(=paFloat64); IRIX misses unsigned 8 and 32 bit signed ints. + */ + DBUG(("OpenStream() started.\n")); + if (ipp) + { + inputChannelCount = ipp->channelCount; + inputSampleFormat = ipp->sampleFormat; + /* Unless alternate device specification is supported, reject the use of paUseHostApiSpecificDeviceSpecification. */ + if (ipp->device == paUseHostApiSpecificDeviceSpecification) /* DEVICE CHOOSEN BY CLIENT. */ + return paInvalidDevice; + /* Check that input device can support inputChannelCount. */ + if (inputChannelCount > hostApi->deviceInfos[ipp->device]->maxInputChannels) + return paInvalidChannelCount; + /* Validate inputStreamInfo. */ + if (ipp->hostApiSpecificStreamInfo) + return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */ + hostInputSampleFormat = PaUtil_SelectClosestAvailableFormat(irixFormats, inputSampleFormat); + /* Check if samplerate is supported for this input device. */ + result = sr_supported(SGIHostApi->sgiDeviceIDs[ipp->device].i, sampleRate); + if (result != paFormatIsSupported) /* PA_SGI_SET_LAST_AL_ERROR() may already be called. */ + return result; + /* Validate input latency. Use defaults if necessary. */ + if (ipp->suggestedLatency < hostApi->deviceInfos[ipp->device]->defaultLowInputLatency) + latency_in = hostApi->deviceInfos[ipp->device]->defaultLowInputLatency; /* Low = minimum. */ + else if (ipp->suggestedLatency > 10.0 * hostApi->deviceInfos[ipp->device]->defaultHighInputLatency) + latency_in = 10.0 * hostApi->deviceInfos[ipp->device]->defaultHighInputLatency; /* 10*High = max. */ + else + latency_in = ipp->suggestedLatency; + } + else + { + inputChannelCount = 0; + inputSampleFormat = hostInputSampleFormat = paInt16; /* Surpress 'uninitialised var' warnings. */ + latency_in = 0.0; /* Necessary? */ + } + if (opp) { - ERR_RPT(("Streampointer NULL!\n")); - result = paBadStreamPtr; goto done; + outputChannelCount = opp->channelCount; + outputSampleFormat = opp->sampleFormat; + if (opp->device == paUseHostApiSpecificDeviceSpecification) /* Like input (above). */ + return paInvalidDevice; + if (outputChannelCount > hostApi->deviceInfos[opp->device]->maxOutputChannels) + return paInvalidChannelCount; + if (opp->hostApiSpecificStreamInfo ) + return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */ + hostOutputSampleFormat = PaUtil_SelectClosestAvailableFormat(irixFormats, outputSampleFormat); + /* Check if samplerate is supported for this output device. */ + result = sr_supported(SGIHostApi->sgiDeviceIDs[opp->device].i, sampleRate); + if (result != paFormatIsSupported) + return result; + /* Validate output latency. Use defaults if necessary. */ + if (opp->suggestedLatency < hostApi->deviceInfos[opp->device]->defaultLowOutputLatency) + latency_out = hostApi->deviceInfos[opp->device]->defaultLowOutputLatency; /* Low = minimum. */ + else if (opp->suggestedLatency > 10.0 * hostApi->deviceInfos[opp->device]->defaultHighOutputLatency) + latency_out = 10.0 * hostApi->deviceInfos[opp->device]->defaultHighOutputLatency; /* 10*High = max. */ + else + latency_out = opp->suggestedLatency; } - pahsc = (PaHostSoundControl*)PaHost_AllocateFastMemory(sizeof(PaHostSoundControl)); - if (pahsc == NULL) + else { - ERR_RPT(("FAST Memory allocation failed.\n")); /* Pass trough some ERR_RPT-exit- */ - result = paInsufficientMemory; goto done; /* code (nothing will be freed). */ + outputChannelCount = 0; + outputSampleFormat = hostOutputSampleFormat = paInt16; /* Surpress 'uninitialised var' warning. */ + latency_out = 0.0; + } + /* Sure that ipp and opp will never be both NULL. */ + + if( (streamFlags & paPlatformSpecificFlags) != 0 ) /* Validate platform specific flags. */ + return paInvalidFlag; /* Unexpected platform specific flag. */ + + stream = (PaSGIStream*)PaUtil_AllocateMemory( sizeof(PaSGIStream) ); + if (!stream) + { result = paInsufficientMemory; goto cleanup; } + + stream->hostPortBuffIn.port = (ALport)NULL; /* Ports closed. */ + stream->hostPortBuffIn.buffer = NULL; /* No buffers yet. */ + stream->hostPortBuffOut.port = (ALport)NULL; + stream->hostPortBuffOut.buffer = NULL; + + if (streamCallback) + PaUtil_InitializeStreamRepresentation(&stream->streamRepresentation, + &SGIHostApi->callbackStreamInterface, streamCallback, userData); + else + PaUtil_InitializeStreamRepresentation(&stream->streamRepresentation, + &SGIHostApi->blockingStreamInterface, streamCallback, userData); + /* (NULL.) */ + if (framesPerBuffer == paFramesPerBufferUnspecified) /* Proposal 004. */ + { /* Keep framesPerBuffer zero but come up with some fixed host buffer size. */ + double lowest_lat = 0.0; /* 0.0 to surpress uninit warning, we're sure it will end up higher. */ + if (ipp) + lowest_lat = latency_in; /* Sure > 0.0! */ + if (opp && (latency_out < lowest_lat)) + lowest_lat = latency_out; + /* So that queue size becomes approximately 5 times framesPerHostBuffer: */ + framesPerHostBuffer = (unsigned long)((lowest_lat * sampleRate) / 4.0); + /* But always limit: */ + if (framesPerHostBuffer < 64L) + framesPerHostBuffer = 64L; + else if (framesPerHostBuffer > 32768L) + framesPerHostBuffer = 32768L; + DBUG(("Decided to use a fixed host buffer size of %ld frames.\n", framesPerHostBuffer)); } - memset(pahsc, 0, sizeof(PaHostSoundControl)); - pahsc->pahsc_threadPID = -1; /* Should pahsc_threadPID be inited to */ - past->past_DeviceData = (void*)pahsc; /* -1 instead of 0 ?? */ - /*------------------------------------------ Manipulate hardware if necessary and allowed: --*/ - ALseterrorhandler(0); /* 0 = turn off the default error handler. */ - pvbuf[0] = AL_INPUT_RATE; - pvbuf[2] = AL_INPUT_COUNT; - pvbuf[4] = AL_OUTPUT_RATE; /* TO FIX: rates may be logically, not always in Hz! */ - pvbuf[6] = AL_OUTPUT_COUNT; - sr = (long)(past->past_SampleRate + 0.5); /* Common for both input and output :-) */ - /*-----------------------------------------------------------------------------*/ - /* OVERWRITE 'past_NumUserBuffers'-field in the struct supplied by the caller. */ - /* This field may be set to zero by a client application to ask for minimum */ - /* latency. It is used below, to set both input- and output-AL-queuesizes. */ - minNumBuffers = Pa_GetMinNumBuffers(past->past_FramesPerUserBuffer, - past->past_SampleRate); /* Take biggest. */ - past->past_NumUserBuffers = (minNumBuffers > past->past_NumUserBuffers) ? - minNumBuffers : past->past_NumUserBuffers; - DBUG(("past->past_NumUserBuffers=%d\n", past->past_NumUserBuffers)); - /*----------------------------------------------------------------------------------*/ - pahsc->pahsc_UserBuffersPerHostBuffer = past->past_NumUserBuffers >> 1; - DBUG(("pahsc_UserBuffersPerHostBuffer=%d\n",pahsc->pahsc_UserBuffersPerHostBuffer)); - /* 1 is minimum because Pa_GetMinNumBuffers() returns >= 2. - Callback will be called 'pahsc_UserBuffersPerHostBuffer' times (with 'past_FramesPerUserBuffer') - per host transfer. */ - /*---------------------------------------------------- SET INPUT CONFIGURATION: ---------------------*/ - if (past->past_NumInputChannels > 0) /* We need to lookup the corre- */ - { /* sponding native AL-number(s). */ - /*--------------------------------------------------- Allocate native buffers: --------------*/ - pahsc->pahsc_SamplesPerInputHostBuffer = pahsc->pahsc_UserBuffersPerHostBuffer * - past->past_FramesPerUserBuffer * /* Needed by the */ - past->past_NumInputChannels; /* audio-thread. */ - DBUG(("pahsc_SamplesPerInputHostBuffer=%d\n", pahsc->pahsc_SamplesPerInputHostBuffer)); - pahsc->pahsc_BytesPerInputHostBuffer = pahsc->pahsc_SamplesPerInputHostBuffer * sizeof(short); - pahsc->pahsc_InputHostBuffer = (short*)PaHost_AllocateFastMemory(pahsc->pahsc_BytesPerInputHostBuffer); - if (!pahsc->pahsc_InputHostBuffer) + else + framesPerHostBuffer = framesPerBuffer; /* Then just take the requested amount. No buffer-adaption yet? */ + + sr_in = sr_out = sampleRate; + /*-------------------------------------------------------------------------------------------*/ + result = set_sgi_device(SGIHostApi->sgiDeviceIDs, /* Needed by alSetDevice and other functs. */ + ipp, /* Reads channelCount, device but NOT latency. */ + &latency_in, /* Read limited requested latency but also WRITE actual. */ + hostInputSampleFormat, /* For alSetSampFmt and alSetWidth. */ + "r", /* "r" for reading from input port. */ + "portaudio in", /* Name string. */ + framesPerHostBuffer, /* As calculated or as requested by the client. */ + &sr_in, /* Receive actual s.rate after setting it. */ + &stream->hostPortBuffIn); /* Receives ALport and input host buffer. */ + if (result != paNoError) goto cleanup; + /*-------------------------------------------------------------------------------------------*/ + result = set_sgi_device(SGIHostApi->sgiDeviceIDs, + opp, + &latency_out, + hostOutputSampleFormat, + "w", /* "w" for writing. */ + "portaudio out", + framesPerHostBuffer, + &sr_out, + &stream->hostPortBuffOut); + if (result != paNoError) goto cleanup; + /*------------------------------------------------------------------------------------------*/ + if (fabs(sr_in - sr_out) > 0.001) /* Make sure both are the 'same'. */ + { + DBUG(("Weird samplerate difference between input and output!\n")); + result = paInvalidSampleRate; /* Could not come up with a better error code. */ + goto cleanup; + } /* sr_in '==' sr_out. */ + sampleRate = sr_in; /* Following fields set to estimated or actual values: */ + stream->streamRepresentation.streamInfo.sampleRate = sampleRate; + stream->streamRepresentation.streamInfo.inputLatency = latency_in; /* 0.0 if output only. */ + stream->streamRepresentation.streamInfo.outputLatency = latency_out; /* 0.0 if input only. */ + + PaUtil_InitializeCpuLoadMeasurer(&stream->cpuLoadMeasurer, sampleRate); + result = PaUtil_InitializeBufferProcessor(&stream->bufferProcessor, + inputChannelCount, inputSampleFormat, hostInputSampleFormat, + outputChannelCount, outputSampleFormat, hostOutputSampleFormat, + sampleRate, streamFlags, + framesPerBuffer, /* As requested by OpenStream(), may be zero! */ + framesPerHostBuffer, /* Use fixed number of frames per host buffer */ + paUtilFixedHostBufferSize, /* to keep things simple. See pa_common/pa_ */ + streamCallback, userData); /* process.h for more hostbuffersize options. */ + if (result != paNoError) + goto cleanup; + + stream->framesPerHostCallback = framesPerHostBuffer; + stream->streamFlags = streamFlags; /* Remember priming request. */ + stream->state = PA_SGI_STREAM_FLAG_STOPPED_; /* After opening, the stream */ + stream->stopAbort = PA_SGI_REQ_CONT_; /* is in the stopped state. */ + *s = (PaStream*)stream; /* Pass object to caller. */ +cleanup: + if (result != paNoError) /* Always set result when jumping to cleanup after failure. */ + { + if (stream) { - ERR_RPT(("Fast memory allocation failed (in).\n")); - result = paInsufficientMemory; - goto done; + streamCleanupAndClose(stream); /* Frees i/o buffers and closes AL ports. */ + PaUtil_FreeMemory(stream); + } + } + return result; +} + +/** POSIX thread that performs the actual i/o and calls the client's callback, + spawned by StartStream(). +*/ +static void* PaSGIpthread(void *userData) +{ + PaSGIStream* stream = (PaSGIStream*)userData; + int callbackResult = paContinue; + double nanosec_per_frame; + PaStreamCallbackTimeInfo timeInfo = { 0, 0, 0 }; + + stream->state = PA_SGI_STREAM_FLAG_ACTIVE_; /* Parent thread also sets active flag, but we + make no assumption about who does this first. */ + nanosec_per_frame = 1000000000.0 / stream->streamRepresentation.streamInfo.sampleRate; + /*----------------------------------------------- OUTPUT PRIMING: -----------------------------*/ + if (stream->hostPortBuffOut.port) /* Somewhat less than AL queue size so the next */ + { /* output buffer will (probably) not block. */ + unsigned long frames_to_prime = (long)(0.5 + + (stream->streamRepresentation.streamInfo.outputLatency + * stream->streamRepresentation.streamInfo.sampleRate)); + if (stream->streamFlags & paPrimeOutputBuffersUsingStreamCallback) + { + PaStreamCallbackFlags cbflags = paPrimingOutput; + if (stream->hostPortBuffIn.port) /* Only set this flag in case of full duplex. */ + cbflags |= paInputUnderflow; + DBUG(("Prime with client's callback: < %ld frames.\n", frames_to_prime)); + while (frames_to_prime >= stream->framesPerHostCallback) /* We will not do less (yet). */ + { /* TODO: Timestamps and CPU load */ + PaUtil_BeginBufferProcessing(&stream->bufferProcessor, /* measurement during priming. */ + &timeInfo, + cbflags); /* Pass underflow + priming flags. */ + if (stream->hostPortBuffIn.port) /* Does that provide client's call- */ + PaUtil_SetNoInput(&stream->bufferProcessor); /* back with silent inputbuffers? */ + + PaUtil_SetOutputFrameCount(&stream->bufferProcessor, 0); /* 0=take host buffer size. */ + PaUtil_SetInterleavedOutputChannels(&stream->bufferProcessor, 0, + stream->hostPortBuffOut.buffer, 0); + callbackResult = paContinue; /* Call the client's callback. */ + frames_to_prime -= PaUtil_EndBufferProcessing(&stream->bufferProcessor, &callbackResult); + if (callbackResult == paAbort) + { /* What should we do in other cases */ + stream->stopAbort = PA_SGI_REQ_ABORT_; /* where (callbackResult!=paContinue). */ + break; /* Don't even output the samples just returned (also skip following while). */ + } + else /* Write interleaved samples to SGI device. */ + alWriteFrames(stream->hostPortBuffOut.port, stream->hostPortBuffOut.buffer, + stream->framesPerHostCallback); } - padIN = Pa_GetInternalDevice(past->past_InputDeviceID); - if (!padIN) + } + else /* Prime with silence. */ { - ERR_RPT(("Pa_GetInternalDevice() for input failed.\n")); - result = paHostError; - goto done; + DBUG(("Prime with silence: %ld frames.\n", frames_to_prime)); + alZeroFrames(stream->hostPortBuffOut.port, frames_to_prime); } - if (ALgetparams(padIN->pad_ALdevice, &pvbuf[0], 4)) /* Although input and output will both be on */ - goto sgiError; /* the same AL-device, the AL-library might */ - if (pvbuf[1] != sr) /* contain more than AL_DEFAULT_DEVICE in */ - { /* Rate different from current harware-rate? the future. Therefore 2 seperate queries. */ - if (pvbuf[3] > 0) /* Means, there's other clients using AL-input-ports */ - { - ERR_RPT(("Sorry, not allowed to switch input-hardware to %ld Hz because \ -another process is currently using input at %ld Hz.\n", sr, pvbuf[1])); - result = paHostError; - goto done; - } - pvbuf[1] = sr; /* Then set input-rate. */ - if (ALsetparams(padIN->pad_ALdevice, &pvbuf[0], 2)) - goto sgiError; /* WHETHER THIS SAMPLERATE WAS REALLY PRESENT IN OUR ARRAY OF RATES, */ - } /* IS NOT CHECKED, AT LEAST NOT BY ME, WITHIN THIS FILE! Does PA do? */ - pahsc->pahsc_ALconfigIN = ALnewconfig(); /* Released at PaHost_CloseStream(). */ - if (pahsc->pahsc_ALconfigIN == (ALconfig)0) - goto sgiError; - if (ALsetsampfmt(pahsc->pahsc_ALconfigIN, AL_SAMPFMT_TWOSCOMP))/* Choose paInt16 as native i/o-format. */ - goto sgiError; - if (ALsetwidth (pahsc->pahsc_ALconfigIN, AL_SAMPLE_16)) /* Only meaningful when sample format for */ - goto sgiError; /* config is set to two's complement format. */ - /************************ Future versions might (dynamically) switch to 32-bit floats? ******* - if (ALsetsampfmt(pahsc_ALconfigIN, AL_SAMPFMT_FLOAT)) (Then also call another CallConvert-func.) - goto sgiError; - if (ALsetfloatmax (pahsc_ALconfigIN, 1.0)) Only meaningful when sample format for config - goto sgiError; is set to AL_SAMPFMT_FLOAT or AL_SAMPFMT_DOUBLE. */ - /*--------- Set internal AL queuesize (in samples, not in frames!) -------------------------------*/ - alq = (long)past->past_NumUserBuffers * past->past_FramesPerUserBuffer * past->past_NumInputChannels; - DBUG(("AL input queuesize = %ld samples.\n", alq)); - if (ALsetqueuesize(pahsc->pahsc_ALconfigIN, alq)) - goto sgiError; - if (ALsetchannels (pahsc->pahsc_ALconfigIN, (long)(past->past_NumInputChannels))) - goto sgiError; /* Returns 0 on success, -1 on failure. */ } - /*---------------------------------------------------- SET OUTPUT CONFIGURATION: ------------------------*/ - if (past->past_NumOutputChannels > 0) /* CARE: padOUT/IN may NOT be NULL if Channels <= 0! */ - { /* We use padOUT/IN later on, or at least 1 of both. */ - pahsc->pahsc_SamplesPerOutputHostBuffer = pahsc->pahsc_UserBuffersPerHostBuffer * - past->past_FramesPerUserBuffer * /* Needed by the */ - past->past_NumOutputChannels; /* audio-thread. */ - DBUG(("pahsc_SamplesPerOutputHostBuffer=%d\n", pahsc->pahsc_SamplesPerOutputHostBuffer)); - pahsc->pahsc_BytesPerOutputHostBuffer = pahsc->pahsc_SamplesPerOutputHostBuffer * sizeof(short); - pahsc->pahsc_OutputHostBuffer = (short*)PaHost_AllocateFastMemory(pahsc->pahsc_BytesPerOutputHostBuffer); - if (!pahsc->pahsc_OutputHostBuffer) + /*------------------------------------------------------ I/O: ---------------------------------*/ + while (!stream->stopAbort) /* Exit loop immediately when 'stop' or 'abort' are raised. */ + { + unsigned long framesProcessed; + stamp_t fn, t, fnd, td; /* Unsigned 64 bit. */ + + PaUtil_BeginCpuLoadMeasurement( &stream->cpuLoadMeasurer ); + /* IMPLEMENT ME: - handle buffer slips. */ + if (stream->hostPortBuffIn.port) + { + /* Get device sample frame number associated with next audio sample frame + we're going to read from this port. */ + alGetFrameNumber(stream->hostPortBuffIn.port, &fn); + /* Get some recent pair of (frame number, time) from the audio device to + which our port is connected. time is 'UST' which is given in nanoseconds + and shared with the other audio devices and with other media. */ + alGetFrameTime(stream->hostPortBuffIn.port, &fnd, &td); + /* Calculate UST associated with fn, the next sample frame we're going to read or + write. Because this is signed arithmetic, code works for both inputs and outputs. */ + t = td + (stamp_t) ((double)(fn - fnd) * nanosec_per_frame); + /* If port is not in underflow or overflow state, we can alReadFrames() or + alWriteFrames() here and know that t is the time associated with the first + sample frame of the buffer we read or write. */ + timeInfo.inputBufferAdcTime = ((PaTime)t) / 1000000000.0; + /* Read interleaved samples from AL port (I think it will block only the first time). */ + alReadFrames(stream->hostPortBuffIn.port, stream->hostPortBuffIn.buffer, + stream->framesPerHostCallback); + } + if (stream->hostPortBuffOut.port) { - ERR_RPT(("Fast memory allocation failed (out).\n")); - result = paInsufficientMemory; - goto done; + alGetFrameNumber(stream->hostPortBuffOut.port, &fn); + alGetFrameTime(stream->hostPortBuffOut.port, &fnd, &td); + t = td + (stamp_t) ((double)(fn - fnd) * nanosec_per_frame); + timeInfo.outputBufferDacTime = ((PaTime)t) / 1000000000.0; + } + dmGetUST((unsigned long long*)(&t)); /* Receive time in nanoseconds in t. */ + timeInfo.currentTime = ((PaTime)t) / 1000000000.0; + + /* If you need to byte swap or shift inputBuffer to convert it into a pa format, do it here. */ + PaUtil_BeginBufferProcessing(&stream->bufferProcessor, + &timeInfo, + 0 /* IMPLEMENT ME: pass underflow/overflow flags when necessary */); + + if (stream->hostPortBuffIn.port) /* Equivalent to (inputChannelCount > 0) */ + { /* We are sure about the amount to transfer (PaUtil_Set before alRead). */ + PaUtil_SetInputFrameCount(&stream->bufferProcessor, 0 /* 0 means take host buffer size */); + PaUtil_SetInterleavedInputChannels(&stream->bufferProcessor, + 0, /* first channel of inputBuffer is channel 0 */ + stream->hostPortBuffIn.buffer, + 0 ); /* 0 - use inputChannelCount passed to init buffer processor */ } - padOUT = Pa_GetInternalDevice(past->past_OutputDeviceID); - if (!padOUT) + if (stream->hostPortBuffOut.port) { - ERR_RPT(("Pa_GetInternalDevice() for output failed.\n")); - result = paHostError; - goto done; + PaUtil_SetOutputFrameCount(&stream->bufferProcessor, 0 /* 0 means take host buffer size */); + PaUtil_SetInterleavedOutputChannels(&stream->bufferProcessor, + 0, /* first channel of outputBuffer is channel 0 */ + stream->hostPortBuffOut.buffer, + 0 ); /* 0 - use outputChannelCount passed to init buffer processor */ } - if (ALgetparams(padOUT->pad_ALdevice,&pvbuf[4], 4)) - goto sgiError; - if (pvbuf[5] != sr) - { /* Output needed and rate different from current harware-rate. */ - if (pvbuf[7] > 0) /* Means, there's other clients using AL-output-ports */ + /* + 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; /* Whoops, lost this somewhere, back again in v 1.2.2.16! */ + 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) + { /* Once finished, call the finished callback. */ + DBUG(("SGI callbackResult = %d.\n", callbackResult)); + if (stream->streamRepresentation.streamFinishedCallback) + stream->streamRepresentation.streamFinishedCallback(stream->streamRepresentation.userData); + if (callbackResult == paAbort) { - ERR_RPT(("Sorry, not allowed to switch output-hardware to %ld Hz because \ -another process is currently using output at %ld Hz.\n", sr, pvbuf[5])); - result = paHostError; - goto done; /* Will free again the inputbuffer */ - } /* that was just created above. */ - pvbuf[5] = sr; /* Then set output-rate. */ - if (ALsetparams(padOUT->pad_ALdevice, &pvbuf[4], 2)) - goto sgiError; + stream->stopAbort = PA_SGI_REQ_ABORT_; + break; /* Don't play the last buffer returned. */ + } + else /* paComplete or some other non-zero value. */ + stream->stopAbort = PA_SGI_REQ_STOP_; } - pahsc->pahsc_ALconfigOUT = ALnewconfig(); /* Released at PaHost_CloseStream(). */ - if (pahsc->pahsc_ALconfigOUT == (ALconfig)0) - goto sgiError; - if (ALsetsampfmt(pahsc->pahsc_ALconfigOUT, AL_SAMPFMT_TWOSCOMP)) /* Choose paInt16 as native i/o-format. */ - goto sgiError; - if (ALsetwidth (pahsc->pahsc_ALconfigOUT, AL_SAMPLE_16)) /* Only meaningful when sample format for */ - goto sgiError; /* config is set to two's complement format. */ - /** Future versions might (dynamically) switch to 32-bit floats. **/ - alq = (long)past->past_NumUserBuffers * past->past_FramesPerUserBuffer * past->past_NumOutputChannels; - DBUG(("AL output queuesize = %ld samples.\n", alq)); - if (ALsetqueuesize(pahsc->pahsc_ALconfigOUT, alq)) - goto sgiError; - if (ALsetchannels (pahsc->pahsc_ALconfigOUT, (long)(past->past_NumOutputChannels))) - goto sgiError; + if (stream->hostPortBuffOut.port) /* Write interleaved samples to SGI device */ + alWriteFrames(stream->hostPortBuffOut.port, /* (like unix_oss, AFTER checking callback result). */ + stream->hostPortBuffOut.buffer, stream->framesPerHostCallback); } - /*----------------------------------------------- TEST DEVICE ID's: --------------------*/ - if ((past->past_OutputDeviceID != past->past_InputDeviceID) && /* Who SETS these devive-numbers? */ - (past->past_NumOutputChannels > 0) && (past->past_NumInputChannels > 0)) - { - ERR_RPT(("Cannot setup bidirectional stream between different devices.\n")); - result = paHostError; - goto done; + if (stream->hostPortBuffOut.port) /* Drain output buffer(s), as long as we don't see an 'abort' request. */ + { + while ((!(stream->stopAbort & PA_SGI_REQ_ABORT_)) && /* Assume _STOP_ is set (or meant). */ + (alGetFilled(stream->hostPortBuffOut.port) > 1)) /* In case of ABORT we quickly leave (again). */ + ; /* Don't provide any new (not even silent) samples, but let an underrun [almost] occur. */ } - goto done; /* (no errors occured) */ -sgiError: - result = translateSGIerror(); /* Translates SGI AL-code to PA-code and ERR_RPTs string. */ -done: - if (result != paNoError) - PaHost_CloseStream(past); /* Frees memory (only if really allocated!). */ - return result; + if (callbackResult != paContinue) + stream->state = PA_SGI_STREAM_FLAG_FINISHED_; + return NULL; } -/*-----------------------------------------------------*/ -PaError PaHost_StartOutput(internalPortAudioStream *past) + +/* + When CloseStream() is called, the multi-api layer ensures + that the stream has already been stopped or aborted. +*/ +static PaError CloseStream(PaStream* s) { - return paNoError; /* Hmm, not implemented yet? */ + PaError result = paNoError; + PaSGIStream* stream = (PaSGIStream*)s; + + DBUG(("SGI CloseStream() started.\n")); + streamCleanupAndClose(stream); /* Releases i/o buffers and closes AL ports. */ + PaUtil_TerminateBufferProcessor(&stream->bufferProcessor); + PaUtil_TerminateStreamRepresentation(&stream->streamRepresentation); + PaUtil_FreeMemory(stream); + return result; } -PaError PaHost_StartInput(internalPortAudioStream *past) + + +static PaError StartStream(PaStream *s) { - return paNoError; + PaError result = paNoError; + PaSGIStream* stream = (PaSGIStream*)s; + + DBUG(("StartStream() started.\n")); + PaUtil_ResetBufferProcessor(&stream->bufferProcessor); /* See pa_common/pa_process.h. */ + if (stream->bufferProcessor.streamCallback) + { /* only when callback is used */ + if (pthread_create(&stream->thread, + NULL, /* pthread_attr_t * attr */ + PaSGIpthread, /* Function to spawn. */ + (void*)stream)) /* Pass stream as arg. */ + { + PA_SGI_SET_LAST_IRIX_ERROR() /* Let's hope oserror() tells something useful. */ + result = paUnanticipatedHostError; + } + else + stream->state = PA_SGI_STREAM_FLAG_ACTIVE_; + } /* Set active before returning from this function. */ + else + stream->state = PA_SGI_STREAM_FLAG_ACTIVE_; /* Apparently, setting active for blocking i/o is */ + return result; /* necessary (for patest_write_sine for example). */ } -/*------------------------------------------------------------------------------*/ -PaError PaHost_StartEngine(internalPortAudioStream *past) + +static PaError StopStream( PaStream *s ) { - PaHostSoundControl *pahsc; - usptr_t *arena; - if (!past) /* Test argument. */ - { - ERR_RPT(("PaHost_StartEngine(NULL)!\n")); - return paBadStreamPtr; - } - pahsc = (PaHostSoundControl*)past->past_DeviceData; - if (!pahsc) - { - ERR_RPT(("PaHost_StartEngine(arg): arg->past_DeviceData = NULL!\n")); - return paHostError; - } - past->past_StopSoon = 0; /* Assume SGI ALport is already opened! */ - past->past_StopNow = 0; /* Why don't we check pahsc for NULL? */ - past->past_IsActive = 1; - - /* Although the pthread_create() function, as well as , may be */ - /* available in IRIX, use sproc() on SGI to create audio-background-thread. */ - /* (Linux/oss uses pthread_create() instead of __clone() because: */ - /* - pthread_create also works for other UNIX systems like Solaris, */ - /* - Java HotSpot VM crashes in pthread_setcanceltype() using __clone().) */ + PaError result = paNoError; + PaSGIStream* stream = (PaSGIStream*)s; - usconfig(CONF_ARENATYPE, US_SHAREDONLY); /* (From SGI-AL-examples, file */ - arena = usinit(tmpnam(0)); /* motifexample.c, function */ - SendSema = usnewpollsema(arena, 0); /* InitializeAudioProcess().) */ - RcvSema = usnewsema(arena, 1); /* 1= common mutual exclusion semaphore, where 1 and only 1 process - will be permitted through a semaphore at a time. Values > 1 - imply that up to val resources may be simultaneously used, but requests - for more than val resources cause the calling process to block until a - resource comes free (by a process holding a resource performing a - usvsema(). IS THIS usnewsema() TOO PLATFORM SPECIFIC? */ - prctl(PR_SETEXITSIG, 0); /* No not (void*)9, but 0, which doesn't kill the parent! */ - /* PR_SETEXITSIG controls whether all members of a share group will be - signaled if any one of them leaves the share group (either via exit() - or exec()). If 2nd arg, interpreted as an int is 0, then normal IRIX - process termination rules apply, namely that the parent is sent a - SIGCLD upon death of child, but no indication of death of parent is - given. If the second argument is a valid signal number then if any - member of a share group leaves the share group, a signal is - sent to ALL surviving members of the share group. */ - /* SPAWN AUDIO-CHILD: */ - pahsc->pahsc_threadPID = sproc(Pa_SgiAudioProcess, /* Returns process ID of */ - PR_SALL, /* new process, or -1. */ - (void*)past); /* Pass past as optional */ /* IS THIS SAFE, will past never */ - if (pahsc->pahsc_threadPID == -1) /* third void-ptr-arg. */ /* be moved around in memory???? */ + if (stream->bufferProcessor.streamCallback) /* Only for callback streams. */ { - ERR_RPT(("PaHost_StartEngine() failed to spawn audio-thread.\n")); - sPaHostError = oserror(); /* Pass native error-number to shared area. */ - return paHostError; /* But return the generic error-number. */ + stream->stopAbort = PA_SGI_REQ_STOP_; /* Signal and wait for the thread to drain outputs. */ + if (pthread_join(stream->thread, NULL)) /* When succesful, stream->state */ + { /* is still ACTIVE, or FINISHED. */ + PA_SGI_SET_LAST_IRIX_ERROR() + result = paUnanticipatedHostError; + } + else /* Transition from ACTIVE or FINISHED to STOPPED. */ + stream->state = PA_SGI_STREAM_FLAG_STOPPED_; + stream->stopAbort = PA_SGI_REQ_CONT_; /* For possible next start. */ } - return paNoError; /* Hmmm, errno may come from other threads in same group! */ -} /* ("man sproc" in IRIX6.2 to read about _SGI_MP_SOURCE.) */ +/* else + stream->state = PA_SGI_STREAM_FLAG_STOPPED_; Is this necessary for blocking i/o? */ + return result; +} + -/*------------------------------------------------------------------------------*/ -PaError PaHost_StopEngine(internalPortAudioStream *past, int abort) +static PaError AbortStream( PaStream *s ) { - int hres; - long timeOut; - PaError result = paNoError; - PaHostSoundControl *pahsc; - - DBUG(("PaHost_StopEngine() called.\n")); - if (!past) - return paBadStreamPtr; - pahsc = (PaHostSoundControl*)past->past_DeviceData; - /* Prevent from doing this twice!! */ - if ((!pahsc) || /* Some tests call this CLOSE twice!! */ - (!past->past_IsActive) || - past->past_StopSoon || past->past_StopNow) - return result; /* paNoError (already stopped, no err?). */ - past->past_StopSoon = 1; /* Tell background thread to stop generating */ - if (abort) /* more and to let current data play out. If */ - past->past_StopNow = 1; /* aborting, tell backgrnd thread to stop NOW! */ - /*---- USE SEMAPHORE LOCK TO COMMUNICATE: -----*/ - usvsema(SendSema); /* Increments count associated with SendSema. */ - /* Wait for the response. */ - uspsema(RcvSema); /* Decrements count of previously allocated */ - /* semaphore specified by RcvSema. */ - while (past->past_IsActive) /* REALLY WAIT. */ - { - /* DBUG(("wait 1 ms for audio-thread to stop.\n")); */ - Pa_Sleep(1); - } + PaError result = paNoError; + PaSGIStream *stream = (PaSGIStream*)s; -#if 0 /* We don't need to KILL(), just COMMUNICATE and be patient... */ - if (pahsc->pahsc_threadPID != -1) /* Did we really init it to -1 somewhere? */ + if (stream->bufferProcessor.streamCallback) /* Only for callback streams. */ { - DBUG(("PaHost_StopEngine() is about to kill(SIGKILL) audio-thread.\n")); - if (kill(pahsc->pahsc_threadPID, SIGKILL)) /* Or SIGTERM or SIGQUIT(core) */ - { /* Returns -1 in case of error. */ - result = paHostError; - sPaHostError = oserror(); /* Hmmm, other threads may also write here! */ - ERR_RPT(("PaHost_StopEngine() failed to kill audio-thread.\n")); + stream->stopAbort = PA_SGI_REQ_ABORT_; + if (pthread_join(stream->thread, NULL)) + { + PA_SGI_SET_LAST_IRIX_ERROR() + result = paUnanticipatedHostError; } - else - pahsc->pahsc_threadPID = -1; /* Notify that we've killed this thread. */ + else /* Transition from ACTIVE or FINISHED to STOPPED. */ + stream->state = PA_SGI_STREAM_FLAG_STOPPED_; + stream->stopAbort = PA_SGI_REQ_CONT_; /* For possible next start. */ } -#endif - past->past_IsActive = 0; /* Even when kill() failed and pahsc_threadPID still there??? */ +/* else + stream->state = PA_SGI_STREAM_FLAG_STOPPED_; Is this necessary for blocking i/o? */ return result; } -/*---------------------------------------------------------------*/ -PaError PaHost_StopOutput(internalPortAudioStream *past, int abort) -{ - return paNoError; /* Not implemented yet? */ + +static PaError IsStreamStopped( PaStream *s ) /* Not just the opposite of IsStreamActive(): */ +{ /* in the 'callback finished' state, it */ + /* returns zero instead of nonzero. */ + if (((PaSGIStream*)s)->state & PA_SGI_STREAM_FLAG_STOPPED_) + return 1; + return 0; } -PaError PaHost_StopInput(internalPortAudioStream *past, int abort ) + + +static PaError IsStreamActive( PaStream *s ) { - return paNoError; + if (((PaSGIStream*)s)->state & PA_SGI_STREAM_FLAG_ACTIVE_) + return 1; + return 0; } -/*******************************************************************/ -PaError PaHost_CloseStream(internalPortAudioStream *past) + +static PaTime GetStreamTime( PaStream *s ) { - PaHostSoundControl *pahsc; - PaError result = paNoError; + stamp_t t; - DBUG(("PaHost_CloseStream() called.\n")); - if (!past) - return paBadStreamPtr; - pahsc = (PaHostSoundControl *) past->past_DeviceData; - if (!pahsc) /* If pahsc not NULL, past_DeviceData will be freed, and set to NULL. */ - return result; /* This test prevents from freeing NULL-pointers. */ - - if (pahsc->pahsc_ALconfigIN) - { /* Release configuration structs, only if allocated. */ - ALfreeconfig(pahsc->pahsc_ALconfigIN); - pahsc->pahsc_ALconfigIN = NULL; - } - if (pahsc->pahsc_ALconfigOUT) - { - ALfreeconfig(pahsc->pahsc_ALconfigOUT); /* (Al-ports were already closed by audioProcess). */ - pahsc->pahsc_ALconfigOUT = NULL; - } - if (pahsc->pahsc_InputHostBuffer) - { - PaHost_FreeFastMemory(pahsc->pahsc_InputHostBuffer, pahsc->pahsc_BytesPerInputHostBuffer); - pahsc->pahsc_InputHostBuffer = NULL; - } - if (pahsc->pahsc_OutputHostBuffer) - { - PaHost_FreeFastMemory(pahsc->pahsc_OutputHostBuffer, pahsc->pahsc_BytesPerOutputHostBuffer); - pahsc->pahsc_OutputHostBuffer = NULL; - } - PaHost_FreeFastMemory(pahsc, sizeof(PaHostSoundControl)); - past->past_DeviceData = NULL; /* PaHost_OpenStream() allocated FAST MEM. */ - return result; + (void) s; /* Suppress unused argument warning. */ + dmGetUST((unsigned long long*)(&t)); /* Receive time in nanoseconds in t. */ + return (PaTime)t / 1000000000.0; } -/*------------------------------------------------------------------------*/ -/* Determine minimum number of buffers required for (SGI) host based on */ -/* minimum latency. Latency can be optionally set by user by setting an */ -/* environment variable. For example, to set my latency to 200 msec, I've */ -/* put this line in my '.cshrc' file: setenv PA_MIN_LATENCY_MSEC 200 */ -/* It always calls the 'PRINT' macro. */ -/* The minimum number that is returned is 2. */ -/* This number is directly proportional to the AL-queue sizes to set up. */ -/* It is one more than the number of user buffers per host buffer - in */ -/* case minimum is returned, or, twice the user buffers per host buffer. */ -/*------------------------------------------------------------------------*/ -int Pa_GetMinNumBuffers(int framesPerUserBuffer, double framesPerSecond) +static double GetStreamCpuLoad( PaStream* s ) { - int minBuffers, minLatencyMsec; - char *minLatencyText; - double actualLatency; - - minLatencyText = getenv(PA_LATENCY_ENV_NAME); /* Defined at top of file. */ - if (minLatencyText) - { - minLatencyMsec = atoi(minLatencyText); - if (minLatencyMsec < 10) - { /* 10 is the minimum. */ - minLatencyMsec = 10; - PRINT (("Environment variable 'PA_MIN_LATENCY_MSEC' below minimum of %d milliseconds.\n", - minLatencyMsec)); - } - else if (minLatencyMsec > 4000) - { /* 4000 is the maximum. */ - minLatencyMsec = 4000; - PRINT (("Environment variable 'PA_MIN_LATENCY_MSEC' above maximum of %d milliseconds.\n", - minLatencyMsec)); - } - else - PRINT (("Using environment variable 'PA_MIN_LATENCY_MSEC' (set to %d milliseconds).\n", - minLatencyMsec)); - } - else - { - minLatencyMsec = MIN_LATENCY_MSEC; /* Defined at top of this file. */ - PRINT (("Environment variable 'PA_MIN_LATENCY_MSEC' not found.\nUsing default of %d milliseconds\n", - minLatencyMsec)); - } - minBuffers = (int)((minLatencyMsec * framesPerSecond) / - (1000.0 * framesPerUserBuffer)); - if (minBuffers < 2) - minBuffers = 2; - actualLatency = 1000.0 * minBuffers * framesPerUserBuffer / framesPerSecond; - PRINT (("Actual AL latency set to %.2f milliseconds\n", actualLatency)); - return minBuffers; + PaSGIStream *stream = (PaSGIStream*)s; + + return PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer ); } -/*---------------------------------------------------------------------*/ -PaError PaHost_Term(void) /* Frees all of the linked audio-devices. */ -{ /* Called by Pa_Terminate() from pa_lib.c. */ - internalPortAudioDevice *pad = sDeviceList, - *nxt; - while (pad) + +/* + 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 ) +{ + PaSGIStream* stream = (PaSGIStream*)s; + int n; + +printf("stream->framesPerHostCallback=%ld.\n", stream->framesPerHostCallback); +fflush(stdout); + + while (frames) { - DBUG(("PaHost_Term: freeing %s\n", pad->pad_DeviceName)); - nxt = pad->pad_Next; - PaHost_FreeFastMemory(pad, sizeof(internalPortAudioDevice)); - pad = nxt; /* PaHost_Init allocated this FAST MEM.*/ + if (frames > stream->framesPerHostCallback) n = stream->framesPerHostCallback; + else n = frames; + /* Read interleaved samples from SGI device. */ + alReadFrames(stream->hostPortBuffIn.port, /* Port already opened by OpenStream(). */ + stream->hostPortBuffIn.buffer, n); /* Already allocated by OpenStream(). */ + /* alReadFrames() always returns 0. */ + PaUtil_SetInputFrameCount(&stream->bufferProcessor, 0); /* 0 means take host buffer size */ + PaUtil_SetInterleavedInputChannels(&stream->bufferProcessor, + 0, /* first channel of inputBuffer is channel 0 */ + stream->hostPortBuffIn.buffer, + 0 ); /* 0 means use inputChannelCount passed at init. */ + /* Copy samples from host input channels set up by the PaUtil_SetInterleavedInputChannels + to a user supplied buffer. */ +printf("frames=%ld, buffer=%ld\n", frames, (long)buffer); +fflush(stdout); + PaUtil_CopyInput(&stream->bufferProcessor, &buffer, n); + frames -= n; } - sDeviceList = (internalPortAudioDevice*)NULL; - return 0; /* Got rid of sNumDevices=0; */ +printf("DONE: frames=%ld, buffer=%ld\n", frames, (long)buffer); + return paNoError; } -/***********************************************************************/ -void Pa_Sleep( long msec ) /* Sleep requested number of milliseconds. */ -{ -#if 0 - struct timeval timeout; - timeout.tv_sec = msec / 1000; - timeout.tv_usec = (msec % 1000) * 1000; - select(0, NULL, NULL, NULL, &timeout); -#else - long usecs = msec * 1000; - usleep( usecs ); -#endif -} -/*---------------------------------------------------------------------------------------*/ -/* Allocate memory that can be accessed in real-time. This may need to be held in physi- */ -/* cal memory so that it is not paged to virtual memory. This call MUST be balanced with */ -/* a call to PaHost_FreeFastMemory(). */ -void *PaHost_AllocateFastMemory(long numBytes) +static PaError WriteStream( PaStream* s, + const void *buffer, + unsigned long frames ) { - void *addr = malloc(numBytes); /* mpin() reads into memory all pages over the given */ - if (addr) /* range and locks the pages into memory. A counter */ - { /* is incremented each time the page is locked. The */ - if (mpin(addr, numBytes)) /* superuser can lock as many pages as it wishes, */ - { /* others are limited to the configurable PLOCK_MA. */ - ERR_RPT(("PaHost_AllocateFastMemory() failed to mpin() memory.\n")); -#if 1 - free(addr); /* You MAY cut out these 2 lines to be less strict, */ - addr = NULL; /* you then only get the warning but PA goes on... */ -#endif /* Only problem then may be corresponding munpin() */ - } /* call at PaHost_FreeFastMemory(), below. */ - memset(addr, 0, numBytes); /* Locks established with mlock are not inherited by */ - } /* a child process after a fork. Furthermore, IRIX- */ - return addr; /* man-pages warn against mixing both mpin and mlock */ -} /* in 1 piece of code, so stick to mpin()/munpin() ! */ - - -/*---------------------------------------------------------------------------------------*/ -/* Free memory that could be accessed in real-time. This call MUST be balanced with a */ -/* call to PaHost_AllocateFastMemory(). */ -void PaHost_FreeFastMemory(void *addr, long numBytes) -{ - if (addr) + PaSGIStream* stream = (PaSGIStream*)s; + unsigned long n; + while (frames) { - if (munpin(addr, numBytes)) /* Will munpin() fail when it was never mpinned? */ - ERR_RPT(("WARNING: PaHost_FreeFastMemory() failed to munpin() memory.\n")); - free(addr); /* But go on, try to release it, just warn... */ + PaUtil_SetOutputFrameCount(&stream->bufferProcessor, 0); /* 0 means take host buffer size */ + PaUtil_SetInterleavedOutputChannels(&stream->bufferProcessor, + 0, /* first channel of inputBuffer is channel 0 */ + stream->hostPortBuffOut.buffer, + 0 ); /* 0 means use inputChannelCount passed at init. */ + /* Copy samples from user supplied buffer to host input channels set up by + PaUtil_SetInterleavedOutputChannels. Copies the minimum of the number of user frames + (specified by the frameCount parameter) and the number of host frames (specified in + a previous call to SetOutputFrameCount()). */ + n = PaUtil_CopyOutput(&stream->bufferProcessor, &buffer, frames); + /* Write interleaved samples to SGI device. */ + alWriteFrames(stream->hostPortBuffOut.port, stream->hostPortBuffOut.buffer, n); + frames -= n; /* alWriteFrames always returns 0. */ } + return paNoError; } -/*----------------------------------------------------------*/ -PaError PaHost_StreamActive( internalPortAudioStream *past ) + +static signed long GetStreamReadAvailable( PaStream* s ) { - PaHostSoundControl *pahsc; - if (past == NULL) - return paBadStreamPtr; - pahsc = (PaHostSoundControl *) past->past_DeviceData; - if (pahsc == NULL) - return paInternalError; - return (PaError)(past->past_IsActive != 0); + return (signed long)alGetFilled(((PaSGIStream*)s)->hostPortBuffIn.port); } -/*-------------------------------------------------------------------*/ -PaTimestamp Pa_StreamTime( PortAudioStream *stream ) + +static signed long GetStreamWriteAvailable( PaStream* s ) { - internalPortAudioStream *past = (internalPortAudioStream *) stream; -/* FIXME - return actual frames played, not frames generated. -** Need to query the output device somehow. -*/ - return past->past_FrameCount; + return (signed long)alGetFillable(((PaSGIStream*)s)->hostPortBuffOut.port); } + + +/* CVS reminder: + To download the 'v19-devel' branch from portaudio's CVS server for the first time, type: + cvs -d:pserver:anonymous@www.portaudio.com:/home/cvs checkout -r v19-devel portaudio + Then 'cd' to the 'portaudio' directory that should have been created. + To commit changes: + cvs -d:pserver:pieter@www.portaudio.com:/home/cvs login + cvs -d:pserver:pieter@www.portaudio.com:/home/cvs commit -m 'blabla.' -r v19-devel pa_sgi/pa_sgi.c + cvs -d:pserver:pieter@www.portaudio.com:/home/cvs logout + To see if someone else worked on something: + cvs -d:pserver:anonymous@www.portaudio.com:/home/cvs update -r v19-devel + To get an older revision of a certain file (without sticky business): + cvs -d:pserver:anonymous@www.portaudio.com:/home/cvs update -p -r 1.1.1.1.2.4 pa_tests/patest1.c >pa_tests/patest1.c-OLD + To see logs: + cvs -d:pserver:anonymous@www.portaudio.com:/home/cvs log pa_common/pa_skeleton.c +*/ diff --git a/pa_sgi/pthread-Makefile b/pa_sgi/pthread-Makefile deleted file mode 100644 index 527677a..0000000 --- a/pa_sgi/pthread-Makefile +++ /dev/null @@ -1,52 +0,0 @@ -# Make PortAudio for Silicon Graphics IRIX (6.2) -# Pieter suurmond, september 22, 2001. (v15 pa_sgi sub-version #0.18) - -# pthread, math (as with linux) and SGI audio library: -# SGI-books say -lpthread should be the last on the line. -LIBS = -lm -laudio -lpthread - -CDEFINES = -I../pa_common - -# Possible CFLAGS with MIPSpro compiler are: -32, -o32, -n32, -64, -# -mips1, -mips2, -mips3, -mips4, etc. Use -g, -g2, -g3 for debugging. -# And use for example -O2 or -O3 for better optimization: -CFLAGS = -O2 -PASRC = ../pa_common/pa_lib.c pa_sgi.c -PAINC = ../pa_common/portaudio.h - -# Tests that work (SGI Indy with R5000 @ 180MHz running IRIX 6.2). -#TESTC = $(PASRC) ../pa_tests/patest_record.c # OK -#TESTC = $(PASRC) ../pa_tests/patest_many.c # OK -#TESTC = $(PASRC) ../pa_tests/patest_latency.c # OK -#TESTC = $(PASRC) ../pa_tests/patest_longsine.c # OK but needs more than 4 buffers to do without glitches. -TESTC = $(PASRC) ../pa_tests/patest_saw.c # Seems OK (does it gracefully exit?). -#TESTC = $(PASRC) ../pa_tests/patest_wire.c # OK -#TESTC = $(PASRC) ../pa_tests/pa_devs.c # OK -#TESTC = $(PASRC) ../pa_tests/patest_sine.c # OK -#TESTC = $(PASRC) ../pa_tests/patest_sine_time.c # OK -#TESTC = $(PASRC) ../pa_tests/patest_sine8.c # OK -#TESTC = $(PASRC) ../pa_tests/patest_leftright.c # OK -#TESTC = $(PASRC) ../pa_tests/patest_pink.c # OK -#TESTC = $(PASRC) ../pa_tests/patest_clip.c # OK -#TESTC = $(PASRC) ../pa_tests/patest_stop.c # OK -#TESTC = $(PASRC) ../pa_tests/patest_dither.c # OK -#TESTC = $(PASRC) ../pa_tests/patest_sync.c # BEEPS and delta's, no crashes anymore. - -# Tests that do not yet work. -#TESTC = $(PASRC) ../pa_tests/paqa_devs.c # Heavy crash with core-dump after PaHost_OpenStream: opening 1 output channel(s) on AL default -#TESTC = $(PASRC) ../pa_tests/paqa_errs.c # Heavy crash with core-dump after PaHost_OpenStream: opening 2 output channel(s) on AL default -#TESTC = $(PASRC) ../pa_tests/pa_fuzz.c # THIS FUZZ CRASHED MY WHOLE IRIX SYSTEM after "ENTER"! :-( - # PROCESS IN ITSELF RUNS OK, WITH LARGER BUFFSIZES THOUGH. - # OH MAYBE IT WAS BECAUSE DEBUGGING WAS ON??? - # ANYWAY, I'M NOT GONNA RUN THAT AGAIN... WAY TOO DANGEROUS! -TESTH = $(PAINC) - -all: patest - -# "cc" for the MIPSpro compiler, may be changed to "gcc": -patest: $(TESTC) $(TESTH) Makefile - cc $(CFLAGS) $(TESTC) $(CDEFINES) $(LIBS) -o patest - -run: patest - ./patest - diff --git a/pa_sgi/pthread-pa_sgi.c b/pa_sgi/pthread-pa_sgi.c deleted file mode 100644 index e9ab273..0000000 --- a/pa_sgi/pthread-pa_sgi.c +++ /dev/null @@ -1,908 +0,0 @@ -/* - * PortAudio Portable Real-Time Audio Library - * Latest Version at: http://www.portaudio.com - * SGI IRIX implementation by Pieter Suurmond, september 22, 2001 (#0.18). - * - * Copyright (c) 1999-2001 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. - */ -/* -Modfication History: - 8/12/2001 - Pieter Suurmond - took the v15 pa_linux_oss.c file and started to adapt for IRIX 6.2. - 8/17/2001 - alpha release with IRIX sproc()-method, may sometimes let IRIX6.2 crash at closing audiostream. - 9/22/2001 - #0.18 pthread starts to work a bit: - BUT UNDER IRIX6.2, I DON'T GET IT TO WORK REALLY CORRECTLY, - this POSIX-attempt, - DON'T USE THIS FILE FOR RELIABLE OPERATION, IT IS HERE JUST - FOR DOCUMENTATION/ARCHIVE... OR FOR ANYONE WHO WANTS TO FIX...... -TODO: - - Test under IRIX 6.5. - - Dynamically switch to 32 bit float as native format when appropriate (let SGI do the conversion), - and maybe also the other natively supported formats? (might increase performance) - - Not sure whether CPU UTILIZATION MEASUREMENT (from OSS/linux) really works. Changed nothing yet, - seems ok, but I've not yet tested it thoroughly. (maybe utilization-code may be made _unix_common_ then?) - - The minimal number of buffers setting... I do not yet fully understand it.. I now just take *4. -REFERENCES: - - IRIX 6.2 man pages regarding SGI AL library. - - IRIS Digital MediaProgramming Guide (online books as well as man-pages come with IRIX 6.2 and - may not be publically available on the internet). -*/ - -#include /* Standard libraries. */ -#include - -#include "../pa_common/portaudio.h" /* Portaudio headers. */ -#include "../pa_common/pa_host.h" -#include "../pa_common/pa_trace.h" - -/* -#include -#include -#include Not needed -#include -#include -#include -#include Needed? -#include -#include sched_param struct and related functions - used in setting thread priorities. -#include Some POSIX constants such as _POSIX_THREAD_THREADS_MAX -*/ - -#include /* Pthreads are supported by IRIX 6.2 after */ - /* patches 1361, 1367, and 1429 are applied. */ - -#include /* fcntl.h needed for "O_RDONLY". */ -#include /* For usleep() and constants used when calling sysconf() */ - /* to query POSIX limits (see the sysconf(3) ref. page. */ - -#include /* SGI-specific audio library. */ - - -/*--------------------------------------------*/ -#define PRINT(x) { printf x; fflush(stdout); } -#define ERR_RPT(x) PRINT(x) -#define DBUG(x) PRINT(x) -#define DBUGX(x) /* PRINT(x) */ - -#define MAX_CHARS_DEVNAME (16) /* Was 32 in OSS (20 for AL but "in"/"out" is concat. */ -#define MAX_SAMPLE_RATES (8) /* Known from SGI AL there are 7 (was 10 in OSS v15). */ - -typedef struct internalPortAudioDevice /* IRIX specific device info: */ -{ - PaDeviceID /* NEW: */ pad_DeviceID; /* THIS "ID" IS NEW HERE (Pieter)! */ - long pad_ALdevice; /* SGI-number! */ - double pad_SampleRates[MAX_SAMPLE_RATES]; /* for pointing to from pad_Info */ - char pad_DeviceName[MAX_CHARS_DEVNAME+1]; /* +1 for \0, one more than OSS. */ - PaDeviceInfo pad_Info; /* pad_Info (v15) contains: */ - /* int structVersion; */ - /* const char* name; */ - /* int maxInputChannels, maxOutputChannels; */ - /* int numSampleRates; Num rates, or -1 if range supprtd. */ - /* const double* sampleRates; Array of supported sample rates, */ - /* PaSampleFormat nativeSampleFormats; or {min,max} if range supported. */ - struct internalPortAudioDevice* pad_Next; /* Singly linked list, (NULL=end). */ -} internalPortAudioDevice; - -typedef struct PaHostSoundControl /* Structure to contain all SGI IRIX specific data. */ -{ - ALport pahsc_ALportIN, /* IRIX-audio-library-datatype. ALports can only be */ - pahsc_ALportOUT; /* unidirectional, so we sometimes need 2 of them. */ - pthread_t pahsc_ThreadPID; - short *pahsc_NativeInputBuffer, /* Allocated here, in this file, if necessary. */ - *pahsc_NativeOutputBuffer; - unsigned int pahsc_BytesPerInputBuffer, /* Native buffer sizes in bytes, really needed here */ - pahsc_BytesPerOutputBuffer; /* to free FAST memory, if buffs were alloctd FAST. */ - unsigned int pahsc_SamplesPerInputBuffer, /* These amounts are needed again and again in the */ - pahsc_SamplesPerOutputBuffer; /* audio-thread (don't need to be kept globally). */ - struct itimerval pahsc_EntryTime, /* For measuring CPU utilization (same as linux). */ - pahsc_LastExitTime; - long pahsc_InsideCountSum, - pahsc_TotalCountSum; -} PaHostSoundControl; - -/*----------------------------- Shared Data ------------------------------------------------------*/ -static internalPortAudioDevice* sDeviceList = NULL; /* FIXME - put Mutex around this shared data. */ -static int sPaHostError = 0; /* Maybe more than one process writing errs!? */ - -long Pa_GetHostError(void) -{ - return (long)sPaHostError; -} - -/*----------------------------- BEGIN CPU UTILIZATION MEASUREMENT -----------------*/ -/* (copied from source pa_linux_oss/pa_linux_oss.c) */ -static void Pa_StartUsageCalculation( internalPortAudioStream *past ) -{ - struct itimerval itimer; - PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; - if( pahsc == NULL ) return; -/* Query system timer for usage analysis and to prevent overuse of CPU. */ - getitimer( ITIMER_REAL, &pahsc->pahsc_EntryTime ); -} - -static long SubtractTime_AminusB( struct itimerval *timeA, struct itimerval *timeB ) -{ - long secs = timeA->it_value.tv_sec - timeB->it_value.tv_sec; - long usecs = secs * 1000000; - usecs += (timeA->it_value.tv_usec - timeB->it_value.tv_usec); - return usecs; -} - -static void Pa_EndUsageCalculation( internalPortAudioStream *past ) -{ - struct itimerval currentTime; - long insideCount; - long totalCount; /* Measure CPU utilization during this callback. */ - -#define LOWPASS_COEFFICIENT_0 (0.95) -#define LOWPASS_COEFFICIENT_1 (0.99999 - LOWPASS_COEFFICIENT_0) - - PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; - if (pahsc == NULL) - return; - if (getitimer( ITIMER_REAL, ¤tTime ) == 0 ) - { - if (past->past_IfLastExitValid) - { - insideCount = SubtractTime_AminusB( &pahsc->pahsc_EntryTime, ¤tTime ); - pahsc->pahsc_InsideCountSum += insideCount; - totalCount = SubtractTime_AminusB( &pahsc->pahsc_LastExitTime, ¤tTime ); - pahsc->pahsc_TotalCountSum += totalCount; - /* DBUG(("insideCount = %d, totalCount = %d\n", insideCount, totalCount )); */ - /* Low pass filter the result because sometimes we get called several times in a row. */ - /* That can cause the TotalCount to be very low which can cause the usage to appear */ - /* unnaturally high. So we must filter numerator and denominator separately!!! */ - if (pahsc->pahsc_InsideCountSum > 0) - { - past->past_AverageInsideCount = ((LOWPASS_COEFFICIENT_0 * past->past_AverageInsideCount) + - (LOWPASS_COEFFICIENT_1 * pahsc->pahsc_InsideCountSum)); - past->past_AverageTotalCount = ((LOWPASS_COEFFICIENT_0 * past->past_AverageTotalCount) + - (LOWPASS_COEFFICIENT_1 * pahsc->pahsc_TotalCountSum)); - past->past_Usage = past->past_AverageInsideCount / past->past_AverageTotalCount; - pahsc->pahsc_InsideCountSum = 0; - pahsc->pahsc_TotalCountSum = 0; - } - } - past->past_IfLastExitValid = 1; - } - pahsc->pahsc_LastExitTime.it_value.tv_sec = 100; - pahsc->pahsc_LastExitTime.it_value.tv_usec = 0; - setitimer( ITIMER_REAL, &pahsc->pahsc_LastExitTime, NULL ); - past->past_IfLastExitValid = 1; -} /*----------- END OF CPU UTILIZATION CODE (from pa_linux_oss/pa_linux_oss.c v15)--------------------*/ - - -/*--------------------------------------------------------------------------------------*/ -PaError translateSGIerror(void) /* Calls oserror(), may be used after an SGI AL-library */ -{ /* call to report via ERR_RPT(), yields a PaError-num. */ - const char* a = "SGI AL "; /* (Not absolutely sure errno came from THIS thread! */ - switch(oserror()) /* Read IRIX man-pages about the _SGI_MP_SOURCE macro.) */ - { - case AL_BAD_OUT_OF_MEM: - ERR_RPT(("%sout of memory.\n", a)); - return paInsufficientMemory; /* Known PaError. */ - case AL_BAD_CONFIG: - ERR_RPT(("%sconfiguration invalid or NULL.\n", a)); - return paHostError; /* Generic PaError. */ - case AL_BAD_CHANNELS: - ERR_RPT(("%schannels not 1,2 or 4.\n", a)); - return paHostError; /* Generic PaError. */ - case AL_BAD_NO_PORTS: - ERR_RPT(("%sout of audio ports.\n", a)); - return paHostError; /* Generic PaError. */ - case AL_BAD_DEVICE: - ERR_RPT(("%swrong device number.\n", a)); - return paHostError; /* Generic PaError. */ - case AL_BAD_DEVICE_ACCESS: - ERR_RPT(("%swrong device access.\n", a)); - return paHostError; /* Generic PaError. */ - case AL_BAD_DIRECTION: - ERR_RPT(("%sinvalid direction.\n", a)); - return paHostError; /* Generic PaError. */ - case AL_BAD_SAMPFMT: - ERR_RPT(("%sdoesn't accept sampleformat.\n", a)); - return paHostError; /* Generic PaError. */ - case AL_BAD_FLOATMAX: - ERR_RPT(("%smax float value is zero.\n", a)); - return paHostError; /* Generic PaError. */ - case AL_BAD_WIDTH: - ERR_RPT(("%sunsupported samplewidth.\n", a)); - return paHostError; /* Generic PaError. */ - case AL_BAD_QSIZE: - ERR_RPT(("%sinvalid queue size.\n", a)); - return paHostError; /* Generic PaError. */ - case AL_BAD_PVBUFFER: - ERR_RPT(("%sPVbuffer null.\n", a)); - return paHostError; /* Generic PaError. */ - case AL_BAD_BUFFERLENGTH_NEG: - ERR_RPT(("%snegative bufferlength.\n", a)); - return paHostError; /* Generic PaError. */ - case AL_BAD_BUFFERLENGTH_ODD: - ERR_RPT(("%sodd bufferlength.\n", a)); - return paHostError; /* Generic PaError. */ - case AL_BAD_PARAM: - ERR_RPT(("%sparameter not valid for device.\n", a)); - return paHostError; /* Generic PaError. */ - default: - ERR_RPT(("%sunknown error.\n", a)); - return paHostError; /* Generic PaError. */ - } -} - -/*------------------------------------------------------------------------------------------*/ -/* Tries to set various rates and formats and fill in the device info structure. */ -static PaError Pa_sgiQueryDevice(long ALdev, /* (AL_DEFAULT_DEVICE) */ - PaDeviceID id, /* (DefaultI|ODeviceID()) */ - char* name, /* (for example "SGI AL") */ - internalPortAudioDevice* pad) /* Result written to pad. */ -{ - int format; - long min, max; /* To catch hardware characteristics. */ - ALseterrorhandler(0); /* 0 = turn off the default error handler. */ - /*--------------------------------------------------------------------------------------*/ - pad->pad_ALdevice = ALdev; /* Set the AL device number. */ - pad->pad_DeviceID = id; /* Set the PA device number. */ - if (strlen(name) > MAX_CHARS_DEVNAME) /* MAX_CHARS defined above. */ - { - ERR_RPT(("Pa_QueryDevice(): name too long (%s).\n", name)); - return paHostError; - } - strcpy(pad->pad_DeviceName, name); /* Write name-string. */ - pad->pad_Info.name = pad->pad_DeviceName; /* Set pointer,..hmmm. */ - /*--------------------------------- natively supported sample formats: -----------------*/ - pad->pad_Info.nativeSampleFormats = paInt16; /* Later also include paFloat32 | ..| etc. */ - /* Then also choose other CallConvertXX()! */ - /*--------------------------------- number of available i/o channels: ------------------*/ - if (ALgetminmax(ALdev, AL_INPUT_COUNT, &min, &max)) - return translateSGIerror(); - pad->pad_Info.maxInputChannels = max; - DBUG(("Pa_QueryDevice: maxInputChannels = %d\n", pad->pad_Info.maxInputChannels)) - if (ALgetminmax(ALdev, AL_OUTPUT_COUNT, &min, &max)) - return translateSGIerror(); - pad->pad_Info.maxOutputChannels = max; - DBUG(("Pa_QueryDevice: maxOutputChannels = %d\n", pad->pad_Info.maxOutputChannels)) - /*--------------------------------- supported samplerates: ----------------------*/ - pad->pad_Info.numSampleRates = 7; - pad->pad_Info.sampleRates = pad->pad_SampleRates; - pad->pad_SampleRates[0] = (double)AL_RATE_8000; /* long -> double. */ - pad->pad_SampleRates[1] = (double)AL_RATE_11025; - pad->pad_SampleRates[2] = (double)AL_RATE_16000; - pad->pad_SampleRates[3] = (double)AL_RATE_22050; - pad->pad_SampleRates[4] = (double)AL_RATE_32000; - pad->pad_SampleRates[5] = (double)AL_RATE_44100; - pad->pad_SampleRates[6] = (double)AL_RATE_48000; - if (ALgetminmax(ALdev, AL_INPUT_RATE, &min, &max)) /* Ask INPUT rate-max. */ - return translateSGIerror(); /* double -> long. */ - if (max != (long)(0.5 + pad->pad_SampleRates[6])) /* FP-compare not recommndd. */ - goto weird; - if (ALgetminmax(ALdev, AL_OUTPUT_RATE, &min, &max)) /* Ask OUTPUT rate-max. */ - return translateSGIerror(); - if (max != (long)(0.5 + pad->pad_SampleRates[6])) - { -weird: ERR_RPT(("Pa_sgiQueryDevice() did not confirm max samplerate (%ld)\n",max)); - return paHostError; /* Or make it a warning and just carry on... */ - } - /*-------------------------------------------------------------------------------*/ - return paNoError; -} - - -/*--------------------------------------------------------------------------------*/ -int Pa_CountDevices() /* Name of this function suggests it only counts and */ -{ /* is NOT destructive, it however resets whole PA ! */ - int numDevices = 0; /* Let 's not do that here. */ - internalPortAudioDevice* currentDevice = sDeviceList; /* COPY GLOBAL VAR. */ -#if 0 /* Remains from linux_oss v15: Pa_Initialize(), on */ - if (!currentDevice) /* its turn, calls PaHost_Init() via file pa_lib.c. */ - Pa_Initialize(); /* Isn't that a bit too 'rude'? Don't be too */ -#endif /* friendly to clients that forgot to initialize PA. */ - while (currentDevice) /* Slower but more elegant than the sNumDevices-way: */ - { - numDevices++; - currentDevice = currentDevice->pad_Next; - } - return numDevices; -} - -/*-------------------------------------------------------------------------------*/ -static internalPortAudioDevice *Pa_GetInternalDevice(PaDeviceID id) -{ - int numDevices = 0; - internalPortAudioDevice *res = (internalPortAudioDevice*)NULL; - internalPortAudioDevice *pad = sDeviceList; /* COPY GLOBAL VAR. */ - while (pad) /* pad may be NULL, that's ok, return 0. */ - { /* (Added ->pad_DeviceID field to the pad-struct, Pieter, 2001.) */ - if (pad->pad_DeviceID == id) /* This the device we were looking for? */ - res = pad; /* But keep on(!) counting so we don't */ - numDevices++; /* have to call Pa_CountDevices() later. */ - pad = pad->pad_Next; /* Advance to the next device or NULL. */ - } /* No assumptions about order of ID's in */ - if (!res) /* the list. */ - ERR_RPT(("Pa_GetInternalDevice() could not find specified ID (%d).\n",id)); - if ((id < 0) || (id >= numDevices)) - { - ERR_RPT(("Pa_GetInternalDevice() supplied with an illegal ID (%d).\n",id)); -#if 1 /* Be strict, even when found, */ - res = (internalPortAudioDevice*)NULL; /* do not accept illegal ID's. */ -#endif - } - return res; -} - -/*----------------------------------------------------------------------*/ -const PaDeviceInfo* Pa_GetDeviceInfo(PaDeviceID id) -{ - PaDeviceInfo* res = (PaDeviceInfo*)NULL; - internalPortAudioDevice* pad = Pa_GetInternalDevice(id); /* Call. */ - if (pad) - res = &pad->pad_Info; /* Not finding the specified ID is not */ - if (!res) /* the same as &pad->pad_Info == NULL. */ - ERR_RPT(("Pa_GetDeviceInfo() could not find it (ID=%d).\n", id)); - return res; /* So (maybe) a second/third ERR_RPT(). */ -} - -/*------------------------------------------------*/ -PaDeviceID Pa_GetDefaultInputDeviceID(void) -{ - return 0; /* 0 is the default device ID. */ -} -/*------------------------------------------------*/ -PaDeviceID Pa_GetDefaultOutputDeviceID(void) -{ - return 0; -} - -/*-------------------------------------------------------------------------------------------------*/ -/* Build linked a list with all the available audio devices on this SGI machine (only 1 for now). */ -PaError PaHost_Init(void) /* Called by Pa_Initialize() from pa_lib.c. */ -{ - internalPortAudioDevice* pad; - PaError r = paNoError; - int audioLibFileID; /* To test for the presence of audio. */ - - if (sDeviceList) /* Allow re-init, only warn, no error. */ - { - ERR_RPT(("Warning: PaHost_Init() did not really re-init PA.\n")); - return r; - } - /*------------- ADD THE SGI DEFAULT DEVICE TO THE LIST: ---------------------------------------*/ - audioLibFileID = open("/dev/hdsp/hdsp0master", O_RDONLY); /* Try to open Indigo style audio */ - if (audioLibFileID < 0) /* IO port. On failure, machine */ - { /* has no audio ability. */ - ERR_RPT(("PaHost_Init(): This machine has no (Indigo-style) audio abilities.\n")); - return paHostError; - } - close(audioLibFileID); /* Allocate fast mem to hold device info. */ - pad = PaHost_AllocateFastMemory(sizeof(internalPortAudioDevice)); - if (pad == NULL) - return paInsufficientMemory; - memset(pad, 0, sizeof(internalPortAudioDevice)); /* "pad->pad_Next = NULL" is more elegant. */ - r = Pa_sgiQueryDevice(AL_DEFAULT_DEVICE, /* Set AL device num (AL_DEFAULT_DEVICE). */ - Pa_GetDefaultOutputDeviceID(),/* Set PA device num (or InputDeviceID()). */ - "AL default", /* A suitable name. */ - pad); /* Write args and queried info into pad. */ - if (r != paNoError) - { - ERR_RPT(("Pa_QueryDevice for '%s' returned: %d\n", pad->pad_DeviceName, r)); - PaHost_FreeFastMemory(pad, sizeof(internalPortAudioDevice)); /* sDeviceList still NULL ! */ - } - else - sDeviceList = pad; /* First element in linked list. pad->pad_Next already NULL. */ - /*------------- QUERY AND ADD MORE POSSIBLE SGI DEVICES TO THE LINKED LIST: -------------------*/ - /*---------------------------------------------------------------------------------------------*/ - return r; -} - -/*---------------------------------------------------------------------------------------------------*/ -static PaError Pa_SgiAudioProcess(internalPortAudioStream *past) /* Spawned by PaHost_StartEngine(). */ -{ - PaError result = paNoError; - PaHostSoundControl *pahsc; - - if (!past) - return paBadStreamPtr; - pahsc = (PaHostSoundControl*)past->past_DeviceData; - if (!pahsc) - return paInternalError; - past->past_IsActive = 1; /* Wasn't this already done by the calling parent?! */ - DBUG(("entering thread.\n")); - - while (!past->past_StopSoon) /* OR-ing StopSoon and StopNow here gives problems! */ - { - /*---------------------------------------- INPUT: ------------------------------------*/ - if (pahsc->pahsc_NativeInputBuffer) /* Then pahsc_ALportIN should also be there! */ - { - while (ALgetfilled(pahsc->pahsc_ALportIN) < pahsc->pahsc_SamplesPerInputBuffer) - { - /* Trying sginap(1); and usleep(); here... things get blocked under IRIX6.2. */ - if (past->past_StopNow) /* Don't let ALreadsamps() block */ - goto done; - } - if (ALreadsamps(pahsc->pahsc_ALportIN, (void*)pahsc->pahsc_NativeInputBuffer, - pahsc->pahsc_SamplesPerInputBuffer)) /* Number of samples instead */ - { /* of number of frames. */ - ERR_RPT(("ALreadsamps() failed.\n")); - result = paInternalError; - goto done; - } - } - /*---------------------------------------------------- USER CALLBACK ROUTINE: ----------*/ - /* DBUG(("Calling Pa_CallConvertInt16()...\n")); */ - Pa_StartUsageCalculation(past); /* Convert 16 bit native data to */ - result = Pa_CallConvertInt16(past, /* user data and call user routine. */ - pahsc->pahsc_NativeInputBuffer, pahsc->pahsc_NativeOutputBuffer); - Pa_EndUsageCalculation(past); - if (result) - { - DBUG(("Pa_CallConvertInt16() returned %d, stopping...\n", result)); - goto done; /* This is apparently NOT an error! */ - } /* Just letting the userCallBack stop us. */ - /*---------------------------------------- OUTPUT: ------------------------------------*/ - if (pahsc->pahsc_NativeOutputBuffer) /* Then pahsc_ALportOUT should also be there! */ - { - while (ALgetfillable(pahsc->pahsc_ALportOUT) < pahsc->pahsc_SamplesPerOutputBuffer) - { - /* Trying sginap(1); and usleep(); here... things get blocked under IRIX6.2. */ - if (past->past_StopNow) /* Don't let ALwritesamps() block */ - goto done; - } - if (ALwritesamps(pahsc->pahsc_ALportOUT, (void*)pahsc->pahsc_NativeOutputBuffer, - pahsc->pahsc_SamplesPerOutputBuffer)) - { - ERR_RPT(("ALwritesamps() failed.\n")); - result = paInternalError; - goto done; - } - } - /*-------------------------------------------------------------------------------------*/ - } -done: - /* pahsc->pahsc_ThreadPID = -1; Hu? doesn't help!! (added by Pieter) */ - past->past_IsActive = 0; - DBUG(("leaving thread.\n")); - return result; -} - - -/*--------------------------------------------------------------------------------------*/ -PaError PaHost_OpenStream(internalPortAudioStream *past) -{ - PaError result = paNoError; - PaHostSoundControl *pahsc; - unsigned int minNumBuffers; - internalPortAudioDevice *padIN, *padOUT; /* For looking up native AL-numbers. */ - ALconfig sgiALconfig = NULL; /* IRIX-datatype. */ - long pvbuf[8]; /* To get/set hardware configs. */ - long sr, ALqsize; - DBUG(("PaHost_OpenStream() called.\n")); /* Alloc FASTMEM and init host data. */ - if (!past) - { - ERR_RPT(("Streampointer NULL!\n")); - result = paBadStreamPtr; goto done; - } - pahsc = (PaHostSoundControl*)PaHost_AllocateFastMemory(sizeof(PaHostSoundControl)); - if (pahsc == NULL) - { - ERR_RPT(("FAST Memory allocation failed.\n")); /* Pass trough some ERR_RPT-exit- */ - result = paInsufficientMemory; goto done; /* code (nothing will be freed). */ - } - memset(pahsc, 0, sizeof(PaHostSoundControl)); -/* pahsc->pahsc_threadPID = -1; Should pahsc_threadPID be inited to */ - past->past_DeviceData = (void*)pahsc; /* -1 instead of 0 ?? */ - /*--------------------------------------------------- Allocate native buffers: --------*/ - pahsc->pahsc_SamplesPerInputBuffer = past->past_FramesPerUserBuffer * /* Needed by the */ - past->past_NumInputChannels; /* audio-thread. */ - pahsc->pahsc_BytesPerInputBuffer = pahsc->pahsc_SamplesPerInputBuffer * sizeof(short); - if (past->past_NumInputChannels > 0) /* Assumes short = 16 bits! */ - { - pahsc->pahsc_NativeInputBuffer = (short*)PaHost_AllocateFastMemory(pahsc->pahsc_BytesPerInputBuffer); - if( pahsc->pahsc_NativeInputBuffer == NULL ) - { - ERR_RPT(("Fast memory allocation for input-buffer failed.\n")); - result = paInsufficientMemory; goto done; - } - } - pahsc->pahsc_SamplesPerOutputBuffer = past->past_FramesPerUserBuffer * /* Needed by the */ - past->past_NumOutputChannels; /* audio-thread. */ - pahsc->pahsc_BytesPerOutputBuffer = pahsc->pahsc_SamplesPerOutputBuffer * sizeof(short); - if (past->past_NumOutputChannels > 0) /* Assumes short = 16 bits! */ - { - pahsc->pahsc_NativeOutputBuffer = (short*)PaHost_AllocateFastMemory(pahsc->pahsc_BytesPerOutputBuffer); - if (pahsc->pahsc_NativeOutputBuffer == NULL) - { - ERR_RPT(("Fast memory allocation for output-buffer failed.\n")); - result = paInsufficientMemory; goto done; - } - } - /*------------------------------------------ Manipulate hardware if necessary and allowed: --*/ - ALseterrorhandler(0); /* 0 = turn off the default error handler. */ - pvbuf[0] = AL_INPUT_RATE; - pvbuf[2] = AL_INPUT_COUNT; - pvbuf[4] = AL_OUTPUT_RATE; /* TO FIX: rates may be logically, not always in Hz! */ - pvbuf[6] = AL_OUTPUT_COUNT; - sr = (long)(past->past_SampleRate + 0.5); /* Common for input and output :-) */ - if (past->past_NumInputChannels > 0) /* We need to lookup the corre- */ - { /* sponding native AL-number(s). */ - padIN = Pa_GetInternalDevice(past->past_InputDeviceID); - if (!padIN) - { - ERR_RPT(("Pa_GetInternalDevice() for input failed.\n")); - result = paHostError; goto done; - } - if (ALgetparams(padIN->pad_ALdevice, &pvbuf[0], 4)) /* Although input and output will both be on */ - goto sgiError; /* the same AL-device, the AL-library might */ - if (pvbuf[1] != sr) /* contain more than AL_DEFAULT_DEVICE in */ - { /* Rate different from current harware-rate? the future. Therefore 2 seperate queries. */ - if (pvbuf[3] > 0) /* Means, there's other clients using AL-input-ports */ - { - ERR_RPT(("Sorry, not allowed to switch input-hardware to %ld Hz because \ -another process is currently using input at %ld kHz.\n", sr, pvbuf[1])); - result = paHostError; goto done; - } - pvbuf[1] = sr; /* Then set input-rate. */ - if (ALsetparams(padIN->pad_ALdevice, &pvbuf[0], 2)) - goto sgiError; /* WHETHER THIS SAMPLERATE WAS REALLY PRESENT IN OUR ARRAY OF RATES, */ - } /* IS NOT CHECKED, AT LEAST NOT BY ME, WITHIN THIS FILE! Does PA do? */ - } - if (past->past_NumOutputChannels > 0) /* CARE: padOUT/IN may NOT be NULL if Channels <= 0! */ - { /* We use padOUT/IN later on, or at least 1 of both. */ - padOUT = Pa_GetInternalDevice(past->past_OutputDeviceID); - if (!padOUT) - { - ERR_RPT(("Pa_GetInternalDevice() for output failed.\n")); - result = paHostError; goto done; - } - if (ALgetparams(padOUT->pad_ALdevice,&pvbuf[4], 4)) - goto sgiError; - if ((past->past_NumOutputChannels > 0) && (pvbuf[5] != sr)) - { /* Output needed and rate different from current harware-rate. */ - if (pvbuf[7] > 0) /* Means, there's other clients using AL-output-ports */ - { - ERR_RPT(("Sorry, not allowed to switch output-hardware to %ld Hz because \ -another process is currently using output at %ld kHz.\n", sr, pvbuf[5])); - result = paHostError; goto done; /* Will free again the inputbuffer */ - } /* that was just created above. */ - pvbuf[5] = sr; /* Then set output-rate. */ - if (ALsetparams(padOUT->pad_ALdevice, &pvbuf[4], 2)) - goto sgiError; - } - } - /*------------------------------------------ Construct an audio-port-configuration ----------*/ - sgiALconfig = ALnewconfig(); /* Change the SGI-AL-default-settings. */ - if (sgiALconfig == (ALconfig)0) /* sgiALconfig is released here after use! */ - goto sgiError; /* See that sgiALconfig is NOT released! */ - if (ALsetsampfmt(sgiALconfig, AL_SAMPFMT_TWOSCOMP)) /* Choose paInt16 as native i/o-format. */ - goto sgiError; - if (ALsetwidth (sgiALconfig, AL_SAMPLE_16)) /* Only meaningful when sample format for */ - goto sgiError; /* config is set to two's complement format. */ - /************************ Future versions might (dynamically) switch to 32-bit floats? ******* - if (ALsetsampfmt(sgiALconfig, AL_SAMPFMT_FLOAT)) (Then also call another CallConvert-func.) - goto sgiError; - if (ALsetfloatmax (sgiALconfig, 1.0)) Only meaningful when sample format for config - goto sgiError; is set to AL_SAMPFMT_FLOAT or AL_SAMPFMT_DOUBLE. */ - /*---------- ?? --------------------*/ - /* DBUG(("PaHost_OpenStream: pahsc_MinFramesPerHostBuffer = %d\n", pahsc->pahsc_MinFramesPerHostBuffer )); */ - minNumBuffers = Pa_GetMinNumBuffers(past->past_FramesPerUserBuffer, past->past_SampleRate); - past->past_NumUserBuffers = (minNumBuffers > past->past_NumUserBuffers) ? - minNumBuffers : past->past_NumUserBuffers; - /*------------------------------------------------ Set internal AL queuesize (in samples) ----*/ - if (pahsc->pahsc_SamplesPerInputBuffer >= pahsc->pahsc_SamplesPerOutputBuffer) - ALqsize = (long)pahsc->pahsc_SamplesPerInputBuffer; - else /* Take the largest of the two amounts. */ - ALqsize = (long)pahsc->pahsc_SamplesPerOutputBuffer; - ALqsize *= 4; /* 4 times as large as amount per transfer! */ - if (ALsetqueuesize(sgiALconfig, ALqsize)) /* Or should we use past_NumUserBuffers here? */ - goto sgiError; /* Using 2 times may give glitches... */ - /* Have to work on ALsetqueuesize() above. */ - - /* Do ALsetchannels() later, apart per input and/or output. */ - /*----------------------------------------------- OPEN 1 OR 2 AL-DEVICES: --------------------*/ - if (past->past_OutputDeviceID == past->past_InputDeviceID) /* Who SETS these devive-numbers? */ - { - if ((past->past_NumOutputChannels > 0) && (past->past_NumInputChannels > 0)) - { - DBUG(("PaHost_OpenStream: opening both input and output channels.\n")); - /*------------------------- open output port: ----------------------------------*/ - if (ALsetchannels (sgiALconfig, (long)(past->past_NumOutputChannels))) - goto sgiError; /* Returns 0 on success, -1 on failure. */ - pahsc->pahsc_ALportOUT = ALopenport("PA sgi out", "w", sgiALconfig); - if (pahsc->pahsc_ALportOUT == (ALport)0) - goto sgiError; - /*------------------------- open input port: -----------------------------------*/ - if (ALsetchannels (sgiALconfig, (long)(past->past_NumInputChannels))) - goto sgiError; /* Returns 0 on success, -1 on failure. */ - pahsc->pahsc_ALportIN = ALopenport("PA sgi in", "r", sgiALconfig); - if (pahsc->pahsc_ALportIN == (ALport)0) - goto sgiError; /* For some reason the "patest_wire.c"-test crashes! */ - } /* Probably due to too small buffersizes?.... */ - else - { - ERR_RPT(("Cannot setup bidirectional stream between different devices.\n")); - result = paHostError; - goto done; - } - } - else /* (OutputDeviceID != InputDeviceID) */ - { - if (past->past_NumOutputChannels > 0) /* WRITE-ONLY: */ - { - /*------------------------- open output port: ----------------------------------*/ - DBUG(("PaHost_OpenStream: opening %d output channel(s) on %s.\n", - past->past_NumOutputChannels, padOUT->pad_DeviceName)); - if (ALsetchannels (sgiALconfig, (long)(past->past_NumOutputChannels))) - goto sgiError; /* Returns 0 on success, -1 on failure. */ - pahsc->pahsc_ALportOUT = ALopenport("PA sgi out", "w", sgiALconfig); - if (pahsc->pahsc_ALportOUT == (ALport)0) - goto sgiError; - } - if (past->past_NumInputChannels > 0) /* READ-ONLY: */ - { - /*------------------------- open input port: -----------------------------------*/ - DBUG(("PaHost_OpenStream: opening %d input channel(s) on %s.\n", - past->past_NumInputChannels, padIN->pad_DeviceName)); - if (ALsetchannels (sgiALconfig, (long)(past->past_NumInputChannels))) - goto sgiError; /* Returns 0 on success, -1 on failure. */ - pahsc->pahsc_ALportIN = ALopenport("PA sgi in", "r", sgiALconfig); - if (pahsc->pahsc_ALportIN == (ALport)0) - goto sgiError; - } - } - DBUG(("PaHost_OpenStream() succeeded.\n")); - goto done; /* (no errors occured) */ -sgiError: - result = translateSGIerror(); /* Translates SGI AL-code to PA-code and ERR_RPTs string. */ -done: - if (sgiALconfig) - ALfreeconfig(sgiALconfig); /* We don't need that struct anymore. */ - if (result != paNoError) - PaHost_CloseStream(past); /* Frees memory (only if really allocated!). */ - return result; -} - -/*-----------------------------------------------------*/ -PaError PaHost_StartOutput(internalPortAudioStream *past) -{ - return paNoError; /* Hmm, not implemented yet? */ -} -PaError PaHost_StartInput(internalPortAudioStream *past) -{ - return paNoError; -} - -/*------------------------------------------------------------------------------*/ -PaError PaHost_StartEngine(internalPortAudioStream *past) -{ - PaHostSoundControl *pahsc; - int hres; - PaError result = paNoError; - - if (!past) /* Test argument. */ - { - ERR_RPT(("PaHost_StartEngine(NULL)!\n")); - return paBadStreamPtr; - } - pahsc = (PaHostSoundControl*)past->past_DeviceData; - if (!pahsc) - { - ERR_RPT(("PaHost_StartEngine(arg): arg->past_DeviceData == NULL!\n")); - return paHostError; - } - past->past_StopSoon = 0; /* Assume SGI ALport is already opened! */ - past->past_StopNow = 0; - past->past_IsActive = 1; - DBUG(("PaHost_StartEngine() called.\n")); - /* Use pthread_create() instead of __clone() because: */ - /* - pthread_create also works for other UNIX systems like Solaris, */ - /* - Java HotSpot VM crashes in pthread_setcanceltype() when using __clone(). */ - hres = pthread_create(&(pahsc->pahsc_ThreadPID), /* SPAWN AUDIO-CHILD. */ - NULL, /* pthread_attr_t * attr */ - (void*)Pa_SgiAudioProcess, - past); - if (hres) - { - result = paHostError; - sPaHostError = hres; - ERR_RPT(("PaHost_StartEngine() failed to spawn audio-thread.\n")); - } - return result; -} - -/*------------------------------------------------------------------------------*/ -PaError PaHost_StopEngine(internalPortAudioStream *past, int abort) -{ - int hres; - PaError result = paNoError; - PaHostSoundControl *pahsc; - - DBUG(("PaHost_StopEngine() called.\n")); - if (!past) - return paBadStreamPtr; - pahsc = (PaHostSoundControl*)past->past_DeviceData; - if (pahsc == NULL) - return result; /* paNoError (already stopped, no err?). */ - past->past_StopSoon = 1; /* Tell background thread to stop generating */ - if (abort) /* more and to let current data play out. If */ - past->past_StopNow = 1; /* aborting, tell backgrnd thread to stop NOW! */ - if (pahsc->pahsc_ThreadPID != -1) /* Join thread to recover memory resources. */ - { - DBUG(("pthread_join() called.\n")); - hres = pthread_join(pahsc->pahsc_ThreadPID, NULL); - if (hres) - { - result = paHostError; - sPaHostError = hres; - ERR_RPT(("PaHost_StopEngine() failed pthread_join().\n")); - } - pahsc->pahsc_ThreadPID = -1; - } - past->past_IsActive = 0; - return result; -} - -/*---------------------------------------------------------------*/ -PaError PaHost_StopOutput(internalPortAudioStream *past, int abort) -{ - return paNoError; /* Not implemented yet? */ -} -PaError PaHost_StopInput(internalPortAudioStream *past, int abort ) -{ - return paNoError; -} - -/*******************************************************************/ -PaError PaHost_CloseStream(internalPortAudioStream *past) -{ - PaHostSoundControl *pahsc; - PaError result = paNoError; - - DBUG(("PaHost_CloseStream() called.\n")); - if (past == NULL) - return paBadStreamPtr; - pahsc = (PaHostSoundControl *) past->past_DeviceData; - if (pahsc == NULL) /* If pahsc not NULL, past_DeviceData will be freed, and set to NULL. */ - return result; /* This test prevents from freeing NULL-pointers. */ - - if (pahsc->pahsc_ALportIN) - { - if (ALcloseport(pahsc->pahsc_ALportIN)) - result = translateSGIerror(); /* Translates SGI AL-code to PA-code and ERR_RPTs string. */ - else /* But go on anyway... to release other stuff... */ - pahsc->pahsc_ALportIN = (ALport)0; - } - if (pahsc->pahsc_ALportOUT) - { - if (ALcloseport(pahsc->pahsc_ALportOUT)) - result = translateSGIerror(); - else - pahsc->pahsc_ALportOUT = (ALport)0; - } - if (pahsc->pahsc_NativeInputBuffer) - { - PaHost_FreeFastMemory(pahsc->pahsc_NativeInputBuffer, pahsc->pahsc_BytesPerInputBuffer); - pahsc->pahsc_NativeInputBuffer = NULL; - } - if (pahsc->pahsc_NativeOutputBuffer) - { - PaHost_FreeFastMemory(pahsc->pahsc_NativeOutputBuffer, pahsc->pahsc_BytesPerOutputBuffer); - pahsc->pahsc_NativeOutputBuffer = NULL; - } - PaHost_FreeFastMemory(pahsc, sizeof(PaHostSoundControl)); - past->past_DeviceData = NULL; /* PaHost_OpenStream() allocated FAST. */ - return result; -} - -/************************************************************************* -** 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") - -int Pa_GetMinNumBuffers( int framesPerBuffer, double sampleRate ) -{ - return 2; -} -/* Hmmm, the note above isn't appropriate for SGI I'm afraid... */ -/* Do we HAVE to do it this way under IRIX???.... */ -/*--------------------------------------------------------------*/ - - -/*---------------------------------------------------------------------*/ -PaError PaHost_Term(void) /* Frees all of the linked audio-devices. */ -{ /* Called by Pa_Terminate() from pa_lib.c. */ - internalPortAudioDevice *pad = sDeviceList, - *nxt; - while (pad) - { - DBUG(("PaHost_Term: freeing %s\n", pad->pad_DeviceName)); - nxt = pad->pad_Next; - PaHost_FreeFastMemory(pad, sizeof(internalPortAudioDevice)); - pad = nxt; /* PaHost_Init allocated this FAST MEM.*/ - } - sDeviceList = (internalPortAudioDevice*)NULL; - return 0; /* Got rid of sNumDevices=0; */ -} - -/***********************************************************************/ -void Pa_Sleep( long msec ) /* Sleep requested number of milliseconds. */ -{ -#if 0 - struct timeval timeout; - timeout.tv_sec = msec / 1000; - timeout.tv_usec = (msec % 1000) * 1000; - select(0, NULL, NULL, NULL, &timeout); -#else - long usecs = msec * 1000; - usleep( usecs ); -#endif -} - -/*---------------------------------------------------------------------------------------*/ -/* Allocate memory that can be accessed in real-time. This may need to be held in physi- */ -/* cal memory so that it is not paged to virtual memory. This call MUST be balanced with */ -/* a call to PaHost_FreeFastMemory(). */ -void *PaHost_AllocateFastMemory(long numBytes) -{ - void *addr = malloc(numBytes); - if (addr) - memset(addr, 0, numBytes); - return addr; -} - -/*---------------------------------------------------------------------------------------*/ -/* Free memory that could be accessed in real-time. This call MUST be balanced with a */ -/* call to PaHost_AllocateFastMemory(). */ -void PaHost_FreeFastMemory(void *addr, long numBytes) -{ - if (addr) - free(addr); -} - -/*----------------------------------------------------------*/ -PaError PaHost_StreamActive (internalPortAudioStream *past) -{ - PaHostSoundControl *pahsc; - if (past == NULL) - return paBadStreamPtr; - pahsc = (PaHostSoundControl *) past->past_DeviceData; - if (pahsc == NULL) - return paInternalError; - return (PaError)(past->past_IsActive != 0); -} - -/*-------------------------------------------------------------------*/ -PaTimestamp Pa_StreamTime( PortAudioStream *stream ) -{ - internalPortAudioStream *past = (internalPortAudioStream *) stream; -/* FIXME - return actual frames played, not frames generated. -** Need to query the output device somehow. -*/ - return past->past_FrameCount; -} diff --git a/pa_tests/README.txt b/pa_tests/README.txt new file mode 100644 index 0000000..f3a0b82 --- /dev/null +++ b/pa_tests/README.txt @@ -0,0 +1,60 @@ +This directory contains various programs to test PortAudio. The files +named patest_* are tests, the files named debug_* are just scratch +files that may or may not work. + +All following tests are up to date with the V19 API. They should all compile +(without any warnings on GCC 3.3). Note that this does not necissarily mean that +the tests pass, just that they compile. + + x- paqa_devs.c + x- paqa_errs.c (needs reviewing) + x- patest1.c + x- patest_buffer.c + x- patest_callbackstop.c + x- patest_clip.c (last test fails, dither doesn't currently force clip in V19) + x- patest_dither.c + x- patest_hang.c + x- patest_latency.c + x- patest_leftright.c + x- patest_longsine.c + x- patest_many.c + x- patest_maxsines.c + o- patest_mono.c + x- patest_multi_sine.c + x- patest_pink.c + x- patest_prime.c + x- patest_read_record.c + x- patest_record.c + x- patest_ringmix.c + x- patest_saw.c + x- patest_sine.c + x- patest_sine8.c + x- patest_sine_formats.c + x- patest_sine_time.c + x- patest_start_stop.c + x- patest_stop.c + x- patest_sync.c + x- patest_toomanysines.c + o- patest_two_rates.c + x- patest_underflow.c + x- patest_wire.c + x- patest_write_sine.c + x- pa_devs.c + x- pa_fuzz.c + x- pa_minlat.c + +The debug_ files are still in V18 format and may need some V19 adaption. +Feel free to fix them, most simply require adjusting to the new API. + +o- pa_tests/debug_convert.c +o- pa_tests/debug_dither_calc.c +o- pa_tests/debug_dual.c +o- pa_tests/debug_multi_in.c +o- pa_tests/debug_multi_out.c +o- pa_tests/debug_record.c +o- pa_tests/debug_record_reuse.c +o- pa_tests/debug_sine.c +o- pa_tests/debug_sine_amp.c +o- pa_tests/debug_sine_formats.c +o- pa_tests/debug_srate.c +o- pa_tests/debug_test1.c diff --git a/pa_tests/pa_devs.c b/pa_tests/pa_devs.c index 7ca2225..278e027 100644 --- a/pa_tests/pa_devs.c +++ b/pa_tests/pa_devs.c @@ -1,9 +1,12 @@ +/** @file pa_devs.c + @brief List available devices, including device information. + @author Phil Burk http://www.softsynth.com + + @note Define PA_NO_ASIO to compile this code on Windows without + ASIO support. +*/ /* * $Id$ - * pa_devs.c - * List available devices. - * - * Author: Phil Burk http://www.softsynth.com * * This program uses the PortAudio Portable Audio Library. * For more information see: http://www.portaudio.com @@ -36,59 +39,188 @@ #include #include #include "portaudio.h" + +#ifdef WIN32 +#ifndef PA_NO_ASIO +#include "pa_asio.h" +#endif +#endif + +/*******************************************************************/ +static void PrintSupportedStandardSampleRates( + const PaStreamParameters *inputParameters, + const PaStreamParameters *outputParameters ) +{ + static double standardSampleRates[] = { + 8000.0, 9600.0, 11025.0, 12000.0, 16000.0, 22050.0, 24000.0, 32000.0, + 44100.0, 48000.0, 88200.0, 96000.0, 192000.0, -1 /* negative terminated list */ + }; + int i, printCount; + PaError err; + + printCount = 0; + for( i=0; standardSampleRates[i] > 0; i++ ) + { + err = Pa_IsFormatSupported( inputParameters, outputParameters, standardSampleRates[i] ); + if( err == paFormatIsSupported ) + { + if( printCount == 0 ) + { + printf( "\t%8.2f", standardSampleRates[i] ); + printCount = 1; + } + else if( printCount == 4 ) + { + printf( ",\n\t%8.2f", standardSampleRates[i] ); + printCount = 1; + } + else + { + printf( ", %8.2f", standardSampleRates[i] ); + ++printCount; + } + } + } + if( !printCount ) + printf( "None\n" ); + else + printf( "\n" ); +} /*******************************************************************/ int main(void); int main(void) { - int i,j; - int numDevices; - const PaDeviceInfo *pdi; - PaError err; + int i, numDevices, defaultDisplayed; + const PaDeviceInfo *deviceInfo; + PaStreamParameters inputParameters, outputParameters; + PaError err; + + Pa_Initialize(); - numDevices = Pa_CountDevices(); + + printf( "PortAudio version number = %d\nPortAudio version text = '%s'\n", + Pa_GetVersion(), Pa_GetVersionText() ); + + + numDevices = Pa_GetDeviceCount(); if( numDevices < 0 ) { - printf("ERROR: Pa_CountDevices returned 0x%x\n", numDevices ); + printf( "ERROR: Pa_CountDevices returned 0x%x\n", numDevices ); err = numDevices; goto error; } - printf("Number of devices = %d\n", numDevices ); + + printf( "Number of devices = %d\n", numDevices ); for( i=0; iname ); - printf("Max Inputs = %d", pdi->maxInputChannels ); - printf(", Max Outputs = %d\n", pdi->maxOutputChannels ); - if( pdi->numSampleRates == -1 ) + deviceInfo = Pa_GetDeviceInfo( i ); + printf( "--------------------------------------- device #%d\n", i ); + + /* Mark global and API specific default devices */ + defaultDisplayed = 0; + if( i == Pa_GetDefaultInputDevice() ) { - printf("Sample Rate Range = %f to %f\n", pdi->sampleRates[0], pdi->sampleRates[1] ); + printf( "[ Default Input" ); + defaultDisplayed = 1; } - else + else if( i == Pa_GetHostApiInfo( deviceInfo->hostApi )->defaultInputDevice ) { - printf("Sample Rates ="); - for( j=0; jnumSampleRates; j++ ) - { - printf(" %8.2f,", pdi->sampleRates[j] ); - } - printf("\n"); + const PaHostApiInfo *hostInfo = Pa_GetHostApiInfo( deviceInfo->hostApi ); + printf( "[ Default %s Input", hostInfo->name ); + defaultDisplayed = 1; + } + + if( i == Pa_GetDefaultOutputDevice() ) + { + printf( (defaultDisplayed ? "," : "[") ); + printf( " Default Output" ); + defaultDisplayed = 1; + } + else if( i == Pa_GetHostApiInfo( deviceInfo->hostApi )->defaultOutputDevice ) + { + const PaHostApiInfo *hostInfo = Pa_GetHostApiInfo( deviceInfo->hostApi ); + printf( (defaultDisplayed ? "," : "[") ); + printf( " Default %s Output", hostInfo->name ); + defaultDisplayed = 1; + } + + if( defaultDisplayed ) + printf( " ]\n" ); + + /* print device info fields */ + printf( "Name = %s\n", deviceInfo->name ); + printf( "Host API = %s\n", Pa_GetHostApiInfo( deviceInfo->hostApi )->name ); + printf( "Max inputs = %d", deviceInfo->maxInputChannels ); + printf( ", Max outputs = %d\n", deviceInfo->maxOutputChannels ); + + printf( "Default low input latency = %8.3f\n", deviceInfo->defaultLowInputLatency ); + printf( "Default low output latency = %8.3f\n", deviceInfo->defaultLowOutputLatency ); + printf( "Default high input latency = %8.3f\n", deviceInfo->defaultHighInputLatency ); + printf( "Default high output latency = %8.3f\n", deviceInfo->defaultHighOutputLatency ); + +#ifdef WIN32 +#ifndef PA_NO_ASIO +/* ASIO specific latency information */ + if( Pa_GetHostApiInfo( deviceInfo->hostApi )->type == paASIO ){ + long minLatency, maxLatency, preferredLatency, granularity; + + err = PaAsio_GetAvailableLatencyValues( i, + &minLatency, &maxLatency, &preferredLatency, &granularity ); + + printf( "ASIO minimum buffer size = %ld\n", minLatency ); + printf( "ASIO maximum buffer size = %ld\n", maxLatency ); + printf( "ASIO preferred buffer size = %ld\n", preferredLatency ); + + if( granularity == -1 ) + printf( "ASIO buffer granularity = power of 2\n" ); + else + printf( "ASIO buffer granularity = %ld\n", granularity ); + } +#endif /* !PA_NO_ASIO */ +#endif /* WIN32 */ + + printf( "Default sample rate = %8.2f\n", deviceInfo->defaultSampleRate ); + + /* poll for standard sample rates */ + inputParameters.device = i; + inputParameters.channelCount = deviceInfo->maxInputChannels; + inputParameters.sampleFormat = paInt16; + inputParameters.suggestedLatency = 0; /* ignored by Pa_IsFormatSupported() */ + inputParameters.hostApiSpecificStreamInfo = NULL; + + outputParameters.device = i; + outputParameters.channelCount = deviceInfo->maxOutputChannels; + outputParameters.sampleFormat = paInt16; + outputParameters.suggestedLatency = 0; /* ignored by Pa_IsFormatSupported() */ + outputParameters.hostApiSpecificStreamInfo = NULL; + + if( inputParameters.channelCount > 0 ) + { + printf("Supported standard sample rates\n for half-duplex 16 bit %d channel input = \n", + inputParameters.channelCount ); + PrintSupportedStandardSampleRates( &inputParameters, NULL ); + } + + if( outputParameters.channelCount > 0 ) + { + printf("Supported standard sample rates\n for half-duplex 16 bit %d channel output = \n", + outputParameters.channelCount ); + PrintSupportedStandardSampleRates( NULL, &outputParameters ); + } + + if( inputParameters.channelCount > 0 && outputParameters.channelCount > 0 ) + { + printf("Supported standard sample rates\n for full-duplex 16 bit %d channel input, %d channel output = \n", + inputParameters.channelCount, outputParameters.channelCount ); + PrintSupportedStandardSampleRates( &inputParameters, &outputParameters ); } - printf("Native Sample Formats = "); - if( pdi->nativeSampleFormats & paInt8 ) printf("paInt8, "); - if( pdi->nativeSampleFormats & paUInt8 ) printf("paUInt8, "); - if( pdi->nativeSampleFormats & paInt16 ) printf("paInt16, "); - if( pdi->nativeSampleFormats & paInt32 ) printf("paInt32, "); - if( pdi->nativeSampleFormats & paFloat32 ) printf("paFloat32, "); - if( pdi->nativeSampleFormats & paInt24 ) printf("paInt24, "); - if( pdi->nativeSampleFormats & paPackedInt24 ) printf("paPackedInt24, "); - printf("\n"); } + Pa_Terminate(); printf("----------------------------------------------\n"); return 0; + error: Pa_Terminate(); fprintf( stderr, "An error occured while using the portaudio stream\n" ); diff --git a/pa_tests/pa_fuzz.c b/pa_tests/pa_fuzz.c index 3161c74..127c2e3 100644 --- a/pa_tests/pa_fuzz.c +++ b/pa_tests/pa_fuzz.c @@ -1,9 +1,9 @@ +/** @file pa_fuzz.c + @brief Distort input like a fuzz boz. + @author Phil Burk http://www.softsynth.com +*/ /* * $Id$ - * pa_fuzz.c - * Distort input like a fuzz boz. - * - * Author: Phil Burk http://www.softsynth.com * * This program uses the PortAudio Portable Audio Library. * For more information see: http://www.portaudio.com @@ -48,9 +48,11 @@ typedef float SAMPLE; float CubicAmplifier( float input ); -static int fuzzCallback( void *inputBuffer, void *outputBuffer, +static int fuzzCallback( const void *inputBuffer, void *outputBuffer, unsigned long framesPerBuffer, - PaTimestamp outTime, void *userData ); + const PaStreamCallbackTimeInfo* timeInfo, + PaStreamCallbackFlags statusFlags, + void *userData ); /* Non-linear amplifier with soft distortion curve. */ float CubicAmplifier( float input ) @@ -76,14 +78,17 @@ static int gNumNoInputs = 0; ** It may be called at interrupt level on some machines so don't do anything ** that could mess up the system like calling malloc() or free(). */ -static int fuzzCallback( void *inputBuffer, void *outputBuffer, +static int fuzzCallback( const void *inputBuffer, void *outputBuffer, unsigned long framesPerBuffer, - PaTimestamp outTime, void *userData ) + const PaStreamCallbackTimeInfo* timeInfo, + PaStreamCallbackFlags statusFlags, + void *userData ) { SAMPLE *out = (SAMPLE*)outputBuffer; - SAMPLE *in = (SAMPLE*)inputBuffer; + const SAMPLE *in = (const SAMPLE*)inputBuffer; unsigned int i; - (void) outTime; /* Prevent unused variable warnings. */ + (void) timeInfo; /* Prevent unused variable warnings. */ + (void) statusFlags; (void) userData; if( inputBuffer == NULL ) @@ -103,33 +108,41 @@ static int fuzzCallback( void *inputBuffer, void *outputBuffer, *out++ = *in++; /* right - clean */ } } - return 0; + + return paContinue; } /*******************************************************************/ int main(void); int main(void) { - PortAudioStream *stream; + PaStreamParameters inputParameters, outputParameters; + PaStream *stream; PaError err; err = Pa_Initialize(); if( err != paNoError ) goto error; + + inputParameters.device = Pa_GetDefaultInputDevice(); /* default input device */ + inputParameters.channelCount = 2; /* stereo input */ + inputParameters.sampleFormat = PA_SAMPLE_TYPE; + inputParameters.suggestedLatency = Pa_GetDeviceInfo( inputParameters.device )->defaultLowInputLatency; + inputParameters.hostApiSpecificStreamInfo = NULL; + + outputParameters.device = Pa_GetDefaultOutputDevice(); /* default output device */ + outputParameters.channelCount = 2; /* stereo output */ + outputParameters.sampleFormat = PA_SAMPLE_TYPE; + outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency; + outputParameters.hostApiSpecificStreamInfo = NULL; + err = Pa_OpenStream( &stream, - Pa_GetDefaultInputDeviceID(), /* default output device */ - 2, /* stereo input */ - PA_SAMPLE_TYPE, - NULL, - Pa_GetDefaultOutputDeviceID(), /* default output device */ - 2, /* stereo output */ - PA_SAMPLE_TYPE, - NULL, + &inputParameters, + &outputParameters, SAMPLE_RATE, FRAMES_PER_BUFFER, - 0, /* number of buffers, if zero then use default minimum */ - 0, // paClipOff, /* we won't output out of range samples so don't bother clipping them */ + 0, /* paClipOff, */ /* we won't output out of range samples so don't bother clipping them */ fuzzCallback, NULL ); if( err != paNoError ) goto error; diff --git a/pa_tests/pa_minlat.c b/pa_tests/pa_minlat.c index 90b20df..8400dfd 100644 --- a/pa_tests/pa_minlat.c +++ b/pa_tests/pa_minlat.c @@ -1,10 +1,10 @@ +/** @file pa_minlat.c + @brief Experiment with different numbers of buffers to determine the + minimum latency for a computer. + @author Phil Burk http://www.softsynth.com +*/ /* * $Id$ - * paminlat.c - * Experiment with different numbers of buffers to determine the - * minimum latency for a computer. - * - * Author: Phil Burk http://www.softsynth.com * * This program uses the PortAudio Portable Audio Library. * For more information see: http://www.portaudio.com @@ -34,9 +34,11 @@ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ + #include #include #include +#include #include "portaudio.h" #ifndef M_PI @@ -44,7 +46,7 @@ #endif #define TWOPI (M_PI * 2.0) -#define DEFAULT_BUFFER_SIZE (64) +#define DEFAULT_BUFFER_SIZE (32) typedef struct { @@ -54,9 +56,11 @@ typedef struct paTestData; /* Very simple synthesis routine to generate two sine waves. */ -static int paminlatCallback( void *inputBuffer, void *outputBuffer, +static int paminlatCallback( const void *inputBuffer, void *outputBuffer, unsigned long framesPerBuffer, - PaTimestamp outTime, void *userData ) + const PaStreamCallbackTimeInfo* timeInfo, + PaStreamCallbackFlags statusFlags, + void *userData ) { paTestData *data = (paTestData*)userData; float *out = (float*)outputBuffer; @@ -82,75 +86,85 @@ static int paminlatCallback( void *inputBuffer, void *outputBuffer, data->right_phase = right_phase; return 0; } -void main( int argc, char **argv ); -void main( int argc, char **argv ) + +int main( int argc, char **argv ); +int main( int argc, char **argv ) { - PortAudioStream *stream; + PaStreamParameters outputParameters; + PaStream *stream; PaError err; paTestData data; int go; - int numBuffers = 0; - int minBuffers = 0; + int outLatency = 0; + int minLatency = DEFAULT_BUFFER_SIZE * 2; int framesPerBuffer; double sampleRate = 44100.0; char str[256]; - printf("paminlat - Determine minimum latency for your computer.\n"); - printf(" usage: paminlat {framesPerBuffer}\n"); - printf(" for example: paminlat 256\n"); + + printf("pa_minlat - Determine minimum latency for your computer.\n"); + printf(" usage: pa_minlat {userBufferSize}\n"); + printf(" for example: pa_minlat 64\n"); printf("Adjust your stereo until you hear a smooth tone in each speaker.\n"); - printf("Then try to find the smallest number of buffers that still sounds smooth.\n"); + printf("Then try to find the smallest number of frames that still sounds smooth.\n"); printf("Note that the sound will stop momentarily when you change the number of buffers.\n"); + /* Get bufferSize from command line. */ framesPerBuffer = ( argc > 1 ) ? atol( argv[1] ) : DEFAULT_BUFFER_SIZE; printf("Frames per buffer = %d\n", framesPerBuffer ); data.left_phase = data.right_phase = 0.0; + err = Pa_Initialize(); if( err != paNoError ) goto error; - /* Ask PortAudio for the recommended minimum number of buffers. */ - numBuffers = minBuffers = Pa_GetMinNumBuffers( framesPerBuffer, sampleRate ); - printf("NumBuffers set to %d based on a call to Pa_GetMinNumBuffers()\n", numBuffers ); + + outLatency = sampleRate * 200.0 / 1000.0; /* 200 msec. */ + /* Try different numBuffers in a loop. */ go = 1; while( go ) { + outputParameters.device = Pa_GetDefaultOutputDevice(); /* Default output device. */ + outputParameters.channelCount = 2; /* Stereo output */ + outputParameters.sampleFormat = paFloat32; /* 32 bit floating point output. */ + outputParameters.suggestedLatency = (double)outLatency / sampleRate; /* In seconds. */ + outputParameters.hostApiSpecificStreamInfo = NULL; + + printf("Latency = %d frames = %6.1f msec.\n", outLatency, outputParameters.suggestedLatency * 1000.0 ); - printf("Latency = framesPerBuffer * numBuffers = %d * %d = %d frames = %d msecs.\n", - framesPerBuffer, numBuffers, framesPerBuffer*numBuffers, - (int)((1000 * framesPerBuffer * numBuffers) / sampleRate) ); err = Pa_OpenStream( &stream, - paNoDevice, - 0, /* no input */ - paFloat32, /* 32 bit floating point input */ - NULL, - Pa_GetDefaultOutputDeviceID(), /* default output device */ - 2, /* stereo output */ - paFloat32, /* 32 bit floating point output */ - NULL, + NULL, /* no input */ + &outputParameters, sampleRate, framesPerBuffer, - numBuffers, /* number of buffers */ paClipOff, /* we won't output out of range samples so don't bother clipping them */ paminlatCallback, &data ); if( err != paNoError ) goto error; if( stream == NULL ) goto error; + /* Start audio. */ err = Pa_StartStream( stream ); if( err != paNoError ) goto error; - /* Ask user for a new number of buffers. */ + + /* Ask user for a new nlatency. */ printf("\nMove windows around to see if the sound glitches.\n"); - printf("NumBuffers currently %d, enter new number, or 'q' to quit: ", numBuffers ); - gets( str ); + printf("Latency now %d, enter new number of frames, or 'q' to quit: ", outLatency ); + fgets( str, 256, stdin ); + { + /* Get rid of newline */ + size_t l = strlen( str ) - 1; + if( str[ l ] == '\n') + str[ l ] = '\0'; + } if( str[0] == 'q' ) go = 0; else { - numBuffers = atol( str ); - if( numBuffers < minBuffers ) + outLatency = atol( str ); + if( outLatency < minLatency ) { - printf( "numBuffers below minimum of %d! Set to minimum!!!\n", minBuffers ); - numBuffers = minBuffers; + printf( "Latency below minimum of %d! Set to minimum!!!\n", minLatency ); + outLatency = minLatency; } } /* Stop sound until ENTER hit. */ @@ -163,10 +177,11 @@ void main( int argc, char **argv ) printf("the minimum latency that worked.\n"); printf("PortAudio: Test finished.\n"); Pa_Terminate(); - return; + return 0; error: Pa_Terminate(); fprintf( stderr, "An error occured while using the portaudio stream\n" ); fprintf( stderr, "Error number: %d\n", err ); fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); + return 1; } diff --git a/pa_tests/paqa_devs.c b/pa_tests/paqa_devs.c index c81c99a..f52143c 100644 --- a/pa_tests/paqa_devs.c +++ b/pa_tests/paqa_devs.c @@ -1,11 +1,16 @@ +/** @file paqa_devs.c + @brief Self Testing Quality Assurance app for PortAudio + Try to open each device and run through all the + possible configurations. + + @author Phil Burk http://www.softsynth.com + + Pieter adapted to V19 API. Test now relies heavily on + Pa_IsFormatSupported(). Uses same 'standard' sample rates + as in test pa_devs.c. +*/ /* * $Id$ - * paqa_devs.c - * Self Testing Quality Assurance app for PortAudio - * Try to open each device and run through all the - * possible configurations. - * - * Author: Phil Burk http://www.softsynth.com * * This program uses the PortAudio Portable Audio Library. * For more information see: http://www.portaudio.com @@ -39,9 +44,11 @@ #include #include "portaudio.h" #include "pa_trace.h" + /****************************************** Definitions ***********/ #define MODE_INPUT (0) #define MODE_OUTPUT (1) + typedef struct PaQaData { unsigned long framesLeft; @@ -52,18 +59,23 @@ typedef struct PaQaData PaSampleFormat format; } PaQaData; + /****************************************** Prototypes ***********/ static void TestDevices( int mode ); -static void TestFormats( int mode, PaDeviceID deviceID, double sampleRate, +static void TestFormats( int mode, PaDeviceIndex deviceID, double sampleRate, int numChannels ); -static int TestAdvance( int mode, PaDeviceID deviceID, double sampleRate, +static int TestAdvance( int mode, PaDeviceIndex deviceID, double sampleRate, int numChannels, PaSampleFormat format ); -static int QaCallback( void *inputBuffer, void *outputBuffer, +static int QaCallback( const void *inputBuffer, void *outputBuffer, unsigned long framesPerBuffer, - PaTimestamp outTime, void *userData ); + const PaStreamCallbackTimeInfo* timeInfo, + PaStreamCallbackFlags statusFlags, + void *userData ); + /****************************************** Globals ***********/ static int gNumPassed = 0; static int gNumFailed = 0; + /****************************************** Macros ***********/ /* Print ERROR if it fails. Tally success or failure. */ /* Odd do-while wrapper seems to be needed for some compilers. */ @@ -82,20 +94,22 @@ static int gNumFailed = 0; goto error; \ } \ } while(0) + /*******************************************************************/ /* This routine will be called by the PortAudio engine when audio is needed. ** It may be called at interrupt level on some machines so don't do anything ** that could mess up the system like calling malloc() or free(). */ -static int QaCallback( void *inputBuffer, void *outputBuffer, +static int QaCallback( const void *inputBuffer, void *outputBuffer, unsigned long framesPerBuffer, - PaTimestamp outTime, void *userData ) + const PaStreamCallbackTimeInfo* timeInfo, + PaStreamCallbackFlags statusFlags, + void *userData ) { unsigned long i; short phase; PaQaData *data = (PaQaData *) userData; (void) inputBuffer; - (void) outTime; /* Play simle sawtooth wave. */ if( data->mode == MODE_OUTPUT ) @@ -163,17 +177,18 @@ static int QaCallback( void *inputBuffer, void *outputBuffer, /* Are we through yet? */ if( data->framesLeft > framesPerBuffer ) { - AddTraceMessage("QaCallback: running. framesLeft", data->framesLeft ); + PaUtil_AddTraceMessage("QaCallback: running. framesLeft", data->framesLeft ); data->framesLeft -= framesPerBuffer; return 0; } else { - AddTraceMessage("QaCallback: DONE! framesLeft", data->framesLeft ); + PaUtil_AddTraceMessage("QaCallback: DONE! framesLeft", data->framesLeft ); data->framesLeft = 0; return 1; } } + /*******************************************************************/ int main(void); int main(void) @@ -187,69 +202,60 @@ int main(void) error: Pa_Terminate(); printf("QA Report: %d passed, %d failed.\n", gNumPassed, gNumFailed ); + return 0; } + /******************************************************************* * Try each output device, through its full range of capabilities. */ static void TestDevices( int mode ) { - int id,jc,kr; + int id, jc, i; int maxChannels; const PaDeviceInfo *pdi; - int numDevices = Pa_CountDevices(); - /* Iterate through all devices. */ - for( id=0; idmaxInputChannels : pdi->maxOutputChannels; + maxChannels = (( mode == MODE_INPUT ) ? pdi->maxInputChannels : pdi->maxOutputChannels); + for( jc=1; jc<=maxChannels; jc++ ) { printf("Name = %s\n", pdi->name ); - /* Try each legal sample rate. */ - if( pdi->numSampleRates == -1 ) + /* Try each standard sample rate. */ + for( i=0; standardSampleRates[i] > 0; i++ ) { - double low, high; - low = pdi->sampleRates[0]; - high = pdi->sampleRates[1]; - if( low < 8000.0 ) low = 8000.0; - TestFormats( mode, id, low, jc ); -#define TESTSR(sr) {if(((sr)>=low) && ((sr)<=high)) TestFormats( mode, id, (sr), jc ); } - - TESTSR(11025.0); - TESTSR(22050.0); - TESTSR(44100.0); - TestFormats( mode, id, high, jc ); - } - else - { - for( kr=0; krnumSampleRates; kr++ ) - { - TestFormats( mode, id, pdi->sampleRates[kr], jc ); - } + TestFormats( mode, (PaDeviceIndex)id, standardSampleRates[i], jc ); } } } } + /*******************************************************************/ -static void TestFormats( int mode, PaDeviceID deviceID, double sampleRate, +static void TestFormats( int mode, PaDeviceIndex deviceID, double sampleRate, int numChannels ) { - TestAdvance( mode, deviceID, sampleRate, numChannels, paFloat32 ); /* */ - TestAdvance( mode, deviceID, sampleRate, numChannels, paInt16 ); /* */ - TestAdvance( mode, deviceID, sampleRate, numChannels, paInt32 ); /* */ + TestAdvance( mode, deviceID, sampleRate, numChannels, paFloat32 ); + TestAdvance( mode, deviceID, sampleRate, numChannels, paInt16 ); + TestAdvance( mode, deviceID, sampleRate, numChannels, paInt32 ); /* TestAdvance( mode, deviceID, sampleRate, numChannels, paInt24 ); */ } + /*******************************************************************/ -static int TestAdvance( int mode, PaDeviceID deviceID, double sampleRate, +static int TestAdvance( int mode, PaDeviceIndex deviceID, double sampleRate, int numChannels, PaSampleFormat format ) { - PortAudioStream *stream = NULL; - PaError result; + PaStreamParameters inputParameters, outputParameters, *ipp, *opp; + PaStream *stream = NULL; + PaError result = paNoError; PaQaData myData; -#define FRAMES_PER_BUFFER (64) - printf("------ TestAdvance: %s, device = %d, rate = %g, numChannels = %d, format = %d -------\n", - ( mode == MODE_INPUT ) ? "INPUT" : "OUTPUT", - deviceID, sampleRate, numChannels, format); + #define FRAMES_PER_BUFFER (64) + /* Setup data for synthesis thread. */ myData.framesLeft = (unsigned long) (sampleRate * 100); /* 100 seconds */ myData.numChannels = numChannels; @@ -262,54 +268,78 @@ static int TestAdvance( int mode, PaDeviceID deviceID, double sampleRate, case paInt24: myData.bytesPerSample = 4; break; - case paPackedInt24: +/* case paPackedInt24: myData.bytesPerSample = 3; - break; + break; */ default: myData.bytesPerSample = 2; break; } - EXPECT( ((result = Pa_OpenStream( - &stream, - ( mode == MODE_INPUT ) ? deviceID : paNoDevice, - ( mode == MODE_INPUT ) ? numChannels : 0, - format, - NULL, - ( mode == MODE_OUTPUT ) ? deviceID : paNoDevice, - ( mode == MODE_OUTPUT ) ? numChannels : 0, - format, - NULL, - sampleRate, - FRAMES_PER_BUFFER, /* frames per buffer */ - 0, /* number of buffers, if zero then use default minimum */ - paClipOff, /* we won't output out of range samples so don't bother clipping them */ - QaCallback, - &myData ) - ) == 0) ); - if( stream ) + + if( mode == MODE_INPUT ) { - PaTimestamp oldStamp, newStamp; - unsigned long oldFrames; - int minDelay = ( mode == MODE_INPUT ) ? 1000 : 400; - int minNumBuffers = Pa_GetMinNumBuffers( FRAMES_PER_BUFFER, sampleRate ); - int msec = (int) ((minNumBuffers * 3 * 1000.0 * FRAMES_PER_BUFFER) / sampleRate); - if( msec < minDelay ) msec = minDelay; - printf("msec = %d\n", msec); /**/ - EXPECT( ((result=Pa_StartStream( stream )) == 0) ); - /* Check to make sure PortAudio is advancing timeStamp. */ - result = paNoError; - oldStamp = Pa_StreamTime(stream); - Pa_Sleep(msec); - newStamp = Pa_StreamTime(stream); - printf("oldStamp = %g,newStamp = %g\n", oldStamp, newStamp ); /**/ - EXPECT( (oldStamp < newStamp) ); - /* Check to make sure callback is decrementing framesLeft. */ - oldFrames = myData.framesLeft; - Pa_Sleep(msec); - printf("oldFrames = %d, myData.framesLeft = %d\n", oldFrames, myData.framesLeft ); /**/ - EXPECT( (oldFrames > myData.framesLeft) ); - EXPECT( ((result=Pa_CloseStream( stream )) == 0) ); - stream = NULL; + inputParameters.device = deviceID; + inputParameters.channelCount = numChannels; + inputParameters.sampleFormat = format; + inputParameters.suggestedLatency = Pa_GetDeviceInfo( inputParameters.device )->defaultLowInputLatency; + inputParameters.hostApiSpecificStreamInfo = NULL; + ipp = &inputParameters; + } + else + ipp = NULL; + if( mode == MODE_OUTPUT ) /* Pa_GetDeviceInfo(paNoDevice) COREDUMPS!!! */ + { + outputParameters.device = deviceID; + outputParameters.channelCount = numChannels; + outputParameters.sampleFormat = format; + outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency; + outputParameters.hostApiSpecificStreamInfo = NULL; + opp = &outputParameters; + } + else + opp = NULL; + + if(paFormatIsSupported == Pa_IsFormatSupported( ipp, opp, sampleRate )) + { + printf("------ TestAdvance: %s, device = %d, rate = %g, numChannels = %d, format = %lu -------\n", + ( mode == MODE_INPUT ) ? "INPUT" : "OUTPUT", + deviceID, sampleRate, numChannels, (unsigned long)format); + EXPECT( ((result = Pa_OpenStream( &stream, + ipp, + opp, + sampleRate, + FRAMES_PER_BUFFER, + paClipOff, /* we won't output out of range samples so don't bother clipping them */ + QaCallback, + &myData ) ) == 0) ); + if( stream ) + { + PaTime oldStamp, newStamp; + unsigned long oldFrames; + int minDelay = ( mode == MODE_INPUT ) ? 1000 : 400; + /* Was: + int minNumBuffers = Pa_GetMinNumBuffers( FRAMES_PER_BUFFER, sampleRate ); + int msec = (int) ((minNumBuffers * 3 * 1000.0 * FRAMES_PER_BUFFER) / sampleRate); + */ + int msec = (int)( 3.0 * + (( mode == MODE_INPUT ) ? inputParameters.suggestedLatency : outputParameters.suggestedLatency )); + if( msec < minDelay ) msec = minDelay; + printf("msec = %d\n", msec); /**/ + EXPECT( ((result=Pa_StartStream( stream )) == 0) ); + /* Check to make sure PortAudio is advancing timeStamp. */ + oldStamp = Pa_GetStreamTime(stream); + Pa_Sleep(msec); + newStamp = Pa_GetStreamTime(stream); + printf("oldStamp = %g,newStamp = %g\n", oldStamp, newStamp ); /**/ + EXPECT( (oldStamp < newStamp) ); + /* Check to make sure callback is decrementing framesLeft. */ + oldFrames = myData.framesLeft; + Pa_Sleep(msec); + printf("oldFrames = %lu, myData.framesLeft = %lu\n", oldFrames, myData.framesLeft ); /**/ + EXPECT( (oldFrames > myData.framesLeft) ); + EXPECT( ((result=Pa_CloseStream( stream )) == 0) ); + stream = NULL; + } } error: if( stream != NULL ) Pa_CloseStream( stream ); diff --git a/pa_tests/paqa_errs.c b/pa_tests/paqa_errs.c index e5ffc62..3f90771 100644 --- a/pa_tests/paqa_errs.c +++ b/pa_tests/paqa_errs.c @@ -1,10 +1,11 @@ +/** @file paqa_errs.c + @brief Self Testing Quality Assurance app for PortAudio + Do lots of bad things to test error reporting. + @author Phil Burk http://www.softsynth.com + Pieter Suurmond adapted to V19 API. +*/ /* * $Id$ - * paqa_devs.c - * Self Testing Quality Assurance app for PortAudio - * Do lots of bad things to test error reporting. - * - * Author: Phil Burk http://www.softsynth.com * * This program uses the PortAudio Portable Audio Library. * For more information see: http://www.portaudio.com @@ -34,15 +35,18 @@ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ + #include #include + #include "portaudio.h" -/****************************************** Definitions ***********/ -#define MODE_INPUT (0) -#define MODE_OUTPUT (1) -#define FRAMES_PER_BUFFER (64) -#define SAMPLE_RATE (44100.0) -#define NUM_BUFFERS (0) + +/*--------- Definitions ---------*/ +#define MODE_INPUT (0) +#define MODE_OUTPUT (1) +#define FRAMES_PER_BUFFER (64) +#define SAMPLE_RATE (44100.0) + typedef struct PaQaData { unsigned long framesLeft; @@ -51,21 +55,14 @@ typedef struct PaQaData int mode; } PaQaData; -/****************************************** Prototypes ***********/ -static void TestDevices( int mode ); -static void TestFormats( int mode, PaDeviceID deviceID, double sampleRate, - int numChannels ); -static int TestBadOpens( void ); -static int TestBadActions( void ); -static int QaCallback( void *inputBuffer, void *outputBuffer, - unsigned long framesPerBuffer, - PaTimestamp outTime, void *userData ); -/****************************************** Globals ***********/ -static int gNumPassed = 0; + +static int gNumPassed = 0; /* Two globals */ static int gNumFailed = 0; -/****************************************** Macros ***********/ -/* Print ERROR if it fails. Tally success or failure. */ -/* Odd do-while wrapper seems to be needed for some compilers. */ + +/*------------------- Macros ------------------------------*/ +/* Print ERROR if it fails. Tally success or failure. Odd */ +/* do-while wrapper seems to be needed for some compilers. */ + #define EXPECT(_exp) \ do \ { \ @@ -78,6 +75,7 @@ static int gNumFailed = 0; goto error; \ } \ } while(0) + #define HOPEFOR(_exp) \ do \ { \ @@ -89,20 +87,24 @@ static int gNumFailed = 0; gNumFailed++; \ } \ } while(0) -/*******************************************************************/ + +/*-------------------------------------------------------------------------*/ /* This routine will be called by the PortAudio engine when audio is needed. -** It may be called at interrupt level on some machines so don't do anything -** that could mess up the system like calling malloc() or free(). + It may be called at interrupt level on some machines so don't do anything + that could mess up the system like calling malloc() or free(). */ -static int QaCallback( void *inputBuffer, void *outputBuffer, - unsigned long framesPerBuffer, - PaTimestamp outTime, void *userData ) +static int QaCallback( const void* inputBuffer, + void* outputBuffer, + unsigned long framesPerBuffer, + const PaStreamCallbackTimeInfo* timeInfo, + PaStreamCallbackFlags statusFlags, + void* userData ) { - unsigned long i; - unsigned char *out = (unsigned char *) outputBuffer; - PaQaData *data = (PaQaData *) userData; - (void) inputBuffer; /* Prevent "unused variable" warnings. */ - (void) outTime; + unsigned long i; + unsigned char* out = (unsigned char *) outputBuffer; + PaQaData* data = (PaQaData *) userData; + + (void)inputBuffer; /* Prevent "unused variable" warnings. */ /* Zero out buffer so we don't hear terrible noise. */ if( data->mode == MODE_OUTPUT ) @@ -125,206 +127,254 @@ static int QaCallback( void *inputBuffer, void *outputBuffer, return 1; } } -/*******************************************************************/ -int main(void); -int main(void) + +static PaDeviceIndex FindInputOnlyDevice(void) { - PaError result; - EXPECT( ((result=Pa_Initialize()) == 0) ); - TestBadOpens(); - TestBadActions(); -error: - Pa_Terminate(); - printf("QA Report: %d passed, %d failed.\n", gNumPassed, gNumFailed ); - return 0; + PaDeviceIndex result = Pa_GetDefaultInputDevice(); + if( result != paNoDevice && Pa_GetDeviceInfo(result)->maxOutputChannels == 0 ) + return result; + + for( result = 0; result < Pa_GetDeviceCount(); ++result ) + { + if( Pa_GetDeviceInfo(result)->maxOutputChannels == 0 ) + return result; + } + + return paNoDevice; +} + +static PaDeviceIndex FindOutputOnlyDevice(void) +{ + PaDeviceIndex result = Pa_GetDefaultOutputDevice(); + if( result != paNoDevice && Pa_GetDeviceInfo(result)->maxInputChannels == 0 ) + return result; + + for( result = 0; result < Pa_GetDeviceCount(); ++result ) + { + if( Pa_GetDeviceInfo(result)->maxInputChannels == 0 ) + return result; + } + + return paNoDevice; } -/*******************************************************************/ + +/*-------------------------------------------------------------------------------------------------*/ static int TestBadOpens( void ) { - PortAudioStream *stream = NULL; - PaError result; - PaQaData myData; + PaStream* stream = NULL; + PaError result; + PaQaData myData; + PaStreamParameters ipp, opp; + /* Setup data for synthesis thread. */ myData.framesLeft = (unsigned long) (SAMPLE_RATE * 100); /* 100 seconds */ myData.numChannels = 1; myData.mode = MODE_OUTPUT; - HOPEFOR( (/* No devices specified. */ - (result = Pa_OpenStream( - &stream, - paNoDevice, 0, paFloat32, NULL, - paNoDevice, 0, paFloat32, NULL, - SAMPLE_RATE, FRAMES_PER_BUFFER, NUM_BUFFERS, - paClipOff, - QaCallback, - &myData ) - ) == paInvalidDeviceId) ); - HOPEFOR( ( /* Out of range input device specified. */ - (result = Pa_OpenStream( - &stream, - Pa_CountDevices(), 0, paFloat32, NULL, - paNoDevice, 0, paFloat32, NULL, - SAMPLE_RATE, FRAMES_PER_BUFFER, NUM_BUFFERS, - paClipOff, - QaCallback, - &myData ) - ) == paInvalidDeviceId) ); - - HOPEFOR( ( /* Out of range output device specified. */ - (result = Pa_OpenStream( - &stream, - paNoDevice, 0, paFloat32, NULL, - Pa_CountDevices(), 0, paFloat32, NULL, - SAMPLE_RATE, FRAMES_PER_BUFFER, NUM_BUFFERS, - paClipOff, - QaCallback, - &myData ) - ) == paInvalidDeviceId) ); - HOPEFOR( ( /* Zero input channels. */ - (result = Pa_OpenStream( - &stream, - Pa_GetDefaultInputDeviceID(), 0, paFloat32, NULL, - paNoDevice, 0, paFloat32, NULL, - SAMPLE_RATE, FRAMES_PER_BUFFER, NUM_BUFFERS, - paClipOff, - QaCallback, - &myData ) - ) == paInvalidChannelCount) ); - HOPEFOR( ( /* Zero output channels. */ - (result = Pa_OpenStream( - &stream, - paNoDevice, 0, paFloat32, NULL, - Pa_GetDefaultOutputDeviceID(), 0, paFloat32, NULL, - SAMPLE_RATE, FRAMES_PER_BUFFER, NUM_BUFFERS, - paClipOff, - QaCallback, - &myData ) - ) == paInvalidChannelCount) ); - HOPEFOR( ( /* Nonzero input channels but no device. */ - (result = Pa_OpenStream( - &stream, - Pa_GetDefaultInputDeviceID(), 2, paFloat32, NULL, - paNoDevice, 2, paFloat32, NULL, - SAMPLE_RATE, FRAMES_PER_BUFFER, NUM_BUFFERS, - paClipOff, - QaCallback, - &myData ) - ) == paInvalidChannelCount) ); - - HOPEFOR( ( /* Nonzero output channels but no device. */ - (result = Pa_OpenStream( - &stream, - paNoDevice, 2, paFloat32, NULL, - Pa_GetDefaultOutputDeviceID(), 2, paFloat32, NULL, - SAMPLE_RATE, FRAMES_PER_BUFFER, NUM_BUFFERS, - paClipOff, - QaCallback, - &myData ) - ) == paInvalidChannelCount) ); - HOPEFOR( ( /* NULL stream pointer. */ - (result = Pa_OpenStream( - NULL, - paNoDevice, 0, paFloat32, NULL, - Pa_GetDefaultOutputDeviceID(), 2, paFloat32, NULL, - SAMPLE_RATE, FRAMES_PER_BUFFER, NUM_BUFFERS, - paClipOff, - QaCallback, - &myData ) - ) == paBadStreamPtr) ); - HOPEFOR( ( /* Low sample rate. */ - (result = Pa_OpenStream( - &stream, - paNoDevice, 0, paFloat32, NULL, - Pa_GetDefaultOutputDeviceID(), 2, paFloat32, NULL, - 1.0, FRAMES_PER_BUFFER, NUM_BUFFERS, - paClipOff, - QaCallback, - &myData ) - ) == paInvalidSampleRate) ); - HOPEFOR( ( /* High sample rate. */ - (result = Pa_OpenStream( - &stream, - paNoDevice, 0, paFloat32, NULL, - Pa_GetDefaultOutputDeviceID(), 2, paFloat32, NULL, - 10000000.0, FRAMES_PER_BUFFER, NUM_BUFFERS, - paClipOff, - QaCallback, - &myData ) - ) == paInvalidSampleRate) ); - HOPEFOR( ( /* NULL callback. */ - (result = Pa_OpenStream( - &stream, - paNoDevice, 0, paFloat32, NULL, - Pa_GetDefaultOutputDeviceID(), 2, paFloat32, NULL, - SAMPLE_RATE, FRAMES_PER_BUFFER, NUM_BUFFERS, - paClipOff, - NULL, - &myData ) - ) == paNullCallback) ); - HOPEFOR( ( /* Bad flag. */ - (result = Pa_OpenStream( - &stream, - paNoDevice, 0, paFloat32, NULL, - Pa_GetDefaultOutputDeviceID(), 2, paFloat32, NULL, - SAMPLE_RATE, FRAMES_PER_BUFFER, NUM_BUFFERS, - (1<<3), - QaCallback, - &myData ) - ) == paInvalidFlag) ); - -#if 0 /* FIXME - this is legal for some implementations. */ - HOPEFOR( ( /* Use input device as output device. */ - (result = Pa_OpenStream( - &stream, - paNoDevice, 0, paFloat32, NULL, - Pa_GetDefaultInputDeviceID(), 2, paFloat32, NULL, - SAMPLE_RATE, FRAMES_PER_BUFFER, NUM_BUFFERS, - paClipOff, - QaCallback, - &myData ) - ) == paInvalidDeviceId) ); - - HOPEFOR( ( /* Use output device as input device. */ - (result = Pa_OpenStream( - &stream, - Pa_GetDefaultOutputDeviceID(), 2, paFloat32, NULL, - paNoDevice, 0, paFloat32, NULL, - SAMPLE_RATE, FRAMES_PER_BUFFER, NUM_BUFFERS, - paClipOff, - QaCallback, - &myData ) - ) == paInvalidDeviceId) ); -#endif + + /*----------------------------- No devices specified: */ + ipp.device = opp.device = paNoDevice; + ipp.channelCount = opp.channelCount = 0; /* Also no channels. */ + ipp.hostApiSpecificStreamInfo = opp.hostApiSpecificStreamInfo = NULL; + ipp.sampleFormat = opp.sampleFormat = paFloat32; + /* Take the low latency of the default device for all subsequent tests. */ + ipp.suggestedLatency = Pa_GetDeviceInfo(Pa_GetDefaultInputDevice())->defaultLowInputLatency; + opp.suggestedLatency = Pa_GetDeviceInfo(Pa_GetDefaultOutputDevice())->defaultLowOutputLatency; + HOPEFOR(((result = Pa_OpenStream(&stream, &ipp, &opp, + SAMPLE_RATE, FRAMES_PER_BUFFER, + paClipOff, QaCallback, &myData )) == paInvalidDevice)); + + /*----------------------------- No devices specified #2: */ + HOPEFOR(((result = Pa_OpenStream(&stream, NULL, NULL, + SAMPLE_RATE, FRAMES_PER_BUFFER, + paClipOff, QaCallback, &myData )) == paInvalidDevice)); + + /*----------------------------- Out of range input device specified: */ + ipp.hostApiSpecificStreamInfo = opp.hostApiSpecificStreamInfo = NULL; + ipp.sampleFormat = opp.sampleFormat = paFloat32; + ipp.channelCount = 0; ipp.device = Pa_GetDeviceCount(); /* And no output device, and no channels. */ + opp.channelCount = 0; opp.device = paNoDevice; + HOPEFOR(((result = Pa_OpenStream(&stream, &ipp, NULL, + SAMPLE_RATE, FRAMES_PER_BUFFER, + paClipOff, QaCallback, &myData )) == paInvalidDevice)); + + /*----------------------------- Out of range output device specified: */ + ipp.hostApiSpecificStreamInfo = opp.hostApiSpecificStreamInfo = NULL; + ipp.sampleFormat = opp.sampleFormat = paFloat32; + ipp.channelCount = 0; ipp.device = paNoDevice; /* And no input device, and no channels. */ + opp.channelCount = 0; opp.device = Pa_GetDeviceCount(); + HOPEFOR(((result = Pa_OpenStream(&stream, NULL, &opp, + SAMPLE_RATE, FRAMES_PER_BUFFER, + paClipOff, QaCallback, &myData )) == paInvalidDevice)); + + /*----------------------------- Zero input channels: */ + ipp.hostApiSpecificStreamInfo = opp.hostApiSpecificStreamInfo = NULL; + ipp.sampleFormat = opp.sampleFormat = paFloat32; + ipp.channelCount = 0; ipp.device = Pa_GetDefaultInputDevice(); + opp.channelCount = 0; opp.device = paNoDevice; /* And no output device, and no output channels. */ + HOPEFOR(((result = Pa_OpenStream(&stream, &ipp, NULL, + SAMPLE_RATE, FRAMES_PER_BUFFER, + paClipOff, QaCallback, &myData )) == paInvalidChannelCount)); + + /*----------------------------- Zero output channels: */ + ipp.hostApiSpecificStreamInfo = opp.hostApiSpecificStreamInfo = NULL; + ipp.sampleFormat = opp.sampleFormat = paFloat32; + ipp.channelCount = 0; ipp.device = paNoDevice; /* And no input device, and no input channels. */ + opp.channelCount = 0; opp.device = Pa_GetDefaultOutputDevice(); + HOPEFOR(((result = Pa_OpenStream(&stream, NULL, &opp, + SAMPLE_RATE, FRAMES_PER_BUFFER, + paClipOff, QaCallback, &myData )) == paInvalidChannelCount)); + + /*----------------------------- Nonzero input and output channels but no output device: */ + ipp.hostApiSpecificStreamInfo = opp.hostApiSpecificStreamInfo = NULL; + ipp.sampleFormat = opp.sampleFormat = paFloat32; + ipp.channelCount = 2; ipp.device = Pa_GetDefaultInputDevice(); /* Both stereo. */ + opp.channelCount = 2; opp.device = paNoDevice; + HOPEFOR(((result = Pa_OpenStream(&stream, &ipp, &opp, + SAMPLE_RATE, FRAMES_PER_BUFFER, + paClipOff, QaCallback, &myData )) == paInvalidDevice)); + + /*----------------------------- Nonzero input and output channels but no input device: */ + ipp.hostApiSpecificStreamInfo = opp.hostApiSpecificStreamInfo = NULL; + ipp.sampleFormat = opp.sampleFormat = paFloat32; + ipp.channelCount = 2; ipp.device = paNoDevice; + opp.channelCount = 2; opp.device = Pa_GetDefaultOutputDevice(); + HOPEFOR(((result = Pa_OpenStream(&stream, &ipp, &opp, + SAMPLE_RATE, FRAMES_PER_BUFFER, + paClipOff, QaCallback, &myData )) == paInvalidDevice)); + + /*----------------------------- NULL stream pointer: */ + ipp.hostApiSpecificStreamInfo = opp.hostApiSpecificStreamInfo = NULL; + ipp.sampleFormat = opp.sampleFormat = paFloat32; + ipp.channelCount = 0; ipp.device = paNoDevice; /* Output is more likely than input. */ + opp.channelCount = 2; opp.device = Pa_GetDefaultOutputDevice(); /* Only 2 output channels. */ + HOPEFOR(((result = Pa_OpenStream(NULL, &ipp, &opp, + SAMPLE_RATE, FRAMES_PER_BUFFER, + paClipOff, QaCallback, &myData )) == paBadStreamPtr)); + + /*----------------------------- Low sample rate: */ + ipp.hostApiSpecificStreamInfo = opp.hostApiSpecificStreamInfo = NULL; + ipp.sampleFormat = opp.sampleFormat = paFloat32; + ipp.channelCount = 0; ipp.device = paNoDevice; + opp.channelCount = 2; opp.device = Pa_GetDefaultOutputDevice(); + HOPEFOR(((result = Pa_OpenStream(&stream, NULL, &opp, + 1.0, FRAMES_PER_BUFFER, /* 1 cycle per second (1 Hz) is too low. */ + paClipOff, QaCallback, &myData )) == paInvalidSampleRate)); + + /*----------------------------- High sample rate: */ + ipp.hostApiSpecificStreamInfo = opp.hostApiSpecificStreamInfo = NULL; + ipp.sampleFormat = opp.sampleFormat = paFloat32; + ipp.channelCount = 0; ipp.device = paNoDevice; + opp.channelCount = 2; opp.device = Pa_GetDefaultOutputDevice(); + HOPEFOR(((result = Pa_OpenStream(&stream, NULL, &opp, + 10000000.0, FRAMES_PER_BUFFER, /* 10^6 cycles per second (10 MHz) is too high. */ + paClipOff, QaCallback, &myData )) == paInvalidSampleRate)); + + /*----------------------------- NULL callback: */ + /* NULL callback is valid in V19 -- it means use blocking read/write stream + + ipp.hostApiSpecificStreamInfo = opp.hostApiSpecificStreamInfo = NULL; + ipp.sampleFormat = opp.sampleFormat = paFloat32; + ipp.channelCount = 0; ipp.device = paNoDevice; + opp.channelCount = 2; opp.device = Pa_GetDefaultOutputDevice(); + HOPEFOR(((result = Pa_OpenStream(&stream, NULL, &opp, + SAMPLE_RATE, FRAMES_PER_BUFFER, + paClipOff, + NULL, + &myData )) == paNullCallback)); + */ + + /*----------------------------- Bad flag: */ + ipp.hostApiSpecificStreamInfo = opp.hostApiSpecificStreamInfo = NULL; + ipp.sampleFormat = opp.sampleFormat = paFloat32; + ipp.channelCount = 0; ipp.device = paNoDevice; + opp.channelCount = 2; opp.device = Pa_GetDefaultOutputDevice(); + HOPEFOR(((result = Pa_OpenStream(&stream, NULL, &opp, + SAMPLE_RATE, FRAMES_PER_BUFFER, + 255, /* Is 8 maybe legal V19 API? */ + QaCallback, &myData )) == paInvalidFlag)); + + /*----------------------------- using input device as output device: */ + if( FindInputOnlyDevice() != paNoDevice ) + { + ipp.hostApiSpecificStreamInfo = opp.hostApiSpecificStreamInfo = NULL; + ipp.sampleFormat = opp.sampleFormat = paFloat32; + ipp.channelCount = 0; ipp.device = paNoDevice; /* And no input device, and no channels. */ + opp.channelCount = 2; opp.device = FindInputOnlyDevice(); + HOPEFOR(((result = Pa_OpenStream(&stream, NULL, &opp, + SAMPLE_RATE, FRAMES_PER_BUFFER, + paClipOff, QaCallback, &myData )) == paInvalidChannelCount)); + } + + /*----------------------------- using output device as input device: */ + if( FindOutputOnlyDevice() != paNoDevice ) + { + ipp.hostApiSpecificStreamInfo = opp.hostApiSpecificStreamInfo = NULL; + ipp.sampleFormat = opp.sampleFormat = paFloat32; + ipp.channelCount = 2; ipp.device = FindOutputOnlyDevice(); + opp.channelCount = 0; opp.device = paNoDevice; /* And no output device, and no channels. */ + HOPEFOR(((result = Pa_OpenStream(&stream, &ipp, NULL, + SAMPLE_RATE, FRAMES_PER_BUFFER, + paClipOff, QaCallback, &myData )) == paInvalidChannelCount)); + + } if( stream != NULL ) Pa_CloseStream( stream ); return result; } -/*******************************************************************/ + +/*-----------------------------------------------------------------------------------------*/ static int TestBadActions( void ) { - PortAudioStream *stream = NULL; - PaError result; - PaQaData myData; + PaStream* stream = NULL; + PaError result; + PaQaData myData; + PaStreamParameters opp; + /* Setup data for synthesis thread. */ - myData.framesLeft = (unsigned long) (SAMPLE_RATE * 100); /* 100 seconds */ + myData.framesLeft = (unsigned long)(SAMPLE_RATE * 100); /* 100 seconds */ myData.numChannels = 1; myData.mode = MODE_OUTPUT; - /* Default output. */ - EXPECT( ((result = Pa_OpenStream( - &stream, - paNoDevice, 0, paFloat32, NULL, - Pa_GetDefaultOutputDeviceID(), 2, paFloat32, NULL, - SAMPLE_RATE, FRAMES_PER_BUFFER, NUM_BUFFERS, - paClipOff, - QaCallback, - &myData ) - ) == 0) ); - HOPEFOR( ((result = Pa_StartStream( NULL )) == paBadStreamPtr) ); - HOPEFOR( ((result = Pa_StopStream( NULL )) == paBadStreamPtr) ); - HOPEFOR( ((result = Pa_StreamActive( NULL )) == paBadStreamPtr) ); - HOPEFOR( ((result = Pa_CloseStream( NULL )) == paBadStreamPtr) ); - HOPEFOR( ((result = (PaError)Pa_StreamTime( NULL )) != 0) ); - HOPEFOR( ((result = (PaError)Pa_GetCPULoad( NULL )) != 0) ); -error: - if( stream != NULL ) Pa_CloseStream( stream ); + + opp.device = Pa_GetDefaultOutputDevice(); /* Default output. */ + opp.channelCount = 2; /* Stereo output. */ + opp.hostApiSpecificStreamInfo = NULL; + opp.sampleFormat = paFloat32; + opp.suggestedLatency = Pa_GetDeviceInfo(opp.device)->defaultLowOutputLatency; + + HOPEFOR(((result = Pa_OpenStream(&stream, NULL, /* Take NULL as input parame- */ + &opp, /* ters, meaning try only output. */ + SAMPLE_RATE, FRAMES_PER_BUFFER, + paClipOff, QaCallback, &myData )) == paNoError)); + + HOPEFOR(((result = Pa_StartStream(NULL)) == paBadStreamPtr)); + HOPEFOR(((result = Pa_StopStream(NULL)) == paBadStreamPtr)); + HOPEFOR(((result = Pa_IsStreamStopped(NULL)) == paBadStreamPtr)); + HOPEFOR(((result = Pa_IsStreamActive(NULL)) == paBadStreamPtr)); + HOPEFOR(((result = Pa_CloseStream(NULL)) == paBadStreamPtr)); + HOPEFOR(((result = Pa_SetStreamFinishedCallback(NULL, NULL)) == paBadStreamPtr)); + HOPEFOR(((result = !Pa_GetStreamInfo(NULL)))); + HOPEFOR(((result = Pa_GetStreamTime(NULL)) == 0.0)); + HOPEFOR(((result = Pa_GetStreamCpuLoad(NULL)) == 0.0)); + HOPEFOR(((result = Pa_ReadStream(NULL, NULL, 0)) == paBadStreamPtr)); + HOPEFOR(((result = Pa_WriteStream(NULL, NULL, 0)) == paBadStreamPtr)); + + /** @todo test Pa_GetStreamReadAvailable and Pa_GetStreamWriteAvailable */ + + if (stream != NULL) Pa_CloseStream(stream); return result; } + +/*---------------------------------------------------------------------*/ +int main(void); +int main(void) +{ + PaError result; + + EXPECT(((result = Pa_Initialize()) == paNoError)); + TestBadOpens(); + TestBadActions(); +error: + Pa_Terminate(); + printf("QA Report: %d passed, %d failed.\n", gNumPassed, gNumFailed); + return 0; +} diff --git a/pa_tests/patest1.c b/pa_tests/patest1.c index 5fddd51..15fdfdd 100644 --- a/pa_tests/patest1.c +++ b/pa_tests/patest1.c @@ -1,18 +1,48 @@ -/* - $Id$ - patest1.c - Ring modulate the audio input with a sine wave for 20 seconds - using the Portable Audio api - Author: Ross Bencina - Modifications: - April 5th, 2001 - PLB - Check for NULL inputBuffer. +/** @file patest1.c + @brief Ring modulate the audio input with a sine wave for 20 seconds. + @author Ross Bencina */ +/* + * $Id$ + * + * This program uses the PortAudio Portable Audio Library. + * For more information see: http://www.portaudio.com + * 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. + * + */ #include #include #include "portaudio.h" + #ifndef M_PI -#define M_PI (3.14159265) +#define M_PI (3.14159265) #endif + +#define SAMPLE_RATE (44100) + typedef struct { float sine[100]; @@ -20,95 +50,143 @@ typedef struct int sampsToGo; } patest1data; -static int patest1Callback( void *inputBuffer, void *outputBuffer, - unsigned long bufferFrames, - PaTimestamp outTime, void *userData ) + +static int patest1Callback( const void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + const PaStreamCallbackTimeInfo* timeInfo, + PaStreamCallbackFlags statusFlags, + void *userData ) { patest1data *data = (patest1data*)userData; float *in = (float*)inputBuffer; float *out = (float*)outputBuffer; - int framesToCalc = bufferFrames; - unsigned long i; - int finished = 0; - /* Check to see if any input data is available. */ - if(inputBuffer == NULL) return 0; - if( data->sampsToGo < bufferFrames ) + int framesToCalc = framesPerBuffer; + unsigned long i = 0; + int finished; + + if( data->sampsToGo < framesPerBuffer ) { framesToCalc = data->sampsToGo; - finished = 1; + finished = paComplete; } - for( i=0; isine[data->phase]; /* left */ *out++ = *in++ * data->sine[data->phase++]; /* right */ if( data->phase >= 100 ) data->phase = 0; } + data->sampsToGo -= framesToCalc; + /* zero remainder of final buffer if not already done */ - for( ; idefaultLowInputLatency; + inputParameters.hostApiSpecificStreamInfo = NULL; + + outputParameters.device = Pa_GetDefaultOutputDevice(); /* default output device */ + outputParameters.channelCount = 2; /* stereo output */ + outputParameters.sampleFormat = paFloat32; /* 32 bit floating point output */ + outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency; + outputParameters.hostApiSpecificStreamInfo = NULL; + err = Pa_OpenStream( - &stream, - inputDevice, - 2, /* stereo input */ - paFloat32, /* 32 bit floating point input */ - NULL, - outputDevice, - 2, /* stereo output */ - paFloat32, /* 32 bit floating point output */ - NULL, - 44100., - 512, /* small buffers */ - 0, /* let PA determine number of buffers */ - paClipOff, /* we won't output out of range samples so don't bother clipping them */ - patest1Callback, - &data ); - if( err == paNoError ) - { - err = Pa_StartStream( stream ); - printf( "Press any key to end.\n" ); - getc( stdin ); //wait for input before exiting - Pa_AbortStream( stream ); + &stream, + &inputParameters, + &outputParameters, + (double)SAMPLE_RATE, /* Samplerate in Hertz. */ + 512, /* Small buffers */ + paClipOff, /* We won't output out of range samples so don't bother clipping them. */ + patest1Callback, + &data ); + if( err != paNoError ) goto done; - printf( "Waiting for stream to complete...\n" ); + err = Pa_StartStream( stream ); + if( err != paNoError ) goto done; + + printf( "Press any key to end.\n" ); fflush(stdout); + + getc( stdin ); /* wait for input before exiting */ - while( Pa_StreamActive( stream ) ) - Pa_Sleep(1000); /* sleep until playback has finished */ + err = Pa_AbortStream( stream ); + if( err != paNoError ) goto done; + + printf( "Waiting for stream to complete...\n" ); - err = Pa_CloseStream( stream ); - } - else + /* sleep until playback has finished */ + while( ( err = Pa_IsStreamActive( stream ) ) == 1 ) Pa_Sleep(1000); + if( err < 0 ) goto done; + + err = Pa_CloseStream( stream ); + if( err != paNoError ) goto done; + +done: + Pa_Terminate(); + + if( err != paNoError ) { - fprintf( stderr, "An error occured while opening the portaudio stream\n" ); - if( err == paHostError ) - fprintf( stderr, "Host error number: %d\n", Pa_GetHostError() ); + fprintf( stderr, "An error occured while using portaudio\n" ); + if( err == paUnanticipatedHostError ) + { + fprintf( stderr, " unanticipated host error.\n"); + herr = Pa_GetLastHostErrorInfo(); + if (herr) + { + fprintf( stderr, " Error number: %ld\n", herr->errorCode ); + if (herr->errorText) + fprintf( stderr, " Error text: %s\n", herr->errorText ); + } + else + fprintf( stderr, " Pa_GetLastHostErrorInfo() failed!\n" ); + } else - fprintf( stderr, "Error number: %d\n", err ); + { + fprintf( stderr, " Error number: %d\n", err ); + fprintf( stderr, " Error text: %s\n", Pa_GetErrorText( err ) ); + } + + err = 1; /* Always return 0 or 1, but no other return codes. */ } - Pa_Terminate(); + printf( "bye\n" ); - return 0; + return err; } diff --git a/pa_tests/patest_buffer.c b/pa_tests/patest_buffer.c index 4963504..120c23f 100644 --- a/pa_tests/patest_buffer.c +++ b/pa_tests/patest_buffer.c @@ -1,9 +1,9 @@ +/** @file patest_buffer.c + @brief Test opening streams with different buffer sizes. + @author Phil Burk http://www.softsynth.com +*/ /* * $Id$ - * patest_buffer.c - * Test opening streams with different buffer sizes. - * - * Author: Phil Burk http://www.softsynth.com * * This program uses the PortAudio Portable Audio Library. * For more information see: http://www.portaudio.com @@ -37,15 +37,15 @@ #include #include #include "portaudio.h" -#define NUM_SECONDS (1) +#define NUM_SECONDS (3) #define SAMPLE_RATE (44100) #ifndef M_PI #define M_PI (3.14159265) #endif #define TABLE_SIZE (200) -#define BUFFER_TABLE 9 -long buffer_table[] = {200,256,500,512,600, 723, 1000, 1024, 2345}; +#define BUFFER_TABLE 14 +long buffer_table[] = {paFramesPerBufferUnspecified,16,32,64,128,200,256,500,512,600,723,1000,1024,2345}; typedef struct { @@ -55,25 +55,23 @@ typedef struct unsigned int sampsToGo; } paTestData; -PaError TestOnce( int buffersize ); +PaError TestOnce( int buffersize, PaDeviceIndex ); -static int patest1Callback( void *inputBuffer, void *outputBuffer, - unsigned long framesPerBuffer, - PaTimestamp outTime, void *userData ); /* This routine will be called by the PortAudio engine when audio is needed. ** It may called at interrupt level on some machines so don't do anything ** that could mess up the system like calling malloc() or free(). */ -static int patest1Callback( void *inputBuffer, void *outputBuffer, +static int patest1Callback( const void *inputBuffer, void *outputBuffer, unsigned long framesPerBuffer, - PaTimestamp outTime, void *userData ) + const PaStreamCallbackTimeInfo* timeInfo, + PaStreamCallbackFlags statusFlags, + void *userData ) { paTestData *data = (paTestData*)userData; short *out = (short*)outputBuffer; unsigned int i; int finished = 0; (void) inputBuffer; /* Prevent "unused variable" warnings. */ - (void) outTime; if( data->sampsToGo < framesPerBuffer ) { @@ -112,27 +110,37 @@ static int patest1Callback( void *inputBuffer, void *outputBuffer, } return finished; } + /*******************************************************************/ -int main(void); -int main(void) +int main(int argc, char **args); +int main(int argc, char **args) { int i; + int device = -1; PaError err; - printf("Test opening streams with different buffer sizes\n\n"); + printf("Test opening streams with different buffer sizes\n"); + if( argc > 1 ) { + device=atoi( args[1] ); + printf("Using device number %d.\n\n", device ); + } else { + printf("Using default device.\n\n" ); + } for (i = 0 ; i < BUFFER_TABLE; i++) { - printf("Buffer size %d\n", buffer_table[i]); - err = TestOnce(buffer_table[i]); + printf("Buffer size %ld\n", buffer_table[i]); + err = TestOnce(buffer_table[i], device); if( err < 0 ) return 0; } + return 0; } -PaError TestOnce( int buffersize ) +PaError TestOnce( int buffersize, PaDeviceIndex device ) { - PortAudioStream *stream; + PaStreamParameters outputParameters; + PaStream *stream; PaError err; paTestData data; int i; @@ -146,20 +154,22 @@ PaError TestOnce( int buffersize ) data.sampsToGo = totalSamps = NUM_SECONDS * SAMPLE_RATE; /* Play for a few seconds. */ err = Pa_Initialize(); if( err != paNoError ) goto error; + + if( device == -1 ) + outputParameters.device = Pa_GetDefaultOutputDevice(); /* default output device */ + else + outputParameters.device = device ; + outputParameters.channelCount = 2; /* stereo output */ + outputParameters.sampleFormat = paInt16; /* 32 bit floating point output */ + outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency; + outputParameters.hostApiSpecificStreamInfo = NULL; err = Pa_OpenStream( &stream, - paNoDevice,/* default input device */ - 0, /* no input */ - paInt16, /* sample format */ - NULL, - Pa_GetDefaultOutputDeviceID(), /* default output device */ - 2, /* stereo output */ - paInt16, /* sample format */ - NULL, + NULL, /* no input */ + &outputParameters, SAMPLE_RATE, - buffersize, /* frames per buffer */ - 0, /* number of buffers, if zero then use default minimum */ - paClipOff, /* we won't output out of range samples so don't bother clipping them */ + buffersize, /* frames per buffer */ + (paClipOff | paDitherOff), patest1Callback, &data ); if( err != paNoError ) goto error; @@ -167,7 +177,7 @@ PaError TestOnce( int buffersize ) err = Pa_StartStream( stream ); if( err != paNoError ) goto error; printf("Waiting for sound to finish.\n"); - Pa_Sleep(1000); + Pa_Sleep(1000*NUM_SECONDS); err = Pa_CloseStream( stream ); if( err != paNoError ) goto error; Pa_Terminate(); @@ -177,5 +187,6 @@ error: fprintf( stderr, "An error occured while using the portaudio stream\n" ); fprintf( stderr, "Error number: %d\n", err ); fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); + fprintf( stderr, "Host Error message: %s\n", Pa_GetLastHostErrorInfo()->errorText ); return err; } diff --git a/pa_tests/patest_callbackstop.c b/pa_tests/patest_callbackstop.c new file mode 100644 index 0000000..2da642e --- /dev/null +++ b/pa_tests/patest_callbackstop.c @@ -0,0 +1,221 @@ +/** @file patest_callbackstop.c + @brief Test the paComplete callback result code. + @author Ross Bencina +*/ +/* + * $Id$ + * + * This program uses the PortAudio Portable Audio Library. + * For more information see: http://www.portaudio.com/ + * 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. + * + */ +#include +#include +#include "portaudio.h" + +#define NUM_SECONDS (5) +#define NUM_LOOPS (4) +#define SAMPLE_RATE (44100) +#define FRAMES_PER_BUFFER (67) + +#ifndef M_PI +#define M_PI (3.14159265) +#endif + +#define TABLE_SIZE (200) +typedef struct +{ + float sine[TABLE_SIZE]; + int phase; + unsigned long generatedFramesCount; + volatile int callbackReturnedPaComplete; + volatile int callbackInvokedAfterReturningPaComplete; +} +TestData; + +/* + This routine will be called by the PortAudio stream when audio is needed. + It may be called at interrupt level on some machines so don't do anything + that could mess up the system like calling malloc() or free(). +*/ +static int TestCallback( const void *input, void *output, + unsigned long frameCount, + const PaStreamCallbackTimeInfo* timeInfo, + PaStreamCallbackFlags statusFlags, + void *userData ) +{ + TestData *data = (TestData*)userData; + float *out = (float*)output; + unsigned long i; + float x; + + (void) input; /* Prevent unused variable warnings. */ + (void) timeInfo; + (void) statusFlags; + + + if( data->callbackReturnedPaComplete ) + data->callbackInvokedAfterReturningPaComplete = 1; + + for( i=0; isine[ data->phase++ ]; + if( data->phase >= TABLE_SIZE ) + data->phase -= TABLE_SIZE; + + *out++ = x; /* left */ + *out++ = x; /* right */ + } + + data->generatedFramesCount += frameCount; + if( data->generatedFramesCount >= (NUM_SECONDS * SAMPLE_RATE) ) + { + data->callbackReturnedPaComplete = 1; + return paComplete; + } + else + { + return paContinue; + } +} + +/*----------------------------------------------------------------------------*/ +int main(void); +int main(void) +{ + PaStreamParameters outputParameters; + PaStream *stream; + PaError err; + TestData data; + int i, j; + + + printf( "PortAudio Test: output sine wave. SR = %d, BufSize = %d\n", + SAMPLE_RATE, FRAMES_PER_BUFFER ); + + /* initialise sinusoidal wavetable */ + for( i=0; idefaultLowOutputLatency; + outputParameters.hostApiSpecificStreamInfo = NULL; + + err = Pa_OpenStream( + &stream, + NULL, /* no input */ + &outputParameters, + SAMPLE_RATE, + FRAMES_PER_BUFFER, + paClipOff, /* output will be in-range, so no need to clip */ + TestCallback, + &data ); + if( err != paNoError ) goto error; + + printf("Repeating test %d times.\n", NUM_LOOPS ); + + for( i=0; i < NUM_LOOPS; ++i ) + { + data.phase = 0; + data.generatedFramesCount = 0; + data.callbackReturnedPaComplete = 0; + data.callbackInvokedAfterReturningPaComplete = 0; + + err = Pa_StartStream( stream ); + if( err != paNoError ) goto error; + + printf("Play for %d seconds.\n", NUM_SECONDS ); + + /* wait for the callback to complete generating NUM_SECONDS of tone */ + + do + { + Pa_Sleep( 500 ); + } + while( !data.callbackReturnedPaComplete ); + + printf( "Callback returned paComplete.\n" ); + printf( "Waiting for buffers to finish playing...\n" ); + + /* wait for stream to become inactive, + or for a timeout of approximately NUM_SECONDS + */ + + j = 0; + while( (err = Pa_IsStreamActive( stream )) == 1 && j < NUM_SECONDS * 2 ) + { + printf(".\n" ); + Pa_Sleep( 500 ); + ++j; + } + + if( err < 0 ) + { + goto error; + } + else if( err == 1 ) + { + printf( "TEST FAILED: Timed out waiting for buffers to finish playing.\n" ); + } + else + { + printf("Buffers finished.\n" ); + } + + if( data.callbackInvokedAfterReturningPaComplete ) + { + printf( "TEST FAILED: Callback was invoked after returning paComplete.\n" ); + } + + + err = Pa_StopStream( stream ); + if( err != paNoError ) goto error; + } + + err = Pa_CloseStream( stream ); + if( err != paNoError ) goto error; + + Pa_Terminate(); + printf("Test finished.\n"); + + return err; +error: + Pa_Terminate(); + fprintf( stderr, "An error occured while using the portaudio stream\n" ); + fprintf( stderr, "Error number: %d\n", err ); + fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); + return err; +} diff --git a/pa_tests/patest_clip.c b/pa_tests/patest_clip.c index 39cd1c8..1d17d11 100644 --- a/pa_tests/patest_clip.c +++ b/pa_tests/patest_clip.c @@ -1,10 +1,11 @@ +/** @file patest_clip.c + @brief Play a sine wave for several seconds at an amplitude + that would require clipping. + + @author Phil Burk http://www.softsynth.com +*/ /* * $Id$ - * patest_clip.c - * Play a sine wave using the Portable Audio api for several seconds - * at an amplitude that would require clipping. - * - * Author: Phil Burk http://www.softsynth.com * * This program uses the PortAudio Portable Audio Library. * For more information see: http://www.portaudio.com @@ -37,12 +38,14 @@ #include #include #include "portaudio.h" + #define NUM_SECONDS (4) #define SAMPLE_RATE (44100) #ifndef M_PI #define M_PI (3.14159265) #endif #define TABLE_SIZE (200) + typedef struct paTestData { float sine[TABLE_SIZE]; @@ -51,21 +54,26 @@ typedef struct paTestData int right_phase; } paTestData; + PaError PlaySine( paTestData *data, unsigned long flags, float amplitude ); + /* This routine will be called by the PortAudio engine when audio is needed. ** It may called at interrupt level on some machines so don't do anything ** that could mess up the system like calling malloc() or free(). */ -static int sineCallback( void *inputBuffer, void *outputBuffer, - unsigned long framesPerBuffer, - PaTimestamp outTime, void *userData ) +static int sineCallback( const void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + const PaStreamCallbackTimeInfo* timeInfo, + PaStreamCallbackFlags statusFlags, + void *userData ) { paTestData *data = (paTestData*)userData; float *out = (float*)outputBuffer; float amplitude = data->amplitude; unsigned int i; (void) inputBuffer; /* Prevent "unused variable" warnings. */ - (void) outTime; + (void) timeInfo; + (void) statusFlags; for( i=0; ileft_phase = data->right_phase = 0; data->amplitude = amplitude; + err = Pa_Initialize(); if( err != paNoError ) goto error; + + outputParameters.device = Pa_GetDefaultOutputDevice(); /* default output device */ + outputParameters.channelCount = 2; /* stereo output */ + outputParameters.sampleFormat = paFloat32; /* 32 bit floating point output */ + outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency; + outputParameters.hostApiSpecificStreamInfo = NULL; + err = Pa_OpenStream( &stream, - paNoDevice,/* default input device */ - 0, /* no input */ - paFloat32, /* 32 bit floating point input */ - NULL, - Pa_GetDefaultOutputDeviceID(), /* default output device */ - 2, /* stereo output */ - paFloat32, /* 32 bit floating point output */ - NULL, + NULL, /* no input */ + &outputParameters, SAMPLE_RATE, 1024, - 0, /* number of buffers, if zero then use default minimum */ - flags, /* we won't output out of range samples so don't bother clipping them */ + flags, sineCallback, data ); if( err != paNoError ) goto error; + err = Pa_StartStream( stream ); if( err != paNoError ) goto error; + Pa_Sleep( NUM_SECONDS * 1000 ); - printf("CPULoad = %8.6f\n", Pa_GetCPULoad( stream ) ); + printf("CPULoad = %8.6f\n", Pa_GetStreamCpuLoad( stream ) ); + err = Pa_CloseStream( stream ); if( err != paNoError ) goto error; + Pa_Terminate(); return paNoError; error: diff --git a/pa_tests/patest_dither.c b/pa_tests/patest_dither.c index 1aa0d38..10f03e4 100644 --- a/pa_tests/patest_dither.c +++ b/pa_tests/patest_dither.c @@ -1,10 +1,12 @@ +/** @file patest_dither.c + @brief Attempt to hear difference between dithered and non-dithered signal. + + This only has an effect if the native format is 16 bit. + + @author Phil Burk http://www.softsynth.com +*/ /* * $Id$ - * patest_dither.c - * Attempt to hear difference between dithered and non-dithered signal. - * This only has an effect if the native format is 16 bit. - * - * Author: Phil Burk http://www.softsynth.com * * This program uses the PortAudio Portable Audio Library. * For more information see: http://www.portaudio.com @@ -36,39 +38,40 @@ */ #include #include + #include "portaudio.h" -#define NUM_SECONDS (4) + +#define NUM_SECONDS (5) #define SAMPLE_RATE (44100) #ifndef M_PI #define M_PI (3.14159265) #endif #define TABLE_SIZE (200) + typedef struct paTestData { float sine[TABLE_SIZE]; float amplitude; - int left_phase; - int right_phase; + int left_phase; + int right_phase; } paTestData; -PaError PlaySine( paTestData *data, PaStreamFlags flags, float amplitude ); -static int sineCallback( void *inputBuffer, void *outputBuffer, - unsigned long framesPerBuffer, - PaTimestamp outTime, void *userData ); + /* This routine will be called by the PortAudio engine when audio is needed. ** It may called at interrupt level on some machines so don't do anything ** that could mess up the system like calling malloc() or free(). */ -static int sineCallback( void *inputBuffer, void *outputBuffer, +static int sineCallback( const void *inputBuffer, void *outputBuffer, unsigned long framesPerBuffer, - PaTimestamp outTime, void *userData ) + const PaStreamCallbackTimeInfo *timeInfo, + PaStreamCallbackFlags statusFlags, void *userData ) { paTestData *data = (paTestData*)userData; float *out = (float*)outputBuffer; float amplitude = data->amplitude; unsigned int i; - (void) outTime; (void) inputBuffer; + for( i=0; isine[data->left_phase]; /* left */ @@ -80,14 +83,69 @@ static int sineCallback( void *inputBuffer, void *outputBuffer, } return 0; } + +/*****************************************************************************/ +/* + V18 version did not call Pa_Terminate() if Pa_Initialize() failed. + This V19 version ALWAYS calls Pa_Terminate(). PS. +*/ +PaError PlaySine( paTestData *data, PaStreamFlags flags, float amplitude ); +PaError PlaySine( paTestData *data, PaStreamFlags flags, float amplitude ) +{ + PaStream* stream; + PaStreamParameters outputParameters; + PaError err; + + data->left_phase = data->right_phase = 0; + data->amplitude = amplitude; + + err = Pa_Initialize(); + if (err != paNoError) + goto done; + + outputParameters.device = Pa_GetDefaultOutputDevice(); /* default output device */ + outputParameters.channelCount = 2; /* stereo output */ + outputParameters.hostApiSpecificStreamInfo = NULL; + outputParameters.sampleFormat = paFloat32; /* 32 bit floating point output. */ + /* When you change this, also */ + /* adapt the callback routine! */ + outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device ) + ->defaultLowOutputLatency; /* Low latency. */ + err = Pa_OpenStream( &stream, + NULL, /* No input. */ + &outputParameters, + SAMPLE_RATE, + 1024, /* frames per buffer */ + flags, + sineCallback, + (void*)data ); + if (err != paNoError) + goto done; + + err = Pa_StartStream( stream ); + if (err != paNoError) + goto done; + + Pa_Sleep( NUM_SECONDS * 1000 ); + printf("CPULoad = %8.6f\n", Pa_GetStreamCpuLoad(stream)); + + err = Pa_CloseStream( stream ); +done: + Pa_Sleep( 250 ); /* Just a small silence. */ + Pa_Terminate(); + return err; +} + + /*******************************************************************/ int main(void); int main(void) { - PaError err; - paTestData DATA; - int i; - float amplitude = 32.0 / (1<<15); + PaError err; + paTestData DATA; + int i; + float amplitude = 4.0 / (1<<15); + printf("PortAudio Test: output EXTREMELY QUIET sine wave with and without dithering.\n"); /* initialise sinusoidal wavetable */ for( i=0; ileft_phase = data->right_phase = 0; - data->amplitude = amplitude; - err = Pa_Initialize(); - if( err != paNoError ) goto error; - err = Pa_OpenStream( - &stream, - paNoDevice,/* default input device */ - 0, /* no input */ - paFloat32, /* 32 bit floating point input */ - NULL, - Pa_GetDefaultOutputDeviceID(), /* default output device */ - 2, /* stereo output */ - paFloat32, /* 32 bit floating point output */ - NULL, - SAMPLE_RATE, - 1024, - 0, /* number of buffers, if zero then use default minimum */ - flags, /* we won't output out of range samples so don't bother clipping them */ - sineCallback, - (void *)data ); - if( err != paNoError ) goto error; - - err = Pa_StartStream( stream ); - if( err != paNoError ) goto error; - Pa_Sleep( NUM_SECONDS * 1000 ); - printf("CPULoad = %8.6f\n", Pa_GetCPULoad( stream ) ); - err = Pa_CloseStream( stream ); - if( err != paNoError ) goto error; - Pa_Terminate(); - return paNoError; -error: - return err; +done: + if (err) + { + fprintf( stderr, "An error occured while using the portaudio stream\n" ); + fprintf( stderr, "Error number: %d\n", err ); + fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); + err = 1; /* Though PlaySine() already called Pa_Terminate(), */ + } /* we may still call Pa_GetErrorText(). */ + else + printf("\n(Don't forget to turn the VOLUME DOWN after listening so carefully.)\n"); + return err; /* 0 or 1. */ } diff --git a/pa_tests/patest_hang.c b/pa_tests/patest_hang.c index 6d533da..42858f2 100644 --- a/pa_tests/patest_hang.c +++ b/pa_tests/patest_hang.c @@ -1,10 +1,10 @@ +/** @file patest_hang.c + @brief Play a sine then hang audio callback to test watchdog. + @author Ross Bencina + @author Phil Burk +*/ /* * $Id$ - * Play a sine then hang audio callback to test watchdog. - * - * Authors: - * Ross Bencina - * Phil Burk * * This program uses the PortAudio Portable Audio Library. * For more information see: http://www.audiomulch.com/portaudio/ @@ -36,15 +36,15 @@ */ #include #include -#include "portaudio.h" +#include "portaudio.h" -#define SAMPLE_RATE (44100) -#define FRAMES_PER_BUFFER (1024) +#define SAMPLE_RATE (44100) +#define FRAMES_PER_BUFFER (1024) #ifndef M_PI -#define M_PI (3.14159265) +#define M_PI (3.14159265) #endif -#define TWOPI (M_PI * 2.0) +#define TWOPI (M_PI * 2.0) typedef struct paTestData { @@ -57,9 +57,11 @@ paTestData; ** It may called at interrupt level on some machines so don't do anything ** that could mess up the system like calling malloc() or free(). */ -static int patestCallback( void *inputBuffer, void *outputBuffer, - unsigned long framesPerBuffer, - PaTimestamp outTime, void *userData ) +static int patestCallback( const void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + const PaStreamCallbackTimeInfo* timeInfo, + PaStreamCallbackFlags statusFlags, + void *userData ) { paTestData *data = (paTestData*)userData; float *out = (float*)outputBuffer; @@ -68,8 +70,7 @@ static int patestCallback( void *inputBuffer, void *outputBuffer, double phaseInc = 0.02; double phase = data->phase; - (void) outTime; /* Prevent unused variable warnings. */ - (void) inputBuffer; + (void) inputBuffer; /* Prevent unused argument warning. */ for( i=0; idefaultLowOutputLatency; + err = Pa_OpenStream(&stream, + NULL, /* No input. */ + &outputParameters, + SAMPLE_RATE, + FRAMES_PER_BUFFER, + paClipOff, /* No out of range samples. */ + patestCallback, + &data); + if (err != paNoError) goto error; err = Pa_StartStream( stream ); if( err != paNoError ) goto error; -/* Gradually increase sleep time. */ - for( i=0; i<10000; i+= 1000 ) + /* Gradually increase sleep time. */ + /* Was: for( i=0; i<10000; i+= 1000 ) */ + for(i=0; i <= 1000; i += 100) { printf("Sleep for %d milliseconds in audio callback.\n", i ); data.sleepFor = i; diff --git a/pa_tests/patest_in_overflow.c b/pa_tests/patest_in_overflow.c new file mode 100644 index 0000000..a0be2c6 --- /dev/null +++ b/pa_tests/patest_in_overflow.c @@ -0,0 +1,224 @@ +/** @file patest_in_overflow.c + @brief Count input overflows (using paInputOverflow flag) under + overloaded and normal conditions. + This test uses the same method to overload the stream as does + patest_out_underflow.c -- it generates sine waves until the cpu load + exceeds a certain level. However this test is only concerned with + input and so doesn't ouput any sound. + + @author Ross Bencina + @author Phil Burk +*/ +/* + * $Id$ + * + * This program uses the PortAudio Portable Audio Library. + * For more information see: http://www.audiomulch.com/portaudio/ + * Copyright (c) 1999-2004 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. + * + */ +#include +#include +#include "portaudio.h" + +#define MAX_SINES (500) +#define MAX_LOAD (1.2) +#define SAMPLE_RATE (44100) +#define FRAMES_PER_BUFFER (512) +#ifndef M_PI +#define M_PI (3.14159265) +#endif +#define TWOPI (M_PI * 2.0) + +typedef struct paTestData +{ + int sineCount; + double phases[MAX_SINES]; + int countOverflows; + int inputOverflowCount; +} +paTestData; + +/* This routine will be called by the PortAudio engine when audio is needed. +** It may called at interrupt level on some machines so don't do anything +** that could mess up the system like calling malloc() or free(). +*/ +static int patestCallback( const void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + const PaStreamCallbackTimeInfo* timeInfo, + PaStreamCallbackFlags statusFlags, + void *userData ) +{ + paTestData *data = (paTestData*)userData; + float out; /* variable to hold dummy output */ + unsigned long i; + int j; + int finished = paContinue; + (void) timeInfo; /* Prevent unused variable warning. */ + (void) inputBuffer; /* Prevent unused variable warning. */ + (void) outputBuffer; /* Prevent unused variable warning. */ + + if( data->countOverflows && (statusFlags & paInputOverflow) ) + data->inputOverflowCount++; + + for( i=0; isineCount; j++ ) + { + /* Advance phase of next oscillator. */ + phase = data->phases[j]; + phase += phaseInc; + if( phase > TWOPI ) phase -= TWOPI; + + phaseInc *= 1.02; + if( phaseInc > 0.5 ) phaseInc *= 0.5; + + /* This is not a very efficient way to calc sines. */ + output += (float) sin( phase ); + data->phases[j] = phase; + } + /* this is an input-only stream so we don't actually use the output */ + out = (float) (output / data->sineCount); + (void) out; /* suppress unused variable warning*/ + } + + return finished; +} + +/*******************************************************************/ +int main(void); +int main(void) +{ + PaStreamParameters inputParameters; + PaStream *stream; + PaError err; + int safeSineCount, stressedSineCount; + int safeOverflowCount, stressedOverflowCount; + paTestData data = {0}; + double load; + + + printf("PortAudio Test: input only, no sound output. Load callback by performing calculations, count input overflows. SR = %d, BufSize = %d. MAX_LOAD = %f\n", + SAMPLE_RATE, FRAMES_PER_BUFFER, (float)MAX_LOAD ); + + err = Pa_Initialize(); + if( err != paNoError ) goto error; + + inputParameters.device = Pa_GetDefaultInputDevice(); /* default input device */ + inputParameters.channelCount = 1; /* mono output */ + inputParameters.sampleFormat = paFloat32; /* 32 bit floating point output */ + inputParameters.suggestedLatency = Pa_GetDeviceInfo( inputParameters.device )->defaultLowInputLatency; + inputParameters.hostApiSpecificStreamInfo = NULL; + + err = Pa_OpenStream( + &stream, + &inputParameters, + NULL, /* no output */ + SAMPLE_RATE, + FRAMES_PER_BUFFER, + paClipOff, /* we won't output out of range samples so don't bother clipping them */ + patestCallback, + &data ); + if( err != paNoError ) goto error; + err = Pa_StartStream( stream ); + if( err != paNoError ) goto error; + + printf("Establishing load conditions...\n" ); + + /* Determine number of sines required to get to 50% */ + do + { + data.sineCount++; + Pa_Sleep( 100 ); + + load = Pa_GetStreamCpuLoad( stream ); + printf("sineCount = %d, CPU load = %f\n", data.sineCount, load ); + } + while( load < 0.5 && data.sineCount < (MAX_SINES-1)); + + safeSineCount = data.sineCount; + + /* Calculate target stress value then ramp up to that level*/ + stressedSineCount = (int) (2.0 * data.sineCount * MAX_LOAD ); + if( stressedSineCount > MAX_SINES ) + stressedSineCount = MAX_SINES; + for( ; data.sineCount < stressedSineCount; data.sineCount++ ) + { + Pa_Sleep( 100 ); + load = Pa_GetStreamCpuLoad( stream ); + printf("STRESSING: sineCount = %d, CPU load = %f\n", data.sineCount, load ); + } + + printf("Counting overflows for 5 seconds.\n"); + data.countOverflows = 1; + Pa_Sleep( 5000 ); + + stressedOverflowCount = data.inputOverflowCount; + + data.countOverflows = 0; + data.sineCount = safeSineCount; + + printf("Resuming safe load...\n"); + Pa_Sleep( 1500 ); + data.inputOverflowCount = 0; + Pa_Sleep( 1500 ); + load = Pa_GetStreamCpuLoad( stream ); + printf("sineCount = %d, CPU load = %f\n", data.sineCount, load ); + + printf("Counting overflows for 5 seconds.\n"); + data.countOverflows = 1; + Pa_Sleep( 5000 ); + + safeOverflowCount = data.inputOverflowCount; + + printf("Stop stream.\n"); + err = Pa_StopStream( stream ); + if( err != paNoError ) goto error; + + err = Pa_CloseStream( stream ); + if( err != paNoError ) goto error; + + Pa_Terminate(); + + if( stressedOverflowCount == 0 ) + printf("Test failed, no input overflows detected under stress.\n"); + else if( safeOverflowCount != 0 ) + printf("Test failed, %d unexpected overflows detected under safe load.\n", safeOverflowCount); + else + printf("Test passed, %d expected input overflows detected under stress, 0 unexpected overflows detected under safe load.\n", stressedOverflowCount ); + + return err; +error: + Pa_Terminate(); + fprintf( stderr, "An error occured while using the portaudio stream\n" ); + fprintf( stderr, "Error number: %d\n", err ); + fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); + return err; +} diff --git a/pa_tests/patest_latency.c b/pa_tests/patest_latency.c index 30c8160..f422511 100644 --- a/pa_tests/patest_latency.c +++ b/pa_tests/patest_latency.c @@ -1,9 +1,10 @@ +/** @file + @brief Hear the latency caused by big buffers. + Play a sine wave and change frequency based on letter input. + @author Phil Burk , and Darren Gibbs +*/ /* * $Id$ - * Hear the latency caused by big buffers. - * Play a sine wave and change frequency based on letter input. - * - * Author: Phil Burk , and Darren Gibbs * * This program uses the PortAudio Portable Audio Library. * For more information see: http://www.portaudio.com @@ -33,27 +34,22 @@ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ + #include #include #include "portaudio.h" -#define OUTPUT_DEVICE (Pa_GetDefaultOutputDeviceID()) +#define OUTPUT_DEVICE (Pa_GetDefaultOutputDevice()) #define SAMPLE_RATE (44100) #define FRAMES_PER_BUFFER (64) -#if 0 -#define MIN_LATENCY_MSEC (2000) -#define NUM_BUFFERS ((MIN_LATENCY_MSEC * SAMPLE_RATE) / (FRAMES_PER_BUFFER * 1000)) -#else -#define NUM_BUFFERS (0) -#endif - #define MIN_FREQ (100.0f) #define CalcPhaseIncrement(freq) ((freq)/SAMPLE_RATE) #ifndef M_PI #define M_PI (3.14159265) #endif #define TABLE_SIZE (400) + typedef struct { float sine[TABLE_SIZE + 1]; /* add one for guard point for interpolation */ @@ -62,6 +58,7 @@ typedef struct float right_phase; } paTestData; + float LookupSine( paTestData *data, float phase ); /* Convert phase between and 1.0 to sine value * using linear interpolation. @@ -76,20 +73,22 @@ float LookupSine( paTestData *data, float phase ) float val = lo + fract*(hi-lo); return val; } + /* This routine will be called by the PortAudio engine when audio is needed. ** It may called at interrupt level on some machines so don't do anything ** that could mess up the system like calling malloc() or free(). */ -static int patestCallback( void *inputBuffer, void *outputBuffer, +static int patestCallback( const void *inputBuffer, void *outputBuffer, unsigned long framesPerBuffer, - PaTimestamp outTime, void *userData ) + const PaStreamCallbackTimeInfo* timeInfo, + PaStreamCallbackFlags statusFlags, + void *userData ) { paTestData *data = (paTestData*)userData; float *out = (float*)outputBuffer; int i; - int finished = 0; - (void) outTime; /* Prevent unused variable warnings. */ - (void) inputBuffer; + + (void) inputBuffer; /* Prevent unused variable warning. */ for( i=0; idefaultLowOutputLatency; + outputParameters.hostApiSpecificStreamInfo = NULL; + + printf("Requested output latency = %.4f seconds.\n", outputParameters.suggestedLatency ); + printf("%d frames per buffer.\n.", FRAMES_PER_BUFFER ); + err = Pa_OpenStream( &stream, - paNoDevice, - 0, /* no input */ - paFloat32, /* 32 bit floating point input */ - NULL, - OUTPUT_DEVICE, - 2, /* stereo output */ - paFloat32, /* 32 bit floating point output */ - NULL, + NULL, /* no input */ + &outputParameters, SAMPLE_RATE, FRAMES_PER_BUFFER, - NUM_BUFFERS, /* number of buffers, if zero then use default minimum */ - paClipOff|paDitherOff, /* we won't output out of range samples so don't bother clipping them */ + paClipOff|paDitherOff, /* we won't output out of range samples so don't bother clipping them */ patestCallback, &data ); if( err != paNoError ) goto error; + err = Pa_StartStream( stream ); if( err != paNoError ) goto error; printf("Play ASCII keyboard. Hit 'q' to stop. (Use RETURN key on Mac)\n"); diff --git a/pa_tests/patest_leftright.c b/pa_tests/patest_leftright.c index d718aef..1582236 100644 --- a/pa_tests/patest_leftright.c +++ b/pa_tests/patest_leftright.c @@ -1,12 +1,14 @@ +/** @file patest_leftright.c + @brief Play different tone sine waves that + alternate between left and right channel. + + The low tone should be on the left channel. + + @author Ross Bencina + @author Phil Burk +*/ /* * $Id$ - * patest_leftright.c - * Play different tone sine waves that alternate between left and right channel. - * The low tone should be on the left channel. - * - * Authors: - * Ross Bencina - * Phil Burk * * This program uses the PortAudio Portable Audio Library. * For more information see: http://www.audiomulch.com/portaudio/ @@ -39,6 +41,7 @@ #include #include #include "portaudio.h" + #define NUM_SECONDS (8) #define SAMPLE_RATE (44100) #define FRAMES_PER_BUFFER (512) @@ -59,15 +62,18 @@ paTestData; ** It may called at interrupt level on some machines so don't do anything ** that could mess up the system like calling malloc() or free(). */ -static int patestCallback( void *inputBuffer, void *outputBuffer, - unsigned long framesPerBuffer, - PaTimestamp outTime, void *userData ) +static int patestCallback( const void *inputBuffer, + void *outputBuffer, + unsigned long framesPerBuffer, + const PaStreamCallbackTimeInfo* timeInfo, + PaStreamCallbackFlags statusFlags, + void *userData ) { paTestData *data = (paTestData*)userData; float *out = (float*)outputBuffer; unsigned long i; int finished = 0; - (void) outTime; /* Prevent unused variable warnings. */ + /* Prevent unused variable warnings. */ (void) inputBuffer; for( i=0; idefaultLowOutputLatency; + outputParameters.hostApiSpecificStreamInfo = NULL; + + err = Pa_OpenStream( &stream, + NULL, /* No input. */ + &outputParameters, /* As above. */ + SAMPLE_RATE, + FRAMES_PER_BUFFER, + paClipOff, /* we won't output out of range samples so don't bother clipping them */ + patestCallback, + &data ); if( err != paNoError ) goto error; err = Pa_StartStream( stream ); @@ -148,7 +153,7 @@ int main(void) timeout = NUM_SECONDS * 4; while( timeout > 0 ) { - Pa_Sleep( 300 ); + Pa_Sleep( 300 ); /*(Irix very much likes sleeps <= 1000 ms.)*/ timeout -= 1; } diff --git a/pa_tests/patest_longsine.c b/pa_tests/patest_longsine.c index 0e1e337..3a6ec39 100644 --- a/pa_tests/patest_longsine.c +++ b/pa_tests/patest_longsine.c @@ -1,9 +1,9 @@ +/** @file patest_longsine.c + @brief Play a sine wave until ENTER hit. + @author Phil Burk http://www.softsynth.com +*/ /* * $Id$ - * patest_longsine.c - * Play a sine wave using the Portable Audio api until ENTER hit. - * - * Author: Phil Burk http://www.softsynth.com * * This program uses the PortAudio Portable Audio Library. * For more information see: http://www.portaudio.com @@ -33,8 +33,10 @@ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ + #include #include + #include "portaudio.h" #define SAMPLE_RATE (44100) @@ -56,15 +58,17 @@ paTestData; ** It may called at interrupt level on some machines so don't do anything ** that could mess up the system like calling malloc() or free(). */ -static int patestCallback( void *inputBuffer, void *outputBuffer, - unsigned long framesPerBuffer, - PaTimestamp outTime, void *userData ) +static int patestCallback(const void* inputBuffer, + void* outputBuffer, + unsigned long framesPerBuffer, + const PaStreamCallbackTimeInfo* timeInfo, + PaStreamCallbackFlags statusFlags, + void* userData) { paTestData *data = (paTestData*)userData; float *out = (float*)outputBuffer; unsigned int i; - (void) outTime; /* Prevent unused variable warnings. */ - (void) inputBuffer; + (void) inputBuffer; /* Prevent unused argument warning. */ for( i=0; isine[data->left_phase]; /* left */ @@ -81,7 +85,8 @@ static int patestCallback( void *inputBuffer, void *outputBuffer, int main(void); int main(void) { - PortAudioStream *stream; + PaStreamParameters outputParameters; + PaStream *stream; PaError err; paTestData data; int i; @@ -97,22 +102,20 @@ int main(void) err = Pa_Initialize(); if( err != paNoError ) goto error; - err = Pa_OpenStream( - &stream, - paNoDevice,/* default input device */ - 0, /* no input */ - paFloat32, /* 32 bit floating point input */ - NULL, - Pa_GetDefaultOutputDeviceID(), /* default output device */ - 2, /* stereo output */ - paFloat32, /* 32 bit floating point output */ - NULL, - SAMPLE_RATE, - 256, /* frames per buffer */ - 0, /* number of buffers, if zero then use default minimum */ - paClipOff, /* we won't output out of range samples so don't bother clipping them */ - patestCallback, - &data ); + outputParameters.device = Pa_GetDefaultOutputDevice(); /* default output device */ + outputParameters.channelCount = 2; /* stereo output */ + outputParameters.sampleFormat = paFloat32; /* 32 bit floating point output */ + outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency; + outputParameters.hostApiSpecificStreamInfo = NULL; + + err = Pa_OpenStream( &stream, + NULL, /* No input. */ + &outputParameters, /* As above. */ + SAMPLE_RATE, + 256, /* Frames per buffer. */ + paClipOff, /* No out of range samples expected. */ + patestCallback, + &data ); if( err != paNoError ) goto error; err = Pa_StartStream( stream ); diff --git a/pa_tests/patest_many.c b/pa_tests/patest_many.c index 18169e6..6a67846 100644 --- a/pa_tests/patest_many.c +++ b/pa_tests/patest_many.c @@ -1,9 +1,9 @@ +/** @file patest_many.c + @brief Start and stop the PortAudio Driver multiple times. + @author Phil Burk http://www.softsynth.com +*/ /* * $Id$ - * patest_many.c - * Start and stop the PortAudio Driver multiple times. - * - * Author: Phil Burk http://www.softsynth.com * * This program uses the PortAudio Portable Audio Library. * For more information see: http://www.portaudio.com @@ -52,23 +52,27 @@ typedef struct } paTestData; PaError TestOnce( void ); -static int patest1Callback( void *inputBuffer, void *outputBuffer, +static int patest1Callback( const void *inputBuffer, void *outputBuffer, unsigned long framesPerBuffer, - PaTimestamp outTime, void *userData ); + const PaStreamCallbackTimeInfo* timeInfo, + PaStreamCallbackFlags statusFlags, + void *userData ); + /* This routine will be called by the PortAudio engine when audio is needed. ** It may called at interrupt level on some machines so don't do anything ** that could mess up the system like calling malloc() or free(). */ -static int patest1Callback( void *inputBuffer, void *outputBuffer, +static int patest1Callback( const void *inputBuffer, void *outputBuffer, unsigned long framesPerBuffer, - PaTimestamp outTime, void *userData ) + const PaStreamCallbackTimeInfo* timeInfo, + PaStreamCallbackFlags statusFlags, + void *userData ) { paTestData *data = (paTestData*)userData; short *out = (short*)outputBuffer; unsigned int i; int finished = 0; (void) inputBuffer; /* Prevent "unused variable" warnings. */ - (void) outTime; if( data->sampsToGo < framesPerBuffer ) { @@ -145,7 +149,8 @@ int main(int argc, char **argv) #endif PaError TestOnce( void ) { - PortAudioStream *stream; + PaStreamParameters outputParameters; + PaStream *stream; PaError err; paTestData data; int i; @@ -159,20 +164,19 @@ PaError TestOnce( void ) data.sampsToGo = totalSamps = NUM_SECONDS * SAMPLE_RATE; /* Play for a few seconds. */ err = Pa_Initialize(); if( err != paNoError ) goto error; + + outputParameters.device = Pa_GetDefaultOutputDevice(); /* default output device */ + outputParameters.channelCount = 2; /* stereo output */ + outputParameters.sampleFormat = paInt16; + outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency; + outputParameters.hostApiSpecificStreamInfo = NULL; err = Pa_OpenStream( &stream, - paNoDevice,/* default input device */ - 0, /* no input */ - paInt16, /* sample format */ - NULL, - Pa_GetDefaultOutputDeviceID(), /* default output device */ - 2, /* stereo output */ - paInt16, /* sample format */ - NULL, + NULL, /* no input */ + &outputParameters, SAMPLE_RATE, - 1024, /* frames per buffer */ - 8, /* number of buffers, if zero then use default minimum */ - paClipOff, /* we won't output out of range samples so don't bother clipping them */ + 1024, /* frames per buffer */ + paClipOff, /* we won't output out of range samples so don't bother clipping them */ patest1Callback, &data ); if( err != paNoError ) goto error; diff --git a/pa_tests/patest_maxsines.c b/pa_tests/patest_maxsines.c index 7745be8..56592ea 100644 --- a/pa_tests/patest_maxsines.c +++ b/pa_tests/patest_maxsines.c @@ -1,11 +1,10 @@ +/** @file patest_maxsines.c + @brief How many sine waves can we calculate and play in less than 80% CPU Load. + @author Ross Bencina + @author Phil Burk +*/ /* * $Id$ - * patest_maxsines.c - * How many sine waves can we calculate and play in less than 80% CPU Load. - * - * Authors: - * Ross Bencina - * Phil Burk * * This program uses the PortAudio Portable Audio Library. * For more information see: http://www.audiomulch.com/portaudio/ @@ -82,9 +81,12 @@ float LookupSine( paTestData *data, float phase ) ** It may called at interrupt level on some machines so don't do anything ** that could mess up the system like calling malloc() or free(). */ -static int patestCallback( void *inputBuffer, void *outputBuffer, - unsigned long framesPerBuffer, - PaTimestamp outTime, void *userData ) +static int patestCallback(const void* inputBuffer, + void* outputBuffer, + unsigned long framesPerBuffer, + const PaStreamCallbackTimeInfo* timeInfo, + PaStreamCallbackFlags statusFlags, + void* userData ) { paTestData *data = (paTestData*)userData; float *out = (float*)outputBuffer; @@ -94,10 +96,9 @@ static int patestCallback( void *inputBuffer, void *outputBuffer, unsigned long i; int j; int finished = 0; - (void) outTime; /* Prevent unused variable warnings. */ - (void) inputBuffer; + (void) inputBuffer; /* Prevent unused argument warning. */ -/* Detemine amplitude scaling factor */ + /* Determine amplitude scaling factor */ numForScale = data->numSines; if( numForScale < 8 ) numForScale = 8; /* prevent pops at beginning */ scaler = 1.0f / numForScale; @@ -132,11 +133,13 @@ static int patestCallback( void *inputBuffer, void *outputBuffer, int main(void); int main(void) { - int i; - PortAudioStream *stream; - PaError err; - paTestData data = {0}; - double load; + int i; + PaStream* stream; + PaStreamParameters outputParameters; + PaError err; + paTestData data = {0}; + double load; + printf("PortAudio Test: output sine wave. SR = %d, BufSize = %d\n", SAMPLE_RATE, FRAMES_PER_BUFFER); /* initialise sinusoidal wavetable */ @@ -147,43 +150,48 @@ int main(void) data.sine[TABLE_SIZE] = data.sine[0]; /* set guard point */ err = Pa_Initialize(); - if( err != paNoError ) goto error; - err = Pa_OpenStream( - &stream, - paNoDevice, - 0, /* no input */ - paFloat32, - NULL, - Pa_GetDefaultOutputDeviceID(), /* default output device */ - 2, /* stereo output */ - paFloat32, /* 32 bit floating point output */ - NULL, - SAMPLE_RATE, - FRAMES_PER_BUFFER, - 0, /* number of buffers, if zero then use default minimum */ - paClipOff, /* we won't output out of range samples so don't bother clipping them */ - patestCallback, - &data ); - if( err != paNoError ) goto error; + if( err != paNoError ) + goto error; + outputParameters.device = Pa_GetDefaultOutputDevice(); /* Default output device. */ + outputParameters.channelCount = 2; /* Stereo output. */ + outputParameters.sampleFormat = paFloat32; /* 32 bit floating point output. */ + outputParameters.hostApiSpecificStreamInfo = NULL; + outputParameters.suggestedLatency = Pa_GetDeviceInfo(outputParameters.device) + ->defaultHighOutputLatency; + err = Pa_OpenStream(&stream, + NULL, /* no input */ + &outputParameters, + SAMPLE_RATE, + FRAMES_PER_BUFFER, + paClipOff, /* No out of range samples should occur. */ + patestCallback, + &data); + if( err != paNoError ) + goto error; + err = Pa_StartStream( stream ); - if( err != paNoError ) goto error; + if( err != paNoError ) + goto error; -/* Play an increasing number of sine waves until we hit MAX_USAGE */ - do - { + /* Play an increasing number of sine waves until we hit MAX_USAGE */ + do { data.numSines++; - Pa_Sleep( 200 ); - - load = Pa_GetCPULoad( stream ); + Pa_Sleep(200); + load = Pa_GetStreamCpuLoad(stream); printf("numSines = %d, CPU load = %f\n", data.numSines, load ); - fflush( stdout ); - } - while( (load < MAX_USAGE) && (data.numSines < MAX_SINES) ); + fflush(stdout); + } while((load < MAX_USAGE) && (data.numSines < MAX_SINES)); + + Pa_Sleep(2000); /* Stay for 2 seconds around 80% CPU. */ err = Pa_StopStream( stream ); - if( err != paNoError ) goto error; + if( err != paNoError ) + goto error; + err = Pa_CloseStream( stream ); - if( err != paNoError ) goto error; + if( err != paNoError ) + goto error; + Pa_Terminate(); printf("Test finished.\n"); return err; diff --git a/pa_tests/patest_mono.c b/pa_tests/patest_mono.c new file mode 100644 index 0000000..e7b5736 --- /dev/null +++ b/pa_tests/patest_mono.c @@ -0,0 +1,145 @@ +/* + * $Id$ + * patest_sine.c + * Play a monophonic sine wave using the Portable Audio api for several seconds. + * + * Authors: + * Ross Bencina + * Phil Burk + * + * This program uses the PortAudio Portable Audio Library. + * For more information see: http://www.audiomulch.com/portaudio/ + * 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. + * + */ +#include +#include +#include "portaudio.h" + +#define NUM_SECONDS (10) +#define SAMPLE_RATE (44100) +#define AMPLITUDE (0.8) +#define FRAMES_PER_BUFFER (64) +#define OUTPUT_DEVICE Pa_GetDefaultOutputDevice() + +#ifndef M_PI +#define M_PI (3.14159265) +#endif + +#define TABLE_SIZE (200) +typedef struct +{ + float sine[TABLE_SIZE]; + int phase; +} +paTestData; + +/* This routine will be called by the PortAudio engine when audio is needed. +** It may called at interrupt level on some machines so don't do anything +** that could mess up the system like calling malloc() or free(). +*/ +static int patestCallback( const void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + const PaStreamCallbackTimeInfo* timeInfo, + PaStreamCallbackFlags statusFlags, + void *userData ) +{ + paTestData *data = (paTestData*)userData; + float *out = (float*)outputBuffer; + unsigned long i; + int finished = 0; + /* avoid unused variable warnings */ + (void) inputBuffer; + (void) timeInfo; + (void) statusFlags; + for( i=0; isine[data->phase]; /* left */ + data->phase += 1; + if( data->phase >= TABLE_SIZE ) data->phase -= TABLE_SIZE; + } + return finished; +} + +/*******************************************************************/ +int main(void); +int main(void) +{ + PaStreamParameters outputParameters; + PaStream *stream; + PaError err; + paTestData data; + int i; + printf("PortAudio Test: output MONO sine wave. SR = %d, BufSize = %d\n", SAMPLE_RATE, FRAMES_PER_BUFFER); + /* initialise sinusoidal wavetable */ + for( i=0; idefaultLowOutputLatency; + outputParameters.hostApiSpecificStreamInfo = NULL; + + err = Pa_OpenStream( + &stream, + NULL, /* no input */ + &outputParameters, + SAMPLE_RATE, + FRAMES_PER_BUFFER, + paClipOff, /* we won't output out of range samples so don't bother clipping them */ + patestCallback, + &data ); + if( err != paNoError ) goto error; + + err = Pa_StartStream( stream ); + if( err != paNoError ) goto error; + + printf("Play for %d seconds.\n", NUM_SECONDS ); fflush(stdout); + Pa_Sleep( NUM_SECONDS * 1000 ); + + err = Pa_StopStream( stream ); + if( err != paNoError ) goto error; + + err = Pa_CloseStream( stream ); + if( err != paNoError ) goto error; + + Pa_Terminate(); + printf("Test finished.\n"); + return err; +error: + Pa_Terminate(); + fprintf( stderr, "An error occured while using the portaudio stream\n" ); + fprintf( stderr, "Error number: %d\n", err ); + fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); + return err; +} \ No newline at end of file diff --git a/pa_tests/patest_mono_asio_channel_select.c b/pa_tests/patest_mono_asio_channel_select.c new file mode 100644 index 0000000..4c4ffcc --- /dev/null +++ b/pa_tests/patest_mono_asio_channel_select.c @@ -0,0 +1,155 @@ +/* + * $Id$ + * patest_sine.c + * Play a monophonic sine wave using the Portable Audio api for several seconds. + * + * Authors: + * Ross Bencina + * Phil Burk + * + * This program uses the PortAudio Portable Audio Library. + * For more information see: http://www.audiomulch.com/portaudio/ + * 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. + * + */ +#include +#include +#include "portaudio.h" +#include "pa_asio.h" + +#define NUM_SECONDS (10) +#define SAMPLE_RATE (44100) +#define AMPLITUDE (0.8) +#define FRAMES_PER_BUFFER (64) +#define OUTPUT_DEVICE Pa_GetDefaultOutputDevice() + +#ifndef M_PI +#define M_PI (3.14159265) +#endif + +#define TABLE_SIZE (200) +typedef struct +{ + float sine[TABLE_SIZE]; + int phase; +} +paTestData; + +/* This routine will be called by the PortAudio engine when audio is needed. +** It may called at interrupt level on some machines so don't do anything +** that could mess up the system like calling malloc() or free(). +*/ +static int patestCallback( const void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + const PaStreamCallbackTimeInfo* timeInfo, + PaStreamCallbackFlags statusFlags, + void *userData ) +{ + paTestData *data = (paTestData*)userData; + float *out = (float*)outputBuffer; + unsigned long i; + int finished = 0; + /* avoid unused variable warnings */ + (void) inputBuffer; + (void) timeInfo; + (void) statusFlags; + for( i=0; isine[data->phase]; /* left */ + data->phase += 1; + if( data->phase >= TABLE_SIZE ) data->phase -= TABLE_SIZE; + } + return finished; +} + +/*******************************************************************/ +int main(void); +int main(void) +{ + PaStreamParameters outputParameters; + PaAsioStreamInfo asioOutputInfo; + PaStream *stream; + PaError err; + paTestData data; + int outputChannelSelectors[1]; + int i; + printf("PortAudio Test: output MONO sine wave. SR = %d, BufSize = %d\n", SAMPLE_RATE, FRAMES_PER_BUFFER); + /* initialise sinusoidal wavetable */ + for( i=0; idefaultLowOutputLatency; + + asioOutputInfo.size = sizeof(PaAsioStreamInfo); + asioOutputInfo.hostApiType = paASIO; + asioOutputInfo.version = 1; + asioOutputInfo.flags = paAsioUseChannelSelectors; + outputChannelSelectors[0] = 1; /* select the second (right) ASIO device channel */ + asioOutputInfo.channelSelectors = outputChannelSelectors; + outputParameters.hostApiSpecificStreamInfo = &asioOutputInfo; + + err = Pa_OpenStream( + &stream, + NULL, /* no input */ + &outputParameters, + SAMPLE_RATE, + FRAMES_PER_BUFFER, + paClipOff, /* we won't output out of range samples so don't bother clipping them */ + patestCallback, + &data ); + if( err != paNoError ) goto error; + + err = Pa_StartStream( stream ); + if( err != paNoError ) goto error; + + printf("Play for %d seconds.\n", NUM_SECONDS ); fflush(stdout); + Pa_Sleep( NUM_SECONDS * 1000 ); + + err = Pa_StopStream( stream ); + if( err != paNoError ) goto error; + + err = Pa_CloseStream( stream ); + if( err != paNoError ) goto error; + + Pa_Terminate(); + printf("Test finished.\n"); + return err; +error: + Pa_Terminate(); + fprintf( stderr, "An error occured while using the portaudio stream\n" ); + fprintf( stderr, "Error number: %d\n", err ); + fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); + return err; +} diff --git a/pa_tests/patest_multi_sine.c b/pa_tests/patest_multi_sine.c index 01ea2a1..161c882 100644 --- a/pa_tests/patest_multi_sine.c +++ b/pa_tests/patest_multi_sine.c @@ -1,10 +1,9 @@ +/** @file patest_multi_sine.c + @brief Play a different sine wave on each channel. + @author Phil Burk http://www.softsynth.com +*/ /* * $Id$ - * patest_multi_out.c - * Play a different sine wave on each channels, - * using the Portable Audio api. - * - * Author: Phil Burk http://www.softsynth.com * * This program uses the PortAudio Portable Audio Library. * For more information see: http://www.portaudio.com @@ -34,15 +33,16 @@ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ + #include #include + #include "portaudio.h" -#define OUTPUT_DEVICE (Pa_GetDefaultOutputDeviceID()) -#define SAMPLE_RATE (44100) -#define FRAMES_PER_BUFFER (256) -#define FREQ_INCR (300.0 / SAMPLE_RATE) -#define MAX_CHANNELS (64) +#define SAMPLE_RATE (44100) +#define FRAMES_PER_BUFFER (256) +#define FREQ_INCR (300.0 / SAMPLE_RATE) +#define MAX_CHANNELS (64) #ifndef M_PI #define M_PI (3.14159265) @@ -50,8 +50,9 @@ typedef struct { - int numChannels; - double phases[MAX_CHANNELS]; + short interleaved; /* Nonzero for interleaved / zero for non-interleaved. */ + int numChannels; /* Actually used. */ + double phases[MAX_CHANNELS]; /* Each channel gets its' own frequency. */ } paTestData; @@ -59,86 +60,135 @@ paTestData; ** It may called at interrupt level on some machines so don't do anything ** that could mess up the system like calling malloc() or free(). */ -static int patestCallback( void *inputBuffer, void *outputBuffer, - unsigned long framesPerBuffer, - PaTimestamp outTime, void *userData ) +static int patestCallback(const void* inputBuffer, + void* outputBuffer, + unsigned long framesPerBuffer, + const PaStreamCallbackTimeInfo* timeInfo, + PaStreamCallbackFlags statusFlags, + void* userData) { - paTestData *data = (paTestData*)userData; - float *out = (float*)outputBuffer; - int frameIndex, channelIndex; - int finished = 0; - (void) outTime; /* Prevent unused variable warnings. */ - (void) inputBuffer; - - for( frameIndex=0; frameIndex<(int)framesPerBuffer; frameIndex++ ) - { - for( channelIndex=0; channelIndexnumChannels; channelIndex++ ) + int frameIndex, channelIndex; + float** outputs = (float**)outputBuffer; + paTestData* data = (paTestData*)userData; + + (void) inputBuffer; /* Prevent unused arg warning. */ + if (data->interleaved) { - /* Output sine wave on every channel. */ - *out++ = (float) sin(data->phases[channelIndex]); + float *out = (float*)outputBuffer; /* interleaved version */ + for( frameIndex=0; frameIndex<(int)framesPerBuffer; frameIndex++ ) + { + for( channelIndex=0; channelIndexnumChannels; channelIndex++ ) + { + /* Output sine wave on every channel. */ + *out++ = (float) sin(data->phases[channelIndex]); - /* Play each channel at a higher frequency. */ - data->phases[channelIndex] += FREQ_INCR * (4 + channelIndex); - if( data->phases[channelIndex] >= (2.0 * M_PI) ) data->phases[channelIndex] -= (2.0 * M_PI); + /* Play each channel at a higher frequency. */ + data->phases[channelIndex] += FREQ_INCR * (4 + channelIndex); + if( data->phases[channelIndex] >= (2.0 * M_PI) ) data->phases[channelIndex] -= (2.0 * M_PI); + } + } } - } + else + { + for( frameIndex=0; frameIndex<(int)framesPerBuffer; frameIndex++ ) + { + for( channelIndex=0; channelIndexnumChannels; channelIndex++ ) + { + /* Output sine wave on every channel. */ + outputs[channelIndex][frameIndex] = (float) sin(data->phases[channelIndex]); + /* Play each channel at a higher frequency. */ + data->phases[channelIndex] += FREQ_INCR * (4 + channelIndex); + if( data->phases[channelIndex] >= (2.0 * M_PI) ) data->phases[channelIndex] -= (2.0 * M_PI); + } + } + } return 0; } /*******************************************************************/ -int main(void); +int test(short interleaved) +{ + PaStream* stream; + PaStreamParameters outputParameters; + PaError err; + const PaDeviceInfo* pdi; + paTestData data; + short n; + + outputParameters.device = Pa_GetDefaultOutputDevice(); /* Default output device, max channels. */ + pdi = Pa_GetDeviceInfo(outputParameters.device); + outputParameters.channelCount = pdi->maxOutputChannels; + if (outputParameters.channelCount > MAX_CHANNELS) + outputParameters.channelCount = MAX_CHANNELS; + outputParameters.sampleFormat = paFloat32; /* 32 bit floating point output */ + outputParameters.suggestedLatency = pdi->defaultLowOutputLatency; + outputParameters.hostApiSpecificStreamInfo = NULL; + + data.interleaved = interleaved; + data.numChannels = outputParameters.channelCount; + for (n = 0; n < data.numChannels; n++) + data.phases[n] = 0.0; /* Phases wrap and maybe don't need initialisation. */ + printf("%d ", data.numChannels); + if (interleaved) + printf("interleaved "); + else + { + printf(" non-interleaved "); + outputParameters.sampleFormat |= paNonInterleaved; + } + printf("channels.\n"); + + err = Pa_OpenStream(&stream, + NULL, /* No input. */ + &outputParameters, + SAMPLE_RATE, /* Sample rate. */ + FRAMES_PER_BUFFER, /* Frames per buffer. */ + paClipOff, /* Samples never out of range, no clipping. */ + patestCallback, + &data); + if (err == paNoError) + { + err = Pa_StartStream(stream); + if (err == paNoError) + { + printf("Hit ENTER to stop this test.\n"); + getchar(); + err = Pa_StopStream(stream); + } + Pa_CloseStream( stream ); + } + return err; +} + + +/*******************************************************************/ int main(void) { - PortAudioStream *stream; PaError err; - const PaDeviceInfo *pdi; - paTestData data = {0}; + printf("PortAudio Test: output sine wave on each channel.\n" ); err = Pa_Initialize(); - if( err != paNoError ) goto error; + if (err != paNoError) + goto done; + + err = test(1); /* 1 means interleaved. */ + if (err != paNoError) + goto done; + + err = test(0); /* 0 means not interleaved. */ + if (err != paNoError) + goto done; - pdi = Pa_GetDeviceInfo( OUTPUT_DEVICE ); - data.numChannels = pdi->maxOutputChannels; - if( data.numChannels > MAX_CHANNELS ) data.numChannels = MAX_CHANNELS; - printf("Number of Channels = %d\n", data.numChannels ); - - err = Pa_OpenStream( - &stream, - paNoDevice, /* default input device */ - 0, /* no input */ - paFloat32, /* 32 bit floating point input */ - NULL, - OUTPUT_DEVICE, - data.numChannels, - paFloat32, /* 32 bit floating point output */ - NULL, - SAMPLE_RATE, - FRAMES_PER_BUFFER, /* frames per buffer */ - 0, /* number of buffers, if zero then use default minimum */ - paClipOff, /* we won't output out of range samples so don't bother clipping them */ - patestCallback, - &data ); - if( err != paNoError ) goto error; - - err = Pa_StartStream( stream ); - if( err != paNoError ) goto error; - - printf("Hit ENTER to stop sound.\n"); - getchar(); - - err = Pa_StopStream( stream ); - if( err != paNoError ) goto error; - - Pa_CloseStream( stream ); - Pa_Terminate(); printf("Test finished.\n"); - return err; -error: +done: + if (err) + { + fprintf(stderr, "An error occured while using the portaudio stream\n"); + fprintf(stderr, "Error number: %d\n", err ); + fprintf(stderr, "Error message: %s\n", Pa_GetErrorText(err)); + } Pa_Terminate(); - fprintf( stderr, "An error occured while using the portaudio stream\n" ); - fprintf( stderr, "Error number: %d\n", err ); - fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); - return err; + return 0; } diff --git a/pa_tests/patest_out_underflow.c b/pa_tests/patest_out_underflow.c new file mode 100644 index 0000000..8e6f278 --- /dev/null +++ b/pa_tests/patest_out_underflow.c @@ -0,0 +1,217 @@ +/** @file patest_out_underflow.c + @brief Count output underflows (using paOutputUnderflow flag) + under overloaded and normal conditions. + @author Ross Bencina + @author Phil Burk +*/ +/* + * $Id$ + * + * This program uses the PortAudio Portable Audio Library. + * For more information see: http://www.audiomulch.com/portaudio/ + * Copyright (c) 1999-2004 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. + * + */ +#include +#include +#include "portaudio.h" + +#define MAX_SINES (500) +#define MAX_LOAD (1.2) +#define SAMPLE_RATE (44100) +#define FRAMES_PER_BUFFER (512) +#ifndef M_PI +#define M_PI (3.14159265) +#endif +#define TWOPI (M_PI * 2.0) + +typedef struct paTestData +{ + int sineCount; + double phases[MAX_SINES]; + int countUnderflows; + int outputUnderflowCount; +} +paTestData; + +/* This routine will be called by the PortAudio engine when audio is needed. +** It may called at interrupt level on some machines so don't do anything +** that could mess up the system like calling malloc() or free(). +*/ +static int patestCallback( const void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + const PaStreamCallbackTimeInfo* timeInfo, + PaStreamCallbackFlags statusFlags, + void *userData ) +{ + paTestData *data = (paTestData*)userData; + float *out = (float*)outputBuffer; + unsigned long i; + int j; + int finished = paContinue; + (void) timeInfo; /* Prevent unused variable warning. */ + (void) inputBuffer; /* Prevent unused variable warning. */ + + + if( data->countUnderflows && (statusFlags & paOutputUnderflow) ) + data->outputUnderflowCount++; + + for( i=0; isineCount; j++ ) + { + /* Advance phase of next oscillator. */ + phase = data->phases[j]; + phase += phaseInc; + if( phase > TWOPI ) phase -= TWOPI; + + phaseInc *= 1.02; + if( phaseInc > 0.5 ) phaseInc *= 0.5; + + /* This is not a very efficient way to calc sines. */ + output += (float) sin( phase ); + data->phases[j] = phase; + } + *out++ = (float) (output / data->sineCount); + } + + return finished; +} + +/*******************************************************************/ +int main(void); +int main(void) +{ + PaStreamParameters outputParameters; + PaStream *stream; + PaError err; + int safeSineCount, stressedSineCount; + int safeUnderflowCount, stressedUnderflowCount; + paTestData data = {0}; + double load; + + + printf("PortAudio Test: output sine waves, count underflows. SR = %d, BufSize = %d. MAX_LOAD = %f\n", + SAMPLE_RATE, FRAMES_PER_BUFFER, (float)MAX_LOAD ); + + err = Pa_Initialize(); + if( err != paNoError ) goto error; + + outputParameters.device = Pa_GetDefaultOutputDevice(); /* default output device */ + outputParameters.channelCount = 1; /* mono output */ + outputParameters.sampleFormat = paFloat32; /* 32 bit floating point output */ + outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency; + outputParameters.hostApiSpecificStreamInfo = NULL; + + err = Pa_OpenStream( + &stream, + NULL, /* no input */ + &outputParameters, + SAMPLE_RATE, + FRAMES_PER_BUFFER, + paClipOff, /* we won't output out of range samples so don't bother clipping them */ + patestCallback, + &data ); + if( err != paNoError ) goto error; + err = Pa_StartStream( stream ); + if( err != paNoError ) goto error; + + printf("Establishing load conditions...\n" ); + + /* Determine number of sines required to get to 50% */ + do + { + data.sineCount++; + Pa_Sleep( 100 ); + + load = Pa_GetStreamCpuLoad( stream ); + printf("sineCount = %d, CPU load = %f\n", data.sineCount, load ); + } + while( load < 0.5 && data.sineCount < (MAX_SINES-1)); + + safeSineCount = data.sineCount; + + /* Calculate target stress value then ramp up to that level*/ + stressedSineCount = (int) (2.0 * data.sineCount * MAX_LOAD ); + if( stressedSineCount > MAX_SINES ) + stressedSineCount = MAX_SINES; + for( ; data.sineCount < stressedSineCount; data.sineCount++ ) + { + Pa_Sleep( 100 ); + load = Pa_GetStreamCpuLoad( stream ); + printf("STRESSING: sineCount = %d, CPU load = %f\n", data.sineCount, load ); + } + + printf("Counting underflows for 5 seconds.\n"); + data.countUnderflows = 1; + Pa_Sleep( 5000 ); + + stressedUnderflowCount = data.outputUnderflowCount; + + data.countUnderflows = 0; + data.sineCount = safeSineCount; + + printf("Resuming safe load...\n"); + Pa_Sleep( 1500 ); + data.outputUnderflowCount = 0; + Pa_Sleep( 1500 ); + load = Pa_GetStreamCpuLoad( stream ); + printf("sineCount = %d, CPU load = %f\n", data.sineCount, load ); + + printf("Counting underflows for 5 seconds.\n"); + data.countUnderflows = 1; + Pa_Sleep( 5000 ); + + safeUnderflowCount = data.outputUnderflowCount; + + printf("Stop stream.\n"); + err = Pa_StopStream( stream ); + if( err != paNoError ) goto error; + + err = Pa_CloseStream( stream ); + if( err != paNoError ) goto error; + + Pa_Terminate(); + + if( stressedUnderflowCount == 0 ) + printf("Test failed, no output underflows detected under stress.\n"); + else if( safeUnderflowCount != 0 ) + printf("Test failed, %d unexpected underflows detected under safe load.\n", safeUnderflowCount); + else + printf("Test passed, %d expected output underflows detected under stress, 0 unexpected underflows detected under safe load.\n", stressedUnderflowCount ); + + return err; +error: + Pa_Terminate(); + fprintf( stderr, "An error occured while using the portaudio stream\n" ); + fprintf( stderr, "Error number: %d\n", err ); + fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); + return err; +} diff --git a/pa_tests/patest_pink.c b/pa_tests/patest_pink.c index c1fdece..f2db85d 100644 --- a/pa_tests/patest_pink.c +++ b/pa_tests/patest_pink.c @@ -1,18 +1,22 @@ +/** @file patest_pink.c + @brief Generate Pink Noise using Gardner method. + + Optimization suggested by James McCartney uses a tree + to select which random value to replace. +
+	x x x x x x x x x x x x x x x x 
+	x   x   x   x   x   x   x   x   
+	x       x       x       x       
+	 x               x               
+	   x   
+
+ Tree is generated by counting trailing zeros in an increasing index. + When the index is zero, no random number is selected. + + @author Phil Burk http://www.softsynth.com +*/ /* * $Id$ - patest_pink.c - Generate Pink Noise using Gardner method. - Optimization suggested by James McCartney uses a tree - to select which random value to replace. - x x x x x x x x x x x x x x x x - x x x x x x x x - x x x x - x x - x - Tree is generated by counting trailing zeros in an increasing index. - When the index is zero, no random number is selected. - * - * Author: Phil Burk http://www.softsynth.com * * This program uses the PortAudio Portable Audio Library. * For more information see: http://www.portaudio.com @@ -42,12 +46,15 @@ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ + #include #include #include "portaudio.h" + #define PINK_MAX_RANDOM_ROWS (30) #define PINK_RANDOM_BITS (24) #define PINK_RANDOM_SHIFT ((sizeof(long)*8)-PINK_RANDOM_BITS) + typedef struct { long pink_Rows[PINK_MAX_RANDOM_ROWS]; @@ -57,10 +64,12 @@ typedef struct float pink_Scalar; /* Used to scale within range of -1.0 to +1.0 */ } PinkNoise; + /* Prototypes */ static unsigned long GenerateRandomNumber( void ); void InitializePinkNoise( PinkNoise *pink, int numRows ); float GeneratePinkNoise( PinkNoise *pink ); + /************************************************************/ /* Calculate pseudo-random 32 bit number based on linear congruential method. */ static unsigned long GenerateRandomNumber( void ) @@ -70,6 +79,7 @@ static unsigned long GenerateRandomNumber( void ) randSeed = (randSeed * 196314165) + 907633515; return randSeed; } + /************************************************************/ /* Setup PinkNoise structure for N rows of generators. */ void InitializePinkNoise( PinkNoise *pink, int numRows ) @@ -85,11 +95,13 @@ void InitializePinkNoise( PinkNoise *pink, int numRows ) for( i=0; ipink_Rows[i] = 0; pink->pink_RunningSum = 0; } + #define PINK_MEASURE #ifdef PINK_MEASURE float pinkMax = -999.0; float pinkMin = 999.0; #endif + /* Generate Pink noise values between -1.0 and +1.0 */ float GeneratePinkNoise( PinkNoise *pink ) { @@ -132,9 +144,11 @@ float GeneratePinkNoise( PinkNoise *pink ) #endif return output; } + /*******************************************************************/ #define PINK_TEST #ifdef PINK_TEST + /* Context for callback routine. */ typedef struct { @@ -143,13 +157,17 @@ typedef struct unsigned int sampsToGo; } paTestData; + /* This routine will be called by the PortAudio engine when audio is needed. ** It may called at interrupt level on some machines so don't do anything ** that could mess up the system like calling malloc() or free(). */ -static int patestCallback( void *inputBuffer, void *outputBuffer, - unsigned long framesPerBuffer, - PaTimestamp outTime, void *userData ) +static int patestCallback(const void* inputBuffer, + void* outputBuffer, + unsigned long framesPerBuffer, + const PaStreamCallbackTimeInfo* timeInfo, + PaStreamCallbackFlags statusFlags, + void* userData) { int finished; int i; @@ -157,7 +175,6 @@ static int patestCallback( void *inputBuffer, void *outputBuffer, paTestData *data = (paTestData*)userData; float *out = (float*)outputBuffer; (void) inputBuffer; /* Prevent "unused variable" warnings. */ - (void) outTime; /* Are we almost at end. */ if( data->sampsToGo < framesPerBuffer ) @@ -178,17 +195,23 @@ static int patestCallback( void *inputBuffer, void *outputBuffer, data->sampsToGo -= numFrames; return finished; } + /*******************************************************************/ int main(void); int main(void) { - PortAudioStream *stream; - PaError err; - paTestData data; - int totalSamps; + PaStream* stream; + PaError err; + paTestData data; + PaStreamParameters outputParameters; + int totalSamps; + static const double SR = 44100.0; + static const int FPB = 2048; /* Frames per buffer: 46 ms buffers. */ + /* Initialize two pink noise signals with different numbers of rows. */ - InitializePinkNoise( &data.leftPink, 12 ); + InitializePinkNoise( &data.leftPink, 12 ); InitializePinkNoise( &data.rightPink, 16 ); + /* Look at a few values. */ { int i; @@ -199,35 +222,36 @@ int main(void) printf("Pink = %f\n", pink ); } } - data.sampsToGo = totalSamps = 8*44100; /* Play for a few seconds. */ + + data.sampsToGo = totalSamps = (int)(60.0 * SR); /* Play a whole minute. */ err = Pa_Initialize(); if( err != paNoError ) goto error; + /* Open a stereo PortAudio stream so we can hear the result. */ - err = Pa_OpenStream( - &stream, - paNoDevice, - 0, /* no input */ - paFloat32, /* 32 bit floating point input */ - NULL, - Pa_GetDefaultOutputDeviceID(), /* default output device */ - 2, /* stereo output */ - paFloat32, /* 32 bit floating point output */ - NULL, - 44100., - 2048, /* 46 msec buffers */ - 0, /* number of buffers, if zero then use default minimum */ - paClipOff, /* we won't output out of range samples so don't bother clipping them */ - patestCallback, - &data ); + outputParameters.device = Pa_GetDefaultOutputDevice(); /* Take the default output device. */ + outputParameters.channelCount = 2; /* Stereo output, most likely supported. */ + outputParameters.hostApiSpecificStreamInfo = NULL; + outputParameters.sampleFormat = paFloat32; /* 32 bit floating point output. */ + outputParameters.suggestedLatency = + Pa_GetDeviceInfo(outputParameters.device)->defaultLowOutputLatency; + err = Pa_OpenStream(&stream, + NULL, /* No input. */ + &outputParameters, + SR, /* Sample rate. */ + FPB, /* Frames per buffer. */ + paClipOff, /* we won't output out of range samples so don't bother clipping them */ + patestCallback, + &data); if( err != paNoError ) goto error; err = Pa_StartStream( stream ); if( err != paNoError ) goto error; - printf("Waiting for sound to finish.\n"); - while( Pa_StreamActive( stream ) ) - { - Pa_Sleep(100); /* SPIN! */ - } + + printf("Stereo pink noise for one minute...\n"); + + while( ( err = Pa_IsStreamActive( stream ) ) == 1 ) Pa_Sleep(100); + if( err < 0 ) goto error; + err = Pa_CloseStream( stream ); if( err != paNoError ) goto error; #ifdef PINK_MEASURE diff --git a/pa_tests/patest_prime.c b/pa_tests/patest_prime.c new file mode 100644 index 0000000..47d1f5f --- /dev/null +++ b/pa_tests/patest_prime.c @@ -0,0 +1,223 @@ +/** @file patest_prime.c + @brief Test stream priming mode. + @author Ross Bencina http://www.audiomulch.com/~rossb +*/ + +/* + * $Id$ + * + * This program uses the PortAudio Portable Audio Library. + * For more information see: http://www.portaudio.com + * 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. + * + */ + +#include +#include +#include "portaudio.h" +#include "pa_util.h" + +#define NUM_BEEPS (3) +#define SAMPLE_RATE (44100) +#define SAMPLE_PERIOD (1.0/44100.0) +#define FRAMES_PER_BUFFER (256) +#define BEEP_DURATION (400) +#define IDLE_DURATION (SAMPLE_RATE*2) /* 2 seconds */ +#define SLEEP_MSEC (50) + +#define STATE_BKG_IDLE (0) +#define STATE_BKG_BEEPING (1) + +typedef struct +{ + float leftPhase; + float rightPhase; + int state; + int beepCountdown; + int idleCountdown; +} +paTestData; + +static void InitializeTestData( paTestData *testData ) +{ + testData->leftPhase = 0; + testData->rightPhase = 0; + testData->state = STATE_BKG_BEEPING; + testData->beepCountdown = BEEP_DURATION; + testData->idleCountdown = IDLE_DURATION; +} + +/* This routine will be called by the PortAudio engine when audio is needed. +** It may called at interrupt level on some machines so don't do anything +** that could mess up the system like calling malloc() or free(). +*/ +static int patestCallback( const void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + const PaStreamCallbackTimeInfo *timeInfo, + PaStreamCallbackFlags statusFlags, void *userData ) +{ + /* Cast data passed through stream to our structure. */ + paTestData *data = (paTestData*)userData; + float *out = (float*)outputBuffer; + unsigned int i; + int result = paContinue; + + /* supress unused parameter warnings */ + (void) inputBuffer; + (void) timeInfo; + (void) statusFlags; + + for( i=0; istate ) + { + case STATE_BKG_IDLE: + *out++ = 0.0; /* left */ + *out++ = 0.0; /* right */ + --data->idleCountdown; + + if( data->idleCountdown <= 0 ) result = paComplete; + break; + + case STATE_BKG_BEEPING: + if( data->beepCountdown <= 0 ) + { + data->state = STATE_BKG_IDLE; + *out++ = 0.0; /* left */ + *out++ = 0.0; /* right */ + } + else + { + /* Play sawtooth wave. */ + *out++ = data->leftPhase; /* left */ + *out++ = data->rightPhase; /* right */ + /* Generate simple sawtooth phaser that ranges between -1.0 and 1.0. */ + data->leftPhase += 0.01f; + /* When signal reaches top, drop back down. */ + if( data->leftPhase >= 1.0f ) data->leftPhase -= 2.0f; + /* higher pitch so we can distinguish left and right. */ + data->rightPhase += 0.03f; + if( data->rightPhase >= 1.0f ) data->rightPhase -= 2.0f; + } + --data->beepCountdown; + break; + } + } + + return result; +} + +/*******************************************************************/ +static PaError DoTest( int flags ) +{ + PaStream *stream; + PaError err; + paTestData data; + PaStreamParameters outputParameters; + + InitializeTestData( &data ); + + outputParameters.device = Pa_GetDefaultOutputDevice(); + outputParameters.channelCount = 2; + outputParameters.hostApiSpecificStreamInfo = NULL; + outputParameters.sampleFormat = paFloat32; + outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultHighOutputLatency; + + /* Open an audio I/O stream. */ + err = Pa_OpenStream( + &stream, + NULL, /* no input */ + &outputParameters, + SAMPLE_RATE, + FRAMES_PER_BUFFER, /* frames per buffer */ + paClipOff | flags, /* we won't output out of range samples so don't bother clipping them */ + patestCallback, + &data ); + if( err != paNoError ) goto error; + + + err = Pa_StartStream( stream ); + if( err != paNoError ) goto error; + + printf("hear \"BEEP\"\n" ); + fflush(stdout); + + while( ( err = Pa_IsStreamActive( stream ) ) == 1 ) Pa_Sleep(SLEEP_MSEC); + if( err < 0 ) goto error; + + err = Pa_StopStream( stream ); + if( err != paNoError ) goto error; + + err = Pa_CloseStream( stream ); + if( err != paNoError ) goto error; + + return err; +error: + return err; +} + +/*******************************************************************/ +int main(void); +int main(void) +{ + PaError err = paNoError; + int i; + + /* Initialize library before making any other calls. */ + err = Pa_Initialize(); + if( err != paNoError ) goto error; + + printf("PortAudio Test: Testing stream playback with no priming.\n"); + printf("PortAudio Test: you should see BEEP before you hear it.\n"); + printf("BEEP %d times.\n", NUM_BEEPS ); + + for( i=0; i< NUM_BEEPS; ++i ) + { + err = DoTest( 0 ); + if( err != paNoError ) + goto error; + } + + printf("PortAudio Test: Testing stream playback with priming.\n"); + printf("PortAudio Test: you should see BEEP around the same time you hear it.\n"); + for( i=0; i< NUM_BEEPS; ++i ) + { + err = DoTest( paPrimeOutputBuffersUsingStreamCallback ); + if( err != paNoError ) + goto error; + } + + printf("Test finished.\n"); + + Pa_Terminate(); + return err; +error: + Pa_Terminate(); + fprintf( stderr, "An error occured while using the portaudio stream\n" ); + fprintf( stderr, "Error number: %d\n", err ); + fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); + return err; +} diff --git a/pa_tests/patest_read_record.c b/pa_tests/patest_read_record.c new file mode 100644 index 0000000..5e9ca01 --- /dev/null +++ b/pa_tests/patest_read_record.c @@ -0,0 +1,229 @@ +/** @file patest_read_record.c + @brief Record input into an array; Save array to a file; Playback recorded + data. Implemented using the blocking API (Pa_ReadStream(), Pa_WriteStream() ) + @author Phil Burk http://www.softsynth.com + @author Ross Bencina rossb@audiomulch.com +*/ +/* + * $Id$ + * + * This program uses the PortAudio Portable Audio Library. + * For more information see: http://www.portaudio.com + * 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. + * + */ + +#include +#include +#include "portaudio.h" + +/* #define SAMPLE_RATE (17932) // Test failure to open with this value. */ +#define SAMPLE_RATE (44100) +#define FRAMES_PER_BUFFER (1024) +#define NUM_SECONDS (5) +#define NUM_CHANNELS (2) +/* #define DITHER_FLAG (paDitherOff) */ +#define DITHER_FLAG (0) /**/ + +/* Select sample format. */ +#if 1 +#define PA_SAMPLE_TYPE paFloat32 +typedef float SAMPLE; +#define SAMPLE_SILENCE (0.0f) +#define PRINTF_S_FORMAT "%.8f" +#elif 1 +#define PA_SAMPLE_TYPE paInt16 +typedef short SAMPLE; +#define SAMPLE_SILENCE (0) +#define PRINTF_S_FORMAT "%d" +#elif 0 +#define PA_SAMPLE_TYPE paInt8 +typedef char SAMPLE; +#define SAMPLE_SILENCE (0) +#define PRINTF_S_FORMAT "%d" +#else +#define PA_SAMPLE_TYPE paUInt8 +typedef unsigned char SAMPLE; +#define SAMPLE_SILENCE (128) +#define PRINTF_S_FORMAT "%d" +#endif + + +/*******************************************************************/ +int main(void); +int main(void) +{ + PaStreamParameters inputParameters, outputParameters; + PaStream *stream; + PaError err; + SAMPLE *recordedSamples; + int i; + int totalFrames; + int numSamples; + int numBytes; + SAMPLE max, average, val; + + + printf("patest_read_record.c\n"); fflush(stdout); + + totalFrames = NUM_SECONDS * SAMPLE_RATE; /* Record for a few seconds. */ + numSamples = totalFrames * NUM_CHANNELS; + + numBytes = numSamples * sizeof(SAMPLE); + recordedSamples = (SAMPLE *) malloc( numBytes ); + if( recordedSamples == NULL ) + { + printf("Could not allocate record array.\n"); + exit(1); + } + for( i=0; idefaultLowInputLatency; + inputParameters.hostApiSpecificStreamInfo = NULL; + + /* Record some audio. -------------------------------------------- */ + err = Pa_OpenStream( + &stream, + &inputParameters, + NULL, /* &outputParameters, */ + SAMPLE_RATE, + FRAMES_PER_BUFFER, + paClipOff, /* we won't output out of range samples so don't bother clipping them */ + NULL, /* no callback, use blocking API */ + NULL ); /* no callback, so no callback userData */ + if( err != paNoError ) goto error; + + err = Pa_StartStream( stream ); + if( err != paNoError ) goto error; + printf("Now recording!!\n"); fflush(stdout); + + err = Pa_ReadStream( stream, recordedSamples, totalFrames ); + if( err != paNoError ) goto error; + + err = Pa_CloseStream( stream ); + if( err != paNoError ) goto error; + + /* Measure maximum peak amplitude. */ + max = 0; + average = 0; + for( i=0; i max ) + { + max = val; + } + average += val; + } + + average = average / numSamples; + + printf("Sample max amplitude = "PRINTF_S_FORMAT"\n", max ); + printf("Sample average = "PRINTF_S_FORMAT"\n", average ); +/* Was as below. Better choose at compile time because this + keeps generating compiler-warnings: + if( PA_SAMPLE_TYPE == paFloat32 ) + { + printf("sample max amplitude = %f\n", max ); + printf("sample average = %f\n", average ); + } + else + { + printf("sample max amplitude = %d\n", max ); + printf("sample average = %d\n", average ); + } +*/ + /* Write recorded data to a file. */ +#if 0 + { + FILE *fid; + fid = fopen("recorded.raw", "wb"); + if( fid == NULL ) + { + printf("Could not open file."); + } + else + { + fwrite( recordedSamples, NUM_CHANNELS * sizeof(SAMPLE), totalFrames, fid ); + fclose( fid ); + printf("Wrote data to 'recorded.raw'\n"); + } + } +#endif + + /* Playback recorded data. -------------------------------------------- */ + + outputParameters.device = Pa_GetDefaultOutputDevice(); /* default output device */ + outputParameters.channelCount = NUM_CHANNELS; + outputParameters.sampleFormat = PA_SAMPLE_TYPE; + outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency; + outputParameters.hostApiSpecificStreamInfo = NULL; + + printf("Begin playback.\n"); fflush(stdout); + err = Pa_OpenStream( + &stream, + NULL, /* no input */ + &outputParameters, + SAMPLE_RATE, + FRAMES_PER_BUFFER, + paClipOff, /* we won't output out of range samples so don't bother clipping them */ + NULL, /* no callback, use blocking API */ + NULL ); /* no callback, so no callback userData */ + if( err != paNoError ) goto error; + + if( stream ) + { + err = Pa_StartStream( stream ); + if( err != paNoError ) goto error; + printf("Waiting for playback to finish.\n"); fflush(stdout); + + err = Pa_WriteStream( stream, recordedSamples, totalFrames ); + if( err != paNoError ) goto error; + + err = Pa_CloseStream( stream ); + if( err != paNoError ) goto error; + printf("Done.\n"); fflush(stdout); + } + free( recordedSamples ); + + Pa_Terminate(); + return 0; + +error: + Pa_Terminate(); + fprintf( stderr, "An error occured while using the portaudio stream\n" ); + fprintf( stderr, "Error number: %d\n", err ); + fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); + return -1; +} + diff --git a/pa_tests/patest_read_write_wire.c b/pa_tests/patest_read_write_wire.c new file mode 100644 index 0000000..69a7200 --- /dev/null +++ b/pa_tests/patest_read_write_wire.c @@ -0,0 +1,178 @@ +/** @file patest_read_write_wire.c + @brief Tests ifull duplex blocking I/O by passing input straight to output. + @author Bjorn Roche. XO Audio LLC for Z-Systems Engineering. + @author based on code by: Phil Burk http://www.softsynth.com + @author based on code by: Ross Bencina rossb@audiomulch.com +*/ +/* + * $Id: patest_read_record.c 757 2004-02-13 07:48:10Z rossbencina $ + * + * This program uses the PortAudio Portable Audio Library. + * For more information see: http://www.portaudio.com + * 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. + * + */ + +#include +#include +#include "portaudio.h" + +/* #define SAMPLE_RATE (17932) // Test failure to open with this value. */ +#define SAMPLE_RATE (44100) +#define FRAMES_PER_BUFFER (1024) +#define NUM_CHANNELS (2) +/* #define DITHER_FLAG (paDitherOff) */ +#define DITHER_FLAG (0) /**/ + +/* Select sample format. */ +#if 1 +#define PA_SAMPLE_TYPE paFloat32 +typedef float SAMPLE; +#define SAMPLE_SILENCE (0.0f) +#define PRINTF_S_FORMAT "%.8f" +#elif 1 +#define PA_SAMPLE_TYPE paInt16 +typedef short SAMPLE; +#define SAMPLE_SILENCE (0) +#define PRINTF_S_FORMAT "%d" +#elif 0 +#define PA_SAMPLE_TYPE paInt8 +typedef char SAMPLE; +#define SAMPLE_SILENCE (0) +#define PRINTF_S_FORMAT "%d" +#else +#define PA_SAMPLE_TYPE paUInt8 +typedef unsigned char SAMPLE; +#define SAMPLE_SILENCE (128) +#define PRINTF_S_FORMAT "%d" +#endif + + +/*******************************************************************/ +int main(void); +int main(void) +{ + PaStreamParameters inputParameters, outputParameters; + PaStream *stream; + PaError err; + SAMPLE *sampleBlock; + int i; + int numBytes; + + + printf("patest_read_write_wire.c\n"); fflush(stdout); + + numBytes = FRAMES_PER_BUFFER * NUM_CHANNELS * sizeof(SAMPLE); + sampleBlock = (SAMPLE *) malloc( numBytes ); + if( sampleBlock == NULL ) + { + printf("Could not allocate record array.\n"); + exit(1); + } + for( i=0; idefaultLowInputLatency ); + printf( "Input HL: %g s\n", Pa_GetDeviceInfo( inputParameters.device )->defaultHighInputLatency ); + inputParameters.channelCount = NUM_CHANNELS; + inputParameters.sampleFormat = PA_SAMPLE_TYPE; + inputParameters.suggestedLatency = Pa_GetDeviceInfo( inputParameters.device )->defaultHighInputLatency; + inputParameters.hostApiSpecificStreamInfo = NULL; + + outputParameters.device = Pa_GetDefaultOutputDevice(); /* default output device */ + printf( "Output LL: %g s\n", Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency ); + printf( "Output HL: %g s\n", Pa_GetDeviceInfo( outputParameters.device )->defaultHighOutputLatency ); + outputParameters.channelCount = NUM_CHANNELS; + outputParameters.sampleFormat = PA_SAMPLE_TYPE; + outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultHighOutputLatency; + outputParameters.hostApiSpecificStreamInfo = NULL; + + /* -- setup -- */ + + err = Pa_OpenStream( + &stream, + &inputParameters, + &outputParameters, + SAMPLE_RATE, + FRAMES_PER_BUFFER, + paClipOff, /* we won't output out of range samples so don't bother clipping them */ + NULL, /* no callback, use blocking API */ + NULL ); /* no callback, so no callback userData */ + if( err != paNoError ) goto error; + + err = Pa_StartStream( stream ); + if( err != paNoError ) goto error; + printf("Wire on. Will run one minute.\n"); fflush(stdout); + + for( i=0; i<(60*SAMPLE_RATE)/FRAMES_PER_BUFFER; ++i ) + { + err = Pa_WriteStream( stream, sampleBlock, FRAMES_PER_BUFFER ); + if( err ) goto xrun; + err = Pa_ReadStream( stream, sampleBlock, FRAMES_PER_BUFFER ); + if( err ) goto xrun; + } + err = Pa_StopStream( stream ); + if( err != paNoError ) goto error; + + err = Pa_StartStream( stream ); + if( err != paNoError ) goto error; + printf("Wire on. Interrupt to stop.\n"); fflush(stdout); + + while( 1 ) + { + err = Pa_WriteStream( stream, sampleBlock, FRAMES_PER_BUFFER ); + if( err ) goto xrun; + err = Pa_ReadStream( stream, sampleBlock, FRAMES_PER_BUFFER ); + if( err ) goto xrun; + } + err = Pa_StopStream( stream ); + if( err != paNoError ) goto error; + + free( sampleBlock ); + + Pa_Terminate(); + return 0; + +xrun: + Pa_Terminate(); + if( err & paInputOverflow ) + fprintf( stderr, "Input Overflow.\n" ); + if( err & paOutputUnderflow ) + fprintf( stderr, "Output Underflow.\n" ); + return -2; + +error: + Pa_Terminate(); + fprintf( stderr, "An error occured while using the portaudio stream\n" ); + fprintf( stderr, "Error number: %d\n", err ); + fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); + return -1; +} + diff --git a/pa_tests/patest_record.c b/pa_tests/patest_record.c index 11d8791..7ba3582 100644 --- a/pa_tests/patest_record.c +++ b/pa_tests/patest_record.c @@ -1,11 +1,9 @@ +/** @file patest_record.c + @brief Record input into an array; Save array to a file; Playback recorded data. + @author Phil Burk http://www.softsynth.com +*/ /* * $Id$ - * patest_record.c - * Record input into an array. - * Save array to a file. - * Playback recorded data. - * - * Author: Phil Burk http://www.softsynth.com * * This program uses the PortAudio Portable Audio Library. * For more information see: http://www.portaudio.com @@ -35,35 +33,40 @@ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ + #include #include #include "portaudio.h" -/* #define SAMPLE_RATE (17932) /* Test failure to open with this value. */ +/* #define SAMPLE_RATE (17932) // Test failure to open with this value. */ #define SAMPLE_RATE (44100) +#define FRAMES_PER_BUFFER (1024) #define NUM_SECONDS (5) #define NUM_CHANNELS (2) -/* #define DITHER_FLAG (paDitherOff) /**/ +/* #define DITHER_FLAG (paDitherOff) */ #define DITHER_FLAG (0) /**/ /* Select sample format. */ -#if 0 +#if 1 #define PA_SAMPLE_TYPE paFloat32 typedef float SAMPLE; #define SAMPLE_SILENCE (0.0f) -#elif 0 +#define PRINTF_S_FORMAT "%.8f" +#elif 1 #define PA_SAMPLE_TYPE paInt16 typedef short SAMPLE; #define SAMPLE_SILENCE (0) +#define PRINTF_S_FORMAT "%d" #elif 0 #define PA_SAMPLE_TYPE paInt8 typedef char SAMPLE; #define SAMPLE_SILENCE (0) +#define PRINTF_S_FORMAT "%d" #else #define PA_SAMPLE_TYPE paUInt8 typedef unsigned char SAMPLE; #define SAMPLE_SILENCE (128) - +#define PRINTF_S_FORMAT "%d" #endif typedef struct @@ -73,16 +76,19 @@ typedef struct SAMPLE *recordedSamples; } paTestData; + /* This routine will be called by the PortAudio engine when audio is needed. ** It may be called at interrupt level on some machines so don't do anything ** that could mess up the system like calling malloc() or free(). */ -static int recordCallback( void *inputBuffer, void *outputBuffer, +static int recordCallback( const void *inputBuffer, void *outputBuffer, unsigned long framesPerBuffer, - PaTimestamp outTime, void *userData ) + const PaStreamCallbackTimeInfo* timeInfo, + PaStreamCallbackFlags statusFlags, + void *userData ) { paTestData *data = (paTestData*)userData; - SAMPLE *rptr = (SAMPLE*)inputBuffer; + const SAMPLE *rptr = (const SAMPLE*)inputBuffer; SAMPLE *wptr = &data->recordedSamples[data->frameIndex * NUM_CHANNELS]; long framesToCalc; long i; @@ -90,18 +96,21 @@ static int recordCallback( void *inputBuffer, void *outputBuffer, unsigned long framesLeft = data->maxFrameIndex - data->frameIndex; (void) outputBuffer; /* Prevent unused variable warnings. */ - (void) outTime; + (void) timeInfo; + (void) statusFlags; + (void) userData; if( framesLeft < framesPerBuffer ) { framesToCalc = framesLeft; - finished = 1; + finished = paComplete; } else { framesToCalc = framesPerBuffer; - finished = 0; + finished = paContinue; } + if( inputBuffer == NULL ) { for( i=0; irecordedSamples[data->frameIndex * NUM_CHANNELS]; @@ -136,8 +147,11 @@ static int playCallback( void *inputBuffer, void *outputBuffer, unsigned int i; int finished; unsigned int framesLeft = data->maxFrameIndex - data->frameIndex; + (void) inputBuffer; /* Prevent unused variable warnings. */ - (void) outTime; + (void) timeInfo; + (void) statusFlags; + (void) userData; if( framesLeft < framesPerBuffer ) { @@ -153,7 +167,7 @@ static int playCallback( void *inputBuffer, void *outputBuffer, if( NUM_CHANNELS == 2 ) *wptr++ = 0; /* right */ } data->frameIndex += framesLeft; - finished = 1; + finished = paComplete; } else { @@ -163,7 +177,7 @@ static int playCallback( void *inputBuffer, void *outputBuffer, if( NUM_CHANNELS == 2 ) *wptr++ = *rptr++; /* right */ } data->frameIndex += framesPerBuffer; - finished = 0; + finished = paContinue; } return finished; } @@ -172,67 +186,70 @@ static int playCallback( void *inputBuffer, void *outputBuffer, int main(void); int main(void) { - PortAudioStream *stream; - PaError err; - paTestData data; - int i; - int totalFrames; - int numSamples; - int numBytes; - SAMPLE max, average, val; + PaStreamParameters inputParameters, + outputParameters; + PaStream* stream; + PaError err = paNoError; + paTestData data; + int i; + int totalFrames; + int numSamples; + int numBytes; + SAMPLE max, val; + double average; + printf("patest_record.c\n"); fflush(stdout); data.maxFrameIndex = totalFrames = NUM_SECONDS * SAMPLE_RATE; /* Record for a few seconds. */ data.frameIndex = 0; numSamples = totalFrames * NUM_CHANNELS; - numBytes = numSamples * sizeof(SAMPLE); - data.recordedSamples = (SAMPLE *) malloc( numBytes ); + data.recordedSamples = (SAMPLE *) malloc( numBytes ); /* From now on, recordedSamples is initialised. */ if( data.recordedSamples == NULL ) { printf("Could not allocate record array.\n"); - exit(1); + goto done; } for( i=0; idefaultLowInputLatency; + inputParameters.hostApiSpecificStreamInfo = NULL; /* Record some audio. -------------------------------------------- */ err = Pa_OpenStream( &stream, - Pa_GetDefaultInputDeviceID(), - NUM_CHANNELS, /* stereo input */ - PA_SAMPLE_TYPE, - NULL, - paNoDevice, - 0, - PA_SAMPLE_TYPE, - NULL, + &inputParameters, + NULL, /* &outputParameters, */ SAMPLE_RATE, - 1024, /* frames per buffer */ - 0, /* number of buffers, if zero then use default minimum */ - 0, //paDitherOff, /* flags */ + FRAMES_PER_BUFFER, + paClipOff, /* we won't output out of range samples so don't bother clipping them */ recordCallback, &data ); - if( err != paNoError ) goto error; + if( err != paNoError ) goto done; err = Pa_StartStream( stream ); - if( err != paNoError ) goto error; + if( err != paNoError ) goto done; printf("Now recording!!\n"); fflush(stdout); - while( Pa_StreamActive( stream ) ) + while( ( err = Pa_IsStreamActive( stream ) ) == 1 ) { Pa_Sleep(1000); printf("index = %d\n", data.frameIndex ); fflush(stdout); } + if( err < 0 ) goto done; err = Pa_CloseStream( stream ); - if( err != paNoError ) goto error; + if( err != paNoError ) goto done; /* Measure maximum peak amplitude. */ max = 0; - average = 0; + average = 0.0; for( i=0; idefaultLowOutputLatency; + outputParameters.hostApiSpecificStreamInfo = NULL; + printf("Begin playback.\n"); fflush(stdout); err = Pa_OpenStream( &stream, - paNoDevice, - 0, /* NO input */ - PA_SAMPLE_TYPE, - NULL, - Pa_GetDefaultOutputDeviceID(), - NUM_CHANNELS, /* stereo output */ - PA_SAMPLE_TYPE, - NULL, + NULL, /* no input */ + &outputParameters, SAMPLE_RATE, - 1024, /* frames per buffer */ - 0, /* number of buffers, if zero then use default minimum */ - paClipOff, /* we won't output out of range samples so don't bother clipping them */ + FRAMES_PER_BUFFER, + paClipOff, /* we won't output out of range samples so don't bother clipping them */ playCallback, &data ); - if( err != paNoError ) goto error; + if( err != paNoError ) goto done; if( stream ) { err = Pa_StartStream( stream ); - if( err != paNoError ) goto error; + if( err != paNoError ) goto done; + printf("Waiting for playback to finish.\n"); fflush(stdout); - while( Pa_StreamActive( stream ) ) Pa_Sleep(100); - + while( ( err = Pa_IsStreamActive( stream ) ) == 1 ) Pa_Sleep(100); + if( err < 0 ) goto done; + err = Pa_CloseStream( stream ); - if( err != paNoError ) goto error; + if( err != paNoError ) goto done; + printf("Done.\n"); fflush(stdout); } - free( data.recordedSamples ); - - Pa_Terminate(); - return 0; -error: +done: Pa_Terminate(); - fprintf( stderr, "An error occured while using the portaudio stream\n" ); - fprintf( stderr, "Error number: %d\n", err ); - fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); - return -1; + if( data.recordedSamples ) /* Sure it is NULL or valid. */ + free( data.recordedSamples ); + if( err != paNoError ) + { + fprintf( stderr, "An error occured while using the portaudio stream\n" ); + fprintf( stderr, "Error number: %d\n", err ); + fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); + err = 1; /* Always return 0 or 1, but no other return codes. */ + } + return err; } + diff --git a/pa_tests/patest_ringmix.c b/pa_tests/patest_ringmix.c index 0bae220..1df0623 100644 --- a/pa_tests/patest_ringmix.c +++ b/pa_tests/patest_ringmix.c @@ -1,16 +1,53 @@ -/* $Id$ */ +/** @file patest_ringmix.c + @brief Ring modulate inputs to left output, mix inputs to right output. +*/ +/* + * $Id$ + * + * This program uses the PortAudio Portable Audio Library. + * For more information see: http://www.portaudio.com + * 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. + * + */ + #include "stdio.h" #include "portaudio.h" /* This will be called asynchronously by the PortAudio engine. */ -static int myCallback( void *inputBuffer, void *outputBuffer, - unsigned long framesPerBuffer, PaTimestamp outTime, void *userData ) +static int myCallback( const void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + const PaStreamCallbackTimeInfo* timeInfo, + PaStreamCallbackFlags statusFlags, + void *userData ) { - float *out = (float *) outputBuffer; - float *in = (float *) inputBuffer; + const float *in = (const float *) inputBuffer; + float *out = (float *) outputBuffer; float leftInput, rightInput; unsigned int i; - if( inputBuffer == NULL ) return 0; + /* Read input buffer, process data, and fill output buffer. */ for( i=0; i + @author Phil Burk +*/ /* * $Id$ - * patest_sine.c - * Play a sine wave using the Portable Audio api for several seconds. - * - * Authors: - * Ross Bencina - * Phil Burk * * This program uses the PortAudio Portable Audio Library. - * For more information see: http://www.audiomulch.com/portaudio/ + * For more information see: http://www.portaudio.com/ * Copyright (c) 1999-2000 Ross Bencina and Phil Burk * * Permission is hereby granted, free of charge, to any person obtaining @@ -60,16 +59,20 @@ paTestData; ** It may called at interrupt level on some machines so don't do anything ** that could mess up the system like calling malloc() or free(). */ -static int patestCallback( void *inputBuffer, void *outputBuffer, - unsigned long framesPerBuffer, - PaTimestamp outTime, void *userData ) +static int patestCallback( const void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + const PaStreamCallbackTimeInfo* timeInfo, + PaStreamCallbackFlags statusFlags, + void *userData ) { paTestData *data = (paTestData*)userData; float *out = (float*)outputBuffer; unsigned long i; - int finished = 0; - (void) outTime; /* Prevent unused variable warnings. */ + + (void) timeInfo; /* Prevent unused variable warnings. */ + (void) statusFlags; (void) inputBuffer; + for( i=0; isine[data->left_phase]; /* left */ @@ -79,54 +82,65 @@ static int patestCallback( void *inputBuffer, void *outputBuffer, data->right_phase += 3; /* higher pitch so we can distinguish left and right. */ if( data->right_phase >= TABLE_SIZE ) data->right_phase -= TABLE_SIZE; } - return finished; + + return paContinue; } /*******************************************************************/ int main(void); int main(void) { - PortAudioStream *stream; + PaStreamParameters outputParameters; + PaStream *stream; PaError err; paTestData data; int i; + + printf("PortAudio Test: output sine wave. SR = %d, BufSize = %d\n", SAMPLE_RATE, FRAMES_PER_BUFFER); + /* initialise sinusoidal wavetable */ for( i=0; idefaultLowOutputLatency; + outputParameters.hostApiSpecificStreamInfo = NULL; + err = Pa_OpenStream( &stream, - paNoDevice,/* default input device */ - 0, /* no input */ - paFloat32, /* 32 bit floating point input */ - NULL, - Pa_GetDefaultOutputDeviceID(), /* default output device */ - 2, /* stereo output */ - paFloat32, /* 32 bit floating point output */ - NULL, + NULL, /* no input */ + &outputParameters, SAMPLE_RATE, FRAMES_PER_BUFFER, - 0, /* number of buffers, if zero then use default minimum */ paClipOff, /* we won't output out of range samples so don't bother clipping them */ patestCallback, &data ); if( err != paNoError ) goto error; + err = Pa_StartStream( stream ); if( err != paNoError ) goto error; + printf("Play for %d seconds.\n", NUM_SECONDS ); Pa_Sleep( NUM_SECONDS * 1000 ); err = Pa_StopStream( stream ); if( err != paNoError ) goto error; + err = Pa_CloseStream( stream ); if( err != paNoError ) goto error; + Pa_Terminate(); printf("Test finished.\n"); + return err; error: Pa_Terminate(); diff --git a/pa_tests/patest_sine8.c b/pa_tests/patest_sine8.c index 73154c9..5a9d1fe 100644 --- a/pa_tests/patest_sine8.c +++ b/pa_tests/patest_sine8.c @@ -1,10 +1,9 @@ +/** @file patest_sine8.c + @brief Test 8 bit data: play a sine wave for several seconds. + @author Ross Bencina +*/ /* * $Id$ - * patest_sine8.c - * Play a sine wave using the Portable Audio api for several seconds. - * Test 8 bit data. - * - * Author: Ross Bencina * * This program uses the PortAudio Portable Audio Library. * For more information see: http://www.audiomulch.com/portaudio/ @@ -34,21 +33,26 @@ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ + #include #include #include "portaudio.h" + #define NUM_SECONDS (8) #define SAMPLE_RATE (44100) -#define TEST_UNSIGNED (1) +#define TABLE_SIZE (200) +#define TEST_UNSIGNED (0) + #if TEST_UNSIGNED -#define TEST_FORMAT paUInt8 +#define TEST_FORMAT paUInt8 #else -#define TEST_FORMAT paInt8 +#define TEST_FORMAT paInt8 #endif + #ifndef M_PI -#define M_PI (3.14159265) +#define M_PI (3.14159265) #endif -#define TABLE_SIZE (200) + typedef struct { #if TEST_UNSIGNED @@ -61,21 +65,23 @@ typedef struct unsigned int framesToGo; } paTestData; + /* This routine will be called by the PortAudio engine when audio is needed. ** It may called at interrupt level on some machines so don't do anything ** that could mess up the system like calling malloc() or free(). */ -static int patestCallback( void *inputBuffer, void *outputBuffer, +static int patestCallback( const void *inputBuffer, void *outputBuffer, unsigned long framesPerBuffer, - PaTimestamp outTime, void *userData ) + const PaStreamCallbackTimeInfo* timeInfo, + PaStreamCallbackFlags statusFlags, + void *userData ) { paTestData *data = (paTestData*)userData; char *out = (char*)outputBuffer; int i; int framesToCalc; int finished = 0; - (void) outTime; /* Prevent unused variable warnings. */ - (void) inputBuffer; + (void) inputBuffer; /* Prevent unused variable warnings. */ if( data->framesToGo < framesPerBuffer ) { @@ -112,15 +118,18 @@ static int patestCallback( void *inputBuffer, void *outputBuffer, } return finished; } + /*******************************************************************/ int main(void); int main(void) { - PortAudioStream *stream; - PaError err; - paTestData data; - int i; - int totalSamps; + PaStreamParameters outputParameters; + PaStream* stream; + PaError err; + paTestData data; + PaTime streamOpened; + int i, totalSamps; + #if TEST_UNSIGNED printf("PortAudio Test: output UNsigned 8 bit sine wave.\n"); #else @@ -133,45 +142,64 @@ int main(void) #if TEST_UNSIGNED data.sine[i] += (unsigned char) 0x80; #endif - } data.left_phase = data.right_phase = 0; data.framesToGo = totalSamps = NUM_SECONDS * SAMPLE_RATE; /* Play for a few seconds. */ + err = Pa_Initialize(); - if( err != paNoError ) goto error; - err = Pa_OpenStream( - &stream, - paNoDevice,/* default input device */ - 0, /* no input */ - TEST_FORMAT, - NULL, - Pa_GetDefaultOutputDeviceID(), /* default output device */ - 2, /* stereo output */ - TEST_FORMAT, - NULL, - SAMPLE_RATE, - 256, /* frames per buffer */ - 0, /* number of buffers, if zero then use default minimum */ - paClipOff, /* we won't output out of range samples so don't bother clipping them */ - patestCallback, - &data ); - if( err != paNoError ) goto error; + if( err != paNoError ) + goto error; + + outputParameters.device = Pa_GetDefaultOutputDevice(); /* Default output device. */ + outputParameters.channelCount = 2; /* Stereo output. */ + outputParameters.sampleFormat = TEST_FORMAT; + outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency; + outputParameters.hostApiSpecificStreamInfo = NULL; + err = Pa_OpenStream( &stream, + NULL, /* No input. */ + &outputParameters, + SAMPLE_RATE, + 256, /* Frames per buffer. */ + paClipOff, /* We won't output out of range samples so don't bother clipping them. */ + patestCallback, + &data ); + if( err != paNoError ) + goto error; + + streamOpened = Pa_GetStreamTime( stream ); /* Time in seconds when stream was opened (approx). */ + err = Pa_StartStream( stream ); - if( err != paNoError ) goto error; + if( err != paNoError ) + goto error; + /* Watch until sound is halfway finished. */ - while( Pa_StreamTime( stream ) < (totalSamps/2) ) Pa_Sleep(10); - /* Stop sound until ENTER hit. */ + /* (Was ( Pa_StreamTime( stream ) < (totalSamps/2) ) in V18. */ + while( (Pa_GetStreamTime( stream ) - streamOpened) < (PaTime)NUM_SECONDS / 2.0 ) + Pa_Sleep(10); + + /* Stop sound until ENTER hit. (Hu? don't see any keyboard-input here.) */ err = Pa_StopStream( stream ); - if( err != paNoError ) goto error; + if( err != paNoError ) + goto error; + printf("Pause for 2 seconds.\n"); Pa_Sleep( 2000 ); err = Pa_StartStream( stream ); - if( err != paNoError ) goto error; + if( err != paNoError ) + goto error; + printf("Waiting for sound to finish.\n"); - while( Pa_StreamActive( stream ) ) Pa_Sleep(10); + + while( ( err = Pa_IsStreamActive( stream ) ) == 1 ) + Pa_Sleep(100); + if( err < 0 ) + goto error; + err = Pa_CloseStream( stream ); - if( err != paNoError ) goto error; + if( err != paNoError ) + goto error; + Pa_Terminate(); printf("Test finished.\n"); return err; diff --git a/pa_tests/patest_sine_formats.c b/pa_tests/patest_sine_formats.c index ea92603..448a4eb 100644 --- a/pa_tests/patest_sine_formats.c +++ b/pa_tests/patest_sine_formats.c @@ -1,10 +1,9 @@ +/** @file patest_sine_formats.c + @brief Play a sine wave for several seconds. Test various data formats. + @author Phil Burk +*/ /* * $Id$ - * patest_sine_formats.c - * Play a sine wave using the Portable Audio api for several seconds. - * Test various data formats. - * - * Author: Phil Burk * * This program uses the PortAudio Portable Audio Library. * For more information see: http://www.audiomulch.com/portaudio/ @@ -38,7 +37,7 @@ #include #include "portaudio.h" -#define NUM_SECONDS (20) +#define NUM_SECONDS (10) #define SAMPLE_RATE (44100) #define FRAMES_PER_BUFFER (512) #define LEFT_FREQ (SAMPLE_RATE/256.0) /* So we hit 1.0 */ @@ -96,17 +95,19 @@ paTestData; ** It may called at interrupt level on some machines so don't do anything ** that could mess up the system like calling malloc() or free(). */ -static int patestCallback( void *inputBuffer, void *outputBuffer, +static int patestCallback( const void *inputBuffer, + void *outputBuffer, unsigned long framesPerBuffer, - PaTimestamp outTime, void *userData ) + const PaStreamCallbackTimeInfo* timeInfo, + PaStreamCallbackFlags statusFlags, + void *userData ) { paTestData *data = (paTestData*)userData; SAMPLE_t *out = (SAMPLE_t *)outputBuffer; int i; int framesToCalc; int finished = 0; - (void) outTime; /* Prevent unused variable warnings. */ - (void) inputBuffer; + (void) inputBuffer; /* Prevent unused variable warnings. */ if( data->framesToGo < framesPerBuffer ) { @@ -142,42 +143,42 @@ static int patestCallback( void *inputBuffer, void *outputBuffer, int main(void); int main(void) { - PortAudioStream *stream; + PaStream *stream; + PaStreamParameters outputParameters; PaError err; paTestData data; int totalSamps; printf("PortAudio Test: output " FORMAT_NAME "\n"); - data.left_phase = data.right_phase = 0.0; data.framesToGo = totalSamps = NUM_SECONDS * SAMPLE_RATE; /* Play for a few seconds. */ err = Pa_Initialize(); if( err != paNoError ) goto error; - err = Pa_OpenStream( - &stream, - paNoDevice,/* default input device */ - 0, /* no input */ - TEST_FORMAT, - NULL, - Pa_GetDefaultOutputDeviceID(), /* default output device */ - 2, /* stereo output */ - TEST_FORMAT, - NULL, - SAMPLE_RATE, - FRAMES_PER_BUFFER, - 0, /* number of buffers, if zero then use default minimum */ - paClipOff, /* we won't output out of range samples so don't bother clipping them */ - patestCallback, - &data ); + + outputParameters.device = Pa_GetDefaultOutputDevice(); /* Default output device. */ + outputParameters.channelCount = 2; /* Stereo output */ + outputParameters.sampleFormat = TEST_FORMAT; /* Selected above. */ + outputParameters.suggestedLatency = Pa_GetDeviceInfo(outputParameters.device)->defaultLowOutputLatency; + outputParameters.hostApiSpecificStreamInfo = NULL; + err = Pa_OpenStream( &stream, + NULL, /* No input. */ + &outputParameters, /* As above. */ + SAMPLE_RATE, + FRAMES_PER_BUFFER, + paClipOff, /* we won't output out of range samples so don't bother clipping them */ + patestCallback, + &data ); if( err != paNoError ) goto error; err = Pa_StartStream( stream ); if( err != paNoError ) goto error; printf("Waiting %d seconds for sound to finish.\n", NUM_SECONDS ); - while( Pa_StreamActive( stream ) ) Pa_Sleep(10); + + while( ( err = Pa_IsStreamActive( stream ) ) == 1 ) Pa_Sleep(100); + if( err < 0 ) goto error; err = Pa_CloseStream( stream ); if( err != paNoError ) goto error; diff --git a/pa_tests/patest_sine_time.c b/pa_tests/patest_sine_time.c index 9c3f0af..cf45275 100644 --- a/pa_tests/patest_sine_time.c +++ b/pa_tests/patest_sine_time.c @@ -1,13 +1,11 @@ +/** @file patest_sine_time.c + @brief Play a sine wave for several seconds, pausing in the middle. + Uses the Pa_GetStreamTime() call. + @author Ross Bencina + @author Phil Burk +*/ /* * $Id$ - * patest_sine_time.c - * Play a sine wave using the Portable Audio api for several seconds. - * Pausing in the middle. - * use the Pa_StreamTime() and Pa_StreamActive() calls. - * - * Authors: - * Ross Bencina - * Phil Burk * * This program uses the PortAudio Portable Audio Library. * For more information see: http://www.audiomulch.com/portaudio/ @@ -39,78 +37,78 @@ */ #include #include + #include "portaudio.h" +#include "pa_util.h" + #define NUM_SECONDS (8) #define SAMPLE_RATE (44100) #define FRAMES_PER_BUFFER (64) -#define NUM_BUFFERS (0) + #ifndef M_PI #define M_PI (3.14159265) #endif +#define TWOPI (M_PI * 2.0) + #define TABLE_SIZE (200) + typedef struct { - float sine[TABLE_SIZE]; - int left_phase; - int right_phase; - int framesToGo; - volatile PaTimestamp outTime; + double left_phase; + double right_phase; + volatile PaTime outTime; } paTestData; + /* This routine will be called by the PortAudio engine when audio is needed. ** It may called at interrupt level on some machines so don't do anything ** that could mess up the system like calling malloc() or free(). */ -static int patestCallback( void *inputBuffer, void *outputBuffer, - unsigned long framesPerBuffer, - PaTimestamp outTime, void *userData ) +static int patestCallback( const void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + const PaStreamCallbackTimeInfo* timeInfo, + PaStreamCallbackFlags statusFlags, + void *userData ) { paTestData *data = (paTestData*)userData; float *out = (float*)outputBuffer; - int i; - int framesToCalc; - int finished = 0; - (void) outTime; /* Prevent unused variable warnings. */ + unsigned int i; + + double left_phaseInc = 0.02; + double right_phaseInc = 0.06; + + double left_phase = data->left_phase; + double right_phase = data->right_phase; + + (void) statusFlags; /* Prevent unused variable warnings. */ (void) inputBuffer; - data->outTime = outTime; - - if( data->framesToGo < framesPerBuffer ) - { - framesToCalc = data->framesToGo; - data->framesToGo = 0; - finished = 1; - } - else - { - framesToCalc = framesPerBuffer; - data->framesToGo -= framesPerBuffer; - } + data->outTime = timeInfo->outputBufferDacTime; - for( i=0; isine[data->left_phase]; /* left */ - *out++ = data->sine[data->right_phase]; /* right */ - data->left_phase += 1; - if( data->left_phase >= TABLE_SIZE ) data->left_phase -= TABLE_SIZE; - data->right_phase += 3; /* higher pitch so we can distinguish left and right. */ - if( data->right_phase >= TABLE_SIZE ) data->right_phase -= TABLE_SIZE; - } - /* zero remainder of final buffer */ - for( ; i<(int)framesPerBuffer; i++ ) - { - *out++ = 0; /* left */ - *out++ = 0; /* right */ + left_phase += left_phaseInc; + if( left_phase > TWOPI ) left_phase -= TWOPI; + *out++ = (float) sin( left_phase ); + + right_phase += right_phaseInc; + if( right_phase > TWOPI ) right_phase -= TWOPI; + *out++ = (float) sin( right_phase ); } - return finished; + + data->left_phase = left_phase; + data->right_phase = right_phase; + + return paContinue; } + /*******************************************************************/ -static void ReportStreamTime( PortAudioStream *stream, paTestData *data ); -static void ReportStreamTime( PortAudioStream *stream, paTestData *data ) +static void ReportStreamTime( PaStream *stream, paTestData *data ); +static void ReportStreamTime( PaStream *stream, paTestData *data ) { - PaTimestamp streamTime, latency, outTime; + PaTime streamTime, latency, outTime; - streamTime = Pa_StreamTime( stream ); + streamTime = Pa_GetStreamTime( stream ); outTime = data->outTime; if( outTime < 0.0 ) { @@ -119,7 +117,7 @@ static void ReportStreamTime( PortAudioStream *stream, paTestData *data ) else { latency = outTime - streamTime; - printf("Stream time = %8.1f, outTime = %8.1f, latency = %8.1f\n", + printf("Stream time = %8.4f, outTime = %8.4f, latency = %8.4f\n", streamTime, outTime, latency ); } fflush(stdout); @@ -129,73 +127,78 @@ static void ReportStreamTime( PortAudioStream *stream, paTestData *data ) int main(void); int main(void) { - PortAudioStream *stream; + PaStreamParameters outputParameters; + PaStream *stream; PaError err; - paTestData DATA; - int i; - int totalSamps; + paTestData data; + PaTime startTime; + printf("PortAudio Test: output sine wave. SR = %d, BufSize = %d\n", SAMPLE_RATE, FRAMES_PER_BUFFER); - /* initialise sinusoidal wavetable */ - for( i=0; idefaultLowOutputLatency; + outputParameters.hostApiSpecificStreamInfo = NULL; + err = Pa_OpenStream( &stream, - paNoDevice,/* default input device */ - 0, /* no input */ - paFloat32, /* 32 bit floating point input */ - NULL, - Pa_GetDefaultOutputDeviceID(), /* default output device */ - 2, /* stereo output */ - paFloat32, /* 32 bit floating point output */ - NULL, + NULL, /* no input */ + &outputParameters, SAMPLE_RATE, - FRAMES_PER_BUFFER, /* frames per buffer */ - NUM_BUFFERS, /* number of buffers, if zero then use default minimum */ + FRAMES_PER_BUFFER, paClipOff, /* we won't output out of range samples so don't bother clipping them */ patestCallback, - &DATA ); - if( err != paNoError ) goto error; - - DATA.outTime = -1.0; // mark time for callback as undefined - err = Pa_StartStream( stream ); + &data ); if( err != paNoError ) goto error; - + /* Watch until sound is halfway finished. */ printf("Play for %d seconds.\n", NUM_SECONDS/2 ); fflush(stdout); + + data.outTime = -1.0; /* mark time for callback as undefined */ + err = Pa_StartStream( stream ); + if( err != paNoError ) goto error; + + startTime = Pa_GetStreamTime( stream ); + do { - ReportStreamTime( stream, &DATA ); + ReportStreamTime( stream, &data ); Pa_Sleep(100); - } while( Pa_StreamTime( stream ) < (totalSamps/2) ); + } while( (Pa_GetStreamTime( stream ) - startTime) < (NUM_SECONDS/2) ); - /* Stop sound until ENTER hit. */ + /* Stop sound for 2 seconds. */ err = Pa_StopStream( stream ); if( err != paNoError ) goto error; + printf("Pause for 2 seconds.\n"); fflush(stdout); Pa_Sleep( 2000 ); - DATA.outTime = -1.0; // mark time for callback as undefined + data.outTime = -1.0; /* mark time for callback as undefined */ err = Pa_StartStream( stream ); if( err != paNoError ) goto error; + + startTime = Pa_GetStreamTime( stream ); printf("Play until sound is finished.\n"); fflush(stdout); do { - ReportStreamTime( stream, &DATA ); + ReportStreamTime( stream, &data ); Pa_Sleep(100); - } while( Pa_StreamActive( stream ) ); + } while( (Pa_GetStreamTime( stream ) - startTime) < (NUM_SECONDS/2) ); err = Pa_CloseStream( stream ); if( err != paNoError ) goto error; + Pa_Terminate(); printf("Test finished.\n"); return err; + error: Pa_Terminate(); fprintf( stderr, "An error occured while using the portaudio stream\n" ); diff --git a/pa_tests/patest_start_stop.c b/pa_tests/patest_start_stop.c new file mode 100644 index 0000000..03ade17 --- /dev/null +++ b/pa_tests/patest_start_stop.c @@ -0,0 +1,162 @@ +/** @file patest_start_stop.c + @brief Play a sine wave for several seconds + - start and stop the stream multiple times. + + @author Ross Bencina + @author Phil Burk +*/ +/* + * $Id$ + * + * This program uses the PortAudio Portable Audio Library. + * For more information see: http://www.portaudio.com/ + * 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. + * + */ +#include +#include +#include "portaudio.h" + +#define OUTPUT_DEVICE Pa_GetDefaultOutputDevice() /* default output device */ + +#define NUM_SECONDS (3) +#define NUM_LOOPS (4) +#define SAMPLE_RATE (44100) +#define FRAMES_PER_BUFFER (400) + +#ifndef M_PI +#define M_PI (3.14159265) +#endif + +#define TABLE_SIZE (200) +typedef struct +{ + float sine[TABLE_SIZE]; + int left_phase; + int right_phase; +} +paTestData; + +/* This routine will be called by the PortAudio engine when audio is needed. +** It may called at interrupt level on some machines so don't do anything +** that could mess up the system like calling malloc() or free(). +*/ +static int patestCallback( const void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + const PaStreamCallbackTimeInfo* timeInfo, + PaStreamCallbackFlags statusFlags, + void *userData ) +{ + paTestData *data = (paTestData*)userData; + float *out = (float*)outputBuffer; + unsigned long i; + + (void) timeInfo; /* Prevent unused variable warnings. */ + (void) statusFlags; + (void) inputBuffer; + + for( i=0; isine[data->left_phase]; /* left */ + *out++ = data->sine[data->right_phase]; /* right */ + data->left_phase += 1; + if( data->left_phase >= TABLE_SIZE ) data->left_phase -= TABLE_SIZE; + data->right_phase += 3; /* higher pitch so we can distinguish left and right. */ + if( data->right_phase >= TABLE_SIZE ) data->right_phase -= TABLE_SIZE; + } + + return paContinue; +} + +/*******************************************************************/ +int main(void); +int main(void) +{ + PaStreamParameters outputParameters; + PaStream *stream; + PaError err; + paTestData data; + int i; + + + printf("PortAudio Test: output sine wave. SR = %d, BufSize = %d\n", SAMPLE_RATE, FRAMES_PER_BUFFER); + + /* initialise sinusoidal wavetable */ + for( i=0; idefaultLowOutputLatency; + outputParameters.hostApiSpecificStreamInfo = NULL; + + err = Pa_OpenStream( + &stream, + NULL, /* no input */ + &outputParameters, + SAMPLE_RATE, + FRAMES_PER_BUFFER, + paClipOff, /* we won't output out of range samples so don't bother clipping them */ + patestCallback, + &data ); + if( err != paNoError ) goto error; + + for( i=0; i +*/ /* * $Id$ - * patest_stop.c - * - * Test the three ways of stopping audio: - * calling Pa_StopStream(), - * calling Pa_AbortStream(), - * and returning a 1 from the callback function. - * - * A long latency is set up so that you can hear the difference. - * Then a simple 8 note sequence is repeated twice. - * The program will print what you should hear. - * - * Author: Phil Burk * * This program uses the PortAudio Portable Audio Library. * For more information see: http://www.portaudio.com @@ -44,12 +46,12 @@ #include #include #include "portaudio.h" -#define OUTPUT_DEVICE (Pa_GetDefaultOutputDeviceID()) + +#define OUTPUT_DEVICE (Pa_GetDefaultOutputDevice()) #define SLEEP_DUR (200) #define SAMPLE_RATE (44100) #define FRAMES_PER_BUFFER (256) -#define LATENCY_MSEC (3000) -#define NUM_BUFFERS ((LATENCY_MSEC * SAMPLE_RATE) / (FRAMES_PER_BUFFER * 1000)) +#define LATENCY_SECONDS (3.f) #define FRAMES_PER_NOTE (SAMPLE_RATE/2) #define MAX_REPEATS (2) #define FUNDAMENTAL (400.0f / SAMPLE_RATE) @@ -65,9 +67,10 @@ #define M_PI (3.14159265) #endif #define TABLE_SIZE (400) + typedef struct { - float waveform[TABLE_SIZE + 1]; // add one for guard point for interpolation + float waveform[TABLE_SIZE + 1]; /* Add one for guard point for interpolation. */ float phase_increment; float phase; float *tune; @@ -75,14 +78,16 @@ typedef struct int frameCounter; int noteCounter; int repeatCounter; - PaTimestamp outTime; + PaTime outTime; int stopMode; int done; } paTestData; + /************* Prototypes *****************************/ int TestStopMode( paTestData *data ); float LookupWaveform( paTestData *data, float phase ); + /****************************************************** * Convert phase between 0.0 and 1.0 to waveform value * using linear interpolation. @@ -97,23 +102,30 @@ float LookupWaveform( paTestData *data, float phase ) float val = lo + fract*(hi-lo); return val; } + /* This routine will be called by the PortAudio engine when audio is needed. ** It may called at interrupt level on some machines so don't do anything ** that could mess up the system like calling malloc() or free(). */ -static int patestCallback( void *inputBuffer, void *outputBuffer, - unsigned long framesPerBuffer, - PaTimestamp outTime, void *userData ) +static int patestCallback( const void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + const PaStreamCallbackTimeInfo* timeInfo, + PaStreamCallbackFlags statusFlags, + void *userData ) { paTestData *data = (paTestData*)userData; float *out = (float*)outputBuffer; float value; unsigned int i = 0; - int finished = 0; - (void) outTime; /* Prevent unused variable warnings. */ - (void) inputBuffer; + int finished = paContinue; + + (void) inputBuffer; /* Prevent unused variable warnings. */ + (void) timeInfo; + (void) statusFlags; - data->outTime = outTime; + + /* data->outTime = outTime; */ + if( !data->done ) { for( i=0; idone = 1; if( data->stopMode == MODE_FINISH ) { - finished = 1; + finished = paComplete; break; } } @@ -162,92 +174,103 @@ static int patestCallback( void *inputBuffer, void *outputBuffer, int main(void); int main(void) { - paTestData DATA; + paTestData data; int i; float simpleTune[] = { NOTE_0, NOTE_1, NOTE_2, NOTE_3, NOTE_4, NOTE_3, NOTE_2, NOTE_1 }; - printf("PortAudio Test: play song and test stopping. ask for %d buffers\n", NUM_BUFFERS ); + + printf("PortAudio Test: play song and test stopping. ask for %f seconds latency\n", LATENCY_SECONDS ); /* initialise sinusoidal wavetable */ for( i=0; idone = 0; data->phase = 0.0; data->frameCounter = 0; data->noteCounter = 0; data->repeatCounter = 0; data->phase_increment = data->tune[data->noteCounter]; + err = Pa_Initialize(); if( err != paNoError ) goto error; + + outputParameters.device = OUTPUT_DEVICE; + outputParameters.channelCount = 2; /* stereo output */ + outputParameters.sampleFormat = paFloat32; /* 32 bit floating point output */ + outputParameters.suggestedLatency = LATENCY_SECONDS; + outputParameters.hostApiSpecificStreamInfo = NULL; + err = Pa_OpenStream( &stream, - paNoDevice,/* default input device */ - 0, /* no input */ - paFloat32, /* 32 bit floating point input */ - NULL, - OUTPUT_DEVICE, - 2, /* stereo output */ - paFloat32, /* 32 bit floating point output */ - NULL, + NULL, /* no input */ + &outputParameters, SAMPLE_RATE, FRAMES_PER_BUFFER, /* frames per buffer */ - NUM_BUFFERS, /* number of buffers, if zero then use default minimum */ paClipOff, /* we won't output out of range samples so don't bother clipping them */ patestCallback, data ); if( err != paNoError ) goto error; + err = Pa_StartStream( stream ); if( err != paNoError ) goto error; + if( data->stopMode == MODE_FINISH ) { - while( Pa_StreamActive( stream ) ) + while( ( err = Pa_IsStreamActive( stream ) ) == 1 ) { /*printf("outTime = %g, note# = %d, repeat# = %d\n", data->outTime, data->noteCounter, data->repeatCounter ); - fflush(stdout); /**/ + fflush(stdout); */ Pa_Sleep( SLEEP_DUR ); } + if( err < 0 ) goto error; } else { @@ -255,10 +278,11 @@ int TestStopMode( paTestData *data ) { /*printf("outTime = %g, note# = %d, repeat# = %d\n", data->outTime, data->noteCounter, data->repeatCounter ); - fflush(stdout); /**/ + fflush(stdout); */ Pa_Sleep( SLEEP_DUR ); } } + if( data->stopMode == MODE_ABORT ) { printf("Call Pa_AbortStream()\n"); @@ -270,12 +294,16 @@ int TestStopMode( paTestData *data ) err = Pa_StopStream( stream ); } if( err != paNoError ) goto error; + printf("Call Pa_CloseStream()\n"); fflush(stdout); err = Pa_CloseStream( stream ); if( err != paNoError ) goto error; + Pa_Terminate(); printf("Test finished.\n"); + return err; + error: Pa_Terminate(); fprintf( stderr, "An error occured while using the portaudio stream\n" ); diff --git a/pa_tests/patest_stop_playout.c b/pa_tests/patest_stop_playout.c new file mode 100644 index 0000000..41134d5 --- /dev/null +++ b/pa_tests/patest_stop_playout.c @@ -0,0 +1,432 @@ +/** @file patest_stop_playout.c + @brief Test whether all queued samples are played when Pa_StopStream() + is used with a callback or read/write stream, or when the callback + returns paComplete. + @author Ross Bencina +*/ +/* + * $Id$ + * + * This program uses the PortAudio Portable Audio Library. + * For more information see: http://www.portaudio.com/ + * Copyright (c) 1999-2004 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. + * + */ +#include +#include +#include "portaudio.h" + +#define SAMPLE_RATE (44100) +#define FRAMES_PER_BUFFER (1024) + +#define TONE_SECONDS (1) /* long tone */ +#define TONE_FADE_SECONDS (.04) /* fades at start and end of long tone */ +#define GAP_SECONDS (.25) /* gap between long tone and blip */ +#define BLIP_SECONDS (.035) /* short blip */ + +#define NUM_REPEATS (3) + +#ifndef M_PI +#define M_PI (3.14159265) +#endif + +#define TABLE_SIZE (2048) +typedef struct +{ + float sine[TABLE_SIZE+1]; + + int repeatCount; + + double phase; + double lowIncrement, highIncrement; + + int gap1Length, toneLength, toneFadesLength, gap2Length, blipLength; + int gap1Countdown, toneCountdown, gap2Countdown, blipCountdown; +} +TestData; + + +static void RetriggerTestSignalGenerator( TestData *data ) +{ + data->phase = 0.; + data->gap1Countdown = data->gap1Length; + data->toneCountdown = data->toneLength; + data->gap2Countdown = data->gap2Length; + data->blipCountdown = data->blipLength; +} + + +static void ResetTestSignalGenerator( TestData *data ) +{ + data->repeatCount = 0; + RetriggerTestSignalGenerator( data ); +} + + +static void InitTestSignalGenerator( TestData *data ) +{ + int signalLengthModBufferLength, i; + + /* initialise sinusoidal wavetable */ + for( i=0; isine[i] = (float) sin( ((double)i/(double)TABLE_SIZE) * M_PI * 2. ); + } + data->sine[TABLE_SIZE] = data->sine[0]; /* guard point for linear interpolation */ + + + + data->lowIncrement = (330. / SAMPLE_RATE) * TABLE_SIZE; + data->highIncrement = (1760. / SAMPLE_RATE) * TABLE_SIZE; + + data->gap1Length = GAP_SECONDS * SAMPLE_RATE; + data->toneLength = TONE_SECONDS * SAMPLE_RATE; + data->toneFadesLength = TONE_FADE_SECONDS * SAMPLE_RATE; + data->gap2Length = GAP_SECONDS * SAMPLE_RATE; + data->blipLength = BLIP_SECONDS * SAMPLE_RATE; + + /* adjust signal length to be a multiple of the buffer length */ + signalLengthModBufferLength = (data->gap1Length + data->toneLength + data->gap2Length + data->blipLength) % FRAMES_PER_BUFFER; + if( signalLengthModBufferLength > 0 ) + data->toneLength += signalLengthModBufferLength; + + ResetTestSignalGenerator( data ); +} + + +#define MIN( a, b ) (((a)<(b))?(a):(b)) + +static void GenerateTestSignal( TestData *data, float *stereo, int frameCount ) +{ + int framesGenerated = 0; + float output; + long index; + float fraction; + int count, i; + + while( framesGenerated < frameCount && data->repeatCount < NUM_REPEATS ) + { + if( framesGenerated < frameCount && data->gap1Countdown > 0 ){ + count = MIN( frameCount - framesGenerated, data->gap1Countdown ); + for( i=0; i < count; ++i ) + { + *stereo++ = 0.f; + *stereo++ = 0.f; + } + + data->gap1Countdown -= count; + framesGenerated += count; + } + + if( framesGenerated < frameCount && data->toneCountdown > 0 ){ + count = MIN( frameCount - framesGenerated, data->toneCountdown ); + for( i=0; i < count; ++i ) + { + /* tone with data->lowIncrement phase increment */ + index = (long)data->phase; + fraction = data->phase - index; + output = data->sine[ index ] + (data->sine[ index + 1 ] - data->sine[ index ]) * fraction; + + data->phase += data->lowIncrement; + while( data->phase >= TABLE_SIZE ) + data->phase -= TABLE_SIZE; + + /* apply fade to ends */ + + if( data->toneCountdown < data->toneFadesLength ) + { + /* cosine-bell fade out at end */ + output *= (-cos(((float)data->toneCountdown / (float)data->toneFadesLength) * M_PI) + 1.) * .5; + } + else if( data->toneCountdown > data->toneLength - data->toneFadesLength ) + { + /* cosine-bell fade in at start */ + output *= (cos(((float)(data->toneCountdown - (data->toneLength - data->toneFadesLength)) / (float)data->toneFadesLength) * M_PI) + 1.) * .5; + } + + output *= .5; /* play tone half as loud as blip */ + + *stereo++ = output; + *stereo++ = output; + + data->toneCountdown--; + } + + framesGenerated += count; + } + + if( framesGenerated < frameCount && data->gap2Countdown > 0 ){ + count = MIN( frameCount - framesGenerated, data->gap2Countdown ); + for( i=0; i < count; ++i ) + { + *stereo++ = 0.f; + *stereo++ = 0.f; + } + + data->gap2Countdown -= count; + framesGenerated += count; + } + + if( framesGenerated < frameCount && data->blipCountdown > 0 ){ + count = MIN( frameCount - framesGenerated, data->blipCountdown ); + for( i=0; i < count; ++i ) + { + /* tone with data->highIncrement phase increment */ + index = (long)data->phase; + fraction = data->phase - index; + output = data->sine[ index ] + (data->sine[ index + 1 ] - data->sine[ index ]) * fraction; + + data->phase += data->highIncrement; + while( data->phase >= TABLE_SIZE ) + data->phase -= TABLE_SIZE; + + /* cosine-bell envelope over whole blip */ + output *= (-cos( ((float)data->blipCountdown / (float)data->blipLength) * 2. * M_PI) + 1.) * .5; + + *stereo++ = output; + *stereo++ = output; + + data->blipCountdown--; + } + + framesGenerated += count; + } + + + if( data->blipCountdown == 0 ) + { + RetriggerTestSignalGenerator( data ); + data->repeatCount++; + } + } + + if( framesGenerated < frameCount ) + { + count = frameCount - framesGenerated; + for( i=0; i < count; ++i ) + { + *stereo++ = 0.f; + *stereo++ = 0.f; + } + } +} + + +static int IsTestSignalFinished( TestData *data ) +{ + if( data->repeatCount >= NUM_REPEATS ) + return 1; + else + return 0; +} + + +static int TestCallback1( const void *inputBuffer, void *outputBuffer, + unsigned long frameCount, + const PaStreamCallbackTimeInfo* timeInfo, + PaStreamCallbackFlags statusFlags, + void *userData ) +{ + (void) inputBuffer; /* Prevent unused variable warnings. */ + (void) timeInfo; + (void) statusFlags; + + GenerateTestSignal( (TestData*)userData, (float*)outputBuffer, frameCount ); + + if( IsTestSignalFinished( (TestData*)userData ) ) + return paComplete; + else + return paContinue; +} + + +volatile int testCallback2Finished = 0; + +static int TestCallback2( const void *inputBuffer, void *outputBuffer, + unsigned long frameCount, + const PaStreamCallbackTimeInfo* timeInfo, + PaStreamCallbackFlags statusFlags, + void *userData ) +{ + (void) inputBuffer; /* Prevent unused variable warnings. */ + (void) timeInfo; + (void) statusFlags; + + GenerateTestSignal( (TestData*)userData, (float*)outputBuffer, frameCount ); + + if( IsTestSignalFinished( (TestData*)userData ) ) + testCallback2Finished = 1; + + return paContinue; +} + +/*******************************************************************/ +int main(void); +int main(void) +{ + PaStreamParameters outputParameters; + PaStream *stream; + PaError err; + TestData data; + float writeBuffer[ FRAMES_PER_BUFFER * 2 ]; + + printf("PortAudio Test: check that stopping stream plays out all queued samples. SR = %d, BufSize = %d\n", SAMPLE_RATE, FRAMES_PER_BUFFER); + + InitTestSignalGenerator( &data ); + + err = Pa_Initialize(); + if( err != paNoError ) goto error; + + outputParameters.device = Pa_GetDefaultOutputDevice(); /* default output device */ + outputParameters.channelCount = 2; /* stereo output */ + outputParameters.sampleFormat = paFloat32; /* 32 bit floating point output */ + outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultHighOutputLatency; + outputParameters.hostApiSpecificStreamInfo = NULL; + +/* test paComplete ---------------------------------------------------------- */ + + ResetTestSignalGenerator( &data ); + + err = Pa_OpenStream( + &stream, + NULL, /* no input */ + &outputParameters, + SAMPLE_RATE, + FRAMES_PER_BUFFER, + paClipOff, /* we won't output out of range samples so don't bother clipping them */ + TestCallback1, + &data ); + if( err != paNoError ) goto error; + + err = Pa_StartStream( stream ); + if( err != paNoError ) goto error; + + + printf("\nPlaying 'tone-blip' %d times using callback, stops by returning paComplete from callback.\n", NUM_REPEATS ); + printf("If final blip is not intact, callback+paComplete implementation may be faulty.\n\n" ); + + while( (err = Pa_IsStreamActive( stream )) == 1 ) + Pa_Sleep( 5 ); + + if( err != 0 ) goto error; + + + err = Pa_StopStream( stream ); + if( err != paNoError ) goto error; + + err = Pa_CloseStream( stream ); + if( err != paNoError ) goto error; + + Pa_Sleep( 500 ); + +/* test Pa_StopStream() with callback --------------------------------------- */ + + ResetTestSignalGenerator( &data ); + + testCallback2Finished = 0; + + err = Pa_OpenStream( + &stream, + NULL, /* no input */ + &outputParameters, + SAMPLE_RATE, + FRAMES_PER_BUFFER, + paClipOff, /* we won't output out of range samples so don't bother clipping them */ + TestCallback2, + &data ); + if( err != paNoError ) goto error; + + err = Pa_StartStream( stream ); + if( err != paNoError ) goto error; + + + printf("\nPlaying 'tone-blip' %d times using callback, stops by calling Pa_StopStream.\n", NUM_REPEATS ); + printf("If final blip is not intact, callback+Pa_StopStream implementation may be faulty.\n\n" ); + + /* note that polling a volatile flag is not a good way to synchronise with + the callback, but it's the best we can do portably. */ + while( !testCallback2Finished ) + Pa_Sleep( 2 ); + + err = Pa_StopStream( stream ); + if( err != paNoError ) goto error; + + + err = Pa_CloseStream( stream ); + if( err != paNoError ) goto error; + + Pa_Sleep( 500 ); + +/* test Pa_StopStream() with Pa_WriteStream --------------------------------- */ + + ResetTestSignalGenerator( &data ); + + err = Pa_OpenStream( + &stream, + NULL, /* no input */ + &outputParameters, + SAMPLE_RATE, + FRAMES_PER_BUFFER, + paClipOff, /* we won't output out of range samples so don't bother clipping them */ + NULL, /* no callback, use blocking API */ + NULL ); /* no callback, so no callback userData */ + if( err != paNoError ) goto error; + + err = Pa_StartStream( stream ); + if( err != paNoError ) goto error; + + + printf("\nPlaying 'tone-blip' %d times using Pa_WriteStream, stops by calling Pa_StopStream.\n", NUM_REPEATS ); + printf("If final blip is not intact, Pa_WriteStream+Pa_StopStream implementation may be faulty.\n\n" ); + + do{ + GenerateTestSignal( &data, writeBuffer, FRAMES_PER_BUFFER ); + err = Pa_WriteStream( stream, writeBuffer, FRAMES_PER_BUFFER ); + if( err != paNoError ) goto error; + + }while( !IsTestSignalFinished( &data ) ); + + err = Pa_StopStream( stream ); + if( err != paNoError ) goto error; + + + err = Pa_CloseStream( stream ); + if( err != paNoError ) goto error; + +/* -------------------------------------------------------------------------- */ + + Pa_Terminate(); + printf("Test finished.\n"); + + return err; + +error: + Pa_Terminate(); + fprintf( stderr, "An error occured while using the portaudio stream\n" ); + fprintf( stderr, "Error number: %d\n", err ); + fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); + return err; +} diff --git a/pa_tests/patest_sync.c b/pa_tests/patest_sync.c index e2eb88a..6dc13ee 100644 --- a/pa_tests/patest_sync.c +++ b/pa_tests/patest_sync.c @@ -1,19 +1,21 @@ +/** @file patest_sync.c + @brief Test time stamping and synchronization of audio and video. + + A high latency is used so we can hear the difference in time. + Random durations are used so we know we are hearing the right beep + and not the one before or after. + + Sequence of events: + -# Foreground requests a beep. + -# Background randomly schedules a beep. + -# Foreground waits for the beep to be heard based on PaUtil_GetTime(). + -# Foreground outputs video (printf) in sync with audio. + -# Repeat. + + @author Phil Burk http://www.softsynth.com +*/ /* * $Id$ - * patest_sync.c - * Test time stamping and synchronization of audio and video. - * A high latency is used so we can hear the difference in time. - * Random durations are used so we know we are hearing the right beep - * and not the one before or after. - * - * Sequence of events: - * Foreground requests a beep. - * Background randomly schedules a beep. - * Foreground waits for the beep to be heard based on Pa_StreamTime(). - * Foreground outputs video (printf) in sync with audio. - * Repeat. - * - * Author: Phil Burk http://www.softsynth.com * * This program uses the PortAudio Portable Audio Library. * For more information see: http://www.portaudio.com @@ -46,43 +48,49 @@ #include #include #include "portaudio.h" +#include "pa_util.h" #define NUM_BEEPS (6) #define SAMPLE_RATE (44100) +#define SAMPLE_PERIOD (1.0/44100.0) #define FRAMES_PER_BUFFER (256) -#define BEEP_DURATION (1000) +#define BEEP_DURATION (400) #define LATENCY_MSEC (2000) #define SLEEP_MSEC (10) -#define TIMEOUT_MSEC ((3 * LATENCY_MSEC) / (2 * SLEEP_MSEC)) -#define NUM_BUFFERS ((LATENCY_MSEC * SAMPLE_RATE) / (FRAMES_PER_BUFFER * 1000)) -#define STATE_BKG_IDLE (0) -#define STATE_BKG_PENDING (1) -#define STATE_BKG_BEEPING (2) +#define TIMEOUT_MSEC (15000) + +#define STATE_BKG_IDLE (0) +#define STATE_BKG_PENDING (1) +#define STATE_BKG_BEEPING (2) typedef struct { float left_phase; float right_phase; int state; - int requestBeep; /* Set by foreground, cleared by background. */ - PaTimestamp beepTime; + volatile int requestBeep; /* Set by foreground, cleared by background. */ + PaTime beepTime; int beepCount; + double latency; /* For debugging. */ } paTestData; + static unsigned long GenerateRandomNumber( void ); /************************************************************/ /* Calculate pseudo-random 32 bit number based on linear congruential method. */ static unsigned long GenerateRandomNumber( void ) { - static unsigned long randSeed = 22222; /* Change this for different random sequences. */ + static unsigned long randSeed = 99887766; /* Change this for different random sequences. */ randSeed = (randSeed * 196314165) + 907633515; return randSeed; } + /* This routine will be called by the PortAudio engine when audio is needed. ** It may called at interrupt level on some machines so don't do anything ** that could mess up the system like calling malloc() or free(). */ -static int patestCallback( void *inputBuffer, void *outputBuffer, +static int patestCallback( const void *inputBuffer, void *outputBuffer, unsigned long framesPerBuffer, - PaTimestamp outTime, void *userData ) + const PaStreamCallbackTimeInfo *timeInfo, + PaStreamCallbackFlags statusFlags, void *userData ) { /* Cast data passed through stream to our structure. */ paTestData *data = (paTestData*)userData; @@ -90,6 +98,8 @@ static int patestCallback( void *inputBuffer, void *outputBuffer, unsigned int i; (void) inputBuffer; + data->latency = timeInfo->outputBufferDacTime - timeInfo->currentTime; + for( i=0; istate ) @@ -99,27 +109,29 @@ static int patestCallback( void *inputBuffer, void *outputBuffer, if( data->requestBeep ) { int random = GenerateRandomNumber() >> 14; - data->beepTime = outTime + (i + random + (SAMPLE_RATE/4)); + data->beepTime = timeInfo->outputBufferDacTime + (( (double)(random + SAMPLE_RATE)) * SAMPLE_PERIOD ); data->state = STATE_BKG_PENDING; - data->requestBeep = 0; - data->left_phase = data->right_phase = 0.0; } *out++ = 0.0; /* left */ *out++ = 0.0; /* right */ break; + case STATE_BKG_PENDING: - if( (outTime + i) >= data->beepTime ) + if( (timeInfo->outputBufferDacTime + (i*SAMPLE_PERIOD)) >= data->beepTime ) { data->state = STATE_BKG_BEEPING; data->beepCount = BEEP_DURATION; + data->left_phase = data->right_phase = 0.0; } *out++ = 0.0; /* left */ *out++ = 0.0; /* right */ break; + case STATE_BKG_BEEPING: if( data->beepCount <= 0 ) { data->state = STATE_BKG_IDLE; + data->requestBeep = 0; *out++ = 0.0; /* left */ *out++ = 0.0; /* right */ } @@ -138,6 +150,7 @@ static int patestCallback( void *inputBuffer, void *outputBuffer, } data->beepCount -= 1; break; + default: data->state = STATE_BKG_IDLE; break; @@ -149,11 +162,12 @@ static int patestCallback( void *inputBuffer, void *outputBuffer, int main(void); int main(void) { - PortAudioStream *stream; + PaStream *stream; PaError err; paTestData DATA; int i, timeout; - PaTimestamp previousTime; + PaTime previousTime; + PaStreamParameters outputParameters; printf("PortAudio Test: you should see BEEP at the same time you hear it.\n"); printf("Wait for a few seconds random delay between BEEPs.\n"); printf("BEEP %d times.\n", NUM_BEEPS ); @@ -164,25 +178,37 @@ int main(void) /* Initialize library before making any other calls. */ err = Pa_Initialize(); if( err != paNoError ) goto error; + + outputParameters.device = Pa_GetDefaultOutputDevice(); + outputParameters.channelCount = 2; + outputParameters.hostApiSpecificStreamInfo = NULL; + outputParameters.sampleFormat = paFloat32; + outputParameters.suggestedLatency = (double)LATENCY_MSEC / 1000; + /* Open an audio I/O stream. */ - err = Pa_OpenDefaultStream( + err = Pa_OpenStream( &stream, - 0, /* no input channels */ - 2, /* stereo output */ - paFloat32, /* 32 bit floating point output */ + NULL, /* no input */ + &outputParameters, SAMPLE_RATE, - FRAMES_PER_BUFFER, - NUM_BUFFERS, + FRAMES_PER_BUFFER, /* frames per buffer */ + paClipOff, /* we won't output out of range samples so don't bother clipping them */ patestCallback, &DATA ); - if( err != paNoError ) goto error; + if( err != paNoError ) goto error; + err = Pa_StartStream( stream ); if( err != paNoError ) goto error; - previousTime = Pa_StreamTime( stream ); + + printf("started\n"); + fflush(stdout); + + previousTime = Pa_GetStreamTime( stream ); for( i=0; i 0 ) ) Pa_Sleep(SLEEP_MSEC); @@ -191,30 +217,36 @@ int main(void) fprintf( stderr, "Timed out waiting for background to acknowledge request.\n" ); goto error; } + printf("calc beep for %9.3f, latency = %6.3f\n", DATA.beepTime, DATA.latency ); + fflush(stdout); + /* Wait for scheduled beep time. */ timeout = TIMEOUT_MSEC + (10000/SLEEP_MSEC); - while( (Pa_StreamTime( stream ) < DATA.beepTime) && (timeout-- > 0 ) ) + while( (Pa_GetStreamTime( stream ) < DATA.beepTime) && (timeout-- > 0 ) ) { Pa_Sleep(SLEEP_MSEC); } if( timeout <= 0 ) { - fprintf( stderr, "Timed out waiting for time. Now = %g, Beep for %g.\n", - Pa_StreamTime( stream ), DATA.beepTime ); + fprintf( stderr, "Timed out waiting for time. Now = %9.3f, Beep for %9.3f.\n", + PaUtil_GetTime(), DATA.beepTime ); goto error; } + /* Beep should be sounding now so print synchronized BEEP. */ - printf("BEEP"); - fflush(stdout); - printf(" at %d, delta = %d\n", - (long) DATA.beepTime, (long) (DATA.beepTime - previousTime) ); + printf("hear \"BEEP\" at %9.3f, delta = %9.3f\n", + Pa_GetStreamTime( stream ), (DATA.beepTime - previousTime) ); fflush(stdout); + previousTime = DATA.beepTime; } + err = Pa_StopStream( stream ); if( err != paNoError ) goto error; + err = Pa_CloseStream( stream ); if( err != paNoError ) goto error; + Pa_Terminate(); printf("Test finished.\n"); return err; diff --git a/pa_tests/patest_toomanysines.c b/pa_tests/patest_toomanysines.c index f78df8c..b7b2266 100644 --- a/pa_tests/patest_toomanysines.c +++ b/pa_tests/patest_toomanysines.c @@ -1,10 +1,10 @@ +/** @file patest_toomanysines.c + @brief Play more sine waves than we can handle in real time as a stress test. + @author Ross Bencina + @author Phil Burk +*/ /* * $Id$ - * Play more sine waves than we can handle in real time as a stress test, - * - * Authors: - * Ross Bencina - * Phil Burk * * This program uses the PortAudio Portable Audio Library. * For more information see: http://www.audiomulch.com/portaudio/ @@ -58,17 +58,18 @@ paTestData; ** It may called at interrupt level on some machines so don't do anything ** that could mess up the system like calling malloc() or free(). */ -static int patestCallback( void *inputBuffer, void *outputBuffer, - unsigned long framesPerBuffer, - PaTimestamp outTime, void *userData ) +static int patestCallback( const void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + const PaStreamCallbackTimeInfo* timeInfo, + PaStreamCallbackFlags statusFlags, + void *userData ) { paTestData *data = (paTestData*)userData; float *out = (float*)outputBuffer; unsigned long i; int j; int finished = 0; - (void) outTime; /* Prevent unused variable warnings. */ - (void) inputBuffer; + (void) inputBuffer; /* Prevent unused variable warning. */ for( i=0; iphases[j] = phase; } - - *out++ = (float) (output / data->numSines); } return finished; @@ -100,32 +99,34 @@ static int patestCallback( void *inputBuffer, void *outputBuffer, int main(void); int main(void) { - PortAudioStream *stream; + PaStreamParameters outputParameters; + PaStream *stream; PaError err; int numStress; paTestData data = {0}; double load; + printf("PortAudio Test: output sine wave. SR = %d, BufSize = %d. MAX_LOAD = %f\n", SAMPLE_RATE, FRAMES_PER_BUFFER, MAX_LOAD ); err = Pa_Initialize(); if( err != paNoError ) goto error; + + outputParameters.device = Pa_GetDefaultOutputDevice(); /* default output device */ + outputParameters.channelCount = 1; /* mono output */ + outputParameters.sampleFormat = paFloat32; /* 32 bit floating point output */ + outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency; + outputParameters.hostApiSpecificStreamInfo = NULL; + err = Pa_OpenStream( &stream, - paNoDevice,/* default input device */ - 0, /* no input */ - paFloat32, /* 32 bit floating point input */ - NULL, - Pa_GetDefaultOutputDeviceID(), /* default output device */ - 1, /* mono output */ - paFloat32, /* 32 bit floating point output */ - NULL, + NULL, /* no input */ + &outputParameters, SAMPLE_RATE, - FRAMES_PER_BUFFER, /* frames per buffer */ - 0, /* number of buffers, if zero then use default minimum */ - paClipOff, /* we won't output out of range samples so don't bother clipping them */ + FRAMES_PER_BUFFER, + paClipOff, /* we won't output out of range samples so don't bother clipping them */ patestCallback, - &data ); + &data ); if( err != paNoError ) goto error; err = Pa_StartStream( stream ); if( err != paNoError ) goto error; @@ -136,7 +137,7 @@ int main(void) data.numSines++; Pa_Sleep( 100 ); - load = Pa_GetCPULoad( stream ); + load = Pa_GetStreamCpuLoad( stream ); printf("numSines = %d, CPU load = %f\n", data.numSines, load ); } while( load < 0.5 ); @@ -146,7 +147,7 @@ int main(void) for( ; data.numSines < numStress; data.numSines++ ) { Pa_Sleep( 200 ); - load = Pa_GetCPULoad( stream ); + load = Pa_GetStreamCpuLoad( stream ); printf("STRESSING: numSines = %d, CPU load = %f\n", data.numSines, load ); } diff --git a/pa_tests/patest_two_rates.c b/pa_tests/patest_two_rates.c new file mode 100644 index 0000000..9953241 --- /dev/null +++ b/pa_tests/patest_two_rates.c @@ -0,0 +1,168 @@ +/* + * $Id$ + * patest_two_rates.c + * Play two streams at different rates to make sure they don't interfere. + * + * Author: Phil Burk http://www.softsynth.com + * + * This program uses the PortAudio Portable Audio Library. + * For more information see: http://www.portaudio.com + * 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. + * + */ +#include +#include +#include "portaudio.h" + +#define OUTPUT_DEVICE (Pa_GetDefaultOutputDeviceID()) +#define SAMPLE_RATE_1 (44100) +#define SAMPLE_RATE_2 (44100) +#define FRAMES_PER_BUFFER (256) +#define FREQ_INCR (0.1) + +#ifndef M_PI +#define M_PI (3.14159265) +#endif + +typedef struct +{ + double phase; + double numFrames; +} paTestData; + +/* This routine will be called by the PortAudio engine when audio is needed. +** It may called at interrupt level on some machines so don't do anything +** that could mess up the system like calling malloc() or free(). +*/ +static int patestCallback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ) +{ + paTestData *data = (paTestData*)userData; + float *out = (float*)outputBuffer; + int frameIndex, channelIndex; + int finished = 0; + (void) outTime; /* Prevent unused variable warnings. */ + (void) inputBuffer; + + for( frameIndex=0; frameIndex<(int)framesPerBuffer; frameIndex++ ) + { + /* Generate sine wave. */ + float value = (float) 0.3 * sin(data->phase); + /* Stereo - two channels. */ + *out++ = value; + *out++ = value; + + data->phase += FREQ_INCR; + if( data->phase >= (2.0 * M_PI) ) data->phase -= (2.0 * M_PI); + } + + return 0; +} + +/*******************************************************************/ +int main(void); +int main(void) +{ + PaError err; + PortAudioStream *stream1; + PortAudioStream *stream2; + paTestData data1 = {0}; + paTestData data2 = {0}; + printf("PortAudio Test: two rates.\n" ); + + err = Pa_Initialize(); + if( err != paNoError ) goto error; + + /* Start first stream. **********************/ + err = Pa_OpenStream( + &stream1, + paNoDevice, /* default input device */ + 0, /* no input */ + paFloat32, /* 32 bit floating point input */ + NULL, + OUTPUT_DEVICE, + 2, /* Stereo */ + paFloat32, /* 32 bit floating point output */ + NULL, + SAMPLE_RATE_1, + FRAMES_PER_BUFFER, /* frames per buffer */ + 0, /* number of buffers, if zero then use default minimum */ + paClipOff, /* we won't output out of range samples so don't bother clipping them */ + patestCallback, + &data1 ); + if( err != paNoError ) goto error; + + err = Pa_StartStream( stream1 ); + if( err != paNoError ) goto error; + + Pa_Sleep( 3 * 1000 ); + + /* Start second stream. **********************/ + err = Pa_OpenStream( + &stream2, + paNoDevice, /* default input device */ + 0, /* no input */ + paFloat32, /* 32 bit floating point input */ + NULL, + OUTPUT_DEVICE, + 2, /* Stereo */ + paFloat32, /* 32 bit floating point output */ + NULL, + SAMPLE_RATE_2, + FRAMES_PER_BUFFER, /* frames per buffer */ + 0, /* number of buffers, if zero then use default minimum */ + paClipOff, /* we won't output out of range samples so don't bother clipping them */ + patestCallback, + &data2 ); + if( err != paNoError ) goto error; + + err = Pa_StartStream( stream2 ); + if( err != paNoError ) goto error; + + Pa_Sleep( 3 * 1000 ); + + err = Pa_StopStream( stream2 ); + if( err != paNoError ) goto error; + + Pa_Sleep( 3 * 1000 ); + + err = Pa_StopStream( stream1 ); + if( err != paNoError ) goto error; + + Pa_CloseStream( stream2 ); + Pa_CloseStream( stream1 ); + + Pa_Terminate(); + printf("Test finished.\n"); + return err; +error: + Pa_Terminate(); + fprintf( stderr, "An error occured while using the portaudio stream\n" ); + fprintf( stderr, "Error number: %d\n", err ); + fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); + return err; +} diff --git a/pa_tests/patest_underflow.c b/pa_tests/patest_underflow.c index ca07cf4..7ff3de6 100644 --- a/pa_tests/patest_underflow.c +++ b/pa_tests/patest_underflow.c @@ -1,12 +1,11 @@ +/** @file patest_underflow.c + @brief Simulate an output buffer underflow condition. + Tests whether the stream can be stopped when underflowing buffers. + @author Ross Bencina + @author Phil Burk +*/ /* * $Id$ - * patest_underflow.c - * Simulate an output buffer underflow condition. - * Tests whether the stream can be stopped when underflowing buffers. - * - * Authors: - * Ross Bencina - * Phil Burk * * This program uses the PortAudio Portable Audio Library. * For more information see: http://www.audiomulch.com/portaudio/ @@ -63,16 +62,17 @@ paTestData; ** It may called at interrupt level on some machines so don't do anything ** that could mess up the system like calling malloc() or free(). */ -static int patestCallback( void *inputBuffer, void *outputBuffer, - unsigned long framesPerBuffer, - PaTimestamp outTime, void *userData ) +static int patestCallback( const void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + const PaStreamCallbackTimeInfo* timeInfo, + PaStreamCallbackFlags statusFlags, + void *userData ) { paTestData *data = (paTestData*)userData; float *out = (float*)outputBuffer; unsigned long i; int finished = 0; - (void) outTime; /* Prevent unused variable warnings. */ - (void) inputBuffer; + (void) inputBuffer; /* Prevent unused variable warnings. */ for( i=0; isine[data->left_phase]; /* left */ @@ -94,7 +94,8 @@ static int patestCallback( void *inputBuffer, void *outputBuffer, int main(void); int main(void) { - PortAudioStream *stream; + PaStreamParameters outputParameters; + PaStream *stream; PaError err; paTestData data; int i; @@ -107,19 +108,18 @@ int main(void) data.left_phase = data.right_phase = data.sleepTime = 0; err = Pa_Initialize(); if( err != paNoError ) goto error; + + outputParameters.device = Pa_GetDefaultOutputDevice(); /* default output device */ + outputParameters.channelCount = 2; /* stereo output */ + outputParameters.sampleFormat = paFloat32; /* 32 bit floating point output */ + outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency; + outputParameters.hostApiSpecificStreamInfo = NULL; err = Pa_OpenStream( &stream, - paNoDevice,/* default input device */ - 0, /* no input */ - paFloat32, /* 32 bit floating point input */ - NULL, - Pa_GetDefaultOutputDeviceID(), /* default output device */ - 2, /* stereo output */ - paFloat32, /* 32 bit floating point output */ - NULL, + NULL, /* no input */ + &outputParameters, SAMPLE_RATE, FRAMES_PER_BUFFER, - 0, /* number of buffers, if zero then use default minimum */ paClipOff, /* we won't output out of range samples so don't bother clipping them */ patestCallback, &data ); diff --git a/pa_tests/patest_wire.c b/pa_tests/patest_wire.c index c24d225..d83ce22 100644 --- a/pa_tests/patest_wire.c +++ b/pa_tests/patest_wire.c @@ -1,13 +1,18 @@ +/** @file patest_wire.c + @brief Pass input directly to output. + + Note that some HW devices, for example many ISA audio cards + on PCs, do NOT support full duplex! For a PC, you normally need + a PCI based audio card such as the SBLive. + + @author Phil Burk http://www.softsynth.com + + While adapting to V19-API, I excluded configs with framesPerCallback=0 + because of an assert in file pa_common/pa_process.c. Pieter, Oct 9, 2003. + +*/ /* * $Id$ - * patest_wire.c - * - * Pass input directly to output. - * Note that some HW devices, for example many ISA audio cards - * on PCs, do NOT support full duplex! For a PC, you normally need - * a PCI based audio card such as the SBLive. - * - * Author: Phil Burk http://www.softsynth.com * * This program uses the PortAudio Portable Audio Library. * For more information see: http://www.portaudio.com @@ -40,105 +45,240 @@ #include #include #include "portaudio.h" -/* -** Note that many of the older ISA sound cards on PCs do NOT support -** full duplex audio (simultaneous record and playback). -** And some only support full duplex at lower sample rates. -*/ -#define SAMPLE_RATE (44100) -#define FRAMES_PER_BUFFER (64) -#if 1 -#define PA_SAMPLE_TYPE paFloat32 -typedef float SAMPLE; + +#define SAMPLE_RATE (44100) + +typedef struct WireConfig_s +{ + int isInputInterleaved; + int isOutputInterleaved; + int numInputChannels; + int numOutputChannels; + int framesPerCallback; +} WireConfig_t; + +#define USE_FLOAT_INPUT (1) +#define USE_FLOAT_OUTPUT (1) + +/* Latencies set to defaults. */ + +#if USE_FLOAT_INPUT + #define INPUT_FORMAT paFloat32 + typedef float INPUT_SAMPLE; #else -#define PA_SAMPLE_TYPE paInt16 -typedef short SAMPLE; + #define INPUT_FORMAT paInt16 + typedef short INPUT_SAMPLE; #endif -static int wireCallback( void *inputBuffer, void *outputBuffer, + +#if USE_FLOAT_OUTPUT + #define OUTPUT_FORMAT paFloat32 + typedef float OUTPUT_SAMPLE; +#else + #define OUTPUT_FORMAT paInt16 + typedef short OUTPUT_SAMPLE; +#endif + +double gInOutScaler = 1.0; +#define CONVERT_IN_TO_OUT(in) ((OUTPUT_SAMPLE) ((in) * gInOutScaler)) + +#define INPUT_DEVICE (Pa_GetDefaultInputDevice()) +#define OUTPUT_DEVICE (Pa_GetDefaultOutputDevice()) + +static PaError TestConfiguration( WireConfig_t *config ); + +static int wireCallback( const void *inputBuffer, void *outputBuffer, unsigned long framesPerBuffer, - PaTimestamp outTime, void *userData ); + const PaStreamCallbackTimeInfo* timeInfo, + PaStreamCallbackFlags statusFlags, + void *userData ); /* This routine will be called by the PortAudio engine when audio is needed. ** It may be called at interrupt level on some machines so don't do anything ** that could mess up the system like calling malloc() or free(). */ -static int wireCallback( void *inputBuffer, void *outputBuffer, + +static int wireCallback( const void *inputBuffer, void *outputBuffer, unsigned long framesPerBuffer, - PaTimestamp outTime, void *userData ) + const PaStreamCallbackTimeInfo* timeInfo, + PaStreamCallbackFlags statusFlags, + void *userData ) { - SAMPLE *out = (SAMPLE*)outputBuffer; - SAMPLE *in = (SAMPLE*)inputBuffer; + INPUT_SAMPLE *in; + OUTPUT_SAMPLE *out; + int inStride; + int outStride; + int inDone = 0; + int outDone = 0; + WireConfig_t *config = (WireConfig_t *) userData; unsigned int i; - (void) outTime; + int inChannel, outChannel; /* This may get called with NULL inputBuffer during initial setup. */ - if( inputBuffer == NULL ) + if( inputBuffer == NULL) return 0; + + inChannel=0, outChannel=0; + while( !(inDone && outDone) ) { - for( i=0; iisInputInterleaved ) { - *out++ = 0; /* left */ - *out++ = 0; /* right */ + in = ((INPUT_SAMPLE*)inputBuffer) + inChannel; + inStride = config->numInputChannels; } - } - else - { + else + { + in = ((INPUT_SAMPLE**)inputBuffer)[inChannel]; + inStride = 1; + } + + if( config->isOutputInterleaved ) + { + out = ((OUTPUT_SAMPLE*)outputBuffer) + outChannel; + outStride = config->numOutputChannels; + } + else + { + out = ((OUTPUT_SAMPLE**)outputBuffer)[outChannel]; + outStride = 1; + } + for( i=0; inumInputChannels - 1)) inChannel++; + else inDone = 1; + if(outChannel < (config->numOutputChannels - 1)) outChannel++; + else outDone = 1; + } return 0; } + /*******************************************************************/ int main(void); int main(void) { - PortAudioStream *stream; PaError err; - + WireConfig_t CONFIG; + WireConfig_t *config = &CONFIG; + int configIndex = 0;; + err = Pa_Initialize(); if( err != paNoError ) goto error; + + printf("Please connect audio signal to input and listen for it on output!\n"); + printf("input format = %lu\n", INPUT_FORMAT ); + printf("output format = %lu\n", OUTPUT_FORMAT ); + printf("input device ID = %d\n", INPUT_DEVICE ); + printf("output device ID = %d\n", OUTPUT_DEVICE ); + + if( INPUT_FORMAT == OUTPUT_FORMAT ) + { + gInOutScaler = 1.0; + } + else if( (INPUT_FORMAT == paInt16) && (OUTPUT_FORMAT == paFloat32) ) + { + gInOutScaler = 1.0/32768.0; + } + else if( (INPUT_FORMAT == paFloat32) && (OUTPUT_FORMAT == paInt16) ) + { + gInOutScaler = 32768.0; + } + + for( config->isInputInterleaved = 0; config->isInputInterleaved < 2; config->isInputInterleaved++ ) + { + for( config->isOutputInterleaved = 0; config->isOutputInterleaved < 2; config->isOutputInterleaved++ ) + { + for( config->numInputChannels = 1; config->numInputChannels < 3; config->numInputChannels++ ) + { + for( config->numOutputChannels = 1; config->numOutputChannels < 3; config->numOutputChannels++ ) + { + /* If framesPerCallback = 0, assertion fails in file pa_common/pa_process.c, line 1413: EX. */ + for( config->framesPerCallback = 64; config->framesPerCallback < 129; config->framesPerCallback += 64 ) + { + printf("-----------------------------------------------\n" ); + printf("Configuration #%d\n", configIndex++ ); + err = TestConfiguration( config ); + /* Give user a chance to bail out. */ + if( err == 1 ) + { + err = paNoError; + goto done; + } + else if( err != paNoError ) goto error; + } + } + } + } + } + +done: + Pa_Terminate(); + printf("Full duplex sound test complete.\n"); fflush(stdout); + printf("Hit ENTER to quit.\n"); fflush(stdout); + getchar(); + return 0; + +error: + Pa_Terminate(); + fprintf( stderr, "An error occured while using the portaudio stream\n" ); + fprintf( stderr, "Error number: %d\n", err ); + fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); + printf("Hit ENTER to quit.\n"); fflush(stdout); + getchar(); + return -1; +} + +static PaError TestConfiguration( WireConfig_t *config ) +{ + int c; + PaError err; + PaStream *stream; + PaStreamParameters inputParameters, outputParameters; - printf("PortAudio Test: input device ID = %d\n", Pa_GetDefaultInputDeviceID() ); - printf("PortAudio Test: output device ID = %d\n", Pa_GetDefaultOutputDeviceID() ); + printf("input %sinterleaved!\n", (config->isInputInterleaved ? " " : "NOT ") ); + printf("output %sinterleaved!\n", (config->isOutputInterleaved ? " " : "NOT ") ); + printf("input channels = %d\n", config->numInputChannels ); + printf("output channels = %d\n", config->numOutputChannels ); + printf("framesPerCallback = %d\n", config->framesPerCallback ); + + inputParameters.device = INPUT_DEVICE; /* default input device */ + inputParameters.channelCount = config->numInputChannels; + inputParameters.sampleFormat = INPUT_FORMAT | (config->isInputInterleaved ? 0 : paNonInterleaved); + inputParameters.suggestedLatency = Pa_GetDeviceInfo( inputParameters.device )->defaultLowInputLatency; + inputParameters.hostApiSpecificStreamInfo = NULL; + + outputParameters.device = OUTPUT_DEVICE; /* default output device */ + outputParameters.channelCount = config->numOutputChannels; + outputParameters.sampleFormat = OUTPUT_FORMAT | (config->isOutputInterleaved ? 0 : paNonInterleaved); + outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency; + outputParameters.hostApiSpecificStreamInfo = NULL; + err = Pa_OpenStream( &stream, - Pa_GetDefaultInputDeviceID(), /* default output device */ - 2, /* stereo input */ - PA_SAMPLE_TYPE, - NULL, - Pa_GetDefaultOutputDeviceID(), /* default output device */ - 2, /* stereo output */ - PA_SAMPLE_TYPE, - NULL, + &inputParameters, + &outputParameters, SAMPLE_RATE, - FRAMES_PER_BUFFER, /* frames per buffer */ - 0, /* number of buffers, if zero then use default minimum */ - paClipOff, /* we won't output out of range samples so don't bother clipping them */ + config->framesPerCallback, /* frames per buffer */ + paClipOff, /* we won't output out of range samples so don't bother clipping them */ wireCallback, - NULL ); /* no data */ + config ); if( err != paNoError ) goto error; err = Pa_StartStream( stream ); if( err != paNoError ) goto error; - printf("Full duplex sound test in progress.\n"); - printf("Hit ENTER to exit test.\n"); fflush(stdout); - getchar(); + printf("Hit ENTER for next configuration, or 'q' to quit.\n"); fflush(stdout); + c = getchar(); printf("Closing stream.\n"); err = Pa_CloseStream( stream ); if( err != paNoError ) goto error; - Pa_Terminate(); - - printf("Full duplex sound test complete.\n"); fflush(stdout); - return 0; + + if( c == 'q' ) return 1; + error: - Pa_Terminate(); - fprintf( stderr, "An error occured while using the portaudio stream\n" ); - fprintf( stderr, "Error number: %d\n", err ); - fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); - return -1; + return err; } diff --git a/pa_tests/patest_write_sine.c b/pa_tests/patest_write_sine.c new file mode 100644 index 0000000..f0fcba0 --- /dev/null +++ b/pa_tests/patest_write_sine.c @@ -0,0 +1,147 @@ +/** @file patest_write_sine.c + @brief Play a sine wave for several seconds using the blocking API (Pa_WriteStream()) + @author Ross Bencina + @author Phil Burk +*/ +/* + * $Id$ + * + * This program uses the PortAudio Portable Audio Library. + * For more information see: http://www.portaudio.com/ + * 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. + * + */ +#include +#include +#include "portaudio.h" + +#define NUM_SECONDS (5) +#define SAMPLE_RATE (44100) +#define FRAMES_PER_BUFFER (1024) + +#ifndef M_PI +#define M_PI (3.14159265) +#endif + +#define TABLE_SIZE (200) + + +int main(void); +int main(void) +{ + PaStreamParameters outputParameters; + PaStream *stream; + PaError err; + float buffer[FRAMES_PER_BUFFER][2]; /* stereo output buffer */ + float sine[TABLE_SIZE]; /* sine wavetable */ + int left_phase = 0; + int right_phase = 0; + int left_inc = 1; + int right_inc = 3; /* higher pitch so we can distinguish left and right. */ + int i, j, k; + int bufferCount; + + + printf("PortAudio Test: output sine wave. SR = %d, BufSize = %d\n", SAMPLE_RATE, FRAMES_PER_BUFFER); + + /* initialise sinusoidal wavetable */ + for( i=0; idefaultLowOutputLatency; + outputParameters.hostApiSpecificStreamInfo = NULL; + + err = Pa_OpenStream( + &stream, + NULL, /* no input */ + &outputParameters, + SAMPLE_RATE, + FRAMES_PER_BUFFER, + paClipOff, /* we won't output out of range samples so don't bother clipping them */ + NULL, /* no callback, use blocking API */ + NULL ); /* no callback, so no callback userData */ + if( err != paNoError ) goto error; + + + printf( "Play 3 times, higher each time.\n" ); + + for( k=0; k < 3; ++k ) + { + err = Pa_StartStream( stream ); + if( err != paNoError ) goto error; + + printf("Play for %d seconds.\n", NUM_SECONDS ); + + bufferCount = ((NUM_SECONDS * SAMPLE_RATE) / FRAMES_PER_BUFFER); + + for( i=0; i < bufferCount; i++ ) + { + for( j=0; j < FRAMES_PER_BUFFER; j++ ) + { + buffer[j][0] = sine[left_phase]; /* left */ + buffer[j][1] = sine[right_phase]; /* right */ + left_phase += left_inc; + if( left_phase >= TABLE_SIZE ) left_phase -= TABLE_SIZE; + right_phase += right_inc; + if( right_phase >= TABLE_SIZE ) right_phase -= TABLE_SIZE; + } + + err = Pa_WriteStream( stream, buffer, FRAMES_PER_BUFFER ); + if( err != paNoError ) goto error; + } + + err = Pa_StopStream( stream ); + if( err != paNoError ) goto error; + + ++left_inc; + ++right_inc; + + Pa_Sleep( 1000 ); + } + + err = Pa_CloseStream( stream ); + if( err != paNoError ) goto error; + + Pa_Terminate(); + printf("Test finished.\n"); + + return err; +error: + Pa_Terminate(); + fprintf( stderr, "An error occured while using the portaudio stream\n" ); + fprintf( stderr, "Error number: %d\n", err ); + fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); + return err; +} diff --git a/pa_unix/pa_unix_hostapis.c b/pa_unix/pa_unix_hostapis.c new file mode 100644 index 0000000..570f596 --- /dev/null +++ b/pa_unix/pa_unix_hostapis.c @@ -0,0 +1,64 @@ +/* + * $Id$ + * 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. + * + * 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. + */ + + +#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 ); + + +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 + 0 /* NULL terminated array */ + }; + +int paDefaultHostApiIndex = 0; + + diff --git a/pa_unix/pa_unix_util.c b/pa_unix/pa_unix_util.c new file mode 100644 index 0000000..d4b1371 --- /dev/null +++ b/pa_unix/pa_unix_util.c @@ -0,0 +1,672 @@ +/* + * $Id$ + * 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. + * + * 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. + */ + + +#include +#include +#include +#include +#include +#include +#include /* For memset */ +#include +#include + +#include "pa_util.h" +#include "pa_unix_util.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; +} + +#if 0 +PaError PaUnixThread_Initialize( PaUnixThread* self ) +{ + th->watchdogRunning = 0; + th->rtSched = 0; + th->callbackTime = 0; + th->callbackCpuTime = 0; + th->useWatchdog = 1; + th->throttledSleepTime = 0; + th->cpuLoadMeasurer = clm; + + th->rtPrio = (sched_get_priority_max( SCHED_FIFO ) - sched_get_priority_min( SCHED_FIFO )) / 2 + + sched_get_priority_min( SCHED_FIFO ); +} +#endif + +PaError PaUnixThread_New( PaUnixThread* self, void* (*threadFunc)( void* ), void* threadArg, PaTime waitForChild ) +{ + 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 */ + +#if 0 && defined _POSIX_MEMLOCK && (_POSIX_MEMLOCK != -1) + if( th->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 + + 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 0 + if( th->rtSched ) + { + if( th->useWatchdog ) + { + int err; + struct sched_param wdSpm = { 0 }; + /* Launch watchdog, watchdog sets callback thread priority */ + int prio = PA_MIN( th->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( &th->watchdogThread, &attr, &WatchdogFunc, th )) ) + { + PA_UNLESS( err == EPERM, paInternalError ); + /* Permission error, go on without realtime privileges */ + PA_DEBUG(( "Failed bumping priority\n" )); + } + else + { + int policy; + th->watchdogRunning = 1; + PA_ENSURE_SYSTEM( pthread_getschedparam( th->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 + PA_ENSURE( BoostPriority( th ) ); + } +#endif + + 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 +/* Threading utility struct */ +typedef struct PaAlsaThreading +{ + pthread_t watchdogThread; + pthread_t callbackThread; + int watchdogRunning; + int rtSched; + int rtPrio; + int useWatchdog; + unsigned long throttledSleepTime; + volatile PaTime callbackTime; + volatile PaTime callbackCpuTime; + PaUtilCpuLoadMeasurer *cpuLoadMeasurer; +} PaAlsaThreading; + +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 PaError BoostPriority( PaAlsaThreading *th ) +{ + PaError result = paNoError; + struct sched_param spm = { 0 }; + spm.sched_priority = th->rtPrio; + + assert( th ); + + if( pthread_setschedparam( th->callbackThread, 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; +} + +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 ); +} +#endif + +/* +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 ); +} +*/ diff --git a/pa_unix/pa_unix_util.h b/pa_unix/pa_unix_util.h new file mode 100644 index 0000000..49bfedf --- /dev/null +++ b/pa_unix/pa_unix_util.h @@ -0,0 +1,179 @@ +#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. + * @return: If timed out waiting on child, paTimedOut. + */ +PaError PaUnixThread_New( PaUnixThread* self, void* (*threadFunc)( void* ), void* threadArg, PaTime waitForChild ); + +/** 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 diff --git a/pa_unix_oss/Makefile b/pa_unix_oss/Makefile deleted file mode 100644 index f501563..0000000 --- a/pa_unix_oss/Makefile +++ /dev/null @@ -1,43 +0,0 @@ -# Make PortAudio for Linux - -LIBS = -lm -lpthread - -CDEFINES = -I../pa_common -CFLAGS = -g -Wall -PASRC = ../pa_common/pa_lib.c pa_unix_oss.c -PAINC = ../pa_common/portaudio.h - -# Tests that work. -TESTC = $(PASRC) ../pa_tests/patest_sine.c -#TESTC = $(PASRC) ../pa_tests/patest_longsine.c -#TESTC = $(PASRC) ../pa_tests/patest_sine_time.c -#TESTC = $(PASRC) ../pa_tests/patest_maxsines.c -#TESTC = $(PASRC) ../pa_tests/patest_toomanysines.c -#TESTC = $(PASRC) ../pa_tests/patest_underflow.c -#TESTC = $(PASRC) ../pa_tests/patest_hang.c -#TESTC = $(PASRC) ../pa_tests/patest_sync.c -#TESTC = $(PASRC) ../pa_tests/patest_pink.c -#TESTC = $(PASRC) ../pa_tests/patest_leftright.c -#TESTC = $(PASRC) ../pa_tests/patest_clip.c -#TESTC = $(PASRC) ../pa_tests/patest_dither.c -#TESTC = $(PASRC) ../pa_tests/pa_devs.c -#TESTC = $(PASRC) ../pa_tests/patest_many.c -#TESTC = $(PASRC) ../pa_tests/patest_record.c -#TESTC = $(PASRC) ../pa_tests/pa_fuzz.c -#TESTC = $(PASRC) ../pa_tests/patest_wire.c -#TESTC = $(PASRC) ../pa_tests/paqa_devs.c - -# Tests that do not yet work. -# OSS doesn't let us make obscenely huge buffers so the test will seem to fail. But its OK. -#TESTC = $(PASRC) ../pa_tests/patest_stop.c - -TESTH = $(PAINC) - -all: patest - -patest: $(TESTC) $(TESTH) Makefile - gcc $(CFLAGS) $(TESTC) $(CDEFINES) $(LIBS) -o patest - -run: patest - ./patest - diff --git a/pa_unix_oss/Makefile_freebsd b/pa_unix_oss/Makefile_freebsd deleted file mode 100644 index fc8b14d..0000000 --- a/pa_unix_oss/Makefile_freebsd +++ /dev/null @@ -1,36 +0,0 @@ -# Make PortAudio for FreeBSD - -LIBS = -lm -pthread - -CDEFINES = -I../pa_common -CFLAGS = -g -PASRC = ../pa_common/pa_lib.c pa_freebsd.c -PAINC = ../pa_common/portaudio.h - -# Tests that work. -#TESTC = $(PASRC) ../pa_tests/patest_sine.c -TESTC = $(PASRC) ../pa_tests/patest_sine_time.c -#TESTC = $(PASRC) ../pa_tests/patest_stop.c -#TESTC = $(PASRC) ../pa_tests/patest_sync.c -#TESTC = $(PASRC) ../pa_tests/patest_pink.c -#TESTC = $(PASRC) ../pa_tests/patest_leftright.c -#TESTC = $(PASRC) ../pa_tests/patest_clip.c -#TESTC = $(PASRC) ../pa_tests/patest_dither.c -#TESTC = $(PASRC) ../pa_tests/pa_devs.c -#TESTC = $(PASRC) ../pa_tests/patest_many.c -#TESTC = $(PASRC) ../pa_tests/patest_record.c -#TESTC = $(PASRC) ../pa_tests/patest_wire.c -#TESTC = $(PASRC) ../pa_tests/paqa_devs.c - -# Tests that do not yet work. - -TESTH = $(PAINC) - -all: patest - -patest: $(TESTC) $(TESTH) Makefile - gcc $(CFLAGS) $(TESTC) $(CDEFINES) $(LIBS) -o patest - -run: patest - ./patest - diff --git a/pa_unix_oss/pa_unix_oss.c b/pa_unix_oss/pa_unix_oss.c index 97f513d..8f2ec52 100644 --- a/pa_unix_oss/pa_unix_oss.c +++ b/pa_unix_oss/pa_unix_oss.c @@ -1,9 +1,15 @@ /* + * $Id$ * PortAudio Portable Real-Time Audio Library * Latest Version at: http://www.portaudio.com - * Linux OSS Implementation by douglas repetto and Phil Burk + * OSS implementation by: + * Douglas Repetto + * Phil Burk + * Dominic Mazzoni + * Arve Knudsen * - * Copyright (c) 1999-2000 Phil Burk + * 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 @@ -27,300 +33,337 @@ * 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. - * */ -/* -Modfication History - 1/2001 - Phil Burk - initial hack for Linux - 2/2001 - Douglas Repetto - many improvements, initial query support - 4/2/2001 - Phil - stop/abort thread control, separate in/out native buffers - 5/28/2001 - Phil - use pthread_create() instead of clone(). Thanks Stephen Brandon! - use pthread_join() after thread shutdown. - 5/29/2001 - Phil - query for multiple devices, multiple formats, - input mode and input+output mode working, - Pa_GetCPULoad() implemented. - PLB20010817 - Phil & Janos Haber - don't halt if test of sample rate fails. - SB20010904 - Stephen Brandon - mods needed for GNUSTEP and SndKit - JH20010905 - Janos Haber - FreeBSD mods - 2001-09-22 - Heiko - (i.e. Heiko Purnhagen ;-) - added 24k and 16k to ratesToTry[] - fixed Pa_GetInternalDevice() - changed DEVICE_NAME_BASE from /dev/audio to /dev/dsp - handled SNDCTL_DSP_SPEED in Pq_QueryDevice() more graceful - fixed Pa_StreamTime() for paqa_errs.c - fixed numCannel=2 oddity and error handling in Pa_SetupDeviceFormat() - grep also for HP20010922 ... - PLB20010924 - Phil - merged Heiko's changes - removed sNumDevices and potential related bugs, - use getenv("PA_MIN_LATENCY_MSEC") to set desired latency, - simplify CPU Load calculation by comparing real-time to framesPerBuffer, - always close device when querying even if error occurs, - PLB20010927 - Phil - Improved negotiation for numChannels. - SG20011005 - Stewart Greenhill - set numChannels back to reasonable value after query. - DH20010115 - David Herring - fixed uninitialized handle. - - DM20020218 - Dominic Mazzoni - Try to open in nonblocking mode first, in case - the device is already open. New implementation of - Pa_StreamTime that uses SNDCTL_DSP_GETOPTR but - uses our own counter to avoid wraparound. - PLB20020222 - Phil Burk - Added WatchDog proc if audio running at high priority. - Check error return from read() and write(). - Check CPU endianness instead of assuming Little Endian. - -TODO -O- put semaphore lock around shared data? -O- handle native formats better -O- handle stereo-only device better ??? -O- what if input and output of a device capabilities differ (e.g. es1371) ??? -*/ -/* - PROPOSED - should we add this to "portaudio.h". Problem with - Pa_QueryDevice() not having same driver name os Pa_OpenStream(). - - A PaDriverInfo structure can be passed to the underlying device - on the Pa_OpenStream() call. The contents and interpretation of - the structure is determined by the PA implementation. -*/ -typedef struct PaDriverInfo /* PROPOSED */ -{ - /* Size of structure. Allows driver to extend the structure without breaking existing applications. */ - int size; - /* Can be used to request a specific device name. */ - const char *name; - unsigned long data; -} -PaDriverInfo; - - #include -#include -#include -#include +#include #include -#include -#include #include +#include #include -#include -#include #include +#include +#include +#include #include - -#ifdef __linux__ -#include +#include +#include +#include +#include +#include + +#ifdef __FreeBSD__ +# include +# define DEVICE_NAME_BASE "/dev/dsp" +#elif defined __linux__ +# include +# define DEVICE_NAME_BASE "/dev/dsp" #else -#include /* JH20010905 */ +# include /* JH20010905 */ +# define DEVICE_NAME_BASE "/dev/audio" #endif #include "portaudio.h" -#include "pa_host.h" -#include "pa_trace.h" - -#define PRINT(x) { printf x; fflush(stdout); } -#define ERR_RPT(x) PRINT(x) -#define DBUG(x) /* PRINT(x) */ -#define DBUGX(x) /* PRINT(x) */ - -#define BAD_DEVICE_ID (-1) +#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/pa_unix_util.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 ); -#define MIN_LATENCY_MSEC (100) -#define MIN_TIMEOUT_MSEC (100) -#define MAX_TIMEOUT_MSEC (1000) - -/************************************************* Definitions ********/ -#ifdef __linux__ - #define DEVICE_NAME_BASE "/dev/dsp" -#else - #define DEVICE_NAME_BASE "/dev/audio" +#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 -/* What is a pthread_t anyway? Here is a guess at a value that will never happen in real life. */ -#define INVALID_THREAD (-1) +/* PaOSSHostApiRepresentation - host api datastructure specific to this implementation */ -#define MAX_CHARS_DEVNAME (32) -#define MAX_SAMPLE_RATES (10) -typedef struct internalPortAudioDevice +typedef struct { - struct internalPortAudioDevice *pad_Next; /* Singly linked list. */ - double pad_SampleRates[MAX_SAMPLE_RATES]; /* for pointing to from pad_Info */ - char pad_DeviceName[MAX_CHARS_DEVNAME]; - PaDeviceInfo pad_Info; + PaUtilHostApiRepresentation inheritedHostApiRep; + PaUtilStreamInterface callbackStreamInterface; + PaUtilStreamInterface blockingStreamInterface; + + PaUtilAllocationGroup *allocations; + + PaHostApiIndex hostApiIndex; } -internalPortAudioDevice; +PaOSSHostApiRepresentation; -/* Define structure to contain all OSS and Linux specific data. */ -typedef struct PaHostSoundControl +/** 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 pahsc_OutputHandle; - int pahsc_InputHandle; - int pahsc_AudioPriority; /* priority of background audio thread */ - pthread_t pahsc_AudioThread; /* background audio thread */ - pid_t pahsc_AudioThreadPID; /* background audio thread */ - pthread_t pahsc_WatchDogThread; /* highest priority thread that protects system */ - int pahsc_WatchDogRun; /* Ask WatchDog to stop. */ - pthread_t pahsc_CanaryThread; /* low priority thread that detects abuse by audio */ - struct timeval pahsc_CanaryTime; - int pahsc_CanaryRun; /* Ask Canary to stop. */ - short *pahsc_NativeInputBuffer; - short *pahsc_NativeOutputBuffer; - unsigned int pahsc_BytesPerInputBuffer; /* native buffer size in bytes */ - unsigned int pahsc_BytesPerOutputBuffer; /* native buffer size in bytes */ - /* For measuring CPU utilization. */ - struct timeval pahsc_EntryTime; - double pahsc_InverseMicrosPerBuffer; /* 1/Microseconds of real-time audio per user buffer. */ - - /* For calculating stream time */ - int pahsc_LastPosPtr; - double pahsc_LastStreamBytes; -} -PaHostSoundControl; + 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; -/************************************************* Shared Data ********/ -/* FIXME - put Mutex around this shared data. */ -static internalPortAudioDevice *sDeviceList = NULL; -static int sDefaultInputDeviceID = paNoDevice; -static int sDefaultOutputDeviceID = paNoDevice; -static int sPaHostError = 0; + PaUtilThreading threading; -/************************************************* Prototypes **********/ + int sharedDevice; + unsigned long framesPerHostBuffer; + int triggered; /* Have the devices been triggered yet (first start) */ -static internalPortAudioDevice *Pa_GetInternalDevice( PaDeviceID id ); -static PaError Pa_QueryDevices( void ); -static PaError Pa_QueryDevice( const char *deviceName, internalPortAudioDevice *pad ); -static PaError Pa_SetupDeviceFormat( int devHandle, int numChannels, int sampleRate ); + int isActive; + int isStopped; -/********************************* BEGIN CPU UTILIZATION MEASUREMENT ****/ -static void Pa_StartUsageCalculation( internalPortAudioStream *past ) -{ - PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; - if( pahsc == NULL ) return; - /* Query system timer for usage analysis and to prevent overuse of CPU. */ - gettimeofday( &pahsc->pahsc_EntryTime, NULL ); -} + int lastPosPtr; + double lastStreamBytes; -static long SubtractTime_AminusB( struct timeval *timeA, struct timeval *timeB ) -{ - long secs = timeA->tv_sec - timeB->tv_sec; - long usecs = secs * 1000000; - usecs += (timeA->tv_usec - timeB->tv_usec); - return usecs; -} + int framesProcessed; -/****************************************************************************** -** Measure fractional CPU load based on real-time it took to calculate -** buffers worth of output. -*/ -static void Pa_EndUsageCalculation( internalPortAudioStream *past ) -{ - struct timeval currentTime; - long usecsElapsed; - double newUsage; + double sampleRate; + + int callbackMode; + int callbackStop, callbackAbort; -#define LOWPASS_COEFFICIENT_0 (0.95) -#define LOWPASS_COEFFICIENT_1 (0.99999 - LOWPASS_COEFFICIENT_0) + 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(); - PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; - if( pahsc == NULL ) return; + return result; - if( gettimeofday( ¤tTime, NULL ) == 0 ) +error: + if( ossHostApi ) { - usecsElapsed = SubtractTime_AminusB( ¤tTime, &pahsc->pahsc_EntryTime ); - /* Use inverse because it is faster than the divide. */ - newUsage = usecsElapsed * pahsc->pahsc_InverseMicrosPerBuffer; - - past->past_Usage = (LOWPASS_COEFFICIENT_0 * past->past_Usage) + - (LOWPASS_COEFFICIENT_1 * newUsage); + if( ossHostApi->allocations ) + { + PaUtil_FreeAllAllocations( ossHostApi->allocations ); + PaUtil_DestroyAllocationGroup( ossHostApi->allocations ); + } + + PaUtil_FreeMemory( ossHostApi ); } + return result; } -/****************************************** END CPU UTILIZATION *******/ -#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 ) +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 ) { - 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; + 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; } -#endif -/********************************************************************* - * Try to open the named device. - * If it opens, try to set various rates and formats and fill in - * the device info structure. - */ -static PaError Pa_QueryDevice( const char *deviceName, internalPortAudioDevice *pad ) +static PaError QueryDirection( const char *deviceName, StreamMode mode, double *defaultSampleRate, int *maxChannelCount, + double *defaultLowLatency, double *defaultHighLatency ) { - int result = paHostError; - int tempDevHandle; + PaError result = paNoError; int numChannels, maxNumChannels; - int format; - int numSampleRates; - int sampleRate; - int numRatesToTry; - int ratesToTry[9] = {96000, 48000, 44100, 32000, 24000, 22050, 16000, 11025, 8000}; - int i; + int busy = 0; + int devHandle = -1; + int sr; + *maxChannelCount = 0; /* Default value in case this fails */ - /* 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 - - */ - if ( (tempDevHandle = open(deviceName,O_WRONLY|O_NONBLOCK)) == -1 ) + if ( (devHandle = open( deviceName, (mode == StreamMode_In ? O_RDONLY : O_WRONLY) | O_NONBLOCK )) < 0 ) { - DBUG(("Pa_QueryDevice: could not open %s\n", deviceName )); - return paHostError; - } + 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 ) )); + } - /* Ask OSS what formats are supported by the hardware. */ - pad->pad_Info.nativeSampleFormats = 0; - if (ioctl(tempDevHandle, SNDCTL_DSP_GETFMTS, &format) == -1) - { - ERR_RPT(("Pa_QueryDevice: could not get format info\n" )); - goto error; + return paDeviceUnavailable; } - if( format & AFMT_U8 ) pad->pad_Info.nativeSampleFormats |= paUInt8; - if( format & AFMT_S16_NE ) pad->pad_Info.nativeSampleFormats |= paInt16; /* Negotiate for the maximum number of channels for this device. PLB20010927 * Consider up to 16 as the upper number of channels. - * Variable numChannels should contain the actual upper limit after the call. + * 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; - DBUG(("Pa_QueryDevice: use SNDCTL_DSP_CHANNELS, numChannels = %d\n", numChannels )) - if(ioctl(tempDevHandle, SNDCTL_DSP_CHANNELS, &temp) < 0 ) + if( ioctl( devHandle, SNDCTL_DSP_CHANNELS, &temp ) < 0 ) { + busy = EAGAIN == errno || EBUSY == errno; /* ioctl() failed so bail out if we already have stereo */ - if( numChannels > 2 ) break; + 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; - DBUG(("Pa_QueryDevice: temp = %d\n", temp )) - if( temp > maxNumChannels ) maxNumChannels = temp; /* Save maximum. */ + 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(tempDevHandle, SNDCTL_DSP_STEREO, &stereo) < 0) + if( ioctl( devHandle, SNDCTL_DSP_STEREO, &stereo ) < 0 ) { maxNumChannels = 1; } @@ -328,577 +371,590 @@ static PaError Pa_QueryDevice( const char *deviceName, internalPortAudioDevice * { maxNumChannels = (stereo) ? 2 : 1; } - DBUG(("Pa_QueryDevice: use SNDCTL_DSP_STEREO, maxNumChannels = %d\n", maxNumChannels )) + PA_DEBUG(( "%s: use SNDCTL_DSP_STEREO, maxNumChannels = %d\n", __FUNCTION__, maxNumChannels )) } - pad->pad_Info.maxOutputChannels = maxNumChannels; - DBUG(("Pa_QueryDevice: maxNumChannels = %d\n", 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 */ { - int temp = maxNumChannels; - if( temp > 2 ) temp = 2; /* use most reasonable default value */ - ioctl(tempDevHandle, SNDCTL_DSP_CHANNELS, &temp); + /* use most reasonable default value */ + int temp = PA_MIN( maxNumChannels, 2 ); + ENSURE_( ioctl( devHandle, SNDCTL_DSP_CHANNELS, &temp ), paUnanticipatedHostError ); } - /* FIXME - for now, assume maxInputChannels = maxOutputChannels. - * Eventually do separate queries for O_WRONLY and O_RDONLY - */ - pad->pad_Info.maxInputChannels = pad->pad_Info.maxOutputChannels; - - DBUG(("Pa_QueryDevice: maxInputChannels = %d\n", - pad->pad_Info.maxInputChannels)) - - - /* Determine available sample rates by trying each one and seeing result. - */ - numSampleRates = 0; - numRatesToTry = sizeof(ratesToTry)/sizeof(int); - for (i = 0; i < numRatesToTry; i++) + /* Get supported sample rate closest to 44100 Hz */ + if( *defaultSampleRate < 0 ) { - sampleRate = ratesToTry[i]; - - if (ioctl(tempDevHandle, SNDCTL_DSP_SPEED, &sampleRate) >= 0 ) /* PLB20010817 */ + sr = 44100; + if( ioctl( devHandle, SNDCTL_DSP_SPEED, &sr ) < 0 ) { - if (sampleRate == ratesToTry[i]) - { - DBUG(("Pa_QueryDevice: got sample rate: %d\n", sampleRate)) - pad->pad_SampleRates[numSampleRates] = (float)ratesToTry[i]; - numSampleRates++; - } + result = paUnanticipatedHostError; + goto error; } - } - DBUG(("Pa_QueryDevice: final numSampleRates = %d\n", numSampleRates)) - if (numSampleRates==0) /* HP20010922 */ - { - ERR_RPT(("Pa_QueryDevice: no supported sample rate (or SNDCTL_DSP_SPEED ioctl call failed).\n" )); - goto error; + *defaultSampleRate = sr; } - pad->pad_Info.numSampleRates = numSampleRates; - pad->pad_Info.sampleRates = pad->pad_SampleRates; - - pad->pad_Info.name = deviceName; - - result = paNoError; + *maxChannelCount = maxNumChannels; + /* TODO */ + *defaultLowLatency = 512. / *defaultSampleRate; + *defaultHighLatency = 2048. / *defaultSampleRate; error: - /* We MUST close the handle here or we won't be able to reopen it later!!! */ - close(tempDevHandle); + if( devHandle >= 0 ) + close( devHandle ); return result; } -/********************************************************************* - * Determines the number of available devices by trying to open - * each "/dev/dsp#" or "/dsp/audio#" in order until it fails. - * Add each working device to a singly linked list of devices. +/** 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 Pa_QueryDevices( void ) +static PaError QueryDevice( char *deviceName, PaOSSHostApiRepresentation *ossApi, PaDeviceInfo **deviceInfo ) { - internalPortAudioDevice *pad, *lastPad; - int go = 1; - int numDevices = 0; - PaError testResult; - PaError result = paNoError; - - sDefaultInputDeviceID = paNoDevice; - sDefaultOutputDeviceID = paNoDevice; + PaError result = paNoError; + double sampleRate = -1.; + int maxInputChannels, maxOutputChannels; + PaTime defaultLowInputLatency, defaultLowOutputLatency, defaultHighInputLatency, defaultHighOutputLatency; + PaError tmpRes = paNoError; + int busy = 0; + *deviceInfo = NULL; - lastPad = 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 + */ - while( go ) + /* 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 ) { - /* Allocate structure to hold device info. */ - pad = PaHost_AllocateFastMemory( sizeof(internalPortAudioDevice) ); - if( pad == NULL ) return paInsufficientMemory; - memset( pad, 0, sizeof(internalPortAudioDevice) ); - - /* Build name for device. */ - if( numDevices == 0 ) - { - sprintf( pad->pad_DeviceName, DEVICE_NAME_BASE); - } - else - { - sprintf( pad->pad_DeviceName, DEVICE_NAME_BASE "%d", numDevices ); - } - - DBUG(("Try device %s\n", pad->pad_DeviceName )); - testResult = Pa_QueryDevice( pad->pad_DeviceName, pad ); - DBUG(("Pa_QueryDevice returned %d\n", testResult )); - if( testResult != paNoError ) + if( tmpRes != paDeviceUnavailable ) { - if( lastPad == NULL ) - { - result = testResult; /* No good devices! */ - } - go = 0; - PaHost_FreeFastMemory( pad, sizeof(internalPortAudioDevice) ); + PA_DEBUG(( "%s: Querying device %s for capture failed!\n", __FUNCTION__, deviceName )); + /* PA_ENSURE( tmpRes ); */ } - else + ++busy; + } + if( (tmpRes = QueryDirection( deviceName, StreamMode_Out, &sampleRate, &maxOutputChannels, &defaultLowOutputLatency, + &defaultHighOutputLatency )) != paNoError ) + { + if( tmpRes != paDeviceUnavailable ) { - numDevices += 1; - /* Add to linked list of devices. */ - if( lastPad ) - { - lastPad->pad_Next = pad; - } - else - { - sDeviceList = pad; /* First element in linked list. */ - } - lastPad = pad; + 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; } - return result; + 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; } -/*************************************************************************/ -int Pa_CountDevices() +/** 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 ) { - int numDevices = 0; - internalPortAudioDevice *pad; + 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: Can there only be 10 devices? */ - if( sDeviceList == NULL ) Pa_Initialize(); - /* Count devices in list. */ - pad = sDeviceList; - while( pad != NULL ) + for( i = 0; i < 10; i++ ) { - pad = pad->pad_Next; - numDevices++; + 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; + } } - return numDevices; + /* 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 internalPortAudioDevice *Pa_GetInternalDevice( PaDeviceID id ) +static void Terminate( struct PaUtilHostApiRepresentation *hostApi ) { - internalPortAudioDevice *pad; - if( (id < 0) || ( id >= Pa_CountDevices()) ) return NULL; - pad = sDeviceList; - while( id > 0 ) + PaOSSHostApiRepresentation *ossHostApi = (PaOSSHostApiRepresentation*)hostApi; + + if( ossHostApi->allocations ) { - pad = pad->pad_Next; - id--; + PaUtil_FreeAllAllocations( ossHostApi->allocations ); + PaUtil_DestroyAllocationGroup( ossHostApi->allocations ); } - return pad; -} -/*************************************************************************/ -const PaDeviceInfo* Pa_GetDeviceInfo( PaDeviceID id ) -{ - internalPortAudioDevice *pad; - if( (id < 0) || ( id >= Pa_CountDevices()) ) return NULL; - pad = Pa_GetInternalDevice( id ); - return &pad->pad_Info ; + PaUtil_FreeMemory( ossHostApi ); } -static PaError Pa_MaybeQueryDevices( void ) +static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi, + const PaStreamParameters *inputParameters, + const PaStreamParameters *outputParameters, + double sampleRate ) { - if( sDeviceList == NULL ) + PaError result = paNoError; + PaDeviceIndex device; + PaDeviceInfo *deviceInfo; + char *deviceName; + int inputChannelCount, outputChannelCount; + int tempDevHandle = -1; + int flags; + PaSampleFormat inputSampleFormat, outputSampleFormat; + + if( inputParameters ) { - return Pa_QueryDevices(); - } - return 0; -} + inputChannelCount = inputParameters->channelCount; + inputSampleFormat = inputParameters->sampleFormat; -PaDeviceID Pa_GetDefaultInputDeviceID( void ) -{ - /* return paNoDevice; */ - return 0; -} + /* unless alternate device specification is supported, reject the use of + paUseHostApiSpecificDeviceSpecification */ -PaDeviceID Pa_GetDefaultOutputDeviceID( void ) -{ - return 0; -} + if( inputParameters->device == paUseHostApiSpecificDeviceSpecification ) + return paInvalidDevice; -/********************************************************************** -** Make sure that we have queried the device capabilities. -*/ + /* check that input device can support inputChannelCount */ + if( inputChannelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels ) + return paInvalidChannelCount; -PaError PaHost_Init( void ) -{ - return Pa_MaybeQueryDevices(); -} + /* validate inputStreamInfo */ + if( inputParameters->hostApiSpecificStreamInfo ) + return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */ + } + else + { + inputChannelCount = 0; + } -/******************************************************************************************* - * The ol' Canary in a Coal Mine trick. - * Just update the time periodically. - * Runs at low priority so if audio thread runs wild, this thread will get starved - * and the watchdog will detect it. - */ - -#define SCHEDULER_POLICY SCHED_RR -#define WATCHDOG_MAX_SECONDS (3) -#define WATCHDOG_INTERVAL_USEC (1000000) + if( outputParameters ) + { + outputChannelCount = outputParameters->channelCount; + outputSampleFormat = outputParameters->sampleFormat; + + /* unless alternate device specification is supported, reject the use of + paUseHostApiSpecificDeviceSpecification */ -static int PaHost_CanaryProc( PaHostSoundControl *pahsc ) -{ - int result = 0; + if( outputParameters->device == paUseHostApiSpecificDeviceSpecification ) + return paInvalidDevice; -#ifdef GNUSTEP - GSRegisterCurrentThread(); /* SB20010904 */ -#endif + /* check that output device can support inputChannelCount */ + if( outputChannelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels ) + return paInvalidChannelCount; - while( pahsc->pahsc_CanaryRun && ((result = usleep( WATCHDOG_INTERVAL_USEC )) == 0) ) - { - gettimeofday( &pahsc->pahsc_CanaryTime, NULL ); + /* validate outputStreamInfo */ + if( outputParameters->hostApiSpecificStreamInfo ) + return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */ + } + else + { + outputChannelCount = 0; } - DBUG(("PaHost_CanaryProc: exiting.\n")); - -#ifdef GNUSTEP - GSUnregisterCurrentThread(); /* SB20010904 */ -#endif + if (inputChannelCount == 0 && outputChannelCount == 0) + return paInvalidChannelCount; - return result; -} + /* if full duplex, make sure that they're the same device */ -/******************************************************************************************* - * Monitor audio thread and lower its it if it hogs the CPU. - * To prevent getting killed, the audio thread must update a - * variable with a timer value. - * If the value is not recent enough, then the - * thread will get killed. - */ + if (inputChannelCount > 0 && outputChannelCount > 0 && + inputParameters->device != outputParameters->device) + return paInvalidDevice; -static PaError PaHost_WatchDogProc( PaHostSoundControl *pahsc ) -{ - PaError result = 0; - struct sched_param schp = { 0 }; - int maxPri; + /* if full duplex, also make sure that they're the same number of channels */ -#ifdef GNUSTEP - GSRegisterCurrentThread(); /* SB20010904 */ -#endif - -/* Run at a priority level above audio thread so we can still run if it hangs. */ -/* Rise more than 1 because of rumored off-by-one scheduler bugs. */ - schp.sched_priority = pahsc->pahsc_AudioPriority + 4; - maxPri = sched_get_priority_max(SCHEDULER_POLICY); - if( schp.sched_priority > maxPri ) schp.sched_priority = maxPri; + if (inputChannelCount > 0 && outputChannelCount > 0 && + inputChannelCount != outputChannelCount) + return paInvalidChannelCount; - if (sched_setscheduler(0, SCHEDULER_POLICY, &schp) != 0) - { - ERR_RPT(("PaHost_WatchDogProc: cannot set watch dog priority!\n")); - goto killAudio; - } + /* open the device so we can do more tests */ - /* Compare watchdog time with audio and canary thread times. */ - /* Sleep for a while or until thread cancelled. */ - while( pahsc->pahsc_WatchDogRun && ((result = usleep( WATCHDOG_INTERVAL_USEC )) == 0) ) + if( inputChannelCount > 0 ) { - int delta; - struct timeval currentTime; - - gettimeofday( ¤tTime, NULL ); - - /* If audio thread is not advancing, then lower its priority. */ - delta = currentTime.tv_sec - pahsc->pahsc_EntryTime.tv_sec; - DBUG(("PaHost_WatchDogProc: audio delta = %d\n", delta )); - if( delta > WATCHDOG_MAX_SECONDS ) - { - goto killAudio; - } - - /* If canary died, then kill audio and canary. */ - delta = currentTime.tv_sec - pahsc->pahsc_CanaryTime.tv_sec; - if( delta > WATCHDOG_MAX_SECONDS ) - { - ERR_RPT(("PaHost_WatchDogProc: canary died!\n")); - goto lowerAudio; - } + result = PaUtil_DeviceIndexToHostApiDeviceIndex(&device, inputParameters->device, hostApi); + if (result != paNoError) + return result; } - - DBUG(("PaHost_WatchDogProc: exiting.\n")); -#ifdef GNUSTEP - GSUnregisterCurrentThread(); /* SB20010904 */ -#endif - return 0; - -lowerAudio: + else { - struct sched_param schat = { 0 }; - if( sched_setscheduler(pahsc->pahsc_AudioThreadPID, SCHED_OTHER, &schat) != 0) - { - ERR_RPT(("PaHost_WatchDogProc: failed to lower audio priority. errno = %d\n", errno )); - /* Fall through into killing audio thread. */ - } - else - { - ERR_RPT(("PaHost_WatchDogProc: lowered audio priority to prevent hogging of CPU.\n")); - goto cleanup; - } + result = PaUtil_DeviceIndexToHostApiDeviceIndex(&device, outputParameters->device, hostApi); + if (result != paNoError) + return result; } + + deviceInfo = hostApi->deviceInfos[device]; + deviceName = (char *)deviceInfo->name; -killAudio: - ERR_RPT(("PaHost_WatchDogProc: killing hung audio thread!\n")); - pthread_kill( pahsc->pahsc_AudioThread, SIGKILL ); - -cleanup: - pahsc->pahsc_CanaryRun = 0; - DBUG(("PaHost_WatchDogProc: cancel Canary\n")); - pthread_cancel( pahsc->pahsc_CanaryThread ); - DBUG(("PaHost_WatchDogProc: join Canary\n")); - pthread_join( pahsc->pahsc_CanaryThread, NULL ); - DBUG(("PaHost_WatchDogProc: forget Canary\n")); - pahsc->pahsc_CanaryThread = INVALID_THREAD; - -#ifdef GNUSTEP - GSUnregisterCurrentThread(); /* SB20010904 */ -#endif - return 0; + 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; } -/*******************************************************************************************/ -static void PaHost_StopWatchDog( PaHostSoundControl *pahsc ) -{ -/* Cancel WatchDog thread if there is one. */ - if( pahsc->pahsc_WatchDogThread != INVALID_THREAD ) +/** 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 ) { - pahsc->pahsc_WatchDogRun = 0; - DBUG(("PaHost_StopWatchDog: cancel WatchDog\n")); - pthread_cancel( pahsc->pahsc_WatchDogThread ); - pthread_join( pahsc->pahsc_WatchDogThread, NULL ); - pahsc->pahsc_WatchDogThread = INVALID_THREAD; + return paInvalidDevice; } -/* Cancel Canary thread if there is one. */ - if( pahsc->pahsc_CanaryThread != INVALID_THREAD ) + + maxChans = (mode == StreamMode_In ? deviceInfo->maxInputChannels : + deviceInfo->maxOutputChannels); + if( parameters->channelCount > maxChans ) { - pahsc->pahsc_CanaryRun = 0; - DBUG(("PaHost_StopWatchDog: cancel Canary\n")); - pthread_cancel( pahsc->pahsc_CanaryThread ); - DBUG(("PaHost_StopWatchDog: join Canary\n")); - pthread_join( pahsc->pahsc_CanaryThread, NULL ); - pahsc->pahsc_CanaryThread = INVALID_THREAD; + return paInvalidChannelCount; } + + return paNoError; } -/*******************************************************************************************/ -static PaError PaHost_StartWatchDog( PaHostSoundControl *pahsc ) +static PaError PaOssStreamComponent_Initialize( PaOssStreamComponent *component, const PaStreamParameters *parameters, + int callbackMode, int fd, const char *deviceName ) { - int hres; - PaError result = 0; - - /* The watch dog watches for these timer updates */ - gettimeofday( &pahsc->pahsc_EntryTime, NULL ); - gettimeofday( &pahsc->pahsc_CanaryTime, NULL ); - - /* Launch a canary thread to detect priority abuse. */ - pahsc->pahsc_CanaryRun = 1; - hres = pthread_create(&(pahsc->pahsc_CanaryThread), - NULL /*pthread_attr_t * attr*/, - (void*)PaHost_CanaryProc, pahsc); - if( hres != 0 ) - { - pahsc->pahsc_CanaryThread = INVALID_THREAD; - result = paHostError; - sPaHostError = hres; - goto error; - } + 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); - /* Launch a watchdog thread to prevent runaway audio thread. */ - pahsc->pahsc_WatchDogRun = 1; - hres = pthread_create(&(pahsc->pahsc_WatchDogThread), - NULL /*pthread_attr_t * attr*/, - (void*)PaHost_WatchDogProc, pahsc); - if( hres != 0 ) + if( !callbackMode && !component->userInterleaved ) { - pahsc->pahsc_WatchDogThread = INVALID_THREAD; - result = paHostError; - sPaHostError = hres; - goto error; + /* Pre-allocate non-interleaved user provided buffers */ + PA_UNLESS( component->userBuffers = PaUtil_AllocateMemory( sizeof (void *) * component->userChannelCount ), + paInsufficientMemory ); } - return result; - + error: - PaHost_StopWatchDog( pahsc ); return result; } -/******************************************************************************************* - * Bump priority of audio thread if running with superuser priveledges. - * if priority bumped then launch a watchdog. - */ -static PaError PaHost_BoostPriority( internalPortAudioStream *past ) +static void PaOssStreamComponent_Terminate( PaOssStreamComponent *component ) { - PaHostSoundControl *pahsc; - PaError result = paNoError; - struct sched_param schp = { 0 }; - - pahsc = (PaHostSoundControl *) past->past_DeviceData; - if( pahsc == NULL ) return paInternalError; - - pahsc->pahsc_AudioThreadPID = getpid(); - DBUG(("PaHost_BoostPriority: audio PID = %d\n", pahsc->pahsc_AudioThreadPID )); - - /* Choose a priority in the middle of the range. */ - pahsc->pahsc_AudioPriority = (sched_get_priority_max(SCHEDULER_POLICY) - - sched_get_priority_min(SCHEDULER_POLICY)) / 2; - schp.sched_priority = pahsc->pahsc_AudioPriority; + assert( component ); - if (sched_setscheduler(0, SCHEDULER_POLICY, &schp) != 0) - { - PRINT(("PortAudio: only superuser can use real-time priority.\n")); - } - else - { - PRINT(("PortAudio: audio callback priority set to level %d!\n", schp.sched_priority)); - /* We are running at high priority so we should have a watchdog in case audio goes wild. */ - result = PaHost_StartWatchDog( pahsc ); - } - - return result; + 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 Pa_AudioThreadProc( internalPortAudioStream *past ) +static PaError ModifyBlocking( int fd, int blocking ) { - PaError result; - PaHostSoundControl *pahsc; - ssize_t bytes_read, bytes_written; - count_info info; - int delta; - - pahsc = (PaHostSoundControl *) past->past_DeviceData; - if( pahsc == NULL ) return paInternalError; - -#ifdef GNUSTEP - GSRegisterCurrentThread(); /* SB20010904 */ -#endif + PaError result = paNoError; + int fflags; - result = PaHost_BoostPriority( past ); - if( result < 0 ) goto error; + ENSURE_( fflags = fcntl( fd, F_GETFL ), paUnanticipatedHostError ); - past->past_IsActive = 1; - DBUG(("entering thread.\n")); + if( blocking ) + fflags &= ~O_NONBLOCK; + else + fflags |= O_NONBLOCK; + + ENSURE_( fcntl( fd, F_SETFL, fflags ), paUnanticipatedHostError ); - while( (past->past_StopNow == 0) && (past->past_StopSoon == 0) ) +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 ) { - /* Read data from device */ - if(pahsc->pahsc_NativeInputBuffer) - { - DBUG(("Pa_AudioThreadProc: attempt to read %d bytes\n", pahsc->pahsc_BytesPerInputBuffer)); - bytes_read = read(pahsc->pahsc_InputHandle, - (void *)pahsc->pahsc_NativeInputBuffer, - pahsc->pahsc_BytesPerInputBuffer); - DBUG(("Pa_AudioThreadProc: bytes_read = %d\n", bytes_read)); - if( bytes_read < pahsc->pahsc_BytesPerInputBuffer ) - { - ERR_RPT(("PortAudio: read interrupted! Only got %d bytes.\n", bytes_read )); - break; - } - } + duplex = 1; + flags |= O_RDWR; + } + else if( idevName ) + flags |= O_RDONLY; + else + flags |= O_WRONLY; - /* Convert 16 bit native data to user data and call user routine. */ - DBUG(("converting...\n")); - Pa_StartUsageCalculation( past ); - result = Pa_CallConvertInt16( past, - pahsc->pahsc_NativeInputBuffer, - pahsc->pahsc_NativeOutputBuffer ); - Pa_EndUsageCalculation( past ); - if( result != 0) - { - DBUG(("hmm, Pa_CallConvertInt16() says: %d. i'm bailing.\n", - result)); - break; - } + /* 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 */ - /* Write data to device. */ - if( pahsc->pahsc_NativeOutputBuffer ) + /* 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 */ - bytes_written = write(pahsc->pahsc_OutputHandle, - (void *)pahsc->pahsc_NativeOutputBuffer, - pahsc->pahsc_BytesPerOutputBuffer); - if( bytes_written < pahsc->pahsc_BytesPerOutputBuffer ) - { - ERR_RPT(("PortAudio: write interrupted! Only got %d bytes.\n", bytes_written )); - break; - } + /* Initially disable */ + enableBits = ~PCM_ENABLE_OUTPUT; + ENSURE_( ioctl( *odev, SNDCTL_DSP_SETTRIGGER, &enableBits ), paUnanticipatedHostError ); } - - /* Update current stream time (using a double so that - we don't wrap around like info.bytes does) */ - if( pahsc->pahsc_NativeOutputBuffer ) - ioctl(pahsc->pahsc_OutputHandle, SNDCTL_DSP_GETOPTR, &info); else - ioctl(pahsc->pahsc_InputHandle, SNDCTL_DSP_GETIPTR, &info); - delta = (info.bytes - pahsc->pahsc_LastPosPtr) & 0x000FFFFF; - pahsc->pahsc_LastStreamBytes += delta; - pahsc->pahsc_LastPosPtr = info.bytes; + { + ENSURE_( *odev = dup( *idev ), paUnanticipatedHostError ); + } } - DBUG(("Pa_AudioThreadProc: left audio loop.\n")); - - past->past_IsActive = 0; - PaHost_StopWatchDog( pahsc ); - + error: - DBUG(("leaving audio thread.\n")); -#ifdef GNUSTEP - GSUnregisterCurrentThread(); /* SB20010904 */ -#endif return result; } -/*******************************************************************************************/ -static PaError Pa_SetupDeviceFormat( int devHandle, int numChannels, int sampleRate ) +static PaError PaOssStream_Initialize( PaOssStream *stream, const PaStreamParameters *inputParameters, const PaStreamParameters *outputParameters, + PaStreamCallback callback, void *userData, PaStreamFlags streamFlags, + PaOSSHostApiRepresentation *ossApi ) { PaError result = paNoError; - int tmp; + int idev, odev; + PaUtilHostApiRepresentation *hostApi = &ossApi->inheritedHostApiRep; + const char *idevName = NULL, *odevName = NULL; - /* Set format, channels, and rate in this order to keep OSS happy. */ - /* Set data format. FIXME - handle more native formats. */ - tmp = AFMT_S16_NE; - if( ioctl(devHandle,SNDCTL_DSP_SETFMT,&tmp) == -1) - { - ERR_RPT(("Pa_SetupDeviceFormat: could not SNDCTL_DSP_SETFMT\n" )); - return paHostError; - } - if( tmp != AFMT_S16_NE ) + assert( stream ); + + memset( stream, 0, sizeof (PaOssStream) ); + stream->isStopped = 1; + + PA_ENSURE( PaUtil_InitializeThreading( &stream->threading ) ); + + if( inputParameters && outputParameters ) { - ERR_RPT(("Pa_SetupDeviceFormat: HW does not support AFMT_S16_NE\n" )); - return paHostError; + if( inputParameters->device == outputParameters->device ) + stream->sharedDevice = 1; } - - /* Set number of channels. */ - tmp = numChannels; - if (ioctl(devHandle, SNDCTL_DSP_CHANNELS, &numChannels) == -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 ) { - ERR_RPT(("Pa_SetupDeviceFormat: could not SNDCTL_DSP_CHANNELS\n" )); - return paHostError; + PA_UNLESS( stream->capture = PaUtil_AllocateMemory( sizeof (PaOssStreamComponent) ), paInsufficientMemory ); + PA_ENSURE( PaOssStreamComponent_Initialize( stream->capture, inputParameters, callback != NULL, idev, idevName ) ); } - if( tmp != numChannels) + if( outputParameters ) { - ERR_RPT(("Pa_SetupDeviceFormat: HW does not support %d channels\n", numChannels )); - return paHostError; + PA_UNLESS( stream->playback = PaUtil_AllocateMemory( sizeof (PaOssStreamComponent) ), paInsufficientMemory ); + PA_ENSURE( PaOssStreamComponent_Initialize( stream->playback, outputParameters, callback != NULL, odev, odevName ) ); } - /* Set playing frequency. 44100, 22050 and 11025 are safe bets. */ - tmp = sampleRate; - if( ioctl(devHandle,SNDCTL_DSP_SPEED,&tmp) == -1) + if( callback != NULL ) { - ERR_RPT(("Pa_SetupDeviceFormat: could not SNDCTL_DSP_SPEED\n" )); - return paHostError; + PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation, + &ossApi->callbackStreamInterface, callback, userData ); + stream->callbackMode = 1; } - if( tmp != sampleRate) + else { - ERR_RPT(("Pa_SetupDeviceFormat: HW does not support %d Hz sample rate\n",sampleRate )); - return paHostError; + 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; @@ -906,472 +962,963 @@ static int CalcHigherLogTwo( int n ) return log2; } -/******************************************************************************************* -** Set number of fragments and size of fragments to achieve desired latency. -*/ -static void Pa_SetLatency( int devHandle, int numBuffers, int framesPerBuffer, int channelsPerFrame ) +static PaError PaOssStreamComponent_Configure( PaOssStreamComponent *component, double sampleRate, unsigned long framesPerBuffer, + StreamMode streamMode, PaOssStreamComponent *master ) { - int tmp; - int bufferSize, powerOfTwo; - - /* Increase size of buffers and reduce number of buffers to reduce latency inside driver. */ - while( numBuffers > 8 ) + PaError result = paNoError; + int temp, nativeFormat; + int sr = (int)sampleRate; + PaSampleFormat availableFormats, hostFormat; + int chans = component->userChannelCount; + int frgmt; + int numBufs; + int bytesPerBuf; + double 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 ) { - numBuffers = (numBuffers + 1) >> 1; - framesPerBuffer = framesPerBuffer << 1; - } + /* 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 = component->latency * sampleRate; + fragSz = bufSz / 4; + } + else + { + fragSz = framesPerBuffer; + bufSz = 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 = 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 ); - /* calculate size of buffers in bytes */ - bufferSize = framesPerBuffer * channelsPerFrame * sizeof(short); /* FIXME - other sizes? */ + /* 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 ); - /* Calculate next largest power of two */ - powerOfTwo = CalcHigherLogTwo( bufferSize ); - DBUG(("Pa_SetLatency: numBuffers = %d, framesPerBuffer = %d, powerOfTwo = %d\n", - numBuffers, framesPerBuffer, powerOfTwo )); + /* try to set the sample rate */ + ENSURE_( ioctl( component->fd, SNDCTL_DSP_SPEED, &sr ), paInvalidSampleRate ); - /* Encode info into a single int */ - tmp=(numBuffers<<16) + powerOfTwo; + /* 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; - if(ioctl(devHandle,SNDCTL_DSP_SETFRAGMENT,&tmp) == -1) + /* 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 { - ERR_RPT(("Pa_SetLatency: could not SNDCTL_DSP_SETFRAGMENT\n" )); - /* Don't return an error. Best to just continue and hope for the best. */ - ERR_RPT(("Pa_SetLatency: numBuffers = %d, framesPerBuffer = %d, powerOfTwo = %d\n", - numBuffers, framesPerBuffer, powerOfTwo )); + 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; } -/************************************************************************* -** 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 cshrc file. -*/ -#define PA_LATENCY_ENV_NAME ("PA_MIN_LATENCY_MSEC") +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; +} -int Pa_GetMinNumBuffers( int framesPerBuffer, double framesPerSecond ) +static PaError PaOssStreamComponent_Write( PaOssStreamComponent *component, unsigned long *frames ) { - int minBuffers; - int minLatencyMsec = MIN_LATENCY_MSEC; - char *minLatencyText = getenv(PA_LATENCY_ENV_NAME); - if( minLatencyText != NULL ) + 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; + 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 ) { - PRINT(("PA_MIN_LATENCY_MSEC = %s\n", minLatencyText )); - minLatencyMsec = atoi( minLatencyText ); - if( minLatencyMsec < 1 ) minLatencyMsec = 1; - else if( minLatencyMsec > 5000 ) minLatencyMsec = 5000; + 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; } - minBuffers = (int) ((minLatencyMsec * framesPerSecond) / ( 1000.0 * framesPerBuffer )); - if( minBuffers < 2 ) minBuffers = 2; - return minBuffers; + 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; } -/*******************************************************************/ -PaError PaHost_OpenStream( internalPortAudioStream *past ) +/* 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; - PaHostSoundControl *pahsc; - unsigned int minNumBuffers; - internalPortAudioDevice *pad; - DBUG(("PaHost_OpenStream() called.\n" )); - - /* Allocate and initialize host data. */ - pahsc = (PaHostSoundControl *) malloc(sizeof(PaHostSoundControl)); - if( pahsc == NULL ) + 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, outLatency; + + /* validate platform specific flags */ + if( (streamFlags & paPlatformSpecificFlags) != 0 ) + return paInvalidFlag; /* unexpected platform specific flag */ + + if( inputParameters ) { - result = paInsufficientMemory; - goto error; + /* 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; } - memset( pahsc, 0, sizeof(PaHostSoundControl) ); - past->past_DeviceData = (void *) pahsc; - - pahsc->pahsc_OutputHandle = BAD_DEVICE_ID; /* No device currently opened. */ - pahsc->pahsc_InputHandle = BAD_DEVICE_ID; - pahsc->pahsc_AudioThread = INVALID_THREAD; - pahsc->pahsc_WatchDogThread = INVALID_THREAD; - - /* Allocate native buffers. */ - pahsc->pahsc_BytesPerInputBuffer = past->past_FramesPerUserBuffer * - past->past_NumInputChannels * sizeof(short); - if( past->past_NumInputChannels > 0) + if( outputParameters ) { - pahsc->pahsc_NativeInputBuffer = (short *) malloc(pahsc->pahsc_BytesPerInputBuffer); - if( pahsc->pahsc_NativeInputBuffer == NULL ) - { - result = paInsufficientMemory; - goto error; - } + outputDeviceInfo = hostApi->deviceInfos[outputParameters->device]; + PA_ENSURE( ValidateParameters( outputParameters, outputDeviceInfo, StreamMode_Out ) ); + + outputChannelCount = outputParameters->channelCount; + outputSampleFormat = outputParameters->sampleFormat; } - pahsc->pahsc_BytesPerOutputBuffer = past->past_FramesPerUserBuffer * - past->past_NumOutputChannels * sizeof(short); - if( past->past_NumOutputChannels > 0) + + /* 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 ) { - pahsc->pahsc_NativeOutputBuffer = (short *) malloc(pahsc->pahsc_BytesPerOutputBuffer); - if( pahsc->pahsc_NativeOutputBuffer == NULL ) + if( inputParameters->device == outputParameters->device ) { - result = paInsufficientMemory; - goto error; + if( inputParameters->channelCount != outputParameters->channelCount ) + return paInvalidChannelCount; } } + + /* 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; - /* DBUG(("PaHost_OpenStream: pahsc_MinFramesPerHostBuffer = %d\n", pahsc->pahsc_MinFramesPerHostBuffer )); */ - minNumBuffers = Pa_GetMinNumBuffers( past->past_FramesPerUserBuffer, past->past_SampleRate ); - past->past_NumUserBuffers = ( minNumBuffers > past->past_NumUserBuffers ) ? minNumBuffers : past->past_NumUserBuffers; + *s = (PaStream*)stream; - pahsc->pahsc_InverseMicrosPerBuffer = past->past_SampleRate / (1000000.0 * past->past_FramesPerUserBuffer); - DBUG(("pahsc_InverseMicrosPerBuffer = %g\n", pahsc->pahsc_InverseMicrosPerBuffer )); + 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; */ + } - /* ------------------------- OPEN DEVICE -----------------------*/ + FD_ZERO( &readFds ); + FD_ZERO( &writeFds ); - /* just output */ - if (past->past_OutputDeviceID == past->past_InputDeviceID) + while( pollPlayback || pollCapture ) { + pthread_testcancel(); + + /* select may modify the timeout parameter */ + selectTimeval.tv_usec = timeout; + nfds = 0; - if ((past->past_NumOutputChannels > 0) && (past->past_NumInputChannels > 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 ) { - pad = Pa_GetInternalDevice( past->past_OutputDeviceID ); - DBUG(("PaHost_OpenStream: attempt to open %s for O_RDWR\n", pad->pad_DeviceName )); - /* dmazzoni: test it first in nonblocking mode to - make sure the device is not busy */ - pahsc->pahsc_InputHandle = open(pad->pad_DeviceName,O_RDWR|O_NONBLOCK); - if(pahsc->pahsc_InputHandle==-1) - { - ERR_RPT(("PaHost_OpenStream: could not open %s for O_RDWR\n", pad->pad_DeviceName )); - result = paHostError; - goto error; - } - close(pahsc->pahsc_InputHandle); + ENSURE_( -1, paUnanticipatedHostError ); + } + */ + pthread_testcancel(); - pahsc->pahsc_OutputHandle = pahsc->pahsc_InputHandle = - open(pad->pad_DeviceName,O_RDWR); - if(pahsc->pahsc_InputHandle==-1) + if( pollCapture ) + { + if( FD_ISSET( captureFd, &readFds ) ) { - ERR_RPT(("PaHost_OpenStream: could not open %s for O_RDWR\n", pad->pad_DeviceName )); - result = paHostError; - goto error; + FD_CLR( captureFd, &readFds ); + pollCapture = 0; } - Pa_SetLatency( pahsc->pahsc_OutputHandle, - past->past_NumUserBuffers, past->past_FramesPerUserBuffer, - past->past_NumOutputChannels ); - result = Pa_SetupDeviceFormat( pahsc->pahsc_OutputHandle, - past->past_NumOutputChannels, (int)past->past_SampleRate ); - } - } - else - { - if (past->past_NumOutputChannels > 0) - { - pad = Pa_GetInternalDevice( past->past_OutputDeviceID ); - DBUG(("PaHost_OpenStream: attempt to open %s for O_WRONLY\n", pad->pad_DeviceName )); - /* dmazzoni: test it first in nonblocking mode to - make sure the device is not busy */ - pahsc->pahsc_OutputHandle = open(pad->pad_DeviceName,O_WRONLY|O_NONBLOCK); - if(pahsc->pahsc_OutputHandle==-1) + /* + if( stream->capture->pfd->revents & POLLIN ) { - ERR_RPT(("PaHost_OpenStream: could not open %s for O_WRONLY\n", pad->pad_DeviceName )); - result = paHostError; - goto error; + --nfds; + ++ofs; + pollCapture = 0; } - close(pahsc->pahsc_OutputHandle); - - pahsc->pahsc_OutputHandle = open(pad->pad_DeviceName,O_WRONLY); - if(pahsc->pahsc_OutputHandle==-1) + */ + else if( stream->playback ) /* Timed out, go on with playback? */ { - ERR_RPT(("PaHost_OpenStream: could not open %s for O_WRONLY\n", pad->pad_DeviceName )); - result = paHostError; - goto error; + /*PA_DEBUG(( "%s: Trying to poll again for capture frames, pollTimeout: %d\n", + __FUNCTION__, stream->pollTimeout ));*/ } - Pa_SetLatency( pahsc->pahsc_OutputHandle, - past->past_NumUserBuffers, past->past_FramesPerUserBuffer, - past->past_NumOutputChannels ); - result = Pa_SetupDeviceFormat( pahsc->pahsc_OutputHandle, - past->past_NumOutputChannels, (int)past->past_SampleRate ); } - - if (past->past_NumInputChannels > 0) + if( pollPlayback ) { - pad = Pa_GetInternalDevice( past->past_InputDeviceID ); - DBUG(("PaHost_OpenStream: attempt to open %s for O_RDONLY\n", pad->pad_DeviceName )); - /* dmazzoni: test it first in nonblocking mode to - make sure the device is not busy */ - pahsc->pahsc_InputHandle = open(pad->pad_DeviceName,O_RDONLY|O_NONBLOCK); - if(pahsc->pahsc_InputHandle==-1) + if( FD_ISSET( playbackFd, &writeFds ) ) { - ERR_RPT(("PaHost_OpenStream: could not open %s for O_RDONLY\n", pad->pad_DeviceName )); - result = paHostError; - goto error; + FD_CLR( playbackFd, &writeFds ); + pollPlayback = 0; } - close(pahsc->pahsc_InputHandle); - - pahsc->pahsc_InputHandle = open(pad->pad_DeviceName,O_RDONLY); - if(pahsc->pahsc_InputHandle==-1) + /* + if( stream->playback->pfd->revents & POLLOUT ) { - ERR_RPT(("PaHost_OpenStream: could not open %s for O_RDONLY\n", pad->pad_DeviceName )); - result = paHostError; - goto error; + --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 ));*/ } - Pa_SetLatency( pahsc->pahsc_InputHandle, /* DH20010115 - was OutputHandle! */ - past->past_NumUserBuffers, past->past_FramesPerUserBuffer, - past->past_NumInputChannels ); - result = Pa_SetupDeviceFormat( pahsc->pahsc_InputHandle, - past->past_NumInputChannels, (int)past->past_SampleRate ); } } + 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__ )); - DBUG(("PaHost_OpenStream: SUCCESS - result = %d\n", result )); - return result; + 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: - ERR_RPT(("PaHost_OpenStream: ERROR - result = %d\n", result )); - PaHost_CloseStream( past ); return result; } -/*************************************************************************/ -PaError PaHost_StartOutput( internalPortAudioStream *past ) +/** Prepare stream for capture/playback. + * + * In order to synchronize capture and playback properly we use the SETTRIGGER command. + */ +static PaError PaOssStream_Prepare( PaOssStream *stream ) { - return paNoError; + 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; } -/*************************************************************************/ -PaError PaHost_StartInput( internalPortAudioStream *past ) +/** Stop audio processing + * + */ +static PaError PaOssStream_Stop( PaOssStream *stream, int abort ) { - return paNoError; + 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; } -/*************************************************************************/ -PaError PaHost_StartEngine( internalPortAudioStream *past ) +/** Clean up after thread exit. + * + * Aspect StreamState: If the user has registered a streamFinishedCallback it will be called here + */ +static void OnExit( void *data ) { - PaHostSoundControl *pahsc; - PaError result = paNoError; - int hres; + PaOssStream *stream = (PaOssStream *) data; + assert( data ); - pahsc = (PaHostSoundControl *) past->past_DeviceData; + PaUtil_ResetCpuLoadMeasurer( &stream->cpuLoadMeasurer ); - past->past_StopSoon = 0; - past->past_StopNow = 0; - past->past_IsActive = 1; + PaOssStream_Stop( stream, stream->callbackAbort ); + + PA_DEBUG(( "OnExit: Stoppage\n" )); - /* Use pthread_create() instead of __clone() because: - * - pthread_create also works for other UNIX systems like Solaris, - * - the Java HotSpot VM crashes in pthread_setcanceltype() when using __clone() - */ - hres = pthread_create(&(pahsc->pahsc_AudioThread), - NULL /*pthread_attr_t * attr*/, - (void*)Pa_AudioThreadProc, past); - if( hres != 0 ) + /* 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 ) { - result = paHostError; - sPaHostError = hres; - pahsc->pahsc_AudioThread = INVALID_THREAD; - goto error; + 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 ); } -error: return result; } -/*************************************************************************/ -PaError PaHost_StopEngine( internalPortAudioStream *past, int abort ) +/** 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 ) { - int hres; - PaError result = paNoError; - PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; + PaError result = paNoError; + PaOssStream *stream = (PaOssStream*)userData; + unsigned long framesAvail, framesProcessed; + 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 */ - if( pahsc == NULL ) return paNoError; + /* 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 ) ); - /* Tell background thread to stop generating more data and to let current data play out. */ - past->past_StopSoon = 1; - /* If aborting, tell background thread to stop NOW! */ - if( abort ) past->past_StopNow = 1; + /* 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 ); + } - /* Join thread to recover memory resources. */ - if( pahsc->pahsc_AudioThread != INVALID_THREAD ) + while( 1 ) { - /* This check is needed for GNUSTEP - SB20010904 */ - if ( !pthread_equal( pahsc->pahsc_AudioThread, pthread_self() ) ) + 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 ) { - hres = pthread_join( pahsc->pahsc_AudioThread, NULL ); + PA_ENSURE( PaOssStream_WaitForFrames( stream, &framesAvail ) ); /* Wait on available frames */ + assert( framesAvail % stream->framesPerHostBuffer == 0 ); } else { - DBUG(("Play thread was stopped from itself - can't do pthread_join()\n")); - hres = 0; + framesAvail = stream->framesPerHostBuffer; } - if( hres != 0 ) + while( framesAvail > 0 ) { - result = paHostError; - sPaHostError = hres; + unsigned long frames = framesAvail; + + pthread_testcancel(); + + PaUtil_BeginCpuLoadMeasurement( &stream->cpuLoadMeasurer ); + + /* Read data */ + if ( stream->capture ) + { + PA_ENSURE( PaOssStreamComponent_Read( stream->capture, &frames ) ); + assert( frames == framesAvail ); + } + +#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 ) ); + assert( frames == framesAvail ); + + /* TODO: handle bytesWritten != bytesRequested (slippage?) */ + } + + 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; } - pahsc->pahsc_AudioThread = INVALID_THREAD; } - past->past_IsActive = 0; + pthread_cleanup_pop( 1 ); - return result; +error: + pthread_exit( NULL ); } -/*************************************************************************/ -PaError PaHost_StopInput( internalPortAudioStream *past, int abort ) +/** Close the stream. + * + */ +static PaError CloseStream( PaStream* s ) { - return paNoError; -} + PaError result = paNoError; + PaOssStream *stream = (PaOssStream*)s; -/*************************************************************************/ -PaError PaHost_StopOutput( internalPortAudioStream *past, int abort ) -{ - return paNoError; + assert( stream ); + + PaUtil_TerminateBufferProcessor( &stream->bufferProcessor ); + PaOssStream_Terminate( stream ); + + return result; } -/*******************************************************************/ -PaError PaHost_CloseStream( internalPortAudioStream *past ) +/** 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 ) { - PaHostSoundControl *pahsc; - if( past == NULL ) return paBadStreamPtr; - pahsc = (PaHostSoundControl *) past->past_DeviceData; - if( pahsc == NULL ) return paNoError; + PaError result = paNoError; + PaOssStream *stream = (PaOssStream*)s; - if( pahsc->pahsc_OutputHandle != BAD_DEVICE_ID ) - { - int err; - DBUG(("PaHost_CloseStream: attempt to close output device handle = %d\n", - pahsc->pahsc_OutputHandle )); - err = close(pahsc->pahsc_OutputHandle); - if( err < 0 ) - { - ERR_RPT(("PaHost_CloseStream: warning, closing output device failed.\n")); - } - } + stream->isActive = 1; + stream->isStopped = 0; + stream->lastPosPtr = 0; + stream->lastStreamBytes = 0; + stream->framesProcessed = 0; - if( (pahsc->pahsc_InputHandle != BAD_DEVICE_ID) && - (pahsc->pahsc_InputHandle != pahsc->pahsc_OutputHandle) ) + /* only use the thread for callback streams */ + if( stream->bufferProcessor.streamCallback ) { - int err; - DBUG(("PaHost_CloseStream: attempt to close input device handle = %d\n", - pahsc->pahsc_InputHandle )); - err = close(pahsc->pahsc_InputHandle); - if( err < 0 ) - { - ERR_RPT(("PaHost_CloseStream: warning, closing input device failed.\n")); - } + PA_ENSURE( PaUtil_StartThreading( &stream->threading, &PaOSS_AudioThreadProc, stream ) ); + sem_wait( &stream->semaphore ); } - pahsc->pahsc_OutputHandle = BAD_DEVICE_ID; - pahsc->pahsc_InputHandle = BAD_DEVICE_ID; + else + PA_ENSURE( PaOssStream_Prepare( stream ) ); - if( pahsc->pahsc_NativeInputBuffer ) - { - free( pahsc->pahsc_NativeInputBuffer ); - pahsc->pahsc_NativeInputBuffer = NULL; - } - if( pahsc->pahsc_NativeOutputBuffer ) +error: + return result; +} + +static PaError RealStop( PaOssStream *stream, int abort ) +{ + PaError result = paNoError; + + if( stream->callbackMode ) { - free( pahsc->pahsc_NativeOutputBuffer ); - pahsc->pahsc_NativeOutputBuffer = NULL; + 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 ) ); - free( pahsc ); - past->past_DeviceData = NULL; - return paNoError; + stream->isStopped = 1; + +error: + return result; } -/*************************************************************************/ -PaError PaHost_Term( void ) +/** 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 ) { - /* Free all of the linked devices. */ - internalPortAudioDevice *pad, *nextPad; - pad = sDeviceList; - while( pad != NULL ) - { - nextPad = pad->pad_Next; - DBUG(("PaHost_Term: freeing %s\n", pad->pad_DeviceName )); - PaHost_FreeFastMemory( pad, sizeof(internalPortAudioDevice) ); - pad = nextPad; - } - sDeviceList = NULL; - return 0; + return RealStop( (PaOssStream *)s, 0 ); } -/************************************************************************* - * Sleep for the requested number of milliseconds. +/** 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. */ -void Pa_Sleep( long msec ) +static PaError AbortStream( PaStream *s ) { -#if 0 - struct timeval timeout; - timeout.tv_sec = msec / 1000; - timeout.tv_usec = (msec % 1000) * 1000; - select( 0, NULL, NULL, NULL, &timeout ); -#else - long usecs = msec * 1000; - usleep( usecs ); -#endif + return RealStop( (PaOssStream *)s, 1 ); } -/************************************************************************* - * Allocate memory that can be accessed in real-time. - * This may need to be held in physical memory so that it is not - * paged to virtual memory. - * This call MUST be balanced with a call to PaHost_FreeFastMemory(). +/** Is the stream in the Stopped state. + * */ -void *PaHost_AllocateFastMemory( long numBytes ) +static PaError IsStreamStopped( PaStream *s ) { - void *addr = malloc( numBytes ); /* FIXME - do we need physical, wired, non-virtual memory? */ - if( addr != NULL ) memset( addr, 0, numBytes ); - return addr; + PaOssStream *stream = (PaOssStream*)s; + + return (stream->isStopped); } -/************************************************************************* - * Free memory that could be accessed in real-time. - * This call MUST be balanced with a call to PaHost_AllocateFastMemory(). +/** Is the stream in the Active state. + * */ -void PaHost_FreeFastMemory( void *addr, long numBytes ) +static PaError IsStreamActive( PaStream *s ) +{ + PaOssStream *stream = (PaOssStream*)s; + + return (stream->isActive); +} + +static PaTime GetStreamTime( PaStream *s ) { - if( addr != NULL ) free( addr ); + 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; } -/***********************************************************************/ -PaError PaHost_StreamActive( internalPortAudioStream *past ) +static double GetStreamCpuLoad( PaStream* s ) { - PaHostSoundControl *pahsc; - if( past == NULL ) return paBadStreamPtr; - pahsc = (PaHostSoundControl *) past->past_DeviceData; - if( pahsc == NULL ) return paInternalError; - return (PaError) (past->past_IsActive != 0); + PaOssStream *stream = (PaOssStream*)s; + + return PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer ); } -/***********************************************************************/ -PaTimestamp Pa_StreamTime( PortAudioStream *stream ) + +/* + 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 ) { - internalPortAudioStream *past = (internalPortAudioStream *) stream; - PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; - count_info info; - int delta; + 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 ); - if( past == NULL ) return paBadStreamPtr; + bytesRequested = framesRequested * PaOssStreamComponent_FrameSize( stream->capture ); + bytesRead = read( stream->capture->fd, stream->capture->buffer, bytesRequested ); + if ( bytesRequested != bytesRead ) + return paUnanticipatedHostError; - if( pahsc->pahsc_NativeOutputBuffer ) { - ioctl(pahsc->pahsc_OutputHandle, SNDCTL_DSP_GETOPTR, &info); - delta = (info.bytes - pahsc->pahsc_LastPosPtr) & 0x000FFFFF; - return (pahsc->pahsc_LastStreamBytes + delta) / (past->past_NumOutputChannels * sizeof(short)); + 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; } - else { - ioctl(pahsc->pahsc_InputHandle, SNDCTL_DSP_GETIPTR, &info); - delta = (info.bytes - pahsc->pahsc_LastPosPtr) & 0x000FFFFF; - return (pahsc->pahsc_LastStreamBytes + delta) / (past->past_NumInputChannels * sizeof(short)); + 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; } -/***********************************************************************/ -long Pa_GetHostError( void ) + +/* TODO: Compute number of allocated bytes somewhere else, can we use ODELAY with capture */ +static signed long GetStreamWriteAvailable( PaStream* s ) { - return (long) sPaHostError; + 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 ); } + diff --git a/pa_win/dev-cpp/Makefile-dll b/pa_win/dev-cpp/Makefile-dll new file mode 100644 index 0000000..856af63 --- /dev/null +++ b/pa_win/dev-cpp/Makefile-dll @@ -0,0 +1,78 @@ +# Project: portaudio-dll +# Makefile created by Dev-C++ 4.9.8.2 + +CPP = g++.exe +CC = gcc.exe +WINDRES = windres.exe +RES = +OBJ = ./pa_skeleton.o ./pa_stream.o ./pa_trace.o ./pa_allocation.o ./pa_converters.o ./pa_cpuload.o ./pa_dither.o ./pa_front.o ./pa_process.o ./pa_asio.o ./pa_win_util.o ./pa_win_hostapis.o ./pa_win_ds.o ./dsound_wrapper.o ./pa_win_wmme.o ./iasiothiscallresolver.o $(RES) +LINKOBJ = ./pa_skeleton.o ./pa_stream.o ./pa_trace.o ./pa_allocation.o ./pa_converters.o ./pa_cpuload.o ./pa_dither.o ./pa_front.o ./pa_process.o ./pa_asio.o ./pa_win_util.o ./pa_win_hostapis.o ./pa_win_ds.o ./dsound_wrapper.o ./pa_win_wmme.o ./iasiothiscallresolver.o $(RES) +LIBS = -L"C:/Dev-CPP/lib" -fmessage-length=0 --no-export-all-symbols --add-stdcall-alias ../../../asiosdk2/asiosdk2.a -lkernel32 -luser32 -lgdi32 -lwinspool -lcomdlg32 -ladvapi32 -lshell32 -lole32 -loleaut32 -luuid -lodbc32 -lodbccp32 -lwinmm -O3 -s +INCS = -I"C:/Dev-CPP/include" -I"../../../asiosdk2" -I"../../../asiosdk2/common" -I"../../../asiosdk2/host" -I"../../../asiosdk2/host/pc" -I"../../pa_common" +CXXINCS = -I"C:/Dev-CPP/include/c++" -I"C:/Dev-CPP/include/c++/mingw32" -I"C:/Dev-CPP/include/c++/backward" -I"C:/Dev-CPP/include" -I"../../../asiosdk2" -I"../../../asiosdk2/common" -I"../../../asiosdk2/host" -I"../../../asiosdk2/host/pc" -I"../../pa_common" +BIN = portaudio-dll.dll +CXXFLAGS = $(CXXINCS)-O3 -fmessage-length=0 -Wall +CFLAGS = $(INCS)-DBUILDING_DLL=1 -O3 -fmessage-length=0 -Wall + +.PHONY: all all-before all-after clean clean-custom + +all: all-before portaudio-dll.dll all-after + + +clean: clean-custom + rm -f $(OBJ) $(BIN) + +DLLWRAP=dllwrap.exe +DEFFILE=libportaudio-dll.def +STATICLIB=libportaudio-dll.a + +$(BIN): $(LINKOBJ) + $(DLLWRAP) --output-def $(DEFFILE) --driver-name c++ --implib $(STATICLIB) $(LINKOBJ) $(LIBS) -o $(BIN) + +./pa_skeleton.o: ../../pa_common/pa_skeleton.c + $(CPP) -c ../../pa_common/pa_skeleton.c -o ./pa_skeleton.o $(CXXFLAGS) + +./pa_stream.o: ../../pa_common/pa_stream.c + $(CPP) -c ../../pa_common/pa_stream.c -o ./pa_stream.o $(CXXFLAGS) + +./pa_trace.o: ../../pa_common/pa_trace.c + $(CPP) -c ../../pa_common/pa_trace.c -o ./pa_trace.o $(CXXFLAGS) + +./pa_allocation.o: ../../pa_common/pa_allocation.c + $(CPP) -c ../../pa_common/pa_allocation.c -o ./pa_allocation.o $(CXXFLAGS) + +./pa_converters.o: ../../pa_common/pa_converters.c + $(CPP) -c ../../pa_common/pa_converters.c -o ./pa_converters.o $(CXXFLAGS) + +./pa_cpuload.o: ../../pa_common/pa_cpuload.c + $(CPP) -c ../../pa_common/pa_cpuload.c -o ./pa_cpuload.o $(CXXFLAGS) + +./pa_dither.o: ../../pa_common/pa_dither.c + $(CPP) -c ../../pa_common/pa_dither.c -o ./pa_dither.o $(CXXFLAGS) + +./pa_front.o: ../../pa_common/pa_front.c + $(CPP) -c ../../pa_common/pa_front.c -o ./pa_front.o $(CXXFLAGS) + +./pa_process.o: ../../pa_common/pa_process.c + $(CPP) -c ../../pa_common/pa_process.c -o ./pa_process.o $(CXXFLAGS) + +./pa_asio.o: ../../pa_asio/pa_asio.cpp + $(CPP) -c ../../pa_asio/pa_asio.cpp -o ./pa_asio.o $(CXXFLAGS) + +./pa_win_util.o: ../pa_win_util.c + $(CPP) -c ../pa_win_util.c -o ./pa_win_util.o $(CXXFLAGS) + +./pa_win_hostapis.o: ../pa_win_hostapis.c + $(CPP) -c ../pa_win_hostapis.c -o ./pa_win_hostapis.o $(CXXFLAGS) + +./pa_win_ds.o: ../../pa_win_ds/pa_win_ds.c + $(CPP) -c ../../pa_win_ds/pa_win_ds.c -o ./pa_win_ds.o $(CXXFLAGS) + +./dsound_wrapper.o: ../../pa_win_ds/dsound_wrapper.c + $(CPP) -c ../../pa_win_ds/dsound_wrapper.c -o ./dsound_wrapper.o $(CXXFLAGS) + +./pa_win_wmme.o: ../../pa_win_wmme/pa_win_wmme.c + $(CPP) -c ../../pa_win_wmme/pa_win_wmme.c -o ./pa_win_wmme.o $(CXXFLAGS) + +./iasiothiscallresolver.o: ../../pa_asio/iasiothiscallresolver.cpp + $(CPP) -c ../../pa_asio/iasiothiscallresolver.cpp -o ./iasiothiscallresolver.o $(CXXFLAGS) diff --git a/pa_win/dev-cpp/Makefile-static b/pa_win/dev-cpp/Makefile-static new file mode 100644 index 0000000..2a1647d --- /dev/null +++ b/pa_win/dev-cpp/Makefile-static @@ -0,0 +1,75 @@ +# Project: portaudio-static +# Makefile created by Dev-C++ 4.9.8.2 + +CPP = g++.exe +CC = gcc.exe +WINDRES = windres.exe +RES = +OBJ = ./pa_skeleton.o ./pa_stream.o ./pa_trace.o ./pa_allocation.o ./pa_converters.o ./pa_cpuload.o ./pa_dither.o ./pa_front.o ./pa_process.o ./pa_asio.o ./pa_win_util.o ./pa_win_hostapis.o ./pa_win_ds.o ./dsound_wrapper.o ./pa_win_wmme.o ./iasiothiscallresolver.o $(RES) +LINKOBJ = ./pa_skeleton.o ./pa_stream.o ./pa_trace.o ./pa_allocation.o ./pa_converters.o ./pa_cpuload.o ./pa_dither.o ./pa_front.o ./pa_process.o ./pa_asio.o ./pa_win_util.o ./pa_win_hostapis.o ./pa_win_ds.o ./dsound_wrapper.o ./pa_win_wmme.o ./iasiothiscallresolver.o $(RES) +LIBS = -L"C:/Dev-CPP/lib" -fmessage-length=0 -O3 -s +INCS = -I"C:/Dev-CPP/include" -I"../../../asiosdk2" -I"../../../asiosdk2/common" -I"../../../asiosdk2/host" -I"../../../asiosdk2/host/pc" -I"../../pa_common" +CXXINCS = -I"C:/Dev-CPP/include/c++" -I"C:/Dev-CPP/include/c++/mingw32" -I"C:/Dev-CPP/include/c++/backward" -I"C:/Dev-CPP/include" -I"../../../asiosdk2" -I"../../../asiosdk2/common" -I"../../../asiosdk2/host" -I"../../../asiosdk2/host/pc" -I"../../pa_common" +BIN = portaudio-static.a +CXXFLAGS = $(CXXINCS)-O3 -fmessage-length=0 -Wall +CFLAGS = $(INCS)-O3 -fmessage-length=0 -Wall + +.PHONY: all all-before all-after clean clean-custom + +all: all-before portaudio-static.a all-after + + +clean: clean-custom + rm -f $(OBJ) $(BIN) + +$(BIN): $(LINKOBJ) + ar r $(BIN) $(LINKOBJ) + ranlib $(BIN) + +./pa_skeleton.o: ../../pa_common/pa_skeleton.c + $(CPP) -c ../../pa_common/pa_skeleton.c -o ./pa_skeleton.o $(CXXFLAGS) + +./pa_stream.o: ../../pa_common/pa_stream.c + $(CPP) -c ../../pa_common/pa_stream.c -o ./pa_stream.o $(CXXFLAGS) + +./pa_trace.o: ../../pa_common/pa_trace.c + $(CPP) -c ../../pa_common/pa_trace.c -o ./pa_trace.o $(CXXFLAGS) + +./pa_allocation.o: ../../pa_common/pa_allocation.c + $(CPP) -c ../../pa_common/pa_allocation.c -o ./pa_allocation.o $(CXXFLAGS) + +./pa_converters.o: ../../pa_common/pa_converters.c + $(CPP) -c ../../pa_common/pa_converters.c -o ./pa_converters.o $(CXXFLAGS) + +./pa_cpuload.o: ../../pa_common/pa_cpuload.c + $(CPP) -c ../../pa_common/pa_cpuload.c -o ./pa_cpuload.o $(CXXFLAGS) + +./pa_dither.o: ../../pa_common/pa_dither.c + $(CPP) -c ../../pa_common/pa_dither.c -o ./pa_dither.o $(CXXFLAGS) + +./pa_front.o: ../../pa_common/pa_front.c + $(CPP) -c ../../pa_common/pa_front.c -o ./pa_front.o $(CXXFLAGS) + +./pa_process.o: ../../pa_common/pa_process.c + $(CPP) -c ../../pa_common/pa_process.c -o ./pa_process.o $(CXXFLAGS) + +./pa_asio.o: ../../pa_asio/pa_asio.cpp + $(CPP) -c ../../pa_asio/pa_asio.cpp -o ./pa_asio.o $(CXXFLAGS) + +./pa_win_util.o: ../pa_win_util.c + $(CPP) -c ../pa_win_util.c -o ./pa_win_util.o $(CXXFLAGS) + +./pa_win_hostapis.o: ../pa_win_hostapis.c + $(CPP) -c ../pa_win_hostapis.c -o ./pa_win_hostapis.o $(CXXFLAGS) + +./pa_win_ds.o: ../../pa_win_ds/pa_win_ds.c + $(CPP) -c ../../pa_win_ds/pa_win_ds.c -o ./pa_win_ds.o $(CXXFLAGS) + +./dsound_wrapper.o: ../../pa_win_ds/dsound_wrapper.c + $(CPP) -c ../../pa_win_ds/dsound_wrapper.c -o ./dsound_wrapper.o $(CXXFLAGS) + +./pa_win_wmme.o: ../../pa_win_wmme/pa_win_wmme.c + $(CPP) -c ../../pa_win_wmme/pa_win_wmme.c -o ./pa_win_wmme.o $(CXXFLAGS) + +./iasiothiscallresolver.o: ../../pa_asio/iasiothiscallresolver.cpp + $(CPP) -c ../../pa_asio/iasiothiscallresolver.cpp -o ./iasiothiscallresolver.o $(CXXFLAGS) diff --git a/pa_win/dev-cpp/portaudio-dll.dev b/pa_win/dev-cpp/portaudio-dll.dev new file mode 100644 index 0000000..086e109 --- /dev/null +++ b/pa_win/dev-cpp/portaudio-dll.dev @@ -0,0 +1,209 @@ +[Project] +FileName=portaudio-dll.dev +Name=portaudio-dll +UnitCount=16 +Type=3 +Ver=1 +ObjFiles= +Includes=..\..\..\asiosdk2;..\..\..\asiosdk2\common;..\..\..\asiosdk2\host;..\..\..\asiosdk2\host\pc;..\..\pa_common +Libs= +PrivateResource= +ResourceIncludes= +MakeIncludes= +Compiler=-DBUILDING_DLL=1_@@_-O3_@@_ +CppCompiler=-O3_@@_ +Linker=--no-export-all-symbols --add-stdcall-alias_@@_../../../asiosdk2/asiosdk2.a_@@_-lkernel32 -luser32 -lgdi32 -lwinspool -lcomdlg32 -ladvapi32 -lshell32 -lole32 -loleaut32 -luuid -lodbc32 -lodbccp32 -lwinmm_@@_-O3 -s_@@_ +IsCpp=1 +Icon= +ExeOutput=. +ObjectOutput=. +OverrideOutput=0 +OverrideOutputName=portaudio.a +HostApplication= +Folders= +CommandLine= +IncludeVersionInfo=0 +SupportXPThemes=0 +CompilerSet=0 +CompilerSettings=0000000000000000000 +UseCustomMakefile=0 +CustomMakefile= + +[Unit1] +FileName=..\..\pa_common\pa_skeleton.c +CompileCpp=1 +Folder=portaudio +Compile=1 +Link=1 +Priority=1000 +OverrideBuildCmd=0 +BuildCmd=$(CC) -c pa_skeleton.c -o ./pa_skeleton.o $(CFLAGS) + +[Unit2] +FileName=..\..\pa_common\pa_stream.c +CompileCpp=1 +Folder=portaudio +Compile=1 +Link=1 +Priority=1000 +OverrideBuildCmd=0 +BuildCmd=$(CC) -c pa_stream.c -o ./pa_stream.o $(CFLAGS) + +[Unit3] +FileName=..\..\pa_common\pa_trace.c +CompileCpp=1 +Folder=portaudio +Compile=1 +Link=1 +Priority=1000 +OverrideBuildCmd=0 +BuildCmd=$(CC) -c pa_trace.c -o ./pa_trace.o $(CFLAGS) + +[Unit4] +FileName=..\..\pa_common\pa_allocation.c +CompileCpp=1 +Folder=portaudio +Compile=1 +Link=1 +Priority=1000 +OverrideBuildCmd=0 +BuildCmd=$(CC) -c pa_allocation.c -o ./pa_allocation.o $(CFLAGS) + +[Unit5] +FileName=..\..\pa_common\pa_converters.c +CompileCpp=1 +Folder=portaudio +Compile=1 +Link=1 +Priority=1000 +OverrideBuildCmd=0 +BuildCmd=$(CC) -c pa_converters.c -o ./pa_converters.o $(CFLAGS) + +[Unit6] +FileName=..\..\pa_common\pa_cpuload.c +CompileCpp=1 +Folder=portaudio +Compile=1 +Link=1 +Priority=1000 +OverrideBuildCmd=0 +BuildCmd=$(CC) -c pa_cpuload.c -o ./pa_cpuload.o $(CFLAGS) + +[Unit7] +FileName=..\..\pa_common\pa_dither.c +CompileCpp=1 +Folder=portaudio +Compile=1 +Link=1 +Priority=1000 +OverrideBuildCmd=0 +BuildCmd=$(CC) -c pa_dither.c -o ./pa_dither.o $(CFLAGS) + +[Unit8] +FileName=..\..\pa_common\pa_front.c +CompileCpp=1 +Folder=portaudio +Compile=1 +Link=1 +Priority=1000 +OverrideBuildCmd=0 +BuildCmd=$(CC) -c pa_front.c -o ./pa_front.o $(CFLAGS) + +[Unit9] +FileName=..\..\pa_common\pa_process.c +CompileCpp=1 +Folder=portaudio +Compile=1 +Link=1 +Priority=1000 +OverrideBuildCmd=0 +BuildCmd=$(CC) -c pa_process.c -o ./pa_process.o $(CFLAGS) + +[VersionInfo] +Major=0 +Minor=1 +Release=1 +Build=1 +LanguageID=1033 +CharsetID=1252 +CompanyName= +FileVersion= +FileDescription=Developed using the Dev-C++ IDE +InternalName= +LegalCopyright= +LegalTrademarks= +OriginalFilename= +ProductName= +ProductVersion= +AutoIncBuildNr=0 + +[Unit10] +FileName=..\..\pa_asio\pa_asio.cpp +CompileCpp=1 +Folder=portaudio +Compile=1 +Link=1 +Priority=1000 +OverrideBuildCmd=0 +BuildCmd=$(CPP) -c pa_asio.cpp -o ./pa_asio.o $(CXXFLAGS) + +[Unit11] +FileName=..\pa_win_util.c +CompileCpp=1 +Folder=portaudio +Compile=1 +Link=1 +Priority=1000 +OverrideBuildCmd=0 +BuildCmd=$(CC) -c pa_win_util.c -o ./pa_win_util.o $(CFLAGS) + +[Unit12] +FileName=..\pa_win_hostapis.c +CompileCpp=1 +Folder=portaudio +Compile=1 +Link=1 +Priority=1000 +OverrideBuildCmd=0 +BuildCmd=$(CC) -c pa_win_hostapis.c -o ./pa_win_hostapis.o $(CFLAGS) + +[Unit13] +FileName=..\..\pa_win_ds\pa_win_ds.c +CompileCpp=1 +Folder=portaudio +Compile=1 +Link=1 +Priority=1000 +OverrideBuildCmd=0 +BuildCmd=$(CC) -c pa_win_ds.c -o ./pa_win_ds.o $(CFLAGS) + +[Unit14] +FileName=..\..\pa_win_ds\dsound_wrapper.c +CompileCpp=1 +Folder=portaudio +Compile=1 +Link=1 +Priority=1000 +OverrideBuildCmd=0 +BuildCmd=$(CC) -c dsound_wrapper.c -o ./dsound_wrapper.o $(CFLAGS) + +[Unit15] +FileName=..\..\pa_win_wmme\pa_win_wmme.c +CompileCpp=1 +Folder=portaudio +Compile=1 +Link=1 +Priority=1000 +OverrideBuildCmd=0 +BuildCmd=$(CC) -c pa_win_wmme.c -o ./pa_win_wmme.o $(CFLAGS) + +[Unit16] +FileName=..\..\pa_asio\iasiothiscallresolver.cpp +CompileCpp=1 +Folder=portaudio +Compile=1 +Link=1 +Priority=1000 +OverrideBuildCmd=0 +BuildCmd= + diff --git a/pa_win/dev-cpp/portaudio-static.dev b/pa_win/dev-cpp/portaudio-static.dev new file mode 100644 index 0000000..2aae584 --- /dev/null +++ b/pa_win/dev-cpp/portaudio-static.dev @@ -0,0 +1,209 @@ +[Project] +FileName=portaudio-static.dev +Name=portaudio-static +UnitCount=16 +Type=2 +Ver=1 +ObjFiles= +Includes=..\..\..\asiosdk2;..\..\..\asiosdk2\common;..\..\..\asiosdk2\host;..\..\..\asiosdk2\host\pc;..\..\pa_common +Libs= +PrivateResource= +ResourceIncludes= +MakeIncludes= +Compiler=-O3_@@_ +CppCompiler=-O3_@@_ +Linker=-O3 -s_@@_ +IsCpp=1 +Icon= +ExeOutput=. +ObjectOutput=. +OverrideOutput=0 +OverrideOutputName=portaudio.a +HostApplication= +Folders= +CommandLine= +IncludeVersionInfo=0 +SupportXPThemes=0 +CompilerSet=0 +CompilerSettings=0000000000000000000 +UseCustomMakefile=0 +CustomMakefile= + +[Unit1] +FileName=..\..\pa_common\pa_skeleton.c +CompileCpp=1 +Folder=portaudio +Compile=1 +Link=1 +Priority=1000 +OverrideBuildCmd=0 +BuildCmd=$(CC) -c pa_skeleton.c -o ./pa_skeleton.o $(CFLAGS) + +[Unit2] +FileName=..\..\pa_common\pa_stream.c +CompileCpp=1 +Folder=portaudio +Compile=1 +Link=1 +Priority=1000 +OverrideBuildCmd=0 +BuildCmd=$(CC) -c pa_stream.c -o ./pa_stream.o $(CFLAGS) + +[Unit3] +FileName=..\..\pa_common\pa_trace.c +CompileCpp=1 +Folder=portaudio +Compile=1 +Link=1 +Priority=1000 +OverrideBuildCmd=0 +BuildCmd=$(CC) -c pa_trace.c -o ./pa_trace.o $(CFLAGS) + +[Unit4] +FileName=..\..\pa_common\pa_allocation.c +CompileCpp=1 +Folder=portaudio +Compile=1 +Link=1 +Priority=1000 +OverrideBuildCmd=0 +BuildCmd=$(CC) -c pa_allocation.c -o ./pa_allocation.o $(CFLAGS) + +[Unit5] +FileName=..\..\pa_common\pa_converters.c +CompileCpp=1 +Folder=portaudio +Compile=1 +Link=1 +Priority=1000 +OverrideBuildCmd=0 +BuildCmd=$(CC) -c pa_converters.c -o ./pa_converters.o $(CFLAGS) + +[Unit6] +FileName=..\..\pa_common\pa_cpuload.c +CompileCpp=1 +Folder=portaudio +Compile=1 +Link=1 +Priority=1000 +OverrideBuildCmd=0 +BuildCmd=$(CC) -c pa_cpuload.c -o ./pa_cpuload.o $(CFLAGS) + +[Unit7] +FileName=..\..\pa_common\pa_dither.c +CompileCpp=1 +Folder=portaudio +Compile=1 +Link=1 +Priority=1000 +OverrideBuildCmd=0 +BuildCmd=$(CC) -c pa_dither.c -o ./pa_dither.o $(CFLAGS) + +[Unit8] +FileName=..\..\pa_common\pa_front.c +CompileCpp=1 +Folder=portaudio +Compile=1 +Link=1 +Priority=1000 +OverrideBuildCmd=0 +BuildCmd=$(CC) -c pa_front.c -o ./pa_front.o $(CFLAGS) + +[Unit9] +FileName=..\..\pa_common\pa_process.c +CompileCpp=1 +Folder=portaudio +Compile=1 +Link=1 +Priority=1000 +OverrideBuildCmd=0 +BuildCmd=$(CC) -c pa_process.c -o ./pa_process.o $(CFLAGS) + +[VersionInfo] +Major=0 +Minor=1 +Release=1 +Build=1 +LanguageID=1033 +CharsetID=1252 +CompanyName= +FileVersion= +FileDescription=Developed using the Dev-C++ IDE +InternalName= +LegalCopyright= +LegalTrademarks= +OriginalFilename= +ProductName= +ProductVersion= +AutoIncBuildNr=0 + +[Unit10] +FileName=..\..\pa_asio\pa_asio.cpp +CompileCpp=1 +Folder=portaudio +Compile=1 +Link=1 +Priority=1000 +OverrideBuildCmd=0 +BuildCmd=$(CPP) -c pa_asio.cpp -o ./pa_asio.o $(CXXFLAGS) + +[Unit11] +FileName=..\..\pa_win\pa_win_util.c +CompileCpp=1 +Folder=portaudio +Compile=1 +Link=1 +Priority=1000 +OverrideBuildCmd=0 +BuildCmd=$(CC) -c pa_win_util.c -o ./pa_win_util.o $(CFLAGS) + +[Unit12] +FileName=..\..\pa_win\pa_win_hostapis.c +CompileCpp=1 +Folder=portaudio +Compile=1 +Link=1 +Priority=1000 +OverrideBuildCmd=0 +BuildCmd=$(CC) -c pa_win_hostapis.c -o ./pa_win_hostapis.o $(CFLAGS) + +[Unit13] +FileName=..\..\pa_win_ds\pa_win_ds.c +CompileCpp=1 +Folder=portaudio +Compile=1 +Link=1 +Priority=1000 +OverrideBuildCmd=0 +BuildCmd=$(CC) -c pa_win_ds.c -o ./pa_win_ds.o $(CFLAGS) + +[Unit14] +FileName=..\..\pa_win_ds\dsound_wrapper.c +CompileCpp=1 +Folder=portaudio +Compile=1 +Link=1 +Priority=1000 +OverrideBuildCmd=0 +BuildCmd=$(CC) -c dsound_wrapper.c -o ./dsound_wrapper.o $(CFLAGS) + +[Unit15] +FileName=..\..\pa_win_wmme\pa_win_wmme.c +CompileCpp=1 +Folder=portaudio +Compile=1 +Link=1 +Priority=1000 +OverrideBuildCmd=0 +BuildCmd=$(CC) -c pa_win_wmme.c -o ./pa_win_wmme.o $(CFLAGS) + +[Unit16] +FileName=..\..\pa_asio\iasiothiscallresolver.cpp +CompileCpp=1 +Folder=portaudio +Compile=1 +Link=1 +Priority=1000 +OverrideBuildCmd=0 +BuildCmd= + diff --git a/pa_win/dev-cpp/readme.txt b/pa_win/dev-cpp/readme.txt new file mode 100644 index 0000000..07108a7 --- /dev/null +++ b/pa_win/dev-cpp/readme.txt @@ -0,0 +1,23 @@ +From: "Peter L Jones" +Sent: Wednesday, September 17, 2003 5:18 AM +Subject: Dev-C++ project files + +I attach two project files intended for portaudio/pa_win/dev-cpp (i.e. in +parallel with the msvc directory), if you want them. One is for a static +library build and one for a DLL. I've used the static library (in building +a single monolithic DLL) but I can't guarantee the DLL version will build a +working library (I think it's mostly there, though!). + +I also attach the resulting makefiles, which may be of use to other MinGW +users. + +They're rooted in the directory given above and drop their object and +library files in the same place. They assume the asiosdk2 files are in the +same directory as portaudio/ in a sub-directory called asiosdk2/. Oh! The +DLL is built against a static asiosdk2.a library... maybe not the best way +to do it... I ought to figure out how to link against a "home made" dll in +Dev-C++, I guess ;-) + +Cheers, + +-- Peter diff --git a/pa_win/msvc/Makefile.msvc b/pa_win/msvc/Makefile.msvc new file mode 100644 index 0000000..2f1a104 --- /dev/null +++ b/pa_win/msvc/Makefile.msvc @@ -0,0 +1,159 @@ +# Portaudio v1.9-devel VC6 DLL makefile 1.0 +# +# David Viens, davidv@plogue.com +# (im far from a VC6 makefile expert, so please bear with me :) +# +# For more info, look at readme.txt +# +#if you keep the ASIODIR as ".", it will use the SDK files that direclty in "pa_win/msvc" dir +ASIODIR=. +ASIOINC=/I ".\host" /I ".\host\pc" /I ".\common" +# + +LIBZ=kernel32.lib user32.lib gdi32.lib wininet.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib winmm.lib dsound.lib dxguid.lib + +CPP=cl.exe +LINK32=link.exe + +#release +CFLAGS=/nologo /MD /W3 /GX /O2 /Ob2 /I "src" /I "Win32" /I "$(MSVCDir)\Include" /D "WIN32" /D "NDEBUG" /D "_USRDLL" /YX /FD +DLL_LINK_FLAGS= /nologo /dll /incremental:no /libpath:"$(MSVCDir)\Lib" $(LIBZ) /pdb:"portaudio.pdb" /implib:".\portaudio.lib" /machine:I386 /out:"portaudio.dll" + + +COMMONINC=/I "..\..\pa_common" /I "." + +#==================================================================== +# Targets + +ALL : portaudio.dll + +CLEAN : + -@erase "*.obj" + +#==================================================================== + + +LINK32_OBJS= \ + ".\pa_allocation.obj" \ + ".\pa_converters.obj" \ + ".\pa_x86_plain_converters.obj" \ +# ".\pa_cppHelp.obj" \ + ".\pa_cpuload.obj" \ + ".\pa_dither.obj" \ + ".\pa_front.obj" \ + ".\pa_process.obj" \ + ".\pa_skeleton.obj" \ + ".\pa_stream.obj" \ + ".\pa_trace.obj" \ +# + ".\pa_win_hostapis.obj" \ + ".\pa_win_util.obj" \ +# + ".\pa_win_wmme.obj" \ +# + ".\pa_win_ds.obj" \ + ".\dsound_wrapper.obj" \ +# + ".\pa_asio.obj" \ +# + ".\asio.obj" \ + ".\ASIOConvertSamples.obj" \ + ".\asiodrivers.obj" \ + ".\asiolist.obj" \ + ".\combase.obj" \ + ".\debugmessage.obj" \ +# ".\dllentry.obj" \ + ".\register.obj" + + +portaudio.dll : $(LINK32_OBJS) ".\portaudio.def" + $(LINK32) $(DLL_LINK_FLAGS) /def:".\portaudio.def" $(LINK32_OBJS) + +#==================================================================== +# asio files (need to agree to steinberg agreement) +# this makefile assumes all files have being copied in the pa_win/msvc dir (for now) +# see readme.txt for details + +".\asio.obj" : ".\common\asio.cpp" + $(CPP) $(CFLAGS) $(ASIOINC) /Fo".\asio.obj" /c ".\common\asio.cpp" + +".\ASIOConvertSamples.obj" : ".\host\ASIOConvertSamples.cpp" + $(CPP) $(CFLAGS) $(ASIOINC) /Fo".\ASIOConvertSamples.obj" /c ".\host\ASIOConvertSamples.cpp" + +".\asiodrivers.obj" : ".\host\asiodrivers.cpp" + $(CPP) $(CFLAGS) $(ASIOINC) /Fo".\asiodrivers.obj" /c ".\host\asiodrivers.cpp" + +".\asiolist.obj" : ".\host\pc\asiolist.cpp" + $(CPP) $(CFLAGS) $(ASIOINC) /Fo".\asiolist.obj" /c ".\host\pc\asiolist.cpp" + +".\combase.obj" : ".\common\combase.cpp" + $(CPP) $(CFLAGS) $(ASIOINC) /Fo".\combase.obj" /c ".\common\combase.cpp" + +".\debugmessage.obj" : ".\common\debugmessage.cpp" + $(CPP) $(CFLAGS) $(ASIOINC) /Fo".\debugmessage.obj" /c ".\common\debugmessage.cpp" + +".\register.obj" : ".\common\register.cpp" + $(CPP) $(CFLAGS) $(ASIOINC) /Fo".\register.obj" /c ".\common\register.cpp" + +#==================================================================== +# Portaudio Common +# +".\pa_allocation.obj" : "..\..\pa_common\pa_allocation.c" + $(CPP) $(CFLAGS) $(COMMONINC) /Fo".\pa_allocation.obj" /c "..\..\pa_common\pa_allocation.c" + +".\pa_converters.obj" : "..\..\pa_common\pa_converters.c" + $(CPP) $(CFLAGS) $(COMMONINC) /Fo".\pa_converters.obj" /c "..\..\pa_common\pa_converters.c" + +".\pa_cppHelp.obj" : "..\..\pa_common\pa_cppHelp.cpp" + $(CPP) $(CFLAGS) $(COMMONINC) /Fo".\pa_cppHelp.obj" /c "..\..\pa_common\pa_cppHelp.cpp" + +".\pa_cpuload.obj" : "..\..\pa_common\pa_cpuload.c" + $(CPP) $(CFLAGS) $(COMMONINC) /Fo".\pa_cpuload.obj" /c "..\..\pa_common\pa_cpuload.c" + +".\pa_dither.obj" : "..\..\pa_common\pa_dither.c" + $(CPP) $(CFLAGS) $(COMMONINC) /Fo".\pa_dither.obj" /c "..\..\pa_common\pa_dither.c" + +".\pa_front.obj" : "..\..\pa_common\pa_front.c" + $(CPP) $(CFLAGS) $(COMMONINC) /Fo".\pa_front.obj" /c "..\..\pa_common\pa_front.c" + +".\pa_process.obj" : "..\..\pa_common\pa_process.c" + $(CPP) $(CFLAGS) $(COMMONINC) /Fo".\pa_process.obj" /c "..\..\pa_common\pa_process.c" + +".\pa_skeleton.obj" : "..\..\pa_common\pa_skeleton.c" + $(CPP) $(CFLAGS) $(COMMONINC) /Fo".\pa_skeleton.obj" /c "..\..\pa_common\pa_skeleton.c" + +".\pa_stream.obj" : "..\..\pa_common\pa_stream.c" + $(CPP) $(CFLAGS) $(COMMONINC) /Fo".\pa_stream.obj" /c "..\..\pa_common\pa_stream.c" + +".\pa_trace.obj" : "..\..\pa_common\pa_trace.c" + $(CPP) $(CFLAGS) $(COMMONINC) /Fo".\pa_trace.obj" /c "..\..\pa_common\pa_trace.c" + +#==================================================================== +# Portaudio implementations +# + +".\pa_win_hostapis.obj" : "..\..\pa_win\pa_win_hostapis.c" + $(CPP) $(CFLAGS) $(COMMONINC) /Fo".\pa_win_hostapis.obj" /c "..\..\pa_win\pa_win_hostapis.c" + +".\pa_win_util.obj" : "..\..\pa_win\pa_win_util.c" + $(CPP) $(CFLAGS) $(COMMONINC) /Fo".\pa_win_util.obj" /c "..\..\pa_win\pa_win_util.c" + +".\pa_x86_plain_converters.obj" : "..\..\pa_win\pa_x86_plain_converters.c" + $(CPP) $(CFLAGS) $(COMMONINC) /Fo".\pa_x86_plain_converters.obj" /c "..\..\pa_win\pa_x86_plain_converters.c" + +".\pa_asio.obj" : "..\..\pa_asio\pa_asio.cpp" + $(CPP) $(CFLAGS) $(ASIOINC) $(COMMONINC) /Fo".\pa_asio.obj" /c "..\..\pa_asio\pa_asio.cpp" + +".\pa_win_wmme.obj" : "..\..\pa_win_wmme\pa_win_wmme.c" + $(CPP) $(CFLAGS) $(COMMONINC) /Fo".\pa_win_wmme.obj" /c "..\..\pa_win_wmme\pa_win_wmme.c" + +".\pa_win_ds.obj" : "..\..\pa_win_ds\pa_win_ds.c" + $(CPP) $(CFLAGS) $(COMMONINC) /Fo".\pa_win_ds.obj" /c "..\..\pa_win_ds\pa_win_ds.c" + +".\dsound_wrapper.obj" : "..\..\pa_win_ds\dsound_wrapper.c" + $(CPP) $(CFLAGS) $(COMMONINC) /Fo".\dsound_wrapper.obj" /c "..\..\pa_win_ds\dsound_wrapper.c" + + +# End of Makefile +#==================================================================== +# \ No newline at end of file diff --git a/pa_win/msvc/clean.bat b/pa_win/msvc/clean.bat new file mode 100755 index 0000000..601c0d3 --- /dev/null +++ b/pa_win/msvc/clean.bat @@ -0,0 +1,7 @@ +del *.obj +del *.dll +del *.lib +del *.exp +del *.pch +del *.idb + diff --git a/pa_win/msvc/make.bat b/pa_win/msvc/make.bat new file mode 100755 index 0000000..34d6aed --- /dev/null +++ b/pa_win/msvc/make.bat @@ -0,0 +1,8 @@ +CALL C:\progra~1\micros~2\VC98\bin\vcvars32 +del *.dll +del *.lib +nmake Makefile.msvc +del *.obj +del *.exp +del *.pch +del *.idb diff --git a/pa_win/msvc/portaudio.def b/pa_win/msvc/portaudio.def new file mode 100644 index 0000000..97a1c35 --- /dev/null +++ b/pa_win/msvc/portaudio.def @@ -0,0 +1,43 @@ +LIBRARY portaudio.dll +EXPORTS + +; +Pa_GetVersion @1 +Pa_GetVersionText @2 +Pa_GetErrorText @3 +Pa_Initialize @4 +Pa_Terminate @5 +Pa_GetHostApiCount @6 +Pa_GetDefaultHostApi @7 +Pa_GetHostApiInfo @8 +Pa_HostApiTypeIdToHostApiIndex @9 +Pa_HostApiDeviceIndexToDeviceIndex @10 +Pa_GetLastHostErrorInfo @11 +Pa_GetDeviceCount @12 +Pa_GetDefaultInputDevice @13 +Pa_GetDefaultOutputDevice @14 +Pa_GetDeviceInfo @15 +Pa_IsFormatSupported @16 +Pa_OpenStream @17 +Pa_OpenDefaultStream @18 +Pa_CloseStream @19 +Pa_SetStreamFinishedCallback @20 +Pa_StartStream @21 +Pa_StopStream @22 +Pa_AbortStream @23 +Pa_IsStreamStopped @24 +Pa_IsStreamActive @25 +Pa_GetStreamInfo @26 +Pa_GetStreamTime @27 +Pa_GetStreamCpuLoad @28 +Pa_ReadStream @29 +Pa_WriteStream @30 +Pa_GetStreamReadAvailable @31 +Pa_GetStreamWriteAvailable @32 +Pa_GetSampleSize @33 +Pa_Sleep @34 +PaAsio_GetAvailableLatencyValues @50 +PaAsio_ShowControlPanel @51 +PaUtil_InitializeX86PlainConverters @52 +PaAsio_GetInputChannelName @53 +PaAsio_GetOutputChannelName @54 \ No newline at end of file diff --git a/pa_win/msvc/readme.txt b/pa_win/msvc/readme.txt new file mode 100644 index 0000000..19ced4c --- /dev/null +++ b/pa_win/msvc/readme.txt @@ -0,0 +1,56 @@ +Hello + + This is a small list of steps in order to build portaudio +(Currently v19-devel) into a VC6 DLL and lib file. +This DLL contains all 3 current win32 PA APIS (MM/DS/ASIO) + +1)Copy the source dirs that comes with the ASIO SDK inside pa_win\msvc + so you should now have: + + pa_win\msvc\common + pa_win\msvc\host + pa_win\msvc\host\sample + pa_win\msvc\host\pc + pa_win\msvc\host\mac (not needed) + + You dont need "driver" + + +2)execure "make.bat", this assumes VC6 is installed in + C:\Program Files\Microsoft Visual Studio\ + + if its not, + + Open a command Prompt and execute "vcvars32.bat" which sets the environment + so that you can use Microsoft's "nmake" + EX: C:\Program Files\Microsoft Visual Studio\VC98\Bin\vcvars32.bat + or (C:\progra~1\micros~2\VC98\bin\vcvars32) dumb de dumb + + You should now have seen a line that said: + "Setting environment for using Microsoft Visual C++ tools." + While in pa_win\msvc , type "nmake makefile.msvc" + this _should_ create portaudio.dll and portaudio.lib + +3)Now in any VC6 project, in which you require portaudio, + you can just link with portaudio.lib, and of course include the + relevant headers + (portaudio.h, and/or pa_asio.h , pa_x86_plain_converters.h) See (*) + +4) Your new exe should now use portaudio.dll. + + +Have fun! + +(*): you may want to add/remove some DLL entry points. +Right now those 3 entries are _not_ from portaudio.h + +(from portaudio.def) +(...) +PaAsio_GetAvailableLatencyValues @50 +PaAsio_ShowControlPanel @51 +PaUtil_InitializeX86PlainConverters @52 + + +----- +last update April 16th 2003 +David Viens, davidv@plogue.com \ No newline at end of file diff --git a/pa_win/msvc/setenv.bat b/pa_win/msvc/setenv.bat new file mode 100755 index 0000000..f4c815a --- /dev/null +++ b/pa_win/msvc/setenv.bat @@ -0,0 +1 @@ +C:\progra~1\micros~2\VC98\bin\vcvars32 diff --git a/pa_win/pa_win_hostapis.c b/pa_win/pa_win_hostapis.c new file mode 100644 index 0000000..acdaf9a --- /dev/null +++ b/pa_win/pa_win_hostapis.c @@ -0,0 +1,91 @@ +/* + * $Id$ + * 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. + * + * 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. + */ + +/** @file + 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; + diff --git a/pa_win/pa_win_util.c b/pa_win/pa_win_util.c new file mode 100644 index 0000000..32d0dbb --- /dev/null +++ b/pa_win/pa_win_util.c @@ -0,0 +1,134 @@ +/* + * $Id$ + * 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. + * + * 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. + */ + +/** @file + 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 + { + return timeGetTime() * .001; + } +} diff --git a/pa_win/pa_x86_plain_converters.c b/pa_win/pa_x86_plain_converters.c new file mode 100644 index 0000000..98442a8 --- /dev/null +++ b/pa_win/pa_x86_plain_converters.c @@ -0,0 +1,1167 @@ +#include "pa_x86_plain_converters.h" + +#include "pa_converters.h" +#include "pa_dither.h" + +/* + plain intel assemby versions of standard pa converter functions. + + 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; +} + +/* -------------------------------------------------------------------------- */ diff --git a/pa_win/pa_x86_plain_converters.h b/pa_win/pa_x86_plain_converters.h new file mode 100644 index 0000000..f56c710 --- /dev/null +++ b/pa_win/pa_x86_plain_converters.h @@ -0,0 +1,19 @@ +#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 +*/ +void PaUtil_InitializeX86PlainConverters( void ); + + +#ifdef __cplusplus +} +#endif /* __cplusplus */ +#endif /* PA_X86_PLAIN_CONVERTERS_H */ diff --git a/pa_win_ds/dsound_wrapper.c b/pa_win_ds/dsound_wrapper.c index e795525..474fb84 100644 --- a/pa_win_ds/dsound_wrapper.c +++ b/pa_win_ds/dsound_wrapper.c @@ -36,12 +36,21 @@ #include #include #include -#define INITGUID // Needed to build IID_IDirectSoundNotify. See objbase.h for info. -#include -#include + #include "dsound_wrapper.h" +#include "pa_dsound_dynlink.h" #include "pa_trace.h" +/* + Rather than linking with dxguid.a or using "#define INITGUID" to force a + header file to instantiate the required GUID(s), we define them directly + below. +*/ +#include // needed for the DEFINE_GUID macro +DEFINE_GUID(IID_IDirectSoundNotify, 0xb0210783, 0x89cd, 0x11d0, 0xaf, 0x8, 0x0, 0xa0, 0xc9, 0x25, 0xcd, 0x16); + + + /************************************************************************************/ void DSW_Term( DSoundWrapper *dsw ) { @@ -52,19 +61,20 @@ void DSW_Term( DSoundWrapper *dsw ) IDirectSoundBuffer_Release( dsw->dsw_OutputBuffer ); dsw->dsw_OutputBuffer = NULL; } -#if SUPPORT_AUDIO_CAPTURE + if (dsw->dsw_InputBuffer) { IDirectSoundCaptureBuffer_Stop( dsw->dsw_InputBuffer ); IDirectSoundCaptureBuffer_Release( dsw->dsw_InputBuffer ); dsw->dsw_InputBuffer = NULL; } + if (dsw->dsw_pDirectSoundCapture) { IDirectSoundCapture_Release( dsw->dsw_pDirectSoundCapture ); dsw->dsw_pDirectSoundCapture = NULL; } -#endif /* SUPPORT_AUDIO_CAPTURE */ + if (dsw->dsw_pDirectSound) { IDirectSound_Release( dsw->dsw_pDirectSound ); @@ -81,13 +91,13 @@ HRESULT DSW_Init( DSoundWrapper *dsw ) HRESULT DSW_InitOutputDevice( DSoundWrapper *dsw, LPGUID lpGUID ) { // Create the DS object - HRESULT hr = DirectSoundCreate( lpGUID, &dsw->dsw_pDirectSound, NULL ); + HRESULT hr = paWinDsDSoundEntryPoints.DirectSoundCreate( lpGUID, &dsw->dsw_pDirectSound, NULL ); if( hr != DS_OK ) return hr; return hr; } /************************************************************************************/ -HRESULT DSW_InitOutputBuffer( DSoundWrapper *dsw, unsigned long nFrameRate, int nChannels, int bytesPerBuffer ) +HRESULT DSW_InitOutputBuffer( DSoundWrapper *dsw, unsigned long nFrameRate, WORD nChannels, int bytesPerBuffer ) { DWORD dwDataLen; DWORD playCursor; @@ -100,17 +110,25 @@ HRESULT DSW_InitOutputBuffer( DSoundWrapper *dsw, unsigned long nFrameRate, int DSBUFFERDESC secondaryDesc; unsigned char* pDSBuffData; LARGE_INTEGER counterFrequency; + dsw->dsw_OutputSize = bytesPerBuffer; dsw->dsw_OutputRunning = FALSE; dsw->dsw_OutputUnderflows = 0; dsw->dsw_FramesWritten = 0; - dsw->dsw_BytesPerFrame = nChannels * sizeof(short); + dsw->dsw_BytesPerOutputFrame = nChannels * sizeof(short); + // 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( dsw->dsw_pDirectSound, @@ -118,6 +136,7 @@ HRESULT DSW_InitOutputBuffer( DSoundWrapper *dsw, unsigned long nFrameRate, int { 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. @@ -135,11 +154,12 @@ HRESULT DSW_InitOutputBuffer( DSoundWrapper *dsw, unsigned long nFrameRate, int wfFormat.nChannels = nChannels; wfFormat.nSamplesPerSec = nFrameRate; wfFormat.wBitsPerSample = 8 * sizeof(short); - wfFormat.nBlockAlign = wfFormat.nChannels * wfFormat.wBitsPerSample / 8; + wfFormat.nBlockAlign = (WORD)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8)); wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign; wfFormat.cbSize = 0; /* No extended format info. */ // Set the primary buffer's format if((result = IDirectSoundBuffer_SetFormat( pPrimaryBuffer, &wfFormat)) != DS_OK) return result; + // ---------------------------------------------------------------------- // Setup the secondary buffer description ZeroMemory(&secondaryDesc, sizeof(DSBUFFERDESC)); @@ -161,7 +181,6 @@ HRESULT DSW_InitOutputBuffer( DSoundWrapper *dsw, unsigned long nFrameRate, int { int framesInBuffer = bytesPerBuffer / (nChannels * sizeof(short)); dsw->dsw_CounterTicksPerBuffer.QuadPart = (counterFrequency.QuadPart * framesInBuffer) / nFrameRate; - AddTraceMessage("dsw_CounterTicksPerBuffer = %d\n", dsw->dsw_CounterTicksPerBuffer.LowPart ); } else { @@ -174,7 +193,7 @@ HRESULT DSW_InitOutputBuffer( DSoundWrapper *dsw, unsigned long nFrameRate, int { return hr; } - dsw->dsw_FramesWritten = dsw->dsw_WriteOffset / dsw->dsw_BytesPerFrame; + dsw->dsw_FramesWritten = dsw->dsw_WriteOffset / dsw->dsw_BytesPerOutputFrame; /* printf("DSW_InitOutputBuffer: playCursor = %d, writeCursor = %d\n", playCursor, dsw->dsw_WriteOffset ); */ return DS_OK; } @@ -217,6 +236,31 @@ HRESULT DSW_StopOutput( DSoundWrapper *dsw ) } /************************************************************************************/ +HRESULT DSW_QueryOutputFilled( DSoundWrapper *dsw, long *bytesFilledPtr ) +{ + HRESULT hr; + DWORD playCursor; + DWORD writeCursor; + long bytesFilled; + // Query to see where play position is. + // We don't need the writeCursor but sometimes DirectSound doesn't handle NULLS correctly + // so let's pass a pointer just to be safe. + hr = IDirectSoundBuffer_GetCurrentPosition( dsw->dsw_OutputBuffer, &playCursor, &writeCursor ); + if( hr != DS_OK ) + { + return hr; + } + bytesFilled = dsw->dsw_WriteOffset - playCursor; + if( bytesFilled < 0 ) bytesFilled += dsw->dsw_OutputSize; // unwrap offset + *bytesFilledPtr = bytesFilled; + return hr; +} + +/************************************************************************************ + * 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. + */ HRESULT DSW_QueryOutputSpace( DSoundWrapper *dsw, long *bytesEmpty ) { HRESULT hr; @@ -225,16 +269,11 @@ HRESULT DSW_QueryOutputSpace( DSoundWrapper *dsw, long *bytesEmpty ) long numBytesEmpty; long playWriteGap; // Query to see how much room is in buffer. - // Note: Even though writeCursor is not used, it must be passed to prevent DirectSound from dieing - // under WinNT. The Microsoft documentation says we can pass NULL but apparently not. - // Thanks to Max Rheiner for the fix. hr = IDirectSoundBuffer_GetCurrentPosition( dsw->dsw_OutputBuffer, &playCursor, &writeCursor ); if( hr != DS_OK ) { return hr; } - AddTraceMessage("playCursor", playCursor); - AddTraceMessage("dsw_WriteOffset", dsw->dsw_WriteOffset); // Determine size of gap between playIndex and WriteIndex that we cannot write into. playWriteGap = writeCursor - playCursor; if( playWriteGap < 0 ) playWriteGap += dsw->dsw_OutputSize; // unwrap @@ -260,13 +299,11 @@ HRESULT DSW_QueryOutputSpace( DSoundWrapper *dsw, long *bytesEmpty ) buffersWrapped = (bytesExpected - bytesPlayed) / dsw->dsw_OutputSize; if( buffersWrapped > 0 ) { - AddTraceMessage("playCursor wrapped! bytesPlayed", bytesPlayed ); - AddTraceMessage("playCursor wrapped! bytesExpected", bytesExpected ); playCursor += (buffersWrapped * dsw->dsw_OutputSize); bytesPlayed += (buffersWrapped * dsw->dsw_OutputSize); } /* Maintain frame output cursor. */ - dsw->dsw_FramesPlayed += (bytesPlayed / dsw->dsw_BytesPerFrame); + dsw->dsw_FramesPlayed += (bytesPlayed / dsw->dsw_BytesPerOutputFrame); } numBytesEmpty = playCursor - dsw->dsw_WriteOffset; if( numBytesEmpty < 0 ) numBytesEmpty += dsw->dsw_OutputSize; // unwrap offset @@ -276,7 +313,6 @@ HRESULT DSW_QueryOutputSpace( DSoundWrapper *dsw, long *bytesEmpty ) if( dsw->dsw_OutputRunning ) { dsw->dsw_OutputUnderflows += 1; - AddTraceMessage("underflow detected! numBytesEmpty", numBytesEmpty ); } dsw->dsw_WriteOffset = writeCursor; numBytesEmpty = dsw->dsw_OutputSize - playWriteGap; @@ -311,7 +347,7 @@ HRESULT DSW_ZeroEmptySpace( DSoundWrapper *dsw ) // Update our buffer offset and unlock sound buffer dsw->dsw_WriteOffset = (dsw->dsw_WriteOffset + dwsize1 + dwsize2) % dsw->dsw_OutputSize; IDirectSoundBuffer_Unlock( dsw->dsw_OutputBuffer, lpbuf1, dwsize1, lpbuf2, dwsize2); - dsw->dsw_FramesWritten += bytesEmpty / dsw->dsw_BytesPerFrame; + dsw->dsw_FramesWritten += bytesEmpty / dsw->dsw_BytesPerOutputFrame; } return hr; } @@ -338,7 +374,7 @@ HRESULT DSW_WriteBlock( DSoundWrapper *dsw, char *buf, long numBytes ) // Update our buffer offset and unlock sound buffer dsw->dsw_WriteOffset = (dsw->dsw_WriteOffset + dwsize1 + dwsize2) % dsw->dsw_OutputSize; IDirectSoundBuffer_Unlock( dsw->dsw_OutputBuffer, lpbuf1, dwsize1, lpbuf2, dwsize2); - dsw->dsw_FramesWritten += numBytes / dsw->dsw_BytesPerFrame; + dsw->dsw_FramesWritten += numBytes / dsw->dsw_BytesPerOutputFrame; } return hr; } @@ -353,7 +389,6 @@ DWORD DSW_GetOutputStatus( DSoundWrapper *dsw ) return( status ); } -#if SUPPORT_AUDIO_CAPTURE /* These routines are used to support audio input. * Do NOT compile these calls when using NT4 because it does * not support the entry points. @@ -361,22 +396,25 @@ DWORD DSW_GetOutputStatus( DSoundWrapper *dsw ) /************************************************************************************/ HRESULT DSW_InitInputDevice( DSoundWrapper *dsw, LPGUID lpGUID ) { - HRESULT hr = DirectSoundCaptureCreate( lpGUID, &dsw->dsw_pDirectSoundCapture, NULL ); + HRESULT hr = paWinDsDSoundEntryPoints.DirectSoundCaptureCreate( lpGUID, &dsw->dsw_pDirectSoundCapture, NULL ); if( hr != DS_OK ) return hr; return hr; } /************************************************************************************/ -HRESULT DSW_InitInputBuffer( DSoundWrapper *dsw, unsigned long nFrameRate, int nChannels, int bytesPerBuffer ) +HRESULT DSW_InitInputBuffer( DSoundWrapper *dsw, unsigned long nFrameRate, WORD nChannels, int bytesPerBuffer ) { DSCBUFFERDESC captureDesc; WAVEFORMATEX wfFormat; HRESULT result; + + dsw->dsw_BytesPerInputFrame = nChannels * sizeof(short); + // Define the buffer format wfFormat.wFormatTag = WAVE_FORMAT_PCM; wfFormat.nChannels = nChannels; wfFormat.nSamplesPerSec = nFrameRate; wfFormat.wBitsPerSample = 8 * sizeof(short); - wfFormat.nBlockAlign = wfFormat.nChannels * (wfFormat.wBitsPerSample / 8); + wfFormat.nBlockAlign = (WORD)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8)); wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign; wfFormat.cbSize = 0; /* No extended format info. */ dsw->dsw_InputSize = bytesPerBuffer; @@ -463,4 +501,3 @@ HRESULT DSW_ReadBlock( DSoundWrapper *dsw, char *buf, long numBytes ) return hr; } -#endif /* SUPPORT_AUDIO_CAPTURE */ diff --git a/pa_win_ds/dsound_wrapper.h b/pa_win_ds/dsound_wrapper.h index e926514..839969d 100644 --- a/pa_win_ds/dsound_wrapper.h +++ b/pa_win_ds/dsound_wrapper.h @@ -35,14 +35,22 @@ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ -#include -#if !defined(BOOL) -#define BOOL short + +/* 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 -#ifndef SUPPORT_AUDIO_CAPTURE -#define SUPPORT_AUDIO_CAPTURE (1) #endif +/* + We are only using DX3 in here, no need to polute the namespace - davidv +*/ +#define DIRECTSOUND_VERSION 0x0300 + +#include + #ifdef __cplusplus extern "C" { @@ -54,12 +62,12 @@ extern "C" typedef struct { - /* Output */ +/* Output */ LPDIRECTSOUND dsw_pDirectSound; LPDIRECTSOUNDBUFFER dsw_OutputBuffer; DWORD dsw_WriteOffset; /* last write position */ INT dsw_OutputSize; - INT dsw_BytesPerFrame; + INT dsw_BytesPerOutputFrame; /* Try to detect play buffer underflows. */ LARGE_INTEGER dsw_CounterTicksPerBuffer; /* counter ticks it should take to play a full buffer */ LARGE_INTEGER dsw_LastPlayTime; @@ -69,20 +77,18 @@ typedef struct /* use double which lets us can play for several thousand years with enough precision */ double dsw_FramesWritten; double dsw_FramesPlayed; -#if SUPPORT_AUDIO_CAPTURE - /* Input */ +/* Input */ + INT dsw_BytesPerInputFrame; LPDIRECTSOUNDCAPTURE dsw_pDirectSoundCapture; LPDIRECTSOUNDCAPTUREBUFFER dsw_InputBuffer; UINT dsw_ReadOffset; /* last read position */ UINT dsw_InputSize; -#endif /* SUPPORT_AUDIO_CAPTURE */ +} DSoundWrapper; -} -DSoundWrapper; HRESULT DSW_Init( DSoundWrapper *dsw ); void DSW_Term( DSoundWrapper *dsw ); HRESULT DSW_InitOutputBuffer( DSoundWrapper *dsw, unsigned long nFrameRate, - int nChannels, int bufSize ); + WORD nChannels, int bufSize ); HRESULT DSW_StartOutput( DSoundWrapper *dsw ); HRESULT DSW_StopOutput( DSoundWrapper *dsw ); DWORD DSW_GetOutputStatus( DSoundWrapper *dsw ); @@ -91,14 +97,13 @@ HRESULT DSW_ZeroEmptySpace( DSoundWrapper *dsw ); HRESULT DSW_QueryOutputSpace( DSoundWrapper *dsw, long *bytesEmpty ); HRESULT DSW_Enumerate( DSoundWrapper *dsw ); -#if SUPPORT_AUDIO_CAPTURE HRESULT DSW_InitInputBuffer( DSoundWrapper *dsw, unsigned long nFrameRate, - int nChannels, int bufSize ); + WORD nChannels, int bufSize ); HRESULT DSW_StartInput( DSoundWrapper *dsw ); HRESULT DSW_StopInput( DSoundWrapper *dsw ); HRESULT DSW_ReadBlock( DSoundWrapper *dsw, char *buf, long numBytes ); HRESULT DSW_QueryInputFilled( DSoundWrapper *dsw, long *bytesFilled ); -#endif /* SUPPORT_AUDIO_CAPTURE */ +HRESULT DSW_QueryOutputFilled( DSoundWrapper *dsw, long *bytesFilled ); #ifdef __cplusplus } diff --git a/pa_win_ds/pa_dsound.c b/pa_win_ds/pa_dsound.c deleted file mode 100644 index 877c01d..0000000 --- a/pa_win_ds/pa_dsound.c +++ /dev/null @@ -1,1021 +0,0 @@ -/* - * $Id$ - * PortAudio Portable Real-Time Audio Library - * Latest Version at: http://www.softsynth.com/portaudio/ - * DirectSound Implementation - * - * Copyright (c) 1999-2000 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. - * - */ -/* Modifications - * 7/19/01 Mike Berry - casts for compiling with __MWERKS__ CodeWarrior - * 9/27/01 Phil Burk - use number of frames instead of real-time for CPULoad calculation. - * 4/19/02 Phil Burk - Check for Win XP for system latency calculation. - */ -/* Compiler flags: - SUPPORT_AUDIO_CAPTURE - define this flag if you want to SUPPORT_AUDIO_CAPTURE - */ - -#include -#include -#ifndef __MWERKS__ -#include -#include -#endif //__MWERKS__ -#include -#include "portaudio.h" -#include "pa_host.h" -#include "pa_trace.h" -#include "dsound_wrapper.h" - -#define PRINT(x) { printf x; fflush(stdout); } -#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) - -/* Trigger an underflow for testing purposes. Should normally be (0). */ -#define PA_SIMULATE_UNDERFLOW (0) -#if PA_SIMULATE_UNDERFLOW -static gUnderCallbackCounter = 0; -#define UNDER_START_GAP (10) -#define UNDER_STOP_GAP (UNDER_START_GAP + 4) -#endif - -/************************************************* Definitions ********/ -typedef struct internalPortAudioStream internalPortAudioStream; -typedef struct internalPortAudioDevice -{ - GUID pad_GUID; - GUID *pad_lpGUID; - double pad_SampleRates[10]; /* for pointing to from pad_Info FIXME?!*/ - PaDeviceInfo pad_Info; -} -internalPortAudioDevice; - -/* Define structure to contain all DirectSound and Windows specific data. */ -typedef struct PaHostSoundControl -{ - DSoundWrapper pahsc_DSoundWrapper; - MMRESULT pahsc_TimerID; - BOOL pahsc_IfInsideCallback; /* Test for reentrancy. */ - short *pahsc_NativeBuffer; - unsigned int pahsc_BytesPerBuffer; /* native buffer size in bytes */ - double pahsc_ValidFramesWritten; - int pahsc_FramesPerDSBuffer; - /* For measuring CPU utilization. */ - LARGE_INTEGER pahsc_EntryCount; - double pahsc_InverseTicksPerUserBuffer; -} -PaHostSoundControl; - -/************************************************* Shared Data ********/ -/* FIXME - put Mutex around this shared data. */ -static int sNumDevices = 0; -static int sDeviceIndex = 0; -static internalPortAudioDevice *sDevices = NULL; -static int sDefaultInputDeviceID = paNoDevice; -static int sDefaultOutputDeviceID = paNoDevice; -static int sEnumerationError; -static int sPaHostError = 0; -/************************************************* Prototypes **********/ -static internalPortAudioDevice *Pa_GetInternalDevice( PaDeviceID id ); -static BOOL CALLBACK Pa_EnumProc(LPGUID lpGUID, - LPCTSTR lpszDesc, - LPCTSTR lpszDrvName, - LPVOID lpContext ); -static BOOL CALLBACK Pa_CountDevProc(LPGUID lpGUID, - LPCTSTR lpszDesc, - LPCTSTR lpszDrvName, - LPVOID lpContext ); -static Pa_QueryDevices( void ); -static void CALLBACK Pa_TimerCallback(UINT uID, UINT uMsg, - DWORD dwUser, DWORD dw1, DWORD dw2); - -/********************************* BEGIN CPU UTILIZATION MEASUREMENT ****/ -static void Pa_StartUsageCalculation( internalPortAudioStream *past ) -{ - PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; - if( pahsc == NULL ) return; - /* Query system timer for usage analysis and to prevent overuse of CPU. */ - QueryPerformanceCounter( &pahsc->pahsc_EntryCount ); -} - -static void Pa_EndUsageCalculation( internalPortAudioStream *past ) -{ - LARGE_INTEGER CurrentCount = { 0, 0 }; - PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; - if( pahsc == NULL ) return; - /* - ** Measure CPU utilization during this callback. Note that this calculation - ** assumes that we had the processor the whole time. - */ -#define LOWPASS_COEFFICIENT_0 (0.9) -#define LOWPASS_COEFFICIENT_1 (0.99999 - LOWPASS_COEFFICIENT_0) - if( QueryPerformanceCounter( &CurrentCount ) ) - { - LONGLONG InsideCount = CurrentCount.QuadPart - pahsc->pahsc_EntryCount.QuadPart; - double newUsage = InsideCount * pahsc->pahsc_InverseTicksPerUserBuffer; - past->past_Usage = (LOWPASS_COEFFICIENT_0 * past->past_Usage) + - (LOWPASS_COEFFICIENT_1 * newUsage); - } -} - -/****************************************** END CPU UTILIZATION *******/ -static PaError Pa_QueryDevices( void ) -{ - int numBytes; - sDefaultInputDeviceID = paNoDevice; - sDefaultOutputDeviceID = paNoDevice; - /* Enumerate once just to count devices. */ - sNumDevices = 0; // for default device - DirectSoundEnumerate( (LPDSENUMCALLBACK)Pa_CountDevProc, NULL ); -#if SUPPORT_AUDIO_CAPTURE - DirectSoundCaptureEnumerate( (LPDSENUMCALLBACK)Pa_CountDevProc, NULL ); -#endif /* SUPPORT_AUDIO_CAPTURE */ - /* Allocate structures to hold device info. */ - numBytes = sNumDevices * sizeof(internalPortAudioDevice); - sDevices = (internalPortAudioDevice *)PaHost_AllocateFastMemory( numBytes ); /* MEM */ - if( sDevices == NULL ) return paInsufficientMemory; - /* Enumerate again to fill in structures. */ - sDeviceIndex = 0; - sEnumerationError = 0; - DirectSoundEnumerate( (LPDSENUMCALLBACK)Pa_EnumProc, (void *)0 ); -#if SUPPORT_AUDIO_CAPTURE - if( sEnumerationError != paNoError ) return sEnumerationError; - sEnumerationError = 0; - DirectSoundCaptureEnumerate( (LPDSENUMCALLBACK)Pa_EnumProc, (void *)1 ); -#endif /* SUPPORT_AUDIO_CAPTURE */ - return sEnumerationError; -} -/************************************************************************************/ -long Pa_GetHostError() -{ - return sPaHostError; -} -/************************************************************************************ -** Just count devices so we know how much memory to allocate. -*/ -static BOOL CALLBACK Pa_CountDevProc(LPGUID lpGUID, - LPCTSTR lpszDesc, - LPCTSTR lpszDrvName, - LPVOID lpContext ) -{ - sNumDevices++; - return TRUE; -} -/************************************************************************************ -** Extract capabilities info from each device. -*/ -static BOOL CALLBACK Pa_EnumProc(LPGUID lpGUID, - LPCTSTR lpszDesc, - LPCTSTR lpszDrvName, - LPVOID lpContext ) -{ - HRESULT hr; - LPDIRECTSOUND lpDirectSound; -#if SUPPORT_AUDIO_CAPTURE - LPDIRECTSOUNDCAPTURE lpDirectSoundCapture; -#endif /* SUPPORT_AUDIO_CAPTURE */ - int isInput = (int) lpContext; /* Passed from Pa_CountDevices() */ - internalPortAudioDevice *pad; - - if( sDeviceIndex >= sNumDevices ) - { - sEnumerationError = paInternalError; - return FALSE; - } - pad = &sDevices[sDeviceIndex]; - /* Copy GUID to static array. Set pointer. */ - if( lpGUID == NULL ) - { - pad->pad_lpGUID = NULL; - } - else - { - memcpy( &pad->pad_GUID, lpGUID, sizeof(GUID) ); - pad->pad_lpGUID = &pad->pad_GUID; - } - pad->pad_Info.sampleRates = pad->pad_SampleRates; /* Point to array. */ - /* Allocate room for descriptive name. */ - if( lpszDesc != NULL ) - { - int len = strlen(lpszDesc); - pad->pad_Info.name = (char *)malloc( len+1 ); - if( pad->pad_Info.name == NULL ) - { - sEnumerationError = paInsufficientMemory; - return FALSE; - } - memcpy( (void *) pad->pad_Info.name, lpszDesc, len+1 ); - } -#if SUPPORT_AUDIO_CAPTURE - if( isInput ) - { - /********** Input ******************************/ - DSCCAPS caps; - if( lpGUID == NULL ) sDefaultInputDeviceID = sDeviceIndex; - hr = DirectSoundCaptureCreate( lpGUID, &lpDirectSoundCapture, NULL ); - if( hr != DS_OK ) - { - pad->pad_Info.maxInputChannels = 0; - DBUG(("Cannot create Capture for %s. Result = 0x%x\n", lpszDesc, hr )); - } - else - { - /* Query device characteristics. */ - caps.dwSize = sizeof(caps); - IDirectSoundCapture_GetCaps( lpDirectSoundCapture, &caps ); - /* printf("caps.dwFormats = 0x%x\n", caps.dwFormats ); */ - pad->pad_Info.maxInputChannels = caps.dwChannels; - /* Determine sample rates from flags. */ - if( caps.dwChannels == 2 ) - { - int index = 0; - if( caps.dwFormats & WAVE_FORMAT_1S16) pad->pad_SampleRates[index++] = 11025.0; - if( caps.dwFormats & WAVE_FORMAT_2S16) pad->pad_SampleRates[index++] = 22050.0; - if( caps.dwFormats & WAVE_FORMAT_4S16) pad->pad_SampleRates[index++] = 44100.0; - pad->pad_Info.numSampleRates = index; - } - else if( caps.dwChannels == 1 ) - { - int index = 0; - if( caps.dwFormats & WAVE_FORMAT_1M16) pad->pad_SampleRates[index++] = 11025.0; - if( caps.dwFormats & WAVE_FORMAT_2M16) pad->pad_SampleRates[index++] = 22050.0; - if( caps.dwFormats & WAVE_FORMAT_4M16) pad->pad_SampleRates[index++] = 44100.0; - pad->pad_Info.numSampleRates = index; - } - else pad->pad_Info.numSampleRates = 0; - IDirectSoundCapture_Release( lpDirectSoundCapture ); - } - } - else -#endif /* SUPPORT_AUDIO_CAPTURE */ - - { - /********** Output ******************************/ - DSCAPS caps; - if( lpGUID == NULL ) sDefaultOutputDeviceID = sDeviceIndex; - /* Create interfaces for each object. */ - hr = DirectSoundCreate( lpGUID, &lpDirectSound, NULL ); - if( hr != DS_OK ) - { - pad->pad_Info.maxOutputChannels = 0; - DBUG(("Cannot create dsound for %s. Result = 0x%x\n", lpszDesc, hr )); - } - else - { - /* Query device characteristics. */ - caps.dwSize = sizeof(caps); - IDirectSound_GetCaps( lpDirectSound, &caps ); - pad->pad_Info.maxOutputChannels = ( caps.dwFlags & DSCAPS_PRIMARYSTEREO ) ? 2 : 1; - /* Get sample rates. */ - pad->pad_SampleRates[0] = (double) caps.dwMinSecondarySampleRate; - pad->pad_SampleRates[1] = (double) caps.dwMaxSecondarySampleRate; - if( caps.dwFlags & DSCAPS_CONTINUOUSRATE ) pad->pad_Info.numSampleRates = -1; - 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. - */ - pad->pad_SampleRates[0] = 11025.0f; - pad->pad_SampleRates[1] = 48000.0f; - pad->pad_Info.numSampleRates = -1; /* continuous range */ - - DBUG(("PA - Reported rates both zero. Setting to fake values for device #%d\n", sDeviceIndex )); - } - else - { - pad->pad_Info.numSampleRates = 1; - } - } - 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. - */ - pad->pad_Info.numSampleRates = -1; - DBUG(("PA - Sample rate range used instead of two odd values for device #%d\n", sDeviceIndex )); - } - else pad->pad_Info.numSampleRates = 2; - IDirectSound_Release( lpDirectSound ); - } - } - pad->pad_Info.nativeSampleFormats = paInt16; - sDeviceIndex++; - return( TRUE ); -} -/*************************************************************************/ -int Pa_CountDevices() -{ - if( sNumDevices <= 0 ) Pa_Initialize(); - return sNumDevices; -} -static internalPortAudioDevice *Pa_GetInternalDevice( PaDeviceID id ) -{ - if( (id < 0) || ( id >= Pa_CountDevices()) ) return NULL; - return &sDevices[id]; -} -/*************************************************************************/ -const PaDeviceInfo* Pa_GetDeviceInfo( PaDeviceID id ) -{ - internalPortAudioDevice *pad; - if( (id < 0) || ( id >= Pa_CountDevices()) ) return NULL; - pad = Pa_GetInternalDevice( id ); - return &pad->pad_Info ; -} -static PaError Pa_MaybeQueryDevices( void ) -{ - if( sNumDevices == 0 ) - { - return Pa_QueryDevices(); - } - return 0; -} -/************************************************************************* -** Returns recommended device ID. -** On the PC, the recommended device can be specified by the user 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 ID by using -** the supplied application "pa_devs". -*/ -#define PA_ENV_BUF_SIZE (32) -#define PA_REC_IN_DEV_ENV_NAME ("PA_RECOMMENDED_INPUT_DEVICE") -#define PA_REC_OUT_DEV_ENV_NAME ("PA_RECOMMENDED_OUTPUT_DEVICE") -static PaDeviceID PaHost_GetEnvDefaultDeviceID( char *envName ) -{ - DWORD hresult; - char envbuf[PA_ENV_BUF_SIZE]; - PaDeviceID recommendedID = paNoDevice; - /* Let user determine default device by setting environment variable. */ - hresult = GetEnvironmentVariable( envName, envbuf, PA_ENV_BUF_SIZE ); - if( (hresult > 0) && (hresult < PA_ENV_BUF_SIZE) ) - { - recommendedID = atoi( envbuf ); - } - return recommendedID; -} -PaDeviceID Pa_GetDefaultInputDeviceID( void ) -{ - PaError result; - result = PaHost_GetEnvDefaultDeviceID( PA_REC_IN_DEV_ENV_NAME ); - if( result < 0 ) - { - result = Pa_MaybeQueryDevices(); - if( result < 0 ) return result; - result = sDefaultInputDeviceID; - } - return result; -} -PaDeviceID Pa_GetDefaultOutputDeviceID( void ) -{ - PaError result; - result = PaHost_GetEnvDefaultDeviceID( PA_REC_OUT_DEV_ENV_NAME ); - if( result < 0 ) - { - result = Pa_MaybeQueryDevices(); - if( result < 0 ) return result; - result = sDefaultOutputDeviceID; - } - return result; -} -/********************************************************************** -** Make sure that we have queried the device capabilities. -*/ -PaError PaHost_Init( void ) -{ -#if PA_SIMULATE_UNDERFLOW - PRINT(("WARNING - Underflow Simulation Enabled - Expect a Big Glitch!!!\n")); -#endif - return Pa_MaybeQueryDevices(); -} -static PaError Pa_TimeSlice( internalPortAudioStream *past ) -{ - PaError result = 0; - long bytesEmpty = 0; - long bytesFilled = 0; - long bytesToXfer = 0; - long numChunks; - HRESULT hresult; - PaHostSoundControl *pahsc; - short *nativeBufPtr; - past->past_NumCallbacks += 1; - pahsc = (PaHostSoundControl *) past->past_DeviceData; - if( pahsc == NULL ) return paInternalError; - /* How much input data is available? */ -#if SUPPORT_AUDIO_CAPTURE - if( past->past_NumInputChannels > 0 ) - { - DSW_QueryInputFilled( &pahsc->pahsc_DSoundWrapper, &bytesFilled ); - bytesToXfer = bytesFilled; - } -#endif /* SUPPORT_AUDIO_CAPTURE */ - /* How much output room is available? */ - if( past->past_NumOutputChannels > 0 ) - { - DSW_QueryOutputSpace( &pahsc->pahsc_DSoundWrapper, &bytesEmpty ); - bytesToXfer = bytesEmpty; - } - AddTraceMessage( "bytesEmpty ", bytesEmpty ); - /* Choose smallest value if both are active. */ - if( (past->past_NumInputChannels > 0) && (past->past_NumOutputChannels > 0) ) - { - bytesToXfer = ( bytesFilled < bytesEmpty ) ? bytesFilled : bytesEmpty; - } - /* printf("bytesFilled = %d, bytesEmpty = %d, bytesToXfer = %d\n", - bytesFilled, bytesEmpty, bytesToXfer); - */ - /* Quantize to multiples of a buffer. */ - numChunks = bytesToXfer / pahsc->pahsc_BytesPerBuffer; - if( numChunks > (long)(past->past_NumUserBuffers/2) ) - { - numChunks = (long)past->past_NumUserBuffers/2; - } - else if( numChunks < 0 ) - { - numChunks = 0; - } - AddTraceMessage( "numChunks ", numChunks ); - nativeBufPtr = pahsc->pahsc_NativeBuffer; - if( numChunks > 0 ) - { - while( numChunks-- > 0 ) - { - /* Measure usage based on time to process one user buffer. */ - Pa_StartUsageCalculation( past ); -#if SUPPORT_AUDIO_CAPTURE - /* Get native data from DirectSound. */ - if( past->past_NumInputChannels > 0 ) - { - hresult = DSW_ReadBlock( &pahsc->pahsc_DSoundWrapper, (char *) nativeBufPtr, pahsc->pahsc_BytesPerBuffer ); - if( hresult < 0 ) - { - ERR_RPT(("DirectSound ReadBlock failed, hresult = 0x%x\n",hresult)); - sPaHostError = hresult; - break; - } - } -#endif /* SUPPORT_AUDIO_CAPTURE */ - /* Convert 16 bit native data to user data and call user routine. */ - result = Pa_CallConvertInt16( past, nativeBufPtr, nativeBufPtr ); - if( result != 0) break; - /* Pass native data to DirectSound. */ - if( past->past_NumOutputChannels > 0 ) - { - /* static short DEBUGHACK = 0; - DEBUGHACK += 0x0049; - nativeBufPtr[0] = DEBUGHACK; /* Make buzz to see if DirectSound still running. */ - hresult = DSW_WriteBlock( &pahsc->pahsc_DSoundWrapper, (char *) nativeBufPtr, pahsc->pahsc_BytesPerBuffer ); - if( hresult < 0 ) - { - ERR_RPT(("DirectSound WriteBlock failed, result = 0x%x\n",hresult)); - sPaHostError = hresult; - break; - } - } - Pa_EndUsageCalculation( past ); - } - } - return result; -} -/*******************************************************************/ -static void CALLBACK Pa_TimerCallback(UINT uID, UINT uMsg, DWORD dwUser, DWORD dw1, DWORD dw2) -{ - internalPortAudioStream *past; - PaHostSoundControl *pahsc; -#if PA_SIMULATE_UNDERFLOW - gUnderCallbackCounter++; - if( (gUnderCallbackCounter >= UNDER_START_GAP) && - (gUnderCallbackCounter <= UNDER_STOP_GAP) ) - { - if( gUnderCallbackCounter == UNDER_START_GAP) - { - AddTraceMessage("Begin stall: gUnderCallbackCounter =======", gUnderCallbackCounter ); - } - if( gUnderCallbackCounter == UNDER_STOP_GAP) - { - AddTraceMessage("End stall: gUnderCallbackCounter =======", gUnderCallbackCounter ); - } - return; - } -#endif - past = (internalPortAudioStream *) dwUser; - if( past == NULL ) return; - pahsc = (PaHostSoundControl *) past->past_DeviceData; - if( pahsc == NULL ) return; - if( !pahsc->pahsc_IfInsideCallback && past->past_IsActive ) - { - if( past->past_StopNow ) - { - past->past_IsActive = 0; - } - else if( past->past_StopSoon ) - { - DSoundWrapper *dsw = &pahsc->pahsc_DSoundWrapper; - if( past->past_NumOutputChannels > 0 ) - { - DSW_ZeroEmptySpace( dsw ); - AddTraceMessage("Pa_TimerCallback: waiting - written ", (int) dsw->dsw_FramesWritten ); - AddTraceMessage("Pa_TimerCallback: waiting - played ", (int) dsw->dsw_FramesPlayed ); - /* clear past_IsActive when all sound played */ - if( dsw->dsw_FramesPlayed >= past->past_FrameCount ) - { - past->past_IsActive = 0; - } - } - else - { - past->past_IsActive = 0; - } - } - else - { - pahsc->pahsc_IfInsideCallback = 1; - if( Pa_TimeSlice( past ) != 0) /* Call time slice independant of timing method. */ - { - past->past_StopSoon = 1; - } - pahsc->pahsc_IfInsideCallback = 0; - } - } -} -/*******************************************************************/ -PaError PaHost_OpenStream( internalPortAudioStream *past ) -{ - HRESULT hr; - PaError result = paNoError; - PaHostSoundControl *pahsc; - int numBytes, maxChannels; - unsigned int minNumBuffers; - internalPortAudioDevice *pad; - DSoundWrapper *dsw; - /* Allocate and initialize host data. */ - pahsc = (PaHostSoundControl *) PaHost_AllocateFastMemory(sizeof(PaHostSoundControl)); /* MEM */ - if( pahsc == NULL ) - { - result = paInsufficientMemory; - goto error; - } - memset( pahsc, 0, sizeof(PaHostSoundControl) ); - past->past_DeviceData = (void *) pahsc; - pahsc->pahsc_TimerID = 0; - dsw = &pahsc->pahsc_DSoundWrapper; - DSW_Init( dsw ); - /* Allocate native buffer. */ - maxChannels = ( past->past_NumOutputChannels > past->past_NumInputChannels ) ? - past->past_NumOutputChannels : past->past_NumInputChannels; - pahsc->pahsc_BytesPerBuffer = past->past_FramesPerUserBuffer * maxChannels * sizeof(short); - if( maxChannels > 0 ) - { - pahsc->pahsc_NativeBuffer = (short *) PaHost_AllocateFastMemory(pahsc->pahsc_BytesPerBuffer); /* MEM */ - if( pahsc->pahsc_NativeBuffer == NULL ) - { - result = paInsufficientMemory; - goto error; - } - } - else - { - result = paInvalidChannelCount; - goto error; - } - - DBUG(("PaHost_OpenStream: pahsc_MinFramesPerHostBuffer = %d\n", pahsc->pahsc_MinFramesPerHostBuffer )); - minNumBuffers = Pa_GetMinNumBuffers( past->past_FramesPerUserBuffer, past->past_SampleRate ); - past->past_NumUserBuffers = ( minNumBuffers > past->past_NumUserBuffers ) ? minNumBuffers : past->past_NumUserBuffers; - numBytes = pahsc->pahsc_BytesPerBuffer * past->past_NumUserBuffers; - if( numBytes < DSBSIZE_MIN ) - { - result = paBufferTooSmall; - goto error; - } - if( numBytes > DSBSIZE_MAX ) - { - result = paBufferTooBig; - goto error; - } - pahsc->pahsc_FramesPerDSBuffer = past->past_FramesPerUserBuffer * past->past_NumUserBuffers; - { - int msecLatency = (int) ((pahsc->pahsc_FramesPerDSBuffer * 1000) / past->past_SampleRate); - PRINT(("PortAudio on DirectSound - Latency = %d frames, %d msec\n", pahsc->pahsc_FramesPerDSBuffer, msecLatency )); - } - /* ------------------ OUTPUT */ - if( (past->past_OutputDeviceID >= 0) && (past->past_NumOutputChannels > 0) ) - { - DBUG(("PaHost_OpenStream: deviceID = 0x%x\n", past->past_OutputDeviceID)); - pad = Pa_GetInternalDevice( past->past_OutputDeviceID ); - hr = DirectSoundCreate( pad->pad_lpGUID, &dsw->dsw_pDirectSound, NULL ); - /* If this fails, then try each output device until we find one that works. */ - if( hr != DS_OK ) - { - int i; - ERR_RPT(("Creation of requested Audio Output device '%s' failed.\n", - ((pad->pad_lpGUID == NULL) ? "Default" : pad->pad_Info.name) )); - for( i=0; ipad_Info.maxOutputChannels >= past->past_NumOutputChannels ) - { - DBUG(("Try device '%s' instead.\n", pad->pad_Info.name )); - hr = DirectSoundCreate( pad->pad_lpGUID, &dsw->dsw_pDirectSound, NULL ); - if( hr == DS_OK ) - { - ERR_RPT(("Using device '%s' instead.\n", pad->pad_Info.name )); - break; - } - } - } - } - if( hr != DS_OK ) - { - ERR_RPT(("PortAudio: DirectSoundCreate() failed!\n")); - result = paHostError; - sPaHostError = hr; - goto error; - } - hr = DSW_InitOutputBuffer( dsw, - (unsigned long) (past->past_SampleRate + 0.5), - past->past_NumOutputChannels, numBytes ); - DBUG(("DSW_InitOutputBuffer() returns %x\n", hr)); - if( hr != DS_OK ) - { - result = paHostError; - sPaHostError = hr; - goto error; - } - past->past_FrameCount = pahsc->pahsc_DSoundWrapper.dsw_FramesWritten; - } -#if SUPPORT_AUDIO_CAPTURE - /* ------------------ INPUT */ - if( (past->past_InputDeviceID >= 0) && (past->past_NumInputChannels > 0) ) - { - pad = Pa_GetInternalDevice( past->past_InputDeviceID ); - hr = DirectSoundCaptureCreate( pad->pad_lpGUID, &dsw->dsw_pDirectSoundCapture, NULL ); - /* If this fails, then try each input device until we find one that works. */ - if( hr != DS_OK ) - { - int i; - ERR_RPT(("Creation of requested Audio Capture device '%s' failed.\n", - ((pad->pad_lpGUID == NULL) ? "Default" : pad->pad_Info.name) )); - for( i=0; ipad_Info.maxInputChannels >= past->past_NumInputChannels ) - { - PRINT(("Try device '%s' instead.\n", pad->pad_Info.name )); - hr = DirectSoundCaptureCreate( pad->pad_lpGUID, &dsw->dsw_pDirectSoundCapture, NULL ); - if( hr == DS_OK ) break; - } - } - } - if( hr != DS_OK ) - { - ERR_RPT(("PortAudio: DirectSoundCaptureCreate() failed!\n")); - result = paHostError; - sPaHostError = hr; - goto error; - } - hr = DSW_InitInputBuffer( dsw, - (unsigned long) (past->past_SampleRate + 0.5), - past->past_NumInputChannels, numBytes ); - DBUG(("DSW_InitInputBuffer() returns %x\n", hr)); - if( hr != DS_OK ) - { - ERR_RPT(("PortAudio: DSW_InitInputBuffer() returns %x\n", hr)); - result = paHostError; - sPaHostError = hr; - goto error; - } - } -#endif /* SUPPORT_AUDIO_CAPTURE */ - /* Calculate scalar used in CPULoad calculation. */ - { - LARGE_INTEGER frequency; - if( QueryPerformanceFrequency( &frequency ) == 0 ) - { - pahsc->pahsc_InverseTicksPerUserBuffer = 0.0; - } - else - { - pahsc->pahsc_InverseTicksPerUserBuffer = past->past_SampleRate / - ( (double)frequency.QuadPart * past->past_FramesPerUserBuffer ); - DBUG(("pahsc_InverseTicksPerUserBuffer = %g\n", pahsc->pahsc_InverseTicksPerUserBuffer )); - } - } - return result; -error: - PaHost_CloseStream( past ); - return result; -} -/*************************************************************************/ -PaError PaHost_StartOutput( internalPortAudioStream *past ) -{ - HRESULT hr; - PaHostSoundControl *pahsc; - PaError result = paNoError; - pahsc = (PaHostSoundControl *) past->past_DeviceData; - /* Give user callback a chance to pre-fill buffer. */ - result = Pa_TimeSlice( past ); - if( result != paNoError ) return result; // FIXME - what if finished? - hr = DSW_StartOutput( &pahsc->pahsc_DSoundWrapper ); - DBUG(("PaHost_StartOutput: DSW_StartOutput returned = 0x%X.\n", hr)); - if( hr != DS_OK ) - { - result = paHostError; - sPaHostError = hr; - goto error; - } -error: - return result; -} -/*************************************************************************/ -PaError PaHost_StartInput( internalPortAudioStream *past ) -{ - PaError result = paNoError; -#if SUPPORT_AUDIO_CAPTURE - HRESULT hr; - PaHostSoundControl *pahsc; - pahsc = (PaHostSoundControl *) past->past_DeviceData; - hr = DSW_StartInput( &pahsc->pahsc_DSoundWrapper ); - DBUG(("Pa_StartStream: DSW_StartInput returned = 0x%X.\n", hr)); - if( hr != DS_OK ) - { - result = paHostError; - sPaHostError = hr; - goto error; - } -error: -#endif /* SUPPORT_AUDIO_CAPTURE */ - return result; -} -/*************************************************************************/ -PaError PaHost_StartEngine( internalPortAudioStream *past ) -{ - PaHostSoundControl *pahsc; - PaError result = paNoError; - pahsc = (PaHostSoundControl *) past->past_DeviceData; - past->past_StopNow = 0; - past->past_StopSoon = 0; - past->past_IsActive = 1; - /* Create timer that will wake us up so we can fill the DSound buffer. */ - { - int msecPerBuffer; - int resolution; - int bufsPerInterrupt = past->past_NumUserBuffers/4; - if( bufsPerInterrupt < 1 ) bufsPerInterrupt = 1; - msecPerBuffer = 1000 * (bufsPerInterrupt * past->past_FramesPerUserBuffer) / (int) past->past_SampleRate; - if( msecPerBuffer < 10 ) msecPerBuffer = 10; - else if( msecPerBuffer > 100 ) msecPerBuffer = 100; - resolution = msecPerBuffer/4; - pahsc->pahsc_TimerID = timeSetEvent( msecPerBuffer, resolution, (LPTIMECALLBACK) Pa_TimerCallback, - (DWORD) past, TIME_PERIODIC ); - } - if( pahsc->pahsc_TimerID == 0 ) - { - past->past_IsActive = 0; - result = paHostError; - sPaHostError = 0; - goto error; - } -error: - return result; -} -/*************************************************************************/ -PaError PaHost_StopEngine( internalPortAudioStream *past, int abort ) -{ - int timeoutMsec; - PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; - if( pahsc == NULL ) return paNoError; - if( abort ) past->past_StopNow = 1; - past->past_StopSoon = 1; - /* Set timeout at 20% beyond maximum time we might wait. */ - timeoutMsec = (int) (1200.0 * pahsc->pahsc_FramesPerDSBuffer / past->past_SampleRate); - while( past->past_IsActive && (timeoutMsec > 0) ) - { - Sleep(10); - timeoutMsec -= 10; - } - if( pahsc->pahsc_TimerID != 0 ) - { - timeKillEvent(pahsc->pahsc_TimerID); /* Stop callback timer. */ - pahsc->pahsc_TimerID = 0; - } - return paNoError; -} -/*************************************************************************/ -PaError PaHost_StopInput( internalPortAudioStream *past, int abort ) -{ -#if SUPPORT_AUDIO_CAPTURE - HRESULT hr; - PaHostSoundControl *pahsc = (PaHostSoundControl *) past->past_DeviceData; - if( pahsc == NULL ) return paNoError; - (void) abort; - hr = DSW_StopInput( &pahsc->pahsc_DSoundWrapper ); - DBUG(("DSW_StopInput() result is %x\n", hr)); -#endif /* SUPPORT_AUDIO_CAPTURE */ - return paNoError; -} -/*************************************************************************/ -PaError PaHost_StopOutput( internalPortAudioStream *past, int abort ) -{ - HRESULT hr; - PaHostSoundControl *pahsc; - pahsc = (PaHostSoundControl *) past->past_DeviceData; - if( pahsc == NULL ) return paNoError; - (void) abort; - hr = DSW_StopOutput( &pahsc->pahsc_DSoundWrapper ); - DBUG(("DSW_StopOutput() result is %x\n", hr)); - return paNoError; -} -/*******************************************************************/ -PaError PaHost_CloseStream( internalPortAudioStream *past ) -{ - PaHostSoundControl *pahsc; - if( past == NULL ) return paBadStreamPtr; - pahsc = (PaHostSoundControl *) past->past_DeviceData; - if( pahsc == NULL ) return paNoError; - DSW_Term( &pahsc->pahsc_DSoundWrapper ); - if( pahsc->pahsc_NativeBuffer ) - { - PaHost_FreeFastMemory( pahsc->pahsc_NativeBuffer, pahsc->pahsc_BytesPerBuffer ); /* MEM */ - pahsc->pahsc_NativeBuffer = NULL; - } - PaHost_FreeFastMemory( pahsc, sizeof(PaHostSoundControl) ); /* MEM */ - past->past_DeviceData = NULL; - return paNoError; -} - -/* Set minimal latency based on whether NT or Win95. - * NT has higher latency. - */ -static int PaHost_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; -} - -/************************************************************************* -** 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") -int Pa_GetMinNumBuffers( int framesPerBuffer, double sampleRate ) -{ - char envbuf[PA_ENV_BUF_SIZE]; - DWORD hresult; - int minLatencyMsec = 0; - double msecPerBuffer = (1000.0 * framesPerBuffer) / sampleRate; - int minBuffers; - /* 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 = PaHost_GetMinSystemLatency(); -#if PA_USE_HIGH_LATENCY - PRINT(("PA - Minimum Latency set to %d msec!\n", minLatencyMsec )); -#endif - - } - minBuffers = (int) (1.0 + ((double)minLatencyMsec / msecPerBuffer)); - if( minBuffers < 2 ) minBuffers = 2; - return minBuffers; -} -/*************************************************************************/ -PaError PaHost_Term( void ) -{ - int i; - /* Free names allocated during enumeration. */ - for( i=0; ipast_DeviceData; - if( pahsc == NULL ) return paInternalError; - return (PaError) (past->past_IsActive); -} -/*************************************************************************/ -PaTimestamp Pa_StreamTime( PortAudioStream *stream ) -{ - DSoundWrapper *dsw; - internalPortAudioStream *past = (internalPortAudioStream *) stream; - PaHostSoundControl *pahsc; - if( past == NULL ) return paBadStreamPtr; - pahsc = (PaHostSoundControl *) past->past_DeviceData; - dsw = &pahsc->pahsc_DSoundWrapper; - return dsw->dsw_FramesPlayed; -} diff --git a/pa_win_ds/pa_win_ds.c b/pa_win_ds/pa_win_ds.c new file mode 100644 index 0000000..dfcc6e7 --- /dev/null +++ b/pa_win_ds/pa_win_ds.c @@ -0,0 +1,2178 @@ +/* + * $Id$ + * 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-2006 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. + * + * 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. + */ + +/** @file + + @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 check that CoInitialize() CoUninitialize() are always correctly + paired, even in error cases. + + @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 + + old TODOs from phil, need to work out if these have been done: + O- fix "patest_stop.c" +*/ + +#include +#include /* strlen() */ + +#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_win_ds_dynlink.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 +{ + GUID guid; + GUID *lpGUID; + double sampleRates[3]; +} PaWinDsDeviceInfo; + +typedef struct +{ + PaUtilHostApiRepresentation inheritedHostApiRep; + PaUtilStreamInterface callbackStreamInterface; + PaUtilStreamInterface blockingStreamInterface; + + PaUtilAllocationGroup *allocations; + + /* implementation specific data goes here */ + PaWinDsDeviceInfo *winDsDeviceInfos; + +} 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; +} DSDeviceNameAndGUID; + +typedef struct DSDeviceNameAndGUIDVector{ + PaUtilAllocationGroup *allocations; + PaError enumerationError; + + int count; + int free; + DSDeviceNameAndGUID *items; // Allocated using LocalAlloc() +} DSDeviceNameAndGUIDVector; + +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) );; + } + } + + 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->count; + --namesAndGUIDs->free; + + return TRUE; +} + + +/* + 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 ) +{ + PaUtilHostApiRepresentation *hostApi = &winDsHostApi->inheritedHostApiRep; + PaDeviceInfo *deviceInfo = hostApi->deviceInfos[hostApi->info.deviceCount]; + PaWinDsDeviceInfo *winDsDeviceInfo = &winDsHostApi->winDsDeviceInfos[hostApi->info.deviceCount]; + 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; + /* Mono or stereo device? */ + deviceInfo->maxOutputChannels = ( caps.dwFlags & DSCAPS_PRIMARYSTEREO ) ? 2 : 1; + + 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 ) +{ + PaUtilHostApiRepresentation *hostApi = &winDsHostApi->inheritedHostApiRep; + PaDeviceInfo *deviceInfo = hostApi->deviceInfos[hostApi->info.deviceCount]; + PaWinDsDeviceInfo *winDsDeviceInfo = &winDsHostApi->winDsDeviceInfos[hostApi->info.deviceCount]; + 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; + deviceInfo->maxOutputChannels = 0; + + 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; + DSDeviceNameAndGUIDVector inputNamesAndGUIDs, outputNamesAndGUIDs; + PaDeviceInfo *deviceInfoArray; + + HRESULT hr = CoInitialize(NULL); /** @todo: should uninitialize too */ + if( FAILED(hr) ){ + return paUnanticipatedHostError; + } + + /* initialise guid vectors so they can be safely deleted on error */ + inputNamesAndGUIDs.items = NULL; + outputNamesAndGUIDs.items = NULL; + + PaWinDs_InitializeDSoundEntryPoints(); + + winDsHostApi = (PaWinDsHostApiRepresentation*)PaUtil_AllocateMemory( sizeof(PaWinDsHostApiRepresentation) ); + if( !winDsHostApi ) + { + result = paInsufficientMemory; + goto error; + } + + 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( &inputNamesAndGUIDs, winDsHostApi->allocations ); + if( result != paNoError ) + goto error; + + result = InitializeDSDeviceNameAndGUIDVector( &outputNamesAndGUIDs, winDsHostApi->allocations ); + if( result != paNoError ) + goto error; + + paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerate( (LPDSENUMCALLBACK)CollectGUIDsProc, (void *)&inputNamesAndGUIDs ); + + paWinDsDSoundEntryPoints.DirectSoundEnumerate( (LPDSENUMCALLBACK)CollectGUIDsProc, (void *)&outputNamesAndGUIDs ); + + if( inputNamesAndGUIDs.enumerationError != paNoError ) + { + result = inputNamesAndGUIDs.enumerationError; + goto error; + } + + if( outputNamesAndGUIDs.enumerationError != paNoError ) + { + result = outputNamesAndGUIDs.enumerationError; + goto error; + } + + deviceCount = inputNamesAndGUIDs.count + outputNamesAndGUIDs.count; + + 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 = (PaDeviceInfo*)PaUtil_GroupAllocateMemory( + winDsHostApi->allocations, sizeof(PaDeviceInfo) * deviceCount ); + if( !deviceInfoArray ) + { + result = paInsufficientMemory; + goto error; + } + + /* allocate all DSound specific info structs in a contiguous block */ + winDsHostApi->winDsDeviceInfos = (PaWinDsDeviceInfo*)PaUtil_GroupAllocateMemory( + winDsHostApi->allocations, sizeof(PaWinDsDeviceInfo) * deviceCount ); + if( !winDsHostApi->winDsDeviceInfos ) + { + result = paInsufficientMemory; + goto error; + } + + for( i=0; i < deviceCount; ++i ) + { + PaDeviceInfo *deviceInfo = &deviceInfoArray[i]; + deviceInfo->structVersion = 2; + deviceInfo->hostApi = hostApiIndex; + deviceInfo->name = 0; + (*hostApi)->deviceInfos[i] = deviceInfo; + } + + for( i=0; i< inputNamesAndGUIDs.count; ++i ) + { + result = AddInputDeviceInfoFromDirectSoundCapture( winDsHostApi, + inputNamesAndGUIDs.items[i].name, + inputNamesAndGUIDs.items[i].lpGUID ); + if( result != paNoError ) + goto error; + } + + for( i=0; i< outputNamesAndGUIDs.count; ++i ) + { + result = AddOutputDeviceInfoFromDirectSound( winDsHostApi, + outputNamesAndGUIDs.items[i].name, + outputNamesAndGUIDs.items[i].lpGUID ); + if( result != paNoError ) + goto error; + } + } + + result = TerminateDSDeviceNameAndGUIDVector( &inputNamesAndGUIDs ); + if( result != paNoError ) + goto error; + + result = TerminateDSDeviceNameAndGUIDVector( &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( &inputNamesAndGUIDs ); + TerminateDSDeviceNameAndGUIDVector( &outputNamesAndGUIDs ); + + return result; +} + + +/***********************************************************************************/ +static void Terminate( struct PaUtilHostApiRepresentation *hostApi ) +{ + PaWinDsHostApiRepresentation *winDsHostApi = (PaWinDsHostApiRepresentation*)hostApi; + + /* + 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(); + + 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 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; + + /* 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; + } + + /* + 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, unsigned long nFrameRate, WORD nChannels, int bytesPerBuffer ) +{ + DSCBUFFERDESC captureDesc; + WAVEFORMATEX wfFormat; + HRESULT result; + + stream->bytesPerInputFrame = nChannels * sizeof(short); + + // Define the buffer format + wfFormat.wFormatTag = WAVE_FORMAT_PCM; + wfFormat.nChannels = nChannels; + wfFormat.nSamplesPerSec = nFrameRate; + wfFormat.wBitsPerSample = 8 * sizeof(short); + wfFormat.nBlockAlign = (WORD)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8)); + wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign; + wfFormat.cbSize = 0; /* No extended format info. */ + stream->inputSize = bytesPerBuffer; + // ---------------------------------------------------------------------- + // Setup the secondary buffer description + ZeroMemory(&captureDesc, sizeof(DSCBUFFERDESC)); + captureDesc.dwSize = sizeof(DSCBUFFERDESC); + captureDesc.dwFlags = 0; + captureDesc.dwBufferBytes = bytesPerBuffer; + captureDesc.lpwfxFormat = &wfFormat; + // Create the capture buffer + 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, unsigned long nFrameRate, WORD nChannels, int bytesPerBuffer ) +{ + DWORD dwDataLen; + DWORD playCursor; + HRESULT result; + LPDIRECTSOUNDBUFFER pPrimaryBuffer; + HWND hWnd; + HRESULT hr; + WAVEFORMATEX wfFormat; + DSBUFFERDESC primaryDesc; + DSBUFFERDESC secondaryDesc; + unsigned char* pDSBuffData; + LARGE_INTEGER counterFrequency; + + stream->outputBufferSizeBytes = bytesPerBuffer; + stream->outputIsRunning = FALSE; + stream->outputUnderflowCount = 0; + stream->dsw_framesWritten = 0; + stream->bytesPerOutputFrame = nChannels * sizeof(short); + + // 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; + // Define the buffer format + wfFormat.wFormatTag = WAVE_FORMAT_PCM; + wfFormat.nChannels = nChannels; + wfFormat.nSamplesPerSec = nFrameRate; + wfFormat.wBitsPerSample = 8 * sizeof(short); + wfFormat.nBlockAlign = (WORD)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8)); + wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign; + wfFormat.cbSize = 0; /* No extended format info. */ + // Set the primary buffer's format + if((result = IDirectSoundBuffer_SetFormat( pPrimaryBuffer, &wfFormat)) != 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 = &wfFormat; + // 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 * sizeof(short)); + 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; + int inputChannelCount, outputChannelCount; + PaSampleFormat inputSampleFormat, outputSampleFormat; + PaSampleFormat hostInputSampleFormat, hostOutputSampleFormat; + unsigned long suggestedInputLatencyFrames, suggestedOutputLatencyFrames; + + if( inputParameters ) + { + 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( inputChannelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels ) + return paInvalidChannelCount; + + /* validate hostApiSpecificStreamInfo */ + if( inputParameters->hostApiSpecificStreamInfo ) + return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */ + } + else + { + inputChannelCount = 0; + suggestedInputLatencyFrames = 0; + } + + + if( outputParameters ) + { + 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 inputChannelCount */ + if( outputChannelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels ) + return paInvalidChannelCount; + + /* validate hostApiSpecificStreamInfo */ + if( outputParameters->hostApiSpecificStreamInfo ) + return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */ + } + else + { + outputChannelCount = 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 */ + hostInputSampleFormat = + PaUtil_SelectClosestAvailableFormat( paInt16 /* native formats */, inputParameters->sampleFormat ); + } + + if( outputParameters ) + { + /* IMPLEMENT ME - establish which host formats are available */ + hostOutputSampleFormat = + PaUtil_SelectClosestAvailableFormat( paInt16 /* native formats */, outputParameters->sampleFormat ); + } + + 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)); + */ + + bytesPerDirectSoundBuffer = stream->framesPerDSBuffer * outputParameters->channelCount * sizeof(short); + if( bytesPerDirectSoundBuffer < DSBSIZE_MIN ) + { + result = paBufferTooSmall; + goto error; + } + else if( bytesPerDirectSoundBuffer > DSBSIZE_MAX ) + { + result = paBufferTooBig; + goto error; + } + + + hr = paWinDsDSoundEntryPoints.DirectSoundCreate( winDsHostApi->winDsDeviceInfos[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, + (unsigned long) (sampleRate + 0.5), + (WORD)outputParameters->channelCount, bytesPerDirectSoundBuffer ); + 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)); + */ + + bytesPerDirectSoundBuffer = stream->framesPerDSBuffer * inputParameters->channelCount * sizeof(short); + if( bytesPerDirectSoundBuffer < DSBSIZE_MIN ) + { + result = paBufferTooSmall; + goto error; + } + else if( bytesPerDirectSoundBuffer > DSBSIZE_MAX ) + { + result = paBufferTooBig; + goto error; + } + + hr = paWinDsDSoundEntryPoints.DirectSoundCaptureCreate( winDsHostApi->winDsDeviceInfos[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, + (unsigned long) (sampleRate + 0.5), + (WORD)inputParameters->channelCount, bytesPerDirectSoundBuffer ); + 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; +} + + + diff --git a/pa_win_ds/pa_win_ds_dynlink.c b/pa_win_ds/pa_win_ds_dynlink.c new file mode 100644 index 0000000..ef8a41c --- /dev/null +++ b/pa_win_ds/pa_win_ds_dynlink.c @@ -0,0 +1,121 @@ +#include "pa_win_ds_dynlink.h" + + +PaWinDsDSoundEntryPoints paWinDsDSoundEntryPoints = { 0, 0, 0, 0, 0, 0, 0 }; + + +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.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; + } +} \ No newline at end of file diff --git a/pa_win_ds/pa_win_ds_dynlink.h b/pa_win_ds/pa_win_ds_dynlink.h new file mode 100644 index 0000000..281287b --- /dev/null +++ b/pa_win_ds/pa_win_ds_dynlink.h @@ -0,0 +1,82 @@ +#ifndef INCLUDED_PA_DSOUND_DYNLINK_H +#define INCLUDED_PA_DSOUND_DYNLINK_H +/* + * 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. + * + * 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. + * + */ + +/* 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 *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 */ diff --git a/pa_win_ds/portaudio.def b/pa_win_ds/portaudio.def deleted file mode 100644 index 8012b99..0000000 --- a/pa_win_ds/portaudio.def +++ /dev/null @@ -1,28 +0,0 @@ -LIBRARY PortAudio -DESCRIPTION 'PortAudio Portable interface to audio HW' - -EXPORTS - ; Explicit exports can go here - Pa_Initialize @1 - Pa_Terminate @2 - Pa_GetHostError @3 - Pa_GetErrorText @4 - Pa_CountDevices @5 - Pa_GetDefaultInputDeviceID @6 - Pa_GetDefaultOutputDeviceID @7 - Pa_GetDeviceInfo @8 - Pa_OpenStream @9 - Pa_OpenDefaultStream @10 - Pa_CloseStream @11 - Pa_StartStream @12 - Pa_StopStream @13 - Pa_StreamActive @14 - Pa_StreamTime @15 - Pa_GetCPULoad @16 - Pa_GetMinNumBuffers @17 - Pa_Sleep @18 - - ;123456789012345678901234567890123456 - ;000000000111111111122222222223333333 - - diff --git a/pa_win_wasapi/pa_win_wasapi.cpp b/pa_win_wasapi/pa_win_wasapi.cpp new file mode 100644 index 0000000..34b8cfa --- /dev/null +++ b/pa_win_wasapi/pa_win_wasapi.cpp @@ -0,0 +1,1770 @@ +/* + * Portable Audio I/O Library WASAPI implementation + * Copyright (c) 2006 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. + * + * 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. + */ + +/** @file + @brief WASAPI implementation of support for a host API. + + @note This file is provided as a starting point for implementing support for + a new host API. IMPLEMENT ME comments are used to indicate functionality + which much be customised for each implementation. +*/ + + + +//these headers are only in Windows SDK CTP Feb 2006 and only work in VC 2005! +#if _MSC_VER >= 1400 +#include +#include //must be before other Wasapi headers +#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" + + + +/* 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 +//only in Windows SDK CTP Feb 2006 and only work in VC 2005! +#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; + + //output + PaWinWasapiSubStream out; + IAudioRenderClient *rclient; + + + bool running; + bool closeRequest; + + DWORD dwThreadId; + HANDLE hThread; + + 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_NO_SINGLE_PROCESS :text ="AUDCLNT_E_NO_SINGLE_PROCESS"; 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; + 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; + + if (!setupAVRT()){ + PRINT(("Windows WASAPI : No AVRT! (not VISTA?)")); + goto error; + } + + 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 ){ + + 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; + } + + wcstombs(deviceName, value.pwszVal,MAX_STR_LEN-1); //todo proper size + + 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_FAILED_JUMP(hResult, 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 *)∈ + + 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 *)∈ + + 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 &wav, + 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(&wav,0,sizeof(WAVEFORMATEXTENSIBLE)); + + WAVEFORMATEX *old = (WAVEFORMATEX *)&wav; + old->nChannels = (WORD)params->channelCount; + old->nSamplesPerSec = (DWORD)sampleRate; + old->wBitsPerSample = bytesPerSample*8; + old->nAvgBytesPerSec = 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) + wav.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT; + else + wav.SubFormat = KSDATAFORMAT_SUBTYPE_PCM; + + wav.Samples.wValidBitsPerSample = old->wBitsPerSample; //no extra padding! + + switch(params->channelCount){ + case 1: wav.dwChannelMask = SPEAKER_FRONT_CENTER; break; + case 2: wav.dwChannelMask = 0x1 | 0x2; break; + case 4: wav.dwChannelMask = 0x1 | 0x2 | 0x10 | 0x20; break; + case 6: wav.dwChannelMask = 0x1 | 0x2 | 0x4 | 0x8 | 0x10 | 0x20; break; + case 8: wav.dwChannelMask = 0x1 | 0x2 | 0x4 | 0x8 | 0x10 | 0x20 | 0x40 | 0x80; break; + default: wav.dwChannelMask = 0; break; + } + } + + return paNoError; +} + + +enum PaWasapiFormatAnswer {PWFA_OK,PWFA_NO,PWFA_SUGGESTED}; + + +static PaWasapiFormatAnswer +IsFormatSupportedInternal(IAudioClient * myClient, WAVEFORMATEXTENSIBLE &wavex){ + + PaWasapiFormatAnswer answer = PWFA_OK; + + WAVEFORMATEX *closestMatch=0; + HRESULT hResult = myClient->IsFormatSupported( + //AUDCLNT_SHAREMODE_EXCLUSIVE, + AUDCLNT_SHAREMODE_SHARED, + (WAVEFORMATEX*)&wavex,&closestMatch); + + if (hResult == S_OK) + answer = PWFA_OK; + else if (closestMatch){ + WAVEFORMATEXTENSIBLE* ext = (WAVEFORMATEXTENSIBLE*)closestMatch; + + if (closestMatch->wFormatTag == WAVE_FORMAT_EXTENSIBLE) + memcpy(&wavex,closestMatch,sizeof(WAVEFORMATEXTENSIBLE)); + else + memcpy(&wavex,closestMatch,sizeof(WAVEFORMATEX)); + + CoTaskMemFree(closestMatch); + answer = PWFA_SUGGESTED; + + }else if (hResult != S_OK){ + logAUDCLNT_E(hResult); + answer = PWFA_NO; + } + + 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; + + WAVEFORMATEXTENSIBLE wavex; + waveformatFromParams(wavex,inputParameters,sampleRate); + + 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; + } + + PaWasapiFormatAnswer answer = IsFormatSupportedInternal(myClient,wavex); + myClient->Release(); + + switch (answer){ + case PWFA_OK: break; + case PWFA_NO: return paSampleFormatNotSupported; + case PWFA_SUGGESTED: + { + PRINT(("Suggested format:")); + LogWAVEFORMATEXTENSIBLE(wavex); + if (wavex.Format.nSamplesPerSec == (DWORD)sampleRate){ + //no problem its a format issue only + } + else{ + return paInvalidSampleRate; + } + } + } + + + } + 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; + + WAVEFORMATEXTENSIBLE wavex; + waveformatFromParams(wavex,outputParameters,sampleRate); + + 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; + } + + PaWasapiFormatAnswer answer = IsFormatSupportedInternal(myClient,wavex); + myClient->Release(); + + switch (answer){ + case PWFA_OK: break; + case PWFA_NO: return paSampleFormatNotSupported; + case PWFA_SUGGESTED: + { + PRINT(("Suggested format:")); + LogWAVEFORMATEXTENSIBLE(wavex); + if (wavex.Format.nSamplesPerSec == (DWORD)sampleRate){ + //no problem its a format issue only + } + else{ + return paInvalidSampleRate; + } + } + } + + + } + 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; + + waveformatFromParams(stream->in.wavex,outputParameters,sampleRate); + + PaWasapiFormatAnswer answer = IsFormatSupportedInternal(stream->in.client, + stream->in.wavex); + + switch (answer){ + case PWFA_OK: break; + case PWFA_NO: return paSampleFormatNotSupported; + case PWFA_SUGGESTED: + { + PRINT(("Suggested format:")); + LogWAVEFORMATEXTENSIBLE(stream->in.wavex); + if (stream->in.wavex.Format.nSamplesPerSec == (DWORD)sampleRate){ + //no problem its a format issue only + } + else{ + return paInvalidSampleRate; + } + } + } + + //stream->out.period = info.DefaultDevicePeriod; + stream->in.period = info.MinimumDevicePeriod; + + hResult = stream->in.client->Initialize( + AUDCLNT_SHAREMODE_SHARED, + //AUDCLNT_SHAREMODE_EXCLUSIVE, + 0, //no flags + stream->in.period*3, //tripple buffer + 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; + + waveformatFromParams(stream->out.wavex,outputParameters,sampleRate); + + PaWasapiFormatAnswer answer = IsFormatSupportedInternal(stream->out.client, + stream->out.wavex); + + switch (answer){ + case PWFA_OK: break; + case PWFA_NO: return paSampleFormatNotSupported; + case PWFA_SUGGESTED: + { + PRINT(("Suggested format:")); + LogWAVEFORMATEXTENSIBLE(stream->out.wavex); + if (stream->out.wavex.Format.nSamplesPerSec == (DWORD)sampleRate){ + //no problem its a format issue only + } + else{ + return paInvalidSampleRate; + } + } + } + + //stream->out.period = info.DefaultDevicePeriod; + stream->out.period = info.MinimumDevicePeriod; + + hResult = stream->out.client->Initialize( + AUDCLNT_SHAREMODE_SHARED, + //AUDCLNT_SHAREMODE_EXCLUSIVE, + 0, //no flags + stream->out.period*3, //tripple buffer + 0,//stream->out.period, + (WAVEFORMATEX*)&stream->out.wavex, + &stream->session + ); + + if (hResult != S_OK){ + logAUDCLNT_E(hResult); + 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 = (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); + CloseHandle(stream->hThread); + + PaUtil_TerminateBufferProcessor( &stream->bufferProcessor ); + PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation ); + PaUtil_FreeMemory( stream ); + + return result; +} + +VOID 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 + (LPTHREAD_START_ROUTINE) 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 +ProcThread(void *param){ + + HRESULT hResult; + + 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")); + } + + + PaWinWasapiStream *stream = (PaWinWasapiStream*)param; + + HANDLE context; + GUID threadOrderGUID; + memset(&threadOrderGUID,0,sizeof(GUID)); + LARGE_INTEGER large; + + large.QuadPart = stream->out.period; + + BOOL ok = pAvRtCreateThreadOrderingGroup(&context, + &large, + &threadOrderGUID, +#ifdef _DEBUG + 0 //THREAD_ORDER_GROUP_INFINITE_TIMEOUT +#else + 0 //default is 5 times the 2nd param +#endif + //TEXT("Audio") + ); + + if (!ok){ + PRINT(("AvRtCreateThreadOrderingGroup failed!\n")); + } + + //debug + { + HANDLE hh = GetCurrentThread(); + int currprio = GetThreadPriority(hh); + DWORD currclass = GetPriorityClass(GetCurrentProcess()); + PRINT(("currprio 0x%X currclass 0x%X\n",currprio,currclass)); + } + + + //fill up initial buffer latency?? + + if (stream->out.client){ + hResult = stream->out.client->Start(); + if (hResult != S_OK) + logAUDCLNT_E(hResult); + } + + stream->running = true; + + while(!stream->closeRequest){ + BOOL answer = pAvRtWaitOnThreadOrderingGroup(context); + if (!answer){ + PRINT(("AvRtWaitOnThreadOrderingGroup failed\n")); + } + + unsigned long usingBS = stream->out.framesPerHostCallback; + + UINT32 padding=0; + hResult = stream->out.client->GetCurrentPadding(&padding); + logAUDCLNT_E(hResult); + + //buffer full dont pursue + if (padding == stream->out.bufferSize) + continue; + + //if something is already inside + if (padding > 0){ + usingBS = stream->out.bufferSize-padding; + if (usingBS > stream->out.framesPerHostCallback){ + //PRINT(("underflow! %d\n",usingBS)); + } + else if (usingBS < stream->out.framesPerHostCallback){ + //PRINT(("overflow! %d\n",usingBS)); + } + } + else + usingBS = stream->out.framesPerHostCallback; + + + BYTE*indata =0; + BYTE*outdata=0; + + hResult = stream->rclient->GetBuffer(usingBS,&outdata); + + if (hResult != S_OK || !outdata) { + logAUDCLNT_E(hResult); + continue; + } + + WaspiHostProcessingLoop(indata, usingBS + ,outdata,usingBS,stream); + + hResult = stream->rclient->ReleaseBuffer(usingBS,0); + if (hResult != S_OK) + logAUDCLNT_E(hResult); + + } + + + BOOL bRes = pAvRtDeleteThreadOrderingGroup(context); + if (!bRes){ + PRINT(("AvRtDeleteThreadOrderingGroup failure\n")); + } + + stream->closeRequest = false; +} + + + + +#endif //VC 2005 \ No newline at end of file diff --git a/pa_win_wdmks/pa_win_wdmks.c b/pa_win_wdmks/pa_win_wdmks.c new file mode 100644 index 0000000..34d0ee6 --- /dev/null +++ b/pa_win_wdmks/pa_win_wdmks.c @@ -0,0 +1,3269 @@ +/* + * $Id$ + * 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. + * + * 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. + */ + +/** @file + @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 +#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 + */ +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 diff --git a/pa_win_wdmks/readme.txt b/pa_win_wdmks/readme.txt new file mode 100644 index 0000000..1a381fe --- /dev/null +++ b/pa_win_wdmks/readme.txt @@ -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 diff --git a/pa_win_wmme/Makefile.cygwin b/pa_win_wmme/Makefile.cygwin deleted file mode 100644 index 5cb4ace..0000000 --- a/pa_win_wmme/Makefile.cygwin +++ /dev/null @@ -1,34 +0,0 @@ - -# Makefile for PortAudio on cygwin -# Contributed by Bill Eldridge on 6/13/2001 - -ARCH= pa_win_wmme - -TESTS:= $(wildcard pa_tests/pa*.c pa_tests/debug*.c) - -.c.o: - -gcc -c -I./pa_common $< -o $*.o - -gcc $*.o -o $*.exe -L/usr/local/lib -L$(ARCH) -lportaudio.dll -lwinmm - -all: sharedlib tests - -sharedlib: ./pa_common/pa_lib.c - gcc -c -I./pa_common pa_common/pa_lib.c -o pa_common/pa_lib.o - gcc -c -I./pa_common pa_win_wmme/pa_win_wmme.c -o pa_win_wmme/pa_win_wmme.o - dlltool --export-all --output-def pa_win_wmme/pa_lib.def pa_common/pa_lib.o pa_win_wmme/pa_win_wmme.o - gcc -shared -Wl,--enable-auto-image-base -o pa_win_wmme/portaudio.dll -Wl,--out-implib=pa_win_wmme/libportaudio.dll.a pa_win_wmme/pa_lib.def pa_common/pa_lib.o pa_win_wmme/pa_win_wmme.o -L/usr/lib/w32api -lwinmm - cp pa_win_wmme/portaudio.dll /usr/local/bin - -tests: $(TESTS:.c=.o) - -sine: - gcc -c -I./pa_common pa_tests/patest_sine.c -o pa_tests/patest_sine.o - gcc pa_tests/patest_sine.o -o pa_tests/patest_sine.exe -L/usr/local/lib -lportaudio.dll -lwinmm - -clean: - -rm ./pa_tests/*.exe - -nothing: - gcc pa_tests/patest_sine.o -L/usr/lib/w32api -L./pa_win_wmme -lportaudio.dll -lwinmm - - diff --git a/pa_win_wmme/pa_win_wmme.c b/pa_win_wmme/pa_win_wmme.c index ba7ca62..7167c08 100644 --- a/pa_win_wmme/pa_win_wmme.c +++ b/pa_win_wmme/pa_win_wmme.c @@ -1,15 +1,15 @@ /* * $Id$ * pa_win_wmme.c - * Implementation of PortAudio for Windows MultiMedia Extensions (WMME) - * + * Implementation of PortAudio for Windows MultiMedia Extensions (WMME) + * * PortAudio Portable Real-Time Audio Library * Latest Version at: http://www.portaudio.com * * Authors: Ross Bencina and Phil Burk * Copyright (c) 1999-2000 Ross Bencina and Phil Burk * - * Permission is hereby granted, free of charge, to any person obtainingF + * 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, @@ -33,9 +33,6 @@ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ -/* - All memory allocations and frees are marked with MEM for quick review. -*/ /* Modification History: PLB = Phil Burk @@ -44,7 +41,7 @@ PLB20010402 - sDevicePtrs now allocates based on sizeof(pointer) PLB20010413 - check for excessive numbers of channels PLB20010422 - apply Mike Berry's changes for CodeWarrior on PC - including condition including of memory.h, + including conditional inclusion of memory.h, and explicit typecasting on memory allocation PLB20010802 - use GlobalAlloc for sDevicesPtr instead of PaHost_AllocFastMemory PLB20010816 - pass process instead of thread to SetPriorityClass() @@ -54,6 +51,53 @@ RDB20020411 - various renaming cleanups, factored streamData alloc and cpu usage init RDB20020417 - stopped counting WAVE_MAPPER when there were no real devices refactoring, renaming and fixed a few edge case bugs + RDB20020531 - converted to V19 framework + ** NOTE maintanance history is now stored in CVS ** +*/ + +/** @file + + @todo Fix buffer catch up code, can sometimes get stuck (perhaps fixed now, + needs to be reviewed and tested.) + + @todo implement paInputUnderflow, paOutputOverflow streamCallback statusFlags, paNeverDropInput. + + @todo BUG: PA_MME_SET_LAST_WAVEIN/OUT_ERROR is used in functions which may + be called asynchronously from the callback thread. this is bad. + + @todo implement inputBufferAdcTime in callback thread + + @todo review/fix error recovery and cleanup in marked functions + + @todo implement timeInfo for stream priming + + @todo handle the case where the callback returns paAbort or paComplete during stream priming. + + @todo review input overflow and output underflow handling in ReadStream and WriteStream + +Non-critical stuff for the future: + + @todo Investigate supporting host buffer formats > 16 bits + + @todo define UNICODE and _UNICODE in the project settings and see what breaks + +*/ + +/* + How it works: + + For both callback and blocking read/write streams we open the MME devices + in CALLBACK_EVENT mode. In this mode, MME signals an Event object whenever + it has finished with a buffer (either filled it for input, or played it + for output). Where necessary we block waiting for Event objects using + WaitMultipleObjects(). + + When implementing a PA callback stream, we set up a high priority thread + which waits on the MME buffer Events and drains/fills the buffers when + they are ready. + + When implementing a PA blocking read/write stream, we simply wait on these + Events (when necessary) inside the ReadStream() and WriteStream() functions. */ #include @@ -62,476 +106,266 @@ #include #include #include +#include /* PLB20010422 - "memory.h" doesn't work on CodeWarrior for PC. Thanks Mike Berry for the mod. */ #ifndef __MWERKS__ #include #include #endif /* __MWERKS__ */ + #include "portaudio.h" -#include "pa_host.h" #include "pa_trace.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" -/************************************************* Constants ********/ -#define PA_TRACK_MEMORY (0) +#include "pa_win_wmme.h" -#define PA_USE_TIMER_CALLBACK (0) /* Select between two options for background task. 0=thread, 1=timer */ -/* Switches for debugging. */ -#define PA_SIMULATE_UNDERFLOW (0) /* Set to one to force an underflow of the output buffer. */ +#if (defined(WIN32) && (defined(_MSC_VER) && (_MSC_VER >= 1200))) /* MSC version 6 and above */ +#pragma comment(lib, "winmm.lib") +#endif + +/* + provided in newer platform sdks + */ +#ifndef DWORD_PTR +#define DWORD_PTR DWORD +#endif -/* To trace program, enable TRACE_REALTIME_EVENTS in pa_trace.h */ -#define PA_TRACE_RUN (0) -#define PA_TRACE_START_STOP (1) +/************************************************* Constants ********/ -#define PA_USE_HIGH_LATENCY (0) /* For debugging glitches. */ +#define PA_MME_USE_HIGH_DEFAULT_LATENCY_ (0) /* For debugging glitches. */ -#if PA_USE_HIGH_LATENCY - #define PA_MIN_MSEC_PER_HOST_BUFFER (100) - #define PA_MAX_MSEC_PER_HOST_BUFFER (300) /* Do not exceed unless user buffer exceeds */ - #define PA_MIN_NUM_HOST_BUFFERS (4) - #define PA_MAX_NUM_HOST_BUFFERS (16) /* OK to exceed if necessary */ - #define PA_WIN_9X_LATENCY (400) +#if PA_MME_USE_HIGH_DEFAULT_LATENCY_ + #define PA_MME_WIN_9X_DEFAULT_LATENCY_ (0.4) + #define PA_MME_MIN_HOST_OUTPUT_BUFFER_COUNT_ (4) + #define PA_MME_MIN_HOST_INPUT_BUFFER_COUNT_FULL_DUPLEX_ (4) + #define PA_MME_MIN_HOST_INPUT_BUFFER_COUNT_HALF_DUPLEX_ (4) + #define PA_MME_MIN_HOST_BUFFER_FRAMES_WHEN_UNSPECIFIED_ (16) + #define PA_MME_MAX_HOST_BUFFER_SECS_ (0.3) /* Do not exceed unless user buffer exceeds */ + #define PA_MME_MAX_HOST_BUFFER_BYTES_ (32 * 1024) /* Has precedence over PA_MME_MAX_HOST_BUFFER_SECS_, some drivers are known to crash with buffer sizes > 32k */ #else - #define PA_MIN_MSEC_PER_HOST_BUFFER (10) - #define PA_MAX_MSEC_PER_HOST_BUFFER (100) /* Do not exceed unless user buffer exceeds */ - #define PA_MIN_NUM_HOST_BUFFERS (3) - #define PA_MAX_NUM_HOST_BUFFERS (16) /* OK to exceed if necessary */ - #define PA_WIN_9X_LATENCY (200) + #define PA_MME_WIN_9X_DEFAULT_LATENCY_ (0.2) + #define PA_MME_MIN_HOST_OUTPUT_BUFFER_COUNT_ (2) + #define PA_MME_MIN_HOST_INPUT_BUFFER_COUNT_FULL_DUPLEX_ (3) + #define PA_MME_MIN_HOST_INPUT_BUFFER_COUNT_HALF_DUPLEX_ (2) + #define PA_MME_MIN_HOST_BUFFER_FRAMES_WHEN_UNSPECIFIED_ (16) + #define PA_MME_MAX_HOST_BUFFER_SECS_ (0.1) /* Do not exceed unless user buffer exceeds */ + #define PA_MME_MAX_HOST_BUFFER_BYTES_ (32 * 1024) /* Has precedence over PA_MME_MAX_HOST_BUFFER_SECS_, some drivers are known to crash with buffer sizes > 32k */ #endif -#define MIN_TIMEOUT_MSEC (1000) -/* -** Use higher latency for NT because it is even worse at real-time -** operation than Win9x. +/* Use higher latency for NT because it is even worse at real-time + operation than Win9x. */ -#define PA_WIN_NT_LATENCY (PA_WIN_9X_LATENCY * 2) -#define PA_WIN_WDM_LATENCY (PA_WIN_9X_LATENCY) +#define PA_MME_WIN_NT_DEFAULT_LATENCY_ (PA_MME_WIN_9X_DEFAULT_LATENCY_ * 2) +#define PA_MME_WIN_WDM_DEFAULT_LATENCY_ (PA_MME_WIN_9X_DEFAULT_LATENCY_) -#if PA_SIMULATE_UNDERFLOW -static gUnderCallbackCounter = 0; -#define UNDER_SLEEP_AT (40) -#define UNDER_SLEEP_FOR (500) -#endif -#define PRINT(x) { printf x; fflush(stdout); } -#define ERR_RPT(x) PRINT(x) -#define DBUG(x) /* PRINT(x) /**/ -#define DBUGX(x) /* PRINT(x) */ -/************************************************* Definitions ********/ -/************************************************************** - * Structure for internal host specific stream data. - * This is allocated on a per stream basis. - */ -typedef struct PaWMMEStreamData -{ - /* Input -------------- */ - HWAVEIN hWaveIn; - WAVEHDR *inputBuffers; - int currentInputBuffer; - int bytesPerHostInputBuffer; - int bytesPerUserInputBuffer; /* native buffer size in bytes */ - /* Output -------------- */ - HWAVEOUT hWaveOut; - WAVEHDR *outputBuffers; - int currentOutputBuffer; - int bytesPerHostOutputBuffer; - int bytesPerUserOutputBuffer; /* native buffer size in bytes */ - /* Run Time -------------- */ - PaTimestamp framesPlayed; - long lastPosition; /* used to track frames played. */ - /* For measuring CPU utilization. */ - LARGE_INTEGER entryCount; - double inverseTicksPerHostBuffer; - /* Init Time -------------- */ - int numHostBuffers; - int framesPerHostBuffer; - int userBuffersPerHostBuffer; - CRITICAL_SECTION streamLock; /* Mutext to prevent threads from colliding. */ - INT streamLockInited; -#if PA_USE_TIMER_CALLBACK - BOOL ifInsideCallback; /* Test for reentrancy. */ - MMRESULT timerID; -#else - HANDLE abortEvent; - int abortEventInited; - HANDLE bufferEvent; - int bufferEventInited; - HANDLE engineThread; - DWORD engineThreadID; -#endif -} -PaWMMEStreamData; -/************************************************* Shared Data ********/ -/* FIXME - put Mutex around this shared data. */ -static int sNumInputDevices = 0; -static int sNumOutputDevices = 0; -static int sNumDevices = 0; -static PaDeviceInfo **sDevicePtrs = NULL; -static int sDefaultInputDeviceID = paNoDevice; -static int sDefaultOutputDeviceID = paNoDevice; -static int sPaHostError = 0; -static const char sMapperSuffixInput[] = " - Input"; -static const char sMapperSuffixOutput[] = " - Output"; - -#if PA_TRACK_MEMORY -static int sNumAllocations = 0; -#endif +#define PA_MME_MIN_TIMEOUT_MSEC_ (1000) -/************************************************* Macros ********/ -/* Convert external PA ID to an internal ID that includes WAVE_MAPPER */ -#define PaDeviceIdToWinId(id) (((id) < sNumInputDevices) ? (id - 1) : (id - sNumInputDevices - 1)) -/************************************************* Prototypes **********/ +static const char constInputMapperSuffix_[] = " - Input"; +static const char constOutputMapperSuffix_[] = " - Output"; -void Pa_InitializeNumDevices( void ); -PaError Pa_AllocateDevicePtrs( void ); +/********************************************************************/ -static void CALLBACK Pa_TimerCallback(UINT uID, UINT uMsg, - DWORD dwUser, DWORD dw1, DWORD dw2); -PaError PaHost_GetTotalBufferFrames( internalPortAudioStream *past ); -static PaError PaHost_UpdateStreamTime( PaWMMEStreamData *wmmeStreamData ); -static PaError PaHost_BackgroundManager( internalPortAudioStream *past ); +typedef struct PaWinMmeStream PaWinMmeStream; /* forward declaration */ -static void *PaHost_AllocateTrackedMemory( long numBytes ); -static void PaHost_FreeTrackedMemory( void *addr ); +/* prototypes for functions declared in this file */ -/*******************************************************************/ -static PaError PaHost_AllocateWMMEStreamData( internalPortAudioStream *stream ) +#ifdef __cplusplus +extern "C" { - PaError result = paNoError; - PaWMMEStreamData *wmmeStreamData; - - wmmeStreamData = (PaWMMEStreamData *) PaHost_AllocateFastMemory(sizeof(PaWMMEStreamData)); /* MEM */ - if( wmmeStreamData == NULL ) - { - result = paInsufficientMemory; - goto error; - } - memset( wmmeStreamData, 0, sizeof(PaWMMEStreamData) ); - stream->past_DeviceData = (void *) wmmeStreamData; - - return result; - -error: - return result; -} +#endif /* __cplusplus */ -/*******************************************************************/ -static void PaHost_FreeWMMEStreamData( internalPortAudioStream *internalStream ) -{ - PaWMMEStreamData *wmmeStreamData = (PaWMMEStreamData *) internalStream->past_DeviceData; +PaError PaWinMme_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index ); - PaHost_FreeFastMemory( wmmeStreamData, sizeof(PaWMMEStreamData) ); /* MEM */ - internalStream->past_DeviceData = NULL; +#ifdef __cplusplus } -/*************************************************************************/ -static PaWMMEStreamData* PaHost_GetWMMEStreamData( internalPortAudioStream* internalStream ) -{ - PaWMMEStreamData *result = NULL; +#endif /* __cplusplus */ + +static void Terminate( struct PaUtilHostApiRepresentation *hostApi ); +static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi, + PaStream** stream, + 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 ); + + +/* macros for setting last host error information */ + +#ifdef UNICODE + +#define PA_MME_SET_LAST_WAVEIN_ERROR( mmresult ) \ + { \ + wchar_t mmeErrorTextWide[ MAXERRORLENGTH ]; \ + char mmeErrorText[ MAXERRORLENGTH ]; \ + waveInGetErrorText( mmresult, mmeErrorTextWide, MAXERRORLENGTH ); \ + WideCharToMultiByte( CP_ACP, WC_COMPOSITECHECK | WC_DEFAULTCHAR,\ + mmeErrorTextWide, -1, mmeErrorText, MAXERRORLENGTH, NULL, NULL ); \ + PaUtil_SetLastHostErrorInfo( paMME, mmresult, mmeErrorText ); \ + } - if( internalStream != NULL ) - { - result = (PaWMMEStreamData *) internalStream->past_DeviceData; +#define PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult ) \ + { \ + wchar_t mmeErrorTextWide[ MAXERRORLENGTH ]; \ + char mmeErrorText[ MAXERRORLENGTH ]; \ + waveOutGetErrorText( mmresult, mmeErrorTextWide, MAXERRORLENGTH ); \ + WideCharToMultiByte( CP_ACP, WC_COMPOSITECHECK | WC_DEFAULTCHAR,\ + mmeErrorTextWide, -1, mmeErrorText, MAXERRORLENGTH, NULL, NULL ); \ + PaUtil_SetLastHostErrorInfo( paMME, mmresult, mmeErrorText ); \ } - return result; -} -/********************************* BEGIN CPU UTILIZATION MEASUREMENT ****/ -/* FIXME: the cpu usage code should be factored out into a common module */ -static void Pa_InitializeCpuUsageScalar( internalPortAudioStream *stream ) -{ - PaWMMEStreamData *wmmeStreamData = (PaWMMEStreamData *) stream->past_DeviceData; + +#else /* !UNICODE */ - LARGE_INTEGER frequency; - if( QueryPerformanceFrequency( &frequency ) == 0 ) - { - wmmeStreamData->inverseTicksPerHostBuffer = 0.0; +#define PA_MME_SET_LAST_WAVEIN_ERROR( mmresult ) \ + { \ + char mmeErrorText[ MAXERRORLENGTH ]; \ + waveInGetErrorText( mmresult, mmeErrorText, MAXERRORLENGTH ); \ + PaUtil_SetLastHostErrorInfo( paMME, mmresult, mmeErrorText ); \ } - else - { - wmmeStreamData->inverseTicksPerHostBuffer = stream->past_SampleRate / - ( (double)frequency.QuadPart * stream->past_FramesPerUserBuffer * wmmeStreamData->userBuffersPerHostBuffer ); - DBUG(("inverseTicksPerHostBuffer = %g\n", wmmeStreamData->inverseTicksPerHostBuffer )); + +#define PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult ) \ + { \ + char mmeErrorText[ MAXERRORLENGTH ]; \ + waveOutGetErrorText( mmresult, mmeErrorText, MAXERRORLENGTH ); \ + PaUtil_SetLastHostErrorInfo( paMME, mmresult, mmeErrorText ); \ } -} -static void Pa_StartUsageCalculation( internalPortAudioStream *stream ) -{ - PaWMMEStreamData *wmmeStreamData = (PaWMMEStreamData *) stream->past_DeviceData; - if( wmmeStreamData == NULL ) return; - /* Query system timer for usage analysis and to prevent overuse of CPU. */ - QueryPerformanceCounter( &wmmeStreamData->entryCount ); +#endif /* UNICODE */ + + +static void PaMme_SetLastSystemError( DWORD errorCode ) +{ + char *lpMsgBuf; + FormatMessage( + FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, + NULL, + errorCode, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + (LPTSTR) &lpMsgBuf, + 0, + NULL + ); + PaUtil_SetLastHostErrorInfo( paMME, errorCode, lpMsgBuf ); + LocalFree( lpMsgBuf ); } -static void Pa_EndUsageCalculation( internalPortAudioStream *stream ) + +#define PA_MME_SET_LAST_SYSTEM_ERROR( errorCode ) \ + PaMme_SetLastSystemError( errorCode ) + + +/* PaError returning wrappers for some commonly used win32 functions + note that we allow passing a null ptr to have no effect. +*/ + +static PaError CreateEventWithPaError( HANDLE *handle, + LPSECURITY_ATTRIBUTES lpEventAttributes, + BOOL bManualReset, + BOOL bInitialState, + LPCTSTR lpName ) { - LARGE_INTEGER CurrentCount; - PaWMMEStreamData *wmmeStreamData = (PaWMMEStreamData *) stream->past_DeviceData; + PaError result = paNoError; - if( wmmeStreamData == NULL ) return; - /* - * Measure CPU utilization during this callback. Note that this calculation - * assumes that we had the processor the whole time. - */ -#define LOWPASS_COEFFICIENT_0 (0.9) -#define LOWPASS_COEFFICIENT_1 (0.99999 - LOWPASS_COEFFICIENT_0) - if( QueryPerformanceCounter( &CurrentCount ) ) + *handle = NULL; + + *handle = CreateEvent( lpEventAttributes, bManualReset, bInitialState, lpName ); + if( *handle == NULL ) { - LONGLONG InsideCount = CurrentCount.QuadPart - wmmeStreamData->entryCount.QuadPart; - double newUsage = InsideCount * wmmeStreamData->inverseTicksPerHostBuffer; - stream->past_Usage = (LOWPASS_COEFFICIENT_0 * stream->past_Usage) + - (LOWPASS_COEFFICIENT_1 * newUsage); + result = paUnanticipatedHostError; + PA_MME_SET_LAST_SYSTEM_ERROR( GetLastError() ); } + + return result; } -/****************************************** END CPU UTILIZATION *******/ -static void Pa_InitializeNumDevices( void ) + +static PaError ResetEventWithPaError( HANDLE handle ) { - sNumInputDevices = waveInGetNumDevs(); - if( sNumInputDevices > 0 ) - { - sNumInputDevices += 1; /* add one extra for the WAVE_MAPPER */ - sDefaultInputDeviceID = 0; - } - else - { - sDefaultInputDeviceID = paNoDevice; - } + PaError result = paNoError; - sNumOutputDevices = waveOutGetNumDevs(); - if( sNumOutputDevices > 0 ) - { - sNumOutputDevices += 1; /* add one extra for the WAVE_MAPPER */ - sDefaultOutputDeviceID = sNumInputDevices; - } - else + if( handle ) { - sDefaultOutputDeviceID = paNoDevice; + if( ResetEvent( handle ) == 0 ) + { + result = paUnanticipatedHostError; + PA_MME_SET_LAST_SYSTEM_ERROR( GetLastError() ); + } } - sNumDevices = sNumInputDevices + sNumOutputDevices; + return result; } -static PaError Pa_AllocateDevicePtrs( void ) -{ - int numBytes; - int i; - - /* Allocate structures to hold device info. */ - /* PLB20010402 - was allocating too much memory. */ - /* numBytes = sNumDevices * sizeof(PaDeviceInfo); // PLB20010402 */ - - if( sNumDevices > 0 ) - { - numBytes = sNumDevices * sizeof(PaDeviceInfo *); /* PLB20010402 */ - sDevicePtrs = (PaDeviceInfo **) PaHost_AllocateTrackedMemory( numBytes ); /* MEM */ - if( sDevicePtrs == NULL ) return paInsufficientMemory; - for( i = 0; i < sNumDevices; i++ ) - sDevicePtrs[i] = NULL; /* RDB20020417 explicitly set each ptr to NULL */ - } - else +static PaError CloseHandleWithPaError( HANDLE handle ) +{ + PaError result = paNoError; + + if( handle ) { - sDevicePtrs = NULL; + if( CloseHandle( handle ) == 0 ) + { + result = paUnanticipatedHostError; + PA_MME_SET_LAST_SYSTEM_ERROR( GetLastError() ); + } } - return paNoError; -} -/*************************************************************************/ -long Pa_GetHostError() -{ - return sPaHostError; -} -/*************************************************************************/ -int Pa_CountDevices() -{ - if( PaHost_IsInitialized() ) - return sNumDevices; - else - return 0; + return result; } -/************************************************************************* - * If a PaDeviceInfo structure has not already been created, - * then allocate one and fill it in for the selected device. - * - * We create one extra input and one extra output device for the WAVE_MAPPER. - * [Does anyone know how to query the default device and get its name?] - */ -const PaDeviceInfo* Pa_GetDeviceInfo( PaDeviceID id ) -{ -#define NUM_STANDARDSAMPLINGRATES 3 /* 11.025, 22.05, 44.1 */ -#define NUM_CUSTOMSAMPLINGRATES 5 /* must be the same number of elements as in the array below */ -#define MAX_NUMSAMPLINGRATES (NUM_STANDARDSAMPLINGRATES+NUM_CUSTOMSAMPLINGRATES) - static DWORD customSamplingRates[] = { 32000, 48000, 64000, 88200, 96000 }; - PaDeviceInfo *deviceInfo; - double *sampleRates; /* non-const ptr */ - int i; - char *s; - - if( id < 0 || id >= sNumDevices ) - return NULL; - if( sDevicePtrs[ id ] != NULL ) - { - return sDevicePtrs[ id ]; - } - deviceInfo = (PaDeviceInfo *)PaHost_AllocateTrackedMemory( sizeof(PaDeviceInfo) ); /* MEM */ - if( deviceInfo == NULL ) return NULL; - deviceInfo->structVersion = 1; - deviceInfo->maxInputChannels = 0; - deviceInfo->maxOutputChannels = 0; - deviceInfo->numSampleRates = 0; - sampleRates = (double*)PaHost_AllocateTrackedMemory( MAX_NUMSAMPLINGRATES * sizeof(double) ); /* MEM */ - deviceInfo->sampleRates = sampleRates; - deviceInfo->nativeSampleFormats = paInt16; /* should query for higher bit depths below */ - if( id < sNumInputDevices ) - { - /* input device */ - int inputMmID = PaDeviceIdToWinId(id); - WAVEINCAPS wic; - if( waveInGetDevCaps( inputMmID, &wic, sizeof( WAVEINCAPS ) ) != MMSYSERR_NOERROR ) - goto error; - /* Append I/O suffix to WAVE_MAPPER device. */ - if( inputMmID == WAVE_MAPPER ) - { - s = (char *) PaHost_AllocateTrackedMemory( strlen( wic.szPname ) + 1 + sizeof(sMapperSuffixInput) ); /* MEM */ - strcpy( s, wic.szPname ); - strcat( s, sMapperSuffixInput ); - } - else - { - s = (char *) PaHost_AllocateTrackedMemory( strlen( wic.szPname ) + 1 ); /* MEM */ - strcpy( s, wic.szPname ); - } - deviceInfo->name = s; - deviceInfo->maxInputChannels = wic.wChannels; - /* Sometimes a device can return a rediculously large number of channels. - * This happened with an SBLive card on a Windows ME box. - * If that happens, then force it to 2 channels. PLB20010413 - */ - if( (deviceInfo->maxInputChannels < 1) || (deviceInfo->maxInputChannels > 256) ) - { - ERR_RPT(("Pa_GetDeviceInfo: Num input channels reported as %d! Changed to 2.\n", deviceInfo->maxOutputChannels )); - deviceInfo->maxInputChannels = 2; - } - /* Add a sample rate to the list if we can do stereo 16 bit at that rate - * based on the format flags. */ - if( wic.dwFormats & WAVE_FORMAT_1M16 ||wic.dwFormats & WAVE_FORMAT_1S16 ) - sampleRates[ deviceInfo->numSampleRates++ ] = 11025.; - if( wic.dwFormats & WAVE_FORMAT_2M16 ||wic.dwFormats & WAVE_FORMAT_2S16 ) - sampleRates[ deviceInfo->numSampleRates++ ] = 22050.; - if( wic.dwFormats & WAVE_FORMAT_4M16 ||wic.dwFormats & WAVE_FORMAT_4S16 ) - sampleRates[ deviceInfo->numSampleRates++ ] = 44100.; - /* Add a sample rate to the list if we can do stereo 16 bit at that rate - * based on opening the device successfully. */ - for( i=0; i < NUM_CUSTOMSAMPLINGRATES; i++ ) - { - WAVEFORMATEX wfx; - wfx.wFormatTag = WAVE_FORMAT_PCM; - wfx.nSamplesPerSec = customSamplingRates[i]; - wfx.wBitsPerSample = 16; - wfx.cbSize = 0; /* ignored */ - wfx.nChannels = (WORD)deviceInfo->maxInputChannels; - wfx.nAvgBytesPerSec = wfx.nChannels * wfx.nSamplesPerSec * sizeof(short); - wfx.nBlockAlign = (WORD)(wfx.nChannels * sizeof(short)); - if( waveInOpen( NULL, inputMmID, &wfx, 0, 0, WAVE_FORMAT_QUERY ) == MMSYSERR_NOERROR ) - { - sampleRates[ deviceInfo->numSampleRates++ ] = customSamplingRates[i]; - } - } - } - else if( id - sNumInputDevices < sNumOutputDevices ) - { - /* output device */ - int outputMmID = PaDeviceIdToWinId(id); - WAVEOUTCAPS woc; - if( waveOutGetDevCaps( outputMmID, &woc, sizeof( WAVEOUTCAPS ) ) != MMSYSERR_NOERROR ) - goto error; - /* Append I/O suffix to WAVE_MAPPER device. */ - if( outputMmID == WAVE_MAPPER ) - { - s = (char *) PaHost_AllocateTrackedMemory( strlen( woc.szPname ) + 1 + sizeof(sMapperSuffixOutput) ); /* MEM */ - strcpy( s, woc.szPname ); - strcat( s, sMapperSuffixOutput ); - } - else - { - s = (char *) PaHost_AllocateTrackedMemory( strlen( woc.szPname ) + 1 ); /* MEM */ - strcpy( s, woc.szPname ); - } - deviceInfo->name = s; - deviceInfo->maxOutputChannels = woc.wChannels; - /* Sometimes a device can return a rediculously large number of channels. - * This happened with an SBLive card on a Windows ME box. - * It also happens on Win XP! - */ - if( (deviceInfo->maxOutputChannels < 1) || (deviceInfo->maxOutputChannels > 256) ) - { -#if 1 - deviceInfo->maxOutputChannels = 2; -#else - /* If channel max is goofy, then query for max channels. PLB20020228 - * This doesn't seem to help. Disable code for now. Remove it later. - */ - ERR_RPT(("Pa_GetDeviceInfo: Num output channels reported as %d!", deviceInfo->maxOutputChannels )); - deviceInfo->maxOutputChannels = 0; - /* Attempt to find the correct maximum by querying the device. */ - for( i=2; i<16; i += 2 ) - { - WAVEFORMATEX wfx; - wfx.wFormatTag = WAVE_FORMAT_PCM; - wfx.nSamplesPerSec = 44100; - wfx.wBitsPerSample = 16; - wfx.cbSize = 0; /* ignored */ - wfx.nChannels = (WORD) i; - wfx.nAvgBytesPerSec = wfx.nChannels * wfx.nSamplesPerSec * sizeof(short); - wfx.nBlockAlign = (WORD)(wfx.nChannels * sizeof(short)); - if( waveOutOpen( NULL, outputMmID, &wfx, 0, 0, WAVE_FORMAT_QUERY ) == MMSYSERR_NOERROR ) - { - deviceInfo->maxOutputChannels = i; - } - else - { - break; - } - } -#endif - ERR_RPT((" Changed to %d.\n", deviceInfo->maxOutputChannels )); - } +/* PaWinMmeHostApiRepresentation - host api datastructure specific to this implementation */ - /* Add a sample rate to the list if we can do stereo 16 bit at that rate - * based on the format flags. */ - if( woc.dwFormats & WAVE_FORMAT_1M16 ||woc.dwFormats & WAVE_FORMAT_1S16 ) - sampleRates[ deviceInfo->numSampleRates++ ] = 11025.; - if( woc.dwFormats & WAVE_FORMAT_2M16 ||woc.dwFormats & WAVE_FORMAT_2S16 ) - sampleRates[ deviceInfo->numSampleRates++ ] = 22050.; - if( woc.dwFormats & WAVE_FORMAT_4M16 ||woc.dwFormats & WAVE_FORMAT_4S16 ) - sampleRates[ deviceInfo->numSampleRates++ ] = 44100.; +typedef struct +{ + PaUtilHostApiRepresentation inheritedHostApiRep; + PaUtilStreamInterface callbackStreamInterface; + PaUtilStreamInterface blockingStreamInterface; - /* Add a sample rate to the list if we can do stereo 16 bit at that rate - * based on opening the device successfully. */ - for( i=0; i < NUM_CUSTOMSAMPLINGRATES; i++ ) - { - WAVEFORMATEX wfx; - wfx.wFormatTag = WAVE_FORMAT_PCM; - wfx.nSamplesPerSec = customSamplingRates[i]; - wfx.wBitsPerSample = 16; - wfx.cbSize = 0; /* ignored */ - wfx.nChannels = (WORD)deviceInfo->maxOutputChannels; - wfx.nAvgBytesPerSec = wfx.nChannels * wfx.nSamplesPerSec * sizeof(short); - wfx.nBlockAlign = (WORD)(wfx.nChannels * sizeof(short)); - if( waveOutOpen( NULL, outputMmID, &wfx, 0, 0, WAVE_FORMAT_QUERY ) == MMSYSERR_NOERROR ) - { - sampleRates[ deviceInfo->numSampleRates++ ] = customSamplingRates[i]; - } - } - } - sDevicePtrs[ id ] = deviceInfo; - return deviceInfo; + PaUtilAllocationGroup *allocations; + + int inputDeviceCount, outputDeviceCount; + + /** winMmeDeviceIds is an array of WinMme device ids. + fields in the range [0, inputDeviceCount) are input device ids, + and [inputDeviceCount, inputDeviceCount + outputDeviceCount) are output + device ids. + */ + UINT *winMmeDeviceIds; +} +PaWinMmeHostApiRepresentation; -error: - PaHost_FreeTrackedMemory( sampleRates ); /* MEM */ - PaHost_FreeTrackedMemory( deviceInfo ); /* MEM */ - return NULL; +typedef struct +{ + PaDeviceInfo inheritedDeviceInfo; + DWORD dwFormats; /**<< standard formats bitmask from the WAVEINCAPS and WAVEOUTCAPS structures */ } +PaWinMmeDeviceInfo; + + /************************************************************************* * Returns recommended device ID. * On the PC, the recommended device can be specified by the user by @@ -542,1166 +376,3259 @@ error: * The user should first determine the available device ID by using * the supplied application "pa_devs". */ -#define PA_ENV_BUF_SIZE (32) -#define PA_REC_IN_DEV_ENV_NAME ("PA_RECOMMENDED_INPUT_DEVICE") -#define PA_REC_OUT_DEV_ENV_NAME ("PA_RECOMMENDED_OUTPUT_DEVICE") -static PaDeviceID PaHost_GetEnvDefaultDeviceID( char *envName ) +#define PA_ENV_BUF_SIZE_ (32) +#define PA_REC_IN_DEV_ENV_NAME_ ("PA_RECOMMENDED_INPUT_DEVICE") +#define PA_REC_OUT_DEV_ENV_NAME_ ("PA_RECOMMENDED_OUTPUT_DEVICE") +static PaDeviceIndex GetEnvDefaultDeviceID( char *envName ) { + PaDeviceIndex recommendedIndex = paNoDevice; DWORD hresult; - char envbuf[PA_ENV_BUF_SIZE]; - PaDeviceID recommendedID = paNoDevice; + char envbuf[PA_ENV_BUF_SIZE_]; + +#ifndef WIN32_PLATFORM_PSPC /* no GetEnvironmentVariable on PocketPC */ /* Let user determine default device by setting environment variable. */ - hresult = GetEnvironmentVariable( envName, envbuf, PA_ENV_BUF_SIZE ); - if( (hresult > 0) && (hresult < PA_ENV_BUF_SIZE) ) + hresult = GetEnvironmentVariable( envName, envbuf, PA_ENV_BUF_SIZE_ ); + if( (hresult > 0) && (hresult < PA_ENV_BUF_SIZE_) ) { - recommendedID = atoi( envbuf ); + recommendedIndex = atoi( envbuf ); } - return recommendedID; +#endif + + return recommendedIndex; } -/********************************************************************** - * Check for environment variable, else query devices and use result. - */ -PaDeviceID Pa_GetDefaultInputDeviceID( void ) + + +static void InitializeDefaultDeviceIdsFromEnv( PaWinMmeHostApiRepresentation *hostApi ) { - PaDeviceID result; + PaDeviceIndex device; - result = PaHost_GetEnvDefaultDeviceID( PA_REC_IN_DEV_ENV_NAME ); - if( result == paNoDevice || result < 0 || result >= sNumInputDevices ) + /* input */ + device = GetEnvDefaultDeviceID( PA_REC_IN_DEV_ENV_NAME_ ); + if( device != paNoDevice && + ( device >= 0 && device < hostApi->inheritedHostApiRep.info.deviceCount ) && + hostApi->inheritedHostApiRep.deviceInfos[ device ]->maxInputChannels > 0 ) { - result = sDefaultInputDeviceID; + hostApi->inheritedHostApiRep.info.defaultInputDevice = device; } - return result; + + /* output */ + device = GetEnvDefaultDeviceID( PA_REC_OUT_DEV_ENV_NAME_ ); + if( device != paNoDevice && + ( device >= 0 && device < hostApi->inheritedHostApiRep.info.deviceCount ) && + hostApi->inheritedHostApiRep.deviceInfos[ device ]->maxOutputChannels > 0 ) + { + hostApi->inheritedHostApiRep.info.defaultOutputDevice = device; + } +} + + +/** Convert external PA ID to a windows multimedia device ID +*/ +static UINT LocalDeviceIndexToWinMmeDeviceId( PaWinMmeHostApiRepresentation *hostApi, PaDeviceIndex device ) +{ + assert( device >= 0 && device < hostApi->inputDeviceCount + hostApi->outputDeviceCount ); + + return hostApi->winMmeDeviceIds[ device ]; } -PaDeviceID Pa_GetDefaultOutputDeviceID( void ) + + +static PaError QueryInputWaveFormatEx( int deviceId, WAVEFORMATEX *waveFormatEx ) { - PaDeviceID result; + MMRESULT mmresult; + + switch( mmresult = waveInOpen( NULL, deviceId, waveFormatEx, 0, 0, WAVE_FORMAT_QUERY ) ) + { + case MMSYSERR_NOERROR: + return paNoError; + case MMSYSERR_ALLOCATED: /* Specified resource is already allocated. */ + return paDeviceUnavailable; + case MMSYSERR_NODRIVER: /* No device driver is present. */ + return paDeviceUnavailable; + case MMSYSERR_NOMEM: /* Unable to allocate or lock memory. */ + return paInsufficientMemory; + case WAVERR_BADFORMAT: /* Attempted to open with an unsupported waveform-audio format. */ + return paSampleFormatNotSupported; + + case MMSYSERR_BADDEVICEID: /* Specified device identifier is out of range. */ + /* falls through */ + default: + PA_MME_SET_LAST_WAVEIN_ERROR( mmresult ); + return paUnanticipatedHostError; + } +} - result = PaHost_GetEnvDefaultDeviceID( PA_REC_OUT_DEV_ENV_NAME ); - if( result == paNoDevice || result < sNumInputDevices || result >= sNumDevices ) + +static PaError QueryOutputWaveFormatEx( int deviceId, WAVEFORMATEX *waveFormatEx ) +{ + MMRESULT mmresult; + + switch( mmresult = waveOutOpen( NULL, deviceId, waveFormatEx, 0, 0, WAVE_FORMAT_QUERY ) ) { - result = sDefaultOutputDeviceID; + case MMSYSERR_NOERROR: + return paNoError; + case MMSYSERR_ALLOCATED: /* Specified resource is already allocated. */ + return paDeviceUnavailable; + case MMSYSERR_NODRIVER: /* No device driver is present. */ + return paDeviceUnavailable; + case MMSYSERR_NOMEM: /* Unable to allocate or lock memory. */ + return paInsufficientMemory; + case WAVERR_BADFORMAT: /* Attempted to open with an unsupported waveform-audio format. */ + return paSampleFormatNotSupported; + + case MMSYSERR_BADDEVICEID: /* Specified device identifier is out of range. */ + /* falls through */ + default: + PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult ); + return paUnanticipatedHostError; } - return result; } -/********************************************************************** - * Initialize Host dependant part of API. - */ -PaError PaHost_Init( void ) + + +static PaError QueryFormatSupported( PaDeviceInfo *deviceInfo, + PaError (*waveFormatExQueryFunction)(int, WAVEFORMATEX*), + int winMmeDeviceId, int channels, double sampleRate ) { + PaWinMmeDeviceInfo *winMmeDeviceInfo = (PaWinMmeDeviceInfo*)deviceInfo; + WAVEFORMATEX waveFormatEx; + + if( sampleRate == 11025.0 + && ( (channels == 1 && (winMmeDeviceInfo->dwFormats & WAVE_FORMAT_1M16)) + || (channels == 2 && (winMmeDeviceInfo->dwFormats & WAVE_FORMAT_1S16)) ) ){ -#if PA_TRACK_MEMORY - PRINT(("PaHost_Init: sNumAllocations = %d\n", sNumAllocations )); -#endif + return paNoError; + } -#if PA_SIMULATE_UNDERFLOW - PRINT(("WARNING - Underflow Simulation Enabled - Expect a Big Glitch!!!\n")); -#endif - + if( sampleRate == 22050.0 + && ( (channels == 1 && (winMmeDeviceInfo->dwFormats & WAVE_FORMAT_2M16)) + || (channels == 2 && (winMmeDeviceInfo->dwFormats & WAVE_FORMAT_2S16)) ) ){ + + return paNoError; + } - Pa_InitializeNumDevices(); + if( sampleRate == 44100.0 + && ( (channels == 1 && (winMmeDeviceInfo->dwFormats & WAVE_FORMAT_4M16)) + || (channels == 2 && (winMmeDeviceInfo->dwFormats & WAVE_FORMAT_4S16)) ) ){ - return Pa_AllocateDevicePtrs(); + return paNoError; + } + + waveFormatEx.wFormatTag = WAVE_FORMAT_PCM; + waveFormatEx.nChannels = (WORD)channels; + waveFormatEx.nSamplesPerSec = (DWORD)sampleRate; + waveFormatEx.nAvgBytesPerSec = waveFormatEx.nSamplesPerSec * channels * sizeof(short); + waveFormatEx.nBlockAlign = (WORD)(channels * sizeof(short)); + waveFormatEx.wBitsPerSample = 16; + waveFormatEx.cbSize = 0; + + return waveFormatExQueryFunction( winMmeDeviceId, &waveFormatEx ); } -/********************************************************************** - * Check WAVE buffers to see if they are done. - * Fill any available output buffers and use any available - * input buffers by calling user callback. - * - * This routine will loop until: - * user callback returns !=0 OR - * all output buffers are filled OR - * past->past_StopSoon is set OR - * an error occurs when calling WMME. - * - * Returns >0 when user requests a stop, <0 on error. - * - */ -static PaError Pa_TimeSlice( internalPortAudioStream *stream ) -{ - PaError result = paNoError; - MMRESULT mmresult; - char *inBufPtr; - char *outBufPtr; - int gotInput = 0; - int gotOutput = 0; - int i; - int buffersProcessed = 0; - int done = 0; - PaWMMEStreamData *wmmeStreamData = (PaWMMEStreamData *) stream->past_DeviceData; - - if( wmmeStreamData == NULL ) return paInternalError; - - stream->past_NumCallbacks += 1; -#if PA_TRACE_RUN - AddTraceMessage("Pa_TimeSlice: past_NumCallbacks ", stream->past_NumCallbacks ); -#endif - /* JM20020118 - prevent hung thread when buffers underflow. */ - /* while( !done ) /* BAD */ - while( !done && !stream->past_StopSoon ) /* GOOD */ - { -#if PA_SIMULATE_UNDERFLOW - if(gUnderCallbackCounter++ == UNDER_SLEEP_AT) - { - Sleep(UNDER_SLEEP_FOR); - } -#endif +#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 }; - /* If we are using output, then we need an empty output buffer. */ - gotOutput = 0; - outBufPtr = NULL; - if( stream->past_NumOutputChannels > 0 ) - { - if((wmmeStreamData->outputBuffers[ wmmeStreamData->currentOutputBuffer ].dwFlags & WHDR_DONE) == 0) - { - break; /* If none empty then bail and try again later. */ - } - else - { - outBufPtr = wmmeStreamData->outputBuffers[ wmmeStreamData->currentOutputBuffer ].lpData; - gotOutput = 1; - } - } - /* Use an input buffer if one is available. */ - gotInput = 0; - inBufPtr = NULL; - if( ( stream->past_NumInputChannels > 0 ) && - (wmmeStreamData->inputBuffers[ wmmeStreamData->currentInputBuffer ].dwFlags & WHDR_DONE) ) - { - inBufPtr = wmmeStreamData->inputBuffers[ wmmeStreamData->currentInputBuffer ].lpData; - gotInput = 1; -#if PA_TRACE_RUN - AddTraceMessage("Pa_TimeSlice: got input buffer at ", (int)inBufPtr ); - AddTraceMessage("Pa_TimeSlice: got input buffer # ", wmmeStreamData->currentInputBuffer ); -#endif +static void DetectDefaultSampleRate( PaWinMmeDeviceInfo *winMmeDeviceInfo, int winMmeDeviceId, + PaError (*waveFormatExQueryFunction)(int, WAVEFORMATEX*), int maxChannels ) +{ + PaDeviceInfo *deviceInfo = &winMmeDeviceInfo->inheritedDeviceInfo; + int i; + + deviceInfo->defaultSampleRate = 0.; - } - /* If we can't do anything then bail out. */ - if( !gotInput && !gotOutput ) break; - buffersProcessed += 1; - /* Each Wave buffer contains multiple user buffers so do them all now. */ - /* Base Usage on time it took to process one host buffer. */ - Pa_StartUsageCalculation( stream ); - for( i=0; iuserBuffersPerHostBuffer; i++ ) - { - if( done ) - { - if( gotOutput ) - { - /* Clear remainder of wave buffer if we are waiting for stop. */ - AddTraceMessage("Pa_TimeSlice: zero rest of wave buffer ", i ); - memset( outBufPtr, 0, wmmeStreamData->bytesPerUserOutputBuffer ); - } - } - else - { - /* Convert 16 bit native data to user data and call user routine. */ - result = Pa_CallConvertInt16( stream, (short *) inBufPtr, (short *) outBufPtr ); - if( result != 0) done = 1; - } - if( gotInput ) inBufPtr += wmmeStreamData->bytesPerUserInputBuffer; - if( gotOutput) outBufPtr += wmmeStreamData->bytesPerUserOutputBuffer; - } - Pa_EndUsageCalculation( stream ); - /* Send WAVE buffer to Wave Device to be refilled. */ - if( gotInput ) - { - mmresult = waveInAddBuffer( wmmeStreamData->hWaveIn, - &wmmeStreamData->inputBuffers[ wmmeStreamData->currentInputBuffer ], - sizeof(WAVEHDR) ); - if( mmresult != MMSYSERR_NOERROR ) - { - sPaHostError = mmresult; - result = paHostError; - break; - } - wmmeStreamData->currentInputBuffer = (wmmeStreamData->currentInputBuffer+1 >= wmmeStreamData->numHostBuffers) ? - 0 : wmmeStreamData->currentInputBuffer+1; - } - /* Write WAVE buffer to Wave Device. */ - if( gotOutput ) + for( i=0; i < PA_DEFAULTSAMPLERATESEARCHORDER_COUNT_; ++i ) + { + double sampleRate = defaultSampleRateSearchOrder_[ i ]; + PaError paerror = QueryFormatSupported( deviceInfo, waveFormatExQueryFunction, winMmeDeviceId, maxChannels, sampleRate ); + if( paerror == paNoError ) { -#if PA_TRACE_START_STOP - AddTraceMessage( "Pa_TimeSlice: writing buffer ", wmmeStreamData->currentOutputBuffer ); -#endif - mmresult = waveOutWrite( wmmeStreamData->hWaveOut, - &wmmeStreamData->outputBuffers[ wmmeStreamData->currentOutputBuffer ], - sizeof(WAVEHDR) ); - if( mmresult != MMSYSERR_NOERROR ) - { - sPaHostError = mmresult; - result = paHostError; - break; - } - wmmeStreamData->currentOutputBuffer = (wmmeStreamData->currentOutputBuffer+1 >= wmmeStreamData->numHostBuffers) ? - 0 : wmmeStreamData->currentOutputBuffer+1; + deviceInfo->defaultSampleRate = sampleRate; + break; } - } - -#if PA_TRACE_RUN - AddTraceMessage("Pa_TimeSlice: buffersProcessed ", buffersProcessed ); -#endif - return (result != 0) ? result : done; } -/*******************************************************************/ -static PaError PaHost_BackgroundManager( internalPortAudioStream *stream ) + +static PaError InitializeInputDeviceInfo( PaWinMmeHostApiRepresentation *winMmeHostApi, + PaWinMmeDeviceInfo *winMmeDeviceInfo, UINT winMmeInputDeviceId, int *success ) { - PaError result = paNoError; - int i; - int numQueuedoutputBuffers = 0; - PaWMMEStreamData *wmmeStreamData = (PaWMMEStreamData *) stream->past_DeviceData; + PaError result = paNoError; + char *deviceName; /* non-const ptr */ + MMRESULT mmresult; + WAVEINCAPS wic; + PaDeviceInfo *deviceInfo = &winMmeDeviceInfo->inheritedDeviceInfo; + + *success = 0; - /* Has someone asked us to abort by calling Pa_AbortStream()? */ - if( stream->past_StopNow ) + mmresult = waveInGetDevCaps( winMmeInputDeviceId, &wic, sizeof( WAVEINCAPS ) ); + if( mmresult == MMSYSERR_NOMEM ) { - stream->past_IsActive = 0; /* Will cause thread to return. */ + result = paInsufficientMemory; + goto error; } - /* Has someone asked us to stop by calling Pa_StopStream() - * OR has a user callback returned '1' to indicate finished. - */ - else if( stream->past_StopSoon ) + else if( mmresult != MMSYSERR_NOERROR ) { - /* Poll buffer and when all have played then exit thread. */ - /* Count how many output buffers are queued. */ - numQueuedoutputBuffers = 0; - if( stream->past_NumOutputChannels > 0 ) - { - for( i=0; inumHostBuffers; i++ ) - { - if( !( wmmeStreamData->outputBuffers[ i ].dwFlags & WHDR_DONE) ) - { -#if PA_TRACE_START_STOP - AddTraceMessage( "PaHost_BackgroundManager: waiting for buffer ", i ); -#endif - numQueuedoutputBuffers++; - } - } - } -#if PA_TRACE_START_STOP - AddTraceMessage( "PaHost_BackgroundManager: numQueuedoutputBuffers ", numQueuedoutputBuffers ); -#endif - if( numQueuedoutputBuffers == 0 ) + /* instead of returning paUnanticipatedHostError we return + paNoError, but leave success set as 0. This allows + Pa_Initialize to just ignore this device, without failing + the entire initialisation process. + */ + return paNoError; + } + + if( winMmeInputDeviceId == WAVE_MAPPER ) + { + /* Append I/O suffix to WAVE_MAPPER device. */ + deviceName = (char *)PaUtil_GroupAllocateMemory( + winMmeHostApi->allocations, strlen( wic.szPname ) + 1 + sizeof(constInputMapperSuffix_) ); + if( !deviceName ) { - stream->past_IsActive = 0; /* Will cause thread to return. */ + result = paInsufficientMemory; + goto error; } + strcpy( deviceName, wic.szPname ); + strcat( deviceName, constInputMapperSuffix_ ); } else { - /* Process full input buffer and fill up empty output buffers. */ - if( (result = Pa_TimeSlice( stream )) != 0) + deviceName = (char*)PaUtil_GroupAllocateMemory( + winMmeHostApi->allocations, strlen( wic.szPname ) + 1 ); + if( !deviceName ) { - /* User callback has asked us to stop. */ -#if PA_TRACE_START_STOP - AddTraceMessage( "PaHost_BackgroundManager: TimeSlice() returned ", result ); -#endif - stream->past_StopSoon = 1; /* Request that audio play out then stop. */ - result = paNoError; + result = paInsufficientMemory; + goto error; } + strcpy( deviceName, wic.szPname ); } + deviceInfo->name = deviceName; - PaHost_UpdateStreamTime( wmmeStreamData ); - return result; -} - -#if PA_USE_TIMER_CALLBACK -/*******************************************************************/ -static void CALLBACK Pa_TimerCallback(UINT uID, UINT uMsg, DWORD dwUser, DWORD dw1, DWORD dw2) -{ - internalPortAudioStream *stream; - PaWMMEStreamData *wmmeStreamData; - PaError result; - - stream = (internalPortAudioStream *) dwUser; - if( stream == NULL ) return; - wmmeStreamData = (PaWMMEStreamData *) stream->past_DeviceData; - if( wmmeStreamData == NULL ) return; - if( wmmeStreamData->ifInsideCallback ) - { - if( wmmeStreamData->timerID != 0 ) - { - timeKillEvent(wmmeStreamData->timerID); /* Stop callback timer. */ - wmmeStreamData->timerID = 0; - } - return; - } - wmmeStreamData->ifInsideCallback = 1; - /* Manage flags and audio processing. */ - result = PaHost_BackgroundManager( stream ); - if( result != paNoError ) + deviceInfo->maxInputChannels = wic.wChannels; + /* Sometimes a device can return a rediculously large number of channels. + * This happened with an SBLive card on a Windows ME box. + * If that happens, then force it to 2 channels. PLB20010413 + */ + if( (deviceInfo->maxInputChannels < 1) || (deviceInfo->maxInputChannels > 256) ) { - stream->past_IsActive = 0; - } - wmmeStreamData->ifInsideCallback = 0; -} -#else /* PA_USE_TIMER_CALLBACK */ -/*******************************************************************/ -static DWORD WINAPI WinMMPa_OutputThreadProc( void *pArg ) -{ - internalPortAudioStream *stream; - PaWMMEStreamData *wmmeStreamData; - HANDLE events[2]; - int numEvents = 0; - DWORD result = 0; - DWORD waitResult; - DWORD numTimeouts = 0; - DWORD timeOut; - stream = (internalPortAudioStream *) pArg; - wmmeStreamData = (PaWMMEStreamData *) stream->past_DeviceData; -#if PA_TRACE_START_STOP - AddTraceMessage( "WinMMPa_OutputThreadProc: timeoutPeriod", timeoutPeriod ); - AddTraceMessage( "WinMMPa_OutputThreadProc: past_NumUserBuffers", stream->past_NumUserBuffers ); -#endif - /* Calculate timeOut as half the time it would take to play all buffers. */ - timeOut = (DWORD) (500.0 * PaHost_GetTotalBufferFrames( stream ) / stream->past_SampleRate); - /* Get event(s) ready for wait. */ - events[numEvents++] = wmmeStreamData->bufferEvent; - if( wmmeStreamData->abortEventInited ) events[numEvents++] = wmmeStreamData->abortEvent; - /* Stay in this thread as long as we are "active". */ - while( stream->past_IsActive ) - { - /*******************************************************************/ - /******** WAIT here for an event from WMME or PA *******************/ - /*******************************************************************/ - waitResult = WaitForMultipleObjects( numEvents, events, FALSE, timeOut ); - /* Error? */ - if( waitResult == WAIT_FAILED ) - { - sPaHostError = GetLastError(); - result = paHostError; - stream->past_IsActive = 0; - } - /* Timeout? Don't stop. Just keep polling for DONE.*/ - else if( waitResult == WAIT_TIMEOUT ) - { -#if PA_TRACE_START_STOP - AddTraceMessage( "WinMMPa_OutputThreadProc: timed out ", numQueuedoutputBuffers ); -#endif - numTimeouts += 1; - } - /* Manage flags and audio processing. */ - result = PaHost_BackgroundManager( stream ); - if( result != paNoError ) - { - stream->past_IsActive = 0; - } + PA_DEBUG(("Pa_GetDeviceInfo: Num input channels reported as %d! Changed to 2.\n", deviceInfo->maxInputChannels )); + deviceInfo->maxInputChannels = 2; } + + winMmeDeviceInfo->dwFormats = wic.dwFormats; + + DetectDefaultSampleRate( winMmeDeviceInfo, winMmeInputDeviceId, + QueryInputWaveFormatEx, deviceInfo->maxInputChannels ); + + *success = 1; + +error: return result; } -#endif -/*******************************************************************/ -PaError PaHost_OpenInputStream( internalPortAudioStream *stream ) + +static PaError InitializeOutputDeviceInfo( PaWinMmeHostApiRepresentation *winMmeHostApi, + PaWinMmeDeviceInfo *winMmeDeviceInfo, UINT winMmeOutputDeviceId, int *success ) { - PaError result = paNoError; - MMRESULT mmresult; - PaWMMEStreamData *wmmeStreamData; - int i; - int inputMmId; - int bytesPerInputFrame; - WAVEFORMATEX wfx; - const PaDeviceInfo *deviceInfo; - - wmmeStreamData = (PaWMMEStreamData *) stream->past_DeviceData; - DBUG(("PaHost_OpenStream: deviceID = 0x%x\n", stream->past_InputDeviceID)); - deviceInfo = Pa_GetDeviceInfo( stream->past_InputDeviceID ); - if( deviceInfo == NULL ) return paInternalError; - - switch( deviceInfo->nativeSampleFormats ) - { - case paInt32: - case paFloat32: - bytesPerInputFrame = sizeof(float) * stream->past_NumInputChannels; - break; - default: - bytesPerInputFrame = sizeof(short) * stream->past_NumInputChannels; - break; - } - wfx.wFormatTag = WAVE_FORMAT_PCM; - wfx.nChannels = (WORD) stream->past_NumInputChannels; - wfx.nSamplesPerSec = (DWORD) stream->past_SampleRate; - wfx.nAvgBytesPerSec = (DWORD)(bytesPerInputFrame * stream->past_SampleRate); - wfx.nBlockAlign = (WORD)bytesPerInputFrame; - wfx.wBitsPerSample = (WORD)((bytesPerInputFrame/stream->past_NumInputChannels) * 8); - wfx.cbSize = 0; - inputMmId = PaDeviceIdToWinId( stream->past_InputDeviceID ); -#if PA_USE_TIMER_CALLBACK - mmresult = waveInOpen( &wmmeStreamData->hWaveIn, inputMmId, &wfx, - 0, 0, CALLBACK_NULL ); -#else - mmresult = waveInOpen( &wmmeStreamData->hWaveIn, inputMmId, &wfx, - (DWORD)wmmeStreamData->bufferEvent, (DWORD) stream, CALLBACK_EVENT ); -#endif - if( mmresult != MMSYSERR_NOERROR ) + PaError result = paNoError; + char *deviceName; /* non-const ptr */ + MMRESULT mmresult; + WAVEOUTCAPS woc; + PaDeviceInfo *deviceInfo = &winMmeDeviceInfo->inheritedDeviceInfo; + + *success = 0; + + mmresult = waveOutGetDevCaps( winMmeOutputDeviceId, &woc, sizeof( WAVEOUTCAPS ) ); + if( mmresult == MMSYSERR_NOMEM ) { - ERR_RPT(("PortAudio: PaHost_OpenInputStream() failed!\n")); - result = paHostError; - sPaHostError = mmresult; + result = paInsufficientMemory; goto error; } - /* Allocate an array to hold the buffer pointers. */ - wmmeStreamData->inputBuffers = (WAVEHDR *) PaHost_AllocateTrackedMemory( sizeof(WAVEHDR)*wmmeStreamData->numHostBuffers ); /* MEM */ - if( wmmeStreamData->inputBuffers == NULL ) + else if( mmresult != MMSYSERR_NOERROR ) { - result = paInsufficientMemory; - goto error; + /* instead of returning paUnanticipatedHostError we return + paNoError, but leave success set as 0. This allows + Pa_Initialize to just ignore this device, without failing + the entire initialisation process. + */ + return paNoError; } - /* Allocate each buffer. */ - for( i=0; inumHostBuffers; i++ ) + + if( winMmeOutputDeviceId == WAVE_MAPPER ) { - wmmeStreamData->inputBuffers[i].lpData = (char *)PaHost_AllocateTrackedMemory( wmmeStreamData->bytesPerHostInputBuffer ); /* MEM */ - if( wmmeStreamData->inputBuffers[i].lpData == NULL ) + /* Append I/O suffix to WAVE_MAPPER device. */ + deviceName = (char *)PaUtil_GroupAllocateMemory( + winMmeHostApi->allocations, strlen( woc.szPname ) + 1 + sizeof(constOutputMapperSuffix_) ); + if( !deviceName ) { result = paInsufficientMemory; goto error; } - wmmeStreamData->inputBuffers[i].dwBufferLength = wmmeStreamData->bytesPerHostInputBuffer; - wmmeStreamData->inputBuffers[i].dwUser = i; - if( ( mmresult = waveInPrepareHeader( wmmeStreamData->hWaveIn, &wmmeStreamData->inputBuffers[i], sizeof(WAVEHDR) )) != MMSYSERR_NOERROR ) + strcpy( deviceName, woc.szPname ); + strcat( deviceName, constOutputMapperSuffix_ ); + } + else + { + deviceName = (char*)PaUtil_GroupAllocateMemory( + winMmeHostApi->allocations, strlen( woc.szPname ) + 1 ); + if( !deviceName ) { - result = paHostError; - sPaHostError = mmresult; + result = paInsufficientMemory; goto error; } + strcpy( deviceName, woc.szPname ); } - return result; + deviceInfo->name = deviceName; + + deviceInfo->maxOutputChannels = woc.wChannels; + /* Sometimes a device can return a rediculously large number of channels. + * This happened with an SBLive card on a Windows ME box. + * It also happens on Win XP! + */ + if( (deviceInfo->maxOutputChannels < 1) || (deviceInfo->maxOutputChannels > 256) ) + { + PA_DEBUG(("Pa_GetDeviceInfo: Num output channels reported as %d! Changed to 2.\n", deviceInfo->maxOutputChannels )); + deviceInfo->maxOutputChannels = 2; + } + + winMmeDeviceInfo->dwFormats = woc.dwFormats; + + DetectDefaultSampleRate( winMmeDeviceInfo, winMmeOutputDeviceId, + QueryOutputWaveFormatEx, deviceInfo->maxOutputChannels ); + *success = 1; + error: return result; } -/*******************************************************************/ -PaError PaHost_OpenOutputStream( internalPortAudioStream *stream ) + + +static void GetDefaultLatencies( PaTime *defaultLowLatency, PaTime *defaultHighLatency ) { - PaError result = paNoError; - MMRESULT mmresult; - PaWMMEStreamData *wmmeStreamData; - int i; - int outputMmID; - int bytesPerOutputFrame; - WAVEFORMATEX wfx; - const PaDeviceInfo *deviceInfo; - - wmmeStreamData = (PaWMMEStreamData *) stream->past_DeviceData; - DBUG(("PaHost_OpenStream: deviceID = 0x%x\n", stream->past_OutputDeviceID)); - - deviceInfo = Pa_GetDeviceInfo( stream->past_OutputDeviceID ); - if( deviceInfo == NULL ) return paInternalError; - - switch( deviceInfo->nativeSampleFormats ) - { - case paInt32: - case paFloat32: - bytesPerOutputFrame = sizeof(float) * stream->past_NumOutputChannels; - break; - default: - bytesPerOutputFrame = sizeof(short) * stream->past_NumOutputChannels; - break; - } - wfx.wFormatTag = WAVE_FORMAT_PCM; - wfx.nChannels = (WORD) stream->past_NumOutputChannels; - wfx.nSamplesPerSec = (DWORD) stream->past_SampleRate; - wfx.nAvgBytesPerSec = (DWORD)(bytesPerOutputFrame * stream->past_SampleRate); - wfx.nBlockAlign = (WORD)bytesPerOutputFrame; - wfx.wBitsPerSample = (WORD)((bytesPerOutputFrame/stream->past_NumOutputChannels) * 8); - wfx.cbSize = 0; - outputMmID = PaDeviceIdToWinId( stream->past_OutputDeviceID ); -#if PA_USE_TIMER_CALLBACK - mmresult = waveOutOpen( &wmmeStreamData->hWaveOut, outputMmID, &wfx, - 0, 0, CALLBACK_NULL ); -#else + OSVERSIONINFO osvi; + osvi.dwOSVersionInfoSize = sizeof( osvi ); + GetVersionEx( &osvi ); - wmmeStreamData->abortEvent = CreateEvent( NULL, TRUE, FALSE, NULL ); - if( wmmeStreamData->abortEvent == NULL ) + /* Check for NT */ + if( (osvi.dwMajorVersion == 4) && (osvi.dwPlatformId == 2) ) { - result = paHostError; - sPaHostError = GetLastError(); - goto error; + *defaultLowLatency = PA_MME_WIN_NT_DEFAULT_LATENCY_; } - wmmeStreamData->abortEventInited = 1; - mmresult = waveOutOpen( &wmmeStreamData->hWaveOut, outputMmID, &wfx, - (DWORD)wmmeStreamData->bufferEvent, (DWORD) stream, CALLBACK_EVENT ); -#endif - if( mmresult != MMSYSERR_NOERROR ) + else if(osvi.dwMajorVersion >= 5) { - ERR_RPT(("PortAudio: PaHost_OpenOutputStream() failed!\n")); - result = paHostError; - sPaHostError = mmresult; - goto error; + *defaultLowLatency = PA_MME_WIN_WDM_DEFAULT_LATENCY_; } - /* Allocate an array to hold the buffer pointers. */ - wmmeStreamData->outputBuffers = (WAVEHDR *) PaHost_AllocateTrackedMemory( sizeof(WAVEHDR)*wmmeStreamData->numHostBuffers ); /* MEM */ - if( wmmeStreamData->outputBuffers == NULL ) + else + { + *defaultLowLatency = PA_MME_WIN_9X_DEFAULT_LATENCY_; + } + + *defaultHighLatency = *defaultLowLatency * 2; +} + + +PaError PaWinMme_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex ) +{ + PaError result = paNoError; + int i; + PaWinMmeHostApiRepresentation *winMmeHostApi; + int inputDeviceCount, outputDeviceCount, maximumPossibleDeviceCount; + PaWinMmeDeviceInfo *deviceInfoArray; + int deviceInfoInitializationSucceeded; + PaTime defaultLowLatency, defaultHighLatency; + + winMmeHostApi = (PaWinMmeHostApiRepresentation*)PaUtil_AllocateMemory( sizeof(PaWinMmeHostApiRepresentation) ); + if( !winMmeHostApi ) { result = paInsufficientMemory; goto error; } - /* Allocate each buffer. */ - for( i=0; inumHostBuffers; i++ ) + + winMmeHostApi->allocations = PaUtil_CreateAllocationGroup(); + if( !winMmeHostApi->allocations ) { - wmmeStreamData->outputBuffers[i].lpData = (char *) PaHost_AllocateTrackedMemory( wmmeStreamData->bytesPerHostOutputBuffer ); /* MEM */ - if( wmmeStreamData->outputBuffers[i].lpData == NULL ) + result = paInsufficientMemory; + goto error; + } + + *hostApi = &winMmeHostApi->inheritedHostApiRep; + (*hostApi)->info.structVersion = 1; + (*hostApi)->info.type = paMME; + (*hostApi)->info.name = "MME"; + + + /* initialise device counts and default devices under the assumption that + there are no devices. These values are incremented below if and when + devices are successfully initialized. + */ + (*hostApi)->info.deviceCount = 0; + (*hostApi)->info.defaultInputDevice = paNoDevice; + (*hostApi)->info.defaultOutputDevice = paNoDevice; + winMmeHostApi->inputDeviceCount = 0; + winMmeHostApi->outputDeviceCount = 0; + + + maximumPossibleDeviceCount = 0; + + inputDeviceCount = waveInGetNumDevs(); + if( inputDeviceCount > 0 ) + maximumPossibleDeviceCount += inputDeviceCount + 1; /* assume there is a WAVE_MAPPER */ + + outputDeviceCount = waveOutGetNumDevs(); + if( outputDeviceCount > 0 ) + maximumPossibleDeviceCount += outputDeviceCount + 1; /* assume there is a WAVE_MAPPER */ + + + if( maximumPossibleDeviceCount > 0 ){ + + (*hostApi)->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory( + winMmeHostApi->allocations, sizeof(PaDeviceInfo*) * maximumPossibleDeviceCount ); + if( !(*hostApi)->deviceInfos ) { result = paInsufficientMemory; goto error; } - wmmeStreamData->outputBuffers[i].dwBufferLength = wmmeStreamData->bytesPerHostOutputBuffer; - wmmeStreamData->outputBuffers[i].dwUser = i; - if( (mmresult = waveOutPrepareHeader( wmmeStreamData->hWaveOut, &wmmeStreamData->outputBuffers[i], sizeof(WAVEHDR) )) != MMSYSERR_NOERROR ) + + /* allocate all device info structs in a contiguous block */ + deviceInfoArray = (PaWinMmeDeviceInfo*)PaUtil_GroupAllocateMemory( + winMmeHostApi->allocations, sizeof(PaWinMmeDeviceInfo) * maximumPossibleDeviceCount ); + if( !deviceInfoArray ) { - result = paHostError; - sPaHostError = mmresult; + result = paInsufficientMemory; goto error; } - } - return result; -error: - return result; -} -/*******************************************************************/ -PaError PaHost_GetTotalBufferFrames( internalPortAudioStream *stream ) -{ - PaWMMEStreamData *wmmeStreamData = (PaWMMEStreamData *) stream->past_DeviceData; - return wmmeStreamData->numHostBuffers * wmmeStreamData->framesPerHostBuffer; -} -/******************************************************************* - * Determine number of WAVE Buffers - * and how many User Buffers we can put into each WAVE buffer. - */ -static void PaHost_CalcNumHostBuffers( internalPortAudioStream *stream ) -{ - PaWMMEStreamData *wmmeStreamData = (PaWMMEStreamData *) stream->past_DeviceData; - unsigned int minNumBuffers; - int minframesPerHostBuffer; - int maxframesPerHostBuffer; - int minTotalFrames; - int userBuffersPerHostBuffer; - int framesPerHostBuffer; - int numHostBuffers; - - /* Calculate minimum and maximum sizes based on timing and sample rate. */ - minframesPerHostBuffer = (int) (PA_MIN_MSEC_PER_HOST_BUFFER * stream->past_SampleRate * 0.001); - minframesPerHostBuffer = (minframesPerHostBuffer + 7) & ~7; - DBUG(("PaHost_CalcNumHostBuffers: minframesPerHostBuffer = %d\n", minframesPerHostBuffer )); - maxframesPerHostBuffer = (int) (PA_MAX_MSEC_PER_HOST_BUFFER * stream->past_SampleRate * 0.001); - maxframesPerHostBuffer = (maxframesPerHostBuffer + 7) & ~7; - DBUG(("PaHost_CalcNumHostBuffers: maxframesPerHostBuffer = %d\n", maxframesPerHostBuffer )); - /* Determine number of user buffers based on minimum latency. */ - minNumBuffers = Pa_GetMinNumBuffers( stream->past_FramesPerUserBuffer, stream->past_SampleRate ); - stream->past_NumUserBuffers = ( minNumBuffers > stream->past_NumUserBuffers ) ? minNumBuffers : stream->past_NumUserBuffers; - DBUG(("PaHost_CalcNumHostBuffers: min past_NumUserBuffers = %d\n", stream->past_NumUserBuffers )); - minTotalFrames = stream->past_NumUserBuffers * stream->past_FramesPerUserBuffer; - /* We cannot make the WAVE buffers too small because they may not get serviced quickly enough. */ - if( (int) stream->past_FramesPerUserBuffer < minframesPerHostBuffer ) - { - userBuffersPerHostBuffer = - (minframesPerHostBuffer + stream->past_FramesPerUserBuffer - 1) / - stream->past_FramesPerUserBuffer; - } - else - { - userBuffersPerHostBuffer = 1; - } - framesPerHostBuffer = stream->past_FramesPerUserBuffer * userBuffersPerHostBuffer; - /* Calculate number of WAVE buffers needed. Round up to cover minTotalFrames. */ - numHostBuffers = (minTotalFrames + framesPerHostBuffer - 1) / framesPerHostBuffer; - /* Make sure we have anough WAVE buffers. */ - if( numHostBuffers < PA_MIN_NUM_HOST_BUFFERS) - { - numHostBuffers = PA_MIN_NUM_HOST_BUFFERS; - } - else if( (numHostBuffers > PA_MAX_NUM_HOST_BUFFERS) && - ((int) stream->past_FramesPerUserBuffer < (maxframesPerHostBuffer/2) ) ) - { - /* If we have too many WAVE buffers, try to put more user buffers in a wave buffer. */ - while(numHostBuffers > PA_MAX_NUM_HOST_BUFFERS) + winMmeHostApi->winMmeDeviceIds = (UINT*)PaUtil_GroupAllocateMemory( + winMmeHostApi->allocations, sizeof(int) * maximumPossibleDeviceCount ); + if( !winMmeHostApi->winMmeDeviceIds ) { - userBuffersPerHostBuffer += 1; - framesPerHostBuffer = stream->past_FramesPerUserBuffer * userBuffersPerHostBuffer; - numHostBuffers = (minTotalFrames + framesPerHostBuffer - 1) / framesPerHostBuffer; - /* If we have gone too far, back up one. */ - if( (framesPerHostBuffer > maxframesPerHostBuffer) || - (numHostBuffers < PA_MAX_NUM_HOST_BUFFERS) ) - { - userBuffersPerHostBuffer -= 1; - framesPerHostBuffer = stream->past_FramesPerUserBuffer * userBuffersPerHostBuffer; - numHostBuffers = (minTotalFrames + framesPerHostBuffer - 1) / framesPerHostBuffer; - break; - } + result = paInsufficientMemory; + goto error; } - } - wmmeStreamData->userBuffersPerHostBuffer = userBuffersPerHostBuffer; - wmmeStreamData->framesPerHostBuffer = framesPerHostBuffer; - wmmeStreamData->numHostBuffers = numHostBuffers; - DBUG(("PaHost_CalcNumHostBuffers: userBuffersPerHostBuffer = %d\n", wmmeStreamData->userBuffersPerHostBuffer )); - DBUG(("PaHost_CalcNumHostBuffers: numHostBuffers = %d\n", wmmeStreamData->numHostBuffers )); - DBUG(("PaHost_CalcNumHostBuffers: framesPerHostBuffer = %d\n", wmmeStreamData->framesPerHostBuffer )); - DBUG(("PaHost_CalcNumHostBuffers: past_NumUserBuffers = %d\n", stream->past_NumUserBuffers )); -} -/*******************************************************************/ -PaError PaHost_OpenStream( internalPortAudioStream *stream ) -{ - PaError result = paNoError; - PaWMMEStreamData *wmmeStreamData; + GetDefaultLatencies( &defaultLowLatency, &defaultHighLatency ); - result = PaHost_AllocateWMMEStreamData( stream ); - if( result != paNoError ) return result; + if( inputDeviceCount > 0 ){ + /* -1 is the WAVE_MAPPER */ + for( i = -1; i < inputDeviceCount; ++i ){ + UINT winMmeDeviceId = (UINT)((i==-1) ? WAVE_MAPPER : i); + PaWinMmeDeviceInfo *wmmeDeviceInfo = &deviceInfoArray[ (*hostApi)->info.deviceCount ]; + PaDeviceInfo *deviceInfo = &wmmeDeviceInfo->inheritedDeviceInfo; + deviceInfo->structVersion = 2; + deviceInfo->hostApi = hostApiIndex; - wmmeStreamData = PaHost_GetWMMEStreamData( stream ); + deviceInfo->maxInputChannels = 0; + deviceInfo->maxOutputChannels = 0; - /* Figure out how user buffers fit into WAVE buffers. */ - PaHost_CalcNumHostBuffers( stream ); - { - int msecLatency = (int) ((PaHost_GetTotalBufferFrames(stream) * 1000) / stream->past_SampleRate); - DBUG(("PortAudio on WMME - Latency = %d frames, %d msec\n", PaHost_GetTotalBufferFrames(stream), msecLatency )); - } - InitializeCriticalSection( &wmmeStreamData->streamLock ); - wmmeStreamData->streamLockInited = 1; + deviceInfo->defaultLowInputLatency = defaultLowLatency; + deviceInfo->defaultLowOutputLatency = defaultLowLatency; + deviceInfo->defaultHighInputLatency = defaultHighLatency; + deviceInfo->defaultHighOutputLatency = defaultHighLatency; -#if (PA_USE_TIMER_CALLBACK == 0) - wmmeStreamData->bufferEventInited = 0; - wmmeStreamData->bufferEvent = CreateEvent( NULL, FALSE, FALSE, NULL ); - if( wmmeStreamData->bufferEvent == NULL ) - { - result = paHostError; - sPaHostError = GetLastError(); - goto error; - } - wmmeStreamData->bufferEventInited = 1; -#endif /* (PA_USE_TIMER_CALLBACK == 0) */ - /* ------------------ OUTPUT */ - wmmeStreamData->bytesPerUserOutputBuffer = stream->past_FramesPerUserBuffer * stream->past_NumOutputChannels * sizeof(short); - wmmeStreamData->bytesPerHostOutputBuffer = wmmeStreamData->userBuffersPerHostBuffer * wmmeStreamData->bytesPerUserOutputBuffer; - if( (stream->past_OutputDeviceID != paNoDevice) && (stream->past_NumOutputChannels > 0) ) - { - result = PaHost_OpenOutputStream( stream ); - if( result < 0 ) goto error; - } - /* ------------------ INPUT */ - wmmeStreamData->bytesPerUserInputBuffer = stream->past_FramesPerUserBuffer * stream->past_NumInputChannels * sizeof(short); - wmmeStreamData->bytesPerHostInputBuffer = wmmeStreamData->userBuffersPerHostBuffer * wmmeStreamData->bytesPerUserInputBuffer; - if( (stream->past_InputDeviceID != paNoDevice) && (stream->past_NumInputChannels > 0) ) - { - result = PaHost_OpenInputStream( stream ); - if( result < 0 ) goto error; + result = InitializeInputDeviceInfo( winMmeHostApi, wmmeDeviceInfo, + winMmeDeviceId, &deviceInfoInitializationSucceeded ); + if( result != paNoError ) + goto error; + + if( deviceInfoInitializationSucceeded ){ + if( (*hostApi)->info.defaultInputDevice == paNoDevice ) + (*hostApi)->info.defaultInputDevice = (*hostApi)->info.deviceCount; + + winMmeHostApi->winMmeDeviceIds[ (*hostApi)->info.deviceCount ] = winMmeDeviceId; + (*hostApi)->deviceInfos[ (*hostApi)->info.deviceCount ] = deviceInfo; + + winMmeHostApi->inputDeviceCount++; + (*hostApi)->info.deviceCount++; + } + } + } + + if( outputDeviceCount > 0 ){ + /* -1 is the WAVE_MAPPER */ + for( i = -1; i < outputDeviceCount; ++i ){ + UINT winMmeDeviceId = (UINT)((i==-1) ? WAVE_MAPPER : i); + PaWinMmeDeviceInfo *wmmeDeviceInfo = &deviceInfoArray[ (*hostApi)->info.deviceCount ]; + PaDeviceInfo *deviceInfo = &wmmeDeviceInfo->inheritedDeviceInfo; + deviceInfo->structVersion = 2; + deviceInfo->hostApi = hostApiIndex; + + deviceInfo->maxInputChannels = 0; + deviceInfo->maxOutputChannels = 0; + + deviceInfo->defaultLowInputLatency = defaultLowLatency; + deviceInfo->defaultLowOutputLatency = defaultLowLatency; + deviceInfo->defaultHighInputLatency = defaultHighLatency; + deviceInfo->defaultHighOutputLatency = defaultHighLatency; + + result = InitializeOutputDeviceInfo( winMmeHostApi, wmmeDeviceInfo, + winMmeDeviceId, &deviceInfoInitializationSucceeded ); + if( result != paNoError ) + goto error; + + if( deviceInfoInitializationSucceeded ){ + if( (*hostApi)->info.defaultOutputDevice == paNoDevice ) + (*hostApi)->info.defaultOutputDevice = (*hostApi)->info.deviceCount; + + winMmeHostApi->winMmeDeviceIds[ (*hostApi)->info.deviceCount ] = winMmeDeviceId; + (*hostApi)->deviceInfos[ (*hostApi)->info.deviceCount ] = deviceInfo; + + winMmeHostApi->outputDeviceCount++; + (*hostApi)->info.deviceCount++; + } + } + } } + + + InitializeDefaultDeviceIdsFromEnv( winMmeHostApi ); + + (*hostApi)->Terminate = Terminate; + (*hostApi)->OpenStream = OpenStream; + (*hostApi)->IsFormatSupported = IsFormatSupported; + + PaUtil_InitializeStreamInterface( &winMmeHostApi->callbackStreamInterface, CloseStream, StartStream, + StopStream, AbortStream, IsStreamStopped, IsStreamActive, + GetStreamTime, GetStreamCpuLoad, + PaUtil_DummyRead, PaUtil_DummyWrite, + PaUtil_DummyGetReadAvailable, PaUtil_DummyGetWriteAvailable ); - Pa_InitializeCpuUsageScalar( stream ); + PaUtil_InitializeStreamInterface( &winMmeHostApi->blockingStreamInterface, CloseStream, StartStream, + StopStream, AbortStream, IsStreamStopped, IsStreamActive, + GetStreamTime, PaUtil_DummyGetCpuLoad, + ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable ); return result; error: - PaHost_CloseStream( stream ); + if( winMmeHostApi ) + { + if( winMmeHostApi->allocations ) + { + PaUtil_FreeAllAllocations( winMmeHostApi->allocations ); + PaUtil_DestroyAllocationGroup( winMmeHostApi->allocations ); + } + + PaUtil_FreeMemory( winMmeHostApi ); + } + return result; } -/*************************************************************************/ -PaError PaHost_StartOutput( internalPortAudioStream *stream ) + + +static void Terminate( struct PaUtilHostApiRepresentation *hostApi ) { - PaError result = paNoError; - MMRESULT mmresult; - int i; - PaWMMEStreamData *wmmeStreamData = PaHost_GetWMMEStreamData( stream ); + PaWinMmeHostApiRepresentation *winMmeHostApi = (PaWinMmeHostApiRepresentation*)hostApi; + + if( winMmeHostApi->allocations ) + { + PaUtil_FreeAllAllocations( winMmeHostApi->allocations ); + PaUtil_DestroyAllocationGroup( winMmeHostApi->allocations ); + } + + PaUtil_FreeMemory( winMmeHostApi ); +} - if( wmmeStreamData == NULL ) return paInternalError; - if( stream->past_OutputDeviceID != paNoDevice ) +static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi, + const PaStreamParameters *inputParameters, + const PaStreamParameters *outputParameters, + double sampleRate ) +{ + PaWinMmeHostApiRepresentation *winMmeHostApi = (PaWinMmeHostApiRepresentation*)hostApi; + PaDeviceInfo *inputDeviceInfo, *outputDeviceInfo; + int inputChannelCount, outputChannelCount; + int inputMultipleDeviceChannelCount, outputMultipleDeviceChannelCount; + PaSampleFormat inputSampleFormat, outputSampleFormat; + PaWinMmeStreamInfo *inputStreamInfo, *outputStreamInfo; + UINT winMmeInputDeviceId, winMmeOutputDeviceId; + unsigned int i; + PaError paerror; + + /* The calls to QueryFormatSupported below are intended to detect invalid + sample rates. If we assume that the channel count and format are OK, + then the only thing that could fail is the sample rate. This isn't + strictly true, but I can't think of a better way to test that the + sample rate is valid. + */ + + if( inputParameters ) { - if( (mmresult = waveOutPause( wmmeStreamData->hWaveOut )) != MMSYSERR_NOERROR ) - { - result = paHostError; - sPaHostError = mmresult; - goto error; - } - for( i=0; inumHostBuffers; i++ ) + inputChannelCount = inputParameters->channelCount; + inputSampleFormat = inputParameters->sampleFormat; + inputStreamInfo = inputParameters->hostApiSpecificStreamInfo; + + /* all standard sample formats are supported by the buffer adapter, + this implementation doesn't support any custom sample formats */ + if( inputSampleFormat & paCustomFormat ) + return paSampleFormatNotSupported; + + if( inputParameters->device == paUseHostApiSpecificDeviceSpecification + && inputStreamInfo && (inputStreamInfo->flags & paWinMmeUseMultipleDevices) ) { - ZeroMemory( wmmeStreamData->outputBuffers[i].lpData, wmmeStreamData->outputBuffers[i].dwBufferLength ); - mmresult = waveOutWrite( wmmeStreamData->hWaveOut, &wmmeStreamData->outputBuffers[i], sizeof(WAVEHDR) ); - if( mmresult != MMSYSERR_NOERROR ) + inputMultipleDeviceChannelCount = 0; + for( i=0; i< inputStreamInfo->deviceCount; ++i ) { - result = paHostError; - sPaHostError = mmresult; - goto error; + inputMultipleDeviceChannelCount += inputStreamInfo->devices[i].channelCount; + + inputDeviceInfo = hostApi->deviceInfos[ inputStreamInfo->devices[i].device ]; + + /* check that input device can support inputChannelCount */ + if( inputStreamInfo->devices[i].channelCount <= 0 + || inputStreamInfo->devices[i].channelCount > inputDeviceInfo->maxInputChannels ) + return paInvalidChannelCount; + + /* test for valid sample rate, see comment above */ + winMmeInputDeviceId = LocalDeviceIndexToWinMmeDeviceId( winMmeHostApi, inputStreamInfo->devices[i].device ); + paerror = QueryFormatSupported( inputDeviceInfo, QueryInputWaveFormatEx, winMmeInputDeviceId, inputStreamInfo->devices[i].channelCount, sampleRate ); + if( paerror != paNoError ) + return paInvalidSampleRate; } - stream->past_FrameCount += wmmeStreamData->framesPerHostBuffer; + + if( inputMultipleDeviceChannelCount != inputChannelCount ) + return paIncompatibleHostApiSpecificStreamInfo; } - wmmeStreamData->currentOutputBuffer = 0; - if( (mmresult = waveOutRestart( wmmeStreamData->hWaveOut )) != MMSYSERR_NOERROR ) + else { - result = paHostError; - sPaHostError = mmresult; - goto error; + if( inputStreamInfo && (inputStreamInfo->flags & paWinMmeUseMultipleDevices) ) + return paIncompatibleHostApiSpecificStreamInfo; /* paUseHostApiSpecificDeviceSpecification was not supplied as the input device */ + + inputDeviceInfo = hostApi->deviceInfos[ inputParameters->device ]; + + /* check that input device can support inputChannelCount */ + if( inputChannelCount > inputDeviceInfo->maxInputChannels ) + return paInvalidChannelCount; + + /* test for valid sample rate, see comment above */ + winMmeInputDeviceId = LocalDeviceIndexToWinMmeDeviceId( winMmeHostApi, inputParameters->device ); + paerror = QueryFormatSupported( inputDeviceInfo, QueryInputWaveFormatEx, winMmeInputDeviceId, inputChannelCount, sampleRate ); + if( paerror != paNoError ) + return paInvalidSampleRate; } } -error: - DBUG(("PaHost_StartOutput: wave returned mmresult = 0x%X.\n", mmresult)); - return result; -} -/*************************************************************************/ -PaError PaHost_StartInput( internalPortAudioStream *internalStream ) -{ - PaError result = paNoError; - MMRESULT mmresult; - int i; - PaWMMEStreamData *wmmeStreamData = PaHost_GetWMMEStreamData( internalStream ); + if( outputParameters ) + { + outputChannelCount = outputParameters->channelCount; + outputSampleFormat = outputParameters->sampleFormat; + outputStreamInfo = outputParameters->hostApiSpecificStreamInfo; - if( wmmeStreamData == NULL ) return paInternalError; + /* all standard sample formats are supported by the buffer adapter, + this implementation doesn't support any custom sample formats */ + if( outputSampleFormat & paCustomFormat ) + return paSampleFormatNotSupported; - if( internalStream->past_InputDeviceID != paNoDevice ) - { - for( i=0; inumHostBuffers; i++ ) + if( outputParameters->device == paUseHostApiSpecificDeviceSpecification + && outputStreamInfo && (outputStreamInfo->flags & paWinMmeUseMultipleDevices) ) { - mmresult = waveInAddBuffer( wmmeStreamData->hWaveIn, &wmmeStreamData->inputBuffers[i], sizeof(WAVEHDR) ); - if( mmresult != MMSYSERR_NOERROR ) + outputMultipleDeviceChannelCount = 0; + for( i=0; i< outputStreamInfo->deviceCount; ++i ) { - result = paHostError; - sPaHostError = mmresult; - goto error; + outputMultipleDeviceChannelCount += outputStreamInfo->devices[i].channelCount; + + outputDeviceInfo = hostApi->deviceInfos[ outputStreamInfo->devices[i].device ]; + + /* check that output device can support outputChannelCount */ + if( outputStreamInfo->devices[i].channelCount <= 0 + || outputStreamInfo->devices[i].channelCount > outputDeviceInfo->maxOutputChannels ) + return paInvalidChannelCount; + + /* test for valid sample rate, see comment above */ + winMmeOutputDeviceId = LocalDeviceIndexToWinMmeDeviceId( winMmeHostApi, outputStreamInfo->devices[i].device ); + paerror = QueryFormatSupported( outputDeviceInfo, QueryOutputWaveFormatEx, winMmeOutputDeviceId, outputStreamInfo->devices[i].channelCount, sampleRate ); + if( paerror != paNoError ) + return paInvalidSampleRate; } + + if( outputMultipleDeviceChannelCount != outputChannelCount ) + return paIncompatibleHostApiSpecificStreamInfo; } - wmmeStreamData->currentInputBuffer = 0; - mmresult = waveInStart( wmmeStreamData->hWaveIn ); - DBUG(("Pa_StartStream: waveInStart returned = 0x%X.\n", mmresult)); - if( mmresult != MMSYSERR_NOERROR ) + else { - result = paHostError; - sPaHostError = mmresult; - goto error; + if( outputStreamInfo && (outputStreamInfo->flags & paWinMmeUseMultipleDevices) ) + return paIncompatibleHostApiSpecificStreamInfo; /* paUseHostApiSpecificDeviceSpecification was not supplied as the output device */ + + outputDeviceInfo = hostApi->deviceInfos[ outputParameters->device ]; + + /* check that output device can support outputChannelCount */ + if( outputChannelCount > outputDeviceInfo->maxOutputChannels ) + return paInvalidChannelCount; + + /* test for valid sample rate, see comment above */ + winMmeOutputDeviceId = LocalDeviceIndexToWinMmeDeviceId( winMmeHostApi, outputParameters->device ); + paerror = QueryFormatSupported( outputDeviceInfo, QueryOutputWaveFormatEx, winMmeOutputDeviceId, outputChannelCount, sampleRate ); + if( paerror != paNoError ) + return paInvalidSampleRate; } } + + /* + - if a full duplex stream is requested, check that the combination + of input and output parameters is supported -error: - return result; -} -/*************************************************************************/ -PaError PaHost_StartEngine( internalPortAudioStream *stream ) -{ - PaError result = paNoError; - PaWMMEStreamData *wmmeStreamData = PaHost_GetWMMEStreamData( stream ); -#if PA_USE_TIMER_CALLBACK - int resolution; - int bufsPerTimerCallback; - int msecPerBuffer; -#endif /* PA_USE_TIMER_CALLBACK */ - - if( wmmeStreamData == NULL ) return paInternalError; - - stream->past_StopSoon = 0; - stream->past_StopNow = 0; - stream->past_IsActive = 1; - wmmeStreamData->framesPlayed = 0.0; - wmmeStreamData->lastPosition = 0; -#if PA_TRACE_START_STOP - AddTraceMessage( "PaHost_StartEngine: TimeSlice() returned ", result ); -#endif -#if PA_USE_TIMER_CALLBACK - /* Create timer that will wake us up so we can fill the DSound buffer. */ - bufsPerTimerCallback = wmmeStreamData->numHostBuffers/4; - if( bufsPerTimerCallback < 1 ) bufsPerTimerCallback = 1; - if( bufsPerTimerCallback < 1 ) bufsPerTimerCallback = 1; - msecPerBuffer = (1000 * bufsPerTimerCallback * - wmmeStreamData->userBuffersPerHostBuffer * - internalStream->past_FramesPerUserBuffer ) / (int) internalStream->past_SampleRate; - if( msecPerBuffer < 10 ) msecPerBuffer = 10; - else if( msecPerBuffer > 100 ) msecPerBuffer = 100; - resolution = msecPerBuffer/4; - wmmeStreamData->timerID = timeSetEvent( msecPerBuffer, resolution, - (LPTIMECALLBACK) Pa_TimerCallback, - (DWORD) stream, TIME_PERIODIC ); - if( wmmeStreamData->timerID == 0 ) - { - result = paHostError; - sPaHostError = GetLastError();; - goto error; - } -#else /* PA_USE_TIMER_CALLBACK */ - ResetEvent( wmmeStreamData->abortEvent ); - /* Create thread that waits for audio buffers to be ready for processing. */ - wmmeStreamData->engineThread = CreateThread( 0, 0, WinMMPa_OutputThreadProc, stream, 0, &wmmeStreamData->engineThreadID ); - if( wmmeStreamData->engineThread == NULL ) - { - result = paHostError; - sPaHostError = GetLastError();; - goto error; - } -#if PA_TRACE_START_STOP - AddTraceMessage( "PaHost_StartEngine: thread ", (int) wmmeStreamData->engineThread ); -#endif - /* I used to pass the thread which was failing. I now pass GetCurrentProcess(). - * This fix could improve latency for some applications. It could also result in CPU - * starvation if the callback did too much processing. - * I also added result checks, so we might see more failures at initialization. - * Thanks to Alberto di Bene for spotting this. - */ - if( !SetPriorityClass( GetCurrentProcess(), HIGH_PRIORITY_CLASS ) ) /* PLB20010816 */ - { - result = paHostError; - sPaHostError = GetLastError();; - goto error; - } - if( !SetThreadPriority( wmmeStreamData->engineThread, THREAD_PRIORITY_HIGHEST ) ) - { - result = paHostError; - sPaHostError = GetLastError();; - goto error; - } -#endif + - check that the device supports sampleRate -error: - return result; + for mme all we can do is test that the input and output devices + support the requested sample rate and number of channels. we + cannot test for full duplex compatibility. + */ + + return paFormatIsSupported; } -/*************************************************************************/ -PaError PaHost_StopEngine( internalPortAudioStream *internalStream, int abort ) -{ - int timeOut; - PaWMMEStreamData *wmmeStreamData = PaHost_GetWMMEStreamData( internalStream ); - if( wmmeStreamData == NULL ) return paNoError; - /* Tell background thread to stop generating more data and to let current data play out. */ - internalStream->past_StopSoon = 1; - /* If aborting, tell background thread to stop NOW! */ - if( abort ) internalStream->past_StopNow = 1; - /* Calculate timeOut longer than longest time it could take to play all buffers. */ - timeOut = (DWORD) (1500.0 * PaHost_GetTotalBufferFrames( internalStream ) / internalStream->past_SampleRate); - if( timeOut < MIN_TIMEOUT_MSEC ) timeOut = MIN_TIMEOUT_MSEC; +static void SelectBufferSizeAndCount( unsigned long baseBufferSize, + unsigned long requestedLatency, + unsigned long baseBufferCount, unsigned long minimumBufferCount, + unsigned long maximumBufferSize, unsigned long *hostBufferSize, + unsigned long *hostBufferCount ) +{ + unsigned long sizeMultiplier, bufferCount, latency; + unsigned long nextLatency, nextBufferSize; + int baseBufferSizeIsPowerOfTwo; + + sizeMultiplier = 1; + bufferCount = baseBufferCount; + + /* count-1 below because latency is always determined by one less + than the total number of buffers. + */ + latency = (baseBufferSize * sizeMultiplier) * (bufferCount-1); -#if PA_USE_TIMER_CALLBACK - if( (internalStream->past_OutputDeviceID != paNoDevice) && - internalStream->past_IsActive && - (wmmeStreamData->timerID != 0) ) + if( latency > requestedLatency ) { - /* Wait for IsActive to drop. */ - while( (internalStream->past_IsActive) && (timeOut > 0) ) + + /* reduce number of buffers without falling below suggested latency */ + + nextLatency = (baseBufferSize * sizeMultiplier) * (bufferCount-2); + while( bufferCount > minimumBufferCount && nextLatency >= requestedLatency ) { - Sleep(10); - timeOut -= 10; + --bufferCount; + nextLatency = (baseBufferSize * sizeMultiplier) * (bufferCount-2); } - timeKillEvent( wmmeStreamData->timerID ); /* Stop callback timer. */ - wmmeStreamData->timerID = 0; - } -#else /* PA_USE_TIMER_CALLBACK */ -#if PA_TRACE_START_STOP - AddTraceMessage( "PaHost_StopEngine: thread ", (int) wmmeStreamData->engineThread ); -#endif - if( (internalStream->past_OutputDeviceID != paNoDevice) && - (internalStream->past_IsActive) && - (wmmeStreamData->engineThread != NULL) ) - { - DWORD got; - /* Tell background thread to stop generating more data and to let current data play out. */ - DBUG(("PaHost_StopEngine: waiting for background thread.\n")); - got = WaitForSingleObject( wmmeStreamData->engineThread, timeOut ); - if( got == WAIT_TIMEOUT ) + + }else if( latency < requestedLatency ){ + + baseBufferSizeIsPowerOfTwo = (! (baseBufferSize & (baseBufferSize - 1))); + if( baseBufferSizeIsPowerOfTwo ){ + + /* double size of buffers without exceeding requestedLatency */ + + nextBufferSize = (baseBufferSize * (sizeMultiplier*2)); + nextLatency = nextBufferSize * (bufferCount-1); + while( nextBufferSize <= maximumBufferSize + && nextLatency < requestedLatency ) + { + sizeMultiplier *= 2; + nextBufferSize = (baseBufferSize * (sizeMultiplier*2)); + nextLatency = nextBufferSize * (bufferCount-1); + } + + }else{ + + /* increase size of buffers upto first excess of requestedLatency */ + + nextBufferSize = (baseBufferSize * (sizeMultiplier+1)); + nextLatency = nextBufferSize * (bufferCount-1); + while( nextBufferSize <= maximumBufferSize + && nextLatency < requestedLatency ) + { + ++sizeMultiplier; + nextBufferSize = (baseBufferSize * (sizeMultiplier+1)); + nextLatency = nextBufferSize * (bufferCount-1); + } + + if( nextLatency < requestedLatency ) + ++sizeMultiplier; + } + + /* increase number of buffers until requestedLatency is reached */ + + latency = (baseBufferSize * sizeMultiplier) * (bufferCount-1); + while( latency < requestedLatency ) { - ERR_RPT(("PaHost_StopEngine: timed out while waiting for background thread to finish.\n")); - return paTimedOut; + ++bufferCount; + latency = (baseBufferSize * sizeMultiplier) * (bufferCount-1); } - CloseHandle( wmmeStreamData->engineThread ); - wmmeStreamData->engineThread = NULL; } -#endif /* PA_USE_TIMER_CALLBACK */ - internalStream->past_IsActive = 0; - return paNoError; + *hostBufferSize = baseBufferSize * sizeMultiplier; + *hostBufferCount = bufferCount; } -/*************************************************************************/ -PaError PaHost_StopInput( internalPortAudioStream *stream, int abort ) + + +static void ReselectBufferCount( unsigned long bufferSize, + unsigned long requestedLatency, + unsigned long baseBufferCount, unsigned long minimumBufferCount, + unsigned long *hostBufferCount ) { - MMRESULT mmresult; - PaWMMEStreamData *wmmeStreamData = PaHost_GetWMMEStreamData( stream ); + unsigned long bufferCount, latency; + unsigned long nextLatency; + + bufferCount = baseBufferCount; - if( wmmeStreamData == NULL ) return paNoError; /* FIXME: why return paNoError? */ - (void) abort; /* unused parameter */ + /* count-1 below because latency is always determined by one less + than the total number of buffers. + */ + latency = bufferSize * (bufferCount-1); - if( wmmeStreamData->hWaveIn != NULL ) + if( latency > requestedLatency ) { - mmresult = waveInReset( wmmeStreamData->hWaveIn ); - if( mmresult != MMSYSERR_NOERROR ) + /* reduce number of buffers without falling below suggested latency */ + + nextLatency = bufferSize * (bufferCount-2); + while( bufferCount > minimumBufferCount && nextLatency >= requestedLatency ) { - sPaHostError = mmresult; - return paHostError; + --bufferCount; + nextLatency = bufferSize * (bufferCount-2); } - } - return paNoError; -} -/*************************************************************************/ -PaError PaHost_StopOutput( internalPortAudioStream *internalStream, int abort ) -{ - MMRESULT mmresult; - PaWMMEStreamData *wmmeStreamData = PaHost_GetWMMEStreamData( internalStream ); - if( wmmeStreamData == NULL ) return paNoError; /* FIXME: why return paNoError? */ - (void) abort; /* unused parameter */ + }else if( latency < requestedLatency ){ -#if PA_TRACE_START_STOP - AddTraceMessage( "PaHost_StopOutput: hWaveOut ", (int) wmmeStreamData->hWaveOut ); -#endif - if( wmmeStreamData->hWaveOut != NULL ) - { - mmresult = waveOutReset( wmmeStreamData->hWaveOut ); - if( mmresult != MMSYSERR_NOERROR ) + /* increase number of buffers until requestedLatency is reached */ + + latency = bufferSize * (bufferCount-1); + while( latency < requestedLatency ) { - sPaHostError = mmresult; - return paHostError; - } + ++bufferCount; + latency = bufferSize * (bufferCount-1); + } } - return paNoError; + + *hostBufferCount = bufferCount; } -/*******************************************************************/ -PaError PaHost_CloseStream( internalPortAudioStream *stream ) -{ - int i; - PaWMMEStreamData *wmmeStreamData = PaHost_GetWMMEStreamData( stream ); - if( stream == NULL ) return paBadStreamPtr; - if( wmmeStreamData == NULL ) return paNoError; /* FIXME: why return no error? */ -#if PA_TRACE_START_STOP - AddTraceMessage( "PaHost_CloseStream: hWaveOut ", (int) wmmeStreamData->hWaveOut ); -#endif - /* Free data and device for output. */ - if( wmmeStreamData->hWaveOut ) +/* CalculateBufferSettings() fills the framesPerHostInputBuffer, hostInputBufferCount, + framesPerHostOutputBuffer and hostOutputBufferCount parameters based on the values + of the other parameters. +*/ + +static PaError CalculateBufferSettings( + unsigned long *framesPerHostInputBuffer, unsigned long *hostInputBufferCount, + unsigned long *framesPerHostOutputBuffer, unsigned long *hostOutputBufferCount, + int inputChannelCount, PaSampleFormat hostInputSampleFormat, + PaTime suggestedInputLatency, PaWinMmeStreamInfo *inputStreamInfo, + int outputChannelCount, PaSampleFormat hostOutputSampleFormat, + PaTime suggestedOutputLatency, PaWinMmeStreamInfo *outputStreamInfo, + double sampleRate, unsigned long framesPerBuffer ) +{ + PaError result = paNoError; + int effectiveInputChannelCount, effectiveOutputChannelCount; + int hostInputFrameSize = 0; + unsigned int i; + + if( inputChannelCount > 0 ) { - if( wmmeStreamData->outputBuffers ) + int hostInputSampleSize = Pa_GetSampleSize( hostInputSampleFormat ); + if( hostInputSampleSize < 0 ) { - for( i=0; inumHostBuffers; i++ ) - { - waveOutUnprepareHeader( wmmeStreamData->hWaveOut, &wmmeStreamData->outputBuffers[i], sizeof(WAVEHDR) ); - PaHost_FreeTrackedMemory( wmmeStreamData->outputBuffers[i].lpData ); /* MEM */ - } - PaHost_FreeTrackedMemory( wmmeStreamData->outputBuffers ); /* MEM */ + result = hostInputSampleSize; + goto error; } - waveOutClose( wmmeStreamData->hWaveOut ); - } - /* Free data and device for input. */ - if( wmmeStreamData->hWaveIn ) - { - if( wmmeStreamData->inputBuffers ) + + if( inputStreamInfo + && ( inputStreamInfo->flags & paWinMmeUseMultipleDevices ) ) { - for( i=0; inumHostBuffers; i++ ) + /* set effectiveInputChannelCount to the largest number of + channels on any one device. + */ + effectiveInputChannelCount = 0; + for( i=0; i< inputStreamInfo->deviceCount; ++i ) { - waveInUnprepareHeader( wmmeStreamData->hWaveIn, &wmmeStreamData->inputBuffers[i], sizeof(WAVEHDR) ); - PaHost_FreeTrackedMemory( wmmeStreamData->inputBuffers[i].lpData ); /* MEM */ + if( inputStreamInfo->devices[i].channelCount > effectiveInputChannelCount ) + effectiveInputChannelCount = inputStreamInfo->devices[i].channelCount; } - PaHost_FreeTrackedMemory( wmmeStreamData->inputBuffers ); /* MEM */ } - waveInClose( wmmeStreamData->hWaveIn ); - } -#if (PA_USE_TIMER_CALLBACK == 0) - if( wmmeStreamData->abortEventInited ) CloseHandle( wmmeStreamData->abortEvent ); - if( wmmeStreamData->bufferEventInited ) CloseHandle( wmmeStreamData->bufferEvent ); -#endif - if( wmmeStreamData->streamLockInited ) - DeleteCriticalSection( &wmmeStreamData->streamLock ); - - PaHost_FreeWMMEStreamData( stream ); + else + { + effectiveInputChannelCount = inputChannelCount; + } + + hostInputFrameSize = hostInputSampleSize * effectiveInputChannelCount; + + if( inputStreamInfo + && ( inputStreamInfo->flags & paWinMmeUseLowLevelLatencyParameters ) ) + { + if( inputStreamInfo->bufferCount <= 0 + || inputStreamInfo->framesPerBuffer <= 0 ) + { + result = paIncompatibleHostApiSpecificStreamInfo; + goto error; + } + + *framesPerHostInputBuffer = inputStreamInfo->framesPerBuffer; + *hostInputBufferCount = inputStreamInfo->bufferCount; + } + else + { + unsigned long hostBufferSizeBytes, hostBufferCount; + unsigned long minimumBufferCount = (outputChannelCount > 0) + ? PA_MME_MIN_HOST_INPUT_BUFFER_COUNT_FULL_DUPLEX_ + : PA_MME_MIN_HOST_INPUT_BUFFER_COUNT_HALF_DUPLEX_; + + unsigned long maximumBufferSize = (long) ((PA_MME_MAX_HOST_BUFFER_SECS_ * sampleRate) * hostInputFrameSize); + if( maximumBufferSize > PA_MME_MAX_HOST_BUFFER_BYTES_ ) + maximumBufferSize = PA_MME_MAX_HOST_BUFFER_BYTES_; + + /* compute the following in bytes, then convert back to frames */ + + SelectBufferSizeAndCount( + ((framesPerBuffer == paFramesPerBufferUnspecified) + ? PA_MME_MIN_HOST_BUFFER_FRAMES_WHEN_UNSPECIFIED_ + : framesPerBuffer ) * hostInputFrameSize, /* baseBufferSize */ + ((unsigned long)(suggestedInputLatency * sampleRate)) * hostInputFrameSize, /* suggestedLatency */ + 4, /* baseBufferCount */ + minimumBufferCount, maximumBufferSize, + &hostBufferSizeBytes, &hostBufferCount ); + + *framesPerHostInputBuffer = hostBufferSizeBytes / hostInputFrameSize; + *hostInputBufferCount = hostBufferCount; + } + } + else + { + *framesPerHostInputBuffer = 0; + *hostInputBufferCount = 0; + } + + if( outputChannelCount > 0 ) + { + if( outputStreamInfo + && ( outputStreamInfo->flags & paWinMmeUseLowLevelLatencyParameters ) ) + { + if( outputStreamInfo->bufferCount <= 0 + || outputStreamInfo->framesPerBuffer <= 0 ) + { + result = paIncompatibleHostApiSpecificStreamInfo; + goto error; + } + + *framesPerHostOutputBuffer = outputStreamInfo->framesPerBuffer; + *hostOutputBufferCount = outputStreamInfo->bufferCount; + + + if( inputChannelCount > 0 ) /* full duplex */ + { + if( *framesPerHostInputBuffer != *framesPerHostOutputBuffer ) + { + if( inputStreamInfo + && ( inputStreamInfo->flags & paWinMmeUseLowLevelLatencyParameters ) ) + { + /* a custom StreamInfo was used for specifying both input + and output buffer sizes, the larger buffer size + must be a multiple of the smaller buffer size */ + + if( *framesPerHostInputBuffer < *framesPerHostOutputBuffer ) + { + if( *framesPerHostOutputBuffer % *framesPerHostInputBuffer != 0 ) + { + result = paIncompatibleHostApiSpecificStreamInfo; + goto error; + } + } + else + { + assert( *framesPerHostInputBuffer > *framesPerHostOutputBuffer ); + if( *framesPerHostInputBuffer % *framesPerHostOutputBuffer != 0 ) + { + result = paIncompatibleHostApiSpecificStreamInfo; + goto error; + } + } + } + else + { + /* a custom StreamInfo was not used for specifying the input buffer size, + so use the output buffer size, and approximately the same latency. */ + + *framesPerHostInputBuffer = *framesPerHostOutputBuffer; + *hostInputBufferCount = (((unsigned long)(suggestedInputLatency * sampleRate)) / *framesPerHostInputBuffer) + 1; + + if( *hostInputBufferCount < PA_MME_MIN_HOST_INPUT_BUFFER_COUNT_FULL_DUPLEX_ ) + *hostInputBufferCount = PA_MME_MIN_HOST_INPUT_BUFFER_COUNT_FULL_DUPLEX_; + } + } + } + } + else + { + unsigned long hostBufferSizeBytes, hostBufferCount; + unsigned long minimumBufferCount = PA_MME_MIN_HOST_OUTPUT_BUFFER_COUNT_; + unsigned long maximumBufferSize; + int hostOutputFrameSize; + int hostOutputSampleSize; + + hostOutputSampleSize = Pa_GetSampleSize( hostOutputSampleFormat ); + if( hostOutputSampleSize < 0 ) + { + result = hostOutputSampleSize; + goto error; + } + + if( outputStreamInfo + && ( outputStreamInfo->flags & paWinMmeUseMultipleDevices ) ) + { + /* set effectiveOutputChannelCount to the largest number of + channels on any one device. + */ + effectiveOutputChannelCount = 0; + for( i=0; i< outputStreamInfo->deviceCount; ++i ) + { + if( outputStreamInfo->devices[i].channelCount > effectiveOutputChannelCount ) + effectiveOutputChannelCount = outputStreamInfo->devices[i].channelCount; + } + } + else + { + effectiveOutputChannelCount = outputChannelCount; + } + + hostOutputFrameSize = hostOutputSampleSize * effectiveOutputChannelCount; + + maximumBufferSize = (long) ((PA_MME_MAX_HOST_BUFFER_SECS_ * sampleRate) * hostOutputFrameSize); + if( maximumBufferSize > PA_MME_MAX_HOST_BUFFER_BYTES_ ) + maximumBufferSize = PA_MME_MAX_HOST_BUFFER_BYTES_; + + + /* compute the following in bytes, then convert back to frames */ + + SelectBufferSizeAndCount( + ((framesPerBuffer == paFramesPerBufferUnspecified) + ? PA_MME_MIN_HOST_BUFFER_FRAMES_WHEN_UNSPECIFIED_ + : framesPerBuffer ) * hostOutputFrameSize, /* baseBufferSize */ + ((unsigned long)(suggestedOutputLatency * sampleRate)) * hostOutputFrameSize, /* suggestedLatency */ + 4, /* baseBufferCount */ + minimumBufferCount, + maximumBufferSize, + &hostBufferSizeBytes, &hostBufferCount ); + + *framesPerHostOutputBuffer = hostBufferSizeBytes / hostOutputFrameSize; + *hostOutputBufferCount = hostBufferCount; + + + if( inputChannelCount > 0 ) + { + /* ensure that both input and output buffer sizes are the same. + if they don't match at this stage, choose the smallest one + and use that for input and output + */ + + if( *framesPerHostOutputBuffer != *framesPerHostInputBuffer ) + { + if( framesPerHostInputBuffer < framesPerHostOutputBuffer ) + { + unsigned long framesPerHostBuffer = *framesPerHostInputBuffer; + + minimumBufferCount = PA_MME_MIN_HOST_OUTPUT_BUFFER_COUNT_; + ReselectBufferCount( + framesPerHostBuffer * hostOutputFrameSize, /* bufferSize */ + ((unsigned long)(suggestedOutputLatency * sampleRate)) * hostOutputFrameSize, /* suggestedLatency */ + 4, /* baseBufferCount */ + minimumBufferCount, + &hostBufferCount ); + + *framesPerHostOutputBuffer = framesPerHostBuffer; + *hostOutputBufferCount = hostBufferCount; + } + else + { + unsigned long framesPerHostBuffer = *framesPerHostOutputBuffer; + + minimumBufferCount = PA_MME_MIN_HOST_INPUT_BUFFER_COUNT_FULL_DUPLEX_; + ReselectBufferCount( + framesPerHostBuffer * hostInputFrameSize, /* bufferSize */ + ((unsigned long)(suggestedInputLatency * sampleRate)) * hostInputFrameSize, /* suggestedLatency */ + 4, /* baseBufferCount */ + minimumBufferCount, + &hostBufferCount ); + + *framesPerHostInputBuffer = framesPerHostBuffer; + *hostInputBufferCount = hostBufferCount; + } + } + } + } + } + else + { + *framesPerHostOutputBuffer = 0; + *hostOutputBufferCount = 0; + } + +error: + return result; +} + + +typedef struct +{ + HANDLE bufferEvent; + void *waveHandles; + unsigned int deviceCount; + /* unsigned int channelCount; */ + WAVEHDR **waveHeaders; /* waveHeaders[device][buffer] */ + unsigned int bufferCount; + unsigned int currentBufferIndex; + unsigned int framesPerBuffer; + unsigned int framesUsedInCurrentBuffer; +}PaWinMmeSingleDirectionHandlesAndBuffers; + +/* prototypes for functions operating on PaWinMmeSingleDirectionHandlesAndBuffers */ + +static void InitializeSingleDirectionHandlesAndBuffers( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers ); +static PaError InitializeWaveHandles( PaWinMmeHostApiRepresentation *winMmeHostApi, + PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers, + unsigned long bytesPerHostSample, + double sampleRate, PaWinMmeDeviceAndChannelCount *devices, + unsigned int deviceCount, int isInput ); +static PaError TerminateWaveHandles( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers, int isInput, int currentlyProcessingAnError ); +static PaError InitializeWaveHeaders( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers, + unsigned long hostBufferCount, + PaSampleFormat hostSampleFormat, + unsigned long framesPerHostBuffer, + PaWinMmeDeviceAndChannelCount *devices, + int isInput ); +static void TerminateWaveHeaders( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers, int isInput ); + + +static void InitializeSingleDirectionHandlesAndBuffers( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers ) +{ + handlesAndBuffers->bufferEvent = 0; + handlesAndBuffers->waveHandles = 0; + handlesAndBuffers->deviceCount = 0; + handlesAndBuffers->waveHeaders = 0; + handlesAndBuffers->bufferCount = 0; +} + +static PaError InitializeWaveHandles( PaWinMmeHostApiRepresentation *winMmeHostApi, + PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers, + unsigned long bytesPerHostSample, + double sampleRate, PaWinMmeDeviceAndChannelCount *devices, + unsigned int deviceCount, int isInput ) +{ + PaError result; + MMRESULT mmresult; + unsigned long bytesPerFrame; + WAVEFORMATEX wfx; + signed int i; + + /* for error cleanup we expect that InitializeSingleDirectionHandlesAndBuffers() + has already been called to zero some fields */ + + result = CreateEventWithPaError( &handlesAndBuffers->bufferEvent, NULL, FALSE, FALSE, NULL ); + if( result != paNoError ) goto error; + + if( isInput ) + handlesAndBuffers->waveHandles = (void*)PaUtil_AllocateMemory( sizeof(HWAVEIN) * deviceCount ); + else + handlesAndBuffers->waveHandles = (void*)PaUtil_AllocateMemory( sizeof(HWAVEOUT) * deviceCount ); + if( !handlesAndBuffers->waveHandles ) + { + result = paInsufficientMemory; + goto error; + } + + handlesAndBuffers->deviceCount = deviceCount; + + for( i = 0; i < (signed int)deviceCount; ++i ) + { + if( isInput ) + ((HWAVEIN*)handlesAndBuffers->waveHandles)[i] = 0; + else + ((HWAVEOUT*)handlesAndBuffers->waveHandles)[i] = 0; + } + + wfx.wFormatTag = WAVE_FORMAT_PCM; + wfx.nSamplesPerSec = (DWORD) sampleRate; + wfx.cbSize = 0; + + for( i = 0; i < (signed int)deviceCount; ++i ) + { + UINT winMmeDeviceId; + + winMmeDeviceId = LocalDeviceIndexToWinMmeDeviceId( winMmeHostApi, devices[i].device ); + wfx.nChannels = (WORD)devices[i].channelCount; + + bytesPerFrame = wfx.nChannels * bytesPerHostSample; + + wfx.nAvgBytesPerSec = (DWORD)(bytesPerFrame * sampleRate); + wfx.nBlockAlign = (WORD)bytesPerFrame; + wfx.wBitsPerSample = (WORD)((bytesPerFrame/wfx.nChannels) * 8); + + /* REVIEW: consider not firing an event for input when a full duplex + stream is being used. this would probably depend on the + neverDropInput flag. */ + + if( isInput ) + mmresult = waveInOpen( &((HWAVEIN*)handlesAndBuffers->waveHandles)[i], winMmeDeviceId, &wfx, + (DWORD_PTR)handlesAndBuffers->bufferEvent, (DWORD_PTR)0, CALLBACK_EVENT ); + else + mmresult = waveOutOpen( &((HWAVEOUT*)handlesAndBuffers->waveHandles)[i], winMmeDeviceId, &wfx, + (DWORD_PTR)handlesAndBuffers->bufferEvent, (DWORD_PTR)0, CALLBACK_EVENT ); + + if( mmresult != MMSYSERR_NOERROR ) + { + switch( mmresult ) + { + case MMSYSERR_ALLOCATED: /* Specified resource is already allocated. */ + result = paDeviceUnavailable; + break; + case MMSYSERR_NODRIVER: /* No device driver is present. */ + result = paDeviceUnavailable; + break; + case MMSYSERR_NOMEM: /* Unable to allocate or lock memory. */ + result = paInsufficientMemory; + break; + + case MMSYSERR_BADDEVICEID: /* Specified device identifier is out of range. */ + /* falls through */ + case WAVERR_BADFORMAT: /* Attempted to open with an unsupported waveform-audio format. */ + /* falls through */ + default: + result = paUnanticipatedHostError; + if( isInput ) + { + PA_MME_SET_LAST_WAVEIN_ERROR( mmresult ); + } + else + { + PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult ); + } + } + goto error; + } + } + + return result; + +error: + TerminateWaveHandles( handlesAndBuffers, isInput, 1 /* currentlyProcessingAnError */ ); + + return result; +} + + +static PaError TerminateWaveHandles( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers, int isInput, int currentlyProcessingAnError ) +{ + PaError result = paNoError; + MMRESULT mmresult; + signed int i; + + if( handlesAndBuffers->waveHandles ) + { + for( i = handlesAndBuffers->deviceCount-1; i >= 0; --i ) + { + if( isInput ) + { + if( ((HWAVEIN*)handlesAndBuffers->waveHandles)[i] ) + mmresult = waveInClose( ((HWAVEIN*)handlesAndBuffers->waveHandles)[i] ); + else + mmresult = MMSYSERR_NOERROR; + } + else + { + if( ((HWAVEOUT*)handlesAndBuffers->waveHandles)[i] ) + mmresult = waveOutClose( ((HWAVEOUT*)handlesAndBuffers->waveHandles)[i] ); + else + mmresult = MMSYSERR_NOERROR; + } + + if( mmresult != MMSYSERR_NOERROR && + !currentlyProcessingAnError ) /* don't update the error state if we're already processing an error */ + { + result = paUnanticipatedHostError; + if( isInput ) + { + PA_MME_SET_LAST_WAVEIN_ERROR( mmresult ); + } + else + { + PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult ); + } + /* note that we don't break here, we try to continue closing devices */ + } + } + + PaUtil_FreeMemory( handlesAndBuffers->waveHandles ); + handlesAndBuffers->waveHandles = 0; + } + + if( handlesAndBuffers->bufferEvent ) + { + result = CloseHandleWithPaError( handlesAndBuffers->bufferEvent ); + handlesAndBuffers->bufferEvent = 0; + } + + return result; +} + + +static PaError InitializeWaveHeaders( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers, + unsigned long hostBufferCount, + PaSampleFormat hostSampleFormat, + unsigned long framesPerHostBuffer, + PaWinMmeDeviceAndChannelCount *devices, + int isInput ) +{ + PaError result = paNoError; + MMRESULT mmresult; + WAVEHDR *deviceWaveHeaders; + signed int i, j; + + /* for error cleanup we expect that InitializeSingleDirectionHandlesAndBuffers() + has already been called to zero some fields */ + + + /* allocate an array of pointers to arrays of wave headers, one array of + wave headers per device */ + handlesAndBuffers->waveHeaders = (WAVEHDR**)PaUtil_AllocateMemory( sizeof(WAVEHDR*) * handlesAndBuffers->deviceCount ); + if( !handlesAndBuffers->waveHeaders ) + { + result = paInsufficientMemory; + goto error; + } + + for( i = 0; i < (signed int)handlesAndBuffers->deviceCount; ++i ) + handlesAndBuffers->waveHeaders[i] = 0; + + handlesAndBuffers->bufferCount = hostBufferCount; + + for( i = 0; i < (signed int)handlesAndBuffers->deviceCount; ++i ) + { + int bufferBytes = Pa_GetSampleSize( hostSampleFormat ) * + framesPerHostBuffer * devices[i].channelCount; + if( bufferBytes < 0 ) + { + result = paInternalError; + goto error; + } + + /* Allocate an array of wave headers for device i */ + deviceWaveHeaders = (WAVEHDR *) PaUtil_AllocateMemory( sizeof(WAVEHDR)*hostBufferCount ); + if( !deviceWaveHeaders ) + { + result = paInsufficientMemory; + goto error; + } + + for( j=0; j < (signed int)hostBufferCount; ++j ) + deviceWaveHeaders[j].lpData = 0; + + handlesAndBuffers->waveHeaders[i] = deviceWaveHeaders; + + /* Allocate a buffer for each wave header */ + for( j=0; j < (signed int)hostBufferCount; ++j ) + { + deviceWaveHeaders[j].lpData = (char *)PaUtil_AllocateMemory( bufferBytes ); + if( !deviceWaveHeaders[j].lpData ) + { + result = paInsufficientMemory; + goto error; + } + deviceWaveHeaders[j].dwBufferLength = bufferBytes; + deviceWaveHeaders[j].dwUser = 0xFFFFFFFF; /* indicates that *PrepareHeader() has not yet been called, for error clean up code */ + + if( isInput ) + { + mmresult = waveInPrepareHeader( ((HWAVEIN*)handlesAndBuffers->waveHandles)[i], &deviceWaveHeaders[j], sizeof(WAVEHDR) ); + if( mmresult != MMSYSERR_NOERROR ) + { + result = paUnanticipatedHostError; + PA_MME_SET_LAST_WAVEIN_ERROR( mmresult ); + goto error; + } + } + else /* output */ + { + mmresult = waveOutPrepareHeader( ((HWAVEOUT*)handlesAndBuffers->waveHandles)[i], &deviceWaveHeaders[j], sizeof(WAVEHDR) ); + if( mmresult != MMSYSERR_NOERROR ) + { + result = paUnanticipatedHostError; + PA_MME_SET_LAST_WAVEIN_ERROR( mmresult ); + goto error; + } + } + deviceWaveHeaders[j].dwUser = devices[i].channelCount; + } + } + + return result; + +error: + TerminateWaveHeaders( handlesAndBuffers, isInput ); + + return result; +} + + +static void TerminateWaveHeaders( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers, int isInput ) +{ + signed int i, j; + WAVEHDR *deviceWaveHeaders; + + if( handlesAndBuffers->waveHeaders ) + { + for( i = handlesAndBuffers->deviceCount-1; i >= 0 ; --i ) + { + deviceWaveHeaders = handlesAndBuffers->waveHeaders[i]; /* wave headers for device i */ + if( deviceWaveHeaders ) + { + for( j = handlesAndBuffers->bufferCount-1; j >= 0; --j ) + { + if( deviceWaveHeaders[j].lpData ) + { + if( deviceWaveHeaders[j].dwUser != 0xFFFFFFFF ) + { + if( isInput ) + waveInUnprepareHeader( ((HWAVEIN*)handlesAndBuffers->waveHandles)[i], &deviceWaveHeaders[j], sizeof(WAVEHDR) ); + else + waveOutUnprepareHeader( ((HWAVEOUT*)handlesAndBuffers->waveHandles)[i], &deviceWaveHeaders[j], sizeof(WAVEHDR) ); + } + + PaUtil_FreeMemory( deviceWaveHeaders[j].lpData ); + } + } + + PaUtil_FreeMemory( deviceWaveHeaders ); + } + } + + PaUtil_FreeMemory( handlesAndBuffers->waveHeaders ); + handlesAndBuffers->waveHeaders = 0; + } +} + + + +/* PaWinMmeStream - a stream data structure specifically for this implementation */ +/* note that struct PaWinMmeStream is typedeffed to PaWinMmeStream above. */ +struct PaWinMmeStream +{ + PaUtilStreamRepresentation streamRepresentation; + PaUtilCpuLoadMeasurer cpuLoadMeasurer; + PaUtilBufferProcessor bufferProcessor; + + int primeStreamUsingCallback; + + PaWinMmeSingleDirectionHandlesAndBuffers input; + PaWinMmeSingleDirectionHandlesAndBuffers output; + + /* Processing thread management -------------- */ + HANDLE abortEvent; + HANDLE processingThread; + DWORD processingThreadId; + + char throttleProcessingThreadOnOverload; /* 0 -> don't throtte, non-0 -> throttle */ + int processingThreadPriority; + int highThreadPriority; + int throttledThreadPriority; + unsigned long throttledSleepMsecs; + + int isStopped; + volatile int isActive; + volatile int stopProcessing; /* stop thread once existing buffers have been returned */ + volatile int abortProcessing; /* stop thread immediately */ + + DWORD allBuffersDurationMs; /* used to calculate timeouts */ +}; + +/* updates deviceCount if PaWinMmeUseMultipleDevices is used */ + +static PaError ValidateWinMmeSpecificStreamInfo( + const PaStreamParameters *streamParameters, + const PaWinMmeStreamInfo *streamInfo, + char *throttleProcessingThreadOnOverload, + unsigned long *deviceCount ) +{ + if( streamInfo ) + { + if( streamInfo->size != sizeof( PaWinMmeStreamInfo ) + || streamInfo->version != 1 ) + { + return paIncompatibleHostApiSpecificStreamInfo; + } + + if( streamInfo->flags & paWinMmeDontThrottleOverloadedProcessingThread ) + *throttleProcessingThreadOnOverload = 0; + + if( streamInfo->flags & paWinMmeUseMultipleDevices ) + { + if( streamParameters->device != paUseHostApiSpecificDeviceSpecification ) + return paInvalidDevice; + + *deviceCount = streamInfo->deviceCount; + } + } + + return paNoError; +} + +static PaError RetrieveDevicesFromStreamParameters( + struct PaUtilHostApiRepresentation *hostApi, + const PaStreamParameters *streamParameters, + const PaWinMmeStreamInfo *streamInfo, + PaWinMmeDeviceAndChannelCount *devices, + unsigned long deviceCount ) +{ + PaError result = paNoError; + unsigned int i; + int totalChannelCount; + PaDeviceIndex hostApiDevice; + + if( streamInfo && streamInfo->flags & paWinMmeUseMultipleDevices ) + { + totalChannelCount = 0; + for( i=0; i < deviceCount; ++i ) + { + /* validate that the device number is within range */ + result = PaUtil_DeviceIndexToHostApiDeviceIndex( &hostApiDevice, + streamInfo->devices[i].device, hostApi ); + if( result != paNoError ) + return result; + + devices[i].device = hostApiDevice; + devices[i].channelCount = streamInfo->devices[i].channelCount; + + totalChannelCount += devices[i].channelCount; + } + + if( totalChannelCount != streamParameters->channelCount ) + { + /* channelCount must match total channels specified by multiple devices */ + return paInvalidChannelCount; /* REVIEW use of this error code */ + } + } + else + { + devices[0].device = streamParameters->device; + devices[0].channelCount = streamParameters->channelCount; + } + + return result; +} + +static PaError ValidateInputChannelCounts( + struct PaUtilHostApiRepresentation *hostApi, + PaWinMmeDeviceAndChannelCount *devices, + unsigned long deviceCount ) +{ + unsigned int i; + + for( i=0; i < deviceCount; ++i ) + { + if( devices[i].channelCount < 1 || devices[i].channelCount + > hostApi->deviceInfos[ devices[i].device ]->maxInputChannels ) + return paInvalidChannelCount; + } + + return paNoError; +} + +static PaError ValidateOutputChannelCounts( + struct PaUtilHostApiRepresentation *hostApi, + PaWinMmeDeviceAndChannelCount *devices, + unsigned long deviceCount ) +{ + unsigned int i; + + for( i=0; i < deviceCount; ++i ) + { + if( devices[i].channelCount < 1 || devices[i].channelCount + > hostApi->deviceInfos[ devices[i].device ]->maxOutputChannels ) + return paInvalidChannelCount; + } + + return paNoError; +} + + +/* the following macros are intended to improve the readability of the following code */ +#define PA_IS_INPUT_STREAM_( stream ) ( stream ->input.waveHandles ) +#define PA_IS_OUTPUT_STREAM_( stream ) ( stream ->output.waveHandles ) +#define PA_IS_FULL_DUPLEX_STREAM_( stream ) ( stream ->input.waveHandles && stream ->output.waveHandles ) +#define PA_IS_HALF_DUPLEX_STREAM_( stream ) ( !(stream ->input.waveHandles && stream ->output.waveHandles) ) + +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; + PaWinMmeHostApiRepresentation *winMmeHostApi = (PaWinMmeHostApiRepresentation*)hostApi; + PaWinMmeStream *stream = 0; + int bufferProcessorIsInitialized = 0; + int streamRepresentationIsInitialized = 0; + PaSampleFormat hostInputSampleFormat, hostOutputSampleFormat; + int inputChannelCount, outputChannelCount; + PaSampleFormat inputSampleFormat, outputSampleFormat; + double suggestedInputLatency, suggestedOutputLatency; + PaWinMmeStreamInfo *inputStreamInfo, *outputStreamInfo; + unsigned long framesPerHostInputBuffer; + unsigned long hostInputBufferCount; + unsigned long framesPerHostOutputBuffer; + unsigned long hostOutputBufferCount; + unsigned long framesPerBufferProcessorCall; + PaWinMmeDeviceAndChannelCount *inputDevices = 0; /* contains all devices and channel counts as local host api ids, even when PaWinMmeUseMultipleDevices is not used */ + unsigned long inputDeviceCount = 0; + PaWinMmeDeviceAndChannelCount *outputDevices = 0; + unsigned long outputDeviceCount = 0; /* contains all devices and channel counts as local host api ids, even when PaWinMmeUseMultipleDevices is not used */ + char throttleProcessingThreadOnOverload = 1; + + + if( inputParameters ) + { + inputChannelCount = inputParameters->channelCount; + inputSampleFormat = inputParameters->sampleFormat; + suggestedInputLatency = inputParameters->suggestedLatency; + + inputDeviceCount = 1; + + /* validate input hostApiSpecificStreamInfo */ + inputStreamInfo = (PaWinMmeStreamInfo*)inputParameters->hostApiSpecificStreamInfo; + result = ValidateWinMmeSpecificStreamInfo( inputParameters, inputStreamInfo, + &throttleProcessingThreadOnOverload, + &inputDeviceCount ); + if( result != paNoError ) return result; + + inputDevices = (PaWinMmeDeviceAndChannelCount*)alloca( sizeof(PaWinMmeDeviceAndChannelCount) * inputDeviceCount ); + if( !inputDevices ) return paInsufficientMemory; + + result = RetrieveDevicesFromStreamParameters( hostApi, inputParameters, inputStreamInfo, inputDevices, inputDeviceCount ); + if( result != paNoError ) return result; + + result = ValidateInputChannelCounts( hostApi, inputDevices, inputDeviceCount ); + if( result != paNoError ) return result; + + hostInputSampleFormat = + PaUtil_SelectClosestAvailableFormat( paInt16 /* native formats */, inputSampleFormat ); + } + else + { + inputChannelCount = 0; + inputSampleFormat = 0; + suggestedInputLatency = 0.; + inputStreamInfo = 0; + hostInputSampleFormat = 0; + } + + + if( outputParameters ) + { + outputChannelCount = outputParameters->channelCount; + outputSampleFormat = outputParameters->sampleFormat; + suggestedOutputLatency = outputParameters->suggestedLatency; + + outputDeviceCount = 1; + + /* validate output hostApiSpecificStreamInfo */ + outputStreamInfo = (PaWinMmeStreamInfo*)outputParameters->hostApiSpecificStreamInfo; + result = ValidateWinMmeSpecificStreamInfo( outputParameters, outputStreamInfo, + &throttleProcessingThreadOnOverload, + &outputDeviceCount ); + if( result != paNoError ) return result; + + outputDevices = (PaWinMmeDeviceAndChannelCount*)alloca( sizeof(PaWinMmeDeviceAndChannelCount) * outputDeviceCount ); + if( !outputDevices ) return paInsufficientMemory; + + result = RetrieveDevicesFromStreamParameters( hostApi, outputParameters, outputStreamInfo, outputDevices, outputDeviceCount ); + if( result != paNoError ) return result; + + result = ValidateOutputChannelCounts( hostApi, outputDevices, outputDeviceCount ); + if( result != paNoError ) return result; + + hostOutputSampleFormat = + PaUtil_SelectClosestAvailableFormat( paInt16 /* native formats */, outputSampleFormat ); + } + else + { + outputChannelCount = 0; + outputSampleFormat = 0; + outputStreamInfo = 0; + hostOutputSampleFormat = 0; + suggestedOutputLatency = 0.; + } + + + /* + IMPLEMENT ME: + - alter sampleRate to a close allowable rate if possible / necessary + */ + + + /* validate platform specific flags */ + if( (streamFlags & paPlatformSpecificFlags) != 0 ) + return paInvalidFlag; /* unexpected platform specific flag */ + + + result = CalculateBufferSettings( &framesPerHostInputBuffer, &hostInputBufferCount, + &framesPerHostOutputBuffer, &hostOutputBufferCount, + inputChannelCount, hostInputSampleFormat, suggestedInputLatency, inputStreamInfo, + outputChannelCount, hostOutputSampleFormat, suggestedOutputLatency, outputStreamInfo, + sampleRate, framesPerBuffer ); + if( result != paNoError ) goto error; + + + stream = (PaWinMmeStream*)PaUtil_AllocateMemory( sizeof(PaWinMmeStream) ); + if( !stream ) + { + result = paInsufficientMemory; + goto error; + } + + InitializeSingleDirectionHandlesAndBuffers( &stream->input ); + InitializeSingleDirectionHandlesAndBuffers( &stream->output ); + + stream->abortEvent = 0; + stream->processingThread = 0; + + stream->throttleProcessingThreadOnOverload = throttleProcessingThreadOnOverload; + + PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation, + ( (streamCallback) + ? &winMmeHostApi->callbackStreamInterface + : &winMmeHostApi->blockingStreamInterface ), + streamCallback, userData ); + streamRepresentationIsInitialized = 1; + + PaUtil_InitializeCpuLoadMeasurer( &stream->cpuLoadMeasurer, sampleRate ); + + + if( inputParameters && outputParameters ) /* full duplex */ + { + if( framesPerHostInputBuffer < framesPerHostOutputBuffer ) + { + assert( (framesPerHostOutputBuffer % framesPerHostInputBuffer) == 0 ); /* CalculateBufferSettings() should guarantee this condition */ + + framesPerBufferProcessorCall = framesPerHostInputBuffer; + } + else + { + assert( (framesPerHostInputBuffer % framesPerHostOutputBuffer) == 0 ); /* CalculateBufferSettings() should guarantee this condition */ + + framesPerBufferProcessorCall = framesPerHostOutputBuffer; + } + } + else if( inputParameters ) + { + framesPerBufferProcessorCall = framesPerHostInputBuffer; + } + else if( outputParameters ) + { + framesPerBufferProcessorCall = framesPerHostOutputBuffer; + } + + stream->input.framesPerBuffer = framesPerHostInputBuffer; + stream->output.framesPerBuffer = framesPerHostOutputBuffer; + + result = PaUtil_InitializeBufferProcessor( &stream->bufferProcessor, + inputChannelCount, inputSampleFormat, hostInputSampleFormat, + outputChannelCount, outputSampleFormat, hostOutputSampleFormat, + sampleRate, streamFlags, framesPerBuffer, + framesPerBufferProcessorCall, paUtilFixedHostBufferSize, + streamCallback, userData ); + if( result != paNoError ) goto error; + + bufferProcessorIsInitialized = 1; + + stream->streamRepresentation.streamInfo.inputLatency = + (double)(PaUtil_GetBufferProcessorInputLatency(&stream->bufferProcessor) + +(framesPerHostInputBuffer * (hostInputBufferCount-1))) / sampleRate; + stream->streamRepresentation.streamInfo.outputLatency = + (double)(PaUtil_GetBufferProcessorOutputLatency(&stream->bufferProcessor) + +(framesPerHostOutputBuffer * (hostOutputBufferCount-1))) / sampleRate; + stream->streamRepresentation.streamInfo.sampleRate = sampleRate; + + stream->primeStreamUsingCallback = ( (streamFlags&paPrimeOutputBuffersUsingStreamCallback) && streamCallback ) ? 1 : 0; + + /* time to sleep when throttling due to >100% cpu usage. + -a quater of a buffer's duration */ + stream->throttledSleepMsecs = + (unsigned long)(stream->bufferProcessor.framesPerHostBuffer * + stream->bufferProcessor.samplePeriod * .25 * 1000); + + stream->isStopped = 1; + stream->isActive = 0; + + + /* for maximum compatibility with multi-device multichannel drivers, + we first open all devices, then we prepare all buffers, finally + we start all devices ( in StartStream() ). teardown in reverse order. + */ + + if( inputParameters ) + { + result = InitializeWaveHandles( winMmeHostApi, &stream->input, + stream->bufferProcessor.bytesPerHostInputSample, sampleRate, + inputDevices, inputDeviceCount, 1 /* isInput */ ); + if( result != paNoError ) goto error; + } + + if( outputParameters ) + { + result = InitializeWaveHandles( winMmeHostApi, &stream->output, + stream->bufferProcessor.bytesPerHostOutputSample, sampleRate, + outputDevices, outputDeviceCount, 0 /* isInput */ ); + if( result != paNoError ) goto error; + } + + if( inputParameters ) + { + result = InitializeWaveHeaders( &stream->input, hostInputBufferCount, + hostInputSampleFormat, framesPerHostInputBuffer, inputDevices, 1 /* isInput */ ); + if( result != paNoError ) goto error; + } + + if( outputParameters ) + { + result = InitializeWaveHeaders( &stream->output, hostOutputBufferCount, + hostOutputSampleFormat, framesPerHostOutputBuffer, outputDevices, 0 /* not isInput */ ); + if( result != paNoError ) goto error; + + stream->allBuffersDurationMs = (DWORD) (1000.0 * (framesPerHostOutputBuffer * stream->output.bufferCount) / sampleRate); + } + else + { + stream->allBuffersDurationMs = (DWORD) (1000.0 * (framesPerHostInputBuffer * stream->input.bufferCount) / sampleRate); + } + + + if( streamCallback ) + { + /* abort event is only needed for callback streams */ + result = CreateEventWithPaError( &stream->abortEvent, NULL, TRUE, FALSE, NULL ); + if( result != paNoError ) goto error; + } + + *s = (PaStream*)stream; + + return result; + +error: + + if( stream ) + { + if( stream->abortEvent ) + CloseHandle( stream->abortEvent ); + + TerminateWaveHeaders( &stream->output, 0 /* not isInput */ ); + TerminateWaveHeaders( &stream->input, 1 /* isInput */ ); + + TerminateWaveHandles( &stream->output, 0 /* not isInput */, 1 /* currentlyProcessingAnError */ ); + TerminateWaveHandles( &stream->input, 1 /* isInput */, 1 /* currentlyProcessingAnError */ ); + + if( bufferProcessorIsInitialized ) + PaUtil_TerminateBufferProcessor( &stream->bufferProcessor ); + + if( streamRepresentationIsInitialized ) + PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation ); + + PaUtil_FreeMemory( stream ); + } + + return result; +} + + +/* return non-zero if all current buffers are done */ +static int BuffersAreDone( WAVEHDR **waveHeaders, unsigned int deviceCount, int bufferIndex ) +{ + unsigned int i; + + for( i=0; i < deviceCount; ++i ) + { + if( !(waveHeaders[i][ bufferIndex ].dwFlags & WHDR_DONE) ) + { + return 0; + } + } + + return 1; +} + +static int CurrentInputBuffersAreDone( PaWinMmeStream *stream ) +{ + return BuffersAreDone( stream->input.waveHeaders, stream->input.deviceCount, stream->input.currentBufferIndex ); +} + +static int CurrentOutputBuffersAreDone( PaWinMmeStream *stream ) +{ + return BuffersAreDone( stream->output.waveHeaders, stream->output.deviceCount, stream->output.currentBufferIndex ); +} + + +/* return non-zero if any buffers are queued */ +static int NoBuffersAreQueued( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers ) +{ + unsigned int i, j; + + if( handlesAndBuffers->waveHandles ) + { + for( i=0; i < handlesAndBuffers->bufferCount; ++i ) + { + for( j=0; j < handlesAndBuffers->deviceCount; ++j ) + { + if( !( handlesAndBuffers->waveHeaders[ j ][ i ].dwFlags & WHDR_DONE) ) + { + return 0; + } + } + } + } + + return 1; +} + + +#define PA_CIRCULAR_INCREMENT_( current, max )\ + ( (((current) + 1) >= (max)) ? (0) : (current+1) ) + +#define PA_CIRCULAR_DECREMENT_( current, max )\ + ( ((current) == 0) ? ((max)-1) : (current-1) ) + + +static signed long GetAvailableFrames( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers ) +{ + signed long result = 0; + unsigned int i; + + if( BuffersAreDone( handlesAndBuffers->waveHeaders, handlesAndBuffers->deviceCount, handlesAndBuffers->currentBufferIndex ) ) + { + /* we could calculate the following in O(1) if we kept track of the + last done buffer */ + result = handlesAndBuffers->framesPerBuffer - handlesAndBuffers->framesUsedInCurrentBuffer; + + i = PA_CIRCULAR_INCREMENT_( handlesAndBuffers->currentBufferIndex, handlesAndBuffers->bufferCount ); + while( i != handlesAndBuffers->currentBufferIndex ) + { + if( BuffersAreDone( handlesAndBuffers->waveHeaders, handlesAndBuffers->deviceCount, i ) ) + { + result += handlesAndBuffers->framesPerBuffer; + i = PA_CIRCULAR_INCREMENT_( i, handlesAndBuffers->bufferCount ); + } + else + break; + } + } + + return result; +} + + +static PaError AdvanceToNextInputBuffer( PaWinMmeStream *stream ) +{ + PaError result = paNoError; + MMRESULT mmresult; + unsigned int i; + + for( i=0; i < stream->input.deviceCount; ++i ) + { + mmresult = waveInAddBuffer( ((HWAVEIN*)stream->input.waveHandles)[i], + &stream->input.waveHeaders[i][ stream->input.currentBufferIndex ], + sizeof(WAVEHDR) ); + if( mmresult != MMSYSERR_NOERROR ) + { + result = paUnanticipatedHostError; + PA_MME_SET_LAST_WAVEIN_ERROR( mmresult ); + } + } + + stream->input.currentBufferIndex = + PA_CIRCULAR_INCREMENT_( stream->input.currentBufferIndex, stream->input.bufferCount ); + + stream->input.framesUsedInCurrentBuffer = 0; + + return result; +} + + +static PaError AdvanceToNextOutputBuffer( PaWinMmeStream *stream ) +{ + PaError result = paNoError; + MMRESULT mmresult; + unsigned int i; + + for( i=0; i < stream->output.deviceCount; ++i ) + { + mmresult = waveOutWrite( ((HWAVEOUT*)stream->output.waveHandles)[i], + &stream->output.waveHeaders[i][ stream->output.currentBufferIndex ], + sizeof(WAVEHDR) ); + if( mmresult != MMSYSERR_NOERROR ) + { + result = paUnanticipatedHostError; + PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult ); + } + } + + stream->output.currentBufferIndex = + PA_CIRCULAR_INCREMENT_( stream->output.currentBufferIndex, stream->output.bufferCount ); + + stream->output.framesUsedInCurrentBuffer = 0; + + return result; +} + + +/* requeue all but the most recent input with the driver. Used for catching + up after a total input buffer underrun */ +static PaError CatchUpInputBuffers( PaWinMmeStream *stream ) +{ + PaError result = paNoError; + unsigned int i; + + for( i=0; i < stream->input.bufferCount - 1; ++i ) + { + result = AdvanceToNextInputBuffer( stream ); + if( result != paNoError ) + break; + } + + return result; +} + + +/* take the most recent output and duplicate it to all other output buffers + and requeue them. Used for catching up after a total output buffer underrun. +*/ +static PaError CatchUpOutputBuffers( PaWinMmeStream *stream ) +{ + PaError result = paNoError; + unsigned int i, j; + unsigned int previousBufferIndex = + PA_CIRCULAR_DECREMENT_( stream->output.currentBufferIndex, stream->output.bufferCount ); + + for( i=0; i < stream->output.bufferCount - 1; ++i ) + { + for( j=0; j < stream->output.deviceCount; ++j ) + { + if( stream->output.waveHeaders[j][ stream->output.currentBufferIndex ].lpData + != stream->output.waveHeaders[j][ previousBufferIndex ].lpData ) + { + CopyMemory( stream->output.waveHeaders[j][ stream->output.currentBufferIndex ].lpData, + stream->output.waveHeaders[j][ previousBufferIndex ].lpData, + stream->output.waveHeaders[j][ stream->output.currentBufferIndex ].dwBufferLength ); + } + } + + result = AdvanceToNextOutputBuffer( stream ); + if( result != paNoError ) + break; + } + + return result; +} + + +static DWORD WINAPI ProcessingThreadProc( void *pArg ) +{ + PaWinMmeStream *stream = (PaWinMmeStream *)pArg; + HANDLE events[3]; + int eventCount = 0; + DWORD result = paNoError; + DWORD waitResult; + DWORD timeout = (unsigned long)(stream->allBuffersDurationMs * 0.5); + int hostBuffersAvailable; + signed int hostInputBufferIndex, hostOutputBufferIndex; + PaStreamCallbackFlags statusFlags; + int callbackResult; + int done = 0; + unsigned int channel, i; + unsigned long framesProcessed; + + /* prepare event array for call to WaitForMultipleObjects() */ + if( stream->input.bufferEvent ) + events[eventCount++] = stream->input.bufferEvent; + if( stream->output.bufferEvent ) + events[eventCount++] = stream->output.bufferEvent; + events[eventCount++] = stream->abortEvent; + + statusFlags = 0; /** @todo support paInputUnderflow, paOutputOverflow and paNeverDropInput */ + + /* loop until something causes us to stop */ + do{ + /* wait for MME to signal that a buffer is available, or for + the PA abort event to be signaled. + + When this indicates that one or more buffers are available + NoBuffersAreQueued() and Current*BuffersAreDone are used below to + poll for additional done buffers. NoBuffersAreQueued() will fail + to identify an underrun/overflow if the driver doesn't mark all done + buffers prior to signalling the event. Some drivers do this + (eg RME Digi96, and others don't eg VIA PC 97 input). This isn't a + huge problem, it just means that we won't always be able to detect + underflow/overflow. + */ + waitResult = WaitForMultipleObjects( eventCount, events, FALSE /* wait all = FALSE */, timeout ); + if( waitResult == WAIT_FAILED ) + { + result = paUnanticipatedHostError; + /** @todo FIXME/REVIEW: can't return host error info from an asyncronous thread */ + done = 1; + } + else if( waitResult == WAIT_TIMEOUT ) + { + /* if a timeout is encountered, continue */ + } + + if( stream->abortProcessing ) + { + /* Pa_AbortStream() has been called, stop processing immediately */ + done = 1; + } + else if( stream->stopProcessing ) + { + /* Pa_StopStream() has been called or the user callback returned + non-zero, processing will continue until all output buffers + are marked as done. The stream will stop immediately if it + is input-only. + */ + + if( PA_IS_OUTPUT_STREAM_(stream) ) + { + if( NoBuffersAreQueued( &stream->output ) ) + done = 1; /* Will cause thread to return. */ + } + else + { + /* input only stream */ + done = 1; /* Will cause thread to return. */ + } + } + else + { + hostBuffersAvailable = 1; + + /* process all available host buffers */ + do + { + hostInputBufferIndex = -1; + hostOutputBufferIndex = -1; + + if( PA_IS_INPUT_STREAM_(stream) ) + { + if( CurrentInputBuffersAreDone( stream ) ) + { + if( NoBuffersAreQueued( &stream->input ) ) + { + /** @todo + if all of the other buffers are also ready then + we discard all but the most recent. This is an + input buffer overflow. FIXME: these buffers should + be passed to the callback in a paNeverDropInput + stream. + + note that it is also possible for an input overflow + to happen while the callback is processing a buffer. + that is handled further down. + */ + result = CatchUpInputBuffers( stream ); + if( result != paNoError ) + done = 1; + + statusFlags |= paInputOverflow; + } + + hostInputBufferIndex = stream->input.currentBufferIndex; + } + } + + if( PA_IS_OUTPUT_STREAM_(stream) ) + { + if( CurrentOutputBuffersAreDone( stream ) ) + { + /* ok, we have an output buffer */ + + if( NoBuffersAreQueued( &stream->output ) ) + { + /* + if all of the other buffers are also ready, catch up by copying + the most recently generated buffer into all but one of the output + buffers. + + note that this catch up code only handles the case where all + buffers have been played out due to this thread not having + woken up at all. a more common case occurs when this thread + is woken up, processes one buffer, but takes too long, and as + a result all the other buffers have become un-queued. that + case is handled further down. + */ + + result = CatchUpOutputBuffers( stream ); + if( result != paNoError ) + done = 1; + + statusFlags |= paOutputUnderflow; + } + + hostOutputBufferIndex = stream->output.currentBufferIndex; + } + } + + + if( (PA_IS_FULL_DUPLEX_STREAM_(stream) && hostInputBufferIndex != -1 && hostOutputBufferIndex != -1) || + (PA_IS_HALF_DUPLEX_STREAM_(stream) && ( hostInputBufferIndex != -1 || hostOutputBufferIndex != -1 ) ) ) + { + PaStreamCallbackTimeInfo timeInfo = {0,0,0}; /** @todo implement inputBufferAdcTime */ + + + if( PA_IS_OUTPUT_STREAM_(stream) ) + { + /* set timeInfo.currentTime and calculate timeInfo.outputBufferDacTime + from the current wave out position */ + MMTIME mmtime; + double timeBeforeGetPosition, timeAfterGetPosition; + double time; + long framesInBufferRing; + long writePosition; + long playbackPosition; + HWAVEOUT firstWaveOutDevice = ((HWAVEOUT*)stream->output.waveHandles)[0]; + + mmtime.wType = TIME_SAMPLES; + timeBeforeGetPosition = PaUtil_GetTime(); + waveOutGetPosition( firstWaveOutDevice, &mmtime, sizeof(MMTIME) ); + timeAfterGetPosition = PaUtil_GetTime(); + + timeInfo.currentTime = timeAfterGetPosition; + + /* approximate time at which wave out position was measured + as half way between timeBeforeGetPosition and timeAfterGetPosition */ + time = timeBeforeGetPosition + (timeAfterGetPosition - timeBeforeGetPosition) * .5; + + framesInBufferRing = stream->output.bufferCount * stream->bufferProcessor.framesPerHostBuffer; + playbackPosition = mmtime.u.sample % framesInBufferRing; + + writePosition = stream->output.currentBufferIndex * stream->bufferProcessor.framesPerHostBuffer + + stream->output.framesUsedInCurrentBuffer; + + if( playbackPosition >= writePosition ){ + timeInfo.outputBufferDacTime = + time + ((double)( writePosition + (framesInBufferRing - playbackPosition) ) * stream->bufferProcessor.samplePeriod ); + }else{ + timeInfo.outputBufferDacTime = + time + ((double)( writePosition - playbackPosition ) * stream->bufferProcessor.samplePeriod ); + } + } + + + PaUtil_BeginCpuLoadMeasurement( &stream->cpuLoadMeasurer ); + + PaUtil_BeginBufferProcessing( &stream->bufferProcessor, &timeInfo, statusFlags ); + + /* reset status flags once they have been passed to the buffer processor */ + statusFlags = 0; + + if( PA_IS_INPUT_STREAM_(stream) ) + { + PaUtil_SetInputFrameCount( &stream->bufferProcessor, 0 /* default to host buffer size */ ); + + channel = 0; + for( i=0; iinput.deviceCount; ++i ) + { + /* we have stored the number of channels in the buffer in dwUser */ + int channelCount = stream->input.waveHeaders[i][ hostInputBufferIndex ].dwUser; + + PaUtil_SetInterleavedInputChannels( &stream->bufferProcessor, channel, + stream->input.waveHeaders[i][ hostInputBufferIndex ].lpData + + stream->input.framesUsedInCurrentBuffer * channelCount * + stream->bufferProcessor.bytesPerHostInputSample, + channelCount ); + + + channel += channelCount; + } + } + + if( PA_IS_OUTPUT_STREAM_(stream) ) + { + PaUtil_SetOutputFrameCount( &stream->bufferProcessor, 0 /* default to host buffer size */ ); + + channel = 0; + for( i=0; ioutput.deviceCount; ++i ) + { + /* we have stored the number of channels in the buffer in dwUser */ + int channelCount = stream->output.waveHeaders[i][ hostOutputBufferIndex ].dwUser; + + PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor, channel, + stream->output.waveHeaders[i][ hostOutputBufferIndex ].lpData + + stream->output.framesUsedInCurrentBuffer * channelCount * + stream->bufferProcessor.bytesPerHostOutputSample, + channelCount ); + + channel += channelCount; + } + } + + callbackResult = paContinue; + framesProcessed = PaUtil_EndBufferProcessing( &stream->bufferProcessor, &callbackResult ); + + stream->input.framesUsedInCurrentBuffer += framesProcessed; + stream->output.framesUsedInCurrentBuffer += framesProcessed; + + PaUtil_EndCpuLoadMeasurement( &stream->cpuLoadMeasurer, framesProcessed ); + + if( callbackResult == paContinue ) + { + /* nothing special to do */ + } + else if( callbackResult == paAbort ) + { + stream->abortProcessing = 1; + done = 1; + /** @todo FIXME: should probably reset the output device immediately once the callback returns paAbort */ + result = paNoError; + } + else + { + /* User callback has asked us to stop with paComplete or other non-zero value */ + stream->stopProcessing = 1; /* stop once currently queued audio has finished */ + result = paNoError; + } + + + if( PA_IS_INPUT_STREAM_(stream) + && stream->stopProcessing == 0 && stream->abortProcessing == 0 + && stream->input.framesUsedInCurrentBuffer == stream->input.framesPerBuffer ) + { + if( NoBuffersAreQueued( &stream->input ) ) + { + /** @todo need to handle PaNeverDropInput here where necessary */ + result = CatchUpInputBuffers( stream ); + if( result != paNoError ) + done = 1; + + statusFlags |= paInputOverflow; + } + + result = AdvanceToNextInputBuffer( stream ); + if( result != paNoError ) + done = 1; + } + + + if( PA_IS_OUTPUT_STREAM_(stream) && !stream->abortProcessing ) + { + if( stream->stopProcessing && + stream->output.framesUsedInCurrentBuffer < stream->output.framesPerBuffer ) + { + /* zero remaining samples in output output buffer and flush */ + + stream->output.framesUsedInCurrentBuffer += PaUtil_ZeroOutput( &stream->bufferProcessor, + stream->output.framesPerBuffer - stream->output.framesUsedInCurrentBuffer ); + + /* we send the entire buffer to the output devices, but we could + just send a partial buffer, rather than zeroing the unused + samples. + */ + } + + if( stream->output.framesUsedInCurrentBuffer == stream->output.framesPerBuffer ) + { + /* check for underflow before enquing the just-generated buffer, + but recover from underflow after enquing it. This ensures + that the most recent audio segment is repeated */ + int outputUnderflow = NoBuffersAreQueued( &stream->output ); + + result = AdvanceToNextOutputBuffer( stream ); + if( result != paNoError ) + done = 1; + + if( outputUnderflow && !done && !stream->stopProcessing ) + { + /* Recover from underflow in the case where the + underflow occured while processing the buffer + we just finished */ + + result = CatchUpOutputBuffers( stream ); + if( result != paNoError ) + done = 1; + + statusFlags |= paOutputUnderflow; + } + } + } + + if( stream->throttleProcessingThreadOnOverload != 0 ) + { + if( stream->stopProcessing || stream->abortProcessing ) + { + if( stream->processingThreadPriority != stream->highThreadPriority ) + { + SetThreadPriority( stream->processingThread, stream->highThreadPriority ); + stream->processingThreadPriority = stream->highThreadPriority; + } + } + else if( PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer ) > 1. ) + { + if( stream->processingThreadPriority != stream->throttledThreadPriority ) + { + SetThreadPriority( stream->processingThread, stream->throttledThreadPriority ); + stream->processingThreadPriority = stream->throttledThreadPriority; + } + + /* sleep to give other processes a go */ + Sleep( stream->throttledSleepMsecs ); + } + else + { + if( stream->processingThreadPriority != stream->highThreadPriority ) + { + SetThreadPriority( stream->processingThread, stream->highThreadPriority ); + stream->processingThreadPriority = stream->highThreadPriority; + } + } + } + } + else + { + hostBuffersAvailable = 0; + } + } + while( hostBuffersAvailable && + stream->stopProcessing == 0 && + stream->abortProcessing == 0 && + !done ); + } + } + while( !done ); + + stream->isActive = 0; + + if( stream->streamRepresentation.streamFinishedCallback != 0 ) + stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData ); + + PaUtil_ResetCpuLoadMeasurer( &stream->cpuLoadMeasurer ); + + 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; + PaWinMmeStream *stream = (PaWinMmeStream*)s; + + result = CloseHandleWithPaError( stream->abortEvent ); + if( result != paNoError ) goto error; + + TerminateWaveHeaders( &stream->output, 0 /* not isInput */ ); + TerminateWaveHeaders( &stream->input, 1 /* isInput */ ); + + TerminateWaveHandles( &stream->output, 0 /* not isInput */, 0 /* not currentlyProcessingAnError */ ); + TerminateWaveHandles( &stream->input, 1 /* isInput */, 0 /* not currentlyProcessingAnError */ ); + + PaUtil_TerminateBufferProcessor( &stream->bufferProcessor ); + PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation ); + PaUtil_FreeMemory( stream ); + +error: + /** @todo REVIEW: what is the best way to clean up a stream if an error is detected? */ + return result; +} + + +static PaError StartStream( PaStream *s ) +{ + PaError result; + PaWinMmeStream *stream = (PaWinMmeStream*)s; + MMRESULT mmresult; + unsigned int i, j; + int callbackResult; + unsigned int channel; + unsigned long framesProcessed; + PaStreamCallbackTimeInfo timeInfo = {0,0,0}; /** @todo implement this for stream priming */ + + PaUtil_ResetBufferProcessor( &stream->bufferProcessor ); + + if( PA_IS_INPUT_STREAM_(stream) ) + { + for( i=0; iinput.bufferCount; ++i ) + { + for( j=0; jinput.deviceCount; ++j ) + { + mmresult = waveInAddBuffer( ((HWAVEIN*)stream->input.waveHandles)[j], &stream->input.waveHeaders[j][i], sizeof(WAVEHDR) ); + if( mmresult != MMSYSERR_NOERROR ) + { + result = paUnanticipatedHostError; + PA_MME_SET_LAST_WAVEIN_ERROR( mmresult ); + goto error; + } + } + } + stream->input.currentBufferIndex = 0; + stream->input.framesUsedInCurrentBuffer = 0; + } + + if( PA_IS_OUTPUT_STREAM_(stream) ) + { + for( i=0; ioutput.deviceCount; ++i ) + { + if( (mmresult = waveOutPause( ((HWAVEOUT*)stream->output.waveHandles)[i] )) != MMSYSERR_NOERROR ) + { + result = paUnanticipatedHostError; + PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult ); + goto error; + } + } + + for( i=0; ioutput.bufferCount; ++i ) + { + if( stream->primeStreamUsingCallback ) + { + + stream->output.framesUsedInCurrentBuffer = 0; + do{ + + PaUtil_BeginBufferProcessing( &stream->bufferProcessor, + &timeInfo, + paPrimingOutput | ((stream->input.bufferCount > 0 ) ? paInputUnderflow : 0)); + + if( stream->input.bufferCount > 0 ) + PaUtil_SetNoInput( &stream->bufferProcessor ); + + PaUtil_SetOutputFrameCount( &stream->bufferProcessor, 0 /* default to host buffer size */ ); + + channel = 0; + for( j=0; joutput.deviceCount; ++j ) + { + /* we have stored the number of channels in the buffer in dwUser */ + int channelCount = stream->output.waveHeaders[j][i].dwUser; + + PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor, channel, + stream->output.waveHeaders[j][i].lpData + + stream->output.framesUsedInCurrentBuffer * channelCount * + stream->bufferProcessor.bytesPerHostOutputSample, + channelCount ); + + /* we have stored the number of channels in the buffer in dwUser */ + channel += channelCount; + } + + callbackResult = paContinue; + framesProcessed = PaUtil_EndBufferProcessing( &stream->bufferProcessor, &callbackResult ); + stream->output.framesUsedInCurrentBuffer += framesProcessed; + + if( callbackResult != paContinue ) + { + /** @todo fix this, what do we do if callback result is non-zero during stream + priming? + + for complete: play out primed waveHeaders as usual + for abort: clean up immediately. + */ + } + + }while( stream->output.framesUsedInCurrentBuffer != stream->output.framesPerBuffer ); + + } + else + { + for( j=0; joutput.deviceCount; ++j ) + { + ZeroMemory( stream->output.waveHeaders[j][i].lpData, stream->output.waveHeaders[j][i].dwBufferLength ); + } + } + + /* we queue all channels of a single buffer frame (accross all + devices, because some multidevice multichannel drivers work + better this way */ + for( j=0; joutput.deviceCount; ++j ) + { + mmresult = waveOutWrite( ((HWAVEOUT*)stream->output.waveHandles)[j], &stream->output.waveHeaders[j][i], sizeof(WAVEHDR) ); + if( mmresult != MMSYSERR_NOERROR ) + { + result = paUnanticipatedHostError; + PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult ); + goto error; + } + } + } + stream->output.currentBufferIndex = 0; + stream->output.framesUsedInCurrentBuffer = 0; + } + + + stream->isStopped = 0; + stream->isActive = 1; + stream->stopProcessing = 0; + stream->abortProcessing = 0; + + result = ResetEventWithPaError( stream->input.bufferEvent ); + if( result != paNoError ) goto error; + + result = ResetEventWithPaError( stream->output.bufferEvent ); + if( result != paNoError ) goto error; + + + if( stream->streamRepresentation.streamCallback ) + { + /* callback stream */ + + result = ResetEventWithPaError( stream->abortEvent ); + if( result != paNoError ) goto error; + + /* Create thread that waits for audio buffers to be ready for processing. */ + stream->processingThread = CreateThread( 0, 0, ProcessingThreadProc, stream, 0, &stream->processingThreadId ); + if( !stream->processingThread ) + { + result = paUnanticipatedHostError; + PA_MME_SET_LAST_SYSTEM_ERROR( GetLastError() ); + goto error; + } + + /** @todo could have mme specific stream parameters to allow the user + to set the callback thread priorities */ + stream->highThreadPriority = THREAD_PRIORITY_TIME_CRITICAL; + stream->throttledThreadPriority = THREAD_PRIORITY_NORMAL; + + if( !SetThreadPriority( stream->processingThread, stream->highThreadPriority ) ) + { + result = paUnanticipatedHostError; + PA_MME_SET_LAST_SYSTEM_ERROR( GetLastError() ); + goto error; + } + stream->processingThreadPriority = stream->highThreadPriority; + } + else + { + /* blocking read/write stream */ - return paNoError; + } + + if( PA_IS_INPUT_STREAM_(stream) ) + { + for( i=0; i < stream->input.deviceCount; ++i ) + { + mmresult = waveInStart( ((HWAVEIN*)stream->input.waveHandles)[i] ); + PA_DEBUG(("Pa_StartStream: waveInStart returned = 0x%X.\n", mmresult)); + if( mmresult != MMSYSERR_NOERROR ) + { + result = paUnanticipatedHostError; + PA_MME_SET_LAST_WAVEIN_ERROR( mmresult ); + goto error; + } + } + } + + if( PA_IS_OUTPUT_STREAM_(stream) ) + { + for( i=0; i < stream->output.deviceCount; ++i ) + { + if( (mmresult = waveOutRestart( ((HWAVEOUT*)stream->output.waveHandles)[i] )) != MMSYSERR_NOERROR ) + { + result = paUnanticipatedHostError; + PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult ); + goto error; + } + } + } + + return result; + +error: + /** @todo FIXME: implement recovery as best we can + This should involve rolling back to a state as-if this function had never been called + */ + return result; } -/************************************************************************* - * 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") -int Pa_GetMinNumBuffers( int framesPerBuffer, double sampleRate ) -{ - char envbuf[PA_ENV_BUF_SIZE]; - DWORD hresult; - int minLatencyMsec = 0; - double msecPerBuffer = (1000.0 * framesPerBuffer) / sampleRate; - int minBuffers; - /* 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) ) + +static PaError StopStream( PaStream *s ) +{ + PaError result = paNoError; + PaWinMmeStream *stream = (PaWinMmeStream*)s; + int timeout; + DWORD waitResult; + MMRESULT mmresult; + signed int hostOutputBufferIndex; + unsigned int channel, waitCount, i; + + /** @todo + REVIEW: the error checking in this function needs review. the basic + idea is to return from this function in a known state - for example + there is no point avoiding calling waveInReset just because + the thread times out. + */ + + if( stream->processingThread ) { - minLatencyMsec = atoi( envbuf ); /* REVIEW: will we crash if the environment variable contains some nasty value? */ + /* callback stream */ + + /* Tell processing thread to stop generating more data and to let current data play out. */ + stream->stopProcessing = 1; + + /* Calculate timeOut longer than longest time it could take to return all buffers. */ + timeout = (int)(stream->allBuffersDurationMs * 1.5); + if( timeout < PA_MME_MIN_TIMEOUT_MSEC_ ) + timeout = PA_MME_MIN_TIMEOUT_MSEC_; + + PA_DEBUG(("WinMME StopStream: waiting for background thread.\n")); + + waitResult = WaitForSingleObject( stream->processingThread, timeout ); + if( waitResult == WAIT_TIMEOUT ) + { + /* try to abort */ + stream->abortProcessing = 1; + SetEvent( stream->abortEvent ); + waitResult = WaitForSingleObject( stream->processingThread, timeout ); + if( waitResult == WAIT_TIMEOUT ) + { + PA_DEBUG(("WinMME StopStream: timed out while waiting for background thread to finish.\n")); + result = paTimedOut; + } + } + + CloseHandle( stream->processingThread ); + stream->processingThread = NULL; } else { - /* 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; - } -#if PA_USE_HIGH_LATENCY - PRINT(("PA - Minimum Latency set to %d msec!\n", minLatencyMsec )); -#endif + /* blocking read / write stream */ + + if( PA_IS_OUTPUT_STREAM_(stream) ) + { + if( stream->output.framesUsedInCurrentBuffer > 0 ) + { + /* there are still unqueued frames in the current buffer, so flush them */ + + hostOutputBufferIndex = stream->output.currentBufferIndex; + + PaUtil_SetOutputFrameCount( &stream->bufferProcessor, + stream->output.framesPerBuffer - stream->output.framesUsedInCurrentBuffer ); + + channel = 0; + for( i=0; ioutput.deviceCount; ++i ) + { + /* we have stored the number of channels in the buffer in dwUser */ + int channelCount = stream->output.waveHeaders[i][ hostOutputBufferIndex ].dwUser; + + PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor, channel, + stream->output.waveHeaders[i][ hostOutputBufferIndex ].lpData + + stream->output.framesUsedInCurrentBuffer * channelCount * + stream->bufferProcessor.bytesPerHostOutputSample, + channelCount ); + + channel += channelCount; + } + + PaUtil_ZeroOutput( &stream->bufferProcessor, + stream->output.framesPerBuffer - stream->output.framesUsedInCurrentBuffer ); + + /* we send the entire buffer to the output devices, but we could + just send a partial buffer, rather than zeroing the unused + samples. + */ + AdvanceToNextOutputBuffer( stream ); + } + + + timeout = (stream->allBuffersDurationMs / stream->output.bufferCount) + 1; + if( timeout < PA_MME_MIN_TIMEOUT_MSEC_ ) + timeout = PA_MME_MIN_TIMEOUT_MSEC_; + + waitCount = 0; + while( !NoBuffersAreQueued( &stream->output ) && waitCount <= stream->output.bufferCount ) + { + /* wait for MME to signal that a buffer is available */ + waitResult = WaitForSingleObject( stream->output.bufferEvent, timeout ); + if( waitResult == WAIT_FAILED ) + { + break; + } + else if( waitResult == WAIT_TIMEOUT ) + { + /* keep waiting */ + } + + ++waitCount; + } + } + } + + if( PA_IS_OUTPUT_STREAM_(stream) ) + { + for( i =0; i < stream->output.deviceCount; ++i ) + { + mmresult = waveOutReset( ((HWAVEOUT*)stream->output.waveHandles)[i] ); + if( mmresult != MMSYSERR_NOERROR ) + { + result = paUnanticipatedHostError; + PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult ); + } + } + } + if( PA_IS_INPUT_STREAM_(stream) ) + { + for( i=0; i < stream->input.deviceCount; ++i ) + { + mmresult = waveInReset( ((HWAVEIN*)stream->input.waveHandles)[i] ); + if( mmresult != MMSYSERR_NOERROR ) + { + result = paUnanticipatedHostError; + PA_MME_SET_LAST_WAVEIN_ERROR( mmresult ); + } + } } - DBUG(("PA - Minimum Latency set to %d msec!\n", minLatencyMsec )); - minBuffers = (int) (1.0 + ((double)minLatencyMsec / msecPerBuffer)); - if( minBuffers < 2 ) minBuffers = 2; - return minBuffers; + + stream->isStopped = 1; + stream->isActive = 0; + + return result; } -/************************************************************************* - * Cleanup device info. - */ -PaError PaHost_Term( void ) + + +static PaError AbortStream( PaStream *s ) { - int i; + PaError result = paNoError; + PaWinMmeStream *stream = (PaWinMmeStream*)s; + int timeout; + DWORD waitResult; + MMRESULT mmresult; + unsigned int i; + + /** @todo + REVIEW: the error checking in this function needs review. the basic + idea is to return from this function in a known state - for example + there is no point avoiding calling waveInReset just because + the thread times out. + */ + + if( stream->processingThread ) + { + /* callback stream */ + + /* Tell processing thread to abort immediately */ + stream->abortProcessing = 1; + SetEvent( stream->abortEvent ); + } - if( sNumDevices > 0 ) + + if( PA_IS_OUTPUT_STREAM_(stream) ) { - if( sDevicePtrs != NULL ) + for( i =0; i < stream->output.deviceCount; ++i ) { - for( i=0; ioutput.waveHandles)[i] ); + if( mmresult != MMSYSERR_NOERROR ) { - if( sDevicePtrs[i] != NULL ) - { - PaHost_FreeTrackedMemory( (char*)sDevicePtrs[i]->name ); /* MEM */ - PaHost_FreeTrackedMemory( (void*)sDevicePtrs[i]->sampleRates ); /* MEM */ - PaHost_FreeTrackedMemory( sDevicePtrs[i] ); /* MEM */ - } + PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult ); + return paUnanticipatedHostError; } - PaHost_FreeTrackedMemory( sDevicePtrs ); /* MEM */ - sDevicePtrs = NULL; } - sNumDevices = 0; } -#if PA_TRACK_MEMORY - PRINT(("PaHost_Term: sNumAllocations = %d\n", sNumAllocations )); -#endif + if( PA_IS_INPUT_STREAM_(stream) ) + { + for( i=0; i < stream->input.deviceCount; ++i ) + { + mmresult = waveInReset( ((HWAVEIN*)stream->input.waveHandles)[i] ); + if( mmresult != MMSYSERR_NOERROR ) + { + PA_MME_SET_LAST_WAVEIN_ERROR( mmresult ); + return paUnanticipatedHostError; + } + } + } - return paNoError; + + if( stream->processingThread ) + { + /* callback stream */ + + PA_DEBUG(("WinMME AbortStream: waiting for background thread.\n")); + + /* Calculate timeOut longer than longest time it could take to return all buffers. */ + timeout = (int)(stream->allBuffersDurationMs * 1.5); + if( timeout < PA_MME_MIN_TIMEOUT_MSEC_ ) + timeout = PA_MME_MIN_TIMEOUT_MSEC_; + + waitResult = WaitForSingleObject( stream->processingThread, timeout ); + if( waitResult == WAIT_TIMEOUT ) + { + PA_DEBUG(("WinMME AbortStream: timed out while waiting for background thread to finish.\n")); + return paTimedOut; + } + + CloseHandle( stream->processingThread ); + stream->processingThread = NULL; + } + + stream->isStopped = 1; + stream->isActive = 0; + + return result; } -/*************************************************************************/ -void Pa_Sleep( long msec ) + + +static PaError IsStreamStopped( PaStream *s ) { - Sleep( msec ); + PaWinMmeStream *stream = (PaWinMmeStream*)s; + + return stream->isStopped; } -/************************************************************************* -FIXME: the following memory allocation routines should not be declared here - * Allocate memory that can be accessed in real-time. - * This may need to be held in physical memory so that it is not - * paged to virtual memory. - * This call MUST be balanced with a call to PaHost_FreeFastMemory(). - * Memory will be set to zero. - */ -void *PaHost_AllocateFastMemory( long numBytes ) + + +static PaError IsStreamActive( PaStream *s ) { - return PaHost_AllocateTrackedMemory( numBytes ); /* FIXME - do we need physical memory? Use VirtualLock() */ /* MEM */ + PaWinMmeStream *stream = (PaWinMmeStream*)s; + + return stream->isActive; } -/************************************************************************* - * Free memory that could be accessed in real-time. - * This call MUST be balanced with a call to PaHost_AllocateFastMemory(). - */ -void PaHost_FreeFastMemory( void *addr, long numBytes ) + + +static PaTime GetStreamTime( PaStream *s ) { - (void) numBytes; /* unused parameter */ + (void) s; /* unused parameter */ - PaHost_FreeTrackedMemory( addr ); /* MEM */ + return PaUtil_GetTime(); } -/************************************************************************* - * Track memory allocations to avoid leaks. - */ -static void *PaHost_AllocateTrackedMemory( long numBytes ) + +static double GetStreamCpuLoad( PaStream* s ) { - void *result = GlobalAlloc( GPTR, numBytes ); /* MEM */ + PaWinMmeStream *stream = (PaWinMmeStream*)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 ) +{ + PaError result = paNoError; + PaWinMmeStream *stream = (PaWinMmeStream*)s; + void *userBuffer; + unsigned long framesRead = 0; + unsigned long framesProcessed; + signed int hostInputBufferIndex; + DWORD waitResult; + DWORD timeout = (unsigned long)(stream->allBuffersDurationMs * 0.5); + unsigned int channel, i; + + if( PA_IS_INPUT_STREAM_(stream) ) + { + /* make a local copy of the user buffer pointer(s). this is necessary + because PaUtil_CopyInput() advances these pointers every time + it is called. + */ + if( stream->bufferProcessor.userInputIsInterleaved ) + { + userBuffer = buffer; + } + else + { + userBuffer = alloca( sizeof(void*) * stream->bufferProcessor.inputChannelCount ); + if( !userBuffer ) + return paInsufficientMemory; + for( i = 0; ibufferProcessor.inputChannelCount; ++i ) + ((void**)userBuffer)[i] = ((void**)buffer)[i]; + } + + do{ + if( CurrentInputBuffersAreDone( stream ) ) + { + if( NoBuffersAreQueued( &stream->input ) ) + { + /** @todo REVIEW: consider what to do if the input overflows. + do we requeue all of the buffers? should we be running + a thread to make sure they are always queued? */ + + result = paInputOverflowed; + } + + hostInputBufferIndex = stream->input.currentBufferIndex; + + PaUtil_SetInputFrameCount( &stream->bufferProcessor, + stream->input.framesPerBuffer - stream->input.framesUsedInCurrentBuffer ); + + channel = 0; + for( i=0; iinput.deviceCount; ++i ) + { + /* we have stored the number of channels in the buffer in dwUser */ + int channelCount = stream->input.waveHeaders[i][ hostInputBufferIndex ].dwUser; + + PaUtil_SetInterleavedInputChannels( &stream->bufferProcessor, channel, + stream->input.waveHeaders[i][ hostInputBufferIndex ].lpData + + stream->input.framesUsedInCurrentBuffer * channelCount * + stream->bufferProcessor.bytesPerHostInputSample, + channelCount ); + + channel += channelCount; + } + + framesProcessed = PaUtil_CopyInput( &stream->bufferProcessor, &userBuffer, frames - framesRead ); + + stream->input.framesUsedInCurrentBuffer += framesProcessed; + if( stream->input.framesUsedInCurrentBuffer == stream->input.framesPerBuffer ) + { + result = AdvanceToNextInputBuffer( stream ); + if( result != paNoError ) + break; + } + + framesRead += framesProcessed; + + }else{ + /* wait for MME to signal that a buffer is available */ + waitResult = WaitForSingleObject( stream->input.bufferEvent, timeout ); + if( waitResult == WAIT_FAILED ) + { + result = paUnanticipatedHostError; + break; + } + else if( waitResult == WAIT_TIMEOUT ) + { + /* if a timeout is encountered, continue, + perhaps we should give up eventually + */ + } + } + }while( framesRead < frames ); + } + else + { + result = paCanNotReadFromAnOutputOnlyStream; + } -#if PA_TRACK_MEMORY - if( result != NULL ) sNumAllocations += 1; -#endif return result; } -static void PaHost_FreeTrackedMemory( void *addr ) + +static PaError WriteStream( PaStream* s, + const void *buffer, + unsigned long frames ) { - if( addr != NULL ) + PaError result = paNoError; + PaWinMmeStream *stream = (PaWinMmeStream*)s; + const void *userBuffer; + unsigned long framesWritten = 0; + unsigned long framesProcessed; + signed int hostOutputBufferIndex; + DWORD waitResult; + DWORD timeout = (unsigned long)(stream->allBuffersDurationMs * 0.5); + unsigned int channel, i; + + + if( PA_IS_OUTPUT_STREAM_(stream) ) { - GlobalFree( addr ); /* MEM */ -#if PA_TRACK_MEMORY - sNumAllocations -= 1; -#endif + /* make a local copy of the user buffer pointer(s). this is necessary + because PaUtil_CopyOutput() advances these pointers every time + it is called. + */ + if( stream->bufferProcessor.userOutputIsInterleaved ) + { + userBuffer = buffer; + } + else + { + userBuffer = alloca( sizeof(void*) * stream->bufferProcessor.outputChannelCount ); + if( !userBuffer ) + return paInsufficientMemory; + for( i = 0; ibufferProcessor.outputChannelCount; ++i ) + ((const void**)userBuffer)[i] = ((const void**)buffer)[i]; + } + + do{ + if( CurrentOutputBuffersAreDone( stream ) ) + { + if( NoBuffersAreQueued( &stream->output ) ) + { + /** @todo REVIEW: consider what to do if the output + underflows. do we requeue all the existing buffers with + zeros? should we run a separate thread to keep the buffers + enqueued at all times? */ + + result = paOutputUnderflowed; + } + + hostOutputBufferIndex = stream->output.currentBufferIndex; + + PaUtil_SetOutputFrameCount( &stream->bufferProcessor, + stream->output.framesPerBuffer - stream->output.framesUsedInCurrentBuffer ); + + channel = 0; + for( i=0; ioutput.deviceCount; ++i ) + { + /* we have stored the number of channels in the buffer in dwUser */ + int channelCount = stream->output.waveHeaders[i][ hostOutputBufferIndex ].dwUser; + + PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor, channel, + stream->output.waveHeaders[i][ hostOutputBufferIndex ].lpData + + stream->output.framesUsedInCurrentBuffer * channelCount * + stream->bufferProcessor.bytesPerHostOutputSample, + channelCount ); + + channel += channelCount; + } + + framesProcessed = PaUtil_CopyOutput( &stream->bufferProcessor, &userBuffer, frames - framesWritten ); + + stream->output.framesUsedInCurrentBuffer += framesProcessed; + if( stream->output.framesUsedInCurrentBuffer == stream->output.framesPerBuffer ) + { + result = AdvanceToNextOutputBuffer( stream ); + if( result != paNoError ) + break; + } + + framesWritten += framesProcessed; + } + else + { + /* wait for MME to signal that a buffer is available */ + waitResult = WaitForSingleObject( stream->output.bufferEvent, timeout ); + if( waitResult == WAIT_FAILED ) + { + result = paUnanticipatedHostError; + break; + } + else if( waitResult == WAIT_TIMEOUT ) + { + /* if a timeout is encountered, continue, + perhaps we should give up eventually + */ + } + } + }while( framesWritten < frames ); + } + else + { + result = paCanNotWriteToAnInputOnlyStream; } + + return result; } -/***********************************************************************/ -PaError PaHost_StreamActive( internalPortAudioStream *internalStream ) + +static signed long GetStreamReadAvailable( PaStream* s ) { - if( internalStream == NULL ) return paBadStreamPtr; + PaWinMmeStream *stream = (PaWinMmeStream*)s; + + if( PA_IS_INPUT_STREAM_(stream) ) + return GetAvailableFrames( &stream->input ); + else + return paCanNotReadFromAnOutputOnlyStream; +} - return (PaError) internalStream->past_IsActive; + +static signed long GetStreamWriteAvailable( PaStream* s ) +{ + PaWinMmeStream *stream = (PaWinMmeStream*)s; + + if( PA_IS_OUTPUT_STREAM_(stream) ) + return GetAvailableFrames( &stream->output ); + else + return paCanNotWriteToAnInputOnlyStream; } -/************************************************************************* - * This must be called periodically because mmtime.u.sample - * is a DWORD and can wrap and lose sync after a few hours. - */ -static PaError PaHost_UpdateStreamTime( PaWMMEStreamData *wmmeStreamData ) + + +/* NOTE: the following functions are MME-stream specific, and are called directly + by client code. We need to check for many more error conditions here because + we don't have the benefit of pa_front.c's parameter checking. +*/ + +static PaError GetWinMMEStreamPointer( PaWinMmeStream **stream, PaStream *s ) { - MMRESULT mmresult; - MMTIME mmtime; - mmtime.wType = TIME_SAMPLES; + PaError result; + PaUtilHostApiRepresentation *hostApi; + PaWinMmeHostApiRepresentation *winMmeHostApi; + + result = PaUtil_ValidateStreamPointer( s ); + if( result != paNoError ) + return result; - if( wmmeStreamData->hWaveOut != NULL ) + result = PaUtil_GetHostApiRepresentation( &hostApi, paMME ); + if( result != paNoError ) + return result; + + winMmeHostApi = (PaWinMmeHostApiRepresentation*)hostApi; + + /* note, the following would be easier if there was a generic way of testing + that a stream belongs to a specific host API */ + + if( PA_STREAM_REP( s )->streamInterface == &winMmeHostApi->callbackStreamInterface + || PA_STREAM_REP( s )->streamInterface == &winMmeHostApi->blockingStreamInterface ) { - mmresult = waveOutGetPosition( wmmeStreamData->hWaveOut, &mmtime, sizeof(mmtime) ); + /* s is a WinMME stream */ + *stream = (PaWinMmeStream *)s; + return paNoError; } else { - mmresult = waveInGetPosition( wmmeStreamData->hWaveIn, &mmtime, sizeof(mmtime) ); + return paIncompatibleStreamHostApi; } - - if( mmresult != MMSYSERR_NOERROR ) - { - sPaHostError = mmresult; - return paHostError; - } - - /* This data has two variables and is shared by foreground and background. - * So we need to make it thread safe. */ - EnterCriticalSection( &wmmeStreamData->streamLock ); - wmmeStreamData->framesPlayed += ((long)mmtime.u.sample) - wmmeStreamData->lastPosition; - wmmeStreamData->lastPosition = (long)mmtime.u.sample; - LeaveCriticalSection( &wmmeStreamData->streamLock ); - - return paNoError; } -/*************************************************************************/ -PaTimestamp Pa_StreamTime( PortAudioStream *stream ) + + +int PaWinMME_GetStreamInputHandleCount( PaStream* s ) +{ + PaWinMmeStream *stream; + PaError result = GetWinMMEStreamPointer( &stream, s ); + + if( result == paNoError ) + return (PA_IS_INPUT_STREAM_(stream)) ? stream->input.deviceCount : 0; + else + return result; +} + + +HWAVEIN PaWinMME_GetStreamInputHandle( PaStream* s, int handleIndex ) +{ + PaWinMmeStream *stream; + PaError result = GetWinMMEStreamPointer( &stream, s ); + + if( result == paNoError + && PA_IS_INPUT_STREAM_(stream) + && handleIndex >= 0 + && (unsigned int)handleIndex < stream->input.deviceCount ) + return ((HWAVEIN*)stream->input.waveHandles)[handleIndex]; + else + return 0; +} + + +int PaWinMME_GetStreamOutputHandleCount( PaStream* s) { - internalPortAudioStream *internalStream = PaHost_GetStreamRepresentation( stream ); - PaWMMEStreamData *wmmeStreamData = PaHost_GetWMMEStreamData( internalStream ); + PaWinMmeStream *stream; + PaError result = GetWinMMEStreamPointer( &stream, s ); - if( internalStream == NULL ) return paBadStreamPtr; - if( wmmeStreamData == NULL ) return paInternalError; + if( result == paNoError ) + return (PA_IS_OUTPUT_STREAM_(stream)) ? stream->output.deviceCount : 0; + else + return result; +} - PaHost_UpdateStreamTime( wmmeStreamData ); - return wmmeStreamData->framesPlayed; + +HWAVEOUT PaWinMME_GetStreamOutputHandle( PaStream* s, int handleIndex ) +{ + PaWinMmeStream *stream; + PaError result = GetWinMMEStreamPointer( &stream, s ); + + if( result == paNoError + && PA_IS_OUTPUT_STREAM_(stream) + && handleIndex >= 0 + && (unsigned int)handleIndex < stream->output.deviceCount ) + return ((HWAVEOUT*)stream->output.waveHandles)[handleIndex]; + else + return 0; } -/*************************************************************************/ + + diff --git a/pa_win_wmme/pa_win_wmme.h b/pa_win_wmme/pa_win_wmme.h new file mode 100644 index 0000000..458f88f --- /dev/null +++ b/pa_win_wmme/pa_win_wmme.h @@ -0,0 +1,160 @@ +#ifndef PA_WIN_WMME_H +#define PA_WIN_WMME_H +/* + * $Id$ + * 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. + * + * 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. + * + */ + +/** @file + @brief WMME-specific PortAudio API extension header file. +*/ + + +#include "portaudio.h" + +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + + +#define paWinMmeUseLowLevelLatencyParameters (0x01) +#define paWinMmeUseMultipleDevices (0x02) /* use mme specific multiple device feature */ + + +/* 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; + +}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_GetStreamInputHandle(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 */ diff --git a/portaudio-2.0.pc.in b/portaudio-2.0.pc.in new file mode 100644 index 0000000..a29c6c0 --- /dev/null +++ b/portaudio-2.0.pc.in @@ -0,0 +1,11 @@ +prefix=@prefix@ +libdir=@libdir@ +includedir=@includedir@ + +Name: PortAudio +Description: Portable audio I/O +Requires: +Version: 19 + +Libs: -L${libdir} -lportaudio @LIBS@ +Cflags: -I${includedir} @THREAD_CFLAGS@ diff --git a/scons/SConscript_common b/scons/SConscript_common new file mode 100644 index 0000000..75b15f7 --- /dev/null +++ b/scons/SConscript_common @@ -0,0 +1,23 @@ +import os.path, sys + +class ConfigurationError(Exception): + def __init__(self, reason): + Exception.__init__(self, "Configuration failed: %s" % reason) + +env = Environment() + +# sunos, aix, hpux, irix, sunos appear to be platforms known by SCons, assuming they're POSIX compliant +Posix = ("linux", "darwin", "sunos", "aix", "hpux", "irix", "sunos") +Windows = ("win32", "cygwin") + +if env["PLATFORM"] == "posix": + if sys.platform[:5] == "linux": + Platform = "linux" + else: + raise ConfigurationError("Unknown platform %s" % sys.platform) +else: + if not env["PLATFORM"] in ("win32", "cygwin") + Posix: + raise ConfigurationError("Unknown platform %s" % env["PLATFORM"]) + Platform = env["PLATFORM"] + +Export("Platform", "Posix", "ConfigurationError") diff --git a/scons/SConscript_opts b/scons/SConscript_opts new file mode 100644 index 0000000..44ab678 --- /dev/null +++ b/scons/SConscript_opts @@ -0,0 +1,85 @@ +import os.path, sys + +def _PackageOption(pkgName, default=1): + """ Allow user to choose whether a package should be used if available. This results in a commandline option use, + where Pkgname is the name of the package with a capitalized first letter. + @param pkgName: Name of package. + @param default: The default value for this option ("yes"/"no"). + """ + return BoolOption("use%s" % pkgName[0].upper() + pkgName[1:], "use %s if available" % (pkgName), default) + +def _BoolOption(opt, explanation, default=1): + """ Allow user to enable/disable a certain option. This results in a commandline option enable