🛠️🐜 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.

627 lines
18 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 "winmm.h"
  22. #include <stdlib.h>
  23. #include <stdio.h>
  24. #include <memory.h>
  25. #include <windows.h>
  26. #include <mmsystem.h>
  27. #include <mmreg.h>
  28. #include <array>
  29. #include <atomic>
  30. #include <thread>
  31. #include <vector>
  32. #include <string>
  33. #include <algorithm>
  34. #include <functional>
  35. #include "alnumeric.h"
  36. #include "core/device.h"
  37. #include "core/helpers.h"
  38. #include "core/logging.h"
  39. #include "ringbuffer.h"
  40. #include "strutils.h"
  41. #include "threads.h"
  42. #ifndef WAVE_FORMAT_IEEE_FLOAT
  43. #define WAVE_FORMAT_IEEE_FLOAT 0x0003
  44. #endif
  45. namespace {
  46. #define DEVNAME_HEAD "OpenAL Soft on "
  47. al::vector<std::string> PlaybackDevices;
  48. al::vector<std::string> CaptureDevices;
  49. bool checkName(const al::vector<std::string> &list, const std::string &name)
  50. { return std::find(list.cbegin(), list.cend(), name) != list.cend(); }
  51. void ProbePlaybackDevices(void)
  52. {
  53. PlaybackDevices.clear();
  54. UINT numdevs{waveOutGetNumDevs()};
  55. PlaybackDevices.reserve(numdevs);
  56. for(UINT i{0};i < numdevs;++i)
  57. {
  58. std::string dname;
  59. WAVEOUTCAPSW WaveCaps{};
  60. if(waveOutGetDevCapsW(i, &WaveCaps, sizeof(WaveCaps)) == MMSYSERR_NOERROR)
  61. {
  62. const std::string basename{DEVNAME_HEAD + wstr_to_utf8(WaveCaps.szPname)};
  63. int count{1};
  64. std::string newname{basename};
  65. while(checkName(PlaybackDevices, newname))
  66. {
  67. newname = basename;
  68. newname += " #";
  69. newname += std::to_string(++count);
  70. }
  71. dname = std::move(newname);
  72. TRACE("Got device \"%s\", ID %u\n", dname.c_str(), i);
  73. }
  74. PlaybackDevices.emplace_back(std::move(dname));
  75. }
  76. }
  77. void ProbeCaptureDevices(void)
  78. {
  79. CaptureDevices.clear();
  80. UINT numdevs{waveInGetNumDevs()};
  81. CaptureDevices.reserve(numdevs);
  82. for(UINT i{0};i < numdevs;++i)
  83. {
  84. std::string dname;
  85. WAVEINCAPSW WaveCaps{};
  86. if(waveInGetDevCapsW(i, &WaveCaps, sizeof(WaveCaps)) == MMSYSERR_NOERROR)
  87. {
  88. const std::string basename{DEVNAME_HEAD + wstr_to_utf8(WaveCaps.szPname)};
  89. int count{1};
  90. std::string newname{basename};
  91. while(checkName(CaptureDevices, newname))
  92. {
  93. newname = basename;
  94. newname += " #";
  95. newname += std::to_string(++count);
  96. }
  97. dname = std::move(newname);
  98. TRACE("Got device \"%s\", ID %u\n", dname.c_str(), i);
  99. }
  100. CaptureDevices.emplace_back(std::move(dname));
  101. }
  102. }
  103. struct WinMMPlayback final : public BackendBase {
  104. WinMMPlayback(DeviceBase *device) noexcept : BackendBase{device} { }
  105. ~WinMMPlayback() override;
  106. void CALLBACK waveOutProc(HWAVEOUT device, UINT msg, DWORD_PTR param1, DWORD_PTR param2) noexcept;
  107. static void CALLBACK waveOutProcC(HWAVEOUT device, UINT msg, DWORD_PTR instance, DWORD_PTR param1, DWORD_PTR param2) noexcept
  108. { reinterpret_cast<WinMMPlayback*>(instance)->waveOutProc(device, msg, param1, param2); }
  109. int mixerProc();
  110. void open(const char *name) override;
  111. bool reset() override;
  112. void start() override;
  113. void stop() override;
  114. std::atomic<uint> mWritable{0u};
  115. al::semaphore mSem;
  116. uint mIdx{0u};
  117. std::array<WAVEHDR,4> mWaveBuffer{};
  118. HWAVEOUT mOutHdl{nullptr};
  119. WAVEFORMATEX mFormat{};
  120. std::atomic<bool> mKillNow{true};
  121. std::thread mThread;
  122. DEF_NEWDEL(WinMMPlayback)
  123. };
  124. WinMMPlayback::~WinMMPlayback()
  125. {
  126. if(mOutHdl)
  127. waveOutClose(mOutHdl);
  128. mOutHdl = nullptr;
  129. al_free(mWaveBuffer[0].lpData);
  130. std::fill(mWaveBuffer.begin(), mWaveBuffer.end(), WAVEHDR{});
  131. }
  132. /* WinMMPlayback::waveOutProc
  133. *
  134. * Posts a message to 'WinMMPlayback::mixerProc' everytime a WaveOut Buffer is
  135. * completed and returns to the application (for more data)
  136. */
  137. void CALLBACK WinMMPlayback::waveOutProc(HWAVEOUT, UINT msg, DWORD_PTR, DWORD_PTR) noexcept
  138. {
  139. if(msg != WOM_DONE) return;
  140. mWritable.fetch_add(1, std::memory_order_acq_rel);
  141. mSem.post();
  142. }
  143. FORCE_ALIGN int WinMMPlayback::mixerProc()
  144. {
  145. SetRTPriority();
  146. althrd_setname(MIXER_THREAD_NAME);
  147. while(!mKillNow.load(std::memory_order_acquire)
  148. && mDevice->Connected.load(std::memory_order_acquire))
  149. {
  150. uint todo{mWritable.load(std::memory_order_acquire)};
  151. if(todo < 1)
  152. {
  153. mSem.wait();
  154. continue;
  155. }
  156. size_t widx{mIdx};
  157. do {
  158. WAVEHDR &waveHdr = mWaveBuffer[widx];
  159. if(++widx == mWaveBuffer.size()) widx = 0;
  160. mDevice->renderSamples(waveHdr.lpData, mDevice->UpdateSize, mFormat.nChannels);
  161. mWritable.fetch_sub(1, std::memory_order_acq_rel);
  162. waveOutWrite(mOutHdl, &waveHdr, sizeof(WAVEHDR));
  163. } while(--todo);
  164. mIdx = static_cast<uint>(widx);
  165. }
  166. return 0;
  167. }
  168. void WinMMPlayback::open(const char *name)
  169. {
  170. if(PlaybackDevices.empty())
  171. ProbePlaybackDevices();
  172. // Find the Device ID matching the deviceName if valid
  173. auto iter = name ?
  174. std::find(PlaybackDevices.cbegin(), PlaybackDevices.cend(), name) :
  175. PlaybackDevices.cbegin();
  176. if(iter == PlaybackDevices.cend())
  177. throw al::backend_exception{al::backend_error::NoDevice, "Device name \"%s\" not found",
  178. name};
  179. auto DeviceID = static_cast<UINT>(std::distance(PlaybackDevices.cbegin(), iter));
  180. DevFmtType fmttype{mDevice->FmtType};
  181. retry_open:
  182. WAVEFORMATEX format{};
  183. if(fmttype == DevFmtFloat)
  184. {
  185. format.wFormatTag = WAVE_FORMAT_IEEE_FLOAT;
  186. format.wBitsPerSample = 32;
  187. }
  188. else
  189. {
  190. format.wFormatTag = WAVE_FORMAT_PCM;
  191. if(fmttype == DevFmtUByte || fmttype == DevFmtByte)
  192. format.wBitsPerSample = 8;
  193. else
  194. format.wBitsPerSample = 16;
  195. }
  196. format.nChannels = ((mDevice->FmtChans == DevFmtMono) ? 1 : 2);
  197. format.nBlockAlign = static_cast<WORD>(format.wBitsPerSample * format.nChannels / 8);
  198. format.nSamplesPerSec = mDevice->Frequency;
  199. format.nAvgBytesPerSec = format.nSamplesPerSec * format.nBlockAlign;
  200. format.cbSize = 0;
  201. HWAVEOUT outHandle{};
  202. MMRESULT res{waveOutOpen(&outHandle, DeviceID, &format,
  203. reinterpret_cast<DWORD_PTR>(&WinMMPlayback::waveOutProcC),
  204. reinterpret_cast<DWORD_PTR>(this), CALLBACK_FUNCTION)};
  205. if(res != MMSYSERR_NOERROR)
  206. {
  207. if(fmttype == DevFmtFloat)
  208. {
  209. fmttype = DevFmtShort;
  210. goto retry_open;
  211. }
  212. throw al::backend_exception{al::backend_error::DeviceError, "waveOutOpen failed: %u", res};
  213. }
  214. if(mOutHdl)
  215. waveOutClose(mOutHdl);
  216. mOutHdl = outHandle;
  217. mFormat = format;
  218. mDevice->DeviceName = PlaybackDevices[DeviceID];
  219. }
  220. bool WinMMPlayback::reset()
  221. {
  222. mDevice->BufferSize = static_cast<uint>(uint64_t{mDevice->BufferSize} *
  223. mFormat.nSamplesPerSec / mDevice->Frequency);
  224. mDevice->BufferSize = (mDevice->BufferSize+3) & ~0x3u;
  225. mDevice->UpdateSize = mDevice->BufferSize / 4;
  226. mDevice->Frequency = mFormat.nSamplesPerSec;
  227. if(mFormat.wFormatTag == WAVE_FORMAT_IEEE_FLOAT)
  228. {
  229. if(mFormat.wBitsPerSample == 32)
  230. mDevice->FmtType = DevFmtFloat;
  231. else
  232. {
  233. ERR("Unhandled IEEE float sample depth: %d\n", mFormat.wBitsPerSample);
  234. return false;
  235. }
  236. }
  237. else if(mFormat.wFormatTag == WAVE_FORMAT_PCM)
  238. {
  239. if(mFormat.wBitsPerSample == 16)
  240. mDevice->FmtType = DevFmtShort;
  241. else if(mFormat.wBitsPerSample == 8)
  242. mDevice->FmtType = DevFmtUByte;
  243. else
  244. {
  245. ERR("Unhandled PCM sample depth: %d\n", mFormat.wBitsPerSample);
  246. return false;
  247. }
  248. }
  249. else
  250. {
  251. ERR("Unhandled format tag: 0x%04x\n", mFormat.wFormatTag);
  252. return false;
  253. }
  254. if(mFormat.nChannels >= 2)
  255. mDevice->FmtChans = DevFmtStereo;
  256. else if(mFormat.nChannels == 1)
  257. mDevice->FmtChans = DevFmtMono;
  258. else
  259. {
  260. ERR("Unhandled channel count: %d\n", mFormat.nChannels);
  261. return false;
  262. }
  263. setDefaultWFXChannelOrder();
  264. uint BufferSize{mDevice->UpdateSize * mFormat.nChannels * mDevice->bytesFromFmt()};
  265. al_free(mWaveBuffer[0].lpData);
  266. mWaveBuffer[0] = WAVEHDR{};
  267. mWaveBuffer[0].lpData = static_cast<char*>(al_calloc(16, BufferSize * mWaveBuffer.size()));
  268. mWaveBuffer[0].dwBufferLength = BufferSize;
  269. for(size_t i{1};i < mWaveBuffer.size();i++)
  270. {
  271. mWaveBuffer[i] = WAVEHDR{};
  272. mWaveBuffer[i].lpData = mWaveBuffer[i-1].lpData + mWaveBuffer[i-1].dwBufferLength;
  273. mWaveBuffer[i].dwBufferLength = BufferSize;
  274. }
  275. mIdx = 0;
  276. return true;
  277. }
  278. void WinMMPlayback::start()
  279. {
  280. try {
  281. for(auto &waveHdr : mWaveBuffer)
  282. waveOutPrepareHeader(mOutHdl, &waveHdr, sizeof(WAVEHDR));
  283. mWritable.store(static_cast<uint>(mWaveBuffer.size()), std::memory_order_release);
  284. mKillNow.store(false, std::memory_order_release);
  285. mThread = std::thread{std::mem_fn(&WinMMPlayback::mixerProc), this};
  286. }
  287. catch(std::exception& e) {
  288. throw al::backend_exception{al::backend_error::DeviceError,
  289. "Failed to start mixing thread: %s", e.what()};
  290. }
  291. }
  292. void WinMMPlayback::stop()
  293. {
  294. if(mKillNow.exchange(true, std::memory_order_acq_rel) || !mThread.joinable())
  295. return;
  296. mThread.join();
  297. while(mWritable.load(std::memory_order_acquire) < mWaveBuffer.size())
  298. mSem.wait();
  299. for(auto &waveHdr : mWaveBuffer)
  300. waveOutUnprepareHeader(mOutHdl, &waveHdr, sizeof(WAVEHDR));
  301. mWritable.store(0, std::memory_order_release);
  302. }
  303. struct WinMMCapture final : public BackendBase {
  304. WinMMCapture(DeviceBase *device) noexcept : BackendBase{device} { }
  305. ~WinMMCapture() override;
  306. void CALLBACK waveInProc(HWAVEIN device, UINT msg, DWORD_PTR param1, DWORD_PTR param2) noexcept;
  307. static void CALLBACK waveInProcC(HWAVEIN device, UINT msg, DWORD_PTR instance, DWORD_PTR param1, DWORD_PTR param2) noexcept
  308. { reinterpret_cast<WinMMCapture*>(instance)->waveInProc(device, msg, param1, param2); }
  309. int captureProc();
  310. void open(const char *name) override;
  311. void start() override;
  312. void stop() override;
  313. void captureSamples(al::byte *buffer, uint samples) override;
  314. uint availableSamples() override;
  315. std::atomic<uint> mReadable{0u};
  316. al::semaphore mSem;
  317. uint mIdx{0};
  318. std::array<WAVEHDR,4> mWaveBuffer{};
  319. HWAVEIN mInHdl{nullptr};
  320. RingBufferPtr mRing{nullptr};
  321. WAVEFORMATEX mFormat{};
  322. std::atomic<bool> mKillNow{true};
  323. std::thread mThread;
  324. DEF_NEWDEL(WinMMCapture)
  325. };
  326. WinMMCapture::~WinMMCapture()
  327. {
  328. // Close the Wave device
  329. if(mInHdl)
  330. waveInClose(mInHdl);
  331. mInHdl = nullptr;
  332. al_free(mWaveBuffer[0].lpData);
  333. std::fill(mWaveBuffer.begin(), mWaveBuffer.end(), WAVEHDR{});
  334. }
  335. /* WinMMCapture::waveInProc
  336. *
  337. * Posts a message to 'WinMMCapture::captureProc' everytime a WaveIn Buffer is
  338. * completed and returns to the application (with more data).
  339. */
  340. void CALLBACK WinMMCapture::waveInProc(HWAVEIN, UINT msg, DWORD_PTR, DWORD_PTR) noexcept
  341. {
  342. if(msg != WIM_DATA) return;
  343. mReadable.fetch_add(1, std::memory_order_acq_rel);
  344. mSem.post();
  345. }
  346. int WinMMCapture::captureProc()
  347. {
  348. althrd_setname(RECORD_THREAD_NAME);
  349. while(!mKillNow.load(std::memory_order_acquire) &&
  350. mDevice->Connected.load(std::memory_order_acquire))
  351. {
  352. uint todo{mReadable.load(std::memory_order_acquire)};
  353. if(todo < 1)
  354. {
  355. mSem.wait();
  356. continue;
  357. }
  358. size_t widx{mIdx};
  359. do {
  360. WAVEHDR &waveHdr = mWaveBuffer[widx];
  361. widx = (widx+1) % mWaveBuffer.size();
  362. mRing->write(waveHdr.lpData, waveHdr.dwBytesRecorded / mFormat.nBlockAlign);
  363. mReadable.fetch_sub(1, std::memory_order_acq_rel);
  364. waveInAddBuffer(mInHdl, &waveHdr, sizeof(WAVEHDR));
  365. } while(--todo);
  366. mIdx = static_cast<uint>(widx);
  367. }
  368. return 0;
  369. }
  370. void WinMMCapture::open(const char *name)
  371. {
  372. if(CaptureDevices.empty())
  373. ProbeCaptureDevices();
  374. // Find the Device ID matching the deviceName if valid
  375. auto iter = name ?
  376. std::find(CaptureDevices.cbegin(), CaptureDevices.cend(), name) :
  377. CaptureDevices.cbegin();
  378. if(iter == CaptureDevices.cend())
  379. throw al::backend_exception{al::backend_error::NoDevice, "Device name \"%s\" not found",
  380. name};
  381. auto DeviceID = static_cast<UINT>(std::distance(CaptureDevices.cbegin(), iter));
  382. switch(mDevice->FmtChans)
  383. {
  384. case DevFmtMono:
  385. case DevFmtStereo:
  386. break;
  387. case DevFmtQuad:
  388. case DevFmtX51:
  389. case DevFmtX61:
  390. case DevFmtX71:
  391. case DevFmtX3D71:
  392. case DevFmtAmbi3D:
  393. throw al::backend_exception{al::backend_error::DeviceError, "%s capture not supported",
  394. DevFmtChannelsString(mDevice->FmtChans)};
  395. }
  396. switch(mDevice->FmtType)
  397. {
  398. case DevFmtUByte:
  399. case DevFmtShort:
  400. case DevFmtInt:
  401. case DevFmtFloat:
  402. break;
  403. case DevFmtByte:
  404. case DevFmtUShort:
  405. case DevFmtUInt:
  406. throw al::backend_exception{al::backend_error::DeviceError, "%s samples not supported",
  407. DevFmtTypeString(mDevice->FmtType)};
  408. }
  409. mFormat = WAVEFORMATEX{};
  410. mFormat.wFormatTag = (mDevice->FmtType == DevFmtFloat) ?
  411. WAVE_FORMAT_IEEE_FLOAT : WAVE_FORMAT_PCM;
  412. mFormat.nChannels = static_cast<WORD>(mDevice->channelsFromFmt());
  413. mFormat.wBitsPerSample = static_cast<WORD>(mDevice->bytesFromFmt() * 8);
  414. mFormat.nBlockAlign = static_cast<WORD>(mFormat.wBitsPerSample * mFormat.nChannels / 8);
  415. mFormat.nSamplesPerSec = mDevice->Frequency;
  416. mFormat.nAvgBytesPerSec = mFormat.nSamplesPerSec * mFormat.nBlockAlign;
  417. mFormat.cbSize = 0;
  418. MMRESULT res{waveInOpen(&mInHdl, DeviceID, &mFormat,
  419. reinterpret_cast<DWORD_PTR>(&WinMMCapture::waveInProcC),
  420. reinterpret_cast<DWORD_PTR>(this), CALLBACK_FUNCTION)};
  421. if(res != MMSYSERR_NOERROR)
  422. throw al::backend_exception{al::backend_error::DeviceError, "waveInOpen failed: %u", res};
  423. // Ensure each buffer is 50ms each
  424. DWORD BufferSize{mFormat.nAvgBytesPerSec / 20u};
  425. BufferSize -= (BufferSize % mFormat.nBlockAlign);
  426. // Allocate circular memory buffer for the captured audio
  427. // Make sure circular buffer is at least 100ms in size
  428. uint CapturedDataSize{mDevice->BufferSize};
  429. CapturedDataSize = static_cast<uint>(maxz(CapturedDataSize, BufferSize*mWaveBuffer.size()));
  430. mRing = RingBuffer::Create(CapturedDataSize, mFormat.nBlockAlign, false);
  431. al_free(mWaveBuffer[0].lpData);
  432. mWaveBuffer[0] = WAVEHDR{};
  433. mWaveBuffer[0].lpData = static_cast<char*>(al_calloc(16, BufferSize * mWaveBuffer.size()));
  434. mWaveBuffer[0].dwBufferLength = BufferSize;
  435. for(size_t i{1};i < mWaveBuffer.size();++i)
  436. {
  437. mWaveBuffer[i] = WAVEHDR{};
  438. mWaveBuffer[i].lpData = mWaveBuffer[i-1].lpData + mWaveBuffer[i-1].dwBufferLength;
  439. mWaveBuffer[i].dwBufferLength = mWaveBuffer[i-1].dwBufferLength;
  440. }
  441. mDevice->DeviceName = CaptureDevices[DeviceID];
  442. }
  443. void WinMMCapture::start()
  444. {
  445. try {
  446. for(size_t i{0};i < mWaveBuffer.size();++i)
  447. {
  448. waveInPrepareHeader(mInHdl, &mWaveBuffer[i], sizeof(WAVEHDR));
  449. waveInAddBuffer(mInHdl, &mWaveBuffer[i], sizeof(WAVEHDR));
  450. }
  451. mKillNow.store(false, std::memory_order_release);
  452. mThread = std::thread{std::mem_fn(&WinMMCapture::captureProc), this};
  453. waveInStart(mInHdl);
  454. }
  455. catch(std::exception& e) {
  456. throw al::backend_exception{al::backend_error::DeviceError,
  457. "Failed to start recording thread: %s", e.what()};
  458. }
  459. }
  460. void WinMMCapture::stop()
  461. {
  462. waveInStop(mInHdl);
  463. mKillNow.store(true, std::memory_order_release);
  464. if(mThread.joinable())
  465. {
  466. mSem.post();
  467. mThread.join();
  468. }
  469. waveInReset(mInHdl);
  470. for(size_t i{0};i < mWaveBuffer.size();++i)
  471. waveInUnprepareHeader(mInHdl, &mWaveBuffer[i], sizeof(WAVEHDR));
  472. mReadable.store(0, std::memory_order_release);
  473. mIdx = 0;
  474. }
  475. void WinMMCapture::captureSamples(al::byte *buffer, uint samples)
  476. { mRing->read(buffer, samples); }
  477. uint WinMMCapture::availableSamples()
  478. { return static_cast<uint>(mRing->readSpace()); }
  479. } // namespace
  480. bool WinMMBackendFactory::init()
  481. { return true; }
  482. bool WinMMBackendFactory::querySupport(BackendType type)
  483. { return type == BackendType::Playback || type == BackendType::Capture; }
  484. std::string WinMMBackendFactory::probe(BackendType type)
  485. {
  486. std::string outnames;
  487. auto add_device = [&outnames](const std::string &dname) -> void
  488. {
  489. /* +1 to also append the null char (to ensure a null-separated list and
  490. * double-null terminated list).
  491. */
  492. if(!dname.empty())
  493. outnames.append(dname.c_str(), dname.length()+1);
  494. };
  495. switch(type)
  496. {
  497. case BackendType::Playback:
  498. ProbePlaybackDevices();
  499. std::for_each(PlaybackDevices.cbegin(), PlaybackDevices.cend(), add_device);
  500. break;
  501. case BackendType::Capture:
  502. ProbeCaptureDevices();
  503. std::for_each(CaptureDevices.cbegin(), CaptureDevices.cend(), add_device);
  504. break;
  505. }
  506. return outnames;
  507. }
  508. BackendPtr WinMMBackendFactory::createBackend(DeviceBase *device, BackendType type)
  509. {
  510. if(type == BackendType::Playback)
  511. return BackendPtr{new WinMMPlayback{device}};
  512. if(type == BackendType::Capture)
  513. return BackendPtr{new WinMMCapture{device}};
  514. return nullptr;
  515. }
  516. BackendFactory &WinMMBackendFactory::getFactory()
  517. {
  518. static WinMMBackendFactory factory{};
  519. return factory;
  520. }