From d9f566896848080d2563a33c23a6851be4da951f Mon Sep 17 00:00:00 2001 From: Ivan Epifanov Date: Wed, 27 Jan 2021 18:16:01 +0300 Subject: [PATCH] Master is for patchsets --- .github/workflows/ci.yml | 63 - .travis.yml | 124 - BSD-3Clause | 30 - CMakeLists.txt | 1606 ----------- COPYING | 437 --- ChangeLog | 567 ---- README.md | 62 +- XCompile-Android.txt | 11 - XCompile.txt | 37 - al/auxeffectslot.cpp | 1017 ------- al/auxeffectslot.h | 68 - al/buffer.cpp | 1631 ----------- al/buffer.h | 65 - al/effect.cpp | 745 ----- al/effect.h | 60 - al/effects/autowah.cpp | 109 - al/effects/chorus.cpp | 276 -- al/effects/compressor.cpp | 72 - al/effects/convolution.cpp | 93 - al/effects/dedicated.cpp | 72 - al/effects/distortion.cpp | 114 - al/effects/echo.cpp | 111 - al/effects/effects.h | 79 - al/effects/equalizer.cpp | 169 -- al/effects/fshifter.cpp | 128 - al/effects/modulator.cpp | 134 - al/effects/null.cpp | 93 - al/effects/pshifter.cpp | 84 - al/effects/reverb.cpp | 556 ---- al/effects/vmorpher.cpp | 247 -- al/error.cpp | 106 - al/event.cpp | 223 -- al/event.h | 9 - al/extension.cpp | 79 - al/filter.cpp | 714 ----- al/filter.h | 52 - al/listener.cpp | 452 --- al/listener.h | 31 - al/source.cpp | 3494 ----------------------- al/source.h | 127 - al/state.cpp | 893 ------ alc/alc.cpp | 4130 ---------------------------- alc/alcmain.h | 371 --- alc/alconfig.cpp | 542 ---- alc/alconfig.h | 20 - alc/alcontext.h | 282 -- alc/alu.cpp | 2018 -------------- alc/alu.h | 141 - alc/async_event.h | 49 - alc/backends/alsa.cpp | 1268 --------- alc/backends/alsa.h | 19 - alc/backends/base.cpp | 194 -- alc/backends/base.h | 119 - alc/backends/coreaudio.cpp | 686 ----- alc/backends/coreaudio.h | 19 - alc/backends/dsound.cpp | 868 ------ alc/backends/dsound.h | 19 - alc/backends/jack.cpp | 601 ---- alc/backends/jack.h | 19 - alc/backends/loopback.cpp | 79 - alc/backends/loopback.h | 19 - alc/backends/null.cpp | 179 -- alc/backends/null.h | 19 - alc/backends/oboe.cpp | 250 -- alc/backends/oboe.h | 19 - alc/backends/opensl.cpp | 974 ------- alc/backends/opensl.h | 19 - alc/backends/oss.cpp | 686 ----- alc/backends/oss.h | 19 - alc/backends/portaudio.cpp | 442 --- alc/backends/portaudio.h | 19 - alc/backends/pulseaudio.cpp | 1521 ---------- alc/backends/pulseaudio.h | 19 - alc/backends/sdl2.cpp | 216 -- alc/backends/sdl2.h | 19 - alc/backends/sndio.cpp | 517 ---- alc/backends/sndio.h | 19 - alc/backends/solaris.cpp | 294 -- alc/backends/solaris.h | 19 - alc/backends/wasapi.cpp | 1847 ------------- alc/backends/wasapi.h | 19 - alc/backends/wave.cpp | 405 --- alc/backends/wave.h | 19 - alc/backends/winmm.cpp | 631 ----- alc/backends/winmm.h | 19 - alc/bformatdec.cpp | 298 -- alc/bformatdec.h | 75 - alc/buffer_storage.cpp | 38 - alc/buffer_storage.h | 88 - alc/compat.h | 9 - alc/converter.cpp | 370 --- alc/converter.h | 59 - alc/effects/autowah.cpp | 212 -- alc/effects/base.h | 206 -- alc/effects/chorus.cpp | 287 -- alc/effects/compressor.cpp | 168 -- alc/effects/convolution.cpp | 567 ---- alc/effects/dedicated.cpp | 110 - alc/effects/distortion.cpp | 167 -- alc/effects/echo.cpp | 168 -- alc/effects/equalizer.cpp | 184 -- alc/effects/fshifter.cpp | 232 -- alc/effects/modulator.cpp | 173 -- alc/effects/null.cpp | 79 - alc/effects/pshifter.cpp | 260 -- alc/effects/reverb.cpp | 1704 ------------ alc/effects/vmorpher.cpp | 314 --- alc/effectslot.cpp | 25 - alc/effectslot.h | 89 - alc/front_stablizer.h | 36 - alc/helpers.cpp | 435 --- alc/hrtf.cpp | 1473 ---------- alc/hrtf.h | 90 - alc/inprogext.h | 73 - alc/panning.cpp | 1210 -------- alc/uiddefs.cpp | 37 - alc/voice.cpp | 807 ------ alc/voice.h | 224 -- alc/voice_change.h | 31 - alsoftrc.sample | 553 ---- appveyor.yml | 15 - build/.empty | 0 cmake/FindALSA.cmake | 73 - cmake/FindAudioIO.cmake | 21 - cmake/FindFFmpeg.cmake | 171 -- cmake/FindJACK.cmake | 60 - cmake/FindMySOFA.cmake | 81 - cmake/FindOSS.cmake | 33 - cmake/FindOboe.cmake | 31 - cmake/FindOpenSL.cmake | 63 - cmake/FindPortAudio.cmake | 32 - cmake/FindPulseAudio.cmake | 43 - cmake/FindSDL2.cmake | 191 -- cmake/FindSndFile.cmake | 25 - cmake/FindSoundIO.cmake | 32 - cmake/bin2h.script.cmake | 13 - common/albit.h | 35 - common/albyte.h | 67 - common/alcomplex.cpp | 79 - common/alcomplex.h | 38 - common/alfstream.cpp | 150 - common/alfstream.h | 74 - common/almalloc.cpp | 64 - common/almalloc.h | 291 -- common/alnumeric.h | 360 --- common/aloptional.h | 161 -- common/alspan.h | 315 --- common/alstring.cpp | 45 - common/alstring.h | 30 - common/atomic.h | 33 - common/dynload.cpp | 44 - common/dynload.h | 14 - common/intrusive_ptr.h | 120 - common/math_defs.h | 26 - common/opthelpers.h | 39 - common/polyphase_resampler.cpp | 222 -- common/polyphase_resampler.h | 45 - common/pragmadefs.h | 21 - common/ringbuffer.cpp | 224 -- common/ringbuffer.h | 113 - common/strutils.cpp | 64 - common/strutils.h | 24 - common/threads.cpp | 176 -- common/threads.h | 48 - common/vecmat.h | 118 - common/vector.h | 15 - common/win_main_utf8.h | 117 - config.h.in | 120 - core/ambdec.cpp | 375 --- core/ambdec.h | 52 - core/ambidefs.h | 171 -- core/bs2b.cpp | 183 -- core/bs2b.h | 89 - core/bsinc_defs.h | 16 - core/bsinc_tables.cpp | 288 -- core/bsinc_tables.h | 17 - core/bufferline.h | 14 - core/cpu_caps.cpp | 142 - core/cpu_caps.h | 26 - core/devformat.cpp | 65 - core/devformat.h | 106 - core/except.cpp | 31 - core/except.h | 31 - core/filters/biquad.cpp | 163 -- core/filters/biquad.h | 144 - core/filters/nfc.cpp | 383 --- core/filters/nfc.h | 63 - core/filters/splitter.cpp | 113 - core/filters/splitter.h | 36 - core/fmt_traits.cpp | 79 - core/fmt_traits.h | 81 - core/fpu_ctrl.cpp | 56 - core/fpu_ctrl.h | 21 - core/logging.cpp | 95 - core/logging.h | 47 - core/mastering.cpp | 441 --- core/mastering.h | 104 - core/mixer/defs.h | 101 - core/mixer/hrtfbase.h | 159 -- core/mixer/hrtfdefs.h | 53 - core/mixer/mixer_c.cpp | 198 -- core/mixer/mixer_neon.cpp | 305 -- core/mixer/mixer_sse.cpp | 271 -- core/mixer/mixer_sse2.cpp | 89 - core/mixer/mixer_sse3.cpp | 0 core/mixer/mixer_sse41.cpp | 94 - core/uhjfilter.cpp | 275 -- core/uhjfilter.h | 39 - docs/3D7.1.txt | 82 - docs/ambdec.txt | 189 -- docs/ambisonics.txt | 119 - docs/env-vars.txt | 78 - docs/hrtf.txt | 83 - examples/alconvolve.c | 594 ---- examples/alffplay.cpp | 2111 -------------- examples/alhrtf.c | 302 -- examples/allatency.c | 217 -- examples/alloopback.c | 286 -- examples/almultireverb.c | 688 ----- examples/alplay.c | 180 -- examples/alrecord.c | 403 --- examples/alreverb.c | 344 --- examples/alstream.c | 325 --- examples/alstreamcb.cpp | 404 --- examples/altonegen.c | 330 --- examples/common/alhelpers.c | 193 -- examples/common/alhelpers.h | 25 - hrtf/Default HRTF.mhr | Bin 80353 -> 0 bytes include/AL/al.h | 655 ----- include/AL/alc.h | 270 -- include/AL/alext.h | 586 ---- include/AL/efx-creative.h | 3 - include/AL/efx-presets.h | 402 --- include/AL/efx.h | 762 ----- openal-soft-1.19.1-vita-0.patch | 718 +++++ openal.pc.in | 12 - presets/3D7.1.ambdec | 43 - presets/hexagon.ambdec | 51 - presets/itu5.1-nocenter.ambdec | 46 - presets/itu5.1.ambdec | 48 - presets/presets.txt | 42 - presets/rectangle.ambdec | 45 - presets/square.ambdec | 45 - resources/openal32.rc | 90 - resources/resource.h | 15 - resources/router.rc | 90 - resources/soft_oal.rc | 90 - router/al.cpp | 132 - router/alc.cpp | 932 ------- router/router.cpp | 439 --- router/router.h | 192 -- utils/CIAIR.def | 3958 -------------------------- utils/IRC_1005.def | 425 --- utils/MIT_KEMAR.def | 844 ------ utils/MIT_KEMAR_sofa.def | 51 - utils/SCUT_KEMAR.def | 48 - utils/alsoft-config/CMakeLists.txt | 31 - utils/alsoft-config/main.cpp | 11 - utils/alsoft-config/mainwindow.cpp | 1423 ---------- utils/alsoft-config/mainwindow.h | 85 - utils/alsoft-config/mainwindow.ui | 2572 ----------------- utils/alsoft-config/verstr.cpp | 10 - utils/alsoft-config/verstr.h | 8 - utils/getopt.c | 137 - utils/getopt.h | 26 - utils/makemhr/loaddef.cpp | 2026 -------------- utils/makemhr/loaddef.h | 13 - utils/makemhr/loadsofa.cpp | 568 ---- utils/makemhr/loadsofa.h | 10 - utils/makemhr/makemhr.cpp | 1681 ----------- utils/makemhr/makemhr.h | 120 - utils/openal-info.c | 441 --- utils/sofa-info.cpp | 139 - utils/sofa-support.cpp | 292 -- utils/sofa-support.h | 30 - version.cmake | 11 - version.h.in | 9 - 277 files changed, 722 insertions(+), 81644 deletions(-) delete mode 100644 .github/workflows/ci.yml delete mode 100644 .travis.yml delete mode 100644 BSD-3Clause delete mode 100644 CMakeLists.txt delete mode 100644 COPYING delete mode 100644 ChangeLog delete mode 100644 XCompile-Android.txt delete mode 100644 XCompile.txt delete mode 100644 al/auxeffectslot.cpp delete mode 100644 al/auxeffectslot.h delete mode 100644 al/buffer.cpp delete mode 100644 al/buffer.h delete mode 100644 al/effect.cpp delete mode 100644 al/effect.h delete mode 100644 al/effects/autowah.cpp delete mode 100644 al/effects/chorus.cpp delete mode 100644 al/effects/compressor.cpp delete mode 100644 al/effects/convolution.cpp delete mode 100644 al/effects/dedicated.cpp delete mode 100644 al/effects/distortion.cpp delete mode 100644 al/effects/echo.cpp delete mode 100644 al/effects/effects.h delete mode 100644 al/effects/equalizer.cpp delete mode 100644 al/effects/fshifter.cpp delete mode 100644 al/effects/modulator.cpp delete mode 100644 al/effects/null.cpp delete mode 100644 al/effects/pshifter.cpp delete mode 100644 al/effects/reverb.cpp delete mode 100644 al/effects/vmorpher.cpp delete mode 100644 al/error.cpp delete mode 100644 al/event.cpp delete mode 100644 al/event.h delete mode 100644 al/extension.cpp delete mode 100644 al/filter.cpp delete mode 100644 al/filter.h delete mode 100644 al/listener.cpp delete mode 100644 al/listener.h delete mode 100644 al/source.cpp delete mode 100644 al/source.h delete mode 100644 al/state.cpp delete mode 100644 alc/alc.cpp delete mode 100644 alc/alcmain.h delete mode 100644 alc/alconfig.cpp delete mode 100644 alc/alconfig.h delete mode 100644 alc/alcontext.h delete mode 100644 alc/alu.cpp delete mode 100644 alc/alu.h delete mode 100644 alc/async_event.h delete mode 100644 alc/backends/alsa.cpp delete mode 100644 alc/backends/alsa.h delete mode 100644 alc/backends/base.cpp delete mode 100644 alc/backends/base.h delete mode 100644 alc/backends/coreaudio.cpp delete mode 100644 alc/backends/coreaudio.h delete mode 100644 alc/backends/dsound.cpp delete mode 100644 alc/backends/dsound.h delete mode 100644 alc/backends/jack.cpp delete mode 100644 alc/backends/jack.h delete mode 100644 alc/backends/loopback.cpp delete mode 100644 alc/backends/loopback.h delete mode 100644 alc/backends/null.cpp delete mode 100644 alc/backends/null.h delete mode 100644 alc/backends/oboe.cpp delete mode 100644 alc/backends/oboe.h delete mode 100644 alc/backends/opensl.cpp delete mode 100644 alc/backends/opensl.h delete mode 100644 alc/backends/oss.cpp delete mode 100644 alc/backends/oss.h delete mode 100644 alc/backends/portaudio.cpp delete mode 100644 alc/backends/portaudio.h delete mode 100644 alc/backends/pulseaudio.cpp delete mode 100644 alc/backends/pulseaudio.h delete mode 100644 alc/backends/sdl2.cpp delete mode 100644 alc/backends/sdl2.h delete mode 100644 alc/backends/sndio.cpp delete mode 100644 alc/backends/sndio.h delete mode 100644 alc/backends/solaris.cpp delete mode 100644 alc/backends/solaris.h delete mode 100644 alc/backends/wasapi.cpp delete mode 100644 alc/backends/wasapi.h delete mode 100644 alc/backends/wave.cpp delete mode 100644 alc/backends/wave.h delete mode 100644 alc/backends/winmm.cpp delete mode 100644 alc/backends/winmm.h delete mode 100644 alc/bformatdec.cpp delete mode 100644 alc/bformatdec.h delete mode 100644 alc/buffer_storage.cpp delete mode 100644 alc/buffer_storage.h delete mode 100644 alc/compat.h delete mode 100644 alc/converter.cpp delete mode 100644 alc/converter.h delete mode 100644 alc/effects/autowah.cpp delete mode 100644 alc/effects/base.h delete mode 100644 alc/effects/chorus.cpp delete mode 100644 alc/effects/compressor.cpp delete mode 100644 alc/effects/convolution.cpp delete mode 100644 alc/effects/dedicated.cpp delete mode 100644 alc/effects/distortion.cpp delete mode 100644 alc/effects/echo.cpp delete mode 100644 alc/effects/equalizer.cpp delete mode 100644 alc/effects/fshifter.cpp delete mode 100644 alc/effects/modulator.cpp delete mode 100644 alc/effects/null.cpp delete mode 100644 alc/effects/pshifter.cpp delete mode 100644 alc/effects/reverb.cpp delete mode 100644 alc/effects/vmorpher.cpp delete mode 100644 alc/effectslot.cpp delete mode 100644 alc/effectslot.h delete mode 100644 alc/front_stablizer.h delete mode 100644 alc/helpers.cpp delete mode 100644 alc/hrtf.cpp delete mode 100644 alc/hrtf.h delete mode 100644 alc/inprogext.h delete mode 100644 alc/panning.cpp delete mode 100644 alc/uiddefs.cpp delete mode 100644 alc/voice.cpp delete mode 100644 alc/voice.h delete mode 100644 alc/voice_change.h delete mode 100644 alsoftrc.sample delete mode 100644 appveyor.yml delete mode 100644 build/.empty delete mode 100644 cmake/FindALSA.cmake delete mode 100644 cmake/FindAudioIO.cmake delete mode 100644 cmake/FindFFmpeg.cmake delete mode 100644 cmake/FindJACK.cmake delete mode 100644 cmake/FindMySOFA.cmake delete mode 100644 cmake/FindOSS.cmake delete mode 100644 cmake/FindOboe.cmake delete mode 100644 cmake/FindOpenSL.cmake delete mode 100644 cmake/FindPortAudio.cmake delete mode 100644 cmake/FindPulseAudio.cmake delete mode 100644 cmake/FindSDL2.cmake delete mode 100644 cmake/FindSndFile.cmake delete mode 100644 cmake/FindSoundIO.cmake delete mode 100644 cmake/bin2h.script.cmake delete mode 100644 common/albit.h delete mode 100644 common/albyte.h delete mode 100644 common/alcomplex.cpp delete mode 100644 common/alcomplex.h delete mode 100644 common/alfstream.cpp delete mode 100644 common/alfstream.h delete mode 100644 common/almalloc.cpp delete mode 100644 common/almalloc.h delete mode 100644 common/alnumeric.h delete mode 100644 common/aloptional.h delete mode 100644 common/alspan.h delete mode 100644 common/alstring.cpp delete mode 100644 common/alstring.h delete mode 100644 common/atomic.h delete mode 100644 common/dynload.cpp delete mode 100644 common/dynload.h delete mode 100644 common/intrusive_ptr.h delete mode 100644 common/math_defs.h delete mode 100644 common/opthelpers.h delete mode 100644 common/polyphase_resampler.cpp delete mode 100644 common/polyphase_resampler.h delete mode 100644 common/pragmadefs.h delete mode 100644 common/ringbuffer.cpp delete mode 100644 common/ringbuffer.h delete mode 100644 common/strutils.cpp delete mode 100644 common/strutils.h delete mode 100644 common/threads.cpp delete mode 100644 common/threads.h delete mode 100644 common/vecmat.h delete mode 100644 common/vector.h delete mode 100644 common/win_main_utf8.h delete mode 100644 config.h.in delete mode 100644 core/ambdec.cpp delete mode 100644 core/ambdec.h delete mode 100644 core/ambidefs.h delete mode 100644 core/bs2b.cpp delete mode 100644 core/bs2b.h delete mode 100644 core/bsinc_defs.h delete mode 100644 core/bsinc_tables.cpp delete mode 100644 core/bsinc_tables.h delete mode 100644 core/bufferline.h delete mode 100644 core/cpu_caps.cpp delete mode 100644 core/cpu_caps.h delete mode 100644 core/devformat.cpp delete mode 100644 core/devformat.h delete mode 100644 core/except.cpp delete mode 100644 core/except.h delete mode 100644 core/filters/biquad.cpp delete mode 100644 core/filters/biquad.h delete mode 100644 core/filters/nfc.cpp delete mode 100644 core/filters/nfc.h delete mode 100644 core/filters/splitter.cpp delete mode 100644 core/filters/splitter.h delete mode 100644 core/fmt_traits.cpp delete mode 100644 core/fmt_traits.h delete mode 100644 core/fpu_ctrl.cpp delete mode 100644 core/fpu_ctrl.h delete mode 100644 core/logging.cpp delete mode 100644 core/logging.h delete mode 100644 core/mastering.cpp delete mode 100644 core/mastering.h delete mode 100644 core/mixer/defs.h delete mode 100644 core/mixer/hrtfbase.h delete mode 100644 core/mixer/hrtfdefs.h delete mode 100644 core/mixer/mixer_c.cpp delete mode 100644 core/mixer/mixer_neon.cpp delete mode 100644 core/mixer/mixer_sse.cpp delete mode 100644 core/mixer/mixer_sse2.cpp delete mode 100644 core/mixer/mixer_sse3.cpp delete mode 100644 core/mixer/mixer_sse41.cpp delete mode 100644 core/uhjfilter.cpp delete mode 100644 core/uhjfilter.h delete mode 100644 docs/3D7.1.txt delete mode 100644 docs/ambdec.txt delete mode 100644 docs/ambisonics.txt delete mode 100644 docs/env-vars.txt delete mode 100644 docs/hrtf.txt delete mode 100644 examples/alconvolve.c delete mode 100644 examples/alffplay.cpp delete mode 100644 examples/alhrtf.c delete mode 100644 examples/allatency.c delete mode 100644 examples/alloopback.c delete mode 100644 examples/almultireverb.c delete mode 100644 examples/alplay.c delete mode 100644 examples/alrecord.c delete mode 100644 examples/alreverb.c delete mode 100644 examples/alstream.c delete mode 100644 examples/alstreamcb.cpp delete mode 100644 examples/altonegen.c delete mode 100644 examples/common/alhelpers.c delete mode 100644 examples/common/alhelpers.h delete mode 100644 hrtf/Default HRTF.mhr delete mode 100644 include/AL/al.h delete mode 100644 include/AL/alc.h delete mode 100644 include/AL/alext.h delete mode 100644 include/AL/efx-creative.h delete mode 100644 include/AL/efx-presets.h delete mode 100644 include/AL/efx.h create mode 100644 openal-soft-1.19.1-vita-0.patch delete mode 100644 openal.pc.in delete mode 100644 presets/3D7.1.ambdec delete mode 100644 presets/hexagon.ambdec delete mode 100644 presets/itu5.1-nocenter.ambdec delete mode 100644 presets/itu5.1.ambdec delete mode 100644 presets/presets.txt delete mode 100644 presets/rectangle.ambdec delete mode 100644 presets/square.ambdec delete mode 100644 resources/openal32.rc delete mode 100644 resources/resource.h delete mode 100644 resources/router.rc delete mode 100644 resources/soft_oal.rc delete mode 100644 router/al.cpp delete mode 100644 router/alc.cpp delete mode 100644 router/router.cpp delete mode 100644 router/router.h delete mode 100644 utils/CIAIR.def delete mode 100644 utils/IRC_1005.def delete mode 100644 utils/MIT_KEMAR.def delete mode 100644 utils/MIT_KEMAR_sofa.def delete mode 100644 utils/SCUT_KEMAR.def delete mode 100644 utils/alsoft-config/CMakeLists.txt delete mode 100644 utils/alsoft-config/main.cpp delete mode 100644 utils/alsoft-config/mainwindow.cpp delete mode 100644 utils/alsoft-config/mainwindow.h delete mode 100644 utils/alsoft-config/mainwindow.ui delete mode 100644 utils/alsoft-config/verstr.cpp delete mode 100644 utils/alsoft-config/verstr.h delete mode 100644 utils/getopt.c delete mode 100644 utils/getopt.h delete mode 100644 utils/makemhr/loaddef.cpp delete mode 100644 utils/makemhr/loaddef.h delete mode 100644 utils/makemhr/loadsofa.cpp delete mode 100644 utils/makemhr/loadsofa.h delete mode 100644 utils/makemhr/makemhr.cpp delete mode 100644 utils/makemhr/makemhr.h delete mode 100644 utils/openal-info.c delete mode 100644 utils/sofa-info.cpp delete mode 100644 utils/sofa-support.cpp delete mode 100644 utils/sofa-support.h delete mode 100644 version.cmake delete mode 100644 version.h.in diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml deleted file mode 100644 index edf853c7..00000000 --- a/.github/workflows/ci.yml +++ /dev/null @@ -1,63 +0,0 @@ -name: CI - -on: [push] - -jobs: - build: - name: ${{matrix.config.name}} - runs-on: ${{matrix.config.os}} - strategy: - matrix: - config: - - { - name: "Visual Studio 64-bit", - os: windows-latest, - cmake_opts: "-A x64 \ - -DALSOFT_BUILD_ROUTER=ON \ - -DALSOFT_REQUIRE_WINMM=ON \ - -DALSOFT_REQUIRE_DSOUND=ON \ - -DALSOFT_REQUIRE_WASAPI=ON", - build_type: "Release" - } - - { - name: "macOS", - os: macos-latest, - cmake_opts: "-DALSOFT_REQUIRE_COREAUDIO=ON", - build_type: "Release" - } - - { - name: "Linux", - os: ubuntu-latest, - cmake_opts: "-DALSOFT_REQUIRE_ALSA=ON \ - -DALSOFT_REQUIRE_OSS=ON \ - -DALSOFT_REQUIRE_PORTAUDIO=ON \ - -DALSOFT_REQUIRE_PULSEAUDIO=ON \ - -DALSOFT_REQUIRE_JACK=ON", - deps_cmdline: "sudo apt update && sudo apt-get install -qq \ - libpulse-dev \ - portaudio19-dev \ - libasound2-dev \ - libjack-dev \ - qtbase5-dev", - build_type: "Release" - } - - steps: - - uses: actions/checkout@v1 - - - name: Install Dependencies - shell: bash - run: | - if [[ ! -z "${{matrix.config.deps_cmdline}}" ]]; then - eval ${{matrix.config.deps_cmdline}} - fi - - - name: Configure - shell: bash - run: | - cmake -B build -DCMAKE_BUILD_TYPE=${{matrix.config.build_type}} ${{matrix.config.cmake_opts}} . - - - name: Build - shell: bash - run: | - cmake --build build --config ${{matrix.config.build_type}} diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 5931c521..00000000 --- a/.travis.yml +++ /dev/null @@ -1,124 +0,0 @@ -language: cpp -matrix: - include: - - os: linux - dist: xenial - - os: linux - dist: trusty - env: - - BUILD_ANDROID=true - - os: freebsd - compiler: clang - - os: osx - - os: osx - osx_image: xcode11 - env: - - BUILD_IOS=true -sudo: required -install: - - > - if [[ "${TRAVIS_OS_NAME}" == "linux" && -z "${BUILD_ANDROID}" ]]; then - # Install pulseaudio, portaudio, ALSA, JACK dependencies for - # corresponding backends. - # Install Qt5 dependency for alsoft-config. - sudo apt-get install -qq \ - libpulse-dev \ - portaudio19-dev \ - libasound2-dev \ - libjack-dev \ - qtbase5-dev - fi - - > - if [[ "${TRAVIS_OS_NAME}" == "linux" && "${BUILD_ANDROID}" == "true" ]]; then - curl -o ~/android-ndk.zip https://dl.google.com/android/repository/android-ndk-r21-linux-x86_64.zip - unzip -q ~/android-ndk.zip -d ~ \ - 'android-ndk-r21/build/cmake/*' \ - 'android-ndk-r21/build/core/toolchains/arm-linux-androideabi-*/*' \ - 'android-ndk-r21/platforms/android-16/arch-arm/*' \ - 'android-ndk-r21/source.properties' \ - 'android-ndk-r21/sources/android/support/include/*' \ - 'android-ndk-r21/sources/cxx-stl/llvm-libc++/libs/armeabi-v7a/*' \ - 'android-ndk-r21/sources/cxx-stl/llvm-libc++/include/*' \ - 'android-ndk-r21/sysroot/*' \ - 'android-ndk-r21/toolchains/arm-linux-androideabi-4.9/prebuilt/linux-x86_64/*' \ - 'android-ndk-r21/toolchains/llvm/prebuilt/linux-x86_64/*' - export OBOE_LOC=~/oboe - git clone --depth 1 -b 1.3-stable https://github.com/google/oboe "$OBOE_LOC" - fi - - > - if [[ "${TRAVIS_OS_NAME}" == "freebsd" ]]; then - # Install Ninja as it's used downstream. - # Install dependencies for all supported backends. - # Install Qt5 dependency for alsoft-config. - # Install ffmpeg for examples. - sudo pkg install -y \ - alsa-lib \ - ffmpeg \ - jackit \ - libmysofa \ - ninja \ - portaudio \ - pulseaudio \ - qt5-buildtools \ - qt5-qmake \ - qt5-widgets \ - sdl2 \ - sndio \ - $NULL - fi -script: - - cmake --version - - > - if [[ "${TRAVIS_OS_NAME}" == "linux" && -z "${BUILD_ANDROID}" ]]; then - cmake \ - -DALSOFT_REQUIRE_ALSA=ON \ - -DALSOFT_REQUIRE_OSS=ON \ - -DALSOFT_REQUIRE_PORTAUDIO=ON \ - -DALSOFT_REQUIRE_PULSEAUDIO=ON \ - -DALSOFT_REQUIRE_JACK=ON \ - -DALSOFT_EMBED_HRTF_DATA=YES \ - . - fi - - > - if [[ "${TRAVIS_OS_NAME}" == "linux" && "${BUILD_ANDROID}" == "true" ]]; then - cmake \ - -DANDROID_STL=c++_shared \ - -DCMAKE_TOOLCHAIN_FILE=~/android-ndk-r21/build/cmake/android.toolchain.cmake \ - -DOBOE_SOURCE="$OBOE_LOC" \ - -DALSOFT_REQUIRE_OBOE=ON \ - -DALSOFT_REQUIRE_OPENSL=ON \ - -DALSOFT_EMBED_HRTF_DATA=YES \ - . - fi - - > - if [[ "${TRAVIS_OS_NAME}" == "freebsd" ]]; then - cmake -GNinja \ - -DALSOFT_REQUIRE_ALSA=ON \ - -DALSOFT_REQUIRE_JACK=ON \ - -DALSOFT_REQUIRE_OSS=ON \ - -DALSOFT_REQUIRE_PORTAUDIO=ON \ - -DALSOFT_REQUIRE_PULSEAUDIO=ON \ - -DALSOFT_REQUIRE_SDL2=ON \ - -DALSOFT_REQUIRE_SNDIO=ON \ - -DALSOFT_EMBED_HRTF_DATA=YES \ - . - fi - - > - if [[ "${TRAVIS_OS_NAME}" == "osx" && -z "${BUILD_IOS}" ]]; then - cmake \ - -DALSOFT_REQUIRE_COREAUDIO=ON \ - -DALSOFT_EMBED_HRTF_DATA=YES \ - . - fi - - > - if [[ "${TRAVIS_OS_NAME}" == "osx" && "${BUILD_IOS}" == "true" ]]; then - cmake \ - -GXcode \ - -DCMAKE_SYSTEM_NAME=iOS \ - -DALSOFT_OSX_FRAMEWORK=ON \ - -DALSOFT_REQUIRE_COREAUDIO=ON \ - -DALSOFT_EMBED_HRTF_DATA=YES \ - "-DCMAKE_OSX_ARCHITECTURES=armv7;arm64" \ - . - fi - - cmake --build . --clean-first diff --git a/BSD-3Clause b/BSD-3Clause deleted file mode 100644 index 45cc8e6d..00000000 --- a/BSD-3Clause +++ /dev/null @@ -1,30 +0,0 @@ -Portions of this software are licensed under the BSD 3-Clause license. - -Copyright (c) 2015, Archontis Politis -Copyright (c) 2019, Christopher Robinson -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -* Neither the name of Spherical-Harmonic-Transform nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/CMakeLists.txt b/CMakeLists.txt deleted file mode 100644 index 444049d2..00000000 --- a/CMakeLists.txt +++ /dev/null @@ -1,1606 +0,0 @@ -# CMake build file list for OpenAL - -cmake_minimum_required(VERSION 3.0.2) - -# The workaround for try_compile failing with code signing -# since cmake-3.18.2, not required -set(CMAKE_TRY_COMPILE_PLATFORM_VARIABLES - "CMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_REQUIRED" - "CMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_ALLOWED") -set(CMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_REQUIRED NO) -set(CMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_ALLOWED NO) - -# Fix compile failure with armv7 deployment target >= 11.0, xcode clang will -# report: -# error: invalid iOS deployment version '--target=armv7-apple-ios13.6', -# iOS 10 is the maximum deployment target for 32-bit targets -# If CMAKE_OSX_DEPLOYMENT_TARGET is not defined, cmake will choose latest -# deployment target -if(CMAKE_SYSTEM_NAME STREQUAL "iOS") - if("${CMAKE_OSX_ARCHITECTURES}" MATCHES ".*armv7.*") - if(NOT DEFINED CMAKE_OSX_DEPLOYMENT_TARGET - OR NOT CMAKE_OSX_DEPLOYMENT_TARGET VERSION_LESS "11.0") - message(STATUS "Forcing iOS deployment target to 10.0 for armv7") - set(CMAKE_OSX_DEPLOYMENT_TARGET "10.0" CACHE STRING "Minimum OS X deployment version" - FORCE) - endif() - endif() -endif() - -project(OpenAL) - -if(COMMAND CMAKE_POLICY) - cmake_policy(SET CMP0003 NEW) - cmake_policy(SET CMP0005 NEW) - if(POLICY CMP0020) - cmake_policy(SET CMP0020 NEW) - endif(POLICY CMP0020) - if(POLICY CMP0042) - cmake_policy(SET CMP0042 NEW) - endif(POLICY CMP0042) - if(POLICY CMP0054) - cmake_policy(SET CMP0054 NEW) - endif(POLICY CMP0054) - if(POLICY CMP0075) - cmake_policy(SET CMP0075 NEW) - endif(POLICY CMP0075) -endif(COMMAND CMAKE_POLICY) - -if(NOT CMAKE_BUILD_TYPE) - set(CMAKE_BUILD_TYPE RelWithDebInfo CACHE STRING - "Choose the type of build, options are: Debug Release RelWithDebInfo MinSizeRel." - FORCE) -endif() -if(NOT CMAKE_DEBUG_POSTFIX) - set(CMAKE_DEBUG_POSTFIX "" CACHE STRING - "Library postfix for debug builds. Normally left blank." - FORCE) -endif() - -set(CMAKE_MODULE_PATH "${OpenAL_SOURCE_DIR}/cmake") - -include(CheckFunctionExists) -include(CheckLibraryExists) -include(CheckIncludeFile) -include(CheckIncludeFiles) -include(CheckSymbolExists) -include(CheckCCompilerFlag) -include(CheckCXXCompilerFlag) -include(CheckCSourceCompiles) -include(CheckCXXSourceCompiles) -include(CheckStructHasMember) -include(GNUInstallDirs) - - -option(ALSOFT_DLOPEN "Check for the dlopen API for loading optional libs" ON) - -option(ALSOFT_WERROR "Treat compile warnings as errors" OFF) - -option(ALSOFT_UTILS "Build utility programs" ON) -option(ALSOFT_NO_CONFIG_UTIL "Disable building the alsoft-config utility" OFF) - -option(ALSOFT_EXAMPLES "Build example programs" ON) - -option(ALSOFT_INSTALL "Install main library" ON) -option(ALSOFT_INSTALL_CONFIG "Install alsoft.conf sample configuration file" ON) -option(ALSOFT_INSTALL_HRTF_DATA "Install HRTF data files" ON) -option(ALSOFT_INSTALL_AMBDEC_PRESETS "Install AmbDec preset files" ON) -option(ALSOFT_INSTALL_EXAMPLES "Install example programs (alplay, alstream, ...)" ON) -option(ALSOFT_INSTALL_UTILS "Install utility programs (openal-info, alsoft-config, ...)" ON) -option(ALSOFT_UPDATE_BUILD_VERSION "Update git build version info" ON) - -if(DEFINED SHARE_INSTALL_DIR) - message(WARNING "SHARE_INSTALL_DIR is deprecated. Use the variables provided by the GNUInstallDirs module instead") - set(CMAKE_INSTALL_DATADIR "${SHARE_INSTALL_DIR}") -endif() - -if(DEFINED LIB_SUFFIX) - message(WARNING "LIB_SUFFIX is deprecated. Use the variables provided by the GNUInstallDirs module instead") -endif() -if(DEFINED ALSOFT_CONFIG) - message(WARNING "ALSOFT_CONFIG is deprecated. Use ALSOFT_INSTALL_CONFIG instead") -endif() -if(DEFINED ALSOFT_HRTF_DEFS) - message(WARNING "ALSOFT_HRTF_DEFS is deprecated. Use ALSOFT_INSTALL_HRTF_DATA instead") -endif() -if(DEFINED ALSOFT_AMBDEC_PRESETS) - message(WARNING "ALSOFT_AMBDEC_PRESETS is deprecated. Use ALSOFT_INSTALL_AMBDEC_PRESETS instead") -endif() - - -set(CPP_DEFS ) # C pre-processor, not C++ -set(INC_PATHS ) -set(C_FLAGS ) -set(LINKER_FLAGS ) -set(EXTRA_LIBS ) - -if(WIN32) - set(CPP_DEFS ${CPP_DEFS} _WIN32) - if(MINGW) - set(CPP_DEFS ${CPP_DEFS} __USE_MINGW_ANSI_STDIO) - endif() - - option(ALSOFT_BUILD_ROUTER "Build the router (EXPERIMENTAL; creates OpenAL32.dll and soft_oal.dll)" OFF) - if(MINGW) - option(ALSOFT_BUILD_IMPORT_LIB "Build an import .lib using dlltool (requires sed)" ON) - endif() -elseif(APPLE) - option(ALSOFT_OSX_FRAMEWORK "Build as macOS framework" OFF) -endif() - - -# QNX's gcc do not uses /usr/include and /usr/lib pathes by default -if("${CMAKE_C_PLATFORM_ID}" STREQUAL "QNX") - set(INC_PATHS ${INC_PATHS} /usr/include) - set(LINKER_FLAGS ${LINKER_FLAGS} -L/usr/lib) -endif() - -# When the library is built for static linking, apps should define -# AL_LIBTYPE_STATIC when including the AL headers. -if(NOT LIBTYPE) - set(LIBTYPE SHARED) -endif() - -set(LIB_MAJOR_VERSION "1") -set(LIB_MINOR_VERSION "21") -set(LIB_REVISION "0") -set(LIB_VERSION "${LIB_MAJOR_VERSION}.${LIB_MINOR_VERSION}.${LIB_REVISION}") -set(LIB_VERSION_NUM ${LIB_MAJOR_VERSION},${LIB_MINOR_VERSION},${LIB_REVISION},0) - -set(EXPORT_DECL "") - - -# Require C++14 -set(CMAKE_CXX_STANDARD 14) -set(CMAKE_CXX_STANDARD_REQUIRED TRUE) - -# Prefer C11, but support C99 and C90 too. -set(CMAKE_C_STANDARD 11) - -if(NOT WIN32) - # Check if _POSIX_C_SOURCE and _XOPEN_SOURCE needs to be set for POSIX functions - check_symbol_exists(posix_memalign stdlib.h HAVE_POSIX_MEMALIGN_DEFAULT) - if(NOT HAVE_POSIX_MEMALIGN_DEFAULT) - set(OLD_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS}) - set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} -D_POSIX_C_SOURCE=200112L -D_XOPEN_SOURCE=600") - check_symbol_exists(posix_memalign stdlib.h HAVE_POSIX_MEMALIGN_POSIX) - if(NOT HAVE_POSIX_MEMALIGN_POSIX) - set(CMAKE_REQUIRED_FLAGS ${OLD_REQUIRED_FLAGS}) - else() - set(CPP_DEFS ${CPP_DEFS} _POSIX_C_SOURCE=200112L _XOPEN_SOURCE=600) - endif() - endif() - unset(OLD_REQUIRED_FLAGS) -endif() - -# C99 has restrict, but C++ does not, so we can only utilize __restrict. -check_cxx_source_compiles("int *__restrict foo; -int main() { return 0; }" HAVE___RESTRICT) -if(HAVE___RESTRICT) - set(CPP_DEFS ${CPP_DEFS} RESTRICT=__restrict) -else() - set(CPP_DEFS ${CPP_DEFS} "RESTRICT=") -endif() - -# Some systems may need libatomic for atomic functions to work -set(OLD_REQUIRED_LIBRARIES ${CMAKE_REQUIRED_LIBRARIES}) -set(CMAKE_REQUIRED_LIBRARIES ${OLD_REQUIRED_LIBRARIES} atomic) -check_cxx_source_compiles("#include -std::atomic foo{0}; -int main() { return foo.fetch_add(2); }" -HAVE_LIBATOMIC) -if(NOT HAVE_LIBATOMIC) - set(CMAKE_REQUIRED_LIBRARIES "${OLD_REQUIRED_LIBRARIES}") -else() - set(EXTRA_LIBS atomic ${EXTRA_LIBS}) -endif() -unset(OLD_REQUIRED_LIBRARIES) - -# Include liblog for Android logging -check_library_exists(log __android_log_print "" HAVE_LIBLOG) -if(HAVE_LIBLOG) - set(EXTRA_LIBS log ${EXTRA_LIBS}) - set(CMAKE_REQUIRED_LIBRARIES ${CMAKE_REQUIRED_LIBRARIES} log) -endif() - -if(MSVC) - set(CPP_DEFS ${CPP_DEFS} _CRT_SECURE_NO_WARNINGS NOMINMAX) - check_cxx_compiler_flag(/permissive- HAVE_PERMISSIVE_SWITCH) - if(HAVE_PERMISSIVE_SWITCH) - set(C_FLAGS ${C_FLAGS} $<$:/permissive->) - endif() - set(C_FLAGS ${C_FLAGS} /W4 /w14640 /wd4065 /wd4268 /wd4324 /wd5030) - # Remove /W3, which is added by default, since we set /W4. Some build - # generators with MSVC complain about both /W3 and /W4 being specified. - foreach(flag_var CMAKE_C_FLAGS CMAKE_CXX_FLAGS) - if(${flag_var} MATCHES "/W3") - string(REGEX REPLACE "/W3" "" ${flag_var} "${${flag_var}}") - endif() - endforeach() - - if(NOT DXSDK_DIR) - string(REGEX REPLACE "\\\\" "/" DXSDK_DIR "$ENV{DXSDK_DIR}") - else() - string(REGEX REPLACE "\\\\" "/" DXSDK_DIR "${DXSDK_DIR}") - endif() - if(DXSDK_DIR) - message(STATUS "Using DirectX SDK directory: ${DXSDK_DIR}") - endif() - - option(FORCE_STATIC_VCRT "Force /MT for static VC runtimes" OFF) - if(FORCE_STATIC_VCRT) - foreach(flag_var - CMAKE_C_FLAGS CMAKE_C_FLAGS_DEBUG CMAKE_C_FLAGS_RELEASE - CMAKE_C_FLAGS_MINSIZEREL CMAKE_C_FLAGS_RELWITHDEBINFO - CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE - CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELWITHDEBINFO) - if(${flag_var} MATCHES "/MD") - string(REGEX REPLACE "/MD" "/MT" ${flag_var} "${${flag_var}}") - endif() - endforeach(flag_var) - endif() -else() - set(C_FLAGS ${C_FLAGS} -Winline -Wunused -Wall -Wextra -Wshadow -Wconversion -Wcast-align - -Wpedantic - $<$:-Wold-style-cast -Wnon-virtual-dtor -Woverloaded-virtual>) - - if(ALSOFT_WERROR) - set(C_FLAGS ${C_FLAGS} -Werror) - endif() - - # We want RelWithDebInfo to actually include debug stuff (define _DEBUG - # instead of NDEBUG) - foreach(flag_var CMAKE_C_FLAGS_RELWITHDEBINFO CMAKE_CXX_FLAGS_RELWITHDEBINFO) - if(${flag_var} MATCHES "-DNDEBUG") - string(REGEX REPLACE "-DNDEBUG" "-D_DEBUG" ${flag_var} "${${flag_var}}") - endif() - endforeach() - - check_c_compiler_flag(-fno-math-errno HAVE_FNO_MATH_ERRNO) - if(HAVE_FNO_MATH_ERRNO) - set(C_FLAGS ${C_FLAGS} -fno-math-errno) - endif() - - option(ALSOFT_STATIC_LIBGCC "Force -static-libgcc for static GCC runtimes" OFF) - if(ALSOFT_STATIC_LIBGCC) - set(OLD_REQUIRED_LIBRARIES ${CMAKE_REQUIRED_LIBRARIES}) - set(CMAKE_REQUIRED_LIBRARIES ${CMAKE_REQUIRED_LIBRARIES} -static-libgcc) - check_cxx_source_compiles("int main() { }" HAVE_STATIC_LIBGCC_SWITCH) - set(CMAKE_REQUIRED_LIBRARIES ${OLD_REQUIRED_LIBRARIES}) - unset(OLD_REQUIRED_LIBRARIES) - - if(NOT HAVE_STATIC_LIBGCC_SWITCH) - message(FATAL_ERROR "Cannot static link libgcc") - endif() - set(LINKER_FLAGS ${LINKER_FLAGS} -static-libgcc) - endif() - - option(ALSOFT_STATIC_STDCXX "Static link libstdc++" OFF) - if(ALSOFT_STATIC_STDCXX) - set(OLD_REQUIRED_LIBRARIES ${CMAKE_REQUIRED_LIBRARIES}) - set(CMAKE_REQUIRED_LIBRARIES ${CMAKE_REQUIRED_LIBRARIES} "-Wl,--push-state,-Bstatic,-lstdc++,--pop-state") - check_cxx_source_compiles("int main() { }" HAVE_STATIC_LIBSTDCXX_SWITCH) - set(CMAKE_REQUIRED_LIBRARIES ${OLD_REQUIRED_LIBRARIES}) - unset(OLD_REQUIRED_LIBRARIES) - - if(NOT HAVE_STATIC_LIBSTDCXX_SWITCH) - message(FATAL_ERROR "Cannot static link libstdc++") - endif() - set(LINKER_FLAGS ${LINKER_FLAGS} "-Wl,--push-state,-Bstatic,-lstdc++,--pop-state") - endif() - - if(WIN32) - option(ALSOFT_STATIC_WINPTHREAD "Static link libwinpthread" OFF) - if(ALSOFT_STATIC_WINPTHREAD) - set(OLD_REQUIRED_LIBRARIES ${CMAKE_REQUIRED_LIBRARIES}) - set(CMAKE_REQUIRED_LIBRARIES ${CMAKE_REQUIRED_LIBRARIES} "-Wl,--push-state,-Bstatic,-lwinpthread,--pop-state") - check_cxx_source_compiles("int main() { }" HAVE_STATIC_LIBWINPTHREAD_SWITCH) - set(CMAKE_REQUIRED_LIBRARIES ${OLD_REQUIRED_LIBRARIES}) - unset(OLD_REQUIRED_LIBRARIES) - - if(NOT HAVE_STATIC_LIBWINPTHREAD_SWITCH) - message(FATAL_ERROR "Cannot static link libwinpthread") - endif() - set(LINKER_FLAGS ${LINKER_FLAGS} "-Wl,--push-state,-Bstatic,-lwinpthread,--pop-state") - endif() - endif() -endif() - -# Set visibility/export options if available -if(WIN32) - if(NOT LIBTYPE STREQUAL "STATIC") - set(EXPORT_DECL "__declspec(dllexport)") - endif() -else() - set(OLD_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS}") - # Yes GCC, really don't accept visibility modes you don't support - set(CMAKE_REQUIRED_FLAGS "${OLD_REQUIRED_FLAGS} -Wattributes -Werror") - - check_c_source_compiles("int foo() __attribute__((visibility(\"protected\"))); - int main() {return 0;}" HAVE_GCC_PROTECTED_VISIBILITY) - if(HAVE_GCC_PROTECTED_VISIBILITY) - if(NOT LIBTYPE STREQUAL "STATIC") - set(EXPORT_DECL "__attribute__((visibility(\"protected\")))") - endif() - else() - check_c_source_compiles("int foo() __attribute__((visibility(\"default\"))); - int main() {return 0;}" HAVE_GCC_DEFAULT_VISIBILITY) - if(HAVE_GCC_DEFAULT_VISIBILITY) - if(NOT LIBTYPE STREQUAL "STATIC") - set(EXPORT_DECL "__attribute__((visibility(\"default\")))") - endif() - endif() - endif() - - if(HAVE_GCC_PROTECTED_VISIBILITY OR HAVE_GCC_DEFAULT_VISIBILITY) - check_c_compiler_flag(-fvisibility=hidden HAVE_VISIBILITY_HIDDEN_SWITCH) - if(HAVE_VISIBILITY_HIDDEN_SWITCH) - set(C_FLAGS ${C_FLAGS} -fvisibility=hidden) - endif() - endif() - - set(CMAKE_REQUIRED_FLAGS "${OLD_REQUIRED_FLAGS}") -endif() - - -set(SSE2_SWITCH "") - -set(OLD_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS}) -if(NOT MSVC) - # Yes GCC, really don't accept command line options you don't support - set(CMAKE_REQUIRED_FLAGS "${OLD_REQUIRED_FLAGS} -Werror") -endif() -check_c_compiler_flag(-msse2 HAVE_MSSE2_SWITCH) -if(HAVE_MSSE2_SWITCH) - set(SSE2_SWITCH "-msse2") -endif() -set(CMAKE_REQUIRED_FLAGS ${OLD_REQUIRED_FLAGS}) -unset(OLD_REQUIRED_FLAGS) - -check_include_file(xmmintrin.h HAVE_XMMINTRIN_H) -check_include_file(emmintrin.h HAVE_EMMINTRIN_H) -check_include_file(pmmintrin.h HAVE_PMMINTRIN_H) -check_include_file(smmintrin.h HAVE_SMMINTRIN_H) -check_include_file(arm_neon.h HAVE_ARM_NEON_H) - -set(HAVE_SSE 0) -set(HAVE_SSE2 0) -set(HAVE_SSE3 0) -set(HAVE_SSE4_1 0) -set(HAVE_NEON 0) - -# Check for SSE+SSE2 support -option(ALSOFT_REQUIRE_SSE "Require SSE support" OFF) -option(ALSOFT_REQUIRE_SSE2 "Require SSE2 support" OFF) -if(HAVE_XMMINTRIN_H AND HAVE_EMMINTRIN_H) - option(ALSOFT_CPUEXT_SSE "Enable SSE support" ON) - option(ALSOFT_CPUEXT_SSE2 "Enable SSE2 support" ON) - if(ALSOFT_CPUEXT_SSE AND ALSOFT_CPUEXT_SSE2) - set(HAVE_SSE 1) - set(HAVE_SSE2 1) - endif() -endif() -if(ALSOFT_REQUIRE_SSE AND NOT HAVE_SSE) - message(FATAL_ERROR "Failed to enabled required SSE CPU extensions") -endif() -if(ALSOFT_REQUIRE_SSE2 AND NOT HAVE_SSE2) - message(FATAL_ERROR "Failed to enable required SSE2 CPU extensions") -endif() - -option(ALSOFT_REQUIRE_SSE3 "Require SSE3 support" OFF) -if(HAVE_PMMINTRIN_H) - option(ALSOFT_CPUEXT_SSE3 "Enable SSE3 support" ON) - if(HAVE_SSE2 AND ALSOFT_CPUEXT_SSE3) - set(HAVE_SSE3 1) - endif() -endif() -if(ALSOFT_REQUIRE_SSE3 AND NOT HAVE_SSE3) - message(FATAL_ERROR "Failed to enable required SSE3 CPU extensions") -endif() - -option(ALSOFT_REQUIRE_SSE4_1 "Require SSE4.1 support" OFF) -if(HAVE_SMMINTRIN_H) - option(ALSOFT_CPUEXT_SSE4_1 "Enable SSE4.1 support" ON) - if(HAVE_SSE3 AND ALSOFT_CPUEXT_SSE4_1) - set(HAVE_SSE4_1 1) - endif() -endif() -if(ALSOFT_REQUIRE_SSE4_1 AND NOT HAVE_SSE4_1) - message(FATAL_ERROR "Failed to enable required SSE4.1 CPU extensions") -endif() - -# Check for ARM Neon support -option(ALSOFT_REQUIRE_NEON "Require ARM NEON support" OFF) -if(HAVE_ARM_NEON_H) - option(ALSOFT_CPUEXT_NEON "Enable ARM NEON support" ON) - if(ALSOFT_CPUEXT_NEON) - check_c_source_compiles("#include - int main() - { - int32x4_t ret4 = vdupq_n_s32(0); - return vgetq_lane_s32(ret4, 0); - }" HAVE_NEON_INTRINSICS) - if(HAVE_NEON_INTRINSICS) - set(HAVE_NEON 1) - endif() - endif() -endif() -if(ALSOFT_REQUIRE_NEON AND NOT HAVE_NEON) - message(FATAL_ERROR "Failed to enabled required ARM NEON CPU extensions") -endif() - - -set(SSE_FLAGS ) -set(FPMATH_SET "0") -if(CMAKE_SIZEOF_VOID_P MATCHES "4" AND HAVE_SSE2) - option(ALSOFT_ENABLE_SSE2_CODEGEN "Enable SSE2 code generation instead of x87 for 32-bit targets." TRUE) - if(ALSOFT_ENABLE_SSE2_CODEGEN) - if(SSE2_SWITCH OR NOT MSVC) - check_c_compiler_flag("${SSE2_SWITCH} -mfpmath=sse" HAVE_MFPMATH_SSE_2) - if(HAVE_MFPMATH_SSE_2) - set(SSE_FLAGS ${SSE_FLAGS} ${SSE2_SWITCH} -mfpmath=sse) - set(C_FLAGS ${C_FLAGS} ${SSE_FLAGS}) - set(FPMATH_SET 2) - endif() - # SSE depends on a 16-byte aligned stack, and by default, GCC - # assumes the stack is suitably aligned. Older Linux code or other - # OSs don't guarantee this on 32-bit, so externally-callable - # functions need to ensure an aligned stack. - set(EXPORT_DECL "${EXPORT_DECL} __attribute__((force_align_arg_pointer))") - elseif(MSVC) - check_c_compiler_flag("/arch:SSE2" HAVE_ARCH_SSE2) - if(HAVE_ARCH_SSE2) - set(SSE_FLAGS ${SSE_FLAGS} "/arch:SSE2") - set(C_FLAGS ${C_FLAGS} ${SSE_FLAGS}) - set(FPMATH_SET 2) - endif() - endif() - endif() -endif() - -if(HAVE_SSE2) - set(OLD_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS}) - foreach(flag_var ${SSE_FLAGS}) - set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} ${flag_var}") - endforeach() - - check_c_source_compiles("#include - int main() {_mm_pause(); return 0;}" HAVE_SSE_INTRINSICS) - - set(CMAKE_REQUIRED_FLAGS ${OLD_REQUIRED_FLAGS}) -endif() - - -check_include_file(malloc.h HAVE_MALLOC_H) -check_include_file(cpuid.h HAVE_CPUID_H) -check_include_file(intrin.h HAVE_INTRIN_H) -check_include_file(guiddef.h HAVE_GUIDDEF_H) -if(NOT HAVE_GUIDDEF_H) - check_include_file(initguid.h HAVE_INITGUID_H) -endif() - -# Some systems need libm for some math functions to work -set(MATH_LIB ) -check_library_exists(m pow "" HAVE_LIBM) -if(HAVE_LIBM) - set(MATH_LIB ${MATH_LIB} m) - set(CMAKE_REQUIRED_LIBRARIES ${CMAKE_REQUIRED_LIBRARIES} m) -endif() - -# Some systems need to link with -lrt for clock_gettime as used by the common -# eaxmple functions. -set(RT_LIB ) -check_library_exists(rt clock_gettime "" HAVE_LIBRT) -if(HAVE_LIBRT) - set(RT_LIB rt) -endif() - -# Check for the dlopen API (for dynamicly loading backend libs) -if(ALSOFT_DLOPEN) - check_include_file(dlfcn.h HAVE_DLFCN_H) - check_library_exists(dl dlopen "" HAVE_LIBDL) - if(HAVE_LIBDL) - set(EXTRA_LIBS dl ${EXTRA_LIBS}) - set(CMAKE_REQUIRED_LIBRARIES ${CMAKE_REQUIRED_LIBRARIES} dl) - endif() -endif() - -# Check for a cpuid intrinsic -if(HAVE_CPUID_H) - check_c_source_compiles("#include - int main() - { - unsigned int eax, ebx, ecx, edx; - return __get_cpuid(0, &eax, &ebx, &ecx, &edx); - }" HAVE_GCC_GET_CPUID) -endif() -if(HAVE_INTRIN_H) - check_c_source_compiles("#include - int main() - { - int regs[4]; - __cpuid(regs, 0); - return regs[0]; - }" HAVE_CPUID_INTRINSIC) -endif() - -check_cxx_source_compiles("#include -int main() -{ - void *ptr{std::aligned_alloc(alignof(int), sizeof(int))}; - std::free(ptr); - return 0; -}" HAVE_STD_ALIGNED_ALLOC) -check_symbol_exists(posix_memalign stdlib.h HAVE_POSIX_MEMALIGN) -check_symbol_exists(_aligned_malloc malloc.h HAVE__ALIGNED_MALLOC) -check_symbol_exists(proc_pidpath libproc.h HAVE_PROC_PIDPATH) - -if(NOT WIN32) - # We need pthreads outside of Windows, for semaphores. It's also used to - # set the priority and name of threads, when possible. - check_include_file(pthread.h HAVE_PTHREAD_H) - if(NOT HAVE_PTHREAD_H) - message(FATAL_ERROR "PThreads is required for non-Windows builds!") - endif() - - check_c_compiler_flag(-pthread HAVE_PTHREAD) - if(HAVE_PTHREAD) - set(CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS} -pthread") - set(C_FLAGS ${C_FLAGS} -pthread) - set(LINKER_FLAGS ${LINKER_FLAGS} -pthread) - endif() - - check_symbol_exists(pthread_setschedparam pthread.h HAVE_PTHREAD_SETSCHEDPARAM) - - # Some systems need pthread_np.h to get pthread_setname_np - check_include_files("pthread.h;pthread_np.h" HAVE_PTHREAD_NP_H) - if(HAVE_PTHREAD_NP_H) - check_symbol_exists(pthread_setname_np "pthread.h;pthread_np.h" HAVE_PTHREAD_SETNAME_NP) - if(NOT HAVE_PTHREAD_SETNAME_NP) - check_symbol_exists(pthread_set_name_np "pthread.h;pthread_np.h" HAVE_PTHREAD_SET_NAME_NP) - else() - check_c_source_compiles(" -#include -#include -int main() -{ - pthread_setname_np(\"testname\"); - return 0; -}" - PTHREAD_SETNAME_NP_ONE_PARAM - ) - check_c_source_compiles(" -#include -#include -int main() -{ - pthread_setname_np(pthread_self(), \"%s\", \"testname\"); - return 0; -}" - PTHREAD_SETNAME_NP_THREE_PARAMS - ) - endif() - else() - check_symbol_exists(pthread_setname_np pthread.h HAVE_PTHREAD_SETNAME_NP) - if(NOT HAVE_PTHREAD_SETNAME_NP) - check_symbol_exists(pthread_set_name_np pthread.h HAVE_PTHREAD_SET_NAME_NP) - else() - check_c_source_compiles(" -#include -int main() -{ - pthread_setname_np(\"testname\"); - return 0; -}" - PTHREAD_SETNAME_NP_ONE_PARAM - ) - check_c_source_compiles(" -#include -int main() -{ - pthread_setname_np(pthread_self(), \"%s\", \"testname\"); - return 0; -}" - PTHREAD_SETNAME_NP_THREE_PARAMS - ) - endif() - endif() -endif() - -check_symbol_exists(getopt unistd.h HAVE_GETOPT) - - -# Common sources used by both the OpenAL implementation library, the OpenAL -# router, and certain tools and examples. -set(COMMON_OBJS - common/albit.h - common/albyte.h - common/alcomplex.cpp - common/alcomplex.h - common/alfstream.cpp - common/alfstream.h - common/almalloc.cpp - common/almalloc.h - common/alnumeric.h - common/aloptional.h - common/alspan.h - common/alstring.cpp - common/alstring.h - common/atomic.h - common/dynload.cpp - common/dynload.h - common/intrusive_ptr.h - common/math_defs.h - common/opthelpers.h - common/polyphase_resampler.cpp - common/polyphase_resampler.h - common/pragmadefs.h - common/ringbuffer.cpp - common/ringbuffer.h - common/strutils.cpp - common/strutils.h - common/threads.cpp - common/threads.h - common/vecmat.h - common/vector.h) - -# Core library routines -set(CORE_OBJS - core/ambdec.cpp - core/ambdec.h - core/ambidefs.h - core/bs2b.cpp - core/bs2b.h - core/bsinc_defs.h - core/bsinc_tables.cpp - core/bsinc_tables.h - core/bufferline.h - core/cpu_caps.cpp - core/cpu_caps.h - core/devformat.cpp - core/devformat.h - core/except.cpp - core/except.h - core/filters/biquad.h - core/filters/biquad.cpp - core/filters/nfc.cpp - core/filters/nfc.h - core/filters/splitter.cpp - core/filters/splitter.h - core/fmt_traits.cpp - core/fmt_traits.h - core/fpu_ctrl.cpp - core/fpu_ctrl.h - core/logging.cpp - core/logging.h - core/mastering.cpp - core/mastering.h - core/uhjfilter.cpp - core/uhjfilter.h - core/mixer/defs.h - core/mixer/hrtfbase.h - core/mixer/hrtfdefs.h - core/mixer/mixer_c.cpp) - -# AL and related routines -set(OPENAL_OBJS - al/auxeffectslot.cpp - al/auxeffectslot.h - al/buffer.cpp - al/buffer.h - al/effect.cpp - al/effect.h - al/effects/autowah.cpp - al/effects/chorus.cpp - al/effects/compressor.cpp - al/effects/convolution.cpp - al/effects/dedicated.cpp - al/effects/distortion.cpp - al/effects/echo.cpp - al/effects/effects.h - al/effects/equalizer.cpp - al/effects/fshifter.cpp - al/effects/modulator.cpp - al/effects/null.cpp - al/effects/pshifter.cpp - al/effects/reverb.cpp - al/effects/vmorpher.cpp - al/error.cpp - al/event.cpp - al/event.h - al/extension.cpp - al/filter.cpp - al/filter.h - al/listener.cpp - al/listener.h - al/source.cpp - al/source.h - al/state.cpp) - -# ALC and related routines -set(ALC_OBJS - alc/alc.cpp - alc/alcmain.h - alc/alu.cpp - alc/alu.h - alc/alconfig.cpp - alc/alconfig.h - alc/alcontext.h - alc/async_event.h - alc/bformatdec.cpp - alc/bformatdec.h - alc/buffer_storage.cpp - alc/buffer_storage.h - alc/compat.h - alc/converter.cpp - alc/converter.h - alc/effectslot.cpp - alc/effectslot.h - alc/effects/base.h - alc/effects/autowah.cpp - alc/effects/chorus.cpp - alc/effects/compressor.cpp - alc/effects/convolution.cpp - alc/effects/dedicated.cpp - alc/effects/distortion.cpp - alc/effects/echo.cpp - alc/effects/equalizer.cpp - alc/effects/fshifter.cpp - alc/effects/modulator.cpp - alc/effects/null.cpp - alc/effects/pshifter.cpp - alc/effects/reverb.cpp - alc/effects/vmorpher.cpp - alc/front_stablizer.h - alc/helpers.cpp - alc/hrtf.cpp - alc/hrtf.h - alc/inprogext.h - alc/panning.cpp - alc/uiddefs.cpp - alc/voice.cpp - alc/voice.h - alc/voice_change.h) - -# Include SIMD mixers -set(CPU_EXTS "Default") -if(HAVE_SSE2) - set(CORE_OBJS ${CORE_OBJS} core/mixer/mixer_sse.cpp core/mixer/mixer_sse2.cpp) - set(CPU_EXTS "${CPU_EXTS}, SSE, SSE2") -endif() -if(HAVE_SSE3) - set(CORE_OBJS ${CORE_OBJS} core/mixer/mixer_sse3.cpp) - set(CPU_EXTS "${CPU_EXTS}, SSE3") -endif() -if(HAVE_SSE4_1) - set(CORE_OBJS ${CORE_OBJS} core/mixer/mixer_sse41.cpp) - set(CPU_EXTS "${CPU_EXTS}, SSE4.1") -endif() -if(HAVE_NEON) - set(CORE_OBJS ${CORE_OBJS} core/mixer/mixer_neon.cpp) - set(CPU_EXTS "${CPU_EXTS}, Neon") -endif() - - -set(HAVE_ALSA 0) -set(HAVE_OSS 0) -set(HAVE_SOLARIS 0) -set(HAVE_SNDIO 0) -set(HAVE_DSOUND 0) -set(HAVE_WASAPI 0) -set(HAVE_WINMM 0) -set(HAVE_PORTAUDIO 0) -set(HAVE_PULSEAUDIO 0) -set(HAVE_COREAUDIO 0) -set(HAVE_OPENSL 0) -set(HAVE_OBOE 0) -set(HAVE_WAVE 0) -set(HAVE_SDL2 0) - -if(WIN32 OR HAVE_DLFCN_H) - set(IS_LINKED "") - macro(ADD_BACKEND_LIBS _LIBS) - endmacro() -else() - set(IS_LINKED " (linked)") - macro(ADD_BACKEND_LIBS _LIBS) - set(EXTRA_LIBS ${_LIBS} ${EXTRA_LIBS}) - endmacro() -endif() - -set(BACKENDS "") -set(ALC_OBJS ${ALC_OBJS} - alc/backends/base.cpp - alc/backends/base.h - # Default backends, always available - alc/backends/loopback.cpp - alc/backends/loopback.h - alc/backends/null.cpp - alc/backends/null.h -) - -# Check ALSA backend -option(ALSOFT_REQUIRE_ALSA "Require ALSA backend" OFF) -find_package(ALSA) -if(ALSA_FOUND) - option(ALSOFT_BACKEND_ALSA "Enable ALSA backend" ON) - if(ALSOFT_BACKEND_ALSA) - set(HAVE_ALSA 1) - set(BACKENDS "${BACKENDS} ALSA${IS_LINKED},") - set(ALC_OBJS ${ALC_OBJS} alc/backends/alsa.cpp alc/backends/alsa.h) - add_backend_libs(${ALSA_LIBRARIES}) - set(INC_PATHS ${INC_PATHS} ${ALSA_INCLUDE_DIRS}) - endif() -endif() -if(ALSOFT_REQUIRE_ALSA AND NOT HAVE_ALSA) - message(FATAL_ERROR "Failed to enabled required ALSA backend") -endif() - -# Check OSS backend -option(ALSOFT_REQUIRE_OSS "Require OSS backend" OFF) -find_package(OSS) -if(OSS_FOUND) - option(ALSOFT_BACKEND_OSS "Enable OSS backend" ON) - if(ALSOFT_BACKEND_OSS) - set(HAVE_OSS 1) - set(BACKENDS "${BACKENDS} OSS,") - set(ALC_OBJS ${ALC_OBJS} alc/backends/oss.cpp alc/backends/oss.h) - if(OSS_LIBRARIES) - set(EXTRA_LIBS ${OSS_LIBRARIES} ${EXTRA_LIBS}) - endif() - set(INC_PATHS ${INC_PATHS} ${OSS_INCLUDE_DIRS}) - endif() -endif() -if(ALSOFT_REQUIRE_OSS AND NOT HAVE_OSS) - message(FATAL_ERROR "Failed to enabled required OSS backend") -endif() - -# Check Solaris backend -option(ALSOFT_REQUIRE_SOLARIS "Require Solaris backend" OFF) -find_package(AudioIO) -if(AUDIOIO_FOUND) - option(ALSOFT_BACKEND_SOLARIS "Enable Solaris backend" ON) - if(ALSOFT_BACKEND_SOLARIS) - set(HAVE_SOLARIS 1) - set(BACKENDS "${BACKENDS} Solaris,") - set(ALC_OBJS ${ALC_OBJS} alc/backends/solaris.cpp alc/backends/solaris.h) - set(INC_PATHS ${INC_PATHS} ${AUDIOIO_INCLUDE_DIRS}) - endif() -endif() -if(ALSOFT_REQUIRE_SOLARIS AND NOT HAVE_SOLARIS) - message(FATAL_ERROR "Failed to enabled required Solaris backend") -endif() - -# Check SndIO backend -option(ALSOFT_REQUIRE_SNDIO "Require SndIO backend" OFF) -find_package(SoundIO) -if(SOUNDIO_FOUND) - option(ALSOFT_BACKEND_SNDIO "Enable SndIO backend" ON) - if(ALSOFT_BACKEND_SNDIO) - set(HAVE_SNDIO 1) - set(BACKENDS "${BACKENDS} SndIO (linked),") - set(ALC_OBJS ${ALC_OBJS} alc/backends/sndio.cpp alc/backends/sndio.h) - set(EXTRA_LIBS ${SOUNDIO_LIBRARIES} ${EXTRA_LIBS}) - set(INC_PATHS ${INC_PATHS} ${SOUNDIO_INCLUDE_DIRS}) - endif() -endif() -if(ALSOFT_REQUIRE_SNDIO AND NOT HAVE_SNDIO) - message(FATAL_ERROR "Failed to enabled required SndIO backend") -endif() - -# Check Windows-only backends -option(ALSOFT_REQUIRE_WINMM "Require Windows Multimedia backend" OFF) -option(ALSOFT_REQUIRE_DSOUND "Require DirectSound backend" OFF) -option(ALSOFT_REQUIRE_WASAPI "Require WASAPI backend" OFF) -if(WIN32) - # Check MMSystem backend - option(ALSOFT_BACKEND_WINMM "Enable Windows Multimedia backend" ON) - if(ALSOFT_BACKEND_WINMM) - set(HAVE_WINMM 1) - set(BACKENDS "${BACKENDS} WinMM,") - set(ALC_OBJS ${ALC_OBJS} alc/backends/winmm.cpp alc/backends/winmm.h) - # There doesn't seem to be good way to search for winmm.lib for MSVC. - # find_library doesn't find it without being told to look in a specific - # place in the WindowsSDK, but it links anyway. If there ends up being - # Windows targets without this, another means to detect it is needed. - set(EXTRA_LIBS winmm ${EXTRA_LIBS}) - endif() - - # Check DSound backend - check_include_file(dsound.h HAVE_DSOUND_H) - if(DXSDK_DIR) - find_path(DSOUND_INCLUDE_DIR NAMES "dsound.h" - PATHS "${DXSDK_DIR}" PATH_SUFFIXES include - DOC "The DirectSound include directory") - endif() - if(HAVE_DSOUND_H OR DSOUND_INCLUDE_DIR) - option(ALSOFT_BACKEND_DSOUND "Enable DirectSound backend" ON) - if(ALSOFT_BACKEND_DSOUND) - set(HAVE_DSOUND 1) - set(BACKENDS "${BACKENDS} DirectSound,") - set(ALC_OBJS ${ALC_OBJS} alc/backends/dsound.cpp alc/backends/dsound.h) - - if(NOT HAVE_DSOUND_H) - set(INC_PATHS ${INC_PATHS} ${DSOUND_INCLUDE_DIR}) - endif() - endif() - endif() - - # Check for WASAPI backend - check_include_file(mmdeviceapi.h HAVE_MMDEVICEAPI_H) - if(HAVE_MMDEVICEAPI_H) - option(ALSOFT_BACKEND_WASAPI "Enable WASAPI backend" ON) - if(ALSOFT_BACKEND_WASAPI) - set(HAVE_WASAPI 1) - set(BACKENDS "${BACKENDS} WASAPI,") - set(ALC_OBJS ${ALC_OBJS} alc/backends/wasapi.cpp alc/backends/wasapi.h) - endif() - endif() -endif() -if(ALSOFT_REQUIRE_WINMM AND NOT HAVE_WINMM) - message(FATAL_ERROR "Failed to enabled required WinMM backend") -endif() -if(ALSOFT_REQUIRE_DSOUND AND NOT HAVE_DSOUND) - message(FATAL_ERROR "Failed to enabled required DSound backend") -endif() -if(ALSOFT_REQUIRE_WASAPI AND NOT HAVE_WASAPI) - message(FATAL_ERROR "Failed to enabled required WASAPI backend") -endif() - -# Check PortAudio backend -option(ALSOFT_REQUIRE_PORTAUDIO "Require PortAudio backend" OFF) -find_package(PortAudio) -if(PORTAUDIO_FOUND) - option(ALSOFT_BACKEND_PORTAUDIO "Enable PortAudio backend" ON) - if(ALSOFT_BACKEND_PORTAUDIO) - set(HAVE_PORTAUDIO 1) - set(BACKENDS "${BACKENDS} PortAudio${IS_LINKED},") - set(ALC_OBJS ${ALC_OBJS} alc/backends/portaudio.cpp alc/backends/portaudio.h) - add_backend_libs(${PORTAUDIO_LIBRARIES}) - set(INC_PATHS ${INC_PATHS} ${PORTAUDIO_INCLUDE_DIRS}) - endif() -endif() -if(ALSOFT_REQUIRE_PORTAUDIO AND NOT HAVE_PORTAUDIO) - message(FATAL_ERROR "Failed to enabled required PortAudio backend") -endif() - -# Check PulseAudio backend -option(ALSOFT_REQUIRE_PULSEAUDIO "Require PulseAudio backend" OFF) -find_package(PulseAudio) -if(PULSEAUDIO_FOUND) - option(ALSOFT_BACKEND_PULSEAUDIO "Enable PulseAudio backend" ON) - if(ALSOFT_BACKEND_PULSEAUDIO) - set(HAVE_PULSEAUDIO 1) - set(BACKENDS "${BACKENDS} PulseAudio${IS_LINKED},") - set(ALC_OBJS ${ALC_OBJS} alc/backends/pulseaudio.cpp alc/backends/pulseaudio.h) - add_backend_libs(${PULSEAUDIO_LIBRARIES}) - set(INC_PATHS ${INC_PATHS} ${PULSEAUDIO_INCLUDE_DIRS}) - endif() -endif() -if(ALSOFT_REQUIRE_PULSEAUDIO AND NOT HAVE_PULSEAUDIO) - message(FATAL_ERROR "Failed to enabled required PulseAudio backend") -endif() - -# Check JACK backend -option(ALSOFT_REQUIRE_JACK "Require JACK backend" OFF) -find_package(JACK) -if(JACK_FOUND) - option(ALSOFT_BACKEND_JACK "Enable JACK backend" ON) - if(ALSOFT_BACKEND_JACK) - set(HAVE_JACK 1) - set(BACKENDS "${BACKENDS} JACK${IS_LINKED},") - set(ALC_OBJS ${ALC_OBJS} alc/backends/jack.cpp alc/backends/jack.h) - add_backend_libs(${JACK_LIBRARIES}) - set(INC_PATHS ${INC_PATHS} ${JACK_INCLUDE_DIRS}) - endif() -endif() -if(ALSOFT_REQUIRE_JACK AND NOT HAVE_JACK) - message(FATAL_ERROR "Failed to enabled required JACK backend") -endif() - -# Check CoreAudio backend -option(ALSOFT_REQUIRE_COREAUDIO "Require CoreAudio backend" OFF) -find_library(COREAUDIO_FRAMEWORK NAMES CoreAudio) -find_path(AUDIOUNIT_INCLUDE_DIR NAMES AudioUnit/AudioUnit.h) -if(COREAUDIO_FRAMEWORK AND AUDIOUNIT_INCLUDE_DIR) - option(ALSOFT_BACKEND_COREAUDIO "Enable CoreAudio backend" ON) - if(ALSOFT_BACKEND_COREAUDIO) - set(HAVE_COREAUDIO 1) - set(ALC_OBJS ${ALC_OBJS} alc/backends/coreaudio.cpp alc/backends/coreaudio.h) - set(BACKENDS "${BACKENDS} CoreAudio,") - if(CMAKE_SYSTEM_NAME STREQUAL "iOS") - find_library(COREFOUNDATION_FRAMEWORK NAMES CoreFoundation) - set(EXTRA_LIBS ${COREAUDIO_FRAMEWORK} ${COREFOUNDATION_FRAMEWORK} ${EXTRA_LIBS}) - else() - set(EXTRA_LIBS ${COREAUDIO_FRAMEWORK} /System/Library/Frameworks/AudioUnit.framework - /System/Library/Frameworks/ApplicationServices.framework ${EXTRA_LIBS}) - endif() - - # Some versions of OSX may need the AudioToolbox framework. Add it if - # it's found. - find_library(AUDIOTOOLBOX_LIBRARY NAMES AudioToolbox) - if(AUDIOTOOLBOX_LIBRARY) - set(EXTRA_LIBS ${AUDIOTOOLBOX_LIBRARY} ${EXTRA_LIBS}) - endif() - - set(INC_PATHS ${INC_PATHS} ${AUDIOUNIT_INCLUDE_DIR}) - endif() -endif() -if(ALSOFT_REQUIRE_COREAUDIO AND NOT HAVE_COREAUDIO) - message(FATAL_ERROR "Failed to enabled required CoreAudio backend") -endif() - -# Check for OpenSL (Android) backend -option(ALSOFT_REQUIRE_OPENSL "Require OpenSL backend" OFF) -find_package(OpenSL) -if(OPENSL_FOUND) - option(ALSOFT_BACKEND_OPENSL "Enable OpenSL backend" ON) - if(ALSOFT_BACKEND_OPENSL) - set(HAVE_OPENSL 1) - set(ALC_OBJS ${ALC_OBJS} alc/backends/opensl.cpp alc/backends/opensl.h) - set(BACKENDS "${BACKENDS} OpenSL,") - set(EXTRA_LIBS "OpenSL::OpenSLES" ${EXTRA_LIBS}) - endif() -endif() -if(ALSOFT_REQUIRE_OPENSL AND NOT HAVE_OPENSL) - message(FATAL_ERROR "Failed to enabled required OpenSL backend") -endif() - -# Check for Oboe (Android) backend -set(OBOE_TARGET ) -if(ANDROID) - set(OBOE_SOURCE "" CACHE STRING "Source directory for Oboe.") - if(OBOE_SOURCE) - # Force Oboe to build with hidden symbols. Don't want to be exporting - # them from OpenAL. - set(OLD_CXX_FLAGS ${CMAKE_CXX_FLAGS}) - check_cxx_compiler_flag(-fvisibility=hidden HAVE_VISIBILITY_HIDDEN_SWITCH) - if(HAVE_VISIBILITY_HIDDEN_SWITCH) - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fvisibility=hidden") - endif() - add_subdirectory(${OBOE_SOURCE} ./oboe) - set(CMAKE_CXX_FLAGS ${OLD_CXX_FLAGS}) - unset(OLD_CXX_FLAGS) - - set(OBOE_TARGET oboe) - else() - find_package(Oboe) - if(OBOE_FOUND) - set(OBOE_TARGET "oboe::oboe") - endif() - endif() -endif() - -option(ALSOFT_REQUIRE_OBOE "Require Oboe backend" OFF) -if(OBOE_TARGET) - option(ALSOFT_BACKEND_OBOE "Enable Oboe backend" ON) - if(ALSOFT_BACKEND_OBOE) - set(HAVE_OBOE 1) - set(ALC_OBJS ${ALC_OBJS} alc/backends/oboe.cpp alc/backends/oboe.h) - set(BACKENDS "${BACKENDS} Oboe,") - set(EXTRA_LIBS ${OBOE_TARGET} ${EXTRA_LIBS}) - endif() -endif() -if(ALSOFT_REQUIRE_OBOE AND NOT HAVE_OBOE) - message(FATAL_ERROR "Failed to enabled required Oboe backend") -endif() - -# Check for SDL2 backend -option(ALSOFT_REQUIRE_SDL2 "Require SDL2 backend" OFF) -find_package(SDL2) -if(SDL2_FOUND) - # Off by default, since it adds a runtime dependency - option(ALSOFT_BACKEND_SDL2 "Enable SDL2 backend" OFF) - if(ALSOFT_BACKEND_SDL2) - set(HAVE_SDL2 1) - set(ALC_OBJS ${ALC_OBJS} alc/backends/sdl2.cpp alc/backends/sdl2.h) - set(BACKENDS "${BACKENDS} SDL2,") - set(EXTRA_LIBS ${SDL2_LIBRARY} ${EXTRA_LIBS}) - set(INC_PATHS ${INC_PATHS} ${SDL2_INCLUDE_DIR}) - endif() -endif() -if(ALSOFT_REQUIRE_SDL2 AND NOT SDL2_FOUND) - message(FATAL_ERROR "Failed to enabled required SDL2 backend") -endif() - -# Optionally enable the Wave Writer backend -option(ALSOFT_BACKEND_WAVE "Enable Wave Writer backend" ON) -if(ALSOFT_BACKEND_WAVE) - set(HAVE_WAVE 1) - set(ALC_OBJS ${ALC_OBJS} alc/backends/wave.cpp alc/backends/wave.h) - set(BACKENDS "${BACKENDS} WaveFile,") -endif() - -# This is always available -set(BACKENDS "${BACKENDS} Null") - - -find_package(Git) -if(ALSOFT_UPDATE_BUILD_VERSION AND GIT_FOUND AND EXISTS "${OpenAL_SOURCE_DIR}/.git") - # Get the current working branch and its latest abbreviated commit hash - add_custom_target(build_version - ${CMAKE_COMMAND} -D GIT_EXECUTABLE=${GIT_EXECUTABLE} -D LIB_VERSION=${LIB_VERSION} - -D LIB_VERSION_NUM=${LIB_VERSION_NUM} -D SRC=${OpenAL_SOURCE_DIR}/version.h.in - -D DST=${OpenAL_BINARY_DIR}/version.h -P ${OpenAL_SOURCE_DIR}/version.cmake - WORKING_DIRECTORY "${OpenAL_SOURCE_DIR}" - VERBATIM - ) -else() - set(GIT_BRANCH "UNKNOWN") - set(GIT_COMMIT_HASH "unknown") - configure_file( - "${OpenAL_SOURCE_DIR}/version.h.in" - "${OpenAL_BINARY_DIR}/version.h") -endif() - - -option(ALSOFT_EMBED_HRTF_DATA "Embed the HRTF data files (increases library footprint)" ON) -if(ALSOFT_EMBED_HRTF_DATA) - macro(make_hrtf_header FILENAME VARNAME) - set(infile "${OpenAL_SOURCE_DIR}/hrtf/${FILENAME}") - set(outfile "${OpenAL_BINARY_DIR}/${VARNAME}.h") - - add_custom_command(OUTPUT "${outfile}" - COMMAND ${CMAKE_COMMAND} -D "INPUT_FILE=${infile}" -D "OUTPUT_FILE=${outfile}" - -D "VARIABLE_NAME=${VARNAME}" -P "${CMAKE_MODULE_PATH}/bin2h.script.cmake" - WORKING_DIRECTORY "${OpenAL_SOURCE_DIR}" - DEPENDS "${infile}" "${CMAKE_MODULE_PATH}/bin2h.script.cmake" - VERBATIM - ) - set(ALC_OBJS ${ALC_OBJS} "${outfile}") - endmacro() - - make_hrtf_header("Default HRTF.mhr" "hrtf_default") -endif() - - -if(ALSOFT_UTILS AND NOT ALSOFT_NO_CONFIG_UTIL) - find_package(Qt5Widgets) -endif() -if(ALSOFT_EXAMPLES) - find_package(SndFile) - find_package(SDL2) - if(SDL2_FOUND) - find_package(FFmpeg COMPONENTS AVFORMAT AVCODEC AVUTIL SWSCALE SWRESAMPLE) - endif() -endif() - -if(NOT WIN32) - set(LIBNAME "openal") -else() - set(LIBNAME "OpenAL32") -endif() - -# Needed for openal.pc.in -set(prefix ${CMAKE_INSTALL_PREFIX}) -set(exec_prefix "\${prefix}") -set(libdir "\${exec_prefix}/${CMAKE_INSTALL_LIBDIR}") -set(bindir "\${exec_prefix}/${CMAKE_INSTALL_BINDIR}") -set(includedir "\${prefix}/${CMAKE_INSTALL_INCLUDEDIR}") -set(PACKAGE_VERSION "${LIB_VERSION}") -set(PKG_CONFIG_CFLAGS ) -set(PKG_CONFIG_PRIVATE_LIBS ) -if(LIBTYPE STREQUAL "STATIC") - set(PKG_CONFIG_CFLAGS -DAL_LIBTYPE_STATIC) - foreach(FLAG ${LINKER_FLAGS} ${EXTRA_LIBS} ${MATH_LIB}) - # If this is already a linker flag, or is a full path+file, add it - # as-is. Otherwise, it's a name intended to be dressed as -lname. - if(FLAG MATCHES "^-.*" OR EXISTS "${FLAG}") - set(PKG_CONFIG_PRIVATE_LIBS "${PKG_CONFIG_PRIVATE_LIBS} ${FLAG}") - else() - set(PKG_CONFIG_PRIVATE_LIBS "${PKG_CONFIG_PRIVATE_LIBS} -l${FLAG}") - endif() - endforeach() -endif() - -# End configuration -configure_file( - "${OpenAL_SOURCE_DIR}/config.h.in" - "${OpenAL_BINARY_DIR}/config.h") -configure_file( - "${OpenAL_SOURCE_DIR}/openal.pc.in" - "${OpenAL_BINARY_DIR}/openal.pc" - @ONLY) - - -add_library(common STATIC EXCLUDE_FROM_ALL ${COMMON_OBJS}) -target_include_directories(common PRIVATE ${OpenAL_BINARY_DIR} ${OpenAL_SOURCE_DIR}/include) -target_compile_definitions(common PRIVATE ${CPP_DEFS}) -target_compile_options(common PRIVATE ${C_FLAGS}) -set_target_properties(common PROPERTIES POSITION_INDEPENDENT_CODE TRUE) - - -unset(HAS_ROUTER) -set(IMPL_TARGET OpenAL) # Either OpenAL or soft_oal. - -# Build main library -if(LIBTYPE STREQUAL "STATIC") - add_library(${IMPL_TARGET} STATIC ${COMMON_OBJS} ${OPENAL_OBJS} ${ALC_OBJS} ${CORE_OBJS}) - target_compile_definitions(${IMPL_TARGET} PUBLIC AL_LIBTYPE_STATIC) - target_link_libraries(${IMPL_TARGET} PRIVATE ${LINKER_FLAGS} ${EXTRA_LIBS} ${MATH_LIB}) - if(WIN32) - # This option is for static linking OpenAL Soft into another project - # that already defines the IDs. It is up to that project to ensure all - # required IDs are defined. - option(ALSOFT_NO_UID_DEFS "Do not define GUIDs, IIDs, CLSIDs, or PropertyKeys" OFF) - if(ALSOFT_NO_UID_DEFS) - target_compile_definitions(${IMPL_TARGET} PRIVATE AL_NO_UID_DEFS) - endif() - endif() -else() - set(RC_CONFIG resources/openal32.rc) - if(WIN32 AND ALSOFT_BUILD_ROUTER) - add_library(OpenAL SHARED - resources/router.rc - router/router.cpp - router/router.h - router/alc.cpp - router/al.cpp - ) - target_compile_definitions(OpenAL - PRIVATE AL_BUILD_LIBRARY AL_ALEXT_PROTOTYPES ${CPP_DEFS}) - target_compile_options(OpenAL PRIVATE ${C_FLAGS}) - target_link_libraries(OpenAL PRIVATE common ${LINKER_FLAGS}) - target_include_directories(OpenAL - PUBLIC - $ - $ - PRIVATE - ${OpenAL_SOURCE_DIR}/common - ${OpenAL_BINARY_DIR} - ) - set_target_properties(OpenAL PROPERTIES PREFIX "") - set_target_properties(OpenAL PROPERTIES OUTPUT_NAME ${LIBNAME}) - if(TARGET build_version) - add_dependencies(OpenAL build_version) - endif() - set(HAS_ROUTER 1) - - set(LIBNAME "soft_oal") - set(IMPL_TARGET soft_oal) - set(RC_CONFIG resources/soft_oal.rc) - endif() - - # !important: for osx framework public header works, the headers must be in - # the project - set(TARGET_PUBLIC_HEADERS include/AL/al.h include/AL/alc.h include/AL/alext.h include/AL/efx.h) - add_library(${IMPL_TARGET} SHARED ${OPENAL_OBJS} ${ALC_OBJS} ${CORE_OBJS} ${RC_CONFIG} - ${TARGET_PUBLIC_HEADERS}) - if(WIN32) - set_target_properties(${IMPL_TARGET} PROPERTIES PREFIX "") - endif() - target_link_libraries(${IMPL_TARGET} PRIVATE common ${LINKER_FLAGS} ${EXTRA_LIBS} ${MATH_LIB}) - - if(APPLE AND ALSOFT_OSX_FRAMEWORK) - # Sets framework name to soft_oal to avoid ambiguity with the system OpenAL.framework - set(LIBNAME "soft_oal") - if(GIT_FOUND) - EXECUTE_PROCESS(COMMAND ${GIT_EXECUTABLE} rev-list --count head - TIMEOUT 5 - OUTPUT_VARIABLE BUNDLE_VERSION - OUTPUT_STRIP_TRAILING_WHITESPACE) - else() - set(BUNDLE_VERSION 1) - endif() - - # Build: Fix rpath in iOS shared libraries - # If this flag is not set, the final dylib binary ld path will be - # /User/xxx/*/soft_oal.framework/soft_oal, which can't be loaded by iOS devices. - # See also: https://github.com/libjpeg-turbo/libjpeg-turbo/commit/c80ddef7a4ce21ace9e3ca0fd190d320cc8cdaeb - if(NOT CMAKE_SHARED_LIBRARY_RUNTIME_C_FLAG) - set(CMAKE_SHARED_LIBRARY_RUNTIME_C_FLAG "-Wl,-rpath,") - endif() - - set_target_properties(${IMPL_TARGET} PROPERTIES - FRAMEWORK TRUE - FRAMEWORK_VERSION C - MACOSX_FRAMEWORK_NAME "${IMPL_TARGET}" - MACOSX_FRAMEWORK_IDENTIFIER "org.openal-soft.openal" - MACOSX_FRAMEWORK_SHORT_VERSION_STRING ${LIB_VERSION} - MACOSX_FRAMEWORK_BUNDLE_VERSION ${BUNDLE_VERSION} - XCODE_ATTRIBUTE_CODE_SIGN_IDENTITY "" - XCODE_ATTRIBUTE_CODE_SIGNING_ALLOWED "NO" - XCODE_ATTRIBUTE_CODE_SIGNING_REQUIRED "NO" - PUBLIC_HEADER "${TARGET_PUBLIC_HEADERS}" - MACOSX_RPATH TRUE) - endif() -endif() - -target_include_directories(${IMPL_TARGET} - PUBLIC - $ - $ - PRIVATE - ${INC_PATHS} - ${OpenAL_BINARY_DIR} - ${OpenAL_SOURCE_DIR} - ${OpenAL_SOURCE_DIR}/alc - ${OpenAL_SOURCE_DIR}/common -) - -set_target_properties(${IMPL_TARGET} PROPERTIES OUTPUT_NAME ${LIBNAME} - VERSION ${LIB_VERSION} - SOVERSION ${LIB_MAJOR_VERSION} -) -target_compile_definitions(${IMPL_TARGET} - PRIVATE AL_BUILD_LIBRARY AL_ALEXT_PROTOTYPES ${CPP_DEFS}) -target_compile_options(${IMPL_TARGET} PRIVATE ${C_FLAGS}) - -if(TARGET build_version) - add_dependencies(${IMPL_TARGET} build_version) -endif() - -if(WIN32 AND MINGW AND ALSOFT_BUILD_IMPORT_LIB AND NOT LIBTYPE STREQUAL "STATIC") - find_program(SED_EXECUTABLE NAMES sed DOC "sed executable") - if(NOT SED_EXECUTABLE OR NOT CMAKE_DLLTOOL) - message(STATUS "") - if(NOT SED_EXECUTABLE) - message(STATUS "WARNING: Cannot find sed, disabling .def/.lib generation") - endif() - if(NOT CMAKE_DLLTOOL) - message(STATUS "WARNING: Cannot find dlltool, disabling .def/.lib generation") - endif() - else() - set_property(TARGET OpenAL APPEND_STRING PROPERTY - LINK_FLAGS " -Wl,--output-def,OpenAL32.def") - add_custom_command(TARGET OpenAL POST_BUILD - COMMAND "${SED_EXECUTABLE}" -i -e "s/ @[^ ]*//" OpenAL32.def - COMMAND "${CMAKE_DLLTOOL}" -d OpenAL32.def -l OpenAL32.lib -D OpenAL32.dll - COMMENT "Stripping ordinals from OpenAL32.def and generating OpenAL32.lib..." - VERBATIM - ) - endif() -endif() - -if(HAS_ROUTER) - message(STATUS "") - message(STATUS "Building DLL router") -endif() - -message(STATUS " -Building OpenAL with support for the following backends: - ${BACKENDS} - -Building with support for CPU extensions: - ${CPU_EXTS} -") -if(FPMATH_SET) - message(STATUS "Building with SSE${FPMATH_SET} codegen -") -endif() - -if(ALSOFT_EMBED_HRTF_DATA) - message(STATUS "Embedding HRTF datasets -") -endif() - -# Install main library -if(ALSOFT_INSTALL) - install(TARGETS OpenAL EXPORT OpenAL - RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} - LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} - ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} - FRAMEWORK DESTINATION ${CMAKE_INSTALL_LIBDIR} - INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} ${CMAKE_INSTALL_INCLUDEDIR}/AL) - export(TARGETS OpenAL - NAMESPACE OpenAL:: - FILE OpenALConfig.cmake) - install(EXPORT OpenAL - DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/OpenAL - NAMESPACE OpenAL:: - FILE OpenALConfig.cmake) - install(DIRECTORY include/AL - DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) - install(FILES "${OpenAL_BINARY_DIR}/openal.pc" - DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig") - if(TARGET soft_oal) - install(TARGETS soft_oal - RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}) - endif() - message(STATUS "Installing library and headers") -else() - message(STATUS "NOT installing library and headers") -endif() - -if(ALSOFT_INSTALL_CONFIG) - install(FILES alsoftrc.sample - DESTINATION ${CMAKE_INSTALL_DATADIR}/openal) - message(STATUS "Installing sample configuration") -endif() - -if(ALSOFT_INSTALL_HRTF_DATA) - install(DIRECTORY hrtf - DESTINATION ${CMAKE_INSTALL_DATADIR}/openal) - message(STATUS "Installing HRTF data files") -endif() - -if(ALSOFT_INSTALL_AMBDEC_PRESETS) - install(DIRECTORY presets - DESTINATION ${CMAKE_INSTALL_DATADIR}/openal) - message(STATUS "Installing AmbDec presets") -endif() -message(STATUS "") - -set(UNICODE_FLAG ) -if(MINGW) - set(UNICODE_FLAG ${UNICODE_FLAG} -municode) -endif() -set(EXTRA_INSTALLS ) -if(ALSOFT_UTILS) - add_executable(openal-info utils/openal-info.c) - target_include_directories(openal-info PRIVATE ${OpenAL_SOURCE_DIR}/common) - target_compile_options(openal-info PRIVATE ${C_FLAGS}) - target_link_libraries(openal-info PRIVATE ${LINKER_FLAGS} OpenAL ${UNICODE_FLAG}) - if(ALSOFT_INSTALL_EXAMPLES) - set(EXTRA_INSTALLS ${EXTRA_INSTALLS} openal-info) - endif() - - find_package(MySOFA) - if(MYSOFA_FOUND) - set(SOFA_SUPPORT_SRCS - utils/sofa-support.cpp - utils/sofa-support.h) - add_library(sofa-support STATIC EXCLUDE_FROM_ALL ${SOFA_SUPPORT_SRCS}) - target_compile_definitions(sofa-support PRIVATE ${CPP_DEFS}) - target_include_directories(sofa-support PUBLIC ${OpenAL_SOURCE_DIR}/common) - target_compile_options(sofa-support PRIVATE ${C_FLAGS}) - target_link_libraries(sofa-support PUBLIC common MySOFA::MySOFA PRIVATE ${LINKER_FLAGS}) - - set(MAKEMHR_SRCS - utils/makemhr/loaddef.cpp - utils/makemhr/loaddef.h - utils/makemhr/loadsofa.cpp - utils/makemhr/loadsofa.h - utils/makemhr/makemhr.cpp - utils/makemhr/makemhr.h) - if(NOT HAVE_GETOPT) - set(MAKEMHR_SRCS ${MAKEMHR_SRCS} utils/getopt.c utils/getopt.h) - endif() - add_executable(makemhr ${MAKEMHR_SRCS}) - target_compile_definitions(makemhr PRIVATE ${CPP_DEFS}) - target_include_directories(makemhr - PRIVATE ${OpenAL_BINARY_DIR} ${OpenAL_SOURCE_DIR}/utils) - target_compile_options(makemhr PRIVATE ${C_FLAGS}) - target_link_libraries(makemhr PRIVATE ${LINKER_FLAGS} sofa-support ${UNICODE_FLAG}) - if(ALSOFT_INSTALL_EXAMPLES) - set(EXTRA_INSTALLS ${EXTRA_INSTALLS} makemhr) - endif() - - set(SOFAINFO_SRCS utils/sofa-info.cpp) - add_executable(sofa-info ${SOFAINFO_SRCS}) - target_compile_definitions(sofa-info PRIVATE ${CPP_DEFS}) - target_include_directories(sofa-info PRIVATE ${OpenAL_SOURCE_DIR}/utils) - target_compile_options(sofa-info PRIVATE ${C_FLAGS}) - target_link_libraries(sofa-info PRIVATE ${LINKER_FLAGS} sofa-support ${UNICODE_FLAG}) - endif() - message(STATUS "Building utility programs") - - if(NOT ALSOFT_NO_CONFIG_UTIL) - add_subdirectory(utils/alsoft-config) - endif() - message(STATUS "") -endif() - - -# Add a static library with common functions used by multiple example targets -add_library(ex-common STATIC EXCLUDE_FROM_ALL - examples/common/alhelpers.c - examples/common/alhelpers.h) -target_compile_definitions(ex-common PUBLIC ${CPP_DEFS}) -target_include_directories(ex-common PUBLIC ${OpenAL_SOURCE_DIR}/common) -target_compile_options(ex-common PUBLIC ${C_FLAGS}) -target_link_libraries(ex-common PUBLIC OpenAL PRIVATE ${RT_LIB}) - -if(ALSOFT_EXAMPLES) - add_executable(altonegen examples/altonegen.c) - target_link_libraries(altonegen PRIVATE ${LINKER_FLAGS} ${MATH_LIB} ex-common ${UNICODE_FLAG}) - - add_executable(alrecord examples/alrecord.c) - target_link_libraries(alrecord PRIVATE ${LINKER_FLAGS} ex-common ${UNICODE_FLAG}) - - if(ALSOFT_INSTALL_EXAMPLES) - set(EXTRA_INSTALLS ${EXTRA_INSTALLS} altonegen alrecord) - endif() - - message(STATUS "Building example programs") - - if(SNDFILE_FOUND) - add_executable(alplay examples/alplay.c) - target_link_libraries(alplay PRIVATE ${LINKER_FLAGS} SndFile::SndFile ex-common - ${UNICODE_FLAG}) - - add_executable(alstream examples/alstream.c) - target_link_libraries(alstream PRIVATE ${LINKER_FLAGS} SndFile::SndFile ex-common - ${UNICODE_FLAG}) - - add_executable(alreverb examples/alreverb.c) - target_link_libraries(alreverb PRIVATE ${LINKER_FLAGS} SndFile::SndFile ex-common - ${UNICODE_FLAG}) - - add_executable(almultireverb examples/almultireverb.c) - target_link_libraries(almultireverb - PRIVATE ${LINKER_FLAGS} SndFile::SndFile ex-common ${MATH_LIB} ${UNICODE_FLAG}) - - add_executable(allatency examples/allatency.c) - target_link_libraries(allatency PRIVATE ${LINKER_FLAGS} SndFile::SndFile ex-common - ${UNICODE_FLAG}) - - add_executable(alhrtf examples/alhrtf.c) - target_link_libraries(alhrtf - PRIVATE ${LINKER_FLAGS} SndFile::SndFile ex-common ${MATH_LIB} ${UNICODE_FLAG}) - - add_executable(alstreamcb examples/alstreamcb.cpp) - target_link_libraries(alstreamcb PRIVATE ${LINKER_FLAGS} SndFile::SndFile ex-common - ${UNICODE_FLAG}) - - add_executable(alconvolve examples/alconvolve.c) - target_link_libraries(alconvolve PRIVATE ${LINKER_FLAGS} common SndFile::SndFile ex-common - ${UNICODE_FLAG}) - - if(ALSOFT_INSTALL_EXAMPLES) - set(EXTRA_INSTALLS ${EXTRA_INSTALLS} alplay alstream alreverb almultireverb allatency - alhrtf) - endif() - - message(STATUS "Building SndFile example programs") - endif() - - if(SDL2_FOUND) - add_executable(alloopback examples/alloopback.c) - target_include_directories(alloopback PRIVATE ${SDL2_INCLUDE_DIR}) - target_link_libraries(alloopback - PRIVATE ${LINKER_FLAGS} ${SDL2_LIBRARY} ex-common ${MATH_LIB}) - - if(ALSOFT_INSTALL_EXAMPLES) - set(EXTRA_INSTALLS ${EXTRA_INSTALLS} alloopback) - endif() - - message(STATUS "Building SDL example programs") - - set(FFVER_OK FALSE) - if(FFMPEG_FOUND) - set(FFVER_OK TRUE) - if(AVFORMAT_VERSION VERSION_LESS "57.56.101") - message(STATUS "libavformat is too old! (${AVFORMAT_VERSION}, wanted 57.56.101)") - set(FFVER_OK FALSE) - endif() - if(AVCODEC_VERSION VERSION_LESS "57.64.101") - message(STATUS "libavcodec is too old! (${AVCODEC_VERSION}, wanted 57.64.101)") - set(FFVER_OK FALSE) - endif() - if(AVUTIL_VERSION VERSION_LESS "55.34.101") - message(STATUS "libavutil is too old! (${AVUTIL_VERSION}, wanted 55.34.101)") - set(FFVER_OK FALSE) - endif() - if(SWSCALE_VERSION VERSION_LESS "4.2.100") - message(STATUS "libswscale is too old! (${SWSCALE_VERSION}, wanted 4.2.100)") - set(FFVER_OK FALSE) - endif() - if(SWRESAMPLE_VERSION VERSION_LESS "2.3.100") - message(STATUS "libswresample is too old! (${SWRESAMPLE_VERSION}, wanted 2.3.100)") - set(FFVER_OK FALSE) - endif() - endif() - if(FFVER_OK) - add_executable(alffplay examples/alffplay.cpp) - target_include_directories(alffplay - PRIVATE ${SDL2_INCLUDE_DIR} ${FFMPEG_INCLUDE_DIRS}) - target_link_libraries(alffplay - PRIVATE ${LINKER_FLAGS} ${SDL2_LIBRARY} ${FFMPEG_LIBRARIES} ex-common) - - if(ALSOFT_INSTALL_EXAMPLES) - set(EXTRA_INSTALLS ${EXTRA_INSTALLS} alffplay) - endif() - message(STATUS "Building SDL+FFmpeg example programs") - endif() - endif() - message(STATUS "") -endif() - -if(EXTRA_INSTALLS) - install(TARGETS ${EXTRA_INSTALLS} - RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} - BUNDLE DESTINATION ${CMAKE_INSTALL_BINDIR} - LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} - ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}) -endif() diff --git a/COPYING b/COPYING deleted file mode 100644 index 8d5d0000..00000000 --- a/COPYING +++ /dev/null @@ -1,437 +0,0 @@ - GNU LIBRARY GENERAL PUBLIC LICENSE - Version 2, June 1991 - - Copyright (C) 1991 Free Software Foundation, Inc. - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - -[This is the first released version of the library GPL. It is - numbered 2 because it goes with version 2 of the ordinary GPL.] - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -Licenses are intended to guarantee your freedom to share and change -free software--to make sure the software is free for all its users. - - This license, the Library General Public License, applies to some -specially designated Free Software Foundation software, and to any -other libraries whose authors decide to use it. You can use it for -your libraries, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -this service if you wish), that you receive source code or can get it -if you want it, that you can change the software or use pieces of it -in new free programs; and that you know you can do these things. - - To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if -you distribute copies of the library, or if you modify it. - - For example, if you distribute copies of the library, whether gratis -or for a fee, you must give the recipients all the rights that we gave -you. You must make sure that they, too, receive or can get the source -code. If you link a program with the library, you must provide -complete object files to the recipients so that they can relink them -with the library, after making changes to the library and recompiling -it. And you must show them these terms so they know their rights. - - Our method of protecting your rights has two steps: (1) copyright -the library, and (2) offer you this license which gives you legal -permission to copy, distribute and/or modify the library. - - Also, for each distributor's protection, we want to make certain -that everyone understands that there is no warranty for this free -library. If the library is modified by someone else and passed on, we -want its recipients to know that what they have is not the original -version, so that any problems introduced by others will not reflect on -the original authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that companies distributing free -software will individually obtain patent licenses, thus in effect -transforming the program into proprietary software. To prevent this, -we have made it clear that any patent must be licensed for everyone's -free use or not licensed at all. - - Most GNU software, including some libraries, is covered by the ordinary -GNU General Public License, which was designed for utility programs. This -license, the GNU Library General Public License, applies to certain -designated libraries. This license is quite different from the ordinary -one; be sure to read it in full, and don't assume that anything in it is -the same as in the ordinary license. - - The reason we have a separate public license for some libraries is that -they blur the distinction we usually make between modifying or adding to a -program and simply using it. Linking a program with a library, without -changing the library, is in some sense simply using the library, and is -analogous to running a utility program or application program. However, in -a textual and legal sense, the linked executable is a combined work, a -derivative of the original library, and the ordinary General Public License -treats it as such. - - Because of this blurred distinction, using the ordinary General -Public License for libraries did not effectively promote software -sharing, because most developers did not use the libraries. We -concluded that weaker conditions might promote sharing better. - - However, unrestricted linking of non-free programs would deprive the -users of those programs of all benefit from the free status of the -libraries themselves. This Library General Public License is intended to -permit developers of non-free programs to use free libraries, while -preserving your freedom as a user of such programs to change the free -libraries that are incorporated in them. (We have not seen how to achieve -this as regards changes in header files, but we have achieved it as regards -changes in the actual functions of the Library.) The hope is that this -will lead to faster development of free libraries. - - The precise terms and conditions for copying, distribution and -modification follow. Pay close attention to the difference between a -"work based on the library" and a "work that uses the library". The -former contains code derived from the library, while the latter only -works together with the library. - - Note that it is possible for a library to be covered by the ordinary -General Public License rather than by this special one. - - GNU LIBRARY GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License Agreement applies to any software library which -contains a notice placed by the copyright holder or other authorized -party saying it may be distributed under the terms of this Library -General Public License (also called "this License"). Each licensee is -addressed as "you". - - A "library" means a collection of software functions and/or data -prepared so as to be conveniently linked with application programs -(which use some of those functions and data) to form executables. - - The "Library", below, refers to any such software library or work -which has been distributed under these terms. A "work based on the -Library" means either the Library or any derivative work under -copyright law: that is to say, a work containing the Library or a -portion of it, either verbatim or with modifications and/or translated -straightforwardly into another language. (Hereinafter, translation is -included without limitation in the term "modification".) - - "Source code" for a work means the preferred form of the work for -making modifications to it. For a library, complete source code means -all the source code for all modules it contains, plus any associated -interface definition files, plus the scripts used to control compilation -and installation of the library. - - Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running a program using the Library is not restricted, and output from -such a program is covered only if its contents constitute a work based -on the Library (independent of the use of the Library in a tool for -writing it). Whether that is true depends on what the Library does -and what the program that uses the Library does. - - 1. You may copy and distribute verbatim copies of the Library's -complete source code as you receive it, in any medium, provided that -you conspicuously and appropriately publish on each copy an -appropriate copyright notice and disclaimer of warranty; keep intact -all the notices that refer to this License and to the absence of any -warranty; and distribute a copy of this License along with the -Library. - - You may charge a fee for the physical act of transferring a copy, -and you may at your option offer warranty protection in exchange for a -fee. - - 2. You may modify your copy or copies of the Library or any portion -of it, thus forming a work based on the Library, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) The modified work must itself be a software library. - - b) You must cause the files modified to carry prominent notices - stating that you changed the files and the date of any change. - - c) You must cause the whole of the work to be licensed at no - charge to all third parties under the terms of this License. - - d) If a facility in the modified Library refers to a function or a - table of data to be supplied by an application program that uses - the facility, other than as an argument passed when the facility - is invoked, then you must make a good faith effort to ensure that, - in the event an application does not supply such function or - table, the facility still operates, and performs whatever part of - its purpose remains meaningful. - - (For example, a function in a library to compute square roots has - a purpose that is entirely well-defined independent of the - application. Therefore, Subsection 2d requires that any - application-supplied function or table used by this function must - be optional: if the application does not supply it, the square - root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Library, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Library, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote -it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library -with the Library (or with a work based on the Library) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may opt to apply the terms of the ordinary GNU General Public -License instead of this License to a given copy of the Library. To do -this, you must alter all the notices that refer to this License, so -that they refer to the ordinary GNU General Public License, version 2, -instead of to this License. (If a newer version than version 2 of the -ordinary GNU General Public License has appeared, then you can specify -that version instead if you wish.) Do not make any other change in -these notices. - - Once this change is made in a given copy, it is irreversible for -that copy, so the ordinary GNU General Public License applies to all -subsequent copies and derivative works made from that copy. - - This option is useful when you wish to copy part of the code of -the Library into a program that is not a library. - - 4. You may copy and distribute the Library (or a portion or -derivative of it, under Section 2) in object code or executable form -under the terms of Sections 1 and 2 above provided that you accompany -it with the complete corresponding machine-readable source code, which -must be distributed under the terms of Sections 1 and 2 above on a -medium customarily used for software interchange. - - If distribution of object code is made by offering access to copy -from a designated place, then offering equivalent access to copy the -source code from the same place satisfies the requirement to -distribute the source code, even though third parties are not -compelled to copy the source along with the object code. - - 5. A program that contains no derivative of any portion of the -Library, but is designed to work with the Library by being compiled or -linked with it, is called a "work that uses the Library". Such a -work, in isolation, is not a derivative work of the Library, and -therefore falls outside the scope of this License. - - However, linking a "work that uses the Library" with the Library -creates an executable that is a derivative of the Library (because it -contains portions of the Library), rather than a "work that uses the -library". The executable is therefore covered by this License. -Section 6 states terms for distribution of such executables. - - When a "work that uses the Library" uses material from a header file -that is part of the Library, the object code for the work may be a -derivative work of the Library even though the source code is not. -Whether this is true is especially significant if the work can be -linked without the Library, or if the work is itself a library. The -threshold for this to be true is not precisely defined by law. - - If such an object file uses only numerical parameters, data -structure layouts and accessors, and small macros and small inline -functions (ten lines or less in length), then the use of the object -file is unrestricted, regardless of whether it is legally a derivative -work. (Executables containing this object code plus portions of the -Library will still fall under Section 6.) - - Otherwise, if the work is a derivative of the Library, you may -distribute the object code for the work under the terms of Section 6. -Any executables containing that work also fall under Section 6, -whether or not they are linked directly with the Library itself. - - 6. As an exception to the Sections above, you may also compile or -link a "work that uses the Library" with the Library to produce a -work containing portions of the Library, and distribute that work -under terms of your choice, provided that the terms permit -modification of the work for the customer's own use and reverse -engineering for debugging such modifications. - - You must give prominent notice with each copy of the work that the -Library is used in it and that the Library and its use are covered by -this License. You must supply a copy of this License. If the work -during execution displays copyright notices, you must include the -copyright notice for the Library among them, as well as a reference -directing the user to the copy of this License. Also, you must do one -of these things: - - a) Accompany the work with the complete corresponding - machine-readable source code for the Library including whatever - changes were used in the work (which must be distributed under - Sections 1 and 2 above); and, if the work is an executable linked - with the Library, with the complete machine-readable "work that - uses the Library", as object code and/or source code, so that the - user can modify the Library and then relink to produce a modified - executable containing the modified Library. (It is understood - that the user who changes the contents of definitions files in the - Library will not necessarily be able to recompile the application - to use the modified definitions.) - - b) Accompany the work with a written offer, valid for at - least three years, to give the same user the materials - specified in Subsection 6a, above, for a charge no more - than the cost of performing this distribution. - - c) If distribution of the work is made by offering access to copy - from a designated place, offer equivalent access to copy the above - specified materials from the same place. - - d) Verify that the user has already received a copy of these - materials or that you have already sent this user a copy. - - For an executable, the required form of the "work that uses the -Library" must include any data and utility programs needed for -reproducing the executable from it. However, as a special exception, -the source code distributed need not include anything that is normally -distributed (in either source or binary form) with the major -components (compiler, kernel, and so on) of the operating system on -which the executable runs, unless that component itself accompanies -the executable. - - It may happen that this requirement contradicts the license -restrictions of other proprietary libraries that do not normally -accompany the operating system. Such a contradiction means you cannot -use both them and the Library together in an executable that you -distribute. - - 7. You may place library facilities that are a work based on the -Library side-by-side in a single library together with other library -facilities not covered by this License, and distribute such a combined -library, provided that the separate distribution of the work based on -the Library and of the other library facilities is otherwise -permitted, and provided that you do these two things: - - a) Accompany the combined library with a copy of the same work - based on the Library, uncombined with any other library - facilities. This must be distributed under the terms of the - Sections above. - - b) Give prominent notice with the combined library of the fact - that part of it is a work based on the Library, and explaining - where to find the accompanying uncombined form of the same work. - - 8. You may not copy, modify, sublicense, link with, or distribute -the Library except as expressly provided under this License. Any -attempt otherwise to copy, modify, sublicense, link with, or -distribute the Library is void, and will automatically terminate your -rights under this License. However, parties who have received copies, -or rights, from you under this License will not have their licenses -terminated so long as such parties remain in full compliance. - - 9. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Library or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Library (or any work based on the -Library), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Library or works based on it. - - 10. Each time you redistribute the Library (or any work based on the -Library), the recipient automatically receives a license from the -original licensor to copy, distribute, link with or modify the Library -subject to these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to -this License. - - 11. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Library at all. For example, if a patent -license would not permit royalty-free redistribution of the Library by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under any -particular circumstance, the balance of the section is intended to apply, -and the section as a whole is intended to apply in other circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 12. If the distribution and/or use of the Library is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Library under this License may add -an explicit geographical distribution limitation excluding those countries, -so that distribution is permitted only in or among countries not thus -excluded. In such case, this License incorporates the limitation as if -written in the body of this License. - - 13. The Free Software Foundation may publish revised and/or new -versions of the Library General Public License from time to time. -Such new versions will be similar in spirit to the present version, -but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Library -specifies a version number of this License which applies to it and -"any later version", you have the option of following the terms and -conditions either of that version or of any later version published by -the Free Software Foundation. If the Library does not specify a -license version number, you may choose any version ever published by -the Free Software Foundation. - - 14. If you wish to incorporate parts of the Library into other free -programs whose distribution conditions are incompatible with these, -write to the author to ask for permission. For software which is -copyrighted by the Free Software Foundation, write to the Free -Software Foundation; we sometimes make exceptions for this. Our -decision will be guided by the two goals of preserving the free status -of all derivatives of our free software and of promoting the sharing -and reuse of software generally. - - NO WARRANTY - - 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO -WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR -OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY -KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE -LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME -THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN -WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY -AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU -FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR -CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE -LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING -RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A -FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF -SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH -DAMAGES. - - END OF TERMS AND CONDITIONS diff --git a/ChangeLog b/ChangeLog deleted file mode 100644 index e5bee5cd..00000000 --- a/ChangeLog +++ /dev/null @@ -1,567 +0,0 @@ -openal-soft-1.21.1: - - Improved alext.h's detection of standard types. - - Improved slightly the local source position when the listener and source - are near each other. - - Fixed compilation for Windows ARM targets with MSVC. - - Fixed ARM NEON detection on Windows. - - Fixed CoreAudio capture when the requested sample rate doesn't match the - system configuration. - - Fixed OpenSL capture desyncing from the internal capture buffer. - - Fixed sources missing a batch update when applied after quickly restarting - the source. - - Fixed missing source stop events when stopping a paused source. - -openal-soft-1.21.0: - - Updated library codebase to C++14. - - Implemented the AL_SOFT_effect_target extension. - - Implemented the AL_SOFT_events extension. - - Implemented the ALC_SOFT_loopback_bformat extension. - - Improved memory use for mixing voices. - - Improved detection of NEON capabilities. - - Improved handling of PulseAudio devices that lack manual start control. - - Improved mixing performance with PulseAudio. - - Improved high-frequency scaling quality for the HRTF B-Format decoder. - - Improved makemhr's HRIR delay calculation. - - Improved WASAPI capture of mono formats with multichannel input. - - Reimplemented the modulation stage for reverb. - - Enabled real-time mixing priority by default, for backends that use the - setting. It can still be disabled in the config file. - - Enabled dual-band processing for the built-in quad and 7.1 output decoders. - - Fixed a potential crash when deleting an effect slot immediately after the - last source using it stops. - - Fixed building with the static runtime on MSVC. - - Fixed using source stereo angles outside of -pi...+pi. - - Fixed the buffer processed event count for sources that start with empty - buffers. - - Fixed trying to open an unopenable WASAPI device causing all devices to - stop working. - - Fixed stale devices when re-enumerating WASAPI devices. - - Fixed using unicode paths with the log file on Windows. - - Fixed DirectSound capture reporting bad sample counts or erroring when - reading samples. - - Added an in-progress extension for a callback-driven buffer type. - - Added an in-progress extension for higher-order B-Format buffers. - - Added an in-progress extension for convolution reverb. - - Added an experimental Oboe backend for Android playback. This requires the - Oboe sources at build time, so that it's built as a static library included - in libopenal. - - Added an option for auto-connecting JACK ports. - - Added greater-than-stereo support to the SoundIO backend. - - Modified the mixer to be fully asynchronous with the external API, and - should now be real-time safe. Although alcRenderSamplesSOFT is not due to - locking to check the device handle validity. - - Modified the UHJ encoder to use an all-pass FIR filter that's less harmful - to non-filtered signal phase. - - Converted examples from SDL_sound to libsndfile. To avoid issues when - combining SDL2 and SDL_sound. - - Worked around a 32-bit GCC/MinGW bug with TLS destructors. See: - https://gcc.gnu.org/bugzilla/show_bug.cgi?id=83562 - - Reduced the maximum number of source sends from 16 to 6. - - Removed the QSA backend. It's been broken for who knows how long. - - Got rid of the compile-time native-tools targets, using cmake and global - initialization instead. This should make cross-compiling less troublesome. - -openal-soft-1.20.1: - - Implemented the AL_SOFT_direct_channels_remix extension. This extends - AL_DIRECT_CHANNELS_SOFT to optionally remix input channels that don't have - a matching output channel. - - Implemented the AL_SOFT_bformat_ex extension. This extends B-Format buffer - support for N3D or SN3D scaling, or ACN channel ordering. - - Fixed a potential voice leak when a source is started and stopped or - restarted in quick succession. - - Fixed a potential device reset failure with JACK. - - Improved handling of unsupported channel configurations with WASAPI. Such - setups will now try to output at least a stereo mix. - - Improved clarity a bit for the HRTF second-order ambisonic decoder. - - Improved detection of compatible layouts for SOFA files in makemhr and - sofa-info. - - Added the ability to resample HRTFs on load. MHR files no longer need to - match the device sample rate to be usable. - - Added an option to limit the HRTF's filter length. - -openal-soft-1.20.0: - - Converted the library codebase to C++11. A lot of hacks and custom - structures have been replaced with standard or cleaner implementations. - - Partially implemented the Vocal Morpher effect. - - Fixed the bsinc SSE resamplers on non-GCC compilers. - - Fixed OpenSL capture. - - Fixed support for extended capture formats with OpenSL. - - Fixed handling of WASAPI not reporting a default device. - - Fixed performance problems relating to semaphores on macOS. - - Modified the bsinc12 resampler's transition band to better avoid aliasing - noise. - - Modified alcResetDeviceSOFT to attempt recovery of disconnected devices. - - Modified the virtual speaker layout for HRTF B-Format decoding. - - Modified the PulseAudio backend to use a custom processing loop. - - Renamed the makehrtf utility to makemhr. - - Improved the efficiency of the bsinc resamplers when up-sampling. - - Improved the quality of the bsinc resamplers slightly. - - Improved the efficiency of the HRTF filters. - - Improved the HRTF B-Format decoder coefficient generation. - - Improved reverb feedback fading to be more consistent with pan fading. - - Improved handling of sources that end prematurely, avoiding loud clicks. - - Improved the performance of some reverb processing loops. - - Added fast_bsinc12 and 24 resamplers that improve efficiency at the cost of - some quality. Notably, down-sampling has less smooth pitch ramping. - - Added support for SOFA input files with makemhr. - - Added a build option to use pre-built native tools. For cross-compiling, - use with caution and ensure the native tools' binaries are kept up-to-date. - - Added an adjust-latency config option for the PulseAudio backend. - - Added basic support for multi-field HRTFs. - - Added an option for mixing first- or second-order B-Format with HRTF - output. This can improve HRTF performance given a number of sources. - - Added an RC file for proper DLL version information. - - Disabled some old KDE workarounds by default. Specifically, PulseAudio - streams can now be moved (KDE may try to move them after opening). - -openal-soft-1.19.1: - - Implemented capture support for the SoundIO backend. - - Fixed source buffer queues potentially not playing properly when a queue - entry completes. - - Fixed possible unexpected failures when generating auxiliary effect slots. - - Fixed a crash with certain reverb or device settings. - - Fixed OpenSL capture. - - Improved output limiter response, better ensuring the sample amplitude is - clamped for output. - -openal-soft-1.19.0: - - Implemented the ALC_SOFT_device_clock extension. - - Implemented the Pitch Shifter, Frequency Shifter, and Autowah effects. - - Fixed compiling on FreeBSD systems that use freebsd-lib 9.1. - - Fixed compiling on NetBSD. - - Fixed the reverb effect's density scale and panning parameters. - - Fixed use of the WASAPI backend with certain games, which caused odd COM - initialization errors. - - Increased the number of virtual channels for decoding Ambisonics to HRTF - output. - - Changed 32-bit x86 builds to use SSE2 math by default for performance. - Build-time options are available to use just SSE1 or x87 instead. - - Replaced the 4-point Sinc resampler with a more efficient cubic resampler. - - Renamed the MMDevAPI backend to WASAPI. - - Added support for 24-bit, dual-ear HRTF data sets. The built-in data set - has been updated to 24-bit. - - Added a 24- to 48-point band-limited Sinc resampler. - - Added an SDL2 playback backend. Disabled by default to avoid a dependency - on SDL2. - - Improved the performance and quality of the Chorus and Flanger effects. - - Improved the efficiency of the band-limited Sinc resampler. - - Improved the Sinc resampler's transition band to avoid over-attenuating - higher frequencies. - - Improved the performance of some filter operations. - - Improved the efficiency of object ID lookups. - - Improved the efficienty of internal voice/source synchronization. - - Improved AL call error logging with contextualized messages. - - Removed the reverb effect's modulation stage. Due to the lack of reference - for its intended behavior and strength. - -openal-soft-1.18.2: - - Fixed resetting the FPU rounding mode after certain function calls on - Windows. - - Fixed use of SSE intrinsics when building with Clang on Windows. - - Fixed a crash with the JACK backend when using JACK1. - - Fixed use of pthread_setnane_np on NetBSD. - - Fixed building on FreeBSD with an older freebsd-lib. - - OSS now links with libossaudio if found at build time (for NetBSD). - -openal-soft-1.18.1: - - Fixed an issue where resuming a source might not restart playing it. - - Fixed PulseAudio playback when the configured stream length is much less - than the requested length. - - Fixed MMDevAPI capture with sample rates not matching the backing device. - - Fixed int32 output for the Wave Writer. - - Fixed enumeration of OSS devices that are missing device files. - - Added correct retrieval of the executable's path on FreeBSD. - - Added a config option to specify the dithering depth. - - Added a 5.1 decoder preset that excludes front-center output. - -openal-soft-1.18.0: - - Implemented the AL_EXT_STEREO_ANGLES and AL_EXT_SOURCE_RADIUS extensions. - - Implemented the AL_SOFT_gain_clamp_ex, AL_SOFT_source_resampler, - AL_SOFT_source_spatialize, and ALC_SOFT_output_limiter extensions. - - Implemented 3D processing for some effects. Currently implemented for - Reverb, Compressor, Equalizer, and Ring Modulator. - - Implemented 2-channel UHJ output encoding. This needs to be enabled with a - config option to be used. - - Implemented dual-band processing for high-quality ambisonic decoding. - - Implemented distance-compensation for surround sound output. - - Implemented near-field emulation and compensation with ambisonic rendering. - Currently only applies when using the high-quality ambisonic decoder or - ambisonic output, with appropriate config options. - - Implemented an output limiter to reduce the amount of distortion from - clipping. - - Implemented dithering for 8-bit and 16-bit output. - - Implemented a config option to select a preferred HRTF. - - Implemented a run-time check for NEON extensions using /proc/cpuinfo. - - Implemented experimental capture support for the OpenSL backend. - - Fixed building on compilers with NEON support but don't default to having - NEON enabled. - - Fixed support for JACK on Windows. - - Fixed starting a source while alcSuspendContext is in effect. - - Fixed detection of headsets as headphones, with MMDevAPI. - - Added support for AmbDec config files, for custom ambisonic decoder - configurations. Version 3 files only. - - Added backend-specific options to alsoft-config. - - Added first-, second-, and third-order ambisonic output formats. Currently - only works with backends that don't rely on channel labels, like JACK, - ALSA, and OSS. - - Added a build option to embed the default HRTFs into the lib. - - Added AmbDec presets to enable high-quality ambisonic decoding. - - Added an AmbDec preset for 3D7.1 speaker setups. - - Added documentation regarding Ambisonics, 3D7.1, AmbDec config files, and - the provided ambdec presets. - - Added the ability for MMDevAPI to open devices given a Device ID or GUID - string. - - Added an option to the example apps to open a specific device. - - Increased the maximum auxiliary send limit to 16 (up from 4). Requires - requesting them with the ALC_MAX_AUXILIARY_SENDS context creation - attribute. - - Increased the default auxiliary effect slot count to 64 (up from 4). - - Reduced the default period count to 3 (down from 4). - - Slightly improved automatic naming for enumerated HRTFs. - - Improved B-Format decoding with HRTF output. - - Improved internal property handling for better batching behavior. - - Improved performance of certain filter uses. - - Removed support for the AL_SOFT_buffer_samples and AL_SOFT_buffer_sub_data - extensions. Due to conflicts with AL_EXT_SOURCE_RADIUS. - -openal-soft-1.17.2: - - Implemented device enumeration for OSSv4. - - Fixed building on OSX. - - Fixed building on non-Windows systems without POSIX-2008. - - Fixed Dedicated Dialog and Dedicated LFE effect output. - - Added a build option to override the share install dir. - - Added a build option to static-link libgcc for MinGW. - -openal-soft-1.17.1: - - Fixed building with JACK and without PulseAudio. - - Fixed building on FreeBSD. - - Fixed the ALSA backend's allow-resampler option. - - Fixed handling of inexact ALSA period counts. - - Altered device naming scheme on Windows backends to better match other - drivers. - - Updated the CoreAudio backend to use the AudioComponent API. This clears up - deprecation warnings for OSX 10.11, although requires OSX 10.6 or newer. - -openal-soft-1.17.0: - - Implemented a JACK playback backend. - - Implemented the AL_EXT_BFORMAT and AL_EXT_MULAW_BFORMAT extensions. - - Implemented the ALC_SOFT_HRTF extension. - - Implemented C, SSE3, and SSE4.1 based 4- and 8-point Sinc resamplers. - - Implemented a C and SSE based band-limited Sinc resampler. This does 12- to - 24-point Sinc resampling, and performs anti-aliasing. - - Implemented B-Format output support for the wave file writer. This creates - FuMa-style first-order Ambisonics wave files (AMB format). - - Implemented a stereo-mode config option for treating stereo modes as either - speakers or headphones. - - Implemented per-device configuration options. - - Fixed handling of PulseAudio and MMDevAPI devices that have identical - descriptions. - - Fixed a potential lockup when stopping playback of suspended PulseAudio devices. - - Fixed logging of Unicode characters on Windows. - - Fixed 5.1 surround sound channels. By default it will now use the side - channels for the surround output. A configuration using rear channels is - still available. - - Fixed the QSA backend potentially altering the capture format. - - Fixed detecting MMDevAPI's default device. - - Fixed returning the default capture device name. - - Fixed mixing property calculations when deferring context updates. - - Altered the behavior of alcSuspendContext and alcProcessContext to better - match certain Windows drivers. - - Altered the panning algorithm, utilizing Ambisonics for better side and - back positioning cues with surround sound output. - - Improved support for certain older Windows apps. - - Improved the alffplay example to support surround sound streams. - - Improved support for building as a sub-project. - - Added an HRTF playback example. - - Added a tone generator output test. - - Added a toolchain to help with cross-compiling to Android. - -openal-soft-1.16.0: - - Implemented EFX Chorus, Flanger, Distortion, Equalizer, and Compressor - effects. - - Implemented high-pass and band-pass EFX filters. - - Implemented the high-pass filter for the EAXReverb effect. - - Implemented SSE2 and SSE4.1 linear resamplers. - - Implemented Neon-enhanced non-HRTF mixers. - - Implemented a QSA backend, for QNX. - - Implemented the ALC_SOFT_pause_device, AL_SOFT_deferred_updates, - AL_SOFT_block_alignment, AL_SOFT_MSADPCM, and AL_SOFT_source_length - extensions. - - Fixed resetting mmdevapi backend devices. - - Fixed clamping when converting 32-bit float samples to integer. - - Fixed modulation range in the Modulator effect. - - Several fixes for the OpenSL playback backend. - - Fixed device specifier names that have Unicode characters on Windows. - - Added support for filenames and paths with Unicode (UTF-8) characters on - Windows. - - Added support for alsoft.conf config files found in XDG Base Directory - Specification locations (XDG_CONFIG_DIRS and XDG_CONFIG_HOME, or their - defaults) on non-Windows systems. - - Added a GUI configuration utility (requires Qt 4.8). - - Added support for environment variable expansion in config options (not - keys or section names). - - Added an example that uses SDL2 and ffmpeg. - - Modified examples to use SDL_sound. - - Modified CMake config option names for better sorting. - - HRTF data sets specified in the hrtf_tables config option may now be - relative or absolute filenames. - - Made the default HRTF data set an external file, and added a data set for - 48khz playback in addition to 44.1khz. - - Added support for C11 atomic methods. - - Improved support for some non-GNU build systems. - -openal-soft-1.15.1: - - Fixed a regression with retrieving the source's AL_GAIN property. - -openal-soft-1.15: - - Fixed device enumeration with the OSS backend. - - Reorganized internal mixing logic, so unneeded steps can potentially be - skipped for better performance. - - Removed the lookup table for calculating the mixing pans. The panning is - now calculated directly for better precision. - - Improved the panning of stereo source channels when using stereo output. - - Improved source filter quality on send paths. - - Added a config option to allow PulseAudio to move streams between devices. - - The PulseAudio backend will now attempt to spawn a server by default. - - Added a workaround for a DirectSound bug relating to float32 output. - - Added SSE-based mixers, for HRTF and non-HRTF mixing. - - Added support for the new AL_SOFT_source_latency extension. - - Improved ALSA capture by avoiding an extra buffer when using sizes - supported by the underlying device. - - Improved the makehrtf utility to support new options and input formats. - - Modified the CFLAGS declared in the pkg-config file so the "AL/" portion of - the header includes can optionally be omitted. - - Added a couple example code programs to show how to apply reverb, and - retrieve latency. - - The configuration sample is now installed into the share/openal/ directory - instead of /etc/openal. - - The configuration sample now gets installed by default. diff --git a/README.md b/README.md index 0c9d3027..6badb27c 100644 --- a/README.md +++ b/README.md @@ -1,61 +1,7 @@ -OpenAL soft -=========== +# openal-soft-vita -`master` branch CI status : [![Build Status](https://travis-ci.org/kcat/openal-soft.svg?branch=master)](https://travis-ci.org/kcat/openal-soft) [![Windows Build Status](https://ci.appveyor.com/api/projects/status/github/kcat/openal-soft?branch=master&svg=true)](https://ci.appveyor.com/api/projects/status/github/kcat/openal-soft?branch=master&svg=true) +This repo contains patchsets for vita [openal-soft](https://openal-soft.org/) port. -OpenAL Soft is an LGPL-licensed, cross-platform, software implementation of the OpenAL 3D audio API. It's forked from the open-sourced Windows version available originally from openal.org's SVN repository (now defunct). -OpenAL provides capabilities for playing audio in a virtual 3D environment. Distance attenuation, doppler shift, and directional sound emitters are among the features handled by the API. More advanced effects, including air absorption, occlusion, and environmental reverb, are available through the EFX extension. It also facilitates streaming audio, multi-channel buffers, and audio capture. +Format is openal-soft--vita-.patch -More information is available on the [official website](http://openal-soft.org/) - -Source Install -------------- -To install OpenAL Soft, use your favorite shell to go into the build/ -directory, and run: - -```bash -cmake .. -``` - -Assuming configuration went well, you can then build it, typically using GNU -Make (KDevelop, MSVC, and others are possible depending on your system setup -and CMake configuration). - -Please Note: Double check that the appropriate backends were detected. Often, -complaints of no sound, crashing, and missing devices can be solved by making -sure the correct backends are being used. CMake's output will identify which -backends were enabled. - -For most systems, you will likely want to make sure ALSA, OSS, and PulseAudio -were detected (if your target system uses them). For Windows, make sure -DirectSound was detected. - - -Utilities ---------- -The source package comes with an informational utility, openal-info, and is -built by default. It prints out information provided by the ALC and AL sub- -systems, including discovered devices, version information, and extensions. - - -Configuration -------------- - -OpenAL Soft can be configured on a per-user and per-system basis. This allows -users and sysadmins to control information provided to applications, as well -as application-agnostic behavior of the library. See alsoftrc.sample for -available settings. - - -Acknowledgements ----------------- - -Special thanks go to: - - - Creative Labs for the original source code this is based off of. - - Christopher Fitzgerald for the current reverb effect implementation, and -helping with the low-pass and HRTF filters. - - Christian Borss for the 3D panning code previous versions used as a base. - - Ben Davis for the idea behind a previous version of the click-removal code. - - Richard Furse for helping with my understanding of Ambisonics that is used by -the various parts of the library. +For full source see vita-* branches diff --git a/XCompile-Android.txt b/XCompile-Android.txt deleted file mode 100644 index 7a660d2a..00000000 --- a/XCompile-Android.txt +++ /dev/null @@ -1,11 +0,0 @@ -# Cross-compiling for Android is handled by the NDK's own provided toolchain, -# which as of this writing, should be in -# ${ndk_root}/build/cmake/android.toolchain.cmake -# -# Certain older NDK versions may also need to explicitly pick the libc++ -# runtime. So for example: -# cmake .. -DANDROID_STL=c++_shared \ -# -DCMAKE_TOOLCHAIN_FILE=${ndk_root}/build/cmake/android.toolchain.cmake -# - -MESSAGE(FATAL_ERROR "Use the toolchain provided by the Android NDK") diff --git a/XCompile.txt b/XCompile.txt deleted file mode 100644 index 32706bc1..00000000 --- a/XCompile.txt +++ /dev/null @@ -1,37 +0,0 @@ -# Cross-compiling requires CMake 2.6 or newer. Example: -# cmake .. -DCMAKE_TOOLCHAIN_FILE=../XCompile.txt -DHOST=i686-w64-mingw32 -# Where 'i686-w64-mingw32' is the host prefix for your cross-compiler. If you -# already have a toolchain file setup, you may use that instead of this file. - -# the name of the target operating system -SET(CMAKE_SYSTEM_NAME Windows) - -# which compilers to use for C and C++ -SET(CMAKE_C_COMPILER "${HOST}-gcc") -SET(CMAKE_CXX_COMPILER "${HOST}-g++") -SET(CMAKE_RC_COMPILER "${HOST}-windres") - -# here is the target environment located -SET(CMAKE_FIND_ROOT_PATH "/usr/${HOST}") - -# here is where stuff gets installed to -SET(CMAKE_INSTALL_PREFIX "${CMAKE_FIND_ROOT_PATH}" CACHE STRING "Install path prefix, prepended onto install directories." FORCE) - -# adjust the default behaviour of the FIND_XXX() commands: -# search headers and libraries in the target environment, search -# programs in the host environment -set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) -set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) -set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) - -# set env vars so that pkg-config will look in the appropriate directory for -# .pc files (as there seems to be no way to force using ${HOST}-pkg-config) -set(ENV{PKG_CONFIG_LIBDIR} "${CMAKE_INSTALL_PREFIX}/lib/pkgconfig") -set(ENV{PKG_CONFIG_PATH} "") - -# Qt4 tools -SET(QT_QMAKE_EXECUTABLE ${HOST}-qmake) -SET(QT_MOC_EXECUTABLE ${HOST}-moc) -SET(QT_RCC_EXECUTABLE ${HOST}-rcc) -SET(QT_UIC_EXECUTABLE ${HOST}-uic) -SET(QT_LRELEASE_EXECUTABLE ${HOST}-lrelease) diff --git a/al/auxeffectslot.cpp b/al/auxeffectslot.cpp deleted file mode 100644 index 4af2acf2..00000000 --- a/al/auxeffectslot.cpp +++ /dev/null @@ -1,1017 +0,0 @@ -/** - * OpenAL cross platform audio library - * Copyright (C) 1999-2007 by authors. - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - * Or go to http://www.gnu.org/copyleft/lgpl.html - */ - -#include "config.h" - -#include "auxeffectslot.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -#include "AL/al.h" -#include "AL/alc.h" -#include "AL/efx.h" - -#include "alcmain.h" -#include "alcontext.h" -#include "almalloc.h" -#include "alnumeric.h" -#include "alspan.h" -#include "alu.h" -#include "buffer.h" -#include "core/except.h" -#include "core/fpu_ctrl.h" -#include "core/logging.h" -#include "effect.h" -#include "inprogext.h" -#include "opthelpers.h" - - -namespace { - -struct FactoryItem { - EffectSlotType Type; - EffectStateFactory* (&GetFactory)(void); -}; -constexpr FactoryItem FactoryList[] = { - { EffectSlotType::None, NullStateFactory_getFactory }, - { EffectSlotType::EAXReverb, ReverbStateFactory_getFactory }, - { EffectSlotType::Reverb, StdReverbStateFactory_getFactory }, - { EffectSlotType::Autowah, AutowahStateFactory_getFactory }, - { EffectSlotType::Chorus, ChorusStateFactory_getFactory }, - { EffectSlotType::Compressor, CompressorStateFactory_getFactory }, - { EffectSlotType::Distortion, DistortionStateFactory_getFactory }, - { EffectSlotType::Echo, EchoStateFactory_getFactory }, - { EffectSlotType::Equalizer, EqualizerStateFactory_getFactory }, - { EffectSlotType::Flanger, FlangerStateFactory_getFactory }, - { EffectSlotType::FrequencyShifter, FshifterStateFactory_getFactory }, - { EffectSlotType::RingModulator, ModulatorStateFactory_getFactory }, - { EffectSlotType::PitchShifter, PshifterStateFactory_getFactory }, - { EffectSlotType::VocalMorpher, VmorpherStateFactory_getFactory }, - { EffectSlotType::DedicatedDialog, DedicatedStateFactory_getFactory }, - { EffectSlotType::DedicatedLFE, DedicatedStateFactory_getFactory }, - { EffectSlotType::Convolution, ConvolutionStateFactory_getFactory }, -}; - -EffectStateFactory *getFactoryByType(EffectSlotType type) -{ - auto iter = std::find_if(std::begin(FactoryList), std::end(FactoryList), - [type](const FactoryItem &item) noexcept -> bool - { return item.Type == type; }); - return (iter != std::end(FactoryList)) ? iter->GetFactory() : nullptr; -} - - -inline ALeffectslot *LookupEffectSlot(ALCcontext *context, ALuint id) noexcept -{ - const size_t lidx{(id-1) >> 6}; - const ALuint slidx{(id-1) & 0x3f}; - - if UNLIKELY(lidx >= context->mEffectSlotList.size()) - return nullptr; - EffectSlotSubList &sublist{context->mEffectSlotList[lidx]}; - if UNLIKELY(sublist.FreeMask & (1_u64 << slidx)) - return nullptr; - return sublist.EffectSlots + slidx; -} - -inline ALeffect *LookupEffect(ALCdevice *device, ALuint id) noexcept -{ - const size_t lidx{(id-1) >> 6}; - const ALuint slidx{(id-1) & 0x3f}; - - if UNLIKELY(lidx >= device->EffectList.size()) - return nullptr; - EffectSubList &sublist = device->EffectList[lidx]; - if UNLIKELY(sublist.FreeMask & (1_u64 << slidx)) - return nullptr; - return sublist.Effects + slidx; -} - -inline ALbuffer *LookupBuffer(ALCdevice *device, ALuint id) noexcept -{ - const size_t lidx{(id-1) >> 6}; - const ALuint slidx{(id-1) & 0x3f}; - - if UNLIKELY(lidx >= device->BufferList.size()) - return nullptr; - BufferSubList &sublist = device->BufferList[lidx]; - if UNLIKELY(sublist.FreeMask & (1_u64 << slidx)) - return nullptr; - return sublist.Buffers + slidx; -} - - -void AddActiveEffectSlots(const al::span auxslots, ALCcontext *context) -{ - if(auxslots.empty()) return; - EffectSlotArray *curarray{context->mActiveAuxSlots.load(std::memory_order_acquire)}; - size_t newcount{curarray->size() + auxslots.size()}; - - /* Insert the new effect slots into the head of the array, followed by the - * existing ones. - */ - EffectSlotArray *newarray = EffectSlot::CreatePtrArray(newcount); - auto slotiter = std::transform(auxslots.begin(), auxslots.end(), newarray->begin(), - [](ALeffectslot *auxslot) noexcept { return &auxslot->mSlot; }); - std::copy(curarray->begin(), curarray->end(), slotiter); - - /* Remove any duplicates (first instance of each will be kept). */ - auto last = newarray->end(); - for(auto start=newarray->begin()+1;;) - { - last = std::remove(start, last, *(start-1)); - if(start == last) break; - ++start; - } - newcount = static_cast(std::distance(newarray->begin(), last)); - - /* Reallocate newarray if the new size ended up smaller from duplicate - * removal. - */ - if UNLIKELY(newcount < newarray->size()) - { - curarray = newarray; - newarray = EffectSlot::CreatePtrArray(newcount); - std::copy_n(curarray->begin(), newcount, newarray->begin()); - delete curarray; - curarray = nullptr; - } - std::uninitialized_fill_n(newarray->end(), newcount, nullptr); - - curarray = context->mActiveAuxSlots.exchange(newarray, std::memory_order_acq_rel); - context->mDevice->waitForMix(); - - al::destroy_n(curarray->end(), curarray->size()); - delete curarray; -} - -void RemoveActiveEffectSlots(const al::span auxslots, ALCcontext *context) -{ - if(auxslots.empty()) return; - EffectSlotArray *curarray{context->mActiveAuxSlots.load(std::memory_order_acquire)}; - - /* Don't shrink the allocated array size since we don't know how many (if - * any) of the effect slots to remove are in the array. - */ - EffectSlotArray *newarray = EffectSlot::CreatePtrArray(curarray->size()); - - auto new_end = std::copy(curarray->begin(), curarray->end(), newarray->begin()); - /* Remove elements from newarray that match any ID in slotids. */ - for(const ALeffectslot *auxslot : auxslots) - { - auto slot_match = [auxslot](EffectSlot *slot) noexcept -> bool - { return (slot == &auxslot->mSlot); }; - new_end = std::remove_if(newarray->begin(), new_end, slot_match); - } - - /* Reallocate with the new size. */ - auto newsize = static_cast(std::distance(newarray->begin(), new_end)); - if LIKELY(newsize != newarray->size()) - { - curarray = newarray; - newarray = EffectSlot::CreatePtrArray(newsize); - std::copy_n(curarray->begin(), newsize, newarray->begin()); - - delete curarray; - curarray = nullptr; - } - std::uninitialized_fill_n(newarray->end(), newsize, nullptr); - - curarray = context->mActiveAuxSlots.exchange(newarray, std::memory_order_acq_rel); - context->mDevice->waitForMix(); - - al::destroy_n(curarray->end(), curarray->size()); - delete curarray; -} - - -EffectSlotType EffectSlotTypeFromEnum(ALenum type) -{ - switch(type) - { - case AL_EFFECT_NULL: return EffectSlotType::None; - case AL_EFFECT_REVERB: return EffectSlotType::Reverb; - case AL_EFFECT_CHORUS: return EffectSlotType::Chorus; - case AL_EFFECT_DISTORTION: return EffectSlotType::Distortion; - case AL_EFFECT_ECHO: return EffectSlotType::Echo; - case AL_EFFECT_FLANGER: return EffectSlotType::Flanger; - case AL_EFFECT_FREQUENCY_SHIFTER: return EffectSlotType::FrequencyShifter; - case AL_EFFECT_VOCAL_MORPHER: return EffectSlotType::VocalMorpher; - case AL_EFFECT_PITCH_SHIFTER: return EffectSlotType::PitchShifter; - case AL_EFFECT_RING_MODULATOR: return EffectSlotType::RingModulator; - case AL_EFFECT_AUTOWAH: return EffectSlotType::Autowah; - case AL_EFFECT_COMPRESSOR: return EffectSlotType::Compressor; - case AL_EFFECT_EQUALIZER: return EffectSlotType::Equalizer; - case AL_EFFECT_EAXREVERB: return EffectSlotType::EAXReverb; - case AL_EFFECT_DEDICATED_LOW_FREQUENCY_EFFECT: return EffectSlotType::DedicatedLFE; - case AL_EFFECT_DEDICATED_DIALOGUE: return EffectSlotType::DedicatedDialog; - case AL_EFFECT_CONVOLUTION_REVERB_SOFT: return EffectSlotType::Convolution; - } - ERR("Unhandled effect enum: 0x%04x\n", type); - return EffectSlotType::None; -} - -bool EnsureEffectSlots(ALCcontext *context, size_t needed) -{ - size_t count{std::accumulate(context->mEffectSlotList.cbegin(), - context->mEffectSlotList.cend(), size_t{0}, - [](size_t cur, const EffectSlotSubList &sublist) noexcept -> size_t - { return cur + static_cast(PopCount(sublist.FreeMask)); })}; - - while(needed > count) - { - if UNLIKELY(context->mEffectSlotList.size() >= 1<<25) - return false; - - context->mEffectSlotList.emplace_back(); - auto sublist = context->mEffectSlotList.end() - 1; - sublist->FreeMask = ~0_u64; - sublist->EffectSlots = static_cast( - al_calloc(alignof(ALeffectslot), sizeof(ALeffectslot)*64)); - if UNLIKELY(!sublist->EffectSlots) - { - context->mEffectSlotList.pop_back(); - return false; - } - count += 64; - } - return true; -} - -ALeffectslot *AllocEffectSlot(ALCcontext *context) -{ - auto sublist = std::find_if(context->mEffectSlotList.begin(), context->mEffectSlotList.end(), - [](const EffectSlotSubList &entry) noexcept -> bool - { return entry.FreeMask != 0; }); - auto lidx = static_cast(std::distance(context->mEffectSlotList.begin(), sublist)); - auto slidx = static_cast(CountTrailingZeros(sublist->FreeMask)); - - ALeffectslot *slot{::new(sublist->EffectSlots + slidx) ALeffectslot{}}; - aluInitEffectPanning(&slot->mSlot, context); - - /* Add 1 to avoid source ID 0. */ - slot->id = ((lidx<<6) | slidx) + 1; - - context->mNumEffectSlots += 1; - sublist->FreeMask &= ~(1_u64 << slidx); - - return slot; -} - -void FreeEffectSlot(ALCcontext *context, ALeffectslot *slot) -{ - const ALuint id{slot->id - 1}; - const size_t lidx{id >> 6}; - const ALuint slidx{id & 0x3f}; - - al::destroy_at(slot); - - context->mEffectSlotList[lidx].FreeMask |= 1_u64 << slidx; - context->mNumEffectSlots--; -} - - -#define DO_UPDATEPROPS() do { \ - if(!context->mDeferUpdates.load(std::memory_order_acquire) \ - && slot->mState == SlotState::Playing) \ - slot->updateProps(context.get()); \ - else \ - slot->PropsClean.clear(std::memory_order_release); \ -} while(0) - -} // namespace - - -AL_API void AL_APIENTRY alGenAuxiliaryEffectSlots(ALsizei n, ALuint *effectslots) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - if UNLIKELY(n < 0) - context->setError(AL_INVALID_VALUE, "Generating %d effect slots", n); - if UNLIKELY(n <= 0) return; - - std::unique_lock slotlock{context->mEffectSlotLock}; - ALCdevice *device{context->mDevice.get()}; - if(static_cast(n) > device->AuxiliaryEffectSlotMax-context->mNumEffectSlots) - { - context->setError(AL_OUT_OF_MEMORY, "Exceeding %u effect slot limit (%u + %d)", - device->AuxiliaryEffectSlotMax, context->mNumEffectSlots, n); - return; - } - if(!EnsureEffectSlots(context.get(), static_cast(n))) - { - context->setError(AL_OUT_OF_MEMORY, "Failed to allocate %d effectslot%s", n, - (n==1) ? "" : "s"); - return; - } - - if(n == 1) - { - ALeffectslot *slot{AllocEffectSlot(context.get())}; - if(!slot) return; - effectslots[0] = slot->id; - } - else - { - al::vector ids; - ALsizei count{n}; - ids.reserve(static_cast(count)); - do { - ALeffectslot *slot{AllocEffectSlot(context.get())}; - if(!slot) - { - slotlock.unlock(); - alDeleteAuxiliaryEffectSlots(static_cast(ids.size()), ids.data()); - return; - } - ids.emplace_back(slot->id); - } while(--count); - std::copy(ids.cbegin(), ids.cend(), effectslots); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alDeleteAuxiliaryEffectSlots(ALsizei n, const ALuint *effectslots) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - if UNLIKELY(n < 0) - context->setError(AL_INVALID_VALUE, "Deleting %d effect slots", n); - if UNLIKELY(n <= 0) return; - - std::lock_guard _{context->mEffectSlotLock}; - if(n == 1) - { - ALeffectslot *slot{LookupEffectSlot(context.get(), effectslots[0])}; - if UNLIKELY(!slot) - { - context->setError(AL_INVALID_NAME, "Invalid effect slot ID %u", effectslots[0]); - return; - } - if UNLIKELY(ReadRef(slot->ref) != 0) - { - context->setError(AL_INVALID_OPERATION, "Deleting in-use effect slot %u", - effectslots[0]); - return; - } - RemoveActiveEffectSlots({&slot, 1u}, context.get()); - FreeEffectSlot(context.get(), slot); - } - else - { - auto slots = al::vector(static_cast(n)); - for(size_t i{0};i < slots.size();++i) - { - ALeffectslot *slot{LookupEffectSlot(context.get(), effectslots[i])}; - if UNLIKELY(!slot) - { - context->setError(AL_INVALID_NAME, "Invalid effect slot ID %u", effectslots[i]); - return; - } - if UNLIKELY(ReadRef(slot->ref) != 0) - { - context->setError(AL_INVALID_OPERATION, "Deleting in-use effect slot %u", - effectslots[i]); - return; - } - slots[i] = slot; - } - /* Remove any duplicates. */ - auto slots_end = slots.end(); - for(auto start=slots.begin()+1;start != slots_end;++start) - { - slots_end = std::remove(start, slots_end, *(start-1)); - if(start == slots_end) break; - } - slots.erase(slots_end, slots.end()); - - /* All effectslots are valid, remove and delete them */ - RemoveActiveEffectSlots(slots, context.get()); - for(ALeffectslot *slot : slots) - FreeEffectSlot(context.get(), slot); - } -} -END_API_FUNC - -AL_API ALboolean AL_APIENTRY alIsAuxiliaryEffectSlot(ALuint effectslot) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if LIKELY(context) - { - std::lock_guard _{context->mEffectSlotLock}; - if(LookupEffectSlot(context.get(), effectslot) != nullptr) - return AL_TRUE; - } - return AL_FALSE; -} -END_API_FUNC - - -AL_API void AL_APIENTRY alAuxiliaryEffectSlotPlaySOFT(ALuint slotid) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - std::lock_guard _{context->mEffectSlotLock}; - ALeffectslot *slot{LookupEffectSlot(context.get(), slotid)}; - if UNLIKELY(!slot) - { - context->setError(AL_INVALID_NAME, "Invalid effect slot ID %u", slotid); - return; - } - if(slot->mState == SlotState::Playing) - return; - - slot->PropsClean.test_and_set(std::memory_order_acq_rel); - slot->updateProps(context.get()); - - AddActiveEffectSlots({&slot, 1}, context.get()); - slot->mState = SlotState::Playing; -} -END_API_FUNC - -AL_API void AL_APIENTRY alAuxiliaryEffectSlotPlayvSOFT(ALsizei n, const ALuint *slotids) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - if UNLIKELY(n < 0) - context->setError(AL_INVALID_VALUE, "Playing %d effect slots", n); - if UNLIKELY(n <= 0) return; - - auto slots = al::vector(static_cast(n)); - std::lock_guard _{context->mEffectSlotLock}; - for(size_t i{0};i < slots.size();++i) - { - ALeffectslot *slot{LookupEffectSlot(context.get(), slotids[i])}; - if UNLIKELY(!slot) - { - context->setError(AL_INVALID_NAME, "Invalid effect slot ID %u", slotids[i]); - return; - } - - if(slot->mState != SlotState::Playing) - { - slot->PropsClean.test_and_set(std::memory_order_acq_rel); - slot->updateProps(context.get()); - } - slots[i] = slot; - }; - - AddActiveEffectSlots(slots, context.get()); - for(auto slot : slots) - slot->mState = SlotState::Playing; -} -END_API_FUNC - -AL_API void AL_APIENTRY alAuxiliaryEffectSlotStopSOFT(ALuint slotid) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - std::lock_guard _{context->mEffectSlotLock}; - ALeffectslot *slot{LookupEffectSlot(context.get(), slotid)}; - if UNLIKELY(!slot) - { - context->setError(AL_INVALID_NAME, "Invalid effect slot ID %u", slotid); - return; - } - - RemoveActiveEffectSlots({&slot, 1}, context.get()); - slot->mState = SlotState::Stopped; -} -END_API_FUNC - -AL_API void AL_APIENTRY alAuxiliaryEffectSlotStopvSOFT(ALsizei n, const ALuint *slotids) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - if UNLIKELY(n < 0) - context->setError(AL_INVALID_VALUE, "Stopping %d effect slots", n); - if UNLIKELY(n <= 0) return; - - auto slots = al::vector(static_cast(n)); - std::lock_guard _{context->mEffectSlotLock}; - for(size_t i{0};i < slots.size();++i) - { - ALeffectslot *slot{LookupEffectSlot(context.get(), slotids[i])}; - if UNLIKELY(!slot) - { - context->setError(AL_INVALID_NAME, "Invalid effect slot ID %u", slotids[i]); - return; - } - - slots[i] = slot; - }; - - RemoveActiveEffectSlots(slots, context.get()); - for(auto slot : slots) - slot->mState = SlotState::Stopped; -} -END_API_FUNC - - -AL_API void AL_APIENTRY alAuxiliaryEffectSloti(ALuint effectslot, ALenum param, ALint value) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - std::lock_guard _{context->mPropLock}; - std::lock_guard __{context->mEffectSlotLock}; - ALeffectslot *slot = LookupEffectSlot(context.get(), effectslot); - if UNLIKELY(!slot) - SETERR_RETURN(context, AL_INVALID_NAME,, "Invalid effect slot ID %u", effectslot); - - ALeffectslot *target{}; - ALCdevice *device{}; - ALenum err{}; - switch(param) - { - case AL_EFFECTSLOT_EFFECT: - device = context->mDevice.get(); - - { - std::lock_guard ___{device->EffectLock}; - ALeffect *effect{value ? LookupEffect(device, static_cast(value)) : nullptr}; - if(!(value == 0 || effect != nullptr)) - SETERR_RETURN(context, AL_INVALID_VALUE,, "Invalid effect ID %u", value); - err = slot->initEffect(effect, context.get()); - } - if UNLIKELY(err != AL_NO_ERROR) - { - context->setError(err, "Effect initialization failed"); - return; - } - if UNLIKELY(slot->mState == SlotState::Initial) - { - AddActiveEffectSlots({&slot, 1}, context.get()); - slot->mState = SlotState::Playing; - } - break; - - case AL_EFFECTSLOT_AUXILIARY_SEND_AUTO: - if(!(value == AL_TRUE || value == AL_FALSE)) - SETERR_RETURN(context, AL_INVALID_VALUE,, - "Effect slot auxiliary send auto out of range"); - slot->AuxSendAuto = !!value; - break; - - case AL_EFFECTSLOT_TARGET_SOFT: - target = LookupEffectSlot(context.get(), static_cast(value)); - if(value && !target) - SETERR_RETURN(context, AL_INVALID_VALUE,, "Invalid effect slot target ID"); - if(target) - { - ALeffectslot *checker{target}; - while(checker && checker != slot) - checker = checker->Target; - if(checker) - SETERR_RETURN(context, AL_INVALID_OPERATION,, - "Setting target of effect slot ID %u to %u creates circular chain", slot->id, - target->id); - } - - if(ALeffectslot *oldtarget{slot->Target}) - { - /* We must force an update if there was an existing effect slot - * target, in case it's about to be deleted. - */ - if(target) IncrementRef(target->ref); - DecrementRef(oldtarget->ref); - slot->Target = target; - slot->updateProps(context.get()); - return; - } - - if(target) IncrementRef(target->ref); - slot->Target = target; - break; - - case AL_BUFFER: - device = context->mDevice.get(); - - if(slot->mState == SlotState::Playing) - SETERR_RETURN(context, AL_INVALID_OPERATION,, - "Setting buffer on playing effect slot %u", slot->id); - - { - std::lock_guard ___{device->BufferLock}; - ALbuffer *buffer{}; - if(value) - { - buffer = LookupBuffer(device, static_cast(value)); - if(!buffer) SETERR_RETURN(context, AL_INVALID_VALUE,, "Invalid buffer ID"); - if(buffer->mCallback) - SETERR_RETURN(context, AL_INVALID_OPERATION,, - "Callback buffer not valid for effects"); - - IncrementRef(buffer->ref); - } - - if(ALbuffer *oldbuffer{slot->Buffer}) - DecrementRef(oldbuffer->ref); - slot->Buffer = buffer; - - FPUCtl mixer_mode{}; - auto *state = slot->Effect.State.get(); - state->deviceUpdate(device, buffer); - } - break; - - case AL_EFFECTSLOT_STATE_SOFT: - SETERR_RETURN(context, AL_INVALID_OPERATION,, "AL_EFFECTSLOT_STATE_SOFT is read-only"); - - default: - SETERR_RETURN(context, AL_INVALID_ENUM,, "Invalid effect slot integer property 0x%04x", - param); - } - DO_UPDATEPROPS(); -} -END_API_FUNC - -AL_API void AL_APIENTRY alAuxiliaryEffectSlotiv(ALuint effectslot, ALenum param, const ALint *values) -START_API_FUNC -{ - switch(param) - { - case AL_EFFECTSLOT_EFFECT: - case AL_EFFECTSLOT_AUXILIARY_SEND_AUTO: - case AL_EFFECTSLOT_TARGET_SOFT: - case AL_EFFECTSLOT_STATE_SOFT: - case AL_BUFFER: - alAuxiliaryEffectSloti(effectslot, param, values[0]); - return; - } - - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - std::lock_guard _{context->mEffectSlotLock}; - ALeffectslot *slot = LookupEffectSlot(context.get(), effectslot); - if UNLIKELY(!slot) - SETERR_RETURN(context, AL_INVALID_NAME,, "Invalid effect slot ID %u", effectslot); - - switch(param) - { - default: - SETERR_RETURN(context, AL_INVALID_ENUM,, - "Invalid effect slot integer-vector property 0x%04x", param); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alAuxiliaryEffectSlotf(ALuint effectslot, ALenum param, ALfloat value) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - std::lock_guard _{context->mPropLock}; - std::lock_guard __{context->mEffectSlotLock}; - ALeffectslot *slot = LookupEffectSlot(context.get(), effectslot); - if UNLIKELY(!slot) - SETERR_RETURN(context, AL_INVALID_NAME,, "Invalid effect slot ID %u", effectslot); - - switch(param) - { - case AL_EFFECTSLOT_GAIN: - if(!(value >= 0.0f && value <= 1.0f)) - SETERR_RETURN(context, AL_INVALID_VALUE,, "Effect slot gain out of range"); - slot->Gain = value; - break; - - default: - SETERR_RETURN(context, AL_INVALID_ENUM,, "Invalid effect slot float property 0x%04x", - param); - } - DO_UPDATEPROPS(); -} -END_API_FUNC - -AL_API void AL_APIENTRY alAuxiliaryEffectSlotfv(ALuint effectslot, ALenum param, const ALfloat *values) -START_API_FUNC -{ - switch(param) - { - case AL_EFFECTSLOT_GAIN: - alAuxiliaryEffectSlotf(effectslot, param, values[0]); - return; - } - - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - std::lock_guard _{context->mEffectSlotLock}; - ALeffectslot *slot = LookupEffectSlot(context.get(), effectslot); - if UNLIKELY(!slot) - SETERR_RETURN(context, AL_INVALID_NAME,, "Invalid effect slot ID %u", effectslot); - - switch(param) - { - default: - SETERR_RETURN(context, AL_INVALID_ENUM,, - "Invalid effect slot float-vector property 0x%04x", param); - } -} -END_API_FUNC - - -AL_API void AL_APIENTRY alGetAuxiliaryEffectSloti(ALuint effectslot, ALenum param, ALint *value) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - std::lock_guard _{context->mEffectSlotLock}; - ALeffectslot *slot = LookupEffectSlot(context.get(), effectslot); - if UNLIKELY(!slot) - SETERR_RETURN(context, AL_INVALID_NAME,, "Invalid effect slot ID %u", effectslot); - - switch(param) - { - case AL_EFFECTSLOT_AUXILIARY_SEND_AUTO: - *value = slot->AuxSendAuto ? AL_TRUE : AL_FALSE; - break; - - case AL_EFFECTSLOT_TARGET_SOFT: - if(auto *target = slot->Target) - *value = static_cast(target->id); - else - *value = 0; - break; - - case AL_EFFECTSLOT_STATE_SOFT: - *value = static_cast(slot->mState); - break; - - case AL_BUFFER: - if(auto *buffer = slot->Buffer) - *value = static_cast(buffer->id); - else - *value = 0; - break; - - default: - context->setError(AL_INVALID_ENUM, "Invalid effect slot integer property 0x%04x", param); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alGetAuxiliaryEffectSlotiv(ALuint effectslot, ALenum param, ALint *values) -START_API_FUNC -{ - switch(param) - { - case AL_EFFECTSLOT_EFFECT: - case AL_EFFECTSLOT_AUXILIARY_SEND_AUTO: - case AL_EFFECTSLOT_TARGET_SOFT: - case AL_EFFECTSLOT_STATE_SOFT: - case AL_BUFFER: - alGetAuxiliaryEffectSloti(effectslot, param, values); - return; - } - - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - std::lock_guard _{context->mEffectSlotLock}; - ALeffectslot *slot = LookupEffectSlot(context.get(), effectslot); - if UNLIKELY(!slot) - SETERR_RETURN(context, AL_INVALID_NAME,, "Invalid effect slot ID %u", effectslot); - - switch(param) - { - default: - context->setError(AL_INVALID_ENUM, "Invalid effect slot integer-vector property 0x%04x", - param); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alGetAuxiliaryEffectSlotf(ALuint effectslot, ALenum param, ALfloat *value) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - std::lock_guard _{context->mEffectSlotLock}; - ALeffectslot *slot = LookupEffectSlot(context.get(), effectslot); - if UNLIKELY(!slot) - SETERR_RETURN(context, AL_INVALID_NAME,, "Invalid effect slot ID %u", effectslot); - - switch(param) - { - case AL_EFFECTSLOT_GAIN: - *value = slot->Gain; - break; - - default: - context->setError(AL_INVALID_ENUM, "Invalid effect slot float property 0x%04x", param); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alGetAuxiliaryEffectSlotfv(ALuint effectslot, ALenum param, ALfloat *values) -START_API_FUNC -{ - switch(param) - { - case AL_EFFECTSLOT_GAIN: - alGetAuxiliaryEffectSlotf(effectslot, param, values); - return; - } - - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - std::lock_guard _{context->mEffectSlotLock}; - ALeffectslot *slot = LookupEffectSlot(context.get(), effectslot); - if UNLIKELY(!slot) - SETERR_RETURN(context, AL_INVALID_NAME,, "Invalid effect slot ID %u", effectslot); - - switch(param) - { - default: - context->setError(AL_INVALID_ENUM, "Invalid effect slot float-vector property 0x%04x", - param); - } -} -END_API_FUNC - - -ALeffectslot::ALeffectslot() -{ - PropsClean.test_and_set(std::memory_order_relaxed); - - EffectStateFactory *factory{getFactoryByType(EffectSlotType::None)}; - assert(factory != nullptr); - - al::intrusive_ptr state{factory->create()}; - Effect.State = state; - mSlot.mEffectState = state.release(); -} - -ALeffectslot::~ALeffectslot() -{ - if(Target) - DecrementRef(Target->ref); - Target = nullptr; - if(Buffer) - DecrementRef(Buffer->ref); - Buffer = nullptr; - - EffectSlotProps *props{mSlot.Update.exchange(nullptr)}; - if(props) - { - TRACE("Freed unapplied AuxiliaryEffectSlot update %p\n", - decltype(std::declval()){props}); - delete props; - } - - if(mSlot.mEffectState) - mSlot.mEffectState->release(); -} - -ALenum ALeffectslot::initEffect(ALeffect *effect, ALCcontext *context) -{ - EffectSlotType newtype{EffectSlotTypeFromEnum(effect ? effect->type : AL_EFFECT_NULL)}; - if(newtype != Effect.Type) - { - EffectStateFactory *factory{getFactoryByType(newtype)}; - if(!factory) - { - ERR("Failed to find factory for effect slot type %d\n", static_cast(newtype)); - return AL_INVALID_ENUM; - } - al::intrusive_ptr state{factory->create()}; - - ALCdevice *device{context->mDevice.get()}; - std::unique_lock statelock{device->StateLock}; - state->mOutTarget = device->Dry.Buffer; - { - FPUCtl mixer_mode{}; - state->deviceUpdate(device, Buffer); - } - - Effect.Type = newtype; - Effect.Props = effect ? effect->Props : EffectProps{}; - - Effect.State = std::move(state); - } - else if(effect) - Effect.Props = effect->Props; - - /* Remove state references from old effect slot property updates. */ - EffectSlotProps *props{context->mFreeEffectslotProps.load()}; - while(props) - { - props->State = nullptr; - props = props->next.load(std::memory_order_relaxed); - } - - return AL_NO_ERROR; -} - -void ALeffectslot::updateProps(ALCcontext *context) -{ - /* Get an unused property container, or allocate a new one as needed. */ - EffectSlotProps *props{context->mFreeEffectslotProps.load(std::memory_order_relaxed)}; - if(!props) - props = new EffectSlotProps{}; - else - { - EffectSlotProps *next; - do { - next = props->next.load(std::memory_order_relaxed); - } while(context->mFreeEffectslotProps.compare_exchange_weak(props, next, - std::memory_order_seq_cst, std::memory_order_acquire) == 0); - } - - /* Copy in current property values. */ - props->Gain = Gain; - props->AuxSendAuto = AuxSendAuto; - props->Target = Target ? &Target->mSlot : nullptr; - - props->Type = Effect.Type; - props->Props = Effect.Props; - props->State = Effect.State; - - /* Set the new container for updating internal parameters. */ - props = mSlot.Update.exchange(props, std::memory_order_acq_rel); - if(props) - { - /* If there was an unused update container, put it back in the - * freelist. - */ - props->State = nullptr; - AtomicReplaceHead(context->mFreeEffectslotProps, props); - } -} - -void UpdateAllEffectSlotProps(ALCcontext *context) -{ - std::lock_guard _{context->mEffectSlotLock}; - for(auto &sublist : context->mEffectSlotList) - { - uint64_t usemask{~sublist.FreeMask}; - while(usemask) - { - const int idx{CountTrailingZeros(usemask)}; - ALeffectslot *slot{sublist.EffectSlots + idx}; - usemask &= ~(1_u64 << idx); - - if(slot->mState != SlotState::Stopped - && slot->PropsClean.test_and_set(std::memory_order_acq_rel)) - slot->updateProps(context); - } - } -} - -EffectSlotSubList::~EffectSlotSubList() -{ - uint64_t usemask{~FreeMask}; - while(usemask) - { - const ALsizei idx{CountTrailingZeros(usemask)}; - al::destroy_at(EffectSlots+idx); - usemask &= ~(1_u64 << idx); - } - FreeMask = ~usemask; - al_free(EffectSlots); - EffectSlots = nullptr; -} diff --git a/al/auxeffectslot.h b/al/auxeffectslot.h deleted file mode 100644 index c1c9703f..00000000 --- a/al/auxeffectslot.h +++ /dev/null @@ -1,68 +0,0 @@ -#ifndef AL_AUXEFFECTSLOT_H -#define AL_AUXEFFECTSLOT_H - -#include -#include - -#include "AL/al.h" -#include "AL/alc.h" -#include "AL/efx.h" - -#include "alcmain.h" -#include "almalloc.h" -#include "atomic.h" -#include "effectslot.h" -#include "effects/base.h" -#include "intrusive_ptr.h" -#include "vector.h" - -struct ALbuffer; -struct ALeffect; -struct WetBuffer; - - -enum class SlotState : ALenum { - Initial = AL_INITIAL, - Playing = AL_PLAYING, - Stopped = AL_STOPPED, -}; - -struct ALeffectslot { - float Gain{1.0f}; - bool AuxSendAuto{true}; - ALeffectslot *Target{nullptr}; - ALbuffer *Buffer{nullptr}; - - struct { - EffectSlotType Type{EffectSlotType::None}; - EffectProps Props{}; - - al::intrusive_ptr State; - } Effect; - - std::atomic_flag PropsClean; - - SlotState mState{SlotState::Initial}; - - RefCount ref{0u}; - - EffectSlot mSlot; - - /* Self ID */ - ALuint id{}; - - ALeffectslot(); - ALeffectslot(const ALeffectslot&) = delete; - ALeffectslot& operator=(const ALeffectslot&) = delete; - ~ALeffectslot(); - - ALenum initEffect(ALeffect *effect, ALCcontext *context); - void updateProps(ALCcontext *context); - - /* This can be new'd for the context's default effect slot. */ - DEF_NEWDEL(ALeffectslot) -}; - -void UpdateAllEffectSlotProps(ALCcontext *context); - -#endif diff --git a/al/buffer.cpp b/al/buffer.cpp deleted file mode 100644 index cdbedf70..00000000 --- a/al/buffer.cpp +++ /dev/null @@ -1,1631 +0,0 @@ -/** - * OpenAL cross platform audio library - * Copyright (C) 1999-2007 by authors. - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - * Or go to http://www.gnu.org/copyleft/lgpl.html - */ - -#include "config.h" - -#include "buffer.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "AL/al.h" -#include "AL/alc.h" -#include "AL/alext.h" - -#include "albyte.h" -#include "alcmain.h" -#include "alcontext.h" -#include "almalloc.h" -#include "alnumeric.h" -#include "aloptional.h" -#include "atomic.h" -#include "core/except.h" -#include "inprogext.h" -#include "opthelpers.h" - - -namespace { - -constexpr int MaxAdpcmChannels{2}; - -/* IMA ADPCM Stepsize table */ -constexpr int IMAStep_size[89] = { - 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, - 21, 23, 25, 28, 31, 34, 37, 41, 45, 50, 55, - 60, 66, 73, 80, 88, 97, 107, 118, 130, 143, 157, - 173, 190, 209, 230, 253, 279, 307, 337, 371, 408, 449, - 494, 544, 598, 658, 724, 796, 876, 963, 1060, 1166, 1282, - 1411, 1552, 1707, 1878, 2066, 2272, 2499, 2749, 3024, 3327, 3660, - 4026, 4428, 4871, 5358, 5894, 6484, 7132, 7845, 8630, 9493,10442, - 11487,12635,13899,15289,16818,18500,20350,22358,24633,27086,29794, - 32767 -}; - -/* IMA4 ADPCM Codeword decode table */ -constexpr int IMA4Codeword[16] = { - 1, 3, 5, 7, 9, 11, 13, 15, - -1,-3,-5,-7,-9,-11,-13,-15, -}; - -/* IMA4 ADPCM Step index adjust decode table */ -constexpr int IMA4Index_adjust[16] = { - -1,-1,-1,-1, 2, 4, 6, 8, - -1,-1,-1,-1, 2, 4, 6, 8 -}; - - -/* MSADPCM Adaption table */ -constexpr int MSADPCMAdaption[16] = { - 230, 230, 230, 230, 307, 409, 512, 614, - 768, 614, 512, 409, 307, 230, 230, 230 -}; - -/* MSADPCM Adaption Coefficient tables */ -constexpr int MSADPCMAdaptionCoeff[7][2] = { - { 256, 0 }, - { 512, -256 }, - { 0, 0 }, - { 192, 64 }, - { 240, 0 }, - { 460, -208 }, - { 392, -232 } -}; - - -void DecodeIMA4Block(int16_t *dst, const al::byte *src, size_t numchans, size_t align) -{ - int sample[MaxAdpcmChannels]{}; - int index[MaxAdpcmChannels]{}; - ALuint code[MaxAdpcmChannels]{}; - - for(size_t c{0};c < numchans;c++) - { - sample[c] = al::to_integer(src[0]) | (al::to_integer(src[1])<<8); - sample[c] = (sample[c]^0x8000) - 32768; - src += 2; - index[c] = al::to_integer(src[0]) | (al::to_integer(src[1])<<8); - index[c] = clampi((index[c]^0x8000) - 32768, 0, 88); - src += 2; - - *(dst++) = static_cast(sample[c]); - } - - for(size_t i{1};i < align;i++) - { - if((i&7) == 1) - { - for(size_t c{0};c < numchans;c++) - { - code[c] = al::to_integer(src[0]) | (al::to_integer(src[1])<< 8) | - (al::to_integer(src[2])<<16) | (al::to_integer(src[3])<<24); - src += 4; - } - } - - for(size_t c{0};c < numchans;c++) - { - const ALuint nibble{code[c]&0xf}; - code[c] >>= 4; - - sample[c] += IMA4Codeword[nibble] * IMAStep_size[index[c]] / 8; - sample[c] = clampi(sample[c], -32768, 32767); - - index[c] += IMA4Index_adjust[nibble]; - index[c] = clampi(index[c], 0, 88); - - *(dst++) = static_cast(sample[c]); - } - } -} - -void DecodeMSADPCMBlock(int16_t *dst, const al::byte *src, size_t numchans, size_t align) -{ - uint8_t blockpred[MaxAdpcmChannels]{}; - int delta[MaxAdpcmChannels]{}; - int16_t samples[MaxAdpcmChannels][2]{}; - - for(size_t c{0};c < numchans;c++) - { - blockpred[c] = std::min(al::to_integer(src[0]), 6); - ++src; - } - for(size_t c{0};c < numchans;c++) - { - delta[c] = al::to_integer(src[0]) | (al::to_integer(src[1])<<8); - delta[c] = (delta[c]^0x8000) - 32768; - src += 2; - } - for(size_t c{0};c < numchans;c++) - { - samples[c][0] = static_cast(al::to_integer(src[0]) | - (al::to_integer(src[1])<<8)); - src += 2; - } - for(size_t c{0};c < numchans;c++) - { - samples[c][1] = static_cast(al::to_integer(src[0]) | - (al::to_integer(src[1])<<8)); - src += 2; - } - - /* Second sample is written first. */ - for(size_t c{0};c < numchans;c++) - *(dst++) = samples[c][1]; - for(size_t c{0};c < numchans;c++) - *(dst++) = samples[c][0]; - - int num{0}; - for(size_t i{2};i < align;i++) - { - for(size_t c{0};c < numchans;c++) - { - /* Read the nibble (first is in the upper bits). */ - al::byte nibble; - if(!(num++ & 1)) - nibble = *src >> 4; - else - nibble = *(src++) & 0x0f; - - int pred{(samples[c][0]*MSADPCMAdaptionCoeff[blockpred[c]][0] + - samples[c][1]*MSADPCMAdaptionCoeff[blockpred[c]][1]) / 256}; - pred += (al::to_integer(nibble^0x08) - 0x08) * delta[c]; - pred = clampi(pred, -32768, 32767); - - samples[c][1] = samples[c][0]; - samples[c][0] = static_cast(pred); - - delta[c] = (MSADPCMAdaption[al::to_integer(nibble)] * delta[c]) / 256; - delta[c] = maxi(16, delta[c]); - - *(dst++) = static_cast(pred); - } - } -} - -void Convert_int16_ima4(int16_t *dst, const al::byte *src, size_t numchans, size_t len, - size_t align) -{ - assert(numchans <= MaxAdpcmChannels); - const size_t byte_align{((align-1)/2 + 4) * numchans}; - - len /= align; - while(len--) - { - DecodeIMA4Block(dst, src, numchans, align); - src += byte_align; - dst += align*numchans; - } -} - -void Convert_int16_msadpcm(int16_t *dst, const al::byte *src, size_t numchans, size_t len, - size_t align) -{ - assert(numchans <= MaxAdpcmChannels); - const size_t byte_align{((align-2)/2 + 7) * numchans}; - - len /= align; - while(len--) - { - DecodeMSADPCMBlock(dst, src, numchans, align); - src += byte_align; - dst += align*numchans; - } -} - - -ALuint BytesFromUserFmt(UserFmtType type) noexcept -{ - switch(type) - { - case UserFmtUByte: return sizeof(uint8_t); - case UserFmtShort: return sizeof(int16_t); - case UserFmtFloat: return sizeof(float); - case UserFmtDouble: return sizeof(double); - case UserFmtMulaw: return sizeof(uint8_t); - case UserFmtAlaw: return sizeof(uint8_t); - case UserFmtIMA4: break; /* not handled here */ - case UserFmtMSADPCM: break; /* not handled here */ - } - return 0; -} -ALuint ChannelsFromUserFmt(UserFmtChannels chans, ALuint ambiorder) noexcept -{ - switch(chans) - { - case UserFmtMono: return 1; - case UserFmtStereo: return 2; - case UserFmtRear: return 2; - case UserFmtQuad: return 4; - case UserFmtX51: return 6; - case UserFmtX61: return 7; - case UserFmtX71: return 8; - case UserFmtBFormat2D: return (ambiorder*2) + 1; - case UserFmtBFormat3D: return (ambiorder+1) * (ambiorder+1); - } - return 0; -} - -al::optional AmbiLayoutFromEnum(ALenum layout) -{ - switch(layout) - { - case AL_FUMA_SOFT: return al::make_optional(AmbiLayout::FuMa); - case AL_ACN_SOFT: return al::make_optional(AmbiLayout::ACN); - } - return al::nullopt; -} -ALenum EnumFromAmbiLayout(AmbiLayout layout) -{ - switch(layout) - { - case AmbiLayout::FuMa: return AL_FUMA_SOFT; - case AmbiLayout::ACN: return AL_ACN_SOFT; - } - throw std::runtime_error{"Invalid AmbiLayout: "+std::to_string(int(layout))}; -} - -al::optional AmbiScalingFromEnum(ALenum scale) -{ - switch(scale) - { - case AL_FUMA_SOFT: return al::make_optional(AmbiScaling::FuMa); - case AL_SN3D_SOFT: return al::make_optional(AmbiScaling::SN3D); - case AL_N3D_SOFT: return al::make_optional(AmbiScaling::N3D); - } - return al::nullopt; -} -ALenum EnumFromAmbiScaling(AmbiScaling scale) -{ - switch(scale) - { - case AmbiScaling::FuMa: return AL_FUMA_SOFT; - case AmbiScaling::SN3D: return AL_SN3D_SOFT; - case AmbiScaling::N3D: return AL_SN3D_SOFT; - } - throw std::runtime_error{"Invalid AmbiScaling: "+std::to_string(int(scale))}; -} - - -constexpr ALbitfieldSOFT INVALID_STORAGE_MASK{~unsigned(AL_MAP_READ_BIT_SOFT | - AL_MAP_WRITE_BIT_SOFT | AL_MAP_PERSISTENT_BIT_SOFT | AL_PRESERVE_DATA_BIT_SOFT)}; -constexpr ALbitfieldSOFT MAP_READ_WRITE_FLAGS{AL_MAP_READ_BIT_SOFT | AL_MAP_WRITE_BIT_SOFT}; -constexpr ALbitfieldSOFT INVALID_MAP_FLAGS{~unsigned(AL_MAP_READ_BIT_SOFT | AL_MAP_WRITE_BIT_SOFT | - AL_MAP_PERSISTENT_BIT_SOFT)}; - - -bool EnsureBuffers(ALCdevice *device, size_t needed) -{ - size_t count{std::accumulate(device->BufferList.cbegin(), device->BufferList.cend(), size_t{0}, - [](size_t cur, const BufferSubList &sublist) noexcept -> size_t - { return cur + static_cast(PopCount(sublist.FreeMask)); })}; - - while(needed > count) - { - if UNLIKELY(device->BufferList.size() >= 1<<25) - return false; - - device->BufferList.emplace_back(); - auto sublist = device->BufferList.end() - 1; - sublist->FreeMask = ~0_u64; - sublist->Buffers = static_cast(al_calloc(alignof(ALbuffer), sizeof(ALbuffer)*64)); - if UNLIKELY(!sublist->Buffers) - { - device->BufferList.pop_back(); - return false; - } - count += 64; - } - return true; -} - -ALbuffer *AllocBuffer(ALCdevice *device) -{ - auto sublist = std::find_if(device->BufferList.begin(), device->BufferList.end(), - [](const BufferSubList &entry) noexcept -> bool - { return entry.FreeMask != 0; } - ); - - auto lidx = static_cast(std::distance(device->BufferList.begin(), sublist)); - auto slidx = static_cast(CountTrailingZeros(sublist->FreeMask)); - - ALbuffer *buffer{::new (sublist->Buffers + slidx) ALbuffer{}}; - - /* Add 1 to avoid buffer ID 0. */ - buffer->id = ((lidx<<6) | slidx) + 1; - - sublist->FreeMask &= ~(1_u64 << slidx); - - return buffer; -} - -void FreeBuffer(ALCdevice *device, ALbuffer *buffer) -{ - const ALuint id{buffer->id - 1}; - const size_t lidx{id >> 6}; - const ALuint slidx{id & 0x3f}; - - al::destroy_at(buffer); - - device->BufferList[lidx].FreeMask |= 1_u64 << slidx; -} - -inline ALbuffer *LookupBuffer(ALCdevice *device, ALuint id) -{ - const size_t lidx{(id-1) >> 6}; - const ALuint slidx{(id-1) & 0x3f}; - - if UNLIKELY(lidx >= device->BufferList.size()) - return nullptr; - BufferSubList &sublist = device->BufferList[lidx]; - if UNLIKELY(sublist.FreeMask & (1_u64 << slidx)) - return nullptr; - return sublist.Buffers + slidx; -} - - -ALuint SanitizeAlignment(UserFmtType type, ALuint align) -{ - if(align == 0) - { - if(type == UserFmtIMA4) - { - /* Here is where things vary: - * nVidia and Apple use 64+1 sample frames per block -> block_size=36 bytes per channel - * Most PC sound software uses 2040+1 sample frames per block -> block_size=1024 bytes per channel - */ - return 65; - } - if(type == UserFmtMSADPCM) - return 64; - return 1; - } - - if(type == UserFmtIMA4) - { - /* IMA4 block alignment must be a multiple of 8, plus 1. */ - if((align&7) == 1) return static_cast(align); - return 0; - } - if(type == UserFmtMSADPCM) - { - /* MSADPCM block alignment must be a multiple of 2. */ - if((align&1) == 0) return static_cast(align); - return 0; - } - - return static_cast(align); -} - - -const ALchar *NameFromUserFmtType(UserFmtType type) -{ - switch(type) - { - case UserFmtUByte: return "UInt8"; - case UserFmtShort: return "Int16"; - case UserFmtFloat: return "Float32"; - case UserFmtDouble: return "Float64"; - case UserFmtMulaw: return "muLaw"; - case UserFmtAlaw: return "aLaw"; - case UserFmtIMA4: return "IMA4 ADPCM"; - case UserFmtMSADPCM: return "MSADPCM"; - } - return ""; -} - -/** Loads the specified data into the buffer, using the specified format. */ -void LoadData(ALCcontext *context, ALbuffer *ALBuf, ALsizei freq, ALuint size, - UserFmtChannels SrcChannels, UserFmtType SrcType, const al::byte *SrcData, - ALbitfieldSOFT access) -{ - if UNLIKELY(ReadRef(ALBuf->ref) != 0 || ALBuf->MappedAccess != 0) - SETERR_RETURN(context, AL_INVALID_OPERATION,, "Modifying storage for in-use buffer %u", - ALBuf->id); - - /* Currently no channel configurations need to be converted. */ - FmtChannels DstChannels{FmtMono}; - switch(SrcChannels) - { - case UserFmtMono: DstChannels = FmtMono; break; - case UserFmtStereo: DstChannels = FmtStereo; break; - case UserFmtRear: DstChannels = FmtRear; break; - case UserFmtQuad: DstChannels = FmtQuad; break; - case UserFmtX51: DstChannels = FmtX51; break; - case UserFmtX61: DstChannels = FmtX61; break; - case UserFmtX71: DstChannels = FmtX71; break; - case UserFmtBFormat2D: DstChannels = FmtBFormat2D; break; - case UserFmtBFormat3D: DstChannels = FmtBFormat3D; break; - } - if UNLIKELY(static_cast(SrcChannels) != static_cast(DstChannels)) - SETERR_RETURN(context, AL_INVALID_ENUM, , "Invalid format"); - - /* IMA4 and MSADPCM convert to 16-bit short. */ - FmtType DstType{FmtUByte}; - switch(SrcType) - { - case UserFmtUByte: DstType = FmtUByte; break; - case UserFmtShort: DstType = FmtShort; break; - case UserFmtFloat: DstType = FmtFloat; break; - case UserFmtDouble: DstType = FmtDouble; break; - case UserFmtAlaw: DstType = FmtAlaw; break; - case UserFmtMulaw: DstType = FmtMulaw; break; - case UserFmtIMA4: DstType = FmtShort; break; - case UserFmtMSADPCM: DstType = FmtShort; break; - } - - /* TODO: Currently we can only map samples when they're not converted. To - * allow it would need some kind of double-buffering to hold onto a copy of - * the original data. - */ - if((access&MAP_READ_WRITE_FLAGS)) - { - if UNLIKELY(static_cast(SrcType) != static_cast(DstType)) - SETERR_RETURN(context, AL_INVALID_VALUE,, "%s samples cannot be mapped", - NameFromUserFmtType(SrcType)); - } - - const ALuint unpackalign{ALBuf->UnpackAlign}; - const ALuint align{SanitizeAlignment(SrcType, unpackalign)}; - if UNLIKELY(align < 1) - SETERR_RETURN(context, AL_INVALID_VALUE,, "Invalid unpack alignment %u for %s samples", - unpackalign, NameFromUserFmtType(SrcType)); - - const ALuint ambiorder{(DstChannels == FmtBFormat2D || DstChannels == FmtBFormat3D) ? - ALBuf->UnpackAmbiOrder : 0}; - - if((access&AL_PRESERVE_DATA_BIT_SOFT)) - { - /* Can only preserve data with the same format and alignment. */ - if UNLIKELY(ALBuf->mChannels != DstChannels || ALBuf->OriginalType != SrcType) - SETERR_RETURN(context, AL_INVALID_VALUE,, "Preserving data of mismatched format"); - if UNLIKELY(ALBuf->OriginalAlign != align) - SETERR_RETURN(context, AL_INVALID_VALUE,, "Preserving data of mismatched alignment"); - if(ALBuf->mAmbiOrder != ambiorder) - SETERR_RETURN(context, AL_INVALID_VALUE,, "Preserving data of mismatched order"); - } - - /* Convert the input/source size in bytes to sample frames using the unpack - * block alignment. - */ - const ALuint SrcByteAlign{ChannelsFromUserFmt(SrcChannels, ambiorder) * - ((SrcType == UserFmtIMA4) ? (align-1)/2 + 4 : - (SrcType == UserFmtMSADPCM) ? (align-2)/2 + 7 : - (align * BytesFromUserFmt(SrcType)))}; - if UNLIKELY((size%SrcByteAlign) != 0) - SETERR_RETURN(context, AL_INVALID_VALUE,, - "Data size %d is not a multiple of frame size %d (%d unpack alignment)", - size, SrcByteAlign, align); - - if UNLIKELY(size/SrcByteAlign > std::numeric_limits::max()/align) - SETERR_RETURN(context, AL_OUT_OF_MEMORY,, - "Buffer size overflow, %d blocks x %d samples per block", size/SrcByteAlign, align); - const ALuint frames{size / SrcByteAlign * align}; - - /* Convert the sample frames to the number of bytes needed for internal - * storage. - */ - ALuint NumChannels{ChannelsFromFmt(DstChannels, ambiorder)}; - ALuint FrameSize{NumChannels * BytesFromFmt(DstType)}; - if UNLIKELY(frames > std::numeric_limits::max()/FrameSize) - SETERR_RETURN(context, AL_OUT_OF_MEMORY,, - "Buffer size overflow, %d frames x %d bytes per frame", frames, FrameSize); - size_t newsize{static_cast(frames) * FrameSize}; - - /* Round up to the next 16-byte multiple. This could reallocate only when - * increasing or the new size is less than half the current, but then the - * buffer's AL_SIZE would not be very reliable for accounting buffer memory - * usage, and reporting the real size could cause problems for apps that - * use AL_SIZE to try to get the buffer's play length. - */ - newsize = RoundUp(newsize, 16); - if(newsize != ALBuf->mData.size()) - { - auto newdata = al::vector(newsize, al::byte{}); - if((access&AL_PRESERVE_DATA_BIT_SOFT)) - { - const size_t tocopy{minz(newdata.size(), ALBuf->mData.size())}; - std::copy_n(ALBuf->mData.begin(), tocopy, newdata.begin()); - } - newdata.swap(ALBuf->mData); - } - - if(SrcType == UserFmtIMA4) - { - assert(DstType == FmtShort); - if(SrcData != nullptr && !ALBuf->mData.empty()) - Convert_int16_ima4(reinterpret_cast(ALBuf->mData.data()), SrcData, - NumChannels, frames, align); - ALBuf->OriginalAlign = align; - } - else if(SrcType == UserFmtMSADPCM) - { - assert(DstType == FmtShort); - if(SrcData != nullptr && !ALBuf->mData.empty()) - Convert_int16_msadpcm(reinterpret_cast(ALBuf->mData.data()), SrcData, - NumChannels, frames, align); - ALBuf->OriginalAlign = align; - } - else - { - assert(static_cast(SrcType) == static_cast(DstType)); - if(SrcData != nullptr && !ALBuf->mData.empty()) - std::copy_n(SrcData, frames*FrameSize, ALBuf->mData.begin()); - ALBuf->OriginalAlign = 1; - } - ALBuf->OriginalSize = size; - ALBuf->OriginalType = SrcType; - - ALBuf->Access = access; - - ALBuf->mSampleRate = static_cast(freq); - ALBuf->mChannels = DstChannels; - ALBuf->mType = DstType; - ALBuf->mAmbiOrder = ambiorder; - - ALBuf->mCallback = nullptr; - ALBuf->mUserData = nullptr; - - ALBuf->mSampleLen = frames; - ALBuf->mLoopStart = 0; - ALBuf->mLoopEnd = ALBuf->mSampleLen; -} - -/** Prepares the buffer to use the specified callback, using the specified format. */ -void PrepareCallback(ALCcontext *context, ALbuffer *ALBuf, ALsizei freq, - UserFmtChannels SrcChannels, UserFmtType SrcType, LPALBUFFERCALLBACKTYPESOFT callback, - void *userptr) -{ - if UNLIKELY(ReadRef(ALBuf->ref) != 0 || ALBuf->MappedAccess != 0) - SETERR_RETURN(context, AL_INVALID_OPERATION,, "Modifying callback for in-use buffer %u", - ALBuf->id); - - /* Currently no channel configurations need to be converted. */ - FmtChannels DstChannels{FmtMono}; - switch(SrcChannels) - { - case UserFmtMono: DstChannels = FmtMono; break; - case UserFmtStereo: DstChannels = FmtStereo; break; - case UserFmtRear: DstChannels = FmtRear; break; - case UserFmtQuad: DstChannels = FmtQuad; break; - case UserFmtX51: DstChannels = FmtX51; break; - case UserFmtX61: DstChannels = FmtX61; break; - case UserFmtX71: DstChannels = FmtX71; break; - case UserFmtBFormat2D: DstChannels = FmtBFormat2D; break; - case UserFmtBFormat3D: DstChannels = FmtBFormat3D; break; - } - if UNLIKELY(static_cast(SrcChannels) != static_cast(DstChannels)) - SETERR_RETURN(context, AL_INVALID_ENUM,, "Invalid format"); - - /* IMA4 and MSADPCM convert to 16-bit short. Not supported with callbacks. */ - FmtType DstType{FmtUByte}; - switch(SrcType) - { - case UserFmtUByte: DstType = FmtUByte; break; - case UserFmtShort: DstType = FmtShort; break; - case UserFmtFloat: DstType = FmtFloat; break; - case UserFmtDouble: DstType = FmtDouble; break; - case UserFmtAlaw: DstType = FmtAlaw; break; - case UserFmtMulaw: DstType = FmtMulaw; break; - case UserFmtIMA4: DstType = FmtShort; break; - case UserFmtMSADPCM: DstType = FmtShort; break; - } - if UNLIKELY(static_cast(SrcType) != static_cast(DstType)) - SETERR_RETURN(context, AL_INVALID_ENUM,, "Unsupported callback format"); - - const ALuint ambiorder{(DstChannels == FmtBFormat2D || DstChannels == FmtBFormat3D) ? - ALBuf->UnpackAmbiOrder : 0}; - - al::vector(FrameSizeFromFmt(DstChannels, DstType, ambiorder) * - size_t{BufferLineSize + (MaxResamplerPadding>>1)}).swap(ALBuf->mData); - - ALBuf->mCallback = callback; - ALBuf->mUserData = userptr; - - ALBuf->OriginalType = SrcType; - ALBuf->OriginalSize = 0; - ALBuf->OriginalAlign = 1; - ALBuf->Access = 0; - - ALBuf->mSampleRate = static_cast(freq); - ALBuf->mChannels = DstChannels; - ALBuf->mType = DstType; - ALBuf->mAmbiOrder = ambiorder; - - ALBuf->mSampleLen = 0; - ALBuf->mLoopStart = 0; - ALBuf->mLoopEnd = ALBuf->mSampleLen; -} - - -struct DecompResult { UserFmtChannels channels; UserFmtType type; }; -al::optional DecomposeUserFormat(ALenum format) -{ - struct FormatMap { - ALenum format; - UserFmtChannels channels; - UserFmtType type; - }; - static const std::array UserFmtList{{ - { AL_FORMAT_MONO8, UserFmtMono, UserFmtUByte }, - { AL_FORMAT_MONO16, UserFmtMono, UserFmtShort }, - { AL_FORMAT_MONO_FLOAT32, UserFmtMono, UserFmtFloat }, - { AL_FORMAT_MONO_DOUBLE_EXT, UserFmtMono, UserFmtDouble }, - { AL_FORMAT_MONO_IMA4, UserFmtMono, UserFmtIMA4 }, - { AL_FORMAT_MONO_MSADPCM_SOFT, UserFmtMono, UserFmtMSADPCM }, - { AL_FORMAT_MONO_MULAW, UserFmtMono, UserFmtMulaw }, - { AL_FORMAT_MONO_ALAW_EXT, UserFmtMono, UserFmtAlaw }, - - { AL_FORMAT_STEREO8, UserFmtStereo, UserFmtUByte }, - { AL_FORMAT_STEREO16, UserFmtStereo, UserFmtShort }, - { AL_FORMAT_STEREO_FLOAT32, UserFmtStereo, UserFmtFloat }, - { AL_FORMAT_STEREO_DOUBLE_EXT, UserFmtStereo, UserFmtDouble }, - { AL_FORMAT_STEREO_IMA4, UserFmtStereo, UserFmtIMA4 }, - { AL_FORMAT_STEREO_MSADPCM_SOFT, UserFmtStereo, UserFmtMSADPCM }, - { AL_FORMAT_STEREO_MULAW, UserFmtStereo, UserFmtMulaw }, - { AL_FORMAT_STEREO_ALAW_EXT, UserFmtStereo, UserFmtAlaw }, - - { AL_FORMAT_REAR8, UserFmtRear, UserFmtUByte }, - { AL_FORMAT_REAR16, UserFmtRear, UserFmtShort }, - { AL_FORMAT_REAR32, UserFmtRear, UserFmtFloat }, - { AL_FORMAT_REAR_MULAW, UserFmtRear, UserFmtMulaw }, - - { AL_FORMAT_QUAD8_LOKI, UserFmtQuad, UserFmtUByte }, - { AL_FORMAT_QUAD16_LOKI, UserFmtQuad, UserFmtShort }, - - { AL_FORMAT_QUAD8, UserFmtQuad, UserFmtUByte }, - { AL_FORMAT_QUAD16, UserFmtQuad, UserFmtShort }, - { AL_FORMAT_QUAD32, UserFmtQuad, UserFmtFloat }, - { AL_FORMAT_QUAD_MULAW, UserFmtQuad, UserFmtMulaw }, - - { AL_FORMAT_51CHN8, UserFmtX51, UserFmtUByte }, - { AL_FORMAT_51CHN16, UserFmtX51, UserFmtShort }, - { AL_FORMAT_51CHN32, UserFmtX51, UserFmtFloat }, - { AL_FORMAT_51CHN_MULAW, UserFmtX51, UserFmtMulaw }, - - { AL_FORMAT_61CHN8, UserFmtX61, UserFmtUByte }, - { AL_FORMAT_61CHN16, UserFmtX61, UserFmtShort }, - { AL_FORMAT_61CHN32, UserFmtX61, UserFmtFloat }, - { AL_FORMAT_61CHN_MULAW, UserFmtX61, UserFmtMulaw }, - - { AL_FORMAT_71CHN8, UserFmtX71, UserFmtUByte }, - { AL_FORMAT_71CHN16, UserFmtX71, UserFmtShort }, - { AL_FORMAT_71CHN32, UserFmtX71, UserFmtFloat }, - { AL_FORMAT_71CHN_MULAW, UserFmtX71, UserFmtMulaw }, - - { AL_FORMAT_BFORMAT2D_8, UserFmtBFormat2D, UserFmtUByte }, - { AL_FORMAT_BFORMAT2D_16, UserFmtBFormat2D, UserFmtShort }, - { AL_FORMAT_BFORMAT2D_FLOAT32, UserFmtBFormat2D, UserFmtFloat }, - { AL_FORMAT_BFORMAT2D_MULAW, UserFmtBFormat2D, UserFmtMulaw }, - - { AL_FORMAT_BFORMAT3D_8, UserFmtBFormat3D, UserFmtUByte }, - { AL_FORMAT_BFORMAT3D_16, UserFmtBFormat3D, UserFmtShort }, - { AL_FORMAT_BFORMAT3D_FLOAT32, UserFmtBFormat3D, UserFmtFloat }, - { AL_FORMAT_BFORMAT3D_MULAW, UserFmtBFormat3D, UserFmtMulaw }, - }}; - - for(const auto &fmt : UserFmtList) - { - if(fmt.format == format) - return al::make_optional({fmt.channels, fmt.type}); - } - return al::nullopt; -} - -} // namespace - - -AL_API void AL_APIENTRY alGenBuffers(ALsizei n, ALuint *buffers) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - if UNLIKELY(n < 0) - context->setError(AL_INVALID_VALUE, "Generating %d buffers", n); - if UNLIKELY(n <= 0) return; - - ALCdevice *device{context->mDevice.get()}; - std::lock_guard _{device->BufferLock}; - if(!EnsureBuffers(device, static_cast(n))) - { - context->setError(AL_OUT_OF_MEMORY, "Failed to allocate %d buffer%s", n, (n==1)?"":"s"); - return; - } - - if LIKELY(n == 1) - { - /* Special handling for the easy and normal case. */ - ALbuffer *buffer{AllocBuffer(device)}; - buffers[0] = buffer->id; - } - else - { - /* Store the allocated buffer IDs in a separate local list, to avoid - * modifying the user storage in case of failure. - */ - al::vector ids; - ids.reserve(static_cast(n)); - do { - ALbuffer *buffer{AllocBuffer(device)}; - ids.emplace_back(buffer->id); - } while(--n); - std::copy(ids.begin(), ids.end(), buffers); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alDeleteBuffers(ALsizei n, const ALuint *buffers) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - if UNLIKELY(n < 0) - context->setError(AL_INVALID_VALUE, "Deleting %d buffers", n); - if UNLIKELY(n <= 0) return; - - ALCdevice *device{context->mDevice.get()}; - std::lock_guard _{device->BufferLock}; - - /* First try to find any buffers that are invalid or in-use. */ - auto validate_buffer = [device, &context](const ALuint bid) -> bool - { - if(!bid) return true; - ALbuffer *ALBuf{LookupBuffer(device, bid)}; - if UNLIKELY(!ALBuf) - { - context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", bid); - return false; - } - if UNLIKELY(ReadRef(ALBuf->ref) != 0) - { - context->setError(AL_INVALID_OPERATION, "Deleting in-use buffer %u", bid); - return false; - } - return true; - }; - const ALuint *buffers_end = buffers + n; - auto invbuf = std::find_if_not(buffers, buffers_end, validate_buffer); - if UNLIKELY(invbuf != buffers_end) return; - - /* All good. Delete non-0 buffer IDs. */ - auto delete_buffer = [device](const ALuint bid) -> void - { - ALbuffer *buffer{bid ? LookupBuffer(device, bid) : nullptr}; - if(buffer) FreeBuffer(device, buffer); - }; - std::for_each(buffers, buffers_end, delete_buffer); -} -END_API_FUNC - -AL_API ALboolean AL_APIENTRY alIsBuffer(ALuint buffer) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if LIKELY(context) - { - ALCdevice *device{context->mDevice.get()}; - std::lock_guard _{device->BufferLock}; - if(!buffer || LookupBuffer(device, buffer)) - return AL_TRUE; - } - return AL_FALSE; -} -END_API_FUNC - - -AL_API void AL_APIENTRY alBufferData(ALuint buffer, ALenum format, const ALvoid *data, ALsizei size, ALsizei freq) -START_API_FUNC -{ alBufferStorageSOFT(buffer, format, data, size, freq, 0); } -END_API_FUNC - -AL_API void AL_APIENTRY alBufferStorageSOFT(ALuint buffer, ALenum format, const ALvoid *data, ALsizei size, ALsizei freq, ALbitfieldSOFT flags) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - ALCdevice *device{context->mDevice.get()}; - std::lock_guard _{device->BufferLock}; - - ALbuffer *albuf = LookupBuffer(device, buffer); - if UNLIKELY(!albuf) - context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer); - else if UNLIKELY(size < 0) - context->setError(AL_INVALID_VALUE, "Negative storage size %d", size); - else if UNLIKELY(freq < 1) - context->setError(AL_INVALID_VALUE, "Invalid sample rate %d", freq); - else if UNLIKELY((flags&INVALID_STORAGE_MASK) != 0) - context->setError(AL_INVALID_VALUE, "Invalid storage flags 0x%x", - flags&INVALID_STORAGE_MASK); - else if UNLIKELY((flags&AL_MAP_PERSISTENT_BIT_SOFT) && !(flags&MAP_READ_WRITE_FLAGS)) - context->setError(AL_INVALID_VALUE, - "Declaring persistently mapped storage without read or write access"); - else - { - auto usrfmt = DecomposeUserFormat(format); - if UNLIKELY(!usrfmt) - context->setError(AL_INVALID_ENUM, "Invalid format 0x%04x", format); - else - LoadData(context.get(), albuf, freq, static_cast(size), usrfmt->channels, - usrfmt->type, static_cast(data), flags); - } -} -END_API_FUNC - -AL_API void* AL_APIENTRY alMapBufferSOFT(ALuint buffer, ALsizei offset, ALsizei length, ALbitfieldSOFT access) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return nullptr; - - ALCdevice *device{context->mDevice.get()}; - std::lock_guard _{device->BufferLock}; - - ALbuffer *albuf = LookupBuffer(device, buffer); - if UNLIKELY(!albuf) - context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer); - else if UNLIKELY((access&INVALID_MAP_FLAGS) != 0) - context->setError(AL_INVALID_VALUE, "Invalid map flags 0x%x", access&INVALID_MAP_FLAGS); - else if UNLIKELY(!(access&MAP_READ_WRITE_FLAGS)) - context->setError(AL_INVALID_VALUE, "Mapping buffer %u without read or write access", - buffer); - else - { - ALbitfieldSOFT unavailable = (albuf->Access^access) & access; - if UNLIKELY(ReadRef(albuf->ref) != 0 && !(access&AL_MAP_PERSISTENT_BIT_SOFT)) - context->setError(AL_INVALID_OPERATION, - "Mapping in-use buffer %u without persistent mapping", buffer); - else if UNLIKELY(albuf->MappedAccess != 0) - context->setError(AL_INVALID_OPERATION, "Mapping already-mapped buffer %u", buffer); - else if UNLIKELY((unavailable&AL_MAP_READ_BIT_SOFT)) - context->setError(AL_INVALID_VALUE, - "Mapping buffer %u for reading without read access", buffer); - else if UNLIKELY((unavailable&AL_MAP_WRITE_BIT_SOFT)) - context->setError(AL_INVALID_VALUE, - "Mapping buffer %u for writing without write access", buffer); - else if UNLIKELY((unavailable&AL_MAP_PERSISTENT_BIT_SOFT)) - context->setError(AL_INVALID_VALUE, - "Mapping buffer %u persistently without persistent access", buffer); - else if UNLIKELY(offset < 0 || length <= 0 - || static_cast(offset) >= albuf->OriginalSize - || static_cast(length) > albuf->OriginalSize - static_cast(offset)) - context->setError(AL_INVALID_VALUE, "Mapping invalid range %d+%d for buffer %u", - offset, length, buffer); - else - { - void *retval{albuf->mData.data() + offset}; - albuf->MappedAccess = access; - albuf->MappedOffset = offset; - albuf->MappedSize = length; - return retval; - } - } - - return nullptr; -} -END_API_FUNC - -AL_API void AL_APIENTRY alUnmapBufferSOFT(ALuint buffer) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - ALCdevice *device{context->mDevice.get()}; - std::lock_guard _{device->BufferLock}; - - ALbuffer *albuf = LookupBuffer(device, buffer); - if UNLIKELY(!albuf) - context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer); - else if UNLIKELY(albuf->MappedAccess == 0) - context->setError(AL_INVALID_OPERATION, "Unmapping unmapped buffer %u", buffer); - else - { - albuf->MappedAccess = 0; - albuf->MappedOffset = 0; - albuf->MappedSize = 0; - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alFlushMappedBufferSOFT(ALuint buffer, ALsizei offset, ALsizei length) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - ALCdevice *device{context->mDevice.get()}; - std::lock_guard _{device->BufferLock}; - - ALbuffer *albuf = LookupBuffer(device, buffer); - if UNLIKELY(!albuf) - context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer); - else if UNLIKELY(!(albuf->MappedAccess&AL_MAP_WRITE_BIT_SOFT)) - context->setError(AL_INVALID_OPERATION, "Flushing buffer %u while not mapped for writing", - buffer); - else if UNLIKELY(offset < albuf->MappedOffset || length <= 0 - || offset >= albuf->MappedOffset+albuf->MappedSize - || length > albuf->MappedOffset+albuf->MappedSize-offset) - context->setError(AL_INVALID_VALUE, "Flushing invalid range %d+%d on buffer %u", offset, - length, buffer); - else - { - /* FIXME: Need to use some method of double-buffering for the mixer and - * app to hold separate memory, which can be safely transfered - * asynchronously. Currently we just say the app shouldn't write where - * OpenAL's reading, and hope for the best... - */ - std::atomic_thread_fence(std::memory_order_seq_cst); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alBufferSubDataSOFT(ALuint buffer, ALenum format, const ALvoid *data, ALsizei offset, ALsizei length) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - ALCdevice *device{context->mDevice.get()}; - std::lock_guard _{device->BufferLock}; - - ALbuffer *albuf = LookupBuffer(device, buffer); - if UNLIKELY(!albuf) - { - context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer); - return; - } - - auto usrfmt = DecomposeUserFormat(format); - if UNLIKELY(!usrfmt) - { - context->setError(AL_INVALID_ENUM, "Invalid format 0x%04x", format); - return; - } - - ALuint unpack_align{albuf->UnpackAlign}; - ALuint align{SanitizeAlignment(usrfmt->type, unpack_align)}; - if UNLIKELY(align < 1) - context->setError(AL_INVALID_VALUE, "Invalid unpack alignment %u", unpack_align); - else if UNLIKELY(long{usrfmt->channels} != long{albuf->mChannels} - || usrfmt->type != albuf->OriginalType) - context->setError(AL_INVALID_ENUM, "Unpacking data with mismatched format"); - else if UNLIKELY(align != albuf->OriginalAlign) - context->setError(AL_INVALID_VALUE, - "Unpacking data with alignment %u does not match original alignment %u", align, - albuf->OriginalAlign); - else if UNLIKELY(albuf->isBFormat() && albuf->UnpackAmbiOrder != albuf->mAmbiOrder) - context->setError(AL_INVALID_VALUE, "Unpacking data with mismatched ambisonic order"); - else if UNLIKELY(albuf->MappedAccess != 0) - context->setError(AL_INVALID_OPERATION, "Unpacking data into mapped buffer %u", buffer); - else - { - ALuint num_chans{albuf->channelsFromFmt()}; - ALuint frame_size{num_chans * albuf->bytesFromFmt()}; - ALuint byte_align{ - (albuf->OriginalType == UserFmtIMA4) ? ((align-1)/2 + 4) * num_chans : - (albuf->OriginalType == UserFmtMSADPCM) ? ((align-2)/2 + 7) * num_chans : - (align * frame_size) - }; - - if UNLIKELY(offset < 0 || length < 0 || static_cast(offset) > albuf->OriginalSize - || static_cast(length) > albuf->OriginalSize-static_cast(offset)) - context->setError(AL_INVALID_VALUE, "Invalid data sub-range %d+%d on buffer %u", - offset, length, buffer); - else if UNLIKELY((static_cast(offset)%byte_align) != 0) - context->setError(AL_INVALID_VALUE, - "Sub-range offset %d is not a multiple of frame size %d (%d unpack alignment)", - offset, byte_align, align); - else if UNLIKELY((static_cast(length)%byte_align) != 0) - context->setError(AL_INVALID_VALUE, - "Sub-range length %d is not a multiple of frame size %d (%d unpack alignment)", - length, byte_align, align); - else - { - /* offset -> byte offset, length -> sample count */ - size_t byteoff{static_cast(offset)/byte_align * align * frame_size}; - size_t samplen{static_cast(length)/byte_align * align}; - - void *dst = albuf->mData.data() + byteoff; - if(usrfmt->type == UserFmtIMA4 && albuf->mType == FmtShort) - Convert_int16_ima4(static_cast(dst), static_cast(data), - num_chans, samplen, align); - else if(usrfmt->type == UserFmtMSADPCM && albuf->mType == FmtShort) - Convert_int16_msadpcm(static_cast(dst), - static_cast(data), num_chans, samplen, align); - else - { - assert(long{usrfmt->type} == long{albuf->mType}); - memcpy(dst, data, size_t{samplen} * frame_size); - } - } - } -} -END_API_FUNC - - -AL_API void AL_APIENTRY alBufferSamplesSOFT(ALuint /*buffer*/, ALuint /*samplerate*/, - ALenum /*internalformat*/, ALsizei /*samples*/, ALenum /*channels*/, ALenum /*type*/, - const ALvoid* /*data*/) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - context->setError(AL_INVALID_OPERATION, "alBufferSamplesSOFT not supported"); -} -END_API_FUNC - -AL_API void AL_APIENTRY alBufferSubSamplesSOFT(ALuint /*buffer*/, ALsizei /*offset*/, - ALsizei /*samples*/, ALenum /*channels*/, ALenum /*type*/, const ALvoid* /*data*/) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - context->setError(AL_INVALID_OPERATION, "alBufferSubSamplesSOFT not supported"); -} -END_API_FUNC - -AL_API void AL_APIENTRY alGetBufferSamplesSOFT(ALuint /*buffer*/, ALsizei /*offset*/, - ALsizei /*samples*/, ALenum /*channels*/, ALenum /*type*/, ALvoid* /*data*/) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - context->setError(AL_INVALID_OPERATION, "alGetBufferSamplesSOFT not supported"); -} -END_API_FUNC - -AL_API ALboolean AL_APIENTRY alIsBufferFormatSupportedSOFT(ALenum /*format*/) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return AL_FALSE; - - context->setError(AL_INVALID_OPERATION, "alIsBufferFormatSupportedSOFT not supported"); - return AL_FALSE; -} -END_API_FUNC - - -AL_API void AL_APIENTRY alBufferf(ALuint buffer, ALenum param, ALfloat /*value*/) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - ALCdevice *device{context->mDevice.get()}; - std::lock_guard _{device->BufferLock}; - - if UNLIKELY(LookupBuffer(device, buffer) == nullptr) - context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer); - else switch(param) - { - default: - context->setError(AL_INVALID_ENUM, "Invalid buffer float property 0x%04x", param); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alBuffer3f(ALuint buffer, ALenum param, - ALfloat /*value1*/, ALfloat /*value2*/, ALfloat /*value3*/) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - ALCdevice *device{context->mDevice.get()}; - std::lock_guard _{device->BufferLock}; - - if UNLIKELY(LookupBuffer(device, buffer) == nullptr) - context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer); - else switch(param) - { - default: - context->setError(AL_INVALID_ENUM, "Invalid buffer 3-float property 0x%04x", param); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alBufferfv(ALuint buffer, ALenum param, const ALfloat *values) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - ALCdevice *device{context->mDevice.get()}; - std::lock_guard _{device->BufferLock}; - - if UNLIKELY(LookupBuffer(device, buffer) == nullptr) - context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer); - else if UNLIKELY(!values) - context->setError(AL_INVALID_VALUE, "NULL pointer"); - else switch(param) - { - default: - context->setError(AL_INVALID_ENUM, "Invalid buffer float-vector property 0x%04x", param); - } -} -END_API_FUNC - - -AL_API void AL_APIENTRY alBufferi(ALuint buffer, ALenum param, ALint value) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - ALCdevice *device{context->mDevice.get()}; - std::lock_guard _{device->BufferLock}; - - ALbuffer *albuf = LookupBuffer(device, buffer); - if UNLIKELY(!albuf) - context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer); - else switch(param) - { - case AL_UNPACK_BLOCK_ALIGNMENT_SOFT: - if UNLIKELY(value < 0) - context->setError(AL_INVALID_VALUE, "Invalid unpack block alignment %d", value); - else - albuf->UnpackAlign = static_cast(value); - break; - - case AL_PACK_BLOCK_ALIGNMENT_SOFT: - if UNLIKELY(value < 0) - context->setError(AL_INVALID_VALUE, "Invalid pack block alignment %d", value); - else - albuf->PackAlign = static_cast(value); - break; - - case AL_AMBISONIC_LAYOUT_SOFT: - if UNLIKELY(ReadRef(albuf->ref) != 0) - context->setError(AL_INVALID_OPERATION, "Modifying in-use buffer %u's ambisonic layout", - buffer); - else if UNLIKELY(value != AL_FUMA_SOFT && value != AL_ACN_SOFT) - context->setError(AL_INVALID_VALUE, "Invalid unpack ambisonic layout %04x", value); - else - albuf->mAmbiLayout = AmbiLayoutFromEnum(value).value(); - break; - - case AL_AMBISONIC_SCALING_SOFT: - if UNLIKELY(ReadRef(albuf->ref) != 0) - context->setError(AL_INVALID_OPERATION, "Modifying in-use buffer %u's ambisonic scaling", - buffer); - else if UNLIKELY(value != AL_FUMA_SOFT && value != AL_SN3D_SOFT && value != AL_N3D_SOFT) - context->setError(AL_INVALID_VALUE, "Invalid unpack ambisonic scaling %04x", value); - else - albuf->mAmbiScaling = AmbiScalingFromEnum(value).value(); - break; - - case AL_UNPACK_AMBISONIC_ORDER_SOFT: - if UNLIKELY(value < 1 || value > 14) - context->setError(AL_INVALID_VALUE, "Invalid unpack ambisonic order %d", value); - else - albuf->UnpackAmbiOrder = static_cast(value); - break; - - default: - context->setError(AL_INVALID_ENUM, "Invalid buffer integer property 0x%04x", param); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alBuffer3i(ALuint buffer, ALenum param, - ALint /*value1*/, ALint /*value2*/, ALint /*value3*/) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - ALCdevice *device{context->mDevice.get()}; - std::lock_guard _{device->BufferLock}; - - if UNLIKELY(LookupBuffer(device, buffer) == nullptr) - context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer); - else switch(param) - { - default: - context->setError(AL_INVALID_ENUM, "Invalid buffer 3-integer property 0x%04x", param); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alBufferiv(ALuint buffer, ALenum param, const ALint *values) -START_API_FUNC -{ - if(values) - { - switch(param) - { - case AL_UNPACK_BLOCK_ALIGNMENT_SOFT: - case AL_PACK_BLOCK_ALIGNMENT_SOFT: - case AL_AMBISONIC_LAYOUT_SOFT: - case AL_AMBISONIC_SCALING_SOFT: - case AL_UNPACK_AMBISONIC_ORDER_SOFT: - alBufferi(buffer, param, values[0]); - return; - } - } - - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - ALCdevice *device{context->mDevice.get()}; - std::lock_guard _{device->BufferLock}; - - ALbuffer *albuf = LookupBuffer(device, buffer); - if UNLIKELY(!albuf) - context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer); - else if UNLIKELY(!values) - context->setError(AL_INVALID_VALUE, "NULL pointer"); - else switch(param) - { - case AL_LOOP_POINTS_SOFT: - if UNLIKELY(ReadRef(albuf->ref) != 0) - context->setError(AL_INVALID_OPERATION, "Modifying in-use buffer %u's loop points", - buffer); - else if UNLIKELY(values[0] < 0 || values[0] >= values[1] - || static_cast(values[1]) > albuf->mSampleLen) - context->setError(AL_INVALID_VALUE, "Invalid loop point range %d -> %d on buffer %u", - values[0], values[1], buffer); - else - { - albuf->mLoopStart = static_cast(values[0]); - albuf->mLoopEnd = static_cast(values[1]); - } - break; - - default: - context->setError(AL_INVALID_ENUM, "Invalid buffer integer-vector property 0x%04x", param); - } -} -END_API_FUNC - - -AL_API void AL_APIENTRY alGetBufferf(ALuint buffer, ALenum param, ALfloat *value) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - ALCdevice *device{context->mDevice.get()}; - std::lock_guard _{device->BufferLock}; - - ALbuffer *albuf = LookupBuffer(device, buffer); - if UNLIKELY(!albuf) - context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer); - else if UNLIKELY(!value) - context->setError(AL_INVALID_VALUE, "NULL pointer"); - else switch(param) - { - default: - context->setError(AL_INVALID_ENUM, "Invalid buffer float property 0x%04x", param); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alGetBuffer3f(ALuint buffer, ALenum param, ALfloat *value1, ALfloat *value2, ALfloat *value3) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - ALCdevice *device{context->mDevice.get()}; - std::lock_guard _{device->BufferLock}; - - if UNLIKELY(LookupBuffer(device, buffer) == nullptr) - context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer); - else if UNLIKELY(!value1 || !value2 || !value3) - context->setError(AL_INVALID_VALUE, "NULL pointer"); - else switch(param) - { - default: - context->setError(AL_INVALID_ENUM, "Invalid buffer 3-float property 0x%04x", param); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alGetBufferfv(ALuint buffer, ALenum param, ALfloat *values) -START_API_FUNC -{ - switch(param) - { - case AL_SEC_LENGTH_SOFT: - alGetBufferf(buffer, param, values); - return; - } - - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - ALCdevice *device{context->mDevice.get()}; - std::lock_guard _{device->BufferLock}; - - if UNLIKELY(LookupBuffer(device, buffer) == nullptr) - context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer); - else if UNLIKELY(!values) - context->setError(AL_INVALID_VALUE, "NULL pointer"); - else switch(param) - { - default: - context->setError(AL_INVALID_ENUM, "Invalid buffer float-vector property 0x%04x", param); - } -} -END_API_FUNC - - -AL_API void AL_APIENTRY alGetBufferi(ALuint buffer, ALenum param, ALint *value) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - ALCdevice *device{context->mDevice.get()}; - std::lock_guard _{device->BufferLock}; - ALbuffer *albuf = LookupBuffer(device, buffer); - if UNLIKELY(!albuf) - context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer); - else if UNLIKELY(!value) - context->setError(AL_INVALID_VALUE, "NULL pointer"); - else switch(param) - { - case AL_FREQUENCY: - *value = static_cast(albuf->mSampleRate); - break; - - case AL_BITS: - *value = static_cast(albuf->bytesFromFmt() * 8); - break; - - case AL_CHANNELS: - *value = static_cast(albuf->channelsFromFmt()); - break; - - case AL_SIZE: - *value = static_cast(albuf->mSampleLen * albuf->frameSizeFromFmt()); - break; - - case AL_UNPACK_BLOCK_ALIGNMENT_SOFT: - *value = static_cast(albuf->UnpackAlign); - break; - - case AL_PACK_BLOCK_ALIGNMENT_SOFT: - *value = static_cast(albuf->PackAlign); - break; - - case AL_AMBISONIC_LAYOUT_SOFT: - *value = EnumFromAmbiLayout(albuf->mAmbiLayout); - break; - - case AL_AMBISONIC_SCALING_SOFT: - *value = EnumFromAmbiScaling(albuf->mAmbiScaling); - break; - - case AL_UNPACK_AMBISONIC_ORDER_SOFT: - *value = static_cast(albuf->UnpackAmbiOrder); - break; - - default: - context->setError(AL_INVALID_ENUM, "Invalid buffer integer property 0x%04x", param); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alGetBuffer3i(ALuint buffer, ALenum param, ALint *value1, ALint *value2, ALint *value3) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - ALCdevice *device{context->mDevice.get()}; - std::lock_guard _{device->BufferLock}; - if UNLIKELY(LookupBuffer(device, buffer) == nullptr) - context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer); - else if UNLIKELY(!value1 || !value2 || !value3) - context->setError(AL_INVALID_VALUE, "NULL pointer"); - else switch(param) - { - default: - context->setError(AL_INVALID_ENUM, "Invalid buffer 3-integer property 0x%04x", param); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alGetBufferiv(ALuint buffer, ALenum param, ALint *values) -START_API_FUNC -{ - switch(param) - { - case AL_FREQUENCY: - case AL_BITS: - case AL_CHANNELS: - case AL_SIZE: - case AL_INTERNAL_FORMAT_SOFT: - case AL_BYTE_LENGTH_SOFT: - case AL_SAMPLE_LENGTH_SOFT: - case AL_UNPACK_BLOCK_ALIGNMENT_SOFT: - case AL_PACK_BLOCK_ALIGNMENT_SOFT: - case AL_AMBISONIC_LAYOUT_SOFT: - case AL_AMBISONIC_SCALING_SOFT: - case AL_UNPACK_AMBISONIC_ORDER_SOFT: - alGetBufferi(buffer, param, values); - return; - } - - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - ALCdevice *device{context->mDevice.get()}; - std::lock_guard _{device->BufferLock}; - ALbuffer *albuf = LookupBuffer(device, buffer); - if UNLIKELY(!albuf) - context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer); - else if UNLIKELY(!values) - context->setError(AL_INVALID_VALUE, "NULL pointer"); - else switch(param) - { - case AL_LOOP_POINTS_SOFT: - values[0] = static_cast(albuf->mLoopStart); - values[1] = static_cast(albuf->mLoopEnd); - break; - - default: - context->setError(AL_INVALID_ENUM, "Invalid buffer integer-vector property 0x%04x", param); - } -} -END_API_FUNC - - -AL_API void AL_APIENTRY alBufferCallbackSOFT(ALuint buffer, ALenum format, ALsizei freq, - LPALBUFFERCALLBACKTYPESOFT callback, ALvoid *userptr, ALbitfieldSOFT flags) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - ALCdevice *device{context->mDevice.get()}; - std::lock_guard _{device->BufferLock}; - - ALbuffer *albuf = LookupBuffer(device, buffer); - if UNLIKELY(!albuf) - context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer); - else if UNLIKELY(freq < 1) - context->setError(AL_INVALID_VALUE, "Invalid sample rate %d", freq); - else if UNLIKELY(callback == nullptr) - context->setError(AL_INVALID_VALUE, "NULL callback"); - else if UNLIKELY(flags != 0) - context->setError(AL_INVALID_VALUE, "Invalid callback flags 0x%x", flags); - else - { - auto usrfmt = DecomposeUserFormat(format); - if UNLIKELY(!usrfmt) - context->setError(AL_INVALID_ENUM, "Invalid format 0x%04x", format); - else - PrepareCallback(context.get(), albuf, freq, usrfmt->channels, usrfmt->type, callback, - userptr); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alGetBufferPtrSOFT(ALuint buffer, ALenum param, ALvoid **value) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - ALCdevice *device{context->mDevice.get()}; - std::lock_guard _{device->BufferLock}; - ALbuffer *albuf = LookupBuffer(device, buffer); - if UNLIKELY(!albuf) - context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer); - else if UNLIKELY(!value) - context->setError(AL_INVALID_VALUE, "NULL pointer"); - else switch(param) - { - case AL_BUFFER_CALLBACK_FUNCTION_SOFT: - *value = reinterpret_cast(albuf->mCallback); - break; - case AL_BUFFER_CALLBACK_USER_PARAM_SOFT: - *value = albuf->mUserData; - break; - - default: - context->setError(AL_INVALID_ENUM, "Invalid buffer pointer property 0x%04x", param); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alGetBuffer3PtrSOFT(ALuint buffer, ALenum param, ALvoid **value1, ALvoid **value2, ALvoid **value3) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - ALCdevice *device{context->mDevice.get()}; - std::lock_guard _{device->BufferLock}; - if UNLIKELY(LookupBuffer(device, buffer) == nullptr) - context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer); - else if UNLIKELY(!value1 || !value2 || !value3) - context->setError(AL_INVALID_VALUE, "NULL pointer"); - else switch(param) - { - default: - context->setError(AL_INVALID_ENUM, "Invalid buffer 3-pointer property 0x%04x", param); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alGetBufferPtrvSOFT(ALuint buffer, ALenum param, ALvoid **values) -START_API_FUNC -{ - switch(param) - { - case AL_BUFFER_CALLBACK_FUNCTION_SOFT: - case AL_BUFFER_CALLBACK_USER_PARAM_SOFT: - alGetBufferPtrSOFT(buffer, param, values); - return; - } - - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - ALCdevice *device{context->mDevice.get()}; - std::lock_guard _{device->BufferLock}; - if UNLIKELY(LookupBuffer(device, buffer) == nullptr) - context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer); - else if UNLIKELY(!values) - context->setError(AL_INVALID_VALUE, "NULL pointer"); - else switch(param) - { - default: - context->setError(AL_INVALID_ENUM, "Invalid buffer pointer-vector property 0x%04x", param); - } -} -END_API_FUNC - - -BufferSubList::~BufferSubList() -{ - uint64_t usemask{~FreeMask}; - while(usemask) - { - const ALsizei idx{CountTrailingZeros(usemask)}; - al::destroy_at(Buffers+idx); - usemask &= ~(1_u64 << idx); - } - FreeMask = ~usemask; - al_free(Buffers); - Buffers = nullptr; -} diff --git a/al/buffer.h b/al/buffer.h deleted file mode 100644 index 02cb49a9..00000000 --- a/al/buffer.h +++ /dev/null @@ -1,65 +0,0 @@ -#ifndef AL_BUFFER_H -#define AL_BUFFER_H - -#include - -#include "AL/al.h" - -#include "albyte.h" -#include "almalloc.h" -#include "atomic.h" -#include "buffer_storage.h" -#include "inprogext.h" -#include "vector.h" - - -/* User formats */ -enum UserFmtType : unsigned char { - UserFmtUByte = FmtUByte, - UserFmtShort = FmtShort, - UserFmtFloat = FmtFloat, - UserFmtMulaw = FmtMulaw, - UserFmtAlaw = FmtAlaw, - UserFmtDouble = FmtDouble, - - UserFmtIMA4 = 128, - UserFmtMSADPCM, -}; -enum UserFmtChannels : unsigned char { - UserFmtMono = FmtMono, - UserFmtStereo = FmtStereo, - UserFmtRear = FmtRear, - UserFmtQuad = FmtQuad, - UserFmtX51 = FmtX51, - UserFmtX61 = FmtX61, - UserFmtX71 = FmtX71, - UserFmtBFormat2D = FmtBFormat2D, - UserFmtBFormat3D = FmtBFormat3D, -}; - - -struct ALbuffer : public BufferStorage { - ALbitfieldSOFT Access{0u}; - - UserFmtType OriginalType{}; - ALuint OriginalSize{0}; - ALuint OriginalAlign{0}; - - ALuint UnpackAlign{0}; - ALuint PackAlign{0}; - ALuint UnpackAmbiOrder{1}; - - ALbitfieldSOFT MappedAccess{0u}; - ALsizei MappedOffset{0}; - ALsizei MappedSize{0}; - - /* Number of times buffer was attached to a source (deletion can only occur when 0) */ - RefCount ref{0u}; - - /* Self ID */ - ALuint id{0}; - - DISABLE_ALLOC() -}; - -#endif diff --git a/al/effect.cpp b/al/effect.cpp deleted file mode 100644 index 02b31fac..00000000 --- a/al/effect.cpp +++ /dev/null @@ -1,745 +0,0 @@ -/** - * OpenAL cross platform audio library - * Copyright (C) 1999-2007 by authors. - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - * Or go to http://www.gnu.org/copyleft/lgpl.html - */ - -#include "config.h" - -#include "effect.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "AL/al.h" -#include "AL/alc.h" -#include "AL/alext.h" -#include "AL/efx-presets.h" -#include "AL/efx.h" - -#include "alcmain.h" -#include "alcontext.h" -#include "almalloc.h" -#include "alnumeric.h" -#include "alstring.h" -#include "core/except.h" -#include "core/logging.h" -#include "effects/base.h" -#include "opthelpers.h" -#include "vector.h" - - -const EffectList gEffectList[16]{ - { "eaxreverb", EAXREVERB_EFFECT, AL_EFFECT_EAXREVERB }, - { "reverb", REVERB_EFFECT, AL_EFFECT_REVERB }, - { "autowah", AUTOWAH_EFFECT, AL_EFFECT_AUTOWAH }, - { "chorus", CHORUS_EFFECT, AL_EFFECT_CHORUS }, - { "compressor", COMPRESSOR_EFFECT, AL_EFFECT_COMPRESSOR }, - { "distortion", DISTORTION_EFFECT, AL_EFFECT_DISTORTION }, - { "echo", ECHO_EFFECT, AL_EFFECT_ECHO }, - { "equalizer", EQUALIZER_EFFECT, AL_EFFECT_EQUALIZER }, - { "flanger", FLANGER_EFFECT, AL_EFFECT_FLANGER }, - { "fshifter", FSHIFTER_EFFECT, AL_EFFECT_FREQUENCY_SHIFTER }, - { "modulator", MODULATOR_EFFECT, AL_EFFECT_RING_MODULATOR }, - { "pshifter", PSHIFTER_EFFECT, AL_EFFECT_PITCH_SHIFTER }, - { "vmorpher", VMORPHER_EFFECT, AL_EFFECT_VOCAL_MORPHER }, - { "dedicated", DEDICATED_EFFECT, AL_EFFECT_DEDICATED_LOW_FREQUENCY_EFFECT }, - { "dedicated", DEDICATED_EFFECT, AL_EFFECT_DEDICATED_DIALOGUE }, - { "convolution", CONVOLUTION_EFFECT, AL_EFFECT_CONVOLUTION_REVERB_SOFT }, -}; - -bool DisabledEffects[MAX_EFFECTS]; - - -effect_exception::effect_exception(ALenum code, const char *msg, ...) : mErrorCode{code} -{ - std::va_list args; - va_start(args, msg); - setMessage(msg, args); - va_end(args); -} - -namespace { - -struct EffectPropsItem { - ALenum Type; - const EffectProps &DefaultProps; - const EffectVtable &Vtable; -}; -constexpr EffectPropsItem EffectPropsList[] = { - { AL_EFFECT_NULL, NullEffectProps, NullEffectVtable }, - { AL_EFFECT_EAXREVERB, ReverbEffectProps, ReverbEffectVtable }, - { AL_EFFECT_REVERB, StdReverbEffectProps, StdReverbEffectVtable }, - { AL_EFFECT_AUTOWAH, AutowahEffectProps, AutowahEffectVtable }, - { AL_EFFECT_CHORUS, ChorusEffectProps, ChorusEffectVtable }, - { AL_EFFECT_COMPRESSOR, CompressorEffectProps, CompressorEffectVtable }, - { AL_EFFECT_DISTORTION, DistortionEffectProps, DistortionEffectVtable }, - { AL_EFFECT_ECHO, EchoEffectProps, EchoEffectVtable }, - { AL_EFFECT_EQUALIZER, EqualizerEffectProps, EqualizerEffectVtable }, - { AL_EFFECT_FLANGER, FlangerEffectProps, FlangerEffectVtable }, - { AL_EFFECT_FREQUENCY_SHIFTER, FshifterEffectProps, FshifterEffectVtable }, - { AL_EFFECT_RING_MODULATOR, ModulatorEffectProps, ModulatorEffectVtable }, - { AL_EFFECT_PITCH_SHIFTER, PshifterEffectProps, PshifterEffectVtable }, - { AL_EFFECT_VOCAL_MORPHER, VmorpherEffectProps, VmorpherEffectVtable }, - { AL_EFFECT_DEDICATED_DIALOGUE, DedicatedEffectProps, DedicatedEffectVtable }, - { AL_EFFECT_DEDICATED_LOW_FREQUENCY_EFFECT, DedicatedEffectProps, DedicatedEffectVtable }, - { AL_EFFECT_CONVOLUTION_REVERB_SOFT, ConvolutionEffectProps, ConvolutionEffectVtable }, -}; - - -void ALeffect_setParami(ALeffect *effect, ALenum param, int value) -{ effect->vtab->setParami(&effect->Props, param, value); } -void ALeffect_setParamiv(ALeffect *effect, ALenum param, const int *values) -{ effect->vtab->setParamiv(&effect->Props, param, values); } -void ALeffect_setParamf(ALeffect *effect, ALenum param, float value) -{ effect->vtab->setParamf(&effect->Props, param, value); } -void ALeffect_setParamfv(ALeffect *effect, ALenum param, const float *values) -{ effect->vtab->setParamfv(&effect->Props, param, values); } - -void ALeffect_getParami(const ALeffect *effect, ALenum param, int *value) -{ effect->vtab->getParami(&effect->Props, param, value); } -void ALeffect_getParamiv(const ALeffect *effect, ALenum param, int *values) -{ effect->vtab->getParamiv(&effect->Props, param, values); } -void ALeffect_getParamf(const ALeffect *effect, ALenum param, float *value) -{ effect->vtab->getParamf(&effect->Props, param, value); } -void ALeffect_getParamfv(const ALeffect *effect, ALenum param, float *values) -{ effect->vtab->getParamfv(&effect->Props, param, values); } - - -const EffectPropsItem *getEffectPropsItemByType(ALenum type) -{ - auto iter = std::find_if(std::begin(EffectPropsList), std::end(EffectPropsList), - [type](const EffectPropsItem &item) noexcept -> bool - { return item.Type == type; }); - return (iter != std::end(EffectPropsList)) ? std::addressof(*iter) : nullptr; -} - -void InitEffectParams(ALeffect *effect, ALenum type) -{ - const EffectPropsItem *item{getEffectPropsItemByType(type)}; - if(item) - { - effect->Props = item->DefaultProps; - effect->vtab = &item->Vtable; - } - else - { - effect->Props = EffectProps{}; - effect->vtab = &NullEffectVtable; - } - effect->type = type; -} - -bool EnsureEffects(ALCdevice *device, size_t needed) -{ - size_t count{std::accumulate(device->EffectList.cbegin(), device->EffectList.cend(), size_t{0}, - [](size_t cur, const EffectSubList &sublist) noexcept -> size_t - { return cur + static_cast(PopCount(sublist.FreeMask)); })}; - - while(needed > count) - { - if UNLIKELY(device->EffectList.size() >= 1<<25) - return false; - - device->EffectList.emplace_back(); - auto sublist = device->EffectList.end() - 1; - sublist->FreeMask = ~0_u64; - sublist->Effects = static_cast(al_calloc(alignof(ALeffect), sizeof(ALeffect)*64)); - if UNLIKELY(!sublist->Effects) - { - device->EffectList.pop_back(); - return false; - } - count += 64; - } - return true; -} - -ALeffect *AllocEffect(ALCdevice *device) -{ - auto sublist = std::find_if(device->EffectList.begin(), device->EffectList.end(), - [](const EffectSubList &entry) noexcept -> bool - { return entry.FreeMask != 0; } - ); - auto lidx = static_cast(std::distance(device->EffectList.begin(), sublist)); - auto slidx = static_cast(CountTrailingZeros(sublist->FreeMask)); - - ALeffect *effect{::new (sublist->Effects + slidx) ALeffect{}}; - InitEffectParams(effect, AL_EFFECT_NULL); - - /* Add 1 to avoid effect ID 0. */ - effect->id = ((lidx<<6) | slidx) + 1; - - sublist->FreeMask &= ~(1_u64 << slidx); - - return effect; -} - -void FreeEffect(ALCdevice *device, ALeffect *effect) -{ - const ALuint id{effect->id - 1}; - const size_t lidx{id >> 6}; - const ALuint slidx{id & 0x3f}; - - al::destroy_at(effect); - - device->EffectList[lidx].FreeMask |= 1_u64 << slidx; -} - -inline ALeffect *LookupEffect(ALCdevice *device, ALuint id) -{ - const size_t lidx{(id-1) >> 6}; - const ALuint slidx{(id-1) & 0x3f}; - - if UNLIKELY(lidx >= device->EffectList.size()) - return nullptr; - EffectSubList &sublist = device->EffectList[lidx]; - if UNLIKELY(sublist.FreeMask & (1_u64 << slidx)) - return nullptr; - return sublist.Effects + slidx; -} - -} // namespace - -AL_API void AL_APIENTRY alGenEffects(ALsizei n, ALuint *effects) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - if UNLIKELY(n < 0) - context->setError(AL_INVALID_VALUE, "Generating %d effects", n); - if UNLIKELY(n <= 0) return; - - ALCdevice *device{context->mDevice.get()}; - std::lock_guard _{device->EffectLock}; - if(!EnsureEffects(device, static_cast(n))) - { - context->setError(AL_OUT_OF_MEMORY, "Failed to allocate %d effect%s", n, (n==1)?"":"s"); - return; - } - - if LIKELY(n == 1) - { - /* Special handling for the easy and normal case. */ - ALeffect *effect{AllocEffect(device)}; - effects[0] = effect->id; - } - else - { - /* Store the allocated buffer IDs in a separate local list, to avoid - * modifying the user storage in case of failure. - */ - al::vector ids; - ids.reserve(static_cast(n)); - do { - ALeffect *effect{AllocEffect(device)}; - ids.emplace_back(effect->id); - } while(--n); - std::copy(ids.cbegin(), ids.cend(), effects); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alDeleteEffects(ALsizei n, const ALuint *effects) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - if UNLIKELY(n < 0) - context->setError(AL_INVALID_VALUE, "Deleting %d effects", n); - if UNLIKELY(n <= 0) return; - - ALCdevice *device{context->mDevice.get()}; - std::lock_guard _{device->EffectLock}; - - /* First try to find any effects that are invalid. */ - auto validate_effect = [device](const ALuint eid) -> bool - { return !eid || LookupEffect(device, eid) != nullptr; }; - - const ALuint *effects_end = effects + n; - auto inveffect = std::find_if_not(effects, effects_end, validate_effect); - if UNLIKELY(inveffect != effects_end) - { - context->setError(AL_INVALID_NAME, "Invalid effect ID %u", *inveffect); - return; - } - - /* All good. Delete non-0 effect IDs. */ - auto delete_effect = [device](ALuint eid) -> void - { - ALeffect *effect{eid ? LookupEffect(device, eid) : nullptr}; - if(effect) FreeEffect(device, effect); - }; - std::for_each(effects, effects_end, delete_effect); -} -END_API_FUNC - -AL_API ALboolean AL_APIENTRY alIsEffect(ALuint effect) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if LIKELY(context) - { - ALCdevice *device{context->mDevice.get()}; - std::lock_guard _{device->EffectLock}; - if(!effect || LookupEffect(device, effect)) - return AL_TRUE; - } - return AL_FALSE; -} -END_API_FUNC - -AL_API void AL_APIENTRY alEffecti(ALuint effect, ALenum param, ALint value) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - ALCdevice *device{context->mDevice.get()}; - std::lock_guard _{device->EffectLock}; - - ALeffect *aleffect{LookupEffect(device, effect)}; - if UNLIKELY(!aleffect) - context->setError(AL_INVALID_NAME, "Invalid effect ID %u", effect); - else if(param == AL_EFFECT_TYPE) - { - bool isOk{value == AL_EFFECT_NULL}; - if(!isOk) - { - for(const EffectList &effectitem : gEffectList) - { - if(value == effectitem.val && !DisabledEffects[effectitem.type]) - { - isOk = true; - break; - } - } - } - - if(isOk) - InitEffectParams(aleffect, value); - else - context->setError(AL_INVALID_VALUE, "Effect type 0x%04x not supported", value); - } - else try - { - /* Call the appropriate handler */ - ALeffect_setParami(aleffect, param, value); - } - catch(effect_exception &e) { - context->setError(e.errorCode(), "%s", e.what()); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alEffectiv(ALuint effect, ALenum param, const ALint *values) -START_API_FUNC -{ - switch(param) - { - case AL_EFFECT_TYPE: - alEffecti(effect, param, values[0]); - return; - } - - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - ALCdevice *device{context->mDevice.get()}; - std::lock_guard _{device->EffectLock}; - - ALeffect *aleffect{LookupEffect(device, effect)}; - if UNLIKELY(!aleffect) - context->setError(AL_INVALID_NAME, "Invalid effect ID %u", effect); - else try - { - /* Call the appropriate handler */ - ALeffect_setParamiv(aleffect, param, values); - } - catch(effect_exception &e) { - context->setError(e.errorCode(), "%s", e.what()); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alEffectf(ALuint effect, ALenum param, ALfloat value) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - ALCdevice *device{context->mDevice.get()}; - std::lock_guard _{device->EffectLock}; - - ALeffect *aleffect{LookupEffect(device, effect)}; - if UNLIKELY(!aleffect) - context->setError(AL_INVALID_NAME, "Invalid effect ID %u", effect); - else try - { - /* Call the appropriate handler */ - ALeffect_setParamf(aleffect, param, value); - } - catch(effect_exception &e) { - context->setError(e.errorCode(), "%s", e.what()); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alEffectfv(ALuint effect, ALenum param, const ALfloat *values) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - ALCdevice *device{context->mDevice.get()}; - std::lock_guard _{device->EffectLock}; - - ALeffect *aleffect{LookupEffect(device, effect)}; - if UNLIKELY(!aleffect) - context->setError(AL_INVALID_NAME, "Invalid effect ID %u", effect); - else try - { - /* Call the appropriate handler */ - ALeffect_setParamfv(aleffect, param, values); - } - catch(effect_exception &e) { - context->setError(e.errorCode(), "%s", e.what()); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alGetEffecti(ALuint effect, ALenum param, ALint *value) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - ALCdevice *device{context->mDevice.get()}; - std::lock_guard _{device->EffectLock}; - - const ALeffect *aleffect{LookupEffect(device, effect)}; - if UNLIKELY(!aleffect) - context->setError(AL_INVALID_NAME, "Invalid effect ID %u", effect); - else if(param == AL_EFFECT_TYPE) - *value = aleffect->type; - else try - { - /* Call the appropriate handler */ - ALeffect_getParami(aleffect, param, value); - } - catch(effect_exception &e) { - context->setError(e.errorCode(), "%s", e.what()); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alGetEffectiv(ALuint effect, ALenum param, ALint *values) -START_API_FUNC -{ - switch(param) - { - case AL_EFFECT_TYPE: - alGetEffecti(effect, param, values); - return; - } - - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - ALCdevice *device{context->mDevice.get()}; - std::lock_guard _{device->EffectLock}; - - const ALeffect *aleffect{LookupEffect(device, effect)}; - if UNLIKELY(!aleffect) - context->setError(AL_INVALID_NAME, "Invalid effect ID %u", effect); - else try - { - /* Call the appropriate handler */ - ALeffect_getParamiv(aleffect, param, values); - } - catch(effect_exception &e) { - context->setError(e.errorCode(), "%s", e.what()); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alGetEffectf(ALuint effect, ALenum param, ALfloat *value) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - ALCdevice *device{context->mDevice.get()}; - std::lock_guard _{device->EffectLock}; - - const ALeffect *aleffect{LookupEffect(device, effect)}; - if UNLIKELY(!aleffect) - context->setError(AL_INVALID_NAME, "Invalid effect ID %u", effect); - else try - { - /* Call the appropriate handler */ - ALeffect_getParamf(aleffect, param, value); - } - catch(effect_exception &e) { - context->setError(e.errorCode(), "%s", e.what()); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alGetEffectfv(ALuint effect, ALenum param, ALfloat *values) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - ALCdevice *device{context->mDevice.get()}; - std::lock_guard _{device->EffectLock}; - - const ALeffect *aleffect{LookupEffect(device, effect)}; - if UNLIKELY(!aleffect) - context->setError(AL_INVALID_NAME, "Invalid effect ID %u", effect); - else try - { - /* Call the appropriate handler */ - ALeffect_getParamfv(aleffect, param, values); - } - catch(effect_exception &e) { - context->setError(e.errorCode(), "%s", e.what()); - } -} -END_API_FUNC - - -void InitEffect(ALeffect *effect) -{ - InitEffectParams(effect, AL_EFFECT_NULL); -} - -EffectSubList::~EffectSubList() -{ - uint64_t usemask{~FreeMask}; - while(usemask) - { - const ALsizei idx{CountTrailingZeros(usemask)}; - al::destroy_at(Effects+idx); - usemask &= ~(1_u64 << idx); - } - FreeMask = ~usemask; - al_free(Effects); - Effects = nullptr; -} - - -#define DECL(x) { #x, EFX_REVERB_PRESET_##x } -static const struct { - const char name[32]; - EFXEAXREVERBPROPERTIES props; -} reverblist[] = { - DECL(GENERIC), - DECL(PADDEDCELL), - DECL(ROOM), - DECL(BATHROOM), - DECL(LIVINGROOM), - DECL(STONEROOM), - DECL(AUDITORIUM), - DECL(CONCERTHALL), - DECL(CAVE), - DECL(ARENA), - DECL(HANGAR), - DECL(CARPETEDHALLWAY), - DECL(HALLWAY), - DECL(STONECORRIDOR), - DECL(ALLEY), - DECL(FOREST), - DECL(CITY), - DECL(MOUNTAINS), - DECL(QUARRY), - DECL(PLAIN), - DECL(PARKINGLOT), - DECL(SEWERPIPE), - DECL(UNDERWATER), - DECL(DRUGGED), - DECL(DIZZY), - DECL(PSYCHOTIC), - - DECL(CASTLE_SMALLROOM), - DECL(CASTLE_SHORTPASSAGE), - DECL(CASTLE_MEDIUMROOM), - DECL(CASTLE_LARGEROOM), - DECL(CASTLE_LONGPASSAGE), - DECL(CASTLE_HALL), - DECL(CASTLE_CUPBOARD), - DECL(CASTLE_COURTYARD), - DECL(CASTLE_ALCOVE), - - DECL(FACTORY_SMALLROOM), - DECL(FACTORY_SHORTPASSAGE), - DECL(FACTORY_MEDIUMROOM), - DECL(FACTORY_LARGEROOM), - DECL(FACTORY_LONGPASSAGE), - DECL(FACTORY_HALL), - DECL(FACTORY_CUPBOARD), - DECL(FACTORY_COURTYARD), - DECL(FACTORY_ALCOVE), - - DECL(ICEPALACE_SMALLROOM), - DECL(ICEPALACE_SHORTPASSAGE), - DECL(ICEPALACE_MEDIUMROOM), - DECL(ICEPALACE_LARGEROOM), - DECL(ICEPALACE_LONGPASSAGE), - DECL(ICEPALACE_HALL), - DECL(ICEPALACE_CUPBOARD), - DECL(ICEPALACE_COURTYARD), - DECL(ICEPALACE_ALCOVE), - - DECL(SPACESTATION_SMALLROOM), - DECL(SPACESTATION_SHORTPASSAGE), - DECL(SPACESTATION_MEDIUMROOM), - DECL(SPACESTATION_LARGEROOM), - DECL(SPACESTATION_LONGPASSAGE), - DECL(SPACESTATION_HALL), - DECL(SPACESTATION_CUPBOARD), - DECL(SPACESTATION_ALCOVE), - - DECL(WOODEN_SMALLROOM), - DECL(WOODEN_SHORTPASSAGE), - DECL(WOODEN_MEDIUMROOM), - DECL(WOODEN_LARGEROOM), - DECL(WOODEN_LONGPASSAGE), - DECL(WOODEN_HALL), - DECL(WOODEN_CUPBOARD), - DECL(WOODEN_COURTYARD), - DECL(WOODEN_ALCOVE), - - DECL(SPORT_EMPTYSTADIUM), - DECL(SPORT_SQUASHCOURT), - DECL(SPORT_SMALLSWIMMINGPOOL), - DECL(SPORT_LARGESWIMMINGPOOL), - DECL(SPORT_GYMNASIUM), - DECL(SPORT_FULLSTADIUM), - DECL(SPORT_STADIUMTANNOY), - - DECL(PREFAB_WORKSHOP), - DECL(PREFAB_SCHOOLROOM), - DECL(PREFAB_PRACTISEROOM), - DECL(PREFAB_OUTHOUSE), - DECL(PREFAB_CARAVAN), - - DECL(DOME_TOMB), - DECL(PIPE_SMALL), - DECL(DOME_SAINTPAULS), - DECL(PIPE_LONGTHIN), - DECL(PIPE_LARGE), - DECL(PIPE_RESONANT), - - DECL(OUTDOORS_BACKYARD), - DECL(OUTDOORS_ROLLINGPLAINS), - DECL(OUTDOORS_DEEPCANYON), - DECL(OUTDOORS_CREEK), - DECL(OUTDOORS_VALLEY), - - DECL(MOOD_HEAVEN), - DECL(MOOD_HELL), - DECL(MOOD_MEMORY), - - DECL(DRIVING_COMMENTATOR), - DECL(DRIVING_PITGARAGE), - DECL(DRIVING_INCAR_RACER), - DECL(DRIVING_INCAR_SPORTS), - DECL(DRIVING_INCAR_LUXURY), - DECL(DRIVING_FULLGRANDSTAND), - DECL(DRIVING_EMPTYGRANDSTAND), - DECL(DRIVING_TUNNEL), - - DECL(CITY_STREETS), - DECL(CITY_SUBWAY), - DECL(CITY_MUSEUM), - DECL(CITY_LIBRARY), - DECL(CITY_UNDERPASS), - DECL(CITY_ABANDONED), - - DECL(DUSTYROOM), - DECL(CHAPEL), - DECL(SMALLWATERROOM), -}; -#undef DECL - -void LoadReverbPreset(const char *name, ALeffect *effect) -{ - if(al::strcasecmp(name, "NONE") == 0) - { - InitEffectParams(effect, AL_EFFECT_NULL); - TRACE("Loading reverb '%s'\n", "NONE"); - return; - } - - if(!DisabledEffects[EAXREVERB_EFFECT]) - InitEffectParams(effect, AL_EFFECT_EAXREVERB); - else if(!DisabledEffects[REVERB_EFFECT]) - InitEffectParams(effect, AL_EFFECT_REVERB); - else - InitEffectParams(effect, AL_EFFECT_NULL); - for(const auto &reverbitem : reverblist) - { - const EFXEAXREVERBPROPERTIES *props; - - if(al::strcasecmp(name, reverbitem.name) != 0) - continue; - - TRACE("Loading reverb '%s'\n", reverbitem.name); - props = &reverbitem.props; - effect->Props.Reverb.Density = props->flDensity; - effect->Props.Reverb.Diffusion = props->flDiffusion; - effect->Props.Reverb.Gain = props->flGain; - effect->Props.Reverb.GainHF = props->flGainHF; - effect->Props.Reverb.GainLF = props->flGainLF; - effect->Props.Reverb.DecayTime = props->flDecayTime; - effect->Props.Reverb.DecayHFRatio = props->flDecayHFRatio; - effect->Props.Reverb.DecayLFRatio = props->flDecayLFRatio; - effect->Props.Reverb.ReflectionsGain = props->flReflectionsGain; - effect->Props.Reverb.ReflectionsDelay = props->flReflectionsDelay; - effect->Props.Reverb.ReflectionsPan[0] = props->flReflectionsPan[0]; - effect->Props.Reverb.ReflectionsPan[1] = props->flReflectionsPan[1]; - effect->Props.Reverb.ReflectionsPan[2] = props->flReflectionsPan[2]; - effect->Props.Reverb.LateReverbGain = props->flLateReverbGain; - effect->Props.Reverb.LateReverbDelay = props->flLateReverbDelay; - effect->Props.Reverb.LateReverbPan[0] = props->flLateReverbPan[0]; - effect->Props.Reverb.LateReverbPan[1] = props->flLateReverbPan[1]; - effect->Props.Reverb.LateReverbPan[2] = props->flLateReverbPan[2]; - effect->Props.Reverb.EchoTime = props->flEchoTime; - effect->Props.Reverb.EchoDepth = props->flEchoDepth; - effect->Props.Reverb.ModulationTime = props->flModulationTime; - effect->Props.Reverb.ModulationDepth = props->flModulationDepth; - effect->Props.Reverb.AirAbsorptionGainHF = props->flAirAbsorptionGainHF; - effect->Props.Reverb.HFReference = props->flHFReference; - effect->Props.Reverb.LFReference = props->flLFReference; - effect->Props.Reverb.RoomRolloffFactor = props->flRoomRolloffFactor; - effect->Props.Reverb.DecayHFLimit = props->iDecayHFLimit ? AL_TRUE : AL_FALSE; - return; - } - - WARN("Reverb preset '%s' not found\n", name); -} diff --git a/al/effect.h b/al/effect.h deleted file mode 100644 index 10a692c9..00000000 --- a/al/effect.h +++ /dev/null @@ -1,60 +0,0 @@ -#ifndef AL_EFFECT_H -#define AL_EFFECT_H - -#include "AL/al.h" -#include "AL/efx.h" - -#include "al/effects/effects.h" -#include "alc/effects/base.h" - - -enum { - EAXREVERB_EFFECT = 0, - REVERB_EFFECT, - AUTOWAH_EFFECT, - CHORUS_EFFECT, - COMPRESSOR_EFFECT, - DISTORTION_EFFECT, - ECHO_EFFECT, - EQUALIZER_EFFECT, - FLANGER_EFFECT, - FSHIFTER_EFFECT, - MODULATOR_EFFECT, - PSHIFTER_EFFECT, - VMORPHER_EFFECT, - DEDICATED_EFFECT, - CONVOLUTION_EFFECT, - - MAX_EFFECTS -}; -extern bool DisabledEffects[MAX_EFFECTS]; - -extern float ReverbBoost; - -struct EffectList { - const char name[16]; - int type; - ALenum val; -}; -extern const EffectList gEffectList[16]; - - -struct ALeffect { - // Effect type (AL_EFFECT_NULL, ...) - ALenum type{AL_EFFECT_NULL}; - - EffectProps Props{}; - - const EffectVtable *vtab{nullptr}; - - /* Self ID */ - ALuint id{0u}; - - DISABLE_ALLOC() -}; - -void InitEffect(ALeffect *effect); - -void LoadReverbPreset(const char *name, ALeffect *effect); - -#endif diff --git a/al/effects/autowah.cpp b/al/effects/autowah.cpp deleted file mode 100644 index 65d4b702..00000000 --- a/al/effects/autowah.cpp +++ /dev/null @@ -1,109 +0,0 @@ - -#include "config.h" - -#include -#include - -#include - -#include "AL/efx.h" - -#include "effects/base.h" -#include "effects.h" - -namespace { - -void Autowah_setParamf(EffectProps *props, ALenum param, float val) -{ - switch(param) - { - case AL_AUTOWAH_ATTACK_TIME: - if(!(val >= AL_AUTOWAH_MIN_ATTACK_TIME && val <= AL_AUTOWAH_MAX_ATTACK_TIME)) - throw effect_exception{AL_INVALID_VALUE, "Autowah attack time out of range"}; - props->Autowah.AttackTime = val; - break; - - case AL_AUTOWAH_RELEASE_TIME: - if(!(val >= AL_AUTOWAH_MIN_RELEASE_TIME && val <= AL_AUTOWAH_MAX_RELEASE_TIME)) - throw effect_exception{AL_INVALID_VALUE, "Autowah release time out of range"}; - props->Autowah.ReleaseTime = val; - break; - - case AL_AUTOWAH_RESONANCE: - if(!(val >= AL_AUTOWAH_MIN_RESONANCE && val <= AL_AUTOWAH_MAX_RESONANCE)) - throw effect_exception{AL_INVALID_VALUE, "Autowah resonance out of range"}; - props->Autowah.Resonance = val; - break; - - case AL_AUTOWAH_PEAK_GAIN: - if(!(val >= AL_AUTOWAH_MIN_PEAK_GAIN && val <= AL_AUTOWAH_MAX_PEAK_GAIN)) - throw effect_exception{AL_INVALID_VALUE, "Autowah peak gain out of range"}; - props->Autowah.PeakGain = val; - break; - - default: - throw effect_exception{AL_INVALID_ENUM, "Invalid autowah float property 0x%04x", param}; - } -} -void Autowah_setParamfv(EffectProps *props, ALenum param, const float *vals) -{ Autowah_setParamf(props, param, vals[0]); } - -void Autowah_setParami(EffectProps*, ALenum param, int) -{ throw effect_exception{AL_INVALID_ENUM, "Invalid autowah integer property 0x%04x", param}; } -void Autowah_setParamiv(EffectProps*, ALenum param, const int*) -{ - throw effect_exception{AL_INVALID_ENUM, "Invalid autowah integer vector property 0x%04x", - param}; -} - -void Autowah_getParamf(const EffectProps *props, ALenum param, float *val) -{ - switch(param) - { - case AL_AUTOWAH_ATTACK_TIME: - *val = props->Autowah.AttackTime; - break; - - case AL_AUTOWAH_RELEASE_TIME: - *val = props->Autowah.ReleaseTime; - break; - - case AL_AUTOWAH_RESONANCE: - *val = props->Autowah.Resonance; - break; - - case AL_AUTOWAH_PEAK_GAIN: - *val = props->Autowah.PeakGain; - break; - - default: - throw effect_exception{AL_INVALID_ENUM, "Invalid autowah float property 0x%04x", param}; - } - -} -void Autowah_getParamfv(const EffectProps *props, ALenum param, float *vals) -{ Autowah_getParamf(props, param, vals); } - -void Autowah_getParami(const EffectProps*, ALenum param, int*) -{ throw effect_exception{AL_INVALID_ENUM, "Invalid autowah integer property 0x%04x", param}; } -void Autowah_getParamiv(const EffectProps*, ALenum param, int*) -{ - throw effect_exception{AL_INVALID_ENUM, "Invalid autowah integer vector property 0x%04x", - param}; -} - -EffectProps genDefaultProps() noexcept -{ - EffectProps props{}; - props.Autowah.AttackTime = AL_AUTOWAH_DEFAULT_ATTACK_TIME; - props.Autowah.ReleaseTime = AL_AUTOWAH_DEFAULT_RELEASE_TIME; - props.Autowah.Resonance = AL_AUTOWAH_DEFAULT_RESONANCE; - props.Autowah.PeakGain = AL_AUTOWAH_DEFAULT_PEAK_GAIN; - return props; -} - -} // namespace - -DEFINE_ALEFFECT_VTABLE(Autowah); - -const EffectProps AutowahEffectProps{genDefaultProps()}; diff --git a/al/effects/chorus.cpp b/al/effects/chorus.cpp deleted file mode 100644 index b2395283..00000000 --- a/al/effects/chorus.cpp +++ /dev/null @@ -1,276 +0,0 @@ - -#include "config.h" - -#include "AL/al.h" -#include "AL/efx.h" - -#include "aloptional.h" -#include "core/logging.h" -#include "effects.h" -#include "effects/base.h" - - -namespace { - -static_assert(AL_CHORUS_WAVEFORM_SINUSOID == AL_FLANGER_WAVEFORM_SINUSOID, "Chorus/Flanger waveform value mismatch"); -static_assert(AL_CHORUS_WAVEFORM_TRIANGLE == AL_FLANGER_WAVEFORM_TRIANGLE, "Chorus/Flanger waveform value mismatch"); - -inline al::optional WaveformFromEnum(ALenum type) -{ - switch(type) - { - case AL_CHORUS_WAVEFORM_SINUSOID: return al::make_optional(ChorusWaveform::Sinusoid); - case AL_CHORUS_WAVEFORM_TRIANGLE: return al::make_optional(ChorusWaveform::Triangle); - } - return al::nullopt; -} -inline ALenum EnumFromWaveform(ChorusWaveform type) -{ - switch(type) - { - case ChorusWaveform::Sinusoid: return AL_CHORUS_WAVEFORM_SINUSOID; - case ChorusWaveform::Triangle: return AL_CHORUS_WAVEFORM_TRIANGLE; - } - throw std::runtime_error{"Invalid chorus waveform: "+std::to_string(static_cast(type))}; -} - -void Chorus_setParami(EffectProps *props, ALenum param, int val) -{ - switch(param) - { - case AL_CHORUS_WAVEFORM: - if(auto formopt = WaveformFromEnum(val)) - props->Chorus.Waveform = *formopt; - else - throw effect_exception{AL_INVALID_VALUE, "Invalid chorus waveform: 0x%04x", val}; - break; - - case AL_CHORUS_PHASE: - if(!(val >= AL_CHORUS_MIN_PHASE && val <= AL_CHORUS_MAX_PHASE)) - throw effect_exception{AL_INVALID_VALUE, "Chorus phase out of range: %d", val}; - props->Chorus.Phase = val; - break; - - default: - throw effect_exception{AL_INVALID_ENUM, "Invalid chorus integer property 0x%04x", param}; - } -} -void Chorus_setParamiv(EffectProps *props, ALenum param, const int *vals) -{ Chorus_setParami(props, param, vals[0]); } -void Chorus_setParamf(EffectProps *props, ALenum param, float val) -{ - switch(param) - { - case AL_CHORUS_RATE: - if(!(val >= AL_CHORUS_MIN_RATE && val <= AL_CHORUS_MAX_RATE)) - throw effect_exception{AL_INVALID_VALUE, "Chorus rate out of range: %f", val}; - props->Chorus.Rate = val; - break; - - case AL_CHORUS_DEPTH: - if(!(val >= AL_CHORUS_MIN_DEPTH && val <= AL_CHORUS_MAX_DEPTH)) - throw effect_exception{AL_INVALID_VALUE, "Chorus depth out of range: %f", val}; - props->Chorus.Depth = val; - break; - - case AL_CHORUS_FEEDBACK: - if(!(val >= AL_CHORUS_MIN_FEEDBACK && val <= AL_CHORUS_MAX_FEEDBACK)) - throw effect_exception{AL_INVALID_VALUE, "Chorus feedback out of range: %f", val}; - props->Chorus.Feedback = val; - break; - - case AL_CHORUS_DELAY: - if(!(val >= AL_CHORUS_MIN_DELAY && val <= AL_CHORUS_MAX_DELAY)) - throw effect_exception{AL_INVALID_VALUE, "Chorus delay out of range: %f", val}; - props->Chorus.Delay = val; - break; - - default: - throw effect_exception{AL_INVALID_ENUM, "Invalid chorus float property 0x%04x", param}; - } -} -void Chorus_setParamfv(EffectProps *props, ALenum param, const float *vals) -{ Chorus_setParamf(props, param, vals[0]); } - -void Chorus_getParami(const EffectProps *props, ALenum param, int *val) -{ - switch(param) - { - case AL_CHORUS_WAVEFORM: - *val = EnumFromWaveform(props->Chorus.Waveform); - break; - - case AL_CHORUS_PHASE: - *val = props->Chorus.Phase; - break; - - default: - throw effect_exception{AL_INVALID_ENUM, "Invalid chorus integer property 0x%04x", param}; - } -} -void Chorus_getParamiv(const EffectProps *props, ALenum param, int *vals) -{ Chorus_getParami(props, param, vals); } -void Chorus_getParamf(const EffectProps *props, ALenum param, float *val) -{ - switch(param) - { - case AL_CHORUS_RATE: - *val = props->Chorus.Rate; - break; - - case AL_CHORUS_DEPTH: - *val = props->Chorus.Depth; - break; - - case AL_CHORUS_FEEDBACK: - *val = props->Chorus.Feedback; - break; - - case AL_CHORUS_DELAY: - *val = props->Chorus.Delay; - break; - - default: - throw effect_exception{AL_INVALID_ENUM, "Invalid chorus float property 0x%04x", param}; - } -} -void Chorus_getParamfv(const EffectProps *props, ALenum param, float *vals) -{ Chorus_getParamf(props, param, vals); } - -const EffectProps genDefaultChorusProps() noexcept -{ - EffectProps props{}; - props.Chorus.Waveform = *WaveformFromEnum(AL_CHORUS_DEFAULT_WAVEFORM); - props.Chorus.Phase = AL_CHORUS_DEFAULT_PHASE; - props.Chorus.Rate = AL_CHORUS_DEFAULT_RATE; - props.Chorus.Depth = AL_CHORUS_DEFAULT_DEPTH; - props.Chorus.Feedback = AL_CHORUS_DEFAULT_FEEDBACK; - props.Chorus.Delay = AL_CHORUS_DEFAULT_DELAY; - return props; -} - - -void Flanger_setParami(EffectProps *props, ALenum param, int val) -{ - switch(param) - { - case AL_FLANGER_WAVEFORM: - if(auto formopt = WaveformFromEnum(val)) - props->Chorus.Waveform = *formopt; - else - throw effect_exception{AL_INVALID_VALUE, "Invalid flanger waveform: 0x%04x", val}; - break; - - case AL_FLANGER_PHASE: - if(!(val >= AL_FLANGER_MIN_PHASE && val <= AL_FLANGER_MAX_PHASE)) - throw effect_exception{AL_INVALID_VALUE, "Flanger phase out of range: %d", val}; - props->Chorus.Phase = val; - break; - - default: - throw effect_exception{AL_INVALID_ENUM, "Invalid flanger integer property 0x%04x", param}; - } -} -void Flanger_setParamiv(EffectProps *props, ALenum param, const int *vals) -{ Flanger_setParami(props, param, vals[0]); } -void Flanger_setParamf(EffectProps *props, ALenum param, float val) -{ - switch(param) - { - case AL_FLANGER_RATE: - if(!(val >= AL_FLANGER_MIN_RATE && val <= AL_FLANGER_MAX_RATE)) - throw effect_exception{AL_INVALID_VALUE, "Flanger rate out of range: %f", val}; - props->Chorus.Rate = val; - break; - - case AL_FLANGER_DEPTH: - if(!(val >= AL_FLANGER_MIN_DEPTH && val <= AL_FLANGER_MAX_DEPTH)) - throw effect_exception{AL_INVALID_VALUE, "Flanger depth out of range: %f", val}; - props->Chorus.Depth = val; - break; - - case AL_FLANGER_FEEDBACK: - if(!(val >= AL_FLANGER_MIN_FEEDBACK && val <= AL_FLANGER_MAX_FEEDBACK)) - throw effect_exception{AL_INVALID_VALUE, "Flanger feedback out of range: %f", val}; - props->Chorus.Feedback = val; - break; - - case AL_FLANGER_DELAY: - if(!(val >= AL_FLANGER_MIN_DELAY && val <= AL_FLANGER_MAX_DELAY)) - throw effect_exception{AL_INVALID_VALUE, "Flanger delay out of range: %f", val}; - props->Chorus.Delay = val; - break; - - default: - throw effect_exception{AL_INVALID_ENUM, "Invalid flanger float property 0x%04x", param}; - } -} -void Flanger_setParamfv(EffectProps *props, ALenum param, const float *vals) -{ Flanger_setParamf(props, param, vals[0]); } - -void Flanger_getParami(const EffectProps *props, ALenum param, int *val) -{ - switch(param) - { - case AL_FLANGER_WAVEFORM: - *val = EnumFromWaveform(props->Chorus.Waveform); - break; - - case AL_FLANGER_PHASE: - *val = props->Chorus.Phase; - break; - - default: - throw effect_exception{AL_INVALID_ENUM, "Invalid flanger integer property 0x%04x", param}; - } -} -void Flanger_getParamiv(const EffectProps *props, ALenum param, int *vals) -{ Flanger_getParami(props, param, vals); } -void Flanger_getParamf(const EffectProps *props, ALenum param, float *val) -{ - switch(param) - { - case AL_FLANGER_RATE: - *val = props->Chorus.Rate; - break; - - case AL_FLANGER_DEPTH: - *val = props->Chorus.Depth; - break; - - case AL_FLANGER_FEEDBACK: - *val = props->Chorus.Feedback; - break; - - case AL_FLANGER_DELAY: - *val = props->Chorus.Delay; - break; - - default: - throw effect_exception{AL_INVALID_ENUM, "Invalid flanger float property 0x%04x", param}; - } -} -void Flanger_getParamfv(const EffectProps *props, ALenum param, float *vals) -{ Flanger_getParamf(props, param, vals); } - -EffectProps genDefaultFlangerProps() noexcept -{ - EffectProps props{}; - props.Chorus.Waveform = *WaveformFromEnum(AL_FLANGER_DEFAULT_WAVEFORM); - props.Chorus.Phase = AL_FLANGER_DEFAULT_PHASE; - props.Chorus.Rate = AL_FLANGER_DEFAULT_RATE; - props.Chorus.Depth = AL_FLANGER_DEFAULT_DEPTH; - props.Chorus.Feedback = AL_FLANGER_DEFAULT_FEEDBACK; - props.Chorus.Delay = AL_FLANGER_DEFAULT_DELAY; - return props; -} - -} // namespace - -DEFINE_ALEFFECT_VTABLE(Chorus); - -const EffectProps ChorusEffectProps{genDefaultChorusProps()}; - -DEFINE_ALEFFECT_VTABLE(Flanger); - -const EffectProps FlangerEffectProps{genDefaultFlangerProps()}; diff --git a/al/effects/compressor.cpp b/al/effects/compressor.cpp deleted file mode 100644 index 94e07431..00000000 --- a/al/effects/compressor.cpp +++ /dev/null @@ -1,72 +0,0 @@ - -#include "config.h" - -#include "AL/al.h" -#include "AL/efx.h" - -#include "effects.h" -#include "effects/base.h" - - -namespace { - -void Compressor_setParami(EffectProps *props, ALenum param, int val) -{ - switch(param) - { - case AL_COMPRESSOR_ONOFF: - if(!(val >= AL_COMPRESSOR_MIN_ONOFF && val <= AL_COMPRESSOR_MAX_ONOFF)) - throw effect_exception{AL_INVALID_VALUE, "Compressor state out of range"}; - props->Compressor.OnOff = (val != AL_FALSE); - break; - - default: - throw effect_exception{AL_INVALID_ENUM, "Invalid compressor integer property 0x%04x", - param}; - } -} -void Compressor_setParamiv(EffectProps *props, ALenum param, const int *vals) -{ Compressor_setParami(props, param, vals[0]); } -void Compressor_setParamf(EffectProps*, ALenum param, float) -{ throw effect_exception{AL_INVALID_ENUM, "Invalid compressor float property 0x%04x", param}; } -void Compressor_setParamfv(EffectProps*, ALenum param, const float*) -{ - throw effect_exception{AL_INVALID_ENUM, "Invalid compressor float-vector property 0x%04x", - param}; -} - -void Compressor_getParami(const EffectProps *props, ALenum param, int *val) -{ - switch(param) - { - case AL_COMPRESSOR_ONOFF: - *val = props->Compressor.OnOff; - break; - - default: - throw effect_exception{AL_INVALID_ENUM, "Invalid compressor integer property 0x%04x", - param}; - } -} -void Compressor_getParamiv(const EffectProps *props, ALenum param, int *vals) -{ Compressor_getParami(props, param, vals); } -void Compressor_getParamf(const EffectProps*, ALenum param, float*) -{ throw effect_exception{AL_INVALID_ENUM, "Invalid compressor float property 0x%04x", param}; } -void Compressor_getParamfv(const EffectProps*, ALenum param, float*) -{ - throw effect_exception{AL_INVALID_ENUM, "Invalid compressor float-vector property 0x%04x", - param}; -} - -EffectProps genDefaultProps() noexcept -{ - EffectProps props{}; - props.Compressor.OnOff = AL_COMPRESSOR_DEFAULT_ONOFF; - return props; -} - -} // namespace - -DEFINE_ALEFFECT_VTABLE(Compressor); - -const EffectProps CompressorEffectProps{genDefaultProps()}; diff --git a/al/effects/convolution.cpp b/al/effects/convolution.cpp deleted file mode 100644 index 4d87b1c4..00000000 --- a/al/effects/convolution.cpp +++ /dev/null @@ -1,93 +0,0 @@ - -#include "config.h" - -#include "AL/al.h" -#include "inprogext.h" - -#include "effects.h" -#include "effects/base.h" - - -namespace { - -void Convolution_setParami(EffectProps* /*props*/, ALenum param, int /*val*/) -{ - switch(param) - { - default: - throw effect_exception{AL_INVALID_ENUM, "Invalid null effect integer property 0x%04x", - param}; - } -} -void Convolution_setParamiv(EffectProps *props, ALenum param, const int *vals) -{ - switch(param) - { - default: - Convolution_setParami(props, param, vals[0]); - } -} -void Convolution_setParamf(EffectProps* /*props*/, ALenum param, float /*val*/) -{ - switch(param) - { - default: - throw effect_exception{AL_INVALID_ENUM, "Invalid null effect float property 0x%04x", - param}; - } -} -void Convolution_setParamfv(EffectProps *props, ALenum param, const float *vals) -{ - switch(param) - { - default: - Convolution_setParamf(props, param, vals[0]); - } -} - -void Convolution_getParami(const EffectProps* /*props*/, ALenum param, int* /*val*/) -{ - switch(param) - { - default: - throw effect_exception{AL_INVALID_ENUM, "Invalid null effect integer property 0x%04x", - param}; - } -} -void Convolution_getParamiv(const EffectProps *props, ALenum param, int *vals) -{ - switch(param) - { - default: - Convolution_getParami(props, param, vals); - } -} -void Convolution_getParamf(const EffectProps* /*props*/, ALenum param, float* /*val*/) -{ - switch(param) - { - default: - throw effect_exception{AL_INVALID_ENUM, "Invalid null effect float property 0x%04x", - param}; - } -} -void Convolution_getParamfv(const EffectProps *props, ALenum param, float *vals) -{ - switch(param) - { - default: - Convolution_getParamf(props, param, vals); - } -} - -EffectProps genDefaultProps() noexcept -{ - EffectProps props{}; - return props; -} - -} // namespace - -DEFINE_ALEFFECT_VTABLE(Convolution); - -const EffectProps ConvolutionEffectProps{genDefaultProps()}; diff --git a/al/effects/dedicated.cpp b/al/effects/dedicated.cpp deleted file mode 100644 index 334d9e56..00000000 --- a/al/effects/dedicated.cpp +++ /dev/null @@ -1,72 +0,0 @@ - -#include "config.h" - -#include - -#include "AL/al.h" -#include "AL/efx.h" - -#include "effects.h" -#include "effects/base.h" - - -namespace { - -void Dedicated_setParami(EffectProps*, ALenum param, int) -{ throw effect_exception{AL_INVALID_ENUM, "Invalid dedicated integer property 0x%04x", param}; } -void Dedicated_setParamiv(EffectProps*, ALenum param, const int*) -{ - throw effect_exception{AL_INVALID_ENUM, "Invalid dedicated integer-vector property 0x%04x", - param}; -} -void Dedicated_setParamf(EffectProps *props, ALenum param, float val) -{ - switch(param) - { - case AL_DEDICATED_GAIN: - if(!(val >= 0.0f && std::isfinite(val))) - throw effect_exception{AL_INVALID_VALUE, "Dedicated gain out of range"}; - props->Dedicated.Gain = val; - break; - - default: - throw effect_exception{AL_INVALID_ENUM, "Invalid dedicated float property 0x%04x", param}; - } -} -void Dedicated_setParamfv(EffectProps *props, ALenum param, const float *vals) -{ Dedicated_setParamf(props, param, vals[0]); } - -void Dedicated_getParami(const EffectProps*, ALenum param, int*) -{ throw effect_exception{AL_INVALID_ENUM, "Invalid dedicated integer property 0x%04x", param}; } -void Dedicated_getParamiv(const EffectProps*, ALenum param, int*) -{ - throw effect_exception{AL_INVALID_ENUM, "Invalid dedicated integer-vector property 0x%04x", - param}; -} -void Dedicated_getParamf(const EffectProps *props, ALenum param, float *val) -{ - switch(param) - { - case AL_DEDICATED_GAIN: - *val = props->Dedicated.Gain; - break; - - default: - throw effect_exception{AL_INVALID_ENUM, "Invalid dedicated float property 0x%04x", param}; - } -} -void Dedicated_getParamfv(const EffectProps *props, ALenum param, float *vals) -{ Dedicated_getParamf(props, param, vals); } - -EffectProps genDefaultProps() noexcept -{ - EffectProps props{}; - props.Dedicated.Gain = 1.0f; - return props; -} - -} // namespace - -DEFINE_ALEFFECT_VTABLE(Dedicated); - -const EffectProps DedicatedEffectProps{genDefaultProps()}; diff --git a/al/effects/distortion.cpp b/al/effects/distortion.cpp deleted file mode 100644 index 8961a4d9..00000000 --- a/al/effects/distortion.cpp +++ /dev/null @@ -1,114 +0,0 @@ - -#include "config.h" - -#include "AL/al.h" -#include "AL/efx.h" - -#include "effects.h" -#include "effects/base.h" - - -namespace { - -void Distortion_setParami(EffectProps*, ALenum param, int) -{ throw effect_exception{AL_INVALID_ENUM, "Invalid distortion integer property 0x%04x", param}; } -void Distortion_setParamiv(EffectProps*, ALenum param, const int*) -{ - throw effect_exception{AL_INVALID_ENUM, "Invalid distortion integer-vector property 0x%04x", - param}; -} -void Distortion_setParamf(EffectProps *props, ALenum param, float val) -{ - switch(param) - { - case AL_DISTORTION_EDGE: - if(!(val >= AL_DISTORTION_MIN_EDGE && val <= AL_DISTORTION_MAX_EDGE)) - throw effect_exception{AL_INVALID_VALUE, "Distortion edge out of range"}; - props->Distortion.Edge = val; - break; - - case AL_DISTORTION_GAIN: - if(!(val >= AL_DISTORTION_MIN_GAIN && val <= AL_DISTORTION_MAX_GAIN)) - throw effect_exception{AL_INVALID_VALUE, "Distortion gain out of range"}; - props->Distortion.Gain = val; - break; - - case AL_DISTORTION_LOWPASS_CUTOFF: - if(!(val >= AL_DISTORTION_MIN_LOWPASS_CUTOFF && val <= AL_DISTORTION_MAX_LOWPASS_CUTOFF)) - throw effect_exception{AL_INVALID_VALUE, "Distortion low-pass cutoff out of range"}; - props->Distortion.LowpassCutoff = val; - break; - - case AL_DISTORTION_EQCENTER: - if(!(val >= AL_DISTORTION_MIN_EQCENTER && val <= AL_DISTORTION_MAX_EQCENTER)) - throw effect_exception{AL_INVALID_VALUE, "Distortion EQ center out of range"}; - props->Distortion.EQCenter = val; - break; - - case AL_DISTORTION_EQBANDWIDTH: - if(!(val >= AL_DISTORTION_MIN_EQBANDWIDTH && val <= AL_DISTORTION_MAX_EQBANDWIDTH)) - throw effect_exception{AL_INVALID_VALUE, "Distortion EQ bandwidth out of range"}; - props->Distortion.EQBandwidth = val; - break; - - default: - throw effect_exception{AL_INVALID_ENUM, "Invalid distortion float property 0x%04x", param}; - } -} -void Distortion_setParamfv(EffectProps *props, ALenum param, const float *vals) -{ Distortion_setParamf(props, param, vals[0]); } - -void Distortion_getParami(const EffectProps*, ALenum param, int*) -{ throw effect_exception{AL_INVALID_ENUM, "Invalid distortion integer property 0x%04x", param}; } -void Distortion_getParamiv(const EffectProps*, ALenum param, int*) -{ - throw effect_exception{AL_INVALID_ENUM, "Invalid distortion integer-vector property 0x%04x", - param}; -} -void Distortion_getParamf(const EffectProps *props, ALenum param, float *val) -{ - switch(param) - { - case AL_DISTORTION_EDGE: - *val = props->Distortion.Edge; - break; - - case AL_DISTORTION_GAIN: - *val = props->Distortion.Gain; - break; - - case AL_DISTORTION_LOWPASS_CUTOFF: - *val = props->Distortion.LowpassCutoff; - break; - - case AL_DISTORTION_EQCENTER: - *val = props->Distortion.EQCenter; - break; - - case AL_DISTORTION_EQBANDWIDTH: - *val = props->Distortion.EQBandwidth; - break; - - default: - throw effect_exception{AL_INVALID_ENUM, "Invalid distortion float property 0x%04x", param}; - } -} -void Distortion_getParamfv(const EffectProps *props, ALenum param, float *vals) -{ Distortion_getParamf(props, param, vals); } - -EffectProps genDefaultProps() noexcept -{ - EffectProps props{}; - props.Distortion.Edge = AL_DISTORTION_DEFAULT_EDGE; - props.Distortion.Gain = AL_DISTORTION_DEFAULT_GAIN; - props.Distortion.LowpassCutoff = AL_DISTORTION_DEFAULT_LOWPASS_CUTOFF; - props.Distortion.EQCenter = AL_DISTORTION_DEFAULT_EQCENTER; - props.Distortion.EQBandwidth = AL_DISTORTION_DEFAULT_EQBANDWIDTH; - return props; -} - -} // namespace - -DEFINE_ALEFFECT_VTABLE(Distortion); - -const EffectProps DistortionEffectProps{genDefaultProps()}; diff --git a/al/effects/echo.cpp b/al/effects/echo.cpp deleted file mode 100644 index 79a60521..00000000 --- a/al/effects/echo.cpp +++ /dev/null @@ -1,111 +0,0 @@ - -#include "config.h" - -#include "AL/al.h" -#include "AL/efx.h" - -#include "effects.h" -#include "effects/base.h" - - -namespace { - -static_assert(EchoMaxDelay >= AL_ECHO_MAX_DELAY, "Echo max delay too short"); -static_assert(EchoMaxLRDelay >= AL_ECHO_MAX_LRDELAY, "Echo max left-right delay too short"); - -void Echo_setParami(EffectProps*, ALenum param, int) -{ throw effect_exception{AL_INVALID_ENUM, "Invalid echo integer property 0x%04x", param}; } -void Echo_setParamiv(EffectProps*, ALenum param, const int*) -{ throw effect_exception{AL_INVALID_ENUM, "Invalid echo integer-vector property 0x%04x", param}; } -void Echo_setParamf(EffectProps *props, ALenum param, float val) -{ - switch(param) - { - case AL_ECHO_DELAY: - if(!(val >= AL_ECHO_MIN_DELAY && val <= AL_ECHO_MAX_DELAY)) - throw effect_exception{AL_INVALID_VALUE, "Echo delay out of range"}; - props->Echo.Delay = val; - break; - - case AL_ECHO_LRDELAY: - if(!(val >= AL_ECHO_MIN_LRDELAY && val <= AL_ECHO_MAX_LRDELAY)) - throw effect_exception{AL_INVALID_VALUE, "Echo LR delay out of range"}; - props->Echo.LRDelay = val; - break; - - case AL_ECHO_DAMPING: - if(!(val >= AL_ECHO_MIN_DAMPING && val <= AL_ECHO_MAX_DAMPING)) - throw effect_exception{AL_INVALID_VALUE, "Echo damping out of range"}; - props->Echo.Damping = val; - break; - - case AL_ECHO_FEEDBACK: - if(!(val >= AL_ECHO_MIN_FEEDBACK && val <= AL_ECHO_MAX_FEEDBACK)) - throw effect_exception{AL_INVALID_VALUE, "Echo feedback out of range"}; - props->Echo.Feedback = val; - break; - - case AL_ECHO_SPREAD: - if(!(val >= AL_ECHO_MIN_SPREAD && val <= AL_ECHO_MAX_SPREAD)) - throw effect_exception{AL_INVALID_VALUE, "Echo spread out of range"}; - props->Echo.Spread = val; - break; - - default: - throw effect_exception{AL_INVALID_ENUM, "Invalid echo float property 0x%04x", param}; - } -} -void Echo_setParamfv(EffectProps *props, ALenum param, const float *vals) -{ Echo_setParamf(props, param, vals[0]); } - -void Echo_getParami(const EffectProps*, ALenum param, int*) -{ throw effect_exception{AL_INVALID_ENUM, "Invalid echo integer property 0x%04x", param}; } -void Echo_getParamiv(const EffectProps*, ALenum param, int*) -{ throw effect_exception{AL_INVALID_ENUM, "Invalid echo integer-vector property 0x%04x", param}; } -void Echo_getParamf(const EffectProps *props, ALenum param, float *val) -{ - switch(param) - { - case AL_ECHO_DELAY: - *val = props->Echo.Delay; - break; - - case AL_ECHO_LRDELAY: - *val = props->Echo.LRDelay; - break; - - case AL_ECHO_DAMPING: - *val = props->Echo.Damping; - break; - - case AL_ECHO_FEEDBACK: - *val = props->Echo.Feedback; - break; - - case AL_ECHO_SPREAD: - *val = props->Echo.Spread; - break; - - default: - throw effect_exception{AL_INVALID_ENUM, "Invalid echo float property 0x%04x", param}; - } -} -void Echo_getParamfv(const EffectProps *props, ALenum param, float *vals) -{ Echo_getParamf(props, param, vals); } - -EffectProps genDefaultProps() noexcept -{ - EffectProps props{}; - props.Echo.Delay = AL_ECHO_DEFAULT_DELAY; - props.Echo.LRDelay = AL_ECHO_DEFAULT_LRDELAY; - props.Echo.Damping = AL_ECHO_DEFAULT_DAMPING; - props.Echo.Feedback = AL_ECHO_DEFAULT_FEEDBACK; - props.Echo.Spread = AL_ECHO_DEFAULT_SPREAD; - return props; -} - -} // namespace - -DEFINE_ALEFFECT_VTABLE(Echo); - -const EffectProps EchoEffectProps{genDefaultProps()}; diff --git a/al/effects/effects.h b/al/effects/effects.h deleted file mode 100644 index d6c88c4f..00000000 --- a/al/effects/effects.h +++ /dev/null @@ -1,79 +0,0 @@ -#ifndef AL_EFFECTS_EFFECTS_H -#define AL_EFFECTS_EFFECTS_H - -#include "AL/al.h" - -#include "core/except.h" - -union EffectProps; - - -class effect_exception final : public al::base_exception { - ALenum mErrorCode; - -public: - [[gnu::format(printf, 3, 4)]] - effect_exception(ALenum code, const char *msg, ...); - - ALenum errorCode() const noexcept { return mErrorCode; } -}; - - -struct EffectVtable { - void (*const setParami)(EffectProps *props, ALenum param, int val); - void (*const setParamiv)(EffectProps *props, ALenum param, const int *vals); - void (*const setParamf)(EffectProps *props, ALenum param, float val); - void (*const setParamfv)(EffectProps *props, ALenum param, const float *vals); - - void (*const getParami)(const EffectProps *props, ALenum param, int *val); - void (*const getParamiv)(const EffectProps *props, ALenum param, int *vals); - void (*const getParamf)(const EffectProps *props, ALenum param, float *val); - void (*const getParamfv)(const EffectProps *props, ALenum param, float *vals); -}; - -#define DEFINE_ALEFFECT_VTABLE(T) \ -const EffectVtable T##EffectVtable = { \ - T##_setParami, T##_setParamiv, \ - T##_setParamf, T##_setParamfv, \ - T##_getParami, T##_getParamiv, \ - T##_getParamf, T##_getParamfv, \ -} - - -/* Default properties for the given effect types. */ -extern const EffectProps NullEffectProps; -extern const EffectProps ReverbEffectProps; -extern const EffectProps StdReverbEffectProps; -extern const EffectProps AutowahEffectProps; -extern const EffectProps ChorusEffectProps; -extern const EffectProps CompressorEffectProps; -extern const EffectProps DistortionEffectProps; -extern const EffectProps EchoEffectProps; -extern const EffectProps EqualizerEffectProps; -extern const EffectProps FlangerEffectProps; -extern const EffectProps FshifterEffectProps; -extern const EffectProps ModulatorEffectProps; -extern const EffectProps PshifterEffectProps; -extern const EffectProps VmorpherEffectProps; -extern const EffectProps DedicatedEffectProps; -extern const EffectProps ConvolutionEffectProps; - -/* Vtables to get/set properties for the given effect types. */ -extern const EffectVtable NullEffectVtable; -extern const EffectVtable ReverbEffectVtable; -extern const EffectVtable StdReverbEffectVtable; -extern const EffectVtable AutowahEffectVtable; -extern const EffectVtable ChorusEffectVtable; -extern const EffectVtable CompressorEffectVtable; -extern const EffectVtable DistortionEffectVtable; -extern const EffectVtable EchoEffectVtable; -extern const EffectVtable EqualizerEffectVtable; -extern const EffectVtable FlangerEffectVtable; -extern const EffectVtable FshifterEffectVtable; -extern const EffectVtable ModulatorEffectVtable; -extern const EffectVtable PshifterEffectVtable; -extern const EffectVtable VmorpherEffectVtable; -extern const EffectVtable DedicatedEffectVtable; -extern const EffectVtable ConvolutionEffectVtable; - -#endif /* AL_EFFECTS_EFFECTS_H */ diff --git a/al/effects/equalizer.cpp b/al/effects/equalizer.cpp deleted file mode 100644 index 3a7c0a8f..00000000 --- a/al/effects/equalizer.cpp +++ /dev/null @@ -1,169 +0,0 @@ - -#include "config.h" - -#include "AL/al.h" -#include "AL/efx.h" - -#include "effects.h" -#include "effects/base.h" - - -namespace { - -void Equalizer_setParami(EffectProps*, ALenum param, int) -{ throw effect_exception{AL_INVALID_ENUM, "Invalid equalizer integer property 0x%04x", param}; } -void Equalizer_setParamiv(EffectProps*, ALenum param, const int*) -{ - throw effect_exception{AL_INVALID_ENUM, "Invalid equalizer integer-vector property 0x%04x", - param}; -} -void Equalizer_setParamf(EffectProps *props, ALenum param, float val) -{ - switch(param) - { - case AL_EQUALIZER_LOW_GAIN: - if(!(val >= AL_EQUALIZER_MIN_LOW_GAIN && val <= AL_EQUALIZER_MAX_LOW_GAIN)) - throw effect_exception{AL_INVALID_VALUE, "Equalizer low-band gain out of range"}; - props->Equalizer.LowGain = val; - break; - - case AL_EQUALIZER_LOW_CUTOFF: - if(!(val >= AL_EQUALIZER_MIN_LOW_CUTOFF && val <= AL_EQUALIZER_MAX_LOW_CUTOFF)) - throw effect_exception{AL_INVALID_VALUE, "Equalizer low-band cutoff out of range"}; - props->Equalizer.LowCutoff = val; - break; - - case AL_EQUALIZER_MID1_GAIN: - if(!(val >= AL_EQUALIZER_MIN_MID1_GAIN && val <= AL_EQUALIZER_MAX_MID1_GAIN)) - throw effect_exception{AL_INVALID_VALUE, "Equalizer mid1-band gain out of range"}; - props->Equalizer.Mid1Gain = val; - break; - - case AL_EQUALIZER_MID1_CENTER: - if(!(val >= AL_EQUALIZER_MIN_MID1_CENTER && val <= AL_EQUALIZER_MAX_MID1_CENTER)) - throw effect_exception{AL_INVALID_VALUE, "Equalizer mid1-band center out of range"}; - props->Equalizer.Mid1Center = val; - break; - - case AL_EQUALIZER_MID1_WIDTH: - if(!(val >= AL_EQUALIZER_MIN_MID1_WIDTH && val <= AL_EQUALIZER_MAX_MID1_WIDTH)) - throw effect_exception{AL_INVALID_VALUE, "Equalizer mid1-band width out of range"}; - props->Equalizer.Mid1Width = val; - break; - - case AL_EQUALIZER_MID2_GAIN: - if(!(val >= AL_EQUALIZER_MIN_MID2_GAIN && val <= AL_EQUALIZER_MAX_MID2_GAIN)) - throw effect_exception{AL_INVALID_VALUE, "Equalizer mid2-band gain out of range"}; - props->Equalizer.Mid2Gain = val; - break; - - case AL_EQUALIZER_MID2_CENTER: - if(!(val >= AL_EQUALIZER_MIN_MID2_CENTER && val <= AL_EQUALIZER_MAX_MID2_CENTER)) - throw effect_exception{AL_INVALID_VALUE, "Equalizer mid2-band center out of range"}; - props->Equalizer.Mid2Center = val; - break; - - case AL_EQUALIZER_MID2_WIDTH: - if(!(val >= AL_EQUALIZER_MIN_MID2_WIDTH && val <= AL_EQUALIZER_MAX_MID2_WIDTH)) - throw effect_exception{AL_INVALID_VALUE, "Equalizer mid2-band width out of range"}; - props->Equalizer.Mid2Width = val; - break; - - case AL_EQUALIZER_HIGH_GAIN: - if(!(val >= AL_EQUALIZER_MIN_HIGH_GAIN && val <= AL_EQUALIZER_MAX_HIGH_GAIN)) - throw effect_exception{AL_INVALID_VALUE, "Equalizer high-band gain out of range"}; - props->Equalizer.HighGain = val; - break; - - case AL_EQUALIZER_HIGH_CUTOFF: - if(!(val >= AL_EQUALIZER_MIN_HIGH_CUTOFF && val <= AL_EQUALIZER_MAX_HIGH_CUTOFF)) - throw effect_exception{AL_INVALID_VALUE, "Equalizer high-band cutoff out of range"}; - props->Equalizer.HighCutoff = val; - break; - - default: - throw effect_exception{AL_INVALID_ENUM, "Invalid equalizer float property 0x%04x", param}; - } -} -void Equalizer_setParamfv(EffectProps *props, ALenum param, const float *vals) -{ Equalizer_setParamf(props, param, vals[0]); } - -void Equalizer_getParami(const EffectProps*, ALenum param, int*) -{ throw effect_exception{AL_INVALID_ENUM, "Invalid equalizer integer property 0x%04x", param}; } -void Equalizer_getParamiv(const EffectProps*, ALenum param, int*) -{ - throw effect_exception{AL_INVALID_ENUM, "Invalid equalizer integer-vector property 0x%04x", - param}; -} -void Equalizer_getParamf(const EffectProps *props, ALenum param, float *val) -{ - switch(param) - { - case AL_EQUALIZER_LOW_GAIN: - *val = props->Equalizer.LowGain; - break; - - case AL_EQUALIZER_LOW_CUTOFF: - *val = props->Equalizer.LowCutoff; - break; - - case AL_EQUALIZER_MID1_GAIN: - *val = props->Equalizer.Mid1Gain; - break; - - case AL_EQUALIZER_MID1_CENTER: - *val = props->Equalizer.Mid1Center; - break; - - case AL_EQUALIZER_MID1_WIDTH: - *val = props->Equalizer.Mid1Width; - break; - - case AL_EQUALIZER_MID2_GAIN: - *val = props->Equalizer.Mid2Gain; - break; - - case AL_EQUALIZER_MID2_CENTER: - *val = props->Equalizer.Mid2Center; - break; - - case AL_EQUALIZER_MID2_WIDTH: - *val = props->Equalizer.Mid2Width; - break; - - case AL_EQUALIZER_HIGH_GAIN: - *val = props->Equalizer.HighGain; - break; - - case AL_EQUALIZER_HIGH_CUTOFF: - *val = props->Equalizer.HighCutoff; - break; - - default: - throw effect_exception{AL_INVALID_ENUM, "Invalid equalizer float property 0x%04x", param}; - } -} -void Equalizer_getParamfv(const EffectProps *props, ALenum param, float *vals) -{ Equalizer_getParamf(props, param, vals); } - -EffectProps genDefaultProps() noexcept -{ - EffectProps props{}; - props.Equalizer.LowCutoff = AL_EQUALIZER_DEFAULT_LOW_CUTOFF; - props.Equalizer.LowGain = AL_EQUALIZER_DEFAULT_LOW_GAIN; - props.Equalizer.Mid1Center = AL_EQUALIZER_DEFAULT_MID1_CENTER; - props.Equalizer.Mid1Gain = AL_EQUALIZER_DEFAULT_MID1_GAIN; - props.Equalizer.Mid1Width = AL_EQUALIZER_DEFAULT_MID1_WIDTH; - props.Equalizer.Mid2Center = AL_EQUALIZER_DEFAULT_MID2_CENTER; - props.Equalizer.Mid2Gain = AL_EQUALIZER_DEFAULT_MID2_GAIN; - props.Equalizer.Mid2Width = AL_EQUALIZER_DEFAULT_MID2_WIDTH; - props.Equalizer.HighCutoff = AL_EQUALIZER_DEFAULT_HIGH_CUTOFF; - props.Equalizer.HighGain = AL_EQUALIZER_DEFAULT_HIGH_GAIN; - return props; -} - -} // namespace - -DEFINE_ALEFFECT_VTABLE(Equalizer); - -const EffectProps EqualizerEffectProps{genDefaultProps()}; diff --git a/al/effects/fshifter.cpp b/al/effects/fshifter.cpp deleted file mode 100644 index 444b0260..00000000 --- a/al/effects/fshifter.cpp +++ /dev/null @@ -1,128 +0,0 @@ - -#include "config.h" - -#include "AL/al.h" -#include "AL/efx.h" - -#include "aloptional.h" -#include "effects.h" -#include "effects/base.h" - - -namespace { - -al::optional DirectionFromEmum(ALenum value) -{ - switch(value) - { - case AL_FREQUENCY_SHIFTER_DIRECTION_DOWN: return al::make_optional(FShifterDirection::Down); - case AL_FREQUENCY_SHIFTER_DIRECTION_UP: return al::make_optional(FShifterDirection::Up); - case AL_FREQUENCY_SHIFTER_DIRECTION_OFF: return al::make_optional(FShifterDirection::Off); - } - return al::nullopt; -} -ALenum EnumFromDirection(FShifterDirection dir) -{ - switch(dir) - { - case FShifterDirection::Down: return AL_FREQUENCY_SHIFTER_DIRECTION_DOWN; - case FShifterDirection::Up: return AL_FREQUENCY_SHIFTER_DIRECTION_UP; - case FShifterDirection::Off: return AL_FREQUENCY_SHIFTER_DIRECTION_OFF; - } - throw std::runtime_error{"Invalid direction: "+std::to_string(static_cast(dir))}; -} - -void Fshifter_setParamf(EffectProps *props, ALenum param, float val) -{ - switch(param) - { - case AL_FREQUENCY_SHIFTER_FREQUENCY: - if(!(val >= AL_FREQUENCY_SHIFTER_MIN_FREQUENCY && val <= AL_FREQUENCY_SHIFTER_MAX_FREQUENCY)) - throw effect_exception{AL_INVALID_VALUE, "Frequency shifter frequency out of range"}; - props->Fshifter.Frequency = val; - break; - - default: - throw effect_exception{AL_INVALID_ENUM, "Invalid frequency shifter float property 0x%04x", - param}; - } -} -void Fshifter_setParamfv(EffectProps *props, ALenum param, const float *vals) -{ Fshifter_setParamf(props, param, vals[0]); } - -void Fshifter_setParami(EffectProps *props, ALenum param, int val) -{ - switch(param) - { - case AL_FREQUENCY_SHIFTER_LEFT_DIRECTION: - if(auto diropt = DirectionFromEmum(val)) - props->Fshifter.LeftDirection = *diropt; - else - throw effect_exception{AL_INVALID_VALUE, - "Unsupported frequency shifter left direction: 0x%04x", val}; - break; - - case AL_FREQUENCY_SHIFTER_RIGHT_DIRECTION: - if(auto diropt = DirectionFromEmum(val)) - props->Fshifter.RightDirection = *diropt; - else - throw effect_exception{AL_INVALID_VALUE, - "Unsupported frequency shifter right direction: 0x%04x", val}; - break; - - default: - throw effect_exception{AL_INVALID_ENUM, - "Invalid frequency shifter integer property 0x%04x", param}; - } -} -void Fshifter_setParamiv(EffectProps *props, ALenum param, const int *vals) -{ Fshifter_setParami(props, param, vals[0]); } - -void Fshifter_getParami(const EffectProps *props, ALenum param, int *val) -{ - switch(param) - { - case AL_FREQUENCY_SHIFTER_LEFT_DIRECTION: - *val = EnumFromDirection(props->Fshifter.LeftDirection); - break; - case AL_FREQUENCY_SHIFTER_RIGHT_DIRECTION: - *val = EnumFromDirection(props->Fshifter.RightDirection); - break; - default: - throw effect_exception{AL_INVALID_ENUM, - "Invalid frequency shifter integer property 0x%04x", param}; - } -} -void Fshifter_getParamiv(const EffectProps *props, ALenum param, int *vals) -{ Fshifter_getParami(props, param, vals); } - -void Fshifter_getParamf(const EffectProps *props, ALenum param, float *val) -{ - switch(param) - { - case AL_FREQUENCY_SHIFTER_FREQUENCY: - *val = props->Fshifter.Frequency; - break; - - default: - throw effect_exception{AL_INVALID_ENUM, "Invalid frequency shifter float property 0x%04x", - param}; - } -} -void Fshifter_getParamfv(const EffectProps *props, ALenum param, float *vals) -{ Fshifter_getParamf(props, param, vals); } - -EffectProps genDefaultProps() noexcept -{ - EffectProps props{}; - props.Fshifter.Frequency = AL_FREQUENCY_SHIFTER_DEFAULT_FREQUENCY; - props.Fshifter.LeftDirection = *DirectionFromEmum(AL_FREQUENCY_SHIFTER_DEFAULT_LEFT_DIRECTION); - props.Fshifter.RightDirection = *DirectionFromEmum(AL_FREQUENCY_SHIFTER_DEFAULT_RIGHT_DIRECTION); - return props; -} - -} // namespace - -DEFINE_ALEFFECT_VTABLE(Fshifter); - -const EffectProps FshifterEffectProps{genDefaultProps()}; diff --git a/al/effects/modulator.cpp b/al/effects/modulator.cpp deleted file mode 100644 index 89dcc209..00000000 --- a/al/effects/modulator.cpp +++ /dev/null @@ -1,134 +0,0 @@ - -#include "config.h" - -#include "AL/al.h" -#include "AL/efx.h" - -#include "aloptional.h" -#include "effects.h" -#include "effects/base.h" - - -namespace { - -al::optional WaveformFromEmum(ALenum value) -{ - switch(value) - { - case AL_RING_MODULATOR_SINUSOID: return al::make_optional(ModulatorWaveform::Sinusoid); - case AL_RING_MODULATOR_SAWTOOTH: return al::make_optional(ModulatorWaveform::Sawtooth); - case AL_RING_MODULATOR_SQUARE: return al::make_optional(ModulatorWaveform::Square); - } - return al::nullopt; -} -ALenum EnumFromWaveform(ModulatorWaveform type) -{ - switch(type) - { - case ModulatorWaveform::Sinusoid: return AL_RING_MODULATOR_SINUSOID; - case ModulatorWaveform::Sawtooth: return AL_RING_MODULATOR_SAWTOOTH; - case ModulatorWaveform::Square: return AL_RING_MODULATOR_SQUARE; - } - throw std::runtime_error{"Invalid modulator waveform: " + - std::to_string(static_cast(type))}; -} - -void Modulator_setParamf(EffectProps *props, ALenum param, float val) -{ - switch(param) - { - case AL_RING_MODULATOR_FREQUENCY: - if(!(val >= AL_RING_MODULATOR_MIN_FREQUENCY && val <= AL_RING_MODULATOR_MAX_FREQUENCY)) - throw effect_exception{AL_INVALID_VALUE, "Modulator frequency out of range: %f", val}; - props->Modulator.Frequency = val; - break; - - case AL_RING_MODULATOR_HIGHPASS_CUTOFF: - if(!(val >= AL_RING_MODULATOR_MIN_HIGHPASS_CUTOFF && val <= AL_RING_MODULATOR_MAX_HIGHPASS_CUTOFF)) - throw effect_exception{AL_INVALID_VALUE, "Modulator high-pass cutoff out of range: %f", val}; - props->Modulator.HighPassCutoff = val; - break; - - default: - throw effect_exception{AL_INVALID_ENUM, "Invalid modulator float property 0x%04x", param}; - } -} -void Modulator_setParamfv(EffectProps *props, ALenum param, const float *vals) -{ Modulator_setParamf(props, param, vals[0]); } -void Modulator_setParami(EffectProps *props, ALenum param, int val) -{ - switch(param) - { - case AL_RING_MODULATOR_FREQUENCY: - case AL_RING_MODULATOR_HIGHPASS_CUTOFF: - Modulator_setParamf(props, param, static_cast(val)); - break; - - case AL_RING_MODULATOR_WAVEFORM: - if(auto formopt = WaveformFromEmum(val)) - props->Modulator.Waveform = *formopt; - else - throw effect_exception{AL_INVALID_VALUE, "Invalid modulator waveform: 0x%04x", val}; - break; - - default: - throw effect_exception{AL_INVALID_ENUM, "Invalid modulator integer property 0x%04x", - param}; - } -} -void Modulator_setParamiv(EffectProps *props, ALenum param, const int *vals) -{ Modulator_setParami(props, param, vals[0]); } - -void Modulator_getParami(const EffectProps *props, ALenum param, int *val) -{ - switch(param) - { - case AL_RING_MODULATOR_FREQUENCY: - *val = static_cast(props->Modulator.Frequency); - break; - case AL_RING_MODULATOR_HIGHPASS_CUTOFF: - *val = static_cast(props->Modulator.HighPassCutoff); - break; - case AL_RING_MODULATOR_WAVEFORM: - *val = EnumFromWaveform(props->Modulator.Waveform); - break; - - default: - throw effect_exception{AL_INVALID_ENUM, "Invalid modulator integer property 0x%04x", - param}; - } -} -void Modulator_getParamiv(const EffectProps *props, ALenum param, int *vals) -{ Modulator_getParami(props, param, vals); } -void Modulator_getParamf(const EffectProps *props, ALenum param, float *val) -{ - switch(param) - { - case AL_RING_MODULATOR_FREQUENCY: - *val = props->Modulator.Frequency; - break; - case AL_RING_MODULATOR_HIGHPASS_CUTOFF: - *val = props->Modulator.HighPassCutoff; - break; - - default: - throw effect_exception{AL_INVALID_ENUM, "Invalid modulator float property 0x%04x", param}; - } -} -void Modulator_getParamfv(const EffectProps *props, ALenum param, float *vals) -{ Modulator_getParamf(props, param, vals); } - -EffectProps genDefaultProps() noexcept -{ - EffectProps props{}; - props.Modulator.Frequency = AL_RING_MODULATOR_DEFAULT_FREQUENCY; - props.Modulator.HighPassCutoff = AL_RING_MODULATOR_DEFAULT_HIGHPASS_CUTOFF; - props.Modulator.Waveform = *WaveformFromEmum(AL_RING_MODULATOR_DEFAULT_WAVEFORM); - return props; -} - -} // namespace - -DEFINE_ALEFFECT_VTABLE(Modulator); - -const EffectProps ModulatorEffectProps{genDefaultProps()}; diff --git a/al/effects/null.cpp b/al/effects/null.cpp deleted file mode 100644 index 0ac5278f..00000000 --- a/al/effects/null.cpp +++ /dev/null @@ -1,93 +0,0 @@ - -#include "config.h" - -#include "AL/al.h" -#include "AL/efx.h" - -#include "effects.h" -#include "effects/base.h" - - -namespace { - -void Null_setParami(EffectProps* /*props*/, ALenum param, int /*val*/) -{ - switch(param) - { - default: - throw effect_exception{AL_INVALID_ENUM, "Invalid null effect integer property 0x%04x", - param}; - } -} -void Null_setParamiv(EffectProps *props, ALenum param, const int *vals) -{ - switch(param) - { - default: - Null_setParami(props, param, vals[0]); - } -} -void Null_setParamf(EffectProps* /*props*/, ALenum param, float /*val*/) -{ - switch(param) - { - default: - throw effect_exception{AL_INVALID_ENUM, "Invalid null effect float property 0x%04x", - param}; - } -} -void Null_setParamfv(EffectProps *props, ALenum param, const float *vals) -{ - switch(param) - { - default: - Null_setParamf(props, param, vals[0]); - } -} - -void Null_getParami(const EffectProps* /*props*/, ALenum param, int* /*val*/) -{ - switch(param) - { - default: - throw effect_exception{AL_INVALID_ENUM, "Invalid null effect integer property 0x%04x", - param}; - } -} -void Null_getParamiv(const EffectProps *props, ALenum param, int *vals) -{ - switch(param) - { - default: - Null_getParami(props, param, vals); - } -} -void Null_getParamf(const EffectProps* /*props*/, ALenum param, float* /*val*/) -{ - switch(param) - { - default: - throw effect_exception{AL_INVALID_ENUM, "Invalid null effect float property 0x%04x", - param}; - } -} -void Null_getParamfv(const EffectProps *props, ALenum param, float *vals) -{ - switch(param) - { - default: - Null_getParamf(props, param, vals); - } -} - -EffectProps genDefaultProps() noexcept -{ - EffectProps props{}; - return props; -} - -} // namespace - -DEFINE_ALEFFECT_VTABLE(Null); - -const EffectProps NullEffectProps{genDefaultProps()}; diff --git a/al/effects/pshifter.cpp b/al/effects/pshifter.cpp deleted file mode 100644 index e6b0b3b0..00000000 --- a/al/effects/pshifter.cpp +++ /dev/null @@ -1,84 +0,0 @@ - -#include "config.h" - -#include "AL/al.h" -#include "AL/efx.h" - -#include "effects.h" -#include "effects/base.h" - - -namespace { - -void Pshifter_setParamf(EffectProps*, ALenum param, float) -{ throw effect_exception{AL_INVALID_ENUM, "Invalid pitch shifter float property 0x%04x", param}; } -void Pshifter_setParamfv(EffectProps*, ALenum param, const float*) -{ - throw effect_exception{AL_INVALID_ENUM, "Invalid pitch shifter float-vector property 0x%04x", - param}; -} - -void Pshifter_setParami(EffectProps *props, ALenum param, int val) -{ - switch(param) - { - case AL_PITCH_SHIFTER_COARSE_TUNE: - if(!(val >= AL_PITCH_SHIFTER_MIN_COARSE_TUNE && val <= AL_PITCH_SHIFTER_MAX_COARSE_TUNE)) - throw effect_exception{AL_INVALID_VALUE, "Pitch shifter coarse tune out of range"}; - props->Pshifter.CoarseTune = val; - break; - - case AL_PITCH_SHIFTER_FINE_TUNE: - if(!(val >= AL_PITCH_SHIFTER_MIN_FINE_TUNE && val <= AL_PITCH_SHIFTER_MAX_FINE_TUNE)) - throw effect_exception{AL_INVALID_VALUE, "Pitch shifter fine tune out of range"}; - props->Pshifter.FineTune = val; - break; - - default: - throw effect_exception{AL_INVALID_ENUM, "Invalid pitch shifter integer property 0x%04x", - param}; - } -} -void Pshifter_setParamiv(EffectProps *props, ALenum param, const int *vals) -{ Pshifter_setParami(props, param, vals[0]); } - -void Pshifter_getParami(const EffectProps *props, ALenum param, int *val) -{ - switch(param) - { - case AL_PITCH_SHIFTER_COARSE_TUNE: - *val = props->Pshifter.CoarseTune; - break; - case AL_PITCH_SHIFTER_FINE_TUNE: - *val = props->Pshifter.FineTune; - break; - - default: - throw effect_exception{AL_INVALID_ENUM, "Invalid pitch shifter integer property 0x%04x", - param}; - } -} -void Pshifter_getParamiv(const EffectProps *props, ALenum param, int *vals) -{ Pshifter_getParami(props, param, vals); } - -void Pshifter_getParamf(const EffectProps*, ALenum param, float*) -{ throw effect_exception{AL_INVALID_ENUM, "Invalid pitch shifter float property 0x%04x", param}; } -void Pshifter_getParamfv(const EffectProps*, ALenum param, float*) -{ - throw effect_exception{AL_INVALID_ENUM, "Invalid pitch shifter float vector-property 0x%04x", - param}; -} - -EffectProps genDefaultProps() noexcept -{ - EffectProps props{}; - props.Pshifter.CoarseTune = AL_PITCH_SHIFTER_DEFAULT_COARSE_TUNE; - props.Pshifter.FineTune = AL_PITCH_SHIFTER_DEFAULT_FINE_TUNE; - return props; -} - -} // namespace - -DEFINE_ALEFFECT_VTABLE(Pshifter); - -const EffectProps PshifterEffectProps{genDefaultProps()}; diff --git a/al/effects/reverb.cpp b/al/effects/reverb.cpp deleted file mode 100644 index caa0c81e..00000000 --- a/al/effects/reverb.cpp +++ /dev/null @@ -1,556 +0,0 @@ - -#include "config.h" - -#include - -#include "AL/al.h" -#include "AL/efx.h" - -#include "effects.h" -#include "effects/base.h" - - -namespace { - -void Reverb_setParami(EffectProps *props, ALenum param, int val) -{ - switch(param) - { - case AL_EAXREVERB_DECAY_HFLIMIT: - if(!(val >= AL_EAXREVERB_MIN_DECAY_HFLIMIT && val <= AL_EAXREVERB_MAX_DECAY_HFLIMIT)) - throw effect_exception{AL_INVALID_VALUE, "EAX Reverb decay hflimit out of range"}; - props->Reverb.DecayHFLimit = val != AL_FALSE; - break; - - default: - throw effect_exception{AL_INVALID_ENUM, "Invalid EAX reverb integer property 0x%04x", - param}; - } -} -void Reverb_setParamiv(EffectProps *props, ALenum param, const int *vals) -{ Reverb_setParami(props, param, vals[0]); } -void Reverb_setParamf(EffectProps *props, ALenum param, float val) -{ - switch(param) - { - case AL_EAXREVERB_DENSITY: - if(!(val >= AL_EAXREVERB_MIN_DENSITY && val <= AL_EAXREVERB_MAX_DENSITY)) - throw effect_exception{AL_INVALID_VALUE, "EAX Reverb density out of range"}; - props->Reverb.Density = val; - break; - - case AL_EAXREVERB_DIFFUSION: - if(!(val >= AL_EAXREVERB_MIN_DIFFUSION && val <= AL_EAXREVERB_MAX_DIFFUSION)) - throw effect_exception{AL_INVALID_VALUE, "EAX Reverb diffusion out of range"}; - props->Reverb.Diffusion = val; - break; - - case AL_EAXREVERB_GAIN: - if(!(val >= AL_EAXREVERB_MIN_GAIN && val <= AL_EAXREVERB_MAX_GAIN)) - throw effect_exception{AL_INVALID_VALUE, "EAX Reverb gain out of range"}; - props->Reverb.Gain = val; - break; - - case AL_EAXREVERB_GAINHF: - if(!(val >= AL_EAXREVERB_MIN_GAINHF && val <= AL_EAXREVERB_MAX_GAINHF)) - throw effect_exception{AL_INVALID_VALUE, "EAX Reverb gainhf out of range"}; - props->Reverb.GainHF = val; - break; - - case AL_EAXREVERB_GAINLF: - if(!(val >= AL_EAXREVERB_MIN_GAINLF && val <= AL_EAXREVERB_MAX_GAINLF)) - throw effect_exception{AL_INVALID_VALUE, "EAX Reverb gainlf out of range"}; - props->Reverb.GainLF = val; - break; - - case AL_EAXREVERB_DECAY_TIME: - if(!(val >= AL_EAXREVERB_MIN_DECAY_TIME && val <= AL_EAXREVERB_MAX_DECAY_TIME)) - throw effect_exception{AL_INVALID_VALUE, "EAX Reverb decay time out of range"}; - props->Reverb.DecayTime = val; - break; - - case AL_EAXREVERB_DECAY_HFRATIO: - if(!(val >= AL_EAXREVERB_MIN_DECAY_HFRATIO && val <= AL_EAXREVERB_MAX_DECAY_HFRATIO)) - throw effect_exception{AL_INVALID_VALUE, "EAX Reverb decay hfratio out of range"}; - props->Reverb.DecayHFRatio = val; - break; - - case AL_EAXREVERB_DECAY_LFRATIO: - if(!(val >= AL_EAXREVERB_MIN_DECAY_LFRATIO && val <= AL_EAXREVERB_MAX_DECAY_LFRATIO)) - throw effect_exception{AL_INVALID_VALUE, "EAX Reverb decay lfratio out of range"}; - props->Reverb.DecayLFRatio = val; - break; - - case AL_EAXREVERB_REFLECTIONS_GAIN: - if(!(val >= AL_EAXREVERB_MIN_REFLECTIONS_GAIN && val <= AL_EAXREVERB_MAX_REFLECTIONS_GAIN)) - throw effect_exception{AL_INVALID_VALUE, "EAX Reverb reflections gain out of range"}; - props->Reverb.ReflectionsGain = val; - break; - - case AL_EAXREVERB_REFLECTIONS_DELAY: - if(!(val >= AL_EAXREVERB_MIN_REFLECTIONS_DELAY && val <= AL_EAXREVERB_MAX_REFLECTIONS_DELAY)) - throw effect_exception{AL_INVALID_VALUE, "EAX Reverb reflections delay out of range"}; - props->Reverb.ReflectionsDelay = val; - break; - - case AL_EAXREVERB_LATE_REVERB_GAIN: - if(!(val >= AL_EAXREVERB_MIN_LATE_REVERB_GAIN && val <= AL_EAXREVERB_MAX_LATE_REVERB_GAIN)) - throw effect_exception{AL_INVALID_VALUE, "EAX Reverb late reverb gain out of range"}; - props->Reverb.LateReverbGain = val; - break; - - case AL_EAXREVERB_LATE_REVERB_DELAY: - if(!(val >= AL_EAXREVERB_MIN_LATE_REVERB_DELAY && val <= AL_EAXREVERB_MAX_LATE_REVERB_DELAY)) - throw effect_exception{AL_INVALID_VALUE, "EAX Reverb late reverb delay out of range"}; - props->Reverb.LateReverbDelay = val; - break; - - case AL_EAXREVERB_AIR_ABSORPTION_GAINHF: - if(!(val >= AL_EAXREVERB_MIN_AIR_ABSORPTION_GAINHF && val <= AL_EAXREVERB_MAX_AIR_ABSORPTION_GAINHF)) - throw effect_exception{AL_INVALID_VALUE, "EAX Reverb air absorption gainhf out of range"}; - props->Reverb.AirAbsorptionGainHF = val; - break; - - case AL_EAXREVERB_ECHO_TIME: - if(!(val >= AL_EAXREVERB_MIN_ECHO_TIME && val <= AL_EAXREVERB_MAX_ECHO_TIME)) - throw effect_exception{AL_INVALID_VALUE, "EAX Reverb echo time out of range"}; - props->Reverb.EchoTime = val; - break; - - case AL_EAXREVERB_ECHO_DEPTH: - if(!(val >= AL_EAXREVERB_MIN_ECHO_DEPTH && val <= AL_EAXREVERB_MAX_ECHO_DEPTH)) - throw effect_exception{AL_INVALID_VALUE, "EAX Reverb echo depth out of range"}; - props->Reverb.EchoDepth = val; - break; - - case AL_EAXREVERB_MODULATION_TIME: - if(!(val >= AL_EAXREVERB_MIN_MODULATION_TIME && val <= AL_EAXREVERB_MAX_MODULATION_TIME)) - throw effect_exception{AL_INVALID_VALUE, "EAX Reverb modulation time out of range"}; - props->Reverb.ModulationTime = val; - break; - - case AL_EAXREVERB_MODULATION_DEPTH: - if(!(val >= AL_EAXREVERB_MIN_MODULATION_DEPTH && val <= AL_EAXREVERB_MAX_MODULATION_DEPTH)) - throw effect_exception{AL_INVALID_VALUE, "EAX Reverb modulation depth out of range"}; - props->Reverb.ModulationDepth = val; - break; - - case AL_EAXREVERB_HFREFERENCE: - if(!(val >= AL_EAXREVERB_MIN_HFREFERENCE && val <= AL_EAXREVERB_MAX_HFREFERENCE)) - throw effect_exception{AL_INVALID_VALUE, "EAX Reverb hfreference out of range"}; - props->Reverb.HFReference = val; - break; - - case AL_EAXREVERB_LFREFERENCE: - if(!(val >= AL_EAXREVERB_MIN_LFREFERENCE && val <= AL_EAXREVERB_MAX_LFREFERENCE)) - throw effect_exception{AL_INVALID_VALUE, "EAX Reverb lfreference out of range"}; - props->Reverb.LFReference = val; - break; - - case AL_EAXREVERB_ROOM_ROLLOFF_FACTOR: - if(!(val >= AL_EAXREVERB_MIN_ROOM_ROLLOFF_FACTOR && val <= AL_EAXREVERB_MAX_ROOM_ROLLOFF_FACTOR)) - throw effect_exception{AL_INVALID_VALUE, "EAX Reverb room rolloff factor out of range"}; - props->Reverb.RoomRolloffFactor = val; - break; - - default: - throw effect_exception{AL_INVALID_ENUM, "Invalid EAX reverb float property 0x%04x", param}; - } -} -void Reverb_setParamfv(EffectProps *props, ALenum param, const float *vals) -{ - switch(param) - { - case AL_EAXREVERB_REFLECTIONS_PAN: - if(!(std::isfinite(vals[0]) && std::isfinite(vals[1]) && std::isfinite(vals[2]))) - throw effect_exception{AL_INVALID_VALUE, "EAX Reverb reflections pan out of range"}; - props->Reverb.ReflectionsPan[0] = vals[0]; - props->Reverb.ReflectionsPan[1] = vals[1]; - props->Reverb.ReflectionsPan[2] = vals[2]; - break; - case AL_EAXREVERB_LATE_REVERB_PAN: - if(!(std::isfinite(vals[0]) && std::isfinite(vals[1]) && std::isfinite(vals[2]))) - throw effect_exception{AL_INVALID_VALUE, "EAX Reverb late reverb pan out of range"}; - props->Reverb.LateReverbPan[0] = vals[0]; - props->Reverb.LateReverbPan[1] = vals[1]; - props->Reverb.LateReverbPan[2] = vals[2]; - break; - - default: - Reverb_setParamf(props, param, vals[0]); - break; - } -} - -void Reverb_getParami(const EffectProps *props, ALenum param, int *val) -{ - switch(param) - { - case AL_EAXREVERB_DECAY_HFLIMIT: - *val = props->Reverb.DecayHFLimit; - break; - - default: - throw effect_exception{AL_INVALID_ENUM, "Invalid EAX reverb integer property 0x%04x", - param}; - } -} -void Reverb_getParamiv(const EffectProps *props, ALenum param, int *vals) -{ Reverb_getParami(props, param, vals); } -void Reverb_getParamf(const EffectProps *props, ALenum param, float *val) -{ - switch(param) - { - case AL_EAXREVERB_DENSITY: - *val = props->Reverb.Density; - break; - - case AL_EAXREVERB_DIFFUSION: - *val = props->Reverb.Diffusion; - break; - - case AL_EAXREVERB_GAIN: - *val = props->Reverb.Gain; - break; - - case AL_EAXREVERB_GAINHF: - *val = props->Reverb.GainHF; - break; - - case AL_EAXREVERB_GAINLF: - *val = props->Reverb.GainLF; - break; - - case AL_EAXREVERB_DECAY_TIME: - *val = props->Reverb.DecayTime; - break; - - case AL_EAXREVERB_DECAY_HFRATIO: - *val = props->Reverb.DecayHFRatio; - break; - - case AL_EAXREVERB_DECAY_LFRATIO: - *val = props->Reverb.DecayLFRatio; - break; - - case AL_EAXREVERB_REFLECTIONS_GAIN: - *val = props->Reverb.ReflectionsGain; - break; - - case AL_EAXREVERB_REFLECTIONS_DELAY: - *val = props->Reverb.ReflectionsDelay; - break; - - case AL_EAXREVERB_LATE_REVERB_GAIN: - *val = props->Reverb.LateReverbGain; - break; - - case AL_EAXREVERB_LATE_REVERB_DELAY: - *val = props->Reverb.LateReverbDelay; - break; - - case AL_EAXREVERB_AIR_ABSORPTION_GAINHF: - *val = props->Reverb.AirAbsorptionGainHF; - break; - - case AL_EAXREVERB_ECHO_TIME: - *val = props->Reverb.EchoTime; - break; - - case AL_EAXREVERB_ECHO_DEPTH: - *val = props->Reverb.EchoDepth; - break; - - case AL_EAXREVERB_MODULATION_TIME: - *val = props->Reverb.ModulationTime; - break; - - case AL_EAXREVERB_MODULATION_DEPTH: - *val = props->Reverb.ModulationDepth; - break; - - case AL_EAXREVERB_HFREFERENCE: - *val = props->Reverb.HFReference; - break; - - case AL_EAXREVERB_LFREFERENCE: - *val = props->Reverb.LFReference; - break; - - case AL_EAXREVERB_ROOM_ROLLOFF_FACTOR: - *val = props->Reverb.RoomRolloffFactor; - break; - - default: - throw effect_exception{AL_INVALID_ENUM, "Invalid EAX reverb float property 0x%04x", param}; - } -} -void Reverb_getParamfv(const EffectProps *props, ALenum param, float *vals) -{ - switch(param) - { - case AL_EAXREVERB_REFLECTIONS_PAN: - vals[0] = props->Reverb.ReflectionsPan[0]; - vals[1] = props->Reverb.ReflectionsPan[1]; - vals[2] = props->Reverb.ReflectionsPan[2]; - break; - case AL_EAXREVERB_LATE_REVERB_PAN: - vals[0] = props->Reverb.LateReverbPan[0]; - vals[1] = props->Reverb.LateReverbPan[1]; - vals[2] = props->Reverb.LateReverbPan[2]; - break; - - default: - Reverb_getParamf(props, param, vals); - break; - } -} - -EffectProps genDefaultProps() noexcept -{ - EffectProps props{}; - props.Reverb.Density = AL_EAXREVERB_DEFAULT_DENSITY; - props.Reverb.Diffusion = AL_EAXREVERB_DEFAULT_DIFFUSION; - props.Reverb.Gain = AL_EAXREVERB_DEFAULT_GAIN; - props.Reverb.GainHF = AL_EAXREVERB_DEFAULT_GAINHF; - props.Reverb.GainLF = AL_EAXREVERB_DEFAULT_GAINLF; - props.Reverb.DecayTime = AL_EAXREVERB_DEFAULT_DECAY_TIME; - props.Reverb.DecayHFRatio = AL_EAXREVERB_DEFAULT_DECAY_HFRATIO; - props.Reverb.DecayLFRatio = AL_EAXREVERB_DEFAULT_DECAY_LFRATIO; - props.Reverb.ReflectionsGain = AL_EAXREVERB_DEFAULT_REFLECTIONS_GAIN; - props.Reverb.ReflectionsDelay = AL_EAXREVERB_DEFAULT_REFLECTIONS_DELAY; - props.Reverb.ReflectionsPan[0] = AL_EAXREVERB_DEFAULT_REFLECTIONS_PAN_XYZ; - props.Reverb.ReflectionsPan[1] = AL_EAXREVERB_DEFAULT_REFLECTIONS_PAN_XYZ; - props.Reverb.ReflectionsPan[2] = AL_EAXREVERB_DEFAULT_REFLECTIONS_PAN_XYZ; - props.Reverb.LateReverbGain = AL_EAXREVERB_DEFAULT_LATE_REVERB_GAIN; - props.Reverb.LateReverbDelay = AL_EAXREVERB_DEFAULT_LATE_REVERB_DELAY; - props.Reverb.LateReverbPan[0] = AL_EAXREVERB_DEFAULT_LATE_REVERB_PAN_XYZ; - props.Reverb.LateReverbPan[1] = AL_EAXREVERB_DEFAULT_LATE_REVERB_PAN_XYZ; - props.Reverb.LateReverbPan[2] = AL_EAXREVERB_DEFAULT_LATE_REVERB_PAN_XYZ; - props.Reverb.EchoTime = AL_EAXREVERB_DEFAULT_ECHO_TIME; - props.Reverb.EchoDepth = AL_EAXREVERB_DEFAULT_ECHO_DEPTH; - props.Reverb.ModulationTime = AL_EAXREVERB_DEFAULT_MODULATION_TIME; - props.Reverb.ModulationDepth = AL_EAXREVERB_DEFAULT_MODULATION_DEPTH; - props.Reverb.AirAbsorptionGainHF = AL_EAXREVERB_DEFAULT_AIR_ABSORPTION_GAINHF; - props.Reverb.HFReference = AL_EAXREVERB_DEFAULT_HFREFERENCE; - props.Reverb.LFReference = AL_EAXREVERB_DEFAULT_LFREFERENCE; - props.Reverb.RoomRolloffFactor = AL_EAXREVERB_DEFAULT_ROOM_ROLLOFF_FACTOR; - props.Reverb.DecayHFLimit = AL_EAXREVERB_DEFAULT_DECAY_HFLIMIT; - return props; -} - - -void StdReverb_setParami(EffectProps *props, ALenum param, int val) -{ - switch(param) - { - case AL_REVERB_DECAY_HFLIMIT: - if(!(val >= AL_REVERB_MIN_DECAY_HFLIMIT && val <= AL_REVERB_MAX_DECAY_HFLIMIT)) - throw effect_exception{AL_INVALID_VALUE, "Reverb decay hflimit out of range"}; - props->Reverb.DecayHFLimit = val != AL_FALSE; - break; - - default: - throw effect_exception{AL_INVALID_ENUM, "Invalid reverb integer property 0x%04x", param}; - } -} -void StdReverb_setParamiv(EffectProps *props, ALenum param, const int *vals) -{ StdReverb_setParami(props, param, vals[0]); } -void StdReverb_setParamf(EffectProps *props, ALenum param, float val) -{ - switch(param) - { - case AL_REVERB_DENSITY: - if(!(val >= AL_REVERB_MIN_DENSITY && val <= AL_REVERB_MAX_DENSITY)) - throw effect_exception{AL_INVALID_VALUE, "Reverb density out of range"}; - props->Reverb.Density = val; - break; - - case AL_REVERB_DIFFUSION: - if(!(val >= AL_REVERB_MIN_DIFFUSION && val <= AL_REVERB_MAX_DIFFUSION)) - throw effect_exception{AL_INVALID_VALUE, "Reverb diffusion out of range"}; - props->Reverb.Diffusion = val; - break; - - case AL_REVERB_GAIN: - if(!(val >= AL_REVERB_MIN_GAIN && val <= AL_REVERB_MAX_GAIN)) - throw effect_exception{AL_INVALID_VALUE, "Reverb gain out of range"}; - props->Reverb.Gain = val; - break; - - case AL_REVERB_GAINHF: - if(!(val >= AL_REVERB_MIN_GAINHF && val <= AL_REVERB_MAX_GAINHF)) - throw effect_exception{AL_INVALID_VALUE, "Reverb gainhf out of range"}; - props->Reverb.GainHF = val; - break; - - case AL_REVERB_DECAY_TIME: - if(!(val >= AL_REVERB_MIN_DECAY_TIME && val <= AL_REVERB_MAX_DECAY_TIME)) - throw effect_exception{AL_INVALID_VALUE, "Reverb decay time out of range"}; - props->Reverb.DecayTime = val; - break; - - case AL_REVERB_DECAY_HFRATIO: - if(!(val >= AL_REVERB_MIN_DECAY_HFRATIO && val <= AL_REVERB_MAX_DECAY_HFRATIO)) - throw effect_exception{AL_INVALID_VALUE, "Reverb decay hfratio out of range"}; - props->Reverb.DecayHFRatio = val; - break; - - case AL_REVERB_REFLECTIONS_GAIN: - if(!(val >= AL_REVERB_MIN_REFLECTIONS_GAIN && val <= AL_REVERB_MAX_REFLECTIONS_GAIN)) - throw effect_exception{AL_INVALID_VALUE, "Reverb reflections gain out of range"}; - props->Reverb.ReflectionsGain = val; - break; - - case AL_REVERB_REFLECTIONS_DELAY: - if(!(val >= AL_REVERB_MIN_REFLECTIONS_DELAY && val <= AL_REVERB_MAX_REFLECTIONS_DELAY)) - throw effect_exception{AL_INVALID_VALUE, "Reverb reflections delay out of range"}; - props->Reverb.ReflectionsDelay = val; - break; - - case AL_REVERB_LATE_REVERB_GAIN: - if(!(val >= AL_REVERB_MIN_LATE_REVERB_GAIN && val <= AL_REVERB_MAX_LATE_REVERB_GAIN)) - throw effect_exception{AL_INVALID_VALUE, "Reverb late reverb gain out of range"}; - props->Reverb.LateReverbGain = val; - break; - - case AL_REVERB_LATE_REVERB_DELAY: - if(!(val >= AL_REVERB_MIN_LATE_REVERB_DELAY && val <= AL_REVERB_MAX_LATE_REVERB_DELAY)) - throw effect_exception{AL_INVALID_VALUE, "Reverb late reverb delay out of range"}; - props->Reverb.LateReverbDelay = val; - break; - - case AL_REVERB_AIR_ABSORPTION_GAINHF: - if(!(val >= AL_REVERB_MIN_AIR_ABSORPTION_GAINHF && val <= AL_REVERB_MAX_AIR_ABSORPTION_GAINHF)) - throw effect_exception{AL_INVALID_VALUE, "Reverb air absorption gainhf out of range"}; - props->Reverb.AirAbsorptionGainHF = val; - break; - - case AL_REVERB_ROOM_ROLLOFF_FACTOR: - if(!(val >= AL_REVERB_MIN_ROOM_ROLLOFF_FACTOR && val <= AL_REVERB_MAX_ROOM_ROLLOFF_FACTOR)) - throw effect_exception{AL_INVALID_VALUE, "Reverb room rolloff factor out of range"}; - props->Reverb.RoomRolloffFactor = val; - break; - - default: - throw effect_exception{AL_INVALID_ENUM, "Invalid reverb float property 0x%04x", param}; - } -} -void StdReverb_setParamfv(EffectProps *props, ALenum param, const float *vals) -{ StdReverb_setParamf(props, param, vals[0]); } - -void StdReverb_getParami(const EffectProps *props, ALenum param, int *val) -{ - switch(param) - { - case AL_REVERB_DECAY_HFLIMIT: - *val = props->Reverb.DecayHFLimit; - break; - - default: - throw effect_exception{AL_INVALID_ENUM, "Invalid reverb integer property 0x%04x", param}; - } -} -void StdReverb_getParamiv(const EffectProps *props, ALenum param, int *vals) -{ StdReverb_getParami(props, param, vals); } -void StdReverb_getParamf(const EffectProps *props, ALenum param, float *val) -{ - switch(param) - { - case AL_REVERB_DENSITY: - *val = props->Reverb.Density; - break; - - case AL_REVERB_DIFFUSION: - *val = props->Reverb.Diffusion; - break; - - case AL_REVERB_GAIN: - *val = props->Reverb.Gain; - break; - - case AL_REVERB_GAINHF: - *val = props->Reverb.GainHF; - break; - - case AL_REVERB_DECAY_TIME: - *val = props->Reverb.DecayTime; - break; - - case AL_REVERB_DECAY_HFRATIO: - *val = props->Reverb.DecayHFRatio; - break; - - case AL_REVERB_REFLECTIONS_GAIN: - *val = props->Reverb.ReflectionsGain; - break; - - case AL_REVERB_REFLECTIONS_DELAY: - *val = props->Reverb.ReflectionsDelay; - break; - - case AL_REVERB_LATE_REVERB_GAIN: - *val = props->Reverb.LateReverbGain; - break; - - case AL_REVERB_LATE_REVERB_DELAY: - *val = props->Reverb.LateReverbDelay; - break; - - case AL_REVERB_AIR_ABSORPTION_GAINHF: - *val = props->Reverb.AirAbsorptionGainHF; - break; - - case AL_REVERB_ROOM_ROLLOFF_FACTOR: - *val = props->Reverb.RoomRolloffFactor; - break; - - default: - throw effect_exception{AL_INVALID_ENUM, "Invalid reverb float property 0x%04x", param}; - } -} -void StdReverb_getParamfv(const EffectProps *props, ALenum param, float *vals) -{ StdReverb_getParamf(props, param, vals); } - -EffectProps genDefaultStdProps() noexcept -{ - EffectProps props{}; - props.Reverb.Density = AL_REVERB_DEFAULT_DENSITY; - props.Reverb.Diffusion = AL_REVERB_DEFAULT_DIFFUSION; - props.Reverb.Gain = AL_REVERB_DEFAULT_GAIN; - props.Reverb.GainHF = AL_REVERB_DEFAULT_GAINHF; - props.Reverb.GainLF = 1.0f; - props.Reverb.DecayTime = AL_REVERB_DEFAULT_DECAY_TIME; - props.Reverb.DecayHFRatio = AL_REVERB_DEFAULT_DECAY_HFRATIO; - props.Reverb.DecayLFRatio = 1.0f; - props.Reverb.ReflectionsGain = AL_REVERB_DEFAULT_REFLECTIONS_GAIN; - props.Reverb.ReflectionsDelay = AL_REVERB_DEFAULT_REFLECTIONS_DELAY; - props.Reverb.ReflectionsPan[0] = 0.0f; - props.Reverb.ReflectionsPan[1] = 0.0f; - props.Reverb.ReflectionsPan[2] = 0.0f; - props.Reverb.LateReverbGain = AL_REVERB_DEFAULT_LATE_REVERB_GAIN; - props.Reverb.LateReverbDelay = AL_REVERB_DEFAULT_LATE_REVERB_DELAY; - props.Reverb.LateReverbPan[0] = 0.0f; - props.Reverb.LateReverbPan[1] = 0.0f; - props.Reverb.LateReverbPan[2] = 0.0f; - props.Reverb.EchoTime = 0.25f; - props.Reverb.EchoDepth = 0.0f; - props.Reverb.ModulationTime = 0.25f; - props.Reverb.ModulationDepth = 0.0f; - props.Reverb.AirAbsorptionGainHF = AL_REVERB_DEFAULT_AIR_ABSORPTION_GAINHF; - props.Reverb.HFReference = 5000.0f; - props.Reverb.LFReference = 250.0f; - props.Reverb.RoomRolloffFactor = AL_REVERB_DEFAULT_ROOM_ROLLOFF_FACTOR; - props.Reverb.DecayHFLimit = AL_REVERB_DEFAULT_DECAY_HFLIMIT; - return props; -} - -} // namespace - -DEFINE_ALEFFECT_VTABLE(Reverb); - -const EffectProps ReverbEffectProps{genDefaultProps()}; - -DEFINE_ALEFFECT_VTABLE(StdReverb); - -const EffectProps StdReverbEffectProps{genDefaultStdProps()}; diff --git a/al/effects/vmorpher.cpp b/al/effects/vmorpher.cpp deleted file mode 100644 index 03eb2c62..00000000 --- a/al/effects/vmorpher.cpp +++ /dev/null @@ -1,247 +0,0 @@ - -#include "config.h" - -#include "AL/al.h" -#include "AL/efx.h" - -#include "aloptional.h" -#include "effects.h" -#include "effects/base.h" - - -namespace { - -al::optional PhenomeFromEnum(ALenum val) -{ -#define HANDLE_PHENOME(x) case AL_VOCAL_MORPHER_PHONEME_ ## x: \ - return al::make_optional(VMorpherPhenome::x) - switch(val) - { - HANDLE_PHENOME(A); - HANDLE_PHENOME(E); - HANDLE_PHENOME(I); - HANDLE_PHENOME(O); - HANDLE_PHENOME(U); - HANDLE_PHENOME(AA); - HANDLE_PHENOME(AE); - HANDLE_PHENOME(AH); - HANDLE_PHENOME(AO); - HANDLE_PHENOME(EH); - HANDLE_PHENOME(ER); - HANDLE_PHENOME(IH); - HANDLE_PHENOME(IY); - HANDLE_PHENOME(UH); - HANDLE_PHENOME(UW); - HANDLE_PHENOME(B); - HANDLE_PHENOME(D); - HANDLE_PHENOME(F); - HANDLE_PHENOME(G); - HANDLE_PHENOME(J); - HANDLE_PHENOME(K); - HANDLE_PHENOME(L); - HANDLE_PHENOME(M); - HANDLE_PHENOME(N); - HANDLE_PHENOME(P); - HANDLE_PHENOME(R); - HANDLE_PHENOME(S); - HANDLE_PHENOME(T); - HANDLE_PHENOME(V); - HANDLE_PHENOME(Z); - } - return al::nullopt; -#undef HANDLE_PHENOME -} -ALenum EnumFromPhenome(VMorpherPhenome phenome) -{ -#define HANDLE_PHENOME(x) case VMorpherPhenome::x: return AL_VOCAL_MORPHER_PHONEME_ ## x - switch(phenome) - { - HANDLE_PHENOME(A); - HANDLE_PHENOME(E); - HANDLE_PHENOME(I); - HANDLE_PHENOME(O); - HANDLE_PHENOME(U); - HANDLE_PHENOME(AA); - HANDLE_PHENOME(AE); - HANDLE_PHENOME(AH); - HANDLE_PHENOME(AO); - HANDLE_PHENOME(EH); - HANDLE_PHENOME(ER); - HANDLE_PHENOME(IH); - HANDLE_PHENOME(IY); - HANDLE_PHENOME(UH); - HANDLE_PHENOME(UW); - HANDLE_PHENOME(B); - HANDLE_PHENOME(D); - HANDLE_PHENOME(F); - HANDLE_PHENOME(G); - HANDLE_PHENOME(J); - HANDLE_PHENOME(K); - HANDLE_PHENOME(L); - HANDLE_PHENOME(M); - HANDLE_PHENOME(N); - HANDLE_PHENOME(P); - HANDLE_PHENOME(R); - HANDLE_PHENOME(S); - HANDLE_PHENOME(T); - HANDLE_PHENOME(V); - HANDLE_PHENOME(Z); - } - throw std::runtime_error{"Invalid phenome: "+std::to_string(static_cast(phenome))}; -#undef HANDLE_PHENOME -} - -al::optional WaveformFromEmum(ALenum value) -{ - switch(value) - { - case AL_VOCAL_MORPHER_WAVEFORM_SINUSOID: return al::make_optional(VMorpherWaveform::Sinusoid); - case AL_VOCAL_MORPHER_WAVEFORM_TRIANGLE: return al::make_optional(VMorpherWaveform::Triangle); - case AL_VOCAL_MORPHER_WAVEFORM_SAWTOOTH: return al::make_optional(VMorpherWaveform::Sawtooth); - } - return al::nullopt; -} -ALenum EnumFromWaveform(VMorpherWaveform type) -{ - switch(type) - { - case VMorpherWaveform::Sinusoid: return AL_VOCAL_MORPHER_WAVEFORM_SINUSOID; - case VMorpherWaveform::Triangle: return AL_VOCAL_MORPHER_WAVEFORM_TRIANGLE; - case VMorpherWaveform::Sawtooth: return AL_VOCAL_MORPHER_WAVEFORM_SAWTOOTH; - } - throw std::runtime_error{"Invalid vocal morpher waveform: " + - std::to_string(static_cast(type))}; -} - -void Vmorpher_setParami(EffectProps *props, ALenum param, int val) -{ - switch(param) - { - case AL_VOCAL_MORPHER_PHONEMEA: - if(auto phenomeopt = PhenomeFromEnum(val)) - props->Vmorpher.PhonemeA = *phenomeopt; - else - throw effect_exception{AL_INVALID_VALUE, "Vocal morpher phoneme-a out of range: 0x%04x", val}; - break; - - case AL_VOCAL_MORPHER_PHONEMEA_COARSE_TUNING: - if(!(val >= AL_VOCAL_MORPHER_MIN_PHONEMEA_COARSE_TUNING && val <= AL_VOCAL_MORPHER_MAX_PHONEMEA_COARSE_TUNING)) - throw effect_exception{AL_INVALID_VALUE, "Vocal morpher phoneme-a coarse tuning out of range"}; - props->Vmorpher.PhonemeACoarseTuning = val; - break; - - case AL_VOCAL_MORPHER_PHONEMEB: - if(auto phenomeopt = PhenomeFromEnum(val)) - props->Vmorpher.PhonemeB = *phenomeopt; - else - throw effect_exception{AL_INVALID_VALUE, "Vocal morpher phoneme-b out of range: 0x%04x", val}; - break; - - case AL_VOCAL_MORPHER_PHONEMEB_COARSE_TUNING: - if(!(val >= AL_VOCAL_MORPHER_MIN_PHONEMEB_COARSE_TUNING && val <= AL_VOCAL_MORPHER_MAX_PHONEMEB_COARSE_TUNING)) - throw effect_exception{AL_INVALID_VALUE, "Vocal morpher phoneme-b coarse tuning out of range"}; - props->Vmorpher.PhonemeBCoarseTuning = val; - break; - - case AL_VOCAL_MORPHER_WAVEFORM: - if(auto formopt = WaveformFromEmum(val)) - props->Vmorpher.Waveform = *formopt; - else - throw effect_exception{AL_INVALID_VALUE, "Vocal morpher waveform out of range: 0x%04x", val}; - break; - - default: - throw effect_exception{AL_INVALID_ENUM, "Invalid vocal morpher integer property 0x%04x", - param}; - } -} -void Vmorpher_setParamiv(EffectProps*, ALenum param, const int*) -{ - throw effect_exception{AL_INVALID_ENUM, "Invalid vocal morpher integer-vector property 0x%04x", - param}; -} -void Vmorpher_setParamf(EffectProps *props, ALenum param, float val) -{ - switch(param) - { - case AL_VOCAL_MORPHER_RATE: - if(!(val >= AL_VOCAL_MORPHER_MIN_RATE && val <= AL_VOCAL_MORPHER_MAX_RATE)) - throw effect_exception{AL_INVALID_VALUE, "Vocal morpher rate out of range"}; - props->Vmorpher.Rate = val; - break; - - default: - throw effect_exception{AL_INVALID_ENUM, "Invalid vocal morpher float property 0x%04x", - param}; - } -} -void Vmorpher_setParamfv(EffectProps *props, ALenum param, const float *vals) -{ Vmorpher_setParamf(props, param, vals[0]); } - -void Vmorpher_getParami(const EffectProps *props, ALenum param, int* val) -{ - switch(param) - { - case AL_VOCAL_MORPHER_PHONEMEA: - *val = EnumFromPhenome(props->Vmorpher.PhonemeA); - break; - - case AL_VOCAL_MORPHER_PHONEMEA_COARSE_TUNING: - *val = props->Vmorpher.PhonemeACoarseTuning; - break; - - case AL_VOCAL_MORPHER_PHONEMEB: - *val = EnumFromPhenome(props->Vmorpher.PhonemeB); - break; - - case AL_VOCAL_MORPHER_PHONEMEB_COARSE_TUNING: - *val = props->Vmorpher.PhonemeBCoarseTuning; - break; - - case AL_VOCAL_MORPHER_WAVEFORM: - *val = EnumFromWaveform(props->Vmorpher.Waveform); - break; - - default: - throw effect_exception{AL_INVALID_ENUM, "Invalid vocal morpher integer property 0x%04x", - param}; - } -} -void Vmorpher_getParamiv(const EffectProps*, ALenum param, int*) -{ - throw effect_exception{AL_INVALID_ENUM, "Invalid vocal morpher integer-vector property 0x%04x", - param}; -} -void Vmorpher_getParamf(const EffectProps *props, ALenum param, float *val) -{ - switch(param) - { - case AL_VOCAL_MORPHER_RATE: - *val = props->Vmorpher.Rate; - break; - - default: - throw effect_exception{AL_INVALID_ENUM, "Invalid vocal morpher float property 0x%04x", - param}; - } -} -void Vmorpher_getParamfv(const EffectProps *props, ALenum param, float *vals) -{ Vmorpher_getParamf(props, param, vals); } - -EffectProps genDefaultProps() noexcept -{ - EffectProps props{}; - props.Vmorpher.Rate = AL_VOCAL_MORPHER_DEFAULT_RATE; - props.Vmorpher.PhonemeA = *PhenomeFromEnum(AL_VOCAL_MORPHER_DEFAULT_PHONEMEA); - props.Vmorpher.PhonemeB = *PhenomeFromEnum(AL_VOCAL_MORPHER_DEFAULT_PHONEMEB); - props.Vmorpher.PhonemeACoarseTuning = AL_VOCAL_MORPHER_DEFAULT_PHONEMEA_COARSE_TUNING; - props.Vmorpher.PhonemeBCoarseTuning = AL_VOCAL_MORPHER_DEFAULT_PHONEMEB_COARSE_TUNING; - props.Vmorpher.Waveform = *WaveformFromEmum(AL_VOCAL_MORPHER_DEFAULT_WAVEFORM); - return props; -} - -} // namespace - -DEFINE_ALEFFECT_VTABLE(Vmorpher); - -const EffectProps VmorpherEffectProps{genDefaultProps()}; diff --git a/al/error.cpp b/al/error.cpp deleted file mode 100644 index 444b55aa..00000000 --- a/al/error.cpp +++ /dev/null @@ -1,106 +0,0 @@ -/** - * OpenAL cross platform audio library - * Copyright (C) 1999-2000 by authors. - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - * Or go to http://www.gnu.org/copyleft/lgpl.html - */ - -#include "config.h" - -#ifdef _WIN32 -#define WIN32_LEAN_AND_MEAN -#include -#endif - -#include -#include -#include -#include -#include -#include - -#include "AL/al.h" -#include "AL/alc.h" - -#include "alcontext.h" -#include "almalloc.h" -#include "core/except.h" -#include "core/logging.h" -#include "opthelpers.h" -#include "vector.h" - - -bool TrapALError{false}; - -void ALCcontext::setError(ALenum errorCode, const char *msg, ...) -{ - auto message = al::vector(256); - - va_list args, args2; - va_start(args, msg); - va_copy(args2, args); - int msglen{std::vsnprintf(message.data(), message.size(), msg, args)}; - if(msglen >= 0 && static_cast(msglen) >= message.size()) - { - message.resize(static_cast(msglen) + 1u); - msglen = std::vsnprintf(message.data(), message.size(), msg, args2); - } - va_end(args2); - va_end(args); - - if(msglen >= 0) msg = message.data(); - else msg = ""; - - WARN("Error generated on context %p, code 0x%04x, \"%s\"\n", - decltype(std::declval()){this}, errorCode, msg); - if(TrapALError) - { -#ifdef _WIN32 - /* DebugBreak will cause an exception if there is no debugger */ - if(IsDebuggerPresent()) - DebugBreak(); -#elif defined(SIGTRAP) - raise(SIGTRAP); -#endif - } - - ALenum curerr{AL_NO_ERROR}; - mLastError.compare_exchange_strong(curerr, errorCode); -} - -AL_API ALenum AL_APIENTRY alGetError(void) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) - { - constexpr ALenum deferror{AL_INVALID_OPERATION}; - WARN("Querying error state on null context (implicitly 0x%04x)\n", deferror); - if(TrapALError) - { -#ifdef _WIN32 - if(IsDebuggerPresent()) - DebugBreak(); -#elif defined(SIGTRAP) - raise(SIGTRAP); -#endif - } - return deferror; - } - - return context->mLastError.exchange(AL_NO_ERROR); -} -END_API_FUNC diff --git a/al/event.cpp b/al/event.cpp deleted file mode 100644 index a5d7be38..00000000 --- a/al/event.cpp +++ /dev/null @@ -1,223 +0,0 @@ - -#include "config.h" - -#include "event.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "AL/al.h" -#include "AL/alc.h" - -#include "albyte.h" -#include "alcontext.h" -#include "almalloc.h" -#include "async_event.h" -#include "core/except.h" -#include "core/logging.h" -#include "effects/base.h" -#include "inprogext.h" -#include "opthelpers.h" -#include "ringbuffer.h" -#include "threads.h" -#include "voice_change.h" - - -static int EventThread(ALCcontext *context) -{ - RingBuffer *ring{context->mAsyncEvents.get()}; - bool quitnow{false}; - while LIKELY(!quitnow) - { - auto evt_data = ring->getReadVector().first; - if(evt_data.len == 0) - { - context->mEventSem.wait(); - continue; - } - - std::lock_guard _{context->mEventCbLock}; - do { - auto *evt_ptr = reinterpret_cast(evt_data.buf); - evt_data.buf += sizeof(AsyncEvent); - evt_data.len -= 1; - - AsyncEvent evt{*evt_ptr}; - al::destroy_at(evt_ptr); - ring->readAdvance(1); - - quitnow = evt.EnumType == EventType_KillThread; - if UNLIKELY(quitnow) break; - - if(evt.EnumType == EventType_ReleaseEffectState) - { - evt.u.mEffectState->release(); - continue; - } - - uint enabledevts{context->mEnabledEvts.load(std::memory_order_acquire)}; - if(!context->mEventCb) continue; - - if(evt.EnumType == EventType_SourceStateChange) - { - if(!(enabledevts&EventType_SourceStateChange)) - continue; - ALuint state{}; - std::string msg{"Source ID " + std::to_string(evt.u.srcstate.id)}; - msg += " state has changed to "; - switch(evt.u.srcstate.state) - { - case VChangeState::Reset: - msg += "AL_INITIAL"; - state = AL_INITIAL; - break; - case VChangeState::Stop: - msg += "AL_STOPPED"; - state = AL_STOPPED; - break; - case VChangeState::Play: - msg += "AL_PLAYING"; - state = AL_PLAYING; - break; - case VChangeState::Pause: - msg += "AL_PAUSED"; - state = AL_PAUSED; - break; - /* Shouldn't happen */ - case VChangeState::Restart: - break; - } - context->mEventCb(AL_EVENT_TYPE_SOURCE_STATE_CHANGED_SOFT, evt.u.srcstate.id, - state, static_cast(msg.length()), msg.c_str(), context->mEventParam); - } - else if(evt.EnumType == EventType_BufferCompleted) - { - if(!(enabledevts&EventType_BufferCompleted)) - continue; - std::string msg{std::to_string(evt.u.bufcomp.count)}; - if(evt.u.bufcomp.count == 1) msg += " buffer completed"; - else msg += " buffers completed"; - context->mEventCb(AL_EVENT_TYPE_BUFFER_COMPLETED_SOFT, evt.u.bufcomp.id, - evt.u.bufcomp.count, static_cast(msg.length()), msg.c_str(), - context->mEventParam); - } - else if(evt.EnumType == EventType_Disconnected) - { - if(!(enabledevts&EventType_Disconnected)) - continue; - context->mEventCb(AL_EVENT_TYPE_DISCONNECTED_SOFT, 0, 0, - static_cast(strlen(evt.u.disconnect.msg)), evt.u.disconnect.msg, - context->mEventParam); - } - } while(evt_data.len != 0); - } - return 0; -} - -void StartEventThrd(ALCcontext *ctx) -{ - try { - ctx->mEventThread = std::thread{EventThread, ctx}; - } - catch(std::exception& e) { - ERR("Failed to start event thread: %s\n", e.what()); - } - catch(...) { - ERR("Failed to start event thread! Expect problems.\n"); - } -} - -void StopEventThrd(ALCcontext *ctx) -{ - RingBuffer *ring{ctx->mAsyncEvents.get()}; - auto evt_data = ring->getWriteVector().first; - if(evt_data.len == 0) - { - do { - std::this_thread::yield(); - evt_data = ring->getWriteVector().first; - } while(evt_data.len == 0); - } - ::new(evt_data.buf) AsyncEvent{EventType_KillThread}; - ring->writeAdvance(1); - - ctx->mEventSem.post(); - if(ctx->mEventThread.joinable()) - ctx->mEventThread.join(); -} - -AL_API void AL_APIENTRY alEventControlSOFT(ALsizei count, const ALenum *types, ALboolean enable) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - if(count < 0) context->setError(AL_INVALID_VALUE, "Controlling %d events", count); - if(count <= 0) return; - if(!types) SETERR_RETURN(context, AL_INVALID_VALUE,, "NULL pointer"); - - uint flags{0}; - const ALenum *types_end = types+count; - auto bad_type = std::find_if_not(types, types_end, - [&flags](ALenum type) noexcept -> bool - { - if(type == AL_EVENT_TYPE_BUFFER_COMPLETED_SOFT) - flags |= EventType_BufferCompleted; - else if(type == AL_EVENT_TYPE_SOURCE_STATE_CHANGED_SOFT) - flags |= EventType_SourceStateChange; - else if(type == AL_EVENT_TYPE_DISCONNECTED_SOFT) - flags |= EventType_Disconnected; - else - return false; - return true; - } - ); - if(bad_type != types_end) - SETERR_RETURN(context, AL_INVALID_ENUM,, "Invalid event type 0x%04x", *bad_type); - - if(enable) - { - uint enabledevts{context->mEnabledEvts.load(std::memory_order_relaxed)}; - while(context->mEnabledEvts.compare_exchange_weak(enabledevts, enabledevts|flags, - std::memory_order_acq_rel, std::memory_order_acquire) == 0) - { - /* enabledevts is (re-)filled with the current value on failure, so - * just try again. - */ - } - } - else - { - uint enabledevts{context->mEnabledEvts.load(std::memory_order_relaxed)}; - while(context->mEnabledEvts.compare_exchange_weak(enabledevts, enabledevts&~flags, - std::memory_order_acq_rel, std::memory_order_acquire) == 0) - { - } - /* Wait to ensure the event handler sees the changed flags before - * returning. - */ - std::lock_guard{context->mEventCbLock}; - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alEventCallbackSOFT(ALEVENTPROCSOFT callback, void *userParam) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - std::lock_guard _{context->mPropLock}; - std::lock_guard __{context->mEventCbLock}; - context->mEventCb = callback; - context->mEventParam = userParam; -} -END_API_FUNC diff --git a/al/event.h b/al/event.h deleted file mode 100644 index 83513c51..00000000 --- a/al/event.h +++ /dev/null @@ -1,9 +0,0 @@ -#ifndef AL_EVENT_H -#define AL_EVENT_H - -struct ALCcontext; - -void StartEventThrd(ALCcontext *ctx); -void StopEventThrd(ALCcontext *ctx); - -#endif diff --git a/al/extension.cpp b/al/extension.cpp deleted file mode 100644 index 7346a5c6..00000000 --- a/al/extension.cpp +++ /dev/null @@ -1,79 +0,0 @@ -/** - * OpenAL cross platform audio library - * Copyright (C) 1999-2007 by authors. - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - * Or go to http://www.gnu.org/copyleft/lgpl.html - */ - -#include "config.h" - -#include -#include -#include - -#include "AL/al.h" -#include "AL/alc.h" - -#include "alcontext.h" -#include "alstring.h" -#include "core/except.h" -#include "opthelpers.h" - - -AL_API ALboolean AL_APIENTRY alIsExtensionPresent(const ALchar *extName) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return AL_FALSE; - - if(!extName) - SETERR_RETURN(context, AL_INVALID_VALUE, AL_FALSE, "NULL pointer"); - - size_t len{strlen(extName)}; - const char *ptr{context->mExtensionList}; - while(ptr && *ptr) - { - if(al::strncasecmp(ptr, extName, len) == 0 && (ptr[len] == '\0' || isspace(ptr[len]))) - return AL_TRUE; - - if((ptr=strchr(ptr, ' ')) != nullptr) - { - do { - ++ptr; - } while(isspace(*ptr)); - } - } - - return AL_FALSE; -} -END_API_FUNC - - -AL_API ALvoid* AL_APIENTRY alGetProcAddress(const ALchar *funcName) -START_API_FUNC -{ - if(!funcName) return nullptr; - return alcGetProcAddress(nullptr, funcName); -} -END_API_FUNC - -AL_API ALenum AL_APIENTRY alGetEnumValue(const ALchar *enumName) -START_API_FUNC -{ - if(!enumName) return static_cast(0); - return alcGetEnumValue(nullptr, enumName); -} -END_API_FUNC diff --git a/al/filter.cpp b/al/filter.cpp deleted file mode 100644 index e549b1c9..00000000 --- a/al/filter.cpp +++ /dev/null @@ -1,714 +0,0 @@ -/** - * OpenAL cross platform audio library - * Copyright (C) 1999-2007 by authors. - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - * Or go to http://www.gnu.org/copyleft/lgpl.html - */ - -#include "config.h" - -#include "filter.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "AL/al.h" -#include "AL/alc.h" -#include "AL/efx.h" - -#include "alcmain.h" -#include "alcontext.h" -#include "almalloc.h" -#include "alnumeric.h" -#include "core/except.h" -#include "opthelpers.h" -#include "vector.h" - - -namespace { - -class filter_exception final : public al::base_exception { - ALenum mErrorCode; - -public: - [[gnu::format(printf, 3, 4)]] - filter_exception(ALenum code, const char *msg, ...) : mErrorCode{code} - { - std::va_list args; - va_start(args, msg); - setMessage(msg, args); - va_end(args); - } - ALenum errorCode() const noexcept { return mErrorCode; } -}; - -#define FILTER_MIN_GAIN 0.0f -#define FILTER_MAX_GAIN 4.0f /* +12dB */ - -#define DEFINE_ALFILTER_VTABLE(T) \ -const ALfilter::Vtable T##_vtable = { \ - T##_setParami, T##_setParamiv, T##_setParamf, T##_setParamfv, \ - T##_getParami, T##_getParamiv, T##_getParamf, T##_getParamfv, \ -} - -void ALlowpass_setParami(ALfilter*, ALenum param, int) -{ throw filter_exception{AL_INVALID_ENUM, "Invalid low-pass integer property 0x%04x", param}; } -void ALlowpass_setParamiv(ALfilter*, ALenum param, const int*) -{ - throw filter_exception{AL_INVALID_ENUM, "Invalid low-pass integer-vector property 0x%04x", - param}; -} -void ALlowpass_setParamf(ALfilter *filter, ALenum param, float val) -{ - switch(param) - { - case AL_LOWPASS_GAIN: - if(!(val >= FILTER_MIN_GAIN && val <= FILTER_MAX_GAIN)) - throw filter_exception{AL_INVALID_VALUE, "Low-pass gain %f out of range", val}; - filter->Gain = val; - break; - - case AL_LOWPASS_GAINHF: - if(!(val >= AL_LOWPASS_MIN_GAINHF && val <= AL_LOWPASS_MAX_GAINHF)) - throw filter_exception{AL_INVALID_VALUE, "Low-pass gainhf %f out of range", val}; - filter->GainHF = val; - break; - - default: - throw filter_exception{AL_INVALID_ENUM, "Invalid low-pass float property 0x%04x", param}; - } -} -void ALlowpass_setParamfv(ALfilter *filter, ALenum param, const float *vals) -{ ALlowpass_setParamf(filter, param, vals[0]); } - -void ALlowpass_getParami(const ALfilter*, ALenum param, int*) -{ throw filter_exception{AL_INVALID_ENUM, "Invalid low-pass integer property 0x%04x", param}; } -void ALlowpass_getParamiv(const ALfilter*, ALenum param, int*) -{ - throw filter_exception{AL_INVALID_ENUM, "Invalid low-pass integer-vector property 0x%04x", - param}; -} -void ALlowpass_getParamf(const ALfilter *filter, ALenum param, float *val) -{ - switch(param) - { - case AL_LOWPASS_GAIN: - *val = filter->Gain; - break; - - case AL_LOWPASS_GAINHF: - *val = filter->GainHF; - break; - - default: - throw filter_exception{AL_INVALID_ENUM, "Invalid low-pass float property 0x%04x", param}; - } -} -void ALlowpass_getParamfv(const ALfilter *filter, ALenum param, float *vals) -{ ALlowpass_getParamf(filter, param, vals); } - -DEFINE_ALFILTER_VTABLE(ALlowpass); - - -void ALhighpass_setParami(ALfilter*, ALenum param, int) -{ throw filter_exception{AL_INVALID_ENUM, "Invalid high-pass integer property 0x%04x", param}; } -void ALhighpass_setParamiv(ALfilter*, ALenum param, const int*) -{ - throw filter_exception{AL_INVALID_ENUM, "Invalid high-pass integer-vector property 0x%04x", - param}; -} -void ALhighpass_setParamf(ALfilter *filter, ALenum param, float val) -{ - switch(param) - { - case AL_HIGHPASS_GAIN: - if(!(val >= FILTER_MIN_GAIN && val <= FILTER_MAX_GAIN)) - throw filter_exception{AL_INVALID_VALUE, "High-pass gain %f out of range", val}; - filter->Gain = val; - break; - - case AL_HIGHPASS_GAINLF: - if(!(val >= AL_HIGHPASS_MIN_GAINLF && val <= AL_HIGHPASS_MAX_GAINLF)) - throw filter_exception{AL_INVALID_VALUE, "High-pass gainlf %f out of range", val}; - filter->GainLF = val; - break; - - default: - throw filter_exception{AL_INVALID_ENUM, "Invalid high-pass float property 0x%04x", param}; - } -} -void ALhighpass_setParamfv(ALfilter *filter, ALenum param, const float *vals) -{ ALhighpass_setParamf(filter, param, vals[0]); } - -void ALhighpass_getParami(const ALfilter*, ALenum param, int*) -{ throw filter_exception{AL_INVALID_ENUM, "Invalid high-pass integer property 0x%04x", param}; } -void ALhighpass_getParamiv(const ALfilter*, ALenum param, int*) -{ - throw filter_exception{AL_INVALID_ENUM, "Invalid high-pass integer-vector property 0x%04x", - param}; -} -void ALhighpass_getParamf(const ALfilter *filter, ALenum param, float *val) -{ - switch(param) - { - case AL_HIGHPASS_GAIN: - *val = filter->Gain; - break; - - case AL_HIGHPASS_GAINLF: - *val = filter->GainLF; - break; - - default: - throw filter_exception{AL_INVALID_ENUM, "Invalid high-pass float property 0x%04x", param}; - } -} -void ALhighpass_getParamfv(const ALfilter *filter, ALenum param, float *vals) -{ ALhighpass_getParamf(filter, param, vals); } - -DEFINE_ALFILTER_VTABLE(ALhighpass); - - -void ALbandpass_setParami(ALfilter*, ALenum param, int) -{ throw filter_exception{AL_INVALID_ENUM, "Invalid band-pass integer property 0x%04x", param}; } -void ALbandpass_setParamiv(ALfilter*, ALenum param, const int*) -{ - throw filter_exception{AL_INVALID_ENUM, "Invalid band-pass integer-vector property 0x%04x", - param}; -} -void ALbandpass_setParamf(ALfilter *filter, ALenum param, float val) -{ - switch(param) - { - case AL_BANDPASS_GAIN: - if(!(val >= FILTER_MIN_GAIN && val <= FILTER_MAX_GAIN)) - throw filter_exception{AL_INVALID_VALUE, "Band-pass gain %f out of range", val}; - filter->Gain = val; - break; - - case AL_BANDPASS_GAINHF: - if(!(val >= AL_BANDPASS_MIN_GAINHF && val <= AL_BANDPASS_MAX_GAINHF)) - throw filter_exception{AL_INVALID_VALUE, "Band-pass gainhf %f out of range", val}; - filter->GainHF = val; - break; - - case AL_BANDPASS_GAINLF: - if(!(val >= AL_BANDPASS_MIN_GAINLF && val <= AL_BANDPASS_MAX_GAINLF)) - throw filter_exception{AL_INVALID_VALUE, "Band-pass gainlf %f out of range", val}; - filter->GainLF = val; - break; - - default: - throw filter_exception{AL_INVALID_ENUM, "Invalid band-pass float property 0x%04x", param}; - } -} -void ALbandpass_setParamfv(ALfilter *filter, ALenum param, const float *vals) -{ ALbandpass_setParamf(filter, param, vals[0]); } - -void ALbandpass_getParami(const ALfilter*, ALenum param, int*) -{ throw filter_exception{AL_INVALID_ENUM, "Invalid band-pass integer property 0x%04x", param}; } -void ALbandpass_getParamiv(const ALfilter*, ALenum param, int*) -{ - throw filter_exception{AL_INVALID_ENUM, "Invalid band-pass integer-vector property 0x%04x", - param}; -} -void ALbandpass_getParamf(const ALfilter *filter, ALenum param, float *val) -{ - switch(param) - { - case AL_BANDPASS_GAIN: - *val = filter->Gain; - break; - - case AL_BANDPASS_GAINHF: - *val = filter->GainHF; - break; - - case AL_BANDPASS_GAINLF: - *val = filter->GainLF; - break; - - default: - throw filter_exception{AL_INVALID_ENUM, "Invalid band-pass float property 0x%04x", param}; - } -} -void ALbandpass_getParamfv(const ALfilter *filter, ALenum param, float *vals) -{ ALbandpass_getParamf(filter, param, vals); } - -DEFINE_ALFILTER_VTABLE(ALbandpass); - - -void ALnullfilter_setParami(ALfilter*, ALenum param, int) -{ throw filter_exception{AL_INVALID_ENUM, "Invalid null filter property 0x%04x", param}; } -void ALnullfilter_setParamiv(ALfilter*, ALenum param, const int*) -{ throw filter_exception{AL_INVALID_ENUM, "Invalid null filter property 0x%04x", param}; } -void ALnullfilter_setParamf(ALfilter*, ALenum param, float) -{ throw filter_exception{AL_INVALID_ENUM, "Invalid null filter property 0x%04x", param}; } -void ALnullfilter_setParamfv(ALfilter*, ALenum param, const float*) -{ throw filter_exception{AL_INVALID_ENUM, "Invalid null filter property 0x%04x", param}; } - -void ALnullfilter_getParami(const ALfilter*, ALenum param, int*) -{ throw filter_exception{AL_INVALID_ENUM, "Invalid null filter property 0x%04x", param}; } -void ALnullfilter_getParamiv(const ALfilter*, ALenum param, int*) -{ throw filter_exception{AL_INVALID_ENUM, "Invalid null filter property 0x%04x", param}; } -void ALnullfilter_getParamf(const ALfilter*, ALenum param, float*) -{ throw filter_exception{AL_INVALID_ENUM, "Invalid null filter property 0x%04x", param}; } -void ALnullfilter_getParamfv(const ALfilter*, ALenum param, float*) -{ throw filter_exception{AL_INVALID_ENUM, "Invalid null filter property 0x%04x", param}; } - -DEFINE_ALFILTER_VTABLE(ALnullfilter); - - -void InitFilterParams(ALfilter *filter, ALenum type) -{ - if(type == AL_FILTER_LOWPASS) - { - filter->Gain = AL_LOWPASS_DEFAULT_GAIN; - filter->GainHF = AL_LOWPASS_DEFAULT_GAINHF; - filter->HFReference = LOWPASSFREQREF; - filter->GainLF = 1.0f; - filter->LFReference = HIGHPASSFREQREF; - filter->vtab = &ALlowpass_vtable; - } - else if(type == AL_FILTER_HIGHPASS) - { - filter->Gain = AL_HIGHPASS_DEFAULT_GAIN; - filter->GainHF = 1.0f; - filter->HFReference = LOWPASSFREQREF; - filter->GainLF = AL_HIGHPASS_DEFAULT_GAINLF; - filter->LFReference = HIGHPASSFREQREF; - filter->vtab = &ALhighpass_vtable; - } - else if(type == AL_FILTER_BANDPASS) - { - filter->Gain = AL_BANDPASS_DEFAULT_GAIN; - filter->GainHF = AL_BANDPASS_DEFAULT_GAINHF; - filter->HFReference = LOWPASSFREQREF; - filter->GainLF = AL_BANDPASS_DEFAULT_GAINLF; - filter->LFReference = HIGHPASSFREQREF; - filter->vtab = &ALbandpass_vtable; - } - else - { - filter->Gain = 1.0f; - filter->GainHF = 1.0f; - filter->HFReference = LOWPASSFREQREF; - filter->GainLF = 1.0f; - filter->LFReference = HIGHPASSFREQREF; - filter->vtab = &ALnullfilter_vtable; - } - filter->type = type; -} - -bool EnsureFilters(ALCdevice *device, size_t needed) -{ - size_t count{std::accumulate(device->FilterList.cbegin(), device->FilterList.cend(), size_t{0}, - [](size_t cur, const FilterSubList &sublist) noexcept -> size_t - { return cur + static_cast(PopCount(sublist.FreeMask)); })}; - - while(needed > count) - { - if UNLIKELY(device->FilterList.size() >= 1<<25) - return false; - - device->FilterList.emplace_back(); - auto sublist = device->FilterList.end() - 1; - sublist->FreeMask = ~0_u64; - sublist->Filters = static_cast(al_calloc(alignof(ALfilter), sizeof(ALfilter)*64)); - if UNLIKELY(!sublist->Filters) - { - device->FilterList.pop_back(); - return false; - } - count += 64; - } - return true; -} - - -ALfilter *AllocFilter(ALCdevice *device) -{ - auto sublist = std::find_if(device->FilterList.begin(), device->FilterList.end(), - [](const FilterSubList &entry) noexcept -> bool - { return entry.FreeMask != 0; } - ); - auto lidx = static_cast(std::distance(device->FilterList.begin(), sublist)); - auto slidx = static_cast(CountTrailingZeros(sublist->FreeMask)); - - ALfilter *filter{::new(sublist->Filters + slidx) ALfilter{}}; - InitFilterParams(filter, AL_FILTER_NULL); - - /* Add 1 to avoid filter ID 0. */ - filter->id = ((lidx<<6) | slidx) + 1; - - sublist->FreeMask &= ~(1_u64 << slidx); - - return filter; -} - -void FreeFilter(ALCdevice *device, ALfilter *filter) -{ - const ALuint id{filter->id - 1}; - const size_t lidx{id >> 6}; - const ALuint slidx{id & 0x3f}; - - al::destroy_at(filter); - - device->FilterList[lidx].FreeMask |= 1_u64 << slidx; -} - - -inline ALfilter *LookupFilter(ALCdevice *device, ALuint id) -{ - const size_t lidx{(id-1) >> 6}; - const ALuint slidx{(id-1) & 0x3f}; - - if UNLIKELY(lidx >= device->FilterList.size()) - return nullptr; - FilterSubList &sublist = device->FilterList[lidx]; - if UNLIKELY(sublist.FreeMask & (1_u64 << slidx)) - return nullptr; - return sublist.Filters + slidx; -} - -} // namespace - -AL_API void AL_APIENTRY alGenFilters(ALsizei n, ALuint *filters) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - if UNLIKELY(n < 0) - context->setError(AL_INVALID_VALUE, "Generating %d filters", n); - if UNLIKELY(n <= 0) return; - - ALCdevice *device{context->mDevice.get()}; - std::lock_guard _{device->EffectLock}; - if(!EnsureFilters(device, static_cast(n))) - { - context->setError(AL_OUT_OF_MEMORY, "Failed to allocate %d filter%s", n, (n==1)?"":"s"); - return; - } - - if LIKELY(n == 1) - { - /* Special handling for the easy and normal case. */ - ALfilter *filter{AllocFilter(device)}; - if(filter) filters[0] = filter->id; - } - else - { - /* Store the allocated buffer IDs in a separate local list, to avoid - * modifying the user storage in case of failure. - */ - al::vector ids; - ids.reserve(static_cast(n)); - do { - ALfilter *filter{AllocFilter(device)}; - ids.emplace_back(filter->id); - } while(--n); - std::copy(ids.begin(), ids.end(), filters); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alDeleteFilters(ALsizei n, const ALuint *filters) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - if UNLIKELY(n < 0) - context->setError(AL_INVALID_VALUE, "Deleting %d filters", n); - if UNLIKELY(n <= 0) return; - - ALCdevice *device{context->mDevice.get()}; - std::lock_guard _{device->FilterLock}; - - /* First try to find any filters that are invalid. */ - auto validate_filter = [device](const ALuint fid) -> bool - { return !fid || LookupFilter(device, fid) != nullptr; }; - - const ALuint *filters_end = filters + n; - auto invflt = std::find_if_not(filters, filters_end, validate_filter); - if UNLIKELY(invflt != filters_end) - { - context->setError(AL_INVALID_NAME, "Invalid filter ID %u", *invflt); - return; - } - - /* All good. Delete non-0 filter IDs. */ - auto delete_filter = [device](const ALuint fid) -> void - { - ALfilter *filter{fid ? LookupFilter(device, fid) : nullptr}; - if(filter) FreeFilter(device, filter); - }; - std::for_each(filters, filters_end, delete_filter); -} -END_API_FUNC - -AL_API ALboolean AL_APIENTRY alIsFilter(ALuint filter) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if LIKELY(context) - { - ALCdevice *device{context->mDevice.get()}; - std::lock_guard _{device->FilterLock}; - if(!filter || LookupFilter(device, filter)) - return AL_TRUE; - } - return AL_FALSE; -} -END_API_FUNC - - -AL_API void AL_APIENTRY alFilteri(ALuint filter, ALenum param, ALint value) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - ALCdevice *device{context->mDevice.get()}; - std::lock_guard _{device->FilterLock}; - - ALfilter *alfilt{LookupFilter(device, filter)}; - if UNLIKELY(!alfilt) - context->setError(AL_INVALID_NAME, "Invalid filter ID %u", filter); - else - { - if(param == AL_FILTER_TYPE) - { - if(value == AL_FILTER_NULL || value == AL_FILTER_LOWPASS - || value == AL_FILTER_HIGHPASS || value == AL_FILTER_BANDPASS) - InitFilterParams(alfilt, value); - else - context->setError(AL_INVALID_VALUE, "Invalid filter type 0x%04x", value); - } - else try - { - /* Call the appropriate handler */ - alfilt->setParami(param, value); - } - catch(filter_exception &e) { - context->setError(e.errorCode(), "%s", e.what()); - } - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alFilteriv(ALuint filter, ALenum param, const ALint *values) -START_API_FUNC -{ - switch(param) - { - case AL_FILTER_TYPE: - alFilteri(filter, param, values[0]); - return; - } - - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - ALCdevice *device{context->mDevice.get()}; - std::lock_guard _{device->FilterLock}; - - ALfilter *alfilt{LookupFilter(device, filter)}; - if UNLIKELY(!alfilt) - context->setError(AL_INVALID_NAME, "Invalid filter ID %u", filter); - else try - { - /* Call the appropriate handler */ - alfilt->setParamiv(param, values); - } - catch(filter_exception &e) { - context->setError(e.errorCode(), "%s", e.what()); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alFilterf(ALuint filter, ALenum param, ALfloat value) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - ALCdevice *device{context->mDevice.get()}; - std::lock_guard _{device->FilterLock}; - - ALfilter *alfilt{LookupFilter(device, filter)}; - if UNLIKELY(!alfilt) - context->setError(AL_INVALID_NAME, "Invalid filter ID %u", filter); - else try - { - /* Call the appropriate handler */ - alfilt->setParamf(param, value); - } - catch(filter_exception &e) { - context->setError(e.errorCode(), "%s", e.what()); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alFilterfv(ALuint filter, ALenum param, const ALfloat *values) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - ALCdevice *device{context->mDevice.get()}; - std::lock_guard _{device->FilterLock}; - - ALfilter *alfilt{LookupFilter(device, filter)}; - if UNLIKELY(!alfilt) - context->setError(AL_INVALID_NAME, "Invalid filter ID %u", filter); - else try - { - /* Call the appropriate handler */ - alfilt->setParamfv(param, values); - } - catch(filter_exception &e) { - context->setError(e.errorCode(), "%s", e.what()); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alGetFilteri(ALuint filter, ALenum param, ALint *value) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - ALCdevice *device{context->mDevice.get()}; - std::lock_guard _{device->FilterLock}; - - const ALfilter *alfilt{LookupFilter(device, filter)}; - if UNLIKELY(!alfilt) - context->setError(AL_INVALID_NAME, "Invalid filter ID %u", filter); - else - { - if(param == AL_FILTER_TYPE) - *value = alfilt->type; - else try - { - /* Call the appropriate handler */ - alfilt->getParami(param, value); - } - catch(filter_exception &e) { - context->setError(e.errorCode(), "%s", e.what()); - } - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alGetFilteriv(ALuint filter, ALenum param, ALint *values) -START_API_FUNC -{ - switch(param) - { - case AL_FILTER_TYPE: - alGetFilteri(filter, param, values); - return; - } - - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - ALCdevice *device{context->mDevice.get()}; - std::lock_guard _{device->FilterLock}; - - const ALfilter *alfilt{LookupFilter(device, filter)}; - if UNLIKELY(!alfilt) - context->setError(AL_INVALID_NAME, "Invalid filter ID %u", filter); - else try - { - /* Call the appropriate handler */ - alfilt->getParamiv(param, values); - } - catch(filter_exception &e) { - context->setError(e.errorCode(), "%s", e.what()); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alGetFilterf(ALuint filter, ALenum param, ALfloat *value) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - ALCdevice *device{context->mDevice.get()}; - std::lock_guard _{device->FilterLock}; - - const ALfilter *alfilt{LookupFilter(device, filter)}; - if UNLIKELY(!alfilt) - context->setError(AL_INVALID_NAME, "Invalid filter ID %u", filter); - else try - { - /* Call the appropriate handler */ - alfilt->getParamf(param, value); - } - catch(filter_exception &e) { - context->setError(e.errorCode(), "%s", e.what()); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alGetFilterfv(ALuint filter, ALenum param, ALfloat *values) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - ALCdevice *device{context->mDevice.get()}; - std::lock_guard _{device->FilterLock}; - - const ALfilter *alfilt{LookupFilter(device, filter)}; - if UNLIKELY(!alfilt) - context->setError(AL_INVALID_NAME, "Invalid filter ID %u", filter); - else try - { - /* Call the appropriate handler */ - alfilt->getParamfv(param, values); - } - catch(filter_exception &e) { - context->setError(e.errorCode(), "%s", e.what()); - } -} -END_API_FUNC - - -FilterSubList::~FilterSubList() -{ - uint64_t usemask{~FreeMask}; - while(usemask) - { - const ALsizei idx{CountTrailingZeros(usemask)}; - al::destroy_at(Filters+idx); - usemask &= ~(1_u64 << idx); - } - FreeMask = ~usemask; - al_free(Filters); - Filters = nullptr; -} diff --git a/al/filter.h b/al/filter.h deleted file mode 100644 index 123e64b0..00000000 --- a/al/filter.h +++ /dev/null @@ -1,52 +0,0 @@ -#ifndef AL_FILTER_H -#define AL_FILTER_H - -#include "AL/al.h" -#include "AL/alc.h" -#include "AL/alext.h" - -#include "almalloc.h" - - -#define LOWPASSFREQREF 5000.0f -#define HIGHPASSFREQREF 250.0f - - -struct ALfilter { - ALenum type{AL_FILTER_NULL}; - - float Gain{1.0f}; - float GainHF{1.0f}; - float HFReference{LOWPASSFREQREF}; - float GainLF{1.0f}; - float LFReference{HIGHPASSFREQREF}; - - struct Vtable { - void (*const setParami )(ALfilter *filter, ALenum param, int val); - void (*const setParamiv)(ALfilter *filter, ALenum param, const int *vals); - void (*const setParamf )(ALfilter *filter, ALenum param, float val); - void (*const setParamfv)(ALfilter *filter, ALenum param, const float *vals); - - void (*const getParami )(const ALfilter *filter, ALenum param, int *val); - void (*const getParamiv)(const ALfilter *filter, ALenum param, int *vals); - void (*const getParamf )(const ALfilter *filter, ALenum param, float *val); - void (*const getParamfv)(const ALfilter *filter, ALenum param, float *vals); - }; - const Vtable *vtab{nullptr}; - - /* Self ID */ - ALuint id{0}; - - void setParami(ALenum param, int value) { vtab->setParami(this, param, value); } - void setParamiv(ALenum param, const int *values) { vtab->setParamiv(this, param, values); } - void setParamf(ALenum param, float value) { vtab->setParamf(this, param, value); } - void setParamfv(ALenum param, const float *values) { vtab->setParamfv(this, param, values); } - void getParami(ALenum param, int *value) const { vtab->getParami(this, param, value); } - void getParamiv(ALenum param, int *values) const { vtab->getParamiv(this, param, values); } - void getParamf(ALenum param, float *value) const { vtab->getParamf(this, param, value); } - void getParamfv(ALenum param, float *values) const { vtab->getParamfv(this, param, values); } - - DISABLE_ALLOC() -}; - -#endif diff --git a/al/listener.cpp b/al/listener.cpp deleted file mode 100644 index 4bbc145c..00000000 --- a/al/listener.cpp +++ /dev/null @@ -1,452 +0,0 @@ -/** - * OpenAL cross platform audio library - * Copyright (C) 1999-2000 by authors. - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - * Or go to http://www.gnu.org/copyleft/lgpl.html - */ - -#include "config.h" - -#include "listener.h" - -#include -#include - -#include "AL/al.h" -#include "AL/alc.h" -#include "AL/efx.h" - -#include "alcontext.h" -#include "almalloc.h" -#include "atomic.h" -#include "core/except.h" -#include "opthelpers.h" - - -#define DO_UPDATEPROPS() do { \ - if(!context->mDeferUpdates.load(std::memory_order_acquire)) \ - UpdateListenerProps(context.get()); \ - else \ - listener.PropsClean.clear(std::memory_order_release); \ -} while(0) - - -AL_API void AL_APIENTRY alListenerf(ALenum param, ALfloat value) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - ALlistener &listener = context->mListener; - std::lock_guard _{context->mPropLock}; - switch(param) - { - case AL_GAIN: - if(!(value >= 0.0f && std::isfinite(value))) - SETERR_RETURN(context, AL_INVALID_VALUE,, "Listener gain out of range"); - listener.Gain = value; - DO_UPDATEPROPS(); - break; - - case AL_METERS_PER_UNIT: - if(!(value >= AL_MIN_METERS_PER_UNIT && value <= AL_MAX_METERS_PER_UNIT)) - SETERR_RETURN(context, AL_INVALID_VALUE,, "Listener meters per unit out of range"); - listener.mMetersPerUnit = value; - DO_UPDATEPROPS(); - break; - - default: - context->setError(AL_INVALID_ENUM, "Invalid listener float property"); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alListener3f(ALenum param, ALfloat value1, ALfloat value2, ALfloat value3) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - ALlistener &listener = context->mListener; - std::lock_guard _{context->mPropLock}; - switch(param) - { - case AL_POSITION: - if(!(std::isfinite(value1) && std::isfinite(value2) && std::isfinite(value3))) - SETERR_RETURN(context, AL_INVALID_VALUE,, "Listener position out of range"); - listener.Position[0] = value1; - listener.Position[1] = value2; - listener.Position[2] = value3; - DO_UPDATEPROPS(); - break; - - case AL_VELOCITY: - if(!(std::isfinite(value1) && std::isfinite(value2) && std::isfinite(value3))) - SETERR_RETURN(context, AL_INVALID_VALUE,, "Listener velocity out of range"); - listener.Velocity[0] = value1; - listener.Velocity[1] = value2; - listener.Velocity[2] = value3; - DO_UPDATEPROPS(); - break; - - default: - context->setError(AL_INVALID_ENUM, "Invalid listener 3-float property"); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alListenerfv(ALenum param, const ALfloat *values) -START_API_FUNC -{ - if(values) - { - switch(param) - { - case AL_GAIN: - case AL_METERS_PER_UNIT: - alListenerf(param, values[0]); - return; - - case AL_POSITION: - case AL_VELOCITY: - alListener3f(param, values[0], values[1], values[2]); - return; - } - } - - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - ALlistener &listener = context->mListener; - std::lock_guard _{context->mPropLock}; - if(!values) SETERR_RETURN(context, AL_INVALID_VALUE,, "NULL pointer"); - switch(param) - { - case AL_ORIENTATION: - if(!(std::isfinite(values[0]) && std::isfinite(values[1]) && std::isfinite(values[2]) && - std::isfinite(values[3]) && std::isfinite(values[4]) && std::isfinite(values[5]))) - SETERR_RETURN(context, AL_INVALID_VALUE,, "Listener orientation out of range"); - /* AT then UP */ - listener.OrientAt[0] = values[0]; - listener.OrientAt[1] = values[1]; - listener.OrientAt[2] = values[2]; - listener.OrientUp[0] = values[3]; - listener.OrientUp[1] = values[4]; - listener.OrientUp[2] = values[5]; - DO_UPDATEPROPS(); - break; - - default: - context->setError(AL_INVALID_ENUM, "Invalid listener float-vector property"); - } -} -END_API_FUNC - - -AL_API void AL_APIENTRY alListeneri(ALenum param, ALint /*value*/) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - std::lock_guard _{context->mPropLock}; - switch(param) - { - default: - context->setError(AL_INVALID_ENUM, "Invalid listener integer property"); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alListener3i(ALenum param, ALint value1, ALint value2, ALint value3) -START_API_FUNC -{ - switch(param) - { - case AL_POSITION: - case AL_VELOCITY: - alListener3f(param, static_cast(value1), static_cast(value2), static_cast(value3)); - return; - } - - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - std::lock_guard _{context->mPropLock}; - switch(param) - { - default: - context->setError(AL_INVALID_ENUM, "Invalid listener 3-integer property"); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alListeneriv(ALenum param, const ALint *values) -START_API_FUNC -{ - if(values) - { - ALfloat fvals[6]; - switch(param) - { - case AL_POSITION: - case AL_VELOCITY: - alListener3f(param, static_cast(values[0]), static_cast(values[1]), static_cast(values[2])); - return; - - case AL_ORIENTATION: - fvals[0] = static_cast(values[0]); - fvals[1] = static_cast(values[1]); - fvals[2] = static_cast(values[2]); - fvals[3] = static_cast(values[3]); - fvals[4] = static_cast(values[4]); - fvals[5] = static_cast(values[5]); - alListenerfv(param, fvals); - return; - } - } - - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - std::lock_guard _{context->mPropLock}; - if(!values) - context->setError(AL_INVALID_VALUE, "NULL pointer"); - else switch(param) - { - default: - context->setError(AL_INVALID_ENUM, "Invalid listener integer-vector property"); - } -} -END_API_FUNC - - -AL_API void AL_APIENTRY alGetListenerf(ALenum param, ALfloat *value) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - ALlistener &listener = context->mListener; - std::lock_guard _{context->mPropLock}; - if(!value) - context->setError(AL_INVALID_VALUE, "NULL pointer"); - else switch(param) - { - case AL_GAIN: - *value = listener.Gain; - break; - - case AL_METERS_PER_UNIT: - *value = listener.mMetersPerUnit; - break; - - default: - context->setError(AL_INVALID_ENUM, "Invalid listener float property"); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alGetListener3f(ALenum param, ALfloat *value1, ALfloat *value2, ALfloat *value3) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - ALlistener &listener = context->mListener; - std::lock_guard _{context->mPropLock}; - if(!value1 || !value2 || !value3) - context->setError(AL_INVALID_VALUE, "NULL pointer"); - else switch(param) - { - case AL_POSITION: - *value1 = listener.Position[0]; - *value2 = listener.Position[1]; - *value3 = listener.Position[2]; - break; - - case AL_VELOCITY: - *value1 = listener.Velocity[0]; - *value2 = listener.Velocity[1]; - *value3 = listener.Velocity[2]; - break; - - default: - context->setError(AL_INVALID_ENUM, "Invalid listener 3-float property"); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alGetListenerfv(ALenum param, ALfloat *values) -START_API_FUNC -{ - switch(param) - { - case AL_GAIN: - case AL_METERS_PER_UNIT: - alGetListenerf(param, values); - return; - - case AL_POSITION: - case AL_VELOCITY: - alGetListener3f(param, values+0, values+1, values+2); - return; - } - - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - ALlistener &listener = context->mListener; - std::lock_guard _{context->mPropLock}; - if(!values) - context->setError(AL_INVALID_VALUE, "NULL pointer"); - else switch(param) - { - case AL_ORIENTATION: - // AT then UP - values[0] = listener.OrientAt[0]; - values[1] = listener.OrientAt[1]; - values[2] = listener.OrientAt[2]; - values[3] = listener.OrientUp[0]; - values[4] = listener.OrientUp[1]; - values[5] = listener.OrientUp[2]; - break; - - default: - context->setError(AL_INVALID_ENUM, "Invalid listener float-vector property"); - } -} -END_API_FUNC - - -AL_API void AL_APIENTRY alGetListeneri(ALenum param, ALint *value) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - std::lock_guard _{context->mPropLock}; - if(!value) - context->setError(AL_INVALID_VALUE, "NULL pointer"); - else switch(param) - { - default: - context->setError(AL_INVALID_ENUM, "Invalid listener integer property"); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alGetListener3i(ALenum param, ALint *value1, ALint *value2, ALint *value3) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - ALlistener &listener = context->mListener; - std::lock_guard _{context->mPropLock}; - if(!value1 || !value2 || !value3) - context->setError(AL_INVALID_VALUE, "NULL pointer"); - else switch(param) - { - case AL_POSITION: - *value1 = static_cast(listener.Position[0]); - *value2 = static_cast(listener.Position[1]); - *value3 = static_cast(listener.Position[2]); - break; - - case AL_VELOCITY: - *value1 = static_cast(listener.Velocity[0]); - *value2 = static_cast(listener.Velocity[1]); - *value3 = static_cast(listener.Velocity[2]); - break; - - default: - context->setError(AL_INVALID_ENUM, "Invalid listener 3-integer property"); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alGetListeneriv(ALenum param, ALint* values) -START_API_FUNC -{ - switch(param) - { - case AL_POSITION: - case AL_VELOCITY: - alGetListener3i(param, values+0, values+1, values+2); - return; - } - - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - ALlistener &listener = context->mListener; - std::lock_guard _{context->mPropLock}; - if(!values) - context->setError(AL_INVALID_VALUE, "NULL pointer"); - else switch(param) - { - case AL_ORIENTATION: - // AT then UP - values[0] = static_cast(listener.OrientAt[0]); - values[1] = static_cast(listener.OrientAt[1]); - values[2] = static_cast(listener.OrientAt[2]); - values[3] = static_cast(listener.OrientUp[0]); - values[4] = static_cast(listener.OrientUp[1]); - values[5] = static_cast(listener.OrientUp[2]); - break; - - default: - context->setError(AL_INVALID_ENUM, "Invalid listener integer-vector property"); - } -} -END_API_FUNC - - -void UpdateListenerProps(ALCcontext *context) -{ - /* Get an unused proprty container, or allocate a new one as needed. */ - ListenerProps *props{context->mFreeListenerProps.load(std::memory_order_acquire)}; - if(!props) - props = new ListenerProps{}; - else - { - ListenerProps *next; - do { - next = props->next.load(std::memory_order_relaxed); - } while(context->mFreeListenerProps.compare_exchange_weak(props, next, - std::memory_order_seq_cst, std::memory_order_acquire) == 0); - } - - /* Copy in current property values. */ - ALlistener &listener = context->mListener; - props->Position = listener.Position; - props->Velocity = listener.Velocity; - props->OrientAt = listener.OrientAt; - props->OrientUp = listener.OrientUp; - props->Gain = listener.Gain; - props->MetersPerUnit = listener.mMetersPerUnit; - - /* Set the new container for updating internal parameters. */ - props = context->mParams.ListenerUpdate.exchange(props, std::memory_order_acq_rel); - if(props) - { - /* If there was an unused update container, put it back in the - * freelist. - */ - AtomicReplaceHead(context->mFreeListenerProps, props); - } -} diff --git a/al/listener.h b/al/listener.h deleted file mode 100644 index 5f3ce3ec..00000000 --- a/al/listener.h +++ /dev/null @@ -1,31 +0,0 @@ -#ifndef AL_LISTENER_H -#define AL_LISTENER_H - -#include -#include - -#include "AL/al.h" -#include "AL/alc.h" -#include "AL/efx.h" - -#include "almalloc.h" - - -struct ALlistener { - std::array Position{{0.0f, 0.0f, 0.0f}}; - std::array Velocity{{0.0f, 0.0f, 0.0f}}; - std::array OrientAt{{0.0f, 0.0f, -1.0f}}; - std::array OrientUp{{0.0f, 1.0f, 0.0f}}; - float Gain{1.0f}; - float mMetersPerUnit{AL_DEFAULT_METERS_PER_UNIT}; - - std::atomic_flag PropsClean; - - ALlistener() { PropsClean.test_and_set(std::memory_order_relaxed); } - - DISABLE_ALLOC() -}; - -void UpdateListenerProps(ALCcontext *context); - -#endif diff --git a/al/source.cpp b/al/source.cpp deleted file mode 100644 index 770e3778..00000000 --- a/al/source.cpp +++ /dev/null @@ -1,3494 +0,0 @@ -/** - * OpenAL cross platform audio library - * Copyright (C) 1999-2007 by authors. - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - * Or go to http://www.gnu.org/copyleft/lgpl.html - */ - -#include "config.h" - -#include "source.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "AL/al.h" -#include "AL/alc.h" -#include "AL/alext.h" -#include "AL/efx.h" - -#include "alcmain.h" -#include "alcontext.h" -#include "almalloc.h" -#include "alnumeric.h" -#include "aloptional.h" -#include "alspan.h" -#include "alu.h" -#include "atomic.h" -#include "auxeffectslot.h" -#include "backends/base.h" -#include "bformatdec.h" -#include "buffer.h" -#include "core/ambidefs.h" -#include "core/except.h" -#include "core/filters/nfc.h" -#include "core/filters/splitter.h" -#include "core/logging.h" -#include "event.h" -#include "filter.h" -#include "inprogext.h" -#include "math_defs.h" -#include "opthelpers.h" -#include "ringbuffer.h" -#include "threads.h" -#include "voice_change.h" - - -namespace { - -using namespace std::placeholders; -using std::chrono::nanoseconds; - -Voice *GetSourceVoice(ALsource *source, ALCcontext *context) -{ - auto voicelist = context->getVoicesSpan(); - ALuint idx{source->VoiceIdx}; - if(idx < voicelist.size()) - { - ALuint sid{source->id}; - Voice *voice = voicelist[idx]; - if(voice->mSourceID.load(std::memory_order_acquire) == sid) - return voice; - } - source->VoiceIdx = INVALID_VOICE_IDX; - return nullptr; -} - - -void UpdateSourceProps(const ALsource *source, Voice *voice, ALCcontext *context) -{ - /* Get an unused property container, or allocate a new one as needed. */ - VoicePropsItem *props{context->mFreeVoiceProps.load(std::memory_order_acquire)}; - if(!props) - props = new VoicePropsItem{}; - else - { - VoicePropsItem *next; - do { - next = props->next.load(std::memory_order_relaxed); - } while(context->mFreeVoiceProps.compare_exchange_weak(props, next, - std::memory_order_acq_rel, std::memory_order_acquire) == 0); - } - - props->Pitch = source->Pitch; - props->Gain = source->Gain; - props->OuterGain = source->OuterGain; - props->MinGain = source->MinGain; - props->MaxGain = source->MaxGain; - props->InnerAngle = source->InnerAngle; - props->OuterAngle = source->OuterAngle; - props->RefDistance = source->RefDistance; - props->MaxDistance = source->MaxDistance; - props->RolloffFactor = source->RolloffFactor; - props->Position = source->Position; - props->Velocity = source->Velocity; - props->Direction = source->Direction; - props->OrientAt = source->OrientAt; - props->OrientUp = source->OrientUp; - props->HeadRelative = source->HeadRelative; - props->mDistanceModel = source->mDistanceModel; - props->mResampler = source->mResampler; - props->DirectChannels = source->DirectChannels; - props->mSpatializeMode = source->mSpatialize; - - props->DryGainHFAuto = source->DryGainHFAuto; - props->WetGainAuto = source->WetGainAuto; - props->WetGainHFAuto = source->WetGainHFAuto; - props->OuterGainHF = source->OuterGainHF; - - props->AirAbsorptionFactor = source->AirAbsorptionFactor; - props->RoomRolloffFactor = source->RoomRolloffFactor; - props->DopplerFactor = source->DopplerFactor; - - props->StereoPan = source->StereoPan; - - props->Radius = source->Radius; - - props->Direct.Gain = source->Direct.Gain; - props->Direct.GainHF = source->Direct.GainHF; - props->Direct.HFReference = source->Direct.HFReference; - props->Direct.GainLF = source->Direct.GainLF; - props->Direct.LFReference = source->Direct.LFReference; - - auto copy_send = [](const ALsource::SendData &srcsend) noexcept -> VoiceProps::SendData - { - VoiceProps::SendData ret{}; - ret.Slot = srcsend.Slot ? &srcsend.Slot->mSlot : nullptr; - ret.Gain = srcsend.Gain; - ret.GainHF = srcsend.GainHF; - ret.HFReference = srcsend.HFReference; - ret.GainLF = srcsend.GainLF; - ret.LFReference = srcsend.LFReference; - return ret; - }; - std::transform(source->Send.cbegin(), source->Send.cend(), props->Send, copy_send); - if(!props->Send[0].Slot && context->mDefaultSlot) - props->Send[0].Slot = &context->mDefaultSlot->mSlot; - - /* Set the new container for updating internal parameters. */ - props = voice->mUpdate.exchange(props, std::memory_order_acq_rel); - if(props) - { - /* If there was an unused update container, put it back in the - * freelist. - */ - AtomicReplaceHead(context->mFreeVoiceProps, props); - } -} - -/* GetSourceSampleOffset - * - * Gets the current read offset for the given Source, in 32.32 fixed-point - * samples. The offset is relative to the start of the queue (not the start of - * the current buffer). - */ -int64_t GetSourceSampleOffset(ALsource *Source, ALCcontext *context, nanoseconds *clocktime) -{ - ALCdevice *device{context->mDevice.get()}; - const BufferlistItem *Current{}; - uint64_t readPos{}; - ALuint refcount; - Voice *voice; - - do { - refcount = device->waitForMix(); - *clocktime = GetDeviceClockTime(device); - voice = GetSourceVoice(Source, context); - if(voice) - { - Current = voice->mCurrentBuffer.load(std::memory_order_relaxed); - - readPos = uint64_t{voice->mPosition.load(std::memory_order_relaxed)} << 32; - readPos |= uint64_t{voice->mPositionFrac.load(std::memory_order_relaxed)} << - (32-MixerFracBits); - } - std::atomic_thread_fence(std::memory_order_acquire); - } while(refcount != device->MixCount.load(std::memory_order_relaxed)); - - if(!voice) - return 0; - - const BufferlistItem *BufferList{Source->queue}; - while(BufferList && BufferList != Current) - { - readPos += uint64_t{BufferList->mSampleLen} << 32; - BufferList = BufferList->mNext.load(std::memory_order_relaxed); - } - return static_cast(minu64(readPos, 0x7fffffffffffffff_u64)); -} - -/* GetSourceSecOffset - * - * Gets the current read offset for the given Source, in seconds. The offset is - * relative to the start of the queue (not the start of the current buffer). - */ -double GetSourceSecOffset(ALsource *Source, ALCcontext *context, nanoseconds *clocktime) -{ - ALCdevice *device{context->mDevice.get()}; - const BufferlistItem *Current{}; - uint64_t readPos{}; - ALuint refcount; - Voice *voice; - - do { - refcount = device->waitForMix(); - *clocktime = GetDeviceClockTime(device); - voice = GetSourceVoice(Source, context); - if(voice) - { - Current = voice->mCurrentBuffer.load(std::memory_order_relaxed); - - readPos = uint64_t{voice->mPosition.load(std::memory_order_relaxed)} << MixerFracBits; - readPos |= voice->mPositionFrac.load(std::memory_order_relaxed); - } - std::atomic_thread_fence(std::memory_order_acquire); - } while(refcount != device->MixCount.load(std::memory_order_relaxed)); - - if(!voice) - return 0.0f; - - const BufferlistItem *BufferList{Source->queue}; - const BufferStorage *BufferFmt{nullptr}; - while(BufferList && BufferList != Current) - { - if(!BufferFmt) BufferFmt = BufferList->mBuffer; - readPos += uint64_t{BufferList->mSampleLen} << MixerFracBits; - BufferList = BufferList->mNext.load(std::memory_order_relaxed); - } - while(BufferList && !BufferFmt) - { - BufferFmt = BufferList->mBuffer; - BufferList = BufferList->mNext.load(std::memory_order_relaxed); - } - assert(BufferFmt != nullptr); - - return static_cast(readPos) / double{MixerFracOne} / BufferFmt->mSampleRate; -} - -/* GetSourceOffset - * - * Gets the current read offset for the given Source, in the appropriate format - * (Bytes, Samples or Seconds). The offset is relative to the start of the - * queue (not the start of the current buffer). - */ -double GetSourceOffset(ALsource *Source, ALenum name, ALCcontext *context) -{ - ALCdevice *device{context->mDevice.get()}; - const BufferlistItem *Current{}; - ALuint readPos{}; - ALuint readPosFrac{}; - ALuint refcount; - Voice *voice; - - do { - refcount = device->waitForMix(); - voice = GetSourceVoice(Source, context); - if(voice) - { - Current = voice->mCurrentBuffer.load(std::memory_order_relaxed); - - readPos = voice->mPosition.load(std::memory_order_relaxed); - readPosFrac = voice->mPositionFrac.load(std::memory_order_relaxed); - } - std::atomic_thread_fence(std::memory_order_acquire); - } while(refcount != device->MixCount.load(std::memory_order_relaxed)); - - if(!voice) - return 0.0; - - const BufferlistItem *BufferList{Source->queue}; - const ALbuffer *BufferFmt{nullptr}; - while(BufferList) - { - if(!BufferFmt) - BufferFmt = static_cast(BufferList->mBuffer); - if(BufferList == Current) break; - - readPos += BufferList->mSampleLen; - - BufferList = BufferList->mNext.load(std::memory_order_relaxed); - } - while(BufferList && !BufferFmt) - { - BufferFmt = static_cast(BufferList->mBuffer); - BufferList = BufferList->mNext.load(std::memory_order_relaxed); - } - assert(BufferFmt != nullptr); - - double offset{}; - switch(name) - { - case AL_SEC_OFFSET: - offset = (readPos + readPosFrac/double{MixerFracOne}) / BufferFmt->mSampleRate; - break; - - case AL_SAMPLE_OFFSET: - offset = readPos + readPosFrac/double{MixerFracOne}; - break; - - case AL_BYTE_OFFSET: - if(BufferFmt->OriginalType == UserFmtIMA4) - { - ALuint FrameBlockSize{BufferFmt->OriginalAlign}; - ALuint align{(BufferFmt->OriginalAlign-1)/2 + 4}; - ALuint BlockSize{align * BufferFmt->channelsFromFmt()}; - - /* Round down to nearest ADPCM block */ - offset = static_cast(readPos / FrameBlockSize * BlockSize); - } - else if(BufferFmt->OriginalType == UserFmtMSADPCM) - { - ALuint FrameBlockSize{BufferFmt->OriginalAlign}; - ALuint align{(FrameBlockSize-2)/2 + 7}; - ALuint BlockSize{align * BufferFmt->channelsFromFmt()}; - - /* Round down to nearest ADPCM block */ - offset = static_cast(readPos / FrameBlockSize * BlockSize); - } - else - { - const ALuint FrameSize{BufferFmt->frameSizeFromFmt()}; - offset = static_cast(readPos * FrameSize); - } - break; - } - return offset; -} - - -struct VoicePos { - ALuint pos, frac; - BufferlistItem *bufferitem; -}; - -/** - * GetSampleOffset - * - * Retrieves the voice position, fixed-point fraction, and bufferlist item - * using the givem offset type and offset. If the offset is out of range, - * returns an empty optional. - */ -al::optional GetSampleOffset(BufferlistItem *BufferList, ALenum OffsetType, - double Offset) -{ - /* Find the first valid Buffer in the Queue */ - const ALbuffer *BufferFmt{nullptr}; - while(BufferList) - { - BufferFmt = static_cast(BufferList->mBuffer); - if(BufferFmt != nullptr) break; - BufferList = BufferList->mNext.load(std::memory_order_relaxed); - } - if(!BufferList) - return al::nullopt; - - /* Get sample frame offset */ - ALuint offset{0u}, frac{0u}; - double dbloff, dblfrac; - switch(OffsetType) - { - case AL_SEC_OFFSET: - dblfrac = std::modf(Offset*BufferFmt->mSampleRate, &dbloff); - offset = static_cast(mind(dbloff, std::numeric_limits::max())); - frac = static_cast(mind(dblfrac*MixerFracOne, MixerFracOne-1.0)); - break; - - case AL_SAMPLE_OFFSET: - dblfrac = std::modf(Offset, &dbloff); - offset = static_cast(mind(dbloff, std::numeric_limits::max())); - frac = static_cast(mind(dblfrac*MixerFracOne, MixerFracOne-1.0)); - break; - - case AL_BYTE_OFFSET: - /* Determine the ByteOffset (and ensure it is block aligned) */ - offset = static_cast(Offset); - if(BufferFmt->OriginalType == UserFmtIMA4) - { - const ALuint align{(BufferFmt->OriginalAlign-1)/2 + 4}; - offset /= align * BufferFmt->channelsFromFmt(); - offset *= BufferFmt->OriginalAlign; - } - else if(BufferFmt->OriginalType == UserFmtMSADPCM) - { - const ALuint align{(BufferFmt->OriginalAlign-2)/2 + 7}; - offset /= align * BufferFmt->channelsFromFmt(); - offset *= BufferFmt->OriginalAlign; - } - else - offset /= BufferFmt->frameSizeFromFmt(); - frac = 0; - break; - } - - /* Find the bufferlist item this offset belongs to. */ - ALuint totalBufferLen{0u}; - while(BufferList && totalBufferLen <= offset) - { - if(BufferList->mSampleLen > offset-totalBufferLen) - { - /* Offset is in this buffer */ - return al::make_optional(VoicePos{offset-totalBufferLen, frac, BufferList}); - } - totalBufferLen += BufferList->mSampleLen; - - BufferList = BufferList->mNext.load(std::memory_order_relaxed); - } - - /* Offset is out of range of the queue */ - return al::nullopt; -} - - -void InitVoice(Voice *voice, ALsource *source, BufferlistItem *BufferList, ALCcontext *context, - ALCdevice *device) -{ - voice->mLoopBuffer.store(source->Looping ? source->queue : nullptr, std::memory_order_relaxed); - - BufferStorage *buffer{BufferList->mBuffer}; - ALuint num_channels{buffer->channelsFromFmt()}; - voice->mFrequency = buffer->mSampleRate; - voice->mFmtChannels = buffer->mChannels; - voice->mSampleSize = buffer->bytesFromFmt(); - voice->mAmbiLayout = buffer->mAmbiLayout; - voice->mAmbiScaling = buffer->mAmbiScaling; - voice->mAmbiOrder = buffer->mAmbiOrder; - - if(buffer->mCallback) voice->mFlags |= VoiceIsCallback; - else if(source->SourceType == AL_STATIC) voice->mFlags |= VoiceIsStatic; - voice->mNumCallbackSamples = 0; - - /* Clear the stepping value explicitly so the mixer knows not to mix this - * until the update gets applied. - */ - voice->mStep = 0; - - if(voice->mChans.capacity() > 2 && num_channels < voice->mChans.capacity()) - al::vector{}.swap(voice->mChans); - voice->mChans.reserve(maxu(2, num_channels)); - voice->mChans.resize(num_channels); - - /* Don't need to set the VOICE_IS_AMBISONIC flag if the device is not - * higher order than the voice. No HF scaling is necessary to mix it. - */ - if(voice->mAmbiOrder && device->mAmbiOrder > voice->mAmbiOrder) - { - const uint8_t *OrderFromChan{(voice->mFmtChannels == FmtBFormat2D) ? - AmbiIndex::OrderFrom2DChannel().data() : - AmbiIndex::OrderFromChannel().data()}; - const auto scales = BFormatDec::GetHFOrderScales(voice->mAmbiOrder, device->mAmbiOrder); - - const BandSplitter splitter{device->mXOverFreq / static_cast(device->Frequency)}; - - for(auto &chandata : voice->mChans) - { - chandata.mPrevSamples.fill(0.0f); - chandata.mAmbiScale = scales[*(OrderFromChan++)]; - chandata.mAmbiSplitter = splitter; - chandata.mDryParams = DirectParams{}; - std::fill_n(chandata.mWetParams.begin(), device->NumAuxSends, SendParams{}); - } - - voice->mFlags |= VoiceIsAmbisonic; - } - else - { - /* Clear previous samples. */ - for(auto &chandata : voice->mChans) - { - chandata.mPrevSamples.fill(0.0f); - chandata.mDryParams = DirectParams{}; - std::fill_n(chandata.mWetParams.begin(), device->NumAuxSends, SendParams{}); - } - } - - if(device->AvgSpeakerDist > 0.0f) - { - const float w1{SpeedOfSoundMetersPerSec / - (device->AvgSpeakerDist * static_cast(device->Frequency))}; - for(auto &chandata : voice->mChans) - chandata.mDryParams.NFCtrlFilter.init(w1); - } - - source->PropsClean.test_and_set(std::memory_order_acq_rel); - UpdateSourceProps(source, voice, context); - - voice->mSourceID.store(source->id, std::memory_order_release); -} - - -VoiceChange *GetVoiceChanger(ALCcontext *ctx) -{ - VoiceChange *vchg{ctx->mVoiceChangeTail}; - if UNLIKELY(vchg == ctx->mCurrentVoiceChange.load(std::memory_order_acquire)) - { - ctx->allocVoiceChanges(1); - vchg = ctx->mVoiceChangeTail; - } - - ctx->mVoiceChangeTail = vchg->mNext.exchange(nullptr, std::memory_order_relaxed); - - return vchg; -} - -void SendVoiceChanges(ALCcontext *ctx, VoiceChange *tail) -{ - ALCdevice *device{ctx->mDevice.get()}; - - VoiceChange *oldhead{ctx->mCurrentVoiceChange.load(std::memory_order_acquire)}; - while(VoiceChange *next{oldhead->mNext.load(std::memory_order_relaxed)}) - oldhead = next; - oldhead->mNext.store(tail, std::memory_order_release); - - const bool connected{device->Connected.load(std::memory_order_acquire)}; - device->waitForMix(); - if UNLIKELY(!connected) - { - /* If the device is disconnected, just ignore all pending changes. */ - VoiceChange *cur{ctx->mCurrentVoiceChange.load(std::memory_order_acquire)}; - while(VoiceChange *next{cur->mNext.load(std::memory_order_acquire)}) - { - cur = next; - if(Voice *voice{cur->mVoice}) - voice->mSourceID.store(0, std::memory_order_relaxed); - } - ctx->mCurrentVoiceChange.store(cur, std::memory_order_release); - } -} - - -bool SetVoiceOffset(Voice *oldvoice, const VoicePos &vpos, ALsource *source, ALCcontext *context, - ALCdevice *device) -{ - /* First, get a free voice to start at the new offset. */ - auto voicelist = context->getVoicesSpan(); - Voice *newvoice{}; - ALuint vidx{0}; - for(Voice *voice : voicelist) - { - if(voice->mPlayState.load(std::memory_order_acquire) == Voice::Stopped - && voice->mSourceID.load(std::memory_order_relaxed) == 0u - && voice->mPendingChange.load(std::memory_order_relaxed) == false) - { - newvoice = voice; - break; - } - ++vidx; - } - if UNLIKELY(!newvoice) - { - auto &allvoices = *context->mVoices.load(std::memory_order_relaxed); - if(allvoices.size() == voicelist.size()) - context->allocVoices(1); - context->mActiveVoiceCount.fetch_add(1, std::memory_order_release); - voicelist = context->getVoicesSpan(); - - vidx = 0; - for(Voice *voice : voicelist) - { - if(voice->mPlayState.load(std::memory_order_acquire) == Voice::Stopped - && voice->mSourceID.load(std::memory_order_relaxed) == 0u - && voice->mPendingChange.load(std::memory_order_relaxed) == false) - { - newvoice = voice; - break; - } - ++vidx; - } - } - - /* Initialize the new voice and set its starting offset. - * TODO: It might be better to have the VoiceChange processing copy the old - * voice's mixing parameters (and pending update) insead of initializing it - * all here. This would just need to set the minimum properties to link the - * voice to the source and its position-dependent properties (including the - * fading flag). - */ - newvoice->mPlayState.store(Voice::Pending, std::memory_order_relaxed); - newvoice->mPosition.store(vpos.pos, std::memory_order_relaxed); - newvoice->mPositionFrac.store(vpos.frac, std::memory_order_relaxed); - newvoice->mCurrentBuffer.store(vpos.bufferitem, std::memory_order_relaxed); - newvoice->mFlags = (vpos.pos > 0 || vpos.frac > 0 || vpos.bufferitem != source->queue) ? - VoiceIsFading : 0u; - InitVoice(newvoice, source, source->queue, context, device); - source->VoiceIdx = vidx; - - /* Set the old voice as having a pending change, and send it off with the - * new one with a new offset voice change. - */ - oldvoice->mPendingChange.store(true, std::memory_order_relaxed); - - VoiceChange *vchg{GetVoiceChanger(context)}; - vchg->mOldVoice = oldvoice; - vchg->mVoice = newvoice; - vchg->mSourceID = source->id; - vchg->mState = VChangeState::Restart; - SendVoiceChanges(context, vchg); - - /* If the old voice still has a sourceID, it's still active and the change- - * over will work on the next update. - */ - if LIKELY(oldvoice->mSourceID.load(std::memory_order_acquire) != 0u) - return true; - - /* Otherwise, if the new voice's state is not pending, the change-over - * already happened. - */ - if(newvoice->mPlayState.load(std::memory_order_acquire) != Voice::Pending) - return true; - - /* Otherwise, wait for any current mix to finish and check one last time. */ - device->waitForMix(); - if(newvoice->mPlayState.load(std::memory_order_acquire) != Voice::Pending) - return true; - /* The change-over failed because the old voice stopped before the new - * voice could start at the new offset. Let go of the new voice and have - * the caller store the source offset since it's stopped. - */ - newvoice->mCurrentBuffer.store(nullptr, std::memory_order_relaxed); - newvoice->mLoopBuffer.store(nullptr, std::memory_order_relaxed); - newvoice->mSourceID.store(0u, std::memory_order_relaxed); - newvoice->mPlayState.store(Voice::Stopped, std::memory_order_relaxed); - return false; -} - - -/** - * Returns if the last known state for the source was playing or paused. Does - * not sync with the mixer voice. - */ -inline bool IsPlayingOrPaused(ALsource *source) -{ return source->state == AL_PLAYING || source->state == AL_PAUSED; } - -/** - * Returns an updated source state using the matching voice's status (or lack - * thereof). - */ -inline ALenum GetSourceState(ALsource *source, Voice *voice) -{ - if(!voice && source->state == AL_PLAYING) - source->state = AL_STOPPED; - return source->state; -} - -/** - * Returns if the source should specify an update, given the context's - * deferring state and the source's last known state. - */ -inline bool SourceShouldUpdate(ALsource *source, ALCcontext *context) -{ - return !context->mDeferUpdates.load(std::memory_order_acquire) && - IsPlayingOrPaused(source); -} - - -bool EnsureSources(ALCcontext *context, size_t needed) -{ - size_t count{std::accumulate(context->mSourceList.cbegin(), context->mSourceList.cend(), - size_t{0}, - [](size_t cur, const SourceSubList &sublist) noexcept -> size_t - { return cur + static_cast(PopCount(sublist.FreeMask)); })}; - - while(needed > count) - { - if UNLIKELY(context->mSourceList.size() >= 1<<25) - return false; - - context->mSourceList.emplace_back(); - auto sublist = context->mSourceList.end() - 1; - sublist->FreeMask = ~0_u64; - sublist->Sources = static_cast(al_calloc(alignof(ALsource), sizeof(ALsource)*64)); - if UNLIKELY(!sublist->Sources) - { - context->mSourceList.pop_back(); - return false; - } - count += 64; - } - return true; -} - -ALsource *AllocSource(ALCcontext *context) -{ - auto sublist = std::find_if(context->mSourceList.begin(), context->mSourceList.end(), - [](const SourceSubList &entry) noexcept -> bool - { return entry.FreeMask != 0; } - ); - auto lidx = static_cast(std::distance(context->mSourceList.begin(), sublist)); - auto slidx = static_cast(CountTrailingZeros(sublist->FreeMask)); - - ALsource *source{::new(sublist->Sources + slidx) ALsource{}}; - - /* Add 1 to avoid source ID 0. */ - source->id = ((lidx<<6) | slidx) + 1; - - context->mNumSources += 1; - sublist->FreeMask &= ~(1_u64 << slidx); - - return source; -} - -void FreeSource(ALCcontext *context, ALsource *source) -{ - const ALuint id{source->id - 1}; - const size_t lidx{id >> 6}; - const ALuint slidx{id & 0x3f}; - - if(IsPlayingOrPaused(source)) - { - if(Voice *voice{GetSourceVoice(source, context)}) - { - VoiceChange *vchg{GetVoiceChanger(context)}; - - voice->mPendingChange.store(true, std::memory_order_relaxed); - vchg->mVoice = voice; - vchg->mSourceID = source->id; - vchg->mState = VChangeState::Stop; - - SendVoiceChanges(context, vchg); - } - } - - al::destroy_at(source); - - context->mSourceList[lidx].FreeMask |= 1_u64 << slidx; - context->mNumSources--; -} - - -inline ALsource *LookupSource(ALCcontext *context, ALuint id) noexcept -{ - const size_t lidx{(id-1) >> 6}; - const ALuint slidx{(id-1) & 0x3f}; - - if UNLIKELY(lidx >= context->mSourceList.size()) - return nullptr; - SourceSubList &sublist{context->mSourceList[lidx]}; - if UNLIKELY(sublist.FreeMask & (1_u64 << slidx)) - return nullptr; - return sublist.Sources + slidx; -} - -inline ALbuffer *LookupBuffer(ALCdevice *device, ALuint id) noexcept -{ - const size_t lidx{(id-1) >> 6}; - const ALuint slidx{(id-1) & 0x3f}; - - if UNLIKELY(lidx >= device->BufferList.size()) - return nullptr; - BufferSubList &sublist = device->BufferList[lidx]; - if UNLIKELY(sublist.FreeMask & (1_u64 << slidx)) - return nullptr; - return sublist.Buffers + slidx; -} - -inline ALfilter *LookupFilter(ALCdevice *device, ALuint id) noexcept -{ - const size_t lidx{(id-1) >> 6}; - const ALuint slidx{(id-1) & 0x3f}; - - if UNLIKELY(lidx >= device->FilterList.size()) - return nullptr; - FilterSubList &sublist = device->FilterList[lidx]; - if UNLIKELY(sublist.FreeMask & (1_u64 << slidx)) - return nullptr; - return sublist.Filters + slidx; -} - -inline ALeffectslot *LookupEffectSlot(ALCcontext *context, ALuint id) noexcept -{ - const size_t lidx{(id-1) >> 6}; - const ALuint slidx{(id-1) & 0x3f}; - - if UNLIKELY(lidx >= context->mEffectSlotList.size()) - return nullptr; - EffectSlotSubList &sublist{context->mEffectSlotList[lidx]}; - if UNLIKELY(sublist.FreeMask & (1_u64 << slidx)) - return nullptr; - return sublist.EffectSlots + slidx; -} - - -al::optional SpatializeModeFromEnum(ALenum mode) -{ - switch(mode) - { - case AL_FALSE: return al::make_optional(SpatializeMode::Off); - case AL_TRUE: return al::make_optional(SpatializeMode::On); - case AL_AUTO_SOFT: return al::make_optional(SpatializeMode::Auto); - } - WARN("Unsupported spatialize mode: 0x%04x\n", mode); - return al::nullopt; -} -ALenum EnumFromSpatializeMode(SpatializeMode mode) -{ - switch(mode) - { - case SpatializeMode::Off: return AL_FALSE; - case SpatializeMode::On: return AL_TRUE; - case SpatializeMode::Auto: return AL_AUTO_SOFT; - } - throw std::runtime_error{"Invalid SpatializeMode: "+std::to_string(int(mode))}; -} - -al::optional DirectModeFromEnum(ALenum mode) -{ - switch(mode) - { - case AL_FALSE: return al::make_optional(DirectMode::Off); - case AL_DROP_UNMATCHED_SOFT: return al::make_optional(DirectMode::DropMismatch); - case AL_REMIX_UNMATCHED_SOFT: return al::make_optional(DirectMode::RemixMismatch); - } - WARN("Unsupported direct mode: 0x%04x\n", mode); - return al::nullopt; -} -ALenum EnumFromDirectMode(DirectMode mode) -{ - switch(mode) - { - case DirectMode::Off: return AL_FALSE; - case DirectMode::DropMismatch: return AL_DROP_UNMATCHED_SOFT; - case DirectMode::RemixMismatch: return AL_REMIX_UNMATCHED_SOFT; - } - throw std::runtime_error{"Invalid DirectMode: "+std::to_string(int(mode))}; -} - -al::optional DistanceModelFromALenum(ALenum model) -{ - switch(model) - { - case AL_NONE: return al::make_optional(DistanceModel::Disable); - case AL_INVERSE_DISTANCE: return al::make_optional(DistanceModel::Inverse); - case AL_INVERSE_DISTANCE_CLAMPED: return al::make_optional(DistanceModel::InverseClamped); - case AL_LINEAR_DISTANCE: return al::make_optional(DistanceModel::Linear); - case AL_LINEAR_DISTANCE_CLAMPED: return al::make_optional(DistanceModel::LinearClamped); - case AL_EXPONENT_DISTANCE: return al::make_optional(DistanceModel::Exponent); - case AL_EXPONENT_DISTANCE_CLAMPED: return al::make_optional(DistanceModel::ExponentClamped); - } - return al::nullopt; -} -ALenum ALenumFromDistanceModel(DistanceModel model) -{ - switch(model) - { - case DistanceModel::Disable: return AL_NONE; - case DistanceModel::Inverse: return AL_INVERSE_DISTANCE; - case DistanceModel::InverseClamped: return AL_INVERSE_DISTANCE_CLAMPED; - case DistanceModel::Linear: return AL_LINEAR_DISTANCE; - case DistanceModel::LinearClamped: return AL_LINEAR_DISTANCE_CLAMPED; - case DistanceModel::Exponent: return AL_EXPONENT_DISTANCE; - case DistanceModel::ExponentClamped: return AL_EXPONENT_DISTANCE_CLAMPED; - } - throw std::runtime_error{"Unexpected distance model "+std::to_string(static_cast(model))}; -} - -enum SourceProp : ALenum { - srcPitch = AL_PITCH, - srcGain = AL_GAIN, - srcMinGain = AL_MIN_GAIN, - srcMaxGain = AL_MAX_GAIN, - srcMaxDistance = AL_MAX_DISTANCE, - srcRolloffFactor = AL_ROLLOFF_FACTOR, - srcDopplerFactor = AL_DOPPLER_FACTOR, - srcConeOuterGain = AL_CONE_OUTER_GAIN, - srcSecOffset = AL_SEC_OFFSET, - srcSampleOffset = AL_SAMPLE_OFFSET, - srcByteOffset = AL_BYTE_OFFSET, - srcConeInnerAngle = AL_CONE_INNER_ANGLE, - srcConeOuterAngle = AL_CONE_OUTER_ANGLE, - srcRefDistance = AL_REFERENCE_DISTANCE, - - srcPosition = AL_POSITION, - srcVelocity = AL_VELOCITY, - srcDirection = AL_DIRECTION, - - srcSourceRelative = AL_SOURCE_RELATIVE, - srcLooping = AL_LOOPING, - srcBuffer = AL_BUFFER, - srcSourceState = AL_SOURCE_STATE, - srcBuffersQueued = AL_BUFFERS_QUEUED, - srcBuffersProcessed = AL_BUFFERS_PROCESSED, - srcSourceType = AL_SOURCE_TYPE, - - /* ALC_EXT_EFX */ - srcConeOuterGainHF = AL_CONE_OUTER_GAINHF, - srcAirAbsorptionFactor = AL_AIR_ABSORPTION_FACTOR, - srcRoomRolloffFactor = AL_ROOM_ROLLOFF_FACTOR, - srcDirectFilterGainHFAuto = AL_DIRECT_FILTER_GAINHF_AUTO, - srcAuxSendFilterGainAuto = AL_AUXILIARY_SEND_FILTER_GAIN_AUTO, - srcAuxSendFilterGainHFAuto = AL_AUXILIARY_SEND_FILTER_GAINHF_AUTO, - srcDirectFilter = AL_DIRECT_FILTER, - srcAuxSendFilter = AL_AUXILIARY_SEND_FILTER, - - /* AL_SOFT_direct_channels */ - srcDirectChannelsSOFT = AL_DIRECT_CHANNELS_SOFT, - - /* AL_EXT_source_distance_model */ - srcDistanceModel = AL_DISTANCE_MODEL, - - /* AL_SOFT_source_latency */ - srcSampleOffsetLatencySOFT = AL_SAMPLE_OFFSET_LATENCY_SOFT, - srcSecOffsetLatencySOFT = AL_SEC_OFFSET_LATENCY_SOFT, - - /* AL_EXT_STEREO_ANGLES */ - srcAngles = AL_STEREO_ANGLES, - - /* AL_EXT_SOURCE_RADIUS */ - srcRadius = AL_SOURCE_RADIUS, - - /* AL_EXT_BFORMAT */ - srcOrientation = AL_ORIENTATION, - - /* AL_SOFT_source_resampler */ - srcResampler = AL_SOURCE_RESAMPLER_SOFT, - - /* AL_SOFT_source_spatialize */ - srcSpatialize = AL_SOURCE_SPATIALIZE_SOFT, - - /* ALC_SOFT_device_clock */ - srcSampleOffsetClockSOFT = AL_SAMPLE_OFFSET_CLOCK_SOFT, - srcSecOffsetClockSOFT = AL_SEC_OFFSET_CLOCK_SOFT, -}; - - -constexpr size_t MaxValues{6u}; - -ALuint FloatValsByProp(ALenum prop) -{ - switch(static_cast(prop)) - { - case AL_PITCH: - case AL_GAIN: - case AL_MIN_GAIN: - case AL_MAX_GAIN: - case AL_MAX_DISTANCE: - case AL_ROLLOFF_FACTOR: - case AL_DOPPLER_FACTOR: - case AL_CONE_OUTER_GAIN: - case AL_SEC_OFFSET: - case AL_SAMPLE_OFFSET: - case AL_BYTE_OFFSET: - case AL_CONE_INNER_ANGLE: - case AL_CONE_OUTER_ANGLE: - case AL_REFERENCE_DISTANCE: - case AL_CONE_OUTER_GAINHF: - case AL_AIR_ABSORPTION_FACTOR: - case AL_ROOM_ROLLOFF_FACTOR: - case AL_DIRECT_FILTER_GAINHF_AUTO: - case AL_AUXILIARY_SEND_FILTER_GAIN_AUTO: - case AL_AUXILIARY_SEND_FILTER_GAINHF_AUTO: - case AL_DIRECT_CHANNELS_SOFT: - case AL_DISTANCE_MODEL: - case AL_SOURCE_RELATIVE: - case AL_LOOPING: - case AL_SOURCE_STATE: - case AL_BUFFERS_QUEUED: - case AL_BUFFERS_PROCESSED: - case AL_SOURCE_TYPE: - case AL_SOURCE_RADIUS: - case AL_SOURCE_RESAMPLER_SOFT: - case AL_SOURCE_SPATIALIZE_SOFT: - return 1; - - case AL_STEREO_ANGLES: - return 2; - - case AL_POSITION: - case AL_VELOCITY: - case AL_DIRECTION: - return 3; - - case AL_ORIENTATION: - return 6; - - case AL_SEC_OFFSET_LATENCY_SOFT: - case AL_SEC_OFFSET_CLOCK_SOFT: - break; /* Double only */ - - case AL_BUFFER: - case AL_DIRECT_FILTER: - case AL_AUXILIARY_SEND_FILTER: - break; /* i/i64 only */ - case AL_SAMPLE_OFFSET_LATENCY_SOFT: - case AL_SAMPLE_OFFSET_CLOCK_SOFT: - break; /* i64 only */ - } - return 0; -} -ALuint DoubleValsByProp(ALenum prop) -{ - switch(static_cast(prop)) - { - case AL_PITCH: - case AL_GAIN: - case AL_MIN_GAIN: - case AL_MAX_GAIN: - case AL_MAX_DISTANCE: - case AL_ROLLOFF_FACTOR: - case AL_DOPPLER_FACTOR: - case AL_CONE_OUTER_GAIN: - case AL_SEC_OFFSET: - case AL_SAMPLE_OFFSET: - case AL_BYTE_OFFSET: - case AL_CONE_INNER_ANGLE: - case AL_CONE_OUTER_ANGLE: - case AL_REFERENCE_DISTANCE: - case AL_CONE_OUTER_GAINHF: - case AL_AIR_ABSORPTION_FACTOR: - case AL_ROOM_ROLLOFF_FACTOR: - case AL_DIRECT_FILTER_GAINHF_AUTO: - case AL_AUXILIARY_SEND_FILTER_GAIN_AUTO: - case AL_AUXILIARY_SEND_FILTER_GAINHF_AUTO: - case AL_DIRECT_CHANNELS_SOFT: - case AL_DISTANCE_MODEL: - case AL_SOURCE_RELATIVE: - case AL_LOOPING: - case AL_SOURCE_STATE: - case AL_BUFFERS_QUEUED: - case AL_BUFFERS_PROCESSED: - case AL_SOURCE_TYPE: - case AL_SOURCE_RADIUS: - case AL_SOURCE_RESAMPLER_SOFT: - case AL_SOURCE_SPATIALIZE_SOFT: - return 1; - - case AL_SEC_OFFSET_LATENCY_SOFT: - case AL_SEC_OFFSET_CLOCK_SOFT: - case AL_STEREO_ANGLES: - return 2; - - case AL_POSITION: - case AL_VELOCITY: - case AL_DIRECTION: - return 3; - - case AL_ORIENTATION: - return 6; - - case AL_BUFFER: - case AL_DIRECT_FILTER: - case AL_AUXILIARY_SEND_FILTER: - break; /* i/i64 only */ - case AL_SAMPLE_OFFSET_LATENCY_SOFT: - case AL_SAMPLE_OFFSET_CLOCK_SOFT: - break; /* i64 only */ - } - return 0; -} - - -bool SetSourcefv(ALsource *Source, ALCcontext *Context, SourceProp prop, const al::span values); -bool SetSourceiv(ALsource *Source, ALCcontext *Context, SourceProp prop, const al::span values); -bool SetSourcei64v(ALsource *Source, ALCcontext *Context, SourceProp prop, const al::span values); - -#define CHECKSIZE(v, s) do { \ - if LIKELY((v).size() == (s) || (v).size() == MaxValues) break; \ - Context->setError(AL_INVALID_ENUM, \ - "Property 0x%04x expects %d value(s), got %zu", prop, (s), \ - (v).size()); \ - return false; \ -} while(0) -#define CHECKVAL(x) do { \ - if LIKELY(x) break; \ - Context->setError(AL_INVALID_VALUE, "Value out of range"); \ - return false; \ -} while(0) - -bool UpdateSourceProps(ALsource *source, ALCcontext *context) -{ - Voice *voice; - if(SourceShouldUpdate(source, context) && (voice=GetSourceVoice(source, context)) != nullptr) - UpdateSourceProps(source, voice, context); - else - source->PropsClean.clear(std::memory_order_release); - return true; -} - -bool SetSourcefv(ALsource *Source, ALCcontext *Context, SourceProp prop, const al::span values) -{ - int ival; - - switch(prop) - { - case AL_SEC_OFFSET_LATENCY_SOFT: - case AL_SEC_OFFSET_CLOCK_SOFT: - /* Query only */ - SETERR_RETURN(Context, AL_INVALID_OPERATION, false, - "Setting read-only source property 0x%04x", prop); - - case AL_PITCH: - CHECKSIZE(values, 1); - CHECKVAL(values[0] >= 0.0f); - - Source->Pitch = values[0]; - return UpdateSourceProps(Source, Context); - - case AL_CONE_INNER_ANGLE: - CHECKSIZE(values, 1); - CHECKVAL(values[0] >= 0.0f && values[0] <= 360.0f); - - Source->InnerAngle = values[0]; - return UpdateSourceProps(Source, Context); - - case AL_CONE_OUTER_ANGLE: - CHECKSIZE(values, 1); - CHECKVAL(values[0] >= 0.0f && values[0] <= 360.0f); - - Source->OuterAngle = values[0]; - return UpdateSourceProps(Source, Context); - - case AL_GAIN: - CHECKSIZE(values, 1); - CHECKVAL(values[0] >= 0.0f); - - Source->Gain = values[0]; - return UpdateSourceProps(Source, Context); - - case AL_MAX_DISTANCE: - CHECKSIZE(values, 1); - CHECKVAL(values[0] >= 0.0f); - - Source->MaxDistance = values[0]; - return UpdateSourceProps(Source, Context); - - case AL_ROLLOFF_FACTOR: - CHECKSIZE(values, 1); - CHECKVAL(values[0] >= 0.0f); - - Source->RolloffFactor = values[0]; - return UpdateSourceProps(Source, Context); - - case AL_REFERENCE_DISTANCE: - CHECKSIZE(values, 1); - CHECKVAL(values[0] >= 0.0f); - - Source->RefDistance = values[0]; - return UpdateSourceProps(Source, Context); - - case AL_MIN_GAIN: - CHECKSIZE(values, 1); - CHECKVAL(values[0] >= 0.0f); - - Source->MinGain = values[0]; - return UpdateSourceProps(Source, Context); - - case AL_MAX_GAIN: - CHECKSIZE(values, 1); - CHECKVAL(values[0] >= 0.0f); - - Source->MaxGain = values[0]; - return UpdateSourceProps(Source, Context); - - case AL_CONE_OUTER_GAIN: - CHECKSIZE(values, 1); - CHECKVAL(values[0] >= 0.0f && values[0] <= 1.0f); - - Source->OuterGain = values[0]; - return UpdateSourceProps(Source, Context); - - case AL_CONE_OUTER_GAINHF: - CHECKSIZE(values, 1); - CHECKVAL(values[0] >= 0.0f && values[0] <= 1.0f); - - Source->OuterGainHF = values[0]; - return UpdateSourceProps(Source, Context); - - case AL_AIR_ABSORPTION_FACTOR: - CHECKSIZE(values, 1); - CHECKVAL(values[0] >= 0.0f && values[0] <= 10.0f); - - Source->AirAbsorptionFactor = values[0]; - return UpdateSourceProps(Source, Context); - - case AL_ROOM_ROLLOFF_FACTOR: - CHECKSIZE(values, 1); - CHECKVAL(values[0] >= 0.0f && values[0] <= 10.0f); - - Source->RoomRolloffFactor = values[0]; - return UpdateSourceProps(Source, Context); - - case AL_DOPPLER_FACTOR: - CHECKSIZE(values, 1); - CHECKVAL(values[0] >= 0.0f && values[0] <= 1.0f); - - Source->DopplerFactor = values[0]; - return UpdateSourceProps(Source, Context); - - case AL_SEC_OFFSET: - case AL_SAMPLE_OFFSET: - case AL_BYTE_OFFSET: - CHECKSIZE(values, 1); - CHECKVAL(values[0] >= 0.0f); - - if(Voice *voice{GetSourceVoice(Source, Context)}) - { - if((voice->mFlags&VoiceIsCallback)) - SETERR_RETURN(Context, AL_INVALID_VALUE, false, - "Source offset for callback is invalid"); - auto vpos = GetSampleOffset(Source->queue, prop, values[0]); - if(!vpos) SETERR_RETURN(Context, AL_INVALID_VALUE, false, "Invalid offset"); - - if(SetVoiceOffset(voice, *vpos, Source, Context, Context->mDevice.get())) - return true; - } - Source->OffsetType = prop; - Source->Offset = values[0]; - return true; - - case AL_SOURCE_RADIUS: - CHECKSIZE(values, 1); - CHECKVAL(values[0] >= 0.0f && std::isfinite(values[0])); - - Source->Radius = values[0]; - return UpdateSourceProps(Source, Context); - - case AL_STEREO_ANGLES: - CHECKSIZE(values, 2); - CHECKVAL(std::isfinite(values[0]) && std::isfinite(values[1])); - - Source->StereoPan[0] = values[0]; - Source->StereoPan[1] = values[1]; - return UpdateSourceProps(Source, Context); - - - case AL_POSITION: - CHECKSIZE(values, 3); - CHECKVAL(std::isfinite(values[0]) && std::isfinite(values[1]) && std::isfinite(values[2])); - - Source->Position[0] = values[0]; - Source->Position[1] = values[1]; - Source->Position[2] = values[2]; - return UpdateSourceProps(Source, Context); - - case AL_VELOCITY: - CHECKSIZE(values, 3); - CHECKVAL(std::isfinite(values[0]) && std::isfinite(values[1]) && std::isfinite(values[2])); - - Source->Velocity[0] = values[0]; - Source->Velocity[1] = values[1]; - Source->Velocity[2] = values[2]; - return UpdateSourceProps(Source, Context); - - case AL_DIRECTION: - CHECKSIZE(values, 3); - CHECKVAL(std::isfinite(values[0]) && std::isfinite(values[1]) && std::isfinite(values[2])); - - Source->Direction[0] = values[0]; - Source->Direction[1] = values[1]; - Source->Direction[2] = values[2]; - return UpdateSourceProps(Source, Context); - - case AL_ORIENTATION: - CHECKSIZE(values, 6); - CHECKVAL(std::isfinite(values[0]) && std::isfinite(values[1]) && std::isfinite(values[2]) - && std::isfinite(values[3]) && std::isfinite(values[4]) && std::isfinite(values[5])); - - Source->OrientAt[0] = values[0]; - Source->OrientAt[1] = values[1]; - Source->OrientAt[2] = values[2]; - Source->OrientUp[0] = values[3]; - Source->OrientUp[1] = values[4]; - Source->OrientUp[2] = values[5]; - return UpdateSourceProps(Source, Context); - - - case AL_SOURCE_RELATIVE: - case AL_LOOPING: - case AL_SOURCE_STATE: - case AL_SOURCE_TYPE: - case AL_DISTANCE_MODEL: - case AL_DIRECT_FILTER_GAINHF_AUTO: - case AL_AUXILIARY_SEND_FILTER_GAIN_AUTO: - case AL_AUXILIARY_SEND_FILTER_GAINHF_AUTO: - case AL_DIRECT_CHANNELS_SOFT: - case AL_SOURCE_RESAMPLER_SOFT: - case AL_SOURCE_SPATIALIZE_SOFT: - CHECKSIZE(values, 1); - ival = static_cast(values[0]); - return SetSourceiv(Source, Context, prop, {&ival, 1u}); - - case AL_BUFFERS_QUEUED: - case AL_BUFFERS_PROCESSED: - CHECKSIZE(values, 1); - ival = static_cast(static_cast(values[0])); - return SetSourceiv(Source, Context, prop, {&ival, 1u}); - - case AL_BUFFER: - case AL_DIRECT_FILTER: - case AL_AUXILIARY_SEND_FILTER: - case AL_SAMPLE_OFFSET_LATENCY_SOFT: - case AL_SAMPLE_OFFSET_CLOCK_SOFT: - break; - } - - ERR("Unexpected property: 0x%04x\n", prop); - Context->setError(AL_INVALID_ENUM, "Invalid source float property 0x%04x", prop); - return false; -} - -bool SetSourceiv(ALsource *Source, ALCcontext *Context, SourceProp prop, const al::span values) -{ - ALCdevice *device{Context->mDevice.get()}; - ALeffectslot *slot{nullptr}; - BufferlistItem *oldlist{nullptr}; - std::unique_lock slotlock; - float fvals[6]; - - switch(prop) - { - case AL_SOURCE_STATE: - case AL_SOURCE_TYPE: - case AL_BUFFERS_QUEUED: - case AL_BUFFERS_PROCESSED: - /* Query only */ - SETERR_RETURN(Context, AL_INVALID_OPERATION, false, - "Setting read-only source property 0x%04x", prop); - - case AL_SOURCE_RELATIVE: - CHECKSIZE(values, 1); - CHECKVAL(values[0] == AL_FALSE || values[0] == AL_TRUE); - - Source->HeadRelative = values[0] != AL_FALSE; - return UpdateSourceProps(Source, Context); - - case AL_LOOPING: - CHECKSIZE(values, 1); - CHECKVAL(values[0] == AL_FALSE || values[0] == AL_TRUE); - - Source->Looping = values[0] != AL_FALSE; - if(IsPlayingOrPaused(Source)) - { - if(Voice *voice{GetSourceVoice(Source, Context)}) - { - if(Source->Looping) - voice->mLoopBuffer.store(Source->queue, std::memory_order_release); - else - voice->mLoopBuffer.store(nullptr, std::memory_order_release); - - /* If the source is playing, wait for the current mix to finish - * to ensure it isn't currently looping back or reaching the - * end. - */ - device->waitForMix(); - } - } - return true; - - case AL_BUFFER: - CHECKSIZE(values, 1); - { - const ALenum state{GetSourceState(Source, GetSourceVoice(Source, Context))}; - if(state == AL_PLAYING || state == AL_PAUSED) - SETERR_RETURN(Context, AL_INVALID_OPERATION, false, - "Setting buffer on playing or paused source %u", Source->id); - } - oldlist = Source->queue; - if(values[0]) - { - std::lock_guard _{device->BufferLock}; - ALbuffer *buffer{LookupBuffer(device, static_cast(values[0]))}; - if(!buffer) - SETERR_RETURN(Context, AL_INVALID_VALUE, false, "Invalid buffer ID %u", - static_cast(values[0])); - if(buffer->MappedAccess && !(buffer->MappedAccess&AL_MAP_PERSISTENT_BIT_SOFT)) - SETERR_RETURN(Context, AL_INVALID_OPERATION, false, - "Setting non-persistently mapped buffer %u", buffer->id); - if(buffer->mCallback && ReadRef(buffer->ref) != 0) - SETERR_RETURN(Context, AL_INVALID_OPERATION, false, - "Setting already-set callback buffer %u", buffer->id); - - /* Add the selected buffer to a one-item queue */ - auto newlist = new BufferlistItem{}; - newlist->mSampleLen = buffer->mSampleLen; - newlist->mBuffer = buffer; - IncrementRef(buffer->ref); - - /* Source is now Static */ - Source->SourceType = AL_STATIC; - Source->queue = newlist; - } - else - { - /* Source is now Undetermined */ - Source->SourceType = AL_UNDETERMINED; - Source->queue = nullptr; - } - - /* Delete all elements in the previous queue */ - while(oldlist != nullptr) - { - std::unique_ptr head{oldlist}; - oldlist = head->mNext.load(std::memory_order_relaxed); - - if(auto *buffer{static_cast(head->mBuffer)}) - DecrementRef(buffer->ref); - } - return true; - - case AL_SEC_OFFSET: - case AL_SAMPLE_OFFSET: - case AL_BYTE_OFFSET: - CHECKSIZE(values, 1); - CHECKVAL(values[0] >= 0); - - if(Voice *voice{GetSourceVoice(Source, Context)}) - { - if((voice->mFlags&VoiceIsCallback)) - SETERR_RETURN(Context, AL_INVALID_VALUE, false, - "Source offset for callback is invalid"); - auto vpos = GetSampleOffset(Source->queue, prop, values[0]); - if(!vpos) SETERR_RETURN(Context, AL_INVALID_VALUE, false, "Invalid source offset"); - - if(SetVoiceOffset(voice, *vpos, Source, Context, device)) - return true; - } - Source->OffsetType = prop; - Source->Offset = values[0]; - return true; - - case AL_DIRECT_FILTER: - CHECKSIZE(values, 1); - if(values[0]) - { - std::lock_guard _{device->FilterLock}; - ALfilter *filter{LookupFilter(device, static_cast(values[0]))}; - if(!filter) - SETERR_RETURN(Context, AL_INVALID_VALUE, false, "Invalid filter ID %u", - static_cast(values[0])); - Source->Direct.Gain = filter->Gain; - Source->Direct.GainHF = filter->GainHF; - Source->Direct.HFReference = filter->HFReference; - Source->Direct.GainLF = filter->GainLF; - Source->Direct.LFReference = filter->LFReference; - } - else - { - Source->Direct.Gain = 1.0f; - Source->Direct.GainHF = 1.0f; - Source->Direct.HFReference = LOWPASSFREQREF; - Source->Direct.GainLF = 1.0f; - Source->Direct.LFReference = HIGHPASSFREQREF; - } - return UpdateSourceProps(Source, Context); - - case AL_DIRECT_FILTER_GAINHF_AUTO: - CHECKSIZE(values, 1); - CHECKVAL(values[0] == AL_FALSE || values[0] == AL_TRUE); - - Source->DryGainHFAuto = values[0] != AL_FALSE; - return UpdateSourceProps(Source, Context); - - case AL_AUXILIARY_SEND_FILTER_GAIN_AUTO: - CHECKSIZE(values, 1); - CHECKVAL(values[0] == AL_FALSE || values[0] == AL_TRUE); - - Source->WetGainAuto = values[0] != AL_FALSE; - return UpdateSourceProps(Source, Context); - - case AL_AUXILIARY_SEND_FILTER_GAINHF_AUTO: - CHECKSIZE(values, 1); - CHECKVAL(values[0] == AL_FALSE || values[0] == AL_TRUE); - - Source->WetGainHFAuto = values[0] != AL_FALSE; - return UpdateSourceProps(Source, Context); - - case AL_DIRECT_CHANNELS_SOFT: - CHECKSIZE(values, 1); - if(auto mode = DirectModeFromEnum(values[0])) - { - Source->DirectChannels = *mode; - return UpdateSourceProps(Source, Context); - } - Context->setError(AL_INVALID_VALUE, "Unsupported AL_DIRECT_CHANNELS_SOFT: 0x%04x\n", - values[0]); - return false; - - case AL_DISTANCE_MODEL: - CHECKSIZE(values, 1); - if(auto model = DistanceModelFromALenum(values[0])) - { - Source->mDistanceModel = *model; - if(Context->mSourceDistanceModel) - return UpdateSourceProps(Source, Context); - return true; - } - Context->setError(AL_INVALID_VALUE, "Distance model out of range: 0x%04x", values[0]); - return false; - - case AL_SOURCE_RESAMPLER_SOFT: - CHECKSIZE(values, 1); - CHECKVAL(values[0] >= 0 && values[0] <= static_cast(Resampler::Max)); - - Source->mResampler = static_cast(values[0]); - return UpdateSourceProps(Source, Context); - - case AL_SOURCE_SPATIALIZE_SOFT: - CHECKSIZE(values, 1); - if(auto mode = SpatializeModeFromEnum(values[0])) - { - Source->mSpatialize = *mode; - return UpdateSourceProps(Source, Context); - } - Context->setError(AL_INVALID_VALUE, "Unsupported AL_SOURCE_SPATIALIZE_SOFT: 0x%04x\n", - values[0]); - return false; - - case AL_AUXILIARY_SEND_FILTER: - CHECKSIZE(values, 3); - slotlock = std::unique_lock{Context->mEffectSlotLock}; - if(values[0] && (slot=LookupEffectSlot(Context, static_cast(values[0]))) == nullptr) - SETERR_RETURN(Context, AL_INVALID_VALUE, false, "Invalid effect ID %u", values[0]); - if(static_cast(values[1]) >= device->NumAuxSends) - SETERR_RETURN(Context, AL_INVALID_VALUE, false, "Invalid send %u", values[1]); - - if(values[2]) - { - std::lock_guard _{device->FilterLock}; - ALfilter *filter{LookupFilter(device, static_cast(values[2]))}; - if(!filter) - SETERR_RETURN(Context, AL_INVALID_VALUE, false, "Invalid filter ID %u", values[2]); - - auto &send = Source->Send[static_cast(values[1])]; - send.Gain = filter->Gain; - send.GainHF = filter->GainHF; - send.HFReference = filter->HFReference; - send.GainLF = filter->GainLF; - send.LFReference = filter->LFReference; - } - else - { - /* Disable filter */ - auto &send = Source->Send[static_cast(values[1])]; - send.Gain = 1.0f; - send.GainHF = 1.0f; - send.HFReference = LOWPASSFREQREF; - send.GainLF = 1.0f; - send.LFReference = HIGHPASSFREQREF; - } - - if(slot != Source->Send[static_cast(values[1])].Slot && IsPlayingOrPaused(Source)) - { - /* Add refcount on the new slot, and release the previous slot */ - if(slot) IncrementRef(slot->ref); - if(auto *oldslot = Source->Send[static_cast(values[1])].Slot) - DecrementRef(oldslot->ref); - Source->Send[static_cast(values[1])].Slot = slot; - - /* We must force an update if the auxiliary slot changed on an - * active source, in case the slot is about to be deleted. - */ - Voice *voice{GetSourceVoice(Source, Context)}; - if(voice) UpdateSourceProps(Source, voice, Context); - else Source->PropsClean.clear(std::memory_order_release); - } - else - { - if(slot) IncrementRef(slot->ref); - if(auto *oldslot = Source->Send[static_cast(values[1])].Slot) - DecrementRef(oldslot->ref); - Source->Send[static_cast(values[1])].Slot = slot; - UpdateSourceProps(Source, Context); - } - return true; - - - /* 1x float */ - case AL_CONE_INNER_ANGLE: - case AL_CONE_OUTER_ANGLE: - case AL_PITCH: - case AL_GAIN: - case AL_MIN_GAIN: - case AL_MAX_GAIN: - case AL_REFERENCE_DISTANCE: - case AL_ROLLOFF_FACTOR: - case AL_CONE_OUTER_GAIN: - case AL_MAX_DISTANCE: - case AL_DOPPLER_FACTOR: - case AL_CONE_OUTER_GAINHF: - case AL_AIR_ABSORPTION_FACTOR: - case AL_ROOM_ROLLOFF_FACTOR: - case AL_SOURCE_RADIUS: - CHECKSIZE(values, 1); - fvals[0] = static_cast(values[0]); - return SetSourcefv(Source, Context, prop, {fvals, 1u}); - - /* 3x float */ - case AL_POSITION: - case AL_VELOCITY: - case AL_DIRECTION: - CHECKSIZE(values, 3); - fvals[0] = static_cast(values[0]); - fvals[1] = static_cast(values[1]); - fvals[2] = static_cast(values[2]); - return SetSourcefv(Source, Context, prop, {fvals, 3u}); - - /* 6x float */ - case AL_ORIENTATION: - CHECKSIZE(values, 6); - fvals[0] = static_cast(values[0]); - fvals[1] = static_cast(values[1]); - fvals[2] = static_cast(values[2]); - fvals[3] = static_cast(values[3]); - fvals[4] = static_cast(values[4]); - fvals[5] = static_cast(values[5]); - return SetSourcefv(Source, Context, prop, {fvals, 6u}); - - case AL_SAMPLE_OFFSET_LATENCY_SOFT: - case AL_SEC_OFFSET_LATENCY_SOFT: - case AL_SEC_OFFSET_CLOCK_SOFT: - case AL_SAMPLE_OFFSET_CLOCK_SOFT: - case AL_STEREO_ANGLES: - break; - } - - ERR("Unexpected property: 0x%04x\n", prop); - Context->setError(AL_INVALID_ENUM, "Invalid source integer property 0x%04x", prop); - return false; -} - -bool SetSourcei64v(ALsource *Source, ALCcontext *Context, SourceProp prop, const al::span values) -{ - float fvals[MaxValues]; - int ivals[MaxValues]; - - switch(prop) - { - case AL_SOURCE_TYPE: - case AL_BUFFERS_QUEUED: - case AL_BUFFERS_PROCESSED: - case AL_SOURCE_STATE: - case AL_SAMPLE_OFFSET_LATENCY_SOFT: - case AL_SAMPLE_OFFSET_CLOCK_SOFT: - /* Query only */ - SETERR_RETURN(Context, AL_INVALID_OPERATION, false, - "Setting read-only source property 0x%04x", prop); - - /* 1x int */ - case AL_SOURCE_RELATIVE: - case AL_LOOPING: - case AL_SEC_OFFSET: - case AL_SAMPLE_OFFSET: - case AL_BYTE_OFFSET: - case AL_DIRECT_FILTER_GAINHF_AUTO: - case AL_AUXILIARY_SEND_FILTER_GAIN_AUTO: - case AL_AUXILIARY_SEND_FILTER_GAINHF_AUTO: - case AL_DIRECT_CHANNELS_SOFT: - case AL_DISTANCE_MODEL: - case AL_SOURCE_RESAMPLER_SOFT: - case AL_SOURCE_SPATIALIZE_SOFT: - CHECKSIZE(values, 1); - CHECKVAL(values[0] <= INT_MAX && values[0] >= INT_MIN); - - ivals[0] = static_cast(values[0]); - return SetSourceiv(Source, Context, prop, {ivals, 1u}); - - /* 1x uint */ - case AL_BUFFER: - case AL_DIRECT_FILTER: - CHECKSIZE(values, 1); - CHECKVAL(values[0] <= UINT_MAX && values[0] >= 0); - - ivals[0] = static_cast(values[0]); - return SetSourceiv(Source, Context, prop, {ivals, 1u}); - - /* 3x uint */ - case AL_AUXILIARY_SEND_FILTER: - CHECKSIZE(values, 3); - CHECKVAL(values[0] <= UINT_MAX && values[0] >= 0 && values[1] <= UINT_MAX && values[1] >= 0 - && values[2] <= UINT_MAX && values[2] >= 0); - - ivals[0] = static_cast(values[0]); - ivals[1] = static_cast(values[1]); - ivals[2] = static_cast(values[2]); - return SetSourceiv(Source, Context, prop, {ivals, 3u}); - - /* 1x float */ - case AL_CONE_INNER_ANGLE: - case AL_CONE_OUTER_ANGLE: - case AL_PITCH: - case AL_GAIN: - case AL_MIN_GAIN: - case AL_MAX_GAIN: - case AL_REFERENCE_DISTANCE: - case AL_ROLLOFF_FACTOR: - case AL_CONE_OUTER_GAIN: - case AL_MAX_DISTANCE: - case AL_DOPPLER_FACTOR: - case AL_CONE_OUTER_GAINHF: - case AL_AIR_ABSORPTION_FACTOR: - case AL_ROOM_ROLLOFF_FACTOR: - case AL_SOURCE_RADIUS: - CHECKSIZE(values, 1); - fvals[0] = static_cast(values[0]); - return SetSourcefv(Source, Context, prop, {fvals, 1u}); - - /* 3x float */ - case AL_POSITION: - case AL_VELOCITY: - case AL_DIRECTION: - CHECKSIZE(values, 3); - fvals[0] = static_cast(values[0]); - fvals[1] = static_cast(values[1]); - fvals[2] = static_cast(values[2]); - return SetSourcefv(Source, Context, prop, {fvals, 3u}); - - /* 6x float */ - case AL_ORIENTATION: - CHECKSIZE(values, 6); - fvals[0] = static_cast(values[0]); - fvals[1] = static_cast(values[1]); - fvals[2] = static_cast(values[2]); - fvals[3] = static_cast(values[3]); - fvals[4] = static_cast(values[4]); - fvals[5] = static_cast(values[5]); - return SetSourcefv(Source, Context, prop, {fvals, 6u}); - - case AL_SEC_OFFSET_LATENCY_SOFT: - case AL_SEC_OFFSET_CLOCK_SOFT: - case AL_STEREO_ANGLES: - break; - } - - ERR("Unexpected property: 0x%04x\n", prop); - Context->setError(AL_INVALID_ENUM, "Invalid source integer64 property 0x%04x", prop); - return false; -} - -#undef CHECKVAL - - -bool GetSourcedv(ALsource *Source, ALCcontext *Context, SourceProp prop, const al::span values); -bool GetSourceiv(ALsource *Source, ALCcontext *Context, SourceProp prop, const al::span values); -bool GetSourcei64v(ALsource *Source, ALCcontext *Context, SourceProp prop, const al::span values); - -bool GetSourcedv(ALsource *Source, ALCcontext *Context, SourceProp prop, const al::span values) -{ - ALCdevice *device{Context->mDevice.get()}; - ClockLatency clocktime; - nanoseconds srcclock; - int ivals[MaxValues]; - bool err; - - switch(prop) - { - case AL_GAIN: - CHECKSIZE(values, 1); - values[0] = Source->Gain; - return true; - - case AL_PITCH: - CHECKSIZE(values, 1); - values[0] = Source->Pitch; - return true; - - case AL_MAX_DISTANCE: - CHECKSIZE(values, 1); - values[0] = Source->MaxDistance; - return true; - - case AL_ROLLOFF_FACTOR: - CHECKSIZE(values, 1); - values[0] = Source->RolloffFactor; - return true; - - case AL_REFERENCE_DISTANCE: - CHECKSIZE(values, 1); - values[0] = Source->RefDistance; - return true; - - case AL_CONE_INNER_ANGLE: - CHECKSIZE(values, 1); - values[0] = Source->InnerAngle; - return true; - - case AL_CONE_OUTER_ANGLE: - CHECKSIZE(values, 1); - values[0] = Source->OuterAngle; - return true; - - case AL_MIN_GAIN: - CHECKSIZE(values, 1); - values[0] = Source->MinGain; - return true; - - case AL_MAX_GAIN: - CHECKSIZE(values, 1); - values[0] = Source->MaxGain; - return true; - - case AL_CONE_OUTER_GAIN: - CHECKSIZE(values, 1); - values[0] = Source->OuterGain; - return true; - - case AL_SEC_OFFSET: - case AL_SAMPLE_OFFSET: - case AL_BYTE_OFFSET: - CHECKSIZE(values, 1); - values[0] = GetSourceOffset(Source, prop, Context); - return true; - - case AL_CONE_OUTER_GAINHF: - CHECKSIZE(values, 1); - values[0] = Source->OuterGainHF; - return true; - - case AL_AIR_ABSORPTION_FACTOR: - CHECKSIZE(values, 1); - values[0] = Source->AirAbsorptionFactor; - return true; - - case AL_ROOM_ROLLOFF_FACTOR: - CHECKSIZE(values, 1); - values[0] = Source->RoomRolloffFactor; - return true; - - case AL_DOPPLER_FACTOR: - CHECKSIZE(values, 1); - values[0] = Source->DopplerFactor; - return true; - - case AL_SOURCE_RADIUS: - CHECKSIZE(values, 1); - values[0] = Source->Radius; - return true; - - case AL_STEREO_ANGLES: - CHECKSIZE(values, 2); - values[0] = Source->StereoPan[0]; - values[1] = Source->StereoPan[1]; - return true; - - case AL_SEC_OFFSET_LATENCY_SOFT: - CHECKSIZE(values, 2); - /* Get the source offset with the clock time first. Then get the clock - * time with the device latency. Order is important. - */ - values[0] = GetSourceSecOffset(Source, Context, &srcclock); - { - std::lock_guard _{device->StateLock}; - clocktime = GetClockLatency(device); - } - if(srcclock == clocktime.ClockTime) - values[1] = static_cast(clocktime.Latency.count()) / 1000000000.0; - else - { - /* If the clock time incremented, reduce the latency by that much - * since it's that much closer to the source offset it got earlier. - */ - const nanoseconds diff{clocktime.ClockTime - srcclock}; - const nanoseconds latency{clocktime.Latency - std::min(clocktime.Latency, diff)}; - values[1] = static_cast(latency.count()) / 1000000000.0; - } - return true; - - case AL_SEC_OFFSET_CLOCK_SOFT: - CHECKSIZE(values, 2); - values[0] = GetSourceSecOffset(Source, Context, &srcclock); - values[1] = static_cast(srcclock.count()) / 1000000000.0; - return true; - - case AL_POSITION: - CHECKSIZE(values, 3); - values[0] = Source->Position[0]; - values[1] = Source->Position[1]; - values[2] = Source->Position[2]; - return true; - - case AL_VELOCITY: - CHECKSIZE(values, 3); - values[0] = Source->Velocity[0]; - values[1] = Source->Velocity[1]; - values[2] = Source->Velocity[2]; - return true; - - case AL_DIRECTION: - CHECKSIZE(values, 3); - values[0] = Source->Direction[0]; - values[1] = Source->Direction[1]; - values[2] = Source->Direction[2]; - return true; - - case AL_ORIENTATION: - CHECKSIZE(values, 6); - values[0] = Source->OrientAt[0]; - values[1] = Source->OrientAt[1]; - values[2] = Source->OrientAt[2]; - values[3] = Source->OrientUp[0]; - values[4] = Source->OrientUp[1]; - values[5] = Source->OrientUp[2]; - return true; - - /* 1x int */ - case AL_SOURCE_RELATIVE: - case AL_LOOPING: - case AL_SOURCE_STATE: - case AL_BUFFERS_QUEUED: - case AL_BUFFERS_PROCESSED: - case AL_SOURCE_TYPE: - case AL_DIRECT_FILTER_GAINHF_AUTO: - case AL_AUXILIARY_SEND_FILTER_GAIN_AUTO: - case AL_AUXILIARY_SEND_FILTER_GAINHF_AUTO: - case AL_DIRECT_CHANNELS_SOFT: - case AL_DISTANCE_MODEL: - case AL_SOURCE_RESAMPLER_SOFT: - case AL_SOURCE_SPATIALIZE_SOFT: - CHECKSIZE(values, 1); - if((err=GetSourceiv(Source, Context, prop, {ivals, 1u})) != false) - values[0] = static_cast(ivals[0]); - return err; - - case AL_BUFFER: - case AL_DIRECT_FILTER: - case AL_AUXILIARY_SEND_FILTER: - case AL_SAMPLE_OFFSET_LATENCY_SOFT: - case AL_SAMPLE_OFFSET_CLOCK_SOFT: - break; - } - - ERR("Unexpected property: 0x%04x\n", prop); - Context->setError(AL_INVALID_ENUM, "Invalid source double property 0x%04x", prop); - return false; -} - -bool GetSourceiv(ALsource *Source, ALCcontext *Context, SourceProp prop, const al::span values) -{ - double dvals[MaxValues]; - bool err; - - switch(prop) - { - case AL_SOURCE_RELATIVE: - CHECKSIZE(values, 1); - values[0] = Source->HeadRelative; - return true; - - case AL_LOOPING: - CHECKSIZE(values, 1); - values[0] = Source->Looping; - return true; - - case AL_BUFFER: - CHECKSIZE(values, 1); - { - BufferlistItem *BufferList{(Source->SourceType==AL_STATIC) ? Source->queue : nullptr}; - ALbuffer *buffer{BufferList ? static_cast(BufferList->mBuffer) : nullptr}; - values[0] = buffer ? static_cast(buffer->id) : 0; - } - return true; - - case AL_SOURCE_STATE: - CHECKSIZE(values, 1); - values[0] = GetSourceState(Source, GetSourceVoice(Source, Context)); - return true; - - case AL_BUFFERS_QUEUED: - CHECKSIZE(values, 1); - if(BufferlistItem *BufferList{Source->queue}) - { - ALsizei count{0}; - do { - ++count; - BufferList = BufferList->mNext.load(std::memory_order_relaxed); - } while(BufferList != nullptr); - values[0] = count; - } - else - values[0] = 0; - return true; - - case AL_BUFFERS_PROCESSED: - CHECKSIZE(values, 1); - if(Source->Looping || Source->SourceType != AL_STREAMING) - { - /* Buffers on a looping source are in a perpetual state of PENDING, - * so don't report any as PROCESSED - */ - values[0] = 0; - } - else - { - const BufferlistItem *BufferList{Source->queue}; - const BufferlistItem *Current{nullptr}; - ALsizei played{0}; - - Voice *voice{GetSourceVoice(Source, Context)}; - if(voice != nullptr) - Current = voice->mCurrentBuffer.load(std::memory_order_relaxed); - else if(Source->state == AL_INITIAL) - Current = BufferList; - - while(BufferList && BufferList != Current) - { - ++played; - BufferList = BufferList->mNext.load(std::memory_order_relaxed); - } - values[0] = played; - } - return true; - - case AL_SOURCE_TYPE: - CHECKSIZE(values, 1); - values[0] = Source->SourceType; - return true; - - case AL_DIRECT_FILTER_GAINHF_AUTO: - CHECKSIZE(values, 1); - values[0] = Source->DryGainHFAuto; - return true; - - case AL_AUXILIARY_SEND_FILTER_GAIN_AUTO: - CHECKSIZE(values, 1); - values[0] = Source->WetGainAuto; - return true; - - case AL_AUXILIARY_SEND_FILTER_GAINHF_AUTO: - CHECKSIZE(values, 1); - values[0] = Source->WetGainHFAuto; - return true; - - case AL_DIRECT_CHANNELS_SOFT: - CHECKSIZE(values, 1); - values[0] = EnumFromDirectMode(Source->DirectChannels); - return true; - - case AL_DISTANCE_MODEL: - CHECKSIZE(values, 1); - values[0] = ALenumFromDistanceModel(Source->mDistanceModel); - return true; - - case AL_SOURCE_RESAMPLER_SOFT: - CHECKSIZE(values, 1); - values[0] = static_cast(Source->mResampler); - return true; - - case AL_SOURCE_SPATIALIZE_SOFT: - CHECKSIZE(values, 1); - values[0] = EnumFromSpatializeMode(Source->mSpatialize); - return true; - - /* 1x float/double */ - case AL_CONE_INNER_ANGLE: - case AL_CONE_OUTER_ANGLE: - case AL_PITCH: - case AL_GAIN: - case AL_MIN_GAIN: - case AL_MAX_GAIN: - case AL_REFERENCE_DISTANCE: - case AL_ROLLOFF_FACTOR: - case AL_CONE_OUTER_GAIN: - case AL_MAX_DISTANCE: - case AL_SEC_OFFSET: - case AL_SAMPLE_OFFSET: - case AL_BYTE_OFFSET: - case AL_DOPPLER_FACTOR: - case AL_AIR_ABSORPTION_FACTOR: - case AL_ROOM_ROLLOFF_FACTOR: - case AL_CONE_OUTER_GAINHF: - case AL_SOURCE_RADIUS: - CHECKSIZE(values, 1); - if((err=GetSourcedv(Source, Context, prop, {dvals, 1u})) != false) - values[0] = static_cast(dvals[0]); - return err; - - /* 3x float/double */ - case AL_POSITION: - case AL_VELOCITY: - case AL_DIRECTION: - CHECKSIZE(values, 3); - if((err=GetSourcedv(Source, Context, prop, {dvals, 3u})) != false) - { - values[0] = static_cast(dvals[0]); - values[1] = static_cast(dvals[1]); - values[2] = static_cast(dvals[2]); - } - return err; - - /* 6x float/double */ - case AL_ORIENTATION: - CHECKSIZE(values, 6); - if((err=GetSourcedv(Source, Context, prop, {dvals, 6u})) != false) - { - values[0] = static_cast(dvals[0]); - values[1] = static_cast(dvals[1]); - values[2] = static_cast(dvals[2]); - values[3] = static_cast(dvals[3]); - values[4] = static_cast(dvals[4]); - values[5] = static_cast(dvals[5]); - } - return err; - - case AL_SAMPLE_OFFSET_LATENCY_SOFT: - case AL_SAMPLE_OFFSET_CLOCK_SOFT: - break; /* i64 only */ - case AL_SEC_OFFSET_LATENCY_SOFT: - case AL_SEC_OFFSET_CLOCK_SOFT: - break; /* Double only */ - case AL_STEREO_ANGLES: - break; /* Float/double only */ - - case AL_DIRECT_FILTER: - case AL_AUXILIARY_SEND_FILTER: - break; /* ??? */ - } - - ERR("Unexpected property: 0x%04x\n", prop); - Context->setError(AL_INVALID_ENUM, "Invalid source integer property 0x%04x", prop); - return false; -} - -bool GetSourcei64v(ALsource *Source, ALCcontext *Context, SourceProp prop, const al::span values) -{ - ALCdevice *device = Context->mDevice.get(); - ClockLatency clocktime; - nanoseconds srcclock; - double dvals[MaxValues]; - int ivals[MaxValues]; - bool err; - - switch(prop) - { - case AL_SAMPLE_OFFSET_LATENCY_SOFT: - CHECKSIZE(values, 2); - /* Get the source offset with the clock time first. Then get the clock - * time with the device latency. Order is important. - */ - values[0] = GetSourceSampleOffset(Source, Context, &srcclock); - { - std::lock_guard _{device->StateLock}; - clocktime = GetClockLatency(device); - } - if(srcclock == clocktime.ClockTime) - values[1] = clocktime.Latency.count(); - else - { - /* If the clock time incremented, reduce the latency by that much - * since it's that much closer to the source offset it got earlier. - */ - const nanoseconds diff{clocktime.ClockTime - srcclock}; - values[1] = nanoseconds{clocktime.Latency - std::min(clocktime.Latency, diff)}.count(); - } - return true; - - case AL_SAMPLE_OFFSET_CLOCK_SOFT: - CHECKSIZE(values, 2); - values[0] = GetSourceSampleOffset(Source, Context, &srcclock); - values[1] = srcclock.count(); - return true; - - /* 1x float/double */ - case AL_CONE_INNER_ANGLE: - case AL_CONE_OUTER_ANGLE: - case AL_PITCH: - case AL_GAIN: - case AL_MIN_GAIN: - case AL_MAX_GAIN: - case AL_REFERENCE_DISTANCE: - case AL_ROLLOFF_FACTOR: - case AL_CONE_OUTER_GAIN: - case AL_MAX_DISTANCE: - case AL_SEC_OFFSET: - case AL_SAMPLE_OFFSET: - case AL_BYTE_OFFSET: - case AL_DOPPLER_FACTOR: - case AL_AIR_ABSORPTION_FACTOR: - case AL_ROOM_ROLLOFF_FACTOR: - case AL_CONE_OUTER_GAINHF: - case AL_SOURCE_RADIUS: - CHECKSIZE(values, 1); - if((err=GetSourcedv(Source, Context, prop, {dvals, 1u})) != false) - values[0] = static_cast(dvals[0]); - return err; - - /* 3x float/double */ - case AL_POSITION: - case AL_VELOCITY: - case AL_DIRECTION: - CHECKSIZE(values, 3); - if((err=GetSourcedv(Source, Context, prop, {dvals, 3u})) != false) - { - values[0] = static_cast(dvals[0]); - values[1] = static_cast(dvals[1]); - values[2] = static_cast(dvals[2]); - } - return err; - - /* 6x float/double */ - case AL_ORIENTATION: - CHECKSIZE(values, 6); - if((err=GetSourcedv(Source, Context, prop, {dvals, 6u})) != false) - { - values[0] = static_cast(dvals[0]); - values[1] = static_cast(dvals[1]); - values[2] = static_cast(dvals[2]); - values[3] = static_cast(dvals[3]); - values[4] = static_cast(dvals[4]); - values[5] = static_cast(dvals[5]); - } - return err; - - /* 1x int */ - case AL_SOURCE_RELATIVE: - case AL_LOOPING: - case AL_SOURCE_STATE: - case AL_BUFFERS_QUEUED: - case AL_BUFFERS_PROCESSED: - case AL_SOURCE_TYPE: - case AL_DIRECT_FILTER_GAINHF_AUTO: - case AL_AUXILIARY_SEND_FILTER_GAIN_AUTO: - case AL_AUXILIARY_SEND_FILTER_GAINHF_AUTO: - case AL_DIRECT_CHANNELS_SOFT: - case AL_DISTANCE_MODEL: - case AL_SOURCE_RESAMPLER_SOFT: - case AL_SOURCE_SPATIALIZE_SOFT: - CHECKSIZE(values, 1); - if((err=GetSourceiv(Source, Context, prop, {ivals, 1u})) != false) - values[0] = ivals[0]; - return err; - - /* 1x uint */ - case AL_BUFFER: - case AL_DIRECT_FILTER: - CHECKSIZE(values, 1); - if((err=GetSourceiv(Source, Context, prop, {ivals, 1u})) != false) - values[0] = static_cast(ivals[0]); - return err; - - /* 3x uint */ - case AL_AUXILIARY_SEND_FILTER: - CHECKSIZE(values, 3); - if((err=GetSourceiv(Source, Context, prop, {ivals, 3u})) != false) - { - values[0] = static_cast(ivals[0]); - values[1] = static_cast(ivals[1]); - values[2] = static_cast(ivals[2]); - } - return err; - - case AL_SEC_OFFSET_LATENCY_SOFT: - case AL_SEC_OFFSET_CLOCK_SOFT: - break; /* Double only */ - case AL_STEREO_ANGLES: - break; /* Float/double only */ - } - - ERR("Unexpected property: 0x%04x\n", prop); - Context->setError(AL_INVALID_ENUM, "Invalid source integer64 property 0x%04x", prop); - return false; -} - -} // namespace - -AL_API void AL_APIENTRY alGenSources(ALsizei n, ALuint *sources) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - if UNLIKELY(n < 0) - context->setError(AL_INVALID_VALUE, "Generating %d sources", n); - if UNLIKELY(n <= 0) return; - - std::unique_lock srclock{context->mSourceLock}; - ALCdevice *device{context->mDevice.get()}; - if(static_cast(n) > device->SourcesMax-context->mNumSources) - { - context->setError(AL_OUT_OF_MEMORY, "Exceeding %u source limit (%u + %d)", - device->SourcesMax, context->mNumSources, n); - return; - } - if(!EnsureSources(context.get(), static_cast(n))) - { - context->setError(AL_OUT_OF_MEMORY, "Failed to allocate %d source%s", n, (n==1)?"":"s"); - return; - } - - if(n == 1) - { - ALsource *source{AllocSource(context.get())}; - sources[0] = source->id; - } - else - { - al::vector ids; - ids.reserve(static_cast(n)); - do { - ALsource *source{AllocSource(context.get())}; - ids.emplace_back(source->id); - } while(--n); - std::copy(ids.cbegin(), ids.cend(), sources); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alDeleteSources(ALsizei n, const ALuint *sources) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - if UNLIKELY(n < 0) - SETERR_RETURN(context, AL_INVALID_VALUE,, "Deleting %d sources", n); - - std::lock_guard _{context->mSourceLock}; - - /* Check that all Sources are valid */ - auto validate_source = [&context](const ALuint sid) -> bool - { return LookupSource(context.get(), sid) != nullptr; }; - - const ALuint *sources_end = sources + n; - auto invsrc = std::find_if_not(sources, sources_end, validate_source); - if UNLIKELY(invsrc != sources_end) - { - context->setError(AL_INVALID_NAME, "Invalid source ID %u", *invsrc); - return; - } - - /* All good. Delete source IDs. */ - auto delete_source = [&context](const ALuint sid) -> void - { - ALsource *src{LookupSource(context.get(), sid)}; - if(src) FreeSource(context.get(), src); - }; - std::for_each(sources, sources_end, delete_source); -} -END_API_FUNC - -AL_API ALboolean AL_APIENTRY alIsSource(ALuint source) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if LIKELY(context) - { - std::lock_guard _{context->mSourceLock}; - if(LookupSource(context.get(), source) != nullptr) - return AL_TRUE; - } - return AL_FALSE; -} -END_API_FUNC - - -AL_API void AL_APIENTRY alSourcef(ALuint source, ALenum param, ALfloat value) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - std::lock_guard _{context->mPropLock}; - std::lock_guard __{context->mSourceLock}; - ALsource *Source = LookupSource(context.get(), source); - if UNLIKELY(!Source) - context->setError(AL_INVALID_NAME, "Invalid source ID %u", source); - else - SetSourcefv(Source, context.get(), static_cast(param), {&value, 1u}); -} -END_API_FUNC - -AL_API void AL_APIENTRY alSource3f(ALuint source, ALenum param, ALfloat value1, ALfloat value2, ALfloat value3) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - std::lock_guard _{context->mPropLock}; - std::lock_guard __{context->mSourceLock}; - ALsource *Source = LookupSource(context.get(), source); - if UNLIKELY(!Source) - context->setError(AL_INVALID_NAME, "Invalid source ID %u", source); - else - { - const float fvals[3]{ value1, value2, value3 }; - SetSourcefv(Source, context.get(), static_cast(param), fvals); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alSourcefv(ALuint source, ALenum param, const ALfloat *values) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - std::lock_guard _{context->mPropLock}; - std::lock_guard __{context->mSourceLock}; - ALsource *Source = LookupSource(context.get(), source); - if UNLIKELY(!Source) - context->setError(AL_INVALID_NAME, "Invalid source ID %u", source); - else if UNLIKELY(!values) - context->setError(AL_INVALID_VALUE, "NULL pointer"); - else - SetSourcefv(Source, context.get(), static_cast(param), {values, MaxValues}); -} -END_API_FUNC - - -AL_API void AL_APIENTRY alSourcedSOFT(ALuint source, ALenum param, ALdouble value) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - std::lock_guard _{context->mPropLock}; - std::lock_guard __{context->mSourceLock}; - ALsource *Source = LookupSource(context.get(), source); - if UNLIKELY(!Source) - context->setError(AL_INVALID_NAME, "Invalid source ID %u", source); - else - { - const float fval[1]{static_cast(value)}; - SetSourcefv(Source, context.get(), static_cast(param), fval); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alSource3dSOFT(ALuint source, ALenum param, ALdouble value1, ALdouble value2, ALdouble value3) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - std::lock_guard _{context->mPropLock}; - std::lock_guard __{context->mSourceLock}; - ALsource *Source = LookupSource(context.get(), source); - if UNLIKELY(!Source) - context->setError(AL_INVALID_NAME, "Invalid source ID %u", source); - else - { - const float fvals[3]{static_cast(value1), static_cast(value2), - static_cast(value3)}; - SetSourcefv(Source, context.get(), static_cast(param), fvals); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alSourcedvSOFT(ALuint source, ALenum param, const ALdouble *values) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - std::lock_guard _{context->mPropLock}; - std::lock_guard __{context->mSourceLock}; - ALsource *Source = LookupSource(context.get(), source); - if UNLIKELY(!Source) - context->setError(AL_INVALID_NAME, "Invalid source ID %u", source); - else if UNLIKELY(!values) - context->setError(AL_INVALID_VALUE, "NULL pointer"); - else - { - const ALuint count{DoubleValsByProp(param)}; - float fvals[MaxValues]; - for(ALuint i{0};i < count;i++) - fvals[i] = static_cast(values[i]); - SetSourcefv(Source, context.get(), static_cast(param), {fvals, count}); - } -} -END_API_FUNC - - -AL_API void AL_APIENTRY alSourcei(ALuint source, ALenum param, ALint value) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - std::lock_guard _{context->mPropLock}; - std::lock_guard __{context->mSourceLock}; - ALsource *Source = LookupSource(context.get(), source); - if UNLIKELY(!Source) - context->setError(AL_INVALID_NAME, "Invalid source ID %u", source); - else - SetSourceiv(Source, context.get(), static_cast(param), {&value, 1u}); -} -END_API_FUNC - -AL_API void AL_APIENTRY alSource3i(ALuint source, ALenum param, ALint value1, ALint value2, ALint value3) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - std::lock_guard _{context->mPropLock}; - std::lock_guard __{context->mSourceLock}; - ALsource *Source = LookupSource(context.get(), source); - if UNLIKELY(!Source) - context->setError(AL_INVALID_NAME, "Invalid source ID %u", source); - else - { - const int ivals[3]{ value1, value2, value3 }; - SetSourceiv(Source, context.get(), static_cast(param), ivals); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alSourceiv(ALuint source, ALenum param, const ALint *values) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - std::lock_guard _{context->mPropLock}; - std::lock_guard __{context->mSourceLock}; - ALsource *Source = LookupSource(context.get(), source); - if UNLIKELY(!Source) - context->setError(AL_INVALID_NAME, "Invalid source ID %u", source); - else if UNLIKELY(!values) - context->setError(AL_INVALID_VALUE, "NULL pointer"); - else - SetSourceiv(Source, context.get(), static_cast(param), {values, MaxValues}); -} -END_API_FUNC - - -AL_API void AL_APIENTRY alSourcei64SOFT(ALuint source, ALenum param, ALint64SOFT value) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - std::lock_guard _{context->mPropLock}; - std::lock_guard __{context->mSourceLock}; - ALsource *Source{LookupSource(context.get(), source)}; - if UNLIKELY(!Source) - context->setError(AL_INVALID_NAME, "Invalid source ID %u", source); - else - SetSourcei64v(Source, context.get(), static_cast(param), {&value, 1u}); -} -END_API_FUNC - -AL_API void AL_APIENTRY alSource3i64SOFT(ALuint source, ALenum param, ALint64SOFT value1, ALint64SOFT value2, ALint64SOFT value3) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - std::lock_guard _{context->mPropLock}; - std::lock_guard __{context->mSourceLock}; - ALsource *Source{LookupSource(context.get(), source)}; - if UNLIKELY(!Source) - context->setError(AL_INVALID_NAME, "Invalid source ID %u", source); - else - { - const int64_t i64vals[3]{ value1, value2, value3 }; - SetSourcei64v(Source, context.get(), static_cast(param), i64vals); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alSourcei64vSOFT(ALuint source, ALenum param, const ALint64SOFT *values) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - std::lock_guard _{context->mPropLock}; - std::lock_guard __{context->mSourceLock}; - ALsource *Source{LookupSource(context.get(), source)}; - if UNLIKELY(!Source) - context->setError(AL_INVALID_NAME, "Invalid source ID %u", source); - else if UNLIKELY(!values) - context->setError(AL_INVALID_VALUE, "NULL pointer"); - else - SetSourcei64v(Source, context.get(), static_cast(param), {values, MaxValues}); -} -END_API_FUNC - - -AL_API void AL_APIENTRY alGetSourcef(ALuint source, ALenum param, ALfloat *value) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - std::lock_guard _{context->mSourceLock}; - ALsource *Source{LookupSource(context.get(), source)}; - if UNLIKELY(!Source) - context->setError(AL_INVALID_NAME, "Invalid source ID %u", source); - else if UNLIKELY(!value) - context->setError(AL_INVALID_VALUE, "NULL pointer"); - else - { - double dval[1]; - if(GetSourcedv(Source, context.get(), static_cast(param), dval)) - *value = static_cast(dval[0]); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alGetSource3f(ALuint source, ALenum param, ALfloat *value1, ALfloat *value2, ALfloat *value3) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - std::lock_guard _{context->mSourceLock}; - ALsource *Source{LookupSource(context.get(), source)}; - if UNLIKELY(!Source) - context->setError(AL_INVALID_NAME, "Invalid source ID %u", source); - else if UNLIKELY(!(value1 && value2 && value3)) - context->setError(AL_INVALID_VALUE, "NULL pointer"); - else - { - double dvals[3]; - if(GetSourcedv(Source, context.get(), static_cast(param), dvals)) - { - *value1 = static_cast(dvals[0]); - *value2 = static_cast(dvals[1]); - *value3 = static_cast(dvals[2]); - } - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alGetSourcefv(ALuint source, ALenum param, ALfloat *values) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - std::lock_guard _{context->mSourceLock}; - ALsource *Source{LookupSource(context.get(), source)}; - if UNLIKELY(!Source) - context->setError(AL_INVALID_NAME, "Invalid source ID %u", source); - else if UNLIKELY(!values) - context->setError(AL_INVALID_VALUE, "NULL pointer"); - else - { - const ALuint count{FloatValsByProp(param)}; - double dvals[MaxValues]; - if(GetSourcedv(Source, context.get(), static_cast(param), {dvals, count})) - { - for(ALuint i{0};i < count;i++) - values[i] = static_cast(dvals[i]); - } - } -} -END_API_FUNC - - -AL_API void AL_APIENTRY alGetSourcedSOFT(ALuint source, ALenum param, ALdouble *value) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - std::lock_guard _{context->mSourceLock}; - ALsource *Source{LookupSource(context.get(), source)}; - if UNLIKELY(!Source) - context->setError(AL_INVALID_NAME, "Invalid source ID %u", source); - else if UNLIKELY(!value) - context->setError(AL_INVALID_VALUE, "NULL pointer"); - else - GetSourcedv(Source, context.get(), static_cast(param), {value, 1u}); -} -END_API_FUNC - -AL_API void AL_APIENTRY alGetSource3dSOFT(ALuint source, ALenum param, ALdouble *value1, ALdouble *value2, ALdouble *value3) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - std::lock_guard _{context->mSourceLock}; - ALsource *Source{LookupSource(context.get(), source)}; - if UNLIKELY(!Source) - context->setError(AL_INVALID_NAME, "Invalid source ID %u", source); - else if UNLIKELY(!(value1 && value2 && value3)) - context->setError(AL_INVALID_VALUE, "NULL pointer"); - else - { - double dvals[3]; - if(GetSourcedv(Source, context.get(), static_cast(param), dvals)) - { - *value1 = dvals[0]; - *value2 = dvals[1]; - *value3 = dvals[2]; - } - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alGetSourcedvSOFT(ALuint source, ALenum param, ALdouble *values) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - std::lock_guard _{context->mSourceLock}; - ALsource *Source{LookupSource(context.get(), source)}; - if UNLIKELY(!Source) - context->setError(AL_INVALID_NAME, "Invalid source ID %u", source); - else if UNLIKELY(!values) - context->setError(AL_INVALID_VALUE, "NULL pointer"); - else - GetSourcedv(Source, context.get(), static_cast(param), {values, MaxValues}); -} -END_API_FUNC - - -AL_API void AL_APIENTRY alGetSourcei(ALuint source, ALenum param, ALint *value) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - std::lock_guard _{context->mSourceLock}; - ALsource *Source{LookupSource(context.get(), source)}; - if UNLIKELY(!Source) - context->setError(AL_INVALID_NAME, "Invalid source ID %u", source); - else if UNLIKELY(!value) - context->setError(AL_INVALID_VALUE, "NULL pointer"); - else - GetSourceiv(Source, context.get(), static_cast(param), {value, 1u}); -} -END_API_FUNC - -AL_API void AL_APIENTRY alGetSource3i(ALuint source, ALenum param, ALint *value1, ALint *value2, ALint *value3) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - std::lock_guard _{context->mSourceLock}; - ALsource *Source{LookupSource(context.get(), source)}; - if UNLIKELY(!Source) - context->setError(AL_INVALID_NAME, "Invalid source ID %u", source); - else if UNLIKELY(!(value1 && value2 && value3)) - context->setError(AL_INVALID_VALUE, "NULL pointer"); - else - { - int ivals[3]; - if(GetSourceiv(Source, context.get(), static_cast(param), ivals)) - { - *value1 = ivals[0]; - *value2 = ivals[1]; - *value3 = ivals[2]; - } - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alGetSourceiv(ALuint source, ALenum param, ALint *values) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - std::lock_guard _{context->mSourceLock}; - ALsource *Source{LookupSource(context.get(), source)}; - if UNLIKELY(!Source) - context->setError(AL_INVALID_NAME, "Invalid source ID %u", source); - else if UNLIKELY(!values) - context->setError(AL_INVALID_VALUE, "NULL pointer"); - else - GetSourceiv(Source, context.get(), static_cast(param), {values, MaxValues}); -} -END_API_FUNC - - -AL_API void AL_APIENTRY alGetSourcei64SOFT(ALuint source, ALenum param, ALint64SOFT *value) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - std::lock_guard _{context->mSourceLock}; - ALsource *Source{LookupSource(context.get(), source)}; - if UNLIKELY(!Source) - context->setError(AL_INVALID_NAME, "Invalid source ID %u", source); - else if UNLIKELY(!value) - context->setError(AL_INVALID_VALUE, "NULL pointer"); - else - GetSourcei64v(Source, context.get(), static_cast(param), {value, 1u}); -} -END_API_FUNC - -AL_API void AL_APIENTRY alGetSource3i64SOFT(ALuint source, ALenum param, ALint64SOFT *value1, ALint64SOFT *value2, ALint64SOFT *value3) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - std::lock_guard _{context->mSourceLock}; - ALsource *Source{LookupSource(context.get(), source)}; - if UNLIKELY(!Source) - context->setError(AL_INVALID_NAME, "Invalid source ID %u", source); - else if UNLIKELY(!(value1 && value2 && value3)) - context->setError(AL_INVALID_VALUE, "NULL pointer"); - else - { - int64_t i64vals[3]; - if(GetSourcei64v(Source, context.get(), static_cast(param), i64vals)) - { - *value1 = i64vals[0]; - *value2 = i64vals[1]; - *value3 = i64vals[2]; - } - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alGetSourcei64vSOFT(ALuint source, ALenum param, ALint64SOFT *values) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - std::lock_guard _{context->mSourceLock}; - ALsource *Source{LookupSource(context.get(), source)}; - if UNLIKELY(!Source) - context->setError(AL_INVALID_NAME, "Invalid source ID %u", source); - else if UNLIKELY(!values) - context->setError(AL_INVALID_VALUE, "NULL pointer"); - else - GetSourcei64v(Source, context.get(), static_cast(param), {values, MaxValues}); -} -END_API_FUNC - - -AL_API void AL_APIENTRY alSourcePlay(ALuint source) -START_API_FUNC -{ alSourcePlayv(1, &source); } -END_API_FUNC - -AL_API void AL_APIENTRY alSourcePlayv(ALsizei n, const ALuint *sources) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - if UNLIKELY(n < 0) - context->setError(AL_INVALID_VALUE, "Playing %d sources", n); - if UNLIKELY(n <= 0) return; - - al::vector extra_sources; - std::array source_storage; - al::span srchandles; - if LIKELY(static_cast(n) <= source_storage.size()) - srchandles = {source_storage.data(), static_cast(n)}; - else - { - extra_sources.resize(static_cast(n)); - srchandles = {extra_sources.data(), extra_sources.size()}; - } - - std::lock_guard _{context->mSourceLock}; - for(auto &srchdl : srchandles) - { - srchdl = LookupSource(context.get(), *sources); - if(!srchdl) - SETERR_RETURN(context, AL_INVALID_NAME,, "Invalid source ID %u", *sources); - ++sources; - } - - ALCdevice *device{context->mDevice.get()}; - /* If the device is disconnected, go right to stopped. */ - if UNLIKELY(!device->Connected.load(std::memory_order_acquire)) - { - /* TODO: Send state change event? */ - for(ALsource *source : srchandles) - { - source->Offset = 0.0; - source->OffsetType = AL_NONE; - source->state = AL_STOPPED; - } - return; - } - - /* Count the number of reusable voices. */ - auto voicelist = context->getVoicesSpan(); - size_t free_voices{0}; - for(const Voice *voice : voicelist) - { - free_voices += (voice->mPlayState.load(std::memory_order_acquire) == Voice::Stopped - && voice->mSourceID.load(std::memory_order_relaxed) == 0u - && voice->mPendingChange.load(std::memory_order_relaxed) == false); - if(free_voices == srchandles.size()) - break; - } - if UNLIKELY(srchandles.size() != free_voices) - { - const size_t inc_amount{srchandles.size() - free_voices}; - auto &allvoices = *context->mVoices.load(std::memory_order_relaxed); - if(inc_amount > allvoices.size() - voicelist.size()) - { - /* Increase the number of voices to handle the request. */ - context->allocVoices(inc_amount - (allvoices.size() - voicelist.size())); - } - context->mActiveVoiceCount.fetch_add(inc_amount, std::memory_order_release); - voicelist = context->getVoicesSpan(); - } - - auto voiceiter = voicelist.begin(); - ALuint vidx{0}; - VoiceChange *tail{}, *cur{}; - for(ALsource *source : srchandles) - { - /* Check that there is a queue containing at least one valid, non zero - * length buffer. - */ - BufferlistItem *BufferList{source->queue}; - while(BufferList && BufferList->mSampleLen == 0) - { - BufferStorage *buffer{BufferList->mBuffer}; - if(buffer && buffer->mCallback) break; - BufferList = BufferList->mNext.load(std::memory_order_relaxed); - } - - /* If there's nothing to play, go right to stopped. */ - if UNLIKELY(!BufferList) - { - /* NOTE: A source without any playable buffers should not have a - * Voice since it shouldn't be in a playing or paused state. So - * there's no need to look up its voice and clear the source. - */ - source->Offset = 0.0; - source->OffsetType = AL_NONE; - source->state = AL_STOPPED; - continue; - } - - if(!cur) - cur = tail = GetVoiceChanger(context.get()); - else - { - cur->mNext.store(GetVoiceChanger(context.get()), std::memory_order_relaxed); - cur = cur->mNext.load(std::memory_order_relaxed); - } - Voice *voice{GetSourceVoice(source, context.get())}; - switch(GetSourceState(source, voice)) - { - case AL_PAUSED: - /* A source that's paused simply resumes. If there's no voice, it - * was lost from a disconnect, so just start over with a new one. - */ - cur->mOldVoice = nullptr; - if(!voice) break; - cur->mVoice = voice; - cur->mSourceID = source->id; - cur->mState = VChangeState::Play; - source->state = AL_PLAYING; - continue; - - case AL_PLAYING: - /* A source that's already playing is restarted from the beginning. - * Stop the current voice and start a new one so it properly cross- - * fades back to the beginning. - */ - if(voice) - voice->mPendingChange.store(true, std::memory_order_relaxed); - cur->mOldVoice = voice; - voice = nullptr; - break; - - default: - assert(voice == nullptr); - cur->mOldVoice = nullptr; - break; - } - - /* Find the next unused voice to play this source with. */ - for(;voiceiter != voicelist.end();++voiceiter,++vidx) - { - Voice *v{*voiceiter}; - if(v->mPlayState.load(std::memory_order_acquire) == Voice::Stopped - && v->mSourceID.load(std::memory_order_relaxed) == 0u - && v->mPendingChange.load(std::memory_order_relaxed) == false) - { - voice = v; - break; - } - } - - voice->mPosition.store(0u, std::memory_order_relaxed); - voice->mPositionFrac.store(0, std::memory_order_relaxed); - voice->mCurrentBuffer.store(source->queue, std::memory_order_relaxed); - voice->mFlags = 0; - /* A source that's not playing or paused has any offset applied when it - * starts playing. - */ - if(const ALenum offsettype{source->OffsetType}) - { - const double offset{source->Offset}; - source->OffsetType = AL_NONE; - source->Offset = 0.0; - if(auto vpos = GetSampleOffset(BufferList, offsettype, offset)) - { - voice->mPosition.store(vpos->pos, std::memory_order_relaxed); - voice->mPositionFrac.store(vpos->frac, std::memory_order_relaxed); - voice->mCurrentBuffer.store(vpos->bufferitem, std::memory_order_relaxed); - if(vpos->pos != 0 || vpos->frac != 0 || vpos->bufferitem != source->queue) - voice->mFlags |= VoiceIsFading; - } - } - InitVoice(voice, source, BufferList, context.get(), device); - - source->VoiceIdx = vidx; - source->state = AL_PLAYING; - - cur->mVoice = voice; - cur->mSourceID = source->id; - cur->mState = VChangeState::Play; - } - if LIKELY(tail) - SendVoiceChanges(context.get(), tail); -} -END_API_FUNC - - -AL_API void AL_APIENTRY alSourcePause(ALuint source) -START_API_FUNC -{ alSourcePausev(1, &source); } -END_API_FUNC - -AL_API void AL_APIENTRY alSourcePausev(ALsizei n, const ALuint *sources) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - if UNLIKELY(n < 0) - context->setError(AL_INVALID_VALUE, "Pausing %d sources", n); - if UNLIKELY(n <= 0) return; - - al::vector extra_sources; - std::array source_storage; - al::span srchandles; - if LIKELY(static_cast(n) <= source_storage.size()) - srchandles = {source_storage.data(), static_cast(n)}; - else - { - extra_sources.resize(static_cast(n)); - srchandles = {extra_sources.data(), extra_sources.size()}; - } - - std::lock_guard _{context->mSourceLock}; - for(auto &srchdl : srchandles) - { - srchdl = LookupSource(context.get(), *sources); - if(!srchdl) - SETERR_RETURN(context, AL_INVALID_NAME,, "Invalid source ID %u", *sources); - ++sources; - } - - /* Pausing has to be done in two steps. First, for each source that's - * detected to be playing, chamge the voice (asynchronously) to - * stopping/paused. - */ - VoiceChange *tail{}, *cur{}; - for(ALsource *source : srchandles) - { - Voice *voice{GetSourceVoice(source, context.get())}; - if(GetSourceState(source, voice) == AL_PLAYING) - { - if(!cur) - cur = tail = GetVoiceChanger(context.get()); - else - { - cur->mNext.store(GetVoiceChanger(context.get()), std::memory_order_relaxed); - cur = cur->mNext.load(std::memory_order_relaxed); - } - cur->mVoice = voice; - cur->mSourceID = source->id; - cur->mState = VChangeState::Pause; - } - } - if LIKELY(tail) - { - SendVoiceChanges(context.get(), tail); - /* Second, now that the voice changes have been sent, because it's - * possible that the voice stopped after it was detected playing and - * before the voice got paused, recheck that the source is still - * considered playing and set it to paused if so. - */ - for(ALsource *source : srchandles) - { - Voice *voice{GetSourceVoice(source, context.get())}; - if(GetSourceState(source, voice) == AL_PLAYING) - source->state = AL_PAUSED; - } - } -} -END_API_FUNC - - -AL_API void AL_APIENTRY alSourceStop(ALuint source) -START_API_FUNC -{ alSourceStopv(1, &source); } -END_API_FUNC - -AL_API void AL_APIENTRY alSourceStopv(ALsizei n, const ALuint *sources) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - if UNLIKELY(n < 0) - context->setError(AL_INVALID_VALUE, "Stopping %d sources", n); - if UNLIKELY(n <= 0) return; - - al::vector extra_sources; - std::array source_storage; - al::span srchandles; - if LIKELY(static_cast(n) <= source_storage.size()) - srchandles = {source_storage.data(), static_cast(n)}; - else - { - extra_sources.resize(static_cast(n)); - srchandles = {extra_sources.data(), extra_sources.size()}; - } - - std::lock_guard _{context->mSourceLock}; - for(auto &srchdl : srchandles) - { - srchdl = LookupSource(context.get(), *sources); - if(!srchdl) - SETERR_RETURN(context, AL_INVALID_NAME,, "Invalid source ID %u", *sources); - ++sources; - } - - VoiceChange *tail{}, *cur{}; - for(ALsource *source : srchandles) - { - if(Voice *voice{GetSourceVoice(source, context.get())}) - { - if(!cur) - cur = tail = GetVoiceChanger(context.get()); - else - { - cur->mNext.store(GetVoiceChanger(context.get()), std::memory_order_relaxed); - cur = cur->mNext.load(std::memory_order_relaxed); - } - voice->mPendingChange.store(true, std::memory_order_relaxed); - cur->mVoice = voice; - cur->mSourceID = source->id; - cur->mState = VChangeState::Stop; - source->state = AL_STOPPED; - } - source->Offset = 0.0; - source->OffsetType = AL_NONE; - source->VoiceIdx = INVALID_VOICE_IDX; - } - if LIKELY(tail) - SendVoiceChanges(context.get(), tail); -} -END_API_FUNC - - -AL_API void AL_APIENTRY alSourceRewind(ALuint source) -START_API_FUNC -{ alSourceRewindv(1, &source); } -END_API_FUNC - -AL_API void AL_APIENTRY alSourceRewindv(ALsizei n, const ALuint *sources) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - if UNLIKELY(n < 0) - context->setError(AL_INVALID_VALUE, "Rewinding %d sources", n); - if UNLIKELY(n <= 0) return; - - al::vector extra_sources; - std::array source_storage; - al::span srchandles; - if LIKELY(static_cast(n) <= source_storage.size()) - srchandles = {source_storage.data(), static_cast(n)}; - else - { - extra_sources.resize(static_cast(n)); - srchandles = {extra_sources.data(), extra_sources.size()}; - } - - std::lock_guard _{context->mSourceLock}; - for(auto &srchdl : srchandles) - { - srchdl = LookupSource(context.get(), *sources); - if(!srchdl) - SETERR_RETURN(context, AL_INVALID_NAME,, "Invalid source ID %u", *sources); - ++sources; - } - - VoiceChange *tail{}, *cur{}; - for(ALsource *source : srchandles) - { - Voice *voice{GetSourceVoice(source, context.get())}; - if(source->state != AL_INITIAL) - { - if(!cur) - cur = tail = GetVoiceChanger(context.get()); - else - { - cur->mNext.store(GetVoiceChanger(context.get()), std::memory_order_relaxed); - cur = cur->mNext.load(std::memory_order_relaxed); - } - if(voice) - voice->mPendingChange.store(true, std::memory_order_relaxed); - cur->mVoice = voice; - cur->mSourceID = source->id; - cur->mState = VChangeState::Reset; - source->state = AL_INITIAL; - } - source->Offset = 0.0; - source->OffsetType = AL_NONE; - source->VoiceIdx = INVALID_VOICE_IDX; - } - if LIKELY(tail) - SendVoiceChanges(context.get(), tail); -} -END_API_FUNC - - -AL_API void AL_APIENTRY alSourceQueueBuffers(ALuint src, ALsizei nb, const ALuint *buffers) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - if UNLIKELY(nb < 0) - context->setError(AL_INVALID_VALUE, "Queueing %d buffers", nb); - if UNLIKELY(nb <= 0) return; - - std::lock_guard _{context->mSourceLock}; - ALsource *source{LookupSource(context.get(),src)}; - if UNLIKELY(!source) - SETERR_RETURN(context, AL_INVALID_NAME,, "Invalid source ID %u", src); - - /* Can't queue on a Static Source */ - if UNLIKELY(source->SourceType == AL_STATIC) - SETERR_RETURN(context, AL_INVALID_OPERATION,, "Queueing onto static source %u", src); - - /* Check for a valid Buffer, for its frequency and format */ - ALCdevice *device{context->mDevice.get()}; - ALbuffer *BufferFmt{nullptr}; - BufferlistItem *BufferList{source->queue}; - while(BufferList && !BufferFmt) - { - BufferFmt = static_cast(BufferList->mBuffer); - BufferList = BufferList->mNext.load(std::memory_order_relaxed); - } - - std::unique_lock buflock{device->BufferLock}; - BufferlistItem *BufferListStart{nullptr}; - BufferList = nullptr; - for(ALsizei i{0};i < nb;i++) - { - bool fmt_mismatch{false}; - ALbuffer *buffer{nullptr}; - if(buffers[i] && (buffer=LookupBuffer(device, buffers[i])) == nullptr) - { - context->setError(AL_INVALID_NAME, "Queueing invalid buffer ID %u", buffers[i]); - goto buffer_error; - } - if(buffer && buffer->mCallback) - { - context->setError(AL_INVALID_OPERATION, "Queueing callback buffer %u", buffers[i]); - goto buffer_error; - } - - if(!BufferListStart) - { - BufferListStart = new BufferlistItem{}; - BufferList = BufferListStart; - } - else - { - auto item = new BufferlistItem{}; - BufferList->mNext.store(item, std::memory_order_relaxed); - BufferList = item; - } - BufferList->mNext.store(nullptr, std::memory_order_relaxed); - BufferList->mSampleLen = buffer ? buffer->mSampleLen : 0; - BufferList->mBuffer = buffer; - if(!buffer) continue; - - IncrementRef(buffer->ref); - - if(buffer->MappedAccess != 0 && !(buffer->MappedAccess&AL_MAP_PERSISTENT_BIT_SOFT)) - { - context->setError(AL_INVALID_OPERATION, "Queueing non-persistently mapped buffer %u", - buffer->id); - goto buffer_error; - } - - if(BufferFmt == nullptr) - BufferFmt = buffer; - else - { - fmt_mismatch |= BufferFmt->mSampleRate != buffer->mSampleRate; - fmt_mismatch |= BufferFmt->mChannels != buffer->mChannels; - if(BufferFmt->isBFormat()) - { - fmt_mismatch |= BufferFmt->mAmbiLayout != buffer->mAmbiLayout; - fmt_mismatch |= BufferFmt->mAmbiScaling != buffer->mAmbiScaling; - } - fmt_mismatch |= BufferFmt->mAmbiOrder != buffer->mAmbiOrder; - fmt_mismatch |= BufferFmt->OriginalType != buffer->OriginalType; - } - if(fmt_mismatch) - { - context->setError(AL_INVALID_OPERATION, "Queueing buffer with mismatched format"); - - buffer_error: - /* A buffer failed (invalid ID or format), so unlock and release - * each buffer we had. */ - while(BufferListStart) - { - std::unique_ptr head{BufferListStart}; - BufferListStart = head->mNext.load(std::memory_order_relaxed); - if(auto *buf{static_cast(head->mBuffer)}) - DecrementRef(buf->ref); - } - return; - } - } - /* All buffers good. */ - buflock.unlock(); - - /* Source is now streaming */ - source->SourceType = AL_STREAMING; - - BufferList = source->queue; - if(!BufferList) - source->queue = BufferListStart; - else - { - BufferlistItem *next; - while((next=BufferList->mNext.load(std::memory_order_relaxed)) != nullptr) - BufferList = next; - BufferList->mNext.store(BufferListStart, std::memory_order_release); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alSourceUnqueueBuffers(ALuint src, ALsizei nb, ALuint *buffers) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - if UNLIKELY(nb < 0) - context->setError(AL_INVALID_VALUE, "Unqueueing %d buffers", nb); - if UNLIKELY(nb <= 0) return; - - std::lock_guard _{context->mSourceLock}; - ALsource *source{LookupSource(context.get(),src)}; - if UNLIKELY(!source) - SETERR_RETURN(context, AL_INVALID_NAME,, "Invalid source ID %u", src); - - if UNLIKELY(source->Looping) - SETERR_RETURN(context, AL_INVALID_VALUE,, "Unqueueing from looping source %u", src); - if UNLIKELY(source->SourceType != AL_STREAMING) - SETERR_RETURN(context, AL_INVALID_VALUE,, "Unqueueing from a non-streaming source %u", - src); - - /* Make sure enough buffers have been processed to unqueue. */ - BufferlistItem *BufferList{source->queue}; - Voice *voice{GetSourceVoice(source, context.get())}; - BufferlistItem *Current{nullptr}; - if(voice) - Current = voice->mCurrentBuffer.load(std::memory_order_relaxed); - else if(source->state == AL_INITIAL) - Current = BufferList; - if UNLIKELY(BufferList == Current) - SETERR_RETURN(context, AL_INVALID_VALUE,, "Unqueueing %d buffer%s (none processed)", nb, - (nb==1) ? "" : "s"); - - ALuint i{1u}; - while(i < static_cast(nb)) - { - /* If the next bufferlist to check is NULL or is the current one, it's - * trying to unqueue more buffers than are processed. - */ - BufferlistItem *next{BufferList->mNext.load(std::memory_order_relaxed)}; - if UNLIKELY(!next || next == Current) - SETERR_RETURN(context, AL_INVALID_VALUE,, "Unqueueing %d buffers (only %u processed)", - nb, i); - BufferList = next; - - ++i; - } - - do { - std::unique_ptr head{source->queue}; - source->queue = head->mNext.load(std::memory_order_relaxed); - - if(auto *buffer{static_cast(head->mBuffer)}) - { - *(buffers++) = buffer->id; - DecrementRef(buffer->ref); - } - else - *(buffers++) = 0; - } while(--nb); -} -END_API_FUNC - - -ALsource::ALsource() -{ - Direct.Gain = 1.0f; - Direct.GainHF = 1.0f; - Direct.HFReference = LOWPASSFREQREF; - Direct.GainLF = 1.0f; - Direct.LFReference = HIGHPASSFREQREF; - for(auto &send : Send) - { - send.Slot = nullptr; - send.Gain = 1.0f; - send.GainHF = 1.0f; - send.HFReference = LOWPASSFREQREF; - send.GainLF = 1.0f; - send.LFReference = HIGHPASSFREQREF; - } - - PropsClean.test_and_set(std::memory_order_relaxed); -} - -ALsource::~ALsource() -{ - BufferlistItem *BufferList{queue}; - while(BufferList != nullptr) - { - std::unique_ptr head{BufferList}; - BufferList = head->mNext.load(std::memory_order_relaxed); - if(auto *buffer{static_cast(head->mBuffer)}) - DecrementRef(buffer->ref); - } - queue = nullptr; - - auto clear_send = [](ALsource::SendData &send) -> void - { if(send.Slot) DecrementRef(send.Slot->ref); }; - std::for_each(Send.begin(), Send.end(), clear_send); -} - -void UpdateAllSourceProps(ALCcontext *context) -{ - std::lock_guard _{context->mSourceLock}; - auto voicelist = context->getVoicesSpan(); - ALuint vidx{0u}; - for(Voice *voice : voicelist) - { - ALuint sid{voice->mSourceID.load(std::memory_order_acquire)}; - ALsource *source = sid ? LookupSource(context, sid) : nullptr; - if(source && source->VoiceIdx == vidx) - { - if(!source->PropsClean.test_and_set(std::memory_order_acq_rel)) - UpdateSourceProps(source, voice, context); - } - ++vidx; - } -} - -SourceSubList::~SourceSubList() -{ - uint64_t usemask{~FreeMask}; - while(usemask) - { - const ALsizei idx{CountTrailingZeros(usemask)}; - al::destroy_at(Sources+idx); - usemask &= ~(1_u64 << idx); - } - FreeMask = ~usemask; - al_free(Sources); - Sources = nullptr; -} diff --git a/al/source.h b/al/source.h deleted file mode 100644 index c0281f3e..00000000 --- a/al/source.h +++ /dev/null @@ -1,127 +0,0 @@ -#ifndef AL_SOURCE_H -#define AL_SOURCE_H - -#include -#include -#include -#include -#include - -#include "AL/al.h" -#include "AL/alc.h" - -#include "alcontext.h" -#include "almalloc.h" -#include "alnumeric.h" -#include "alu.h" -#include "math_defs.h" -#include "vector.h" -#include "voice.h" - -struct ALbuffer; -struct ALeffectslot; -struct BufferlistItem; - - -#define DEFAULT_SENDS 2 - -#define INVALID_VOICE_IDX static_cast(-1) - - -struct ALsource { - /** Source properties. */ - float Pitch{1.0f}; - float Gain{1.0f}; - float OuterGain{0.0f}; - float MinGain{0.0f}; - float MaxGain{1.0f}; - float InnerAngle{360.0f}; - float OuterAngle{360.0f}; - float RefDistance{1.0f}; - float MaxDistance{std::numeric_limits::max()}; - float RolloffFactor{1.0f}; - std::array Position{{0.0f, 0.0f, 0.0f}}; - std::array Velocity{{0.0f, 0.0f, 0.0f}}; - std::array Direction{{0.0f, 0.0f, 0.0f}}; - std::array OrientAt{{0.0f, 0.0f, -1.0f}}; - std::array OrientUp{{0.0f, 1.0f, 0.0f}}; - bool HeadRelative{false}; - bool Looping{false}; - DistanceModel mDistanceModel{DistanceModel::Default}; - Resampler mResampler{ResamplerDefault}; - DirectMode DirectChannels{DirectMode::Off}; - SpatializeMode mSpatialize{SpatializeMode::Auto}; - - bool DryGainHFAuto{true}; - bool WetGainAuto{true}; - bool WetGainHFAuto{true}; - float OuterGainHF{1.0f}; - - float AirAbsorptionFactor{0.0f}; - float RoomRolloffFactor{0.0f}; - float DopplerFactor{1.0f}; - - /* NOTE: Stereo pan angles are specified in radians, counter-clockwise - * rather than clockwise. - */ - std::array StereoPan{{Deg2Rad( 30.0f), Deg2Rad(-30.0f)}}; - - float Radius{0.0f}; - - /** Direct filter and auxiliary send info. */ - struct { - float Gain; - float GainHF; - float HFReference; - float GainLF; - float LFReference; - } Direct; - struct SendData { - ALeffectslot *Slot; - float Gain; - float GainHF; - float HFReference; - float GainLF; - float LFReference; - }; - std::array Send; - - /** - * Last user-specified offset, and the offset type (bytes, samples, or - * seconds). - */ - double Offset{0.0}; - ALenum OffsetType{AL_NONE}; - - /** Source type (static, streaming, or undetermined) */ - ALenum SourceType{AL_UNDETERMINED}; - - /** Source state (initial, playing, paused, or stopped) */ - ALenum state{AL_INITIAL}; - - /** Source Buffer Queue head. */ - BufferlistItem *queue{nullptr}; - - std::atomic_flag PropsClean; - - /* Index into the context's Voices array. Lazily updated, only checked and - * reset when looking up the voice. - */ - ALuint VoiceIdx{INVALID_VOICE_IDX}; - - /** Self ID */ - ALuint id{0}; - - - ALsource(); - ~ALsource(); - - ALsource(const ALsource&) = delete; - ALsource& operator=(const ALsource&) = delete; - - DISABLE_ALLOC() -}; - -void UpdateAllSourceProps(ALCcontext *context); - -#endif diff --git a/al/state.cpp b/al/state.cpp deleted file mode 100644 index ae761fb8..00000000 --- a/al/state.cpp +++ /dev/null @@ -1,893 +0,0 @@ -/** - * OpenAL cross platform audio library - * Copyright (C) 1999-2000 by authors. - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - * Or go to http://www.gnu.org/copyleft/lgpl.html - */ - -#include "config.h" - -#include "version.h" - -#include -#include -#include -#include -#include - -#include "AL/al.h" -#include "AL/alc.h" -#include "AL/alext.h" - -#include "alcontext.h" -#include "almalloc.h" -#include "alnumeric.h" -#include "alspan.h" -#include "alu.h" -#include "atomic.h" -#include "core/except.h" -#include "event.h" -#include "inprogext.h" -#include "opthelpers.h" -#include "strutils.h" -#include "voice.h" - - -namespace { - -constexpr ALchar alVendor[] = "OpenAL Community"; -constexpr ALchar alVersion[] = "1.1 ALSOFT " ALSOFT_VERSION; -constexpr ALchar alRenderer[] = "OpenAL Soft"; - -// Error Messages -constexpr ALchar alNoError[] = "No Error"; -constexpr ALchar alErrInvalidName[] = "Invalid Name"; -constexpr ALchar alErrInvalidEnum[] = "Invalid Enum"; -constexpr ALchar alErrInvalidValue[] = "Invalid Value"; -constexpr ALchar alErrInvalidOp[] = "Invalid Operation"; -constexpr ALchar alErrOutOfMemory[] = "Out of Memory"; - -/* Resampler strings */ -template struct ResamplerName { }; -template<> struct ResamplerName -{ static constexpr const ALchar *Get() noexcept { return "Nearest"; } }; -template<> struct ResamplerName -{ static constexpr const ALchar *Get() noexcept { return "Linear"; } }; -template<> struct ResamplerName -{ static constexpr const ALchar *Get() noexcept { return "Cubic"; } }; -template<> struct ResamplerName -{ static constexpr const ALchar *Get() noexcept { return "11th order Sinc (fast)"; } }; -template<> struct ResamplerName -{ static constexpr const ALchar *Get() noexcept { return "11th order Sinc"; } }; -template<> struct ResamplerName -{ static constexpr const ALchar *Get() noexcept { return "23rd order Sinc (fast)"; } }; -template<> struct ResamplerName -{ static constexpr const ALchar *Get() noexcept { return "23rd order Sinc"; } }; - -const ALchar *GetResamplerName(const Resampler rtype) -{ -#define HANDLE_RESAMPLER(r) case r: return ResamplerName::Get() - switch(rtype) - { - HANDLE_RESAMPLER(Resampler::Point); - HANDLE_RESAMPLER(Resampler::Linear); - HANDLE_RESAMPLER(Resampler::Cubic); - HANDLE_RESAMPLER(Resampler::FastBSinc12); - HANDLE_RESAMPLER(Resampler::BSinc12); - HANDLE_RESAMPLER(Resampler::FastBSinc24); - HANDLE_RESAMPLER(Resampler::BSinc24); - } -#undef HANDLE_RESAMPLER - /* Should never get here. */ - throw std::runtime_error{"Unexpected resampler index"}; -} - -al::optional DistanceModelFromALenum(ALenum model) -{ - switch(model) - { - case AL_NONE: return al::make_optional(DistanceModel::Disable); - case AL_INVERSE_DISTANCE: return al::make_optional(DistanceModel::Inverse); - case AL_INVERSE_DISTANCE_CLAMPED: return al::make_optional(DistanceModel::InverseClamped); - case AL_LINEAR_DISTANCE: return al::make_optional(DistanceModel::Linear); - case AL_LINEAR_DISTANCE_CLAMPED: return al::make_optional(DistanceModel::LinearClamped); - case AL_EXPONENT_DISTANCE: return al::make_optional(DistanceModel::Exponent); - case AL_EXPONENT_DISTANCE_CLAMPED: return al::make_optional(DistanceModel::ExponentClamped); - } - return al::nullopt; -} -ALenum ALenumFromDistanceModel(DistanceModel model) -{ - switch(model) - { - case DistanceModel::Disable: return AL_NONE; - case DistanceModel::Inverse: return AL_INVERSE_DISTANCE; - case DistanceModel::InverseClamped: return AL_INVERSE_DISTANCE_CLAMPED; - case DistanceModel::Linear: return AL_LINEAR_DISTANCE; - case DistanceModel::LinearClamped: return AL_LINEAR_DISTANCE_CLAMPED; - case DistanceModel::Exponent: return AL_EXPONENT_DISTANCE; - case DistanceModel::ExponentClamped: return AL_EXPONENT_DISTANCE_CLAMPED; - } - throw std::runtime_error{"Unexpected distance model "+std::to_string(static_cast(model))}; -} - -} // namespace - -/* WARNING: Non-standard export! Not part of any extension, or exposed in the - * alcFunctions list. - */ -extern "C" AL_API const ALchar* AL_APIENTRY alsoft_get_version(void) -START_API_FUNC -{ - static const auto spoof = al::getenv("ALSOFT_SPOOF_VERSION"); - if(spoof) return spoof->c_str(); - return ALSOFT_VERSION; -} -END_API_FUNC - -#define DO_UPDATEPROPS() do { \ - if(!context->mDeferUpdates.load(std::memory_order_acquire)) \ - UpdateContextProps(context.get()); \ - else \ - context->mPropsClean.clear(std::memory_order_release); \ -} while(0) - - -AL_API void AL_APIENTRY alEnable(ALenum capability) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - std::lock_guard _{context->mPropLock}; - switch(capability) - { - case AL_SOURCE_DISTANCE_MODEL: - context->mSourceDistanceModel = true; - DO_UPDATEPROPS(); - break; - - default: - context->setError(AL_INVALID_VALUE, "Invalid enable property 0x%04x", capability); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alDisable(ALenum capability) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - std::lock_guard _{context->mPropLock}; - switch(capability) - { - case AL_SOURCE_DISTANCE_MODEL: - context->mSourceDistanceModel = false; - DO_UPDATEPROPS(); - break; - - default: - context->setError(AL_INVALID_VALUE, "Invalid disable property 0x%04x", capability); - } -} -END_API_FUNC - -AL_API ALboolean AL_APIENTRY alIsEnabled(ALenum capability) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return AL_FALSE; - - std::lock_guard _{context->mPropLock}; - ALboolean value{AL_FALSE}; - switch(capability) - { - case AL_SOURCE_DISTANCE_MODEL: - value = context->mSourceDistanceModel ? AL_TRUE : AL_FALSE; - break; - - default: - context->setError(AL_INVALID_VALUE, "Invalid is enabled property 0x%04x", capability); - } - - return value; -} -END_API_FUNC - -AL_API ALboolean AL_APIENTRY alGetBoolean(ALenum pname) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return AL_FALSE; - - std::lock_guard _{context->mPropLock}; - ALboolean value{AL_FALSE}; - switch(pname) - { - case AL_DOPPLER_FACTOR: - if(context->mDopplerFactor != 0.0f) - value = AL_TRUE; - break; - - case AL_DOPPLER_VELOCITY: - if(context->mDopplerVelocity != 0.0f) - value = AL_TRUE; - break; - - case AL_DISTANCE_MODEL: - if(context->mDistanceModel == DistanceModel::Default) - value = AL_TRUE; - break; - - case AL_SPEED_OF_SOUND: - if(context->mSpeedOfSound != 0.0f) - value = AL_TRUE; - break; - - case AL_DEFERRED_UPDATES_SOFT: - if(context->mDeferUpdates.load(std::memory_order_acquire)) - value = AL_TRUE; - break; - - case AL_GAIN_LIMIT_SOFT: - if(GainMixMax/context->mGainBoost != 0.0f) - value = AL_TRUE; - break; - - case AL_NUM_RESAMPLERS_SOFT: - /* Always non-0. */ - value = AL_TRUE; - break; - - case AL_DEFAULT_RESAMPLER_SOFT: - value = static_cast(ResamplerDefault) ? AL_TRUE : AL_FALSE; - break; - - default: - context->setError(AL_INVALID_VALUE, "Invalid boolean property 0x%04x", pname); - } - - return value; -} -END_API_FUNC - -AL_API ALdouble AL_APIENTRY alGetDouble(ALenum pname) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return 0.0; - - std::lock_guard _{context->mPropLock}; - ALdouble value{0.0}; - switch(pname) - { - case AL_DOPPLER_FACTOR: - value = context->mDopplerFactor; - break; - - case AL_DOPPLER_VELOCITY: - value = context->mDopplerVelocity; - break; - - case AL_DISTANCE_MODEL: - value = static_cast(ALenumFromDistanceModel(context->mDistanceModel)); - break; - - case AL_SPEED_OF_SOUND: - value = context->mSpeedOfSound; - break; - - case AL_DEFERRED_UPDATES_SOFT: - if(context->mDeferUpdates.load(std::memory_order_acquire)) - value = static_cast(AL_TRUE); - break; - - case AL_GAIN_LIMIT_SOFT: - value = ALdouble{GainMixMax}/context->mGainBoost; - break; - - case AL_NUM_RESAMPLERS_SOFT: - value = static_cast(Resampler::Max) + 1.0; - break; - - case AL_DEFAULT_RESAMPLER_SOFT: - value = static_cast(ResamplerDefault); - break; - - default: - context->setError(AL_INVALID_VALUE, "Invalid double property 0x%04x", pname); - } - - return value; -} -END_API_FUNC - -AL_API ALfloat AL_APIENTRY alGetFloat(ALenum pname) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return 0.0f; - - std::lock_guard _{context->mPropLock}; - ALfloat value{0.0f}; - switch(pname) - { - case AL_DOPPLER_FACTOR: - value = context->mDopplerFactor; - break; - - case AL_DOPPLER_VELOCITY: - value = context->mDopplerVelocity; - break; - - case AL_DISTANCE_MODEL: - value = static_cast(ALenumFromDistanceModel(context->mDistanceModel)); - break; - - case AL_SPEED_OF_SOUND: - value = context->mSpeedOfSound; - break; - - case AL_DEFERRED_UPDATES_SOFT: - if(context->mDeferUpdates.load(std::memory_order_acquire)) - value = static_cast(AL_TRUE); - break; - - case AL_GAIN_LIMIT_SOFT: - value = GainMixMax/context->mGainBoost; - break; - - case AL_NUM_RESAMPLERS_SOFT: - value = static_cast(Resampler::Max) + 1.0f; - break; - - case AL_DEFAULT_RESAMPLER_SOFT: - value = static_cast(ResamplerDefault); - break; - - default: - context->setError(AL_INVALID_VALUE, "Invalid float property 0x%04x", pname); - } - - return value; -} -END_API_FUNC - -AL_API ALint AL_APIENTRY alGetInteger(ALenum pname) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return 0; - - std::lock_guard _{context->mPropLock}; - ALint value{0}; - switch(pname) - { - case AL_DOPPLER_FACTOR: - value = static_cast(context->mDopplerFactor); - break; - - case AL_DOPPLER_VELOCITY: - value = static_cast(context->mDopplerVelocity); - break; - - case AL_DISTANCE_MODEL: - value = ALenumFromDistanceModel(context->mDistanceModel); - break; - - case AL_SPEED_OF_SOUND: - value = static_cast(context->mSpeedOfSound); - break; - - case AL_DEFERRED_UPDATES_SOFT: - if(context->mDeferUpdates.load(std::memory_order_acquire)) - value = AL_TRUE; - break; - - case AL_GAIN_LIMIT_SOFT: - value = static_cast(GainMixMax/context->mGainBoost); - break; - - case AL_NUM_RESAMPLERS_SOFT: - value = static_cast(Resampler::Max) + 1; - break; - - case AL_DEFAULT_RESAMPLER_SOFT: - value = static_cast(ResamplerDefault); - break; - - default: - context->setError(AL_INVALID_VALUE, "Invalid integer property 0x%04x", pname); - } - - return value; -} -END_API_FUNC - -extern "C" AL_API ALint64SOFT AL_APIENTRY alGetInteger64SOFT(ALenum pname) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return 0_i64; - - std::lock_guard _{context->mPropLock}; - ALint64SOFT value{0}; - switch(pname) - { - case AL_DOPPLER_FACTOR: - value = static_cast(context->mDopplerFactor); - break; - - case AL_DOPPLER_VELOCITY: - value = static_cast(context->mDopplerVelocity); - break; - - case AL_DISTANCE_MODEL: - value = ALenumFromDistanceModel(context->mDistanceModel); - break; - - case AL_SPEED_OF_SOUND: - value = static_cast(context->mSpeedOfSound); - break; - - case AL_DEFERRED_UPDATES_SOFT: - if(context->mDeferUpdates.load(std::memory_order_acquire)) - value = AL_TRUE; - break; - - case AL_GAIN_LIMIT_SOFT: - value = static_cast(GainMixMax/context->mGainBoost); - break; - - case AL_NUM_RESAMPLERS_SOFT: - value = static_cast(Resampler::Max) + 1; - break; - - case AL_DEFAULT_RESAMPLER_SOFT: - value = static_cast(ResamplerDefault); - break; - - default: - context->setError(AL_INVALID_VALUE, "Invalid integer64 property 0x%04x", pname); - } - - return value; -} -END_API_FUNC - -AL_API ALvoid* AL_APIENTRY alGetPointerSOFT(ALenum pname) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return nullptr; - - std::lock_guard _{context->mPropLock}; - void *value{nullptr}; - switch(pname) - { - case AL_EVENT_CALLBACK_FUNCTION_SOFT: - value = reinterpret_cast(context->mEventCb); - break; - - case AL_EVENT_CALLBACK_USER_PARAM_SOFT: - value = context->mEventParam; - break; - - default: - context->setError(AL_INVALID_VALUE, "Invalid pointer property 0x%04x", pname); - } - - return value; -} -END_API_FUNC - -AL_API void AL_APIENTRY alGetBooleanv(ALenum pname, ALboolean *values) -START_API_FUNC -{ - if(values) - { - switch(pname) - { - case AL_DOPPLER_FACTOR: - case AL_DOPPLER_VELOCITY: - case AL_DISTANCE_MODEL: - case AL_SPEED_OF_SOUND: - case AL_DEFERRED_UPDATES_SOFT: - case AL_GAIN_LIMIT_SOFT: - case AL_NUM_RESAMPLERS_SOFT: - case AL_DEFAULT_RESAMPLER_SOFT: - values[0] = alGetBoolean(pname); - return; - } - } - - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - if(!values) - context->setError(AL_INVALID_VALUE, "NULL pointer"); - else switch(pname) - { - default: - context->setError(AL_INVALID_VALUE, "Invalid boolean-vector property 0x%04x", pname); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alGetDoublev(ALenum pname, ALdouble *values) -START_API_FUNC -{ - if(values) - { - switch(pname) - { - case AL_DOPPLER_FACTOR: - case AL_DOPPLER_VELOCITY: - case AL_DISTANCE_MODEL: - case AL_SPEED_OF_SOUND: - case AL_DEFERRED_UPDATES_SOFT: - case AL_GAIN_LIMIT_SOFT: - case AL_NUM_RESAMPLERS_SOFT: - case AL_DEFAULT_RESAMPLER_SOFT: - values[0] = alGetDouble(pname); - return; - } - } - - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - if(!values) - context->setError(AL_INVALID_VALUE, "NULL pointer"); - else switch(pname) - { - default: - context->setError(AL_INVALID_VALUE, "Invalid double-vector property 0x%04x", pname); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alGetFloatv(ALenum pname, ALfloat *values) -START_API_FUNC -{ - if(values) - { - switch(pname) - { - case AL_DOPPLER_FACTOR: - case AL_DOPPLER_VELOCITY: - case AL_DISTANCE_MODEL: - case AL_SPEED_OF_SOUND: - case AL_DEFERRED_UPDATES_SOFT: - case AL_GAIN_LIMIT_SOFT: - case AL_NUM_RESAMPLERS_SOFT: - case AL_DEFAULT_RESAMPLER_SOFT: - values[0] = alGetFloat(pname); - return; - } - } - - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - if(!values) - context->setError(AL_INVALID_VALUE, "NULL pointer"); - else switch(pname) - { - default: - context->setError(AL_INVALID_VALUE, "Invalid float-vector property 0x%04x", pname); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alGetIntegerv(ALenum pname, ALint *values) -START_API_FUNC -{ - if(values) - { - switch(pname) - { - case AL_DOPPLER_FACTOR: - case AL_DOPPLER_VELOCITY: - case AL_DISTANCE_MODEL: - case AL_SPEED_OF_SOUND: - case AL_DEFERRED_UPDATES_SOFT: - case AL_GAIN_LIMIT_SOFT: - case AL_NUM_RESAMPLERS_SOFT: - case AL_DEFAULT_RESAMPLER_SOFT: - values[0] = alGetInteger(pname); - return; - } - } - - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - if(!values) - context->setError(AL_INVALID_VALUE, "NULL pointer"); - else switch(pname) - { - default: - context->setError(AL_INVALID_VALUE, "Invalid integer-vector property 0x%04x", pname); - } -} -END_API_FUNC - -extern "C" AL_API void AL_APIENTRY alGetInteger64vSOFT(ALenum pname, ALint64SOFT *values) -START_API_FUNC -{ - if(values) - { - switch(pname) - { - case AL_DOPPLER_FACTOR: - case AL_DOPPLER_VELOCITY: - case AL_DISTANCE_MODEL: - case AL_SPEED_OF_SOUND: - case AL_DEFERRED_UPDATES_SOFT: - case AL_GAIN_LIMIT_SOFT: - case AL_NUM_RESAMPLERS_SOFT: - case AL_DEFAULT_RESAMPLER_SOFT: - values[0] = alGetInteger64SOFT(pname); - return; - } - } - - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - if(!values) - context->setError(AL_INVALID_VALUE, "NULL pointer"); - else switch(pname) - { - default: - context->setError(AL_INVALID_VALUE, "Invalid integer64-vector property 0x%04x", pname); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alGetPointervSOFT(ALenum pname, ALvoid **values) -START_API_FUNC -{ - if(values) - { - switch(pname) - { - case AL_EVENT_CALLBACK_FUNCTION_SOFT: - case AL_EVENT_CALLBACK_USER_PARAM_SOFT: - values[0] = alGetPointerSOFT(pname); - return; - } - } - - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - if(!values) - context->setError(AL_INVALID_VALUE, "NULL pointer"); - else switch(pname) - { - default: - context->setError(AL_INVALID_VALUE, "Invalid pointer-vector property 0x%04x", pname); - } -} -END_API_FUNC - -AL_API const ALchar* AL_APIENTRY alGetString(ALenum pname) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return nullptr; - - const ALchar *value{nullptr}; - switch(pname) - { - case AL_VENDOR: - value = alVendor; - break; - - case AL_VERSION: - value = alVersion; - break; - - case AL_RENDERER: - value = alRenderer; - break; - - case AL_EXTENSIONS: - value = context->mExtensionList; - break; - - case AL_NO_ERROR: - value = alNoError; - break; - - case AL_INVALID_NAME: - value = alErrInvalidName; - break; - - case AL_INVALID_ENUM: - value = alErrInvalidEnum; - break; - - case AL_INVALID_VALUE: - value = alErrInvalidValue; - break; - - case AL_INVALID_OPERATION: - value = alErrInvalidOp; - break; - - case AL_OUT_OF_MEMORY: - value = alErrOutOfMemory; - break; - - default: - context->setError(AL_INVALID_VALUE, "Invalid string property 0x%04x", pname); - } - return value; -} -END_API_FUNC - -AL_API void AL_APIENTRY alDopplerFactor(ALfloat value) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - if(!(value >= 0.0f && std::isfinite(value))) - context->setError(AL_INVALID_VALUE, "Doppler factor %f out of range", value); - else - { - std::lock_guard _{context->mPropLock}; - context->mDopplerFactor = value; - DO_UPDATEPROPS(); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alDopplerVelocity(ALfloat value) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - if(!(value >= 0.0f && std::isfinite(value))) - context->setError(AL_INVALID_VALUE, "Doppler velocity %f out of range", value); - else - { - std::lock_guard _{context->mPropLock}; - context->mDopplerVelocity = value; - DO_UPDATEPROPS(); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alSpeedOfSound(ALfloat value) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - if(!(value > 0.0f && std::isfinite(value))) - context->setError(AL_INVALID_VALUE, "Speed of sound %f out of range", value); - else - { - std::lock_guard _{context->mPropLock}; - context->mSpeedOfSound = value; - DO_UPDATEPROPS(); - } -} -END_API_FUNC - -AL_API void AL_APIENTRY alDistanceModel(ALenum value) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - if(auto model = DistanceModelFromALenum(value)) - { - std::lock_guard _{context->mPropLock}; - context->mDistanceModel = *model; - if(!context->mSourceDistanceModel) - DO_UPDATEPROPS(); - } - else - context->setError(AL_INVALID_VALUE, "Distance model 0x%04x out of range", value); -} -END_API_FUNC - - -AL_API void AL_APIENTRY alDeferUpdatesSOFT(void) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - context->deferUpdates(); -} -END_API_FUNC - -AL_API void AL_APIENTRY alProcessUpdatesSOFT(void) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return; - - context->processUpdates(); -} -END_API_FUNC - - -AL_API const ALchar* AL_APIENTRY alGetStringiSOFT(ALenum pname, ALsizei index) -START_API_FUNC -{ - ContextRef context{GetContextRef()}; - if UNLIKELY(!context) return nullptr; - - const ALchar *value{nullptr}; - switch(pname) - { - case AL_RESAMPLER_NAME_SOFT: - if(index < 0 || index > static_cast(Resampler::Max)) - context->setError(AL_INVALID_VALUE, "Resampler name index %d out of range", index); - else - value = GetResamplerName(static_cast(index)); - break; - - default: - context->setError(AL_INVALID_VALUE, "Invalid string indexed property"); - } - return value; -} -END_API_FUNC - - -void UpdateContextProps(ALCcontext *context) -{ - /* Get an unused proprty container, or allocate a new one as needed. */ - ContextProps *props{context->mFreeContextProps.load(std::memory_order_acquire)}; - if(!props) - props = new ContextProps{}; - else - { - ContextProps *next; - do { - next = props->next.load(std::memory_order_relaxed); - } while(context->mFreeContextProps.compare_exchange_weak(props, next, - std::memory_order_seq_cst, std::memory_order_acquire) == 0); - } - - /* Copy in current property values. */ - props->DopplerFactor = context->mDopplerFactor; - props->DopplerVelocity = context->mDopplerVelocity; - props->SpeedOfSound = context->mSpeedOfSound; - - props->SourceDistanceModel = context->mSourceDistanceModel; - props->mDistanceModel = context->mDistanceModel; - - /* Set the new container for updating internal parameters. */ - props = context->mParams.ContextUpdate.exchange(props, std::memory_order_acq_rel); - if(props) - { - /* If there was an unused update container, put it back in the - * freelist. - */ - AtomicReplaceHead(context->mFreeContextProps, props); - } -} diff --git a/alc/alc.cpp b/alc/alc.cpp deleted file mode 100644 index e7c85525..00000000 --- a/alc/alc.cpp +++ /dev/null @@ -1,4130 +0,0 @@ -/** - * OpenAL cross platform audio library - * Copyright (C) 1999-2007 by authors. - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - * Or go to http://www.gnu.org/copyleft/lgpl.html - */ - -#include "config.h" - -#include "version.h" - -#ifdef _WIN32 -#define WIN32_LEAN_AND_MEAN -#include -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "AL/al.h" -#include "AL/alc.h" -#include "AL/alext.h" -#include "AL/efx.h" - -#include "al/auxeffectslot.h" -#include "al/buffer.h" -#include "al/effect.h" -#include "al/event.h" -#include "al/filter.h" -#include "al/listener.h" -#include "al/source.h" -#include "alcmain.h" -#include "albyte.h" -#include "alconfig.h" -#include "alcontext.h" -#include "almalloc.h" -#include "alnumeric.h" -#include "aloptional.h" -#include "alspan.h" -#include "alstring.h" -#include "alu.h" -#include "async_event.h" -#include "atomic.h" -#include "bformatdec.h" -#include "compat.h" -#include "core/ambidefs.h" -#include "core/bs2b.h" -#include "core/cpu_caps.h" -#include "core/devformat.h" -#include "core/except.h" -#include "core/mastering.h" -#include "core/filters/nfc.h" -#include "core/filters/splitter.h" -#include "core/fpu_ctrl.h" -#include "core/logging.h" -#include "core/uhjfilter.h" -#include "effects/base.h" -#include "front_stablizer.h" -#include "hrtf.h" -#include "inprogext.h" -#include "intrusive_ptr.h" -#include "opthelpers.h" -#include "pragmadefs.h" -#include "ringbuffer.h" -#include "strutils.h" -#include "threads.h" -#include "vecmat.h" -#include "vector.h" -#include "voice_change.h" - -#include "backends/base.h" -#include "backends/null.h" -#include "backends/loopback.h" -#ifdef HAVE_JACK -#include "backends/jack.h" -#endif -#ifdef HAVE_PULSEAUDIO -#include "backends/pulseaudio.h" -#endif -#ifdef HAVE_ALSA -#include "backends/alsa.h" -#endif -#ifdef HAVE_WASAPI -#include "backends/wasapi.h" -#endif -#ifdef HAVE_COREAUDIO -#include "backends/coreaudio.h" -#endif -#ifdef HAVE_OPENSL -#include "backends/opensl.h" -#endif -#ifdef HAVE_OBOE -#include "backends/oboe.h" -#endif -#ifdef HAVE_SOLARIS -#include "backends/solaris.h" -#endif -#ifdef HAVE_SNDIO -#include "backends/sndio.h" -#endif -#ifdef HAVE_OSS -#include "backends/oss.h" -#endif -#ifdef HAVE_DSOUND -#include "backends/dsound.h" -#endif -#ifdef HAVE_WINMM -#include "backends/winmm.h" -#endif -#ifdef HAVE_PORTAUDIO -#include "backends/portaudio.h" -#endif -#ifdef HAVE_SDL2 -#include "backends/sdl2.h" -#endif -#ifdef HAVE_WAVE -#include "backends/wave.h" -#endif - - -namespace { - -using namespace std::placeholders; -using std::chrono::seconds; -using std::chrono::nanoseconds; - -using voidp = void*; - - -/************************************************ - * Backends - ************************************************/ -struct BackendInfo { - const char *name; - BackendFactory& (*getFactory)(void); -}; - -BackendInfo BackendList[] = { -#ifdef HAVE_JACK - { "jack", JackBackendFactory::getFactory }, -#endif -#ifdef HAVE_PULSEAUDIO - { "pulse", PulseBackendFactory::getFactory }, -#endif -#ifdef HAVE_ALSA - { "alsa", AlsaBackendFactory::getFactory }, -#endif -#ifdef HAVE_WASAPI - { "wasapi", WasapiBackendFactory::getFactory }, -#endif -#ifdef HAVE_COREAUDIO - { "core", CoreAudioBackendFactory::getFactory }, -#endif -#ifdef HAVE_OBOE - { "oboe", OboeBackendFactory::getFactory }, -#endif -#ifdef HAVE_OPENSL - { "opensl", OSLBackendFactory::getFactory }, -#endif -#ifdef HAVE_SOLARIS - { "solaris", SolarisBackendFactory::getFactory }, -#endif -#ifdef HAVE_SNDIO - { "sndio", SndIOBackendFactory::getFactory }, -#endif -#ifdef HAVE_OSS - { "oss", OSSBackendFactory::getFactory }, -#endif -#ifdef HAVE_DSOUND - { "dsound", DSoundBackendFactory::getFactory }, -#endif -#ifdef HAVE_WINMM - { "winmm", WinMMBackendFactory::getFactory }, -#endif -#ifdef HAVE_PORTAUDIO - { "port", PortBackendFactory::getFactory }, -#endif -#ifdef HAVE_SDL2 - { "sdl2", SDL2BackendFactory::getFactory }, -#endif - - { "null", NullBackendFactory::getFactory }, -#ifdef HAVE_WAVE - { "wave", WaveBackendFactory::getFactory }, -#endif -}; - -BackendFactory *PlaybackFactory{}; -BackendFactory *CaptureFactory{}; - - -/************************************************ - * Functions, enums, and errors - ************************************************/ -#define DECL(x) { #x, reinterpret_cast(x) } -const struct { - const char *funcName; - void *address; -} alcFunctions[] = { - DECL(alcCreateContext), - DECL(alcMakeContextCurrent), - DECL(alcProcessContext), - DECL(alcSuspendContext), - DECL(alcDestroyContext), - DECL(alcGetCurrentContext), - DECL(alcGetContextsDevice), - DECL(alcOpenDevice), - DECL(alcCloseDevice), - DECL(alcGetError), - DECL(alcIsExtensionPresent), - DECL(alcGetProcAddress), - DECL(alcGetEnumValue), - DECL(alcGetString), - DECL(alcGetIntegerv), - DECL(alcCaptureOpenDevice), - DECL(alcCaptureCloseDevice), - DECL(alcCaptureStart), - DECL(alcCaptureStop), - DECL(alcCaptureSamples), - - DECL(alcSetThreadContext), - DECL(alcGetThreadContext), - - DECL(alcLoopbackOpenDeviceSOFT), - DECL(alcIsRenderFormatSupportedSOFT), - DECL(alcRenderSamplesSOFT), - - DECL(alcDevicePauseSOFT), - DECL(alcDeviceResumeSOFT), - - DECL(alcGetStringiSOFT), - DECL(alcResetDeviceSOFT), - - DECL(alcGetInteger64vSOFT), - - DECL(alEnable), - DECL(alDisable), - DECL(alIsEnabled), - DECL(alGetString), - DECL(alGetBooleanv), - DECL(alGetIntegerv), - DECL(alGetFloatv), - DECL(alGetDoublev), - DECL(alGetBoolean), - DECL(alGetInteger), - DECL(alGetFloat), - DECL(alGetDouble), - DECL(alGetError), - DECL(alIsExtensionPresent), - DECL(alGetProcAddress), - DECL(alGetEnumValue), - DECL(alListenerf), - DECL(alListener3f), - DECL(alListenerfv), - DECL(alListeneri), - DECL(alListener3i), - DECL(alListeneriv), - DECL(alGetListenerf), - DECL(alGetListener3f), - DECL(alGetListenerfv), - DECL(alGetListeneri), - DECL(alGetListener3i), - DECL(alGetListeneriv), - DECL(alGenSources), - DECL(alDeleteSources), - DECL(alIsSource), - DECL(alSourcef), - DECL(alSource3f), - DECL(alSourcefv), - DECL(alSourcei), - DECL(alSource3i), - DECL(alSourceiv), - DECL(alGetSourcef), - DECL(alGetSource3f), - DECL(alGetSourcefv), - DECL(alGetSourcei), - DECL(alGetSource3i), - DECL(alGetSourceiv), - DECL(alSourcePlayv), - DECL(alSourceStopv), - DECL(alSourceRewindv), - DECL(alSourcePausev), - DECL(alSourcePlay), - DECL(alSourceStop), - DECL(alSourceRewind), - DECL(alSourcePause), - DECL(alSourceQueueBuffers), - DECL(alSourceUnqueueBuffers), - DECL(alGenBuffers), - DECL(alDeleteBuffers), - DECL(alIsBuffer), - DECL(alBufferData), - DECL(alBufferf), - DECL(alBuffer3f), - DECL(alBufferfv), - DECL(alBufferi), - DECL(alBuffer3i), - DECL(alBufferiv), - DECL(alGetBufferf), - DECL(alGetBuffer3f), - DECL(alGetBufferfv), - DECL(alGetBufferi), - DECL(alGetBuffer3i), - DECL(alGetBufferiv), - DECL(alDopplerFactor), - DECL(alDopplerVelocity), - DECL(alSpeedOfSound), - DECL(alDistanceModel), - - DECL(alGenFilters), - DECL(alDeleteFilters), - DECL(alIsFilter), - DECL(alFilteri), - DECL(alFilteriv), - DECL(alFilterf), - DECL(alFilterfv), - DECL(alGetFilteri), - DECL(alGetFilteriv), - DECL(alGetFilterf), - DECL(alGetFilterfv), - DECL(alGenEffects), - DECL(alDeleteEffects), - DECL(alIsEffect), - DECL(alEffecti), - DECL(alEffectiv), - DECL(alEffectf), - DECL(alEffectfv), - DECL(alGetEffecti), - DECL(alGetEffectiv), - DECL(alGetEffectf), - DECL(alGetEffectfv), - DECL(alGenAuxiliaryEffectSlots), - DECL(alDeleteAuxiliaryEffectSlots), - DECL(alIsAuxiliaryEffectSlot), - DECL(alAuxiliaryEffectSloti), - DECL(alAuxiliaryEffectSlotiv), - DECL(alAuxiliaryEffectSlotf), - DECL(alAuxiliaryEffectSlotfv), - DECL(alGetAuxiliaryEffectSloti), - DECL(alGetAuxiliaryEffectSlotiv), - DECL(alGetAuxiliaryEffectSlotf), - DECL(alGetAuxiliaryEffectSlotfv), - - DECL(alDeferUpdatesSOFT), - DECL(alProcessUpdatesSOFT), - - DECL(alSourcedSOFT), - DECL(alSource3dSOFT), - DECL(alSourcedvSOFT), - DECL(alGetSourcedSOFT), - DECL(alGetSource3dSOFT), - DECL(alGetSourcedvSOFT), - DECL(alSourcei64SOFT), - DECL(alSource3i64SOFT), - DECL(alSourcei64vSOFT), - DECL(alGetSourcei64SOFT), - DECL(alGetSource3i64SOFT), - DECL(alGetSourcei64vSOFT), - - DECL(alGetStringiSOFT), - - DECL(alBufferStorageSOFT), - DECL(alMapBufferSOFT), - DECL(alUnmapBufferSOFT), - DECL(alFlushMappedBufferSOFT), - - DECL(alEventControlSOFT), - DECL(alEventCallbackSOFT), - DECL(alGetPointerSOFT), - DECL(alGetPointervSOFT), - - DECL(alBufferCallbackSOFT), - DECL(alGetBufferPtrSOFT), - DECL(alGetBuffer3PtrSOFT), - DECL(alGetBufferPtrvSOFT), - - DECL(alAuxiliaryEffectSlotPlaySOFT), - DECL(alAuxiliaryEffectSlotPlayvSOFT), - DECL(alAuxiliaryEffectSlotStopSOFT), - DECL(alAuxiliaryEffectSlotStopvSOFT), -}; -#undef DECL - -#define DECL(x) { #x, (x) } -constexpr struct { - const ALCchar *enumName; - ALCenum value; -} alcEnumerations[] = { - DECL(ALC_INVALID), - DECL(ALC_FALSE), - DECL(ALC_TRUE), - - DECL(ALC_MAJOR_VERSION), - DECL(ALC_MINOR_VERSION), - DECL(ALC_ATTRIBUTES_SIZE), - DECL(ALC_ALL_ATTRIBUTES), - DECL(ALC_DEFAULT_DEVICE_SPECIFIER), - DECL(ALC_DEVICE_SPECIFIER), - DECL(ALC_ALL_DEVICES_SPECIFIER), - DECL(ALC_DEFAULT_ALL_DEVICES_SPECIFIER), - DECL(ALC_EXTENSIONS), - DECL(ALC_FREQUENCY), - DECL(ALC_REFRESH), - DECL(ALC_SYNC), - DECL(ALC_MONO_SOURCES), - DECL(ALC_STEREO_SOURCES), - DECL(ALC_CAPTURE_DEVICE_SPECIFIER), - DECL(ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER), - DECL(ALC_CAPTURE_SAMPLES), - DECL(ALC_CONNECTED), - - DECL(ALC_EFX_MAJOR_VERSION), - DECL(ALC_EFX_MINOR_VERSION), - DECL(ALC_MAX_AUXILIARY_SENDS), - - DECL(ALC_FORMAT_CHANNELS_SOFT), - DECL(ALC_FORMAT_TYPE_SOFT), - - DECL(ALC_MONO_SOFT), - DECL(ALC_STEREO_SOFT), - DECL(ALC_QUAD_SOFT), - DECL(ALC_5POINT1_SOFT), - DECL(ALC_6POINT1_SOFT), - DECL(ALC_7POINT1_SOFT), - DECL(ALC_BFORMAT3D_SOFT), - - DECL(ALC_BYTE_SOFT), - DECL(ALC_UNSIGNED_BYTE_SOFT), - DECL(ALC_SHORT_SOFT), - DECL(ALC_UNSIGNED_SHORT_SOFT), - DECL(ALC_INT_SOFT), - DECL(ALC_UNSIGNED_INT_SOFT), - DECL(ALC_FLOAT_SOFT), - - DECL(ALC_HRTF_SOFT), - DECL(ALC_DONT_CARE_SOFT), - DECL(ALC_HRTF_STATUS_SOFT), - DECL(ALC_HRTF_DISABLED_SOFT), - DECL(ALC_HRTF_ENABLED_SOFT), - DECL(ALC_HRTF_DENIED_SOFT), - DECL(ALC_HRTF_REQUIRED_SOFT), - DECL(ALC_HRTF_HEADPHONES_DETECTED_SOFT), - DECL(ALC_HRTF_UNSUPPORTED_FORMAT_SOFT), - DECL(ALC_NUM_HRTF_SPECIFIERS_SOFT), - DECL(ALC_HRTF_SPECIFIER_SOFT), - DECL(ALC_HRTF_ID_SOFT), - - DECL(ALC_AMBISONIC_LAYOUT_SOFT), - DECL(ALC_AMBISONIC_SCALING_SOFT), - DECL(ALC_AMBISONIC_ORDER_SOFT), - DECL(ALC_ACN_SOFT), - DECL(ALC_FUMA_SOFT), - DECL(ALC_N3D_SOFT), - DECL(ALC_SN3D_SOFT), - - DECL(ALC_OUTPUT_LIMITER_SOFT), - - DECL(ALC_NO_ERROR), - DECL(ALC_INVALID_DEVICE), - DECL(ALC_INVALID_CONTEXT), - DECL(ALC_INVALID_ENUM), - DECL(ALC_INVALID_VALUE), - DECL(ALC_OUT_OF_MEMORY), - - - DECL(AL_INVALID), - DECL(AL_NONE), - DECL(AL_FALSE), - DECL(AL_TRUE), - - DECL(AL_SOURCE_RELATIVE), - DECL(AL_CONE_INNER_ANGLE), - DECL(AL_CONE_OUTER_ANGLE), - DECL(AL_PITCH), - DECL(AL_POSITION), - DECL(AL_DIRECTION), - DECL(AL_VELOCITY), - DECL(AL_LOOPING), - DECL(AL_BUFFER), - DECL(AL_GAIN), - DECL(AL_MIN_GAIN), - DECL(AL_MAX_GAIN), - DECL(AL_ORIENTATION), - DECL(AL_REFERENCE_DISTANCE), - DECL(AL_ROLLOFF_FACTOR), - DECL(AL_CONE_OUTER_GAIN), - DECL(AL_MAX_DISTANCE), - DECL(AL_SEC_OFFSET), - DECL(AL_SAMPLE_OFFSET), - DECL(AL_BYTE_OFFSET), - DECL(AL_SOURCE_TYPE), - DECL(AL_STATIC), - DECL(AL_STREAMING), - DECL(AL_UNDETERMINED), - DECL(AL_METERS_PER_UNIT), - DECL(AL_LOOP_POINTS_SOFT), - DECL(AL_DIRECT_CHANNELS_SOFT), - - DECL(AL_DIRECT_FILTER), - DECL(AL_AUXILIARY_SEND_FILTER), - DECL(AL_AIR_ABSORPTION_FACTOR), - DECL(AL_ROOM_ROLLOFF_FACTOR), - DECL(AL_CONE_OUTER_GAINHF), - DECL(AL_DIRECT_FILTER_GAINHF_AUTO), - DECL(AL_AUXILIARY_SEND_FILTER_GAIN_AUTO), - DECL(AL_AUXILIARY_SEND_FILTER_GAINHF_AUTO), - - DECL(AL_SOURCE_STATE), - DECL(AL_INITIAL), - DECL(AL_PLAYING), - DECL(AL_PAUSED), - DECL(AL_STOPPED), - - DECL(AL_BUFFERS_QUEUED), - DECL(AL_BUFFERS_PROCESSED), - - DECL(AL_FORMAT_MONO8), - DECL(AL_FORMAT_MONO16), - DECL(AL_FORMAT_MONO_FLOAT32), - DECL(AL_FORMAT_MONO_DOUBLE_EXT), - DECL(AL_FORMAT_STEREO8), - DECL(AL_FORMAT_STEREO16), - DECL(AL_FORMAT_STEREO_FLOAT32), - DECL(AL_FORMAT_STEREO_DOUBLE_EXT), - DECL(AL_FORMAT_MONO_IMA4), - DECL(AL_FORMAT_STEREO_IMA4), - DECL(AL_FORMAT_MONO_MSADPCM_SOFT), - DECL(AL_FORMAT_STEREO_MSADPCM_SOFT), - DECL(AL_FORMAT_QUAD8_LOKI), - DECL(AL_FORMAT_QUAD16_LOKI), - DECL(AL_FORMAT_QUAD8), - DECL(AL_FORMAT_QUAD16), - DECL(AL_FORMAT_QUAD32), - DECL(AL_FORMAT_51CHN8), - DECL(AL_FORMAT_51CHN16), - DECL(AL_FORMAT_51CHN32), - DECL(AL_FORMAT_61CHN8), - DECL(AL_FORMAT_61CHN16), - DECL(AL_FORMAT_61CHN32), - DECL(AL_FORMAT_71CHN8), - DECL(AL_FORMAT_71CHN16), - DECL(AL_FORMAT_71CHN32), - DECL(AL_FORMAT_REAR8), - DECL(AL_FORMAT_REAR16), - DECL(AL_FORMAT_REAR32), - DECL(AL_FORMAT_MONO_MULAW), - DECL(AL_FORMAT_MONO_MULAW_EXT), - DECL(AL_FORMAT_STEREO_MULAW), - DECL(AL_FORMAT_STEREO_MULAW_EXT), - DECL(AL_FORMAT_QUAD_MULAW), - DECL(AL_FORMAT_51CHN_MULAW), - DECL(AL_FORMAT_61CHN_MULAW), - DECL(AL_FORMAT_71CHN_MULAW), - DECL(AL_FORMAT_REAR_MULAW), - DECL(AL_FORMAT_MONO_ALAW_EXT), - DECL(AL_FORMAT_STEREO_ALAW_EXT), - - DECL(AL_FORMAT_BFORMAT2D_8), - DECL(AL_FORMAT_BFORMAT2D_16), - DECL(AL_FORMAT_BFORMAT2D_FLOAT32), - DECL(AL_FORMAT_BFORMAT2D_MULAW), - DECL(AL_FORMAT_BFORMAT3D_8), - DECL(AL_FORMAT_BFORMAT3D_16), - DECL(AL_FORMAT_BFORMAT3D_FLOAT32), - DECL(AL_FORMAT_BFORMAT3D_MULAW), - - DECL(AL_FREQUENCY), - DECL(AL_BITS), - DECL(AL_CHANNELS), - DECL(AL_SIZE), - DECL(AL_UNPACK_BLOCK_ALIGNMENT_SOFT), - DECL(AL_PACK_BLOCK_ALIGNMENT_SOFT), - - DECL(AL_SOURCE_RADIUS), - - DECL(AL_STEREO_ANGLES), - - DECL(AL_UNUSED), - DECL(AL_PENDING), - DECL(AL_PROCESSED), - - DECL(AL_NO_ERROR), - DECL(AL_INVALID_NAME), - DECL(AL_INVALID_ENUM), - DECL(AL_INVALID_VALUE), - DECL(AL_INVALID_OPERATION), - DECL(AL_OUT_OF_MEMORY), - - DECL(AL_VENDOR), - DECL(AL_VERSION), - DECL(AL_RENDERER), - DECL(AL_EXTENSIONS), - - DECL(AL_DOPPLER_FACTOR), - DECL(AL_DOPPLER_VELOCITY), - DECL(AL_DISTANCE_MODEL), - DECL(AL_SPEED_OF_SOUND), - DECL(AL_SOURCE_DISTANCE_MODEL), - DECL(AL_DEFERRED_UPDATES_SOFT), - DECL(AL_GAIN_LIMIT_SOFT), - - DECL(AL_INVERSE_DISTANCE), - DECL(AL_INVERSE_DISTANCE_CLAMPED), - DECL(AL_LINEAR_DISTANCE), - DECL(AL_LINEAR_DISTANCE_CLAMPED), - DECL(AL_EXPONENT_DISTANCE), - DECL(AL_EXPONENT_DISTANCE_CLAMPED), - - DECL(AL_FILTER_TYPE), - DECL(AL_FILTER_NULL), - DECL(AL_FILTER_LOWPASS), - DECL(AL_FILTER_HIGHPASS), - DECL(AL_FILTER_BANDPASS), - - DECL(AL_LOWPASS_GAIN), - DECL(AL_LOWPASS_GAINHF), - - DECL(AL_HIGHPASS_GAIN), - DECL(AL_HIGHPASS_GAINLF), - - DECL(AL_BANDPASS_GAIN), - DECL(AL_BANDPASS_GAINHF), - DECL(AL_BANDPASS_GAINLF), - - DECL(AL_EFFECT_TYPE), - DECL(AL_EFFECT_NULL), - DECL(AL_EFFECT_REVERB), - DECL(AL_EFFECT_EAXREVERB), - DECL(AL_EFFECT_CHORUS), - DECL(AL_EFFECT_DISTORTION), - DECL(AL_EFFECT_ECHO), - DECL(AL_EFFECT_FLANGER), - DECL(AL_EFFECT_PITCH_SHIFTER), - DECL(AL_EFFECT_FREQUENCY_SHIFTER), - DECL(AL_EFFECT_VOCAL_MORPHER), - DECL(AL_EFFECT_RING_MODULATOR), - DECL(AL_EFFECT_AUTOWAH), - DECL(AL_EFFECT_COMPRESSOR), - DECL(AL_EFFECT_EQUALIZER), - DECL(AL_EFFECT_DEDICATED_LOW_FREQUENCY_EFFECT), - DECL(AL_EFFECT_DEDICATED_DIALOGUE), - - DECL(AL_EFFECTSLOT_EFFECT), - DECL(AL_EFFECTSLOT_GAIN), - DECL(AL_EFFECTSLOT_AUXILIARY_SEND_AUTO), - DECL(AL_EFFECTSLOT_NULL), - - DECL(AL_EAXREVERB_DENSITY), - DECL(AL_EAXREVERB_DIFFUSION), - DECL(AL_EAXREVERB_GAIN), - DECL(AL_EAXREVERB_GAINHF), - DECL(AL_EAXREVERB_GAINLF), - DECL(AL_EAXREVERB_DECAY_TIME), - DECL(AL_EAXREVERB_DECAY_HFRATIO), - DECL(AL_EAXREVERB_DECAY_LFRATIO), - DECL(AL_EAXREVERB_REFLECTIONS_GAIN), - DECL(AL_EAXREVERB_REFLECTIONS_DELAY), - DECL(AL_EAXREVERB_REFLECTIONS_PAN), - DECL(AL_EAXREVERB_LATE_REVERB_GAIN), - DECL(AL_EAXREVERB_LATE_REVERB_DELAY), - DECL(AL_EAXREVERB_LATE_REVERB_PAN), - DECL(AL_EAXREVERB_ECHO_TIME), - DECL(AL_EAXREVERB_ECHO_DEPTH), - DECL(AL_EAXREVERB_MODULATION_TIME), - DECL(AL_EAXREVERB_MODULATION_DEPTH), - DECL(AL_EAXREVERB_AIR_ABSORPTION_GAINHF), - DECL(AL_EAXREVERB_HFREFERENCE), - DECL(AL_EAXREVERB_LFREFERENCE), - DECL(AL_EAXREVERB_ROOM_ROLLOFF_FACTOR), - DECL(AL_EAXREVERB_DECAY_HFLIMIT), - - DECL(AL_REVERB_DENSITY), - DECL(AL_REVERB_DIFFUSION), - DECL(AL_REVERB_GAIN), - DECL(AL_REVERB_GAINHF), - DECL(AL_REVERB_DECAY_TIME), - DECL(AL_REVERB_DECAY_HFRATIO), - DECL(AL_REVERB_REFLECTIONS_GAIN), - DECL(AL_REVERB_REFLECTIONS_DELAY), - DECL(AL_REVERB_LATE_REVERB_GAIN), - DECL(AL_REVERB_LATE_REVERB_DELAY), - DECL(AL_REVERB_AIR_ABSORPTION_GAINHF), - DECL(AL_REVERB_ROOM_ROLLOFF_FACTOR), - DECL(AL_REVERB_DECAY_HFLIMIT), - - DECL(AL_CHORUS_WAVEFORM), - DECL(AL_CHORUS_PHASE), - DECL(AL_CHORUS_RATE), - DECL(AL_CHORUS_DEPTH), - DECL(AL_CHORUS_FEEDBACK), - DECL(AL_CHORUS_DELAY), - - DECL(AL_DISTORTION_EDGE), - DECL(AL_DISTORTION_GAIN), - DECL(AL_DISTORTION_LOWPASS_CUTOFF), - DECL(AL_DISTORTION_EQCENTER), - DECL(AL_DISTORTION_EQBANDWIDTH), - - DECL(AL_ECHO_DELAY), - DECL(AL_ECHO_LRDELAY), - DECL(AL_ECHO_DAMPING), - DECL(AL_ECHO_FEEDBACK), - DECL(AL_ECHO_SPREAD), - - DECL(AL_FLANGER_WAVEFORM), - DECL(AL_FLANGER_PHASE), - DECL(AL_FLANGER_RATE), - DECL(AL_FLANGER_DEPTH), - DECL(AL_FLANGER_FEEDBACK), - DECL(AL_FLANGER_DELAY), - - DECL(AL_FREQUENCY_SHIFTER_FREQUENCY), - DECL(AL_FREQUENCY_SHIFTER_LEFT_DIRECTION), - DECL(AL_FREQUENCY_SHIFTER_RIGHT_DIRECTION), - - DECL(AL_RING_MODULATOR_FREQUENCY), - DECL(AL_RING_MODULATOR_HIGHPASS_CUTOFF), - DECL(AL_RING_MODULATOR_WAVEFORM), - - DECL(AL_PITCH_SHIFTER_COARSE_TUNE), - DECL(AL_PITCH_SHIFTER_FINE_TUNE), - - DECL(AL_COMPRESSOR_ONOFF), - - DECL(AL_EQUALIZER_LOW_GAIN), - DECL(AL_EQUALIZER_LOW_CUTOFF), - DECL(AL_EQUALIZER_MID1_GAIN), - DECL(AL_EQUALIZER_MID1_CENTER), - DECL(AL_EQUALIZER_MID1_WIDTH), - DECL(AL_EQUALIZER_MID2_GAIN), - DECL(AL_EQUALIZER_MID2_CENTER), - DECL(AL_EQUALIZER_MID2_WIDTH), - DECL(AL_EQUALIZER_HIGH_GAIN), - DECL(AL_EQUALIZER_HIGH_CUTOFF), - - DECL(AL_DEDICATED_GAIN), - - DECL(AL_AUTOWAH_ATTACK_TIME), - DECL(AL_AUTOWAH_RELEASE_TIME), - DECL(AL_AUTOWAH_RESONANCE), - DECL(AL_AUTOWAH_PEAK_GAIN), - - DECL(AL_VOCAL_MORPHER_PHONEMEA), - DECL(AL_VOCAL_MORPHER_PHONEMEB_COARSE_TUNING), - DECL(AL_VOCAL_MORPHER_PHONEMEB), - DECL(AL_VOCAL_MORPHER_PHONEMEB_COARSE_TUNING), - DECL(AL_VOCAL_MORPHER_WAVEFORM), - DECL(AL_VOCAL_MORPHER_RATE), - - DECL(AL_EFFECTSLOT_TARGET_SOFT), - - DECL(AL_NUM_RESAMPLERS_SOFT), - DECL(AL_DEFAULT_RESAMPLER_SOFT), - DECL(AL_SOURCE_RESAMPLER_SOFT), - DECL(AL_RESAMPLER_NAME_SOFT), - - DECL(AL_SOURCE_SPATIALIZE_SOFT), - DECL(AL_AUTO_SOFT), - - DECL(AL_MAP_READ_BIT_SOFT), - DECL(AL_MAP_WRITE_BIT_SOFT), - DECL(AL_MAP_PERSISTENT_BIT_SOFT), - DECL(AL_PRESERVE_DATA_BIT_SOFT), - - DECL(AL_EVENT_CALLBACK_FUNCTION_SOFT), - DECL(AL_EVENT_CALLBACK_USER_PARAM_SOFT), - DECL(AL_EVENT_TYPE_BUFFER_COMPLETED_SOFT), - DECL(AL_EVENT_TYPE_SOURCE_STATE_CHANGED_SOFT), - DECL(AL_EVENT_TYPE_DISCONNECTED_SOFT), - - DECL(AL_DROP_UNMATCHED_SOFT), - DECL(AL_REMIX_UNMATCHED_SOFT), - - DECL(AL_AMBISONIC_LAYOUT_SOFT), - DECL(AL_AMBISONIC_SCALING_SOFT), - DECL(AL_FUMA_SOFT), - DECL(AL_ACN_SOFT), - DECL(AL_SN3D_SOFT), - DECL(AL_N3D_SOFT), - - DECL(AL_BUFFER_CALLBACK_FUNCTION_SOFT), - DECL(AL_BUFFER_CALLBACK_USER_PARAM_SOFT), - - DECL(AL_UNPACK_AMBISONIC_ORDER_SOFT), - - DECL(AL_EFFECT_CONVOLUTION_REVERB_SOFT), - DECL(AL_EFFECTSLOT_STATE_SOFT), -}; -#undef DECL - -constexpr ALCchar alcNoError[] = "No Error"; -constexpr ALCchar alcErrInvalidDevice[] = "Invalid Device"; -constexpr ALCchar alcErrInvalidContext[] = "Invalid Context"; -constexpr ALCchar alcErrInvalidEnum[] = "Invalid Enum"; -constexpr ALCchar alcErrInvalidValue[] = "Invalid Value"; -constexpr ALCchar alcErrOutOfMemory[] = "Out of Memory"; - - -/************************************************ - * Global variables - ************************************************/ - -/* Enumerated device names */ -constexpr ALCchar alcDefaultName[] = "OpenAL Soft\0"; - -std::string alcAllDevicesList; -std::string alcCaptureDeviceList; - -/* Default is always the first in the list */ -al::string alcDefaultAllDevicesSpecifier; -al::string alcCaptureDefaultDeviceSpecifier; - -/* Default context extensions */ -constexpr ALchar alExtList[] = - "AL_EXT_ALAW " - "AL_EXT_BFORMAT " - "AL_EXT_DOUBLE " - "AL_EXT_EXPONENT_DISTANCE " - "AL_EXT_FLOAT32 " - "AL_EXT_IMA4 " - "AL_EXT_LINEAR_DISTANCE " - "AL_EXT_MCFORMATS " - "AL_EXT_MULAW " - "AL_EXT_MULAW_BFORMAT " - "AL_EXT_MULAW_MCFORMATS " - "AL_EXT_OFFSET " - "AL_EXT_source_distance_model " - "AL_EXT_SOURCE_RADIUS " - "AL_EXT_STEREO_ANGLES " - "AL_LOKI_quadriphonic " - "AL_SOFT_bformat_ex " - "AL_SOFTX_bformat_hoa " - "AL_SOFT_block_alignment " - "AL_SOFTX_callback_buffer " - "AL_SOFTX_convolution_reverb " - "AL_SOFT_deferred_updates " - "AL_SOFT_direct_channels " - "AL_SOFT_direct_channels_remix " - "AL_SOFT_effect_target " - "AL_SOFT_events " - "AL_SOFTX_filter_gain_ex " - "AL_SOFT_gain_clamp_ex " - "AL_SOFT_loop_points " - "AL_SOFTX_map_buffer " - "AL_SOFT_MSADPCM " - "AL_SOFT_source_latency " - "AL_SOFT_source_length " - "AL_SOFT_source_resampler " - "AL_SOFT_source_spatialize"; - -std::atomic LastNullDeviceError{ALC_NO_ERROR}; - -/* Thread-local current context. The handling may look a little obtuse, but - * it's designed this way to avoid a bug with 32-bit GCC/MinGW, which causes - * thread-local object destructors to get a junk 'this' pointer. This method - * has the benefit of making LocalContext access more efficient since it's a - * a plain pointer, with the ThreadContext object used to check it at thread - * exit (and given no data fields, 'this' being junk is inconsequential since - * it's never accessed). - */ -thread_local ALCcontext *LocalContext{nullptr}; -class ThreadCtx { -public: - ~ThreadCtx() - { - if(ALCcontext *ctx{LocalContext}) - { - const bool result{ctx->releaseIfNoDelete()}; - ERR("Context %p current for thread being destroyed%s!\n", voidp{ctx}, - result ? "" : ", leak detected"); - } - } - - void set(ALCcontext *ctx) const noexcept { LocalContext = ctx; } -}; -thread_local ThreadCtx ThreadContext; - -/* Process-wide current context */ -std::atomic GlobalContext{nullptr}; - -/* Flag to trap ALC device errors */ -bool TrapALCError{false}; - -/* One-time configuration init control */ -std::once_flag alc_config_once{}; - -/* Default effect that applies to sources that don't have an effect on send 0 */ -ALeffect DefaultEffect; - -/* Flag to specify if alcSuspendContext/alcProcessContext should defer/process - * updates. - */ -bool SuspendDefers{true}; - -/* Initial seed for dithering. */ -constexpr uint DitherRNGSeed{22222u}; - - -/************************************************ - * ALC information - ************************************************/ -constexpr ALCchar alcNoDeviceExtList[] = - "ALC_ENUMERATE_ALL_EXT " - "ALC_ENUMERATION_EXT " - "ALC_EXT_CAPTURE " - "ALC_EXT_thread_local_context " - "ALC_SOFT_loopback " - "ALC_SOFT_loopback_bformat"; -constexpr ALCchar alcExtensionList[] = - "ALC_ENUMERATE_ALL_EXT " - "ALC_ENUMERATION_EXT " - "ALC_EXT_CAPTURE " - "ALC_EXT_DEDICATED " - "ALC_EXT_disconnect " - "ALC_EXT_EFX " - "ALC_EXT_thread_local_context " - "ALC_SOFT_device_clock " - "ALC_SOFT_HRTF " - "ALC_SOFT_loopback " - "ALC_SOFT_loopback_bformat " - "ALC_SOFT_output_limiter " - "ALC_SOFT_pause_device"; -constexpr int alcMajorVersion{1}; -constexpr int alcMinorVersion{1}; - -constexpr int alcEFXMajorVersion{1}; -constexpr int alcEFXMinorVersion{0}; - - -/* To avoid extraneous allocations, a 0-sized FlexArray is defined - * globally as a sharable object. - */ -al::FlexArray EmptyContextArray{0u}; - - -using DeviceRef = al::intrusive_ptr; - - -/************************************************ - * Device lists - ************************************************/ -al::vector DeviceList; -al::vector ContextList; - -std::recursive_mutex ListLock; - - -void alc_initconfig(void) -{ - if(auto loglevel = al::getenv("ALSOFT_LOGLEVEL")) - { - long lvl = strtol(loglevel->c_str(), nullptr, 0); - if(lvl >= static_cast(LogLevel::Trace)) - gLogLevel = LogLevel::Trace; - else if(lvl <= static_cast(LogLevel::Disable)) - gLogLevel = LogLevel::Disable; - else - gLogLevel = static_cast(lvl); - } - -#ifdef _WIN32 - if(const auto logfile = al::getenv(L"ALSOFT_LOGFILE")) - { - FILE *logf{_wfopen(logfile->c_str(), L"wt")}; - if(logf) gLogFile = logf; - else - { - auto u8name = wstr_to_utf8(logfile->c_str()); - ERR("Failed to open log file '%s'\n", u8name.c_str()); - } - } -#else - if(const auto logfile = al::getenv("ALSOFT_LOGFILE")) - { - FILE *logf{fopen(logfile->c_str(), "wt")}; - if(logf) gLogFile = logf; - else ERR("Failed to open log file '%s'\n", logfile->c_str()); - } -#endif - - TRACE("Initializing library v%s-%s %s\n", ALSOFT_VERSION, ALSOFT_GIT_COMMIT_HASH, - ALSOFT_GIT_BRANCH); - { - al::string names; - if(al::size(BackendList) < 1) - names = "(none)"; - else - { - const al::span infos{BackendList}; - names = infos[0].name; - for(const auto &backend : infos.subspan<1>()) - { - names += ", "; - names += backend.name; - } - } - TRACE("Supported backends: %s\n", names.c_str()); - } - ReadALConfig(); - - if(auto suspendmode = al::getenv("__ALSOFT_SUSPEND_CONTEXT")) - { - if(al::strcasecmp(suspendmode->c_str(), "ignore") == 0) - { - SuspendDefers = false; - TRACE("Selected context suspend behavior, \"ignore\"\n"); - } - else - ERR("Unhandled context suspend behavior setting: \"%s\"\n", suspendmode->c_str()); - } - - int capfilter{0}; -#if defined(HAVE_SSE4_1) - capfilter |= CPU_CAP_SSE | CPU_CAP_SSE2 | CPU_CAP_SSE3 | CPU_CAP_SSE4_1; -#elif defined(HAVE_SSE3) - capfilter |= CPU_CAP_SSE | CPU_CAP_SSE2 | CPU_CAP_SSE3; -#elif defined(HAVE_SSE2) - capfilter |= CPU_CAP_SSE | CPU_CAP_SSE2; -#elif defined(HAVE_SSE) - capfilter |= CPU_CAP_SSE; -#endif -#ifdef HAVE_NEON - capfilter |= CPU_CAP_NEON; -#endif - if(auto cpuopt = ConfigValueStr(nullptr, nullptr, "disable-cpu-exts")) - { - const char *str{cpuopt->c_str()}; - if(al::strcasecmp(str, "all") == 0) - capfilter = 0; - else - { - const char *next = str; - do { - str = next; - while(isspace(str[0])) - str++; - next = strchr(str, ','); - - if(!str[0] || str[0] == ',') - continue; - - size_t len{next ? static_cast(next-str) : strlen(str)}; - while(len > 0 && isspace(str[len-1])) - len--; - if(len == 3 && al::strncasecmp(str, "sse", len) == 0) - capfilter &= ~CPU_CAP_SSE; - else if(len == 4 && al::strncasecmp(str, "sse2", len) == 0) - capfilter &= ~CPU_CAP_SSE2; - else if(len == 4 && al::strncasecmp(str, "sse3", len) == 0) - capfilter &= ~CPU_CAP_SSE3; - else if(len == 6 && al::strncasecmp(str, "sse4.1", len) == 0) - capfilter &= ~CPU_CAP_SSE4_1; - else if(len == 4 && al::strncasecmp(str, "neon", len) == 0) - capfilter &= ~CPU_CAP_NEON; - else - WARN("Invalid CPU extension \"%s\"\n", str); - } while(next++); - } - } - if(auto cpuopt = GetCPUInfo()) - { - if(!cpuopt->mVendor.empty() || !cpuopt->mName.empty()) - { - TRACE("Vendor ID: \"%s\"\n", cpuopt->mVendor.c_str()); - TRACE("Name: \"%s\"\n", cpuopt->mName.c_str()); - } - const int caps{cpuopt->mCaps}; - TRACE("Extensions:%s%s%s%s%s%s\n", - ((capfilter&CPU_CAP_SSE) ? ((caps&CPU_CAP_SSE) ? " +SSE" : " -SSE") : ""), - ((capfilter&CPU_CAP_SSE2) ? ((caps&CPU_CAP_SSE2) ? " +SSE2" : " -SSE2") : ""), - ((capfilter&CPU_CAP_SSE3) ? ((caps&CPU_CAP_SSE3) ? " +SSE3" : " -SSE3") : ""), - ((capfilter&CPU_CAP_SSE4_1) ? ((caps&CPU_CAP_SSE4_1) ? " +SSE4.1" : " -SSE4.1") : ""), - ((capfilter&CPU_CAP_NEON) ? ((caps&CPU_CAP_NEON) ? " +NEON" : " -NEON") : ""), - ((!capfilter) ? " -none-" : "")); - CPUCapFlags = caps & capfilter; - } - - if(auto priopt = ConfigValueInt(nullptr, nullptr, "rt-prio")) - RTPrioLevel = *priopt; - - aluInit(); - aluInitMixer(); - - auto traperr = al::getenv("ALSOFT_TRAP_ERROR"); - if(traperr && (al::strcasecmp(traperr->c_str(), "true") == 0 - || std::strtol(traperr->c_str(), nullptr, 0) == 1)) - { - TrapALError = true; - TrapALCError = true; - } - else - { - traperr = al::getenv("ALSOFT_TRAP_AL_ERROR"); - if(traperr) - TrapALError = al::strcasecmp(traperr->c_str(), "true") == 0 - || strtol(traperr->c_str(), nullptr, 0) == 1; - else - TrapALError = !!GetConfigValueBool(nullptr, nullptr, "trap-al-error", false); - - traperr = al::getenv("ALSOFT_TRAP_ALC_ERROR"); - if(traperr) - TrapALCError = al::strcasecmp(traperr->c_str(), "true") == 0 - || strtol(traperr->c_str(), nullptr, 0) == 1; - else - TrapALCError = !!GetConfigValueBool(nullptr, nullptr, "trap-alc-error", false); - } - - if(auto boostopt = ConfigValueFloat(nullptr, "reverb", "boost")) - { - const float valf{std::isfinite(*boostopt) ? clampf(*boostopt, -24.0f, 24.0f) : 0.0f}; - ReverbBoost *= std::pow(10.0f, valf / 20.0f); - } - - auto BackendListEnd = std::end(BackendList); - auto devopt = al::getenv("ALSOFT_DRIVERS"); - if(devopt || (devopt=ConfigValueStr(nullptr, nullptr, "drivers"))) - { - auto backendlist_cur = std::begin(BackendList); - - bool endlist{true}; - const char *next{devopt->c_str()}; - do { - const char *devs{next}; - while(isspace(devs[0])) - devs++; - next = strchr(devs, ','); - - const bool delitem{devs[0] == '-'}; - if(devs[0] == '-') devs++; - - if(!devs[0] || devs[0] == ',') - { - endlist = false; - continue; - } - endlist = true; - - size_t len{next ? (static_cast(next-devs)) : strlen(devs)}; - while(len > 0 && isspace(devs[len-1])) --len; -#ifdef HAVE_WASAPI - /* HACK: For backwards compatibility, convert backend references of - * mmdevapi to wasapi. This should eventually be removed. - */ - if(len == 8 && strncmp(devs, "mmdevapi", len) == 0) - { - devs = "wasapi"; - len = 6; - } -#endif - - auto find_backend = [devs,len](const BackendInfo &backend) -> bool - { return len == strlen(backend.name) && strncmp(backend.name, devs, len) == 0; }; - auto this_backend = std::find_if(std::begin(BackendList), BackendListEnd, - find_backend); - - if(this_backend == BackendListEnd) - continue; - - if(delitem) - BackendListEnd = std::move(this_backend+1, BackendListEnd, this_backend); - else - backendlist_cur = std::rotate(backendlist_cur, this_backend, this_backend+1); - } while(next++); - - if(endlist) - BackendListEnd = backendlist_cur; - } - - auto init_backend = [](BackendInfo &backend) -> void - { - if(PlaybackFactory && CaptureFactory) - return; - - BackendFactory &factory = backend.getFactory(); - if(!factory.init()) - { - WARN("Failed to initialize backend \"%s\"\n", backend.name); - return; - } - - TRACE("Initialized backend \"%s\"\n", backend.name); - if(!PlaybackFactory && factory.querySupport(BackendType::Playback)) - { - PlaybackFactory = &factory; - TRACE("Added \"%s\" for playback\n", backend.name); - } - if(!CaptureFactory && factory.querySupport(BackendType::Capture)) - { - CaptureFactory = &factory; - TRACE("Added \"%s\" for capture\n", backend.name); - } - }; - std::for_each(std::begin(BackendList), BackendListEnd, init_backend); - - LoopbackBackendFactory::getFactory().init(); - - if(!PlaybackFactory) - WARN("No playback backend available!\n"); - if(!CaptureFactory) - WARN("No capture backend available!\n"); - - if(auto exclopt = ConfigValueStr(nullptr, nullptr, "excludefx")) - { - const char *next{exclopt->c_str()}; - do { - const char *str{next}; - next = strchr(str, ','); - - if(!str[0] || next == str) - continue; - - size_t len{next ? static_cast(next-str) : strlen(str)}; - for(const EffectList &effectitem : gEffectList) - { - if(len == strlen(effectitem.name) && - strncmp(effectitem.name, str, len) == 0) - DisabledEffects[effectitem.type] = true; - } - } while(next++); - } - - InitEffect(&DefaultEffect); - auto defrevopt = al::getenv("ALSOFT_DEFAULT_REVERB"); - if(defrevopt || (defrevopt=ConfigValueStr(nullptr, nullptr, "default-reverb"))) - LoadReverbPreset(defrevopt->c_str(), &DefaultEffect); -} -#define DO_INITCONFIG() std::call_once(alc_config_once, [](){alc_initconfig();}) - - -/************************************************ - * Device enumeration - ************************************************/ -void ProbeAllDevicesList() -{ - DO_INITCONFIG(); - - std::lock_guard _{ListLock}; - if(!PlaybackFactory) - decltype(alcAllDevicesList){}.swap(alcAllDevicesList); - else - { - std::string names{PlaybackFactory->probe(BackendType::Playback)}; - if(names.empty()) names += '\0'; - names.swap(alcAllDevicesList); - } -} -void ProbeCaptureDeviceList() -{ - DO_INITCONFIG(); - - std::lock_guard _{ListLock}; - if(!CaptureFactory) - decltype(alcCaptureDeviceList){}.swap(alcCaptureDeviceList); - else - { - std::string names{CaptureFactory->probe(BackendType::Capture)}; - if(names.empty()) names += '\0'; - names.swap(alcCaptureDeviceList); - } -} - -} // namespace - -/* Mixing thread piority level */ -int RTPrioLevel{1}; - -FILE *gLogFile{stderr}; -#ifdef _DEBUG -LogLevel gLogLevel{LogLevel::Warning}; -#else -LogLevel gLogLevel{LogLevel::Error}; -#endif - -/************************************************ - * Library initialization - ************************************************/ -#if defined(_WIN32) && !defined(AL_LIBTYPE_STATIC) -BOOL APIENTRY DllMain(HINSTANCE module, DWORD reason, LPVOID /*reserved*/) -{ - switch(reason) - { - case DLL_PROCESS_ATTACH: - /* Pin the DLL so we won't get unloaded until the process terminates */ - GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_PIN | GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, - reinterpret_cast(module), &module); - break; - } - return TRUE; -} -#endif - -/************************************************ - * Device format information - ************************************************/ -namespace { - -struct DevFmtPair { DevFmtChannels chans; DevFmtType type; }; -al::optional DecomposeDevFormat(ALenum format) -{ - static const struct { - ALenum format; - DevFmtChannels channels; - DevFmtType type; - } list[] = { - { AL_FORMAT_MONO8, DevFmtMono, DevFmtUByte }, - { AL_FORMAT_MONO16, DevFmtMono, DevFmtShort }, - { AL_FORMAT_MONO_FLOAT32, DevFmtMono, DevFmtFloat }, - - { AL_FORMAT_STEREO8, DevFmtStereo, DevFmtUByte }, - { AL_FORMAT_STEREO16, DevFmtStereo, DevFmtShort }, - { AL_FORMAT_STEREO_FLOAT32, DevFmtStereo, DevFmtFloat }, - - { AL_FORMAT_QUAD8, DevFmtQuad, DevFmtUByte }, - { AL_FORMAT_QUAD16, DevFmtQuad, DevFmtShort }, - { AL_FORMAT_QUAD32, DevFmtQuad, DevFmtFloat }, - - { AL_FORMAT_51CHN8, DevFmtX51, DevFmtUByte }, - { AL_FORMAT_51CHN16, DevFmtX51, DevFmtShort }, - { AL_FORMAT_51CHN32, DevFmtX51, DevFmtFloat }, - - { AL_FORMAT_61CHN8, DevFmtX61, DevFmtUByte }, - { AL_FORMAT_61CHN16, DevFmtX61, DevFmtShort }, - { AL_FORMAT_61CHN32, DevFmtX61, DevFmtFloat }, - - { AL_FORMAT_71CHN8, DevFmtX71, DevFmtUByte }, - { AL_FORMAT_71CHN16, DevFmtX71, DevFmtShort }, - { AL_FORMAT_71CHN32, DevFmtX71, DevFmtFloat }, - }; - - for(const auto &item : list) - { - if(item.format == format) - return al::make_optional(DevFmtPair{item.channels, item.type}); - } - - return al::nullopt; -} - -al::optional DevFmtTypeFromEnum(ALCenum type) -{ - switch(type) - { - case ALC_BYTE_SOFT: return al::make_optional(DevFmtByte); - case ALC_UNSIGNED_BYTE_SOFT: return al::make_optional(DevFmtUByte); - case ALC_SHORT_SOFT: return al::make_optional(DevFmtShort); - case ALC_UNSIGNED_SHORT_SOFT: return al::make_optional(DevFmtUShort); - case ALC_INT_SOFT: return al::make_optional(DevFmtInt); - case ALC_UNSIGNED_INT_SOFT: return al::make_optional(DevFmtUInt); - case ALC_FLOAT_SOFT: return al::make_optional(DevFmtFloat); - } - WARN("Unsupported format type: 0x%04x\n", type); - return al::nullopt; -} -ALCenum EnumFromDevFmt(DevFmtType type) -{ - switch(type) - { - case DevFmtByte: return ALC_BYTE_SOFT; - case DevFmtUByte: return ALC_UNSIGNED_BYTE_SOFT; - case DevFmtShort: return ALC_SHORT_SOFT; - case DevFmtUShort: return ALC_UNSIGNED_SHORT_SOFT; - case DevFmtInt: return ALC_INT_SOFT; - case DevFmtUInt: return ALC_UNSIGNED_INT_SOFT; - case DevFmtFloat: return ALC_FLOAT_SOFT; - } - throw std::runtime_error{"Invalid DevFmtType: "+std::to_string(int(type))}; -} - -al::optional DevFmtChannelsFromEnum(ALCenum channels) -{ - switch(channels) - { - case ALC_MONO_SOFT: return al::make_optional(DevFmtMono); - case ALC_STEREO_SOFT: return al::make_optional(DevFmtStereo); - case ALC_QUAD_SOFT: return al::make_optional(DevFmtQuad); - case ALC_5POINT1_SOFT: return al::make_optional(DevFmtX51); - case ALC_6POINT1_SOFT: return al::make_optional(DevFmtX61); - case ALC_7POINT1_SOFT: return al::make_optional(DevFmtX71); - case ALC_BFORMAT3D_SOFT: return al::make_optional(DevFmtAmbi3D); - } - WARN("Unsupported format channels: 0x%04x\n", channels); - return al::nullopt; -} -ALCenum EnumFromDevFmt(DevFmtChannels channels) -{ - switch(channels) - { - case DevFmtMono: return ALC_MONO_SOFT; - case DevFmtStereo: return ALC_STEREO_SOFT; - case DevFmtQuad: return ALC_QUAD_SOFT; - case DevFmtX51: /* fall-through */ - case DevFmtX51Rear: return ALC_5POINT1_SOFT; - case DevFmtX61: return ALC_6POINT1_SOFT; - case DevFmtX71: return ALC_7POINT1_SOFT; - case DevFmtAmbi3D: return ALC_BFORMAT3D_SOFT; - } - throw std::runtime_error{"Invalid DevFmtChannels: "+std::to_string(int(channels))}; -} - -al::optional DevAmbiLayoutFromEnum(ALCenum layout) -{ - switch(layout) - { - case ALC_FUMA_SOFT: return al::make_optional(DevAmbiLayout::FuMa); - case ALC_ACN_SOFT: return al::make_optional(DevAmbiLayout::ACN); - } - WARN("Unsupported ambisonic layout: 0x%04x\n", layout); - return al::nullopt; -} -ALCenum EnumFromDevAmbi(DevAmbiLayout layout) -{ - switch(layout) - { - case DevAmbiLayout::FuMa: return ALC_FUMA_SOFT; - case DevAmbiLayout::ACN: return ALC_ACN_SOFT; - } - throw std::runtime_error{"Invalid DevAmbiLayout: "+std::to_string(int(layout))}; -} - -al::optional DevAmbiScalingFromEnum(ALCenum scaling) -{ - switch(scaling) - { - case ALC_FUMA_SOFT: return al::make_optional(DevAmbiScaling::FuMa); - case ALC_SN3D_SOFT: return al::make_optional(DevAmbiScaling::SN3D); - case ALC_N3D_SOFT: return al::make_optional(DevAmbiScaling::N3D); - } - WARN("Unsupported ambisonic scaling: 0x%04x\n", scaling); - return al::nullopt; -} -ALCenum EnumFromDevAmbi(DevAmbiScaling scaling) -{ - switch(scaling) - { - case DevAmbiScaling::FuMa: return ALC_FUMA_SOFT; - case DevAmbiScaling::SN3D: return ALC_SN3D_SOFT; - case DevAmbiScaling::N3D: return ALC_N3D_SOFT; - } - throw std::runtime_error{"Invalid DevAmbiScaling: "+std::to_string(int(scaling))}; -} - - -/* Downmixing channel arrays, to map the given format's missing channels to - * existing ones. Based on Wine's DSound downmix values, which are based on - * PulseAudio's. - */ -const std::array MonoDownmix{{ - { FrontLeft, {{{FrontCenter, 0.5f}, {LFE, 0.0f}}} }, - { FrontRight, {{{FrontCenter, 0.5f}, {LFE, 0.0f}}} }, - { SideLeft, {{{FrontCenter, 0.5f/9.0f}, {LFE, 0.0f}}} }, - { SideRight, {{{FrontCenter, 0.5f/9.0f}, {LFE, 0.0f}}} }, - { BackLeft, {{{FrontCenter, 0.5f/9.0f}, {LFE, 0.0f}}} }, - { BackRight, {{{FrontCenter, 0.5f/9.0f}, {LFE, 0.0f}}} }, - { BackCenter, {{{FrontCenter, 1.0f/9.0f}, {LFE, 0.0f}}} }, -}}; -const std::array StereoDownmix{{ - { FrontCenter, {{{FrontLeft, 0.5f}, {FrontRight, 0.5f}}} }, - { SideLeft, {{{FrontLeft, 1.0f/9.0f}, {FrontRight, 0.0f}}} }, - { SideRight, {{{FrontLeft, 0.0f}, {FrontRight, 1.0f/9.0f}}} }, - { BackLeft, {{{FrontLeft, 1.0f/9.0f}, {FrontRight, 0.0f}}} }, - { BackRight, {{{FrontLeft, 0.0f}, {FrontRight, 1.0f/9.0f}}} }, - { BackCenter, {{{FrontLeft, 0.5f/9.0f}, {FrontRight, 0.5f/9.0f}}} }, -}}; -const std::array QuadDownmix{{ - { FrontCenter, {{{FrontLeft, 0.5f}, {FrontRight, 0.5f}}} }, - { SideLeft, {{{FrontLeft, 0.5f}, {BackLeft, 0.5f}}} }, - { SideRight, {{{FrontRight, 0.5f}, {BackRight, 0.5f}}} }, - { BackCenter, {{{BackLeft, 0.5f}, {BackRight, 0.5f}}} }, -}}; -const std::array X51Downmix{{ - { BackLeft, {{{SideLeft, 1.0f}, {SideRight, 0.0f}}} }, - { BackRight, {{{SideLeft, 0.0f}, {SideRight, 1.0f}}} }, - { BackCenter, {{{SideLeft, 0.5f}, {SideRight, 0.5f}}} }, -}}; -const std::array X51RearDownmix{{ - { SideLeft, {{{BackLeft, 1.0f}, {BackRight, 0.0f}}} }, - { SideRight, {{{BackLeft, 0.0f}, {BackRight, 1.0f}}} }, - { BackCenter, {{{BackLeft, 0.5f}, {BackRight, 0.5f}}} }, -}}; -const std::array X61Downmix{{ - { BackLeft, {{{BackCenter, 0.5f}, {SideLeft, 0.5f}}} }, - { BackRight, {{{BackCenter, 0.5f}, {SideRight, 0.5f}}} }, -}}; -const std::array X71Downmix{{ - { BackCenter, {{{BackLeft, 0.5f}, {BackRight, 0.5f}}} }, -}}; - -} // namespace - -/************************************************ - * Miscellaneous ALC helpers - ************************************************/ - -void ALCcontext::processUpdates() -{ - std::lock_guard _{mPropLock}; - if(mDeferUpdates.exchange(false, std::memory_order_acq_rel)) - { - /* Tell the mixer to stop applying updates, then wait for any active - * updating to finish, before providing updates. - */ - mHoldUpdates.store(true, std::memory_order_release); - while((mUpdateCount.load(std::memory_order_acquire)&1) != 0) { - /* busy-wait */ - } - - if(!mPropsClean.test_and_set(std::memory_order_acq_rel)) - UpdateContextProps(this); - if(!mListener.PropsClean.test_and_set(std::memory_order_acq_rel)) - UpdateListenerProps(this); - UpdateAllEffectSlotProps(this); - UpdateAllSourceProps(this); - - /* Now with all updates declared, let the mixer continue applying them - * so they all happen at once. - */ - mHoldUpdates.store(false, std::memory_order_release); - } -} - - -void ALCcontext::allocVoiceChanges(size_t addcount) -{ - constexpr size_t clustersize{128}; - /* Convert element count to cluster count. */ - addcount = (addcount+(clustersize-1)) / clustersize; - while(addcount) - { - VoiceChangeCluster cluster{std::make_unique(clustersize)}; - for(size_t i{1};i < clustersize;++i) - cluster[i-1].mNext.store(std::addressof(cluster[i]), std::memory_order_relaxed); - cluster[clustersize-1].mNext.store(mVoiceChangeTail, std::memory_order_relaxed); - mVoiceChangeClusters.emplace_back(std::move(cluster)); - mVoiceChangeTail = mVoiceChangeClusters.back().get(); - --addcount; - } -} - -void ALCcontext::allocVoices(size_t addcount) -{ - constexpr size_t clustersize{32}; - /* Convert element count to cluster count. */ - addcount = (addcount+(clustersize-1)) / clustersize; - - if(addcount >= std::numeric_limits::max()/clustersize - mVoiceClusters.size()) - throw std::runtime_error{"Allocating too many voices"}; - const size_t totalcount{(mVoiceClusters.size()+addcount) * clustersize}; - TRACE("Increasing allocated voices to %zu\n", totalcount); - - auto newarray = VoiceArray::Create(totalcount); - while(addcount) - { - mVoiceClusters.emplace_back(std::make_unique(clustersize)); - --addcount; - } - - auto voice_iter = newarray->begin(); - for(VoiceCluster &cluster : mVoiceClusters) - { - for(size_t i{0};i < clustersize;++i) - *(voice_iter++) = &cluster[i]; - } - - if(auto *oldvoices = mVoices.exchange(newarray.release(), std::memory_order_acq_rel)) - { - mDevice->waitForMix(); - delete oldvoices; - } -} - - -/** Stores the latest ALC device error. */ -static void alcSetError(ALCdevice *device, ALCenum errorCode) -{ - WARN("Error generated on device %p, code 0x%04x\n", voidp{device}, errorCode); - if(TrapALCError) - { -#ifdef _WIN32 - /* DebugBreak() will cause an exception if there is no debugger */ - if(IsDebuggerPresent()) - DebugBreak(); -#elif defined(SIGTRAP) - raise(SIGTRAP); -#endif - } - - if(device) - device->LastError.store(errorCode); - else - LastNullDeviceError.store(errorCode); -} - - -static std::unique_ptr CreateDeviceLimiter(const ALCdevice *device, const float threshold) -{ - constexpr bool AutoKnee{true}; - constexpr bool AutoAttack{true}; - constexpr bool AutoRelease{true}; - constexpr bool AutoPostGain{true}; - constexpr bool AutoDeclip{true}; - constexpr float LookAheadTime{0.001f}; - constexpr float HoldTime{0.002f}; - constexpr float PreGainDb{0.0f}; - constexpr float PostGainDb{0.0f}; - constexpr float Ratio{std::numeric_limits::infinity()}; - constexpr float KneeDb{0.0f}; - constexpr float AttackTime{0.02f}; - constexpr float ReleaseTime{0.2f}; - - return Compressor::Create(device->RealOut.Buffer.size(), static_cast(device->Frequency), - AutoKnee, AutoAttack, AutoRelease, AutoPostGain, AutoDeclip, LookAheadTime, HoldTime, - PreGainDb, PostGainDb, threshold, Ratio, KneeDb, AttackTime, ReleaseTime); -} - -/** - * Updates the device's base clock time with however many samples have been - * done. This is used so frequency changes on the device don't cause the time - * to jump forward or back. Must not be called while the device is running/ - * mixing. - */ -static inline void UpdateClockBase(ALCdevice *device) -{ - IncrementRef(device->MixCount); - device->ClockBase += nanoseconds{seconds{device->SamplesDone}} / device->Frequency; - device->SamplesDone = 0; - IncrementRef(device->MixCount); -} - -/** - * Updates device parameters according to the attribute list (caller is - * responsible for holding the list lock). - */ -static ALCenum UpdateDeviceParams(ALCdevice *device, const int *attrList) -{ - HrtfRequestMode hrtf_userreq{Hrtf_Default}; - HrtfRequestMode hrtf_appreq{Hrtf_Default}; - ALCenum gainLimiter{device->LimiterState}; - uint new_sends{device->NumAuxSends}; - DevFmtChannels oldChans; - DevFmtType oldType; - int hrtf_id{-1}; - uint oldFreq; - - if((!attrList || !attrList[0]) && device->Type == DeviceType::Loopback) - { - WARN("Missing attributes for loopback device\n"); - return ALC_INVALID_VALUE; - } - - // Check for attributes - if(attrList && attrList[0]) - { - uint numMono{device->NumMonoSources}; - uint numStereo{device->NumStereoSources}; - uint numSends{device->NumAuxSends}; - - al::optional optchans; - al::optional opttype; - al::optional optlayout; - al::optional optscale; - - uint aorder{0u}; - uint freq{0u}; - -#define TRACE_ATTR(a, v) TRACE("%s = %d\n", #a, v) - size_t attrIdx{0}; - while(attrList[attrIdx]) - { - switch(attrList[attrIdx]) - { - case ALC_FORMAT_CHANNELS_SOFT: - TRACE_ATTR(ALC_FORMAT_CHANNELS_SOFT, attrList[attrIdx + 1]); - optchans = DevFmtChannelsFromEnum(attrList[attrIdx + 1]); - break; - - case ALC_FORMAT_TYPE_SOFT: - TRACE_ATTR(ALC_FORMAT_TYPE_SOFT, attrList[attrIdx + 1]); - opttype = DevFmtTypeFromEnum(attrList[attrIdx + 1]); - break; - - case ALC_FREQUENCY: - freq = static_cast(attrList[attrIdx + 1]); - TRACE_ATTR(ALC_FREQUENCY, freq); - break; - - case ALC_AMBISONIC_LAYOUT_SOFT: - TRACE_ATTR(ALC_AMBISONIC_LAYOUT_SOFT, attrList[attrIdx + 1]); - optlayout = DevAmbiLayoutFromEnum(attrList[attrIdx + 1]); - break; - - case ALC_AMBISONIC_SCALING_SOFT: - TRACE_ATTR(ALC_AMBISONIC_SCALING_SOFT, attrList[attrIdx + 1]); - optscale = DevAmbiScalingFromEnum(attrList[attrIdx + 1]); - break; - - case ALC_AMBISONIC_ORDER_SOFT: - aorder = static_cast(attrList[attrIdx + 1]); - TRACE_ATTR(ALC_AMBISONIC_ORDER_SOFT, aorder); - break; - - case ALC_MONO_SOURCES: - numMono = static_cast(attrList[attrIdx + 1]); - TRACE_ATTR(ALC_MONO_SOURCES, numMono); - if(numMono > INT_MAX) numMono = 0; - break; - - case ALC_STEREO_SOURCES: - numStereo = static_cast(attrList[attrIdx + 1]); - TRACE_ATTR(ALC_STEREO_SOURCES, numStereo); - if(numStereo > INT_MAX) numStereo = 0; - break; - - case ALC_MAX_AUXILIARY_SENDS: - numSends = static_cast(attrList[attrIdx + 1]); - TRACE_ATTR(ALC_MAX_AUXILIARY_SENDS, numSends); - if(numSends > INT_MAX) numSends = 0; - else numSends = minu(numSends, MAX_SENDS); - break; - - case ALC_HRTF_SOFT: - TRACE_ATTR(ALC_HRTF_SOFT, attrList[attrIdx + 1]); - if(attrList[attrIdx + 1] == ALC_FALSE) - hrtf_appreq = Hrtf_Disable; - else if(attrList[attrIdx + 1] == ALC_TRUE) - hrtf_appreq = Hrtf_Enable; - else - hrtf_appreq = Hrtf_Default; - break; - - case ALC_HRTF_ID_SOFT: - hrtf_id = attrList[attrIdx + 1]; - TRACE_ATTR(ALC_HRTF_ID_SOFT, hrtf_id); - break; - - case ALC_OUTPUT_LIMITER_SOFT: - gainLimiter = attrList[attrIdx + 1]; - TRACE_ATTR(ALC_OUTPUT_LIMITER_SOFT, gainLimiter); - break; - - default: - TRACE("0x%04X = %d (0x%x)\n", attrList[attrIdx], - attrList[attrIdx + 1], attrList[attrIdx + 1]); - break; - } - - attrIdx += 2; - } -#undef TRACE_ATTR - - const bool loopback{device->Type == DeviceType::Loopback}; - if(loopback) - { - if(!optchans || !opttype) - return ALC_INVALID_VALUE; - if(freq < MIN_OUTPUT_RATE || freq > MAX_OUTPUT_RATE) - return ALC_INVALID_VALUE; - if(*optchans == DevFmtAmbi3D) - { - if(!optlayout || !optscale) - return ALC_INVALID_VALUE; - if(aorder < 1 || aorder > MaxAmbiOrder) - return ALC_INVALID_VALUE; - if((*optlayout == DevAmbiLayout::FuMa || *optscale == DevAmbiScaling::FuMa) - && aorder > 3) - return ALC_INVALID_VALUE; - } - } - - /* If a context is already running on the device, stop playback so the - * device attributes can be updated. - */ - if(device->Flags.test(DeviceRunning)) - device->Backend->stop(); - device->Flags.reset(DeviceRunning); - - UpdateClockBase(device); - - const char *devname{nullptr}; - if(loopback) - { - device->Frequency = freq; - device->FmtChans = *optchans; - device->FmtType = *opttype; - if(device->FmtChans == DevFmtAmbi3D) - { - device->mAmbiOrder = aorder; - device->mAmbiLayout = *optlayout; - device->mAmbiScale = *optscale; - } - } - else - { - devname = device->DeviceName.c_str(); - - device->BufferSize = DEFAULT_UPDATE_SIZE * DEFAULT_NUM_UPDATES; - device->UpdateSize = DEFAULT_UPDATE_SIZE; - device->Frequency = DEFAULT_OUTPUT_RATE; - - freq = ConfigValueUInt(devname, nullptr, "frequency").value_or(freq); - if(freq < 1) - device->Flags.reset(FrequencyRequest); - else - { - freq = clampu(freq, MIN_OUTPUT_RATE, MAX_OUTPUT_RATE); - - const double scale{static_cast(freq) / device->Frequency}; - device->UpdateSize = static_cast(device->UpdateSize*scale + 0.5); - device->BufferSize = static_cast(device->BufferSize*scale + 0.5); - - device->Frequency = freq; - device->Flags.set(FrequencyRequest); - } - - if(auto persizeopt = ConfigValueUInt(devname, nullptr, "period_size")) - device->UpdateSize = clampu(*persizeopt, 64, 8192); - - if(auto peropt = ConfigValueUInt(devname, nullptr, "periods")) - device->BufferSize = device->UpdateSize * clampu(*peropt, 2, 16); - else - device->BufferSize = maxu(device->BufferSize, device->UpdateSize*2); - } - - if(numMono > INT_MAX-numStereo) - numMono = INT_MAX-numStereo; - numMono += numStereo; - if(auto srcsopt = ConfigValueUInt(devname, nullptr, "sources")) - { - if(*srcsopt <= 0) numMono = 256; - else numMono = *srcsopt; - } - else - numMono = maxu(numMono, 256); - numStereo = minu(numStereo, numMono); - numMono -= numStereo; - device->SourcesMax = numMono + numStereo; - - device->NumMonoSources = numMono; - device->NumStereoSources = numStereo; - - if(auto sendsopt = ConfigValueInt(devname, nullptr, "sends")) - new_sends = minu(numSends, static_cast(clampi(*sendsopt, 0, MAX_SENDS))); - else - new_sends = numSends; - } - - if(device->Flags.test(DeviceRunning)) - return ALC_NO_ERROR; - - device->AvgSpeakerDist = 0.0f; - device->Uhj_Encoder = nullptr; - device->AmbiDecoder = nullptr; - device->Bs2b = nullptr; - device->PostProcess = nullptr; - - device->Limiter = nullptr; - device->ChannelDelays = nullptr; - - std::fill(std::begin(device->HrtfAccumData), std::end(device->HrtfAccumData), float2{}); - - device->Dry.AmbiMap.fill(BFChannelConfig{}); - device->Dry.Buffer = {}; - std::fill(std::begin(device->NumChannelsPerOrder), std::end(device->NumChannelsPerOrder), 0u); - device->RealOut.RemixMap = {}; - device->RealOut.ChannelIndex.fill(INVALID_CHANNEL_INDEX); - device->RealOut.Buffer = {}; - device->MixBuffer.clear(); - device->MixBuffer.shrink_to_fit(); - - UpdateClockBase(device); - device->FixedLatency = nanoseconds::zero(); - - device->DitherDepth = 0.0f; - device->DitherSeed = DitherRNGSeed; - - /************************************************************************* - * Update device format request if HRTF is requested - */ - device->HrtfStatus = ALC_HRTF_DISABLED_SOFT; - if(device->Type != DeviceType::Loopback) - { - if(auto hrtfopt = ConfigValueStr(device->DeviceName.c_str(), nullptr, "hrtf")) - { - const char *hrtf{hrtfopt->c_str()}; - if(al::strcasecmp(hrtf, "true") == 0) - hrtf_userreq = Hrtf_Enable; - else if(al::strcasecmp(hrtf, "false") == 0) - hrtf_userreq = Hrtf_Disable; - else if(al::strcasecmp(hrtf, "auto") != 0) - ERR("Unexpected hrtf value: %s\n", hrtf); - } - - if(hrtf_userreq == Hrtf_Enable || (hrtf_userreq != Hrtf_Disable && hrtf_appreq == Hrtf_Enable)) - { - device->FmtChans = DevFmtStereo; - device->Flags.set(ChannelsRequest); - } - } - - oldFreq = device->Frequency; - oldChans = device->FmtChans; - oldType = device->FmtType; - - TRACE("Pre-reset: %s%s, %s%s, %s%uhz, %u / %u buffer\n", - device->Flags.test(ChannelsRequest)?"*":"", DevFmtChannelsString(device->FmtChans), - device->Flags.test(SampleTypeRequest)?"*":"", DevFmtTypeString(device->FmtType), - device->Flags.test(FrequencyRequest)?"*":"", device->Frequency, - device->UpdateSize, device->BufferSize); - - try { - auto backend = device->Backend.get(); - if(!backend->reset()) - throw al::backend_exception{al::backend_error::DeviceError, "Device reset failure"}; - } - catch(std::exception &e) { - device->handleDisconnect("%s", e.what()); - return ALC_INVALID_DEVICE; - } - - if(device->FmtChans != oldChans && device->Flags.test(ChannelsRequest)) - { - ERR("Failed to set %s, got %s instead\n", DevFmtChannelsString(oldChans), - DevFmtChannelsString(device->FmtChans)); - device->Flags.reset(ChannelsRequest); - } - if(device->FmtType != oldType && device->Flags.test(SampleTypeRequest)) - { - ERR("Failed to set %s, got %s instead\n", DevFmtTypeString(oldType), - DevFmtTypeString(device->FmtType)); - device->Flags.reset(SampleTypeRequest); - } - if(device->Frequency != oldFreq && device->Flags.test(FrequencyRequest)) - { - WARN("Failed to set %uhz, got %uhz instead\n", oldFreq, device->Frequency); - device->Flags.reset(FrequencyRequest); - } - - TRACE("Post-reset: %s, %s, %uhz, %u / %u buffer\n", - DevFmtChannelsString(device->FmtChans), DevFmtTypeString(device->FmtType), - device->Frequency, device->UpdateSize, device->BufferSize); - - switch(device->FmtChans) - { - case DevFmtMono: device->RealOut.RemixMap = MonoDownmix; break; - case DevFmtStereo: device->RealOut.RemixMap = StereoDownmix; break; - case DevFmtQuad: device->RealOut.RemixMap = QuadDownmix; break; - case DevFmtX51: device->RealOut.RemixMap = X51Downmix; break; - case DevFmtX51Rear: device->RealOut.RemixMap = X51RearDownmix; break; - case DevFmtX61: device->RealOut.RemixMap = X61Downmix; break; - case DevFmtX71: device->RealOut.RemixMap = X71Downmix; break; - case DevFmtAmbi3D: break; - } - - aluInitRenderer(device, hrtf_id, hrtf_appreq, hrtf_userreq); - - device->NumAuxSends = new_sends; - TRACE("Max sources: %d (%d + %d), effect slots: %d, sends: %d\n", - device->SourcesMax, device->NumMonoSources, device->NumStereoSources, - device->AuxiliaryEffectSlotMax, device->NumAuxSends); - - nanoseconds::rep sample_delay{0}; - if(device->Uhj_Encoder) - sample_delay += Uhj2Encoder::sFilterSize; - if(device->mHrtfState) - sample_delay += HrtfDirectDelay; - if(auto *ambidec = device->AmbiDecoder.get()) - { - if(ambidec->hasStablizer()) - sample_delay += FrontStablizer::DelayLength; - } - - if(GetConfigValueBool(device->DeviceName.c_str(), nullptr, "dither", 1)) - { - int depth{ConfigValueInt(device->DeviceName.c_str(), nullptr, "dither-depth").value_or(0)}; - if(depth <= 0) - { - switch(device->FmtType) - { - case DevFmtByte: - case DevFmtUByte: - depth = 8; - break; - case DevFmtShort: - case DevFmtUShort: - depth = 16; - break; - case DevFmtInt: - case DevFmtUInt: - case DevFmtFloat: - break; - } - } - - if(depth > 0) - { - depth = clampi(depth, 2, 24); - device->DitherDepth = std::pow(2.0f, static_cast(depth-1)); - } - } - if(!(device->DitherDepth > 0.0f)) - TRACE("Dithering disabled\n"); - else - TRACE("Dithering enabled (%d-bit, %g)\n", float2int(std::log2(device->DitherDepth)+0.5f)+1, - device->DitherDepth); - - device->LimiterState = gainLimiter; - if(auto limopt = ConfigValueBool(device->DeviceName.c_str(), nullptr, "output-limiter")) - gainLimiter = *limopt ? ALC_TRUE : ALC_FALSE; - - /* Valid values for gainLimiter are ALC_DONT_CARE_SOFT, ALC_TRUE, and - * ALC_FALSE. For ALC_DONT_CARE_SOFT, use the limiter for integer-based - * output (where samples must be clamped), and don't for floating-point - * (which can take unclamped samples). - */ - if(gainLimiter == ALC_DONT_CARE_SOFT) - { - switch(device->FmtType) - { - case DevFmtByte: - case DevFmtUByte: - case DevFmtShort: - case DevFmtUShort: - case DevFmtInt: - case DevFmtUInt: - gainLimiter = ALC_TRUE; - break; - case DevFmtFloat: - gainLimiter = ALC_FALSE; - break; - } - } - if(gainLimiter == ALC_FALSE) - TRACE("Output limiter disabled\n"); - else - { - float thrshld{1.0f}; - switch(device->FmtType) - { - case DevFmtByte: - case DevFmtUByte: - thrshld = 127.0f / 128.0f; - break; - case DevFmtShort: - case DevFmtUShort: - thrshld = 32767.0f / 32768.0f; - break; - case DevFmtInt: - case DevFmtUInt: - case DevFmtFloat: - break; - } - if(device->DitherDepth > 0.0f) - thrshld -= 1.0f / device->DitherDepth; - - const float thrshld_dB{std::log10(thrshld) * 20.0f}; - auto limiter = CreateDeviceLimiter(device, thrshld_dB); - - sample_delay += limiter->getLookAhead(); - device->Limiter = std::move(limiter); - TRACE("Output limiter enabled, %.4fdB limit\n", thrshld_dB); - } - - /* Convert the sample delay from samples to nanosamples to nanoseconds. */ - device->FixedLatency += nanoseconds{seconds{sample_delay}} / device->Frequency; - TRACE("Fixed device latency: %" PRId64 "ns\n", int64_t{device->FixedLatency.count()}); - - FPUCtl mixer_mode{}; - for(ALCcontext *context : *device->mContexts.load()) - { - std::unique_lock proplock{context->mPropLock}; - std::unique_lock slotlock{context->mEffectSlotLock}; - - /* Clear out unused wet buffers. */ - auto buffer_not_in_use = [](WetBufferPtr &wetbuffer) noexcept -> bool - { return !wetbuffer->mInUse; }; - auto wetbuffer_iter = std::remove_if(context->mWetBuffers.begin(), - context->mWetBuffers.end(), buffer_not_in_use); - context->mWetBuffers.erase(wetbuffer_iter, context->mWetBuffers.end()); - - if(ALeffectslot *slot{context->mDefaultSlot.get()}) - { - aluInitEffectPanning(&slot->mSlot, context); - - EffectState *state{slot->Effect.State.get()}; - state->mOutTarget = device->Dry.Buffer; - state->deviceUpdate(device, slot->Buffer); - slot->updateProps(context); - } - - if(EffectSlotArray *curarray{context->mActiveAuxSlots.load(std::memory_order_relaxed)}) - std::fill_n(curarray->end(), curarray->size(), nullptr); - for(auto &sublist : context->mEffectSlotList) - { - uint64_t usemask{~sublist.FreeMask}; - while(usemask) - { - const int idx{CountTrailingZeros(usemask)}; - ALeffectslot *slot{sublist.EffectSlots + idx}; - usemask &= ~(1_u64 << idx); - - aluInitEffectPanning(&slot->mSlot, context); - - EffectState *state{slot->Effect.State.get()}; - state->mOutTarget = device->Dry.Buffer; - state->deviceUpdate(device, slot->Buffer); - slot->updateProps(context); - } - } - slotlock.unlock(); - - const uint num_sends{device->NumAuxSends}; - std::unique_lock srclock{context->mSourceLock}; - for(auto &sublist : context->mSourceList) - { - uint64_t usemask{~sublist.FreeMask}; - while(usemask) - { - const int idx{CountTrailingZeros(usemask)}; - ALsource *source{sublist.Sources + idx}; - usemask &= ~(1_u64 << idx); - - auto clear_send = [](ALsource::SendData &send) -> void - { - if(send.Slot) - DecrementRef(send.Slot->ref); - send.Slot = nullptr; - send.Gain = 1.0f; - send.GainHF = 1.0f; - send.HFReference = LOWPASSFREQREF; - send.GainLF = 1.0f; - send.LFReference = HIGHPASSFREQREF; - }; - auto send_begin = source->Send.begin() + static_cast(num_sends); - std::for_each(send_begin, source->Send.end(), clear_send); - - source->PropsClean.clear(std::memory_order_release); - } - } - - /* Clear any pre-existing voice property structs, in case the number of - * auxiliary sends is changing. Active sources will have updates - * respecified in UpdateAllSourceProps. - */ - VoicePropsItem *vprops{context->mFreeVoiceProps.exchange(nullptr, std::memory_order_acq_rel)}; - while(vprops) - { - VoicePropsItem *next = vprops->next.load(std::memory_order_relaxed); - delete vprops; - vprops = next; - } - - auto voicelist = context->getVoicesSpan(); - for(Voice *voice : voicelist) - { - /* Clear extraneous property set sends. */ - std::fill(std::begin(voice->mProps.Send)+num_sends, std::end(voice->mProps.Send), - VoiceProps::SendData{}); - - std::fill(voice->mSend.begin()+num_sends, voice->mSend.end(), Voice::TargetData{}); - for(auto &chandata : voice->mChans) - { - std::fill(chandata.mWetParams.begin()+num_sends, chandata.mWetParams.end(), - SendParams{}); - } - - delete voice->mUpdate.exchange(nullptr, std::memory_order_acq_rel); - - /* Force the voice to stopped if it was stopping. */ - Voice::State vstate{Voice::Stopping}; - voice->mPlayState.compare_exchange_strong(vstate, Voice::Stopped, - std::memory_order_acquire, std::memory_order_acquire); - if(voice->mSourceID.load(std::memory_order_relaxed) == 0u) - continue; - - voice->mStep = 0; - voice->mFlags |= VoiceIsFading; - - if(voice->mAmbiOrder && device->mAmbiOrder > voice->mAmbiOrder) - { - const uint8_t *OrderFromChan{(voice->mFmtChannels == FmtBFormat2D) ? - AmbiIndex::OrderFrom2DChannel().data() : - AmbiIndex::OrderFromChannel().data()}; - - const BandSplitter splitter{device->mXOverFreq / - static_cast(device->Frequency)}; - - const auto scales = BFormatDec::GetHFOrderScales(voice->mAmbiOrder, - device->mAmbiOrder); - for(auto &chandata : voice->mChans) - { - chandata.mPrevSamples.fill(0.0f); - chandata.mAmbiScale = scales[*(OrderFromChan++)]; - chandata.mAmbiSplitter = splitter; - chandata.mDryParams = DirectParams{}; - std::fill_n(chandata.mWetParams.begin(), num_sends, SendParams{}); - } - - voice->mFlags |= VoiceIsAmbisonic; - } - else - { - /* Clear previous samples. */ - for(auto &chandata : voice->mChans) - { - chandata.mPrevSamples.fill(0.0f); - chandata.mDryParams = DirectParams{}; - std::fill_n(chandata.mWetParams.begin(), num_sends, SendParams{}); - } - - voice->mFlags &= ~VoiceIsAmbisonic; - } - - if(device->AvgSpeakerDist > 0.0f) - { - /* Reinitialize the NFC filters for new parameters. */ - const float w1{SpeedOfSoundMetersPerSec / - (device->AvgSpeakerDist * static_cast(device->Frequency))}; - for(auto &chandata : voice->mChans) - chandata.mDryParams.NFCtrlFilter.init(w1); - } - } - srclock.unlock(); - - context->mPropsClean.test_and_set(std::memory_order_release); - UpdateContextProps(context); - context->mListener.PropsClean.test_and_set(std::memory_order_release); - UpdateListenerProps(context); - UpdateAllSourceProps(context); - } - mixer_mode.leave(); - - if(!device->Flags.test(DevicePaused)) - { - try { - auto backend = device->Backend.get(); - backend->start(); - device->Flags.set(DeviceRunning); - } - catch(al::backend_exception& e) { - device->handleDisconnect("%s", e.what()); - return ALC_INVALID_DEVICE; - } - } - - return ALC_NO_ERROR; -} - - -ALCdevice::ALCdevice(DeviceType type) : Type{type}, mContexts{&EmptyContextArray} -{ -} - -ALCdevice::~ALCdevice() -{ - TRACE("Freeing device %p\n", voidp{this}); - - Backend = nullptr; - - size_t count{std::accumulate(BufferList.cbegin(), BufferList.cend(), size_t{0u}, - [](size_t cur, const BufferSubList &sublist) noexcept -> size_t - { return cur + static_cast(PopCount(~sublist.FreeMask)); })}; - if(count > 0) - WARN("%zu Buffer%s not deleted\n", count, (count==1)?"":"s"); - - count = std::accumulate(EffectList.cbegin(), EffectList.cend(), size_t{0u}, - [](size_t cur, const EffectSubList &sublist) noexcept -> size_t - { return cur + static_cast(PopCount(~sublist.FreeMask)); }); - if(count > 0) - WARN("%zu Effect%s not deleted\n", count, (count==1)?"":"s"); - - count = std::accumulate(FilterList.cbegin(), FilterList.cend(), size_t{0u}, - [](size_t cur, const FilterSubList &sublist) noexcept -> size_t - { return cur + static_cast(PopCount(~sublist.FreeMask)); }); - if(count > 0) - WARN("%zu Filter%s not deleted\n", count, (count==1)?"":"s"); - - mHrtf = nullptr; - - auto *oldarray = mContexts.exchange(nullptr, std::memory_order_relaxed); - if(oldarray != &EmptyContextArray) delete oldarray; -} - - -/** Checks if the device handle is valid, and returns a new reference if so. */ -static DeviceRef VerifyDevice(ALCdevice *device) -{ - std::lock_guard _{ListLock}; - auto iter = std::lower_bound(DeviceList.begin(), DeviceList.end(), device); - if(iter != DeviceList.end() && *iter == device) - { - (*iter)->add_ref(); - return DeviceRef{*iter}; - } - return nullptr; -} - - -ALCcontext::ALCcontext(al::intrusive_ptr device) : mDevice{std::move(device)} -{ - mPropsClean.test_and_set(std::memory_order_relaxed); -} - -ALCcontext::~ALCcontext() -{ - TRACE("Freeing context %p\n", voidp{this}); - - size_t count{0}; - ContextProps *cprops{mParams.ContextUpdate.exchange(nullptr, std::memory_order_relaxed)}; - if(cprops) - { - ++count; - delete cprops; - } - cprops = mFreeContextProps.exchange(nullptr, std::memory_order_acquire); - while(cprops) - { - std::unique_ptr old{cprops}; - cprops = old->next.load(std::memory_order_relaxed); - ++count; - } - TRACE("Freed %zu context property object%s\n", count, (count==1)?"":"s"); - - count = std::accumulate(mSourceList.cbegin(), mSourceList.cend(), size_t{0u}, - [](size_t cur, const SourceSubList &sublist) noexcept -> size_t - { return cur + static_cast(PopCount(~sublist.FreeMask)); }); - if(count > 0) - WARN("%zu Source%s not deleted\n", count, (count==1)?"":"s"); - mSourceList.clear(); - mNumSources = 0; - - count = 0; - EffectSlotProps *eprops{mFreeEffectslotProps.exchange(nullptr, std::memory_order_acquire)}; - while(eprops) - { - std::unique_ptr old{eprops}; - eprops = old->next.load(std::memory_order_relaxed); - ++count; - } - TRACE("Freed %zu AuxiliaryEffectSlot property object%s\n", count, (count==1)?"":"s"); - - if(EffectSlotArray *curarray{mActiveAuxSlots.exchange(nullptr, std::memory_order_relaxed)}) - { - al::destroy_n(curarray->end(), curarray->size()); - delete curarray; - } - mDefaultSlot = nullptr; - - count = std::accumulate(mEffectSlotList.cbegin(), mEffectSlotList.cend(), size_t{0u}, - [](size_t cur, const EffectSlotSubList &sublist) noexcept -> size_t - { return cur + static_cast(PopCount(~sublist.FreeMask)); }); - if(count > 0) - WARN("%zu AuxiliaryEffectSlot%s not deleted\n", count, (count==1)?"":"s"); - mEffectSlotList.clear(); - mNumEffectSlots = 0; - - count = 0; - VoicePropsItem *vprops{mFreeVoiceProps.exchange(nullptr, std::memory_order_acquire)}; - while(vprops) - { - std::unique_ptr old{vprops}; - vprops = old->next.load(std::memory_order_relaxed); - ++count; - } - TRACE("Freed %zu voice property object%s\n", count, (count==1)?"":"s"); - - delete mVoices.exchange(nullptr, std::memory_order_relaxed); - - count = 0; - ListenerProps *lprops{mParams.ListenerUpdate.exchange(nullptr, std::memory_order_relaxed)}; - if(lprops) - { - ++count; - delete lprops; - } - lprops = mFreeListenerProps.exchange(nullptr, std::memory_order_acquire); - while(lprops) - { - std::unique_ptr old{lprops}; - lprops = old->next.load(std::memory_order_relaxed); - ++count; - } - TRACE("Freed %zu listener property object%s\n", count, (count==1)?"":"s"); - - if(mAsyncEvents) - { - count = 0; - auto evt_vec = mAsyncEvents->getReadVector(); - if(evt_vec.first.len > 0) - { - al::destroy_n(reinterpret_cast(evt_vec.first.buf), evt_vec.first.len); - count += evt_vec.first.len; - } - if(evt_vec.second.len > 0) - { - al::destroy_n(reinterpret_cast(evt_vec.second.buf), evt_vec.second.len); - count += evt_vec.second.len; - } - if(count > 0) - TRACE("Destructed %zu orphaned event%s\n", count, (count==1)?"":"s"); - mAsyncEvents->readAdvance(count); - } -} - -void ALCcontext::init() -{ - if(DefaultEffect.type != AL_EFFECT_NULL && mDevice->Type == DeviceType::Playback) - { - mDefaultSlot = std::make_unique(); - aluInitEffectPanning(&mDefaultSlot->mSlot, this); - } - - EffectSlotArray *auxslots; - if(!mDefaultSlot) - auxslots = EffectSlot::CreatePtrArray(0); - else - { - auxslots = EffectSlot::CreatePtrArray(1); - (*auxslots)[0] = &mDefaultSlot->mSlot; - mDefaultSlot->mState = SlotState::Playing; - } - mActiveAuxSlots.store(auxslots, std::memory_order_relaxed); - - allocVoiceChanges(1); - { - VoiceChange *cur{mVoiceChangeTail}; - while(VoiceChange *next{cur->mNext.load(std::memory_order_relaxed)}) - cur = next; - mCurrentVoiceChange.store(cur, std::memory_order_relaxed); - } - - mExtensionList = alExtList; - - - mParams.Matrix = alu::Matrix::Identity(); - mParams.Velocity = alu::Vector{}; - mParams.Gain = mListener.Gain; - mParams.MetersPerUnit = mListener.mMetersPerUnit; - mParams.DopplerFactor = mDopplerFactor; - mParams.SpeedOfSound = mSpeedOfSound * mDopplerVelocity; - mParams.SourceDistanceModel = mSourceDistanceModel; - mParams.mDistanceModel = mDistanceModel; - - - mAsyncEvents = RingBuffer::Create(511, sizeof(AsyncEvent), false); - StartEventThrd(this); - - - allocVoices(256); - mActiveVoiceCount.store(64, std::memory_order_relaxed); -} - -bool ALCcontext::deinit() -{ - if(LocalContext == this) - { - WARN("%p released while current on thread\n", voidp{this}); - ThreadContext.set(nullptr); - release(); - } - - ALCcontext *origctx{this}; - if(GlobalContext.compare_exchange_strong(origctx, nullptr)) - release(); - - bool ret{}; - /* First make sure this context exists in the device's list. */ - auto *oldarray = mDevice->mContexts.load(std::memory_order_acquire); - if(auto toremove = static_cast(std::count(oldarray->begin(), oldarray->end(), this))) - { - using ContextArray = al::FlexArray; - auto alloc_ctx_array = [](const size_t count) -> ContextArray* - { - if(count == 0) return &EmptyContextArray; - return ContextArray::Create(count).release(); - }; - auto *newarray = alloc_ctx_array(oldarray->size() - toremove); - - /* Copy the current/old context handles to the new array, excluding the - * given context. - */ - std::copy_if(oldarray->begin(), oldarray->end(), newarray->begin(), - std::bind(std::not_equal_to{}, _1, this)); - - /* Store the new context array in the device. Wait for any current mix - * to finish before deleting the old array. - */ - mDevice->mContexts.store(newarray); - if(oldarray != &EmptyContextArray) - { - mDevice->waitForMix(); - delete oldarray; - } - - ret = !newarray->empty(); - } - else - ret = !oldarray->empty(); - - StopEventThrd(this); - - return ret; -} - - -/** - * Checks if the given context is valid, returning a new reference to it if so. - */ -static ContextRef VerifyContext(ALCcontext *context) -{ - std::lock_guard _{ListLock}; - auto iter = std::lower_bound(ContextList.begin(), ContextList.end(), context); - if(iter != ContextList.end() && *iter == context) - { - (*iter)->add_ref(); - return ContextRef{*iter}; - } - return nullptr; -} - -/** Returns a new reference to the currently active context for this thread. */ -ContextRef GetContextRef(void) -{ - ALCcontext *context{LocalContext}; - if(context) - context->add_ref(); - else - { - std::lock_guard _{ListLock}; - context = GlobalContext.load(std::memory_order_acquire); - if(context) context->add_ref(); - } - return ContextRef{context}; -} - - -/************************************************ - * Standard ALC functions - ************************************************/ - -ALC_API ALCenum ALC_APIENTRY alcGetError(ALCdevice *device) -START_API_FUNC -{ - DeviceRef dev{VerifyDevice(device)}; - if(dev) return dev->LastError.exchange(ALC_NO_ERROR); - return LastNullDeviceError.exchange(ALC_NO_ERROR); -} -END_API_FUNC - - -ALC_API void ALC_APIENTRY alcSuspendContext(ALCcontext *context) -START_API_FUNC -{ - if(!SuspendDefers) - return; - - ContextRef ctx{VerifyContext(context)}; - if(!ctx) - alcSetError(nullptr, ALC_INVALID_CONTEXT); - else - ctx->deferUpdates(); -} -END_API_FUNC - -ALC_API void ALC_APIENTRY alcProcessContext(ALCcontext *context) -START_API_FUNC -{ - if(!SuspendDefers) - return; - - ContextRef ctx{VerifyContext(context)}; - if(!ctx) - alcSetError(nullptr, ALC_INVALID_CONTEXT); - else - ctx->processUpdates(); -} -END_API_FUNC - - -ALC_API const ALCchar* ALC_APIENTRY alcGetString(ALCdevice *Device, ALCenum param) -START_API_FUNC -{ - const ALCchar *value{nullptr}; - - switch(param) - { - case ALC_NO_ERROR: - value = alcNoError; - break; - - case ALC_INVALID_ENUM: - value = alcErrInvalidEnum; - break; - - case ALC_INVALID_VALUE: - value = alcErrInvalidValue; - break; - - case ALC_INVALID_DEVICE: - value = alcErrInvalidDevice; - break; - - case ALC_INVALID_CONTEXT: - value = alcErrInvalidContext; - break; - - case ALC_OUT_OF_MEMORY: - value = alcErrOutOfMemory; - break; - - case ALC_DEVICE_SPECIFIER: - value = alcDefaultName; - break; - - case ALC_ALL_DEVICES_SPECIFIER: - if(DeviceRef dev{VerifyDevice(Device)}) - value = dev->DeviceName.c_str(); - else - { - ProbeAllDevicesList(); - value = alcAllDevicesList.c_str(); - } - break; - - case ALC_CAPTURE_DEVICE_SPECIFIER: - if(DeviceRef dev{VerifyDevice(Device)}) - value = dev->DeviceName.c_str(); - else - { - ProbeCaptureDeviceList(); - value = alcCaptureDeviceList.c_str(); - } - break; - - /* Default devices are always first in the list */ - case ALC_DEFAULT_DEVICE_SPECIFIER: - value = alcDefaultName; - break; - - case ALC_DEFAULT_ALL_DEVICES_SPECIFIER: - if(alcAllDevicesList.empty()) - ProbeAllDevicesList(); - - /* Copy first entry as default. */ - alcDefaultAllDevicesSpecifier = alcAllDevicesList.c_str(); - value = alcDefaultAllDevicesSpecifier.c_str(); - break; - - case ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER: - if(alcCaptureDeviceList.empty()) - ProbeCaptureDeviceList(); - - /* Copy first entry as default. */ - alcCaptureDefaultDeviceSpecifier = alcCaptureDeviceList.c_str(); - value = alcCaptureDefaultDeviceSpecifier.c_str(); - break; - - case ALC_EXTENSIONS: - if(VerifyDevice(Device)) - value = alcExtensionList; - else - value = alcNoDeviceExtList; - break; - - case ALC_HRTF_SPECIFIER_SOFT: - if(DeviceRef dev{VerifyDevice(Device)}) - { - std::lock_guard _{dev->StateLock}; - value = (dev->mHrtf ? dev->HrtfName.c_str() : ""); - } - else - alcSetError(nullptr, ALC_INVALID_DEVICE); - break; - - default: - alcSetError(VerifyDevice(Device).get(), ALC_INVALID_ENUM); - break; - } - - return value; -} -END_API_FUNC - - -static inline int NumAttrsForDevice(ALCdevice *device) -{ - if(device->Type == DeviceType::Capture) return 9; - if(device->Type != DeviceType::Loopback) return 29; - if(device->FmtChans == DevFmtAmbi3D) - return 35; - return 29; -} - -static size_t GetIntegerv(ALCdevice *device, ALCenum param, const al::span values) -{ - size_t i; - - if(values.empty()) - { - alcSetError(device, ALC_INVALID_VALUE); - return 0; - } - - if(!device) - { - switch(param) - { - case ALC_MAJOR_VERSION: - values[0] = alcMajorVersion; - return 1; - case ALC_MINOR_VERSION: - values[0] = alcMinorVersion; - return 1; - - case ALC_ATTRIBUTES_SIZE: - case ALC_ALL_ATTRIBUTES: - case ALC_FREQUENCY: - case ALC_REFRESH: - case ALC_SYNC: - case ALC_MONO_SOURCES: - case ALC_STEREO_SOURCES: - case ALC_CAPTURE_SAMPLES: - case ALC_FORMAT_CHANNELS_SOFT: - case ALC_FORMAT_TYPE_SOFT: - case ALC_AMBISONIC_LAYOUT_SOFT: - case ALC_AMBISONIC_SCALING_SOFT: - case ALC_AMBISONIC_ORDER_SOFT: - case ALC_MAX_AMBISONIC_ORDER_SOFT: - alcSetError(nullptr, ALC_INVALID_DEVICE); - return 0; - - default: - alcSetError(nullptr, ALC_INVALID_ENUM); - } - return 0; - } - - if(device->Type == DeviceType::Capture) - { - switch(param) - { - case ALC_ATTRIBUTES_SIZE: - values[0] = NumAttrsForDevice(device); - return 1; - - case ALC_ALL_ATTRIBUTES: - i = 0; - if(values.size() < static_cast(NumAttrsForDevice(device))) - alcSetError(device, ALC_INVALID_VALUE); - else - { - std::lock_guard _{device->StateLock}; - values[i++] = ALC_MAJOR_VERSION; - values[i++] = alcMajorVersion; - values[i++] = ALC_MINOR_VERSION; - values[i++] = alcMinorVersion; - values[i++] = ALC_CAPTURE_SAMPLES; - values[i++] = static_cast(device->Backend->availableSamples()); - values[i++] = ALC_CONNECTED; - values[i++] = device->Connected.load(std::memory_order_relaxed); - values[i++] = 0; - } - return i; - - case ALC_MAJOR_VERSION: - values[0] = alcMajorVersion; - return 1; - case ALC_MINOR_VERSION: - values[0] = alcMinorVersion; - return 1; - - case ALC_CAPTURE_SAMPLES: - { - std::lock_guard _{device->StateLock}; - values[0] = static_cast(device->Backend->availableSamples()); - } - return 1; - - case ALC_CONNECTED: - { - std::lock_guard _{device->StateLock}; - values[0] = device->Connected.load(std::memory_order_acquire); - } - return 1; - - default: - alcSetError(device, ALC_INVALID_ENUM); - } - return 0; - } - - /* render device */ - switch(param) - { - case ALC_ATTRIBUTES_SIZE: - values[0] = NumAttrsForDevice(device); - return 1; - - case ALC_ALL_ATTRIBUTES: - i = 0; - if(values.size() < static_cast(NumAttrsForDevice(device))) - alcSetError(device, ALC_INVALID_VALUE); - else - { - std::lock_guard _{device->StateLock}; - values[i++] = ALC_MAJOR_VERSION; - values[i++] = alcMajorVersion; - values[i++] = ALC_MINOR_VERSION; - values[i++] = alcMinorVersion; - values[i++] = ALC_EFX_MAJOR_VERSION; - values[i++] = alcEFXMajorVersion; - values[i++] = ALC_EFX_MINOR_VERSION; - values[i++] = alcEFXMinorVersion; - - values[i++] = ALC_FREQUENCY; - values[i++] = static_cast(device->Frequency); - if(device->Type != DeviceType::Loopback) - { - values[i++] = ALC_REFRESH; - values[i++] = static_cast(device->Frequency / device->UpdateSize); - - values[i++] = ALC_SYNC; - values[i++] = ALC_FALSE; - } - else - { - if(device->FmtChans == DevFmtAmbi3D) - { - values[i++] = ALC_AMBISONIC_LAYOUT_SOFT; - values[i++] = EnumFromDevAmbi(device->mAmbiLayout); - - values[i++] = ALC_AMBISONIC_SCALING_SOFT; - values[i++] = EnumFromDevAmbi(device->mAmbiScale); - - values[i++] = ALC_AMBISONIC_ORDER_SOFT; - values[i++] = static_cast(device->mAmbiOrder); - } - - values[i++] = ALC_FORMAT_CHANNELS_SOFT; - values[i++] = EnumFromDevFmt(device->FmtChans); - - values[i++] = ALC_FORMAT_TYPE_SOFT; - values[i++] = EnumFromDevFmt(device->FmtType); - } - - values[i++] = ALC_MONO_SOURCES; - values[i++] = static_cast(device->NumMonoSources); - - values[i++] = ALC_STEREO_SOURCES; - values[i++] = static_cast(device->NumStereoSources); - - values[i++] = ALC_MAX_AUXILIARY_SENDS; - values[i++] = static_cast(device->NumAuxSends); - - values[i++] = ALC_HRTF_SOFT; - values[i++] = (device->mHrtf ? ALC_TRUE : ALC_FALSE); - - values[i++] = ALC_HRTF_STATUS_SOFT; - values[i++] = device->HrtfStatus; - - values[i++] = ALC_OUTPUT_LIMITER_SOFT; - values[i++] = device->Limiter ? ALC_TRUE : ALC_FALSE; - - values[i++] = ALC_MAX_AMBISONIC_ORDER_SOFT; - values[i++] = MaxAmbiOrder; - - values[i++] = 0; - } - return i; - - case ALC_MAJOR_VERSION: - values[0] = alcMajorVersion; - return 1; - - case ALC_MINOR_VERSION: - values[0] = alcMinorVersion; - return 1; - - case ALC_EFX_MAJOR_VERSION: - values[0] = alcEFXMajorVersion; - return 1; - - case ALC_EFX_MINOR_VERSION: - values[0] = alcEFXMinorVersion; - return 1; - - case ALC_FREQUENCY: - values[0] = static_cast(device->Frequency); - return 1; - - case ALC_REFRESH: - if(device->Type == DeviceType::Loopback) - { - alcSetError(device, ALC_INVALID_DEVICE); - return 0; - } - { - std::lock_guard _{device->StateLock}; - values[0] = static_cast(device->Frequency / device->UpdateSize); - } - return 1; - - case ALC_SYNC: - if(device->Type == DeviceType::Loopback) - { - alcSetError(device, ALC_INVALID_DEVICE); - return 0; - } - values[0] = ALC_FALSE; - return 1; - - case ALC_FORMAT_CHANNELS_SOFT: - if(device->Type != DeviceType::Loopback) - { - alcSetError(device, ALC_INVALID_DEVICE); - return 0; - } - values[0] = EnumFromDevFmt(device->FmtChans); - return 1; - - case ALC_FORMAT_TYPE_SOFT: - if(device->Type != DeviceType::Loopback) - { - alcSetError(device, ALC_INVALID_DEVICE); - return 0; - } - values[0] = EnumFromDevFmt(device->FmtType); - return 1; - - case ALC_AMBISONIC_LAYOUT_SOFT: - if(device->Type != DeviceType::Loopback || device->FmtChans != DevFmtAmbi3D) - { - alcSetError(device, ALC_INVALID_DEVICE); - return 0; - } - values[0] = EnumFromDevAmbi(device->mAmbiLayout); - return 1; - - case ALC_AMBISONIC_SCALING_SOFT: - if(device->Type != DeviceType::Loopback || device->FmtChans != DevFmtAmbi3D) - { - alcSetError(device, ALC_INVALID_DEVICE); - return 0; - } - values[0] = EnumFromDevAmbi(device->mAmbiScale); - return 1; - - case ALC_AMBISONIC_ORDER_SOFT: - if(device->Type != DeviceType::Loopback || device->FmtChans != DevFmtAmbi3D) - { - alcSetError(device, ALC_INVALID_DEVICE); - return 0; - } - values[0] = static_cast(device->mAmbiOrder); - return 1; - - case ALC_MONO_SOURCES: - values[0] = static_cast(device->NumMonoSources); - return 1; - - case ALC_STEREO_SOURCES: - values[0] = static_cast(device->NumStereoSources); - return 1; - - case ALC_MAX_AUXILIARY_SENDS: - values[0] = static_cast(device->NumAuxSends); - return 1; - - case ALC_CONNECTED: - { - std::lock_guard _{device->StateLock}; - values[0] = device->Connected.load(std::memory_order_acquire); - } - return 1; - - case ALC_HRTF_SOFT: - values[0] = (device->mHrtf ? ALC_TRUE : ALC_FALSE); - return 1; - - case ALC_HRTF_STATUS_SOFT: - values[0] = device->HrtfStatus; - return 1; - - case ALC_NUM_HRTF_SPECIFIERS_SOFT: - { - std::lock_guard _{device->StateLock}; - device->HrtfList = EnumerateHrtf(device->DeviceName.c_str()); - values[0] = static_cast(minz(device->HrtfList.size(), - std::numeric_limits::max())); - } - return 1; - - case ALC_OUTPUT_LIMITER_SOFT: - values[0] = device->Limiter ? ALC_TRUE : ALC_FALSE; - return 1; - - case ALC_MAX_AMBISONIC_ORDER_SOFT: - values[0] = MaxAmbiOrder; - return 1; - - default: - alcSetError(device, ALC_INVALID_ENUM); - } - return 0; -} - -ALC_API void ALC_APIENTRY alcGetIntegerv(ALCdevice *device, ALCenum param, ALCsizei size, ALCint *values) -START_API_FUNC -{ - DeviceRef dev{VerifyDevice(device)}; - if(size <= 0 || values == nullptr) - alcSetError(dev.get(), ALC_INVALID_VALUE); - else - GetIntegerv(dev.get(), param, {values, static_cast(size)}); -} -END_API_FUNC - -ALC_API void ALC_APIENTRY alcGetInteger64vSOFT(ALCdevice *device, ALCenum pname, ALCsizei size, ALCint64SOFT *values) -START_API_FUNC -{ - DeviceRef dev{VerifyDevice(device)}; - if(size <= 0 || values == nullptr) - { - alcSetError(dev.get(), ALC_INVALID_VALUE); - return; - } - if(!dev || dev->Type == DeviceType::Capture) - { - auto ivals = al::vector(static_cast(size)); - size_t got{GetIntegerv(dev.get(), pname, ivals)}; - std::copy_n(ivals.begin(), got, values); - return; - } - /* render device */ - switch(pname) - { - case ALC_ATTRIBUTES_SIZE: - *values = NumAttrsForDevice(dev.get())+4; - break; - - case ALC_ALL_ATTRIBUTES: - if(size < NumAttrsForDevice(dev.get())+4) - alcSetError(dev.get(), ALC_INVALID_VALUE); - else - { - size_t i{0}; - std::lock_guard _{dev->StateLock}; - values[i++] = ALC_FREQUENCY; - values[i++] = dev->Frequency; - - if(dev->Type != DeviceType::Loopback) - { - values[i++] = ALC_REFRESH; - values[i++] = dev->Frequency / dev->UpdateSize; - - values[i++] = ALC_SYNC; - values[i++] = ALC_FALSE; - } - else - { - if(dev->FmtChans == DevFmtAmbi3D) - { - values[i++] = ALC_AMBISONIC_LAYOUT_SOFT; - values[i++] = EnumFromDevAmbi(dev->mAmbiLayout); - - values[i++] = ALC_AMBISONIC_SCALING_SOFT; - values[i++] = EnumFromDevAmbi(dev->mAmbiScale); - - values[i++] = ALC_AMBISONIC_ORDER_SOFT; - values[i++] = dev->mAmbiOrder; - } - - values[i++] = ALC_FORMAT_CHANNELS_SOFT; - values[i++] = EnumFromDevFmt(dev->FmtChans); - - values[i++] = ALC_FORMAT_TYPE_SOFT; - values[i++] = EnumFromDevFmt(dev->FmtType); - } - - values[i++] = ALC_MONO_SOURCES; - values[i++] = dev->NumMonoSources; - - values[i++] = ALC_STEREO_SOURCES; - values[i++] = dev->NumStereoSources; - - values[i++] = ALC_MAX_AUXILIARY_SENDS; - values[i++] = dev->NumAuxSends; - - values[i++] = ALC_HRTF_SOFT; - values[i++] = (dev->mHrtf ? ALC_TRUE : ALC_FALSE); - - values[i++] = ALC_HRTF_STATUS_SOFT; - values[i++] = dev->HrtfStatus; - - values[i++] = ALC_OUTPUT_LIMITER_SOFT; - values[i++] = dev->Limiter ? ALC_TRUE : ALC_FALSE; - - ClockLatency clock{GetClockLatency(dev.get())}; - values[i++] = ALC_DEVICE_CLOCK_SOFT; - values[i++] = clock.ClockTime.count(); - - values[i++] = ALC_DEVICE_LATENCY_SOFT; - values[i++] = clock.Latency.count(); - - values[i++] = 0; - } - break; - - case ALC_DEVICE_CLOCK_SOFT: - { - std::lock_guard _{dev->StateLock}; - uint samplecount, refcount; - nanoseconds basecount; - do { - refcount = dev->waitForMix(); - basecount = dev->ClockBase; - samplecount = dev->SamplesDone; - } while(refcount != ReadRef(dev->MixCount)); - basecount += nanoseconds{seconds{samplecount}} / dev->Frequency; - *values = basecount.count(); - } - break; - - case ALC_DEVICE_LATENCY_SOFT: - { - std::lock_guard _{dev->StateLock}; - ClockLatency clock{GetClockLatency(dev.get())}; - *values = clock.Latency.count(); - } - break; - - case ALC_DEVICE_CLOCK_LATENCY_SOFT: - if(size < 2) - alcSetError(dev.get(), ALC_INVALID_VALUE); - else - { - std::lock_guard _{dev->StateLock}; - ClockLatency clock{GetClockLatency(dev.get())}; - values[0] = clock.ClockTime.count(); - values[1] = clock.Latency.count(); - } - break; - - default: - auto ivals = al::vector(static_cast(size)); - size_t got{GetIntegerv(dev.get(), pname, ivals)}; - std::copy_n(ivals.begin(), got, values); - break; - } -} -END_API_FUNC - - -ALC_API ALCboolean ALC_APIENTRY alcIsExtensionPresent(ALCdevice *device, const ALCchar *extName) -START_API_FUNC -{ - DeviceRef dev{VerifyDevice(device)}; - if(!extName) - alcSetError(dev.get(), ALC_INVALID_VALUE); - else - { - size_t len = strlen(extName); - const char *ptr = (dev ? alcExtensionList : alcNoDeviceExtList); - while(ptr && *ptr) - { - if(al::strncasecmp(ptr, extName, len) == 0 && (ptr[len] == '\0' || isspace(ptr[len]))) - return ALC_TRUE; - - if((ptr=strchr(ptr, ' ')) != nullptr) - { - do { - ++ptr; - } while(isspace(*ptr)); - } - } - } - return ALC_FALSE; -} -END_API_FUNC - - -ALC_API ALCvoid* ALC_APIENTRY alcGetProcAddress(ALCdevice *device, const ALCchar *funcName) -START_API_FUNC -{ - if(!funcName) - { - DeviceRef dev{VerifyDevice(device)}; - alcSetError(dev.get(), ALC_INVALID_VALUE); - } - else - { - for(const auto &func : alcFunctions) - { - if(strcmp(func.funcName, funcName) == 0) - return func.address; - } - } - return nullptr; -} -END_API_FUNC - - -ALC_API ALCenum ALC_APIENTRY alcGetEnumValue(ALCdevice *device, const ALCchar *enumName) -START_API_FUNC -{ - if(!enumName) - { - DeviceRef dev{VerifyDevice(device)}; - alcSetError(dev.get(), ALC_INVALID_VALUE); - } - else - { - for(const auto &enm : alcEnumerations) - { - if(strcmp(enm.enumName, enumName) == 0) - return enm.value; - } - } - return 0; -} -END_API_FUNC - - -ALC_API ALCcontext* ALC_APIENTRY alcCreateContext(ALCdevice *device, const ALCint *attrList) -START_API_FUNC -{ - /* Explicitly hold the list lock while taking the StateLock in case the - * device is asynchronously destroyed, to ensure this new context is - * properly cleaned up after being made. - */ - std::unique_lock listlock{ListLock}; - DeviceRef dev{VerifyDevice(device)}; - if(!dev || dev->Type == DeviceType::Capture || !dev->Connected.load(std::memory_order_relaxed)) - { - listlock.unlock(); - alcSetError(dev.get(), ALC_INVALID_DEVICE); - return nullptr; - } - std::unique_lock statelock{dev->StateLock}; - listlock.unlock(); - - dev->LastError.store(ALC_NO_ERROR); - - ALCenum err{UpdateDeviceParams(dev.get(), attrList)}; - if(err != ALC_NO_ERROR) - { - alcSetError(dev.get(), err); - return nullptr; - } - - ContextRef context{new ALCcontext{dev}}; - context->init(); - - if(auto volopt = ConfigValueFloat(dev->DeviceName.c_str(), nullptr, "volume-adjust")) - { - const float valf{*volopt}; - if(!std::isfinite(valf)) - ERR("volume-adjust must be finite: %f\n", valf); - else - { - const float db{clampf(valf, -24.0f, 24.0f)}; - if(db != valf) - WARN("volume-adjust clamped: %f, range: +/-%f\n", valf, 24.0f); - context->mGainBoost = std::pow(10.0f, db/20.0f); - TRACE("volume-adjust gain: %f\n", context->mGainBoost); - } - } - UpdateListenerProps(context.get()); - - { - using ContextArray = al::FlexArray; - - /* Allocate a new context array, which holds 1 more than the current/ - * old array. - */ - auto *oldarray = device->mContexts.load(); - const size_t newcount{oldarray->size()+1}; - std::unique_ptr newarray{ContextArray::Create(newcount)}; - - /* Copy the current/old context handles to the new array, appending the - * new context. - */ - auto iter = std::copy(oldarray->begin(), oldarray->end(), newarray->begin()); - *iter = context.get(); - - /* Store the new context array in the device. Wait for any current mix - * to finish before deleting the old array. - */ - dev->mContexts.store(newarray.release()); - if(oldarray != &EmptyContextArray) - { - dev->waitForMix(); - delete oldarray; - } - } - statelock.unlock(); - - { - std::lock_guard _{ListLock}; - auto iter = std::lower_bound(ContextList.cbegin(), ContextList.cend(), context.get()); - ContextList.emplace(iter, context.get()); - } - - if(ALeffectslot *slot{context->mDefaultSlot.get()}) - { - if(slot->initEffect(&DefaultEffect, context.get()) == AL_NO_ERROR) - slot->updateProps(context.get()); - else - ERR("Failed to initialize the default effect\n"); - } - - TRACE("Created context %p\n", voidp{context.get()}); - return context.release(); -} -END_API_FUNC - -ALC_API void ALC_APIENTRY alcDestroyContext(ALCcontext *context) -START_API_FUNC -{ - std::unique_lock listlock{ListLock}; - auto iter = std::lower_bound(ContextList.begin(), ContextList.end(), context); - if(iter == ContextList.end() || *iter != context) - { - listlock.unlock(); - alcSetError(nullptr, ALC_INVALID_CONTEXT); - return; - } - /* Hold a reference to this context so it remains valid until the ListLock - * is released. - */ - ContextRef ctx{*iter}; - ContextList.erase(iter); - - ALCdevice *Device{ctx->mDevice.get()}; - - std::lock_guard _{Device->StateLock}; - if(!ctx->deinit() && Device->Flags.test(DeviceRunning)) - { - Device->Backend->stop(); - Device->Flags.reset(DeviceRunning); - } -} -END_API_FUNC - - -ALC_API ALCcontext* ALC_APIENTRY alcGetCurrentContext(void) -START_API_FUNC -{ - ALCcontext *Context{LocalContext}; - if(!Context) Context = GlobalContext.load(); - return Context; -} -END_API_FUNC - -/** Returns the currently active thread-local context. */ -ALC_API ALCcontext* ALC_APIENTRY alcGetThreadContext(void) -START_API_FUNC -{ return LocalContext; } -END_API_FUNC - -ALC_API ALCboolean ALC_APIENTRY alcMakeContextCurrent(ALCcontext *context) -START_API_FUNC -{ - /* context must be valid or nullptr */ - ContextRef ctx; - if(context) - { - ctx = VerifyContext(context); - if(!ctx) - { - alcSetError(nullptr, ALC_INVALID_CONTEXT); - return ALC_FALSE; - } - } - /* Release this reference (if any) to store it in the GlobalContext - * pointer. Take ownership of the reference (if any) that was previously - * stored there. - */ - ctx = ContextRef{GlobalContext.exchange(ctx.release())}; - - /* Reset (decrement) the previous global reference by replacing it with the - * thread-local context. Take ownership of the thread-local context - * reference (if any), clearing the storage to null. - */ - ctx = ContextRef{LocalContext}; - if(ctx) ThreadContext.set(nullptr); - /* Reset (decrement) the previous thread-local reference. */ - - return ALC_TRUE; -} -END_API_FUNC - -/** Makes the given context the active context for the current thread. */ -ALC_API ALCboolean ALC_APIENTRY alcSetThreadContext(ALCcontext *context) -START_API_FUNC -{ - /* context must be valid or nullptr */ - ContextRef ctx; - if(context) - { - ctx = VerifyContext(context); - if(!ctx) - { - alcSetError(nullptr, ALC_INVALID_CONTEXT); - return ALC_FALSE; - } - } - /* context's reference count is already incremented */ - ContextRef old{LocalContext}; - ThreadContext.set(ctx.release()); - - return ALC_TRUE; -} -END_API_FUNC - - -ALC_API ALCdevice* ALC_APIENTRY alcGetContextsDevice(ALCcontext *Context) -START_API_FUNC -{ - ContextRef ctx{VerifyContext(Context)}; - if(!ctx) - { - alcSetError(nullptr, ALC_INVALID_CONTEXT); - return nullptr; - } - return ctx->mDevice.get(); -} -END_API_FUNC - - -ALC_API ALCdevice* ALC_APIENTRY alcOpenDevice(const ALCchar *deviceName) -START_API_FUNC -{ - DO_INITCONFIG(); - - if(!PlaybackFactory) - { - alcSetError(nullptr, ALC_INVALID_VALUE); - return nullptr; - } - - if(deviceName) - { - if(!deviceName[0] || al::strcasecmp(deviceName, alcDefaultName) == 0 -#ifdef _WIN32 - /* Some old Windows apps hardcode these expecting OpenAL to use a - * specific audio API, even when they're not enumerated. Creative's - * router effectively ignores them too. - */ - || al::strcasecmp(deviceName, "DirectSound3D") == 0 - || al::strcasecmp(deviceName, "DirectSound") == 0 - || al::strcasecmp(deviceName, "MMSYSTEM") == 0 -#endif - || al::strcasecmp(deviceName, "openal-soft") == 0) - deviceName = nullptr; - } - - DeviceRef device{new ALCdevice{DeviceType::Playback}}; - - /* Set output format */ - device->FmtChans = DevFmtChannelsDefault; - device->FmtType = DevFmtTypeDefault; - device->Frequency = DEFAULT_OUTPUT_RATE; - device->UpdateSize = DEFAULT_UPDATE_SIZE; - device->BufferSize = DEFAULT_UPDATE_SIZE * DEFAULT_NUM_UPDATES; - - device->SourcesMax = 256; - device->AuxiliaryEffectSlotMax = 64; - device->NumAuxSends = DEFAULT_SENDS; - - try { - auto backend = PlaybackFactory->createBackend(device.get(), BackendType::Playback); - std::lock_guard _{ListLock}; - backend->open(deviceName); - device->Backend = std::move(backend); - } - catch(al::backend_exception &e) { - WARN("Failed to open playback device: %s\n", e.what()); - alcSetError(nullptr, (e.errorCode() == al::backend_error::OutOfMemory) - ? ALC_OUT_OF_MEMORY : ALC_INVALID_VALUE); - return nullptr; - } - - deviceName = device->DeviceName.c_str(); - if(auto chanopt = ConfigValueStr(deviceName, nullptr, "channels")) - { - static const struct ChannelMap { - const char name[16]; - DevFmtChannels chans; - uint order; - } chanlist[] = { - { "mono", DevFmtMono, 0 }, - { "stereo", DevFmtStereo, 0 }, - { "quad", DevFmtQuad, 0 }, - { "surround51", DevFmtX51, 0 }, - { "surround61", DevFmtX61, 0 }, - { "surround71", DevFmtX71, 0 }, - { "surround51rear", DevFmtX51Rear, 0 }, - { "ambi1", DevFmtAmbi3D, 1 }, - { "ambi2", DevFmtAmbi3D, 2 }, - { "ambi3", DevFmtAmbi3D, 3 }, - }; - - const ALCchar *fmt{chanopt->c_str()}; - auto iter = std::find_if(std::begin(chanlist), std::end(chanlist), - [fmt](const ChannelMap &entry) -> bool - { return al::strcasecmp(entry.name, fmt) == 0; } - ); - if(iter == std::end(chanlist)) - ERR("Unsupported channels: %s\n", fmt); - else - { - device->FmtChans = iter->chans; - device->mAmbiOrder = iter->order; - device->Flags.set(ChannelsRequest); - } - } - if(auto typeopt = ConfigValueStr(deviceName, nullptr, "sample-type")) - { - static const struct TypeMap { - const char name[16]; - DevFmtType type; - } typelist[] = { - { "int8", DevFmtByte }, - { "uint8", DevFmtUByte }, - { "int16", DevFmtShort }, - { "uint16", DevFmtUShort }, - { "int32", DevFmtInt }, - { "uint32", DevFmtUInt }, - { "float32", DevFmtFloat }, - }; - - const ALCchar *fmt{typeopt->c_str()}; - auto iter = std::find_if(std::begin(typelist), std::end(typelist), - [fmt](const TypeMap &entry) -> bool - { return al::strcasecmp(entry.name, fmt) == 0; } - ); - if(iter == std::end(typelist)) - ERR("Unsupported sample-type: %s\n", fmt); - else - { - device->FmtType = iter->type; - device->Flags.set(SampleTypeRequest); - } - } - - if(uint freq{ConfigValueUInt(deviceName, nullptr, "frequency").value_or(0u)}) - { - if(freq < MIN_OUTPUT_RATE || freq > MAX_OUTPUT_RATE) - { - const uint newfreq{clampu(freq, MIN_OUTPUT_RATE, MAX_OUTPUT_RATE)}; - ERR("%uhz request clamped to %uhz\n", freq, newfreq); - freq = newfreq; - } - const double scale{static_cast(freq) / device->Frequency}; - device->UpdateSize = static_cast(device->UpdateSize*scale + 0.5); - device->BufferSize = static_cast(device->BufferSize*scale + 0.5); - device->Frequency = freq; - device->Flags.set(FrequencyRequest); - } - - if(auto persizeopt = ConfigValueUInt(deviceName, nullptr, "period_size")) - device->UpdateSize = clampu(*persizeopt, 64, 8192); - - if(auto peropt = ConfigValueUInt(deviceName, nullptr, "periods")) - device->BufferSize = device->UpdateSize * clampu(*peropt, 2, 16); - else - device->BufferSize = maxu(device->BufferSize, device->UpdateSize*2); - - if(auto srcsmax = ConfigValueUInt(deviceName, nullptr, "sources").value_or(0)) - device->SourcesMax = srcsmax; - - if(auto slotsmax = ConfigValueUInt(deviceName, nullptr, "slots").value_or(0)) - device->AuxiliaryEffectSlotMax = minu(slotsmax, INT_MAX); - - if(auto sendsopt = ConfigValueInt(deviceName, nullptr, "sends")) - device->NumAuxSends = minu(DEFAULT_SENDS, - static_cast(clampi(*sendsopt, 0, MAX_SENDS))); - - device->NumStereoSources = 1; - device->NumMonoSources = device->SourcesMax - device->NumStereoSources; - - if(auto ambiopt = ConfigValueStr(deviceName, nullptr, "ambi-format")) - { - const ALCchar *fmt{ambiopt->c_str()}; - if(al::strcasecmp(fmt, "fuma") == 0) - { - if(device->mAmbiOrder > 3) - ERR("FuMa is incompatible with %d%s order ambisonics (up to third-order only)\n", - device->mAmbiOrder, - (((device->mAmbiOrder%100)/10) == 1) ? "th" : - ((device->mAmbiOrder%10) == 1) ? "st" : - ((device->mAmbiOrder%10) == 2) ? "nd" : - ((device->mAmbiOrder%10) == 3) ? "rd" : "th"); - else - { - device->mAmbiLayout = DevAmbiLayout::FuMa; - device->mAmbiScale = DevAmbiScaling::FuMa; - } - } - else if(al::strcasecmp(fmt, "ambix") == 0 || al::strcasecmp(fmt, "acn+sn3d") == 0) - { - device->mAmbiLayout = DevAmbiLayout::ACN; - device->mAmbiScale = DevAmbiScaling::SN3D; - } - else if(al::strcasecmp(fmt, "acn+n3d") == 0) - { - device->mAmbiLayout = DevAmbiLayout::ACN; - device->mAmbiScale = DevAmbiScaling::N3D; - } - else - ERR("Unsupported ambi-format: %s\n", fmt); - } - - { - std::lock_guard _{ListLock}; - auto iter = std::lower_bound(DeviceList.cbegin(), DeviceList.cend(), device.get()); - DeviceList.emplace(iter, device.get()); - } - - TRACE("Created device %p, \"%s\"\n", voidp{device.get()}, device->DeviceName.c_str()); - return device.release(); -} -END_API_FUNC - -ALC_API ALCboolean ALC_APIENTRY alcCloseDevice(ALCdevice *device) -START_API_FUNC -{ - std::unique_lock listlock{ListLock}; - auto iter = std::lower_bound(DeviceList.begin(), DeviceList.end(), device); - if(iter == DeviceList.end() || *iter != device) - { - alcSetError(nullptr, ALC_INVALID_DEVICE); - return ALC_FALSE; - } - if((*iter)->Type == DeviceType::Capture) - { - alcSetError(*iter, ALC_INVALID_DEVICE); - return ALC_FALSE; - } - - /* Erase the device, and any remaining contexts left on it, from their - * respective lists. - */ - DeviceRef dev{*iter}; - DeviceList.erase(iter); - - std::unique_lock statelock{dev->StateLock}; - al::vector orphanctxs; - for(ALCcontext *ctx : *dev->mContexts.load()) - { - auto ctxiter = std::lower_bound(ContextList.begin(), ContextList.end(), ctx); - if(ctxiter != ContextList.end() && *ctxiter == ctx) - { - orphanctxs.emplace_back(ContextRef{*ctxiter}); - ContextList.erase(ctxiter); - } - } - listlock.unlock(); - - for(ContextRef &context : orphanctxs) - { - WARN("Releasing orphaned context %p\n", voidp{context.get()}); - context->deinit(); - } - orphanctxs.clear(); - - if(dev->Flags.test(DeviceRunning)) - dev->Backend->stop(); - dev->Flags.reset(DeviceRunning); - - return ALC_TRUE; -} -END_API_FUNC - - -/************************************************ - * ALC capture functions - ************************************************/ -ALC_API ALCdevice* ALC_APIENTRY alcCaptureOpenDevice(const ALCchar *deviceName, ALCuint frequency, ALCenum format, ALCsizei samples) -START_API_FUNC -{ - DO_INITCONFIG(); - - if(!CaptureFactory) - { - alcSetError(nullptr, ALC_INVALID_VALUE); - return nullptr; - } - - if(samples <= 0) - { - alcSetError(nullptr, ALC_INVALID_VALUE); - return nullptr; - } - - if(deviceName) - { - if(!deviceName[0] || al::strcasecmp(deviceName, alcDefaultName) == 0 - || al::strcasecmp(deviceName, "openal-soft") == 0) - deviceName = nullptr; - } - - DeviceRef device{new ALCdevice{DeviceType::Capture}}; - - auto decompfmt = DecomposeDevFormat(format); - if(!decompfmt) - { - alcSetError(nullptr, ALC_INVALID_ENUM); - return nullptr; - } - - device->Frequency = frequency; - device->FmtChans = decompfmt->chans; - device->FmtType = decompfmt->type; - device->Flags.set(FrequencyRequest); - device->Flags.set(ChannelsRequest); - device->Flags.set(SampleTypeRequest); - - device->UpdateSize = static_cast(samples); - device->BufferSize = static_cast(samples); - - try { - TRACE("Capture format: %s, %s, %uhz, %u / %u buffer\n", - DevFmtChannelsString(device->FmtChans), DevFmtTypeString(device->FmtType), - device->Frequency, device->UpdateSize, device->BufferSize); - - auto backend = CaptureFactory->createBackend(device.get(), BackendType::Capture); - std::lock_guard _{ListLock}; - backend->open(deviceName); - device->Backend = std::move(backend); - } - catch(al::backend_exception &e) { - WARN("Failed to open capture device: %s\n", e.what()); - alcSetError(nullptr, (e.errorCode() == al::backend_error::OutOfMemory) - ? ALC_OUT_OF_MEMORY : ALC_INVALID_VALUE); - return nullptr; - } - - { - std::lock_guard _{ListLock}; - auto iter = std::lower_bound(DeviceList.cbegin(), DeviceList.cend(), device.get()); - DeviceList.emplace(iter, device.get()); - } - - TRACE("Created capture device %p, \"%s\"\n", voidp{device.get()}, device->DeviceName.c_str()); - return device.release(); -} -END_API_FUNC - -ALC_API ALCboolean ALC_APIENTRY alcCaptureCloseDevice(ALCdevice *device) -START_API_FUNC -{ - std::unique_lock listlock{ListLock}; - auto iter = std::lower_bound(DeviceList.begin(), DeviceList.end(), device); - if(iter == DeviceList.end() || *iter != device) - { - alcSetError(nullptr, ALC_INVALID_DEVICE); - return ALC_FALSE; - } - if((*iter)->Type != DeviceType::Capture) - { - alcSetError(*iter, ALC_INVALID_DEVICE); - return ALC_FALSE; - } - - DeviceRef dev{*iter}; - DeviceList.erase(iter); - listlock.unlock(); - - std::lock_guard _{dev->StateLock}; - if(dev->Flags.test(DeviceRunning)) - dev->Backend->stop(); - dev->Flags.reset(DeviceRunning); - - return ALC_TRUE; -} -END_API_FUNC - -ALC_API void ALC_APIENTRY alcCaptureStart(ALCdevice *device) -START_API_FUNC -{ - DeviceRef dev{VerifyDevice(device)}; - if(!dev || dev->Type != DeviceType::Capture) - { - alcSetError(dev.get(), ALC_INVALID_DEVICE); - return; - } - - std::lock_guard _{dev->StateLock}; - if(!dev->Connected.load(std::memory_order_acquire)) - alcSetError(dev.get(), ALC_INVALID_DEVICE); - else if(!dev->Flags.test(DeviceRunning)) - { - try { - auto backend = dev->Backend.get(); - backend->start(); - dev->Flags.set(DeviceRunning); - } - catch(al::backend_exception& e) { - dev->handleDisconnect("%s", e.what()); - alcSetError(dev.get(), ALC_INVALID_DEVICE); - } - } -} -END_API_FUNC - -ALC_API void ALC_APIENTRY alcCaptureStop(ALCdevice *device) -START_API_FUNC -{ - DeviceRef dev{VerifyDevice(device)}; - if(!dev || dev->Type != DeviceType::Capture) - alcSetError(dev.get(), ALC_INVALID_DEVICE); - else - { - std::lock_guard _{dev->StateLock}; - if(dev->Flags.test(DeviceRunning)) - dev->Backend->stop(); - dev->Flags.reset(DeviceRunning); - } -} -END_API_FUNC - -ALC_API void ALC_APIENTRY alcCaptureSamples(ALCdevice *device, ALCvoid *buffer, ALCsizei samples) -START_API_FUNC -{ - DeviceRef dev{VerifyDevice(device)}; - if(!dev || dev->Type != DeviceType::Capture) - { - alcSetError(dev.get(), ALC_INVALID_DEVICE); - return; - } - - if(samples < 0 || (samples > 0 && buffer == nullptr)) - { - alcSetError(dev.get(), ALC_INVALID_VALUE); - return; - } - if(samples < 1) - return; - - std::lock_guard _{dev->StateLock}; - BackendBase *backend{dev->Backend.get()}; - - const auto usamples = static_cast(samples); - if(usamples > backend->availableSamples()) - { - alcSetError(dev.get(), ALC_INVALID_VALUE); - return; - } - - backend->captureSamples(static_cast(buffer), usamples); -} -END_API_FUNC - - -/************************************************ - * ALC loopback functions - ************************************************/ - -/** Open a loopback device, for manual rendering. */ -ALC_API ALCdevice* ALC_APIENTRY alcLoopbackOpenDeviceSOFT(const ALCchar *deviceName) -START_API_FUNC -{ - DO_INITCONFIG(); - - /* Make sure the device name, if specified, is us. */ - if(deviceName && strcmp(deviceName, alcDefaultName) != 0) - { - alcSetError(nullptr, ALC_INVALID_VALUE); - return nullptr; - } - - DeviceRef device{new ALCdevice{DeviceType::Loopback}}; - - device->SourcesMax = 256; - device->AuxiliaryEffectSlotMax = 64; - device->NumAuxSends = DEFAULT_SENDS; - - //Set output format - device->BufferSize = 0; - device->UpdateSize = 0; - - device->Frequency = DEFAULT_OUTPUT_RATE; - device->FmtChans = DevFmtChannelsDefault; - device->FmtType = DevFmtTypeDefault; - - if(auto srcsmax = ConfigValueUInt(nullptr, nullptr, "sources").value_or(0)) - device->SourcesMax = srcsmax; - - if(auto slotsmax = ConfigValueUInt(nullptr, nullptr, "slots").value_or(0)) - device->AuxiliaryEffectSlotMax = minu(slotsmax, INT_MAX); - - if(auto sendsopt = ConfigValueInt(nullptr, nullptr, "sends")) - device->NumAuxSends = minu(DEFAULT_SENDS, - static_cast(clampi(*sendsopt, 0, MAX_SENDS))); - - device->NumStereoSources = 1; - device->NumMonoSources = device->SourcesMax - device->NumStereoSources; - - try { - auto backend = LoopbackBackendFactory::getFactory().createBackend(device.get(), - BackendType::Playback); - backend->open("Loopback"); - device->Backend = std::move(backend); - } - catch(al::backend_exception &e) { - WARN("Failed to open loopback device: %s\n", e.what()); - alcSetError(nullptr, (e.errorCode() == al::backend_error::OutOfMemory) - ? ALC_OUT_OF_MEMORY : ALC_INVALID_VALUE); - return nullptr; - } - - { - std::lock_guard _{ListLock}; - auto iter = std::lower_bound(DeviceList.cbegin(), DeviceList.cend(), device.get()); - DeviceList.emplace(iter, device.get()); - } - - TRACE("Created loopback device %p\n", voidp{device.get()}); - return device.release(); -} -END_API_FUNC - -/** - * Determines if the loopback device supports the given format for rendering. - */ -ALC_API ALCboolean ALC_APIENTRY alcIsRenderFormatSupportedSOFT(ALCdevice *device, ALCsizei freq, ALCenum channels, ALCenum type) -START_API_FUNC -{ - DeviceRef dev{VerifyDevice(device)}; - if(!dev || dev->Type != DeviceType::Loopback) - alcSetError(dev.get(), ALC_INVALID_DEVICE); - else if(freq <= 0) - alcSetError(dev.get(), ALC_INVALID_VALUE); - else - { - if(DevFmtTypeFromEnum(type).has_value() && DevFmtChannelsFromEnum(channels).has_value() - && freq >= MIN_OUTPUT_RATE && freq <= MAX_OUTPUT_RATE) - return ALC_TRUE; - } - - return ALC_FALSE; -} -END_API_FUNC - -/** - * Renders some samples into a buffer, using the format last set by the - * attributes given to alcCreateContext. - */ -FORCE_ALIGN ALC_API void ALC_APIENTRY alcRenderSamplesSOFT(ALCdevice *device, ALCvoid *buffer, ALCsizei samples) -START_API_FUNC -{ - DeviceRef dev{VerifyDevice(device)}; - if(!dev || dev->Type != DeviceType::Loopback) - alcSetError(dev.get(), ALC_INVALID_DEVICE); - else if(samples < 0 || (samples > 0 && buffer == nullptr)) - alcSetError(dev.get(), ALC_INVALID_VALUE); - else - dev->renderSamples(buffer, static_cast(samples), dev->channelsFromFmt()); -} -END_API_FUNC - - -/************************************************ - * ALC DSP pause/resume functions - ************************************************/ - -/** Pause the DSP to stop audio processing. */ -ALC_API void ALC_APIENTRY alcDevicePauseSOFT(ALCdevice *device) -START_API_FUNC -{ - DeviceRef dev{VerifyDevice(device)}; - if(!dev || dev->Type != DeviceType::Playback) - alcSetError(dev.get(), ALC_INVALID_DEVICE); - else - { - std::lock_guard _{dev->StateLock}; - if(dev->Flags.test(DeviceRunning)) - dev->Backend->stop(); - dev->Flags.reset(DeviceRunning); - dev->Flags.set(DevicePaused); - } -} -END_API_FUNC - -/** Resume the DSP to restart audio processing. */ -ALC_API void ALC_APIENTRY alcDeviceResumeSOFT(ALCdevice *device) -START_API_FUNC -{ - DeviceRef dev{VerifyDevice(device)}; - if(!dev || dev->Type != DeviceType::Playback) - { - alcSetError(dev.get(), ALC_INVALID_DEVICE); - return; - } - - std::lock_guard _{dev->StateLock}; - if(!dev->Flags.test(DevicePaused)) - return; - dev->Flags.reset(DevicePaused); - if(dev->mContexts.load()->empty()) - return; - - try { - auto backend = dev->Backend.get(); - backend->start(); - dev->Flags.set(DeviceRunning); - } - catch(al::backend_exception& e) { - dev->handleDisconnect("%s", e.what()); - alcSetError(dev.get(), ALC_INVALID_DEVICE); - } -} -END_API_FUNC - - -/************************************************ - * ALC HRTF functions - ************************************************/ - -/** Gets a string parameter at the given index. */ -ALC_API const ALCchar* ALC_APIENTRY alcGetStringiSOFT(ALCdevice *device, ALCenum paramName, ALCsizei index) -START_API_FUNC -{ - DeviceRef dev{VerifyDevice(device)}; - if(!dev || dev->Type == DeviceType::Capture) - alcSetError(dev.get(), ALC_INVALID_DEVICE); - else switch(paramName) - { - case ALC_HRTF_SPECIFIER_SOFT: - if(index >= 0 && static_cast(index) < dev->HrtfList.size()) - return dev->HrtfList[static_cast(index)].c_str(); - alcSetError(dev.get(), ALC_INVALID_VALUE); - break; - - default: - alcSetError(dev.get(), ALC_INVALID_ENUM); - break; - } - - return nullptr; -} -END_API_FUNC - -/** Resets the given device output, using the specified attribute list. */ -ALC_API ALCboolean ALC_APIENTRY alcResetDeviceSOFT(ALCdevice *device, const ALCint *attribs) -START_API_FUNC -{ - std::unique_lock listlock{ListLock}; - DeviceRef dev{VerifyDevice(device)}; - if(!dev || dev->Type == DeviceType::Capture) - { - listlock.unlock(); - alcSetError(dev.get(), ALC_INVALID_DEVICE); - return ALC_FALSE; - } - std::lock_guard _{dev->StateLock}; - listlock.unlock(); - - /* Force the backend to stop mixing first since we're resetting. Also reset - * the connected state so lost devices can attempt recover. - */ - if(dev->Flags.test(DeviceRunning)) - dev->Backend->stop(); - dev->Flags.reset(DeviceRunning); - if(!dev->Connected.load(std::memory_order_relaxed)) - { - /* Make sure disconnection is finished before continuing on. */ - dev->waitForMix(); - - for(ALCcontext *ctx : *dev->mContexts.load(std::memory_order_acquire)) - { - /* Clear any pending voice changes and reallocate voices to get a - * clean restart. - */ - std::lock_guard __{ctx->mSourceLock}; - auto *vchg = ctx->mCurrentVoiceChange.load(std::memory_order_acquire); - while(auto *next = vchg->mNext.load(std::memory_order_acquire)) - vchg = next; - ctx->mCurrentVoiceChange.store(vchg, std::memory_order_release); - - ctx->mVoiceClusters.clear(); - ctx->allocVoices(std::max(256, - ctx->mActiveVoiceCount.load(std::memory_order_relaxed))); - } - - dev->Connected.store(true); - } - - ALCenum err{UpdateDeviceParams(dev.get(), attribs)}; - if LIKELY(err == ALC_NO_ERROR) return ALC_TRUE; - - alcSetError(dev.get(), err); - return ALC_FALSE; -} -END_API_FUNC diff --git a/alc/alcmain.h b/alc/alcmain.h deleted file mode 100644 index e9309c40..00000000 --- a/alc/alcmain.h +++ /dev/null @@ -1,371 +0,0 @@ -#ifndef ALC_MAIN_H -#define ALC_MAIN_H - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "AL/al.h" -#include "AL/alc.h" -#include "AL/alext.h" - -#include "almalloc.h" -#include "alnumeric.h" -#include "alspan.h" -#include "atomic.h" -#include "core/ambidefs.h" -#include "core/bufferline.h" -#include "core/devformat.h" -#include "core/filters/splitter.h" -#include "core/mixer/defs.h" -#include "hrtf.h" -#include "inprogext.h" -#include "intrusive_ptr.h" -#include "vector.h" - -class BFormatDec; -struct ALbuffer; -struct ALeffect; -struct ALfilter; -struct BackendBase; -struct Compressor; -struct EffectState; -struct Uhj2Encoder; -struct bs2b; - -using uint = unsigned int; - - -#define MIN_OUTPUT_RATE 8000 -#define MAX_OUTPUT_RATE 192000 -#define DEFAULT_OUTPUT_RATE 44100 - -#define DEFAULT_UPDATE_SIZE 882 /* 20ms */ -#define DEFAULT_NUM_UPDATES 3 - - -enum class DeviceType : unsigned char { - Playback, - Capture, - Loopback -}; - - -enum class RenderMode : unsigned char { - Normal, - Pairwise, - Hrtf -}; - - -struct InputRemixMap { - struct TargetMix { Channel channel; float mix; }; - - Channel channel; - std::array targets; -}; - - -struct BufferSubList { - uint64_t FreeMask{~0_u64}; - ALbuffer *Buffers{nullptr}; /* 64 */ - - BufferSubList() noexcept = default; - BufferSubList(const BufferSubList&) = delete; - BufferSubList(BufferSubList&& rhs) noexcept : FreeMask{rhs.FreeMask}, Buffers{rhs.Buffers} - { rhs.FreeMask = ~0_u64; rhs.Buffers = nullptr; } - ~BufferSubList(); - - BufferSubList& operator=(const BufferSubList&) = delete; - BufferSubList& operator=(BufferSubList&& rhs) noexcept - { std::swap(FreeMask, rhs.FreeMask); std::swap(Buffers, rhs.Buffers); return *this; } -}; - -struct EffectSubList { - uint64_t FreeMask{~0_u64}; - ALeffect *Effects{nullptr}; /* 64 */ - - EffectSubList() noexcept = default; - EffectSubList(const EffectSubList&) = delete; - EffectSubList(EffectSubList&& rhs) noexcept : FreeMask{rhs.FreeMask}, Effects{rhs.Effects} - { rhs.FreeMask = ~0_u64; rhs.Effects = nullptr; } - ~EffectSubList(); - - EffectSubList& operator=(const EffectSubList&) = delete; - EffectSubList& operator=(EffectSubList&& rhs) noexcept - { std::swap(FreeMask, rhs.FreeMask); std::swap(Effects, rhs.Effects); return *this; } -}; - -struct FilterSubList { - uint64_t FreeMask{~0_u64}; - ALfilter *Filters{nullptr}; /* 64 */ - - FilterSubList() noexcept = default; - FilterSubList(const FilterSubList&) = delete; - FilterSubList(FilterSubList&& rhs) noexcept : FreeMask{rhs.FreeMask}, Filters{rhs.Filters} - { rhs.FreeMask = ~0_u64; rhs.Filters = nullptr; } - ~FilterSubList(); - - FilterSubList& operator=(const FilterSubList&) = delete; - FilterSubList& operator=(FilterSubList&& rhs) noexcept - { std::swap(FreeMask, rhs.FreeMask); std::swap(Filters, rhs.Filters); return *this; } -}; - - -/* Maximum delay in samples for speaker distance compensation. */ -#define MAX_DELAY_LENGTH 1024 - -struct DistanceComp { - struct ChanData { - float Gain{1.0f}; - uint Length{0u}; /* Valid range is [0...MAX_DELAY_LENGTH). */ - float *Buffer{nullptr}; - }; - - std::array mChannels; - al::FlexArray mSamples; - - DistanceComp(size_t count) : mSamples{count} { } - - static std::unique_ptr Create(size_t numsamples) - { return std::unique_ptr{new(FamCount(numsamples)) DistanceComp{numsamples}}; } - - DEF_FAM_NEWDEL(DistanceComp, mSamples) -}; - - -struct BFChannelConfig { - float Scale; - uint Index; -}; - - -struct MixParams { - /* Coefficient channel mapping for mixing to the buffer. */ - std::array AmbiMap{}; - - al::span Buffer; -}; - -struct RealMixParams { - al::span RemixMap; - std::array ChannelIndex{}; - - al::span Buffer; -}; - -enum { - // Frequency was requested by the app or config file - FrequencyRequest, - // Channel configuration was requested by the config file - ChannelsRequest, - // Sample type was requested by the config file - SampleTypeRequest, - - // Specifies if the DSP is paused at user request - DevicePaused, - // Specifies if the device is currently running - DeviceRunning, - - DeviceFlagsCount -}; - -struct ALCdevice : public al::intrusive_ref { - std::atomic Connected{true}; - const DeviceType Type{}; - - uint Frequency{}; - uint UpdateSize{}; - uint BufferSize{}; - - DevFmtChannels FmtChans{}; - DevFmtType FmtType{}; - bool IsHeadphones{false}; - uint mAmbiOrder{0}; - float mXOverFreq{400.0f}; - /* For DevFmtAmbi* output only, specifies the channel order and - * normalization. - */ - DevAmbiLayout mAmbiLayout{DevAmbiLayout::Default}; - DevAmbiScaling mAmbiScale{DevAmbiScaling::Default}; - - std::string DeviceName; - - // Device flags - std::bitset Flags{}; - - // Maximum number of sources that can be created - uint SourcesMax{}; - // Maximum number of slots that can be created - uint AuxiliaryEffectSlotMax{}; - - /* Rendering mode. */ - RenderMode mRenderMode{RenderMode::Normal}; - - /* The average speaker distance as determined by the ambdec configuration, - * HRTF data set, or the NFC-HOA reference delay. Only used for NFC. - */ - float AvgSpeakerDist{0.0f}; - - uint SamplesDone{0u}; - std::chrono::nanoseconds ClockBase{0}; - std::chrono::nanoseconds FixedLatency{0}; - - /* Temp storage used for mixer processing. */ - alignas(16) float SourceData[BufferLineSize + MaxResamplerPadding]; - alignas(16) float ResampledData[BufferLineSize]; - alignas(16) float FilteredData[BufferLineSize]; - union { - alignas(16) float HrtfSourceData[BufferLineSize + HrtfHistoryLength]; - alignas(16) float NfcSampleData[BufferLineSize]; - }; - - /* Persistent storage for HRTF mixing. */ - alignas(16) float2 HrtfAccumData[BufferLineSize + HrirLength + HrtfDirectDelay]; - - /* Mixing buffer used by the Dry mix and Real output. */ - al::vector MixBuffer; - - /* The "dry" path corresponds to the main output. */ - MixParams Dry; - uint NumChannelsPerOrder[MaxAmbiOrder+1]{}; - - /* "Real" output, which will be written to the device buffer. May alias the - * dry buffer. - */ - RealMixParams RealOut; - - /* HRTF state and info */ - std::unique_ptr mHrtfState; - al::intrusive_ptr mHrtf; - uint mIrSize{0}; - - /* Ambisonic-to-UHJ encoder */ - std::unique_ptr Uhj_Encoder; - - /* Ambisonic decoder for speakers */ - std::unique_ptr AmbiDecoder; - - /* Stereo-to-binaural filter */ - std::unique_ptr Bs2b; - - using PostProc = void(ALCdevice::*)(const size_t SamplesToDo); - PostProc PostProcess{nullptr}; - - std::unique_ptr Limiter; - - /* Delay buffers used to compensate for speaker distances. */ - std::unique_ptr ChannelDelays; - - /* Dithering control. */ - float DitherDepth{0.0f}; - uint DitherSeed{0u}; - - /* Running count of the mixer invocations, in 31.1 fixed point. This - * actually increments *twice* when mixing, first at the start and then at - * the end, so the bottom bit indicates if the device is currently mixing - * and the upper bits indicates how many mixes have been done. - */ - RefCount MixCount{0u}; - - // Contexts created on this device - std::atomic*> mContexts{nullptr}; - - /* This lock protects the device state (format, update size, etc) from - * being from being changed in multiple threads, or being accessed while - * being changed. It's also used to serialize calls to the backend. - */ - std::mutex StateLock; - std::unique_ptr Backend; - - - ALCuint NumMonoSources{}; - ALCuint NumStereoSources{}; - ALCuint NumAuxSends{}; - - std::string HrtfName; - al::vector HrtfList; - ALCenum HrtfStatus{ALC_FALSE}; - - ALCenum LimiterState{ALC_DONT_CARE_SOFT}; - - std::atomic LastError{ALC_NO_ERROR}; - - // Map of Buffers for this device - std::mutex BufferLock; - al::vector BufferList; - - // Map of Effects for this device - std::mutex EffectLock; - al::vector EffectList; - - // Map of Filters for this device - std::mutex FilterLock; - al::vector FilterList; - - - ALCdevice(DeviceType type); - ALCdevice(const ALCdevice&) = delete; - ALCdevice& operator=(const ALCdevice&) = delete; - ~ALCdevice(); - - uint bytesFromFmt() const noexcept { return BytesFromDevFmt(FmtType); } - uint channelsFromFmt() const noexcept { return ChannelsFromDevFmt(FmtChans, mAmbiOrder); } - uint frameSizeFromFmt() const noexcept { return bytesFromFmt() * channelsFromFmt(); } - - uint waitForMix() const noexcept - { - uint refcount; - while((refcount=MixCount.load(std::memory_order_acquire))&1) { - } - return refcount; - } - - void ProcessHrtf(const size_t SamplesToDo); - void ProcessAmbiDec(const size_t SamplesToDo); - void ProcessAmbiDecStablized(const size_t SamplesToDo); - void ProcessUhj(const size_t SamplesToDo); - void ProcessBs2b(const size_t SamplesToDo); - - inline void postProcess(const size_t SamplesToDo) - { if LIKELY(PostProcess) (this->*PostProcess)(SamplesToDo); } - - void renderSamples(void *outBuffer, const uint numSamples, const size_t frameStep); - - /* Caller must lock the device state, and the mixer must not be running. */ - [[gnu::format(printf,2,3)]] void handleDisconnect(const char *msg, ...); - - DEF_NEWDEL(ALCdevice) -}; - -/* Must be less than 15 characters (16 including terminating null) for - * compatibility with pthread_setname_np limitations. */ -#define MIXER_THREAD_NAME "alsoft-mixer" - -#define RECORD_THREAD_NAME "alsoft-record" - - -extern int RTPrioLevel; -void SetRTPriority(void); - -/** - * Returns the index for the given channel name (e.g. FrontCenter), or - * INVALID_CHANNEL_INDEX if it doesn't exist. - */ -inline uint GetChannelIdxByName(const RealMixParams &real, Channel chan) noexcept -{ return real.ChannelIndex[chan]; } -#define INVALID_CHANNEL_INDEX ~0u - - -al::vector SearchDataFiles(const char *match, const char *subdir); - -#endif diff --git a/alc/alconfig.cpp b/alc/alconfig.cpp deleted file mode 100644 index 634679aa..00000000 --- a/alc/alconfig.cpp +++ /dev/null @@ -1,542 +0,0 @@ -/** - * OpenAL cross platform audio library - * Copyright (C) 1999-2007 by authors. - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - * Or go to http://www.gnu.org/copyleft/lgpl.html - */ - -#include "config.h" - -#include "alconfig.h" - -#include -#include -#include -#ifdef _WIN32 -#include -#include -#endif -#ifdef __APPLE__ -#include -#endif - -#include -#include -#include -#include - -#include "alfstream.h" -#include "alstring.h" -#include "compat.h" -#include "core/logging.h" -#include "strutils.h" -#include "vector.h" - - -namespace { - -struct ConfigEntry { - std::string key; - std::string value; -}; -al::vector ConfOpts; - - -std::string &lstrip(std::string &line) -{ - size_t pos{0}; - while(pos < line.length() && std::isspace(line[pos])) - ++pos; - line.erase(0, pos); - return line; -} - -bool readline(std::istream &f, std::string &output) -{ - while(f.good() && f.peek() == '\n') - f.ignore(); - - return std::getline(f, output) && !output.empty(); -} - -std::string expdup(const char *str) -{ - std::string output; - - std::string envval; - while(*str != '\0') - { - const char *addstr; - size_t addstrlen; - - if(str[0] != '$') - { - const char *next = std::strchr(str, '$'); - addstr = str; - addstrlen = next ? static_cast(next-str) : std::strlen(str); - - str += addstrlen; - } - else - { - str++; - if(*str == '$') - { - const char *next = std::strchr(str+1, '$'); - addstr = str; - addstrlen = next ? static_cast(next-str) : std::strlen(str); - - str += addstrlen; - } - else - { - const bool hasbraces{(*str == '{')}; - - if(hasbraces) str++; - const char *envstart = str; - while(std::isalnum(*str) || *str == '_') - ++str; - if(hasbraces && *str != '}') - continue; - const std::string envname{envstart, str}; - if(hasbraces) str++; - - envval = al::getenv(envname.c_str()).value_or(std::string{}); - addstr = envval.data(); - addstrlen = envval.length(); - } - } - if(addstrlen == 0) - continue; - - output.append(addstr, addstrlen); - } - - return output; -} - -void LoadConfigFromFile(std::istream &f) -{ - std::string curSection; - std::string buffer; - - while(readline(f, buffer)) - { - if(lstrip(buffer).empty()) - continue; - - if(buffer[0] == '[') - { - char *line{&buffer[0]}; - char *section = line+1; - char *endsection; - - endsection = std::strchr(section, ']'); - if(!endsection || section == endsection) - { - ERR(" config parse error: bad line \"%s\"\n", line); - continue; - } - if(endsection[1] != 0) - { - char *end = endsection+1; - while(std::isspace(*end)) - ++end; - if(*end != 0 && *end != '#') - { - ERR(" config parse error: bad line \"%s\"\n", line); - continue; - } - } - *endsection = 0; - - curSection.clear(); - if(al::strcasecmp(section, "general") != 0) - { - do { - char *nextp = std::strchr(section, '%'); - if(!nextp) - { - curSection += section; - break; - } - - curSection.append(section, nextp); - section = nextp; - - if(((section[1] >= '0' && section[1] <= '9') || - (section[1] >= 'a' && section[1] <= 'f') || - (section[1] >= 'A' && section[1] <= 'F')) && - ((section[2] >= '0' && section[2] <= '9') || - (section[2] >= 'a' && section[2] <= 'f') || - (section[2] >= 'A' && section[2] <= 'F'))) - { - int b{0}; - if(section[1] >= '0' && section[1] <= '9') - b = (section[1]-'0') << 4; - else if(section[1] >= 'a' && section[1] <= 'f') - b = (section[1]-'a'+0xa) << 4; - else if(section[1] >= 'A' && section[1] <= 'F') - b = (section[1]-'A'+0x0a) << 4; - if(section[2] >= '0' && section[2] <= '9') - b |= (section[2]-'0'); - else if(section[2] >= 'a' && section[2] <= 'f') - b |= (section[2]-'a'+0xa); - else if(section[2] >= 'A' && section[2] <= 'F') - b |= (section[2]-'A'+0x0a); - curSection += static_cast(b); - section += 3; - } - else if(section[1] == '%') - { - curSection += '%'; - section += 2; - } - else - { - curSection += '%'; - section += 1; - } - } while(*section != 0); - } - - continue; - } - - auto cmtpos = std::min(buffer.find('#'), buffer.size()); - while(cmtpos > 0 && std::isspace(buffer[cmtpos-1])) - --cmtpos; - if(!cmtpos) continue; - buffer.erase(cmtpos); - - auto sep = buffer.find('='); - if(sep == std::string::npos) - { - ERR(" config parse error: malformed option line: \"%s\"\n", buffer.c_str()); - continue; - } - auto keyend = sep++; - while(keyend > 0 && std::isspace(buffer[keyend-1])) - --keyend; - if(!keyend) - { - ERR(" config parse error: malformed option line: \"%s\"\n", buffer.c_str()); - continue; - } - while(sep < buffer.size() && std::isspace(buffer[sep])) - sep++; - - std::string fullKey; - if(!curSection.empty()) - { - fullKey += curSection; - fullKey += '/'; - } - fullKey += buffer.substr(0u, keyend); - - std::string value{(sep < buffer.size()) ? buffer.substr(sep) : std::string{}}; - if(value.size() > 1) - { - if((value.front() == '"' && value.back() == '"') - || (value.front() == '\'' && value.back() == '\'')) - { - value.pop_back(); - value.erase(value.begin()); - } - } - - TRACE(" found '%s' = '%s'\n", fullKey.c_str(), value.c_str()); - - /* Check if we already have this option set */ - auto find_key = [&fullKey](const ConfigEntry &entry) -> bool - { return entry.key == fullKey; }; - auto ent = std::find_if(ConfOpts.begin(), ConfOpts.end(), find_key); - if(ent != ConfOpts.end()) - { - if(!value.empty()) - ent->value = expdup(value.c_str()); - else - ConfOpts.erase(ent); - } - else if(!value.empty()) - ConfOpts.emplace_back(ConfigEntry{std::move(fullKey), expdup(value.c_str())}); - } - ConfOpts.shrink_to_fit(); -} - -} // namespace - - -#ifdef _WIN32 -void ReadALConfig() -{ - WCHAR buffer[MAX_PATH]; - if(SHGetSpecialFolderPathW(nullptr, buffer, CSIDL_APPDATA, FALSE) != FALSE) - { - std::string filepath{wstr_to_utf8(buffer)}; - filepath += "\\alsoft.ini"; - - TRACE("Loading config %s...\n", filepath.c_str()); - al::ifstream f{filepath}; - if(f.is_open()) - LoadConfigFromFile(f); - } - - std::string ppath{GetProcBinary().path}; - if(!ppath.empty()) - { - ppath += "\\alsoft.ini"; - TRACE("Loading config %s...\n", ppath.c_str()); - al::ifstream f{ppath}; - if(f.is_open()) - LoadConfigFromFile(f); - } - - if(auto confpath = al::getenv(L"ALSOFT_CONF")) - { - TRACE("Loading config %s...\n", wstr_to_utf8(confpath->c_str()).c_str()); - al::ifstream f{*confpath}; - if(f.is_open()) - LoadConfigFromFile(f); - } -} - -#else - -void ReadALConfig() -{ - const char *str{"/etc/openal/alsoft.conf"}; - - TRACE("Loading config %s...\n", str); - al::ifstream f{str}; - if(f.is_open()) - LoadConfigFromFile(f); - f.close(); - - std::string confpaths{al::getenv("XDG_CONFIG_DIRS").value_or("/etc/xdg")}; - /* Go through the list in reverse, since "the order of base directories - * denotes their importance; the first directory listed is the most - * important". Ergo, we need to load the settings from the later dirs - * first so that the settings in the earlier dirs override them. - */ - std::string fname; - while(!confpaths.empty()) - { - auto next = confpaths.find_last_of(':'); - if(next < confpaths.length()) - { - fname = confpaths.substr(next+1); - confpaths.erase(next); - } - else - { - fname = confpaths; - confpaths.clear(); - } - - if(fname.empty() || fname.front() != '/') - WARN("Ignoring XDG config dir: %s\n", fname.c_str()); - else - { - if(fname.back() != '/') fname += "/alsoft.conf"; - else fname += "alsoft.conf"; - - TRACE("Loading config %s...\n", fname.c_str()); - f = al::ifstream{fname}; - if(f.is_open()) - LoadConfigFromFile(f); - } - fname.clear(); - } - -#ifdef __APPLE__ - CFBundleRef mainBundle = CFBundleGetMainBundle(); - if(mainBundle) - { - unsigned char fileName[PATH_MAX]; - CFURLRef configURL; - - if((configURL=CFBundleCopyResourceURL(mainBundle, CFSTR(".alsoftrc"), CFSTR(""), nullptr)) && - CFURLGetFileSystemRepresentation(configURL, true, fileName, sizeof(fileName))) - { - f = al::ifstream{reinterpret_cast(fileName)}; - if(f.is_open()) - LoadConfigFromFile(f); - } - } -#endif - - if(auto homedir = al::getenv("HOME")) - { - fname = *homedir; - if(fname.back() != '/') fname += "/.alsoftrc"; - else fname += ".alsoftrc"; - - TRACE("Loading config %s...\n", fname.c_str()); - f = al::ifstream{fname}; - if(f.is_open()) - LoadConfigFromFile(f); - } - - if(auto configdir = al::getenv("XDG_CONFIG_HOME")) - { - fname = *configdir; - if(fname.back() != '/') fname += "/alsoft.conf"; - else fname += "alsoft.conf"; - } - else - { - fname.clear(); - if(auto homedir = al::getenv("HOME")) - { - fname = *homedir; - if(fname.back() != '/') fname += "/.config/alsoft.conf"; - else fname += ".config/alsoft.conf"; - } - } - if(!fname.empty()) - { - TRACE("Loading config %s...\n", fname.c_str()); - f = al::ifstream{fname}; - if(f.is_open()) - LoadConfigFromFile(f); - } - - std::string ppath{GetProcBinary().path}; - if(!ppath.empty()) - { - if(ppath.back() != '/') ppath += "/alsoft.conf"; - else ppath += "alsoft.conf"; - - TRACE("Loading config %s...\n", ppath.c_str()); - f = al::ifstream{ppath}; - if(f.is_open()) - LoadConfigFromFile(f); - } - - if(auto confname = al::getenv("ALSOFT_CONF")) - { - TRACE("Loading config %s...\n", confname->c_str()); - f = al::ifstream{*confname}; - if(f.is_open()) - LoadConfigFromFile(f); - } -} -#endif - -const char *GetConfigValue(const char *devName, const char *blockName, const char *keyName, const char *def) -{ - if(!keyName) - return def; - - std::string key; - if(blockName && al::strcasecmp(blockName, "general") != 0) - { - key = blockName; - if(devName) - { - key += '/'; - key += devName; - } - key += '/'; - key += keyName; - } - else - { - if(devName) - { - key = devName; - key += '/'; - } - key += keyName; - } - - auto iter = std::find_if(ConfOpts.cbegin(), ConfOpts.cend(), - [&key](const ConfigEntry &entry) -> bool - { return entry.key == key; } - ); - if(iter != ConfOpts.cend()) - { - TRACE("Found %s = \"%s\"\n", key.c_str(), iter->value.c_str()); - if(!iter->value.empty()) - return iter->value.c_str(); - return def; - } - - if(!devName) - { - TRACE("Key %s not found\n", key.c_str()); - return def; - } - return GetConfigValue(nullptr, blockName, keyName, def); -} - -int ConfigValueExists(const char *devName, const char *blockName, const char *keyName) -{ - const char *val = GetConfigValue(devName, blockName, keyName, ""); - return val[0] != 0; -} - -al::optional ConfigValueStr(const char *devName, const char *blockName, const char *keyName) -{ - const char *val = GetConfigValue(devName, blockName, keyName, ""); - if(!val[0]) return al::nullopt; - - return al::make_optional(val); -} - -al::optional ConfigValueInt(const char *devName, const char *blockName, const char *keyName) -{ - const char *val = GetConfigValue(devName, blockName, keyName, ""); - if(!val[0]) return al::nullopt; - - return al::make_optional(static_cast(std::strtol(val, nullptr, 0))); -} - -al::optional ConfigValueUInt(const char *devName, const char *blockName, const char *keyName) -{ - const char *val = GetConfigValue(devName, blockName, keyName, ""); - if(!val[0]) return al::nullopt; - - return al::make_optional(static_cast(std::strtoul(val, nullptr, 0))); -} - -al::optional ConfigValueFloat(const char *devName, const char *blockName, const char *keyName) -{ - const char *val = GetConfigValue(devName, blockName, keyName, ""); - if(!val[0]) return al::nullopt; - - return al::make_optional(std::strtof(val, nullptr)); -} - -al::optional ConfigValueBool(const char *devName, const char *blockName, const char *keyName) -{ - const char *val = GetConfigValue(devName, blockName, keyName, ""); - if(!val[0]) return al::nullopt; - - return al::make_optional( - al::strcasecmp(val, "true") == 0 || al::strcasecmp(val, "yes") == 0 || - al::strcasecmp(val, "on") == 0 || atoi(val) != 0); -} - -int GetConfigValueBool(const char *devName, const char *blockName, const char *keyName, int def) -{ - const char *val = GetConfigValue(devName, blockName, keyName, ""); - - if(!val[0]) return def != 0; - return (al::strcasecmp(val, "true") == 0 || al::strcasecmp(val, "yes") == 0 || - al::strcasecmp(val, "on") == 0 || atoi(val) != 0); -} diff --git a/alc/alconfig.h b/alc/alconfig.h deleted file mode 100644 index ffc7adad..00000000 --- a/alc/alconfig.h +++ /dev/null @@ -1,20 +0,0 @@ -#ifndef ALCONFIG_H -#define ALCONFIG_H - -#include - -#include "aloptional.h" - -void ReadALConfig(); - -int ConfigValueExists(const char *devName, const char *blockName, const char *keyName); -const char *GetConfigValue(const char *devName, const char *blockName, const char *keyName, const char *def); -int GetConfigValueBool(const char *devName, const char *blockName, const char *keyName, int def); - -al::optional ConfigValueStr(const char *devName, const char *blockName, const char *keyName); -al::optional ConfigValueInt(const char *devName, const char *blockName, const char *keyName); -al::optional ConfigValueUInt(const char *devName, const char *blockName, const char *keyName); -al::optional ConfigValueFloat(const char *devName, const char *blockName, const char *keyName); -al::optional ConfigValueBool(const char *devName, const char *blockName, const char *keyName); - -#endif /* ALCONFIG_H */ diff --git a/alc/alcontext.h b/alc/alcontext.h deleted file mode 100644 index 31160bb2..00000000 --- a/alc/alcontext.h +++ /dev/null @@ -1,282 +0,0 @@ -#ifndef ALCONTEXT_H -#define ALCONTEXT_H - -#include -#include -#include -#include -#include -#include -#include -#include - -#include "AL/al.h" -#include "AL/alc.h" - -#include "al/listener.h" -#include "almalloc.h" -#include "alnumeric.h" -#include "alu.h" -#include "atomic.h" -#include "inprogext.h" -#include "intrusive_ptr.h" -#include "threads.h" -#include "vecmat.h" -#include "vector.h" - -struct ALeffectslot; -struct ALsource; -struct EffectSlot; -struct EffectSlotProps; -struct RingBuffer; -struct Voice; -struct VoiceChange; -struct VoicePropsItem; - - -enum class DistanceModel : unsigned char { - Disable, - Inverse, InverseClamped, - Linear, LinearClamped, - Exponent, ExponentClamped, - - Default = InverseClamped -}; - - -struct WetBuffer { - bool mInUse; - al::FlexArray mBuffer; - - WetBuffer(size_t count) : mBuffer{count} { } - - DEF_FAM_NEWDEL(WetBuffer, mBuffer) -}; -using WetBufferPtr = std::unique_ptr; - - -struct ContextProps { - float DopplerFactor; - float DopplerVelocity; - float SpeedOfSound; - bool SourceDistanceModel; - DistanceModel mDistanceModel; - - std::atomic next; - - DEF_NEWDEL(ContextProps) -}; - -struct ListenerProps { - std::array Position; - std::array Velocity; - std::array OrientAt; - std::array OrientUp; - float Gain; - float MetersPerUnit; - - std::atomic next; - - DEF_NEWDEL(ListenerProps) -}; - -struct ContextParams { - /* Pointer to the most recent property values that are awaiting an update. */ - std::atomic ContextUpdate{nullptr}; - std::atomic ListenerUpdate{nullptr}; - - alu::Matrix Matrix{alu::Matrix::Identity()}; - alu::Vector Velocity{}; - - float Gain{1.0f}; - float MetersPerUnit{1.0f}; - - float DopplerFactor{1.0f}; - float SpeedOfSound{343.3f}; /* in units per sec! */ - - bool SourceDistanceModel{false}; - DistanceModel mDistanceModel{}; -}; - - -struct SourceSubList { - uint64_t FreeMask{~0_u64}; - ALsource *Sources{nullptr}; /* 64 */ - - SourceSubList() noexcept = default; - SourceSubList(const SourceSubList&) = delete; - SourceSubList(SourceSubList&& rhs) noexcept : FreeMask{rhs.FreeMask}, Sources{rhs.Sources} - { rhs.FreeMask = ~0_u64; rhs.Sources = nullptr; } - ~SourceSubList(); - - SourceSubList& operator=(const SourceSubList&) = delete; - SourceSubList& operator=(SourceSubList&& rhs) noexcept - { std::swap(FreeMask, rhs.FreeMask); std::swap(Sources, rhs.Sources); return *this; } -}; - -struct EffectSlotSubList { - uint64_t FreeMask{~0_u64}; - ALeffectslot *EffectSlots{nullptr}; /* 64 */ - - EffectSlotSubList() noexcept = default; - EffectSlotSubList(const EffectSlotSubList&) = delete; - EffectSlotSubList(EffectSlotSubList&& rhs) noexcept - : FreeMask{rhs.FreeMask}, EffectSlots{rhs.EffectSlots} - { rhs.FreeMask = ~0_u64; rhs.EffectSlots = nullptr; } - ~EffectSlotSubList(); - - EffectSlotSubList& operator=(const EffectSlotSubList&) = delete; - EffectSlotSubList& operator=(EffectSlotSubList&& rhs) noexcept - { std::swap(FreeMask, rhs.FreeMask); std::swap(EffectSlots, rhs.EffectSlots); return *this; } -}; - -struct ALCcontext : public al::intrusive_ref { - const al::intrusive_ptr mDevice; - - /* Counter for the pre-mixing updates, in 31.1 fixed point (lowest bit - * indicates if updates are currently happening). - */ - RefCount mUpdateCount{0u}; - std::atomic mHoldUpdates{false}; - - float mGainBoost{1.0f}; - - /* Linked lists of unused property containers, free to use for future - * updates. - */ - std::atomic mFreeContextProps{nullptr}; - std::atomic mFreeListenerProps{nullptr}; - std::atomic mFreeVoiceProps{nullptr}; - std::atomic mFreeEffectslotProps{nullptr}; - - /* The voice change tail is the beginning of the "free" elements, up to and - * *excluding* the current. If tail==current, there's no free elements and - * new ones need to be allocated. The current voice change is the element - * last processed, and any after are pending. - */ - VoiceChange *mVoiceChangeTail{}; - std::atomic mCurrentVoiceChange{}; - - void allocVoiceChanges(size_t addcount); - - - ContextParams mParams; - - using VoiceArray = al::FlexArray; - std::atomic mVoices{}; - std::atomic mActiveVoiceCount{}; - - void allocVoices(size_t addcount); - al::span getVoicesSpan() const noexcept - { - return {mVoices.load(std::memory_order_relaxed)->data(), - mActiveVoiceCount.load(std::memory_order_relaxed)}; - } - al::span getVoicesSpanAcquired() const noexcept - { - return {mVoices.load(std::memory_order_acquire)->data(), - mActiveVoiceCount.load(std::memory_order_acquire)}; - } - - - using EffectSlotArray = al::FlexArray; - std::atomic mActiveAuxSlots{nullptr}; - - std::thread mEventThread; - al::semaphore mEventSem; - std::unique_ptr mAsyncEvents; - std::atomic mEnabledEvts{0u}; - - /* Asynchronous voice change actions are processed as a linked list of - * VoiceChange objects by the mixer, which is atomically appended to. - * However, to avoid allocating each object individually, they're allocated - * in clusters that are stored in a vector for easy automatic cleanup. - */ - using VoiceChangeCluster = std::unique_ptr; - al::vector mVoiceChangeClusters; - - using VoiceCluster = std::unique_ptr; - al::vector mVoiceClusters; - - /* Wet buffers used by effect slots. */ - al::vector mWetBuffers; - - - std::atomic_flag mPropsClean; - std::atomic mDeferUpdates{false}; - - std::mutex mPropLock; - - std::atomic mLastError{AL_NO_ERROR}; - - DistanceModel mDistanceModel{DistanceModel::Default}; - bool mSourceDistanceModel{false}; - - float mDopplerFactor{1.0f}; - float mDopplerVelocity{1.0f}; - float mSpeedOfSound{SpeedOfSoundMetersPerSec}; - - std::mutex mEventCbLock; - ALEVENTPROCSOFT mEventCb{}; - void *mEventParam{nullptr}; - - ALlistener mListener{}; - - al::vector mSourceList; - ALuint mNumSources{0}; - std::mutex mSourceLock; - - al::vector mEffectSlotList; - ALuint mNumEffectSlots{0u}; - std::mutex mEffectSlotLock; - - /* Default effect slot */ - std::unique_ptr mDefaultSlot; - - const char *mExtensionList{nullptr}; - - - ALCcontext(al::intrusive_ptr device); - ALCcontext(const ALCcontext&) = delete; - ALCcontext& operator=(const ALCcontext&) = delete; - ~ALCcontext(); - - void init(); - /** - * Removes the context from its device and removes it from being current on - * the running thread or globally. Returns true if other contexts still - * exist on the device. - */ - bool deinit(); - - /** - * Defers/suspends updates for the given context's listener and sources. - * This does *NOT* stop mixing, but rather prevents certain property - * changes from taking effect. - */ - void deferUpdates() noexcept { mDeferUpdates.exchange(true, std::memory_order_acq_rel); } - - /** Resumes update processing after being deferred. */ - void processUpdates(); - - [[gnu::format(printf,3,4)]] void setError(ALenum errorCode, const char *msg, ...); - - DEF_NEWDEL(ALCcontext) -}; - -#define SETERR_RETURN(ctx, err, retval, ...) do { \ - (ctx)->setError((err), __VA_ARGS__); \ - return retval; \ -} while(0) - - -using ContextRef = al::intrusive_ptr; - -ContextRef GetContextRef(void); - -void UpdateContextProps(ALCcontext *context); - - -extern bool TrapALError; - -#endif /* ALCONTEXT_H */ diff --git a/alc/alu.cpp b/alc/alu.cpp deleted file mode 100644 index 0cbfefec..00000000 --- a/alc/alu.cpp +++ /dev/null @@ -1,2018 +0,0 @@ -/** - * OpenAL cross platform audio library - * Copyright (C) 1999-2007 by authors. - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - * Or go to http://www.gnu.org/copyleft/lgpl.html - */ - -#include "config.h" - -#include "alu.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "AL/al.h" -#include "AL/alc.h" -#include "AL/efx.h" - -#include "alcmain.h" -#include "alcontext.h" -#include "almalloc.h" -#include "alnumeric.h" -#include "alspan.h" -#include "alstring.h" -#include "async_event.h" -#include "atomic.h" -#include "bformatdec.h" -#include "core/ambidefs.h" -#include "core/bs2b.h" -#include "core/bsinc_tables.h" -#include "core/cpu_caps.h" -#include "core/devformat.h" -#include "core/filters/biquad.h" -#include "core/filters/nfc.h" -#include "core/filters/splitter.h" -#include "core/fpu_ctrl.h" -#include "core/mastering.h" -#include "core/mixer/defs.h" -#include "core/uhjfilter.h" -#include "effects/base.h" -#include "effectslot.h" -#include "front_stablizer.h" -#include "hrtf.h" -#include "inprogext.h" -#include "math_defs.h" -#include "opthelpers.h" -#include "ringbuffer.h" -#include "strutils.h" -#include "threads.h" -#include "vecmat.h" -#include "voice.h" -#include "voice_change.h" - -struct CTag; -#ifdef HAVE_SSE -struct SSETag; -#endif -#ifdef HAVE_SSE2 -struct SSE2Tag; -#endif -#ifdef HAVE_SSE4_1 -struct SSE4Tag; -#endif -#ifdef HAVE_NEON -struct NEONTag; -#endif -struct CopyTag; -struct PointTag; -struct LerpTag; -struct CubicTag; -struct BSincTag; -struct FastBSincTag; - - -static_assert(MaxResamplerPadding >= BSincPointsMax, "MaxResamplerPadding is too small"); -static_assert(!(MaxResamplerPadding&1), "MaxResamplerPadding is not a multiple of two"); - - -namespace { - -constexpr uint MaxPitch{10}; - -static_assert((BufferLineSize-1)/MaxPitch > 0, "MaxPitch is too large for BufferLineSize!"); -static_assert((INT_MAX>>MixerFracBits)/MaxPitch > BufferLineSize, - "MaxPitch and/or BufferLineSize are too large for MixerFracBits!"); - -using namespace std::placeholders; - -float InitConeScale() -{ - float ret{1.0f}; - if(auto optval = al::getenv("__ALSOFT_HALF_ANGLE_CONES")) - { - if(al::strcasecmp(optval->c_str(), "true") == 0 - || strtol(optval->c_str(), nullptr, 0) == 1) - ret *= 0.5f; - } - return ret; -} - -float InitZScale() -{ - float ret{1.0f}; - if(auto optval = al::getenv("__ALSOFT_REVERSE_Z")) - { - if(al::strcasecmp(optval->c_str(), "true") == 0 - || strtol(optval->c_str(), nullptr, 0) == 1) - ret *= -1.0f; - } - return ret; -} - -} // namespace - -/* Cone scalar */ -const float ConeScale{InitConeScale()}; - -/* Localized Z scalar for mono sources */ -const float ZScale{InitZScale()}; - -namespace { - -struct ChanMap { - Channel channel; - float angle; - float elevation; -}; - -using HrtfDirectMixerFunc = void(*)(FloatBufferLine &LeftOut, FloatBufferLine &RightOut, - const al::span InSamples, float2 *AccumSamples, - float *TempBuf, HrtfChannelState *ChanState, const size_t IrSize, const size_t BufferSize); - -HrtfDirectMixerFunc MixDirectHrtf{MixDirectHrtf_}; - -inline HrtfDirectMixerFunc SelectHrtfMixer(void) -{ -#ifdef HAVE_NEON - if((CPUCapFlags&CPU_CAP_NEON)) - return MixDirectHrtf_; -#endif -#ifdef HAVE_SSE - if((CPUCapFlags&CPU_CAP_SSE)) - return MixDirectHrtf_; -#endif - - return MixDirectHrtf_; -} - - -inline void BsincPrepare(const uint increment, BsincState *state, const BSincTable *table) -{ - size_t si{BSincScaleCount - 1}; - float sf{0.0f}; - - if(increment > MixerFracOne) - { - sf = MixerFracOne / static_cast(increment); - sf = maxf(0.0f, (BSincScaleCount-1) * (sf-table->scaleBase) * table->scaleRange); - si = float2uint(sf); - /* The interpolation factor is fit to this diagonally-symmetric curve - * to reduce the transition ripple caused by interpolating different - * scales of the sinc function. - */ - sf = 1.0f - std::cos(std::asin(sf - static_cast(si))); - } - - state->sf = sf; - state->m = table->m[si]; - state->l = (state->m/2) - 1; - state->filter = table->Tab + table->filterOffset[si]; -} - -inline ResamplerFunc SelectResampler(Resampler resampler, uint increment) -{ - switch(resampler) - { - case Resampler::Point: - return Resample_; - case Resampler::Linear: -#ifdef HAVE_NEON - if((CPUCapFlags&CPU_CAP_NEON)) - return Resample_; -#endif -#ifdef HAVE_SSE4_1 - if((CPUCapFlags&CPU_CAP_SSE4_1)) - return Resample_; -#endif -#ifdef HAVE_SSE2 - if((CPUCapFlags&CPU_CAP_SSE2)) - return Resample_; -#endif - return Resample_; - case Resampler::Cubic: - return Resample_; - case Resampler::BSinc12: - case Resampler::BSinc24: - if(increment <= MixerFracOne) - { - /* fall-through */ - case Resampler::FastBSinc12: - case Resampler::FastBSinc24: -#ifdef HAVE_NEON - if((CPUCapFlags&CPU_CAP_NEON)) - return Resample_; -#endif -#ifdef HAVE_SSE - if((CPUCapFlags&CPU_CAP_SSE)) - return Resample_; -#endif - return Resample_; - } -#ifdef HAVE_NEON - if((CPUCapFlags&CPU_CAP_NEON)) - return Resample_; -#endif -#ifdef HAVE_SSE - if((CPUCapFlags&CPU_CAP_SSE)) - return Resample_; -#endif - return Resample_; - } - - return Resample_; -} - -} // namespace - -void aluInit(void) -{ - MixDirectHrtf = SelectHrtfMixer(); -} - - -ResamplerFunc PrepareResampler(Resampler resampler, uint increment, InterpState *state) -{ - switch(resampler) - { - case Resampler::Point: - case Resampler::Linear: - case Resampler::Cubic: - break; - case Resampler::FastBSinc12: - case Resampler::BSinc12: - BsincPrepare(increment, &state->bsinc, &bsinc12); - break; - case Resampler::FastBSinc24: - case Resampler::BSinc24: - BsincPrepare(increment, &state->bsinc, &bsinc24); - break; - } - return SelectResampler(resampler, increment); -} - - -void ALCdevice::ProcessHrtf(const size_t SamplesToDo) -{ - /* HRTF is stereo output only. */ - const uint lidx{RealOut.ChannelIndex[FrontLeft]}; - const uint ridx{RealOut.ChannelIndex[FrontRight]}; - - MixDirectHrtf(RealOut.Buffer[lidx], RealOut.Buffer[ridx], Dry.Buffer, HrtfAccumData, - mHrtfState->mTemp.data(), mHrtfState->mChannels.data(), mHrtfState->mIrSize, SamplesToDo); -} - -void ALCdevice::ProcessAmbiDec(const size_t SamplesToDo) -{ - AmbiDecoder->process(RealOut.Buffer, Dry.Buffer.data(), SamplesToDo); -} - -void ALCdevice::ProcessAmbiDecStablized(const size_t SamplesToDo) -{ - /* Decode with front image stablization. */ - const uint lidx{RealOut.ChannelIndex[FrontLeft]}; - const uint ridx{RealOut.ChannelIndex[FrontRight]}; - const uint cidx{RealOut.ChannelIndex[FrontCenter]}; - - AmbiDecoder->processStablize(RealOut.Buffer, Dry.Buffer.data(), lidx, ridx, cidx, - SamplesToDo); -} - -void ALCdevice::ProcessUhj(const size_t SamplesToDo) -{ - /* UHJ is stereo output only. */ - const uint lidx{RealOut.ChannelIndex[FrontLeft]}; - const uint ridx{RealOut.ChannelIndex[FrontRight]}; - - /* Encode to stereo-compatible 2-channel UHJ output. */ - Uhj_Encoder->encode(RealOut.Buffer[lidx], RealOut.Buffer[ridx], Dry.Buffer.data(), - SamplesToDo); -} - -void ALCdevice::ProcessBs2b(const size_t SamplesToDo) -{ - /* First, decode the ambisonic mix to the "real" output. */ - AmbiDecoder->process(RealOut.Buffer, Dry.Buffer.data(), SamplesToDo); - - /* BS2B is stereo output only. */ - const uint lidx{RealOut.ChannelIndex[FrontLeft]}; - const uint ridx{RealOut.ChannelIndex[FrontRight]}; - - /* Now apply the BS2B binaural/crossfeed filter. */ - bs2b_cross_feed(Bs2b.get(), RealOut.Buffer[lidx].data(), RealOut.Buffer[ridx].data(), - SamplesToDo); -} - - -namespace { - -/* This RNG method was created based on the math found in opusdec. It's quick, - * and starting with a seed value of 22222, is suitable for generating - * whitenoise. - */ -inline uint dither_rng(uint *seed) noexcept -{ - *seed = (*seed * 96314165) + 907633515; - return *seed; -} - - -inline auto& GetAmbiScales(AmbiScaling scaletype) noexcept -{ - if(scaletype == AmbiScaling::FuMa) return AmbiScale::FromFuMa(); - if(scaletype == AmbiScaling::SN3D) return AmbiScale::FromSN3D(); - return AmbiScale::FromN3D(); -} - -inline auto& GetAmbiLayout(AmbiLayout layouttype) noexcept -{ - if(layouttype == AmbiLayout::FuMa) return AmbiIndex::FromFuMa(); - return AmbiIndex::FromACN(); -} - -inline auto& GetAmbi2DLayout(AmbiLayout layouttype) noexcept -{ - if(layouttype == AmbiLayout::FuMa) return AmbiIndex::FromFuMa2D(); - return AmbiIndex::FromACN2D(); -} - - -bool CalcContextParams(ALCcontext *ctx) -{ - ContextProps *props{ctx->mParams.ContextUpdate.exchange(nullptr, std::memory_order_acq_rel)}; - if(!props) return false; - - ctx->mParams.DopplerFactor = props->DopplerFactor; - ctx->mParams.SpeedOfSound = props->SpeedOfSound * props->DopplerVelocity; - - ctx->mParams.SourceDistanceModel = props->SourceDistanceModel; - ctx->mParams.mDistanceModel = props->mDistanceModel; - - AtomicReplaceHead(ctx->mFreeContextProps, props); - return true; -} - -bool CalcListenerParams(ALCcontext *ctx) -{ - ListenerProps *props{ctx->mParams.ListenerUpdate.exchange(nullptr, - std::memory_order_acq_rel)}; - if(!props) return false; - - /* AT then UP */ - alu::Vector N{props->OrientAt[0], props->OrientAt[1], props->OrientAt[2], 0.0f}; - N.normalize(); - alu::Vector V{props->OrientUp[0], props->OrientUp[1], props->OrientUp[2], 0.0f}; - V.normalize(); - /* Build and normalize right-vector */ - alu::Vector U{N.cross_product(V)}; - U.normalize(); - - const alu::MatrixR rot{ - U[0], V[0], -N[0], 0.0, - U[1], V[1], -N[1], 0.0, - U[2], V[2], -N[2], 0.0, - 0.0, 0.0, 0.0, 1.0}; - const alu::VectorR pos{props->Position[0],props->Position[1],props->Position[2],1.0}; - const alu::VectorR vel{props->Velocity[0],props->Velocity[1],props->Velocity[2],0.0}; - const alu::Vector P{alu::cast_to(rot * pos)}; - - ctx->mParams.Matrix = alu::Matrix{ - U[0], V[0], -N[0], 0.0f, - U[1], V[1], -N[1], 0.0f, - U[2], V[2], -N[2], 0.0f, - -P[0], -P[1], -P[2], 1.0f}; - ctx->mParams.Velocity = alu::cast_to(rot * vel); - - ctx->mParams.Gain = props->Gain * ctx->mGainBoost; - ctx->mParams.MetersPerUnit = props->MetersPerUnit; - - AtomicReplaceHead(ctx->mFreeListenerProps, props); - return true; -} - -bool CalcEffectSlotParams(EffectSlot *slot, EffectSlot **sorted_slots, ALCcontext *context) -{ - EffectSlotProps *props{slot->Update.exchange(nullptr, std::memory_order_acq_rel)}; - if(!props) return false; - - /* If the effect slot target changed, clear the first sorted entry to force - * a re-sort. - */ - if(slot->Target != props->Target) - *sorted_slots = nullptr; - slot->Gain = props->Gain; - slot->AuxSendAuto = props->AuxSendAuto; - slot->Target = props->Target; - slot->EffectType = props->Type; - slot->mEffectProps = props->Props; - if(props->Type == EffectSlotType::Reverb || props->Type == EffectSlotType::EAXReverb) - { - slot->RoomRolloff = props->Props.Reverb.RoomRolloffFactor; - slot->DecayTime = props->Props.Reverb.DecayTime; - slot->DecayLFRatio = props->Props.Reverb.DecayLFRatio; - slot->DecayHFRatio = props->Props.Reverb.DecayHFRatio; - slot->DecayHFLimit = props->Props.Reverb.DecayHFLimit; - slot->AirAbsorptionGainHF = props->Props.Reverb.AirAbsorptionGainHF; - } - else - { - slot->RoomRolloff = 0.0f; - slot->DecayTime = 0.0f; - slot->DecayLFRatio = 0.0f; - slot->DecayHFRatio = 0.0f; - slot->DecayHFLimit = false; - slot->AirAbsorptionGainHF = 1.0f; - } - - EffectState *state{props->State.release()}; - EffectState *oldstate{slot->mEffectState}; - slot->mEffectState = state; - - /* Only release the old state if it won't get deleted, since we can't be - * deleting/freeing anything in the mixer. - */ - if(!oldstate->releaseIfNoDelete()) - { - /* Otherwise, if it would be deleted send it off with a release event. */ - RingBuffer *ring{context->mAsyncEvents.get()}; - auto evt_vec = ring->getWriteVector(); - if LIKELY(evt_vec.first.len > 0) - { - AsyncEvent *evt{::new(evt_vec.first.buf) AsyncEvent{EventType_ReleaseEffectState}}; - evt->u.mEffectState = oldstate; - ring->writeAdvance(1); - } - else - { - /* If writing the event failed, the queue was probably full. Store - * the old state in the property object where it can eventually be - * cleaned up sometime later (not ideal, but better than blocking - * or leaking). - */ - props->State.reset(oldstate); - } - } - - AtomicReplaceHead(context->mFreeEffectslotProps, props); - - EffectTarget output; - if(EffectSlot *target{slot->Target}) - output = EffectTarget{&target->Wet, nullptr}; - else - { - ALCdevice *device{context->mDevice.get()}; - output = EffectTarget{&device->Dry, &device->RealOut}; - } - state->update(context, slot, &slot->mEffectProps, output); - return true; -} - - -/* Scales the given azimuth toward the side (+/- pi/2 radians) for positions in - * front. - */ -inline float ScaleAzimuthFront(float azimuth, float scale) -{ - const float abs_azi{std::fabs(azimuth)}; - if(!(abs_azi >= al::MathDefs::Pi()*0.5f)) - return std::copysign(minf(abs_azi*scale, al::MathDefs::Pi()*0.5f), azimuth); - return azimuth; -} - -/* Wraps the given value in radians to stay between [-pi,+pi] */ -inline float WrapRadians(float r) -{ - constexpr float Pi{al::MathDefs::Pi()}; - constexpr float Pi2{al::MathDefs::Tau()}; - if(r > Pi) return std::fmod(Pi+r, Pi2) - Pi; - if(r < -Pi) return Pi - std::fmod(Pi-r, Pi2); - return r; -} - -/* Begin ambisonic rotation helpers. - * - * Rotating first-order B-Format just needs a straight-forward X/Y/Z rotation - * matrix. Higher orders, however, are more complicated. The method implemented - * here is a recursive algorithm (the rotation for first-order is used to help - * generate the second-order rotation, which helps generate the third-order - * rotation, etc). - * - * Adapted from - * , - * provided under the BSD 3-Clause license. - * - * Copyright (c) 2015, Archontis Politis - * Copyright (c) 2019, Christopher Robinson - * - * The u, v, and w coefficients used for generating higher-order rotations are - * precomputed since they're constant. The second-order coefficients are - * followed by the third-order coefficients, etc. - */ -struct RotatorCoeffs { - float u, v, w; - - template - static std::array ConcatArrays(const std::array &lhs, - const std::array &rhs) - { - std::array ret; - auto iter = std::copy(lhs.cbegin(), lhs.cend(), ret.begin()); - std::copy(rhs.cbegin(), rhs.cend(), iter); - return ret; - } - - template - static std::array GenCoeffs() - { - std::array ret{}; - auto coeffs = ret.begin(); - - for(int m{-l};m <= l;++m) - { - for(int n{-l};n <= l;++n) - { - // compute u,v,w terms of Eq.8.1 (Table I) - const bool d{m == 0}; // the delta function d_m0 - const float denom{static_cast((std::abs(n) == l) ? - (2*l) * (2*l - 1) : (l*l - n*n))}; - - const int abs_m{std::abs(m)}; - coeffs->u = std::sqrt(static_cast(l*l - m*m)/denom); - coeffs->v = std::sqrt(static_cast(l+abs_m-1) * static_cast(l+abs_m) / - denom) * (1.0f+d) * (1.0f - 2.0f*d) * 0.5f; - coeffs->w = std::sqrt(static_cast(l-abs_m-1) * static_cast(l-abs_m) / - denom) * (1.0f-d) * -0.5f; - ++coeffs; - } - } - - return ret; - } -}; -const auto RotatorCoeffArray = RotatorCoeffs::ConcatArrays(RotatorCoeffs::GenCoeffs<2>(), - RotatorCoeffs::GenCoeffs<3>()); - -/** - * Given the matrix, pre-filled with the (zeroth- and) first-order rotation - * coefficients, this fills in the coefficients for the higher orders up to and - * including the given order. The matrix is in ACN layout. - */ -void AmbiRotator(std::array,MaxAmbiChannels> &matrix, - const int order) -{ - /* Don't do anything for < 2nd order. */ - if(order < 2) return; - - auto P = [](const int i, const int l, const int a, const int n, const size_t last_band, - const std::array,MaxAmbiChannels> &R) - { - const float ri1{ R[static_cast(i+2)][ 1+2]}; - const float rim1{R[static_cast(i+2)][-1+2]}; - const float ri0{ R[static_cast(i+2)][ 0+2]}; - - auto vec = R[static_cast(a+l-1) + last_band].cbegin() + last_band; - if(n == -l) - return ri1*vec[0] + rim1*vec[static_cast(l-1)*size_t{2}]; - if(n == l) - return ri1*vec[static_cast(l-1)*size_t{2}] - rim1*vec[0]; - return ri0*vec[static_cast(n+l-1)]; - }; - - auto U = [P](const int l, const int m, const int n, const size_t last_band, - const std::array,MaxAmbiChannels> &R) - { - return P(0, l, m, n, last_band, R); - }; - auto V = [P](const int l, const int m, const int n, const size_t last_band, - const std::array,MaxAmbiChannels> &R) - { - if(m > 0) - { - const bool d{m == 1}; - const float p0{P( 1, l, m-1, n, last_band, R)}; - const float p1{P(-1, l, -m+1, n, last_band, R)}; - return d ? p0*std::sqrt(2.0f) : (p0 - p1); - } - const bool d{m == -1}; - const float p0{P( 1, l, m+1, n, last_band, R)}; - const float p1{P(-1, l, -m-1, n, last_band, R)}; - return d ? p1*std::sqrt(2.0f) : (p0 + p1); - }; - auto W = [P](const int l, const int m, const int n, const size_t last_band, - const std::array,MaxAmbiChannels> &R) - { - assert(m != 0); - if(m > 0) - { - const float p0{P( 1, l, m+1, n, last_band, R)}; - const float p1{P(-1, l, -m-1, n, last_band, R)}; - return p0 + p1; - } - const float p0{P( 1, l, m-1, n, last_band, R)}; - const float p1{P(-1, l, -m+1, n, last_band, R)}; - return p0 - p1; - }; - - // compute rotation matrix of each subsequent band recursively - auto coeffs = RotatorCoeffArray.cbegin(); - size_t band_idx{4}, last_band{1}; - for(int l{2};l <= order;++l) - { - size_t y{band_idx}; - for(int m{-l};m <= l;++m,++y) - { - size_t x{band_idx}; - for(int n{-l};n <= l;++n,++x) - { - float r{0.0f}; - - // computes Eq.8.1 - const float u{coeffs->u}; - if(u != 0.0f) r += u * U(l, m, n, last_band, matrix); - const float v{coeffs->v}; - if(v != 0.0f) r += v * V(l, m, n, last_band, matrix); - const float w{coeffs->w}; - if(w != 0.0f) r += w * W(l, m, n, last_band, matrix); - - matrix[y][x] = r; - ++coeffs; - } - } - last_band = band_idx; - band_idx += static_cast(l)*size_t{2} + 1; - } -} -/* End ambisonic rotation helpers. */ - - -struct GainTriplet { float Base, HF, LF; }; - -void CalcPanningAndFilters(Voice *voice, const float xpos, const float ypos, const float zpos, - const float Distance, const float Spread, const GainTriplet &DryGain, - const al::span WetGain, EffectSlot *(&SendSlots)[MAX_SENDS], - const VoiceProps *props, const ContextParams &Context, const ALCdevice *Device) -{ - static const ChanMap MonoMap[1]{ - { FrontCenter, 0.0f, 0.0f } - }, RearMap[2]{ - { BackLeft, Deg2Rad(-150.0f), Deg2Rad(0.0f) }, - { BackRight, Deg2Rad( 150.0f), Deg2Rad(0.0f) } - }, QuadMap[4]{ - { FrontLeft, Deg2Rad( -45.0f), Deg2Rad(0.0f) }, - { FrontRight, Deg2Rad( 45.0f), Deg2Rad(0.0f) }, - { BackLeft, Deg2Rad(-135.0f), Deg2Rad(0.0f) }, - { BackRight, Deg2Rad( 135.0f), Deg2Rad(0.0f) } - }, X51Map[6]{ - { FrontLeft, Deg2Rad( -30.0f), Deg2Rad(0.0f) }, - { FrontRight, Deg2Rad( 30.0f), Deg2Rad(0.0f) }, - { FrontCenter, Deg2Rad( 0.0f), Deg2Rad(0.0f) }, - { LFE, 0.0f, 0.0f }, - { SideLeft, Deg2Rad(-110.0f), Deg2Rad(0.0f) }, - { SideRight, Deg2Rad( 110.0f), Deg2Rad(0.0f) } - }, X61Map[7]{ - { FrontLeft, Deg2Rad(-30.0f), Deg2Rad(0.0f) }, - { FrontRight, Deg2Rad( 30.0f), Deg2Rad(0.0f) }, - { FrontCenter, Deg2Rad( 0.0f), Deg2Rad(0.0f) }, - { LFE, 0.0f, 0.0f }, - { BackCenter, Deg2Rad(180.0f), Deg2Rad(0.0f) }, - { SideLeft, Deg2Rad(-90.0f), Deg2Rad(0.0f) }, - { SideRight, Deg2Rad( 90.0f), Deg2Rad(0.0f) } - }, X71Map[8]{ - { FrontLeft, Deg2Rad( -30.0f), Deg2Rad(0.0f) }, - { FrontRight, Deg2Rad( 30.0f), Deg2Rad(0.0f) }, - { FrontCenter, Deg2Rad( 0.0f), Deg2Rad(0.0f) }, - { LFE, 0.0f, 0.0f }, - { BackLeft, Deg2Rad(-150.0f), Deg2Rad(0.0f) }, - { BackRight, Deg2Rad( 150.0f), Deg2Rad(0.0f) }, - { SideLeft, Deg2Rad( -90.0f), Deg2Rad(0.0f) }, - { SideRight, Deg2Rad( 90.0f), Deg2Rad(0.0f) } - }; - - ChanMap StereoMap[2]{ - { FrontLeft, Deg2Rad(-30.0f), Deg2Rad(0.0f) }, - { FrontRight, Deg2Rad( 30.0f), Deg2Rad(0.0f) } - }; - - const auto Frequency = static_cast(Device->Frequency); - const uint NumSends{Device->NumAuxSends}; - - const size_t num_channels{voice->mChans.size()}; - ASSUME(num_channels > 0); - - for(auto &chandata : voice->mChans) - { - chandata.mDryParams.Hrtf.Target = HrtfFilter{}; - chandata.mDryParams.Gains.Target.fill(0.0f); - std::for_each(chandata.mWetParams.begin(), chandata.mWetParams.begin()+NumSends, - [](SendParams ¶ms) -> void { params.Gains.Target.fill(0.0f); }); - } - - DirectMode DirectChannels{props->DirectChannels}; - const ChanMap *chans{nullptr}; - float downmix_gain{1.0f}; - switch(voice->mFmtChannels) - { - case FmtMono: - chans = MonoMap; - /* Mono buffers are never played direct. */ - DirectChannels = DirectMode::Off; - break; - - case FmtStereo: - if(DirectChannels == DirectMode::Off) - { - /* Convert counter-clockwise to clock-wise, and wrap between - * [-pi,+pi]. - */ - StereoMap[0].angle = WrapRadians(-props->StereoPan[0]); - StereoMap[1].angle = WrapRadians(-props->StereoPan[1]); - } - - chans = StereoMap; - downmix_gain = 1.0f / 2.0f; - break; - - case FmtRear: - chans = RearMap; - downmix_gain = 1.0f / 2.0f; - break; - - case FmtQuad: - chans = QuadMap; - downmix_gain = 1.0f / 4.0f; - break; - - case FmtX51: - chans = X51Map; - /* NOTE: Excludes LFE. */ - downmix_gain = 1.0f / 5.0f; - break; - - case FmtX61: - chans = X61Map; - /* NOTE: Excludes LFE. */ - downmix_gain = 1.0f / 6.0f; - break; - - case FmtX71: - chans = X71Map; - /* NOTE: Excludes LFE. */ - downmix_gain = 1.0f / 7.0f; - break; - - case FmtBFormat2D: - case FmtBFormat3D: - DirectChannels = DirectMode::Off; - break; - } - - voice->mFlags &= ~(VoiceHasHrtf | VoiceHasNfc); - if(voice->mFmtChannels == FmtBFormat2D || voice->mFmtChannels == FmtBFormat3D) - { - /* Special handling for B-Format sources. */ - - if(Device->AvgSpeakerDist > 0.0f) - { - if(!(Distance > std::numeric_limits::epsilon())) - { - /* NOTE: The NFCtrlFilters were created with a w0 of 0, which - * is what we want for FOA input. The first channel may have - * been previously re-adjusted if panned, so reset it. - */ - voice->mChans[0].mDryParams.NFCtrlFilter.adjust(0.0f); - } - else - { - /* Clamp the distance for really close sources, to prevent - * excessive bass. - */ - const float mdist{maxf(Distance, Device->AvgSpeakerDist/4.0f)}; - const float w0{SpeedOfSoundMetersPerSec / (mdist * Frequency)}; - - /* Only need to adjust the first channel of a B-Format source. */ - voice->mChans[0].mDryParams.NFCtrlFilter.adjust(w0); - } - - voice->mFlags |= VoiceHasNfc; - } - - /* Panning a B-Format sound toward some direction is easy. Just pan the - * first (W) channel as a normal mono sound. The angular spread is used - * as a directional scalar to blend between full coverage and full - * panning. - */ - const float coverage{!(Distance > std::numeric_limits::epsilon()) ? 1.0f : - (Spread * (1.0f/al::MathDefs::Tau()))}; - - auto calc_coeffs = [xpos,ypos,zpos](RenderMode mode) - { - if(mode != RenderMode::Pairwise) - return CalcDirectionCoeffs({xpos, ypos, zpos}, 0.0f); - - /* Clamp Y, in case rounding errors caused it to end up outside - * of -1...+1. - */ - const float ev{std::asin(clampf(ypos, -1.0f, 1.0f))}; - /* Negate Z for right-handed coords with -Z in front. */ - const float az{std::atan2(xpos, -zpos)}; - - /* A scalar of 1.5 for plain stereo results in +/-60 degrees - * being moved to +/-90 degrees for direct right and left - * speaker responses. - */ - return CalcAngleCoeffs(ScaleAzimuthFront(az, 1.5f), ev, 0.0f); - }; - auto coeffs = calc_coeffs(Device->mRenderMode); - std::transform(coeffs.begin()+1, coeffs.end(), coeffs.begin()+1, - std::bind(std::multiplies{}, _1, 1.0f-coverage)); - - /* NOTE: W needs to be scaled according to channel scaling. */ - auto&& scales = GetAmbiScales(voice->mAmbiScaling); - ComputePanGains(&Device->Dry, coeffs.data(), DryGain.Base*scales[0], - voice->mChans[0].mDryParams.Gains.Target); - for(uint i{0};i < NumSends;i++) - { - if(const EffectSlot *Slot{SendSlots[i]}) - ComputePanGains(&Slot->Wet, coeffs.data(), WetGain[i].Base*scales[0], - voice->mChans[0].mWetParams[i].Gains.Target); - } - - if(coverage > 0.0f) - { - /* Local B-Format sources have their XYZ channels rotated according - * to the orientation. - */ - /* AT then UP */ - alu::Vector N{props->OrientAt[0], props->OrientAt[1], props->OrientAt[2], 0.0f}; - N.normalize(); - alu::Vector V{props->OrientUp[0], props->OrientUp[1], props->OrientUp[2], 0.0f}; - V.normalize(); - if(!props->HeadRelative) - { - N = Context.Matrix * N; - V = Context.Matrix * V; - } - /* Build and normalize right-vector */ - alu::Vector U{N.cross_product(V)}; - U.normalize(); - - /* Build a rotation matrix. Manually fill the zeroth- and first- - * order elements, then construct the rotation for the higher - * orders. - */ - std::array,MaxAmbiChannels> shrot{}; - shrot[0][0] = 1.0f; - shrot[1][1] = U[0]; shrot[1][2] = -V[0]; shrot[1][3] = -N[0]; - shrot[2][1] = -U[1]; shrot[2][2] = V[1]; shrot[2][3] = N[1]; - shrot[3][1] = U[2]; shrot[3][2] = -V[2]; shrot[3][3] = -N[2]; - AmbiRotator(shrot, static_cast(minu(voice->mAmbiOrder, Device->mAmbiOrder))); - - /* Convert the rotation matrix for input ordering and scaling, and - * whether input is 2D or 3D. - */ - const uint8_t *index_map{(voice->mFmtChannels == FmtBFormat2D) ? - GetAmbi2DLayout(voice->mAmbiLayout).data() : - GetAmbiLayout(voice->mAmbiLayout).data()}; - - static const uint8_t ChansPerOrder[MaxAmbiOrder+1]{1, 3, 5, 7,}; - static const uint8_t OrderOffset[MaxAmbiOrder+1]{0, 1, 4, 9,}; - for(size_t c{1};c < num_channels;c++) - { - const size_t acn{index_map[c]}; - const size_t order{AmbiIndex::OrderFromChannel()[acn]}; - const size_t tocopy{ChansPerOrder[order]}; - const size_t offset{OrderOffset[order]}; - const float scale{scales[acn] * coverage}; - auto in = shrot.cbegin() + offset; - - coeffs = std::array{}; - for(size_t x{0};x < tocopy;++x) - coeffs[offset+x] = in[x][acn] * scale; - - ComputePanGains(&Device->Dry, coeffs.data(), DryGain.Base, - voice->mChans[c].mDryParams.Gains.Target); - - for(uint i{0};i < NumSends;i++) - { - if(const EffectSlot *Slot{SendSlots[i]}) - ComputePanGains(&Slot->Wet, coeffs.data(), WetGain[i].Base, - voice->mChans[c].mWetParams[i].Gains.Target); - } - } - } - } - else if(DirectChannels != DirectMode::Off && Device->FmtChans != DevFmtAmbi3D) - { - /* Direct source channels always play local. Skip the virtual channels - * and write inputs to the matching real outputs. - */ - voice->mDirect.Buffer = Device->RealOut.Buffer; - - for(size_t c{0};c < num_channels;c++) - { - uint idx{GetChannelIdxByName(Device->RealOut, chans[c].channel)}; - if(idx != INVALID_CHANNEL_INDEX) - voice->mChans[c].mDryParams.Gains.Target[idx] = DryGain.Base; - else if(DirectChannels == DirectMode::RemixMismatch) - { - auto match_channel = [chans,c](const InputRemixMap &map) noexcept -> bool - { return chans[c].channel == map.channel; }; - auto remap = std::find_if(Device->RealOut.RemixMap.cbegin(), - Device->RealOut.RemixMap.cend(), match_channel); - if(remap != Device->RealOut.RemixMap.cend()) - for(const auto &target : remap->targets) - { - idx = GetChannelIdxByName(Device->RealOut, target.channel); - if(idx != INVALID_CHANNEL_INDEX) - voice->mChans[c].mDryParams.Gains.Target[idx] = DryGain.Base * - target.mix; - } - } - } - - /* Auxiliary sends still use normal channel panning since they mix to - * B-Format, which can't channel-match. - */ - for(size_t c{0};c < num_channels;c++) - { - const auto coeffs = CalcAngleCoeffs(chans[c].angle, chans[c].elevation, 0.0f); - - for(uint i{0};i < NumSends;i++) - { - if(const EffectSlot *Slot{SendSlots[i]}) - ComputePanGains(&Slot->Wet, coeffs.data(), WetGain[i].Base, - voice->mChans[c].mWetParams[i].Gains.Target); - } - } - } - else if(Device->mRenderMode == RenderMode::Hrtf) - { - /* Full HRTF rendering. Skip the virtual channels and render to the - * real outputs. - */ - voice->mDirect.Buffer = Device->RealOut.Buffer; - - if(Distance > std::numeric_limits::epsilon()) - { - const float ev{std::asin(clampf(ypos, -1.0f, 1.0f))}; - const float az{std::atan2(xpos, -zpos)}; - - /* Get the HRIR coefficients and delays just once, for the given - * source direction. - */ - GetHrtfCoeffs(Device->mHrtf.get(), ev, az, Distance, Spread, - voice->mChans[0].mDryParams.Hrtf.Target.Coeffs, - voice->mChans[0].mDryParams.Hrtf.Target.Delay); - voice->mChans[0].mDryParams.Hrtf.Target.Gain = DryGain.Base * downmix_gain; - - /* Remaining channels use the same results as the first. */ - for(size_t c{1};c < num_channels;c++) - { - /* Skip LFE */ - if(chans[c].channel == LFE) continue; - voice->mChans[c].mDryParams.Hrtf.Target = voice->mChans[0].mDryParams.Hrtf.Target; - } - - /* Calculate the directional coefficients once, which apply to all - * input channels of the source sends. - */ - const auto coeffs = CalcDirectionCoeffs({xpos, ypos, zpos}, Spread); - - for(size_t c{0};c < num_channels;c++) - { - /* Skip LFE */ - if(chans[c].channel == LFE) - continue; - for(uint i{0};i < NumSends;i++) - { - if(const EffectSlot *Slot{SendSlots[i]}) - ComputePanGains(&Slot->Wet, coeffs.data(), WetGain[i].Base * downmix_gain, - voice->mChans[c].mWetParams[i].Gains.Target); - } - } - } - else - { - /* Local sources on HRTF play with each channel panned to its - * relative location around the listener, providing "virtual - * speaker" responses. - */ - for(size_t c{0};c < num_channels;c++) - { - /* Skip LFE */ - if(chans[c].channel == LFE) - continue; - - /* Get the HRIR coefficients and delays for this channel - * position. - */ - GetHrtfCoeffs(Device->mHrtf.get(), chans[c].elevation, chans[c].angle, - std::numeric_limits::infinity(), Spread, - voice->mChans[c].mDryParams.Hrtf.Target.Coeffs, - voice->mChans[c].mDryParams.Hrtf.Target.Delay); - voice->mChans[c].mDryParams.Hrtf.Target.Gain = DryGain.Base; - - /* Normal panning for auxiliary sends. */ - const auto coeffs = CalcAngleCoeffs(chans[c].angle, chans[c].elevation, Spread); - - for(uint i{0};i < NumSends;i++) - { - if(const EffectSlot *Slot{SendSlots[i]}) - ComputePanGains(&Slot->Wet, coeffs.data(), WetGain[i].Base, - voice->mChans[c].mWetParams[i].Gains.Target); - } - } - } - - voice->mFlags |= VoiceHasHrtf; - } - else - { - /* Non-HRTF rendering. Use normal panning to the output. */ - - if(Distance > std::numeric_limits::epsilon()) - { - /* Calculate NFC filter coefficient if needed. */ - if(Device->AvgSpeakerDist > 0.0f) - { - /* Clamp the distance for really close sources, to prevent - * excessive bass. - */ - const float mdist{maxf(Distance, Device->AvgSpeakerDist/4.0f)}; - const float w0{SpeedOfSoundMetersPerSec / (mdist * Frequency)}; - - /* Adjust NFC filters. */ - for(size_t c{0};c < num_channels;c++) - voice->mChans[c].mDryParams.NFCtrlFilter.adjust(w0); - - voice->mFlags |= VoiceHasNfc; - } - - /* Calculate the directional coefficients once, which apply to all - * input channels. - */ - auto calc_coeffs = [xpos,ypos,zpos,Spread](RenderMode mode) - { - if(mode != RenderMode::Pairwise) - return CalcDirectionCoeffs({xpos, ypos, zpos}, Spread); - const float ev{std::asin(clampf(ypos, -1.0f, 1.0f))}; - const float az{std::atan2(xpos, -zpos)}; - return CalcAngleCoeffs(ScaleAzimuthFront(az, 1.5f), ev, Spread); - }; - const auto coeffs = calc_coeffs(Device->mRenderMode); - - for(size_t c{0};c < num_channels;c++) - { - /* Special-case LFE */ - if(chans[c].channel == LFE) - { - if(Device->Dry.Buffer.data() == Device->RealOut.Buffer.data()) - { - const uint idx{GetChannelIdxByName(Device->RealOut, chans[c].channel)}; - if(idx != INVALID_CHANNEL_INDEX) - voice->mChans[c].mDryParams.Gains.Target[idx] = DryGain.Base; - } - continue; - } - - ComputePanGains(&Device->Dry, coeffs.data(), DryGain.Base * downmix_gain, - voice->mChans[c].mDryParams.Gains.Target); - for(uint i{0};i < NumSends;i++) - { - if(const EffectSlot *Slot{SendSlots[i]}) - ComputePanGains(&Slot->Wet, coeffs.data(), WetGain[i].Base * downmix_gain, - voice->mChans[c].mWetParams[i].Gains.Target); - } - } - } - else - { - if(Device->AvgSpeakerDist > 0.0f) - { - /* If the source distance is 0, simulate a plane-wave by using - * infinite distance, which results in a w0 of 0. - */ - constexpr float w0{0.0f}; - for(size_t c{0};c < num_channels;c++) - voice->mChans[c].mDryParams.NFCtrlFilter.adjust(w0); - - voice->mFlags |= VoiceHasNfc; - } - - for(size_t c{0};c < num_channels;c++) - { - /* Special-case LFE */ - if(chans[c].channel == LFE) - { - if(Device->Dry.Buffer.data() == Device->RealOut.Buffer.data()) - { - const uint idx{GetChannelIdxByName(Device->RealOut, chans[c].channel)}; - if(idx != INVALID_CHANNEL_INDEX) - voice->mChans[c].mDryParams.Gains.Target[idx] = DryGain.Base; - } - continue; - } - - const auto coeffs = CalcAngleCoeffs((Device->mRenderMode == RenderMode::Pairwise) - ? ScaleAzimuthFront(chans[c].angle, 3.0f) : chans[c].angle, - chans[c].elevation, Spread); - - ComputePanGains(&Device->Dry, coeffs.data(), DryGain.Base, - voice->mChans[c].mDryParams.Gains.Target); - for(uint i{0};i < NumSends;i++) - { - if(const EffectSlot *Slot{SendSlots[i]}) - ComputePanGains(&Slot->Wet, coeffs.data(), WetGain[i].Base, - voice->mChans[c].mWetParams[i].Gains.Target); - } - } - } - } - - { - const float hfNorm{props->Direct.HFReference / Frequency}; - const float lfNorm{props->Direct.LFReference / Frequency}; - - voice->mDirect.FilterType = AF_None; - if(DryGain.HF != 1.0f) voice->mDirect.FilterType |= AF_LowPass; - if(DryGain.LF != 1.0f) voice->mDirect.FilterType |= AF_HighPass; - - auto &lowpass = voice->mChans[0].mDryParams.LowPass; - auto &highpass = voice->mChans[0].mDryParams.HighPass; - lowpass.setParamsFromSlope(BiquadType::HighShelf, hfNorm, DryGain.HF, 1.0f); - highpass.setParamsFromSlope(BiquadType::LowShelf, lfNorm, DryGain.LF, 1.0f); - for(size_t c{1};c < num_channels;c++) - { - voice->mChans[c].mDryParams.LowPass.copyParamsFrom(lowpass); - voice->mChans[c].mDryParams.HighPass.copyParamsFrom(highpass); - } - } - for(uint i{0};i < NumSends;i++) - { - const float hfNorm{props->Send[i].HFReference / Frequency}; - const float lfNorm{props->Send[i].LFReference / Frequency}; - - voice->mSend[i].FilterType = AF_None; - if(WetGain[i].HF != 1.0f) voice->mSend[i].FilterType |= AF_LowPass; - if(WetGain[i].LF != 1.0f) voice->mSend[i].FilterType |= AF_HighPass; - - auto &lowpass = voice->mChans[0].mWetParams[i].LowPass; - auto &highpass = voice->mChans[0].mWetParams[i].HighPass; - lowpass.setParamsFromSlope(BiquadType::HighShelf, hfNorm, WetGain[i].HF, 1.0f); - highpass.setParamsFromSlope(BiquadType::LowShelf, lfNorm, WetGain[i].LF, 1.0f); - for(size_t c{1};c < num_channels;c++) - { - voice->mChans[c].mWetParams[i].LowPass.copyParamsFrom(lowpass); - voice->mChans[c].mWetParams[i].HighPass.copyParamsFrom(highpass); - } - } -} - -void CalcNonAttnSourceParams(Voice *voice, const VoiceProps *props, const ALCcontext *context) -{ - const ALCdevice *Device{context->mDevice.get()}; - EffectSlot *SendSlots[MAX_SENDS]; - - voice->mDirect.Buffer = Device->Dry.Buffer; - for(uint i{0};i < Device->NumAuxSends;i++) - { - SendSlots[i] = props->Send[i].Slot; - if(!SendSlots[i] || SendSlots[i]->EffectType == EffectSlotType::None) - { - SendSlots[i] = nullptr; - voice->mSend[i].Buffer = {}; - } - else - voice->mSend[i].Buffer = SendSlots[i]->Wet.Buffer; - } - - /* Calculate the stepping value */ - const auto Pitch = static_cast(voice->mFrequency) / - static_cast(Device->Frequency) * props->Pitch; - if(Pitch > float{MaxPitch}) - voice->mStep = MaxPitch<mStep = maxu(fastf2u(Pitch * MixerFracOne), 1); - voice->mResampler = PrepareResampler(props->mResampler, voice->mStep, &voice->mResampleState); - - /* Calculate gains */ - GainTriplet DryGain; - DryGain.Base = minf(clampf(props->Gain, props->MinGain, props->MaxGain) * props->Direct.Gain * - context->mParams.Gain, GainMixMax); - DryGain.HF = props->Direct.GainHF; - DryGain.LF = props->Direct.GainLF; - GainTriplet WetGain[MAX_SENDS]; - for(uint i{0};i < Device->NumAuxSends;i++) - { - WetGain[i].Base = minf(clampf(props->Gain, props->MinGain, props->MaxGain) * - props->Send[i].Gain * context->mParams.Gain, GainMixMax); - WetGain[i].HF = props->Send[i].GainHF; - WetGain[i].LF = props->Send[i].GainLF; - } - - CalcPanningAndFilters(voice, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, DryGain, WetGain, SendSlots, props, - context->mParams, Device); -} - -void CalcAttnSourceParams(Voice *voice, const VoiceProps *props, const ALCcontext *context) -{ - const ALCdevice *Device{context->mDevice.get()}; - const uint NumSends{Device->NumAuxSends}; - - /* Set mixing buffers and get send parameters. */ - voice->mDirect.Buffer = Device->Dry.Buffer; - EffectSlot *SendSlots[MAX_SENDS]; - float RoomRolloff[MAX_SENDS]; - GainTriplet DecayDistance[MAX_SENDS]; - for(uint i{0};i < NumSends;i++) - { - SendSlots[i] = props->Send[i].Slot; - if(!SendSlots[i] || SendSlots[i]->EffectType == EffectSlotType::None) - { - SendSlots[i] = nullptr; - RoomRolloff[i] = 0.0f; - DecayDistance[i].Base = 0.0f; - DecayDistance[i].LF = 0.0f; - DecayDistance[i].HF = 0.0f; - } - else if(SendSlots[i]->AuxSendAuto) - { - RoomRolloff[i] = SendSlots[i]->RoomRolloff + props->RoomRolloffFactor; - /* Calculate the distances to where this effect's decay reaches - * -60dB. - */ - DecayDistance[i].Base = SendSlots[i]->DecayTime * SpeedOfSoundMetersPerSec; - DecayDistance[i].LF = DecayDistance[i].Base * SendSlots[i]->DecayLFRatio; - DecayDistance[i].HF = DecayDistance[i].Base * SendSlots[i]->DecayHFRatio; - if(SendSlots[i]->DecayHFLimit) - { - const float airAbsorption{SendSlots[i]->AirAbsorptionGainHF}; - if(airAbsorption < 1.0f) - { - /* Calculate the distance to where this effect's air - * absorption reaches -60dB, and limit the effect's HF - * decay distance (so it doesn't take any longer to decay - * than the air would allow). - */ - constexpr float log10_decaygain{-3.0f/*std::log10(ReverbDecayGain)*/}; - const float absorb_dist{log10_decaygain / std::log10(airAbsorption)}; - DecayDistance[i].HF = minf(absorb_dist, DecayDistance[i].HF); - } - } - } - else - { - /* If the slot's auxiliary send auto is off, the data sent to the - * effect slot is the same as the dry path, sans filter effects */ - RoomRolloff[i] = props->RolloffFactor; - DecayDistance[i].Base = 0.0f; - DecayDistance[i].LF = 0.0f; - DecayDistance[i].HF = 0.0f; - } - - if(!SendSlots[i]) - voice->mSend[i].Buffer = {}; - else - voice->mSend[i].Buffer = SendSlots[i]->Wet.Buffer; - } - - /* Transform source to listener space (convert to head relative) */ - alu::Vector Position{props->Position[0], props->Position[1], props->Position[2], 1.0f}; - alu::Vector Velocity{props->Velocity[0], props->Velocity[1], props->Velocity[2], 0.0f}; - alu::Vector Direction{props->Direction[0], props->Direction[1], props->Direction[2], 0.0f}; - if(!props->HeadRelative) - { - /* Transform source vectors */ - Position = context->mParams.Matrix * Position; - Velocity = context->mParams.Matrix * Velocity; - Direction = context->mParams.Matrix * Direction; - } - else - { - /* Offset the source velocity to be relative of the listener velocity */ - Velocity += context->mParams.Velocity; - } - - const bool directional{Direction.normalize() > 0.0f}; - alu::Vector ToSource{Position[0], Position[1], Position[2], 0.0f}; - const float Distance{ToSource.normalize()}; - - /* Initial source gain */ - GainTriplet DryGain{props->Gain, 1.0f, 1.0f}; - GainTriplet WetGain[MAX_SENDS]; - for(uint i{0};i < NumSends;i++) - WetGain[i] = DryGain; - - /* Calculate distance attenuation */ - float ClampedDist{Distance}; - - switch(context->mParams.SourceDistanceModel ? props->mDistanceModel - : context->mParams.mDistanceModel) - { - case DistanceModel::InverseClamped: - ClampedDist = clampf(ClampedDist, props->RefDistance, props->MaxDistance); - if(props->MaxDistance < props->RefDistance) break; - /*fall-through*/ - case DistanceModel::Inverse: - if(!(props->RefDistance > 0.0f)) - ClampedDist = props->RefDistance; - else - { - float dist{lerp(props->RefDistance, ClampedDist, props->RolloffFactor)}; - if(dist > 0.0f) DryGain.Base *= props->RefDistance / dist; - for(uint i{0};i < NumSends;i++) - { - dist = lerp(props->RefDistance, ClampedDist, RoomRolloff[i]); - if(dist > 0.0f) WetGain[i].Base *= props->RefDistance / dist; - } - } - break; - - case DistanceModel::LinearClamped: - ClampedDist = clampf(ClampedDist, props->RefDistance, props->MaxDistance); - if(props->MaxDistance < props->RefDistance) break; - /*fall-through*/ - case DistanceModel::Linear: - if(!(props->MaxDistance != props->RefDistance)) - ClampedDist = props->RefDistance; - else - { - float attn{props->RolloffFactor * (ClampedDist-props->RefDistance) / - (props->MaxDistance-props->RefDistance)}; - DryGain.Base *= maxf(1.0f - attn, 0.0f); - for(uint i{0};i < NumSends;i++) - { - attn = RoomRolloff[i] * (ClampedDist-props->RefDistance) / - (props->MaxDistance-props->RefDistance); - WetGain[i].Base *= maxf(1.0f - attn, 0.0f); - } - } - break; - - case DistanceModel::ExponentClamped: - ClampedDist = clampf(ClampedDist, props->RefDistance, props->MaxDistance); - if(props->MaxDistance < props->RefDistance) break; - /*fall-through*/ - case DistanceModel::Exponent: - if(!(ClampedDist > 0.0f && props->RefDistance > 0.0f)) - ClampedDist = props->RefDistance; - else - { - const float dist_ratio{ClampedDist/props->RefDistance}; - DryGain.Base *= std::pow(dist_ratio, -props->RolloffFactor); - for(uint i{0};i < NumSends;i++) - WetGain[i].Base *= std::pow(dist_ratio, -RoomRolloff[i]); - } - break; - - case DistanceModel::Disable: - ClampedDist = props->RefDistance; - break; - } - - /* Calculate directional soundcones */ - if(directional && props->InnerAngle < 360.0f) - { - const float Angle{Rad2Deg(std::acos(Direction.dot_product(ToSource)) * ConeScale * -2.0f)}; - - float ConeGain, ConeHF; - if(!(Angle > props->InnerAngle)) - { - ConeGain = 1.0f; - ConeHF = 1.0f; - } - else if(Angle < props->OuterAngle) - { - const float scale{(Angle-props->InnerAngle) / (props->OuterAngle-props->InnerAngle)}; - ConeGain = lerp(1.0f, props->OuterGain, scale); - ConeHF = lerp(1.0f, props->OuterGainHF, scale); - } - else - { - ConeGain = props->OuterGain; - ConeHF = props->OuterGainHF; - } - - DryGain.Base *= ConeGain; - if(props->DryGainHFAuto) - DryGain.HF *= ConeHF; - if(props->WetGainAuto) - std::for_each(std::begin(WetGain), std::begin(WetGain)+NumSends, - [ConeGain](GainTriplet &gain) noexcept -> void { gain.Base *= ConeGain; }); - if(props->WetGainHFAuto) - std::for_each(std::begin(WetGain), std::begin(WetGain)+NumSends, - [ConeHF](GainTriplet &gain) noexcept -> void { gain.HF *= ConeHF; }); - } - - /* Apply gain and frequency filters */ - DryGain.Base = minf(clampf(DryGain.Base, props->MinGain, props->MaxGain) * props->Direct.Gain * - context->mParams.Gain, GainMixMax); - DryGain.HF *= props->Direct.GainHF; - DryGain.LF *= props->Direct.GainLF; - for(uint i{0};i < NumSends;i++) - { - WetGain[i].Base = minf(clampf(WetGain[i].Base, props->MinGain, props->MaxGain) * - props->Send[i].Gain * context->mParams.Gain, GainMixMax); - WetGain[i].HF *= props->Send[i].GainHF; - WetGain[i].LF *= props->Send[i].GainLF; - } - - /* Distance-based air absorption and initial send decay. */ - if(ClampedDist > props->RefDistance && props->RolloffFactor > 0.0f) - { - const float meters_base{(ClampedDist-props->RefDistance) * props->RolloffFactor * - context->mParams.MetersPerUnit}; - if(props->AirAbsorptionFactor > 0.0f) - { - const float hfattn{std::pow(AirAbsorbGainHF, meters_base*props->AirAbsorptionFactor)}; - DryGain.HF *= hfattn; - std::for_each(std::begin(WetGain), std::begin(WetGain)+NumSends, - [hfattn](GainTriplet &gain) noexcept -> void { gain.HF *= hfattn; }); - } - - if(props->WetGainAuto) - { - /* Apply a decay-time transformation to the wet path, based on the - * source distance in meters. The initial decay of the reverb - * effect is calculated and applied to the wet path. - */ - for(uint i{0};i < NumSends;i++) - { - if(!(DecayDistance[i].Base > 0.0f)) - continue; - - const float gain{std::pow(ReverbDecayGain, meters_base/DecayDistance[i].Base)}; - WetGain[i].Base *= gain; - /* Yes, the wet path's air absorption is applied with - * WetGainAuto on, rather than WetGainHFAuto. - */ - if(gain > 0.0f) - { - float gainhf{std::pow(ReverbDecayGain, meters_base/DecayDistance[i].HF)}; - WetGain[i].HF *= minf(gainhf / gain, 1.0f); - float gainlf{std::pow(ReverbDecayGain, meters_base/DecayDistance[i].LF)}; - WetGain[i].LF *= minf(gainlf / gain, 1.0f); - } - } - } - } - - - /* Initial source pitch */ - float Pitch{props->Pitch}; - - /* Calculate velocity-based doppler effect */ - float DopplerFactor{props->DopplerFactor * context->mParams.DopplerFactor}; - if(DopplerFactor > 0.0f) - { - const alu::Vector &lvelocity = context->mParams.Velocity; - float vss{Velocity.dot_product(ToSource) * -DopplerFactor}; - float vls{lvelocity.dot_product(ToSource) * -DopplerFactor}; - - const float SpeedOfSound{context->mParams.SpeedOfSound}; - if(!(vls < SpeedOfSound)) - { - /* Listener moving away from the source at the speed of sound. - * Sound waves can't catch it. - */ - Pitch = 0.0f; - } - else if(!(vss < SpeedOfSound)) - { - /* Source moving toward the listener at the speed of sound. Sound - * waves bunch up to extreme frequencies. - */ - Pitch = std::numeric_limits::infinity(); - } - else - { - /* Source and listener movement is nominal. Calculate the proper - * doppler shift. - */ - Pitch *= (SpeedOfSound-vls) / (SpeedOfSound-vss); - } - } - - /* Adjust pitch based on the buffer and output frequencies, and calculate - * fixed-point stepping value. - */ - Pitch *= static_cast(voice->mFrequency) / static_cast(Device->Frequency); - if(Pitch > float{MaxPitch}) - voice->mStep = MaxPitch<mStep = maxu(fastf2u(Pitch * MixerFracOne), 1); - voice->mResampler = PrepareResampler(props->mResampler, voice->mStep, &voice->mResampleState); - - float spread{0.0f}; - if(props->Radius > Distance) - spread = al::MathDefs::Tau() - Distance/props->Radius*al::MathDefs::Pi(); - else if(Distance > 0.0f) - spread = std::asin(props->Radius/Distance) * 2.0f; - - CalcPanningAndFilters(voice, ToSource[0], ToSource[1], ToSource[2]*ZScale, - Distance*context->mParams.MetersPerUnit, spread, DryGain, WetGain, SendSlots, props, - context->mParams, Device); -} - -void CalcSourceParams(Voice *voice, ALCcontext *context, bool force) -{ - VoicePropsItem *props{voice->mUpdate.exchange(nullptr, std::memory_order_acq_rel)}; - if(!props && !force) return; - - if(props) - { - voice->mProps = *props; - - AtomicReplaceHead(context->mFreeVoiceProps, props); - } - - if((voice->mProps.DirectChannels != DirectMode::Off && voice->mFmtChannels != FmtMono - && voice->mFmtChannels != FmtBFormat2D && voice->mFmtChannels != FmtBFormat3D) - || voice->mProps.mSpatializeMode==SpatializeMode::Off - || (voice->mProps.mSpatializeMode==SpatializeMode::Auto && voice->mFmtChannels != FmtMono)) - CalcNonAttnSourceParams(voice, &voice->mProps, context); - else - CalcAttnSourceParams(voice, &voice->mProps, context); -} - - -void SendSourceStateEvent(ALCcontext *context, uint id, VChangeState state) -{ - RingBuffer *ring{context->mAsyncEvents.get()}; - auto evt_vec = ring->getWriteVector(); - if(evt_vec.first.len < 1) return; - - AsyncEvent *evt{::new(evt_vec.first.buf) AsyncEvent{EventType_SourceStateChange}}; - evt->u.srcstate.id = id; - evt->u.srcstate.state = state; - - ring->writeAdvance(1); -} - -void ProcessVoiceChanges(ALCcontext *ctx) -{ - VoiceChange *cur{ctx->mCurrentVoiceChange.load(std::memory_order_acquire)}; - VoiceChange *next{cur->mNext.load(std::memory_order_acquire)}; - if(!next) return; - - const uint enabledevt{ctx->mEnabledEvts.load(std::memory_order_acquire)}; - do { - cur = next; - - bool sendevt{false}; - if(cur->mState == VChangeState::Reset || cur->mState == VChangeState::Stop) - { - if(Voice *voice{cur->mVoice}) - { - voice->mCurrentBuffer.store(nullptr, std::memory_order_relaxed); - voice->mLoopBuffer.store(nullptr, std::memory_order_relaxed); - /* A source ID indicates the voice was playing or paused, which - * gets a reset/stop event. - */ - sendevt = voice->mSourceID.exchange(0u, std::memory_order_relaxed) != 0u; - Voice::State oldvstate{Voice::Playing}; - voice->mPlayState.compare_exchange_strong(oldvstate, Voice::Stopping, - std::memory_order_relaxed, std::memory_order_acquire); - voice->mPendingChange.store(false, std::memory_order_release); - } - /* Reset state change events are always sent, even if the voice is - * already stopped or even if there is no voice. - */ - sendevt |= (cur->mState == VChangeState::Reset); - } - else if(cur->mState == VChangeState::Pause) - { - Voice *voice{cur->mVoice}; - Voice::State oldvstate{Voice::Playing}; - sendevt = voice->mPlayState.compare_exchange_strong(oldvstate, Voice::Stopping, - std::memory_order_release, std::memory_order_acquire); - } - else if(cur->mState == VChangeState::Play) - { - /* NOTE: When playing a voice, sending a source state change event - * depends if there's an old voice to stop and if that stop is - * successful. If there is no old voice, a playing event is always - * sent. If there is an old voice, an event is sent only if the - * voice is already stopped. - */ - if(Voice *oldvoice{cur->mOldVoice}) - { - oldvoice->mCurrentBuffer.store(nullptr, std::memory_order_relaxed); - oldvoice->mLoopBuffer.store(nullptr, std::memory_order_relaxed); - oldvoice->mSourceID.store(0u, std::memory_order_relaxed); - Voice::State oldvstate{Voice::Playing}; - sendevt = !oldvoice->mPlayState.compare_exchange_strong(oldvstate, Voice::Stopping, - std::memory_order_relaxed, std::memory_order_acquire); - oldvoice->mPendingChange.store(false, std::memory_order_release); - } - else - sendevt = true; - - Voice *voice{cur->mVoice}; - voice->mPlayState.store(Voice::Playing, std::memory_order_release); - } - else if(cur->mState == VChangeState::Restart) - { - /* Restarting a voice never sends a source change event. */ - Voice *oldvoice{cur->mOldVoice}; - oldvoice->mCurrentBuffer.store(nullptr, std::memory_order_relaxed); - oldvoice->mLoopBuffer.store(nullptr, std::memory_order_relaxed); - /* If there's no sourceID, the old voice finished so don't start - * the new one at its new offset. - */ - if(oldvoice->mSourceID.exchange(0u, std::memory_order_relaxed) != 0u) - { - /* Otherwise, set the voice to stopping if it's not already (it - * might already be, if paused), and play the new voice as - * appropriate. - */ - Voice::State oldvstate{Voice::Playing}; - oldvoice->mPlayState.compare_exchange_strong(oldvstate, Voice::Stopping, - std::memory_order_relaxed, std::memory_order_acquire); - - Voice *voice{cur->mVoice}; - voice->mPlayState.store((oldvstate == Voice::Playing) ? Voice::Playing - : Voice::Stopped, std::memory_order_release); - } - oldvoice->mPendingChange.store(false, std::memory_order_release); - } - if(sendevt && (enabledevt&EventType_SourceStateChange)) - SendSourceStateEvent(ctx, cur->mSourceID, cur->mState); - - next = cur->mNext.load(std::memory_order_acquire); - } while(next); - ctx->mCurrentVoiceChange.store(cur, std::memory_order_release); -} - -void ProcessParamUpdates(ALCcontext *ctx, const EffectSlotArray &slots, - const al::span voices) -{ - ProcessVoiceChanges(ctx); - - IncrementRef(ctx->mUpdateCount); - if LIKELY(!ctx->mHoldUpdates.load(std::memory_order_acquire)) - { - bool force{CalcContextParams(ctx)}; - force |= CalcListenerParams(ctx); - auto sorted_slots = const_cast(slots.data() + slots.size()); - for(EffectSlot *slot : slots) - force |= CalcEffectSlotParams(slot, sorted_slots, ctx); - - for(Voice *voice : voices) - { - /* Only update voices that have a source. */ - if(voice->mSourceID.load(std::memory_order_relaxed) != 0) - CalcSourceParams(voice, ctx, force); - } - } - IncrementRef(ctx->mUpdateCount); -} - -void ProcessContexts(ALCdevice *device, const uint SamplesToDo) -{ - ASSUME(SamplesToDo > 0); - - for(ALCcontext *ctx : *device->mContexts.load(std::memory_order_acquire)) - { - const EffectSlotArray &auxslots = *ctx->mActiveAuxSlots.load(std::memory_order_acquire); - const al::span voices{ctx->getVoicesSpanAcquired()}; - - /* Process pending propery updates for objects on the context. */ - ProcessParamUpdates(ctx, auxslots, voices); - - /* Clear auxiliary effect slot mixing buffers. */ - for(EffectSlot *slot : auxslots) - { - for(auto &buffer : slot->Wet.Buffer) - buffer.fill(0.0f); - } - - /* Process voices that have a playing source. */ - for(Voice *voice : voices) - { - const Voice::State vstate{voice->mPlayState.load(std::memory_order_acquire)}; - if(vstate != Voice::Stopped && vstate != Voice::Pending) - voice->mix(vstate, ctx, SamplesToDo); - } - - /* Process effects. */ - if(const size_t num_slots{auxslots.size()}) - { - auto slots = auxslots.data(); - auto slots_end = slots + num_slots; - - /* Sort the slots into extra storage, so that effect slots come - * before their effect slot target (or their targets' target). - */ - const al::span sorted_slots{const_cast(slots_end), - num_slots}; - /* Skip sorting if it has already been done. */ - if(!sorted_slots[0]) - { - /* First, copy the slots to the sorted list, then partition the - * sorted list so that all slots without a target slot go to - * the end. - */ - std::copy(slots, slots_end, sorted_slots.begin()); - auto split_point = std::partition(sorted_slots.begin(), sorted_slots.end(), - [](const EffectSlot *slot) noexcept -> bool - { return slot->Target != nullptr; }); - /* There must be at least one slot without a slot target. */ - assert(split_point != sorted_slots.end()); - - /* Simple case: no more than 1 slot has a target slot. Either - * all slots go right to the output, or the remaining one must - * target an already-partitioned slot. - */ - if(split_point - sorted_slots.begin() > 1) - { - /* At least two slots target other slots. Starting from the - * back of the sorted list, continue partitioning the front - * of the list given each target until all targets are - * accounted for. This ensures all slots without a target - * go last, all slots directly targeting those last slots - * go second-to-last, all slots directly targeting those - * second-last slots go third-to-last, etc. - */ - auto next_target = sorted_slots.end(); - do { - /* This shouldn't happen, but if there's unsorted slots - * left that don't target any sorted slots, they can't - * contribute to the output, so leave them. - */ - if UNLIKELY(next_target == split_point) - break; - - --next_target; - split_point = std::partition(sorted_slots.begin(), split_point, - [next_target](const EffectSlot *slot) noexcept -> bool - { return slot->Target != *next_target; }); - } while(split_point - sorted_slots.begin() > 1); - } - } - - for(const EffectSlot *slot : sorted_slots) - { - EffectState *state{slot->mEffectState}; - state->process(SamplesToDo, slot->Wet.Buffer, state->mOutTarget); - } - } - - /* Signal the event handler if there are any events to read. */ - RingBuffer *ring{ctx->mAsyncEvents.get()}; - if(ring->readSpace() > 0) - ctx->mEventSem.post(); - } -} - - -void ApplyDistanceComp(const al::span Samples, const size_t SamplesToDo, - const DistanceComp::ChanData *distcomp) -{ - ASSUME(SamplesToDo > 0); - - for(auto &chanbuffer : Samples) - { - const float gain{distcomp->Gain}; - const size_t base{distcomp->Length}; - float *distbuf{al::assume_aligned<16>(distcomp->Buffer)}; - ++distcomp; - - if(base < 1) - continue; - - float *inout{al::assume_aligned<16>(chanbuffer.data())}; - auto inout_end = inout + SamplesToDo; - if LIKELY(SamplesToDo >= base) - { - auto delay_end = std::rotate(inout, inout_end - base, inout_end); - std::swap_ranges(inout, delay_end, distbuf); - } - else - { - auto delay_start = std::swap_ranges(inout, inout_end, distbuf); - std::rotate(distbuf, delay_start, distbuf + base); - } - std::transform(inout, inout_end, inout, std::bind(std::multiplies{}, _1, gain)); - } -} - -void ApplyDither(const al::span Samples, uint *dither_seed, - const float quant_scale, const size_t SamplesToDo) -{ - ASSUME(SamplesToDo > 0); - - /* Dithering. Generate whitenoise (uniform distribution of random values - * between -1 and +1) and add it to the sample values, after scaling up to - * the desired quantization depth amd before rounding. - */ - const float invscale{1.0f / quant_scale}; - uint seed{*dither_seed}; - auto dither_sample = [&seed,invscale,quant_scale](const float sample) noexcept -> float - { - float val{sample * quant_scale}; - uint rng0{dither_rng(&seed)}; - uint rng1{dither_rng(&seed)}; - val += static_cast(rng0*(1.0/UINT_MAX) - rng1*(1.0/UINT_MAX)); - return fast_roundf(val) * invscale; - }; - for(FloatBufferLine &inout : Samples) - std::transform(inout.begin(), inout.begin()+SamplesToDo, inout.begin(), dither_sample); - *dither_seed = seed; -} - - -/* Base template left undefined. Should be marked =delete, but Clang 3.8.1 - * chokes on that given the inline specializations. - */ -template -inline T SampleConv(float) noexcept; - -template<> inline float SampleConv(float val) noexcept -{ return val; } -template<> inline int32_t SampleConv(float val) noexcept -{ - /* Floats have a 23-bit mantissa, plus an implied 1 bit and a sign bit. - * This means a normalized float has at most 25 bits of signed precision. - * When scaling and clamping for a signed 32-bit integer, these following - * values are the best a float can give. - */ - return fastf2i(clampf(val*2147483648.0f, -2147483648.0f, 2147483520.0f)); -} -template<> inline int16_t SampleConv(float val) noexcept -{ return static_cast(fastf2i(clampf(val*32768.0f, -32768.0f, 32767.0f))); } -template<> inline int8_t SampleConv(float val) noexcept -{ return static_cast(fastf2i(clampf(val*128.0f, -128.0f, 127.0f))); } - -/* Define unsigned output variations. */ -template<> inline uint32_t SampleConv(float val) noexcept -{ return static_cast(SampleConv(val)) + 2147483648u; } -template<> inline uint16_t SampleConv(float val) noexcept -{ return static_cast(SampleConv(val) + 32768); } -template<> inline uint8_t SampleConv(float val) noexcept -{ return static_cast(SampleConv(val) + 128); } - -template -void Write(const al::span InBuffer, void *OutBuffer, const size_t Offset, - const size_t SamplesToDo, const size_t FrameStep) -{ - ASSUME(FrameStep > 0); - ASSUME(SamplesToDo > 0); - - DevFmtType_t *outbase = static_cast*>(OutBuffer) + Offset*FrameStep; - for(const FloatBufferLine &inbuf : InBuffer) - { - DevFmtType_t *out{outbase++}; - auto conv_sample = [FrameStep,&out](const float s) noexcept -> void - { - *out = SampleConv>(s); - out += FrameStep; - }; - std::for_each(inbuf.begin(), inbuf.begin()+SamplesToDo, conv_sample); - } -} - -} // namespace - -void ALCdevice::renderSamples(void *outBuffer, const uint numSamples, const size_t frameStep) -{ - FPUCtl mixer_mode{}; - for(uint written{0u};written < numSamples;) - { - const uint samplesToDo{minu(numSamples-written, BufferLineSize)}; - - /* Clear main mixing buffers. */ - for(FloatBufferLine &buffer : MixBuffer) - buffer.fill(0.0f); - - /* Increment the mix count at the start (lsb should now be 1). */ - IncrementRef(MixCount); - - /* Process and mix each context's sources and effects. */ - ProcessContexts(this, samplesToDo); - - /* Increment the clock time. Every second's worth of samples is - * converted and added to clock base so that large sample counts don't - * overflow during conversion. This also guarantees a stable - * conversion. - */ - SamplesDone += samplesToDo; - ClockBase += std::chrono::seconds{SamplesDone / Frequency}; - SamplesDone %= Frequency; - - /* Increment the mix count at the end (lsb should now be 0). */ - IncrementRef(MixCount); - - /* Apply any needed post-process for finalizing the Dry mix to the - * RealOut (Ambisonic decode, UHJ encode, etc). - */ - postProcess(samplesToDo); - - /* Apply compression, limiting sample amplitude if needed or desired. */ - if(Limiter) Limiter->process(samplesToDo, RealOut.Buffer.data()); - - /* Apply delays and attenuation for mismatched speaker distances. */ - if(ChannelDelays) - ApplyDistanceComp(RealOut.Buffer, samplesToDo, ChannelDelays->mChannels.data()); - - /* Apply dithering. The compressor should have left enough headroom for - * the dither noise to not saturate. - */ - if(DitherDepth > 0.0f) - ApplyDither(RealOut.Buffer, &DitherSeed, DitherDepth, samplesToDo); - - if LIKELY(outBuffer) - { - /* Finally, interleave and convert samples, writing to the device's - * output buffer. - */ - switch(FmtType) - { -#define HANDLE_WRITE(T) case T: \ - Write(RealOut.Buffer, outBuffer, written, samplesToDo, frameStep); break; - HANDLE_WRITE(DevFmtByte) - HANDLE_WRITE(DevFmtUByte) - HANDLE_WRITE(DevFmtShort) - HANDLE_WRITE(DevFmtUShort) - HANDLE_WRITE(DevFmtInt) - HANDLE_WRITE(DevFmtUInt) - HANDLE_WRITE(DevFmtFloat) -#undef HANDLE_WRITE - } - } - - written += samplesToDo; - } -} - -void ALCdevice::handleDisconnect(const char *msg, ...) -{ - if(!Connected.exchange(false, std::memory_order_acq_rel)) - return; - - AsyncEvent evt{EventType_Disconnected}; - - va_list args; - va_start(args, msg); - int msglen{vsnprintf(evt.u.disconnect.msg, sizeof(evt.u.disconnect.msg), msg, args)}; - va_end(args); - - if(msglen < 0 || static_cast(msglen) >= sizeof(evt.u.disconnect.msg)) - evt.u.disconnect.msg[sizeof(evt.u.disconnect.msg)-1] = 0; - - IncrementRef(MixCount); - for(ALCcontext *ctx : *mContexts.load()) - { - const uint enabledevt{ctx->mEnabledEvts.load(std::memory_order_acquire)}; - if((enabledevt&EventType_Disconnected)) - { - RingBuffer *ring{ctx->mAsyncEvents.get()}; - auto evt_data = ring->getWriteVector().first; - if(evt_data.len > 0) - { - ::new(evt_data.buf) AsyncEvent{evt}; - ring->writeAdvance(1); - ctx->mEventSem.post(); - } - } - - auto voicelist = ctx->getVoicesSpanAcquired(); - auto stop_voice = [](Voice *voice) -> void - { - voice->mCurrentBuffer.store(nullptr, std::memory_order_relaxed); - voice->mLoopBuffer.store(nullptr, std::memory_order_relaxed); - voice->mSourceID.store(0u, std::memory_order_relaxed); - voice->mPlayState.store(Voice::Stopped, std::memory_order_release); - }; - std::for_each(voicelist.begin(), voicelist.end(), stop_voice); - } - IncrementRef(MixCount); -} diff --git a/alc/alu.h b/alc/alu.h deleted file mode 100644 index 2aa1a652..00000000 --- a/alc/alu.h +++ /dev/null @@ -1,141 +0,0 @@ -#ifndef ALU_H -#define ALU_H - -#include -#include -#include -#include - -#include "alspan.h" -#include "core/ambidefs.h" -#include "core/bufferline.h" -#include "core/devformat.h" - -struct ALCcontext; -struct ALCdevice; -struct EffectSlot; -struct MixParams; - - -#define MAX_SENDS 6 - - -using MixerFunc = void(*)(const al::span InSamples, - const al::span OutBuffer, float *CurrentGains, const float *TargetGains, - const size_t Counter, const size_t OutPos); - -extern MixerFunc MixSamples; - - -constexpr float GainMixMax{1000.0f}; /* +60dB */ - -constexpr float SpeedOfSoundMetersPerSec{343.3f}; -constexpr float AirAbsorbGainHF{0.99426f}; /* -0.05dB */ - -/** Target gain for the reverb decay feedback reaching the decay time. */ -constexpr float ReverbDecayGain{0.001f}; /* -60 dB */ - - -enum HrtfRequestMode { - Hrtf_Default = 0, - Hrtf_Enable = 1, - Hrtf_Disable = 2, -}; - -void aluInit(void); - -void aluInitMixer(void); - -/* aluInitRenderer - * - * Set up the appropriate panning method and mixing method given the device - * properties. - */ -void aluInitRenderer(ALCdevice *device, int hrtf_id, HrtfRequestMode hrtf_appreq, - HrtfRequestMode hrtf_userreq); - -void aluInitEffectPanning(EffectSlot *slot, ALCcontext *context); - -/** - * Calculates ambisonic encoder coefficients using the X, Y, and Z direction - * components, which must represent a normalized (unit length) vector, and the - * spread is the angular width of the sound (0...tau). - * - * NOTE: The components use ambisonic coordinates. As a result: - * - * Ambisonic Y = OpenAL -X - * Ambisonic Z = OpenAL Y - * Ambisonic X = OpenAL -Z - * - * The components are ordered such that OpenAL's X, Y, and Z are the first, - * second, and third parameters respectively -- simply negate X and Z. - */ -std::array CalcAmbiCoeffs(const float y, const float z, const float x, - const float spread); - -/** - * CalcDirectionCoeffs - * - * Calculates ambisonic coefficients based on an OpenAL direction vector. The - * vector must be normalized (unit length), and the spread is the angular width - * of the sound (0...tau). - */ -inline std::array CalcDirectionCoeffs(const float (&dir)[3], - const float spread) -{ - /* Convert from OpenAL coords to Ambisonics. */ - return CalcAmbiCoeffs(-dir[0], dir[1], -dir[2], spread); -} - -/** - * CalcAngleCoeffs - * - * Calculates ambisonic coefficients based on azimuth and elevation. The - * azimuth and elevation parameters are in radians, going right and up - * respectively. - */ -inline std::array CalcAngleCoeffs(const float azimuth, - const float elevation, const float spread) -{ - const float x{-std::sin(azimuth) * std::cos(elevation)}; - const float y{ std::sin(elevation)}; - const float z{ std::cos(azimuth) * std::cos(elevation)}; - - return CalcAmbiCoeffs(x, y, z, spread); -} - - -/** - * ComputePanGains - * - * Computes panning gains using the given channel decoder coefficients and the - * pre-calculated direction or angle coefficients. For B-Format sources, the - * coeffs are a 'slice' of a transform matrix for the input channel, used to - * scale and orient the sound samples. - */ -void ComputePanGains(const MixParams *mix, const float*RESTRICT coeffs, const float ingain, - const al::span gains); - - -/** Helper to set an identity/pass-through panning for ambisonic mixing (3D input). */ -template -auto SetAmbiPanIdentity(T iter, I count, F func) -> std::enable_if_t::value> -{ - if(count < 1) return; - - std::array coeffs{{1.0f}}; - func(*iter, coeffs); - ++iter; - for(I i{1};i < count;++i,++iter) - { - coeffs[i-1] = 0.0f; - coeffs[i ] = 1.0f; - func(*iter, coeffs); - } -} - - -extern const float ConeScale; -extern const float ZScale; - -#endif diff --git a/alc/async_event.h b/alc/async_event.h deleted file mode 100644 index 1ee58b10..00000000 --- a/alc/async_event.h +++ /dev/null @@ -1,49 +0,0 @@ -#ifndef ALC_EVENT_H -#define ALC_EVENT_H - -#include "almalloc.h" - -struct EffectState; -enum class VChangeState; - -using uint = unsigned int; - - -enum { - /* End event thread processing. */ - EventType_KillThread = 0, - - /* User event types. */ - EventType_SourceStateChange = 1<<0, - EventType_BufferCompleted = 1<<1, - EventType_Disconnected = 1<<2, - - /* Internal events. */ - EventType_ReleaseEffectState = 65536, -}; - -struct AsyncEvent { - uint EnumType{0u}; - union { - char dummy; - struct { - uint id; - VChangeState state; - } srcstate; - struct { - uint id; - uint count; - } bufcomp; - struct { - char msg[244]; - } disconnect; - EffectState *mEffectState; - } u{}; - - AsyncEvent() noexcept = default; - constexpr AsyncEvent(uint type) noexcept : EnumType{type} { } - - DISABLE_ALLOC() -}; - -#endif diff --git a/alc/backends/alsa.cpp b/alc/backends/alsa.cpp deleted file mode 100644 index bdfdd040..00000000 --- a/alc/backends/alsa.cpp +++ /dev/null @@ -1,1268 +0,0 @@ -/** - * OpenAL cross platform audio library - * Copyright (C) 1999-2007 by authors. - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - * Or go to http://www.gnu.org/copyleft/lgpl.html - */ - -#include "config.h" - -#include "backends/alsa.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "albyte.h" -#include "alcmain.h" -#include "alconfig.h" -#include "almalloc.h" -#include "alnumeric.h" -#include "aloptional.h" -#include "alu.h" -#include "core/logging.h" -#include "dynload.h" -#include "ringbuffer.h" -#include "threads.h" -#include "vector.h" - -#include - - -namespace { - -constexpr char alsaDevice[] = "ALSA Default"; - - -#ifdef HAVE_DYNLOAD -#define ALSA_FUNCS(MAGIC) \ - MAGIC(snd_strerror); \ - MAGIC(snd_pcm_open); \ - MAGIC(snd_pcm_close); \ - MAGIC(snd_pcm_nonblock); \ - MAGIC(snd_pcm_frames_to_bytes); \ - MAGIC(snd_pcm_bytes_to_frames); \ - MAGIC(snd_pcm_hw_params_malloc); \ - MAGIC(snd_pcm_hw_params_free); \ - MAGIC(snd_pcm_hw_params_any); \ - MAGIC(snd_pcm_hw_params_current); \ - MAGIC(snd_pcm_hw_params_set_access); \ - MAGIC(snd_pcm_hw_params_set_format); \ - MAGIC(snd_pcm_hw_params_set_channels); \ - MAGIC(snd_pcm_hw_params_set_periods_near); \ - MAGIC(snd_pcm_hw_params_set_rate_near); \ - MAGIC(snd_pcm_hw_params_set_rate); \ - MAGIC(snd_pcm_hw_params_set_rate_resample); \ - MAGIC(snd_pcm_hw_params_set_buffer_time_near); \ - MAGIC(snd_pcm_hw_params_set_period_time_near); \ - MAGIC(snd_pcm_hw_params_set_buffer_size_near); \ - MAGIC(snd_pcm_hw_params_set_period_size_near); \ - MAGIC(snd_pcm_hw_params_set_buffer_size_min); \ - MAGIC(snd_pcm_hw_params_get_buffer_time_min); \ - MAGIC(snd_pcm_hw_params_get_buffer_time_max); \ - MAGIC(snd_pcm_hw_params_get_period_time_min); \ - MAGIC(snd_pcm_hw_params_get_period_time_max); \ - MAGIC(snd_pcm_hw_params_get_buffer_size); \ - MAGIC(snd_pcm_hw_params_get_period_size); \ - MAGIC(snd_pcm_hw_params_get_access); \ - MAGIC(snd_pcm_hw_params_get_periods); \ - MAGIC(snd_pcm_hw_params_test_format); \ - MAGIC(snd_pcm_hw_params_test_channels); \ - MAGIC(snd_pcm_hw_params); \ - MAGIC(snd_pcm_sw_params_malloc); \ - MAGIC(snd_pcm_sw_params_current); \ - MAGIC(snd_pcm_sw_params_set_avail_min); \ - MAGIC(snd_pcm_sw_params_set_stop_threshold); \ - MAGIC(snd_pcm_sw_params); \ - MAGIC(snd_pcm_sw_params_free); \ - MAGIC(snd_pcm_prepare); \ - MAGIC(snd_pcm_start); \ - MAGIC(snd_pcm_resume); \ - MAGIC(snd_pcm_reset); \ - MAGIC(snd_pcm_wait); \ - MAGIC(snd_pcm_delay); \ - MAGIC(snd_pcm_state); \ - MAGIC(snd_pcm_avail_update); \ - MAGIC(snd_pcm_areas_silence); \ - MAGIC(snd_pcm_mmap_begin); \ - MAGIC(snd_pcm_mmap_commit); \ - MAGIC(snd_pcm_readi); \ - MAGIC(snd_pcm_writei); \ - MAGIC(snd_pcm_drain); \ - MAGIC(snd_pcm_drop); \ - MAGIC(snd_pcm_recover); \ - MAGIC(snd_pcm_info_malloc); \ - MAGIC(snd_pcm_info_free); \ - MAGIC(snd_pcm_info_set_device); \ - MAGIC(snd_pcm_info_set_subdevice); \ - MAGIC(snd_pcm_info_set_stream); \ - MAGIC(snd_pcm_info_get_name); \ - MAGIC(snd_ctl_pcm_next_device); \ - MAGIC(snd_ctl_pcm_info); \ - MAGIC(snd_ctl_open); \ - MAGIC(snd_ctl_close); \ - MAGIC(snd_ctl_card_info_malloc); \ - MAGIC(snd_ctl_card_info_free); \ - MAGIC(snd_ctl_card_info); \ - MAGIC(snd_ctl_card_info_get_name); \ - MAGIC(snd_ctl_card_info_get_id); \ - MAGIC(snd_card_next); \ - MAGIC(snd_config_update_free_global) - -static void *alsa_handle; -#define MAKE_FUNC(f) decltype(f) * p##f -ALSA_FUNCS(MAKE_FUNC); -#undef MAKE_FUNC - -#ifndef IN_IDE_PARSER -#define snd_strerror psnd_strerror -#define snd_pcm_open psnd_pcm_open -#define snd_pcm_close psnd_pcm_close -#define snd_pcm_nonblock psnd_pcm_nonblock -#define snd_pcm_frames_to_bytes psnd_pcm_frames_to_bytes -#define snd_pcm_bytes_to_frames psnd_pcm_bytes_to_frames -#define snd_pcm_hw_params_malloc psnd_pcm_hw_params_malloc -#define snd_pcm_hw_params_free psnd_pcm_hw_params_free -#define snd_pcm_hw_params_any psnd_pcm_hw_params_any -#define snd_pcm_hw_params_current psnd_pcm_hw_params_current -#define snd_pcm_hw_params_set_access psnd_pcm_hw_params_set_access -#define snd_pcm_hw_params_set_format psnd_pcm_hw_params_set_format -#define snd_pcm_hw_params_set_channels psnd_pcm_hw_params_set_channels -#define snd_pcm_hw_params_set_periods_near psnd_pcm_hw_params_set_periods_near -#define snd_pcm_hw_params_set_rate_near psnd_pcm_hw_params_set_rate_near -#define snd_pcm_hw_params_set_rate psnd_pcm_hw_params_set_rate -#define snd_pcm_hw_params_set_rate_resample psnd_pcm_hw_params_set_rate_resample -#define snd_pcm_hw_params_set_buffer_time_near psnd_pcm_hw_params_set_buffer_time_near -#define snd_pcm_hw_params_set_period_time_near psnd_pcm_hw_params_set_period_time_near -#define snd_pcm_hw_params_set_buffer_size_near psnd_pcm_hw_params_set_buffer_size_near -#define snd_pcm_hw_params_set_period_size_near psnd_pcm_hw_params_set_period_size_near -#define snd_pcm_hw_params_set_buffer_size_min psnd_pcm_hw_params_set_buffer_size_min -#define snd_pcm_hw_params_get_buffer_time_min psnd_pcm_hw_params_get_buffer_time_min -#define snd_pcm_hw_params_get_buffer_time_max psnd_pcm_hw_params_get_buffer_time_max -#define snd_pcm_hw_params_get_period_time_min psnd_pcm_hw_params_get_period_time_min -#define snd_pcm_hw_params_get_period_time_max psnd_pcm_hw_params_get_period_time_max -#define snd_pcm_hw_params_get_buffer_size psnd_pcm_hw_params_get_buffer_size -#define snd_pcm_hw_params_get_period_size psnd_pcm_hw_params_get_period_size -#define snd_pcm_hw_params_get_access psnd_pcm_hw_params_get_access -#define snd_pcm_hw_params_get_periods psnd_pcm_hw_params_get_periods -#define snd_pcm_hw_params_test_format psnd_pcm_hw_params_test_format -#define snd_pcm_hw_params_test_channels psnd_pcm_hw_params_test_channels -#define snd_pcm_hw_params psnd_pcm_hw_params -#define snd_pcm_sw_params_malloc psnd_pcm_sw_params_malloc -#define snd_pcm_sw_params_current psnd_pcm_sw_params_current -#define snd_pcm_sw_params_set_avail_min psnd_pcm_sw_params_set_avail_min -#define snd_pcm_sw_params_set_stop_threshold psnd_pcm_sw_params_set_stop_threshold -#define snd_pcm_sw_params psnd_pcm_sw_params -#define snd_pcm_sw_params_free psnd_pcm_sw_params_free -#define snd_pcm_prepare psnd_pcm_prepare -#define snd_pcm_start psnd_pcm_start -#define snd_pcm_resume psnd_pcm_resume -#define snd_pcm_reset psnd_pcm_reset -#define snd_pcm_wait psnd_pcm_wait -#define snd_pcm_delay psnd_pcm_delay -#define snd_pcm_state psnd_pcm_state -#define snd_pcm_avail_update psnd_pcm_avail_update -#define snd_pcm_areas_silence psnd_pcm_areas_silence -#define snd_pcm_mmap_begin psnd_pcm_mmap_begin -#define snd_pcm_mmap_commit psnd_pcm_mmap_commit -#define snd_pcm_readi psnd_pcm_readi -#define snd_pcm_writei psnd_pcm_writei -#define snd_pcm_drain psnd_pcm_drain -#define snd_pcm_drop psnd_pcm_drop -#define snd_pcm_recover psnd_pcm_recover -#define snd_pcm_info_malloc psnd_pcm_info_malloc -#define snd_pcm_info_free psnd_pcm_info_free -#define snd_pcm_info_set_device psnd_pcm_info_set_device -#define snd_pcm_info_set_subdevice psnd_pcm_info_set_subdevice -#define snd_pcm_info_set_stream psnd_pcm_info_set_stream -#define snd_pcm_info_get_name psnd_pcm_info_get_name -#define snd_ctl_pcm_next_device psnd_ctl_pcm_next_device -#define snd_ctl_pcm_info psnd_ctl_pcm_info -#define snd_ctl_open psnd_ctl_open -#define snd_ctl_close psnd_ctl_close -#define snd_ctl_card_info_malloc psnd_ctl_card_info_malloc -#define snd_ctl_card_info_free psnd_ctl_card_info_free -#define snd_ctl_card_info psnd_ctl_card_info -#define snd_ctl_card_info_get_name psnd_ctl_card_info_get_name -#define snd_ctl_card_info_get_id psnd_ctl_card_info_get_id -#define snd_card_next psnd_card_next -#define snd_config_update_free_global psnd_config_update_free_global -#endif -#endif - - -struct HwParamsDeleter { - void operator()(snd_pcm_hw_params_t *ptr) { snd_pcm_hw_params_free(ptr); } -}; -using HwParamsPtr = std::unique_ptr; -HwParamsPtr CreateHwParams() -{ - snd_pcm_hw_params_t *hp{}; - snd_pcm_hw_params_malloc(&hp); - return HwParamsPtr{hp}; -} - -struct SwParamsDeleter { - void operator()(snd_pcm_sw_params_t *ptr) { snd_pcm_sw_params_free(ptr); } -}; -using SwParamsPtr = std::unique_ptr; -SwParamsPtr CreateSwParams() -{ - snd_pcm_sw_params_t *sp{}; - snd_pcm_sw_params_malloc(&sp); - return SwParamsPtr{sp}; -} - - -struct DevMap { - std::string name; - std::string device_name; -}; - -al::vector PlaybackDevices; -al::vector CaptureDevices; - - -const char *prefix_name(snd_pcm_stream_t stream) -{ - assert(stream == SND_PCM_STREAM_PLAYBACK || stream == SND_PCM_STREAM_CAPTURE); - return (stream==SND_PCM_STREAM_PLAYBACK) ? "device-prefix" : "capture-prefix"; -} - -al::vector probe_devices(snd_pcm_stream_t stream) -{ - al::vector devlist; - - snd_ctl_card_info_t *info; - snd_ctl_card_info_malloc(&info); - snd_pcm_info_t *pcminfo; - snd_pcm_info_malloc(&pcminfo); - - devlist.emplace_back(DevMap{alsaDevice, - GetConfigValue(nullptr, "alsa", (stream==SND_PCM_STREAM_PLAYBACK) ? "device" : "capture", - "default")}); - - const char *customdevs{GetConfigValue(nullptr, "alsa", - (stream == SND_PCM_STREAM_PLAYBACK) ? "custom-devices" : "custom-captures", "")}; - while(const char *curdev{customdevs}) - { - if(!curdev[0]) break; - customdevs = strchr(curdev, ';'); - const char *sep{strchr(curdev, '=')}; - if(!sep) - { - std::string spec{customdevs ? std::string(curdev, customdevs++) : std::string(curdev)}; - ERR("Invalid ALSA device specification \"%s\"\n", spec.c_str()); - continue; - } - - const char *oldsep{sep++}; - devlist.emplace_back(DevMap{std::string(curdev, oldsep), - customdevs ? std::string(sep, customdevs++) : std::string(sep)}); - const auto &entry = devlist.back(); - TRACE("Got device \"%s\", \"%s\"\n", entry.name.c_str(), entry.device_name.c_str()); - } - - const std::string main_prefix{ - ConfigValueStr(nullptr, "alsa", prefix_name(stream)).value_or("plughw:")}; - - int card{-1}; - int err{snd_card_next(&card)}; - for(;err >= 0 && card >= 0;err = snd_card_next(&card)) - { - std::string name{"hw:" + std::to_string(card)}; - - snd_ctl_t *handle; - if((err=snd_ctl_open(&handle, name.c_str(), 0)) < 0) - { - ERR("control open (hw:%d): %s\n", card, snd_strerror(err)); - continue; - } - if((err=snd_ctl_card_info(handle, info)) < 0) - { - ERR("control hardware info (hw:%d): %s\n", card, snd_strerror(err)); - snd_ctl_close(handle); - continue; - } - - const char *cardname{snd_ctl_card_info_get_name(info)}; - const char *cardid{snd_ctl_card_info_get_id(info)}; - name = prefix_name(stream); - name += '-'; - name += cardid; - const std::string card_prefix{ - ConfigValueStr(nullptr, "alsa", name.c_str()).value_or(main_prefix)}; - - int dev{-1}; - while(1) - { - if(snd_ctl_pcm_next_device(handle, &dev) < 0) - ERR("snd_ctl_pcm_next_device failed\n"); - if(dev < 0) break; - - snd_pcm_info_set_device(pcminfo, static_cast(dev)); - snd_pcm_info_set_subdevice(pcminfo, 0); - snd_pcm_info_set_stream(pcminfo, stream); - if((err=snd_ctl_pcm_info(handle, pcminfo)) < 0) - { - if(err != -ENOENT) - ERR("control digital audio info (hw:%d): %s\n", card, snd_strerror(err)); - continue; - } - - /* "prefix-cardid-dev" */ - name = prefix_name(stream); - name += '-'; - name += cardid; - name += '-'; - name += std::to_string(dev); - const std::string device_prefix{ - ConfigValueStr(nullptr, "alsa", name.c_str()).value_or(card_prefix)}; - - /* "CardName, PcmName (CARD=cardid,DEV=dev)" */ - name = cardname; - name += ", "; - name += snd_pcm_info_get_name(pcminfo); - name += " (CARD="; - name += cardid; - name += ",DEV="; - name += std::to_string(dev); - name += ')'; - - /* "devprefixCARD=cardid,DEV=dev" */ - std::string device{device_prefix}; - device += "CARD="; - device += cardid; - device += ",DEV="; - device += std::to_string(dev); - - devlist.emplace_back(DevMap{std::move(name), std::move(device)}); - const auto &entry = devlist.back(); - TRACE("Got device \"%s\", \"%s\"\n", entry.name.c_str(), entry.device_name.c_str()); - } - snd_ctl_close(handle); - } - if(err < 0) - ERR("snd_card_next failed: %s\n", snd_strerror(err)); - - snd_pcm_info_free(pcminfo); - snd_ctl_card_info_free(info); - - return devlist; -} - - -int verify_state(snd_pcm_t *handle) -{ - snd_pcm_state_t state{snd_pcm_state(handle)}; - - int err; - switch(state) - { - case SND_PCM_STATE_OPEN: - case SND_PCM_STATE_SETUP: - case SND_PCM_STATE_PREPARED: - case SND_PCM_STATE_RUNNING: - case SND_PCM_STATE_DRAINING: - case SND_PCM_STATE_PAUSED: - /* All Okay */ - break; - - case SND_PCM_STATE_XRUN: - if((err=snd_pcm_recover(handle, -EPIPE, 1)) < 0) - return err; - break; - case SND_PCM_STATE_SUSPENDED: - if((err=snd_pcm_recover(handle, -ESTRPIPE, 1)) < 0) - return err; - break; - case SND_PCM_STATE_DISCONNECTED: - return -ENODEV; - } - - return state; -} - - -struct AlsaPlayback final : public BackendBase { - AlsaPlayback(ALCdevice *device) noexcept : BackendBase{device} { } - ~AlsaPlayback() override; - - int mixerProc(); - int mixerNoMMapProc(); - - void open(const char *name) override; - bool reset() override; - void start() override; - void stop() override; - - ClockLatency getClockLatency() override; - - snd_pcm_t *mPcmHandle{nullptr}; - - std::mutex mMutex; - - al::vector mBuffer; - - std::atomic mKillNow{true}; - std::thread mThread; - - DEF_NEWDEL(AlsaPlayback) -}; - -AlsaPlayback::~AlsaPlayback() -{ - if(mPcmHandle) - snd_pcm_close(mPcmHandle); - mPcmHandle = nullptr; -} - - -int AlsaPlayback::mixerProc() -{ - SetRTPriority(); - althrd_setname(MIXER_THREAD_NAME); - - const size_t samplebits{mDevice->bytesFromFmt() * 8}; - const snd_pcm_uframes_t update_size{mDevice->UpdateSize}; - const snd_pcm_uframes_t buffer_size{mDevice->BufferSize}; - while(!mKillNow.load(std::memory_order_acquire)) - { - int state{verify_state(mPcmHandle)}; - if(state < 0) - { - ERR("Invalid state detected: %s\n", snd_strerror(state)); - mDevice->handleDisconnect("Bad state: %s", snd_strerror(state)); - break; - } - - snd_pcm_sframes_t avails{snd_pcm_avail_update(mPcmHandle)}; - if(avails < 0) - { - ERR("available update failed: %s\n", snd_strerror(static_cast(avails))); - continue; - } - snd_pcm_uframes_t avail{static_cast(avails)}; - - if(avail > buffer_size) - { - WARN("available samples exceeds the buffer size\n"); - snd_pcm_reset(mPcmHandle); - continue; - } - - // make sure there's frames to process - if(avail < update_size) - { - if(state != SND_PCM_STATE_RUNNING) - { - int err{snd_pcm_start(mPcmHandle)}; - if(err < 0) - { - ERR("start failed: %s\n", snd_strerror(err)); - continue; - } - } - if(snd_pcm_wait(mPcmHandle, 1000) == 0) - ERR("Wait timeout... buffer size too low?\n"); - continue; - } - avail -= avail%update_size; - - // it is possible that contiguous areas are smaller, thus we use a loop - std::lock_guard _{mMutex}; - while(avail > 0) - { - snd_pcm_uframes_t frames{avail}; - - const snd_pcm_channel_area_t *areas{}; - snd_pcm_uframes_t offset{}; - int err{snd_pcm_mmap_begin(mPcmHandle, &areas, &offset, &frames)}; - if(err < 0) - { - ERR("mmap begin error: %s\n", snd_strerror(err)); - break; - } - - char *WritePtr{static_cast(areas->addr) + (offset * areas->step / 8)}; - mDevice->renderSamples(WritePtr, static_cast(frames), areas->step/samplebits); - - snd_pcm_sframes_t commitres{snd_pcm_mmap_commit(mPcmHandle, offset, frames)}; - if(commitres < 0 || static_cast(commitres) != frames) - { - ERR("mmap commit error: %s\n", - snd_strerror(commitres >= 0 ? -EPIPE : static_cast(commitres))); - break; - } - - avail -= frames; - } - } - - return 0; -} - -int AlsaPlayback::mixerNoMMapProc() -{ - SetRTPriority(); - althrd_setname(MIXER_THREAD_NAME); - - const size_t frame_step{mDevice->channelsFromFmt()}; - const snd_pcm_uframes_t update_size{mDevice->UpdateSize}; - const snd_pcm_uframes_t buffer_size{mDevice->BufferSize}; - while(!mKillNow.load(std::memory_order_acquire)) - { - int state{verify_state(mPcmHandle)}; - if(state < 0) - { - ERR("Invalid state detected: %s\n", snd_strerror(state)); - mDevice->handleDisconnect("Bad state: %s", snd_strerror(state)); - break; - } - - snd_pcm_sframes_t avail{snd_pcm_avail_update(mPcmHandle)}; - if(avail < 0) - { - ERR("available update failed: %s\n", snd_strerror(static_cast(avail))); - continue; - } - - if(static_cast(avail) > buffer_size) - { - WARN("available samples exceeds the buffer size\n"); - snd_pcm_reset(mPcmHandle); - continue; - } - - if(static_cast(avail) < update_size) - { - if(state != SND_PCM_STATE_RUNNING) - { - int err{snd_pcm_start(mPcmHandle)}; - if(err < 0) - { - ERR("start failed: %s\n", snd_strerror(err)); - continue; - } - } - if(snd_pcm_wait(mPcmHandle, 1000) == 0) - ERR("Wait timeout... buffer size too low?\n"); - continue; - } - - al::byte *WritePtr{mBuffer.data()}; - avail = snd_pcm_bytes_to_frames(mPcmHandle, static_cast(mBuffer.size())); - std::lock_guard _{mMutex}; - mDevice->renderSamples(WritePtr, static_cast(avail), frame_step); - while(avail > 0) - { - snd_pcm_sframes_t ret{snd_pcm_writei(mPcmHandle, WritePtr, - static_cast(avail))}; - switch(ret) - { - case -EAGAIN: - continue; -#if ESTRPIPE != EPIPE - case -ESTRPIPE: -#endif - case -EPIPE: - case -EINTR: - ret = snd_pcm_recover(mPcmHandle, static_cast(ret), 1); - if(ret < 0) - avail = 0; - break; - default: - if(ret >= 0) - { - WritePtr += snd_pcm_frames_to_bytes(mPcmHandle, ret); - avail -= ret; - } - break; - } - if(ret < 0) - { - ret = snd_pcm_prepare(mPcmHandle); - if(ret < 0) break; - } - } - } - - return 0; -} - - -void AlsaPlayback::open(const char *name) -{ - const char *driver{}; - if(name) - { - if(PlaybackDevices.empty()) - PlaybackDevices = probe_devices(SND_PCM_STREAM_PLAYBACK); - - auto iter = std::find_if(PlaybackDevices.cbegin(), PlaybackDevices.cend(), - [name](const DevMap &entry) -> bool - { return entry.name == name; } - ); - if(iter == PlaybackDevices.cend()) - throw al::backend_exception{al::backend_error::NoDevice, - "Device name \"%s\" not found", name}; - driver = iter->device_name.c_str(); - } - else - { - name = alsaDevice; - driver = GetConfigValue(nullptr, "alsa", "device", "default"); - } - - TRACE("Opening device \"%s\"\n", driver); - int err{snd_pcm_open(&mPcmHandle, driver, SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK)}; - if(err < 0) - throw al::backend_exception{al::backend_error::NoDevice, - "Could not open ALSA device \"%s\"", driver}; - - /* Free alsa's global config tree. Otherwise valgrind reports a ton of leaks. */ - snd_config_update_free_global(); - - mDevice->DeviceName = name; -} - -bool AlsaPlayback::reset() -{ - snd_pcm_format_t format{SND_PCM_FORMAT_UNKNOWN}; - switch(mDevice->FmtType) - { - case DevFmtByte: - format = SND_PCM_FORMAT_S8; - break; - case DevFmtUByte: - format = SND_PCM_FORMAT_U8; - break; - case DevFmtShort: - format = SND_PCM_FORMAT_S16; - break; - case DevFmtUShort: - format = SND_PCM_FORMAT_U16; - break; - case DevFmtInt: - format = SND_PCM_FORMAT_S32; - break; - case DevFmtUInt: - format = SND_PCM_FORMAT_U32; - break; - case DevFmtFloat: - format = SND_PCM_FORMAT_FLOAT; - break; - } - - bool allowmmap{!!GetConfigValueBool(mDevice->DeviceName.c_str(), "alsa", "mmap", 1)}; - uint periodLen{static_cast(mDevice->UpdateSize * 1000000_u64 / mDevice->Frequency)}; - uint bufferLen{static_cast(mDevice->BufferSize * 1000000_u64 / mDevice->Frequency)}; - uint rate{mDevice->Frequency}; - - int err{}; - HwParamsPtr hp{CreateHwParams()}; -#define CHECK(x) do { \ - if((err=(x)) < 0) \ - throw al::backend_exception{al::backend_error::DeviceError, #x " failed: %s", \ - snd_strerror(err)}; \ -} while(0) - CHECK(snd_pcm_hw_params_any(mPcmHandle, hp.get())); - /* set interleaved access */ - if(!allowmmap - || snd_pcm_hw_params_set_access(mPcmHandle, hp.get(), SND_PCM_ACCESS_MMAP_INTERLEAVED) < 0) - { - /* No mmap */ - CHECK(snd_pcm_hw_params_set_access(mPcmHandle, hp.get(), SND_PCM_ACCESS_RW_INTERLEAVED)); - } - /* test and set format (implicitly sets sample bits) */ - if(snd_pcm_hw_params_test_format(mPcmHandle, hp.get(), format) < 0) - { - static const struct { - snd_pcm_format_t format; - DevFmtType fmttype; - } formatlist[] = { - { SND_PCM_FORMAT_FLOAT, DevFmtFloat }, - { SND_PCM_FORMAT_S32, DevFmtInt }, - { SND_PCM_FORMAT_U32, DevFmtUInt }, - { SND_PCM_FORMAT_S16, DevFmtShort }, - { SND_PCM_FORMAT_U16, DevFmtUShort }, - { SND_PCM_FORMAT_S8, DevFmtByte }, - { SND_PCM_FORMAT_U8, DevFmtUByte }, - }; - - for(const auto &fmt : formatlist) - { - format = fmt.format; - if(snd_pcm_hw_params_test_format(mPcmHandle, hp.get(), format) >= 0) - { - mDevice->FmtType = fmt.fmttype; - break; - } - } - } - CHECK(snd_pcm_hw_params_set_format(mPcmHandle, hp.get(), format)); - /* test and set channels (implicitly sets frame bits) */ - if(snd_pcm_hw_params_test_channels(mPcmHandle, hp.get(), mDevice->channelsFromFmt()) < 0) - { - static const DevFmtChannels channellist[] = { - DevFmtStereo, - DevFmtQuad, - DevFmtX51, - DevFmtX71, - DevFmtMono, - }; - - for(const auto &chan : channellist) - { - if(snd_pcm_hw_params_test_channels(mPcmHandle, hp.get(), ChannelsFromDevFmt(chan, 0)) >= 0) - { - mDevice->FmtChans = chan; - mDevice->mAmbiOrder = 0; - break; - } - } - } - CHECK(snd_pcm_hw_params_set_channels(mPcmHandle, hp.get(), mDevice->channelsFromFmt())); - /* set rate (implicitly constrains period/buffer parameters) */ - if(!GetConfigValueBool(mDevice->DeviceName.c_str(), "alsa", "allow-resampler", 0) - || !mDevice->Flags.test(FrequencyRequest)) - { - if(snd_pcm_hw_params_set_rate_resample(mPcmHandle, hp.get(), 0) < 0) - ERR("Failed to disable ALSA resampler\n"); - } - else if(snd_pcm_hw_params_set_rate_resample(mPcmHandle, hp.get(), 1) < 0) - ERR("Failed to enable ALSA resampler\n"); - CHECK(snd_pcm_hw_params_set_rate_near(mPcmHandle, hp.get(), &rate, nullptr)); - /* set period time (implicitly constrains period/buffer parameters) */ - if((err=snd_pcm_hw_params_set_period_time_near(mPcmHandle, hp.get(), &periodLen, nullptr)) < 0) - ERR("snd_pcm_hw_params_set_period_time_near failed: %s\n", snd_strerror(err)); - /* set buffer time (implicitly sets buffer size/bytes/time and period size/bytes) */ - if((err=snd_pcm_hw_params_set_buffer_time_near(mPcmHandle, hp.get(), &bufferLen, nullptr)) < 0) - ERR("snd_pcm_hw_params_set_buffer_time_near failed: %s\n", snd_strerror(err)); - /* install and prepare hardware configuration */ - CHECK(snd_pcm_hw_params(mPcmHandle, hp.get())); - - /* retrieve configuration info */ - snd_pcm_uframes_t periodSizeInFrames{}; - snd_pcm_uframes_t bufferSizeInFrames{}; - snd_pcm_access_t access{}; - - CHECK(snd_pcm_hw_params_get_access(hp.get(), &access)); - CHECK(snd_pcm_hw_params_get_period_size(hp.get(), &periodSizeInFrames, nullptr)); - CHECK(snd_pcm_hw_params_get_buffer_size(hp.get(), &bufferSizeInFrames)); - hp = nullptr; - - SwParamsPtr sp{CreateSwParams()}; - CHECK(snd_pcm_sw_params_current(mPcmHandle, sp.get())); - CHECK(snd_pcm_sw_params_set_avail_min(mPcmHandle, sp.get(), periodSizeInFrames)); - CHECK(snd_pcm_sw_params_set_stop_threshold(mPcmHandle, sp.get(), bufferSizeInFrames)); - CHECK(snd_pcm_sw_params(mPcmHandle, sp.get())); -#undef CHECK - sp = nullptr; - - mDevice->BufferSize = static_cast(bufferSizeInFrames); - mDevice->UpdateSize = static_cast(periodSizeInFrames); - mDevice->Frequency = rate; - - setDefaultChannelOrder(); - - return true; -} - -void AlsaPlayback::start() -{ - int err{}; - snd_pcm_access_t access{}; - HwParamsPtr hp{CreateHwParams()}; -#define CHECK(x) do { \ - if((err=(x)) < 0) \ - throw al::backend_exception{al::backend_error::DeviceError, #x " failed: %s", \ - snd_strerror(err)}; \ -} while(0) - CHECK(snd_pcm_hw_params_current(mPcmHandle, hp.get())); - /* retrieve configuration info */ - CHECK(snd_pcm_hw_params_get_access(hp.get(), &access)); - hp = nullptr; - - int (AlsaPlayback::*thread_func)(){}; - if(access == SND_PCM_ACCESS_RW_INTERLEAVED) - { - mBuffer.resize( - static_cast(snd_pcm_frames_to_bytes(mPcmHandle, mDevice->UpdateSize))); - thread_func = &AlsaPlayback::mixerNoMMapProc; - } - else - { - CHECK(snd_pcm_prepare(mPcmHandle)); - thread_func = &AlsaPlayback::mixerProc; - } -#undef CHECK - - try { - mKillNow.store(false, std::memory_order_release); - mThread = std::thread{std::mem_fn(thread_func), this}; - } - catch(std::exception& e) { - throw al::backend_exception{al::backend_error::DeviceError, - "Failed to start mixing thread: %s", e.what()}; - } -} - -void AlsaPlayback::stop() -{ - if(mKillNow.exchange(true, std::memory_order_acq_rel) || !mThread.joinable()) - return; - mThread.join(); - - mBuffer.clear(); - int err{snd_pcm_drop(mPcmHandle)}; - if(err < 0) - ERR("snd_pcm_drop failed: %s\n", snd_strerror(err)); -} - -ClockLatency AlsaPlayback::getClockLatency() -{ - ClockLatency ret; - - std::lock_guard _{mMutex}; - ret.ClockTime = GetDeviceClockTime(mDevice); - snd_pcm_sframes_t delay{}; - int err{snd_pcm_delay(mPcmHandle, &delay)}; - if(err < 0) - { - ERR("Failed to get pcm delay: %s\n", snd_strerror(err)); - delay = 0; - } - ret.Latency = std::chrono::seconds{std::max(0, delay)}; - ret.Latency /= mDevice->Frequency; - - return ret; -} - - -struct AlsaCapture final : public BackendBase { - AlsaCapture(ALCdevice *device) noexcept : BackendBase{device} { } - ~AlsaCapture() override; - - void open(const char *name) override; - void start() override; - void stop() override; - void captureSamples(al::byte *buffer, uint samples) override; - uint availableSamples() override; - ClockLatency getClockLatency() override; - - snd_pcm_t *mPcmHandle{nullptr}; - - al::vector mBuffer; - - bool mDoCapture{false}; - RingBufferPtr mRing{nullptr}; - - snd_pcm_sframes_t mLastAvail{0}; - - DEF_NEWDEL(AlsaCapture) -}; - -AlsaCapture::~AlsaCapture() -{ - if(mPcmHandle) - snd_pcm_close(mPcmHandle); - mPcmHandle = nullptr; -} - - -void AlsaCapture::open(const char *name) -{ - const char *driver{}; - if(name) - { - if(CaptureDevices.empty()) - CaptureDevices = probe_devices(SND_PCM_STREAM_CAPTURE); - - auto iter = std::find_if(CaptureDevices.cbegin(), CaptureDevices.cend(), - [name](const DevMap &entry) -> bool - { return entry.name == name; } - ); - if(iter == CaptureDevices.cend()) - throw al::backend_exception{al::backend_error::NoDevice, - "Device name \"%s\" not found", name}; - driver = iter->device_name.c_str(); - } - else - { - name = alsaDevice; - driver = GetConfigValue(nullptr, "alsa", "capture", "default"); - } - - TRACE("Opening device \"%s\"\n", driver); - int err{snd_pcm_open(&mPcmHandle, driver, SND_PCM_STREAM_CAPTURE, SND_PCM_NONBLOCK)}; - if(err < 0) - throw al::backend_exception{al::backend_error::NoDevice, - "Could not open ALSA device \"%s\"", driver}; - - /* Free alsa's global config tree. Otherwise valgrind reports a ton of leaks. */ - snd_config_update_free_global(); - - snd_pcm_format_t format{SND_PCM_FORMAT_UNKNOWN}; - switch(mDevice->FmtType) - { - case DevFmtByte: - format = SND_PCM_FORMAT_S8; - break; - case DevFmtUByte: - format = SND_PCM_FORMAT_U8; - break; - case DevFmtShort: - format = SND_PCM_FORMAT_S16; - break; - case DevFmtUShort: - format = SND_PCM_FORMAT_U16; - break; - case DevFmtInt: - format = SND_PCM_FORMAT_S32; - break; - case DevFmtUInt: - format = SND_PCM_FORMAT_U32; - break; - case DevFmtFloat: - format = SND_PCM_FORMAT_FLOAT; - break; - } - - snd_pcm_uframes_t bufferSizeInFrames{maxu(mDevice->BufferSize, 100*mDevice->Frequency/1000)}; - snd_pcm_uframes_t periodSizeInFrames{minu(mDevice->BufferSize, 25*mDevice->Frequency/1000)}; - - bool needring{false}; - HwParamsPtr hp{CreateHwParams()}; -#define CHECK(x) do { \ - if((err=(x)) < 0) \ - throw al::backend_exception{al::backend_error::DeviceError, #x " failed: %s", \ - snd_strerror(err)}; \ -} while(0) - CHECK(snd_pcm_hw_params_any(mPcmHandle, hp.get())); - /* set interleaved access */ - CHECK(snd_pcm_hw_params_set_access(mPcmHandle, hp.get(), SND_PCM_ACCESS_RW_INTERLEAVED)); - /* set format (implicitly sets sample bits) */ - CHECK(snd_pcm_hw_params_set_format(mPcmHandle, hp.get(), format)); - /* set channels (implicitly sets frame bits) */ - CHECK(snd_pcm_hw_params_set_channels(mPcmHandle, hp.get(), mDevice->channelsFromFmt())); - /* set rate (implicitly constrains period/buffer parameters) */ - CHECK(snd_pcm_hw_params_set_rate(mPcmHandle, hp.get(), mDevice->Frequency, 0)); - /* set buffer size in frame units (implicitly sets period size/bytes/time and buffer time/bytes) */ - if(snd_pcm_hw_params_set_buffer_size_min(mPcmHandle, hp.get(), &bufferSizeInFrames) < 0) - { - TRACE("Buffer too large, using intermediate ring buffer\n"); - needring = true; - CHECK(snd_pcm_hw_params_set_buffer_size_near(mPcmHandle, hp.get(), &bufferSizeInFrames)); - } - /* set buffer size in frame units (implicitly sets period size/bytes/time and buffer time/bytes) */ - CHECK(snd_pcm_hw_params_set_period_size_near(mPcmHandle, hp.get(), &periodSizeInFrames, nullptr)); - /* install and prepare hardware configuration */ - CHECK(snd_pcm_hw_params(mPcmHandle, hp.get())); - /* retrieve configuration info */ - CHECK(snd_pcm_hw_params_get_period_size(hp.get(), &periodSizeInFrames, nullptr)); -#undef CHECK - hp = nullptr; - - if(needring) - mRing = RingBuffer::Create(mDevice->BufferSize, mDevice->frameSizeFromFmt(), false); - - mDevice->DeviceName = name; -} - - -void AlsaCapture::start() -{ - int err{snd_pcm_prepare(mPcmHandle)}; - if(err < 0) - throw al::backend_exception{al::backend_error::DeviceError, "snd_pcm_prepare failed: %s", - snd_strerror(err)}; - - err = snd_pcm_start(mPcmHandle); - if(err < 0) - throw al::backend_exception{al::backend_error::DeviceError, "snd_pcm_start failed: %s", - snd_strerror(err)}; - - mDoCapture = true; -} - -void AlsaCapture::stop() -{ - /* OpenAL requires access to unread audio after stopping, but ALSA's - * snd_pcm_drain is unreliable and snd_pcm_drop drops it. Capture what's - * available now so it'll be available later after the drop. - */ - uint avail{availableSamples()}; - if(!mRing && avail > 0) - { - /* The ring buffer implicitly captures when checking availability. - * Direct access needs to explicitly capture it into temp storage. - */ - auto temp = al::vector( - static_cast(snd_pcm_frames_to_bytes(mPcmHandle, avail))); - captureSamples(temp.data(), avail); - mBuffer = std::move(temp); - } - int err{snd_pcm_drop(mPcmHandle)}; - if(err < 0) - ERR("drop failed: %s\n", snd_strerror(err)); - mDoCapture = false; -} - -void AlsaCapture::captureSamples(al::byte *buffer, uint samples) -{ - if(mRing) - { - mRing->read(buffer, samples); - return; - } - - mLastAvail -= samples; - while(mDevice->Connected.load(std::memory_order_acquire) && samples > 0) - { - snd_pcm_sframes_t amt{0}; - - if(!mBuffer.empty()) - { - /* First get any data stored from the last stop */ - amt = snd_pcm_bytes_to_frames(mPcmHandle, static_cast(mBuffer.size())); - if(static_cast(amt) > samples) amt = samples; - - amt = snd_pcm_frames_to_bytes(mPcmHandle, amt); - std::copy_n(mBuffer.begin(), amt, buffer); - - mBuffer.erase(mBuffer.begin(), mBuffer.begin()+amt); - amt = snd_pcm_bytes_to_frames(mPcmHandle, amt); - } - else if(mDoCapture) - amt = snd_pcm_readi(mPcmHandle, buffer, samples); - if(amt < 0) - { - ERR("read error: %s\n", snd_strerror(static_cast(amt))); - - if(amt == -EAGAIN) - continue; - if((amt=snd_pcm_recover(mPcmHandle, static_cast(amt), 1)) >= 0) - { - amt = snd_pcm_start(mPcmHandle); - if(amt >= 0) - amt = snd_pcm_avail_update(mPcmHandle); - } - if(amt < 0) - { - const char *err{snd_strerror(static_cast(amt))}; - ERR("restore error: %s\n", err); - mDevice->handleDisconnect("Capture recovery failure: %s", err); - break; - } - /* If the amount available is less than what's asked, we lost it - * during recovery. So just give silence instead. */ - if(static_cast(amt) < samples) - break; - continue; - } - - buffer = buffer + amt; - samples -= static_cast(amt); - } - if(samples > 0) - std::fill_n(buffer, snd_pcm_frames_to_bytes(mPcmHandle, samples), - al::byte((mDevice->FmtType == DevFmtUByte) ? 0x80 : 0)); -} - -uint AlsaCapture::availableSamples() -{ - snd_pcm_sframes_t avail{0}; - if(mDevice->Connected.load(std::memory_order_acquire) && mDoCapture) - avail = snd_pcm_avail_update(mPcmHandle); - if(avail < 0) - { - ERR("avail update failed: %s\n", snd_strerror(static_cast(avail))); - - if((avail=snd_pcm_recover(mPcmHandle, static_cast(avail), 1)) >= 0) - { - if(mDoCapture) - avail = snd_pcm_start(mPcmHandle); - if(avail >= 0) - avail = snd_pcm_avail_update(mPcmHandle); - } - if(avail < 0) - { - const char *err{snd_strerror(static_cast(avail))}; - ERR("restore error: %s\n", err); - mDevice->handleDisconnect("Capture recovery failure: %s", err); - } - } - - if(!mRing) - { - if(avail < 0) avail = 0; - avail += snd_pcm_bytes_to_frames(mPcmHandle, static_cast(mBuffer.size())); - if(avail > mLastAvail) mLastAvail = avail; - return static_cast(mLastAvail); - } - - while(avail > 0) - { - auto vec = mRing->getWriteVector(); - if(vec.first.len == 0) break; - - snd_pcm_sframes_t amt{std::min(static_cast(vec.first.len), avail)}; - amt = snd_pcm_readi(mPcmHandle, vec.first.buf, static_cast(amt)); - if(amt < 0) - { - ERR("read error: %s\n", snd_strerror(static_cast(amt))); - - if(amt == -EAGAIN) - continue; - if((amt=snd_pcm_recover(mPcmHandle, static_cast(amt), 1)) >= 0) - { - if(mDoCapture) - amt = snd_pcm_start(mPcmHandle); - if(amt >= 0) - amt = snd_pcm_avail_update(mPcmHandle); - } - if(amt < 0) - { - const char *err{snd_strerror(static_cast(amt))}; - ERR("restore error: %s\n", err); - mDevice->handleDisconnect("Capture recovery failure: %s", err); - break; - } - avail = amt; - continue; - } - - mRing->writeAdvance(static_cast(amt)); - avail -= amt; - } - - return static_cast(mRing->readSpace()); -} - -ClockLatency AlsaCapture::getClockLatency() -{ - ClockLatency ret; - - ret.ClockTime = GetDeviceClockTime(mDevice); - snd_pcm_sframes_t delay{}; - int err{snd_pcm_delay(mPcmHandle, &delay)}; - if(err < 0) - { - ERR("Failed to get pcm delay: %s\n", snd_strerror(err)); - delay = 0; - } - ret.Latency = std::chrono::seconds{std::max(0, delay)}; - ret.Latency /= mDevice->Frequency; - - return ret; -} - -} // namespace - - -bool AlsaBackendFactory::init() -{ - bool error{false}; - -#ifdef HAVE_DYNLOAD - if(!alsa_handle) - { - std::string missing_funcs; - - alsa_handle = LoadLib("libasound.so.2"); - if(!alsa_handle) - { - WARN("Failed to load %s\n", "libasound.so.2"); - return false; - } - - error = false; -#define LOAD_FUNC(f) do { \ - p##f = reinterpret_cast(GetSymbol(alsa_handle, #f)); \ - if(p##f == nullptr) { \ - error = true; \ - missing_funcs += "\n" #f; \ - } \ -} while(0) - ALSA_FUNCS(LOAD_FUNC); -#undef LOAD_FUNC - - if(error) - { - WARN("Missing expected functions:%s\n", missing_funcs.c_str()); - CloseLib(alsa_handle); - alsa_handle = nullptr; - } - } -#endif - - return !error; -} - -bool AlsaBackendFactory::querySupport(BackendType type) -{ return (type == BackendType::Playback || type == BackendType::Capture); } - -std::string AlsaBackendFactory::probe(BackendType type) -{ - std::string outnames; - - auto add_device = [&outnames](const DevMap &entry) -> void - { - /* +1 to also append the null char (to ensure a null-separated list and - * double-null terminated list). - */ - outnames.append(entry.name.c_str(), entry.name.length()+1); - }; - switch(type) - { - case BackendType::Playback: - PlaybackDevices = probe_devices(SND_PCM_STREAM_PLAYBACK); - std::for_each(PlaybackDevices.cbegin(), PlaybackDevices.cend(), add_device); - break; - - case BackendType::Capture: - CaptureDevices = probe_devices(SND_PCM_STREAM_CAPTURE); - std::for_each(CaptureDevices.cbegin(), CaptureDevices.cend(), add_device); - break; - } - - return outnames; -} - -BackendPtr AlsaBackendFactory::createBackend(ALCdevice *device, BackendType type) -{ - if(type == BackendType::Playback) - return BackendPtr{new AlsaPlayback{device}}; - if(type == BackendType::Capture) - return BackendPtr{new AlsaCapture{device}}; - return nullptr; -} - -BackendFactory &AlsaBackendFactory::getFactory() -{ - static AlsaBackendFactory factory{}; - return factory; -} diff --git a/alc/backends/alsa.h b/alc/backends/alsa.h deleted file mode 100644 index 12023cb6..00000000 --- a/alc/backends/alsa.h +++ /dev/null @@ -1,19 +0,0 @@ -#ifndef BACKENDS_ALSA_H -#define BACKENDS_ALSA_H - -#include "backends/base.h" - -struct AlsaBackendFactory final : public BackendFactory { -public: - bool init() override; - - bool querySupport(BackendType type) override; - - std::string probe(BackendType type) override; - - BackendPtr createBackend(ALCdevice *device, BackendType type) override; - - static BackendFactory &getFactory(); -}; - -#endif /* BACKENDS_ALSA_H */ diff --git a/alc/backends/base.cpp b/alc/backends/base.cpp deleted file mode 100644 index 8642f40c..00000000 --- a/alc/backends/base.cpp +++ /dev/null @@ -1,194 +0,0 @@ - -#include "config.h" - -#include "base.h" - -#include -#include - -#ifdef _WIN32 -#define WIN32_LEAN_AND_MEAN -#include -#include -#endif - -#include "alcmain.h" -#include "alnumeric.h" -#include "aloptional.h" -#include "atomic.h" -#include "core/logging.h" - - -bool BackendBase::reset() -{ throw al::backend_exception{al::backend_error::DeviceError, "Invalid BackendBase call"}; } - -void BackendBase::captureSamples(al::byte*, uint) -{ } - -uint BackendBase::availableSamples() -{ return 0; } - -ClockLatency BackendBase::getClockLatency() -{ - ClockLatency ret; - - uint refcount; - do { - refcount = mDevice->waitForMix(); - ret.ClockTime = GetDeviceClockTime(mDevice); - std::atomic_thread_fence(std::memory_order_acquire); - } while(refcount != ReadRef(mDevice->MixCount)); - - /* NOTE: The device will generally have about all but one periods filled at - * any given time during playback. Without a more accurate measurement from - * the output, this is an okay approximation. - */ - ret.Latency = std::max(std::chrono::seconds{mDevice->BufferSize-mDevice->UpdateSize}, - std::chrono::seconds::zero()); - ret.Latency /= mDevice->Frequency; - - return ret; -} - -void BackendBase::setDefaultWFXChannelOrder() -{ - mDevice->RealOut.ChannelIndex.fill(INVALID_CHANNEL_INDEX); - - switch(mDevice->FmtChans) - { - case DevFmtMono: - mDevice->RealOut.ChannelIndex[FrontCenter] = 0; - break; - case DevFmtStereo: - mDevice->RealOut.ChannelIndex[FrontLeft] = 0; - mDevice->RealOut.ChannelIndex[FrontRight] = 1; - break; - case DevFmtQuad: - mDevice->RealOut.ChannelIndex[FrontLeft] = 0; - mDevice->RealOut.ChannelIndex[FrontRight] = 1; - mDevice->RealOut.ChannelIndex[BackLeft] = 2; - mDevice->RealOut.ChannelIndex[BackRight] = 3; - break; - case DevFmtX51: - mDevice->RealOut.ChannelIndex[FrontLeft] = 0; - mDevice->RealOut.ChannelIndex[FrontRight] = 1; - mDevice->RealOut.ChannelIndex[FrontCenter] = 2; - mDevice->RealOut.ChannelIndex[LFE] = 3; - mDevice->RealOut.ChannelIndex[SideLeft] = 4; - mDevice->RealOut.ChannelIndex[SideRight] = 5; - break; - case DevFmtX51Rear: - mDevice->RealOut.ChannelIndex[FrontLeft] = 0; - mDevice->RealOut.ChannelIndex[FrontRight] = 1; - mDevice->RealOut.ChannelIndex[FrontCenter] = 2; - mDevice->RealOut.ChannelIndex[LFE] = 3; - mDevice->RealOut.ChannelIndex[BackLeft] = 4; - mDevice->RealOut.ChannelIndex[BackRight] = 5; - break; - case DevFmtX61: - mDevice->RealOut.ChannelIndex[FrontLeft] = 0; - mDevice->RealOut.ChannelIndex[FrontRight] = 1; - mDevice->RealOut.ChannelIndex[FrontCenter] = 2; - mDevice->RealOut.ChannelIndex[LFE] = 3; - mDevice->RealOut.ChannelIndex[BackCenter] = 4; - mDevice->RealOut.ChannelIndex[SideLeft] = 5; - mDevice->RealOut.ChannelIndex[SideRight] = 6; - break; - case DevFmtX71: - mDevice->RealOut.ChannelIndex[FrontLeft] = 0; - mDevice->RealOut.ChannelIndex[FrontRight] = 1; - mDevice->RealOut.ChannelIndex[FrontCenter] = 2; - mDevice->RealOut.ChannelIndex[LFE] = 3; - mDevice->RealOut.ChannelIndex[BackLeft] = 4; - mDevice->RealOut.ChannelIndex[BackRight] = 5; - mDevice->RealOut.ChannelIndex[SideLeft] = 6; - mDevice->RealOut.ChannelIndex[SideRight] = 7; - break; - case DevFmtAmbi3D: - break; - } -} - -void BackendBase::setDefaultChannelOrder() -{ - mDevice->RealOut.ChannelIndex.fill(INVALID_CHANNEL_INDEX); - - switch(mDevice->FmtChans) - { - case DevFmtX51Rear: - mDevice->RealOut.ChannelIndex[FrontLeft] = 0; - mDevice->RealOut.ChannelIndex[FrontRight] = 1; - mDevice->RealOut.ChannelIndex[BackLeft] = 2; - mDevice->RealOut.ChannelIndex[BackRight] = 3; - mDevice->RealOut.ChannelIndex[FrontCenter] = 4; - mDevice->RealOut.ChannelIndex[LFE] = 5; - return; - case DevFmtX71: - mDevice->RealOut.ChannelIndex[FrontLeft] = 0; - mDevice->RealOut.ChannelIndex[FrontRight] = 1; - mDevice->RealOut.ChannelIndex[BackLeft] = 2; - mDevice->RealOut.ChannelIndex[BackRight] = 3; - mDevice->RealOut.ChannelIndex[FrontCenter] = 4; - mDevice->RealOut.ChannelIndex[LFE] = 5; - mDevice->RealOut.ChannelIndex[SideLeft] = 6; - mDevice->RealOut.ChannelIndex[SideRight] = 7; - return; - - /* Same as WFX order */ - case DevFmtMono: - case DevFmtStereo: - case DevFmtQuad: - case DevFmtX51: - case DevFmtX61: - case DevFmtAmbi3D: - setDefaultWFXChannelOrder(); - break; - } -} - -#ifdef _WIN32 -void BackendBase::setChannelOrderFromWFXMask(uint chanmask) -{ - auto get_channel = [](const DWORD chanbit) noexcept -> al::optional - { - switch(chanbit) - { - case SPEAKER_FRONT_LEFT: return al::make_optional(FrontLeft); - case SPEAKER_FRONT_RIGHT: return al::make_optional(FrontRight); - case SPEAKER_FRONT_CENTER: return al::make_optional(FrontCenter); - case SPEAKER_LOW_FREQUENCY: return al::make_optional(LFE); - case SPEAKER_BACK_LEFT: return al::make_optional(BackLeft); - case SPEAKER_BACK_RIGHT: return al::make_optional(BackRight); - case SPEAKER_FRONT_LEFT_OF_CENTER: break; - case SPEAKER_FRONT_RIGHT_OF_CENTER: break; - case SPEAKER_BACK_CENTER: return al::make_optional(BackCenter); - case SPEAKER_SIDE_LEFT: return al::make_optional(SideLeft); - case SPEAKER_SIDE_RIGHT: return al::make_optional(SideRight); - case SPEAKER_TOP_CENTER: return al::make_optional(TopCenter); - case SPEAKER_TOP_FRONT_LEFT: return al::make_optional(TopFrontLeft); - case SPEAKER_TOP_FRONT_CENTER: return al::make_optional(TopFrontCenter); - case SPEAKER_TOP_FRONT_RIGHT: return al::make_optional(TopFrontRight); - case SPEAKER_TOP_BACK_LEFT: return al::make_optional(TopBackLeft); - case SPEAKER_TOP_BACK_CENTER: return al::make_optional(TopBackCenter); - case SPEAKER_TOP_BACK_RIGHT: return al::make_optional(TopBackRight); - } - WARN("Unhandled WFX channel bit 0x%lx\n", chanbit); - return al::nullopt; - }; - - const uint numchans{mDevice->channelsFromFmt()}; - uint idx{0}; - while(chanmask) - { - const int bit{CountTrailingZeros(chanmask)}; - const uint mask{1u << bit}; - chanmask &= ~mask; - - if(auto label = get_channel(mask)) - { - mDevice->RealOut.ChannelIndex[*label] = idx; - if(++idx == numchans) break; - } - } -} -#endif diff --git a/alc/backends/base.h b/alc/backends/base.h deleted file mode 100644 index df076276..00000000 --- a/alc/backends/base.h +++ /dev/null @@ -1,119 +0,0 @@ -#ifndef ALC_BACKENDS_BASE_H -#define ALC_BACKENDS_BASE_H - -#include -#include -#include -#include - -#include "albyte.h" -#include "alcmain.h" -#include "core/except.h" - - -using uint = unsigned int; - -struct ClockLatency { - std::chrono::nanoseconds ClockTime; - std::chrono::nanoseconds Latency; -}; - -struct BackendBase { - virtual void open(const char *name) = 0; - - virtual bool reset(); - virtual void start() = 0; - virtual void stop() = 0; - - virtual void captureSamples(al::byte *buffer, uint samples); - virtual uint availableSamples(); - - virtual ClockLatency getClockLatency(); - - ALCdevice *const mDevice; - - BackendBase(ALCdevice *device) noexcept : mDevice{device} { } - virtual ~BackendBase() = default; - -protected: - /** Sets the default channel order used by most non-WaveFormatEx-based APIs. */ - void setDefaultChannelOrder(); - /** Sets the default channel order used by WaveFormatEx. */ - void setDefaultWFXChannelOrder(); - -#ifdef _WIN32 - /** Sets the channel order given the WaveFormatEx mask. */ - void setChannelOrderFromWFXMask(uint chanmask); -#endif -}; -using BackendPtr = std::unique_ptr; - -enum class BackendType { - Playback, - Capture -}; - - -/* Helper to get the current clock time from the device's ClockBase, and - * SamplesDone converted from the sample rate. - */ -inline std::chrono::nanoseconds GetDeviceClockTime(ALCdevice *device) -{ - using std::chrono::seconds; - using std::chrono::nanoseconds; - - auto ns = nanoseconds{seconds{device->SamplesDone}} / device->Frequency; - return device->ClockBase + ns; -} - -/* Helper to get the device latency from the backend, including any fixed - * latency from post-processing. - */ -inline ClockLatency GetClockLatency(ALCdevice *device) -{ - BackendBase *backend{device->Backend.get()}; - ClockLatency ret{backend->getClockLatency()}; - ret.Latency += device->FixedLatency; - return ret; -} - - -struct BackendFactory { - virtual bool init() = 0; - - virtual bool querySupport(BackendType type) = 0; - - virtual std::string probe(BackendType type) = 0; - - virtual BackendPtr createBackend(ALCdevice *device, BackendType type) = 0; - -protected: - virtual ~BackendFactory() = default; -}; - -namespace al { - -enum class backend_error { - NoDevice, - DeviceError, - OutOfMemory -}; - -class backend_exception final : public base_exception { - backend_error mErrorCode; - -public: - [[gnu::format(printf, 3, 4)]] - backend_exception(backend_error code, const char *msg, ...) : mErrorCode{code} - { - std::va_list args; - va_start(args, msg); - setMessage(msg, args); - va_end(args); - } - backend_error errorCode() const noexcept { return mErrorCode; } -}; - -} // namespace al - -#endif /* ALC_BACKENDS_BASE_H */ diff --git a/alc/backends/coreaudio.cpp b/alc/backends/coreaudio.cpp deleted file mode 100644 index 8e38a777..00000000 --- a/alc/backends/coreaudio.cpp +++ /dev/null @@ -1,686 +0,0 @@ -/** - * OpenAL cross platform audio library - * Copyright (C) 1999-2007 by authors. - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - * Or go to http://www.gnu.org/copyleft/lgpl.html - */ - -#include "config.h" - -#include "backends/coreaudio.h" - -#include -#include -#include -#include - -#include - -#include "alcmain.h" -#include "alu.h" -#include "ringbuffer.h" -#include "converter.h" -#include "core/logging.h" -#include "backends/base.h" - -#include -#include -#include - - -namespace { - -static const char ca_device[] = "CoreAudio Default"; - - -struct CoreAudioPlayback final : public BackendBase { - CoreAudioPlayback(ALCdevice *device) noexcept : BackendBase{device} { } - ~CoreAudioPlayback() override; - - OSStatus MixerProc(AudioUnitRenderActionFlags *ioActionFlags, - const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, - AudioBufferList *ioData) noexcept; - static OSStatus MixerProcC(void *inRefCon, AudioUnitRenderActionFlags *ioActionFlags, - const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, - AudioBufferList *ioData) noexcept - { - return static_cast(inRefCon)->MixerProc(ioActionFlags, inTimeStamp, - inBusNumber, inNumberFrames, ioData); - } - - void open(const char *name) override; - bool reset() override; - void start() override; - void stop() override; - - AudioUnit mAudioUnit{}; - - uint mFrameSize{0u}; - AudioStreamBasicDescription mFormat{}; // This is the OpenAL format as a CoreAudio ASBD - - DEF_NEWDEL(CoreAudioPlayback) -}; - -CoreAudioPlayback::~CoreAudioPlayback() -{ - AudioUnitUninitialize(mAudioUnit); - AudioComponentInstanceDispose(mAudioUnit); -} - - -OSStatus CoreAudioPlayback::MixerProc(AudioUnitRenderActionFlags*, const AudioTimeStamp*, UInt32, - UInt32, AudioBufferList *ioData) noexcept -{ - for(size_t i{0};i < ioData->mNumberBuffers;++i) - { - auto &buffer = ioData->mBuffers[i]; - mDevice->renderSamples(buffer.mData, buffer.mDataByteSize/mFrameSize, - buffer.mNumberChannels); - } - return noErr; -} - - -void CoreAudioPlayback::open(const char *name) -{ - if(!name) - name = ca_device; - else if(strcmp(name, ca_device) != 0) - throw al::backend_exception{al::backend_error::NoDevice, "Device name \"%s\" not found", - name}; - - /* open the default output unit */ - AudioComponentDescription desc{}; - desc.componentType = kAudioUnitType_Output; -#if TARGET_OS_IOS - desc.componentSubType = kAudioUnitSubType_RemoteIO; -#else - desc.componentSubType = kAudioUnitSubType_DefaultOutput; -#endif - desc.componentManufacturer = kAudioUnitManufacturer_Apple; - desc.componentFlags = 0; - desc.componentFlagsMask = 0; - - AudioComponent comp{AudioComponentFindNext(NULL, &desc)}; - if(comp == nullptr) - throw al::backend_exception{al::backend_error::NoDevice, "Could not find audio component"}; - - OSStatus err{AudioComponentInstanceNew(comp, &mAudioUnit)}; - if(err != noErr) - throw al::backend_exception{al::backend_error::NoDevice, - "Could not create component instance: %u", err}; - - /* init and start the default audio unit... */ - err = AudioUnitInitialize(mAudioUnit); - if(err != noErr) - throw al::backend_exception{al::backend_error::DeviceError, - "Could not initialize audio unit: %u", err}; - - mDevice->DeviceName = name; -} - -bool CoreAudioPlayback::reset() -{ - OSStatus err{AudioUnitUninitialize(mAudioUnit)}; - if(err != noErr) - ERR("-- AudioUnitUninitialize failed.\n"); - - /* retrieve default output unit's properties (output side) */ - AudioStreamBasicDescription streamFormat{}; - auto size = static_cast(sizeof(AudioStreamBasicDescription)); - err = AudioUnitGetProperty(mAudioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, - 0, &streamFormat, &size); - if(err != noErr || size != sizeof(AudioStreamBasicDescription)) - { - ERR("AudioUnitGetProperty failed\n"); - return false; - } - -#if 0 - TRACE("Output streamFormat of default output unit -\n"); - TRACE(" streamFormat.mFramesPerPacket = %d\n", streamFormat.mFramesPerPacket); - TRACE(" streamFormat.mChannelsPerFrame = %d\n", streamFormat.mChannelsPerFrame); - TRACE(" streamFormat.mBitsPerChannel = %d\n", streamFormat.mBitsPerChannel); - TRACE(" streamFormat.mBytesPerPacket = %d\n", streamFormat.mBytesPerPacket); - TRACE(" streamFormat.mBytesPerFrame = %d\n", streamFormat.mBytesPerFrame); - TRACE(" streamFormat.mSampleRate = %5.0f\n", streamFormat.mSampleRate); -#endif - - /* set default output unit's input side to match output side */ - err = AudioUnitSetProperty(mAudioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, - 0, &streamFormat, size); - if(err != noErr) - { - ERR("AudioUnitSetProperty failed\n"); - return false; - } - - if(mDevice->Frequency != streamFormat.mSampleRate) - { - mDevice->BufferSize = static_cast(uint64_t{mDevice->BufferSize} * - streamFormat.mSampleRate / mDevice->Frequency); - mDevice->Frequency = static_cast(streamFormat.mSampleRate); - } - - /* FIXME: How to tell what channels are what in the output device, and how - * to specify what we're giving? eg, 6.0 vs 5.1 */ - switch(streamFormat.mChannelsPerFrame) - { - case 1: - mDevice->FmtChans = DevFmtMono; - break; - case 2: - mDevice->FmtChans = DevFmtStereo; - break; - case 4: - mDevice->FmtChans = DevFmtQuad; - break; - case 6: - mDevice->FmtChans = DevFmtX51; - break; - case 7: - mDevice->FmtChans = DevFmtX61; - break; - case 8: - mDevice->FmtChans = DevFmtX71; - break; - default: - ERR("Unhandled channel count (%d), using Stereo\n", streamFormat.mChannelsPerFrame); - mDevice->FmtChans = DevFmtStereo; - streamFormat.mChannelsPerFrame = 2; - break; - } - setDefaultWFXChannelOrder(); - - /* use channel count and sample rate from the default output unit's current - * parameters, but reset everything else */ - streamFormat.mFramesPerPacket = 1; - streamFormat.mFormatFlags = 0; - switch(mDevice->FmtType) - { - case DevFmtUByte: - mDevice->FmtType = DevFmtByte; - /* fall-through */ - case DevFmtByte: - streamFormat.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger; - streamFormat.mBitsPerChannel = 8; - break; - case DevFmtUShort: - mDevice->FmtType = DevFmtShort; - /* fall-through */ - case DevFmtShort: - streamFormat.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger; - streamFormat.mBitsPerChannel = 16; - break; - case DevFmtUInt: - mDevice->FmtType = DevFmtInt; - /* fall-through */ - case DevFmtInt: - streamFormat.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger; - streamFormat.mBitsPerChannel = 32; - break; - case DevFmtFloat: - streamFormat.mFormatFlags = kLinearPCMFormatFlagIsFloat; - streamFormat.mBitsPerChannel = 32; - break; - } - streamFormat.mBytesPerFrame = streamFormat.mChannelsPerFrame * - streamFormat.mBitsPerChannel / 8; - streamFormat.mBytesPerPacket = streamFormat.mBytesPerFrame; - streamFormat.mFormatID = kAudioFormatLinearPCM; - streamFormat.mFormatFlags |= kAudioFormatFlagsNativeEndian | - kLinearPCMFormatFlagIsPacked; - - err = AudioUnitSetProperty(mAudioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, - 0, &streamFormat, sizeof(AudioStreamBasicDescription)); - if(err != noErr) - { - ERR("AudioUnitSetProperty failed\n"); - return false; - } - - /* setup callback */ - mFrameSize = mDevice->frameSizeFromFmt(); - AURenderCallbackStruct input{}; - input.inputProc = CoreAudioPlayback::MixerProcC; - input.inputProcRefCon = this; - - err = AudioUnitSetProperty(mAudioUnit, kAudioUnitProperty_SetRenderCallback, - kAudioUnitScope_Input, 0, &input, sizeof(AURenderCallbackStruct)); - if(err != noErr) - { - ERR("AudioUnitSetProperty failed\n"); - return false; - } - - /* init the default audio unit... */ - err = AudioUnitInitialize(mAudioUnit); - if(err != noErr) - { - ERR("AudioUnitInitialize failed\n"); - return false; - } - - return true; -} - -void CoreAudioPlayback::start() -{ - const OSStatus err{AudioOutputUnitStart(mAudioUnit)}; - if(err != noErr) - throw al::backend_exception{al::backend_error::DeviceError, - "AudioOutputUnitStart failed: %d", err}; -} - -void CoreAudioPlayback::stop() -{ - OSStatus err{AudioOutputUnitStop(mAudioUnit)}; - if(err != noErr) - ERR("AudioOutputUnitStop failed\n"); -} - - -struct CoreAudioCapture final : public BackendBase { - CoreAudioCapture(ALCdevice *device) noexcept : BackendBase{device} { } - ~CoreAudioCapture() override; - - OSStatus RecordProc(AudioUnitRenderActionFlags *ioActionFlags, - const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, - UInt32 inNumberFrames, AudioBufferList *ioData) noexcept; - static OSStatus RecordProcC(void *inRefCon, AudioUnitRenderActionFlags *ioActionFlags, - const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, - AudioBufferList *ioData) noexcept - { - return static_cast(inRefCon)->RecordProc(ioActionFlags, inTimeStamp, - inBusNumber, inNumberFrames, ioData); - } - - void open(const char *name) override; - void start() override; - void stop() override; - void captureSamples(al::byte *buffer, uint samples) override; - uint availableSamples() override; - - AudioUnit mAudioUnit{0}; - - uint mFrameSize{0u}; - AudioStreamBasicDescription mFormat{}; // This is the OpenAL format as a CoreAudio ASBD - - SampleConverterPtr mConverter; - - RingBufferPtr mRing{nullptr}; - - DEF_NEWDEL(CoreAudioCapture) -}; - -CoreAudioCapture::~CoreAudioCapture() -{ - if(mAudioUnit) - AudioComponentInstanceDispose(mAudioUnit); - mAudioUnit = 0; -} - - -OSStatus CoreAudioCapture::RecordProc(AudioUnitRenderActionFlags*, - const AudioTimeStamp *inTimeStamp, UInt32, UInt32 inNumberFrames, - AudioBufferList*) noexcept -{ - AudioUnitRenderActionFlags flags = 0; - union { - al::byte _[sizeof(AudioBufferList) + sizeof(AudioBuffer)*2]; - AudioBufferList list; - } audiobuf{}; - - auto rec_vec = mRing->getWriteVector(); - inNumberFrames = static_cast(minz(inNumberFrames, - rec_vec.first.len+rec_vec.second.len)); - - // Fill the ringbuffer's two segments with data from the input device - if(rec_vec.first.len >= inNumberFrames) - { - audiobuf.list.mNumberBuffers = 1; - audiobuf.list.mBuffers[0].mNumberChannels = mFormat.mChannelsPerFrame; - audiobuf.list.mBuffers[0].mData = rec_vec.first.buf; - audiobuf.list.mBuffers[0].mDataByteSize = inNumberFrames * mFormat.mBytesPerFrame; - } - else - { - const auto remaining = static_cast(inNumberFrames - rec_vec.first.len); - audiobuf.list.mNumberBuffers = 2; - audiobuf.list.mBuffers[0].mNumberChannels = mFormat.mChannelsPerFrame; - audiobuf.list.mBuffers[0].mData = rec_vec.first.buf; - audiobuf.list.mBuffers[0].mDataByteSize = static_cast(rec_vec.first.len) * - mFormat.mBytesPerFrame; - audiobuf.list.mBuffers[1].mNumberChannels = mFormat.mChannelsPerFrame; - audiobuf.list.mBuffers[1].mData = rec_vec.second.buf; - audiobuf.list.mBuffers[1].mDataByteSize = remaining * mFormat.mBytesPerFrame; - } - OSStatus err{AudioUnitRender(mAudioUnit, &flags, inTimeStamp, audiobuf.list.mNumberBuffers, - inNumberFrames, &audiobuf.list)}; - if(err != noErr) - { - ERR("AudioUnitRender error: %d\n", err); - return err; - } - - mRing->writeAdvance(inNumberFrames); - return noErr; -} - - -void CoreAudioCapture::open(const char *name) -{ - AudioStreamBasicDescription requestedFormat; // The application requested format - AudioStreamBasicDescription hardwareFormat; // The hardware format - AudioStreamBasicDescription outputFormat; // The AudioUnit output format - AURenderCallbackStruct input; - AudioComponentDescription desc; - UInt32 propertySize; - UInt32 enableIO; - AudioComponent comp; - OSStatus err; - - if(!name) - name = ca_device; - else if(strcmp(name, ca_device) != 0) - throw al::backend_exception{al::backend_error::NoDevice, "Device name \"%s\" not found", - name}; - - desc.componentType = kAudioUnitType_Output; -#if TARGET_OS_IOS - desc.componentSubType = kAudioUnitSubType_RemoteIO; -#else - desc.componentSubType = kAudioUnitSubType_HALOutput; -#endif - desc.componentManufacturer = kAudioUnitManufacturer_Apple; - desc.componentFlags = 0; - desc.componentFlagsMask = 0; - - // Search for component with given description - comp = AudioComponentFindNext(NULL, &desc); - if(comp == NULL) - throw al::backend_exception{al::backend_error::NoDevice, "Could not find audio component"}; - - // Open the component - err = AudioComponentInstanceNew(comp, &mAudioUnit); - if(err != noErr) - throw al::backend_exception{al::backend_error::NoDevice, - "Could not create component instance: %u", err}; - - // Turn off AudioUnit output - enableIO = 0; - err = AudioUnitSetProperty(mAudioUnit, kAudioOutputUnitProperty_EnableIO, - kAudioUnitScope_Output, 0, &enableIO, sizeof(enableIO)); - if(err != noErr) - throw al::backend_exception{al::backend_error::DeviceError, - "Could not disable audio unit output property: %u", err}; - - // Turn on AudioUnit input - enableIO = 1; - err = AudioUnitSetProperty(mAudioUnit, kAudioOutputUnitProperty_EnableIO, - kAudioUnitScope_Input, 1, &enableIO, sizeof(enableIO)); - if(err != noErr) - throw al::backend_exception{al::backend_error::DeviceError, - "Could not enable audio unit input property: %u", err}; - -#if !TARGET_OS_IOS - { - // Get the default input device - AudioDeviceID inputDevice = kAudioDeviceUnknown; - - propertySize = sizeof(AudioDeviceID); - AudioObjectPropertyAddress propertyAddress{}; - propertyAddress.mSelector = kAudioHardwarePropertyDefaultInputDevice; - propertyAddress.mScope = kAudioObjectPropertyScopeGlobal; - propertyAddress.mElement = kAudioObjectPropertyElementMaster; - - err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &propertyAddress, 0, nullptr, - &propertySize, &inputDevice); - if(err != noErr) - throw al::backend_exception{al::backend_error::NoDevice, - "Could not get input device: %u", err}; - if(inputDevice == kAudioDeviceUnknown) - throw al::backend_exception{al::backend_error::NoDevice, "Unknown input device"}; - - // Track the input device - err = AudioUnitSetProperty(mAudioUnit, kAudioOutputUnitProperty_CurrentDevice, - kAudioUnitScope_Global, 0, &inputDevice, sizeof(AudioDeviceID)); - if(err != noErr) - throw al::backend_exception{al::backend_error::NoDevice, - "Could not set input device: %u", err}; - } -#endif - - // set capture callback - input.inputProc = CoreAudioCapture::RecordProcC; - input.inputProcRefCon = this; - - err = AudioUnitSetProperty(mAudioUnit, kAudioOutputUnitProperty_SetInputCallback, - kAudioUnitScope_Global, 0, &input, sizeof(AURenderCallbackStruct)); - if(err != noErr) - throw al::backend_exception{al::backend_error::DeviceError, - "Could not set capture callback: %u", err}; - - // Disable buffer allocation for capture - UInt32 flag{0}; - err = AudioUnitSetProperty(mAudioUnit, kAudioUnitProperty_ShouldAllocateBuffer, - kAudioUnitScope_Output, 1, &flag, sizeof(flag)); - if(err != noErr) - throw al::backend_exception{al::backend_error::DeviceError, - "Could not disable buffer allocation property: %u", err}; - - // Initialize the device - err = AudioUnitInitialize(mAudioUnit); - if(err != noErr) - throw al::backend_exception{al::backend_error::DeviceError, - "Could not initialize audio unit: %u", err}; - - // Get the hardware format - propertySize = sizeof(AudioStreamBasicDescription); - err = AudioUnitGetProperty(mAudioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, - 1, &hardwareFormat, &propertySize); - if(err != noErr || propertySize != sizeof(AudioStreamBasicDescription)) - throw al::backend_exception{al::backend_error::DeviceError, - "Could not get input format: %u", err}; - - // Set up the requested format description - switch(mDevice->FmtType) - { - case DevFmtByte: - requestedFormat.mBitsPerChannel = 8; - requestedFormat.mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked; - break; - case DevFmtUByte: - requestedFormat.mBitsPerChannel = 8; - requestedFormat.mFormatFlags = kAudioFormatFlagIsPacked; - break; - case DevFmtShort: - requestedFormat.mBitsPerChannel = 16; - requestedFormat.mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagsNativeEndian | kAudioFormatFlagIsPacked; - break; - case DevFmtUShort: - requestedFormat.mBitsPerChannel = 16; - requestedFormat.mFormatFlags = kAudioFormatFlagsNativeEndian | kAudioFormatFlagIsPacked; - break; - case DevFmtInt: - requestedFormat.mBitsPerChannel = 32; - requestedFormat.mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagsNativeEndian | kAudioFormatFlagIsPacked; - break; - case DevFmtUInt: - requestedFormat.mBitsPerChannel = 32; - requestedFormat.mFormatFlags = kAudioFormatFlagsNativeEndian | kAudioFormatFlagIsPacked; - break; - case DevFmtFloat: - requestedFormat.mBitsPerChannel = 32; - requestedFormat.mFormatFlags = kLinearPCMFormatFlagIsFloat | kAudioFormatFlagsNativeEndian | kAudioFormatFlagIsPacked; - break; - } - - switch(mDevice->FmtChans) - { - case DevFmtMono: - requestedFormat.mChannelsPerFrame = 1; - break; - case DevFmtStereo: - requestedFormat.mChannelsPerFrame = 2; - break; - - case DevFmtQuad: - case DevFmtX51: - case DevFmtX51Rear: - case DevFmtX61: - case DevFmtX71: - case DevFmtAmbi3D: - throw al::backend_exception{al::backend_error::DeviceError, "%s not supported", - DevFmtChannelsString(mDevice->FmtChans)}; - } - - requestedFormat.mBytesPerFrame = requestedFormat.mChannelsPerFrame * requestedFormat.mBitsPerChannel / 8; - requestedFormat.mBytesPerPacket = requestedFormat.mBytesPerFrame; - requestedFormat.mSampleRate = mDevice->Frequency; - requestedFormat.mFormatID = kAudioFormatLinearPCM; - requestedFormat.mReserved = 0; - requestedFormat.mFramesPerPacket = 1; - - // save requested format description for later use - mFormat = requestedFormat; - mFrameSize = mDevice->frameSizeFromFmt(); - - // Use intermediate format for sample rate conversion (outputFormat) - // Set sample rate to the same as hardware for resampling later - outputFormat = requestedFormat; - outputFormat.mSampleRate = hardwareFormat.mSampleRate; - - // The output format should be the requested format, but using the hardware sample rate - // This is because the AudioUnit will automatically scale other properties, except for sample rate - err = AudioUnitSetProperty(mAudioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, - 1, &outputFormat, sizeof(outputFormat)); - if(err != noErr) - throw al::backend_exception{al::backend_error::DeviceError, - "Could not set input format: %u", err}; - - /* Calculate the minimum AudioUnit output format frame count for the pre- - * conversion ring buffer. Ensure at least 100ms for the total buffer. - */ - double srateScale{double{outputFormat.mSampleRate} / mDevice->Frequency}; - auto FrameCount64 = maxu64(static_cast(std::ceil(mDevice->BufferSize*srateScale)), - static_cast(outputFormat.mSampleRate)/10); - FrameCount64 += MaxResamplerPadding; - if(FrameCount64 > std::numeric_limits::max()) - throw al::backend_exception{al::backend_error::DeviceError, - "Calculated frame count is too large: %" PRIu64, FrameCount64}; - - UInt32 outputFrameCount{}; - propertySize = sizeof(outputFrameCount); - err = AudioUnitGetProperty(mAudioUnit, kAudioUnitProperty_MaximumFramesPerSlice, - kAudioUnitScope_Global, 0, &outputFrameCount, &propertySize); - if(err != noErr || propertySize != sizeof(outputFrameCount)) - throw al::backend_exception{al::backend_error::DeviceError, - "Could not get input frame count: %u", err}; - - outputFrameCount = static_cast(maxu64(outputFrameCount, FrameCount64)); - mRing = RingBuffer::Create(outputFrameCount, mFrameSize, false); - - /* Set up sample converter if needed */ - if(outputFormat.mSampleRate != mDevice->Frequency) - mConverter = CreateSampleConverter(mDevice->FmtType, mDevice->FmtType, - mFormat.mChannelsPerFrame, static_cast(hardwareFormat.mSampleRate), - mDevice->Frequency, Resampler::FastBSinc24); - - mDevice->DeviceName = name; -} - - -void CoreAudioCapture::start() -{ - OSStatus err{AudioOutputUnitStart(mAudioUnit)}; - if(err != noErr) - throw al::backend_exception{al::backend_error::DeviceError, - "AudioOutputUnitStart failed: %d", err}; -} - -void CoreAudioCapture::stop() -{ - OSStatus err{AudioOutputUnitStop(mAudioUnit)}; - if(err != noErr) - ERR("AudioOutputUnitStop failed\n"); -} - -void CoreAudioCapture::captureSamples(al::byte *buffer, uint samples) -{ - if(!mConverter) - { - mRing->read(buffer, samples); - return; - } - - auto rec_vec = mRing->getReadVector(); - const void *src0{rec_vec.first.buf}; - auto src0len = static_cast(rec_vec.first.len); - uint got{mConverter->convert(&src0, &src0len, buffer, samples)}; - size_t total_read{rec_vec.first.len - src0len}; - if(got < samples && !src0len && rec_vec.second.len > 0) - { - const void *src1{rec_vec.second.buf}; - auto src1len = static_cast(rec_vec.second.len); - got += mConverter->convert(&src1, &src1len, buffer + got*mFrameSize, samples-got); - total_read += rec_vec.second.len - src1len; - } - - mRing->readAdvance(total_read); -} - -uint CoreAudioCapture::availableSamples() -{ - if(!mConverter) return static_cast(mRing->readSpace()); - return mConverter->availableOut(static_cast(mRing->readSpace())); -} - -} // namespace - -BackendFactory &CoreAudioBackendFactory::getFactory() -{ - static CoreAudioBackendFactory factory{}; - return factory; -} - -bool CoreAudioBackendFactory::init() { return true; } - -bool CoreAudioBackendFactory::querySupport(BackendType type) -{ return type == BackendType::Playback || type == BackendType::Capture; } - -std::string CoreAudioBackendFactory::probe(BackendType type) -{ - std::string outnames; - switch(type) - { - case BackendType::Playback: - case BackendType::Capture: - /* Includes null char. */ - outnames.append(ca_device, sizeof(ca_device)); - break; - } - return outnames; -} - -BackendPtr CoreAudioBackendFactory::createBackend(ALCdevice *device, BackendType type) -{ - if(type == BackendType::Playback) - return BackendPtr{new CoreAudioPlayback{device}}; - if(type == BackendType::Capture) - return BackendPtr{new CoreAudioCapture{device}}; - return nullptr; -} diff --git a/alc/backends/coreaudio.h b/alc/backends/coreaudio.h deleted file mode 100644 index 16957806..00000000 --- a/alc/backends/coreaudio.h +++ /dev/null @@ -1,19 +0,0 @@ -#ifndef BACKENDS_COREAUDIO_H -#define BACKENDS_COREAUDIO_H - -#include "backends/base.h" - -struct CoreAudioBackendFactory final : public BackendFactory { -public: - bool init() override; - - bool querySupport(BackendType type) override; - - std::string probe(BackendType type) override; - - BackendPtr createBackend(ALCdevice *device, BackendType type) override; - - static BackendFactory &getFactory(); -}; - -#endif /* BACKENDS_COREAUDIO_H */ diff --git a/alc/backends/dsound.cpp b/alc/backends/dsound.cpp deleted file mode 100644 index aa3a92a0..00000000 --- a/alc/backends/dsound.cpp +++ /dev/null @@ -1,868 +0,0 @@ -/** - * OpenAL cross platform audio library - * Copyright (C) 1999-2007 by authors. - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - * Or go to http://www.gnu.org/copyleft/lgpl.html - */ - -#include "config.h" - -#include "backends/dsound.h" - -#define WIN32_LEAN_AND_MEAN -#include - -#include -#include -#include - -#include -#include -#ifndef _WAVEFORMATEXTENSIBLE_ -#include -#include -#endif - -#include -#include -#include -#include -#include -#include -#include - -#include "alcmain.h" -#include "alu.h" -#include "compat.h" -#include "core/logging.h" -#include "dynload.h" -#include "ringbuffer.h" -#include "strutils.h" -#include "threads.h" - -/* MinGW-w64 needs this for some unknown reason now. */ -using LPCWAVEFORMATEX = const WAVEFORMATEX*; -#include - - -#ifndef DSSPEAKER_5POINT1 -# define DSSPEAKER_5POINT1 0x00000006 -#endif -#ifndef DSSPEAKER_5POINT1_BACK -# define DSSPEAKER_5POINT1_BACK 0x00000006 -#endif -#ifndef DSSPEAKER_7POINT1 -# define DSSPEAKER_7POINT1 0x00000007 -#endif -#ifndef DSSPEAKER_7POINT1_SURROUND -# define DSSPEAKER_7POINT1_SURROUND 0x00000008 -#endif -#ifndef DSSPEAKER_5POINT1_SURROUND -# define DSSPEAKER_5POINT1_SURROUND 0x00000009 -#endif - - -/* Some headers seem to define these as macros for __uuidof, which is annoying - * since some headers don't declare them at all. Hopefully the ifdef is enough - * to tell if they need to be declared. - */ -#ifndef KSDATAFORMAT_SUBTYPE_PCM -DEFINE_GUID(KSDATAFORMAT_SUBTYPE_PCM, 0x00000001, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); -#endif -#ifndef KSDATAFORMAT_SUBTYPE_IEEE_FLOAT -DEFINE_GUID(KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, 0x00000003, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); -#endif - -namespace { - -#define DEVNAME_HEAD "OpenAL Soft on " - - -#ifdef HAVE_DYNLOAD -void *ds_handle; -HRESULT (WINAPI *pDirectSoundCreate)(const GUID *pcGuidDevice, IDirectSound **ppDS, IUnknown *pUnkOuter); -HRESULT (WINAPI *pDirectSoundEnumerateW)(LPDSENUMCALLBACKW pDSEnumCallback, void *pContext); -HRESULT (WINAPI *pDirectSoundCaptureCreate)(const GUID *pcGuidDevice, IDirectSoundCapture **ppDSC, IUnknown *pUnkOuter); -HRESULT (WINAPI *pDirectSoundCaptureEnumerateW)(LPDSENUMCALLBACKW pDSEnumCallback, void *pContext); - -#ifndef IN_IDE_PARSER -#define DirectSoundCreate pDirectSoundCreate -#define DirectSoundEnumerateW pDirectSoundEnumerateW -#define DirectSoundCaptureCreate pDirectSoundCaptureCreate -#define DirectSoundCaptureEnumerateW pDirectSoundCaptureEnumerateW -#endif -#endif - - -#define MONO SPEAKER_FRONT_CENTER -#define STEREO (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT) -#define QUAD (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_BACK_LEFT|SPEAKER_BACK_RIGHT) -#define X5DOT1 (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_SIDE_LEFT|SPEAKER_SIDE_RIGHT) -#define X5DOT1REAR (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_BACK_LEFT|SPEAKER_BACK_RIGHT) -#define X6DOT1 (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_BACK_CENTER|SPEAKER_SIDE_LEFT|SPEAKER_SIDE_RIGHT) -#define X7DOT1 (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_BACK_LEFT|SPEAKER_BACK_RIGHT|SPEAKER_SIDE_LEFT|SPEAKER_SIDE_RIGHT) - -#define MAX_UPDATES 128 - -struct DevMap { - std::string name; - GUID guid; - - template - DevMap(T0&& name_, T1&& guid_) - : name{std::forward(name_)}, guid{std::forward(guid_)} - { } -}; - -al::vector PlaybackDevices; -al::vector CaptureDevices; - -bool checkName(const al::vector &list, const std::string &name) -{ - auto match_name = [&name](const DevMap &entry) -> bool - { return entry.name == name; }; - return std::find_if(list.cbegin(), list.cend(), match_name) != list.cend(); -} - -BOOL CALLBACK DSoundEnumDevices(GUID *guid, const WCHAR *desc, const WCHAR*, void *data) noexcept -{ - if(!guid) - return TRUE; - - auto& devices = *static_cast*>(data); - const std::string basename{DEVNAME_HEAD + wstr_to_utf8(desc)}; - - int count{1}; - std::string newname{basename}; - while(checkName(devices, newname)) - { - newname = basename; - newname += " #"; - newname += std::to_string(++count); - } - devices.emplace_back(std::move(newname), *guid); - const DevMap &newentry = devices.back(); - - OLECHAR *guidstr{nullptr}; - HRESULT hr{StringFromCLSID(*guid, &guidstr)}; - if(SUCCEEDED(hr)) - { - TRACE("Got device \"%s\", GUID \"%ls\"\n", newentry.name.c_str(), guidstr); - CoTaskMemFree(guidstr); - } - - return TRUE; -} - - -struct DSoundPlayback final : public BackendBase { - DSoundPlayback(ALCdevice *device) noexcept : BackendBase{device} { } - ~DSoundPlayback() override; - - int mixerProc(); - - void open(const ALCchar *name) override; - bool reset() override; - void start() override; - void stop() override; - - IDirectSound *mDS{nullptr}; - IDirectSoundBuffer *mPrimaryBuffer{nullptr}; - IDirectSoundBuffer *mBuffer{nullptr}; - IDirectSoundNotify *mNotifies{nullptr}; - HANDLE mNotifyEvent{nullptr}; - - std::atomic mKillNow{true}; - std::thread mThread; - - DEF_NEWDEL(DSoundPlayback) -}; - -DSoundPlayback::~DSoundPlayback() -{ - if(mNotifies) - mNotifies->Release(); - mNotifies = nullptr; - if(mBuffer) - mBuffer->Release(); - mBuffer = nullptr; - if(mPrimaryBuffer) - mPrimaryBuffer->Release(); - mPrimaryBuffer = nullptr; - - if(mDS) - mDS->Release(); - mDS = nullptr; - if(mNotifyEvent) - CloseHandle(mNotifyEvent); - mNotifyEvent = nullptr; -} - - -FORCE_ALIGN int DSoundPlayback::mixerProc() -{ - SetRTPriority(); - althrd_setname(MIXER_THREAD_NAME); - - DSBCAPS DSBCaps{}; - DSBCaps.dwSize = sizeof(DSBCaps); - HRESULT err{mBuffer->GetCaps(&DSBCaps)}; - if(FAILED(err)) - { - ERR("Failed to get buffer caps: 0x%lx\n", err); - mDevice->handleDisconnect("Failure retrieving playback buffer info: 0x%lx", err); - return 1; - } - - const size_t FrameStep{mDevice->channelsFromFmt()}; - uint FrameSize{mDevice->frameSizeFromFmt()}; - DWORD FragSize{mDevice->UpdateSize * FrameSize}; - - bool Playing{false}; - DWORD LastCursor{0u}; - mBuffer->GetCurrentPosition(&LastCursor, nullptr); - while(!mKillNow.load(std::memory_order_acquire) && - mDevice->Connected.load(std::memory_order_acquire)) - { - // Get current play cursor - DWORD PlayCursor; - mBuffer->GetCurrentPosition(&PlayCursor, nullptr); - DWORD avail = (PlayCursor-LastCursor+DSBCaps.dwBufferBytes) % DSBCaps.dwBufferBytes; - - if(avail < FragSize) - { - if(!Playing) - { - err = mBuffer->Play(0, 0, DSBPLAY_LOOPING); - if(FAILED(err)) - { - ERR("Failed to play buffer: 0x%lx\n", err); - mDevice->handleDisconnect("Failure starting playback: 0x%lx", err); - return 1; - } - Playing = true; - } - - avail = WaitForSingleObjectEx(mNotifyEvent, 2000, FALSE); - if(avail != WAIT_OBJECT_0) - ERR("WaitForSingleObjectEx error: 0x%lx\n", avail); - continue; - } - avail -= avail%FragSize; - - // Lock output buffer - void *WritePtr1, *WritePtr2; - DWORD WriteCnt1{0u}, WriteCnt2{0u}; - err = mBuffer->Lock(LastCursor, avail, &WritePtr1, &WriteCnt1, &WritePtr2, &WriteCnt2, 0); - - // If the buffer is lost, restore it and lock - if(err == DSERR_BUFFERLOST) - { - WARN("Buffer lost, restoring...\n"); - err = mBuffer->Restore(); - if(SUCCEEDED(err)) - { - Playing = false; - LastCursor = 0; - err = mBuffer->Lock(0, DSBCaps.dwBufferBytes, &WritePtr1, &WriteCnt1, - &WritePtr2, &WriteCnt2, 0); - } - } - - if(SUCCEEDED(err)) - { - mDevice->renderSamples(WritePtr1, WriteCnt1/FrameSize, FrameStep); - if(WriteCnt2 > 0) - mDevice->renderSamples(WritePtr2, WriteCnt2/FrameSize, FrameStep); - - mBuffer->Unlock(WritePtr1, WriteCnt1, WritePtr2, WriteCnt2); - } - else - { - ERR("Buffer lock error: %#lx\n", err); - mDevice->handleDisconnect("Failed to lock output buffer: 0x%lx", err); - return 1; - } - - // Update old write cursor location - LastCursor += WriteCnt1+WriteCnt2; - LastCursor %= DSBCaps.dwBufferBytes; - } - - return 0; -} - -void DSoundPlayback::open(const char *name) -{ - HRESULT hr; - if(PlaybackDevices.empty()) - { - /* Initialize COM to prevent name truncation */ - HRESULT hrcom{CoInitialize(nullptr)}; - hr = DirectSoundEnumerateW(DSoundEnumDevices, &PlaybackDevices); - if(FAILED(hr)) - ERR("Error enumerating DirectSound devices (0x%lx)!\n", hr); - if(SUCCEEDED(hrcom)) - CoUninitialize(); - } - - const GUID *guid{nullptr}; - if(!name && !PlaybackDevices.empty()) - { - name = PlaybackDevices[0].name.c_str(); - guid = &PlaybackDevices[0].guid; - } - else - { - auto iter = std::find_if(PlaybackDevices.cbegin(), PlaybackDevices.cend(), - [name](const DevMap &entry) -> bool { return entry.name == name; }); - if(iter == PlaybackDevices.cend()) - { - GUID id{}; - hr = CLSIDFromString(utf8_to_wstr(name).c_str(), &id); - if(SUCCEEDED(hr)) - iter = std::find_if(PlaybackDevices.cbegin(), PlaybackDevices.cend(), - [&id](const DevMap &entry) -> bool { return entry.guid == id; }); - if(iter == PlaybackDevices.cend()) - throw al::backend_exception{al::backend_error::NoDevice, - "Device name \"%s\" not found", name}; - } - guid = &iter->guid; - } - - hr = DS_OK; - mNotifyEvent = CreateEventW(nullptr, FALSE, FALSE, nullptr); - if(!mNotifyEvent) hr = E_FAIL; - - //DirectSound Init code - if(SUCCEEDED(hr)) - hr = DirectSoundCreate(guid, &mDS, nullptr); - if(SUCCEEDED(hr)) - hr = mDS->SetCooperativeLevel(GetForegroundWindow(), DSSCL_PRIORITY); - if(FAILED(hr)) - throw al::backend_exception{al::backend_error::DeviceError, "Device init failed: 0x%08lx", - hr}; - - mDevice->DeviceName = name; -} - -bool DSoundPlayback::reset() -{ - if(mNotifies) - mNotifies->Release(); - mNotifies = nullptr; - if(mBuffer) - mBuffer->Release(); - mBuffer = nullptr; - if(mPrimaryBuffer) - mPrimaryBuffer->Release(); - mPrimaryBuffer = nullptr; - - switch(mDevice->FmtType) - { - case DevFmtByte: - mDevice->FmtType = DevFmtUByte; - break; - case DevFmtFloat: - if(mDevice->Flags.test(SampleTypeRequest)) - break; - /* fall-through */ - case DevFmtUShort: - mDevice->FmtType = DevFmtShort; - break; - case DevFmtUInt: - mDevice->FmtType = DevFmtInt; - break; - case DevFmtUByte: - case DevFmtShort: - case DevFmtInt: - break; - } - - WAVEFORMATEXTENSIBLE OutputType{}; - DWORD speakers; - HRESULT hr{mDS->GetSpeakerConfig(&speakers)}; - if(SUCCEEDED(hr)) - { - speakers = DSSPEAKER_CONFIG(speakers); - if(!mDevice->Flags.test(ChannelsRequest)) - { - if(speakers == DSSPEAKER_MONO) - mDevice->FmtChans = DevFmtMono; - else if(speakers == DSSPEAKER_STEREO || speakers == DSSPEAKER_HEADPHONE) - mDevice->FmtChans = DevFmtStereo; - else if(speakers == DSSPEAKER_QUAD) - mDevice->FmtChans = DevFmtQuad; - else if(speakers == DSSPEAKER_5POINT1_SURROUND) - mDevice->FmtChans = DevFmtX51; - else if(speakers == DSSPEAKER_5POINT1_BACK) - mDevice->FmtChans = DevFmtX51Rear; - else if(speakers == DSSPEAKER_7POINT1 || speakers == DSSPEAKER_7POINT1_SURROUND) - mDevice->FmtChans = DevFmtX71; - else - ERR("Unknown system speaker config: 0x%lx\n", speakers); - } - mDevice->IsHeadphones = mDevice->FmtChans == DevFmtStereo - && speakers == DSSPEAKER_HEADPHONE; - - switch(mDevice->FmtChans) - { - case DevFmtMono: OutputType.dwChannelMask = MONO; break; - case DevFmtAmbi3D: mDevice->FmtChans = DevFmtStereo; - /*fall-through*/ - case DevFmtStereo: OutputType.dwChannelMask = STEREO; break; - case DevFmtQuad: OutputType.dwChannelMask = QUAD; break; - case DevFmtX51: OutputType.dwChannelMask = X5DOT1; break; - case DevFmtX51Rear: OutputType.dwChannelMask = X5DOT1REAR; break; - case DevFmtX61: OutputType.dwChannelMask = X6DOT1; break; - case DevFmtX71: OutputType.dwChannelMask = X7DOT1; break; - } - -retry_open: - hr = S_OK; - OutputType.Format.wFormatTag = WAVE_FORMAT_PCM; - OutputType.Format.nChannels = static_cast(mDevice->channelsFromFmt()); - OutputType.Format.wBitsPerSample = static_cast(mDevice->bytesFromFmt() * 8); - OutputType.Format.nBlockAlign = static_cast(OutputType.Format.nChannels * - OutputType.Format.wBitsPerSample / 8); - OutputType.Format.nSamplesPerSec = mDevice->Frequency; - OutputType.Format.nAvgBytesPerSec = OutputType.Format.nSamplesPerSec * - OutputType.Format.nBlockAlign; - OutputType.Format.cbSize = 0; - } - - if(OutputType.Format.nChannels > 2 || mDevice->FmtType == DevFmtFloat) - { - OutputType.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE; - OutputType.Samples.wValidBitsPerSample = OutputType.Format.wBitsPerSample; - OutputType.Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX); - if(mDevice->FmtType == DevFmtFloat) - OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT; - else - OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM; - - if(mPrimaryBuffer) - mPrimaryBuffer->Release(); - mPrimaryBuffer = nullptr; - } - else - { - if(SUCCEEDED(hr) && !mPrimaryBuffer) - { - DSBUFFERDESC DSBDescription{}; - DSBDescription.dwSize = sizeof(DSBDescription); - DSBDescription.dwFlags = DSBCAPS_PRIMARYBUFFER; - hr = mDS->CreateSoundBuffer(&DSBDescription, &mPrimaryBuffer, nullptr); - } - if(SUCCEEDED(hr)) - hr = mPrimaryBuffer->SetFormat(&OutputType.Format); - } - - if(SUCCEEDED(hr)) - { - uint num_updates{mDevice->BufferSize / mDevice->UpdateSize}; - if(num_updates > MAX_UPDATES) - num_updates = MAX_UPDATES; - mDevice->BufferSize = mDevice->UpdateSize * num_updates; - - DSBUFFERDESC DSBDescription{}; - DSBDescription.dwSize = sizeof(DSBDescription); - DSBDescription.dwFlags = DSBCAPS_CTRLPOSITIONNOTIFY | DSBCAPS_GETCURRENTPOSITION2 - | DSBCAPS_GLOBALFOCUS; - DSBDescription.dwBufferBytes = mDevice->BufferSize * OutputType.Format.nBlockAlign; - DSBDescription.lpwfxFormat = &OutputType.Format; - - hr = mDS->CreateSoundBuffer(&DSBDescription, &mBuffer, nullptr); - if(FAILED(hr) && mDevice->FmtType == DevFmtFloat) - { - mDevice->FmtType = DevFmtShort; - goto retry_open; - } - } - - if(SUCCEEDED(hr)) - { - void *ptr; - hr = mBuffer->QueryInterface(IID_IDirectSoundNotify, &ptr); - if(SUCCEEDED(hr)) - { - mNotifies = static_cast(ptr); - - uint num_updates{mDevice->BufferSize / mDevice->UpdateSize}; - assert(num_updates <= MAX_UPDATES); - - std::array nots; - for(uint i{0};i < num_updates;++i) - { - nots[i].dwOffset = i * mDevice->UpdateSize * OutputType.Format.nBlockAlign; - nots[i].hEventNotify = mNotifyEvent; - } - if(mNotifies->SetNotificationPositions(num_updates, nots.data()) != DS_OK) - hr = E_FAIL; - } - } - - if(FAILED(hr)) - { - if(mNotifies) - mNotifies->Release(); - mNotifies = nullptr; - if(mBuffer) - mBuffer->Release(); - mBuffer = nullptr; - if(mPrimaryBuffer) - mPrimaryBuffer->Release(); - mPrimaryBuffer = nullptr; - return false; - } - - ResetEvent(mNotifyEvent); - setChannelOrderFromWFXMask(OutputType.dwChannelMask); - - return true; -} - -void DSoundPlayback::start() -{ - try { - mKillNow.store(false, std::memory_order_release); - mThread = std::thread{std::mem_fn(&DSoundPlayback::mixerProc), this}; - } - catch(std::exception& e) { - throw al::backend_exception{al::backend_error::DeviceError, - "Failed to start mixing thread: %s", e.what()}; - } -} - -void DSoundPlayback::stop() -{ - if(mKillNow.exchange(true, std::memory_order_acq_rel) || !mThread.joinable()) - return; - mThread.join(); - - mBuffer->Stop(); -} - - -struct DSoundCapture final : public BackendBase { - DSoundCapture(ALCdevice *device) noexcept : BackendBase{device} { } - ~DSoundCapture() override; - - void open(const char *name) override; - void start() override; - void stop() override; - void captureSamples(al::byte *buffer, uint samples) override; - uint availableSamples() override; - - IDirectSoundCapture *mDSC{nullptr}; - IDirectSoundCaptureBuffer *mDSCbuffer{nullptr}; - DWORD mBufferBytes{0u}; - DWORD mCursor{0u}; - - RingBufferPtr mRing; - - DEF_NEWDEL(DSoundCapture) -}; - -DSoundCapture::~DSoundCapture() -{ - if(mDSCbuffer) - { - mDSCbuffer->Stop(); - mDSCbuffer->Release(); - mDSCbuffer = nullptr; - } - - if(mDSC) - mDSC->Release(); - mDSC = nullptr; -} - - -void DSoundCapture::open(const char *name) -{ - HRESULT hr; - if(CaptureDevices.empty()) - { - /* Initialize COM to prevent name truncation */ - HRESULT hrcom{CoInitialize(nullptr)}; - hr = DirectSoundCaptureEnumerateW(DSoundEnumDevices, &CaptureDevices); - if(FAILED(hr)) - ERR("Error enumerating DirectSound devices (0x%lx)!\n", hr); - if(SUCCEEDED(hrcom)) - CoUninitialize(); - } - - const GUID *guid{nullptr}; - if(!name && !CaptureDevices.empty()) - { - name = CaptureDevices[0].name.c_str(); - guid = &CaptureDevices[0].guid; - } - else - { - auto iter = std::find_if(CaptureDevices.cbegin(), CaptureDevices.cend(), - [name](const DevMap &entry) -> bool { return entry.name == name; }); - if(iter == CaptureDevices.cend()) - { - GUID id{}; - hr = CLSIDFromString(utf8_to_wstr(name).c_str(), &id); - if(SUCCEEDED(hr)) - iter = std::find_if(CaptureDevices.cbegin(), CaptureDevices.cend(), - [&id](const DevMap &entry) -> bool { return entry.guid == id; }); - if(iter == CaptureDevices.cend()) - throw al::backend_exception{al::backend_error::NoDevice, - "Device name \"%s\" not found", name}; - } - guid = &iter->guid; - } - - switch(mDevice->FmtType) - { - case DevFmtByte: - case DevFmtUShort: - case DevFmtUInt: - WARN("%s capture samples not supported\n", DevFmtTypeString(mDevice->FmtType)); - throw al::backend_exception{al::backend_error::DeviceError, - "%s capture samples not supported", DevFmtTypeString(mDevice->FmtType)}; - - case DevFmtUByte: - case DevFmtShort: - case DevFmtInt: - case DevFmtFloat: - break; - } - - WAVEFORMATEXTENSIBLE InputType{}; - switch(mDevice->FmtChans) - { - case DevFmtMono: InputType.dwChannelMask = MONO; break; - case DevFmtStereo: InputType.dwChannelMask = STEREO; break; - case DevFmtQuad: InputType.dwChannelMask = QUAD; break; - case DevFmtX51: InputType.dwChannelMask = X5DOT1; break; - case DevFmtX51Rear: InputType.dwChannelMask = X5DOT1REAR; break; - case DevFmtX61: InputType.dwChannelMask = X6DOT1; break; - case DevFmtX71: InputType.dwChannelMask = X7DOT1; break; - case DevFmtAmbi3D: - WARN("%s capture not supported\n", DevFmtChannelsString(mDevice->FmtChans)); - throw al::backend_exception{al::backend_error::DeviceError, "%s capture not supported", - DevFmtChannelsString(mDevice->FmtChans)}; - } - - InputType.Format.wFormatTag = WAVE_FORMAT_PCM; - InputType.Format.nChannels = static_cast(mDevice->channelsFromFmt()); - InputType.Format.wBitsPerSample = static_cast(mDevice->bytesFromFmt() * 8); - InputType.Format.nBlockAlign = static_cast(InputType.Format.nChannels * - InputType.Format.wBitsPerSample / 8); - InputType.Format.nSamplesPerSec = mDevice->Frequency; - InputType.Format.nAvgBytesPerSec = InputType.Format.nSamplesPerSec * - InputType.Format.nBlockAlign; - InputType.Format.cbSize = 0; - InputType.Samples.wValidBitsPerSample = InputType.Format.wBitsPerSample; - if(mDevice->FmtType == DevFmtFloat) - InputType.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT; - else - InputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM; - - if(InputType.Format.nChannels > 2 || mDevice->FmtType == DevFmtFloat) - { - InputType.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE; - InputType.Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX); - } - - uint samples{mDevice->BufferSize}; - samples = maxu(samples, 100 * mDevice->Frequency / 1000); - - DSCBUFFERDESC DSCBDescription{}; - DSCBDescription.dwSize = sizeof(DSCBDescription); - DSCBDescription.dwFlags = 0; - DSCBDescription.dwBufferBytes = samples * InputType.Format.nBlockAlign; - DSCBDescription.lpwfxFormat = &InputType.Format; - - //DirectSoundCapture Init code - hr = DirectSoundCaptureCreate(guid, &mDSC, nullptr); - if(SUCCEEDED(hr)) - mDSC->CreateCaptureBuffer(&DSCBDescription, &mDSCbuffer, nullptr); - if(SUCCEEDED(hr)) - mRing = RingBuffer::Create(mDevice->BufferSize, InputType.Format.nBlockAlign, false); - - if(FAILED(hr)) - { - mRing = nullptr; - if(mDSCbuffer) - mDSCbuffer->Release(); - mDSCbuffer = nullptr; - if(mDSC) - mDSC->Release(); - mDSC = nullptr; - - throw al::backend_exception{al::backend_error::DeviceError, "Device init failed: 0x%08lx", - hr}; - } - - mBufferBytes = DSCBDescription.dwBufferBytes; - setChannelOrderFromWFXMask(InputType.dwChannelMask); - - mDevice->DeviceName = name; -} - -void DSoundCapture::start() -{ - const HRESULT hr{mDSCbuffer->Start(DSCBSTART_LOOPING)}; - if(FAILED(hr)) - throw al::backend_exception{al::backend_error::DeviceError, - "Failure starting capture: 0x%lx", hr}; -} - -void DSoundCapture::stop() -{ - HRESULT hr{mDSCbuffer->Stop()}; - if(FAILED(hr)) - { - ERR("stop failed: 0x%08lx\n", hr); - mDevice->handleDisconnect("Failure stopping capture: 0x%lx", hr); - } -} - -void DSoundCapture::captureSamples(al::byte *buffer, uint samples) -{ mRing->read(buffer, samples); } - -uint DSoundCapture::availableSamples() -{ - if(!mDevice->Connected.load(std::memory_order_acquire)) - return static_cast(mRing->readSpace()); - - const uint FrameSize{mDevice->frameSizeFromFmt()}; - const DWORD BufferBytes{mBufferBytes}; - const DWORD LastCursor{mCursor}; - - DWORD ReadCursor{}; - void *ReadPtr1{}, *ReadPtr2{}; - DWORD ReadCnt1{}, ReadCnt2{}; - HRESULT hr{mDSCbuffer->GetCurrentPosition(nullptr, &ReadCursor)}; - if(SUCCEEDED(hr)) - { - const DWORD NumBytes{(BufferBytes+ReadCursor-LastCursor) % BufferBytes}; - if(!NumBytes) return static_cast(mRing->readSpace()); - hr = mDSCbuffer->Lock(LastCursor, NumBytes, &ReadPtr1, &ReadCnt1, &ReadPtr2, &ReadCnt2, 0); - } - if(SUCCEEDED(hr)) - { - mRing->write(ReadPtr1, ReadCnt1/FrameSize); - if(ReadPtr2 != nullptr && ReadCnt2 > 0) - mRing->write(ReadPtr2, ReadCnt2/FrameSize); - hr = mDSCbuffer->Unlock(ReadPtr1, ReadCnt1, ReadPtr2, ReadCnt2); - mCursor = ReadCursor; - } - - if(FAILED(hr)) - { - ERR("update failed: 0x%08lx\n", hr); - mDevice->handleDisconnect("Failure retrieving capture data: 0x%lx", hr); - } - - return static_cast(mRing->readSpace()); -} - -} // namespace - - -BackendFactory &DSoundBackendFactory::getFactory() -{ - static DSoundBackendFactory factory{}; - return factory; -} - -bool DSoundBackendFactory::init() -{ -#ifdef HAVE_DYNLOAD - if(!ds_handle) - { - ds_handle = LoadLib("dsound.dll"); - if(!ds_handle) - { - ERR("Failed to load dsound.dll\n"); - return false; - } - -#define LOAD_FUNC(f) do { \ - p##f = reinterpret_cast(GetSymbol(ds_handle, #f)); \ - if(!p##f) \ - { \ - CloseLib(ds_handle); \ - ds_handle = nullptr; \ - return false; \ - } \ -} while(0) - LOAD_FUNC(DirectSoundCreate); - LOAD_FUNC(DirectSoundEnumerateW); - LOAD_FUNC(DirectSoundCaptureCreate); - LOAD_FUNC(DirectSoundCaptureEnumerateW); -#undef LOAD_FUNC - } -#endif - return true; -} - -bool DSoundBackendFactory::querySupport(BackendType type) -{ return (type == BackendType::Playback || type == BackendType::Capture); } - -std::string DSoundBackendFactory::probe(BackendType type) -{ - std::string outnames; - auto add_device = [&outnames](const DevMap &entry) -> void - { - /* +1 to also append the null char (to ensure a null-separated list and - * double-null terminated list). - */ - outnames.append(entry.name.c_str(), entry.name.length()+1); - }; - - /* Initialize COM to prevent name truncation */ - HRESULT hr; - HRESULT hrcom{CoInitialize(nullptr)}; - switch(type) - { - case BackendType::Playback: - PlaybackDevices.clear(); - hr = DirectSoundEnumerateW(DSoundEnumDevices, &PlaybackDevices); - if(FAILED(hr)) - ERR("Error enumerating DirectSound playback devices (0x%lx)!\n", hr); - std::for_each(PlaybackDevices.cbegin(), PlaybackDevices.cend(), add_device); - break; - - case BackendType::Capture: - CaptureDevices.clear(); - hr = DirectSoundCaptureEnumerateW(DSoundEnumDevices, &CaptureDevices); - if(FAILED(hr)) - ERR("Error enumerating DirectSound capture devices (0x%lx)!\n", hr); - std::for_each(CaptureDevices.cbegin(), CaptureDevices.cend(), add_device); - break; - } - if(SUCCEEDED(hrcom)) - CoUninitialize(); - - return outnames; -} - -BackendPtr DSoundBackendFactory::createBackend(ALCdevice *device, BackendType type) -{ - if(type == BackendType::Playback) - return BackendPtr{new DSoundPlayback{device}}; - if(type == BackendType::Capture) - return BackendPtr{new DSoundCapture{device}}; - return nullptr; -} diff --git a/alc/backends/dsound.h b/alc/backends/dsound.h deleted file mode 100644 index 83f7d5c7..00000000 --- a/alc/backends/dsound.h +++ /dev/null @@ -1,19 +0,0 @@ -#ifndef BACKENDS_DSOUND_H -#define BACKENDS_DSOUND_H - -#include "backends/base.h" - -struct DSoundBackendFactory final : public BackendFactory { -public: - bool init() override; - - bool querySupport(BackendType type) override; - - std::string probe(BackendType type) override; - - BackendPtr createBackend(ALCdevice *device, BackendType type) override; - - static BackendFactory &getFactory(); -}; - -#endif /* BACKENDS_DSOUND_H */ diff --git a/alc/backends/jack.cpp b/alc/backends/jack.cpp deleted file mode 100644 index 7c9573ce..00000000 --- a/alc/backends/jack.cpp +++ /dev/null @@ -1,601 +0,0 @@ -/** - * OpenAL cross platform audio library - * Copyright (C) 1999-2007 by authors. - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - * Or go to http://www.gnu.org/copyleft/lgpl.html - */ - -#include "config.h" - -#include "backends/jack.h" - -#include -#include -#include -#include - -#include -#include -#include - -#include "alcmain.h" -#include "alu.h" -#include "alconfig.h" -#include "core/logging.h" -#include "dynload.h" -#include "ringbuffer.h" -#include "threads.h" - -#include -#include - - -namespace { - -constexpr char jackDevice[] = "JACK Default"; - - -#ifdef HAVE_DYNLOAD -#define JACK_FUNCS(MAGIC) \ - MAGIC(jack_client_open); \ - MAGIC(jack_client_close); \ - MAGIC(jack_client_name_size); \ - MAGIC(jack_get_client_name); \ - MAGIC(jack_connect); \ - MAGIC(jack_activate); \ - MAGIC(jack_deactivate); \ - MAGIC(jack_port_register); \ - MAGIC(jack_port_unregister); \ - MAGIC(jack_port_get_buffer); \ - MAGIC(jack_port_name); \ - MAGIC(jack_get_ports); \ - MAGIC(jack_free); \ - MAGIC(jack_get_sample_rate); \ - MAGIC(jack_set_error_function); \ - MAGIC(jack_set_process_callback); \ - MAGIC(jack_set_buffer_size_callback); \ - MAGIC(jack_set_buffer_size); \ - MAGIC(jack_get_buffer_size); - -void *jack_handle; -#define MAKE_FUNC(f) decltype(f) * p##f -JACK_FUNCS(MAKE_FUNC); -decltype(jack_error_callback) * pjack_error_callback; -#undef MAKE_FUNC - -#ifndef IN_IDE_PARSER -#define jack_client_open pjack_client_open -#define jack_client_close pjack_client_close -#define jack_client_name_size pjack_client_name_size -#define jack_get_client_name pjack_get_client_name -#define jack_connect pjack_connect -#define jack_activate pjack_activate -#define jack_deactivate pjack_deactivate -#define jack_port_register pjack_port_register -#define jack_port_unregister pjack_port_unregister -#define jack_port_get_buffer pjack_port_get_buffer -#define jack_port_name pjack_port_name -#define jack_get_ports pjack_get_ports -#define jack_free pjack_free -#define jack_get_sample_rate pjack_get_sample_rate -#define jack_set_error_function pjack_set_error_function -#define jack_set_process_callback pjack_set_process_callback -#define jack_set_buffer_size_callback pjack_set_buffer_size_callback -#define jack_set_buffer_size pjack_set_buffer_size -#define jack_get_buffer_size pjack_get_buffer_size -#define jack_error_callback (*pjack_error_callback) -#endif -#endif - - -jack_options_t ClientOptions = JackNullOption; - -bool jack_load() -{ - bool error{false}; - -#ifdef HAVE_DYNLOAD - if(!jack_handle) - { - std::string missing_funcs; - -#ifdef _WIN32 -#define JACKLIB "libjack.dll" -#else -#define JACKLIB "libjack.so.0" -#endif - jack_handle = LoadLib(JACKLIB); - if(!jack_handle) - { - WARN("Failed to load %s\n", JACKLIB); - return false; - } - - error = false; -#define LOAD_FUNC(f) do { \ - p##f = reinterpret_cast(GetSymbol(jack_handle, #f)); \ - if(p##f == nullptr) { \ - error = true; \ - missing_funcs += "\n" #f; \ - } \ -} while(0) - JACK_FUNCS(LOAD_FUNC); -#undef LOAD_FUNC - /* Optional symbols. These don't exist in all versions of JACK. */ -#define LOAD_SYM(f) p##f = reinterpret_cast(GetSymbol(jack_handle, #f)) - LOAD_SYM(jack_error_callback); -#undef LOAD_SYM - - if(error) - { - WARN("Missing expected functions:%s\n", missing_funcs.c_str()); - CloseLib(jack_handle); - jack_handle = nullptr; - } - } -#endif - - return !error; -} - - -struct DeviceEntry { - std::string mName; - std::string mPattern; -}; - -al::vector PlaybackList; - - -void EnumerateDevices(al::vector &list) -{ - al::vector{}.swap(list); - - list.emplace_back(DeviceEntry{jackDevice, ""}); - - std::string customList{ConfigValueStr(nullptr, "jack", "custom-devices").value_or("")}; - size_t strpos{0}; - while(strpos < customList.size()) - { - size_t nextpos{customList.find(';', strpos)}; - size_t seppos{customList.find('=', strpos)}; - if(seppos >= nextpos || seppos == strpos) - { - const std::string entry{customList.substr(strpos, nextpos-strpos)}; - ERR("Invalid device entry: \"%s\"\n", entry.c_str()); - if(nextpos != std::string::npos) ++nextpos; - strpos = nextpos; - continue; - } - - size_t count{1}; - std::string name{customList.substr(strpos, seppos-strpos)}; - auto check_name = [&name](const DeviceEntry &entry) -> bool - { return entry.mName == name; }; - while(std::find_if(list.cbegin(), list.cend(), check_name) != list.cend()) - { - name = customList.substr(strpos, seppos-strpos); - name += " #"; - name += std::to_string(++count); - } - - ++seppos; - list.emplace_back(DeviceEntry{std::move(name), customList.substr(seppos, nextpos-seppos)}); - const auto &entry = list.back(); - TRACE("Got custom device: %s = %s\n", entry.mName.c_str(), entry.mPattern.c_str()); - - if(nextpos != std::string::npos) ++nextpos; - strpos = nextpos; - } -} - - -struct JackPlayback final : public BackendBase { - JackPlayback(ALCdevice *device) noexcept : BackendBase{device} { } - ~JackPlayback() override; - - int process(jack_nframes_t numframes) noexcept; - static int processC(jack_nframes_t numframes, void *arg) noexcept - { return static_cast(arg)->process(numframes); } - - int mixerProc(); - - void open(const char *name) override; - bool reset() override; - void start() override; - void stop() override; - ClockLatency getClockLatency() override; - - std::string mPortPattern; - - jack_client_t *mClient{nullptr}; - std::array mPort{}; - - std::mutex mMutex; - - std::atomic mPlaying{false}; - RingBufferPtr mRing; - al::semaphore mSem; - - std::atomic mKillNow{true}; - std::thread mThread; - - DEF_NEWDEL(JackPlayback) -}; - -JackPlayback::~JackPlayback() -{ - if(!mClient) - return; - - std::for_each(mPort.begin(), mPort.end(), - [this](jack_port_t *port) -> void - { if(port) jack_port_unregister(mClient, port); } - ); - mPort.fill(nullptr); - jack_client_close(mClient); - mClient = nullptr; -} - - -int JackPlayback::process(jack_nframes_t numframes) noexcept -{ - std::array out; - size_t numchans{0}; - for(auto port : mPort) - { - if(!port) break; - out[numchans++] = static_cast(jack_port_get_buffer(port, numframes)); - } - - jack_nframes_t total{0}; - if LIKELY(mPlaying.load(std::memory_order_acquire)) - { - auto data = mRing->getReadVector(); - jack_nframes_t todo{minu(numframes, static_cast(data.first.len))}; - auto write_first = [&data,numchans,todo](float *outbuf) -> float* - { - const float *RESTRICT in = reinterpret_cast(data.first.buf); - auto deinterlace_input = [&in,numchans]() noexcept -> float - { - float ret{*in}; - in += numchans; - return ret; - }; - std::generate_n(outbuf, todo, deinterlace_input); - data.first.buf += sizeof(float); - return outbuf + todo; - }; - std::transform(out.begin(), out.begin()+numchans, out.begin(), write_first); - total += todo; - - todo = minu(numframes-total, static_cast(data.second.len)); - if(todo > 0) - { - auto write_second = [&data,numchans,todo](float *outbuf) -> float* - { - const float *RESTRICT in = reinterpret_cast(data.second.buf); - auto deinterlace_input = [&in,numchans]() noexcept -> float - { - float ret{*in}; - in += numchans; - return ret; - }; - std::generate_n(outbuf, todo, deinterlace_input); - data.second.buf += sizeof(float); - return outbuf + todo; - }; - std::transform(out.begin(), out.begin()+numchans, out.begin(), write_second); - total += todo; - } - - mRing->readAdvance(total); - mSem.post(); - } - - if(numframes > total) - { - const jack_nframes_t todo{numframes - total}; - auto clear_buf = [todo](float *outbuf) -> void { std::fill_n(outbuf, todo, 0.0f); }; - std::for_each(out.begin(), out.begin()+numchans, clear_buf); - } - - return 0; -} - -int JackPlayback::mixerProc() -{ - SetRTPriority(); - althrd_setname(MIXER_THREAD_NAME); - - const size_t frame_step{mDevice->channelsFromFmt()}; - - while(!mKillNow.load(std::memory_order_acquire) - && mDevice->Connected.load(std::memory_order_acquire)) - { - if(mRing->writeSpace() < mDevice->UpdateSize) - { - mSem.wait(); - continue; - } - - auto data = mRing->getWriteVector(); - size_t todo{data.first.len + data.second.len}; - todo -= todo%mDevice->UpdateSize; - - const auto len1 = static_cast(minz(data.first.len, todo)); - const auto len2 = static_cast(minz(data.second.len, todo-len1)); - - std::lock_guard _{mMutex}; - mDevice->renderSamples(data.first.buf, len1, frame_step); - if(len2 > 0) - mDevice->renderSamples(data.second.buf, len2, frame_step); - mRing->writeAdvance(todo); - } - - return 0; -} - - -void JackPlayback::open(const char *name) -{ - mPortPattern.clear(); - - if(!name) - name = jackDevice; - else if(strcmp(name, jackDevice) != 0) - { - if(PlaybackList.empty()) - EnumerateDevices(PlaybackList); - - auto check_name = [name](const DeviceEntry &entry) -> bool - { return entry.mName == name; }; - auto iter = std::find_if(PlaybackList.cbegin(), PlaybackList.cend(), check_name); - if(iter == PlaybackList.cend()) - throw al::backend_exception{al::backend_error::NoDevice, - "Device name \"%s\" not found", name}; - mPortPattern = iter->mPattern; - } - - const char *client_name{"alsoft"}; - jack_status_t status; - mClient = jack_client_open(client_name, ClientOptions, &status, nullptr); - if(mClient == nullptr) - throw al::backend_exception{al::backend_error::DeviceError, - "Failed to open client connection: 0x%02x", status}; - - if((status&JackServerStarted)) - TRACE("JACK server started\n"); - if((status&JackNameNotUnique)) - { - client_name = jack_get_client_name(mClient); - TRACE("Client name not unique, got '%s' instead\n", client_name); - } - - jack_set_process_callback(mClient, &JackPlayback::processC, this); - - mDevice->DeviceName = name; -} - -bool JackPlayback::reset() -{ - std::for_each(mPort.begin(), mPort.end(), - [this](jack_port_t *port) -> void - { if(port) jack_port_unregister(mClient, port); }); - mPort.fill(nullptr); - - /* Ignore the requested buffer metrics and just keep one JACK-sized buffer - * ready for when requested. - */ - mDevice->Frequency = jack_get_sample_rate(mClient); - mDevice->UpdateSize = jack_get_buffer_size(mClient); - mDevice->BufferSize = mDevice->UpdateSize * 2; - - const char *devname{mDevice->DeviceName.c_str()}; - uint bufsize{ConfigValueUInt(devname, "jack", "buffer-size").value_or(mDevice->UpdateSize)}; - bufsize = maxu(NextPowerOf2(bufsize), mDevice->UpdateSize); - mDevice->BufferSize = bufsize + mDevice->UpdateSize; - - /* Force 32-bit float output. */ - mDevice->FmtType = DevFmtFloat; - - auto ports_end = mPort.begin() + mDevice->channelsFromFmt(); - auto bad_port = std::find_if_not(mPort.begin(), ports_end, - [this](jack_port_t *&port) -> bool - { - std::string name{"channel_" + std::to_string(&port - &mPort[0] + 1)}; - port = jack_port_register(mClient, name.c_str(), JACK_DEFAULT_AUDIO_TYPE, - JackPortIsOutput, 0); - return port != nullptr; - }); - if(bad_port != ports_end) - { - ERR("Not enough JACK ports available for %s output\n", DevFmtChannelsString(mDevice->FmtChans)); - if(bad_port == mPort.begin()) return false; - - if(bad_port == mPort.begin()+1) - mDevice->FmtChans = DevFmtMono; - else - { - ports_end = mPort.begin()+2; - while(bad_port != ports_end) - { - jack_port_unregister(mClient, *(--bad_port)); - *bad_port = nullptr; - } - mDevice->FmtChans = DevFmtStereo; - } - } - - setDefaultChannelOrder(); - - return true; -} - -void JackPlayback::start() -{ - if(jack_activate(mClient)) - throw al::backend_exception{al::backend_error::DeviceError, "Failed to activate client"}; - - const char *devname{mDevice->DeviceName.c_str()}; - if(ConfigValueBool(devname, "jack", "connect-ports").value_or(true)) - { - const char **ports{jack_get_ports(mClient, mPortPattern.c_str(), nullptr, - JackPortIsPhysical|JackPortIsInput)}; - if(ports == nullptr) - { - jack_deactivate(mClient); - throw al::backend_exception{al::backend_error::DeviceError, - "No physical playback ports found"}; - } - auto connect_port = [this](const jack_port_t *port, const char *pname) -> bool - { - if(!port) return false; - if(!pname) - { - ERR("No physical playback port for \"%s\"\n", jack_port_name(port)); - return false; - } - if(jack_connect(mClient, jack_port_name(port), pname)) - ERR("Failed to connect output port \"%s\" to \"%s\"\n", jack_port_name(port), - pname); - return true; - }; - std::mismatch(mPort.begin(), mPort.end(), ports, connect_port); - jack_free(ports); - } - - /* Reconfigure buffer metrics in case the server changed it since the reset - * (it won't change again after jack_activate), then allocate the ring - * buffer with the appropriate size. - */ - mDevice->Frequency = jack_get_sample_rate(mClient); - mDevice->UpdateSize = jack_get_buffer_size(mClient); - mDevice->BufferSize = mDevice->UpdateSize * 2; - - uint bufsize{ConfigValueUInt(devname, "jack", "buffer-size").value_or(mDevice->UpdateSize)}; - bufsize = maxu(NextPowerOf2(bufsize), mDevice->UpdateSize); - mDevice->BufferSize = bufsize + mDevice->UpdateSize; - - mRing = nullptr; - mRing = RingBuffer::Create(bufsize, mDevice->frameSizeFromFmt(), true); - - try { - mPlaying.store(true, std::memory_order_release); - mKillNow.store(false, std::memory_order_release); - mThread = std::thread{std::mem_fn(&JackPlayback::mixerProc), this}; - } - catch(std::exception& e) { - jack_deactivate(mClient); - mPlaying.store(false, std::memory_order_release); - throw al::backend_exception{al::backend_error::DeviceError, - "Failed to start mixing thread: %s", e.what()}; - } -} - -void JackPlayback::stop() -{ - if(mKillNow.exchange(true, std::memory_order_acq_rel) || !mThread.joinable()) - return; - - mSem.post(); - mThread.join(); - - jack_deactivate(mClient); - mPlaying.store(false, std::memory_order_release); -} - - -ClockLatency JackPlayback::getClockLatency() -{ - ClockLatency ret; - - std::lock_guard _{mMutex}; - ret.ClockTime = GetDeviceClockTime(mDevice); - ret.Latency = std::chrono::seconds{mRing->readSpace()}; - ret.Latency /= mDevice->Frequency; - - return ret; -} - - -void jack_msg_handler(const char *message) -{ - WARN("%s\n", message); -} - -} // namespace - -bool JackBackendFactory::init() -{ - if(!jack_load()) - return false; - - if(!GetConfigValueBool(nullptr, "jack", "spawn-server", 0)) - ClientOptions = static_cast(ClientOptions | JackNoStartServer); - - void (*old_error_cb)(const char*){&jack_error_callback ? jack_error_callback : nullptr}; - jack_set_error_function(jack_msg_handler); - jack_status_t status; - jack_client_t *client{jack_client_open("alsoft", ClientOptions, &status, nullptr)}; - jack_set_error_function(old_error_cb); - if(!client) - { - WARN("jack_client_open() failed, 0x%02x\n", status); - if((status&JackServerFailed) && !(ClientOptions&JackNoStartServer)) - ERR("Unable to connect to JACK server\n"); - return false; - } - - jack_client_close(client); - return true; -} - -bool JackBackendFactory::querySupport(BackendType type) -{ return (type == BackendType::Playback); } - -std::string JackBackendFactory::probe(BackendType type) -{ - std::string outnames; - auto append_name = [&outnames](const DeviceEntry &entry) -> void - { - /* Includes null char. */ - outnames.append(entry.mName.c_str(), entry.mName.length()+1); - }; - switch(type) - { - case BackendType::Playback: - EnumerateDevices(PlaybackList); - std::for_each(PlaybackList.cbegin(), PlaybackList.cend(), append_name); - break; - case BackendType::Capture: - break; - } - return outnames; -} - -BackendPtr JackBackendFactory::createBackend(ALCdevice *device, BackendType type) -{ - if(type == BackendType::Playback) - return BackendPtr{new JackPlayback{device}}; - return nullptr; -} - -BackendFactory &JackBackendFactory::getFactory() -{ - static JackBackendFactory factory{}; - return factory; -} diff --git a/alc/backends/jack.h b/alc/backends/jack.h deleted file mode 100644 index f966c8f0..00000000 --- a/alc/backends/jack.h +++ /dev/null @@ -1,19 +0,0 @@ -#ifndef BACKENDS_JACK_H -#define BACKENDS_JACK_H - -#include "backends/base.h" - -struct JackBackendFactory final : public BackendFactory { -public: - bool init() override; - - bool querySupport(BackendType type) override; - - std::string probe(BackendType type) override; - - BackendPtr createBackend(ALCdevice *device, BackendType type) override; - - static BackendFactory &getFactory(); -}; - -#endif /* BACKENDS_JACK_H */ diff --git a/alc/backends/loopback.cpp b/alc/backends/loopback.cpp deleted file mode 100644 index 7f421ea7..00000000 --- a/alc/backends/loopback.cpp +++ /dev/null @@ -1,79 +0,0 @@ -/** - * OpenAL cross platform audio library - * Copyright (C) 2011 by Chris Robinson - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - * Or go to http://www.gnu.org/copyleft/lgpl.html - */ - -#include "config.h" - -#include "backends/loopback.h" - -#include "alcmain.h" -#include "alu.h" - - -namespace { - -struct LoopbackBackend final : public BackendBase { - LoopbackBackend(ALCdevice *device) noexcept : BackendBase{device} { } - - void open(const ALCchar *name) override; - bool reset() override; - void start() override; - void stop() override; - - DEF_NEWDEL(LoopbackBackend) -}; - - -void LoopbackBackend::open(const ALCchar *name) -{ - mDevice->DeviceName = name; -} - -bool LoopbackBackend::reset() -{ - setDefaultWFXChannelOrder(); - return true; -} - -void LoopbackBackend::start() -{ } - -void LoopbackBackend::stop() -{ } - -} // namespace - - -bool LoopbackBackendFactory::init() -{ return true; } - -bool LoopbackBackendFactory::querySupport(BackendType) -{ return true; } - -std::string LoopbackBackendFactory::probe(BackendType) -{ return std::string{}; } - -BackendPtr LoopbackBackendFactory::createBackend(ALCdevice *device, BackendType) -{ return BackendPtr{new LoopbackBackend{device}}; } - -BackendFactory &LoopbackBackendFactory::getFactory() -{ - static LoopbackBackendFactory factory{}; - return factory; -} diff --git a/alc/backends/loopback.h b/alc/backends/loopback.h deleted file mode 100644 index d000e033..00000000 --- a/alc/backends/loopback.h +++ /dev/null @@ -1,19 +0,0 @@ -#ifndef BACKENDS_LOOPBACK_H -#define BACKENDS_LOOPBACK_H - -#include "backends/base.h" - -struct LoopbackBackendFactory final : public BackendFactory { -public: - bool init() override; - - bool querySupport(BackendType type) override; - - std::string probe(BackendType type) override; - - BackendPtr createBackend(ALCdevice *device, BackendType type) override; - - static BackendFactory &getFactory(); -}; - -#endif /* BACKENDS_LOOPBACK_H */ diff --git a/alc/backends/null.cpp b/alc/backends/null.cpp deleted file mode 100644 index 15a36ddd..00000000 --- a/alc/backends/null.cpp +++ /dev/null @@ -1,179 +0,0 @@ -/** - * OpenAL cross platform audio library - * Copyright (C) 2010 by Chris Robinson - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - * Or go to http://www.gnu.org/copyleft/lgpl.html - */ - -#include "config.h" - -#include "backends/null.h" - -#include -#include -#include -#include -#include -#include -#include - -#include "alcmain.h" -#include "almalloc.h" -#include "alu.h" -#include "threads.h" - - -namespace { - -using std::chrono::seconds; -using std::chrono::milliseconds; -using std::chrono::nanoseconds; - -constexpr char nullDevice[] = "No Output"; - - -struct NullBackend final : public BackendBase { - NullBackend(ALCdevice *device) noexcept : BackendBase{device} { } - - int mixerProc(); - - void open(const char *name) override; - bool reset() override; - void start() override; - void stop() override; - - std::atomic mKillNow{true}; - std::thread mThread; - - DEF_NEWDEL(NullBackend) -}; - -int NullBackend::mixerProc() -{ - const milliseconds restTime{mDevice->UpdateSize*1000/mDevice->Frequency / 2}; - - SetRTPriority(); - althrd_setname(MIXER_THREAD_NAME); - - int64_t done{0}; - auto start = std::chrono::steady_clock::now(); - while(!mKillNow.load(std::memory_order_acquire) - && mDevice->Connected.load(std::memory_order_acquire)) - { - auto now = std::chrono::steady_clock::now(); - - /* This converts from nanoseconds to nanosamples, then to samples. */ - int64_t avail{std::chrono::duration_cast((now-start) * mDevice->Frequency).count()}; - if(avail-done < mDevice->UpdateSize) - { - std::this_thread::sleep_for(restTime); - continue; - } - while(avail-done >= mDevice->UpdateSize) - { - mDevice->renderSamples(nullptr, mDevice->UpdateSize, 0u); - done += mDevice->UpdateSize; - } - - /* For every completed second, increment the start time and reduce the - * samples done. This prevents the difference between the start time - * and current time from growing too large, while maintaining the - * correct number of samples to render. - */ - if(done >= mDevice->Frequency) - { - seconds s{done/mDevice->Frequency}; - start += s; - done -= mDevice->Frequency*s.count(); - } - } - - return 0; -} - - -void NullBackend::open(const char *name) -{ - if(!name) - name = nullDevice; - else if(strcmp(name, nullDevice) != 0) - throw al::backend_exception{al::backend_error::NoDevice, "Device name \"%s\" not found", - name}; - - mDevice->DeviceName = name; -} - -bool NullBackend::reset() -{ - setDefaultWFXChannelOrder(); - return true; -} - -void NullBackend::start() -{ - try { - mKillNow.store(false, std::memory_order_release); - mThread = std::thread{std::mem_fn(&NullBackend::mixerProc), this}; - } - catch(std::exception& e) { - throw al::backend_exception{al::backend_error::DeviceError, - "Failed to start mixing thread: %s", e.what()}; - } -} - -void NullBackend::stop() -{ - if(mKillNow.exchange(true, std::memory_order_acq_rel) || !mThread.joinable()) - return; - mThread.join(); -} - -} // namespace - - -bool NullBackendFactory::init() -{ return true; } - -bool NullBackendFactory::querySupport(BackendType type) -{ return (type == BackendType::Playback); } - -std::string NullBackendFactory::probe(BackendType type) -{ - std::string outnames; - switch(type) - { - case BackendType::Playback: - /* Includes null char. */ - outnames.append(nullDevice, sizeof(nullDevice)); - break; - case BackendType::Capture: - break; - } - return outnames; -} - -BackendPtr NullBackendFactory::createBackend(ALCdevice *device, BackendType type) -{ - if(type == BackendType::Playback) - return BackendPtr{new NullBackend{device}}; - return nullptr; -} - -BackendFactory &NullBackendFactory::getFactory() -{ - static NullBackendFactory factory{}; - return factory; -} diff --git a/alc/backends/null.h b/alc/backends/null.h deleted file mode 100644 index 8e9c59e5..00000000 --- a/alc/backends/null.h +++ /dev/null @@ -1,19 +0,0 @@ -#ifndef BACKENDS_NULL_H -#define BACKENDS_NULL_H - -#include "backends/base.h" - -struct NullBackendFactory final : public BackendFactory { -public: - bool init() override; - - bool querySupport(BackendType type) override; - - std::string probe(BackendType type) override; - - BackendPtr createBackend(ALCdevice *device, BackendType type) override; - - static BackendFactory &getFactory(); -}; - -#endif /* BACKENDS_NULL_H */ diff --git a/alc/backends/oboe.cpp b/alc/backends/oboe.cpp deleted file mode 100644 index 5b0d121d..00000000 --- a/alc/backends/oboe.cpp +++ /dev/null @@ -1,250 +0,0 @@ - -#include "config.h" - -#include "oboe.h" - -#include -#include - -#include "alu.h" -#include "core/logging.h" - -#include "oboe/Oboe.h" - - -namespace { - -constexpr char device_name[] = "Oboe Default"; - - -struct OboePlayback final : public BackendBase, public oboe::AudioStreamCallback { - OboePlayback(ALCdevice *device) : BackendBase{device} { } - - oboe::ManagedStream mStream; - - oboe::DataCallbackResult onAudioReady(oboe::AudioStream *oboeStream, void *audioData, - int32_t numFrames) override; - - void open(const char *name) override; - bool reset() override; - void start() override; - void stop() override; -}; - - -oboe::DataCallbackResult OboePlayback::onAudioReady(oboe::AudioStream *oboeStream, void *audioData, - int32_t numFrames) -{ - assert(numFrames > 0); - const int32_t numChannels{oboeStream->getChannelCount()}; - - if UNLIKELY(numChannels > 2 && mDevice->FmtChans == DevFmtStereo) - { - /* If the device is only mixing stereo but there's more than two - * output channels, there are unused channels that need to be silenced. - */ - if(mStream->getFormat() == oboe::AudioFormat::Float) - memset(audioData, 0, static_cast(numFrames*numChannels)*sizeof(float)); - else - memset(audioData, 0, static_cast(numFrames*numChannels)*sizeof(int16_t)); - } - - mDevice->renderSamples(audioData, static_cast(numFrames), - static_cast(numChannels)); - return oboe::DataCallbackResult::Continue; -} - - -void OboePlayback::open(const char *name) -{ - if(!name) - name = device_name; - else if(std::strcmp(name, device_name) != 0) - throw al::backend_exception{al::backend_error::NoDevice, "Device name \"%s\" not found", - name}; - - /* Open a basic output stream, just to ensure it can work. */ - oboe::Result result{oboe::AudioStreamBuilder{}.setDirection(oboe::Direction::Output) - ->setPerformanceMode(oboe::PerformanceMode::LowLatency) - ->openManagedStream(mStream)}; - if(result != oboe::Result::OK) - throw al::backend_exception{al::backend_error::DeviceError, "Failed to create stream: %s", - oboe::convertToText(result)}; - - mDevice->DeviceName = name; -} - -bool OboePlayback::reset() -{ - oboe::AudioStreamBuilder builder; - builder.setDirection(oboe::Direction::Output); - builder.setPerformanceMode(oboe::PerformanceMode::LowLatency); - /* Don't let Oboe convert. We should be able to handle anything it gives - * back. - */ - builder.setSampleRateConversionQuality(oboe::SampleRateConversionQuality::None); - builder.setChannelConversionAllowed(false); - builder.setFormatConversionAllowed(false); - builder.setCallback(this); - - if(mDevice->Flags.test(FrequencyRequest)) - builder.setSampleRate(static_cast(mDevice->Frequency)); - if(mDevice->Flags.test(ChannelsRequest)) - { - /* Only use mono or stereo at user request. There's no telling what - * other counts may be inferred as. - */ - builder.setChannelCount((mDevice->FmtChans==DevFmtMono) ? oboe::ChannelCount::Mono - : (mDevice->FmtChans==DevFmtStereo) ? oboe::ChannelCount::Stereo - : oboe::ChannelCount::Unspecified); - } - if(mDevice->Flags.test(SampleTypeRequest)) - { - oboe::AudioFormat format{oboe::AudioFormat::Unspecified}; - switch(mDevice->FmtType) - { - case DevFmtByte: - case DevFmtUByte: - case DevFmtShort: - case DevFmtUShort: - format = oboe::AudioFormat::I16; - break; - case DevFmtInt: - case DevFmtUInt: - case DevFmtFloat: - format = oboe::AudioFormat::Float; - break; - } - builder.setFormat(format); - } - - oboe::Result result{builder.openManagedStream(mStream)}; - /* If the format failed, try asking for the defaults. */ - while(result == oboe::Result::ErrorInvalidFormat) - { - if(builder.getFormat() != oboe::AudioFormat::Unspecified) - builder.setFormat(oboe::AudioFormat::Unspecified); - else if(builder.getSampleRate() != oboe::kUnspecified) - builder.setSampleRate(oboe::kUnspecified); - else if(builder.getChannelCount() != oboe::ChannelCount::Unspecified) - builder.setChannelCount(oboe::ChannelCount::Unspecified); - else - break; - result = builder.openManagedStream(mStream); - } - if(result != oboe::Result::OK) - throw al::backend_exception{al::backend_error::DeviceError, "Failed to create stream: %s", - oboe::convertToText(result)}; - TRACE("Got stream with properties:\n%s", oboe::convertToText(mStream.get())); - - switch(mStream->getChannelCount()) - { - case oboe::ChannelCount::Mono: - mDevice->FmtChans = DevFmtMono; - break; - case oboe::ChannelCount::Stereo: - mDevice->FmtChans = DevFmtStereo; - break; - /* Other potential configurations. Could be wrong, but better than failing. - * Assume WFX channel order. - */ - case 4: - mDevice->FmtChans = DevFmtQuad; - break; - case 6: - mDevice->FmtChans = DevFmtX51Rear; - break; - case 7: - mDevice->FmtChans = DevFmtX61; - break; - case 8: - mDevice->FmtChans = DevFmtX71; - break; - default: - if(mStream->getChannelCount() < 1) - throw al::backend_exception{al::backend_error::DeviceError, - "Got unhandled channel count: %d", mStream->getChannelCount()}; - /* Assume first two channels are front left/right. We can do a stereo - * mix and keep the other channels silent. - */ - mDevice->FmtChans = DevFmtStereo; - break; - } - setDefaultWFXChannelOrder(); - - switch(mStream->getFormat()) - { - case oboe::AudioFormat::I16: - mDevice->FmtType = DevFmtShort; - break; - case oboe::AudioFormat::Float: - mDevice->FmtType = DevFmtFloat; - break; - case oboe::AudioFormat::Unspecified: - case oboe::AudioFormat::Invalid: - throw al::backend_exception{al::backend_error::DeviceError, - "Got unhandled sample type: %s", oboe::convertToText(mStream->getFormat())}; - } - mDevice->Frequency = static_cast(mStream->getSampleRate()); - - /* Ensure the period size is no less than 10ms. It's possible for FramesPerCallback to be 0 - * indicating variable updates, but OpenAL should have a reasonable minimum update size set. - * FramesPerBurst may not necessarily be correct, but hopefully it can act as a minimum - * update size. - */ - mDevice->UpdateSize = maxu(mDevice->Frequency / 100, - static_cast(mStream->getFramesPerBurst())); - mDevice->BufferSize = maxu(mDevice->UpdateSize * 2, - static_cast(mStream->getBufferSizeInFrames())); - - return true; -} - -void OboePlayback::start() -{ - const oboe::Result result{mStream->start()}; - if(result != oboe::Result::OK) - throw al::backend_exception{al::backend_error::DeviceError, "Failed to start stream: %s", - oboe::convertToText(result)}; -} - -void OboePlayback::stop() -{ - oboe::Result result{mStream->stop()}; - if(result != oboe::Result::OK) - throw al::backend_exception{al::backend_error::DeviceError, "Failed to stop stream: %s", - oboe::convertToText(result)}; -} - -} // namespace - -bool OboeBackendFactory::init() { return true; } - -bool OboeBackendFactory::querySupport(BackendType type) -{ return type == BackendType::Playback; } - -std::string OboeBackendFactory::probe(BackendType type) -{ - switch(type) - { - case BackendType::Playback: - /* Includes null char. */ - return std::string{device_name, sizeof(device_name)}; - case BackendType::Capture: - break; - } - return std::string{}; -} - -BackendPtr OboeBackendFactory::createBackend(ALCdevice *device, BackendType type) -{ - if(type == BackendType::Playback) - return BackendPtr{new OboePlayback{device}}; - return nullptr; -} - -BackendFactory &OboeBackendFactory::getFactory() -{ - static OboeBackendFactory factory{}; - return factory; -} diff --git a/alc/backends/oboe.h b/alc/backends/oboe.h deleted file mode 100644 index 93b98e37..00000000 --- a/alc/backends/oboe.h +++ /dev/null @@ -1,19 +0,0 @@ -#ifndef BACKENDS_OBOE_H -#define BACKENDS_OBOE_H - -#include "backends/base.h" - -struct OboeBackendFactory final : public BackendFactory { -public: - bool init() override; - - bool querySupport(BackendType type) override; - - std::string probe(BackendType type) override; - - BackendPtr createBackend(ALCdevice *device, BackendType type) override; - - static BackendFactory &getFactory(); -}; - -#endif /* BACKENDS_OBOE_H */ diff --git a/alc/backends/opensl.cpp b/alc/backends/opensl.cpp deleted file mode 100644 index 926911f0..00000000 --- a/alc/backends/opensl.cpp +++ /dev/null @@ -1,974 +0,0 @@ -/* - * Copyright (C) 2011 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* This is an OpenAL backend for Android using the native audio APIs based on - * OpenSL ES 1.0.1. It is based on source code for the native-audio sample app - * bundled with NDK. - */ - -#include "config.h" - -#include "backends/opensl.h" - -#include -#include - -#include -#include -#include -#include -#include - -#include "albit.h" -#include "alcmain.h" -#include "alu.h" -#include "compat.h" -#include "core/logging.h" -#include "ringbuffer.h" -#include "threads.h" - -#include -#include -#include - - -namespace { - -/* Helper macros */ -#define EXTRACT_VCALL_ARGS(...) __VA_ARGS__)) -#define VCALL(obj, func) ((*(obj))->func((obj), EXTRACT_VCALL_ARGS -#define VCALL0(obj, func) ((*(obj))->func((obj) EXTRACT_VCALL_ARGS - - -constexpr char opensl_device[] = "OpenSL"; - - -constexpr SLuint32 GetChannelMask(DevFmtChannels chans) noexcept -{ - switch(chans) - { - case DevFmtMono: return SL_SPEAKER_FRONT_CENTER; - case DevFmtStereo: return SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT; - case DevFmtQuad: return SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT | - SL_SPEAKER_BACK_LEFT | SL_SPEAKER_BACK_RIGHT; - case DevFmtX51: return SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT | - SL_SPEAKER_FRONT_CENTER | SL_SPEAKER_LOW_FREQUENCY | SL_SPEAKER_SIDE_LEFT | - SL_SPEAKER_SIDE_RIGHT; - case DevFmtX51Rear: return SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT | - SL_SPEAKER_FRONT_CENTER | SL_SPEAKER_LOW_FREQUENCY | SL_SPEAKER_BACK_LEFT | - SL_SPEAKER_BACK_RIGHT; - case DevFmtX61: return SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT | - SL_SPEAKER_FRONT_CENTER | SL_SPEAKER_LOW_FREQUENCY | SL_SPEAKER_BACK_CENTER | - SL_SPEAKER_SIDE_LEFT | SL_SPEAKER_SIDE_RIGHT; - case DevFmtX71: return SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT | - SL_SPEAKER_FRONT_CENTER | SL_SPEAKER_LOW_FREQUENCY | SL_SPEAKER_BACK_LEFT | - SL_SPEAKER_BACK_RIGHT | SL_SPEAKER_SIDE_LEFT | SL_SPEAKER_SIDE_RIGHT; - case DevFmtAmbi3D: - break; - } - return 0; -} - -#ifdef SL_ANDROID_DATAFORMAT_PCM_EX -constexpr SLuint32 GetTypeRepresentation(DevFmtType type) noexcept -{ - switch(type) - { - case DevFmtUByte: - case DevFmtUShort: - case DevFmtUInt: - return SL_ANDROID_PCM_REPRESENTATION_UNSIGNED_INT; - case DevFmtByte: - case DevFmtShort: - case DevFmtInt: - return SL_ANDROID_PCM_REPRESENTATION_SIGNED_INT; - case DevFmtFloat: - return SL_ANDROID_PCM_REPRESENTATION_FLOAT; - } - return 0; -} -#endif - -constexpr SLuint32 GetByteOrderEndianness() noexcept -{ - if /*constexpr*/(al::endian::native == al::endian::little) - return SL_BYTEORDER_LITTLEENDIAN; - return SL_BYTEORDER_BIGENDIAN; -} - -const char *res_str(SLresult result) noexcept -{ - switch(result) - { - case SL_RESULT_SUCCESS: return "Success"; - case SL_RESULT_PRECONDITIONS_VIOLATED: return "Preconditions violated"; - case SL_RESULT_PARAMETER_INVALID: return "Parameter invalid"; - case SL_RESULT_MEMORY_FAILURE: return "Memory failure"; - case SL_RESULT_RESOURCE_ERROR: return "Resource error"; - case SL_RESULT_RESOURCE_LOST: return "Resource lost"; - case SL_RESULT_IO_ERROR: return "I/O error"; - case SL_RESULT_BUFFER_INSUFFICIENT: return "Buffer insufficient"; - case SL_RESULT_CONTENT_CORRUPTED: return "Content corrupted"; - case SL_RESULT_CONTENT_UNSUPPORTED: return "Content unsupported"; - case SL_RESULT_CONTENT_NOT_FOUND: return "Content not found"; - case SL_RESULT_PERMISSION_DENIED: return "Permission denied"; - case SL_RESULT_FEATURE_UNSUPPORTED: return "Feature unsupported"; - case SL_RESULT_INTERNAL_ERROR: return "Internal error"; - case SL_RESULT_UNKNOWN_ERROR: return "Unknown error"; - case SL_RESULT_OPERATION_ABORTED: return "Operation aborted"; - case SL_RESULT_CONTROL_LOST: return "Control lost"; -#ifdef SL_RESULT_READONLY - case SL_RESULT_READONLY: return "ReadOnly"; -#endif -#ifdef SL_RESULT_ENGINEOPTION_UNSUPPORTED - case SL_RESULT_ENGINEOPTION_UNSUPPORTED: return "Engine option unsupported"; -#endif -#ifdef SL_RESULT_SOURCE_SINK_INCOMPATIBLE - case SL_RESULT_SOURCE_SINK_INCOMPATIBLE: return "Source/Sink incompatible"; -#endif - } - return "Unknown error code"; -} - -#define PRINTERR(x, s) do { \ - if UNLIKELY((x) != SL_RESULT_SUCCESS) \ - ERR("%s: %s\n", (s), res_str((x))); \ -} while(0) - - -struct OpenSLPlayback final : public BackendBase { - OpenSLPlayback(ALCdevice *device) noexcept : BackendBase{device} { } - ~OpenSLPlayback() override; - - void process(SLAndroidSimpleBufferQueueItf bq) noexcept; - static void processC(SLAndroidSimpleBufferQueueItf bq, void *context) noexcept - { static_cast(context)->process(bq); } - - int mixerProc(); - - void open(const char *name) override; - bool reset() override; - void start() override; - void stop() override; - ClockLatency getClockLatency() override; - - /* engine interfaces */ - SLObjectItf mEngineObj{nullptr}; - SLEngineItf mEngine{nullptr}; - - /* output mix interfaces */ - SLObjectItf mOutputMix{nullptr}; - - /* buffer queue player interfaces */ - SLObjectItf mBufferQueueObj{nullptr}; - - RingBufferPtr mRing{nullptr}; - al::semaphore mSem; - - std::mutex mMutex; - - uint mFrameSize{0}; - - std::atomic mKillNow{true}; - std::thread mThread; - - DEF_NEWDEL(OpenSLPlayback) -}; - -OpenSLPlayback::~OpenSLPlayback() -{ - if(mBufferQueueObj) - VCALL0(mBufferQueueObj,Destroy)(); - mBufferQueueObj = nullptr; - - if(mOutputMix) - VCALL0(mOutputMix,Destroy)(); - mOutputMix = nullptr; - - if(mEngineObj) - VCALL0(mEngineObj,Destroy)(); - mEngineObj = nullptr; - mEngine = nullptr; -} - - -/* this callback handler is called every time a buffer finishes playing */ -void OpenSLPlayback::process(SLAndroidSimpleBufferQueueItf) noexcept -{ - /* A note on the ringbuffer usage: The buffer queue seems to hold on to the - * pointer passed to the Enqueue method, rather than copying the audio. - * Consequently, the ringbuffer contains the audio that is currently queued - * and waiting to play. This process() callback is called when a buffer is - * finished, so we simply move the read pointer up to indicate the space is - * available for writing again, and wake up the mixer thread to mix and - * queue more audio. - */ - mRing->readAdvance(1); - - mSem.post(); -} - -int OpenSLPlayback::mixerProc() -{ - SetRTPriority(); - althrd_setname(MIXER_THREAD_NAME); - - SLPlayItf player; - SLAndroidSimpleBufferQueueItf bufferQueue; - SLresult result{VCALL(mBufferQueueObj,GetInterface)(SL_IID_ANDROIDSIMPLEBUFFERQUEUE, - &bufferQueue)}; - PRINTERR(result, "bufferQueue->GetInterface SL_IID_ANDROIDSIMPLEBUFFERQUEUE"); - if(SL_RESULT_SUCCESS == result) - { - result = VCALL(mBufferQueueObj,GetInterface)(SL_IID_PLAY, &player); - PRINTERR(result, "bufferQueue->GetInterface SL_IID_PLAY"); - } - - const size_t frame_step{mDevice->channelsFromFmt()}; - - if(SL_RESULT_SUCCESS != result) - mDevice->handleDisconnect("Failed to get playback buffer: 0x%08x", result); - - while(SL_RESULT_SUCCESS == result && !mKillNow.load(std::memory_order_acquire) - && mDevice->Connected.load(std::memory_order_acquire)) - { - if(mRing->writeSpace() == 0) - { - SLuint32 state{0}; - - result = VCALL(player,GetPlayState)(&state); - PRINTERR(result, "player->GetPlayState"); - if(SL_RESULT_SUCCESS == result && state != SL_PLAYSTATE_PLAYING) - { - result = VCALL(player,SetPlayState)(SL_PLAYSTATE_PLAYING); - PRINTERR(result, "player->SetPlayState"); - } - if(SL_RESULT_SUCCESS != result) - { - mDevice->handleDisconnect("Failed to start playback: 0x%08x", result); - break; - } - - if(mRing->writeSpace() == 0) - { - mSem.wait(); - continue; - } - } - - std::unique_lock dlock{mMutex}; - auto data = mRing->getWriteVector(); - mDevice->renderSamples(data.first.buf, - static_cast(data.first.len)*mDevice->UpdateSize, frame_step); - if(data.second.len > 0) - mDevice->renderSamples(data.second.buf, - static_cast(data.second.len)*mDevice->UpdateSize, frame_step); - - size_t todo{data.first.len + data.second.len}; - mRing->writeAdvance(todo); - dlock.unlock(); - - for(size_t i{0};i < todo;i++) - { - if(!data.first.len) - { - data.first = data.second; - data.second.buf = nullptr; - data.second.len = 0; - } - - result = VCALL(bufferQueue,Enqueue)(data.first.buf, mDevice->UpdateSize*mFrameSize); - PRINTERR(result, "bufferQueue->Enqueue"); - if(SL_RESULT_SUCCESS != result) - { - mDevice->handleDisconnect("Failed to queue audio: 0x%08x", result); - break; - } - - data.first.len--; - data.first.buf += mDevice->UpdateSize*mFrameSize; - } - } - - return 0; -} - - -void OpenSLPlayback::open(const char *name) -{ - if(!name) - name = opensl_device; - else if(strcmp(name, opensl_device) != 0) - throw al::backend_exception{al::backend_error::NoDevice, "Device name \"%s\" not found", - name}; - - // create engine - SLresult result{slCreateEngine(&mEngineObj, 0, nullptr, 0, nullptr, nullptr)}; - PRINTERR(result, "slCreateEngine"); - if(SL_RESULT_SUCCESS == result) - { - result = VCALL(mEngineObj,Realize)(SL_BOOLEAN_FALSE); - PRINTERR(result, "engine->Realize"); - } - if(SL_RESULT_SUCCESS == result) - { - result = VCALL(mEngineObj,GetInterface)(SL_IID_ENGINE, &mEngine); - PRINTERR(result, "engine->GetInterface"); - } - if(SL_RESULT_SUCCESS == result) - { - result = VCALL(mEngine,CreateOutputMix)(&mOutputMix, 0, nullptr, nullptr); - PRINTERR(result, "engine->CreateOutputMix"); - } - if(SL_RESULT_SUCCESS == result) - { - result = VCALL(mOutputMix,Realize)(SL_BOOLEAN_FALSE); - PRINTERR(result, "outputMix->Realize"); - } - - if(SL_RESULT_SUCCESS != result) - { - if(mOutputMix) - VCALL0(mOutputMix,Destroy)(); - mOutputMix = nullptr; - - if(mEngineObj) - VCALL0(mEngineObj,Destroy)(); - mEngineObj = nullptr; - mEngine = nullptr; - - throw al::backend_exception{al::backend_error::DeviceError, - "Failed to initialize OpenSL device: 0x%08x", result}; - } - - mDevice->DeviceName = name; -} - -bool OpenSLPlayback::reset() -{ - SLresult result; - - if(mBufferQueueObj) - VCALL0(mBufferQueueObj,Destroy)(); - mBufferQueueObj = nullptr; - - mRing = nullptr; - -#if 0 - if(!mDevice->Flags.get()) - { - /* FIXME: Disabled until I figure out how to get the Context needed for - * the getSystemService call. - */ - JNIEnv *env = Android_GetJNIEnv(); - jobject jctx = Android_GetContext(); - - /* Get necessary stuff for using java.lang.Integer, - * android.content.Context, and android.media.AudioManager. - */ - jclass int_cls = JCALL(env,FindClass)("java/lang/Integer"); - jmethodID int_parseint = JCALL(env,GetStaticMethodID)(int_cls, - "parseInt", "(Ljava/lang/String;)I" - ); - TRACE("Integer: %p, parseInt: %p\n", int_cls, int_parseint); - - jclass ctx_cls = JCALL(env,FindClass)("android/content/Context"); - jfieldID ctx_audsvc = JCALL(env,GetStaticFieldID)(ctx_cls, - "AUDIO_SERVICE", "Ljava/lang/String;" - ); - jmethodID ctx_getSysSvc = JCALL(env,GetMethodID)(ctx_cls, - "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;" - ); - TRACE("Context: %p, AUDIO_SERVICE: %p, getSystemService: %p\n", - ctx_cls, ctx_audsvc, ctx_getSysSvc); - - jclass audmgr_cls = JCALL(env,FindClass)("android/media/AudioManager"); - jfieldID audmgr_prop_out_srate = JCALL(env,GetStaticFieldID)(audmgr_cls, - "PROPERTY_OUTPUT_SAMPLE_RATE", "Ljava/lang/String;" - ); - jmethodID audmgr_getproperty = JCALL(env,GetMethodID)(audmgr_cls, - "getProperty", "(Ljava/lang/String;)Ljava/lang/String;" - ); - TRACE("AudioManager: %p, PROPERTY_OUTPUT_SAMPLE_RATE: %p, getProperty: %p\n", - audmgr_cls, audmgr_prop_out_srate, audmgr_getproperty); - - const char *strchars; - jstring strobj; - - /* Now make the calls. */ - //AudioManager audMgr = (AudioManager)getSystemService(Context.AUDIO_SERVICE); - strobj = JCALL(env,GetStaticObjectField)(ctx_cls, ctx_audsvc); - jobject audMgr = JCALL(env,CallObjectMethod)(jctx, ctx_getSysSvc, strobj); - strchars = JCALL(env,GetStringUTFChars)(strobj, nullptr); - TRACE("Context.getSystemService(%s) = %p\n", strchars, audMgr); - JCALL(env,ReleaseStringUTFChars)(strobj, strchars); - - //String srateStr = audMgr.getProperty(AudioManager.PROPERTY_OUTPUT_SAMPLE_RATE); - strobj = JCALL(env,GetStaticObjectField)(audmgr_cls, audmgr_prop_out_srate); - jstring srateStr = JCALL(env,CallObjectMethod)(audMgr, audmgr_getproperty, strobj); - strchars = JCALL(env,GetStringUTFChars)(strobj, nullptr); - TRACE("audMgr.getProperty(%s) = %p\n", strchars, srateStr); - JCALL(env,ReleaseStringUTFChars)(strobj, strchars); - - //int sampleRate = Integer.parseInt(srateStr); - sampleRate = JCALL(env,CallStaticIntMethod)(int_cls, int_parseint, srateStr); - - strchars = JCALL(env,GetStringUTFChars)(srateStr, nullptr); - TRACE("Got system sample rate %uhz (%s)\n", sampleRate, strchars); - JCALL(env,ReleaseStringUTFChars)(srateStr, strchars); - - if(!sampleRate) sampleRate = device->Frequency; - else sampleRate = maxu(sampleRate, MIN_OUTPUT_RATE); - } -#endif - - mDevice->FmtChans = DevFmtStereo; - mDevice->FmtType = DevFmtShort; - - setDefaultWFXChannelOrder(); - mFrameSize = mDevice->frameSizeFromFmt(); - - - const std::array ids{{ SL_IID_ANDROIDSIMPLEBUFFERQUEUE, SL_IID_ANDROIDCONFIGURATION }}; - const std::array reqs{{ SL_BOOLEAN_TRUE, SL_BOOLEAN_FALSE }}; - - SLDataLocator_OutputMix loc_outmix{}; - loc_outmix.locatorType = SL_DATALOCATOR_OUTPUTMIX; - loc_outmix.outputMix = mOutputMix; - - SLDataSink audioSnk{}; - audioSnk.pLocator = &loc_outmix; - audioSnk.pFormat = nullptr; - - SLDataLocator_AndroidSimpleBufferQueue loc_bufq{}; - loc_bufq.locatorType = SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE; - loc_bufq.numBuffers = mDevice->BufferSize / mDevice->UpdateSize; - - SLDataSource audioSrc{}; -#ifdef SL_ANDROID_DATAFORMAT_PCM_EX - SLAndroidDataFormat_PCM_EX format_pcm_ex{}; - format_pcm_ex.formatType = SL_ANDROID_DATAFORMAT_PCM_EX; - format_pcm_ex.numChannels = mDevice->channelsFromFmt(); - format_pcm_ex.sampleRate = mDevice->Frequency * 1000; - format_pcm_ex.bitsPerSample = mDevice->bytesFromFmt() * 8; - format_pcm_ex.containerSize = format_pcm_ex.bitsPerSample; - format_pcm_ex.channelMask = GetChannelMask(mDevice->FmtChans); - format_pcm_ex.endianness = GetByteOrderEndianness(); - format_pcm_ex.representation = GetTypeRepresentation(mDevice->FmtType); - - audioSrc.pLocator = &loc_bufq; - audioSrc.pFormat = &format_pcm_ex; - - result = VCALL(mEngine,CreateAudioPlayer)(&mBufferQueueObj, &audioSrc, &audioSnk, ids.size(), - ids.data(), reqs.data()); - if(SL_RESULT_SUCCESS != result) -#endif - { - /* Alter sample type according to what SLDataFormat_PCM can support. */ - switch(mDevice->FmtType) - { - case DevFmtByte: mDevice->FmtType = DevFmtUByte; break; - case DevFmtUInt: mDevice->FmtType = DevFmtInt; break; - case DevFmtFloat: - case DevFmtUShort: mDevice->FmtType = DevFmtShort; break; - case DevFmtUByte: - case DevFmtShort: - case DevFmtInt: - break; - } - - SLDataFormat_PCM format_pcm{}; - format_pcm.formatType = SL_DATAFORMAT_PCM; - format_pcm.numChannels = mDevice->channelsFromFmt(); - format_pcm.samplesPerSec = mDevice->Frequency * 1000; - format_pcm.bitsPerSample = mDevice->bytesFromFmt() * 8; - format_pcm.containerSize = format_pcm.bitsPerSample; - format_pcm.channelMask = GetChannelMask(mDevice->FmtChans); - format_pcm.endianness = GetByteOrderEndianness(); - - audioSrc.pLocator = &loc_bufq; - audioSrc.pFormat = &format_pcm; - - result = VCALL(mEngine,CreateAudioPlayer)(&mBufferQueueObj, &audioSrc, &audioSnk, ids.size(), - ids.data(), reqs.data()); - PRINTERR(result, "engine->CreateAudioPlayer"); - } - if(SL_RESULT_SUCCESS == result) - { - /* Set the stream type to "media" (games, music, etc), if possible. */ - SLAndroidConfigurationItf config; - result = VCALL(mBufferQueueObj,GetInterface)(SL_IID_ANDROIDCONFIGURATION, &config); - PRINTERR(result, "bufferQueue->GetInterface SL_IID_ANDROIDCONFIGURATION"); - if(SL_RESULT_SUCCESS == result) - { - SLint32 streamType = SL_ANDROID_STREAM_MEDIA; - result = VCALL(config,SetConfiguration)(SL_ANDROID_KEY_STREAM_TYPE, &streamType, - sizeof(streamType)); - PRINTERR(result, "config->SetConfiguration"); - } - - /* Clear any error since this was optional. */ - result = SL_RESULT_SUCCESS; - } - if(SL_RESULT_SUCCESS == result) - { - result = VCALL(mBufferQueueObj,Realize)(SL_BOOLEAN_FALSE); - PRINTERR(result, "bufferQueue->Realize"); - } - if(SL_RESULT_SUCCESS == result) - { - const uint num_updates{mDevice->BufferSize / mDevice->UpdateSize}; - mRing = RingBuffer::Create(num_updates, mFrameSize*mDevice->UpdateSize, true); - } - - if(SL_RESULT_SUCCESS != result) - { - if(mBufferQueueObj) - VCALL0(mBufferQueueObj,Destroy)(); - mBufferQueueObj = nullptr; - - return false; - } - - return true; -} - -void OpenSLPlayback::start() -{ - mRing->reset(); - - SLAndroidSimpleBufferQueueItf bufferQueue; - SLresult result{VCALL(mBufferQueueObj,GetInterface)(SL_IID_ANDROIDSIMPLEBUFFERQUEUE, - &bufferQueue)}; - PRINTERR(result, "bufferQueue->GetInterface"); - if(SL_RESULT_SUCCESS == result) - { - result = VCALL(bufferQueue,RegisterCallback)(&OpenSLPlayback::processC, this); - PRINTERR(result, "bufferQueue->RegisterCallback"); - } - if(SL_RESULT_SUCCESS != result) - throw al::backend_exception{al::backend_error::DeviceError, - "Failed to register callback: 0x%08x", result}; - - try { - mKillNow.store(false, std::memory_order_release); - mThread = std::thread(std::mem_fn(&OpenSLPlayback::mixerProc), this); - } - catch(std::exception& e) { - throw al::backend_exception{al::backend_error::DeviceError, - "Failed to start mixing thread: %s", e.what()}; - } -} - -void OpenSLPlayback::stop() -{ - if(mKillNow.exchange(true, std::memory_order_acq_rel) || !mThread.joinable()) - return; - - mSem.post(); - mThread.join(); - - SLPlayItf player; - SLresult result{VCALL(mBufferQueueObj,GetInterface)(SL_IID_PLAY, &player)}; - PRINTERR(result, "bufferQueue->GetInterface"); - if(SL_RESULT_SUCCESS == result) - { - result = VCALL(player,SetPlayState)(SL_PLAYSTATE_STOPPED); - PRINTERR(result, "player->SetPlayState"); - } - - SLAndroidSimpleBufferQueueItf bufferQueue; - result = VCALL(mBufferQueueObj,GetInterface)(SL_IID_ANDROIDSIMPLEBUFFERQUEUE, &bufferQueue); - PRINTERR(result, "bufferQueue->GetInterface"); - if(SL_RESULT_SUCCESS == result) - { - result = VCALL0(bufferQueue,Clear)(); - PRINTERR(result, "bufferQueue->Clear"); - } - if(SL_RESULT_SUCCESS == result) - { - result = VCALL(bufferQueue,RegisterCallback)(nullptr, nullptr); - PRINTERR(result, "bufferQueue->RegisterCallback"); - } - if(SL_RESULT_SUCCESS == result) - { - SLAndroidSimpleBufferQueueState state; - do { - std::this_thread::yield(); - result = VCALL(bufferQueue,GetState)(&state); - } while(SL_RESULT_SUCCESS == result && state.count > 0); - PRINTERR(result, "bufferQueue->GetState"); - } -} - -ClockLatency OpenSLPlayback::getClockLatency() -{ - ClockLatency ret; - - std::lock_guard _{mMutex}; - ret.ClockTime = GetDeviceClockTime(mDevice); - ret.Latency = std::chrono::seconds{mRing->readSpace() * mDevice->UpdateSize}; - ret.Latency /= mDevice->Frequency; - - return ret; -} - - -struct OpenSLCapture final : public BackendBase { - OpenSLCapture(ALCdevice *device) noexcept : BackendBase{device} { } - ~OpenSLCapture() override; - - void process(SLAndroidSimpleBufferQueueItf bq) noexcept; - static void processC(SLAndroidSimpleBufferQueueItf bq, void *context) noexcept - { static_cast(context)->process(bq); } - - void open(const char *name) override; - void start() override; - void stop() override; - void captureSamples(al::byte *buffer, uint samples) override; - uint availableSamples() override; - - /* engine interfaces */ - SLObjectItf mEngineObj{nullptr}; - SLEngineItf mEngine; - - /* recording interfaces */ - SLObjectItf mRecordObj{nullptr}; - - RingBufferPtr mRing{nullptr}; - uint mSplOffset{0u}; - - uint mFrameSize{0}; - - DEF_NEWDEL(OpenSLCapture) -}; - -OpenSLCapture::~OpenSLCapture() -{ - if(mRecordObj) - VCALL0(mRecordObj,Destroy)(); - mRecordObj = nullptr; - - if(mEngineObj) - VCALL0(mEngineObj,Destroy)(); - mEngineObj = nullptr; - mEngine = nullptr; -} - - -void OpenSLCapture::process(SLAndroidSimpleBufferQueueItf) noexcept -{ - /* A new chunk has been written into the ring buffer, advance it. */ - mRing->writeAdvance(1); -} - - -void OpenSLCapture::open(const char* name) -{ - if(!name) - name = opensl_device; - else if(strcmp(name, opensl_device) != 0) - throw al::backend_exception{al::backend_error::NoDevice, "Device name \"%s\" not found", - name}; - - SLresult result{slCreateEngine(&mEngineObj, 0, nullptr, 0, nullptr, nullptr)}; - PRINTERR(result, "slCreateEngine"); - if(SL_RESULT_SUCCESS == result) - { - result = VCALL(mEngineObj,Realize)(SL_BOOLEAN_FALSE); - PRINTERR(result, "engine->Realize"); - } - if(SL_RESULT_SUCCESS == result) - { - result = VCALL(mEngineObj,GetInterface)(SL_IID_ENGINE, &mEngine); - PRINTERR(result, "engine->GetInterface"); - } - if(SL_RESULT_SUCCESS == result) - { - mFrameSize = mDevice->frameSizeFromFmt(); - /* Ensure the total length is at least 100ms */ - uint length{maxu(mDevice->BufferSize, mDevice->Frequency/10)}; - /* Ensure the per-chunk length is at least 10ms, and no more than 50ms. */ - uint update_len{clampu(mDevice->BufferSize/3, mDevice->Frequency/100, - mDevice->Frequency/100*5)}; - uint num_updates{(length+update_len-1) / update_len}; - - mRing = RingBuffer::Create(num_updates, update_len*mFrameSize, false); - - mDevice->UpdateSize = update_len; - mDevice->BufferSize = static_cast(mRing->writeSpace() * update_len); - } - if(SL_RESULT_SUCCESS == result) - { - const std::array ids{{ SL_IID_ANDROIDSIMPLEBUFFERQUEUE, SL_IID_ANDROIDCONFIGURATION }}; - const std::array reqs{{ SL_BOOLEAN_TRUE, SL_BOOLEAN_FALSE }}; - - SLDataLocator_IODevice loc_dev{}; - loc_dev.locatorType = SL_DATALOCATOR_IODEVICE; - loc_dev.deviceType = SL_IODEVICE_AUDIOINPUT; - loc_dev.deviceID = SL_DEFAULTDEVICEID_AUDIOINPUT; - loc_dev.device = nullptr; - - SLDataSource audioSrc{}; - audioSrc.pLocator = &loc_dev; - audioSrc.pFormat = nullptr; - - SLDataLocator_AndroidSimpleBufferQueue loc_bq{}; - loc_bq.locatorType = SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE; - loc_bq.numBuffers = mDevice->BufferSize / mDevice->UpdateSize; - - SLDataSink audioSnk{}; -#ifdef SL_ANDROID_DATAFORMAT_PCM_EX - SLAndroidDataFormat_PCM_EX format_pcm_ex{}; - format_pcm_ex.formatType = SL_ANDROID_DATAFORMAT_PCM_EX; - format_pcm_ex.numChannels = mDevice->channelsFromFmt(); - format_pcm_ex.sampleRate = mDevice->Frequency * 1000; - format_pcm_ex.bitsPerSample = mDevice->bytesFromFmt() * 8; - format_pcm_ex.containerSize = format_pcm_ex.bitsPerSample; - format_pcm_ex.channelMask = GetChannelMask(mDevice->FmtChans); - format_pcm_ex.endianness = GetByteOrderEndianness(); - format_pcm_ex.representation = GetTypeRepresentation(mDevice->FmtType); - - audioSnk.pLocator = &loc_bq; - audioSnk.pFormat = &format_pcm_ex; - result = VCALL(mEngine,CreateAudioRecorder)(&mRecordObj, &audioSrc, &audioSnk, - ids.size(), ids.data(), reqs.data()); - if(SL_RESULT_SUCCESS != result) -#endif - { - /* Fallback to SLDataFormat_PCM only if it supports the desired - * sample type. - */ - if(mDevice->FmtType == DevFmtUByte || mDevice->FmtType == DevFmtShort - || mDevice->FmtType == DevFmtInt) - { - SLDataFormat_PCM format_pcm{}; - format_pcm.formatType = SL_DATAFORMAT_PCM; - format_pcm.numChannels = mDevice->channelsFromFmt(); - format_pcm.samplesPerSec = mDevice->Frequency * 1000; - format_pcm.bitsPerSample = mDevice->bytesFromFmt() * 8; - format_pcm.containerSize = format_pcm.bitsPerSample; - format_pcm.channelMask = GetChannelMask(mDevice->FmtChans); - format_pcm.endianness = GetByteOrderEndianness(); - - audioSnk.pLocator = &loc_bq; - audioSnk.pFormat = &format_pcm; - result = VCALL(mEngine,CreateAudioRecorder)(&mRecordObj, &audioSrc, &audioSnk, - ids.size(), ids.data(), reqs.data()); - } - PRINTERR(result, "engine->CreateAudioRecorder"); - } - } - if(SL_RESULT_SUCCESS == result) - { - /* Set the record preset to "generic", if possible. */ - SLAndroidConfigurationItf config; - result = VCALL(mRecordObj,GetInterface)(SL_IID_ANDROIDCONFIGURATION, &config); - PRINTERR(result, "recordObj->GetInterface SL_IID_ANDROIDCONFIGURATION"); - if(SL_RESULT_SUCCESS == result) - { - SLuint32 preset = SL_ANDROID_RECORDING_PRESET_GENERIC; - result = VCALL(config,SetConfiguration)(SL_ANDROID_KEY_RECORDING_PRESET, &preset, - sizeof(preset)); - PRINTERR(result, "config->SetConfiguration"); - } - - /* Clear any error since this was optional. */ - result = SL_RESULT_SUCCESS; - } - if(SL_RESULT_SUCCESS == result) - { - result = VCALL(mRecordObj,Realize)(SL_BOOLEAN_FALSE); - PRINTERR(result, "recordObj->Realize"); - } - - SLAndroidSimpleBufferQueueItf bufferQueue; - if(SL_RESULT_SUCCESS == result) - { - result = VCALL(mRecordObj,GetInterface)(SL_IID_ANDROIDSIMPLEBUFFERQUEUE, &bufferQueue); - PRINTERR(result, "recordObj->GetInterface"); - } - if(SL_RESULT_SUCCESS == result) - { - result = VCALL(bufferQueue,RegisterCallback)(&OpenSLCapture::processC, this); - PRINTERR(result, "bufferQueue->RegisterCallback"); - } - if(SL_RESULT_SUCCESS == result) - { - const uint chunk_size{mDevice->UpdateSize * mFrameSize}; - - auto data = mRing->getWriteVector(); - for(size_t i{0u};i < data.first.len && SL_RESULT_SUCCESS == result;i++) - { - result = VCALL(bufferQueue,Enqueue)(data.first.buf + chunk_size*i, chunk_size); - PRINTERR(result, "bufferQueue->Enqueue"); - } - for(size_t i{0u};i < data.second.len && SL_RESULT_SUCCESS == result;i++) - { - result = VCALL(bufferQueue,Enqueue)(data.second.buf + chunk_size*i, chunk_size); - PRINTERR(result, "bufferQueue->Enqueue"); - } - } - - if(SL_RESULT_SUCCESS != result) - { - if(mRecordObj) - VCALL0(mRecordObj,Destroy)(); - mRecordObj = nullptr; - - if(mEngineObj) - VCALL0(mEngineObj,Destroy)(); - mEngineObj = nullptr; - mEngine = nullptr; - - throw al::backend_exception{al::backend_error::DeviceError, - "Failed to initialize OpenSL device: 0x%08x", result}; - } - - mDevice->DeviceName = name; -} - -void OpenSLCapture::start() -{ - SLRecordItf record; - SLresult result{VCALL(mRecordObj,GetInterface)(SL_IID_RECORD, &record)}; - PRINTERR(result, "recordObj->GetInterface"); - - if(SL_RESULT_SUCCESS == result) - { - result = VCALL(record,SetRecordState)(SL_RECORDSTATE_RECORDING); - PRINTERR(result, "record->SetRecordState"); - } - if(SL_RESULT_SUCCESS != result) - throw al::backend_exception{al::backend_error::DeviceError, - "Failed to start capture: 0x%08x", result}; -} - -void OpenSLCapture::stop() -{ - SLRecordItf record; - SLresult result{VCALL(mRecordObj,GetInterface)(SL_IID_RECORD, &record)}; - PRINTERR(result, "recordObj->GetInterface"); - - if(SL_RESULT_SUCCESS == result) - { - result = VCALL(record,SetRecordState)(SL_RECORDSTATE_PAUSED); - PRINTERR(result, "record->SetRecordState"); - } -} - -void OpenSLCapture::captureSamples(al::byte *buffer, uint samples) -{ - const uint update_size{mDevice->UpdateSize}; - const uint chunk_size{update_size * mFrameSize}; - - /* Read the desired samples from the ring buffer then advance its read - * pointer. - */ - size_t adv_count{0}; - auto rdata = mRing->getReadVector(); - for(uint i{0};i < samples;) - { - const uint rem{minu(samples - i, update_size - mSplOffset)}; - std::copy_n(rdata.first.buf + mSplOffset*size_t{mFrameSize}, rem*size_t{mFrameSize}, - buffer + i*size_t{mFrameSize}); - - mSplOffset += rem; - if(mSplOffset == update_size) - { - /* Finished a chunk, reset the offset and advance the read pointer. */ - mSplOffset = 0; - - ++adv_count; - rdata.first.len -= 1; - if(!rdata.first.len) - rdata.first = rdata.second; - else - rdata.first.buf += chunk_size; - } - - i += rem; - } - mRing->readAdvance(adv_count); - - SLAndroidSimpleBufferQueueItf bufferQueue{}; - if LIKELY(mDevice->Connected.load(std::memory_order_acquire)) - { - const SLresult result{VCALL(mRecordObj,GetInterface)(SL_IID_ANDROIDSIMPLEBUFFERQUEUE, - &bufferQueue)}; - PRINTERR(result, "recordObj->GetInterface"); - if UNLIKELY(SL_RESULT_SUCCESS != result) - { - mDevice->handleDisconnect("Failed to get capture buffer queue: 0x%08x", result); - bufferQueue = nullptr; - } - } - - if LIKELY(bufferQueue) - { - SLresult result{SL_RESULT_SUCCESS}; - auto wdata = mRing->getWriteVector(); - for(size_t i{0u};i < wdata.first.len && SL_RESULT_SUCCESS == result;i++) - { - result = VCALL(bufferQueue,Enqueue)(wdata.first.buf + chunk_size*i, chunk_size); - PRINTERR(result, "bufferQueue->Enqueue"); - } - for(size_t i{0u};i < wdata.second.len && SL_RESULT_SUCCESS == result;i++) - { - result = VCALL(bufferQueue,Enqueue)(wdata.second.buf + chunk_size*i, chunk_size); - PRINTERR(result, "bufferQueue->Enqueue"); - } - } -} - -uint OpenSLCapture::availableSamples() -{ return static_cast(mRing->readSpace()*mDevice->UpdateSize - mSplOffset); } - -} // namespace - -bool OSLBackendFactory::init() { return true; } - -bool OSLBackendFactory::querySupport(BackendType type) -{ return (type == BackendType::Playback || type == BackendType::Capture); } - -std::string OSLBackendFactory::probe(BackendType type) -{ - std::string outnames; - switch(type) - { - case BackendType::Playback: - case BackendType::Capture: - /* Includes null char. */ - outnames.append(opensl_device, sizeof(opensl_device)); - break; - } - return outnames; -} - -BackendPtr OSLBackendFactory::createBackend(ALCdevice *device, BackendType type) -{ - if(type == BackendType::Playback) - return BackendPtr{new OpenSLPlayback{device}}; - if(type == BackendType::Capture) - return BackendPtr{new OpenSLCapture{device}}; - return nullptr; -} - -BackendFactory &OSLBackendFactory::getFactory() -{ - static OSLBackendFactory factory{}; - return factory; -} diff --git a/alc/backends/opensl.h b/alc/backends/opensl.h deleted file mode 100644 index b1c5cf5a..00000000 --- a/alc/backends/opensl.h +++ /dev/null @@ -1,19 +0,0 @@ -#ifndef BACKENDS_OSL_H -#define BACKENDS_OSL_H - -#include "backends/base.h" - -struct OSLBackendFactory final : public BackendFactory { -public: - bool init() override; - - bool querySupport(BackendType type) override; - - std::string probe(BackendType type) override; - - BackendPtr createBackend(ALCdevice *device, BackendType type) override; - - static BackendFactory &getFactory(); -}; - -#endif /* BACKENDS_OSL_H */ diff --git a/alc/backends/oss.cpp b/alc/backends/oss.cpp deleted file mode 100644 index 4cff5959..00000000 --- a/alc/backends/oss.cpp +++ /dev/null @@ -1,686 +0,0 @@ -/** - * OpenAL cross platform audio library - * Copyright (C) 1999-2007 by authors. - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - * Or go to http://www.gnu.org/copyleft/lgpl.html - */ - -#include "config.h" - -#include "backends/oss.h" - -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "alcmain.h" -#include "alconfig.h" -#include "albyte.h" -#include "almalloc.h" -#include "alnumeric.h" -#include "aloptional.h" -#include "alu.h" -#include "core/logging.h" -#include "ringbuffer.h" -#include "threads.h" -#include "vector.h" - -#include - -/* - * The OSS documentation talks about SOUND_MIXER_READ, but the header - * only contains MIXER_READ. Play safe. Same for WRITE. - */ -#ifndef SOUND_MIXER_READ -#define SOUND_MIXER_READ MIXER_READ -#endif -#ifndef SOUND_MIXER_WRITE -#define SOUND_MIXER_WRITE MIXER_WRITE -#endif - -#if defined(SOUND_VERSION) && (SOUND_VERSION < 0x040000) -#define ALC_OSS_COMPAT -#endif -#ifndef SNDCTL_AUDIOINFO -#define ALC_OSS_COMPAT -#endif - -/* - * FreeBSD strongly discourages the use of specific devices, - * such as those returned in oss_audioinfo.devnode - */ -#ifdef __FreeBSD__ -#define ALC_OSS_DEVNODE_TRUC -#endif - -namespace { - -constexpr char DefaultName[] = "OSS Default"; -std::string DefaultPlayback{"/dev/dsp"}; -std::string DefaultCapture{"/dev/dsp"}; - -struct DevMap { - std::string name; - std::string device_name; -}; - -al::vector PlaybackDevices; -al::vector CaptureDevices; - - -#ifdef ALC_OSS_COMPAT - -#define DSP_CAP_OUTPUT 0x00020000 -#define DSP_CAP_INPUT 0x00010000 -void ALCossListPopulate(al::vector &devlist, int type) -{ - devlist.emplace_back(DevMap{DefaultName, (type==DSP_CAP_INPUT) ? DefaultCapture : DefaultPlayback}); -} - -#else - -void ALCossListAppend(al::vector &list, al::span handle, al::span path) -{ -#ifdef ALC_OSS_DEVNODE_TRUC - for(size_t i{0};i < path.size();++i) - { - if(path[i] == '.' && handle.size() + i >= path.size()) - { - const size_t hoffset{handle.size() + i - path.size()}; - if(strncmp(path.data() + i, handle.data() + hoffset, path.size() - i) == 0) - handle = handle.first(hoffset); - path = path.first(i); - } - } -#endif - if(handle.empty()) - handle = path; - - std::string basename{handle.data(), handle.size()}; - std::string devname{path.data(), path.size()}; - - auto match_devname = [&devname](const DevMap &entry) -> bool - { return entry.device_name == devname; }; - if(std::find_if(list.cbegin(), list.cend(), match_devname) != list.cend()) - return; - - auto checkName = [&list](const std::string &name) -> bool - { - auto match_name = [&name](const DevMap &entry) -> bool { return entry.name == name; }; - return std::find_if(list.cbegin(), list.cend(), match_name) != list.cend(); - }; - int count{1}; - std::string newname{basename}; - while(checkName(newname)) - { - newname = basename; - newname += " #"; - newname += std::to_string(++count); - } - - list.emplace_back(DevMap{std::move(newname), std::move(devname)}); - const DevMap &entry = list.back(); - - TRACE("Got device \"%s\", \"%s\"\n", entry.name.c_str(), entry.device_name.c_str()); -} - -void ALCossListPopulate(al::vector &devlist, int type_flag) -{ - int fd{open("/dev/mixer", O_RDONLY)}; - if(fd < 0) - { - TRACE("Could not open /dev/mixer: %s\n", strerror(errno)); - goto done; - } - - oss_sysinfo si; - if(ioctl(fd, SNDCTL_SYSINFO, &si) == -1) - { - TRACE("SNDCTL_SYSINFO failed: %s\n", strerror(errno)); - goto done; - } - - for(int i{0};i < si.numaudios;i++) - { - oss_audioinfo ai; - ai.dev = i; - if(ioctl(fd, SNDCTL_AUDIOINFO, &ai) == -1) - { - ERR("SNDCTL_AUDIOINFO (%d) failed: %s\n", i, strerror(errno)); - continue; - } - if(!(ai.caps&type_flag) || ai.devnode[0] == '\0') - continue; - - al::span handle; - if(ai.handle[0] != '\0') - handle = {ai.handle, strnlen(ai.handle, sizeof(ai.handle))}; - else - handle = {ai.name, strnlen(ai.name, sizeof(ai.name))}; - al::span devnode{ai.devnode, strnlen(ai.devnode, sizeof(ai.devnode))}; - - ALCossListAppend(devlist, handle, devnode); - } - -done: - if(fd >= 0) - close(fd); - fd = -1; - - const char *defdev{((type_flag==DSP_CAP_INPUT) ? DefaultCapture : DefaultPlayback).c_str()}; - auto iter = std::find_if(devlist.cbegin(), devlist.cend(), - [defdev](const DevMap &entry) -> bool - { return entry.device_name == defdev; } - ); - if(iter == devlist.cend()) - devlist.insert(devlist.begin(), DevMap{DefaultName, defdev}); - else - { - DevMap entry{std::move(*iter)}; - devlist.erase(iter); - devlist.insert(devlist.begin(), std::move(entry)); - } - devlist.shrink_to_fit(); -} - -#endif - -uint log2i(uint x) -{ - uint y{0}; - while(x > 1) - { - x >>= 1; - y++; - } - return y; -} - - -struct OSSPlayback final : public BackendBase { - OSSPlayback(ALCdevice *device) noexcept : BackendBase{device} { } - ~OSSPlayback() override; - - int mixerProc(); - - void open(const char *name) override; - bool reset() override; - void start() override; - void stop() override; - - int mFd{-1}; - - al::vector mMixData; - - std::atomic mKillNow{true}; - std::thread mThread; - - DEF_NEWDEL(OSSPlayback) -}; - -OSSPlayback::~OSSPlayback() -{ - if(mFd != -1) - close(mFd); - mFd = -1; -} - - -int OSSPlayback::mixerProc() -{ - SetRTPriority(); - althrd_setname(MIXER_THREAD_NAME); - - const size_t frame_step{mDevice->channelsFromFmt()}; - const size_t frame_size{mDevice->frameSizeFromFmt()}; - - while(!mKillNow.load(std::memory_order_acquire) - && mDevice->Connected.load(std::memory_order_acquire)) - { - pollfd pollitem{}; - pollitem.fd = mFd; - pollitem.events = POLLOUT; - - int pret{poll(&pollitem, 1, 1000)}; - if(pret < 0) - { - if(errno == EINTR || errno == EAGAIN) - continue; - ERR("poll failed: %s\n", strerror(errno)); - mDevice->handleDisconnect("Failed waiting for playback buffer: %s", strerror(errno)); - break; - } - else if(pret == 0) - { - WARN("poll timeout\n"); - continue; - } - - al::byte *write_ptr{mMixData.data()}; - size_t to_write{mMixData.size()}; - mDevice->renderSamples(write_ptr, static_cast(to_write/frame_size), frame_step); - while(to_write > 0 && !mKillNow.load(std::memory_order_acquire)) - { - ssize_t wrote{write(mFd, write_ptr, to_write)}; - if(wrote < 0) - { - if(errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) - continue; - ERR("write failed: %s\n", strerror(errno)); - mDevice->handleDisconnect("Failed writing playback samples: %s", strerror(errno)); - break; - } - - to_write -= static_cast(wrote); - write_ptr += wrote; - } - } - - return 0; -} - - -void OSSPlayback::open(const char *name) -{ - const char *devname{DefaultPlayback.c_str()}; - if(!name) - name = DefaultName; - else - { - if(PlaybackDevices.empty()) - ALCossListPopulate(PlaybackDevices, DSP_CAP_OUTPUT); - - auto iter = std::find_if(PlaybackDevices.cbegin(), PlaybackDevices.cend(), - [&name](const DevMap &entry) -> bool - { return entry.name == name; } - ); - if(iter == PlaybackDevices.cend()) - throw al::backend_exception{al::backend_error::NoDevice, - "Device name \"%s\" not found", name}; - devname = iter->device_name.c_str(); - } - - mFd = ::open(devname, O_WRONLY); - if(mFd == -1) - throw al::backend_exception{al::backend_error::NoDevice, "Could not open %s: %s", devname, - strerror(errno)}; - - mDevice->DeviceName = name; -} - -bool OSSPlayback::reset() -{ - int ossFormat{}; - switch(mDevice->FmtType) - { - case DevFmtByte: - ossFormat = AFMT_S8; - break; - case DevFmtUByte: - ossFormat = AFMT_U8; - break; - case DevFmtUShort: - case DevFmtInt: - case DevFmtUInt: - case DevFmtFloat: - mDevice->FmtType = DevFmtShort; - /* fall-through */ - case DevFmtShort: - ossFormat = AFMT_S16_NE; - break; - } - - uint periods{mDevice->BufferSize / mDevice->UpdateSize}; - uint numChannels{mDevice->channelsFromFmt()}; - uint ossSpeed{mDevice->Frequency}; - uint frameSize{numChannels * mDevice->bytesFromFmt()}; - /* According to the OSS spec, 16 bytes (log2(16)) is the minimum. */ - uint log2FragmentSize{maxu(log2i(mDevice->UpdateSize*frameSize), 4)}; - uint numFragmentsLogSize{(periods << 16) | log2FragmentSize}; - - audio_buf_info info{}; - const char *err; -#define CHECKERR(func) if((func) < 0) { \ - err = #func; \ - goto err; \ -} - /* Don't fail if SETFRAGMENT fails. We can handle just about anything - * that's reported back via GETOSPACE */ - ioctl(mFd, SNDCTL_DSP_SETFRAGMENT, &numFragmentsLogSize); - CHECKERR(ioctl(mFd, SNDCTL_DSP_SETFMT, &ossFormat)); - CHECKERR(ioctl(mFd, SNDCTL_DSP_CHANNELS, &numChannels)); - CHECKERR(ioctl(mFd, SNDCTL_DSP_SPEED, &ossSpeed)); - CHECKERR(ioctl(mFd, SNDCTL_DSP_GETOSPACE, &info)); - if(0) - { - err: - ERR("%s failed: %s\n", err, strerror(errno)); - return false; - } -#undef CHECKERR - - if(mDevice->channelsFromFmt() != numChannels) - { - ERR("Failed to set %s, got %d channels instead\n", DevFmtChannelsString(mDevice->FmtChans), - numChannels); - return false; - } - - if(!((ossFormat == AFMT_S8 && mDevice->FmtType == DevFmtByte) || - (ossFormat == AFMT_U8 && mDevice->FmtType == DevFmtUByte) || - (ossFormat == AFMT_S16_NE && mDevice->FmtType == DevFmtShort))) - { - ERR("Failed to set %s samples, got OSS format %#x\n", DevFmtTypeString(mDevice->FmtType), - ossFormat); - return false; - } - - mDevice->Frequency = ossSpeed; - mDevice->UpdateSize = static_cast(info.fragsize) / frameSize; - mDevice->BufferSize = static_cast(info.fragments) * mDevice->UpdateSize; - - setDefaultChannelOrder(); - - mMixData.resize(mDevice->UpdateSize * mDevice->frameSizeFromFmt()); - - return true; -} - -void OSSPlayback::start() -{ - try { - mKillNow.store(false, std::memory_order_release); - mThread = std::thread{std::mem_fn(&OSSPlayback::mixerProc), this}; - } - catch(std::exception& e) { - throw al::backend_exception{al::backend_error::DeviceError, - "Failed to start mixing thread: %s", e.what()}; - } -} - -void OSSPlayback::stop() -{ - if(mKillNow.exchange(true, std::memory_order_acq_rel) || !mThread.joinable()) - return; - mThread.join(); - - if(ioctl(mFd, SNDCTL_DSP_RESET) != 0) - ERR("Error resetting device: %s\n", strerror(errno)); -} - - -struct OSScapture final : public BackendBase { - OSScapture(ALCdevice *device) noexcept : BackendBase{device} { } - ~OSScapture() override; - - int recordProc(); - - void open(const char *name) override; - void start() override; - void stop() override; - void captureSamples(al::byte *buffer, uint samples) override; - uint availableSamples() override; - - int mFd{-1}; - - RingBufferPtr mRing{nullptr}; - - std::atomic mKillNow{true}; - std::thread mThread; - - DEF_NEWDEL(OSScapture) -}; - -OSScapture::~OSScapture() -{ - if(mFd != -1) - close(mFd); - mFd = -1; -} - - -int OSScapture::recordProc() -{ - SetRTPriority(); - althrd_setname(RECORD_THREAD_NAME); - - const size_t frame_size{mDevice->frameSizeFromFmt()}; - while(!mKillNow.load(std::memory_order_acquire)) - { - pollfd pollitem{}; - pollitem.fd = mFd; - pollitem.events = POLLIN; - - int sret{poll(&pollitem, 1, 1000)}; - if(sret < 0) - { - if(errno == EINTR || errno == EAGAIN) - continue; - ERR("poll failed: %s\n", strerror(errno)); - mDevice->handleDisconnect("Failed to check capture samples: %s", strerror(errno)); - break; - } - else if(sret == 0) - { - WARN("poll timeout\n"); - continue; - } - - auto vec = mRing->getWriteVector(); - if(vec.first.len > 0) - { - ssize_t amt{read(mFd, vec.first.buf, vec.first.len*frame_size)}; - if(amt < 0) - { - ERR("read failed: %s\n", strerror(errno)); - mDevice->handleDisconnect("Failed reading capture samples: %s", strerror(errno)); - break; - } - mRing->writeAdvance(static_cast(amt)/frame_size); - } - } - - return 0; -} - - -void OSScapture::open(const char *name) -{ - const char *devname{DefaultCapture.c_str()}; - if(!name) - name = DefaultName; - else - { - if(CaptureDevices.empty()) - ALCossListPopulate(CaptureDevices, DSP_CAP_INPUT); - - auto iter = std::find_if(CaptureDevices.cbegin(), CaptureDevices.cend(), - [&name](const DevMap &entry) -> bool - { return entry.name == name; } - ); - if(iter == CaptureDevices.cend()) - throw al::backend_exception{al::backend_error::NoDevice, - "Device name \"%s\" not found", name}; - devname = iter->device_name.c_str(); - } - - mFd = ::open(devname, O_RDONLY); - if(mFd == -1) - throw al::backend_exception{al::backend_error::NoDevice, "Could not open %s: %s", devname, - strerror(errno)}; - - int ossFormat{}; - switch(mDevice->FmtType) - { - case DevFmtByte: - ossFormat = AFMT_S8; - break; - case DevFmtUByte: - ossFormat = AFMT_U8; - break; - case DevFmtShort: - ossFormat = AFMT_S16_NE; - break; - case DevFmtUShort: - case DevFmtInt: - case DevFmtUInt: - case DevFmtFloat: - throw al::backend_exception{al::backend_error::DeviceError, - "%s capture samples not supported", DevFmtTypeString(mDevice->FmtType)}; - } - - uint periods{4}; - uint numChannels{mDevice->channelsFromFmt()}; - uint frameSize{numChannels * mDevice->bytesFromFmt()}; - uint ossSpeed{mDevice->Frequency}; - /* according to the OSS spec, 16 bytes are the minimum */ - uint log2FragmentSize{maxu(log2i(mDevice->BufferSize * frameSize / periods), 4)}; - uint numFragmentsLogSize{(periods << 16) | log2FragmentSize}; - - audio_buf_info info{}; -#define CHECKERR(func) if((func) < 0) { \ - throw al::backend_exception{al::backend_error::DeviceError, #func " failed: %s", \ - strerror(errno)}; \ -} - CHECKERR(ioctl(mFd, SNDCTL_DSP_SETFRAGMENT, &numFragmentsLogSize)); - CHECKERR(ioctl(mFd, SNDCTL_DSP_SETFMT, &ossFormat)); - CHECKERR(ioctl(mFd, SNDCTL_DSP_CHANNELS, &numChannels)); - CHECKERR(ioctl(mFd, SNDCTL_DSP_SPEED, &ossSpeed)); - CHECKERR(ioctl(mFd, SNDCTL_DSP_GETISPACE, &info)); -#undef CHECKERR - - if(mDevice->channelsFromFmt() != numChannels) - throw al::backend_exception{al::backend_error::DeviceError, - "Failed to set %s, got %d channels instead", DevFmtChannelsString(mDevice->FmtChans), - numChannels}; - - if(!((ossFormat == AFMT_S8 && mDevice->FmtType == DevFmtByte) - || (ossFormat == AFMT_U8 && mDevice->FmtType == DevFmtUByte) - || (ossFormat == AFMT_S16_NE && mDevice->FmtType == DevFmtShort))) - throw al::backend_exception{al::backend_error::DeviceError, - "Failed to set %s samples, got OSS format %#x", DevFmtTypeString(mDevice->FmtType), - ossFormat}; - - mRing = RingBuffer::Create(mDevice->BufferSize, frameSize, false); - - mDevice->DeviceName = name; -} - -void OSScapture::start() -{ - try { - mKillNow.store(false, std::memory_order_release); - mThread = std::thread{std::mem_fn(&OSScapture::recordProc), this}; - } - catch(std::exception& e) { - throw al::backend_exception{al::backend_error::DeviceError, - "Failed to start recording thread: %s", e.what()}; - } -} - -void OSScapture::stop() -{ - if(mKillNow.exchange(true, std::memory_order_acq_rel) || !mThread.joinable()) - return; - mThread.join(); - - if(ioctl(mFd, SNDCTL_DSP_RESET) != 0) - ERR("Error resetting device: %s\n", strerror(errno)); -} - -void OSScapture::captureSamples(al::byte *buffer, uint samples) -{ mRing->read(buffer, samples); } - -uint OSScapture::availableSamples() -{ return static_cast(mRing->readSpace()); } - -} // namespace - - -BackendFactory &OSSBackendFactory::getFactory() -{ - static OSSBackendFactory factory{}; - return factory; -} - -bool OSSBackendFactory::init() -{ - if(auto devopt = ConfigValueStr(nullptr, "oss", "device")) - DefaultPlayback = std::move(*devopt); - if(auto capopt = ConfigValueStr(nullptr, "oss", "capture")) - DefaultCapture = std::move(*capopt); - - return true; -} - -bool OSSBackendFactory::querySupport(BackendType type) -{ return (type == BackendType::Playback || type == BackendType::Capture); } - -std::string OSSBackendFactory::probe(BackendType type) -{ - std::string outnames; - - auto add_device = [&outnames](const DevMap &entry) -> void - { - struct stat buf; - if(stat(entry.device_name.c_str(), &buf) == 0) - { - /* Includes null char. */ - outnames.append(entry.name.c_str(), entry.name.length()+1); - } - }; - - switch(type) - { - case BackendType::Playback: - PlaybackDevices.clear(); - ALCossListPopulate(PlaybackDevices, DSP_CAP_OUTPUT); - std::for_each(PlaybackDevices.cbegin(), PlaybackDevices.cend(), add_device); - break; - - case BackendType::Capture: - CaptureDevices.clear(); - ALCossListPopulate(CaptureDevices, DSP_CAP_INPUT); - std::for_each(CaptureDevices.cbegin(), CaptureDevices.cend(), add_device); - break; - } - - return outnames; -} - -BackendPtr OSSBackendFactory::createBackend(ALCdevice *device, BackendType type) -{ - if(type == BackendType::Playback) - return BackendPtr{new OSSPlayback{device}}; - if(type == BackendType::Capture) - return BackendPtr{new OSScapture{device}}; - return nullptr; -} diff --git a/alc/backends/oss.h b/alc/backends/oss.h deleted file mode 100644 index dd92efc3..00000000 --- a/alc/backends/oss.h +++ /dev/null @@ -1,19 +0,0 @@ -#ifndef BACKENDS_OSS_H -#define BACKENDS_OSS_H - -#include "backends/base.h" - -struct OSSBackendFactory final : public BackendFactory { -public: - bool init() override; - - bool querySupport(BackendType type) override; - - std::string probe(BackendType type) override; - - BackendPtr createBackend(ALCdevice *device, BackendType type) override; - - static BackendFactory &getFactory(); -}; - -#endif /* BACKENDS_OSS_H */ diff --git a/alc/backends/portaudio.cpp b/alc/backends/portaudio.cpp deleted file mode 100644 index d2e6a5a4..00000000 --- a/alc/backends/portaudio.cpp +++ /dev/null @@ -1,442 +0,0 @@ -/** - * OpenAL cross platform audio library - * Copyright (C) 1999-2007 by authors. - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - * Or go to http://www.gnu.org/copyleft/lgpl.html - */ - -#include "config.h" - -#include "backends/portaudio.h" - -#include -#include -#include - -#include "alcmain.h" -#include "alu.h" -#include "alconfig.h" -#include "core/logging.h" -#include "dynload.h" -#include "ringbuffer.h" - -#include - - -namespace { - -constexpr char pa_device[] = "PortAudio Default"; - - -#ifdef HAVE_DYNLOAD -void *pa_handle; -#define MAKE_FUNC(x) decltype(x) * p##x -MAKE_FUNC(Pa_Initialize); -MAKE_FUNC(Pa_Terminate); -MAKE_FUNC(Pa_GetErrorText); -MAKE_FUNC(Pa_StartStream); -MAKE_FUNC(Pa_StopStream); -MAKE_FUNC(Pa_OpenStream); -MAKE_FUNC(Pa_CloseStream); -MAKE_FUNC(Pa_GetDefaultOutputDevice); -MAKE_FUNC(Pa_GetDefaultInputDevice); -MAKE_FUNC(Pa_GetStreamInfo); -#undef MAKE_FUNC - -#ifndef IN_IDE_PARSER -#define Pa_Initialize pPa_Initialize -#define Pa_Terminate pPa_Terminate -#define Pa_GetErrorText pPa_GetErrorText -#define Pa_StartStream pPa_StartStream -#define Pa_StopStream pPa_StopStream -#define Pa_OpenStream pPa_OpenStream -#define Pa_CloseStream pPa_CloseStream -#define Pa_GetDefaultOutputDevice pPa_GetDefaultOutputDevice -#define Pa_GetDefaultInputDevice pPa_GetDefaultInputDevice -#define Pa_GetStreamInfo pPa_GetStreamInfo -#endif -#endif - - -struct PortPlayback final : public BackendBase { - PortPlayback(ALCdevice *device) noexcept : BackendBase{device} { } - ~PortPlayback() override; - - int writeCallback(const void *inputBuffer, void *outputBuffer, unsigned long framesPerBuffer, - const PaStreamCallbackTimeInfo *timeInfo, const PaStreamCallbackFlags statusFlags) noexcept; - static int writeCallbackC(const void *inputBuffer, void *outputBuffer, - unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo *timeInfo, - const PaStreamCallbackFlags statusFlags, void *userData) noexcept - { - return static_cast(userData)->writeCallback(inputBuffer, outputBuffer, - framesPerBuffer, timeInfo, statusFlags); - } - - void open(const char *name) override; - bool reset() override; - void start() override; - void stop() override; - - PaStream *mStream{nullptr}; - PaStreamParameters mParams{}; - uint mUpdateSize{0u}; - - DEF_NEWDEL(PortPlayback) -}; - -PortPlayback::~PortPlayback() -{ - PaError err{mStream ? Pa_CloseStream(mStream) : paNoError}; - if(err != paNoError) - ERR("Error closing stream: %s\n", Pa_GetErrorText(err)); - mStream = nullptr; -} - - -int PortPlayback::writeCallback(const void*, void *outputBuffer, unsigned long framesPerBuffer, - const PaStreamCallbackTimeInfo*, const PaStreamCallbackFlags) noexcept -{ - mDevice->renderSamples(outputBuffer, static_cast(framesPerBuffer), - static_cast(mParams.channelCount)); - return 0; -} - - -void PortPlayback::open(const char *name) -{ - if(!name) - name = pa_device; - else if(strcmp(name, pa_device) != 0) - throw al::backend_exception{al::backend_error::NoDevice, "Device name \"%s\" not found", - name}; - - mUpdateSize = mDevice->UpdateSize; - - auto devidopt = ConfigValueInt(nullptr, "port", "device"); - if(devidopt && *devidopt >= 0) mParams.device = *devidopt; - else mParams.device = Pa_GetDefaultOutputDevice(); - mParams.suggestedLatency = mDevice->BufferSize / static_cast(mDevice->Frequency); - mParams.hostApiSpecificStreamInfo = nullptr; - - mParams.channelCount = ((mDevice->FmtChans == DevFmtMono) ? 1 : 2); - - switch(mDevice->FmtType) - { - case DevFmtByte: - mParams.sampleFormat = paInt8; - break; - case DevFmtUByte: - mParams.sampleFormat = paUInt8; - break; - case DevFmtUShort: - /* fall-through */ - case DevFmtShort: - mParams.sampleFormat = paInt16; - break; - case DevFmtUInt: - /* fall-through */ - case DevFmtInt: - mParams.sampleFormat = paInt32; - break; - case DevFmtFloat: - mParams.sampleFormat = paFloat32; - break; - } - -retry_open: - PaError err{Pa_OpenStream(&mStream, nullptr, &mParams, mDevice->Frequency, mDevice->UpdateSize, - paNoFlag, &PortPlayback::writeCallbackC, this)}; - if(err != paNoError) - { - if(mParams.sampleFormat == paFloat32) - { - mParams.sampleFormat = paInt16; - goto retry_open; - } - throw al::backend_exception{al::backend_error::NoDevice, "Failed to open stream: %s", - Pa_GetErrorText(err)}; - } - - mDevice->DeviceName = name; -} - -bool PortPlayback::reset() -{ - const PaStreamInfo *streamInfo{Pa_GetStreamInfo(mStream)}; - mDevice->Frequency = static_cast(streamInfo->sampleRate); - mDevice->UpdateSize = mUpdateSize; - - if(mParams.sampleFormat == paInt8) - mDevice->FmtType = DevFmtByte; - else if(mParams.sampleFormat == paUInt8) - mDevice->FmtType = DevFmtUByte; - else if(mParams.sampleFormat == paInt16) - mDevice->FmtType = DevFmtShort; - else if(mParams.sampleFormat == paInt32) - mDevice->FmtType = DevFmtInt; - else if(mParams.sampleFormat == paFloat32) - mDevice->FmtType = DevFmtFloat; - else - { - ERR("Unexpected sample format: 0x%lx\n", mParams.sampleFormat); - return false; - } - - if(mParams.channelCount == 2) - mDevice->FmtChans = DevFmtStereo; - else if(mParams.channelCount == 1) - mDevice->FmtChans = DevFmtMono; - else - { - ERR("Unexpected channel count: %u\n", mParams.channelCount); - return false; - } - setDefaultChannelOrder(); - - return true; -} - -void PortPlayback::start() -{ - const PaError err{Pa_StartStream(mStream)}; - if(err == paNoError) - throw al::backend_exception{al::backend_error::DeviceError, "Failed to start playback: %s", - Pa_GetErrorText(err)}; -} - -void PortPlayback::stop() -{ - PaError err{Pa_StopStream(mStream)}; - if(err != paNoError) - ERR("Error stopping stream: %s\n", Pa_GetErrorText(err)); -} - - -struct PortCapture final : public BackendBase { - PortCapture(ALCdevice *device) noexcept : BackendBase{device} { } - ~PortCapture() override; - - int readCallback(const void *inputBuffer, void *outputBuffer, unsigned long framesPerBuffer, - const PaStreamCallbackTimeInfo *timeInfo, const PaStreamCallbackFlags statusFlags) noexcept; - static int readCallbackC(const void *inputBuffer, void *outputBuffer, - unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo *timeInfo, - const PaStreamCallbackFlags statusFlags, void *userData) noexcept - { - return static_cast(userData)->readCallback(inputBuffer, outputBuffer, - framesPerBuffer, timeInfo, statusFlags); - } - - void open(const char *name) override; - void start() override; - void stop() override; - void captureSamples(al::byte *buffer, uint samples) override; - uint availableSamples() override; - - PaStream *mStream{nullptr}; - PaStreamParameters mParams; - - RingBufferPtr mRing{nullptr}; - - DEF_NEWDEL(PortCapture) -}; - -PortCapture::~PortCapture() -{ - PaError err{mStream ? Pa_CloseStream(mStream) : paNoError}; - if(err != paNoError) - ERR("Error closing stream: %s\n", Pa_GetErrorText(err)); - mStream = nullptr; -} - - -int PortCapture::readCallback(const void *inputBuffer, void*, unsigned long framesPerBuffer, - const PaStreamCallbackTimeInfo*, const PaStreamCallbackFlags) noexcept -{ - mRing->write(inputBuffer, framesPerBuffer); - return 0; -} - - -void PortCapture::open(const char *name) -{ - if(!name) - name = pa_device; - else if(strcmp(name, pa_device) != 0) - throw al::backend_exception{al::backend_error::NoDevice, "Device name \"%s\" not found", - name}; - - uint samples{mDevice->BufferSize}; - samples = maxu(samples, 100 * mDevice->Frequency / 1000); - uint frame_size{mDevice->frameSizeFromFmt()}; - - mRing = RingBuffer::Create(samples, frame_size, false); - - auto devidopt = ConfigValueInt(nullptr, "port", "capture"); - if(devidopt && *devidopt >= 0) mParams.device = *devidopt; - else mParams.device = Pa_GetDefaultOutputDevice(); - mParams.suggestedLatency = 0.0f; - mParams.hostApiSpecificStreamInfo = nullptr; - - switch(mDevice->FmtType) - { - case DevFmtByte: - mParams.sampleFormat = paInt8; - break; - case DevFmtUByte: - mParams.sampleFormat = paUInt8; - break; - case DevFmtShort: - mParams.sampleFormat = paInt16; - break; - case DevFmtInt: - mParams.sampleFormat = paInt32; - break; - case DevFmtFloat: - mParams.sampleFormat = paFloat32; - break; - case DevFmtUInt: - case DevFmtUShort: - throw al::backend_exception{al::backend_error::DeviceError, "%s samples not supported", - DevFmtTypeString(mDevice->FmtType)}; - } - mParams.channelCount = static_cast(mDevice->channelsFromFmt()); - - PaError err{Pa_OpenStream(&mStream, &mParams, nullptr, mDevice->Frequency, - paFramesPerBufferUnspecified, paNoFlag, &PortCapture::readCallbackC, this)}; - if(err != paNoError) - throw al::backend_exception{al::backend_error::NoDevice, "Failed to open stream: %s", - Pa_GetErrorText(err)}; - - mDevice->DeviceName = name; -} - - -void PortCapture::start() -{ - const PaError err{Pa_StartStream(mStream)}; - if(err != paNoError) - throw al::backend_exception{al::backend_error::DeviceError, - "Failed to start recording: %s", Pa_GetErrorText(err)}; -} - -void PortCapture::stop() -{ - PaError err{Pa_StopStream(mStream)}; - if(err != paNoError) - ERR("Error stopping stream: %s\n", Pa_GetErrorText(err)); -} - - -uint PortCapture::availableSamples() -{ return static_cast(mRing->readSpace()); } - -void PortCapture::captureSamples(al::byte *buffer, uint samples) -{ mRing->read(buffer, samples); } - -} // namespace - - -bool PortBackendFactory::init() -{ - PaError err; - -#ifdef HAVE_DYNLOAD - if(!pa_handle) - { -#ifdef _WIN32 -# define PALIB "portaudio.dll" -#elif defined(__APPLE__) && defined(__MACH__) -# define PALIB "libportaudio.2.dylib" -#elif defined(__OpenBSD__) -# define PALIB "libportaudio.so" -#else -# define PALIB "libportaudio.so.2" -#endif - - pa_handle = LoadLib(PALIB); - if(!pa_handle) - return false; - -#define LOAD_FUNC(f) do { \ - p##f = reinterpret_cast(GetSymbol(pa_handle, #f)); \ - if(p##f == nullptr) \ - { \ - CloseLib(pa_handle); \ - pa_handle = nullptr; \ - return false; \ - } \ -} while(0) - LOAD_FUNC(Pa_Initialize); - LOAD_FUNC(Pa_Terminate); - LOAD_FUNC(Pa_GetErrorText); - LOAD_FUNC(Pa_StartStream); - LOAD_FUNC(Pa_StopStream); - LOAD_FUNC(Pa_OpenStream); - LOAD_FUNC(Pa_CloseStream); - LOAD_FUNC(Pa_GetDefaultOutputDevice); - LOAD_FUNC(Pa_GetDefaultInputDevice); - LOAD_FUNC(Pa_GetStreamInfo); -#undef LOAD_FUNC - - if((err=Pa_Initialize()) != paNoError) - { - ERR("Pa_Initialize() returned an error: %s\n", Pa_GetErrorText(err)); - CloseLib(pa_handle); - pa_handle = nullptr; - return false; - } - } -#else - if((err=Pa_Initialize()) != paNoError) - { - ERR("Pa_Initialize() returned an error: %s\n", Pa_GetErrorText(err)); - return false; - } -#endif - return true; -} - -bool PortBackendFactory::querySupport(BackendType type) -{ return (type == BackendType::Playback || type == BackendType::Capture); } - -std::string PortBackendFactory::probe(BackendType type) -{ - std::string outnames; - switch(type) - { - case BackendType::Playback: - case BackendType::Capture: - /* Includes null char. */ - outnames.append(pa_device, sizeof(pa_device)); - break; - } - return outnames; -} - -BackendPtr PortBackendFactory::createBackend(ALCdevice *device, BackendType type) -{ - if(type == BackendType::Playback) - return BackendPtr{new PortPlayback{device}}; - if(type == BackendType::Capture) - return BackendPtr{new PortCapture{device}}; - return nullptr; -} - -BackendFactory &PortBackendFactory::getFactory() -{ - static PortBackendFactory factory{}; - return factory; -} diff --git a/alc/backends/portaudio.h b/alc/backends/portaudio.h deleted file mode 100644 index 9dbd6b94..00000000 --- a/alc/backends/portaudio.h +++ /dev/null @@ -1,19 +0,0 @@ -#ifndef BACKENDS_PORTAUDIO_H -#define BACKENDS_PORTAUDIO_H - -#include "backends/base.h" - -struct PortBackendFactory final : public BackendFactory { -public: - bool init() override; - - bool querySupport(BackendType type) override; - - std::string probe(BackendType type) override; - - BackendPtr createBackend(ALCdevice *device, BackendType type) override; - - static BackendFactory &getFactory(); -}; - -#endif /* BACKENDS_PORTAUDIO_H */ diff --git a/alc/backends/pulseaudio.cpp b/alc/backends/pulseaudio.cpp deleted file mode 100644 index a6aa93a5..00000000 --- a/alc/backends/pulseaudio.cpp +++ /dev/null @@ -1,1521 +0,0 @@ -/** - * OpenAL cross platform audio library - * Copyright (C) 2009 by Konstantinos Natsakis - * Copyright (C) 2010 by Chris Robinson - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - * Or go to http://www.gnu.org/copyleft/lgpl.html - */ - -#include "config.h" - -#include "backends/pulseaudio.h" - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -#include "alcmain.h" -#include "alu.h" -#include "alconfig.h" -#include "compat.h" -#include "core/logging.h" -#include "dynload.h" -#include "strutils.h" - -#include - - -namespace { - -#ifdef HAVE_DYNLOAD -#define PULSE_FUNCS(MAGIC) \ - MAGIC(pa_mainloop_new); \ - MAGIC(pa_mainloop_free); \ - MAGIC(pa_mainloop_set_poll_func); \ - MAGIC(pa_mainloop_run); \ - MAGIC(pa_mainloop_quit); \ - MAGIC(pa_mainloop_get_api); \ - MAGIC(pa_context_new); \ - MAGIC(pa_context_unref); \ - MAGIC(pa_context_get_state); \ - MAGIC(pa_context_disconnect); \ - MAGIC(pa_context_set_state_callback); \ - MAGIC(pa_context_errno); \ - MAGIC(pa_context_connect); \ - MAGIC(pa_context_get_server_info); \ - MAGIC(pa_context_get_sink_info_by_name); \ - MAGIC(pa_context_get_sink_info_list); \ - MAGIC(pa_context_get_source_info_by_name); \ - MAGIC(pa_context_get_source_info_list); \ - MAGIC(pa_stream_new); \ - MAGIC(pa_stream_unref); \ - MAGIC(pa_stream_drop); \ - MAGIC(pa_stream_get_state); \ - MAGIC(pa_stream_peek); \ - MAGIC(pa_stream_write); \ - MAGIC(pa_stream_connect_record); \ - MAGIC(pa_stream_connect_playback); \ - MAGIC(pa_stream_readable_size); \ - MAGIC(pa_stream_writable_size); \ - MAGIC(pa_stream_is_corked); \ - MAGIC(pa_stream_cork); \ - MAGIC(pa_stream_is_suspended); \ - MAGIC(pa_stream_get_device_name); \ - MAGIC(pa_stream_get_latency); \ - MAGIC(pa_stream_set_write_callback); \ - MAGIC(pa_stream_set_buffer_attr); \ - MAGIC(pa_stream_get_buffer_attr); \ - MAGIC(pa_stream_get_sample_spec); \ - MAGIC(pa_stream_get_time); \ - MAGIC(pa_stream_set_read_callback); \ - MAGIC(pa_stream_set_state_callback); \ - MAGIC(pa_stream_set_moved_callback); \ - MAGIC(pa_stream_set_underflow_callback); \ - MAGIC(pa_stream_new_with_proplist); \ - MAGIC(pa_stream_disconnect); \ - MAGIC(pa_stream_set_buffer_attr_callback); \ - MAGIC(pa_stream_begin_write); \ - MAGIC(pa_channel_map_init_auto); \ - MAGIC(pa_channel_map_parse); \ - MAGIC(pa_channel_map_snprint); \ - MAGIC(pa_channel_map_equal); \ - MAGIC(pa_channel_map_superset); \ - MAGIC(pa_channel_position_to_string); \ - MAGIC(pa_operation_get_state); \ - MAGIC(pa_operation_unref); \ - MAGIC(pa_sample_spec_valid); \ - MAGIC(pa_frame_size); \ - MAGIC(pa_strerror); \ - MAGIC(pa_path_get_filename); \ - MAGIC(pa_get_binary_name); \ - MAGIC(pa_xmalloc); \ - MAGIC(pa_xfree); - -void *pulse_handle; -#define MAKE_FUNC(x) decltype(x) * p##x -PULSE_FUNCS(MAKE_FUNC) -#undef MAKE_FUNC - -#ifndef IN_IDE_PARSER -#define pa_mainloop_new ppa_mainloop_new -#define pa_mainloop_free ppa_mainloop_free -#define pa_mainloop_set_poll_func ppa_mainloop_set_poll_func -#define pa_mainloop_run ppa_mainloop_run -#define pa_mainloop_quit ppa_mainloop_quit -#define pa_mainloop_get_api ppa_mainloop_get_api -#define pa_context_new ppa_context_new -#define pa_context_unref ppa_context_unref -#define pa_context_get_state ppa_context_get_state -#define pa_context_disconnect ppa_context_disconnect -#define pa_context_set_state_callback ppa_context_set_state_callback -#define pa_context_errno ppa_context_errno -#define pa_context_connect ppa_context_connect -#define pa_context_get_server_info ppa_context_get_server_info -#define pa_context_get_sink_info_by_name ppa_context_get_sink_info_by_name -#define pa_context_get_sink_info_list ppa_context_get_sink_info_list -#define pa_context_get_source_info_by_name ppa_context_get_source_info_by_name -#define pa_context_get_source_info_list ppa_context_get_source_info_list -#define pa_stream_new ppa_stream_new -#define pa_stream_unref ppa_stream_unref -#define pa_stream_disconnect ppa_stream_disconnect -#define pa_stream_drop ppa_stream_drop -#define pa_stream_set_write_callback ppa_stream_set_write_callback -#define pa_stream_set_buffer_attr ppa_stream_set_buffer_attr -#define pa_stream_get_buffer_attr ppa_stream_get_buffer_attr -#define pa_stream_get_sample_spec ppa_stream_get_sample_spec -#define pa_stream_get_time ppa_stream_get_time -#define pa_stream_set_read_callback ppa_stream_set_read_callback -#define pa_stream_set_state_callback ppa_stream_set_state_callback -#define pa_stream_set_moved_callback ppa_stream_set_moved_callback -#define pa_stream_set_underflow_callback ppa_stream_set_underflow_callback -#define pa_stream_connect_record ppa_stream_connect_record -#define pa_stream_connect_playback ppa_stream_connect_playback -#define pa_stream_readable_size ppa_stream_readable_size -#define pa_stream_writable_size ppa_stream_writable_size -#define pa_stream_is_corked ppa_stream_is_corked -#define pa_stream_cork ppa_stream_cork -#define pa_stream_is_suspended ppa_stream_is_suspended -#define pa_stream_get_device_name ppa_stream_get_device_name -#define pa_stream_get_latency ppa_stream_get_latency -#define pa_stream_set_buffer_attr_callback ppa_stream_set_buffer_attr_callback -#define pa_stream_begin_write ppa_stream_begin_write -#define pa_channel_map_init_auto ppa_channel_map_init_auto -#define pa_channel_map_parse ppa_channel_map_parse -#define pa_channel_map_snprint ppa_channel_map_snprint -#define pa_channel_map_equal ppa_channel_map_equal -#define pa_channel_map_superset ppa_channel_map_superset -#define pa_channel_position_to_string ppa_channel_position_to_string -#define pa_operation_get_state ppa_operation_get_state -#define pa_operation_unref ppa_operation_unref -#define pa_sample_spec_valid ppa_sample_spec_valid -#define pa_frame_size ppa_frame_size -#define pa_strerror ppa_strerror -#define pa_stream_get_state ppa_stream_get_state -#define pa_stream_peek ppa_stream_peek -#define pa_stream_write ppa_stream_write -#define pa_xfree ppa_xfree -#define pa_path_get_filename ppa_path_get_filename -#define pa_get_binary_name ppa_get_binary_name -#define pa_xmalloc ppa_xmalloc -#endif /* IN_IDE_PARSER */ - -#endif - - -constexpr pa_channel_map MonoChanMap{ - 1, {PA_CHANNEL_POSITION_MONO} -}, StereoChanMap{ - 2, {PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT} -}, QuadChanMap{ - 4, { - PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT, - PA_CHANNEL_POSITION_REAR_LEFT, PA_CHANNEL_POSITION_REAR_RIGHT - } -}, X51ChanMap{ - 6, { - PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT, - PA_CHANNEL_POSITION_FRONT_CENTER, PA_CHANNEL_POSITION_LFE, - PA_CHANNEL_POSITION_SIDE_LEFT, PA_CHANNEL_POSITION_SIDE_RIGHT - } -}, X51RearChanMap{ - 6, { - PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT, - PA_CHANNEL_POSITION_FRONT_CENTER, PA_CHANNEL_POSITION_LFE, - PA_CHANNEL_POSITION_REAR_LEFT, PA_CHANNEL_POSITION_REAR_RIGHT - } -}, X61ChanMap{ - 7, { - PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT, - PA_CHANNEL_POSITION_FRONT_CENTER, PA_CHANNEL_POSITION_LFE, - PA_CHANNEL_POSITION_REAR_CENTER, - PA_CHANNEL_POSITION_SIDE_LEFT, PA_CHANNEL_POSITION_SIDE_RIGHT - } -}, X71ChanMap{ - 8, { - PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT, - PA_CHANNEL_POSITION_FRONT_CENTER, PA_CHANNEL_POSITION_LFE, - PA_CHANNEL_POSITION_REAR_LEFT, PA_CHANNEL_POSITION_REAR_RIGHT, - PA_CHANNEL_POSITION_SIDE_LEFT, PA_CHANNEL_POSITION_SIDE_RIGHT - } -}; - -al::optional ChannelFromPulse(pa_channel_position_t chan) -{ - switch(chan) - { - case PA_CHANNEL_POSITION_INVALID: break; - case PA_CHANNEL_POSITION_MONO: return al::make_optional(FrontCenter); - case PA_CHANNEL_POSITION_FRONT_LEFT: return al::make_optional(FrontLeft); - case PA_CHANNEL_POSITION_FRONT_RIGHT: return al::make_optional(FrontRight); - case PA_CHANNEL_POSITION_FRONT_CENTER: return al::make_optional(FrontCenter); - case PA_CHANNEL_POSITION_REAR_CENTER: return al::make_optional(BackCenter); - case PA_CHANNEL_POSITION_REAR_LEFT: return al::make_optional(BackLeft); - case PA_CHANNEL_POSITION_REAR_RIGHT: return al::make_optional(BackRight); - case PA_CHANNEL_POSITION_LFE: return al::make_optional(LFE); - case PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER: break; - case PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER: break; - case PA_CHANNEL_POSITION_SIDE_LEFT: return al::make_optional(SideLeft); - case PA_CHANNEL_POSITION_SIDE_RIGHT: return al::make_optional(SideRight); - case PA_CHANNEL_POSITION_AUX0: break; - case PA_CHANNEL_POSITION_AUX1: break; - case PA_CHANNEL_POSITION_AUX2: break; - case PA_CHANNEL_POSITION_AUX3: break; - case PA_CHANNEL_POSITION_AUX4: break; - case PA_CHANNEL_POSITION_AUX5: break; - case PA_CHANNEL_POSITION_AUX6: break; - case PA_CHANNEL_POSITION_AUX7: break; - case PA_CHANNEL_POSITION_AUX8: break; - case PA_CHANNEL_POSITION_AUX9: break; - case PA_CHANNEL_POSITION_AUX10: break; - case PA_CHANNEL_POSITION_AUX11: break; - case PA_CHANNEL_POSITION_AUX12: break; - case PA_CHANNEL_POSITION_AUX13: break; - case PA_CHANNEL_POSITION_AUX14: break; - case PA_CHANNEL_POSITION_AUX15: break; - case PA_CHANNEL_POSITION_AUX16: break; - case PA_CHANNEL_POSITION_AUX17: break; - case PA_CHANNEL_POSITION_AUX18: break; - case PA_CHANNEL_POSITION_AUX19: break; - case PA_CHANNEL_POSITION_AUX20: break; - case PA_CHANNEL_POSITION_AUX21: break; - case PA_CHANNEL_POSITION_AUX22: break; - case PA_CHANNEL_POSITION_AUX23: break; - case PA_CHANNEL_POSITION_AUX24: break; - case PA_CHANNEL_POSITION_AUX25: break; - case PA_CHANNEL_POSITION_AUX26: break; - case PA_CHANNEL_POSITION_AUX27: break; - case PA_CHANNEL_POSITION_AUX28: break; - case PA_CHANNEL_POSITION_AUX29: break; - case PA_CHANNEL_POSITION_AUX30: break; - case PA_CHANNEL_POSITION_AUX31: break; - case PA_CHANNEL_POSITION_TOP_CENTER: return al::make_optional(TopCenter); - case PA_CHANNEL_POSITION_TOP_FRONT_LEFT: return al::make_optional(TopFrontLeft); - case PA_CHANNEL_POSITION_TOP_FRONT_RIGHT: return al::make_optional(TopFrontRight); - case PA_CHANNEL_POSITION_TOP_FRONT_CENTER: return al::make_optional(TopFrontCenter); - case PA_CHANNEL_POSITION_TOP_REAR_LEFT: return al::make_optional(TopBackLeft); - case PA_CHANNEL_POSITION_TOP_REAR_RIGHT: return al::make_optional(TopBackRight); - case PA_CHANNEL_POSITION_TOP_REAR_CENTER: return al::make_optional(TopBackCenter); - case PA_CHANNEL_POSITION_MAX: break; - } - WARN("Unexpected channel enum %d (%s)\n", chan, pa_channel_position_to_string(chan)); - return al::nullopt; -} - -void SetChannelOrderFromMap(ALCdevice *device, const pa_channel_map &chanmap) -{ - device->RealOut.ChannelIndex.fill(INVALID_CHANNEL_INDEX); - for(uint i{0};i < chanmap.channels;++i) - { - if(auto label = ChannelFromPulse(chanmap.map[i])) - device->RealOut.ChannelIndex[*label] = i; - } -} - - -/* *grumble* Don't use enums for bitflags. */ -constexpr inline pa_stream_flags_t operator|(pa_stream_flags_t lhs, pa_stream_flags_t rhs) -{ return pa_stream_flags_t(int(lhs) | int(rhs)); } -inline pa_stream_flags_t& operator|=(pa_stream_flags_t &lhs, pa_stream_flags_t rhs) -{ - lhs = lhs | rhs; - return lhs; -} -inline pa_stream_flags_t& operator&=(pa_stream_flags_t &lhs, int rhs) -{ - lhs = pa_stream_flags_t(int(lhs) & rhs); - return lhs; -} - -inline pa_context_flags_t& operator|=(pa_context_flags_t &lhs, pa_context_flags_t rhs) -{ - lhs = pa_context_flags_t(int(lhs) | int(rhs)); - return lhs; -} - - -struct DevMap { - std::string name; - std::string device_name; -}; - -bool checkName(const al::span list, const std::string &name) -{ - auto match_name = [&name](const DevMap &entry) -> bool { return entry.name == name; }; - return std::find_if(list.cbegin(), list.cend(), match_name) != list.cend(); -} - -al::vector PlaybackDevices; -al::vector CaptureDevices; - - -/* Global flags and properties */ -pa_context_flags_t pulse_ctx_flags; - -class PulseMainloop { - std::thread mThread; - std::mutex mMutex; - std::condition_variable mCondVar; - pa_mainloop *mMainloop{nullptr}; - - static int poll(struct pollfd *ufds, unsigned long nfds, int timeout, void *userdata) noexcept - { - auto plock = static_cast*>(userdata); - plock->unlock(); - int r{::poll(ufds, nfds, timeout)}; - plock->lock(); - return r; - } - - int mainloop_proc() - { - SetRTPriority(); - - std::unique_lock plock{mMutex}; - mMainloop = pa_mainloop_new(); - - pa_mainloop_set_poll_func(mMainloop, poll, &plock); - mCondVar.notify_all(); - - int ret{}; - pa_mainloop_run(mMainloop, &ret); - - pa_mainloop_free(mMainloop); - mMainloop = nullptr; - - return ret; - } - -public: - ~PulseMainloop() - { - if(mThread.joinable()) - { - { - std::lock_guard _{mMutex}; - pa_mainloop_quit(mMainloop, 0); - } - mThread.join(); - } - } - - std::unique_lock getUniqueLock() { return std::unique_lock{mMutex}; } - std::condition_variable &getCondVar() noexcept { return mCondVar; } - - void contextStateCallback(pa_context *context) noexcept - { - pa_context_state_t state{pa_context_get_state(context)}; - if(state == PA_CONTEXT_READY || !PA_CONTEXT_IS_GOOD(state)) - mCondVar.notify_all(); - } - static void contextStateCallbackC(pa_context *context, void *pdata) noexcept - { static_cast(pdata)->contextStateCallback(context); } - - void streamStateCallback(pa_stream *stream) noexcept - { - pa_stream_state_t state{pa_stream_get_state(stream)}; - if(state == PA_STREAM_READY || !PA_STREAM_IS_GOOD(state)) - mCondVar.notify_all(); - } - static void streamStateCallbackC(pa_stream *stream, void *pdata) noexcept - { static_cast(pdata)->streamStateCallback(stream); } - - void streamSuccessCallback(pa_stream*, int) noexcept - { mCondVar.notify_all(); } - static void streamSuccessCallbackC(pa_stream *stream, int success, void *pdata) noexcept - { static_cast(pdata)->streamSuccessCallback(stream, success); } - - void waitForOperation(pa_operation *op, std::unique_lock &plock) - { - if(op) - { - mCondVar.wait(plock, - [op]() -> bool { return pa_operation_get_state(op) != PA_OPERATION_RUNNING; }); - pa_operation_unref(op); - } - } - - pa_context *connectContext(std::unique_lock &plock); - - pa_stream *connectStream(const char *device_name, std::unique_lock &plock, - pa_context *context, pa_stream_flags_t flags, pa_buffer_attr *attr, pa_sample_spec *spec, - pa_channel_map *chanmap, BackendType type); - - void close(pa_context *context, pa_stream *stream); - - - void deviceSinkCallback(pa_context*, const pa_sink_info *info, int eol) noexcept - { - if(eol) - { - mCondVar.notify_all(); - return; - } - - /* Skip this device is if it's already in the list. */ - auto match_devname = [info](const DevMap &entry) -> bool - { return entry.device_name == info->name; }; - if(std::find_if(PlaybackDevices.cbegin(), PlaybackDevices.cend(), match_devname) != PlaybackDevices.cend()) - return; - - /* Make sure the display name (description) is unique. Append a number - * counter as needed. - */ - int count{1}; - std::string newname{info->description}; - while(checkName(PlaybackDevices, newname)) - { - newname = info->description; - newname += " #"; - newname += std::to_string(++count); - } - PlaybackDevices.emplace_back(DevMap{std::move(newname), info->name}); - DevMap &newentry = PlaybackDevices.back(); - - TRACE("Got device \"%s\", \"%s\"\n", newentry.name.c_str(), newentry.device_name.c_str()); - } - static void deviceSinkCallbackC(pa_context *context, const pa_sink_info *info, int eol, void *pdata) noexcept - { static_cast(pdata)->deviceSinkCallback(context, info, eol); } - - void deviceSourceCallback(pa_context*, const pa_source_info *info, int eol) noexcept - { - if(eol) - { - mCondVar.notify_all(); - return; - } - - /* Skip this device is if it's already in the list. */ - auto match_devname = [info](const DevMap &entry) -> bool - { return entry.device_name == info->name; }; - if(std::find_if(CaptureDevices.cbegin(), CaptureDevices.cend(), match_devname) != CaptureDevices.cend()) - return; - - /* Make sure the display name (description) is unique. Append a number - * counter as needed. - */ - int count{1}; - std::string newname{info->description}; - while(checkName(CaptureDevices, newname)) - { - newname = info->description; - newname += " #"; - newname += std::to_string(++count); - } - CaptureDevices.emplace_back(DevMap{std::move(newname), info->name}); - DevMap &newentry = CaptureDevices.back(); - - TRACE("Got device \"%s\", \"%s\"\n", newentry.name.c_str(), newentry.device_name.c_str()); - } - static void deviceSourceCallbackC(pa_context *context, const pa_source_info *info, int eol, void *pdata) noexcept - { static_cast(pdata)->deviceSourceCallback(context, info, eol); } - - void probePlaybackDevices(); - void probeCaptureDevices(); -}; - - -pa_context *PulseMainloop::connectContext(std::unique_lock &plock) -{ - const char *name{"OpenAL Soft"}; - - const PathNamePair &binname = GetProcBinary(); - if(!binname.fname.empty()) - name = binname.fname.c_str(); - - if(!mMainloop) - { - mThread = std::thread{std::mem_fn(&PulseMainloop::mainloop_proc), this}; - mCondVar.wait(plock, [this]() noexcept { return mMainloop; }); - } - - pa_context *context{pa_context_new(pa_mainloop_get_api(mMainloop), name)}; - if(!context) throw al::backend_exception{al::backend_error::OutOfMemory, - "pa_context_new() failed"}; - - pa_context_set_state_callback(context, &contextStateCallbackC, this); - - int err; - if((err=pa_context_connect(context, nullptr, pulse_ctx_flags, nullptr)) >= 0) - { - pa_context_state_t state; - while((state=pa_context_get_state(context)) != PA_CONTEXT_READY) - { - if(!PA_CONTEXT_IS_GOOD(state)) - { - err = pa_context_errno(context); - if(err > 0) err = -err; - break; - } - - mCondVar.wait(plock); - } - } - pa_context_set_state_callback(context, nullptr, nullptr); - - if(err < 0) - { - pa_context_unref(context); - throw al::backend_exception{al::backend_error::DeviceError, "Context did not connect (%s)", - pa_strerror(err)}; - } - - return context; -} - -pa_stream *PulseMainloop::connectStream(const char *device_name, - std::unique_lock &plock, pa_context *context, pa_stream_flags_t flags, - pa_buffer_attr *attr, pa_sample_spec *spec, pa_channel_map *chanmap, BackendType type) -{ - const char *stream_id{(type==BackendType::Playback) ? "Playback Stream" : "Capture Stream"}; - pa_stream *stream{pa_stream_new(context, stream_id, spec, chanmap)}; - if(!stream) - throw al::backend_exception{al::backend_error::OutOfMemory, "pa_stream_new() failed (%s)", - pa_strerror(pa_context_errno(context))}; - - pa_stream_set_state_callback(stream, &streamStateCallbackC, this); - - int err{(type==BackendType::Playback) ? - pa_stream_connect_playback(stream, device_name, attr, flags, nullptr, nullptr) : - pa_stream_connect_record(stream, device_name, attr, flags)}; - if(err < 0) - { - pa_stream_unref(stream); - throw al::backend_exception{al::backend_error::DeviceError, "%s did not connect (%s)", - stream_id, pa_strerror(err)}; - } - - pa_stream_state_t state; - while((state=pa_stream_get_state(stream)) != PA_STREAM_READY) - { - if(!PA_STREAM_IS_GOOD(state)) - { - err = pa_context_errno(context); - pa_stream_unref(stream); - throw al::backend_exception{al::backend_error::DeviceError, - "%s did not get ready (%s)", stream_id, pa_strerror(err)}; - } - - mCondVar.wait(plock); - } - pa_stream_set_state_callback(stream, nullptr, nullptr); - - return stream; -} - -void PulseMainloop::close(pa_context *context, pa_stream *stream) -{ - std::lock_guard _{mMutex}; - if(stream) - { - pa_stream_set_state_callback(stream, nullptr, nullptr); - pa_stream_set_moved_callback(stream, nullptr, nullptr); - pa_stream_set_write_callback(stream, nullptr, nullptr); - pa_stream_set_buffer_attr_callback(stream, nullptr, nullptr); - pa_stream_disconnect(stream); - pa_stream_unref(stream); - } - - pa_context_disconnect(context); - pa_context_unref(context); -} - - -void PulseMainloop::probePlaybackDevices() -{ - pa_context *context{}; - pa_stream *stream{}; - - PlaybackDevices.clear(); - try { - std::unique_lock plock{mMutex}; - - context = connectContext(plock); - pa_operation *op{pa_context_get_sink_info_by_name(context, nullptr, - &deviceSinkCallbackC, this)}; - waitForOperation(op, plock); - - op = pa_context_get_sink_info_list(context, &deviceSinkCallbackC, this); - waitForOperation(op, plock); - - pa_context_disconnect(context); - pa_context_unref(context); - context = nullptr; - } - catch(std::exception &e) { - ERR("Error enumerating devices: %s\n", e.what()); - if(context) close(context, stream); - } -} - -void PulseMainloop::probeCaptureDevices() -{ - pa_context *context{}; - pa_stream *stream{}; - - CaptureDevices.clear(); - try { - std::unique_lock plock{mMutex}; - - context = connectContext(plock); - pa_operation *op{pa_context_get_source_info_by_name(context, nullptr, - &deviceSourceCallbackC, this)}; - waitForOperation(op, plock); - - op = pa_context_get_source_info_list(context, &deviceSourceCallbackC, this); - waitForOperation(op, plock); - - pa_context_disconnect(context); - pa_context_unref(context); - context = nullptr; - } - catch(std::exception &e) { - ERR("Error enumerating devices: %s\n", e.what()); - if(context) close(context, stream); - } -} - - -/* Used for initial connection test and enumeration. */ -PulseMainloop gGlobalMainloop; - - -struct PulsePlayback final : public BackendBase { - PulsePlayback(ALCdevice *device) noexcept : BackendBase{device} { } - ~PulsePlayback() override; - - void bufferAttrCallback(pa_stream *stream) noexcept; - static void bufferAttrCallbackC(pa_stream *stream, void *pdata) noexcept - { static_cast(pdata)->bufferAttrCallback(stream); } - - void streamStateCallback(pa_stream *stream) noexcept; - static void streamStateCallbackC(pa_stream *stream, void *pdata) noexcept - { static_cast(pdata)->streamStateCallback(stream); } - - void streamWriteCallback(pa_stream *stream, size_t nbytes) noexcept; - static void streamWriteCallbackC(pa_stream *stream, size_t nbytes, void *pdata) noexcept - { static_cast(pdata)->streamWriteCallback(stream, nbytes); } - - void sinkInfoCallback(pa_context *context, const pa_sink_info *info, int eol) noexcept; - static void sinkInfoCallbackC(pa_context *context, const pa_sink_info *info, int eol, void *pdata) noexcept - { static_cast(pdata)->sinkInfoCallback(context, info, eol); } - - void sinkNameCallback(pa_context *context, const pa_sink_info *info, int eol) noexcept; - static void sinkNameCallbackC(pa_context *context, const pa_sink_info *info, int eol, void *pdata) noexcept - { static_cast(pdata)->sinkNameCallback(context, info, eol); } - - void streamMovedCallback(pa_stream *stream) noexcept; - static void streamMovedCallbackC(pa_stream *stream, void *pdata) noexcept - { static_cast(pdata)->streamMovedCallback(stream); } - - void open(const char *name) override; - bool reset() override; - void start() override; - void stop() override; - ClockLatency getClockLatency() override; - - PulseMainloop mMainloop; - - al::optional mDeviceName{al::nullopt}; - - pa_buffer_attr mAttr; - pa_sample_spec mSpec; - - pa_stream *mStream{nullptr}; - pa_context *mContext{nullptr}; - - uint mFrameSize{0u}; - - DEF_NEWDEL(PulsePlayback) -}; - -PulsePlayback::~PulsePlayback() -{ - if(!mContext) - return; - - mMainloop.close(mContext, mStream); - mContext = nullptr; - mStream = nullptr; -} - - -void PulsePlayback::bufferAttrCallback(pa_stream *stream) noexcept -{ - /* FIXME: Update the device's UpdateSize (and/or BufferSize) using the new - * buffer attributes? Changing UpdateSize will change the ALC_REFRESH - * property, which probably shouldn't change between device resets. But - * leaving it alone means ALC_REFRESH will be off. - */ - mAttr = *(pa_stream_get_buffer_attr(stream)); - TRACE("minreq=%d, tlength=%d, prebuf=%d\n", mAttr.minreq, mAttr.tlength, mAttr.prebuf); -} - -void PulsePlayback::streamStateCallback(pa_stream *stream) noexcept -{ - if(pa_stream_get_state(stream) == PA_STREAM_FAILED) - { - ERR("Received stream failure!\n"); - mDevice->handleDisconnect("Playback stream failure"); - } - mMainloop.getCondVar().notify_all(); -} - -void PulsePlayback::streamWriteCallback(pa_stream *stream, size_t nbytes) noexcept -{ - do { - pa_free_cb_t free_func{nullptr}; - auto buflen = static_cast(-1); - void *buf; - if UNLIKELY(pa_stream_begin_write(stream, &buf, &buflen) || !buf) - { - buflen = nbytes; - buf = pa_xmalloc(buflen); - free_func = pa_xfree; - } - else - buflen = minz(buflen, nbytes); - nbytes -= buflen; - - mDevice->renderSamples(buf, static_cast(buflen/mFrameSize), mSpec.channels); - - int ret{pa_stream_write(stream, buf, buflen, free_func, 0, PA_SEEK_RELATIVE)}; - if UNLIKELY(ret != PA_OK) - ERR("Failed to write to stream: %d, %s\n", ret, pa_strerror(ret)); - } while(nbytes > 0); -} - -void PulsePlayback::sinkInfoCallback(pa_context*, const pa_sink_info *info, int eol) noexcept -{ - struct ChannelMap { - DevFmtChannels fmt; - pa_channel_map map; - }; - static constexpr std::array chanmaps{{ - { DevFmtX71, X71ChanMap }, - { DevFmtX61, X61ChanMap }, - { DevFmtX51, X51ChanMap }, - { DevFmtX51Rear, X51RearChanMap }, - { DevFmtQuad, QuadChanMap }, - { DevFmtStereo, StereoChanMap }, - { DevFmtMono, MonoChanMap } - }}; - - if(eol) - { - mMainloop.getCondVar().notify_all(); - return; - } - - auto chaniter = std::find_if(chanmaps.cbegin(), chanmaps.cend(), - [info](const ChannelMap &chanmap) -> bool - { return pa_channel_map_superset(&info->channel_map, &chanmap.map); } - ); - if(chaniter != chanmaps.cend()) - { - if(!mDevice->Flags.test(ChannelsRequest)) - mDevice->FmtChans = chaniter->fmt; - } - else - { - char chanmap_str[PA_CHANNEL_MAP_SNPRINT_MAX]{}; - pa_channel_map_snprint(chanmap_str, sizeof(chanmap_str), &info->channel_map); - WARN("Failed to find format for channel map:\n %s\n", chanmap_str); - } - - if(info->active_port) - TRACE("Active port: %s (%s)\n", info->active_port->name, info->active_port->description); - mDevice->IsHeadphones = (mDevice->FmtChans == DevFmtStereo - && info->active_port && strcmp(info->active_port->name, "analog-output-headphones") == 0); -} - -void PulsePlayback::sinkNameCallback(pa_context*, const pa_sink_info *info, int eol) noexcept -{ - if(eol) - { - mMainloop.getCondVar().notify_all(); - return; - } - mDevice->DeviceName = info->description; -} - -void PulsePlayback::streamMovedCallback(pa_stream *stream) noexcept -{ - mDeviceName = pa_stream_get_device_name(stream); - TRACE("Stream moved to %s\n", mDeviceName->c_str()); -} - - -void PulsePlayback::open(const char *name) -{ - const char *pulse_name{nullptr}; - const char *dev_name{nullptr}; - - if(name) - { - if(PlaybackDevices.empty()) - mMainloop.probePlaybackDevices(); - - auto iter = std::find_if(PlaybackDevices.cbegin(), PlaybackDevices.cend(), - [name](const DevMap &entry) -> bool { return entry.name == name; }); - if(iter == PlaybackDevices.cend()) - throw al::backend_exception{al::backend_error::NoDevice, - "Device name \"%s\" not found", name}; - pulse_name = iter->device_name.c_str(); - dev_name = iter->name.c_str(); - } - - auto plock = mMainloop.getUniqueLock(); - mContext = mMainloop.connectContext(plock); - - pa_stream_flags_t flags{PA_STREAM_START_CORKED | PA_STREAM_FIX_FORMAT | PA_STREAM_FIX_RATE | - PA_STREAM_FIX_CHANNELS}; - if(!GetConfigValueBool(nullptr, "pulse", "allow-moves", 1)) - flags |= PA_STREAM_DONT_MOVE; - - pa_sample_spec spec{}; - spec.format = PA_SAMPLE_S16NE; - spec.rate = 44100; - spec.channels = 2; - - if(!pulse_name) - { - static const auto defname = al::getenv("ALSOFT_PULSE_DEFAULT"); - if(defname) pulse_name = defname->c_str(); - } - TRACE("Connecting to \"%s\"\n", pulse_name ? pulse_name : "(default)"); - mStream = mMainloop.connectStream(pulse_name, plock, mContext, flags, nullptr, &spec, nullptr, - BackendType::Playback); - - pa_stream_set_moved_callback(mStream, &PulsePlayback::streamMovedCallbackC, this); - mFrameSize = static_cast(pa_frame_size(pa_stream_get_sample_spec(mStream))); - - mDeviceName = pulse_name ? al::make_optional(pulse_name) : al::nullopt; - if(!dev_name) - { - pa_operation *op{pa_context_get_sink_info_by_name(mContext, - pa_stream_get_device_name(mStream), &PulsePlayback::sinkNameCallbackC, this)}; - mMainloop.waitForOperation(op, plock); - } - else - mDevice->DeviceName = dev_name; -} - -bool PulsePlayback::reset() -{ - auto plock = mMainloop.getUniqueLock(); - const auto deviceName = mDeviceName ? mDeviceName->c_str() : nullptr; - - if(mStream) - { - pa_stream_set_state_callback(mStream, nullptr, nullptr); - pa_stream_set_moved_callback(mStream, nullptr, nullptr); - pa_stream_set_write_callback(mStream, nullptr, nullptr); - pa_stream_set_buffer_attr_callback(mStream, nullptr, nullptr); - pa_stream_disconnect(mStream); - pa_stream_unref(mStream); - mStream = nullptr; - } - - pa_operation *op{pa_context_get_sink_info_by_name(mContext, deviceName, - &PulsePlayback::sinkInfoCallbackC, this)}; - mMainloop.waitForOperation(op, plock); - - pa_stream_flags_t flags{PA_STREAM_START_CORKED | PA_STREAM_INTERPOLATE_TIMING | - PA_STREAM_AUTO_TIMING_UPDATE | PA_STREAM_EARLY_REQUESTS}; - if(!GetConfigValueBool(nullptr, "pulse", "allow-moves", 1)) - flags |= PA_STREAM_DONT_MOVE; - if(GetConfigValueBool(mDevice->DeviceName.c_str(), "pulse", "adjust-latency", 0)) - { - /* ADJUST_LATENCY can't be specified with EARLY_REQUESTS, for some - * reason. So if the user wants to adjust the overall device latency, - * we can't ask to get write signals as soon as minreq is reached. - */ - flags &= ~PA_STREAM_EARLY_REQUESTS; - flags |= PA_STREAM_ADJUST_LATENCY; - } - if(GetConfigValueBool(mDevice->DeviceName.c_str(), "pulse", "fix-rate", 0) - || !mDevice->Flags.test(FrequencyRequest)) - flags |= PA_STREAM_FIX_RATE; - - pa_channel_map chanmap{}; - switch(mDevice->FmtChans) - { - case DevFmtMono: - chanmap = MonoChanMap; - break; - case DevFmtAmbi3D: - mDevice->FmtChans = DevFmtStereo; - /*fall-through*/ - case DevFmtStereo: - chanmap = StereoChanMap; - break; - case DevFmtQuad: - chanmap = QuadChanMap; - break; - case DevFmtX51: - chanmap = X51ChanMap; - break; - case DevFmtX51Rear: - chanmap = X51RearChanMap; - break; - case DevFmtX61: - chanmap = X61ChanMap; - break; - case DevFmtX71: - chanmap = X71ChanMap; - break; - } - SetChannelOrderFromMap(mDevice, chanmap); - - switch(mDevice->FmtType) - { - case DevFmtByte: - mDevice->FmtType = DevFmtUByte; - /* fall-through */ - case DevFmtUByte: - mSpec.format = PA_SAMPLE_U8; - break; - case DevFmtUShort: - mDevice->FmtType = DevFmtShort; - /* fall-through */ - case DevFmtShort: - mSpec.format = PA_SAMPLE_S16NE; - break; - case DevFmtUInt: - mDevice->FmtType = DevFmtInt; - /* fall-through */ - case DevFmtInt: - mSpec.format = PA_SAMPLE_S32NE; - break; - case DevFmtFloat: - mSpec.format = PA_SAMPLE_FLOAT32NE; - break; - } - mSpec.rate = mDevice->Frequency; - mSpec.channels = static_cast(mDevice->channelsFromFmt()); - if(pa_sample_spec_valid(&mSpec) == 0) - throw al::backend_exception{al::backend_error::DeviceError, "Invalid sample spec"}; - - const auto frame_size = static_cast(pa_frame_size(&mSpec)); - mAttr.maxlength = ~0u; - mAttr.tlength = mDevice->BufferSize * frame_size; - mAttr.prebuf = 0u; - mAttr.minreq = mDevice->UpdateSize * frame_size; - mAttr.fragsize = ~0u; - - mStream = mMainloop.connectStream(deviceName, plock, mContext, flags, &mAttr, &mSpec, - &chanmap, BackendType::Playback); - - pa_stream_set_state_callback(mStream, &PulsePlayback::streamStateCallbackC, this); - pa_stream_set_moved_callback(mStream, &PulsePlayback::streamMovedCallbackC, this); - - mSpec = *(pa_stream_get_sample_spec(mStream)); - mFrameSize = static_cast(pa_frame_size(&mSpec)); - - if(mDevice->Frequency != mSpec.rate) - { - /* Server updated our playback rate, so modify the buffer attribs - * accordingly. - */ - const auto scale = static_cast(mSpec.rate) / mDevice->Frequency; - const auto perlen = static_cast(clampd(scale*mDevice->UpdateSize + 0.5, 64.0, - 8192.0)); - const auto buflen = static_cast(clampd(scale*mDevice->BufferSize + 0.5, perlen*2, - std::numeric_limits::max()/mFrameSize)); - - mAttr.maxlength = ~0u; - mAttr.tlength = buflen * mFrameSize; - mAttr.prebuf = 0u; - mAttr.minreq = perlen * mFrameSize; - - op = pa_stream_set_buffer_attr(mStream, &mAttr, &PulseMainloop::streamSuccessCallbackC, - &mMainloop); - mMainloop.waitForOperation(op, plock); - - mDevice->Frequency = mSpec.rate; - } - - pa_stream_set_buffer_attr_callback(mStream, &PulsePlayback::bufferAttrCallbackC, this); - bufferAttrCallback(mStream); - - mDevice->BufferSize = mAttr.tlength / mFrameSize; - mDevice->UpdateSize = mAttr.minreq / mFrameSize; - - return true; -} - -void PulsePlayback::start() -{ - auto plock = mMainloop.getUniqueLock(); - - pa_stream_set_write_callback(mStream, &PulsePlayback::streamWriteCallbackC, this); - pa_operation *op{pa_stream_cork(mStream, 0, &PulseMainloop::streamSuccessCallbackC, - &mMainloop)}; - - /* Write some (silent) samples to fill the prebuf amount if needed. */ - if(size_t prebuf{mAttr.prebuf}) - { - prebuf = minz(prebuf, pa_stream_writable_size(mStream)); - - void *buf{pa_xmalloc(prebuf)}; - switch(mSpec.format) - { - case PA_SAMPLE_U8: - std::fill_n(static_cast(buf), prebuf, 0x80); - break; - case PA_SAMPLE_ALAW: - std::fill_n(static_cast(buf), prebuf, 0xD5); - break; - case PA_SAMPLE_ULAW: - std::fill_n(static_cast(buf), prebuf, 0x7f); - break; - default: - std::fill_n(static_cast(buf), prebuf, 0x00); - break; - } - pa_stream_write(mStream, buf, prebuf, pa_xfree, 0, PA_SEEK_RELATIVE); - } - - mMainloop.waitForOperation(op, plock); -} - -void PulsePlayback::stop() -{ - auto plock = mMainloop.getUniqueLock(); - - pa_operation *op{pa_stream_cork(mStream, 1, &PulseMainloop::streamSuccessCallbackC, - &mMainloop)}; - mMainloop.waitForOperation(op, plock); - pa_stream_set_write_callback(mStream, nullptr, nullptr); -} - - -ClockLatency PulsePlayback::getClockLatency() -{ - ClockLatency ret; - pa_usec_t latency; - int neg, err; - - { - auto plock = mMainloop.getUniqueLock(); - ret.ClockTime = GetDeviceClockTime(mDevice); - err = pa_stream_get_latency(mStream, &latency, &neg); - } - - if UNLIKELY(err != 0) - { - /* If err = -PA_ERR_NODATA, it means we were called too soon after - * starting the stream and no timing info has been received from the - * server yet. Give a generic value since nothing better is available. - */ - if(err != -PA_ERR_NODATA) - ERR("Failed to get stream latency: 0x%x\n", err); - latency = mDevice->BufferSize - mDevice->UpdateSize; - neg = 0; - } - else if UNLIKELY(neg) - latency = 0; - ret.Latency = std::chrono::microseconds{latency}; - - return ret; -} - - -struct PulseCapture final : public BackendBase { - PulseCapture(ALCdevice *device) noexcept : BackendBase{device} { } - ~PulseCapture() override; - - void streamStateCallback(pa_stream *stream) noexcept; - static void streamStateCallbackC(pa_stream *stream, void *pdata) noexcept - { static_cast(pdata)->streamStateCallback(stream); } - - void sourceNameCallback(pa_context *context, const pa_source_info *info, int eol) noexcept; - static void sourceNameCallbackC(pa_context *context, const pa_source_info *info, int eol, void *pdata) noexcept - { static_cast(pdata)->sourceNameCallback(context, info, eol); } - - void streamMovedCallback(pa_stream *stream) noexcept; - static void streamMovedCallbackC(pa_stream *stream, void *pdata) noexcept - { static_cast(pdata)->streamMovedCallback(stream); } - - void open(const char *name) override; - void start() override; - void stop() override; - void captureSamples(al::byte *buffer, uint samples) override; - uint availableSamples() override; - ClockLatency getClockLatency() override; - - PulseMainloop mMainloop; - - al::optional mDeviceName{al::nullopt}; - - uint mLastReadable{0u}; - al::byte mSilentVal{}; - - al::span mCapBuffer; - ssize_t mCapLen{0}; - - pa_buffer_attr mAttr{}; - pa_sample_spec mSpec{}; - - pa_stream *mStream{nullptr}; - pa_context *mContext{nullptr}; - - DEF_NEWDEL(PulseCapture) -}; - -PulseCapture::~PulseCapture() -{ - if(!mContext) - return; - - mMainloop.close(mContext, mStream); - mContext = nullptr; - mStream = nullptr; -} - - -void PulseCapture::streamStateCallback(pa_stream *stream) noexcept -{ - if(pa_stream_get_state(stream) == PA_STREAM_FAILED) - { - ERR("Received stream failure!\n"); - mDevice->handleDisconnect("Capture stream failure"); - } - mMainloop.getCondVar().notify_all(); -} - -void PulseCapture::sourceNameCallback(pa_context*, const pa_source_info *info, int eol) noexcept -{ - if(eol) - { - mMainloop.getCondVar().notify_all(); - return; - } - mDevice->DeviceName = info->description; -} - -void PulseCapture::streamMovedCallback(pa_stream *stream) noexcept -{ - mDeviceName = pa_stream_get_device_name(stream); - TRACE("Stream moved to %s\n", mDeviceName->c_str()); -} - - -void PulseCapture::open(const char *name) -{ - const char *pulse_name{nullptr}; - if(name) - { - if(CaptureDevices.empty()) - mMainloop.probeCaptureDevices(); - - auto iter = std::find_if(CaptureDevices.cbegin(), CaptureDevices.cend(), - [name](const DevMap &entry) -> bool { return entry.name == name; }); - if(iter == CaptureDevices.cend()) - throw al::backend_exception{al::backend_error::NoDevice, - "Device name \"%s\" not found", name}; - pulse_name = iter->device_name.c_str(); - mDevice->DeviceName = iter->name; - } - - auto plock = mMainloop.getUniqueLock(); - mContext = mMainloop.connectContext(plock); - - pa_channel_map chanmap{}; - switch(mDevice->FmtChans) - { - case DevFmtMono: - chanmap = MonoChanMap; - break; - case DevFmtStereo: - chanmap = StereoChanMap; - break; - case DevFmtQuad: - chanmap = QuadChanMap; - break; - case DevFmtX51: - chanmap = X51ChanMap; - break; - case DevFmtX51Rear: - chanmap = X51RearChanMap; - break; - case DevFmtX61: - chanmap = X61ChanMap; - break; - case DevFmtX71: - chanmap = X71ChanMap; - break; - case DevFmtAmbi3D: - throw al::backend_exception{al::backend_error::DeviceError, "%s capture not supported", - DevFmtChannelsString(mDevice->FmtChans)}; - } - SetChannelOrderFromMap(mDevice, chanmap); - - switch(mDevice->FmtType) - { - case DevFmtUByte: - mSilentVal = al::byte(0x80); - mSpec.format = PA_SAMPLE_U8; - break; - case DevFmtShort: - mSpec.format = PA_SAMPLE_S16NE; - break; - case DevFmtInt: - mSpec.format = PA_SAMPLE_S32NE; - break; - case DevFmtFloat: - mSpec.format = PA_SAMPLE_FLOAT32NE; - break; - case DevFmtByte: - case DevFmtUShort: - case DevFmtUInt: - throw al::backend_exception{al::backend_error::DeviceError, - "%s capture samples not supported", DevFmtTypeString(mDevice->FmtType)}; - } - mSpec.rate = mDevice->Frequency; - mSpec.channels = static_cast(mDevice->channelsFromFmt()); - if(pa_sample_spec_valid(&mSpec) == 0) - throw al::backend_exception{al::backend_error::DeviceError, "Invalid sample format"}; - - const auto frame_size = static_cast(pa_frame_size(&mSpec)); - const uint samples{maxu(mDevice->BufferSize, 100 * mDevice->Frequency / 1000)}; - mAttr.minreq = ~0u; - mAttr.prebuf = ~0u; - mAttr.maxlength = samples * frame_size; - mAttr.tlength = ~0u; - mAttr.fragsize = minu(samples, 50*mDevice->Frequency/1000) * frame_size; - - pa_stream_flags_t flags{PA_STREAM_START_CORKED | PA_STREAM_ADJUST_LATENCY}; - if(!GetConfigValueBool(nullptr, "pulse", "allow-moves", 1)) - flags |= PA_STREAM_DONT_MOVE; - - TRACE("Connecting to \"%s\"\n", pulse_name ? pulse_name : "(default)"); - mStream = mMainloop.connectStream(pulse_name, plock, mContext, flags, &mAttr, &mSpec, &chanmap, - BackendType::Capture); - - pa_stream_set_moved_callback(mStream, &PulseCapture::streamMovedCallbackC, this); - pa_stream_set_state_callback(mStream, &PulseCapture::streamStateCallbackC, this); - - mDeviceName = pulse_name ? al::make_optional(pulse_name) : al::nullopt; - if(mDevice->DeviceName.empty()) - { - pa_operation *op{pa_context_get_source_info_by_name(mContext, - pa_stream_get_device_name(mStream), &PulseCapture::sourceNameCallbackC, this)}; - mMainloop.waitForOperation(op, plock); - } -} - -void PulseCapture::start() -{ - auto plock = mMainloop.getUniqueLock(); - pa_operation *op{pa_stream_cork(mStream, 0, &PulseMainloop::streamSuccessCallbackC, - &mMainloop)}; - mMainloop.waitForOperation(op, plock); -} - -void PulseCapture::stop() -{ - auto plock = mMainloop.getUniqueLock(); - pa_operation *op{pa_stream_cork(mStream, 1, &PulseMainloop::streamSuccessCallbackC, - &mMainloop)}; - mMainloop.waitForOperation(op, plock); -} - -void PulseCapture::captureSamples(al::byte *buffer, uint samples) -{ - al::span dstbuf{buffer, samples * pa_frame_size(&mSpec)}; - - /* Capture is done in fragment-sized chunks, so we loop until we get all - * that's available */ - mLastReadable -= static_cast(dstbuf.size()); - while(!dstbuf.empty()) - { - if(!mCapBuffer.empty()) - { - const size_t rem{minz(dstbuf.size(), mCapBuffer.size())}; - if UNLIKELY(mCapLen < 0) - std::fill_n(dstbuf.begin(), rem, mSilentVal); - else - std::copy_n(mCapBuffer.begin(), rem, dstbuf.begin()); - dstbuf = dstbuf.subspan(rem); - mCapBuffer = mCapBuffer.subspan(rem); - - continue; - } - - if UNLIKELY(!mDevice->Connected.load(std::memory_order_acquire)) - break; - - auto plock = mMainloop.getUniqueLock(); - if(mCapLen != 0) - { - pa_stream_drop(mStream); - mCapBuffer = {}; - mCapLen = 0; - } - const pa_stream_state_t state{pa_stream_get_state(mStream)}; - if UNLIKELY(!PA_STREAM_IS_GOOD(state)) - { - mDevice->handleDisconnect("Bad capture state: %u", state); - break; - } - const void *capbuf; - size_t caplen; - if UNLIKELY(pa_stream_peek(mStream, &capbuf, &caplen) < 0) - { - mDevice->handleDisconnect("Failed retrieving capture samples: %s", - pa_strerror(pa_context_errno(mContext))); - break; - } - plock.unlock(); - - if(caplen == 0) break; - if UNLIKELY(!capbuf) - mCapLen = -static_cast(caplen); - else - mCapLen = static_cast(caplen); - mCapBuffer = {static_cast(capbuf), caplen}; - } - if(!dstbuf.empty()) - std::fill(dstbuf.begin(), dstbuf.end(), mSilentVal); -} - -uint PulseCapture::availableSamples() -{ - size_t readable{mCapBuffer.size()}; - - if(mDevice->Connected.load(std::memory_order_acquire)) - { - auto plock = mMainloop.getUniqueLock(); - size_t got{pa_stream_readable_size(mStream)}; - if UNLIKELY(static_cast(got) < 0) - { - const char *err{pa_strerror(static_cast(got))}; - ERR("pa_stream_readable_size() failed: %s\n", err); - mDevice->handleDisconnect("Failed getting readable size: %s", err); - } - else - { - const auto caplen = static_cast(std::abs(mCapLen)); - if(got > caplen) readable += got - caplen; - } - } - - readable = std::min(readable, std::numeric_limits::max()); - mLastReadable = std::max(mLastReadable, static_cast(readable)); - return mLastReadable / static_cast(pa_frame_size(&mSpec)); -} - - -ClockLatency PulseCapture::getClockLatency() -{ - ClockLatency ret; - pa_usec_t latency; - int neg, err; - - { - auto plock = mMainloop.getUniqueLock(); - ret.ClockTime = GetDeviceClockTime(mDevice); - err = pa_stream_get_latency(mStream, &latency, &neg); - } - - if UNLIKELY(err != 0) - { - ERR("Failed to get stream latency: 0x%x\n", err); - latency = 0; - neg = 0; - } - else if UNLIKELY(neg) - latency = 0; - ret.Latency = std::chrono::microseconds{latency}; - - return ret; -} - -} // namespace - - -bool PulseBackendFactory::init() -{ -#ifdef HAVE_DYNLOAD - if(!pulse_handle) - { - bool ret{true}; - std::string missing_funcs; - -#ifdef _WIN32 -#define PALIB "libpulse-0.dll" -#elif defined(__APPLE__) && defined(__MACH__) -#define PALIB "libpulse.0.dylib" -#else -#define PALIB "libpulse.so.0" -#endif - pulse_handle = LoadLib(PALIB); - if(!pulse_handle) - { - WARN("Failed to load %s\n", PALIB); - return false; - } - -#define LOAD_FUNC(x) do { \ - p##x = reinterpret_cast(GetSymbol(pulse_handle, #x)); \ - if(!(p##x)) { \ - ret = false; \ - missing_funcs += "\n" #x; \ - } \ -} while(0) - PULSE_FUNCS(LOAD_FUNC) -#undef LOAD_FUNC - - if(!ret) - { - WARN("Missing expected functions:%s\n", missing_funcs.c_str()); - CloseLib(pulse_handle); - pulse_handle = nullptr; - return false; - } - } -#endif /* HAVE_DYNLOAD */ - - pulse_ctx_flags = PA_CONTEXT_NOFLAGS; - if(!GetConfigValueBool(nullptr, "pulse", "spawn-server", 1)) - pulse_ctx_flags |= PA_CONTEXT_NOAUTOSPAWN; - - try { - auto plock = gGlobalMainloop.getUniqueLock(); - pa_context *context{gGlobalMainloop.connectContext(plock)}; - pa_context_disconnect(context); - pa_context_unref(context); - return true; - } - catch(...) { - return false; - } -} - -bool PulseBackendFactory::querySupport(BackendType type) -{ return type == BackendType::Playback || type == BackendType::Capture; } - -std::string PulseBackendFactory::probe(BackendType type) -{ - std::string outnames; - - auto add_device = [&outnames](const DevMap &entry) -> void - { - /* +1 to also append the null char (to ensure a null-separated list and - * double-null terminated list). - */ - outnames.append(entry.name.c_str(), entry.name.length()+1); - }; - - switch(type) - { - case BackendType::Playback: - gGlobalMainloop.probePlaybackDevices(); - std::for_each(PlaybackDevices.cbegin(), PlaybackDevices.cend(), add_device); - break; - - case BackendType::Capture: - gGlobalMainloop.probeCaptureDevices(); - std::for_each(CaptureDevices.cbegin(), CaptureDevices.cend(), add_device); - break; - } - - return outnames; -} - -BackendPtr PulseBackendFactory::createBackend(ALCdevice *device, BackendType type) -{ - if(type == BackendType::Playback) - return BackendPtr{new PulsePlayback{device}}; - if(type == BackendType::Capture) - return BackendPtr{new PulseCapture{device}}; - return nullptr; -} - -BackendFactory &PulseBackendFactory::getFactory() -{ - static PulseBackendFactory factory{}; - return factory; -} diff --git a/alc/backends/pulseaudio.h b/alc/backends/pulseaudio.h deleted file mode 100644 index 86b81502..00000000 --- a/alc/backends/pulseaudio.h +++ /dev/null @@ -1,19 +0,0 @@ -#ifndef BACKENDS_PULSEAUDIO_H -#define BACKENDS_PULSEAUDIO_H - -#include "backends/base.h" - -class PulseBackendFactory final : public BackendFactory { -public: - bool init() override; - - bool querySupport(BackendType type) override; - - std::string probe(BackendType type) override; - - BackendPtr createBackend(ALCdevice *device, BackendType type) override; - - static BackendFactory &getFactory(); -}; - -#endif /* BACKENDS_PULSEAUDIO_H */ diff --git a/alc/backends/sdl2.cpp b/alc/backends/sdl2.cpp deleted file mode 100644 index 084b51c0..00000000 --- a/alc/backends/sdl2.cpp +++ /dev/null @@ -1,216 +0,0 @@ -/** - * OpenAL cross platform audio library - * Copyright (C) 2018 by authors. - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - * Or go to http://www.gnu.org/copyleft/lgpl.html - */ - -#include "config.h" - -#include "backends/sdl2.h" - -#include -#include -#include -#include - -#include "alcmain.h" -#include "almalloc.h" -#include "alu.h" -#include "core/logging.h" - -#include - - -namespace { - -#ifdef _WIN32 -#define DEVNAME_PREFIX "OpenAL Soft on " -#else -#define DEVNAME_PREFIX "" -#endif - -constexpr char defaultDeviceName[] = DEVNAME_PREFIX "Default Device"; - -struct Sdl2Backend final : public BackendBase { - Sdl2Backend(ALCdevice *device) noexcept : BackendBase{device} { } - ~Sdl2Backend() override; - - void audioCallback(Uint8 *stream, int len) noexcept; - static void audioCallbackC(void *ptr, Uint8 *stream, int len) noexcept - { static_cast(ptr)->audioCallback(stream, len); } - - void open(const char *name) override; - bool reset() override; - void start() override; - void stop() override; - - SDL_AudioDeviceID mDeviceID{0u}; - uint mFrameSize{0}; - - uint mFrequency{0u}; - DevFmtChannels mFmtChans{}; - DevFmtType mFmtType{}; - uint mUpdateSize{0u}; - - DEF_NEWDEL(Sdl2Backend) -}; - -Sdl2Backend::~Sdl2Backend() -{ - if(mDeviceID) - SDL_CloseAudioDevice(mDeviceID); - mDeviceID = 0; -} - -void Sdl2Backend::audioCallback(Uint8 *stream, int len) noexcept -{ - const auto ulen = static_cast(len); - assert((ulen % mFrameSize) == 0); - mDevice->renderSamples(stream, ulen / mFrameSize, mDevice->channelsFromFmt()); -} - -void Sdl2Backend::open(const char *name) -{ - SDL_AudioSpec want{}, have{}; - - want.freq = static_cast(mDevice->Frequency); - switch(mDevice->FmtType) - { - case DevFmtUByte: want.format = AUDIO_U8; break; - case DevFmtByte: want.format = AUDIO_S8; break; - case DevFmtUShort: want.format = AUDIO_U16SYS; break; - case DevFmtShort: want.format = AUDIO_S16SYS; break; - case DevFmtUInt: /* fall-through */ - case DevFmtInt: want.format = AUDIO_S32SYS; break; - case DevFmtFloat: want.format = AUDIO_F32; break; - } - want.channels = (mDevice->FmtChans == DevFmtMono) ? 1 : 2; - want.samples = static_cast(mDevice->UpdateSize); - want.callback = &Sdl2Backend::audioCallbackC; - want.userdata = this; - - /* Passing nullptr to SDL_OpenAudioDevice opens a default, which isn't - * necessarily the first in the list. - */ - if(!name || strcmp(name, defaultDeviceName) == 0) - mDeviceID = SDL_OpenAudioDevice(nullptr, SDL_FALSE, &want, &have, - SDL_AUDIO_ALLOW_ANY_CHANGE); - else - { - const size_t prefix_len = strlen(DEVNAME_PREFIX); - if(strncmp(name, DEVNAME_PREFIX, prefix_len) == 0) - mDeviceID = SDL_OpenAudioDevice(name+prefix_len, SDL_FALSE, &want, &have, - SDL_AUDIO_ALLOW_ANY_CHANGE); - else - mDeviceID = SDL_OpenAudioDevice(name, SDL_FALSE, &want, &have, - SDL_AUDIO_ALLOW_ANY_CHANGE); - } - if(mDeviceID == 0) - throw al::backend_exception{al::backend_error::NoDevice, "%s", SDL_GetError()}; - - mDevice->Frequency = static_cast(have.freq); - - if(have.channels == 1) - mDevice->FmtChans = DevFmtMono; - else if(have.channels == 2) - mDevice->FmtChans = DevFmtStereo; - else - throw al::backend_exception{al::backend_error::DeviceError, - "Unhandled SDL channel count: %d", int{have.channels}}; - - switch(have.format) - { - case AUDIO_U8: mDevice->FmtType = DevFmtUByte; break; - case AUDIO_S8: mDevice->FmtType = DevFmtByte; break; - case AUDIO_U16SYS: mDevice->FmtType = DevFmtUShort; break; - case AUDIO_S16SYS: mDevice->FmtType = DevFmtShort; break; - case AUDIO_S32SYS: mDevice->FmtType = DevFmtInt; break; - case AUDIO_F32SYS: mDevice->FmtType = DevFmtFloat; break; - default: - throw al::backend_exception{al::backend_error::DeviceError, "Unhandled SDL format: 0x%04x", - have.format}; - } - mDevice->UpdateSize = have.samples; - mDevice->BufferSize = have.samples * 2; /* SDL always (tries to) use two periods. */ - - mFrameSize = mDevice->frameSizeFromFmt(); - mFrequency = mDevice->Frequency; - mFmtChans = mDevice->FmtChans; - mFmtType = mDevice->FmtType; - mUpdateSize = mDevice->UpdateSize; - - mDevice->DeviceName = name ? name : defaultDeviceName; -} - -bool Sdl2Backend::reset() -{ - mDevice->Frequency = mFrequency; - mDevice->FmtChans = mFmtChans; - mDevice->FmtType = mFmtType; - mDevice->UpdateSize = mUpdateSize; - mDevice->BufferSize = mUpdateSize * 2; - setDefaultWFXChannelOrder(); - return true; -} - -void Sdl2Backend::start() -{ SDL_PauseAudioDevice(mDeviceID, 0); } - -void Sdl2Backend::stop() -{ SDL_PauseAudioDevice(mDeviceID, 1); } - -} // namespace - -BackendFactory &SDL2BackendFactory::getFactory() -{ - static SDL2BackendFactory factory{}; - return factory; -} - -bool SDL2BackendFactory::init() -{ return (SDL_InitSubSystem(SDL_INIT_AUDIO) == 0); } - -bool SDL2BackendFactory::querySupport(BackendType type) -{ return type == BackendType::Playback; } - -std::string SDL2BackendFactory::probe(BackendType type) -{ - std::string outnames; - - if(type != BackendType::Playback) - return outnames; - - int num_devices{SDL_GetNumAudioDevices(SDL_FALSE)}; - - /* Includes null char. */ - outnames.append(defaultDeviceName, sizeof(defaultDeviceName)); - for(int i{0};i < num_devices;++i) - { - std::string name{DEVNAME_PREFIX}; - name += SDL_GetAudioDeviceName(i, SDL_FALSE); - if(!name.empty()) - outnames.append(name.c_str(), name.length()+1); - } - return outnames; -} - -BackendPtr SDL2BackendFactory::createBackend(ALCdevice *device, BackendType type) -{ - if(type == BackendType::Playback) - return BackendPtr{new Sdl2Backend{device}}; - return nullptr; -} diff --git a/alc/backends/sdl2.h b/alc/backends/sdl2.h deleted file mode 100644 index ce79d52e..00000000 --- a/alc/backends/sdl2.h +++ /dev/null @@ -1,19 +0,0 @@ -#ifndef BACKENDS_SDL2_H -#define BACKENDS_SDL2_H - -#include "backends/base.h" - -struct SDL2BackendFactory final : public BackendFactory { -public: - bool init() override; - - bool querySupport(BackendType type) override; - - std::string probe(BackendType type) override; - - BackendPtr createBackend(ALCdevice *device, BackendType type) override; - - static BackendFactory &getFactory(); -}; - -#endif /* BACKENDS_SDL2_H */ diff --git a/alc/backends/sndio.cpp b/alc/backends/sndio.cpp deleted file mode 100644 index 41bdb73b..00000000 --- a/alc/backends/sndio.cpp +++ /dev/null @@ -1,517 +0,0 @@ -/** - * OpenAL cross platform audio library - * Copyright (C) 1999-2007 by authors. - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - * Or go to http://www.gnu.org/copyleft/lgpl.html - */ - -#include "config.h" - -#include "backends/sndio.h" - -#include -#include -#include - -#include -#include - -#include "alcmain.h" -#include "alu.h" -#include "core/logging.h" -#include "ringbuffer.h" -#include "threads.h" -#include "vector.h" - -#include - - -namespace { - -static const char sndio_device[] = "SndIO Default"; - - -struct SndioPlayback final : public BackendBase { - SndioPlayback(ALCdevice *device) noexcept : BackendBase{device} { } - ~SndioPlayback() override; - - int mixerProc(); - - void open(const char *name) override; - bool reset() override; - void start() override; - void stop() override; - - sio_hdl *mSndHandle{nullptr}; - - al::vector mBuffer; - - std::atomic mKillNow{true}; - std::thread mThread; - - DEF_NEWDEL(SndioPlayback) -}; - -SndioPlayback::~SndioPlayback() -{ - if(mSndHandle) - sio_close(mSndHandle); - mSndHandle = nullptr; -} - -int SndioPlayback::mixerProc() -{ - sio_par par; - sio_initpar(&par); - if(!sio_getpar(mSndHandle, &par)) - { - mDevice->handleDisconnect("Failed to get device parameters"); - return 1; - } - - const size_t frameStep{par.pchan}; - const size_t frameSize{frameStep * par.bps}; - - SetRTPriority(); - althrd_setname(MIXER_THREAD_NAME); - - while(!mKillNow.load(std::memory_order_acquire) - && mDevice->Connected.load(std::memory_order_acquire)) - { - al::byte *WritePtr{mBuffer.data()}; - size_t len{mBuffer.size()}; - - mDevice->renderSamples(WritePtr, static_cast(len/frameSize), frameStep); - while(len > 0 && !mKillNow.load(std::memory_order_acquire)) - { - size_t wrote{sio_write(mSndHandle, WritePtr, len)}; - if(wrote == 0) - { - ERR("sio_write failed\n"); - mDevice->handleDisconnect("Failed to write playback samples"); - break; - } - - len -= wrote; - WritePtr += wrote; - } - } - - return 0; -} - - -void SndioPlayback::open(const char *name) -{ - if(!name) - name = sndio_device; - else if(strcmp(name, sndio_device) != 0) - throw al::backend_exception{al::backend_error::NoDevice, "Device name \"%s\" not found", - name}; - - mSndHandle = sio_open(nullptr, SIO_PLAY, 0); - if(mSndHandle == nullptr) - throw al::backend_exception{al::backend_error::NoDevice, "Could not open backend device"}; - - mDevice->DeviceName = name; -} - -bool SndioPlayback::reset() -{ - sio_par par; - sio_initpar(&par); - - par.rate = mDevice->Frequency; - switch(mDevice->FmtChans) - { - case DevFmtMono : par.pchan = 1; break; - case DevFmtQuad : par.pchan = 4; break; - case DevFmtX51Rear: // fall-through - "Similar to 5.1, except using rear channels instead of sides" - case DevFmtX51 : par.pchan = 6; break; - case DevFmtX61 : par.pchan = 7; break; - case DevFmtX71 : par.pchan = 8; break; - - // fall back to stereo for Ambi3D - case DevFmtAmbi3D : // fall-through - case DevFmtStereo : par.pchan = 2; break; - } - - switch(mDevice->FmtType) - { - case DevFmtByte: - par.bits = 8; - par.sig = 1; - break; - case DevFmtUByte: - par.bits = 8; - par.sig = 0; - break; - case DevFmtFloat: - case DevFmtShort: - par.bits = 16; - par.sig = 1; - break; - case DevFmtUShort: - par.bits = 16; - par.sig = 0; - break; - case DevFmtInt: - par.bits = 32; - par.sig = 1; - break; - case DevFmtUInt: - par.bits = 32; - par.sig = 0; - break; - } - par.le = SIO_LE_NATIVE; - - par.round = mDevice->UpdateSize; - par.appbufsz = mDevice->BufferSize - mDevice->UpdateSize; - if(!par.appbufsz) par.appbufsz = mDevice->UpdateSize; - - if(!sio_setpar(mSndHandle, &par) || !sio_getpar(mSndHandle, &par)) - { - ERR("Failed to set device parameters\n"); - return false; - } - - if(par.bits != par.bps*8) - { - ERR("Padded samples not supported (%u of %u bits)\n", par.bits, par.bps*8); - return false; - } - if(par.le != SIO_LE_NATIVE) - { - ERR("Non-native-endian samples not supported (got %s-endian)\n", - par.le ? "little" : "big"); - return false; - } - - mDevice->Frequency = par.rate; - - if(par.pchan < 2) - { - if(mDevice->FmtChans != DevFmtMono) - { - WARN("Got %u channel for %s\n", par.pchan, DevFmtChannelsString(mDevice->FmtChans)); - mDevice->FmtChans = DevFmtMono; - } - } - else if((par.pchan == 2 && mDevice->FmtChans != DevFmtStereo) - || par.pchan == 3 - || (par.pchan == 4 && mDevice->FmtChans != DevFmtQuad) - || par.pchan == 5 - || (par.pchan == 6 && mDevice->FmtChans != DevFmtX51 && mDevice->FmtChans != DevFmtX51Rear) - || (par.pchan == 7 && mDevice->FmtChans != DevFmtX61) - || (par.pchan == 8 && mDevice->FmtChans != DevFmtX71) - || par.pchan > 8) - { - WARN("Got %u channels for %s\n", par.pchan, DevFmtChannelsString(mDevice->FmtChans)); - mDevice->FmtChans = DevFmtStereo; - } - - if(par.bits == 8 && par.sig == 1) - mDevice->FmtType = DevFmtByte; - else if(par.bits == 8 && par.sig == 0) - mDevice->FmtType = DevFmtUByte; - else if(par.bits == 16 && par.sig == 1) - mDevice->FmtType = DevFmtShort; - else if(par.bits == 16 && par.sig == 0) - mDevice->FmtType = DevFmtUShort; - else if(par.bits == 32 && par.sig == 1) - mDevice->FmtType = DevFmtInt; - else if(par.bits == 32 && par.sig == 0) - mDevice->FmtType = DevFmtUInt; - else - { - ERR("Unhandled sample format: %s %u-bit\n", (par.sig?"signed":"unsigned"), par.bits); - return false; - } - - setDefaultChannelOrder(); - - mDevice->UpdateSize = par.round; - mDevice->BufferSize = par.bufsz + par.round; - - mBuffer.resize(mDevice->UpdateSize * par.pchan*par.bps); - if(par.sig == 1) - std::fill(mBuffer.begin(), mBuffer.end(), al::byte{}); - else if(par.bits == 8) - std::fill_n(mBuffer.data(), mBuffer.size(), al::byte(0x80)); - else if(par.bits == 16) - std::fill_n(reinterpret_cast(mBuffer.data()), mBuffer.size()/2, 0x8000); - else if(par.bits == 32) - std::fill_n(reinterpret_cast(mBuffer.data()), mBuffer.size()/4, 0x80000000u); - - return true; -} - -void SndioPlayback::start() -{ - if(!sio_start(mSndHandle)) - throw al::backend_exception{al::backend_error::DeviceError, "Error starting playback"}; - - try { - mKillNow.store(false, std::memory_order_release); - mThread = std::thread{std::mem_fn(&SndioPlayback::mixerProc), this}; - } - catch(std::exception& e) { - sio_stop(mSndHandle); - throw al::backend_exception{al::backend_error::DeviceError, - "Failed to start mixing thread: %s", e.what()}; - } -} - -void SndioPlayback::stop() -{ - if(mKillNow.exchange(true, std::memory_order_acq_rel) || !mThread.joinable()) - return; - mThread.join(); - - if(!sio_stop(mSndHandle)) - ERR("Error stopping device\n"); -} - - -struct SndioCapture final : public BackendBase { - SndioCapture(ALCdevice *device) noexcept : BackendBase{device} { } - ~SndioCapture() override; - - int recordProc(); - - void open(const char *name) override; - void start() override; - void stop() override; - void captureSamples(al::byte *buffer, uint samples) override; - uint availableSamples() override; - - sio_hdl *mSndHandle{nullptr}; - - RingBufferPtr mRing; - - std::atomic mKillNow{true}; - std::thread mThread; - - DEF_NEWDEL(SndioCapture) -}; - -SndioCapture::~SndioCapture() -{ - if(mSndHandle) - sio_close(mSndHandle); - mSndHandle = nullptr; -} - -int SndioCapture::recordProc() -{ - SetRTPriority(); - althrd_setname(RECORD_THREAD_NAME); - - const uint frameSize{mDevice->frameSizeFromFmt()}; - - while(!mKillNow.load(std::memory_order_acquire) - && mDevice->Connected.load(std::memory_order_acquire)) - { - auto data = mRing->getWriteVector(); - size_t todo{data.first.len + data.second.len}; - if(todo == 0) - { - static char junk[4096]; - sio_read(mSndHandle, junk, - minz(sizeof(junk)/frameSize, mDevice->UpdateSize)*frameSize); - continue; - } - - size_t total{0u}; - data.first.len *= frameSize; - data.second.len *= frameSize; - todo = minz(todo, mDevice->UpdateSize) * frameSize; - while(total < todo) - { - if(!data.first.len) - data.first = data.second; - - size_t got{sio_read(mSndHandle, data.first.buf, minz(todo-total, data.first.len))}; - if(!got) - { - mDevice->handleDisconnect("Failed to read capture samples"); - break; - } - - data.first.buf += got; - data.first.len -= got; - total += got; - } - mRing->writeAdvance(total / frameSize); - } - - return 0; -} - - -void SndioCapture::open(const char *name) -{ - if(!name) - name = sndio_device; - else if(strcmp(name, sndio_device) != 0) - throw al::backend_exception{al::backend_error::NoDevice, "Device name \"%s\" not found", - name}; - - mSndHandle = sio_open(nullptr, SIO_REC, 0); - if(mSndHandle == nullptr) - throw al::backend_exception{al::backend_error::NoDevice, "Could not open backend device"}; - - sio_par par; - sio_initpar(&par); - - switch(mDevice->FmtType) - { - case DevFmtByte: - par.bps = 1; - par.sig = 1; - break; - case DevFmtUByte: - par.bps = 1; - par.sig = 0; - break; - case DevFmtShort: - par.bps = 2; - par.sig = 1; - break; - case DevFmtUShort: - par.bps = 2; - par.sig = 0; - break; - case DevFmtInt: - par.bps = 4; - par.sig = 1; - break; - case DevFmtUInt: - par.bps = 4; - par.sig = 0; - break; - case DevFmtFloat: - throw al::backend_exception{al::backend_error::DeviceError, - "%s capture samples not supported", DevFmtTypeString(mDevice->FmtType)}; - } - par.bits = par.bps * 8; - par.le = SIO_LE_NATIVE; - par.msb = SIO_LE_NATIVE ? 0 : 1; - par.rchan = mDevice->channelsFromFmt(); - par.rate = mDevice->Frequency; - - par.appbufsz = maxu(mDevice->BufferSize, mDevice->Frequency/10); - par.round = minu(par.appbufsz, mDevice->Frequency/40); - - mDevice->UpdateSize = par.round; - mDevice->BufferSize = par.appbufsz; - - if(!sio_setpar(mSndHandle, &par) || !sio_getpar(mSndHandle, &par)) - throw al::backend_exception{al::backend_error::DeviceError, - "Failed to set device praameters"}; - - if(par.bits != par.bps*8) - throw al::backend_exception{al::backend_error::DeviceError, - "Padded samples not supported (got %u of %u bits)", par.bits, par.bps*8}; - - if(!((mDevice->FmtType == DevFmtByte && par.bits == 8 && par.sig != 0) - || (mDevice->FmtType == DevFmtUByte && par.bits == 8 && par.sig == 0) - || (mDevice->FmtType == DevFmtShort && par.bits == 16 && par.sig != 0) - || (mDevice->FmtType == DevFmtUShort && par.bits == 16 && par.sig == 0) - || (mDevice->FmtType == DevFmtInt && par.bits == 32 && par.sig != 0) - || (mDevice->FmtType == DevFmtUInt && par.bits == 32 && par.sig == 0)) - || mDevice->channelsFromFmt() != par.rchan || mDevice->Frequency != par.rate) - throw al::backend_exception{al::backend_error::DeviceError, - "Failed to set format %s %s %uhz, got %c%u %u-channel %uhz instead", - DevFmtTypeString(mDevice->FmtType), DevFmtChannelsString(mDevice->FmtChans), - mDevice->Frequency, par.sig?'s':'u', par.bits, par.rchan, par.rate}; - - mRing = RingBuffer::Create(mDevice->BufferSize, par.bps*par.rchan, false); - - setDefaultChannelOrder(); - - mDevice->DeviceName = name; -} - -void SndioCapture::start() -{ - if(!sio_start(mSndHandle)) - throw al::backend_exception{al::backend_error::DeviceError, "Error starting capture"}; - - try { - mKillNow.store(false, std::memory_order_release); - mThread = std::thread{std::mem_fn(&SndioCapture::recordProc), this}; - } - catch(std::exception& e) { - sio_stop(mSndHandle); - throw al::backend_exception{al::backend_error::DeviceError, - "Failed to start capture thread: %s", e.what()}; - } -} - -void SndioCapture::stop() -{ - if(mKillNow.exchange(true, std::memory_order_acq_rel) || !mThread.joinable()) - return; - mThread.join(); - - if(!sio_stop(mSndHandle)) - ERR("Error stopping device\n"); -} - -void SndioCapture::captureSamples(al::byte *buffer, uint samples) -{ mRing->read(buffer, samples); } - -uint SndioCapture::availableSamples() -{ return static_cast(mRing->readSpace()); } - -} // namespace - -BackendFactory &SndIOBackendFactory::getFactory() -{ - static SndIOBackendFactory factory{}; - return factory; -} - -bool SndIOBackendFactory::init() -{ return true; } - -bool SndIOBackendFactory::querySupport(BackendType type) -{ return (type == BackendType::Playback || type == BackendType::Capture); } - -std::string SndIOBackendFactory::probe(BackendType type) -{ - std::string outnames; - switch(type) - { - case BackendType::Playback: - case BackendType::Capture: - /* Includes null char. */ - outnames.append(sndio_device, sizeof(sndio_device)); - break; - } - return outnames; -} - -BackendPtr SndIOBackendFactory::createBackend(ALCdevice *device, BackendType type) -{ - if(type == BackendType::Playback) - return BackendPtr{new SndioPlayback{device}}; - if(type == BackendType::Capture) - return BackendPtr{new SndioCapture{device}}; - return nullptr; -} diff --git a/alc/backends/sndio.h b/alc/backends/sndio.h deleted file mode 100644 index 83d02906..00000000 --- a/alc/backends/sndio.h +++ /dev/null @@ -1,19 +0,0 @@ -#ifndef BACKENDS_SNDIO_H -#define BACKENDS_SNDIO_H - -#include "backends/base.h" - -struct SndIOBackendFactory final : public BackendFactory { -public: - bool init() override; - - bool querySupport(BackendType type) override; - - std::string probe(BackendType type) override; - - BackendPtr createBackend(ALCdevice *device, BackendType type) override; - - static BackendFactory &getFactory(); -}; - -#endif /* BACKENDS_SNDIO_H */ diff --git a/alc/backends/solaris.cpp b/alc/backends/solaris.cpp deleted file mode 100644 index f2763357..00000000 --- a/alc/backends/solaris.cpp +++ /dev/null @@ -1,294 +0,0 @@ -/** - * OpenAL cross platform audio library - * Copyright (C) 1999-2007 by authors. - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - * Or go to http://www.gnu.org/copyleft/lgpl.html - */ - -#include "config.h" - -#include "backends/solaris.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -#include "alcmain.h" -#include "albyte.h" -#include "alu.h" -#include "alconfig.h" -#include "compat.h" -#include "core/logging.h" -#include "threads.h" -#include "vector.h" - -#include - - -namespace { - -constexpr char solaris_device[] = "Solaris Default"; - -std::string solaris_driver{"/dev/audio"}; - - -struct SolarisBackend final : public BackendBase { - SolarisBackend(ALCdevice *device) noexcept : BackendBase{device} { } - ~SolarisBackend() override; - - int mixerProc(); - - void open(const char *name) override; - bool reset() override; - void start() override; - void stop() override; - - int mFd{-1}; - - al::vector mBuffer; - - std::atomic mKillNow{true}; - std::thread mThread; - - DEF_NEWDEL(SolarisBackend) -}; - -SolarisBackend::~SolarisBackend() -{ - if(mFd != -1) - close(mFd); - mFd = -1; -} - -int SolarisBackend::mixerProc() -{ - SetRTPriority(); - althrd_setname(MIXER_THREAD_NAME); - - const size_t frame_step{mDevice->channelsFromFmt()}; - const uint frame_size{mDevice->frameSizeFromFmt()}; - - while(!mKillNow.load(std::memory_order_acquire) - && mDevice->Connected.load(std::memory_order_acquire)) - { - pollfd pollitem{}; - pollitem.fd = mFd; - pollitem.events = POLLOUT; - - int pret{poll(&pollitem, 1, 1000)}; - if(pret < 0) - { - if(errno == EINTR || errno == EAGAIN) - continue; - ERR("poll failed: %s\n", strerror(errno)); - mDevice->handleDisconnect("Failed to wait for playback buffer: %s", strerror(errno)); - break; - } - else if(pret == 0) - { - WARN("poll timeout\n"); - continue; - } - - al::byte *write_ptr{mBuffer.data()}; - size_t to_write{mBuffer.size()}; - mDevice->renderSamples(write_ptr, static_cast(to_write/frame_size), frame_step); - while(to_write > 0 && !mKillNow.load(std::memory_order_acquire)) - { - ssize_t wrote{write(mFd, write_ptr, to_write)}; - if(wrote < 0) - { - if(errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) - continue; - ERR("write failed: %s\n", strerror(errno)); - mDevice->handleDisconnect("Failed to write playback samples: %s", strerror(errno)); - break; - } - - to_write -= static_cast(wrote); - write_ptr += wrote; - } - } - - return 0; -} - - -void SolarisBackend::open(const char *name) -{ - if(!name) - name = solaris_device; - else if(strcmp(name, solaris_device) != 0) - throw al::backend_exception{al::backend_error::NoDevice, "Device name \"%s\" not found", - name}; - - mFd = ::open(solaris_driver.c_str(), O_WRONLY); - if(mFd == -1) - throw al::backend_exception{al::backend_error::NoDevice, "Could not open %s: %s", - solaris_driver.c_str(), strerror(errno)}; - - mDevice->DeviceName = name; -} - -bool SolarisBackend::reset() -{ - audio_info_t info; - AUDIO_INITINFO(&info); - - info.play.sample_rate = mDevice->Frequency; - - if(mDevice->FmtChans != DevFmtMono) - mDevice->FmtChans = DevFmtStereo; - uint numChannels{mDevice->channelsFromFmt()}; - info.play.channels = numChannels; - - switch(mDevice->FmtType) - { - case DevFmtByte: - info.play.precision = 8; - info.play.encoding = AUDIO_ENCODING_LINEAR; - break; - case DevFmtUByte: - info.play.precision = 8; - info.play.encoding = AUDIO_ENCODING_LINEAR8; - break; - case DevFmtUShort: - case DevFmtInt: - case DevFmtUInt: - case DevFmtFloat: - mDevice->FmtType = DevFmtShort; - /* fall-through */ - case DevFmtShort: - info.play.precision = 16; - info.play.encoding = AUDIO_ENCODING_LINEAR; - break; - } - - uint frameSize{numChannels * mDevice->bytesFromFmt()}; - info.play.buffer_size = mDevice->BufferSize * frameSize; - - if(ioctl(mFd, AUDIO_SETINFO, &info) < 0) - { - ERR("ioctl failed: %s\n", strerror(errno)); - return false; - } - - if(mDevice->channelsFromFmt() != info.play.channels) - { - ERR("Failed to set %s, got %u channels instead\n", DevFmtChannelsString(mDevice->FmtChans), - info.play.channels); - return false; - } - - if(!((info.play.precision == 8 && info.play.encoding == AUDIO_ENCODING_LINEAR8 && mDevice->FmtType == DevFmtUByte) || - (info.play.precision == 8 && info.play.encoding == AUDIO_ENCODING_LINEAR && mDevice->FmtType == DevFmtByte) || - (info.play.precision == 16 && info.play.encoding == AUDIO_ENCODING_LINEAR && mDevice->FmtType == DevFmtShort) || - (info.play.precision == 32 && info.play.encoding == AUDIO_ENCODING_LINEAR && mDevice->FmtType == DevFmtInt))) - { - ERR("Could not set %s samples, got %d (0x%x)\n", DevFmtTypeString(mDevice->FmtType), - info.play.precision, info.play.encoding); - return false; - } - - mDevice->Frequency = info.play.sample_rate; - mDevice->BufferSize = info.play.buffer_size / frameSize; - mDevice->UpdateSize = mDevice->BufferSize / 2; - - setDefaultChannelOrder(); - - mBuffer.resize(mDevice->UpdateSize * mDevice->frameSizeFromFmt()); - std::fill(mBuffer.begin(), mBuffer.end(), al::byte{}); - - return true; -} - -void SolarisBackend::start() -{ - try { - mKillNow.store(false, std::memory_order_release); - mThread = std::thread{std::mem_fn(&SolarisBackend::mixerProc), this}; - } - catch(std::exception& e) { - throw al::backend_exception{al::backend_error::DeviceError, - "Failed to start mixing thread: %s", e.what()}; - } -} - -void SolarisBackend::stop() -{ - if(mKillNow.exchange(true, std::memory_order_acq_rel) || !mThread.joinable()) - return; - mThread.join(); - - if(ioctl(mFd, AUDIO_DRAIN) < 0) - ERR("Error draining device: %s\n", strerror(errno)); -} - -} // namespace - -BackendFactory &SolarisBackendFactory::getFactory() -{ - static SolarisBackendFactory factory{}; - return factory; -} - -bool SolarisBackendFactory::init() -{ - if(auto devopt = ConfigValueStr(nullptr, "solaris", "device")) - solaris_driver = std::move(*devopt); - return true; -} - -bool SolarisBackendFactory::querySupport(BackendType type) -{ return type == BackendType::Playback; } - -std::string SolarisBackendFactory::probe(BackendType type) -{ - std::string outnames; - switch(type) - { - case BackendType::Playback: - { - struct stat buf; - if(stat(solaris_driver.c_str(), &buf) == 0) - outnames.append(solaris_device, sizeof(solaris_device)); - } - break; - - case BackendType::Capture: - break; - } - return outnames; -} - -BackendPtr SolarisBackendFactory::createBackend(ALCdevice *device, BackendType type) -{ - if(type == BackendType::Playback) - return BackendPtr{new SolarisBackend{device}}; - return nullptr; -} diff --git a/alc/backends/solaris.h b/alc/backends/solaris.h deleted file mode 100644 index 4a9e505b..00000000 --- a/alc/backends/solaris.h +++ /dev/null @@ -1,19 +0,0 @@ -#ifndef BACKENDS_SOLARIS_H -#define BACKENDS_SOLARIS_H - -#include "backends/base.h" - -struct SolarisBackendFactory final : public BackendFactory { -public: - bool init() override; - - bool querySupport(BackendType type) override; - - std::string probe(BackendType type) override; - - BackendPtr createBackend(ALCdevice *device, BackendType type) override; - - static BackendFactory &getFactory(); -}; - -#endif /* BACKENDS_SOLARIS_H */ diff --git a/alc/backends/wasapi.cpp b/alc/backends/wasapi.cpp deleted file mode 100644 index 1d1b93c4..00000000 --- a/alc/backends/wasapi.cpp +++ /dev/null @@ -1,1847 +0,0 @@ -/** - * OpenAL cross platform audio library - * Copyright (C) 2011 by authors. - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - * Or go to http://www.gnu.org/copyleft/lgpl.html - */ - -#include "config.h" - -#include "backends/wasapi.h" - -#define WIN32_LEAN_AND_MEAN -#include - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#ifndef _WAVEFORMATEXTENSIBLE_ -#include -#include -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "alcmain.h" -#include "alu.h" -#include "compat.h" -#include "converter.h" -#include "core/logging.h" -#include "ringbuffer.h" -#include "strutils.h" -#include "threads.h" - - -/* Some headers seem to define these as macros for __uuidof, which is annoying - * since some headers don't declare them at all. Hopefully the ifdef is enough - * to tell if they need to be declared. - */ -#ifndef KSDATAFORMAT_SUBTYPE_PCM -DEFINE_GUID(KSDATAFORMAT_SUBTYPE_PCM, 0x00000001, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); -#endif -#ifndef KSDATAFORMAT_SUBTYPE_IEEE_FLOAT -DEFINE_GUID(KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, 0x00000003, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); -#endif - -DEFINE_DEVPROPKEY(DEVPKEY_Device_FriendlyName, 0xa45c254e, 0xdf1c, 0x4efd, 0x80,0x20, 0x67,0xd1,0x46,0xa8,0x50,0xe0, 14); -DEFINE_PROPERTYKEY(PKEY_AudioEndpoint_FormFactor, 0x1da5d803, 0xd492, 0x4edd, 0x8c,0x23, 0xe0,0xc0,0xff,0xee,0x7f,0x0e, 0); -DEFINE_PROPERTYKEY(PKEY_AudioEndpoint_GUID, 0x1da5d803, 0xd492, 0x4edd, 0x8c, 0x23,0xe0, 0xc0,0xff,0xee,0x7f,0x0e, 4 ); - - -namespace { - -using std::chrono::milliseconds; -using std::chrono::seconds; - -using ReferenceTime = std::chrono::duration>; - -inline constexpr ReferenceTime operator "" _reftime(unsigned long long int n) noexcept -{ return ReferenceTime{static_cast(n)}; } - - -#define MONO SPEAKER_FRONT_CENTER -#define STEREO (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT) -#define QUAD (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_BACK_LEFT|SPEAKER_BACK_RIGHT) -#define X5DOT1 (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_SIDE_LEFT|SPEAKER_SIDE_RIGHT) -#define X5DOT1REAR (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_BACK_LEFT|SPEAKER_BACK_RIGHT) -#define X6DOT1 (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_BACK_CENTER|SPEAKER_SIDE_LEFT|SPEAKER_SIDE_RIGHT) -#define X7DOT1 (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_BACK_LEFT|SPEAKER_BACK_RIGHT|SPEAKER_SIDE_LEFT|SPEAKER_SIDE_RIGHT) - -constexpr inline DWORD MaskFromTopBits(DWORD b) noexcept -{ - b |= b>>1; - b |= b>>2; - b |= b>>4; - b |= b>>8; - b |= b>>16; - return b; -} -constexpr DWORD MonoMask{MaskFromTopBits(MONO)}; -constexpr DWORD StereoMask{MaskFromTopBits(STEREO)}; -constexpr DWORD QuadMask{MaskFromTopBits(QUAD)}; -constexpr DWORD X51Mask{MaskFromTopBits(X5DOT1)}; -constexpr DWORD X51RearMask{MaskFromTopBits(X5DOT1REAR)}; -constexpr DWORD X61Mask{MaskFromTopBits(X6DOT1)}; -constexpr DWORD X71Mask{MaskFromTopBits(X7DOT1)}; - -#define DEVNAME_HEAD "OpenAL Soft on " - - -/* Scales the given reftime value, rounding the result. */ -inline uint RefTime2Samples(const ReferenceTime &val, uint srate) -{ - const auto retval = (val*srate + ReferenceTime{seconds{1}}/2) / seconds{1}; - return static_cast(mini64(retval, std::numeric_limits::max())); -} - - -template -class ComPtr { - T *mPtr{nullptr}; - -public: - ComPtr() noexcept = default; - ComPtr(const ComPtr &rhs) : mPtr{rhs.mPtr} { if(mPtr) mPtr->AddRef(); } - ComPtr(ComPtr&& rhs) noexcept : mPtr{rhs.mPtr} { rhs.mPtr = nullptr; } - ComPtr(std::nullptr_t) noexcept { } - explicit ComPtr(T *ptr) noexcept : mPtr{ptr} { } - ~ComPtr() { if(mPtr) mPtr->Release(); } - - ComPtr& operator=(const ComPtr &rhs) - { - if(!rhs.mPtr) - { - if(mPtr) - mPtr->Release(); - mPtr = nullptr; - } - else - { - rhs.mPtr->AddRef(); - try { - if(mPtr) - mPtr->Release(); - mPtr = rhs.mPtr; - } - catch(...) { - rhs.mPtr->Release(); - throw; - } - } - return *this; - } - ComPtr& operator=(ComPtr&& rhs) - { - if(mPtr) - mPtr->Release(); - mPtr = rhs.mPtr; - rhs.mPtr = nullptr; - return *this; - } - - operator bool() const noexcept { return mPtr != nullptr; } - - T& operator*() const noexcept { return *mPtr; } - T* operator->() const noexcept { return mPtr; } - T* get() const noexcept { return mPtr; } - T** getPtr() noexcept { return &mPtr; } - - T* release() noexcept - { - T *ret{mPtr}; - mPtr = nullptr; - return ret; - } - - void swap(ComPtr &rhs) noexcept { std::swap(mPtr, rhs.mPtr); } - void swap(ComPtr&& rhs) noexcept { std::swap(mPtr, rhs.mPtr); } -}; - - -class GuidPrinter { - char mMsg[64]; - -public: - GuidPrinter(const GUID &guid) - { - std::snprintf(mMsg, al::size(mMsg), "{%08lx-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}", - DWORD{guid.Data1}, guid.Data2, guid.Data3, guid.Data4[0], guid.Data4[1], guid.Data4[2], - guid.Data4[3], guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7]); - } - const char *c_str() const { return mMsg; } -}; - -struct PropVariant { - PROPVARIANT mProp; - -public: - PropVariant() { PropVariantInit(&mProp); } - ~PropVariant() { clear(); } - - void clear() { PropVariantClear(&mProp); } - - PROPVARIANT* get() noexcept { return &mProp; } - - PROPVARIANT& operator*() noexcept { return mProp; } - const PROPVARIANT& operator*() const noexcept { return mProp; } - - PROPVARIANT* operator->() noexcept { return &mProp; } - const PROPVARIANT* operator->() const noexcept { return &mProp; } -}; - -struct DevMap { - std::string name; - std::string endpoint_guid; // obtained from PKEY_AudioEndpoint_GUID , set to "Unknown device GUID" if absent. - std::wstring devid; - - template - DevMap(T0&& name_, T1&& guid_, T2&& devid_) - : name{std::forward(name_)} - , endpoint_guid{std::forward(guid_)} - , devid{std::forward(devid_)} - { } -}; - -bool checkName(const al::vector &list, const std::string &name) -{ - return std::find_if(list.cbegin(), list.cend(), - [&name](const DevMap &entry) -> bool - { return entry.name == name; } - ) != list.cend(); -} - -al::vector PlaybackDevices; -al::vector CaptureDevices; - - -using NameGUIDPair = std::pair; -NameGUIDPair get_device_name_and_guid(IMMDevice *device) -{ - static constexpr char UnknownName[]{"Unknown Device Name"}; - static constexpr char UnknownGuid[]{"Unknown Device GUID"}; - std::string name{DEVNAME_HEAD}; - std::string guid; - - ComPtr ps; - HRESULT hr = device->OpenPropertyStore(STGM_READ, ps.getPtr()); - if(FAILED(hr)) - { - WARN("OpenPropertyStore failed: 0x%08lx\n", hr); - return std::make_pair(UnknownName, UnknownGuid); - } - - PropVariant pvprop; - hr = ps->GetValue(reinterpret_cast(DEVPKEY_Device_FriendlyName), pvprop.get()); - if(FAILED(hr)) - { - WARN("GetValue Device_FriendlyName failed: 0x%08lx\n", hr); - name += UnknownName; - } - else if(pvprop->vt == VT_LPWSTR) - name += wstr_to_utf8(pvprop->pwszVal); - else - { - WARN("Unexpected PROPVARIANT type: 0x%04x\n", pvprop->vt); - name += UnknownName; - } - - pvprop.clear(); - hr = ps->GetValue(reinterpret_cast(PKEY_AudioEndpoint_GUID), pvprop.get()); - if(FAILED(hr)) - { - WARN("GetValue AudioEndpoint_GUID failed: 0x%08lx\n", hr); - guid = UnknownGuid; - } - else if(pvprop->vt == VT_LPWSTR) - guid = wstr_to_utf8(pvprop->pwszVal); - else - { - WARN("Unexpected PROPVARIANT type: 0x%04x\n", pvprop->vt); - guid = UnknownGuid; - } - - return std::make_pair(std::move(name), std::move(guid)); -} - -void get_device_formfactor(IMMDevice *device, EndpointFormFactor *formfactor) -{ - ComPtr ps; - HRESULT hr = device->OpenPropertyStore(STGM_READ, ps.getPtr()); - if(FAILED(hr)) - { - WARN("OpenPropertyStore failed: 0x%08lx\n", hr); - return; - } - - PropVariant pvform; - hr = ps->GetValue(reinterpret_cast(PKEY_AudioEndpoint_FormFactor), pvform.get()); - if(FAILED(hr)) - WARN("GetValue AudioEndpoint_FormFactor failed: 0x%08lx\n", hr); - else if(pvform->vt == VT_UI4) - *formfactor = static_cast(pvform->ulVal); - else if(pvform->vt == VT_EMPTY) - *formfactor = UnknownFormFactor; - else - WARN("Unexpected PROPVARIANT type: 0x%04x\n", pvform->vt); -} - - -void add_device(IMMDevice *device, const WCHAR *devid, al::vector &list) -{ - for(auto &entry : list) - { - if(entry.devid == devid) - return; - } - - auto name_guid = get_device_name_and_guid(device); - - int count{1}; - std::string newname{name_guid.first}; - while(checkName(list, newname)) - { - newname = name_guid.first; - newname += " #"; - newname += std::to_string(++count); - } - list.emplace_back(std::move(newname), std::move(name_guid.second), devid); - const DevMap &newentry = list.back(); - - TRACE("Got device \"%s\", \"%s\", \"%ls\"\n", newentry.name.c_str(), - newentry.endpoint_guid.c_str(), newentry.devid.c_str()); -} - -WCHAR *get_device_id(IMMDevice *device) -{ - WCHAR *devid; - - const HRESULT hr{device->GetId(&devid)}; - if(FAILED(hr)) - { - ERR("Failed to get device id: %lx\n", hr); - return nullptr; - } - - return devid; -} - -void probe_devices(IMMDeviceEnumerator *devenum, EDataFlow flowdir, al::vector &list) -{ - al::vector{}.swap(list); - - ComPtr coll; - HRESULT hr{devenum->EnumAudioEndpoints(flowdir, DEVICE_STATE_ACTIVE, coll.getPtr())}; - if(FAILED(hr)) - { - ERR("Failed to enumerate audio endpoints: 0x%08lx\n", hr); - return; - } - - UINT count{0}; - hr = coll->GetCount(&count); - if(SUCCEEDED(hr) && count > 0) - list.reserve(count); - - ComPtr device; - hr = devenum->GetDefaultAudioEndpoint(flowdir, eMultimedia, device.getPtr()); - if(SUCCEEDED(hr)) - { - if(WCHAR *devid{get_device_id(device.get())}) - { - add_device(device.get(), devid, list); - CoTaskMemFree(devid); - } - device = nullptr; - } - - for(UINT i{0};i < count;++i) - { - hr = coll->Item(i, device.getPtr()); - if(FAILED(hr)) continue; - - if(WCHAR *devid{get_device_id(device.get())}) - { - add_device(device.get(), devid, list); - CoTaskMemFree(devid); - } - device = nullptr; - } -} - - -bool MakeExtensible(WAVEFORMATEXTENSIBLE *out, const WAVEFORMATEX *in) -{ - *out = WAVEFORMATEXTENSIBLE{}; - if(in->wFormatTag == WAVE_FORMAT_EXTENSIBLE) - { - *out = *CONTAINING_RECORD(in, const WAVEFORMATEXTENSIBLE, Format); - out->Format.cbSize = sizeof(*out) - sizeof(out->Format); - } - else if(in->wFormatTag == WAVE_FORMAT_PCM) - { - out->Format = *in; - out->Format.cbSize = 0; - out->Samples.wValidBitsPerSample = out->Format.wBitsPerSample; - if(out->Format.nChannels == 1) - out->dwChannelMask = MONO; - else if(out->Format.nChannels == 2) - out->dwChannelMask = STEREO; - else - ERR("Unhandled PCM channel count: %d\n", out->Format.nChannels); - out->SubFormat = KSDATAFORMAT_SUBTYPE_PCM; - } - else if(in->wFormatTag == WAVE_FORMAT_IEEE_FLOAT) - { - out->Format = *in; - out->Format.cbSize = 0; - out->Samples.wValidBitsPerSample = out->Format.wBitsPerSample; - if(out->Format.nChannels == 1) - out->dwChannelMask = MONO; - else if(out->Format.nChannels == 2) - out->dwChannelMask = STEREO; - else - ERR("Unhandled IEEE float channel count: %d\n", out->Format.nChannels); - out->SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT; - } - else - { - ERR("Unhandled format tag: 0x%04x\n", in->wFormatTag); - return false; - } - return true; -} - -void TraceFormat(const char *msg, const WAVEFORMATEX *format) -{ - constexpr size_t fmtex_extra_size{sizeof(WAVEFORMATEXTENSIBLE)-sizeof(WAVEFORMATEX)}; - if(format->wFormatTag == WAVE_FORMAT_EXTENSIBLE && format->cbSize >= fmtex_extra_size) - { - const WAVEFORMATEXTENSIBLE *fmtex{ - CONTAINING_RECORD(format, const WAVEFORMATEXTENSIBLE, Format)}; - TRACE("%s:\n" - " FormatTag = 0x%04x\n" - " Channels = %d\n" - " SamplesPerSec = %lu\n" - " AvgBytesPerSec = %lu\n" - " BlockAlign = %d\n" - " BitsPerSample = %d\n" - " Size = %d\n" - " Samples = %d\n" - " ChannelMask = 0x%lx\n" - " SubFormat = %s\n", - msg, fmtex->Format.wFormatTag, fmtex->Format.nChannels, fmtex->Format.nSamplesPerSec, - fmtex->Format.nAvgBytesPerSec, fmtex->Format.nBlockAlign, fmtex->Format.wBitsPerSample, - fmtex->Format.cbSize, fmtex->Samples.wReserved, fmtex->dwChannelMask, - GuidPrinter{fmtex->SubFormat}.c_str()); - } - else - TRACE("%s:\n" - " FormatTag = 0x%04x\n" - " Channels = %d\n" - " SamplesPerSec = %lu\n" - " AvgBytesPerSec = %lu\n" - " BlockAlign = %d\n" - " BitsPerSample = %d\n" - " Size = %d\n", - msg, format->wFormatTag, format->nChannels, format->nSamplesPerSec, - format->nAvgBytesPerSec, format->nBlockAlign, format->wBitsPerSample, format->cbSize); -} - - -enum class MsgType { - OpenDevice, - ResetDevice, - StartDevice, - StopDevice, - CloseDevice, - EnumeratePlayback, - EnumerateCapture, - QuitThread, - - Count -}; - -constexpr char MessageStr[static_cast(MsgType::Count)][20]{ - "Open Device", - "Reset Device", - "Start Device", - "Stop Device", - "Close Device", - "Enumerate Playback", - "Enumerate Capture", - "Quit" -}; - - -/* Proxy interface used by the message handler. */ -struct WasapiProxy { - virtual ~WasapiProxy() = default; - - virtual HRESULT openProxy() = 0; - virtual void closeProxy() = 0; - - virtual HRESULT resetProxy() = 0; - virtual HRESULT startProxy() = 0; - virtual void stopProxy() = 0; - - struct Msg { - MsgType mType; - WasapiProxy *mProxy; - std::promise mPromise; - }; - static std::deque mMsgQueue; - static std::mutex mMsgQueueLock; - static std::condition_variable mMsgQueueCond; - - std::future pushMessage(MsgType type) - { - std::promise promise; - std::future future{promise.get_future()}; - { - std::lock_guard _{mMsgQueueLock}; - mMsgQueue.emplace_back(Msg{type, this, std::move(promise)}); - } - mMsgQueueCond.notify_one(); - return future; - } - - static std::future pushMessageStatic(MsgType type) - { - std::promise promise; - std::future future{promise.get_future()}; - { - std::lock_guard _{mMsgQueueLock}; - mMsgQueue.emplace_back(Msg{type, nullptr, std::move(promise)}); - } - mMsgQueueCond.notify_one(); - return future; - } - - static bool popMessage(Msg &msg) - { - std::unique_lock lock{mMsgQueueLock}; - mMsgQueueCond.wait(lock, []{return !mMsgQueue.empty();}); - msg = std::move(mMsgQueue.front()); - mMsgQueue.pop_front(); - return msg.mType != MsgType::QuitThread; - } - - static int messageHandler(std::promise *promise); -}; -std::deque WasapiProxy::mMsgQueue; -std::mutex WasapiProxy::mMsgQueueLock; -std::condition_variable WasapiProxy::mMsgQueueCond; - -int WasapiProxy::messageHandler(std::promise *promise) -{ - TRACE("Starting message thread\n"); - - HRESULT cohr{CoInitializeEx(nullptr, COINIT_MULTITHREADED)}; - if(FAILED(cohr)) - { - WARN("Failed to initialize COM: 0x%08lx\n", cohr); - promise->set_value(cohr); - return 0; - } - - void *ptr{}; - HRESULT hr{CoCreateInstance(CLSID_MMDeviceEnumerator, nullptr, CLSCTX_INPROC_SERVER, - IID_IMMDeviceEnumerator, &ptr)}; - if(FAILED(hr)) - { - WARN("Failed to create IMMDeviceEnumerator instance: 0x%08lx\n", hr); - promise->set_value(hr); - CoUninitialize(); - return 0; - } - static_cast(ptr)->Release(); - CoUninitialize(); - - TRACE("Message thread initialization complete\n"); - promise->set_value(S_OK); - promise = nullptr; - - TRACE("Starting message loop\n"); - uint deviceCount{0}; - Msg msg; - while(popMessage(msg)) - { - TRACE("Got message \"%s\" (0x%04x, this=%p)\n", - MessageStr[static_cast(msg.mType)], static_cast(msg.mType), - decltype(std::declval()){msg.mProxy}); - - switch(msg.mType) - { - case MsgType::OpenDevice: - hr = cohr = S_OK; - if(++deviceCount == 1) - hr = cohr = CoInitializeEx(nullptr, COINIT_MULTITHREADED); - if(SUCCEEDED(hr)) - hr = msg.mProxy->openProxy(); - msg.mPromise.set_value(hr); - - if(FAILED(hr)) - { - if(--deviceCount == 0 && SUCCEEDED(cohr)) - CoUninitialize(); - } - continue; - - case MsgType::ResetDevice: - hr = msg.mProxy->resetProxy(); - msg.mPromise.set_value(hr); - continue; - - case MsgType::StartDevice: - hr = msg.mProxy->startProxy(); - msg.mPromise.set_value(hr); - continue; - - case MsgType::StopDevice: - msg.mProxy->stopProxy(); - msg.mPromise.set_value(S_OK); - continue; - - case MsgType::CloseDevice: - msg.mProxy->closeProxy(); - msg.mPromise.set_value(S_OK); - - if(--deviceCount == 0) - CoUninitialize(); - continue; - - case MsgType::EnumeratePlayback: - case MsgType::EnumerateCapture: - hr = cohr = S_OK; - if(++deviceCount == 1) - hr = cohr = CoInitializeEx(nullptr, COINIT_MULTITHREADED); - if(SUCCEEDED(hr)) - hr = CoCreateInstance(CLSID_MMDeviceEnumerator, nullptr, CLSCTX_INPROC_SERVER, - IID_IMMDeviceEnumerator, &ptr); - if(FAILED(hr)) - msg.mPromise.set_value(hr); - else - { - ComPtr enumerator{static_cast(ptr)}; - - if(msg.mType == MsgType::EnumeratePlayback) - probe_devices(enumerator.get(), eRender, PlaybackDevices); - else if(msg.mType == MsgType::EnumerateCapture) - probe_devices(enumerator.get(), eCapture, CaptureDevices); - msg.mPromise.set_value(S_OK); - } - - if(--deviceCount == 0 && SUCCEEDED(cohr)) - CoUninitialize(); - continue; - - default: - ERR("Unexpected message: %u\n", static_cast(msg.mType)); - msg.mPromise.set_value(E_FAIL); - continue; - } - } - TRACE("Message loop finished\n"); - - return 0; -} - - -struct WasapiPlayback final : public BackendBase, WasapiProxy { - WasapiPlayback(ALCdevice *device) noexcept : BackendBase{device} { } - ~WasapiPlayback() override; - - int mixerProc(); - - void open(const char *name) override; - HRESULT openProxy() override; - void closeProxy() override; - - bool reset() override; - HRESULT resetProxy() override; - void start() override; - HRESULT startProxy() override; - void stop() override; - void stopProxy() override; - - ClockLatency getClockLatency() override; - - std::wstring mDevId; - - HRESULT mOpenStatus{E_FAIL}; - ComPtr mMMDev{nullptr}; - ComPtr mClient{nullptr}; - ComPtr mRender{nullptr}; - HANDLE mNotifyEvent{nullptr}; - - UINT32 mFrameStep{0u}; - std::atomic mPadding{0u}; - - std::mutex mMutex; - - std::atomic mKillNow{true}; - std::thread mThread; - - DEF_NEWDEL(WasapiPlayback) -}; - -WasapiPlayback::~WasapiPlayback() -{ - if(SUCCEEDED(mOpenStatus)) - pushMessage(MsgType::CloseDevice).wait(); - mOpenStatus = E_FAIL; - - if(mNotifyEvent != nullptr) - CloseHandle(mNotifyEvent); - mNotifyEvent = nullptr; -} - - -FORCE_ALIGN int WasapiPlayback::mixerProc() -{ - HRESULT hr{CoInitializeEx(nullptr, COINIT_MULTITHREADED)}; - if(FAILED(hr)) - { - ERR("CoInitializeEx(nullptr, COINIT_MULTITHREADED) failed: 0x%08lx\n", hr); - mDevice->handleDisconnect("COM init failed: 0x%08lx", hr); - return 1; - } - - SetRTPriority(); - althrd_setname(MIXER_THREAD_NAME); - - const uint update_size{mDevice->UpdateSize}; - const UINT32 buffer_len{mDevice->BufferSize}; - while(!mKillNow.load(std::memory_order_relaxed)) - { - UINT32 written; - hr = mClient->GetCurrentPadding(&written); - if(FAILED(hr)) - { - ERR("Failed to get padding: 0x%08lx\n", hr); - mDevice->handleDisconnect("Failed to retrieve buffer padding: 0x%08lx", hr); - break; - } - mPadding.store(written, std::memory_order_relaxed); - - uint len{buffer_len - written}; - if(len < update_size) - { - DWORD res{WaitForSingleObjectEx(mNotifyEvent, 2000, FALSE)}; - if(res != WAIT_OBJECT_0) - ERR("WaitForSingleObjectEx error: 0x%lx\n", res); - continue; - } - - BYTE *buffer; - hr = mRender->GetBuffer(len, &buffer); - if(SUCCEEDED(hr)) - { - { - std::lock_guard _{mMutex}; - mDevice->renderSamples(buffer, len, mFrameStep); - mPadding.store(written + len, std::memory_order_relaxed); - } - hr = mRender->ReleaseBuffer(len, 0); - } - if(FAILED(hr)) - { - ERR("Failed to buffer data: 0x%08lx\n", hr); - mDevice->handleDisconnect("Failed to send playback samples: 0x%08lx", hr); - break; - } - } - mPadding.store(0u, std::memory_order_release); - - CoUninitialize(); - return 0; -} - - -void WasapiPlayback::open(const char *name) -{ - HRESULT hr{S_OK}; - - mNotifyEvent = CreateEventW(nullptr, FALSE, FALSE, nullptr); - if(mNotifyEvent == nullptr) - { - ERR("Failed to create notify events: %lu\n", GetLastError()); - hr = E_FAIL; - } - - if(SUCCEEDED(hr)) - { - if(name) - { - if(PlaybackDevices.empty()) - pushMessage(MsgType::EnumeratePlayback).wait(); - - hr = E_FAIL; - auto iter = std::find_if(PlaybackDevices.cbegin(), PlaybackDevices.cend(), - [name](const DevMap &entry) -> bool - { return entry.name == name || entry.endpoint_guid == name; }); - if(iter == PlaybackDevices.cend()) - { - const std::wstring wname{utf8_to_wstr(name)}; - iter = std::find_if(PlaybackDevices.cbegin(), PlaybackDevices.cend(), - [&wname](const DevMap &entry) -> bool - { return entry.devid == wname; }); - } - if(iter == PlaybackDevices.cend()) - WARN("Failed to find device name matching \"%s\"\n", name); - else - { - mDevId = iter->devid; - mDevice->DeviceName = iter->name; - hr = S_OK; - } - } - } - - if(SUCCEEDED(hr)) - hr = pushMessage(MsgType::OpenDevice).get(); - mOpenStatus = hr; - - if(FAILED(hr)) - { - if(mNotifyEvent != nullptr) - CloseHandle(mNotifyEvent); - mNotifyEvent = nullptr; - - mDevId.clear(); - - throw al::backend_exception{al::backend_error::DeviceError, "Device init failed: 0x%08lx", - hr}; - } -} - -HRESULT WasapiPlayback::openProxy() -{ - void *ptr; - HRESULT hr{CoCreateInstance(CLSID_MMDeviceEnumerator, nullptr, CLSCTX_INPROC_SERVER, - IID_IMMDeviceEnumerator, &ptr)}; - if(SUCCEEDED(hr)) - { - ComPtr enumerator{static_cast(ptr)}; - if(mDevId.empty()) - hr = enumerator->GetDefaultAudioEndpoint(eRender, eMultimedia, mMMDev.getPtr()); - else - hr = enumerator->GetDevice(mDevId.c_str(), mMMDev.getPtr()); - } - if(SUCCEEDED(hr)) - hr = mMMDev->Activate(IID_IAudioClient, CLSCTX_INPROC_SERVER, nullptr, &ptr); - if(SUCCEEDED(hr)) - { - mClient = ComPtr{static_cast(ptr)}; - if(mDevice->DeviceName.empty()) - mDevice->DeviceName = get_device_name_and_guid(mMMDev.get()).first; - } - - if(FAILED(hr)) - mMMDev = nullptr; - - return hr; -} - -void WasapiPlayback::closeProxy() -{ - mClient = nullptr; - mMMDev = nullptr; -} - - -bool WasapiPlayback::reset() -{ - HRESULT hr{pushMessage(MsgType::ResetDevice).get()}; - if(FAILED(hr)) - throw al::backend_exception{al::backend_error::DeviceError, "0x%08lx", hr}; - return true; -} - -HRESULT WasapiPlayback::resetProxy() -{ - mClient = nullptr; - - void *ptr; - HRESULT hr{mMMDev->Activate(IID_IAudioClient, CLSCTX_INPROC_SERVER, nullptr, &ptr)}; - if(FAILED(hr)) - { - ERR("Failed to reactivate audio client: 0x%08lx\n", hr); - return hr; - } - mClient = ComPtr{static_cast(ptr)}; - - WAVEFORMATEX *wfx; - hr = mClient->GetMixFormat(&wfx); - if(FAILED(hr)) - { - ERR("Failed to get mix format: 0x%08lx\n", hr); - return hr; - } - - WAVEFORMATEXTENSIBLE OutputType; - if(!MakeExtensible(&OutputType, wfx)) - { - CoTaskMemFree(wfx); - return E_FAIL; - } - CoTaskMemFree(wfx); - wfx = nullptr; - - const ReferenceTime per_time{ReferenceTime{seconds{mDevice->UpdateSize}} / mDevice->Frequency}; - const ReferenceTime buf_time{ReferenceTime{seconds{mDevice->BufferSize}} / mDevice->Frequency}; - - if(!mDevice->Flags.test(FrequencyRequest)) - mDevice->Frequency = OutputType.Format.nSamplesPerSec; - if(!mDevice->Flags.test(ChannelsRequest)) - { - const uint32_t chancount{OutputType.Format.nChannels}; - const DWORD chanmask{OutputType.dwChannelMask}; - if(chancount >= 8 && (chanmask&X71Mask) == X7DOT1) - mDevice->FmtChans = DevFmtX71; - else if(chancount >= 7 && (chanmask&X61Mask) == X6DOT1) - mDevice->FmtChans = DevFmtX61; - else if(chancount >= 6 && (chanmask&X51Mask) == X5DOT1) - mDevice->FmtChans = DevFmtX51; - else if(chancount >= 6 && (chanmask&X51RearMask) == X5DOT1REAR) - mDevice->FmtChans = DevFmtX51Rear; - else if(chancount >= 4 && (chanmask&QuadMask) == QUAD) - mDevice->FmtChans = DevFmtQuad; - else if(chancount >= 2 && (chanmask&StereoMask) == STEREO) - mDevice->FmtChans = DevFmtStereo; - else if(chancount >= 1 && (chanmask&MonoMask) == MONO) - mDevice->FmtChans = DevFmtMono; - else - ERR("Unhandled channel config: %d -- 0x%08lx\n", chancount, chanmask); - } - - OutputType.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE; - switch(mDevice->FmtChans) - { - case DevFmtMono: - OutputType.Format.nChannels = 1; - OutputType.dwChannelMask = MONO; - break; - case DevFmtAmbi3D: - mDevice->FmtChans = DevFmtStereo; - /*fall-through*/ - case DevFmtStereo: - OutputType.Format.nChannels = 2; - OutputType.dwChannelMask = STEREO; - break; - case DevFmtQuad: - OutputType.Format.nChannels = 4; - OutputType.dwChannelMask = QUAD; - break; - case DevFmtX51: - OutputType.Format.nChannels = 6; - OutputType.dwChannelMask = X5DOT1; - break; - case DevFmtX51Rear: - OutputType.Format.nChannels = 6; - OutputType.dwChannelMask = X5DOT1REAR; - break; - case DevFmtX61: - OutputType.Format.nChannels = 7; - OutputType.dwChannelMask = X6DOT1; - break; - case DevFmtX71: - OutputType.Format.nChannels = 8; - OutputType.dwChannelMask = X7DOT1; - break; - } - switch(mDevice->FmtType) - { - case DevFmtByte: - mDevice->FmtType = DevFmtUByte; - /* fall-through */ - case DevFmtUByte: - OutputType.Format.wBitsPerSample = 8; - OutputType.Samples.wValidBitsPerSample = 8; - OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM; - break; - case DevFmtUShort: - mDevice->FmtType = DevFmtShort; - /* fall-through */ - case DevFmtShort: - OutputType.Format.wBitsPerSample = 16; - OutputType.Samples.wValidBitsPerSample = 16; - OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM; - break; - case DevFmtUInt: - mDevice->FmtType = DevFmtInt; - /* fall-through */ - case DevFmtInt: - OutputType.Format.wBitsPerSample = 32; - OutputType.Samples.wValidBitsPerSample = 32; - OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM; - break; - case DevFmtFloat: - OutputType.Format.wBitsPerSample = 32; - OutputType.Samples.wValidBitsPerSample = 32; - OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT; - break; - } - OutputType.Format.nSamplesPerSec = mDevice->Frequency; - - OutputType.Format.nBlockAlign = static_cast(OutputType.Format.nChannels * - OutputType.Format.wBitsPerSample / 8); - OutputType.Format.nAvgBytesPerSec = OutputType.Format.nSamplesPerSec * - OutputType.Format.nBlockAlign; - - TraceFormat("Requesting playback format", &OutputType.Format); - hr = mClient->IsFormatSupported(AUDCLNT_SHAREMODE_SHARED, &OutputType.Format, &wfx); - if(FAILED(hr)) - { - ERR("Failed to check format support: 0x%08lx\n", hr); - hr = mClient->GetMixFormat(&wfx); - } - if(FAILED(hr)) - { - ERR("Failed to find a supported format: 0x%08lx\n", hr); - return hr; - } - - if(wfx != nullptr) - { - TraceFormat("Got playback format", wfx); - if(!MakeExtensible(&OutputType, wfx)) - { - CoTaskMemFree(wfx); - return E_FAIL; - } - CoTaskMemFree(wfx); - wfx = nullptr; - - mDevice->Frequency = OutputType.Format.nSamplesPerSec; - const uint32_t chancount{OutputType.Format.nChannels}; - const DWORD chanmask{OutputType.dwChannelMask}; - if(chancount >= 8 && (chanmask&X71Mask) == X7DOT1) - mDevice->FmtChans = DevFmtX71; - else if(chancount >= 7 && (chanmask&X61Mask) == X6DOT1) - mDevice->FmtChans = DevFmtX61; - else if(chancount >= 6 && (chanmask&X51Mask) == X5DOT1) - mDevice->FmtChans = DevFmtX51; - else if(chancount >= 6 && (chanmask&X51RearMask) == X5DOT1REAR) - mDevice->FmtChans = DevFmtX51Rear; - else if(chancount >= 4 && (chanmask&QuadMask) == QUAD) - mDevice->FmtChans = DevFmtQuad; - else if(chancount >= 2 && (chanmask&StereoMask) == STEREO) - mDevice->FmtChans = DevFmtStereo; - else if(chancount >= 1 && (chanmask&MonoMask) == MONO) - mDevice->FmtChans = DevFmtMono; - else - { - ERR("Unhandled extensible channels: %d -- 0x%08lx\n", OutputType.Format.nChannels, - OutputType.dwChannelMask); - mDevice->FmtChans = DevFmtStereo; - OutputType.Format.nChannels = 2; - OutputType.dwChannelMask = STEREO; - } - - if(IsEqualGUID(OutputType.SubFormat, KSDATAFORMAT_SUBTYPE_PCM)) - { - if(OutputType.Format.wBitsPerSample == 8) - mDevice->FmtType = DevFmtUByte; - else if(OutputType.Format.wBitsPerSample == 16) - mDevice->FmtType = DevFmtShort; - else if(OutputType.Format.wBitsPerSample == 32) - mDevice->FmtType = DevFmtInt; - else - { - mDevice->FmtType = DevFmtShort; - OutputType.Format.wBitsPerSample = 16; - } - } - else if(IsEqualGUID(OutputType.SubFormat, KSDATAFORMAT_SUBTYPE_IEEE_FLOAT)) - { - mDevice->FmtType = DevFmtFloat; - OutputType.Format.wBitsPerSample = 32; - } - else - { - ERR("Unhandled format sub-type: %s\n", GuidPrinter{OutputType.SubFormat}.c_str()); - mDevice->FmtType = DevFmtShort; - if(OutputType.Format.wFormatTag != WAVE_FORMAT_EXTENSIBLE) - OutputType.Format.wFormatTag = WAVE_FORMAT_PCM; - OutputType.Format.wBitsPerSample = 16; - OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM; - } - OutputType.Samples.wValidBitsPerSample = OutputType.Format.wBitsPerSample; - } - mFrameStep = OutputType.Format.nChannels; - - EndpointFormFactor formfactor{UnknownFormFactor}; - get_device_formfactor(mMMDev.get(), &formfactor); - mDevice->IsHeadphones = (mDevice->FmtChans == DevFmtStereo - && (formfactor == Headphones || formfactor == Headset)); - - setChannelOrderFromWFXMask(OutputType.dwChannelMask); - - hr = mClient->Initialize(AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_EVENTCALLBACK, - buf_time.count(), 0, &OutputType.Format, nullptr); - if(FAILED(hr)) - { - ERR("Failed to initialize audio client: 0x%08lx\n", hr); - return hr; - } - - UINT32 buffer_len{}; - ReferenceTime min_per{}; - hr = mClient->GetDevicePeriod(&reinterpret_cast(min_per), nullptr); - if(SUCCEEDED(hr)) - hr = mClient->GetBufferSize(&buffer_len); - if(FAILED(hr)) - { - ERR("Failed to get audio buffer info: 0x%08lx\n", hr); - return hr; - } - - /* Find the nearest multiple of the period size to the update size */ - if(min_per < per_time) - min_per *= maxi64((per_time + min_per/2) / min_per, 1); - mDevice->UpdateSize = minu(RefTime2Samples(min_per, mDevice->Frequency), buffer_len/2); - mDevice->BufferSize = buffer_len; - - hr = mClient->SetEventHandle(mNotifyEvent); - if(FAILED(hr)) - { - ERR("Failed to set event handle: 0x%08lx\n", hr); - return hr; - } - - return hr; -} - - -void WasapiPlayback::start() -{ - const HRESULT hr{pushMessage(MsgType::StartDevice).get()}; - if(FAILED(hr)) - throw al::backend_exception{al::backend_error::DeviceError, - "Failed to start playback: 0x%lx", hr}; -} - -HRESULT WasapiPlayback::startProxy() -{ - ResetEvent(mNotifyEvent); - - HRESULT hr{mClient->Start()}; - if(FAILED(hr)) - { - ERR("Failed to start audio client: 0x%08lx\n", hr); - return hr; - } - - void *ptr; - hr = mClient->GetService(IID_IAudioRenderClient, &ptr); - if(SUCCEEDED(hr)) - { - mRender = ComPtr{static_cast(ptr)}; - try { - mKillNow.store(false, std::memory_order_release); - mThread = std::thread{std::mem_fn(&WasapiPlayback::mixerProc), this}; - } - catch(...) { - mRender = nullptr; - ERR("Failed to start thread\n"); - hr = E_FAIL; - } - } - - if(FAILED(hr)) - mClient->Stop(); - - return hr; -} - - -void WasapiPlayback::stop() -{ pushMessage(MsgType::StopDevice).wait(); } - -void WasapiPlayback::stopProxy() -{ - if(!mRender || !mThread.joinable()) - return; - - mKillNow.store(true, std::memory_order_release); - mThread.join(); - - mRender = nullptr; - mClient->Stop(); -} - - -ClockLatency WasapiPlayback::getClockLatency() -{ - ClockLatency ret; - - std::lock_guard _{mMutex}; - ret.ClockTime = GetDeviceClockTime(mDevice); - ret.Latency = std::chrono::seconds{mPadding.load(std::memory_order_relaxed)}; - ret.Latency /= mDevice->Frequency; - - return ret; -} - - -struct WasapiCapture final : public BackendBase, WasapiProxy { - WasapiCapture(ALCdevice *device) noexcept : BackendBase{device} { } - ~WasapiCapture() override; - - int recordProc(); - - void open(const char *name) override; - HRESULT openProxy() override; - void closeProxy() override; - - HRESULT resetProxy() override; - void start() override; - HRESULT startProxy() override; - void stop() override; - void stopProxy() override; - - void captureSamples(al::byte *buffer, uint samples) override; - uint availableSamples() override; - - std::wstring mDevId; - - HRESULT mOpenStatus{E_FAIL}; - ComPtr mMMDev{nullptr}; - ComPtr mClient{nullptr}; - ComPtr mCapture{nullptr}; - HANDLE mNotifyEvent{nullptr}; - - ChannelConverter mChannelConv{}; - SampleConverterPtr mSampleConv; - RingBufferPtr mRing; - - std::atomic mKillNow{true}; - std::thread mThread; - - DEF_NEWDEL(WasapiCapture) -}; - -WasapiCapture::~WasapiCapture() -{ - if(SUCCEEDED(mOpenStatus)) - pushMessage(MsgType::CloseDevice).wait(); - mOpenStatus = E_FAIL; - - if(mNotifyEvent != nullptr) - CloseHandle(mNotifyEvent); - mNotifyEvent = nullptr; -} - - -FORCE_ALIGN int WasapiCapture::recordProc() -{ - HRESULT hr{CoInitializeEx(nullptr, COINIT_MULTITHREADED)}; - if(FAILED(hr)) - { - ERR("CoInitializeEx(nullptr, COINIT_MULTITHREADED) failed: 0x%08lx\n", hr); - mDevice->handleDisconnect("COM init failed: 0x%08lx", hr); - return 1; - } - - althrd_setname(RECORD_THREAD_NAME); - - al::vector samples; - while(!mKillNow.load(std::memory_order_relaxed)) - { - UINT32 avail; - hr = mCapture->GetNextPacketSize(&avail); - if(FAILED(hr)) - ERR("Failed to get next packet size: 0x%08lx\n", hr); - else if(avail > 0) - { - UINT32 numsamples; - DWORD flags; - BYTE *rdata; - - hr = mCapture->GetBuffer(&rdata, &numsamples, &flags, nullptr, nullptr); - if(FAILED(hr)) - ERR("Failed to get capture buffer: 0x%08lx\n", hr); - else - { - if(mChannelConv.is_active()) - { - samples.resize(numsamples*2); - mChannelConv.convert(rdata, samples.data(), numsamples); - rdata = reinterpret_cast(samples.data()); - } - - auto data = mRing->getWriteVector(); - - size_t dstframes; - if(mSampleConv) - { - const void *srcdata{rdata}; - uint srcframes{numsamples}; - - dstframes = mSampleConv->convert(&srcdata, &srcframes, data.first.buf, - static_cast(minz(data.first.len, INT_MAX))); - if(srcframes > 0 && dstframes == data.first.len && data.second.len > 0) - { - /* If some source samples remain, all of the first dest - * block was filled, and there's space in the second - * dest block, do another run for the second block. - */ - dstframes += mSampleConv->convert(&srcdata, &srcframes, data.second.buf, - static_cast(minz(data.second.len, INT_MAX))); - } - } - else - { - const uint framesize{mDevice->frameSizeFromFmt()}; - size_t len1{minz(data.first.len, numsamples)}; - size_t len2{minz(data.second.len, numsamples-len1)}; - - memcpy(data.first.buf, rdata, len1*framesize); - if(len2 > 0) - memcpy(data.second.buf, rdata+len1*framesize, len2*framesize); - dstframes = len1 + len2; - } - - mRing->writeAdvance(dstframes); - - hr = mCapture->ReleaseBuffer(numsamples); - if(FAILED(hr)) ERR("Failed to release capture buffer: 0x%08lx\n", hr); - } - } - - if(FAILED(hr)) - { - mDevice->handleDisconnect("Failed to capture samples: 0x%08lx", hr); - break; - } - - DWORD res{WaitForSingleObjectEx(mNotifyEvent, 2000, FALSE)}; - if(res != WAIT_OBJECT_0) - ERR("WaitForSingleObjectEx error: 0x%lx\n", res); - } - - CoUninitialize(); - return 0; -} - - -void WasapiCapture::open(const char *name) -{ - HRESULT hr{S_OK}; - - mNotifyEvent = CreateEventW(nullptr, FALSE, FALSE, nullptr); - if(mNotifyEvent == nullptr) - { - ERR("Failed to create notify event: %lu\n", GetLastError()); - hr = E_FAIL; - } - - if(SUCCEEDED(hr)) - { - if(name) - { - if(CaptureDevices.empty()) - pushMessage(MsgType::EnumerateCapture).wait(); - - hr = E_FAIL; - auto iter = std::find_if(CaptureDevices.cbegin(), CaptureDevices.cend(), - [name](const DevMap &entry) -> bool - { return entry.name == name || entry.endpoint_guid == name; }); - if(iter == CaptureDevices.cend()) - { - const std::wstring wname{utf8_to_wstr(name)}; - iter = std::find_if(CaptureDevices.cbegin(), CaptureDevices.cend(), - [&wname](const DevMap &entry) -> bool - { return entry.devid == wname; }); - } - if(iter == CaptureDevices.cend()) - WARN("Failed to find device name matching \"%s\"\n", name); - else - { - mDevId = iter->devid; - mDevice->DeviceName = iter->name; - hr = S_OK; - } - } - } - - if(SUCCEEDED(hr)) - hr = pushMessage(MsgType::OpenDevice).get(); - mOpenStatus = hr; - - if(FAILED(hr)) - { - if(mNotifyEvent != nullptr) - CloseHandle(mNotifyEvent); - mNotifyEvent = nullptr; - - mDevId.clear(); - - throw al::backend_exception{al::backend_error::DeviceError, "Device init failed: 0x%08lx", - hr}; - } - - hr = pushMessage(MsgType::ResetDevice).get(); - if(FAILED(hr)) - { - if(hr == E_OUTOFMEMORY) - throw al::backend_exception{al::backend_error::OutOfMemory, "Out of memory"}; - throw al::backend_exception{al::backend_error::DeviceError, "Device reset failed"}; - } -} - -HRESULT WasapiCapture::openProxy() -{ - void *ptr; - HRESULT hr{CoCreateInstance(CLSID_MMDeviceEnumerator, nullptr, CLSCTX_INPROC_SERVER, - IID_IMMDeviceEnumerator, &ptr)}; - if(SUCCEEDED(hr)) - { - ComPtr enumerator{static_cast(ptr)}; - if(mDevId.empty()) - hr = enumerator->GetDefaultAudioEndpoint(eCapture, eMultimedia, mMMDev.getPtr()); - else - hr = enumerator->GetDevice(mDevId.c_str(), mMMDev.getPtr()); - } - if(SUCCEEDED(hr)) - hr = mMMDev->Activate(IID_IAudioClient, CLSCTX_INPROC_SERVER, nullptr, &ptr); - if(SUCCEEDED(hr)) - { - mClient = ComPtr{static_cast(ptr)}; - if(mDevice->DeviceName.empty()) - mDevice->DeviceName = get_device_name_and_guid(mMMDev.get()).first; - } - - if(FAILED(hr)) - mMMDev = nullptr; - - return hr; -} - -void WasapiCapture::closeProxy() -{ - mClient = nullptr; - mMMDev = nullptr; -} - -HRESULT WasapiCapture::resetProxy() -{ - mClient = nullptr; - - void *ptr; - HRESULT hr{mMMDev->Activate(IID_IAudioClient, CLSCTX_INPROC_SERVER, nullptr, &ptr)}; - if(FAILED(hr)) - { - ERR("Failed to reactivate audio client: 0x%08lx\n", hr); - return hr; - } - mClient = ComPtr{static_cast(ptr)}; - - // Make sure buffer is at least 100ms in size - ReferenceTime buf_time{ReferenceTime{seconds{mDevice->BufferSize}} / mDevice->Frequency}; - buf_time = std::max(buf_time, ReferenceTime{milliseconds{100}}); - - WAVEFORMATEXTENSIBLE InputType{}; - InputType.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE; - switch(mDevice->FmtChans) - { - case DevFmtMono: - InputType.Format.nChannels = 1; - InputType.dwChannelMask = MONO; - break; - case DevFmtStereo: - InputType.Format.nChannels = 2; - InputType.dwChannelMask = STEREO; - break; - case DevFmtQuad: - InputType.Format.nChannels = 4; - InputType.dwChannelMask = QUAD; - break; - case DevFmtX51: - InputType.Format.nChannels = 6; - InputType.dwChannelMask = X5DOT1; - break; - case DevFmtX51Rear: - InputType.Format.nChannels = 6; - InputType.dwChannelMask = X5DOT1REAR; - break; - case DevFmtX61: - InputType.Format.nChannels = 7; - InputType.dwChannelMask = X6DOT1; - break; - case DevFmtX71: - InputType.Format.nChannels = 8; - InputType.dwChannelMask = X7DOT1; - break; - - case DevFmtAmbi3D: - return E_FAIL; - } - switch(mDevice->FmtType) - { - /* NOTE: Signedness doesn't matter, the converter will handle it. */ - case DevFmtByte: - case DevFmtUByte: - InputType.Format.wBitsPerSample = 8; - InputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM; - break; - case DevFmtShort: - case DevFmtUShort: - InputType.Format.wBitsPerSample = 16; - InputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM; - break; - case DevFmtInt: - case DevFmtUInt: - InputType.Format.wBitsPerSample = 32; - InputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM; - break; - case DevFmtFloat: - InputType.Format.wBitsPerSample = 32; - InputType.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT; - break; - } - InputType.Samples.wValidBitsPerSample = InputType.Format.wBitsPerSample; - InputType.Format.nSamplesPerSec = mDevice->Frequency; - - InputType.Format.nBlockAlign = static_cast(InputType.Format.nChannels * - InputType.Format.wBitsPerSample / 8); - InputType.Format.nAvgBytesPerSec = InputType.Format.nSamplesPerSec * - InputType.Format.nBlockAlign; - InputType.Format.cbSize = sizeof(InputType) - sizeof(InputType.Format); - - TraceFormat("Requesting capture format", &InputType.Format); - WAVEFORMATEX *wfx; - hr = mClient->IsFormatSupported(AUDCLNT_SHAREMODE_SHARED, &InputType.Format, &wfx); - if(FAILED(hr)) - { - ERR("Failed to check format support: 0x%08lx\n", hr); - return hr; - } - - mSampleConv = nullptr; - mChannelConv = {}; - - if(wfx != nullptr) - { - TraceFormat("Got capture format", wfx); - if(!MakeExtensible(&InputType, wfx)) - { - CoTaskMemFree(wfx); - return E_FAIL; - } - CoTaskMemFree(wfx); - wfx = nullptr; - - auto validate_fmt = [](ALCdevice *device, uint32_t chancount, DWORD chanmask) noexcept - -> bool - { - switch(device->FmtChans) - { - /* If the device wants mono, we can handle any input. */ - case DevFmtMono: - return true; - /* If the device wants stereo, we can handle mono or stereo input. */ - case DevFmtStereo: - return (chancount == 2 && (chanmask == 0 || (chanmask&StereoMask) == STEREO)) - || (chancount == 1 && (chanmask&MonoMask) == MONO); - /* Otherwise, the device must match the input type. */ - case DevFmtQuad: - return (chancount == 4 && (chanmask == 0 || (chanmask&QuadMask) == QUAD)); - /* 5.1 (Side) and 5.1 (Rear) are interchangeable here. */ - case DevFmtX51: - case DevFmtX51Rear: - return (chancount == 6 && (chanmask == 0 || (chanmask&X51Mask) == X5DOT1 - || (chanmask&X51RearMask) == X5DOT1REAR)); - case DevFmtX61: - return (chancount == 7 && (chanmask == 0 || (chanmask&X61Mask) == X6DOT1)); - case DevFmtX71: - return (chancount == 8 && (chanmask == 0 || (chanmask&X71Mask) == X7DOT1)); - case DevFmtAmbi3D: return (chanmask == 0 && device->channelsFromFmt()); - } - return false; - }; - if(!validate_fmt(mDevice, InputType.Format.nChannels, InputType.dwChannelMask)) - { - ERR("Failed to match format, wanted: %s %s %uhz, got: 0x%08lx mask %d channel%s %d-bit %luhz\n", - DevFmtChannelsString(mDevice->FmtChans), DevFmtTypeString(mDevice->FmtType), - mDevice->Frequency, InputType.dwChannelMask, InputType.Format.nChannels, - (InputType.Format.nChannels==1)?"":"s", InputType.Format.wBitsPerSample, - InputType.Format.nSamplesPerSec); - return E_FAIL; - } - } - - DevFmtType srcType{}; - if(IsEqualGUID(InputType.SubFormat, KSDATAFORMAT_SUBTYPE_PCM)) - { - if(InputType.Format.wBitsPerSample == 8) - srcType = DevFmtUByte; - else if(InputType.Format.wBitsPerSample == 16) - srcType = DevFmtShort; - else if(InputType.Format.wBitsPerSample == 32) - srcType = DevFmtInt; - else - { - ERR("Unhandled integer bit depth: %d\n", InputType.Format.wBitsPerSample); - return E_FAIL; - } - } - else if(IsEqualGUID(InputType.SubFormat, KSDATAFORMAT_SUBTYPE_IEEE_FLOAT)) - { - if(InputType.Format.wBitsPerSample == 32) - srcType = DevFmtFloat; - else - { - ERR("Unhandled float bit depth: %d\n", InputType.Format.wBitsPerSample); - return E_FAIL; - } - } - else - { - ERR("Unhandled format sub-type: %s\n", GuidPrinter{InputType.SubFormat}.c_str()); - return E_FAIL; - } - - if(mDevice->FmtChans == DevFmtMono && InputType.Format.nChannels != 1) - { - uint chanmask{(1u<FmtChans}; - TRACE("Created %s multichannel-to-mono converter\n", DevFmtTypeString(srcType)); - /* The channel converter always outputs float, so change the input type - * for the resampler/type-converter. - */ - srcType = DevFmtFloat; - } - else if(mDevice->FmtChans == DevFmtStereo && InputType.Format.nChannels == 1) - { - mChannelConv = ChannelConverter{srcType, 1, 0x1, mDevice->FmtChans}; - TRACE("Created %s mono-to-stereo converter\n", DevFmtTypeString(srcType)); - srcType = DevFmtFloat; - } - - if(mDevice->Frequency != InputType.Format.nSamplesPerSec || mDevice->FmtType != srcType) - { - mSampleConv = CreateSampleConverter(srcType, mDevice->FmtType, mDevice->channelsFromFmt(), - InputType.Format.nSamplesPerSec, mDevice->Frequency, Resampler::FastBSinc24); - if(!mSampleConv) - { - ERR("Failed to create converter for %s format, dst: %s %uhz, src: %s %luhz\n", - DevFmtChannelsString(mDevice->FmtChans), DevFmtTypeString(mDevice->FmtType), - mDevice->Frequency, DevFmtTypeString(srcType), InputType.Format.nSamplesPerSec); - return E_FAIL; - } - TRACE("Created converter for %s format, dst: %s %uhz, src: %s %luhz\n", - DevFmtChannelsString(mDevice->FmtChans), DevFmtTypeString(mDevice->FmtType), - mDevice->Frequency, DevFmtTypeString(srcType), InputType.Format.nSamplesPerSec); - } - - hr = mClient->Initialize(AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_EVENTCALLBACK, - buf_time.count(), 0, &InputType.Format, nullptr); - if(FAILED(hr)) - { - ERR("Failed to initialize audio client: 0x%08lx\n", hr); - return hr; - } - - UINT32 buffer_len{}; - ReferenceTime min_per{}; - hr = mClient->GetDevicePeriod(&reinterpret_cast(min_per), nullptr); - if(SUCCEEDED(hr)) - hr = mClient->GetBufferSize(&buffer_len); - if(FAILED(hr)) - { - ERR("Failed to get buffer size: 0x%08lx\n", hr); - return hr; - } - mDevice->UpdateSize = RefTime2Samples(min_per, mDevice->Frequency); - mDevice->BufferSize = buffer_len; - - mRing = RingBuffer::Create(buffer_len, mDevice->frameSizeFromFmt(), false); - - hr = mClient->SetEventHandle(mNotifyEvent); - if(FAILED(hr)) - { - ERR("Failed to set event handle: 0x%08lx\n", hr); - return hr; - } - - return hr; -} - - -void WasapiCapture::start() -{ - const HRESULT hr{pushMessage(MsgType::StartDevice).get()}; - if(FAILED(hr)) - throw al::backend_exception{al::backend_error::DeviceError, - "Failed to start recording: 0x%lx", hr}; -} - -HRESULT WasapiCapture::startProxy() -{ - ResetEvent(mNotifyEvent); - - HRESULT hr{mClient->Start()}; - if(FAILED(hr)) - { - ERR("Failed to start audio client: 0x%08lx\n", hr); - return hr; - } - - void *ptr; - hr = mClient->GetService(IID_IAudioCaptureClient, &ptr); - if(SUCCEEDED(hr)) - { - mCapture = ComPtr{static_cast(ptr)}; - try { - mKillNow.store(false, std::memory_order_release); - mThread = std::thread{std::mem_fn(&WasapiCapture::recordProc), this}; - } - catch(...) { - mCapture = nullptr; - ERR("Failed to start thread\n"); - hr = E_FAIL; - } - } - - if(FAILED(hr)) - { - mClient->Stop(); - mClient->Reset(); - } - - return hr; -} - - -void WasapiCapture::stop() -{ pushMessage(MsgType::StopDevice).wait(); } - -void WasapiCapture::stopProxy() -{ - if(!mCapture || !mThread.joinable()) - return; - - mKillNow.store(true, std::memory_order_release); - mThread.join(); - - mCapture = nullptr; - mClient->Stop(); - mClient->Reset(); -} - - -void WasapiCapture::captureSamples(al::byte *buffer, uint samples) -{ mRing->read(buffer, samples); } - -uint WasapiCapture::availableSamples() -{ return static_cast(mRing->readSpace()); } - -} // namespace - - -bool WasapiBackendFactory::init() -{ - static HRESULT InitResult{E_FAIL}; - - if(FAILED(InitResult)) try - { - std::promise promise; - auto future = promise.get_future(); - - std::thread{&WasapiProxy::messageHandler, &promise}.detach(); - InitResult = future.get(); - } - catch(...) { - } - - return SUCCEEDED(InitResult); -} - -bool WasapiBackendFactory::querySupport(BackendType type) -{ return type == BackendType::Playback || type == BackendType::Capture; } - -std::string WasapiBackendFactory::probe(BackendType type) -{ - std::string outnames; - auto add_device = [&outnames](const DevMap &entry) -> void - { - /* +1 to also append the null char (to ensure a null-separated list and - * double-null terminated list). - */ - outnames.append(entry.name.c_str(), entry.name.length()+1); - }; - - switch(type) - { - case BackendType::Playback: - WasapiProxy::pushMessageStatic(MsgType::EnumeratePlayback).wait(); - std::for_each(PlaybackDevices.cbegin(), PlaybackDevices.cend(), add_device); - break; - - case BackendType::Capture: - WasapiProxy::pushMessageStatic(MsgType::EnumerateCapture).wait(); - std::for_each(CaptureDevices.cbegin(), CaptureDevices.cend(), add_device); - break; - } - - return outnames; -} - -BackendPtr WasapiBackendFactory::createBackend(ALCdevice *device, BackendType type) -{ - if(type == BackendType::Playback) - return BackendPtr{new WasapiPlayback{device}}; - if(type == BackendType::Capture) - return BackendPtr{new WasapiCapture{device}}; - return nullptr; -} - -BackendFactory &WasapiBackendFactory::getFactory() -{ - static WasapiBackendFactory factory{}; - return factory; -} diff --git a/alc/backends/wasapi.h b/alc/backends/wasapi.h deleted file mode 100644 index 97143c1a..00000000 --- a/alc/backends/wasapi.h +++ /dev/null @@ -1,19 +0,0 @@ -#ifndef BACKENDS_WASAPI_H -#define BACKENDS_WASAPI_H - -#include "backends/base.h" - -struct WasapiBackendFactory final : public BackendFactory { -public: - bool init() override; - - bool querySupport(BackendType type) override; - - std::string probe(BackendType type) override; - - BackendPtr createBackend(ALCdevice *device, BackendType type) override; - - static BackendFactory &getFactory(); -}; - -#endif /* BACKENDS_WASAPI_H */ diff --git a/alc/backends/wave.cpp b/alc/backends/wave.cpp deleted file mode 100644 index afff1d56..00000000 --- a/alc/backends/wave.cpp +++ /dev/null @@ -1,405 +0,0 @@ -/** - * OpenAL cross platform audio library - * Copyright (C) 1999-2007 by authors. - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - * Or go to http://www.gnu.org/copyleft/lgpl.html - */ - -#include "config.h" - -#include "backends/wave.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "albit.h" -#include "albyte.h" -#include "alcmain.h" -#include "alconfig.h" -#include "almalloc.h" -#include "alnumeric.h" -#include "alu.h" -#include "compat.h" -#include "core/logging.h" -#include "strutils.h" -#include "threads.h" -#include "vector.h" - - -namespace { - -using std::chrono::seconds; -using std::chrono::milliseconds; -using std::chrono::nanoseconds; - -using ubyte = unsigned char; -using ushort = unsigned short; - -constexpr char waveDevice[] = "Wave File Writer"; - -constexpr ubyte SUBTYPE_PCM[]{ - 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xaa, - 0x00, 0x38, 0x9b, 0x71 -}; -constexpr ubyte SUBTYPE_FLOAT[]{ - 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xaa, - 0x00, 0x38, 0x9b, 0x71 -}; - -constexpr ubyte SUBTYPE_BFORMAT_PCM[]{ - 0x01, 0x00, 0x00, 0x00, 0x21, 0x07, 0xd3, 0x11, 0x86, 0x44, 0xc8, 0xc1, - 0xca, 0x00, 0x00, 0x00 -}; - -constexpr ubyte SUBTYPE_BFORMAT_FLOAT[]{ - 0x03, 0x00, 0x00, 0x00, 0x21, 0x07, 0xd3, 0x11, 0x86, 0x44, 0xc8, 0xc1, - 0xca, 0x00, 0x00, 0x00 -}; - -void fwrite16le(ushort val, FILE *f) -{ - ubyte data[2]{ static_cast(val&0xff), static_cast((val>>8)&0xff) }; - fwrite(data, 1, 2, f); -} - -void fwrite32le(uint val, FILE *f) -{ - ubyte data[4]{ static_cast(val&0xff), static_cast((val>>8)&0xff), - static_cast((val>>16)&0xff), static_cast((val>>24)&0xff) }; - fwrite(data, 1, 4, f); -} - - -struct WaveBackend final : public BackendBase { - WaveBackend(ALCdevice *device) noexcept : BackendBase{device} { } - ~WaveBackend() override; - - int mixerProc(); - - void open(const char *name) override; - bool reset() override; - void start() override; - void stop() override; - - FILE *mFile{nullptr}; - long mDataStart{-1}; - - al::vector mBuffer; - - std::atomic mKillNow{true}; - std::thread mThread; - - DEF_NEWDEL(WaveBackend) -}; - -WaveBackend::~WaveBackend() -{ - if(mFile) - fclose(mFile); - mFile = nullptr; -} - -int WaveBackend::mixerProc() -{ - const milliseconds restTime{mDevice->UpdateSize*1000/mDevice->Frequency / 2}; - - althrd_setname(MIXER_THREAD_NAME); - - const size_t frameStep{mDevice->channelsFromFmt()}; - const size_t frameSize{mDevice->frameSizeFromFmt()}; - - int64_t done{0}; - auto start = std::chrono::steady_clock::now(); - while(!mKillNow.load(std::memory_order_acquire) && - mDevice->Connected.load(std::memory_order_acquire)) - { - auto now = std::chrono::steady_clock::now(); - - /* This converts from nanoseconds to nanosamples, then to samples. */ - int64_t avail{std::chrono::duration_cast((now-start) * - mDevice->Frequency).count()}; - if(avail-done < mDevice->UpdateSize) - { - std::this_thread::sleep_for(restTime); - continue; - } - while(avail-done >= mDevice->UpdateSize) - { - mDevice->renderSamples(mBuffer.data(), mDevice->UpdateSize, frameStep); - done += mDevice->UpdateSize; - - if /*constexpr*/(al::endian::native != al::endian::little) - { - const uint bytesize{mDevice->bytesFromFmt()}; - - if(bytesize == 2) - { - ushort *samples = reinterpret_cast(mBuffer.data()); - const size_t len{mBuffer.size() / 2}; - for(size_t i{0};i < len;i++) - { - const ushort samp{samples[i]}; - samples[i] = static_cast((samp>>8) | (samp<<8)); - } - } - else if(bytesize == 4) - { - uint *samples = reinterpret_cast(mBuffer.data()); - const size_t len{mBuffer.size() / 4}; - for(size_t i{0};i < len;i++) - { - const uint samp{samples[i]}; - samples[i] = (samp>>24) | ((samp>>8)&0x0000ff00) | - ((samp<<8)&0x00ff0000) | (samp<<24); - } - } - } - - const size_t fs{fwrite(mBuffer.data(), frameSize, mDevice->UpdateSize, mFile)}; - if(fs < mDevice->UpdateSize || ferror(mFile)) - { - ERR("Error writing to file\n"); - mDevice->handleDisconnect("Failed to write playback samples"); - break; - } - } - - /* For every completed second, increment the start time and reduce the - * samples done. This prevents the difference between the start time - * and current time from growing too large, while maintaining the - * correct number of samples to render. - */ - if(done >= mDevice->Frequency) - { - seconds s{done/mDevice->Frequency}; - done %= mDevice->Frequency; - start += s; - } - } - - return 0; -} - -void WaveBackend::open(const char *name) -{ - const char *fname{GetConfigValue(nullptr, "wave", "file", "")}; - if(!fname[0]) throw al::backend_exception{al::backend_error::NoDevice, - "No wave output filename"}; - - if(!name) - name = waveDevice; - else if(strcmp(name, waveDevice) != 0) - throw al::backend_exception{al::backend_error::NoDevice, "Device name \"%s\" not found", - name}; - -#ifdef _WIN32 - { - std::wstring wname = utf8_to_wstr(fname); - mFile = _wfopen(wname.c_str(), L"wb"); - } -#else - mFile = fopen(fname, "wb"); -#endif - if(!mFile) - throw al::backend_exception{al::backend_error::DeviceError, "Could not open file '%s': %s", - fname, strerror(errno)}; - - mDevice->DeviceName = name; -} - -bool WaveBackend::reset() -{ - uint channels{0}, bytes{0}, chanmask{0}; - bool isbformat{false}; - size_t val; - - fseek(mFile, 0, SEEK_SET); - clearerr(mFile); - - if(GetConfigValueBool(nullptr, "wave", "bformat", 0)) - { - mDevice->FmtChans = DevFmtAmbi3D; - mDevice->mAmbiOrder = 1; - } - - switch(mDevice->FmtType) - { - case DevFmtByte: - mDevice->FmtType = DevFmtUByte; - break; - case DevFmtUShort: - mDevice->FmtType = DevFmtShort; - break; - case DevFmtUInt: - mDevice->FmtType = DevFmtInt; - break; - case DevFmtUByte: - case DevFmtShort: - case DevFmtInt: - case DevFmtFloat: - break; - } - switch(mDevice->FmtChans) - { - case DevFmtMono: chanmask = 0x04; break; - case DevFmtStereo: chanmask = 0x01 | 0x02; break; - case DevFmtQuad: chanmask = 0x01 | 0x02 | 0x10 | 0x20; break; - case DevFmtX51: chanmask = 0x01 | 0x02 | 0x04 | 0x08 | 0x200 | 0x400; break; - case DevFmtX51Rear: chanmask = 0x01 | 0x02 | 0x04 | 0x08 | 0x010 | 0x020; break; - case DevFmtX61: chanmask = 0x01 | 0x02 | 0x04 | 0x08 | 0x100 | 0x200 | 0x400; break; - case DevFmtX71: chanmask = 0x01 | 0x02 | 0x04 | 0x08 | 0x010 | 0x020 | 0x200 | 0x400; break; - case DevFmtAmbi3D: - /* .amb output requires FuMa */ - mDevice->mAmbiOrder = minu(mDevice->mAmbiOrder, 3); - mDevice->mAmbiLayout = DevAmbiLayout::FuMa; - mDevice->mAmbiScale = DevAmbiScaling::FuMa; - isbformat = true; - chanmask = 0; - break; - } - bytes = mDevice->bytesFromFmt(); - channels = mDevice->channelsFromFmt(); - - rewind(mFile); - - fputs("RIFF", mFile); - fwrite32le(0xFFFFFFFF, mFile); // 'RIFF' header len; filled in at close - - fputs("WAVE", mFile); - - fputs("fmt ", mFile); - fwrite32le(40, mFile); // 'fmt ' header len; 40 bytes for EXTENSIBLE - - // 16-bit val, format type id (extensible: 0xFFFE) - fwrite16le(0xFFFE, mFile); - // 16-bit val, channel count - fwrite16le(static_cast(channels), mFile); - // 32-bit val, frequency - fwrite32le(mDevice->Frequency, mFile); - // 32-bit val, bytes per second - fwrite32le(mDevice->Frequency * channels * bytes, mFile); - // 16-bit val, frame size - fwrite16le(static_cast(channels * bytes), mFile); - // 16-bit val, bits per sample - fwrite16le(static_cast(bytes * 8), mFile); - // 16-bit val, extra byte count - fwrite16le(22, mFile); - // 16-bit val, valid bits per sample - fwrite16le(static_cast(bytes * 8), mFile); - // 32-bit val, channel mask - fwrite32le(chanmask, mFile); - // 16 byte GUID, sub-type format - val = fwrite((mDevice->FmtType == DevFmtFloat) ? - (isbformat ? SUBTYPE_BFORMAT_FLOAT : SUBTYPE_FLOAT) : - (isbformat ? SUBTYPE_BFORMAT_PCM : SUBTYPE_PCM), 1, 16, mFile); - (void)val; - - fputs("data", mFile); - fwrite32le(0xFFFFFFFF, mFile); // 'data' header len; filled in at close - - if(ferror(mFile)) - { - ERR("Error writing header: %s\n", strerror(errno)); - return false; - } - mDataStart = ftell(mFile); - - setDefaultWFXChannelOrder(); - - const uint bufsize{mDevice->frameSizeFromFmt() * mDevice->UpdateSize}; - mBuffer.resize(bufsize); - - return true; -} - -void WaveBackend::start() -{ - if(mDataStart > 0 && fseek(mFile, 0, SEEK_END) != 0) - WARN("Failed to seek on output file\n"); - try { - mKillNow.store(false, std::memory_order_release); - mThread = std::thread{std::mem_fn(&WaveBackend::mixerProc), this}; - } - catch(std::exception& e) { - throw al::backend_exception{al::backend_error::DeviceError, - "Failed to start mixing thread: %s", e.what()}; - } -} - -void WaveBackend::stop() -{ - if(mKillNow.exchange(true, std::memory_order_acq_rel) || !mThread.joinable()) - return; - mThread.join(); - - if(mDataStart > 0) - { - long size{ftell(mFile)}; - if(size > 0) - { - long dataLen{size - mDataStart}; - if(fseek(mFile, 4, SEEK_SET) == 0) - fwrite32le(static_cast(size-8), mFile); // 'WAVE' header len - if(fseek(mFile, mDataStart-4, SEEK_SET) == 0) - fwrite32le(static_cast(dataLen), mFile); // 'data' header len - } - } -} - -} // namespace - - -bool WaveBackendFactory::init() -{ return true; } - -bool WaveBackendFactory::querySupport(BackendType type) -{ return type == BackendType::Playback; } - -std::string WaveBackendFactory::probe(BackendType type) -{ - std::string outnames; - switch(type) - { - case BackendType::Playback: - /* Includes null char. */ - outnames.append(waveDevice, sizeof(waveDevice)); - break; - case BackendType::Capture: - break; - } - return outnames; -} - -BackendPtr WaveBackendFactory::createBackend(ALCdevice *device, BackendType type) -{ - if(type == BackendType::Playback) - return BackendPtr{new WaveBackend{device}}; - return nullptr; -} - -BackendFactory &WaveBackendFactory::getFactory() -{ - static WaveBackendFactory factory{}; - return factory; -} diff --git a/alc/backends/wave.h b/alc/backends/wave.h deleted file mode 100644 index 5719961f..00000000 --- a/alc/backends/wave.h +++ /dev/null @@ -1,19 +0,0 @@ -#ifndef BACKENDS_WAVE_H -#define BACKENDS_WAVE_H - -#include "backends/base.h" - -struct WaveBackendFactory final : public BackendFactory { -public: - bool init() override; - - bool querySupport(BackendType type) override; - - std::string probe(BackendType type) override; - - BackendPtr createBackend(ALCdevice *device, BackendType type) override; - - static BackendFactory &getFactory(); -}; - -#endif /* BACKENDS_WAVE_H */ diff --git a/alc/backends/winmm.cpp b/alc/backends/winmm.cpp deleted file mode 100644 index 9b88f12e..00000000 --- a/alc/backends/winmm.cpp +++ /dev/null @@ -1,631 +0,0 @@ -/** - * OpenAL cross platform audio library - * Copyright (C) 1999-2007 by authors. - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - * Or go to http://www.gnu.org/copyleft/lgpl.html - */ - -#include "config.h" - -#include "backends/winmm.h" - -#include -#include -#include - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -#include "alcmain.h" -#include "alu.h" -#include "compat.h" -#include "core/logging.h" -#include "ringbuffer.h" -#include "strutils.h" -#include "threads.h" - -#ifndef WAVE_FORMAT_IEEE_FLOAT -#define WAVE_FORMAT_IEEE_FLOAT 0x0003 -#endif - -namespace { - -#define DEVNAME_HEAD "OpenAL Soft on " - - -al::vector PlaybackDevices; -al::vector CaptureDevices; - -bool checkName(const al::vector &list, const std::string &name) -{ return std::find(list.cbegin(), list.cend(), name) != list.cend(); } - -void ProbePlaybackDevices(void) -{ - PlaybackDevices.clear(); - - UINT numdevs{waveOutGetNumDevs()}; - PlaybackDevices.reserve(numdevs); - for(UINT i{0};i < numdevs;++i) - { - std::string dname; - - WAVEOUTCAPSW WaveCaps{}; - if(waveOutGetDevCapsW(i, &WaveCaps, sizeof(WaveCaps)) == MMSYSERR_NOERROR) - { - const std::string basename{DEVNAME_HEAD + wstr_to_utf8(WaveCaps.szPname)}; - - int count{1}; - std::string newname{basename}; - while(checkName(PlaybackDevices, newname)) - { - newname = basename; - newname += " #"; - newname += std::to_string(++count); - } - dname = std::move(newname); - - TRACE("Got device \"%s\", ID %u\n", dname.c_str(), i); - } - PlaybackDevices.emplace_back(std::move(dname)); - } -} - -void ProbeCaptureDevices(void) -{ - CaptureDevices.clear(); - - UINT numdevs{waveInGetNumDevs()}; - CaptureDevices.reserve(numdevs); - for(UINT i{0};i < numdevs;++i) - { - std::string dname; - - WAVEINCAPSW WaveCaps{}; - if(waveInGetDevCapsW(i, &WaveCaps, sizeof(WaveCaps)) == MMSYSERR_NOERROR) - { - const std::string basename{DEVNAME_HEAD + wstr_to_utf8(WaveCaps.szPname)}; - - int count{1}; - std::string newname{basename}; - while(checkName(CaptureDevices, newname)) - { - newname = basename; - newname += " #"; - newname += std::to_string(++count); - } - dname = std::move(newname); - - TRACE("Got device \"%s\", ID %u\n", dname.c_str(), i); - } - CaptureDevices.emplace_back(std::move(dname)); - } -} - - -struct WinMMPlayback final : public BackendBase { - WinMMPlayback(ALCdevice *device) noexcept : BackendBase{device} { } - ~WinMMPlayback() override; - - void CALLBACK waveOutProc(HWAVEOUT device, UINT msg, DWORD_PTR param1, DWORD_PTR param2) noexcept; - static void CALLBACK waveOutProcC(HWAVEOUT device, UINT msg, DWORD_PTR instance, DWORD_PTR param1, DWORD_PTR param2) noexcept - { reinterpret_cast(instance)->waveOutProc(device, msg, param1, param2); } - - int mixerProc(); - - void open(const char *name) override; - bool reset() override; - void start() override; - void stop() override; - - std::atomic mWritable{0u}; - al::semaphore mSem; - uint mIdx{0u}; - std::array mWaveBuffer{}; - - HWAVEOUT mOutHdl{nullptr}; - - WAVEFORMATEX mFormat{}; - - std::atomic mKillNow{true}; - std::thread mThread; - - DEF_NEWDEL(WinMMPlayback) -}; - -WinMMPlayback::~WinMMPlayback() -{ - if(mOutHdl) - waveOutClose(mOutHdl); - mOutHdl = nullptr; - - al_free(mWaveBuffer[0].lpData); - std::fill(mWaveBuffer.begin(), mWaveBuffer.end(), WAVEHDR{}); -} - -/* WinMMPlayback::waveOutProc - * - * Posts a message to 'WinMMPlayback::mixerProc' everytime a WaveOut Buffer is - * completed and returns to the application (for more data) - */ -void CALLBACK WinMMPlayback::waveOutProc(HWAVEOUT, UINT msg, DWORD_PTR, DWORD_PTR) noexcept -{ - if(msg != WOM_DONE) return; - mWritable.fetch_add(1, std::memory_order_acq_rel); - mSem.post(); -} - -FORCE_ALIGN int WinMMPlayback::mixerProc() -{ - SetRTPriority(); - althrd_setname(MIXER_THREAD_NAME); - - const size_t frame_step{mDevice->channelsFromFmt()}; - - while(!mKillNow.load(std::memory_order_acquire) - && mDevice->Connected.load(std::memory_order_acquire)) - { - uint todo{mWritable.load(std::memory_order_acquire)}; - if(todo < 1) - { - mSem.wait(); - continue; - } - - size_t widx{mIdx}; - do { - WAVEHDR &waveHdr = mWaveBuffer[widx]; - widx = (widx+1) % mWaveBuffer.size(); - - mDevice->renderSamples(waveHdr.lpData, mDevice->UpdateSize, frame_step); - mWritable.fetch_sub(1, std::memory_order_acq_rel); - waveOutWrite(mOutHdl, &waveHdr, sizeof(WAVEHDR)); - } while(--todo); - mIdx = static_cast(widx); - } - - return 0; -} - - -void WinMMPlayback::open(const char *name) -{ - if(PlaybackDevices.empty()) - ProbePlaybackDevices(); - - // Find the Device ID matching the deviceName if valid - auto iter = name ? - std::find(PlaybackDevices.cbegin(), PlaybackDevices.cend(), name) : - PlaybackDevices.cbegin(); - if(iter == PlaybackDevices.cend()) - throw al::backend_exception{al::backend_error::NoDevice, "Device name \"%s\" not found", - name}; - auto DeviceID = static_cast(std::distance(PlaybackDevices.cbegin(), iter)); - -retry_open: - mFormat = WAVEFORMATEX{}; - if(mDevice->FmtType == DevFmtFloat) - { - mFormat.wFormatTag = WAVE_FORMAT_IEEE_FLOAT; - mFormat.wBitsPerSample = 32; - } - else - { - mFormat.wFormatTag = WAVE_FORMAT_PCM; - if(mDevice->FmtType == DevFmtUByte || mDevice->FmtType == DevFmtByte) - mFormat.wBitsPerSample = 8; - else - mFormat.wBitsPerSample = 16; - } - mFormat.nChannels = ((mDevice->FmtChans == DevFmtMono) ? 1 : 2); - mFormat.nBlockAlign = static_cast(mFormat.wBitsPerSample * mFormat.nChannels / 8); - mFormat.nSamplesPerSec = mDevice->Frequency; - mFormat.nAvgBytesPerSec = mFormat.nSamplesPerSec * mFormat.nBlockAlign; - mFormat.cbSize = 0; - - MMRESULT res{waveOutOpen(&mOutHdl, DeviceID, &mFormat, - reinterpret_cast(&WinMMPlayback::waveOutProcC), - reinterpret_cast(this), CALLBACK_FUNCTION)}; - if(res != MMSYSERR_NOERROR) - { - if(mDevice->FmtType == DevFmtFloat) - { - mDevice->FmtType = DevFmtShort; - goto retry_open; - } - throw al::backend_exception{al::backend_error::DeviceError, "waveOutOpen failed: %u", res}; - } - - mDevice->DeviceName = PlaybackDevices[DeviceID]; -} - -bool WinMMPlayback::reset() -{ - mDevice->BufferSize = static_cast(uint64_t{mDevice->BufferSize} * - mFormat.nSamplesPerSec / mDevice->Frequency); - mDevice->BufferSize = (mDevice->BufferSize+3) & ~0x3u; - mDevice->UpdateSize = mDevice->BufferSize / 4; - mDevice->Frequency = mFormat.nSamplesPerSec; - - if(mFormat.wFormatTag == WAVE_FORMAT_IEEE_FLOAT) - { - if(mFormat.wBitsPerSample == 32) - mDevice->FmtType = DevFmtFloat; - else - { - ERR("Unhandled IEEE float sample depth: %d\n", mFormat.wBitsPerSample); - return false; - } - } - else if(mFormat.wFormatTag == WAVE_FORMAT_PCM) - { - if(mFormat.wBitsPerSample == 16) - mDevice->FmtType = DevFmtShort; - else if(mFormat.wBitsPerSample == 8) - mDevice->FmtType = DevFmtUByte; - else - { - ERR("Unhandled PCM sample depth: %d\n", mFormat.wBitsPerSample); - return false; - } - } - else - { - ERR("Unhandled format tag: 0x%04x\n", mFormat.wFormatTag); - return false; - } - - uint chanmask{}; - if(mFormat.nChannels == 2) - { - mDevice->FmtChans = DevFmtStereo; - chanmask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; - } - else if(mFormat.nChannels == 1) - { - mDevice->FmtChans = DevFmtMono; - chanmask = SPEAKER_FRONT_CENTER; - } - else - { - ERR("Unhandled channel count: %d\n", mFormat.nChannels); - return false; - } - setChannelOrderFromWFXMask(chanmask); - - uint BufferSize{mDevice->UpdateSize * mDevice->frameSizeFromFmt()}; - - al_free(mWaveBuffer[0].lpData); - mWaveBuffer[0] = WAVEHDR{}; - mWaveBuffer[0].lpData = static_cast(al_calloc(16, BufferSize * mWaveBuffer.size())); - mWaveBuffer[0].dwBufferLength = BufferSize; - for(size_t i{1};i < mWaveBuffer.size();i++) - { - mWaveBuffer[i] = WAVEHDR{}; - mWaveBuffer[i].lpData = mWaveBuffer[i-1].lpData + mWaveBuffer[i-1].dwBufferLength; - mWaveBuffer[i].dwBufferLength = BufferSize; - } - mIdx = 0; - - return true; -} - -void WinMMPlayback::start() -{ - try { - std::for_each(mWaveBuffer.begin(), mWaveBuffer.end(), - [this](WAVEHDR &waveHdr) -> void - { waveOutPrepareHeader(mOutHdl, &waveHdr, sizeof(WAVEHDR)); }); - mWritable.store(static_cast(mWaveBuffer.size()), std::memory_order_release); - - mKillNow.store(false, std::memory_order_release); - mThread = std::thread{std::mem_fn(&WinMMPlayback::mixerProc), this}; - } - catch(std::exception& e) { - throw al::backend_exception{al::backend_error::DeviceError, - "Failed to start mixing thread: %s", e.what()}; - } -} - -void WinMMPlayback::stop() -{ - if(mKillNow.exchange(true, std::memory_order_acq_rel) || !mThread.joinable()) - return; - mThread.join(); - - while(mWritable.load(std::memory_order_acquire) < mWaveBuffer.size()) - mSem.wait(); - std::for_each(mWaveBuffer.begin(), mWaveBuffer.end(), - [this](WAVEHDR &waveHdr) -> void - { waveOutUnprepareHeader(mOutHdl, &waveHdr, sizeof(WAVEHDR)); }); - mWritable.store(0, std::memory_order_release); -} - - -struct WinMMCapture final : public BackendBase { - WinMMCapture(ALCdevice *device) noexcept : BackendBase{device} { } - ~WinMMCapture() override; - - void CALLBACK waveInProc(HWAVEIN device, UINT msg, DWORD_PTR param1, DWORD_PTR param2) noexcept; - static void CALLBACK waveInProcC(HWAVEIN device, UINT msg, DWORD_PTR instance, DWORD_PTR param1, DWORD_PTR param2) noexcept - { reinterpret_cast(instance)->waveInProc(device, msg, param1, param2); } - - int captureProc(); - - void open(const char *name) override; - void start() override; - void stop() override; - void captureSamples(al::byte *buffer, uint samples) override; - uint availableSamples() override; - - std::atomic mReadable{0u}; - al::semaphore mSem; - uint mIdx{0}; - std::array mWaveBuffer{}; - - HWAVEIN mInHdl{nullptr}; - - RingBufferPtr mRing{nullptr}; - - WAVEFORMATEX mFormat{}; - - std::atomic mKillNow{true}; - std::thread mThread; - - DEF_NEWDEL(WinMMCapture) -}; - -WinMMCapture::~WinMMCapture() -{ - // Close the Wave device - if(mInHdl) - waveInClose(mInHdl); - mInHdl = nullptr; - - al_free(mWaveBuffer[0].lpData); - std::fill(mWaveBuffer.begin(), mWaveBuffer.end(), WAVEHDR{}); -} - -/* WinMMCapture::waveInProc - * - * Posts a message to 'WinMMCapture::captureProc' everytime a WaveIn Buffer is - * completed and returns to the application (with more data). - */ -void CALLBACK WinMMCapture::waveInProc(HWAVEIN, UINT msg, DWORD_PTR, DWORD_PTR) noexcept -{ - if(msg != WIM_DATA) return; - mReadable.fetch_add(1, std::memory_order_acq_rel); - mSem.post(); -} - -int WinMMCapture::captureProc() -{ - althrd_setname(RECORD_THREAD_NAME); - - while(!mKillNow.load(std::memory_order_acquire) && - mDevice->Connected.load(std::memory_order_acquire)) - { - uint todo{mReadable.load(std::memory_order_acquire)}; - if(todo < 1) - { - mSem.wait(); - continue; - } - - size_t widx{mIdx}; - do { - WAVEHDR &waveHdr = mWaveBuffer[widx]; - widx = (widx+1) % mWaveBuffer.size(); - - mRing->write(waveHdr.lpData, waveHdr.dwBytesRecorded / mFormat.nBlockAlign); - mReadable.fetch_sub(1, std::memory_order_acq_rel); - waveInAddBuffer(mInHdl, &waveHdr, sizeof(WAVEHDR)); - } while(--todo); - mIdx = static_cast(widx); - } - - return 0; -} - - -void WinMMCapture::open(const char *name) -{ - if(CaptureDevices.empty()) - ProbeCaptureDevices(); - - // Find the Device ID matching the deviceName if valid - auto iter = name ? - std::find(CaptureDevices.cbegin(), CaptureDevices.cend(), name) : - CaptureDevices.cbegin(); - if(iter == CaptureDevices.cend()) - throw al::backend_exception{al::backend_error::NoDevice, "Device name \"%s\" not found", - name}; - auto DeviceID = static_cast(std::distance(CaptureDevices.cbegin(), iter)); - - switch(mDevice->FmtChans) - { - case DevFmtMono: - case DevFmtStereo: - break; - - case DevFmtQuad: - case DevFmtX51: - case DevFmtX51Rear: - case DevFmtX61: - case DevFmtX71: - case DevFmtAmbi3D: - throw al::backend_exception{al::backend_error::DeviceError, "%s capture not supported", - DevFmtChannelsString(mDevice->FmtChans)}; - } - - switch(mDevice->FmtType) - { - case DevFmtUByte: - case DevFmtShort: - case DevFmtInt: - case DevFmtFloat: - break; - - case DevFmtByte: - case DevFmtUShort: - case DevFmtUInt: - throw al::backend_exception{al::backend_error::DeviceError, "%s samples not supported", - DevFmtTypeString(mDevice->FmtType)}; - } - - mFormat = WAVEFORMATEX{}; - mFormat.wFormatTag = (mDevice->FmtType == DevFmtFloat) ? - WAVE_FORMAT_IEEE_FLOAT : WAVE_FORMAT_PCM; - mFormat.nChannels = static_cast(mDevice->channelsFromFmt()); - mFormat.wBitsPerSample = static_cast(mDevice->bytesFromFmt() * 8); - mFormat.nBlockAlign = static_cast(mFormat.wBitsPerSample * mFormat.nChannels / 8); - mFormat.nSamplesPerSec = mDevice->Frequency; - mFormat.nAvgBytesPerSec = mFormat.nSamplesPerSec * mFormat.nBlockAlign; - mFormat.cbSize = 0; - - MMRESULT res{waveInOpen(&mInHdl, DeviceID, &mFormat, - reinterpret_cast(&WinMMCapture::waveInProcC), - reinterpret_cast(this), CALLBACK_FUNCTION)}; - if(res != MMSYSERR_NOERROR) - throw al::backend_exception{al::backend_error::DeviceError, "waveInOpen failed: %u", res}; - - // Ensure each buffer is 50ms each - DWORD BufferSize{mFormat.nAvgBytesPerSec / 20u}; - BufferSize -= (BufferSize % mFormat.nBlockAlign); - - // Allocate circular memory buffer for the captured audio - // Make sure circular buffer is at least 100ms in size - uint CapturedDataSize{mDevice->BufferSize}; - CapturedDataSize = static_cast(maxz(CapturedDataSize, BufferSize*mWaveBuffer.size())); - - mRing = RingBuffer::Create(CapturedDataSize, mFormat.nBlockAlign, false); - - al_free(mWaveBuffer[0].lpData); - mWaveBuffer[0] = WAVEHDR{}; - mWaveBuffer[0].lpData = static_cast(al_calloc(16, BufferSize * mWaveBuffer.size())); - mWaveBuffer[0].dwBufferLength = BufferSize; - for(size_t i{1};i < mWaveBuffer.size();++i) - { - mWaveBuffer[i] = WAVEHDR{}; - mWaveBuffer[i].lpData = mWaveBuffer[i-1].lpData + mWaveBuffer[i-1].dwBufferLength; - mWaveBuffer[i].dwBufferLength = mWaveBuffer[i-1].dwBufferLength; - } - - mDevice->DeviceName = CaptureDevices[DeviceID]; -} - -void WinMMCapture::start() -{ - try { - for(size_t i{0};i < mWaveBuffer.size();++i) - { - waveInPrepareHeader(mInHdl, &mWaveBuffer[i], sizeof(WAVEHDR)); - waveInAddBuffer(mInHdl, &mWaveBuffer[i], sizeof(WAVEHDR)); - } - - mKillNow.store(false, std::memory_order_release); - mThread = std::thread{std::mem_fn(&WinMMCapture::captureProc), this}; - - waveInStart(mInHdl); - } - catch(std::exception& e) { - throw al::backend_exception{al::backend_error::DeviceError, - "Failed to start recording thread: %s", e.what()}; - } -} - -void WinMMCapture::stop() -{ - waveInStop(mInHdl); - - mKillNow.store(true, std::memory_order_release); - if(mThread.joinable()) - { - mSem.post(); - mThread.join(); - } - - waveInReset(mInHdl); - for(size_t i{0};i < mWaveBuffer.size();++i) - waveInUnprepareHeader(mInHdl, &mWaveBuffer[i], sizeof(WAVEHDR)); - - mReadable.store(0, std::memory_order_release); - mIdx = 0; -} - -void WinMMCapture::captureSamples(al::byte *buffer, uint samples) -{ mRing->read(buffer, samples); } - -uint WinMMCapture::availableSamples() -{ return static_cast(mRing->readSpace()); } - -} // namespace - - -bool WinMMBackendFactory::init() -{ return true; } - -bool WinMMBackendFactory::querySupport(BackendType type) -{ return type == BackendType::Playback || type == BackendType::Capture; } - -std::string WinMMBackendFactory::probe(BackendType type) -{ - std::string outnames; - auto add_device = [&outnames](const std::string &dname) -> void - { - /* +1 to also append the null char (to ensure a null-separated list and - * double-null terminated list). - */ - if(!dname.empty()) - outnames.append(dname.c_str(), dname.length()+1); - }; - switch(type) - { - case BackendType::Playback: - ProbePlaybackDevices(); - std::for_each(PlaybackDevices.cbegin(), PlaybackDevices.cend(), add_device); - break; - - case BackendType::Capture: - ProbeCaptureDevices(); - std::for_each(CaptureDevices.cbegin(), CaptureDevices.cend(), add_device); - break; - } - return outnames; -} - -BackendPtr WinMMBackendFactory::createBackend(ALCdevice *device, BackendType type) -{ - if(type == BackendType::Playback) - return BackendPtr{new WinMMPlayback{device}}; - if(type == BackendType::Capture) - return BackendPtr{new WinMMCapture{device}}; - return nullptr; -} - -BackendFactory &WinMMBackendFactory::getFactory() -{ - static WinMMBackendFactory factory{}; - return factory; -} diff --git a/alc/backends/winmm.h b/alc/backends/winmm.h deleted file mode 100644 index bf09ddd9..00000000 --- a/alc/backends/winmm.h +++ /dev/null @@ -1,19 +0,0 @@ -#ifndef BACKENDS_WINMM_H -#define BACKENDS_WINMM_H - -#include "backends/base.h" - -struct WinMMBackendFactory final : public BackendFactory { -public: - bool init() override; - - bool querySupport(BackendType type) override; - - std::string probe(BackendType type) override; - - BackendPtr createBackend(ALCdevice *device, BackendType type) override; - - static BackendFactory &getFactory(); -}; - -#endif /* BACKENDS_WINMM_H */ diff --git a/alc/bformatdec.cpp b/alc/bformatdec.cpp deleted file mode 100644 index 9b2d9049..00000000 --- a/alc/bformatdec.cpp +++ /dev/null @@ -1,298 +0,0 @@ - -#include "config.h" - -#include "bformatdec.h" - -#include -#include -#include -#include -#include -#include - -#include "almalloc.h" -#include "alu.h" -#include "core/ambdec.h" -#include "core/filters/splitter.h" -#include "front_stablizer.h" -#include "math_defs.h" -#include "opthelpers.h" - - -namespace { - -constexpr std::array Ambi3DDecoderHFScale{{ - 1.00000000e+00f, 1.00000000e+00f -}}; -constexpr std::array Ambi3DDecoderHFScale2O{{ - 7.45355990e-01f, 1.00000000e+00f, 1.00000000e+00f -}}; -constexpr std::array Ambi3DDecoderHFScale3O{{ - 5.89792205e-01f, 8.79693856e-01f, 1.00000000e+00f, 1.00000000e+00f -}}; - -inline auto& GetDecoderHFScales(uint order) noexcept -{ - if(order >= 3) return Ambi3DDecoderHFScale3O; - if(order == 2) return Ambi3DDecoderHFScale2O; - return Ambi3DDecoderHFScale; -} - -inline auto& GetAmbiScales(AmbDecScale scaletype) noexcept -{ - if(scaletype == AmbDecScale::FuMa) return AmbiScale::FromFuMa(); - if(scaletype == AmbDecScale::SN3D) return AmbiScale::FromSN3D(); - return AmbiScale::FromN3D(); -} - -} // namespace - - -BFormatDec::BFormatDec(const AmbDecConf *conf, const bool allow_2band, const size_t inchans, - const uint srate, const uint (&chanmap)[MAX_OUTPUT_CHANNELS], - std::unique_ptr stablizer) - : mStablizer{std::move(stablizer)}, mDualBand{allow_2band && (conf->FreqBands == 2)} - , mChannelDec{inchans} -{ - const bool periphonic{(conf->ChanMask&AmbiPeriphonicMask) != 0}; - auto&& coeff_scale = GetAmbiScales(conf->CoeffScale); - - if(!mDualBand) - { - for(size_t j{0},k{0};j < mChannelDec.size();++j) - { - const size_t acn{periphonic ? j : AmbiIndex::FromACN2D()[j]}; - if(!(conf->ChanMask&(1u<HFOrderGain[order] / coeff_scale[acn]}; - for(size_t i{0u};i < conf->NumSpeakers;++i) - { - const size_t chanidx{chanmap[i]}; - mChannelDec[j].mGains.Single[chanidx] = conf->Matrix[i][k] * gain; - } - ++k; - } - } - else - { - mChannelDec[0].mXOver.init(conf->XOverFreq / static_cast(srate)); - for(size_t j{1};j < mChannelDec.size();++j) - mChannelDec[j].mXOver = mChannelDec[0].mXOver; - - const float ratio{std::pow(10.0f, conf->XOverRatio / 40.0f)}; - for(size_t j{0},k{0};j < mChannelDec.size();++j) - { - const size_t acn{periphonic ? j : AmbiIndex::FromACN2D()[j]}; - if(!(conf->ChanMask&(1u<HFOrderGain[order] * ratio / coeff_scale[acn]}; - const float lfGain{conf->LFOrderGain[order] / ratio / coeff_scale[acn]}; - for(size_t i{0u};i < conf->NumSpeakers;++i) - { - const size_t chanidx{chanmap[i]}; - mChannelDec[j].mGains.Dual[sHFBand][chanidx] = conf->HFMatrix[i][k] * hfGain; - mChannelDec[j].mGains.Dual[sLFBand][chanidx] = conf->LFMatrix[i][k] * lfGain; - } - ++k; - } - } -} - -BFormatDec::BFormatDec(const size_t inchans, const al::span coeffs, - const al::span coeffslf, std::unique_ptr stablizer) - : mStablizer{std::move(stablizer)}, mDualBand{!coeffslf.empty()}, mChannelDec{inchans} -{ - if(!mDualBand) - { - for(size_t j{0};j < mChannelDec.size();++j) - { - float *outcoeffs{mChannelDec[j].mGains.Single}; - for(const ChannelDec &incoeffs : coeffs) - *(outcoeffs++) = incoeffs[j]; - } - } - else - { - for(size_t j{0};j < mChannelDec.size();++j) - { - float *outcoeffs{mChannelDec[j].mGains.Dual[sHFBand]}; - for(const ChannelDec &incoeffs : coeffs) - *(outcoeffs++) = incoeffs[j]; - - outcoeffs = mChannelDec[j].mGains.Dual[sLFBand]; - for(const ChannelDec &incoeffs : coeffslf) - *(outcoeffs++) = incoeffs[j]; - } - } -} - - -void BFormatDec::process(const al::span OutBuffer, - const FloatBufferLine *InSamples, const size_t SamplesToDo) -{ - ASSUME(SamplesToDo > 0); - - if(mDualBand) - { - const al::span hfSamples{mSamples[sHFBand].data(), SamplesToDo}; - const al::span lfSamples{mSamples[sLFBand].data(), SamplesToDo}; - for(auto &chandec : mChannelDec) - { - chandec.mXOver.process({InSamples->data(), SamplesToDo}, hfSamples.data(), - lfSamples.data()); - MixSamples(hfSamples, OutBuffer, chandec.mGains.Dual[sHFBand], - chandec.mGains.Dual[sHFBand], 0, 0); - MixSamples(lfSamples, OutBuffer, chandec.mGains.Dual[sLFBand], - chandec.mGains.Dual[sLFBand], 0, 0); - ++InSamples; - } - } - else - { - for(auto &chandec : mChannelDec) - { - MixSamples({InSamples->data(), SamplesToDo}, OutBuffer, chandec.mGains.Single, - chandec.mGains.Single, 0, 0); - ++InSamples; - } - } -} - -void BFormatDec::processStablize(const al::span OutBuffer, - const FloatBufferLine *InSamples, const size_t lidx, const size_t ridx, const size_t cidx, - const size_t SamplesToDo) -{ - ASSUME(SamplesToDo > 0); - - /* Move the existing direct L/R signal out so it doesn't get processed by - * the stablizer. Add a delay to it so it stays aligned with the stablizer - * delay. - */ - float *RESTRICT mid{al::assume_aligned<16>(mStablizer->MidDirect.data())}; - float *RESTRICT side{al::assume_aligned<16>(mStablizer->Side.data())}; - for(size_t i{0};i < SamplesToDo;++i) - { - mid[FrontStablizer::DelayLength+i] = OutBuffer[lidx][i] + OutBuffer[ridx][i]; - side[FrontStablizer::DelayLength+i] = OutBuffer[lidx][i] - OutBuffer[ridx][i]; - } - std::fill_n(OutBuffer[lidx].begin(), SamplesToDo, 0.0f); - std::fill_n(OutBuffer[ridx].begin(), SamplesToDo, 0.0f); - - /* Decode the B-Format input to OutBuffer. */ - process(OutBuffer, InSamples, SamplesToDo); - - /* Apply a delay to all channels, except the front-left and front-right, so - * they maintain correct timing. - */ - const size_t NumChannels{OutBuffer.size()}; - for(size_t i{0u};i < NumChannels;i++) - { - if(i == lidx || i == ridx) - continue; - - auto &DelayBuf = mStablizer->DelayBuf[i]; - auto buffer_end = OutBuffer[i].begin() + SamplesToDo; - if LIKELY(SamplesToDo >= FrontStablizer::DelayLength) - { - auto delay_end = std::rotate(OutBuffer[i].begin(), - buffer_end - FrontStablizer::DelayLength, buffer_end); - std::swap_ranges(OutBuffer[i].begin(), delay_end, DelayBuf.begin()); - } - else - { - auto delay_start = std::swap_ranges(OutBuffer[i].begin(), buffer_end, - DelayBuf.begin()); - std::rotate(DelayBuf.begin(), delay_start, DelayBuf.end()); - } - } - - /* Include the side signal for what was just decoded. */ - for(size_t i{0};i < SamplesToDo;++i) - side[FrontStablizer::DelayLength+i] += OutBuffer[lidx][i] - OutBuffer[ridx][i]; - - /* Combine the delayed mid signal with the decoded mid signal. Note that - * the samples are stored and combined in reverse, so the newest samples - * are at the front and the oldest at the back. - */ - al::span tmpbuf{mStablizer->TempBuf.data(), SamplesToDo+FrontStablizer::DelayLength}; - auto tmpiter = tmpbuf.begin() + SamplesToDo; - std::copy(mStablizer->MidDelay.cbegin(), mStablizer->MidDelay.cend(), tmpiter); - for(size_t i{0};i < SamplesToDo;++i) - *--tmpiter = OutBuffer[lidx][i] + OutBuffer[ridx][i]; - /* Save the newest samples for next time. */ - std::copy_n(tmpbuf.cbegin(), mStablizer->MidDelay.size(), mStablizer->MidDelay.begin()); - - /* Apply an all-pass on the reversed signal, then reverse the samples to - * get the forward signal with a reversed phase shift. The future samples - * are included with the all-pass to reduce the error in the output - * samples (the smaller the delay, the more error is introduced). - */ - mStablizer->MidFilter.applyAllpass(tmpbuf); - tmpbuf = tmpbuf.subspan(); - std::reverse(tmpbuf.begin(), tmpbuf.end()); - - /* Now apply the band-splitter, combining its phase shift with the reversed - * phase shift, restoring the original phase on the split signal. - */ - mStablizer->MidFilter.process(tmpbuf, mStablizer->MidHF.data(), mStablizer->MidLF.data()); - - /* This pans the separate low- and high-frequency signals between being on - * the center channel and the left+right channels. The low-frequency signal - * is panned 1/3rd toward center and the high-frequency signal is panned - * 1/4th toward center. These values can be tweaked. - */ - const float cos_lf{std::cos(1.0f/3.0f * (al::MathDefs::Pi()*0.5f))}; - const float cos_hf{std::cos(1.0f/4.0f * (al::MathDefs::Pi()*0.5f))}; - const float sin_lf{std::sin(1.0f/3.0f * (al::MathDefs::Pi()*0.5f))}; - const float sin_hf{std::sin(1.0f/4.0f * (al::MathDefs::Pi()*0.5f))}; - for(size_t i{0};i < SamplesToDo;i++) - { - const float m{mStablizer->MidLF[i]*cos_lf + mStablizer->MidHF[i]*cos_hf + mid[i]}; - const float c{mStablizer->MidLF[i]*sin_lf + mStablizer->MidHF[i]*sin_hf}; - const float s{side[i]}; - - /* The generated center channel signal adds to the existing signal, - * while the modified left and right channels replace. - */ - OutBuffer[lidx][i] = (m + s) * 0.5f; - OutBuffer[ridx][i] = (m - s) * 0.5f; - OutBuffer[cidx][i] += c * 0.5f; - } - /* Move the delayed mid/side samples to the front for next time. */ - auto mid_end = mStablizer->MidDirect.cbegin() + SamplesToDo; - std::copy(mid_end, mid_end+FrontStablizer::DelayLength, mStablizer->MidDirect.begin()); - auto side_end = mStablizer->Side.cbegin() + SamplesToDo; - std::copy(side_end, side_end+FrontStablizer::DelayLength, mStablizer->Side.begin()); -} - - -auto BFormatDec::GetHFOrderScales(const uint in_order, const uint out_order) noexcept - -> std::array -{ - std::array ret{}; - - assert(out_order >= in_order); - - const auto &target = GetDecoderHFScales(out_order); - const auto &input = GetDecoderHFScales(in_order); - - for(size_t i{0};i < in_order+1;++i) - ret[i] = input[i] / target[i]; - - return ret; -} - -std::unique_ptr BFormatDec::Create(const AmbDecConf *conf, const bool allow_2band, - const size_t inchans, const uint srate, const uint (&chanmap)[MAX_OUTPUT_CHANNELS], - std::unique_ptr stablizer) -{ - return std::unique_ptr{new(FamCount(inchans)) - BFormatDec{conf, allow_2band, inchans, srate, chanmap, std::move(stablizer)}}; -} -std::unique_ptr BFormatDec::Create(const size_t inchans, - const al::span coeffs, const al::span coeffslf, - std::unique_ptr stablizer) -{ - return std::unique_ptr{new(FamCount(inchans)) - BFormatDec{inchans, coeffs, coeffslf, std::move(stablizer)}}; -} diff --git a/alc/bformatdec.h b/alc/bformatdec.h deleted file mode 100644 index 7715d364..00000000 --- a/alc/bformatdec.h +++ /dev/null @@ -1,75 +0,0 @@ -#ifndef BFORMATDEC_H -#define BFORMATDEC_H - -#include -#include -#include - -#include "almalloc.h" -#include "alspan.h" -#include "core/ambidefs.h" -#include "core/bufferline.h" -#include "core/devformat.h" -#include "core/filters/splitter.h" - -struct AmbDecConf; -struct FrontStablizer; - - -using ChannelDec = std::array; - -class BFormatDec { - static constexpr size_t sHFBand{0}; - static constexpr size_t sLFBand{1}; - static constexpr size_t sNumBands{2}; - - struct ChannelDecoder { - union MatrixU { - float Dual[sNumBands][MAX_OUTPUT_CHANNELS]; - float Single[MAX_OUTPUT_CHANNELS]; - } mGains{}; - - /* NOTE: BandSplitter filter is unused with single-band decoding. */ - BandSplitter mXOver; - }; - - alignas(16) std::array mSamples; - - const std::unique_ptr mStablizer; - const bool mDualBand{false}; - - al::FlexArray mChannelDec; - -public: - BFormatDec(const AmbDecConf *conf, const bool allow_2band, const size_t inchans, - const uint srate, const uint (&chanmap)[MAX_OUTPUT_CHANNELS], - std::unique_ptr stablizer); - BFormatDec(const size_t inchans, const al::span coeffs, - const al::span coeffslf, std::unique_ptr stablizer); - - bool hasStablizer() const noexcept { return mStablizer != nullptr; }; - - /* Decodes the ambisonic input to the given output channels. */ - void process(const al::span OutBuffer, const FloatBufferLine *InSamples, - const size_t SamplesToDo); - - /* Decodes the ambisonic input to the given output channels with stablization. */ - void processStablize(const al::span OutBuffer, - const FloatBufferLine *InSamples, const size_t lidx, const size_t ridx, const size_t cidx, - const size_t SamplesToDo); - - /* Retrieves per-order HF scaling factors for "upsampling" ambisonic data. */ - static std::array GetHFOrderScales(const uint in_order, - const uint out_order) noexcept; - - static std::unique_ptr Create(const AmbDecConf *conf, const bool allow_2band, - const size_t inchans, const uint srate, const uint (&chanmap)[MAX_OUTPUT_CHANNELS], - std::unique_ptr stablizer); - static std::unique_ptr Create(const size_t inchans, - const al::span coeffs, const al::span coeffslf, - std::unique_ptr stablizer); - - DEF_FAM_NEWDEL(BFormatDec, mChannelDec) -}; - -#endif /* BFORMATDEC_H */ diff --git a/alc/buffer_storage.cpp b/alc/buffer_storage.cpp deleted file mode 100644 index 7d3adddd..00000000 --- a/alc/buffer_storage.cpp +++ /dev/null @@ -1,38 +0,0 @@ - -#include "config.h" - -#include "buffer_storage.h" - -#include - - -uint BytesFromFmt(FmtType type) noexcept -{ - switch(type) - { - case FmtUByte: return sizeof(uint8_t); - case FmtShort: return sizeof(int16_t); - case FmtFloat: return sizeof(float); - case FmtDouble: return sizeof(double); - case FmtMulaw: return sizeof(uint8_t); - case FmtAlaw: return sizeof(uint8_t); - } - return 0; -} - -uint ChannelsFromFmt(FmtChannels chans, uint ambiorder) noexcept -{ - switch(chans) - { - case FmtMono: return 1; - case FmtStereo: return 2; - case FmtRear: return 2; - case FmtQuad: return 4; - case FmtX51: return 6; - case FmtX61: return 7; - case FmtX71: return 8; - case FmtBFormat2D: return (ambiorder*2) + 1; - case FmtBFormat3D: return (ambiorder+1) * (ambiorder+1); - } - return 0; -} diff --git a/alc/buffer_storage.h b/alc/buffer_storage.h deleted file mode 100644 index 60770184..00000000 --- a/alc/buffer_storage.h +++ /dev/null @@ -1,88 +0,0 @@ -#ifndef ALC_BUFFER_STORAGE_H -#define ALC_BUFFER_STORAGE_H - -#include - -#include "albyte.h" -#include "almalloc.h" -#include "vector.h" - - -using uint = unsigned int; - -/* Storable formats */ -enum FmtType : unsigned char { - FmtUByte, - FmtShort, - FmtFloat, - FmtDouble, - FmtMulaw, - FmtAlaw, -}; -enum FmtChannels : unsigned char { - FmtMono, - FmtStereo, - FmtRear, - FmtQuad, - FmtX51, /* (WFX order) */ - FmtX61, /* (WFX order) */ - FmtX71, /* (WFX order) */ - FmtBFormat2D, - FmtBFormat3D, -}; - -enum class AmbiLayout : unsigned char { - FuMa, - ACN, -}; -enum class AmbiScaling : unsigned char { - FuMa, - SN3D, - N3D, -}; - -uint BytesFromFmt(FmtType type) noexcept; -uint ChannelsFromFmt(FmtChannels chans, uint ambiorder) noexcept; -inline uint FrameSizeFromFmt(FmtChannels chans, FmtType type, uint ambiorder) noexcept -{ return ChannelsFromFmt(chans, ambiorder) * BytesFromFmt(type); } - - -using CallbackType = int(*)(void*, void*, int); - -struct BufferStorage { - al::vector mData; - - CallbackType mCallback{nullptr}; - void *mUserData{nullptr}; - - uint mSampleRate{0u}; - FmtChannels mChannels{}; - FmtType mType{}; - uint mSampleLen{0u}; - - AmbiLayout mAmbiLayout{AmbiLayout::FuMa}; - AmbiScaling mAmbiScaling{AmbiScaling::FuMa}; - uint mAmbiOrder{0u}; - - uint mLoopStart{0u}; - uint mLoopEnd{0u}; - - inline uint bytesFromFmt() const noexcept { return BytesFromFmt(mType); } - inline uint channelsFromFmt() const noexcept - { return ChannelsFromFmt(mChannels, mAmbiOrder); } - inline uint frameSizeFromFmt() const noexcept { return channelsFromFmt() * bytesFromFmt(); } - - inline bool isBFormat() const noexcept - { return mChannels == FmtBFormat2D || mChannels == FmtBFormat3D; } -}; - - -struct BufferlistItem { - std::atomic mNext{nullptr}; - uint mSampleLen{0u}; - BufferStorage *mBuffer{nullptr}; - - DEF_NEWDEL(BufferlistItem) -}; - -#endif /* ALC_BUFFER_STORAGE_H */ diff --git a/alc/compat.h b/alc/compat.h deleted file mode 100644 index 960b4b94..00000000 --- a/alc/compat.h +++ /dev/null @@ -1,9 +0,0 @@ -#ifndef AL_COMPAT_H -#define AL_COMPAT_H - -#include - -struct PathNamePair { std::string path, fname; }; -const PathNamePair &GetProcBinary(void); - -#endif /* AL_COMPAT_H */ diff --git a/alc/converter.cpp b/alc/converter.cpp deleted file mode 100644 index 5016b373..00000000 --- a/alc/converter.cpp +++ /dev/null @@ -1,370 +0,0 @@ - -#include "config.h" - -#include "converter.h" - -#include -#include -#include -#include -#include - -#include "albyte.h" -#include "alnumeric.h" -#include "core/fpu_ctrl.h" - -struct CTag; -struct CopyTag; - - -namespace { - -constexpr uint MaxPitch{10}; - -static_assert((BufferLineSize-1)/MaxPitch > 0, "MaxPitch is too large for BufferLineSize!"); -static_assert((INT_MAX>>MixerFracBits)/MaxPitch > BufferLineSize, - "MaxPitch and/or BufferLineSize are too large for MixerFracBits!"); - -/* Base template left undefined. Should be marked =delete, but Clang 3.8.1 - * chokes on that given the inline specializations. - */ -template -inline float LoadSample(DevFmtType_t val) noexcept; - -template<> inline float LoadSample(DevFmtType_t val) noexcept -{ return val * (1.0f/128.0f); } -template<> inline float LoadSample(DevFmtType_t val) noexcept -{ return val * (1.0f/32768.0f); } -template<> inline float LoadSample(DevFmtType_t val) noexcept -{ return static_cast(val) * (1.0f/2147483648.0f); } -template<> inline float LoadSample(DevFmtType_t val) noexcept -{ return val; } - -template<> inline float LoadSample(DevFmtType_t val) noexcept -{ return LoadSample(static_cast(val - 128)); } -template<> inline float LoadSample(DevFmtType_t val) noexcept -{ return LoadSample(static_cast(val - 32768)); } -template<> inline float LoadSample(DevFmtType_t val) noexcept -{ return LoadSample(static_cast(val - 2147483648u)); } - - -template -inline void LoadSampleArray(float *RESTRICT dst, const void *src, const size_t srcstep, - const size_t samples) noexcept -{ - const DevFmtType_t *ssrc = static_cast*>(src); - for(size_t i{0u};i < samples;i++) - dst[i] = LoadSample(ssrc[i*srcstep]); -} - -void LoadSamples(float *dst, const void *src, const size_t srcstep, const DevFmtType srctype, - const size_t samples) noexcept -{ -#define HANDLE_FMT(T) \ - case T: LoadSampleArray(dst, src, srcstep, samples); break - switch(srctype) - { - HANDLE_FMT(DevFmtByte); - HANDLE_FMT(DevFmtUByte); - HANDLE_FMT(DevFmtShort); - HANDLE_FMT(DevFmtUShort); - HANDLE_FMT(DevFmtInt); - HANDLE_FMT(DevFmtUInt); - HANDLE_FMT(DevFmtFloat); - } -#undef HANDLE_FMT -} - - -template -inline DevFmtType_t StoreSample(float) noexcept; - -template<> inline float StoreSample(float val) noexcept -{ return val; } -template<> inline int32_t StoreSample(float val) noexcept -{ return fastf2i(clampf(val*2147483648.0f, -2147483648.0f, 2147483520.0f)); } -template<> inline int16_t StoreSample(float val) noexcept -{ return static_cast(fastf2i(clampf(val*32768.0f, -32768.0f, 32767.0f))); } -template<> inline int8_t StoreSample(float val) noexcept -{ return static_cast(fastf2i(clampf(val*128.0f, -128.0f, 127.0f))); } - -/* Define unsigned output variations. */ -template<> inline uint32_t StoreSample(float val) noexcept -{ return static_cast(StoreSample(val)) + 2147483648u; } -template<> inline uint16_t StoreSample(float val) noexcept -{ return static_cast(StoreSample(val) + 32768); } -template<> inline uint8_t StoreSample(float val) noexcept -{ return static_cast(StoreSample(val) + 128); } - -template -inline void StoreSampleArray(void *dst, const float *RESTRICT src, const size_t dststep, - const size_t samples) noexcept -{ - DevFmtType_t *sdst = static_cast*>(dst); - for(size_t i{0u};i < samples;i++) - sdst[i*dststep] = StoreSample(src[i]); -} - - -void StoreSamples(void *dst, const float *src, const size_t dststep, const DevFmtType dsttype, - const size_t samples) noexcept -{ -#define HANDLE_FMT(T) \ - case T: StoreSampleArray(dst, src, dststep, samples); break - switch(dsttype) - { - HANDLE_FMT(DevFmtByte); - HANDLE_FMT(DevFmtUByte); - HANDLE_FMT(DevFmtShort); - HANDLE_FMT(DevFmtUShort); - HANDLE_FMT(DevFmtInt); - HANDLE_FMT(DevFmtUInt); - HANDLE_FMT(DevFmtFloat); - } -#undef HANDLE_FMT -} - - -template -void Mono2Stereo(float *RESTRICT dst, const void *src, const size_t frames) noexcept -{ - const DevFmtType_t *ssrc = static_cast*>(src); - for(size_t i{0u};i < frames;i++) - dst[i*2 + 1] = dst[i*2 + 0] = LoadSample(ssrc[i]) * 0.707106781187f; -} - -template -void Multi2Mono(uint chanmask, const size_t step, const float scale, float *RESTRICT dst, - const void *src, const size_t frames) noexcept -{ - const DevFmtType_t *ssrc = static_cast*>(src); - std::fill_n(dst, frames, 0.0f); - for(size_t c{0};chanmask;++c) - { - if LIKELY((chanmask&1)) - { - for(size_t i{0u};i < frames;i++) - dst[i] += LoadSample(ssrc[i*step + c]); - } - chanmask >>= 1; - } - for(size_t i{0u};i < frames;i++) - dst[i] *= scale; -} - -} // namespace - -SampleConverterPtr CreateSampleConverter(DevFmtType srcType, DevFmtType dstType, size_t numchans, - uint srcRate, uint dstRate, Resampler resampler) -{ - if(numchans < 1 || srcRate < 1 || dstRate < 1) - return nullptr; - - SampleConverterPtr converter{new(FamCount(numchans)) SampleConverter{numchans}}; - converter->mSrcType = srcType; - converter->mDstType = dstType; - converter->mSrcTypeSize = BytesFromDevFmt(srcType); - converter->mDstTypeSize = BytesFromDevFmt(dstType); - - converter->mSrcPrepCount = 0; - converter->mFracOffset = 0; - - /* Have to set the mixer FPU mode since that's what the resampler code expects. */ - FPUCtl mixer_mode{}; - auto step = static_cast( - mind(srcRate*double{MixerFracOne}/dstRate + 0.5, MaxPitch*MixerFracOne)); - converter->mIncrement = maxu(step, 1); - if(converter->mIncrement == MixerFracOne) - converter->mResample = Resample_; - else - converter->mResample = PrepareResampler(resampler, converter->mIncrement, - &converter->mState); - - return converter; -} - -uint SampleConverter::availableOut(uint srcframes) const -{ - int prepcount{mSrcPrepCount}; - if(prepcount < 0) - { - /* Negative prepcount means we need to skip that many input samples. */ - if(static_cast(-prepcount) >= srcframes) - return 0; - srcframes -= static_cast(-prepcount); - prepcount = 0; - } - - if(srcframes < 1) - { - /* No output samples if there's no input samples. */ - return 0; - } - - if(prepcount < MaxResamplerPadding - && static_cast(MaxResamplerPadding - prepcount) >= srcframes) - { - /* Not enough input samples to generate an output sample. */ - return 0; - } - - auto DataSize64 = static_cast(prepcount); - DataSize64 += srcframes; - DataSize64 -= MaxResamplerPadding; - DataSize64 <<= MixerFracBits; - DataSize64 -= mFracOffset; - - /* If we have a full prep, we can generate at least one sample. */ - return static_cast(clampu64((DataSize64 + mIncrement-1)/mIncrement, 1, - std::numeric_limits::max())); -} - -uint SampleConverter::convert(const void **src, uint *srcframes, void *dst, uint dstframes) -{ - const uint SrcFrameSize{static_cast(mChan.size()) * mSrcTypeSize}; - const uint DstFrameSize{static_cast(mChan.size()) * mDstTypeSize}; - const uint increment{mIncrement}; - auto SamplesIn = static_cast(*src); - uint NumSrcSamples{*srcframes}; - - FPUCtl mixer_mode{}; - uint pos{0}; - while(pos < dstframes && NumSrcSamples > 0) - { - int prepcount{mSrcPrepCount}; - if(prepcount < 0) - { - /* Negative prepcount means we need to skip that many input samples. */ - if(static_cast(-prepcount) >= NumSrcSamples) - { - mSrcPrepCount = static_cast(NumSrcSamples) + prepcount; - NumSrcSamples = 0; - break; - } - SamplesIn += SrcFrameSize*static_cast(-prepcount); - NumSrcSamples -= static_cast(-prepcount); - mSrcPrepCount = 0; - continue; - } - const uint toread{minu(NumSrcSamples, BufferLineSize - MaxResamplerPadding)}; - - if(prepcount < MaxResamplerPadding - && static_cast(MaxResamplerPadding - prepcount) >= toread) - { - /* Not enough input samples to generate an output sample. Store - * what we're given for later. - */ - for(size_t chan{0u};chan < mChan.size();chan++) - LoadSamples(&mChan[chan].PrevSamples[prepcount], SamplesIn + mSrcTypeSize*chan, - mChan.size(), mSrcType, toread); - - mSrcPrepCount = prepcount + static_cast(toread); - NumSrcSamples = 0; - break; - } - - float *RESTRICT SrcData{mSrcSamples}; - float *RESTRICT DstData{mDstSamples}; - uint DataPosFrac{mFracOffset}; - auto DataSize64 = static_cast(prepcount); - DataSize64 += toread; - DataSize64 -= MaxResamplerPadding; - DataSize64 <<= MixerFracBits; - DataSize64 -= DataPosFrac; - - /* If we have a full prep, we can generate at least one sample. */ - auto DstSize = static_cast( - clampu64((DataSize64 + increment-1)/increment, 1, BufferLineSize)); - DstSize = minu(DstSize, dstframes-pos); - - for(size_t chan{0u};chan < mChan.size();chan++) - { - const al::byte *SrcSamples{SamplesIn + mSrcTypeSize*chan}; - al::byte *DstSamples = static_cast(dst) + mDstTypeSize*chan; - - /* Load the previous samples into the source data first, then the - * new samples from the input buffer. - */ - std::copy_n(mChan[chan].PrevSamples, prepcount, SrcData); - LoadSamples(SrcData + prepcount, SrcSamples, mChan.size(), mSrcType, toread); - - /* Store as many prep samples for next time as possible, given the - * number of output samples being generated. - */ - uint SrcDataEnd{(DstSize*increment + DataPosFrac)>>MixerFracBits}; - if(SrcDataEnd >= static_cast(prepcount)+toread) - std::fill(std::begin(mChan[chan].PrevSamples), - std::end(mChan[chan].PrevSamples), 0.0f); - else - { - const size_t len{minz(al::size(mChan[chan].PrevSamples), - static_cast(prepcount)+toread-SrcDataEnd)}; - std::copy_n(SrcData+SrcDataEnd, len, mChan[chan].PrevSamples); - std::fill(std::begin(mChan[chan].PrevSamples)+len, - std::end(mChan[chan].PrevSamples), 0.0f); - } - - /* Now resample, and store the result in the output buffer. */ - const float *ResampledData{mResample(&mState, SrcData+(MaxResamplerPadding>>1), - DataPosFrac, increment, {DstData, DstSize})}; - - StoreSamples(DstSamples, ResampledData, mChan.size(), mDstType, DstSize); - } - - /* Update the number of prep samples still available, as well as the - * fractional offset. - */ - DataPosFrac += increment*DstSize; - mSrcPrepCount = mini(prepcount + static_cast(toread - (DataPosFrac>>MixerFracBits)), - MaxResamplerPadding); - mFracOffset = DataPosFrac & MixerFracMask; - - /* Update the src and dst pointers in case there's still more to do. */ - SamplesIn += SrcFrameSize*(DataPosFrac>>MixerFracBits); - NumSrcSamples -= minu(NumSrcSamples, (DataPosFrac>>MixerFracBits)); - - dst = static_cast(dst) + DstFrameSize*DstSize; - pos += DstSize; - } - - *src = SamplesIn; - *srcframes = NumSrcSamples; - - return pos; -} - - -void ChannelConverter::convert(const void *src, float *dst, uint frames) const -{ - if(mDstChans == DevFmtMono) - { - const float scale{std::sqrt(1.0f / static_cast(PopCount(mChanMask)))}; - switch(mSrcType) - { -#define HANDLE_FMT(T) case T: Multi2Mono(mChanMask, mSrcStep, scale, dst, src, frames); break - HANDLE_FMT(DevFmtByte); - HANDLE_FMT(DevFmtUByte); - HANDLE_FMT(DevFmtShort); - HANDLE_FMT(DevFmtUShort); - HANDLE_FMT(DevFmtInt); - HANDLE_FMT(DevFmtUInt); - HANDLE_FMT(DevFmtFloat); -#undef HANDLE_FMT - } - } - else if(mChanMask == 0x1 && mDstChans == DevFmtStereo) - { - switch(mSrcType) - { -#define HANDLE_FMT(T) case T: Mono2Stereo(dst, src, frames); break - HANDLE_FMT(DevFmtByte); - HANDLE_FMT(DevFmtUByte); - HANDLE_FMT(DevFmtShort); - HANDLE_FMT(DevFmtUShort); - HANDLE_FMT(DevFmtInt); - HANDLE_FMT(DevFmtUInt); - HANDLE_FMT(DevFmtFloat); -#undef HANDLE_FMT - } - } -} diff --git a/alc/converter.h b/alc/converter.h deleted file mode 100644 index ffcfbc18..00000000 --- a/alc/converter.h +++ /dev/null @@ -1,59 +0,0 @@ -#ifndef CONVERTER_H -#define CONVERTER_H - -#include -#include - -#include "almalloc.h" -#include "core/devformat.h" -#include "core/mixer/defs.h" - -using uint = unsigned int; - - -struct SampleConverter { - DevFmtType mSrcType{}; - DevFmtType mDstType{}; - uint mSrcTypeSize{}; - uint mDstTypeSize{}; - - int mSrcPrepCount{}; - - uint mFracOffset{}; - uint mIncrement{}; - InterpState mState{}; - ResamplerFunc mResample{}; - - alignas(16) float mSrcSamples[BufferLineSize]{}; - alignas(16) float mDstSamples[BufferLineSize]{}; - - struct ChanSamples { - alignas(16) float PrevSamples[MaxResamplerPadding]; - }; - al::FlexArray mChan; - - SampleConverter(size_t numchans) : mChan{numchans} { } - - uint convert(const void **src, uint *srcframes, void *dst, uint dstframes); - uint availableOut(uint srcframes) const; - - DEF_FAM_NEWDEL(SampleConverter, mChan) -}; -using SampleConverterPtr = std::unique_ptr; - -SampleConverterPtr CreateSampleConverter(DevFmtType srcType, DevFmtType dstType, size_t numchans, - uint srcRate, uint dstRate, Resampler resampler); - - -struct ChannelConverter { - DevFmtType mSrcType{}; - uint mSrcStep{}; - uint mChanMask{}; - DevFmtChannels mDstChans{}; - - bool is_active() const noexcept { return mChanMask != 0; } - - void convert(const void *src, float *dst, uint frames) const; -}; - -#endif /* CONVERTER_H */ diff --git a/alc/effects/autowah.cpp b/alc/effects/autowah.cpp deleted file mode 100644 index 403a23e3..00000000 --- a/alc/effects/autowah.cpp +++ /dev/null @@ -1,212 +0,0 @@ -/** - * OpenAL cross platform audio library - * Copyright (C) 2018 by Raul Herraiz. - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - * Or go to http://www.gnu.org/copyleft/lgpl.html - */ - -#include "config.h" - -#include -#include - -#include - -#include "alcmain.h" -#include "alcontext.h" -#include "core/filters/biquad.h" -#include "effectslot.h" -#include "vecmat.h" - -namespace { - -constexpr float GainScale{31621.0f}; -constexpr float MinFreq{20.0f}; -constexpr float MaxFreq{2500.0f}; -constexpr float QFactor{5.0f}; - -struct AutowahState final : public EffectState { - /* Effect parameters */ - float mAttackRate; - float mReleaseRate; - float mResonanceGain; - float mPeakGain; - float mFreqMinNorm; - float mBandwidthNorm; - float mEnvDelay; - - /* Filter components derived from the envelope. */ - struct { - float cos_w0; - float alpha; - } mEnv[BufferLineSize]; - - struct { - /* Effect filters' history. */ - struct { - float z1, z2; - } Filter; - - /* Effect gains for each output channel */ - float CurrentGains[MAX_OUTPUT_CHANNELS]; - float TargetGains[MAX_OUTPUT_CHANNELS]; - } mChans[MaxAmbiChannels]; - - /* Effects buffers */ - alignas(16) float mBufferOut[BufferLineSize]; - - - void deviceUpdate(const ALCdevice *device, const BufferStorage *buffer) override; - void update(const ALCcontext *context, const EffectSlot *slot, const EffectProps *props, - const EffectTarget target) override; - void process(const size_t samplesToDo, const al::span samplesIn, - const al::span samplesOut) override; - - DEF_NEWDEL(AutowahState) -}; - -void AutowahState::deviceUpdate(const ALCdevice*, const BufferStorage* /*buffer*/) -{ - /* (Re-)initializing parameters and clear the buffers. */ - - mAttackRate = 1.0f; - mReleaseRate = 1.0f; - mResonanceGain = 10.0f; - mPeakGain = 4.5f; - mFreqMinNorm = 4.5e-4f; - mBandwidthNorm = 0.05f; - mEnvDelay = 0.0f; - - for(auto &e : mEnv) - { - e.cos_w0 = 0.0f; - e.alpha = 0.0f; - } - - for(auto &chan : mChans) - { - std::fill(std::begin(chan.CurrentGains), std::end(chan.CurrentGains), 0.0f); - chan.Filter.z1 = 0.0f; - chan.Filter.z2 = 0.0f; - } -} - -void AutowahState::update(const ALCcontext *context, const EffectSlot *slot, - const EffectProps *props, const EffectTarget target) -{ - const ALCdevice *device{context->mDevice.get()}; - const auto frequency = static_cast(device->Frequency); - - const float ReleaseTime{clampf(props->Autowah.ReleaseTime, 0.001f, 1.0f)}; - - mAttackRate = std::exp(-1.0f / (props->Autowah.AttackTime*frequency)); - mReleaseRate = std::exp(-1.0f / (ReleaseTime*frequency)); - /* 0-20dB Resonance Peak gain */ - mResonanceGain = std::sqrt(std::log10(props->Autowah.Resonance)*10.0f / 3.0f); - mPeakGain = 1.0f - std::log10(props->Autowah.PeakGain / GainScale); - mFreqMinNorm = MinFreq / frequency; - mBandwidthNorm = (MaxFreq-MinFreq) / frequency; - - mOutTarget = target.Main->Buffer; - auto set_gains = [slot,target](auto &chan, al::span coeffs) - { ComputePanGains(target.Main, coeffs.data(), slot->Gain, chan.TargetGains); }; - SetAmbiPanIdentity(std::begin(mChans), slot->Wet.Buffer.size(), set_gains); -} - -void AutowahState::process(const size_t samplesToDo, - const al::span samplesIn, const al::span samplesOut) -{ - const float attack_rate{mAttackRate}; - const float release_rate{mReleaseRate}; - const float res_gain{mResonanceGain}; - const float peak_gain{mPeakGain}; - const float freq_min{mFreqMinNorm}; - const float bandwidth{mBandwidthNorm}; - - float env_delay{mEnvDelay}; - for(size_t i{0u};i < samplesToDo;i++) - { - float w0, sample, a; - - /* Envelope follower described on the book: Audio Effects, Theory, - * Implementation and Application. - */ - sample = peak_gain * std::fabs(samplesIn[0][i]); - a = (sample > env_delay) ? attack_rate : release_rate; - env_delay = lerp(sample, env_delay, a); - - /* Calculate the cos and alpha components for this sample's filter. */ - w0 = minf((bandwidth*env_delay + freq_min), 0.46f) * al::MathDefs::Tau(); - mEnv[i].cos_w0 = std::cos(w0); - mEnv[i].alpha = std::sin(w0)/(2.0f * QFactor); - } - mEnvDelay = env_delay; - - auto chandata = std::addressof(mChans[0]); - for(const auto &insamples : samplesIn) - { - /* This effectively inlines BiquadFilter_setParams for a peaking - * filter and BiquadFilter_processC. The alpha and cosine components - * for the filter coefficients were previously calculated with the - * envelope. Because the filter changes for each sample, the - * coefficients are transient and don't need to be held. - */ - float z1{chandata->Filter.z1}; - float z2{chandata->Filter.z2}; - - for(size_t i{0u};i < samplesToDo;i++) - { - const float alpha{mEnv[i].alpha}; - const float cos_w0{mEnv[i].cos_w0}; - float input, output; - float a[3], b[3]; - - b[0] = 1.0f + alpha*res_gain; - b[1] = -2.0f * cos_w0; - b[2] = 1.0f - alpha*res_gain; - a[0] = 1.0f + alpha/res_gain; - a[1] = -2.0f * cos_w0; - a[2] = 1.0f - alpha/res_gain; - - input = insamples[i]; - output = input*(b[0]/a[0]) + z1; - z1 = input*(b[1]/a[0]) - output*(a[1]/a[0]) + z2; - z2 = input*(b[2]/a[0]) - output*(a[2]/a[0]); - mBufferOut[i] = output; - } - chandata->Filter.z1 = z1; - chandata->Filter.z2 = z2; - - /* Now, mix the processed sound data to the output. */ - MixSamples({mBufferOut, samplesToDo}, samplesOut, chandata->CurrentGains, - chandata->TargetGains, samplesToDo, 0); - ++chandata; - } -} - - -struct AutowahStateFactory final : public EffectStateFactory { - al::intrusive_ptr create() override - { return al::intrusive_ptr{new AutowahState{}}; } -}; - -} // namespace - -EffectStateFactory *AutowahStateFactory_getFactory() -{ - static AutowahStateFactory AutowahFactory{}; - return &AutowahFactory; -} diff --git a/alc/effects/base.h b/alc/effects/base.h deleted file mode 100644 index 32d7fc86..00000000 --- a/alc/effects/base.h +++ /dev/null @@ -1,206 +0,0 @@ -#ifndef EFFECTS_BASE_H -#define EFFECTS_BASE_H - -#include - -#include "alcmain.h" -#include "almalloc.h" -#include "alspan.h" -#include "atomic.h" -#include "intrusive_ptr.h" - -struct EffectSlot; -struct BufferStorage; - - -enum class ChorusWaveform { - Sinusoid, - Triangle -}; - -constexpr float EchoMaxDelay{0.207f}; -constexpr float EchoMaxLRDelay{0.404f}; - -enum class FShifterDirection { - Down, - Up, - Off -}; - -enum class ModulatorWaveform { - Sinusoid, - Sawtooth, - Square -}; - -enum class VMorpherPhenome { - A, E, I, O, U, - AA, AE, AH, AO, EH, ER, IH, IY, UH, UW, - B, D, F, G, J, K, L, M, N, P, R, S, T, V, Z -}; - -enum class VMorpherWaveform { - Sinusoid, - Triangle, - Sawtooth -}; - -union EffectProps { - struct { - // Shared Reverb Properties - float Density; - float Diffusion; - float Gain; - float GainHF; - float DecayTime; - float DecayHFRatio; - float ReflectionsGain; - float ReflectionsDelay; - float LateReverbGain; - float LateReverbDelay; - float AirAbsorptionGainHF; - float RoomRolloffFactor; - bool DecayHFLimit; - - // Additional EAX Reverb Properties - float GainLF; - float DecayLFRatio; - float ReflectionsPan[3]; - float LateReverbPan[3]; - float EchoTime; - float EchoDepth; - float ModulationTime; - float ModulationDepth; - float HFReference; - float LFReference; - } Reverb; - - struct { - float AttackTime; - float ReleaseTime; - float Resonance; - float PeakGain; - } Autowah; - - struct { - ChorusWaveform Waveform; - int Phase; - float Rate; - float Depth; - float Feedback; - float Delay; - } Chorus; /* Also Flanger */ - - struct { - bool OnOff; - } Compressor; - - struct { - float Edge; - float Gain; - float LowpassCutoff; - float EQCenter; - float EQBandwidth; - } Distortion; - - struct { - float Delay; - float LRDelay; - - float Damping; - float Feedback; - - float Spread; - } Echo; - - struct { - float LowCutoff; - float LowGain; - float Mid1Center; - float Mid1Gain; - float Mid1Width; - float Mid2Center; - float Mid2Gain; - float Mid2Width; - float HighCutoff; - float HighGain; - } Equalizer; - - struct { - float Frequency; - FShifterDirection LeftDirection; - FShifterDirection RightDirection; - } Fshifter; - - struct { - float Frequency; - float HighPassCutoff; - ModulatorWaveform Waveform; - } Modulator; - - struct { - int CoarseTune; - int FineTune; - } Pshifter; - - struct { - float Rate; - VMorpherPhenome PhonemeA; - VMorpherPhenome PhonemeB; - int PhonemeACoarseTuning; - int PhonemeBCoarseTuning; - VMorpherWaveform Waveform; - } Vmorpher; - - struct { - float Gain; - } Dedicated; -}; - - -struct EffectTarget { - MixParams *Main; - RealMixParams *RealOut; -}; - -struct EffectState : public al::intrusive_ref { - al::span mOutTarget; - - - virtual ~EffectState() = default; - - virtual void deviceUpdate(const ALCdevice *device, const BufferStorage *buffer) = 0; - virtual void update(const ALCcontext *context, const EffectSlot *slot, - const EffectProps *props, const EffectTarget target) = 0; - virtual void process(const size_t samplesToDo, const al::span samplesIn, - const al::span samplesOut) = 0; -}; - - -struct EffectStateFactory { - virtual ~EffectStateFactory() = default; - - virtual al::intrusive_ptr create() = 0; -}; - - -EffectStateFactory *NullStateFactory_getFactory(void); -EffectStateFactory *ReverbStateFactory_getFactory(void); -EffectStateFactory *StdReverbStateFactory_getFactory(void); -EffectStateFactory *AutowahStateFactory_getFactory(void); -EffectStateFactory *ChorusStateFactory_getFactory(void); -EffectStateFactory *CompressorStateFactory_getFactory(void); -EffectStateFactory *DistortionStateFactory_getFactory(void); -EffectStateFactory *EchoStateFactory_getFactory(void); -EffectStateFactory *EqualizerStateFactory_getFactory(void); -EffectStateFactory *FlangerStateFactory_getFactory(void); -EffectStateFactory *FshifterStateFactory_getFactory(void); -EffectStateFactory *ModulatorStateFactory_getFactory(void); -EffectStateFactory *PshifterStateFactory_getFactory(void); -EffectStateFactory* VmorpherStateFactory_getFactory(void); - -EffectStateFactory *DedicatedStateFactory_getFactory(void); - -EffectStateFactory *ConvolutionStateFactory_getFactory(void); - -#endif /* EFFECTS_BASE_H */ diff --git a/alc/effects/chorus.cpp b/alc/effects/chorus.cpp deleted file mode 100644 index 92d57c18..00000000 --- a/alc/effects/chorus.cpp +++ /dev/null @@ -1,287 +0,0 @@ -/** - * OpenAL cross platform audio library - * Copyright (C) 2013 by Mike Gorchak - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - * Or go to http://www.gnu.org/copyleft/lgpl.html - */ - -#include "config.h" - -#include -#include -#include -#include -#include - -#include "alcmain.h" -#include "alcontext.h" -#include "almalloc.h" -#include "alnumeric.h" -#include "alspan.h" -#include "alu.h" -#include "core/ambidefs.h" -#include "effects/base.h" -#include "effectslot.h" -#include "math_defs.h" -#include "opthelpers.h" -#include "vector.h" - - -namespace { - -#define MAX_UPDATE_SAMPLES 256 - -struct ChorusState final : public EffectState { - al::vector mSampleBuffer; - uint mOffset{0}; - - uint mLfoOffset{0}; - uint mLfoRange{1}; - float mLfoScale{0.0f}; - uint mLfoDisp{0}; - - /* Gains for left and right sides */ - struct { - float Current[MAX_OUTPUT_CHANNELS]{}; - float Target[MAX_OUTPUT_CHANNELS]{}; - } mGains[2]; - - /* effect parameters */ - ChorusWaveform mWaveform{}; - int mDelay{0}; - float mDepth{0.0f}; - float mFeedback{0.0f}; - - void getTriangleDelays(uint (*delays)[MAX_UPDATE_SAMPLES], const size_t todo); - void getSinusoidDelays(uint (*delays)[MAX_UPDATE_SAMPLES], const size_t todo); - - void deviceUpdate(const ALCdevice *device, const BufferStorage *buffer) override; - void update(const ALCcontext *context, const EffectSlot *slot, const EffectProps *props, - const EffectTarget target) override; - void process(const size_t samplesToDo, const al::span samplesIn, - const al::span samplesOut) override; - - DEF_NEWDEL(ChorusState) -}; - -void ChorusState::deviceUpdate(const ALCdevice *Device, const BufferStorage* /*buffer*/) -{ - constexpr float max_delay{maxf(AL_CHORUS_MAX_DELAY, AL_FLANGER_MAX_DELAY)}; - - const auto frequency = static_cast(Device->Frequency); - const size_t maxlen{NextPowerOf2(float2uint(max_delay*2.0f*frequency) + 1u)}; - if(maxlen != mSampleBuffer.size()) - al::vector(maxlen).swap(mSampleBuffer); - - std::fill(mSampleBuffer.begin(), mSampleBuffer.end(), 0.0f); - for(auto &e : mGains) - { - std::fill(std::begin(e.Current), std::end(e.Current), 0.0f); - std::fill(std::begin(e.Target), std::end(e.Target), 0.0f); - } -} - -void ChorusState::update(const ALCcontext *Context, const EffectSlot *Slot, - const EffectProps *props, const EffectTarget target) -{ - constexpr int mindelay{(MaxResamplerPadding>>1) << MixerFracBits}; - - /* The LFO depth is scaled to be relative to the sample delay. Clamp the - * delay and depth to allow enough padding for resampling. - */ - const ALCdevice *device{Context->mDevice.get()}; - const auto frequency = static_cast(device->Frequency); - - mWaveform = props->Chorus.Waveform; - - mDelay = maxi(float2int(props->Chorus.Delay*frequency*MixerFracOne + 0.5f), mindelay); - mDepth = minf(props->Chorus.Depth * static_cast(mDelay), - static_cast(mDelay - mindelay)); - - mFeedback = props->Chorus.Feedback; - - /* Gains for left and right sides */ - const auto lcoeffs = CalcDirectionCoeffs({-1.0f, 0.0f, 0.0f}, 0.0f); - const auto rcoeffs = CalcDirectionCoeffs({ 1.0f, 0.0f, 0.0f}, 0.0f); - - mOutTarget = target.Main->Buffer; - ComputePanGains(target.Main, lcoeffs.data(), Slot->Gain, mGains[0].Target); - ComputePanGains(target.Main, rcoeffs.data(), Slot->Gain, mGains[1].Target); - - float rate{props->Chorus.Rate}; - if(!(rate > 0.0f)) - { - mLfoOffset = 0; - mLfoRange = 1; - mLfoScale = 0.0f; - mLfoDisp = 0; - } - else - { - /* Calculate LFO coefficient (number of samples per cycle). Limit the - * max range to avoid overflow when calculating the displacement. - */ - uint lfo_range{float2uint(minf(frequency/rate + 0.5f, float{INT_MAX/360 - 180}))}; - - mLfoOffset = mLfoOffset * lfo_range / mLfoRange; - mLfoRange = lfo_range; - switch(mWaveform) - { - case ChorusWaveform::Triangle: - mLfoScale = 4.0f / static_cast(mLfoRange); - break; - case ChorusWaveform::Sinusoid: - mLfoScale = al::MathDefs::Tau() / static_cast(mLfoRange); - break; - } - - /* Calculate lfo phase displacement */ - int phase{props->Chorus.Phase}; - if(phase < 0) phase = 360 + phase; - mLfoDisp = (mLfoRange*static_cast(phase) + 180) / 360; - } -} - - -void ChorusState::getTriangleDelays(uint (*delays)[MAX_UPDATE_SAMPLES], const size_t todo) -{ - const uint lfo_range{mLfoRange}; - const float lfo_scale{mLfoScale}; - const float depth{mDepth}; - const int delay{mDelay}; - - ASSUME(lfo_range > 0); - ASSUME(todo > 0); - - uint offset{mLfoOffset}; - auto gen_lfo = [&offset,lfo_range,lfo_scale,depth,delay]() -> uint - { - offset = (offset+1)%lfo_range; - const float offset_norm{static_cast(offset) * lfo_scale}; - return static_cast(fastf2i((1.0f-std::abs(2.0f-offset_norm)) * depth) + delay); - }; - std::generate_n(delays[0], todo, gen_lfo); - - offset = (mLfoOffset+mLfoDisp) % lfo_range; - std::generate_n(delays[1], todo, gen_lfo); - - mLfoOffset = static_cast(mLfoOffset+todo) % lfo_range; -} - -void ChorusState::getSinusoidDelays(uint (*delays)[MAX_UPDATE_SAMPLES], const size_t todo) -{ - const uint lfo_range{mLfoRange}; - const float lfo_scale{mLfoScale}; - const float depth{mDepth}; - const int delay{mDelay}; - - ASSUME(lfo_range > 0); - ASSUME(todo > 0); - - uint offset{mLfoOffset}; - auto gen_lfo = [&offset,lfo_range,lfo_scale,depth,delay]() -> uint - { - offset = (offset+1)%lfo_range; - const float offset_norm{static_cast(offset) * lfo_scale}; - return static_cast(fastf2i(std::sin(offset_norm)*depth) + delay); - }; - std::generate_n(delays[0], todo, gen_lfo); - - offset = (mLfoOffset+mLfoDisp) % lfo_range; - std::generate_n(delays[1], todo, gen_lfo); - - mLfoOffset = static_cast(mLfoOffset+todo) % lfo_range; -} - -void ChorusState::process(const size_t samplesToDo, const al::span samplesIn, const al::span samplesOut) -{ - const size_t bufmask{mSampleBuffer.size()-1}; - const float feedback{mFeedback}; - const uint avgdelay{(static_cast(mDelay) + (MixerFracOne>>1)) >> MixerFracBits}; - float *RESTRICT delaybuf{mSampleBuffer.data()}; - uint offset{mOffset}; - - for(size_t base{0u};base < samplesToDo;) - { - const size_t todo{minz(MAX_UPDATE_SAMPLES, samplesToDo-base)}; - - uint moddelays[2][MAX_UPDATE_SAMPLES]; - if(mWaveform == ChorusWaveform::Sinusoid) - getSinusoidDelays(moddelays, todo); - else /*if(mWaveform == ChorusWaveform::Triangle)*/ - getTriangleDelays(moddelays, todo); - - alignas(16) float temps[2][MAX_UPDATE_SAMPLES]; - for(size_t i{0u};i < todo;++i) - { - // Feed the buffer's input first (necessary for delays < 1). - delaybuf[offset&bufmask] = samplesIn[0][base+i]; - - // Tap for the left output. - uint delay{offset - (moddelays[0][i]>>MixerFracBits)}; - float mu{static_cast(moddelays[0][i]&MixerFracMask) * (1.0f/MixerFracOne)}; - temps[0][i] = cubic(delaybuf[(delay+1) & bufmask], delaybuf[(delay ) & bufmask], - delaybuf[(delay-1) & bufmask], delaybuf[(delay-2) & bufmask], mu); - - // Tap for the right output. - delay = offset - (moddelays[1][i]>>MixerFracBits); - mu = static_cast(moddelays[1][i]&MixerFracMask) * (1.0f/MixerFracOne); - temps[1][i] = cubic(delaybuf[(delay+1) & bufmask], delaybuf[(delay ) & bufmask], - delaybuf[(delay-1) & bufmask], delaybuf[(delay-2) & bufmask], mu); - - // Accumulate feedback from the average delay of the taps. - delaybuf[offset&bufmask] += delaybuf[(offset-avgdelay) & bufmask] * feedback; - ++offset; - } - - for(ALsizei c{0};c < 2;++c) - MixSamples({temps[c], todo}, samplesOut, mGains[c].Current, mGains[c].Target, - samplesToDo-base, base); - - base += todo; - } - - mOffset = offset; -} - - -struct ChorusStateFactory final : public EffectStateFactory { - al::intrusive_ptr create() override - { return al::intrusive_ptr{new ChorusState{}}; } -}; - - -/* Flanger is basically a chorus with a really short delay. They can both use - * the same processing functions, so piggyback flanger on the chorus functions. - */ -struct FlangerStateFactory final : public EffectStateFactory { - al::intrusive_ptr create() override - { return al::intrusive_ptr{new ChorusState{}}; } -}; - -} // namespace - -EffectStateFactory *ChorusStateFactory_getFactory() -{ - static ChorusStateFactory ChorusFactory{}; - return &ChorusFactory; -} - -EffectStateFactory *FlangerStateFactory_getFactory() -{ - static FlangerStateFactory FlangerFactory{}; - return &FlangerFactory; -} diff --git a/alc/effects/compressor.cpp b/alc/effects/compressor.cpp deleted file mode 100644 index 4e2f2098..00000000 --- a/alc/effects/compressor.cpp +++ /dev/null @@ -1,168 +0,0 @@ -/** - * OpenAL cross platform audio library - * Copyright (C) 2013 by Anis A. Hireche - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - * Or go to http://www.gnu.org/copyleft/lgpl.html - */ - -#include "config.h" - -#include - -#include "alcmain.h" -#include "alcontext.h" -#include "alu.h" -#include "effectslot.h" -#include "vecmat.h" - - -namespace { - -#define AMP_ENVELOPE_MIN 0.5f -#define AMP_ENVELOPE_MAX 2.0f - -#define ATTACK_TIME 0.1f /* 100ms to rise from min to max */ -#define RELEASE_TIME 0.2f /* 200ms to drop from max to min */ - - -struct CompressorState final : public EffectState { - /* Effect gains for each channel */ - float mGain[MaxAmbiChannels][MAX_OUTPUT_CHANNELS]{}; - - /* Effect parameters */ - bool mEnabled{true}; - float mAttackMult{1.0f}; - float mReleaseMult{1.0f}; - float mEnvFollower{1.0f}; - - - void deviceUpdate(const ALCdevice *device, const BufferStorage *buffer) override; - void update(const ALCcontext *context, const EffectSlot *slot, const EffectProps *props, - const EffectTarget target) override; - void process(const size_t samplesToDo, const al::span samplesIn, - const al::span samplesOut) override; - - DEF_NEWDEL(CompressorState) -}; - -void CompressorState::deviceUpdate(const ALCdevice *device, const BufferStorage* /*buffer*/) -{ - /* Number of samples to do a full attack and release (non-integer sample - * counts are okay). - */ - const float attackCount{static_cast(device->Frequency) * ATTACK_TIME}; - const float releaseCount{static_cast(device->Frequency) * RELEASE_TIME}; - - /* Calculate per-sample multipliers to attack and release at the desired - * rates. - */ - mAttackMult = std::pow(AMP_ENVELOPE_MAX/AMP_ENVELOPE_MIN, 1.0f/attackCount); - mReleaseMult = std::pow(AMP_ENVELOPE_MIN/AMP_ENVELOPE_MAX, 1.0f/releaseCount); -} - -void CompressorState::update(const ALCcontext*, const EffectSlot *slot, - const EffectProps *props, const EffectTarget target) -{ - mEnabled = props->Compressor.OnOff; - - mOutTarget = target.Main->Buffer; - auto set_gains = [slot,target](auto &gains, al::span coeffs) - { ComputePanGains(target.Main, coeffs.data(), slot->Gain, gains); }; - SetAmbiPanIdentity(std::begin(mGain), slot->Wet.Buffer.size(), set_gains); -} - -void CompressorState::process(const size_t samplesToDo, - const al::span samplesIn, const al::span samplesOut) -{ - for(size_t base{0u};base < samplesToDo;) - { - float gains[256]; - const size_t td{minz(256, samplesToDo-base)}; - - /* Generate the per-sample gains from the signal envelope. */ - float env{mEnvFollower}; - if(mEnabled) - { - for(size_t i{0u};i < td;++i) - { - /* Clamp the absolute amplitude to the defined envelope limits, - * then attack or release the envelope to reach it. - */ - const float amplitude{clampf(std::fabs(samplesIn[0][base+i]), AMP_ENVELOPE_MIN, - AMP_ENVELOPE_MAX)}; - if(amplitude > env) - env = minf(env*mAttackMult, amplitude); - else if(amplitude < env) - env = maxf(env*mReleaseMult, amplitude); - - /* Apply the reciprocal of the envelope to normalize the volume - * (compress the dynamic range). - */ - gains[i] = 1.0f / env; - } - } - else - { - /* Same as above, except the amplitude is forced to 1. This helps - * ensure smooth gain changes when the compressor is turned on and - * off. - */ - for(size_t i{0u};i < td;++i) - { - const float amplitude{1.0f}; - if(amplitude > env) - env = minf(env*mAttackMult, amplitude); - else if(amplitude < env) - env = maxf(env*mReleaseMult, amplitude); - - gains[i] = 1.0f / env; - } - } - mEnvFollower = env; - - /* Now compress the signal amplitude to output. */ - auto changains = std::addressof(mGain[0]); - for(const auto &input : samplesIn) - { - const float *outgains{*(changains++)}; - for(FloatBufferLine &output : samplesOut) - { - const float gain{*(outgains++)}; - if(!(std::fabs(gain) > GainSilenceThreshold)) - continue; - - for(size_t i{0u};i < td;i++) - output[base+i] += input[base+i] * gains[i] * gain; - } - } - - base += td; - } -} - - -struct CompressorStateFactory final : public EffectStateFactory { - al::intrusive_ptr create() override - { return al::intrusive_ptr{new CompressorState{}}; } -}; - -} // namespace - -EffectStateFactory *CompressorStateFactory_getFactory() -{ - static CompressorStateFactory CompressorFactory{}; - return &CompressorFactory; -} diff --git a/alc/effects/convolution.cpp b/alc/effects/convolution.cpp deleted file mode 100644 index 2dec0dc6..00000000 --- a/alc/effects/convolution.cpp +++ /dev/null @@ -1,567 +0,0 @@ - -#include "config.h" - -#include - -#ifdef HAVE_SSE_INTRINSICS -#include -#elif defined(HAVE_NEON) -#include -#endif - -#include "alcmain.h" -#include "alcomplex.h" -#include "alcontext.h" -#include "almalloc.h" -#include "alspan.h" -#include "bformatdec.h" -#include "buffer_storage.h" -#include "core/ambidefs.h" -#include "core/filters/splitter.h" -#include "core/fmt_traits.h" -#include "core/logging.h" -#include "effects/base.h" -#include "effectslot.h" -#include "math_defs.h" -#include "polyphase_resampler.h" - - -namespace { - -/* Convolution reverb is implemented using a segmented overlap-add method. The - * impulse response is broken up into multiple segments of 128 samples, and - * each segment has an FFT applied with a 256-sample buffer (the latter half - * left silent) to get its frequency-domain response. The resulting response - * has its positive/non-mirrored frequencies saved (129 bins) in each segment. - * - * Input samples are similarly broken up into 128-sample segments, with an FFT - * applied to each new incoming segment to get its 129 bins. A history of FFT'd - * input segments is maintained, equal to the length of the impulse response. - * - * To apply the reverberation, each impulse response segment is convolved with - * its paired input segment (using complex multiplies, far cheaper than FIRs), - * accumulating into a 256-bin FFT buffer. The input history is then shifted to - * align with later impulse response segments for next time. - * - * An inverse FFT is then applied to the accumulated FFT buffer to get a 256- - * sample time-domain response for output, which is split in two halves. The - * first half is the 128-sample output, and the second half is a 128-sample - * (really, 127) delayed extension, which gets added to the output next time. - * Convolving two time-domain responses of lengths N and M results in a time- - * domain signal of length N+M-1, and this holds true regardless of the - * convolution being applied in the frequency domain, so these "overflow" - * samples need to be accounted for. - * - * To avoid a delay with gathering enough input samples to apply an FFT with, - * the first segment is applied directly in the time-domain as the samples come - * in. Once enough have been retrieved, the FFT is applied on the input and - * it's paired with the remaining (FFT'd) filter segments for processing. - */ - - -void LoadSamples(double *RESTRICT dst, const al::byte *src, const size_t srcstep, FmtType srctype, - const size_t samples) noexcept -{ -#define HANDLE_FMT(T) case T: al::LoadSampleArray(dst, src, srcstep, samples); break - switch(srctype) - { - HANDLE_FMT(FmtUByte); - HANDLE_FMT(FmtShort); - HANDLE_FMT(FmtFloat); - HANDLE_FMT(FmtDouble); - HANDLE_FMT(FmtMulaw); - HANDLE_FMT(FmtAlaw); - } -#undef HANDLE_FMT -} - - -inline auto& GetAmbiScales(AmbiScaling scaletype) noexcept -{ - if(scaletype == AmbiScaling::FuMa) return AmbiScale::FromFuMa(); - if(scaletype == AmbiScaling::SN3D) return AmbiScale::FromSN3D(); - return AmbiScale::FromN3D(); -} - -inline auto& GetAmbiLayout(AmbiLayout layouttype) noexcept -{ - if(layouttype == AmbiLayout::FuMa) return AmbiIndex::FromFuMa(); - return AmbiIndex::FromACN(); -} - -inline auto& GetAmbi2DLayout(AmbiLayout layouttype) noexcept -{ - if(layouttype == AmbiLayout::FuMa) return AmbiIndex::FromFuMa2D(); - return AmbiIndex::FromACN2D(); -} - - -struct ChanMap { - Channel channel; - float angle; - float elevation; -}; - -using complex_d = std::complex; - -constexpr size_t ConvolveUpdateSize{256}; -constexpr size_t ConvolveUpdateSamples{ConvolveUpdateSize / 2}; - - -void apply_fir(al::span dst, const float *RESTRICT src, const float *RESTRICT filter) -{ -#ifdef HAVE_SSE_INTRINSICS - for(float &output : dst) - { - __m128 r4{_mm_setzero_ps()}; - for(size_t j{0};j < ConvolveUpdateSamples;j+=4) - { - const __m128 coeffs{_mm_load_ps(&filter[j])}; - const __m128 s{_mm_loadu_ps(&src[j])}; - - r4 = _mm_add_ps(r4, _mm_mul_ps(s, coeffs)); - } - r4 = _mm_add_ps(r4, _mm_shuffle_ps(r4, r4, _MM_SHUFFLE(0, 1, 2, 3))); - r4 = _mm_add_ps(r4, _mm_movehl_ps(r4, r4)); - output = _mm_cvtss_f32(r4); - - ++src; - } - -#elif defined(HAVE_NEON) - - for(float &output : dst) - { - float32x4_t r4{vdupq_n_f32(0.0f)}; - for(size_t j{0};j < ConvolveUpdateSamples;j+=4) - r4 = vmlaq_f32(r4, vld1q_f32(&src[j]), vld1q_f32(&filter[j])); - r4 = vaddq_f32(r4, vrev64q_f32(r4)); - output = vget_lane_f32(vadd_f32(vget_low_f32(r4), vget_high_f32(r4)), 0); - - ++src; - } - -#else - - for(float &output : dst) - { - float ret{0.0f}; - for(size_t j{0};j < ConvolveUpdateSamples;++j) - ret += src[j] * filter[j]; - output = ret; - ++src; - } -#endif -} - -struct ConvolutionState final : public EffectState { - FmtChannels mChannels{}; - AmbiLayout mAmbiLayout{}; - AmbiScaling mAmbiScaling{}; - uint mAmbiOrder{}; - - size_t mFifoPos{0}; - std::array mInput{}; - al::vector,16> mFilter; - al::vector,16> mOutput; - - alignas(16) std::array mFftBuffer{}; - - size_t mCurrentSegment{0}; - size_t mNumConvolveSegs{0}; - - struct ChannelData { - alignas(16) FloatBufferLine mBuffer{}; - float mHfScale{}; - BandSplitter mFilter{}; - float Current[MAX_OUTPUT_CHANNELS]{}; - float Target[MAX_OUTPUT_CHANNELS]{}; - }; - using ChannelDataArray = al::FlexArray; - std::unique_ptr mChans; - std::unique_ptr mComplexData; - - - ConvolutionState() = default; - ~ConvolutionState() override = default; - - void NormalMix(const al::span samplesOut, const size_t samplesToDo); - void UpsampleMix(const al::span samplesOut, const size_t samplesToDo); - void (ConvolutionState::*mMix)(const al::span,const size_t) - {&ConvolutionState::NormalMix}; - - void deviceUpdate(const ALCdevice *device, const BufferStorage *buffer) override; - void update(const ALCcontext *context, const EffectSlot *slot, const EffectProps *props, - const EffectTarget target) override; - void process(const size_t samplesToDo, const al::span samplesIn, - const al::span samplesOut) override; - - DEF_NEWDEL(ConvolutionState) -}; - -void ConvolutionState::NormalMix(const al::span samplesOut, - const size_t samplesToDo) -{ - for(auto &chan : *mChans) - MixSamples({chan.mBuffer.data(), samplesToDo}, samplesOut, chan.Current, chan.Target, - samplesToDo, 0); -} - -void ConvolutionState::UpsampleMix(const al::span samplesOut, - const size_t samplesToDo) -{ - for(auto &chan : *mChans) - { - const al::span src{chan.mBuffer.data(), samplesToDo}; - chan.mFilter.processHfScale(src, chan.mHfScale); - MixSamples(src, samplesOut, chan.Current, chan.Target, samplesToDo, 0); - } -} - - -void ConvolutionState::deviceUpdate(const ALCdevice *device, const BufferStorage *buffer) -{ - constexpr uint MaxConvolveAmbiOrder{1u}; - - mFifoPos = 0; - mInput.fill(0.0f); - decltype(mFilter){}.swap(mFilter); - decltype(mOutput){}.swap(mOutput); - mFftBuffer.fill(complex_d{}); - - mCurrentSegment = 0; - mNumConvolveSegs = 0; - - mChans = nullptr; - mComplexData = nullptr; - - /* An empty buffer doesn't need a convolution filter. */ - if(!buffer || buffer->mSampleLen < 1) return; - - constexpr size_t m{ConvolveUpdateSize/2 + 1}; - auto bytesPerSample = BytesFromFmt(buffer->mType); - auto realChannels = ChannelsFromFmt(buffer->mChannels, buffer->mAmbiOrder); - auto numChannels = ChannelsFromFmt(buffer->mChannels, - minu(buffer->mAmbiOrder, MaxConvolveAmbiOrder)); - - mChans = ChannelDataArray::Create(numChannels); - - /* The impulse response needs to have the same sample rate as the input and - * output. The bsinc24 resampler is decent, but there is high-frequency - * attenation that some people may be able to pick up on. Since this is - * called very infrequently, go ahead and use the polyphase resampler. - */ - PPhaseResampler resampler; - if(device->Frequency != buffer->mSampleRate) - resampler.init(buffer->mSampleRate, device->Frequency); - const auto resampledCount = static_cast( - (uint64_t{buffer->mSampleLen}*device->Frequency + (buffer->mSampleRate-1)) / - buffer->mSampleRate); - - const BandSplitter splitter{device->mXOverFreq / static_cast(device->Frequency)}; - for(auto &e : *mChans) - e.mFilter = splitter; - - mFilter.resize(numChannels, {}); - mOutput.resize(numChannels, {}); - - /* Calculate the number of segments needed to hold the impulse response and - * the input history (rounded up), and allocate them. Exclude one segment - * which gets applied as a time-domain FIR filter. Make sure at least one - * segment is allocated to simplify handling. - */ - mNumConvolveSegs = (resampledCount+(ConvolveUpdateSamples-1)) / ConvolveUpdateSamples; - mNumConvolveSegs = maxz(mNumConvolveSegs, 2) - 1; - - const size_t complex_length{mNumConvolveSegs * m * (numChannels+1)}; - mComplexData = std::make_unique(complex_length); - std::fill_n(mComplexData.get(), complex_length, complex_d{}); - - mChannels = buffer->mChannels; - mAmbiLayout = buffer->mAmbiLayout; - mAmbiScaling = buffer->mAmbiScaling; - mAmbiOrder = minu(buffer->mAmbiOrder, MaxConvolveAmbiOrder); - - auto srcsamples = std::make_unique(maxz(buffer->mSampleLen, resampledCount)); - complex_d *filteriter = mComplexData.get() + mNumConvolveSegs*m; - for(size_t c{0};c < numChannels;++c) - { - /* Load the samples from the buffer, and resample to match the device. */ - LoadSamples(srcsamples.get(), buffer->mData.data() + bytesPerSample*c, realChannels, - buffer->mType, buffer->mSampleLen); - if(device->Frequency != buffer->mSampleRate) - resampler.process(buffer->mSampleLen, srcsamples.get(), resampledCount, - srcsamples.get()); - - /* Store the first segment's samples in reverse in the time-domain, to - * apply as a FIR filter. - */ - const size_t first_size{minz(resampledCount, ConvolveUpdateSamples)}; - std::transform(srcsamples.get(), srcsamples.get()+first_size, mFilter[c].rbegin(), - [](const double d) noexcept -> float { return static_cast(d); }); - - size_t done{first_size}; - for(size_t s{0};s < mNumConvolveSegs;++s) - { - const size_t todo{minz(resampledCount-done, ConvolveUpdateSamples)}; - - auto iter = std::copy_n(&srcsamples[done], todo, mFftBuffer.begin()); - done += todo; - std::fill(iter, mFftBuffer.end(), complex_d{}); - - forward_fft(mFftBuffer); - filteriter = std::copy_n(mFftBuffer.cbegin(), m, filteriter); - } - } -} - - -void ConvolutionState::update(const ALCcontext *context, const EffectSlot *slot, - const EffectProps* /*props*/, const EffectTarget target) -{ - /* NOTE: Stereo and Rear are slightly different from normal mixing (as - * defined in alu.cpp). These are 45 degrees from center, rather than the - * 30 degrees used there. - * - * TODO: LFE is not mixed to output. This will require each buffer channel - * to have its own output target since the main mixing buffer won't have an - * LFE channel (due to being B-Format). - */ - static const ChanMap MonoMap[1]{ - { FrontCenter, 0.0f, 0.0f } - }, StereoMap[2]{ - { FrontLeft, Deg2Rad(-45.0f), Deg2Rad(0.0f) }, - { FrontRight, Deg2Rad( 45.0f), Deg2Rad(0.0f) } - }, RearMap[2]{ - { BackLeft, Deg2Rad(-135.0f), Deg2Rad(0.0f) }, - { BackRight, Deg2Rad( 135.0f), Deg2Rad(0.0f) } - }, QuadMap[4]{ - { FrontLeft, Deg2Rad( -45.0f), Deg2Rad(0.0f) }, - { FrontRight, Deg2Rad( 45.0f), Deg2Rad(0.0f) }, - { BackLeft, Deg2Rad(-135.0f), Deg2Rad(0.0f) }, - { BackRight, Deg2Rad( 135.0f), Deg2Rad(0.0f) } - }, X51Map[6]{ - { FrontLeft, Deg2Rad( -30.0f), Deg2Rad(0.0f) }, - { FrontRight, Deg2Rad( 30.0f), Deg2Rad(0.0f) }, - { FrontCenter, Deg2Rad( 0.0f), Deg2Rad(0.0f) }, - { LFE, 0.0f, 0.0f }, - { SideLeft, Deg2Rad(-110.0f), Deg2Rad(0.0f) }, - { SideRight, Deg2Rad( 110.0f), Deg2Rad(0.0f) } - }, X61Map[7]{ - { FrontLeft, Deg2Rad(-30.0f), Deg2Rad(0.0f) }, - { FrontRight, Deg2Rad( 30.0f), Deg2Rad(0.0f) }, - { FrontCenter, Deg2Rad( 0.0f), Deg2Rad(0.0f) }, - { LFE, 0.0f, 0.0f }, - { BackCenter, Deg2Rad(180.0f), Deg2Rad(0.0f) }, - { SideLeft, Deg2Rad(-90.0f), Deg2Rad(0.0f) }, - { SideRight, Deg2Rad( 90.0f), Deg2Rad(0.0f) } - }, X71Map[8]{ - { FrontLeft, Deg2Rad( -30.0f), Deg2Rad(0.0f) }, - { FrontRight, Deg2Rad( 30.0f), Deg2Rad(0.0f) }, - { FrontCenter, Deg2Rad( 0.0f), Deg2Rad(0.0f) }, - { LFE, 0.0f, 0.0f }, - { BackLeft, Deg2Rad(-150.0f), Deg2Rad(0.0f) }, - { BackRight, Deg2Rad( 150.0f), Deg2Rad(0.0f) }, - { SideLeft, Deg2Rad( -90.0f), Deg2Rad(0.0f) }, - { SideRight, Deg2Rad( 90.0f), Deg2Rad(0.0f) } - }; - - if(mNumConvolveSegs < 1) - return; - - mMix = &ConvolutionState::NormalMix; - - for(auto &chan : *mChans) - std::fill(std::begin(chan.Target), std::end(chan.Target), 0.0f); - const float gain{slot->Gain}; - if(mChannels == FmtBFormat3D || mChannels == FmtBFormat2D) - { - ALCdevice *device{context->mDevice.get()}; - if(device->mAmbiOrder > mAmbiOrder) - { - mMix = &ConvolutionState::UpsampleMix; - const auto scales = BFormatDec::GetHFOrderScales(mAmbiOrder, device->mAmbiOrder); - (*mChans)[0].mHfScale = scales[0]; - for(size_t i{1};i < mChans->size();++i) - (*mChans)[i].mHfScale = scales[1]; - } - mOutTarget = target.Main->Buffer; - - auto&& scales = GetAmbiScales(mAmbiScaling); - const uint8_t *index_map{(mChannels == FmtBFormat2D) ? - GetAmbi2DLayout(mAmbiLayout).data() : - GetAmbiLayout(mAmbiLayout).data()}; - - std::array coeffs{}; - for(size_t c{0u};c < mChans->size();++c) - { - const size_t acn{index_map[c]}; - coeffs[acn] = scales[acn]; - ComputePanGains(target.Main, coeffs.data(), gain, (*mChans)[c].Target); - coeffs[acn] = 0.0f; - } - } - else - { - ALCdevice *device{context->mDevice.get()}; - al::span chanmap{}; - switch(mChannels) - { - case FmtMono: chanmap = MonoMap; break; - case FmtStereo: chanmap = StereoMap; break; - case FmtRear: chanmap = RearMap; break; - case FmtQuad: chanmap = QuadMap; break; - case FmtX51: chanmap = X51Map; break; - case FmtX61: chanmap = X61Map; break; - case FmtX71: chanmap = X71Map; break; - case FmtBFormat2D: - case FmtBFormat3D: - break; - } - - mOutTarget = target.Main->Buffer; - if(device->mRenderMode == RenderMode::Pairwise) - { - auto ScaleAzimuthFront = [](float azimuth, float scale) -> float - { - const float abs_azi{std::fabs(azimuth)}; - if(!(abs_azi >= al::MathDefs::Pi()*0.5f)) - return std::copysign(minf(abs_azi*scale, al::MathDefs::Pi()*0.5f), azimuth); - return azimuth; - }; - - for(size_t i{0};i < chanmap.size();++i) - { - if(chanmap[i].channel == LFE) continue; - const auto coeffs = CalcAngleCoeffs(ScaleAzimuthFront(chanmap[i].angle, 2.0f), - chanmap[i].elevation, 0.0f); - ComputePanGains(target.Main, coeffs.data(), gain, (*mChans)[i].Target); - } - } - else for(size_t i{0};i < chanmap.size();++i) - { - if(chanmap[i].channel == LFE) continue; - const auto coeffs = CalcAngleCoeffs(chanmap[i].angle, chanmap[i].elevation, 0.0f); - ComputePanGains(target.Main, coeffs.data(), gain, (*mChans)[i].Target); - } - } -} - -void ConvolutionState::process(const size_t samplesToDo, - const al::span samplesIn, const al::span samplesOut) -{ - if(mNumConvolveSegs < 1) - return; - - constexpr size_t m{ConvolveUpdateSize/2 + 1}; - size_t curseg{mCurrentSegment}; - auto &chans = *mChans; - - for(size_t base{0u};base < samplesToDo;) - { - const size_t todo{minz(ConvolveUpdateSamples-mFifoPos, samplesToDo-base)}; - - std::copy_n(samplesIn[0].begin() + base, todo, - mInput.begin()+ConvolveUpdateSamples+mFifoPos); - - /* Apply the FIR for the newly retrieved input samples, and combine it - * with the inverse FFT'd output samples. - */ - for(size_t c{0};c < chans.size();++c) - { - auto buf_iter = chans[c].mBuffer.begin() + base; - apply_fir({std::addressof(*buf_iter), todo}, mInput.data()+1 + mFifoPos, - mFilter[c].data()); - - auto fifo_iter = mOutput[c].begin() + mFifoPos; - std::transform(fifo_iter, fifo_iter+todo, buf_iter, buf_iter, std::plus<>{}); - } - - mFifoPos += todo; - base += todo; - - /* Check whether the input buffer is filled with new samples. */ - if(mFifoPos < ConvolveUpdateSamples) break; - mFifoPos = 0; - - /* Move the newest input to the front for the next iteration's history. */ - std::copy(mInput.cbegin()+ConvolveUpdateSamples, mInput.cend(), mInput.begin()); - - /* Calculate the frequency domain response and add the relevant - * frequency bins to the FFT history. - */ - auto fftiter = std::copy_n(mInput.cbegin(), ConvolveUpdateSamples, mFftBuffer.begin()); - std::fill(fftiter, mFftBuffer.end(), complex_d{}); - forward_fft(mFftBuffer); - - std::copy_n(mFftBuffer.cbegin(), m, &mComplexData[curseg*m]); - - const complex_d *RESTRICT filter{mComplexData.get() + mNumConvolveSegs*m}; - for(size_t c{0};c < chans.size();++c) - { - std::fill_n(mFftBuffer.begin(), m, complex_d{}); - - /* Convolve each input segment with its IR filter counterpart - * (aligned in time). - */ - const complex_d *RESTRICT input{&mComplexData[curseg*m]}; - for(size_t s{curseg};s < mNumConvolveSegs;++s) - { - for(size_t i{0};i < m;++i,++input,++filter) - mFftBuffer[i] += *input * *filter; - } - input = mComplexData.get(); - for(size_t s{0};s < curseg;++s) - { - for(size_t i{0};i < m;++i,++input,++filter) - mFftBuffer[i] += *input * *filter; - } - - /* Reconstruct the mirrored/negative frequencies to do a proper - * inverse FFT. - */ - for(size_t i{m};i < ConvolveUpdateSize;++i) - mFftBuffer[i] = std::conj(mFftBuffer[ConvolveUpdateSize-i]); - - /* Apply iFFT to get the 256 (really 255) samples for output. The - * 128 output samples are combined with the last output's 127 - * second-half samples (and this output's second half is - * subsequently saved for next time). - */ - inverse_fft(mFftBuffer); - - /* The iFFT'd response is scaled up by the number of bins, so apply - * the inverse to normalize the output. - */ - for(size_t i{0};i < ConvolveUpdateSamples;++i) - mOutput[c][i] = - static_cast(mFftBuffer[i].real() * (1.0/double{ConvolveUpdateSize})) + - mOutput[c][ConvolveUpdateSamples+i]; - for(size_t i{0};i < ConvolveUpdateSamples;++i) - mOutput[c][ConvolveUpdateSamples+i] = - static_cast(mFftBuffer[ConvolveUpdateSamples+i].real() * - (1.0/double{ConvolveUpdateSize})); - } - - /* Shift the input history. */ - curseg = curseg ? (curseg-1) : (mNumConvolveSegs-1); - } - mCurrentSegment = curseg; - - /* Finally, mix to the output. */ - (this->*mMix)(samplesOut, samplesToDo); -} - - -struct ConvolutionStateFactory final : public EffectStateFactory { - al::intrusive_ptr create() override - { return al::intrusive_ptr{new ConvolutionState{}}; } -}; - -} // namespace - -EffectStateFactory *ConvolutionStateFactory_getFactory() -{ - static ConvolutionStateFactory ConvolutionFactory{}; - return &ConvolutionFactory; -} diff --git a/alc/effects/dedicated.cpp b/alc/effects/dedicated.cpp deleted file mode 100644 index 876b14ef..00000000 --- a/alc/effects/dedicated.cpp +++ /dev/null @@ -1,110 +0,0 @@ -/** - * OpenAL cross platform audio library - * Copyright (C) 2011 by Chris Robinson. - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - * Or go to http://www.gnu.org/copyleft/lgpl.html - */ - -#include "config.h" - -#include -#include -#include - -#include "alcmain.h" -#include "alcontext.h" -#include "alu.h" -#include "effectslot.h" - - -namespace { - -struct DedicatedState final : public EffectState { - float mCurrentGains[MAX_OUTPUT_CHANNELS]; - float mTargetGains[MAX_OUTPUT_CHANNELS]; - - - void deviceUpdate(const ALCdevice *device, const BufferStorage *buffer) override; - void update(const ALCcontext *context, const EffectSlot *slot, const EffectProps *props, - const EffectTarget target) override; - void process(const size_t samplesToDo, const al::span samplesIn, - const al::span samplesOut) override; - - DEF_NEWDEL(DedicatedState) -}; - -void DedicatedState::deviceUpdate(const ALCdevice*, const BufferStorage*) -{ - std::fill(std::begin(mCurrentGains), std::end(mCurrentGains), 0.0f); -} - -void DedicatedState::update(const ALCcontext*, const EffectSlot *slot, - const EffectProps *props, const EffectTarget target) -{ - std::fill(std::begin(mTargetGains), std::end(mTargetGains), 0.0f); - - const float Gain{slot->Gain * props->Dedicated.Gain}; - - if(slot->EffectType == EffectSlotType::DedicatedLFE) - { - const uint idx{!target.RealOut ? INVALID_CHANNEL_INDEX : - GetChannelIdxByName(*target.RealOut, LFE)}; - if(idx != INVALID_CHANNEL_INDEX) - { - mOutTarget = target.RealOut->Buffer; - mTargetGains[idx] = Gain; - } - } - else if(slot->EffectType == EffectSlotType::DedicatedDialog) - { - /* Dialog goes to the front-center speaker if it exists, otherwise it - * plays from the front-center location. */ - const uint idx{!target.RealOut ? INVALID_CHANNEL_INDEX : - GetChannelIdxByName(*target.RealOut, FrontCenter)}; - if(idx != INVALID_CHANNEL_INDEX) - { - mOutTarget = target.RealOut->Buffer; - mTargetGains[idx] = Gain; - } - else - { - const auto coeffs = CalcDirectionCoeffs({0.0f, 0.0f, -1.0f}, 0.0f); - - mOutTarget = target.Main->Buffer; - ComputePanGains(target.Main, coeffs.data(), Gain, mTargetGains); - } - } -} - -void DedicatedState::process(const size_t samplesToDo, const al::span samplesIn, const al::span samplesOut) -{ - MixSamples({samplesIn[0].data(), samplesToDo}, samplesOut, mCurrentGains, mTargetGains, - samplesToDo, 0); -} - - -struct DedicatedStateFactory final : public EffectStateFactory { - al::intrusive_ptr create() override - { return al::intrusive_ptr{new DedicatedState{}}; } -}; - -} // namespace - -EffectStateFactory *DedicatedStateFactory_getFactory() -{ - static DedicatedStateFactory DedicatedFactory{}; - return &DedicatedFactory; -} diff --git a/alc/effects/distortion.cpp b/alc/effects/distortion.cpp deleted file mode 100644 index 46ca03d8..00000000 --- a/alc/effects/distortion.cpp +++ /dev/null @@ -1,167 +0,0 @@ -/** - * OpenAL cross platform audio library - * Copyright (C) 2013 by Mike Gorchak - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - * Or go to http://www.gnu.org/copyleft/lgpl.html - */ - -#include "config.h" - -#include -#include -#include - -#include "alcmain.h" -#include "alcontext.h" -#include "core/filters/biquad.h" -#include "effectslot.h" - - -namespace { - -struct DistortionState final : public EffectState { - /* Effect gains for each channel */ - float mGain[MAX_OUTPUT_CHANNELS]{}; - - /* Effect parameters */ - BiquadFilter mLowpass; - BiquadFilter mBandpass; - float mAttenuation{}; - float mEdgeCoeff{}; - - float mBuffer[2][BufferLineSize]{}; - - - void deviceUpdate(const ALCdevice *device, const BufferStorage *buffer) override; - void update(const ALCcontext *context, const EffectSlot *slot, const EffectProps *props, - const EffectTarget target) override; - void process(const size_t samplesToDo, const al::span samplesIn, - const al::span samplesOut) override; - - DEF_NEWDEL(DistortionState) -}; - -void DistortionState::deviceUpdate(const ALCdevice*, const BufferStorage*) -{ - mLowpass.clear(); - mBandpass.clear(); -} - -void DistortionState::update(const ALCcontext *context, const EffectSlot *slot, - const EffectProps *props, const EffectTarget target) -{ - const ALCdevice *device{context->mDevice.get()}; - - /* Store waveshaper edge settings. */ - const float edge{minf(std::sin(al::MathDefs::Pi()*0.5f * props->Distortion.Edge), - 0.99f)}; - mEdgeCoeff = 2.0f * edge / (1.0f-edge); - - float cutoff{props->Distortion.LowpassCutoff}; - /* Bandwidth value is constant in octaves. */ - float bandwidth{(cutoff / 2.0f) / (cutoff * 0.67f)}; - /* Divide normalized frequency by the amount of oversampling done during - * processing. - */ - auto frequency = static_cast(device->Frequency); - mLowpass.setParamsFromBandwidth(BiquadType::LowPass, cutoff/frequency/4.0f, 1.0f, bandwidth); - - cutoff = props->Distortion.EQCenter; - /* Convert bandwidth in Hz to octaves. */ - bandwidth = props->Distortion.EQBandwidth / (cutoff * 0.67f); - mBandpass.setParamsFromBandwidth(BiquadType::BandPass, cutoff/frequency/4.0f, 1.0f, bandwidth); - - const auto coeffs = CalcDirectionCoeffs({0.0f, 0.0f, -1.0f}, 0.0f); - - mOutTarget = target.Main->Buffer; - ComputePanGains(target.Main, coeffs.data(), slot->Gain*props->Distortion.Gain, mGain); -} - -void DistortionState::process(const size_t samplesToDo, const al::span samplesIn, const al::span samplesOut) -{ - const float fc{mEdgeCoeff}; - for(size_t base{0u};base < samplesToDo;) - { - /* Perform 4x oversampling to avoid aliasing. Oversampling greatly - * improves distortion quality and allows to implement lowpass and - * bandpass filters using high frequencies, at which classic IIR - * filters became unstable. - */ - size_t todo{minz(BufferLineSize, (samplesToDo-base) * 4)}; - - /* Fill oversample buffer using zero stuffing. Multiply the sample by - * the amount of oversampling to maintain the signal's power. - */ - for(size_t i{0u};i < todo;i++) - mBuffer[0][i] = !(i&3) ? samplesIn[0][(i>>2)+base] * 4.0f : 0.0f; - - /* First step, do lowpass filtering of original signal. Additionally - * perform buffer interpolation and lowpass cutoff for oversampling - * (which is fortunately first step of distortion). So combine three - * operations into the one. - */ - mLowpass.process({mBuffer[0], todo}, mBuffer[1]); - - /* Second step, do distortion using waveshaper function to emulate - * signal processing during tube overdriving. Three steps of - * waveshaping are intended to modify waveform without boost/clipping/ - * attenuation process. - */ - auto proc_sample = [fc](float smp) -> float - { - smp = (1.0f + fc) * smp/(1.0f + fc*std::abs(smp)); - smp = (1.0f + fc) * smp/(1.0f + fc*std::abs(smp)) * -1.0f; - smp = (1.0f + fc) * smp/(1.0f + fc*std::abs(smp)); - return smp; - }; - std::transform(std::begin(mBuffer[1]), std::begin(mBuffer[1])+todo, std::begin(mBuffer[0]), - proc_sample); - - /* Third step, do bandpass filtering of distorted signal. */ - mBandpass.process({mBuffer[0], todo}, mBuffer[1]); - - todo >>= 2; - const float *outgains{mGain}; - for(FloatBufferLine &output : samplesOut) - { - /* Fourth step, final, do attenuation and perform decimation, - * storing only one sample out of four. - */ - const float gain{*(outgains++)}; - if(!(std::fabs(gain) > GainSilenceThreshold)) - continue; - - for(size_t i{0u};i < todo;i++) - output[base+i] += gain * mBuffer[1][i*4]; - } - - base += todo; - } -} - - -struct DistortionStateFactory final : public EffectStateFactory { - al::intrusive_ptr create() override - { return al::intrusive_ptr{new DistortionState{}}; } -}; - -} // namespace - -EffectStateFactory *DistortionStateFactory_getFactory() -{ - static DistortionStateFactory DistortionFactory{}; - return &DistortionFactory; -} diff --git a/alc/effects/echo.cpp b/alc/effects/echo.cpp deleted file mode 100644 index b84e501a..00000000 --- a/alc/effects/echo.cpp +++ /dev/null @@ -1,168 +0,0 @@ -/** - * OpenAL cross platform audio library - * Copyright (C) 2009 by Chris Robinson. - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - * Or go to http://www.gnu.org/copyleft/lgpl.html - */ - -#include "config.h" - -#include -#include - -#include - -#include "alcmain.h" -#include "alcontext.h" -#include "core/filters/biquad.h" -#include "effectslot.h" -#include "vector.h" - - -namespace { - -constexpr float LowpassFreqRef{5000.0f}; - -struct EchoState final : public EffectState { - al::vector mSampleBuffer; - - // The echo is two tap. The delay is the number of samples from before the - // current offset - struct { - size_t delay{0u}; - } mTap[2]; - size_t mOffset{0u}; - - /* The panning gains for the two taps */ - struct { - float Current[MAX_OUTPUT_CHANNELS]{}; - float Target[MAX_OUTPUT_CHANNELS]{}; - } mGains[2]; - - BiquadFilter mFilter; - float mFeedGain{0.0f}; - - alignas(16) float mTempBuffer[2][BufferLineSize]; - - void deviceUpdate(const ALCdevice *device, const BufferStorage *buffer) override; - void update(const ALCcontext *context, const EffectSlot *slot, const EffectProps *props, - const EffectTarget target) override; - void process(const size_t samplesToDo, const al::span samplesIn, - const al::span samplesOut) override; - - DEF_NEWDEL(EchoState) -}; - -void EchoState::deviceUpdate(const ALCdevice *Device, const BufferStorage* /*buffer*/) -{ - const auto frequency = static_cast(Device->Frequency); - - // Use the next power of 2 for the buffer length, so the tap offsets can be - // wrapped using a mask instead of a modulo - const uint maxlen{NextPowerOf2(float2uint(EchoMaxDelay*frequency + 0.5f) + - float2uint(EchoMaxLRDelay*frequency + 0.5f))}; - if(maxlen != mSampleBuffer.size()) - al::vector(maxlen).swap(mSampleBuffer); - - std::fill(mSampleBuffer.begin(), mSampleBuffer.end(), 0.0f); - for(auto &e : mGains) - { - std::fill(std::begin(e.Current), std::end(e.Current), 0.0f); - std::fill(std::begin(e.Target), std::end(e.Target), 0.0f); - } -} - -void EchoState::update(const ALCcontext *context, const EffectSlot *slot, - const EffectProps *props, const EffectTarget target) -{ - const ALCdevice *device{context->mDevice.get()}; - const auto frequency = static_cast(device->Frequency); - - mTap[0].delay = maxu(float2uint(props->Echo.Delay*frequency + 0.5f), 1); - mTap[1].delay = float2uint(props->Echo.LRDelay*frequency + 0.5f) + mTap[0].delay; - - const float gainhf{maxf(1.0f - props->Echo.Damping, 0.0625f)}; /* Limit -24dB */ - mFilter.setParamsFromSlope(BiquadType::HighShelf, LowpassFreqRef/frequency, gainhf, 1.0f); - - mFeedGain = props->Echo.Feedback; - - /* Convert echo spread (where 0 = center, +/-1 = sides) to angle. */ - const float angle{std::asin(props->Echo.Spread)}; - - const auto coeffs0 = CalcAngleCoeffs(-angle, 0.0f, 0.0f); - const auto coeffs1 = CalcAngleCoeffs( angle, 0.0f, 0.0f); - - mOutTarget = target.Main->Buffer; - ComputePanGains(target.Main, coeffs0.data(), slot->Gain, mGains[0].Target); - ComputePanGains(target.Main, coeffs1.data(), slot->Gain, mGains[1].Target); -} - -void EchoState::process(const size_t samplesToDo, const al::span samplesIn, const al::span samplesOut) -{ - const size_t mask{mSampleBuffer.size()-1}; - float *RESTRICT delaybuf{mSampleBuffer.data()}; - size_t offset{mOffset}; - size_t tap1{offset - mTap[0].delay}; - size_t tap2{offset - mTap[1].delay}; - float z1, z2; - - ASSUME(samplesToDo > 0); - - const BiquadFilter filter{mFilter}; - std::tie(z1, z2) = mFilter.getComponents(); - for(size_t i{0u};i < samplesToDo;) - { - offset &= mask; - tap1 &= mask; - tap2 &= mask; - - size_t td{minz(mask+1 - maxz(offset, maxz(tap1, tap2)), samplesToDo-i)}; - do { - /* Feed the delay buffer's input first. */ - delaybuf[offset] = samplesIn[0][i]; - - /* Get delayed output from the first and second taps. Use the - * second tap for feedback. - */ - mTempBuffer[0][i] = delaybuf[tap1++]; - mTempBuffer[1][i] = delaybuf[tap2++]; - const float feedb{mTempBuffer[1][i++]}; - - /* Add feedback to the delay buffer with damping and attenuation. */ - delaybuf[offset++] += filter.processOne(feedb, z1, z2) * mFeedGain; - } while(--td); - } - mFilter.setComponents(z1, z2); - mOffset = offset; - - for(ALsizei c{0};c < 2;c++) - MixSamples({mTempBuffer[c], samplesToDo}, samplesOut, mGains[c].Current, mGains[c].Target, - samplesToDo, 0); -} - - -struct EchoStateFactory final : public EffectStateFactory { - al::intrusive_ptr create() override - { return al::intrusive_ptr{new EchoState{}}; } -}; - -} // namespace - -EffectStateFactory *EchoStateFactory_getFactory() -{ - static EchoStateFactory EchoFactory{}; - return &EchoFactory; -} diff --git a/alc/effects/equalizer.cpp b/alc/effects/equalizer.cpp deleted file mode 100644 index 133ab319..00000000 --- a/alc/effects/equalizer.cpp +++ /dev/null @@ -1,184 +0,0 @@ -/** - * OpenAL cross platform audio library - * Copyright (C) 2013 by Mike Gorchak - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - * Or go to http://www.gnu.org/copyleft/lgpl.html - */ - -#include "config.h" - -#include -#include - -#include -#include - -#include "alcmain.h" -#include "alcontext.h" -#include "core/filters/biquad.h" -#include "effectslot.h" -#include "vecmat.h" - - -namespace { - -/* The document "Effects Extension Guide.pdf" says that low and high * - * frequencies are cutoff frequencies. This is not fully correct, they * - * are corner frequencies for low and high shelf filters. If they were * - * just cutoff frequencies, there would be no need in cutoff frequency * - * gains, which are present. Documentation for "Creative Proteus X2" * - * software describes 4-band equalizer functionality in a much better * - * way. This equalizer seems to be a predecessor of OpenAL 4-band * - * equalizer. With low and high shelf filters we are able to cutoff * - * frequencies below and/or above corner frequencies using attenuation * - * gains (below 1.0) and amplify all low and/or high frequencies using * - * gains above 1.0. * - * * - * Low-shelf Low Mid Band High Mid Band High-shelf * - * corner center center corner * - * frequency frequency frequency frequency * - * 50Hz..800Hz 200Hz..3000Hz 1000Hz..8000Hz 4000Hz..16000Hz * - * * - * | | | | * - * | | | | * - * B -----+ /--+--\ /--+--\ +----- * - * O |\ | | | | | | /| * - * O | \ - | - - | - / | * - * S + | \ | | | | | | / | * - * T | | | | | | | | | | * - * ---------+---------------+------------------+---------------+-------- * - * C | | | | | | | | | | * - * U - | / | | | | | | \ | * - * T | / - | - - | - \ | * - * O |/ | | | | | | \| * - * F -----+ \--+--/ \--+--/ +----- * - * F | | | | * - * | | | | * - * * - * Gains vary from 0.126 up to 7.943, which means from -18dB attenuation * - * up to +18dB amplification. Band width varies from 0.01 up to 1.0 in * - * octaves for two mid bands. * - * * - * Implementation is based on the "Cookbook formulae for audio EQ biquad * - * filter coefficients" by Robert Bristow-Johnson * - * http://www.musicdsp.org/files/Audio-EQ-Cookbook.txt */ - - -struct EqualizerState final : public EffectState { - struct { - /* Effect parameters */ - BiquadFilter filter[4]; - - /* Effect gains for each channel */ - float CurrentGains[MAX_OUTPUT_CHANNELS]{}; - float TargetGains[MAX_OUTPUT_CHANNELS]{}; - } mChans[MaxAmbiChannels]; - - FloatBufferLine mSampleBuffer{}; - - - void deviceUpdate(const ALCdevice *device, const BufferStorage *buffer) override; - void update(const ALCcontext *context, const EffectSlot *slot, const EffectProps *props, - const EffectTarget target) override; - void process(const size_t samplesToDo, const al::span samplesIn, - const al::span samplesOut) override; - - DEF_NEWDEL(EqualizerState) -}; - -void EqualizerState::deviceUpdate(const ALCdevice*, const BufferStorage*) -{ - for(auto &e : mChans) - { - std::for_each(std::begin(e.filter), std::end(e.filter), std::mem_fn(&BiquadFilter::clear)); - std::fill(std::begin(e.CurrentGains), std::end(e.CurrentGains), 0.0f); - } -} - -void EqualizerState::update(const ALCcontext *context, const EffectSlot *slot, - const EffectProps *props, const EffectTarget target) -{ - const ALCdevice *device{context->mDevice.get()}; - auto frequency = static_cast(device->Frequency); - float gain, f0norm; - - /* Calculate coefficients for the each type of filter. Note that the shelf - * and peaking filters' gain is for the centerpoint of the transition band, - * while the effect property gains are for the shelf/peak itself. So the - * property gains need their dB halved (sqrt of linear gain) for the - * shelf/peak to reach the provided gain. - */ - gain = std::sqrt(props->Equalizer.LowGain); - f0norm = props->Equalizer.LowCutoff / frequency; - mChans[0].filter[0].setParamsFromSlope(BiquadType::LowShelf, f0norm, gain, 0.75f); - - gain = std::sqrt(props->Equalizer.Mid1Gain); - f0norm = props->Equalizer.Mid1Center / frequency; - mChans[0].filter[1].setParamsFromBandwidth(BiquadType::Peaking, f0norm, gain, - props->Equalizer.Mid1Width); - - gain = std::sqrt(props->Equalizer.Mid2Gain); - f0norm = props->Equalizer.Mid2Center / frequency; - mChans[0].filter[2].setParamsFromBandwidth(BiquadType::Peaking, f0norm, gain, - props->Equalizer.Mid2Width); - - gain = std::sqrt(props->Equalizer.HighGain); - f0norm = props->Equalizer.HighCutoff / frequency; - mChans[0].filter[3].setParamsFromSlope(BiquadType::HighShelf, f0norm, gain, 0.75f); - - /* Copy the filter coefficients for the other input channels. */ - for(size_t i{1u};i < slot->Wet.Buffer.size();++i) - { - mChans[i].filter[0].copyParamsFrom(mChans[0].filter[0]); - mChans[i].filter[1].copyParamsFrom(mChans[0].filter[1]); - mChans[i].filter[2].copyParamsFrom(mChans[0].filter[2]); - mChans[i].filter[3].copyParamsFrom(mChans[0].filter[3]); - } - - mOutTarget = target.Main->Buffer; - auto set_gains = [slot,target](auto &chan, al::span coeffs) - { ComputePanGains(target.Main, coeffs.data(), slot->Gain, chan.TargetGains); }; - SetAmbiPanIdentity(std::begin(mChans), slot->Wet.Buffer.size(), set_gains); -} - -void EqualizerState::process(const size_t samplesToDo, const al::span samplesIn, const al::span samplesOut) -{ - const al::span buffer{mSampleBuffer.data(), samplesToDo}; - auto chan = std::addressof(mChans[0]); - for(const auto &input : samplesIn) - { - const al::span inbuf{input.data(), samplesToDo}; - DualBiquad{chan->filter[0], chan->filter[1]}.process(inbuf, buffer.begin()); - DualBiquad{chan->filter[2], chan->filter[3]}.process(buffer, buffer.begin()); - - MixSamples(buffer, samplesOut, chan->CurrentGains, chan->TargetGains, samplesToDo, 0u); - ++chan; - } -} - - -struct EqualizerStateFactory final : public EffectStateFactory { - al::intrusive_ptr create() override - { return al::intrusive_ptr{new EqualizerState{}}; } -}; - -} // namespace - -EffectStateFactory *EqualizerStateFactory_getFactory() -{ - static EqualizerStateFactory EqualizerFactory{}; - return &EqualizerFactory; -} diff --git a/alc/effects/fshifter.cpp b/alc/effects/fshifter.cpp deleted file mode 100644 index 1f202fc3..00000000 --- a/alc/effects/fshifter.cpp +++ /dev/null @@ -1,232 +0,0 @@ -/** - * OpenAL cross platform audio library - * Copyright (C) 2018 by Raul Herraiz. - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - * Or go to http://www.gnu.org/copyleft/lgpl.html - */ - -#include "config.h" - -#include -#include -#include -#include -#include - -#include "alcmain.h" -#include "alcomplex.h" -#include "alcontext.h" -#include "alu.h" -#include "effectslot.h" -#include "math_defs.h" - - -namespace { - -using complex_d = std::complex; - -#define HIL_SIZE 1024 -#define OVERSAMP (1<<2) - -#define HIL_STEP (HIL_SIZE / OVERSAMP) -#define FIFO_LATENCY (HIL_STEP * (OVERSAMP-1)) - -/* Define a Hann window, used to filter the HIL input and output. */ -std::array InitHannWindow() -{ - std::array ret; - /* Create lookup table of the Hann window for the desired size, i.e. HIL_SIZE */ - for(size_t i{0};i < HIL_SIZE>>1;i++) - { - constexpr double scale{al::MathDefs::Pi() / double{HIL_SIZE}}; - const double val{std::sin(static_cast(i+1) * scale)}; - ret[i] = ret[HIL_SIZE-1-i] = val * val; - } - return ret; -} -alignas(16) const std::array HannWindow = InitHannWindow(); - - -struct FshifterState final : public EffectState { - /* Effect parameters */ - size_t mCount{}; - uint mPhaseStep[2]{}; - uint mPhase[2]{}; - double mSign[2]{}; - - /* Effects buffers */ - double mInFIFO[HIL_SIZE]{}; - complex_d mOutFIFO[HIL_STEP]{}; - complex_d mOutputAccum[HIL_SIZE]{}; - complex_d mAnalytic[HIL_SIZE]{}; - complex_d mOutdata[BufferLineSize]{}; - - alignas(16) float mBufferOut[BufferLineSize]{}; - - /* Effect gains for each output channel */ - struct { - float Current[MAX_OUTPUT_CHANNELS]{}; - float Target[MAX_OUTPUT_CHANNELS]{}; - } mGains[2]; - - - void deviceUpdate(const ALCdevice *device, const BufferStorage *buffer) override; - void update(const ALCcontext *context, const EffectSlot *slot, const EffectProps *props, - const EffectTarget target) override; - void process(const size_t samplesToDo, const al::span samplesIn, - const al::span samplesOut) override; - - DEF_NEWDEL(FshifterState) -}; - -void FshifterState::deviceUpdate(const ALCdevice*, const BufferStorage*) -{ - /* (Re-)initializing parameters and clear the buffers. */ - mCount = FIFO_LATENCY; - - std::fill(std::begin(mPhaseStep), std::end(mPhaseStep), 0u); - std::fill(std::begin(mPhase), std::end(mPhase), 0u); - std::fill(std::begin(mSign), std::end(mSign), 1.0); - std::fill(std::begin(mInFIFO), std::end(mInFIFO), 0.0); - std::fill(std::begin(mOutFIFO), std::end(mOutFIFO), complex_d{}); - std::fill(std::begin(mOutputAccum), std::end(mOutputAccum), complex_d{}); - std::fill(std::begin(mAnalytic), std::end(mAnalytic), complex_d{}); - - for(auto &gain : mGains) - { - std::fill(std::begin(gain.Current), std::end(gain.Current), 0.0f); - std::fill(std::begin(gain.Target), std::end(gain.Target), 0.0f); - } -} - -void FshifterState::update(const ALCcontext *context, const EffectSlot *slot, - const EffectProps *props, const EffectTarget target) -{ - const ALCdevice *device{context->mDevice.get()}; - - const float step{props->Fshifter.Frequency / static_cast(device->Frequency)}; - mPhaseStep[0] = mPhaseStep[1] = fastf2u(minf(step, 1.0f) * MixerFracOne); - - switch(props->Fshifter.LeftDirection) - { - case FShifterDirection::Down: - mSign[0] = -1.0; - break; - case FShifterDirection::Up: - mSign[0] = 1.0; - break; - case FShifterDirection::Off: - mPhase[0] = 0; - mPhaseStep[0] = 0; - break; - } - - switch(props->Fshifter.RightDirection) - { - case FShifterDirection::Down: - mSign[1] = -1.0; - break; - case FShifterDirection::Up: - mSign[1] = 1.0; - break; - case FShifterDirection::Off: - mPhase[1] = 0; - mPhaseStep[1] = 0; - break; - } - - const auto lcoeffs = CalcDirectionCoeffs({-1.0f, 0.0f, 0.0f}, 0.0f); - const auto rcoeffs = CalcDirectionCoeffs({ 1.0f, 0.0f, 0.0f}, 0.0f); - - mOutTarget = target.Main->Buffer; - ComputePanGains(target.Main, lcoeffs.data(), slot->Gain, mGains[0].Target); - ComputePanGains(target.Main, rcoeffs.data(), slot->Gain, mGains[1].Target); -} - -void FshifterState::process(const size_t samplesToDo, const al::span samplesIn, const al::span samplesOut) -{ - for(size_t base{0u};base < samplesToDo;) - { - size_t todo{minz(HIL_SIZE-mCount, samplesToDo-base)}; - - /* Fill FIFO buffer with samples data */ - size_t count{mCount}; - do { - mInFIFO[count] = samplesIn[0][base]; - mOutdata[base] = mOutFIFO[count-FIFO_LATENCY]; - ++base; ++count; - } while(--todo); - mCount = count; - - /* Check whether FIFO buffer is filled */ - if(mCount < HIL_SIZE) break; - mCount = FIFO_LATENCY; - - /* Real signal windowing and store in Analytic buffer */ - for(size_t k{0};k < HIL_SIZE;k++) - mAnalytic[k] = mInFIFO[k]*HannWindow[k]; - - /* Processing signal by Discrete Hilbert Transform (analytical signal). */ - complex_hilbert(mAnalytic); - - /* Windowing and add to output accumulator */ - for(size_t k{0};k < HIL_SIZE;k++) - mOutputAccum[k] += 2.0/OVERSAMP*HannWindow[k]*mAnalytic[k]; - - /* Shift accumulator, input & output FIFO */ - std::copy_n(mOutputAccum, HIL_STEP, mOutFIFO); - auto accum_iter = std::copy(std::begin(mOutputAccum)+HIL_STEP, std::end(mOutputAccum), - std::begin(mOutputAccum)); - std::fill(accum_iter, std::end(mOutputAccum), complex_d{}); - std::copy(std::begin(mInFIFO)+HIL_STEP, std::end(mInFIFO), std::begin(mInFIFO)); - } - - /* Process frequency shifter using the analytic signal obtained. */ - float *RESTRICT BufferOut{mBufferOut}; - for(int c{0};c < 2;++c) - { - const uint phase_step{mPhaseStep[c]}; - uint phase_idx{mPhase[c]}; - for(size_t k{0};k < samplesToDo;++k) - { - const double phase{phase_idx * ((1.0/MixerFracOne) * al::MathDefs::Tau())}; - BufferOut[k] = static_cast(mOutdata[k].real()*std::cos(phase) + - mOutdata[k].imag()*std::sin(phase)*mSign[c]); - - phase_idx += phase_step; - phase_idx &= MixerFracMask; - } - mPhase[c] = phase_idx; - - /* Now, mix the processed sound data to the output. */ - MixSamples({BufferOut, samplesToDo}, samplesOut, mGains[c].Current, mGains[c].Target, - maxz(samplesToDo, 512), 0); - } -} - - -struct FshifterStateFactory final : public EffectStateFactory { - al::intrusive_ptr create() override - { return al::intrusive_ptr{new FshifterState{}}; } -}; - -} // namespace - -EffectStateFactory *FshifterStateFactory_getFactory() -{ - static FshifterStateFactory FshifterFactory{}; - return &FshifterFactory; -} diff --git a/alc/effects/modulator.cpp b/alc/effects/modulator.cpp deleted file mode 100644 index eeb41635..00000000 --- a/alc/effects/modulator.cpp +++ /dev/null @@ -1,173 +0,0 @@ -/** - * OpenAL cross platform audio library - * Copyright (C) 2009 by Chris Robinson. - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - * Or go to http://www.gnu.org/copyleft/lgpl.html - */ - -#include "config.h" - -#include -#include - -#include -#include - -#include "alcmain.h" -#include "alcontext.h" -#include "core/filters/biquad.h" -#include "effectslot.h" -#include "vecmat.h" - - -namespace { - -#define MAX_UPDATE_SAMPLES 128 - -#define WAVEFORM_FRACBITS 24 -#define WAVEFORM_FRACONE (1<::Tau() / WAVEFORM_FRACONE}; - return std::sin(static_cast(index) * scale); -} - -inline float Saw(uint index) -{ return static_cast(index)*(2.0f/WAVEFORM_FRACONE) - 1.0f; } - -inline float Square(uint index) -{ return static_cast(static_cast((index>>(WAVEFORM_FRACBITS-2))&2) - 1); } - -inline float One(uint) { return 1.0f; } - -template -void Modulate(float *RESTRICT dst, uint index, const uint step, size_t todo) -{ - for(size_t i{0u};i < todo;i++) - { - index += step; - index &= WAVEFORM_FRACMASK; - dst[i] = func(index); - } -} - - -struct ModulatorState final : public EffectState { - void (*mGetSamples)(float*RESTRICT, uint, const uint, size_t){}; - - uint mIndex{0}; - uint mStep{1}; - - struct { - BiquadFilter Filter; - - float CurrentGains[MAX_OUTPUT_CHANNELS]{}; - float TargetGains[MAX_OUTPUT_CHANNELS]{}; - } mChans[MaxAmbiChannels]; - - - void deviceUpdate(const ALCdevice *device, const BufferStorage *buffer) override; - void update(const ALCcontext *context, const EffectSlot *slot, const EffectProps *props, - const EffectTarget target) override; - void process(const size_t samplesToDo, const al::span samplesIn, - const al::span samplesOut) override; - - DEF_NEWDEL(ModulatorState) -}; - -void ModulatorState::deviceUpdate(const ALCdevice*, const BufferStorage*) -{ - for(auto &e : mChans) - { - e.Filter.clear(); - std::fill(std::begin(e.CurrentGains), std::end(e.CurrentGains), 0.0f); - } -} - -void ModulatorState::update(const ALCcontext *context, const EffectSlot *slot, - const EffectProps *props, const EffectTarget target) -{ - const ALCdevice *device{context->mDevice.get()}; - - const float step{props->Modulator.Frequency / static_cast(device->Frequency)}; - mStep = fastf2u(clampf(step*WAVEFORM_FRACONE, 0.0f, float{WAVEFORM_FRACONE-1})); - - if(mStep == 0) - mGetSamples = Modulate; - else if(props->Modulator.Waveform == ModulatorWaveform::Sinusoid) - mGetSamples = Modulate; - else if(props->Modulator.Waveform == ModulatorWaveform::Sawtooth) - mGetSamples = Modulate; - else /*if(props->Modulator.Waveform == ModulatorWaveform::Square)*/ - mGetSamples = Modulate; - - float f0norm{props->Modulator.HighPassCutoff / static_cast(device->Frequency)}; - f0norm = clampf(f0norm, 1.0f/512.0f, 0.49f); - /* Bandwidth value is constant in octaves. */ - mChans[0].Filter.setParamsFromBandwidth(BiquadType::HighPass, f0norm, 1.0f, 0.75f); - for(size_t i{1u};i < slot->Wet.Buffer.size();++i) - mChans[i].Filter.copyParamsFrom(mChans[0].Filter); - - mOutTarget = target.Main->Buffer; - auto set_gains = [slot,target](auto &chan, al::span coeffs) - { ComputePanGains(target.Main, coeffs.data(), slot->Gain, chan.TargetGains); }; - SetAmbiPanIdentity(std::begin(mChans), slot->Wet.Buffer.size(), set_gains); -} - -void ModulatorState::process(const size_t samplesToDo, const al::span samplesIn, const al::span samplesOut) -{ - for(size_t base{0u};base < samplesToDo;) - { - alignas(16) float modsamples[MAX_UPDATE_SAMPLES]; - const size_t td{minz(MAX_UPDATE_SAMPLES, samplesToDo-base)}; - - mGetSamples(modsamples, mIndex, mStep, td); - mIndex += static_cast(mStep * td); - mIndex &= WAVEFORM_FRACMASK; - - auto chandata = std::begin(mChans); - for(const auto &input : samplesIn) - { - alignas(16) float temps[MAX_UPDATE_SAMPLES]; - - chandata->Filter.process({&input[base], td}, temps); - for(size_t i{0u};i < td;i++) - temps[i] *= modsamples[i]; - - MixSamples({temps, td}, samplesOut, chandata->CurrentGains, chandata->TargetGains, - samplesToDo-base, base); - ++chandata; - } - - base += td; - } -} - - -struct ModulatorStateFactory final : public EffectStateFactory { - al::intrusive_ptr create() override - { return al::intrusive_ptr{new ModulatorState{}}; } -}; - -} // namespace - -EffectStateFactory *ModulatorStateFactory_getFactory() -{ - static ModulatorStateFactory ModulatorFactory{}; - return &ModulatorFactory; -} diff --git a/alc/effects/null.cpp b/alc/effects/null.cpp deleted file mode 100644 index 9608f48a..00000000 --- a/alc/effects/null.cpp +++ /dev/null @@ -1,79 +0,0 @@ - -#include "config.h" - -#include "alcmain.h" -#include "alcontext.h" -#include "almalloc.h" -#include "alspan.h" -#include "effects/base.h" -#include "effectslot.h" - - -namespace { - -struct NullState final : public EffectState { - NullState(); - ~NullState() override; - - void deviceUpdate(const ALCdevice *device, const BufferStorage *buffer) override; - void update(const ALCcontext *context, const EffectSlot *slot, const EffectProps *props, - const EffectTarget target) override; - void process(const size_t samplesToDo, const al::span samplesIn, - const al::span samplesOut) override; - - DEF_NEWDEL(NullState) -}; - -/* This constructs the effect state. It's called when the object is first - * created. - */ -NullState::NullState() = default; - -/* This destructs the effect state. It's called only when the effect instance - * is no longer used. - */ -NullState::~NullState() = default; - -/* This updates the device-dependant effect state. This is called on state - * initialization and any time the device parameters (e.g. playback frequency, - * format) have been changed. Will always be followed by a call to the update - * method, if successful. - */ -void NullState::deviceUpdate(const ALCdevice* /*device*/, const BufferStorage* /*buffer*/) -{ -} - -/* This updates the effect state with new properties. This is called any time - * the effect is (re)loaded into a slot. - */ -void NullState::update(const ALCcontext* /*context*/, const EffectSlot* /*slot*/, - const EffectProps* /*props*/, const EffectTarget /*target*/) -{ -} - -/* This processes the effect state, for the given number of samples from the - * input to the output buffer. The result should be added to the output buffer, - * not replace it. - */ -void NullState::process(const size_t/*samplesToDo*/, - const al::span /*samplesIn*/, - const al::span /*samplesOut*/) -{ -} - - -struct NullStateFactory final : public EffectStateFactory { - al::intrusive_ptr create() override; -}; - -/* Creates EffectState objects of the appropriate type. */ -al::intrusive_ptr NullStateFactory::create() -{ return al::intrusive_ptr{new NullState{}}; } - -} // namespace - -EffectStateFactory *NullStateFactory_getFactory() -{ - static NullStateFactory NullFactory{}; - return &NullFactory; -} diff --git a/alc/effects/pshifter.cpp b/alc/effects/pshifter.cpp deleted file mode 100644 index 3a577ce7..00000000 --- a/alc/effects/pshifter.cpp +++ /dev/null @@ -1,260 +0,0 @@ -/** - * OpenAL cross platform audio library - * Copyright (C) 2018 by Raul Herraiz. - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - * Or go to http://www.gnu.org/copyleft/lgpl.html - */ - -#include "config.h" - -#include -#include -#include -#include -#include - -#include "alcmain.h" -#include "alcomplex.h" -#include "alcontext.h" -#include "alnumeric.h" -#include "alu.h" -#include "effectslot.h" -#include "math_defs.h" - - -namespace { - -using complex_d = std::complex; - -#define STFT_SIZE 1024 -#define STFT_HALF_SIZE (STFT_SIZE>>1) -#define OVERSAMP (1<<2) - -#define STFT_STEP (STFT_SIZE / OVERSAMP) -#define FIFO_LATENCY (STFT_STEP * (OVERSAMP-1)) - -/* Define a Hann window, used to filter the STFT input and output. */ -std::array InitHannWindow() -{ - std::array ret; - /* Create lookup table of the Hann window for the desired size, i.e. STFT_SIZE */ - for(size_t i{0};i < STFT_SIZE>>1;i++) - { - constexpr double scale{al::MathDefs::Pi() / double{STFT_SIZE}}; - const double val{std::sin(static_cast(i+1) * scale)}; - ret[i] = ret[STFT_SIZE-1-i] = val * val; - } - return ret; -} -alignas(16) const std::array HannWindow = InitHannWindow(); - - -struct FrequencyBin { - double Amplitude; - double FreqBin; -}; - - -struct PshifterState final : public EffectState { - /* Effect parameters */ - size_t mCount; - uint mPitchShiftI; - double mPitchShift; - - /* Effects buffers */ - std::array mFIFO; - std::array mLastPhase; - std::array mSumPhase; - std::array mOutputAccum; - - std::array mFftBuffer; - - std::array mAnalysisBuffer; - std::array mSynthesisBuffer; - - alignas(16) FloatBufferLine mBufferOut; - - /* Effect gains for each output channel */ - float mCurrentGains[MAX_OUTPUT_CHANNELS]; - float mTargetGains[MAX_OUTPUT_CHANNELS]; - - - void deviceUpdate(const ALCdevice *device, const BufferStorage *buffer) override; - void update(const ALCcontext *context, const EffectSlot *slot, const EffectProps *props, - const EffectTarget target) override; - void process(const size_t samplesToDo, const al::span samplesIn, - const al::span samplesOut) override; - - DEF_NEWDEL(PshifterState) -}; - -void PshifterState::deviceUpdate(const ALCdevice* /*device*/, const BufferStorage* /*buffer*/) -{ - /* (Re-)initializing parameters and clear the buffers. */ - mCount = FIFO_LATENCY; - mPitchShiftI = MixerFracOne; - mPitchShift = 1.0; - - std::fill(mFIFO.begin(), mFIFO.end(), 0.0); - std::fill(mLastPhase.begin(), mLastPhase.end(), 0.0); - std::fill(mSumPhase.begin(), mSumPhase.end(), 0.0); - std::fill(mOutputAccum.begin(), mOutputAccum.end(), 0.0); - std::fill(mFftBuffer.begin(), mFftBuffer.end(), complex_d{}); - std::fill(mAnalysisBuffer.begin(), mAnalysisBuffer.end(), FrequencyBin{}); - std::fill(mSynthesisBuffer.begin(), mSynthesisBuffer.end(), FrequencyBin{}); - - std::fill(std::begin(mCurrentGains), std::end(mCurrentGains), 0.0f); - std::fill(std::begin(mTargetGains), std::end(mTargetGains), 0.0f); -} - -void PshifterState::update(const ALCcontext*, const EffectSlot *slot, - const EffectProps *props, const EffectTarget target) -{ - const int tune{props->Pshifter.CoarseTune*100 + props->Pshifter.FineTune}; - const float pitch{std::pow(2.0f, static_cast(tune) / 1200.0f)}; - mPitchShiftI = fastf2u(pitch*MixerFracOne); - mPitchShift = mPitchShiftI * double{1.0/MixerFracOne}; - - const auto coeffs = CalcDirectionCoeffs({0.0f, 0.0f, -1.0f}, 0.0f); - - mOutTarget = target.Main->Buffer; - ComputePanGains(target.Main, coeffs.data(), slot->Gain, mTargetGains); -} - -void PshifterState::process(const size_t samplesToDo, const al::span samplesIn, const al::span samplesOut) -{ - /* Pitch shifter engine based on the work of Stephan Bernsee. - * http://blogs.zynaptiq.com/bernsee/pitch-shifting-using-the-ft/ - */ - - /* Cycle offset per update expected of each frequency bin (bin 0 is none, - * bin 1 is x1, bin 2 is x2, etc). - */ - constexpr double expected_cycles{al::MathDefs::Tau() / OVERSAMP}; - - for(size_t base{0u};base < samplesToDo;) - { - const size_t todo{minz(STFT_SIZE-mCount, samplesToDo-base)}; - - /* Retrieve the output samples from the FIFO and fill in the new input - * samples. - */ - auto fifo_iter = mFIFO.begin() + mCount; - std::transform(fifo_iter, fifo_iter+todo, mBufferOut.begin()+base, - [](double d) noexcept -> float { return static_cast(d); }); - - std::copy_n(samplesIn[0].begin()+base, todo, fifo_iter); - mCount += todo; - base += todo; - - /* Check whether FIFO buffer is filled with new samples. */ - if(mCount < STFT_SIZE) break; - mCount = FIFO_LATENCY; - - /* Time-domain signal windowing, store in FftBuffer, and apply a - * forward FFT to get the frequency-domain signal. - */ - for(size_t k{0u};k < STFT_SIZE;k++) - mFftBuffer[k] = mFIFO[k] * HannWindow[k]; - forward_fft(mFftBuffer); - - /* Analyze the obtained data. Since the real FFT is symmetric, only - * STFT_HALF_SIZE+1 samples are needed. - */ - for(size_t k{0u};k < STFT_HALF_SIZE+1;k++) - { - const double amplitude{std::abs(mFftBuffer[k])}; - const double phase{std::arg(mFftBuffer[k])}; - - /* Compute phase difference and subtract expected phase difference */ - double tmp{(phase - mLastPhase[k]) - static_cast(k)*expected_cycles}; - - /* Map delta phase into +/- Pi interval */ - int qpd{double2int(tmp / al::MathDefs::Pi())}; - tmp -= al::MathDefs::Pi() * (qpd + (qpd%2)); - - /* Get deviation from bin frequency from the +/- Pi interval */ - tmp /= expected_cycles; - - /* Compute the k-th partials' true frequency and store the - * amplitude and frequency bin in the analysis buffer. - */ - mAnalysisBuffer[k].Amplitude = amplitude; - mAnalysisBuffer[k].FreqBin = static_cast(k) + tmp; - - /* Store the actual phase[k] for the next frame. */ - mLastPhase[k] = phase; - } - - /* Shift the frequency bins according to the pitch adjustment, - * accumulating the amplitudes of overlapping frequency bins. - */ - std::fill(mSynthesisBuffer.begin(), mSynthesisBuffer.end(), FrequencyBin{}); - const size_t bin_count{minz(STFT_HALF_SIZE+1, - (((STFT_HALF_SIZE+1)<>1) - 1)/mPitchShiftI + 1)}; - for(size_t k{0u};k < bin_count;k++) - { - const size_t j{(k*mPitchShiftI + (MixerFracOne>>1)) >> MixerFracBits}; - mSynthesisBuffer[j].Amplitude += mAnalysisBuffer[k].Amplitude; - mSynthesisBuffer[j].FreqBin = mAnalysisBuffer[k].FreqBin * mPitchShift; - } - - /* Reconstruct the frequency-domain signal from the adjusted frequency - * bins. - */ - for(size_t k{0u};k < STFT_HALF_SIZE+1;k++) - { - /* Calculate actual delta phase and accumulate it to get bin phase */ - mSumPhase[k] += mSynthesisBuffer[k].FreqBin * expected_cycles; - - mFftBuffer[k] = std::polar(mSynthesisBuffer[k].Amplitude, mSumPhase[k]); - } - for(size_t k{STFT_HALF_SIZE+1};k < STFT_SIZE;++k) - mFftBuffer[k] = std::conj(mFftBuffer[STFT_SIZE-k]); - - /* Apply an inverse FFT to get the time-domain siganl, and accumulate - * for the output with windowing. - */ - inverse_fft(mFftBuffer); - for(size_t k{0u};k < STFT_SIZE;k++) - mOutputAccum[k] += HannWindow[k]*mFftBuffer[k].real() * (4.0/OVERSAMP/STFT_SIZE); - - /* Shift FIFO and accumulator. */ - fifo_iter = std::copy(mFIFO.begin()+STFT_STEP, mFIFO.end(), mFIFO.begin()); - std::copy_n(mOutputAccum.begin(), STFT_STEP, fifo_iter); - auto accum_iter = std::copy(mOutputAccum.begin()+STFT_STEP, mOutputAccum.end(), - mOutputAccum.begin()); - std::fill(accum_iter, mOutputAccum.end(), 0.0); - } - - /* Now, mix the processed sound data to the output. */ - MixSamples({mBufferOut.data(), samplesToDo}, samplesOut, mCurrentGains, mTargetGains, - maxz(samplesToDo, 512), 0); -} - - -struct PshifterStateFactory final : public EffectStateFactory { - al::intrusive_ptr create() override - { return al::intrusive_ptr{new PshifterState{}}; } -}; - -} // namespace - -EffectStateFactory *PshifterStateFactory_getFactory() -{ - static PshifterStateFactory PshifterFactory{}; - return &PshifterFactory; -} diff --git a/alc/effects/reverb.cpp b/alc/effects/reverb.cpp deleted file mode 100644 index 1aaad4a6..00000000 --- a/alc/effects/reverb.cpp +++ /dev/null @@ -1,1704 +0,0 @@ -/** - * Ambisonic reverb engine for the OpenAL cross platform audio library - * Copyright (C) 2008-2017 by Chris Robinson and Christopher Fitzgerald. - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - * Or go to http://www.gnu.org/copyleft/lgpl.html - */ - -#include "config.h" - -#include -#include -#include - -#include -#include -#include -#include - -#include "alcmain.h" -#include "alcontext.h" -#include "alnumeric.h" -#include "bformatdec.h" -#include "core/filters/biquad.h" -#include "effectslot.h" -#include "vector.h" -#include "vecmat.h" - -/* This is a user config option for modifying the overall output of the reverb - * effect. - */ -float ReverbBoost = 1.0f; - -namespace { - -#define MOD_FRACBITS 24 -#define MOD_FRACONE (1< 3:above back right, 1:below front right <-> 2:below - * back left). It's not quite opposite, since the A-Format results in a - * tetrahedron, but it's close enough. Should the model be extended to 8-lines - * in the future, true opposites can be used. - */ -alignas(16) constexpr float B2A[NUM_LINES][NUM_LINES]{ - { 0.288675134595f, 0.288675134595f, 0.288675134595f, 0.288675134595f }, - { 0.288675134595f, -0.288675134595f, -0.288675134595f, 0.288675134595f }, - { 0.288675134595f, 0.288675134595f, -0.288675134595f, -0.288675134595f }, - { 0.288675134595f, -0.288675134595f, 0.288675134595f, -0.288675134595f } -}; - -/* Converts A-Format to B-Format. */ -alignas(16) constexpr float A2B[NUM_LINES][NUM_LINES]{ - { 0.866025403785f, 0.866025403785f, 0.866025403785f, 0.866025403785f }, - { 0.866025403785f, -0.866025403785f, 0.866025403785f, -0.866025403785f }, - { 0.866025403785f, -0.866025403785f, -0.866025403785f, 0.866025403785f }, - { 0.866025403785f, 0.866025403785f, -0.866025403785f, -0.866025403785f } -}; - - -/* The all-pass and delay lines have a variable length dependent on the - * effect's density parameter, which helps alter the perceived environment - * size. The size-to-density conversion is a cubed scale: - * - * density = min(1.0, pow(size, 3.0) / DENSITY_SCALE); - * - * The line lengths scale linearly with room size, so the inverse density - * conversion is needed, taking the cube root of the re-scaled density to - * calculate the line length multiplier: - * - * length_mult = max(5.0, cbrt(density*DENSITY_SCALE)); - * - * The density scale below will result in a max line multiplier of 50, for an - * effective size range of 5m to 50m. - */ -constexpr float DENSITY_SCALE{125000.0f}; - -/* All delay line lengths are specified in seconds. - * - * To approximate early reflections, we break them up into primary (those - * arriving from the same direction as the source) and secondary (those - * arriving from the opposite direction). - * - * The early taps decorrelate the 4-channel signal to approximate an average - * room response for the primary reflections after the initial early delay. - * - * Given an average room dimension (d_a) and the speed of sound (c) we can - * calculate the average reflection delay (r_a) regardless of listener and - * source positions as: - * - * r_a = d_a / c - * c = 343.3 - * - * This can extended to finding the average difference (r_d) between the - * maximum (r_1) and minimum (r_0) reflection delays: - * - * r_0 = 2 / 3 r_a - * = r_a - r_d / 2 - * = r_d - * r_1 = 4 / 3 r_a - * = r_a + r_d / 2 - * = 2 r_d - * r_d = 2 / 3 r_a - * = r_1 - r_0 - * - * As can be determined by integrating the 1D model with a source (s) and - * listener (l) positioned across the dimension of length (d_a): - * - * r_d = int_(l=0)^d_a (int_(s=0)^d_a |2 d_a - 2 (l + s)| ds) dl / c - * - * The initial taps (T_(i=0)^N) are then specified by taking a power series - * that ranges between r_0 and half of r_1 less r_0: - * - * R_i = 2^(i / (2 N - 1)) r_d - * = r_0 + (2^(i / (2 N - 1)) - 1) r_d - * = r_0 + T_i - * T_i = R_i - r_0 - * = (2^(i / (2 N - 1)) - 1) r_d - * - * Assuming an average of 1m, we get the following taps: - */ -constexpr std::array EARLY_TAP_LENGTHS{{ - 0.0000000e+0f, 2.0213520e-4f, 4.2531060e-4f, 6.7171600e-4f -}}; - -/* The early all-pass filter lengths are based on the early tap lengths: - * - * A_i = R_i / a - * - * Where a is the approximate maximum all-pass cycle limit (20). - */ -constexpr std::array EARLY_ALLPASS_LENGTHS{{ - 9.7096800e-5f, 1.0720356e-4f, 1.1836234e-4f, 1.3068260e-4f -}}; - -/* The early delay lines are used to transform the primary reflections into - * the secondary reflections. The A-format is arranged in such a way that - * the channels/lines are spatially opposite: - * - * C_i is opposite C_(N-i-1) - * - * The delays of the two opposing reflections (R_i and O_i) from a source - * anywhere along a particular dimension always sum to twice its full delay: - * - * 2 r_a = R_i + O_i - * - * With that in mind we can determine the delay between the two reflections - * and thus specify our early line lengths (L_(i=0)^N) using: - * - * O_i = 2 r_a - R_(N-i-1) - * L_i = O_i - R_(N-i-1) - * = 2 (r_a - R_(N-i-1)) - * = 2 (r_a - T_(N-i-1) - r_0) - * = 2 r_a (1 - (2 / 3) 2^((N - i - 1) / (2 N - 1))) - * - * Using an average dimension of 1m, we get: - */ -constexpr std::array EARLY_LINE_LENGTHS{{ - 5.9850400e-4f, 1.0913150e-3f, 1.5376658e-3f, 1.9419362e-3f -}}; - -/* The late all-pass filter lengths are based on the late line lengths: - * - * A_i = (5 / 3) L_i / r_1 - */ -constexpr std::array LATE_ALLPASS_LENGTHS{{ - 1.6182800e-4f, 2.0389060e-4f, 2.8159360e-4f, 3.2365600e-4f -}}; - -/* The late lines are used to approximate the decaying cycle of recursive - * late reflections. - * - * Splitting the lines in half, we start with the shortest reflection paths - * (L_(i=0)^(N/2)): - * - * L_i = 2^(i / (N - 1)) r_d - * - * Then for the opposite (longest) reflection paths (L_(i=N/2)^N): - * - * L_i = 2 r_a - L_(i-N/2) - * = 2 r_a - 2^((i - N / 2) / (N - 1)) r_d - * - * For our 1m average room, we get: - */ -constexpr std::array LATE_LINE_LENGTHS{{ - 1.9419362e-3f, 2.4466860e-3f, 3.3791220e-3f, 3.8838720e-3f -}}; - - -using ReverbUpdateLine = std::array; - -struct DelayLineI { - /* The delay lines use interleaved samples, with the lengths being powers - * of 2 to allow the use of bit-masking instead of a modulus for wrapping. - */ - size_t Mask{0u}; - union { - uintptr_t LineOffset{0u}; - std::array *Line; - }; - - /* Given the allocated sample buffer, this function updates each delay line - * offset. - */ - void realizeLineOffset(std::array *sampleBuffer) noexcept - { Line = sampleBuffer + LineOffset; } - - /* Calculate the length of a delay line and store its mask and offset. */ - uint calcLineLength(const float length, const uintptr_t offset, const float frequency, - const uint extra) - { - /* All line lengths are powers of 2, calculated from their lengths in - * seconds, rounded up. - */ - uint samples{float2uint(std::ceil(length*frequency))}; - samples = NextPowerOf2(samples + extra); - - /* All lines share a single sample buffer. */ - Mask = samples - 1; - LineOffset = offset; - - /* Return the sample count for accumulation. */ - return samples; - } - - void write(size_t offset, const size_t c, const float *RESTRICT in, const size_t count) const noexcept - { - ASSUME(count > 0); - for(size_t i{0u};i < count;) - { - offset &= Mask; - size_t td{minz(Mask+1 - offset, count - i)}; - do { - Line[offset++][c] = in[i++]; - } while(--td); - } - } -}; - -struct VecAllpass { - DelayLineI Delay; - float Coeff{0.0f}; - size_t Offset[NUM_LINES][2]{}; - - void processFaded(const al::span samples, size_t offset, - const float xCoeff, const float yCoeff, float fadeCount, const float fadeStep, - const size_t todo); - void processUnfaded(const al::span samples, size_t offset, - const float xCoeff, const float yCoeff, const size_t todo); -}; - -struct T60Filter { - /* Two filters are used to adjust the signal. One to control the low - * frequencies, and one to control the high frequencies. - */ - float MidGain[2]{0.0f, 0.0f}; - BiquadFilter HFFilter, LFFilter; - - void calcCoeffs(const float length, const float lfDecayTime, const float mfDecayTime, - const float hfDecayTime, const float lf0norm, const float hf0norm); - - /* Applies the two T60 damping filter sections. */ - void process(const al::span samples) - { DualBiquad{HFFilter, LFFilter}.process(samples, samples.data()); } -}; - -struct EarlyReflections { - /* A Gerzon vector all-pass filter is used to simulate initial diffusion. - * The spread from this filter also helps smooth out the reverb tail. - */ - VecAllpass VecAp; - - /* An echo line is used to complete the second half of the early - * reflections. - */ - DelayLineI Delay; - size_t Offset[NUM_LINES][2]{}; - float Coeff[NUM_LINES][2]{}; - - /* The gain for each output channel based on 3D panning. */ - float CurrentGain[NUM_LINES][MAX_OUTPUT_CHANNELS]{}; - float PanGain[NUM_LINES][MAX_OUTPUT_CHANNELS]{}; - - void updateLines(const float density_mult, const float diffusion, const float decayTime, - const float frequency); -}; - - -struct Modulation { - /* The vibrato time is tracked with an index over a (MOD_FRACONE) - * normalized range. - */ - uint Index, Step; - - /* The depth of frequency change, in samples. */ - float Depth[2]; - - float ModDelays[MAX_UPDATE_SAMPLES]; - - void updateModulator(float modTime, float modDepth, float frequency); - - void calcDelays(size_t todo); - void calcFadedDelays(size_t todo, float fadeCount, float fadeStep); -}; - -struct LateReverb { - /* A recursive delay line is used fill in the reverb tail. */ - DelayLineI Delay; - size_t Offset[NUM_LINES][2]{}; - - /* Attenuation to compensate for the modal density and decay rate of the - * late lines. - */ - float DensityGain[2]{0.0f, 0.0f}; - - /* T60 decay filters are used to simulate absorption. */ - T60Filter T60[NUM_LINES]; - - Modulation Mod; - - /* A Gerzon vector all-pass filter is used to simulate diffusion. */ - VecAllpass VecAp; - - /* The gain for each output channel based on 3D panning. */ - float CurrentGain[NUM_LINES][MAX_OUTPUT_CHANNELS]{}; - float PanGain[NUM_LINES][MAX_OUTPUT_CHANNELS]{}; - - void updateLines(const float density_mult, const float diffusion, const float lfDecayTime, - const float mfDecayTime, const float hfDecayTime, const float lf0norm, - const float hf0norm, const float frequency); -}; - -struct ReverbState final : public EffectState { - /* All delay lines are allocated as a single buffer to reduce memory - * fragmentation and management code. - */ - al::vector,16> mSampleBuffer; - - struct { - /* Calculated parameters which indicate if cross-fading is needed after - * an update. - */ - float Density{AL_EAXREVERB_DEFAULT_DENSITY}; - float Diffusion{AL_EAXREVERB_DEFAULT_DIFFUSION}; - float DecayTime{AL_EAXREVERB_DEFAULT_DECAY_TIME}; - float HFDecayTime{AL_EAXREVERB_DEFAULT_DECAY_HFRATIO * AL_EAXREVERB_DEFAULT_DECAY_TIME}; - float LFDecayTime{AL_EAXREVERB_DEFAULT_DECAY_LFRATIO * AL_EAXREVERB_DEFAULT_DECAY_TIME}; - float ModulationTime{AL_EAXREVERB_DEFAULT_MODULATION_TIME}; - float ModulationDepth{AL_EAXREVERB_DEFAULT_MODULATION_DEPTH}; - float HFReference{AL_EAXREVERB_DEFAULT_HFREFERENCE}; - float LFReference{AL_EAXREVERB_DEFAULT_LFREFERENCE}; - } mParams; - - /* Master effect filters */ - struct { - BiquadFilter Lp; - BiquadFilter Hp; - } mFilter[NUM_LINES]; - - /* Core delay line (early reflections and late reverb tap from this). */ - DelayLineI mDelay; - - /* Tap points for early reflection delay. */ - size_t mEarlyDelayTap[NUM_LINES][2]{}; - float mEarlyDelayCoeff[NUM_LINES][2]{}; - - /* Tap points for late reverb feed and delay. */ - size_t mLateFeedTap{}; - size_t mLateDelayTap[NUM_LINES][2]{}; - - /* Coefficients for the all-pass and line scattering matrices. */ - float mMixX{0.0f}; - float mMixY{0.0f}; - - EarlyReflections mEarly; - - LateReverb mLate; - - bool mDoFading{}; - - /* Maximum number of samples to process at once. */ - size_t mMaxUpdate[2]{MAX_UPDATE_SAMPLES, MAX_UPDATE_SAMPLES}; - - /* The current write offset for all delay lines. */ - size_t mOffset{}; - - /* Temporary storage used when processing. */ - union { - alignas(16) FloatBufferLine mTempLine{}; - alignas(16) std::array mTempSamples; - }; - alignas(16) std::array mEarlySamples{}; - alignas(16) std::array mLateSamples{}; - - using MixOutT = void (ReverbState::*)(const al::span samplesOut, - const size_t counter, const size_t offset, const size_t todo); - - MixOutT mMixOut{&ReverbState::MixOutPlain}; - std::array mOrderScales{}; - std::array,2> mAmbiSplitter; - - - static void DoMixRow(const al::span OutBuffer, const al::span Gains, - const float *InSamples, const size_t InStride) - { - std::fill(OutBuffer.begin(), OutBuffer.end(), 0.0f); - for(const float gain : Gains) - { - const float *RESTRICT input{al::assume_aligned<16>(InSamples)}; - InSamples += InStride; - - if(!(std::fabs(gain) > GainSilenceThreshold)) - continue; - - for(float &sample : OutBuffer) - { - sample += *input * gain; - ++input; - } - } - } - - - void MixOutPlain(const al::span samplesOut, const size_t counter, - const size_t offset, const size_t todo) - { - ASSUME(todo > 0); - - /* Convert back to B-Format, and mix the results to output. */ - const al::span tmpspan{al::assume_aligned<16>(mTempLine.data()), todo}; - for(size_t c{0u};c < NUM_LINES;c++) - { - DoMixRow(tmpspan, A2B[c], mEarlySamples[0].data(), mEarlySamples[0].size()); - MixSamples(tmpspan, samplesOut, mEarly.CurrentGain[c], mEarly.PanGain[c], counter, - offset); - } - for(size_t c{0u};c < NUM_LINES;c++) - { - DoMixRow(tmpspan, A2B[c], mLateSamples[0].data(), mLateSamples[0].size()); - MixSamples(tmpspan, samplesOut, mLate.CurrentGain[c], mLate.PanGain[c], counter, - offset); - } - } - - void MixOutAmbiUp(const al::span samplesOut, const size_t counter, - const size_t offset, const size_t todo) - { - ASSUME(todo > 0); - - const al::span tmpspan{al::assume_aligned<16>(mTempLine.data()), todo}; - for(size_t c{0u};c < NUM_LINES;c++) - { - DoMixRow(tmpspan, A2B[c], mEarlySamples[0].data(), mEarlySamples[0].size()); - - /* Apply scaling to the B-Format's HF response to "upsample" it to - * higher-order output. - */ - const float hfscale{(c==0) ? mOrderScales[0] : mOrderScales[1]}; - mAmbiSplitter[0][c].processHfScale(tmpspan, hfscale); - - MixSamples(tmpspan, samplesOut, mEarly.CurrentGain[c], mEarly.PanGain[c], counter, - offset); - } - for(size_t c{0u};c < NUM_LINES;c++) - { - DoMixRow(tmpspan, A2B[c], mLateSamples[0].data(), mLateSamples[0].size()); - - const float hfscale{(c==0) ? mOrderScales[0] : mOrderScales[1]}; - mAmbiSplitter[1][c].processHfScale(tmpspan, hfscale); - - MixSamples(tmpspan, samplesOut, mLate.CurrentGain[c], mLate.PanGain[c], counter, - offset); - } - } - - void allocLines(const float frequency); - - void updateDelayLine(const float earlyDelay, const float lateDelay, const float density_mult, - const float decayTime, const float frequency); - void update3DPanning(const float *ReflectionsPan, const float *LateReverbPan, - const float earlyGain, const float lateGain, const EffectTarget &target); - - void earlyUnfaded(const size_t offset, const size_t todo); - void earlyFaded(const size_t offset, const size_t todo, const float fade, - const float fadeStep); - - void lateUnfaded(const size_t offset, const size_t todo); - void lateFaded(const size_t offset, const size_t todo, const float fade, - const float fadeStep); - - void deviceUpdate(const ALCdevice *device, const BufferStorage *buffer) override; - void update(const ALCcontext *context, const EffectSlot *slot, const EffectProps *props, - const EffectTarget target) override; - void process(const size_t samplesToDo, const al::span samplesIn, - const al::span samplesOut) override; - - DEF_NEWDEL(ReverbState) -}; - -/************************************** - * Device Update * - **************************************/ - -inline float CalcDelayLengthMult(float density) -{ return maxf(5.0f, std::cbrt(density*DENSITY_SCALE)); } - -/* Calculates the delay line metrics and allocates the shared sample buffer - * for all lines given the sample rate (frequency). - */ -void ReverbState::allocLines(const float frequency) -{ - /* All delay line lengths are calculated to accomodate the full range of - * lengths given their respective paramters. - */ - size_t totalSamples{0u}; - - /* Multiplier for the maximum density value, i.e. density=1, which is - * actually the least density... - */ - const float multiplier{CalcDelayLengthMult(AL_EAXREVERB_MAX_DENSITY)}; - - /* The main delay length includes the maximum early reflection delay, the - * largest early tap width, the maximum late reverb delay, and the - * largest late tap width. Finally, it must also be extended by the - * update size (BufferLineSize) for block processing. - */ - float length{AL_EAXREVERB_MAX_REFLECTIONS_DELAY + EARLY_TAP_LENGTHS.back()*multiplier + - AL_EAXREVERB_MAX_LATE_REVERB_DELAY + - (LATE_LINE_LENGTHS.back() - LATE_LINE_LENGTHS.front())/float{NUM_LINES}*multiplier}; - totalSamples += mDelay.calcLineLength(length, totalSamples, frequency, BufferLineSize); - - /* The early vector all-pass line. */ - length = EARLY_ALLPASS_LENGTHS.back() * multiplier; - totalSamples += mEarly.VecAp.Delay.calcLineLength(length, totalSamples, frequency, 0); - - /* The early reflection line. */ - length = EARLY_LINE_LENGTHS.back() * multiplier; - totalSamples += mEarly.Delay.calcLineLength(length, totalSamples, frequency, 0); - - /* The late vector all-pass line. */ - length = LATE_ALLPASS_LENGTHS.back() * multiplier; - totalSamples += mLate.VecAp.Delay.calcLineLength(length, totalSamples, frequency, 0); - - /* The modulator's line length is calculated from the maximum modulation - * time and depth coefficient, and halfed for the low-to-high frequency - * swing. - */ - constexpr float max_mod_delay{AL_EAXREVERB_MAX_MODULATION_TIME*MODULATION_DEPTH_COEFF / 2.0f}; - - /* The late delay lines are calculated from the largest maximum density - * line length, and the maximum modulation delay. An additional sample is - * added to keep it stable when there is no modulation. - */ - length = LATE_LINE_LENGTHS.back()*multiplier + max_mod_delay; - totalSamples += mLate.Delay.calcLineLength(length, totalSamples, frequency, 1); - - if(totalSamples != mSampleBuffer.size()) - decltype(mSampleBuffer)(totalSamples).swap(mSampleBuffer); - - /* Clear the sample buffer. */ - std::fill(mSampleBuffer.begin(), mSampleBuffer.end(), decltype(mSampleBuffer)::value_type{}); - - /* Update all delays to reflect the new sample buffer. */ - mDelay.realizeLineOffset(mSampleBuffer.data()); - mEarly.VecAp.Delay.realizeLineOffset(mSampleBuffer.data()); - mEarly.Delay.realizeLineOffset(mSampleBuffer.data()); - mLate.VecAp.Delay.realizeLineOffset(mSampleBuffer.data()); - mLate.Delay.realizeLineOffset(mSampleBuffer.data()); -} - -void ReverbState::deviceUpdate(const ALCdevice *device, const BufferStorage* /*buffer*/) -{ - const auto frequency = static_cast(device->Frequency); - - /* Allocate the delay lines. */ - allocLines(frequency); - - const float multiplier{CalcDelayLengthMult(AL_EAXREVERB_MAX_DENSITY)}; - - /* The late feed taps are set a fixed position past the latest delay tap. */ - mLateFeedTap = float2uint( - (AL_EAXREVERB_MAX_REFLECTIONS_DELAY + EARLY_TAP_LENGTHS.back()*multiplier) * frequency); - - /* Clear filters and gain coefficients since the delay lines were all just - * cleared (if not reallocated). - */ - for(auto &filter : mFilter) - { - filter.Lp.clear(); - filter.Hp.clear(); - } - - for(auto &coeff : mEarlyDelayCoeff) - std::fill(std::begin(coeff), std::end(coeff), 0.0f); - for(auto &coeff : mEarly.Coeff) - std::fill(std::begin(coeff), std::end(coeff), 0.0f); - - mLate.DensityGain[0] = 0.0f; - mLate.DensityGain[1] = 0.0f; - for(auto &t60 : mLate.T60) - { - t60.MidGain[0] = 0.0f; - t60.MidGain[1] = 0.0f; - t60.HFFilter.clear(); - t60.LFFilter.clear(); - } - - mLate.Mod.Index = 0; - mLate.Mod.Step = 1; - std::fill(std::begin(mLate.Mod.Depth), std::end(mLate.Mod.Depth), 0.0f); - - for(auto &gains : mEarly.CurrentGain) - std::fill(std::begin(gains), std::end(gains), 0.0f); - for(auto &gains : mEarly.PanGain) - std::fill(std::begin(gains), std::end(gains), 0.0f); - for(auto &gains : mLate.CurrentGain) - std::fill(std::begin(gains), std::end(gains), 0.0f); - for(auto &gains : mLate.PanGain) - std::fill(std::begin(gains), std::end(gains), 0.0f); - - /* Reset fading and offset base. */ - mDoFading = true; - std::fill(std::begin(mMaxUpdate), std::end(mMaxUpdate), MAX_UPDATE_SAMPLES); - mOffset = 0; - - if(device->mAmbiOrder > 1) - { - mMixOut = &ReverbState::MixOutAmbiUp; - mOrderScales = BFormatDec::GetHFOrderScales(1, device->mAmbiOrder); - } - else - { - mMixOut = &ReverbState::MixOutPlain; - mOrderScales.fill(1.0f); - } - mAmbiSplitter[0][0].init(device->mXOverFreq / frequency); - std::fill(mAmbiSplitter[0].begin()+1, mAmbiSplitter[0].end(), mAmbiSplitter[0][0]); - std::fill(mAmbiSplitter[1].begin(), mAmbiSplitter[1].end(), mAmbiSplitter[0][0]); -} - -/************************************** - * Effect Update * - **************************************/ - -/* Calculate a decay coefficient given the length of each cycle and the time - * until the decay reaches -60 dB. - */ -inline float CalcDecayCoeff(const float length, const float decayTime) -{ return std::pow(ReverbDecayGain, length/decayTime); } - -/* Calculate a decay length from a coefficient and the time until the decay - * reaches -60 dB. - */ -inline float CalcDecayLength(const float coeff, const float decayTime) -{ - constexpr float log10_decaygain{-3.0f/*std::log10(ReverbDecayGain)*/}; - return std::log10(coeff) * decayTime / log10_decaygain; -} - -/* Calculate an attenuation to be applied to the input of any echo models to - * compensate for modal density and decay time. - */ -inline float CalcDensityGain(const float a) -{ - /* The energy of a signal can be obtained by finding the area under the - * squared signal. This takes the form of Sum(x_n^2), where x is the - * amplitude for the sample n. - * - * Decaying feedback matches exponential decay of the form Sum(a^n), - * where a is the attenuation coefficient, and n is the sample. The area - * under this decay curve can be calculated as: 1 / (1 - a). - * - * Modifying the above equation to find the area under the squared curve - * (for energy) yields: 1 / (1 - a^2). Input attenuation can then be - * calculated by inverting the square root of this approximation, - * yielding: 1 / sqrt(1 / (1 - a^2)), simplified to: sqrt(1 - a^2). - */ - return std::sqrt(1.0f - a*a); -} - -/* Calculate the scattering matrix coefficients given a diffusion factor. */ -inline void CalcMatrixCoeffs(const float diffusion, float *x, float *y) -{ - /* The matrix is of order 4, so n is sqrt(4 - 1). */ - constexpr float n{1.73205080756887719318f/*std::sqrt(3.0f)*/}; - const float t{diffusion * std::atan(n)}; - - /* Calculate the first mixing matrix coefficient. */ - *x = std::cos(t); - /* Calculate the second mixing matrix coefficient. */ - *y = std::sin(t) / n; -} - -/* Calculate the limited HF ratio for use with the late reverb low-pass - * filters. - */ -float CalcLimitedHfRatio(const float hfRatio, const float airAbsorptionGainHF, - const float decayTime) -{ - /* Find the attenuation due to air absorption in dB (converting delay - * time to meters using the speed of sound). Then reversing the decay - * equation, solve for HF ratio. The delay length is cancelled out of - * the equation, so it can be calculated once for all lines. - */ - float limitRatio{1.0f / SpeedOfSoundMetersPerSec / - CalcDecayLength(airAbsorptionGainHF, decayTime)}; - - /* Using the limit calculated above, apply the upper bound to the HF ratio. */ - return minf(limitRatio, hfRatio); -} - - -/* Calculates the 3-band T60 damping coefficients for a particular delay line - * of specified length, using a combination of two shelf filter sections given - * decay times for each band split at two reference frequencies. - */ -void T60Filter::calcCoeffs(const float length, const float lfDecayTime, - const float mfDecayTime, const float hfDecayTime, const float lf0norm, - const float hf0norm) -{ - const float mfGain{CalcDecayCoeff(length, mfDecayTime)}; - const float lfGain{CalcDecayCoeff(length, lfDecayTime) / mfGain}; - const float hfGain{CalcDecayCoeff(length, hfDecayTime) / mfGain}; - - MidGain[1] = mfGain; - LFFilter.setParamsFromSlope(BiquadType::LowShelf, lf0norm, lfGain, 1.0f); - HFFilter.setParamsFromSlope(BiquadType::HighShelf, hf0norm, hfGain, 1.0f); -} - -/* Update the early reflection line lengths and gain coefficients. */ -void EarlyReflections::updateLines(const float density_mult, const float diffusion, - const float decayTime, const float frequency) -{ - constexpr float sqrt1_2{0.70710678118654752440f/*1.0f/std::sqrt(2.0f)*/}; - - /* Calculate the all-pass feed-back/forward coefficient. */ - VecAp.Coeff = diffusion*diffusion * sqrt1_2; - - for(size_t i{0u};i < NUM_LINES;i++) - { - /* Calculate the delay length of each all-pass line. */ - float length{EARLY_ALLPASS_LENGTHS[i] * density_mult}; - VecAp.Offset[i][1] = float2uint(length * frequency); - - /* Calculate the delay length of each delay line. */ - length = EARLY_LINE_LENGTHS[i] * density_mult; - Offset[i][1] = float2uint(length * frequency); - - /* Calculate the gain (coefficient) for each line. */ - Coeff[i][1] = CalcDecayCoeff(length, decayTime); - } -} - -/* Update the EAX modulation step and depth. Keep in mind that this kind of - * vibrato is additive and not multiplicative as one may expect. The downswing - * will sound stronger than the upswing. - */ -void Modulation::updateModulator(float modTime, float modDepth, float frequency) -{ - /* Modulation is calculated in two parts. - * - * The modulation time effects the sinus rate, altering the speed of - * frequency changes. An index is incremented for each sample with an - * appropriate step size to generate an LFO, which will vary the feedback - * delay over time. - */ - Step = maxu(fastf2u(MOD_FRACONE / (frequency * modTime)), 1); - - /* The modulation depth effects the amount of frequency change over the - * range of the sinus. It needs to be scaled by the modulation time so that - * a given depth produces a consistent change in frequency over all ranges - * of time. Since the depth is applied to a sinus value, it needs to be - * halved once for the sinus range and again for the sinus swing in time - * (half of it is spent decreasing the frequency, half is spent increasing - * it). - */ - if(modTime >= AL_EAXREVERB_DEFAULT_MODULATION_TIME) - { - /* To cancel the effects of a long period modulation on the late - * reverberation, the amount of pitch should be varied (decreased) - * according to the modulation time. The natural form is varying - * inversely, in fact resulting in an invariant. - */ - Depth[1] = MODULATION_DEPTH_COEFF / 4.0f * AL_EAXREVERB_DEFAULT_MODULATION_TIME * - modDepth * frequency; - } - else - Depth[1] = MODULATION_DEPTH_COEFF / 4.0f * modTime * modDepth * frequency; -} - -/* Update the late reverb line lengths and T60 coefficients. */ -void LateReverb::updateLines(const float density_mult, const float diffusion, - const float lfDecayTime, const float mfDecayTime, const float hfDecayTime, - const float lf0norm, const float hf0norm, const float frequency) -{ - /* Scaling factor to convert the normalized reference frequencies from - * representing 0...freq to 0...max_reference. - */ - const float norm_weight_factor{frequency / AL_EAXREVERB_MAX_HFREFERENCE}; - - const float late_allpass_avg{ - std::accumulate(LATE_ALLPASS_LENGTHS.begin(), LATE_ALLPASS_LENGTHS.end(), 0.0f) / - float{NUM_LINES}}; - - /* To compensate for changes in modal density and decay time of the late - * reverb signal, the input is attenuated based on the maximal energy of - * the outgoing signal. This approximation is used to keep the apparent - * energy of the signal equal for all ranges of density and decay time. - * - * The average length of the delay lines is used to calculate the - * attenuation coefficient. - */ - float length{std::accumulate(LATE_LINE_LENGTHS.begin(), LATE_LINE_LENGTHS.end(), 0.0f) / - float{NUM_LINES} + late_allpass_avg}; - length *= density_mult; - /* The density gain calculation uses an average decay time weighted by - * approximate bandwidth. This attempts to compensate for losses of energy - * that reduce decay time due to scattering into highly attenuated bands. - */ - const float decayTimeWeighted{ - lf0norm*norm_weight_factor*lfDecayTime + - (hf0norm - lf0norm)*norm_weight_factor*mfDecayTime + - (1.0f - hf0norm*norm_weight_factor)*hfDecayTime}; - DensityGain[1] = CalcDensityGain(CalcDecayCoeff(length, decayTimeWeighted)); - - /* Calculate the all-pass feed-back/forward coefficient. */ - constexpr float sqrt1_2{0.70710678118654752440f/*1.0f/std::sqrt(2.0f)*/}; - VecAp.Coeff = diffusion*diffusion * sqrt1_2; - - for(size_t i{0u};i < NUM_LINES;i++) - { - /* Calculate the delay length of each all-pass line. */ - length = LATE_ALLPASS_LENGTHS[i] * density_mult; - VecAp.Offset[i][1] = float2uint(length * frequency); - - /* Calculate the delay length of each feedback delay line. */ - length = LATE_LINE_LENGTHS[i] * density_mult; - Offset[i][1] = float2uint(length*frequency + 0.5f); - - /* Approximate the absorption that the vector all-pass would exhibit - * given the current diffusion so we don't have to process a full T60 - * filter for each of its four lines. Also include the average - * modulation delay (depth is half the max delay in samples). - */ - length += lerp(LATE_ALLPASS_LENGTHS[i], late_allpass_avg, diffusion)*density_mult + - Mod.Depth[1]/frequency; - - /* Calculate the T60 damping coefficients for each line. */ - T60[i].calcCoeffs(length, lfDecayTime, mfDecayTime, hfDecayTime, lf0norm, hf0norm); - } -} - - -/* Update the offsets for the main effect delay line. */ -void ReverbState::updateDelayLine(const float earlyDelay, const float lateDelay, - const float density_mult, const float decayTime, const float frequency) -{ - /* Early reflection taps are decorrelated by means of an average room - * reflection approximation described above the definition of the taps. - * This approximation is linear and so the above density multiplier can - * be applied to adjust the width of the taps. A single-band decay - * coefficient is applied to simulate initial attenuation and absorption. - * - * Late reverb taps are based on the late line lengths to allow a zero- - * delay path and offsets that would continue the propagation naturally - * into the late lines. - */ - for(size_t i{0u};i < NUM_LINES;i++) - { - float length{EARLY_TAP_LENGTHS[i]*density_mult}; - mEarlyDelayTap[i][1] = float2uint((earlyDelay+length) * frequency); - mEarlyDelayCoeff[i][1] = CalcDecayCoeff(length, decayTime); - - length = (LATE_LINE_LENGTHS[i] - LATE_LINE_LENGTHS.front())/float{NUM_LINES}*density_mult + - lateDelay; - mLateDelayTap[i][1] = mLateFeedTap + float2uint(length * frequency); - } -} - -/* Creates a transform matrix given a reverb vector. The vector pans the reverb - * reflections toward the given direction, using its magnitude (up to 1) as a - * focal strength. This function results in a B-Format transformation matrix - * that spatially focuses the signal in the desired direction. - */ -alu::Matrix GetTransformFromVector(const float *vec) -{ - constexpr float sqrt3{1.73205080756887719318f}; - - /* Normalize the panning vector according to the N3D scale, which has an - * extra sqrt(3) term on the directional components. Converting from OpenAL - * to B-Format also requires negating X (ACN 1) and Z (ACN 3). Note however - * that the reverb panning vectors use left-handed coordinates, unlike the - * rest of OpenAL which use right-handed. This is fixed by negating Z, - * which cancels out with the B-Format Z negation. - */ - float norm[3]; - float mag{std::sqrt(vec[0]*vec[0] + vec[1]*vec[1] + vec[2]*vec[2])}; - if(mag > 1.0f) - { - norm[0] = vec[0] / mag * -sqrt3; - norm[1] = vec[1] / mag * sqrt3; - norm[2] = vec[2] / mag * sqrt3; - mag = 1.0f; - } - else - { - /* If the magnitude is less than or equal to 1, just apply the sqrt(3) - * term. There's no need to renormalize the magnitude since it would - * just be reapplied in the matrix. - */ - norm[0] = vec[0] * -sqrt3; - norm[1] = vec[1] * sqrt3; - norm[2] = vec[2] * sqrt3; - } - - return alu::Matrix{ - 1.0f, 0.0f, 0.0f, 0.0f, - norm[0], 1.0f-mag, 0.0f, 0.0f, - norm[1], 0.0f, 1.0f-mag, 0.0f, - norm[2], 0.0f, 0.0f, 1.0f-mag - }; -} - -/* Update the early and late 3D panning gains. */ -void ReverbState::update3DPanning(const float *ReflectionsPan, const float *LateReverbPan, - const float earlyGain, const float lateGain, const EffectTarget &target) -{ - /* Create matrices that transform a B-Format signal according to the - * panning vectors. - */ - const alu::Matrix earlymat{GetTransformFromVector(ReflectionsPan)}; - const alu::Matrix latemat{GetTransformFromVector(LateReverbPan)}; - - mOutTarget = target.Main->Buffer; - for(size_t i{0u};i < NUM_LINES;i++) - { - const float coeffs[MaxAmbiChannels]{earlymat[0][i], earlymat[1][i], earlymat[2][i], - earlymat[3][i]}; - ComputePanGains(target.Main, coeffs, earlyGain, mEarly.PanGain[i]); - } - for(size_t i{0u};i < NUM_LINES;i++) - { - const float coeffs[MaxAmbiChannels]{latemat[0][i], latemat[1][i], latemat[2][i], - latemat[3][i]}; - ComputePanGains(target.Main, coeffs, lateGain, mLate.PanGain[i]); - } -} - -void ReverbState::update(const ALCcontext *Context, const EffectSlot *Slot, - const EffectProps *props, const EffectTarget target) -{ - const ALCdevice *Device{Context->mDevice.get()}; - const auto frequency = static_cast(Device->Frequency); - - /* Calculate the master filters */ - float hf0norm{minf(props->Reverb.HFReference/frequency, 0.49f)}; - mFilter[0].Lp.setParamsFromSlope(BiquadType::HighShelf, hf0norm, props->Reverb.GainHF, 1.0f); - float lf0norm{minf(props->Reverb.LFReference/frequency, 0.49f)}; - mFilter[0].Hp.setParamsFromSlope(BiquadType::LowShelf, lf0norm, props->Reverb.GainLF, 1.0f); - for(size_t i{1u};i < NUM_LINES;i++) - { - mFilter[i].Lp.copyParamsFrom(mFilter[0].Lp); - mFilter[i].Hp.copyParamsFrom(mFilter[0].Hp); - } - - /* The density-based room size (delay length) multiplier. */ - const float density_mult{CalcDelayLengthMult(props->Reverb.Density)}; - - /* Update the main effect delay and associated taps. */ - updateDelayLine(props->Reverb.ReflectionsDelay, props->Reverb.LateReverbDelay, - density_mult, props->Reverb.DecayTime, frequency); - - /* Update the early lines. */ - mEarly.updateLines(density_mult, props->Reverb.Diffusion, props->Reverb.DecayTime, frequency); - - /* Get the mixing matrix coefficients. */ - CalcMatrixCoeffs(props->Reverb.Diffusion, &mMixX, &mMixY); - - /* If the HF limit parameter is flagged, calculate an appropriate limit - * based on the air absorption parameter. - */ - float hfRatio{props->Reverb.DecayHFRatio}; - if(props->Reverb.DecayHFLimit && props->Reverb.AirAbsorptionGainHF < 1.0f) - hfRatio = CalcLimitedHfRatio(hfRatio, props->Reverb.AirAbsorptionGainHF, - props->Reverb.DecayTime); - - /* Calculate the LF/HF decay times. */ - const float lfDecayTime{clampf(props->Reverb.DecayTime * props->Reverb.DecayLFRatio, - AL_EAXREVERB_MIN_DECAY_TIME, AL_EAXREVERB_MAX_DECAY_TIME)}; - const float hfDecayTime{clampf(props->Reverb.DecayTime * hfRatio, - AL_EAXREVERB_MIN_DECAY_TIME, AL_EAXREVERB_MAX_DECAY_TIME)}; - - /* Update the modulator rate and depth. */ - mLate.Mod.updateModulator(props->Reverb.ModulationTime, props->Reverb.ModulationDepth, - frequency); - - /* Update the late lines. */ - mLate.updateLines(density_mult, props->Reverb.Diffusion, lfDecayTime, - props->Reverb.DecayTime, hfDecayTime, lf0norm, hf0norm, frequency); - - /* Update early and late 3D panning. */ - const float gain{props->Reverb.Gain * Slot->Gain * ReverbBoost}; - update3DPanning(props->Reverb.ReflectionsPan, props->Reverb.LateReverbPan, - props->Reverb.ReflectionsGain*gain, props->Reverb.LateReverbGain*gain, target); - - /* Calculate the max update size from the smallest relevant delay. */ - mMaxUpdate[1] = minz(MAX_UPDATE_SAMPLES, minz(mEarly.Offset[0][1], mLate.Offset[0][1])); - - /* Determine if delay-line cross-fading is required. Density is essentially - * a master control for the feedback delays, so changes the offsets of many - * delay lines. - */ - mDoFading |= (mParams.Density != props->Reverb.Density || - /* Diffusion and decay times influences the decay rate (gain) of the - * late reverb T60 filter. - */ - mParams.Diffusion != props->Reverb.Diffusion || - mParams.DecayTime != props->Reverb.DecayTime || - mParams.HFDecayTime != hfDecayTime || - mParams.LFDecayTime != lfDecayTime || - /* Modulation time and depth both require fading the modulation delay. */ - mParams.ModulationTime != props->Reverb.ModulationTime || - mParams.ModulationDepth != props->Reverb.ModulationDepth || - /* HF/LF References control the weighting used to calculate the density - * gain. - */ - mParams.HFReference != props->Reverb.HFReference || - mParams.LFReference != props->Reverb.LFReference); - if(mDoFading) - { - mParams.Density = props->Reverb.Density; - mParams.Diffusion = props->Reverb.Diffusion; - mParams.DecayTime = props->Reverb.DecayTime; - mParams.HFDecayTime = hfDecayTime; - mParams.LFDecayTime = lfDecayTime; - mParams.ModulationTime = props->Reverb.ModulationTime; - mParams.ModulationDepth = props->Reverb.ModulationDepth; - mParams.HFReference = props->Reverb.HFReference; - mParams.LFReference = props->Reverb.LFReference; - } -} - - -/************************************** - * Effect Processing * - **************************************/ - -/* Applies a scattering matrix to the 4-line (vector) input. This is used - * for both the below vector all-pass model and to perform modal feed-back - * delay network (FDN) mixing. - * - * The matrix is derived from a skew-symmetric matrix to form a 4D rotation - * matrix with a single unitary rotational parameter: - * - * [ d, a, b, c ] 1 = a^2 + b^2 + c^2 + d^2 - * [ -a, d, c, -b ] - * [ -b, -c, d, a ] - * [ -c, b, -a, d ] - * - * The rotation is constructed from the effect's diffusion parameter, - * yielding: - * - * 1 = x^2 + 3 y^2 - * - * Where a, b, and c are the coefficient y with differing signs, and d is the - * coefficient x. The final matrix is thus: - * - * [ x, y, -y, y ] n = sqrt(matrix_order - 1) - * [ -y, x, y, y ] t = diffusion_parameter * atan(n) - * [ y, -y, x, y ] x = cos(t) - * [ -y, -y, -y, x ] y = sin(t) / n - * - * Any square orthogonal matrix with an order that is a power of two will - * work (where ^T is transpose, ^-1 is inverse): - * - * M^T = M^-1 - * - * Using that knowledge, finding an appropriate matrix can be accomplished - * naively by searching all combinations of: - * - * M = D + S - S^T - * - * Where D is a diagonal matrix (of x), and S is a triangular matrix (of y) - * whose combination of signs are being iterated. - */ -inline auto VectorPartialScatter(const std::array &RESTRICT in, - const float xCoeff, const float yCoeff) -> std::array -{ - return std::array{{ - xCoeff*in[0] + yCoeff*( in[1] + -in[2] + in[3]), - xCoeff*in[1] + yCoeff*(-in[0] + in[2] + in[3]), - xCoeff*in[2] + yCoeff*( in[0] + -in[1] + in[3]), - xCoeff*in[3] + yCoeff*(-in[0] + -in[1] + -in[2] ) - }}; -} - -/* Utilizes the above, but reverses the input channels. */ -void VectorScatterRevDelayIn(const DelayLineI delay, size_t offset, const float xCoeff, - const float yCoeff, const al::span in, const size_t count) -{ - ASSUME(count > 0); - - for(size_t i{0u};i < count;) - { - offset &= delay.Mask; - size_t td{minz(delay.Mask+1 - offset, count-i)}; - do { - std::array f; - for(size_t j{0u};j < NUM_LINES;j++) - f[NUM_LINES-1-j] = in[j][i]; - ++i; - - delay.Line[offset++] = VectorPartialScatter(f, xCoeff, yCoeff); - } while(--td); - } -} - -/* This applies a Gerzon multiple-in/multiple-out (MIMO) vector all-pass - * filter to the 4-line input. - * - * It works by vectorizing a regular all-pass filter and replacing the delay - * element with a scattering matrix (like the one above) and a diagonal - * matrix of delay elements. - * - * Two static specializations are used for transitional (cross-faded) delay - * line processing and non-transitional processing. - */ -void VecAllpass::processUnfaded(const al::span samples, size_t offset, - const float xCoeff, const float yCoeff, const size_t todo) -{ - const DelayLineI delay{Delay}; - const float feedCoeff{Coeff}; - - ASSUME(todo > 0); - - size_t vap_offset[NUM_LINES]; - for(size_t j{0u};j < NUM_LINES;j++) - vap_offset[j] = offset - Offset[j][0]; - for(size_t i{0u};i < todo;) - { - for(size_t j{0u};j < NUM_LINES;j++) - vap_offset[j] &= delay.Mask; - offset &= delay.Mask; - - size_t maxoff{offset}; - for(size_t j{0u};j < NUM_LINES;j++) - maxoff = maxz(maxoff, vap_offset[j]); - size_t td{minz(delay.Mask+1 - maxoff, todo - i)}; - - do { - std::array f; - for(size_t j{0u};j < NUM_LINES;j++) - { - const float input{samples[j][i]}; - const float out{delay.Line[vap_offset[j]++][j] - feedCoeff*input}; - f[j] = input + feedCoeff*out; - - samples[j][i] = out; - } - ++i; - - delay.Line[offset++] = VectorPartialScatter(f, xCoeff, yCoeff); - } while(--td); - } -} -void VecAllpass::processFaded(const al::span samples, size_t offset, - const float xCoeff, const float yCoeff, float fadeCount, const float fadeStep, - const size_t todo) -{ - const DelayLineI delay{Delay}; - const float feedCoeff{Coeff}; - - ASSUME(todo > 0); - - size_t vap_offset[NUM_LINES][2]; - for(size_t j{0u};j < NUM_LINES;j++) - { - vap_offset[j][0] = offset - Offset[j][0]; - vap_offset[j][1] = offset - Offset[j][1]; - } - for(size_t i{0u};i < todo;) - { - for(size_t j{0u};j < NUM_LINES;j++) - { - vap_offset[j][0] &= delay.Mask; - vap_offset[j][1] &= delay.Mask; - } - offset &= delay.Mask; - - size_t maxoff{offset}; - for(size_t j{0u};j < NUM_LINES;j++) - maxoff = maxz(maxoff, maxz(vap_offset[j][0], vap_offset[j][1])); - size_t td{minz(delay.Mask+1 - maxoff, todo - i)}; - - do { - fadeCount += 1.0f; - const float fade{fadeCount * fadeStep}; - - std::array f; - for(size_t j{0u};j < NUM_LINES;j++) - f[j] = delay.Line[vap_offset[j][0]++][j]*(1.0f-fade) + - delay.Line[vap_offset[j][1]++][j]*fade; - - for(size_t j{0u};j < NUM_LINES;j++) - { - const float input{samples[j][i]}; - const float out{f[j] - feedCoeff*input}; - f[j] = input + feedCoeff*out; - - samples[j][i] = out; - } - ++i; - - delay.Line[offset++] = VectorPartialScatter(f, xCoeff, yCoeff); - } while(--td); - } -} - -/* This generates early reflections. - * - * This is done by obtaining the primary reflections (those arriving from the - * same direction as the source) from the main delay line. These are - * attenuated and all-pass filtered (based on the diffusion parameter). - * - * The early lines are then fed in reverse (according to the approximately - * opposite spatial location of the A-Format lines) to create the secondary - * reflections (those arriving from the opposite direction as the source). - * - * The early response is then completed by combining the primary reflections - * with the delayed and attenuated output from the early lines. - * - * Finally, the early response is reversed, scattered (based on diffusion), - * and fed into the late reverb section of the main delay line. - * - * Two static specializations are used for transitional (cross-faded) delay - * line processing and non-transitional processing. - */ -void ReverbState::earlyUnfaded(const size_t offset, const size_t todo) -{ - const DelayLineI early_delay{mEarly.Delay}; - const DelayLineI main_delay{mDelay}; - const float mixX{mMixX}; - const float mixY{mMixY}; - - ASSUME(todo > 0); - - /* First, load decorrelated samples from the main delay line as the primary - * reflections. - */ - for(size_t j{0u};j < NUM_LINES;j++) - { - size_t early_delay_tap{offset - mEarlyDelayTap[j][0]}; - const float coeff{mEarlyDelayCoeff[j][0]}; - for(size_t i{0u};i < todo;) - { - early_delay_tap &= main_delay.Mask; - size_t td{minz(main_delay.Mask+1 - early_delay_tap, todo - i)}; - do { - mTempSamples[j][i++] = main_delay.Line[early_delay_tap++][j] * coeff; - } while(--td); - } - } - - /* Apply a vector all-pass, to help color the initial reflections based on - * the diffusion strength. - */ - mEarly.VecAp.processUnfaded(mTempSamples, offset, mixX, mixY, todo); - - /* Apply a delay and bounce to generate secondary reflections, combine with - * the primary reflections and write out the result for mixing. - */ - for(size_t j{0u};j < NUM_LINES;j++) - { - size_t feedb_tap{offset - mEarly.Offset[j][0]}; - const float feedb_coeff{mEarly.Coeff[j][0]}; - float *out{mEarlySamples[j].data()}; - - for(size_t i{0u};i < todo;) - { - feedb_tap &= early_delay.Mask; - size_t td{minz(early_delay.Mask+1 - feedb_tap, todo - i)}; - do { - out[i] = mTempSamples[j][i] + early_delay.Line[feedb_tap++][j]*feedb_coeff; - ++i; - } while(--td); - } - } - for(size_t j{0u};j < NUM_LINES;j++) - early_delay.write(offset, NUM_LINES-1-j, mTempSamples[j].data(), todo); - - /* Also write the result back to the main delay line for the late reverb - * stage to pick up at the appropriate time, appplying a scatter and - * bounce to improve the initial diffusion in the late reverb. - */ - const size_t late_feed_tap{offset - mLateFeedTap}; - VectorScatterRevDelayIn(main_delay, late_feed_tap, mixX, mixY, mEarlySamples, todo); -} -void ReverbState::earlyFaded(const size_t offset, const size_t todo, const float fade, - const float fadeStep) -{ - const DelayLineI early_delay{mEarly.Delay}; - const DelayLineI main_delay{mDelay}; - const float mixX{mMixX}; - const float mixY{mMixY}; - - ASSUME(todo > 0); - - for(size_t j{0u};j < NUM_LINES;j++) - { - size_t early_delay_tap0{offset - mEarlyDelayTap[j][0]}; - size_t early_delay_tap1{offset - mEarlyDelayTap[j][1]}; - const float oldCoeff{mEarlyDelayCoeff[j][0]}; - const float oldCoeffStep{-oldCoeff * fadeStep}; - const float newCoeffStep{mEarlyDelayCoeff[j][1] * fadeStep}; - float fadeCount{fade}; - - for(size_t i{0u};i < todo;) - { - early_delay_tap0 &= main_delay.Mask; - early_delay_tap1 &= main_delay.Mask; - size_t td{minz(main_delay.Mask+1 - maxz(early_delay_tap0, early_delay_tap1), todo-i)}; - do { - fadeCount += 1.0f; - const float fade0{oldCoeff + oldCoeffStep*fadeCount}; - const float fade1{newCoeffStep*fadeCount}; - mTempSamples[j][i++] = - main_delay.Line[early_delay_tap0++][j]*fade0 + - main_delay.Line[early_delay_tap1++][j]*fade1; - } while(--td); - } - } - - mEarly.VecAp.processFaded(mTempSamples, offset, mixX, mixY, fade, fadeStep, todo); - - for(size_t j{0u};j < NUM_LINES;j++) - { - size_t feedb_tap0{offset - mEarly.Offset[j][0]}; - size_t feedb_tap1{offset - mEarly.Offset[j][1]}; - const float feedb_oldCoeff{mEarly.Coeff[j][0]}; - const float feedb_oldCoeffStep{-feedb_oldCoeff * fadeStep}; - const float feedb_newCoeffStep{mEarly.Coeff[j][1] * fadeStep}; - float *out{mEarlySamples[j].data()}; - float fadeCount{fade}; - - for(size_t i{0u};i < todo;) - { - feedb_tap0 &= early_delay.Mask; - feedb_tap1 &= early_delay.Mask; - size_t td{minz(early_delay.Mask+1 - maxz(feedb_tap0, feedb_tap1), todo - i)}; - - do { - fadeCount += 1.0f; - const float fade0{feedb_oldCoeff + feedb_oldCoeffStep*fadeCount}; - const float fade1{feedb_newCoeffStep*fadeCount}; - out[i] = mTempSamples[j][i] + - early_delay.Line[feedb_tap0++][j]*fade0 + - early_delay.Line[feedb_tap1++][j]*fade1; - ++i; - } while(--td); - } - } - for(size_t j{0u};j < NUM_LINES;j++) - early_delay.write(offset, NUM_LINES-1-j, mTempSamples[j].data(), todo); - - const size_t late_feed_tap{offset - mLateFeedTap}; - VectorScatterRevDelayIn(main_delay, late_feed_tap, mixX, mixY, mEarlySamples, todo); -} - - -void Modulation::calcDelays(size_t todo) -{ - constexpr float inv_scale{MOD_FRACONE / al::MathDefs::Tau()}; - uint idx{Index}; - const uint step{Step}; - const float depth{Depth[0]}; - for(size_t i{0};i < todo;++i) - { - idx += step; - const float lfo{std::sin(static_cast(idx&MOD_FRACMASK) / inv_scale)}; - ModDelays[i] = (lfo+1.0f) * depth; - } - Index = idx; -} - -void Modulation::calcFadedDelays(size_t todo, float fadeCount, float fadeStep) -{ - constexpr float inv_scale{MOD_FRACONE / al::MathDefs::Tau()}; - uint idx{Index}; - const uint step{Step}; - const float depth{Depth[0]}; - const float depthStep{(Depth[1]-depth) * fadeStep}; - for(size_t i{0};i < todo;++i) - { - fadeCount += 1.0f; - idx += step; - const float lfo{std::sin(static_cast(idx&MOD_FRACMASK) / inv_scale)}; - ModDelays[i] = (lfo+1.0f) * (depth + depthStep*fadeCount); - } - Index = idx; -} - - -/* This generates the reverb tail using a modified feed-back delay network - * (FDN). - * - * Results from the early reflections are mixed with the output from the - * modulated late delay lines. - * - * The late response is then completed by T60 and all-pass filtering the mix. - * - * Finally, the lines are reversed (so they feed their opposite directions) - * and scattered with the FDN matrix before re-feeding the delay lines. - * - * Two variations are made, one for for transitional (cross-faded) delay line - * processing and one for non-transitional processing. - */ -void ReverbState::lateUnfaded(const size_t offset, const size_t todo) -{ - const DelayLineI late_delay{mLate.Delay}; - const DelayLineI main_delay{mDelay}; - const float mixX{mMixX}; - const float mixY{mMixY}; - - ASSUME(todo > 0); - - /* First, calculate the modulated delays for the late feedback. */ - mLate.Mod.calcDelays(todo); - - /* Next, load decorrelated samples from the main and feedback delay lines. - * Filter the signal to apply its frequency-dependent decay. - */ - for(size_t j{0u};j < NUM_LINES;j++) - { - size_t late_delay_tap{offset - mLateDelayTap[j][0]}; - size_t late_feedb_tap{offset - mLate.Offset[j][0]}; - const float midGain{mLate.T60[j].MidGain[0]}; - const float densityGain{mLate.DensityGain[0] * midGain}; - - for(size_t i{0u};i < todo;) - { - late_delay_tap &= main_delay.Mask; - size_t td{minz(todo - i, main_delay.Mask+1 - late_delay_tap)}; - do { - /* Calculate the read offset and fraction between it and the - * next sample. - */ - const float fdelay{mLate.Mod.ModDelays[i]}; - const size_t delay{float2uint(fdelay)}; - const float frac{fdelay - static_cast(delay)}; - - /* Feed the delay line with the late feedback sample, and get - * the two samples crossed by the delayed offset. - */ - const float out0{late_delay.Line[(late_feedb_tap-delay) & late_delay.Mask][j]}; - const float out1{late_delay.Line[(late_feedb_tap-delay-1) & late_delay.Mask][j]}; - ++late_feedb_tap; - - /* The output is obtained by linearly interpolating the two - * samples that were acquired above, and combined with the main - * delay tap. - */ - mTempSamples[j][i] = lerp(out0, out1, frac)*midGain + - main_delay.Line[late_delay_tap++][j]*densityGain; - ++i; - } while(--td); - } - mLate.T60[j].process({mTempSamples[j].data(), todo}); - } - - /* Apply a vector all-pass to improve micro-surface diffusion, and write - * out the results for mixing. - */ - mLate.VecAp.processUnfaded(mTempSamples, offset, mixX, mixY, todo); - for(size_t j{0u};j < NUM_LINES;j++) - std::copy_n(mTempSamples[j].begin(), todo, mLateSamples[j].begin()); - - /* Finally, scatter and bounce the results to refeed the feedback buffer. */ - VectorScatterRevDelayIn(late_delay, offset, mixX, mixY, mTempSamples, todo); -} -void ReverbState::lateFaded(const size_t offset, const size_t todo, const float fade, - const float fadeStep) -{ - const DelayLineI late_delay{mLate.Delay}; - const DelayLineI main_delay{mDelay}; - const float mixX{mMixX}; - const float mixY{mMixY}; - - ASSUME(todo > 0); - - mLate.Mod.calcFadedDelays(todo, fade, fadeStep); - - for(size_t j{0u};j < NUM_LINES;j++) - { - const float oldMidGain{mLate.T60[j].MidGain[0]}; - const float midGain{mLate.T60[j].MidGain[1]}; - const float oldMidStep{-oldMidGain * fadeStep}; - const float midStep{midGain * fadeStep}; - const float oldDensityGain{mLate.DensityGain[0] * oldMidGain}; - const float densityGain{mLate.DensityGain[1] * midGain}; - const float oldDensityStep{-oldDensityGain * fadeStep}; - const float densityStep{densityGain * fadeStep}; - size_t late_delay_tap0{offset - mLateDelayTap[j][0]}; - size_t late_delay_tap1{offset - mLateDelayTap[j][1]}; - size_t late_feedb_tap0{offset - mLate.Offset[j][0]}; - size_t late_feedb_tap1{offset - mLate.Offset[j][1]}; - float fadeCount{fade}; - - for(size_t i{0u};i < todo;) - { - late_delay_tap0 &= main_delay.Mask; - late_delay_tap1 &= main_delay.Mask; - size_t td{minz(todo - i, main_delay.Mask+1 - maxz(late_delay_tap0, late_delay_tap1))}; - do { - fadeCount += 1.0f; - - const float fdelay{mLate.Mod.ModDelays[i]}; - const size_t delay{float2uint(fdelay)}; - const float frac{fdelay - static_cast(delay)}; - - const float out00{late_delay.Line[(late_feedb_tap0-delay) & late_delay.Mask][j]}; - const float out01{late_delay.Line[(late_feedb_tap0-delay-1) & late_delay.Mask][j]}; - ++late_feedb_tap0; - const float out10{late_delay.Line[(late_feedb_tap1-delay) & late_delay.Mask][j]}; - const float out11{late_delay.Line[(late_feedb_tap1-delay-1) & late_delay.Mask][j]}; - ++late_feedb_tap1; - - const float fade0{oldDensityGain + oldDensityStep*fadeCount}; - const float fade1{densityStep*fadeCount}; - const float gfade0{oldMidGain + oldMidStep*fadeCount}; - const float gfade1{midStep*fadeCount}; - mTempSamples[j][i] = lerp(out00, out01, frac)*gfade0 + - lerp(out10, out11, frac)*gfade1 + - main_delay.Line[late_delay_tap0++][j]*fade0 + - main_delay.Line[late_delay_tap1++][j]*fade1; - ++i; - } while(--td); - } - mLate.T60[j].process({mTempSamples[j].data(), todo}); - } - - mLate.VecAp.processFaded(mTempSamples, offset, mixX, mixY, fade, fadeStep, todo); - for(size_t j{0u};j < NUM_LINES;j++) - std::copy_n(mTempSamples[j].begin(), todo, mLateSamples[j].begin()); - - VectorScatterRevDelayIn(late_delay, offset, mixX, mixY, mTempSamples, todo); -} - -void ReverbState::process(const size_t samplesToDo, const al::span samplesIn, const al::span samplesOut) -{ - size_t offset{mOffset}; - - ASSUME(samplesToDo > 0); - - /* Convert B-Format to A-Format for processing. */ - const size_t numInput{minz(samplesIn.size(), NUM_LINES)}; - const al::span tmpspan{al::assume_aligned<16>(mTempLine.data()), samplesToDo}; - for(size_t c{0u};c < NUM_LINES;c++) - { - std::fill(tmpspan.begin(), tmpspan.end(), 0.0f); - for(size_t i{0};i < numInput;++i) - { - const float gain{B2A[c][i]}; - const float *RESTRICT input{al::assume_aligned<16>(samplesIn[i].data())}; - - for(float &sample : tmpspan) - { - sample += *input * gain; - ++input; - } - } - - /* Band-pass the incoming samples and feed the initial delay line. */ - DualBiquad{mFilter[c].Lp, mFilter[c].Hp}.process(tmpspan, tmpspan.data()); - mDelay.write(offset, c, tmpspan.cbegin(), samplesToDo); - } - - /* Process reverb for these samples. */ - if LIKELY(!mDoFading) - { - for(size_t base{0};base < samplesToDo;) - { - /* Calculate the number of samples we can do this iteration. */ - size_t todo{minz(samplesToDo - base, mMaxUpdate[0])}; - /* Some mixers require maintaining a 4-sample alignment, so ensure - * that if it's not the last iteration. - */ - if(base+todo < samplesToDo) todo &= ~size_t{3}; - ASSUME(todo > 0); - - /* Generate non-faded early reflections and late reverb. */ - earlyUnfaded(offset, todo); - lateUnfaded(offset, todo); - - /* Finally, mix early reflections and late reverb. */ - (this->*mMixOut)(samplesOut, samplesToDo-base, base, todo); - - offset += todo; - base += todo; - } - } - else - { - const float fadeStep{1.0f / static_cast(samplesToDo)}; - for(size_t base{0};base < samplesToDo;) - { - size_t todo{minz(samplesToDo - base, minz(mMaxUpdate[0], mMaxUpdate[1]))}; - if(base+todo < samplesToDo) todo &= ~size_t{3}; - ASSUME(todo > 0); - - /* Generate cross-faded early reflections and late reverb. */ - auto fadeCount = static_cast(base); - earlyFaded(offset, todo, fadeCount, fadeStep); - lateFaded(offset, todo, fadeCount, fadeStep); - - (this->*mMixOut)(samplesOut, samplesToDo-base, base, todo); - - offset += todo; - base += todo; - } - - /* Update the cross-fading delay line taps. */ - for(size_t c{0u};c < NUM_LINES;c++) - { - mEarlyDelayTap[c][0] = mEarlyDelayTap[c][1]; - mEarlyDelayCoeff[c][0] = mEarlyDelayCoeff[c][1]; - mLateDelayTap[c][0] = mLateDelayTap[c][1]; - mEarly.VecAp.Offset[c][0] = mEarly.VecAp.Offset[c][1]; - mEarly.Offset[c][0] = mEarly.Offset[c][1]; - mEarly.Coeff[c][0] = mEarly.Coeff[c][1]; - mLate.Offset[c][0] = mLate.Offset[c][1]; - mLate.T60[c].MidGain[0] = mLate.T60[c].MidGain[1]; - mLate.VecAp.Offset[c][0] = mLate.VecAp.Offset[c][1]; - } - mLate.DensityGain[0] = mLate.DensityGain[1]; - mLate.Mod.Depth[0] = mLate.Mod.Depth[1]; - mMaxUpdate[0] = mMaxUpdate[1]; - mDoFading = false; - } - mOffset = offset; -} - - -struct ReverbStateFactory final : public EffectStateFactory { - al::intrusive_ptr create() override - { return al::intrusive_ptr{new ReverbState{}}; } -}; - -struct StdReverbStateFactory final : public EffectStateFactory { - al::intrusive_ptr create() override - { return al::intrusive_ptr{new ReverbState{}}; } -}; - -} // namespace - -EffectStateFactory *ReverbStateFactory_getFactory() -{ - static ReverbStateFactory ReverbFactory{}; - return &ReverbFactory; -} - -EffectStateFactory *StdReverbStateFactory_getFactory() -{ - static StdReverbStateFactory ReverbFactory{}; - return &ReverbFactory; -} diff --git a/alc/effects/vmorpher.cpp b/alc/effects/vmorpher.cpp deleted file mode 100644 index f1c46b8c..00000000 --- a/alc/effects/vmorpher.cpp +++ /dev/null @@ -1,314 +0,0 @@ -/** - * OpenAL cross platform audio library - * Copyright (C) 2019 by Anis A. Hireche - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - * Or go to http://www.gnu.org/copyleft/lgpl.html - */ - -#include "config.h" - -#include -#include -#include -#include - -#include "alcmain.h" -#include "alcontext.h" -#include "alu.h" -#include "effectslot.h" -#include "math_defs.h" - - -namespace { - -#define MAX_UPDATE_SAMPLES 256 -#define NUM_FORMANTS 4 -#define NUM_FILTERS 2 -#define Q_FACTOR 5.0f - -#define VOWEL_A_INDEX 0 -#define VOWEL_B_INDEX 1 - -#define WAVEFORM_FRACBITS 24 -#define WAVEFORM_FRACONE (1<::Tau() / WAVEFORM_FRACONE}; - return std::sin(static_cast(index) * scale)*0.5f + 0.5f; -} - -inline float Saw(uint index) -{ return static_cast(index) / float{WAVEFORM_FRACONE}; } - -inline float Triangle(uint index) -{ return std::fabs(static_cast(index)*(2.0f/WAVEFORM_FRACONE) - 1.0f); } - -inline float Half(uint) { return 0.5f; } - -template -void Oscillate(float *RESTRICT dst, uint index, const uint step, size_t todo) -{ - for(size_t i{0u};i < todo;i++) - { - index += step; - index &= WAVEFORM_FRACMASK; - dst[i] = func(index); - } -} - -struct FormantFilter -{ - float mCoeff{0.0f}; - float mGain{1.0f}; - float mS1{0.0f}; - float mS2{0.0f}; - - FormantFilter() = default; - FormantFilter(float f0norm, float gain) - : mCoeff{std::tan(al::MathDefs::Pi() * f0norm)}, mGain{gain} - { } - - inline void process(const float *samplesIn, float *samplesOut, const size_t numInput) - { - /* A state variable filter from a topology-preserving transform. - * Based on a talk given by Ivan Cohen: https://www.youtube.com/watch?v=esjHXGPyrhg - */ - const float g{mCoeff}; - const float gain{mGain}; - const float h{1.0f / (1.0f + (g/Q_FACTOR) + (g*g))}; - float s1{mS1}; - float s2{mS2}; - - for(size_t i{0u};i < numInput;i++) - { - const float H{(samplesIn[i] - (1.0f/Q_FACTOR + g)*s1 - s2)*h}; - const float B{g*H + s1}; - const float L{g*B + s2}; - - s1 = g*H + B; - s2 = g*B + L; - - // Apply peak and accumulate samples. - samplesOut[i] += B * gain; - } - mS1 = s1; - mS2 = s2; - } - - inline void clear() - { - mS1 = 0.0f; - mS2 = 0.0f; - } -}; - - -struct VmorpherState final : public EffectState { - struct { - /* Effect parameters */ - FormantFilter Formants[NUM_FILTERS][NUM_FORMANTS]; - - /* Effect gains for each channel */ - float CurrentGains[MAX_OUTPUT_CHANNELS]{}; - float TargetGains[MAX_OUTPUT_CHANNELS]{}; - } mChans[MaxAmbiChannels]; - - void (*mGetSamples)(float*RESTRICT, uint, const uint, size_t){}; - - uint mIndex{0}; - uint mStep{1}; - - /* Effects buffers */ - alignas(16) float mSampleBufferA[MAX_UPDATE_SAMPLES]{}; - alignas(16) float mSampleBufferB[MAX_UPDATE_SAMPLES]{}; - alignas(16) float mLfo[MAX_UPDATE_SAMPLES]{}; - - void deviceUpdate(const ALCdevice *device, const BufferStorage *buffer) override; - void update(const ALCcontext *context, const EffectSlot *slot, const EffectProps *props, - const EffectTarget target) override; - void process(const size_t samplesToDo, const al::span samplesIn, - const al::span samplesOut) override; - - static std::array getFiltersByPhoneme(VMorpherPhenome phoneme, - float frequency, float pitch); - - DEF_NEWDEL(VmorpherState) -}; - -std::array VmorpherState::getFiltersByPhoneme(VMorpherPhenome phoneme, - float frequency, float pitch) -{ - /* Using soprano formant set of values to - * better match mid-range frequency space. - * - * See: https://www.classes.cs.uchicago.edu/archive/1999/spring/CS295/Computing_Resources/Csound/CsManual3.48b1.HTML/Appendices/table3.html - */ - switch(phoneme) - { - case VMorpherPhenome::A: - return {{ - {( 800 * pitch) / frequency, 1.000000f}, /* std::pow(10.0f, 0 / 20.0f); */ - {(1150 * pitch) / frequency, 0.501187f}, /* std::pow(10.0f, -6 / 20.0f); */ - {(2900 * pitch) / frequency, 0.025118f}, /* std::pow(10.0f, -32 / 20.0f); */ - {(3900 * pitch) / frequency, 0.100000f} /* std::pow(10.0f, -20 / 20.0f); */ - }}; - case VMorpherPhenome::E: - return {{ - {( 350 * pitch) / frequency, 1.000000f}, /* std::pow(10.0f, 0 / 20.0f); */ - {(2000 * pitch) / frequency, 0.100000f}, /* std::pow(10.0f, -20 / 20.0f); */ - {(2800 * pitch) / frequency, 0.177827f}, /* std::pow(10.0f, -15 / 20.0f); */ - {(3600 * pitch) / frequency, 0.009999f} /* std::pow(10.0f, -40 / 20.0f); */ - }}; - case VMorpherPhenome::I: - return {{ - {( 270 * pitch) / frequency, 1.000000f}, /* std::pow(10.0f, 0 / 20.0f); */ - {(2140 * pitch) / frequency, 0.251188f}, /* std::pow(10.0f, -12 / 20.0f); */ - {(2950 * pitch) / frequency, 0.050118f}, /* std::pow(10.0f, -26 / 20.0f); */ - {(3900 * pitch) / frequency, 0.050118f} /* std::pow(10.0f, -26 / 20.0f); */ - }}; - case VMorpherPhenome::O: - return {{ - {( 450 * pitch) / frequency, 1.000000f}, /* std::pow(10.0f, 0 / 20.0f); */ - {( 800 * pitch) / frequency, 0.281838f}, /* std::pow(10.0f, -11 / 20.0f); */ - {(2830 * pitch) / frequency, 0.079432f}, /* std::pow(10.0f, -22 / 20.0f); */ - {(3800 * pitch) / frequency, 0.079432f} /* std::pow(10.0f, -22 / 20.0f); */ - }}; - case VMorpherPhenome::U: - return {{ - {( 325 * pitch) / frequency, 1.000000f}, /* std::pow(10.0f, 0 / 20.0f); */ - {( 700 * pitch) / frequency, 0.158489f}, /* std::pow(10.0f, -16 / 20.0f); */ - {(2700 * pitch) / frequency, 0.017782f}, /* std::pow(10.0f, -35 / 20.0f); */ - {(3800 * pitch) / frequency, 0.009999f} /* std::pow(10.0f, -40 / 20.0f); */ - }}; - default: - break; - } - return {}; -} - - -void VmorpherState::deviceUpdate(const ALCdevice* /*device*/, const BufferStorage* /*buffer*/) -{ - for(auto &e : mChans) - { - std::for_each(std::begin(e.Formants[VOWEL_A_INDEX]), std::end(e.Formants[VOWEL_A_INDEX]), - std::mem_fn(&FormantFilter::clear)); - std::for_each(std::begin(e.Formants[VOWEL_B_INDEX]), std::end(e.Formants[VOWEL_B_INDEX]), - std::mem_fn(&FormantFilter::clear)); - std::fill(std::begin(e.CurrentGains), std::end(e.CurrentGains), 0.0f); - } -} - -void VmorpherState::update(const ALCcontext *context, const EffectSlot *slot, - const EffectProps *props, const EffectTarget target) -{ - const ALCdevice *device{context->mDevice.get()}; - const float frequency{static_cast(device->Frequency)}; - const float step{props->Vmorpher.Rate / frequency}; - mStep = fastf2u(clampf(step*WAVEFORM_FRACONE, 0.0f, float{WAVEFORM_FRACONE-1})); - - if(mStep == 0) - mGetSamples = Oscillate; - else if(props->Vmorpher.Waveform == VMorpherWaveform::Sinusoid) - mGetSamples = Oscillate; - else if(props->Vmorpher.Waveform == VMorpherWaveform::Triangle) - mGetSamples = Oscillate; - else /*if(props->Vmorpher.Waveform == VMorpherWaveform::Sawtooth)*/ - mGetSamples = Oscillate; - - const float pitchA{std::pow(2.0f, - static_cast(props->Vmorpher.PhonemeACoarseTuning) / 12.0f)}; - const float pitchB{std::pow(2.0f, - static_cast(props->Vmorpher.PhonemeBCoarseTuning) / 12.0f)}; - - auto vowelA = getFiltersByPhoneme(props->Vmorpher.PhonemeA, frequency, pitchA); - auto vowelB = getFiltersByPhoneme(props->Vmorpher.PhonemeB, frequency, pitchB); - - /* Copy the filter coefficients to the input channels. */ - for(size_t i{0u};i < slot->Wet.Buffer.size();++i) - { - std::copy(vowelA.begin(), vowelA.end(), std::begin(mChans[i].Formants[VOWEL_A_INDEX])); - std::copy(vowelB.begin(), vowelB.end(), std::begin(mChans[i].Formants[VOWEL_B_INDEX])); - } - - mOutTarget = target.Main->Buffer; - auto set_gains = [slot,target](auto &chan, al::span coeffs) - { ComputePanGains(target.Main, coeffs.data(), slot->Gain, chan.TargetGains); }; - SetAmbiPanIdentity(std::begin(mChans), slot->Wet.Buffer.size(), set_gains); -} - -void VmorpherState::process(const size_t samplesToDo, const al::span samplesIn, const al::span samplesOut) -{ - /* Following the EFX specification for a conformant implementation which describes - * the effect as a pair of 4-band formant filters blended together using an LFO. - */ - for(size_t base{0u};base < samplesToDo;) - { - const size_t td{minz(MAX_UPDATE_SAMPLES, samplesToDo-base)}; - - mGetSamples(mLfo, mIndex, mStep, td); - mIndex += static_cast(mStep * td); - mIndex &= WAVEFORM_FRACMASK; - - auto chandata = std::begin(mChans); - for(const auto &input : samplesIn) - { - auto& vowelA = chandata->Formants[VOWEL_A_INDEX]; - auto& vowelB = chandata->Formants[VOWEL_B_INDEX]; - - /* Process first vowel. */ - std::fill_n(std::begin(mSampleBufferA), td, 0.0f); - vowelA[0].process(&input[base], mSampleBufferA, td); - vowelA[1].process(&input[base], mSampleBufferA, td); - vowelA[2].process(&input[base], mSampleBufferA, td); - vowelA[3].process(&input[base], mSampleBufferA, td); - - /* Process second vowel. */ - std::fill_n(std::begin(mSampleBufferB), td, 0.0f); - vowelB[0].process(&input[base], mSampleBufferB, td); - vowelB[1].process(&input[base], mSampleBufferB, td); - vowelB[2].process(&input[base], mSampleBufferB, td); - vowelB[3].process(&input[base], mSampleBufferB, td); - - alignas(16) float blended[MAX_UPDATE_SAMPLES]; - for(size_t i{0u};i < td;i++) - blended[i] = lerp(mSampleBufferA[i], mSampleBufferB[i], mLfo[i]); - - /* Now, mix the processed sound data to the output. */ - MixSamples({blended, td}, samplesOut, chandata->CurrentGains, chandata->TargetGains, - samplesToDo-base, base); - ++chandata; - } - - base += td; - } -} - - -struct VmorpherStateFactory final : public EffectStateFactory { - al::intrusive_ptr create() override - { return al::intrusive_ptr{new VmorpherState{}}; } -}; - -} // namespace - -EffectStateFactory *VmorpherStateFactory_getFactory() -{ - static VmorpherStateFactory VmorpherFactory{}; - return &VmorpherFactory; -} diff --git a/alc/effectslot.cpp b/alc/effectslot.cpp deleted file mode 100644 index 8abac248..00000000 --- a/alc/effectslot.cpp +++ /dev/null @@ -1,25 +0,0 @@ - -#include "config.h" - -#include "effectslot.h" - -#include - -#include "alcontext.h" -#include "almalloc.h" - - -EffectSlotArray *EffectSlot::CreatePtrArray(size_t count) noexcept -{ - /* Allocate space for twice as many pointers, so the mixer has scratch - * space to store a sorted list during mixing. - */ - void *ptr{al_calloc(alignof(EffectSlotArray), EffectSlotArray::Sizeof(count*2))}; - return new(ptr) EffectSlotArray{count}; -} - -EffectSlot::~EffectSlot() -{ - if(mWetBuffer) - mWetBuffer->mInUse = false; -} diff --git a/alc/effectslot.h b/alc/effectslot.h deleted file mode 100644 index c1eb1cc3..00000000 --- a/alc/effectslot.h +++ /dev/null @@ -1,89 +0,0 @@ -#ifndef EFFECTSLOT_H -#define EFFECTSLOT_H - -#include - -#include "almalloc.h" -#include "alcmain.h" -#include "effects/base.h" -#include "intrusive_ptr.h" - - -struct EffectSlot; -struct WetBuffer; - -using EffectSlotArray = al::FlexArray; - - -enum class EffectSlotType : unsigned char { - None, - Reverb, - Chorus, - Distortion, - Echo, - Flanger, - FrequencyShifter, - VocalMorpher, - PitchShifter, - RingModulator, - Autowah, - Compressor, - Equalizer, - EAXReverb, - DedicatedLFE, - DedicatedDialog, - Convolution -}; - -struct EffectSlotProps { - float Gain; - bool AuxSendAuto; - EffectSlot *Target; - - EffectSlotType Type; - EffectProps Props; - - al::intrusive_ptr State; - - std::atomic next; - - DEF_NEWDEL(EffectSlotProps) -}; - - -struct EffectSlot { - std::atomic Update{nullptr}; - - /* Wet buffer configuration is ACN channel order with N3D scaling. - * Consequently, effects that only want to work with mono input can use - * channel 0 by itself. Effects that want multichannel can process the - * ambisonics signal and make a B-Format source pan. - */ - MixParams Wet; - - float Gain{1.0f}; - bool AuxSendAuto{true}; - EffectSlot *Target{nullptr}; - - EffectSlotType EffectType{EffectSlotType::None}; - EffectProps mEffectProps{}; - EffectState *mEffectState{nullptr}; - - float RoomRolloff{0.0f}; /* Added to the source's room rolloff, not multiplied. */ - float DecayTime{0.0f}; - float DecayLFRatio{0.0f}; - float DecayHFRatio{0.0f}; - bool DecayHFLimit{false}; - float AirAbsorptionGainHF{1.0f}; - - /* Mixing buffer used by the Wet mix. */ - WetBuffer *mWetBuffer{nullptr}; - - ~EffectSlot(); - - static EffectSlotArray *CreatePtrArray(size_t count) noexcept; - - DISABLE_ALLOC() -}; - -#endif /* EFFECTSLOT_H */ diff --git a/alc/front_stablizer.h b/alc/front_stablizer.h deleted file mode 100644 index 0fedeb50..00000000 --- a/alc/front_stablizer.h +++ /dev/null @@ -1,36 +0,0 @@ -#ifndef ALC_FRONT_STABLIZER_H -#define ALC_FRONT_STABLIZER_H - -#include -#include - -#include "almalloc.h" -#include "core/bufferline.h" -#include "core/filters/splitter.h" - - -struct FrontStablizer { - static constexpr size_t DelayLength{256u}; - - FrontStablizer(size_t numchans) : DelayBuf{numchans} { } - - alignas(16) std::array Side{}; - alignas(16) std::array MidDirect{}; - alignas(16) std::array MidDelay{}; - - alignas(16) std::array TempBuf{}; - - BandSplitter MidFilter; - alignas(16) FloatBufferLine MidLF{}; - alignas(16) FloatBufferLine MidHF{}; - - using DelayLine = std::array; - al::FlexArray DelayBuf; - - static std::unique_ptr Create(size_t numchans) - { return std::unique_ptr{new(FamCount(numchans)) FrontStablizer{numchans}}; } - - DEF_FAM_NEWDEL(FrontStablizer, DelayBuf) -}; - -#endif /* ALC_FRONT_STABLIZER_H */ diff --git a/alc/helpers.cpp b/alc/helpers.cpp deleted file mode 100644 index 8c1c8562..00000000 --- a/alc/helpers.cpp +++ /dev/null @@ -1,435 +0,0 @@ -/** - * OpenAL cross platform audio library - * Copyright (C) 2011 by authors. - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - * Or go to http://www.gnu.org/copyleft/lgpl.html - */ - -#include "config.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -#include "alcmain.h" -#include "almalloc.h" -#include "alfstream.h" -#include "alspan.h" -#include "alstring.h" -#include "compat.h" -#include "core/logging.h" -#include "strutils.h" -#include "vector.h" - - -#ifdef _WIN32 - -#include - -const PathNamePair &GetProcBinary() -{ - static PathNamePair ret; - if(!ret.fname.empty() || !ret.path.empty()) - return ret; - - auto fullpath = al::vector(256); - DWORD len; - while((len=GetModuleFileNameW(nullptr, fullpath.data(), static_cast(fullpath.size()))) == fullpath.size()) - fullpath.resize(fullpath.size() << 1); - if(len == 0) - { - ERR("Failed to get process name: error %lu\n", GetLastError()); - return ret; - } - - fullpath.resize(len); - if(fullpath.back() != 0) - fullpath.push_back(0); - - auto sep = std::find(fullpath.rbegin()+1, fullpath.rend(), '\\'); - sep = std::find(fullpath.rbegin()+1, sep, '/'); - if(sep != fullpath.rend()) - { - *sep = 0; - ret.fname = wstr_to_utf8(&*sep + 1); - ret.path = wstr_to_utf8(fullpath.data()); - } - else - ret.fname = wstr_to_utf8(fullpath.data()); - - TRACE("Got binary: %s, %s\n", ret.path.c_str(), ret.fname.c_str()); - return ret; -} - -namespace { - -void DirectorySearch(const char *path, const char *ext, al::vector *const results) -{ - std::string pathstr{path}; - pathstr += "\\*"; - pathstr += ext; - TRACE("Searching %s\n", pathstr.c_str()); - - std::wstring wpath{utf8_to_wstr(pathstr.c_str())}; - WIN32_FIND_DATAW fdata; - HANDLE hdl{FindFirstFileW(wpath.c_str(), &fdata)}; - if(hdl == INVALID_HANDLE_VALUE) return; - - const auto base = results->size(); - - do { - results->emplace_back(); - std::string &str = results->back(); - str = path; - str += '\\'; - str += wstr_to_utf8(fdata.cFileName); - } while(FindNextFileW(hdl, &fdata)); - FindClose(hdl); - - const al::span newlist{results->data()+base, results->size()-base}; - std::sort(newlist.begin(), newlist.end()); - for(const auto &name : newlist) - TRACE(" got %s\n", name.c_str()); -} - -} // namespace - -al::vector SearchDataFiles(const char *ext, const char *subdir) -{ - auto is_slash = [](int c) noexcept -> int { return (c == '\\' || c == '/'); }; - - static std::mutex search_lock; - std::lock_guard _{search_lock}; - - /* If the path is absolute, use it directly. */ - al::vector results; - if(isalpha(subdir[0]) && subdir[1] == ':' && is_slash(subdir[2])) - { - std::string path{subdir}; - std::replace(path.begin(), path.end(), '/', '\\'); - DirectorySearch(path.c_str(), ext, &results); - return results; - } - if(subdir[0] == '\\' && subdir[1] == '\\' && subdir[2] == '?' && subdir[3] == '\\') - { - DirectorySearch(subdir, ext, &results); - return results; - } - - std::string path; - - /* Search the app-local directory. */ - if(auto localpath = al::getenv(L"ALSOFT_LOCAL_PATH")) - { - path = wstr_to_utf8(localpath->c_str()); - if(is_slash(path.back())) - path.pop_back(); - } - else if(WCHAR *cwdbuf{_wgetcwd(nullptr, 0)}) - { - path = wstr_to_utf8(cwdbuf); - if(is_slash(path.back())) - path.pop_back(); - free(cwdbuf); - } - else - path = "."; - std::replace(path.begin(), path.end(), '/', '\\'); - DirectorySearch(path.c_str(), ext, &results); - - /* Search the local and global data dirs. */ - static const int ids[2]{ CSIDL_APPDATA, CSIDL_COMMON_APPDATA }; - for(int id : ids) - { - WCHAR buffer[MAX_PATH]; - if(SHGetSpecialFolderPathW(nullptr, buffer, id, FALSE) == FALSE) - continue; - - path = wstr_to_utf8(buffer); - if(!is_slash(path.back())) - path += '\\'; - path += subdir; - std::replace(path.begin(), path.end(), '/', '\\'); - - DirectorySearch(path.c_str(), ext, &results); - } - - return results; -} - -void SetRTPriority(void) -{ - if(RTPrioLevel > 0) - { - if(!SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL)) - ERR("Failed to set priority level for thread\n"); - } -} - -#else - -#include -#include -#include -#ifdef __FreeBSD__ -#include -#endif -#ifdef __HAIKU__ -#include -#endif -#ifdef HAVE_PROC_PIDPATH -#include -#endif -#if defined(HAVE_PTHREAD_SETSCHEDPARAM) && !defined(__OpenBSD__) -#include -#include -#endif - -const PathNamePair &GetProcBinary() -{ - static PathNamePair ret; - if(!ret.fname.empty() || !ret.path.empty()) - return ret; - - al::vector pathname; -#ifdef __FreeBSD__ - size_t pathlen; - int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1 }; - if(sysctl(mib, 4, nullptr, &pathlen, nullptr, 0) == -1) - WARN("Failed to sysctl kern.proc.pathname: %s\n", strerror(errno)); - else - { - pathname.resize(pathlen + 1); - sysctl(mib, 4, pathname.data(), &pathlen, nullptr, 0); - pathname.resize(pathlen); - } -#endif -#ifdef HAVE_PROC_PIDPATH - if(pathname.empty()) - { - char procpath[PROC_PIDPATHINFO_MAXSIZE]{}; - const pid_t pid{getpid()}; - if(proc_pidpath(pid, procpath, sizeof(procpath)) < 1) - ERR("proc_pidpath(%d, ...) failed: %s\n", pid, strerror(errno)); - else - pathname.insert(pathname.end(), procpath, procpath+strlen(procpath)); - } -#endif -#ifdef __HAIKU__ - if(pathname.empty()) - { - char procpath[PATH_MAX]; - if(find_path(B_APP_IMAGE_SYMBOL, B_FIND_PATH_IMAGE_PATH, NULL, procpath, sizeof(procpath)) == B_OK) - pathname.insert(pathname.end(), procpath, procpath+strlen(procpath)); - } -#endif - if(pathname.empty()) - { - static const char SelfLinkNames[][32]{ - "/proc/self/exe", - "/proc/self/file", - "/proc/curproc/exe", - "/proc/curproc/file" - }; - - pathname.resize(256); - - const char *selfname{}; - ssize_t len{}; - for(const char *name : SelfLinkNames) - { - selfname = name; - len = readlink(selfname, pathname.data(), pathname.size()); - if(len >= 0 || errno != ENOENT) break; - } - - while(len > 0 && static_cast(len) == pathname.size()) - { - pathname.resize(pathname.size() << 1); - len = readlink(selfname, pathname.data(), pathname.size()); - } - if(len <= 0) - { - WARN("Failed to readlink %s: %s\n", selfname, strerror(errno)); - return ret; - } - - pathname.resize(static_cast(len)); - } - while(!pathname.empty() && pathname.back() == 0) - pathname.pop_back(); - - auto sep = std::find(pathname.crbegin(), pathname.crend(), '/'); - if(sep != pathname.crend()) - { - ret.path = std::string(pathname.cbegin(), sep.base()-1); - ret.fname = std::string(sep.base(), pathname.cend()); - } - else - ret.fname = std::string(pathname.cbegin(), pathname.cend()); - - TRACE("Got binary: %s, %s\n", ret.path.c_str(), ret.fname.c_str()); - return ret; -} - -namespace { - -void DirectorySearch(const char *path, const char *ext, al::vector *const results) -{ - TRACE("Searching %s for *%s\n", path, ext); - DIR *dir{opendir(path)}; - if(!dir) return; - - const auto base = results->size(); - const size_t extlen{strlen(ext)}; - - while(struct dirent *dirent{readdir(dir)}) - { - if(strcmp(dirent->d_name, ".") == 0 || strcmp(dirent->d_name, "..") == 0) - continue; - - const size_t len{strlen(dirent->d_name)}; - if(len <= extlen) continue; - if(al::strcasecmp(dirent->d_name+len-extlen, ext) != 0) - continue; - - results->emplace_back(); - std::string &str = results->back(); - str = path; - if(str.back() != '/') - str.push_back('/'); - str += dirent->d_name; - } - closedir(dir); - - const al::span newlist{results->data()+base, results->size()-base}; - std::sort(newlist.begin(), newlist.end()); - for(const auto &name : newlist) - TRACE(" got %s\n", name.c_str()); -} - -} // namespace - -al::vector SearchDataFiles(const char *ext, const char *subdir) -{ - static std::mutex search_lock; - std::lock_guard _{search_lock}; - - al::vector results; - if(subdir[0] == '/') - { - DirectorySearch(subdir, ext, &results); - return results; - } - - /* Search the app-local directory. */ - if(auto localpath = al::getenv("ALSOFT_LOCAL_PATH")) - DirectorySearch(localpath->c_str(), ext, &results); - else - { - al::vector cwdbuf(256); - while(!getcwd(cwdbuf.data(), cwdbuf.size())) - { - if(errno != ERANGE) - { - cwdbuf.clear(); - break; - } - cwdbuf.resize(cwdbuf.size() << 1); - } - if(cwdbuf.empty()) - DirectorySearch(".", ext, &results); - else - { - DirectorySearch(cwdbuf.data(), ext, &results); - cwdbuf.clear(); - } - } - - // Search local data dir - if(auto datapath = al::getenv("XDG_DATA_HOME")) - { - std::string &path = *datapath; - if(path.back() != '/') - path += '/'; - path += subdir; - DirectorySearch(path.c_str(), ext, &results); - } - else if(auto homepath = al::getenv("HOME")) - { - std::string &path = *homepath; - if(path.back() == '/') - path.pop_back(); - path += "/.local/share/"; - path += subdir; - DirectorySearch(path.c_str(), ext, &results); - } - - // Search global data dirs - std::string datadirs{al::getenv("XDG_DATA_DIRS").value_or("/usr/local/share/:/usr/share/")}; - - size_t curpos{0u}; - while(curpos < datadirs.size()) - { - size_t nextpos{datadirs.find(':', curpos)}; - - std::string path{(nextpos != std::string::npos) ? - datadirs.substr(curpos, nextpos++ - curpos) : datadirs.substr(curpos)}; - curpos = nextpos; - - if(path.empty()) continue; - if(path.back() != '/') - path += '/'; - path += subdir; - - DirectorySearch(path.c_str(), ext, &results); - } - - return results; -} - -void SetRTPriority() -{ -#if defined(HAVE_PTHREAD_SETSCHEDPARAM) && !defined(__OpenBSD__) - if(RTPrioLevel > 0) - { - struct sched_param param{}; - /* Use the minimum real-time priority possible for now (on Linux this - * should be 1 for SCHED_RR). - */ - param.sched_priority = sched_get_priority_min(SCHED_RR); - int err; -#ifdef SCHED_RESET_ON_FORK - err = pthread_setschedparam(pthread_self(), SCHED_RR|SCHED_RESET_ON_FORK, ¶m); - if(err == EINVAL) -#endif - err = pthread_setschedparam(pthread_self(), SCHED_RR, ¶m); - if(err != 0) - ERR("Failed to set real-time priority for thread: %s (%d)\n", std::strerror(err), err); - } -#else - /* Real-time priority not available */ - if(RTPrioLevel > 0) - ERR("Cannot set priority level for thread\n"); -#endif -} - -#endif diff --git a/alc/hrtf.cpp b/alc/hrtf.cpp deleted file mode 100644 index 3f4ddf61..00000000 --- a/alc/hrtf.cpp +++ /dev/null @@ -1,1473 +0,0 @@ -/** - * OpenAL cross platform audio library - * Copyright (C) 2011 by Chris Robinson - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - * Or go to http://www.gnu.org/copyleft/lgpl.html - */ - -#include "config.h" - -#include "hrtf.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "albit.h" -#include "albyte.h" -#include "alcmain.h" -#include "alconfig.h" -#include "alfstream.h" -#include "almalloc.h" -#include "alnumeric.h" -#include "aloptional.h" -#include "alspan.h" -#include "core/filters/splitter.h" -#include "core/logging.h" -#include "math_defs.h" -#include "opthelpers.h" -#include "polyphase_resampler.h" - - -namespace { - -using namespace std::placeholders; - -struct HrtfEntry { - std::string mDispName; - std::string mFilename; -}; - -struct LoadedHrtf { - std::string mFilename; - std::unique_ptr mEntry; -}; - -/* Data set limits must be the same as or more flexible than those defined in - * the makemhr utility. - */ -constexpr uint MinFdCount{1}; -constexpr uint MaxFdCount{16}; - -constexpr uint MinFdDistance{50}; -constexpr uint MaxFdDistance{2500}; - -constexpr uint MinEvCount{5}; -constexpr uint MaxEvCount{181}; - -constexpr uint MinAzCount{1}; -constexpr uint MaxAzCount{255}; - -constexpr uint MaxHrirDelay{HrtfHistoryLength - 1}; - -constexpr uint HrirDelayFracBits{2}; -constexpr uint HrirDelayFracOne{1 << HrirDelayFracBits}; -constexpr uint HrirDelayFracHalf{HrirDelayFracOne >> 1}; - -static_assert(MaxHrirDelay*HrirDelayFracOne < 256, "MAX_HRIR_DELAY or DELAY_FRAC too large"); - -constexpr char magicMarker00[8]{'M','i','n','P','H','R','0','0'}; -constexpr char magicMarker01[8]{'M','i','n','P','H','R','0','1'}; -constexpr char magicMarker02[8]{'M','i','n','P','H','R','0','2'}; -constexpr char magicMarker03[8]{'M','i','n','P','H','R','0','3'}; - -/* First value for pass-through coefficients (remaining are 0), used for omni- - * directional sounds. */ -constexpr float PassthruCoeff{0.707106781187f/*sqrt(0.5)*/}; - -std::mutex LoadedHrtfLock; -al::vector LoadedHrtfs; - -std::mutex EnumeratedHrtfLock; -al::vector EnumeratedHrtfs; - - -class databuf final : public std::streambuf { - int_type underflow() override - { return traits_type::eof(); } - - pos_type seekoff(off_type offset, std::ios_base::seekdir whence, std::ios_base::openmode mode) override - { - if((mode&std::ios_base::out) || !(mode&std::ios_base::in)) - return traits_type::eof(); - - char_type *cur; - switch(whence) - { - case std::ios_base::beg: - if(offset < 0 || offset > egptr()-eback()) - return traits_type::eof(); - cur = eback() + offset; - break; - - case std::ios_base::cur: - if((offset >= 0 && offset > egptr()-gptr()) || - (offset < 0 && -offset > gptr()-eback())) - return traits_type::eof(); - cur = gptr() + offset; - break; - - case std::ios_base::end: - if(offset > 0 || -offset > egptr()-eback()) - return traits_type::eof(); - cur = egptr() + offset; - break; - - default: - return traits_type::eof(); - } - - setg(eback(), cur, egptr()); - return cur - eback(); - } - - pos_type seekpos(pos_type pos, std::ios_base::openmode mode) override - { - // Simplified version of seekoff - if((mode&std::ios_base::out) || !(mode&std::ios_base::in)) - return traits_type::eof(); - - if(pos < 0 || pos > egptr()-eback()) - return traits_type::eof(); - - setg(eback(), eback() + static_cast(pos), egptr()); - return pos; - } - -public: - databuf(const char_type *start_, const char_type *end_) noexcept - { - setg(const_cast(start_), const_cast(start_), - const_cast(end_)); - } -}; - -class idstream final : public std::istream { - databuf mStreamBuf; - -public: - idstream(const char *start_, const char *end_) - : std::istream{nullptr}, mStreamBuf{start_, end_} - { init(&mStreamBuf); } -}; - - -struct IdxBlend { uint idx; float blend; }; -/* Calculate the elevation index given the polar elevation in radians. This - * will return an index between 0 and (evcount - 1). - */ -IdxBlend CalcEvIndex(uint evcount, float ev) -{ - ev = (al::MathDefs::Pi()*0.5f + ev) * static_cast(evcount-1) / - al::MathDefs::Pi(); - uint idx{float2uint(ev)}; - - return IdxBlend{minu(idx, evcount-1), ev-static_cast(idx)}; -} - -/* Calculate the azimuth index given the polar azimuth in radians. This will - * return an index between 0 and (azcount - 1). - */ -IdxBlend CalcAzIndex(uint azcount, float az) -{ - az = (al::MathDefs::Tau()+az) * static_cast(azcount) / - al::MathDefs::Tau(); - uint idx{float2uint(az)}; - - return IdxBlend{idx%azcount, az-static_cast(idx)}; -} - -} // namespace - - -/* Calculates static HRIR coefficients and delays for the given polar elevation - * and azimuth in radians. The coefficients are normalized. - */ -void GetHrtfCoeffs(const HrtfStore *Hrtf, float elevation, float azimuth, float distance, - float spread, HrirArray &coeffs, const al::span delays) -{ - const float dirfact{1.0f - (spread / al::MathDefs::Tau())}; - - const auto *field = Hrtf->field; - const auto *field_end = field + Hrtf->fdCount-1; - size_t ebase{0}; - while(distance < field->distance && field != field_end) - { - ebase += field->evCount; - ++field; - } - - /* Calculate the elevation indices. */ - const auto elev0 = CalcEvIndex(field->evCount, elevation); - const size_t elev1_idx{minu(elev0.idx+1, field->evCount-1)}; - const size_t ir0offset{Hrtf->elev[ebase + elev0.idx].irOffset}; - const size_t ir1offset{Hrtf->elev[ebase + elev1_idx].irOffset}; - - /* Calculate azimuth indices. */ - const auto az0 = CalcAzIndex(Hrtf->elev[ebase + elev0.idx].azCount, azimuth); - const auto az1 = CalcAzIndex(Hrtf->elev[ebase + elev1_idx].azCount, azimuth); - - /* Calculate the HRIR indices to blend. */ - const size_t idx[4]{ - ir0offset + az0.idx, - ir0offset + ((az0.idx+1) % Hrtf->elev[ebase + elev0.idx].azCount), - ir1offset + az1.idx, - ir1offset + ((az1.idx+1) % Hrtf->elev[ebase + elev1_idx].azCount) - }; - - /* Calculate bilinear blending weights, attenuated according to the - * directional panning factor. - */ - const float blend[4]{ - (1.0f-elev0.blend) * (1.0f-az0.blend) * dirfact, - (1.0f-elev0.blend) * ( az0.blend) * dirfact, - ( elev0.blend) * (1.0f-az1.blend) * dirfact, - ( elev0.blend) * ( az1.blend) * dirfact - }; - - /* Calculate the blended HRIR delays. */ - float d{Hrtf->delays[idx[0]][0]*blend[0] + Hrtf->delays[idx[1]][0]*blend[1] + - Hrtf->delays[idx[2]][0]*blend[2] + Hrtf->delays[idx[3]][0]*blend[3]}; - delays[0] = fastf2u(d * float{1.0f/HrirDelayFracOne}); - d = Hrtf->delays[idx[0]][1]*blend[0] + Hrtf->delays[idx[1]][1]*blend[1] + - Hrtf->delays[idx[2]][1]*blend[2] + Hrtf->delays[idx[3]][1]*blend[3]; - delays[1] = fastf2u(d * float{1.0f/HrirDelayFracOne}); - - /* Calculate the blended HRIR coefficients. */ - float *coeffout{al::assume_aligned<16>(&coeffs[0][0])}; - coeffout[0] = PassthruCoeff * (1.0f-dirfact); - coeffout[1] = PassthruCoeff * (1.0f-dirfact); - std::fill_n(coeffout+2, size_t{HrirLength-1}*2, 0.0f); - for(size_t c{0};c < 4;c++) - { - const float *srccoeffs{al::assume_aligned<16>(Hrtf->coeffs[idx[c]][0].data())}; - const float mult{blend[c]}; - auto blend_coeffs = [mult](const float src, const float coeff) noexcept -> float - { return src*mult + coeff; }; - std::transform(srccoeffs, srccoeffs + HrirLength*2, coeffout, coeffout, blend_coeffs); - } -} - - -std::unique_ptr DirectHrtfState::Create(size_t num_chans) -{ return std::unique_ptr{new(FamCount(num_chans)) DirectHrtfState{num_chans}}; } - -void DirectHrtfState::build(const HrtfStore *Hrtf, const uint irSize, - const al::span AmbiPoints, const float (*AmbiMatrix)[MaxAmbiChannels], - const float XOverFreq, const al::span AmbiOrderHFGain) -{ - using double2 = std::array; - struct ImpulseResponse { - const HrirArray &hrir; - uint ldelay, rdelay; - }; - - const double xover_norm{double{XOverFreq} / Hrtf->sampleRate}; - for(size_t i{0};i < mChannels.size();++i) - { - const size_t order{AmbiIndex::OrderFromChannel()[i]}; - mChannels[i].mSplitter.init(static_cast(xover_norm)); - mChannels[i].mHfScale = AmbiOrderHFGain[order]; - } - - uint min_delay{HrtfHistoryLength*HrirDelayFracOne}, max_delay{0}; - al::vector impres; impres.reserve(AmbiPoints.size()); - auto calc_res = [Hrtf,&max_delay,&min_delay](const AngularPoint &pt) -> ImpulseResponse - { - auto &field = Hrtf->field[0]; - const auto elev0 = CalcEvIndex(field.evCount, pt.Elev.value); - const size_t elev1_idx{minu(elev0.idx+1, field.evCount-1)}; - const size_t ir0offset{Hrtf->elev[elev0.idx].irOffset}; - const size_t ir1offset{Hrtf->elev[elev1_idx].irOffset}; - - const auto az0 = CalcAzIndex(Hrtf->elev[elev0.idx].azCount, pt.Azim.value); - const auto az1 = CalcAzIndex(Hrtf->elev[elev1_idx].azCount, pt.Azim.value); - - const size_t idx[4]{ - ir0offset + az0.idx, - ir0offset + ((az0.idx+1) % Hrtf->elev[elev0.idx].azCount), - ir1offset + az1.idx, - ir1offset + ((az1.idx+1) % Hrtf->elev[elev1_idx].azCount) - }; - - const std::array blend{{ - (1.0-elev0.blend) * (1.0-az0.blend), - (1.0-elev0.blend) * ( az0.blend), - ( elev0.blend) * (1.0-az1.blend), - ( elev0.blend) * ( az1.blend) - }}; - - /* The largest blend factor serves as the closest HRIR. */ - const size_t irOffset{idx[std::max_element(blend.begin(), blend.end()) - blend.begin()]}; - ImpulseResponse res{Hrtf->coeffs[irOffset], - Hrtf->delays[irOffset][0], Hrtf->delays[irOffset][1]}; - - min_delay = minu(min_delay, minu(res.ldelay, res.rdelay)); - max_delay = maxu(max_delay, maxu(res.ldelay, res.rdelay)); - - return res; - }; - std::transform(AmbiPoints.begin(), AmbiPoints.end(), std::back_inserter(impres), calc_res); - auto hrir_delay_round = [](const uint d) noexcept -> uint - { return (d+HrirDelayFracHalf) >> HrirDelayFracBits; }; - - auto tmpres = al::vector>(mChannels.size()); - for(size_t c{0u};c < AmbiPoints.size();++c) - { - const HrirArray &hrir{impres[c].hrir}; - const uint ldelay{hrir_delay_round(impres[c].ldelay - min_delay)}; - const uint rdelay{hrir_delay_round(impres[c].rdelay - min_delay)}; - - for(size_t i{0u};i < mChannels.size();++i) - { - const double mult{AmbiMatrix[c][i]}; - const size_t numirs{HrirLength - maxz(ldelay, rdelay)}; - size_t lidx{ldelay}, ridx{rdelay}; - for(size_t j{0};j < numirs;++j) - { - tmpres[i][lidx++][0] += hrir[j][0] * mult; - tmpres[i][ridx++][1] += hrir[j][1] * mult; - } - } - } - impres.clear(); - - for(size_t i{0u};i < mChannels.size();++i) - { - auto copy_arr = [](const double2 &in) noexcept -> float2 - { return float2{{static_cast(in[0]), static_cast(in[1])}}; }; - std::transform(tmpres[i].cbegin(), tmpres[i].cend(), mChannels[i].mCoeffs.begin(), - copy_arr); - } - tmpres.clear(); - - max_delay -= min_delay; - const uint max_length{minu(hrir_delay_round(max_delay) + irSize, HrirLength)}; - - TRACE("Skipped delay: %.2f, new max delay: %.2f, FIR length: %u\n", - min_delay/double{HrirDelayFracOne}, max_delay/double{HrirDelayFracOne}, - max_length); - mIrSize = max_length; -} - - -namespace { - -std::unique_ptr CreateHrtfStore(uint rate, ushort irSize, - const al::span fields, - const al::span elevs, const HrirArray *coeffs, - const ubyte2 *delays, const char *filename) -{ - std::unique_ptr Hrtf; - - const size_t irCount{size_t{elevs.back().azCount} + elevs.back().irOffset}; - size_t total{sizeof(HrtfStore)}; - total = RoundUp(total, alignof(HrtfStore::Field)); /* Align for field infos */ - total += sizeof(HrtfStore::Field)*fields.size(); - total = RoundUp(total, alignof(HrtfStore::Elevation)); /* Align for elevation infos */ - total += sizeof(Hrtf->elev[0])*elevs.size(); - total = RoundUp(total, 16); /* Align for coefficients using SIMD */ - total += sizeof(Hrtf->coeffs[0])*irCount; - total += sizeof(Hrtf->delays[0])*irCount; - - Hrtf.reset(new (al_calloc(16, total)) HrtfStore{}); - if(!Hrtf) - ERR("Out of memory allocating storage for %s.\n", filename); - else - { - InitRef(Hrtf->mRef, 1u); - Hrtf->sampleRate = rate; - Hrtf->irSize = irSize; - Hrtf->fdCount = static_cast(fields.size()); - - /* Set up pointers to storage following the main HRTF struct. */ - char *base = reinterpret_cast(Hrtf.get()); - size_t offset{sizeof(HrtfStore)}; - - offset = RoundUp(offset, alignof(HrtfStore::Field)); /* Align for field infos */ - auto field_ = reinterpret_cast(base + offset); - offset += sizeof(field_[0])*fields.size(); - - offset = RoundUp(offset, alignof(HrtfStore::Elevation)); /* Align for elevation infos */ - auto elev_ = reinterpret_cast(base + offset); - offset += sizeof(elev_[0])*elevs.size(); - - offset = RoundUp(offset, 16); /* Align for coefficients using SIMD */ - auto coeffs_ = reinterpret_cast(base + offset); - offset += sizeof(coeffs_[0])*irCount; - - auto delays_ = reinterpret_cast(base + offset); - offset += sizeof(delays_[0])*irCount; - - assert(offset == total); - - /* Copy input data to storage. */ - std::copy(fields.cbegin(), fields.cend(), field_); - std::copy(elevs.cbegin(), elevs.cend(), elev_); - std::copy_n(coeffs, irCount, coeffs_); - std::copy_n(delays, irCount, delays_); - - /* Finally, assign the storage pointers. */ - Hrtf->field = field_; - Hrtf->elev = elev_; - Hrtf->coeffs = coeffs_; - Hrtf->delays = delays_; - } - - return Hrtf; -} - -void MirrorLeftHrirs(const al::span elevs, HrirArray *coeffs, - ubyte2 *delays) -{ - for(const auto &elev : elevs) - { - const ushort evoffset{elev.irOffset}; - const ushort azcount{elev.azCount}; - for(size_t j{0};j < azcount;j++) - { - const size_t lidx{evoffset + j}; - const size_t ridx{evoffset + ((azcount-j) % azcount)}; - - const size_t irSize{coeffs[ridx].size()}; - for(size_t k{0};k < irSize;k++) - coeffs[ridx][k][1] = coeffs[lidx][k][0]; - delays[ridx][1] = delays[lidx][0]; - } - } -} - - -template -inline T readle(std::istream &data) -{ - static_assert((num_bits&7) == 0, "num_bits must be a multiple of 8"); - static_assert(num_bits <= sizeof(T)*8, "num_bits is too large for the type"); - - T ret{}; - if /*constexpr*/(al::endian::native == al::endian::little) - { - if(!data.read(reinterpret_cast(&ret), num_bits/8)) - return static_cast(EOF); - } - else - { - al::byte b[sizeof(T)]{}; - if(!data.read(reinterpret_cast(b), num_bits/8)) - return static_cast(EOF); - std::reverse_copy(std::begin(b), std::end(b), reinterpret_cast(&ret)); - } - - if /*constexpr*/(std::is_signed::value && num_bits < sizeof(T)*8) - { - constexpr auto signbit = static_cast(1u << (num_bits-1)); - return static_cast((ret^signbit) - signbit); - } - return ret; -} - -template<> -inline uint8_t readle(std::istream &data) -{ return static_cast(data.get()); } - - -std::unique_ptr LoadHrtf00(std::istream &data, const char *filename) -{ - uint rate{readle(data)}; - ushort irCount{readle(data)}; - ushort irSize{readle(data)}; - ubyte evCount{readle(data)}; - if(!data || data.eof()) - { - ERR("Failed reading %s\n", filename); - return nullptr; - } - - if(irSize < MinIrLength || irSize > HrirLength) - { - ERR("Unsupported HRIR size, irSize=%d (%d to %d)\n", irSize, MinIrLength, HrirLength); - return nullptr; - } - if(evCount < MinEvCount || evCount > MaxEvCount) - { - ERR("Unsupported elevation count: evCount=%d (%d to %d)\n", - evCount, MinEvCount, MaxEvCount); - return nullptr; - } - - auto elevs = al::vector(evCount); - for(auto &elev : elevs) - elev.irOffset = readle(data); - if(!data || data.eof()) - { - ERR("Failed reading %s\n", filename); - return nullptr; - } - for(size_t i{1};i < evCount;i++) - { - if(elevs[i].irOffset <= elevs[i-1].irOffset) - { - ERR("Invalid evOffset: evOffset[%zu]=%d (last=%d)\n", i, elevs[i].irOffset, - elevs[i-1].irOffset); - return nullptr; - } - } - if(irCount <= elevs.back().irOffset) - { - ERR("Invalid evOffset: evOffset[%zu]=%d (irCount=%d)\n", - elevs.size()-1, elevs.back().irOffset, irCount); - return nullptr; - } - - for(size_t i{1};i < evCount;i++) - { - elevs[i-1].azCount = static_cast(elevs[i].irOffset - elevs[i-1].irOffset); - if(elevs[i-1].azCount < MinAzCount || elevs[i-1].azCount > MaxAzCount) - { - ERR("Unsupported azimuth count: azCount[%zd]=%d (%d to %d)\n", - i-1, elevs[i-1].azCount, MinAzCount, MaxAzCount); - return nullptr; - } - } - elevs.back().azCount = static_cast(irCount - elevs.back().irOffset); - if(elevs.back().azCount < MinAzCount || elevs.back().azCount > MaxAzCount) - { - ERR("Unsupported azimuth count: azCount[%zu]=%d (%d to %d)\n", - elevs.size()-1, elevs.back().azCount, MinAzCount, MaxAzCount); - return nullptr; - } - - auto coeffs = al::vector(irCount, HrirArray{}); - auto delays = al::vector(irCount); - for(auto &hrir : coeffs) - { - for(auto &val : al::span{hrir.data(), irSize}) - val[0] = readle(data) / 32768.0f; - } - for(auto &val : delays) - val[0] = readle(data); - if(!data || data.eof()) - { - ERR("Failed reading %s\n", filename); - return nullptr; - } - for(size_t i{0};i < irCount;i++) - { - if(delays[i][0] > MaxHrirDelay) - { - ERR("Invalid delays[%zd]: %d (%d)\n", i, delays[i][0], MaxHrirDelay); - return nullptr; - } - delays[i][0] <<= HrirDelayFracBits; - } - - /* Mirror the left ear responses to the right ear. */ - MirrorLeftHrirs({elevs.data(), elevs.size()}, coeffs.data(), delays.data()); - - const HrtfStore::Field field[1]{{0.0f, evCount}}; - return CreateHrtfStore(rate, irSize, field, {elevs.data(), elevs.size()}, coeffs.data(), - delays.data(), filename); -} - -std::unique_ptr LoadHrtf01(std::istream &data, const char *filename) -{ - uint rate{readle(data)}; - ushort irSize{readle(data)}; - ubyte evCount{readle(data)}; - if(!data || data.eof()) - { - ERR("Failed reading %s\n", filename); - return nullptr; - } - - if(irSize < MinIrLength || irSize > HrirLength) - { - ERR("Unsupported HRIR size, irSize=%d (%d to %d)\n", irSize, MinIrLength, HrirLength); - return nullptr; - } - if(evCount < MinEvCount || evCount > MaxEvCount) - { - ERR("Unsupported elevation count: evCount=%d (%d to %d)\n", - evCount, MinEvCount, MaxEvCount); - return nullptr; - } - - auto elevs = al::vector(evCount); - for(auto &elev : elevs) - elev.azCount = readle(data); - if(!data || data.eof()) - { - ERR("Failed reading %s\n", filename); - return nullptr; - } - for(size_t i{0};i < evCount;++i) - { - if(elevs[i].azCount < MinAzCount || elevs[i].azCount > MaxAzCount) - { - ERR("Unsupported azimuth count: azCount[%zd]=%d (%d to %d)\n", i, elevs[i].azCount, - MinAzCount, MaxAzCount); - return nullptr; - } - } - - elevs[0].irOffset = 0; - for(size_t i{1};i < evCount;i++) - elevs[i].irOffset = static_cast(elevs[i-1].irOffset + elevs[i-1].azCount); - const ushort irCount{static_cast(elevs.back().irOffset + elevs.back().azCount)}; - - auto coeffs = al::vector(irCount, HrirArray{}); - auto delays = al::vector(irCount); - for(auto &hrir : coeffs) - { - for(auto &val : al::span{hrir.data(), irSize}) - val[0] = readle(data) / 32768.0f; - } - for(auto &val : delays) - val[0] = readle(data); - if(!data || data.eof()) - { - ERR("Failed reading %s\n", filename); - return nullptr; - } - for(size_t i{0};i < irCount;i++) - { - if(delays[i][0] > MaxHrirDelay) - { - ERR("Invalid delays[%zd]: %d (%d)\n", i, delays[i][0], MaxHrirDelay); - return nullptr; - } - delays[i][0] <<= HrirDelayFracBits; - } - - /* Mirror the left ear responses to the right ear. */ - MirrorLeftHrirs({elevs.data(), elevs.size()}, coeffs.data(), delays.data()); - - const HrtfStore::Field field[1]{{0.0f, evCount}}; - return CreateHrtfStore(rate, irSize, field, {elevs.data(), elevs.size()}, coeffs.data(), - delays.data(), filename); -} - -std::unique_ptr LoadHrtf02(std::istream &data, const char *filename) -{ - constexpr ubyte SampleType_S16{0}; - constexpr ubyte SampleType_S24{1}; - constexpr ubyte ChanType_LeftOnly{0}; - constexpr ubyte ChanType_LeftRight{1}; - - uint rate{readle(data)}; - ubyte sampleType{readle(data)}; - ubyte channelType{readle(data)}; - ushort irSize{readle(data)}; - ubyte fdCount{readle(data)}; - if(!data || data.eof()) - { - ERR("Failed reading %s\n", filename); - return nullptr; - } - - if(sampleType > SampleType_S24) - { - ERR("Unsupported sample type: %d\n", sampleType); - return nullptr; - } - if(channelType > ChanType_LeftRight) - { - ERR("Unsupported channel type: %d\n", channelType); - return nullptr; - } - - if(irSize < MinIrLength || irSize > HrirLength) - { - ERR("Unsupported HRIR size, irSize=%d (%d to %d)\n", irSize, MinIrLength, HrirLength); - return nullptr; - } - if(fdCount < 1 || fdCount > MaxFdCount) - { - ERR("Unsupported number of field-depths: fdCount=%d (%d to %d)\n", fdCount, MinFdCount, - MaxFdCount); - return nullptr; - } - - auto fields = al::vector(fdCount); - auto elevs = al::vector{}; - for(size_t f{0};f < fdCount;f++) - { - const ushort distance{readle(data)}; - const ubyte evCount{readle(data)}; - if(!data || data.eof()) - { - ERR("Failed reading %s\n", filename); - return nullptr; - } - - if(distance < MinFdDistance || distance > MaxFdDistance) - { - ERR("Unsupported field distance[%zu]=%d (%d to %d millimeters)\n", f, distance, - MinFdDistance, MaxFdDistance); - return nullptr; - } - if(evCount < MinEvCount || evCount > MaxEvCount) - { - ERR("Unsupported elevation count: evCount[%zu]=%d (%d to %d)\n", f, evCount, - MinEvCount, MaxEvCount); - return nullptr; - } - - fields[f].distance = distance / 1000.0f; - fields[f].evCount = evCount; - if(f > 0 && fields[f].distance <= fields[f-1].distance) - { - ERR("Field distance[%zu] is not after previous (%f > %f)\n", f, fields[f].distance, - fields[f-1].distance); - return nullptr; - } - - const size_t ebase{elevs.size()}; - elevs.resize(ebase + evCount); - for(auto &elev : al::span(elevs.data()+ebase, evCount)) - elev.azCount = readle(data); - if(!data || data.eof()) - { - ERR("Failed reading %s\n", filename); - return nullptr; - } - - for(size_t e{0};e < evCount;e++) - { - if(elevs[ebase+e].azCount < MinAzCount || elevs[ebase+e].azCount > MaxAzCount) - { - ERR("Unsupported azimuth count: azCount[%zu][%zu]=%d (%d to %d)\n", f, e, - elevs[ebase+e].azCount, MinAzCount, MaxAzCount); - return nullptr; - } - } - } - - elevs[0].irOffset = 0; - std::partial_sum(elevs.cbegin(), elevs.cend(), elevs.begin(), - [](const HrtfStore::Elevation &last, const HrtfStore::Elevation &cur) - -> HrtfStore::Elevation - { - return HrtfStore::Elevation{cur.azCount, - static_cast(last.azCount + last.irOffset)}; - }); - const auto irTotal = static_cast(elevs.back().azCount + elevs.back().irOffset); - - auto coeffs = al::vector(irTotal, HrirArray{}); - auto delays = al::vector(irTotal); - if(channelType == ChanType_LeftOnly) - { - if(sampleType == SampleType_S16) - { - for(auto &hrir : coeffs) - { - for(auto &val : al::span{hrir.data(), irSize}) - val[0] = readle(data) / 32768.0f; - } - } - else if(sampleType == SampleType_S24) - { - for(auto &hrir : coeffs) - { - for(auto &val : al::span{hrir.data(), irSize}) - val[0] = static_cast(readle(data)) / 8388608.0f; - } - } - for(auto &val : delays) - val[0] = readle(data); - if(!data || data.eof()) - { - ERR("Failed reading %s\n", filename); - return nullptr; - } - for(size_t i{0};i < irTotal;++i) - { - if(delays[i][0] > MaxHrirDelay) - { - ERR("Invalid delays[%zu][0]: %d (%d)\n", i, delays[i][0], MaxHrirDelay); - return nullptr; - } - delays[i][0] <<= HrirDelayFracBits; - } - - /* Mirror the left ear responses to the right ear. */ - MirrorLeftHrirs({elevs.data(), elevs.size()}, coeffs.data(), delays.data()); - } - else if(channelType == ChanType_LeftRight) - { - if(sampleType == SampleType_S16) - { - for(auto &hrir : coeffs) - { - for(auto &val : al::span{hrir.data(), irSize}) - { - val[0] = readle(data) / 32768.0f; - val[1] = readle(data) / 32768.0f; - } - } - } - else if(sampleType == SampleType_S24) - { - for(auto &hrir : coeffs) - { - for(auto &val : al::span{hrir.data(), irSize}) - { - val[0] = static_cast(readle(data)) / 8388608.0f; - val[1] = static_cast(readle(data)) / 8388608.0f; - } - } - } - for(auto &val : delays) - { - val[0] = readle(data); - val[1] = readle(data); - } - if(!data || data.eof()) - { - ERR("Failed reading %s\n", filename); - return nullptr; - } - - for(size_t i{0};i < irTotal;++i) - { - if(delays[i][0] > MaxHrirDelay) - { - ERR("Invalid delays[%zu][0]: %d (%d)\n", i, delays[i][0], MaxHrirDelay); - return nullptr; - } - if(delays[i][1] > MaxHrirDelay) - { - ERR("Invalid delays[%zu][1]: %d (%d)\n", i, delays[i][1], MaxHrirDelay); - return nullptr; - } - delays[i][0] <<= HrirDelayFracBits; - delays[i][1] <<= HrirDelayFracBits; - } - } - - if(fdCount > 1) - { - auto fields_ = al::vector(fields.size()); - auto elevs_ = al::vector(elevs.size()); - auto coeffs_ = al::vector(coeffs.size()); - auto delays_ = al::vector(delays.size()); - - /* Simple reverse for the per-field elements. */ - std::reverse_copy(fields.cbegin(), fields.cend(), fields_.begin()); - - /* Each field has a group of elevations, which each have an azimuth - * count. Reverse the order of the groups, keeping the relative order - * of per-group azimuth counts. - */ - auto elevs__end = elevs_.end(); - auto copy_azs = [&elevs,&elevs__end](const ptrdiff_t ebase, const HrtfStore::Field &field) - -> ptrdiff_t - { - auto elevs_src = elevs.begin()+ebase; - elevs__end = std::copy_backward(elevs_src, elevs_src+field.evCount, elevs__end); - return ebase + field.evCount; - }; - (void)std::accumulate(fields.cbegin(), fields.cend(), ptrdiff_t{0}, copy_azs); - assert(elevs_.begin() == elevs__end); - - /* Reestablish the IR offset for each elevation index, given the new - * ordering of elevations. - */ - elevs_[0].irOffset = 0; - std::partial_sum(elevs_.cbegin(), elevs_.cend(), elevs_.begin(), - [](const HrtfStore::Elevation &last, const HrtfStore::Elevation &cur) - -> HrtfStore::Elevation - { - return HrtfStore::Elevation{cur.azCount, - static_cast(last.azCount + last.irOffset)}; - }); - - /* Reverse the order of each field's group of IRs. */ - auto coeffs_end = coeffs_.end(); - auto delays_end = delays_.end(); - auto copy_irs = [&elevs,&coeffs,&delays,&coeffs_end,&delays_end]( - const ptrdiff_t ebase, const HrtfStore::Field &field) -> ptrdiff_t - { - auto accum_az = [](int count, const HrtfStore::Elevation &elev) noexcept -> int - { return count + elev.azCount; }; - const auto elevs_mid = elevs.cbegin() + ebase; - const auto elevs_end = elevs_mid + field.evCount; - const int abase{std::accumulate(elevs.cbegin(), elevs_mid, 0, accum_az)}; - const int num_azs{std::accumulate(elevs_mid, elevs_end, 0, accum_az)}; - - coeffs_end = std::copy_backward(coeffs.cbegin() + abase, - coeffs.cbegin() + (abase+num_azs), coeffs_end); - delays_end = std::copy_backward(delays.cbegin() + abase, - delays.cbegin() + (abase+num_azs), delays_end); - - return ebase + field.evCount; - }; - (void)std::accumulate(fields.cbegin(), fields.cend(), ptrdiff_t{0}, copy_irs); - assert(coeffs_.begin() == coeffs_end); - assert(delays_.begin() == delays_end); - - fields = std::move(fields_); - elevs = std::move(elevs_); - coeffs = std::move(coeffs_); - delays = std::move(delays_); - } - - return CreateHrtfStore(rate, irSize, {fields.data(), fields.size()}, - {elevs.data(), elevs.size()}, coeffs.data(), delays.data(), filename); -} - -std::unique_ptr LoadHrtf03(std::istream &data, const char *filename) -{ - constexpr ubyte ChanType_LeftOnly{0}; - constexpr ubyte ChanType_LeftRight{1}; - - uint rate{readle(data)}; - ubyte channelType{readle(data)}; - ushort irSize{readle(data)}; - ubyte fdCount{readle(data)}; - if(!data || data.eof()) - { - ERR("Failed reading %s\n", filename); - return nullptr; - } - - if(channelType > ChanType_LeftRight) - { - ERR("Unsupported channel type: %d\n", channelType); - return nullptr; - } - - if(irSize < MinIrLength || irSize > HrirLength) - { - ERR("Unsupported HRIR size, irSize=%d (%d to %d)\n", irSize, MinIrLength, HrirLength); - return nullptr; - } - if(fdCount < 1 || fdCount > MaxFdCount) - { - ERR("Unsupported number of field-depths: fdCount=%d (%d to %d)\n", fdCount, MinFdCount, - MaxFdCount); - return nullptr; - } - - auto fields = al::vector(fdCount); - auto elevs = al::vector{}; - for(size_t f{0};f < fdCount;f++) - { - const ushort distance{readle(data)}; - const ubyte evCount{readle(data)}; - if(!data || data.eof()) - { - ERR("Failed reading %s\n", filename); - return nullptr; - } - - if(distance < MinFdDistance || distance > MaxFdDistance) - { - ERR("Unsupported field distance[%zu]=%d (%d to %d millimeters)\n", f, distance, - MinFdDistance, MaxFdDistance); - return nullptr; - } - if(evCount < MinEvCount || evCount > MaxEvCount) - { - ERR("Unsupported elevation count: evCount[%zu]=%d (%d to %d)\n", f, evCount, - MinEvCount, MaxEvCount); - return nullptr; - } - - fields[f].distance = distance / 1000.0f; - fields[f].evCount = evCount; - if(f > 0 && fields[f].distance > fields[f-1].distance) - { - ERR("Field distance[%zu] is not before previous (%f <= %f)\n", f, fields[f].distance, - fields[f-1].distance); - return nullptr; - } - - const size_t ebase{elevs.size()}; - elevs.resize(ebase + evCount); - for(auto &elev : al::span(elevs.data()+ebase, evCount)) - elev.azCount = readle(data); - if(!data || data.eof()) - { - ERR("Failed reading %s\n", filename); - return nullptr; - } - - for(size_t e{0};e < evCount;e++) - { - if(elevs[ebase+e].azCount < MinAzCount || elevs[ebase+e].azCount > MaxAzCount) - { - ERR("Unsupported azimuth count: azCount[%zu][%zu]=%d (%d to %d)\n", f, e, - elevs[ebase+e].azCount, MinAzCount, MaxAzCount); - return nullptr; - } - } - } - - elevs[0].irOffset = 0; - std::partial_sum(elevs.cbegin(), elevs.cend(), elevs.begin(), - [](const HrtfStore::Elevation &last, const HrtfStore::Elevation &cur) - -> HrtfStore::Elevation - { - return HrtfStore::Elevation{cur.azCount, - static_cast(last.azCount + last.irOffset)}; - }); - const auto irTotal = static_cast(elevs.back().azCount + elevs.back().irOffset); - - auto coeffs = al::vector(irTotal, HrirArray{}); - auto delays = al::vector(irTotal); - if(channelType == ChanType_LeftOnly) - { - for(auto &hrir : coeffs) - { - for(auto &val : al::span{hrir.data(), irSize}) - val[0] = static_cast(readle(data)) / 8388608.0f; - } - for(auto &val : delays) - val[0] = readle(data); - if(!data || data.eof()) - { - ERR("Failed reading %s\n", filename); - return nullptr; - } - for(size_t i{0};i < irTotal;++i) - { - if(delays[i][0] > MaxHrirDelay<{hrir.data(), irSize}) - { - val[0] = static_cast(readle(data)) / 8388608.0f; - val[1] = static_cast(readle(data)) / 8388608.0f; - } - } - for(auto &val : delays) - { - val[0] = readle(data); - val[1] = readle(data); - } - if(!data || data.eof()) - { - ERR("Failed reading %s\n", filename); - return nullptr; - } - - for(size_t i{0};i < irTotal;++i) - { - if(delays[i][0] > MaxHrirDelay< MaxHrirDelay< bool { return name == entry.mDispName; }; - auto &enum_names = EnumeratedHrtfs; - return std::find_if(enum_names.cbegin(), enum_names.cend(), match_name) != enum_names.cend(); -} - -void AddFileEntry(const std::string &filename) -{ - /* Check if this file has already been enumerated. */ - auto enum_iter = std::find_if(EnumeratedHrtfs.cbegin(), EnumeratedHrtfs.cend(), - [&filename](const HrtfEntry &entry) -> bool - { return entry.mFilename == filename; }); - if(enum_iter != EnumeratedHrtfs.cend()) - { - TRACE("Skipping duplicate file entry %s\n", filename.c_str()); - return; - } - - /* TODO: Get a human-readable name from the HRTF data (possibly coming in a - * format update). */ - size_t namepos{filename.find_last_of('/')+1}; - if(!namepos) namepos = filename.find_last_of('\\')+1; - - size_t extpos{filename.find_last_of('.')}; - if(extpos <= namepos) extpos = std::string::npos; - - const std::string basename{(extpos == std::string::npos) ? - filename.substr(namepos) : filename.substr(namepos, extpos-namepos)}; - std::string newname{basename}; - int count{1}; - while(checkName(newname)) - { - newname = basename; - newname += " #"; - newname += std::to_string(++count); - } - EnumeratedHrtfs.emplace_back(HrtfEntry{newname, filename}); - const HrtfEntry &entry = EnumeratedHrtfs.back(); - - TRACE("Adding file entry \"%s\"\n", entry.mFilename.c_str()); -} - -/* Unfortunate that we have to duplicate AddFileEntry to take a memory buffer - * for input instead of opening the given filename. - */ -void AddBuiltInEntry(const std::string &dispname, uint residx) -{ - const std::string filename{'!'+std::to_string(residx)+'_'+dispname}; - - auto enum_iter = std::find_if(EnumeratedHrtfs.cbegin(), EnumeratedHrtfs.cend(), - [&filename](const HrtfEntry &entry) -> bool - { return entry.mFilename == filename; }); - if(enum_iter != EnumeratedHrtfs.cend()) - { - TRACE("Skipping duplicate file entry %s\n", filename.c_str()); - return; - } - - /* TODO: Get a human-readable name from the HRTF data (possibly coming in a - * format update). */ - - std::string newname{dispname}; - int count{1}; - while(checkName(newname)) - { - newname = dispname; - newname += " #"; - newname += std::to_string(++count); - } - EnumeratedHrtfs.emplace_back(HrtfEntry{newname, filename}); - const HrtfEntry &entry = EnumeratedHrtfs.back(); - - TRACE("Adding built-in entry \"%s\"\n", entry.mFilename.c_str()); -} - - -#define IDR_DEFAULT_HRTF_MHR 1 - -#ifndef ALSOFT_EMBED_HRTF_DATA - -al::span GetResource(int /*name*/) -{ return {}; } - -#else - -#include "hrtf_default.h" - -al::span GetResource(int name) -{ - if(name == IDR_DEFAULT_HRTF_MHR) - return {reinterpret_cast(hrtf_default), sizeof(hrtf_default)}; - return {}; -} -#endif - -} // namespace - - -al::vector EnumerateHrtf(const char *devname) -{ - std::lock_guard _{EnumeratedHrtfLock}; - EnumeratedHrtfs.clear(); - - bool usedefaults{true}; - if(auto pathopt = ConfigValueStr(devname, nullptr, "hrtf-paths")) - { - const char *pathlist{pathopt->c_str()}; - while(pathlist && *pathlist) - { - const char *next, *end; - - while(isspace(*pathlist) || *pathlist == ',') - pathlist++; - if(*pathlist == '\0') - continue; - - next = strchr(pathlist, ','); - if(next) - end = next++; - else - { - end = pathlist + strlen(pathlist); - usedefaults = false; - } - - while(end != pathlist && isspace(*(end-1))) - --end; - if(end != pathlist) - { - const std::string pname{pathlist, end}; - for(const auto &fname : SearchDataFiles(".mhr", pname.c_str())) - AddFileEntry(fname); - } - - pathlist = next; - } - } - - if(usedefaults) - { - for(const auto &fname : SearchDataFiles(".mhr", "openal/hrtf")) - AddFileEntry(fname); - - if(!GetResource(IDR_DEFAULT_HRTF_MHR).empty()) - AddBuiltInEntry("Built-In HRTF", IDR_DEFAULT_HRTF_MHR); - } - - al::vector list; - list.reserve(EnumeratedHrtfs.size()); - for(auto &entry : EnumeratedHrtfs) - list.emplace_back(entry.mDispName); - - if(auto defhrtfopt = ConfigValueStr(devname, nullptr, "default-hrtf")) - { - auto iter = std::find(list.begin(), list.end(), *defhrtfopt); - if(iter == list.end()) - WARN("Failed to find default HRTF \"%s\"\n", defhrtfopt->c_str()); - else if(iter != list.begin()) - std::rotate(list.begin(), iter, iter+1); - } - - return list; -} - -HrtfStorePtr GetLoadedHrtf(const std::string &name, const uint devrate) -{ - std::lock_guard _{EnumeratedHrtfLock}; - auto entry_iter = std::find_if(EnumeratedHrtfs.cbegin(), EnumeratedHrtfs.cend(), - [&name](const HrtfEntry &entry) -> bool { return entry.mDispName == name; }); - if(entry_iter == EnumeratedHrtfs.cend()) - return nullptr; - const std::string &fname = entry_iter->mFilename; - - std::lock_guard __{LoadedHrtfLock}; - auto hrtf_lt_fname = [](LoadedHrtf &hrtf, const std::string &filename) -> bool - { return hrtf.mFilename < filename; }; - auto handle = std::lower_bound(LoadedHrtfs.begin(), LoadedHrtfs.end(), fname, hrtf_lt_fname); - while(handle != LoadedHrtfs.end() && handle->mFilename == fname) - { - HrtfStore *hrtf{handle->mEntry.get()}; - if(hrtf && hrtf->sampleRate == devrate) - { - hrtf->add_ref(); - return HrtfStorePtr{hrtf}; - } - ++handle; - } - - std::unique_ptr stream; - int residx{}; - char ch{}; - if(sscanf(fname.c_str(), "!%d%c", &residx, &ch) == 2 && ch == '_') - { - TRACE("Loading %s...\n", fname.c_str()); - al::span res{GetResource(residx)}; - if(res.empty()) - { - ERR("Could not get resource %u, %s\n", residx, name.c_str()); - return nullptr; - } - stream = std::make_unique(res.begin(), res.end()); - } - else - { - TRACE("Loading %s...\n", fname.c_str()); - auto fstr = std::make_unique(fname.c_str(), std::ios::binary); - if(!fstr->is_open()) - { - ERR("Could not open %s\n", fname.c_str()); - return nullptr; - } - stream = std::move(fstr); - } - - std::unique_ptr hrtf; - char magic[sizeof(magicMarker03)]; - stream->read(magic, sizeof(magic)); - if(stream->gcount() < static_cast(sizeof(magicMarker03))) - ERR("%s data is too short (%zu bytes)\n", name.c_str(), stream->gcount()); - else if(memcmp(magic, magicMarker03, sizeof(magicMarker03)) == 0) - { - TRACE("Detected data set format v3\n"); - hrtf = LoadHrtf03(*stream, name.c_str()); - } - else if(memcmp(magic, magicMarker02, sizeof(magicMarker02)) == 0) - { - TRACE("Detected data set format v2\n"); - hrtf = LoadHrtf02(*stream, name.c_str()); - } - else if(memcmp(magic, magicMarker01, sizeof(magicMarker01)) == 0) - { - TRACE("Detected data set format v1\n"); - hrtf = LoadHrtf01(*stream, name.c_str()); - } - else if(memcmp(magic, magicMarker00, sizeof(magicMarker00)) == 0) - { - TRACE("Detected data set format v0\n"); - hrtf = LoadHrtf00(*stream, name.c_str()); - } - else - ERR("Invalid header in %s: \"%.8s\"\n", name.c_str(), magic); - stream.reset(); - - if(!hrtf) - { - ERR("Failed to load %s\n", name.c_str()); - return nullptr; - } - - if(hrtf->sampleRate != devrate) - { - TRACE("Resampling HRTF %s (%uhz -> %uhz)\n", name.c_str(), hrtf->sampleRate, devrate); - - /* Calculate the last elevation's index and get the total IR count. */ - const size_t lastEv{std::accumulate(hrtf->field, hrtf->field+hrtf->fdCount, size_t{0}, - [](const size_t curval, const HrtfStore::Field &field) noexcept -> size_t - { return curval + field.evCount; } - ) - 1}; - const size_t irCount{size_t{hrtf->elev[lastEv].irOffset} + hrtf->elev[lastEv].azCount}; - - /* Resample all the IRs. */ - std::array,2> inout; - PPhaseResampler rs; - rs.init(hrtf->sampleRate, devrate); - for(size_t i{0};i < irCount;++i) - { - HrirArray &coeffs = const_cast(hrtf->coeffs[i]); - for(size_t j{0};j < 2;++j) - { - std::transform(coeffs.cbegin(), coeffs.cend(), inout[0].begin(), - [j](const float2 &in) noexcept -> double { return in[j]; }); - rs.process(HrirLength, inout[0].data(), HrirLength, inout[1].data()); - for(size_t k{0};k < HrirLength;++k) - coeffs[k][j] = static_cast(inout[1][k]); - } - } - rs = {}; - - /* Scale the delays for the new sample rate. */ - float max_delay{0.0f}; - auto new_delays = al::vector(irCount); - const float rate_scale{static_cast(devrate)/static_cast(hrtf->sampleRate)}; - for(size_t i{0};i < irCount;++i) - { - for(size_t j{0};j < 2;++j) - { - const float new_delay{std::round(hrtf->delays[i][j] * rate_scale) / - float{HrirDelayFracOne}}; - max_delay = maxf(max_delay, new_delay); - new_delays[i][j] = new_delay; - } - } - - /* If the new delays exceed the max, scale it down to fit (essentially - * shrinking the head radius; not ideal but better than a per-delay - * clamp). - */ - float delay_scale{HrirDelayFracOne}; - if(max_delay > MaxHrirDelay) - { - WARN("Resampled delay exceeds max (%.2f > %d)\n", max_delay, MaxHrirDelay); - delay_scale *= float{MaxHrirDelay} / max_delay; - } - - for(size_t i{0};i < irCount;++i) - { - ubyte2 &delays = const_cast(hrtf->delays[i]); - for(size_t j{0};j < 2;++j) - delays[j] = static_cast(float2int(new_delays[i][j]*delay_scale + 0.5f)); - } - - /* Scale the IR size for the new sample rate and update the stored - * sample rate. - */ - const float newIrSize{std::round(static_cast(hrtf->irSize) * rate_scale)}; - hrtf->irSize = static_cast(minf(HrirLength, newIrSize)); - hrtf->sampleRate = devrate; - } - - TRACE("Loaded HRTF %s for sample rate %uhz, %u-sample filter\n", name.c_str(), - hrtf->sampleRate, hrtf->irSize); - handle = LoadedHrtfs.emplace(handle, LoadedHrtf{fname, std::move(hrtf)}); - - return HrtfStorePtr{handle->mEntry.get()}; -} - - -void HrtfStore::add_ref() -{ - auto ref = IncrementRef(mRef); - TRACE("HrtfStore %p increasing refcount to %u\n", decltype(std::declval()){this}, ref); -} - -void HrtfStore::release() -{ - auto ref = DecrementRef(mRef); - TRACE("HrtfStore %p decreasing refcount to %u\n", decltype(std::declval()){this}, ref); - if(ref == 0) - { - std::lock_guard _{LoadedHrtfLock}; - - /* Go through and remove all unused HRTFs. */ - auto remove_unused = [](LoadedHrtf &hrtf) -> bool - { - HrtfStore *entry{hrtf.mEntry.get()}; - if(entry && ReadRef(entry->mRef) == 0) - { - TRACE("Unloading unused HRTF %s\n", hrtf.mFilename.data()); - hrtf.mEntry = nullptr; - return true; - } - return false; - }; - auto iter = std::remove_if(LoadedHrtfs.begin(), LoadedHrtfs.end(), remove_unused); - LoadedHrtfs.erase(iter, LoadedHrtfs.end()); - } -} diff --git a/alc/hrtf.h b/alc/hrtf.h deleted file mode 100644 index a46b64e2..00000000 --- a/alc/hrtf.h +++ /dev/null @@ -1,90 +0,0 @@ -#ifndef ALC_HRTF_H -#define ALC_HRTF_H - -#include -#include -#include -#include - -#include "almalloc.h" -#include "alspan.h" -#include "atomic.h" -#include "core/ambidefs.h" -#include "core/bufferline.h" -#include "core/filters/splitter.h" -#include "core/mixer/hrtfdefs.h" -#include "intrusive_ptr.h" -#include "vector.h" - - -struct HrtfStore { - RefCount mRef; - - uint sampleRate; - uint irSize; - - struct Field { - float distance; - ubyte evCount; - }; - /* NOTE: Fields are stored *backwards*. field[0] is the farthest field, and - * field[fdCount-1] is the nearest. - */ - uint fdCount; - const Field *field; - - struct Elevation { - ushort azCount; - ushort irOffset; - }; - Elevation *elev; - const HrirArray *coeffs; - const ubyte2 *delays; - - void add_ref(); - void release(); - - DEF_PLACE_NEWDEL() -}; -using HrtfStorePtr = al::intrusive_ptr; - - -struct EvRadians { float value; }; -struct AzRadians { float value; }; -struct AngularPoint { - EvRadians Elev; - AzRadians Azim; -}; - - -struct DirectHrtfState { - std::array mTemp; - - /* HRTF filter state for dry buffer content */ - uint mIrSize{0}; - al::FlexArray mChannels; - - DirectHrtfState(size_t numchans) : mChannels{numchans} { } - /** - * Produces HRTF filter coefficients for decoding B-Format, given a set of - * virtual speaker positions, a matching decoding matrix, and per-order - * high-frequency gains for the decoder. The calculated impulse responses - * are ordered and scaled according to the matrix input. - */ - void build(const HrtfStore *Hrtf, const uint irSize, - const al::span AmbiPoints, const float (*AmbiMatrix)[MaxAmbiChannels], - const float XOverFreq, const al::span AmbiOrderHFGain); - - static std::unique_ptr Create(size_t num_chans); - - DEF_FAM_NEWDEL(DirectHrtfState, mChannels) -}; - - -al::vector EnumerateHrtf(const char *devname); -HrtfStorePtr GetLoadedHrtf(const std::string &name, const uint devrate); - -void GetHrtfCoeffs(const HrtfStore *Hrtf, float elevation, float azimuth, float distance, - float spread, HrirArray &coeffs, const al::span delays); - -#endif /* ALC_HRTF_H */ diff --git a/alc/inprogext.h b/alc/inprogext.h deleted file mode 100644 index ea27a531..00000000 --- a/alc/inprogext.h +++ /dev/null @@ -1,73 +0,0 @@ -#ifndef INPROGEXT_H -#define INPROGEXT_H - -#include "AL/al.h" -#include "AL/alc.h" -#include "AL/alext.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#ifndef AL_SOFT_map_buffer -#define AL_SOFT_map_buffer 1 -typedef unsigned int ALbitfieldSOFT; -#define AL_MAP_READ_BIT_SOFT 0x00000001 -#define AL_MAP_WRITE_BIT_SOFT 0x00000002 -#define AL_MAP_PERSISTENT_BIT_SOFT 0x00000004 -#define AL_PRESERVE_DATA_BIT_SOFT 0x00000008 -typedef void (AL_APIENTRY*LPALBUFFERSTORAGESOFT)(ALuint buffer, ALenum format, const ALvoid *data, ALsizei size, ALsizei freq, ALbitfieldSOFT flags); -typedef void* (AL_APIENTRY*LPALMAPBUFFERSOFT)(ALuint buffer, ALsizei offset, ALsizei length, ALbitfieldSOFT access); -typedef void (AL_APIENTRY*LPALUNMAPBUFFERSOFT)(ALuint buffer); -typedef void (AL_APIENTRY*LPALFLUSHMAPPEDBUFFERSOFT)(ALuint buffer, ALsizei offset, ALsizei length); -#ifdef AL_ALEXT_PROTOTYPES -AL_API void AL_APIENTRY alBufferStorageSOFT(ALuint buffer, ALenum format, const ALvoid *data, ALsizei size, ALsizei freq, ALbitfieldSOFT flags); -AL_API void* AL_APIENTRY alMapBufferSOFT(ALuint buffer, ALsizei offset, ALsizei length, ALbitfieldSOFT access); -AL_API void AL_APIENTRY alUnmapBufferSOFT(ALuint buffer); -AL_API void AL_APIENTRY alFlushMappedBufferSOFT(ALuint buffer, ALsizei offset, ALsizei length); -#endif -#endif - -#ifndef AL_SOFT_callback_buffer -#define AL_SOFT_callback_buffer -#define AL_BUFFER_CALLBACK_FUNCTION_SOFT 0x19A0 -#define AL_BUFFER_CALLBACK_USER_PARAM_SOFT 0x19A1 -typedef ALsizei (AL_APIENTRY*LPALBUFFERCALLBACKTYPESOFT)(ALvoid *userptr, ALvoid *sampledata, ALsizei numsamples); -typedef void (AL_APIENTRY*LPALBUFFERCALLBACKSOFT)(ALuint buffer, ALenum format, ALsizei freq, LPALBUFFERCALLBACKTYPESOFT callback, ALvoid *userptr, ALbitfieldSOFT flags); -typedef void (AL_APIENTRY*LPALGETBUFFERPTRSOFT)(ALuint buffer, ALenum param, ALvoid **value); -typedef void (AL_APIENTRY*LPALGETBUFFER3PTRSOFT)(ALuint buffer, ALenum param, ALvoid **value1, ALvoid **value2, ALvoid **value3); -typedef void (AL_APIENTRY*LPALGETBUFFERPTRVSOFT)(ALuint buffer, ALenum param, ALvoid **values); -#ifdef AL_ALEXT_PROTOTYPES -AL_API void AL_APIENTRY alBufferCallbackSOFT(ALuint buffer, ALenum format, ALsizei freq, LPALBUFFERCALLBACKTYPESOFT callback, ALvoid *userptr, ALbitfieldSOFT flags); -AL_API void AL_APIENTRY alGetBufferPtrSOFT(ALuint buffer, ALenum param, ALvoid **ptr); -AL_API void AL_APIENTRY alGetBuffer3PtrSOFT(ALuint buffer, ALenum param, ALvoid **ptr0, ALvoid **ptr1, ALvoid **ptr2); -AL_API void AL_APIENTRY alGetBufferPtrvSOFT(ALuint buffer, ALenum param, ALvoid **ptr); -#endif -#endif - -#ifndef AL_SOFT_bformat_hoa -#define AL_SOFT_bformat_hoa -#define AL_UNPACK_AMBISONIC_ORDER_SOFT 0x199D -#endif - -#ifndef AL_SOFT_convolution_reverb -#define AL_SOFT_convolution_reverb -#define AL_EFFECT_CONVOLUTION_REVERB_SOFT 0xA000 -#define AL_EFFECTSLOT_STATE_SOFT 0x199D -typedef void (AL_APIENTRY*LPALAUXILIARYEFFECTSLOTPLAYSOFT)(ALuint slotid); -typedef void (AL_APIENTRY*LPALAUXILIARYEFFECTSLOTPLAYVSOFT)(ALsizei n, const ALuint *slotids); -typedef void (AL_APIENTRY*LPALAUXILIARYEFFECTSLOTSTOPSOFT)(ALuint slotid); -typedef void (AL_APIENTRY*LPALAUXILIARYEFFECTSLOTSTOPVSOFT)(ALsizei n, const ALuint *slotids); -#ifdef AL_ALEXT_PROTOTYPES -AL_API void AL_APIENTRY alAuxiliaryEffectSlotPlaySOFT(ALuint slotid); -AL_API void AL_APIENTRY alAuxiliaryEffectSlotPlayvSOFT(ALsizei n, const ALuint *slotids); -AL_API void AL_APIENTRY alAuxiliaryEffectSlotStopSOFT(ALuint slotid); -AL_API void AL_APIENTRY alAuxiliaryEffectSlotStopvSOFT(ALsizei n, const ALuint *slotids); -#endif -#endif - -#ifdef __cplusplus -} /* extern "C" */ -#endif - -#endif /* INPROGEXT_H */ diff --git a/alc/panning.cpp b/alc/panning.cpp deleted file mode 100644 index 1ac3bb04..00000000 --- a/alc/panning.cpp +++ /dev/null @@ -1,1210 +0,0 @@ -/** - * OpenAL cross platform audio library - * Copyright (C) 1999-2010 by authors. - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - * Or go to http://www.gnu.org/copyleft/lgpl.html - */ - -#include "config.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "AL/al.h" -#include "AL/alc.h" -#include "AL/alext.h" - -#include "al/auxeffectslot.h" -#include "alcmain.h" -#include "alconfig.h" -#include "alcontext.h" -#include "almalloc.h" -#include "alnumeric.h" -#include "aloptional.h" -#include "alspan.h" -#include "alstring.h" -#include "alu.h" -#include "bformatdec.h" -#include "core/ambdec.h" -#include "core/ambidefs.h" -#include "core/bs2b.h" -#include "core/devformat.h" -#include "core/logging.h" -#include "core/uhjfilter.h" -#include "front_stablizer.h" -#include "hrtf.h" -#include "math_defs.h" -#include "opthelpers.h" - - -namespace { - -using namespace std::placeholders; -using std::chrono::seconds; -using std::chrono::nanoseconds; - -inline const char *GetLabelFromChannel(Channel channel) -{ - switch(channel) - { - case FrontLeft: return "front-left"; - case FrontRight: return "front-right"; - case FrontCenter: return "front-center"; - case LFE: return "lfe"; - case BackLeft: return "back-left"; - case BackRight: return "back-right"; - case BackCenter: return "back-center"; - case SideLeft: return "side-left"; - case SideRight: return "side-right"; - - case TopFrontLeft: return "top-front-left"; - case TopFrontCenter: return "top-front-center"; - case TopFrontRight: return "top-front-right"; - case TopCenter: return "top-center"; - case TopBackLeft: return "top-back-left"; - case TopBackCenter: return "top-back-center"; - case TopBackRight: return "top-back-right"; - - case MaxChannels: break; - } - return "(unknown)"; -} - - -std::unique_ptr CreateStablizer(const size_t outchans, const uint srate) -{ - auto stablizer = FrontStablizer::Create(outchans); - for(auto &buf : stablizer->DelayBuf) - std::fill(buf.begin(), buf.end(), 0.0f); - - /* Initialize band-splitting filter for the mid signal, with a crossover at - * 5khz (could be higher). - */ - stablizer->MidFilter.init(5000.0f / static_cast(srate)); - - return stablizer; -} - -void AllocChannels(ALCdevice *device, const size_t main_chans, const size_t real_chans) -{ - TRACE("Channel config, Main: %zu, Real: %zu\n", main_chans, real_chans); - - /* Allocate extra channels for any post-filter output. */ - const size_t num_chans{main_chans + real_chans}; - - TRACE("Allocating %zu channels, %zu bytes\n", num_chans, - num_chans*sizeof(device->MixBuffer[0])); - device->MixBuffer.resize(num_chans); - al::span buffer{device->MixBuffer}; - - device->Dry.Buffer = buffer.first(main_chans); - buffer = buffer.subspan(main_chans); - if(real_chans != 0) - { - device->RealOut.Buffer = buffer.first(real_chans); - buffer = buffer.subspan(real_chans); - } - else - device->RealOut.Buffer = device->Dry.Buffer; -} - - -struct ChannelMap { - Channel ChanName; - float Config[MaxAmbi2DChannels]; -}; - -bool MakeSpeakerMap(ALCdevice *device, const AmbDecConf *conf, uint (&speakermap)[MAX_OUTPUT_CHANNELS]) -{ - auto map_spkr = [device](const AmbDecConf::SpeakerConf &speaker) -> uint - { - /* NOTE: AmbDec does not define any standard speaker names, however - * for this to work we have to by able to find the output channel - * the speaker definition corresponds to. Therefore, OpenAL Soft - * requires these channel labels to be recognized: - * - * LF = Front left - * RF = Front right - * LS = Side left - * RS = Side right - * LB = Back left - * RB = Back right - * CE = Front center - * CB = Back center - * - * Additionally, surround51 will acknowledge back speakers for side - * channels, and surround51rear will acknowledge side speakers for - * back channels, to avoid issues with an ambdec expecting 5.1 to - * use the side channels when the device is configured for back, - * and vice-versa. - */ - Channel ch{}; - if(speaker.Name == "LF") - ch = FrontLeft; - else if(speaker.Name == "RF") - ch = FrontRight; - else if(speaker.Name == "CE") - ch = FrontCenter; - else if(speaker.Name == "LS") - { - if(device->FmtChans == DevFmtX51Rear) - ch = BackLeft; - else - ch = SideLeft; - } - else if(speaker.Name == "RS") - { - if(device->FmtChans == DevFmtX51Rear) - ch = BackRight; - else - ch = SideRight; - } - else if(speaker.Name == "LB") - { - if(device->FmtChans == DevFmtX51) - ch = SideLeft; - else - ch = BackLeft; - } - else if(speaker.Name == "RB") - { - if(device->FmtChans == DevFmtX51) - ch = SideRight; - else - ch = BackRight; - } - else if(speaker.Name == "CB") - ch = BackCenter; - else - { - ERR("AmbDec speaker label \"%s\" not recognized\n", speaker.Name.c_str()); - return INVALID_CHANNEL_INDEX; - } - const uint chidx{GetChannelIdxByName(device->RealOut, ch)}; - if(chidx == INVALID_CHANNEL_INDEX) - ERR("Failed to lookup AmbDec speaker label %s\n", speaker.Name.c_str()); - return chidx; - }; - std::transform(conf->Speakers.get(), conf->Speakers.get()+conf->NumSpeakers, - std::begin(speakermap), map_spkr); - /* Return success if no invalid entries are found. */ - auto spkrmap_end = std::begin(speakermap) + conf->NumSpeakers; - return std::find(std::begin(speakermap), spkrmap_end, INVALID_CHANNEL_INDEX) == spkrmap_end; -} - - -void InitNearFieldCtrl(ALCdevice *device, float ctrl_dist, uint order, bool is3d) -{ - static const uint chans_per_order2d[MaxAmbiOrder+1]{ 1, 2, 2, 2 }; - static const uint chans_per_order3d[MaxAmbiOrder+1]{ 1, 3, 5, 7 }; - - /* NFC is only used when AvgSpeakerDist is greater than 0. */ - const char *devname{device->DeviceName.c_str()}; - if(!GetConfigValueBool(devname, "decoder", "nfc", 0) || !(ctrl_dist > 0.0f)) - return; - - device->AvgSpeakerDist = clampf(ctrl_dist, 0.1f, 10.0f); - TRACE("Using near-field reference distance: %.2f meters\n", device->AvgSpeakerDist); - - auto iter = std::copy_n(is3d ? chans_per_order3d : chans_per_order2d, order+1u, - std::begin(device->NumChannelsPerOrder)); - std::fill(iter, std::end(device->NumChannelsPerOrder), 0u); -} - -void InitDistanceComp(ALCdevice *device, const AmbDecConf *conf, - const uint (&speakermap)[MAX_OUTPUT_CHANNELS]) -{ - auto get_max = std::bind(maxf, _1, - std::bind(std::mem_fn(&AmbDecConf::SpeakerConf::Distance), _2)); - const float maxdist{std::accumulate(conf->Speakers.get(), - conf->Speakers.get()+conf->NumSpeakers, 0.0f, get_max)}; - - const char *devname{device->DeviceName.c_str()}; - if(!GetConfigValueBool(devname, "decoder", "distance-comp", 1) || !(maxdist > 0.0f)) - return; - - const auto distSampleScale = static_cast(device->Frequency) / SpeedOfSoundMetersPerSec; - std::vector ChanDelay; - size_t total{0u}; - ChanDelay.reserve(conf->NumSpeakers + 1); - for(size_t i{0u};i < conf->NumSpeakers;i++) - { - const AmbDecConf::SpeakerConf &speaker = conf->Speakers[i]; - const uint chan{speakermap[i]}; - - /* Distance compensation only delays in steps of the sample rate. This - * is a bit less accurate since the delay time falls to the nearest - * sample time, but it's far simpler as it doesn't have to deal with - * phase offsets. This means at 48khz, for instance, the distance delay - * will be in steps of about 7 millimeters. - */ - float delay{std::floor((maxdist - speaker.Distance)*distSampleScale + 0.5f)}; - if(delay > float{MAX_DELAY_LENGTH-1}) - { - ERR("Delay for speaker \"%s\" exceeds buffer length (%f > %d)\n", - speaker.Name.c_str(), delay, MAX_DELAY_LENGTH-1); - delay = float{MAX_DELAY_LENGTH-1}; - } - - ChanDelay.resize(maxz(ChanDelay.size(), chan+1)); - ChanDelay[chan].Length = static_cast(delay); - ChanDelay[chan].Gain = speaker.Distance / maxdist; - TRACE("Channel %u \"%s\" distance compensation: %u samples, %f gain\n", chan, - speaker.Name.c_str(), ChanDelay[chan].Length, ChanDelay[chan].Gain); - - /* Round up to the next 4th sample, so each channel buffer starts - * 16-byte aligned. - */ - total += RoundUp(ChanDelay[chan].Length, 4); - } - - if(total > 0) - { - auto chandelays = DistanceComp::Create(total); - std::copy(ChanDelay.cbegin(), ChanDelay.cend(), chandelays->mChannels.begin()); - - chandelays->mChannels[0].Buffer = chandelays->mSamples.data(); - auto set_bufptr = [](const DistanceComp::ChanData &last, const DistanceComp::ChanData &cur) - -> DistanceComp::ChanData - { - DistanceComp::ChanData ret{cur}; - ret.Buffer = last.Buffer + RoundUp(last.Length, 4); - return ret; - }; - std::partial_sum(ChanDelay.begin(), ChanDelay.end(), ChanDelay.begin(), set_bufptr); - device->ChannelDelays = std::move(chandelays); - } -} - - -inline auto& GetAmbiScales(DevAmbiScaling scaletype) noexcept -{ - if(scaletype == DevAmbiScaling::FuMa) return AmbiScale::FromFuMa(); - if(scaletype == DevAmbiScaling::SN3D) return AmbiScale::FromSN3D(); - return AmbiScale::FromN3D(); -} - -inline auto& GetAmbiLayout(DevAmbiLayout layouttype) noexcept -{ - if(layouttype == DevAmbiLayout::FuMa) return AmbiIndex::FromFuMa(); - return AmbiIndex::FromACN(); -} - - -using ChannelCoeffs = std::array; -enum DecoderMode : bool { - SingleBand = false, - DualBand = true -}; - -template -struct DecoderConfig; - -template -struct DecoderConfig { - uint mOrder; - std::array mChannels; - std::array mOrderGain; - std::array mCoeffs; -}; - -template -struct DecoderConfig { - uint mOrder; - std::array mChannels; - std::array mOrderGain; - std::array mCoeffs; - std::array mOrderGainLF; - std::array mCoeffsLF; -}; - -template<> -struct DecoderConfig { - uint mOrder; - al::span mChannels; - al::span mOrderGain; - al::span mCoeffs; - al::span mOrderGainLF; - al::span mCoeffsLF; - - template - DecoderConfig& operator=(const DecoderConfig &rhs) noexcept - { - mOrder = rhs.mOrder; - mChannels = rhs.mChannels; - mOrderGain = rhs.mOrderGain; - mCoeffs = rhs.mCoeffs; - mOrderGainLF = {}; - mCoeffsLF = {}; - return *this; - } - - template - DecoderConfig& operator=(const DecoderConfig &rhs) noexcept - { - mOrder = rhs.mOrder; - mChannels = rhs.mChannels; - mOrderGain = rhs.mOrderGain; - mCoeffs = rhs.mCoeffs; - mOrderGainLF = rhs.mOrderGainLF; - mCoeffsLF = rhs.mCoeffsLF; - return *this; - } -}; -using DecoderView = DecoderConfig; - -constexpr DecoderConfig MonoConfig{ - 0, {{FrontCenter}}, - {{1.0f}}, - {{ {{1.0f}} }} -}; -constexpr DecoderConfig StereoConfig{ - 1, {{FrontLeft, FrontRight}}, - {{1.0f, 1.0f}}, - {{ - {{5.00000000e-1f, 2.88675135e-1f, 5.52305643e-2f}}, - {{5.00000000e-1f, -2.88675135e-1f, 5.52305643e-2f}}, - }} -}; -constexpr DecoderConfig QuadConfig{ - 2, {{BackLeft, FrontLeft, FrontRight, BackRight}}, - /*HF*/{{1.15470054e+0f, 1.00000000e+0f, 5.77350269e-1f}}, - {{ - {{2.50000000e-1f, 2.04124145e-1f, -2.04124145e-1f, -1.29099445e-1f, 0.00000000e+0f}}, - {{2.50000000e-1f, 2.04124145e-1f, 2.04124145e-1f, 1.29099445e-1f, 0.00000000e+0f}}, - {{2.50000000e-1f, -2.04124145e-1f, 2.04124145e-1f, -1.29099445e-1f, 0.00000000e+0f}}, - {{2.50000000e-1f, -2.04124145e-1f, -2.04124145e-1f, 1.29099445e-1f, 0.00000000e+0f}}, - }}, - /*LF*/{{1.00000000e+0f, 1.00000000e+0f, 1.00000000e+0f}}, - {{ - {{2.50000000e-1f, 2.04124145e-1f, -2.04124145e-1f, -1.29099445e-1f, 0.00000000e+0f}}, - {{2.50000000e-1f, 2.04124145e-1f, 2.04124145e-1f, 1.29099445e-1f, 0.00000000e+0f}}, - {{2.50000000e-1f, -2.04124145e-1f, 2.04124145e-1f, -1.29099445e-1f, 0.00000000e+0f}}, - {{2.50000000e-1f, -2.04124145e-1f, -2.04124145e-1f, 1.29099445e-1f, 0.00000000e+0f}}, - }} -}; -constexpr DecoderConfig X51Config{ - 2, {{SideLeft, FrontLeft, FrontRight, SideRight}}, - {{1.0f, 1.0f, 1.0f}}, - {{ - {{3.33000782e-1f, 1.89084803e-1f, -2.00042375e-1f, -2.12307769e-2f, -1.14579885e-2f}}, - {{1.88542860e-1f, 1.27709292e-1f, 1.66295695e-1f, 7.30571517e-2f, 2.10901184e-2f}}, - {{1.88542860e-1f, -1.27709292e-1f, 1.66295695e-1f, -7.30571517e-2f, 2.10901184e-2f}}, - {{3.33000782e-1f, -1.89084803e-1f, -2.00042375e-1f, 2.12307769e-2f, -1.14579885e-2f}}, - }} -}; -constexpr DecoderConfig X51RearConfig{ - 2, {{BackLeft, FrontLeft, FrontRight, BackRight}}, - {{1.0f, 1.0f, 1.0f}}, - {{ - {{3.33000782e-1f, 1.89084803e-1f, -2.00042375e-1f, -2.12307769e-2f, -1.14579885e-2f}}, - {{1.88542860e-1f, 1.27709292e-1f, 1.66295695e-1f, 7.30571517e-2f, 2.10901184e-2f}}, - {{1.88542860e-1f, -1.27709292e-1f, 1.66295695e-1f, -7.30571517e-2f, 2.10901184e-2f}}, - {{3.33000782e-1f, -1.89084803e-1f, -2.00042375e-1f, 2.12307769e-2f, -1.14579885e-2f}}, - }} -}; -constexpr DecoderConfig X61Config{ - 2, {{SideLeft, FrontLeft, FrontRight, SideRight, BackCenter}}, - {{1.0f, 1.0f, 1.0f}}, - {{ - {{2.04460341e-1f, 2.17177926e-1f, -4.39996780e-2f, -2.60790269e-2f, -6.87239792e-2f}}, - {{1.58923161e-1f, 9.21772680e-2f, 1.59658796e-1f, 6.66278083e-2f, 3.84686854e-2f}}, - {{1.58923161e-1f, -9.21772680e-2f, 1.59658796e-1f, -6.66278083e-2f, 3.84686854e-2f}}, - {{2.04460341e-1f, -2.17177926e-1f, -4.39996780e-2f, 2.60790269e-2f, -6.87239792e-2f}}, - {{2.50001688e-1f, 0.00000000e+0f, -2.50000094e-1f, 0.00000000e+0f, 6.05133395e-2f}}, - }} -}; -constexpr DecoderConfig X71Config{ - 3, {{BackLeft, SideLeft, FrontLeft, FrontRight, SideRight, BackRight}}, - /*HF*/{{1.22474487e+0f, 1.13151672e+0f, 8.66025404e-1f, 4.68689571e-1f}}, - {{ - {{1.66666667e-1f, 9.62250449e-2f, -1.66666667e-1f, -1.49071198e-1f, 8.60662966e-2f, 7.96819073e-2f, 0.00000000e+0f}}, - {{1.66666667e-1f, 1.92450090e-1f, 0.00000000e+0f, 0.00000000e+0f, -1.72132593e-1f, -7.96819073e-2f, 0.00000000e+0f}}, - {{1.66666667e-1f, 9.62250449e-2f, 1.66666667e-1f, 1.49071198e-1f, 8.60662966e-2f, 7.96819073e-2f, 0.00000000e+0f}}, - {{1.66666667e-1f, -9.62250449e-2f, 1.66666667e-1f, -1.49071198e-1f, 8.60662966e-2f, -7.96819073e-2f, 0.00000000e+0f}}, - {{1.66666667e-1f, -1.92450090e-1f, 0.00000000e+0f, 0.00000000e+0f, -1.72132593e-1f, 7.96819073e-2f, 0.00000000e+0f}}, - {{1.66666667e-1f, -9.62250449e-2f, -1.66666667e-1f, 1.49071198e-1f, 8.60662966e-2f, -7.96819073e-2f, 0.00000000e+0f}}, - }}, - /*LF*/{{1.00000000e+0f, 1.00000000e+0f, 1.00000000e+0f, 1.00000000e+0f}}, - {{ - {{1.66666667e-1f, 9.62250449e-2f, -1.66666667e-1f, -1.49071198e-1f, 8.60662966e-2f, 7.96819073e-2f, 0.00000000e+0f}}, - {{1.66666667e-1f, 1.92450090e-1f, 0.00000000e+0f, 0.00000000e+0f, -1.72132593e-1f, -7.96819073e-2f, 0.00000000e+0f}}, - {{1.66666667e-1f, 9.62250449e-2f, 1.66666667e-1f, 1.49071198e-1f, 8.60662966e-2f, 7.96819073e-2f, 0.00000000e+0f}}, - {{1.66666667e-1f, -9.62250449e-2f, 1.66666667e-1f, -1.49071198e-1f, 8.60662966e-2f, -7.96819073e-2f, 0.00000000e+0f}}, - {{1.66666667e-1f, -1.92450090e-1f, 0.00000000e+0f, 0.00000000e+0f, -1.72132593e-1f, 7.96819073e-2f, 0.00000000e+0f}}, - {{1.66666667e-1f, -9.62250449e-2f, -1.66666667e-1f, 1.49071198e-1f, 8.60662966e-2f, -7.96819073e-2f, 0.00000000e+0f}}, - }} -}; - -void InitPanning(ALCdevice *device, const bool hqdec=false, const bool stablize=false) -{ - DecoderView decoder{}; - switch(device->FmtChans) - { - case DevFmtMono: - decoder = MonoConfig; - break; - case DevFmtStereo: - decoder = StereoConfig; - break; - case DevFmtQuad: - decoder = QuadConfig; - break; - case DevFmtX51: - decoder = X51Config; - break; - case DevFmtX51Rear: - decoder = X51RearConfig; - break; - case DevFmtX61: - decoder = X61Config; - break; - case DevFmtX71: - decoder = X71Config; - break; - case DevFmtAmbi3D: - break; - } - - if(device->FmtChans == DevFmtAmbi3D) - { - const char *devname{device->DeviceName.c_str()}; - auto&& acnmap = GetAmbiLayout(device->mAmbiLayout); - auto&& n3dscale = GetAmbiScales(device->mAmbiScale); - - /* For DevFmtAmbi3D, the ambisonic order is already set. */ - const size_t count{AmbiChannelsFromOrder(device->mAmbiOrder)}; - std::transform(acnmap.begin(), acnmap.begin()+count, std::begin(device->Dry.AmbiMap), - [&n3dscale](const uint8_t &acn) noexcept -> BFChannelConfig - { return BFChannelConfig{1.0f/n3dscale[acn], acn}; } - ); - AllocChannels(device, count, 0); - - float nfc_delay{ConfigValueFloat(devname, "decoder", "nfc-ref-delay").value_or(0.0f)}; - if(nfc_delay > 0.0f) - InitNearFieldCtrl(device, nfc_delay * SpeedOfSoundMetersPerSec, device->mAmbiOrder, - true); - } - else - { - const bool dual_band{hqdec && !decoder.mCoeffsLF.empty()}; - al::vector chancoeffs, chancoeffslf; - for(size_t i{0u};i < decoder.mChannels.size();++i) - { - const uint idx{GetChannelIdxByName(device->RealOut, decoder.mChannels[i])}; - if(idx == INVALID_CHANNEL_INDEX) - { - ERR("Failed to find %s channel in device\n", - GetLabelFromChannel(decoder.mChannels[i])); - continue; - } - - chancoeffs.resize(maxz(chancoeffs.size(), idx+1u), ChannelDec{}); - al::span coeffs{chancoeffs[idx]}; - size_t start{0}; - for(uint o{0};o <= decoder.mOrder;++o) - { - size_t count{o ? 2u : 1u}; - do { - coeffs[start] = decoder.mCoeffs[i][start] * decoder.mOrderGain[o]; - ++start; - } while(--count); - } - if(!dual_band) - continue; - - chancoeffslf.resize(maxz(chancoeffslf.size(), idx+1u), ChannelDec{}); - coeffs = chancoeffslf[idx]; - start = 0; - for(uint o{0};o <= decoder.mOrder;++o) - { - size_t count{o ? 2u : 1u}; - do { - coeffs[start] = decoder.mCoeffsLF[i][start] * decoder.mOrderGainLF[o]; - ++start; - } while(--count); - } - } - - /* For non-DevFmtAmbi3D, set the ambisonic order. */ - device->mAmbiOrder = decoder.mOrder; - - /* Built-in speaker decoders are always 2D. */ - const size_t ambicount{Ambi2DChannelsFromOrder(decoder.mOrder)}; - std::transform(AmbiIndex::FromACN2D().begin(), AmbiIndex::FromACN2D().begin()+ambicount, - std::begin(device->Dry.AmbiMap), - [](const uint8_t &index) noexcept { return BFChannelConfig{1.0f, index}; } - ); - AllocChannels(device, ambicount, device->channelsFromFmt()); - - std::unique_ptr stablizer; - if(stablize) - { - /* Only enable the stablizer if the decoder does not output to the - * front-center channel. - */ - const auto cidx = device->RealOut.ChannelIndex[FrontCenter]; - bool hasfc{false}; - if(cidx < chancoeffs.size()) - { - for(const auto &coeff : chancoeffs[cidx]) - hasfc |= coeff != 0.0f; - } - if(!hasfc && cidx < chancoeffslf.size()) - { - for(const auto &coeff : chancoeffslf[cidx]) - hasfc |= coeff != 0.0f; - } - if(!hasfc) - { - stablizer = CreateStablizer(device->channelsFromFmt(), device->Frequency); - TRACE("Front stablizer enabled\n"); - } - } - - TRACE("Enabling %s-band %s-order%s ambisonic decoder\n", - !dual_band ? "single" : "dual", - (decoder.mOrder > 2) ? "third" : - (decoder.mOrder > 1) ? "second" : "first", - ""); - device->AmbiDecoder = BFormatDec::Create(ambicount, chancoeffs, chancoeffslf, - std::move(stablizer)); - } -} - -void InitCustomPanning(ALCdevice *device, const bool hqdec, const bool stablize, - const AmbDecConf *conf, const uint (&speakermap)[MAX_OUTPUT_CHANNELS]) -{ - if(!hqdec && conf->FreqBands != 1) - ERR("Basic renderer uses the high-frequency matrix as single-band (xover_freq = %.0fhz)\n", - conf->XOverFreq); - device->mXOverFreq = conf->XOverFreq; - - const uint order{(conf->ChanMask > Ambi2OrderMask) ? 3u : - (conf->ChanMask > Ambi1OrderMask) ? 2u : 1u}; - device->mAmbiOrder = order; - - size_t count; - if((conf->ChanMask&AmbiPeriphonicMask)) - { - count = AmbiChannelsFromOrder(order); - std::transform(AmbiIndex::FromACN().begin(), AmbiIndex::FromACN().begin()+count, - std::begin(device->Dry.AmbiMap), - [](const uint8_t &index) noexcept { return BFChannelConfig{1.0f, index}; } - ); - } - else - { - count = Ambi2DChannelsFromOrder(order); - std::transform(AmbiIndex::FromACN2D().begin(), AmbiIndex::FromACN2D().begin()+count, - std::begin(device->Dry.AmbiMap), - [](const uint8_t &index) noexcept { return BFChannelConfig{1.0f, index}; } - ); - } - AllocChannels(device, count, device->channelsFromFmt()); - - std::unique_ptr stablizer; - if(stablize) - { - /* Only enable the stablizer if the decoder does not output to the - * front-center channel. - */ - size_t cidx{0}; - for(;cidx < conf->NumSpeakers;++cidx) - { - if(speakermap[cidx] == FrontCenter) - break; - } - bool hasfc{false}; - if(cidx < conf->NumSpeakers && conf->FreqBands != 1) - { - for(const auto &coeff : conf->LFMatrix[cidx]) - hasfc |= coeff != 0.0f; - } - if(!hasfc && cidx < conf->NumSpeakers) - { - for(const auto &coeff : conf->HFMatrix[cidx]) - hasfc |= coeff != 0.0f; - } - if(!hasfc) - { - stablizer = CreateStablizer(device->channelsFromFmt(), device->Frequency); - TRACE("Front stablizer enabled\n"); - } - } - - TRACE("Enabling %s-band %s-order%s ambisonic decoder\n", - (!hqdec || conf->FreqBands == 1) ? "single" : "dual", - (conf->ChanMask > Ambi2OrderMask) ? "third" : - (conf->ChanMask > Ambi1OrderMask) ? "second" : "first", - (conf->ChanMask&AmbiPeriphonicMask) ? " periphonic" : "" - ); - device->AmbiDecoder = BFormatDec::Create(conf, hqdec, count, device->Frequency, speakermap, - std::move(stablizer)); - - auto accum_spkr_dist = std::bind(std::plus{}, _1, - std::bind(std::mem_fn(&AmbDecConf::SpeakerConf::Distance), _2)); - const float accum_dist{std::accumulate(conf->Speakers.get(), - conf->Speakers.get()+conf->NumSpeakers, 0.0f, accum_spkr_dist)}; - InitNearFieldCtrl(device, accum_dist / static_cast(conf->NumSpeakers), order, - !!(conf->ChanMask&AmbiPeriphonicMask)); - - InitDistanceComp(device, conf, speakermap); -} - -void InitHrtfPanning(ALCdevice *device) -{ - constexpr float Deg180{al::MathDefs::Pi()}; - constexpr float Deg_90{Deg180 / 2.0f /* 90 degrees*/}; - constexpr float Deg_45{Deg_90 / 2.0f /* 45 degrees*/}; - constexpr float Deg135{Deg_45 * 3.0f /*135 degrees*/}; - constexpr float Deg_35{6.154797086e-01f /* 35~ 36 degrees*/}; - constexpr float Deg_69{1.205932499e+00f /* 69~ 70 degrees*/}; - constexpr float Deg111{1.935660155e+00f /*110~111 degrees*/}; - constexpr float Deg_21{3.648638281e-01f /* 20~ 21 degrees*/}; - static const AngularPoint AmbiPoints1O[]{ - { EvRadians{ Deg_35}, AzRadians{-Deg_45} }, - { EvRadians{ Deg_35}, AzRadians{-Deg135} }, - { EvRadians{ Deg_35}, AzRadians{ Deg_45} }, - { EvRadians{ Deg_35}, AzRadians{ Deg135} }, - { EvRadians{-Deg_35}, AzRadians{-Deg_45} }, - { EvRadians{-Deg_35}, AzRadians{-Deg135} }, - { EvRadians{-Deg_35}, AzRadians{ Deg_45} }, - { EvRadians{-Deg_35}, AzRadians{ Deg135} }, - }, AmbiPoints2O[]{ - { EvRadians{-Deg_35}, AzRadians{-Deg_45} }, - { EvRadians{-Deg_35}, AzRadians{-Deg135} }, - { EvRadians{ Deg_35}, AzRadians{-Deg135} }, - { EvRadians{ Deg_35}, AzRadians{ Deg135} }, - { EvRadians{ Deg_35}, AzRadians{ Deg_45} }, - { EvRadians{-Deg_35}, AzRadians{ Deg_45} }, - { EvRadians{-Deg_35}, AzRadians{ Deg135} }, - { EvRadians{ Deg_35}, AzRadians{-Deg_45} }, - { EvRadians{-Deg_69}, AzRadians{-Deg_90} }, - { EvRadians{ Deg_69}, AzRadians{ Deg_90} }, - { EvRadians{-Deg_69}, AzRadians{ Deg_90} }, - { EvRadians{ Deg_69}, AzRadians{-Deg_90} }, - { EvRadians{ 0.0f}, AzRadians{-Deg_69} }, - { EvRadians{ 0.0f}, AzRadians{-Deg111} }, - { EvRadians{ 0.0f}, AzRadians{ Deg_69} }, - { EvRadians{ 0.0f}, AzRadians{ Deg111} }, - { EvRadians{-Deg_21}, AzRadians{ Deg180} }, - { EvRadians{ Deg_21}, AzRadians{ Deg180} }, - { EvRadians{ Deg_21}, AzRadians{ 0.0f} }, - { EvRadians{-Deg_21}, AzRadians{ 0.0f} }, - }; - static const float AmbiMatrix1O[][MaxAmbiChannels]{ - { 1.250000000e-01f, 1.250000000e-01f, 1.250000000e-01f, 1.250000000e-01f }, - { 1.250000000e-01f, 1.250000000e-01f, 1.250000000e-01f, -1.250000000e-01f }, - { 1.250000000e-01f, -1.250000000e-01f, 1.250000000e-01f, 1.250000000e-01f }, - { 1.250000000e-01f, -1.250000000e-01f, 1.250000000e-01f, -1.250000000e-01f }, - { 1.250000000e-01f, 1.250000000e-01f, -1.250000000e-01f, 1.250000000e-01f }, - { 1.250000000e-01f, 1.250000000e-01f, -1.250000000e-01f, -1.250000000e-01f }, - { 1.250000000e-01f, -1.250000000e-01f, -1.250000000e-01f, 1.250000000e-01f }, - { 1.250000000e-01f, -1.250000000e-01f, -1.250000000e-01f, -1.250000000e-01f }, - }, AmbiMatrix2O[][MaxAmbiChannels]{ - { 5.000000000e-02f, 5.000000000e-02f, -5.000000000e-02f, 5.000000000e-02f, 6.454972244e-02f, -6.454972244e-02f, 0.000000000e+00f, -6.454972244e-02f, 0.000000000e+00f }, - { 5.000000000e-02f, 5.000000000e-02f, -5.000000000e-02f, -5.000000000e-02f, -6.454972244e-02f, -6.454972244e-02f, 0.000000000e+00f, 6.454972244e-02f, 0.000000000e+00f }, - { 5.000000000e-02f, 5.000000000e-02f, 5.000000000e-02f, -5.000000000e-02f, -6.454972244e-02f, 6.454972244e-02f, 0.000000000e+00f, -6.454972244e-02f, 0.000000000e+00f }, - { 5.000000000e-02f, -5.000000000e-02f, 5.000000000e-02f, -5.000000000e-02f, 6.454972244e-02f, -6.454972244e-02f, 0.000000000e+00f, -6.454972244e-02f, 0.000000000e+00f }, - { 5.000000000e-02f, -5.000000000e-02f, 5.000000000e-02f, 5.000000000e-02f, -6.454972244e-02f, -6.454972244e-02f, 0.000000000e+00f, 6.454972244e-02f, 0.000000000e+00f }, - { 5.000000000e-02f, -5.000000000e-02f, -5.000000000e-02f, 5.000000000e-02f, -6.454972244e-02f, 6.454972244e-02f, 0.000000000e+00f, -6.454972244e-02f, 0.000000000e+00f }, - { 5.000000000e-02f, -5.000000000e-02f, -5.000000000e-02f, -5.000000000e-02f, 6.454972244e-02f, 6.454972244e-02f, 0.000000000e+00f, 6.454972244e-02f, 0.000000000e+00f }, - { 5.000000000e-02f, 5.000000000e-02f, 5.000000000e-02f, 5.000000000e-02f, 6.454972244e-02f, 6.454972244e-02f, 0.000000000e+00f, 6.454972244e-02f, 0.000000000e+00f }, - { 5.000000000e-02f, 3.090169944e-02f, -8.090169944e-02f, 0.000000000e+00f, 0.000000000e+00f, -6.454972244e-02f, 9.045084972e-02f, 0.000000000e+00f, -1.232790000e-02f }, - { 5.000000000e-02f, -3.090169944e-02f, 8.090169944e-02f, 0.000000000e+00f, 0.000000000e+00f, -6.454972244e-02f, 9.045084972e-02f, 0.000000000e+00f, -1.232790000e-02f }, - { 5.000000000e-02f, -3.090169944e-02f, -8.090169944e-02f, 0.000000000e+00f, 0.000000000e+00f, 6.454972244e-02f, 9.045084972e-02f, 0.000000000e+00f, -1.232790000e-02f }, - { 5.000000000e-02f, 3.090169944e-02f, 8.090169944e-02f, 0.000000000e+00f, 0.000000000e+00f, 6.454972244e-02f, 9.045084972e-02f, 0.000000000e+00f, -1.232790000e-02f }, - { 5.000000000e-02f, 8.090169944e-02f, 0.000000000e+00f, 3.090169944e-02f, 6.454972244e-02f, 0.000000000e+00f, -5.590169944e-02f, 0.000000000e+00f, -7.216878365e-02f }, - { 5.000000000e-02f, 8.090169944e-02f, 0.000000000e+00f, -3.090169944e-02f, -6.454972244e-02f, 0.000000000e+00f, -5.590169944e-02f, 0.000000000e+00f, -7.216878365e-02f }, - { 5.000000000e-02f, -8.090169944e-02f, 0.000000000e+00f, 3.090169944e-02f, -6.454972244e-02f, 0.000000000e+00f, -5.590169944e-02f, 0.000000000e+00f, -7.216878365e-02f }, - { 5.000000000e-02f, -8.090169944e-02f, 0.000000000e+00f, -3.090169944e-02f, 6.454972244e-02f, 0.000000000e+00f, -5.590169944e-02f, 0.000000000e+00f, -7.216878365e-02f }, - { 5.000000000e-02f, 0.000000000e+00f, -3.090169944e-02f, -8.090169944e-02f, 0.000000000e+00f, 0.000000000e+00f, -3.454915028e-02f, 6.454972244e-02f, 8.449668365e-02f }, - { 5.000000000e-02f, 0.000000000e+00f, 3.090169944e-02f, -8.090169944e-02f, 0.000000000e+00f, 0.000000000e+00f, -3.454915028e-02f, -6.454972244e-02f, 8.449668365e-02f }, - { 5.000000000e-02f, 0.000000000e+00f, 3.090169944e-02f, 8.090169944e-02f, 0.000000000e+00f, 0.000000000e+00f, -3.454915028e-02f, 6.454972244e-02f, 8.449668365e-02f }, - { 5.000000000e-02f, 0.000000000e+00f, -3.090169944e-02f, 8.090169944e-02f, 0.000000000e+00f, 0.000000000e+00f, -3.454915028e-02f, -6.454972244e-02f, 8.449668365e-02f }, - }; - static const float AmbiOrderHFGain1O[MaxAmbiOrder+1]{ - 2.000000000e+00f, 1.154700538e+00f - }, AmbiOrderHFGain2O[MaxAmbiOrder+1]{ - 2.357022604e+00f, 1.825741858e+00f, 9.428090416e-01f - }; - - static_assert(al::size(AmbiPoints1O) == al::size(AmbiMatrix1O), "First-Order Ambisonic HRTF mismatch"); - static_assert(al::size(AmbiPoints2O) == al::size(AmbiMatrix2O), "Second-Order Ambisonic HRTF mismatch"); - - /* Don't bother with HOA when using full HRTF rendering. Nothing needs it, - * and it eases the CPU/memory load. - */ - device->mRenderMode = RenderMode::Hrtf; - uint ambi_order{1}; - if(auto modeopt = ConfigValueStr(device->DeviceName.c_str(), nullptr, "hrtf-mode")) - { - struct HrtfModeEntry { - char name[8]; - RenderMode mode; - uint order; - }; - static const HrtfModeEntry hrtf_modes[]{ - { "full", RenderMode::Hrtf, 1 }, - { "ambi1", RenderMode::Normal, 1 }, - { "ambi2", RenderMode::Normal, 2 }, - }; - - const char *mode{modeopt->c_str()}; - if(al::strcasecmp(mode, "basic") == 0 || al::strcasecmp(mode, "ambi3") == 0) - { - ERR("HRTF mode \"%s\" deprecated, substituting \"%s\"\n", mode, "ambi2"); - mode = "ambi2"; - } - - auto match_entry = [mode](const HrtfModeEntry &entry) -> bool - { return al::strcasecmp(mode, entry.name) == 0; }; - auto iter = std::find_if(std::begin(hrtf_modes), std::end(hrtf_modes), match_entry); - if(iter == std::end(hrtf_modes)) - ERR("Unexpected hrtf-mode: %s\n", mode); - else - { - device->mRenderMode = iter->mode; - ambi_order = iter->order; - } - } - TRACE("%u%s order %sHRTF rendering enabled, using \"%s\"\n", ambi_order, - (((ambi_order%100)/10) == 1) ? "th" : - ((ambi_order%10) == 1) ? "st" : - ((ambi_order%10) == 2) ? "nd" : - ((ambi_order%10) == 3) ? "rd" : "th", - (device->mRenderMode == RenderMode::Hrtf) ? "+ Full " : "", - device->HrtfName.c_str()); - - al::span AmbiPoints{AmbiPoints1O}; - const float (*AmbiMatrix)[MaxAmbiChannels]{AmbiMatrix1O}; - al::span AmbiOrderHFGain{AmbiOrderHFGain1O}; - if(ambi_order >= 2) - { - AmbiPoints = AmbiPoints2O; - AmbiMatrix = AmbiMatrix2O; - AmbiOrderHFGain = AmbiOrderHFGain2O; - } - device->mAmbiOrder = ambi_order; - - const size_t count{AmbiChannelsFromOrder(ambi_order)}; - std::transform(AmbiIndex::FromACN().begin(), AmbiIndex::FromACN().begin()+count, - std::begin(device->Dry.AmbiMap), - [](const uint8_t &index) noexcept { return BFChannelConfig{1.0f, index}; } - ); - AllocChannels(device, count, device->channelsFromFmt()); - - HrtfStore *Hrtf{device->mHrtf.get()}; - auto hrtfstate = DirectHrtfState::Create(count); - hrtfstate->build(Hrtf, device->mIrSize, AmbiPoints, AmbiMatrix, device->mXOverFreq, - AmbiOrderHFGain); - device->mHrtfState = std::move(hrtfstate); - - InitNearFieldCtrl(device, Hrtf->field[0].distance, ambi_order, true); -} - -void InitUhjPanning(ALCdevice *device) -{ - /* UHJ is always 2D first-order. */ - constexpr size_t count{Ambi2DChannelsFromOrder(1)}; - - device->mAmbiOrder = 1; - - auto acnmap_begin = AmbiIndex::FromFuMa().begin(); - std::transform(acnmap_begin, acnmap_begin + count, std::begin(device->Dry.AmbiMap), - [](const uint8_t &acn) noexcept -> BFChannelConfig - { return BFChannelConfig{1.0f/AmbiScale::FromFuMa()[acn], acn}; }); - AllocChannels(device, count, device->channelsFromFmt()); -} - -} // namespace - -void aluInitRenderer(ALCdevice *device, int hrtf_id, HrtfRequestMode hrtf_appreq, - HrtfRequestMode hrtf_userreq) -{ - const char *devname{device->DeviceName.c_str()}; - - /* Hold the HRTF the device last used, in case it's used again. */ - HrtfStorePtr old_hrtf{std::move(device->mHrtf)}; - - device->mHrtfState = nullptr; - device->mHrtf = nullptr; - device->mIrSize = 0; - device->HrtfName.clear(); - device->mXOverFreq = 400.0f; - device->mRenderMode = RenderMode::Normal; - - if(device->FmtChans != DevFmtStereo) - { - old_hrtf = nullptr; - if(hrtf_appreq == Hrtf_Enable) - device->HrtfStatus = ALC_HRTF_UNSUPPORTED_FORMAT_SOFT; - - const char *layout{nullptr}; - switch(device->FmtChans) - { - case DevFmtQuad: layout = "quad"; break; - case DevFmtX51: /* fall-through */ - case DevFmtX51Rear: layout = "surround51"; break; - case DevFmtX61: layout = "surround61"; break; - case DevFmtX71: layout = "surround71"; break; - /* Mono, Stereo, and Ambisonics output don't use custom decoders. */ - case DevFmtMono: - case DevFmtStereo: - case DevFmtAmbi3D: - break; - } - - uint speakermap[MAX_OUTPUT_CHANNELS]; - AmbDecConf *pconf{nullptr}; - AmbDecConf conf{}; - if(layout) - { - if(auto decopt = ConfigValueStr(devname, "decoder", layout)) - { - if(auto err = conf.load(decopt->c_str())) - { - ERR("Failed to load layout file %s\n", decopt->c_str()); - ERR(" %s\n", err->c_str()); - } - else if(conf.NumSpeakers > MAX_OUTPUT_CHANNELS) - ERR("Unsupported decoder speaker count %zu (max %d)\n", conf.NumSpeakers, - MAX_OUTPUT_CHANNELS); - else if(conf.ChanMask > Ambi3OrderMask) - ERR("Unsupported decoder channel mask 0x%04x (max 0x%x)\n", conf.ChanMask, - Ambi3OrderMask); - else if(MakeSpeakerMap(device, &conf, speakermap)) - pconf = &conf; - } - } - - /* Enable the stablizer only for formats that have front-left, front- - * right, and front-center outputs. - */ - const bool stablize{device->RealOut.ChannelIndex[FrontCenter] != INVALID_CHANNEL_INDEX - && device->RealOut.ChannelIndex[FrontLeft] != INVALID_CHANNEL_INDEX - && device->RealOut.ChannelIndex[FrontRight] != INVALID_CHANNEL_INDEX - && GetConfigValueBool(devname, nullptr, "front-stablizer", 0) != 0}; - const bool hqdec{GetConfigValueBool(devname, "decoder", "hq-mode", 1) != 0}; - if(!pconf) - InitPanning(device, hqdec, stablize); - else - InitCustomPanning(device, hqdec, stablize, pconf, speakermap); - if(auto *ambidec{device->AmbiDecoder.get()}) - { - device->PostProcess = ambidec->hasStablizer() ? &ALCdevice::ProcessAmbiDecStablized - : &ALCdevice::ProcessAmbiDec; - } - return; - } - - bool headphones{device->IsHeadphones}; - if(device->Type != DeviceType::Loopback) - { - if(auto modeopt = ConfigValueStr(device->DeviceName.c_str(), nullptr, "stereo-mode")) - { - const char *mode{modeopt->c_str()}; - if(al::strcasecmp(mode, "headphones") == 0) - headphones = true; - else if(al::strcasecmp(mode, "speakers") == 0) - headphones = false; - else if(al::strcasecmp(mode, "auto") != 0) - ERR("Unexpected stereo-mode: %s\n", mode); - } - } - - if(hrtf_userreq == Hrtf_Default) - { - bool usehrtf = (headphones && hrtf_appreq != Hrtf_Disable) || - (hrtf_appreq == Hrtf_Enable); - if(!usehrtf) goto no_hrtf; - - device->HrtfStatus = ALC_HRTF_ENABLED_SOFT; - if(headphones && hrtf_appreq != Hrtf_Disable) - device->HrtfStatus = ALC_HRTF_HEADPHONES_DETECTED_SOFT; - } - else - { - if(hrtf_userreq != Hrtf_Enable) - { - if(hrtf_appreq == Hrtf_Enable) - device->HrtfStatus = ALC_HRTF_DENIED_SOFT; - goto no_hrtf; - } - device->HrtfStatus = ALC_HRTF_REQUIRED_SOFT; - } - - if(device->HrtfList.empty()) - device->HrtfList = EnumerateHrtf(device->DeviceName.c_str()); - - if(hrtf_id >= 0 && static_cast(hrtf_id) < device->HrtfList.size()) - { - const std::string &hrtfname = device->HrtfList[static_cast(hrtf_id)]; - if(HrtfStorePtr hrtf{GetLoadedHrtf(hrtfname, device->Frequency)}) - { - device->mHrtf = std::move(hrtf); - device->HrtfName = hrtfname; - } - } - - if(!device->mHrtf) - { - for(const auto &hrtfname : device->HrtfList) - { - if(HrtfStorePtr hrtf{GetLoadedHrtf(hrtfname, device->Frequency)}) - { - device->mHrtf = std::move(hrtf); - device->HrtfName = hrtfname; - break; - } - } - } - - if(device->mHrtf) - { - old_hrtf = nullptr; - - HrtfStore *hrtf{device->mHrtf.get()}; - device->mIrSize = hrtf->irSize; - if(auto hrtfsizeopt = ConfigValueUInt(devname, nullptr, "hrtf-size")) - { - if(*hrtfsizeopt > 0 && *hrtfsizeopt < device->mIrSize) - device->mIrSize = maxu(*hrtfsizeopt, MinIrLength); - } - - InitHrtfPanning(device); - device->PostProcess = &ALCdevice::ProcessHrtf; - return; - } - device->HrtfStatus = ALC_HRTF_UNSUPPORTED_FORMAT_SOFT; - -no_hrtf: - old_hrtf = nullptr; - - device->mRenderMode = RenderMode::Pairwise; - - if(device->Type != DeviceType::Loopback) - { - if(auto cflevopt = ConfigValueInt(device->DeviceName.c_str(), nullptr, "cf_level")) - { - if(*cflevopt > 0 && *cflevopt <= 6) - { - device->Bs2b = std::make_unique(); - bs2b_set_params(device->Bs2b.get(), *cflevopt, - static_cast(device->Frequency)); - TRACE("BS2B enabled\n"); - InitPanning(device); - device->PostProcess = &ALCdevice::ProcessBs2b; - return; - } - } - } - - if(auto encopt = ConfigValueStr(device->DeviceName.c_str(), nullptr, "stereo-encoding")) - { - const char *mode{encopt->c_str()}; - if(al::strcasecmp(mode, "uhj") == 0) - device->mRenderMode = RenderMode::Normal; - else if(al::strcasecmp(mode, "panpot") != 0) - ERR("Unexpected stereo-encoding: %s\n", mode); - } - if(device->mRenderMode == RenderMode::Normal) - { - device->Uhj_Encoder = std::make_unique(); - TRACE("UHJ enabled\n"); - InitUhjPanning(device); - device->PostProcess = &ALCdevice::ProcessUhj; - return; - } - - TRACE("Stereo rendering\n"); - InitPanning(device); - device->PostProcess = &ALCdevice::ProcessAmbiDec; -} - - -void aluInitEffectPanning(EffectSlot *slot, ALCcontext *context) -{ - ALCdevice *device{context->mDevice.get()}; - const size_t count{AmbiChannelsFromOrder(device->mAmbiOrder)}; - - auto wetbuffer_iter = context->mWetBuffers.end(); - if(slot->mWetBuffer) - { - /* If the effect slot already has a wet buffer attached, allocate a new - * one in its place. - */ - wetbuffer_iter = context->mWetBuffers.begin(); - for(;wetbuffer_iter != context->mWetBuffers.end();++wetbuffer_iter) - { - if(wetbuffer_iter->get() == slot->mWetBuffer) - { - slot->mWetBuffer = nullptr; - slot->Wet.Buffer = {}; - - *wetbuffer_iter = WetBufferPtr{new(FamCount(count)) WetBuffer{count}}; - - break; - } - } - } - if(wetbuffer_iter == context->mWetBuffers.end()) - { - /* Otherwise, search for an unused wet buffer. */ - wetbuffer_iter = context->mWetBuffers.begin(); - for(;wetbuffer_iter != context->mWetBuffers.end();++wetbuffer_iter) - { - if(!(*wetbuffer_iter)->mInUse) - break; - } - if(wetbuffer_iter == context->mWetBuffers.end()) - { - /* Otherwise, allocate a new one to use. */ - context->mWetBuffers.emplace_back(WetBufferPtr{new(FamCount(count)) WetBuffer{count}}); - wetbuffer_iter = context->mWetBuffers.end()-1; - } - } - WetBuffer *wetbuffer{slot->mWetBuffer = wetbuffer_iter->get()}; - wetbuffer->mInUse = true; - - auto acnmap_begin = AmbiIndex::FromACN().begin(); - auto iter = std::transform(acnmap_begin, acnmap_begin + count, slot->Wet.AmbiMap.begin(), - [](const uint8_t &acn) noexcept -> BFChannelConfig - { return BFChannelConfig{1.0f, acn}; }); - std::fill(iter, slot->Wet.AmbiMap.end(), BFChannelConfig{}); - slot->Wet.Buffer = wetbuffer->mBuffer; -} - - -std::array CalcAmbiCoeffs(const float y, const float z, const float x, - const float spread) -{ - std::array coeffs; - - /* Zeroth-order */ - coeffs[0] = 1.0f; /* ACN 0 = 1 */ - /* First-order */ - coeffs[1] = 1.732050808f * y; /* ACN 1 = sqrt(3) * Y */ - coeffs[2] = 1.732050808f * z; /* ACN 2 = sqrt(3) * Z */ - coeffs[3] = 1.732050808f * x; /* ACN 3 = sqrt(3) * X */ - /* Second-order */ - const float xx{x*x}, yy{y*y}, zz{z*z}, xy{x*y}, yz{y*z}, xz{x*z}; - coeffs[4] = 3.872983346f * xy; /* ACN 4 = sqrt(15) * X * Y */ - coeffs[5] = 3.872983346f * yz; /* ACN 5 = sqrt(15) * Y * Z */ - coeffs[6] = 1.118033989f * (3.0f*zz - 1.0f); /* ACN 6 = sqrt(5)/2 * (3*Z*Z - 1) */ - coeffs[7] = 3.872983346f * xz; /* ACN 7 = sqrt(15) * X * Z */ - coeffs[8] = 1.936491673f * (xx - yy); /* ACN 8 = sqrt(15)/2 * (X*X - Y*Y) */ - /* Third-order */ - coeffs[9] = 2.091650066f * (y*(3.0f*xx - yy)); /* ACN 9 = sqrt(35/8) * Y * (3*X*X - Y*Y) */ - coeffs[10] = 10.246950766f * (z*xy); /* ACN 10 = sqrt(105) * Z * X * Y */ - coeffs[11] = 1.620185175f * (y*(5.0f*zz - 1.0f)); /* ACN 11 = sqrt(21/8) * Y * (5*Z*Z - 1) */ - coeffs[12] = 1.322875656f * (z*(5.0f*zz - 3.0f)); /* ACN 12 = sqrt(7)/2 * Z * (5*Z*Z - 3) */ - coeffs[13] = 1.620185175f * (x*(5.0f*zz - 1.0f)); /* ACN 13 = sqrt(21/8) * X * (5*Z*Z - 1) */ - coeffs[14] = 5.123475383f * (z*(xx - yy)); /* ACN 14 = sqrt(105)/2 * Z * (X*X - Y*Y) */ - coeffs[15] = 2.091650066f * (x*(xx - 3.0f*yy)); /* ACN 15 = sqrt(35/8) * X * (X*X - 3*Y*Y) */ - /* Fourth-order */ - /* ACN 16 = sqrt(35)*3/2 * X * Y * (X*X - Y*Y) */ - /* ACN 17 = sqrt(35/2)*3/2 * (3*X*X - Y*Y) * Y * Z */ - /* ACN 18 = sqrt(5)*3/2 * X * Y * (7*Z*Z - 1) */ - /* ACN 19 = sqrt(5/2)*3/2 * Y * Z * (7*Z*Z - 3) */ - /* ACN 20 = 3/8 * (35*Z*Z*Z*Z - 30*Z*Z + 3) */ - /* ACN 21 = sqrt(5/2)*3/2 * X * Z * (7*Z*Z - 3) */ - /* ACN 22 = sqrt(5)*3/4 * (X*X - Y*Y) * (7*Z*Z - 1) */ - /* ACN 23 = sqrt(35/2)*3/2 * (X*X - 3*Y*Y) * X * Z */ - /* ACN 24 = sqrt(35)*3/8 * (X*X*X*X - 6*X*X*Y*Y + Y*Y*Y*Y) */ - - if(spread > 0.0f) - { - /* Implement the spread by using a spherical source that subtends the - * angle spread. See: - * http://www.ppsloan.org/publications/StupidSH36.pdf - Appendix A3 - * - * When adjusted for N3D normalization instead of SN3D, these - * calculations are: - * - * ZH0 = -sqrt(pi) * (-1+ca); - * ZH1 = 0.5*sqrt(pi) * sa*sa; - * ZH2 = -0.5*sqrt(pi) * ca*(-1+ca)*(ca+1); - * ZH3 = -0.125*sqrt(pi) * (-1+ca)*(ca+1)*(5*ca*ca - 1); - * ZH4 = -0.125*sqrt(pi) * ca*(-1+ca)*(ca+1)*(7*ca*ca - 3); - * ZH5 = -0.0625*sqrt(pi) * (-1+ca)*(ca+1)*(21*ca*ca*ca*ca - 14*ca*ca + 1); - * - * The gain of the source is compensated for size, so that the - * loudness doesn't depend on the spread. Thus: - * - * ZH0 = 1.0f; - * ZH1 = 0.5f * (ca+1.0f); - * ZH2 = 0.5f * (ca+1.0f)*ca; - * ZH3 = 0.125f * (ca+1.0f)*(5.0f*ca*ca - 1.0f); - * ZH4 = 0.125f * (ca+1.0f)*(7.0f*ca*ca - 3.0f)*ca; - * ZH5 = 0.0625f * (ca+1.0f)*(21.0f*ca*ca*ca*ca - 14.0f*ca*ca + 1.0f); - */ - const float ca{std::cos(spread * 0.5f)}; - /* Increase the source volume by up to +3dB for a full spread. */ - const float scale{std::sqrt(1.0f + spread/al::MathDefs::Tau())}; - - const float ZH0_norm{scale}; - const float ZH1_norm{scale * 0.5f * (ca+1.f)}; - const float ZH2_norm{scale * 0.5f * (ca+1.f)*ca}; - const float ZH3_norm{scale * 0.125f * (ca+1.f)*(5.f*ca*ca-1.f)}; - - /* Zeroth-order */ - coeffs[0] *= ZH0_norm; - /* First-order */ - coeffs[1] *= ZH1_norm; - coeffs[2] *= ZH1_norm; - coeffs[3] *= ZH1_norm; - /* Second-order */ - coeffs[4] *= ZH2_norm; - coeffs[5] *= ZH2_norm; - coeffs[6] *= ZH2_norm; - coeffs[7] *= ZH2_norm; - coeffs[8] *= ZH2_norm; - /* Third-order */ - coeffs[9] *= ZH3_norm; - coeffs[10] *= ZH3_norm; - coeffs[11] *= ZH3_norm; - coeffs[12] *= ZH3_norm; - coeffs[13] *= ZH3_norm; - coeffs[14] *= ZH3_norm; - coeffs[15] *= ZH3_norm; - } - - return coeffs; -} - -void ComputePanGains(const MixParams *mix, const float*RESTRICT coeffs, const float ingain, - const al::span gains) -{ - auto ambimap = mix->AmbiMap.cbegin(); - - auto iter = std::transform(ambimap, ambimap+mix->Buffer.size(), gains.begin(), - [coeffs,ingain](const BFChannelConfig &chanmap) noexcept -> float - { return chanmap.Scale * coeffs[chanmap.Index] * ingain; } - ); - std::fill(iter, gains.end(), 0.0f); -} diff --git a/alc/uiddefs.cpp b/alc/uiddefs.cpp deleted file mode 100644 index 244c01a5..00000000 --- a/alc/uiddefs.cpp +++ /dev/null @@ -1,37 +0,0 @@ - -#include "config.h" - - -#ifndef AL_NO_UID_DEFS - -#if defined(HAVE_GUIDDEF_H) || defined(HAVE_INITGUID_H) -#define INITGUID -#include -#ifdef HAVE_GUIDDEF_H -#include -#else -#include -#endif - -DEFINE_GUID(KSDATAFORMAT_SUBTYPE_PCM, 0x00000001, 0x0000, 0x0010, 0x80,0x00, 0x00,0xaa,0x00,0x38,0x9b,0x71); -DEFINE_GUID(KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, 0x00000003, 0x0000, 0x0010, 0x80,0x00, 0x00,0xaa,0x00,0x38,0x9b,0x71); - -DEFINE_GUID(IID_IDirectSoundNotify, 0xb0210783, 0x89cd, 0x11d0, 0xaf,0x08, 0x00,0xa0,0xc9,0x25,0xcd,0x16); - -DEFINE_GUID(CLSID_MMDeviceEnumerator, 0xbcde0395, 0xe52f, 0x467c, 0x8e,0x3d, 0xc4,0x57,0x92,0x91,0x69,0x2e); -DEFINE_GUID(IID_IMMDeviceEnumerator, 0xa95664d2, 0x9614, 0x4f35, 0xa7,0x46, 0xde,0x8d,0xb6,0x36,0x17,0xe6); -DEFINE_GUID(IID_IAudioClient, 0x1cb9ad4c, 0xdbfa, 0x4c32, 0xb1,0x78, 0xc2,0xf5,0x68,0xa7,0x03,0xb2); -DEFINE_GUID(IID_IAudioRenderClient, 0xf294acfc, 0x3146, 0x4483, 0xa7,0xbf, 0xad,0xdc,0xa7,0xc2,0x60,0xe2); -DEFINE_GUID(IID_IAudioCaptureClient, 0xc8adbd64, 0xe71e, 0x48a0, 0xa4,0xde, 0x18,0x5c,0x39,0x5c,0xd3,0x17); - -#ifdef HAVE_WASAPI -#include -#include -#include -DEFINE_DEVPROPKEY(DEVPKEY_Device_FriendlyName, 0xa45c254e, 0xdf1c, 0x4efd, 0x80,0x20, 0x67,0xd1,0x46,0xa8,0x50,0xe0, 14); -DEFINE_PROPERTYKEY(PKEY_AudioEndpoint_FormFactor, 0x1da5d803, 0xd492, 0x4edd, 0x8c,0x23, 0xe0,0xc0,0xff,0xee,0x7f,0x0e, 0); -DEFINE_PROPERTYKEY(PKEY_AudioEndpoint_GUID, 0x1da5d803, 0xd492, 0x4edd, 0x8c, 0x23,0xe0, 0xc0,0xff,0xee,0x7f,0x0e, 4 ); -#endif -#endif - -#endif /* AL_NO_UID_DEFS */ diff --git a/alc/voice.cpp b/alc/voice.cpp deleted file mode 100644 index 47484452..00000000 --- a/alc/voice.cpp +++ /dev/null @@ -1,807 +0,0 @@ -/** - * OpenAL cross platform audio library - * Copyright (C) 1999-2007 by authors. - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - * Or go to http://www.gnu.org/copyleft/lgpl.html - */ - -#include "config.h" - -#include "voice.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "alcmain.h" -#include "albyte.h" -#include "alconfig.h" -#include "alcontext.h" -#include "alnumeric.h" -#include "aloptional.h" -#include "alspan.h" -#include "alstring.h" -#include "alu.h" -#include "async_event.h" -#include "buffer_storage.h" -#include "core/cpu_caps.h" -#include "core/devformat.h" -#include "core/filters/biquad.h" -#include "core/filters/nfc.h" -#include "core/filters/splitter.h" -#include "core/fmt_traits.h" -#include "core/logging.h" -#include "core/mixer/defs.h" -#include "core/mixer/hrtfdefs.h" -#include "hrtf.h" -#include "inprogext.h" -#include "opthelpers.h" -#include "ringbuffer.h" -#include "threads.h" -#include "vector.h" -#include "voice_change.h" - -struct CTag; -#ifdef HAVE_SSE -struct SSETag; -#endif -#ifdef HAVE_NEON -struct NEONTag; -#endif -struct CopyTag; - - -Resampler ResamplerDefault{Resampler::Linear}; - -MixerFunc MixSamples{Mix_}; - -namespace { - -using HrtfMixerFunc = void(*)(const float *InSamples, float2 *AccumSamples, const uint IrSize, - const MixHrtfFilter *hrtfparams, const size_t BufferSize); -using HrtfMixerBlendFunc = void(*)(const float *InSamples, float2 *AccumSamples, - const uint IrSize, const HrtfFilter *oldparams, const MixHrtfFilter *newparams, - const size_t BufferSize); - -HrtfMixerFunc MixHrtfSamples{MixHrtf_}; -HrtfMixerBlendFunc MixHrtfBlendSamples{MixHrtfBlend_}; - -inline MixerFunc SelectMixer() -{ -#ifdef HAVE_NEON - if((CPUCapFlags&CPU_CAP_NEON)) - return Mix_; -#endif -#ifdef HAVE_SSE - if((CPUCapFlags&CPU_CAP_SSE)) - return Mix_; -#endif - return Mix_; -} - -inline HrtfMixerFunc SelectHrtfMixer() -{ -#ifdef HAVE_NEON - if((CPUCapFlags&CPU_CAP_NEON)) - return MixHrtf_; -#endif -#ifdef HAVE_SSE - if((CPUCapFlags&CPU_CAP_SSE)) - return MixHrtf_; -#endif - return MixHrtf_; -} - -inline HrtfMixerBlendFunc SelectHrtfBlendMixer() -{ -#ifdef HAVE_NEON - if((CPUCapFlags&CPU_CAP_NEON)) - return MixHrtfBlend_; -#endif -#ifdef HAVE_SSE - if((CPUCapFlags&CPU_CAP_SSE)) - return MixHrtfBlend_; -#endif - return MixHrtfBlend_; -} - -} // namespace - - -void aluInitMixer() -{ - if(auto resopt = ConfigValueStr(nullptr, nullptr, "resampler")) - { - struct ResamplerEntry { - const char name[16]; - const Resampler resampler; - }; - constexpr ResamplerEntry ResamplerList[]{ - { "none", Resampler::Point }, - { "point", Resampler::Point }, - { "linear", Resampler::Linear }, - { "cubic", Resampler::Cubic }, - { "bsinc12", Resampler::BSinc12 }, - { "fast_bsinc12", Resampler::FastBSinc12 }, - { "bsinc24", Resampler::BSinc24 }, - { "fast_bsinc24", Resampler::FastBSinc24 }, - }; - - const char *str{resopt->c_str()}; - if(al::strcasecmp(str, "bsinc") == 0) - { - WARN("Resampler option \"%s\" is deprecated, using bsinc12\n", str); - str = "bsinc12"; - } - else if(al::strcasecmp(str, "sinc4") == 0 || al::strcasecmp(str, "sinc8") == 0) - { - WARN("Resampler option \"%s\" is deprecated, using cubic\n", str); - str = "cubic"; - } - - auto iter = std::find_if(std::begin(ResamplerList), std::end(ResamplerList), - [str](const ResamplerEntry &entry) -> bool - { return al::strcasecmp(str, entry.name) == 0; }); - if(iter == std::end(ResamplerList)) - ERR("Invalid resampler: %s\n", str); - else - ResamplerDefault = iter->resampler; - } - - MixSamples = SelectMixer(); - MixHrtfBlendSamples = SelectHrtfBlendMixer(); - MixHrtfSamples = SelectHrtfMixer(); -} - - -namespace { - -void SendSourceStoppedEvent(ALCcontext *context, uint id) -{ - RingBuffer *ring{context->mAsyncEvents.get()}; - auto evt_vec = ring->getWriteVector(); - if(evt_vec.first.len < 1) return; - - AsyncEvent *evt{::new(evt_vec.first.buf) AsyncEvent{EventType_SourceStateChange}}; - evt->u.srcstate.id = id; - evt->u.srcstate.state = VChangeState::Stop; - - ring->writeAdvance(1); -} - - -const float *DoFilters(BiquadFilter &lpfilter, BiquadFilter &hpfilter, float *dst, - const al::span src, int type) -{ - switch(type) - { - case AF_None: - lpfilter.clear(); - hpfilter.clear(); - break; - - case AF_LowPass: - lpfilter.process(src, dst); - hpfilter.clear(); - return dst; - case AF_HighPass: - lpfilter.clear(); - hpfilter.process(src, dst); - return dst; - - case AF_BandPass: - DualBiquad{lpfilter, hpfilter}.process(src, dst); - return dst; - } - return src.data(); -} - - -void LoadSamples(float *RESTRICT dst, const al::byte *src, const size_t srcstep, FmtType srctype, - const size_t samples) noexcept -{ -#define HANDLE_FMT(T) case T: al::LoadSampleArray(dst, src, srcstep, samples); break - switch(srctype) - { - HANDLE_FMT(FmtUByte); - HANDLE_FMT(FmtShort); - HANDLE_FMT(FmtFloat); - HANDLE_FMT(FmtDouble); - HANDLE_FMT(FmtMulaw); - HANDLE_FMT(FmtAlaw); - } -#undef HANDLE_FMT -} - -float *LoadBufferStatic(BufferlistItem *BufferListItem, BufferlistItem *&BufferLoopItem, - const size_t NumChannels, const size_t SampleSize, const size_t chan, size_t DataPosInt, - al::span SrcBuffer) -{ - const BufferStorage &Buffer = *BufferListItem->mBuffer; - const uint LoopStart{Buffer.mLoopStart}; - const uint LoopEnd{Buffer.mLoopEnd}; - ASSUME(LoopEnd > LoopStart); - - /* If current pos is beyond the loop range, do not loop */ - if(!BufferLoopItem || DataPosInt >= LoopEnd) - { - BufferLoopItem = nullptr; - - /* Load what's left to play from the buffer */ - const size_t DataRem{minz(SrcBuffer.size(), Buffer.mSampleLen-DataPosInt)}; - - const al::byte *Data{Buffer.mData.data()}; - Data += (DataPosInt*NumChannels + chan)*SampleSize; - - LoadSamples(SrcBuffer.data(), Data, NumChannels, Buffer.mType, DataRem); - SrcBuffer = SrcBuffer.subspan(DataRem); - } - else - { - /* Load what's left of this loop iteration */ - const size_t DataRem{minz(SrcBuffer.size(), LoopEnd-DataPosInt)}; - - const al::byte *Data{Buffer.mData.data()}; - Data += (DataPosInt*NumChannels + chan)*SampleSize; - - LoadSamples(SrcBuffer.data(), Data, NumChannels, Buffer.mType, DataRem); - SrcBuffer = SrcBuffer.subspan(DataRem); - - /* Load any repeats of the loop we can to fill the buffer. */ - const auto LoopSize = static_cast(LoopEnd - LoopStart); - while(!SrcBuffer.empty()) - { - const size_t DataSize{minz(SrcBuffer.size(), LoopSize)}; - - Data = Buffer.mData.data() + (LoopStart*NumChannels + chan)*SampleSize; - - LoadSamples(SrcBuffer.data(), Data, NumChannels, Buffer.mType, DataSize); - SrcBuffer = SrcBuffer.subspan(DataSize); - } - } - return SrcBuffer.begin(); -} - -float *LoadBufferCallback(BufferlistItem *BufferListItem, const size_t NumChannels, - const size_t SampleSize, const size_t chan, size_t NumCallbackSamples, - al::span SrcBuffer) -{ - const BufferStorage &Buffer = *BufferListItem->mBuffer; - - /* Load what's left to play from the buffer */ - const size_t DataRem{minz(SrcBuffer.size(), NumCallbackSamples)}; - - const al::byte *Data{Buffer.mData.data() + chan*SampleSize}; - - LoadSamples(SrcBuffer.data(), Data, NumChannels, Buffer.mType, DataRem); - SrcBuffer = SrcBuffer.subspan(DataRem); - - return SrcBuffer.begin(); -} - -float *LoadBufferQueue(BufferlistItem *BufferListItem, BufferlistItem *BufferLoopItem, - const size_t NumChannels, const size_t SampleSize, const size_t chan, size_t DataPosInt, - al::span SrcBuffer) -{ - /* Crawl the buffer queue to fill in the temp buffer */ - while(BufferListItem && !SrcBuffer.empty()) - { - BufferStorage *Buffer{BufferListItem->mBuffer}; - if(!(Buffer && DataPosInt < Buffer->mSampleLen)) - { - if(Buffer) DataPosInt -= Buffer->mSampleLen; - BufferListItem = BufferListItem->mNext.load(std::memory_order_acquire); - if(!BufferListItem) BufferListItem = BufferLoopItem; - continue; - } - - const size_t DataSize{minz(SrcBuffer.size(), Buffer->mSampleLen-DataPosInt)}; - - const al::byte *Data{Buffer->mData.data()}; - Data += (DataPosInt*NumChannels + chan)*SampleSize; - - LoadSamples(SrcBuffer.data(), Data, NumChannels, Buffer->mType, DataSize); - SrcBuffer = SrcBuffer.subspan(DataSize); - if(SrcBuffer.empty()) break; - - DataPosInt = 0; - BufferListItem = BufferListItem->mNext.load(std::memory_order_acquire); - if(!BufferListItem) BufferListItem = BufferLoopItem; - } - - return SrcBuffer.begin(); -} - - -void DoHrtfMix(const float *samples, const uint DstBufferSize, DirectParams &parms, - const float TargetGain, const uint Counter, uint OutPos, const uint IrSize, - ALCdevice *Device) -{ - auto &HrtfSamples = Device->HrtfSourceData; - /* Source HRTF mixing needs to include the direct delay so it remains - * aligned with the direct mix's HRTF filtering. - */ - float2 *AccumSamples{Device->HrtfAccumData + HrtfDirectDelay}; - - /* Copy the HRTF history and new input samples into a temp buffer. */ - auto src_iter = std::copy(parms.Hrtf.History.begin(), parms.Hrtf.History.end(), - std::begin(HrtfSamples)); - std::copy_n(samples, DstBufferSize, src_iter); - /* Copy the last used samples back into the history buffer for later. */ - std::copy_n(std::begin(HrtfSamples) + DstBufferSize, parms.Hrtf.History.size(), - parms.Hrtf.History.begin()); - - /* If fading and this is the first mixing pass, fade between the IRs. */ - uint fademix{0u}; - if(Counter && OutPos == 0) - { - fademix = minu(DstBufferSize, Counter); - - float gain{TargetGain}; - - /* The new coefficients need to fade in completely since they're - * replacing the old ones. To keep the gain fading consistent, - * interpolate between the old and new target gains given how much of - * the fade time this mix handles. - */ - if(Counter > fademix) - { - const float a{static_cast(fademix) / static_cast(Counter)}; - gain = lerp(parms.Hrtf.Old.Gain, TargetGain, a); - } - MixHrtfFilter hrtfparams; - hrtfparams.Coeffs = &parms.Hrtf.Target.Coeffs; - hrtfparams.Delay = parms.Hrtf.Target.Delay; - hrtfparams.Gain = 0.0f; - hrtfparams.GainStep = gain / static_cast(fademix); - - MixHrtfBlendSamples(HrtfSamples, AccumSamples+OutPos, IrSize, &parms.Hrtf.Old, &hrtfparams, - fademix); - /* Update the old parameters with the result. */ - parms.Hrtf.Old = parms.Hrtf.Target; - parms.Hrtf.Old.Gain = gain; - OutPos += fademix; - } - - if(fademix < DstBufferSize) - { - const uint todo{DstBufferSize - fademix}; - float gain{TargetGain}; - - /* Interpolate the target gain if the gain fading lasts longer than - * this mix. - */ - if(Counter > DstBufferSize) - { - const float a{static_cast(todo) / static_cast(Counter-fademix)}; - gain = lerp(parms.Hrtf.Old.Gain, TargetGain, a); - } - - MixHrtfFilter hrtfparams; - hrtfparams.Coeffs = &parms.Hrtf.Target.Coeffs; - hrtfparams.Delay = parms.Hrtf.Target.Delay; - hrtfparams.Gain = parms.Hrtf.Old.Gain; - hrtfparams.GainStep = (gain - parms.Hrtf.Old.Gain) / static_cast(todo); - MixHrtfSamples(HrtfSamples+fademix, AccumSamples+OutPos, IrSize, &hrtfparams, todo); - /* Store the now-current gain for next time. */ - parms.Hrtf.Old.Gain = gain; - } -} - -void DoNfcMix(const al::span samples, FloatBufferLine *OutBuffer, DirectParams &parms, - const float *TargetGains, const uint Counter, const uint OutPos, ALCdevice *Device) -{ - using FilterProc = void (NfcFilter::*)(const al::span, float*); - static constexpr FilterProc NfcProcess[MaxAmbiOrder+1]{ - nullptr, &NfcFilter::process1, &NfcFilter::process2, &NfcFilter::process3}; - - float *CurrentGains{parms.Gains.Current.data()}; - MixSamples(samples, {OutBuffer, 1u}, CurrentGains, TargetGains, Counter, OutPos); - ++OutBuffer; - ++CurrentGains; - ++TargetGains; - - const al::span nfcsamples{Device->NfcSampleData, samples.size()}; - size_t order{1}; - while(const size_t chancount{Device->NumChannelsPerOrder[order]}) - { - (parms.NFCtrlFilter.*NfcProcess[order])(samples, nfcsamples.data()); - MixSamples(nfcsamples, {OutBuffer, chancount}, CurrentGains, TargetGains, Counter, OutPos); - OutBuffer += chancount; - CurrentGains += chancount; - TargetGains += chancount; - if(++order == MaxAmbiOrder+1) - break; - } -} - -} // namespace - -void Voice::mix(const State vstate, ALCcontext *Context, const uint SamplesToDo) -{ - static constexpr std::array SilentTarget{}; - - ASSUME(SamplesToDo > 0); - - /* Get voice info */ - uint DataPosInt{mPosition.load(std::memory_order_relaxed)}; - uint DataPosFrac{mPositionFrac.load(std::memory_order_relaxed)}; - BufferlistItem *BufferListItem{mCurrentBuffer.load(std::memory_order_relaxed)}; - BufferlistItem *BufferLoopItem{mLoopBuffer.load(std::memory_order_relaxed)}; - const uint SampleSize{mSampleSize}; - const uint increment{mStep}; - if UNLIKELY(increment < 1) - { - /* If the voice is supposed to be stopping but can't be mixed, just - * stop it before bailing. - */ - if(vstate == Stopping) - mPlayState.store(Stopped, std::memory_order_release); - return; - } - - ASSUME(SampleSize > 0); - - const size_t FrameSize{mChans.size() * SampleSize}; - ASSUME(FrameSize > 0); - - ALCdevice *Device{Context->mDevice.get()}; - const uint NumSends{Device->NumAuxSends}; - const uint IrSize{Device->mIrSize}; - - ResamplerFunc Resample{(increment == MixerFracOne && DataPosFrac == 0) ? - Resample_ : mResampler}; - - uint Counter{(mFlags&VoiceIsFading) ? SamplesToDo : 0}; - if(!Counter) - { - /* No fading, just overwrite the old/current params. */ - for(auto &chandata : mChans) - { - { - DirectParams &parms = chandata.mDryParams; - if(!(mFlags&VoiceHasHrtf)) - parms.Gains.Current = parms.Gains.Target; - else - parms.Hrtf.Old = parms.Hrtf.Target; - } - for(uint send{0};send < NumSends;++send) - { - if(mSend[send].Buffer.empty()) - continue; - - SendParams &parms = chandata.mWetParams[send]; - parms.Gains.Current = parms.Gains.Target; - } - } - } - - float fadeCoeff{1.0f}, fadeGain{1.0f}; - if UNLIKELY(vstate == Stopping) - { - /* Calculate the multiplier for fading the resampled signal by -60dB - * over 1ms. - */ - fadeCoeff = std::pow(0.001f, 1000.0f/static_cast(Device->Frequency)); - } - - uint buffers_done{0u}; - uint OutPos{0u}; - do { - /* Figure out how many buffer samples will be needed */ - uint DstBufferSize{SamplesToDo - OutPos}; - uint SrcBufferSize; - - if(increment <= MixerFracOne) - { - /* Calculate the last written dst sample pos. */ - uint64_t DataSize64{DstBufferSize - 1}; - /* Calculate the last read src sample pos. */ - DataSize64 = (DataSize64*increment + DataPosFrac) >> MixerFracBits; - /* +1 to get the src sample count, include padding. */ - DataSize64 += 1 + MaxResamplerPadding; - - /* Result is guaranteed to be <= BufferLineSize+MaxResamplerPadding - * since we won't use more src samples than dst samples+padding. - */ - SrcBufferSize = static_cast(DataSize64); - } - else - { - uint64_t DataSize64{DstBufferSize}; - /* Calculate the end src sample pos, include padding. */ - DataSize64 = (DataSize64*increment + DataPosFrac) >> MixerFracBits; - DataSize64 += MaxResamplerPadding; - - if(DataSize64 <= BufferLineSize + MaxResamplerPadding) - SrcBufferSize = static_cast(DataSize64); - else - { - /* If the source size got saturated, we can't fill the desired - * dst size. Figure out how many samples we can actually mix. - */ - SrcBufferSize = BufferLineSize + MaxResamplerPadding; - - DataSize64 = SrcBufferSize - MaxResamplerPadding; - DataSize64 = ((DataSize64<(DataSize64) & ~3u; - } - } - } - - if((mFlags&(VoiceIsCallback|VoiceCallbackStopped)) == VoiceIsCallback && BufferListItem) - { - BufferStorage *buffer{BufferListItem->mBuffer}; - - /* Exclude resampler pre-padding from the needed size. */ - const uint toLoad{SrcBufferSize - (MaxResamplerPadding>>1)}; - if(toLoad > mNumCallbackSamples) - { - const size_t byteOffset{mNumCallbackSamples*FrameSize}; - const size_t needBytes{toLoad*FrameSize - byteOffset}; - - const int gotBytes{buffer->mCallback(buffer->mUserData, - &buffer->mData[byteOffset], static_cast(needBytes))}; - if(gotBytes < 1) - mFlags |= VoiceCallbackStopped; - else if(static_cast(gotBytes) < needBytes) - { - mFlags |= VoiceCallbackStopped; - mNumCallbackSamples += static_cast(static_cast(gotBytes) / - FrameSize); - } - else - mNumCallbackSamples = toLoad; - } - } - - const float fadeVal{fadeGain}; - const size_t num_chans{mChans.size()}; - size_t chan_idx{0}; - ASSUME(DstBufferSize > 0); - for(auto &chandata : mChans) - { - const al::span SrcData{Device->SourceData, SrcBufferSize}; - - /* Load the previous samples into the source data first, then load - * what we can from the buffer queue. - */ - auto srciter = std::copy_n(chandata.mPrevSamples.begin(), MaxResamplerPadding>>1, - SrcData.begin()); - - if UNLIKELY(!BufferListItem) - srciter = std::copy(chandata.mPrevSamples.begin()+(MaxResamplerPadding>>1), - chandata.mPrevSamples.end(), srciter); - else if((mFlags&VoiceIsStatic)) - srciter = LoadBufferStatic(BufferListItem, BufferLoopItem, num_chans, - SampleSize, chan_idx, DataPosInt, {srciter, SrcData.end()}); - else if((mFlags&VoiceIsCallback)) - srciter = LoadBufferCallback(BufferListItem, num_chans, SampleSize, chan_idx, - mNumCallbackSamples, {srciter, SrcData.end()}); - else - srciter = LoadBufferQueue(BufferListItem, BufferLoopItem, num_chans, - SampleSize, chan_idx, DataPosInt, {srciter, SrcData.end()}); - - if UNLIKELY(srciter != SrcData.end()) - { - /* If the source buffer wasn't filled, copy the last sample for - * the remaining buffer. Ideally it should have ended with - * silence, but if not the gain fading should help avoid clicks - * from sudden amplitude changes. - */ - const float sample{*(srciter-1)}; - std::fill(srciter, SrcData.end(), sample); - } - - /* Store the last source samples used for next time. */ - std::copy_n(&SrcData[(increment*DstBufferSize + DataPosFrac)>>MixerFracBits], - chandata.mPrevSamples.size(), chandata.mPrevSamples.begin()); - - /* Resample, then apply ambisonic upsampling as needed. */ - float *ResampledData{Resample(&mResampleState, &SrcData[MaxResamplerPadding>>1], - DataPosFrac, increment, {Device->ResampledData, DstBufferSize})}; - if((mFlags&VoiceIsAmbisonic)) - chandata.mAmbiSplitter.processHfScale({ResampledData, DstBufferSize}, - chandata.mAmbiScale); - - if UNLIKELY(vstate == Stopping) - { - fadeGain = fadeVal; - for(float &sample : al::span{ResampledData, DstBufferSize}) - { - fadeGain *= fadeCoeff; - sample *= fadeGain; - } - } - - /* Now filter and mix to the appropriate outputs. */ - float (&FilterBuf)[BufferLineSize] = Device->FilteredData; - { - DirectParams &parms = chandata.mDryParams; - const float *samples{DoFilters(parms.LowPass, parms.HighPass, FilterBuf, - {ResampledData, DstBufferSize}, mDirect.FilterType)}; - - if((mFlags&VoiceHasHrtf)) - { - const float TargetGain{UNLIKELY(vstate == Stopping) ? 0.0f : - parms.Hrtf.Target.Gain}; - DoHrtfMix(samples, DstBufferSize, parms, TargetGain, Counter, OutPos, IrSize, - Device); - } - else if((mFlags&VoiceHasNfc)) - { - const float *TargetGains{UNLIKELY(vstate == Stopping) ? SilentTarget.data() - : parms.Gains.Target.data()}; - DoNfcMix({samples, DstBufferSize}, mDirect.Buffer.data(), parms, TargetGains, - Counter, OutPos, Device); - } - else - { - const float *TargetGains{UNLIKELY(vstate == Stopping) ? SilentTarget.data() - : parms.Gains.Target.data()}; - MixSamples({samples, DstBufferSize}, mDirect.Buffer, - parms.Gains.Current.data(), TargetGains, Counter, OutPos); - } - } - - for(uint send{0};send < NumSends;++send) - { - if(mSend[send].Buffer.empty()) - continue; - - SendParams &parms = chandata.mWetParams[send]; - const float *samples{DoFilters(parms.LowPass, parms.HighPass, FilterBuf, - {ResampledData, DstBufferSize}, mSend[send].FilterType)}; - - const float *TargetGains{UNLIKELY(vstate == Stopping) ? SilentTarget.data() - : parms.Gains.Target.data()}; - MixSamples({samples, DstBufferSize}, mSend[send].Buffer, - parms.Gains.Current.data(), TargetGains, Counter, OutPos); - } - - ++chan_idx; - } - /* Update positions */ - DataPosFrac += increment*DstBufferSize; - const uint SrcSamplesDone{DataPosFrac>>MixerFracBits}; - DataPosInt += SrcSamplesDone; - DataPosFrac &= MixerFracMask; - - OutPos += DstBufferSize; - Counter = maxu(DstBufferSize, Counter) - DstBufferSize; - - if UNLIKELY(!BufferListItem) - { - /* Do nothing extra when there's no buffers. */ - } - else if((mFlags&VoiceIsStatic)) - { - if(BufferLoopItem) - { - /* Handle looping static source */ - const BufferStorage &Buffer = *BufferListItem->mBuffer; - const uint LoopStart{Buffer.mLoopStart}; - const uint LoopEnd{Buffer.mLoopEnd}; - if(DataPosInt >= LoopEnd) - { - assert(LoopEnd > LoopStart); - DataPosInt = ((DataPosInt-LoopStart)%(LoopEnd-LoopStart)) + LoopStart; - } - } - else - { - /* Handle non-looping static source */ - if(DataPosInt >= BufferListItem->mSampleLen) - { - BufferListItem = nullptr; - break; - } - } - } - else if((mFlags&VoiceIsCallback)) - { - BufferStorage &buffer = *BufferListItem->mBuffer; - if(SrcSamplesDone < mNumCallbackSamples) - { - const size_t byteOffset{SrcSamplesDone*FrameSize}; - const size_t byteEnd{mNumCallbackSamples*FrameSize}; - al::byte *data{buffer.mData.data()}; - std::copy(data+byteOffset, data+byteEnd, data); - mNumCallbackSamples -= SrcSamplesDone; - } - else - { - BufferListItem = nullptr; - mNumCallbackSamples = 0; - } - } - else - { - /* Handle streaming source */ - do { - if(BufferListItem->mSampleLen > DataPosInt) - break; - - DataPosInt -= BufferListItem->mSampleLen; - - ++buffers_done; - BufferListItem = BufferListItem->mNext.load(std::memory_order_relaxed); - if(!BufferListItem) BufferListItem = BufferLoopItem; - } while(BufferListItem); - } - } while(OutPos < SamplesToDo); - - mFlags |= VoiceIsFading; - - /* Don't update positions and buffers if we were stopping. */ - if UNLIKELY(vstate == Stopping) - { - mPlayState.store(Stopped, std::memory_order_release); - return; - } - - /* Capture the source ID in case it's reset for stopping. */ - const uint SourceID{mSourceID.load(std::memory_order_relaxed)}; - - /* Update voice info */ - mPosition.store(DataPosInt, std::memory_order_relaxed); - mPositionFrac.store(DataPosFrac, std::memory_order_relaxed); - mCurrentBuffer.store(BufferListItem, std::memory_order_relaxed); - if(!BufferListItem) - { - mLoopBuffer.store(nullptr, std::memory_order_relaxed); - mSourceID.store(0u, std::memory_order_relaxed); - } - std::atomic_thread_fence(std::memory_order_release); - - /* Send any events now, after the position/buffer info was updated. */ - const uint enabledevt{Context->mEnabledEvts.load(std::memory_order_acquire)}; - if(buffers_done > 0 && (enabledevt&EventType_BufferCompleted)) - { - RingBuffer *ring{Context->mAsyncEvents.get()}; - auto evt_vec = ring->getWriteVector(); - if(evt_vec.first.len > 0) - { - AsyncEvent *evt{::new(evt_vec.first.buf) AsyncEvent{EventType_BufferCompleted}}; - evt->u.bufcomp.id = SourceID; - evt->u.bufcomp.count = buffers_done; - ring->writeAdvance(1); - } - } - - if(!BufferListItem) - { - /* If the voice just ended, set it to Stopping so the next render - * ensures any residual noise fades to 0 amplitude. - */ - mPlayState.store(Stopping, std::memory_order_release); - if((enabledevt&EventType_SourceStateChange)) - SendSourceStoppedEvent(Context, SourceID); - } -} diff --git a/alc/voice.h b/alc/voice.h deleted file mode 100644 index 07260c3e..00000000 --- a/alc/voice.h +++ /dev/null @@ -1,224 +0,0 @@ -#ifndef VOICE_H -#define VOICE_H - -#include -#include - -#include "almalloc.h" -#include "alspan.h" -#include "alu.h" -#include "buffer_storage.h" -#include "core/bufferline.h" -#include "core/devformat.h" -#include "core/filters/biquad.h" -#include "core/filters/nfc.h" -#include "core/filters/splitter.h" -#include "core/mixer/defs.h" -#include "core/mixer/hrtfdefs.h" -#include "vector.h" - -struct ALCcontext; -struct EffectSlot; -enum class DistanceModel : unsigned char; - -using uint = unsigned int; - - -enum class SpatializeMode : unsigned char { - Off, - On, - Auto -}; - -enum class DirectMode : unsigned char { - Off, - DropMismatch, - RemixMismatch -}; - - -enum { - AF_None = 0, - AF_LowPass = 1, - AF_HighPass = 2, - AF_BandPass = AF_LowPass | AF_HighPass -}; - - -struct DirectParams { - BiquadFilter LowPass; - BiquadFilter HighPass; - - NfcFilter NFCtrlFilter; - - struct { - HrtfFilter Old; - HrtfFilter Target; - alignas(16) std::array History; - } Hrtf; - - struct { - std::array Current; - std::array Target; - } Gains; -}; - -struct SendParams { - BiquadFilter LowPass; - BiquadFilter HighPass; - - struct { - std::array Current; - std::array Target; - } Gains; -}; - - -struct VoiceProps { - float Pitch; - float Gain; - float OuterGain; - float MinGain; - float MaxGain; - float InnerAngle; - float OuterAngle; - float RefDistance; - float MaxDistance; - float RolloffFactor; - std::array Position; - std::array Velocity; - std::array Direction; - std::array OrientAt; - std::array OrientUp; - bool HeadRelative; - DistanceModel mDistanceModel; - Resampler mResampler; - DirectMode DirectChannels; - SpatializeMode mSpatializeMode; - - bool DryGainHFAuto; - bool WetGainAuto; - bool WetGainHFAuto; - float OuterGainHF; - - float AirAbsorptionFactor; - float RoomRolloffFactor; - float DopplerFactor; - - std::array StereoPan; - - float Radius; - - /** Direct filter and auxiliary send info. */ - struct { - float Gain; - float GainHF; - float HFReference; - float GainLF; - float LFReference; - } Direct; - struct SendData { - EffectSlot *Slot; - float Gain; - float GainHF; - float HFReference; - float GainLF; - float LFReference; - } Send[MAX_SENDS]; -}; - -struct VoicePropsItem : public VoiceProps { - std::atomic next{nullptr}; - - DEF_NEWDEL(VoicePropsItem) -}; - -constexpr uint VoiceIsStatic{ 1u<<0}; -constexpr uint VoiceIsCallback{ 1u<<1}; -constexpr uint VoiceIsAmbisonic{ 1u<<2}; /* Needs HF scaling for ambisonic upsampling. */ -constexpr uint VoiceCallbackStopped{1u<<3}; -constexpr uint VoiceIsFading{ 1u<<4}; /* Use gain stepping for smooth transitions. */ -constexpr uint VoiceHasHrtf{ 1u<<5}; -constexpr uint VoiceHasNfc{ 1u<<6}; - -struct Voice { - enum State { - Stopped, - Playing, - Stopping, - Pending - }; - - std::atomic mUpdate{nullptr}; - - VoiceProps mProps; - - std::atomic mSourceID{0u}; - std::atomic mPlayState{Stopped}; - std::atomic mPendingChange{false}; - - /** - * Source offset in samples, relative to the currently playing buffer, NOT - * the whole queue. - */ - std::atomic mPosition; - /** Fractional (fixed-point) offset to the next sample. */ - std::atomic mPositionFrac; - - /* Current buffer queue item being played. */ - std::atomic mCurrentBuffer; - - /* Buffer queue item to loop to at end of queue (will be NULL for non- - * looping voices). - */ - std::atomic mLoopBuffer; - - /* Properties for the attached buffer(s). */ - FmtChannels mFmtChannels; - uint mFrequency; - uint mSampleSize; - AmbiLayout mAmbiLayout; - AmbiScaling mAmbiScaling; - uint mAmbiOrder; - - /** Current target parameters used for mixing. */ - uint mStep{0}; - - ResamplerFunc mResampler; - - InterpState mResampleState; - - uint mFlags{}; - uint mNumCallbackSamples{0}; - - struct TargetData { - int FilterType; - al::span Buffer; - }; - TargetData mDirect; - std::array mSend; - - struct ChannelData { - alignas(16) std::array mPrevSamples; - - float mAmbiScale; - BandSplitter mAmbiSplitter; - - DirectParams mDryParams; - std::array mWetParams; - }; - al::vector mChans{2}; - - Voice() = default; - Voice(const Voice&) = delete; - ~Voice() { delete mUpdate.exchange(nullptr, std::memory_order_acq_rel); } - Voice& operator=(const Voice&) = delete; - - void mix(const State vstate, ALCcontext *Context, const uint SamplesToDo); - - DEF_NEWDEL(Voice) -}; - -extern Resampler ResamplerDefault; - -#endif /* VOICE_H */ diff --git a/alc/voice_change.h b/alc/voice_change.h deleted file mode 100644 index ddc6186f..00000000 --- a/alc/voice_change.h +++ /dev/null @@ -1,31 +0,0 @@ -#ifndef VOICE_CHANGE_H -#define VOICE_CHANGE_H - -#include - -#include "almalloc.h" - -struct Voice; - -using uint = unsigned int; - - -enum class VChangeState { - Reset, - Stop, - Play, - Pause, - Restart -}; -struct VoiceChange { - Voice *mOldVoice{nullptr}; - Voice *mVoice{nullptr}; - uint mSourceID{0}; - VChangeState mState{}; - - std::atomic mNext{nullptr}; - - DEF_NEWDEL(VoiceChange) -}; - -#endif /* VOICE_CHANGE_H */ diff --git a/alsoftrc.sample b/alsoftrc.sample deleted file mode 100644 index 3c964ada..00000000 --- a/alsoftrc.sample +++ /dev/null @@ -1,553 +0,0 @@ -# OpenAL config file. -# -# Option blocks may appear multiple times, and duplicated options will take the -# last value specified. Environment variables may be specified within option -# values, and are automatically substituted when the config file is loaded. -# Environment variable names may only contain alpha-numeric characters (a-z, -# A-Z, 0-9) and underscores (_), and are prefixed with $. For example, -# specifying "$HOME/file.ext" would typically result in something like -# "/home/user/file.ext". To specify an actual "$" character, use "$$". -# -# Device-specific values may be specified by including the device name in the -# block name, with "general" replaced by the device name. That is, general -# options for the device "Name of Device" would be in the [Name of Device] -# block, while ALSA options would be in the [alsa/Name of Device] block. -# Options marked as "(global)" are not influenced by the device. -# -# The system-wide settings can be put in /etc/openal/alsoft.conf and user- -# specific override settings in $HOME/.alsoftrc. -# For Windows, these settings should go into $AppData\alsoft.ini -# -# Option and block names are case-senstive. The supplied values are only hints -# and may not be honored (though generally it'll try to get as close as -# possible). Note: options that are left unset may default to app- or system- -# specified values. These are the current available settings: - -## -## General stuff -## -[general] - -## disable-cpu-exts: (global) -# Disables use of specialized methods that use specific CPU intrinsics. -# Certain methods may utilize CPU extensions for improved performance, and -# this option is useful for preventing some or all of those methods from being -# used. The available extensions are: sse, sse2, sse3, sse4.1, and neon. -# Specifying 'all' disables use of all such specialized methods. -#disable-cpu-exts = - -## drivers: (global) -# Sets the backend driver list order, comma-seperated. Unknown backends and -# duplicated names are ignored. Unlisted backends won't be considered for use -# unless the list is ended with a comma (e.g. 'oss,' will try OSS first before -# other backends, while 'oss' will try OSS only). Backends prepended with - -# won't be considered for use (e.g. '-oss,' will try all available backends -# except OSS). An empty list means to try all backends. -#drivers = - -## channels: -# Sets the output channel configuration. If left unspecified, one will try to -# be detected from the system, and defaulting to stereo. The available values -# are: mono, stereo, quad, surround51, surround51rear, surround61, surround71, -# ambi1, ambi2, ambi3. Note that the ambi* configurations provide ambisonic -# channels of the given order (using ACN ordering and SN3D normalization by -# default), which need to be decoded to play correctly on speakers. -#channels = - -## sample-type: -# Sets the output sample type. Currently, all mixing is done with 32-bit float -# and converted to the output sample type as needed. Available values are: -# int8 - signed 8-bit int -# uint8 - unsigned 8-bit int -# int16 - signed 16-bit int -# uint16 - unsigned 16-bit int -# int32 - signed 32-bit int -# uint32 - unsigned 32-bit int -# float32 - 32-bit float -#sample-type = float32 - -## frequency: -# Sets the output frequency. If left unspecified it will try to detect a -# default from the system, otherwise it will default to 44100. -#frequency = - -## period_size: -# Sets the update period size, in sample frames. This is the number of frames -# needed for each mixing update. Acceptable values range between 64 and 8192. -# If left unspecified it will default to 1/50th of the frequency (20ms, or 882 -# for 44100, 960 for 48000, etc). -#period_size = - -## periods: -# Sets the number of update periods. Higher values create a larger mix ahead, -# which helps protect against skips when the CPU is under load, but increases -# the delay between a sound getting mixed and being heard. Acceptable values -# range between 2 and 16. -#periods = 3 - -## stereo-mode: -# Specifies if stereo output is treated as being headphones or speakers. With -# headphones, HRTF or crossfeed filters may be used for better audio quality. -# Valid settings are auto, speakers, and headphones. -#stereo-mode = auto - -## stereo-encoding: -# Specifies the encoding method for non-HRTF stereo output. 'panpot' (default) -# uses standard amplitude panning (aka pair-wise, stereo pair, etc) between -# -30 and +30 degrees, while 'uhj' creates stereo-compatible two-channel UHJ -# output, which encodes some surround sound information into stereo output -# that can be decoded with a surround sound receiver. If crossfeed filters are -# used, UHJ is disabled. -#stereo-encoding = panpot - -## ambi-format: -# Specifies the channel order and normalization for the "ambi*" set of channel -# configurations. Valid settings are: fuma, ambix (or acn+sn3d), acn+n3d -#ambi-format = ambix - -## hrtf: -# Controls HRTF processing. These filters provide better spatialization of -# sounds while using headphones, but do require a bit more CPU power. While -# HRTF is used, the cf_level option is ignored. Setting this to auto (default) -# will allow HRTF to be used when headphones are detected or the app requests -# it, while setting true or false will forcefully enable or disable HRTF -# respectively. -#hrtf = auto - -## hrtf-mode: -# Specifies the rendering mode for HRTF processing. Setting the mode to full -# (default) applies a unique HRIR filter to each source given its relative -# location, providing the clearest directional response at the cost of the -# highest CPU usage. Setting the mode to ambi1, ambi2, or ambi3 will instead -# mix to a first-, second-, or third-order ambisonic buffer respectively, then -# decode that buffer with HRTF filters. Ambi1 has the lowest CPU usage, -# replacing the per-source HRIR filter for a simple 4-channel panning mix, but -# retains full 3D placement at the cost of a more diffuse response. Ambi2 and -# ambi3 increasingly improve the directional clarity, at the cost of more CPU -# usage (still less than "full", given some number of active sources). -#hrtf-mode = full - -## hrtf-size: -# Specifies the impulse response size, in samples, for the HRTF filter. Larger -# values increase the filter quality, while smaller values reduce processing -# cost. A value of 0 (default) uses the full filter size in the dataset, and -# the default dataset has a filter size of 32 samples at 44.1khz. -#hrtf-size = 0 - -## default-hrtf: -# Specifies the default HRTF to use. When multiple HRTFs are available, this -# determines the preferred one to use if none are specifically requested. Note -# that this is the enumerated HRTF name, not necessarily the filename. -#default-hrtf = - -## hrtf-paths: -# Specifies a comma-separated list of paths containing HRTF data sets. The -# format of the files are described in docs/hrtf.txt. The files within the -# directories must have the .mhr file extension to be recognized. By default, -# OS-dependent data paths will be used. They will also be used if the list -# ends with a comma. On Windows this is: -# $AppData\openal\hrtf -# And on other systems, it's (in order): -# $XDG_DATA_HOME/openal/hrtf (defaults to $HOME/.local/share/openal/hrtf) -# $XDG_DATA_DIRS/openal/hrtf (defaults to /usr/local/share/openal/hrtf and -# /usr/share/openal/hrtf) -#hrtf-paths = - -## cf_level: -# Sets the crossfeed level for stereo output. Valid values are: -# 0 - No crossfeed -# 1 - Low crossfeed -# 2 - Middle crossfeed -# 3 - High crossfeed (virtual speakers are closer to itself) -# 4 - Low easy crossfeed -# 5 - Middle easy crossfeed -# 6 - High easy crossfeed -# Users of headphones may want to try various settings. Has no effect on non- -# stereo modes. -#cf_level = 0 - -## resampler: (global) -# Selects the default resampler used when mixing sources. Valid values are: -# point - nearest sample, no interpolation -# linear - extrapolates samples using a linear slope between samples -# cubic - extrapolates samples using a Catmull-Rom spline -# bsinc12 - extrapolates samples using a band-limited Sinc filter (varying -# between 12 and 24 points, with anti-aliasing) -# fast_bsinc12 - same as bsinc12, except without interpolation between down- -# sampling scales -# bsinc24 - extrapolates samples using a band-limited Sinc filter (varying -# between 24 and 48 points, with anti-aliasing) -# fast_bsinc24 - same as bsinc24, except without interpolation between down- -# sampling scales -#resampler = linear - -## rt-prio: (global) -# Sets real-time priority for the mixing thread. Not all drivers may use this -# (eg. PortAudio) as they already control the priority of the mixing thread. -# 0 and negative values will disable it. Note that this may constitute a -# security risk since a real-time priority thread can indefinitely block -# normal-priority threads if it fails to wait. Disable this if it turns out to -# be a problem. -#rt-prio = 1 - -## sources: -# Sets the maximum number of allocatable sources. Lower values may help for -# systems with apps that try to play more sounds than the CPU can handle. -#sources = 256 - -## slots: -# Sets the maximum number of Auxiliary Effect Slots an app can create. A slot -# can use a non-negligible amount of CPU time if an effect is set on it even -# if no sources are feeding it, so this may help when apps use more than the -# system can handle. -#slots = 64 - -## sends: -# Limits the number of auxiliary sends allowed per source. Setting this higher -# than the default has no effect. -#sends = 6 - -## front-stablizer: -# Applies filters to "stablize" front sound imaging. A psychoacoustic method -# is used to generate a front-center channel signal from the front-left and -# front-right channels, improving the front response by reducing the combing -# artifacts and phase errors. Consequently, it will only work with channel -# configurations that include front-left, front-right, and front-center. -#front-stablizer = false - -## output-limiter: -# Applies a gain limiter on the final mixed output. This reduces the volume -# when the output samples would otherwise clamp, avoiding excessive clipping -# noise. -#output-limiter = true - -## dither: -# Applies dithering on the final mix, for 8- and 16-bit output by default. -# This replaces the distortion created by nearest-value quantization with low- -# level whitenoise. -#dither = true - -## dither-depth: -# Quantization bit-depth for dithered output. A value of 0 (or less) will -# match the output sample depth. For int32, uint32, and float32 output, 0 will -# disable dithering because they're at or beyond the rendered precision. The -# maximum dither depth is 24. -#dither-depth = 0 - -## volume-adjust: -# A global volume adjustment for source output, expressed in decibels. The -# value is logarithmic, so +6 will be a scale of (approximately) 2x, +12 will -# be a scale of 4x, etc. Similarly, -6 will be x1/2, and -12 is about x1/4. A -# value of 0 means no change. -#volume-adjust = 0 - -## excludefx: (global) -# Sets which effects to exclude, preventing apps from using them. This can -# help for apps that try to use effects which are too CPU intensive for the -# system to handle. Available effects are: eaxreverb,reverb,autowah,chorus, -# compressor,distortion,echo,equalizer,flanger,modulator,dedicated,pshifter, -# fshifter,vmorpher. -#excludefx = - -## default-reverb: (global) -# A reverb preset that applies by default to all sources on send 0 -# (applications that set their own slots on send 0 will override this). -# Available presets are: None, Generic, PaddedCell, Room, Bathroom, -# Livingroom, Stoneroom, Auditorium, ConcertHall, Cave, Arena, Hangar, -# CarpetedHallway, Hallway, StoneCorridor, Alley, Forest, City, Moutains, -# Quarry, Plain, ParkingLot, SewerPipe, Underwater, Drugged, Dizzy, Psychotic. -#default-reverb = - -## trap-alc-error: (global) -# Generates a SIGTRAP signal when an ALC device error is generated, on systems -# that support it. This helps when debugging, while trying to find the cause -# of a device error. On Windows, a breakpoint exception is generated. -#trap-alc-error = false - -## trap-al-error: (global) -# Generates a SIGTRAP signal when an AL context error is generated, on systems -# that support it. This helps when debugging, while trying to find the cause -# of a context error. On Windows, a breakpoint exception is generated. -#trap-al-error = false - -## -## Ambisonic decoder stuff -## -[decoder] - -## hq-mode: -# Enables a high-quality ambisonic decoder. This mode is capable of frequency- -# dependent processing, creating a better reproduction of 3D sound rendering -# over surround sound speakers. Enabling this also requires specifying decoder -# configuration files for the appropriate speaker configuration you intend to -# use (see the quad, surround51, etc options below). Currently, up to third- -# order decoding is supported. -#hq-mode = true - -## distance-comp: -# Enables compensation for the speakers' relative distances to the listener. -# This applies the necessary delays and attenuation to make the speakers -# behave as though they are all equidistant, which is important for proper -# playback of 3D sound rendering. Requires the proper distances to be -# specified in the decoder configuration file. -#distance-comp = true - -## nfc: -# Enables near-field control filters. This simulates and compensates for low- -# frequency effects caused by the curvature of nearby sound-waves, which -# creates a more realistic perception of sound distance. Note that the effect -# may be stronger or weaker than intended if the application doesn't use or -# specify an appropriate unit scale, or if incorrect speaker distances are set -# in the decoder configuration file. -#nfc = false - -## nfc-ref-delay -# Specifies the reference delay value for ambisonic output when NFC filters -# are enabled. If channels is set to one of the ambi* formats, this option -# enables NFC-HOA output with the specified Reference Delay parameter. The -# specified value can then be shared with an appropriate NFC-HOA decoder to -# reproduce correct near-field effects. Keep in mind that despite being -# designed for higher-order ambisonics, this also applies to first-order -# output. When left unset, normal output is created with no near-field -# simulation. Requires the nfc option to also be enabled. -#nfc-ref-delay = - -## quad: -# Decoder configuration file for Quadraphonic channel output. See -# docs/ambdec.txt for a description of the file format. -#quad = - -## surround51: -# Decoder configuration file for 5.1 Surround (Side and Rear) channel output. -# See docs/ambdec.txt for a description of the file format. -#surround51 = - -## surround61: -# Decoder configuration file for 6.1 Surround channel output. See -# docs/ambdec.txt for a description of the file format. -#surround61 = - -## surround71: -# Decoder configuration file for 7.1 Surround channel output. See -# docs/ambdec.txt for a description of the file format. Note: This can be used -# to enable 3D7.1 with the appropriate configuration and speaker placement, -# see docs/3D7.1.txt. -#surround71 = - -## -## Reverb effect stuff (includes EAX reverb) -## -[reverb] - -## boost: (global) -# A global amplification for reverb output, expressed in decibels. The value -# is logarithmic, so +6 will be a scale of (approximately) 2x, +12 will be a -# scale of 4x, etc. Similarly, -6 will be about half, and -12 about 1/4th. A -# value of 0 means no change. -#boost = 0 - -## -## PulseAudio backend stuff -## -[pulse] - -## spawn-server: (global) -# Attempts to autospawn a PulseAudio server whenever needed (initializing the -# backend, enumerating devices, etc). Setting autospawn to false in Pulse's -# client.conf will still prevent autospawning even if this is set to true. -#spawn-server = true - -## allow-moves: (global) -# Allows PulseAudio to move active streams to different devices. Note that the -# device specifier (seen by applications) will not be updated when this -# occurs, and neither will the AL device configuration (sample rate, format, -# etc). -#allow-moves = true - -## fix-rate: -# Specifies whether to match the playback stream's sample rate to the device's -# sample rate. Enabling this forces OpenAL Soft to mix sources and effects -# directly to the actual output rate, avoiding a second resample pass by the -# PulseAudio server. -#fix-rate = false - -## adjust-latency: -# Attempts to adjust the overall latency of device playback. Note that this -# may have adverse effects on the resulting internal buffer sizes and mixing -# updates, leading to performance problems and drop-outs. However, if the -# PulseAudio server is creating a lot of latency, enabling this may help make -# it more manageable. -#adjust-latency = false - -## -## ALSA backend stuff -## -[alsa] - -## device: (global) -# Sets the device name for the default playback device. -#device = default - -## device-prefix: (global) -# Sets the prefix used by the discovered (non-default) playback devices. This -# will be appended with "CARD=c,DEV=d", where c is the card id and d is the -# device index for the requested device name. -#device-prefix = plughw: - -## device-prefix-*: (global) -# Card- and device-specific prefixes may be used to override the device-prefix -# option. The option may specify the card id (eg, device-prefix-NVidia), or -# the card id and device index (eg, device-prefix-NVidia-0). The card id is -# case-sensitive. -#device-prefix- = - -## custom-devices: (global) -# Specifies a list of enumerated playback devices and the ALSA devices they -# refer to. The list pattern is "Display Name=ALSA device;...". The display -# names will be returned for device enumeration, and the ALSA device is the -# device name to open for each enumerated device. -#custom-devices = - -## capture: (global) -# Sets the device name for the default capture device. -#capture = default - -## capture-prefix: (global) -# Sets the prefix used by the discovered (non-default) capture devices. This -# will be appended with "CARD=c,DEV=d", where c is the card id and d is the -# device number for the requested device name. -#capture-prefix = plughw: - -## capture-prefix-*: (global) -# Card- and device-specific prefixes may be used to override the -# capture-prefix option. The option may specify the card id (eg, -# capture-prefix-NVidia), or the card id and device index (eg, -# capture-prefix-NVidia-0). The card id is case-sensitive. -#capture-prefix- = - -## custom-captures: (global) -# Specifies a list of enumerated capture devices and the ALSA devices they -# refer to. The list pattern is "Display Name=ALSA device;...". The display -# names will be returned for device enumeration, and the ALSA device is the -# device name to open for each enumerated device. -#custom-captures = - -## mmap: -# Sets whether to try using mmap mode (helps reduce latencies and CPU -# consumption). If mmap isn't available, it will automatically fall back to -# non-mmap mode. True, yes, on, and non-0 values will attempt to use mmap. 0 -# and anything else will force mmap off. -#mmap = true - -## allow-resampler: -# Specifies whether to allow ALSA's built-in resampler. Enabling this will -# allow the playback device to be set to a different sample rate than the -# actual output, causing ALSA to apply its own resampling pass after OpenAL -# Soft resamples and mixes the sources and effects for output. -#allow-resampler = false - -## -## OSS backend stuff -## -[oss] - -## device: (global) -# Sets the device name for OSS output. -#device = /dev/dsp - -## capture: (global) -# Sets the device name for OSS capture. -#capture = /dev/dsp - -## -## Solaris backend stuff -## -[solaris] - -## device: (global) -# Sets the device name for Solaris output. -#device = /dev/audio - -## -## QSA backend stuff -## -[qsa] - -## -## JACK backend stuff -## -[jack] - -## spawn-server: (global) -# Attempts to autospawn a JACK server whenever needed (initializing the -# backend, opening devices, etc). -#spawn-server = false - -## custom-devices: (global) -# Specifies a list of enumerated devices and the ports they connect to. The -# list pattern is "Display Name=ports regex;Display Name=ports regex;...". The -# display names will be returned for device enumeration, and the ports regex -# is the regular expression to identify the target ports on the server (as -# given by the jack_get_ports function) for each enumerated device. -#custom-devices = - -## connect-ports: -# Attempts to automatically connect the client ports to physical server ports. -# Client ports that fail to connect will leave the remaining channels -# unconnected and silent (the device format won't change to accommodate). -#connect-ports = true - -## buffer-size: -# Sets the update buffer size, in samples, that the backend will keep buffered -# to handle the server's real-time processing requests. This value must be a -# power of 2, or else it will be rounded up to the next power of 2. If it is -# less than JACK's buffer update size, it will be clamped. This option may -# be useful in case the server's update size is too small and doesn't give the -# mixer time to keep enough audio available for the processing requests. -#buffer-size = 0 - -## -## WASAPI backend stuff -## -[wasapi] - -## -## DirectSound backend stuff -## -[dsound] - -## -## Windows Multimedia backend stuff -## -[winmm] - -## -## PortAudio backend stuff -## -[port] - -## device: (global) -# Sets the device index for output. Negative values will use the default as -# given by PortAudio itself. -#device = -1 - -## capture: (global) -# Sets the device index for capture. Negative values will use the default as -# given by PortAudio itself. -#capture = -1 - -## -## Wave File Writer stuff -## -[wave] - -## file: (global) -# Sets the filename of the wave file to write to. An empty name prevents the -# backend from opening, even when explicitly requested. -# THIS WILL OVERWRITE EXISTING FILES WITHOUT QUESTION! -#file = - -## bformat: (global) -# Creates AMB format files using first-order ambisonics instead of a standard -# single- or multi-channel .wav file. -#bformat = false diff --git a/appveyor.yml b/appveyor.yml deleted file mode 100644 index e54760b2..00000000 --- a/appveyor.yml +++ /dev/null @@ -1,15 +0,0 @@ -version: 1.21.0.{build} - -environment: - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017 - GEN: "Visual Studio 15 2017" - matrix: - - ARCH: Win32 - CFG: Release - - ARCH: x64 - CFG: Release - -build_script: - - cd build - - cmake -G "%GEN%" -A %ARCH% -DALSOFT_BUILD_ROUTER=ON -DALSOFT_REQUIRE_WINMM=ON -DALSOFT_REQUIRE_DSOUND=ON -DALSOFT_REQUIRE_WASAPI=ON -DALSOFT_EMBED_HRTF_DATA=YES .. - - cmake --build . --config %CFG% --clean-first diff --git a/build/.empty b/build/.empty deleted file mode 100644 index e69de29b..00000000 diff --git a/cmake/FindALSA.cmake b/cmake/FindALSA.cmake deleted file mode 100644 index 519304d6..00000000 --- a/cmake/FindALSA.cmake +++ /dev/null @@ -1,73 +0,0 @@ -# - Find alsa -# Find the alsa libraries (asound) -# -# This module defines the following variables: -# ALSA_FOUND - True if ALSA_INCLUDE_DIR & ALSA_LIBRARY are found -# ALSA_LIBRARIES - Set when ALSA_LIBRARY is found -# ALSA_INCLUDE_DIRS - Set when ALSA_INCLUDE_DIR is found -# -# ALSA_INCLUDE_DIR - where to find asoundlib.h, etc. -# ALSA_LIBRARY - the asound library -# ALSA_VERSION_STRING - the version of alsa found (since CMake 2.8.8) -# - -#============================================================================= -# Copyright 2009-2011 Kitware, Inc. -# Copyright 2009-2011 Philip Lowman -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# -# * Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# * The names of Kitware, Inc., the Insight Consortium, or the names of -# any consortium members, or of any contributors, may not be used to -# endorse or promote products derived from this software without -# specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS'' -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR -# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#============================================================================= - -find_path(ALSA_INCLUDE_DIR NAMES alsa/asoundlib.h - DOC "The ALSA (asound) include directory" -) - -find_library(ALSA_LIBRARY NAMES asound - DOC "The ALSA (asound) library" -) - -if(ALSA_INCLUDE_DIR AND EXISTS "${ALSA_INCLUDE_DIR}/alsa/version.h") - file(STRINGS "${ALSA_INCLUDE_DIR}/alsa/version.h" alsa_version_str REGEX "^#define[\t ]+SND_LIB_VERSION_STR[\t ]+\".*\"") - - string(REGEX REPLACE "^.*SND_LIB_VERSION_STR[\t ]+\"([^\"]*)\".*$" "\\1" ALSA_VERSION_STRING "${alsa_version_str}") - unset(alsa_version_str) -endif() - -# handle the QUIETLY and REQUIRED arguments and set ALSA_FOUND to TRUE if -# all listed variables are TRUE -include(FindPackageHandleStandardArgs) -find_package_handle_standard_args(ALSA - REQUIRED_VARS ALSA_LIBRARY ALSA_INCLUDE_DIR - VERSION_VAR ALSA_VERSION_STRING) - -if(ALSA_FOUND) - set( ALSA_LIBRARIES ${ALSA_LIBRARY} ) - set( ALSA_INCLUDE_DIRS ${ALSA_INCLUDE_DIR} ) -endif() - -mark_as_advanced(ALSA_INCLUDE_DIR ALSA_LIBRARY) diff --git a/cmake/FindAudioIO.cmake b/cmake/FindAudioIO.cmake deleted file mode 100644 index f0f8b2a5..00000000 --- a/cmake/FindAudioIO.cmake +++ /dev/null @@ -1,21 +0,0 @@ -# - Find AudioIO includes and libraries -# -# AUDIOIO_FOUND - True if AUDIOIO_INCLUDE_DIR is found -# AUDIOIO_INCLUDE_DIRS - Set when AUDIOIO_INCLUDE_DIR is found -# -# AUDIOIO_INCLUDE_DIR - where to find sys/audioio.h, etc. -# - -find_path(AUDIOIO_INCLUDE_DIR - NAMES sys/audioio.h - DOC "The AudioIO include directory" -) - -include(FindPackageHandleStandardArgs) -find_package_handle_standard_args(AudioIO REQUIRED_VARS AUDIOIO_INCLUDE_DIR) - -if(AUDIOIO_FOUND) - set(AUDIOIO_INCLUDE_DIRS ${AUDIOIO_INCLUDE_DIR}) -endif() - -mark_as_advanced(AUDIOIO_INCLUDE_DIR) diff --git a/cmake/FindFFmpeg.cmake b/cmake/FindFFmpeg.cmake deleted file mode 100644 index 60ca68fd..00000000 --- a/cmake/FindFFmpeg.cmake +++ /dev/null @@ -1,171 +0,0 @@ -# vim: ts=2 sw=2 -# - Try to find the required ffmpeg components(default: AVFORMAT, AVUTIL, AVCODEC) -# -# Once done this will define -# FFMPEG_FOUND - System has the all required components. -# FFMPEG_INCLUDE_DIRS - Include directory necessary for using the required components headers. -# FFMPEG_LIBRARIES - Link these to use the required ffmpeg components. -# FFMPEG_DEFINITIONS - Compiler switches required for using the required ffmpeg components. -# -# For each of the components it will additionaly set. -# - AVCODEC -# - AVDEVICE -# - AVFORMAT -# - AVUTIL -# - POSTPROC -# - SWSCALE -# - SWRESAMPLE -# the following variables will be defined -# _FOUND - System has -# _INCLUDE_DIRS - Include directory necessary for using the headers -# _LIBRARIES - Link these to use -# _DEFINITIONS - Compiler switches required for using -# _VERSION - The components version -# -# Copyright (c) 2006, Matthias Kretz, -# Copyright (c) 2008, Alexander Neundorf, -# Copyright (c) 2011, Michael Jansen, -# -# Redistribution and use is allowed according to the terms of the BSD license. - -include(FindPackageHandleStandardArgs) - -if(NOT FFmpeg_FIND_COMPONENTS) - set(FFmpeg_FIND_COMPONENTS AVFORMAT AVCODEC AVUTIL) -endif() - -# -### Macro: set_component_found -# -# Marks the given component as found if both *_LIBRARIES AND *_INCLUDE_DIRS is present. -# -macro(set_component_found _component) - if(${_component}_LIBRARIES AND ${_component}_INCLUDE_DIRS) - # message(STATUS " - ${_component} found.") - set(${_component}_FOUND TRUE) - else() - # message(STATUS " - ${_component} not found.") - endif() -endmacro() - -# -### Macro: find_component -# -# Checks for the given component by invoking pkgconfig and then looking up the libraries and -# include directories. -# -macro(find_component _component _pkgconfig _library _header) - if(NOT WIN32) - # use pkg-config to get the directories and then use these values - # in the FIND_PATH() and FIND_LIBRARY() calls - find_package(PkgConfig) - if(PKG_CONFIG_FOUND) - pkg_check_modules(PC_${_component} ${_pkgconfig}) - endif() - endif() - - find_path(${_component}_INCLUDE_DIRS ${_header} - HINTS - ${FFMPEGSDK_INC} - ${PC_LIB${_component}_INCLUDEDIR} - ${PC_LIB${_component}_INCLUDE_DIRS} - PATH_SUFFIXES - ffmpeg - ) - - find_library(${_component}_LIBRARIES NAMES ${_library} - HINTS - ${FFMPEGSDK_LIB} - ${PC_LIB${_component}_LIBDIR} - ${PC_LIB${_component}_LIBRARY_DIRS} - ) - - STRING(REGEX REPLACE "/.*" "/version.h" _ver_header ${_header}) - if(EXISTS "${${_component}_INCLUDE_DIRS}/${_ver_header}") - file(STRINGS "${${_component}_INCLUDE_DIRS}/${_ver_header}" version_str REGEX "^#define[\t ]+LIB${_component}_VERSION_M.*") - - string(REGEX REPLACE "^.*LIB${_component}_VERSION_MAJOR[\t ]+([0-9]*).*$" "\\1" version_maj "${version_str}") - string(REGEX REPLACE "^.*LIB${_component}_VERSION_MINOR[\t ]+([0-9]*).*$" "\\1" version_min "${version_str}") - string(REGEX REPLACE "^.*LIB${_component}_VERSION_MICRO[\t ]+([0-9]*).*$" "\\1" version_mic "${version_str}") - unset(version_str) - - set(${_component}_VERSION "${version_maj}.${version_min}.${version_mic}" CACHE STRING "The ${_component} version number.") - unset(version_maj) - unset(version_min) - unset(version_mic) - endif(EXISTS "${${_component}_INCLUDE_DIRS}/${_ver_header}") - set(${_component}_VERSION ${PC_${_component}_VERSION} CACHE STRING "The ${_component} version number.") - set(${_component}_DEFINITIONS ${PC_${_component}_CFLAGS_OTHER} CACHE STRING "The ${_component} CFLAGS.") - - set_component_found(${_component}) - - mark_as_advanced( - ${_component}_INCLUDE_DIRS - ${_component}_LIBRARIES - ${_component}_DEFINITIONS - ${_component}_VERSION) -endmacro() - - -set(FFMPEGSDK $ENV{FFMPEG_HOME}) -if(FFMPEGSDK) - set(FFMPEGSDK_INC "${FFMPEGSDK}/include") - set(FFMPEGSDK_LIB "${FFMPEGSDK}/lib") -endif() - -# Check for all possible components. -find_component(AVCODEC libavcodec avcodec libavcodec/avcodec.h) -find_component(AVFORMAT libavformat avformat libavformat/avformat.h) -find_component(AVDEVICE libavdevice avdevice libavdevice/avdevice.h) -find_component(AVUTIL libavutil avutil libavutil/avutil.h) -find_component(SWSCALE libswscale swscale libswscale/swscale.h) -find_component(SWRESAMPLE libswresample swresample libswresample/swresample.h) -find_component(POSTPROC libpostproc postproc libpostproc/postprocess.h) - -# Check if the required components were found and add their stuff to the FFMPEG_* vars. -foreach(_component ${FFmpeg_FIND_COMPONENTS}) - if(${_component}_FOUND) - # message(STATUS "Required component ${_component} present.") - set(FFMPEG_LIBRARIES ${FFMPEG_LIBRARIES} ${${_component}_LIBRARIES}) - set(FFMPEG_DEFINITIONS ${FFMPEG_DEFINITIONS} ${${_component}_DEFINITIONS}) - list(APPEND FFMPEG_INCLUDE_DIRS ${${_component}_INCLUDE_DIRS}) - else() - # message(STATUS "Required component ${_component} missing.") - endif() -endforeach() - -# Add libz if it exists (needed for static ffmpeg builds) -find_library(_FFmpeg_HAVE_LIBZ NAMES z) -if(_FFmpeg_HAVE_LIBZ) - set(FFMPEG_LIBRARIES ${FFMPEG_LIBRARIES} ${_FFmpeg_HAVE_LIBZ}) -endif() - -# Build the include path and library list with duplicates removed. -if(FFMPEG_INCLUDE_DIRS) - list(REMOVE_DUPLICATES FFMPEG_INCLUDE_DIRS) -endif() - -if(FFMPEG_LIBRARIES) - list(REMOVE_DUPLICATES FFMPEG_LIBRARIES) -endif() - -# cache the vars. -set(FFMPEG_INCLUDE_DIRS ${FFMPEG_INCLUDE_DIRS} CACHE STRING "The FFmpeg include directories." FORCE) -set(FFMPEG_LIBRARIES ${FFMPEG_LIBRARIES} CACHE STRING "The FFmpeg libraries." FORCE) -set(FFMPEG_DEFINITIONS ${FFMPEG_DEFINITIONS} CACHE STRING "The FFmpeg cflags." FORCE) - -mark_as_advanced(FFMPEG_INCLUDE_DIRS FFMPEG_LIBRARIES FFMPEG_DEFINITIONS) - -# Now set the noncached _FOUND vars for the components. -foreach(_component AVCODEC AVDEVICE AVFORMAT AVUTIL POSTPROCESS SWRESAMPLE SWSCALE) - set_component_found(${_component}) -endforeach () - -# Compile the list of required vars -set(_FFmpeg_REQUIRED_VARS FFMPEG_LIBRARIES FFMPEG_INCLUDE_DIRS) -foreach(_component ${FFmpeg_FIND_COMPONENTS}) - list(APPEND _FFmpeg_REQUIRED_VARS ${_component}_LIBRARIES ${_component}_INCLUDE_DIRS) -endforeach() - -# Give a nice error message if some of the required vars are missing. -find_package_handle_standard_args(FFmpeg DEFAULT_MSG ${_FFmpeg_REQUIRED_VARS}) diff --git a/cmake/FindJACK.cmake b/cmake/FindJACK.cmake deleted file mode 100644 index b72fe3f9..00000000 --- a/cmake/FindJACK.cmake +++ /dev/null @@ -1,60 +0,0 @@ -# - Find JACK -# Find the JACK libraries -# -# This module defines the following variables: -# JACK_FOUND - True if JACK_INCLUDE_DIR & JACK_LIBRARY are found -# JACK_INCLUDE_DIRS - where to find jack.h, etc. -# JACK_LIBRARIES - the jack library -# - -#============================================================================= -# Copyright 2009-2011 Kitware, Inc. -# Copyright 2009-2011 Philip Lowman -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# -# * Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# * The names of Kitware, Inc., the Insight Consortium, or the names of -# any consortium members, or of any contributors, may not be used to -# endorse or promote products derived from this software without -# specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS'' -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR -# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#============================================================================= - -find_path(JACK_INCLUDE_DIR NAMES jack/jack.h - DOC "The JACK include directory" -) - -find_library(JACK_LIBRARY NAMES jack - DOC "The JACK library" -) - -# handle the QUIETLY and REQUIRED arguments and set JACK_FOUND to TRUE if -# all listed variables are TRUE -include(FindPackageHandleStandardArgs) -find_package_handle_standard_args(JACK REQUIRED_VARS JACK_LIBRARY JACK_INCLUDE_DIR) - -if(JACK_FOUND) - set(JACK_LIBRARIES ${JACK_LIBRARY}) - set(JACK_INCLUDE_DIRS ${JACK_INCLUDE_DIR}) -endif() - -mark_as_advanced(JACK_INCLUDE_DIR JACK_LIBRARY) diff --git a/cmake/FindMySOFA.cmake b/cmake/FindMySOFA.cmake deleted file mode 100644 index 7d485c35..00000000 --- a/cmake/FindMySOFA.cmake +++ /dev/null @@ -1,81 +0,0 @@ -# - Find MySOFA -# Find the MySOFA libraries -# -# This module defines the following variables: -# MYSOFA_FOUND - True if MYSOFA_INCLUDE_DIR & MYSOFA_LIBRARY are found -# MYSOFA_INCLUDE_DIRS - where to find mysofa.h, etc. -# MYSOFA_LIBRARIES - the MySOFA library -# - -#============================================================================= -# Copyright 2009-2011 Kitware, Inc. -# Copyright 2009-2011 Philip Lowman -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# -# * Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# * The names of Kitware, Inc., the Insight Consortium, or the names of -# any consortium members, or of any contributors, may not be used to -# endorse or promote products derived from this software without -# specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS'' -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR -# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#============================================================================= - -find_package(ZLIB) - -find_path(MYSOFA_INCLUDE_DIR NAMES mysofa.h - DOC "The MySOFA include directory" -) - -find_library(MYSOFA_LIBRARY NAMES mysofa - DOC "The MySOFA library" -) - -find_library(MYSOFA_M_LIBRARY NAMES m - DOC "The math library for MySOFA" -) - -# handle the QUIETLY and REQUIRED arguments and set MYSOFA_FOUND to TRUE if -# all listed variables are TRUE -include(FindPackageHandleStandardArgs) -find_package_handle_standard_args(MySOFA REQUIRED_VARS MYSOFA_LIBRARY MYSOFA_INCLUDE_DIR ZLIB_FOUND) - -if(MYSOFA_FOUND) - set(MYSOFA_INCLUDE_DIRS ${MYSOFA_INCLUDE_DIR}) - set(MYSOFA_LIBRARIES ${MYSOFA_LIBRARY}) - set(MYSOFA_LIBRARIES ${MYSOFA_LIBRARIES} ZLIB::ZLIB) - if(MYSOFA_M_LIBRARY) - set(MYSOFA_LIBRARIES ${MYSOFA_LIBRARIES} ${MYSOFA_M_LIBRARY}) - endif() - - add_library(MySOFA::MySOFA UNKNOWN IMPORTED) - set_property(TARGET MySOFA::MySOFA PROPERTY - IMPORTED_LOCATION ${MYSOFA_LIBRARY}) - set_target_properties(MySOFA::MySOFA PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES ${MYSOFA_INCLUDE_DIRS} - INTERFACE_LINK_LIBRARIES ZLIB::ZLIB) - if(MYSOFA_M_LIBRARY) - set_property(TARGET MySOFA::MySOFA APPEND PROPERTY - INTERFACE_LINK_LIBRARIES ${MYSOFA_M_LIBRARY}) - endif() -endif() - -mark_as_advanced(MYSOFA_INCLUDE_DIR MYSOFA_LIBRARY) diff --git a/cmake/FindOSS.cmake b/cmake/FindOSS.cmake deleted file mode 100644 index feffb451..00000000 --- a/cmake/FindOSS.cmake +++ /dev/null @@ -1,33 +0,0 @@ -# - Find OSS includes -# -# OSS_FOUND - True if OSS_INCLUDE_DIR is found -# OSS_INCLUDE_DIRS - Set when OSS_INCLUDE_DIR is found -# OSS_LIBRARIES - Set when OSS_LIBRARY is found -# -# OSS_INCLUDE_DIR - where to find sys/soundcard.h, etc. -# OSS_LIBRARY - where to find libossaudio (optional). -# - -find_path(OSS_INCLUDE_DIR - NAMES sys/soundcard.h - DOC "The OSS include directory" -) - -find_library(OSS_LIBRARY - NAMES ossaudio - DOC "Optional OSS library" -) - -include(FindPackageHandleStandardArgs) -find_package_handle_standard_args(OSS REQUIRED_VARS OSS_INCLUDE_DIR) - -if(OSS_FOUND) - set(OSS_INCLUDE_DIRS ${OSS_INCLUDE_DIR}) - if(OSS_LIBRARY) - set(OSS_LIBRARIES ${OSS_LIBRARY}) - else() - unset(OSS_LIBRARIES) - endif() -endif() - -mark_as_advanced(OSS_INCLUDE_DIR OSS_LIBRARY) diff --git a/cmake/FindOboe.cmake b/cmake/FindOboe.cmake deleted file mode 100644 index bf12c12c..00000000 --- a/cmake/FindOboe.cmake +++ /dev/null @@ -1,31 +0,0 @@ -# - Find Oboe -# Find the Oboe library -# -# This module defines the following variable: -# OBOE_FOUND - True if Oboe was found -# -# This module defines the following target: -# oboe::oboe - Import target for linking Oboe to a project -# - -find_path(OBOE_INCLUDE_DIR NAMES oboe/Oboe.h - DOC "The Oboe include directory" -) - -find_library(OBOE_LIBRARY NAMES oboe - DOC "The Oboe library" -) - -# handle the QUIETLY and REQUIRED arguments and set OBOE_FOUND to TRUE if -# all listed variables are TRUE -include(FindPackageHandleStandardArgs) -find_package_handle_standard_args(Oboe REQUIRED_VARS OBOE_LIBRARY OBOE_INCLUDE_DIR) - -if(OBOE_FOUND) - add_library(oboe::oboe UNKNOWN IMPORTED) - set_target_properties(oboe::oboe PROPERTIES - IMPORTED_LOCATION ${OBOE_LIBRARY} - INTERFACE_INCLUDE_DIRECTORIES ${OBOE_INCLUDE_DIR}) -endif() - -mark_as_advanced(OBOE_INCLUDE_DIR OBOE_LIBRARY) diff --git a/cmake/FindOpenSL.cmake b/cmake/FindOpenSL.cmake deleted file mode 100644 index 00428749..00000000 --- a/cmake/FindOpenSL.cmake +++ /dev/null @@ -1,63 +0,0 @@ -# - Find OpenSL -# Find the OpenSL libraries -# -# This module defines the following variables and targets: -# OPENSL_FOUND - True if OPENSL was found -# OpenSL::OpenSLES - The OpenSLES target -# - -#============================================================================= -# Copyright 2009-2011 Kitware, Inc. -# Copyright 2009-2011 Philip Lowman -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# -# * Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# * The names of Kitware, Inc., the Insight Consortium, or the names of -# any consortium members, or of any contributors, may not be used to -# endorse or promote products derived from this software without -# specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS'' -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR -# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#============================================================================= - -find_path(OPENSL_INCLUDE_DIR NAMES SLES/OpenSLES.h - DOC "The OpenSL include directory") -find_path(OPENSL_ANDROID_INCLUDE_DIR NAMES SLES/OpenSLES_Android.h - DOC "The OpenSL Android include directory") - -find_library(OPENSL_LIBRARY NAMES OpenSLES - DOC "The OpenSL library") - -# handle the QUIETLY and REQUIRED arguments and set OPENSL_FOUND to TRUE if -# all listed variables are TRUE -include(FindPackageHandleStandardArgs) -find_package_handle_standard_args(OpenSL REQUIRED_VARS OPENSL_LIBRARY OPENSL_INCLUDE_DIR - OPENSL_ANDROID_INCLUDE_DIR) - -if(OPENSL_FOUND) - add_library(OpenSL::OpenSLES UNKNOWN IMPORTED) - set_target_properties(OpenSL::OpenSLES PROPERTIES - IMPORTED_LOCATION ${OPENSL_LIBRARY} - INTERFACE_INCLUDE_DIRECTORIES ${OPENSL_INCLUDE_DIR} - INTERFACE_INCLUDE_DIRECTORIES ${OPENSL_ANDROID_INCLUDE_DIR}) -endif() - -mark_as_advanced(OPENSL_INCLUDE_DIR OPENSL_ANDROID_INCLUDE_DIR OPENSL_LIBRARY) diff --git a/cmake/FindPortAudio.cmake b/cmake/FindPortAudio.cmake deleted file mode 100644 index fad2313d..00000000 --- a/cmake/FindPortAudio.cmake +++ /dev/null @@ -1,32 +0,0 @@ -# - Find PortAudio includes and libraries -# -# PORTAUDIO_FOUND - True if PORTAUDIO_INCLUDE_DIR & PORTAUDIO_LIBRARY -# are found -# PORTAUDIO_LIBRARIES - Set when PORTAUDIO_LIBRARY is found -# PORTAUDIO_INCLUDE_DIRS - Set when PORTAUDIO_INCLUDE_DIR is found -# -# PORTAUDIO_INCLUDE_DIR - where to find portaudio.h, etc. -# PORTAUDIO_LIBRARY - the portaudio library -# - -find_path(PORTAUDIO_INCLUDE_DIR - NAMES portaudio.h - DOC "The PortAudio include directory" -) - -find_library(PORTAUDIO_LIBRARY - NAMES portaudio - DOC "The PortAudio library" -) - -include(FindPackageHandleStandardArgs) -find_package_handle_standard_args(PortAudio - REQUIRED_VARS PORTAUDIO_LIBRARY PORTAUDIO_INCLUDE_DIR -) - -if(PORTAUDIO_FOUND) - set(PORTAUDIO_LIBRARIES ${PORTAUDIO_LIBRARY}) - set(PORTAUDIO_INCLUDE_DIRS ${PORTAUDIO_INCLUDE_DIR}) -endif() - -mark_as_advanced(PORTAUDIO_INCLUDE_DIR PORTAUDIO_LIBRARY) diff --git a/cmake/FindPulseAudio.cmake b/cmake/FindPulseAudio.cmake deleted file mode 100644 index 1f6f843a..00000000 --- a/cmake/FindPulseAudio.cmake +++ /dev/null @@ -1,43 +0,0 @@ -# - Find PulseAudio includes and libraries -# -# PULSEAUDIO_FOUND - True if PULSEAUDIO_INCLUDE_DIR & -# PULSEAUDIO_LIBRARY are found -# PULSEAUDIO_LIBRARIES - Set when PULSEAUDIO_LIBRARY is found -# PULSEAUDIO_INCLUDE_DIRS - Set when PULSEAUDIO_INCLUDE_DIR is found -# -# PULSEAUDIO_INCLUDE_DIR - where to find pulse/pulseaudio.h, etc. -# PULSEAUDIO_LIBRARY - the pulse library -# PULSEAUDIO_VERSION_STRING - the version of PulseAudio found -# - -find_path(PULSEAUDIO_INCLUDE_DIR - NAMES pulse/pulseaudio.h - DOC "The PulseAudio include directory" -) - -find_library(PULSEAUDIO_LIBRARY - NAMES pulse - DOC "The PulseAudio library" -) - -if(PULSEAUDIO_INCLUDE_DIR AND EXISTS "${PULSEAUDIO_INCLUDE_DIR}/pulse/version.h") - file(STRINGS "${PULSEAUDIO_INCLUDE_DIR}/pulse/version.h" pulse_version_str - REGEX "^#define[\t ]+pa_get_headers_version\\(\\)[\t ]+\\(\".*\"\\)") - - string(REGEX REPLACE "^.*pa_get_headers_version\\(\\)[\t ]+\\(\"([^\"]*)\"\\).*$" "\\1" - PULSEAUDIO_VERSION_STRING "${pulse_version_str}") - unset(pulse_version_str) -endif() - -include(FindPackageHandleStandardArgs) -find_package_handle_standard_args(PulseAudio - REQUIRED_VARS PULSEAUDIO_LIBRARY PULSEAUDIO_INCLUDE_DIR - VERSION_VAR PULSEAUDIO_VERSION_STRING -) - -if(PULSEAUDIO_FOUND) - set(PULSEAUDIO_LIBRARIES ${PULSEAUDIO_LIBRARY}) - set(PULSEAUDIO_INCLUDE_DIRS ${PULSEAUDIO_INCLUDE_DIR}) -endif() - -mark_as_advanced(PULSEAUDIO_INCLUDE_DIR PULSEAUDIO_LIBRARY) diff --git a/cmake/FindSDL2.cmake b/cmake/FindSDL2.cmake deleted file mode 100644 index e808d006..00000000 --- a/cmake/FindSDL2.cmake +++ /dev/null @@ -1,191 +0,0 @@ -# Locate SDL2 library -# This module defines -# SDL2_LIBRARY, the name of the library to link against -# SDL2_FOUND, if false, do not try to link to SDL2 -# SDL2_INCLUDE_DIR, where to find SDL.h -# -# This module responds to the the flag: -# SDL2_BUILDING_LIBRARY -# If this is defined, then no SDL2_main will be linked in because -# only applications need main(). -# Otherwise, it is assumed you are building an application and this -# module will attempt to locate and set the the proper link flags -# as part of the returned SDL2_LIBRARY variable. -# -# Don't forget to include SDL2main.h and SDL2main.m your project for the -# OS X framework based version. (Other versions link to -lSDL2main which -# this module will try to find on your behalf.) Also for OS X, this -# module will automatically add the -framework Cocoa on your behalf. -# -# -# Additional Note: If you see an empty SDL2_CORE_LIBRARY in your configuration -# and no SDL2_LIBRARY, it means CMake did not find your SDL2 library -# (SDL2.dll, libsdl2.so, SDL2.framework, etc). -# Set SDL2_CORE_LIBRARY to point to your SDL2 library, and configure again. -# Similarly, if you see an empty SDL2MAIN_LIBRARY, you should set this value -# as appropriate. These values are used to generate the final SDL2_LIBRARY -# variable, but when these values are unset, SDL2_LIBRARY does not get created. -# -# -# $SDL2DIR is an environment variable that would -# correspond to the ./configure --prefix=$SDL2DIR -# used in building SDL2. -# l.e.galup 9-20-02 -# -# Modified by Eric Wing. -# Added code to assist with automated building by using environmental variables -# and providing a more controlled/consistent search behavior. -# Added new modifications to recognize OS X frameworks and -# additional Unix paths (FreeBSD, etc). -# Also corrected the header search path to follow "proper" SDL2 guidelines. -# Added a search for SDL2main which is needed by some platforms. -# Added a search for threads which is needed by some platforms. -# Added needed compile switches for MinGW. -# -# On OSX, this will prefer the Framework version (if found) over others. -# People will have to manually change the cache values of -# SDL2_LIBRARY to override this selection or set the CMake environment -# CMAKE_INCLUDE_PATH to modify the search paths. -# -# Note that the header path has changed from SDL2/SDL.h to just SDL.h -# This needed to change because "proper" SDL2 convention -# is #include "SDL.h", not . This is done for portability -# reasons because not all systems place things in SDL2/ (see FreeBSD). -# -# Ported by Johnny Patterson. This is a literal port for SDL2 of the FindSDL.cmake -# module with the minor edit of changing "SDL" to "SDL2" where necessary. This -# was not created for redistribution, and exists temporarily pending official -# SDL2 CMake modules. - -#============================================================================= -# Copyright 2003-2009 Kitware, Inc. -# -# Distributed under the OSI-approved BSD License (the "License"); -# see accompanying file Copyright.txt for details. -# -# This software is distributed WITHOUT ANY WARRANTY; without even the -# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -# See the License for more information. -#============================================================================= -# (To distribute this file outside of CMake, substitute the full -# License text for the above reference.) - - -FIND_PATH(SDL2_INCLUDE_DIR SDL.h - HINTS - $ENV{SDL2DIR} - PATH_SUFFIXES include/SDL2 include - PATHS - ~/Library/Frameworks - /Library/Frameworks - /usr/local/include/SDL2 - /usr/include/SDL2 - /sw # Fink - /opt/local # DarwinPorts - /opt/csw # Blastwave - /opt -) -#MESSAGE("SDL2_INCLUDE_DIR is ${SDL2_INCLUDE_DIR}") - -FIND_LIBRARY(SDL2_CORE_LIBRARY - NAMES SDL2 - HINTS - $ENV{SDL2DIR} - PATH_SUFFIXES lib64 lib - PATHS - /sw - /opt/local - /opt/csw - /opt -) -#MESSAGE("SDL2_CORE_LIBRARY is ${SDL2_CORE_LIBRARY}") - -IF(NOT SDL2_BUILDING_LIBRARY) - IF(NOT ${SDL2_INCLUDE_DIR} MATCHES ".framework") - # Non-OS X framework versions expect you to also dynamically link to - # SDL2main. This is mainly for Windows and OS X. Other (Unix) platforms - # seem to provide SDL2main for compatibility even though they don't - # necessarily need it. - FIND_LIBRARY(SDL2MAIN_LIBRARY - NAMES SDL2main - HINTS - $ENV{SDL2DIR} - PATH_SUFFIXES lib64 lib - PATHS - /sw - /opt/local - /opt/csw - /opt - ) - ENDIF(NOT ${SDL2_INCLUDE_DIR} MATCHES ".framework") -ENDIF(NOT SDL2_BUILDING_LIBRARY) - -# SDL2 may require threads on your system. -# The Apple build may not need an explicit flag because one of the -# frameworks may already provide it. -# But for non-OSX systems, I will use the CMake Threads package. -IF(NOT APPLE) - FIND_PACKAGE(Threads) -ENDIF(NOT APPLE) - -# MinGW needs an additional library, mwindows -# It's total link flags should look like -lmingw32 -lSDL2main -lSDL2 -lmwindows -# (Actually on second look, I think it only needs one of the m* libraries.) -IF(MINGW) - SET(MINGW32_LIBRARY mingw32 CACHE STRING "mwindows for MinGW") -ENDIF(MINGW) - -SET(SDL2_FOUND "NO") -IF(SDL2_CORE_LIBRARY) - SET(SDL2_LIBRARY_TEMP ${SDL2_CORE_LIBRARY}) - - # For SDL2main - IF(NOT SDL2_BUILDING_LIBRARY) - IF(SDL2MAIN_LIBRARY) - SET(SDL2_LIBRARY_TEMP ${SDL2MAIN_LIBRARY} ${SDL2_LIBRARY_TEMP}) - ENDIF(SDL2MAIN_LIBRARY) - ENDIF(NOT SDL2_BUILDING_LIBRARY) - - # For OS X, SDL2 uses Cocoa as a backend so it must link to Cocoa. - # CMake doesn't display the -framework Cocoa string in the UI even - # though it actually is there if I modify a pre-used variable. - # I think it has something to do with the CACHE STRING. - # So I use a temporary variable until the end so I can set the - # "real" variable in one-shot. - IF(APPLE) - SET(SDL2_LIBRARY_TEMP ${SDL2_LIBRARY_TEMP} "-framework Cocoa") - ENDIF(APPLE) - - # For threads, as mentioned Apple doesn't need this. - # In fact, there seems to be a problem if I used the Threads package - # and try using this line, so I'm just skipping it entirely for OS X. - IF(NOT APPLE) - SET(SDL2_LIBRARY_TEMP ${SDL2_LIBRARY_TEMP} ${CMAKE_THREAD_LIBS_INIT}) - ENDIF(NOT APPLE) - - # For MinGW library - IF(MINGW) - SET(SDL2_LIBRARY_TEMP ${MINGW32_LIBRARY} ${SDL2_LIBRARY_TEMP}) - ENDIF(MINGW) - - IF(WIN32) - SET(SDL2_LIBRARY_TEMP winmm imm32 version msimg32 ${SDL2_LIBRARY_TEMP}) - ENDIF(WIN32) - - # Set the final string here so the GUI reflects the final state. - SET(SDL2_LIBRARY ${SDL2_LIBRARY_TEMP}) - - SET(SDL2_FOUND "YES") -ENDIF(SDL2_CORE_LIBRARY) - -INCLUDE(FindPackageHandleStandardArgs) -FIND_PACKAGE_HANDLE_STANDARD_ARGS(SDL2 - REQUIRED_VARS SDL2_LIBRARY SDL2_INCLUDE_DIR) - -IF(SDL2_STATIC) - if (UNIX AND NOT APPLE) - EXECUTE_PROCESS(COMMAND sdl2-config --static-libs OUTPUT_VARIABLE SDL2_LINK_FLAGS) - STRING(REGEX REPLACE "(\r?\n)+$" "" SDL2_LINK_FLAGS "${SDL2_LINK_FLAGS}") - SET(SDL2_LIBRARY ${SDL2_LINK_FLAGS}) - ENDIF() -ENDIF(SDL2_STATIC) diff --git a/cmake/FindSndFile.cmake b/cmake/FindSndFile.cmake deleted file mode 100644 index b931d3c0..00000000 --- a/cmake/FindSndFile.cmake +++ /dev/null @@ -1,25 +0,0 @@ -# - Try to find SndFile -# Once done this will define -# -# SNDFILE_FOUND - system has SndFile -# SndFile::SndFile - the SndFile target -# - -find_path(SNDFILE_INCLUDE_DIR NAMES sndfile.h) - -find_library(SNDFILE_LIBRARY NAMES sndfile sndfile-1) - -# handle the QUIETLY and REQUIRED arguments and set SNDFILE_FOUND to TRUE if -# all listed variables are TRUE -include(FindPackageHandleStandardArgs) -find_package_handle_standard_args(SndFile DEFAULT_MSG SNDFILE_LIBRARY SNDFILE_INCLUDE_DIR) - -if(SNDFILE_FOUND) - add_library(SndFile::SndFile UNKNOWN IMPORTED) - set_target_properties(SndFile::SndFile PROPERTIES - IMPORTED_LOCATION ${SNDFILE_LIBRARY} - INTERFACE_INCLUDE_DIRECTORIES ${SNDFILE_INCLUDE_DIR}) -endif() - -# show the SNDFILE_INCLUDE_DIR and SNDFILE_LIBRARY variables only in the advanced view -mark_as_advanced(SNDFILE_INCLUDE_DIR SNDFILE_LIBRARY) diff --git a/cmake/FindSoundIO.cmake b/cmake/FindSoundIO.cmake deleted file mode 100644 index 10450254..00000000 --- a/cmake/FindSoundIO.cmake +++ /dev/null @@ -1,32 +0,0 @@ -# - Find SoundIO (sndio) includes and libraries -# -# SOUNDIO_FOUND - True if SOUNDIO_INCLUDE_DIR & SOUNDIO_LIBRARY are -# found -# SOUNDIO_LIBRARIES - Set when SOUNDIO_LIBRARY is found -# SOUNDIO_INCLUDE_DIRS - Set when SOUNDIO_INCLUDE_DIR is found -# -# SOUNDIO_INCLUDE_DIR - where to find sndio.h, etc. -# SOUNDIO_LIBRARY - the sndio library -# - -find_path(SOUNDIO_INCLUDE_DIR - NAMES sndio.h - DOC "The SoundIO include directory" -) - -find_library(SOUNDIO_LIBRARY - NAMES sndio - DOC "The SoundIO library" -) - -include(FindPackageHandleStandardArgs) -find_package_handle_standard_args(SoundIO - REQUIRED_VARS SOUNDIO_LIBRARY SOUNDIO_INCLUDE_DIR -) - -if(SOUNDIO_FOUND) - set(SOUNDIO_LIBRARIES ${SOUNDIO_LIBRARY}) - set(SOUNDIO_INCLUDE_DIRS ${SOUNDIO_INCLUDE_DIR}) -endif() - -mark_as_advanced(SOUNDIO_INCLUDE_DIR SOUNDIO_LIBRARY) diff --git a/cmake/bin2h.script.cmake b/cmake/bin2h.script.cmake deleted file mode 100644 index 1438fde2..00000000 --- a/cmake/bin2h.script.cmake +++ /dev/null @@ -1,13 +0,0 @@ -# Read the input file into 'indata', converting each byte to a pair of hex -# characters -file(READ "${INPUT_FILE}" indata HEX) - -# For each pair of characters, indent them and prepend the 0x prefix, and -# append a comma separateor. -# TODO: Prettify this. Should group a number of bytes per line instead of one -# per line. -string(REGEX REPLACE "(..)" " 0x\\1,\n" output "${indata}") - -# Write the list of hex chars to the output file in a const byte array -file(WRITE "${OUTPUT_FILE}" - "const unsigned char ${VARIABLE_NAME}[] = {\n${output}};\n") diff --git a/common/albit.h b/common/albit.h deleted file mode 100644 index 225c0b89..00000000 --- a/common/albit.h +++ /dev/null @@ -1,35 +0,0 @@ -#ifndef AL_BIT_H -#define AL_BIT_H - -namespace al { - -#ifdef __BYTE_ORDER__ -enum class endian { - little = __ORDER_LITTLE_ENDIAN__, - big = __ORDER_BIG_ENDIAN__, - native = __BYTE_ORDER__ -}; - -#else - -/* This doesn't support mixed-endian. */ -namespace detail_ { -constexpr inline bool EndianTest() noexcept -{ - static_assert(sizeof(char) < sizeof(int), "char is too big"); - - constexpr int test_val{1}; - return static_cast(test_val); -} -} // namespace detail_ - -enum class endian { - little = 0, - big = 1, - native = detail_::EndianTest() ? little : big -}; -#endif - -} // namespace al - -#endif /* AL_BIT_H */ diff --git a/common/albyte.h b/common/albyte.h deleted file mode 100644 index b871164d..00000000 --- a/common/albyte.h +++ /dev/null @@ -1,67 +0,0 @@ -#ifndef AL_BYTE_H -#define AL_BYTE_H - -#include -#include -#include -#include - -using uint = unsigned int; - -namespace al { - -/* The "canonical" way to store raw byte data. Like C++17's std::byte, it's not - * treated as a character type and does not work with arithmatic ops. Only - * bitwise ops are allowed. - */ -enum class byte : unsigned char { }; - -template -constexpr std::enable_if_t::value,T> -to_integer(al::byte b) noexcept { return T(b); } - - -template -constexpr std::enable_if_t::value,al::byte> -operator<<(al::byte lhs, T rhs) noexcept { return al::byte(to_integer(lhs) << rhs); } - -template -constexpr std::enable_if_t::value,al::byte> -operator>>(al::byte lhs, T rhs) noexcept { return al::byte(to_integer(lhs) >> rhs); } - -template -constexpr std::enable_if_t::value,al::byte&> -operator<<=(al::byte &lhs, T rhs) noexcept { lhs = lhs << rhs; return lhs; } - -template -constexpr std::enable_if_t::value,al::byte&> -operator>>=(al::byte &lhs, T rhs) noexcept { lhs = lhs >> rhs; return lhs; } - -#define AL_DECL_OP(op, opeq) \ -template \ -constexpr std::enable_if_t::value,al::byte> \ -operator op (al::byte lhs, T rhs) noexcept \ -{ return al::byte(to_integer(lhs) op static_cast(rhs)); } \ - \ -template \ -constexpr std::enable_if_t::value,al::byte&> \ -operator opeq (al::byte &lhs, T rhs) noexcept { lhs = lhs op rhs; return lhs; } \ - \ -constexpr al::byte operator op (al::byte lhs, al::byte rhs) noexcept \ -{ return al::byte(lhs op to_integer(rhs)); } \ - \ -constexpr al::byte& operator opeq (al::byte &lhs, al::byte rhs) noexcept \ -{ lhs = lhs op rhs; return lhs; } - -AL_DECL_OP(|, |=) -AL_DECL_OP(&, &=) -AL_DECL_OP(^, ^=) - -#undef AL_DECL_OP - -constexpr al::byte operator~(al::byte b) noexcept -{ return al::byte(~to_integer(b)); } - -} // namespace al - -#endif /* AL_BYTE_H */ diff --git a/common/alcomplex.cpp b/common/alcomplex.cpp deleted file mode 100644 index 8a823b01..00000000 --- a/common/alcomplex.cpp +++ /dev/null @@ -1,79 +0,0 @@ - -#include "config.h" - -#include "alcomplex.h" - -#include -#include -#include -#include - -#include "alnumeric.h" -#include "math_defs.h" - - -void complex_fft(const al::span> buffer, const double sign) -{ - const size_t fftsize{buffer.size()}; - /* Get the number of bits used for indexing. Simplifies bit-reversal and - * the main loop count. - */ - const size_t log2_size{static_cast(CountTrailingZeros(fftsize))}; - - /* Bit-reversal permutation applied to a sequence of fftsize items. */ - for(size_t idx{1u};idx < fftsize-1;++idx) - { - size_t revidx{0u}, imask{idx}; - for(size_t i{0};i < log2_size;++i) - { - revidx = (revidx<<1) | (imask&1); - imask >>= 1; - } - - if(idx < revidx) - std::swap(buffer[idx], buffer[revidx]); - } - - /* Iterative form of Danielson-Lanczos lemma */ - size_t step2{1u}; - for(size_t i{0};i < log2_size;++i) - { - const double arg{al::MathDefs::Pi() / static_cast(step2)}; - - const std::complex w{std::cos(arg), std::sin(arg)*sign}; - std::complex u{1.0, 0.0}; - const size_t step{step2 << 1}; - for(size_t j{0};j < step2;j++) - { - for(size_t k{j};k < fftsize;k+=step) - { - std::complex temp{buffer[k+step2] * u}; - buffer[k+step2] = buffer[k] - temp; - buffer[k] += temp; - } - - u *= w; - } - - step2 <<= 1; - } -} - -void complex_hilbert(const al::span> buffer) -{ - inverse_fft(buffer); - - const double inverse_size = 1.0/static_cast(buffer.size()); - auto bufiter = buffer.begin(); - const auto halfiter = bufiter + (buffer.size()>>1); - - *bufiter *= inverse_size; ++bufiter; - bufiter = std::transform(bufiter, halfiter, bufiter, - [inverse_size](const std::complex &c) -> std::complex - { return c * (2.0*inverse_size); }); - *bufiter *= inverse_size; ++bufiter; - - std::fill(bufiter, buffer.end(), std::complex{}); - - forward_fft(buffer); -} diff --git a/common/alcomplex.h b/common/alcomplex.h deleted file mode 100644 index 23b8114a..00000000 --- a/common/alcomplex.h +++ /dev/null @@ -1,38 +0,0 @@ -#ifndef ALCOMPLEX_H -#define ALCOMPLEX_H - -#include - -#include "alspan.h" - -/** - * Iterative implementation of 2-radix FFT (In-place algorithm). Sign = -1 is - * FFT and 1 is inverse FFT. Applies the Discrete Fourier Transform (DFT) to - * the data supplied in the buffer, which MUST BE power of two. - */ -void complex_fft(const al::span> buffer, const double sign); - -/** - * Calculate the frequency-domain response of the time-domain signal in the - * provided buffer, which MUST BE power of two. - */ -inline void forward_fft(const al::span> buffer) -{ complex_fft(buffer, -1.0); } - -/** - * Calculate the time-domain signal of the frequency-domain response in the - * provided buffer, which MUST BE power of two. - */ -inline void inverse_fft(const al::span> buffer) -{ complex_fft(buffer, 1.0); } - -/** - * Calculate the complex helical sequence (discrete-time analytical signal) of - * the given input using the discrete Hilbert transform (In-place algorithm). - * Fills the buffer with the discrete-time analytical signal stored in the - * buffer. The buffer is an array of complex numbers and MUST BE power of two, - * and the imaginary components should be cleared to 0. - */ -void complex_hilbert(const al::span> buffer); - -#endif /* ALCOMPLEX_H */ diff --git a/common/alfstream.cpp b/common/alfstream.cpp deleted file mode 100644 index 3beda833..00000000 --- a/common/alfstream.cpp +++ /dev/null @@ -1,150 +0,0 @@ - -#include "config.h" - -#include "alfstream.h" - -#include "strutils.h" - -#ifdef _WIN32 - -namespace al { - -auto filebuf::underflow() -> int_type -{ - if(mFile != INVALID_HANDLE_VALUE && gptr() == egptr()) - { - // Read in the next chunk of data, and set the pointers on success - DWORD got{}; - if(ReadFile(mFile, mBuffer.data(), static_cast(mBuffer.size()), &got, nullptr)) - setg(mBuffer.data(), mBuffer.data(), mBuffer.data()+got); - } - if(gptr() == egptr()) - return traits_type::eof(); - return traits_type::to_int_type(*gptr()); -} - -auto filebuf::seekoff(off_type offset, std::ios_base::seekdir whence, std::ios_base::openmode mode) -> pos_type -{ - if(mFile == INVALID_HANDLE_VALUE || (mode&std::ios_base::out) || !(mode&std::ios_base::in)) - return traits_type::eof(); - - LARGE_INTEGER fpos{}; - switch(whence) - { - case std::ios_base::beg: - fpos.QuadPart = offset; - if(!SetFilePointerEx(mFile, fpos, &fpos, FILE_BEGIN)) - return traits_type::eof(); - break; - - case std::ios_base::cur: - // If the offset remains in the current buffer range, just - // update the pointer. - if((offset >= 0 && offset < off_type(egptr()-gptr())) || - (offset < 0 && -offset <= off_type(gptr()-eback()))) - { - // Get the current file offset to report the correct read - // offset. - fpos.QuadPart = 0; - if(!SetFilePointerEx(mFile, fpos, &fpos, FILE_CURRENT)) - return traits_type::eof(); - setg(eback(), gptr()+offset, egptr()); - return fpos.QuadPart - off_type(egptr()-gptr()); - } - // Need to offset for the file offset being at egptr() while - // the requested offset is relative to gptr(). - offset -= off_type(egptr()-gptr()); - fpos.QuadPart = offset; - if(!SetFilePointerEx(mFile, fpos, &fpos, FILE_CURRENT)) - return traits_type::eof(); - break; - - case std::ios_base::end: - fpos.QuadPart = offset; - if(!SetFilePointerEx(mFile, fpos, &fpos, FILE_END)) - return traits_type::eof(); - break; - - default: - return traits_type::eof(); - } - setg(nullptr, nullptr, nullptr); - return fpos.QuadPart; -} - -auto filebuf::seekpos(pos_type pos, std::ios_base::openmode mode) -> pos_type -{ - // Simplified version of seekoff - if(mFile == INVALID_HANDLE_VALUE || (mode&std::ios_base::out) || !(mode&std::ios_base::in)) - return traits_type::eof(); - - LARGE_INTEGER fpos{}; - fpos.QuadPart = pos; - if(!SetFilePointerEx(mFile, fpos, &fpos, FILE_BEGIN)) - return traits_type::eof(); - - setg(nullptr, nullptr, nullptr); - return fpos.QuadPart; -} - -filebuf::~filebuf() -{ close(); } - -bool filebuf::open(const wchar_t *filename, std::ios_base::openmode mode) -{ - if((mode&std::ios_base::out) || !(mode&std::ios_base::in)) - return false; - HANDLE f{CreateFileW(filename, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL, nullptr)}; - if(f == INVALID_HANDLE_VALUE) return false; - - if(mFile != INVALID_HANDLE_VALUE) - CloseHandle(mFile); - mFile = f; - - setg(nullptr, nullptr, nullptr); - return true; -} -bool filebuf::open(const char *filename, std::ios_base::openmode mode) -{ - std::wstring wname{utf8_to_wstr(filename)}; - return open(wname.c_str(), mode); -} - -void filebuf::close() -{ - if(mFile != INVALID_HANDLE_VALUE) - CloseHandle(mFile); - mFile = INVALID_HANDLE_VALUE; -} - - -ifstream::ifstream(const wchar_t *filename, std::ios_base::openmode mode) - : std::istream{nullptr} -{ - init(&mStreamBuf); - - // Set the failbit if the file failed to open. - if((mode&std::ios_base::out) || !mStreamBuf.open(filename, mode|std::ios_base::in)) - clear(failbit); -} - -ifstream::ifstream(const char *filename, std::ios_base::openmode mode) - : std::istream{nullptr} -{ - init(&mStreamBuf); - - // Set the failbit if the file failed to open. - if((mode&std::ios_base::out) || !mStreamBuf.open(filename, mode|std::ios_base::in)) - clear(failbit); -} - -/* This is only here to ensure the compiler doesn't define an implicit - * destructor, which it tries to automatically inline and subsequently complain - * it can't inline without excessive code growth. - */ -ifstream::~ifstream() { } - -} // namespace al - -#endif diff --git a/common/alfstream.h b/common/alfstream.h deleted file mode 100644 index 353fd2de..00000000 --- a/common/alfstream.h +++ /dev/null @@ -1,74 +0,0 @@ -#ifndef AL_FSTREAM_H -#define AL_FSTREAM_H - -#ifdef _WIN32 - -#define WIN32_LEAN_AND_MEAN -#include - -#include -#include -#include - - -namespace al { - -// Windows' std::ifstream fails with non-ANSI paths since the standard only -// specifies names using const char* (or std::string). MSVC has a non-standard -// extension using const wchar_t* (or std::wstring?) to handle Unicode paths, -// but not all Windows compilers support it. So we have to make our own istream -// that accepts UTF-8 paths and forwards to Unicode-aware I/O functions. -class filebuf final : public std::streambuf { - std::array mBuffer; - HANDLE mFile{INVALID_HANDLE_VALUE}; - - int_type underflow() override; - pos_type seekoff(off_type offset, std::ios_base::seekdir whence, std::ios_base::openmode mode) override; - pos_type seekpos(pos_type pos, std::ios_base::openmode mode) override; - -public: - filebuf() = default; - ~filebuf() override; - - bool open(const wchar_t *filename, std::ios_base::openmode mode); - bool open(const char *filename, std::ios_base::openmode mode); - - bool is_open() const noexcept { return mFile != INVALID_HANDLE_VALUE; } - - void close(); -}; - -// Inherit from std::istream to use our custom streambuf -class ifstream final : public std::istream { - filebuf mStreamBuf; - -public: - ifstream(const wchar_t *filename, std::ios_base::openmode mode = std::ios_base::in); - ifstream(const std::wstring &filename, std::ios_base::openmode mode = std::ios_base::in) - : ifstream(filename.c_str(), mode) { } - ifstream(const char *filename, std::ios_base::openmode mode = std::ios_base::in); - ifstream(const std::string &filename, std::ios_base::openmode mode = std::ios_base::in) - : ifstream(filename.c_str(), mode) { } - ~ifstream() override; - - bool is_open() const noexcept { return mStreamBuf.is_open(); } - - void close() { mStreamBuf.close(); } -}; - -} // namespace al - -#else /* _WIN32 */ - -#include - -namespace al { - -using filebuf = std::filebuf; -using ifstream = std::ifstream; - -} // namespace al - -#endif /* _WIN32 */ - -#endif /* AL_FSTREAM_H */ diff --git a/common/almalloc.cpp b/common/almalloc.cpp deleted file mode 100644 index 4d7ff62c..00000000 --- a/common/almalloc.cpp +++ /dev/null @@ -1,64 +0,0 @@ - -#include "config.h" - -#include "almalloc.h" - -#include -#include -#include -#include -#include -#ifdef HAVE_MALLOC_H -#include -#endif - - -void *al_malloc(size_t alignment, size_t size) -{ - assert((alignment & (alignment-1)) == 0); - alignment = std::max(alignment, alignof(std::max_align_t)); - -#if defined(HAVE_STD_ALIGNED_ALLOC) - size = (size+(alignment-1))&~(alignment-1); - return std::aligned_alloc(alignment, size); -#elif defined(HAVE_POSIX_MEMALIGN) - void *ret{}; - if(posix_memalign(&ret, alignment, size) == 0) - return ret; - return nullptr; -#elif defined(HAVE__ALIGNED_MALLOC) - return _aligned_malloc(size, alignment); -#else - size_t total_size{size + alignment-1 + sizeof(void*)}; - void *base{std::malloc(total_size)}; - if(base != nullptr) - { - void *aligned_ptr{static_cast(base) + sizeof(void*)}; - total_size -= sizeof(void*); - - std::align(alignment, size, aligned_ptr, total_size); - *(static_cast(aligned_ptr)-1) = base; - base = aligned_ptr; - } - return base; -#endif -} - -void *al_calloc(size_t alignment, size_t size) -{ - void *ret{al_malloc(alignment, size)}; - if(ret) std::memset(ret, 0, size); - return ret; -} - -void al_free(void *ptr) noexcept -{ -#if defined(HAVE_STD_ALIGNED_ALLOC) || defined(HAVE_POSIX_MEMALIGN) - std::free(ptr); -#elif defined(HAVE__ALIGNED_MALLOC) - _aligned_free(ptr); -#else - if(ptr != nullptr) - std::free(*(static_cast(ptr) - 1)); -#endif -} diff --git a/common/almalloc.h b/common/almalloc.h deleted file mode 100644 index 75388d9d..00000000 --- a/common/almalloc.h +++ /dev/null @@ -1,291 +0,0 @@ -#ifndef AL_MALLOC_H -#define AL_MALLOC_H - -#include -#include -#include -#include -#include -#include -#include -#include - -#include "pragmadefs.h" - - -[[gnu::alloc_align(1), gnu::alloc_size(2)]] void *al_malloc(size_t alignment, size_t size); -[[gnu::alloc_align(1), gnu::alloc_size(2)]] void *al_calloc(size_t alignment, size_t size); -void al_free(void *ptr) noexcept; - - -#define DISABLE_ALLOC() \ - void *operator new(size_t) = delete; \ - void *operator new[](size_t) = delete; \ - void operator delete(void*) noexcept = delete; \ - void operator delete[](void*) noexcept = delete; - -#define DEF_NEWDEL(T) \ - void *operator new(size_t size) \ - { \ - void *ret = al_malloc(alignof(T), size); \ - if(!ret) throw std::bad_alloc(); \ - return ret; \ - } \ - void *operator new[](size_t size) { return operator new(size); } \ - void operator delete(void *block) noexcept { al_free(block); } \ - void operator delete[](void *block) noexcept { operator delete(block); } - -#define DEF_PLACE_NEWDEL() \ - void *operator new(size_t /*size*/, void *ptr) noexcept { return ptr; } \ - void *operator new[](size_t /*size*/, void *ptr) noexcept { return ptr; } \ - void operator delete(void *block, void*) noexcept { al_free(block); } \ - void operator delete(void *block) noexcept { al_free(block); } \ - void operator delete[](void *block, void*) noexcept { al_free(block); } \ - void operator delete[](void *block) noexcept { al_free(block); } - -enum FamCount : size_t { }; - -#define DEF_FAM_NEWDEL(T, FamMem) \ - static constexpr size_t Sizeof(size_t count) noexcept \ - { \ - return std::max(sizeof(T), \ - decltype(FamMem)::Sizeof(count, offsetof(T, FamMem))); \ - } \ - \ - void *operator new(size_t /*size*/, FamCount count) \ - { \ - if(void *ret{al_malloc(alignof(T), T::Sizeof(count))}) \ - return ret; \ - throw std::bad_alloc(); \ - } \ - void *operator new[](size_t /*size*/) = delete; \ - void operator delete(void *block, FamCount) { al_free(block); } \ - void operator delete(void *block) noexcept { al_free(block); } \ - void operator delete[](void* /*block*/) = delete; - - -namespace al { - -template -struct allocator { - using value_type = T; - using reference = T&; - using const_reference = const T&; - using pointer = T*; - using const_pointer = const T*; - using size_type = std::size_t; - using difference_type = std::ptrdiff_t; - using is_always_equal = std::true_type; - - template - struct rebind { - using other = allocator; - }; - - allocator() noexcept = default; - template - constexpr allocator(const allocator&) noexcept { } - - [[gnu::assume_aligned(alignment), gnu::alloc_size(2)]] T *allocate(std::size_t n) - { - if(n > std::numeric_limits::max()/sizeof(T)) throw std::bad_alloc(); - if(auto p = static_cast(al_malloc(alignment, n*sizeof(T)))) return p; - throw std::bad_alloc(); - } - void deallocate(T *p, std::size_t) noexcept { al_free(p); } -}; -template -bool operator==(const allocator&, const allocator&) noexcept { return true; } -template -bool operator!=(const allocator&, const allocator&) noexcept { return false; } - -template -[[gnu::assume_aligned(alignment)]] inline T* assume_aligned(T *ptr) noexcept { return ptr; } - -/* At least VS 2015 complains that 'ptr' is unused when the given type's - * destructor is trivial (a no-op). So disable that warning for this call. - */ -DIAGNOSTIC_PUSH -msc_pragma(warning(disable : 4100)) -template -constexpr std::enable_if_t::value> -destroy_at(T *ptr) noexcept(std::is_nothrow_destructible::value) -{ ptr->~T(); } -DIAGNOSTIC_POP -template -constexpr std::enable_if_t::value> -destroy_at(T *ptr) noexcept(std::is_nothrow_destructible::value) -{ - for(auto &elem : *ptr) - al::destroy_at(std::addressof(elem)); -} - -template -constexpr void destroy(T first, T end) -{ - while(first != end) - { - al::destroy_at(std::addressof(*first)); - ++first; - } -} - -template -constexpr std::enable_if_t::value,T> -destroy_n(T first, N count) -{ - if(count != 0) - { - do { - al::destroy_at(std::addressof(*first)); - ++first; - } while(--count); - } - return first; -} - - -template -inline std::enable_if_t::value,T> -uninitialized_default_construct_n(T first, N count) -{ - using ValueT = typename std::iterator_traits::value_type; - T current{first}; - if(count != 0) - { - try { - do { - ::new(static_cast(std::addressof(*current))) ValueT; - ++current; - } while(--count); - } - catch(...) { - al::destroy(first, current); - throw; - } - } - return current; -} - - -/* Storage for flexible array data. This is trivially destructible if type T is - * trivially destructible. - */ -template::value> -struct FlexArrayStorage; - -template -struct FlexArrayStorage { - const size_t mSize; - union { - char mDummy; - alignas(alignment) T mArray[1]; - }; - - static constexpr size_t Sizeof(size_t count, size_t base=0u) noexcept - { - return std::max(offsetof(FlexArrayStorage, mArray) + sizeof(T)*count, - sizeof(FlexArrayStorage)) + base; - } - - FlexArrayStorage(size_t size) : mSize{size} - { al::uninitialized_default_construct_n(mArray, mSize); } - ~FlexArrayStorage() = default; - - FlexArrayStorage(const FlexArrayStorage&) = delete; - FlexArrayStorage& operator=(const FlexArrayStorage&) = delete; -}; - -template -struct FlexArrayStorage { - const size_t mSize; - union { - char mDummy; - alignas(alignment) T mArray[1]; - }; - - static constexpr size_t Sizeof(size_t count, size_t base) noexcept - { - return std::max(offsetof(FlexArrayStorage, mArray) + sizeof(T)*count, - sizeof(FlexArrayStorage)) + base; - } - - FlexArrayStorage(size_t size) : mSize{size} - { al::uninitialized_default_construct_n(mArray, mSize); } - ~FlexArrayStorage() { al::destroy_n(mArray, mSize); } - - FlexArrayStorage(const FlexArrayStorage&) = delete; - FlexArrayStorage& operator=(const FlexArrayStorage&) = delete; -}; - -/* A flexible array type. Used either standalone or at the end of a parent - * struct, with placement new, to have a run-time-sized array that's embedded - * with its size. - */ -template -struct FlexArray { - using element_type = T; - using value_type = std::remove_cv_t; - using index_type = size_t; - using difference_type = ptrdiff_t; - - using pointer = T*; - using const_pointer = const T*; - using reference = T&; - using const_reference = const T&; - - using iterator = pointer; - using const_iterator = const_pointer; - using reverse_iterator = std::reverse_iterator; - using const_reverse_iterator = std::reverse_iterator; - - using Storage_t_ = FlexArrayStorage; - - Storage_t_ mStore; - - static constexpr index_type Sizeof(index_type count, index_type base=0u) noexcept - { return Storage_t_::Sizeof(count, base); } - static std::unique_ptr Create(index_type count) - { - void *ptr{al_calloc(alignof(FlexArray), Sizeof(count))}; - return std::unique_ptr{new(ptr) FlexArray{count}}; - } - - FlexArray(index_type size) : mStore{size} { } - ~FlexArray() = default; - - index_type size() const noexcept { return mStore.mSize; } - bool empty() const noexcept { return mStore.mSize == 0; } - - pointer data() noexcept { return mStore.mArray; } - const_pointer data() const noexcept { return mStore.mArray; } - - reference operator[](index_type i) noexcept { return mStore.mArray[i]; } - const_reference operator[](index_type i) const noexcept { return mStore.mArray[i]; } - - reference front() noexcept { return mStore.mArray[0]; } - const_reference front() const noexcept { return mStore.mArray[0]; } - - reference back() noexcept { return mStore.mArray[mStore.mSize-1]; } - const_reference back() const noexcept { return mStore.mArray[mStore.mSize-1]; } - - iterator begin() noexcept { return mStore.mArray; } - const_iterator begin() const noexcept { return mStore.mArray; } - const_iterator cbegin() const noexcept { return mStore.mArray; } - iterator end() noexcept { return mStore.mArray + mStore.mSize; } - const_iterator end() const noexcept { return mStore.mArray + mStore.mSize; } - const_iterator cend() const noexcept { return mStore.mArray + mStore.mSize; } - - reverse_iterator rbegin() noexcept { return end(); } - const_reverse_iterator rbegin() const noexcept { return end(); } - const_reverse_iterator crbegin() const noexcept { return cend(); } - reverse_iterator rend() noexcept { return begin(); } - const_reverse_iterator rend() const noexcept { return begin(); } - const_reverse_iterator crend() const noexcept { return cbegin(); } - - DEF_PLACE_NEWDEL() -}; - -} // namespace al - -#endif /* AL_MALLOC_H */ diff --git a/common/alnumeric.h b/common/alnumeric.h deleted file mode 100644 index b9384a7f..00000000 --- a/common/alnumeric.h +++ /dev/null @@ -1,360 +0,0 @@ -#ifndef AL_NUMERIC_H -#define AL_NUMERIC_H - -#include -#include -#ifdef HAVE_INTRIN_H -#include -#endif -#ifdef HAVE_SSE_INTRINSICS -#include -#endif - -#include "opthelpers.h" - - -inline constexpr int64_t operator "" _i64(unsigned long long int n) noexcept { return static_cast(n); } -inline constexpr uint64_t operator "" _u64(unsigned long long int n) noexcept { return static_cast(n); } - - -constexpr inline float minf(float a, float b) noexcept -{ return ((a > b) ? b : a); } -constexpr inline float maxf(float a, float b) noexcept -{ return ((a > b) ? a : b); } -constexpr inline float clampf(float val, float min, float max) noexcept -{ return minf(max, maxf(min, val)); } - -constexpr inline double mind(double a, double b) noexcept -{ return ((a > b) ? b : a); } -constexpr inline double maxd(double a, double b) noexcept -{ return ((a > b) ? a : b); } -constexpr inline double clampd(double val, double min, double max) noexcept -{ return mind(max, maxd(min, val)); } - -constexpr inline unsigned int minu(unsigned int a, unsigned int b) noexcept -{ return ((a > b) ? b : a); } -constexpr inline unsigned int maxu(unsigned int a, unsigned int b) noexcept -{ return ((a > b) ? a : b); } -constexpr inline unsigned int clampu(unsigned int val, unsigned int min, unsigned int max) noexcept -{ return minu(max, maxu(min, val)); } - -constexpr inline int mini(int a, int b) noexcept -{ return ((a > b) ? b : a); } -constexpr inline int maxi(int a, int b) noexcept -{ return ((a > b) ? a : b); } -constexpr inline int clampi(int val, int min, int max) noexcept -{ return mini(max, maxi(min, val)); } - -constexpr inline int64_t mini64(int64_t a, int64_t b) noexcept -{ return ((a > b) ? b : a); } -constexpr inline int64_t maxi64(int64_t a, int64_t b) noexcept -{ return ((a > b) ? a : b); } -constexpr inline int64_t clampi64(int64_t val, int64_t min, int64_t max) noexcept -{ return mini64(max, maxi64(min, val)); } - -constexpr inline uint64_t minu64(uint64_t a, uint64_t b) noexcept -{ return ((a > b) ? b : a); } -constexpr inline uint64_t maxu64(uint64_t a, uint64_t b) noexcept -{ return ((a > b) ? a : b); } -constexpr inline uint64_t clampu64(uint64_t val, uint64_t min, uint64_t max) noexcept -{ return minu64(max, maxu64(min, val)); } - -constexpr inline size_t minz(size_t a, size_t b) noexcept -{ return ((a > b) ? b : a); } -constexpr inline size_t maxz(size_t a, size_t b) noexcept -{ return ((a > b) ? a : b); } -constexpr inline size_t clampz(size_t val, size_t min, size_t max) noexcept -{ return minz(max, maxz(min, val)); } - - -constexpr inline float lerp(float val1, float val2, float mu) noexcept -{ return val1 + (val2-val1)*mu; } -constexpr inline float cubic(float val1, float val2, float val3, float val4, float mu) noexcept -{ - const float mu2{mu*mu}, mu3{mu2*mu}; - const float a0{-0.5f*mu3 + mu2 + -0.5f*mu}; - const float a1{ 1.5f*mu3 + -2.5f*mu2 + 1.0f}; - const float a2{-1.5f*mu3 + 2.0f*mu2 + 0.5f*mu}; - const float a3{ 0.5f*mu3 + -0.5f*mu2}; - return val1*a0 + val2*a1 + val3*a2 + val4*a3; -} - - -/** Find the next power-of-2 for non-power-of-2 numbers. */ -inline uint32_t NextPowerOf2(uint32_t value) noexcept -{ - if(value > 0) - { - value--; - value |= value>>1; - value |= value>>2; - value |= value>>4; - value |= value>>8; - value |= value>>16; - } - return value+1; -} - -/** Round up a value to the next multiple. */ -inline size_t RoundUp(size_t value, size_t r) noexcept -{ - value += r-1; - return value - (value%r); -} - - -/* Define CountTrailingZeros (count trailing zero bits, starting from the lsb) - * and PopCount (population count/count 1 bits) methods, for 32- and 64-bit - * integers. The CountTrailingZeros results are *UNDEFINED* if the value is 0. - */ -#ifdef __GNUC__ - -/* Define variations for unsigned (long (long)) int, since we don't know what - * uint32/64_t are typedef'd to. - */ -inline int PopCount(unsigned long long val) { return __builtin_popcountll(val); } -inline int PopCount(unsigned long val) { return __builtin_popcountl(val); } -inline int PopCount(unsigned int val) { return __builtin_popcount(val); } - -inline int CountTrailingZeros(unsigned long long val) { return __builtin_ctzll(val); } -inline int CountTrailingZeros(unsigned long val) { return __builtin_ctzl(val); } -inline int CountTrailingZeros(unsigned int val) { return __builtin_ctz(val); } - -#else - -/* There be black magics here. The popcnt method is derived from - * https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel - * while the ctz-utilizing-popcnt algorithm is shown here - * http://www.hackersdelight.org/hdcodetxt/ntz.c.txt - * as the ntz2 variant. These likely aren't the most efficient methods, but - * they're good enough if the GCC built-ins aren't available. - */ -inline int PopCount(uint32_t v) -{ - v = v - ((v >> 1) & 0x55555555u); - v = (v & 0x33333333u) + ((v >> 2) & 0x33333333u); - v = (v + (v >> 4)) & 0x0f0f0f0fu; - return static_cast((v * 0x01010101u) >> 24); -} -inline int PopCount(uint64_t v) -{ - v = v - ((v >> 1) & 0x5555555555555555_u64); - v = (v & 0x3333333333333333_u64) + ((v >> 2) & 0x3333333333333333_u64); - v = (v + (v >> 4)) & 0x0f0f0f0f0f0f0f0f_u64; - return static_cast((v * 0x0101010101010101_u64) >> 56); -} - -#if defined(_WIN64) - -inline int CountTrailingZeros(uint32_t v) -{ - unsigned long idx = 32; - _BitScanForward(&idx, v); - return static_cast(idx); -} -inline int CountTrailingZeros(uint64_t v) -{ - unsigned long idx = 64; - _BitScanForward64(&idx, v); - return static_cast(idx); -} - -#elif defined(_WIN32) - -inline int CountTrailingZeros(uint32_t v) -{ - unsigned long idx = 32; - _BitScanForward(&idx, v); - return static_cast(idx); -} -inline int CountTrailingZeros(uint64_t v) -{ - unsigned long idx = 64; - if(!_BitScanForward(&idx, static_cast(v&0xffffffff))) - { - if(_BitScanForward(&idx, static_cast(v>>32))) - idx += 32; - } - return static_cast(idx); -} - -#else - -inline int CountTrailingZeros(uint32_t value) -{ return PopCount(~value & (value - 1)); } -inline int CountTrailingZeros(uint64_t value) -{ return PopCount(~value & (value - 1)); } - -#endif -#endif - - -/** - * Fast float-to-int conversion. No particular rounding mode is assumed; the - * IEEE-754 default is round-to-nearest with ties-to-even, though an app could - * change it on its own threads. On some systems, a truncating conversion may - * always be the fastest method. - */ -inline int fastf2i(float f) noexcept -{ -#if defined(HAVE_SSE_INTRINSICS) - return _mm_cvt_ss2si(_mm_set_ss(f)); - -#elif defined(_MSC_VER) && defined(_M_IX86_FP) - - int i; - __asm fld f - __asm fistp i - return i; - -#elif (defined(__GNUC__) || defined(__clang__)) && (defined(__i386__) || defined(__x86_64__)) - - int i; -#ifdef __SSE_MATH__ - __asm__("cvtss2si %1, %0" : "=r"(i) : "x"(f)); -#else - __asm__ __volatile__("fistpl %0" : "=m"(i) : "t"(f) : "st"); -#endif - return i; - -#else - - return static_cast(f); -#endif -} -inline unsigned int fastf2u(float f) noexcept -{ return static_cast(fastf2i(f)); } - -/** Converts float-to-int using standard behavior (truncation). */ -inline int float2int(float f) noexcept -{ -#if defined(HAVE_SSE_INTRINSICS) - return _mm_cvtt_ss2si(_mm_set_ss(f)); - -#elif (defined(_MSC_VER) && defined(_M_IX86_FP) && _M_IX86_FP == 0) \ - || ((defined(__GNUC__) || defined(__clang__)) && (defined(__i386__) || defined(__x86_64__)) \ - && !defined(__SSE_MATH__)) - int sign, shift, mant; - union { - float f; - int i; - } conv; - - conv.f = f; - sign = (conv.i>>31) | 1; - shift = ((conv.i>>23)&0xff) - (127+23); - - /* Over/underflow */ - if UNLIKELY(shift >= 31 || shift < -23) - return 0; - - mant = (conv.i&0x7fffff) | 0x800000; - if LIKELY(shift < 0) - return (mant >> -shift) * sign; - return (mant << shift) * sign; - -#else - - return static_cast(f); -#endif -} -inline unsigned int float2uint(float f) noexcept -{ return static_cast(float2int(f)); } - -/** Converts double-to-int using standard behavior (truncation). */ -inline int double2int(double d) noexcept -{ -#if defined(HAVE_SSE_INTRINSICS) - return _mm_cvttsd_si32(_mm_set_sd(d)); - -#elif (defined(_MSC_VER) && defined(_M_IX86_FP) && _M_IX86_FP < 2) \ - || ((defined(__GNUC__) || defined(__clang__)) && (defined(__i386__) || defined(__x86_64__)) \ - && !defined(__SSE2_MATH__)) - int sign, shift; - int64_t mant; - union { - double d; - int64_t i64; - } conv; - - conv.d = d; - sign = (conv.i64 >> 63) | 1; - shift = ((conv.i64 >> 52) & 0x7ff) - (1023 + 52); - - /* Over/underflow */ - if UNLIKELY(shift >= 63 || shift < -52) - return 0; - - mant = (conv.i64 & 0xfffffffffffff_i64) | 0x10000000000000_i64; - if LIKELY(shift < 0) - return (int)(mant >> -shift) * sign; - return (int)(mant << shift) * sign; - -#else - - return static_cast(d); -#endif -} - -/** - * Rounds a float to the nearest integral value, according to the current - * rounding mode. This is essentially an inlined version of rintf, although - * makes fewer promises (e.g. -0 or -0.25 rounded to 0 may result in +0). - */ -inline float fast_roundf(float f) noexcept -{ -#if (defined(__GNUC__) || defined(__clang__)) && (defined(__i386__) || defined(__x86_64__)) \ - && !defined(__SSE_MATH__) - - float out; - __asm__ __volatile__("frndint" : "=t"(out) : "0"(f)); - return out; - -#elif (defined(__GNUC__) || defined(__clang__)) && defined(__aarch64__) - - float out; - __asm__ volatile("frintx %s0, %s1" : "=w"(out) : "w"(f)); - return out; - -#else - - /* Integral limit, where sub-integral precision is not available for - * floats. - */ - static const float ilim[2]{ - 8388608.0f /* 0x1.0p+23 */, - -8388608.0f /* -0x1.0p+23 */ - }; - unsigned int sign, expo; - union { - float f; - unsigned int i; - } conv; - - conv.f = f; - sign = (conv.i>>31)&0x01; - expo = (conv.i>>23)&0xff; - - if UNLIKELY(expo >= 150/*+23*/) - { - /* An exponent (base-2) of 23 or higher is incapable of sub-integral - * precision, so it's already an integral value. We don't need to worry - * about infinity or NaN here. - */ - return f; - } - /* Adding the integral limit to the value (with a matching sign) forces a - * result that has no sub-integral precision, and is consequently forced to - * round to an integral value. Removing the integral limit then restores - * the initial value rounded to the integral. The compiler should not - * optimize this out because of non-associative rules on floating-point - * math (as long as you don't use -fassociative-math, - * -funsafe-math-optimizations, -ffast-math, or -Ofast, in which case this - * may break). - */ - f += ilim[sign]; - return f - ilim[sign]; -#endif -} - -#endif /* AL_NUMERIC_H */ diff --git a/common/aloptional.h b/common/aloptional.h deleted file mode 100644 index 0244c56f..00000000 --- a/common/aloptional.h +++ /dev/null @@ -1,161 +0,0 @@ -#ifndef AL_OPTIONAL_H -#define AL_OPTIONAL_H - -#include -#include -#include - -#include "almalloc.h" - -namespace al { - -struct nullopt_t { }; -struct in_place_t { }; - -constexpr nullopt_t nullopt{}; -constexpr in_place_t in_place{}; - - -template::value> -struct optional_storage; - -template -struct optional_storage { - bool mHasValue{false}; - union { - char mDummy; - T mValue; - }; - - optional_storage() { } - template - explicit optional_storage(in_place_t, Args&& ...args) - : mHasValue{true}, mValue{std::forward(args)...} - { } - ~optional_storage() = default; -}; - -template -struct optional_storage { - bool mHasValue{false}; - union { - char mDummy; - T mValue; - }; - - optional_storage() { } - template - explicit optional_storage(in_place_t, Args&& ...args) - : mHasValue{true}, mValue{std::forward(args)...} - { } - ~optional_storage() { if(mHasValue) al::destroy_at(std::addressof(mValue)); } -}; - -template -class optional { - using storage_t = optional_storage; - - storage_t mStore; - - template - void doConstruct(Args&& ...args) - { - ::new(std::addressof(mStore.mValue)) T{std::forward(args)...}; - mStore.mHasValue = true; - } - -public: - using value_type = T; - - optional() = default; - optional(nullopt_t) noexcept { } - optional(const optional &rhs) { if(rhs) doConstruct(*rhs); } - optional(optional&& rhs) { if(rhs) doConstruct(std::move(*rhs)); } - template - explicit optional(in_place_t, Args&& ...args) - : mStore{al::in_place, std::forward(args)...} - { } - ~optional() = default; - - optional& operator=(nullopt_t) noexcept { reset(); return *this; } - std::enable_if_t::value && std::is_copy_assignable::value, - optional&> operator=(const optional &rhs) - { - if(!rhs) - reset(); - else if(*this) - mStore.mValue = *rhs; - else - doConstruct(*rhs); - return *this; - } - std::enable_if_t::value && std::is_move_assignable::value, - optional&> operator=(optional&& rhs) - { - if(!rhs) - reset(); - else if(*this) - mStore.mValue = std::move(*rhs); - else - doConstruct(std::move(*rhs)); - return *this; - } - template - std::enable_if_t::value - && std::is_assignable::value - && !std::is_same, optional>::value - && (!std::is_same, T>::value || !std::is_scalar::value), - optional&> operator=(U&& rhs) - { - if(*this) - mStore.mValue = std::forward(rhs); - else - doConstruct(std::forward(rhs)); - return *this; - } - - const T* operator->() const { return std::addressof(mStore.mValue); } - T* operator->() { return std::addressof(mStore.mValue); } - const T& operator*() const& { return this->mValue; } - T& operator*() & { return mStore.mValue; } - const T&& operator*() const&& { return std::move(mStore.mValue); } - T&& operator*() && { return std::move(mStore.mValue); } - - operator bool() const noexcept { return mStore.mHasValue; } - bool has_value() const noexcept { return mStore.mHasValue; } - - T& value() & { return mStore.mValue; } - const T& value() const& { return mStore.mValue; } - T&& value() && { return std::move(mStore.mValue); } - const T&& value() const&& { return std::move(mStore.mValue); } - - template - T value_or(U&& defval) const& - { return bool{*this} ? **this : static_cast(std::forward(defval)); } - template - T value_or(U&& defval) && - { return bool{*this} ? std::move(**this) : static_cast(std::forward(defval)); } - - void reset() noexcept - { - if(mStore.mHasValue) - al::destroy_at(std::addressof(mStore.mValue)); - mStore.mHasValue = false; - } -}; - -template -inline optional> make_optional(T&& arg) -{ return optional>{in_place, std::forward(arg)}; } - -template -inline optional make_optional(Args&& ...args) -{ return optional{in_place, std::forward(args)...}; } - -template -inline optional make_optional(std::initializer_list il, Args&& ...args) -{ return optional{in_place, il, std::forward(args)...}; } - -} // namespace al - -#endif /* AL_OPTIONAL_H */ diff --git a/common/alspan.h b/common/alspan.h deleted file mode 100644 index f2c42b16..00000000 --- a/common/alspan.h +++ /dev/null @@ -1,315 +0,0 @@ -#ifndef AL_SPAN_H -#define AL_SPAN_H - -#include -#include -#include -#include -#include - -namespace al { - -template -constexpr auto size(T &cont) noexcept(noexcept(cont.size())) -> decltype(cont.size()) -{ return cont.size(); } - -template -constexpr auto size(const T &cont) noexcept(noexcept(cont.size())) -> decltype(cont.size()) -{ return cont.size(); } - -template -constexpr size_t size(T (&)[N]) noexcept -{ return N; } - -template -constexpr size_t size(std::initializer_list list) noexcept -{ return list.size(); } - - -template -constexpr auto data(T &cont) noexcept(noexcept(cont.data())) -> decltype(cont.data()) -{ return cont.data(); } - -template -constexpr auto data(const T &cont) noexcept(noexcept(cont.data())) -> decltype(cont.data()) -{ return cont.data(); } - -template -constexpr T* data(T (&arr)[N]) noexcept -{ return arr; } - -template -constexpr const T* data(std::initializer_list list) noexcept -{ return list.begin(); } - - -constexpr size_t dynamic_extent{static_cast(-1)}; - -template -class span; - -namespace detail_ { - template - struct make_void { using type = void; }; - template - using void_t = typename make_void::type; - - template - struct is_span_ : std::false_type { }; - template - struct is_span_> : std::true_type { }; - template - using is_span = is_span_>; - - template - struct is_std_array_ : std::false_type { }; - template - struct is_std_array_> : std::true_type { }; - template - using is_std_array = is_std_array_>; - - template - struct has_size_and_data : std::false_type { }; - template - struct has_size_and_data())), decltype(al::data(std::declval()))>> - : std::true_type { }; -} // namespace detail_ - -#define REQUIRES(...) bool rt_=true, std::enable_if_t = true -#define IS_VALID_CONTAINER(C) \ - !detail_::is_span::value && !detail_::is_std_array::value && \ - !std::is_array::value && detail_::has_size_and_data::value && \ - std::is_convertible()))>(*)[],element_type(*)[]>::value - -template -class span { -public: - using element_type = T; - using value_type = std::remove_cv_t; - using index_type = size_t; - using difference_type = ptrdiff_t; - - using pointer = T*; - using const_pointer = const T*; - using reference = T&; - using const_reference = const T&; - - using iterator = pointer; - using const_iterator = const_pointer; - using reverse_iterator = std::reverse_iterator; - using const_reverse_iterator = std::reverse_iterator; - - static constexpr size_t extent{E}; - - template - constexpr span() noexcept { } - constexpr span(pointer ptr, index_type /*count*/) : mData{ptr} { } - constexpr span(pointer first, pointer /*last*/) : mData{first} { } - constexpr span(element_type (&arr)[E]) noexcept : span{al::data(arr), al::size(arr)} { } - constexpr span(std::array &arr) noexcept : span{al::data(arr), al::size(arr)} { } - template::value)> - constexpr span(const std::array &arr) noexcept - : span{al::data(arr), al::size(arr)} - { } - template - constexpr span(U &cont) : span{al::data(cont), al::size(cont)} { } - template - constexpr span(const U &cont) : span{al::data(cont), al::size(cont)} { } - template::value - && std::is_convertible::value)> - constexpr span(const span &span_) noexcept : span{al::data(span_), al::size(span_)} { } - constexpr span(const span&) noexcept = default; - - constexpr span& operator=(const span &rhs) noexcept = default; - - constexpr reference front() const { return *mData; } - constexpr reference back() const { return *(mData+E-1); } - constexpr reference operator[](index_type idx) const { return mData[idx]; } - constexpr pointer data() const noexcept { return mData; } - - constexpr index_type size() const noexcept { return E; } - constexpr index_type size_bytes() const noexcept { return E * sizeof(value_type); } - constexpr bool empty() const noexcept { return E == 0; } - - constexpr iterator begin() const noexcept { return mData; } - constexpr iterator end() const noexcept { return mData+E; } - constexpr const_iterator cbegin() const noexcept { return mData; } - constexpr const_iterator cend() const noexcept { return mData+E; } - - constexpr reverse_iterator rbegin() const noexcept { return reverse_iterator{end()}; } - constexpr reverse_iterator rend() const noexcept { return reverse_iterator{begin()}; } - constexpr const_reverse_iterator crbegin() const noexcept - { return const_reverse_iterator{cend()}; } - constexpr const_reverse_iterator crend() const noexcept - { return const_reverse_iterator{cbegin()}; } - - template - constexpr span first() const - { - static_assert(E >= C, "New size exceeds original capacity"); - return span{mData, C}; - } - - template - constexpr span last() const - { - static_assert(E >= C, "New size exceeds original capacity"); - return span{mData+(E-C), C}; - } - - template - constexpr auto subspan() const -> std::enable_if_t> - { - static_assert(E >= O, "Offset exceeds extent"); - static_assert(E-O >= C, "New size exceeds original capacity"); - return span{mData+O, C}; - } - - template - constexpr auto subspan() const -> std::enable_if_t> - { - static_assert(E >= O, "Offset exceeds extent"); - return span{mData+O, E-O}; - } - - /* NOTE: Can't declare objects of a specialized template class prior to - * defining the specialization. As a result, these methods need to be - * defined later. - */ - constexpr span first(size_t count) const; - constexpr span last(size_t count) const; - constexpr span subspan(size_t offset, - size_t count=dynamic_extent) const; - -private: - pointer mData{nullptr}; -}; - -template -class span { -public: - using element_type = T; - using value_type = std::remove_cv_t; - using index_type = size_t; - using difference_type = ptrdiff_t; - - using pointer = T*; - using const_pointer = const T*; - using reference = T&; - using const_reference = const T&; - - using iterator = pointer; - using const_iterator = const_pointer; - using reverse_iterator = std::reverse_iterator; - using const_reverse_iterator = std::reverse_iterator; - - static constexpr size_t extent{dynamic_extent}; - - constexpr span() noexcept = default; - constexpr span(pointer ptr, index_type count) : mData{ptr}, mDataEnd{ptr+count} { } - constexpr span(pointer first, pointer last) : mData{first}, mDataEnd{last} { } - template - constexpr span(element_type (&arr)[N]) noexcept : span{al::data(arr), al::size(arr)} { } - template - constexpr span(std::array &arr) noexcept : span{al::data(arr), al::size(arr)} { } - template::value)> - constexpr span(const std::array &arr) noexcept - : span{al::data(arr), al::size(arr)} - { } - template - constexpr span(U &cont) : span{al::data(cont), al::size(cont)} { } - template - constexpr span(const U &cont) : span{al::data(cont), al::size(cont)} { } - template::value || extent != N) - && std::is_convertible::value)> - constexpr span(const span &span_) noexcept : span{al::data(span_), al::size(span_)} { } - constexpr span(const span&) noexcept = default; - - constexpr span& operator=(const span &rhs) noexcept = default; - - constexpr reference front() const { return *mData; } - constexpr reference back() const { return *(mDataEnd-1); } - constexpr reference operator[](index_type idx) const { return mData[idx]; } - constexpr pointer data() const noexcept { return mData; } - - constexpr index_type size() const noexcept { return static_cast(mDataEnd-mData); } - constexpr index_type size_bytes() const noexcept - { return static_cast(mDataEnd-mData) * sizeof(value_type); } - constexpr bool empty() const noexcept { return mData == mDataEnd; } - - constexpr iterator begin() const noexcept { return mData; } - constexpr iterator end() const noexcept { return mDataEnd; } - constexpr const_iterator cbegin() const noexcept { return mData; } - constexpr const_iterator cend() const noexcept { return mDataEnd; } - - constexpr reverse_iterator rbegin() const noexcept { return reverse_iterator{end()}; } - constexpr reverse_iterator rend() const noexcept { return reverse_iterator{begin()}; } - constexpr const_reverse_iterator crbegin() const noexcept - { return const_reverse_iterator{cend()}; } - constexpr const_reverse_iterator crend() const noexcept - { return const_reverse_iterator{cbegin()}; } - - template - constexpr span first() const - { return span{mData, C}; } - - constexpr span first(size_t count) const - { return (count >= size()) ? *this : span{mData, mData+count}; } - - template - constexpr span last() const - { return span{mDataEnd-C, C}; } - - constexpr span last(size_t count) const - { return (count >= size()) ? *this : span{mDataEnd-count, mDataEnd}; } - - template - constexpr auto subspan() const -> std::enable_if_t> - { return span{mData+O, C}; } - - template - constexpr auto subspan() const -> std::enable_if_t> - { return span{mData+O, mDataEnd}; } - - constexpr span subspan(size_t offset, size_t count=dynamic_extent) const - { - return (offset > size()) ? span{} : - (count >= size()-offset) ? span{mData+offset, mDataEnd} : - span{mData+offset, mData+offset+count}; - } - -private: - pointer mData{nullptr}; - pointer mDataEnd{nullptr}; -}; - -template -constexpr inline auto span::first(size_t count) const -> span -{ - return (count >= size()) ? span{mData, extent} : - span{mData, count}; -} - -template -constexpr inline auto span::last(size_t count) const -> span -{ - return (count >= size()) ? span{mData, extent} : - span{mData+extent-count, count}; -} - -template -constexpr inline auto span::subspan(size_t offset, size_t count) const - -> span -{ - return (offset > size()) ? span{} : - (count >= size()-offset) ? span{mData+offset, mData+extent} : - span{mData+offset, mData+offset+count}; -} - -#undef IS_VALID_CONTAINER -#undef REQUIRES - -} // namespace al - -#endif /* AL_SPAN_H */ diff --git a/common/alstring.cpp b/common/alstring.cpp deleted file mode 100644 index 4a84be1d..00000000 --- a/common/alstring.cpp +++ /dev/null @@ -1,45 +0,0 @@ - -#include "config.h" - -#include "alstring.h" - -#include -#include - - -namespace { - -int to_upper(const char ch) -{ - using char8_traits = std::char_traits; - return std::toupper(char8_traits::to_int_type(ch)); -} - -} // namespace - -namespace al { - -int strcasecmp(const char *str0, const char *str1) noexcept -{ - do { - const int diff{to_upper(*str0) - to_upper(*str1)}; - if(diff < 0) return -1; - if(diff > 0) return 1; - } while(*(str0++) && *(str1++)); - return 0; -} - -int strncasecmp(const char *str0, const char *str1, std::size_t len) noexcept -{ - if(len > 0) - { - do { - const int diff{to_upper(*str0) - to_upper(*str1)}; - if(diff < 0) return -1; - if(diff > 0) return 1; - } while(--len && *(str0++) && *(str1++)); - } - return 0; -} - -} // namespace al diff --git a/common/alstring.h b/common/alstring.h deleted file mode 100644 index 6c497190..00000000 --- a/common/alstring.h +++ /dev/null @@ -1,30 +0,0 @@ -#ifndef AL_STRING_H -#define AL_STRING_H - -#include -#include -#include - -#include "almalloc.h" - - -namespace al { - -template> -using basic_string = std::basic_string>; - -using string = basic_string; -using wstring = basic_string; -using u16string = basic_string; -using u32string = basic_string; - - -/* These would be better served by using a string_view-like span/view with - * case-insensitive char traits. - */ -int strcasecmp(const char *str0, const char *str1) noexcept; -int strncasecmp(const char *str0, const char *str1, std::size_t len) noexcept; - -} // namespace al - -#endif /* AL_STRING_H */ diff --git a/common/atomic.h b/common/atomic.h deleted file mode 100644 index 5e9b04c6..00000000 --- a/common/atomic.h +++ /dev/null @@ -1,33 +0,0 @@ -#ifndef AL_ATOMIC_H -#define AL_ATOMIC_H - -#include - - -using RefCount = std::atomic; - -inline void InitRef(RefCount &ref, unsigned int value) -{ ref.store(value, std::memory_order_relaxed); } -inline unsigned int ReadRef(RefCount &ref) -{ return ref.load(std::memory_order_acquire); } -inline unsigned int IncrementRef(RefCount &ref) -{ return ref.fetch_add(1u, std::memory_order_acq_rel)+1u; } -inline unsigned int DecrementRef(RefCount &ref) -{ return ref.fetch_sub(1u, std::memory_order_acq_rel)-1u; } - - -/* WARNING: A livelock is theoretically possible if another thread keeps - * changing the head without giving this a chance to actually swap in the new - * one (practically impossible with this little code, but...). - */ -template -inline void AtomicReplaceHead(std::atomic &head, T newhead) -{ - T first_ = head.load(std::memory_order_acquire); - do { - newhead->next.store(first_, std::memory_order_relaxed); - } while(!head.compare_exchange_weak(first_, newhead, - std::memory_order_acq_rel, std::memory_order_acquire)); -} - -#endif /* AL_ATOMIC_H */ diff --git a/common/dynload.cpp b/common/dynload.cpp deleted file mode 100644 index f1c2a7eb..00000000 --- a/common/dynload.cpp +++ /dev/null @@ -1,44 +0,0 @@ - -#include "config.h" - -#include "dynload.h" - -#include "strutils.h" - -#ifdef _WIN32 -#define WIN32_LEAN_AND_MEAN -#include - -void *LoadLib(const char *name) -{ - std::wstring wname{utf8_to_wstr(name)}; - return LoadLibraryW(wname.c_str()); -} -void CloseLib(void *handle) -{ FreeLibrary(static_cast(handle)); } -void *GetSymbol(void *handle, const char *name) -{ return reinterpret_cast(GetProcAddress(static_cast(handle), name)); } - -#elif defined(HAVE_DLFCN_H) - -#include - -void *LoadLib(const char *name) -{ - dlerror(); - void *handle{dlopen(name, RTLD_NOW)}; - const char *err{dlerror()}; - if(err) handle = nullptr; - return handle; -} -void CloseLib(void *handle) -{ dlclose(handle); } -void *GetSymbol(void *handle, const char *name) -{ - dlerror(); - void *sym{dlsym(handle, name)}; - const char *err{dlerror()}; - if(err) sym = nullptr; - return sym; -} -#endif diff --git a/common/dynload.h b/common/dynload.h deleted file mode 100644 index bd9e86f7..00000000 --- a/common/dynload.h +++ /dev/null @@ -1,14 +0,0 @@ -#ifndef AL_DYNLOAD_H -#define AL_DYNLOAD_H - -#if defined(_WIN32) || defined(HAVE_DLFCN_H) - -#define HAVE_DYNLOAD - -void *LoadLib(const char *name); -void CloseLib(void *handle); -void *GetSymbol(void *handle, const char *name); - -#endif - -#endif /* AL_DYNLOAD_H */ diff --git a/common/intrusive_ptr.h b/common/intrusive_ptr.h deleted file mode 100644 index cc82dea5..00000000 --- a/common/intrusive_ptr.h +++ /dev/null @@ -1,120 +0,0 @@ -#ifndef INTRUSIVE_PTR_H -#define INTRUSIVE_PTR_H - -#include "atomic.h" -#include "opthelpers.h" - - -namespace al { - -template -class intrusive_ref { - RefCount mRef{1u}; - -public: - unsigned int add_ref() noexcept { return IncrementRef(mRef); } - unsigned int release() noexcept - { - auto ref = DecrementRef(mRef); - if UNLIKELY(ref == 0) - delete static_cast(this); - return ref; - } - - /** - * Release only if doing so would not bring the object to 0 references and - * delete it. Returns false if the object could not be released. - * - * NOTE: The caller is responsible for handling a failed release, as it - * means the object has no other references and needs to be be deleted - * somehow. - */ - bool releaseIfNoDelete() noexcept - { - auto val = mRef.load(std::memory_order_acquire); - while(val > 1 && !mRef.compare_exchange_strong(val, val-1, std::memory_order_acq_rel)) - { - /* val was updated with the current value on failure, so just try - * again. - */ - } - - return val >= 2; - } -}; - - -template -class intrusive_ptr { - T *mPtr{nullptr}; - -public: - intrusive_ptr() noexcept = default; - intrusive_ptr(const intrusive_ptr &rhs) noexcept : mPtr{rhs.mPtr} - { if(mPtr) mPtr->add_ref(); } - intrusive_ptr(intrusive_ptr&& rhs) noexcept : mPtr{rhs.mPtr} - { rhs.mPtr = nullptr; } - intrusive_ptr(std::nullptr_t) noexcept { } - explicit intrusive_ptr(T *ptr) noexcept : mPtr{ptr} { } - ~intrusive_ptr() { if(mPtr) mPtr->release(); } - - intrusive_ptr& operator=(const intrusive_ptr &rhs) noexcept - { - if(rhs.mPtr) rhs.mPtr->add_ref(); - if(mPtr) mPtr->release(); - mPtr = rhs.mPtr; - return *this; - } - intrusive_ptr& operator=(intrusive_ptr&& rhs) noexcept - { - if(mPtr) - mPtr->release(); - mPtr = rhs.mPtr; - rhs.mPtr = nullptr; - return *this; - } - - operator bool() const noexcept { return mPtr != nullptr; } - - T& operator*() const noexcept { return *mPtr; } - T* operator->() const noexcept { return mPtr; } - T* get() const noexcept { return mPtr; } - - void reset(T *ptr=nullptr) noexcept - { - if(mPtr) - mPtr->release(); - mPtr = ptr; - } - - T* release() noexcept - { - T *ret{mPtr}; - mPtr = nullptr; - return ret; - } - - void swap(intrusive_ptr &rhs) noexcept { std::swap(mPtr, rhs.mPtr); } - void swap(intrusive_ptr&& rhs) noexcept { std::swap(mPtr, rhs.mPtr); } -}; - -#define AL_DECL_OP(op) \ -template \ -inline bool operator op(const intrusive_ptr &lhs, const T *rhs) noexcept \ -{ return lhs.get() op rhs; } \ -template \ -inline bool operator op(const T *lhs, const intrusive_ptr &rhs) noexcept \ -{ return lhs op rhs.get(); } - -AL_DECL_OP(==) -AL_DECL_OP(!=) -AL_DECL_OP(<=) -AL_DECL_OP(>=) -AL_DECL_OP(<) -AL_DECL_OP(>) - -#undef AL_DECL_OP - -} // namespace al - -#endif /* INTRUSIVE_PTR_H */ diff --git a/common/math_defs.h b/common/math_defs.h deleted file mode 100644 index ba007115..00000000 --- a/common/math_defs.h +++ /dev/null @@ -1,26 +0,0 @@ -#ifndef AL_MATH_DEFS_H -#define AL_MATH_DEFS_H - -constexpr float Deg2Rad(float x) noexcept { return x * 1.74532925199432955e-02f/*pi/180*/; } -constexpr float Rad2Deg(float x) noexcept { return x * 5.72957795130823229e+01f/*180/pi*/; } - -namespace al { - -template -struct MathDefs { }; - -template<> -struct MathDefs { - static constexpr float Pi() noexcept { return 3.14159265358979323846e+00f; } - static constexpr float Tau() noexcept { return 6.28318530717958647692e+00f; } -}; - -template<> -struct MathDefs { - static constexpr double Pi() noexcept { return 3.14159265358979323846e+00; } - static constexpr double Tau() noexcept { return 6.28318530717958647692e+00; } -}; - -} // namespace al - -#endif /* AL_MATH_DEFS_H */ diff --git a/common/opthelpers.h b/common/opthelpers.h deleted file mode 100644 index 8f16fd3f..00000000 --- a/common/opthelpers.h +++ /dev/null @@ -1,39 +0,0 @@ -#ifndef OPTHELPERS_H -#define OPTHELPERS_H - -#ifdef __has_builtin -#define HAS_BUILTIN __has_builtin -#else -#define HAS_BUILTIN(x) (0) -#endif - -#if defined(__GNUC__) || HAS_BUILTIN(__builtin_expect) -/* LIKELY optimizes the case where the condition is true. The condition is not - * required to be true, but it can result in more optimal code for the true - * path at the expense of a less optimal false path. - */ -#define LIKELY(x) (__builtin_expect(!!(x), !false)) -/* The opposite of LIKELY, optimizing the case where the condition is false. */ -#define UNLIKELY(x) (__builtin_expect(!!(x), false)) - -#else - -#define LIKELY(x) (!!(x)) -#define UNLIKELY(x) (!!(x)) -#endif - -#if HAS_BUILTIN(__builtin_assume) -/* Unlike LIKELY, ASSUME requires the condition to be true or else it invokes - * undefined behavior. It's essentially an assert without actually checking the - * condition at run-time, allowing for stronger optimizations than LIKELY. - */ -#define ASSUME __builtin_assume -#elif defined(_MSC_VER) -#define ASSUME __assume -#elif defined(__GNUC__) -#define ASSUME(x) do { if(!(x)) __builtin_unreachable(); } while(0) -#else -#define ASSUME(x) ((void)0) -#endif - -#endif /* OPTHELPERS_H */ diff --git a/common/polyphase_resampler.cpp b/common/polyphase_resampler.cpp deleted file mode 100644 index 88c4bc4b..00000000 --- a/common/polyphase_resampler.cpp +++ /dev/null @@ -1,222 +0,0 @@ - -#include "polyphase_resampler.h" - -#include -#include - -#include "math_defs.h" -#include "opthelpers.h" - - -namespace { - -constexpr double Epsilon{1e-9}; - -using uint = unsigned int; - -/* This is the normalized cardinal sine (sinc) function. - * - * sinc(x) = { 1, x = 0 - * { sin(pi x) / (pi x), otherwise. - */ -double Sinc(const double x) -{ - if UNLIKELY(std::abs(x) < Epsilon) - return 1.0; - return std::sin(al::MathDefs::Pi()*x) / (al::MathDefs::Pi()*x); -} - -/* The zero-order modified Bessel function of the first kind, used for the - * Kaiser window. - * - * I_0(x) = sum_{k=0}^inf (1 / k!)^2 (x / 2)^(2 k) - * = sum_{k=0}^inf ((x / 2)^k / k!)^2 - */ -constexpr double BesselI_0(const double x) -{ - // Start at k=1 since k=0 is trivial. - const double x2{x/2.0}; - double term{1.0}; - double sum{1.0}; - int k{1}; - - // Let the integration converge until the term of the sum is no longer - // significant. - double last_sum{}; - do { - const double y{x2 / k}; - ++k; - last_sum = sum; - term *= y * y; - sum += term; - } while(sum != last_sum); - return sum; -} - -/* Calculate a Kaiser window from the given beta value and a normalized k - * [-1, 1]. - * - * w(k) = { I_0(B sqrt(1 - k^2)) / I_0(B), -1 <= k <= 1 - * { 0, elsewhere. - * - * Where k can be calculated as: - * - * k = i / l, where -l <= i <= l. - * - * or: - * - * k = 2 i / M - 1, where 0 <= i <= M. - */ -double Kaiser(const double b, const double k) -{ - if(!(k >= -1.0 && k <= 1.0)) - return 0.0; - return BesselI_0(b * std::sqrt(1.0 - k*k)) / BesselI_0(b); -} - -// Calculates the greatest common divisor of a and b. -constexpr uint Gcd(uint x, uint y) -{ - while(y > 0) - { - const uint z{y}; - y = x % y; - x = z; - } - return x; -} - -/* Calculates the size (order) of the Kaiser window. Rejection is in dB and - * the transition width is normalized frequency (0.5 is nyquist). - * - * M = { ceil((r - 7.95) / (2.285 2 pi f_t)), r > 21 - * { ceil(5.79 / 2 pi f_t), r <= 21. - * - */ -constexpr uint CalcKaiserOrder(const double rejection, const double transition) -{ - const double w_t{2.0 * al::MathDefs::Pi() * transition}; - if LIKELY(rejection > 21.0) - return static_cast(std::ceil((rejection - 7.95) / (2.285 * w_t))); - return static_cast(std::ceil(5.79 / w_t)); -} - -// Calculates the beta value of the Kaiser window. Rejection is in dB. -constexpr double CalcKaiserBeta(const double rejection) -{ - if LIKELY(rejection > 50.0) - return 0.1102 * (rejection - 8.7); - if(rejection >= 21.0) - return (0.5842 * std::pow(rejection - 21.0, 0.4)) + - (0.07886 * (rejection - 21.0)); - return 0.0; -} - -/* Calculates a point on the Kaiser-windowed sinc filter for the given half- - * width, beta, gain, and cutoff. The point is specified in non-normalized - * samples, from 0 to M, where M = (2 l + 1). - * - * w(k) 2 p f_t sinc(2 f_t x) - * - * x -- centered sample index (i - l) - * k -- normalized and centered window index (x / l) - * w(k) -- window function (Kaiser) - * p -- gain compensation factor when sampling - * f_t -- normalized center frequency (or cutoff; 0.5 is nyquist) - */ -double SincFilter(const uint l, const double b, const double gain, const double cutoff, - const uint i) -{ - const double x{static_cast(i) - l}; - return Kaiser(b, x / l) * 2.0 * gain * cutoff * Sinc(2.0 * cutoff * x); -} - -} // namespace - -// Calculate the resampling metrics and build the Kaiser-windowed sinc filter -// that's used to cut frequencies above the destination nyquist. -void PPhaseResampler::init(const uint srcRate, const uint dstRate) -{ - const uint gcd{Gcd(srcRate, dstRate)}; - mP = dstRate / gcd; - mQ = srcRate / gcd; - - /* The cutoff is adjusted by half the transition width, so the transition - * ends before the nyquist (0.5). Both are scaled by the downsampling - * factor. - */ - double cutoff, width; - if(mP > mQ) - { - cutoff = 0.475 / mP; - width = 0.05 / mP; - } - else - { - cutoff = 0.475 / mQ; - width = 0.05 / mQ; - } - // A rejection of -180 dB is used for the stop band. Round up when - // calculating the left offset to avoid increasing the transition width. - const uint l{(CalcKaiserOrder(180.0, width)+1) / 2}; - const double beta{CalcKaiserBeta(180.0)}; - mM = l*2 + 1; - mL = l; - mF.resize(mM); - for(uint i{0};i < mM;i++) - mF[i] = SincFilter(l, beta, mP, cutoff, i); -} - -// Perform the upsample-filter-downsample resampling operation using a -// polyphase filter implementation. -void PPhaseResampler::process(const uint inN, const double *in, const uint outN, double *out) -{ - if UNLIKELY(outN == 0) - return; - - // Handle in-place operation. - std::vector workspace; - double *work{out}; - if UNLIKELY(work == in) - { - workspace.resize(outN); - work = workspace.data(); - } - - // Resample the input. - const uint p{mP}, q{mQ}, m{mM}, l{mL}; - const double *f{mF.data()}; - for(uint i{0};i < outN;i++) - { - // Input starts at l to compensate for the filter delay. This will - // drop any build-up from the first half of the filter. - size_t j_f{(l + q*i) % p}; - size_t j_s{(l + q*i) / p}; - - // Only take input when 0 <= j_s < inN. - double r{0.0}; - if LIKELY(j_f < m) - { - size_t filt_len{(m-j_f+p-1) / p}; - if LIKELY(j_s+1 > inN) - { - size_t skip{std::min(j_s+1 - inN, filt_len)}; - j_f += p*skip; - j_s -= skip; - filt_len -= skip; - } - if(size_t todo{std::min(j_s+1, filt_len)}) - { - do { - r += f[j_f] * in[j_s]; - j_f += p; - --j_s; - } while(--todo); - } - } - work[i] = r; - } - // Clean up after in-place operation. - if(work != out) - std::copy_n(work, outN, out); -} diff --git a/common/polyphase_resampler.h b/common/polyphase_resampler.h deleted file mode 100644 index e9833d12..00000000 --- a/common/polyphase_resampler.h +++ /dev/null @@ -1,45 +0,0 @@ -#ifndef POLYPHASE_RESAMPLER_H -#define POLYPHASE_RESAMPLER_H - -#include - - -/* This is a polyphase sinc-filtered resampler. It is built for very high - * quality results, rather than real-time performance. - * - * Upsample Downsample - * - * p/q = 3/2 p/q = 3/5 - * - * M-+-+-+-> M-+-+-+-> - * -------------------+ ---------------------+ - * p s * f f f f|f| | p s * f f f f f | - * | 0 * 0 0 0|0|0 | | 0 * 0 0 0 0|0| | - * v 0 * 0 0|0|0 0 | v 0 * 0 0 0|0|0 | - * s * f|f|f f f | s * f f|f|f f | - * 0 * |0|0 0 0 0 | 0 * 0|0|0 0 0 | - * --------+=+--------+ 0 * |0|0 0 0 0 | - * d . d .|d|. d . d ----------+=+--------+ - * d . . . .|d|. . . . - * q-> - * q-+-+-+-> - * - * P_f(i,j) = q i mod p + pj - * P_s(i,j) = floor(q i / p) - j - * d[i=0..N-1] = sum_{j=0}^{floor((M - 1) / p)} { - * { f[P_f(i,j)] s[P_s(i,j)], P_f(i,j) < M - * { 0, P_f(i,j) >= M. } - */ - -struct PPhaseResampler { - using uint = unsigned int; - - void init(const uint srcRate, const uint dstRate); - void process(const uint inN, const double *in, const uint outN, double *out); - -private: - uint mP, mQ, mM, mL; - std::vector mF; -}; - -#endif /* POLYPHASE_RESAMPLER_H */ diff --git a/common/pragmadefs.h b/common/pragmadefs.h deleted file mode 100644 index 9f0a711f..00000000 --- a/common/pragmadefs.h +++ /dev/null @@ -1,21 +0,0 @@ -#ifndef PRAGMADEFS_H -#define PRAGMADEFS_H - -#if defined(_MSC_VER) -#define DIAGNOSTIC_PUSH __pragma(warning(push)) -#define DIAGNOSTIC_POP __pragma(warning(pop)) -#define std_pragma(...) -#define msc_pragma __pragma -#else -#if defined(__GNUC__) || defined(__clang__) -#define DIAGNOSTIC_PUSH _Pragma("GCC diagnostic push") -#define DIAGNOSTIC_POP _Pragma("GCC diagnostic pop") -#else -#define DIAGNOSTIC_PUSH -#define DIAGNOSTIC_POP -#endif -#define std_pragma _Pragma -#define msc_pragma(...) -#endif - -#endif /* PRAGMADEFS_H */ diff --git a/common/ringbuffer.cpp b/common/ringbuffer.cpp deleted file mode 100644 index 91857499..00000000 --- a/common/ringbuffer.cpp +++ /dev/null @@ -1,224 +0,0 @@ -/** - * OpenAL cross platform audio library - * Copyright (C) 1999-2007 by authors. - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - * Or go to http://www.gnu.org/copyleft/lgpl.html - */ - -#include "config.h" - -#include "ringbuffer.h" - -#include -#include -#include - -#include "almalloc.h" - - -RingBufferPtr RingBuffer::Create(size_t sz, size_t elem_sz, int limit_writes) -{ - size_t power_of_two{0u}; - if(sz > 0) - { - power_of_two = sz; - power_of_two |= power_of_two>>1; - power_of_two |= power_of_two>>2; - power_of_two |= power_of_two>>4; - power_of_two |= power_of_two>>8; - power_of_two |= power_of_two>>16; -#if SIZE_MAX > UINT_MAX - power_of_two |= power_of_two>>32; -#endif - } - ++power_of_two; - if(power_of_two <= sz || power_of_two > std::numeric_limits::max()/elem_sz) - throw std::overflow_error{"Ring buffer size overflow"}; - - const size_t bufbytes{power_of_two * elem_sz}; - RingBufferPtr rb{new(FamCount(bufbytes)) RingBuffer{bufbytes}}; - rb->mWriteSize = limit_writes ? sz : (power_of_two-1); - rb->mSizeMask = power_of_two - 1; - rb->mElemSize = elem_sz; - - return rb; -} - -void RingBuffer::reset() noexcept -{ - mWritePtr.store(0, std::memory_order_relaxed); - mReadPtr.store(0, std::memory_order_relaxed); - std::fill_n(mBuffer.begin(), (mSizeMask+1)*mElemSize, al::byte{}); -} - - -size_t RingBuffer::read(void *dest, size_t cnt) noexcept -{ - const size_t free_cnt{readSpace()}; - if(free_cnt == 0) return 0; - - const size_t to_read{std::min(cnt, free_cnt)}; - size_t read_ptr{mReadPtr.load(std::memory_order_relaxed) & mSizeMask}; - - size_t n1, n2; - const size_t cnt2{read_ptr + to_read}; - if(cnt2 > mSizeMask+1) - { - n1 = mSizeMask+1 - read_ptr; - n2 = cnt2 & mSizeMask; - } - else - { - n1 = to_read; - n2 = 0; - } - - auto outiter = std::copy_n(mBuffer.begin() + read_ptr*mElemSize, n1*mElemSize, - static_cast(dest)); - read_ptr += n1; - if(n2 > 0) - { - std::copy_n(mBuffer.begin(), n2*mElemSize, outiter); - read_ptr += n2; - } - mReadPtr.store(read_ptr, std::memory_order_release); - return to_read; -} - -size_t RingBuffer::peek(void *dest, size_t cnt) const noexcept -{ - const size_t free_cnt{readSpace()}; - if(free_cnt == 0) return 0; - - const size_t to_read{std::min(cnt, free_cnt)}; - size_t read_ptr{mReadPtr.load(std::memory_order_relaxed) & mSizeMask}; - - size_t n1, n2; - const size_t cnt2{read_ptr + to_read}; - if(cnt2 > mSizeMask+1) - { - n1 = mSizeMask+1 - read_ptr; - n2 = cnt2 & mSizeMask; - } - else - { - n1 = to_read; - n2 = 0; - } - - auto outiter = std::copy_n(mBuffer.begin() + read_ptr*mElemSize, n1*mElemSize, - static_cast(dest)); - if(n2 > 0) - std::copy_n(mBuffer.begin(), n2*mElemSize, outiter); - return to_read; -} - -size_t RingBuffer::write(const void *src, size_t cnt) noexcept -{ - const size_t free_cnt{writeSpace()}; - if(free_cnt == 0) return 0; - - const size_t to_write{std::min(cnt, free_cnt)}; - size_t write_ptr{mWritePtr.load(std::memory_order_relaxed) & mSizeMask}; - - size_t n1, n2; - const size_t cnt2{write_ptr + to_write}; - if(cnt2 > mSizeMask+1) - { - n1 = mSizeMask+1 - write_ptr; - n2 = cnt2 & mSizeMask; - } - else - { - n1 = to_write; - n2 = 0; - } - - auto srcbytes = static_cast(src); - std::copy_n(srcbytes, n1*mElemSize, mBuffer.begin() + write_ptr*mElemSize); - write_ptr += n1; - if(n2 > 0) - { - std::copy_n(srcbytes + n1*mElemSize, n2*mElemSize, mBuffer.begin()); - write_ptr += n2; - } - mWritePtr.store(write_ptr, std::memory_order_release); - return to_write; -} - - -ll_ringbuffer_data_pair RingBuffer::getReadVector() const noexcept -{ - ll_ringbuffer_data_pair ret; - - size_t w{mWritePtr.load(std::memory_order_acquire)}; - size_t r{mReadPtr.load(std::memory_order_acquire)}; - w &= mSizeMask; - r &= mSizeMask; - const size_t free_cnt{(w-r) & mSizeMask}; - - const size_t cnt2{r + free_cnt}; - if(cnt2 > mSizeMask+1) - { - /* Two part vector: the rest of the buffer after the current read ptr, - * plus some from the start of the buffer. */ - ret.first.buf = const_cast(mBuffer.data() + r*mElemSize); - ret.first.len = mSizeMask+1 - r; - ret.second.buf = const_cast(mBuffer.data()); - ret.second.len = cnt2 & mSizeMask; - } - else - { - /* Single part vector: just the rest of the buffer */ - ret.first.buf = const_cast(mBuffer.data() + r*mElemSize); - ret.first.len = free_cnt; - ret.second.buf = nullptr; - ret.second.len = 0; - } - - return ret; -} - -ll_ringbuffer_data_pair RingBuffer::getWriteVector() const noexcept -{ - ll_ringbuffer_data_pair ret; - - size_t w{mWritePtr.load(std::memory_order_acquire)}; - size_t r{mReadPtr.load(std::memory_order_acquire) + mWriteSize - mSizeMask}; - w &= mSizeMask; - r &= mSizeMask; - const size_t free_cnt{(r-w-1) & mSizeMask}; - - const size_t cnt2{w + free_cnt}; - if(cnt2 > mSizeMask+1) - { - /* Two part vector: the rest of the buffer after the current write ptr, - * plus some from the start of the buffer. */ - ret.first.buf = const_cast(mBuffer.data() + w*mElemSize); - ret.first.len = mSizeMask+1 - w; - ret.second.buf = const_cast(mBuffer.data()); - ret.second.len = cnt2 & mSizeMask; - } - else - { - ret.first.buf = const_cast(mBuffer.data() + w*mElemSize); - ret.first.len = free_cnt; - ret.second.buf = nullptr; - ret.second.len = 0; - } - - return ret; -} diff --git a/common/ringbuffer.h b/common/ringbuffer.h deleted file mode 100644 index fa8fce10..00000000 --- a/common/ringbuffer.h +++ /dev/null @@ -1,113 +0,0 @@ -#ifndef RINGBUFFER_H -#define RINGBUFFER_H - -#include -#include -#include -#include - -#include "albyte.h" -#include "almalloc.h" - - -/* NOTE: This lockless ringbuffer implementation is copied from JACK, extended - * to include an element size. Consequently, parameters and return values for a - * size or count is in 'elements', not bytes. Additionally, it only supports - * single-consumer/single-provider operation. - */ - -struct ll_ringbuffer_data { - al::byte *buf; - size_t len; -}; -using ll_ringbuffer_data_pair = std::pair; - - -struct RingBuffer { -private: - std::atomic mWritePtr{0u}; - std::atomic mReadPtr{0u}; - size_t mWriteSize{0u}; - size_t mSizeMask{0u}; - size_t mElemSize{0u}; - - al::FlexArray mBuffer; - -public: - RingBuffer(const size_t count) : mBuffer{count} { } - - /** Reset the read and write pointers to zero. This is not thread safe. */ - void reset() noexcept; - - /** - * The non-copying data reader. Returns two ringbuffer data pointers that - * hold the current readable data. If the readable data is in one segment - * the second segment has zero length. - */ - ll_ringbuffer_data_pair getReadVector() const noexcept; - /** - * The non-copying data writer. Returns two ringbuffer data pointers that - * hold the current writeable data. If the writeable data is in one segment - * the second segment has zero length. - */ - ll_ringbuffer_data_pair getWriteVector() const noexcept; - - /** - * Return the number of elements available for reading. This is the number - * of elements in front of the read pointer and behind the write pointer. - */ - size_t readSpace() const noexcept - { - const size_t w{mWritePtr.load(std::memory_order_acquire)}; - const size_t r{mReadPtr.load(std::memory_order_acquire)}; - return (w-r) & mSizeMask; - } - - /** - * The copying data reader. Copy at most `cnt' elements into `dest'. - * Returns the actual number of elements copied. - */ - size_t read(void *dest, size_t cnt) noexcept; - /** - * The copying data reader w/o read pointer advance. Copy at most `cnt' - * elements into `dest'. Returns the actual number of elements copied. - */ - size_t peek(void *dest, size_t cnt) const noexcept; - /** Advance the read pointer `cnt' places. */ - void readAdvance(size_t cnt) noexcept - { mReadPtr.fetch_add(cnt, std::memory_order_acq_rel); } - - - /** - * Return the number of elements available for writing. This is the number - * of elements in front of the write pointer and behind the read pointer. - */ - size_t writeSpace() const noexcept - { - const size_t w{mWritePtr.load(std::memory_order_acquire)}; - const size_t r{mReadPtr.load(std::memory_order_acquire) + mWriteSize - mSizeMask}; - return (r-w-1) & mSizeMask; - } - - /** - * The copying data writer. Copy at most `cnt' elements from `src'. Returns - * the actual number of elements copied. - */ - size_t write(const void *src, size_t cnt) noexcept; - /** Advance the write pointer `cnt' places. */ - void writeAdvance(size_t cnt) noexcept - { mWritePtr.fetch_add(cnt, std::memory_order_acq_rel); } - - /** - * Create a new ringbuffer to hold at least `sz' elements of `elem_sz' - * bytes. The number of elements is rounded up to the next power of two - * (even if it is already a power of two, to ensure the requested amount - * can be written). - */ - static std::unique_ptr Create(size_t sz, size_t elem_sz, int limit_writes); - - DEF_FAM_NEWDEL(RingBuffer, mBuffer) -}; -using RingBufferPtr = std::unique_ptr; - -#endif /* RINGBUFFER_H */ diff --git a/common/strutils.cpp b/common/strutils.cpp deleted file mode 100644 index 18c4947a..00000000 --- a/common/strutils.cpp +++ /dev/null @@ -1,64 +0,0 @@ - -#include "config.h" - -#include "strutils.h" - -#include - - -#ifdef _WIN32 -#define WIN32_LEAN_AND_MEAN -#include - -std::string wstr_to_utf8(const WCHAR *wstr) -{ - std::string ret; - - int len = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, nullptr, 0, nullptr, nullptr); - if(len > 0) - { - ret.resize(len); - WideCharToMultiByte(CP_UTF8, 0, wstr, -1, &ret[0], len, nullptr, nullptr); - ret.pop_back(); - } - - return ret; -} - -std::wstring utf8_to_wstr(const char *str) -{ - std::wstring ret; - - int len = MultiByteToWideChar(CP_UTF8, 0, str, -1, nullptr, 0); - if(len > 0) - { - ret.resize(len); - MultiByteToWideChar(CP_UTF8, 0, str, -1, &ret[0], len); - ret.pop_back(); - } - - return ret; -} -#endif - -namespace al { - -al::optional getenv(const char *envname) -{ - const char *str{std::getenv(envname)}; - if(str && str[0] != '\0') - return al::make_optional(str); - return al::nullopt; -} - -#ifdef _WIN32 -al::optional getenv(const WCHAR *envname) -{ - const WCHAR *str{_wgetenv(envname)}; - if(str && str[0] != L'\0') - return al::make_optional(str); - return al::nullopt; -} -#endif - -} // namespace al diff --git a/common/strutils.h b/common/strutils.h deleted file mode 100644 index 0c7a0e22..00000000 --- a/common/strutils.h +++ /dev/null @@ -1,24 +0,0 @@ -#ifndef AL_STRUTILS_H -#define AL_STRUTILS_H - -#include - -#include "aloptional.h" - -#ifdef _WIN32 -#include - -std::string wstr_to_utf8(const wchar_t *wstr); -std::wstring utf8_to_wstr(const char *str); -#endif - -namespace al { - -al::optional getenv(const char *envname); -#ifdef _WIN32 -al::optional getenv(const wchar_t *envname); -#endif - -} // namespace al - -#endif /* AL_STRUTILS_H */ diff --git a/common/threads.cpp b/common/threads.cpp deleted file mode 100644 index e847d1f8..00000000 --- a/common/threads.cpp +++ /dev/null @@ -1,176 +0,0 @@ -/** - * OpenAL cross platform audio library - * Copyright (C) 1999-2007 by authors. - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - * Or go to http://www.gnu.org/copyleft/lgpl.html - */ - -#include "config.h" - -#include "opthelpers.h" -#include "threads.h" - -#include - - -#ifdef _WIN32 -#define WIN32_LEAN_AND_MEAN -#include - -#include - -void althrd_setname(const char *name) -{ -#if defined(_MSC_VER) -#define MS_VC_EXCEPTION 0x406D1388 -#pragma pack(push,8) - struct { - DWORD dwType; // Must be 0x1000. - LPCSTR szName; // Pointer to name (in user addr space). - DWORD dwThreadID; // Thread ID (-1=caller thread). - DWORD dwFlags; // Reserved for future use, must be zero. - } info; -#pragma pack(pop) - info.dwType = 0x1000; - info.szName = name; - info.dwThreadID = ~DWORD{0}; - info.dwFlags = 0; - - __try { - RaiseException(MS_VC_EXCEPTION, 0, sizeof(info)/sizeof(ULONG_PTR), (ULONG_PTR*)&info); - } - __except(EXCEPTION_CONTINUE_EXECUTION) { - } -#undef MS_VC_EXCEPTION -#else - (void)name; -#endif -} - -namespace al { - -semaphore::semaphore(unsigned int initial) -{ - if(initial > static_cast(std::numeric_limits::max())) - throw std::system_error(std::make_error_code(std::errc::value_too_large)); - mSem = CreateSemaphore(nullptr, initial, std::numeric_limits::max(), nullptr); - if(mSem == nullptr) - throw std::system_error(std::make_error_code(std::errc::resource_unavailable_try_again)); -} - -semaphore::~semaphore() -{ CloseHandle(mSem); } - -void semaphore::post() -{ - if UNLIKELY(!ReleaseSemaphore(static_cast(mSem), 1, nullptr)) - throw std::system_error(std::make_error_code(std::errc::value_too_large)); -} - -void semaphore::wait() noexcept -{ WaitForSingleObject(static_cast(mSem), INFINITE); } - -bool semaphore::try_wait() noexcept -{ return WaitForSingleObject(static_cast(mSem), 0) == WAIT_OBJECT_0; } - -} // namespace al - -#else - -#if defined(HAVE_PTHREAD_SETNAME_NP) || defined(HAVE_PTHREAD_SET_NAME_NP) -#include -#ifdef HAVE_PTHREAD_NP_H -#include -#endif - -void althrd_setname(const char *name) -{ -#if defined(HAVE_PTHREAD_SET_NAME_NP) - pthread_set_name_np(pthread_self(), name); -#elif defined(PTHREAD_SETNAME_NP_ONE_PARAM) - pthread_setname_np(name); -#elif defined(PTHREAD_SETNAME_NP_THREE_PARAMS) - pthread_setname_np(pthread_self(), "%s", (void*)name); -#else - pthread_setname_np(pthread_self(), name); -#endif -} - -#else - -void althrd_setname(const char*) { } -#endif - -#ifdef __APPLE__ - -namespace al { - -semaphore::semaphore(unsigned int initial) -{ - mSem = dispatch_semaphore_create(initial); - if(!mSem) - throw std::system_error(std::make_error_code(std::errc::resource_unavailable_try_again)); -} - -semaphore::~semaphore() -{ dispatch_release(mSem); } - -void semaphore::post() -{ dispatch_semaphore_signal(mSem); } - -void semaphore::wait() noexcept -{ dispatch_semaphore_wait(mSem, DISPATCH_TIME_FOREVER); } - -bool semaphore::try_wait() noexcept -{ return dispatch_semaphore_wait(mSem, DISPATCH_TIME_NOW) == 0; } - -} // namespace al - -#else /* !__APPLE__ */ - -#include - -namespace al { - -semaphore::semaphore(unsigned int initial) -{ - if(sem_init(&mSem, 0, initial) != 0) - throw std::system_error(std::make_error_code(std::errc::resource_unavailable_try_again)); -} - -semaphore::~semaphore() -{ sem_destroy(&mSem); } - -void semaphore::post() -{ - if(sem_post(&mSem) != 0) - throw std::system_error(std::make_error_code(std::errc::value_too_large)); -} - -void semaphore::wait() noexcept -{ - while(sem_wait(&mSem) == -1 && errno == EINTR) { - } -} - -bool semaphore::try_wait() noexcept -{ return sem_trywait(&mSem) == 0; } - -} // namespace al - -#endif /* __APPLE__ */ - -#endif /* _WIN32 */ diff --git a/common/threads.h b/common/threads.h deleted file mode 100644 index 1cdb5d8f..00000000 --- a/common/threads.h +++ /dev/null @@ -1,48 +0,0 @@ -#ifndef AL_THREADS_H -#define AL_THREADS_H - -#if defined(__GNUC__) && defined(__i386__) -/* force_align_arg_pointer is required for proper function arguments aligning - * when SSE code is used. Some systems (Windows, QNX) do not guarantee our - * thread functions will be properly aligned on the stack, even though GCC may - * generate code with the assumption that it is. */ -#define FORCE_ALIGN __attribute__((force_align_arg_pointer)) -#else -#define FORCE_ALIGN -#endif - -#if defined(__APPLE__) -#include -#elif !defined(_WIN32) -#include -#endif - -void althrd_setname(const char *name); - -namespace al { - -class semaphore { -#ifdef _WIN32 - using native_type = void*; -#elif defined(__APPLE__) - using native_type = dispatch_semaphore_t; -#else - using native_type = sem_t; -#endif - native_type mSem; - -public: - semaphore(unsigned int initial=0); - semaphore(const semaphore&) = delete; - ~semaphore(); - - semaphore& operator=(const semaphore&) = delete; - - void post(); - void wait() noexcept; - bool try_wait() noexcept; -}; - -} // namespace al - -#endif /* AL_THREADS_H */ diff --git a/common/vecmat.h b/common/vecmat.h deleted file mode 100644 index d301cc30..00000000 --- a/common/vecmat.h +++ /dev/null @@ -1,118 +0,0 @@ -#ifndef COMMON_VECMAT_H -#define COMMON_VECMAT_H - -#include -#include -#include -#include - -#include "alspan.h" - - -namespace alu { - -template -class VectorR { - static_assert(std::is_floating_point::value, "Must use floating-point types"); - alignas(16) std::array mVals; - -public: - constexpr VectorR() noexcept = default; - constexpr VectorR(const VectorR&) noexcept = default; - constexpr VectorR(T a, T b, T c, T d) noexcept : mVals{{a, b, c, d}} { } - - constexpr VectorR& operator=(const VectorR&) noexcept = default; - - T& operator[](size_t idx) noexcept { return mVals[idx]; } - constexpr const T& operator[](size_t idx) const noexcept { return mVals[idx]; } - - VectorR& operator+=(const VectorR &rhs) noexcept - { - mVals[0] += rhs.mVals[0]; - mVals[1] += rhs.mVals[1]; - mVals[2] += rhs.mVals[2]; - mVals[3] += rhs.mVals[3]; - return *this; - } - - T normalize() - { - const T length{std::sqrt(mVals[0]*mVals[0] + mVals[1]*mVals[1] + mVals[2]*mVals[2])}; - if(length > std::numeric_limits::epsilon()) - { - T inv_length{T{1}/length}; - mVals[0] *= inv_length; - mVals[1] *= inv_length; - mVals[2] *= inv_length; - return length; - } - mVals[0] = mVals[1] = mVals[2] = T{0}; - return T{0}; - } - - constexpr VectorR cross_product(const alu::VectorR &rhs) const - { - return VectorR{ - (*this)[1]*rhs[2] - (*this)[2]*rhs[1], - (*this)[2]*rhs[0] - (*this)[0]*rhs[2], - (*this)[0]*rhs[1] - (*this)[1]*rhs[0], - T{0}}; - } - - constexpr T dot_product(const alu::VectorR &rhs) const - { return (*this)[0]*rhs[0] + (*this)[1]*rhs[1] + (*this)[2]*rhs[2]; } -}; -using Vector = VectorR; - -template -class MatrixR { - static_assert(std::is_floating_point::value, "Must use floating-point types"); - alignas(16) std::array mVals; - -public: - constexpr MatrixR() noexcept = default; - constexpr MatrixR(const MatrixR&) noexcept = default; - constexpr MatrixR(T aa, T ab, T ac, T ad, - T ba, T bb, T bc, T bd, - T ca, T cb, T cc, T cd, - T da, T db, T dc, T dd) noexcept - : mVals{{aa,ab,ac,ad, ba,bb,bc,bd, ca,cb,cc,cd, da,db,dc,dd}} - { } - - constexpr MatrixR& operator=(const MatrixR&) noexcept = default; - - auto operator[](size_t idx) noexcept { return al::span{&mVals[idx*4], 4}; } - constexpr auto operator[](size_t idx) const noexcept - { return al::span{&mVals[idx*4], 4}; } - - static constexpr MatrixR Identity() noexcept - { - return MatrixR{ - T{1}, T{0}, T{0}, T{0}, - T{0}, T{1}, T{0}, T{0}, - T{0}, T{0}, T{1}, T{0}, - T{0}, T{0}, T{0}, T{1}}; - } -}; -using Matrix = MatrixR; - -template -inline VectorR operator*(const MatrixR &mtx, const VectorR &vec) noexcept -{ - return VectorR{ - vec[0]*mtx[0][0] + vec[1]*mtx[1][0] + vec[2]*mtx[2][0] + vec[3]*mtx[3][0], - vec[0]*mtx[0][1] + vec[1]*mtx[1][1] + vec[2]*mtx[2][1] + vec[3]*mtx[3][1], - vec[0]*mtx[0][2] + vec[1]*mtx[1][2] + vec[2]*mtx[2][2] + vec[3]*mtx[3][2], - vec[0]*mtx[0][3] + vec[1]*mtx[1][3] + vec[2]*mtx[2][3] + vec[3]*mtx[3][3]}; -} - -template -inline VectorR cast_to(const VectorR &vec) noexcept -{ - return VectorR{static_cast(vec[0]), static_cast(vec[1]), - static_cast(vec[2]), static_cast(vec[3])}; -} - -} // namespace alu - -#endif /* COMMON_VECMAT_H */ diff --git a/common/vector.h b/common/vector.h deleted file mode 100644 index 1b69d6a7..00000000 --- a/common/vector.h +++ /dev/null @@ -1,15 +0,0 @@ -#ifndef AL_VECTOR_H -#define AL_VECTOR_H - -#include - -#include "almalloc.h" - -namespace al { - -template -using vector = std::vector>; - -} // namespace al - -#endif /* AL_VECTOR_H */ diff --git a/common/win_main_utf8.h b/common/win_main_utf8.h deleted file mode 100644 index e40c2158..00000000 --- a/common/win_main_utf8.h +++ /dev/null @@ -1,117 +0,0 @@ -#ifndef WIN_MAIN_UTF8_H -#define WIN_MAIN_UTF8_H - -/* For Windows systems this provides a way to get UTF-8 encoded argv strings, - * and also overrides fopen to accept UTF-8 filenames. Working with wmain - * directly complicates cross-platform compatibility, while normal main() in - * Windows uses the current codepage (which has limited availability of - * characters). - * - * For MinGW, you must link with -municode - */ -#ifdef _WIN32 -#define WIN32_LEAN_AND_MEAN -#include -#include -#include - -#ifdef __cplusplus -#include - -#define STATIC_CAST(...) static_cast<__VA_ARGS__> -#define REINTERPRET_CAST(...) reinterpret_cast<__VA_ARGS__> - -#else - -#define STATIC_CAST(...) (__VA_ARGS__) -#define REINTERPRET_CAST(...) (__VA_ARGS__) -#endif - -static FILE *my_fopen(const char *fname, const char *mode) -{ - wchar_t *wname=NULL, *wmode=NULL; - int namelen, modelen; - FILE *file = NULL; - errno_t err; - - namelen = MultiByteToWideChar(CP_UTF8, 0, fname, -1, NULL, 0); - modelen = MultiByteToWideChar(CP_UTF8, 0, mode, -1, NULL, 0); - - if(namelen <= 0 || modelen <= 0) - { - fprintf(stderr, "Failed to convert UTF-8 fname \"%s\", mode \"%s\"\n", fname, mode); - return NULL; - } - -#ifdef __cplusplus - auto strbuf = std::make_unique(static_cast(namelen+modelen)); - wname = strbuf.get(); -#else - wname = (wchar_t*)calloc(sizeof(wchar_t), (size_t)(namelen+modelen)); -#endif - wmode = wname + namelen; - MultiByteToWideChar(CP_UTF8, 0, fname, -1, wname, namelen); - MultiByteToWideChar(CP_UTF8, 0, mode, -1, wmode, modelen); - - err = _wfopen_s(&file, wname, wmode); - if(err) - { - errno = err; - file = NULL; - } - -#ifndef __cplusplus - free(wname); -#endif - return file; -} -#define fopen my_fopen - - -/* SDL overrides main and provides UTF-8 args for us. */ -#if !defined(SDL_MAIN_NEEDED) && !defined(SDL_MAIN_AVAILABLE) -int my_main(int, char**); -#define main my_main - -#ifdef __cplusplus -extern "C" -#endif -int wmain(int argc, wchar_t **wargv) -{ - char **argv; - size_t total; - int i; - - total = sizeof(*argv) * STATIC_CAST(size_t)(argc); - for(i = 0;i < argc;i++) - total += STATIC_CAST(size_t)(WideCharToMultiByte(CP_UTF8, 0, wargv[i], -1, NULL, 0, NULL, - NULL)); - -#ifdef __cplusplus - auto argbuf = std::make_unique(total); - argv = reinterpret_cast(argbuf.get()); -#else - argv = (char**)calloc(1, total); -#endif - argv[0] = REINTERPRET_CAST(char*)(argv + argc); - for(i = 0;i < argc-1;i++) - { - int len = WideCharToMultiByte(CP_UTF8, 0, wargv[i], -1, argv[i], 65535, NULL, NULL); - argv[i+1] = argv[i] + len; - } - WideCharToMultiByte(CP_UTF8, 0, wargv[i], -1, argv[i], 65535, NULL, NULL); - -#ifdef __cplusplus - return main(argc, argv); -#else - i = main(argc, argv); - - free(argv); - return i; -#endif -} -#endif /* !defined(SDL_MAIN_NEEDED) && !defined(SDL_MAIN_AVAILABLE) */ - -#endif /* _WIN32 */ - -#endif /* WIN_MAIN_UTF8_H */ diff --git a/config.h.in b/config.h.in deleted file mode 100644 index f7e1542e..00000000 --- a/config.h.in +++ /dev/null @@ -1,120 +0,0 @@ -/* API declaration export attribute */ -#define AL_API ${EXPORT_DECL} -#define ALC_API ${EXPORT_DECL} - -/* Define if HRTF data is embedded in the library */ -#cmakedefine ALSOFT_EMBED_HRTF_DATA - -/* Define if we have the std::aligned_alloc function */ -#cmakedefine HAVE_STD_ALIGNED_ALLOC - -/* Define if we have the posix_memalign function */ -#cmakedefine HAVE_POSIX_MEMALIGN - -/* Define if we have the _aligned_malloc function */ -#cmakedefine HAVE__ALIGNED_MALLOC - -/* Define if we have the proc_pidpath function */ -#cmakedefine HAVE_PROC_PIDPATH - -/* Define if we have the getopt function */ -#cmakedefine HAVE_GETOPT - -/* Define if we have SSE CPU extensions */ -#cmakedefine HAVE_SSE -#cmakedefine HAVE_SSE2 -#cmakedefine HAVE_SSE3 -#cmakedefine HAVE_SSE4_1 - -/* Define if we have ARM Neon CPU extensions */ -#cmakedefine HAVE_NEON - -/* Define if we have the ALSA backend */ -#cmakedefine HAVE_ALSA - -/* Define if we have the OSS backend */ -#cmakedefine HAVE_OSS - -/* Define if we have the Solaris backend */ -#cmakedefine HAVE_SOLARIS - -/* Define if we have the SndIO backend */ -#cmakedefine HAVE_SNDIO - -/* Define if we have the WASAPI backend */ -#cmakedefine HAVE_WASAPI - -/* Define if we have the DSound backend */ -#cmakedefine HAVE_DSOUND - -/* Define if we have the Windows Multimedia backend */ -#cmakedefine HAVE_WINMM - -/* Define if we have the PortAudio backend */ -#cmakedefine HAVE_PORTAUDIO - -/* Define if we have the PulseAudio backend */ -#cmakedefine HAVE_PULSEAUDIO - -/* Define if we have the JACK backend */ -#cmakedefine HAVE_JACK - -/* Define if we have the CoreAudio backend */ -#cmakedefine HAVE_COREAUDIO - -/* Define if we have the OpenSL backend */ -#cmakedefine HAVE_OPENSL - -/* Define if we have the Oboe backend */ -#cmakedefine HAVE_OBOE - -/* Define if we have the Wave Writer backend */ -#cmakedefine HAVE_WAVE - -/* Define if we have the SDL2 backend */ -#cmakedefine HAVE_SDL2 - -/* Define if we have dlfcn.h */ -#cmakedefine HAVE_DLFCN_H - -/* Define if we have pthread_np.h */ -#cmakedefine HAVE_PTHREAD_NP_H - -/* Define if we have malloc.h */ -#cmakedefine HAVE_MALLOC_H - -/* Define if we have cpuid.h */ -#cmakedefine HAVE_CPUID_H - -/* Define if we have intrin.h */ -#cmakedefine HAVE_INTRIN_H - -/* Define if we have guiddef.h */ -#cmakedefine HAVE_GUIDDEF_H - -/* Define if we have initguid.h */ -#cmakedefine HAVE_INITGUID_H - -/* Define if we have GCC's __get_cpuid() */ -#cmakedefine HAVE_GCC_GET_CPUID - -/* Define if we have the __cpuid() intrinsic */ -#cmakedefine HAVE_CPUID_INTRINSIC - -/* Define if we have SSE intrinsics */ -#cmakedefine HAVE_SSE_INTRINSICS - -/* Define if we have pthread_setschedparam() */ -#cmakedefine HAVE_PTHREAD_SETSCHEDPARAM - -/* Define if we have pthread_setname_np() */ -#cmakedefine HAVE_PTHREAD_SETNAME_NP - -/* Define if pthread_setname_np() only accepts one parameter */ -#cmakedefine PTHREAD_SETNAME_NP_ONE_PARAM - -/* Define if pthread_setname_np() accepts three parameters */ -#cmakedefine PTHREAD_SETNAME_NP_THREE_PARAMS - -/* Define if we have pthread_set_name_np() */ -#cmakedefine HAVE_PTHREAD_SET_NAME_NP diff --git a/core/ambdec.cpp b/core/ambdec.cpp deleted file mode 100644 index 8655f4e7..00000000 --- a/core/ambdec.cpp +++ /dev/null @@ -1,375 +0,0 @@ - -#include "config.h" - -#include "ambdec.h" - -#include -#include -#include -#include -#include -#include - -#include "alfstream.h" -#include "core/logging.h" - - -namespace { - -template -constexpr inline std::size_t size(const T(&)[N]) noexcept -{ return N; } - -int readline(std::istream &f, std::string &output) -{ - while(f.good() && f.peek() == '\n') - f.ignore(); - - return std::getline(f, output) && !output.empty(); -} - -bool read_clipped_line(std::istream &f, std::string &buffer) -{ - while(readline(f, buffer)) - { - std::size_t pos{0}; - while(pos < buffer.length() && std::isspace(buffer[pos])) - pos++; - buffer.erase(0, pos); - - std::size_t cmtpos{buffer.find_first_of('#')}; - if(cmtpos < buffer.length()) - buffer.resize(cmtpos); - while(!buffer.empty() && std::isspace(buffer.back())) - buffer.pop_back(); - - if(!buffer.empty()) - return true; - } - return false; -} - - -std::string read_word(std::istream &f) -{ - std::string ret; - f >> ret; - return ret; -} - -bool is_at_end(const std::string &buffer, std::size_t endpos) -{ - while(endpos < buffer.length() && std::isspace(buffer[endpos])) - ++endpos; - return !(endpos < buffer.length()); -} - - -al::optional load_ambdec_speakers(AmbDecConf::SpeakerConf *spkrs, - const std::size_t num_speakers, std::istream &f, std::string &buffer) -{ - size_t cur_speaker{0}; - while(cur_speaker < num_speakers) - { - std::istringstream istr{buffer}; - - std::string cmd{read_word(istr)}; - if(cmd.empty()) - { - if(!read_clipped_line(f, buffer)) - return al::make_optional("Unexpected end of file"); - continue; - } - - if(cmd == "add_spkr") - { - AmbDecConf::SpeakerConf &spkr = spkrs[cur_speaker++]; - const size_t spkr_num{cur_speaker}; - - istr >> spkr.Name; - if(istr.fail()) WARN("Name not specified for speaker %zu\n", spkr_num); - istr >> spkr.Distance; - if(istr.fail()) WARN("Distance not specified for speaker %zu\n", spkr_num); - istr >> spkr.Azimuth; - if(istr.fail()) WARN("Azimuth not specified for speaker %zu\n", spkr_num); - istr >> spkr.Elevation; - if(istr.fail()) WARN("Elevation not specified for speaker %zu\n", spkr_num); - istr >> spkr.Connection; - if(istr.fail()) TRACE("Connection not specified for speaker %zu\n", spkr_num); - } - else - return al::make_optional("Unexpected speakers command: "+cmd); - - istr.clear(); - const auto endpos = static_cast(istr.tellg()); - if(!is_at_end(buffer, endpos)) - return al::make_optional("Extra junk on line: " + buffer.substr(endpos)); - buffer.clear(); - } - - return al::nullopt; -} - -al::optional load_ambdec_matrix(float (&gains)[MaxAmbiOrder+1], - AmbDecConf::CoeffArray *matrix, const std::size_t maxrow, std::istream &f, std::string &buffer) -{ - bool gotgains{false}; - std::size_t cur{0u}; - while(cur < maxrow) - { - std::istringstream istr{buffer}; - - std::string cmd{read_word(istr)}; - if(cmd.empty()) - { - if(!read_clipped_line(f, buffer)) - return al::make_optional("Unexpected end of file"); - continue; - } - - if(cmd == "order_gain") - { - std::size_t curgain{0u}; - float value; - while(istr.good()) - { - istr >> value; - if(istr.fail()) break; - if(!istr.eof() && !std::isspace(istr.peek())) - return al::make_optional("Extra junk on gain "+std::to_string(curgain+1)+": "+ - buffer.substr(static_cast(istr.tellg()))); - if(curgain < size(gains)) - gains[curgain++] = value; - } - std::fill(std::begin(gains)+curgain, std::end(gains), 0.0f); - gotgains = true; - } - else if(cmd == "add_row") - { - AmbDecConf::CoeffArray &mtxrow = matrix[cur++]; - std::size_t curidx{0u}; - float value{}; - while(istr.good()) - { - istr >> value; - if(istr.fail()) break; - if(!istr.eof() && !std::isspace(istr.peek())) - return al::make_optional("Extra junk on matrix element "+ - std::to_string(curidx)+"x"+std::to_string(cur-1)+": "+ - buffer.substr(static_cast(istr.tellg()))); - if(curidx < mtxrow.size()) - mtxrow[curidx++] = value; - } - std::fill(mtxrow.begin()+curidx, mtxrow.end(), 0.0f); - } - else - return al::make_optional("Unexpected matrix command: "+cmd); - - istr.clear(); - const auto endpos = static_cast(istr.tellg()); - if(!is_at_end(buffer, endpos)) - return al::make_optional("Extra junk on line: " + buffer.substr(endpos)); - buffer.clear(); - } - - if(!gotgains) - return al::make_optional("Matrix order_gain not specified"); - return al::nullopt; -} - -} // namespace - -al::optional AmbDecConf::load(const char *fname) noexcept -{ - al::ifstream f{fname}; - if(!f.is_open()) - return al::make_optional("Failed to open file"); - - bool speakers_loaded{false}; - bool matrix_loaded{false}; - bool lfmatrix_loaded{false}; - std::string buffer; - while(read_clipped_line(f, buffer)) - { - std::istringstream istr{buffer}; - - std::string command{read_word(istr)}; - if(command.empty()) - return al::make_optional("Malformed line: "+buffer); - - if(command == "/description") - istr >> Description; - else if(command == "/version") - { - istr >> Version; - if(!istr.eof() && !std::isspace(istr.peek())) - return al::make_optional("Extra junk after version: " + - buffer.substr(static_cast(istr.tellg()))); - if(Version != 3) - return al::make_optional("Unsupported version: "+std::to_string(Version)); - } - else if(command == "/dec/chan_mask") - { - if(ChanMask) - return al::make_optional("Duplicate chan_mask definition"); - - istr >> std::hex >> ChanMask >> std::dec; - if(!istr.eof() && !std::isspace(istr.peek())) - return al::make_optional("Extra junk after mask: " + - buffer.substr(static_cast(istr.tellg()))); - - if(!ChanMask) - return al::make_optional("Invalid chan_mask: "+std::to_string(ChanMask)); - } - else if(command == "/dec/freq_bands") - { - if(FreqBands) - return al::make_optional("Duplicate freq_bands"); - - istr >> FreqBands; - if(!istr.eof() && !std::isspace(istr.peek())) - return al::make_optional("Extra junk after freq_bands: " + - buffer.substr(static_cast(istr.tellg()))); - - if(FreqBands != 1 && FreqBands != 2) - return al::make_optional("Invalid freq_bands: "+std::to_string(FreqBands)); - } - else if(command == "/dec/speakers") - { - if(NumSpeakers) - return al::make_optional("Duplicate speakers"); - - istr >> NumSpeakers; - if(!istr.eof() && !std::isspace(istr.peek())) - return al::make_optional("Extra junk after speakers: " + - buffer.substr(static_cast(istr.tellg()))); - - if(!NumSpeakers) - return al::make_optional("Invalid speakers: "+std::to_string(NumSpeakers)); - Speakers = std::make_unique(NumSpeakers); - } - else if(command == "/dec/coeff_scale") - { - std::string scale = read_word(istr); - if(scale == "n3d") CoeffScale = AmbDecScale::N3D; - else if(scale == "sn3d") CoeffScale = AmbDecScale::SN3D; - else if(scale == "fuma") CoeffScale = AmbDecScale::FuMa; - else - return al::make_optional("Unexpected coeff_scale: "+scale); - } - else if(command == "/opt/xover_freq") - { - istr >> XOverFreq; - if(!istr.eof() && !std::isspace(istr.peek())) - return al::make_optional("Extra junk after xover_freq: " + - buffer.substr(static_cast(istr.tellg()))); - } - else if(command == "/opt/xover_ratio") - { - istr >> XOverRatio; - if(!istr.eof() && !std::isspace(istr.peek())) - return al::make_optional("Extra junk after xover_ratio: " + - buffer.substr(static_cast(istr.tellg()))); - } - else if(command == "/opt/input_scale" || command == "/opt/nfeff_comp" || - command == "/opt/delay_comp" || command == "/opt/level_comp") - { - /* Unused */ - read_word(istr); - } - else if(command == "/speakers/{") - { - if(!NumSpeakers) - return al::make_optional("Speakers defined without a count"); - - const auto endpos = static_cast(istr.tellg()); - if(!is_at_end(buffer, endpos)) - return al::make_optional("Extra junk on line: " + buffer.substr(endpos)); - buffer.clear(); - - if(auto err = load_ambdec_speakers(Speakers.get(), NumSpeakers, f, buffer)) - return err; - speakers_loaded = true; - - if(!read_clipped_line(f, buffer)) - return al::make_optional("Unexpected end of file"); - std::istringstream istr2{buffer}; - std::string endmark{read_word(istr2)}; - if(endmark != "/}") - return al::make_optional("Expected /} after speaker definitions, got "+endmark); - istr.swap(istr2); - } - else if(command == "/lfmatrix/{" || command == "/hfmatrix/{" || command == "/matrix/{") - { - if(!NumSpeakers) - return al::make_optional("Matrix defined without a count"); - const auto endpos = static_cast(istr.tellg()); - if(!is_at_end(buffer, endpos)) - return al::make_optional("Extra junk on line: " + buffer.substr(endpos)); - buffer.clear(); - - if(!Matrix) - { - Matrix = std::make_unique(NumSpeakers * FreqBands); - LFMatrix = Matrix.get(); - HFMatrix = LFMatrix + NumSpeakers*(FreqBands-1); - } - - if(FreqBands == 1) - { - if(command != "/matrix/{") - return al::make_optional( - "Unexpected \""+command+"\" type for a single-band decoder"); - if(auto err = load_ambdec_matrix(HFOrderGain, HFMatrix, NumSpeakers, f, buffer)) - return err; - matrix_loaded = true; - } - else - { - if(command == "/lfmatrix/{") - { - if(auto err=load_ambdec_matrix(LFOrderGain, LFMatrix, NumSpeakers, f, buffer)) - return err; - lfmatrix_loaded = true; - } - else if(command == "/hfmatrix/{") - { - if(auto err=load_ambdec_matrix(HFOrderGain, HFMatrix, NumSpeakers, f, buffer)) - return err; - matrix_loaded = true; - } - else - return al::make_optional( - "Unexpected \""+command+"\" type for a dual-band decoder"); - } - - if(!read_clipped_line(f, buffer)) - return al::make_optional("Unexpected end of file"); - std::istringstream istr2{buffer}; - std::string endmark{read_word(istr2)}; - if(endmark != "/}") - return al::make_optional("Expected /} after matrix definitions, got "+endmark); - istr.swap(istr2); - } - else if(command == "/end") - { - const auto endpos = static_cast(istr.tellg()); - if(!is_at_end(buffer, endpos)) - return al::make_optional("Extra junk on end: " + buffer.substr(endpos)); - - if(!speakers_loaded || !matrix_loaded || (FreqBands == 2 && !lfmatrix_loaded)) - return al::make_optional("No decoder defined"); - - return al::nullopt; - } - else - return al::make_optional("Unexpected command: " + command); - - istr.clear(); - const auto endpos = static_cast(istr.tellg()); - if(!is_at_end(buffer, endpos)) - return al::make_optional("Extra junk on line: " + buffer.substr(endpos)); - buffer.clear(); - } - return al::make_optional("Unexpected end of file"); -} diff --git a/core/ambdec.h b/core/ambdec.h deleted file mode 100644 index b6aa1225..00000000 --- a/core/ambdec.h +++ /dev/null @@ -1,52 +0,0 @@ -#ifndef CORE_AMBDEC_H -#define CORE_AMBDEC_H - -#include -#include -#include - -#include "aloptional.h" -#include "core/ambidefs.h" - -/* Helpers to read .ambdec configuration files. */ - -enum class AmbDecScale { - N3D, - SN3D, - FuMa, -}; -struct AmbDecConf { - std::string Description; - int Version{0}; /* Must be 3 */ - - unsigned int ChanMask{0u}; - unsigned int FreqBands{0u}; /* Must be 1 or 2 */ - AmbDecScale CoeffScale{}; - - float XOverFreq{0.0f}; - float XOverRatio{0.0f}; - - struct SpeakerConf { - std::string Name; - float Distance{0.0f}; - float Azimuth{0.0f}; - float Elevation{0.0f}; - std::string Connection; - }; - size_t NumSpeakers{0}; - std::unique_ptr Speakers; - - using CoeffArray = std::array; - std::unique_ptr Matrix; - - /* Unused when FreqBands == 1 */ - float LFOrderGain[MaxAmbiOrder+1]{}; - CoeffArray *LFMatrix; - - float HFOrderGain[MaxAmbiOrder+1]{}; - CoeffArray *HFMatrix; - - al::optional load(const char *fname) noexcept; -}; - -#endif /* CORE_AMBDEC_H */ diff --git a/core/ambidefs.h b/core/ambidefs.h deleted file mode 100644 index a72f7b78..00000000 --- a/core/ambidefs.h +++ /dev/null @@ -1,171 +0,0 @@ -#ifndef CORE_AMBIDEFS_H -#define CORE_AMBIDEFS_H - -#include -#include -#include - -using uint = unsigned int; - -/* The maximum number of Ambisonics channels. For a given order (o), the size - * needed will be (o+1)**2, thus zero-order has 1, first-order has 4, second- - * order has 9, third-order has 16, and fourth-order has 25. - */ -constexpr uint8_t MaxAmbiOrder{3}; -constexpr inline size_t AmbiChannelsFromOrder(size_t order) noexcept -{ return (order+1) * (order+1); } -constexpr size_t MaxAmbiChannels{AmbiChannelsFromOrder(MaxAmbiOrder)}; - -/* A bitmask of ambisonic channels for 0 to 4th order. This only specifies up - * to 4th order, which is the highest order a 32-bit mask value can specify (a - * 64-bit mask could handle up to 7th order). - */ -constexpr uint Ambi0OrderMask{0x00000001}; -constexpr uint Ambi1OrderMask{0x0000000f}; -constexpr uint Ambi2OrderMask{0x000001ff}; -constexpr uint Ambi3OrderMask{0x0000ffff}; -constexpr uint Ambi4OrderMask{0x01ffffff}; - -/* A bitmask of ambisonic channels with height information. If none of these - * channels are used/needed, there's no height (e.g. with most surround sound - * speaker setups). This is ACN ordering, with bit 0 being ACN 0, etc. - */ -constexpr uint AmbiPeriphonicMask{0xfe7ce4}; - -/* The maximum number of ambisonic channels for 2D (non-periphonic) - * representation. This is 2 per each order above zero-order, plus 1 for zero- - * order. Or simply, o*2 + 1. - */ -constexpr inline size_t Ambi2DChannelsFromOrder(size_t order) noexcept -{ return order*2 + 1; } -constexpr size_t MaxAmbi2DChannels{Ambi2DChannelsFromOrder(MaxAmbiOrder)}; - - -/* NOTE: These are scale factors as applied to Ambisonics content. Decoder - * coefficients should be divided by these values to get proper scalings. - */ -struct AmbiScale { - static auto& FromN3D() noexcept - { - static constexpr const std::array ret{{ - 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, - 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f - }}; - return ret; - } - static auto& FromSN3D() noexcept - { - static constexpr const std::array ret{{ - 1.000000000f, /* ACN 0, sqrt(1) */ - 1.732050808f, /* ACN 1, sqrt(3) */ - 1.732050808f, /* ACN 2, sqrt(3) */ - 1.732050808f, /* ACN 3, sqrt(3) */ - 2.236067978f, /* ACN 4, sqrt(5) */ - 2.236067978f, /* ACN 5, sqrt(5) */ - 2.236067978f, /* ACN 6, sqrt(5) */ - 2.236067978f, /* ACN 7, sqrt(5) */ - 2.236067978f, /* ACN 8, sqrt(5) */ - 2.645751311f, /* ACN 9, sqrt(7) */ - 2.645751311f, /* ACN 10, sqrt(7) */ - 2.645751311f, /* ACN 11, sqrt(7) */ - 2.645751311f, /* ACN 12, sqrt(7) */ - 2.645751311f, /* ACN 13, sqrt(7) */ - 2.645751311f, /* ACN 14, sqrt(7) */ - 2.645751311f, /* ACN 15, sqrt(7) */ - }}; - return ret; - } - static auto& FromFuMa() noexcept - { - static constexpr const std::array ret{{ - 1.414213562f, /* ACN 0 (W), sqrt(2) */ - 1.732050808f, /* ACN 1 (Y), sqrt(3) */ - 1.732050808f, /* ACN 2 (Z), sqrt(3) */ - 1.732050808f, /* ACN 3 (X), sqrt(3) */ - 1.936491673f, /* ACN 4 (V), sqrt(15)/2 */ - 1.936491673f, /* ACN 5 (T), sqrt(15)/2 */ - 2.236067978f, /* ACN 6 (R), sqrt(5) */ - 1.936491673f, /* ACN 7 (S), sqrt(15)/2 */ - 1.936491673f, /* ACN 8 (U), sqrt(15)/2 */ - 2.091650066f, /* ACN 9 (Q), sqrt(35/8) */ - 1.972026594f, /* ACN 10 (O), sqrt(35)/3 */ - 2.231093404f, /* ACN 11 (M), sqrt(224/45) */ - 2.645751311f, /* ACN 12 (K), sqrt(7) */ - 2.231093404f, /* ACN 13 (L), sqrt(224/45) */ - 1.972026594f, /* ACN 14 (N), sqrt(35)/3 */ - 2.091650066f, /* ACN 15 (P), sqrt(35/8) */ - }}; - return ret; - } -}; - -struct AmbiIndex { - static auto& FromFuMa() noexcept - { - static constexpr const std::array ret{{ - 0, /* W */ - 3, /* X */ - 1, /* Y */ - 2, /* Z */ - 6, /* R */ - 7, /* S */ - 5, /* T */ - 8, /* U */ - 4, /* V */ - 12, /* K */ - 13, /* L */ - 11, /* M */ - 14, /* N */ - 10, /* O */ - 15, /* P */ - 9, /* Q */ - }}; - return ret; - } - static auto& FromFuMa2D() noexcept - { - static constexpr const std::array ret{{ - 0, /* W */ - 3, /* X */ - 1, /* Y */ - 8, /* U */ - 4, /* V */ - 15, /* P */ - 9, /* Q */ - }}; - return ret; - } - - static auto& FromACN() noexcept - { - static constexpr const std::array ret{{ - 0, 1, 2, 3, 4, 5, 6, 7, - 8, 9, 10, 11, 12, 13, 14, 15 - }}; - return ret; - } - static auto& FromACN2D() noexcept - { - static constexpr const std::array ret{{ - 0, 1,3, 4,8, 9,15 - }}; - return ret; - } - - static auto& OrderFromChannel() noexcept - { - static constexpr const std::array ret{{ - 0, 1,1,1, 2,2,2,2,2, 3,3,3,3,3,3,3, - }}; - return ret; - } - static auto& OrderFrom2DChannel() noexcept - { - static constexpr const std::array ret{{ - 0, 1,1, 2,2, 3,3, - }}; - return ret; - } -}; - -#endif /* CORE_AMBIDEFS_H */ diff --git a/core/bs2b.cpp b/core/bs2b.cpp deleted file mode 100644 index 00207bc0..00000000 --- a/core/bs2b.cpp +++ /dev/null @@ -1,183 +0,0 @@ -/*- - * Copyright (c) 2005 Boris Mikhaylov - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -#include "config.h" - -#include -#include -#include - -#include "bs2b.h" -#include "math_defs.h" - - -/* Set up all data. */ -static void init(struct bs2b *bs2b) -{ - float Fc_lo, Fc_hi; - float G_lo, G_hi; - float x, g; - - switch(bs2b->level) - { - case BS2B_LOW_CLEVEL: /* Low crossfeed level */ - Fc_lo = 360.0f; - Fc_hi = 501.0f; - G_lo = 0.398107170553497f; - G_hi = 0.205671765275719f; - break; - - case BS2B_MIDDLE_CLEVEL: /* Middle crossfeed level */ - Fc_lo = 500.0f; - Fc_hi = 711.0f; - G_lo = 0.459726988530872f; - G_hi = 0.228208484414988f; - break; - - case BS2B_HIGH_CLEVEL: /* High crossfeed level (virtual speakers are closer to itself) */ - Fc_lo = 700.0f; - Fc_hi = 1021.0f; - G_lo = 0.530884444230988f; - G_hi = 0.250105790667544f; - break; - - case BS2B_LOW_ECLEVEL: /* Low easy crossfeed level */ - Fc_lo = 360.0f; - Fc_hi = 494.0f; - G_lo = 0.316227766016838f; - G_hi = 0.168236228897329f; - break; - - case BS2B_MIDDLE_ECLEVEL: /* Middle easy crossfeed level */ - Fc_lo = 500.0f; - Fc_hi = 689.0f; - G_lo = 0.354813389233575f; - G_hi = 0.187169483835901f; - break; - - default: /* High easy crossfeed level */ - bs2b->level = BS2B_HIGH_ECLEVEL; - - Fc_lo = 700.0f; - Fc_hi = 975.0f; - G_lo = 0.398107170553497f; - G_hi = 0.205671765275719f; - break; - } /* switch */ - - g = 1.0f / (1.0f - G_hi + G_lo); - - /* $fc = $Fc / $s; - * $d = 1 / 2 / pi / $fc; - * $x = exp(-1 / $d); - */ - x = std::exp(-al::MathDefs::Tau() * Fc_lo / static_cast(bs2b->srate)); - bs2b->b1_lo = x; - bs2b->a0_lo = G_lo * (1.0f - x) * g; - - x = std::exp(-al::MathDefs::Tau() * Fc_hi / static_cast(bs2b->srate)); - bs2b->b1_hi = x; - bs2b->a0_hi = (1.0f - G_hi * (1.0f - x)) * g; - bs2b->a1_hi = -x * g; -} /* init */ - - -/* Exported functions. - * See descriptions in "bs2b.h" - */ - -void bs2b_set_params(struct bs2b *bs2b, int level, int srate) -{ - if(srate <= 0) srate = 1; - - bs2b->level = level; - bs2b->srate = srate; - init(bs2b); -} /* bs2b_set_params */ - -int bs2b_get_level(struct bs2b *bs2b) -{ - return bs2b->level; -} /* bs2b_get_level */ - -int bs2b_get_srate(struct bs2b *bs2b) -{ - return bs2b->srate; -} /* bs2b_get_srate */ - -void bs2b_clear(struct bs2b *bs2b) -{ - std::fill(std::begin(bs2b->history), std::end(bs2b->history), bs2b::t_last_sample{}); -} /* bs2b_clear */ - -void bs2b_cross_feed(struct bs2b *bs2b, float *Left, float *Right, size_t SamplesToDo) -{ - const float a0_lo{bs2b->a0_lo}; - const float b1_lo{bs2b->b1_lo}; - const float a0_hi{bs2b->a0_hi}; - const float a1_hi{bs2b->a1_hi}; - const float b1_hi{bs2b->b1_hi}; - float lsamples[128][2]; - float rsamples[128][2]; - - for(size_t base{0};base < SamplesToDo;) - { - const size_t todo{std::min(128, SamplesToDo-base)}; - - /* Process left input */ - float z_lo{bs2b->history[0].lo}; - float z_hi{bs2b->history[0].hi}; - for(size_t i{0};i < todo;i++) - { - lsamples[i][0] = a0_lo*Left[i] + z_lo; - z_lo = b1_lo*lsamples[i][0]; - - lsamples[i][1] = a0_hi*Left[i] + z_hi; - z_hi = a1_hi*Left[i] + b1_hi*lsamples[i][1]; - } - bs2b->history[0].lo = z_lo; - bs2b->history[0].hi = z_hi; - - /* Process right input */ - z_lo = bs2b->history[1].lo; - z_hi = bs2b->history[1].hi; - for(size_t i{0};i < todo;i++) - { - rsamples[i][0] = a0_lo*Right[i] + z_lo; - z_lo = b1_lo*rsamples[i][0]; - - rsamples[i][1] = a0_hi*Right[i] + z_hi; - z_hi = a1_hi*Right[i] + b1_hi*rsamples[i][1]; - } - bs2b->history[1].lo = z_lo; - bs2b->history[1].hi = z_hi; - - /* Crossfeed */ - for(size_t i{0};i < todo;i++) - *(Left++) = lsamples[i][1] + rsamples[i][0]; - for(size_t i{0};i < todo;i++) - *(Right++) = rsamples[i][1] + lsamples[i][0]; - - base += todo; - } -} /* bs2b_cross_feed */ diff --git a/core/bs2b.h b/core/bs2b.h deleted file mode 100644 index 4d0b9dd8..00000000 --- a/core/bs2b.h +++ /dev/null @@ -1,89 +0,0 @@ -/*- - * Copyright (c) 2005 Boris Mikhaylov - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to - * permit persons to whom the Software is furnished to do so, subject to - * the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, - * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE - * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -#ifndef CORE_BS2B_H -#define CORE_BS2B_H - -#include "almalloc.h" - -/* Number of crossfeed levels */ -#define BS2B_CLEVELS 3 - -/* Normal crossfeed levels */ -#define BS2B_HIGH_CLEVEL 3 -#define BS2B_MIDDLE_CLEVEL 2 -#define BS2B_LOW_CLEVEL 1 - -/* Easy crossfeed levels */ -#define BS2B_HIGH_ECLEVEL BS2B_HIGH_CLEVEL + BS2B_CLEVELS -#define BS2B_MIDDLE_ECLEVEL BS2B_MIDDLE_CLEVEL + BS2B_CLEVELS -#define BS2B_LOW_ECLEVEL BS2B_LOW_CLEVEL + BS2B_CLEVELS - -/* Default crossfeed levels */ -#define BS2B_DEFAULT_CLEVEL BS2B_HIGH_ECLEVEL -/* Default sample rate (Hz) */ -#define BS2B_DEFAULT_SRATE 44100 - -struct bs2b { - int level; /* Crossfeed level */ - int srate; /* Sample rate (Hz) */ - - /* Lowpass IIR filter coefficients */ - float a0_lo; - float b1_lo; - - /* Highboost IIR filter coefficients */ - float a0_hi; - float a1_hi; - float b1_hi; - - /* Buffer of filter history - * [0] - first channel, [1] - second channel - */ - struct t_last_sample { - float lo; - float hi; - } history[2]; - - DEF_NEWDEL(bs2b) -}; - -/* Clear buffers and set new coefficients with new crossfeed level and sample - * rate values. - * level - crossfeed level of *LEVEL values. - * srate - sample rate by Hz. - */ -void bs2b_set_params(bs2b *bs2b, int level, int srate); - -/* Return current crossfeed level value */ -int bs2b_get_level(bs2b *bs2b); - -/* Return current sample rate value */ -int bs2b_get_srate(bs2b *bs2b); - -/* Clear buffer */ -void bs2b_clear(bs2b *bs2b); - -void bs2b_cross_feed(bs2b *bs2b, float *Left, float *Right, size_t SamplesToDo); - -#endif /* CORE_BS2B_H */ diff --git a/core/bsinc_defs.h b/core/bsinc_defs.h deleted file mode 100644 index 43865289..00000000 --- a/core/bsinc_defs.h +++ /dev/null @@ -1,16 +0,0 @@ -#ifndef CORE_BSINC_DEFS_H -#define CORE_BSINC_DEFS_H - -/* The number of distinct scale and phase intervals within the filter table. */ -constexpr unsigned int BSincScaleBits{4}; -constexpr unsigned int BSincScaleCount{1 << BSincScaleBits}; -constexpr unsigned int BSincPhaseBits{5}; -constexpr unsigned int BSincPhaseCount{1 << BSincPhaseBits}; - -/* The maximum number of sample points for the bsinc filters. The max points - * includes the doubling for downsampling, so the maximum number of base sample - * points is 24, which is 23rd order. - */ -constexpr unsigned int BSincPointsMax{48}; - -#endif /* CORE_BSINC_DEFS_H */ diff --git a/core/bsinc_tables.cpp b/core/bsinc_tables.cpp deleted file mode 100644 index 315e1448..00000000 --- a/core/bsinc_tables.cpp +++ /dev/null @@ -1,288 +0,0 @@ - -#include "bsinc_tables.h" - -#include -#include -#include -#include -#include -#include -#include - -#include "math_defs.h" - - -namespace { - -using uint = unsigned int; - - -/* This is the normalized cardinal sine (sinc) function. - * - * sinc(x) = { 1, x = 0 - * { sin(pi x) / (pi x), otherwise. - */ -constexpr double Sinc(const double x) -{ - if(!(x > 1e-15 || x < -1e-15)) - return 1.0; - return std::sin(al::MathDefs::Pi()*x) / (al::MathDefs::Pi()*x); -} - -/* The zero-order modified Bessel function of the first kind, used for the - * Kaiser window. - * - * I_0(x) = sum_{k=0}^inf (1 / k!)^2 (x / 2)^(2 k) - * = sum_{k=0}^inf ((x / 2)^k / k!)^2 - */ -constexpr double BesselI_0(const double x) -{ - /* Start at k=1 since k=0 is trivial. */ - const double x2{x / 2.0}; - double term{1.0}; - double sum{1.0}; - double last_sum{}; - int k{1}; - - /* Let the integration converge until the term of the sum is no longer - * significant. - */ - do { - const double y{x2 / k}; - ++k; - last_sum = sum; - term *= y * y; - sum += term; - } while(sum != last_sum); - - return sum; -} - -/* Calculate a Kaiser window from the given beta value and a normalized k - * [-1, 1]. - * - * w(k) = { I_0(B sqrt(1 - k^2)) / I_0(B), -1 <= k <= 1 - * { 0, elsewhere. - * - * Where k can be calculated as: - * - * k = i / l, where -l <= i <= l. - * - * or: - * - * k = 2 i / M - 1, where 0 <= i <= M. - */ -constexpr double Kaiser(const double beta, const double k, const double besseli_0_beta) -{ - if(!(k >= -1.0 && k <= 1.0)) - return 0.0; - return BesselI_0(beta * std::sqrt(1.0 - k*k)) / besseli_0_beta; -} - -/* Calculates the (normalized frequency) transition width of the Kaiser window. - * Rejection is in dB. - */ -constexpr double CalcKaiserWidth(const double rejection, const uint order) -{ - if(rejection > 21.19) - return (rejection - 7.95) / (order * 2.285 * al::MathDefs::Tau()); - /* This enforces a minimum rejection of just above 21.18dB */ - return 5.79 / (order * al::MathDefs::Tau()); -} - -/* Calculates the beta value of the Kaiser window. Rejection is in dB. */ -constexpr double CalcKaiserBeta(const double rejection) -{ - if(rejection > 50.0) - return 0.1102 * (rejection-8.7); - else if(rejection >= 21.0) - return (0.5842 * std::pow(rejection-21.0, 0.4)) + (0.07886 * (rejection-21.0)); - return 0.0; -} - - -struct BSincHeader { - double width{}; - double beta{}; - double scaleBase{}; - double scaleRange{}; - double besseli_0_beta{}; - - uint a[BSincScaleCount]{}; - uint total_size{}; - - constexpr BSincHeader(uint Rejection, uint Order) noexcept - { - width = CalcKaiserWidth(Rejection, Order); - beta = CalcKaiserBeta(Rejection); - scaleBase = width / 2.0; - scaleRange = 1.0 - scaleBase; - besseli_0_beta = BesselI_0(beta); - - uint num_points{Order+1}; - for(uint si{0};si < BSincScaleCount;++si) - { - const double scale{scaleBase + (scaleRange * si / (BSincScaleCount-1))}; - const uint a_{std::min(static_cast(num_points / 2.0 / scale), num_points)}; - const uint m{2 * a_}; - - a[si] = a_; - total_size += 4 * BSincPhaseCount * ((m+3) & ~3u); - } - } -}; - -/* 11th and 23rd order filters (12 and 24-point respectively) with a 60dB drop - * at nyquist. Each filter will scale up the order when downsampling, to 23rd - * and 47th order respectively. - */ -constexpr BSincHeader bsinc12_hdr{60, 11}; -constexpr BSincHeader bsinc24_hdr{60, 23}; - - -/* NOTE: GCC 5 has an issue with BSincHeader objects being in an anonymous - * namespace while also being used as non-type template parameters. - */ -#if !defined(__clang__) && defined(__GNUC__) && __GNUC__ < 6 -template -struct BSincFilterArray { - alignas(16) std::array mTable; - - BSincFilterArray(const BSincHeader &hdr) -#else -template -struct BSincFilterArray { - alignas(16) std::array mTable; - - BSincFilterArray() -#endif - { - using filter_type = double[][BSincPhaseCount+1][BSincPointsMax]; - auto filter = std::make_unique(BSincScaleCount); - - /* Calculate the Kaiser-windowed Sinc filter coefficients for each - * scale and phase index. - */ - for(uint si{0};si < BSincScaleCount;++si) - { - const uint m{hdr.a[si] * 2}; - const size_t o{(BSincPointsMax-m) / 2}; - const double scale{hdr.scaleBase + (hdr.scaleRange * si / (BSincScaleCount-1))}; - const double cutoff{scale - (hdr.scaleBase * std::max(0.5, scale) * 2.0)}; - const auto a = static_cast(hdr.a[si]); - const double l{a - 1.0}; - - /* Do one extra phase index so that the phase delta has a proper - * target for its last index. - */ - for(uint pi{0};pi <= BSincPhaseCount;++pi) - { - const double phase{l + (pi/double{BSincPhaseCount})}; - - for(uint i{0};i < m;++i) - { - const double x{i - phase}; - filter[si][pi][o+i] = Kaiser(hdr.beta, x/a, hdr.besseli_0_beta) * cutoff * - Sinc(cutoff*x); - } - } - } - - size_t idx{0}; - for(size_t si{0};si < BSincScaleCount-1;++si) - { - const size_t m{((hdr.a[si]*2) + 3) & ~3u}; - const size_t o{(BSincPointsMax-m) / 2}; - - for(size_t pi{0};pi < BSincPhaseCount;++pi) - { - /* Write out the filter. Also calculate and write out the phase - * and scale deltas. - */ - for(size_t i{0};i < m;++i) - mTable[idx++] = static_cast(filter[si][pi][o+i]); - - /* Linear interpolation between phases is simplified by pre- - * calculating the delta (b - a) in: x = a + f (b - a) - */ - for(size_t i{0};i < m;++i) - { - const double phDelta{filter[si][pi+1][o+i] - filter[si][pi][o+i]}; - mTable[idx++] = static_cast(phDelta); - } - - /* Linear interpolation between scales is also simplified. - * - * Given a difference in points between scales, the destination - * points will be 0, thus: x = a + f (-a) - */ - for(size_t i{0};i < m;++i) - { - const double scDelta{filter[si+1][pi][o+i] - filter[si][pi][o+i]}; - mTable[idx++] = static_cast(scDelta); - } - - /* This last simplification is done to complete the bilinear - * equation for the combination of phase and scale. - */ - for(size_t i{0};i < m;++i) - { - const double spDelta{(filter[si+1][pi+1][o+i] - filter[si+1][pi][o+i]) - - (filter[si][pi+1][o+i] - filter[si][pi][o+i])}; - mTable[idx++] = static_cast(spDelta); - } - } - } - { - /* The last scale index doesn't have any scale or scale-phase - * deltas. - */ - constexpr size_t si{BSincScaleCount-1}; - const size_t m{((hdr.a[si]*2) + 3) & ~3u}; - const size_t o{(BSincPointsMax-m) / 2}; - - for(size_t pi{0};pi < BSincPhaseCount;++pi) - { - for(size_t i{0};i < m;++i) - mTable[idx++] = static_cast(filter[si][pi][o+i]); - for(size_t i{0};i < m;++i) - { - const double phDelta{filter[si][pi+1][o+i] - filter[si][pi][o+i]}; - mTable[idx++] = static_cast(phDelta); - } - for(size_t i{0};i < m;++i) - mTable[idx++] = 0.0f; - for(size_t i{0};i < m;++i) - mTable[idx++] = 0.0f; - } - } - assert(idx == hdr.total_size); - } -}; - -#if !defined(__clang__) && defined(__GNUC__) && __GNUC__ < 6 -const BSincFilterArray bsinc12_filter{bsinc12_hdr}; -const BSincFilterArray bsinc24_filter{bsinc24_hdr}; -#else -const BSincFilterArray bsinc12_filter{}; -const BSincFilterArray bsinc24_filter{}; -#endif - -constexpr BSincTable GenerateBSincTable(const BSincHeader &hdr, const float *tab) -{ - BSincTable ret{}; - ret.scaleBase = static_cast(hdr.scaleBase); - ret.scaleRange = static_cast(1.0 / hdr.scaleRange); - for(size_t i{0};i < BSincScaleCount;++i) - ret.m[i] = ((hdr.a[i]*2) + 3) & ~3u; - ret.filterOffset[0] = 0; - for(size_t i{1};i < BSincScaleCount;++i) - ret.filterOffset[i] = ret.filterOffset[i-1] + ret.m[i-1]*4*BSincPhaseCount; - ret.Tab = tab; - return ret; -} - -} // namespace - -const BSincTable bsinc12{GenerateBSincTable(bsinc12_hdr, &bsinc12_filter.mTable.front())}; -const BSincTable bsinc24{GenerateBSincTable(bsinc24_hdr, &bsinc24_filter.mTable.front())}; diff --git a/core/bsinc_tables.h b/core/bsinc_tables.h deleted file mode 100644 index f52cda66..00000000 --- a/core/bsinc_tables.h +++ /dev/null @@ -1,17 +0,0 @@ -#ifndef CORE_BSINC_TABLES_H -#define CORE_BSINC_TABLES_H - -#include "bsinc_defs.h" - - -struct BSincTable { - float scaleBase, scaleRange; - unsigned int m[BSincScaleCount]; - unsigned int filterOffset[BSincScaleCount]; - const float *Tab; -}; - -extern const BSincTable bsinc12; -extern const BSincTable bsinc24; - -#endif /* CORE_BSINC_TABLES_H */ diff --git a/core/bufferline.h b/core/bufferline.h deleted file mode 100644 index 503e208d..00000000 --- a/core/bufferline.h +++ /dev/null @@ -1,14 +0,0 @@ -#ifndef CORE_BUFFERLINE_H -#define CORE_BUFFERLINE_H - -#include - -/* Size for temporary storage of buffer data, in floats. Larger values need - * more memory and are harder on cache, while smaller values may need more - * iterations for mixing. - */ -constexpr int BufferLineSize{1024}; - -using FloatBufferLine = std::array; - -#endif /* CORE_BUFFERLINE_H */ diff --git a/core/cpu_caps.cpp b/core/cpu_caps.cpp deleted file mode 100644 index 8211b331..00000000 --- a/core/cpu_caps.cpp +++ /dev/null @@ -1,142 +0,0 @@ - -#include "config.h" - -#include "cpu_caps.h" - -#if defined(_WIN32) && (defined(_M_ARM) || defined(_M_ARM64)) -#define WIN32_LEAN_AND_MEAN -#include -#ifndef PF_ARM_NEON_INSTRUCTIONS_AVAILABLE -#define PF_ARM_NEON_INSTRUCTIONS_AVAILABLE 19 -#endif -#endif - -#ifdef HAVE_INTRIN_H -#include -#endif -#ifdef HAVE_CPUID_H -#include -#endif - -#include -#include -#include - - -int CPUCapFlags{0}; - -namespace { - -#if defined(HAVE_GCC_GET_CPUID) \ - && (defined(__i386__) || defined(__x86_64__) || defined(_M_IX86) || defined(_M_X64)) -using reg_type = unsigned int; -inline std::array get_cpuid(unsigned int f) -{ - std::array ret{}; - __get_cpuid(f, &ret[0], &ret[1], &ret[2], &ret[3]); - return ret; -} -#define CAN_GET_CPUID -#elif defined(HAVE_CPUID_INTRINSIC) \ - && (defined(__i386__) || defined(__x86_64__) || defined(_M_IX86) || defined(_M_X64)) -using reg_type = int; -inline std::array get_cpuid(unsigned int f) -{ - std::array ret{}; - (__cpuid)(ret.data(), f); - return ret; -} -#define CAN_GET_CPUID -#endif - -} // namespace - -al::optional GetCPUInfo() -{ - CPUInfo ret; - -#ifdef CAN_GET_CPUID - auto cpuregs = get_cpuid(0); - if(cpuregs[0] == 0) - return al::nullopt; - - const reg_type maxfunc{cpuregs[0]}; - - cpuregs = get_cpuid(0x80000000); - const reg_type maxextfunc{cpuregs[0]}; - - ret.mVendor.append(reinterpret_cast(&cpuregs[1]), 4); - ret.mVendor.append(reinterpret_cast(&cpuregs[3]), 4); - ret.mVendor.append(reinterpret_cast(&cpuregs[2]), 4); - auto iter_end = std::remove(ret.mVendor.begin(), ret.mVendor.end(), '\0'); - iter_end = std::unique(ret.mVendor.begin(), iter_end, - [](auto&& c0, auto&& c1) { return std::isspace(c0) && std::isspace(c1); }); - ret.mVendor.erase(iter_end, ret.mVendor.end()); - if(!ret.mVendor.empty() && std::isspace(ret.mVendor.back())) - ret.mVendor.pop_back(); - if(!ret.mVendor.empty() && std::isspace(ret.mVendor.front())) - ret.mVendor.erase(ret.mVendor.begin()); - - if(maxextfunc >= 0x80000004) - { - cpuregs = get_cpuid(0x80000002); - ret.mName.append(reinterpret_cast(cpuregs.data()), 16); - cpuregs = get_cpuid(0x80000003); - ret.mName.append(reinterpret_cast(cpuregs.data()), 16); - cpuregs = get_cpuid(0x80000004); - ret.mName.append(reinterpret_cast(cpuregs.data()), 16); - iter_end = std::remove(ret.mName.begin(), ret.mName.end(), '\0'); - iter_end = std::unique(ret.mName.begin(), iter_end, - [](auto&& c0, auto&& c1) { return std::isspace(c0) && std::isspace(c1); }); - ret.mName.erase(iter_end, ret.mName.end()); - if(!ret.mName.empty() && std::isspace(ret.mName.back())) - ret.mName.pop_back(); - if(!ret.mName.empty() && std::isspace(ret.mName.front())) - ret.mName.erase(ret.mName.begin()); - } - - if(maxfunc >= 1) - { - cpuregs = get_cpuid(1); - if((cpuregs[3]&(1<<25))) - ret.mCaps |= CPU_CAP_SSE; - if((ret.mCaps&CPU_CAP_SSE) && (cpuregs[3]&(1<<26))) - ret.mCaps |= CPU_CAP_SSE2; - if((ret.mCaps&CPU_CAP_SSE2) && (cpuregs[2]&(1<<0))) - ret.mCaps |= CPU_CAP_SSE3; - if((ret.mCaps&CPU_CAP_SSE3) && (cpuregs[2]&(1<<19))) - ret.mCaps |= CPU_CAP_SSE4_1; - } - -#else - - /* Assume support for whatever's supported if we can't check for it */ -#if defined(HAVE_SSE4_1) -#warning "Assuming SSE 4.1 run-time support!" - ret.mCaps |= CPU_CAP_SSE | CPU_CAP_SSE2 | CPU_CAP_SSE3 | CPU_CAP_SSE4_1; -#elif defined(HAVE_SSE3) -#warning "Assuming SSE 3 run-time support!" - ret.mCaps |= CPU_CAP_SSE | CPU_CAP_SSE2 | CPU_CAP_SSE3; -#elif defined(HAVE_SSE2) -#warning "Assuming SSE 2 run-time support!" - ret.mCaps |= CPU_CAP_SSE | CPU_CAP_SSE2; -#elif defined(HAVE_SSE) -#warning "Assuming SSE run-time support!" - ret.mCaps |= CPU_CAP_SSE; -#endif -#endif /* CAN_GET_CPUID */ - -#ifdef HAVE_NEON -#ifdef __ARM_NEON - ret.mCaps |= CPU_CAP_NEON; -#elif defined(_WIN32) && (defined(_M_ARM) || defined(_M_ARM64)) - if(IsProcessorFeaturePresent(PF_ARM_NEON_INSTRUCTIONS_AVAILABLE)) - ret.mCaps |= CPU_CAP_NEON; -#else -#warning "Assuming NEON run-time support!" - ret.mCaps |= CPU_CAP_NEON; -#endif -#endif - - return al::make_optional(ret); -} diff --git a/core/cpu_caps.h b/core/cpu_caps.h deleted file mode 100644 index ffd671d0..00000000 --- a/core/cpu_caps.h +++ /dev/null @@ -1,26 +0,0 @@ -#ifndef CORE_CPU_CAPS_H -#define CORE_CPU_CAPS_H - -#include - -#include "aloptional.h" - - -extern int CPUCapFlags; -enum { - CPU_CAP_SSE = 1<<0, - CPU_CAP_SSE2 = 1<<1, - CPU_CAP_SSE3 = 1<<2, - CPU_CAP_SSE4_1 = 1<<3, - CPU_CAP_NEON = 1<<4, -}; - -struct CPUInfo { - std::string mVendor; - std::string mName; - int mCaps{0}; -}; - -al::optional GetCPUInfo(); - -#endif /* CORE_CPU_CAPS_H */ diff --git a/core/devformat.cpp b/core/devformat.cpp deleted file mode 100644 index d13ef3c6..00000000 --- a/core/devformat.cpp +++ /dev/null @@ -1,65 +0,0 @@ - -#include "config.h" - -#include "devformat.h" - - -uint BytesFromDevFmt(DevFmtType type) noexcept -{ - switch(type) - { - case DevFmtByte: return sizeof(int8_t); - case DevFmtUByte: return sizeof(uint8_t); - case DevFmtShort: return sizeof(int16_t); - case DevFmtUShort: return sizeof(uint16_t); - case DevFmtInt: return sizeof(int32_t); - case DevFmtUInt: return sizeof(uint32_t); - case DevFmtFloat: return sizeof(float); - } - return 0; -} -uint ChannelsFromDevFmt(DevFmtChannels chans, uint ambiorder) noexcept -{ - switch(chans) - { - case DevFmtMono: return 1; - case DevFmtStereo: return 2; - case DevFmtQuad: return 4; - case DevFmtX51: return 6; - case DevFmtX51Rear: return 6; - case DevFmtX61: return 7; - case DevFmtX71: return 8; - case DevFmtAmbi3D: return (ambiorder+1) * (ambiorder+1); - } - return 0; -} - -const char *DevFmtTypeString(DevFmtType type) noexcept -{ - switch(type) - { - case DevFmtByte: return "Int8"; - case DevFmtUByte: return "UInt8"; - case DevFmtShort: return "Int16"; - case DevFmtUShort: return "UInt16"; - case DevFmtInt: return "Int32"; - case DevFmtUInt: return "UInt32"; - case DevFmtFloat: return "Float32"; - } - return "(unknown type)"; -} -const char *DevFmtChannelsString(DevFmtChannels chans) noexcept -{ - switch(chans) - { - case DevFmtMono: return "Mono"; - case DevFmtStereo: return "Stereo"; - case DevFmtQuad: return "Quadraphonic"; - case DevFmtX51: return "5.1 Surround"; - case DevFmtX51Rear: return "5.1 Surround (Rear)"; - case DevFmtX61: return "6.1 Surround"; - case DevFmtX71: return "7.1 Surround"; - case DevFmtAmbi3D: return "Ambisonic 3D"; - } - return "(unknown channels)"; -} diff --git a/core/devformat.h b/core/devformat.h deleted file mode 100644 index 6b6fee77..00000000 --- a/core/devformat.h +++ /dev/null @@ -1,106 +0,0 @@ -#ifndef CORE_DEVFORMAT_H -#define CORE_DEVFORMAT_H - -#include - - -using uint = unsigned int; - -enum Channel : unsigned char { - FrontLeft = 0, - FrontRight, - FrontCenter, - LFE, - BackLeft, - BackRight, - BackCenter, - SideLeft, - SideRight, - - TopFrontLeft, - TopFrontCenter, - TopFrontRight, - TopCenter, - TopBackLeft, - TopBackCenter, - TopBackRight, - - MaxChannels -}; - - -/* Device formats */ -enum DevFmtType : unsigned char { - DevFmtByte, - DevFmtUByte, - DevFmtShort, - DevFmtUShort, - DevFmtInt, - DevFmtUInt, - DevFmtFloat, - - DevFmtTypeDefault = DevFmtFloat -}; -enum DevFmtChannels : unsigned char { - DevFmtMono, - DevFmtStereo, - DevFmtQuad, - DevFmtX51, - DevFmtX61, - DevFmtX71, - DevFmtAmbi3D, - - /* Similar to 5.1, except using rear channels instead of sides */ - DevFmtX51Rear, - - DevFmtChannelsDefault = DevFmtStereo -}; -#define MAX_OUTPUT_CHANNELS 16 - -/* DevFmtType traits, providing the type, etc given a DevFmtType. */ -template -struct DevFmtTypeTraits { }; - -template<> -struct DevFmtTypeTraits { using Type = int8_t; }; -template<> -struct DevFmtTypeTraits { using Type = uint8_t; }; -template<> -struct DevFmtTypeTraits { using Type = int16_t; }; -template<> -struct DevFmtTypeTraits { using Type = uint16_t; }; -template<> -struct DevFmtTypeTraits { using Type = int32_t; }; -template<> -struct DevFmtTypeTraits { using Type = uint32_t; }; -template<> -struct DevFmtTypeTraits { using Type = float; }; - -template -using DevFmtType_t = typename DevFmtTypeTraits::Type; - - -uint BytesFromDevFmt(DevFmtType type) noexcept; -uint ChannelsFromDevFmt(DevFmtChannels chans, uint ambiorder) noexcept; -inline uint FrameSizeFromDevFmt(DevFmtChannels chans, DevFmtType type, uint ambiorder) noexcept -{ return ChannelsFromDevFmt(chans, ambiorder) * BytesFromDevFmt(type); } - -const char *DevFmtTypeString(DevFmtType type) noexcept; -const char *DevFmtChannelsString(DevFmtChannels chans) noexcept; - -enum class DevAmbiLayout : bool { - FuMa, - ACN, - - Default = ACN -}; - -enum class DevAmbiScaling : unsigned char { - FuMa, - SN3D, - N3D, - - Default = SN3D -}; - -#endif /* CORE_DEVFORMAT_H */ diff --git a/core/except.cpp b/core/except.cpp deleted file mode 100644 index 07bb410a..00000000 --- a/core/except.cpp +++ /dev/null @@ -1,31 +0,0 @@ - -#include "config.h" - -#include "except.h" - -#include -#include - -#include "opthelpers.h" - - -namespace al { - -/* Defined here to avoid inlining it. */ -base_exception::~base_exception() { } - -void base_exception::setMessage(const char* msg, std::va_list args) -{ - std::va_list args2; - va_copy(args2, args); - int msglen{std::vsnprintf(nullptr, 0, msg, args)}; - if LIKELY(msglen > 0) - { - mMessage.resize(static_cast(msglen)+1); - std::vsnprintf(&mMessage[0], mMessage.length(), msg, args2); - mMessage.pop_back(); - } - va_end(args2); -} - -} // namespace al diff --git a/core/except.h b/core/except.h deleted file mode 100644 index 0e28e9df..00000000 --- a/core/except.h +++ /dev/null @@ -1,31 +0,0 @@ -#ifndef CORE_EXCEPT_H -#define CORE_EXCEPT_H - -#include -#include -#include -#include - - -namespace al { - -class base_exception : public std::exception { - std::string mMessage; - -protected: - base_exception() = default; - virtual ~base_exception(); - - void setMessage(const char *msg, std::va_list args); - -public: - const char *what() const noexcept override { return mMessage.c_str(); } -}; - -} // namespace al - -#define START_API_FUNC try - -#define END_API_FUNC catch(...) { std::terminate(); } - -#endif /* CORE_EXCEPT_H */ diff --git a/core/filters/biquad.cpp b/core/filters/biquad.cpp deleted file mode 100644 index fefdc8e1..00000000 --- a/core/filters/biquad.cpp +++ /dev/null @@ -1,163 +0,0 @@ - -#include "config.h" - -#include "biquad.h" - -#include -#include -#include - -#include "opthelpers.h" - - -template -void BiquadFilterR::setParams(BiquadType type, Real f0norm, Real gain, Real rcpQ) -{ - // Limit gain to -100dB - assert(gain > 0.00001f); - - const Real w0{al::MathDefs::Tau() * f0norm}; - const Real sin_w0{std::sin(w0)}; - const Real cos_w0{std::cos(w0)}; - const Real alpha{sin_w0/2.0f * rcpQ}; - - Real sqrtgain_alpha_2; - Real a[3]{ 1.0f, 0.0f, 0.0f }; - Real b[3]{ 1.0f, 0.0f, 0.0f }; - - /* Calculate filter coefficients depending on filter type */ - switch(type) - { - case BiquadType::HighShelf: - sqrtgain_alpha_2 = 2.0f * std::sqrt(gain) * alpha; - b[0] = gain*((gain+1.0f) + (gain-1.0f)*cos_w0 + sqrtgain_alpha_2); - b[1] = -2.0f*gain*((gain-1.0f) + (gain+1.0f)*cos_w0 ); - b[2] = gain*((gain+1.0f) + (gain-1.0f)*cos_w0 - sqrtgain_alpha_2); - a[0] = (gain+1.0f) - (gain-1.0f)*cos_w0 + sqrtgain_alpha_2; - a[1] = 2.0f* ((gain-1.0f) - (gain+1.0f)*cos_w0 ); - a[2] = (gain+1.0f) - (gain-1.0f)*cos_w0 - sqrtgain_alpha_2; - break; - case BiquadType::LowShelf: - sqrtgain_alpha_2 = 2.0f * std::sqrt(gain) * alpha; - b[0] = gain*((gain+1.0f) - (gain-1.0f)*cos_w0 + sqrtgain_alpha_2); - b[1] = 2.0f*gain*((gain-1.0f) - (gain+1.0f)*cos_w0 ); - b[2] = gain*((gain+1.0f) - (gain-1.0f)*cos_w0 - sqrtgain_alpha_2); - a[0] = (gain+1.0f) + (gain-1.0f)*cos_w0 + sqrtgain_alpha_2; - a[1] = -2.0f* ((gain-1.0f) + (gain+1.0f)*cos_w0 ); - a[2] = (gain+1.0f) + (gain-1.0f)*cos_w0 - sqrtgain_alpha_2; - break; - case BiquadType::Peaking: - b[0] = 1.0f + alpha * gain; - b[1] = -2.0f * cos_w0; - b[2] = 1.0f - alpha * gain; - a[0] = 1.0f + alpha / gain; - a[1] = -2.0f * cos_w0; - a[2] = 1.0f - alpha / gain; - break; - - case BiquadType::LowPass: - b[0] = (1.0f - cos_w0) / 2.0f; - b[1] = 1.0f - cos_w0; - b[2] = (1.0f - cos_w0) / 2.0f; - a[0] = 1.0f + alpha; - a[1] = -2.0f * cos_w0; - a[2] = 1.0f - alpha; - break; - case BiquadType::HighPass: - b[0] = (1.0f + cos_w0) / 2.0f; - b[1] = -(1.0f + cos_w0); - b[2] = (1.0f + cos_w0) / 2.0f; - a[0] = 1.0f + alpha; - a[1] = -2.0f * cos_w0; - a[2] = 1.0f - alpha; - break; - case BiquadType::BandPass: - b[0] = alpha; - b[1] = 0.0f; - b[2] = -alpha; - a[0] = 1.0f + alpha; - a[1] = -2.0f * cos_w0; - a[2] = 1.0f - alpha; - break; - } - - mA1 = a[1] / a[0]; - mA2 = a[2] / a[0]; - mB0 = b[0] / a[0]; - mB1 = b[1] / a[0]; - mB2 = b[2] / a[0]; -} - -template -void BiquadFilterR::process(const al::span src, Real *dst) -{ - const Real b0{mB0}; - const Real b1{mB1}; - const Real b2{mB2}; - const Real a1{mA1}; - const Real a2{mA2}; - Real z1{mZ1}; - Real z2{mZ2}; - - /* Processing loop is Transposed Direct Form II. This requires less storage - * compared to Direct Form I (only two delay components, instead of a four- - * sample history; the last two inputs and outputs), and works better for - * floating-point which favors summing similarly-sized values while being - * less bothered by overflow. - * - * See: http://www.earlevel.com/main/2003/02/28/biquads/ - */ - auto proc_sample = [b0,b1,b2,a1,a2,&z1,&z2](Real input) noexcept -> Real - { - const Real output{input*b0 + z1}; - z1 = input*b1 - output*a1 + z2; - z2 = input*b2 - output*a2; - return output; - }; - std::transform(src.cbegin(), src.cend(), dst, proc_sample); - - mZ1 = z1; - mZ2 = z2; -} - -template -void BiquadFilterR::dualProcess(BiquadFilterR &other, const al::span src, - Real *dst) -{ - const Real b00{mB0}; - const Real b01{mB1}; - const Real b02{mB2}; - const Real a01{mA1}; - const Real a02{mA2}; - const Real b10{other.mB0}; - const Real b11{other.mB1}; - const Real b12{other.mB2}; - const Real a11{other.mA1}; - const Real a12{other.mA2}; - Real z01{mZ1}; - Real z02{mZ2}; - Real z11{other.mZ1}; - Real z12{other.mZ2}; - - auto proc_sample = [b00,b01,b02,a01,a02,b10,b11,b12,a11,a12,&z01,&z02,&z11,&z12](Real input) noexcept -> Real - { - const Real tmpout{input*b00 + z01}; - z01 = input*b01 - tmpout*a01 + z02; - z02 = input*b02 - tmpout*a02; - input = tmpout; - - const Real output{input*b10 + z11}; - z11 = input*b11 - output*a11 + z12; - z12 = input*b12 - output*a12; - return output; - }; - std::transform(src.cbegin(), src.cend(), dst, proc_sample); - - mZ1 = z01; - mZ2 = z02; - other.mZ1 = z11; - other.mZ2 = z12; -} - -template class BiquadFilterR; -template class BiquadFilterR; diff --git a/core/filters/biquad.h b/core/filters/biquad.h deleted file mode 100644 index b2e2cfdb..00000000 --- a/core/filters/biquad.h +++ /dev/null @@ -1,144 +0,0 @@ -#ifndef CORE_FILTERS_BIQUAD_H -#define CORE_FILTERS_BIQUAD_H - -#include -#include -#include -#include - -#include "alspan.h" -#include "math_defs.h" - - -/* Filters implementation is based on the "Cookbook formulae for audio - * EQ biquad filter coefficients" by Robert Bristow-Johnson - * http://www.musicdsp.org/files/Audio-EQ-Cookbook.txt - */ -/* Implementation note: For the shelf and peaking filters, the specified gain - * is for the centerpoint of the transition band. This better fits EFX filter - * behavior, which expects the shelf's reference frequency to reach the given - * gain. To set the gain for the shelf or peak itself, use the square root of - * the desired linear gain (or halve the dB gain). - */ - -enum class BiquadType { - /** EFX-style low-pass filter, specifying a gain and reference frequency. */ - HighShelf, - /** EFX-style high-pass filter, specifying a gain and reference frequency. */ - LowShelf, - /** Peaking filter, specifying a gain and reference frequency. */ - Peaking, - - /** Low-pass cut-off filter, specifying a cut-off frequency. */ - LowPass, - /** High-pass cut-off filter, specifying a cut-off frequency. */ - HighPass, - /** Band-pass filter, specifying a center frequency. */ - BandPass, -}; - -template -class BiquadFilterR { - /* Last two delayed components for direct form II. */ - Real mZ1{0.0f}, mZ2{0.0f}; - /* Transfer function coefficients "b" (numerator) */ - Real mB0{1.0f}, mB1{0.0f}, mB2{0.0f}; - /* Transfer function coefficients "a" (denominator; a0 is pre-applied). */ - Real mA1{0.0f}, mA2{0.0f}; - - void setParams(BiquadType type, Real f0norm, Real gain, Real rcpQ); - - /** - * Calculates the rcpQ (i.e. 1/Q) coefficient for shelving filters, using - * the reference gain and shelf slope parameter. - * \param gain 0 < gain - * \param slope 0 < slope <= 1 - */ - static Real rcpQFromSlope(Real gain, Real slope) - { return std::sqrt((gain + 1.0f/gain)*(1.0f/slope - 1.0f) + 2.0f); } - - /** - * Calculates the rcpQ (i.e. 1/Q) coefficient for filters, using the - * normalized reference frequency and bandwidth. - * \param f0norm 0 < f0norm < 0.5. - * \param bandwidth 0 < bandwidth - */ - static Real rcpQFromBandwidth(Real f0norm, Real bandwidth) - { - const Real w0{al::MathDefs::Tau() * f0norm}; - return 2.0f*std::sinh(std::log(Real{2.0f})/2.0f*bandwidth*w0/std::sin(w0)); - } - -public: - void clear() noexcept { mZ1 = mZ2 = 0.0f; } - - /** - * Sets the filter state for the specified filter type and its parameters. - * - * \param type The type of filter to apply. - * \param f0norm The normalized reference frequency (ref / sample_rate). - * This is the center point for the Shelf, Peaking, and BandPass filter - * types, or the cutoff frequency for the LowPass and HighPass filter - * types. - * \param gain The gain for the reference frequency response. Only used by - * the Shelf and Peaking filter types. - * \param slope Slope steepness of the transition band. - */ - void setParamsFromSlope(BiquadType type, Real f0norm, Real gain, Real slope) - { - gain = std::max(gain, 0.001f); /* Limit -60dB */ - setParams(type, f0norm, gain, rcpQFromSlope(gain, slope)); - } - - /** - * Sets the filter state for the specified filter type and its parameters. - * - * \param type The type of filter to apply. - * \param f0norm The normalized reference frequency (ref / sample_rate). - * This is the center point for the Shelf, Peaking, and BandPass filter - * types, or the cutoff frequency for the LowPass and HighPass filter - * types. - * \param gain The gain for the reference frequency response. Only used by - * the Shelf and Peaking filter types. - * \param bandwidth Normalized bandwidth of the transition band. - */ - void setParamsFromBandwidth(BiquadType type, Real f0norm, Real gain, Real bandwidth) - { setParams(type, f0norm, gain, rcpQFromBandwidth(f0norm, bandwidth)); } - - void copyParamsFrom(const BiquadFilterR &other) - { - mB0 = other.mB0; - mB1 = other.mB1; - mB2 = other.mB2; - mA1 = other.mA1; - mA2 = other.mA2; - } - - void process(const al::span src, Real *dst); - /** Processes this filter and the other at the same time. */ - void dualProcess(BiquadFilterR &other, const al::span src, Real *dst); - - /* Rather hacky. It's just here to support "manual" processing. */ - std::pair getComponents() const noexcept { return {mZ1, mZ2}; } - void setComponents(Real z1, Real z2) noexcept { mZ1 = z1; mZ2 = z2; } - Real processOne(const Real in, Real &z1, Real &z2) const noexcept - { - const Real out{in*mB0 + z1}; - z1 = in*mB1 - out*mA1 + z2; - z2 = in*mB2 - out*mA2; - return out; - } -}; - -template -struct DualBiquadR { - BiquadFilterR &f0, &f1; - - void process(const al::span src, Real *dst) - { f0.dualProcess(f1, src, dst); } -}; - -using BiquadFilter = BiquadFilterR; -using DualBiquad = DualBiquadR; - -#endif /* CORE_FILTERS_BIQUAD_H */ diff --git a/core/filters/nfc.cpp b/core/filters/nfc.cpp deleted file mode 100644 index 9a28517c..00000000 --- a/core/filters/nfc.cpp +++ /dev/null @@ -1,383 +0,0 @@ - -#include "config.h" - -#include "nfc.h" - -#include - -#include "opthelpers.h" - - -/* Near-field control filters are the basis for handling the near-field effect. - * The near-field effect is a bass-boost present in the directional components - * of a recorded signal, created as a result of the wavefront curvature (itself - * a function of sound distance). Proper reproduction dictates this be - * compensated for using a bass-cut given the playback speaker distance, to - * avoid excessive bass in the playback. - * - * For real-time rendered audio, emulating the near-field effect based on the - * sound source's distance, and subsequently compensating for it at output - * based on the speaker distances, can create a more realistic perception of - * sound distance beyond a simple 1/r attenuation. - * - * These filters do just that. Each one applies a low-shelf filter, created as - * the combination of a bass-boost for a given sound source distance (near- - * field emulation) along with a bass-cut for a given control/speaker distance - * (near-field compensation). - * - * Note that it is necessary to apply a cut along with the boost, since the - * boost alone is unstable in higher-order ambisonics as it causes an infinite - * DC gain (even first-order ambisonics requires there to be no DC offset for - * the boost to work). Consequently, ambisonics requires a control parameter to - * be used to avoid an unstable boost-only filter. NFC-HOA defines this control - * as a reference delay, calculated with: - * - * reference_delay = control_distance / speed_of_sound - * - * This means w0 (for input) or w1 (for output) should be set to: - * - * wN = 1 / (reference_delay * sample_rate) - * - * when dealing with NFC-HOA content. For FOA input content, which does not - * specify a reference_delay variable, w0 should be set to 0 to apply only - * near-field compensation for output. It's important that w1 be a finite, - * positive, non-0 value or else the bass-boost will become unstable again. - * Also, w0 should not be too large compared to w1, to avoid excessively loud - * low frequencies. - */ - -namespace { - -constexpr float B[5][4] = { - { 0.0f }, - { 1.0f }, - { 3.0f, 3.0f }, - { 3.6778f, 6.4595f, 2.3222f }, - { 4.2076f, 11.4877f, 5.7924f, 9.1401f } -}; - -NfcFilter1 NfcFilterCreate1(const float w0, const float w1) noexcept -{ - NfcFilter1 nfc{}; - float b_00, g_0; - float r; - - nfc.base_gain = 1.0f; - nfc.gain = 1.0f; - - /* Calculate bass-boost coefficients. */ - r = 0.5f * w0; - b_00 = B[1][0] * r; - g_0 = 1.0f + b_00; - - nfc.gain *= g_0; - nfc.b1 = 2.0f * b_00 / g_0; - - /* Calculate bass-cut coefficients. */ - r = 0.5f * w1; - b_00 = B[1][0] * r; - g_0 = 1.0f + b_00; - - nfc.base_gain /= g_0; - nfc.gain /= g_0; - nfc.a1 = 2.0f * b_00 / g_0; - - return nfc; -} - -void NfcFilterAdjust1(NfcFilter1 *nfc, const float w0) noexcept -{ - const float r{0.5f * w0}; - const float b_00{B[1][0] * r}; - const float g_0{1.0f + b_00}; - - nfc->gain = nfc->base_gain * g_0; - nfc->b1 = 2.0f * b_00 / g_0; -} - - -NfcFilter2 NfcFilterCreate2(const float w0, const float w1) noexcept -{ - NfcFilter2 nfc{}; - float b_10, b_11, g_1; - float r; - - nfc.base_gain = 1.0f; - nfc.gain = 1.0f; - - /* Calculate bass-boost coefficients. */ - r = 0.5f * w0; - b_10 = B[2][0] * r; - b_11 = B[2][1] * r * r; - g_1 = 1.0f + b_10 + b_11; - - nfc.gain *= g_1; - nfc.b1 = (2.0f*b_10 + 4.0f*b_11) / g_1; - nfc.b2 = 4.0f * b_11 / g_1; - - /* Calculate bass-cut coefficients. */ - r = 0.5f * w1; - b_10 = B[2][0] * r; - b_11 = B[2][1] * r * r; - g_1 = 1.0f + b_10 + b_11; - - nfc.base_gain /= g_1; - nfc.gain /= g_1; - nfc.a1 = (2.0f*b_10 + 4.0f*b_11) / g_1; - nfc.a2 = 4.0f * b_11 / g_1; - - return nfc; -} - -void NfcFilterAdjust2(NfcFilter2 *nfc, const float w0) noexcept -{ - const float r{0.5f * w0}; - const float b_10{B[2][0] * r}; - const float b_11{B[2][1] * r * r}; - const float g_1{1.0f + b_10 + b_11}; - - nfc->gain = nfc->base_gain * g_1; - nfc->b1 = (2.0f*b_10 + 4.0f*b_11) / g_1; - nfc->b2 = 4.0f * b_11 / g_1; -} - - -NfcFilter3 NfcFilterCreate3(const float w0, const float w1) noexcept -{ - NfcFilter3 nfc{}; - float b_10, b_11, g_1; - float b_00, g_0; - float r; - - nfc.base_gain = 1.0f; - nfc.gain = 1.0f; - - /* Calculate bass-boost coefficients. */ - r = 0.5f * w0; - b_10 = B[3][0] * r; - b_11 = B[3][1] * r * r; - b_00 = B[3][2] * r; - g_1 = 1.0f + b_10 + b_11; - g_0 = 1.0f + b_00; - - nfc.gain *= g_1 * g_0; - nfc.b1 = (2.0f*b_10 + 4.0f*b_11) / g_1; - nfc.b2 = 4.0f * b_11 / g_1; - nfc.b3 = 2.0f * b_00 / g_0; - - /* Calculate bass-cut coefficients. */ - r = 0.5f * w1; - b_10 = B[3][0] * r; - b_11 = B[3][1] * r * r; - b_00 = B[3][2] * r; - g_1 = 1.0f + b_10 + b_11; - g_0 = 1.0f + b_00; - - nfc.base_gain /= g_1 * g_0; - nfc.gain /= g_1 * g_0; - nfc.a1 = (2.0f*b_10 + 4.0f*b_11) / g_1; - nfc.a2 = 4.0f * b_11 / g_1; - nfc.a3 = 2.0f * b_00 / g_0; - - return nfc; -} - -void NfcFilterAdjust3(NfcFilter3 *nfc, const float w0) noexcept -{ - const float r{0.5f * w0}; - const float b_10{B[3][0] * r}; - const float b_11{B[3][1] * r * r}; - const float b_00{B[3][2] * r}; - const float g_1{1.0f + b_10 + b_11}; - const float g_0{1.0f + b_00}; - - nfc->gain = nfc->base_gain * g_1 * g_0; - nfc->b1 = (2.0f*b_10 + 4.0f*b_11) / g_1; - nfc->b2 = 4.0f * b_11 / g_1; - nfc->b3 = 2.0f * b_00 / g_0; -} - - -NfcFilter4 NfcFilterCreate4(const float w0, const float w1) noexcept -{ - NfcFilter4 nfc{}; - float b_10, b_11, g_1; - float b_00, b_01, g_0; - float r; - - nfc.base_gain = 1.0f; - nfc.gain = 1.0f; - - /* Calculate bass-boost coefficients. */ - r = 0.5f * w0; - b_10 = B[4][0] * r; - b_11 = B[4][1] * r * r; - b_00 = B[4][2] * r; - b_01 = B[4][3] * r * r; - g_1 = 1.0f + b_10 + b_11; - g_0 = 1.0f + b_00 + b_01; - - nfc.gain *= g_1 * g_0; - nfc.b1 = (2.0f*b_10 + 4.0f*b_11) / g_1; - nfc.b2 = 4.0f * b_11 / g_1; - nfc.b3 = (2.0f*b_00 + 4.0f*b_01) / g_0; - nfc.b4 = 4.0f * b_01 / g_0; - - /* Calculate bass-cut coefficients. */ - r = 0.5f * w1; - b_10 = B[4][0] * r; - b_11 = B[4][1] * r * r; - b_00 = B[4][2] * r; - b_01 = B[4][3] * r * r; - g_1 = 1.0f + b_10 + b_11; - g_0 = 1.0f + b_00 + b_01; - - nfc.base_gain /= g_1 * g_0; - nfc.gain /= g_1 * g_0; - nfc.a1 = (2.0f*b_10 + 4.0f*b_11) / g_1; - nfc.a2 = 4.0f * b_11 / g_1; - nfc.a3 = (2.0f*b_00 + 4.0f*b_01) / g_0; - nfc.a4 = 4.0f * b_01 / g_0; - - return nfc; -} - -void NfcFilterAdjust4(NfcFilter4 *nfc, const float w0) noexcept -{ - const float r{0.5f * w0}; - const float b_10{B[4][0] * r}; - const float b_11{B[4][1] * r * r}; - const float b_00{B[4][2] * r}; - const float b_01{B[4][3] * r * r}; - const float g_1{1.0f + b_10 + b_11}; - const float g_0{1.0f + b_00 + b_01}; - - nfc->gain = nfc->base_gain * g_1 * g_0; - nfc->b1 = (2.0f*b_10 + 4.0f*b_11) / g_1; - nfc->b2 = 4.0f * b_11 / g_1; - nfc->b3 = (2.0f*b_00 + 4.0f*b_01) / g_0; - nfc->b4 = 4.0f * b_01 / g_0; -} - -} // namespace - -void NfcFilter::init(const float w1) noexcept -{ - first = NfcFilterCreate1(0.0f, w1); - second = NfcFilterCreate2(0.0f, w1); - third = NfcFilterCreate3(0.0f, w1); - fourth = NfcFilterCreate4(0.0f, w1); -} - -void NfcFilter::adjust(const float w0) noexcept -{ - NfcFilterAdjust1(&first, w0); - NfcFilterAdjust2(&second, w0); - NfcFilterAdjust3(&third, w0); - NfcFilterAdjust4(&fourth, w0); -} - - -void NfcFilter::process1(const al::span src, float *RESTRICT dst) -{ - const float gain{first.gain}; - const float b1{first.b1}; - const float a1{first.a1}; - float z1{first.z[0]}; - auto proc_sample = [gain,b1,a1,&z1](const float in) noexcept -> float - { - const float y{in*gain - a1*z1}; - const float out{y + b1*z1}; - z1 += y; - return out; - }; - std::transform(src.cbegin(), src.cend(), dst, proc_sample); - first.z[0] = z1; -} - -void NfcFilter::process2(const al::span src, float *RESTRICT dst) -{ - const float gain{second.gain}; - const float b1{second.b1}; - const float b2{second.b2}; - const float a1{second.a1}; - const float a2{second.a2}; - float z1{second.z[0]}; - float z2{second.z[1]}; - auto proc_sample = [gain,b1,b2,a1,a2,&z1,&z2](const float in) noexcept -> float - { - const float y{in*gain - a1*z1 - a2*z2}; - const float out{y + b1*z1 + b2*z2}; - z2 += z1; - z1 += y; - return out; - }; - std::transform(src.cbegin(), src.cend(), dst, proc_sample); - second.z[0] = z1; - second.z[1] = z2; -} - -void NfcFilter::process3(const al::span src, float *RESTRICT dst) -{ - const float gain{third.gain}; - const float b1{third.b1}; - const float b2{third.b2}; - const float b3{third.b3}; - const float a1{third.a1}; - const float a2{third.a2}; - const float a3{third.a3}; - float z1{third.z[0]}; - float z2{third.z[1]}; - float z3{third.z[2]}; - auto proc_sample = [gain,b1,b2,b3,a1,a2,a3,&z1,&z2,&z3](const float in) noexcept -> float - { - float y{in*gain - a1*z1 - a2*z2}; - float out{y + b1*z1 + b2*z2}; - z2 += z1; - z1 += y; - - y = out - a3*z3; - out = y + b3*z3; - z3 += y; - return out; - }; - std::transform(src.cbegin(), src.cend(), dst, proc_sample); - third.z[0] = z1; - third.z[1] = z2; - third.z[2] = z3; -} - -void NfcFilter::process4(const al::span src, float *RESTRICT dst) -{ - const float gain{fourth.gain}; - const float b1{fourth.b1}; - const float b2{fourth.b2}; - const float b3{fourth.b3}; - const float b4{fourth.b4}; - const float a1{fourth.a1}; - const float a2{fourth.a2}; - const float a3{fourth.a3}; - const float a4{fourth.a4}; - float z1{fourth.z[0]}; - float z2{fourth.z[1]}; - float z3{fourth.z[2]}; - float z4{fourth.z[3]}; - auto proc_sample = [gain,b1,b2,b3,b4,a1,a2,a3,a4,&z1,&z2,&z3,&z4](const float in) noexcept -> float - { - float y{in*gain - a1*z1 - a2*z2}; - float out{y + b1*z1 + b2*z2}; - z2 += z1; - z1 += y; - - y = out - a3*z3 - a4*z4; - out = y + b3*z3 + b4*z4; - z4 += z3; - z3 += y; - return out; - }; - std::transform(src.cbegin(), src.cend(), dst, proc_sample); - fourth.z[0] = z1; - fourth.z[1] = z2; - fourth.z[2] = z3; - fourth.z[3] = z4; -} diff --git a/core/filters/nfc.h b/core/filters/nfc.h deleted file mode 100644 index 33f67a5f..00000000 --- a/core/filters/nfc.h +++ /dev/null @@ -1,63 +0,0 @@ -#ifndef CORE_FILTERS_NFC_H -#define CORE_FILTERS_NFC_H - -#include - -#include "alspan.h" - - -struct NfcFilter1 { - float base_gain, gain; - float b1, a1; - float z[1]; -}; -struct NfcFilter2 { - float base_gain, gain; - float b1, b2, a1, a2; - float z[2]; -}; -struct NfcFilter3 { - float base_gain, gain; - float b1, b2, b3, a1, a2, a3; - float z[3]; -}; -struct NfcFilter4 { - float base_gain, gain; - float b1, b2, b3, b4, a1, a2, a3, a4; - float z[4]; -}; - -class NfcFilter { - NfcFilter1 first; - NfcFilter2 second; - NfcFilter3 third; - NfcFilter4 fourth; - -public: - /* NOTE: - * w0 = speed_of_sound / (source_distance * sample_rate); - * w1 = speed_of_sound / (control_distance * sample_rate); - * - * Generally speaking, the control distance should be approximately the - * average speaker distance, or based on the reference delay if outputing - * NFC-HOA. It must not be negative, 0, or infinite. The source distance - * should not be too small relative to the control distance. - */ - - void init(const float w1) noexcept; - void adjust(const float w0) noexcept; - - /* Near-field control filter for first-order ambisonic channels (1-3). */ - void process1(const al::span src, float *RESTRICT dst); - - /* Near-field control filter for second-order ambisonic channels (4-8). */ - void process2(const al::span src, float *RESTRICT dst); - - /* Near-field control filter for third-order ambisonic channels (9-15). */ - void process3(const al::span src, float *RESTRICT dst); - - /* Near-field control filter for fourth-order ambisonic channels (16-24). */ - void process4(const al::span src, float *RESTRICT dst); -}; - -#endif /* CORE_FILTERS_NFC_H */ diff --git a/core/filters/splitter.cpp b/core/filters/splitter.cpp deleted file mode 100644 index 5cc670b7..00000000 --- a/core/filters/splitter.cpp +++ /dev/null @@ -1,113 +0,0 @@ - -#include "config.h" - -#include "splitter.h" - -#include -#include -#include - -#include "math_defs.h" -#include "opthelpers.h" - - -template -void BandSplitterR::init(Real f0norm) -{ - const Real w{f0norm * al::MathDefs::Tau()}; - const Real cw{std::cos(w)}; - if(cw > std::numeric_limits::epsilon()) - mCoeff = (std::sin(w) - 1.0f) / cw; - else - mCoeff = cw * -0.5f; - - mLpZ1 = 0.0f; - mLpZ2 = 0.0f; - mApZ1 = 0.0f; -} - -template -void BandSplitterR::process(const al::span input, Real *hpout, Real *lpout) -{ - const Real ap_coeff{mCoeff}; - const Real lp_coeff{mCoeff*0.5f + 0.5f}; - Real lp_z1{mLpZ1}; - Real lp_z2{mLpZ2}; - Real ap_z1{mApZ1}; - auto proc_sample = [ap_coeff,lp_coeff,&lp_z1,&lp_z2,&ap_z1,&lpout](const Real in) noexcept -> Real - { - /* Low-pass sample processing. */ - Real d{(in - lp_z1) * lp_coeff}; - Real lp_y{lp_z1 + d}; - lp_z1 = lp_y + d; - - d = (lp_y - lp_z2) * lp_coeff; - lp_y = lp_z2 + d; - lp_z2 = lp_y + d; - - *(lpout++) = lp_y; - - /* All-pass sample processing. */ - Real ap_y{in*ap_coeff + ap_z1}; - ap_z1 = in - ap_y*ap_coeff; - - /* High-pass generated from removing low-passed output. */ - return ap_y - lp_y; - }; - std::transform(input.cbegin(), input.cend(), hpout, proc_sample); - mLpZ1 = lp_z1; - mLpZ2 = lp_z2; - mApZ1 = ap_z1; -} - -template -void BandSplitterR::processHfScale(const al::span samples, const Real hfscale) -{ - const Real ap_coeff{mCoeff}; - const Real lp_coeff{mCoeff*0.5f + 0.5f}; - Real lp_z1{mLpZ1}; - Real lp_z2{mLpZ2}; - Real ap_z1{mApZ1}; - auto proc_sample = [hfscale,ap_coeff,lp_coeff,&lp_z1,&lp_z2,&ap_z1](const Real in) noexcept -> Real - { - /* Low-pass sample processing. */ - Real d{(in - lp_z1) * lp_coeff}; - Real lp_y{lp_z1 + d}; - lp_z1 = lp_y + d; - - d = (lp_y - lp_z2) * lp_coeff; - lp_y = lp_z2 + d; - lp_z2 = lp_y + d; - - /* All-pass sample processing. */ - Real ap_y{in*ap_coeff + ap_z1}; - ap_z1 = in - ap_y*ap_coeff; - - /* High-pass generated by removing the low-passed signal, which is then - * scaled and added back to the low-passed signal. - */ - return (ap_y-lp_y)*hfscale + lp_y; - }; - std::transform(samples.begin(), samples.end(), samples.begin(), proc_sample); - mLpZ1 = lp_z1; - mLpZ2 = lp_z2; - mApZ1 = ap_z1; -} - -template -void BandSplitterR::applyAllpass(const al::span samples) const -{ - const Real coeff{mCoeff}; - Real z1{0.0f}; - auto proc_sample = [coeff,&z1](const Real in) noexcept -> Real - { - const Real out{in*coeff + z1}; - z1 = in - out*coeff; - return out; - }; - std::transform(samples.begin(), samples.end(), samples.begin(), proc_sample); -} - - -template class BandSplitterR; -template class BandSplitterR; diff --git a/core/filters/splitter.h b/core/filters/splitter.h deleted file mode 100644 index ba548c10..00000000 --- a/core/filters/splitter.h +++ /dev/null @@ -1,36 +0,0 @@ -#ifndef CORE_FILTERS_SPLITTER_H -#define CORE_FILTERS_SPLITTER_H - -#include - -#include "alspan.h" - - -/* Band splitter. Splits a signal into two phase-matching frequency bands. */ -template -class BandSplitterR { - Real mCoeff{0.0f}; - Real mLpZ1{0.0f}; - Real mLpZ2{0.0f}; - Real mApZ1{0.0f}; - -public: - BandSplitterR() = default; - BandSplitterR(const BandSplitterR&) = default; - BandSplitterR(Real f0norm) { init(f0norm); } - - void init(Real f0norm); - void clear() noexcept { mLpZ1 = mLpZ2 = mApZ1 = 0.0f; } - void process(const al::span input, Real *hpout, Real *lpout); - - void processHfScale(const al::span samples, const Real hfscale); - - /* The all-pass portion of the band splitter. Applies the same phase shift - * without splitting the signal. Note that each use of this method is - * indepedent, it does not track history between calls. - */ - void applyAllpass(const al::span samples) const; -}; -using BandSplitter = BandSplitterR; - -#endif /* CORE_FILTERS_SPLITTER_H */ diff --git a/core/fmt_traits.cpp b/core/fmt_traits.cpp deleted file mode 100644 index 054d8766..00000000 --- a/core/fmt_traits.cpp +++ /dev/null @@ -1,79 +0,0 @@ - -#include "config.h" - -#include "fmt_traits.h" - - -namespace al { - -const int16_t muLawDecompressionTable[256] = { - -32124,-31100,-30076,-29052,-28028,-27004,-25980,-24956, - -23932,-22908,-21884,-20860,-19836,-18812,-17788,-16764, - -15996,-15484,-14972,-14460,-13948,-13436,-12924,-12412, - -11900,-11388,-10876,-10364, -9852, -9340, -8828, -8316, - -7932, -7676, -7420, -7164, -6908, -6652, -6396, -6140, - -5884, -5628, -5372, -5116, -4860, -4604, -4348, -4092, - -3900, -3772, -3644, -3516, -3388, -3260, -3132, -3004, - -2876, -2748, -2620, -2492, -2364, -2236, -2108, -1980, - -1884, -1820, -1756, -1692, -1628, -1564, -1500, -1436, - -1372, -1308, -1244, -1180, -1116, -1052, -988, -924, - -876, -844, -812, -780, -748, -716, -684, -652, - -620, -588, -556, -524, -492, -460, -428, -396, - -372, -356, -340, -324, -308, -292, -276, -260, - -244, -228, -212, -196, -180, -164, -148, -132, - -120, -112, -104, -96, -88, -80, -72, -64, - -56, -48, -40, -32, -24, -16, -8, 0, - 32124, 31100, 30076, 29052, 28028, 27004, 25980, 24956, - 23932, 22908, 21884, 20860, 19836, 18812, 17788, 16764, - 15996, 15484, 14972, 14460, 13948, 13436, 12924, 12412, - 11900, 11388, 10876, 10364, 9852, 9340, 8828, 8316, - 7932, 7676, 7420, 7164, 6908, 6652, 6396, 6140, - 5884, 5628, 5372, 5116, 4860, 4604, 4348, 4092, - 3900, 3772, 3644, 3516, 3388, 3260, 3132, 3004, - 2876, 2748, 2620, 2492, 2364, 2236, 2108, 1980, - 1884, 1820, 1756, 1692, 1628, 1564, 1500, 1436, - 1372, 1308, 1244, 1180, 1116, 1052, 988, 924, - 876, 844, 812, 780, 748, 716, 684, 652, - 620, 588, 556, 524, 492, 460, 428, 396, - 372, 356, 340, 324, 308, 292, 276, 260, - 244, 228, 212, 196, 180, 164, 148, 132, - 120, 112, 104, 96, 88, 80, 72, 64, - 56, 48, 40, 32, 24, 16, 8, 0 -}; - -const int16_t aLawDecompressionTable[256] = { - -5504, -5248, -6016, -5760, -4480, -4224, -4992, -4736, - -7552, -7296, -8064, -7808, -6528, -6272, -7040, -6784, - -2752, -2624, -3008, -2880, -2240, -2112, -2496, -2368, - -3776, -3648, -4032, -3904, -3264, -3136, -3520, -3392, - -22016,-20992,-24064,-23040,-17920,-16896,-19968,-18944, - -30208,-29184,-32256,-31232,-26112,-25088,-28160,-27136, - -11008,-10496,-12032,-11520, -8960, -8448, -9984, -9472, - -15104,-14592,-16128,-15616,-13056,-12544,-14080,-13568, - -344, -328, -376, -360, -280, -264, -312, -296, - -472, -456, -504, -488, -408, -392, -440, -424, - -88, -72, -120, -104, -24, -8, -56, -40, - -216, -200, -248, -232, -152, -136, -184, -168, - -1376, -1312, -1504, -1440, -1120, -1056, -1248, -1184, - -1888, -1824, -2016, -1952, -1632, -1568, -1760, -1696, - -688, -656, -752, -720, -560, -528, -624, -592, - -944, -912, -1008, -976, -816, -784, -880, -848, - 5504, 5248, 6016, 5760, 4480, 4224, 4992, 4736, - 7552, 7296, 8064, 7808, 6528, 6272, 7040, 6784, - 2752, 2624, 3008, 2880, 2240, 2112, 2496, 2368, - 3776, 3648, 4032, 3904, 3264, 3136, 3520, 3392, - 22016, 20992, 24064, 23040, 17920, 16896, 19968, 18944, - 30208, 29184, 32256, 31232, 26112, 25088, 28160, 27136, - 11008, 10496, 12032, 11520, 8960, 8448, 9984, 9472, - 15104, 14592, 16128, 15616, 13056, 12544, 14080, 13568, - 344, 328, 376, 360, 280, 264, 312, 296, - 472, 456, 504, 488, 408, 392, 440, 424, - 88, 72, 120, 104, 24, 8, 56, 40, - 216, 200, 248, 232, 152, 136, 184, 168, - 1376, 1312, 1504, 1440, 1120, 1056, 1248, 1184, - 1888, 1824, 2016, 1952, 1632, 1568, 1760, 1696, - 688, 656, 752, 720, 560, 528, 624, 592, - 944, 912, 1008, 976, 816, 784, 880, 848 -}; - -} // namespace al diff --git a/core/fmt_traits.h b/core/fmt_traits.h deleted file mode 100644 index f797f836..00000000 --- a/core/fmt_traits.h +++ /dev/null @@ -1,81 +0,0 @@ -#ifndef CORE_FMT_TRAITS_H -#define CORE_FMT_TRAITS_H - -#include -#include - -#include "albyte.h" -#include "buffer_storage.h" - - -namespace al { - -extern const int16_t muLawDecompressionTable[256]; -extern const int16_t aLawDecompressionTable[256]; - - -template -struct FmtTypeTraits { }; - -template<> -struct FmtTypeTraits { - using Type = uint8_t; - - template - static constexpr inline OutT to(const Type val) noexcept - { return val*OutT{1.0/128.0} - OutT{1.0}; } -}; -template<> -struct FmtTypeTraits { - using Type = int16_t; - - template - static constexpr inline OutT to(const Type val) noexcept { return val*OutT{1.0/32768.0}; } -}; -template<> -struct FmtTypeTraits { - using Type = float; - - template - static constexpr inline OutT to(const Type val) noexcept { return val; } -}; -template<> -struct FmtTypeTraits { - using Type = double; - - template - static constexpr inline OutT to(const Type val) noexcept { return static_cast(val); } -}; -template<> -struct FmtTypeTraits { - using Type = uint8_t; - - template - static constexpr inline OutT to(const Type val) noexcept - { return muLawDecompressionTable[val] * OutT{1.0/32768.0}; } -}; -template<> -struct FmtTypeTraits { - using Type = uint8_t; - - template - static constexpr inline OutT to(const Type val) noexcept - { return aLawDecompressionTable[val] * OutT{1.0/32768.0}; } -}; - - -template -inline void LoadSampleArray(DstT *RESTRICT dst, const al::byte *src, const size_t srcstep, - const size_t samples) noexcept -{ - using TypeTraits = FmtTypeTraits; - using SampleType = typename TypeTraits::Type; - - const SampleType *RESTRICT ssrc{reinterpret_cast(src)}; - for(size_t i{0u};i < samples;i++) - dst[i] = TypeTraits::template to(ssrc[i*srcstep]); -} - -} // namespace al - -#endif /* CORE_FMT_TRAITS_H */ diff --git a/core/fpu_ctrl.cpp b/core/fpu_ctrl.cpp deleted file mode 100644 index b12f2c96..00000000 --- a/core/fpu_ctrl.cpp +++ /dev/null @@ -1,56 +0,0 @@ - -#include "config.h" - -#include "fpu_ctrl.h" - -#ifdef HAVE_INTRIN_H -#include -#endif -#ifdef HAVE_SSE_INTRINSICS -#include -#endif - -#include "cpu_caps.h" - - -void FPUCtl::enter() noexcept -{ - if(this->in_mode) return; - -#if defined(HAVE_SSE_INTRINSICS) - this->sse_state = _mm_getcsr(); - unsigned int sseState{this->sse_state}; - sseState |= 0x8000; /* set flush-to-zero */ - sseState |= 0x0040; /* set denormals-are-zero */ - _mm_setcsr(sseState); - -#elif defined(__GNUC__) && defined(HAVE_SSE) - - if((CPUCapFlags&CPU_CAP_SSE)) - { - __asm__ __volatile__("stmxcsr %0" : "=m" (*&this->sse_state)); - unsigned int sseState{this->sse_state}; - sseState |= 0x8000; /* set flush-to-zero */ - if((CPUCapFlags&CPU_CAP_SSE2)) - sseState |= 0x0040; /* set denormals-are-zero */ - __asm__ __volatile__("ldmxcsr %0" : : "m" (*&sseState)); - } -#endif - - this->in_mode = true; -} - -void FPUCtl::leave() noexcept -{ - if(!this->in_mode) return; - -#if defined(HAVE_SSE_INTRINSICS) - _mm_setcsr(this->sse_state); - -#elif defined(__GNUC__) && defined(HAVE_SSE) - - if((CPUCapFlags&CPU_CAP_SSE)) - __asm__ __volatile__("ldmxcsr %0" : : "m" (*&this->sse_state)); -#endif - this->in_mode = false; -} diff --git a/core/fpu_ctrl.h b/core/fpu_ctrl.h deleted file mode 100644 index e6dc1fb2..00000000 --- a/core/fpu_ctrl.h +++ /dev/null @@ -1,21 +0,0 @@ -#ifndef CORE_FPU_CTRL_H -#define CORE_FPU_CTRL_H - -class FPUCtl { -#if defined(HAVE_SSE_INTRINSICS) || (defined(__GNUC__) && defined(HAVE_SSE)) - unsigned int sse_state{}; -#endif - bool in_mode{}; - -public: - FPUCtl() noexcept { enter(); in_mode = true; }; - ~FPUCtl() { if(in_mode) leave(); } - - FPUCtl(const FPUCtl&) = delete; - FPUCtl& operator=(const FPUCtl&) = delete; - - void enter() noexcept; - void leave() noexcept; -}; - -#endif /* CORE_FPU_CTRL_H */ diff --git a/core/logging.cpp b/core/logging.cpp deleted file mode 100644 index dd7f53c7..00000000 --- a/core/logging.cpp +++ /dev/null @@ -1,95 +0,0 @@ - -#include "config.h" - -#include "logging.h" - -#include -#include -#include - -#include "strutils.h" -#include "vector.h" - - -#ifdef _WIN32 - -#define WIN32_LEAN_AND_MEAN -#include - -void al_print(LogLevel level, FILE *logfile, const char *fmt, ...) -{ - al::vector dynmsg; - char stcmsg[256]; - char *str{stcmsg}; - - std::va_list args, args2; - va_start(args, fmt); - va_copy(args2, args); - int msglen{std::vsnprintf(str, sizeof(stcmsg), fmt, args)}; - if UNLIKELY(msglen >= 0 && static_cast(msglen) >= sizeof(stcmsg)) - { - dynmsg.resize(static_cast(msglen) + 1u); - str = dynmsg.data(); - msglen = std::vsnprintf(str, dynmsg.size(), fmt, args2); - } - va_end(args2); - va_end(args); - - std::wstring wstr{utf8_to_wstr(str)}; - if(gLogLevel >= level) - { - fputws(wstr.c_str(), logfile); - fflush(logfile); - } - OutputDebugStringW(wstr.c_str()); -} - -#else - -#ifdef __ANDROID__ -#include -#endif - -void al_print(LogLevel level, FILE *logfile, const char *fmt, ...) -{ - al::vector dynmsg; - char stcmsg[256]; - char *str{stcmsg}; - - std::va_list args, args2; - va_start(args, fmt); - va_copy(args2, args); - int msglen{std::vsnprintf(str, sizeof(stcmsg), fmt, args)}; - if UNLIKELY(msglen >= 0 && static_cast(msglen) >= sizeof(stcmsg)) - { - dynmsg.resize(static_cast(msglen) + 1u); - str = dynmsg.data(); - msglen = std::vsnprintf(str, dynmsg.size(), fmt, args2); - } - va_end(args2); - va_end(args); - - if(gLogLevel >= level) - { - std::fputs(str, logfile); - std::fflush(logfile); - } -#ifdef __ANDROID__ - auto android_severity = [](LogLevel l) noexcept - { - switch(l) - { - case LogLevel::Trace: return ANDROID_LOG_DEBUG; - case LogLevel::Warning: return ANDROID_LOG_WARN; - case LogLevel::Error: return ANDROID_LOG_ERROR; - /* Should not happen. */ - case LogLevel::Disable: - break; - } - return ANDROID_LOG_ERROR; - }; - __android_log_print(android_severity(level), "openal", "%s", str); -#endif -} - -#endif diff --git a/core/logging.h b/core/logging.h deleted file mode 100644 index b931c27e..00000000 --- a/core/logging.h +++ /dev/null @@ -1,47 +0,0 @@ -#ifndef CORE_LOGGING_H -#define CORE_LOGGING_H - -#include - -#include "opthelpers.h" - - -enum class LogLevel { - Disable, - Error, - Warning, - Trace -}; -extern LogLevel gLogLevel; - -extern FILE *gLogFile; - - -#if !defined(_WIN32) && !defined(__ANDROID__) -#define TRACE(...) do { \ - if UNLIKELY(gLogLevel >= LogLevel::Trace) \ - fprintf(gLogFile, "[ALSOFT] (II) " __VA_ARGS__); \ -} while(0) - -#define WARN(...) do { \ - if UNLIKELY(gLogLevel >= LogLevel::Warning) \ - fprintf(gLogFile, "[ALSOFT] (WW) " __VA_ARGS__); \ -} while(0) - -#define ERR(...) do { \ - if UNLIKELY(gLogLevel >= LogLevel::Error) \ - fprintf(gLogFile, "[ALSOFT] (EE) " __VA_ARGS__); \ -} while(0) - -#else - -[[gnu::format(printf,3,4)]] void al_print(LogLevel level, FILE *logfile, const char *fmt, ...); - -#define TRACE(...) al_print(LogLevel::Trace, gLogFile, "[ALSOFT] (II) " __VA_ARGS__) - -#define WARN(...) al_print(LogLevel::Warning, gLogFile, "[ALSOFT] (WW) " __VA_ARGS__) - -#define ERR(...) al_print(LogLevel::Error, gLogFile, "[ALSOFT] (EE) " __VA_ARGS__) -#endif - -#endif /* CORE_LOGGING_H */ diff --git a/core/mastering.cpp b/core/mastering.cpp deleted file mode 100644 index e0cb2ca7..00000000 --- a/core/mastering.cpp +++ /dev/null @@ -1,441 +0,0 @@ - -#include "config.h" - -#include "mastering.h" - -#include -#include -#include -#include -#include -#include -#include - -#include "almalloc.h" -#include "alnumeric.h" -#include "alspan.h" -#include "opthelpers.h" - - -/* These structures assume BufferLineSize is a power of 2. */ -static_assert((BufferLineSize & (BufferLineSize-1)) == 0, "BufferLineSize is not a power of 2"); - -struct SlidingHold { - alignas(16) float mValues[BufferLineSize]; - uint mExpiries[BufferLineSize]; - uint mLowerIndex; - uint mUpperIndex; - uint mLength; -}; - - -namespace { - -using namespace std::placeholders; - -/* This sliding hold follows the input level with an instant attack and a - * fixed duration hold before an instant release to the next highest level. - * It is a sliding window maximum (descending maxima) implementation based on - * Richard Harter's ascending minima algorithm available at: - * - * http://www.richardhartersworld.com/cri/2001/slidingmin.html - */ -float UpdateSlidingHold(SlidingHold *Hold, const uint i, const float in) -{ - static constexpr uint mask{BufferLineSize - 1}; - const uint length{Hold->mLength}; - float (&values)[BufferLineSize] = Hold->mValues; - uint (&expiries)[BufferLineSize] = Hold->mExpiries; - uint lowerIndex{Hold->mLowerIndex}; - uint upperIndex{Hold->mUpperIndex}; - - if(i >= expiries[upperIndex]) - upperIndex = (upperIndex + 1) & mask; - - if(in >= values[upperIndex]) - { - values[upperIndex] = in; - expiries[upperIndex] = i + length; - lowerIndex = upperIndex; - } - else - { - do { - do { - if(!(in >= values[lowerIndex])) - goto found_place; - } while(lowerIndex--); - lowerIndex = mask; - } while(1); - found_place: - - lowerIndex = (lowerIndex + 1) & mask; - values[lowerIndex] = in; - expiries[lowerIndex] = i + length; - } - - Hold->mLowerIndex = lowerIndex; - Hold->mUpperIndex = upperIndex; - - return values[upperIndex]; -} - -void ShiftSlidingHold(SlidingHold *Hold, const uint n) -{ - auto exp_begin = std::begin(Hold->mExpiries) + Hold->mUpperIndex; - auto exp_last = std::begin(Hold->mExpiries) + Hold->mLowerIndex; - if(exp_last-exp_begin < 0) - { - std::transform(exp_begin, std::end(Hold->mExpiries), exp_begin, - std::bind(std::minus<>{}, _1, n)); - exp_begin = std::begin(Hold->mExpiries); - } - std::transform(exp_begin, exp_last+1, exp_begin, std::bind(std::minus<>{}, _1, n)); -} - - -/* Multichannel compression is linked via the absolute maximum of all - * channels. - */ -void LinkChannels(Compressor *Comp, const uint SamplesToDo, const FloatBufferLine *OutBuffer) -{ - const size_t numChans{Comp->mNumChans}; - - ASSUME(SamplesToDo > 0); - ASSUME(numChans > 0); - - auto side_begin = std::begin(Comp->mSideChain) + Comp->mLookAhead; - std::fill(side_begin, side_begin+SamplesToDo, 0.0f); - - auto fill_max = [SamplesToDo,side_begin](const FloatBufferLine &input) -> void - { - const float *RESTRICT buffer{al::assume_aligned<16>(input.data())}; - auto max_abs = std::bind(maxf, _1, std::bind(static_cast(std::fabs), _2)); - std::transform(side_begin, side_begin+SamplesToDo, buffer, side_begin, max_abs); - }; - std::for_each(OutBuffer, OutBuffer+numChans, fill_max); -} - -/* This calculates the squared crest factor of the control signal for the - * basic automation of the attack/release times. As suggested by the paper, - * it uses an instantaneous squared peak detector and a squared RMS detector - * both with 200ms release times. - */ -static void CrestDetector(Compressor *Comp, const uint SamplesToDo) -{ - const float a_crest{Comp->mCrestCoeff}; - float y2_peak{Comp->mLastPeakSq}; - float y2_rms{Comp->mLastRmsSq}; - - ASSUME(SamplesToDo > 0); - - auto calc_crest = [&y2_rms,&y2_peak,a_crest](const float x_abs) noexcept -> float - { - const float x2{clampf(x_abs * x_abs, 0.000001f, 1000000.0f)}; - - y2_peak = maxf(x2, lerp(x2, y2_peak, a_crest)); - y2_rms = lerp(x2, y2_rms, a_crest); - return y2_peak / y2_rms; - }; - auto side_begin = std::begin(Comp->mSideChain) + Comp->mLookAhead; - std::transform(side_begin, side_begin+SamplesToDo, std::begin(Comp->mCrestFactor), calc_crest); - - Comp->mLastPeakSq = y2_peak; - Comp->mLastRmsSq = y2_rms; -} - -/* The side-chain starts with a simple peak detector (based on the absolute - * value of the incoming signal) and performs most of its operations in the - * log domain. - */ -void PeakDetector(Compressor *Comp, const uint SamplesToDo) -{ - ASSUME(SamplesToDo > 0); - - /* Clamp the minimum amplitude to near-zero and convert to logarithm. */ - auto side_begin = std::begin(Comp->mSideChain) + Comp->mLookAhead; - std::transform(side_begin, side_begin+SamplesToDo, side_begin, - [](const float s) -> float { return std::log(maxf(0.000001f, s)); }); -} - -/* An optional hold can be used to extend the peak detector so it can more - * solidly detect fast transients. This is best used when operating as a - * limiter. - */ -void PeakHoldDetector(Compressor *Comp, const uint SamplesToDo) -{ - ASSUME(SamplesToDo > 0); - - SlidingHold *hold{Comp->mHold}; - uint i{0}; - auto detect_peak = [&i,hold](const float x_abs) -> float - { - const float x_G{std::log(maxf(0.000001f, x_abs))}; - return UpdateSlidingHold(hold, i++, x_G); - }; - auto side_begin = std::begin(Comp->mSideChain) + Comp->mLookAhead; - std::transform(side_begin, side_begin+SamplesToDo, side_begin, detect_peak); - - ShiftSlidingHold(hold, SamplesToDo); -} - -/* This is the heart of the feed-forward compressor. It operates in the log - * domain (to better match human hearing) and can apply some basic automation - * to knee width, attack/release times, make-up/post gain, and clipping - * reduction. - */ -void GainCompressor(Compressor *Comp, const uint SamplesToDo) -{ - const bool autoKnee{Comp->mAuto.Knee}; - const bool autoAttack{Comp->mAuto.Attack}; - const bool autoRelease{Comp->mAuto.Release}; - const bool autoPostGain{Comp->mAuto.PostGain}; - const bool autoDeclip{Comp->mAuto.Declip}; - const uint lookAhead{Comp->mLookAhead}; - const float threshold{Comp->mThreshold}; - const float slope{Comp->mSlope}; - const float attack{Comp->mAttack}; - const float release{Comp->mRelease}; - const float c_est{Comp->mGainEstimate}; - const float a_adp{Comp->mAdaptCoeff}; - const float *crestFactor{Comp->mCrestFactor}; - float postGain{Comp->mPostGain}; - float knee{Comp->mKnee}; - float t_att{attack}; - float t_rel{release - attack}; - float a_att{std::exp(-1.0f / t_att)}; - float a_rel{std::exp(-1.0f / t_rel)}; - float y_1{Comp->mLastRelease}; - float y_L{Comp->mLastAttack}; - float c_dev{Comp->mLastGainDev}; - - ASSUME(SamplesToDo > 0); - - for(float &sideChain : al::span{Comp->mSideChain, SamplesToDo}) - { - if(autoKnee) - knee = maxf(0.0f, 2.5f * (c_dev + c_est)); - const float knee_h{0.5f * knee}; - - /* This is the gain computer. It applies a static compression curve - * to the control signal. - */ - const float x_over{std::addressof(sideChain)[lookAhead] - threshold}; - const float y_G{ - (x_over <= -knee_h) ? 0.0f : - (std::fabs(x_over) < knee_h) ? (x_over + knee_h) * (x_over + knee_h) / (2.0f * knee) : - x_over}; - - const float y2_crest{*(crestFactor++)}; - if(autoAttack) - { - t_att = 2.0f*attack/y2_crest; - a_att = std::exp(-1.0f / t_att); - } - if(autoRelease) - { - t_rel = 2.0f*release/y2_crest - t_att; - a_rel = std::exp(-1.0f / t_rel); - } - - /* Gain smoothing (ballistics) is done via a smooth decoupled peak - * detector. The attack time is subtracted from the release time - * above to compensate for the chained operating mode. - */ - const float x_L{-slope * y_G}; - y_1 = maxf(x_L, lerp(x_L, y_1, a_rel)); - y_L = lerp(y_1, y_L, a_att); - - /* Knee width and make-up gain automation make use of a smoothed - * measurement of deviation between the control signal and estimate. - * The estimate is also used to bias the measurement to hot-start its - * average. - */ - c_dev = lerp(-(y_L+c_est), c_dev, a_adp); - - if(autoPostGain) - { - /* Clipping reduction is only viable when make-up gain is being - * automated. It modifies the deviation to further attenuate the - * control signal when clipping is detected. The adaptation time - * is sufficiently long enough to suppress further clipping at the - * same output level. - */ - if(autoDeclip) - c_dev = maxf(c_dev, sideChain - y_L - threshold - c_est); - - postGain = -(c_dev + c_est); - } - - sideChain = std::exp(postGain - y_L); - } - - Comp->mLastRelease = y_1; - Comp->mLastAttack = y_L; - Comp->mLastGainDev = c_dev; -} - -/* Combined with the hold time, a look-ahead delay can improve handling of - * fast transients by allowing the envelope time to converge prior to - * reaching the offending impulse. This is best used when operating as a - * limiter. - */ -void SignalDelay(Compressor *Comp, const uint SamplesToDo, FloatBufferLine *OutBuffer) -{ - const size_t numChans{Comp->mNumChans}; - const uint lookAhead{Comp->mLookAhead}; - - ASSUME(SamplesToDo > 0); - ASSUME(numChans > 0); - ASSUME(lookAhead > 0); - - for(size_t c{0};c < numChans;c++) - { - float *inout{al::assume_aligned<16>(OutBuffer[c].data())}; - float *delaybuf{al::assume_aligned<16>(Comp->mDelay[c].data())}; - - auto inout_end = inout + SamplesToDo; - if LIKELY(SamplesToDo >= lookAhead) - { - auto delay_end = std::rotate(inout, inout_end - lookAhead, inout_end); - std::swap_ranges(inout, delay_end, delaybuf); - } - else - { - auto delay_start = std::swap_ranges(inout, inout_end, delaybuf); - std::rotate(delaybuf, delay_start, delaybuf + lookAhead); - } - } -} - -} // namespace - - -std::unique_ptr Compressor::Create(const size_t NumChans, const float SampleRate, - const bool AutoKnee, const bool AutoAttack, const bool AutoRelease, const bool AutoPostGain, - const bool AutoDeclip, const float LookAheadTime, const float HoldTime, const float PreGainDb, - const float PostGainDb, const float ThresholdDb, const float Ratio, const float KneeDb, - const float AttackTime, const float ReleaseTime) -{ - const auto lookAhead = static_cast( - clampf(std::round(LookAheadTime*SampleRate), 0.0f, BufferLineSize-1)); - const auto hold = static_cast( - clampf(std::round(HoldTime*SampleRate), 0.0f, BufferLineSize-1)); - - size_t size{sizeof(Compressor)}; - if(lookAhead > 0) - { - size += sizeof(*Compressor::mDelay) * NumChans; - /* The sliding hold implementation doesn't handle a length of 1. A 1- - * sample hold is useless anyway, it would only ever give back what was - * just given to it. - */ - if(hold > 1) - size += sizeof(*Compressor::mHold); - } - - auto Comp = std::unique_ptr{new (al_calloc(16, size)) Compressor{}}; - Comp->mNumChans = NumChans; - Comp->mAuto.Knee = AutoKnee; - Comp->mAuto.Attack = AutoAttack; - Comp->mAuto.Release = AutoRelease; - Comp->mAuto.PostGain = AutoPostGain; - Comp->mAuto.Declip = AutoPostGain && AutoDeclip; - Comp->mLookAhead = lookAhead; - Comp->mPreGain = std::pow(10.0f, PreGainDb / 20.0f); - Comp->mPostGain = PostGainDb * std::log(10.0f) / 20.0f; - Comp->mThreshold = ThresholdDb * std::log(10.0f) / 20.0f; - Comp->mSlope = 1.0f / maxf(1.0f, Ratio) - 1.0f; - Comp->mKnee = maxf(0.0f, KneeDb * std::log(10.0f) / 20.0f); - Comp->mAttack = maxf(1.0f, AttackTime * SampleRate); - Comp->mRelease = maxf(1.0f, ReleaseTime * SampleRate); - - /* Knee width automation actually treats the compressor as a limiter. By - * varying the knee width, it can effectively be seen as applying - * compression over a wide range of ratios. - */ - if(AutoKnee) - Comp->mSlope = -1.0f; - - if(lookAhead > 0) - { - if(hold > 1) - { - Comp->mHold = ::new (static_cast(Comp.get() + 1)) SlidingHold{}; - Comp->mHold->mValues[0] = -std::numeric_limits::infinity(); - Comp->mHold->mExpiries[0] = hold; - Comp->mHold->mLength = hold; - Comp->mDelay = ::new(static_cast(Comp->mHold + 1)) FloatBufferLine[NumChans]; - } - else - { - Comp->mDelay = ::new(static_cast(Comp.get() + 1)) FloatBufferLine[NumChans]; - } - std::fill_n(Comp->mDelay, NumChans, FloatBufferLine{}); - } - - Comp->mCrestCoeff = std::exp(-1.0f / (0.200f * SampleRate)); // 200ms - Comp->mGainEstimate = Comp->mThreshold * -0.5f * Comp->mSlope; - Comp->mAdaptCoeff = std::exp(-1.0f / (2.0f * SampleRate)); // 2s - - return Comp; -} - -Compressor::~Compressor() -{ - if(mHold) - al::destroy_at(mHold); - mHold = nullptr; - if(mDelay) - al::destroy_n(mDelay, mNumChans); - mDelay = nullptr; -} - - -void Compressor::process(const uint SamplesToDo, FloatBufferLine *OutBuffer) -{ - const size_t numChans{mNumChans}; - - ASSUME(SamplesToDo > 0); - ASSUME(numChans > 0); - - const float preGain{mPreGain}; - if(preGain != 1.0f) - { - auto apply_gain = [SamplesToDo,preGain](FloatBufferLine &input) noexcept -> void - { - float *buffer{al::assume_aligned<16>(input.data())}; - std::transform(buffer, buffer+SamplesToDo, buffer, - std::bind(std::multiplies{}, _1, preGain)); - }; - std::for_each(OutBuffer, OutBuffer+numChans, apply_gain); - } - - LinkChannels(this, SamplesToDo, OutBuffer); - - if(mAuto.Attack || mAuto.Release) - CrestDetector(this, SamplesToDo); - - if(mHold) - PeakHoldDetector(this, SamplesToDo); - else - PeakDetector(this, SamplesToDo); - - GainCompressor(this, SamplesToDo); - - if(mDelay) - SignalDelay(this, SamplesToDo, OutBuffer); - - const float (&sideChain)[BufferLineSize*2] = mSideChain; - auto apply_comp = [SamplesToDo,&sideChain](FloatBufferLine &input) noexcept -> void - { - float *buffer{al::assume_aligned<16>(input.data())}; - const float *gains{al::assume_aligned<16>(&sideChain[0])}; - std::transform(gains, gains+SamplesToDo, buffer, buffer, - std::bind(std::multiplies{}, _1, _2)); - }; - std::for_each(OutBuffer, OutBuffer+numChans, apply_comp); - - auto side_begin = std::begin(mSideChain) + SamplesToDo; - std::copy(side_begin, side_begin+mLookAhead, std::begin(mSideChain)); -} diff --git a/core/mastering.h b/core/mastering.h deleted file mode 100644 index 322d3654..00000000 --- a/core/mastering.h +++ /dev/null @@ -1,104 +0,0 @@ -#ifndef CORE_MASTERING_H -#define CORE_MASTERING_H - -#include - -#include "almalloc.h" -#include "bufferline.h" - -struct SlidingHold; - -using uint = unsigned int; - - -/* General topology and basic automation was based on the following paper: - * - * D. Giannoulis, M. Massberg and J. D. Reiss, - * "Parameter Automation in a Dynamic Range Compressor," - * Journal of the Audio Engineering Society, v61 (10), Oct. 2013 - * - * Available (along with supplemental reading) at: - * - * http://c4dm.eecs.qmul.ac.uk/audioengineering/compressors/ - */ -struct Compressor { - size_t mNumChans{0u}; - - struct { - bool Knee : 1; - bool Attack : 1; - bool Release : 1; - bool PostGain : 1; - bool Declip : 1; - } mAuto{}; - - uint mLookAhead{0}; - - float mPreGain{0.0f}; - float mPostGain{0.0f}; - - float mThreshold{0.0f}; - float mSlope{0.0f}; - float mKnee{0.0f}; - - float mAttack{0.0f}; - float mRelease{0.0f}; - - alignas(16) float mSideChain[2*BufferLineSize]{}; - alignas(16) float mCrestFactor[BufferLineSize]{}; - - SlidingHold *mHold{nullptr}; - FloatBufferLine *mDelay{nullptr}; - - float mCrestCoeff{0.0f}; - float mGainEstimate{0.0f}; - float mAdaptCoeff{0.0f}; - - float mLastPeakSq{0.0f}; - float mLastRmsSq{0.0f}; - float mLastRelease{0.0f}; - float mLastAttack{0.0f}; - float mLastGainDev{0.0f}; - - - ~Compressor(); - void process(const uint SamplesToDo, FloatBufferLine *OutBuffer); - int getLookAhead() const noexcept { return static_cast(mLookAhead); } - - DEF_PLACE_NEWDEL() - - /** - * The compressor is initialized with the following settings: - * - * \param NumChans Number of channels to process. - * \param SampleRate Sample rate to process. - * \param AutoKnee Whether to automate the knee width parameter. - * \param AutoAttack Whether to automate the attack time parameter. - * \param AutoRelease Whether to automate the release time parameter. - * \param AutoPostGain Whether to automate the make-up (post) gain - * parameter. - * \param AutoDeclip Whether to automate clipping reduction. Ignored - * when not automating make-up gain. - * \param LookAheadTime Look-ahead time (in seconds). - * \param HoldTime Peak hold-time (in seconds). - * \param PreGainDb Gain applied before detection (in dB). - * \param PostGainDb Make-up gain applied after compression (in dB). - * \param ThresholdDb Triggering threshold (in dB). - * \param Ratio Compression ratio (x:1). Set to INFINIFTY for true - * limiting. Ignored when automating knee width. - * \param KneeDb Knee width (in dB). Ignored when automating knee - * width. - * \param AttackTime Attack time (in seconds). Acts as a maximum when - * automating attack time. - * \param ReleaseTime Release time (in seconds). Acts as a maximum when - * automating release time. - */ - static std::unique_ptr Create(const size_t NumChans, const float SampleRate, - const bool AutoKnee, const bool AutoAttack, const bool AutoRelease, - const bool AutoPostGain, const bool AutoDeclip, const float LookAheadTime, - const float HoldTime, const float PreGainDb, const float PostGainDb, - const float ThresholdDb, const float Ratio, const float KneeDb, const float AttackTime, - const float ReleaseTime); -}; - -#endif /* CORE_MASTERING_H */ diff --git a/core/mixer/defs.h b/core/mixer/defs.h deleted file mode 100644 index acf60350..00000000 --- a/core/mixer/defs.h +++ /dev/null @@ -1,101 +0,0 @@ -#ifndef CORE_MIXER_DEFS_H -#define CORE_MIXER_DEFS_H - -#include -#include - -#include "alspan.h" -#include "core/bufferline.h" - -struct HrtfChannelState; -struct HrtfFilter; -struct MixHrtfFilter; - -using uint = unsigned int; -using float2 = std::array; - - -constexpr int MixerFracBits{12}; -constexpr int MixerFracOne{1 << MixerFracBits}; -constexpr int MixerFracMask{MixerFracOne - 1}; - -/* Maximum number of samples to pad on the ends of a buffer for resampling. - * Note that the padding is symmetric (half at the beginning and half at the - * end)! - */ -constexpr int MaxResamplerPadding{48}; - -constexpr float GainSilenceThreshold{0.00001f}; /* -100dB */ - - -enum class Resampler { - Point, - Linear, - Cubic, - FastBSinc12, - BSinc12, - FastBSinc24, - BSinc24, - - Max = BSinc24 -}; - -/* Interpolator state. Kind of a misnomer since the interpolator itself is - * stateless. This just keeps it from having to recompute scale-related - * mappings for every sample. - */ -struct BsincState { - float sf; /* Scale interpolation factor. */ - uint m; /* Coefficient count. */ - uint l; /* Left coefficient offset. */ - /* Filter coefficients, followed by the phase, scale, and scale-phase - * delta coefficients. Starting at phase index 0, each subsequent phase - * index follows contiguously. - */ - const float *filter; -}; - -union InterpState { - BsincState bsinc; -}; - -using ResamplerFunc = float*(*)(const InterpState *state, float *RESTRICT src, uint frac, - uint increment, const al::span dst); - -ResamplerFunc PrepareResampler(Resampler resampler, uint increment, InterpState *state); - - -template -float *Resample_(const InterpState *state, float *RESTRICT src, uint frac, uint increment, - const al::span dst); - -template -void Mix_(const al::span InSamples, const al::span OutBuffer, - float *CurrentGains, const float *TargetGains, const size_t Counter, const size_t OutPos); - -template -void MixHrtf_(const float *InSamples, float2 *AccumSamples, const uint IrSize, - const MixHrtfFilter *hrtfparams, const size_t BufferSize); -template -void MixHrtfBlend_(const float *InSamples, float2 *AccumSamples, const uint IrSize, - const HrtfFilter *oldparams, const MixHrtfFilter *newparams, const size_t BufferSize); -template -void MixDirectHrtf_(FloatBufferLine &LeftOut, FloatBufferLine &RightOut, - const al::span InSamples, float2 *AccumSamples, - float *TempBuf, HrtfChannelState *ChanState, const size_t IrSize, const size_t BufferSize); - -/* Vectorized resampler helpers */ -template -inline void InitPosArrays(uint frac, uint increment, uint (&frac_arr)[N], uint (&pos_arr)[N]) -{ - pos_arr[0] = 0; - frac_arr[0] = frac; - for(size_t i{1};i < N;i++) - { - const uint frac_tmp{frac_arr[i-1] + increment}; - pos_arr[i] = pos_arr[i-1] + (frac_tmp>>MixerFracBits); - frac_arr[i] = frac_tmp&MixerFracMask; - } -} - -#endif /* CORE_MIXER_DEFS_H */ diff --git a/core/mixer/hrtfbase.h b/core/mixer/hrtfbase.h deleted file mode 100644 index 7419f960..00000000 --- a/core/mixer/hrtfbase.h +++ /dev/null @@ -1,159 +0,0 @@ -#ifndef CORE_MIXER_HRTFBASE_H -#define CORE_MIXER_HRTFBASE_H - -#include -#include - -#include "almalloc.h" -#include "hrtfdefs.h" -#include "opthelpers.h" - - -using uint = unsigned int; - -using ApplyCoeffsT = void(&)(float2 *RESTRICT Values, const size_t irSize, - const HrirArray &Coeffs, const float left, const float right); - -template -inline void MixHrtfBase(const float *InSamples, float2 *RESTRICT AccumSamples, const size_t IrSize, - const MixHrtfFilter *hrtfparams, const size_t BufferSize) -{ - ASSUME(BufferSize > 0); - - const HrirArray &Coeffs = *hrtfparams->Coeffs; - const float gainstep{hrtfparams->GainStep}; - const float gain{hrtfparams->Gain}; - - size_t ldelay{HrtfHistoryLength - hrtfparams->Delay[0]}; - size_t rdelay{HrtfHistoryLength - hrtfparams->Delay[1]}; - float stepcount{0.0f}; - for(size_t i{0u};i < BufferSize;++i) - { - const float g{gain + gainstep*stepcount}; - const float left{InSamples[ldelay++] * g}; - const float right{InSamples[rdelay++] * g}; - ApplyCoeffs(AccumSamples+i, IrSize, Coeffs, left, right); - - stepcount += 1.0f; - } -} - -template -inline void MixHrtfBlendBase(const float *InSamples, float2 *RESTRICT AccumSamples, - const size_t IrSize, const HrtfFilter *oldparams, const MixHrtfFilter *newparams, - const size_t BufferSize) -{ - ASSUME(BufferSize > 0); - - const auto &OldCoeffs = oldparams->Coeffs; - const float oldGainStep{oldparams->Gain / static_cast(BufferSize)}; - const auto &NewCoeffs = *newparams->Coeffs; - const float newGainStep{newparams->GainStep}; - - if LIKELY(oldparams->Gain > GainSilenceThreshold) - { - size_t ldelay{HrtfHistoryLength - oldparams->Delay[0]}; - size_t rdelay{HrtfHistoryLength - oldparams->Delay[1]}; - auto stepcount = static_cast(BufferSize); - for(size_t i{0u};i < BufferSize;++i) - { - const float g{oldGainStep*stepcount}; - const float left{InSamples[ldelay++] * g}; - const float right{InSamples[rdelay++] * g}; - ApplyCoeffs(AccumSamples+i, IrSize, OldCoeffs, left, right); - - stepcount -= 1.0f; - } - } - - if LIKELY(newGainStep*static_cast(BufferSize) > GainSilenceThreshold) - { - size_t ldelay{HrtfHistoryLength+1 - newparams->Delay[0]}; - size_t rdelay{HrtfHistoryLength+1 - newparams->Delay[1]}; - float stepcount{1.0f}; - for(size_t i{1u};i < BufferSize;++i) - { - const float g{newGainStep*stepcount}; - const float left{InSamples[ldelay++] * g}; - const float right{InSamples[rdelay++] * g}; - ApplyCoeffs(AccumSamples+i, IrSize, NewCoeffs, left, right); - - stepcount += 1.0f; - } - } -} - -template -inline void MixDirectHrtfBase(FloatBufferLine &LeftOut, FloatBufferLine &RightOut, - const al::span InSamples, float2 *RESTRICT AccumSamples, - float *TempBuf, HrtfChannelState *ChanState, const size_t IrSize, const size_t BufferSize) -{ - ASSUME(BufferSize > 0); - - /* Add the existing signal directly to the accumulation buffer, unfiltered, - * and with a delay to align with the input delay. - */ - for(size_t i{0};i < BufferSize;++i) - { - AccumSamples[HrtfDirectDelay+i][0] += LeftOut[i]; - AccumSamples[HrtfDirectDelay+i][1] += RightOut[i]; - } - - for(const FloatBufferLine &input : InSamples) - { - /* For dual-band processing, the signal needs extra scaling applied to - * the high frequency response. The band-splitter alone creates a - * frequency-dependent phase shift, which is not ideal. To counteract - * it, combine it with a backwards phase shift. - */ - - /* Load the input signal backwards, into a temp buffer with delay - * padding. The delay serves to reduce the error caused by the IIR - * filter's phase shift on a partial input. - */ - al::span tempbuf{al::assume_aligned<16>(TempBuf), HrtfDirectDelay+BufferSize}; - auto tmpiter = std::reverse_copy(input.begin(), input.begin()+BufferSize, tempbuf.begin()); - std::copy(ChanState->mDelay.cbegin(), ChanState->mDelay.cend(), tmpiter); - - /* Save the unfiltered newest input samples for next time. */ - std::copy_n(tempbuf.begin(), ChanState->mDelay.size(), ChanState->mDelay.begin()); - - /* Apply the all-pass on the reversed signal and reverse the resulting - * sample array. This produces the forward response with a backwards - * phase shift (+n degrees becomes -n degrees). - */ - ChanState->mSplitter.applyAllpass(tempbuf); - tempbuf = tempbuf.subspan(); - std::reverse(tempbuf.begin(), tempbuf.end()); - - /* Now apply the HF scale with the band-splitter. This applies the - * forward phase shift, which cancels out with the backwards phase - * shift to get the original phase on the scaled signal. - */ - ChanState->mSplitter.processHfScale(tempbuf, ChanState->mHfScale); - - /* Now apply the HRIR coefficients to this channel. */ - const auto &Coeffs = ChanState->mCoeffs; - for(size_t i{0u};i < BufferSize;++i) - { - const float insample{tempbuf[i]}; - ApplyCoeffs(AccumSamples+i, IrSize, Coeffs, insample, insample); - } - - ++ChanState; - } - - for(size_t i{0u};i < BufferSize;++i) - LeftOut[i] = AccumSamples[i][0]; - for(size_t i{0u};i < BufferSize;++i) - RightOut[i] = AccumSamples[i][1]; - - /* Copy the new in-progress accumulation values to the front and clear the - * following samples for the next mix. - */ - auto accum_iter = std::copy_n(AccumSamples+BufferSize, HrirLength+HrtfDirectDelay, - AccumSamples); - std::fill_n(accum_iter, BufferSize, float2{}); -} - -#endif /* CORE_MIXER_HRTFBASE_H */ diff --git a/core/mixer/hrtfdefs.h b/core/mixer/hrtfdefs.h deleted file mode 100644 index 89a9bb8d..00000000 --- a/core/mixer/hrtfdefs.h +++ /dev/null @@ -1,53 +0,0 @@ -#ifndef CORE_MIXER_HRTFDEFS_H -#define CORE_MIXER_HRTFDEFS_H - -#include - -#include "core/ambidefs.h" -#include "core/bufferline.h" -#include "core/filters/splitter.h" - - -using float2 = std::array; -using ubyte = unsigned char; -using ubyte2 = std::array; -using ushort = unsigned short; -using uint = unsigned int; -using uint2 = std::array; - -constexpr uint HrtfHistoryBits{6}; -constexpr uint HrtfHistoryLength{1 << HrtfHistoryBits}; -constexpr uint HrtfHistoryMask{HrtfHistoryLength - 1}; - -constexpr uint HrirBits{7}; -constexpr uint HrirLength{1 << HrirBits}; -constexpr uint HrirMask{HrirLength - 1}; - -constexpr uint MinIrLength{8}; - -constexpr uint HrtfDirectDelay{256}; - -using HrirArray = std::array; - -struct MixHrtfFilter { - const HrirArray *Coeffs; - uint2 Delay; - float Gain; - float GainStep; -}; - -struct HrtfFilter { - alignas(16) HrirArray Coeffs; - uint2 Delay; - float Gain; -}; - - -struct HrtfChannelState { - std::array mDelay{}; - BandSplitter mSplitter; - float mHfScale{}; - alignas(16) HrirArray mCoeffs{}; -}; - -#endif /* CORE_MIXER_HRTFDEFS_H */ diff --git a/core/mixer/mixer_c.cpp b/core/mixer/mixer_c.cpp deleted file mode 100644 index ff9538a4..00000000 --- a/core/mixer/mixer_c.cpp +++ /dev/null @@ -1,198 +0,0 @@ -#include "config.h" - -#include -#include -#include - -#include "alnumeric.h" -#include "core/bsinc_tables.h" -#include "defs.h" -#include "hrtfbase.h" - -struct CTag; -struct CopyTag; -struct PointTag; -struct LerpTag; -struct CubicTag; -struct BSincTag; -struct FastBSincTag; - - -namespace { - -constexpr uint FracPhaseBitDiff{MixerFracBits - BSincPhaseBits}; -constexpr uint FracPhaseDiffOne{1 << FracPhaseBitDiff}; - -inline float do_point(const InterpState&, const float *RESTRICT vals, const uint) -{ return vals[0]; } -inline float do_lerp(const InterpState&, const float *RESTRICT vals, const uint frac) -{ return lerp(vals[0], vals[1], static_cast(frac)*(1.0f/MixerFracOne)); } -inline float do_cubic(const InterpState&, const float *RESTRICT vals, const uint frac) -{ return cubic(vals[0], vals[1], vals[2], vals[3], static_cast(frac)*(1.0f/MixerFracOne)); } -inline float do_bsinc(const InterpState &istate, const float *RESTRICT vals, const uint frac) -{ - const size_t m{istate.bsinc.m}; - - // Calculate the phase index and factor. - const uint pi{frac >> FracPhaseBitDiff}; - const float pf{static_cast(frac & (FracPhaseDiffOne-1)) * (1.0f/FracPhaseDiffOne)}; - - const float *fil{istate.bsinc.filter + m*pi*4}; - const float *phd{fil + m}; - const float *scd{phd + m}; - const float *spd{scd + m}; - - // Apply the scale and phase interpolated filter. - float r{0.0f}; - for(size_t j_f{0};j_f < m;j_f++) - r += (fil[j_f] + istate.bsinc.sf*scd[j_f] + pf*(phd[j_f] + istate.bsinc.sf*spd[j_f])) * vals[j_f]; - return r; -} -inline float do_fastbsinc(const InterpState &istate, const float *RESTRICT vals, const uint frac) -{ - const size_t m{istate.bsinc.m}; - - // Calculate the phase index and factor. - const uint pi{frac >> FracPhaseBitDiff}; - const float pf{static_cast(frac & (FracPhaseDiffOne-1)) * (1.0f/FracPhaseDiffOne)}; - - const float *fil{istate.bsinc.filter + m*pi*4}; - const float *phd{fil + m}; - - // Apply the phase interpolated filter. - float r{0.0f}; - for(size_t j_f{0};j_f < m;j_f++) - r += (fil[j_f] + pf*phd[j_f]) * vals[j_f]; - return r; -} - -using SamplerT = float(&)(const InterpState&, const float*RESTRICT, const uint); -template -float *DoResample(const InterpState *state, float *RESTRICT src, uint frac, uint increment, - const al::span dst) -{ - const InterpState istate{*state}; - for(float &out : dst) - { - out = Sampler(istate, src, frac); - - frac += increment; - src += frac>>MixerFracBits; - frac &= MixerFracMask; - } - return dst.data(); -} - -inline void ApplyCoeffs(float2 *RESTRICT Values, const size_t IrSize, const HrirArray &Coeffs, - const float left, const float right) -{ - ASSUME(IrSize >= MinIrLength); - for(size_t c{0};c < IrSize;++c) - { - Values[c][0] += Coeffs[c][0] * left; - Values[c][1] += Coeffs[c][1] * right; - } -} - -} // namespace - -template<> -float *Resample_(const InterpState*, float *RESTRICT src, uint, uint, - const al::span dst) -{ -#if defined(HAVE_SSE) || defined(HAVE_NEON) - /* Avoid copying the source data if it's aligned like the destination. */ - if((reinterpret_cast(src)&15) == (reinterpret_cast(dst.data())&15)) - return src; -#endif - std::copy_n(src, dst.size(), dst.begin()); - return dst.data(); -} - -template<> -float *Resample_(const InterpState *state, float *RESTRICT src, uint frac, - uint increment, const al::span dst) -{ return DoResample(state, src, frac, increment, dst); } - -template<> -float *Resample_(const InterpState *state, float *RESTRICT src, uint frac, - uint increment, const al::span dst) -{ return DoResample(state, src, frac, increment, dst); } - -template<> -float *Resample_(const InterpState *state, float *RESTRICT src, uint frac, - uint increment, const al::span dst) -{ return DoResample(state, src-1, frac, increment, dst); } - -template<> -float *Resample_(const InterpState *state, float *RESTRICT src, uint frac, - uint increment, const al::span dst) -{ return DoResample(state, src-state->bsinc.l, frac, increment, dst); } - -template<> -float *Resample_(const InterpState *state, float *RESTRICT src, uint frac, - uint increment, const al::span dst) -{ return DoResample(state, src-state->bsinc.l, frac, increment, dst); } - - -template<> -void MixHrtf_(const float *InSamples, float2 *AccumSamples, const uint IrSize, - const MixHrtfFilter *hrtfparams, const size_t BufferSize) -{ MixHrtfBase(InSamples, AccumSamples, IrSize, hrtfparams, BufferSize); } - -template<> -void MixHrtfBlend_(const float *InSamples, float2 *AccumSamples, const uint IrSize, - const HrtfFilter *oldparams, const MixHrtfFilter *newparams, const size_t BufferSize) -{ - MixHrtfBlendBase(InSamples, AccumSamples, IrSize, oldparams, newparams, - BufferSize); -} - -template<> -void MixDirectHrtf_(FloatBufferLine &LeftOut, FloatBufferLine &RightOut, - const al::span InSamples, float2 *AccumSamples, - float *TempBuf, HrtfChannelState *ChanState, const size_t IrSize, const size_t BufferSize) -{ - MixDirectHrtfBase(LeftOut, RightOut, InSamples, AccumSamples, TempBuf, ChanState, - IrSize, BufferSize); -} - - -template<> -void Mix_(const al::span InSamples, const al::span OutBuffer, - float *CurrentGains, const float *TargetGains, const size_t Counter, const size_t OutPos) -{ - const float delta{(Counter > 0) ? 1.0f / static_cast(Counter) : 0.0f}; - const auto min_len = minz(Counter, InSamples.size()); - for(FloatBufferLine &output : OutBuffer) - { - float *RESTRICT dst{al::assume_aligned<16>(output.data()+OutPos)}; - float gain{*CurrentGains}; - const float step{(*TargetGains-gain) * delta}; - - size_t pos{0}; - if(!(std::abs(step) > std::numeric_limits::epsilon())) - gain = *TargetGains; - else - { - float step_count{0.0f}; - for(;pos != min_len;++pos) - { - dst[pos] += InSamples[pos] * (gain + step*step_count); - step_count += 1.0f; - } - if(pos == Counter) - gain = *TargetGains; - else - gain += step*step_count; - } - *CurrentGains = gain; - ++CurrentGains; - ++TargetGains; - - if(!(std::abs(gain) > GainSilenceThreshold)) - continue; - for(;pos != InSamples.size();++pos) - dst[pos] += InSamples[pos] * gain; - } -} diff --git a/core/mixer/mixer_neon.cpp b/core/mixer/mixer_neon.cpp deleted file mode 100644 index f3e5f130..00000000 --- a/core/mixer/mixer_neon.cpp +++ /dev/null @@ -1,305 +0,0 @@ -#include "config.h" - -#include - -#include -#include - -#include "alnumeric.h" -#include "core/bsinc_defs.h" -#include "defs.h" -#include "hrtfbase.h" - -struct NEONTag; -struct LerpTag; -struct BSincTag; -struct FastBSincTag; - - -#if defined(__GNUC__) && !defined(__clang__) && !defined(__ARM_NEON) -#pragma GCC target("fpu=neon") -#endif - -namespace { - -inline float32x4_t set_f4(float l0, float l1, float l2, float l3) -{ - float32x4_t ret{vmovq_n_f32(l0)}; - ret = vsetq_lane_f32(l1, ret, 1); - ret = vsetq_lane_f32(l2, ret, 2); - ret = vsetq_lane_f32(l3, ret, 3); - return ret; -} - -constexpr uint FracPhaseBitDiff{MixerFracBits - BSincPhaseBits}; -constexpr uint FracPhaseDiffOne{1 << FracPhaseBitDiff}; - -inline void ApplyCoeffs(float2 *RESTRICT Values, const size_t IrSize, const HrirArray &Coeffs, - const float left, const float right) -{ - float32x4_t leftright4; - { - float32x2_t leftright2{vmov_n_f32(left)}; - leftright2 = vset_lane_f32(right, leftright2, 1); - leftright4 = vcombine_f32(leftright2, leftright2); - } - - ASSUME(IrSize >= MinIrLength); - for(size_t c{0};c < IrSize;c += 2) - { - float32x4_t vals = vld1q_f32(&Values[c][0]); - float32x4_t coefs = vld1q_f32(&Coeffs[c][0]); - - vals = vmlaq_f32(vals, coefs, leftright4); - - vst1q_f32(&Values[c][0], vals); - } -} - -} // namespace - -template<> -float *Resample_(const InterpState*, float *RESTRICT src, uint frac, - uint increment, const al::span dst) -{ - const int32x4_t increment4 = vdupq_n_s32(static_cast(increment*4)); - const float32x4_t fracOne4 = vdupq_n_f32(1.0f/MixerFracOne); - const int32x4_t fracMask4 = vdupq_n_s32(MixerFracMask); - alignas(16) uint pos_[4], frac_[4]; - int32x4_t pos4, frac4; - - InitPosArrays(frac, increment, frac_, pos_); - frac4 = vld1q_s32(reinterpret_cast(frac_)); - pos4 = vld1q_s32(reinterpret_cast(pos_)); - - auto dst_iter = dst.begin(); - for(size_t todo{dst.size()>>2};todo;--todo) - { - const int pos0{vgetq_lane_s32(pos4, 0)}; - const int pos1{vgetq_lane_s32(pos4, 1)}; - const int pos2{vgetq_lane_s32(pos4, 2)}; - const int pos3{vgetq_lane_s32(pos4, 3)}; - const float32x4_t val1{set_f4(src[pos0], src[pos1], src[pos2], src[pos3])}; - const float32x4_t val2{set_f4(src[pos0+1], src[pos1+1], src[pos2+1], src[pos3+1])}; - - /* val1 + (val2-val1)*mu */ - const float32x4_t r0{vsubq_f32(val2, val1)}; - const float32x4_t mu{vmulq_f32(vcvtq_f32_s32(frac4), fracOne4)}; - const float32x4_t out{vmlaq_f32(val1, mu, r0)}; - - vst1q_f32(dst_iter, out); - dst_iter += 4; - - frac4 = vaddq_s32(frac4, increment4); - pos4 = vaddq_s32(pos4, vshrq_n_s32(frac4, MixerFracBits)); - frac4 = vandq_s32(frac4, fracMask4); - } - - if(size_t todo{dst.size()&3}) - { - src += static_cast(vgetq_lane_s32(pos4, 0)); - frac = static_cast(vgetq_lane_s32(frac4, 0)); - - do { - *(dst_iter++) = lerp(src[0], src[1], static_cast(frac) * (1.0f/MixerFracOne)); - - frac += increment; - src += frac>>MixerFracBits; - frac &= MixerFracMask; - } while(--todo); - } - return dst.data(); -} - -template<> -float *Resample_(const InterpState *state, float *RESTRICT src, uint frac, - uint increment, const al::span dst) -{ - const float *const filter{state->bsinc.filter}; - const float32x4_t sf4{vdupq_n_f32(state->bsinc.sf)}; - const size_t m{state->bsinc.m}; - - src -= state->bsinc.l; - for(float &out_sample : dst) - { - // Calculate the phase index and factor. - const uint pi{frac >> FracPhaseBitDiff}; - const float pf{static_cast(frac & (FracPhaseDiffOne-1)) * (1.0f/FracPhaseDiffOne)}; - - // Apply the scale and phase interpolated filter. - float32x4_t r4{vdupq_n_f32(0.0f)}; - { - const float32x4_t pf4{vdupq_n_f32(pf)}; - const float *fil{filter + m*pi*4}; - const float *phd{fil + m}; - const float *scd{phd + m}; - const float *spd{scd + m}; - size_t td{m >> 2}; - size_t j{0u}; - - do { - /* f = ((fil + sf*scd) + pf*(phd + sf*spd)) */ - const float32x4_t f4 = vmlaq_f32( - vmlaq_f32(vld1q_f32(&fil[j]), sf4, vld1q_f32(&scd[j])), - pf4, vmlaq_f32(vld1q_f32(&phd[j]), sf4, vld1q_f32(&spd[j]))); - /* r += f*src */ - r4 = vmlaq_f32(r4, f4, vld1q_f32(&src[j])); - j += 4; - } while(--td); - } - r4 = vaddq_f32(r4, vrev64q_f32(r4)); - out_sample = vget_lane_f32(vadd_f32(vget_low_f32(r4), vget_high_f32(r4)), 0); - - frac += increment; - src += frac>>MixerFracBits; - frac &= MixerFracMask; - } - return dst.data(); -} - -template<> -float *Resample_(const InterpState *state, float *RESTRICT src, uint frac, - uint increment, const al::span dst) -{ - const float *const filter{state->bsinc.filter}; - const size_t m{state->bsinc.m}; - - src -= state->bsinc.l; - for(float &out_sample : dst) - { - // Calculate the phase index and factor. - const uint pi{frac >> FracPhaseBitDiff}; - const float pf{static_cast(frac & (FracPhaseDiffOne-1)) * (1.0f/FracPhaseDiffOne)}; - - // Apply the phase interpolated filter. - float32x4_t r4{vdupq_n_f32(0.0f)}; - { - const float32x4_t pf4{vdupq_n_f32(pf)}; - const float *fil{filter + m*pi*4}; - const float *phd{fil + m}; - size_t td{m >> 2}; - size_t j{0u}; - - do { - /* f = fil + pf*phd */ - const float32x4_t f4 = vmlaq_f32(vld1q_f32(&fil[j]), pf4, vld1q_f32(&phd[j])); - /* r += f*src */ - r4 = vmlaq_f32(r4, f4, vld1q_f32(&src[j])); - j += 4; - } while(--td); - } - r4 = vaddq_f32(r4, vrev64q_f32(r4)); - out_sample = vget_lane_f32(vadd_f32(vget_low_f32(r4), vget_high_f32(r4)), 0); - - frac += increment; - src += frac>>MixerFracBits; - frac &= MixerFracMask; - } - return dst.data(); -} - - -template<> -void MixHrtf_(const float *InSamples, float2 *AccumSamples, const uint IrSize, - const MixHrtfFilter *hrtfparams, const size_t BufferSize) -{ MixHrtfBase(InSamples, AccumSamples, IrSize, hrtfparams, BufferSize); } - -template<> -void MixHrtfBlend_(const float *InSamples, float2 *AccumSamples, const uint IrSize, - const HrtfFilter *oldparams, const MixHrtfFilter *newparams, const size_t BufferSize) -{ - MixHrtfBlendBase(InSamples, AccumSamples, IrSize, oldparams, newparams, - BufferSize); -} - -template<> -void MixDirectHrtf_(FloatBufferLine &LeftOut, FloatBufferLine &RightOut, - const al::span InSamples, float2 *AccumSamples, - float *TempBuf, HrtfChannelState *ChanState, const size_t IrSize, const size_t BufferSize) -{ - MixDirectHrtfBase(LeftOut, RightOut, InSamples, AccumSamples, TempBuf, ChanState, - IrSize, BufferSize); -} - - -template<> -void Mix_(const al::span InSamples, const al::span OutBuffer, - float *CurrentGains, const float *TargetGains, const size_t Counter, const size_t OutPos) -{ - const float delta{(Counter > 0) ? 1.0f / static_cast(Counter) : 0.0f}; - const auto min_len = minz(Counter, InSamples.size()); - const auto aligned_len = minz((min_len+3) & ~size_t{3}, InSamples.size()) - min_len; - - for(FloatBufferLine &output : OutBuffer) - { - float *RESTRICT dst{al::assume_aligned<16>(output.data()+OutPos)}; - float gain{*CurrentGains}; - const float step{(*TargetGains-gain) * delta}; - - size_t pos{0}; - if(!(std::abs(step) > std::numeric_limits::epsilon())) - gain = *TargetGains; - else - { - float step_count{0.0f}; - /* Mix with applying gain steps in aligned multiples of 4. */ - if(size_t todo{(min_len-pos) >> 2}) - { - const float32x4_t four4{vdupq_n_f32(4.0f)}; - const float32x4_t step4{vdupq_n_f32(step)}; - const float32x4_t gain4{vdupq_n_f32(gain)}; - float32x4_t step_count4{vdupq_n_f32(0.0f)}; - step_count4 = vsetq_lane_f32(1.0f, step_count4, 1); - step_count4 = vsetq_lane_f32(2.0f, step_count4, 2); - step_count4 = vsetq_lane_f32(3.0f, step_count4, 3); - - do { - const float32x4_t val4 = vld1q_f32(&InSamples[pos]); - float32x4_t dry4 = vld1q_f32(&dst[pos]); - dry4 = vmlaq_f32(dry4, val4, vmlaq_f32(gain4, step4, step_count4)); - step_count4 = vaddq_f32(step_count4, four4); - vst1q_f32(&dst[pos], dry4); - pos += 4; - } while(--todo); - /* NOTE: step_count4 now represents the next four counts after - * the last four mixed samples, so the lowest element - * represents the next step count to apply. - */ - step_count = vgetq_lane_f32(step_count4, 0); - } - /* Mix with applying left over gain steps that aren't aligned multiples of 4. */ - for(size_t leftover{min_len&3};leftover;++pos,--leftover) - { - dst[pos] += InSamples[pos] * (gain + step*step_count); - step_count += 1.0f; - } - if(pos == Counter) - gain = *TargetGains; - else - gain += step*step_count; - - /* Mix until pos is aligned with 4 or the mix is done. */ - for(size_t leftover{aligned_len&3};leftover;++pos,--leftover) - dst[pos] += InSamples[pos] * gain; - } - *CurrentGains = gain; - ++CurrentGains; - ++TargetGains; - - if(!(std::abs(gain) > GainSilenceThreshold)) - continue; - if(size_t todo{(InSamples.size()-pos) >> 2}) - { - const float32x4_t gain4 = vdupq_n_f32(gain); - do { - const float32x4_t val4 = vld1q_f32(&InSamples[pos]); - float32x4_t dry4 = vld1q_f32(&dst[pos]); - dry4 = vmlaq_f32(dry4, val4, gain4); - vst1q_f32(&dst[pos], dry4); - pos += 4; - } while(--todo); - } - for(size_t leftover{(InSamples.size()-pos)&3};leftover;++pos,--leftover) - dst[pos] += InSamples[pos] * gain; - } -} diff --git a/core/mixer/mixer_sse.cpp b/core/mixer/mixer_sse.cpp deleted file mode 100644 index 23caf797..00000000 --- a/core/mixer/mixer_sse.cpp +++ /dev/null @@ -1,271 +0,0 @@ -#include "config.h" - -#include - -#include -#include - -#include "alnumeric.h" -#include "core/bsinc_defs.h" -#include "defs.h" -#include "hrtfbase.h" - -struct SSETag; -struct BSincTag; -struct FastBSincTag; - - -/* SSE2 is required for any SSE support. */ -#if defined(__GNUC__) && !defined(__clang__) && !defined(__SSE2__) -#pragma GCC target("sse2") -#endif - -namespace { - -constexpr uint FracPhaseBitDiff{MixerFracBits - BSincPhaseBits}; -constexpr uint FracPhaseDiffOne{1 << FracPhaseBitDiff}; - -#define MLA4(x, y, z) _mm_add_ps(x, _mm_mul_ps(y, z)) - -inline void ApplyCoeffs(float2 *RESTRICT Values, const size_t IrSize, const HrirArray &Coeffs, - const float left, const float right) -{ - const __m128 lrlr{_mm_setr_ps(left, right, left, right)}; - - ASSUME(IrSize >= MinIrLength); - /* This isn't technically correct to test alignment, but it's true for - * systems that support SSE, which is the only one that needs to know the - * alignment of Values (which alternates between 8- and 16-byte aligned). - */ - if(reinterpret_cast(Values)&0x8) - { - __m128 imp0, imp1; - __m128 coeffs{_mm_load_ps(&Coeffs[0][0])}; - __m128 vals{_mm_loadl_pi(_mm_setzero_ps(), reinterpret_cast<__m64*>(&Values[0][0]))}; - imp0 = _mm_mul_ps(lrlr, coeffs); - vals = _mm_add_ps(imp0, vals); - _mm_storel_pi(reinterpret_cast<__m64*>(&Values[0][0]), vals); - size_t td{((IrSize+1)>>1) - 1}; - size_t i{1}; - do { - coeffs = _mm_load_ps(&Coeffs[i+1][0]); - vals = _mm_load_ps(&Values[i][0]); - imp1 = _mm_mul_ps(lrlr, coeffs); - imp0 = _mm_shuffle_ps(imp0, imp1, _MM_SHUFFLE(1, 0, 3, 2)); - vals = _mm_add_ps(imp0, vals); - _mm_store_ps(&Values[i][0], vals); - imp0 = imp1; - i += 2; - } while(--td); - vals = _mm_loadl_pi(vals, reinterpret_cast<__m64*>(&Values[i][0])); - imp0 = _mm_movehl_ps(imp0, imp0); - vals = _mm_add_ps(imp0, vals); - _mm_storel_pi(reinterpret_cast<__m64*>(&Values[i][0]), vals); - } - else - { - for(size_t i{0};i < IrSize;i += 2) - { - const __m128 coeffs{_mm_load_ps(&Coeffs[i][0])}; - __m128 vals{_mm_load_ps(&Values[i][0])}; - vals = MLA4(vals, lrlr, coeffs); - _mm_store_ps(&Values[i][0], vals); - } - } -} - -} // namespace - -template<> -float *Resample_(const InterpState *state, float *RESTRICT src, uint frac, - uint increment, const al::span dst) -{ - const float *const filter{state->bsinc.filter}; - const __m128 sf4{_mm_set1_ps(state->bsinc.sf)}; - const size_t m{state->bsinc.m}; - - src -= state->bsinc.l; - for(float &out_sample : dst) - { - // Calculate the phase index and factor. - const uint pi{frac >> FracPhaseBitDiff}; - const float pf{static_cast(frac & (FracPhaseDiffOne-1)) * (1.0f/FracPhaseDiffOne)}; - - // Apply the scale and phase interpolated filter. - __m128 r4{_mm_setzero_ps()}; - { - const __m128 pf4{_mm_set1_ps(pf)}; - const float *fil{filter + m*pi*4}; - const float *phd{fil + m}; - const float *scd{phd + m}; - const float *spd{scd + m}; - size_t td{m >> 2}; - size_t j{0u}; - - do { - /* f = ((fil + sf*scd) + pf*(phd + sf*spd)) */ - const __m128 f4 = MLA4( - MLA4(_mm_load_ps(&fil[j]), sf4, _mm_load_ps(&scd[j])), - pf4, MLA4(_mm_load_ps(&phd[j]), sf4, _mm_load_ps(&spd[j]))); - /* r += f*src */ - r4 = MLA4(r4, f4, _mm_loadu_ps(&src[j])); - j += 4; - } while(--td); - } - r4 = _mm_add_ps(r4, _mm_shuffle_ps(r4, r4, _MM_SHUFFLE(0, 1, 2, 3))); - r4 = _mm_add_ps(r4, _mm_movehl_ps(r4, r4)); - out_sample = _mm_cvtss_f32(r4); - - frac += increment; - src += frac>>MixerFracBits; - frac &= MixerFracMask; - } - return dst.data(); -} - -template<> -float *Resample_(const InterpState *state, float *RESTRICT src, uint frac, - uint increment, const al::span dst) -{ - const float *const filter{state->bsinc.filter}; - const size_t m{state->bsinc.m}; - - src -= state->bsinc.l; - for(float &out_sample : dst) - { - // Calculate the phase index and factor. - const uint pi{frac >> FracPhaseBitDiff}; - const float pf{static_cast(frac & (FracPhaseDiffOne-1)) * (1.0f/FracPhaseDiffOne)}; - - // Apply the phase interpolated filter. - __m128 r4{_mm_setzero_ps()}; - { - const __m128 pf4{_mm_set1_ps(pf)}; - const float *fil{filter + m*pi*4}; - const float *phd{fil + m}; - size_t td{m >> 2}; - size_t j{0u}; - - do { - /* f = fil + pf*phd */ - const __m128 f4 = MLA4(_mm_load_ps(&fil[j]), pf4, _mm_load_ps(&phd[j])); - /* r += f*src */ - r4 = MLA4(r4, f4, _mm_loadu_ps(&src[j])); - j += 4; - } while(--td); - } - r4 = _mm_add_ps(r4, _mm_shuffle_ps(r4, r4, _MM_SHUFFLE(0, 1, 2, 3))); - r4 = _mm_add_ps(r4, _mm_movehl_ps(r4, r4)); - out_sample = _mm_cvtss_f32(r4); - - frac += increment; - src += frac>>MixerFracBits; - frac &= MixerFracMask; - } - return dst.data(); -} - - -template<> -void MixHrtf_(const float *InSamples, float2 *AccumSamples, const uint IrSize, - const MixHrtfFilter *hrtfparams, const size_t BufferSize) -{ MixHrtfBase(InSamples, AccumSamples, IrSize, hrtfparams, BufferSize); } - -template<> -void MixHrtfBlend_(const float *InSamples, float2 *AccumSamples, const uint IrSize, - const HrtfFilter *oldparams, const MixHrtfFilter *newparams, const size_t BufferSize) -{ - MixHrtfBlendBase(InSamples, AccumSamples, IrSize, oldparams, newparams, - BufferSize); -} - -template<> -void MixDirectHrtf_(FloatBufferLine &LeftOut, FloatBufferLine &RightOut, - const al::span InSamples, float2 *AccumSamples, - float *TempBuf, HrtfChannelState *ChanState, const size_t IrSize, const size_t BufferSize) -{ - MixDirectHrtfBase(LeftOut, RightOut, InSamples, AccumSamples, TempBuf, ChanState, - IrSize, BufferSize); -} - - -template<> -void Mix_(const al::span InSamples, const al::span OutBuffer, - float *CurrentGains, const float *TargetGains, const size_t Counter, const size_t OutPos) -{ - const float delta{(Counter > 0) ? 1.0f / static_cast(Counter) : 0.0f}; - const auto min_len = minz(Counter, InSamples.size()); - const auto aligned_len = minz((min_len+3) & ~size_t{3}, InSamples.size()) - min_len; - - for(FloatBufferLine &output : OutBuffer) - { - float *RESTRICT dst{al::assume_aligned<16>(output.data()+OutPos)}; - float gain{*CurrentGains}; - const float step{(*TargetGains-gain) * delta}; - - size_t pos{0}; - if(!(std::abs(step) > std::numeric_limits::epsilon())) - gain = *TargetGains; - else - { - float step_count{0.0f}; - /* Mix with applying gain steps in aligned multiples of 4. */ - if(size_t todo{(min_len-pos) >> 2}) - { - const __m128 four4{_mm_set1_ps(4.0f)}; - const __m128 step4{_mm_set1_ps(step)}; - const __m128 gain4{_mm_set1_ps(gain)}; - __m128 step_count4{_mm_setr_ps(0.0f, 1.0f, 2.0f, 3.0f)}; - do { - const __m128 val4{_mm_load_ps(&InSamples[pos])}; - __m128 dry4{_mm_load_ps(&dst[pos])}; - - /* dry += val * (gain + step*step_count) */ - dry4 = MLA4(dry4, val4, MLA4(gain4, step4, step_count4)); - - _mm_store_ps(&dst[pos], dry4); - step_count4 = _mm_add_ps(step_count4, four4); - pos += 4; - } while(--todo); - /* NOTE: step_count4 now represents the next four counts after - * the last four mixed samples, so the lowest element - * represents the next step count to apply. - */ - step_count = _mm_cvtss_f32(step_count4); - } - /* Mix with applying left over gain steps that aren't aligned multiples of 4. */ - for(size_t leftover{min_len&3};leftover;++pos,--leftover) - { - dst[pos] += InSamples[pos] * (gain + step*step_count); - step_count += 1.0f; - } - if(pos == Counter) - gain = *TargetGains; - else - gain += step*step_count; - - /* Mix until pos is aligned with 4 or the mix is done. */ - for(size_t leftover{aligned_len&3};leftover;++pos,--leftover) - dst[pos] += InSamples[pos] * gain; - } - *CurrentGains = gain; - ++CurrentGains; - ++TargetGains; - - if(!(std::abs(gain) > GainSilenceThreshold)) - continue; - if(size_t todo{(InSamples.size()-pos) >> 2}) - { - const __m128 gain4{_mm_set1_ps(gain)}; - do { - const __m128 val4{_mm_load_ps(&InSamples[pos])}; - __m128 dry4{_mm_load_ps(&dst[pos])}; - dry4 = _mm_add_ps(dry4, _mm_mul_ps(val4, gain4)); - _mm_store_ps(&dst[pos], dry4); - pos += 4; - } while(--todo); - } - for(size_t leftover{(InSamples.size()-pos)&3};leftover;++pos,--leftover) - dst[pos] += InSamples[pos] * gain; - } -} diff --git a/core/mixer/mixer_sse2.cpp b/core/mixer/mixer_sse2.cpp deleted file mode 100644 index f91d5dcd..00000000 --- a/core/mixer/mixer_sse2.cpp +++ /dev/null @@ -1,89 +0,0 @@ -/** - * OpenAL cross platform audio library - * Copyright (C) 2014 by Timothy Arceri . - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - * Or go to http://www.gnu.org/copyleft/lgpl.html - */ - -#include "config.h" - -#include -#include - -#include "alnumeric.h" -#include "defs.h" - -struct SSE2Tag; -struct LerpTag; - - -#if defined(__GNUC__) && !defined(__clang__) && !defined(__SSE2__) -#pragma GCC target("sse2") -#endif - -template<> -float *Resample_(const InterpState*, float *RESTRICT src, uint frac, - uint increment, const al::span dst) -{ - const __m128i increment4{_mm_set1_epi32(static_cast(increment*4))}; - const __m128 fracOne4{_mm_set1_ps(1.0f/MixerFracOne)}; - const __m128i fracMask4{_mm_set1_epi32(MixerFracMask)}; - - alignas(16) uint pos_[4], frac_[4]; - InitPosArrays(frac, increment, frac_, pos_); - __m128i frac4{_mm_setr_epi32(static_cast(frac_[0]), static_cast(frac_[1]), - static_cast(frac_[2]), static_cast(frac_[3]))}; - __m128i pos4{_mm_setr_epi32(static_cast(pos_[0]), static_cast(pos_[1]), - static_cast(pos_[2]), static_cast(pos_[3]))}; - - auto dst_iter = dst.begin(); - for(size_t todo{dst.size()>>2};todo;--todo) - { - const int pos0{_mm_cvtsi128_si32(_mm_shuffle_epi32(pos4, _MM_SHUFFLE(0, 0, 0, 0)))}; - const int pos1{_mm_cvtsi128_si32(_mm_shuffle_epi32(pos4, _MM_SHUFFLE(1, 1, 1, 1)))}; - const int pos2{_mm_cvtsi128_si32(_mm_shuffle_epi32(pos4, _MM_SHUFFLE(2, 2, 2, 2)))}; - const int pos3{_mm_cvtsi128_si32(_mm_shuffle_epi32(pos4, _MM_SHUFFLE(3, 3, 3, 3)))}; - const __m128 val1{_mm_setr_ps(src[pos0 ], src[pos1 ], src[pos2 ], src[pos3 ])}; - const __m128 val2{_mm_setr_ps(src[pos0+1], src[pos1+1], src[pos2+1], src[pos3+1])}; - - /* val1 + (val2-val1)*mu */ - const __m128 r0{_mm_sub_ps(val2, val1)}; - const __m128 mu{_mm_mul_ps(_mm_cvtepi32_ps(frac4), fracOne4)}; - const __m128 out{_mm_add_ps(val1, _mm_mul_ps(mu, r0))}; - - _mm_store_ps(dst_iter, out); - dst_iter += 4; - - frac4 = _mm_add_epi32(frac4, increment4); - pos4 = _mm_add_epi32(pos4, _mm_srli_epi32(frac4, MixerFracBits)); - frac4 = _mm_and_si128(frac4, fracMask4); - } - - if(size_t todo{dst.size()&3}) - { - src += static_cast(_mm_cvtsi128_si32(pos4)); - frac = static_cast(_mm_cvtsi128_si32(frac4)); - - do { - *(dst_iter++) = lerp(src[0], src[1], static_cast(frac) * (1.0f/MixerFracOne)); - - frac += increment; - src += frac>>MixerFracBits; - frac &= MixerFracMask; - } while(--todo); - } - return dst.data(); -} diff --git a/core/mixer/mixer_sse3.cpp b/core/mixer/mixer_sse3.cpp deleted file mode 100644 index e69de29b..00000000 diff --git a/core/mixer/mixer_sse41.cpp b/core/mixer/mixer_sse41.cpp deleted file mode 100644 index 032e5d54..00000000 --- a/core/mixer/mixer_sse41.cpp +++ /dev/null @@ -1,94 +0,0 @@ -/** - * OpenAL cross platform audio library - * Copyright (C) 2014 by Timothy Arceri . - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public - * License along with this library; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - * Or go to http://www.gnu.org/copyleft/lgpl.html - */ - -#include "config.h" - -#include -#include -#include - -#include "alnumeric.h" -#include "defs.h" - -struct SSE4Tag; -struct LerpTag; - - -#if defined(__GNUC__) && !defined(__clang__) && !defined(__SSE4_1__) -#pragma GCC target("sse4.1") -#endif - -template<> -float *Resample_(const InterpState*, float *RESTRICT src, uint frac, - uint increment, const al::span dst) -{ - const __m128i increment4{_mm_set1_epi32(static_cast(increment*4))}; - const __m128 fracOne4{_mm_set1_ps(1.0f/MixerFracOne)}; - const __m128i fracMask4{_mm_set1_epi32(MixerFracMask)}; - - alignas(16) uint pos_[4], frac_[4]; - InitPosArrays(frac, increment, frac_, pos_); - __m128i frac4{_mm_setr_epi32(static_cast(frac_[0]), static_cast(frac_[1]), - static_cast(frac_[2]), static_cast(frac_[3]))}; - __m128i pos4{_mm_setr_epi32(static_cast(pos_[0]), static_cast(pos_[1]), - static_cast(pos_[2]), static_cast(pos_[3]))}; - - auto dst_iter = dst.begin(); - for(size_t todo{dst.size()>>2};todo;--todo) - { - const int pos0{_mm_extract_epi32(pos4, 0)}; - const int pos1{_mm_extract_epi32(pos4, 1)}; - const int pos2{_mm_extract_epi32(pos4, 2)}; - const int pos3{_mm_extract_epi32(pos4, 3)}; - const __m128 val1{_mm_setr_ps(src[pos0 ], src[pos1 ], src[pos2 ], src[pos3 ])}; - const __m128 val2{_mm_setr_ps(src[pos0+1], src[pos1+1], src[pos2+1], src[pos3+1])}; - - /* val1 + (val2-val1)*mu */ - const __m128 r0{_mm_sub_ps(val2, val1)}; - const __m128 mu{_mm_mul_ps(_mm_cvtepi32_ps(frac4), fracOne4)}; - const __m128 out{_mm_add_ps(val1, _mm_mul_ps(mu, r0))}; - - _mm_store_ps(dst_iter, out); - dst_iter += 4; - - frac4 = _mm_add_epi32(frac4, increment4); - pos4 = _mm_add_epi32(pos4, _mm_srli_epi32(frac4, MixerFracBits)); - frac4 = _mm_and_si128(frac4, fracMask4); - } - - if(size_t todo{dst.size()&3}) - { - /* NOTE: These four elements represent the position *after* the last - * four samples, so the lowest element is the next position to - * resample. - */ - src += static_cast(_mm_cvtsi128_si32(pos4)); - frac = static_cast(_mm_cvtsi128_si32(frac4)); - - do { - *(dst_iter++) = lerp(src[0], src[1], static_cast(frac) * (1.0f/MixerFracOne)); - - frac += increment; - src += frac>>MixerFracBits; - frac &= MixerFracMask; - } while(--todo); - } - return dst.data(); -} diff --git a/core/uhjfilter.cpp b/core/uhjfilter.cpp deleted file mode 100644 index 92f35901..00000000 --- a/core/uhjfilter.cpp +++ /dev/null @@ -1,275 +0,0 @@ - -#include "config.h" - -#include "uhjfilter.h" - -#ifdef HAVE_SSE_INTRINSICS -#include -#elif defined(HAVE_NEON) -#include -#endif - -#include -#include - -#include "alcomplex.h" -#include "alnumeric.h" -#include "opthelpers.h" - - -namespace { - -using complex_d = std::complex; - -struct PhaseShifterT { - alignas(16) std::array Coeffs; - - /* Some notes on this filter construction. - * - * A wide-band phase-shift filter needs a delay to maintain linearity. A - * dirac impulse in the center of a time-domain buffer represents a filter - * passing all frequencies through as-is with a pure delay. Converting that - * to the frequency domain, adjusting the phase of each frequency bin by - * +90 degrees, then converting back to the time domain, results in a FIR - * filter that applies a +90 degree wide-band phase-shift. - * - * A particularly notable aspect of the time-domain filter response is that - * every other coefficient is 0. This allows doubling the effective size of - * the filter, by storing only the non-0 coefficients and double-stepping - * over the input to apply it. - * - * Additionally, the resulting filter is independent of the sample rate. - * The same filter can be applied regardless of the device's sample rate - * and achieve the same effect. - */ - PhaseShifterT() - { - constexpr size_t fft_size{Uhj2Encoder::sFilterSize * 2}; - constexpr size_t half_size{fft_size / 2}; - - /* Generate a frequency domain impulse with a +90 degree phase offset. - * Reconstruct the mirrored frequencies to convert to the time domain. - */ - auto fftBuffer = std::make_unique(fft_size); - std::fill_n(fftBuffer.get(), fft_size, complex_d{}); - fftBuffer[half_size] = 1.0; - - forward_fft({fftBuffer.get(), fft_size}); - for(size_t i{0};i < half_size+1;++i) - fftBuffer[i] = complex_d{-fftBuffer[i].imag(), fftBuffer[i].real()}; - for(size_t i{half_size+1};i < fft_size;++i) - fftBuffer[i] = std::conj(fftBuffer[fft_size - i]); - inverse_fft({fftBuffer.get(), fft_size}); - - /* Reverse the filter for simpler processing, and store only the non-0 - * coefficients. - */ - auto fftiter = fftBuffer.get() + half_size + (Uhj2Encoder::sFilterSize-1); - for(float &coeff : Coeffs) - { - coeff = static_cast(fftiter->real() / double{fft_size}); - fftiter -= 2; - } - } -}; -const PhaseShifterT PShift{}; - -void allpass_process(al::span dst, const float *RESTRICT src) -{ -#ifdef HAVE_SSE_INTRINSICS - size_t pos{0}; - if(size_t todo{dst.size()>>1}) - { - do { - __m128 r04{_mm_setzero_ps()}; - __m128 r14{_mm_setzero_ps()}; - for(size_t j{0};j < PShift.Coeffs.size();j+=4) - { - const __m128 coeffs{_mm_load_ps(&PShift.Coeffs[j])}; - const __m128 s0{_mm_loadu_ps(&src[j*2])}; - const __m128 s1{_mm_loadu_ps(&src[j*2 + 4])}; - - __m128 s{_mm_shuffle_ps(s0, s1, _MM_SHUFFLE(2, 0, 2, 0))}; - r04 = _mm_add_ps(r04, _mm_mul_ps(s, coeffs)); - - s = _mm_shuffle_ps(s0, s1, _MM_SHUFFLE(3, 1, 3, 1)); - r14 = _mm_add_ps(r14, _mm_mul_ps(s, coeffs)); - } - r04 = _mm_add_ps(r04, _mm_shuffle_ps(r04, r04, _MM_SHUFFLE(0, 1, 2, 3))); - r04 = _mm_add_ps(r04, _mm_movehl_ps(r04, r04)); - dst[pos++] += _mm_cvtss_f32(r04); - - r14 = _mm_add_ps(r14, _mm_shuffle_ps(r14, r14, _MM_SHUFFLE(0, 1, 2, 3))); - r14 = _mm_add_ps(r14, _mm_movehl_ps(r14, r14)); - dst[pos++] += _mm_cvtss_f32(r14); - - src += 2; - } while(--todo); - } - if((dst.size()&1)) - { - __m128 r4{_mm_setzero_ps()}; - for(size_t j{0};j < PShift.Coeffs.size();j+=4) - { - const __m128 coeffs{_mm_load_ps(&PShift.Coeffs[j])}; - /* NOTE: This could alternatively be done with two unaligned loads - * and a shuffle. Which would be better? - */ - const __m128 s{_mm_setr_ps(src[j*2], src[j*2 + 2], src[j*2 + 4], src[j*2 + 6])}; - r4 = _mm_add_ps(r4, _mm_mul_ps(s, coeffs)); - } - r4 = _mm_add_ps(r4, _mm_shuffle_ps(r4, r4, _MM_SHUFFLE(0, 1, 2, 3))); - r4 = _mm_add_ps(r4, _mm_movehl_ps(r4, r4)); - - dst[pos] += _mm_cvtss_f32(r4); - } - -#elif defined(HAVE_NEON) - - size_t pos{0}; - if(size_t todo{dst.size()>>1}) - { - /* There doesn't seem to be NEON intrinsics to do this kind of stipple - * shuffling, so there's two custom methods for it. - */ - auto shuffle_2020 = [](float32x4_t a, float32x4_t b) - { - float32x4_t ret{vmovq_n_f32(vgetq_lane_f32(a, 0))}; - ret = vsetq_lane_f32(vgetq_lane_f32(a, 2), ret, 1); - ret = vsetq_lane_f32(vgetq_lane_f32(b, 0), ret, 2); - ret = vsetq_lane_f32(vgetq_lane_f32(b, 2), ret, 3); - return ret; - }; - auto shuffle_3131 = [](float32x4_t a, float32x4_t b) - { - float32x4_t ret{vmovq_n_f32(vgetq_lane_f32(a, 1))}; - ret = vsetq_lane_f32(vgetq_lane_f32(a, 3), ret, 1); - ret = vsetq_lane_f32(vgetq_lane_f32(b, 1), ret, 2); - ret = vsetq_lane_f32(vgetq_lane_f32(b, 3), ret, 3); - return ret; - }; - do { - float32x4_t r04{vdupq_n_f32(0.0f)}; - float32x4_t r14{vdupq_n_f32(0.0f)}; - for(size_t j{0};j < PShift.Coeffs.size();j+=4) - { - const float32x4_t coeffs{vld1q_f32(&PShift.Coeffs[j])}; - const float32x4_t s0{vld1q_f32(&src[j*2])}; - const float32x4_t s1{vld1q_f32(&src[j*2 + 4])}; - - r04 = vmlaq_f32(r04, shuffle_2020(s0, s1), coeffs); - r14 = vmlaq_f32(r14, shuffle_3131(s0, s1), coeffs); - } - r04 = vaddq_f32(r04, vrev64q_f32(r04)); - dst[pos++] = vget_lane_f32(vadd_f32(vget_low_f32(r04), vget_high_f32(r04)), 0); - - r14 = vaddq_f32(r14, vrev64q_f32(r14)); - dst[pos++] = vget_lane_f32(vadd_f32(vget_low_f32(r14), vget_high_f32(r14)), 0); - - src += 2; - } while(--todo); - } - if((dst.size()&1)) - { - auto load4 = [](float32_t a, float32_t b, float32_t c, float32_t d) - { - float32x4_t ret{vmovq_n_f32(a)}; - ret = vsetq_lane_f32(b, ret, 1); - ret = vsetq_lane_f32(c, ret, 2); - ret = vsetq_lane_f32(d, ret, 3); - return ret; - }; - float32x4_t r4{vdupq_n_f32(0.0f)}; - for(size_t j{0};j < PShift.Coeffs.size();j+=4) - { - const float32x4_t coeffs{vld1q_f32(&PShift.Coeffs[j])}; - const float32x4_t s{load4(src[j*2], src[j*2 + 2], src[j*2 + 4], src[j*2 + 6])}; - r4 = vmlaq_f32(r4, s, coeffs); - } - r4 = vaddq_f32(r4, vrev64q_f32(r4)); - dst[pos] = vget_lane_f32(vadd_f32(vget_low_f32(r4), vget_high_f32(r4)), 0); - } - -#else - - for(float &output : dst) - { - float ret{0.0f}; - for(size_t j{0};j < PShift.Coeffs.size();++j) - ret += src[j*2] * PShift.Coeffs[j]; - - output += ret; - ++src; - } -#endif -} - -} // namespace - - -/* Encoding 2-channel UHJ from B-Format is done as: - * - * S = 0.9396926*W + 0.1855740*X - * D = j(-0.3420201*W + 0.5098604*X) + 0.6554516*Y - * - * Left = (S + D)/2.0 - * Right = (S - D)/2.0 - * - * where j is a wide-band +90 degree phase shift. - * - * The phase shift is done using a FIR filter derived from an FFT'd impulse - * with the desired shift. - */ - -void Uhj2Encoder::encode(FloatBufferLine &LeftOut, FloatBufferLine &RightOut, - const FloatBufferLine *InSamples, const size_t SamplesToDo) -{ - ASSUME(SamplesToDo > 0); - - float *RESTRICT left{al::assume_aligned<16>(LeftOut.data())}; - float *RESTRICT right{al::assume_aligned<16>(RightOut.data())}; - - const float *RESTRICT winput{al::assume_aligned<16>(InSamples[0].data())}; - const float *RESTRICT xinput{al::assume_aligned<16>(InSamples[1].data())}; - const float *RESTRICT yinput{al::assume_aligned<16>(InSamples[2].data())}; - - /* Combine the previously delayed mid/side signal with the input. */ - - /* S = 0.9396926*W + 0.1855740*X */ - auto miditer = std::copy(mMidDelay.cbegin(), mMidDelay.cend(), mMid.begin()); - std::transform(winput, winput+SamplesToDo, xinput, miditer, - [](const float w, const float x) noexcept -> float - { return 0.9396926f*w + 0.1855740f*x; }); - - /* D = 0.6554516*Y */ - auto sideiter = std::copy(mSideDelay.cbegin(), mSideDelay.cend(), mSide.begin()); - std::transform(yinput, yinput+SamplesToDo, sideiter, - [](const float y) noexcept -> float { return 0.6554516f*y; }); - - /* Include any existing direct signal in the mid/side buffers. */ - for(size_t i{0};i < SamplesToDo;++i,++miditer) - *miditer += left[i] + right[i]; - for(size_t i{0};i < SamplesToDo;++i,++sideiter) - *sideiter += left[i] - right[i]; - - /* Copy the future samples back to the delay buffers for next time. */ - std::copy_n(mMid.cbegin()+SamplesToDo, mMidDelay.size(), mMidDelay.begin()); - std::copy_n(mSide.cbegin()+SamplesToDo, mSideDelay.size(), mSideDelay.begin()); - - /* Now add the all-passed signal into the side signal. */ - - /* D += j(-0.3420201*W + 0.5098604*X) */ - auto tmpiter = std::copy(mSideHistory.cbegin(), mSideHistory.cend(), mTemp.begin()); - std::transform(winput, winput+SamplesToDo, xinput, tmpiter, - [](const float w, const float x) noexcept -> float - { return -0.3420201f*w + 0.5098604f*x; }); - std::copy_n(mTemp.cbegin()+SamplesToDo, mSideHistory.size(), mSideHistory.begin()); - allpass_process({mSide.data(), SamplesToDo}, mTemp.data()); - - /* Left = (S + D)/2.0 */ - for(size_t i{0};i < SamplesToDo;i++) - left[i] = (mMid[i] + mSide[i]) * 0.5f; - /* Right = (S - D)/2.0 */ - for(size_t i{0};i < SamplesToDo;i++) - right[i] = (mMid[i] - mSide[i]) * 0.5f; -} diff --git a/core/uhjfilter.h b/core/uhjfilter.h deleted file mode 100644 index c2cb8722..00000000 --- a/core/uhjfilter.h +++ /dev/null @@ -1,39 +0,0 @@ -#ifndef CORE_UHJFILTER_H -#define CORE_UHJFILTER_H - -#include - -#include "almalloc.h" -#include "bufferline.h" - - -struct Uhj2Encoder { - /* A particular property of the filter allows it to cover nearly twice its - * length, so the filter size is also the effective delay (despite being - * center-aligned). - */ - constexpr static size_t sFilterSize{128}; - - /* Delays for the unfiltered signal. */ - alignas(16) std::array mMidDelay{}; - alignas(16) std::array mSideDelay{}; - - alignas(16) std::array mMid{}; - alignas(16) std::array mSide{}; - - /* History for the FIR filter. */ - alignas(16) std::array mSideHistory{}; - - alignas(16) std::array mTemp{}; - - /** - * Encodes a 2-channel UHJ (stereo-compatible) signal from a B-Format input - * signal. The input must use FuMa channel ordering and scaling. - */ - void encode(FloatBufferLine &LeftOut, FloatBufferLine &RightOut, - const FloatBufferLine *InSamples, const size_t SamplesToDo); - - DEF_NEWDEL(Uhj2Encoder) -}; - -#endif /* CORE_UHJFILTER_H */ diff --git a/docs/3D7.1.txt b/docs/3D7.1.txt deleted file mode 100644 index 1d40bec6..00000000 --- a/docs/3D7.1.txt +++ /dev/null @@ -1,82 +0,0 @@ -Overview -======== - -3D7.1 is a custom speaker layout designed by Simon Goodwin at Codemasters[1]. -Typical surround sound setups, like quad, 5.1, 6.1, and 7.1, only produce audio -on a 2D horizontal plane with no verticality, which means the envelopment of -"surround" sound is limited to left, right, front, and back panning. Sounds -that should come from above or below will still only play in 2D since there is -no height difference in the speaker array. - -To work around this, 3D7.1 was designed so that some speakers are placed higher -than the listener while others are lower, in a particular configuration that -tries to provide balanced output and maintain some compatibility with existing -audio content and software. Software that recognizes this setup, or can be -configured for it, can then take advantage of the height difference and -increase the perception of verticality for true 3D audio. The result is that -sounds can be perceived as coming from left, right, front, and back, as well as -up and down. - -[1] http://www.codemasters.com/research/3D_sound_for_3D_games.pdf - - -Hardware Setup -============== - -Setting up 3D7.1 requires an audio device capable of raw 8-channel or 7.1 -output, along with a 7.1 speaker kit. The speakers should be hooked up to the -device in the usual way, with front-left and front-right output going to the -front-left and front-right speakers, etc. The placement of the speakers should -be set up according to the table below. Azimuth is the horizontal angle in -degrees, with 0 directly in front and positive values go /left/, and elevation -is the vertical angle in degrees, with 0 at head level and positive values go -/up/. - ------------------------------------------------------------- -- Speaker label | Azimuth | Elevation | New label - ------------------------------------------------------------- -- Front left | 51 | 24 | Upper front left - -- Front right | -51 | 24 | Upper front right - -- Front center | 0 | 0 | Front center - -- Subwoofer/LFE | N/A | N/A | Subwoofer/LFE - -- Side left | 129 | -24 | Lower back left - -- Side right | -129 | -24 | Lower back right - -- Back left | 180 | 55 | Upper back center - -- Back right | 0 | -55 | Lower front center - ------------------------------------------------------------- - -Note that this speaker layout *IS NOT* compatible with standard 7.1 content. -Audio that should be played from the back will come out at the wrong location -since the back speakers are placed in the lower front and upper back positions. -However, this speaker layout *IS* more or less compatible with standard 5.1 -content. Though slightly tilted, to a listener sitting a bit further back from -the center, the front and side speakers will be close enough to their intended -locations that the output won't be too off. - - -Software Setup -============== - -To enable 3D7.1 on OpenAL Soft, first make sure the audio device is configured -for 7.1 output. Then in the alsoft-config utility, under the Renderer tab, -select the 3D7.1.ambdec preset for the 7.1 Surround decoder configuration. And -that's it. Any applications using OpenAL Soft can take advantage of fully 3D -audio, and multi-channel sounds will be properly remixed for the speaker -layout. - -Playback can be improved by (copying and) modifying the 3D7.1.ambdec preset, -changing the specified speaker distances to match the the real distance (in -meters) from the center of the speaker array, then enable High Quality Mode in -alsoft-config. That will improve the quality when the speakers are not all -equidistant. - -Note that care must be taken that the audio device is not treated as a "true" -7.1 device by non-3D7.1-capable applications. In particular, the audio server -should not try to upmix stereo and 5.1 content to "fill out" the back speakers, -and non-3D7.1 apps should be set to either stereo or 5.1 output. - -As such, if your system is capable of it, it may be useful to define a virtual -5.1 device that maps the front, side, and LFE channels to the main device for -output and disables upmixing, then use that virtual 5.1 device for apps that do -normal stereo or surround sound output, and use the main device for apps that -understand 3D7.1 output. diff --git a/docs/ambdec.txt b/docs/ambdec.txt deleted file mode 100644 index 1f328937..00000000 --- a/docs/ambdec.txt +++ /dev/null @@ -1,189 +0,0 @@ -AmbDec Configuration Files -========================== - -AmbDec configuration files were developed by Fons Adriaensen as part of the -AmbDec program . - -The file works by specifying a decoder matrix or matrices which transform -ambisonic channels into speaker feeds. Single-band decoders specify a single -matrix that transforms all frequencies, while dual-band decoders specifies two -matrices where one transforms low frequency sounds and the other transforms -high frequency sounds. See docs/ambisonics.txt for more general information -about ambisonics. - -Starting with OpenAL Soft 1.18, version 3 of the file format is supported as a -means of specifying custom surround sound speaker layouts. These configuration -files are also used to enable the high-quality ambisonic decoder. - - -File Format -=========== - -As of this writing, there is no official documentation of the .ambdec file -format. However, the format as OpenAL Soft sees it is as follows: - -The file is plain text. Comments start with a hash/pound character (#). There -may be any amount of whitespace in between the option and parameter values. -Strings are *not* enclosed in quotation marks. - -/description -Specifies a text description of the configuration. Ignored by OpenAL Soft. - -/version -Declares the format version used by the configuration file. OpenAL Soft -currently only supports version 3. - -/dec/chan_mask -Specifies a hexadecimal mask value of ambisonic input channels used by this -decoder. Counting up from the least significant bit, bit 0 maps to Ambisonic -Channel Number (ACN) 0, bit 1 maps to ACN 1, etc. As an example, a value of 'b' -enables bits 0, 1, and 3 (1011 in binary), which correspond to ACN 0, 1, and 3 -(first-order horizontal). - -/dec/freq_bands -Specifies the number of frequency bands used by the decoder. This must be 1 for -single-band or 2 for dual-band. - -/dec/speakers -Specifies the number of output speakers to decode to. - -/dec/coeff_scale -Specifies the scaling used by the decoder coefficients. Currently recognized -types are fuma, sn3d, and n3d, for Furse-Malham (FuMa), semi-normalized (SN3D), -and fully normalized (N3D) scaling, respectively. - -/opt/input_scale -Specifies the scaling used by the ambisonic input data. As OpenAL Soft renders -the data itself and knows the scaling, this is ignored. - -/opt/nfeff_comp -Specifies whether near-field effect compensation is off (not applied at all), -applied on input (faster, less accurate with varying speaker distances) or -output (slower, more accurate with varying speaker distances). Ignored by -OpenAL Soft. - -/opt/delay_comp -Specifies whether delay compensation is applied for output. This is used to -correct for time variations caused by different speaker distances. As OpenAL -Soft has its own config option for this, this is ignored. - -/opt/level_comp -Specifies whether gain compensation is applied for output. This is used to -correct for volume variations caused by different speaker distances. As OpenAL -Soft has its own config option for this, this is ignored. - -/opt/xover_freq -Specifies the crossover frequency for dual-band decoders. Frequencies less than -this are fed to the low-frequency matrix, and frequencies greater than this are -fed to the high-frequency matrix. Unused for single-band decoders. - -/opt/xover_ratio -Specifies the volume ratio between the frequency bands. Values greater than 0 -decrease the low-frequency output by half the specified value and increase the -high-frequency output by half the specified value, while values less than 0 -increase the low-frequency output and decrease the high-frequency output to -similar effect. Unused for single-band decoders. - -/speakers/{ -Begins the output speaker definitions. A speaker is defined using the add_spkr -command, and there must be a matching number of speaker definitions as the -specified speaker count. The definitions are ended with a "/}". - -add_spkr -Defines an output speaker. The ID is a string identifier for the output speaker -(see Speaker IDs below). The distance is in meters from the center-point of the -physical speaker array. The azimuth is the horizontal angle of the speaker, in -degrees, where 0 is directly front and positive values go left. The elevation -is the vertical angle of the speaker, in degrees, where 0 is directly front and -positive goes upward. The connection string is the JACK port name the speaker -should connect to. Currently, OpenAL Soft uses the ID and distance, and ignores -the rest. - -/lfmatrix/{ -Begins the low-frequency decoder matrix definition. The definition should -include an order_gain command to specify the base gain for the ambisonic -orders. Each matrix row is defined using the add_row command, and there must be -a matching number of rows as the number of speakers. Additionally the row -definitions are in the same order as the speaker definitions. The definitions -are ended with a "/}". Only valid for dual-band decoders. - -/hfmatrix/{ -Begins the high-frequency decoder matrix definition. The definition should -include an order_gain command to specify the base gain for the ambisonic -orders. Each matrix row is defined using the add_row command, and there must be -a matching number of rows as the number of speakers, Additionally the row -definitions are in the same order as the speaker definitions. The definitions -are ended with a "/}". Only valid for dual-band decoders. - -/matrix/{ -Begins the decoder matrix definition. The definition should include an -order_gain command to specify the base gain for the ambisonic orders. Each -matrix row is defined using the add_row command, and there must be a matching -number of rows as the number of speakers. Additionally the row definitions are -in the same order as the speaker definitions. The definitions are ended with a -"/}". Only valid for single-band decoders. - -order_gain -Specifies the base gain for the zeroth-, first-, second-, and third-order -coefficients in the given matrix, automatically scaling the related -coefficients. This should be specified at the beginning of the matrix -definition. - -add_row ... -Specifies a row of coefficients for the matrix. There should be one coefficient -for each enabled bit in the channel mask, and corresponds to the matching ACN -channel. - -/end -Marks the end of the configuration file. - - -Speaker IDs -=========== - -The AmbDec program uses the speaker ID as a label to display in its config -dialog, but does not otherwise use it for any particular purpose. However, -since OpenAL Soft needs to match a speaker definition to an output channel, the -speaker ID is used to identify what output channel it correspond to. Therefore, -OpenAL Soft requires these channel labels to be recognized: - -LF = Front left -RF = Front right -LS = Side left -RS = Side right -LB = Back left -RB = Back right -CE = Front center -CB = Back center - -Additionally, configuration files for surround51 will acknowledge back speakers -for side channels, and surround51rear will acknowledge side speakers for back -channels, to avoid issues with a configuration expecting 5.1 to use the side -channels when the device is configured for back, or vice-versa. - -Furthermore, OpenAL Soft does not require a speaker definition for each output -channel the configuration is used with. So for example a 5.1 configuration may -omit a front center speaker definition, in which case the front center output -channel will not contribute to the ambisonic decode (though OpenAL Soft will -still use it in certain scenarios, such as the AL_EFFECT_DEDICATED_DIALOGUE -effect). - - -Creating Configuration Files -============================ - -Configuration files can be created or modified by hand in a text editor. The -AmbDec program also has a GUI for creating and editing them. However, these -methods rely on you having the coefficients to fill in... they won't be -generated for you. - -Another option is to use the Ambisonic Decoder Toolbox -. This is a collection of -MATLAB and GNU Octave scripts that can generate AmbDec configuration files from -an array of speaker definitions (labels and positions). If you're familiar with -using MATLAB or GNU Octave, this may be a good option. - -There are plans for OpenAL Soft to include a utility to generate coefficients -and make configuration files. However, calculating proper coefficients for -anything other than regular or semi-regular speaker setups is somewhat of a -black art, so may take some time. diff --git a/docs/ambisonics.txt b/docs/ambisonics.txt deleted file mode 100644 index b03e3bed..00000000 --- a/docs/ambisonics.txt +++ /dev/null @@ -1,119 +0,0 @@ -OpenAL Soft's renderer has advanced quite a bit since its start with panned -stereo output. Among these advancements is support for surround sound output, -using psychoacoustic modeling and more accurate plane wave reconstruction. The -concepts in use may not be immediately obvious to people just getting into 3D -audio, or people who only have more indirect experience through the use of 3D -audio APIs, so this document aims to introduce the ideas and purpose of -Ambisonics as used by OpenAL Soft. - - -What Is It? -=========== - -Originally developed in the 1970s by Michael Gerzon and a team others, -Ambisonics was created as a means of recording and playing back 3D sound. -Taking advantage of the way sound waves propogate, it is possible to record a -fully 3D soundfield using as few as 4 channels (or even just 3, if you don't -mind dropping down to 2 dimensions like many surround sound systems are). This -representation is called B-Format. It was designed to handle audio independent -of any specific speaker layout, so with a proper decoder the same recording can -be played back on a variety of speaker setups, from quadraphonic and hexagonal -to cubic and other periphonic (with height) layouts. - -Although it was developed decades ago, various factors held ambisonics back -from really taking hold in the consumer market. However, given the solid -theories backing it, as well as the potential and practical benefits on offer, -it continued to be a topic of research over the years, with improvements being -made over the original design. One of the improvements made is the use of -Spherical Harmonics to increase the number of channels for greater spatial -definition. Where the original 4-channel design is termed as "First-Order -Ambisonics", or FOA, the increased channel count through the use of Spherical -Harmonics is termed as "Higher-Order Ambisonics", or HOA. The details of higher -order ambisonics are out of the scope of this document, but know that the added -channels are still independent of any speaker layout, and aim to further -improve the spatial detail for playback. - -Today, the processing power available on even low-end computers means real-time -Ambisonics processing is possible. Not only can decoders be implemented in -software, but so can encoders, synthesizing a soundfield using multiple panned -sources, thus taking advantage of what ambisonics offers in a virtual audio -environment. - - -How Does It Help? -================= - -Positional sound has come a long way from pan-pot stereo (aka pair-wise). -Although useful at the time, the issues became readily apparent when trying to -extend it for surround sound. Pan-pot doesn't work as well for depth (front- -back) or vertical panning, it has a rather small "sweet spot" (the area the -head needs to be in to perceive the sound in its intended direction), and it -misses key distance-related details of sound waves. - -Ambisonics takes a different approach. It uses all available speakers to help -localize a sound, and it also takes into account how the brain localizes low -frequency sounds compared to high frequency ones -- a so-called psychoacoustic -model. It may seem counter-intuitive (if a sound is coming from the front-left, -surely just play it on the front-left speaker?), but to properly model a sound -coming from where a speaker doesn't exist, more needs to be done to construct a -proper sound wave that's perceived to come from the intended direction. Doing -this creates a larger sweet spot, allowing the perceived sound direction to -remain correct over a larger area around the center of the speakers. - -In addition, Ambisonics can encode the near-field effect of sounds, effectively -capturing the sound distance. The near-field effect is a subtle low-frequency -boost as a result of wave-front curvature, and properly compensating for this -occuring with the output speakers (as well as emulating it with a synthesized -soundfield) can create an improved sense of distance for sounds that move near -or far. - - -How Is It Used? -=============== - -As a 3D audio API, OpenAL is tasked with playing 3D sound as best it can with -the speaker setup the user has. Since the OpenAL API does not explicitly handle -the output channel configuration, it has a lot of leeway in how to deal with -the audio before it's played back for the user to hear. Consequently, OpenAL -Soft (or any other OpenAL implementation that wishes to) can render using -Ambisonics and decode the ambisonic mix for a high level of accuracy over what -simple pan-pot could provide. - -When given an appropriate decoder configuration for the channel layout, the -ambisonic mix can be decoded utilizing the benefits available to ambisonic -processing, including frequency-dependent processing and near-field effects. -Without a decoder configuration, the ambisonic mix can still be decoded for -good stereo or surround sound output, although without near-field effects as -there's no speaker distance information. - -In addition to surround sound output, Ambisonics also has benefits with stereo -output. 2-channel UHJ is a stereo-compatible format that encodes some surround -sound information using a wide-band 90-degree phase shift filter. This is -generated by taking the ambisonic mix and deriving a front-stereo mix with -with the rear sounds filtered in with it. Although the result is not as good as -3-channel (2D) B-Format, it has the distinct advantage of only using 2 channels -and being compatible with stereo output. This means it will sound just fine -when played as-is through a normal stereo device, or it may optionally be fed -to a properly configured surround sound receiver which can extract the encoded -information and restore some of the original surround sound signal. - - -What Are Its Limitations? -========================= - -As good as Ambisonics is, it's not a magic bullet that can overcome all -problems. One of the bigger issues it has is dealing with irregular speaker -setups, such as 5.1 surround sound. The problem mainly lies in the imbalanced -speaker positioning -- there are three speakers within the front 60-degree area -(meaning only 30-degree gaps in between each of the three speakers), while only -two speakers cover the back 140-degree area, leaving 80-degree gaps on the -sides. It should be noted that this problem is inherent to the speaker layout -itself; there isn't much that can be done to get an optimal surround sound -response, with ambisonics or not. It will do the best it can, but there are -trade-offs between detail and accuracy. - -Another issue lies with HRTF. While it's certainly possible to play an -ambisonic mix using HRTF and retain a sense of 3D sound, doing so with a high -degree of spatial detail requires a fair amount of resources, in both memory -and processing time. And even with it, mixing sounds with HRTF directly will -still be better for positional accuracy. diff --git a/docs/env-vars.txt b/docs/env-vars.txt deleted file mode 100644 index fee9ffb0..00000000 --- a/docs/env-vars.txt +++ /dev/null @@ -1,78 +0,0 @@ -Useful Environment Variables - -Below is a list of environment variables that can be set to aid with running or -debugging apps that use OpenAL Soft. They should be set before the app is run. - -*** Logging *** - -ALSOFT_LOGLEVEL -Specifies the amount of logging OpenAL Soft will write out: -0 - Effectively disables all logging -1 - Prints out errors only -2 - Prints out warnings and errors -3 - Prints out additional information, as well as warnings and errors - -ALSOFT_LOGFILE -Specifies a filename that logged output will be written to. Note that the file -will be first cleared when logging is initialized. - -*** Overrides *** - -ALSOFT_CONF -Specifies an additional configuration file to load settings from. These -settings will take precedence over the global and user configs, but not other -environment variable settings. - -ALSOFT_DRIVERS -Overrides the drivers config option. This specifies which backend drivers to -consider or not consider for use. Please see the drivers option in -alsoftrc.sample for a list of available drivers. - -ALSOFT_DEFAULT_REVERB -Specifies the default reverb preset to apply to sources. Please see the -default-reverb option in alsoftrc.sample for additional information and a list -of available presets. - -ALSOFT_TRAP_AL_ERROR -Set to "true" or "1" to force trapping AL errors. Like the trap-al-error config -option, this will raise a SIGTRAP signal (or a breakpoint exception under -Windows) when a context-level error is generated. Useful when run under a -debugger as it will break execution right when the error occurs, making it -easier to track the cause. - -ALSOFT_TRAP_ALC_ERROR -Set to "true" or "1" to force trapping ALC errors. Like the trap-alc-error -config option, this will raise a SIGTRAP signal (or a breakpoint exception -under Windows) when a device-level error is generated. Useful when run under a -debugger as it will break execution right when the error occurs, making it -easier to track the cause. - -ALSOFT_TRAP_ERROR -Set to "true" or "1" to force trapping both ALC and AL errors. - -*** Compatibility *** - -__ALSOFT_HALF_ANGLE_CONES -Older versions of OpenAL Soft incorrectly calculated the cone angles to range -between 0 and 180 degrees, instead of the expected range of 0 to 360 degrees. -Setting this to "true" or "1" restores the old buggy behavior, for apps that -were written to expect the incorrect range. - -__ALSOFT_REVERSE_Z -Applications that don't natively use OpenAL's coordinate system have to convert -to it before passing in 3D coordinates. Depending on how exactly this is done, -it can cause correct output for stereo but incorrect Z panning for surround -sound (i.e., sounds that are supposed to be behind you sound like they're in -front, and vice-versa). Setting this to "true" or "1" will negate the localized -Z coordinate to attempt to fix output for apps that have incorrect front/back -panning. - -__ALSOFT_SUSPEND_CONTEXT -Due to the OpenAL spec not being very clear about them, behavior of the -alcSuspendContext and alcProcessContext methods has varied, and because of -that, previous versions of OpenAL Soft had them no-op. Creative's hardware -drivers and the Rapture3D driver, however, use these methods to batch changes, -which some applications make use of to protect against partial updates. In an -attempt to standardize on that behavior, OpenAL Soft has changed those methods -accordingly. Setting this to "ignore" restores the previous no-op behavior for -applications that interact poorly with the new behavior. diff --git a/docs/hrtf.txt b/docs/hrtf.txt deleted file mode 100644 index 7a1a500f..00000000 --- a/docs/hrtf.txt +++ /dev/null @@ -1,83 +0,0 @@ -HRTF Support -============ - -Starting with OpenAL Soft 1.14, HRTFs can be used to enable enhanced -spatialization for both 3D (mono) and multi-channel sources, when used with -headphones/stereo output. This can be enabled using the 'hrtf' config option. - -For multi-channel sources this creates a virtual speaker effect, making it -sound as if speakers provide a discrete position for each channel around the -listener. For mono sources this provides much more versatility in the perceived -placement of sounds, making it seem as though they are coming from all around, -including above and below the listener, instead of just to the front, back, and -sides. - -The default data set is based on the KEMAR HRTF data provided by MIT, which can -be found at . - - -Custom HRTF Data Sets -===================== - -OpenAL Soft also provides an option to use user-specified data sets, in -addition to or in place of the default set. This allows users to provide data -sets that could be better suited for their heads, or to work with stereo -speakers instead of headphones, for example. - -The file format is specified below. It uses little-endian byte order. - -== -ALchar magic[8] = "MinPHR03"; -ALuint sampleRate; -ALubyte channelType; /* Can be 0 (mono) or 1 (stereo). */ -ALubyte hrirSize; /* Can be 8 to 128 in steps of 8. */ -ALubyte fdCount; /* Can be 1 to 16. */ - -struct { - ALushort distance; /* Can be 50mm to 2500mm. */ - ALubyte evCount; /* Can be 5 to 128. */ - ALubyte azCount[evCount]; /* Each can be 1 to 128. */ -} fields[fdCount]; - -/* NOTE: ALbyte3 is a packed 24-bit sample type, - * hrirCount is the sum of all azCounts. - * channels can be 1 (mono) or 2 (stereo) depending on channelType. - */ -ALbyte3 coefficients[hrirCount][hrirSize][channels]; -ALubyte delays[hrirCount][channels]; /* Each can be 0 to 63. */ -== - -The data layout is as follows: - -The file first starts with the 8-byte marker, "MinPHR03", to identify it as an -HRTF data set. This is followed by an unsigned 32-bit integer, specifying the -sample rate the data set is designed for (OpenAL Soft will resample the HRIRs -if the output device's playback rate doesn't match). - -Afterward, an unsigned 8-bit integer specifies the channel type, which can be 0 -(mono, single-channel) or 1 (stereo, dual-channel). After this is another 8-bit -integer which specifies how many sample points (or finite impulse response -filter coefficients) make up each HRIR. - -The following unsigned 8-bit integer specifies the number of fields used by the -data set, which must be in descending order (farthest first, closest last). -Then for each field an unsigned 16-bit short specifies the distance for that -field in millimeters, followed by an 8-bit integer for the number of -elevations. These elevations start at the bottom (-90 degrees), and increment -upwards. Following this is an array of unsigned 8-bit integers, one for each -elevation which specifies the number of azimuths (and thus HRIRs) that make up -each elevation. Azimuths start clockwise from the front, constructing a full -circle. Mono HRTFs use the same HRIRs for both ears by reversing the azimuth -calculation (ie. left = angle, right = 360-angle). - -The actual coefficients follow. Each coefficient is a signed 24-bit sample. -Stereo HRTFs interleave left/right ear coefficients. The HRIRs must be -minimum-phase. This allows the use of a smaller filter length, reducing -computation. For reference, the default data set uses a 32-point filter while -even the smallest data set provided by MIT used a 128-sample filter (a 4x -reduction by applying minimum-phase reconstruction). - -After the coefficients is an array of unsigned 8-bit delay values as 6.2 fixed- -point integers, one for each HRIR (with stereo HRTFs interleaving left/right -ear delays). This is the propagation delay in samples a signal must wait before -being convolved with the corresponding minimum-phase HRIR filter. diff --git a/examples/alconvolve.c b/examples/alconvolve.c deleted file mode 100644 index d719abdb..00000000 --- a/examples/alconvolve.c +++ /dev/null @@ -1,594 +0,0 @@ -/* - * OpenAL Convolution Reverb Example - * - * Copyright (c) 2020 by Chris Robinson - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -/* This file contains an example for applying convolution reverb to a source. */ - -#include -#include -#include -#include -#include -#include - -#include "sndfile.h" - -#include "AL/al.h" -#include "AL/alext.h" - -#include "common/alhelpers.h" - - -#ifndef AL_SOFT_convolution_reverb -#define AL_SOFT_convolution_reverb -#define AL_EFFECT_CONVOLUTION_REVERB_SOFT 0xA000 -#endif - - -/* Filter object functions */ -static LPALGENFILTERS alGenFilters; -static LPALDELETEFILTERS alDeleteFilters; -static LPALISFILTER alIsFilter; -static LPALFILTERI alFilteri; -static LPALFILTERIV alFilteriv; -static LPALFILTERF alFilterf; -static LPALFILTERFV alFilterfv; -static LPALGETFILTERI alGetFilteri; -static LPALGETFILTERIV alGetFilteriv; -static LPALGETFILTERF alGetFilterf; -static LPALGETFILTERFV alGetFilterfv; - -/* Effect object functions */ -static LPALGENEFFECTS alGenEffects; -static LPALDELETEEFFECTS alDeleteEffects; -static LPALISEFFECT alIsEffect; -static LPALEFFECTI alEffecti; -static LPALEFFECTIV alEffectiv; -static LPALEFFECTF alEffectf; -static LPALEFFECTFV alEffectfv; -static LPALGETEFFECTI alGetEffecti; -static LPALGETEFFECTIV alGetEffectiv; -static LPALGETEFFECTF alGetEffectf; -static LPALGETEFFECTFV alGetEffectfv; - -/* Auxiliary Effect Slot object functions */ -static LPALGENAUXILIARYEFFECTSLOTS alGenAuxiliaryEffectSlots; -static LPALDELETEAUXILIARYEFFECTSLOTS alDeleteAuxiliaryEffectSlots; -static LPALISAUXILIARYEFFECTSLOT alIsAuxiliaryEffectSlot; -static LPALAUXILIARYEFFECTSLOTI alAuxiliaryEffectSloti; -static LPALAUXILIARYEFFECTSLOTIV alAuxiliaryEffectSlotiv; -static LPALAUXILIARYEFFECTSLOTF alAuxiliaryEffectSlotf; -static LPALAUXILIARYEFFECTSLOTFV alAuxiliaryEffectSlotfv; -static LPALGETAUXILIARYEFFECTSLOTI alGetAuxiliaryEffectSloti; -static LPALGETAUXILIARYEFFECTSLOTIV alGetAuxiliaryEffectSlotiv; -static LPALGETAUXILIARYEFFECTSLOTF alGetAuxiliaryEffectSlotf; -static LPALGETAUXILIARYEFFECTSLOTFV alGetAuxiliaryEffectSlotfv; - - -/* This stuff defines a simple streaming player object, the same as alstream.c. - * Comments are removed for brevity, see alstream.c for more details. - */ -#define NUM_BUFFERS 4 -#define BUFFER_SAMPLES 8192 - -typedef struct StreamPlayer { - ALuint buffers[NUM_BUFFERS]; - ALuint source; - - SNDFILE *sndfile; - SF_INFO sfinfo; - float *membuf; - - ALenum format; -} StreamPlayer; - -static StreamPlayer *NewPlayer(void) -{ - StreamPlayer *player; - - player = calloc(1, sizeof(*player)); - assert(player != NULL); - - alGenBuffers(NUM_BUFFERS, player->buffers); - assert(alGetError() == AL_NO_ERROR && "Could not create buffers"); - - alGenSources(1, &player->source); - assert(alGetError() == AL_NO_ERROR && "Could not create source"); - - alSource3i(player->source, AL_POSITION, 0, 0, -1); - alSourcei(player->source, AL_SOURCE_RELATIVE, AL_TRUE); - alSourcei(player->source, AL_ROLLOFF_FACTOR, 0); - assert(alGetError() == AL_NO_ERROR && "Could not set source parameters"); - - return player; -} - -static void ClosePlayerFile(StreamPlayer *player) -{ - if(player->sndfile) - sf_close(player->sndfile); - player->sndfile = NULL; - - free(player->membuf); - player->membuf = NULL; -} - -static void DeletePlayer(StreamPlayer *player) -{ - ClosePlayerFile(player); - - alDeleteSources(1, &player->source); - alDeleteBuffers(NUM_BUFFERS, player->buffers); - if(alGetError() != AL_NO_ERROR) - fprintf(stderr, "Failed to delete object IDs\n"); - - memset(player, 0, sizeof(*player)); - free(player); -} - -static int OpenPlayerFile(StreamPlayer *player, const char *filename) -{ - size_t frame_size; - - ClosePlayerFile(player); - - player->sndfile = sf_open(filename, SFM_READ, &player->sfinfo); - if(!player->sndfile) - { - fprintf(stderr, "Could not open audio in %s: %s\n", filename, sf_strerror(NULL)); - return 0; - } - - player->format = AL_NONE; - if(player->sfinfo.channels == 1) - player->format = AL_FORMAT_MONO_FLOAT32; - else if(player->sfinfo.channels == 2) - player->format = AL_FORMAT_STEREO_FLOAT32; - else if(player->sfinfo.channels == 6) - player->format = AL_FORMAT_51CHN32; - else if(player->sfinfo.channels == 3) - { - if(sf_command(player->sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT) - player->format = AL_FORMAT_BFORMAT2D_FLOAT32; - } - else if(player->sfinfo.channels == 4) - { - if(sf_command(player->sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT) - player->format = AL_FORMAT_BFORMAT3D_FLOAT32; - } - if(!player->format) - { - fprintf(stderr, "Unsupported channel count: %d\n", player->sfinfo.channels); - sf_close(player->sndfile); - player->sndfile = NULL; - return 0; - } - - frame_size = (size_t)(BUFFER_SAMPLES * player->sfinfo.channels) * sizeof(float); - player->membuf = malloc(frame_size); - - return 1; -} - -static int StartPlayer(StreamPlayer *player) -{ - ALsizei i; - - alSourceRewind(player->source); - alSourcei(player->source, AL_BUFFER, 0); - - for(i = 0;i < NUM_BUFFERS;i++) - { - sf_count_t slen = sf_readf_float(player->sndfile, player->membuf, BUFFER_SAMPLES); - if(slen < 1) break; - - slen *= player->sfinfo.channels * (sf_count_t)sizeof(float); - alBufferData(player->buffers[i], player->format, player->membuf, (ALsizei)slen, - player->sfinfo.samplerate); - } - if(alGetError() != AL_NO_ERROR) - { - fprintf(stderr, "Error buffering for playback\n"); - return 0; - } - - alSourceQueueBuffers(player->source, i, player->buffers); - alSourcePlay(player->source); - if(alGetError() != AL_NO_ERROR) - { - fprintf(stderr, "Error starting playback\n"); - return 0; - } - - return 1; -} - -static int UpdatePlayer(StreamPlayer *player) -{ - ALint processed, state; - - alGetSourcei(player->source, AL_SOURCE_STATE, &state); - alGetSourcei(player->source, AL_BUFFERS_PROCESSED, &processed); - if(alGetError() != AL_NO_ERROR) - { - fprintf(stderr, "Error checking source state\n"); - return 0; - } - - while(processed > 0) - { - ALuint bufid; - sf_count_t slen; - - alSourceUnqueueBuffers(player->source, 1, &bufid); - processed--; - - slen = sf_readf_float(player->sndfile, player->membuf, BUFFER_SAMPLES); - if(slen > 0) - { - slen *= player->sfinfo.channels * (sf_count_t)sizeof(float); - alBufferData(bufid, player->format, player->membuf, (ALsizei)slen, - player->sfinfo.samplerate); - alSourceQueueBuffers(player->source, 1, &bufid); - } - if(alGetError() != AL_NO_ERROR) - { - fprintf(stderr, "Error buffering data\n"); - return 0; - } - } - - if(state != AL_PLAYING && state != AL_PAUSED) - { - ALint queued; - - alGetSourcei(player->source, AL_BUFFERS_QUEUED, &queued); - if(queued == 0) - return 0; - - alSourcePlay(player->source); - if(alGetError() != AL_NO_ERROR) - { - fprintf(stderr, "Error restarting playback\n"); - return 0; - } - } - - return 1; -} - - -/* CreateEffect creates a new OpenAL effect object with a convolution reverb - * type, and returns the new effect ID. - */ -static ALuint CreateEffect(void) -{ - ALuint effect = 0; - ALenum err; - - printf("Using Convolution Reverb\n"); - - /* Create the effect object and set the convolution reverb effect type. */ - alGenEffects(1, &effect); - alEffecti(effect, AL_EFFECT_TYPE, AL_EFFECT_CONVOLUTION_REVERB_SOFT); - - /* Check if an error occured, and clean up if so. */ - err = alGetError(); - if(err != AL_NO_ERROR) - { - fprintf(stderr, "OpenAL error: %s\n", alGetString(err)); - if(alIsEffect(effect)) - alDeleteEffects(1, &effect); - return 0; - } - - return effect; -} - -/* LoadBuffer loads the named audio file into an OpenAL buffer object, and - * returns the new buffer ID. - */ -static ALuint LoadSound(const char *filename) -{ - const char *namepart; - ALenum err, format; - ALuint buffer; - SNDFILE *sndfile; - SF_INFO sfinfo; - float *membuf; - sf_count_t num_frames; - ALsizei num_bytes; - - /* Open the audio file and check that it's usable. */ - sndfile = sf_open(filename, SFM_READ, &sfinfo); - if(!sndfile) - { - fprintf(stderr, "Could not open audio in %s: %s\n", filename, sf_strerror(sndfile)); - return 0; - } - if(sfinfo.frames < 1 || sfinfo.frames > (sf_count_t)(INT_MAX/sizeof(float))/sfinfo.channels) - { - fprintf(stderr, "Bad sample count in %s (%" PRId64 ")\n", filename, sfinfo.frames); - sf_close(sndfile); - return 0; - } - - /* Get the sound format, and figure out the OpenAL format. Use floats since - * impulse responses will usually have more than 16-bit precision. - */ - format = AL_NONE; - if(sfinfo.channels == 1) - format = AL_FORMAT_MONO_FLOAT32; - else if(sfinfo.channels == 2) - format = AL_FORMAT_STEREO_FLOAT32; - else if(sfinfo.channels == 3) - { - if(sf_command(sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT) - format = AL_FORMAT_BFORMAT2D_FLOAT32; - } - else if(sfinfo.channels == 4) - { - if(sf_command(sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT) - format = AL_FORMAT_BFORMAT3D_FLOAT32; - } - if(!format) - { - fprintf(stderr, "Unsupported channel count: %d\n", sfinfo.channels); - sf_close(sndfile); - return 0; - } - - namepart = strrchr(filename, '/'); - if(namepart || (namepart=strrchr(filename, '\\'))) - namepart++; - else - namepart = filename; - printf("Loading: %s (%s, %dhz, %" PRId64 " samples / %.2f seconds)\n", namepart, - FormatName(format), sfinfo.samplerate, sfinfo.frames, - (double)sfinfo.frames / sfinfo.samplerate); - fflush(stdout); - - /* Decode the whole audio file to a buffer. */ - membuf = malloc((size_t)(sfinfo.frames * sfinfo.channels) * sizeof(float)); - - num_frames = sf_readf_float(sndfile, membuf, sfinfo.frames); - if(num_frames < 1) - { - free(membuf); - sf_close(sndfile); - fprintf(stderr, "Failed to read samples in %s (%" PRId64 ")\n", filename, num_frames); - return 0; - } - num_bytes = (ALsizei)(num_frames * sfinfo.channels) * (ALsizei)sizeof(float); - - /* Buffer the audio data into a new buffer object, then free the data and - * close the file. - */ - buffer = 0; - alGenBuffers(1, &buffer); - alBufferData(buffer, format, membuf, num_bytes, sfinfo.samplerate); - - free(membuf); - sf_close(sndfile); - - /* Check if an error occured, and clean up if so. */ - err = alGetError(); - if(err != AL_NO_ERROR) - { - fprintf(stderr, "OpenAL Error: %s\n", alGetString(err)); - if(buffer && alIsBuffer(buffer)) - alDeleteBuffers(1, &buffer); - return 0; - } - - return buffer; -} - - -int main(int argc, char **argv) -{ - ALuint ir_buffer, filter, effect, slot; - StreamPlayer *player; - int i; - - /* Print out usage if no arguments were specified */ - if(argc < 2) - { - fprintf(stderr, "Usage: %s [-device ] " - "<[-dry | -nodry] filename>...\n", argv[0]); - return 1; - } - - argv++; argc--; - if(InitAL(&argv, &argc) != 0) - return 1; - - if(!alIsExtensionPresent("AL_SOFTX_convolution_reverb")) - { - CloseAL(); - fprintf(stderr, "Error: Convolution revern not supported\n"); - return 1; - } - - if(argc < 2) - { - CloseAL(); - fprintf(stderr, "Error: Missing impulse response or sound files\n"); - return 1; - } - - /* Define a macro to help load the function pointers. */ -#define LOAD_PROC(T, x) ((x) = (T)alGetProcAddress(#x)) - LOAD_PROC(LPALGENFILTERS, alGenFilters); - LOAD_PROC(LPALDELETEFILTERS, alDeleteFilters); - LOAD_PROC(LPALISFILTER, alIsFilter); - LOAD_PROC(LPALFILTERI, alFilteri); - LOAD_PROC(LPALFILTERIV, alFilteriv); - LOAD_PROC(LPALFILTERF, alFilterf); - LOAD_PROC(LPALFILTERFV, alFilterfv); - LOAD_PROC(LPALGETFILTERI, alGetFilteri); - LOAD_PROC(LPALGETFILTERIV, alGetFilteriv); - LOAD_PROC(LPALGETFILTERF, alGetFilterf); - LOAD_PROC(LPALGETFILTERFV, alGetFilterfv); - - LOAD_PROC(LPALGENEFFECTS, alGenEffects); - LOAD_PROC(LPALDELETEEFFECTS, alDeleteEffects); - LOAD_PROC(LPALISEFFECT, alIsEffect); - LOAD_PROC(LPALEFFECTI, alEffecti); - LOAD_PROC(LPALEFFECTIV, alEffectiv); - LOAD_PROC(LPALEFFECTF, alEffectf); - LOAD_PROC(LPALEFFECTFV, alEffectfv); - LOAD_PROC(LPALGETEFFECTI, alGetEffecti); - LOAD_PROC(LPALGETEFFECTIV, alGetEffectiv); - LOAD_PROC(LPALGETEFFECTF, alGetEffectf); - LOAD_PROC(LPALGETEFFECTFV, alGetEffectfv); - - LOAD_PROC(LPALGENAUXILIARYEFFECTSLOTS, alGenAuxiliaryEffectSlots); - LOAD_PROC(LPALDELETEAUXILIARYEFFECTSLOTS, alDeleteAuxiliaryEffectSlots); - LOAD_PROC(LPALISAUXILIARYEFFECTSLOT, alIsAuxiliaryEffectSlot); - LOAD_PROC(LPALAUXILIARYEFFECTSLOTI, alAuxiliaryEffectSloti); - LOAD_PROC(LPALAUXILIARYEFFECTSLOTIV, alAuxiliaryEffectSlotiv); - LOAD_PROC(LPALAUXILIARYEFFECTSLOTF, alAuxiliaryEffectSlotf); - LOAD_PROC(LPALAUXILIARYEFFECTSLOTFV, alAuxiliaryEffectSlotfv); - LOAD_PROC(LPALGETAUXILIARYEFFECTSLOTI, alGetAuxiliaryEffectSloti); - LOAD_PROC(LPALGETAUXILIARYEFFECTSLOTIV, alGetAuxiliaryEffectSlotiv); - LOAD_PROC(LPALGETAUXILIARYEFFECTSLOTF, alGetAuxiliaryEffectSlotf); - LOAD_PROC(LPALGETAUXILIARYEFFECTSLOTFV, alGetAuxiliaryEffectSlotfv); -#undef LOAD_PROC - - /* Load the reverb into an effect. */ - effect = CreateEffect(); - if(!effect) - { - CloseAL(); - return 1; - } - - /* Load the impulse response sound into a buffer. */ - ir_buffer = LoadSound(argv[0]); - if(!ir_buffer) - { - alDeleteEffects(1, &effect); - CloseAL(); - return 1; - } - - /* Create the effect slot object. This is what "plays" an effect on sources - * that connect to it. - */ - slot = 0; - alGenAuxiliaryEffectSlots(1, &slot); - - /* Set the impulse response sound buffer on the effect slot. This allows - * effects to access it as needed. In this case, convolution reverb uses it - * as the filter source. NOTE: Unlike the effect object, the buffer *is* - * kept referenced and may not be changed or deleted as long as it's set, - * just like with a source. When another buffer is set, or the effect slot - * is deleted, the buffer reference is released. - * - * The effect slot's gain is reduced because the impulse responses I've - * tested with result in excessively loud reverb. Is that normal? Even with - * this, it seems a bit on the loud side. - * - * Also note: unlike standard or EAX reverb, there is no automatic - * attenuation of a source's reverb response with distance, so the reverb - * will remain full volume regardless of a given sound's distance from the - * listener. You can use a send filter to alter a given source's - * contribution to reverb. - */ - alAuxiliaryEffectSloti(slot, AL_BUFFER, (ALint)ir_buffer); - alAuxiliaryEffectSlotf(slot, AL_EFFECTSLOT_GAIN, 1.0f / 16.0f); - alAuxiliaryEffectSloti(slot, AL_EFFECTSLOT_EFFECT, (ALint)effect); - assert(alGetError()==AL_NO_ERROR && "Failed to set effect slot"); - - /* Create a filter that can silence the dry path. */ - filter = 0; - alGenFilters(1, &filter); - alFilteri(filter, AL_FILTER_TYPE, AL_FILTER_LOWPASS); - alFilterf(filter, AL_LOWPASS_GAIN, 0.0f); - - player = NewPlayer(); - /* Connect the player's source to the effect slot. */ - alSource3i(player->source, AL_AUXILIARY_SEND_FILTER, (ALint)slot, 0, AL_FILTER_NULL); - assert(alGetError()==AL_NO_ERROR && "Failed to setup sound source"); - - /* Play each file listed on the command line */ - for(i = 1;i < argc;i++) - { - const char *namepart; - - if(argc-i > 1) - { - if(strcasecmp(argv[i], "-nodry") == 0) - { - alSourcei(player->source, AL_DIRECT_FILTER, (ALint)filter); - ++i; - } - else if(strcasecmp(argv[i], "-dry") == 0) - { - alSourcei(player->source, AL_DIRECT_FILTER, AL_FILTER_NULL); - ++i; - } - } - - if(!OpenPlayerFile(player, argv[i])) - continue; - - namepart = strrchr(argv[i], '/'); - if(namepart || (namepart=strrchr(argv[i], '\\'))) - namepart++; - else - namepart = argv[i]; - - printf("Playing: %s (%s, %dhz)\n", namepart, FormatName(player->format), - player->sfinfo.samplerate); - fflush(stdout); - - if(!StartPlayer(player)) - { - ClosePlayerFile(player); - continue; - } - - while(UpdatePlayer(player)) - al_nssleep(10000000); - - ClosePlayerFile(player); - } - printf("Done.\n"); - - /* All files done. Delete the player and effect resources, and close down - * OpenAL. - */ - DeletePlayer(player); - player = NULL; - - alDeleteAuxiliaryEffectSlots(1, &slot); - alDeleteEffects(1, &effect); - alDeleteFilters(1, &filter); - alDeleteBuffers(1, &ir_buffer); - - CloseAL(); - - return 0; -} diff --git a/examples/alffplay.cpp b/examples/alffplay.cpp deleted file mode 100644 index 6886a42d..00000000 --- a/examples/alffplay.cpp +++ /dev/null @@ -1,2111 +0,0 @@ -/* - * An example showing how to play a stream sync'd to video, using ffmpeg. - * - * Requires C++14. - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -extern "C" { -#ifdef __GNUC__ -_Pragma("GCC diagnostic push") -_Pragma("GCC diagnostic ignored \"-Wconversion\"") -_Pragma("GCC diagnostic ignored \"-Wold-style-cast\"") -#endif -#include "libavcodec/avcodec.h" -#include "libavformat/avformat.h" -#include "libavformat/avio.h" -#include "libavformat/version.h" -#include "libavutil/avutil.h" -#include "libavutil/error.h" -#include "libavutil/frame.h" -#include "libavutil/mem.h" -#include "libavutil/pixfmt.h" -#include "libavutil/rational.h" -#include "libavutil/samplefmt.h" -#include "libavutil/time.h" -#include "libavutil/version.h" -#include "libavutil/channel_layout.h" -#include "libswscale/swscale.h" -#include "libswresample/swresample.h" - -constexpr auto AVNoPtsValue = AV_NOPTS_VALUE; -constexpr auto AVErrorEOF = AVERROR_EOF; - -struct SwsContext; -#ifdef __GNUC__ -_Pragma("GCC diagnostic pop") -#endif -} - -#include "SDL.h" - -#include "AL/alc.h" -#include "AL/al.h" -#include "AL/alext.h" - -#include "common/alhelpers.h" - -extern "C" { -/* Undefine this to disable use of experimental extensions. Don't use for - * production code! Interfaces and behavior may change prior to being - * finalized. - */ -#define ALLOW_EXPERIMENTAL_EXTS - -#ifdef ALLOW_EXPERIMENTAL_EXTS -#ifndef AL_SOFT_callback_buffer -#define AL_SOFT_callback_buffer -typedef unsigned int ALbitfieldSOFT; -#define AL_BUFFER_CALLBACK_FUNCTION_SOFT 0x19A0 -#define AL_BUFFER_CALLBACK_USER_PARAM_SOFT 0x19A1 -typedef ALsizei (AL_APIENTRY*LPALBUFFERCALLBACKTYPESOFT)(ALvoid *userptr, ALvoid *sampledata, ALsizei numsamples); -typedef void (AL_APIENTRY*LPALBUFFERCALLBACKSOFT)(ALuint buffer, ALenum format, ALsizei freq, LPALBUFFERCALLBACKTYPESOFT callback, ALvoid *userptr, ALbitfieldSOFT flags); -typedef void (AL_APIENTRY*LPALGETBUFFERPTRSOFT)(ALuint buffer, ALenum param, ALvoid **value); -typedef void (AL_APIENTRY*LPALGETBUFFER3PTRSOFT)(ALuint buffer, ALenum param, ALvoid **value1, ALvoid **value2, ALvoid **value3); -typedef void (AL_APIENTRY*LPALGETBUFFERPTRVSOFT)(ALuint buffer, ALenum param, ALvoid **values); -#endif -#endif /* ALLOW_EXPERIMENTAL_EXTS */ -} - -namespace { - -inline constexpr int64_t operator "" _i64(unsigned long long int n) noexcept { return static_cast(n); } - -#ifndef M_PI -#define M_PI (3.14159265358979323846) -#endif - -using fixed32 = std::chrono::duration>; -using nanoseconds = std::chrono::nanoseconds; -using microseconds = std::chrono::microseconds; -using milliseconds = std::chrono::milliseconds; -using seconds = std::chrono::seconds; -using seconds_d64 = std::chrono::duration; -using std::chrono::duration_cast; - -const std::string AppName{"alffplay"}; - -ALenum DirectOutMode{AL_FALSE}; -bool EnableWideStereo{false}; -bool DisableVideo{false}; -LPALGETSOURCEI64VSOFT alGetSourcei64vSOFT; -LPALCGETINTEGER64VSOFT alcGetInteger64vSOFT; - -#ifdef AL_SOFT_events -LPALEVENTCONTROLSOFT alEventControlSOFT; -LPALEVENTCALLBACKSOFT alEventCallbackSOFT; -#endif - -#ifdef AL_SOFT_callback_buffer -LPALBUFFERCALLBACKSOFT alBufferCallbackSOFT; -#endif - -const seconds AVNoSyncThreshold{10}; - -#define VIDEO_PICTURE_QUEUE_SIZE 24 - -const seconds_d64 AudioSyncThreshold{0.03}; -const milliseconds AudioSampleCorrectionMax{50}; -/* Averaging filter coefficient for audio sync. */ -#define AUDIO_DIFF_AVG_NB 20 -const double AudioAvgFilterCoeff{std::pow(0.01, 1.0/AUDIO_DIFF_AVG_NB)}; -/* Per-buffer size, in time */ -constexpr milliseconds AudioBufferTime{20}; -/* Buffer total size, in time (should be divisible by the buffer time) */ -constexpr milliseconds AudioBufferTotalTime{800}; -constexpr auto AudioBufferCount = AudioBufferTotalTime / AudioBufferTime; - -enum { - FF_MOVIE_DONE_EVENT = SDL_USEREVENT -}; - -enum class SyncMaster { - Audio, - Video, - External, - - Default = External -}; - - -inline microseconds get_avtime() -{ return microseconds{av_gettime()}; } - -/* Define unique_ptrs to auto-cleanup associated ffmpeg objects. */ -struct AVIOContextDeleter { - void operator()(AVIOContext *ptr) { avio_closep(&ptr); } -}; -using AVIOContextPtr = std::unique_ptr; - -struct AVFormatCtxDeleter { - void operator()(AVFormatContext *ptr) { avformat_close_input(&ptr); } -}; -using AVFormatCtxPtr = std::unique_ptr; - -struct AVCodecCtxDeleter { - void operator()(AVCodecContext *ptr) { avcodec_free_context(&ptr); } -}; -using AVCodecCtxPtr = std::unique_ptr; - -struct AVFrameDeleter { - void operator()(AVFrame *ptr) { av_frame_free(&ptr); } -}; -using AVFramePtr = std::unique_ptr; - -struct SwrContextDeleter { - void operator()(SwrContext *ptr) { swr_free(&ptr); } -}; -using SwrContextPtr = std::unique_ptr; - -struct SwsContextDeleter { - void operator()(SwsContext *ptr) { sws_freeContext(ptr); } -}; -using SwsContextPtr = std::unique_ptr; - - -template -class PacketQueue { - std::mutex mMutex; - std::condition_variable mCondVar; - std::deque mPackets; - size_t mTotalSize{0}; - bool mFinished{false}; - - AVPacket *getPacket(std::unique_lock &lock) - { - while(mPackets.empty() && !mFinished) - mCondVar.wait(lock); - return mPackets.empty() ? nullptr : &mPackets.front(); - } - - void pop() - { - AVPacket *pkt = &mPackets.front(); - mTotalSize -= static_cast(pkt->size); - av_packet_unref(pkt); - mPackets.pop_front(); - } - -public: - ~PacketQueue() - { - for(AVPacket &pkt : mPackets) - av_packet_unref(&pkt); - mPackets.clear(); - mTotalSize = 0; - } - - int sendTo(AVCodecContext *codecctx) - { - std::unique_lock lock{mMutex}; - - AVPacket *pkt{getPacket(lock)}; - if(!pkt) return avcodec_send_packet(codecctx, nullptr); - - const int ret{avcodec_send_packet(codecctx, pkt)}; - if(ret != AVERROR(EAGAIN)) - { - if(ret < 0) - std::cerr<< "Failed to send packet: "< _{mMutex}; - mFinished = true; - } - mCondVar.notify_one(); - } - - bool put(const AVPacket *pkt) - { - { - std::unique_lock lock{mMutex}; - if(mTotalSize >= SizeLimit) - return false; - - mPackets.push_back(AVPacket{}); - if(av_packet_ref(&mPackets.back(), pkt) != 0) - { - mPackets.pop_back(); - return true; - } - - mTotalSize += static_cast(mPackets.back().size); - } - mCondVar.notify_one(); - return true; - } -}; - - -struct MovieState; - -struct AudioState { - MovieState &mMovie; - - AVStream *mStream{nullptr}; - AVCodecCtxPtr mCodecCtx; - - PacketQueue<2*1024*1024> mPackets; - - /* Used for clock difference average computation */ - seconds_d64 mClockDiffAvg{0}; - - /* Time of the next sample to be buffered */ - nanoseconds mCurrentPts{0}; - - /* Device clock time that the stream started at. */ - nanoseconds mDeviceStartTime{nanoseconds::min()}; - - /* Decompressed sample frame, and swresample context for conversion */ - AVFramePtr mDecodedFrame; - SwrContextPtr mSwresCtx; - - /* Conversion format, for what gets fed to OpenAL */ - uint64_t mDstChanLayout{0}; - AVSampleFormat mDstSampleFmt{AV_SAMPLE_FMT_NONE}; - - /* Storage of converted samples */ - uint8_t *mSamples{nullptr}; - int mSamplesLen{0}; /* In samples */ - int mSamplesPos{0}; - int mSamplesMax{0}; - - std::unique_ptr mBufferData; - size_t mBufferDataSize{0}; - std::atomic mReadPos{0}; - std::atomic mWritePos{0}; - - /* OpenAL format */ - ALenum mFormat{AL_NONE}; - ALuint mFrameSize{0}; - - std::mutex mSrcMutex; - std::condition_variable mSrcCond; - std::atomic_flag mConnected; - ALuint mSource{0}; - std::array mBuffers{}; - ALuint mBufferIdx{0}; - - AudioState(MovieState &movie) : mMovie(movie) - { mConnected.test_and_set(std::memory_order_relaxed); } - ~AudioState() - { - if(mSource) - alDeleteSources(1, &mSource); - if(mBuffers[0]) - alDeleteBuffers(static_cast(mBuffers.size()), mBuffers.data()); - - av_freep(&mSamples); - } - -#ifdef AL_SOFT_events - static void AL_APIENTRY EventCallback(ALenum eventType, ALuint object, ALuint param, - ALsizei length, const ALchar *message, void *userParam); -#endif -#ifdef AL_SOFT_callback_buffer - static ALsizei AL_APIENTRY bufferCallbackC(void *userptr, void *data, ALsizei size) - { return static_cast(userptr)->bufferCallback(data, size); } - ALsizei bufferCallback(void *data, ALsizei size); -#endif - - nanoseconds getClockNoLock(); - nanoseconds getClock() - { - std::lock_guard lock{mSrcMutex}; - return getClockNoLock(); - } - - bool startPlayback(); - - int getSync(); - int decodeFrame(); - bool readAudio(uint8_t *samples, unsigned int length, int &sample_skip); - void readAudio(int sample_skip); - - int handler(); -}; - -struct VideoState { - MovieState &mMovie; - - AVStream *mStream{nullptr}; - AVCodecCtxPtr mCodecCtx; - - PacketQueue<14*1024*1024> mPackets; - - /* The pts of the currently displayed frame, and the time (av_gettime) it - * was last updated - used to have running video pts - */ - nanoseconds mDisplayPts{0}; - microseconds mDisplayPtsTime{microseconds::min()}; - std::mutex mDispPtsMutex; - - /* Swscale context for format conversion */ - SwsContextPtr mSwscaleCtx; - - struct Picture { - AVFramePtr mFrame{}; - nanoseconds mPts{nanoseconds::min()}; - }; - std::array mPictQ; - std::atomic mPictQRead{0u}, mPictQWrite{1u}; - std::mutex mPictQMutex; - std::condition_variable mPictQCond; - - SDL_Texture *mImage{nullptr}; - int mWidth{0}, mHeight{0}; /* Logical image size (actual size may be larger) */ - bool mFirstUpdate{true}; - - std::atomic mEOS{false}; - std::atomic mFinalUpdate{false}; - - VideoState(MovieState &movie) : mMovie(movie) { } - ~VideoState() - { - if(mImage) - SDL_DestroyTexture(mImage); - mImage = nullptr; - } - - nanoseconds getClock(); - - void display(SDL_Window *screen, SDL_Renderer *renderer); - void updateVideo(SDL_Window *screen, SDL_Renderer *renderer, bool redraw); - int handler(); -}; - -struct MovieState { - AVIOContextPtr mIOContext; - AVFormatCtxPtr mFormatCtx; - - SyncMaster mAVSyncType{SyncMaster::Default}; - - microseconds mClockBase{microseconds::min()}; - - std::atomic mQuit{false}; - - AudioState mAudio; - VideoState mVideo; - - std::thread mParseThread; - std::thread mAudioThread; - std::thread mVideoThread; - - std::string mFilename; - - MovieState(std::string fname) - : mAudio(*this), mVideo(*this), mFilename(std::move(fname)) - { } - ~MovieState() - { - mQuit = true; - if(mParseThread.joinable()) - mParseThread.join(); - } - - static int decode_interrupt_cb(void *ctx); - bool prepare(); - void setTitle(SDL_Window *window); - - nanoseconds getClock(); - - nanoseconds getMasterClock(); - - nanoseconds getDuration(); - - int streamComponentOpen(unsigned int stream_index); - int parse_handler(); -}; - - -nanoseconds AudioState::getClockNoLock() -{ - // The audio clock is the timestamp of the sample currently being heard. - if(alcGetInteger64vSOFT) - { - // If device start time = min, we aren't playing yet. - if(mDeviceStartTime == nanoseconds::min()) - return nanoseconds::zero(); - - // Get the current device clock time and latency. - auto device = alcGetContextsDevice(alcGetCurrentContext()); - ALCint64SOFT devtimes[2]{0,0}; - alcGetInteger64vSOFT(device, ALC_DEVICE_CLOCK_LATENCY_SOFT, 2, devtimes); - auto latency = nanoseconds{devtimes[1]}; - auto device_time = nanoseconds{devtimes[0]}; - - // The clock is simply the current device time relative to the recorded - // start time. We can also subtract the latency to get more a accurate - // position of where the audio device actually is in the output stream. - return device_time - mDeviceStartTime - latency; - } - - if(mBufferDataSize > 0) - { - if(mDeviceStartTime == nanoseconds::min()) - return nanoseconds::zero(); - - /* With a callback buffer and no device clock, mDeviceStartTime is - * actually the timestamp of the first sample frame played. The audio - * clock, then, is that plus the current source offset. - */ - ALint64SOFT offset[2]; - if(alGetSourcei64vSOFT) - alGetSourcei64vSOFT(mSource, AL_SAMPLE_OFFSET_LATENCY_SOFT, offset); - else - { - ALint ioffset; - alGetSourcei(mSource, AL_SAMPLE_OFFSET, &ioffset); - offset[0] = ALint64SOFT{ioffset} << 32; - offset[1] = 0; - } - /* NOTE: The source state must be checked last, in case an underrun - * occurs and the source stops between getting the state and retrieving - * the offset+latency. - */ - ALint status; - alGetSourcei(mSource, AL_SOURCE_STATE, &status); - - nanoseconds pts{}; - if(status == AL_PLAYING || status == AL_PAUSED) - pts = mDeviceStartTime - nanoseconds{offset[1]} + - duration_cast(fixed32{offset[0] / mCodecCtx->sample_rate}); - else - { - /* If the source is stopped, the pts of the next sample to be heard - * is the pts of the next sample to be buffered, minus the amount - * already in the buffer ready to play. - */ - const size_t woffset{mWritePos.load(std::memory_order_acquire)}; - const size_t roffset{mReadPos.load(std::memory_order_relaxed)}; - const size_t readable{((woffset >= roffset) ? woffset : (mBufferDataSize+woffset)) - - roffset}; - - pts = mCurrentPts - nanoseconds{seconds{readable/mFrameSize}}/mCodecCtx->sample_rate; - } - - return pts; - } - - /* The source-based clock is based on 4 components: - * 1 - The timestamp of the next sample to buffer (mCurrentPts) - * 2 - The length of the source's buffer queue - * (AudioBufferTime*AL_BUFFERS_QUEUED) - * 3 - The offset OpenAL is currently at in the source (the first value - * from AL_SAMPLE_OFFSET_LATENCY_SOFT) - * 4 - The latency between OpenAL and the DAC (the second value from - * AL_SAMPLE_OFFSET_LATENCY_SOFT) - * - * Subtracting the length of the source queue from the next sample's - * timestamp gives the timestamp of the sample at the start of the source - * queue. Adding the source offset to that results in the timestamp for the - * sample at OpenAL's current position, and subtracting the source latency - * from that gives the timestamp of the sample currently at the DAC. - */ - nanoseconds pts{mCurrentPts}; - if(mSource) - { - ALint64SOFT offset[2]; - if(alGetSourcei64vSOFT) - alGetSourcei64vSOFT(mSource, AL_SAMPLE_OFFSET_LATENCY_SOFT, offset); - else - { - ALint ioffset; - alGetSourcei(mSource, AL_SAMPLE_OFFSET, &ioffset); - offset[0] = ALint64SOFT{ioffset} << 32; - offset[1] = 0; - } - ALint queued, status; - alGetSourcei(mSource, AL_BUFFERS_QUEUED, &queued); - alGetSourcei(mSource, AL_SOURCE_STATE, &status); - - /* If the source is AL_STOPPED, then there was an underrun and all - * buffers are processed, so ignore the source queue. The audio thread - * will put the source into an AL_INITIAL state and clear the queue - * when it starts recovery. - */ - if(status != AL_STOPPED) - { - pts -= AudioBufferTime*queued; - pts += duration_cast(fixed32{offset[0] / mCodecCtx->sample_rate}); - } - /* Don't offset by the latency if the source isn't playing. */ - if(status == AL_PLAYING) - pts -= nanoseconds{offset[1]}; - } - - return std::max(pts, nanoseconds::zero()); -} - -bool AudioState::startPlayback() -{ - const size_t woffset{mWritePos.load(std::memory_order_acquire)}; - const size_t roffset{mReadPos.load(std::memory_order_relaxed)}; - const size_t readable{((woffset >= roffset) ? woffset : (mBufferDataSize+woffset)) - - roffset}; - - if(mBufferDataSize > 0) - { - if(readable == 0) - return false; - if(!alcGetInteger64vSOFT) - mDeviceStartTime = mCurrentPts - - nanoseconds{seconds{readable/mFrameSize}}/mCodecCtx->sample_rate; - } - else - { - ALint queued{}; - alGetSourcei(mSource, AL_BUFFERS_QUEUED, &queued); - if(queued == 0) return false; - } - - alSourcePlay(mSource); - if(alcGetInteger64vSOFT) - { - /* Subtract the total buffer queue time from the current pts to get the - * pts of the start of the queue. - */ - int64_t srctimes[2]{0,0}; - alGetSourcei64vSOFT(mSource, AL_SAMPLE_OFFSET_CLOCK_SOFT, srctimes); - auto device_time = nanoseconds{srctimes[1]}; - auto src_offset = duration_cast(fixed32{srctimes[0]}) / - mCodecCtx->sample_rate; - - /* The mixer may have ticked and incremented the device time and sample - * offset, so subtract the source offset from the device time to get - * the device time the source started at. Also subtract startpts to get - * the device time the stream would have started at to reach where it - * is now. - */ - if(mBufferDataSize > 0) - { - nanoseconds startpts{mCurrentPts - - nanoseconds{seconds{readable/mFrameSize}}/mCodecCtx->sample_rate}; - mDeviceStartTime = device_time - src_offset - startpts; - } - else - { - nanoseconds startpts{mCurrentPts - AudioBufferTotalTime}; - mDeviceStartTime = device_time - src_offset - startpts; - } - } - return true; -} - -int AudioState::getSync() -{ - if(mMovie.mAVSyncType == SyncMaster::Audio) - return 0; - - auto ref_clock = mMovie.getMasterClock(); - auto diff = ref_clock - getClockNoLock(); - - if(!(diff < AVNoSyncThreshold && diff > -AVNoSyncThreshold)) - { - /* Difference is TOO big; reset accumulated average */ - mClockDiffAvg = seconds_d64::zero(); - return 0; - } - - /* Accumulate the diffs */ - mClockDiffAvg = mClockDiffAvg*AudioAvgFilterCoeff + diff; - auto avg_diff = mClockDiffAvg*(1.0 - AudioAvgFilterCoeff); - if(avg_diff < AudioSyncThreshold/2.0 && avg_diff > -AudioSyncThreshold) - return 0; - - /* Constrain the per-update difference to avoid exceedingly large skips */ - diff = std::min(diff, AudioSampleCorrectionMax); - return static_cast(duration_cast(diff*mCodecCtx->sample_rate).count()); -} - -int AudioState::decodeFrame() -{ - while(!mMovie.mQuit.load(std::memory_order_relaxed)) - { - int ret; - while((ret=avcodec_receive_frame(mCodecCtx.get(), mDecodedFrame.get())) == AVERROR(EAGAIN)) - mPackets.sendTo(mCodecCtx.get()); - if(ret != 0) - { - if(ret == AVErrorEOF) break; - std::cerr<< "Failed to receive frame: "<nb_samples <= 0) - continue; - - /* If provided, update w/ pts */ - if(mDecodedFrame->best_effort_timestamp != AVNoPtsValue) - mCurrentPts = duration_cast(seconds_d64{av_q2d(mStream->time_base) * - static_cast(mDecodedFrame->best_effort_timestamp)}); - - if(mDecodedFrame->nb_samples > mSamplesMax) - { - av_freep(&mSamples); - av_samples_alloc(&mSamples, nullptr, mCodecCtx->channels, mDecodedFrame->nb_samples, - mDstSampleFmt, 0); - mSamplesMax = mDecodedFrame->nb_samples; - } - /* Return the amount of sample frames converted */ - int data_size{swr_convert(mSwresCtx.get(), &mSamples, mDecodedFrame->nb_samples, - const_cast(mDecodedFrame->data), mDecodedFrame->nb_samples)}; - - av_frame_unref(mDecodedFrame.get()); - return data_size; - } - - return 0; -} - -/* Duplicates the sample at in to out, count times. The frame size is a - * multiple of the template type size. - */ -template -static void sample_dup(uint8_t *out, const uint8_t *in, size_t count, size_t frame_size) -{ - auto *sample = reinterpret_cast(in); - auto *dst = reinterpret_cast(out); - if(frame_size == sizeof(T)) - std::fill_n(dst, count, *sample); - else - { - /* NOTE: frame_size is a multiple of sizeof(T). */ - size_t type_mult{frame_size / sizeof(T)}; - size_t i{0}; - std::generate_n(dst, count*type_mult, - [sample,type_mult,&i]() -> T - { - T ret = sample[i]; - i = (i+1)%type_mult; - return ret; - } - ); - } -} - - -bool AudioState::readAudio(uint8_t *samples, unsigned int length, int &sample_skip) -{ - unsigned int audio_size{0}; - - /* Read the next chunk of data, refill the buffer, and queue it - * on the source */ - length /= mFrameSize; - while(mSamplesLen > 0 && audio_size < length) - { - unsigned int rem{length - audio_size}; - if(mSamplesPos >= 0) - { - const auto len = static_cast(mSamplesLen - mSamplesPos); - if(rem > len) rem = len; - std::copy_n(mSamples + static_cast(mSamplesPos)*mFrameSize, - rem*mFrameSize, samples); - } - else - { - rem = std::min(rem, static_cast(-mSamplesPos)); - - /* Add samples by copying the first sample */ - if((mFrameSize&7) == 0) - sample_dup(samples, mSamples, rem, mFrameSize); - else if((mFrameSize&3) == 0) - sample_dup(samples, mSamples, rem, mFrameSize); - else if((mFrameSize&1) == 0) - sample_dup(samples, mSamples, rem, mFrameSize); - else - sample_dup(samples, mSamples, rem, mFrameSize); - } - - mSamplesPos += rem; - mCurrentPts += nanoseconds{seconds{rem}} / mCodecCtx->sample_rate; - samples += rem*mFrameSize; - audio_size += rem; - - while(mSamplesPos >= mSamplesLen) - { - int frame_len = decodeFrame(); - if(frame_len <= 0) break; - - mSamplesLen = frame_len; - mSamplesPos = std::min(mSamplesLen, sample_skip); - sample_skip -= mSamplesPos; - - // Adjust the device start time and current pts by the amount we're - // skipping/duplicating, so that the clock remains correct for the - // current stream position. - auto skip = nanoseconds{seconds{mSamplesPos}} / mCodecCtx->sample_rate; - mDeviceStartTime -= skip; - mCurrentPts += skip; - continue; - } - } - if(audio_size <= 0) - return false; - - if(audio_size < length) - { - const unsigned int rem{length - audio_size}; - std::fill_n(samples, rem*mFrameSize, - (mDstSampleFmt == AV_SAMPLE_FMT_U8) ? 0x80 : 0x00); - mCurrentPts += nanoseconds{seconds{rem}} / mCodecCtx->sample_rate; - audio_size += rem; - } - return true; -} - -void AudioState::readAudio(int sample_skip) -{ - size_t woffset{mWritePos.load(std::memory_order_acquire)}; - while(mSamplesLen > 0) - { - const size_t roffset{mReadPos.load(std::memory_order_relaxed)}; - - if(mSamplesPos < 0) - { - size_t rem{(((roffset > woffset) ? roffset-1 - : ((roffset == 0) ? mBufferDataSize-1 - : mBufferDataSize)) - woffset) / mFrameSize}; - rem = std::min(rem, static_cast(-mSamplesPos)); - if(rem == 0) break; - - auto *splout{&mBufferData[woffset]}; - if((mFrameSize&7) == 0) - sample_dup(splout, mSamples, rem, mFrameSize); - else if((mFrameSize&3) == 0) - sample_dup(splout, mSamples, rem, mFrameSize); - else if((mFrameSize&1) == 0) - sample_dup(splout, mSamples, rem, mFrameSize); - else - sample_dup(splout, mSamples, rem, mFrameSize); - woffset += rem * mFrameSize; - if(woffset == mBufferDataSize) - woffset = 0; - mWritePos.store(woffset, std::memory_order_release); - mSamplesPos += static_cast(rem); - mCurrentPts += nanoseconds{seconds{rem}} / mCodecCtx->sample_rate; - continue; - } - - const size_t boffset{static_cast(mSamplesPos) * size_t{mFrameSize}}; - const size_t nbytes{static_cast(mSamplesLen)*size_t{mFrameSize} - - boffset}; - if(roffset > woffset) - { - const size_t writable{roffset-woffset-1}; - if(writable < nbytes) break; - - memcpy(&mBufferData[woffset], mSamples+boffset, nbytes); - woffset += nbytes; - } - else - { - const size_t writable{mBufferDataSize+roffset-woffset-1}; - if(writable < nbytes) break; - - const size_t todo1{std::min(nbytes, mBufferDataSize-woffset)}; - const size_t todo2{nbytes - todo1}; - - memcpy(&mBufferData[woffset], mSamples+boffset, todo1); - woffset += todo1; - if(woffset == mBufferDataSize) - { - woffset = 0; - if(todo2 > 0) - { - memcpy(&mBufferData[woffset], mSamples+boffset+todo1, todo2); - woffset += todo2; - } - } - } - mWritePos.store(woffset, std::memory_order_release); - mCurrentPts += nanoseconds{seconds{mSamplesLen-mSamplesPos}} / mCodecCtx->sample_rate; - - do { - mSamplesLen = decodeFrame(); - if(mSamplesLen <= 0) break; - - mSamplesPos = std::min(mSamplesLen, sample_skip); - sample_skip -= mSamplesPos; - - auto skip = nanoseconds{seconds{mSamplesPos}} / mCodecCtx->sample_rate; - mDeviceStartTime -= skip; - mCurrentPts += skip; - } while(mSamplesPos >= mSamplesLen); - } -} - - -#ifdef AL_SOFT_events -void AL_APIENTRY AudioState::EventCallback(ALenum eventType, ALuint object, ALuint param, - ALsizei length, const ALchar *message, void *userParam) -{ - auto self = static_cast(userParam); - - if(eventType == AL_EVENT_TYPE_BUFFER_COMPLETED_SOFT) - { - /* Temporarily lock the source mutex to ensure it's not between - * checking the processed count and going to sleep. - */ - std::unique_lock{self->mSrcMutex}.unlock(); - self->mSrcCond.notify_one(); - return; - } - - std::cout<< "\n---- AL Event on AudioState "<(length)}<<"\n----"<< - std::endl; - - if(eventType == AL_EVENT_TYPE_DISCONNECTED_SOFT) - { - { - std::lock_guard lock{self->mSrcMutex}; - self->mConnected.clear(std::memory_order_release); - } - self->mSrcCond.notify_one(); - } -} -#endif - -#ifdef AL_SOFT_callback_buffer -ALsizei AudioState::bufferCallback(void *data, ALsizei size) -{ - ALsizei got{0}; - - size_t roffset{mReadPos.load(std::memory_order_acquire)}; - while(got < size) - { - const size_t woffset{mWritePos.load(std::memory_order_relaxed)}; - if(woffset == roffset) break; - - size_t todo{((woffset < roffset) ? mBufferDataSize : woffset) - roffset}; - todo = std::min(todo, static_cast(size-got)); - - memcpy(data, &mBufferData[roffset], todo); - data = static_cast(data) + todo; - got += static_cast(todo); - - roffset += todo; - if(roffset == mBufferDataSize) - roffset = 0; - } - mReadPos.store(roffset, std::memory_order_release); - - return got; -} -#endif - -int AudioState::handler() -{ - std::unique_lock srclock{mSrcMutex, std::defer_lock}; - milliseconds sleep_time{AudioBufferTime / 3}; - ALenum fmt; - -#ifdef AL_SOFT_events - const std::array evt_types{{ - AL_EVENT_TYPE_BUFFER_COMPLETED_SOFT, AL_EVENT_TYPE_SOURCE_STATE_CHANGED_SOFT, - AL_EVENT_TYPE_DISCONNECTED_SOFT}}; - if(alEventControlSOFT) - { - alEventControlSOFT(evt_types.size(), evt_types.data(), AL_TRUE); - alEventCallbackSOFT(EventCallback, this); - sleep_time = AudioBufferTotalTime; - } -#endif -#ifdef AL_SOFT_bformat_ex - const bool has_bfmt_ex{alIsExtensionPresent("AL_SOFT_bformat_ex") != AL_FALSE}; - ALenum ambi_layout{AL_FUMA_SOFT}; - ALenum ambi_scale{AL_FUMA_SOFT}; -#endif - - /* Find a suitable format for OpenAL. */ - mDstChanLayout = 0; - mFormat = AL_NONE; - if((mCodecCtx->sample_fmt == AV_SAMPLE_FMT_FLT || mCodecCtx->sample_fmt == AV_SAMPLE_FMT_FLTP) && - alIsExtensionPresent("AL_EXT_FLOAT32")) - { - mDstSampleFmt = AV_SAMPLE_FMT_FLT; - mFrameSize = 4; - if(mCodecCtx->channel_layout == AV_CH_LAYOUT_7POINT1 && - alIsExtensionPresent("AL_EXT_MCFORMATS") && - (fmt=alGetEnumValue("AL_FORMAT_71CHN32")) != AL_NONE && fmt != -1) - { - mDstChanLayout = mCodecCtx->channel_layout; - mFrameSize *= 8; - mFormat = fmt; - } - if((mCodecCtx->channel_layout == AV_CH_LAYOUT_5POINT1 || - mCodecCtx->channel_layout == AV_CH_LAYOUT_5POINT1_BACK) && - alIsExtensionPresent("AL_EXT_MCFORMATS") && - (fmt=alGetEnumValue("AL_FORMAT_51CHN32")) != AL_NONE && fmt != -1) - { - mDstChanLayout = mCodecCtx->channel_layout; - mFrameSize *= 6; - mFormat = fmt; - } - if(mCodecCtx->channel_layout == AV_CH_LAYOUT_MONO) - { - mDstChanLayout = mCodecCtx->channel_layout; - mFrameSize *= 1; - mFormat = AL_FORMAT_MONO_FLOAT32; - } - /* Assume 3D B-Format (ambisonics) if the channel layout is blank and - * there's 4 or more channels. FFmpeg/libavcodec otherwise seems to - * have no way to specify if the source is actually B-Format (let alone - * if it's 2D or 3D). - */ - if(mCodecCtx->channel_layout == 0 && mCodecCtx->channels >= 4 && - alIsExtensionPresent("AL_EXT_BFORMAT") && - (fmt=alGetEnumValue("AL_FORMAT_BFORMAT3D_FLOAT32")) != AL_NONE && fmt != -1) - { - int order{static_cast(std::sqrt(mCodecCtx->channels)) - 1}; - if((order+1)*(order+1) == mCodecCtx->channels || - (order+1)*(order+1) + 2 == mCodecCtx->channels) - { - /* OpenAL only supports first-order with AL_EXT_BFORMAT, which - * is 4 channels for 3D buffers. - */ - mFrameSize *= 4; - mFormat = fmt; - } - } - if(!mFormat) - { - mDstChanLayout = AV_CH_LAYOUT_STEREO; - mFrameSize *= 2; - mFormat = AL_FORMAT_STEREO_FLOAT32; - } - } - if(mCodecCtx->sample_fmt == AV_SAMPLE_FMT_U8 || mCodecCtx->sample_fmt == AV_SAMPLE_FMT_U8P) - { - mDstSampleFmt = AV_SAMPLE_FMT_U8; - mFrameSize = 1; - if(mCodecCtx->channel_layout == AV_CH_LAYOUT_7POINT1 && - alIsExtensionPresent("AL_EXT_MCFORMATS") && - (fmt=alGetEnumValue("AL_FORMAT_71CHN8")) != AL_NONE && fmt != -1) - { - mDstChanLayout = mCodecCtx->channel_layout; - mFrameSize *= 8; - mFormat = fmt; - } - if((mCodecCtx->channel_layout == AV_CH_LAYOUT_5POINT1 || - mCodecCtx->channel_layout == AV_CH_LAYOUT_5POINT1_BACK) && - alIsExtensionPresent("AL_EXT_MCFORMATS") && - (fmt=alGetEnumValue("AL_FORMAT_51CHN8")) != AL_NONE && fmt != -1) - { - mDstChanLayout = mCodecCtx->channel_layout; - mFrameSize *= 6; - mFormat = fmt; - } - if(mCodecCtx->channel_layout == AV_CH_LAYOUT_MONO) - { - mDstChanLayout = mCodecCtx->channel_layout; - mFrameSize *= 1; - mFormat = AL_FORMAT_MONO8; - } - if(mCodecCtx->channel_layout == 0 && mCodecCtx->channels >= 4 && - alIsExtensionPresent("AL_EXT_BFORMAT") && - (fmt=alGetEnumValue("AL_FORMAT_BFORMAT3D8")) != AL_NONE && fmt != -1) - { - int order{static_cast(std::sqrt(mCodecCtx->channels)) - 1}; - if((order+1)*(order+1) == mCodecCtx->channels || - (order+1)*(order+1) + 2 == mCodecCtx->channels) - { - mFrameSize *= 4; - mFormat = fmt; - } - } - if(!mFormat) - { - mDstChanLayout = AV_CH_LAYOUT_STEREO; - mFrameSize *= 2; - mFormat = AL_FORMAT_STEREO8; - } - } - if(!mFormat) - { - mDstSampleFmt = AV_SAMPLE_FMT_S16; - mFrameSize = 2; - if(mCodecCtx->channel_layout == AV_CH_LAYOUT_7POINT1 && - alIsExtensionPresent("AL_EXT_MCFORMATS") && - (fmt=alGetEnumValue("AL_FORMAT_71CHN16")) != AL_NONE && fmt != -1) - { - mDstChanLayout = mCodecCtx->channel_layout; - mFrameSize *= 8; - mFormat = fmt; - } - if((mCodecCtx->channel_layout == AV_CH_LAYOUT_5POINT1 || - mCodecCtx->channel_layout == AV_CH_LAYOUT_5POINT1_BACK) && - alIsExtensionPresent("AL_EXT_MCFORMATS") && - (fmt=alGetEnumValue("AL_FORMAT_51CHN16")) != AL_NONE && fmt != -1) - { - mDstChanLayout = mCodecCtx->channel_layout; - mFrameSize *= 6; - mFormat = fmt; - } - if(mCodecCtx->channel_layout == AV_CH_LAYOUT_MONO) - { - mDstChanLayout = mCodecCtx->channel_layout; - mFrameSize *= 1; - mFormat = AL_FORMAT_MONO16; - } - if(mCodecCtx->channel_layout == 0 && mCodecCtx->channels >= 4 && - alIsExtensionPresent("AL_EXT_BFORMAT") && - (fmt=alGetEnumValue("AL_FORMAT_BFORMAT3D16")) != AL_NONE && fmt != -1) - { - int order{static_cast(std::sqrt(mCodecCtx->channels)) - 1}; - if((order+1)*(order+1) == mCodecCtx->channels || - (order+1)*(order+1) + 2 == mCodecCtx->channels) - { - mFrameSize *= 4; - mFormat = fmt; - } - } - if(!mFormat) - { - mDstChanLayout = AV_CH_LAYOUT_STEREO; - mFrameSize *= 2; - mFormat = AL_FORMAT_STEREO16; - } - } - void *samples{nullptr}; - ALsizei buffer_len{0}; - - mSamples = nullptr; - mSamplesMax = 0; - mSamplesPos = 0; - mSamplesLen = 0; - - mDecodedFrame.reset(av_frame_alloc()); - if(!mDecodedFrame) - { - std::cerr<< "Failed to allocate audio frame" <sample_rate, - (1_i64<channels)-1, mCodecCtx->sample_fmt, mCodecCtx->sample_rate, - 0, nullptr)); - - /* Note that ffmpeg/libavcodec has no method to check the ambisonic - * channel order and normalization, so we can only assume AmbiX as the - * defacto-standard. This is not true for .amb files, which use FuMa. - */ - std::vector mtx(64*64, 0.0); -#ifdef AL_SOFT_bformat_ex - ambi_layout = AL_ACN_SOFT; - ambi_scale = AL_SN3D_SOFT; - if(has_bfmt_ex) - { - /* An identity matrix that doesn't remix any channels. */ - std::cout<< "Found AL_SOFT_bformat_ex" <(mDstChanLayout), mDstSampleFmt, mCodecCtx->sample_rate, - mCodecCtx->channel_layout ? static_cast(mCodecCtx->channel_layout) - : av_get_default_channel_layout(mCodecCtx->channels), - mCodecCtx->sample_fmt, mCodecCtx->sample_rate, - 0, nullptr)); - if(!mSwresCtx || swr_init(mSwresCtx.get()) != 0) - { - std::cerr<< "Failed to initialize audio converter" <(mBuffers.size()), mBuffers.data()); - alGenSources(1, &mSource); - - if(DirectOutMode) - alSourcei(mSource, AL_DIRECT_CHANNELS_SOFT, DirectOutMode); - if(EnableWideStereo) - { - const float angles[2]{static_cast(M_PI / 3.0), static_cast(-M_PI / 3.0)}; - alSourcefv(mSource, AL_STEREO_ANGLES, angles); - } -#ifdef AL_SOFT_bformat_ex - if(has_bfmt_ex) - { - for(ALuint bufid : mBuffers) - { - alBufferi(bufid, AL_AMBISONIC_LAYOUT_SOFT, ambi_layout); - alBufferi(bufid, AL_AMBISONIC_SCALING_SOFT, ambi_scale); - } - } -#endif - - if(alGetError() != AL_NO_ERROR) - goto finish; - -#ifdef AL_SOFT_callback_buffer - if(alBufferCallbackSOFT) - { - alBufferCallbackSOFT(mBuffers[0], mFormat, mCodecCtx->sample_rate, bufferCallbackC, this, - 0); - alSourcei(mSource, AL_BUFFER, static_cast(mBuffers[0])); - if(alGetError() != AL_NO_ERROR) - { - fprintf(stderr, "Failed to set buffer callback\n"); - alSourcei(mSource, AL_BUFFER, 0); - buffer_len = static_cast(duration_cast(mCodecCtx->sample_rate * - AudioBufferTime).count() * mFrameSize); - } - else - { - mBufferDataSize = static_cast(duration_cast(mCodecCtx->sample_rate * - AudioBufferTotalTime).count()) * mFrameSize; - mBufferData.reset(new uint8_t[mBufferDataSize]); - mReadPos.store(0, std::memory_order_relaxed); - mWritePos.store(0, std::memory_order_relaxed); - - ALCint refresh{}; - alcGetIntegerv(alcGetContextsDevice(alcGetCurrentContext()), ALC_REFRESH, 1, &refresh); - sleep_time = milliseconds{seconds{1}} / refresh; - } - } - else -#endif - buffer_len = static_cast(duration_cast(mCodecCtx->sample_rate * - AudioBufferTime).count() * mFrameSize); - if(buffer_len > 0) - samples = av_malloc(static_cast(buffer_len)); - - /* Prefill the codec buffer. */ - do { - const int ret{mPackets.sendTo(mCodecCtx.get())}; - if(ret == AVERROR(EAGAIN) || ret == AVErrorEOF) - break; - } while(1); - - srclock.lock(); - if(alcGetInteger64vSOFT) - { - int64_t devtime{}; - alcGetInteger64vSOFT(alcGetContextsDevice(alcGetCurrentContext()), ALC_DEVICE_CLOCK_SOFT, - 1, &devtime); - mDeviceStartTime = nanoseconds{devtime} - mCurrentPts; - } - - mSamplesLen = decodeFrame(); - if(mSamplesLen > 0) - { - mSamplesPos = std::min(mSamplesLen, getSync()); - - auto skip = nanoseconds{seconds{mSamplesPos}} / mCodecCtx->sample_rate; - mDeviceStartTime -= skip; - mCurrentPts += skip; - } - - while(!mMovie.mQuit.load(std::memory_order_relaxed) - && mConnected.test_and_set(std::memory_order_relaxed)) - { - ALenum state; - if(mBufferDataSize > 0) - { - alGetSourcei(mSource, AL_SOURCE_STATE, &state); - readAudio(getSync()); - } - else - { - ALint processed, queued; - - /* First remove any processed buffers. */ - alGetSourcei(mSource, AL_BUFFERS_PROCESSED, &processed); - while(processed > 0) - { - ALuint bid; - alSourceUnqueueBuffers(mSource, 1, &bid); - --processed; - } - - /* Refill the buffer queue. */ - int sync_skip{getSync()}; - alGetSourcei(mSource, AL_BUFFERS_QUEUED, &queued); - while(static_cast(queued) < mBuffers.size()) - { - /* Read the next chunk of data, filling the buffer, and queue - * it on the source. - */ - const bool got_audio{readAudio(static_cast(samples), - static_cast(buffer_len), sync_skip)}; - if(!got_audio) break; - - const ALuint bufid{mBuffers[mBufferIdx]}; - mBufferIdx = static_cast((mBufferIdx+1) % mBuffers.size()); - - alBufferData(bufid, mFormat, samples, buffer_len, mCodecCtx->sample_rate); - alSourceQueueBuffers(mSource, 1, &bufid); - ++queued; - } - - /* Check that the source is playing. */ - alGetSourcei(mSource, AL_SOURCE_STATE, &state); - if(state == AL_STOPPED) - { - /* AL_STOPPED means there was an underrun. Clear the buffer - * queue since this likely means we're late, and rewind the - * source to get it back into an AL_INITIAL state. - */ - alSourceRewind(mSource); - alSourcei(mSource, AL_BUFFER, 0); - if(alcGetInteger64vSOFT) - { - /* Also update the device start time with the current - * device clock, so the decoder knows we're running behind. - */ - int64_t devtime{}; - alcGetInteger64vSOFT(alcGetContextsDevice(alcGetCurrentContext()), - ALC_DEVICE_CLOCK_SOFT, 1, &devtime); - mDeviceStartTime = nanoseconds{devtime} - mCurrentPts; - } - continue; - } - } - - /* (re)start the source if needed, and wait for a buffer to finish */ - if(state != AL_PLAYING && state != AL_PAUSED) - { - if(!startPlayback()) - break; - } - if(alGetError() != AL_NO_ERROR) - return false; - - mSrcCond.wait_for(srclock, sleep_time); - } - - alSourceRewind(mSource); - alSourcei(mSource, AL_BUFFER, 0); - srclock.unlock(); - -finish: - av_freep(&samples); - -#ifdef AL_SOFT_events - if(alEventControlSOFT) - { - alEventControlSOFT(evt_types.size(), evt_types.data(), AL_FALSE); - alEventCallbackSOFT(nullptr, nullptr); - } -#endif - - return 0; -} - - -nanoseconds VideoState::getClock() -{ - /* NOTE: This returns incorrect times while not playing. */ - std::lock_guard _{mDispPtsMutex}; - if(mDisplayPtsTime == microseconds::min()) - return nanoseconds::zero(); - auto delta = get_avtime() - mDisplayPtsTime; - return mDisplayPts + delta; -} - -/* Called by VideoState::updateVideo to display the next video frame. */ -void VideoState::display(SDL_Window *screen, SDL_Renderer *renderer) -{ - if(!mImage) - return; - - double aspect_ratio; - int win_w, win_h; - int w, h, x, y; - - if(mCodecCtx->sample_aspect_ratio.num == 0) - aspect_ratio = 0.0; - else - { - aspect_ratio = av_q2d(mCodecCtx->sample_aspect_ratio) * mCodecCtx->width / - mCodecCtx->height; - } - if(aspect_ratio <= 0.0) - aspect_ratio = static_cast(mCodecCtx->width) / mCodecCtx->height; - - SDL_GetWindowSize(screen, &win_w, &win_h); - h = win_h; - w = (static_cast(std::rint(h * aspect_ratio)) + 3) & ~3; - if(w > win_w) - { - w = win_w; - h = (static_cast(std::rint(w / aspect_ratio)) + 3) & ~3; - } - x = (win_w - w) / 2; - y = (win_h - h) / 2; - - SDL_Rect src_rect{ 0, 0, mWidth, mHeight }; - SDL_Rect dst_rect{ x, y, w, h }; - SDL_RenderCopy(renderer, mImage, &src_rect, &dst_rect); - SDL_RenderPresent(renderer); -} - -/* Called regularly on the main thread where the SDL_Renderer was created. It - * handles updating the textures of decoded frames and displaying the latest - * frame. - */ -void VideoState::updateVideo(SDL_Window *screen, SDL_Renderer *renderer, bool redraw) -{ - size_t read_idx{mPictQRead.load(std::memory_order_relaxed)}; - Picture *vp{&mPictQ[read_idx]}; - - auto clocktime = mMovie.getMasterClock(); - bool updated{false}; - while(1) - { - size_t next_idx{(read_idx+1)%mPictQ.size()}; - if(next_idx == mPictQWrite.load(std::memory_order_acquire)) - break; - Picture *nextvp{&mPictQ[next_idx]}; - if(clocktime < nextvp->mPts) - break; - - vp = nextvp; - updated = true; - read_idx = next_idx; - } - if(mMovie.mQuit.load(std::memory_order_relaxed)) - { - if(mEOS) - mFinalUpdate = true; - mPictQRead.store(read_idx, std::memory_order_release); - std::unique_lock{mPictQMutex}.unlock(); - mPictQCond.notify_one(); - return; - } - - if(updated) - { - mPictQRead.store(read_idx, std::memory_order_release); - std::unique_lock{mPictQMutex}.unlock(); - mPictQCond.notify_one(); - - /* allocate or resize the buffer! */ - bool fmt_updated{false}; - if(!mImage || mWidth != mCodecCtx->width || mHeight != mCodecCtx->height) - { - fmt_updated = true; - if(mImage) - SDL_DestroyTexture(mImage); - mImage = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_IYUV, SDL_TEXTUREACCESS_STREAMING, - mCodecCtx->coded_width, mCodecCtx->coded_height); - if(!mImage) - std::cerr<< "Failed to create YV12 texture!" <width; - mHeight = mCodecCtx->height; - - if(mFirstUpdate && mWidth > 0 && mHeight > 0) - { - /* For the first update, set the window size to the video size. */ - mFirstUpdate = false; - - int w{mWidth}; - int h{mHeight}; - if(mCodecCtx->sample_aspect_ratio.den != 0) - { - double aspect_ratio = av_q2d(mCodecCtx->sample_aspect_ratio); - if(aspect_ratio >= 1.0) - w = static_cast(w*aspect_ratio + 0.5); - else if(aspect_ratio > 0.0) - h = static_cast(h/aspect_ratio + 0.5); - } - SDL_SetWindowSize(screen, w, h); - } - } - - if(mImage) - { - AVFrame *frame{vp->mFrame.get()}; - void *pixels{nullptr}; - int pitch{0}; - - if(mCodecCtx->pix_fmt == AV_PIX_FMT_YUV420P) - SDL_UpdateYUVTexture(mImage, nullptr, - frame->data[0], frame->linesize[0], - frame->data[1], frame->linesize[1], - frame->data[2], frame->linesize[2] - ); - else if(SDL_LockTexture(mImage, nullptr, &pixels, &pitch) != 0) - std::cerr<< "Failed to lock texture" <coded_width}; - int coded_h{mCodecCtx->coded_height}; - int w{mCodecCtx->width}; - int h{mCodecCtx->height}; - if(!mSwscaleCtx || fmt_updated) - { - mSwscaleCtx.reset(sws_getContext( - w, h, mCodecCtx->pix_fmt, - w, h, AV_PIX_FMT_YUV420P, 0, - nullptr, nullptr, nullptr - )); - } - - /* point pict at the queue */ - uint8_t *pict_data[3]; - pict_data[0] = static_cast(pixels); - pict_data[1] = pict_data[0] + coded_w*coded_h; - pict_data[2] = pict_data[1] + coded_w*coded_h/4; - - int pict_linesize[3]; - pict_linesize[0] = pitch; - pict_linesize[1] = pitch / 2; - pict_linesize[2] = pitch / 2; - - sws_scale(mSwscaleCtx.get(), reinterpret_cast(frame->data), frame->linesize, - 0, h, pict_data, pict_linesize); - SDL_UnlockTexture(mImage); - } - } - - redraw = true; - } - - if(redraw) - { - /* Show the picture! */ - display(screen, renderer); - } - - if(updated) - { - auto disp_time = get_avtime(); - - std::lock_guard _{mDispPtsMutex}; - mDisplayPts = vp->mPts; - mDisplayPtsTime = disp_time; - } - if(mEOS.load(std::memory_order_acquire)) - { - if((read_idx+1)%mPictQ.size() == mPictQWrite.load(std::memory_order_acquire)) - { - mFinalUpdate = true; - std::unique_lock{mPictQMutex}.unlock(); - mPictQCond.notify_one(); - } - } -} - -int VideoState::handler() -{ - std::for_each(mPictQ.begin(), mPictQ.end(), - [](Picture &pict) -> void - { pict.mFrame = AVFramePtr{av_frame_alloc()}; }); - - /* Prefill the codec buffer. */ - do { - const int ret{mPackets.sendTo(mCodecCtx.get())}; - if(ret == AVERROR(EAGAIN) || ret == AVErrorEOF) - break; - } while(1); - - { - std::lock_guard _{mDispPtsMutex}; - mDisplayPtsTime = get_avtime(); - } - - auto current_pts = nanoseconds::zero(); - while(!mMovie.mQuit.load(std::memory_order_relaxed)) - { - size_t write_idx{mPictQWrite.load(std::memory_order_relaxed)}; - Picture *vp{&mPictQ[write_idx]}; - - /* Retrieve video frame. */ - AVFrame *decoded_frame{vp->mFrame.get()}; - int ret; - while((ret=avcodec_receive_frame(mCodecCtx.get(), decoded_frame)) == AVERROR(EAGAIN)) - mPackets.sendTo(mCodecCtx.get()); - if(ret != 0) - { - if(ret == AVErrorEOF) break; - std::cerr<< "Failed to receive frame: "<best_effort_timestamp != AVNoPtsValue) - current_pts = duration_cast(seconds_d64{av_q2d(mStream->time_base) * - static_cast(decoded_frame->best_effort_timestamp)}); - vp->mPts = current_pts; - - /* Update the video clock to the next expected PTS. */ - auto frame_delay = av_q2d(mCodecCtx->time_base); - frame_delay += decoded_frame->repeat_pict * (frame_delay * 0.5); - current_pts += duration_cast(seconds_d64{frame_delay}); - - /* Put the frame in the queue to be loaded into a texture and displayed - * by the rendering thread. - */ - write_idx = (write_idx+1)%mPictQ.size(); - mPictQWrite.store(write_idx, std::memory_order_release); - - /* Send a packet now so it's hopefully ready by the time it's needed. */ - mPackets.sendTo(mCodecCtx.get()); - - if(write_idx == mPictQRead.load(std::memory_order_acquire)) - { - /* Wait until we have space for a new pic */ - std::unique_lock lock{mPictQMutex}; - while(write_idx == mPictQRead.load(std::memory_order_acquire) && - !mMovie.mQuit.load(std::memory_order_relaxed)) - mPictQCond.wait(lock); - } - } - mEOS = true; - - std::unique_lock lock{mPictQMutex}; - while(!mFinalUpdate) mPictQCond.wait(lock); - - return 0; -} - - -int MovieState::decode_interrupt_cb(void *ctx) -{ - return static_cast(ctx)->mQuit.load(std::memory_order_relaxed); -} - -bool MovieState::prepare() -{ - AVIOContext *avioctx{nullptr}; - AVIOInterruptCB intcb{decode_interrupt_cb, this}; - if(avio_open2(&avioctx, mFilename.c_str(), AVIO_FLAG_READ, &intcb, nullptr)) - { - std::cerr<< "Failed to open "<pb = mIOContext.get(); - fmtctx->interrupt_callback = intcb; - if(avformat_open_input(&fmtctx, mFilename.c_str(), nullptr, nullptr) != 0) - { - std::cerr<< "Failed to open "<>(mFormatCtx->duration); } - -int MovieState::streamComponentOpen(unsigned int stream_index) -{ - if(stream_index >= mFormatCtx->nb_streams) - return -1; - - /* Get a pointer to the codec context for the stream, and open the - * associated codec. - */ - AVCodecCtxPtr avctx{avcodec_alloc_context3(nullptr)}; - if(!avctx) return -1; - - if(avcodec_parameters_to_context(avctx.get(), mFormatCtx->streams[stream_index]->codecpar)) - return -1; - - AVCodec *codec{avcodec_find_decoder(avctx->codec_id)}; - if(!codec || avcodec_open2(avctx.get(), codec, nullptr) < 0) - { - std::cerr<< "Unsupported codec: "<codec_id) - << " (0x"<codec_id<codec_type) - { - case AVMEDIA_TYPE_AUDIO: - mAudio.mStream = mFormatCtx->streams[stream_index]; - mAudio.mCodecCtx = std::move(avctx); - break; - - case AVMEDIA_TYPE_VIDEO: - mVideo.mStream = mFormatCtx->streams[stream_index]; - mVideo.mCodecCtx = std::move(avctx); - break; - - default: - return -1; - } - - return static_cast(stream_index); -} - -int MovieState::parse_handler() -{ - auto &audio_queue = mAudio.mPackets; - auto &video_queue = mVideo.mPackets; - - int video_index{-1}; - int audio_index{-1}; - - /* Find the first video and audio streams */ - for(unsigned int i{0u};i < mFormatCtx->nb_streams;i++) - { - auto codecpar = mFormatCtx->streams[i]->codecpar; - if(codecpar->codec_type == AVMEDIA_TYPE_VIDEO && !DisableVideo && video_index < 0) - video_index = streamComponentOpen(i); - else if(codecpar->codec_type == AVMEDIA_TYPE_AUDIO && audio_index < 0) - audio_index = streamComponentOpen(i); - } - - if(video_index < 0 && audio_index < 0) - { - std::cerr<< mFilename<<": could not open codecs" <= 0) - mAudioThread = std::thread{std::mem_fn(&AudioState::handler), &mAudio}; - if(video_index >= 0) - mVideoThread = std::thread{std::mem_fn(&VideoState::handler), &mVideo}; - - /* Main packet reading/dispatching loop */ - while(!mQuit.load(std::memory_order_relaxed)) - { - AVPacket packet; - if(av_read_frame(mFormatCtx.get(), &packet) < 0) - break; - - /* Copy the packet into the queue it's meant for. */ - if(packet.stream_index == video_index) - { - while(!mQuit.load(std::memory_order_acquire) && !video_queue.put(&packet)) - std::this_thread::sleep_for(milliseconds{100}); - } - else if(packet.stream_index == audio_index) - { - while(!mQuit.load(std::memory_order_acquire) && !audio_queue.put(&packet)) - std::this_thread::sleep_for(milliseconds{100}); - } - - av_packet_unref(&packet); - } - /* Finish the queues so the receivers know nothing more is coming. */ - if(mVideo.mCodecCtx) video_queue.setFinished(); - if(mAudio.mCodecCtx) audio_queue.setFinished(); - - /* all done - wait for it */ - if(mVideoThread.joinable()) - mVideoThread.join(); - if(mAudioThread.joinable()) - mAudioThread.join(); - - mVideo.mEOS = true; - std::unique_lock lock{mVideo.mPictQMutex}; - while(!mVideo.mFinalUpdate) - mVideo.mPictQCond.wait(lock); - lock.unlock(); - - SDL_Event evt{}; - evt.user.type = FF_MOVIE_DONE_EVENT; - SDL_PushEvent(&evt); - - return 0; -} - - -// Helper class+method to print the time with human-readable formatting. -struct PrettyTime { - seconds mTime; -}; -std::ostream &operator<<(std::ostream &os, const PrettyTime &rhs) -{ - using hours = std::chrono::hours; - using minutes = std::chrono::minutes; - - seconds t{rhs.mTime}; - if(t.count() < 0) - { - os << '-'; - t *= -1; - } - - // Only handle up to hour formatting - if(t >= hours{1}) - os << duration_cast(t).count() << 'h' << std::setfill('0') << std::setw(2) - << (duration_cast(t).count() % 60) << 'm'; - else - os << duration_cast(t).count() << 'm' << std::setfill('0'); - os << std::setw(2) << (duration_cast(t).count() % 60) << 's' << std::setw(0) - << std::setfill(' '); - return os; -} - -} // namespace - - -int main(int argc, char *argv[]) -{ - std::unique_ptr movState; - - if(argc < 2) - { - std::cerr<< "Usage: "<] [-direct] " <= AV_VERSION_INT(58, 9, 100)) - av_register_all(); -#endif - /* Initialize networking protocols */ - avformat_network_init(); - - if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS)) - { - std::cerr<< "Could not initialize SDL - <<"<( - alcGetProcAddress(device, "alcGetInteger64vSOFT") - ); - } - } - - if(alIsExtensionPresent("AL_SOFT_source_latency")) - { - std::cout<< "Found AL_SOFT_source_latency" <( - alGetProcAddress("alGetSourcei64vSOFT") - ); - } -#ifdef AL_SOFT_events - if(alIsExtensionPresent("AL_SOFT_events")) - { - std::cout<< "Found AL_SOFT_events" <( - alGetProcAddress("alEventControlSOFT")); - alEventCallbackSOFT = reinterpret_cast( - alGetProcAddress("alEventCallbackSOFT")); - } -#endif -#ifdef AL_SOFT_callback_buffer - if(alIsExtensionPresent("AL_SOFTX_callback_buffer")) - { - std::cout<< "Found AL_SOFT_callback_buffer" <( - alGetProcAddress("alBufferCallbackSOFT")); - } -#endif - - int fileidx{0}; - for(;fileidx < argc;++fileidx) - { - if(strcmp(argv[fileidx], "-direct") == 0) - { - if(alIsExtensionPresent("AL_SOFT_direct_channels_remix")) - { - std::cout<< "Found AL_SOFT_direct_channels_remix" <{new MovieState{argv[fileidx++]}}; - if(!movState->prepare()) movState = nullptr; - } - if(!movState) - { - std::cerr<< "Could not start a video" <setTitle(screen); - - /* Default to going to the next movie at the end of one. */ - enum class EomAction { - Next, Quit - } eom_action{EomAction::Next}; - seconds last_time{seconds::min()}; - while(1) - { - SDL_Event event{}; - int have_evt{SDL_WaitEventTimeout(&event, 10)}; - - auto cur_time = std::chrono::duration_cast(movState->getMasterClock()); - if(cur_time != last_time) - { - auto end_time = std::chrono::duration_cast(movState->getDuration()); - std::cout<< " \r "<mQuit = true; - eom_action = EomAction::Quit; - break; - - case SDLK_n: - movState->mQuit = true; - eom_action = EomAction::Next; - break; - - default: - break; - } - break; - - case SDL_WINDOWEVENT: - switch(event.window.event) - { - case SDL_WINDOWEVENT_RESIZED: - SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); - SDL_RenderFillRect(renderer, nullptr); - force_redraw = true; - break; - - case SDL_WINDOWEVENT_EXPOSED: - force_redraw = true; - break; - - default: - break; - } - break; - - case SDL_QUIT: - movState->mQuit = true; - eom_action = EomAction::Quit; - break; - - case FF_MOVIE_DONE_EVENT: - std::cout<<'\n'; - last_time = seconds::min(); - if(eom_action != EomAction::Quit) - { - movState = nullptr; - while(fileidx < argc && !movState) - { - movState = std::unique_ptr{new MovieState{argv[fileidx++]}}; - if(!movState->prepare()) movState = nullptr; - } - if(movState) - { - movState->setTitle(screen); - break; - } - } - - /* Nothing more to play. Shut everything down and quit. */ - movState = nullptr; - - CloseAL(); - - SDL_DestroyRenderer(renderer); - renderer = nullptr; - SDL_DestroyWindow(screen); - screen = nullptr; - - SDL_Quit(); - exit(0); - - default: - break; - } - } while(SDL_PollEvent(&event)); - - movState->mVideo.updateVideo(screen, renderer, force_redraw); - } - - std::cerr<< "SDL_WaitEvent error - "< - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -/* This file contains an example for selecting an HRTF. */ - -#include -#include -#include -#include -#include -#include -#include - -#include "sndfile.h" - -#include "AL/al.h" -#include "AL/alc.h" -#include "AL/alext.h" - -#include "common/alhelpers.h" - - -#ifndef M_PI -#define M_PI (3.14159265358979323846) -#endif - -static LPALCGETSTRINGISOFT alcGetStringiSOFT; -static LPALCRESETDEVICESOFT alcResetDeviceSOFT; - -/* LoadBuffer loads the named audio file into an OpenAL buffer object, and - * returns the new buffer ID. - */ -static ALuint LoadSound(const char *filename) -{ - ALenum err, format; - ALuint buffer; - SNDFILE *sndfile; - SF_INFO sfinfo; - short *membuf; - sf_count_t num_frames; - ALsizei num_bytes; - - /* Open the audio file and check that it's usable. */ - sndfile = sf_open(filename, SFM_READ, &sfinfo); - if(!sndfile) - { - fprintf(stderr, "Could not open audio in %s: %s\n", filename, sf_strerror(sndfile)); - return 0; - } - if(sfinfo.frames < 1 || sfinfo.frames > (sf_count_t)(INT_MAX/sizeof(short))/sfinfo.channels) - { - fprintf(stderr, "Bad sample count in %s (%" PRId64 ")\n", filename, sfinfo.frames); - sf_close(sndfile); - return 0; - } - - /* Get the sound format, and figure out the OpenAL format */ - format = AL_NONE; - if(sfinfo.channels == 1) - format = AL_FORMAT_MONO16; - else if(sfinfo.channels == 2) - format = AL_FORMAT_STEREO16; - else if(sfinfo.channels == 3) - { - if(sf_command(sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT) - format = AL_FORMAT_BFORMAT2D_16; - } - else if(sfinfo.channels == 4) - { - if(sf_command(sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT) - format = AL_FORMAT_BFORMAT3D_16; - } - if(!format) - { - fprintf(stderr, "Unsupported channel count: %d\n", sfinfo.channels); - sf_close(sndfile); - return 0; - } - - /* Decode the whole audio file to a buffer. */ - membuf = malloc((size_t)(sfinfo.frames * sfinfo.channels) * sizeof(short)); - - num_frames = sf_readf_short(sndfile, membuf, sfinfo.frames); - if(num_frames < 1) - { - free(membuf); - sf_close(sndfile); - fprintf(stderr, "Failed to read samples in %s (%" PRId64 ")\n", filename, num_frames); - return 0; - } - num_bytes = (ALsizei)(num_frames * sfinfo.channels) * (ALsizei)sizeof(short); - - /* Buffer the audio data into a new buffer object, then free the data and - * close the file. - */ - buffer = 0; - alGenBuffers(1, &buffer); - alBufferData(buffer, format, membuf, num_bytes, sfinfo.samplerate); - - free(membuf); - sf_close(sndfile); - - /* Check if an error occured, and clean up if so. */ - err = alGetError(); - if(err != AL_NO_ERROR) - { - fprintf(stderr, "OpenAL Error: %s\n", alGetString(err)); - if(buffer && alIsBuffer(buffer)) - alDeleteBuffers(1, &buffer); - return 0; - } - - return buffer; -} - - -int main(int argc, char **argv) -{ - ALCdevice *device; - ALCcontext *context; - ALboolean has_angle_ext; - ALuint source, buffer; - const char *soundname; - const char *hrtfname; - ALCint hrtf_state; - ALCint num_hrtf; - ALdouble angle; - ALenum state; - - /* Print out usage if no arguments were specified */ - if(argc < 2) - { - fprintf(stderr, "Usage: %s [-device ] [-hrtf ] \n", argv[0]); - return 1; - } - - /* Initialize OpenAL, and check for HRTF support. */ - argv++; argc--; - if(InitAL(&argv, &argc) != 0) - return 1; - - context = alcGetCurrentContext(); - device = alcGetContextsDevice(context); - if(!alcIsExtensionPresent(device, "ALC_SOFT_HRTF")) - { - fprintf(stderr, "Error: ALC_SOFT_HRTF not supported\n"); - CloseAL(); - return 1; - } - - /* Define a macro to help load the function pointers. */ -#define LOAD_PROC(d, T, x) ((x) = (T)alcGetProcAddress((d), #x)) - LOAD_PROC(device, LPALCGETSTRINGISOFT, alcGetStringiSOFT); - LOAD_PROC(device, LPALCRESETDEVICESOFT, alcResetDeviceSOFT); -#undef LOAD_PROC - - /* Check for the AL_EXT_STEREO_ANGLES extension to be able to also rotate - * stereo sources. - */ - has_angle_ext = alIsExtensionPresent("AL_EXT_STEREO_ANGLES"); - printf("AL_EXT_STEREO_ANGLES %sfound\n", has_angle_ext?"":"not "); - - /* Check for user-preferred HRTF */ - if(strcmp(argv[0], "-hrtf") == 0) - { - hrtfname = argv[1]; - soundname = argv[2]; - } - else - { - hrtfname = NULL; - soundname = argv[0]; - } - - /* Enumerate available HRTFs, and reset the device using one. */ - alcGetIntegerv(device, ALC_NUM_HRTF_SPECIFIERS_SOFT, 1, &num_hrtf); - if(!num_hrtf) - printf("No HRTFs found\n"); - else - { - ALCint attr[5]; - ALCint index = -1; - ALCint i; - - printf("Available HRTFs:\n"); - for(i = 0;i < num_hrtf;i++) - { - const ALCchar *name = alcGetStringiSOFT(device, ALC_HRTF_SPECIFIER_SOFT, i); - printf(" %d: %s\n", i, name); - - /* Check if this is the HRTF the user requested. */ - if(hrtfname && strcmp(name, hrtfname) == 0) - index = i; - } - - i = 0; - attr[i++] = ALC_HRTF_SOFT; - attr[i++] = ALC_TRUE; - if(index == -1) - { - if(hrtfname) - printf("HRTF \"%s\" not found\n", hrtfname); - printf("Using default HRTF...\n"); - } - else - { - printf("Selecting HRTF %d...\n", index); - attr[i++] = ALC_HRTF_ID_SOFT; - attr[i++] = index; - } - attr[i] = 0; - - if(!alcResetDeviceSOFT(device, attr)) - printf("Failed to reset device: %s\n", alcGetString(device, alcGetError(device))); - } - - /* Check if HRTF is enabled, and show which is being used. */ - alcGetIntegerv(device, ALC_HRTF_SOFT, 1, &hrtf_state); - if(!hrtf_state) - printf("HRTF not enabled!\n"); - else - { - const ALchar *name = alcGetString(device, ALC_HRTF_SPECIFIER_SOFT); - printf("HRTF enabled, using %s\n", name); - } - fflush(stdout); - - /* Load the sound into a buffer. */ - buffer = LoadSound(soundname); - if(!buffer) - { - CloseAL(); - return 1; - } - - /* Create the source to play the sound with. */ - source = 0; - alGenSources(1, &source); - alSourcei(source, AL_SOURCE_RELATIVE, AL_TRUE); - alSource3f(source, AL_POSITION, 0.0f, 0.0f, -1.0f); - alSourcei(source, AL_BUFFER, (ALint)buffer); - assert(alGetError()==AL_NO_ERROR && "Failed to setup sound source"); - - /* Play the sound until it finishes. */ - angle = 0.0; - alSourcePlay(source); - do { - al_nssleep(10000000); - - alcSuspendContext(context); - - /* Rotate the source around the listener by about 1/4 cycle per second, - * and keep it within -pi...+pi. - */ - angle += 0.01 * M_PI * 0.5; - if(angle > M_PI) - angle -= M_PI*2.0; - - /* This only rotates mono sounds. */ - alSource3f(source, AL_POSITION, (ALfloat)sin(angle), 0.0f, -(ALfloat)cos(angle)); - - if(has_angle_ext) - { - /* This rotates stereo sounds with the AL_EXT_STEREO_ANGLES - * extension. Angles are specified counter-clockwise in radians. - */ - ALfloat angles[2] = { (ALfloat)(M_PI/6.0 - angle), (ALfloat)(-M_PI/6.0 - angle) }; - alSourcefv(source, AL_STEREO_ANGLES, angles); - } - alcProcessContext(context); - - alGetSourcei(source, AL_SOURCE_STATE, &state); - } while(alGetError() == AL_NO_ERROR && state == AL_PLAYING); - - /* All done. Delete resources, and close down OpenAL. */ - alDeleteSources(1, &source); - alDeleteBuffers(1, &buffer); - CloseAL(); - - return 0; -} diff --git a/examples/allatency.c b/examples/allatency.c deleted file mode 100644 index 5aa9e864..00000000 --- a/examples/allatency.c +++ /dev/null @@ -1,217 +0,0 @@ -/* - * OpenAL Source Latency Example - * - * Copyright (c) 2012 by Chris Robinson - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -/* This file contains an example for checking the latency of a sound. */ - -#include -#include -#include -#include -#include - -#include "sndfile.h" - -#include "AL/al.h" -#include "AL/alext.h" - -#include "common/alhelpers.h" - - -static LPALSOURCEDSOFT alSourcedSOFT; -static LPALSOURCE3DSOFT alSource3dSOFT; -static LPALSOURCEDVSOFT alSourcedvSOFT; -static LPALGETSOURCEDSOFT alGetSourcedSOFT; -static LPALGETSOURCE3DSOFT alGetSource3dSOFT; -static LPALGETSOURCEDVSOFT alGetSourcedvSOFT; -static LPALSOURCEI64SOFT alSourcei64SOFT; -static LPALSOURCE3I64SOFT alSource3i64SOFT; -static LPALSOURCEI64VSOFT alSourcei64vSOFT; -static LPALGETSOURCEI64SOFT alGetSourcei64SOFT; -static LPALGETSOURCE3I64SOFT alGetSource3i64SOFT; -static LPALGETSOURCEI64VSOFT alGetSourcei64vSOFT; - -/* LoadBuffer loads the named audio file into an OpenAL buffer object, and - * returns the new buffer ID. - */ -static ALuint LoadSound(const char *filename) -{ - ALenum err, format; - ALuint buffer; - SNDFILE *sndfile; - SF_INFO sfinfo; - short *membuf; - sf_count_t num_frames; - ALsizei num_bytes; - - /* Open the audio file and check that it's usable. */ - sndfile = sf_open(filename, SFM_READ, &sfinfo); - if(!sndfile) - { - fprintf(stderr, "Could not open audio in %s: %s\n", filename, sf_strerror(sndfile)); - return 0; - } - if(sfinfo.frames < 1 || sfinfo.frames > (sf_count_t)(INT_MAX/sizeof(short))/sfinfo.channels) - { - fprintf(stderr, "Bad sample count in %s (%" PRId64 ")\n", filename, sfinfo.frames); - sf_close(sndfile); - return 0; - } - - /* Get the sound format, and figure out the OpenAL format */ - format = AL_NONE; - if(sfinfo.channels == 1) - format = AL_FORMAT_MONO16; - else if(sfinfo.channels == 2) - format = AL_FORMAT_STEREO16; - else if(sfinfo.channels == 3) - { - if(sf_command(sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT) - format = AL_FORMAT_BFORMAT2D_16; - } - else if(sfinfo.channels == 4) - { - if(sf_command(sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT) - format = AL_FORMAT_BFORMAT3D_16; - } - if(!format) - { - fprintf(stderr, "Unsupported channel count: %d\n", sfinfo.channels); - sf_close(sndfile); - return 0; - } - - /* Decode the whole audio file to a buffer. */ - membuf = malloc((size_t)(sfinfo.frames * sfinfo.channels) * sizeof(short)); - - num_frames = sf_readf_short(sndfile, membuf, sfinfo.frames); - if(num_frames < 1) - { - free(membuf); - sf_close(sndfile); - fprintf(stderr, "Failed to read samples in %s (%" PRId64 ")\n", filename, num_frames); - return 0; - } - num_bytes = (ALsizei)(num_frames * sfinfo.channels) * (ALsizei)sizeof(short); - - /* Buffer the audio data into a new buffer object, then free the data and - * close the file. - */ - buffer = 0; - alGenBuffers(1, &buffer); - alBufferData(buffer, format, membuf, num_bytes, sfinfo.samplerate); - - free(membuf); - sf_close(sndfile); - - /* Check if an error occured, and clean up if so. */ - err = alGetError(); - if(err != AL_NO_ERROR) - { - fprintf(stderr, "OpenAL Error: %s\n", alGetString(err)); - if(buffer && alIsBuffer(buffer)) - alDeleteBuffers(1, &buffer); - return 0; - } - - return buffer; -} - - -int main(int argc, char **argv) -{ - ALuint source, buffer; - ALdouble offsets[2]; - ALenum state; - - /* Print out usage if no arguments were specified */ - if(argc < 2) - { - fprintf(stderr, "Usage: %s [-device ] \n", argv[0]); - return 1; - } - - /* Initialize OpenAL, and check for source_latency support. */ - argv++; argc--; - if(InitAL(&argv, &argc) != 0) - return 1; - - if(!alIsExtensionPresent("AL_SOFT_source_latency")) - { - fprintf(stderr, "Error: AL_SOFT_source_latency not supported\n"); - CloseAL(); - return 1; - } - - /* Define a macro to help load the function pointers. */ -#define LOAD_PROC(T, x) ((x) = (T)alGetProcAddress(#x)) - LOAD_PROC(LPALSOURCEDSOFT, alSourcedSOFT); - LOAD_PROC(LPALSOURCE3DSOFT, alSource3dSOFT); - LOAD_PROC(LPALSOURCEDVSOFT, alSourcedvSOFT); - LOAD_PROC(LPALGETSOURCEDSOFT, alGetSourcedSOFT); - LOAD_PROC(LPALGETSOURCE3DSOFT, alGetSource3dSOFT); - LOAD_PROC(LPALGETSOURCEDVSOFT, alGetSourcedvSOFT); - LOAD_PROC(LPALSOURCEI64SOFT, alSourcei64SOFT); - LOAD_PROC(LPALSOURCE3I64SOFT, alSource3i64SOFT); - LOAD_PROC(LPALSOURCEI64VSOFT, alSourcei64vSOFT); - LOAD_PROC(LPALGETSOURCEI64SOFT, alGetSourcei64SOFT); - LOAD_PROC(LPALGETSOURCE3I64SOFT, alGetSource3i64SOFT); - LOAD_PROC(LPALGETSOURCEI64VSOFT, alGetSourcei64vSOFT); -#undef LOAD_PROC - - /* Load the sound into a buffer. */ - buffer = LoadSound(argv[0]); - if(!buffer) - { - CloseAL(); - return 1; - } - - /* Create the source to play the sound with. */ - source = 0; - alGenSources(1, &source); - alSourcei(source, AL_BUFFER, (ALint)buffer); - assert(alGetError()==AL_NO_ERROR && "Failed to setup sound source"); - - /* Play the sound until it finishes. */ - alSourcePlay(source); - do { - al_nssleep(10000000); - alGetSourcei(source, AL_SOURCE_STATE, &state); - - /* Get the source offset and latency. AL_SEC_OFFSET_LATENCY_SOFT will - * place the offset (in seconds) in offsets[0], and the time until that - * offset will be heard (in seconds) in offsets[1]. */ - alGetSourcedvSOFT(source, AL_SEC_OFFSET_LATENCY_SOFT, offsets); - printf("\rOffset: %f - Latency:%3u ms ", offsets[0], (ALuint)(offsets[1]*1000)); - fflush(stdout); - } while(alGetError() == AL_NO_ERROR && state == AL_PLAYING); - printf("\n"); - - /* All done. Delete resources, and close down OpenAL. */ - alDeleteSources(1, &source); - alDeleteBuffers(1, &buffer); - CloseAL(); - - return 0; -} diff --git a/examples/alloopback.c b/examples/alloopback.c deleted file mode 100644 index 844efa74..00000000 --- a/examples/alloopback.c +++ /dev/null @@ -1,286 +0,0 @@ -/* - * OpenAL Loopback Example - * - * Copyright (c) 2013 by Chris Robinson - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -/* This file contains an example for using the loopback device for custom - * output handling. - */ - -#include -#include -#include - -#include "SDL.h" -#include "SDL_audio.h" -#include "SDL_error.h" -#include "SDL_stdinc.h" - -#include "AL/al.h" -#include "AL/alc.h" -#include "AL/alext.h" - -#include "common/alhelpers.h" - -#ifndef SDL_AUDIO_MASK_BITSIZE -#define SDL_AUDIO_MASK_BITSIZE (0xFF) -#endif -#ifndef SDL_AUDIO_BITSIZE -#define SDL_AUDIO_BITSIZE(x) (x & SDL_AUDIO_MASK_BITSIZE) -#endif - -#ifndef M_PI -#define M_PI (3.14159265358979323846) -#endif - -typedef struct { - ALCdevice *Device; - ALCcontext *Context; - - ALCsizei FrameSize; -} PlaybackInfo; - -static LPALCLOOPBACKOPENDEVICESOFT alcLoopbackOpenDeviceSOFT; -static LPALCISRENDERFORMATSUPPORTEDSOFT alcIsRenderFormatSupportedSOFT; -static LPALCRENDERSAMPLESSOFT alcRenderSamplesSOFT; - - -void SDLCALL RenderSDLSamples(void *userdata, Uint8 *stream, int len) -{ - PlaybackInfo *playback = (PlaybackInfo*)userdata; - alcRenderSamplesSOFT(playback->Device, stream, len/playback->FrameSize); -} - - -static const char *ChannelsName(ALCenum chans) -{ - switch(chans) - { - case ALC_MONO_SOFT: return "Mono"; - case ALC_STEREO_SOFT: return "Stereo"; - case ALC_QUAD_SOFT: return "Quadraphonic"; - case ALC_5POINT1_SOFT: return "5.1 Surround"; - case ALC_6POINT1_SOFT: return "6.1 Surround"; - case ALC_7POINT1_SOFT: return "7.1 Surround"; - } - return "Unknown Channels"; -} - -static const char *TypeName(ALCenum type) -{ - switch(type) - { - case ALC_BYTE_SOFT: return "S8"; - case ALC_UNSIGNED_BYTE_SOFT: return "U8"; - case ALC_SHORT_SOFT: return "S16"; - case ALC_UNSIGNED_SHORT_SOFT: return "U16"; - case ALC_INT_SOFT: return "S32"; - case ALC_UNSIGNED_INT_SOFT: return "U32"; - case ALC_FLOAT_SOFT: return "Float32"; - } - return "Unknown Type"; -} - -/* Creates a one second buffer containing a sine wave, and returns the new - * buffer ID. */ -static ALuint CreateSineWave(void) -{ - ALshort data[44100*4]; - ALuint buffer; - ALenum err; - ALuint i; - - for(i = 0;i < 44100*4;i++) - data[i] = (ALshort)(sin(i/44100.0 * 1000.0 * 2.0*M_PI) * 32767.0); - - /* Buffer the audio data into a new buffer object. */ - buffer = 0; - alGenBuffers(1, &buffer); - alBufferData(buffer, AL_FORMAT_MONO16, data, sizeof(data), 44100); - - /* Check if an error occured, and clean up if so. */ - err = alGetError(); - if(err != AL_NO_ERROR) - { - fprintf(stderr, "OpenAL Error: %s\n", alGetString(err)); - if(alIsBuffer(buffer)) - alDeleteBuffers(1, &buffer); - return 0; - } - - return buffer; -} - - -int main(int argc, char *argv[]) -{ - PlaybackInfo playback = { NULL, NULL, 0 }; - SDL_AudioSpec desired, obtained; - ALuint source, buffer; - ALCint attrs[16]; - ALenum state; - (void)argc; - (void)argv; - - /* Print out error if extension is missing. */ - if(!alcIsExtensionPresent(NULL, "ALC_SOFT_loopback")) - { - fprintf(stderr, "Error: ALC_SOFT_loopback not supported!\n"); - return 1; - } - - /* Define a macro to help load the function pointers. */ -#define LOAD_PROC(T, x) ((x) = (T)alcGetProcAddress(NULL, #x)) - LOAD_PROC(LPALCLOOPBACKOPENDEVICESOFT, alcLoopbackOpenDeviceSOFT); - LOAD_PROC(LPALCISRENDERFORMATSUPPORTEDSOFT, alcIsRenderFormatSupportedSOFT); - LOAD_PROC(LPALCRENDERSAMPLESSOFT, alcRenderSamplesSOFT); -#undef LOAD_PROC - - if(SDL_Init(SDL_INIT_AUDIO) == -1) - { - fprintf(stderr, "Failed to init SDL audio: %s\n", SDL_GetError()); - return 1; - } - - /* Set up SDL audio with our requested format and callback. */ - desired.channels = 2; - desired.format = AUDIO_S16SYS; - desired.freq = 44100; - desired.padding = 0; - desired.samples = 4096; - desired.callback = RenderSDLSamples; - desired.userdata = &playback; - if(SDL_OpenAudio(&desired, &obtained) != 0) - { - SDL_Quit(); - fprintf(stderr, "Failed to open SDL audio: %s\n", SDL_GetError()); - return 1; - } - - /* Set up our OpenAL attributes based on what we got from SDL. */ - attrs[0] = ALC_FORMAT_CHANNELS_SOFT; - if(obtained.channels == 1) - attrs[1] = ALC_MONO_SOFT; - else if(obtained.channels == 2) - attrs[1] = ALC_STEREO_SOFT; - else - { - fprintf(stderr, "Unhandled SDL channel count: %d\n", obtained.channels); - goto error; - } - - attrs[2] = ALC_FORMAT_TYPE_SOFT; - if(obtained.format == AUDIO_U8) - attrs[3] = ALC_UNSIGNED_BYTE_SOFT; - else if(obtained.format == AUDIO_S8) - attrs[3] = ALC_BYTE_SOFT; - else if(obtained.format == AUDIO_U16SYS) - attrs[3] = ALC_UNSIGNED_SHORT_SOFT; - else if(obtained.format == AUDIO_S16SYS) - attrs[3] = ALC_SHORT_SOFT; - else - { - fprintf(stderr, "Unhandled SDL format: 0x%04x\n", obtained.format); - goto error; - } - - attrs[4] = ALC_FREQUENCY; - attrs[5] = obtained.freq; - - attrs[6] = 0; /* end of list */ - - playback.FrameSize = obtained.channels * SDL_AUDIO_BITSIZE(obtained.format) / 8; - - /* Initialize OpenAL loopback device, using our format attributes. */ - playback.Device = alcLoopbackOpenDeviceSOFT(NULL); - if(!playback.Device) - { - fprintf(stderr, "Failed to open loopback device!\n"); - goto error; - } - /* Make sure the format is supported before setting them on the device. */ - if(alcIsRenderFormatSupportedSOFT(playback.Device, attrs[5], attrs[1], attrs[3]) == ALC_FALSE) - { - fprintf(stderr, "Render format not supported: %s, %s, %dhz\n", - ChannelsName(attrs[1]), TypeName(attrs[3]), attrs[5]); - goto error; - } - playback.Context = alcCreateContext(playback.Device, attrs); - if(!playback.Context || alcMakeContextCurrent(playback.Context) == ALC_FALSE) - { - fprintf(stderr, "Failed to set an OpenAL audio context\n"); - goto error; - } - - /* Start SDL playing. Our callback (thus alcRenderSamplesSOFT) will now - * start being called regularly to update the AL playback state. */ - SDL_PauseAudio(0); - - /* Load the sound into a buffer. */ - buffer = CreateSineWave(); - if(!buffer) - { - SDL_CloseAudio(); - alcDestroyContext(playback.Context); - alcCloseDevice(playback.Device); - SDL_Quit(); - return 1; - } - - /* Create the source to play the sound with. */ - source = 0; - alGenSources(1, &source); - alSourcei(source, AL_BUFFER, (ALint)buffer); - assert(alGetError()==AL_NO_ERROR && "Failed to setup sound source"); - - /* Play the sound until it finishes. */ - alSourcePlay(source); - do { - al_nssleep(10000000); - alGetSourcei(source, AL_SOURCE_STATE, &state); - } while(alGetError() == AL_NO_ERROR && state == AL_PLAYING); - - /* All done. Delete resources, and close OpenAL. */ - alDeleteSources(1, &source); - alDeleteBuffers(1, &buffer); - - /* Stop SDL playing. */ - SDL_PauseAudio(1); - - /* Close up OpenAL and SDL. */ - SDL_CloseAudio(); - alcDestroyContext(playback.Context); - alcCloseDevice(playback.Device); - SDL_Quit(); - - return 0; - -error: - SDL_CloseAudio(); - if(playback.Context) - alcDestroyContext(playback.Context); - if(playback.Device) - alcCloseDevice(playback.Device); - SDL_Quit(); - - return 1; -} diff --git a/examples/almultireverb.c b/examples/almultireverb.c deleted file mode 100644 index eb874061..00000000 --- a/examples/almultireverb.c +++ /dev/null @@ -1,688 +0,0 @@ -/* - * OpenAL Multi-Zone Reverb Example - * - * Copyright (c) 2018 by Chris Robinson - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -/* This file contains an example for controlling multiple reverb zones to - * smoothly transition between reverb environments. The general concept is to - * extend single-reverb by also tracking the closest adjacent environment, and - * utilize EAX Reverb's panning vectors to position them relative to the - * listener. - */ - - -#include -#include -#include -#include -#include -#include -#include - -#include "sndfile.h" - -#include "AL/al.h" -#include "AL/alc.h" -#include "AL/efx.h" -#include "AL/efx-presets.h" - -#include "common/alhelpers.h" - - -#ifndef M_PI -#define M_PI 3.14159265358979323846 -#endif - - -/* Filter object functions */ -static LPALGENFILTERS alGenFilters; -static LPALDELETEFILTERS alDeleteFilters; -static LPALISFILTER alIsFilter; -static LPALFILTERI alFilteri; -static LPALFILTERIV alFilteriv; -static LPALFILTERF alFilterf; -static LPALFILTERFV alFilterfv; -static LPALGETFILTERI alGetFilteri; -static LPALGETFILTERIV alGetFilteriv; -static LPALGETFILTERF alGetFilterf; -static LPALGETFILTERFV alGetFilterfv; - -/* Effect object functions */ -static LPALGENEFFECTS alGenEffects; -static LPALDELETEEFFECTS alDeleteEffects; -static LPALISEFFECT alIsEffect; -static LPALEFFECTI alEffecti; -static LPALEFFECTIV alEffectiv; -static LPALEFFECTF alEffectf; -static LPALEFFECTFV alEffectfv; -static LPALGETEFFECTI alGetEffecti; -static LPALGETEFFECTIV alGetEffectiv; -static LPALGETEFFECTF alGetEffectf; -static LPALGETEFFECTFV alGetEffectfv; - -/* Auxiliary Effect Slot object functions */ -static LPALGENAUXILIARYEFFECTSLOTS alGenAuxiliaryEffectSlots; -static LPALDELETEAUXILIARYEFFECTSLOTS alDeleteAuxiliaryEffectSlots; -static LPALISAUXILIARYEFFECTSLOT alIsAuxiliaryEffectSlot; -static LPALAUXILIARYEFFECTSLOTI alAuxiliaryEffectSloti; -static LPALAUXILIARYEFFECTSLOTIV alAuxiliaryEffectSlotiv; -static LPALAUXILIARYEFFECTSLOTF alAuxiliaryEffectSlotf; -static LPALAUXILIARYEFFECTSLOTFV alAuxiliaryEffectSlotfv; -static LPALGETAUXILIARYEFFECTSLOTI alGetAuxiliaryEffectSloti; -static LPALGETAUXILIARYEFFECTSLOTIV alGetAuxiliaryEffectSlotiv; -static LPALGETAUXILIARYEFFECTSLOTF alGetAuxiliaryEffectSlotf; -static LPALGETAUXILIARYEFFECTSLOTFV alGetAuxiliaryEffectSlotfv; - - -/* LoadEffect loads the given initial reverb properties into the given OpenAL - * effect object, and returns non-zero on success. - */ -static int LoadEffect(ALuint effect, const EFXEAXREVERBPROPERTIES *reverb) -{ - ALenum err; - - alGetError(); - - /* Prepare the effect for EAX Reverb (standard reverb doesn't contain - * the needed panning vectors). - */ - alEffecti(effect, AL_EFFECT_TYPE, AL_EFFECT_EAXREVERB); - if((err=alGetError()) != AL_NO_ERROR) - { - fprintf(stderr, "Failed to set EAX Reverb: %s (0x%04x)\n", alGetString(err), err); - return 0; - } - - /* Load the reverb properties. */ - alEffectf(effect, AL_EAXREVERB_DENSITY, reverb->flDensity); - alEffectf(effect, AL_EAXREVERB_DIFFUSION, reverb->flDiffusion); - alEffectf(effect, AL_EAXREVERB_GAIN, reverb->flGain); - alEffectf(effect, AL_EAXREVERB_GAINHF, reverb->flGainHF); - alEffectf(effect, AL_EAXREVERB_GAINLF, reverb->flGainLF); - alEffectf(effect, AL_EAXREVERB_DECAY_TIME, reverb->flDecayTime); - alEffectf(effect, AL_EAXREVERB_DECAY_HFRATIO, reverb->flDecayHFRatio); - alEffectf(effect, AL_EAXREVERB_DECAY_LFRATIO, reverb->flDecayLFRatio); - alEffectf(effect, AL_EAXREVERB_REFLECTIONS_GAIN, reverb->flReflectionsGain); - alEffectf(effect, AL_EAXREVERB_REFLECTIONS_DELAY, reverb->flReflectionsDelay); - alEffectfv(effect, AL_EAXREVERB_REFLECTIONS_PAN, reverb->flReflectionsPan); - alEffectf(effect, AL_EAXREVERB_LATE_REVERB_GAIN, reverb->flLateReverbGain); - alEffectf(effect, AL_EAXREVERB_LATE_REVERB_DELAY, reverb->flLateReverbDelay); - alEffectfv(effect, AL_EAXREVERB_LATE_REVERB_PAN, reverb->flLateReverbPan); - alEffectf(effect, AL_EAXREVERB_ECHO_TIME, reverb->flEchoTime); - alEffectf(effect, AL_EAXREVERB_ECHO_DEPTH, reverb->flEchoDepth); - alEffectf(effect, AL_EAXREVERB_MODULATION_TIME, reverb->flModulationTime); - alEffectf(effect, AL_EAXREVERB_MODULATION_DEPTH, reverb->flModulationDepth); - alEffectf(effect, AL_EAXREVERB_AIR_ABSORPTION_GAINHF, reverb->flAirAbsorptionGainHF); - alEffectf(effect, AL_EAXREVERB_HFREFERENCE, reverb->flHFReference); - alEffectf(effect, AL_EAXREVERB_LFREFERENCE, reverb->flLFReference); - alEffectf(effect, AL_EAXREVERB_ROOM_ROLLOFF_FACTOR, reverb->flRoomRolloffFactor); - alEffecti(effect, AL_EAXREVERB_DECAY_HFLIMIT, reverb->iDecayHFLimit); - - /* Check if an error occured, and return failure if so. */ - if((err=alGetError()) != AL_NO_ERROR) - { - fprintf(stderr, "Error setting up reverb: %s\n", alGetString(err)); - return 0; - } - - return 1; -} - - -/* LoadBuffer loads the named audio file into an OpenAL buffer object, and - * returns the new buffer ID. - */ -static ALuint LoadSound(const char *filename) -{ - ALenum err, format; - ALuint buffer; - SNDFILE *sndfile; - SF_INFO sfinfo; - short *membuf; - sf_count_t num_frames; - ALsizei num_bytes; - - /* Open the audio file and check that it's usable. */ - sndfile = sf_open(filename, SFM_READ, &sfinfo); - if(!sndfile) - { - fprintf(stderr, "Could not open audio in %s: %s\n", filename, sf_strerror(sndfile)); - return 0; - } - if(sfinfo.frames < 1 || sfinfo.frames > (sf_count_t)(INT_MAX/sizeof(short))/sfinfo.channels) - { - fprintf(stderr, "Bad sample count in %s (%" PRId64 ")\n", filename, sfinfo.frames); - sf_close(sndfile); - return 0; - } - - /* Get the sound format, and figure out the OpenAL format */ - if(sfinfo.channels == 1) - format = AL_FORMAT_MONO16; - else if(sfinfo.channels == 2) - format = AL_FORMAT_STEREO16; - else - { - fprintf(stderr, "Unsupported channel count: %d\n", sfinfo.channels); - sf_close(sndfile); - return 0; - } - - /* Decode the whole audio file to a buffer. */ - membuf = malloc((size_t)(sfinfo.frames * sfinfo.channels) * sizeof(short)); - - num_frames = sf_readf_short(sndfile, membuf, sfinfo.frames); - if(num_frames < 1) - { - free(membuf); - sf_close(sndfile); - fprintf(stderr, "Failed to read samples in %s (%" PRId64 ")\n", filename, num_frames); - return 0; - } - num_bytes = (ALsizei)(num_frames * sfinfo.channels) * (ALsizei)sizeof(short); - - /* Buffer the audio data into a new buffer object, then free the data and - * close the file. - */ - buffer = 0; - alGenBuffers(1, &buffer); - alBufferData(buffer, format, membuf, num_bytes, sfinfo.samplerate); - - free(membuf); - sf_close(sndfile); - - /* Check if an error occured, and clean up if so. */ - err = alGetError(); - if(err != AL_NO_ERROR) - { - fprintf(stderr, "OpenAL Error: %s\n", alGetString(err)); - if(buffer && alIsBuffer(buffer)) - alDeleteBuffers(1, &buffer); - return 0; - } - - return buffer; -} - - -/* Helper to calculate the dot-product of the two given vectors. */ -static ALfloat dot_product(const ALfloat vec0[3], const ALfloat vec1[3]) -{ - return vec0[0]*vec1[0] + vec0[1]*vec1[1] + vec0[2]*vec1[2]; -} - -/* Helper to normalize a given vector. */ -static void normalize(ALfloat vec[3]) -{ - ALfloat mag = sqrtf(dot_product(vec, vec)); - if(mag > 0.00001f) - { - vec[0] /= mag; - vec[1] /= mag; - vec[2] /= mag; - } - else - { - vec[0] = 0.0f; - vec[1] = 0.0f; - vec[2] = 0.0f; - } -} - - -/* The main update function to update the listener and environment effects. */ -static void UpdateListenerAndEffects(float timediff, const ALuint slots[2], const ALuint effects[2], const EFXEAXREVERBPROPERTIES reverbs[2]) -{ - static const ALfloat listener_move_scale = 10.0f; - /* Individual reverb zones are connected via "portals". Each portal has a - * position (center point of the connecting area), a normal (facing - * direction), and a radius (approximate size of the connecting area). - */ - const ALfloat portal_pos[3] = { 0.0f, 0.0f, 0.0f }; - const ALfloat portal_norm[3] = { sqrtf(0.5f), 0.0f, -sqrtf(0.5f) }; - const ALfloat portal_radius = 2.5f; - ALfloat other_dir[3], this_dir[3]; - ALfloat listener_pos[3]; - ALfloat local_norm[3]; - ALfloat local_dir[3]; - ALfloat near_edge[3]; - ALfloat far_edge[3]; - ALfloat dist, edist; - - /* Update the listener position for the amount of time passed. This uses a - * simple triangular LFO to offset the position (moves along the X axis - * between -listener_move_scale and +listener_move_scale for each - * transition). - */ - listener_pos[0] = (fabsf(2.0f - timediff/2.0f) - 1.0f) * listener_move_scale; - listener_pos[1] = 0.0f; - listener_pos[2] = 0.0f; - alListenerfv(AL_POSITION, listener_pos); - - /* Calculate local_dir, which represents the listener-relative point to the - * adjacent zone (should also include orientation). Because EAX Reverb uses - * left-handed coordinates instead of right-handed like the rest of OpenAL, - * negate Z for the local values. - */ - local_dir[0] = portal_pos[0] - listener_pos[0]; - local_dir[1] = portal_pos[1] - listener_pos[1]; - local_dir[2] = -(portal_pos[2] - listener_pos[2]); - /* A normal application would also rotate the portal's normal given the - * listener orientation, to get the listener-relative normal. - */ - local_norm[0] = portal_norm[0]; - local_norm[1] = portal_norm[1]; - local_norm[2] = -portal_norm[2]; - - /* Calculate the distance from the listener to the portal, and ensure it's - * far enough away to not suffer severe floating-point precision issues. - */ - dist = sqrtf(dot_product(local_dir, local_dir)); - if(dist > 0.00001f) - { - const EFXEAXREVERBPROPERTIES *other_reverb, *this_reverb; - ALuint other_effect, this_effect; - ALfloat magnitude, dir_dot_norm; - - /* Normalize the direction to the portal. */ - local_dir[0] /= dist; - local_dir[1] /= dist; - local_dir[2] /= dist; - - /* Calculate the dot product of the portal's local direction and local - * normal, which is used for angular and side checks later on. - */ - dir_dot_norm = dot_product(local_dir, local_norm); - - /* Figure out which zone we're in. */ - if(dir_dot_norm <= 0.0f) - { - /* We're in front of the portal, so we're in Zone 0. */ - this_effect = effects[0]; - other_effect = effects[1]; - this_reverb = &reverbs[0]; - other_reverb = &reverbs[1]; - } - else - { - /* We're behind the portal, so we're in Zone 1. */ - this_effect = effects[1]; - other_effect = effects[0]; - this_reverb = &reverbs[1]; - other_reverb = &reverbs[0]; - } - - /* Calculate the listener-relative extents of the portal. */ - /* First, project the listener-to-portal vector onto the portal's plane - * to get the portal-relative direction along the plane that goes away - * from the listener (toward the farthest edge of the portal). - */ - far_edge[0] = local_dir[0] - local_norm[0]*dir_dot_norm; - far_edge[1] = local_dir[1] - local_norm[1]*dir_dot_norm; - far_edge[2] = local_dir[2] - local_norm[2]*dir_dot_norm; - - edist = sqrtf(dot_product(far_edge, far_edge)); - if(edist > 0.0001f) - { - /* Rescale the portal-relative vector to be at the radius edge. */ - ALfloat mag = portal_radius / edist; - far_edge[0] *= mag; - far_edge[1] *= mag; - far_edge[2] *= mag; - - /* Calculate the closest edge of the portal by negating the - * farthest, and add an offset to make them both relative to the - * listener. - */ - near_edge[0] = local_dir[0]*dist - far_edge[0]; - near_edge[1] = local_dir[1]*dist - far_edge[1]; - near_edge[2] = local_dir[2]*dist - far_edge[2]; - far_edge[0] += local_dir[0]*dist; - far_edge[1] += local_dir[1]*dist; - far_edge[2] += local_dir[2]*dist; - - /* Normalize the listener-relative extents of the portal, then - * calculate the panning magnitude for the other zone given the - * apparent size of the opening. The panning magnitude affects the - * envelopment of the environment, with 1 being a point, 0.5 being - * half coverage around the listener, and 0 being full coverage. - */ - normalize(far_edge); - normalize(near_edge); - magnitude = 1.0f - acosf(dot_product(far_edge, near_edge))/(float)(M_PI*2.0); - - /* Recalculate the panning direction, to be directly between the - * direction of the two extents. - */ - local_dir[0] = far_edge[0] + near_edge[0]; - local_dir[1] = far_edge[1] + near_edge[1]; - local_dir[2] = far_edge[2] + near_edge[2]; - normalize(local_dir); - } - else - { - /* If we get here, the listener is directly in front of or behind - * the center of the portal, making all aperture edges effectively - * equidistant. Calculating the panning magnitude is simplified, - * using the arctangent of the radius and distance. - */ - magnitude = 1.0f - (atan2f(portal_radius, dist) / (float)M_PI); - } - - /* Scale the other zone's panning vector. */ - other_dir[0] = local_dir[0] * magnitude; - other_dir[1] = local_dir[1] * magnitude; - other_dir[2] = local_dir[2] * magnitude; - /* Pan the current zone to the opposite direction of the portal, and - * take the remaining percentage of the portal's magnitude. - */ - this_dir[0] = local_dir[0] * (magnitude-1.0f); - this_dir[1] = local_dir[1] * (magnitude-1.0f); - this_dir[2] = local_dir[2] * (magnitude-1.0f); - - /* Now set the effects' panning vectors and gain. Energy is shared - * between environments, so attenuate according to each zone's - * contribution (note: gain^2 = energy). - */ - alEffectf(this_effect, AL_EAXREVERB_REFLECTIONS_GAIN, this_reverb->flReflectionsGain * sqrtf(magnitude)); - alEffectf(this_effect, AL_EAXREVERB_LATE_REVERB_GAIN, this_reverb->flLateReverbGain * sqrtf(magnitude)); - alEffectfv(this_effect, AL_EAXREVERB_REFLECTIONS_PAN, this_dir); - alEffectfv(this_effect, AL_EAXREVERB_LATE_REVERB_PAN, this_dir); - - alEffectf(other_effect, AL_EAXREVERB_REFLECTIONS_GAIN, other_reverb->flReflectionsGain * sqrtf(1.0f-magnitude)); - alEffectf(other_effect, AL_EAXREVERB_LATE_REVERB_GAIN, other_reverb->flLateReverbGain * sqrtf(1.0f-magnitude)); - alEffectfv(other_effect, AL_EAXREVERB_REFLECTIONS_PAN, other_dir); - alEffectfv(other_effect, AL_EAXREVERB_LATE_REVERB_PAN, other_dir); - } - else - { - /* We're practically in the center of the portal. Give the panning - * vectors a 50/50 split, with Zone 0 covering the half in front of - * the normal, and Zone 1 covering the half behind. - */ - this_dir[0] = local_norm[0] / 2.0f; - this_dir[1] = local_norm[1] / 2.0f; - this_dir[2] = local_norm[2] / 2.0f; - - other_dir[0] = local_norm[0] / -2.0f; - other_dir[1] = local_norm[1] / -2.0f; - other_dir[2] = local_norm[2] / -2.0f; - - alEffectf(effects[0], AL_EAXREVERB_REFLECTIONS_GAIN, reverbs[0].flReflectionsGain * sqrtf(0.5f)); - alEffectf(effects[0], AL_EAXREVERB_LATE_REVERB_GAIN, reverbs[0].flLateReverbGain * sqrtf(0.5f)); - alEffectfv(effects[0], AL_EAXREVERB_REFLECTIONS_PAN, this_dir); - alEffectfv(effects[0], AL_EAXREVERB_LATE_REVERB_PAN, this_dir); - - alEffectf(effects[1], AL_EAXREVERB_REFLECTIONS_GAIN, reverbs[1].flReflectionsGain * sqrtf(0.5f)); - alEffectf(effects[1], AL_EAXREVERB_LATE_REVERB_GAIN, reverbs[1].flLateReverbGain * sqrtf(0.5f)); - alEffectfv(effects[1], AL_EAXREVERB_REFLECTIONS_PAN, other_dir); - alEffectfv(effects[1], AL_EAXREVERB_LATE_REVERB_PAN, other_dir); - } - - /* Finally, update the effect slots with the updated effect parameters. */ - alAuxiliaryEffectSloti(slots[0], AL_EFFECTSLOT_EFFECT, (ALint)effects[0]); - alAuxiliaryEffectSloti(slots[1], AL_EFFECTSLOT_EFFECT, (ALint)effects[1]); -} - - -int main(int argc, char **argv) -{ - static const int MaxTransitions = 8; - EFXEAXREVERBPROPERTIES reverbs[2] = { - EFX_REVERB_PRESET_CARPETEDHALLWAY, - EFX_REVERB_PRESET_BATHROOM - }; - ALCdevice *device = NULL; - ALCcontext *context = NULL; - ALuint effects[2] = { 0, 0 }; - ALuint slots[2] = { 0, 0 }; - ALuint direct_filter = 0; - ALuint buffer = 0; - ALuint source = 0; - ALCint num_sends = 0; - ALenum state = AL_INITIAL; - ALfloat direct_gain = 1.0f; - int basetime = 0; - int loops = 0; - - /* Print out usage if no arguments were specified */ - if(argc < 2) - { - fprintf(stderr, "Usage: %s [-device ] [options] \n\n" - "Options:\n" - "\t-nodirect\tSilence direct path output (easier to hear reverb)\n\n", - argv[0]); - return 1; - } - - /* Initialize OpenAL, and check for EFX support with at least 2 auxiliary - * sends (if multiple sends are supported, 2 are provided by default; if - * you want more, you have to request it through alcCreateContext). - */ - argv++; argc--; - if(InitAL(&argv, &argc) != 0) - return 1; - - while(argc > 0) - { - if(strcmp(argv[0], "-nodirect") == 0) - direct_gain = 0.0f; - else - break; - argv++; - argc--; - } - if(argc < 1) - { - fprintf(stderr, "No filename spacified.\n"); - CloseAL(); - return 1; - } - - context = alcGetCurrentContext(); - device = alcGetContextsDevice(context); - - if(!alcIsExtensionPresent(device, "ALC_EXT_EFX")) - { - fprintf(stderr, "Error: EFX not supported\n"); - CloseAL(); - return 1; - } - - num_sends = 0; - alcGetIntegerv(device, ALC_MAX_AUXILIARY_SENDS, 1, &num_sends); - if(alcGetError(device) != ALC_NO_ERROR || num_sends < 2) - { - fprintf(stderr, "Error: Device does not support multiple sends (got %d, need 2)\n", - num_sends); - CloseAL(); - return 1; - } - - /* Define a macro to help load the function pointers. */ -#define LOAD_PROC(T, x) ((x) = (T)alGetProcAddress(#x)) - LOAD_PROC(LPALGENFILTERS, alGenFilters); - LOAD_PROC(LPALDELETEFILTERS, alDeleteFilters); - LOAD_PROC(LPALISFILTER, alIsFilter); - LOAD_PROC(LPALFILTERI, alFilteri); - LOAD_PROC(LPALFILTERIV, alFilteriv); - LOAD_PROC(LPALFILTERF, alFilterf); - LOAD_PROC(LPALFILTERFV, alFilterfv); - LOAD_PROC(LPALGETFILTERI, alGetFilteri); - LOAD_PROC(LPALGETFILTERIV, alGetFilteriv); - LOAD_PROC(LPALGETFILTERF, alGetFilterf); - LOAD_PROC(LPALGETFILTERFV, alGetFilterfv); - - LOAD_PROC(LPALGENEFFECTS, alGenEffects); - LOAD_PROC(LPALDELETEEFFECTS, alDeleteEffects); - LOAD_PROC(LPALISEFFECT, alIsEffect); - LOAD_PROC(LPALEFFECTI, alEffecti); - LOAD_PROC(LPALEFFECTIV, alEffectiv); - LOAD_PROC(LPALEFFECTF, alEffectf); - LOAD_PROC(LPALEFFECTFV, alEffectfv); - LOAD_PROC(LPALGETEFFECTI, alGetEffecti); - LOAD_PROC(LPALGETEFFECTIV, alGetEffectiv); - LOAD_PROC(LPALGETEFFECTF, alGetEffectf); - LOAD_PROC(LPALGETEFFECTFV, alGetEffectfv); - - LOAD_PROC(LPALGENAUXILIARYEFFECTSLOTS, alGenAuxiliaryEffectSlots); - LOAD_PROC(LPALDELETEAUXILIARYEFFECTSLOTS, alDeleteAuxiliaryEffectSlots); - LOAD_PROC(LPALISAUXILIARYEFFECTSLOT, alIsAuxiliaryEffectSlot); - LOAD_PROC(LPALAUXILIARYEFFECTSLOTI, alAuxiliaryEffectSloti); - LOAD_PROC(LPALAUXILIARYEFFECTSLOTIV, alAuxiliaryEffectSlotiv); - LOAD_PROC(LPALAUXILIARYEFFECTSLOTF, alAuxiliaryEffectSlotf); - LOAD_PROC(LPALAUXILIARYEFFECTSLOTFV, alAuxiliaryEffectSlotfv); - LOAD_PROC(LPALGETAUXILIARYEFFECTSLOTI, alGetAuxiliaryEffectSloti); - LOAD_PROC(LPALGETAUXILIARYEFFECTSLOTIV, alGetAuxiliaryEffectSlotiv); - LOAD_PROC(LPALGETAUXILIARYEFFECTSLOTF, alGetAuxiliaryEffectSlotf); - LOAD_PROC(LPALGETAUXILIARYEFFECTSLOTFV, alGetAuxiliaryEffectSlotfv); -#undef LOAD_PROC - - /* Load the sound into a buffer. */ - buffer = LoadSound(argv[0]); - if(!buffer) - { - CloseAL(); - return 1; - } - - /* Generate two effects for two "zones", and load a reverb into each one. - * Note that unlike single-zone reverb, where you can store one effect per - * preset, for multi-zone reverb you should have one effect per environment - * instance, or one per audible zone. This is because we'll be changing the - * effects' properties in real-time based on the environment instance - * relative to the listener. - */ - alGenEffects(2, effects); - if(!LoadEffect(effects[0], &reverbs[0]) || !LoadEffect(effects[1], &reverbs[1])) - { - alDeleteEffects(2, effects); - alDeleteBuffers(1, &buffer); - CloseAL(); - return 1; - } - - /* Create the effect slot objects, one for each "active" effect. */ - alGenAuxiliaryEffectSlots(2, slots); - - /* Tell the effect slots to use the loaded effect objects, with slot 0 for - * Zone 0 and slot 1 for Zone 1. Note that this effectively copies the - * effect properties. Modifying or deleting the effect object afterward - * won't directly affect the effect slot until they're reapplied like this. - */ - alAuxiliaryEffectSloti(slots[0], AL_EFFECTSLOT_EFFECT, (ALint)effects[0]); - alAuxiliaryEffectSloti(slots[1], AL_EFFECTSLOT_EFFECT, (ALint)effects[1]); - assert(alGetError()==AL_NO_ERROR && "Failed to set effect slot"); - - /* For the purposes of this example, prepare a filter that optionally - * silences the direct path which allows us to hear just the reverberation. - * A filter like this is normally used for obstruction, where the path - * directly between the listener and source is blocked (the exact - * properties depending on the type and thickness of the obstructing - * material). - */ - alGenFilters(1, &direct_filter); - alFilteri(direct_filter, AL_FILTER_TYPE, AL_FILTER_LOWPASS); - alFilterf(direct_filter, AL_LOWPASS_GAIN, direct_gain); - assert(alGetError()==AL_NO_ERROR && "Failed to set direct filter"); - - /* Create the source to play the sound with, place it in front of the - * listener's path in the left zone. - */ - source = 0; - alGenSources(1, &source); - alSourcei(source, AL_LOOPING, AL_TRUE); - alSource3f(source, AL_POSITION, -5.0f, 0.0f, -2.0f); - alSourcei(source, AL_DIRECT_FILTER, (ALint)direct_filter); - alSourcei(source, AL_BUFFER, (ALint)buffer); - - /* Connect the source to the effect slots. Here, we connect source send 0 - * to Zone 0's slot, and send 1 to Zone 1's slot. Filters can be specified - * to occlude the source from each zone by varying amounts; for example, a - * source within a particular zone would be unfiltered, while a source that - * can only see a zone through a window or thin wall may be attenuated for - * that zone. - */ - alSource3i(source, AL_AUXILIARY_SEND_FILTER, (ALint)slots[0], 0, AL_FILTER_NULL); - alSource3i(source, AL_AUXILIARY_SEND_FILTER, (ALint)slots[1], 1, AL_FILTER_NULL); - assert(alGetError()==AL_NO_ERROR && "Failed to setup sound source"); - - /* Get the current time as the base for timing in the main loop. */ - basetime = altime_get(); - loops = 0; - printf("Transition %d of %d...\n", loops+1, MaxTransitions); - - /* Play the sound for a while. */ - alSourcePlay(source); - do { - int curtime; - ALfloat timediff; - - /* Start a batch update, to ensure all changes apply simultaneously. */ - alcSuspendContext(context); - - /* Get the current time to track the amount of time that passed. - * Convert the difference to seconds. - */ - curtime = altime_get(); - timediff = (float)(curtime - basetime) / 1000.0f; - - /* Avoid negative time deltas, in case of non-monotonic clocks. */ - if(timediff < 0.0f) - timediff = 0.0f; - else while(timediff >= 4.0f*(float)((loops&1)+1)) - { - /* For this example, each transition occurs over 4 seconds, and - * there's 2 transitions per cycle. - */ - if(++loops < MaxTransitions) - printf("Transition %d of %d...\n", loops+1, MaxTransitions); - if(!(loops&1)) - { - /* Cycle completed. Decrease the delta and increase the base - * time to start a new cycle. - */ - timediff -= 8.0f; - basetime += 8000; - } - } - - /* Update the listener and effects, and finish the batch. */ - UpdateListenerAndEffects(timediff, slots, effects, reverbs); - alcProcessContext(context); - - al_nssleep(10000000); - - alGetSourcei(source, AL_SOURCE_STATE, &state); - } while(alGetError() == AL_NO_ERROR && state == AL_PLAYING && loops < MaxTransitions); - - /* All done. Delete resources, and close down OpenAL. */ - alDeleteSources(1, &source); - alDeleteAuxiliaryEffectSlots(2, slots); - alDeleteEffects(2, effects); - alDeleteFilters(1, &direct_filter); - alDeleteBuffers(1, &buffer); - - CloseAL(); - - return 0; -} diff --git a/examples/alplay.c b/examples/alplay.c deleted file mode 100644 index 56d5434b..00000000 --- a/examples/alplay.c +++ /dev/null @@ -1,180 +0,0 @@ -/* - * OpenAL Source Play Example - * - * Copyright (c) 2017 by Chris Robinson - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -/* This file contains an example for playing a sound buffer. */ - -#include -#include -#include -#include -#include - -#include "sndfile.h" - -#include "AL/al.h" -#include "AL/alext.h" - -#include "common/alhelpers.h" - - -/* LoadBuffer loads the named audio file into an OpenAL buffer object, and - * returns the new buffer ID. - */ -static ALuint LoadSound(const char *filename) -{ - ALenum err, format; - ALuint buffer; - SNDFILE *sndfile; - SF_INFO sfinfo; - short *membuf; - sf_count_t num_frames; - ALsizei num_bytes; - - /* Open the audio file and check that it's usable. */ - sndfile = sf_open(filename, SFM_READ, &sfinfo); - if(!sndfile) - { - fprintf(stderr, "Could not open audio in %s: %s\n", filename, sf_strerror(sndfile)); - return 0; - } - if(sfinfo.frames < 1 || sfinfo.frames > (sf_count_t)(INT_MAX/sizeof(short))/sfinfo.channels) - { - fprintf(stderr, "Bad sample count in %s (%" PRId64 ")\n", filename, sfinfo.frames); - sf_close(sndfile); - return 0; - } - - /* Get the sound format, and figure out the OpenAL format */ - format = AL_NONE; - if(sfinfo.channels == 1) - format = AL_FORMAT_MONO16; - else if(sfinfo.channels == 2) - format = AL_FORMAT_STEREO16; - else if(sfinfo.channels == 3) - { - if(sf_command(sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT) - format = AL_FORMAT_BFORMAT2D_16; - } - else if(sfinfo.channels == 4) - { - if(sf_command(sndfile, SFC_WAVEX_GET_AMBISONIC, NULL, 0) == SF_AMBISONIC_B_FORMAT) - format = AL_FORMAT_BFORMAT3D_16; - } - if(!format) - { - fprintf(stderr, "Unsupported channel count: %d\n", sfinfo.channels); - sf_close(sndfile); - return 0; - } - - /* Decode the whole audio file to a buffer. */ - membuf = malloc((size_t)(sfinfo.frames * sfinfo.channels) * sizeof(short)); - - num_frames = sf_readf_short(sndfile, membuf, sfinfo.frames); - if(num_frames < 1) - { - free(membuf); - sf_close(sndfile); - fprintf(stderr, "Failed to read samples in %s (%" PRId64 ")\n", filename, num_frames); - return 0; - } - num_bytes = (ALsizei)(num_frames * sfinfo.channels) * (ALsizei)sizeof(short); - - /* Buffer the audio data into a new buffer object, then free the data and - * close the file. - */ - buffer = 0; - alGenBuffers(1, &buffer); - alBufferData(buffer, format, membuf, num_bytes, sfinfo.samplerate); - - free(membuf); - sf_close(sndfile); - - /* Check if an error occured, and clean up if so. */ - err = alGetError(); - if(err != AL_NO_ERROR) - { - fprintf(stderr, "OpenAL Error: %s\n", alGetString(err)); - if(buffer && alIsBuffer(buffer)) - alDeleteBuffers(1, &buffer); - return 0; - } - - return buffer; -} - - -int main(int argc, char **argv) -{ - ALuint source, buffer; - ALfloat offset; - ALenum state; - - /* Print out usage if no arguments were specified */ - if(argc < 2) - { - fprintf(stderr, "Usage: %s [-device ] \n", argv[0]); - return 1; - } - - /* Initialize OpenAL. */ - argv++; argc--; - if(InitAL(&argv, &argc) != 0) - return 1; - - /* Load the sound into a buffer. */ - buffer = LoadSound(argv[0]); - if(!buffer) - { - CloseAL(); - return 1; - } - - /* Create the source to play the sound with. */ - source = 0; - alGenSources(1, &source); - alSourcei(source, AL_BUFFER, (ALint)buffer); - assert(alGetError()==AL_NO_ERROR && "Failed to setup sound source"); - - /* Play the sound until it finishes. */ - alSourcePlay(source); - do { - al_nssleep(10000000); - alGetSourcei(source, AL_SOURCE_STATE, &state); - - /* Get the source offset. */ - alGetSourcef(source, AL_SEC_OFFSET, &offset); - printf("\rOffset: %f ", offset); - fflush(stdout); - } while(alGetError() == AL_NO_ERROR && state == AL_PLAYING); - printf("\n"); - - /* All done. Delete resources, and close down OpenAL. */ - alDeleteSources(1, &source); - alDeleteBuffers(1, &buffer); - - CloseAL(); - - return 0; -} diff --git a/examples/alrecord.c b/examples/alrecord.c deleted file mode 100644 index 03894493..00000000 --- a/examples/alrecord.c +++ /dev/null @@ -1,403 +0,0 @@ -/* - * OpenAL Recording Example - * - * Copyright (c) 2017 by Chris Robinson - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -/* This file contains a relatively simple recorder. */ - -#include -#include -#include -#include - -#include "AL/al.h" -#include "AL/alc.h" -#include "AL/alext.h" - -#include "common/alhelpers.h" - -#include "win_main_utf8.h" - - -#if defined(_WIN64) -#define SZFMT "%I64u" -#elif defined(_WIN32) -#define SZFMT "%u" -#else -#define SZFMT "%zu" -#endif - - -#if defined(_MSC_VER) && (_MSC_VER < 1900) -static float msvc_strtof(const char *str, char **end) -{ return (float)strtod(str, end); } -#define strtof msvc_strtof -#endif - - -static void fwrite16le(ALushort val, FILE *f) -{ - ALubyte data[2]; - data[0] = (ALubyte)(val&0xff); - data[1] = (ALubyte)(val>>8); - fwrite(data, 1, 2, f); -} - -static void fwrite32le(ALuint val, FILE *f) -{ - ALubyte data[4]; - data[0] = (ALubyte)(val&0xff); - data[1] = (ALubyte)((val>>8)&0xff); - data[2] = (ALubyte)((val>>16)&0xff); - data[3] = (ALubyte)(val>>24); - fwrite(data, 1, 4, f); -} - - -typedef struct Recorder { - ALCdevice *mDevice; - - FILE *mFile; - long mDataSizeOffset; - ALuint mDataSize; - float mRecTime; - - ALuint mChannels; - ALuint mBits; - ALuint mSampleRate; - ALuint mFrameSize; - ALbyte *mBuffer; - ALsizei mBufferSize; -} Recorder; - -int main(int argc, char **argv) -{ - static const char optlist[] = -" --channels/-c Set channel count (1 or 2)\n" -" --bits/-b Set channel count (8, 16, or 32)\n" -" --rate/-r Set sample rate (8000 to 96000)\n" -" --time/-t