🛠️🐜 Antkeeper superbuild with dependencies included https://antkeeper.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

690 lines
19 KiB

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