SDL: reverted sndio backend removal.

From 7df102d220ff4dc46988de2efb88ecdfbca7cf87 Mon Sep 17 00:00:00 2001
From: Ozkan Sezer <[EMAIL REDACTED]>
Date: Tue, 22 Nov 2022 22:04:10 +0300
Subject: [PATCH] reverted sndio backend removal.

---
 CMakeLists.txt                   |   3 +
 cmake/sdlchecks.cmake            |  29 +++
 configure                        | 133 +++++++++++
 configure.ac                     |  38 +++
 include/SDL_config.h.cmake       |   2 +
 include/SDL_config.h.in          |   2 +
 src/audio/SDL_audio.c            |   3 +
 src/audio/SDL_sysaudio.h         |   1 +
 src/audio/sndio/SDL_sndioaudio.c | 387 +++++++++++++++++++++++++++++++
 src/audio/sndio/SDL_sndioaudio.h |  49 ++++
 10 files changed, 647 insertions(+)
 create mode 100644 src/audio/sndio/SDL_sndioaudio.c
 create mode 100644 src/audio/sndio/SDL_sndioaudio.h

diff --git a/CMakeLists.txt b/CMakeLists.txt
index 1891154b5660..3aeeae1ee2de 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -462,6 +462,8 @@ set_option(SDL_PIPEWIRE            "Use Pipewire audio" ${UNIX_SYS})
 dep_option(SDL_PIPEWIRE_SHARED     "Dynamically load Pipewire support" ON "SDL_PIPEWIRE" OFF)
 set_option(SDL_PULSEAUDIO          "Use PulseAudio" ${UNIX_SYS})
 dep_option(SDL_PULSEAUDIO_SHARED   "Dynamically load PulseAudio support" ON "SDL_PULSEAUDIO" OFF)
+set_option(SDL_SNDIO               "Support the sndio audio API" ${UNIX_SYS})
+dep_option(SDL_SNDIO_SHARED        "Dynamically load the sndio audio API" ON "SDL_SNDIO" OFF)
 set_option(SDL_LIBSAMPLERATE       "Use libsamplerate for audio rate conversion" ${UNIX_SYS})
 dep_option(SDL_LIBSAMPLERATE_SHARED "Dynamically load libsamplerate" ON "SDL_LIBSAMPLERATE" OFF)
 set_option(SDL_RPATH               "Use an rpath when linking SDL" ${UNIX_SYS})
@@ -1399,6 +1401,7 @@ elseif(UNIX AND NOT APPLE AND NOT RISCOS AND NOT HAIKU)
     CheckALSA()
     CheckPipewire()
     CheckPulseAudio()
+    CheckSNDIO()
   endif()
 
   if(SDL_VIDEO)
diff --git a/cmake/sdlchecks.cmake b/cmake/sdlchecks.cmake
index a8e746f96641..750d55f00fa7 100644
--- a/cmake/sdlchecks.cmake
+++ b/cmake/sdlchecks.cmake
@@ -165,6 +165,35 @@ macro(CheckPulseAudio)
   endif()
 endmacro()
 
