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

843 lines
27 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 "dsound.h"
  22. #define WIN32_LEAN_AND_MEAN
  23. #include <windows.h>
  24. #include <stdlib.h>
  25. #include <stdio.h>
  26. #include <memory.h>
  27. #include <cguid.h>
  28. #include <mmreg.h>
  29. #ifndef _WAVEFORMATEXTENSIBLE_
  30. #include <ks.h>
  31. #include <ksmedia.h>
  32. #endif
  33. #include <atomic>
  34. #include <cassert>
  35. #include <thread>
  36. #include <string>
  37. #include <vector>
  38. #include <algorithm>
  39. #include <functional>
  40. #include "alnumeric.h"
  41. #include "comptr.h"
  42. #include "core/device.h"
  43. #include "core/helpers.h"
  44. #include "core/logging.h"
  45. #include "dynload.h"
  46. #include "ringbuffer.h"
  47. #include "strutils.h"
  48. #include "threads.h"
  49. /* MinGW-w64 needs this for some unknown reason now. */
  50. using LPCWAVEFORMATEX = const WAVEFORMATEX*;
  51. #include <dsound.h>
  52. #ifndef DSSPEAKER_5POINT1
  53. # define DSSPEAKER_5POINT1 0x00000006
  54. #endif
  55. #ifndef DSSPEAKER_5POINT1_BACK
  56. # define DSSPEAKER_5POINT1_BACK 0x00000006
  57. #endif
  58. #ifndef DSSPEAKER_7POINT1
  59. # define DSSPEAKER_7POINT1 0x00000007
  60. #endif
  61. #ifndef DSSPEAKER_7POINT1_SURROUND
  62. # define DSSPEAKER_7POINT1_SURROUND 0x00000008
  63. #endif
  64. #ifndef DSSPEAKER_5POINT1_SURROUND
  65. # define DSSPEAKER_5POINT1_SURROUND 0x00000009
  66. #endif
  67. /* Some headers seem to define these as macros for __uuidof, which is annoying
  68. * since some headers don't declare them at all. Hopefully the ifdef is enough
  69. * to tell if they need to be declared.
  70. */
  71. #ifndef KSDATAFORMAT_SUBTYPE_PCM
  72. DEFINE_GUID(KSDATAFORMAT_SUBTYPE_PCM, 0x00000001, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71);
  73. #endif
  74. #ifndef KSDATAFORMAT_SUBTYPE_IEEE_FLOAT
  75. DEFINE_GUID(KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, 0x00000003, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71);
  76. #endif
  77. namespace {
  78. #define DEVNAME_HEAD "OpenAL Soft on "
  79. #ifdef HAVE_DYNLOAD
  80. void *ds_handle;
  81. HRESULT (WINAPI *pDirectSoundCreate)(const GUID *pcGuidDevice, IDirectSound **ppDS, IUnknown *pUnkOuter);
  82. HRESULT (WINAPI *pDirectSoundEnumerateW)(LPDSENUMCALLBACKW pDSEnumCallback, void *pContext);
  83. HRESULT (WINAPI *pDirectSoundCaptureCreate)(const GUID *pcGuidDevice, IDirectSoundCapture **ppDSC, IUnknown *pUnkOuter);
  84. HRESULT (WINAPI *pDirectSoundCaptureEnumerateW)(LPDSENUMCALLBACKW pDSEnumCallback, void *pContext);
  85. #ifndef IN_IDE_PARSER
  86. #define DirectSoundCreate pDirectSoundCreate
  87. #define DirectSoundEnumerateW pDirectSoundEnumerateW
  88. #define DirectSoundCaptureCreate pDirectSoundCaptureCreate
  89. #define DirectSoundCaptureEnumerateW pDirectSoundCaptureEnumerateW
  90. #endif
  91. #endif
  92. #define MONO SPEAKER_FRONT_CENTER
  93. #define STEREO (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT)
  94. #define QUAD (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_BACK_LEFT|SPEAKER_BACK_RIGHT)
  95. #define X5DOT1 (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_SIDE_LEFT|SPEAKER_SIDE_RIGHT)
  96. #define X5DOT1REAR (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_BACK_LEFT|SPEAKER_BACK_RIGHT)
  97. #define X6DOT1 (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_BACK_CENTER|SPEAKER_SIDE_LEFT|SPEAKER_SIDE_RIGHT)
  98. #define X7DOT1 (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_BACK_LEFT|SPEAKER_BACK_RIGHT|SPEAKER_SIDE_LEFT|SPEAKER_SIDE_RIGHT)
  99. #define MAX_UPDATES 128
  100. struct DevMap {
  101. std::string name;
  102. GUID guid;
  103. template<typename T0, typename T1>
  104. DevMap(T0&& name_, T1&& guid_)
  105. : name{std::forward<T0>(name_)}, guid{std::forward<T1>(guid_)}
  106. { }
  107. };
  108. al::vector<DevMap> PlaybackDevices;
  109. al::vector<DevMap> CaptureDevices;
  110. bool checkName(const al::vector<DevMap> &list, const std::string &name)
  111. {
  112. auto match_name = [&name](const DevMap &entry) -> bool
  113. { return entry.name == name; };
  114. return std::find_if(list.cbegin(), list.cend(), match_name) != list.cend();
  115. }
  116. BOOL CALLBACK DSoundEnumDevices(GUID *guid, const WCHAR *desc, const WCHAR*, void *data) noexcept
  117. {
  118. if(!guid)
  119. return TRUE;
  120. auto& devices = *static_cast<al::vector<DevMap>*>(data);
  121. const std::string basename{DEVNAME_HEAD + wstr_to_utf8(desc)};
  122. int count{1};
  123. std::string newname{basename};
  124. while(checkName(devices, newname))
  125. {
  126. newname = basename;
  127. newname += " #";
  128. newname += std::to_string(++count);
  129. }
  130. devices.emplace_back(std::move(newname), *guid);
  131. const DevMap &newentry = devices.back();
  132. OLECHAR *guidstr{nullptr};
  133. HRESULT hr{StringFromCLSID(*guid, &guidstr)};
  134. if(SUCCEEDED(hr))
  135. {
  136. TRACE("Got device \"%s\", GUID \"%ls\"\n", newentry.name.c_str(), guidstr);
  137. CoTaskMemFree(guidstr);
  138. }
  139. return TRUE;
  140. }
  141. struct DSoundPlayback final : public BackendBase {
  142. DSoundPlayback(DeviceBase *device) noexcept : BackendBase{device} { }
  143. ~DSoundPlayback() override;
  144. int mixerProc();
  145. void open(const char *name) override;
  146. bool reset() override;
  147. void start() override;
  148. void stop() override;
  149. ComPtr<IDirectSound> mDS;
  150. ComPtr<IDirectSoundBuffer> mPrimaryBuffer;
  151. ComPtr<IDirectSoundBuffer> mBuffer;
  152. ComPtr<IDirectSoundNotify> mNotifies;
  153. HANDLE mNotifyEvent{nullptr};
  154. std::atomic<bool> mKillNow{true};
  155. std::thread mThread;
  156. DEF_NEWDEL(DSoundPlayback)
  157. };
  158. DSoundPlayback::~DSoundPlayback()
  159. {
  160. mNotifies = nullptr;
  161. mBuffer = nullptr;
  162. mPrimaryBuffer = nullptr;
  163. mDS = nullptr;
  164. if(mNotifyEvent)
  165. CloseHandle(mNotifyEvent);
  166. mNotifyEvent = nullptr;
  167. }
  168. FORCE_ALIGN int DSoundPlayback::mixerProc()
  169. {
  170. SetRTPriority();
  171. althrd_setname(MIXER_THREAD_NAME);
  172. DSBCAPS DSBCaps{};
  173. DSBCaps.dwSize = sizeof(DSBCaps);
  174. HRESULT err{mBuffer->GetCaps(&DSBCaps)};
  175. if(FAILED(err))
  176. {
  177. ERR("Failed to get buffer caps: 0x%lx\n", err);
  178. mDevice->handleDisconnect("Failure retrieving playback buffer info: 0x%lx", err);
  179. return 1;
  180. }
  181. const size_t FrameStep{mDevice->channelsFromFmt()};
  182. uint FrameSize{mDevice->frameSizeFromFmt()};
  183. DWORD FragSize{mDevice->UpdateSize * FrameSize};
  184. bool Playing{false};
  185. DWORD LastCursor{0u};
  186. mBuffer->GetCurrentPosition(&LastCursor, nullptr);
  187. while(!mKillNow.load(std::memory_order_acquire)
  188. && mDevice->Connected.load(std::memory_order_acquire))
  189. {
  190. // Get current play cursor
  191. DWORD PlayCursor;
  192. mBuffer->GetCurrentPosition(&PlayCursor, nullptr);
  193. DWORD avail = (PlayCursor-LastCursor+DSBCaps.dwBufferBytes) % DSBCaps.dwBufferBytes;
  194. if(avail < FragSize)
  195. {
  196. if(!Playing)
  197. {
  198. err = mBuffer->Play(0, 0, DSBPLAY_LOOPING);
  199. if(FAILED(err))
  200. {
  201. ERR("Failed to play buffer: 0x%lx\n", err);
  202. mDevice->handleDisconnect("Failure starting playback: 0x%lx", err);
  203. return 1;
  204. }
  205. Playing = true;
  206. }
  207. avail = WaitForSingleObjectEx(mNotifyEvent, 2000, FALSE);
  208. if(avail != WAIT_OBJECT_0)
  209. ERR("WaitForSingleObjectEx error: 0x%lx\n", avail);
  210. continue;
  211. }
  212. avail -= avail%FragSize;
  213. // Lock output buffer
  214. void *WritePtr1, *WritePtr2;
  215. DWORD WriteCnt1{0u}, WriteCnt2{0u};
  216. err = mBuffer->Lock(LastCursor, avail, &WritePtr1, &WriteCnt1, &WritePtr2, &WriteCnt2, 0);
  217. // If the buffer is lost, restore it and lock
  218. if(err == DSERR_BUFFERLOST)
  219. {
  220. WARN("Buffer lost, restoring...\n");
  221. err = mBuffer->Restore();
  222. if(SUCCEEDED(err))
  223. {
  224. Playing = false;
  225. LastCursor = 0;
  226. err = mBuffer->Lock(0, DSBCaps.dwBufferBytes, &WritePtr1, &WriteCnt1,
  227. &WritePtr2, &WriteCnt2, 0);
  228. }
  229. }
  230. if(SUCCEEDED(err))
  231. {
  232. mDevice->renderSamples(WritePtr1, WriteCnt1/FrameSize, FrameStep);
  233. if(WriteCnt2 > 0)
  234. mDevice->renderSamples(WritePtr2, WriteCnt2/FrameSize, FrameStep);
  235. mBuffer->Unlock(WritePtr1, WriteCnt1, WritePtr2, WriteCnt2);
  236. }
  237. else
  238. {
  239. ERR("Buffer lock error: %#lx\n", err);
  240. mDevice->handleDisconnect("Failed to lock output buffer: 0x%lx", err);
  241. return 1;
  242. }
  243. // Update old write cursor location
  244. LastCursor += WriteCnt1+WriteCnt2;
  245. LastCursor %= DSBCaps.dwBufferBytes;
  246. }
  247. return 0;
  248. }
  249. void DSoundPlayback::open(const char *name)
  250. {
  251. HRESULT hr;
  252. if(PlaybackDevices.empty())
  253. {
  254. /* Initialize COM to prevent name truncation */
  255. HRESULT hrcom{CoInitialize(nullptr)};
  256. hr = DirectSoundEnumerateW(DSoundEnumDevices, &PlaybackDevices);
  257. if(FAILED(hr))
  258. ERR("Error enumerating DirectSound devices (0x%lx)!\n", hr);
  259. if(SUCCEEDED(hrcom))
  260. CoUninitialize();
  261. }
  262. const GUID *guid{nullptr};
  263. if(!name && !PlaybackDevices.empty())
  264. {
  265. name = PlaybackDevices[0].name.c_str();
  266. guid = &PlaybackDevices[0].guid;
  267. }
  268. else
  269. {
  270. auto iter = std::find_if(PlaybackDevices.cbegin(), PlaybackDevices.cend(),
  271. [name](const DevMap &entry) -> bool { return entry.name == name; });
  272. if(iter == PlaybackDevices.cend())
  273. {
  274. GUID id{};
  275. hr = CLSIDFromString(utf8_to_wstr(name).c_str(), &id);
  276. if(SUCCEEDED(hr))
  277. iter = std::find_if(PlaybackDevices.cbegin(), PlaybackDevices.cend(),
  278. [&id](const DevMap &entry) -> bool { return entry.guid == id; });
  279. if(iter == PlaybackDevices.cend())
  280. throw al::backend_exception{al::backend_error::NoDevice,
  281. "Device name \"%s\" not found", name};
  282. }
  283. guid = &iter->guid;
  284. }
  285. hr = DS_OK;
  286. if(!mNotifyEvent)
  287. {
  288. mNotifyEvent = CreateEventW(nullptr, FALSE, FALSE, nullptr);
  289. if(!mNotifyEvent) hr = E_FAIL;
  290. }
  291. //DirectSound Init code
  292. ComPtr<IDirectSound> ds;
  293. if(SUCCEEDED(hr))
  294. hr = DirectSoundCreate(guid, ds.getPtr(), nullptr);
  295. if(SUCCEEDED(hr))
  296. hr = ds->SetCooperativeLevel(GetForegroundWindow(), DSSCL_PRIORITY);
  297. if(FAILED(hr))
  298. throw al::backend_exception{al::backend_error::DeviceError, "Device init failed: 0x%08lx",
  299. hr};
  300. mNotifies = nullptr;
  301. mBuffer = nullptr;
  302. mPrimaryBuffer = nullptr;
  303. mDS = std::move(ds);
  304. mDevice->DeviceName = name;
  305. }
  306. bool DSoundPlayback::reset()
  307. {
  308. mNotifies = nullptr;
  309. mBuffer = nullptr;
  310. mPrimaryBuffer = nullptr;
  311. switch(mDevice->FmtType)
  312. {
  313. case DevFmtByte:
  314. mDevice->FmtType = DevFmtUByte;
  315. break;
  316. case DevFmtFloat:
  317. if(mDevice->Flags.test(SampleTypeRequest))
  318. break;
  319. /* fall-through */
  320. case DevFmtUShort:
  321. mDevice->FmtType = DevFmtShort;
  322. break;
  323. case DevFmtUInt:
  324. mDevice->FmtType = DevFmtInt;
  325. break;
  326. case DevFmtUByte:
  327. case DevFmtShort:
  328. case DevFmtInt:
  329. break;
  330. }
  331. WAVEFORMATEXTENSIBLE OutputType{};
  332. DWORD speakers;
  333. HRESULT hr{mDS->GetSpeakerConfig(&speakers)};
  334. if(SUCCEEDED(hr))
  335. {
  336. speakers = DSSPEAKER_CONFIG(speakers);
  337. if(!mDevice->Flags.test(ChannelsRequest))
  338. {
  339. if(speakers == DSSPEAKER_MONO)
  340. mDevice->FmtChans = DevFmtMono;
  341. else if(speakers == DSSPEAKER_STEREO || speakers == DSSPEAKER_HEADPHONE)
  342. mDevice->FmtChans = DevFmtStereo;
  343. else if(speakers == DSSPEAKER_QUAD)
  344. mDevice->FmtChans = DevFmtQuad;
  345. else if(speakers == DSSPEAKER_5POINT1_SURROUND || speakers == DSSPEAKER_5POINT1_BACK)
  346. mDevice->FmtChans = DevFmtX51;
  347. else if(speakers == DSSPEAKER_7POINT1 || speakers == DSSPEAKER_7POINT1_SURROUND)
  348. mDevice->FmtChans = DevFmtX71;
  349. else
  350. ERR("Unknown system speaker config: 0x%lx\n", speakers);
  351. }
  352. mDevice->Flags.set(DirectEar, (speakers == DSSPEAKER_HEADPHONE));
  353. switch(mDevice->FmtChans)
  354. {
  355. case DevFmtMono: OutputType.dwChannelMask = MONO; break;
  356. case DevFmtAmbi3D: mDevice->FmtChans = DevFmtStereo;
  357. /*fall-through*/
  358. case DevFmtStereo: OutputType.dwChannelMask = STEREO; break;
  359. case DevFmtQuad: OutputType.dwChannelMask = QUAD; break;
  360. case DevFmtX51: OutputType.dwChannelMask = X5DOT1; break;
  361. case DevFmtX61: OutputType.dwChannelMask = X6DOT1; break;
  362. case DevFmtX71: OutputType.dwChannelMask = X7DOT1; break;
  363. }
  364. retry_open:
  365. hr = S_OK;
  366. OutputType.Format.wFormatTag = WAVE_FORMAT_PCM;
  367. OutputType.Format.nChannels = static_cast<WORD>(mDevice->channelsFromFmt());
  368. OutputType.Format.wBitsPerSample = static_cast<WORD>(mDevice->bytesFromFmt() * 8);
  369. OutputType.Format.nBlockAlign = static_cast<WORD>(OutputType.Format.nChannels *
  370. OutputType.Format.wBitsPerSample / 8);
  371. OutputType.Format.nSamplesPerSec = mDevice->Frequency;
  372. OutputType.Format.nAvgBytesPerSec = OutputType.Format.nSamplesPerSec *
  373. OutputType.Format.nBlockAlign;
  374. OutputType.Format.cbSize = 0;
  375. }
  376. if(OutputType.Format.nChannels > 2 || mDevice->FmtType == DevFmtFloat)
  377. {
  378. OutputType.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  379. OutputType.Samples.wValidBitsPerSample = OutputType.Format.wBitsPerSample;
  380. OutputType.Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX);
  381. if(mDevice->FmtType == DevFmtFloat)
  382. OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  383. else
  384. OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
  385. mPrimaryBuffer = nullptr;
  386. }
  387. else
  388. {
  389. if(SUCCEEDED(hr) && !mPrimaryBuffer)
  390. {
  391. DSBUFFERDESC DSBDescription{};
  392. DSBDescription.dwSize = sizeof(DSBDescription);
  393. DSBDescription.dwFlags = DSBCAPS_PRIMARYBUFFER;
  394. hr = mDS->CreateSoundBuffer(&DSBDescription, mPrimaryBuffer.getPtr(), nullptr);
  395. }
  396. if(SUCCEEDED(hr))
  397. hr = mPrimaryBuffer->SetFormat(&OutputType.Format);
  398. }
  399. if(SUCCEEDED(hr))
  400. {
  401. uint num_updates{mDevice->BufferSize / mDevice->UpdateSize};
  402. if(num_updates > MAX_UPDATES)
  403. num_updates = MAX_UPDATES;
  404. mDevice->BufferSize = mDevice->UpdateSize * num_updates;
  405. DSBUFFERDESC DSBDescription{};
  406. DSBDescription.dwSize = sizeof(DSBDescription);
  407. DSBDescription.dwFlags = DSBCAPS_CTRLPOSITIONNOTIFY | DSBCAPS_GETCURRENTPOSITION2
  408. | DSBCAPS_GLOBALFOCUS;
  409. DSBDescription.dwBufferBytes = mDevice->BufferSize * OutputType.Format.nBlockAlign;
  410. DSBDescription.lpwfxFormat = &OutputType.Format;
  411. hr = mDS->CreateSoundBuffer(&DSBDescription, mBuffer.getPtr(), nullptr);
  412. if(FAILED(hr) && mDevice->FmtType == DevFmtFloat)
  413. {
  414. mDevice->FmtType = DevFmtShort;
  415. goto retry_open;
  416. }
  417. }
  418. if(SUCCEEDED(hr))
  419. {
  420. void *ptr;
  421. hr = mBuffer->QueryInterface(IID_IDirectSoundNotify, &ptr);
  422. if(SUCCEEDED(hr))
  423. {
  424. mNotifies = ComPtr<IDirectSoundNotify>{static_cast<IDirectSoundNotify*>(ptr)};
  425. uint num_updates{mDevice->BufferSize / mDevice->UpdateSize};
  426. assert(num_updates <= MAX_UPDATES);
  427. std::array<DSBPOSITIONNOTIFY,MAX_UPDATES> nots;
  428. for(uint i{0};i < num_updates;++i)
  429. {
  430. nots[i].dwOffset = i * mDevice->UpdateSize * OutputType.Format.nBlockAlign;
  431. nots[i].hEventNotify = mNotifyEvent;
  432. }
  433. if(mNotifies->SetNotificationPositions(num_updates, nots.data()) != DS_OK)
  434. hr = E_FAIL;
  435. }
  436. }
  437. if(FAILED(hr))
  438. {
  439. mNotifies = nullptr;
  440. mBuffer = nullptr;
  441. mPrimaryBuffer = nullptr;
  442. return false;
  443. }
  444. ResetEvent(mNotifyEvent);
  445. setChannelOrderFromWFXMask(OutputType.dwChannelMask);
  446. return true;
  447. }
  448. void DSoundPlayback::start()
  449. {
  450. try {
  451. mKillNow.store(false, std::memory_order_release);
  452. mThread = std::thread{std::mem_fn(&DSoundPlayback::mixerProc), this};
  453. }
  454. catch(std::exception& e) {
  455. throw al::backend_exception{al::backend_error::DeviceError,
  456. "Failed to start mixing thread: %s", e.what()};
  457. }
  458. }
  459. void DSoundPlayback::stop()
  460. {
  461. if(mKillNow.exchange(true, std::memory_order_acq_rel) || !mThread.joinable())
  462. return;
  463. mThread.join();
  464. mBuffer->Stop();
  465. }
  466. struct DSoundCapture final : public BackendBase {
  467. DSoundCapture(DeviceBase *device) noexcept : BackendBase{device} { }
  468. ~DSoundCapture() override;
  469. void open(const char *name) override;
  470. void start() override;
  471. void stop() override;
  472. void captureSamples(al::byte *buffer, uint samples) override;
  473. uint availableSamples() override;
  474. ComPtr<IDirectSoundCapture> mDSC;
  475. ComPtr<IDirectSoundCaptureBuffer> mDSCbuffer;
  476. DWORD mBufferBytes{0u};
  477. DWORD mCursor{0u};
  478. RingBufferPtr mRing;
  479. DEF_NEWDEL(DSoundCapture)
  480. };
  481. DSoundCapture::~DSoundCapture()
  482. {
  483. if(mDSCbuffer)
  484. {
  485. mDSCbuffer->Stop();
  486. mDSCbuffer = nullptr;
  487. }
  488. mDSC = nullptr;
  489. }
  490. void DSoundCapture::open(const char *name)
  491. {
  492. HRESULT hr;
  493. if(CaptureDevices.empty())
  494. {
  495. /* Initialize COM to prevent name truncation */
  496. HRESULT hrcom{CoInitialize(nullptr)};
  497. hr = DirectSoundCaptureEnumerateW(DSoundEnumDevices, &CaptureDevices);
  498. if(FAILED(hr))
  499. ERR("Error enumerating DirectSound devices (0x%lx)!\n", hr);
  500. if(SUCCEEDED(hrcom))
  501. CoUninitialize();
  502. }
  503. const GUID *guid{nullptr};
  504. if(!name && !CaptureDevices.empty())
  505. {
  506. name = CaptureDevices[0].name.c_str();
  507. guid = &CaptureDevices[0].guid;
  508. }
  509. else
  510. {
  511. auto iter = std::find_if(CaptureDevices.cbegin(), CaptureDevices.cend(),
  512. [name](const DevMap &entry) -> bool { return entry.name == name; });
  513. if(iter == CaptureDevices.cend())
  514. {
  515. GUID id{};
  516. hr = CLSIDFromString(utf8_to_wstr(name).c_str(), &id);
  517. if(SUCCEEDED(hr))
  518. iter = std::find_if(CaptureDevices.cbegin(), CaptureDevices.cend(),
  519. [&id](const DevMap &entry) -> bool { return entry.guid == id; });
  520. if(iter == CaptureDevices.cend())
  521. throw al::backend_exception{al::backend_error::NoDevice,
  522. "Device name \"%s\" not found", name};
  523. }
  524. guid = &iter->guid;
  525. }
  526. switch(mDevice->FmtType)
  527. {
  528. case DevFmtByte:
  529. case DevFmtUShort:
  530. case DevFmtUInt:
  531. WARN("%s capture samples not supported\n", DevFmtTypeString(mDevice->FmtType));
  532. throw al::backend_exception{al::backend_error::DeviceError,
  533. "%s capture samples not supported", DevFmtTypeString(mDevice->FmtType)};
  534. case DevFmtUByte:
  535. case DevFmtShort:
  536. case DevFmtInt:
  537. case DevFmtFloat:
  538. break;
  539. }
  540. WAVEFORMATEXTENSIBLE InputType{};
  541. switch(mDevice->FmtChans)
  542. {
  543. case DevFmtMono: InputType.dwChannelMask = MONO; break;
  544. case DevFmtStereo: InputType.dwChannelMask = STEREO; break;
  545. case DevFmtQuad: InputType.dwChannelMask = QUAD; break;
  546. case DevFmtX51: InputType.dwChannelMask = X5DOT1; break;
  547. case DevFmtX61: InputType.dwChannelMask = X6DOT1; break;
  548. case DevFmtX71: InputType.dwChannelMask = X7DOT1; break;
  549. case DevFmtAmbi3D:
  550. WARN("%s capture not supported\n", DevFmtChannelsString(mDevice->FmtChans));
  551. throw al::backend_exception{al::backend_error::DeviceError, "%s capture not supported",
  552. DevFmtChannelsString(mDevice->FmtChans)};
  553. }
  554. InputType.Format.wFormatTag = WAVE_FORMAT_PCM;
  555. InputType.Format.nChannels = static_cast<WORD>(mDevice->channelsFromFmt());
  556. InputType.Format.wBitsPerSample = static_cast<WORD>(mDevice->bytesFromFmt() * 8);
  557. InputType.Format.nBlockAlign = static_cast<WORD>(InputType.Format.nChannels *
  558. InputType.Format.wBitsPerSample / 8);
  559. InputType.Format.nSamplesPerSec = mDevice->Frequency;
  560. InputType.Format.nAvgBytesPerSec = InputType.Format.nSamplesPerSec *
  561. InputType.Format.nBlockAlign;
  562. InputType.Format.cbSize = 0;
  563. InputType.Samples.wValidBitsPerSample = InputType.Format.wBitsPerSample;
  564. if(mDevice->FmtType == DevFmtFloat)
  565. InputType.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  566. else
  567. InputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
  568. if(InputType.Format.nChannels > 2 || mDevice->FmtType == DevFmtFloat)
  569. {
  570. InputType.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  571. InputType.Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX);
  572. }
  573. uint samples{mDevice->BufferSize};
  574. samples = maxu(samples, 100 * mDevice->Frequency / 1000);
  575. DSCBUFFERDESC DSCBDescription{};
  576. DSCBDescription.dwSize = sizeof(DSCBDescription);
  577. DSCBDescription.dwFlags = 0;
  578. DSCBDescription.dwBufferBytes = samples * InputType.Format.nBlockAlign;
  579. DSCBDescription.lpwfxFormat = &InputType.Format;
  580. //DirectSoundCapture Init code
  581. hr = DirectSoundCaptureCreate(guid, mDSC.getPtr(), nullptr);
  582. if(SUCCEEDED(hr))
  583. mDSC->CreateCaptureBuffer(&DSCBDescription, mDSCbuffer.getPtr(), nullptr);
  584. if(SUCCEEDED(hr))
  585. mRing = RingBuffer::Create(mDevice->BufferSize, InputType.Format.nBlockAlign, false);
  586. if(FAILED(hr))
  587. {
  588. mRing = nullptr;
  589. mDSCbuffer = nullptr;
  590. mDSC = nullptr;
  591. throw al::backend_exception{al::backend_error::DeviceError, "Device init failed: 0x%08lx",
  592. hr};
  593. }
  594. mBufferBytes = DSCBDescription.dwBufferBytes;
  595. setChannelOrderFromWFXMask(InputType.dwChannelMask);
  596. mDevice->DeviceName = name;
  597. }
  598. void DSoundCapture::start()
  599. {
  600. const HRESULT hr{mDSCbuffer->Start(DSCBSTART_LOOPING)};
  601. if(FAILED(hr))
  602. throw al::backend_exception{al::backend_error::DeviceError,
  603. "Failure starting capture: 0x%lx", hr};
  604. }
  605. void DSoundCapture::stop()
  606. {
  607. HRESULT hr{mDSCbuffer->Stop()};
  608. if(FAILED(hr))
  609. {
  610. ERR("stop failed: 0x%08lx\n", hr);
  611. mDevice->handleDisconnect("Failure stopping capture: 0x%lx", hr);
  612. }
  613. }
  614. void DSoundCapture::captureSamples(al::byte *buffer, uint samples)
  615. { mRing->read(buffer, samples); }
  616. uint DSoundCapture::availableSamples()
  617. {
  618. if(!mDevice->Connected.load(std::memory_order_acquire))
  619. return static_cast<uint>(mRing->readSpace());
  620. const uint FrameSize{mDevice->frameSizeFromFmt()};
  621. const DWORD BufferBytes{mBufferBytes};
  622. const DWORD LastCursor{mCursor};
  623. DWORD ReadCursor{};
  624. void *ReadPtr1{}, *ReadPtr2{};
  625. DWORD ReadCnt1{}, ReadCnt2{};
  626. HRESULT hr{mDSCbuffer->GetCurrentPosition(nullptr, &ReadCursor)};
  627. if(SUCCEEDED(hr))
  628. {
  629. const DWORD NumBytes{(BufferBytes+ReadCursor-LastCursor) % BufferBytes};
  630. if(!NumBytes) return static_cast<uint>(mRing->readSpace());
  631. hr = mDSCbuffer->Lock(LastCursor, NumBytes, &ReadPtr1, &ReadCnt1, &ReadPtr2, &ReadCnt2, 0);
  632. }
  633. if(SUCCEEDED(hr))
  634. {
  635. mRing->write(ReadPtr1, ReadCnt1/FrameSize);
  636. if(ReadPtr2 != nullptr && ReadCnt2 > 0)
  637. mRing->write(ReadPtr2, ReadCnt2/FrameSize);
  638. hr = mDSCbuffer->Unlock(ReadPtr1, ReadCnt1, ReadPtr2, ReadCnt2);
  639. mCursor = ReadCursor;
  640. }
  641. if(FAILED(hr))
  642. {
  643. ERR("update failed: 0x%08lx\n", hr);
  644. mDevice->handleDisconnect("Failure retrieving capture data: 0x%lx", hr);
  645. }
  646. return static_cast<uint>(mRing->readSpace());
  647. }
  648. } // namespace
  649. BackendFactory &DSoundBackendFactory::getFactory()
  650. {
  651. static DSoundBackendFactory factory{};
  652. return factory;
  653. }
  654. bool DSoundBackendFactory::init()
  655. {
  656. #ifdef HAVE_DYNLOAD
  657. if(!ds_handle)
  658. {
  659. ds_handle = LoadLib("dsound.dll");
  660. if(!ds_handle)
  661. {
  662. ERR("Failed to load dsound.dll\n");
  663. return false;
  664. }
  665. #define LOAD_FUNC(f) do { \
  666. p##f = reinterpret_cast<decltype(p##f)>(GetSymbol(ds_handle, #f)); \
  667. if(!p##f) \
  668. { \
  669. CloseLib(ds_handle); \
  670. ds_handle = nullptr; \
  671. return false; \
  672. } \
  673. } while(0)
  674. LOAD_FUNC(DirectSoundCreate);
  675. LOAD_FUNC(DirectSoundEnumerateW);
  676. LOAD_FUNC(DirectSoundCaptureCreate);
  677. LOAD_FUNC(DirectSoundCaptureEnumerateW);
  678. #undef LOAD_FUNC
  679. }
  680. #endif
  681. return true;
  682. }
  683. bool DSoundBackendFactory::querySupport(BackendType type)
  684. { return (type == BackendType::Playback || type == BackendType::Capture); }
  685. std::string DSoundBackendFactory::probe(BackendType type)
  686. {
  687. std::string outnames;
  688. auto add_device = [&outnames](const DevMap &entry) -> void
  689. {
  690. /* +1 to also append the null char (to ensure a null-separated list and
  691. * double-null terminated list).
  692. */
  693. outnames.append(entry.name.c_str(), entry.name.length()+1);
  694. };
  695. /* Initialize COM to prevent name truncation */
  696. HRESULT hr;
  697. HRESULT hrcom{CoInitialize(nullptr)};
  698. switch(type)
  699. {
  700. case BackendType::Playback:
  701. PlaybackDevices.clear();
  702. hr = DirectSoundEnumerateW(DSoundEnumDevices, &PlaybackDevices);
  703. if(FAILED(hr))
  704. ERR("Error enumerating DirectSound playback devices (0x%lx)!\n", hr);
  705. std::for_each(PlaybackDevices.cbegin(), PlaybackDevices.cend(), add_device);
  706. break;
  707. case BackendType::Capture:
  708. CaptureDevices.clear();
  709. hr = DirectSoundCaptureEnumerateW(DSoundEnumDevices, &CaptureDevices);
  710. if(FAILED(hr))
  711. ERR("Error enumerating DirectSound capture devices (0x%lx)!\n", hr);
  712. std::for_each(CaptureDevices.cbegin(), CaptureDevices.cend(), add_device);
  713. break;
  714. }
  715. if(SUCCEEDED(hrcom))
  716. CoUninitialize();
  717. return outnames;
  718. }
  719. BackendPtr DSoundBackendFactory::createBackend(DeviceBase *device, BackendType type)
  720. {
  721. if(type == BackendType::Playback)
  722. return BackendPtr{new DSoundPlayback{device}};
  723. if(type == BackendType::Capture)
  724. return BackendPtr{new DSoundCapture{device}};
  725. return nullptr;
  726. }