update sdl Merge commit '644725478f4de0f074a6834e8423ac36dce3974f'

This commit is contained in:
Green Sky 2023-09-23 18:53:11 +02:00
commit dd316d2589
No known key found for this signature in database
172 changed files with 7495 additions and 4062 deletions

View File

@ -1,12 +0,0 @@
*.c text
*.cpp text
*.h text
*.cmake text
*.py text
*.txt text
*.sh text
*.vcxproj text eol=crlf
*.sln text eol=crlf
*.filters text eol=crlf
*.appxmanifest text eol=crlf
*.pbxproj text

View File

@ -25,7 +25,7 @@ jobs:
-DSDL_WERROR=ON \
-DSDL_TESTS=ON \
-DSDL_INSTALL_TESTS=ON \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_BUILD_TYPE=Debug \
-DCMAKE_INSTALL_PREFIX=prefix \
-GNinja
- name: Build (CMake)
@ -42,11 +42,11 @@ jobs:
cmake --install build/
- name: Package (CPack)
run: |
cmake --build build/ --config Release --target package
cmake --build build/ --config Debug --target package
- name: Verify CMake configuration files
run: |
emcmake cmake -S cmake/test -B cmake_config_build \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_BUILD_TYPE=Debug \
-DSDL_VENDOR_INFO="Github Workflow" \
-DTEST_SHARED=FALSE \
-DCMAKE_PREFIX_PATH=${{ env.SDL3_DIR }}

View File

@ -52,7 +52,7 @@ jobs:
sudo apt-get update
sudo apt-get install build-essential git \
pkg-config cmake ninja-build gnome-desktop-testing libasound2-dev libpulse-dev \
libaudio-dev libjack-dev libsndio-dev libsamplerate0-dev libx11-dev libxext-dev \
libaudio-dev libjack-dev libsndio-dev libusb-1.0-0-dev libx11-dev libxext-dev \
libxrandr-dev libxcursor-dev libxfixes-dev libxi-dev libxss-dev libwayland-dev \
libxkbcommon-dev libdrm-dev libgbm-dev libgl1-mesa-dev libgles2-mesa-dev \
libegl1-mesa-dev libdbus-1-dev libibus-1.0-dev libudev-dev fcitx-libs-dev
@ -111,7 +111,7 @@ jobs:
${{ matrix.platform.source_cmd }}
set -eu
export SDL_TESTS_QUICK=1
ctest -VV --test-dir build/
ctest -VV --test-dir build/ -j2
if test "${{ runner.os }}" = "Linux"; then
# This should show us the SDL_REVISION
strings build/libSDL3.so.0 | grep SDL-

View File

@ -61,7 +61,7 @@ jobs:
if: "! contains(matrix.platform.name, 'ARM')"
run: |
$env:SDL_TESTS_QUICK=1
ctest -VV --test-dir build/ -C Release
ctest -VV --test-dir build/ -C Release -j2
- name: Install (CMake)
run: |
echo "SDL3_DIR=$Env:GITHUB_WORKSPACE/prefix" >> $Env:GITHUB_ENV

View File

@ -4,6 +4,9 @@ if(CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_CURRENT_BINARY_DIR)
message(FATAL_ERROR "Prevented in-tree build. Please create a build directory outside of the SDL source code and run \"cmake -S ${CMAKE_SOURCE_DIR} -B .\" from there")
endif()
# MSVC runtime library flags are selected by an abstraction.
set(CMAKE_POLICY_DEFAULT_CMP0091 NEW)
# See docs/release_checklist.md
project(SDL3 LANGUAGES C CXX VERSION "3.0.0")
@ -112,8 +115,8 @@ endif()
# for systems without support. It's not currently enough to not use
# pthread functions in a pthread-build; it won't start up on unsupported
# browsers. As such, you have to explicitly enable it on Emscripten builds
# for the time being. This default with change to ON once this becomes
# commonly supported in browsers or the Emscripten teams makes a single
# for the time being. This default will change to ON once this becomes
# commonly supported in browsers or the Emscripten team makes a single
# binary work everywhere.
if (UNIX_OR_MAC_SYS AND NOT EMSCRIPTEN)
set(SDL_PTHREADS_DEFAULT ON)
@ -137,14 +140,6 @@ else()
set(SDL_HIDAPI_LIBUSB_AVAILABLE TRUE)
endif()
# On the other hand, *BSD specifically uses libusb only, so we make a special
# case just for them.
if(FREEBSD OR NETBSD OR OPENBSD OR BSDI)
set(SDL_HIDAPI_LIBUSB_DEFAULT TRUE)
else()
set(SDL_HIDAPI_LIBUSB_DEFAULT FALSE)
endif()
set(SDL_ASSEMBLY_DEFAULT OFF)
if(USE_CLANG OR USE_GCC OR USE_INTELCC OR MSVC_VERSION GREATER 1400)
set(SDL_ASSEMBLY_DEFAULT ON)
@ -166,6 +161,9 @@ endif()
if(MSVC)
option(SDL_FORCE_STATIC_VCRT "Force /MT for static VC runtimes" OFF)
if(SDL_FORCE_STATIC_VCRT)
if(NOT DEFINED CMAKE_MSVC_RUNTIME_LIBRARY)
set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
endif()
foreach(flag_var
CMAKE_C_FLAGS CMAKE_C_FLAGS_DEBUG CMAKE_C_FLAGS_RELEASE
CMAKE_C_FLAGS_MINSIZEREL CMAKE_C_FLAGS_RELWITHDEBINFO)
@ -349,7 +347,8 @@ set_option(SDL_OFFSCREEN "Use offscreen video driver" ON)
option_string(SDL_BACKGROUNDING_SIGNAL "number to use for magic backgrounding signal or 'OFF'" OFF)
option_string(SDL_FOREGROUNDING_SIGNAL "number to use for magic foregrounding signal or 'OFF'" OFF)
dep_option(SDL_HIDAPI "Enable the HIDAPI subsystem" ON "NOT VISIONOS" OFF)
dep_option(SDL_HIDAPI_LIBUSB "Use libusb for low level joystick drivers" ${SDL_HIDAPI_LIBUSB_DEFAULT} "SDL_HIDAPI;${SDL_HIDAPI_LIBUSB_AVAILABLE}" OFF)
dep_option(SDL_HIDAPI_LIBUSB "Use libusb for low level joystick drivers" ON SDL_HIDAPI_LIBUSB_AVAILABLE OFF)
dep_option(SDL_HIDAPI_LIBUSB_SHARED "Dynamically load libusb support" ON SDL_HIDAPI_LIBUSB OFF)
dep_option(SDL_HIDAPI_JOYSTICK "Use HIDAPI for low level joystick drivers" ON SDL_HIDAPI OFF)
dep_option(SDL_VIRTUAL_JOYSTICK "Enable the virtual-joystick driver" ON SDL_HIDAPI OFF)
set_option(SDL_LIBUDEV "Enable libudev support" ON)
@ -3367,6 +3366,7 @@ if(NOT SDL_DISABLE_INSTALL)
SDL_generate_manpages(
SYMBOL "SDL_Init"
WIKIHEADERS_PL_PATH "${CMAKE_CURRENT_SOURCE_DIR}/build-scripts/wikiheaders.pl"
REVISION "${SDL_REVISION}"
)
if(TARGET SDL3-javadoc)
set(SDL_INSTALL_JAVADOCDIR "${CMAKE_INSTALL_DATAROOTDIR}/javadoc" CACHE PATH "Path where to install SDL3 javadoc")

View File

@ -10,7 +10,8 @@ emulators, and popular games including Valve's award winning catalog
and many Humble Bundle games.
More extensive documentation is available in the docs directory, starting
with README.md
with [README.md](docs/README.md). If you are migrating to SDL 3.0 from SDL 2.0,
the changes are extensively documented in [README-migration.md](docs/README-migration.md).
Enjoy!

View File

@ -370,6 +370,8 @@
<ClInclude Include="..\..\src\audio\SDL_audio_c.h" />
<ClInclude Include="..\..\src\audio\SDL_audiodev_c.h" />
<ClInclude Include="..\..\src\audio\SDL_sysaudio.h" />
<ClInclude Include="..\..\src\audio\SDL_audioqueue.h" />
<ClInclude Include="..\..\src\audio\SDL_audioresample.h" />
<ClInclude Include="..\..\src\audio\SDL_wave.h" />
<ClInclude Include="..\..\src\audio\wasapi\SDL_wasapi.h" />
<ClInclude Include="..\..\src\core\gdk\SDL_gdk.h" />
@ -438,7 +440,6 @@
<ClInclude Include="..\..\src\render\software\SDL_rotate.h" />
<ClInclude Include="..\..\src\render\software\SDL_triangle.h" />
<ClInclude Include="..\..\src\SDL_assert_c.h" />
<ClInclude Include="..\..\src\SDL_dataqueue.h" />
<ClInclude Include="..\..\src\SDL_error_c.h" />
<ClCompile Include="..\..\src\core\gdk\SDL_gdk.cpp">
<PrecompiledHeaderOutputFile Condition="'$(Configuration)|$(Platform)'=='Debug|Gaming.Desktop.x64'">$(IntDir)$(TargetName)_cpp.pch</PrecompiledHeaderOutputFile>
@ -550,6 +551,8 @@
<ClCompile Include="..\..\src\audio\SDL_audiocvt.c" />
<ClCompile Include="..\..\src\audio\SDL_audiodev.c" />
<ClCompile Include="..\..\src\audio\SDL_audiotypecvt.c" />
<ClCompile Include="..\..\src\audio\SDL_audioqueue.c" />
<ClCompile Include="..\..\src\audio\SDL_audioresample.c" />
<ClCompile Include="..\..\src\audio\SDL_mixer.c" />
<ClCompile Include="..\..\src\audio\SDL_wave.c" />
<ClCompile Include="..\..\src\audio\wasapi\SDL_wasapi.c" />
@ -582,7 +585,7 @@
<ClCompile Include="..\..\src\events\SDL_touch.c" />
<ClCompile Include="..\..\src\events\SDL_windowevents.c" />
<ClCompile Include="..\..\src\file\SDL_rwops.c" />
<ClCompile Include="..\..\src\filesystem\windows\SDL_sysfilesystem.c" />
<ClCompile Include="..\..\src\filesystem\gdk\SDL_sysfilesystem.c" />
<ClCompile Include="..\..\src\haptic\dummy\SDL_syshaptic.c" />
<ClCompile Include="..\..\src\haptic\SDL_haptic.c" />
<ClCompile Include="..\..\src\haptic\windows\SDL_dinputhaptic.c" />
@ -707,7 +710,6 @@
<ClCompile Include="..\..\src\render\software\SDL_triangle.c" />
<ClCompile Include="..\..\src\SDL.c" />
<ClCompile Include="..\..\src\SDL_assert.c" />
<ClCompile Include="..\..\src\SDL_dataqueue.c" />
<ClCompile Include="..\..\src\SDL_list.c" />
<ClCompile Include="..\..\src\SDL_error.c" />
<ClCompile Include="..\..\src\SDL_hints.c" />

View File

@ -31,7 +31,7 @@
<Filter Include="filesystem">
<UniqueIdentifier>{377061e4-3856-4f05-b916-0d3b360df0f6}</UniqueIdentifier>
</Filter>
<Filter Include="filesystem\windows">
<Filter Include="filesystem\gdk">
<UniqueIdentifier>{226a6643-1c65-4c7f-92aa-861313d974bb}</UniqueIdentifier>
</Filter>
<Filter Include="haptic">
@ -396,7 +396,6 @@
<ClInclude Include="..\..\include\SDL3\SDL_vulkan.h">
<Filter>API Headers</Filter>
</ClInclude>
<ClInclude Include="..\..\src\SDL_dataqueue.h" />
<ClInclude Include="..\..\src\SDL_error_c.h" />
<ClInclude Include="..\..\src\SDL_list.h" />
<ClInclude Include="..\..\include\SDL3\SDL_metal.h">
@ -420,6 +419,12 @@
<ClInclude Include="..\..\src\audio\SDL_sysaudio.h">
<Filter>audio</Filter>
</ClInclude>
<ClInclude Include="..\..\src\audio\SDL_audioqueue.h">
<Filter>audio</Filter>
</ClInclude>
<ClInclude Include="..\..\src\audio\SDL_audioresample.h">
<Filter>audio</Filter>
</ClInclude>
<ClInclude Include="..\..\src\core\windows\SDL_hid.h">
<Filter>core\windows</Filter>
</ClInclude>
@ -838,7 +843,6 @@
<ClCompile Include="..\..\src\audio\wasapi\SDL_wasapi.c" />
<ClCompile Include="..\..\src\SDL.c" />
<ClCompile Include="..\..\src\SDL_assert.c" />
<ClCompile Include="..\..\src\SDL_dataqueue.c" />
<ClCompile Include="..\..\src\SDL_error.c" />
<ClCompile Include="..\..\src\SDL_guid.c" />
<ClCompile Include="..\..\src\SDL_hints.c" />
@ -856,6 +860,12 @@
<ClCompile Include="..\..\src\audio\SDL_audiotypecvt.c">
<Filter>audio</Filter>
</ClCompile>
<ClCompile Include="..\..\src\audio\SDL_audioqueue.c">
<Filter>audio</Filter>
</ClCompile>
<ClCompile Include="..\..\src\audio\SDL_audioresample.c">
<Filter>audio</Filter>
</ClCompile>
<ClCompile Include="..\..\src\audio\SDL_wave.c">
<Filter>audio</Filter>
</ClCompile>
@ -916,8 +926,8 @@
<ClCompile Include="..\..\src\file\SDL_rwops.c">
<Filter>file</Filter>
</ClCompile>
<ClCompile Include="..\..\src\filesystem\windows\SDL_sysfilesystem.c">
<Filter>filesystem\windows</Filter>
<ClCompile Include="..\..\src\filesystem\gdk\SDL_sysfilesystem.c">
<Filter>filesystem\gdk</Filter>
</ClCompile>
<ClCompile Include="..\..\src\haptic\SDL_haptic.c">
<Filter>haptic</Filter>

View File

@ -94,6 +94,11 @@
<ClInclude Include="..\src\audio\SDL_audiodev_c.h" />
<ClInclude Include="..\src\audio\SDL_audio_c.h" />
<ClInclude Include="..\src\audio\SDL_sysaudio.h" />
<<<<<<< HEAD
=======
<ClInclude Include="..\src\audio\SDL_audioqueue.h" />
<ClInclude Include="..\src\audio\SDL_audioresample.h" />
>>>>>>> 644725478f4de0f074a6834e8423ac36dce3974f
<ClInclude Include="..\src\audio\SDL_wave.h" />
<ClInclude Include="..\src\audio\wasapi\SDL_wasapi.h" />
<ClInclude Include="..\src\core\windows\SDL_directx.h" />
@ -147,7 +152,10 @@
<ClInclude Include="..\src\render\software\SDL_rotate.h" />
<ClInclude Include="..\src\render\software\SDL_triangle.h" />
<ClInclude Include="..\src\SDL_assert_c.h" />
<<<<<<< HEAD
<ClInclude Include="..\src\SDL_dataqueue.h" />
=======
>>>>>>> 644725478f4de0f074a6834e8423ac36dce3974f
<ClInclude Include="..\src\SDL_error_c.h" />
<ClInclude Include="..\src\SDL_fatal.h" />
<ClInclude Include="..\src\SDL_hints_c.h" />
@ -194,6 +202,11 @@
<ClCompile Include="..\src\audio\SDL_audiocvt.c" />
<ClCompile Include="..\src\audio\SDL_audiodev.c" />
<ClCompile Include="..\src\audio\SDL_audiotypecvt.c" />
<<<<<<< HEAD
=======
<ClCompile Include="..\src\audio\SDL_audioqueue.c" />
<ClCompile Include="..\src\audio\SDL_audioresample.c" />
>>>>>>> 644725478f4de0f074a6834e8423ac36dce3974f
<ClCompile Include="..\src\audio\SDL_mixer.c" />
<ClCompile Include="..\src\audio\SDL_wave.c" />
<ClCompile Include="..\src\audio\wasapi\SDL_wasapi.c" />
@ -388,7 +401,10 @@
<ClCompile Include="..\src\render\software\SDL_triangle.c" />
<ClCompile Include="..\src\SDL.c" />
<ClCompile Include="..\src\SDL_assert.c" />
<<<<<<< HEAD
<ClCompile Include="..\src\SDL_dataqueue.c" />
=======
>>>>>>> 644725478f4de0f074a6834e8423ac36dce3974f
<ClCompile Include="..\src\SDL_list.c" />
<ClCompile Include="..\src\SDL_error.c" />
<ClCompile Include="..\src\SDL_guid.c" />

View File

@ -183,6 +183,15 @@
<ClInclude Include="..\src\audio\SDL_sysaudio.h">
<Filter>Source Files</Filter>
</ClInclude>
<<<<<<< HEAD
=======
<ClInclude Include="..\src\audio\SDL_audioqueue.h">
<Filter>Source Files</Filter>
</ClInclude>
<ClInclude Include="..\src\audio\SDL_audioresample.h">
<Filter>Source Files</Filter>
</ClInclude>
>>>>>>> 644725478f4de0f074a6834e8423ac36dce3974f
<ClInclude Include="..\src\audio\SDL_wave.h">
<Filter>Source Files</Filter>
</ClInclude>
@ -408,9 +417,12 @@
<ClInclude Include="..\src\video\winrt\SDL_winrtgamebar_cpp.h">
<Filter>Source Files</Filter>
</ClInclude>
<<<<<<< HEAD
<ClInclude Include="..\src\SDL_dataqueue.h">
<Filter>Source Files</Filter>
</ClInclude>
=======
>>>>>>> 644725478f4de0f074a6834e8423ac36dce3974f
<ClInclude Include="..\src\SDL_list.h">
<Filter>Source Files</Filter>
</ClInclude>
@ -474,6 +486,15 @@
<ClCompile Include="..\src\audio\SDL_audiotypecvt.c">
<Filter>Source Files</Filter>
</ClCompile>
<<<<<<< HEAD
=======
<ClCompile Include="..\src\audio\SDL_audioqueue.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\src\audio\SDL_audioresample.c">
<Filter>Source Files</Filter>
</ClCompile>
>>>>>>> 644725478f4de0f074a6834e8423ac36dce3974f
<ClCompile Include="..\src\audio\SDL_mixer.c">
<Filter>Source Files</Filter>
</ClCompile>
@ -786,9 +807,12 @@
<ClCompile Include="..\src\video\winrt\SDL_winrtgamebar.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<<<<<<< HEAD
<ClCompile Include="..\src\SDL_dataqueue.c">
<Filter>Source Files</Filter>
</ClCompile>
=======
>>>>>>> 644725478f4de0f074a6834e8423ac36dce3974f
<ClCompile Include="..\src\SDL_list.c">
<Filter>Source Files</Filter>
</ClCompile>

View File

@ -319,6 +319,8 @@
<ClInclude Include="..\..\src\audio\SDL_audio_c.h" />
<ClInclude Include="..\..\src\audio\SDL_audiodev_c.h" />
<ClInclude Include="..\..\src\audio\SDL_sysaudio.h" />
<ClInclude Include="..\..\src\audio\SDL_audioqueue.h" />
<ClInclude Include="..\..\src\audio\SDL_audioresample.h" />
<ClInclude Include="..\..\src\audio\SDL_wave.h" />
<ClInclude Include="..\..\src\audio\wasapi\SDL_wasapi.h" />
<ClInclude Include="..\..\src\core\windows\SDL_directx.h" />
@ -385,7 +387,6 @@
<ClInclude Include="..\..\src\render\software\SDL_rotate.h" />
<ClInclude Include="..\..\src\render\software\SDL_triangle.h" />
<ClInclude Include="..\..\src\SDL_assert_c.h" />
<ClInclude Include="..\..\src\SDL_dataqueue.h" />
<ClInclude Include="..\..\src\SDL_error_c.h" />
<ClCompile Include="..\..\src\core\windows\pch.c">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Create</PrecompiledHeader>
@ -476,6 +477,8 @@
<ClCompile Include="..\..\src\audio\SDL_audiocvt.c" />
<ClCompile Include="..\..\src\audio\SDL_audiodev.c" />
<ClCompile Include="..\..\src\audio\SDL_audiotypecvt.c" />
<ClCompile Include="..\..\src\audio\SDL_audioqueue.c" />
<ClCompile Include="..\..\src\audio\SDL_audioresample.c" />
<ClCompile Include="..\..\src\audio\SDL_mixer.c" />
<ClCompile Include="..\..\src\audio\SDL_wave.c" />
<ClCompile Include="..\..\src\audio\wasapi\SDL_wasapi.c" />
@ -585,7 +588,6 @@
<ClCompile Include="..\..\src\render\software\SDL_triangle.c" />
<ClCompile Include="..\..\src\SDL.c" />
<ClCompile Include="..\..\src\SDL_assert.c" />
<ClCompile Include="..\..\src\SDL_dataqueue.c" />
<ClCompile Include="..\..\src\SDL_list.c" />
<ClCompile Include="..\..\src\SDL_error.c" />
<ClCompile Include="..\..\src\SDL_hints.c" />

View File

@ -387,7 +387,6 @@
<ClInclude Include="..\..\include\SDL3\SDL_vulkan.h">
<Filter>API Headers</Filter>
</ClInclude>
<ClInclude Include="..\..\src\SDL_dataqueue.h" />
<ClInclude Include="..\..\src\SDL_error_c.h" />
<ClInclude Include="..\..\src\SDL_list.h" />
<ClInclude Include="..\..\include\SDL3\SDL_metal.h">
@ -411,6 +410,12 @@
<ClInclude Include="..\..\src\audio\SDL_sysaudio.h">
<Filter>audio</Filter>
</ClInclude>
<ClInclude Include="..\..\src\audio\SDL_audioqueue.h">
<Filter>audio</Filter>
</ClInclude>
<ClInclude Include="..\..\src\audio\SDL_audioresample.h">
<Filter>audio</Filter>
</ClInclude>
<ClInclude Include="..\..\src\core\windows\SDL_hid.h">
<Filter>core\windows</Filter>
</ClInclude>
@ -817,7 +822,6 @@
<ClCompile Include="..\..\src\audio\wasapi\SDL_wasapi.c" />
<ClCompile Include="..\..\src\SDL.c" />
<ClCompile Include="..\..\src\SDL_assert.c" />
<ClCompile Include="..\..\src\SDL_dataqueue.c" />
<ClCompile Include="..\..\src\SDL_error.c" />
<ClCompile Include="..\..\src\SDL_guid.c" />
<ClCompile Include="..\..\src\SDL_hints.c" />
@ -835,6 +839,12 @@
<ClCompile Include="..\..\src\audio\SDL_audiotypecvt.c">
<Filter>audio</Filter>
</ClCompile>
<ClCompile Include="..\..\src\audio\SDL_audioqueue.c">
<Filter>audio</Filter>
</ClCompile>
<ClCompile Include="..\..\src\audio\SDL_audioresample.c">
<Filter>audio</Filter>
</ClCompile>
<ClCompile Include="..\..\src\audio\SDL_wave.c">
<Filter>audio</Filter>
</ClCompile>

View File

@ -63,7 +63,6 @@
A75FDBB823E4CBC700529352 /* ReadMe.txt in Resources */ = {isa = PBXBuildFile; fileRef = F59C710300D5CB5801000001 /* ReadMe.txt */; };
A75FDBC523EA380300529352 /* SDL_hidapi_rumble.h in Headers */ = {isa = PBXBuildFile; fileRef = A75FDBC323EA380300529352 /* SDL_hidapi_rumble.h */; };
A75FDBCE23EA380300529352 /* SDL_hidapi_rumble.c in Sources */ = {isa = PBXBuildFile; fileRef = A75FDBC423EA380300529352 /* SDL_hidapi_rumble.c */; };
A7D8A94523E2514000DCD162 /* SDL_dataqueue.h in Headers */ = {isa = PBXBuildFile; fileRef = A7D8A57023E2513D00DCD162 /* SDL_dataqueue.h */; };
A7D8A94B23E2514000DCD162 /* SDL.c in Sources */ = {isa = PBXBuildFile; fileRef = A7D8A57123E2513D00DCD162 /* SDL.c */; };
A7D8A95123E2514000DCD162 /* SDL_spinlock.c in Sources */ = {isa = PBXBuildFile; fileRef = A7D8A57323E2513D00DCD162 /* SDL_spinlock.c */; };
A7D8A95723E2514000DCD162 /* SDL_atomic.c in Sources */ = {isa = PBXBuildFile; fileRef = A7D8A57423E2513D00DCD162 /* SDL_atomic.c */; };
@ -315,7 +314,6 @@
A7D8BAFD23E2514500DCD162 /* s_floor.c in Sources */ = {isa = PBXBuildFile; fileRef = A7D8A92523E2514000DCD162 /* s_floor.c */; };
A7D8BB0323E2514500DCD162 /* math_libm.h in Headers */ = {isa = PBXBuildFile; fileRef = A7D8A92623E2514000DCD162 /* math_libm.h */; };
A7D8BB0923E2514500DCD162 /* k_tan.c in Sources */ = {isa = PBXBuildFile; fileRef = A7D8A92723E2514000DCD162 /* k_tan.c */; };
A7D8BB0F23E2514500DCD162 /* SDL_dataqueue.c in Sources */ = {isa = PBXBuildFile; fileRef = A7D8A92823E2514000DCD162 /* SDL_dataqueue.c */; };
A7D8BB1523E2514500DCD162 /* SDL_mouse.c in Sources */ = {isa = PBXBuildFile; fileRef = A7D8A92A23E2514000DCD162 /* SDL_mouse.c */; };
A7D8BB1B23E2514500DCD162 /* SDL_mouse_c.h in Headers */ = {isa = PBXBuildFile; fileRef = A7D8A92B23E2514000DCD162 /* SDL_mouse_c.h */; };
A7D8BB2123E2514500DCD162 /* scancodes_windows.h in Headers */ = {isa = PBXBuildFile; fileRef = A7D8A92C23E2514000DCD162 /* scancodes_windows.h */; };
@ -371,6 +369,12 @@
F31A92C828D4CB39003BFD6A /* SDL_offscreenopengles.h in Headers */ = {isa = PBXBuildFile; fileRef = F31A92C628D4CB39003BFD6A /* SDL_offscreenopengles.h */; };
F31A92D228D4CB39003BFD6A /* SDL_offscreenopengles.c in Sources */ = {isa = PBXBuildFile; fileRef = F31A92C728D4CB39003BFD6A /* SDL_offscreenopengles.c */; };
F32305FF28939F6400E66D30 /* SDL_hidapi_combined.c in Sources */ = {isa = PBXBuildFile; fileRef = F32305FE28939F6400E66D30 /* SDL_hidapi_combined.c */; };
F32DDACF2AB795A30041EAA5 /* SDL_audio_channel_converters.h in Headers */ = {isa = PBXBuildFile; fileRef = F32DDAC92AB795A30041EAA5 /* SDL_audio_channel_converters.h */; };
F32DDAD02AB795A30041EAA5 /* SDL_audioresample.h in Headers */ = {isa = PBXBuildFile; fileRef = F32DDACA2AB795A30041EAA5 /* SDL_audioresample.h */; };
F32DDAD12AB795A30041EAA5 /* SDL_audioqueue.c in Sources */ = {isa = PBXBuildFile; fileRef = F32DDACB2AB795A30041EAA5 /* SDL_audioqueue.c */; };
F32DDAD22AB795A30041EAA5 /* SDL_audio_resampler_filter.h in Headers */ = {isa = PBXBuildFile; fileRef = F32DDACC2AB795A30041EAA5 /* SDL_audio_resampler_filter.h */; };
F32DDAD32AB795A30041EAA5 /* SDL_audioqueue.h in Headers */ = {isa = PBXBuildFile; fileRef = F32DDACD2AB795A30041EAA5 /* SDL_audioqueue.h */; };
F32DDAD42AB795A30041EAA5 /* SDL_audioresample.c in Sources */ = {isa = PBXBuildFile; fileRef = F32DDACE2AB795A30041EAA5 /* SDL_audioresample.c */; };
F34B9895291DEFF500AAC96E /* SDL_hidapi_steam.c in Sources */ = {isa = PBXBuildFile; fileRef = A75FDAAC23E2795C00529352 /* SDL_hidapi_steam.c */; };
F36C7AD1294BA009004D61C3 /* SDL_runapp.c in Sources */ = {isa = PBXBuildFile; fileRef = F36C7AD0294BA009004D61C3 /* SDL_runapp.c */; };
F376F6552559B4E300CFC0BC /* SDL_hidapi.c in Sources */ = {isa = PBXBuildFile; fileRef = A7D8A81423E2513F00DCD162 /* SDL_hidapi.c */; };
@ -531,7 +535,6 @@
A75FDBA723E4CB6F00529352 /* LICENSE.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = LICENSE.txt; sourceTree = "<group>"; };
A75FDBC323EA380300529352 /* SDL_hidapi_rumble.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SDL_hidapi_rumble.h; sourceTree = "<group>"; };
A75FDBC423EA380300529352 /* SDL_hidapi_rumble.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = SDL_hidapi_rumble.c; sourceTree = "<group>"; };
A7D8A57023E2513D00DCD162 /* SDL_dataqueue.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SDL_dataqueue.h; sourceTree = "<group>"; };
A7D8A57123E2513D00DCD162 /* SDL.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = SDL.c; sourceTree = "<group>"; };
A7D8A57323E2513D00DCD162 /* SDL_spinlock.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = SDL_spinlock.c; sourceTree = "<group>"; };
A7D8A57423E2513D00DCD162 /* SDL_atomic.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = SDL_atomic.c; sourceTree = "<group>"; };
@ -812,7 +815,6 @@
A7D8A92523E2514000DCD162 /* s_floor.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = s_floor.c; sourceTree = "<group>"; };
A7D8A92623E2514000DCD162 /* math_libm.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = math_libm.h; sourceTree = "<group>"; };
A7D8A92723E2514000DCD162 /* k_tan.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = k_tan.c; sourceTree = "<group>"; };
A7D8A92823E2514000DCD162 /* SDL_dataqueue.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = SDL_dataqueue.c; sourceTree = "<group>"; };
A7D8A92A23E2514000DCD162 /* SDL_mouse.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = SDL_mouse.c; sourceTree = "<group>"; };
A7D8A92B23E2514000DCD162 /* SDL_mouse_c.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SDL_mouse_c.h; sourceTree = "<group>"; };
A7D8A92C23E2514000DCD162 /* scancodes_windows.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = scancodes_windows.h; sourceTree = "<group>"; };
@ -843,6 +845,12 @@
F31A92C628D4CB39003BFD6A /* SDL_offscreenopengles.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SDL_offscreenopengles.h; sourceTree = "<group>"; };
F31A92C728D4CB39003BFD6A /* SDL_offscreenopengles.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = SDL_offscreenopengles.c; sourceTree = "<group>"; };
F32305FE28939F6400E66D30 /* SDL_hidapi_combined.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = SDL_hidapi_combined.c; sourceTree = "<group>"; };
F32DDAC92AB795A30041EAA5 /* SDL_audio_channel_converters.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SDL_audio_channel_converters.h; sourceTree = "<group>"; };
F32DDACA2AB795A30041EAA5 /* SDL_audioresample.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SDL_audioresample.h; sourceTree = "<group>"; };
F32DDACB2AB795A30041EAA5 /* SDL_audioqueue.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = SDL_audioqueue.c; sourceTree = "<group>"; };
F32DDACC2AB795A30041EAA5 /* SDL_audio_resampler_filter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SDL_audio_resampler_filter.h; sourceTree = "<group>"; };
F32DDACD2AB795A30041EAA5 /* SDL_audioqueue.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SDL_audioqueue.h; sourceTree = "<group>"; };
F32DDACE2AB795A30041EAA5 /* SDL_audioresample.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = SDL_audioresample.c; sourceTree = "<group>"; };
F36C7AD0294BA009004D61C3 /* SDL_runapp.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = SDL_runapp.c; sourceTree = "<group>"; };
F376F6182559B29300CFC0BC /* OpenGLES.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = OpenGLES.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS14.1.sdk/System/Library/Frameworks/OpenGLES.framework; sourceTree = DEVELOPER_DIR; };
F376F61A2559B2AF00CFC0BC /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = System/iOSSupport/System/Library/Frameworks/UIKit.framework; sourceTree = SDKROOT; };
@ -1108,8 +1116,6 @@
A7D8A5EB23E2513D00DCD162 /* video */,
A7D8A7F523E2513F00DCD162 /* SDL_assert_c.h */,
A7D8A94423E2514000DCD162 /* SDL_assert.c */,
A7D8A92823E2514000DCD162 /* SDL_dataqueue.c */,
A7D8A57023E2513D00DCD162 /* SDL_dataqueue.h */,
A7D8A57523E2513D00DCD162 /* SDL_error_c.h */,
A7D8A8BF23E2513F00DCD162 /* SDL_error.c */,
F382071C284F362F004DD584 /* SDL_guid.c */,
@ -1789,10 +1795,16 @@
A7D8A8AF23E2513F00DCD162 /* disk */,
A7D8A87023E2513F00DCD162 /* dummy */,
A7D8A87323E2513F00DCD162 /* SDL_audio_c.h */,
F32DDAC92AB795A30041EAA5 /* SDL_audio_channel_converters.h */,
F32DDACC2AB795A30041EAA5 /* SDL_audio_resampler_filter.h */,
A7D8A8B823E2513F00DCD162 /* SDL_audio.c */,
A7D8A8A123E2513F00DCD162 /* SDL_audiocvt.c */,
A7D8A87723E2513F00DCD162 /* SDL_audiodev_c.h */,
A7D8A88F23E2513F00DCD162 /* SDL_audiodev.c */,
F32DDACB2AB795A30041EAA5 /* SDL_audioqueue.c */,
F32DDACD2AB795A30041EAA5 /* SDL_audioqueue.h */,
F32DDACE2AB795A30041EAA5 /* SDL_audioresample.c */,
F32DDACA2AB795A30041EAA5 /* SDL_audioresample.h */,
A7D8A8A023E2513F00DCD162 /* SDL_audiotypecvt.c */,
A7D8A86523E2513F00DCD162 /* SDL_mixer.c */,
A7D8A89F23E2513F00DCD162 /* SDL_sysaudio.h */,
@ -2064,13 +2076,13 @@
A7D8AF0023E2514100DCD162 /* SDL_cocoavideo.h in Headers */,
A7D8AEE823E2514100DCD162 /* SDL_cocoavulkan.h in Headers */,
A7D8AEFA23E2514100DCD162 /* SDL_cocoawindow.h in Headers */,
F32DDACF2AB795A30041EAA5 /* SDL_audio_channel_converters.h in Headers */,
F3F7D9D12933074E00816151 /* SDL_copying.h in Headers */,
A7D8B8CC23E2514400DCD162 /* SDL_coreaudio.h in Headers */,
A7D8A96F23E2514000DCD162 /* SDL_coremotionsensor.h in Headers */,
F3F7D9B92933074E00816151 /* SDL_cpuinfo.h in Headers */,
F3990E062A788303000D8759 /* SDL_hidapi_ios.h in Headers */,
A7D8B98023E2514400DCD162 /* SDL_d3dmath.h in Headers */,
A7D8A94523E2514000DCD162 /* SDL_dataqueue.h in Headers */,
A7D8B8A223E2514400DCD162 /* SDL_diskaudio.h in Headers */,
A7D8BB3F23E2514500DCD162 /* SDL_displayevents_c.h in Headers */,
A7D8BA1923E2514400DCD162 /* SDL_draw.h in Headers */,
@ -2080,6 +2092,7 @@
A7D8B79423E2514400DCD162 /* SDL_dummyaudio.h in Headers */,
A7D8A96323E2514000DCD162 /* SDL_dummysensor.h in Headers */,
A7D8AB0A23E2514100DCD162 /* SDL_dynapi.h in Headers */,
F32DDAD02AB795A30041EAA5 /* SDL_audioresample.h in Headers */,
A7D8AB1023E2514100DCD162 /* SDL_dynapi_overrides.h in Headers */,
A7D8AB1C23E2514100DCD162 /* SDL_dynapi_procs.h in Headers */,
F3F7D9252933074E00816151 /* SDL_egl.h in Headers */,
@ -2143,6 +2156,7 @@
F3F7D9392933074E00816151 /* SDL_opengles2_gl2ext.h in Headers */,
F3F7D9692933074E00816151 /* SDL_opengles2_gl2platform.h in Headers */,
F3F7D9092933074E00816151 /* SDL_opengles2_khrplatform.h in Headers */,
F32DDAD22AB795A30041EAA5 /* SDL_audio_resampler_filter.h in Headers */,
F3F7D9192933074E00816151 /* SDL_pixels.h in Headers */,
A7D8B2C023E2514200DCD162 /* SDL_pixels_c.h in Headers */,
F3F7D8F12933074E00816151 /* SDL_platform.h in Headers */,
@ -2249,6 +2263,7 @@
A7D8B28423E2514200DCD162 /* vulkan_macos.h in Headers */,
A7D8B29623E2514200DCD162 /* vulkan_mir.h in Headers */,
A7D8B25A23E2514200DCD162 /* vulkan_vi.h in Headers */,
F32DDAD32AB795A30041EAA5 /* SDL_audioqueue.h in Headers */,
A7D8B27823E2514200DCD162 /* vulkan_wayland.h in Headers */,
A7D8B27E23E2514200DCD162 /* vulkan_win32.h in Headers */,
A7D8B29023E2514200DCD162 /* vulkan_xcb.h in Headers */,
@ -2385,6 +2400,7 @@
A7D8B41C23E2514300DCD162 /* SDL_systls.c in Sources */,
9846B07C287A9020000C35C8 /* SDL_hidapi_shield.c in Sources */,
A7D8BBD923E2574800DCD162 /* SDL_uikitmessagebox.m in Sources */,
F32DDAD42AB795A30041EAA5 /* SDL_audioresample.c in Sources */,
A7D8AD2923E2514100DCD162 /* SDL_vulkan_utils.c in Sources */,
A7D8A95123E2514000DCD162 /* SDL_spinlock.c in Sources */,
F34B9895291DEFF500AAC96E /* SDL_hidapi_steam.c in Sources */,
@ -2464,6 +2480,7 @@
A7D8AEE223E2514100DCD162 /* SDL_cocoashape.m in Sources */,
A7D8BBD323E2574800DCD162 /* SDL_uikitappdelegate.m in Sources */,
A7D8AEB823E2514100DCD162 /* SDL_cocoamouse.m in Sources */,
F32DDAD12AB795A30041EAA5 /* SDL_audioqueue.c in Sources */,
A7D8B8E423E2514400DCD162 /* SDL_error.c in Sources */,
A7D8AD6823E2514100DCD162 /* SDL_blit.c in Sources */,
A7D8B5BD23E2514300DCD162 /* SDL_rwops.c in Sources */,
@ -2552,7 +2569,6 @@
A7D8BBDB23E2574800DCD162 /* SDL_uikitmetalview.m in Sources */,
A7D8BB1523E2514500DCD162 /* SDL_mouse.c in Sources */,
A7D8BAD923E2514500DCD162 /* e_rem_pio2.c in Sources */,
A7D8BB0F23E2514500DCD162 /* SDL_dataqueue.c in Sources */,
F395C19C2569C68F00942BFF /* SDL_iokitjoystick.c in Sources */,
A7D8B4B223E2514300DCD162 /* SDL_sysjoystick.c in Sources */,
A7D8B3E023E2514300DCD162 /* SDL_cpuinfo.c in Sources */,

View File

@ -8,23 +8,23 @@ else {
}
android {
compileSdkVersion 31
if (buildAsApplication) {
namespace "org.libsdl.app"
}
compileSdkVersion 34
defaultConfig {
if (buildAsApplication) {
applicationId "org.libsdl.app"
}
minSdkVersion 16
targetSdkVersion 31
minSdkVersion 19
targetSdkVersion 34
versionCode 1
versionName "1.0"
externalNativeBuild {
ndkBuild {
arguments "APP_PLATFORM=android-16"
arguments "APP_PLATFORM=android-19"
// abiFilters 'armeabi-v7a', 'arm64-v8a', 'x86', 'x86_64'
abiFilters 'arm64-v8a'
}
cmake {
arguments "-DANDROID_APP_PLATFORM=android-16", "-DANDROID_STL=c++_static"
arguments "-DANDROID_APP_PLATFORM=android-19", "-DANDROID_STL=c++_static"
// abiFilters 'armeabi-v7a', 'arm64-v8a', 'x86', 'x86_64'
abiFilters 'arm64-v8a'
}
@ -54,7 +54,7 @@ android {
}
}
lintOptions {
lint {
abortOnError false
}

View File

@ -3,7 +3,6 @@
com.gamemaker.game
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.libsdl.app"
android:versionCode="1"
android:versionName="1.0"
android:installLocation="auto">

View File

@ -1416,23 +1416,6 @@ public class SDLActivity extends Activity implements View.OnSystemUiVisibilityCh
}
}
if ((source & InputDevice.SOURCE_KEYBOARD) == InputDevice.SOURCE_KEYBOARD) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
if (isTextInputEvent(event)) {
if (ic != null) {
ic.commitText(String.valueOf((char) event.getUnicodeChar()), 1);
} else {
SDLInputConnection.nativeCommitText(String.valueOf((char) event.getUnicodeChar()), 1);
}
}
onNativeKeyDown(keyCode);
return true;
} else if (event.getAction() == KeyEvent.ACTION_UP) {
onNativeKeyUp(keyCode);
return true;
}
}
if ((source & InputDevice.SOURCE_MOUSE) == InputDevice.SOURCE_MOUSE) {
// on some devices key events are sent for mouse BUTTON_BACK/FORWARD presses
// they are ignored here because sending them as mouse input to SDL is messy
@ -1447,6 +1430,21 @@ public class SDLActivity extends Activity implements View.OnSystemUiVisibilityCh
}
}
if (event.getAction() == KeyEvent.ACTION_DOWN) {
if (isTextInputEvent(event)) {
if (ic != null) {
ic.commitText(String.valueOf((char) event.getUnicodeChar()), 1);
} else {
SDLInputConnection.nativeCommitText(String.valueOf((char) event.getUnicodeChar()), 1);
}
}
onNativeKeyDown(keyCode);
return true;
} else if (event.getAction() == KeyEvent.ACTION_UP) {
onNativeKeyUp(keyCode);
return true;
}
return false;
}

View File

@ -6,7 +6,7 @@ buildscript {
google()
}
dependencies {
classpath 'com.android.tools.build:gradle:7.0.3'
classpath 'com.android.tools.build:gradle:8.1.1'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files

View File

@ -1,6 +1,6 @@
#Thu Nov 11 18:20:34 PST 2021
distributionBase=GRADLE_USER_HOME
distributionUrl=https\://services.gradle.org/distributions/gradle-7.3-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.1.1-bin.zip
distributionPath=wrapper/dists
zipStorePath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME

View File

@ -1069,11 +1069,6 @@ typedef SDL_GameControllerButton, SDL_GamepadButton;
- SDL_GameControllerButton
+ SDL_GamepadButton
@@
typedef SDL_GameControllerButtonBind, SDL_GamepadBinding;
@@
- SDL_GameControllerButtonBind
+ SDL_GamepadBinding
@@
@@
- SDL_GameControllerClose
+ SDL_CloseGamepad
@ -1115,16 +1110,6 @@ typedef SDL_GameControllerButtonBind, SDL_GamepadBinding;
(...)
@@
@@
- SDL_GameControllerGetBindForAxis
+ SDL_GetGamepadBindForAxis
(...)
@@
@@
- SDL_GameControllerGetBindForButton
+ SDL_GetGamepadBindForButton
(...)
@@
@@
- SDL_GameControllerGetButton
+ SDL_GetGamepadButton
(...)
@ -2591,51 +2576,51 @@ typedef SDL_cond, SDL_Condition;
@@
@@
- AUDIO_F32
+ SDL_AUDIO_F32
+ SDL_AUDIO_F32LE
@@
@@
- AUDIO_F32LSB
+ SDL_AUDIO_F32LSB
+ SDL_AUDIO_F32LE
@@
@@
- AUDIO_F32MSB
+ SDL_AUDIO_F32MSB
+ SDL_AUDIO_F32BE
@@
@@
- AUDIO_F32SYS
+ SDL_AUDIO_F32SYS
+ SDL_AUDIO_F32
@@
@@
- AUDIO_S16
+ SDL_AUDIO_S16
+ SDL_AUDIO_S16LE
@@
@@
- AUDIO_S16LSB
+ SDL_AUDIO_S16LSB
+ SDL_AUDIO_S16LE
@@
@@
- AUDIO_S16MSB
+ SDL_AUDIO_S16MSB
+ SDL_AUDIO_S16BE
@@
@@
- AUDIO_S16SYS
+ SDL_AUDIO_S16SYS
+ SDL_AUDIO_S16
@@
@@
- AUDIO_S32
+ SDL_AUDIO_S32
+ SDL_AUDIO_S32LE
@@
@@
- AUDIO_S32LSB
+ SDL_AUDIO_S32LSB
+ SDL_AUDIO_S32LE
@@
@@
- AUDIO_S32MSB
+ SDL_AUDIO_S32MSB
+ SDL_AUDIO_S32BE
@@
@@
- AUDIO_S32SYS
+ SDL_AUDIO_S32SYS
+ SDL_AUDIO_S32
@@
@@
- AUDIO_S8

View File

@ -0,0 +1,599 @@
#!/usr/bin/perl -w
# Add source files and headers to Xcode and Visual Studio projects.
# THIS IS NOT ROBUST, THIS IS JUST RYAN AVOIDING RUNNING BETWEEN
# THREE COMPUTERS AND A BUNCH OF DEVELOPMENT ENVIRONMENTS TO ADD
# A STUPID FILE TO THE BUILD.
use warnings;
use strict;
use File::Basename;
my %xcode_references = ();
sub generate_xcode_id {
my @chars = ('0'..'9', 'A'..'F');
my $str;
do {
my $len = 16;
$str = '0000'; # start and end with '0000' so we know we added it.
while ($len--) {
$str .= $chars[rand @chars]
};
$str .= '0000'; # start and end with '0000' so we know we added it.
} while (defined($xcode_references{$str}));
$xcode_references{$str} = 1; # so future calls can't generate this one.
return $str;
}
sub process_xcode {
my $addpath = shift;
my $pbxprojfname = shift;
my $lineno;
%xcode_references = ();
my $addfname = basename($addpath);
my $addext = '';
if ($addfname =~ /\.(.*?)\Z/) {
$addext = $1;
}
my $is_public_header = ($addpath =~ /\Ainclude\/SDL3\//) ? 1 : 0;
my $filerefpath = $is_public_header ? "SDL3/$addfname" : $addfname;
my $srcs_or_headers = '';
my $addfiletype = '';
if ($addext eq 'c') {
$srcs_or_headers = 'Sources';
$addfiletype = 'sourcecode.c.c';
} elsif ($addext eq 'm') {
$srcs_or_headers = 'Sources';
$addfiletype = 'sourcecode.c.objc';
} elsif ($addext eq 'h') {
$srcs_or_headers = 'Headers';
$addfiletype = 'sourcecode.c.h';
} else {
die("Unexpected file extension '$addext'\n");
}
my $fh;
open $fh, '<', $pbxprojfname or die("Failed to open '$pbxprojfname': $!\n");
chomp(my @pbxproj = <$fh>);
close($fh);
# build a table of all ids, in case we duplicate one by some miracle.
$lineno = 0;
foreach (@pbxproj) {
$lineno++;
# like "F3676F582A7885080091160D /* SDL3.dmg */ = {"
if (/\A\t\t([A-F0-9]{24}) \/\* (.*?) \*\/ \= \{\Z/) {
$xcode_references{$1} = $2;
}
}
# build out of a tree of PBXGroup items.
my %pbxgroups = ();
my $thispbxgroup;
my $pbxgroup_children;
my $pbxgroup_state = 0;
my $pubheaders_group_hash = '';
my $libsrc_group_hash = '';
$lineno = 0;
foreach (@pbxproj) {
$lineno++;
if ($pbxgroup_state == 0) {
$pbxgroup_state++ if /\A\/\* Begin PBXGroup section \*\/\Z/;
} elsif ($pbxgroup_state == 1) {
# like "F3676F582A7885080091160D /* SDL3.dmg */ = {"
if (/\A\t\t([A-F0-9]{24}) \/\* (.*?) \*\/ \= \{\Z/) {
my %newhash = ();
$pbxgroups{$1} = \%newhash;
$thispbxgroup = \%newhash;
$pubheaders_group_hash = $1 if $2 eq 'Public Headers';
$libsrc_group_hash = $1 if $2 eq 'Library Source';
$pbxgroup_state++;
} elsif (/\A\/\* End PBXGroup section \*\/\Z/) {
last;
} else {
die("Expected pbxgroup obj on '$pbxprojfname' line $lineno\n");
}
} elsif ($pbxgroup_state == 2) {
if (/\A\t\t\tisa \= PBXGroup;\Z/) {
$pbxgroup_state++;
} else {
die("Expected pbxgroup obj's isa field on '$pbxprojfname' line $lineno\n");
}
} elsif ($pbxgroup_state == 3) {
if (/\A\t\t\tchildren \= \(\Z/) {
my %newhash = ();
$$thispbxgroup{'children'} = \%newhash;
$pbxgroup_children = \%newhash;
$pbxgroup_state++;
} else {
die("Expected pbxgroup obj's children field on '$pbxprojfname' line $lineno\n");
}
} elsif ($pbxgroup_state == 4) {
if (/\A\t\t\t\t([A-F0-9]{24}) \/\* (.*?) \*\/,\Z/) {
$$pbxgroup_children{$1} = $2;
} elsif (/\A\t\t\t\);\Z/) {
$pbxgroup_state++;
} else {
die("Expected pbxgroup obj's children element on '$pbxprojfname' line $lineno\n");
}
} elsif ($pbxgroup_state == 5) {
if (/\A\t\t\t(.*?) \= (.*?);\Z/) {
$$thispbxgroup{$1} = $2;
} elsif (/\A\t\t\};\Z/) {
$pbxgroup_state = 1;
} else {
die("Expected pbxgroup obj field on '$pbxprojfname' line $lineno\n");
}
} else {
die("bug in this script.");
}
}
die("Didn't see PBXGroup section in '$pbxprojfname'. Bug?\n") if $pbxgroup_state == 0;
die("Didn't see Public Headers PBXGroup in '$pbxprojfname'. Bug?\n") if $pubheaders_group_hash eq '';
die("Didn't see Library Source PBXGroup in '$pbxprojfname'. Bug?\n") if $libsrc_group_hash eq '';
# Some debug log dumping...
if (0) {
foreach (keys %pbxgroups) {
my $k = $_;
my $g = $pbxgroups{$k};
print("$_:\n");
foreach (keys %$g) {
print(" $_:\n");
if ($_ eq 'children') {
my $kids = $$g{$_};
foreach (keys %$kids) {
print(" $_ -> " . $$kids{$_} . "\n");
}
} else {
print(' ' . $$g{$_} . "\n");
}
}
print("\n");
}
}
# Get some unique IDs for our new thing.
my $fileref = generate_xcode_id();
my $buildfileref = generate_xcode_id();
# Figure out what group to insert this into (or what groups to make)
my $add_to_group_fileref = $fileref;
my $add_to_group_addfname = $addfname;
my $newgrptext = '';
my $grphash = '';
if ($is_public_header) {
$grphash = $pubheaders_group_hash; # done!
} else {
$grphash = $libsrc_group_hash;
my @splitpath = split(/\//, dirname($addpath));
if ($splitpath[0] eq 'src') {
shift @splitpath;
}
while (my $elem = shift(@splitpath)) {
my $g = $pbxgroups{$grphash};
my $kids = $$g{'children'};
my $found = 0;
foreach (keys %$kids) {
my $hash = $_;
my $fname = $$kids{$hash};
if (uc($fname) eq uc($elem)) {
$grphash = $hash;
$found = 1;
last;
}
}
unshift(@splitpath, $elem), last if (not $found);
}
if (@splitpath) { # still elements? We need to build groups.
my $newgroupref = generate_xcode_id();
$add_to_group_fileref = $newgroupref;
$add_to_group_addfname = $splitpath[0];
while (my $elem = shift(@splitpath)) {
my $lastelem = @splitpath ? 0 : 1;
my $childhash = $lastelem ? $fileref : generate_xcode_id();
my $childpath = $lastelem ? $addfname : $splitpath[0];
$newgrptext .= "\t\t$newgroupref /* $elem */ = {\n";
$newgrptext .= "\t\t\tisa = PBXGroup;\n";
$newgrptext .= "\t\t\tchildren = (\n";
$newgrptext .= "\t\t\t\t$childhash /* $childpath */,\n";
$newgrptext .= "\t\t\t);\n";
$newgrptext .= "\t\t\tpath = $elem;\n";
$newgrptext .= "\t\t\tsourceTree = \"<group>\";\n";
$newgrptext .= "\t\t};\n";
$newgroupref = $childhash;
}
}
}
my $tmpfname = "$pbxprojfname.tmp";
open $fh, '>', $tmpfname or die("Failed to open '$tmpfname': $!\n");
my $add_to_this_group = 0;
$pbxgroup_state = 0;
$lineno = 0;
foreach (@pbxproj) {
$lineno++;
if ($pbxgroup_state == 0) {
# Drop in new references at the end of their sections...
if (/\A\/\* End PBXBuildFile section \*\/\Z/) {
print $fh "\t\t$buildfileref /* $addfname in $srcs_or_headers */ = {isa = PBXBuildFile; fileRef = $fileref /* $addfname */;";
if ($is_public_header) {
print $fh " settings = {ATTRIBUTES = (Public, ); };";
}
print $fh " };\n";
} elsif (/\A\/\* End PBXFileReference section \*\/\Z/) {
print $fh "\t\t$fileref /* $addfname */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = $addfiletype; name = $addfname; path = $filerefpath; sourceTree = \"<group>\"; };\n";
} elsif (/\A\/\* Begin PBXGroup section \*\/\Z/) {
$pbxgroup_state = 1;
} elsif (/\A\/\* Begin PBXSourcesBuildPhase section \*\/\Z/) {
$pbxgroup_state = 5;
}
} elsif ($pbxgroup_state == 1) {
if (/\A\t\t([A-F0-9]{24}) \/\* (.*?) \*\/ \= \{\Z/) {
$pbxgroup_state++;
$add_to_this_group = $1 eq $grphash;
} elsif (/\A\/\* End PBXGroup section \*\/\Z/) {
print $fh $newgrptext;
$pbxgroup_state = 0;
}
} elsif ($pbxgroup_state == 2) {
if (/\A\t\t\tchildren \= \(\Z/) {
$pbxgroup_state++;
}
} elsif ($pbxgroup_state == 3) {
if (/\A\t\t\t\);\Z/) {
if ($add_to_this_group) {
print $fh "\t\t\t\t$add_to_group_fileref /* $add_to_group_addfname */,\n";
}
$pbxgroup_state++;
}
} elsif ($pbxgroup_state == 4) {
if (/\A\t\t\};\Z/) {
$add_to_this_group = 0;
}
$pbxgroup_state = 1;
} elsif ($pbxgroup_state == 5) {
if (/\A\t\t\t\);\Z/) {
if ($srcs_or_headers eq 'Sources') {
print $fh "\t\t\t\t$buildfileref /* $addfname in $srcs_or_headers */,\n";
}
$pbxgroup_state = 0;
}
}
print $fh "$_\n";
}
close($fh);
rename($tmpfname, $pbxprojfname);
}
my %visualc_references = ();
sub generate_visualc_id { # these are just standard Windows GUIDs.
my @chars = ('0'..'9', 'a'..'f');
my $str;
do {
my $len = 24;
$str = '0000'; # start and end with '0000' so we know we added it.
while ($len--) {
$str .= $chars[rand @chars]
};
$str .= '0000'; # start and end with '0000' so we know we added it.
$str =~ s/\A(........)(....)(....)(............)\Z/$1-$2-$3-$4/; # add dashes in the appropriate places.
} while (defined($visualc_references{$str}));
$visualc_references{$str} = 1; # so future calls can't generate this one.
return $str;
}
sub process_visualstudio {
my $addpath = shift;
my $vcxprojfname = shift;
my $lineno;
%visualc_references = ();
my $is_public_header = ($addpath =~ /\Ainclude\/SDL3\//) ? 1 : 0;
my $addfname = basename($addpath);
my $addext = '';
if ($addfname =~ /\.(.*?)\Z/) {
$addext = $1;
}
my $isheader = 0;
if ($addext eq 'c') {
$isheader = 0;
} elsif ($addext eq 'm') {
return; # don't add Objective-C files to Visual Studio projects!
} elsif ($addext eq 'h') {
$isheader = 1;
} else {
die("Unexpected file extension '$addext'\n");
}
my $fh;
open $fh, '<', $vcxprojfname or die("Failed to open '$vcxprojfname': $!\n");
chomp(my @vcxproj = <$fh>);
close($fh);
my $vcxgroup_state;
my $rawaddvcxpath = "$addpath";
$rawaddvcxpath =~ s/\//\\/g;
# Figure out relative path from vcxproj file...
my $addvcxpath = '';
my @subdirs = split(/\//, $vcxprojfname);
pop @subdirs;
foreach (@subdirs) {
$addvcxpath .= "..\\";
}
$addvcxpath .= $rawaddvcxpath;
my $prevname = undef;
my $tmpfname;
$tmpfname = "$vcxprojfname.tmp";
open $fh, '>', $tmpfname or die("Failed to open '$tmpfname': $!\n");
my $added = 0;
$added = 0;
$vcxgroup_state = 0;
$prevname = undef;
$lineno = 0;
foreach (@vcxproj) {
$lineno++;
if ($vcxgroup_state == 0) {
if (/\A \<ItemGroup\>\Z/) {
$vcxgroup_state = 1;
$prevname = undef;
}
} elsif ($vcxgroup_state == 1) {
if (/\A \<ClInclude .*\Z/) {
$vcxgroup_state = 2 if $isheader;
} elsif (/\A \<ClCompile .*\Z/) {
$vcxgroup_state = 3 if not $isheader;
} elsif (/\A \<\/ItemGroup\>\Z/) {
$vcxgroup_state = 0;
$prevname = undef;
}
}
# Don't do elsif, we need to check this line again.
if ($vcxgroup_state == 2) {
if (/\A <ClInclude Include="(.*?)" \/\>\Z/) {
my $nextname = $1;
if ((not $added) && (((not defined $prevname) || (uc($prevname) lt uc($addvcxpath))) && (uc($nextname) gt uc($addvcxpath)))) {
print $fh " <ClInclude Include=\"$addvcxpath\" />\n";
$vcxgroup_state = 0;
$added = 1;
}
$prevname = $nextname;
} elsif (/\A \<\/ItemGroup\>\Z/) {
if ((not $added) && ((not defined $prevname) || (uc($prevname) lt uc($addvcxpath)))) {
print $fh " <ClInclude Include=\"$addvcxpath\" />\n";
$vcxgroup_state = 0;
$added = 1;
}
}
} elsif ($vcxgroup_state == 3) {
if (/\A <ClCompile Include="(.*?)" \/\>\Z/) {
my $nextname = $1;
if ((not $added) && (((not defined $prevname) || (uc($prevname) lt uc($addvcxpath))) && (uc($nextname) gt uc($addvcxpath)))) {
print $fh " <ClCompile Include=\"$addvcxpath\" />\n";
$vcxgroup_state = 0;
$added = 1;
}
$prevname = $nextname;
} elsif (/\A \<\/ItemGroup\>\Z/) {
if ((not $added) && ((not defined $prevname) || (uc($prevname) lt uc($addvcxpath)))) {
print $fh " <ClCompile Include=\"$addvcxpath\" />\n";
$vcxgroup_state = 0;
$added = 1;
}
}
}
print $fh "$_\n";
}
close($fh);
rename($tmpfname, $vcxprojfname);
my $vcxfiltersfname = "$vcxprojfname.filters";
open $fh, '<', $vcxfiltersfname or die("Failed to open '$vcxfiltersfname': $!\n");
chomp(my @vcxfilters = <$fh>);
close($fh);
my $newgrptext = '';
my $filter = '';
if ($is_public_header) {
$filter = 'API Headers';
} else {
$filter = lc(dirname($addpath));
$filter =~ s/\Asrc\///; # there's no filter for the base "src/" dir, where SDL.c and friends live.
$filter =~ s/\//\\/g;
if ($filter ne '') {
# see if the filter already exists, otherwise add it.
my %existing_filters = ();
my $current_filter = '';
my $found = 0;
foreach (@vcxfilters) {
# These lines happen to be unique, so we don't have to parse down to find this section.
if (/\A \<Filter Include\="(.*?)"\>\Z/) {
$current_filter = lc($1);
if ($current_filter eq $filter) {
$found = 1;
}
} elsif (/\A \<UniqueIdentifier\>\{(.*?)\}\<\/UniqueIdentifier\>\Z/) {
$visualc_references{$1} = $current_filter; # gather up existing GUIDs to avoid duplicates.
$existing_filters{$current_filter} = $1;
}
}
if (not $found) { # didn't find it? We need to build filters.
my $subpath = '';
my @splitpath = split(/\\/, $filter);
while (my $elem = shift(@splitpath)) {
$subpath .= "\\" if ($subpath ne '');
$subpath .= $elem;
if (not $existing_filters{$subpath}) {
my $newgroupref = generate_visualc_id();
$newgrptext .= " <Filter Include=\"$subpath\">\n";
$newgrptext .= " <UniqueIdentifier>{$newgroupref}</UniqueIdentifier>\n";
$newgrptext .= " </Filter>\n"
}
}
}
}
}
$tmpfname = "$vcxfiltersfname.tmp";
open $fh, '>', $tmpfname or die("Failed to open '$tmpfname': $!\n");
$added = 0;
$vcxgroup_state = 0;
$prevname = undef;
$lineno = 0;
foreach (@vcxfilters) {
$lineno++;
# We cheat here, because these lines are unique, we don't have to fully parse this file.
if ($vcxgroup_state == 0) {
if (/\A \<Filter Include\="(.*?)"\>\Z/) {
if ($newgrptext ne '') {
$vcxgroup_state = 1;
$prevname = undef;
}
} elsif (/\A \<ClInclude .*\Z/) {
if ($isheader) {
$vcxgroup_state = 2;
$prevname = undef;
}
} elsif (/\A \<ClCompile .*\Z/) {
if (not $isheader) {
$vcxgroup_state = 3;
$prevname = undef;
}
}
}
# Don't do elsif, we need to check this line again.
if ($vcxgroup_state == 1) {
if (/\A \<\/ItemGroup\>\Z/) {
print $fh $newgrptext;
$newgrptext = '';
$vcxgroup_state = 0;
}
} elsif ($vcxgroup_state == 2) {
if (/\A <ClInclude Include="(.*?)"/) {
my $nextname = $1;
if ((not $added) && (((not defined $prevname) || (uc($prevname) lt uc($addvcxpath))) && (uc($nextname) gt uc($addvcxpath)))) {
print $fh " <ClInclude Include=\"$addvcxpath\"";
if ($filter ne '') {
print $fh ">\n";
print $fh " <Filter>$filter</Filter>\n";
print $fh " </ClInclude>\n";
} else {
print $fh " />\n";
}
$added = 1;
}
$prevname = $nextname;
} elsif (/\A \<\/ItemGroup\>\Z/) {
if ((not $added) && ((not defined $prevname) || (uc($prevname) lt uc($addvcxpath)))) {
print $fh " <ClInclude Include=\"$addvcxpath\"";
if ($filter ne '') {
print $fh ">\n";
print $fh " <Filter>$filter</Filter>\n";
print $fh " </ClInclude>\n";
} else {
print $fh " />\n";
}
$added = 1;
}
$vcxgroup_state = 0;
}
} elsif ($vcxgroup_state == 3) {
if (/\A <ClCompile Include="(.*?)"/) {
my $nextname = $1;
if ((not $added) && (((not defined $prevname) || (uc($prevname) lt uc($addvcxpath))) && (uc($nextname) gt uc($addvcxpath)))) {
print $fh " <ClCompile Include=\"$addvcxpath\"";
if ($filter ne '') {
print $fh ">\n";
print $fh " <Filter>$filter</Filter>\n";
print $fh " </ClCompile>\n";
} else {
print $fh " />\n";
}
$added = 1;
}
$prevname = $nextname;
} elsif (/\A \<\/ItemGroup\>\Z/) {
if ((not $added) && ((not defined $prevname) || (uc($prevname) lt uc($addvcxpath)))) {
print $fh " <ClCompile Include=\"$addvcxpath\"";
if ($filter ne '') {
print $fh ">\n";
print $fh " <Filter>$filter</Filter>\n";
print $fh " </ClCompile>\n";
} else {
print $fh " />\n";
}
$added = 1;
}
$vcxgroup_state = 0;
}
}
print $fh "$_\n";
}
close($fh);
rename($tmpfname, $vcxfiltersfname);
}
# Mainline!
chdir(dirname($0)); # assumed to be in build-scripts
chdir('..'); # head to root of source tree.
foreach (@ARGV) {
s/\A\.\///; # Turn "./path/to/file.txt" into "path/to/file.txt"
my $arg = $_;
process_xcode($arg, 'Xcode/SDL/SDL.xcodeproj/project.pbxproj');
process_visualstudio($arg, 'VisualC/SDL/SDL.vcxproj');
process_visualstudio($arg, 'VisualC-GDK/SDL/SDL.vcxproj');
process_visualstudio($arg, 'VisualC-WinRT/SDL-UWP.vcxproj');
}
print("Done. Please run `git diff` and make sure this looks okay!\n");
exit(0);

View File

@ -41,23 +41,28 @@ gcc -o genfilter build-scripts/gen_audio_resampler_filter.c -lm && ./genfilter >
#include <stdio.h>
#include <math.h>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
#define RESAMPLER_ZERO_CROSSINGS 5
#define RESAMPLER_BITS_PER_SAMPLE 16
#define RESAMPLER_SAMPLES_PER_ZERO_CROSSING (1 << ((RESAMPLER_BITS_PER_SAMPLE / 2) + 1))
#define RESAMPLER_FILTER_SIZE ((RESAMPLER_SAMPLES_PER_ZERO_CROSSING * RESAMPLER_ZERO_CROSSINGS) + 1)
#define RESAMPLER_BITS_PER_ZERO_CROSSING ((RESAMPLER_BITS_PER_SAMPLE / 2) + 1)
#define RESAMPLER_SAMPLES_PER_ZERO_CROSSING (1 << RESAMPLER_BITS_PER_ZERO_CROSSING)
#define RESAMPLER_FILTER_SIZE (RESAMPLER_SAMPLES_PER_ZERO_CROSSING * RESAMPLER_ZERO_CROSSINGS)
/* This is a "modified" bessel function, so you can't use POSIX j0() */
static double
bessel(const double x)
{
const double xdiv2 = x / 2.0;
double i0 = 1.0f;
double f = 1.0f;
double i0 = 1.0;
double f = 1.0;
int i = 1;
while (1) {
const double diff = pow(xdiv2, i * 2) / pow(f, 2);
if (diff < 1.0e-21f) {
if (diff < 1.0e-21) {
break;
}
i0 += diff;
@ -70,30 +75,21 @@ bessel(const double x)
/* build kaiser table with cardinal sine applied to it, and array of differences between elements. */
static void
kaiser_and_sinc(float *table, float *diffs, const int tablelen, const double beta)
kaiser_and_sinc(double *table, const int tablelen, const double beta)
{
const int lenm1 = tablelen - 1;
const int lenm1div2 = lenm1 / 2;
const double bessel_beta = bessel(beta);
int i;
table[0] = 1.0f;
for (i = 1; i < tablelen; i++) {
const double kaiser = bessel(beta * sqrt(1.0 - pow(((i - lenm1) / 2.0) / lenm1div2, 2.0))) / bessel_beta;
table[tablelen - i] = (float) kaiser;
}
table[0] = 1.0;
for (i = 1; i < tablelen; i++) {
const float x = (((float) i) / ((float) RESAMPLER_SAMPLES_PER_ZERO_CROSSING)) * ((float) M_PI);
table[i] *= sinf(x) / x;
diffs[i - 1] = table[i] - table[i - 1];
const double kaiser = bessel(beta * sqrt(1.0 - pow((double)i / (double)(tablelen), 2.0))) / bessel_beta;
const double x = (((double) i) / ((double) RESAMPLER_SAMPLES_PER_ZERO_CROSSING)) * M_PI;
table[i] = kaiser * (sin(x) / x);
}
diffs[lenm1] = 0.0f;
}
static float ResamplerFilter[RESAMPLER_FILTER_SIZE];
static float ResamplerFilterDifference[RESAMPLER_FILTER_SIZE];
static double ResamplerFilter[RESAMPLER_FILTER_SIZE];
static void
PrepareResampleFilter(void)
@ -101,12 +97,12 @@ PrepareResampleFilter(void)
/* if dB > 50, beta=(0.1102 * (dB - 8.7)), according to Matlab. */
const double dB = 80.0;
const double beta = 0.1102 * (dB - 8.7);
kaiser_and_sinc(ResamplerFilter, ResamplerFilterDifference, RESAMPLER_FILTER_SIZE, beta);
kaiser_and_sinc(ResamplerFilter, RESAMPLER_FILTER_SIZE, beta);
}
int main(void)
{
int i;
int i, j;
PrepareResampleFilter();
@ -136,22 +132,16 @@ int main(void)
"\n"
"#define RESAMPLER_ZERO_CROSSINGS %d\n"
"#define RESAMPLER_BITS_PER_SAMPLE %d\n"
"#define RESAMPLER_SAMPLES_PER_ZERO_CROSSING (1 << ((RESAMPLER_BITS_PER_SAMPLE / 2) + 1))\n"
"#define RESAMPLER_FILTER_SIZE ((RESAMPLER_SAMPLES_PER_ZERO_CROSSING * RESAMPLER_ZERO_CROSSINGS) + 1)\n"
"#define RESAMPLER_BITS_PER_ZERO_CROSSING ((RESAMPLER_BITS_PER_SAMPLE / 2) + 1)\n"
"#define RESAMPLER_SAMPLES_PER_ZERO_CROSSING (1 << RESAMPLER_BITS_PER_ZERO_CROSSING)\n"
"#define RESAMPLER_FILTER_SIZE (RESAMPLER_SAMPLES_PER_ZERO_CROSSING * RESAMPLER_ZERO_CROSSINGS)\n"
"\n", RESAMPLER_ZERO_CROSSINGS, RESAMPLER_BITS_PER_SAMPLE
);
printf("static const float ResamplerFilter[RESAMPLER_FILTER_SIZE] = {\n");
printf(" %.9ff", ResamplerFilter[0]);
for (i = 0; i < RESAMPLER_FILTER_SIZE-1; i++) {
printf("%s%.9ff", ((i % 5) == 4) ? ",\n " : ", ", ResamplerFilter[i+1]);
}
printf("\n};\n\n");
printf("static const float ResamplerFilterDifference[RESAMPLER_FILTER_SIZE] = {\n");
printf(" %.9ff", ResamplerFilterDifference[0]);
for (i = 0; i < RESAMPLER_FILTER_SIZE-1; i++) {
printf("%s%.9ff", ((i % 5) == 4) ? ",\n " : ", ", ResamplerFilterDifference[i+1]);
printf("static const float ResamplerFilter[RESAMPLER_FILTER_SIZE] = {");
for (i = 0; i < RESAMPLER_FILTER_SIZE; i++) {
j = (i % RESAMPLER_ZERO_CROSSINGS) * RESAMPLER_SAMPLES_PER_ZERO_CROSSING + (i / RESAMPLER_ZERO_CROSSINGS);
printf("%s%12.9ff,", (i % RESAMPLER_ZERO_CROSSINGS) ? "" : "\n ", ResamplerFilter[j]);
}
printf("\n};\n\n");

View File

@ -31,6 +31,7 @@ my $optionsfname = undef;
my $wikipreamble = undef;
my $changeformat = undef;
my $manpath = undef;
my $gitrev = undef;
foreach (@ARGV) {
$warn_about_missing = 1, next if $_ eq '--warn-about-missing';
@ -47,6 +48,9 @@ foreach (@ARGV) {
} elsif (/\A--manpath=(.*)\Z/) {
$manpath = $1;
next;
} elsif (/\A--rev=(.*)\Z/) {
$gitrev = $1;
next;
}
$srcpath = $_, next if not defined $srcpath;
$wikipath = $_, next if not defined $wikipath;
@ -788,6 +792,45 @@ while (my $d = readdir(DH)) {
}
closedir(DH);
delete $wikifuncs{"Undocumented"};
{
my $path = "$wikipath/Undocumented.md";
open(FH, '>', $path) or die("Can't open '$path': $!\n");
print FH "# Undocumented\n\n";
print FH "## Functions defined in the headers, but not in the wiki\n\n";
my $header_only_func = 0;
foreach (sort keys %headerfuncs) {
my $fn = $_;
if (not defined $wikifuncs{$fn}) {
print FH "- [$fn]($fn)\n";
$header_only_func = 1;
}
}
if (!$header_only_func) {
print FH "(none)\n";
}
print FH "\n";
print FH "## Functions defined in the wiki, but not in the headers\n\n";
my $wiki_only_func = 0;
foreach (sort keys %wikifuncs) {
my $fn = $_;
if (not defined $headerfuncs{$fn}) {
print FH "- [$fn]($fn)\n";
$wiki_only_func = 1;
}
}
if (!$wiki_only_func) {
print FH "(none)\n";
}
print FH "\n";
close(FH);
}
if ($warn_about_missing) {
foreach (keys %wikifuncs) {
@ -1437,8 +1480,10 @@ if ($copy_direction == 1) { # --copy-to-headers
close(FH);
}
my $gitrev = `cd "$srcpath" ; git rev-list HEAD~..`;
chomp($gitrev);
if (!$gitrev) {
$gitrev = `cd "$srcpath" ; git rev-list HEAD~..`;
chomp($gitrev);
}
# !!! FIXME
open(FH, '<', "$srcpath/$versionfname") or die("Can't open '$srcpath/$versionfname': $!\n");

View File

@ -10,4 +10,4 @@ Version: @PROJECT_VERSION@
Requires.private: @SDL_PC_PRIVATE_REQUIRES@
Conflicts:
Libs: -L${libdir} @SDL_RLD_FLAGS@ @SDL_PC_LIBS@ @SDL_PC_SECTION_LIBS_PRIVATE@ @SDL_PC_STATIC_LIBS@
Cflags: -I${includedir} -I${includedir}/SDL3 @SDL_PC_CFLAGS@
Cflags: -I${includedir} @SDL_PC_CFLAGS@

View File

@ -1019,8 +1019,8 @@ endmacro()
# Check for HIDAPI support
macro(CheckHIDAPI)
set(HAVE_HIDAPI TRUE)
if(SDL_HIDAPI)
set(HAVE_HIDAPI ON)
if(SDL_HIDAPI_LIBUSB)
set(HAVE_LIBUSB FALSE)
@ -1029,25 +1029,27 @@ macro(CheckHIDAPI)
if(PC_LIBUSB_FOUND)
cmake_push_check_state()
list(APPEND CMAKE_REQUIRED_INCLUDES ${PC_LIBUSB_INCLUDE_DIRS})
check_include_file(libusb.h HAVE_LIBUSB_H)
list(APPEND CMAKE_REQUIRED_LIBRARIES PkgConfig::PC_LIBUSB)
check_c_source_compiles("
#include <stddef.h>
#include <libusb.h>
int main(int argc, char **argv) {
libusb_close(NULL);
return 0;
}" HAVE_LIBUSB_H)
cmake_pop_check_state()
if(HAVE_LIBUSB_H)
set(HAVE_LIBUSB TRUE)
if(HIDAPI_ONLY_LIBUSB)
sdl_link_dependency(hidapi LIBS PkgConfig::PC_LIBUSB PKG_CONFIG_PREFIX PC_LIBUSB PKG_CONFIG_SPECS ${LibUSB_PKG_CONFIG_SPEC})
else()
# libusb is loaded dynamically, so don't add link to it
FindLibraryAndSONAME("usb-1.0" LIBDIRS ${PC_LIBUSB_LIBRARY_DIRS})
if(USB_1.0_LIB)
set(SDL_LIBUSB_DYNAMIC "\"${USB_1.0_LIB_SONAME}\"")
endif()
FindLibraryAndSONAME("usb-1.0" LIBDIRS ${PC_LIBUSB_LIBRARY_DIRS})
if(SDL_HIDAPI_LIBUSB_SHARED AND USB_1.0_LIB_SONAME)
set(HAVE_HIDAPI_LIBUSB_SHARED ON)
set(SDL_LIBUSB_DYNAMIC "\"${USB_1.0_LIB_SONAME}\"")
sdl_link_dependency(hidapi INCLUDES $<TARGET_PROPERTY:PkgConfig::PC_LIBUSB,INTERFACE_INCLUDE_DIRECTORIES>)
else()
sdl_link_dependency(hidapi LIBS PkgConfig::PC_LIBUSB PKG_CONFIG_PREFIX PC_LIBUSB PKG_CONFIG_SPECS ${LibUSB_PKG_CONFIG_SPEC})
endif()
endif()
endif()
if(HIDAPI_ONLY_LIBUSB AND NOT HAVE_LIBUSB)
set(HAVE_HIDAPI FALSE)
endif()
set(HAVE_HIDAPI_LIBUSB ${HAVE_LIBUSB})
endif()

View File

@ -2,7 +2,9 @@ include(CMakeParseArguments)
include(GNUInstallDirs)
function(SDL_generate_manpages)
cmake_parse_arguments(ARG "" "RESULT_VARIABLE;NAME;BUILD_DOCDIR;HEADERS_DIR;SOURCE_DIR;SYMBOL;OPTION_FILE;WIKIHEADERS_PL_PATH" "" ${ARGN})
cmake_parse_arguments(ARG "" "RESULT_VARIABLE;NAME;BUILD_DOCDIR;HEADERS_DIR;SOURCE_DIR;SYMBOL;OPTION_FILE;WIKIHEADERS_PL_PATH;REVISION" "" ${ARGN})
set(wikiheaders_extra_args)
if(NOT ARG_NAME)
set(ARG_NAME "${PROJECT_NAME}")
@ -25,6 +27,10 @@ function(SDL_generate_manpages)
message(FATAL_ERROR "Missing required SYMBOL argument")
endif()
if(ARG_REVISION)
list(APPEND wikiheaders_extra_args "--rev=${ARG_REVISION}")
endif()
if(NOT ARG_BUILD_DOCDIR)
set(ARG_BUILD_DOCDIR "${CMAKE_CURRENT_BINARY_DIR}/docs")
endif()
@ -40,13 +46,13 @@ function(SDL_generate_manpages)
add_custom_command(
OUTPUT "${BUILD_WIKIDIR}/${ARG_SYMBOL}.md"
COMMAND "${CMAKE_COMMAND}" -E make_directory "${BUILD_WIKIDIR}"
COMMAND "${PERL_EXECUTABLE}" "${ARG_WIKIHEADERS_PL_PATH}" "${ARG_SOURCE_DIR}" "${BUILD_WIKIDIR}" "--options=${ARG_OPTION_FILE}" --copy-to-wiki
COMMAND "${PERL_EXECUTABLE}" "${ARG_WIKIHEADERS_PL_PATH}" "${ARG_SOURCE_DIR}" "${BUILD_WIKIDIR}" "--options=${ARG_OPTION_FILE}" --copy-to-wiki ${wikiheaders_extra_args}
DEPENDS ${HEADER_FILES} "${ARG_WIKIHEADERS_PL_PATH}" "${ARG_OPTION_FILE}"
COMMENT "Generating ${ARG_NAME} wiki markdown files"
)
add_custom_command(
OUTPUT "${BUILD_MANDIR}/man3/${ARG_SYMBOL}.3"
COMMAND "${PERL_EXECUTABLE}" "${ARG_WIKIHEADERS_PL_PATH}" "${ARG_SOURCE_DIR}" "${BUILD_WIKIDIR}" "--options=${ARG_OPTION_FILE}" "--manpath=${BUILD_MANDIR}" --copy-to-manpages
COMMAND "${PERL_EXECUTABLE}" "${ARG_WIKIHEADERS_PL_PATH}" "${ARG_SOURCE_DIR}" "${BUILD_WIKIDIR}" "--options=${ARG_OPTION_FILE}" "--manpath=${BUILD_MANDIR}" --copy-to-manpages ${wikiheaders_extra_args}
DEPENDS "${BUILD_WIKIDIR}/${ARG_SYMBOL}.md" "${ARG_WIKIHEADERS_PL_PATH}" "${ARG_OPTION_FILE}"
COMMENT "Generating ${ARG_NAME} man pages"
)

View File

@ -17,7 +17,7 @@ def main():
binary_data = args.input.open("rb").read()
with args.output.open("w") as fout:
with args.output.open("w", newline="\n") as fout:
fout.write("unsigned char {}[] = {{\n".format(varname))
bytes_written = 0
while bytes_written < len(binary_data):

View File

@ -10,13 +10,13 @@ The rest of this README covers the Android gradle style build process.
Requirements
================================================================================
Android SDK (version 31 or later)
Android SDK (version 34 or later)
https://developer.android.com/sdk/index.html
Android NDK r15c or later
https://developer.android.com/tools/sdk/ndk/index.html
Minimum API level supported by SDL: 16 (Android 4.1)
Minimum API level supported by SDL: 19 (Android 4.4)
How the port works
@ -435,13 +435,13 @@ The Tegra Graphics Debugger is available from NVidia here:
https://developer.nvidia.com/tegra-graphics-debugger
Why is API level 16 the minimum required?
Why is API level 19 the minimum required?
================================================================================
The latest NDK toolchain doesn't support targeting earlier than API level 16.
As of this writing, according to https://developer.android.com/about/dashboards/index.html
about 99% of the Android devices accessing Google Play support API level 16 or
higher (January 2018).
The latest NDK toolchain doesn't support targeting earlier than API level 19.
As of this writing, according to https://www.composables.com/tools/distribution-chart
about 99.7% of the Android devices accessing Google Play support API level 19 or
higher (August 2023).
A note regarding the use of the "dirty rectangles" rendering technique

View File

@ -1,27 +1,187 @@
# Emscripten
(This documentation is not very robust; we will update and expand this later.)
## The state of things
## A quick note about audio
(As of September 2023, but things move quickly and we don't update this
document often.)
In modern times, all the browsers you probably care about (Chrome, Firefox,
Edge, and Safari, on Windows, macOS, Linux, iOS and Android), support some
reasonable base configurations:
- WebAssembly (don't bother with asm.js any more)
- WebGL (which will look like OpenGL ES 2 or 3 to your app).
- Threads (see caveats, though!)
- Game controllers
- Autoupdating (so you can assume they have a recent version of the browser)
All this to say we're at the point where you don't have to make a lot of
concessions to get even a fairly complex SDL-based game up and running.
## RTFM
This document is a quick rundown of some high-level details. The
documentation at [emscripten.org](https://emscripten.org/) is vast
and extremely detailed for a wide variety of topics, and you should at
least skim through it at some point.
## Porting your app to Emscripten
Many many things just need some simple adjustments and they'll compile
like any other C/C++ code, as long as SDL was handling the platform-specific
work for your program.
First, you probably need this in at least one of your source files:
```c
#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#endif
```
Second: assembly language code has to go. Replace it with C. You can even use
[x86 SIMD intrinsic functions in Emscripten](https://emscripten.org/docs/porting/simd.html)!
Third: Middleware has to go. If you have a third-party library you link
against, you either need an Emscripten port of it, or the source code to it
to compile yourself, or you need to remove it.
Fourth: You still start in a function called main(), but you need to get out of
it and into a function that gets called repeatedly, and returns quickly,
called a mainloop.
Somewhere in your program, you probably have something that looks like a more
complicated version of this:
```c
void main(void)
{
initialize_the_game();
while (game_is_still_running) {
check_for_new_input();
think_about_stuff();
draw_the_next_frame();
}
deinitialize_the_game();
}
```
This will not work on Emscripten, because the main thread needs to be free
to do stuff and can't sit in this loop forever. So Emscripten lets you set up
a [mainloop](https://emscripten.org/docs/porting/emscripten-runtime-environment.html#browser-main-loop).
```c
static void mainloop(void) /* this will run often, possibly at the monitor's refresh rate */
{
if (!game_is_still_running) {
deinitialize_the_game();
#ifdef __EMSCRIPTEN__
emscripten_cancel_main_loop(); /* this should "kill" the app. */
#else
exit(0);
#endif
}
check_for_new_input();
think_about_stuff();
draw_the_next_frame();
}
void main(void)
{
initialize_the_game();
#ifdef __EMSCRIPTEN__
emscripten_set_main_loop(mainloop, 0, 1);
#else
while (1) { mainloop(); }
#endif
}
```
Basically, `emscripten_set_main_loop(mainloop, 0, 1);` says "run
`mainloop` over and over until I end the program." The function will
run, and return, freeing the main thread for other tasks, and then
run again when it's time. The `1` parameter does some magic to make
your main() function end immediately; this is useful because you
don't want any shutdown code that might be sitting below this code
to actually run if main() were to continue on, since we're just
getting started.
There's a lot of little details that are beyond the scope of this
document, but that's the biggest intial set of hurdles to porting
your app to the web.
## Do you need threads?
If you plan to use threads, they work on all major browsers now. HOWEVER,
they bring with them a lot of careful considerations. Rendering _must_
be done on the main thread. This is a general guideline for many
platforms, but a hard requirement on the web.
Many other things also must happen on the main thread; often times SDL
and Emscripten make efforts to "proxy" work to the main thread that
must be there, but you have to be careful (and read more detailed
documentation than this for the finer points).
Even when using threads, your main thread needs to set an Emscripten
mainloop that runs quickly and returns, or things will fail to work
correctly.
You should definitely read [Emscripten's pthreads docs](https://emscripten.org/docs/porting/pthreads.html)
for all the finer points. Mostly SDL's thread API will work as expected,
but is built on pthreads, so it shares the same little incompatibilities
that are documented there, such as where you can use a mutex, and when
a thread will start running, etc.
IMPORTANT: You have to decide to either build something that uses
threads or something that doesn't; you can't have one build
that works everywhere. This is an Emscripten (or maybe WebAssembly?
Or just web browsers in general?) limitation. If you aren't using
threads, it's easier to not enable them at all, at build time.
If you use threads, you _have to_ run from a web server that has
[COOP/COEP headers set correctly](https://web.dev/why-coop-coep/)
or your program will fail to start at all.
If building with threads, `__EMSCRIPTEN_PTHREADS__` will be defined
for checking with the C preprocessor, so you can build something
different depending on what sort of build you're compiling.
## Audio
Audio works as expected at the API level, but not exactly like other
platforms.
You'll only see a single default audio device. Audio capture also works;
if the browser pops up a prompt to ask for permission to access the
microphone, the SDL_OpenAudioDevice call will succeed and start producing
silence at a regular interval. Once the user approves the request, real
audio data will flow. If the user denies it, the app is not informed and
will just continue to receive silence.
Modern web browsers will not permit web pages to produce sound before the
user has interacted with them; this is for several reasons, not the least
of which being that no one likes when a random browser tab suddenly starts
making noise and the user has to scramble to figure out which and silence
it.
user has interacted with them (clicked or tapped on them, usually); this is
for several reasons, not the least of which being that no one likes when a
random browser tab suddenly starts making noise and the user has to scramble
to figure out which and silence it.
To solve this, most browsers will refuse to let a web app use the audio
subsystem at all before the user has interacted with (clicked on) the page
in a meaningful way. SDL-based apps also have to deal with this problem; if
the user hasn't interacted with the page, SDL_OpenAudioDevice will fail.
SDL will allow you to open the audio device for playback in this
circumstance, and your audio callback will fire, but SDL will throw the audio
data away until the user interacts with the page. This helps apps that depend
on the audio callback to make progress, and also keeps audio playback in sync
once the app is finally allowed to make noise.
There are two reasonable ways to deal with this: if you are writing some
sort of media player thing, where the user expects there to be a volume
control when you mouseover the canvas, just default that control to a muted
state; if the user clicks on the control to unmute it, on this first click,
open the audio device. This allows the media to play at start, the user can
reasonably opt-in to listening, and you never get access denied to the audio
device.
There are two reasonable ways to deal with the silence at the app level:
if you are writing some sort of media player thing, where the user expects
there to be a volume control when you mouseover the canvas, just default
that control to a muted state; if the user clicks on the control to unmute
it, on this first click, open the audio device. This allows the media to
play at start, and the user can reasonably opt-in to listening.
Many games do not have this sort of UI, and are more rigid about starting
audio along with everything else at the start of the process. For these, your
@ -36,41 +196,170 @@ Please see the discussion at https://github.com/libsdl-org/SDL/issues/6385
for some Javascript code to steal for this approach.
## Rendering
If you use SDL's 2D render API, it will use GLES2 internally, which
Emscripten will turn into WebGL calls. You can also use OpenGL ES 2
directly by creating a GL context and drawing into it.
Calling SDL_RenderPresent (or SDL_GL_SwapWindow) will not actually
present anything on the screen until your return from your mainloop
function.
## Building SDL/emscripten
First: do you _really_ need to build SDL from source?
If you aren't developing SDL itself, have a desire to mess with its source
code, or need something on the bleeding edge, don't build SDL. Just use
Emscripten's packaged version!
Compile and link your app with `-sUSE_SDL=2` and it'll use a build of
SDL packaged with Emscripten. This comes from the same source code and
fixes the Emscripten project makes to SDL are generally merged into SDL's
revision control, so often this is much easier for app developers.
`-sUSE_SDL=1` will select Emscripten's JavaScript reimplementation of SDL
1.2 instead; if you need SDL 1.2, this might be fine, but we generally
recommend you don't use SDL 1.2 in modern times.
If you want to build SDL, though...
SDL currently requires at least Emscripten 3.1.35 to build. Newer versions
are likely to work, as well.
Build:
$ mkdir build
$ cd build
$ emcmake cmake ..
$ emmake make
This works on Linux/Unix and macOS. Please send comments about Windows.
Or with cmake:
Make sure you've [installed emsdk](https://emscripten.org/docs/getting_started/downloads.html)
first, and run `source emsdk_env.sh` at the command line so it finds the
tools.
$ mkdir build
$ cd build
$ emcmake cmake ..
$ emmake make
(These cmake options might be overkill, but this has worked for me.)
To build one of the tests:
```bash
mkdir build
cd build
emcmake cmake ..
# you can also do `emcmake cmake -G Ninja ..` and then use `ninja` instead of this command.
emmake make -j4
```
$ cd test/
$ emcc -O2 --js-opts 0 -g4 testdraw.c -I../include ../build/.libs/libSDL3.a ../build/libSDL3_test.a -o a.html
If you want to build with thread support, something like this works:
Uses GLES2 renderer or software
```bash
mkdir build
cd build
emcmake cmake -DSDL_THREADS=On ..
# you can also do `emcmake cmake -G Ninja ..` and then use `ninja` instead of this command.
emmake make -j4
```
Some other SDL3 libraries can be easily built (assuming SDL3 is installed somewhere):
To build the tests, add `-DSDL_TESTS=On` to the `emcmake cmake` command line.
SDL_mixer (http://www.libsdl.org/projects/SDL_mixer/):
$ emcmake cmake ..
build as usual...
## Building your app
You need to compile with `emcc` instead of `gcc` or `clang` or whatever, but
mostly it uses the same command line arguments as Clang.
Link against the SDL/build/libSDL3.a file you generated by building SDL,
link with `-sUSE_SDL=2` to use Emscripten's prepackaged SDL2 build.
Usually you would produce a binary like this:
```bash
gcc -o mygame mygame.c # or whatever
```
But for Emscripten, you want to output something else:
```bash
emcc -o index.html mygame.c
```
This will produce several files...support Javascript and WebAssembly (.wasm)
files. The `-o index.html` will produce a simple HTML page that loads and
runs your app. You will (probably) eventually want to replace or customize
that file and do `-o index.js` instead to just build the code pieces.
If you're working on a program of any serious size, you'll likely need to
link with `-sALLOW_MEMORY_GROWTH=1 -sMAXIMUM_MEMORY=1gb` to get access
to more memory. If using pthreads, you'll need the `-sMAXIMUM_MEMORY=1gb`
or the app will fail to start on iOS browsers, but this might be a bug that
goes away in the future.
## Data files
Your game probably has data files. Here's how to access them.
Filesystem access works like a Unix filesystem; you have a single directory
tree, possibly interpolated from several mounted locations, no drive letters,
'/' for a path separator. You can access them with standard file APIs like
open() or fopen() or SDL_RWops. You can read or write from the filesystem.
By default, you probably have a "MEMFS" filesystem (all files are stored in
memory, but access to them is immediate and doesn't need to block). There are
other options, like "IDBFS" (files are stored in a local database, so they
don't need to be in RAM all the time and they can persist between runs of the
program, but access is not synchronous). You can mix and match these file
systems, mounting a MEMFS filesystem at one place and idbfs elsewhere, etc,
but that's beyond the scope of this document. Please refer to Emscripten's
[page on the topic](https://emscripten.org/docs/porting/files/file_systems_overview.html)
for more info.
The _easiest_ (but not the best) way to get at your data files is to embed
them in the app itself. Emscripten's linker has support for automating this.
```bash
emcc -o index.html loopwave.c --embed-file=../test/sample.wav@/sounds/sample.wav
```
This will pack ../test/sample.wav in your app, and make it available at
"/sounds/sample.wav" at runtime. Emscripten makes sure this data is available
before your main() function runs, and since it's in MEMFS, you can just
read it like you do on other platforms. `--embed-file` can also accept a
directory to pack an entire tree, and you can specify the argument multiple
times to pack unrelated things into the final installation.
Note that this is absolutely the best approach if you have a few small
files to include and shouldn't worry about the issue further. However, if you
have hundreds of megabytes and/or thousands of files, this is not so great,
since the user will download it all every time they load your page, and it
all has to live in memory at runtime.
[Emscripten's documentation on the matter](https://emscripten.org/docs/porting/files/packaging_files.html)
gives other options and details, and is worth a read.
## Debugging
Debugging web apps is a mixed bag. You should compile and link with
`-gsource-map`, which embeds a ton of source-level debugging information into
the build, and make sure _the app source code is available on the web server_,
which is often a scary proposition for various reasons.
When you debug from the browser's tools and hit a breakpoint, you can step
through the actual C/C++ source code, though, which can be nice.
If you try debugging in Firefox and it doesn't work well for no apparent
reason, try Chrome, and vice-versa. These tools are still relatively new,
and improving all the time.
SDL_Log() (or even plain old printf) will write to the Javascript console,
and honestly I find printf-style debugging to be easier than setting up a build
for proper debugging, so use whatever tools work best for you.
## Questions?
Please give us feedback on this document at [the SDL bug tracker](https://github.com/libsdl-org/SDL/issues).
If something is wrong or unclear, we want to know!
SDL_gfx (http://cms.ferzkopp.net/index.php/software/13-sdl-gfx):
$ emcmake cmake ..
build as usual...

View File

@ -29,6 +29,12 @@ The Windows GDK port supports the full set of Win32 APIs, renderers, controllers
* Global task queue callbacks are dispatched during `SDL_PumpEvents` (which is also called internally if using `SDL_PollEvent`).
* You can get the handle of the global task queue through `SDL_GDKGetTaskQueue`, if needed. When done with the queue, be sure to use `XTaskQueueCloseHandle` to decrement the reference count (otherwise it will cause a resource leak).
* Single-player games have some additional features available:
* Call `SDL_GDKGetDefaultUser` to get the default XUserHandle pointer.
* `SDL_GetPrefPath` still works, but only for single-player titles.
These functions mostly wrap around async APIs, and thus should be treated as synchronous alternatives. Also note that the single-player functions return on any OS errors, so be sure to validate the return values!
* What doesn't work:
* Compilation with anything other than through the included Visual C++ solution file

View File

@ -4,6 +4,8 @@ This guide provides useful information for migrating applications from SDL 2.0 t
Details on API changes are organized by SDL 2.0 header below.
The file with your main() function should include <SDL3/SDL_main.h>, as that is no longer included in SDL.h.
Many functions and symbols have been renamed. We have provided a handy Python script [rename_symbols.py](https://github.com/libsdl-org/SDL/blob/main/build-scripts/rename_symbols.py) to rename SDL2 functions to their SDL3 counterparts:
```sh
rename_symbols.py --all-symbols source_code_path
@ -11,14 +13,11 @@ rename_symbols.py --all-symbols source_code_path
It's also possible to apply a semantic patch to migrate more easily to SDL3: [SDL_migration.cocci](https://github.com/libsdl-org/SDL/blob/main/build-scripts/SDL_migration.cocci)
SDL headers should now be included as `#include <SDL3/SDL.h>`. Typically that's the only header you'll need in your application unless you are using OpenGL or Vulkan functionality. We have provided a handy Python script [rename_headers.py](https://github.com/libsdl-org/SDL/blob/main/build-scripts/rename_headers.py) to rename SDL2 headers to their SDL3 counterparts:
```sh
rename_headers.py source_code_path
```
The file with your main() function should also include <SDL3/SDL_main.h>, see below in the SDL_main.h section.
CMake users should use this snippet to include SDL support in their project:
```
find_package(SDL3 REQUIRED CONFIG REQUIRED COMPONENTS SDL3)
@ -39,10 +38,7 @@ LDFLAGS += $(shell pkg-config sdl3 --libs)
The SDL3test library has been renamed SDL3_test.
There is no SDLmain library anymore, it's now header-only, see below in the SDL_main.h section.
begin_code.h and close_code.h in the public headers have been renamed to SDL_begin_code.h and SDL_close_code.h. These aren't meant to be included directly by applications, but if your application did, please update your `#include` lines.
The SDLmain library has been removed, it's been entirely replaced by SDL_main.h.
The vi format comments have been removed from source code. Vim users can use the [editorconfig plugin](https://github.com/editorconfig/editorconfig-vim) to automatically set tab spacing for the SDL coding style.
@ -53,15 +49,15 @@ The following structures have been renamed:
## SDL_audio.h
The audio subsystem in SDL3 is dramatically different than SDL2. The primary way to play audio is no longer an audio callback; instead you bind SDL_AudioStreams to devices.
The audio subsystem in SDL3 is dramatically different than SDL2. The primary way to play audio is no longer an audio callback; instead you bind SDL_AudioStreams to devices; however, there is still a callback method available if needed.
The SDL 1.2 audio compatibility API has also been removed, as it was a simplified version of the audio callback interface.
SDL3 will not implicitly initialize the audio subsystem on your behalf if you open a device without doing so. Please explicitly call SDL_Init(SDL_INIT_AUDIO) at some point.
If your app depends on the callback method, there is a similar approach you can take. But first, this is the new approach:
SDL3's audio subsystem offers an enormous amount of power over SDL2, but if you just want a simple migration of your existing code, you can ignore most of it. The simplest migration path from SDL2 looks something like this:
In SDL2, you might have done something like this to play audio:
In SDL2, you might have done something like this to play audio...
```c
void SDLCALL MyAudioCallback(void *userdata, Uint8 * stream, int len)
@ -82,20 +78,7 @@ In SDL2, you might have done something like this to play audio:
SDL_PauseAudioDevice(my_audio_device, 0);
```
in SDL3:
```c
/* ...somewhere near startup... */
SDL_AudioSpec spec = { SDL_AUDIO_S16, 2, 44100 };
SDL_AudioDeviceID my_audio_device = SDL_OpenAudioDevice(SDL_AUDIO_DEVICE_DEFAULT_OUTPUT, &spec);
SDL_AudioSteam *stream = SDL_CreateAndBindAudioStream(my_audio_device, &spec);
/* ...in your main loop... */
/* calculate a little more audio into `buf`, add it to `stream` */
SDL_PutAudioStreamData(stream, buf, buflen);
```
If you absolutely require the callback method, SDL_AudioStreams can use a callback whenever more data is to be read from them, which can be used to simulate SDL2 semantics:
...in SDL3, you can do this...
```c
void SDLCALL MyAudioCallback(SDL_AudioStream *stream, int len, void *userdata)
@ -105,19 +88,32 @@ If you absolutely require the callback method, SDL_AudioStreams can use a callba
}
/* ...somewhere near startup... */
SDL_AudioSpec spec = { SDL_AUDIO_S16, 2, 44100 };
SDL_AudioDeviceID my_audio_device = SDL_OpenAudioDevice(SDL_AUDIO_DEVICE_DEFAULT_OUTPUT, &spec);
SDL_AudioSteam *stream = SDL_CreateAndBindAudioStream(my_audio_device, &spec);
SDL_SetAudioStreamGetCallback(stream, MyAudioCallback);
/* MyAudioCallback will be called whenever the device requests more audio data. */
const SDL_AudioSpec spec = { SDL_AUDIO_S16, 2, 44100 };
SDL_AudioStream *stream = SDL_OpenAudioDeviceStream(SDL_AUDIO_DEVICE_DEFAULT_OUTPUT, &spec, MyAudioCallback, &my_audio_callback_user_data);
SDL_ResumeAudioDevice(SDL_GetAudioStreamDevice(stream));
```
If you used SDL_QueueAudio instead of a callback in SDL2, this is also straightforward.
```c
/* ...somewhere near startup... */
const SDL_AudioSpec spec = { SDL_AUDIO_S16, 2, 44100 };
SDL_AudioStream *stream = SDL_OpenAudioDeviceStream(SDL_AUDIO_DEVICE_DEFAULT_OUTPUT, &spec, NULL, NULL);
SDL_ResumeAudioDevice(SDL_GetAudioStreamDevice(stream));
/* ...in your main loop... */
/* calculate a little more audio into `buf`, add it to `stream` */
SDL_PutAudioStreamData(stream, buf, buflen);
```
...these same migration examples apply to audio capture, just using SDL_GetAudioStreamData instead of SDL_PutAudioStreamData.
SDL_AudioInit() and SDL_AudioQuit() have been removed. Instead you can call SDL_InitSubSystem() and SDL_QuitSubSystem() with SDL_INIT_AUDIO, which will properly refcount the subsystems. You can choose a specific audio driver using SDL_AUDIO_DRIVER hint.
The `SDL_AUDIO_ALLOW_*` symbols have been removed; now one may request the format they desire from the audio device, but ultimately SDL_AudioStream will manage the difference. One can use SDL_GetAudioDeviceFormat() to see what the final format is, if any "allowed" changes should be accomodated by the app.
SDL_AudioDeviceID now represents both an open audio device's handle (a "logical" device) and the instance ID that the hardware owns as long as it exists on the system (a "physical" device). The separation between device instances and device indexes is gone.
SDL_AudioDeviceID now represents both an open audio device's handle (a "logical" device) and the instance ID that the hardware owns as long as it exists on the system (a "physical" device). The separation between device instances and device indexes is gone, and logical and physical devices are almost entirely interchangeable at the API level.
Devices are opened by physical device instance ID, and a new logical instance ID is generated by the open operation; This allows any device to be opened multiple times, possibly by unrelated pieces of code. SDL will manage the logical devices to provide a single stream of audio to the physical device behind the scenes.
@ -125,13 +121,13 @@ Devices are not opened by an arbitrary string name anymore, but by device instan
Many functions that would accept a device index and an `iscapture` parameter now just take an SDL_AudioDeviceID, as they are unique across all devices, instead of separate indices into output and capture device lists.
Rather than iterating over audio devices using a device index, there is a new function, SDL_GetAudioDevices(), to get the current list of devices, and new functions to get information about devices from their instance ID:
Rather than iterating over audio devices using a device index, there are new functions, SDL_GetAudioOutputDevices() and SDL_GetAudioCaptureDevices(), to get the current list of devices, and new functions to get information about devices from their instance ID:
```c
{
if (SDL_InitSubSystem(SDL_INIT_AUDIO) == 0) {
int i, num_devices;
SDL_AudioDeviceID *devices = SDL_GetAudioDevices(/*iscapture=*/SDL_FALSE, &num_devices);
SDL_AudioDeviceID *devices = SDL_GetAudioOutputDevices(&num_devices);
if (devices) {
for (i = 0; i < num_devices; ++i) {
SDL_AudioDeviceID instance_id = devices[i];
@ -152,7 +148,7 @@ SDL_PauseAudioDevice() no longer takes a second argument; it always pauses the d
Audio devices, opened by SDL_OpenAudioDevice(), no longer start in a paused state, as they don't begin processing audio until a stream is bound.
SDL_GetAudioDeviceStatus() has been removed; there is now SDL_IsAudioDevicePaused().
SDL_GetAudioDeviceStatus() has been removed; there is now SDL_AudioDevicePaused().
SDL_QueueAudio(), SDL_DequeueAudio, and SDL_ClearQueuedAudio and SDL_GetQueuedAudioSize() have been removed; an SDL_AudioStream bound to a device provides the exact same functionality.
@ -259,18 +255,18 @@ The following functions have been removed:
* SDL_GetQueuedAudioSize()
The following symbols have been renamed:
* AUDIO_F32 => SDL_AUDIO_F32
* AUDIO_F32LSB => SDL_AUDIO_F32LSB
* AUDIO_F32MSB => SDL_AUDIO_F32MSB
* AUDIO_F32SYS => SDL_AUDIO_F32SYS
* AUDIO_S16 => SDL_AUDIO_S16
* AUDIO_S16LSB => SDL_AUDIO_S16LSB
* AUDIO_S16MSB => SDL_AUDIO_S16MSB
* AUDIO_S16SYS => SDL_AUDIO_S16SYS
* AUDIO_S32 => SDL_AUDIO_S32
* AUDIO_S32LSB => SDL_AUDIO_S32LSB
* AUDIO_S32MSB => SDL_AUDIO_S32MSB
* AUDIO_S32SYS => SDL_AUDIO_S32SYS
* AUDIO_F32 => SDL_AUDIO_F32LE
* AUDIO_F32LSB => SDL_AUDIO_F32LE
* AUDIO_F32MSB => SDL_AUDIO_F32BE
* AUDIO_F32SYS => SDL_AUDIO_F32
* AUDIO_S16 => SDL_AUDIO_S16LE
* AUDIO_S16LSB => SDL_AUDIO_S16LE
* AUDIO_S16MSB => SDL_AUDIO_S16BE
* AUDIO_S16SYS => SDL_AUDIO_S16
* AUDIO_S32 => SDL_AUDIO_S32LE
* AUDIO_S32LSB => SDL_AUDIO_S32LE
* AUDIO_S32MSB => SDL_AUDIO_S32BE
* AUDIO_S32SYS => SDL_AUDIO_S32
* AUDIO_S8 => SDL_AUDIO_S8
* AUDIO_U8 => SDL_AUDIO_U8
@ -378,8 +374,6 @@ The SDL_EVENT_GAMEPAD_ADDED event now provides the joystick instance ID in the w
The functions SDL_GetGamepads(), SDL_GetGamepadInstanceName(), SDL_GetGamepadInstancePath(), SDL_GetGamepadInstancePlayerIndex(), SDL_GetGamepadInstanceGUID(), SDL_GetGamepadInstanceVendor(), SDL_GetGamepadInstanceProduct(), SDL_GetGamepadInstanceProductVersion(), and SDL_GetGamepadInstanceType() have been added to directly query the list of available gamepads.
The gamepad binding structure has been removed in favor of exchanging bindings in text format.
SDL_GameControllerGetSensorDataWithTimestamp() has been removed. If you want timestamps for the sensor data, you should use the sensor_timestamp member of SDL_EVENT_GAMEPAD_SENSOR_UPDATE events.
SDL_CONTROLLER_TYPE_VIRTUAL has been removed, so virtual controllers can emulate other gamepad types. If you need to know whether a controller is virtual, you can use SDL_IsJoystickVirtual().
@ -417,7 +411,6 @@ The following enums have been renamed:
The following structures have been renamed:
* SDL_GameController => SDL_Gamepad
* SDL_GameControllerButtonBind => SDL_GamepadBinding
The following functions have been renamed:
* SDL_GameControllerAddMapping() => SDL_AddGamepadMapping()
@ -431,8 +424,6 @@ The following functions have been renamed:
* SDL_GameControllerGetAttached() => SDL_GamepadConnected()
* SDL_GameControllerGetAxis() => SDL_GetGamepadAxis()
* SDL_GameControllerGetAxisFromString() => SDL_GetGamepadAxisFromString()
* SDL_GameControllerGetBindForAxis() => SDL_GetGamepadBindForAxis()
* SDL_GameControllerGetBindForButton() => SDL_GetGamepadBindForButton()
* SDL_GameControllerGetButton() => SDL_GetGamepadButton()
* SDL_GameControllerGetButtonFromString() => SDL_GetGamepadButtonFromString()
* SDL_GameControllerGetFirmwareVersion() => SDL_GetGamepadFirmwareVersion()
@ -475,8 +466,8 @@ The following functions have been renamed:
The following functions have been removed:
* SDL_GameControllerEventState() - replaced with SDL_SetGamepadEventsEnabled() and SDL_GamepadEventsEnabled()
* SDL_GameControllerGetBindForAxis()
* SDL_GameControllerGetBindForButton()
* SDL_GameControllerGetBindForAxis() - replaced with SDL_GetGamepadBindings()
* SDL_GameControllerGetBindForButton() - replaced with SDL_GetGamepadBindings()
* SDL_GameControllerMappingForDeviceIndex() - replaced with SDL_GetGamepadInstanceMapping()
* SDL_GameControllerNameForIndex() - replaced with SDL_GetGamepadInstanceName()
* SDL_GameControllerPathForIndex() - replaced with SDL_GetGamepadInstancePath()
@ -699,27 +690,6 @@ Instead SDL_main.h is now a header-only library **and not included by SDL.h anym
Using it is really simple: Just `#include <SDL3/SDL_main.h>` in the source file with your standard
`int main(int argc, char* argv[])` function.
The rest happens automatically: If your target platform needs the SDL_main functionality,
your main function will be renamed to SDL_main (with a macro, just like in SDL2),
and the real main-function will be implemented by inline code from SDL_main.h - and if your target
platform doesn't need it, nothing happens.
Like in SDL2, if you want to handle the platform-specific main yourself instead of using the SDL_main magic,
you can `#define SDL_MAIN_HANDLED` before `#include <SDL3/SDL_main.h>` - don't forget to call SDL_SetMainReady()
If you need SDL_main.h in another source file (that doesn't implement main()), you also need to
`#define SDL_MAIN_HANDLED` there, to avoid that multiple main functions are generated by SDL_main.h
There is currently one platform where this approach doesn't always work: WinRT.
It requires WinMain to be implemented in a C++ source file that's compiled with `/ZW`. If your main
is implemented in plain C, or you can't use `/ZW` on that file, you can add another .cpp
source file that just contains `#include <SDL3/SDL_main.h>` and compile that with `/ZW` - but keep
in mind that the source file with your standard main also needs that include!
See [README-winrt.md](./README-winrt.md) for more details.
Furthermore, the different SDL_*RunApp() functions (SDL_WinRtRunApp, SDL_GDKRunApp, SDL_UIKitRunApp)
have been unified into just `int SDL_RunApp(int argc, char* argv[], void * reserved)` (which is also
used by additional platforms that didn't have a SDL_RunApp-like function before).
## SDL_metal.h
SDL_Metal_GetDrawableSize() has been removed. SDL_GetWindowSizeInPixels() can be used in its place.

View File

@ -34,3 +34,12 @@ encounter limitations or behavior that is different from other windowing systems
### Warping the global mouse cursor position via ```SDL_WarpMouseGlobal()``` doesn't work
- For security reasons, Wayland does not allow warping the global mouse cursor position.
### The application icon can't be set via ```SDL_SetWindowIcon()```
- Wayland doesn't support programmatically setting the application icon. To provide a custom icon for your application,
you must create an associated desktop entry file, aka a `.desktop` file, that points to the icon image. Please see the
[Desktop Entry Specification](https://specifications.freedesktop.org/desktop-entry-spec/latest/) for more information
on the format of this file. Note that if your application manually sets the application ID via the `SDL_APP_ID` hint
string, the desktop entry file name should match the application ID. For example, if your application ID is set
to `org.my_org.sdl_app`, the desktop entry file should be named `org.my_org.sdl_app.desktop`.

View File

@ -56,3 +56,11 @@ it change the value of `SDL_VIDEO_VULKAN` to 0 in `SDL_config_windows.h`. You
must install the [Vulkan SDK](https://www.lunarg.com/vulkan-sdk/) in order to
use Vulkan graphics in your application.
## Transparent Window Support
SDL uses the Desktop Window Manager (DWM) to create transparent windows. DWM is
always enabled from Windows 8 and above. Windows 7 only enables DWM with Aero Glass
theme.
However, it cannot be guaranteed to work on all hardware configurations (an example
is hybrid GPU systems, such as NVIDIA Optimus laptops).

View File

@ -64,6 +64,8 @@ assert can have unique static variables associated with it.
#define SDL_TriggerBreakpoint() __builtin_debugtrap()
#elif (defined(__GNUC__) || defined(__clang__)) && (defined(__i386__) || defined(__x86_64__))
#define SDL_TriggerBreakpoint() __asm__ __volatile__ ( "int $3\n\t" )
#elif (defined(__GNUC__) || defined(__clang__)) && defined(__riscv)
#define SDL_TriggerBreakpoint() __asm__ __volatile__ ( "ebreak\n\t" )
#elif ( defined(__APPLE__) && (defined(__arm64__) || defined(__aarch64__)) ) /* this might work on other ARM targets, but this is a known quantity... */
#define SDL_TriggerBreakpoint() __asm__ __volatile__ ( "brk #22\n\t" )
#elif defined(__APPLE__) && defined(__arm__)

View File

@ -80,15 +80,16 @@ typedef Uint16 SDL_AudioFormat;
/* @{ */
#define SDL_AUDIO_MASK_BITSIZE (0xFF)
#define SDL_AUDIO_MASK_DATATYPE (1<<8)
#define SDL_AUDIO_MASK_ENDIAN (1<<12)
#define SDL_AUDIO_MASK_FLOAT (1<<8)
#define SDL_AUDIO_MASK_BIG_ENDIAN (1<<12)
#define SDL_AUDIO_MASK_SIGNED (1<<15)
#define SDL_AUDIO_BITSIZE(x) (x & SDL_AUDIO_MASK_BITSIZE)
#define SDL_AUDIO_ISFLOAT(x) (x & SDL_AUDIO_MASK_DATATYPE)
#define SDL_AUDIO_ISBIGENDIAN(x) (x & SDL_AUDIO_MASK_ENDIAN)
#define SDL_AUDIO_ISSIGNED(x) (x & SDL_AUDIO_MASK_SIGNED)
#define SDL_AUDIO_ISINT(x) (!SDL_AUDIO_ISFLOAT(x))
#define SDL_AUDIO_BITSIZE(x) ((x) & SDL_AUDIO_MASK_BITSIZE)
#define SDL_AUDIO_BYTESIZE(x) (SDL_AUDIO_BITSIZE(x) / 8)
#define SDL_AUDIO_ISFLOAT(x) ((x) & SDL_AUDIO_MASK_FLOAT)
#define SDL_AUDIO_ISBIGENDIAN(x) ((x) & SDL_AUDIO_MASK_BIG_ENDIAN)
#define SDL_AUDIO_ISLITTLEENDIAN(x) (!SDL_AUDIO_ISBIGENDIAN(x))
#define SDL_AUDIO_ISSIGNED(x) ((x) & SDL_AUDIO_MASK_SIGNED)
#define SDL_AUDIO_ISINT(x) (!SDL_AUDIO_ISFLOAT(x))
#define SDL_AUDIO_ISUNSIGNED(x) (!SDL_AUDIO_ISSIGNED(x))
/**
@ -99,27 +100,24 @@ typedef Uint16 SDL_AudioFormat;
/* @{ */
#define SDL_AUDIO_U8 0x0008 /**< Unsigned 8-bit samples */
#define SDL_AUDIO_S8 0x8008 /**< Signed 8-bit samples */
#define SDL_AUDIO_S16LSB 0x8010 /**< Signed 16-bit samples */
#define SDL_AUDIO_S16MSB 0x9010 /**< As above, but big-endian byte order */
#define SDL_AUDIO_S16 SDL_AUDIO_S16LSB
#define SDL_AUDIO_S16LE 0x8010 /**< Signed 16-bit samples */
#define SDL_AUDIO_S16BE 0x9010 /**< As above, but big-endian byte order */
/* @} */
/**
* \name int32 support
*/
/* @{ */
#define SDL_AUDIO_S32LSB 0x8020 /**< 32-bit integer samples */
#define SDL_AUDIO_S32MSB 0x9020 /**< As above, but big-endian byte order */
#define SDL_AUDIO_S32 SDL_AUDIO_S32LSB
#define SDL_AUDIO_S32LE 0x8020 /**< 32-bit integer samples */
#define SDL_AUDIO_S32BE 0x9020 /**< As above, but big-endian byte order */
/* @} */
/**
* \name float32 support
*/
/* @{ */
#define SDL_AUDIO_F32LSB 0x8120 /**< 32-bit floating point samples */
#define SDL_AUDIO_F32MSB 0x9120 /**< As above, but big-endian byte order */
#define SDL_AUDIO_F32 SDL_AUDIO_F32LSB
#define SDL_AUDIO_F32LE 0x8120 /**< 32-bit floating point samples */
#define SDL_AUDIO_F32BE 0x9120 /**< As above, but big-endian byte order */
/* @} */
/**
@ -127,13 +125,13 @@ typedef Uint16 SDL_AudioFormat;
*/
/* @{ */
#if SDL_BYTEORDER == SDL_LIL_ENDIAN
#define SDL_AUDIO_S16SYS SDL_AUDIO_S16LSB
#define SDL_AUDIO_S32SYS SDL_AUDIO_S32LSB
#define SDL_AUDIO_F32SYS SDL_AUDIO_F32LSB
#define SDL_AUDIO_S16 SDL_AUDIO_S16LE
#define SDL_AUDIO_S32 SDL_AUDIO_S32LE
#define SDL_AUDIO_F32 SDL_AUDIO_F32LE
#else
#define SDL_AUDIO_S16SYS SDL_AUDIO_S16MSB
#define SDL_AUDIO_S32SYS SDL_AUDIO_S32MSB
#define SDL_AUDIO_F32SYS SDL_AUDIO_F32MSB
#define SDL_AUDIO_S16 SDL_AUDIO_S16BE
#define SDL_AUDIO_S32 SDL_AUDIO_S32BE
#define SDL_AUDIO_F32 SDL_AUDIO_F32BE
#endif
/* @} */
@ -154,6 +152,9 @@ typedef struct SDL_AudioSpec
int freq; /**< sample rate: sample frames per second */
} SDL_AudioSpec;
/* Calculate the size of each audio frame (in bytes) */
#define SDL_AUDIO_FRAMESIZE(x) (SDL_AUDIO_BYTESIZE((x).format) * (x).channels)
/* SDL_AudioStream is an audio conversion interface.
- It can handle resampling data in chunks without generating
artifacts, when it doesn't have the complete buffer available.
@ -308,7 +309,8 @@ extern DECLSPEC SDL_AudioDeviceID *SDLCALL SDL_GetAudioCaptureDevices(int *count
*
* \since This function is available since SDL 3.0.0.
*
* \sa SDL_GetNumAudioDevices
* \sa SDL_GetAudioOutputDevices
* \sa SDL_GetAudioCaptureDevices
* \sa SDL_GetDefaultAudioInfo
*/
extern DECLSPEC char *SDLCALL SDL_GetAudioDeviceName(SDL_AudioDeviceID devid);
@ -325,8 +327,20 @@ extern DECLSPEC char *SDLCALL SDL_GetAudioDeviceName(SDL_AudioDeviceID devid);
* reasonable recommendation before opening the system-recommended default
* device.
*
* You can also use this to request the current device buffer size. This is
* specified in sample frames and represents the amount of data SDL will feed
* to the physical hardware in each chunk. This can be converted to
* milliseconds of audio with the following equation:
*
* `ms = (int) ((((Sint64) frames) * 1000) / spec.freq);`
*
* Buffer size is only important if you need low-level control over the audio
* playback timing. Most apps do not need this.
*
* \param devid the instance ID of the device to query.
* \param spec On return, will be filled with device details.
* \param sample_frames Pointer to store device buffer size, in sample frames.
* Can be NULL.
* \returns 0 on success or a negative error code on failure; call
* SDL_GetError() for more information.
*
@ -334,7 +348,7 @@ extern DECLSPEC char *SDLCALL SDL_GetAudioDeviceName(SDL_AudioDeviceID devid);
*
* \since This function is available since SDL 3.0.0.
*/
extern DECLSPEC int SDLCALL SDL_GetAudioDeviceFormat(SDL_AudioDeviceID devid, SDL_AudioSpec *spec);
extern DECLSPEC int SDLCALL SDL_GetAudioDeviceFormat(SDL_AudioDeviceID devid, SDL_AudioSpec *spec, int *sample_frames);
/**
@ -348,9 +362,9 @@ extern DECLSPEC int SDLCALL SDL_GetAudioDeviceFormat(SDL_AudioDeviceID devid, SD
* An opened audio device starts out with no audio streams bound. To start
* audio playing, bind a stream and supply audio data to it. Unlike SDL2,
* there is no audio callback; you only bind audio streams and make sure they
* have data flowing into them (although, as an optional feature, each audio
* stream may have its own callback, which can be used to simulate SDL2's
* semantics).
* have data flowing into them (however, you can simulate SDL2's semantics
* fairly closely by using SDL_OpenAudioDeviceStream instead of this
* function).
*
* If you don't care about opening a specific device, pass a `devid` of either
* `SDL_AUDIO_DEVICE_DEFAULT_OUTPUT` or `SDL_AUDIO_DEVICE_DEFAULT_CAPTURE`. In
@ -439,7 +453,7 @@ extern DECLSPEC SDL_AudioDeviceID SDLCALL SDL_OpenAudioDevice(SDL_AudioDeviceID
* \since This function is available since SDL 3.0.0.
*
* \sa SDL_ResumeAudioDevice
* \sa SDL_IsAudioDevicePaused
* \sa SDL_AudioDevicePaused
*/
extern DECLSPEC int SDLCALL SDL_PauseAudioDevice(SDL_AudioDeviceID dev);
@ -466,8 +480,8 @@ extern DECLSPEC int SDLCALL SDL_PauseAudioDevice(SDL_AudioDeviceID dev);
*
* \since This function is available since SDL 3.0.0.
*
* \sa SDL_ResumeAudioDevice
* \sa SDL_IsAudioDevicePaused
* \sa SDL_AudioDevicePaused
* \sa SDL_PauseAudioDevice
*/
extern DECLSPEC int SDLCALL SDL_ResumeAudioDevice(SDL_AudioDeviceID dev);
@ -490,9 +504,8 @@ extern DECLSPEC int SDLCALL SDL_ResumeAudioDevice(SDL_AudioDeviceID dev);
*
* \sa SDL_PauseAudioDevice
* \sa SDL_ResumeAudioDevice
* \sa SDL_IsAudioDevicePaused
*/
extern DECLSPEC SDL_bool SDLCALL SDL_IsAudioDevicePaused(SDL_AudioDeviceID dev);
extern DECLSPEC SDL_bool SDLCALL SDL_AudioDevicePaused(SDL_AudioDeviceID dev);
/**
* Close a previously-opened audio device.
@ -549,7 +562,7 @@ extern DECLSPEC void SDLCALL SDL_CloseAudioDevice(SDL_AudioDeviceID devid);
* \sa SDL_BindAudioStreams
* \sa SDL_UnbindAudioStreams
* \sa SDL_UnbindAudioStream
* \sa SDL_GetAudioStreamBinding
* \sa SDL_GetAudioStreamDevice
*/
extern DECLSPEC int SDLCALL SDL_BindAudioStreams(SDL_AudioDeviceID devid, SDL_AudioStream **streams, int num_streams);
@ -571,7 +584,7 @@ extern DECLSPEC int SDLCALL SDL_BindAudioStreams(SDL_AudioDeviceID devid, SDL_Au
* \sa SDL_BindAudioStreams
* \sa SDL_UnbindAudioStreams
* \sa SDL_UnbindAudioStream
* \sa SDL_GetAudioStreamBinding
* \sa SDL_GetAudioStreamDevice
*/
extern DECLSPEC int SDLCALL SDL_BindAudioStream(SDL_AudioDeviceID devid, SDL_AudioStream *stream);
@ -595,7 +608,7 @@ extern DECLSPEC int SDLCALL SDL_BindAudioStream(SDL_AudioDeviceID devid, SDL_Aud
* \sa SDL_BindAudioStreams
* \sa SDL_BindAudioStream
* \sa SDL_UnbindAudioStream
* \sa SDL_GetAudioStreamBinding
* \sa SDL_GetAudioStreamDevice
*/
extern DECLSPEC void SDLCALL SDL_UnbindAudioStreams(SDL_AudioStream **streams, int num_streams);
@ -614,7 +627,7 @@ extern DECLSPEC void SDLCALL SDL_UnbindAudioStreams(SDL_AudioStream **streams, i
* \sa SDL_BindAudioStream
* \sa SDL_BindAudioStreams
* \sa SDL_UnbindAudioStreams
* \sa SDL_GetAudioStreamBinding
* \sa SDL_GetAudioStreamDevice
*/
extern DECLSPEC void SDLCALL SDL_UnbindAudioStream(SDL_AudioStream *stream);
@ -638,7 +651,7 @@ extern DECLSPEC void SDLCALL SDL_UnbindAudioStream(SDL_AudioStream *stream);
* \sa SDL_UnbindAudioStream
* \sa SDL_UnbindAudioStreams
*/
extern DECLSPEC SDL_AudioDeviceID SDLCALL SDL_GetAudioStreamBinding(SDL_AudioStream *stream);
extern DECLSPEC SDL_AudioDeviceID SDLCALL SDL_GetAudioStreamDevice(SDL_AudioStream *stream);
/**
@ -703,11 +716,54 @@ extern DECLSPEC int SDLCALL SDL_GetAudioStreamFormat(SDL_AudioStream *stream,
* \sa SDL_PutAudioStreamData
* \sa SDL_GetAudioStreamData
* \sa SDL_GetAudioStreamAvailable
* \sa SDL_SetAudioStreamFrequencyRatio
*/
extern DECLSPEC int SDLCALL SDL_SetAudioStreamFormat(SDL_AudioStream *stream,
const SDL_AudioSpec *src_spec,
const SDL_AudioSpec *dst_spec);
/**
* Get the frequency ratio of an audio stream.
*
* \param stream the SDL_AudioStream to query.
* \returns the frequency ratio of the stream, or 0.0 on error
*
* \threadsafety It is safe to call this function from any thread, as it holds
* a stream-specific mutex while running.
*
* \since This function is available since SDL 3.0.0.
*
* \sa SDL_SetAudioStreamFrequencyRatio
*/
extern DECLSPEC float SDLCALL SDL_GetAudioStreamFrequencyRatio(SDL_AudioStream *stream);
/**
* Change the frequency ratio of an audio stream.
*
* The frequency ratio is used to adjust the rate at which input data is
* consumed. Changing this effectively modifies the speed and pitch of the
* audio. A value greater than 1.0 will play the audio faster, and at a higher
* pitch. A value less than 1.0 will play the audio slower, and at a lower
* pitch.
*
* This is applied during SDL_GetAudioStreamData, and can be continuously
* changed to create various effects.
*
* \param stream The stream the frequency ratio is being changed
* \param ratio The frequency ratio. 1.0 is normal speed. Must be between 0.01
* and 100.
* \returns 0 on success, or -1 on error.
*
* \threadsafety It is safe to call this function from any thread, as it holds
* a stream-specific mutex while running.
*
* \since This function is available since SDL 3.0.0.
*
* \sa SDL_GetAudioStreamFrequencyRatio
* \sa SDL_SetAudioStreamFormat
*/
extern DECLSPEC int SDLCALL SDL_SetAudioStreamFrequencyRatio(SDL_AudioStream *stream, float ratio);
/**
* Add data to be converted/resampled to the stream.
*
@ -802,6 +858,40 @@ extern DECLSPEC int SDLCALL SDL_GetAudioStreamData(SDL_AudioStream *stream, void
*/
extern DECLSPEC int SDLCALL SDL_GetAudioStreamAvailable(SDL_AudioStream *stream);
/**
* Get the number of bytes currently queued.
*
* Note that audio streams can change their input format at any time, even if
* there is still data queued in a different format, so the returned byte
* count will not necessarily match the number of _sample frames_ available.
* Users of this API should be aware of format changes they make when feeding
* a stream and plan accordingly.
*
* Queued data is not converted until it is consumed by
* SDL_GetAudioStreamData, so this value should be representative of the exact
* data that was put into the stream.
*
* If the stream has so much data that it would overflow an int, the return
* value is clamped to a maximum value, but no queued data is lost; if there
* are gigabytes of data queued, the app might need to read some of it with
* SDL_GetAudioStreamData before this function's return value is no longer
* clamped.
*
* \param stream The audio stream to query
* \returns the number of bytes queued.
*
* \threadsafety It is safe to call this function from any thread.
*
* \since This function is available since SDL 3.0.0.
*
* \sa SDL_PutAudioStreamData
* \sa SDL_GetAudioStreamData
* \sa SDL_ClearAudioStream
*/
extern DECLSPEC int SDLCALL SDL_GetAudioStreamQueued(SDL_AudioStream *stream);
/**
* Tell the stream that you're done sending data, and anything being buffered
* should be converted/resampled and made available immediately.
@ -909,13 +999,22 @@ extern DECLSPEC int SDLCALL SDL_UnlockAudioStream(SDL_AudioStream *stream);
* before your callback is called, so your callback does not need to
* manage the lock explicitly.
*
* Two values are offered here: one is the amount of additional data needed
* to satisfy the immediate request (which might be zero if the stream
* already has enough data queued) and the other is the total amount
* being requested. In a Get call triggering a Put callback, these
* values can be different. In a Put call triggering a Get callback,
* these values are always the same.
*
* Byte counts might be slightly overestimated due to buffering or
* resampling, and may change from call to call.
*
* \param stream The SDL audio stream associated with this callback.
* \param approx_request The _approximate_ amout of data, in bytes, that is requested.
* This might be slightly overestimated due to buffering or
* resampling, and may change from call to call anyhow.
* \param additional_amount The amount of data, in bytes, that is needed right now.
* \param total_amount The total amount of data requested, in bytes, that is requested or available.
* \param userdata An opaque pointer provided by the app for their personal use.
*/
typedef void (SDLCALL *SDL_AudioStreamRequestCallback)(SDL_AudioStream *stream, int approx_request, void *userdata);
typedef void (SDLCALL *SDL_AudioStreamCallback)(void *userdata, SDL_AudioStream *stream, int additional_amount, int total_amount);
/**
* Set a callback that runs when data is requested from an audio stream.
@ -960,7 +1059,7 @@ typedef void (SDLCALL *SDL_AudioStreamRequestCallback)(SDL_AudioStream *stream,
*
* \sa SDL_SetAudioStreamPutCallback
*/
extern DECLSPEC int SDLCALL SDL_SetAudioStreamGetCallback(SDL_AudioStream *stream, SDL_AudioStreamRequestCallback callback, void *userdata);
extern DECLSPEC int SDLCALL SDL_SetAudioStreamGetCallback(SDL_AudioStream *stream, SDL_AudioStreamCallback callback, void *userdata);
/**
* Set a callback that runs when data is added to an audio stream.
@ -1008,7 +1107,7 @@ extern DECLSPEC int SDLCALL SDL_SetAudioStreamGetCallback(SDL_AudioStream *strea
*
* \sa SDL_SetAudioStreamGetCallback
*/
extern DECLSPEC int SDLCALL SDL_SetAudioStreamPutCallback(SDL_AudioStream *stream, SDL_AudioStreamRequestCallback callback, void *userdata);
extern DECLSPEC int SDLCALL SDL_SetAudioStreamPutCallback(SDL_AudioStream *stream, SDL_AudioStreamCallback callback, void *userdata);
/**
@ -1031,32 +1130,125 @@ extern DECLSPEC void SDLCALL SDL_DestroyAudioStream(SDL_AudioStream *stream);
/**
* Convenience function to create and bind an audio stream in one step.
* Convenience function for straightforward audio init for the common case.
*
* This manages the creation of an audio stream, and setting its format
* correctly to match both the app and the audio device's needs. This is
* optional, but slightly less cumbersome to set up for a common use case.
* If all your app intends to do is provide a single source of PCM audio, this
* function allows you to do all your audio setup in a single call.
*
* This is intended to be a clean means to migrate apps from SDL2.
*
* This function will open an audio device, create a stream and bind it.
* Unlike other methods of setup, the audio device will be closed when this
* stream is destroyed, so the app can treat the returned SDL_AudioStream as
* the only object needed to manage audio playback.
*
* Also unlike other functions, the audio device begins paused. This is to map
* more closely to SDL2-style behavior, and since there is no extra step here
* to bind a stream to begin audio flowing. The audio device should be resumed
* with SDL_ResumeAudioDevice(SDL_GetAudioStreamDevice(stream));
*
* This function works with both playback and capture devices.
*
* The `spec` parameter represents the app's side of the audio stream. That
* is, for recording audio, this will be the output format, and for playing
* audio, this will be the input format. This function will set the other side
* of the audio stream to the device's format.
* audio, this will be the input format.
*
* \param devid an audio device to bind a stream to. This must be an opened
* device, and can not be zero.
* \param spec the audio stream's input format
* \returns a bound audio stream on success, ready to use. NULL on error; call
* SDL_GetError() for more information.
* If you don't care about opening a specific audio device, you can (and
* probably _should_), use SDL_AUDIO_DEVICE_DEFAULT_OUTPUT for playback and
* SDL_AUDIO_DEVICE_DEFAULT_CAPTURE for recording.
*
* One can optionally provide a callback function; if NULL, the app is
* expected to queue audio data for playback (or unqueue audio data if
* capturing). Otherwise, the callback will begin to fire once the device is
* unpaused.
*
* \param devid an audio device to open, or SDL_AUDIO_DEVICE_DEFAULT_OUTPUT or
* SDL_AUDIO_DEVICE_DEFAULT_CAPTURE.
* \param spec the audio stream's data format. Required.
* \param callback A callback where the app will provide new data for
* playback, or receive new data for capture. Can be NULL, in
* which case the app will need to call SDL_PutAudioStreamData
* or SDL_GetAudioStreamData as necessary.
* \param userdata App-controlled pointer passed to callback. Can be NULL.
* Ignored if callback is NULL.
* \returns an audio stream on success, ready to use. NULL on error; call
* SDL_GetError() for more information. When done with this stream,
* call SDL_DestroyAudioStream to free resources and close the
* device.
*
* \threadsafety It is safe to call this function from any thread.
*
* \since This function is available since SDL 3.0.0.
*
* \sa SDL_BindAudioStreams
* \sa SDL_UnbindAudioStreams
* \sa SDL_UnbindAudioStream
* \sa SDL_GetAudioStreamDevice
* \sa SDL_ResumeAudioDevice
*/
extern DECLSPEC SDL_AudioStream *SDLCALL SDL_CreateAndBindAudioStream(SDL_AudioDeviceID devid, const SDL_AudioSpec *spec);
extern DECLSPEC SDL_AudioStream *SDLCALL SDL_OpenAudioDeviceStream(SDL_AudioDeviceID devid, const SDL_AudioSpec *spec, SDL_AudioStreamCallback callback, void *userdata);
/**
* A callback that fires when data is about to be fed to an audio device.
*
* This is useful for accessing the final mix, perhaps for writing a
* visualizer or applying a final effect to the audio data before playback.
*
* \sa SDL_SetAudioDevicePostmixCallback
*/
typedef void (SDLCALL *SDL_AudioPostmixCallback)(void *userdata, const SDL_AudioSpec *spec, float *buffer, int buflen);
/**
* Set a callback that fires when data is about to be fed to an audio device.
*
* This is useful for accessing the final mix, perhaps for writing a
* visualizer or applying a final effect to the audio data before playback.
*
* The buffer is the final mix of all bound audio streams on an opened device;
* this callback will fire regularly for any device that is both opened and
* unpaused. If there is no new data to mix, either because no streams are
* bound to the device or all the streams are empty, this callback will still
* fire with the entire buffer set to silence.
*
* This callback is allowed to make changes to the data; the contents of the
* buffer after this call is what is ultimately passed along to the hardware.
*
* The callback is always provided the data in float format (values from -1.0f
* to 1.0f), but the number of channels or sample rate may be different than
* the format the app requested when opening the device; SDL might have had to
* manage a conversion behind the scenes, or the playback might have jumped to
* new physical hardware when a system default changed, etc. These details may
* change between calls. Accordingly, the size of the buffer might change
* between calls as well.
*
* This callback can run at any time, and from any thread; if you need to
* serialize access to your app's data, you should provide and use a mutex or
* other synchronization device.
*
* All of this to say: there are specific needs this callback can fulfill, but
* it is not the simplest interface. Apps should generally provide audio in
* their preferred format through an SDL_AudioStream and let SDL handle the
* difference.
*
* This function is extremely time-sensitive; the callback should do the least
* amount of work possible and return as quickly as it can. The longer the
* callback runs, the higher the risk of audio dropouts or other problems.
*
* This function will block until the audio device is in between iterations,
* so any existing callback that might be running will finish before this
* function sets the new callback and returns.
*
* Setting a NULL callback function disables any previously-set callback.
*
* \param devid The ID of an opened audio device.
* \param callback A callback function to be called. Can be NULL.
* \param userdata App-controlled pointer passed to callback. Can be NULL.
* \returns zero on success, -1 on error; call SDL_GetError() for more
* information.
*
* \threadsafety It is safe to call this function from any thread.
*
* \since This function is available since SDL 3.0.0.
*/
extern DECLSPEC int SDLCALL SDL_SetAudioPostmixCallback(SDL_AudioDeviceID devid, SDL_AudioPostmixCallback callback, void *userdata);
/**

View File

@ -185,8 +185,9 @@ typedef enum
SDL_EVENT_DROP_POSITION, /**< Position while moving over the window */
/* Audio hotplug events */
SDL_EVENT_AUDIO_DEVICE_ADDED = 0x1100, /**< A new audio device is available */
SDL_EVENT_AUDIO_DEVICE_REMOVED, /**< An audio device has been removed. */
SDL_EVENT_AUDIO_DEVICE_ADDED = 0x1100, /**< A new audio device is available */
SDL_EVENT_AUDIO_DEVICE_REMOVED, /**< An audio device has been removed. */
SDL_EVENT_AUDIO_DEVICE_FORMAT_CHANGED, /**< An audio device's format has been changed by the system. */
/* Sensor events */
SDL_EVENT_SENSOR_UPDATE = 0x1200, /**< A sensor was updated */
@ -491,9 +492,9 @@ typedef struct SDL_GamepadSensorEvent
*/
typedef struct SDL_AudioDeviceEvent
{
Uint32 type; /**< ::SDL_EVENT_AUDIO_DEVICE_ADDED, or ::SDL_EVENT_AUDIO_DEVICE_REMOVED */
Uint32 type; /**< ::SDL_EVENT_AUDIO_DEVICE_ADDED, or ::SDL_EVENT_AUDIO_DEVICE_REMOVED, or ::SDL_EVENT_AUDIO_DEVICE_FORMAT_CHANGED */
Uint64 timestamp; /**< In nanoseconds, populated using SDL_GetTicksNS() */
SDL_AudioDeviceID which; /**< SDL_AudioDeviceID for the device being added or removed */
SDL_AudioDeviceID which; /**< SDL_AudioDeviceID for the device being added or removed or changing */
Uint8 iscapture; /**< zero if an output device, non-zero if a capture device. */
Uint8 padding1;
Uint8 padding2;

View File

@ -125,6 +125,53 @@ typedef enum
SDL_GAMEPAD_AXIS_MAX
} SDL_GamepadAxis;
typedef enum
{
SDL_GAMEPAD_BINDTYPE_NONE = 0,
SDL_GAMEPAD_BINDTYPE_BUTTON,
SDL_GAMEPAD_BINDTYPE_AXIS,
SDL_GAMEPAD_BINDTYPE_HAT
} SDL_GamepadBindingType;
typedef struct
{
SDL_GamepadBindingType inputType;
union
{
int button;
struct
{
int axis;
int axis_min;
int axis_max;
} axis;
struct
{
int hat;
int hat_mask;
} hat;
} input;
SDL_GamepadBindingType outputType;
union
{
SDL_GamepadButton button;
struct
{
SDL_GamepadAxis axis;
int axis_min;
int axis_max;
} axis;
} output;
} SDL_GamepadBinding;
/**
* Add support for gamepads that SDL is unaware of or change the binding of an
* existing gamepad.
@ -736,6 +783,19 @@ extern DECLSPEC void SDLCALL SDL_SetGamepadEventsEnabled(SDL_bool enabled);
*/
extern DECLSPEC SDL_bool SDLCALL SDL_GamepadEventsEnabled(void);
/**
* Get the SDL joystick layer bindings for a gamepad
*
* \param gamepad a gamepad
* \param count a pointer filled in with the number of bindings returned
* \returns a NULL terminated array of pointers to bindings which should be
* freed with SDL_free(), or NULL on error; call SDL_GetError() for
* more details.
*
* \since This function is available since SDL 3.0.0.
*/
extern DECLSPEC SDL_GamepadBinding **SDLCALL SDL_GetGamepadBindings(SDL_Gamepad *gamepad, int *count);
/**
* Manually pump gamepad updates if not using the loop.
*

View File

@ -1488,6 +1488,17 @@ extern "C" {
*/
#define SDL_HINT_RENDER_VSYNC "SDL_RENDER_VSYNC"
/**
* \brief A variable controlling whether the Metal render driver select low power device over default one
*
* This variable can be set to the following values:
* "0" - Use the prefered OS device
* "1" - Select a low power one
*
* By default the prefered OS device is used.
*/
#define SDL_HINT_RENDER_METAL_PREFER_LOW_POWER_DEVICE "SDL_RENDER_METAL_PREFER_LOW_POWER_DEVICE"
/**
* \brief A variable controlling if VSYNC is automatically disable if doesn't reach the enough FPS
*
@ -2499,6 +2510,26 @@ extern "C" {
*/
#define SDL_HINT_GDK_TEXTINPUT_MAX_LENGTH "SDL_GDK_TEXTINPUT_MAX_LENGTH"
/**
* Set the next device open's buffer size.
*
* This hint is an integer > 0, that represents the size of the device's
* buffer in sample frames (stereo audio data in 16-bit format is 4 bytes
* per sample frame, for example).
*
* SDL3 generally decides this value on behalf of the app, but if for some
* reason the app needs to dictate this (because they want either lower
* latency or higher throughput AND ARE WILLING TO DEAL WITH what that
* might require of the app), they can specify it.
*
* SDL will try to accomodate this value, but there is no promise you'll
* get the buffer size requested. Many platforms won't honor this request
* at all, or might adjust it.
*
* This hint is checked when opening an audio device and can be changed
* between calls.
*/
#define SDL_HINT_AUDIO_DEVICE_SAMPLE_FRAMES "SDL_AUDIO_DEVICE_SAMPLE_FRAMES"
/**
* \brief An enumeration of hint priorities

View File

@ -43,18 +43,18 @@
#define SDL_atomic_t SDL_AtomicInt
/* ##SDL_audio.h */
#define AUDIO_F32 SDL_AUDIO_F32
#define AUDIO_F32LSB SDL_AUDIO_F32LSB
#define AUDIO_F32MSB SDL_AUDIO_F32MSB
#define AUDIO_F32SYS SDL_AUDIO_F32SYS
#define AUDIO_S16 SDL_AUDIO_S16
#define AUDIO_S16LSB SDL_AUDIO_S16LSB
#define AUDIO_S16MSB SDL_AUDIO_S16MSB
#define AUDIO_S16SYS SDL_AUDIO_S16SYS
#define AUDIO_S32 SDL_AUDIO_S32
#define AUDIO_S32LSB SDL_AUDIO_S32LSB
#define AUDIO_S32MSB SDL_AUDIO_S32MSB
#define AUDIO_S32SYS SDL_AUDIO_S32SYS
#define AUDIO_F32 SDL_AUDIO_F32LE
#define AUDIO_F32LSB SDL_AUDIO_F32LE
#define AUDIO_F32MSB SDL_AUDIO_F32BE
#define AUDIO_F32SYS SDL_AUDIO_F32
#define AUDIO_S16 SDL_AUDIO_S16LE
#define AUDIO_S16LSB SDL_AUDIO_S16LE
#define AUDIO_S16MSB SDL_AUDIO_S16BE
#define AUDIO_S16SYS SDL_AUDIO_S16
#define AUDIO_S32 SDL_AUDIO_S32LE
#define AUDIO_S32LSB SDL_AUDIO_S32LE
#define AUDIO_S32MSB SDL_AUDIO_S32BE
#define AUDIO_S32SYS SDL_AUDIO_S32
#define AUDIO_S8 SDL_AUDIO_S8
#define AUDIO_U8 SDL_AUDIO_U8
#define SDL_AudioStreamAvailable SDL_GetAudioStreamAvailable
@ -202,7 +202,6 @@
#define SDL_GameControllerAxis SDL_GamepadAxis
#define SDL_GameControllerBindType SDL_GamepadBindingType
#define SDL_GameControllerButton SDL_GamepadButton
#define SDL_GameControllerButtonBind SDL_GamepadBinding
#define SDL_GameControllerClose SDL_CloseGamepad
#define SDL_GameControllerFromInstanceID SDL_GetGamepadFromInstanceID
#define SDL_GameControllerFromPlayerIndex SDL_GetGamepadFromPlayerIndex
@ -211,8 +210,6 @@
#define SDL_GameControllerGetAttached SDL_GamepadConnected
#define SDL_GameControllerGetAxis SDL_GetGamepadAxis
#define SDL_GameControllerGetAxisFromString SDL_GetGamepadAxisFromString
#define SDL_GameControllerGetBindForAxis SDL_GetGamepadBindForAxis
#define SDL_GameControllerGetBindForButton SDL_GetGamepadBindForButton
#define SDL_GameControllerGetButton SDL_GetGamepadButton
#define SDL_GameControllerGetButtonFromString SDL_GetGamepadButtonFromString
#define SDL_GameControllerGetFirmwareVersion SDL_GetGamepadFirmwareVersion
@ -494,18 +491,18 @@
#elif !defined(SDL_DISABLE_OLD_NAMES)
/* ##SDL_audio.h */
#define AUDIO_F32 AUDIO_F32_renamed_SDL_AUDIO_F32
#define AUDIO_F32LSB AUDIO_F32LSB_renamed_SDL_AUDIO_F32LSB
#define AUDIO_F32MSB AUDIO_F32MSB_renamed_SDL_AUDIO_F32MSB
#define AUDIO_F32SYS AUDIO_F32SYS_renamed_SDL_AUDIO_F32SYS
#define AUDIO_S16 AUDIO_S16_renamed_SDL_AUDIO_S16
#define AUDIO_S16LSB AUDIO_S16LSB_renamed_SDL_AUDIO_S16LSB
#define AUDIO_S16MSB AUDIO_S16MSB_renamed_SDL_AUDIO_S16MSB
#define AUDIO_S16SYS AUDIO_S16SYS_renamed_SDL_AUDIO_S16SYS
#define AUDIO_S32 AUDIO_S32_renamed_SDL_AUDIO_S32
#define AUDIO_S32LSB AUDIO_S32LSB_renamed_SDL_AUDIO_S32LSB
#define AUDIO_S32MSB AUDIO_S32MSB_renamed_SDL_AUDIO_S32MSB
#define AUDIO_S32SYS AUDIO_S32SYS_renamed_SDL_AUDIO_S32SYS
#define AUDIO_F32 AUDIO_F32_renamed_SDL_AUDIO_F32LE
#define AUDIO_F32LSB AUDIO_F32LSB_renamed_SDL_AUDIO_F32LE
#define AUDIO_F32MSB AUDIO_F32MSB_renamed_SDL_AUDIO_F32BE
#define AUDIO_F32SYS AUDIO_F32SYS_renamed_SDL_AUDIO_F32
#define AUDIO_S16 AUDIO_S16_renamed_SDL_AUDIO_S16LE
#define AUDIO_S16LSB AUDIO_S16LSB_renamed_SDL_AUDIO_S16LE
#define AUDIO_S16MSB AUDIO_S16MSB_renamed_SDL_AUDIO_S16BE
#define AUDIO_S16SYS AUDIO_S16SYS_renamed_SDL_AUDIO_S16
#define AUDIO_S32 AUDIO_S32_renamed_SDL_AUDIO_S32LE
#define AUDIO_S32LSB AUDIO_S32LSB_renamed_SDL_AUDIO_S32LE
#define AUDIO_S32MSB AUDIO_S32MSB_renamed_SDL_AUDIO_S32BE
#define AUDIO_S32SYS AUDIO_S32SYS_renamed_SDL_AUDIO_S32
#define AUDIO_S8 AUDIO_S8_renamed_SDL_AUDIO_S8
#define AUDIO_U8 AUDIO_U8_renamed_SDL_AUDIO_U8
#define SDL_AudioStreamAvailable SDL_AudioStreamAvailable_renamed_SDL_GetAudioStreamAvailable
@ -653,7 +650,6 @@
#define SDL_GameControllerAxis SDL_GameControllerAxis_renamed_SDL_GamepadAxis
#define SDL_GameControllerBindType SDL_GameControllerBindType_renamed_SDL_GamepadBindingType
#define SDL_GameControllerButton SDL_GameControllerButton_renamed_SDL_GamepadButton
#define SDL_GameControllerButtonBind SDL_GameControllerButtonBind_renamed_SDL_GamepadBinding
#define SDL_GameControllerClose SDL_GameControllerClose_renamed_SDL_CloseGamepad
#define SDL_GameControllerFromInstanceID SDL_GameControllerFromInstanceID_renamed_SDL_GetGamepadFromInstanceID
#define SDL_GameControllerFromPlayerIndex SDL_GameControllerFromPlayerIndex_renamed_SDL_GetGamepadFromPlayerIndex
@ -662,8 +658,6 @@
#define SDL_GameControllerGetAttached SDL_GameControllerGetAttached_renamed_SDL_GamepadConnected
#define SDL_GameControllerGetAxis SDL_GameControllerGetAxis_renamed_SDL_GetGamepadAxis
#define SDL_GameControllerGetAxisFromString SDL_GameControllerGetAxisFromString_renamed_SDL_GetGamepadAxisFromString
#define SDL_GameControllerGetBindForAxis SDL_GameControllerGetBindForAxis_renamed_SDL_GetGamepadBindForAxis
#define SDL_GameControllerGetBindForButton SDL_GameControllerGetBindForButton_renamed_SDL_GetGamepadBindForButton
#define SDL_GameControllerGetButton SDL_GameControllerGetButton_renamed_SDL_GetGamepadButton
#define SDL_GameControllerGetButtonFromString SDL_GameControllerGetButtonFromString_renamed_SDL_GetGamepadButtonFromString
#define SDL_GameControllerGetFirmwareVersion SDL_GameControllerGetFirmwareVersion_renamed_SDL_GetGamepadFirmwareVersion

View File

@ -42,7 +42,7 @@
* of the many good 3D engines.
*
* These functions must be called from the main thread.
* See this bug for details: http://bugzilla.libsdl.org/show_bug.cgi?id=1995
* See this bug for details: https://github.com/libsdl-org/SDL/issues/986
*/
#ifndef SDL_render_h_

View File

@ -954,7 +954,22 @@ extern DECLSPEC SDL_bool SDLCALL SDL_WriteS64LE(SDL_RWops *dst, Sint64 value);
*/
extern DECLSPEC SDL_bool SDLCALL SDL_WriteU64BE(SDL_RWops *dst, Uint64 value);
extern DECLSPEC SDL_bool SDLCALL SDL_WriteU64BE(SDL_RWops *dst, Uint64 value);
/**
* Use this function to write 64 bits in native format to an SDL_RWops as
* big-endian data.
*
* SDL byteswaps the data only if necessary, so the application always
* specifies native format, and the data written will be in big-endian format.
*
* \param dst the stream to which data will be written
* \param value the data to be written, in native format
* \returns SDL_TRUE on successful write, SDL_FALSE on failure; call
* SDL_GetError() for more information.
*
* \since This function is available since SDL 3.0.0.
*/
extern DECLSPEC SDL_bool SDLCALL SDL_WriteS64BE(SDL_RWops *dst, Sint64 value);
/* @} *//* Write endian functions */
/* Ends C function definitions when using C++ */

View File

@ -778,15 +778,16 @@ extern DECLSPEC int SDLCALL SDL_FillSurfaceRects
* \param srcrect the SDL_Rect structure representing the rectangle to be
* copied, or NULL to copy the entire surface
* \param dst the SDL_Surface structure that is the blit target
* \param dstrect the SDL_Rect structure representing the target rectangle in
* the destination surface, filled with the actual rectangle
* used after clipping
* \param dstrect the SDL_Rect structure representing the x and y position in
* the destination surface. On input the width and height are
* ignored (taken from srcrect), and on output this is filled
* in with the actual rectangle used after clipping.
* \returns 0 on success or a negative error code on failure; call
* SDL_GetError() for more information.
*
* \since This function is available since SDL 3.0.0.
*
* \sa SDL_BlitSurface
* \sa SDL_BlitSurfaceScaled
*/
extern DECLSPEC int SDLCALL SDL_BlitSurface
(SDL_Surface *src, const SDL_Rect *srcrect,
@ -815,7 +816,6 @@ extern DECLSPEC int SDLCALL SDL_BlitSurfaceUnchecked
(SDL_Surface *src, const SDL_Rect *srcrect,
SDL_Surface *dst, const SDL_Rect *dstrect);
/**
* Perform a fast, low quality, stretch blit between two surfaces of the same
* format.
@ -872,6 +872,8 @@ extern DECLSPEC int SDLCALL SDL_SoftStretchLinear(SDL_Surface *src,
* SDL_GetError() for more information.
*
* \since This function is available since SDL 3.0.0.
*
* \sa SDL_BlitSurface
*/
extern DECLSPEC int SDLCALL SDL_BlitSurfaceScaled
(SDL_Surface *src, const SDL_Rect *srcrect,

View File

@ -582,7 +582,16 @@ extern DECLSPEC SDL_WinRT_DeviceFamily SDLCALL SDL_WinRTGetDeviceFamily();
*/
extern DECLSPEC SDL_bool SDLCALL SDL_IsTablet(void);
/* Functions used by iOS application delegates to notify SDL about state changes */
/* Functions used by iOS app delegates to notify SDL about state changes.
*
* These functions allow iOS apps that have their own event handling to hook
* into SDL to generate SDL events. These map directly to iOS-specific
* events, but since they don't do anything iOS-specific internally, they
* are available on all platforms, in case they might be useful for some
* specific paradigm. Most apps do not need to use these directly; SDL's
* internal event code will handle all this for windows created by
* SDL_CreateWindow!
*/
/*
* \since This function is available since SDL 3.0.0.
@ -623,7 +632,8 @@ extern DECLSPEC void SDLCALL SDL_OnApplicationDidChangeStatusBarOrientation(void
/* Functions used only by GDK */
#ifdef __GDK__
typedef struct XTaskQueueObject * XTaskQueueHandle;
typedef struct XTaskQueueObject *XTaskQueueHandle;
typedef struct XUser *XUserHandle;
/**
* Gets a reference to the global async task queue handle for GDK,
@ -641,6 +651,20 @@ typedef struct XTaskQueueObject * XTaskQueueHandle;
*/
extern DECLSPEC int SDLCALL SDL_GDKGetTaskQueue(XTaskQueueHandle * outTaskQueue);
/**
* Gets a reference to the default user handle for GDK.
*
* This is effectively a synchronous version of XUserAddAsync, which always
* prefers the default user and allows a sign-in UI.
*
* \param outUserHandle a pointer to be filled in with the default user
* handle.
* \returns 0 if success, -1 if any error occurs.
*
* \since This function is available since SDL 2.28.0.
*/
extern DECLSPEC int SDLCALL SDL_GDKGetDefaultUser(XUserHandle * outUserHandle);
#endif
/* Ends C function definitions when using C++ */

View File

@ -38,7 +38,8 @@ extern "C" {
/* Function prototypes */
#define FONT_CHARACTER_SIZE 8
extern int FONT_CHARACTER_SIZE;
#define FONT_LINE_HEIGHT (FONT_CHARACTER_SIZE + 2)
/**

View File

@ -42,7 +42,14 @@ extern "C" {
*
* \note This should be called before any other SDL functions for complete tracking coverage
*/
int SDLTest_TrackAllocations(void);
void SDLTest_TrackAllocations(void);
/**
* \brief Fill allocations with random data
*
* \note This implicitly calls SDLTest_TrackAllocations()
*/
void SDLTest_RandFillAllocations();
/**
* \brief Print a log of any outstanding allocations

View File

@ -132,7 +132,7 @@ typedef enum
SDL_WINDOW_FULLSCREEN = 0x00000001, /**< window is in fullscreen mode */
SDL_WINDOW_OPENGL = 0x00000002, /**< window usable with OpenGL context */
SDL_WINDOW_OCCLUDED = 0x00000004, /**< window is occluded */
SDL_WINDOW_HIDDEN = 0x00000008, /**< window is not visible */
SDL_WINDOW_HIDDEN = 0x00000008, /**< window is neither mapped onto the desktop nor shown in the taskbar/dock/window list; SDL_ShowWindow() is required for it to become visible */
SDL_WINDOW_BORDERLESS = 0x00000010, /**< no window decoration */
SDL_WINDOW_RESIZABLE = 0x00000020, /**< window can be resized */
SDL_WINDOW_MINIMIZED = 0x00000040, /**< window is minimized */
@ -150,7 +150,8 @@ typedef enum
SDL_WINDOW_KEYBOARD_GRABBED = 0x00100000, /**< window has grabbed keyboard input */
SDL_WINDOW_VULKAN = 0x10000000, /**< window usable for Vulkan surface */
SDL_WINDOW_METAL = 0x20000000, /**< window usable for Metal view */
SDL_WINDOW_TRANSPARENT = 0x40000000 /**< window with transparent buffer */
SDL_WINDOW_TRANSPARENT = 0x40000000, /**< window with transparent buffer */
SDL_WINDOW_NOT_FOCUSABLE = 0x80000000, /**< window should not be focusable */
} SDL_WindowFlags;
@ -1676,6 +1677,20 @@ extern DECLSPEC int SDLCALL SDL_SetWindowModalFor(SDL_Window *modal_window, SDL_
*/
extern DECLSPEC int SDLCALL SDL_SetWindowInputFocus(SDL_Window *window);
/**
* Set whether the window may have input focus.
*
* \param window the window to set focusable state
* \param focusable SDL_TRUE to allow input focus, SDL_FALSE to not allow
* input focus
* \returns 0 on success or a negative error code on failure; call
* SDL_GetError() for more information.
*
* \since This function is available since SDL 3.0.0.
*/
extern DECLSPEC int SDLCALL SDL_SetWindowFocusable(SDL_Window *window, SDL_bool focusable);
/**
* Display the system-level window menu.
*

View File

@ -34,7 +34,15 @@
#endif
#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#include <emscripten.h>
/* older Emscriptens don't have this, but we need to for wasm64 compatibility. */
#ifndef MAIN_THREAD_EM_ASM_PTR
#ifdef __wasm64__
#error You need to upgrade your Emscripten compiler to support wasm64
#else
#define MAIN_THREAD_EM_ASM_PTR MAIN_THREAD_EM_ASM_INT
#endif
#endif
#endif
/* The size of the stack buffer to use for rendering assert messages. */
@ -211,7 +219,7 @@ static SDL_AssertState SDLCALL SDL_PromptAssertion(const SDL_AssertData *data, v
}
/* Leave fullscreen mode, if possible (scary!) */
window = SDL_GetFocusWindow();
window = SDL_GetToplevelForKeyboardFocus();
if (window) {
if (window->fullscreen_exclusive) {
SDL_MinimizeWindow(window);
@ -243,7 +251,7 @@ static SDL_AssertState SDLCALL SDL_PromptAssertion(const SDL_AssertData *data, v
for (;;) {
SDL_bool okay = SDL_TRUE;
/* *INDENT-OFF* */ /* clang-format off */
char *buf = (char *) EM_ASM_INT({
char *buf = (char *) MAIN_THREAD_EM_ASM_PTR({
var str =
UTF8ToString($0) + '\n\n' +
'Abort/Retry/Ignore/AlwaysIgnore? [ariA] :';

View File

@ -1,318 +0,0 @@
/*
Simple DirectMedia Layer
Copyright (C) 1997-2023 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "SDL_internal.h"
#include "./SDL_dataqueue.h"
typedef struct SDL_DataQueuePacket
{
size_t datalen; /* bytes currently in use in this packet. */
size_t startpos; /* bytes currently consumed in this packet. */
struct SDL_DataQueuePacket *next; /* next item in linked list. */
Uint8 data[SDL_VARIABLE_LENGTH_ARRAY]; /* packet data */
} SDL_DataQueuePacket;
struct SDL_DataQueue
{
SDL_Mutex *lock;
SDL_DataQueuePacket *head; /* device fed from here. */
SDL_DataQueuePacket *tail; /* queue fills to here. */
SDL_DataQueuePacket *pool; /* these are unused packets. */
size_t packet_size; /* size of new packets */
size_t queued_bytes; /* number of bytes of data in the queue. */
};
static void SDL_FreeDataQueueList(SDL_DataQueuePacket *packet)
{
while (packet) {
SDL_DataQueuePacket *next = packet->next;
SDL_free(packet);
packet = next;
}
}
SDL_DataQueue *SDL_CreateDataQueue(const size_t _packetlen, const size_t initialslack)
{
SDL_DataQueue *queue = (SDL_DataQueue *)SDL_calloc(1, sizeof(SDL_DataQueue));
if (queue == NULL) {
SDL_OutOfMemory();
} else {
const size_t packetlen = _packetlen ? _packetlen : 1024;
const size_t wantpackets = (initialslack + (packetlen - 1)) / packetlen;
size_t i;
queue->packet_size = packetlen;
queue->lock = SDL_CreateMutex();
if (!queue->lock) {
SDL_free(queue);
return NULL;
}
for (i = 0; i < wantpackets; i++) {
SDL_DataQueuePacket *packet = (SDL_DataQueuePacket *)SDL_malloc(sizeof(SDL_DataQueuePacket) + packetlen);
if (packet) { /* don't care if this fails, we'll deal later. */
packet->datalen = 0;
packet->startpos = 0;
packet->next = queue->pool;
queue->pool = packet;
}
}
}
return queue;
}
void SDL_DestroyDataQueue(SDL_DataQueue *queue)
{
if (queue) {
SDL_FreeDataQueueList(queue->head);
SDL_FreeDataQueueList(queue->pool);
SDL_DestroyMutex(queue->lock);
SDL_free(queue);
}
}
void SDL_ClearDataQueue(SDL_DataQueue *queue, const size_t slack)
{
const size_t packet_size = queue ? queue->packet_size : 1;
const size_t slackpackets = (slack + (packet_size - 1)) / packet_size;
SDL_DataQueuePacket *packet;
SDL_DataQueuePacket *prev = NULL;
size_t i;
if (queue == NULL) {
return;
}
SDL_LockMutex(queue->lock);
packet = queue->head;
/* merge the available pool and the current queue into one list. */
if (packet) {
queue->tail->next = queue->pool;
} else {
packet = queue->pool;
}
/* Remove the queued packets from the device. */
queue->tail = NULL;
queue->head = NULL;
queue->queued_bytes = 0;
queue->pool = packet;
/* Optionally keep some slack in the pool to reduce memory allocation pressure. */
for (i = 0; packet && (i < slackpackets); i++) {
prev = packet;
packet = packet->next;
}
if (prev) {
prev->next = NULL;
} else {
queue->pool = NULL;
}
SDL_UnlockMutex(queue->lock);
SDL_FreeDataQueueList(packet); /* free extra packets */
}
/* You must hold queue->lock before calling this! */
static SDL_DataQueuePacket *AllocateDataQueuePacket(SDL_DataQueue *queue)
{
SDL_DataQueuePacket *packet;
SDL_assert(queue != NULL);
packet = queue->pool;
if (packet != NULL) {
/* we have one available in the pool. */
queue->pool = packet->next;
} else {
/* Have to allocate a new one! */
packet = (SDL_DataQueuePacket *)SDL_malloc(sizeof(SDL_DataQueuePacket) + queue->packet_size);
if (packet == NULL) {
return NULL;
}
}
packet->datalen = 0;
packet->startpos = 0;
packet->next = NULL;
SDL_assert((queue->head != NULL) == (queue->queued_bytes != 0));
if (queue->tail == NULL) {
queue->head = packet;
} else {
queue->tail->next = packet;
}
queue->tail = packet;
return packet;
}
int SDL_WriteToDataQueue(SDL_DataQueue *queue, const void *_data, const size_t _len)
{
size_t len = _len;
const Uint8 *data = (const Uint8 *)_data;
const size_t packet_size = queue ? queue->packet_size : 0;
SDL_DataQueuePacket *orighead;
SDL_DataQueuePacket *origtail;
size_t origlen;
size_t datalen;
if (queue == NULL) {
return SDL_InvalidParamError("queue");
}
SDL_LockMutex(queue->lock);
orighead = queue->head;
origtail = queue->tail;
origlen = origtail ? origtail->datalen : 0;
while (len > 0) {
SDL_DataQueuePacket *packet = queue->tail;
SDL_assert(packet == NULL || (packet->datalen <= packet_size));
if (packet == NULL || (packet->datalen >= packet_size)) {
/* tail packet missing or completely full; we need a new packet. */
packet = AllocateDataQueuePacket(queue);
if (packet == NULL) {
/* uhoh, reset so we've queued nothing new, free what we can. */
if (origtail == NULL) {
packet = queue->head; /* whole queue. */
} else {
packet = origtail->next; /* what we added to existing queue. */
origtail->next = NULL;
origtail->datalen = origlen;
}
queue->head = orighead;
queue->tail = origtail;
queue->pool = NULL;
SDL_UnlockMutex(queue->lock);
SDL_FreeDataQueueList(packet); /* give back what we can. */
return SDL_OutOfMemory();
}
}
datalen = SDL_min(len, packet_size - packet->datalen);
SDL_memcpy(packet->data + packet->datalen, data, datalen);
data += datalen;
len -= datalen;
packet->datalen += datalen;
queue->queued_bytes += datalen;
}
SDL_UnlockMutex(queue->lock);
return 0;
}
size_t SDL_PeekIntoDataQueue(SDL_DataQueue *queue, void *_buf, const size_t _len)
{
size_t len = _len;
Uint8 *buf = (Uint8 *)_buf;
Uint8 *ptr = buf;
SDL_DataQueuePacket *packet;
if (queue == NULL) {
return 0;
}
SDL_LockMutex(queue->lock);
for (packet = queue->head; len && packet; packet = packet->next) {
const size_t avail = packet->datalen - packet->startpos;
const size_t cpy = SDL_min(len, avail);
SDL_assert(queue->queued_bytes >= avail);
SDL_memcpy(ptr, packet->data + packet->startpos, cpy);
ptr += cpy;
len -= cpy;
}
SDL_UnlockMutex(queue->lock);
return (size_t)(ptr - buf);
}
size_t SDL_ReadFromDataQueue(SDL_DataQueue *queue, void *_buf, const size_t _len)
{
size_t len = _len;
Uint8 *buf = (Uint8 *)_buf;
Uint8 *ptr = buf;
SDL_DataQueuePacket *packet;
if (queue == NULL) {
return 0;
}
SDL_LockMutex(queue->lock);
while ((len > 0) && ((packet = queue->head) != NULL)) {
const size_t avail = packet->datalen - packet->startpos;
const size_t cpy = SDL_min(len, avail);
SDL_assert(queue->queued_bytes >= avail);
SDL_memcpy(ptr, packet->data + packet->startpos, cpy);
packet->startpos += cpy;
ptr += cpy;
queue->queued_bytes -= cpy;
len -= cpy;
if (packet->startpos == packet->datalen) { /* packet is done, put it in the pool. */
queue->head = packet->next;
SDL_assert((packet->next != NULL) || (packet == queue->tail));
packet->next = queue->pool;
queue->pool = packet;
}
}
SDL_assert((queue->head != NULL) == (queue->queued_bytes != 0));
if (queue->head == NULL) {
queue->tail = NULL; /* in case we drained the queue entirely. */
}
SDL_UnlockMutex(queue->lock);
return (size_t)(ptr - buf);
}
size_t SDL_GetDataQueueSize(SDL_DataQueue *queue)
{
size_t retval = 0;
if (queue) {
SDL_LockMutex(queue->lock);
retval = queue->queued_bytes;
SDL_UnlockMutex(queue->lock);
}
return retval;
}
SDL_Mutex *SDL_GetDataQueueMutex(SDL_DataQueue *queue)
{
return queue ? queue->lock : NULL;
}

View File

@ -1,38 +0,0 @@
/*
Simple DirectMedia Layer
Copyright (C) 1997-2023 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef SDL_dataqueue_h_
#define SDL_dataqueue_h_
/* this is not (currently) a public API. But maybe it should be! */
struct SDL_DataQueue;
typedef struct SDL_DataQueue SDL_DataQueue;
SDL_DataQueue *SDL_CreateDataQueue(const size_t packetlen, const size_t initialslack);
void SDL_DestroyDataQueue(SDL_DataQueue *queue);
void SDL_ClearDataQueue(SDL_DataQueue *queue, const size_t slack);
int SDL_WriteToDataQueue(SDL_DataQueue *queue, const void *data, const size_t len);
size_t SDL_ReadFromDataQueue(SDL_DataQueue *queue, void *buf, const size_t len);
size_t SDL_PeekIntoDataQueue(SDL_DataQueue *queue, void *buf, const size_t len);
size_t SDL_GetDataQueueSize(SDL_DataQueue *queue);
SDL_Mutex *SDL_GetDataQueueMutex(SDL_DataQueue *queue); /* don't destroy this, obviously. */
#endif /* SDL_dataqueue_h_ */

View File

@ -116,6 +116,106 @@ const char *SDL_GetCurrentAudioDriver(void)
return current_audio.name;
}
static int GetDefaultSampleFramesFromFreq(const int freq)
{
const char *hint = SDL_GetHint(SDL_HINT_AUDIO_DEVICE_SAMPLE_FRAMES);
if (hint) {
const int val = SDL_atoi(hint);
if (val > 0) {
return val;
}
}
if (freq <= 22050) {
return 512;
} else if (freq <= 48000) {
return 1024;
} else if (freq <= 96000) {
return 2048;
} else {
return 4096;
}
}
void OnAudioStreamCreated(SDL_AudioStream *stream)
{
SDL_assert(SDL_GetCurrentAudioDriver() != NULL);
SDL_assert(stream != NULL);
// this isn't really part of the "device list" but it's a convenient lock to use here.
SDL_LockRWLockForWriting(current_audio.device_list_lock);
if (current_audio.existing_streams) {
current_audio.existing_streams->prev = stream;
}
stream->prev = NULL;
stream->next = current_audio.existing_streams;
current_audio.existing_streams = stream;
SDL_UnlockRWLock(current_audio.device_list_lock);
}
void OnAudioStreamDestroy(SDL_AudioStream *stream)
{
SDL_assert(SDL_GetCurrentAudioDriver() != NULL);
SDL_assert(stream != NULL);
// this isn't really part of the "device list" but it's a convenient lock to use here.
SDL_LockRWLockForWriting(current_audio.device_list_lock);
if (stream->prev) {
stream->prev->next = stream->next;
}
if (stream->next) {
stream->next->prev = stream->prev;
}
if (stream == current_audio.existing_streams) {
current_audio.existing_streams = stream->next;
}
SDL_UnlockRWLock(current_audio.device_list_lock);
}
// should hold logdev's physical device's lock before calling.
static void UpdateAudioStreamFormatsLogical(SDL_LogicalAudioDevice *logdev)
{
const SDL_bool iscapture = logdev->physical_device->iscapture;
SDL_AudioSpec spec;
SDL_copyp(&spec, &logdev->physical_device->spec);
if (logdev->postmix != NULL) {
spec.format = SDL_AUDIO_F32;
}
for (SDL_AudioStream *stream = logdev->bound_streams; stream != NULL; stream = stream->next_binding) {
// set the proper end of the stream to the device's format.
// SDL_SetAudioStreamFormat does a ton of validation just to memcpy an audiospec.
SDL_LockMutex(stream->lock);
SDL_copyp(iscapture ? &stream->src_spec : &stream->dst_spec, &spec);
SDL_UnlockMutex(stream->lock);
}
}
// should hold device->lock before calling.
static void UpdateAudioStreamFormatsPhysical(SDL_AudioDevice *device)
{
for (SDL_LogicalAudioDevice *logdev = device->logical_devices; logdev != NULL; logdev = logdev->next) {
UpdateAudioStreamFormatsLogical(logdev);
}
}
// device should be locked when calling this.
static SDL_bool AudioDeviceCanUseSimpleCopy(SDL_AudioDevice *device)
{
SDL_assert(device != NULL);
return (
device->logical_devices && // there's a logical device
!device->logical_devices->next && // there's only _ONE_ logical device
!device->logical_devices->postmix && // there isn't a postmix callback
!SDL_AtomicGet(&device->logical_devices->paused) && // it isn't paused
device->logical_devices->bound_streams && // there's a bound stream
!device->logical_devices->bound_streams->next_binding // there's only _ONE_ bound stream.
) ? SDL_TRUE : SDL_FALSE;
}
// device management and hotplug...
@ -176,6 +276,8 @@ static void DestroyLogicalAudioDevice(SDL_LogicalAudioDevice *logdev)
SDL_UnlockMutex(stream->lock);
}
logdev->physical_device->simple_copy = AudioDeviceCanUseSimpleCopy(logdev->physical_device);
SDL_free(logdev);
}
@ -208,7 +310,10 @@ static SDL_AudioDevice *CreatePhysicalAudioDevice(const char *name, SDL_bool isc
{
SDL_assert(name != NULL);
if (SDL_AtomicGet(&current_audio.shutting_down)) {
SDL_LockRWLockForReading(current_audio.device_list_lock);
const int shutting_down = SDL_AtomicGet(&current_audio.shutting_down);
SDL_UnlockRWLock(current_audio.device_list_lock);
if (shutting_down) {
return NULL; // we're shutting down, don't add any devices that are hotplugged at the last possible moment.
}
@ -236,8 +341,9 @@ static SDL_AudioDevice *CreatePhysicalAudioDevice(const char *name, SDL_bool isc
SDL_AtomicSet(&device->condemned, 0);
SDL_AtomicSet(&device->zombie, 0);
device->iscapture = iscapture;
SDL_memcpy(&device->spec, spec, sizeof (SDL_AudioSpec));
SDL_memcpy(&device->default_spec, spec, sizeof (SDL_AudioSpec));
SDL_copyp(&device->spec, spec);
SDL_copyp(&device->default_spec, spec);
device->sample_frames = GetDefaultSampleFramesFromFreq(device->spec.freq);
device->silence_value = SDL_GetSilenceValueForFormat(device->spec.format);
device->handle = handle;
device->prev = NULL;
@ -336,7 +442,7 @@ void SDL_AudioDeviceDisconnected(SDL_AudioDevice *device)
SDL_LogicalAudioDevice *next = NULL;
for (SDL_LogicalAudioDevice *logdev = device->logical_devices; logdev != NULL; logdev = next) {
next = logdev->next;
if (!logdev->is_default) { // if opened as a default, leave it on the zombie device for later migration.
if (!logdev->opened_as_default) { // if opened as a default, leave it on the zombie device for later migration.
DisconnectLogicalAudioDevice(logdev);
}
}
@ -412,7 +518,7 @@ void SDL_AudioDeviceDisconnected(SDL_AudioDevice *device)
static void SDL_AudioThreadDeinit_Default(SDL_AudioDevice *device) { /* no-op. */ }
static void SDL_AudioWaitDevice_Default(SDL_AudioDevice *device) { /* no-op. */ }
static void SDL_AudioPlayDevice_Default(SDL_AudioDevice *device, const Uint8 *buffer, int buffer_size) { /* no-op. */ }
static int SDL_AudioPlayDevice_Default(SDL_AudioDevice *device, const Uint8 *buffer, int buffer_size) { return 0; /* no-op. */ }
static void SDL_AudioWaitCaptureDevice_Default(SDL_AudioDevice *device) { /* no-op. */ }
static void SDL_AudioFlushCapture_Default(SDL_AudioDevice *device) { /* no-op. */ }
static void SDL_AudioCloseDevice_Default(SDL_AudioDevice *device) { /* no-op. */ }
@ -493,6 +599,7 @@ int SDL_InitAudio(const char *driver_name)
}
SDL_ChooseAudioConverters();
SDL_SetupAudioResampler();
SDL_RWLock *device_list_lock = SDL_CreateRWLock(); // create this early, so if it fails we don't have to tear down the whole audio subsystem.
if (!device_list_lock) {
@ -614,6 +721,11 @@ void SDL_QuitAudio(void)
return;
}
// Destroy any audio streams that still exist...
while (current_audio.existing_streams != NULL) {
SDL_DestroyAudioStream(current_audio.existing_streams);
}
// merge device lists so we don't have to duplicate work below.
SDL_LockRWLockForWriting(current_audio.device_list_lock);
SDL_AtomicSet(&current_audio.shutting_down, 1);
@ -676,6 +788,14 @@ void SDL_AudioThreadFinalize(SDL_AudioDevice *device)
SDL_AtomicSet(&device->thread_alive, 0);
}
static void MixFloat32Audio(float *dst, const float *src, const int buffer_size)
{
if (SDL_MixAudioFormat((Uint8 *) dst, (const Uint8 *) src, SDL_AUDIO_F32, buffer_size, SDL_MIX_MAXVOLUME) < 0) {
SDL_assert(!"This shouldn't happen.");
}
}
// Output device thread. This is split into chunks, so backends that need to control this directly can use the pieces they need without duplicating effort.
void SDL_OutputAudioThreadSetup(SDL_AudioDevice *device)
@ -697,41 +817,90 @@ SDL_bool SDL_OutputAudioThreadIterate(SDL_AudioDevice *device)
SDL_bool retval = SDL_TRUE;
int buffer_size = device->buffer_size;
Uint8 *mix_buffer = current_audio.impl.GetDeviceBuf(device, &buffer_size);
if (!mix_buffer) {
Uint8 *device_buffer = current_audio.impl.GetDeviceBuf(device, &buffer_size);
if (!device_buffer) {
retval = SDL_FALSE;
} else {
SDL_assert(buffer_size <= device->buffer_size); // you can ask for less, but not more.
SDL_memset(mix_buffer, device->silence_value, buffer_size); // start with silence.
SDL_assert(AudioDeviceCanUseSimpleCopy(device) == device->simple_copy); // make sure this hasn't gotten out of sync.
for (SDL_LogicalAudioDevice *logdev = device->logical_devices; logdev != NULL; logdev = logdev->next) {
if (SDL_AtomicGet(&logdev->paused)) {
continue; // paused? Skip this logical device.
// can we do a basic copy without silencing/mixing the buffer? This is an extremely likely scenario, so we special-case it.
if (device->simple_copy) {
SDL_LogicalAudioDevice *logdev = device->logical_devices;
SDL_AudioStream *stream = logdev->bound_streams;
// We should have updated this elsewhere if the format changed!
SDL_assert(AUDIO_SPECS_EQUAL(stream->dst_spec, device->spec));
const int br = SDL_GetAudioStreamData(stream, device_buffer, buffer_size);
if (br < 0) { // Probably OOM. Kill the audio device; the whole thing is likely dying soon anyhow.
retval = SDL_FALSE;
SDL_memset(device_buffer, device->silence_value, buffer_size); // just supply silence to the device before we die.
} else if (br < buffer_size) {
SDL_memset(device_buffer + br, device->silence_value, buffer_size - br); // silence whatever we didn't write to.
}
} else { // need to actually mix (or silence the buffer)
float *final_mix_buffer = (float *) ((device->spec.format == SDL_AUDIO_F32) ? device_buffer : device->mix_buffer);
const int needed_samples = buffer_size / SDL_AUDIO_BYTESIZE(device->spec.format);
const int work_buffer_size = needed_samples * sizeof (float);
SDL_AudioSpec outspec;
for (SDL_AudioStream *stream = logdev->bound_streams; stream != NULL; stream = stream->next_binding) {
/* this will hold a lock on `stream` while getting. We don't explicitly lock the streams
for iterating here because the binding linked list can only change while the device lock is held.
(we _do_ lock the stream during binding/unbinding to make sure that two threads can't try to bind
the same stream to different devices at the same time, though.) */
const int br = SDL_GetAudioStreamData(stream, device->work_buffer, buffer_size);
if (br < 0) {
// oh crud, we probably ran out of memory. This is possibly an overreaction to kill the audio device, but it's likely the whole thing is going down in a moment anyhow.
retval = SDL_FALSE;
break;
} else if (br > 0) { // it's okay if we get less than requested, we mix what we have.
// !!! FIXME: this needs to mix to float32 or int32, so we don't clip.
if (SDL_MixAudioFormat(mix_buffer, device->work_buffer, device->spec.format, br, SDL_MIX_MAXVOLUME) < 0) { // !!! FIXME: allow streams to specify gain?
SDL_assert(!"We probably ended up with some totally unexpected audio format here");
retval = SDL_FALSE; // uh...?
SDL_assert(work_buffer_size <= device->work_buffer_size);
outspec.format = SDL_AUDIO_F32;
outspec.channels = device->spec.channels;
outspec.freq = device->spec.freq;
SDL_memset(final_mix_buffer, '\0', work_buffer_size); // start with silence.
for (SDL_LogicalAudioDevice *logdev = device->logical_devices; logdev != NULL; logdev = logdev->next) {
if (SDL_AtomicGet(&logdev->paused)) {
continue; // paused? Skip this logical device.
}
const SDL_AudioPostmixCallback postmix = logdev->postmix;
float *mix_buffer = final_mix_buffer;
if (postmix) {
mix_buffer = device->postmix_buffer;
SDL_memset(mix_buffer, '\0', work_buffer_size); // start with silence.
}
for (SDL_AudioStream *stream = logdev->bound_streams; stream != NULL; stream = stream->next_binding) {
// We should have updated this elsewhere if the format changed!
SDL_assert(AUDIO_SPECS_EQUAL(stream->dst_spec, outspec));
/* this will hold a lock on `stream` while getting. We don't explicitly lock the streams
for iterating here because the binding linked list can only change while the device lock is held.
(we _do_ lock the stream during binding/unbinding to make sure that two threads can't try to bind
the same stream to different devices at the same time, though.) */
const int br = SDL_GetAudioStreamData(stream, device->work_buffer, work_buffer_size);
if (br < 0) { // Probably OOM. Kill the audio device; the whole thing is likely dying soon anyhow.
retval = SDL_FALSE;
break;
} else if (br > 0) { // it's okay if we get less than requested, we mix what we have.
MixFloat32Audio(mix_buffer, (float *) device->work_buffer, br);
}
}
if (postmix) {
SDL_assert(mix_buffer == device->postmix_buffer);
postmix(logdev->postmix_userdata, &outspec, mix_buffer, work_buffer_size);
MixFloat32Audio(final_mix_buffer, mix_buffer, work_buffer_size);
}
}
if (((Uint8 *) final_mix_buffer) != device_buffer) {
// !!! FIXME: we can't promise the device buf is aligned/padded for SIMD.
//ConvertAudio(needed_samples * device->spec.channels, final_mix_buffer, SDL_AUDIO_F32, device->spec.channels, device_buffer, device->spec.format, device->spec.channels, device->work_buffer);
ConvertAudio(needed_samples / device->spec.channels, final_mix_buffer, SDL_AUDIO_F32, device->spec.channels, device->work_buffer, device->spec.format, device->spec.channels, NULL);
SDL_memcpy(device_buffer, device->work_buffer, buffer_size);
}
}
// !!! FIXME: have PlayDevice return a value and do disconnects in here with it.
current_audio.impl.PlayDevice(device, mix_buffer, buffer_size); // this SHOULD NOT BLOCK, as we are holding a lock right now. Block in WaitDevice!
// PlayDevice SHOULD NOT BLOCK, as we are holding a lock right now. Block in WaitDevice instead!
if (current_audio.impl.PlayDevice(device, device_buffer, buffer_size) < 0) {
retval = SDL_FALSE;
}
}
SDL_UnlockMutex(device->lock);
@ -746,9 +915,9 @@ SDL_bool SDL_OutputAudioThreadIterate(SDL_AudioDevice *device)
void SDL_OutputAudioThreadShutdown(SDL_AudioDevice *device)
{
SDL_assert(!device->iscapture);
const int samples = (device->buffer_size / (SDL_AUDIO_BITSIZE(device->spec.format) / 8)) / device->spec.channels;
const int frames = device->buffer_size / SDL_AUDIO_FRAMESIZE(device->spec);
// Wait for the audio to drain. !!! FIXME: don't bother waiting if device is lost.
SDL_Delay(((samples * 1000) / device->spec.freq) * 2);
SDL_Delay(((frames * 1000) / device->spec.freq) * 2);
current_audio.impl.ThreadDeinit(device);
SDL_AudioThreadFinalize(device);
}
@ -791,21 +960,42 @@ SDL_bool SDL_CaptureAudioThreadIterate(SDL_AudioDevice *device)
current_audio.impl.FlushCapture(device); // nothing wants data, dump anything pending.
} else {
// this SHOULD NOT BLOCK, as we are holding a lock right now. Block in WaitCaptureDevice!
const int rc = current_audio.impl.CaptureFromDevice(device, device->work_buffer, device->buffer_size);
if (rc < 0) { // uhoh, device failed for some reason!
int br = current_audio.impl.CaptureFromDevice(device, device->work_buffer, device->buffer_size);
if (br < 0) { // uhoh, device failed for some reason!
retval = SDL_FALSE;
} else if (rc > 0) { // queue the new data to each bound stream.
} else if (br > 0) { // queue the new data to each bound stream.
for (SDL_LogicalAudioDevice *logdev = device->logical_devices; logdev != NULL; logdev = logdev->next) {
if (SDL_AtomicGet(&logdev->paused)) {
continue; // paused? Skip this logical device.
}
void *output_buffer = device->work_buffer;
// I don't know why someone would want a postmix on a capture device, but we offer it for API consistency.
if (logdev->postmix) {
// move to float format.
SDL_AudioSpec outspec;
outspec.format = SDL_AUDIO_F32;
outspec.channels = device->spec.channels;
outspec.freq = device->spec.freq;
output_buffer = device->postmix_buffer;
const int frames = br / SDL_AUDIO_FRAMESIZE(device->spec);
br = frames * SDL_AUDIO_FRAMESIZE(outspec);
ConvertAudio(frames, device->work_buffer, device->spec.format, outspec.channels, device->postmix_buffer, SDL_AUDIO_F32, outspec.channels, NULL);
logdev->postmix(logdev->postmix_userdata, &outspec, device->postmix_buffer, br);
}
for (SDL_AudioStream *stream = logdev->bound_streams; stream != NULL; stream = stream->next_binding) {
// We should have updated this elsewhere if the format changed!
SDL_assert(stream->src_spec.format == (logdev->postmix ? SDL_AUDIO_F32 : device->spec.format));
SDL_assert(stream->src_spec.channels == device->spec.channels);
SDL_assert(stream->src_spec.freq == device->spec.freq);
/* this will hold a lock on `stream` while putting. We don't explicitly lock the streams
for iterating here because the binding linked list can only change while the device lock is held.
(we _do_ lock the stream during binding/unbinding to make sure that two threads can't try to bind
the same stream to different devices at the same time, though.) */
if (SDL_PutAudioStreamData(stream, device->work_buffer, rc) < 0) {
if (SDL_PutAudioStreamData(stream, output_buffer, br) < 0) {
// oh crud, we probably ran out of memory. This is possibly an overreaction to kill the audio device, but it's likely the whole thing is going down in a moment anyhow.
retval = SDL_FALSE;
break;
@ -1036,22 +1226,22 @@ char *SDL_GetAudioDeviceName(SDL_AudioDeviceID devid)
return retval;
}
int SDL_GetAudioDeviceFormat(SDL_AudioDeviceID devid, SDL_AudioSpec *spec)
int SDL_GetAudioDeviceFormat(SDL_AudioDeviceID devid, SDL_AudioSpec *spec, int *sample_frames)
{
if (!spec) {
return SDL_InvalidParamError("spec");
}
SDL_bool is_default = SDL_FALSE;
SDL_bool wants_default = SDL_FALSE;
if (devid == SDL_AUDIO_DEVICE_DEFAULT_OUTPUT) {
devid = current_audio.default_output_device_id;
is_default = SDL_TRUE;
wants_default = SDL_TRUE;
} else if (devid == SDL_AUDIO_DEVICE_DEFAULT_CAPTURE) {
devid = current_audio.default_capture_device_id;
is_default = SDL_TRUE;
wants_default = SDL_TRUE;
}
if ((devid == 0) && is_default) {
if ((devid == 0) && wants_default) {
return SDL_SetError("No default audio device available");
}
@ -1060,7 +1250,10 @@ int SDL_GetAudioDeviceFormat(SDL_AudioDeviceID devid, SDL_AudioSpec *spec)
return -1;
}
SDL_memcpy(spec, &device->spec, sizeof (SDL_AudioSpec));
SDL_copyp(spec, &device->spec);
if (sample_frames) {
*sample_frames = device->sample_frames;
}
SDL_UnlockMutex(device->lock);
return 0;
@ -1080,18 +1273,22 @@ static void ClosePhysicalAudioDevice(SDL_AudioDevice *device)
SDL_AtomicSet(&device->thread_alive, 0);
}
if (device->is_opened) {
if (device->currently_opened) {
current_audio.impl.CloseDevice(device); // if ProvidesOwnCallbackThread, this must join on any existing device thread before returning!
device->is_opened = SDL_FALSE;
device->currently_opened = SDL_FALSE;
device->hidden = NULL; // just in case.
}
if (device->work_buffer) {
SDL_aligned_free(device->work_buffer);
device->work_buffer = NULL;
}
SDL_aligned_free(device->work_buffer);
device->work_buffer = NULL;
SDL_memcpy(&device->spec, &device->default_spec, sizeof (SDL_AudioSpec));
SDL_aligned_free(device->mix_buffer);
device->mix_buffer = NULL;
SDL_aligned_free(device->postmix_buffer);
device->postmix_buffer = NULL;
SDL_copyp(&device->spec, &device->default_spec);
device->sample_frames = 0;
device->silence_value = SDL_GetSilenceValueForFormat(device->spec.format);
SDL_AtomicSet(&device->shutdown, 0); // ready to go again.
@ -1121,16 +1318,14 @@ static SDL_AudioFormat ParseAudioFormatString(const char *string)
#define CHECK_FMT_STRING(x) if (SDL_strcmp(string, #x) == 0) { return SDL_AUDIO_##x; }
CHECK_FMT_STRING(U8);
CHECK_FMT_STRING(S8);
CHECK_FMT_STRING(S16LSB);
CHECK_FMT_STRING(S16MSB);
CHECK_FMT_STRING(S16LE);
CHECK_FMT_STRING(S16BE);
CHECK_FMT_STRING(S16);
CHECK_FMT_STRING(S32LSB);
CHECK_FMT_STRING(S32MSB);
CHECK_FMT_STRING(S32SYS);
CHECK_FMT_STRING(S32LE);
CHECK_FMT_STRING(S32BE);
CHECK_FMT_STRING(S32);
CHECK_FMT_STRING(F32LSB);
CHECK_FMT_STRING(F32MSB);
CHECK_FMT_STRING(F32SYS);
CHECK_FMT_STRING(F32LE);
CHECK_FMT_STRING(F32BE);
CHECK_FMT_STRING(F32);
#undef CHECK_FMT_STRING
}
@ -1168,15 +1363,12 @@ static void PrepareAudioFormat(SDL_bool iscapture, SDL_AudioSpec *spec)
}
}
static int GetDefaultSampleFramesFromFreq(int freq)
{
return SDL_powerof2((freq / 1000) * 46); // Pick the closest power-of-two to ~46 ms at desired frequency
}
void SDL_UpdatedAudioDeviceFormat(SDL_AudioDevice *device)
{
device->silence_value = SDL_GetSilenceValueForFormat(device->spec.format);
device->buffer_size = device->sample_frames * (SDL_AUDIO_BITSIZE(device->spec.format) / 8) * device->spec.channels;
device->buffer_size = device->sample_frames * SDL_AUDIO_FRAMESIZE(device->spec);
device->work_buffer_size = device->sample_frames * sizeof (float) * device->spec.channels;
device->work_buffer_size = SDL_max(device->buffer_size, device->work_buffer_size); // just in case we end up with a 64-bit audio format at some point.
}
char *SDL_GetAudioThreadName(SDL_AudioDevice *device, char *buf, size_t buflen)
@ -1189,7 +1381,7 @@ char *SDL_GetAudioThreadName(SDL_AudioDevice *device, char *buf, size_t buflen)
// this expects the device lock to be held.
static int OpenPhysicalAudioDevice(SDL_AudioDevice *device, const SDL_AudioSpec *inspec)
{
SDL_assert(!device->is_opened);
SDL_assert(!device->currently_opened);
SDL_assert(device->logical_devices == NULL);
// Just pretend to open a zombie device. It can still collect logical devices on the assumption they will all migrate when the default device is officially changed.
@ -1198,7 +1390,7 @@ static int OpenPhysicalAudioDevice(SDL_AudioDevice *device, const SDL_AudioSpec
}
SDL_AudioSpec spec;
SDL_memcpy(&spec, inspec ? inspec : &device->default_spec, sizeof (SDL_AudioSpec));
SDL_copyp(&spec, inspec ? inspec : &device->default_spec);
PrepareAudioFormat(device->iscapture, &spec);
/* We allow the device format to change if it's better than the current settings (by various definitions of "better"). This prevents
@ -1211,7 +1403,7 @@ static int OpenPhysicalAudioDevice(SDL_AudioDevice *device, const SDL_AudioSpec
device->sample_frames = GetDefaultSampleFramesFromFreq(device->spec.freq);
SDL_UpdatedAudioDeviceFormat(device); // start this off sane.
device->is_opened = SDL_TRUE; // mark this true even if impl.OpenDevice fails, so we know to clean up.
device->currently_opened = SDL_TRUE; // mark this true even if impl.OpenDevice fails, so we know to clean up.
if (current_audio.impl.OpenDevice(device) < 0) {
ClosePhysicalAudioDevice(device); // clean up anything the backend left half-initialized.
return -1;
@ -1220,12 +1412,20 @@ static int OpenPhysicalAudioDevice(SDL_AudioDevice *device, const SDL_AudioSpec
SDL_UpdatedAudioDeviceFormat(device); // in case the backend changed things and forgot to call this.
// Allocate a scratch audio buffer
device->work_buffer = (Uint8 *)SDL_aligned_alloc(SDL_SIMDGetAlignment(), device->buffer_size);
device->work_buffer = (Uint8 *)SDL_aligned_alloc(SDL_SIMDGetAlignment(), device->work_buffer_size);
if (device->work_buffer == NULL) {
ClosePhysicalAudioDevice(device);
return SDL_OutOfMemory();
}
if (device->spec.format != SDL_AUDIO_F32) {
device->mix_buffer = (Uint8 *)SDL_aligned_alloc(SDL_SIMDGetAlignment(), device->work_buffer_size);
if (device->mix_buffer == NULL) {
ClosePhysicalAudioDevice(device);
return SDL_OutOfMemory();
}
}
// Start the audio thread if necessary
SDL_AtomicSet(&device->thread_alive, 1);
if (!current_audio.impl.ProvidesOwnCallbackThread) {
@ -1251,16 +1451,16 @@ SDL_AudioDeviceID SDL_OpenAudioDevice(SDL_AudioDeviceID devid, const SDL_AudioSp
return 0;
}
SDL_bool is_default = SDL_FALSE;
SDL_bool wants_default = SDL_FALSE;
if (devid == SDL_AUDIO_DEVICE_DEFAULT_OUTPUT) {
devid = current_audio.default_output_device_id;
is_default = SDL_TRUE;
wants_default = SDL_TRUE;
} else if (devid == SDL_AUDIO_DEVICE_DEFAULT_CAPTURE) {
devid = current_audio.default_capture_device_id;
is_default = SDL_TRUE;
wants_default = SDL_TRUE;
}
if ((devid == 0) && is_default) {
if ((devid == 0) && wants_default) {
SDL_SetError("No default audio device available");
return 0;
}
@ -1273,7 +1473,7 @@ SDL_AudioDeviceID SDL_OpenAudioDevice(SDL_AudioDeviceID devid, const SDL_AudioSp
} else {
SDL_LogicalAudioDevice *logdev = ObtainLogicalAudioDevice(devid); // this locks the physical device, too.
if (logdev) {
is_default = logdev->is_default; // was the original logical device meant to be a default? Make this one, too.
wants_default = logdev->opened_as_default; // was the original logical device meant to be a default? Make this one, too.
device = logdev->physical_device;
}
}
@ -1282,23 +1482,24 @@ SDL_AudioDeviceID SDL_OpenAudioDevice(SDL_AudioDeviceID devid, const SDL_AudioSp
if (device) {
SDL_LogicalAudioDevice *logdev = NULL;
if (!is_default && SDL_AtomicGet(&device->zombie)) {
if (!wants_default && SDL_AtomicGet(&device->zombie)) {
// uhoh, this device is undead, and just waiting for a new default device to be declared so it can hand off to it. Refuse explicit opens.
SDL_SetError("Device was already lost and can't accept new opens");
} else if ((logdev = (SDL_LogicalAudioDevice *) SDL_calloc(1, sizeof (SDL_LogicalAudioDevice))) == NULL) {
SDL_OutOfMemory();
} else if (!device->is_opened && OpenPhysicalAudioDevice(device, spec) == -1) { // first thing using this physical device? Open at the OS level...
} else if (!device->currently_opened && OpenPhysicalAudioDevice(device, spec) == -1) { // first thing using this physical device? Open at the OS level...
SDL_free(logdev);
} else {
SDL_AtomicSet(&logdev->paused, 0);
retval = logdev->instance_id = assign_audio_device_instance_id(device->iscapture, /*islogical=*/SDL_TRUE);
logdev->physical_device = device;
logdev->is_default = is_default;
logdev->opened_as_default = wants_default;
logdev->next = device->logical_devices;
if (device->logical_devices) {
device->logical_devices->prev = logdev;
}
device->logical_devices = logdev;
device->simple_copy = AudioDeviceCanUseSimpleCopy(device);
}
SDL_UnlockMutex(device->lock);
}
@ -1313,6 +1514,7 @@ static int SetLogicalAudioDevicePauseState(SDL_AudioDeviceID devid, int value)
return -1; // ObtainLogicalAudioDevice will have set an error.
}
SDL_AtomicSet(&logdev->paused, value);
logdev->physical_device->simple_copy = AudioDeviceCanUseSimpleCopy(logdev->physical_device);
SDL_UnlockMutex(logdev->physical_device->lock);
return 0;
}
@ -1327,7 +1529,7 @@ int SDLCALL SDL_ResumeAudioDevice(SDL_AudioDeviceID devid)
return SetLogicalAudioDevicePauseState(devid, 0);
}
SDL_bool SDL_IsAudioDevicePaused(SDL_AudioDeviceID devid)
SDL_bool SDL_AudioDevicePaused(SDL_AudioDeviceID devid)
{
SDL_LogicalAudioDevice *logdev = ObtainLogicalAudioDevice(devid);
SDL_bool retval = SDL_FALSE;
@ -1340,6 +1542,31 @@ SDL_bool SDL_IsAudioDevicePaused(SDL_AudioDeviceID devid)
return retval;
}
int SDL_SetAudioPostmixCallback(SDL_AudioDeviceID devid, SDL_AudioPostmixCallback callback, void *userdata)
{
SDL_LogicalAudioDevice *logdev = ObtainLogicalAudioDevice(devid);
int retval = 0;
if (logdev) {
SDL_AudioDevice *device = logdev->physical_device;
if (callback && !device->postmix_buffer) {
device->postmix_buffer = (float *)SDL_aligned_alloc(SDL_SIMDGetAlignment(), device->work_buffer_size);
if (device->mix_buffer == NULL) {
retval = SDL_OutOfMemory();
}
}
if (retval == 0) {
logdev->postmix = callback;
logdev->postmix_userdata = userdata;
}
UpdateAudioStreamFormatsLogical(logdev);
device->simple_copy = AudioDeviceCanUseSimpleCopy(device);
SDL_UnlockMutex(device->lock);
}
return retval;
}
int SDL_BindAudioStreams(SDL_AudioDeviceID devid, SDL_AudioStream **streams, int num_streams)
{
@ -1356,8 +1583,14 @@ int SDL_BindAudioStreams(SDL_AudioDeviceID devid, SDL_AudioStream **streams, int
return SDL_SetError("Audio streams are bound to device ids from SDL_OpenAudioDevice, not raw physical devices");
} else if ((logdev = ObtainLogicalAudioDevice(devid)) == NULL) {
return -1; // ObtainLogicalAudioDevice set the error message.
} else if (logdev->simplified) {
SDL_UnlockMutex(logdev->physical_device->lock);
return SDL_SetError("Cannot change stream bindings on device opened with SDL_OpenAudioDeviceStream");
}
// !!! FIXME: We'll set the device's side's format below, but maybe we should refuse to bind a stream if the app's side doesn't have a format set yet.
// !!! FIXME: Actually, why do we allow there to be an invalid format, again?
// make sure start of list is sane.
SDL_assert(!logdev->bound_streams || (logdev->bound_streams->prev_binding == NULL));
@ -1388,18 +1621,8 @@ int SDL_BindAudioStreams(SDL_AudioDeviceID devid, SDL_AudioStream **streams, int
if (retval == 0) {
// Now that everything is verified, chain everything together.
const SDL_bool iscapture = device->iscapture;
for (int i = 0; i < num_streams; i++) {
SDL_AudioStream *stream = streams[i];
SDL_AudioSpec src_spec, dst_spec;
// set the proper end of the stream to the device's format.
SDL_GetAudioStreamFormat(stream, &src_spec, &dst_spec);
if (iscapture) {
SDL_SetAudioStreamFormat(stream, &device->spec, &dst_spec);
} else {
SDL_SetAudioStreamFormat(stream, &src_spec, &device->spec);
}
stream->bound_device = logdev;
stream->prev_binding = NULL;
@ -1411,8 +1634,12 @@ int SDL_BindAudioStreams(SDL_AudioDeviceID devid, SDL_AudioStream **streams, int
SDL_UnlockMutex(stream->lock);
}
UpdateAudioStreamFormatsLogical(logdev);
}
device->simple_copy = AudioDeviceCanUseSimpleCopy(device);
SDL_UnlockMutex(device->lock);
return retval;
@ -1459,7 +1686,8 @@ void SDL_UnbindAudioStreams(SDL_AudioStream **streams, int num_streams)
// everything is locked, start unbinding streams.
for (int i = 0; i < num_streams; i++) {
SDL_AudioStream *stream = streams[i];
if (stream && stream->bound_device) {
// don't allow unbinding from "simplified" devices (opened with SDL_OpenAudioDeviceStream). Just ignore them.
if (stream && stream->bound_device && !stream->bound_device->simplified) {
if (stream->bound_device->bound_streams == stream) {
SDL_assert(stream->prev_binding == NULL);
stream->bound_device->bound_streams = stream->next_binding;
@ -1482,6 +1710,7 @@ void SDL_UnbindAudioStreams(SDL_AudioStream **streams, int num_streams)
stream->bound_device = NULL;
SDL_UnlockMutex(stream->lock);
if (logdev) {
logdev->physical_device->simple_copy = AudioDeviceCanUseSimpleCopy(logdev->physical_device);
SDL_UnlockMutex(logdev->physical_device->lock);
}
}
@ -1493,7 +1722,7 @@ void SDL_UnbindAudioStream(SDL_AudioStream *stream)
SDL_UnbindAudioStreams(&stream, 1);
}
SDL_AudioDeviceID SDL_GetAudioStreamBinding(SDL_AudioStream *stream)
SDL_AudioDeviceID SDL_GetAudioStreamDevice(SDL_AudioStream *stream)
{
SDL_AudioDeviceID retval = 0;
if (stream) {
@ -1506,45 +1735,71 @@ SDL_AudioDeviceID SDL_GetAudioStreamBinding(SDL_AudioStream *stream)
return retval;
}
SDL_AudioStream *SDL_CreateAndBindAudioStream(SDL_AudioDeviceID devid, const SDL_AudioSpec *spec)
SDL_AudioStream *SDL_OpenAudioDeviceStream(SDL_AudioDeviceID devid, const SDL_AudioSpec *spec, SDL_AudioStreamCallback callback, void *userdata)
{
const SDL_bool islogical = (devid & (1<<1)) ? SDL_FALSE : SDL_TRUE;
if (!islogical) {
SDL_SetError("Audio streams are bound to device ids from SDL_OpenAudioDevice, not raw physical devices");
return NULL;
SDL_AudioDeviceID logdevid = SDL_OpenAudioDevice(devid, spec);
if (!logdevid) {
return NULL; // error string should already be set.
}
SDL_LogicalAudioDevice *logdev = ObtainLogicalAudioDevice(logdevid);
if (logdev == NULL) { // this shouldn't happen, but just in case.
SDL_CloseAudioDevice(logdevid);
return NULL; // error string should already be set.
}
SDL_AudioDevice *physdevice = logdev->physical_device;
SDL_assert(physdevice != NULL);
SDL_AtomicSet(&logdev->paused, 1); // start the device paused, to match SDL2.
physdevice->simple_copy = AudioDeviceCanUseSimpleCopy(physdevice);
SDL_UnlockMutex(physdevice->lock); // we don't need to hold the lock for any of this.
const SDL_bool iscapture = physdevice->iscapture;
SDL_AudioStream *stream = NULL;
SDL_LogicalAudioDevice *logdev = ObtainLogicalAudioDevice(devid);
if (logdev) {
SDL_AudioDevice *device = logdev->physical_device;
if (device->iscapture) {
stream = SDL_CreateAudioStream(&device->spec, spec);
} else {
stream = SDL_CreateAudioStream(spec, &device->spec);
}
if (stream) {
if (SDL_BindAudioStream(devid, stream) == -1) {
SDL_DestroyAudioStream(stream);
stream = NULL;
}
}
SDL_UnlockMutex(device->lock);
if (iscapture) {
stream = SDL_CreateAudioStream(&physdevice->spec, spec);
} else {
stream = SDL_CreateAudioStream(spec, &physdevice->spec);
}
return stream;
if (!stream) {
SDL_CloseAudioDevice(logdevid);
return NULL; // error string should already be set.
}
if (SDL_BindAudioStream(logdevid, stream) == -1) {
SDL_DestroyAudioStream(stream);
SDL_CloseAudioDevice(logdevid);
return NULL; // error string should already be set.
}
logdev->simplified = SDL_TRUE; // forbid further binding changes on this logical device.
stream->simplified = SDL_TRUE; // so we know to close the audio device when this is destroyed.
if (callback) {
int rc;
if (iscapture) {
rc = SDL_SetAudioStreamPutCallback(stream, callback, userdata);
} else {
rc = SDL_SetAudioStreamGetCallback(stream, callback, userdata);
}
SDL_assert(rc == 0); // should only fail if stream==NULL atm.
}
return stream; // ready to rock.
}
#define NUM_FORMATS 8
static const SDL_AudioFormat format_list[NUM_FORMATS][NUM_FORMATS + 1] = {
{ SDL_AUDIO_U8, SDL_AUDIO_S8, SDL_AUDIO_S16LSB, SDL_AUDIO_S16MSB, SDL_AUDIO_S32LSB, SDL_AUDIO_S32MSB, SDL_AUDIO_F32LSB, SDL_AUDIO_F32MSB, 0 },
{ SDL_AUDIO_S8, SDL_AUDIO_U8, SDL_AUDIO_S16LSB, SDL_AUDIO_S16MSB, SDL_AUDIO_S32LSB, SDL_AUDIO_S32MSB, SDL_AUDIO_F32LSB, SDL_AUDIO_F32MSB, 0 },
{ SDL_AUDIO_S16LSB, SDL_AUDIO_S16MSB, SDL_AUDIO_S32LSB, SDL_AUDIO_S32MSB, SDL_AUDIO_F32LSB, SDL_AUDIO_F32MSB, SDL_AUDIO_U8, SDL_AUDIO_S8, 0 },
{ SDL_AUDIO_S16MSB, SDL_AUDIO_S16LSB, SDL_AUDIO_S32MSB, SDL_AUDIO_S32LSB, SDL_AUDIO_F32MSB, SDL_AUDIO_F32LSB, SDL_AUDIO_U8, SDL_AUDIO_S8, 0 },
{ SDL_AUDIO_S32LSB, SDL_AUDIO_S32MSB, SDL_AUDIO_F32LSB, SDL_AUDIO_F32MSB, SDL_AUDIO_S16LSB, SDL_AUDIO_S16MSB, SDL_AUDIO_U8, SDL_AUDIO_S8, 0 },
{ SDL_AUDIO_S32MSB, SDL_AUDIO_S32LSB, SDL_AUDIO_F32MSB, SDL_AUDIO_F32LSB, SDL_AUDIO_S16MSB, SDL_AUDIO_S16LSB, SDL_AUDIO_U8, SDL_AUDIO_S8, 0 },
{ SDL_AUDIO_F32LSB, SDL_AUDIO_F32MSB, SDL_AUDIO_S32LSB, SDL_AUDIO_S32MSB, SDL_AUDIO_S16LSB, SDL_AUDIO_S16MSB, SDL_AUDIO_U8, SDL_AUDIO_S8, 0 },
{ SDL_AUDIO_F32MSB, SDL_AUDIO_F32LSB, SDL_AUDIO_S32MSB, SDL_AUDIO_S32LSB, SDL_AUDIO_S16MSB, SDL_AUDIO_S16LSB, SDL_AUDIO_U8, SDL_AUDIO_S8, 0 },
{ SDL_AUDIO_U8, SDL_AUDIO_S8, SDL_AUDIO_S16LE, SDL_AUDIO_S16BE, SDL_AUDIO_S32LE, SDL_AUDIO_S32BE, SDL_AUDIO_F32LE, SDL_AUDIO_F32BE, 0 },
{ SDL_AUDIO_S8, SDL_AUDIO_U8, SDL_AUDIO_S16LE, SDL_AUDIO_S16BE, SDL_AUDIO_S32LE, SDL_AUDIO_S32BE, SDL_AUDIO_F32LE, SDL_AUDIO_F32BE, 0 },
{ SDL_AUDIO_S16LE, SDL_AUDIO_S16BE, SDL_AUDIO_S32LE, SDL_AUDIO_S32BE, SDL_AUDIO_F32LE, SDL_AUDIO_F32BE, SDL_AUDIO_U8, SDL_AUDIO_S8, 0 },
{ SDL_AUDIO_S16BE, SDL_AUDIO_S16LE, SDL_AUDIO_S32BE, SDL_AUDIO_S32LE, SDL_AUDIO_F32BE, SDL_AUDIO_F32LE, SDL_AUDIO_U8, SDL_AUDIO_S8, 0 },
{ SDL_AUDIO_S32LE, SDL_AUDIO_S32BE, SDL_AUDIO_F32LE, SDL_AUDIO_F32BE, SDL_AUDIO_S16LE, SDL_AUDIO_S16BE, SDL_AUDIO_U8, SDL_AUDIO_S8, 0 },
{ SDL_AUDIO_S32BE, SDL_AUDIO_S32LE, SDL_AUDIO_F32BE, SDL_AUDIO_F32LE, SDL_AUDIO_S16BE, SDL_AUDIO_S16LE, SDL_AUDIO_U8, SDL_AUDIO_S8, 0 },
{ SDL_AUDIO_F32LE, SDL_AUDIO_F32BE, SDL_AUDIO_S32LE, SDL_AUDIO_S32BE, SDL_AUDIO_S16LE, SDL_AUDIO_S16BE, SDL_AUDIO_U8, SDL_AUDIO_S8, 0 },
{ SDL_AUDIO_F32BE, SDL_AUDIO_F32LE, SDL_AUDIO_S32BE, SDL_AUDIO_S32LE, SDL_AUDIO_S16BE, SDL_AUDIO_S16LE, SDL_AUDIO_U8, SDL_AUDIO_S8, 0 },
};
const SDL_AudioFormat *SDL_ClosestAudioFormats(SDL_AudioFormat format)
@ -1597,8 +1852,9 @@ void SDL_DefaultAudioDeviceChanged(SDL_AudioDevice *new_default_device)
SDL_AudioSpec spec;
SDL_bool needs_migration = SDL_FALSE;
SDL_zero(spec);
for (SDL_LogicalAudioDevice *logdev = current_default_device->logical_devices; logdev != NULL; logdev = logdev->next) {
if (logdev->is_default) {
if (logdev->opened_as_default) {
needs_migration = SDL_TRUE;
for (SDL_AudioStream *stream = logdev->bound_streams; stream != NULL; stream = stream->next_binding) {
const SDL_AudioSpec *streamspec = iscapture ? &stream->dst_spec : &stream->src_spec;
@ -1624,19 +1880,16 @@ void SDL_DefaultAudioDeviceChanged(SDL_AudioDevice *new_default_device)
}
if (needs_migration) {
const SDL_bool spec_changed = !AUDIO_SPECS_EQUAL(current_default_device->spec, new_default_device->spec);
const SDL_bool post_fmt_event = (spec_changed && SDL_EventEnabled(SDL_EVENT_AUDIO_DEVICE_FORMAT_CHANGED)) ? SDL_TRUE : SDL_FALSE;
SDL_LogicalAudioDevice *next = NULL;
for (SDL_LogicalAudioDevice *logdev = current_default_device->logical_devices; logdev != NULL; logdev = next) {
next = logdev->next;
if (!logdev->is_default) {
if (!logdev->opened_as_default) {
continue; // not opened as a default, leave it on the current physical device.
}
// make sure all our streams are targeting the new device's format.
for (SDL_AudioStream *stream = logdev->bound_streams; stream != NULL; stream = stream->next_binding) {
SDL_SetAudioStreamFormat(stream, iscapture ? &new_default_device->spec : NULL, iscapture ? NULL : &new_default_device->spec);
}
// now migrate the logical device.
if (logdev->next) {
logdev->next->prev = logdev->prev;
@ -1652,8 +1905,25 @@ void SDL_DefaultAudioDeviceChanged(SDL_AudioDevice *new_default_device)
logdev->prev = NULL;
logdev->next = new_default_device->logical_devices;
new_default_device->logical_devices = logdev;
// make sure all our streams are targeting the new device's format.
UpdateAudioStreamFormatsLogical(logdev);
// Post an event for each logical device we moved.
if (post_fmt_event) {
SDL_Event event;
SDL_zero(event);
event.type = SDL_EVENT_AUDIO_DEVICE_FORMAT_CHANGED;
event.common.timestamp = 0;
event.adevice.iscapture = iscapture ? 1 : 0;
event.adevice.which = logdev->instance_id;
SDL_PushEvent(&event);
}
}
current_default_device->simple_copy = AudioDeviceCanUseSimpleCopy(current_default_device);
new_default_device->simple_copy = AudioDeviceCanUseSimpleCopy(new_default_device);
if (current_default_device->logical_devices == NULL) { // nothing left on the current physical device, close it.
// !!! FIXME: we _need_ to release this lock, but doing so can cause a race condition if someone opens a device while we're closing it.
SDL_UnlockMutex(current_default_device->lock); // can't hold the lock or the audio thread will deadlock while we WaitThread it.
@ -1675,31 +1945,56 @@ void SDL_DefaultAudioDeviceChanged(SDL_AudioDevice *new_default_device)
int SDL_AudioDeviceFormatChangedAlreadyLocked(SDL_AudioDevice *device, const SDL_AudioSpec *newspec, int new_sample_frames)
{
const int orig_work_buffer_size = device->work_buffer_size;
if (AUDIO_SPECS_EQUAL(device->spec, *newspec) && new_sample_frames == device->sample_frames) {
return 0; // we're already in that format.
}
SDL_copyp(&device->spec, newspec);
UpdateAudioStreamFormatsPhysical(device);
SDL_bool kill_device = SDL_FALSE;
const int orig_buffer_size = device->buffer_size;
const SDL_bool iscapture = device->iscapture;
device->sample_frames = new_sample_frames;
SDL_UpdatedAudioDeviceFormat(device);
if (device->work_buffer && (device->work_buffer_size > orig_work_buffer_size)) {
SDL_aligned_free(device->work_buffer);
device->work_buffer = (Uint8 *)SDL_aligned_alloc(SDL_SIMDGetAlignment(), device->work_buffer_size);
if (!device->work_buffer) {
kill_device = SDL_TRUE;
}
if ((device->spec.format != newspec->format) || (device->spec.channels != newspec->channels) || (device->spec.freq != newspec->freq)) {
SDL_memcpy(&device->spec, newspec, sizeof (*newspec));
for (SDL_LogicalAudioDevice *logdev = device->logical_devices; !kill_device && (logdev != NULL); logdev = logdev->next) {
for (SDL_AudioStream *stream = logdev->bound_streams; !kill_device && (stream != NULL); stream = stream->next_binding) {
if (SDL_SetAudioStreamFormat(stream, iscapture ? &device->spec : NULL, iscapture ? NULL : &device->spec) == -1) {
kill_device = SDL_TRUE;
}
if (device->postmix_buffer) {
SDL_aligned_free(device->postmix_buffer);
device->postmix_buffer = (float *)SDL_aligned_alloc(SDL_SIMDGetAlignment(), device->work_buffer_size);
if (!device->postmix_buffer) {
kill_device = SDL_TRUE;
}
}
SDL_aligned_free(device->mix_buffer);
device->mix_buffer = NULL;
if (device->spec.format != SDL_AUDIO_F32) {
device->mix_buffer = (Uint8 *)SDL_aligned_alloc(SDL_SIMDGetAlignment(), device->work_buffer_size);
if (!device->mix_buffer) {
kill_device = SDL_TRUE;
}
}
}
if (!kill_device) {
device->sample_frames = new_sample_frames;
SDL_UpdatedAudioDeviceFormat(device);
if (device->work_buffer && (device->buffer_size > orig_buffer_size)) {
SDL_aligned_free(device->work_buffer);
device->work_buffer = (Uint8 *)SDL_aligned_alloc(SDL_SIMDGetAlignment(), device->buffer_size);
if (!device->work_buffer) {
kill_device = SDL_TRUE;
}
// Post an event for the physical device, and each logical device on this physical device.
if (!kill_device && SDL_EventEnabled(SDL_EVENT_AUDIO_DEVICE_FORMAT_CHANGED)) {
SDL_Event event;
SDL_zero(event);
event.type = SDL_EVENT_AUDIO_DEVICE_FORMAT_CHANGED;
event.common.timestamp = 0;
event.adevice.iscapture = device->iscapture ? 1 : 0;
event.adevice.which = device->instance_id;
SDL_PushEvent(&event);
for (SDL_LogicalAudioDevice *logdev = device->logical_devices; logdev != NULL; logdev = logdev->next) {
event.adevice.which = logdev->instance_id;
SDL_PushEvent(&event);
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,516 @@
/*
Simple DirectMedia Layer
Copyright (C) 1997-2023 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "SDL_internal.h"
#include "SDL_audioqueue.h"
#define AUDIO_SPECS_EQUAL(x, y) (((x).format == (y).format) && ((x).channels == (y).channels) && ((x).freq == (y).freq))
struct SDL_AudioTrack
{
SDL_AudioSpec spec;
SDL_bool flushed;
SDL_AudioTrack *next;
size_t (*avail)(void *ctx);
int (*write)(void *ctx, const Uint8 *buf, size_t len);
size_t (*read)(void *ctx, Uint8 *buf, size_t len, SDL_bool advance);
void (*destroy)(void *ctx);
};
struct SDL_AudioQueue
{
SDL_AudioTrack *head;
SDL_AudioTrack *tail;
size_t chunk_size;
};
typedef struct SDL_AudioChunk SDL_AudioChunk;
struct SDL_AudioChunk
{
SDL_AudioChunk *next;
size_t head;
size_t tail;
Uint8 data[SDL_VARIABLE_LENGTH_ARRAY];
};
typedef struct SDL_ChunkedAudioTrack
{
SDL_AudioTrack track;
size_t chunk_size;
SDL_AudioChunk *head;
SDL_AudioChunk *tail;
size_t queued_bytes;
SDL_AudioChunk *free_chunks;
size_t num_free_chunks;
} SDL_ChunkedAudioTrack;
static void DestroyAudioChunk(SDL_AudioChunk *chunk)
{
SDL_free(chunk);
}
static void DestroyAudioChunks(SDL_AudioChunk *chunk)
{
while (chunk) {
SDL_AudioChunk *next = chunk->next;
DestroyAudioChunk(chunk);
chunk = next;
}
}
static void ResetAudioChunk(SDL_AudioChunk *chunk)
{
chunk->next = NULL;
chunk->head = 0;
chunk->tail = 0;
}
static SDL_AudioChunk *CreateAudioChunk(size_t chunk_size)
{
SDL_AudioChunk *chunk = (SDL_AudioChunk *)SDL_malloc(sizeof(*chunk) + chunk_size);
if (chunk == NULL) {
return NULL;
}
ResetAudioChunk(chunk);
return chunk;
}
static void DestroyAudioTrackChunk(SDL_ChunkedAudioTrack *track, SDL_AudioChunk *chunk)
{
// Keeping a list of free chunks reduces memory allocations,
// But also increases the amount of work to perform when freeing the track.
const size_t max_free_bytes = 64 * 1024;
if (track->chunk_size * track->num_free_chunks < max_free_bytes) {
chunk->next = track->free_chunks;
track->free_chunks = chunk;
++track->num_free_chunks;
} else {
DestroyAudioChunk(chunk);
}
}
static SDL_AudioChunk *CreateAudioTrackChunk(SDL_ChunkedAudioTrack *track)
{
if (track->num_free_chunks > 0) {
SDL_AudioChunk *chunk = track->free_chunks;
track->free_chunks = chunk->next;
--track->num_free_chunks;
ResetAudioChunk(chunk);
return chunk;
}
return CreateAudioChunk(track->chunk_size);
}
static size_t AvailChunkedAudioTrack(void *ctx)
{
SDL_ChunkedAudioTrack *track = ctx;
return track->queued_bytes;
}
static int WriteToChunkedAudioTrack(void *ctx, const Uint8 *data, size_t len)
{
SDL_ChunkedAudioTrack *track = ctx;
SDL_AudioChunk *chunk = track->tail;
// Handle the first chunk
if (chunk == NULL) {
chunk = CreateAudioTrackChunk(track);
if (chunk == NULL) {
return SDL_OutOfMemory();
}
SDL_assert((track->head == NULL) && (track->tail == NULL) && (track->queued_bytes == 0));
track->head = chunk;
track->tail = chunk;
}
size_t total = 0;
size_t old_tail = chunk->tail;
size_t chunk_size = track->chunk_size;
while (chunk) {
size_t to_write = chunk_size - chunk->tail;
to_write = SDL_min(to_write, len - total);
SDL_memcpy(&chunk->data[chunk->tail], &data[total], to_write);
total += to_write;
chunk->tail += to_write;
if (total == len) {
break;
}
SDL_AudioChunk *next = CreateAudioTrackChunk(track);
chunk->next = next;
chunk = next;
}
// Roll back the changes if we couldn't write all the data
if (chunk == NULL) {
chunk = track->tail;
SDL_AudioChunk *next = chunk->next;
chunk->next = NULL;
chunk->tail = old_tail;
DestroyAudioChunks(next);
return SDL_OutOfMemory();
}
track->tail = chunk;
track->queued_bytes += total;
return 0;
}
static size_t ReadFromChunkedAudioTrack(void *ctx, Uint8 *data, size_t len, SDL_bool advance)
{
SDL_ChunkedAudioTrack *track = ctx;
SDL_AudioChunk *chunk = track->head;
size_t total = 0;
size_t head = 0;
while (chunk) {
head = chunk->head;
size_t to_read = chunk->tail - head;
to_read = SDL_min(to_read, len - total);
SDL_memcpy(&data[total], &chunk->data[head], to_read);
total += to_read;
SDL_AudioChunk *next = chunk->next;
if (total == len) {
head += to_read;
break;
}
if (advance) {
DestroyAudioTrackChunk(track, chunk);
}
chunk = next;
}
if (advance) {
if (chunk) {
chunk->head = head;
track->head = chunk;
} else {
track->head = NULL;
track->tail = NULL;
}
track->queued_bytes -= total;
}
return total;
}
static void DestroyChunkedAudioTrack(void *ctx)
{
SDL_ChunkedAudioTrack *track = ctx;
DestroyAudioChunks(track->head);
DestroyAudioChunks(track->free_chunks);
SDL_free(track);
}
static SDL_AudioTrack *CreateChunkedAudioTrack(const SDL_AudioSpec *spec, size_t chunk_size)
{
SDL_ChunkedAudioTrack *track = (SDL_ChunkedAudioTrack *)SDL_calloc(1, sizeof(*track));
if (track == NULL) {
SDL_OutOfMemory();
return NULL;
}
SDL_copyp(&track->track.spec, spec);
track->track.avail = AvailChunkedAudioTrack;
track->track.write = WriteToChunkedAudioTrack;
track->track.read = ReadFromChunkedAudioTrack;
track->track.destroy = DestroyChunkedAudioTrack;
track->chunk_size = chunk_size;
return &track->track;
}
SDL_AudioQueue *SDL_CreateAudioQueue(size_t chunk_size)
{
SDL_AudioQueue *queue = (SDL_AudioQueue *)SDL_calloc(1, sizeof(*queue));
if (queue == NULL) {
SDL_OutOfMemory();
return NULL;
}
queue->chunk_size = chunk_size;
return queue;
}
void SDL_DestroyAudioQueue(SDL_AudioQueue *queue)
{
SDL_ClearAudioQueue(queue);
SDL_free(queue);
}
void SDL_ClearAudioQueue(SDL_AudioQueue *queue)
{
SDL_AudioTrack *track = queue->head;
queue->head = NULL;
queue->tail = NULL;
while (track) {
SDL_AudioTrack *next = track->next;
track->destroy(track);
track = next;
}
}
static void SDL_FlushAudioTrack(SDL_AudioTrack *track)
{
track->flushed = SDL_TRUE;
track->write = NULL;
}
void SDL_FlushAudioQueue(SDL_AudioQueue *queue)
{
SDL_AudioTrack *track = queue->tail;
if (track) {
SDL_FlushAudioTrack(track);
}
}
void SDL_PopAudioQueueHead(SDL_AudioQueue *queue)
{
SDL_AudioTrack *track = queue->head;
for (;;) {
SDL_bool flushed = track->flushed;
SDL_AudioTrack *next = track->next;
track->destroy(track);
track = next;
if (flushed) {
break;
}
}
queue->head = track;
if (track == NULL) {
queue->tail = NULL;
}
}
size_t SDL_GetAudioQueueChunkSize(SDL_AudioQueue *queue)
{
return queue->chunk_size;
}
SDL_AudioTrack *SDL_CreateChunkedAudioTrack(const SDL_AudioSpec *spec, const Uint8 *data, size_t len, size_t chunk_size)
{
SDL_AudioTrack *track = CreateChunkedAudioTrack(spec, chunk_size);
if (track == NULL) {
return NULL;
}
if (track->write(track, data, len) != 0) {
track->destroy(track);
return NULL;
}
return track;
}
void SDL_AddTrackToAudioQueue(SDL_AudioQueue *queue, SDL_AudioTrack *track)
{
SDL_AudioTrack *tail = queue->tail;
if (tail) {
// If the spec has changed, make sure to flush the previous track
if (!AUDIO_SPECS_EQUAL(tail->spec, track->spec)) {
SDL_FlushAudioTrack(tail);
}
tail->next = track;
} else {
queue->head = track;
}
queue->tail = track;
}
int SDL_WriteToAudioQueue(SDL_AudioQueue *queue, const SDL_AudioSpec *spec, const Uint8 *data, size_t len)
{
if (len == 0) {
return 0;
}
SDL_AudioTrack *track = queue->tail;
if ((track != NULL) && !AUDIO_SPECS_EQUAL(track->spec, *spec)) {
SDL_FlushAudioTrack(track);
}
if ((track == NULL) || (track->write == NULL)) {
SDL_AudioTrack *new_track = CreateChunkedAudioTrack(spec, queue->chunk_size);
if (new_track == NULL) {
return SDL_OutOfMemory();
}
if (track) {
track->next = new_track;
} else {
queue->head = new_track;
}
queue->tail = new_track;
track = new_track;
}
return track->write(track, data, len);
}
void *SDL_BeginAudioQueueIter(SDL_AudioQueue *queue)
{
return queue->head;
}
size_t SDL_NextAudioQueueIter(SDL_AudioQueue *queue, void **inout_iter, SDL_AudioSpec *out_spec, SDL_bool *out_flushed)
{
SDL_AudioTrack *iter = *inout_iter;
SDL_assert(iter != NULL);
SDL_copyp(out_spec, &iter->spec);
SDL_bool flushed = SDL_FALSE;
size_t queued_bytes = 0;
while (iter) {
SDL_AudioTrack *track = iter;
iter = iter->next;
size_t avail = track->avail(track);
if (avail >= SDL_SIZE_MAX - queued_bytes) {
queued_bytes = SDL_SIZE_MAX;
flushed = SDL_FALSE;
break;
}
queued_bytes += avail;
flushed = track->flushed;
if (flushed) {
break;
}
}
*inout_iter = iter;
*out_flushed = flushed;
return queued_bytes;
}
int SDL_ReadFromAudioQueue(SDL_AudioQueue *queue, Uint8 *data, size_t len)
{
size_t total = 0;
SDL_AudioTrack *track = queue->head;
for (;;) {
if (track == NULL) {
return SDL_SetError("Reading past end of queue");
}
total += track->read(track, &data[total], len - total, SDL_TRUE);
if (total == len) {
return 0;
}
if (track->flushed) {
return SDL_SetError("Reading past end of flushed track");
}
SDL_AudioTrack *next = track->next;
if (next == NULL) {
return SDL_SetError("Reading past end of incomplete track");
}
queue->head = next;
track->destroy(track);
track = next;
}
}
int SDL_PeekIntoAudioQueue(SDL_AudioQueue *queue, Uint8 *data, size_t len)
{
size_t total = 0;
SDL_AudioTrack *track = queue->head;
for (;;) {
if (track == NULL) {
return SDL_SetError("Peeking past end of queue");
}
total += track->read(track, &data[total], len - total, SDL_FALSE);
if (total == len) {
return 0;
}
if (track->flushed) {
// If we have run out of data, fill the rest with silence.
SDL_memset(&data[total], SDL_GetSilenceValueForFormat(track->spec.format), len - total);
return 0;
}
track = track->next;
}
}

View File

@ -0,0 +1,77 @@
/*
Simple DirectMedia Layer
Copyright (C) 1997-2023 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "SDL_internal.h"
#ifndef SDL_audioqueue_h_
#define SDL_audioqueue_h_
// Internal functions used by SDL_AudioStream for queueing audio.
typedef struct SDL_AudioQueue SDL_AudioQueue;
typedef struct SDL_AudioTrack SDL_AudioTrack;
// Create a new audio queue
SDL_AudioQueue *SDL_CreateAudioQueue(size_t chunk_size);
// Destroy an audio queue
void SDL_DestroyAudioQueue(SDL_AudioQueue *queue);
// Completely clear the queue
void SDL_ClearAudioQueue(SDL_AudioQueue *queue);
// Mark the last track as flushed
void SDL_FlushAudioQueue(SDL_AudioQueue *queue);
// Pop the current head track
// REQUIRES: The head track must exist, and must have been flushed
void SDL_PopAudioQueueHead(SDL_AudioQueue *queue);
// Get the chunk size, mostly for use with SDL_CreateChunkedAudioTrack
// This can be called from any thread
size_t SDL_GetAudioQueueChunkSize(SDL_AudioQueue *queue);
// Write data to the end of queue
// REQUIRES: If the spec has changed, the last track must have been flushed
int SDL_WriteToAudioQueue(SDL_AudioQueue *queue, const SDL_AudioSpec *spec, const Uint8 *data, size_t len);
// Create a track without needing to hold any locks
SDL_AudioTrack *SDL_CreateChunkedAudioTrack(const SDL_AudioSpec *spec, const Uint8 *data, size_t len, size_t chunk_size);
// Add a track to the end of the queue
// REQUIRES: `track != NULL`
void SDL_AddTrackToAudioQueue(SDL_AudioQueue *queue, SDL_AudioTrack *track);
// Iterate over the tracks in the queue
void *SDL_BeginAudioQueueIter(SDL_AudioQueue *queue);
// Query and update the track iterator
// REQUIRES: `*inout_iter != NULL` (a valid iterator)
size_t SDL_NextAudioQueueIter(SDL_AudioQueue *queue, void **inout_iter, SDL_AudioSpec *out_spec, SDL_bool *out_flushed);
// Read data from the start of the queue
// REQUIRES: There must be enough data in the queue
int SDL_ReadFromAudioQueue(SDL_AudioQueue *queue, Uint8 *data, size_t len);
// Peek into the start of the queue
// REQUIRES: There must be enough data in the queue, unless it has been flushed, in which case missing data is filled with silence.
int SDL_PeekIntoAudioQueue(SDL_AudioQueue *queue, Uint8 *data, size_t len);
#endif // SDL_audioqueue_h_

View File

@ -0,0 +1,335 @@
/*
Simple DirectMedia Layer
Copyright (C) 1997-2023 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "SDL_internal.h"
#include "SDL_sysaudio.h"
#include "SDL_audioresample.h"
/* SDL's resampler uses a "bandlimited interpolation" algorithm:
https://ccrma.stanford.edu/~jos/resample/ */
#include "SDL_audio_resampler_filter.h"
/* For a given srcpos, `srcpos + frame` are sampled, where `-RESAMPLER_ZERO_CROSSINGS < frame <= RESAMPLER_ZERO_CROSSINGS`.
* Note, when upsampling, it is also possible to start sampling from `srcpos = -1`. */
#define RESAMPLER_MAX_PADDING_FRAMES (RESAMPLER_ZERO_CROSSINGS + 1)
#define RESAMPLER_FILTER_INTERP_BITS (32 - RESAMPLER_BITS_PER_ZERO_CROSSING)
#define RESAMPLER_FILTER_INTERP_RANGE (1 << RESAMPLER_FILTER_INTERP_BITS)
#define RESAMPLER_SAMPLES_PER_FRAME (RESAMPLER_ZERO_CROSSINGS * 2)
#define RESAMPLER_FULL_FILTER_SIZE (RESAMPLER_SAMPLES_PER_FRAME * (RESAMPLER_SAMPLES_PER_ZERO_CROSSING + 1))
static void ResampleFrame_Scalar(const float *src, float *dst, const float *raw_filter, float interp, int chans)
{
int i, chan;
float filter[RESAMPLER_SAMPLES_PER_FRAME];
// Interpolate between the nearest two filters
for (i = 0; i < RESAMPLER_SAMPLES_PER_FRAME; i++) {
filter[i] = (raw_filter[i] * (1.0f - interp)) + (raw_filter[i + RESAMPLER_SAMPLES_PER_FRAME] * interp);
}
if (chans == 2) {
float out[2];
out[0] = 0.0f;
out[1] = 0.0f;
for (i = 0; i < RESAMPLER_SAMPLES_PER_FRAME; i++) {
const float scale = filter[i];
out[0] += src[i * 2 + 0] * scale;
out[1] += src[i * 2 + 1] * scale;
}
dst[0] = out[0];
dst[1] = out[1];
return;
}
if (chans == 1) {
float out = 0.0f;
for (i = 0; i < RESAMPLER_SAMPLES_PER_FRAME; i++) {
out += src[i] * filter[i];
}
dst[0] = out;
return;
}
for (chan = 0; chan < chans; chan++) {
float f = 0.0f;
for (i = 0; i < RESAMPLER_SAMPLES_PER_FRAME; i++) {
f += src[i * chans + chan] * filter[i];
}
dst[chan] = f;
}
}
#ifdef SDL_SSE_INTRINSICS
static void SDL_TARGETING("sse") ResampleFrame_SSE(const float *src, float *dst, const float *raw_filter, float interp, int chans)
{
#if RESAMPLER_SAMPLES_PER_FRAME != 10
#error Invalid samples per frame
#endif
// Load the filter
__m128 f0 = _mm_loadu_ps(raw_filter + 0);
__m128 f1 = _mm_loadu_ps(raw_filter + 4);
__m128 f2 = _mm_loadl_pi(_mm_setzero_ps(), (const __m64 *)(raw_filter + 8));
__m128 g0 = _mm_loadu_ps(raw_filter + 10);
__m128 g1 = _mm_loadu_ps(raw_filter + 14);
__m128 g2 = _mm_loadl_pi(_mm_setzero_ps(), (const __m64 *)(raw_filter + 18));
__m128 interp1 = _mm_set1_ps(interp);
__m128 interp2 = _mm_sub_ps(_mm_set1_ps(1.0f), _mm_set1_ps(interp));
// Linear interpolate the filter
f0 = _mm_add_ps(_mm_mul_ps(f0, interp2), _mm_mul_ps(g0, interp1));
f1 = _mm_add_ps(_mm_mul_ps(f1, interp2), _mm_mul_ps(g1, interp1));
f2 = _mm_add_ps(_mm_mul_ps(f2, interp2), _mm_mul_ps(g2, interp1));
if (chans == 2) {
// Duplicate each of the filter elements
g0 = _mm_unpackhi_ps(f0, f0);
f0 = _mm_unpacklo_ps(f0, f0);
g1 = _mm_unpackhi_ps(f1, f1);
f1 = _mm_unpacklo_ps(f1, f1);
f2 = _mm_unpacklo_ps(f2, f2);
// Multiply the filter by the input
f0 = _mm_mul_ps(f0, _mm_loadu_ps(src + 0));
g0 = _mm_mul_ps(g0, _mm_loadu_ps(src + 4));
f1 = _mm_mul_ps(f1, _mm_loadu_ps(src + 8));
g1 = _mm_mul_ps(g1, _mm_loadu_ps(src + 12));
f2 = _mm_mul_ps(f2, _mm_loadu_ps(src + 16));
// Calculate the sum
f0 = _mm_add_ps(_mm_add_ps(_mm_add_ps(f0, g0), _mm_add_ps(f1, g1)), f2);
f0 = _mm_add_ps(f0, _mm_movehl_ps(f0, f0));
// Store the result
_mm_storel_pi((__m64 *)dst, f0);
return;
}
if (chans == 1) {
// Multiply the filter by the input
f0 = _mm_mul_ps(f0, _mm_loadu_ps(src + 0));
f1 = _mm_mul_ps(f1, _mm_loadu_ps(src + 4));
f2 = _mm_mul_ps(f2, _mm_loadl_pi(_mm_setzero_ps(), (const __m64 *)(src + 8)));
// Calculate the sum
f0 = _mm_add_ps(f0, f1);
f0 = _mm_add_ps(_mm_add_ps(f0, f2), _mm_movehl_ps(f0, f0));
f0 = _mm_add_ss(f0, _mm_shuffle_ps(f0, f0, _MM_SHUFFLE(1, 1, 1, 1)));
// Store the result
_mm_store_ss(dst, f0);
return;
}
float filter[RESAMPLER_SAMPLES_PER_FRAME];
_mm_storeu_ps(filter + 0, f0);
_mm_storeu_ps(filter + 4, f1);
_mm_storel_pi((__m64 *)(filter + 8), f2);
int i, chan = 0;
for (; chan + 4 <= chans; chan += 4) {
f0 = _mm_setzero_ps();
for (i = 0; i < RESAMPLER_SAMPLES_PER_FRAME; i++) {
f0 = _mm_add_ps(f0, _mm_mul_ps(_mm_loadu_ps(&src[i * chans + chan]), _mm_load1_ps(&filter[i])));
}
_mm_storeu_ps(&dst[chan], f0);
}
for (; chan < chans; chan++) {
f0 = _mm_setzero_ps();
for (i = 0; i < RESAMPLER_SAMPLES_PER_FRAME; i++) {
f0 = _mm_add_ss(f0, _mm_mul_ss(_mm_load_ss(&src[i * chans + chan]), _mm_load_ss(&filter[i])));
}
_mm_store_ss(&dst[chan], f0);
}
}
#endif
static void (*ResampleFrame)(const float *src, float *dst, const float *raw_filter, float interp, int chans);
static float FullResamplerFilter[RESAMPLER_FULL_FILTER_SIZE];
void SDL_SetupAudioResampler(void)
{
static SDL_bool setup = SDL_FALSE;
if (setup) {
return;
}
// Build a table combining the left and right wings, for faster access
int i, j;
for (i = 0; i < RESAMPLER_SAMPLES_PER_ZERO_CROSSING; ++i) {
for (j = 0; j < RESAMPLER_ZERO_CROSSINGS; j++) {
int lwing = (i * RESAMPLER_SAMPLES_PER_FRAME) + (RESAMPLER_ZERO_CROSSINGS - 1) - j;
int rwing = (RESAMPLER_FULL_FILTER_SIZE - 1) - lwing;
float value = ResamplerFilter[(i * RESAMPLER_ZERO_CROSSINGS) + j];
FullResamplerFilter[lwing] = value;
FullResamplerFilter[rwing] = value;
}
}
for (i = 0; i < RESAMPLER_ZERO_CROSSINGS; ++i) {
int rwing = i + RESAMPLER_ZERO_CROSSINGS;
int lwing = (RESAMPLER_FULL_FILTER_SIZE - 1) - rwing;
FullResamplerFilter[lwing] = 0.0f;
FullResamplerFilter[rwing] = 0.0f;
}
ResampleFrame = ResampleFrame_Scalar;
#ifdef SDL_SSE_INTRINSICS
if (SDL_HasSSE()) {
ResampleFrame = ResampleFrame_SSE;
}
#endif
setup = SDL_TRUE;
}
Sint64 SDL_GetResampleRate(int src_rate, int dst_rate)
{
SDL_assert(src_rate > 0);
SDL_assert(dst_rate > 0);
Sint64 sample_rate = ((Sint64)src_rate << 32) / (Sint64)dst_rate;
SDL_assert(sample_rate > 0);
return sample_rate;
}
int SDL_GetResamplerHistoryFrames(void)
{
// Even if we aren't currently resampling, make sure to keep enough history in case we need to later.
return RESAMPLER_MAX_PADDING_FRAMES;
}
int SDL_GetResamplerPaddingFrames(Sint64 resample_rate)
{
// This must always be <= SDL_GetResamplerHistoryFrames()
return resample_rate ? RESAMPLER_MAX_PADDING_FRAMES : 0;
}
// These are not general purpose. They do not check for all possible underflow/overflow
SDL_FORCE_INLINE Sint64 ResamplerAdd(Sint64 a, Sint64 b, Sint64 *ret)
{
if ((b > 0) && (a > SDL_MAX_SINT64 - b)) {
return -1;
}
*ret = a + b;
return 0;
}
SDL_FORCE_INLINE Sint64 ResamplerMul(Sint64 a, Sint64 b, Sint64 *ret)
{
if ((b > 0) && (a > SDL_MAX_SINT64 / b)) {
return -1;
}
*ret = a * b;
return 0;
}
Sint64 SDL_GetResamplerInputFrames(Sint64 output_frames, Sint64 resample_rate, Sint64 resample_offset)
{
// Calculate the index of the last input frame, then add 1.
// ((((output_frames - 1) * resample_rate) + resample_offset) >> 32) + 1
Sint64 output_offset;
if (ResamplerMul(output_frames, resample_rate, &output_offset) ||
ResamplerAdd(output_offset, -resample_rate + resample_offset + 0x100000000, &output_offset)) {
output_offset = SDL_MAX_SINT64;
}
Sint64 input_frames = (Sint64)(Sint32)(output_offset >> 32);
input_frames = SDL_max(input_frames, 0);
return input_frames;
}
Sint64 SDL_GetResamplerOutputFrames(Sint64 input_frames, Sint64 resample_rate, Sint64 *inout_resample_offset)
{
Sint64 resample_offset = *inout_resample_offset;
// input_offset = (input_frames << 32) - resample_offset;
Sint64 input_offset;
if (ResamplerMul(input_frames, 0x100000000, &input_offset) ||
ResamplerAdd(input_offset, -resample_offset, &input_offset)) {
input_offset = SDL_MAX_SINT64;
}
// output_frames = div_ceil(input_offset, resample_rate)
Sint64 output_frames = (input_offset > 0) ? (((input_offset - 1) / resample_rate) + 1) : 0;
*inout_resample_offset = (output_frames * resample_rate) - input_offset;
return output_frames;
}
void SDL_ResampleAudio(int chans, const float *src, int inframes, float *dst, int outframes,
Sint64 resample_rate, Sint64 *inout_resample_offset)
{
int i;
Sint64 srcpos = *inout_resample_offset;
SDL_assert(resample_rate > 0);
for (i = 0; i < outframes; i++) {
int srcindex = (int)(Sint32)(srcpos >> 32);
Uint32 srcfraction = (Uint32)(srcpos & 0xFFFFFFFF);
srcpos += resample_rate;
SDL_assert(srcindex >= -1 && srcindex < inframes);
const float *filter = &FullResamplerFilter[(srcfraction >> RESAMPLER_FILTER_INTERP_BITS) * RESAMPLER_SAMPLES_PER_FRAME];
const float interp = (float)(srcfraction & (RESAMPLER_FILTER_INTERP_RANGE - 1)) * (1.0f / RESAMPLER_FILTER_INTERP_RANGE);
const float *frame = &src[(srcindex - (RESAMPLER_ZERO_CROSSINGS - 1)) * chans];
ResampleFrame(frame, dst, filter, interp, chans);
dst += chans;
}
*inout_resample_offset = srcpos - ((Sint64)inframes << 32);
}

View File

@ -0,0 +1,43 @@
/*
Simple DirectMedia Layer
Copyright (C) 1997-2023 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "SDL_internal.h"
#ifndef SDL_audioresample_h_
#define SDL_audioresample_h_
// Internal functions used by SDL_AudioStream for resampling audio.
// The resampler uses 32:32 fixed-point arithmetic to track its position.
Sint64 SDL_GetResampleRate(const int src_rate, const int dst_rate);
int SDL_GetResamplerHistoryFrames(void);
int SDL_GetResamplerPaddingFrames(Sint64 resample_rate);
Sint64 SDL_GetResamplerInputFrames(Sint64 output_frames, Sint64 resample_rate, Sint64 resample_offset);
Sint64 SDL_GetResamplerOutputFrames(Sint64 input_frames, Sint64 resample_rate, Sint64 *inout_resample_offset);
// Resample some audio.
// REQUIRES: `inframes >= SDL_GetResamplerInputFrames(outframes)`
// REQUIRES: At least `SDL_GetResamplerPaddingFrames(...)` extra frames to the left of src, and right of src+inframes
void SDL_ResampleAudio(int chans, const float *src, int inframes, float *dst, int outframes,
Sint64 resample_rate, Sint64 *inout_resample_offset);
#endif // SDL_audioresample_h_

View File

@ -39,482 +39,510 @@
#define NEED_SCALAR_CONVERTER_FALLBACKS 1
#endif
#define DIVBY128 0.0078125f
#define DIVBY32768 0.000030517578125f
#define DIVBY8388607 0.00000011920930376163766f
#define DIVBY2147483648 0.0000000004656612873077392578125f /* 0x1p-31f */
#if NEED_SCALAR_CONVERTER_FALLBACKS
/* these all convert backwards because (currently) float32 is >= to the size of anything it converts to, so it lets us safely convert in-place. */
#define AUDIOCVT_TOFLOAT_SCALAR(from, fromtype, equation) \
static void SDL_Convert_##from##_to_F32_Scalar(float *dst, const fromtype *src, int num_samples) { \
int i; \
LOG_DEBUG_AUDIO_CONVERT(#from, "F32"); \
for (i = num_samples - 1; i >= 0; --i) { \
dst[i] = equation; \
} \
/* This code requires that floats are in the IEEE-754 binary32 format */
SDL_COMPILE_TIME_ASSERT(float_bits, sizeof(float) == sizeof(Uint32));
union float_bits {
Uint32 u32;
float f32;
};
static void SDL_Convert_S8_to_F32_Scalar(float *dst, const Sint8 *src, int num_samples)
{
int i;
LOG_DEBUG_AUDIO_CONVERT("S8", "F32");
for (i = num_samples - 1; i >= 0; --i) {
/* 1) Construct a float in the range [65536.0, 65538.0)
* 2) Shift the float range to [-1.0, 1.0) */
union float_bits x;
x.u32 = (Uint8)src[i] ^ 0x47800080u;
dst[i] = x.f32 - 65537.0f;
}
}
AUDIOCVT_TOFLOAT_SCALAR(S8, Sint8, ((float)src[i]) * DIVBY128)
AUDIOCVT_TOFLOAT_SCALAR(U8, Uint8, (((float)src[i]) * DIVBY128) - 1.0f)
AUDIOCVT_TOFLOAT_SCALAR(S16, Sint16, ((float)src[i]) * DIVBY32768)
AUDIOCVT_TOFLOAT_SCALAR(S32, Sint32, ((float)(src[i] >> 8)) * DIVBY8388607)
#undef AUDIOCVT_FROMFLOAT_SCALAR
static void SDL_Convert_U8_to_F32_Scalar(float *dst, const Uint8 *src, int num_samples)
{
int i;
/* these all convert forwards because (currently) float32 is >= to the size of anything it converts from, so it lets us safely convert in-place. */
#define AUDIOCVT_FROMFLOAT_SCALAR(to, totype, clampmin, clampmax, equation) \
static void SDL_Convert_F32_to_##to##_Scalar(totype *dst, const float *src, int num_samples) { \
int i; \
LOG_DEBUG_AUDIO_CONVERT("F32", #to); \
for (i = 0; i < num_samples; i++) { \
const float sample = src[i]; \
if (sample >= 1.0f) { \
dst[i] = (totype) (clampmax); \
} else if (sample <= -1.0f) { \
dst[i] = (totype) (clampmin); \
} else { \
dst[i] = (totype) (equation); \
} \
} \
LOG_DEBUG_AUDIO_CONVERT("U8", "F32");
for (i = num_samples - 1; i >= 0; --i) {
/* 1) Construct a float in the range [65536.0, 65538.0)
* 2) Shift the float range to [-1.0, 1.0) */
union float_bits x;
x.u32 = src[i] ^ 0x47800000u;
dst[i] = x.f32 - 65537.0f;
}
}
AUDIOCVT_FROMFLOAT_SCALAR(S8, Sint8, -128, 127, sample * 127.0f);
AUDIOCVT_FROMFLOAT_SCALAR(U8, Uint8, 0, 255, (sample + 1.0f) * 127.0f);
AUDIOCVT_FROMFLOAT_SCALAR(S16, Sint16, -32768, 32767, sample * 32767.0f);
AUDIOCVT_FROMFLOAT_SCALAR(S32, Sint32, -2147483648LL, 2147483647, ((Sint32)(sample * 8388607.0f)) << 8);
#undef AUDIOCVT_FROMFLOAT_SCALAR
static void SDL_Convert_S16_to_F32_Scalar(float *dst, const Sint16 *src, int num_samples)
{
int i;
LOG_DEBUG_AUDIO_CONVERT("S16", "F32");
for (i = num_samples - 1; i >= 0; --i) {
/* 1) Construct a float in the range [256.0, 258.0)
* 2) Shift the float range to [-1.0, 1.0) */
union float_bits x;
x.u32 = (Uint16)src[i] ^ 0x43808000u;
dst[i] = x.f32 - 257.0f;
}
}
static void SDL_Convert_S32_to_F32_Scalar(float *dst, const Sint32 *src, int num_samples)
{
int i;
LOG_DEBUG_AUDIO_CONVERT("S32", "F32");
for (i = num_samples - 1; i >= 0; --i) {
dst[i] = (float)src[i] * DIVBY2147483648;
}
}
/* Create a bit-mask based on the sign-bit. Should optimize to a single arithmetic-shift-right */
#define SIGNMASK(x) (Uint32)(0u - ((Uint32)(x) >> 31))
static void SDL_Convert_F32_to_S8_Scalar(Sint8 *dst, const float *src, int num_samples)
{
int i;
LOG_DEBUG_AUDIO_CONVERT("F32", "S8");
for (i = 0; i < num_samples; ++i) {
/* 1) Shift the float range from [-1.0, 1.0] to [98303.0, 98305.0]
* 2) Shift the integer range from [0x47BFFF80, 0x47C00080] to [-128, 128]
* 3) Clamp the value to [-128, 127] */
union float_bits x;
x.f32 = src[i] + 98304.0f;
Uint32 y = x.u32 - 0x47C00000u;
Uint32 z = 0x7Fu - (y ^ SIGNMASK(y));
y = y ^ (z & SIGNMASK(z));
dst[i] = (Sint8)(y & 0xFF);
}
}
static void SDL_Convert_F32_to_U8_Scalar(Uint8 *dst, const float *src, int num_samples)
{
int i;
LOG_DEBUG_AUDIO_CONVERT("F32", "U8");
for (i = 0; i < num_samples; ++i) {
/* 1) Shift the float range from [-1.0, 1.0] to [98303.0, 98305.0]
* 2) Shift the integer range from [0x47BFFF80, 0x47C00080] to [-128, 128]
* 3) Clamp the value to [-128, 127]
* 4) Shift the integer range from [-128, 127] to [0, 255] */
union float_bits x;
x.f32 = src[i] + 98304.0f;
Uint32 y = x.u32 - 0x47C00000u;
Uint32 z = 0x7Fu - (y ^ SIGNMASK(y));
y = (y ^ 0x80u) ^ (z & SIGNMASK(z));
dst[i] = (Uint8)(y & 0xFF);
}
}
static void SDL_Convert_F32_to_S16_Scalar(Sint16 *dst, const float *src, int num_samples)
{
int i;
LOG_DEBUG_AUDIO_CONVERT("F32", "S16");
for (i = 0; i < num_samples; ++i) {
/* 1) Shift the float range from [-1.0, 1.0] to [383.0, 385.0]
* 2) Shift the integer range from [0x43BF8000, 0x43C08000] to [-32768, 32768]
* 3) Clamp values outside the [-32768, 32767] range */
union float_bits x;
x.f32 = src[i] + 384.0f;
Uint32 y = x.u32 - 0x43C00000u;
Uint32 z = 0x7FFFu - (y ^ SIGNMASK(y));
y = y ^ (z & SIGNMASK(z));
dst[i] = (Sint16)(y & 0xFFFF);
}
}
static void SDL_Convert_F32_to_S32_Scalar(Sint32 *dst, const float *src, int num_samples)
{
int i;
LOG_DEBUG_AUDIO_CONVERT("F32", "S32");
for (i = 0; i < num_samples; ++i) {
/* 1) Shift the float range from [-1.0, 1.0] to [-2147483648.0, 2147483648.0]
* 2) Set values outside the [-2147483648.0, 2147483647.0] range to -2147483648.0
* 3) Convert the float to an integer, and fixup values outside the valid range */
union float_bits x;
x.f32 = src[i];
Uint32 y = x.u32 + 0x0F800000u;
Uint32 z = y - 0xCF000000u;
z &= SIGNMASK(y ^ z);
x.u32 = y - z;
dst[i] = (Sint32)x.f32 ^ (Sint32)SIGNMASK(z);
}
}
#undef SIGNMASK
#endif /* NEED_SCALAR_CONVERTER_FALLBACKS */
#ifdef SDL_SSE2_INTRINSICS
static void SDL_TARGETING("sse2") SDL_Convert_S8_to_F32_SSE2(float *dst, const Sint8 *src, int num_samples)
{
int i;
int i = num_samples;
/* 1) Flip the sign bit to convert from S8 to U8 format
* 2) Construct a float in the range [65536.0, 65538.0)
* 3) Shift the float range to [-1.0, 1.0)
* dst[i] = i2f((src[i] ^ 0x80) | 0x47800000) - 65537.0 */
const __m128i zero = _mm_setzero_si128();
const __m128i flipper = _mm_set1_epi8(-0x80);
const __m128i caster = _mm_set1_epi16(0x4780 /* 0x47800000 = f2i(65536.0) */);
const __m128 offset = _mm_set1_ps(-65537.0);
LOG_DEBUG_AUDIO_CONVERT("S8", "F32 (using SSE2)");
src += num_samples - 1;
dst += num_samples - 1;
while (i >= 16) {
i -= 16;
/* Get dst aligned to 16 bytes (since buffer is growing, we don't have to worry about overreading from src) */
for (i = num_samples; i && (((size_t)(dst - 15)) & 15); --i, --src, --dst) {
*dst = ((float)*src) * DIVBY128;
const __m128i bytes = _mm_xor_si128(_mm_loadu_si128((const __m128i *)&src[i]), flipper);
const __m128i shorts1 = _mm_unpacklo_epi8(bytes, zero);
const __m128i shorts2 = _mm_unpackhi_epi8(bytes, zero);
const __m128 floats1 = _mm_add_ps(_mm_castsi128_ps(_mm_unpacklo_epi16(shorts1, caster)), offset);
const __m128 floats2 = _mm_add_ps(_mm_castsi128_ps(_mm_unpackhi_epi16(shorts1, caster)), offset);
const __m128 floats3 = _mm_add_ps(_mm_castsi128_ps(_mm_unpacklo_epi16(shorts2, caster)), offset);
const __m128 floats4 = _mm_add_ps(_mm_castsi128_ps(_mm_unpackhi_epi16(shorts2, caster)), offset);
_mm_storeu_ps(&dst[i], floats1);
_mm_storeu_ps(&dst[i + 4], floats2);
_mm_storeu_ps(&dst[i + 8], floats3);
_mm_storeu_ps(&dst[i + 12], floats4);
}
src -= 15;
dst -= 15; /* adjust to read SSE blocks from the start. */
SDL_assert(!i || !(((size_t)dst) & 15));
/* Make sure src is aligned too. */
if (!(((size_t)src) & 15)) {
/* Aligned! Do SSE blocks as long as we have 16 bytes available. */
const __m128i *mmsrc = (const __m128i *)src;
const __m128i zero = _mm_setzero_si128();
const __m128 divby128 = _mm_set1_ps(DIVBY128);
while (i >= 16) { /* 16 * 8-bit */
const __m128i bytes = _mm_load_si128(mmsrc); /* get 16 sint8 into an XMM register. */
/* treat as int16, shift left to clear every other sint16, then back right with sign-extend. Now sint16. */
const __m128i shorts1 = _mm_srai_epi16(_mm_slli_epi16(bytes, 8), 8);
/* right-shift-sign-extend gets us sint16 with the other set of values. */
const __m128i shorts2 = _mm_srai_epi16(bytes, 8);
/* unpack against zero to make these int32, shift to make them sign-extend, convert to float, multiply. Whew! */
const __m128 floats1 = _mm_mul_ps(_mm_cvtepi32_ps(_mm_srai_epi32(_mm_slli_epi32(_mm_unpacklo_epi16(shorts1, zero), 16), 16)), divby128);
const __m128 floats2 = _mm_mul_ps(_mm_cvtepi32_ps(_mm_srai_epi32(_mm_slli_epi32(_mm_unpacklo_epi16(shorts2, zero), 16), 16)), divby128);
const __m128 floats3 = _mm_mul_ps(_mm_cvtepi32_ps(_mm_srai_epi32(_mm_slli_epi32(_mm_unpackhi_epi16(shorts1, zero), 16), 16)), divby128);
const __m128 floats4 = _mm_mul_ps(_mm_cvtepi32_ps(_mm_srai_epi32(_mm_slli_epi32(_mm_unpackhi_epi16(shorts2, zero), 16), 16)), divby128);
/* Interleave back into correct order, store. */
_mm_store_ps(dst, _mm_unpacklo_ps(floats1, floats2));
_mm_store_ps(dst + 4, _mm_unpackhi_ps(floats1, floats2));
_mm_store_ps(dst + 8, _mm_unpacklo_ps(floats3, floats4));
_mm_store_ps(dst + 12, _mm_unpackhi_ps(floats3, floats4));
i -= 16;
mmsrc--;
dst -= 16;
}
src = (const Sint8 *)mmsrc;
}
src += 15;
dst += 15; /* adjust for any scalar finishing. */
/* Finish off any leftovers with scalar operations. */
while (i) {
*dst = ((float)*src) * DIVBY128;
i--;
src--;
dst--;
--i;
_mm_store_ss(&dst[i], _mm_add_ss(_mm_castsi128_ps(_mm_cvtsi32_si128((Uint8)src[i] ^ 0x47800080u)), offset));
}
}
static void SDL_TARGETING("sse2") SDL_Convert_U8_to_F32_SSE2(float *dst, const Uint8 *src, int num_samples)
{
int i;
int i = num_samples;
/* 1) Construct a float in the range [65536.0, 65538.0)
* 2) Shift the float range to [-1.0, 1.0)
* dst[i] = i2f(src[i] | 0x47800000) - 65537.0 */
const __m128i zero = _mm_setzero_si128();
const __m128i caster = _mm_set1_epi16(0x4780 /* 0x47800000 = f2i(65536.0) */);
const __m128 offset = _mm_set1_ps(-65537.0);
LOG_DEBUG_AUDIO_CONVERT("U8", "F32 (using SSE2)");
src += num_samples - 1;
dst += num_samples - 1;
while (i >= 16) {
i -= 16;
/* Get dst aligned to 16 bytes (since buffer is growing, we don't have to worry about overreading from src) */
for (i = num_samples; i && (((size_t)(dst - 15)) & 15); --i, --src, --dst) {
*dst = (((float)*src) * DIVBY128) - 1.0f;
const __m128i bytes = _mm_loadu_si128((const __m128i *)&src[i]);
const __m128i shorts1 = _mm_unpacklo_epi8(bytes, zero);
const __m128i shorts2 = _mm_unpackhi_epi8(bytes, zero);
const __m128 floats1 = _mm_add_ps(_mm_castsi128_ps(_mm_unpacklo_epi16(shorts1, caster)), offset);
const __m128 floats2 = _mm_add_ps(_mm_castsi128_ps(_mm_unpackhi_epi16(shorts1, caster)), offset);
const __m128 floats3 = _mm_add_ps(_mm_castsi128_ps(_mm_unpacklo_epi16(shorts2, caster)), offset);
const __m128 floats4 = _mm_add_ps(_mm_castsi128_ps(_mm_unpackhi_epi16(shorts2, caster)), offset);
_mm_storeu_ps(&dst[i], floats1);
_mm_storeu_ps(&dst[i + 4], floats2);
_mm_storeu_ps(&dst[i + 8], floats3);
_mm_storeu_ps(&dst[i + 12], floats4);
}
src -= 15;
dst -= 15; /* adjust to read SSE blocks from the start. */
SDL_assert(!i || !(((size_t)dst) & 15));
/* Make sure src is aligned too. */
if (!(((size_t)src) & 15)) {
/* Aligned! Do SSE blocks as long as we have 16 bytes available. */
const __m128i *mmsrc = (const __m128i *)src;
const __m128i zero = _mm_setzero_si128();
const __m128 divby128 = _mm_set1_ps(DIVBY128);
const __m128 minus1 = _mm_set1_ps(-1.0f);
while (i >= 16) { /* 16 * 8-bit */
const __m128i bytes = _mm_load_si128(mmsrc); /* get 16 uint8 into an XMM register. */
/* treat as int16, shift left to clear every other sint16, then back right with zero-extend. Now uint16. */
const __m128i shorts1 = _mm_srli_epi16(_mm_slli_epi16(bytes, 8), 8);
/* right-shift-zero-extend gets us uint16 with the other set of values. */
const __m128i shorts2 = _mm_srli_epi16(bytes, 8);
/* unpack against zero to make these int32, convert to float, multiply, add. Whew! */
/* Note that AVX2 can do floating point multiply+add in one instruction, fwiw. SSE2 cannot. */
const __m128 floats1 = _mm_add_ps(_mm_mul_ps(_mm_cvtepi32_ps(_mm_unpacklo_epi16(shorts1, zero)), divby128), minus1);
const __m128 floats2 = _mm_add_ps(_mm_mul_ps(_mm_cvtepi32_ps(_mm_unpacklo_epi16(shorts2, zero)), divby128), minus1);
const __m128 floats3 = _mm_add_ps(_mm_mul_ps(_mm_cvtepi32_ps(_mm_unpackhi_epi16(shorts1, zero)), divby128), minus1);
const __m128 floats4 = _mm_add_ps(_mm_mul_ps(_mm_cvtepi32_ps(_mm_unpackhi_epi16(shorts2, zero)), divby128), minus1);
/* Interleave back into correct order, store. */
_mm_store_ps(dst, _mm_unpacklo_ps(floats1, floats2));
_mm_store_ps(dst + 4, _mm_unpackhi_ps(floats1, floats2));
_mm_store_ps(dst + 8, _mm_unpacklo_ps(floats3, floats4));
_mm_store_ps(dst + 12, _mm_unpackhi_ps(floats3, floats4));
i -= 16;
mmsrc--;
dst -= 16;
}
src = (const Uint8 *)mmsrc;
}
src += 15;
dst += 15; /* adjust for any scalar finishing. */
/* Finish off any leftovers with scalar operations. */
while (i) {
*dst = (((float)*src) * DIVBY128) - 1.0f;
i--;
src--;
dst--;
--i;
_mm_store_ss(&dst[i], _mm_add_ss(_mm_castsi128_ps(_mm_cvtsi32_si128((Uint8)src[i] ^ 0x47800000u)), offset));
}
}
static void SDL_TARGETING("sse2") SDL_Convert_S16_to_F32_SSE2(float *dst, const Sint16 *src, int num_samples)
{
int i;
int i = num_samples;
/* 1) Flip the sign bit to convert from S16 to U16 format
* 2) Construct a float in the range [256.0, 258.0)
* 3) Shift the float range to [-1.0, 1.0)
* dst[i] = i2f((src[i] ^ 0x8000) | 0x43800000) - 257.0 */
const __m128i flipper = _mm_set1_epi16(-0x8000);
const __m128i caster = _mm_set1_epi16(0x4380 /* 0x43800000 = f2i(256.0) */);
const __m128 offset = _mm_set1_ps(-257.0f);
LOG_DEBUG_AUDIO_CONVERT("S16", "F32 (using SSE2)");
src += num_samples - 1;
dst += num_samples - 1;
while (i >= 16) {
i -= 16;
/* Get dst aligned to 16 bytes (since buffer is growing, we don't have to worry about overreading from src) */
for (i = num_samples; i && (((size_t)(dst - 7)) & 15); --i, --src, --dst) {
*dst = ((float)*src) * DIVBY32768;
const __m128i shorts1 = _mm_xor_si128(_mm_loadu_si128((const __m128i *)&src[i]), flipper);
const __m128i shorts2 = _mm_xor_si128(_mm_loadu_si128((const __m128i *)&src[i + 8]), flipper);
const __m128 floats1 = _mm_add_ps(_mm_castsi128_ps(_mm_unpacklo_epi16(shorts1, caster)), offset);
const __m128 floats2 = _mm_add_ps(_mm_castsi128_ps(_mm_unpackhi_epi16(shorts1, caster)), offset);
const __m128 floats3 = _mm_add_ps(_mm_castsi128_ps(_mm_unpacklo_epi16(shorts2, caster)), offset);
const __m128 floats4 = _mm_add_ps(_mm_castsi128_ps(_mm_unpackhi_epi16(shorts2, caster)), offset);
_mm_storeu_ps(&dst[i], floats1);
_mm_storeu_ps(&dst[i + 4], floats2);
_mm_storeu_ps(&dst[i + 8], floats3);
_mm_storeu_ps(&dst[i + 12], floats4);
}
src -= 7;
dst -= 7; /* adjust to read SSE blocks from the start. */
SDL_assert(!i || !(((size_t)dst) & 15));
/* Make sure src is aligned too. */
if (!(((size_t)src) & 15)) {
/* Aligned! Do SSE blocks as long as we have 16 bytes available. */
const __m128 divby32768 = _mm_set1_ps(DIVBY32768);
while (i >= 8) { /* 8 * 16-bit */
const __m128i ints = _mm_load_si128((__m128i const *)src); /* get 8 sint16 into an XMM register. */
/* treat as int32, shift left to clear every other sint16, then back right with sign-extend. Now sint32. */
const __m128i a = _mm_srai_epi32(_mm_slli_epi32(ints, 16), 16);
/* right-shift-sign-extend gets us sint32 with the other set of values. */
const __m128i b = _mm_srai_epi32(ints, 16);
/* Interleave these back into the right order, convert to float, multiply, store. */
_mm_store_ps(dst, _mm_mul_ps(_mm_cvtepi32_ps(_mm_unpacklo_epi32(a, b)), divby32768));
_mm_store_ps(dst + 4, _mm_mul_ps(_mm_cvtepi32_ps(_mm_unpackhi_epi32(a, b)), divby32768));
i -= 8;
src -= 8;
dst -= 8;
}
}
src += 7;
dst += 7; /* adjust for any scalar finishing. */
/* Finish off any leftovers with scalar operations. */
while (i) {
*dst = ((float)*src) * DIVBY32768;
i--;
src--;
dst--;
--i;
_mm_store_ss(&dst[i], _mm_add_ss(_mm_castsi128_ps(_mm_cvtsi32_si128((Uint16)src[i] ^ 0x43808000u)), offset));
}
}
static void SDL_TARGETING("sse2") SDL_Convert_S32_to_F32_SSE2(float *dst, const Sint32 *src, int num_samples)
{
int i;
int i = num_samples;
/* dst[i] = f32(src[i]) / f32(0x80000000) */
const __m128 scaler = _mm_set1_ps(DIVBY2147483648);
LOG_DEBUG_AUDIO_CONVERT("S32", "F32 (using SSE2)");
/* Get dst aligned to 16 bytes */
for (i = num_samples; i && (((size_t)dst) & 15); --i, ++src, ++dst) {
*dst = ((float)(*src >> 8)) * DIVBY8388607;
while (i >= 16) {
i -= 16;
const __m128i ints1 = _mm_loadu_si128((const __m128i *)&src[i]);
const __m128i ints2 = _mm_loadu_si128((const __m128i *)&src[i + 4]);
const __m128i ints3 = _mm_loadu_si128((const __m128i *)&src[i + 8]);
const __m128i ints4 = _mm_loadu_si128((const __m128i *)&src[i + 12]);
const __m128 floats1 = _mm_mul_ps(_mm_cvtepi32_ps(ints1), scaler);
const __m128 floats2 = _mm_mul_ps(_mm_cvtepi32_ps(ints2), scaler);
const __m128 floats3 = _mm_mul_ps(_mm_cvtepi32_ps(ints3), scaler);
const __m128 floats4 = _mm_mul_ps(_mm_cvtepi32_ps(ints4), scaler);
_mm_storeu_ps(&dst[i], floats1);
_mm_storeu_ps(&dst[i + 4], floats2);
_mm_storeu_ps(&dst[i + 8], floats3);
_mm_storeu_ps(&dst[i + 12], floats4);
}
SDL_assert(!i || !(((size_t)dst) & 15));
/* Make sure src is aligned too. */
if (!(((size_t)src) & 15)) {
/* Aligned! Do SSE blocks as long as we have 16 bytes available. */
const __m128 divby8388607 = _mm_set1_ps(DIVBY8388607);
const __m128i *mmsrc = (const __m128i *)src;
while (i >= 4) { /* 4 * sint32 */
/* shift out lowest bits so int fits in a float32. Small precision loss, but much faster. */
_mm_store_ps(dst, _mm_mul_ps(_mm_cvtepi32_ps(_mm_srai_epi32(_mm_load_si128(mmsrc), 8)), divby8388607));
i -= 4;
mmsrc++;
dst += 4;
}
src = (const Sint32 *)mmsrc;
}
/* Finish off any leftovers with scalar operations. */
while (i) {
*dst = ((float)(*src >> 8)) * DIVBY8388607;
i--;
src++;
dst++;
--i;
_mm_store_ss(&dst[i], _mm_mul_ss(_mm_cvt_si2ss(_mm_setzero_ps(), src[i]), scaler));
}
}
static void SDL_TARGETING("sse2") SDL_Convert_F32_to_S8_SSE2(Sint8 *dst, const float *src, int num_samples)
{
int i;
int i = num_samples;
/* 1) Shift the float range from [-1.0, 1.0] to [98303.0, 98305.0]
* 2) Extract the lowest 16 bits and clamp to [-128, 127]
* Overflow is correctly handled for inputs between roughly [-255.0, 255.0]
* dst[i] = clamp(i16(f2i(src[i] + 98304.0) & 0xFFFF), -128, 127) */
const __m128 offset = _mm_set1_ps(98304.0f);
const __m128i mask = _mm_set1_epi16(0xFF);
LOG_DEBUG_AUDIO_CONVERT("F32", "S8 (using SSE2)");
/* Get dst aligned to 16 bytes */
for (i = num_samples; i && (((size_t)dst) & 15); --i, ++src, ++dst) {
const float sample = *src;
if (sample >= 1.0f) {
*dst = 127;
} else if (sample <= -1.0f) {
*dst = -128;
} else {
*dst = (Sint8)(sample * 127.0f);
}
while (i >= 16) {
const __m128 floats1 = _mm_loadu_ps(&src[0]);
const __m128 floats2 = _mm_loadu_ps(&src[4]);
const __m128 floats3 = _mm_loadu_ps(&src[8]);
const __m128 floats4 = _mm_loadu_ps(&src[12]);
const __m128i ints1 = _mm_castps_si128(_mm_add_ps(floats1, offset));
const __m128i ints2 = _mm_castps_si128(_mm_add_ps(floats2, offset));
const __m128i ints3 = _mm_castps_si128(_mm_add_ps(floats3, offset));
const __m128i ints4 = _mm_castps_si128(_mm_add_ps(floats4, offset));
const __m128i shorts1 = _mm_and_si128(_mm_packs_epi16(ints1, ints2), mask);
const __m128i shorts2 = _mm_and_si128(_mm_packs_epi16(ints3, ints4), mask);
const __m128i bytes = _mm_packus_epi16(shorts1, shorts2);
_mm_storeu_si128((__m128i*)dst, bytes);
i -= 16;
src += 16;
dst += 16;
}
SDL_assert(!i || !(((size_t)dst) & 15));
/* Make sure src is aligned too. */
if (!(((size_t)src) & 15)) {
/* Aligned! Do SSE blocks as long as we have 16 bytes available. */
const __m128 one = _mm_set1_ps(1.0f);
const __m128 negone = _mm_set1_ps(-1.0f);
const __m128 mulby127 = _mm_set1_ps(127.0f);
__m128i *mmdst = (__m128i *)dst;
while (i >= 16) { /* 16 * float32 */
const __m128i ints1 = _mm_cvtps_epi32(_mm_mul_ps(_mm_min_ps(_mm_max_ps(negone, _mm_load_ps(src)), one), mulby127)); /* load 4 floats, clamp, convert to sint32 */
const __m128i ints2 = _mm_cvtps_epi32(_mm_mul_ps(_mm_min_ps(_mm_max_ps(negone, _mm_load_ps(src + 4)), one), mulby127)); /* load 4 floats, clamp, convert to sint32 */
const __m128i ints3 = _mm_cvtps_epi32(_mm_mul_ps(_mm_min_ps(_mm_max_ps(negone, _mm_load_ps(src + 8)), one), mulby127)); /* load 4 floats, clamp, convert to sint32 */
const __m128i ints4 = _mm_cvtps_epi32(_mm_mul_ps(_mm_min_ps(_mm_max_ps(negone, _mm_load_ps(src + 12)), one), mulby127)); /* load 4 floats, clamp, convert to sint32 */
_mm_store_si128(mmdst, _mm_packs_epi16(_mm_packs_epi32(ints1, ints2), _mm_packs_epi32(ints3, ints4))); /* pack down, store out. */
i -= 16;
src += 16;
mmdst++;
}
dst = (Sint8 *)mmdst;
}
/* Finish off any leftovers with scalar operations. */
while (i) {
const float sample = *src;
if (sample >= 1.0f) {
*dst = 127;
} else if (sample <= -1.0f) {
*dst = -128;
} else {
*dst = (Sint8)(sample * 127.0f);
}
i--;
src++;
dst++;
const __m128i ints = _mm_castps_si128(_mm_add_ss(_mm_load_ss(src), offset));
*dst = (Sint8)(_mm_cvtsi128_si32(_mm_packs_epi16(ints, ints)) & 0xFF);
--i;
++src;
++dst;
}
}
static void SDL_TARGETING("sse2") SDL_Convert_F32_to_U8_SSE2(Uint8 *dst, const float *src, int num_samples)
{
int i;
int i = num_samples;
/* 1) Shift the float range from [-1.0, 1.0] to [98304.0, 98306.0]
* 2) Extract the lowest 16 bits and clamp to [0, 255]
* Overflow is correctly handled for inputs between roughly [-254.0, 254.0]
* dst[i] = clamp(i16(f2i(src[i] + 98305.0) & 0xFFFF), 0, 255) */
const __m128 offset = _mm_set1_ps(98305.0f);
const __m128i mask = _mm_set1_epi16(0xFF);
LOG_DEBUG_AUDIO_CONVERT("F32", "U8 (using SSE2)");
/* Get dst aligned to 16 bytes */
for (i = num_samples; i && (((size_t)dst) & 15); --i, ++src, ++dst) {
const float sample = *src;
if (sample >= 1.0f) {
*dst = 255;
} else if (sample <= -1.0f) {
*dst = 0;
} else {
*dst = (Uint8)((sample + 1.0f) * 127.0f);
}
while (i >= 16) {
const __m128 floats1 = _mm_loadu_ps(&src[0]);
const __m128 floats2 = _mm_loadu_ps(&src[4]);
const __m128 floats3 = _mm_loadu_ps(&src[8]);
const __m128 floats4 = _mm_loadu_ps(&src[12]);
const __m128i ints1 = _mm_castps_si128(_mm_add_ps(floats1, offset));
const __m128i ints2 = _mm_castps_si128(_mm_add_ps(floats2, offset));
const __m128i ints3 = _mm_castps_si128(_mm_add_ps(floats3, offset));
const __m128i ints4 = _mm_castps_si128(_mm_add_ps(floats4, offset));
const __m128i shorts1 = _mm_and_si128(_mm_packus_epi16(ints1, ints2), mask);
const __m128i shorts2 = _mm_and_si128(_mm_packus_epi16(ints3, ints4), mask);
const __m128i bytes = _mm_packus_epi16(shorts1, shorts2);
_mm_storeu_si128((__m128i*)dst, bytes);
i -= 16;
src += 16;
dst += 16;
}
SDL_assert(!i || !(((size_t)dst) & 15));
/* Make sure src is aligned too. */
if (!(((size_t)src) & 15)) {
/* Aligned! Do SSE blocks as long as we have 16 bytes available. */
const __m128 one = _mm_set1_ps(1.0f);
const __m128 negone = _mm_set1_ps(-1.0f);
const __m128 mulby127 = _mm_set1_ps(127.0f);
__m128i *mmdst = (__m128i *)dst;
while (i >= 16) { /* 16 * float32 */
const __m128i ints1 = _mm_cvtps_epi32(_mm_mul_ps(_mm_add_ps(_mm_min_ps(_mm_max_ps(negone, _mm_load_ps(src)), one), one), mulby127)); /* load 4 floats, clamp, convert to sint32 */
const __m128i ints2 = _mm_cvtps_epi32(_mm_mul_ps(_mm_add_ps(_mm_min_ps(_mm_max_ps(negone, _mm_load_ps(src + 4)), one), one), mulby127)); /* load 4 floats, clamp, convert to sint32 */
const __m128i ints3 = _mm_cvtps_epi32(_mm_mul_ps(_mm_add_ps(_mm_min_ps(_mm_max_ps(negone, _mm_load_ps(src + 8)), one), one), mulby127)); /* load 4 floats, clamp, convert to sint32 */
const __m128i ints4 = _mm_cvtps_epi32(_mm_mul_ps(_mm_add_ps(_mm_min_ps(_mm_max_ps(negone, _mm_load_ps(src + 12)), one), one), mulby127)); /* load 4 floats, clamp, convert to sint32 */
_mm_store_si128(mmdst, _mm_packus_epi16(_mm_packs_epi32(ints1, ints2), _mm_packs_epi32(ints3, ints4))); /* pack down, store out. */
i -= 16;
src += 16;
mmdst++;
}
dst = (Uint8 *)mmdst;
}
/* Finish off any leftovers with scalar operations. */
while (i) {
const float sample = *src;
if (sample >= 1.0f) {
*dst = 255;
} else if (sample <= -1.0f) {
*dst = 0;
} else {
*dst = (Uint8)((sample + 1.0f) * 127.0f);
}
i--;
src++;
dst++;
const __m128i ints = _mm_castps_si128(_mm_add_ss(_mm_load_ss(src), offset));
*dst = (Uint8)(_mm_cvtsi128_si32(_mm_packus_epi16(ints, ints)) & 0xFF);
--i;
++src;
++dst;
}
}
static void SDL_TARGETING("sse2") SDL_Convert_F32_to_S16_SSE2(Sint16 *dst, const float *src, int num_samples)
{
int i;
int i = num_samples;
/* 1) Shift the float range from [-1.0, 1.0] to [256.0, 258.0]
* 2) Shift the int range from [0x43800000, 0x43810000] to [-32768,32768]
* 3) Clamp to range [-32768,32767]
* Overflow is correctly handled for inputs between roughly [-257.0, +inf)
* dst[i] = clamp(f2i(src[i] + 257.0) - 0x43808000, -32768, 32767) */
const __m128 offset = _mm_set1_ps(257.0f);
LOG_DEBUG_AUDIO_CONVERT("F32", "S16 (using SSE2)");
/* Get dst aligned to 16 bytes */
for (i = num_samples; i && (((size_t)dst) & 15); --i, ++src, ++dst) {
const float sample = *src;
if (sample >= 1.0f) {
*dst = 32767;
} else if (sample <= -1.0f) {
*dst = -32768;
} else {
*dst = (Sint16)(sample * 32767.0f);
}
while (i >= 16) {
const __m128 floats1 = _mm_loadu_ps(&src[0]);
const __m128 floats2 = _mm_loadu_ps(&src[4]);
const __m128 floats3 = _mm_loadu_ps(&src[8]);
const __m128 floats4 = _mm_loadu_ps(&src[12]);
const __m128i ints1 = _mm_sub_epi32(_mm_castps_si128(_mm_add_ps(floats1, offset)), _mm_castps_si128(offset));
const __m128i ints2 = _mm_sub_epi32(_mm_castps_si128(_mm_add_ps(floats2, offset)), _mm_castps_si128(offset));
const __m128i ints3 = _mm_sub_epi32(_mm_castps_si128(_mm_add_ps(floats3, offset)), _mm_castps_si128(offset));
const __m128i ints4 = _mm_sub_epi32(_mm_castps_si128(_mm_add_ps(floats4, offset)), _mm_castps_si128(offset));
const __m128i shorts1 = _mm_packs_epi32(ints1, ints2);
const __m128i shorts2 = _mm_packs_epi32(ints3, ints4);
_mm_storeu_si128((__m128i*)&dst[0], shorts1);
_mm_storeu_si128((__m128i*)&dst[8], shorts2);
i -= 16;
src += 16;
dst += 16;
}
SDL_assert(!i || !(((size_t)dst) & 15));
/* Make sure src is aligned too. */
if (!(((size_t)src) & 15)) {
/* Aligned! Do SSE blocks as long as we have 16 bytes available. */
const __m128 one = _mm_set1_ps(1.0f);
const __m128 negone = _mm_set1_ps(-1.0f);
const __m128 mulby32767 = _mm_set1_ps(32767.0f);
__m128i *mmdst = (__m128i *)dst;
while (i >= 8) { /* 8 * float32 */
const __m128i ints1 = _mm_cvtps_epi32(_mm_mul_ps(_mm_min_ps(_mm_max_ps(negone, _mm_load_ps(src)), one), mulby32767)); /* load 4 floats, clamp, convert to sint32 */
const __m128i ints2 = _mm_cvtps_epi32(_mm_mul_ps(_mm_min_ps(_mm_max_ps(negone, _mm_load_ps(src + 4)), one), mulby32767)); /* load 4 floats, clamp, convert to sint32 */
_mm_store_si128(mmdst, _mm_packs_epi32(ints1, ints2)); /* pack to sint16, store out. */
i -= 8;
src += 8;
mmdst++;
}
dst = (Sint16 *)mmdst;
}
/* Finish off any leftovers with scalar operations. */
while (i) {
const float sample = *src;
if (sample >= 1.0f) {
*dst = 32767;
} else if (sample <= -1.0f) {
*dst = -32768;
} else {
*dst = (Sint16)(sample * 32767.0f);
}
i--;
src++;
dst++;
const __m128i ints = _mm_sub_epi32(_mm_castps_si128(_mm_add_ss(_mm_load_ss(src), offset)), _mm_castps_si128(offset));
*dst = (Sint16)(_mm_cvtsi128_si32(_mm_packs_epi32(ints, ints)) & 0xFFFF);
--i;
++src;
++dst;
}
}
static void SDL_TARGETING("sse2") SDL_Convert_F32_to_S32_SSE2(Sint32 *dst, const float *src, int num_samples)
{
int i;
int i = num_samples;
/* 1) Scale the float range from [-1.0, 1.0] to [-2147483648.0, 2147483648.0]
* 2) Convert to integer (values too small/large become 0x80000000 = -2147483648)
* 3) Fixup values which were too large (0x80000000 ^ 0xFFFFFFFF = 2147483647)
* dst[i] = i32(src[i] * 2147483648.0) ^ ((src[i] >= 2147483648.0) ? 0xFFFFFFFF : 0x00000000) */
const __m128 limit = _mm_set1_ps(2147483648.0f);
LOG_DEBUG_AUDIO_CONVERT("F32", "S32 (using SSE2)");
/* Get dst aligned to 16 bytes */
for (i = num_samples; i && (((size_t)dst) & 15); --i, ++src, ++dst) {
const float sample = *src;
if (sample >= 1.0f) {
*dst = 2147483647;
} else if (sample <= -1.0f) {
*dst = (Sint32)-2147483648LL;
} else {
*dst = ((Sint32)(sample * 8388607.0f)) << 8;
}
while (i >= 16) {
const __m128 floats1 = _mm_loadu_ps(&src[0]);
const __m128 floats2 = _mm_loadu_ps(&src[4]);
const __m128 floats3 = _mm_loadu_ps(&src[8]);
const __m128 floats4 = _mm_loadu_ps(&src[12]);
const __m128 values1 = _mm_mul_ps(floats1, limit);
const __m128 values2 = _mm_mul_ps(floats2, limit);
const __m128 values3 = _mm_mul_ps(floats3, limit);
const __m128 values4 = _mm_mul_ps(floats4, limit);
const __m128i ints1 = _mm_xor_si128(_mm_cvttps_epi32(values1), _mm_castps_si128(_mm_cmpge_ps(values1, limit)));
const __m128i ints2 = _mm_xor_si128(_mm_cvttps_epi32(values2), _mm_castps_si128(_mm_cmpge_ps(values2, limit)));
const __m128i ints3 = _mm_xor_si128(_mm_cvttps_epi32(values3), _mm_castps_si128(_mm_cmpge_ps(values3, limit)));
const __m128i ints4 = _mm_xor_si128(_mm_cvttps_epi32(values4), _mm_castps_si128(_mm_cmpge_ps(values4, limit)));
_mm_storeu_si128((__m128i*)&dst[0], ints1);
_mm_storeu_si128((__m128i*)&dst[4], ints2);
_mm_storeu_si128((__m128i*)&dst[8], ints3);
_mm_storeu_si128((__m128i*)&dst[12], ints4);
i -= 16;
src += 16;
dst += 16;
}
SDL_assert(!i || !(((size_t)dst) & 15));
SDL_assert(!i || !(((size_t)src) & 15));
{
/* Aligned! Do SSE blocks as long as we have 16 bytes available. */
const __m128 one = _mm_set1_ps(1.0f);
const __m128 negone = _mm_set1_ps(-1.0f);
const __m128 mulby8388607 = _mm_set1_ps(8388607.0f);
__m128i *mmdst = (__m128i *)dst;
while (i >= 4) { /* 4 * float32 */
_mm_store_si128(mmdst, _mm_slli_epi32(_mm_cvtps_epi32(_mm_mul_ps(_mm_min_ps(_mm_max_ps(negone, _mm_load_ps(src)), one), mulby8388607)), 8)); /* load 4 floats, clamp, convert to sint32 */
i -= 4;
src += 4;
mmdst++;
}
dst = (Sint32 *)mmdst;
}
/* Finish off any leftovers with scalar operations. */
while (i) {
const float sample = *src;
if (sample >= 1.0f) {
*dst = 2147483647;
} else if (sample <= -1.0f) {
*dst = (Sint32)-2147483648LL;
} else {
*dst = ((Sint32)(sample * 8388607.0f)) << 8;
}
i--;
src++;
dst++;
const __m128 floats = _mm_load_ss(src);
const __m128 values = _mm_mul_ss(floats, limit);
const __m128i ints = _mm_xor_si128(_mm_cvttps_epi32(values), _mm_castps_si128(_mm_cmpge_ss(values, limit)));
*dst = (Sint32)_mm_cvtsi128_si32(ints);
--i;
++src;
++dst;
}
}
#endif
#ifdef SDL_NEON_INTRINSICS
#define DIVBY128 0.0078125f /* 0x1p-7f */
#define DIVBY32768 0.000030517578125f /* 0x1p-15f */
#define DIVBY8388607 0.00000011920930376163766f /* 0x1.000002p-23f */
static void SDL_Convert_S8_to_F32_NEON(float *dst, const Sint8 *src, int num_samples)
{
int i;

View File

@ -131,7 +131,7 @@ int SDL_MixAudioFormat(Uint8 *dst, const Uint8 *src, SDL_AudioFormat format,
}
} break;
case SDL_AUDIO_S16LSB:
case SDL_AUDIO_S16LE:
{
Sint16 src1, src2;
int dst_sample;
@ -155,7 +155,7 @@ int SDL_MixAudioFormat(Uint8 *dst, const Uint8 *src, SDL_AudioFormat format,
}
} break;
case SDL_AUDIO_S16MSB:
case SDL_AUDIO_S16BE:
{
Sint16 src1, src2;
int dst_sample;
@ -179,7 +179,7 @@ int SDL_MixAudioFormat(Uint8 *dst, const Uint8 *src, SDL_AudioFormat format,
}
} break;
case SDL_AUDIO_S32LSB:
case SDL_AUDIO_S32LE:
{
const Uint32 *src32 = (Uint32 *)src;
Uint32 *dst32 = (Uint32 *)dst;
@ -204,7 +204,7 @@ int SDL_MixAudioFormat(Uint8 *dst, const Uint8 *src, SDL_AudioFormat format,
}
} break;
case SDL_AUDIO_S32MSB:
case SDL_AUDIO_S32BE:
{
const Uint32 *src32 = (Uint32 *)src;
Uint32 *dst32 = (Uint32 *)dst;
@ -229,7 +229,7 @@ int SDL_MixAudioFormat(Uint8 *dst, const Uint8 *src, SDL_AudioFormat format,
}
} break;
case SDL_AUDIO_F32LSB:
case SDL_AUDIO_F32LE:
{
const float fmaxvolume = 1.0f / ((float)SDL_MIX_MAXVOLUME);
const float fvolume = (float)volume;
@ -257,7 +257,7 @@ int SDL_MixAudioFormat(Uint8 *dst, const Uint8 *src, SDL_AudioFormat format,
}
} break;
case SDL_AUDIO_F32MSB:
case SDL_AUDIO_F32BE:
{
const float fmaxvolume = 1.0f / ((float)SDL_MIX_MAXVOLUME);
const float fvolume = (float)volume;

View File

@ -24,8 +24,6 @@
#ifndef SDL_sysaudio_h_
#define SDL_sysaudio_h_
#include "../SDL_dataqueue.h"
#define DEBUG_AUDIOSTREAM 0
#define DEBUG_AUDIO_CONVERT 0
@ -58,6 +56,8 @@ extern void (*SDL_Convert_F32_to_S32)(Sint32 *dst, const float *src, int num_sam
#define DEFAULT_AUDIO_CAPTURE_CHANNELS 1
#define DEFAULT_AUDIO_CAPTURE_FREQUENCY 44100
#define AUDIO_SPECS_EQUAL(x, y) (((x).format == (y).format) && ((x).channels == (y).channels) && ((x).freq == (y).freq))
typedef struct SDL_AudioDevice SDL_AudioDevice;
typedef struct SDL_LogicalAudioDevice SDL_LogicalAudioDevice;
@ -70,8 +70,9 @@ extern void SDL_QuitAudio(void);
// Function to get a list of audio formats, ordered most similar to `format` to least, 0-terminated. Don't free results.
const SDL_AudioFormat *SDL_ClosestAudioFormats(SDL_AudioFormat format);
// Must be called at least once before using converters (SDL_CreateAudioStream will call it !!! FIXME but probably shouldn't).
// Must be called at least once before using converters.
extern void SDL_ChooseAudioConverters(void);
extern void SDL_SetupAudioResampler(void);
/* Backends should call this as devices are added to the system (such as
a USB headset being plugged in), and should also be called for
@ -101,7 +102,7 @@ extern SDL_AudioDevice *SDL_FindPhysicalAudioDeviceByCallback(SDL_bool (*callbac
extern void SDL_UpdatedAudioDeviceFormat(SDL_AudioDevice *device);
// Backends can call this to get a standardized name for a thread to power a specific audio device.
char *SDL_GetAudioThreadName(SDL_AudioDevice *device, char *buf, size_t buflen);
extern char *SDL_GetAudioThreadName(SDL_AudioDevice *device, char *buf, size_t buflen);
// These functions are the heart of the audio threads. Backends can call them directly if they aren't using the SDL-provided thread.
@ -113,6 +114,14 @@ extern SDL_bool SDL_CaptureAudioThreadIterate(SDL_AudioDevice *device);
extern void SDL_CaptureAudioThreadShutdown(SDL_AudioDevice *device);
extern void SDL_AudioThreadFinalize(SDL_AudioDevice *device);
// this gets used from the audio device threads. It has rules, don't use this if you don't know how to use it!
extern void ConvertAudio(int num_frames, const void *src, SDL_AudioFormat src_format, int src_channels,
void *dst, SDL_AudioFormat dst_format, int dst_channels, void* scratch);
// Special case to let something in SDL_audiocvt.c access something in SDL_audio.c. Don't use this.
extern void OnAudioStreamCreated(SDL_AudioStream *stream);
extern void OnAudioStreamDestroy(SDL_AudioStream *stream);
typedef struct SDL_AudioDriverImpl
{
void (*DetectDevices)(SDL_AudioDevice **default_output, SDL_AudioDevice **default_capture);
@ -120,7 +129,7 @@ typedef struct SDL_AudioDriverImpl
void (*ThreadInit)(SDL_AudioDevice *device); // Called by audio thread at start
void (*ThreadDeinit)(SDL_AudioDevice *device); // Called by audio thread at end
void (*WaitDevice)(SDL_AudioDevice *device);
void (*PlayDevice)(SDL_AudioDevice *device, const Uint8 *buffer, int buflen); // buffer and buflen are always from GetDeviceBuf, passed here for convenience.
int (*PlayDevice)(SDL_AudioDevice *device, const Uint8 *buffer, int buflen); // buffer and buflen are always from GetDeviceBuf, passed here for convenience.
Uint8 *(*GetDeviceBuf)(SDL_AudioDevice *device, int *buffer_size);
void (*WaitCaptureDevice)(SDL_AudioDevice *device);
int (*CaptureFromDevice)(SDL_AudioDevice *device, void *buffer, int buflen);
@ -145,6 +154,7 @@ typedef struct SDL_AudioDriver
SDL_RWLock *device_list_lock; // A mutex for device detection
SDL_AudioDevice *output_devices; // the list of currently-available audio output devices.
SDL_AudioDevice *capture_devices; // the list of currently-available audio capture devices.
SDL_AudioStream *existing_streams; // a list of all existing SDL_AudioStreams.
SDL_AudioDeviceID default_output_device_id;
SDL_AudioDeviceID default_capture_device_id;
SDL_AtomicInt output_device_count;
@ -153,46 +163,41 @@ typedef struct SDL_AudioDriver
SDL_AtomicInt shutting_down; // non-zero during SDL_Quit, so we known not to accept any last-minute device hotplugs.
} SDL_AudioDriver;
struct SDL_AudioQueue; // forward decl.
struct SDL_AudioStream
{
SDL_DataQueue *queue;
SDL_Mutex *lock; // this is just a copy of `queue`'s mutex. We share a lock.
SDL_Mutex* lock;
SDL_AudioStreamRequestCallback get_callback;
SDL_AudioStreamCallback get_callback;
void *get_callback_userdata;
SDL_AudioStreamRequestCallback put_callback;
SDL_AudioStreamCallback put_callback;
void *put_callback_userdata;
Uint8 *work_buffer; // used for scratch space during data conversion/resampling.
Uint8 *history_buffer; // history for left padding and future sample rate changes.
Uint8 *future_buffer; // stuff that left the queue for the right padding and will be next read's data.
float *left_padding; // left padding for resampling.
float *right_padding; // right padding for resampling.
SDL_bool flushed;
size_t work_buffer_allocation;
size_t history_buffer_allocation;
size_t future_buffer_allocation;
size_t resampler_padding_allocation;
int resampler_padding_frames;
int history_buffer_frames;
int future_buffer_filled_frames;
SDL_AudioSpec src_spec;
SDL_AudioSpec dst_spec;
float freq_ratio;
int src_sample_frame_size;
int dst_sample_frame_size;
int max_sample_frame_size;
struct SDL_AudioQueue* queue;
Uint64 total_bytes_queued;
int pre_resample_channels;
int packetlen;
SDL_AudioSpec input_spec; // The spec of input data currently being processed
Sint64 resample_offset;
Uint8 *work_buffer; // used for scratch space during data conversion/resampling.
size_t work_buffer_allocation;
Uint8 *history_buffer; // history for left padding and future sample rate changes.
size_t history_buffer_allocation;
SDL_bool simplified; // SDL_TRUE if created via SDL_OpenAudioDeviceStream
SDL_LogicalAudioDevice *bound_device;
SDL_AudioStream *next_binding;
SDL_AudioStream *prev_binding;
SDL_AudioStream *prev; // linked list of all existing streams (so we can free them on shutdown).
SDL_AudioStream *next; // linked list of all existing streams (so we can free them on shutdown).
};
/* Logical devices are an abstraction in SDL3; you can open the same physical
@ -214,7 +219,16 @@ struct SDL_LogicalAudioDevice
SDL_AudioStream *bound_streams;
// SDL_TRUE if this was opened as a default device.
SDL_bool is_default;
SDL_bool opened_as_default;
// SDL_TRUE if device was opened with SDL_OpenAudioDeviceStream (so it forbids binding changes, etc).
SDL_bool simplified;
// If non-NULL, callback into the app that lets them access the final postmix buffer.
SDL_AudioPostmixCallback postmix;
// App-supplied pointer for postmix callback.
void *postmix_userdata;
// double-linked list of opened devices on the same physical device.
SDL_LogicalAudioDevice *next;
@ -263,14 +277,22 @@ struct SDL_AudioDevice
// SDL_TRUE if this is a capture device instead of an output device
SDL_bool iscapture;
// Scratch buffer used for mixing.
// SDL_TRUE if audio thread can skip silence/mix/convert stages and just do a basic memcpy.
SDL_bool simple_copy;
// Scratch buffers used for mixing.
Uint8 *work_buffer;
Uint8 *mix_buffer;
float *postmix_buffer;
// Size of work_buffer (and mix_buffer) in bytes.
int work_buffer_size;
// A thread to feed the audio device
SDL_Thread *thread;
// SDL_TRUE if this physical device is currently opened by the backend.
SDL_bool is_opened;
SDL_bool currently_opened;
// Data private to this driver
struct SDL_PrivateAudioData *hidden;
@ -316,7 +338,4 @@ extern AudioBootStrap N3DSAUDIO_bootstrap;
extern AudioBootStrap EMSCRIPTENAUDIO_bootstrap;
extern AudioBootStrap QSAAUDIO_bootstrap;
extern SDL_AudioDevice *get_audio_dev(SDL_AudioDeviceID id);
extern int get_max_num_audio_dev(void);
#endif // SDL_sysaudio_h_

View File

@ -2039,10 +2039,10 @@ static int WaveLoad(SDL_RWops *src, WaveFile *file, SDL_AudioSpec *spec, Uint8 *
case ALAW_CODE:
case MULAW_CODE:
/* These can be easily stored in the byte order of the system. */
spec->format = SDL_AUDIO_S16SYS;
spec->format = SDL_AUDIO_S16;
break;
case IEEE_FLOAT_CODE:
spec->format = SDL_AUDIO_F32LSB;
spec->format = SDL_AUDIO_F32LE;
break;
case PCM_CODE:
switch (format->bitspersample) {
@ -2050,11 +2050,11 @@ static int WaveLoad(SDL_RWops *src, WaveFile *file, SDL_AudioSpec *spec, Uint8 *
spec->format = SDL_AUDIO_U8;
break;
case 16:
spec->format = SDL_AUDIO_S16LSB;
spec->format = SDL_AUDIO_S16LE;
break;
case 24: /* Has been shifted to 32 bits. */
case 32:
spec->format = SDL_AUDIO_S32LSB;
spec->format = SDL_AUDIO_S32LE;
break;
default:
/* Just in case something unexpected happened in the checks. */

View File

@ -111,13 +111,14 @@ static void AAUDIO_WaitDevice(SDL_AudioDevice *device)
SDL_WaitSemaphore(device->hidden->semaphore);
}
static void AAUDIO_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, int buflen)
static int AAUDIO_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, int buflen)
{
// AAUDIO_dataCallback picks up our work and unblocks AAUDIO_WaitDevice. But make sure we didn't fail here.
if (SDL_AtomicGet(&device->hidden->error_callback_triggered)) {
SDL_AtomicSet(&device->hidden->error_callback_triggered, 0);
SDL_AudioDeviceDisconnected(device);
return -1;
}
return 0;
}
// no need for a FlushCapture implementation, just don't read mixbuf until the next iteration.
@ -197,9 +198,9 @@ static int AAUDIO_OpenDevice(SDL_AudioDevice *device)
const aaudio_direction_t direction = (iscapture ? AAUDIO_DIRECTION_INPUT : AAUDIO_DIRECTION_OUTPUT);
ctx.AAudioStreamBuilder_setDirection(builder, direction);
aaudio_format_t format;
if ((device->spec.format == SDL_AUDIO_S32SYS) && (SDL_GetAndroidSDKVersion() >= 31)) {
if ((device->spec.format == SDL_AUDIO_S32) && (SDL_GetAndroidSDKVersion() >= 31)) {
format = AAUDIO_FORMAT_PCM_I32;
} else if (device->spec.format == SDL_AUDIO_F32SYS) {
} else if (device->spec.format == SDL_AUDIO_F32) {
format = AAUDIO_FORMAT_PCM_FLOAT;
} else {
format = AAUDIO_FORMAT_PCM_I16; // sint16 is a safe bet for everything else.
@ -244,11 +245,11 @@ static int AAUDIO_OpenDevice(SDL_AudioDevice *device)
format = ctx.AAudioStream_getFormat(hidden->stream);
if (format == AAUDIO_FORMAT_PCM_I16) {
device->spec.format = SDL_AUDIO_S16SYS;
device->spec.format = SDL_AUDIO_S16;
} else if (format == AAUDIO_FORMAT_PCM_I32) {
device->spec.format = SDL_AUDIO_S32SYS;
device->spec.format = SDL_AUDIO_S32;
} else if (format == AAUDIO_FORMAT_PCM_FLOAT) {
device->spec.format = SDL_AUDIO_F32SYS;
device->spec.format = SDL_AUDIO_F32;
} else {
return SDL_SetError("Got unexpected audio format %d from AAudioStream_getFormat", (int) format);
}

View File

@ -351,12 +351,11 @@ static void ALSA_WaitDevice(SDL_AudioDevice *device)
}
}
static void ALSA_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, int buflen)
static int ALSA_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, int buflen)
{
SDL_assert(buffer == device->hidden->mixbuf);
Uint8 *sample_buf = device->hidden->mixbuf;
const int frame_size = ((SDL_AUDIO_BITSIZE(device->spec.format)) / 8) *
device->spec.channels;
const int frame_size = SDL_AUDIO_FRAMESIZE(device->spec);
snd_pcm_uframes_t frames_left = (snd_pcm_uframes_t) (buflen / frame_size);
device->hidden->swizzle_func(device, sample_buf, frames_left);
@ -378,8 +377,7 @@ static void ALSA_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, int bu
SDL_LogError(SDL_LOG_CATEGORY_AUDIO,
"ALSA write failed (unrecoverable): %s",
ALSA_snd_strerror(status));
SDL_AudioDeviceDisconnected(device);
return;
return -1;
}
continue;
} else if (status == 0) {
@ -391,6 +389,8 @@ static void ALSA_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, int bu
sample_buf += status * frame_size;
frames_left -= status;
}
return 0;
}
static Uint8 *ALSA_GetDeviceBuf(SDL_AudioDevice *device, int *buffer_size)
@ -401,8 +401,7 @@ static Uint8 *ALSA_GetDeviceBuf(SDL_AudioDevice *device, int *buffer_size)
static int ALSA_CaptureFromDevice(SDL_AudioDevice *device, void *buffer, int buflen)
{
Uint8 *sample_buf = (Uint8 *)buffer;
const int frame_size = ((SDL_AUDIO_BITSIZE(device->spec.format)) / 8) *
device->spec.channels;
const int frame_size = SDL_AUDIO_FRAMESIZE(device->spec);
const int total_frames = buflen / frame_size;
snd_pcm_uframes_t frames_left = total_frames;
@ -564,22 +563,22 @@ static int ALSA_OpenDevice(SDL_AudioDevice *device)
case SDL_AUDIO_S8:
format = SND_PCM_FORMAT_S8;
break;
case SDL_AUDIO_S16LSB:
case SDL_AUDIO_S16LE:
format = SND_PCM_FORMAT_S16_LE;
break;
case SDL_AUDIO_S16MSB:
case SDL_AUDIO_S16BE:
format = SND_PCM_FORMAT_S16_BE;
break;
case SDL_AUDIO_S32LSB:
case SDL_AUDIO_S32LE:
format = SND_PCM_FORMAT_S32_LE;
break;
case SDL_AUDIO_S32MSB:
case SDL_AUDIO_S32BE:
format = SND_PCM_FORMAT_S32_BE;
break;
case SDL_AUDIO_F32LSB:
case SDL_AUDIO_F32LE:
format = SND_PCM_FORMAT_FLOAT_LE;
break;
case SDL_AUDIO_F32MSB:
case SDL_AUDIO_F32BE:
format = SND_PCM_FORMAT_FLOAT_BE;
break;
default:

View File

@ -87,9 +87,10 @@ static int ANDROIDAUDIO_OpenDevice(SDL_AudioDevice *device)
// !!! FIXME: this needs a WaitDevice implementation.
static void ANDROIDAUDIO_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, int buflen)
static int ANDROIDAUDIO_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, int buflen)
{
Android_JNI_WriteAudioBuffer();
return 0;
}
static Uint8 *ANDROIDAUDIO_GetDeviceBuf(SDL_AudioDevice *device, int *buffer_size)

View File

@ -27,7 +27,7 @@
#include "SDL_coreaudio.h"
#include "../../thread/SDL_systhread.h"
#define DEBUG_COREAUDIO 1
#define DEBUG_COREAUDIO 0
#if DEBUG_COREAUDIO
#define CHECK_RESULT(msg) \
@ -525,7 +525,7 @@ static SDL_bool UpdateAudioSession(SDL_AudioDevice *device, SDL_bool open, SDL_b
#endif
static void COREAUDIO_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, int buffer_size)
static int COREAUDIO_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, int buffer_size)
{
AudioQueueBufferRef current_buffer = device->hidden->current_buffer;
SDL_assert(current_buffer != NULL); // should have been called from OutputBufferReadyCallback
@ -533,6 +533,7 @@ static void COREAUDIO_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, i
current_buffer->mAudioDataByteSize = current_buffer->mAudioDataBytesCapacity;
device->hidden->current_buffer = NULL;
AudioQueueEnqueueBuffer(device->hidden->audioQueue, current_buffer, 0, NULL);
return 0;
}
static Uint8 *COREAUDIO_GetDeviceBuf(SDL_AudioDevice *device, int *buffer_size)
@ -875,12 +876,12 @@ static int COREAUDIO_OpenDevice(SDL_AudioDevice *device)
switch (test_format) {
case SDL_AUDIO_U8:
case SDL_AUDIO_S8:
case SDL_AUDIO_S16LSB:
case SDL_AUDIO_S16MSB:
case SDL_AUDIO_S32LSB:
case SDL_AUDIO_S32MSB:
case SDL_AUDIO_F32LSB:
case SDL_AUDIO_F32MSB:
case SDL_AUDIO_S16LE:
case SDL_AUDIO_S16BE:
case SDL_AUDIO_S32LE:
case SDL_AUDIO_S32BE:
case SDL_AUDIO_F32LE:
case SDL_AUDIO_F32BE:
break;
default:

View File

@ -179,7 +179,7 @@ static BOOL CALLBACK FindAllDevs(LPGUID guid, LPCWSTR desc, LPCWSTR module, LPVO
if (str != NULL) {
LPGUID cpyguid = (LPGUID)SDL_malloc(sizeof(GUID));
if (cpyguid) {
SDL_memcpy(cpyguid, guid, sizeof(GUID));
SDL_copyp(cpyguid, guid);
/* Note that spec is NULL, because we are required to connect to the
* device before getting the channel mask and output format, making
@ -285,11 +285,14 @@ static void DSOUND_WaitDevice(SDL_AudioDevice *device)
}
}
static void DSOUND_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, int buflen)
static int DSOUND_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, int buflen)
{
// Unlock the buffer, allowing it to play
SDL_assert(buflen == device->buffer_size);
IDirectSoundBuffer_Unlock(device->hidden->mixbuf, (LPVOID) buffer, buflen, NULL, 0);
if (IDirectSoundBuffer_Unlock(device->hidden->mixbuf, (LPVOID) buffer, buflen, NULL, 0) != DS_OK) {
return -1;
}
return 0;
}
static Uint8 *DSOUND_GetDeviceBuf(SDL_AudioDevice *device, int *buffer_size)
@ -378,7 +381,7 @@ static int DSOUND_CaptureFromDevice(SDL_AudioDevice *device, void *buffer, int b
return -1;
}
SDL_assert(ptr1len == buflen);
SDL_assert(ptr1len == (DWORD)buflen);
SDL_assert(ptr2 == NULL);
SDL_assert(ptr2len == 0);
@ -614,7 +617,7 @@ static int DSOUND_OpenDevice(SDL_AudioDevice *device)
}
wfmt.Format.wBitsPerSample = SDL_AUDIO_BITSIZE(device->spec.format);
wfmt.Format.nChannels = device->spec.channels;
wfmt.Format.nChannels = (WORD)device->spec.channels;
wfmt.Format.nSamplesPerSec = device->spec.freq;
wfmt.Format.nBlockAlign = wfmt.Format.nChannels * (wfmt.Format.wBitsPerSample / 8);
wfmt.Format.nAvgBytesPerSec = wfmt.Format.nSamplesPerSec * wfmt.Format.nBlockAlign;

View File

@ -40,15 +40,16 @@ static void DISKAUDIO_WaitDevice(SDL_AudioDevice *device)
SDL_Delay(device->hidden->io_delay);
}
static void DISKAUDIO_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, int buffer_size)
static int DISKAUDIO_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, int buffer_size)
{
const int written = (int)SDL_RWwrite(device->hidden->io, buffer, (size_t)buffer_size);
if (written != buffer_size) { // If we couldn't write, assume fatal error for now
SDL_AudioDeviceDisconnected(device);
return -1;
}
#ifdef DEBUG_AUDIO
SDL_Log("DISKAUDIO: Wrote %d bytes of audio data", (int) written);
#endif
return 0;
}
static Uint8 *DISKAUDIO_GetDeviceBuf(SDL_AudioDevice *device, int *buffer_size)

View File

@ -111,12 +111,12 @@ static int DSP_OpenDevice(SDL_AudioDevice *device)
format = AFMT_U8;
}
break;
case SDL_AUDIO_S16LSB:
case SDL_AUDIO_S16LE:
if (value & AFMT_S16_LE) {
format = AFMT_S16_LE;
}
break;
case SDL_AUDIO_S16MSB:
case SDL_AUDIO_S16BE:
if (value & AFMT_S16_BE) {
format = AFMT_S16_BE;
}
@ -225,17 +225,17 @@ static void DSP_WaitDevice(SDL_AudioDevice *device)
}
}
static void DSP_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, int buflen)
static int DSP_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, int buflen)
{
struct SDL_PrivateAudioData *h = device->hidden;
if (write(h->audio_fd, buffer, buflen) == -1) {
perror("Audio write");
SDL_AudioDeviceDisconnected(device);
return;
return -1;
}
#ifdef DEBUG_AUDIO
fprintf(stderr, "Wrote %d bytes of audio data\n", h->mixlen);
#endif
return 0;
}
static Uint8 *DSP_GetDeviceBuf(SDL_AudioDevice *device, int *buffer_size)

View File

@ -36,9 +36,9 @@ static Uint8 *EMSCRIPTENAUDIO_GetDeviceBuf(SDL_AudioDevice *device, int *buffer_
return device->hidden->mixbuf;
}
static void EMSCRIPTENAUDIO_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, int buffer_size)
static int EMSCRIPTENAUDIO_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, int buffer_size)
{
const int framelen = (SDL_AUDIO_BITSIZE(device->spec.format) / 8) * device->spec.channels;
const int framelen = SDL_AUDIO_FRAMESIZE(device->spec);
MAIN_THREAD_EM_ASM({
var SDL3 = Module['SDL3'];
var numChannels = SDL3.audio.currentOutputBuffer['numberOfChannels'];
@ -53,11 +53,7 @@ static void EMSCRIPTENAUDIO_PlayDevice(SDL_AudioDevice *device, const Uint8 *buf
}
}
}, buffer, buffer_size / framelen);
}
static void HandleAudioProcess(SDL_AudioDevice *device) // this fires when the main thread is idle.
{
SDL_OutputAudioThreadIterate(device);
return 0;
}
@ -92,11 +88,6 @@ static int EMSCRIPTENAUDIO_CaptureFromDevice(SDL_AudioDevice *device, void *buff
return buflen;
}
static void HandleCaptureProcess(SDL_AudioDevice *device) // this fires when the main thread is idle.
{
SDL_CaptureAudioThreadIterate(device);
}
static void EMSCRIPTENAUDIO_CloseDevice(SDL_AudioDevice *device)
{
if (!device->hidden) {
@ -107,32 +98,28 @@ static void EMSCRIPTENAUDIO_CloseDevice(SDL_AudioDevice *device)
var SDL3 = Module['SDL3'];
if ($0) {
if (SDL3.capture.silenceTimer !== undefined) {
clearTimeout(SDL3.capture.silenceTimer);
clearInterval(SDL3.capture.silenceTimer);
}
if (SDL3.capture.stream !== undefined) {
var tracks = SDL3.capture.stream.getAudioTracks();
for (var i = 0; i < tracks.length; i++) {
SDL3.capture.stream.removeTrack(tracks[i]);
}
SDL3.capture.stream = undefined;
}
if (SDL3.capture.scriptProcessorNode !== undefined) {
SDL3.capture.scriptProcessorNode.onaudioprocess = function(audioProcessingEvent) {};
SDL3.capture.scriptProcessorNode.disconnect();
SDL3.capture.scriptProcessorNode = undefined;
}
if (SDL3.capture.mediaStreamNode !== undefined) {
SDL3.capture.mediaStreamNode.disconnect();
SDL3.capture.mediaStreamNode = undefined;
}
if (SDL3.capture.silenceBuffer !== undefined) {
SDL3.capture.silenceBuffer = undefined
}
SDL3.capture = undefined;
} else {
if (SDL3.audio.scriptProcessorNode != undefined) {
SDL3.audio.scriptProcessorNode.disconnect();
SDL3.audio.scriptProcessorNode = undefined;
}
if (SDL3.audio.silenceTimer !== undefined) {
clearInterval(SDL3.audio.silenceTimer);
}
SDL3.audio = undefined;
}
@ -174,7 +161,9 @@ static int EMSCRIPTENAUDIO_OpenDevice(SDL_AudioDevice *device)
SDL3.audioContext = new webkitAudioContext();
}
if (SDL3.audioContext) {
autoResumeAudioContext(SDL3.audioContext);
if ((typeof navigator.userActivation) === 'undefined') { // Firefox doesn't have this (as of August 2023), use autoResumeAudioContext instead.
autoResumeAudioContext(SDL3.audioContext);
}
}
}
return SDL3.audioContext === undefined ? -1 : 0;
@ -227,8 +216,9 @@ static int EMSCRIPTENAUDIO_OpenDevice(SDL_AudioDevice *device)
var have_microphone = function(stream) {
//console.log('SDL audio capture: we have a microphone! Replacing silence callback.');
if (SDL3.capture.silenceTimer !== undefined) {
clearTimeout(SDL3.capture.silenceTimer);
clearInterval(SDL3.capture.silenceTimer);
SDL3.capture.silenceTimer = undefined;
SDL3.capture.silenceBuffer = undefined
}
SDL3.capture.mediaStreamNode = SDL3.audioContext.createMediaStreamSource(stream);
SDL3.capture.scriptProcessorNode = SDL3.audioContext.createScriptProcessor($1, $0, 1);
@ -255,14 +245,14 @@ static int EMSCRIPTENAUDIO_OpenDevice(SDL_AudioDevice *device)
dynCall('vi', $2, [$3]);
};
SDL3.capture.silenceTimer = setTimeout(silence_callback, ($1 / SDL3.audioContext.sampleRate) * 1000);
SDL3.capture.silenceTimer = setInterval(silence_callback, ($1 / SDL3.audioContext.sampleRate) * 1000);
if ((navigator.mediaDevices !== undefined) && (navigator.mediaDevices.getUserMedia !== undefined)) {
navigator.mediaDevices.getUserMedia({ audio: true, video: false }).then(have_microphone).catch(no_microphone);
} else if (navigator.webkitGetUserMedia !== undefined) {
navigator.webkitGetUserMedia({ audio: true, video: false }, have_microphone, no_microphone);
}
}, device->spec.channels, device->sample_frames, HandleCaptureProcess, device);
}, device->spec.channels, device->sample_frames, SDL_CaptureAudioThreadIterate, device);
} else {
// setup a ScriptProcessorNode
MAIN_THREAD_EM_ASM({
@ -270,11 +260,38 @@ static int EMSCRIPTENAUDIO_OpenDevice(SDL_AudioDevice *device)
SDL3.audio.scriptProcessorNode = SDL3.audioContext['createScriptProcessor']($1, 0, $0);
SDL3.audio.scriptProcessorNode['onaudioprocess'] = function (e) {
if ((SDL3 === undefined) || (SDL3.audio === undefined)) { return; }
// if we're actually running the node, we don't need the fake callback anymore, so kill it.
if (SDL3.audio.silenceTimer !== undefined) {
clearInterval(SDL3.audio.silenceTimer);
SDL3.audio.silenceTimer = undefined;
SDL3.audio.silenceBuffer = undefined;
}
SDL3.audio.currentOutputBuffer = e['outputBuffer'];
dynCall('vi', $2, [$3]);
};
SDL3.audio.scriptProcessorNode['connect'](SDL3.audioContext['destination']);
}, device->spec.channels, device->sample_frames, HandleAudioProcess, device);
if (SDL3.audioContext.state === 'suspended') { // uhoh, autoplay is blocked.
SDL3.audio.silenceBuffer = SDL3.audioContext.createBuffer($0, $1, SDL3.audioContext.sampleRate);
SDL3.audio.silenceBuffer.getChannelData(0).fill(0.0);
var silence_callback = function() {
if ((typeof navigator.userActivation) !== 'undefined') { // Almost everything modern except Firefox (as of August 2023)
if (navigator.userActivation.hasBeenActive) {
SDL3.audioContext.resume();
}
}
// the buffer that gets filled here just gets ignored, so the app can make progress
// and/or avoid flooding audio queues until we can actually play audio.
SDL3.audio.currentOutputBuffer = SDL3.audio.silenceBuffer;
dynCall('vi', $2, [$3]);
SDL3.audio.currentOutputBuffer = undefined;
};
SDL3.audio.silenceTimer = setInterval(silence_callback, ($1 / SDL3.audioContext.sampleRate) * 1000);
}
}, device->spec.channels, device->sample_frames, SDL_OutputAudioThreadIterate, device);
}
return 0;

View File

@ -46,13 +46,14 @@ static Uint8 *HAIKUAUDIO_GetDeviceBuf(SDL_AudioDevice *device, int *buffer_size)
return device->hidden->current_buffer;
}
static void HAIKUAUDIO_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, int buffer_size)
static int HAIKUAUDIO_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, int buffer_size)
{
// We already wrote our output right into the BSoundPlayer's callback's stream. Just clean up our stuff.
SDL_assert(device->hidden->current_buffer != NULL);
SDL_assert(device->hidden->current_buffer_len > 0);
device->hidden->current_buffer = NULL;
device->hidden->current_buffer_len = 0;
return 0;
}
// The Haiku callback for handling the audio buffer
@ -130,29 +131,29 @@ static int HAIKUAUDIO_OpenDevice(SDL_AudioDevice *device)
format.format = media_raw_audio_format::B_AUDIO_UCHAR;
break;
case SDL_AUDIO_S16LSB:
case SDL_AUDIO_S16LE:
format.format = media_raw_audio_format::B_AUDIO_SHORT;
break;
case SDL_AUDIO_S16MSB:
case SDL_AUDIO_S16BE:
format.format = media_raw_audio_format::B_AUDIO_SHORT;
format.byte_order = B_MEDIA_BIG_ENDIAN;
break;
case SDL_AUDIO_S32LSB:
case SDL_AUDIO_S32LE:
format.format = media_raw_audio_format::B_AUDIO_INT;
break;
case SDL_AUDIO_S32MSB:
case SDL_AUDIO_S32BE:
format.format = media_raw_audio_format::B_AUDIO_INT;
format.byte_order = B_MEDIA_BIG_ENDIAN;
break;
case SDL_AUDIO_F32LSB:
case SDL_AUDIO_F32LE:
format.format = media_raw_audio_format::B_AUDIO_FLOAT;
break;
case SDL_AUDIO_F32MSB:
case SDL_AUDIO_F32BE:
format.format = media_raw_audio_format::B_AUDIO_FLOAT;
format.byte_order = B_MEDIA_BIG_ENDIAN;
break;

View File

@ -149,7 +149,7 @@ static int jackProcessPlaybackCallback(jack_nframes_t nframes, void *arg)
return 0;
}
static void JACK_PlayDevice(SDL_AudioDevice *device, const Uint8 *ui8buffer, int buflen)
static int JACK_PlayDevice(SDL_AudioDevice *device, const Uint8 *ui8buffer, int buflen)
{
const float *buffer = (float *) ui8buffer;
jack_port_t **ports = device->hidden->sdlports;
@ -167,6 +167,8 @@ static void JACK_PlayDevice(SDL_AudioDevice *device, const Uint8 *ui8buffer, int
}
}
}
return 0;
}
static Uint8 *JACK_GetDeviceBuf(SDL_AudioDevice *device, int *buffer_size)
@ -307,7 +309,7 @@ static int JACK_OpenDevice(SDL_AudioDevice *device)
/* !!! FIXME: docs say about buffer size: "This size may change, clients that depend on it must register a bufsize_callback so they will be notified if it does." */
/* Jack pretty much demands what it wants. */
device->spec.format = SDL_AUDIO_F32SYS;
device->spec.format = SDL_AUDIO_F32;
device->spec.freq = JACK_jack_get_sample_rate(client);
device->spec.channels = channels;
device->sample_frames = JACK_jack_get_buffer_size(client);

View File

@ -161,7 +161,7 @@ static int N3DSAUDIO_OpenDevice(SDL_AudioDevice *device)
SDL_memset(device->hidden->waveBuf, 0, sizeof(ndspWaveBuf) * NUM_BUFFERS);
const int sample_frame_size = device->spec.channels * (SDL_AUDIO_BITSIZE(device->spec.format) / 8);
const int sample_frame_size = SDL_AUDIO_FRAMESIZE(device->spec);
for (unsigned i = 0; i < NUM_BUFFERS; i++) {
device->hidden->waveBuf[i].data_vaddr = data_vaddr;
device->hidden->waveBuf[i].nsamples = device->buffer_size / sample_frame_size;
@ -176,7 +176,7 @@ static int N3DSAUDIO_OpenDevice(SDL_AudioDevice *device)
return 0;
}
static void N3DSAUDIO_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, int buflen)
static int N3DSAUDIO_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, int buflen)
{
contextLock(device);
@ -185,7 +185,7 @@ static void N3DSAUDIO_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, i
if (device->hidden->isCancelled ||
device->hidden->waveBuf[nextbuf].status != NDSP_WBUF_FREE) {
contextUnlock(device);
return;
return 0; // !!! FIXME: is this a fatal error? If so, this should return -1.
}
device->hidden->nextbuf = (nextbuf + 1) % NUM_BUFFERS;
@ -196,6 +196,8 @@ static void N3DSAUDIO_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, i
DSP_FlushDataCache(device->hidden->waveBuf[nextbuf].data_vaddr, buflen);
ndspChnWaveBufAdd(0, &device->hidden->waveBuf[nextbuf]);
return 0;
}
static void N3DSAUDIO_WaitDevice(SDL_AudioDevice *device)

View File

@ -130,7 +130,7 @@ static void NETBSDAUDIO_WaitDevice(SDL_AudioDevice *device)
SDL_AudioDeviceDisconnected(device);
return;
}
const size_t remain = (size_t)((iscapture ? info.record.seek : info.play.seek) * (SDL_AUDIO_BITSIZE(device->spec.format) / 8));
const size_t remain = (size_t)((iscapture ? info.record.seek : info.play.seek) * SDL_AUDIO_BYTESIZE(device->spec.format));
if (!iscapture && (remain >= device->buffer_size)) {
SDL_Delay(10);
} else if (iscapture && (remain < device->buffer_size)) {
@ -141,20 +141,18 @@ static void NETBSDAUDIO_WaitDevice(SDL_AudioDevice *device)
}
}
static void NETBSDAUDIO_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, int buflen)
static int NETBSDAUDIO_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, int buflen)
{
struct SDL_PrivateAudioData *h = device->hidden;
const int written = write(h->audio_fd, buffer, buflen);
if (written == -1) {
// Non recoverable error has occurred. It should be reported!!!
SDL_AudioDeviceDisconnected(device);
perror("audio");
return;
if (written != buflen) { // Treat even partial writes as fatal errors.
return -1;
}
#ifdef DEBUG_AUDIO
fprintf(stderr, "Wrote %d bytes of audio data\n", written);
#endif
return 0;
}
static Uint8 *NETBSDAUDIO_GetDeviceBuf(SDL_AudioDevice *device, int *buffer_size)
@ -183,7 +181,7 @@ static void NETBSDAUDIO_FlushCapture(SDL_AudioDevice *device)
struct SDL_PrivateAudioData *h = device->hidden;
audio_info_t info;
if (ioctl(device->hidden->audio_fd, AUDIO_GETINFO, &info) == 0) {
size_t remain = (size_t)(info.record.seek * (SDL_AUDIO_BITSIZE(device->spec.format) / 8));
size_t remain = (size_t)(info.record.seek * SDL_AUDIO_BYTESIZE(device->spec.format));
while (remain > 0) {
char buf[512];
const size_t len = SDL_min(sizeof(buf), remain);
@ -250,16 +248,16 @@ static int NETBSDAUDIO_OpenDevice(SDL_AudioDevice *device)
case SDL_AUDIO_S8:
encoding = AUDIO_ENCODING_SLINEAR;
break;
case SDL_AUDIO_S16LSB:
case SDL_AUDIO_S16LE:
encoding = AUDIO_ENCODING_SLINEAR_LE;
break;
case SDL_AUDIO_S16MSB:
case SDL_AUDIO_S16BE:
encoding = AUDIO_ENCODING_SLINEAR_BE;
break;
case SDL_AUDIO_S32LSB:
case SDL_AUDIO_S32LE:
encoding = AUDIO_ENCODING_SLINEAR_LE;
break;
case SDL_AUDIO_S32MSB:
case SDL_AUDIO_S32BE:
encoding = AUDIO_ENCODING_SLINEAR_BE;
break;
default:

View File

@ -248,7 +248,7 @@ static int openslES_CreatePCMRecorder(SDL_AudioDevice *device)
}
// Just go with signed 16-bit audio as it's the most compatible
device->spec.format = SDL_AUDIO_S16SYS;
device->spec.format = SDL_AUDIO_S16;
device->spec.channels = 1;
//device->spec.freq = SL_SAMPLINGRATE_16 / 1000;*/
@ -424,12 +424,12 @@ static int openslES_CreatePCMPlayer(SDL_AudioDevice *device)
if (!test_format) {
// Didn't find a compatible format :
LOGI("No compatible audio format, using signed 16-bit audio");
test_format = SDL_AUDIO_S16SYS;
test_format = SDL_AUDIO_S16;
}
device->spec.format = test_format;
} else {
// Just go with signed 16-bit audio as it's the most compatible
device->spec.format = SDL_AUDIO_S16SYS;
device->spec.format = SDL_AUDIO_S16;
}
// Update the fragment size as size in bytes
@ -638,7 +638,7 @@ static void openslES_WaitDevice(SDL_AudioDevice *device)
SDL_WaitSemaphore(audiodata->playsem);
}
static void openslES_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, int buflen)
static int openslES_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, int buflen)
{
struct SDL_PrivateAudioData *audiodata = device->hidden;
@ -657,6 +657,8 @@ static void openslES_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, in
if (SL_RESULT_SUCCESS != result) {
SDL_PostSemaphore(audiodata->playsem);
}
return 0;
}
/// n playn sem

View File

@ -898,22 +898,22 @@ static void initialize_spa_info(const SDL_AudioSpec *spec, struct spa_audio_info
case SDL_AUDIO_S8:
info->format = SPA_AUDIO_FORMAT_S8;
break;
case SDL_AUDIO_S16LSB:
case SDL_AUDIO_S16LE:
info->format = SPA_AUDIO_FORMAT_S16_LE;
break;
case SDL_AUDIO_S16MSB:
case SDL_AUDIO_S16BE:
info->format = SPA_AUDIO_FORMAT_S16_BE;
break;
case SDL_AUDIO_S32LSB:
case SDL_AUDIO_S32LE:
info->format = SPA_AUDIO_FORMAT_S32_LE;
break;
case SDL_AUDIO_S32MSB:
case SDL_AUDIO_S32BE:
info->format = SPA_AUDIO_FORMAT_S32_BE;
break;
case SDL_AUDIO_F32LSB:
case SDL_AUDIO_F32LE:
info->format = SPA_AUDIO_FORMAT_F32_LE;
break;
case SDL_AUDIO_F32MSB:
case SDL_AUDIO_F32BE:
info->format = SPA_AUDIO_FORMAT_F32_BE;
break;
}
@ -940,7 +940,7 @@ static Uint8 *PIPEWIRE_GetDeviceBuf(SDL_AudioDevice *device, int *buffer_size)
return (Uint8 *) spa_buf->datas[0].data;
}
static void PIPEWIRE_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, int buffer_size)
static int PIPEWIRE_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, int buffer_size)
{
struct pw_stream *stream = device->hidden->stream;
struct pw_buffer *pw_buf = device->hidden->pw_buf;
@ -951,6 +951,8 @@ static void PIPEWIRE_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, in
PIPEWIRE_pw_stream_queue_buffer(stream, pw_buf);
device->hidden->pw_buf = NULL;
return 0;
}
static void output_callback(void *data)
@ -1106,7 +1108,7 @@ static int PIPEWIRE_OpenDevice(SDL_AudioDevice *device)
}
/* Size of a single audio frame in bytes */
priv->stride = (SDL_AUDIO_BITSIZE(device->spec.format) / 8) * device->spec.channels;
priv->stride = SDL_AUDIO_FRAMESIZE(device->spec);
if (device->sample_frames < min_period) {
device->sample_frames = min_period;

View File

@ -85,9 +85,10 @@ static int PS2AUDIO_OpenDevice(SDL_AudioDevice *device)
return 0;
}
static void PS2AUDIO_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, int buflen)
static int PS2AUDIO_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, int buflen)
{
audsrv_play_audio((char *)buffer, buflen);
// this returns number of bytes accepted or a negative error. We assume anything other than buflen is a fatal error.
return (audsrv_play_audio((char *)buffer, buflen) != buflen) ? -1 : 0;
}
static void PS2AUDIO_WaitDevice(SDL_AudioDevice *device)

View File

@ -47,7 +47,7 @@ static int PSPAUDIO_OpenDevice(SDL_AudioDevice *device)
}
// device only natively supports S16LSB
device->spec.format = SDL_AUDIO_S16LSB;
device->spec.format = SDL_AUDIO_S16LE;
/* PSP has some limitations with the Audio. It fully supports 44.1KHz (Mono & Stereo),
however with frequencies different than 44.1KHz, it just supports Stereo,
@ -106,14 +106,16 @@ static int PSPAUDIO_OpenDevice(SDL_AudioDevice *device)
return 0;
}
static void PSPAUDIO_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, int buflen)
static int PSPAUDIO_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, int buflen)
{
int rc;
if (!isBasicAudioConfig(&device->spec)) {
SDL_assert(device->spec.channels == 2);
sceAudioSRCOutputBlocking(PSP_AUDIO_VOLUME_MAX, (void *) buffer);
rc = sceAudioSRCOutputBlocking(PSP_AUDIO_VOLUME_MAX, (void *) buffer);
} else {
sceAudioOutputPannedBlocking(device->hidden->channel, PSP_AUDIO_VOLUME_MAX, PSP_AUDIO_VOLUME_MAX, (void *) buffer);
rc = sceAudioOutputPannedBlocking(device->hidden->channel, PSP_AUDIO_VOLUME_MAX, PSP_AUDIO_VOLUME_MAX, (void *) buffer);
}
return (rc == 0) ? 0 : -1;
}
static void PSPAUDIO_WaitDevice(SDL_AudioDevice *device)

View File

@ -388,7 +388,7 @@ static void PULSEAUDIO_WaitDevice(SDL_AudioDevice *device)
PULSEAUDIO_pa_threaded_mainloop_unlock(pulseaudio_threaded_mainloop);
}
static void PULSEAUDIO_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, int buffer_size)
static int PULSEAUDIO_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, int buffer_size)
{
struct SDL_PrivateAudioData *h = device->hidden;
@ -401,14 +401,14 @@ static void PULSEAUDIO_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer,
PULSEAUDIO_pa_threaded_mainloop_unlock(pulseaudio_threaded_mainloop);
if (rc < 0) {
SDL_AudioDeviceDisconnected(device);
return;
return -1;
}
/*printf("PULSEAUDIO FEED! nbytes=%d\n", buffer_size);*/
h->bytes_requested -= buffer_size;
/*printf("PULSEAUDIO PLAYDEVICE END! written=%d\n", written);*/
return 0;
}
static Uint8 *PULSEAUDIO_GetDeviceBuf(SDL_AudioDevice *device, int *buffer_size)
@ -606,22 +606,22 @@ static int PULSEAUDIO_OpenDevice(SDL_AudioDevice *device)
case SDL_AUDIO_U8:
format = PA_SAMPLE_U8;
break;
case SDL_AUDIO_S16LSB:
case SDL_AUDIO_S16LE:
format = PA_SAMPLE_S16LE;
break;
case SDL_AUDIO_S16MSB:
case SDL_AUDIO_S16BE:
format = PA_SAMPLE_S16BE;
break;
case SDL_AUDIO_S32LSB:
case SDL_AUDIO_S32LE:
format = PA_SAMPLE_S32LE;
break;
case SDL_AUDIO_S32MSB:
case SDL_AUDIO_S32BE:
format = PA_SAMPLE_S32BE;
break;
case SDL_AUDIO_F32LSB:
case SDL_AUDIO_F32LE:
format = PA_SAMPLE_FLOAT32LE;
break;
case SDL_AUDIO_F32MSB:
case SDL_AUDIO_F32BE:
format = PA_SAMPLE_FLOAT32BE;
break;
default:
@ -723,17 +723,17 @@ static SDL_AudioFormat PulseFormatToSDLFormat(pa_sample_format_t format)
case PA_SAMPLE_U8:
return SDL_AUDIO_U8;
case PA_SAMPLE_S16LE:
return SDL_AUDIO_S16LSB;
return SDL_AUDIO_S16LE;
case PA_SAMPLE_S16BE:
return SDL_AUDIO_S16MSB;
return SDL_AUDIO_S16BE;
case PA_SAMPLE_S32LE:
return SDL_AUDIO_S32LSB;
return SDL_AUDIO_S32LE;
case PA_SAMPLE_S32BE:
return SDL_AUDIO_S32MSB;
return SDL_AUDIO_S32BE;
case PA_SAMPLE_FLOAT32LE:
return SDL_AUDIO_F32LSB;
return SDL_AUDIO_F32LE;
case PA_SAMPLE_FLOAT32BE:
return SDL_AUDIO_F32MSB;
return SDL_AUDIO_F32BE;
default:
return 0;
}

View File

@ -110,10 +110,10 @@ static void QSA_WaitDevice(SDL_AudioDevice *device)
}
}
static void QSA_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, int buflen)
static int QSA_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, int buflen)
{
if (SDL_AtomicGet(&device->shutdown) || !device->hidden) {
return;
return 0;
}
int towrite = buflen;
@ -125,7 +125,7 @@ static void QSA_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, int buf
// Check if samples playback got stuck somewhere in hardware or in the audio device driver
if ((errno == EAGAIN) && (bw == 0)) {
if (device->hidden->timeout_on_wait) {
return; // oh well, try again next time. !!! FIXME: Should we just disconnect the device in this case?
return 0; // oh well, try again next time. !!! FIXME: Should we just disconnect the device in this case?
}
}
@ -145,17 +145,17 @@ static void QSA_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, int buf
int status = snd_pcm_plugin_status(device->hidden->audio_handle, &cstatus);
if (status < 0) {
QSA_SetError("snd_pcm_plugin_status", status);
return; // !!! FIXME: disconnect the device?
return -1;
} else if ((cstatus.status == SND_PCM_STATUS_UNDERRUN) || (cstatus.status == SND_PCM_STATUS_READY)) {
status = snd_pcm_plugin_prepare(device->hidden->audio_handle, device->iscapture ? SND_PCM_CHANNEL_CAPTURE : SND_PCM_CHANNEL_PLAYBACK);
if (status < 0) {
QSA_SetError("snd_pcm_plugin_prepare", status);
return; // !!! FIXME: disconnect the device?
return -1;
}
}
continue;
} else {
return; // !!! FIXME: disconnect the device?
return -1;
}
} else {
// we wrote all remaining data
@ -165,9 +165,7 @@ static void QSA_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, int buf
}
// If we couldn't write, assume fatal error for now
if (towrite != 0) {
SDL_AudioDeviceDisconnected(device);
}
return (towrite != 0) ? -1 : 0;
}
static Uint8 *QSA_GetDeviceBuf(SDL_AudioDevice *device, int *buffer_size)
@ -311,7 +309,7 @@ static SDL_AudioFormat QnxFormatToSDLFormat(const int32_t qnxfmt)
#undef CHECKFMT
default: break;
}
return SDL_AUDIO_S16SYS; // oh well.
return SDL_AUDIO_S16; // oh well.
}
static void QSA_DetectDevices(SDL_AudioDevice **default_output, SDL_AudioDevice **default_capture)

View File

@ -175,16 +175,17 @@ static void SNDIO_WaitDevice(SDL_AudioDevice *device)
}
}
static void SNDIO_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, int buflen)
static int SNDIO_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, int buflen)
{
// !!! FIXME: this should be non-blocking so we can check device->shutdown.
// this is set to blocking, because we _have_ to send the entire buffer down, but hopefully WaitDevice took most of the delay time.
if (SNDIO_sio_write(device->hidden->dev, buffer, buflen) != buflen) {
SDL_AudioDeviceDisconnected(device); // If we couldn't write, assume fatal error for now
return -1; // If we couldn't write, assume fatal error for now
}
#ifdef DEBUG_AUDIO
fprintf(stderr, "Wrote %d bytes of audio data\n", written);
#endif
return 0;
}
static int SNDIO_CaptureFromDevice(SDL_AudioDevice *device, void *buffer, int buflen)
@ -283,13 +284,13 @@ static int SNDIO_OpenDevice(SDL_AudioDevice *device)
}
if ((par.bps == 4) && (par.sig) && (par.le)) {
device->spec.format = SDL_AUDIO_S32LSB;
device->spec.format = SDL_AUDIO_S32LE;
} else if ((par.bps == 4) && (par.sig) && (!par.le)) {
device->spec.format = SDL_AUDIO_S32MSB;
device->spec.format = SDL_AUDIO_S32BE;
} else if ((par.bps == 2) && (par.sig) && (par.le)) {
device->spec.format = SDL_AUDIO_S16LSB;
device->spec.format = SDL_AUDIO_S16LE;
} else if ((par.bps == 2) && (par.sig) && (!par.le)) {
device->spec.format = SDL_AUDIO_S16MSB;
device->spec.format = SDL_AUDIO_S16BE;
} else if ((par.bps == 1) && (par.sig)) {
device->spec.format = SDL_AUDIO_S8;
} else if ((par.bps == 1) && (!par.sig)) {

View File

@ -71,7 +71,7 @@ static int VITAAUD_OpenDevice(SDL_AudioDevice *device)
closefmts = SDL_ClosestAudioFormats(device->spec.format);
while ((test_format = *(closefmts++)) != 0) {
if (test_format == SDL_AUDIO_S16LSB) {
if (test_format == SDL_AUDIO_S16LE) {
device->spec.format = test_format;
break;
}
@ -130,9 +130,9 @@ static int VITAAUD_OpenDevice(SDL_AudioDevice *device)
return 0;
}
static void VITAAUD_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, int buffer_size)
static int VITAAUD_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, int buffer_size)
{
sceAudioOutOutput(device->hidden->port, buffer);
return (sceAudioOutOutput(device->hidden->port, buffer) == 0) ? 0 : -1;
}
// This function waits until it is possible to write a full sound buffer

View File

@ -403,22 +403,22 @@ static Uint8 *WASAPI_GetDeviceBuf(SDL_AudioDevice *device, int *buffer_size)
// get an endpoint buffer from WASAPI.
BYTE *buffer = NULL;
while (RecoverWasapiIfLost(device) && device->hidden->render) {
if (!WasapiFailed(device, IAudioRenderClient_GetBuffer(device->hidden->render, device->sample_frames, &buffer))) {
return (Uint8 *)buffer;
if (RecoverWasapiIfLost(device) && device->hidden->render) {
if (WasapiFailed(device, IAudioRenderClient_GetBuffer(device->hidden->render, device->sample_frames, &buffer))) {
SDL_assert(buffer == NULL);
}
SDL_assert(buffer == NULL);
}
return (Uint8 *)buffer;
}
static void WASAPI_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, int buflen)
static int WASAPI_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, int buflen)
{
if (device->hidden->render != NULL) { // definitely activated?
// WasapiFailed() will mark the device for reacquisition or removal elsewhere.
WasapiFailed(device, IAudioRenderClient_ReleaseBuffer(device->hidden->render, device->sample_frames, 0));
}
return 0;
}
static void WASAPI_WaitDevice(SDL_AudioDevice *device)
@ -620,7 +620,7 @@ static int mgmtthrtask_PrepDevice(void *userdata)
return -1;
}
device->hidden->framesize = (SDL_AUDIO_BITSIZE(device->spec.format) / 8) * device->spec.channels;
device->hidden->framesize = SDL_AUDIO_FRAMESIZE(device->spec);
if (device->iscapture) {
IAudioCaptureClient *capture = NULL;

View File

@ -214,3 +214,23 @@ SDL_GDKSuspendComplete()
SetEvent(plmSuspendComplete);
}
}
extern "C" DECLSPEC int
SDL_GDKGetDefaultUser(XUserHandle *outUserHandle)
{
XAsyncBlock block = { 0 };
HRESULT result;
if (FAILED(result = XUserAddAsync(XUserAddOptions::AddDefaultUserAllowingUI, &block))) {
return WIN_SetErrorFromHRESULT("XUserAddAsync", result);
}
do {
result = XUserAddResult(&block, outUserHandle);
} while (result == E_PENDING);
if (FAILED(result)) {
return WIN_SetErrorFromHRESULT("XUserAddResult", result);
}
return 0;
}

View File

@ -565,4 +565,70 @@ char *SDL_DBus_GetLocalMachineId(void)
return NULL;
}
/*
* Convert file drops with mime type "application/vnd.portal.filetransfer" to file paths
* Result must be freed with dbus->free_string_array().
* https://flatpak.github.io/xdg-desktop-portal/#gdbus-method-org-freedesktop-portal-FileTransfer.RetrieveFiles
*/
char **SDL_DBus_DocumentsPortalRetrieveFiles(const char *key, int *path_count)
{
DBusError err;
DBusMessageIter iter, iterDict;
char **paths = NULL;
DBusMessage *reply = NULL;
DBusMessage *msg = dbus.message_new_method_call("org.freedesktop.portal.Documents", /* Node */
"/org/freedesktop/portal/documents", /* Path */
"org.freedesktop.portal.FileTransfer", /* Interface */
"RetrieveFiles"); /* Method */
/* Make sure we have a connection to the dbus session bus */
if (!SDL_DBus_GetContext() || !dbus.session_conn) {
/* We either cannot connect to the session bus or were unable to
* load the D-Bus library at all. */
return NULL;
}
dbus.error_init(&err);
/* First argument is a "application/vnd.portal.filetransfer" key from a DnD or clipboard event */
if (!dbus.message_append_args(msg, DBUS_TYPE_STRING, &key, DBUS_TYPE_INVALID)) {
SDL_OutOfMemory();
dbus.message_unref(msg);
goto failed;
}
/* Second argument is a variant dictionary for options.
* The spec doesn't define any entries yet so it's empty. */
dbus.message_iter_init_append(msg, &iter);
if (!dbus.message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "{sv}", &iterDict) ||
!dbus.message_iter_close_container(&iter, &iterDict)) {
SDL_OutOfMemory();
dbus.message_unref(msg);
goto failed;
}
reply = dbus.connection_send_with_reply_and_block(dbus.session_conn, msg, DBUS_TIMEOUT_USE_DEFAULT, &err);
dbus.message_unref(msg);
if (reply) {
dbus.message_get_args(reply, &err, DBUS_TYPE_ARRAY, DBUS_TYPE_STRING, &paths, path_count, DBUS_TYPE_INVALID);
dbus.message_unref(reply);
}
if (paths) {
return paths;
}
failed:
if (dbus.error_is_set(&err)) {
SDL_SetError("%s: %s", err.name, err.message);
dbus.error_free(&err);
} else {
SDL_SetError("Error retrieving paths for documents portal \"%s\"", key);
}
return NULL;
}
#endif

View File

@ -102,6 +102,8 @@ extern SDL_bool SDL_DBus_ScreensaverInhibit(SDL_bool inhibit);
extern void SDL_DBus_PumpEvents(void);
extern char *SDL_DBus_GetLocalMachineId(void);
extern char **SDL_DBus_DocumentsPortalRetrieveFiles(const char *key, int *files_count);
#endif /* HAVE_DBUS_DBUS_H */
#endif /* SDL_dbus_h_ */

View File

@ -57,8 +57,14 @@ static const PROPERTYKEY SDL_PKEY_AudioEndpoint_GUID = { { 0x1da5d803, 0xd492, 0
static SDL_bool FindByDevIDCallback(SDL_AudioDevice *device, void *userdata)
{
const SDL_IMMDevice_HandleData *handle = (const SDL_IMMDevice_HandleData *) device->handle;
return (SDL_wcscmp(handle->immdevice_id, (LPCWSTR) userdata) == 0) ? SDL_TRUE : SDL_FALSE;
LPCWSTR devid = (LPCWSTR)userdata;
if (devid && device && device->handle) {
const SDL_IMMDevice_HandleData *handle = (const SDL_IMMDevice_HandleData *)device->handle;
if (handle->immdevice_id && SDL_wcscmp(handle->immdevice_id, devid) == 0) {
return SDL_TRUE;
}
}
return SDL_FALSE;
}
static SDL_AudioDevice *SDL_IMMDevice_FindByDevID(LPCWSTR devid)

View File

@ -344,19 +344,19 @@ static const GUID SDL_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT = { 0x00000003, 0x0000, 0x
SDL_AudioFormat SDL_WaveFormatExToSDLFormat(WAVEFORMATEX *waveformat)
{
if ((waveformat->wFormatTag == WAVE_FORMAT_IEEE_FLOAT) && (waveformat->wBitsPerSample == 32)) {
return SDL_AUDIO_F32SYS;
return SDL_AUDIO_F32;
} else if ((waveformat->wFormatTag == WAVE_FORMAT_PCM) && (waveformat->wBitsPerSample == 16)) {
return SDL_AUDIO_S16SYS;
return SDL_AUDIO_S16;
} else if ((waveformat->wFormatTag == WAVE_FORMAT_PCM) && (waveformat->wBitsPerSample == 32)) {
return SDL_AUDIO_S32SYS;
return SDL_AUDIO_S32;
} else if (waveformat->wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
const WAVEFORMATEXTENSIBLE *ext = (const WAVEFORMATEXTENSIBLE *)waveformat;
if ((SDL_memcmp(&ext->SubFormat, &SDL_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, sizeof(GUID)) == 0) && (waveformat->wBitsPerSample == 32)) {
return SDL_AUDIO_F32SYS;
return SDL_AUDIO_F32;
} else if ((SDL_memcmp(&ext->SubFormat, &SDL_KSDATAFORMAT_SUBTYPE_PCM, sizeof(GUID)) == 0) && (waveformat->wBitsPerSample == 16)) {
return SDL_AUDIO_S16SYS;
return SDL_AUDIO_S16;
} else if ((SDL_memcmp(&ext->SubFormat, &SDL_KSDATAFORMAT_SUBTYPE_PCM, sizeof(GUID)) == 0) && (waveformat->wBitsPerSample == 32)) {
return SDL_AUDIO_S32SYS;
return SDL_AUDIO_S32;
}
}
return 0;

View File

@ -172,6 +172,7 @@ SDL3_0.0.0 {
SDL_GetGamepadAppleSFSymbolsNameForButton;
SDL_GetGamepadAxis;
SDL_GetGamepadAxisFromString;
SDL_GetGamepadBindings;
SDL_GetGamepadButton;
SDL_GetGamepadButtonFromString;
SDL_GetGamepadFirmwareVersion;
@ -876,7 +877,7 @@ SDL3_0.0.0 {
SDL_SetAudioStreamGetCallback;
SDL_SetAudioStreamPutCallback;
SDL_DestroyAudioStream;
SDL_CreateAndBindAudioStream;
SDL_OpenAudioDeviceStream;
SDL_LoadWAV_RW;
SDL_LoadWAV;
SDL_MixAudioFormat;
@ -885,8 +886,8 @@ SDL3_0.0.0 {
SDL_LoadWAV;
SDL_PauseAudioDevice;
SDL_ResumeAudioDevice;
SDL_IsAudioDevicePaused;
SDL_GetAudioStreamBinding;
SDL_AudioDevicePaused;
SDL_GetAudioStreamDevice;
SDL_ShowWindowSystemMenu;
SDL_ReadS16LE;
SDL_ReadS16BE;
@ -899,6 +900,13 @@ SDL3_0.0.0 {
SDL_WriteS32LE;
SDL_WriteS32BE;
SDL_WriteS64LE;
SDL_WriteS64BE;
SDL_GDKGetDefaultUser;
SDL_SetWindowFocusable;
SDL_GetAudioStreamFrequencyRatio;
SDL_SetAudioStreamFrequencyRatio;
SDL_SetAudioPostmixCallback;
SDL_GetAudioStreamQueued;
# extra symbols go here (don't modify this line)
local: *;
};

View File

@ -196,6 +196,7 @@
#define SDL_GetGamepadAppleSFSymbolsNameForButton SDL_GetGamepadAppleSFSymbolsNameForButton_REAL
#define SDL_GetGamepadAxis SDL_GetGamepadAxis_REAL
#define SDL_GetGamepadAxisFromString SDL_GetGamepadAxisFromString_REAL
#define SDL_GetGamepadBindings SDL_GetGamepadBindings_REAL
#define SDL_GetGamepadButton SDL_GetGamepadButton_REAL
#define SDL_GetGamepadButtonFromString SDL_GetGamepadButtonFromString_REAL
#define SDL_GetGamepadFirmwareVersion SDL_GetGamepadFirmwareVersion_REAL
@ -901,7 +902,7 @@
#define SDL_SetAudioStreamGetCallback SDL_SetAudioStreamGetCallback_REAL
#define SDL_SetAudioStreamPutCallback SDL_SetAudioStreamPutCallback_REAL
#define SDL_DestroyAudioStream SDL_DestroyAudioStream_REAL
#define SDL_CreateAndBindAudioStream SDL_CreateAndBindAudioStream_REAL
#define SDL_OpenAudioDeviceStream SDL_OpenAudioDeviceStream_REAL
#define SDL_LoadWAV_RW SDL_LoadWAV_RW_REAL
#define SDL_LoadWAV SDL_LoadWAV_REAL
#define SDL_MixAudioFormat SDL_MixAudioFormat_REAL
@ -910,8 +911,8 @@
#define SDL_LoadWAV SDL_LoadWAV_REAL
#define SDL_PauseAudioDevice SDL_PauseAudioDevice_REAL
#define SDL_ResumeAudioDevice SDL_ResumeAudioDevice_REAL
#define SDL_IsAudioDevicePaused SDL_IsAudioDevicePaused_REAL
#define SDL_GetAudioStreamBinding SDL_GetAudioStreamBinding_REAL
#define SDL_AudioDevicePaused SDL_AudioDevicePaused_REAL
#define SDL_GetAudioStreamDevice SDL_GetAudioStreamDevice_REAL
#define SDL_ShowWindowSystemMenu SDL_ShowWindowSystemMenu_REAL
#define SDL_ReadS16LE SDL_ReadS16LE_REAL
#define SDL_ReadS16BE SDL_ReadS16BE_REAL
@ -924,3 +925,10 @@
#define SDL_WriteS32LE SDL_WriteS32LE_REAL
#define SDL_WriteS32BE SDL_WriteS32BE_REAL
#define SDL_WriteS64LE SDL_WriteS64LE_REAL
#define SDL_WriteS64BE SDL_WriteS64BE_REAL
#define SDL_GDKGetDefaultUser SDL_GDKGetDefaultUser_REAL
#define SDL_SetWindowFocusable SDL_SetWindowFocusable_REAL
#define SDL_GetAudioStreamFrequencyRatio SDL_GetAudioStreamFrequencyRatio_REAL
#define SDL_SetAudioStreamFrequencyRatio SDL_SetAudioStreamFrequencyRatio_REAL
#define SDL_SetAudioPostmixCallback SDL_SetAudioPostmixCallback_REAL
#define SDL_GetAudioStreamQueued SDL_GetAudioStreamQueued_REAL

View File

@ -271,6 +271,7 @@ SDL_DYNAPI_PROC(const char*,SDL_GetGamepadAppleSFSymbolsNameForAxis,(SDL_Gamepad
SDL_DYNAPI_PROC(const char*,SDL_GetGamepadAppleSFSymbolsNameForButton,(SDL_Gamepad *a, SDL_GamepadButton b),(a,b),return)
SDL_DYNAPI_PROC(Sint16,SDL_GetGamepadAxis,(SDL_Gamepad *a, SDL_GamepadAxis b),(a,b),return)
SDL_DYNAPI_PROC(SDL_GamepadAxis,SDL_GetGamepadAxisFromString,(const char *a),(a),return)
SDL_DYNAPI_PROC(SDL_GamepadBinding **,SDL_GetGamepadBindings,(SDL_Gamepad *a, int *b),(a,b),return)
SDL_DYNAPI_PROC(Uint8,SDL_GetGamepadButton,(SDL_Gamepad *a, SDL_GamepadButton b),(a,b),return)
SDL_DYNAPI_PROC(SDL_GamepadButton,SDL_GetGamepadButtonFromString,(const char *a),(a),return)
SDL_DYNAPI_PROC(Uint16,SDL_GetGamepadFirmwareVersion,(SDL_Gamepad *a),(a),return)
@ -926,7 +927,7 @@ SDL_DYNAPI_PROC(const char*,SDL_GetCurrentAudioDriver,(void),(),return)
SDL_DYNAPI_PROC(SDL_AudioDeviceID*,SDL_GetAudioOutputDevices,(int *a),(a),return)
SDL_DYNAPI_PROC(SDL_AudioDeviceID*,SDL_GetAudioCaptureDevices,(int *a),(a),return)
SDL_DYNAPI_PROC(char*,SDL_GetAudioDeviceName,(SDL_AudioDeviceID a),(a),return)
SDL_DYNAPI_PROC(int,SDL_GetAudioDeviceFormat,(SDL_AudioDeviceID a, SDL_AudioSpec *b),(a,b),return)
SDL_DYNAPI_PROC(int,SDL_GetAudioDeviceFormat,(SDL_AudioDeviceID a, SDL_AudioSpec *b, int *c),(a,b,c),return)
SDL_DYNAPI_PROC(SDL_AudioDeviceID,SDL_OpenAudioDevice,(SDL_AudioDeviceID a, const SDL_AudioSpec *b),(a,b),return)
SDL_DYNAPI_PROC(void,SDL_CloseAudioDevice,(SDL_AudioDeviceID a),(a),)
SDL_DYNAPI_PROC(int,SDL_BindAudioStreams,(SDL_AudioDeviceID a, SDL_AudioStream **b, int c),(a,b,c),return)
@ -943,10 +944,10 @@ SDL_DYNAPI_PROC(int,SDL_FlushAudioStream,(SDL_AudioStream *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_ClearAudioStream,(SDL_AudioStream *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_LockAudioStream,(SDL_AudioStream *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_UnlockAudioStream,(SDL_AudioStream *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_SetAudioStreamGetCallback,(SDL_AudioStream *a, SDL_AudioStreamRequestCallback b, void *c),(a,b,c),return)
SDL_DYNAPI_PROC(int,SDL_SetAudioStreamPutCallback,(SDL_AudioStream *a, SDL_AudioStreamRequestCallback b, void *c),(a,b,c),return)
SDL_DYNAPI_PROC(int,SDL_SetAudioStreamGetCallback,(SDL_AudioStream *a, SDL_AudioStreamCallback b, void *c),(a,b,c),return)
SDL_DYNAPI_PROC(int,SDL_SetAudioStreamPutCallback,(SDL_AudioStream *a, SDL_AudioStreamCallback b, void *c),(a,b,c),return)
SDL_DYNAPI_PROC(void,SDL_DestroyAudioStream,(SDL_AudioStream *a),(a),)
SDL_DYNAPI_PROC(SDL_AudioStream*,SDL_CreateAndBindAudioStream,(SDL_AudioDeviceID a, const SDL_AudioSpec *b),(a,b),return)
SDL_DYNAPI_PROC(SDL_AudioStream*,SDL_OpenAudioDeviceStream,(SDL_AudioDeviceID a, const SDL_AudioSpec *b, SDL_AudioStreamCallback c, void *d),(a,b,c,d),return)
SDL_DYNAPI_PROC(int,SDL_LoadWAV_RW,(SDL_RWops *a, SDL_bool b, SDL_AudioSpec *c, Uint8 **d, Uint32 *e),(a,b,c,d,e),return)
SDL_DYNAPI_PROC(int,SDL_MixAudioFormat,(Uint8 *a, const Uint8 *b, SDL_AudioFormat c, Uint32 d, int e),(a,b,c,d,e),return)
SDL_DYNAPI_PROC(int,SDL_ConvertAudioSamples,(const SDL_AudioSpec *a, const Uint8 *b, int c, const SDL_AudioSpec *d, Uint8 **e, int *f),(a,b,c,d,e,f),return)
@ -954,8 +955,8 @@ SDL_DYNAPI_PROC(int,SDL_GetSilenceValueForFormat,(SDL_AudioFormat a),(a),return)
SDL_DYNAPI_PROC(int,SDL_LoadWAV,(const char *a, SDL_AudioSpec *b, Uint8 **c, Uint32 *d),(a,b,c,d),return)
SDL_DYNAPI_PROC(int,SDL_PauseAudioDevice,(SDL_AudioDeviceID a),(a),return)
SDL_DYNAPI_PROC(int,SDL_ResumeAudioDevice,(SDL_AudioDeviceID a),(a),return)
SDL_DYNAPI_PROC(SDL_bool,SDL_IsAudioDevicePaused,(SDL_AudioDeviceID a),(a),return)
SDL_DYNAPI_PROC(SDL_AudioDeviceID,SDL_GetAudioStreamBinding,(SDL_AudioStream *a),(a),return)
SDL_DYNAPI_PROC(SDL_bool,SDL_AudioDevicePaused,(SDL_AudioDeviceID a),(a),return)
SDL_DYNAPI_PROC(SDL_AudioDeviceID,SDL_GetAudioStreamDevice,(SDL_AudioStream *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_ShowWindowSystemMenu,(SDL_Window *a, int b, int c),(a,b,c),return)
SDL_DYNAPI_PROC(SDL_bool,SDL_ReadS16LE,(SDL_RWops *a, Sint16 *b),(a,b),return)
SDL_DYNAPI_PROC(SDL_bool,SDL_ReadS16BE,(SDL_RWops *a, Sint16 *b),(a,b),return)
@ -968,3 +969,12 @@ SDL_DYNAPI_PROC(SDL_bool,SDL_WriteS16BE,(SDL_RWops *a, Sint16 b),(a,b),return)
SDL_DYNAPI_PROC(SDL_bool,SDL_WriteS32LE,(SDL_RWops *a, Sint32 b),(a,b),return)
SDL_DYNAPI_PROC(SDL_bool,SDL_WriteS32BE,(SDL_RWops *a, Sint32 b),(a,b),return)
SDL_DYNAPI_PROC(SDL_bool,SDL_WriteS64LE,(SDL_RWops *a, Sint64 b),(a,b),return)
SDL_DYNAPI_PROC(SDL_bool,SDL_WriteS64BE,(SDL_RWops *a, Sint64 b),(a,b),return)
#ifdef __GDK__
SDL_DYNAPI_PROC(int,SDL_GDKGetDefaultUser,(XUserHandle *a),(a),return)
#endif
SDL_DYNAPI_PROC(int,SDL_SetWindowFocusable,(SDL_Window *a, SDL_bool b),(a,b),return)
SDL_DYNAPI_PROC(float,SDL_GetAudioStreamFrequencyRatio,(SDL_AudioStream *a),(a),return)
SDL_DYNAPI_PROC(int,SDL_SetAudioStreamFrequencyRatio,(SDL_AudioStream *a, float b),(a,b),return)
SDL_DYNAPI_PROC(int,SDL_SetAudioPostmixCallback,(SDL_AudioDeviceID a, SDL_AudioPostmixCallback b, void *c),(a,b,c),return)
SDL_DYNAPI_PROC(int,SDL_GetAudioStreamQueued,(SDL_AudioStream *a),(a),return)

View File

@ -418,7 +418,7 @@ static void SDL_LogEvent(const SDL_Event *event)
break;
#undef PRINT_FINGER_EVENT
#define PRINT_DROP_EVENT(event) (void)SDL_snprintf(details, sizeof(details), " (file='%s' timestamp=%u windowid=%u)", event->drop.file, (uint)event->drop.timestamp, (uint)event->drop.windowID)
#define PRINT_DROP_EVENT(event) (void)SDL_snprintf(details, sizeof(details), " (file='%s' timestamp=%u windowid=%u x=%f y=%f)", event->drop.file, (uint)event->drop.timestamp, (uint)event->drop.windowID, event->drop.x, event->drop.y)
SDL_EVENT_CASE(SDL_EVENT_DROP_FILE)
PRINT_DROP_EVENT(event);
break;
@ -431,6 +431,9 @@ static void SDL_LogEvent(const SDL_Event *event)
SDL_EVENT_CASE(SDL_EVENT_DROP_COMPLETE)
PRINT_DROP_EVENT(event);
break;
SDL_EVENT_CASE(SDL_EVENT_DROP_POSITION)
PRINT_DROP_EVENT(event);
break;
#undef PRINT_DROP_EVENT
#define PRINT_AUDIODEV_EVENT(event) (void)SDL_snprintf(details, sizeof(details), " (timestamp=%u which=%u iscapture=%s)", (uint)event->adevice.timestamp, (uint)event->adevice.which, event->adevice.iscapture ? "true" : "false")
@ -440,6 +443,9 @@ static void SDL_LogEvent(const SDL_Event *event)
SDL_EVENT_CASE(SDL_EVENT_AUDIO_DEVICE_REMOVED)
PRINT_AUDIODEV_EVENT(event);
break;
SDL_EVENT_CASE(SDL_EVENT_AUDIO_DEVICE_FORMAT_CHANGED)
PRINT_AUDIODEV_EVENT(event);
break;
#undef PRINT_AUDIODEV_EVENT
SDL_EVENT_CASE(SDL_EVENT_SENSOR_UPDATE)

View File

@ -233,13 +233,31 @@ void SDL_SetDefaultCursor(SDL_Cursor *cursor)
if (mouse->def_cursor) {
SDL_Cursor *default_cursor = mouse->def_cursor;
SDL_Cursor *prev, *curr;
if (mouse->cur_cursor == mouse->def_cursor) {
mouse->cur_cursor = NULL;
}
mouse->def_cursor = NULL;
SDL_DestroyCursor(default_cursor);
for (prev = NULL, curr = mouse->cursors; curr;
prev = curr, curr = curr->next) {
if (curr == default_cursor) {
if (prev) {
prev->next = curr->next;
} else {
mouse->cursors = curr->next;
}
break;
}
}
if (mouse->FreeCursor && default_cursor->driverdata) {
mouse->FreeCursor(default_cursor);
} else {
SDL_free(default_cursor);
}
}
mouse->def_cursor = cursor;
@ -591,6 +609,13 @@ static int SDL_PrivateSendMouseMotion(Uint64 timestamp, SDL_Window *window, SDL_
}
}
if (mouse->has_position && xrel == 0.0f && yrel == 0.0f) { /* Drop events that don't change state */
#ifdef DEBUG_MOUSE
SDL_Log("Mouse event didn't change state - dropped!\n");
#endif
return 0;
}
/* Ignore relative motion positioning the first touch */
if (mouseID == SDL_TOUCH_MOUSEID && !GetButtonState(mouse, SDL_TRUE)) {
xrel = 0.0f;
@ -598,13 +623,6 @@ static int SDL_PrivateSendMouseMotion(Uint64 timestamp, SDL_Window *window, SDL_
}
if (mouse->has_position) {
if (xrel == 0.0f && yrel == 0.0f) { /* Drop events that don't change state */
#ifdef DEBUG_MOUSE
SDL_Log("Mouse event didn't change state - dropped!\n");
#endif
return 0;
}
/* Update internal mouse coordinates */
if (!mouse->relative_mode) {
mouse->x = x;

View File

@ -3,7 +3,7 @@
/*
Copyright (C) 2003-2006,2008 Jamey Sharp, Josh Triplett
Copyright © 2009 Red Hat, Inc.
Copyright © 2009 Red Hat, Inc.
Copyright 1990-1992,1999,2000,2004,2009,2010 Oracle and/or its affiliates.
All rights reserved.

View File

@ -0,0 +1,140 @@
/*
Simple DirectMedia Layer
Copyright (C) 1997-2023 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "../../SDL_internal.h"
#ifdef SDL_FILESYSTEM_XBOX
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* System dependent filesystem routines */
#include "../../core/windows/SDL_windows.h"
#include "SDL_hints.h"
#include "SDL_system.h"
#include "SDL_filesystem.h"
#include <XGameSaveFiles.h>
char *
SDL_GetBasePath(void)
{
/* NOTE: This function is a UTF8 version of the Win32 SDL_GetBasePath()!
* The GDK actually _recommends_ the 'A' functions over the 'W' functions :o
*/
DWORD buflen = 128;
CHAR *path = NULL;
DWORD len = 0;
int i;
while (SDL_TRUE) {
void *ptr = SDL_realloc(path, buflen * sizeof(CHAR));
if (ptr == NULL) {
SDL_free(path);
SDL_OutOfMemory();
return NULL;
}
path = (CHAR *)ptr;
len = GetModuleFileNameA(NULL, path, buflen);
/* if it truncated, then len >= buflen - 1 */
/* if there was enough room (or failure), len < buflen - 1 */
if (len < buflen - 1) {
break;
}
/* buffer too small? Try again. */
buflen *= 2;
}
if (len == 0) {
SDL_free(path);
WIN_SetError("Couldn't locate our .exe");
return NULL;
}
for (i = len - 1; i > 0; i--) {
if (path[i] == '\\') {
break;
}
}
SDL_assert(i > 0); /* Should have been an absolute path. */
path[i + 1] = '\0'; /* chop off filename. */
return path;
}
char *
SDL_GetPrefPath(const char *org, const char *app)
{
XUserHandle user = NULL;
XAsyncBlock block = { 0 };
char *folderPath;
HRESULT result;
const char *csid = SDL_GetHint("SDL_GDK_SERVICE_CONFIGURATION_ID");
if (app == NULL) {
SDL_InvalidParamError("app");
return NULL;
}
/* This should be set before calling SDL_GetPrefPath! */
if (csid == NULL) {
SDL_LogWarn(SDL_LOG_CATEGORY_SYSTEM, "Set SDL_GDK_SERVICE_CONFIGURATION_ID before calling SDL_GetPrefPath!");
return SDL_strdup("T:\\");
}
if (SDL_GDKGetDefaultUser(&user) < 0) {
/* Error already set, just return */
return NULL;
}
if (FAILED(result = XGameSaveFilesGetFolderWithUiAsync(user, csid, &block))) {
WIN_SetErrorFromHRESULT("XGameSaveFilesGetFolderWithUiAsync", result);
return NULL;
}
folderPath = (char*) SDL_malloc(MAX_PATH);
do {
result = XGameSaveFilesGetFolderWithUiResult(&block, MAX_PATH, folderPath);
} while (result == E_PENDING);
if (FAILED(result)) {
WIN_SetErrorFromHRESULT("XGameSaveFilesGetFolderWithUiResult", result);
SDL_free(folderPath);
return NULL;
}
/* We aren't using 'app' here because the container rules are a lot more
* strict than the NTFS rules, so it will most likely be invalid :(
*/
SDL_strlcat(folderPath, "\\SDLPrefPath\\", MAX_PATH);
if (CreateDirectoryA(folderPath, NULL) == FALSE) {
if (GetLastError() != ERROR_ALREADY_EXISTS) {
WIN_SetError("CreateDirectoryA");
SDL_free(folderPath);
return NULL;
}
}
return folderPath;
}
#endif /* SDL_FILESYSTEM_XBOX */
/* vi: set ts=4 sw=4 expandtab: */

View File

@ -332,23 +332,3 @@ done:
return retval;
}
#endif /* SDL_FILESYSTEM_WINDOWS */
#ifdef SDL_FILESYSTEM_XBOX
char *SDL_GetBasePath(void)
{
SDL_Unsupported();
return NULL;
}
char *SDL_GetPrefPath(const char *org, const char *app)
{
SDL_Unsupported();
return NULL;
}
char *SDL_GetUserFolder(SDL_Folder folder)
{
SDL_Unsupported();
return NULL;
}
#endif /* SDL_FILESYSTEM_XBOX */

View File

@ -873,10 +873,47 @@ typedef struct LIBUSB_hid_device_ LIBUSB_hid_device;
#undef read_thread
#undef return_data
/* If the platform has any backend other than libusb, try to avoid using
* libusb as the main backend for devices, since it detaches drivers and
* therefore makes devices inaccessible to the rest of the OS.
*
* We do this by whitelisting devices we know to be accessible _exclusively_
* via libusb; these are typically devices that look like HIDs but have a
* quirk that requires direct access to the hardware.
*/
static const struct {
Uint16 vendor;
Uint16 product;
} SDL_libusb_whitelist[] = {
{ 0x057e, 0x0337 } /* Nintendo WUP-028, Wii U/Switch GameCube Adapter */
};
static SDL_bool IsInWhitelist(Uint16 vendor, Uint16 product)
{
int i;
for (i = 0; i < SDL_arraysize(SDL_libusb_whitelist); i += 1) {
if (vendor == SDL_libusb_whitelist[i].vendor &&
product == SDL_libusb_whitelist[i].product) {
return SDL_TRUE;
}
}
return SDL_FALSE;
}
#endif /* HAVE_LIBUSB */
#endif /* !SDL_HIDAPI_DISABLED */
#if defined(HAVE_PLATFORM_BACKEND) || defined(HAVE_DRIVER_BACKEND)
/* We have another way to get HID devices, so use the whitelist to get devices where libusb is preferred */
#define SDL_HIDAPI_LIBUSB_WHITELIST_DEFAULT SDL_TRUE
#else
/* libusb is the only way to get HID devices, so don't use the whitelist, get them all */
#define SDL_HIDAPI_LIBUSB_WHITELIST_DEFAULT SDL_FALSE
#endif /* HAVE_PLATFORM_BACKEND || HAVE_DRIVER_BACKEND */
static SDL_bool use_libusb_whitelist = SDL_HIDAPI_LIBUSB_WHITELIST_DEFAULT;
/* Shared HIDAPI Implementation */
struct hidapi_backend
@ -1117,6 +1154,8 @@ int SDL_hid_init(void)
}
#endif
use_libusb_whitelist = SDL_GetHintBoolean("SDL_HIDAPI_LIBUSB_WHITELIST",
SDL_HIDAPI_LIBUSB_WHITELIST_DEFAULT);
#ifdef HAVE_LIBUSB
if (SDL_getenv("SDL_HIDAPI_DISABLE_LIBUSB") != NULL) {
SDL_LogDebug(SDL_LOG_CATEGORY_INPUT,
@ -1280,144 +1319,170 @@ Uint32 SDL_hid_device_change_count(void)
return counter;
}
static void AddDeviceToEnumeration(const char *driver_name, struct hid_device_info *dev, struct SDL_hid_device_info **devs, struct SDL_hid_device_info **last)
{
struct SDL_hid_device_info *new_dev;
#ifdef DEBUG_HIDAPI
SDL_Log("Adding %s device to enumeration: %ls %ls 0x%.4hx/0x%.4hx/%d",
driver_name, dev->manufacturer_string, dev->product_string, dev->vendor_id, dev->product_id, dev->interface_number);
#else
(void)driver_name;
#endif
new_dev = (struct SDL_hid_device_info *)SDL_malloc(sizeof(struct SDL_hid_device_info));
if (new_dev == NULL) {
/* Don't bother returning an error, get as many devices as possible */
return;
}
CopyHIDDeviceInfo(dev, new_dev);
if ((*last) != NULL) {
(*last)->next = new_dev;
} else {
*devs = new_dev;
}
*last = new_dev;
}
#if defined(HAVE_LIBUSB) || defined(HAVE_PLATFORM_BACKEND)
static void RemoveDeviceFromEnumeration(const char *driver_name, struct hid_device_info *dev, struct hid_device_info **devs, void (*free_device_info)(struct hid_device_info *))
{
struct hid_device_info *last = NULL, *curr, *next;
for (curr = *devs; curr; curr = next) {
next = curr->next;
if (dev->vendor_id == curr->vendor_id &&
dev->product_id == curr->product_id &&
(dev->interface_number < 0 || curr->interface_number < 0 || dev->interface_number == curr->interface_number)) {
#ifdef DEBUG_HIDAPI
SDL_Log("Skipping %s device: %ls %ls 0x%.4hx/0x%.4hx/%d",
driver_name, curr->manufacturer_string, curr->product_string, curr->vendor_id, curr->product_id, curr->interface_number);
#else
(void)driver_name;
#endif
if (last) {
last->next = next;
} else {
*devs = next;
}
curr->next = NULL;
free_device_info(curr);
continue;
}
last = curr;
}
}
#endif /* HAVE_LIBUSB || HAVE_PLATFORM_BACKEND */
#ifdef HAVE_LIBUSB
static void RemoveNonWhitelistedDevicesFromEnumeration(struct hid_device_info **devs, void (*free_device_info)(struct hid_device_info *))
{
struct hid_device_info *last = NULL, *curr, *next;
for (curr = *devs; curr; curr = next) {
next = curr->next;
if (!IsInWhitelist(curr->vendor_id, curr->product_id)) {
#ifdef DEBUG_HIDAPI
SDL_Log("Device was not in libusb whitelist, skipping: %ls %ls 0x%.4hx/0x%.4hx/%d",
curr->manufacturer_string, curr->product_string, curr->vendor_id, curr->product_id, curr->interface_number);
#endif
if (last) {
last->next = next;
} else {
*devs = next;
}
curr->next = NULL;
free_device_info(curr);
continue;
}
last = curr;
}
}
#endif /* HAVE_LIBUSB */
struct SDL_hid_device_info *SDL_hid_enumerate(unsigned short vendor_id, unsigned short product_id)
{
#if defined(HAVE_PLATFORM_BACKEND) || defined(HAVE_DRIVER_BACKEND) || defined(HAVE_LIBUSB)
#ifdef HAVE_LIBUSB
struct hid_device_info *usb_devs = NULL;
struct hid_device_info *usb_dev;
#endif
#ifdef HAVE_DRIVER_BACKEND
struct hid_device_info *driver_devs = NULL;
struct hid_device_info *driver_dev;
#endif
#ifdef HAVE_PLATFORM_BACKEND
struct hid_device_info *usb_devs = NULL;
struct hid_device_info *raw_devs = NULL;
struct hid_device_info *raw_dev;
#endif
struct SDL_hid_device_info *devs = NULL, *last = NULL, *new_dev;
struct hid_device_info *dev;
struct SDL_hid_device_info *devs = NULL, *last = NULL;
if (SDL_hidapi_refcount == 0 && SDL_hid_init() != 0) {
return NULL;
}
/* Collect the available devices */
#ifdef HAVE_DRIVER_BACKEND
driver_devs = DRIVER_hid_enumerate(vendor_id, product_id);
#endif
#ifdef HAVE_LIBUSB
if (libusb_ctx.libhandle) {
usb_devs = LIBUSB_hid_enumerate(vendor_id, product_id);
#ifdef DEBUG_HIDAPI
SDL_Log("libusb devices found:");
#endif
for (usb_dev = usb_devs; usb_dev; usb_dev = usb_dev->next) {
new_dev = (struct SDL_hid_device_info *)SDL_malloc(sizeof(struct SDL_hid_device_info));
if (new_dev == NULL) {
LIBUSB_hid_free_enumeration(usb_devs);
SDL_hid_free_enumeration(devs);
SDL_OutOfMemory();
return NULL;
}
CopyHIDDeviceInfo(usb_dev, new_dev);
#ifdef DEBUG_HIDAPI
SDL_Log(" - %ls %ls 0x%.4hx 0x%.4hx",
usb_dev->manufacturer_string, usb_dev->product_string,
usb_dev->vendor_id, usb_dev->product_id);
#endif
if (last != NULL) {
last->next = new_dev;
} else {
devs = new_dev;
}
last = new_dev;
if (use_libusb_whitelist) {
RemoveNonWhitelistedDevicesFromEnumeration(&usb_devs, LIBUSB_hid_free_enumeration);
}
}
#endif /* HAVE_LIBUSB */
#ifdef HAVE_DRIVER_BACKEND
driver_devs = DRIVER_hid_enumerate(vendor_id, product_id);
for (driver_dev = driver_devs; driver_dev; driver_dev = driver_dev->next) {
new_dev = (struct SDL_hid_device_info *)SDL_malloc(sizeof(struct SDL_hid_device_info));
CopyHIDDeviceInfo(driver_dev, new_dev);
if (last != NULL) {
last->next = new_dev;
} else {
devs = new_dev;
}
last = new_dev;
}
#endif /* HAVE_DRIVER_BACKEND */
#ifdef HAVE_PLATFORM_BACKEND
if (udev_ctx) {
raw_devs = PLATFORM_hid_enumerate(vendor_id, product_id);
#ifdef DEBUG_HIDAPI
SDL_Log("hidraw devices found:");
}
#endif
for (raw_dev = raw_devs; raw_dev; raw_dev = raw_dev->next) {
SDL_bool bFound = SDL_FALSE;
#ifdef DEBUG_HIDAPI
SDL_Log(" - %ls %ls 0x%.4hx 0x%.4hx",
raw_dev->manufacturer_string, raw_dev->product_string,
raw_dev->vendor_id, raw_dev->product_id);
#endif
#ifdef HAVE_LIBUSB
for (usb_dev = usb_devs; usb_dev; usb_dev = usb_dev->next) {
if (raw_dev->vendor_id == usb_dev->vendor_id &&
raw_dev->product_id == usb_dev->product_id &&
(raw_dev->interface_number < 0 || raw_dev->interface_number == usb_dev->interface_number)) {
bFound = SDL_TRUE;
break;
}
}
#endif
#ifdef HAVE_DRIVER_BACKEND
for (driver_dev = driver_devs; driver_dev; driver_dev = driver_dev->next) {
if (raw_dev->vendor_id == driver_dev->vendor_id &&
raw_dev->product_id == driver_dev->product_id &&
(raw_dev->interface_number < 0 || raw_dev->interface_number == driver_dev->interface_number)) {
bFound = SDL_TRUE;
break;
}
}
#endif
if (!bFound) {
new_dev = (struct SDL_hid_device_info *)SDL_malloc(sizeof(struct SDL_hid_device_info));
if (new_dev == NULL) {
#ifdef HAVE_LIBUSB
if (libusb_ctx.libhandle) {
LIBUSB_hid_free_enumeration(usb_devs);
}
#endif
PLATFORM_hid_free_enumeration(raw_devs);
SDL_hid_free_enumeration(devs);
SDL_OutOfMemory();
return NULL;
}
CopyHIDDeviceInfo(raw_dev, new_dev);
new_dev->next = NULL;
if (last != NULL) {
last->next = new_dev;
} else {
devs = new_dev;
}
last = new_dev;
}
/* Highest priority are custom driver devices */
for (dev = driver_devs; dev; dev = dev->next) {
AddDeviceToEnumeration("driver", dev, &devs, &last);
#ifdef HAVE_LIBUSB
RemoveDeviceFromEnumeration("libusb", dev, &usb_devs, LIBUSB_hid_free_enumeration);
#endif
#ifdef HAVE_PLATFORM_BACKEND
RemoveDeviceFromEnumeration("raw", dev, &raw_devs, PLATFORM_hid_free_enumeration);
#endif
}
/* If whitelist is in effect, libusb has priority, otherwise raw devices do */
if (use_libusb_whitelist) {
for (dev = usb_devs; dev; dev = dev->next) {
AddDeviceToEnumeration("libusb", dev, &devs, &last);
#ifdef HAVE_PLATFORM_BACKEND
RemoveDeviceFromEnumeration("raw", dev, &raw_devs, PLATFORM_hid_free_enumeration);
#endif
}
PLATFORM_hid_free_enumeration(raw_devs);
}
#endif /* HAVE_PLATFORM_BACKEND */
for (dev = raw_devs; dev; dev = dev->next) {
AddDeviceToEnumeration("platform", dev, &devs, &last);
}
} else {
for (dev = raw_devs; dev; dev = dev->next) {
AddDeviceToEnumeration("raw", dev, &devs, &last);
#ifdef HAVE_LIBUSB
if (libusb_ctx.libhandle) {
LIBUSB_hid_free_enumeration(usb_devs);
}
RemoveDeviceFromEnumeration("libusb", dev, &usb_devs, LIBUSB_hid_free_enumeration);
#endif
return devs;
}
for (dev = usb_devs; dev; dev = dev->next) {
AddDeviceToEnumeration("libusb", dev, &devs, &last);
}
}
#else
return NULL;
#endif /* HAVE_PLATFORM_BACKEND || HAVE_DRIVER_BACKEND || HAVE_LIBUSB */
#ifdef HAVE_DRIVER_BACKEND
DRIVER_hid_free_enumeration(driver_devs);
#endif
#ifdef HAVE_LIBUSB
LIBUSB_hid_free_enumeration(usb_devs);
#endif
#ifdef HAVE_PLATFORM_BACKEND
PLATFORM_hid_free_enumeration(raw_devs);
#endif
return devs;
}
void SDL_hid_free_enumeration(struct SDL_hid_device_info *devs)

View File

@ -23,6 +23,7 @@
/* #pragma push_macro/pop_macro works correctly only as of gcc >= 4.4.3
clang-3.0 _seems_ to be OK. */
#pragma push_macro("calloc")
#pragma push_macro("malloc")
#pragma push_macro("realloc")
#pragma push_macro("free")
@ -38,6 +39,7 @@
#pragma push_macro("tolower")
#pragma push_macro("wcsdup")
#undef calloc
#undef malloc
#undef realloc
#undef free
@ -53,6 +55,7 @@
#undef tolower
#undef wcsdup
#define calloc SDL_calloc
#define malloc SDL_malloc
#define realloc SDL_realloc
#define free SDL_free
@ -106,6 +109,7 @@ static int SDL_libusb_get_string_descriptor(libusb_device_handle *dev,
#undef ICONV_CONST
#undef UNDEF_ICONV_CONST
#endif
#pragma pop_macro("calloc")
#pragma pop_macro("malloc")
#pragma pop_macro("realloc")
#pragma pop_macro("free")

View File

@ -1031,7 +1031,7 @@ extern "C"
int hid_init(void)
{
if ( !g_initialized )
if ( !g_initialized && g_HIDDeviceManagerCallbackHandler )
{
// HIDAPI doesn't work well with Android < 4.3
if (SDL_GetAndroidSDKVersion() >= 18) {
@ -1040,12 +1040,6 @@ int hid_init(void)
g_JVM->AttachCurrentThread( &env, NULL );
pthread_setspecific( g_ThreadKey, (void*)env );
if ( !g_HIDDeviceManagerCallbackHandler )
{
LOGV( "hid_init() without callback handler" );
return -1;
}
// Bluetooth is currently only used for Steam Controllers, so check that hint
// before initializing Bluetooth, which will prompt the user for permission.
bool init_usb = true;

View File

@ -74,7 +74,7 @@ case $host in
backend="mac"
os="darwin"
threads="pthreads"
LIBS="${LIBS} -framework IOKit -framework CoreFoundation -framework AppKit"
LIBS="${LIBS} -framework IOKit -framework CoreFoundation"
;;
*-freebsd*)
AC_MSG_RESULT([ (FreeBSD back-end)])

View File

@ -26,6 +26,6 @@ Pod::Spec.new do |spec|
spec.public_header_files = "hidapi/hidapi.h", "mac/hidapi_darwin.h"
spec.frameworks = "IOKit", "CoreFoundation", "AppKit"
spec.frameworks = "IOKit", "CoreFoundation"
end

View File

@ -259,8 +259,16 @@ static int get_usage(uint8_t *report_descriptor, size_t size,
//printf("Usage Page: %x\n", (uint32_t)*usage_page);
}
if (key_cmd == 0x8) {
*usage = get_bytes(report_descriptor, size, data_len, i);
usage_found = 1;
if (data_len == 4) { /* Usages 5.5 / Usage Page 6.2.2.7 */
*usage_page = get_bytes(report_descriptor, size, 2, i + 2);
usage_page_found = 1;
*usage = get_bytes(report_descriptor, size, 2, i);
usage_found = 1;
}
else {
*usage = get_bytes(report_descriptor, size, data_len, i);
usage_found = 1;
}
//printf("Usage: %x\n", (uint32_t)*usage);
}
@ -1015,6 +1023,7 @@ struct hid_device_info HID_API_EXPORT *hid_enumerate(unsigned short vendor_id,
libusb_close(handle);
handle = NULL;
}
break;
}
} /* altsettings */
} /* interfaces */

View File

@ -206,7 +206,7 @@ static wchar_t *copy_udev_string(struct udev_device *dev, const char *udev_name)
* Returns 1 if successful, 0 if an invalid key
* Sets data_len and key_size when successful
*/
static int get_hid_item_size(__u8 *report_descriptor, unsigned int pos, __u32 size, int *data_len, int *key_size)
static int get_hid_item_size(const __u8 *report_descriptor, __u32 size, unsigned int pos, int *data_len, int *key_size)
{
int key = report_descriptor[pos];
int size_code;
@ -262,7 +262,7 @@ static int get_hid_item_size(__u8 *report_descriptor, unsigned int pos, __u32 si
* Get bytes from a HID Report Descriptor.
* Only call with a num_bytes of 0, 1, 2, or 4.
*/
static __u32 get_hid_report_bytes(__u8 *rpt, size_t len, size_t num_bytes, size_t cur)
static __u32 get_hid_report_bytes(const __u8 *rpt, size_t len, size_t num_bytes, size_t cur)
{
/* Return if there aren't enough bytes. */
if (cur + num_bytes >= len)
@ -285,6 +285,60 @@ static __u32 get_hid_report_bytes(__u8 *rpt, size_t len, size_t num_bytes, size_
return 0;
}
/*
* Iterates until the end of a Collection.
* Assumes that *pos is exactly at the beginning of a Collection.
* Skips all nested Collection, i.e. iterates until the end of current level Collection.
*
* The return value is non-0 when an end of current Collection is found,
* 0 when error is occured (broken Descriptor, end of a Collection is found before its begin,
* or no Collection is found at all).
*/
static int hid_iterate_over_collection(const __u8 *report_descriptor, __u32 size, unsigned int *pos, int *data_len, int *key_size)
{
int collection_level = 0;
while (*pos < size) {
int key = report_descriptor[*pos];
int key_cmd = key & 0xfc;
/* Determine data_len and key_size */
if (!get_hid_item_size(report_descriptor, size, *pos, data_len, key_size))
return 0; /* malformed report */
switch (key_cmd) {
case 0xa0: /* Collection 6.2.2.4 (Main) */
collection_level++;
break;
case 0xc0: /* End Collection 6.2.2.4 (Main) */
collection_level--;
break;
}
if (collection_level < 0) {
/* Broken descriptor or someone is using this function wrong,
* i.e. should be called exactly at the collection start */
return 0;
}
if (collection_level == 0) {
/* Found it!
* Also possible when called not at the collection start, but should not happen if used correctly */
return 1;
}
*pos += *data_len + *key_size;
}
return 0; /* Did not find the end of a Collection */
}
struct hid_usage_iterator {
unsigned int pos;
int usage_page_found;
unsigned short usage_page;
};
/*
* Retrieves the device's Usage Page and Usage from the report descriptor.
* The algorithm returns the current Usage Page/Usage pair whenever a new
@ -302,63 +356,64 @@ static __u32 get_hid_report_bytes(__u8 *rpt, size_t len, size_t num_bytes, size_
* 1 when finished processing descriptor.
* -1 on a malformed report.
*/
static int get_next_hid_usage(__u8 *report_descriptor, __u32 size, unsigned int *pos, unsigned short *usage_page, unsigned short *usage)
static int get_next_hid_usage(const __u8 *report_descriptor, __u32 size, struct hid_usage_iterator *ctx, unsigned short *usage_page, unsigned short *usage)
{
int data_len, key_size;
int initial = *pos == 0; /* Used to handle case where no top-level application collection is defined */
int usage_pair_ready = 0;
int initial = ctx->pos == 0; /* Used to handle case where no top-level application collection is defined */
/* Usage is a Local Item, it must be set before each Main Item (Collection) before a pair is returned */
int usage_found = 0;
while (*pos < size) {
int key = report_descriptor[*pos];
while (ctx->pos < size) {
int key = report_descriptor[ctx->pos];
int key_cmd = key & 0xfc;
/* Determine data_len and key_size */
if (!get_hid_item_size(report_descriptor, *pos, size, &data_len, &key_size))
if (!get_hid_item_size(report_descriptor, size, ctx->pos, &data_len, &key_size))
return -1; /* malformed report */
switch (key_cmd) {
case 0x4: /* Usage Page 6.2.2.7 (Global) */
*usage_page = get_hid_report_bytes(report_descriptor, size, data_len, *pos);
ctx->usage_page = get_hid_report_bytes(report_descriptor, size, data_len, ctx->pos);
ctx->usage_page_found = 1;
break;
case 0x8: /* Usage 6.2.2.8 (Local) */
*usage = get_hid_report_bytes(report_descriptor, size, data_len, *pos);
usage_found = 1;
if (data_len == 4) { /* Usages 5.5 / Usage Page 6.2.2.7 */
ctx->usage_page = get_hid_report_bytes(report_descriptor, size, 2, ctx->pos + 2);
ctx->usage_page_found = 1;
*usage = get_hid_report_bytes(report_descriptor, size, 2, ctx->pos);
usage_found = 1;
}
else {
*usage = get_hid_report_bytes(report_descriptor, size, data_len, ctx->pos);
usage_found = 1;
}
break;
case 0xa0: /* Collection 6.2.2.4 (Main) */
/* A Usage Item (Local) must be found for the pair to be valid */
if (usage_found)
usage_pair_ready = 1;
if (!hid_iterate_over_collection(report_descriptor, size, &ctx->pos, &data_len, &key_size)) {
return -1;
}
/* Usage is a Local Item, unset it */
usage_found = 0;
break;
/* A pair is valid - to be reported when Collection is found */
if (usage_found && ctx->usage_page_found) {
*usage_page = ctx->usage_page;
return 0;
}
case 0x80: /* Input 6.2.2.4 (Main) */
case 0x90: /* Output 6.2.2.4 (Main) */
case 0xb0: /* Feature 6.2.2.4 (Main) */
case 0xc0: /* End Collection 6.2.2.4 (Main) */
/* Usage is a Local Item, unset it */
usage_found = 0;
break;
}
/* Skip over this key and its associated data */
*pos += data_len + key_size;
/* Return usage pair */
if (usage_pair_ready)
return 0;
ctx->pos += data_len + key_size;
}
/* If no top-level application collection is found and usage page/usage pair is found, pair is valid
https://docs.microsoft.com/en-us/windows-hardware/drivers/hid/top-level-collections */
if (initial && usage_found)
return 0; /* success */
if (initial && usage_found && ctx->usage_page_found) {
*usage_page = ctx->usage_page;
return 0; /* success */
}
return 1; /* finished processing */
}
@ -804,12 +859,14 @@ static struct hid_device_info * create_device_info_for_device(struct udev_device
result = get_hid_report_descriptor_from_sysfs(sysfs_path, &report_desc);
if (result >= 0) {
unsigned short page = 0, usage = 0;
unsigned int pos = 0;
struct hid_usage_iterator usage_iterator;
memset(&usage_iterator, 0, sizeof(usage_iterator));
/*
* Parse the first usage and usage page
* out of the report descriptor.
*/
if (!get_next_hid_usage(report_desc.value, report_desc.size, &pos, &page, &usage)) {
if (!get_next_hid_usage(report_desc.value, report_desc.size, &usage_iterator, &page, &usage)) {
cur_dev->usage_page = page;
cur_dev->usage = usage;
}
@ -818,7 +875,7 @@ static struct hid_device_info * create_device_info_for_device(struct udev_device
* Parse any additional usage and usage pages
* out of the report descriptor.
*/
while (!get_next_hid_usage(report_desc.value, report_desc.size, &pos, &page, &usage)) {
while (!get_next_hid_usage(report_desc.value, report_desc.size, &usage_iterator, &page, &usage)) {
/* Create new record for additional usage pairs */
struct hid_device_info *tmp = (struct hid_device_info*) calloc(1, sizeof(struct hid_device_info));
struct hid_device_info *prev_dev = cur_dev;
@ -980,9 +1037,10 @@ struct hid_device_info HID_API_EXPORT *hid_enumerate(unsigned short vendor_id,
struct hidraw_report_descriptor report_desc;
unsigned short page = 0, usage = 0;
unsigned int pos = 0;
if (get_hid_report_descriptor_from_sysfs(sysfs_path, &report_desc) >= 0) {
get_next_hid_usage(report_desc.value, report_desc.size, &pos, &page, &usage);
struct hid_usage_iterator usage_iterator;
memset(&usage_iterator, 0, sizeof(usage_iterator));
get_next_hid_usage(report_desc.value, report_desc.size, &usage_iterator, &page, &usage);
}
if (HIDAPI_IGNORE_DEVICE(bus_type, dev_vid, dev_pid, page, usage)) {
continue;

Some files were not shown because too many files have changed in this diff Show More