From 1fd4c865fc084f134363db5155361d5483679235 Mon Sep 17 00:00:00 2001
From: Chris Robinson <chris.kcat@gmail.com>
Date: Fri, 30 Jul 2021 04:15:00 -0700
Subject: Use non-block mode for sndio capture

---
 alc/backends/sndio.cpp | 123 ++++++++++++++++++++++++++++++-------------------
 1 file changed, 76 insertions(+), 47 deletions(-)

diff --git a/alc/backends/sndio.cpp b/alc/backends/sndio.cpp
index c41c6c8b..6852e01a 100644
--- a/alc/backends/sndio.cpp
+++ b/alc/backends/sndio.cpp
@@ -22,6 +22,7 @@
 
 #include "sndio.h"
 
+#include <poll.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
@@ -166,6 +167,7 @@ retry_params:
     }
     par.bps = SIO_BPS(par.bits);
     par.le = SIO_LE_NATIVE;
+    par.msb = 1;
 
     par.rate = mDevice->Frequency;
     par.pchan = mDevice->channelsFromFmt();
@@ -197,6 +199,7 @@ retry_params:
     catch(al::backend_exception &e) {
         if(tryfmt == DevFmtShort)
             throw;
+        par.clear();
         tryfmt = DevFmtShort;
         goto retry_params;
     }
@@ -266,6 +269,11 @@ void SndioPlayback::stop()
 }
 
 