+# Requires:
+# - PkgCheckModules
+# Optional:
+# - SDL_SNDIO_SHARED opt
+# - HAVE_SDL_LOADSO opt
+macro(CheckSNDIO)
+  if(SDL_SNDIO)
+    pkg_check_modules(PKG_SNDIO sndio)
+    if(PKG_SNDIO_FOUND)
+      set(HAVE_SNDIO TRUE)
+      file(GLOB SNDIO_SOURCES ${SDL3_SOURCE_DIR}/src/audio/sndio/*.c)
+      list(APPEND SOURCE_FILES ${SNDIO_SOURCES})
+      set(SDL_AUDIO_DRIVER_SNDIO 1)
+      list(APPEND EXTRA_CFLAGS ${PKG_SNDIO_CFLAGS})
+      if(SDL_SNDIO_SHARED AND NOT HAVE_SDL_LOADSO)
+        message_warn("You must have SDL_LoadObject() support for dynamic sndio loading")
+      endif()
+      FindLibraryAndSONAME("sndio" LIBDIRS ${PKG_SNDIO_LIBRARY_DIRS})
+      if(SDL_SNDIO_SHARED AND SNDIO_LIB AND HAVE_SDL_LOADSO)
+        set(SDL_AUDIO_DRIVER_SNDIO_DYNAMIC "\"${SNDIO_LIB_SONAME}\"")
+        set(HAVE_SNDIO_SHARED TRUE)
+      else()
+        list(APPEND EXTRA_LIBS ${PKG_SNDIO_LDFLAGS})
+      endif()
+      set(HAVE_SDL_AUDIO TRUE)
+    endif()
+  endif()
+endmacro()
+
 # Requires:
 # - SDL_LIBSAMPLERATE
 # Optional:
diff --git a/configure b/configure
index e741f52acaa5..843e75bd389b 100755
--- a/configure
+++ b/configure
@@ -704,6 +704,8 @@ RPI_LIBS
 RPI_CFLAGS
 DECOR_LIBS
 DECOR_CFLAGS
+SNDIO_LIBS
+SNDIO_CFLAGS
 PULSEAUDIO_LIBS
 PULSEAUDIO_CFLAGS
 PIPEWIRE_LIBS
@@ -870,6 +872,8 @@ enable_pipewire
 enable_pipewire_shared
 enable_pulseaudio
 enable_pulseaudio_shared
+enable_sndio
+enable_sndio_shared
 enable_diskaudio
 enable_dummyaudio
 enable_libsamplerate
@@ -948,6 +952,8 @@ PIPEWIRE_CFLAGS
 PIPEWIRE_LIBS
 PULSEAUDIO_CFLAGS
 PULSEAUDIO_LIBS
+SNDIO_CFLAGS
+SNDIO_LIBS
 DECOR_CFLAGS
 DECOR_LIBS
 RPI_CFLAGS
@@ -1642,6 +1648,8 @@ Optional Features:
   --enable-pulseaudio     use PulseAudio [default=yes]
   --enable-pulseaudio-shared
                           dynamically load PulseAudio support [default=yes]
+  --enable-sndio          support the sndio audio API [default=yes]
+  --enable-sndio-shared   dynamically load sndio audio support [default=yes]
   --enable-diskaudio      support the disk writer audio driver [default=yes]
   --enable-dummyaudio     support the dummy audio driver [default=yes]
   --enable-libsamplerate  use libsamplerate for audio rate conversion
@@ -1767,6 +1775,9 @@ Some influential environment variables:
               C compiler flags for PULSEAUDIO, overriding pkg-config
   PULSEAUDIO_LIBS
               linker flags for PULSEAUDIO, overriding pkg-config
+  SNDIO_CFLAGS
+              C compiler flags for SNDIO, overriding pkg-config
+  SNDIO_LIBS  linker flags for SNDIO, overriding pkg-config
   DECOR_CFLAGS
               C compiler flags for DECOR, overriding pkg-config
   DECOR_LIBS  linker flags for DECOR, overriding pkg-config
@@ -21489,6 +21500,127 @@ printf "%s\n" "#define SDL_AUDIO_DRIVER_PULSEAUDIO_DYNAMIC \"$pulseaudio_lib\""
     fi
 }
 
+CheckSNDIO()
+{
+    # Check whether --enable-sndio was given.
+if test ${enable_sndio+y}
+then :
+  enableval=$enable_sndio;
+else $as_nop
+  enable_sndio=yes
+fi
+
+    if test x$enable_audio = xyes -a x$enable_sndio = xyes; then
+
+pkg_failed=no
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for sndio" >&5
+printf %s "checking for sndio... " >&6; }
+
+if test -n "$SNDIO_CFLAGS"; then
+    pkg_cv_SNDIO_CFLAGS="$SNDIO_CFLAGS"
+ elif test -n "$PKG_CONFIG"; then
+    if test -n "$PKG_CONFIG" && \
+    { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"sndio\""; } >&5
+  ($PKG_CONFIG --exists --print-errors "sndio") 2>&5
+  ac_status=$?
+  printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }; then
+  pkg_cv_SNDIO_CFLAGS=`$PKG_CONFIG --cflags "sndio" 2>/dev/null`
+		      test "x$?" != "x0" && pkg_failed=yes
+else
+  pkg_failed=yes
+fi
+ else
+    pkg_failed=untried
+fi
+if test -n "$SNDIO_LIBS"; then
+    pkg_cv_SNDIO_LIBS="$SNDIO_LIBS"
+ elif test -n "$PKG_CONFIG"; then
+    if test -n "$PKG_CONFIG" && \
+    { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"sndio\""; } >&5
+  ($PKG_CONFIG --exists --print-errors "sndio") 2>&5
+  ac_status=$?
+  printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }; then
+  pkg_cv_SNDIO_LIBS=`$PKG_CONFIG --libs "sndio" 2>/dev/null`
+		      test "x$?" != "x0" && pkg_failed=yes
+else
+  pkg_failed=yes
+fi
+ else
+    pkg_failed=untried
+fi
+
+
+
+if test $pkg_failed = yes; then
+        { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5
+printf "%s\n" "no" >&6; }
+
+if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then
+        _pkg_short_errors_supported=yes
+else
+        _pkg_short_errors_supported=no
+fi
+        if test $_pkg_short_errors_supported = yes; then
+	        SNDIO_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "sndio" 2>&1`
+        else
+	        SNDIO_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "sndio" 2>&1`
+        fi
+	# Put the nasty error message in config.log where it belongs
+	echo "$SNDIO_PKG_ERRORS" >&5
+
+	audio_sndio=no
+elif test $pkg_failed = untried; then
+        { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5
+printf "%s\n" "no" >&6; }
+	audio_sndio=no
+else
+	SNDIO_CFLAGS=$pkg_cv_SNDIO_CFLAGS
+	SNDIO_LIBS=$pkg_cv_SNDIO_LIBS
+        { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+printf "%s\n" "yes" >&6; }
+	audio_sndio=yes
+fi
+
+        if test x$audio_sndio = xyes; then
+            # Check whether --enable-sndio-shared was given.
+if test ${enable_sndio_shared+y}
+then :
+  enableval=$enable_sndio_shared;
+else $as_nop
+  enable_sndio_shared=yes
+fi
+
+            sndio_lib=`find_lib "libsndio.so.*" "$SNDIO_LIBS" | sed 's/.*\/\(.*\)/\1/; q'`
+
+            if test x$have_loadso != xyes && \
+               test x$enable_sndio_shared = xyes; then
+                { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: You must have SDL_LoadObject() support for dynamic sndio loading" >&5
+printf "%s\n" "$as_me: WARNING: You must have SDL_LoadObject() support for dynamic sndio loading" >&2;}
+            fi
+            if test x$have_loadso = xyes && \
+               test x$enable_sndio_shared = xyes && test x$sndio_lib != x; then
+                echo "-- dynamic libsndio -> $sndio_lib"
+
+printf "%s\n" "#define SDL_AUDIO_DRIVER_SNDIO_DYNAMIC \"$sndio_lib\"" >>confdefs.h
+
+                SUMMARY_audio="${SUMMARY_audio} sndio(dynamic)"
+            else
+                EXTRA_LDFLAGS="$EXTRA_LDFLAGS $SNDIO_LIBS"
+                SUMMARY_audio="${SUMMARY_audio} sndio"
+            fi
+
+
+printf "%s\n" "#define SDL_AUDIO_DRIVER_SNDIO 1" >>confdefs.h
+
+            SOURCES="$SOURCES $srcdir/src/audio/sndio/*.c"
+            EXTRA_CFLAGS="$EXTRA_CFLAGS $SNDIO_CFLAGS"
+            have_audio=yes
+        fi
+    fi
+}
+
 CheckDiskAudio()
 {
     # Check whether --enable-diskaudio was given.
@@ -27013,6 +27145,7 @@ printf "%s\n" "#define SDL_VIDEO_DRIVER_ANDROID 1" >>confdefs.h
         CheckALSA
         CheckPipewire
         CheckPulseAudio
+        CheckSNDIO
         CheckLibSampleRate
         # Need to check for Raspberry PI first and add platform specific compiler flags, otherwise the test for GLES fails!
         CheckRPI
diff --git a/configure.ac b/configure.ac
index ac9965913edf..aec3c4fb8a51 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1068,6 +1068,43 @@ CheckPulseAudio()
     fi
 }
 
+dnl See if the sndio audio interface is supported
+CheckSNDIO()
+{
+    AC_ARG_ENABLE(sndio,
+[AS_HELP_STRING([--enable-sndio], [support the sndio audio API [default=yes]])],
+                  , enable_sndio=yes)
+    if test x$enable_audio = xyes -a x$enable_sndio = xyes; then
+        PKG_CHECK_MODULES([SNDIO], [sndio], audio_sndio=yes, audio_sndio=no)
+
+        if test x$audio_sndio = xyes; then
+            AC_ARG_ENABLE(sndio-shared,
+[AS_HELP_STRING([--enable-sndio-shared], [dynamically load sndio audio support [default=yes]])],
+                          , enable_sndio_shared=yes)
+            sndio_lib=[`find_lib "libsndio.so.*" "$SNDIO_LIBS" | sed 's/.*\/\(.*\)/\1/; q'`]
+
+            if test x$have_loadso != xyes && \
+               test x$enable_sndio_shared = xyes; then
+                AC_MSG_WARN([You must have SDL_LoadObject() support for dynamic sndio loading])
+            fi
+            if test x$have_loadso = xyes && \
+               test x$enable_sndio_shared = xyes && test x$sndio_lib != x; then
+                echo "-- dynamic libsndio -> $sndio_lib"
+                AC_DEFINE_UNQUOTED(SDL_AUDIO_DRIVER_SNDIO_DYNAMIC, "$sndio_lib", [ ])
+                SUMMARY_audio="${SUMMARY_audio} sndio(dynamic)"
+            else
+                EXTRA_LDFLAGS="$EXTRA_LDFLAGS $SNDIO_LIBS"
+                SUMMARY_audio="${SUMMARY_audio} sndio"
+            fi
+
+            AC_DEFINE(SDL_AUDIO_DRIVER_SNDIO, 1, [ ])
+            SOURCES="$SOURCES $srcdir/src/audio/sndio/*.c"
+            EXTRA_CFLAGS="$EXTRA_CFLAGS $SNDIO_CFLAGS"
+            have_audio=yes
+        fi
+    fi
+}
+
 dnl rcg07142001 See if the user wants the disk writer audio driver...
 CheckDiskAudio()
 {
@@ -3382,6 +3419,7 @@ case "$host" in
         CheckALSA
         CheckPipewire
         CheckPulseAudio
+        CheckSNDIO
         CheckLibSampleRate
         # Need to check for Raspberry PI first and add platform specific compiler flags, otherwise the test for GLES fails!
         CheckRPI
diff --git a/include/SDL_config.h.cmake b/include/SDL_config.h.cmake
index c5ca22625cd0..31ca2cf4f745 100644
--- a/include/SDL_config.h.cmake
+++ b/include/SDL_config.h.cmake
@@ -305,6 +305,8 @@
 #cmakedefine SDL_AUDIO_DRIVER_PIPEWIRE_DYNAMIC @SDL_AUDIO_DRIVER_PIPEWIRE_DYNAMIC@
 #cmakedefine SDL_AUDIO_DRIVER_PULSEAUDIO @SDL_AUDIO_DRIVER_PULSEAUDIO@
 #cmakedefine SDL_AUDIO_DRIVER_PULSEAUDIO_DYNAMIC @SDL_AUDIO_DRIVER_PULSEAUDIO_DYNAMIC@
+#cmakedefine SDL_AUDIO_DRIVER_SNDIO @SDL_AUDIO_DRIVER_SNDIO@
+#cmakedefine SDL_AUDIO_DRIVER_SNDIO_DYNAMIC @SDL_AUDIO_DRIVER_SNDIO_DYNAMIC@
 #cmakedefine SDL_AUDIO_DRIVER_WASAPI @SDL_AUDIO_DRIVER_WASAPI@
 #cmakedefine SDL_AUDIO_DRIVER_VITA @SDL_AUDIO_DRIVER_VITA@
 #cmakedefine SDL_AUDIO_DRIVER_PSP @SDL_AUDIO_DRIVER_PSP@
diff --git a/include/SDL_config.h.in b/include/SDL_config.h.in
index 0611c0e5412f..185c10c5cd88 100644
--- a/include/SDL_config.h.in
+++ b/include/SDL_config.h.in
@@ -292,6 +292,8 @@
 #undef SDL_AUDIO_DRIVER_PIPEWIRE_DYNAMIC
 #undef SDL_AUDIO_DRIVER_PULSEAUDIO
 #undef SDL_AUDIO_DRIVER_PULSEAUDIO_DYNAMIC
+#undef SDL_AUDIO_DRIVER_SNDIO
+#undef SDL_AUDIO_DRIVER_SNDIO_DYNAMIC
 #undef SDL_AUDIO_DRIVER_WASAPI
 
 /* Enable various input drivers */
diff --git a/src/audio/SDL_audio.c b/src/audio/SDL_audio.c
index 2bbc73a8e800..001eecb95c25 100644
--- a/src/audio/SDL_audio.c
+++ b/src/audio/SDL_audio.c
@@ -42,6 +42,9 @@ static const AudioBootStrap *const bootstrap[] = {
 #if SDL_AUDIO_DRIVER_ALSA
     &ALSA_bootstrap,
 #endif
+#if SDL_AUDIO_DRIVER_SNDIO
+    &SNDIO_bootstrap,
+#endif
 #if SDL_AUDIO_DRIVER_NETBSD
     &NETBSDAUDIO_bootstrap,
 #endif
diff --git a/src/audio/SDL_sysaudio.h b/src/audio/SDL_sysaudio.h
index 60a050912110..99870032049a 100644
--- a/src/audio/SDL_sysaudio.h
+++ b/src/audio/SDL_sysaudio.h
@@ -184,6 +184,7 @@ typedef struct AudioBootStrap
 extern AudioBootStrap PIPEWIRE_bootstrap;
 extern AudioBootStrap PULSEAUDIO_bootstrap;
 extern AudioBootStrap ALSA_bootstrap;
+extern AudioBootStrap SNDIO_bootstrap;
 extern AudioBootStrap NETBSDAUDIO_bootstrap;
 extern AudioBootStrap DSP_bootstrap;
 extern AudioBootStrap WASAPI_bootstrap;
diff --git a/src/audio/sndio/SDL_sndioaudio.c b/src/audio/sndio/SDL_sndioaudio.c
new file mode 100644
index 000000000000..29e5315b97e5
--- /dev/null
+++ b/src/audio/sndio/SDL_sndioaudio.c
@@ -0,0 +1,387 @@
+/*
+  Simple DirectMedia Layer
+  Copyright (C) 1997-2022 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"
+
+#if SDL_AUDIO_DRIVER_SNDIO
+
+/* OpenBSD sndio target */
+
+#if HAVE_STDIO_H
+#include <stdio.h>
+#endif
+
+#ifdef HAVE_SIGNAL_H
+#include <signal.h>
+#endif
+
+#include <poll.h>
+#include <unistd.h>
+
+#include "SDL_audio.h"
+#include "../SDL_audio_c.h"
+#include "SDL_sndioaudio.h"
+
+#ifdef SDL_AUDIO_DRIVER_SNDIO_DYNAMIC
+#include "SDL_loadso.h"
+#endif
+
+#ifndef INFTIM
+#define INFTIM -1
+#endif
+
+#ifndef SIO_DEVANY
+#define SIO_DEVANY "default"
+#endif
+
+static struct sio_hdl * (*SNDIO_sio_open)(const char *, unsigned int, int);
+static void (*SNDIO_sio_close)(struct sio_hdl *);
+static int (*SNDIO_sio_setpar)(struct sio_hdl *, struct sio_par *);
+static int (*SNDIO_sio_getpar)(struct sio_hdl *, struct sio_par *);
+static int (*SNDIO_sio_start)(struct sio_hdl *);
+static int (*SNDIO_sio_stop)(struct sio_hdl *);
+static size_t (*SNDIO_sio_read)(struct sio_hdl *, void *, size_t);
+static size_t (*SNDIO_sio_write)(struct sio_hdl *, const void *, size_t);
+static int (*SNDIO_sio_nfds)(struct sio_hdl *);
+static int (*SNDIO_sio_pollfd)(struct sio_hdl *, struct pollfd *, int);
+static int (*SNDIO_sio_revents)(struct sio_hdl *, struct pollfd *);
+static int (*SNDIO_sio_eof)(struct sio_hdl *);
+static void (*SNDIO_sio_initpar)(struct sio_par *);
+
+#ifdef SDL_AUDIO_DRIVER_SNDIO_DYNAMIC
+static const char *sndio_library = SDL_AUDIO_DRIVER_SNDIO_DYNAMIC;
+static void *sndio_handle = NULL;
+
+static int
+load_sndio_sym(const char *fn, void **addr)
+{
+    *addr = SDL_LoadFunction(sndio_handle, fn);
+    if (*addr == NULL) {
+        /* Don't call SDL_SetError(): SDL_LoadFunction already did. */
+        return 0;
+    }
+
+    return 1;
+}
+
+/* cast funcs to char* first, to please GCC's strict aliasing rules. */
+#define SDL_SNDIO_SYM(x) \
+    if (!load_sndio_sym(#x, (void **) (char *) &SNDIO_##x)) return -1
+#else
+#define SDL_SNDIO_SYM(x) SNDIO_##x = x
+#endif
+
+static int
+load_sndio_syms(void)
+{
+    SDL_SNDIO_SYM(sio_open);
+    SDL_SNDIO_SYM(sio_close);
+    SDL_SNDIO_SYM(sio_setpar);
+    SDL_SNDIO_SYM(sio_getpar);
+    SDL_SNDIO_SYM(sio_start);
+    SDL_SNDIO_SYM(sio_stop);
+    SDL_SNDIO_SYM(sio_read);
+    SDL_SNDIO_SYM(sio_write);
+    SDL_SNDIO_SYM(sio_nfds);
+    SDL_SNDIO_SYM(sio_pollfd);
+    SDL_SNDIO_SYM(sio_revents);
+    SDL_SNDIO_SYM(sio_eof);
+    SDL_SNDIO_SYM(sio_initpar);
+    return 0;
+}
+
+#undef SDL_SNDIO_SYM
+
+#ifdef SDL_AUDIO_DRIVER_SNDIO_DYNAMIC
+
+static void
+UnloadSNDIOLibrary(void)
+{
+    if (sndio_handle != NULL) {
+        SDL_UnloadObject(sndio_handle);
+        sndio_handle = NULL;
+    }
+}
+
+static int
+LoadSNDIOLibrary(void)
+{
+    int retval = 0;
+    if (sndio_handle == NULL) {
+        sndio_handle = SDL_LoadObject(sndio_library);
+        if (sndio_handle == NULL) {
+            retval = -1;
+            /* Don't call SDL_SetError(): SDL_LoadObject already did. */
+        } else {
+            retval = load_sndio_syms();
+            if (retval < 0) {
+                UnloadSNDIOLibrary();
+            }
+        }
+    }
+    return retval;
+}
+
+#else
+
+static void
+UnloadSNDIOLibrary(void)
+{
+}
+
+static int
+LoadSNDIOLibrary(void)
+{
+    load_sndio_syms();
+    return 0;
+}
+
+#endif /* SDL_AUDIO_DRIVER_SNDIO_DYNAMIC */
+
+
+
+
+static void
+SNDIO_WaitDevice(_THIS)
+{
+    /* no-op; SNDIO_sio_write() blocks if necessary. */
+}
+
+static void
+SNDIO_PlayDevice(_THIS)
+{
+    const int written = SNDIO_sio_write(this->hidden->dev,
+                                        this->hidden->mixbuf,
+                                        this->hidden->mixlen);
+
+    /* If we couldn't write, assume fatal error for now */
+    if ( written == 0 ) {
+        SDL_OpenedAudioDeviceDisconnected(this);
+    }
+#ifdef DEBUG_AUDIO
+    fprintf(stderr, "Wrote %d bytes of audio data\n", written);
+#endif
+}
+
+static int
+SNDIO_CaptureFromDevice(_THIS, void *buffer, int buflen)
+{
+    size_t r;
+    int revents;
+    int nfds;
+
+    /* Emulate a blocking read */
+    r = SNDIO_sio_read(this->hidden->dev, buffer, buflen);
+    while (r == 0 && !SNDIO_sio_eof(this->hidden->dev)) {
+        if ((nfds = SNDIO_sio_pollfd(this->hidden->dev, this->hidden->pfd, POLLIN)) <= 0
+            || poll(this->hidden->pfd, nfds, INFTIM) < 0) {
+            return -1;
+        }
+        revents = SNDIO_sio_revents(this->hidden->dev, this->hidden->pfd);
+        if (revents & POLLIN) {
+            r = SNDIO_sio_read(this->hidden->dev, buffer, buflen);
+        }
+        if (revents & POLLHUP) {
+            break;
+        }
+    }
+    return (int) r;
+}
+
+static void
+SNDIO_FlushCapture(_THIS)
+{
+    char buf[512];
+
+    while (SNDIO_sio_read(this->hidden->dev, buf, sizeof(buf)) != 0) {
+        /* do nothing */;
+    }
+}
+
+static Uint8 *
+SNDIO_GetDeviceBuf(_THIS)
+{
+    return this->hidden->mixbuf;
+}
+
+static void
+SNDIO_CloseDevice(_THIS)
+{
+    if ( this->hidden->pfd != NULL ) {
+        SDL_free(this->hidden->pfd);
+    }
+    if ( this->hidden->dev != NULL ) {
+        SNDIO_sio_stop(this->hidden->dev);
+        SNDIO_sio_close(this->hidden->dev);
+    }
+    SDL_free(this->hidden->mixbuf);
+    SDL_free(this->hidden);
+}
+
+static int
+SNDIO_OpenDevice(_THIS, const char *devname)
+{
+    SDL_AudioFormat test_format;
+    struct sio_par par;
+    SDL_bool iscapture = this->iscapture;
+
+    this->hidden = (struct SDL_PrivateAudioData *)
+        SDL_malloc(sizeof(*this->hidden));
+    if (this->hidden == NULL) {
+        return SDL_OutOfMemory();
+    }
+    SDL_zerop(this->hidden);
+
+    this->hidden->mixlen = this->spec.size;
+
+    /* Capture devices must be non-blocking for SNDIO_FlushCapture */
+    if ((this->hidden->dev =
+        SNDIO_sio_open(devname != NULL ? devname : SIO_DEVANY,
+                       iscapture ? SIO_REC : SIO_PLAY, iscapture)) == NULL) {
+        return SDL_SetError("sio_open() failed");
+    }
+
+    /* Allocate the pollfd array for capture devices */
+    if (iscapture && (this->hidden->pfd =
+        SDL_malloc(sizeof(struct pollfd) * SNDIO_sio_nfds(this->hidden->dev))) == NULL) {
+        return SDL_OutOfMemory();
+    }
+
+    SNDIO_sio_initpar(&par);
+
+    par.rate = this->spec.freq;
+    par.pchan = this->spec.channels;
+    par.round = this->spec.samples;
+    par.appbufsz = par.round * 2;
+
+    /* Try for a closest match on audio format */
+    for (test_format = SDL_FirstAudioFormat(this->spec.format); test_format; test_format = SDL_NextAudioFormat()) {
+        if (!SDL_AUDIO_ISFLOAT(test_format)) {
+            par.le = SDL_AUDIO_ISLITTLEENDIAN(test_format) ? 1 : 0;
+            par.sig = SDL_AUDIO_ISSIGNED(test_format) ? 1 : 0;
+            par.bits = SDL_AUDIO_BITSIZE(test_format);
+
+            if (SNDIO_sio_setpar(this->hidden->dev, &par) == 0) {
+                continue;
+            }
+            if (SNDIO_sio_getpar(this->hidden->dev, &par) == 0) {
+                return SDL_SetError("sio_getpar() failed");
+            }
+            if (par.bps != SIO_BPS(par.bits)) {
+                continue;
+            }
+            if ((par.bits == 8 * par.bps) || (par.msb)) {
+                break;
+            }
+        }
+    }
+
+    if (!test_format) {
+        return SDL_SetError("%s: Unsupported audio format", "sndio");
+    }
+
+    if ((par.bps == 4) && (par.sig) && (par.le))
+        this->spec.format = AUDIO_S32LSB;
+    else if ((par.bps == 4) && (par.sig) && (!par.le))
+        this->spec.format = AUDIO_S32MSB;
+    else if ((par.bps == 2) && (par.sig) && (par.le))
+        this->spec.format = AUDIO_S16LSB;
+    else if ((par.bps == 2) && (par.sig) && (!par.le))
+        this->spec.format = AUDIO_S16MSB;
+    else if ((par.bps == 2) && (!par.sig) && (par.le))
+        this->spec.format = AUDIO_U16LSB;
+    else if ((par.bps == 2) && (!par.sig) && (!par.le))
+        this->spec.format = AUDIO_U16MSB;
+    else if ((par.bps == 1) && (par.sig))
+        this->spec.format = AUDIO_S8;
+    else if ((par.bps == 1) && (!par.sig))
+        this->spec.format = AUDIO_U8;
+    else {
+        return SDL_SetError("sndio: Got unsupported hardware audio format.");
+    }
+
+    this->spec.freq = par.rate;
+    this->spec.channels = par.pchan;
+    this->spec.samples = par.round;
+
+    /* Calculate the final parameters for this audio specification */
+    SDL_CalculateAudioSpec(&this->spec);
+
+    /* Allocate mixing buffer */
+    this->hidden->mixlen = this->spec.size;
+    this->hidden->mixbuf = (Uint8 *) SDL_malloc(this->hidden->mixlen);
+    if (this->hidden->mixbuf == NULL) {
+        return SDL_OutOfMemory();
+    }
+    SDL_memset(this->hidden->mixbuf, this->spec.silence, this->hidden->mixlen);
+
+    if (!SNDIO_sio_start(this->hidden->dev)) {
+        return SDL_SetError("sio_start() failed");
+    }
+
+    /* We're ready to rock and roll. :-) */
+    return 0;
+}
+
+static void
+SNDIO_Deinitialize(void)
+{
+    UnloadSNDIOLibrary();
+}
+
+static void
+SNDIO_DetectDevices(void)
+{
+	SDL_AddAudioDevice(SDL_FALSE, DEFAULT_OUTPUT_DEVNAME, NULL, (void *) 0x1);
+	SDL_AddAudioDevice(SDL_TRUE, DEFAULT_INPUT_DEVNAME, NULL, (void *) 0x2);
+}
+
+static SDL_bool
+SNDIO_Init(SDL_AudioDriverImpl * impl)
+{
+    if (LoadSNDIOLibrary() < 0) {
+        return SDL_FALSE;
+    }
+
+    /* Set the function pointers */
+    impl->OpenDevice = SNDIO_OpenDevice;
+    impl->WaitDevice = SNDIO_WaitDevice;
+    impl->PlayDevice = SNDIO_PlayDevice;
+    impl->GetDeviceBuf = SNDIO_GetDeviceBuf;
+    impl->CloseDevice = SNDIO_CloseDevice;
+    impl->CaptureFromDevice = SNDIO_CaptureFromDevice;
+    impl->FlushCapture = SNDIO_FlushCapture;
+    impl->Deinitialize = SNDIO_Deinitialize;
+    impl->DetectDevices = SNDIO_DetectDevices;
+
+    impl->AllowsArbitraryDeviceNames = SDL_TRUE;
+    impl->HasCaptureSupport = SDL_TRUE;
+
+    return SDL_TRUE;   /* this audio target is available. */
+}
+
+AudioBootStrap SNDIO_bootstrap = {
+    "sndio", "OpenBSD sndio", SNDIO_Init, SDL_FALSE
+};
+
+#endif /* SDL_AUDIO_DRIVER_SNDIO */
+
+/* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/audio/sndio/SDL_sndioaudio.h b/src/audio/sndio/SDL_sndioaudio.h
new file mode 100644
index 000000000000..57db05cb93e8
--- /dev/null
+++ b/src/audio/sndio/SDL_sndioaudio.h
@@ -0,0 +1,49 @@
+/*
+  Simple DirectMedia Layer
+  Copyright (C) 1997-2022 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_sndioaudio_h_
+#define SDL_sndioaudio_h_
+
+#include <poll.h>
+#include <sndio.h>
+
+#include "../SDL_sysaudio.h"
+
+/* Hidden "this" pointer for the audio functions */
+#define _THIS   SDL_AudioDevice *this
+
+struct SDL_PrivateAudioData
+{
+    /* The audio device handle */
+    struct sio_hdl *dev;
+
+    /* Raw mixing buffer */
+    Uint8 *mixbuf;
+    int mixlen;
+
+    /* Polling structures for non-blocking sndio devices */
+    struct pollfd *pfd;
+};
+
+#endif /* SDL_sndioaudio_h_ */
+
+/* vi: set ts=4 sw=4 expandtab: */