Handle 5.1 Rear with DSound playback
[openal-soft.git] / alc / backends / dsound.cpp
blob3f2bf8df8ed7abc0653f082dfdc805ca5285ec99
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.
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.
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
21 #include "config.h"
23 #include "dsound.h"
25 #define WIN32_LEAN_AND_MEAN
26 #include <windows.h>
28 #include <stdlib.h>
29 #include <stdio.h>
30 #include <memory.h>
32 #include <cguid.h>
33 #include <mmreg.h>
34 #ifndef _WAVEFORMATEXTENSIBLE_
35 #include <ks.h>
36 #include <ksmedia.h>
37 #endif
39 #include <atomic>
40 #include <cassert>
41 #include <thread>
42 #include <string>
43 #include <vector>
44 #include <algorithm>
45 #include <functional>
47 #include "alnumeric.h"
48 #include "comptr.h"
49 #include "core/device.h"
50 #include "core/helpers.h"
51 #include "core/logging.h"
52 #include "dynload.h"
53 #include "ringbuffer.h"
54 #include "strutils.h"
55 #include "threads.h"
57 /* MinGW-w64 needs this for some unknown reason now. */
58 using LPCWAVEFORMATEX = const WAVEFORMATEX*;
59 #include <dsound.h>
62 #ifndef DSSPEAKER_5POINT1
63 # define DSSPEAKER_5POINT1 0x00000006
64 #endif
65 #ifndef DSSPEAKER_5POINT1_BACK
66 # define DSSPEAKER_5POINT1_BACK 0x00000006
67 #endif
68 #ifndef DSSPEAKER_7POINT1
69 # define DSSPEAKER_7POINT1 0x00000007
70 #endif
71 #ifndef DSSPEAKER_7POINT1_SURROUND
72 # define DSSPEAKER_7POINT1_SURROUND 0x00000008
73 #endif
74 #ifndef DSSPEAKER_5POINT1_SURROUND
75 # define DSSPEAKER_5POINT1_SURROUND 0x00000009
76 #endif
79 /* Some headers seem to define these as macros for __uuidof, which is annoying
80 * since some headers don't declare them at all. Hopefully the ifdef is enough
81 * to tell if they need to be declared.
83 #ifndef KSDATAFORMAT_SUBTYPE_PCM
84 DEFINE_GUID(KSDATAFORMAT_SUBTYPE_PCM, 0x00000001, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71);
85 #endif
86 #ifndef KSDATAFORMAT_SUBTYPE_IEEE_FLOAT
87 DEFINE_GUID(KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, 0x00000003, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71);
88 #endif
90 namespace {
92 #define DEVNAME_HEAD "OpenAL Soft on "
95 #ifdef HAVE_DYNLOAD
96 void *ds_handle;
97 HRESULT (WINAPI *pDirectSoundCreate)(const GUID *pcGuidDevice, IDirectSound **ppDS, IUnknown *pUnkOuter);
98 HRESULT (WINAPI *pDirectSoundEnumerateW)(LPDSENUMCALLBACKW pDSEnumCallback, void *pContext);
99 HRESULT (WINAPI *pDirectSoundCaptureCreate)(const GUID *pcGuidDevice, IDirectSoundCapture **ppDSC, IUnknown *pUnkOuter);
100 HRESULT (WINAPI *pDirectSoundCaptureEnumerateW)(LPDSENUMCALLBACKW pDSEnumCallback, void *pContext);
102 #ifndef IN_IDE_PARSER
103 #define DirectSoundCreate pDirectSoundCreate
104 #define DirectSoundEnumerateW pDirectSoundEnumerateW
105 #define DirectSoundCaptureCreate pDirectSoundCaptureCreate
106 #define DirectSoundCaptureEnumerateW pDirectSoundCaptureEnumerateW
107 #endif
108 #endif
111 #define MONO SPEAKER_FRONT_CENTER
112 #define STEREO (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT)
113 #define QUAD (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_BACK_LEFT|SPEAKER_BACK_RIGHT)
114 #define X5DOT1 (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_SIDE_LEFT|SPEAKER_SIDE_RIGHT)
115 #define X5DOT1REAR (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_BACK_LEFT|SPEAKER_BACK_RIGHT)
116 #define X6DOT1 (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_BACK_CENTER|SPEAKER_SIDE_LEFT|SPEAKER_SIDE_RIGHT)
117 #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)
119 #define MAX_UPDATES 128
121 struct DevMap {
122 std::string name;
123 GUID guid;
125 template<typename T0, typename T1>
126 DevMap(T0&& name_, T1&& guid_)
127 : name{std::forward<T0>(name_)}, guid{std::forward<T1>(guid_)}
131 al::vector<DevMap> PlaybackDevices;
132 al::vector<DevMap> CaptureDevices;
134 bool checkName(const al::vector<DevMap> &list, const std::string &name)
136 auto match_name = [&name](const DevMap &entry) -> bool
137 { return entry.name == name; };
138 return std::find_if(list.cbegin(), list.cend(), match_name) != list.cend();
141 BOOL CALLBACK DSoundEnumDevices(GUID *guid, const WCHAR *desc, const WCHAR*, void *data) noexcept
143 if(!guid)
144 return TRUE;
146 auto& devices = *static_cast<al::vector<DevMap>*>(data);
147 const std::string basename{DEVNAME_HEAD + wstr_to_utf8(desc)};
149 int count{1};
150 std::string newname{basename};
151 while(checkName(devices, newname))
153 newname = basename;
154 newname += " #";
155 newname += std::to_string(++count);
157 devices.emplace_back(std::move(newname), *guid);
158 const DevMap &newentry = devices.back();
160 OLECHAR *guidstr{nullptr};
161 HRESULT hr{StringFromCLSID(*guid, &guidstr)};
162 if(SUCCEEDED(hr))
164 TRACE("Got device \"%s\", GUID \"%ls\"\n", newentry.name.c_str(), guidstr);
165 CoTaskMemFree(guidstr);
168 return TRUE;
172 struct DSoundPlayback final : public BackendBase {
173 DSoundPlayback(DeviceBase *device) noexcept : BackendBase{device} { }
174 ~DSoundPlayback() override;
176 int mixerProc();
178 void open(const char *name) override;
179 bool reset() override;
180 void start() override;
181 void stop() override;
183 ComPtr<IDirectSound> mDS;
184 ComPtr<IDirectSoundBuffer> mPrimaryBuffer;
185 ComPtr<IDirectSoundBuffer> mBuffer;
186 ComPtr<IDirectSoundNotify> mNotifies;
187 HANDLE mNotifyEvent{nullptr};
189 std::atomic<bool> mKillNow{true};
190 std::thread mThread;
192 DEF_NEWDEL(DSoundPlayback)
195 DSoundPlayback::~DSoundPlayback()
197 mNotifies = nullptr;
198 mBuffer = nullptr;
199 mPrimaryBuffer = nullptr;
200 mDS = nullptr;
202 if(mNotifyEvent)
203 CloseHandle(mNotifyEvent);
204 mNotifyEvent = nullptr;
208 FORCE_ALIGN int DSoundPlayback::mixerProc()
210 SetRTPriority();
211 althrd_setname(MIXER_THREAD_NAME);
213 DSBCAPS DSBCaps{};
214 DSBCaps.dwSize = sizeof(DSBCaps);
215 HRESULT err{mBuffer->GetCaps(&DSBCaps)};
216 if(FAILED(err))
218 ERR("Failed to get buffer caps: 0x%lx\n", err);
219 mDevice->handleDisconnect("Failure retrieving playback buffer info: 0x%lx", err);
220 return 1;
223 const size_t FrameStep{mDevice->channelsFromFmt()};
224 uint FrameSize{mDevice->frameSizeFromFmt()};
225 DWORD FragSize{mDevice->UpdateSize * FrameSize};
227 bool Playing{false};
228 DWORD LastCursor{0u};
229 mBuffer->GetCurrentPosition(&LastCursor, nullptr);
230 while(!mKillNow.load(std::memory_order_acquire)
231 && mDevice->Connected.load(std::memory_order_acquire))
233 // Get current play cursor
234 DWORD PlayCursor;
235 mBuffer->GetCurrentPosition(&PlayCursor, nullptr);
236 DWORD avail = (PlayCursor-LastCursor+DSBCaps.dwBufferBytes) % DSBCaps.dwBufferBytes;
238 if(avail < FragSize)
240 if(!Playing)
242 err = mBuffer->Play(0, 0, DSBPLAY_LOOPING);
243 if(FAILED(err))
245 ERR("Failed to play buffer: 0x%lx\n", err);
246 mDevice->handleDisconnect("Failure starting playback: 0x%lx", err);
247 return 1;
249 Playing = true;
252 avail = WaitForSingleObjectEx(mNotifyEvent, 2000, FALSE);
253 if(avail != WAIT_OBJECT_0)
254 ERR("WaitForSingleObjectEx error: 0x%lx\n", avail);
255 continue;
257 avail -= avail%FragSize;
259 // Lock output buffer
260 void *WritePtr1, *WritePtr2;
261 DWORD WriteCnt1{0u}, WriteCnt2{0u};
262 err = mBuffer->Lock(LastCursor, avail, &WritePtr1, &WriteCnt1, &WritePtr2, &WriteCnt2, 0);
264 // If the buffer is lost, restore it and lock
265 if(err == DSERR_BUFFERLOST)
267 WARN("Buffer lost, restoring...\n");
268 err = mBuffer->Restore();
269 if(SUCCEEDED(err))
271 Playing = false;
272 LastCursor = 0;
273 err = mBuffer->Lock(0, DSBCaps.dwBufferBytes, &WritePtr1, &WriteCnt1,
274 &WritePtr2, &WriteCnt2, 0);
278 if(SUCCEEDED(err))
280 mDevice->renderSamples(WritePtr1, WriteCnt1/FrameSize, FrameStep);
281 if(WriteCnt2 > 0)
282 mDevice->renderSamples(WritePtr2, WriteCnt2/FrameSize, FrameStep);
284 mBuffer->Unlock(WritePtr1, WriteCnt1, WritePtr2, WriteCnt2);
286 else
288 ERR("Buffer lock error: %#lx\n", err);
289 mDevice->handleDisconnect("Failed to lock output buffer: 0x%lx", err);
290 return 1;
293 // Update old write cursor location
294 LastCursor += WriteCnt1+WriteCnt2;
295 LastCursor %= DSBCaps.dwBufferBytes;
298 return 0;
301 void DSoundPlayback::open(const char *name)
303 HRESULT hr;
304 if(PlaybackDevices.empty())
306 /* Initialize COM to prevent name truncation */
307 HRESULT hrcom{CoInitialize(nullptr)};
308 hr = DirectSoundEnumerateW(DSoundEnumDevices, &PlaybackDevices);
309 if(FAILED(hr))
310 ERR("Error enumerating DirectSound devices (0x%lx)!\n", hr);
311 if(SUCCEEDED(hrcom))
312 CoUninitialize();
315 const GUID *guid{nullptr};
316 if(!name && !PlaybackDevices.empty())
318 name = PlaybackDevices[0].name.c_str();
319 guid = &PlaybackDevices[0].guid;
321 else
323 auto iter = std::find_if(PlaybackDevices.cbegin(), PlaybackDevices.cend(),
324 [name](const DevMap &entry) -> bool { return entry.name == name; });
325 if(iter == PlaybackDevices.cend())
327 GUID id{};
328 hr = CLSIDFromString(utf8_to_wstr(name).c_str(), &id);
329 if(SUCCEEDED(hr))
330 iter = std::find_if(PlaybackDevices.cbegin(), PlaybackDevices.cend(),
331 [&id](const DevMap &entry) -> bool { return entry.guid == id; });
332 if(iter == PlaybackDevices.cend())
333 throw al::backend_exception{al::backend_error::NoDevice,
334 "Device name \"%s\" not found", name};
336 guid = &iter->guid;
339 hr = DS_OK;
340 if(!mNotifyEvent)
342 mNotifyEvent = CreateEventW(nullptr, FALSE, FALSE, nullptr);
343 if(!mNotifyEvent) hr = E_FAIL;
346 //DirectSound Init code
347 ComPtr<IDirectSound> ds;
348 if(SUCCEEDED(hr))
349 hr = DirectSoundCreate(guid, ds.getPtr(), nullptr);
350 if(SUCCEEDED(hr))
351 hr = ds->SetCooperativeLevel(GetForegroundWindow(), DSSCL_PRIORITY);
352 if(FAILED(hr))
353 throw al::backend_exception{al::backend_error::DeviceError, "Device init failed: 0x%08lx",
354 hr};
356 mNotifies = nullptr;
357 mBuffer = nullptr;
358 mPrimaryBuffer = nullptr;
359 mDS = std::move(ds);
361 mDevice->DeviceName = name;
364 bool DSoundPlayback::reset()
366 mNotifies = nullptr;
367 mBuffer = nullptr;
368 mPrimaryBuffer = nullptr;
370 switch(mDevice->FmtType)
372 case DevFmtByte:
373 mDevice->FmtType = DevFmtUByte;
374 break;
375 case DevFmtFloat:
376 if(mDevice->Flags.test(SampleTypeRequest))
377 break;
378 /* fall-through */
379 case DevFmtUShort:
380 mDevice->FmtType = DevFmtShort;
381 break;
382 case DevFmtUInt:
383 mDevice->FmtType = DevFmtInt;
384 break;
385 case DevFmtUByte:
386 case DevFmtShort:
387 case DevFmtInt:
388 break;
391 WAVEFORMATEXTENSIBLE OutputType{};
392 DWORD speakers{};
393 HRESULT hr{mDS->GetSpeakerConfig(&speakers)};
394 if(FAILED(hr))
395 throw al::backend_exception{al::backend_error::DeviceError,
396 "Failed to get speaker config: 0x%08lx", hr};
398 speakers = DSSPEAKER_CONFIG(speakers);
399 if(!mDevice->Flags.test(ChannelsRequest))
401 if(speakers == DSSPEAKER_MONO)
402 mDevice->FmtChans = DevFmtMono;
403 else if(speakers == DSSPEAKER_STEREO || speakers == DSSPEAKER_HEADPHONE)
404 mDevice->FmtChans = DevFmtStereo;
405 else if(speakers == DSSPEAKER_QUAD)
406 mDevice->FmtChans = DevFmtQuad;
407 else if(speakers == DSSPEAKER_5POINT1_SURROUND || speakers == DSSPEAKER_5POINT1_BACK)
408 mDevice->FmtChans = DevFmtX51;
409 else if(speakers == DSSPEAKER_7POINT1 || speakers == DSSPEAKER_7POINT1_SURROUND)
410 mDevice->FmtChans = DevFmtX71;
411 else
412 ERR("Unknown system speaker config: 0x%lx\n", speakers);
414 mDevice->Flags.set(DirectEar, (speakers == DSSPEAKER_HEADPHONE));
415 const bool isRear51{speakers == DSSPEAKER_5POINT1_BACK};
417 switch(mDevice->FmtChans)
419 case DevFmtMono: OutputType.dwChannelMask = MONO; break;
420 case DevFmtAmbi3D: mDevice->FmtChans = DevFmtStereo;
421 /* fall-through */
422 case DevFmtStereo: OutputType.dwChannelMask = STEREO; break;
423 case DevFmtQuad: OutputType.dwChannelMask = QUAD; break;
424 case DevFmtX51: OutputType.dwChannelMask = isRear51 ? X5DOT1REAR : X5DOT1; break;
425 case DevFmtX61: OutputType.dwChannelMask = X6DOT1; break;
426 case DevFmtX71: OutputType.dwChannelMask = X7DOT1; break;
427 case DevFmtX3D71: OutputType.dwChannelMask = X7DOT1; break;
430 retry_open:
431 hr = S_OK;
432 OutputType.Format.wFormatTag = WAVE_FORMAT_PCM;
433 OutputType.Format.nChannels = static_cast<WORD>(mDevice->channelsFromFmt());
434 OutputType.Format.wBitsPerSample = static_cast<WORD>(mDevice->bytesFromFmt() * 8);
435 OutputType.Format.nBlockAlign = static_cast<WORD>(OutputType.Format.nChannels *
436 OutputType.Format.wBitsPerSample / 8);
437 OutputType.Format.nSamplesPerSec = mDevice->Frequency;
438 OutputType.Format.nAvgBytesPerSec = OutputType.Format.nSamplesPerSec *
439 OutputType.Format.nBlockAlign;
440 OutputType.Format.cbSize = 0;
442 if(OutputType.Format.nChannels > 2 || mDevice->FmtType == DevFmtFloat)
444 OutputType.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
445 OutputType.Samples.wValidBitsPerSample = OutputType.Format.wBitsPerSample;
446 OutputType.Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX);
447 if(mDevice->FmtType == DevFmtFloat)
448 OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
449 else
450 OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
452 mPrimaryBuffer = nullptr;
454 else
456 if(SUCCEEDED(hr) && !mPrimaryBuffer)
458 DSBUFFERDESC DSBDescription{};
459 DSBDescription.dwSize = sizeof(DSBDescription);
460 DSBDescription.dwFlags = DSBCAPS_PRIMARYBUFFER;
461 hr = mDS->CreateSoundBuffer(&DSBDescription, mPrimaryBuffer.getPtr(), nullptr);
463 if(SUCCEEDED(hr))
464 hr = mPrimaryBuffer->SetFormat(&OutputType.Format);
467 if(SUCCEEDED(hr))
469 uint num_updates{mDevice->BufferSize / mDevice->UpdateSize};
470 if(num_updates > MAX_UPDATES)
471 num_updates = MAX_UPDATES;
472 mDevice->BufferSize = mDevice->UpdateSize * num_updates;
474 DSBUFFERDESC DSBDescription{};
475 DSBDescription.dwSize = sizeof(DSBDescription);
476 DSBDescription.dwFlags = DSBCAPS_CTRLPOSITIONNOTIFY | DSBCAPS_GETCURRENTPOSITION2
477 | DSBCAPS_GLOBALFOCUS;
478 DSBDescription.dwBufferBytes = mDevice->BufferSize * OutputType.Format.nBlockAlign;
479 DSBDescription.lpwfxFormat = &OutputType.Format;
481 hr = mDS->CreateSoundBuffer(&DSBDescription, mBuffer.getPtr(), nullptr);
482 if(FAILED(hr) && mDevice->FmtType == DevFmtFloat)
484 mDevice->FmtType = DevFmtShort;
485 goto retry_open;
489 if(SUCCEEDED(hr))
491 void *ptr;
492 hr = mBuffer->QueryInterface(IID_IDirectSoundNotify, &ptr);
493 if(SUCCEEDED(hr))
495 mNotifies = ComPtr<IDirectSoundNotify>{static_cast<IDirectSoundNotify*>(ptr)};
497 uint num_updates{mDevice->BufferSize / mDevice->UpdateSize};
498 assert(num_updates <= MAX_UPDATES);
500 std::array<DSBPOSITIONNOTIFY,MAX_UPDATES> nots;
501 for(uint i{0};i < num_updates;++i)
503 nots[i].dwOffset = i * mDevice->UpdateSize * OutputType.Format.nBlockAlign;
504 nots[i].hEventNotify = mNotifyEvent;
506 if(mNotifies->SetNotificationPositions(num_updates, nots.data()) != DS_OK)
507 hr = E_FAIL;
511 if(FAILED(hr))
513 mNotifies = nullptr;
514 mBuffer = nullptr;
515 mPrimaryBuffer = nullptr;
516 return false;
519 ResetEvent(mNotifyEvent);
520 setDefaultWFXChannelOrder();
522 return true;
525 void DSoundPlayback::start()
527 try {
528 mKillNow.store(false, std::memory_order_release);
529 mThread = std::thread{std::mem_fn(&DSoundPlayback::mixerProc), this};
531 catch(std::exception& e) {
532 throw al::backend_exception{al::backend_error::DeviceError,
533 "Failed to start mixing thread: %s", e.what()};
537 void DSoundPlayback::stop()
539 if(mKillNow.exchange(true, std::memory_order_acq_rel) || !mThread.joinable())
540 return;
541 mThread.join();
543 mBuffer->Stop();
547 struct DSoundCapture final : public BackendBase {
548 DSoundCapture(DeviceBase *device) noexcept : BackendBase{device} { }
549 ~DSoundCapture() override;
551 void open(const char *name) override;
552 void start() override;
553 void stop() override;
554 void captureSamples(al::byte *buffer, uint samples) override;
555 uint availableSamples() override;
557 ComPtr<IDirectSoundCapture> mDSC;
558 ComPtr<IDirectSoundCaptureBuffer> mDSCbuffer;
559 DWORD mBufferBytes{0u};
560 DWORD mCursor{0u};
562 RingBufferPtr mRing;
564 DEF_NEWDEL(DSoundCapture)
567 DSoundCapture::~DSoundCapture()
569 if(mDSCbuffer)
571 mDSCbuffer->Stop();
572 mDSCbuffer = nullptr;
574 mDSC = nullptr;
578 void DSoundCapture::open(const char *name)
580 HRESULT hr;
581 if(CaptureDevices.empty())
583 /* Initialize COM to prevent name truncation */
584 HRESULT hrcom{CoInitialize(nullptr)};
585 hr = DirectSoundCaptureEnumerateW(DSoundEnumDevices, &CaptureDevices);
586 if(FAILED(hr))
587 ERR("Error enumerating DirectSound devices (0x%lx)!\n", hr);
588 if(SUCCEEDED(hrcom))
589 CoUninitialize();
592 const GUID *guid{nullptr};
593 if(!name && !CaptureDevices.empty())
595 name = CaptureDevices[0].name.c_str();
596 guid = &CaptureDevices[0].guid;
598 else
600 auto iter = std::find_if(CaptureDevices.cbegin(), CaptureDevices.cend(),
601 [name](const DevMap &entry) -> bool { return entry.name == name; });
602 if(iter == CaptureDevices.cend())
604 GUID id{};
605 hr = CLSIDFromString(utf8_to_wstr(name).c_str(), &id);
606 if(SUCCEEDED(hr))
607 iter = std::find_if(CaptureDevices.cbegin(), CaptureDevices.cend(),
608 [&id](const DevMap &entry) -> bool { return entry.guid == id; });
609 if(iter == CaptureDevices.cend())
610 throw al::backend_exception{al::backend_error::NoDevice,
611 "Device name \"%s\" not found", name};
613 guid = &iter->guid;
616 switch(mDevice->FmtType)
618 case DevFmtByte:
619 case DevFmtUShort:
620 case DevFmtUInt:
621 WARN("%s capture samples not supported\n", DevFmtTypeString(mDevice->FmtType));
622 throw al::backend_exception{al::backend_error::DeviceError,
623 "%s capture samples not supported", DevFmtTypeString(mDevice->FmtType)};
625 case DevFmtUByte:
626 case DevFmtShort:
627 case DevFmtInt:
628 case DevFmtFloat:
629 break;
632 WAVEFORMATEXTENSIBLE InputType{};
633 switch(mDevice->FmtChans)
635 case DevFmtMono: InputType.dwChannelMask = MONO; break;
636 case DevFmtStereo: InputType.dwChannelMask = STEREO; break;
637 case DevFmtQuad: InputType.dwChannelMask = QUAD; break;
638 case DevFmtX51: InputType.dwChannelMask = X5DOT1; break;
639 case DevFmtX61: InputType.dwChannelMask = X6DOT1; break;
640 case DevFmtX71: InputType.dwChannelMask = X7DOT1; break;
641 case DevFmtX3D71:
642 case DevFmtAmbi3D:
643 WARN("%s capture not supported\n", DevFmtChannelsString(mDevice->FmtChans));
644 throw al::backend_exception{al::backend_error::DeviceError, "%s capture not supported",
645 DevFmtChannelsString(mDevice->FmtChans)};
648 InputType.Format.wFormatTag = WAVE_FORMAT_PCM;
649 InputType.Format.nChannels = static_cast<WORD>(mDevice->channelsFromFmt());
650 InputType.Format.wBitsPerSample = static_cast<WORD>(mDevice->bytesFromFmt() * 8);
651 InputType.Format.nBlockAlign = static_cast<WORD>(InputType.Format.nChannels *
652 InputType.Format.wBitsPerSample / 8);
653 InputType.Format.nSamplesPerSec = mDevice->Frequency;
654 InputType.Format.nAvgBytesPerSec = InputType.Format.nSamplesPerSec *
655 InputType.Format.nBlockAlign;
656 InputType.Format.cbSize = 0;
657 InputType.Samples.wValidBitsPerSample = InputType.Format.wBitsPerSample;
658 if(mDevice->FmtType == DevFmtFloat)
659 InputType.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
660 else
661 InputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
663 if(InputType.Format.nChannels > 2 || mDevice->FmtType == DevFmtFloat)
665 InputType.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
666 InputType.Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX);
669 uint samples{mDevice->BufferSize};
670 samples = maxu(samples, 100 * mDevice->Frequency / 1000);
672 DSCBUFFERDESC DSCBDescription{};
673 DSCBDescription.dwSize = sizeof(DSCBDescription);
674 DSCBDescription.dwFlags = 0;
675 DSCBDescription.dwBufferBytes = samples * InputType.Format.nBlockAlign;
676 DSCBDescription.lpwfxFormat = &InputType.Format;
678 //DirectSoundCapture Init code
679 hr = DirectSoundCaptureCreate(guid, mDSC.getPtr(), nullptr);
680 if(SUCCEEDED(hr))
681 mDSC->CreateCaptureBuffer(&DSCBDescription, mDSCbuffer.getPtr(), nullptr);
682 if(SUCCEEDED(hr))
683 mRing = RingBuffer::Create(mDevice->BufferSize, InputType.Format.nBlockAlign, false);
685 if(FAILED(hr))
687 mRing = nullptr;
688 mDSCbuffer = nullptr;
689 mDSC = nullptr;
691 throw al::backend_exception{al::backend_error::DeviceError, "Device init failed: 0x%08lx",
692 hr};
695 mBufferBytes = DSCBDescription.dwBufferBytes;
696 setDefaultWFXChannelOrder();
698 mDevice->DeviceName = name;
701 void DSoundCapture::start()
703 const HRESULT hr{mDSCbuffer->Start(DSCBSTART_LOOPING)};
704 if(FAILED(hr))
705 throw al::backend_exception{al::backend_error::DeviceError,
706 "Failure starting capture: 0x%lx", hr};
709 void DSoundCapture::stop()
711 HRESULT hr{mDSCbuffer->Stop()};
712 if(FAILED(hr))
714 ERR("stop failed: 0x%08lx\n", hr);
715 mDevice->handleDisconnect("Failure stopping capture: 0x%lx", hr);
719 void DSoundCapture::captureSamples(al::byte *buffer, uint samples)
720 { mRing->read(buffer, samples); }
722 uint DSoundCapture::availableSamples()
724 if(!mDevice->Connected.load(std::memory_order_acquire))
725 return static_cast<uint>(mRing->readSpace());
727 const uint FrameSize{mDevice->frameSizeFromFmt()};
728 const DWORD BufferBytes{mBufferBytes};
729 const DWORD LastCursor{mCursor};
731 DWORD ReadCursor{};
732 void *ReadPtr1{}, *ReadPtr2{};
733 DWORD ReadCnt1{}, ReadCnt2{};
734 HRESULT hr{mDSCbuffer->GetCurrentPosition(nullptr, &ReadCursor)};
735 if(SUCCEEDED(hr))
737 const DWORD NumBytes{(BufferBytes+ReadCursor-LastCursor) % BufferBytes};
738 if(!NumBytes) return static_cast<uint>(mRing->readSpace());
739 hr = mDSCbuffer->Lock(LastCursor, NumBytes, &ReadPtr1, &ReadCnt1, &ReadPtr2, &ReadCnt2, 0);
741 if(SUCCEEDED(hr))
743 mRing->write(ReadPtr1, ReadCnt1/FrameSize);
744 if(ReadPtr2 != nullptr && ReadCnt2 > 0)
745 mRing->write(ReadPtr2, ReadCnt2/FrameSize);
746 hr = mDSCbuffer->Unlock(ReadPtr1, ReadCnt1, ReadPtr2, ReadCnt2);
747 mCursor = ReadCursor;
750 if(FAILED(hr))
752 ERR("update failed: 0x%08lx\n", hr);
753 mDevice->handleDisconnect("Failure retrieving capture data: 0x%lx", hr);
756 return static_cast<uint>(mRing->readSpace());
759 } // namespace
762 BackendFactory &DSoundBackendFactory::getFactory()
764 static DSoundBackendFactory factory{};
765 return factory;
768 bool DSoundBackendFactory::init()
770 #ifdef HAVE_DYNLOAD
771 if(!ds_handle)
773 ds_handle = LoadLib("dsound.dll");
774 if(!ds_handle)
776 ERR("Failed to load dsound.dll\n");
777 return false;
780 #define LOAD_FUNC(f) do { \
781 p##f = reinterpret_cast<decltype(p##f)>(GetSymbol(ds_handle, #f)); \
782 if(!p##f) \
784 CloseLib(ds_handle); \
785 ds_handle = nullptr; \
786 return false; \
788 } while(0)
789 LOAD_FUNC(DirectSoundCreate);
790 LOAD_FUNC(DirectSoundEnumerateW);
791 LOAD_FUNC(DirectSoundCaptureCreate);
792 LOAD_FUNC(DirectSoundCaptureEnumerateW);
793 #undef LOAD_FUNC
795 #endif
796 return true;
799 bool DSoundBackendFactory::querySupport(BackendType type)
800 { return (type == BackendType::Playback || type == BackendType::Capture); }
802 std::string DSoundBackendFactory::probe(BackendType type)
804 std::string outnames;
805 auto add_device = [&outnames](const DevMap &entry) -> void
807 /* +1 to also append the null char (to ensure a null-separated list and
808 * double-null terminated list).
810 outnames.append(entry.name.c_str(), entry.name.length()+1);
813 /* Initialize COM to prevent name truncation */
814 HRESULT hr;
815 HRESULT hrcom{CoInitialize(nullptr)};
816 switch(type)
818 case BackendType::Playback:
819 PlaybackDevices.clear();
820 hr = DirectSoundEnumerateW(DSoundEnumDevices, &PlaybackDevices);
821 if(FAILED(hr))
822 ERR("Error enumerating DirectSound playback devices (0x%lx)!\n", hr);
823 std::for_each(PlaybackDevices.cbegin(), PlaybackDevices.cend(), add_device);
824 break;
826 case BackendType::Capture:
827 CaptureDevices.clear();
828 hr = DirectSoundCaptureEnumerateW(DSoundEnumDevices, &CaptureDevices);
829 if(FAILED(hr))
830 ERR("Error enumerating DirectSound capture devices (0x%lx)!\n", hr);
831 std::for_each(CaptureDevices.cbegin(), CaptureDevices.cend(), add_device);
832 break;
834 if(SUCCEEDED(hrcom))
835 CoUninitialize();
837 return outnames;
840 BackendPtr DSoundBackendFactory::createBackend(DeviceBase *device, BackendType type)
842 if(type == BackendType::Playback)
843 return BackendPtr{new DSoundPlayback{device}};
844 if(type == BackendType::Capture)
845 return BackendPtr{new DSoundCapture{device}};
846 return nullptr;