+/* TODO: This could be improved by avoiding the ring buffer and record thread,
+ * counting the available samples with the sio_onmove callback and reading
+ * directly from the device. However, this depends on reasonable support for
+ * capture buffer sizes apps may request.
+ */
 struct SndioCapture final : public BackendBase {
     SndioCapture(DeviceBase *device) noexcept : BackendBase{device} { }
     ~SndioCapture() override;
@@ -280,6 +288,7 @@ struct SndioCapture final : public BackendBase {
 
     sio_hdl *mSndHandle{nullptr};
 
+    al::vector<struct pollfd> mFds;
     RingBufferPtr mRing;
 
     std::atomic<bool> mKillNow{true};
@@ -305,37 +314,53 @@ int SndioCapture::recordProc()
     while(!mKillNow.load(std::memory_order_acquire)
         && mDevice->Connected.load(std::memory_order_acquire))
     {
-        auto data = mRing->getWriteVector();
-        size_t todo{data.first.len + data.second.len};
-        if(todo == 0)
+        /* Wait until there's some samples to read. */
+        const int nfds{sio_pollfd(mSndHandle, mFds.data(), POLLIN)};
+        if(nfds <= 0)
         {
-            static char junk[4096];
-            sio_read(mSndHandle, junk,
-                minz(sizeof(junk)/frameSize, mDevice->UpdateSize)*frameSize);
+            mDevice->handleDisconnect("Failed to get polling fds: %d", nfds);
+            break;
+        }
+        int pollres{::poll(mFds.data(), static_cast<uint>(nfds), 2000)};
+        if(pollres < 0)
+        {
+            if(errno == EINTR) continue;
+            mDevice->handleDisconnect("Poll error: %s", strerror(errno));
+            break;
+        }
+        if(pollres == 0)
             continue;
+
+        const int revents{sio_revents(mSndHandle, mFds.data())};
+        if((revents&POLLHUP))
+        {
+            mDevice->handleDisconnect("Got POLLHUP from poll events");
+            break;
         }
+        if(!(revents&POLLIN))
+            continue;
 
-        size_t total{0u};
-        data.first.len  *= frameSize;
-        data.second.len *= frameSize;
-        todo = minz(todo, mDevice->UpdateSize) * frameSize;
-        while(total < todo)
+        auto data = mRing->getWriteVector();
+        al::span<al::byte> buffer{data.first.buf, data.first.len*frameSize};
+        while(!buffer.empty())
         {
-            if(!data.first.len)
-                data.first = data.second;
+            size_t got{sio_read(mSndHandle, buffer.data(), buffer.size())};
+            if(got == 0) break;
 
-            size_t got{sio_read(mSndHandle, data.first.buf, minz(todo-total, data.first.len))};
-            if(!got)
+            mRing->writeAdvance(got / frameSize);
+            buffer = buffer.subspan(got);
+            if(buffer.empty())
             {
-                mDevice->handleDisconnect("Failed to read capture samples");
-                break;
+                data = mRing->getWriteVector();
+                buffer = {data.first.buf, data.first.len*frameSize};
             }
-
-            data.first.buf += got;
-            data.first.len -= got;
-            total += got;
         }
-        mRing->writeAdvance(total / frameSize);
+        if(buffer.empty())
+        {
+            /* Got samples to read, but no place to store it. Drop it. */
+            static char junk[4096];
+            sio_read(mSndHandle, junk, sizeof(junk) - (sizeof(junk)%frameSize));
+        }
     }
 
     return 0;
@@ -350,76 +375,80 @@ void SndioCapture::open(const char *name)
         throw al::backend_exception{al::backend_error::NoDevice, "Device name \"%s\" not found",
             name};
 
-    mSndHandle = sio_open(nullptr, SIO_REC, 0);
+    mSndHandle = sio_open(nullptr, SIO_REC, true);
     if(mSndHandle == nullptr)
         throw al::backend_exception{al::backend_error::NoDevice, "Could not open backend device"};
 
-    sio_par par;
-    sio_initpar(&par);
-
+    SioPar par;
     switch(mDevice->FmtType)
     {
     case DevFmtByte:
-        par.bps = 1;
+        par.bits = 8;
         par.sig = 1;
         break;
     case DevFmtUByte:
-        par.bps = 1;
+        par.bits = 8;
         par.sig = 0;
         break;
     case DevFmtShort:
-        par.bps = 2;
+        par.bits = 16;
         par.sig = 1;
         break;
     case DevFmtUShort:
-        par.bps = 2;
+        par.bits = 16;
         par.sig = 0;
         break;
     case DevFmtInt:
-        par.bps = 4;
+        par.bits = 32;
         par.sig = 1;
         break;
     case DevFmtUInt:
-        par.bps = 4;
+        par.bits = 32;
         par.sig = 0;
         break;
     case DevFmtFloat:
         throw al::backend_exception{al::backend_error::DeviceError,
             "%s capture samples not supported", DevFmtTypeString(mDevice->FmtType)};
     }
-    par.bits = par.bps * 8;
+    par.bps = SIO_BPS(par.bits);
     par.le = SIO_LE_NATIVE;
-    par.msb = SIO_LE_NATIVE ? 0 : 1;
+    par.msb = 1;
     par.rchan = mDevice->channelsFromFmt();
     par.rate = mDevice->Frequency;
 
     par.appbufsz = maxu(mDevice->BufferSize, mDevice->Frequency/10);
-    par.round = minu(par.appbufsz, mDevice->Frequency/40);
-
-    mDevice->UpdateSize = par.round;
-    mDevice->BufferSize = par.appbufsz;
+    par.round = minu(par.appbufsz/2, mDevice->Frequency/40);
 
     if(!sio_setpar(mSndHandle, &par) || !sio_getpar(mSndHandle, &par))
         throw al::backend_exception{al::backend_error::DeviceError,
             "Failed to set device praameters"};
 
-    if(par.bits != par.bps*8)
+    if(par.bps > 1 && par.le != SIO_LE_NATIVE)
+        throw al::backend_exception{al::backend_error::DeviceError,
+            "%s-endian samples not supported", par.le ? "Little" : "Big"};
+    if(par.bits < par.bps*8 && !par.msb)
         throw al::backend_exception{al::backend_error::DeviceError,
             "Padded samples not supported (got %u of %u bits)", par.bits, par.bps*8};
 
-    if(!((mDevice->FmtType == DevFmtByte && par.bits == 8 && par.sig != 0)
-        || (mDevice->FmtType == DevFmtUByte && par.bits == 8 && par.sig == 0)
-        || (mDevice->FmtType == DevFmtShort && par.bits == 16 && par.sig != 0)
-        || (mDevice->FmtType == DevFmtUShort && par.bits == 16 && par.sig == 0)
-        || (mDevice->FmtType == DevFmtInt && par.bits == 32 && par.sig != 0)
-        || (mDevice->FmtType == DevFmtUInt && par.bits == 32 && par.sig == 0))
-        || mDevice->channelsFromFmt() != par.rchan || mDevice->Frequency != par.rate)
+    auto match_fmt = [](DevFmtType fmttype, const sio_par &par) -> bool
+    {
+        return (fmttype == DevFmtByte && par.bps == 1 && par.sig != 0)
+            || (fmttype == DevFmtUByte && par.bps == 1 && par.sig == 0)
+            || (fmttype == DevFmtShort && par.bps == 2 && par.sig != 0)
+            || (fmttype == DevFmtUShort && par.bps == 2 && par.sig == 0)
+            || (fmttype == DevFmtInt && par.bps == 4 && par.sig != 0)
+            || (fmttype == DevFmtUInt && par.bps == 4 && par.sig == 0);
+    };
+    if(!match_fmt(mDevice->FmtType, par) || mDevice->channelsFromFmt() != par.rchan
+        || mDevice->Frequency != par.rate)
         throw al::backend_exception{al::backend_error::DeviceError,
             "Failed to set format %s %s %uhz, got %c%u %u-channel %uhz instead",
             DevFmtTypeString(mDevice->FmtType), DevFmtChannelsString(mDevice->FmtChans),
-            mDevice->Frequency, par.sig?'s':'u', par.bits, par.rchan, par.rate};
+            mDevice->Frequency, par.sig?'s':'u', par.bps*8, par.rchan, par.rate};
 
     mRing = RingBuffer::Create(mDevice->BufferSize, par.bps*par.rchan, false);
+    mDevice->BufferSize = static_cast<uint>(mRing->writeSpace());
+    mDevice->UpdateSize = par.round;
 
     setDefaultChannelOrder();
 
-- 
cgit v1.2.3