]> git.tdb.fi Git - ext/openal.git/blob - alc/backends/oss.cpp
Import OpenAL Soft 1.23.1 sources
[ext/openal.git] / alc / backends / oss.cpp
1 /**
2  * OpenAL cross platform audio library
3  * Copyright (C) 1999-2007 by authors.
4  * This library is free software; you can redistribute it and/or
5  *  modify it under the terms of the GNU Library General Public
6  *  License as published by the Free Software Foundation; either
7  *  version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
11  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  *  Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library General Public
15  *  License along with this library; if not, write to the
16  *  Free Software Foundation, Inc.,
17  *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18  * Or go to http://www.gnu.org/copyleft/lgpl.html
19  */
20
21 #include "config.h"
22
23 #include "oss.h"
24
25 #include <fcntl.h>
26 #include <poll.h>
27 #include <sys/ioctl.h>
28 #include <sys/stat.h>
29 #include <unistd.h>
30
31 #include <algorithm>
32 #include <atomic>
33 #include <cerrno>
34 #include <cstdio>
35 #include <cstring>
36 #include <exception>
37 #include <functional>
38 #include <memory>
39 #include <new>
40 #include <string>
41 #include <thread>
42 #include <utility>
43
44 #include "albyte.h"
45 #include "alc/alconfig.h"
46 #include "almalloc.h"
47 #include "alnumeric.h"
48 #include "aloptional.h"
49 #include "core/device.h"
50 #include "core/helpers.h"
51 #include "core/logging.h"
52 #include "ringbuffer.h"
53 #include "threads.h"
54 #include "vector.h"
55
56 #include <sys/soundcard.h>
57
58 /*
59  * The OSS documentation talks about SOUND_MIXER_READ, but the header
60  * only contains MIXER_READ. Play safe. Same for WRITE.
61  */
62 #ifndef SOUND_MIXER_READ
63 #define SOUND_MIXER_READ MIXER_READ
64 #endif
65 #ifndef SOUND_MIXER_WRITE
66 #define SOUND_MIXER_WRITE MIXER_WRITE
67 #endif
68
69 #if defined(SOUND_VERSION) && (SOUND_VERSION < 0x040000)
70 #define ALC_OSS_COMPAT
71 #endif
72 #ifndef SNDCTL_AUDIOINFO
73 #define ALC_OSS_COMPAT
74 #endif
75
76 /*
77  * FreeBSD strongly discourages the use of specific devices,
78  * such as those returned in oss_audioinfo.devnode
79  */
80 #ifdef __FreeBSD__
81 #define ALC_OSS_DEVNODE_TRUC
82 #endif
83
84 namespace {
85
86 constexpr char DefaultName[] = "OSS Default";
87 std::string DefaultPlayback{"/dev/dsp"};
88 std::string DefaultCapture{"/dev/dsp"};
89
90 struct DevMap {
91     std::string name;
92     std::string device_name;
93 };
94
95 al::vector<DevMap> PlaybackDevices;
96 al::vector<DevMap> CaptureDevices;
97
98
99 #ifdef ALC_OSS_COMPAT
100
101 #define DSP_CAP_OUTPUT 0x00020000
102 #define DSP_CAP_INPUT 0x00010000
103 void ALCossListPopulate(al::vector<DevMap> &devlist, int type)
104 {
105     devlist.emplace_back(DevMap{DefaultName, (type==DSP_CAP_INPUT) ? DefaultCapture : DefaultPlayback});
106 }
107
108 #else
109
110 void ALCossListAppend(al::vector<DevMap> &list, al::span<const char> handle, al::span<const char> path)
111 {
112 #ifdef ALC_OSS_DEVNODE_TRUC
113     for(size_t i{0};i < path.size();++i)
114     {
115         if(path[i] == '.' && handle.size() + i >= path.size())
116         {
117             const size_t hoffset{handle.size() + i - path.size()};
118             if(strncmp(path.data() + i, handle.data() + hoffset, path.size() - i) == 0)
119                 handle = handle.first(hoffset);
120             path = path.first(i);
121         }
122     }
123 #endif
124     if(handle.empty())
125         handle = path;
126
127     std::string basename{handle.data(), handle.size()};
128     std::string devname{path.data(), path.size()};
129
130     auto match_devname = [&devname](const DevMap &entry) -> bool
131     { return entry.device_name == devname; };
132     if(std::find_if(list.cbegin(), list.cend(), match_devname) != list.cend())
133         return;
134
135     auto checkName = [&list](const std::string &name) -> bool
136     {
137         auto match_name = [&name](const DevMap &entry) -> bool { return entry.name == name; };
138         return std::find_if(list.cbegin(), list.cend(), match_name) != list.cend();
139     };
140     int count{1};
141     std::string newname{basename};
142     while(checkName(newname))
143     {
144         newname = basename;
145         newname += " #";
146         newname += std::to_string(++count);
147     }
148
149     list.emplace_back(DevMap{std::move(newname), std::move(devname)});
150     const DevMap &entry = list.back();
151
152     TRACE("Got device \"%s\", \"%s\"\n", entry.name.c_str(), entry.device_name.c_str());
153 }
154
155 void ALCossListPopulate(al::vector<DevMap> &devlist, int type_flag)
156 {
157     int fd{open("/dev/mixer", O_RDONLY)};
158     if(fd < 0)
159     {
160         TRACE("Could not open /dev/mixer: %s\n", strerror(errno));
161         goto done;
162     }
163
164     oss_sysinfo si;
165     if(ioctl(fd, SNDCTL_SYSINFO, &si) == -1)
166     {
167         TRACE("SNDCTL_SYSINFO failed: %s\n", strerror(errno));
168         goto done;
169     }
170
171     for(int i{0};i < si.numaudios;i++)
172     {
173         oss_audioinfo ai;
174         ai.dev = i;
175         if(ioctl(fd, SNDCTL_AUDIOINFO, &ai) == -1)
176         {
177             ERR("SNDCTL_AUDIOINFO (%d) failed: %s\n", i, strerror(errno));
178             continue;
179         }
180         if(!(ai.caps&type_flag) || ai.devnode[0] == '\0')
181             continue;
182
183         al::span<const char> handle;
184         if(ai.handle[0] != '\0')
185             handle = {ai.handle, strnlen(ai.handle, sizeof(ai.handle))};
186         else
187             handle = {ai.name, strnlen(ai.name, sizeof(ai.name))};
188         al::span<const char> devnode{ai.devnode, strnlen(ai.devnode, sizeof(ai.devnode))};
189
190         ALCossListAppend(devlist, handle, devnode);
191     }
192
193 done:
194     if(fd >= 0)
195         close(fd);
196     fd = -1;
197
198     const char *defdev{((type_flag==DSP_CAP_INPUT) ? DefaultCapture : DefaultPlayback).c_str()};
199     auto iter = std::find_if(devlist.cbegin(), devlist.cend(),
200         [defdev](const DevMap &entry) -> bool
201         { return entry.device_name == defdev; }
202     );
203     if(iter == devlist.cend())
204         devlist.insert(devlist.begin(), DevMap{DefaultName, defdev});
205     else
206     {
207         DevMap entry{std::move(*iter)};
208         devlist.erase(iter);
209         devlist.insert(devlist.begin(), std::move(entry));
210     }
211     devlist.shrink_to_fit();
212 }
213
214 #endif
215
216 uint log2i(uint x)
217 {
218     uint y{0};
219     while(x > 1)
220     {
221         x >>= 1;
222         y++;
223     }
224     return y;
225 }
226
227
228 struct OSSPlayback final : public BackendBase {
229     OSSPlayback(DeviceBase *device) noexcept : BackendBase{device} { }
230     ~OSSPlayback() override;
231
232     int mixerProc();
233
234     void open(const char *name) override;
235     bool reset() override;
236     void start() override;
237     void stop() override;
238
239     int mFd{-1};
240
241     al::vector<al::byte> mMixData;
242
243     std::atomic<bool> mKillNow{true};
244     std::thread mThread;
245
246     DEF_NEWDEL(OSSPlayback)
247 };
248
249 OSSPlayback::~OSSPlayback()
250 {
251     if(mFd != -1)
252         ::close(mFd);
253     mFd = -1;
254 }
255
256
257 int OSSPlayback::mixerProc()
258 {
259     SetRTPriority();
260     althrd_setname(MIXER_THREAD_NAME);
261
262     const size_t frame_step{mDevice->channelsFromFmt()};
263     const size_t frame_size{mDevice->frameSizeFromFmt()};
264
265     while(!mKillNow.load(std::memory_order_acquire)
266         && mDevice->Connected.load(std::memory_order_acquire))
267     {
268         pollfd pollitem{};
269         pollitem.fd = mFd;
270         pollitem.events = POLLOUT;
271
272         int pret{poll(&pollitem, 1, 1000)};
273         if(pret < 0)
274         {
275             if(errno == EINTR || errno == EAGAIN)
276                 continue;
277             ERR("poll failed: %s\n", strerror(errno));
278             mDevice->handleDisconnect("Failed waiting for playback buffer: %s", strerror(errno));
279             break;
280         }
281         else if(pret == 0)
282         {
283             WARN("poll timeout\n");
284             continue;
285         }
286
287         al::byte *write_ptr{mMixData.data()};
288         size_t to_write{mMixData.size()};
289         mDevice->renderSamples(write_ptr, static_cast<uint>(to_write/frame_size), frame_step);
290         while(to_write > 0 && !mKillNow.load(std::memory_order_acquire))
291         {
292             ssize_t wrote{write(mFd, write_ptr, to_write)};
293             if(wrote < 0)
294             {
295                 if(errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
296                     continue;
297                 ERR("write failed: %s\n", strerror(errno));
298                 mDevice->handleDisconnect("Failed writing playback samples: %s", strerror(errno));
299                 break;
300             }
301
302             to_write -= static_cast<size_t>(wrote);
303             write_ptr += wrote;
304         }
305     }
306
307     return 0;
308 }
309
310
311 void OSSPlayback::open(const char *name)
312 {
313     const char *devname{DefaultPlayback.c_str()};
314     if(!name)
315         name = DefaultName;
316     else
317     {
318         if(PlaybackDevices.empty())
319             ALCossListPopulate(PlaybackDevices, DSP_CAP_OUTPUT);
320
321         auto iter = std::find_if(PlaybackDevices.cbegin(), PlaybackDevices.cend(),
322             [&name](const DevMap &entry) -> bool
323             { return entry.name == name; }
324         );
325         if(iter == PlaybackDevices.cend())
326             throw al::backend_exception{al::backend_error::NoDevice,
327                 "Device name \"%s\" not found", name};
328         devname = iter->device_name.c_str();
329     }
330
331     int fd{::open(devname, O_WRONLY)};
332     if(fd == -1)
333         throw al::backend_exception{al::backend_error::NoDevice, "Could not open %s: %s", devname,
334             strerror(errno)};
335
336     if(mFd != -1)
337         ::close(mFd);
338     mFd = fd;
339
340     mDevice->DeviceName = name;
341 }
342
343 bool OSSPlayback::reset()
344 {
345     int ossFormat{};
346     switch(mDevice->FmtType)
347     {
348         case DevFmtByte:
349             ossFormat = AFMT_S8;
350             break;
351         case DevFmtUByte:
352             ossFormat = AFMT_U8;
353             break;
354         case DevFmtUShort:
355         case DevFmtInt:
356         case DevFmtUInt:
357         case DevFmtFloat:
358             mDevice->FmtType = DevFmtShort;
359             /* fall-through */
360         case DevFmtShort:
361             ossFormat = AFMT_S16_NE;
362             break;
363     }
364
365     uint periods{mDevice->BufferSize / mDevice->UpdateSize};
366     uint numChannels{mDevice->channelsFromFmt()};
367     uint ossSpeed{mDevice->Frequency};
368     uint frameSize{numChannels * mDevice->bytesFromFmt()};
369     /* According to the OSS spec, 16 bytes (log2(16)) is the minimum. */
370     uint log2FragmentSize{maxu(log2i(mDevice->UpdateSize*frameSize), 4)};
371     uint numFragmentsLogSize{(periods << 16) | log2FragmentSize};
372
373     audio_buf_info info{};
374     const char *err;
375 #define CHECKERR(func) if((func) < 0) {                                       \
376     err = #func;                                                              \
377     goto err;                                                                 \
378 }
379     /* Don't fail if SETFRAGMENT fails. We can handle just about anything
380      * that's reported back via GETOSPACE */
381     ioctl(mFd, SNDCTL_DSP_SETFRAGMENT, &numFragmentsLogSize);
382     CHECKERR(ioctl(mFd, SNDCTL_DSP_SETFMT, &ossFormat));
383     CHECKERR(ioctl(mFd, SNDCTL_DSP_CHANNELS, &numChannels));
384     CHECKERR(ioctl(mFd, SNDCTL_DSP_SPEED, &ossSpeed));
385     CHECKERR(ioctl(mFd, SNDCTL_DSP_GETOSPACE, &info));
386     if(0)
387     {
388     err:
389         ERR("%s failed: %s\n", err, strerror(errno));
390         return false;
391     }
392 #undef CHECKERR
393
394     if(mDevice->channelsFromFmt() != numChannels)
395     {
396         ERR("Failed to set %s, got %d channels instead\n", DevFmtChannelsString(mDevice->FmtChans),
397             numChannels);
398         return false;
399     }
400
401     if(!((ossFormat == AFMT_S8 && mDevice->FmtType == DevFmtByte) ||
402          (ossFormat == AFMT_U8 && mDevice->FmtType == DevFmtUByte) ||
403          (ossFormat == AFMT_S16_NE && mDevice->FmtType == DevFmtShort)))
404     {
405         ERR("Failed to set %s samples, got OSS format %#x\n", DevFmtTypeString(mDevice->FmtType),
406             ossFormat);
407         return false;
408     }
409
410     mDevice->Frequency = ossSpeed;
411     mDevice->UpdateSize = static_cast<uint>(info.fragsize) / frameSize;
412     mDevice->BufferSize = static_cast<uint>(info.fragments) * mDevice->UpdateSize;
413
414     setDefaultChannelOrder();
415
416     mMixData.resize(mDevice->UpdateSize * mDevice->frameSizeFromFmt());
417
418     return true;
419 }
420
421 void OSSPlayback::start()
422 {
423     try {
424         mKillNow.store(false, std::memory_order_release);
425         mThread = std::thread{std::mem_fn(&OSSPlayback::mixerProc), this};
426     }
427     catch(std::exception& e) {
428         throw al::backend_exception{al::backend_error::DeviceError,
429             "Failed to start mixing thread: %s", e.what()};
430     }
431 }
432
433 void OSSPlayback::stop()
434 {
435     if(mKillNow.exchange(true, std::memory_order_acq_rel) || !mThread.joinable())
436         return;
437     mThread.join();
438
439     if(ioctl(mFd, SNDCTL_DSP_RESET) != 0)
440         ERR("Error resetting device: %s\n", strerror(errno));
441 }
442
443
444 struct OSScapture final : public BackendBase {
445     OSScapture(DeviceBase *device) noexcept : BackendBase{device} { }
446     ~OSScapture() override;
447
448     int recordProc();
449
450     void open(const char *name) override;
451     void start() override;
452     void stop() override;
453     void captureSamples(al::byte *buffer, uint samples) override;
454     uint availableSamples() override;
455
456     int mFd{-1};
457
458     RingBufferPtr mRing{nullptr};
459
460     std::atomic<bool> mKillNow{true};
461     std::thread mThread;
462
463     DEF_NEWDEL(OSScapture)
464 };
465
466 OSScapture::~OSScapture()
467 {
468     if(mFd != -1)
469         close(mFd);
470     mFd = -1;
471 }
472
473
474 int OSScapture::recordProc()
475 {
476     SetRTPriority();
477     althrd_setname(RECORD_THREAD_NAME);
478
479     const size_t frame_size{mDevice->frameSizeFromFmt()};
480     while(!mKillNow.load(std::memory_order_acquire))
481     {
482         pollfd pollitem{};
483         pollitem.fd = mFd;
484         pollitem.events = POLLIN;
485
486         int sret{poll(&pollitem, 1, 1000)};
487         if(sret < 0)
488         {
489             if(errno == EINTR || errno == EAGAIN)
490                 continue;
491             ERR("poll failed: %s\n", strerror(errno));
492             mDevice->handleDisconnect("Failed to check capture samples: %s", strerror(errno));
493             break;
494         }
495         else if(sret == 0)
496         {
497             WARN("poll timeout\n");
498             continue;
499         }
500
501         auto vec = mRing->getWriteVector();
502         if(vec.first.len > 0)
503         {
504             ssize_t amt{read(mFd, vec.first.buf, vec.first.len*frame_size)};
505             if(amt < 0)
506             {
507                 ERR("read failed: %s\n", strerror(errno));
508                 mDevice->handleDisconnect("Failed reading capture samples: %s", strerror(errno));
509                 break;
510             }
511             mRing->writeAdvance(static_cast<size_t>(amt)/frame_size);
512         }
513     }
514
515     return 0;
516 }
517
518
519 void OSScapture::open(const char *name)
520 {
521     const char *devname{DefaultCapture.c_str()};
522     if(!name)
523         name = DefaultName;
524     else
525     {
526         if(CaptureDevices.empty())
527             ALCossListPopulate(CaptureDevices, DSP_CAP_INPUT);
528
529         auto iter = std::find_if(CaptureDevices.cbegin(), CaptureDevices.cend(),
530             [&name](const DevMap &entry) -> bool
531             { return entry.name == name; }
532         );
533         if(iter == CaptureDevices.cend())
534             throw al::backend_exception{al::backend_error::NoDevice,
535                 "Device name \"%s\" not found", name};
536         devname = iter->device_name.c_str();
537     }
538
539     mFd = ::open(devname, O_RDONLY);
540     if(mFd == -1)
541         throw al::backend_exception{al::backend_error::NoDevice, "Could not open %s: %s", devname,
542             strerror(errno)};
543
544     int ossFormat{};
545     switch(mDevice->FmtType)
546     {
547     case DevFmtByte:
548         ossFormat = AFMT_S8;
549         break;
550     case DevFmtUByte:
551         ossFormat = AFMT_U8;
552         break;
553     case DevFmtShort:
554         ossFormat = AFMT_S16_NE;
555         break;
556     case DevFmtUShort:
557     case DevFmtInt:
558     case DevFmtUInt:
559     case DevFmtFloat:
560         throw al::backend_exception{al::backend_error::DeviceError,
561             "%s capture samples not supported", DevFmtTypeString(mDevice->FmtType)};
562     }
563
564     uint periods{4};
565     uint numChannels{mDevice->channelsFromFmt()};
566     uint frameSize{numChannels * mDevice->bytesFromFmt()};
567     uint ossSpeed{mDevice->Frequency};
568     /* according to the OSS spec, 16 bytes are the minimum */
569     uint log2FragmentSize{maxu(log2i(mDevice->BufferSize * frameSize / periods), 4)};
570     uint numFragmentsLogSize{(periods << 16) | log2FragmentSize};
571
572     audio_buf_info info{};
573 #define CHECKERR(func) if((func) < 0) {                                       \
574     throw al::backend_exception{al::backend_error::DeviceError, #func " failed: %s", \
575         strerror(errno)};                                                     \
576 }
577     CHECKERR(ioctl(mFd, SNDCTL_DSP_SETFRAGMENT, &numFragmentsLogSize));
578     CHECKERR(ioctl(mFd, SNDCTL_DSP_SETFMT, &ossFormat));
579     CHECKERR(ioctl(mFd, SNDCTL_DSP_CHANNELS, &numChannels));
580     CHECKERR(ioctl(mFd, SNDCTL_DSP_SPEED, &ossSpeed));
581     CHECKERR(ioctl(mFd, SNDCTL_DSP_GETISPACE, &info));
582 #undef CHECKERR
583
584     if(mDevice->channelsFromFmt() != numChannels)
585         throw al::backend_exception{al::backend_error::DeviceError,
586             "Failed to set %s, got %d channels instead", DevFmtChannelsString(mDevice->FmtChans),
587             numChannels};
588
589     if(!((ossFormat == AFMT_S8 && mDevice->FmtType == DevFmtByte)
590         || (ossFormat == AFMT_U8 && mDevice->FmtType == DevFmtUByte)
591         || (ossFormat == AFMT_S16_NE && mDevice->FmtType == DevFmtShort)))
592         throw al::backend_exception{al::backend_error::DeviceError,
593             "Failed to set %s samples, got OSS format %#x", DevFmtTypeString(mDevice->FmtType),
594             ossFormat};
595
596     mRing = RingBuffer::Create(mDevice->BufferSize, frameSize, false);
597
598     mDevice->DeviceName = name;
599 }
600
601 void OSScapture::start()
602 {
603     try {
604         mKillNow.store(false, std::memory_order_release);
605         mThread = std::thread{std::mem_fn(&OSScapture::recordProc), this};
606     }
607     catch(std::exception& e) {
608         throw al::backend_exception{al::backend_error::DeviceError,
609             "Failed to start recording thread: %s", e.what()};
610     }
611 }
612
613 void OSScapture::stop()
614 {
615     if(mKillNow.exchange(true, std::memory_order_acq_rel) || !mThread.joinable())
616         return;
617     mThread.join();
618
619     if(ioctl(mFd, SNDCTL_DSP_RESET) != 0)
620         ERR("Error resetting device: %s\n", strerror(errno));
621 }
622
623 void OSScapture::captureSamples(al::byte *buffer, uint samples)
624 { mRing->read(buffer, samples); }
625
626 uint OSScapture::availableSamples()
627 { return static_cast<uint>(mRing->readSpace()); }
628
629 } // namespace
630
631
632 BackendFactory &OSSBackendFactory::getFactory()
633 {
634     static OSSBackendFactory factory{};
635     return factory;
636 }
637
638 bool OSSBackendFactory::init()
639 {
640     if(auto devopt = ConfigValueStr(nullptr, "oss", "device"))
641         DefaultPlayback = std::move(*devopt);
642     if(auto capopt = ConfigValueStr(nullptr, "oss", "capture"))
643         DefaultCapture = std::move(*capopt);
644
645     return true;
646 }
647
648 bool OSSBackendFactory::querySupport(BackendType type)
649 { return (type == BackendType::Playback || type == BackendType::Capture); }
650
651 std::string OSSBackendFactory::probe(BackendType type)
652 {
653     std::string outnames;
654
655     auto add_device = [&outnames](const DevMap &entry) -> void
656     {
657         struct stat buf;
658         if(stat(entry.device_name.c_str(), &buf) == 0)
659         {
660             /* Includes null char. */
661             outnames.append(entry.name.c_str(), entry.name.length()+1);
662         }
663     };
664
665     switch(type)
666     {
667     case BackendType::Playback:
668         PlaybackDevices.clear();
669         ALCossListPopulate(PlaybackDevices, DSP_CAP_OUTPUT);
670         std::for_each(PlaybackDevices.cbegin(), PlaybackDevices.cend(), add_device);
671         break;
672
673     case BackendType::Capture:
674         CaptureDevices.clear();
675         ALCossListPopulate(CaptureDevices, DSP_CAP_INPUT);
676         std::for_each(CaptureDevices.cbegin(), CaptureDevices.cend(), add_device);
677         break;
678     }
679
680     return outnames;
681 }
682
683 BackendPtr OSSBackendFactory::createBackend(DeviceBase *device, BackendType type)
684 {
685     if(type == BackendType::Playback)
686         return BackendPtr{new OSSPlayback{device}};
687     if(type == BackendType::Capture)
688         return BackendPtr{new OSScapture{device}};
689     return nullptr;
690 }