Add "fast" variants for the bsinc resamplers
[openal-soft.git] / alc / backends / dsound.cpp
blobc7014e33e1a7840dc7f935ef98d2a45483a68ba1
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 "backends/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 "alcmain.h"
48 #include "alu.h"
49 #include "ringbuffer.h"
50 #include "compat.h"
51 #include "dynload.h"
52 #include "strutils.h"
53 #include "threads.h"
55 /* MinGW-w64 needs this for some unknown reason now. */
56 using LPCWAVEFORMATEX = const WAVEFORMATEX*;
57 #include <dsound.h>
60 #ifndef DSSPEAKER_5POINT1
61 # define DSSPEAKER_5POINT1 0x00000006
62 #endif
63 #ifndef DSSPEAKER_5POINT1_BACK
64 # define DSSPEAKER_5POINT1_BACK 0x00000006
65 #endif
66 #ifndef DSSPEAKER_7POINT1
67 # define DSSPEAKER_7POINT1 0x00000007
68 #endif
69 #ifndef DSSPEAKER_7POINT1_SURROUND
70 # define DSSPEAKER_7POINT1_SURROUND 0x00000008
71 #endif
72 #ifndef DSSPEAKER_5POINT1_SURROUND
73 # define DSSPEAKER_5POINT1_SURROUND 0x00000009
74 #endif
77 /* Some headers seem to define these as macros for __uuidof, which is annoying
78 * since some headers don't declare them at all. Hopefully the ifdef is enough
79 * to tell if they need to be declared.
81 #ifndef KSDATAFORMAT_SUBTYPE_PCM
82 DEFINE_GUID(KSDATAFORMAT_SUBTYPE_PCM, 0x00000001, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71);
83 #endif
84 #ifndef KSDATAFORMAT_SUBTYPE_IEEE_FLOAT
85 DEFINE_GUID(KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, 0x00000003, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71);
86 #endif
88 namespace {
90 #define DEVNAME_HEAD "OpenAL Soft on "
93 #ifdef HAVE_DYNLOAD
94 void *ds_handle;
95 HRESULT (WINAPI *pDirectSoundCreate)(const GUID *pcGuidDevice, IDirectSound **ppDS, IUnknown *pUnkOuter);
96 HRESULT (WINAPI *pDirectSoundEnumerateW)(LPDSENUMCALLBACKW pDSEnumCallback, void *pContext);
97 HRESULT (WINAPI *pDirectSoundCaptureCreate)(const GUID *pcGuidDevice, IDirectSoundCapture **ppDSC, IUnknown *pUnkOuter);
98 HRESULT (WINAPI *pDirectSoundCaptureEnumerateW)(LPDSENUMCALLBACKW pDSEnumCallback, void *pContext);
100 #ifndef IN_IDE_PARSER
101 #define DirectSoundCreate pDirectSoundCreate
102 #define DirectSoundEnumerateW pDirectSoundEnumerateW
103 #define DirectSoundCaptureCreate pDirectSoundCaptureCreate
104 #define DirectSoundCaptureEnumerateW pDirectSoundCaptureEnumerateW
105 #endif
106 #endif
109 #define MAX_UPDATES 128
111 struct DevMap {
112 std::string name;
113 GUID guid;
115 template<typename T0, typename T1>
116 DevMap(T0&& name_, T1&& guid_)
117 : name{std::forward<T0>(name_)}, guid{std::forward<T1>(guid_)}
121 al::vector<DevMap> PlaybackDevices;
122 al::vector<DevMap> CaptureDevices;
124 bool checkName(const al::vector<DevMap> &list, const std::string &name)
126 return std::find_if(list.cbegin(), list.cend(),
127 [&name](const DevMap &entry) -> bool
128 { return entry.name == name; }
129 ) != list.cend();
132 BOOL CALLBACK DSoundEnumDevices(GUID *guid, const WCHAR *desc, const WCHAR*, void *data)
134 if(!guid)
135 return TRUE;
137 auto& devices = *static_cast<al::vector<DevMap>*>(data);
138 const std::string basename{DEVNAME_HEAD + wstr_to_utf8(desc)};
140 int count{1};
141 std::string newname{basename};
142 while(checkName(devices, newname))
144 newname = basename;
145 newname += " #";
146 newname += std::to_string(++count);
148 devices.emplace_back(std::move(newname), *guid);
149 const DevMap &newentry = devices.back();
151 OLECHAR *guidstr{nullptr};
152 HRESULT hr{StringFromCLSID(*guid, &guidstr)};
153 if(SUCCEEDED(hr))
155 TRACE("Got device \"%s\", GUID \"%ls\"\n", newentry.name.c_str(), guidstr);
156 CoTaskMemFree(guidstr);
159 return TRUE;
163 struct DSoundPlayback final : public BackendBase {
164 DSoundPlayback(ALCdevice *device) noexcept : BackendBase{device} { }
165 ~DSoundPlayback() override;
167 int mixerProc();
169 ALCenum open(const ALCchar *name) override;
170 bool reset() override;
171 bool start() override;
172 void stop() override;
174 IDirectSound *mDS{nullptr};
175 IDirectSoundBuffer *mPrimaryBuffer{nullptr};
176 IDirectSoundBuffer *mBuffer{nullptr};
177 IDirectSoundNotify *mNotifies{nullptr};
178 HANDLE mNotifyEvent{nullptr};
180 std::atomic<bool> mKillNow{true};
181 std::thread mThread;
183 DEF_NEWDEL(DSoundPlayback)
186 DSoundPlayback::~DSoundPlayback()
188 if(mNotifies)
189 mNotifies->Release();
190 mNotifies = nullptr;
191 if(mBuffer)
192 mBuffer->Release();
193 mBuffer = nullptr;
194 if(mPrimaryBuffer)
195 mPrimaryBuffer->Release();
196 mPrimaryBuffer = nullptr;
198 if(mDS)
199 mDS->Release();
200 mDS = nullptr;
201 if(mNotifyEvent)
202 CloseHandle(mNotifyEvent);
203 mNotifyEvent = nullptr;
207 FORCE_ALIGN int DSoundPlayback::mixerProc()
209 SetRTPriority();
210 althrd_setname(MIXER_THREAD_NAME);
212 DSBCAPS DSBCaps{};
213 DSBCaps.dwSize = sizeof(DSBCaps);
214 HRESULT err{mBuffer->GetCaps(&DSBCaps)};
215 if(FAILED(err))
217 ERR("Failed to get buffer caps: 0x%lx\n", err);
218 aluHandleDisconnect(mDevice, "Failure retrieving playback buffer info: 0x%lx", err);
219 return 1;
222 ALuint FrameSize{mDevice->frameSizeFromFmt()};
223 DWORD FragSize{mDevice->UpdateSize * FrameSize};
225 bool Playing{false};
226 DWORD LastCursor{0u};
227 mBuffer->GetCurrentPosition(&LastCursor, nullptr);
228 while(!mKillNow.load(std::memory_order_acquire) &&
229 mDevice->Connected.load(std::memory_order_acquire))
231 // Get current play cursor
232 DWORD PlayCursor;
233 mBuffer->GetCurrentPosition(&PlayCursor, nullptr);
234 DWORD avail = (PlayCursor-LastCursor+DSBCaps.dwBufferBytes) % DSBCaps.dwBufferBytes;
236 if(avail < FragSize)
238 if(!Playing)
240 err = mBuffer->Play(0, 0, DSBPLAY_LOOPING);
241 if(FAILED(err))
243 ERR("Failed to play buffer: 0x%lx\n", err);
244 aluHandleDisconnect(mDevice, "Failure starting playback: 0x%lx", err);
245 return 1;
247 Playing = true;
250 avail = WaitForSingleObjectEx(mNotifyEvent, 2000, FALSE);
251 if(avail != WAIT_OBJECT_0)
252 ERR("WaitForSingleObjectEx error: 0x%lx\n", avail);
253 continue;
255 avail -= avail%FragSize;
257 // Lock output buffer
258 void *WritePtr1, *WritePtr2;
259 DWORD WriteCnt1{0u}, WriteCnt2{0u};
260 err = mBuffer->Lock(LastCursor, avail, &WritePtr1, &WriteCnt1, &WritePtr2, &WriteCnt2, 0);
262 // If the buffer is lost, restore it and lock
263 if(err == DSERR_BUFFERLOST)
265 WARN("Buffer lost, restoring...\n");
266 err = mBuffer->Restore();
267 if(SUCCEEDED(err))
269 Playing = false;
270 LastCursor = 0;
271 err = mBuffer->Lock(0, DSBCaps.dwBufferBytes, &WritePtr1, &WriteCnt1,
272 &WritePtr2, &WriteCnt2, 0);
276 if(SUCCEEDED(err))
278 lock();
279 aluMixData(mDevice, WritePtr1, WriteCnt1/FrameSize);
280 if(WriteCnt2 > 0)
281 aluMixData(mDevice, WritePtr2, WriteCnt2/FrameSize);
282 unlock();
284 mBuffer->Unlock(WritePtr1, WriteCnt1, WritePtr2, WriteCnt2);
286 else
288 ERR("Buffer lock error: %#lx\n", err);
289 aluHandleDisconnect(mDevice, "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 ALCenum DSoundPlayback::open(const ALCchar *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
325 { return entry.name == name; }
327 if(iter == PlaybackDevices.cend())
328 return ALC_INVALID_VALUE;
329 guid = &iter->guid;
332 hr = DS_OK;
333 mNotifyEvent = CreateEventW(nullptr, FALSE, FALSE, nullptr);
334 if(!mNotifyEvent) hr = E_FAIL;
336 //DirectSound Init code
337 if(SUCCEEDED(hr))
338 hr = DirectSoundCreate(guid, &mDS, nullptr);
339 if(SUCCEEDED(hr))
340 hr = mDS->SetCooperativeLevel(GetForegroundWindow(), DSSCL_PRIORITY);
341 if(FAILED(hr))
343 ERR("Device init failed: 0x%08lx\n", hr);
344 return ALC_INVALID_VALUE;
347 mDevice->DeviceName = name;
348 return ALC_NO_ERROR;
351 bool DSoundPlayback::reset()
353 if(mNotifies)
354 mNotifies->Release();
355 mNotifies = nullptr;
356 if(mBuffer)
357 mBuffer->Release();
358 mBuffer = nullptr;
359 if(mPrimaryBuffer)
360 mPrimaryBuffer->Release();
361 mPrimaryBuffer = nullptr;
363 switch(mDevice->FmtType)
365 case DevFmtByte:
366 mDevice->FmtType = DevFmtUByte;
367 break;
368 case DevFmtFloat:
369 if(mDevice->Flags.get<SampleTypeRequest>())
370 break;
371 /* fall-through */
372 case DevFmtUShort:
373 mDevice->FmtType = DevFmtShort;
374 break;
375 case DevFmtUInt:
376 mDevice->FmtType = DevFmtInt;
377 break;
378 case DevFmtUByte:
379 case DevFmtShort:
380 case DevFmtInt:
381 break;
384 WAVEFORMATEXTENSIBLE OutputType{};
385 DWORD speakers;
386 HRESULT hr{mDS->GetSpeakerConfig(&speakers)};
387 if(SUCCEEDED(hr))
389 speakers = DSSPEAKER_CONFIG(speakers);
390 if(!mDevice->Flags.get<ChannelsRequest>())
392 if(speakers == DSSPEAKER_MONO)
393 mDevice->FmtChans = DevFmtMono;
394 else if(speakers == DSSPEAKER_STEREO || speakers == DSSPEAKER_HEADPHONE)
395 mDevice->FmtChans = DevFmtStereo;
396 else if(speakers == DSSPEAKER_QUAD)
397 mDevice->FmtChans = DevFmtQuad;
398 else if(speakers == DSSPEAKER_5POINT1_SURROUND)
399 mDevice->FmtChans = DevFmtX51;
400 else if(speakers == DSSPEAKER_5POINT1_BACK)
401 mDevice->FmtChans = DevFmtX51Rear;
402 else if(speakers == DSSPEAKER_7POINT1 || speakers == DSSPEAKER_7POINT1_SURROUND)
403 mDevice->FmtChans = DevFmtX71;
404 else
405 ERR("Unknown system speaker config: 0x%lx\n", speakers);
407 mDevice->IsHeadphones = (mDevice->FmtChans == DevFmtStereo &&
408 speakers == DSSPEAKER_HEADPHONE);
410 switch(mDevice->FmtChans)
412 case DevFmtMono:
413 OutputType.dwChannelMask = SPEAKER_FRONT_CENTER;
414 break;
415 case DevFmtAmbi3D:
416 mDevice->FmtChans = DevFmtStereo;
417 /*fall-through*/
418 case DevFmtStereo:
419 OutputType.dwChannelMask = SPEAKER_FRONT_LEFT |
420 SPEAKER_FRONT_RIGHT;
421 break;
422 case DevFmtQuad:
423 OutputType.dwChannelMask = SPEAKER_FRONT_LEFT |
424 SPEAKER_FRONT_RIGHT |
425 SPEAKER_BACK_LEFT |
426 SPEAKER_BACK_RIGHT;
427 break;
428 case DevFmtX51:
429 OutputType.dwChannelMask = SPEAKER_FRONT_LEFT |
430 SPEAKER_FRONT_RIGHT |
431 SPEAKER_FRONT_CENTER |
432 SPEAKER_LOW_FREQUENCY |
433 SPEAKER_SIDE_LEFT |
434 SPEAKER_SIDE_RIGHT;
435 break;
436 case DevFmtX51Rear:
437 OutputType.dwChannelMask = SPEAKER_FRONT_LEFT |
438 SPEAKER_FRONT_RIGHT |
439 SPEAKER_FRONT_CENTER |
440 SPEAKER_LOW_FREQUENCY |
441 SPEAKER_BACK_LEFT |
442 SPEAKER_BACK_RIGHT;
443 break;
444 case DevFmtX61:
445 OutputType.dwChannelMask = SPEAKER_FRONT_LEFT |
446 SPEAKER_FRONT_RIGHT |
447 SPEAKER_FRONT_CENTER |
448 SPEAKER_LOW_FREQUENCY |
449 SPEAKER_BACK_CENTER |
450 SPEAKER_SIDE_LEFT |
451 SPEAKER_SIDE_RIGHT;
452 break;
453 case DevFmtX71:
454 OutputType.dwChannelMask = SPEAKER_FRONT_LEFT |
455 SPEAKER_FRONT_RIGHT |
456 SPEAKER_FRONT_CENTER |
457 SPEAKER_LOW_FREQUENCY |
458 SPEAKER_BACK_LEFT |
459 SPEAKER_BACK_RIGHT |
460 SPEAKER_SIDE_LEFT |
461 SPEAKER_SIDE_RIGHT;
462 break;
465 retry_open:
466 hr = S_OK;
467 OutputType.Format.wFormatTag = WAVE_FORMAT_PCM;
468 OutputType.Format.nChannels = static_cast<WORD>(mDevice->channelsFromFmt());
469 OutputType.Format.wBitsPerSample = static_cast<WORD>(mDevice->bytesFromFmt() * 8);
470 OutputType.Format.nBlockAlign = static_cast<WORD>(OutputType.Format.nChannels *
471 OutputType.Format.wBitsPerSample / 8);
472 OutputType.Format.nSamplesPerSec = mDevice->Frequency;
473 OutputType.Format.nAvgBytesPerSec = OutputType.Format.nSamplesPerSec *
474 OutputType.Format.nBlockAlign;
475 OutputType.Format.cbSize = 0;
478 if(OutputType.Format.nChannels > 2 || mDevice->FmtType == DevFmtFloat)
480 OutputType.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
481 OutputType.Samples.wValidBitsPerSample = OutputType.Format.wBitsPerSample;
482 OutputType.Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX);
483 if(mDevice->FmtType == DevFmtFloat)
484 OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
485 else
486 OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
488 if(mPrimaryBuffer)
489 mPrimaryBuffer->Release();
490 mPrimaryBuffer = nullptr;
492 else
494 if(SUCCEEDED(hr) && !mPrimaryBuffer)
496 DSBUFFERDESC DSBDescription{};
497 DSBDescription.dwSize = sizeof(DSBDescription);
498 DSBDescription.dwFlags = DSBCAPS_PRIMARYBUFFER;
499 hr = mDS->CreateSoundBuffer(&DSBDescription, &mPrimaryBuffer, nullptr);
501 if(SUCCEEDED(hr))
502 hr = mPrimaryBuffer->SetFormat(&OutputType.Format);
505 if(SUCCEEDED(hr))
507 ALuint num_updates{mDevice->BufferSize / mDevice->UpdateSize};
508 if(num_updates > MAX_UPDATES)
509 num_updates = MAX_UPDATES;
510 mDevice->BufferSize = mDevice->UpdateSize * num_updates;
512 DSBUFFERDESC DSBDescription{};
513 DSBDescription.dwSize = sizeof(DSBDescription);
514 DSBDescription.dwFlags = DSBCAPS_CTRLPOSITIONNOTIFY | DSBCAPS_GETCURRENTPOSITION2 |
515 DSBCAPS_GLOBALFOCUS;
516 DSBDescription.dwBufferBytes = mDevice->BufferSize * OutputType.Format.nBlockAlign;
517 DSBDescription.lpwfxFormat = &OutputType.Format;
519 hr = mDS->CreateSoundBuffer(&DSBDescription, &mBuffer, nullptr);
520 if(FAILED(hr) && mDevice->FmtType == DevFmtFloat)
522 mDevice->FmtType = DevFmtShort;
523 goto retry_open;
527 if(SUCCEEDED(hr))
529 void *ptr;
530 hr = mBuffer->QueryInterface(IID_IDirectSoundNotify, &ptr);
531 if(SUCCEEDED(hr))
533 auto Notifies = static_cast<IDirectSoundNotify*>(ptr);
534 mNotifies = Notifies;
536 ALuint num_updates{mDevice->BufferSize / mDevice->UpdateSize};
537 assert(num_updates <= MAX_UPDATES);
539 std::array<DSBPOSITIONNOTIFY,MAX_UPDATES> nots;
540 for(ALuint i{0};i < num_updates;++i)
542 nots[i].dwOffset = i * mDevice->UpdateSize * OutputType.Format.nBlockAlign;
543 nots[i].hEventNotify = mNotifyEvent;
545 if(Notifies->SetNotificationPositions(num_updates, nots.data()) != DS_OK)
546 hr = E_FAIL;
550 if(FAILED(hr))
552 if(mNotifies)
553 mNotifies->Release();
554 mNotifies = nullptr;
555 if(mBuffer)
556 mBuffer->Release();
557 mBuffer = nullptr;
558 if(mPrimaryBuffer)
559 mPrimaryBuffer->Release();
560 mPrimaryBuffer = nullptr;
561 return false;
564 ResetEvent(mNotifyEvent);
565 SetDefaultWFXChannelOrder(mDevice);
567 return true;
570 bool DSoundPlayback::start()
572 try {
573 mKillNow.store(false, std::memory_order_release);
574 mThread = std::thread{std::mem_fn(&DSoundPlayback::mixerProc), this};
575 return true;
577 catch(std::exception& e) {
578 ERR("Failed to start mixing thread: %s\n", e.what());
580 catch(...) {
582 return false;
585 void DSoundPlayback::stop()
587 if(mKillNow.exchange(true, std::memory_order_acq_rel) || !mThread.joinable())
588 return;
589 mThread.join();
591 mBuffer->Stop();
595 struct DSoundCapture final : public BackendBase {
596 DSoundCapture(ALCdevice *device) noexcept : BackendBase{device} { }
597 ~DSoundCapture() override;
599 ALCenum open(const ALCchar *name) override;
600 bool start() override;
601 void stop() override;
602 ALCenum captureSamples(al::byte *buffer, ALCuint samples) override;
603 ALCuint availableSamples() override;
605 IDirectSoundCapture *mDSC{nullptr};
606 IDirectSoundCaptureBuffer *mDSCbuffer{nullptr};
607 DWORD mBufferBytes{0u};
608 DWORD mCursor{0u};
610 RingBufferPtr mRing;
612 DEF_NEWDEL(DSoundCapture)
615 DSoundCapture::~DSoundCapture()
617 if(mDSCbuffer)
619 mDSCbuffer->Stop();
620 mDSCbuffer->Release();
621 mDSCbuffer = nullptr;
624 if(mDSC)
625 mDSC->Release();
626 mDSC = nullptr;
630 ALCenum DSoundCapture::open(const ALCchar *name)
632 HRESULT hr;
633 if(CaptureDevices.empty())
635 /* Initialize COM to prevent name truncation */
636 HRESULT hrcom{CoInitialize(nullptr)};
637 hr = DirectSoundCaptureEnumerateW(DSoundEnumDevices, &CaptureDevices);
638 if(FAILED(hr))
639 ERR("Error enumerating DirectSound devices (0x%lx)!\n", hr);
640 if(SUCCEEDED(hrcom))
641 CoUninitialize();
644 const GUID *guid{nullptr};
645 if(!name && !CaptureDevices.empty())
647 name = CaptureDevices[0].name.c_str();
648 guid = &CaptureDevices[0].guid;
650 else
652 auto iter = std::find_if(CaptureDevices.cbegin(), CaptureDevices.cend(),
653 [name](const DevMap &entry) -> bool
654 { return entry.name == name; }
656 if(iter == CaptureDevices.cend())
657 return ALC_INVALID_VALUE;
658 guid = &iter->guid;
661 switch(mDevice->FmtType)
663 case DevFmtByte:
664 case DevFmtUShort:
665 case DevFmtUInt:
666 WARN("%s capture samples not supported\n", DevFmtTypeString(mDevice->FmtType));
667 return ALC_INVALID_ENUM;
669 case DevFmtUByte:
670 case DevFmtShort:
671 case DevFmtInt:
672 case DevFmtFloat:
673 break;
676 WAVEFORMATEXTENSIBLE InputType{};
677 switch(mDevice->FmtChans)
679 case DevFmtMono:
680 InputType.dwChannelMask = SPEAKER_FRONT_CENTER;
681 break;
682 case DevFmtStereo:
683 InputType.dwChannelMask = SPEAKER_FRONT_LEFT |
684 SPEAKER_FRONT_RIGHT;
685 break;
686 case DevFmtQuad:
687 InputType.dwChannelMask = SPEAKER_FRONT_LEFT |
688 SPEAKER_FRONT_RIGHT |
689 SPEAKER_BACK_LEFT |
690 SPEAKER_BACK_RIGHT;
691 break;
692 case DevFmtX51:
693 InputType.dwChannelMask = SPEAKER_FRONT_LEFT |
694 SPEAKER_FRONT_RIGHT |
695 SPEAKER_FRONT_CENTER |
696 SPEAKER_LOW_FREQUENCY |
697 SPEAKER_SIDE_LEFT |
698 SPEAKER_SIDE_RIGHT;
699 break;
700 case DevFmtX51Rear:
701 InputType.dwChannelMask = SPEAKER_FRONT_LEFT |
702 SPEAKER_FRONT_RIGHT |
703 SPEAKER_FRONT_CENTER |
704 SPEAKER_LOW_FREQUENCY |
705 SPEAKER_BACK_LEFT |
706 SPEAKER_BACK_RIGHT;
707 break;
708 case DevFmtX61:
709 InputType.dwChannelMask = SPEAKER_FRONT_LEFT |
710 SPEAKER_FRONT_RIGHT |
711 SPEAKER_FRONT_CENTER |
712 SPEAKER_LOW_FREQUENCY |
713 SPEAKER_BACK_CENTER |
714 SPEAKER_SIDE_LEFT |
715 SPEAKER_SIDE_RIGHT;
716 break;
717 case DevFmtX71:
718 InputType.dwChannelMask = SPEAKER_FRONT_LEFT |
719 SPEAKER_FRONT_RIGHT |
720 SPEAKER_FRONT_CENTER |
721 SPEAKER_LOW_FREQUENCY |
722 SPEAKER_BACK_LEFT |
723 SPEAKER_BACK_RIGHT |
724 SPEAKER_SIDE_LEFT |
725 SPEAKER_SIDE_RIGHT;
726 break;
727 case DevFmtAmbi3D:
728 WARN("%s capture not supported\n", DevFmtChannelsString(mDevice->FmtChans));
729 return ALC_INVALID_ENUM;
732 InputType.Format.wFormatTag = WAVE_FORMAT_PCM;
733 InputType.Format.nChannels = static_cast<WORD>(mDevice->channelsFromFmt());
734 InputType.Format.wBitsPerSample = static_cast<WORD>(mDevice->bytesFromFmt() * 8);
735 InputType.Format.nBlockAlign = static_cast<WORD>(InputType.Format.nChannels *
736 InputType.Format.wBitsPerSample / 8);
737 InputType.Format.nSamplesPerSec = mDevice->Frequency;
738 InputType.Format.nAvgBytesPerSec = InputType.Format.nSamplesPerSec *
739 InputType.Format.nBlockAlign;
740 InputType.Format.cbSize = 0;
741 InputType.Samples.wValidBitsPerSample = InputType.Format.wBitsPerSample;
742 if(mDevice->FmtType == DevFmtFloat)
743 InputType.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
744 else
745 InputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
747 if(InputType.Format.nChannels > 2 || mDevice->FmtType == DevFmtFloat)
749 InputType.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
750 InputType.Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX);
753 ALuint samples{mDevice->BufferSize};
754 samples = maxu(samples, 100 * mDevice->Frequency / 1000);
756 DSCBUFFERDESC DSCBDescription{};
757 DSCBDescription.dwSize = sizeof(DSCBDescription);
758 DSCBDescription.dwFlags = 0;
759 DSCBDescription.dwBufferBytes = samples * InputType.Format.nBlockAlign;
760 DSCBDescription.lpwfxFormat = &InputType.Format;
762 //DirectSoundCapture Init code
763 hr = DirectSoundCaptureCreate(guid, &mDSC, nullptr);
764 if(SUCCEEDED(hr))
765 mDSC->CreateCaptureBuffer(&DSCBDescription, &mDSCbuffer, nullptr);
766 if(SUCCEEDED(hr))
768 mRing = CreateRingBuffer(mDevice->BufferSize, InputType.Format.nBlockAlign, false);
769 if(!mRing) hr = DSERR_OUTOFMEMORY;
772 if(FAILED(hr))
774 ERR("Device init failed: 0x%08lx\n", hr);
776 mRing = nullptr;
777 if(mDSCbuffer)
778 mDSCbuffer->Release();
779 mDSCbuffer = nullptr;
780 if(mDSC)
781 mDSC->Release();
782 mDSC = nullptr;
784 return ALC_INVALID_VALUE;
787 mBufferBytes = DSCBDescription.dwBufferBytes;
788 SetDefaultWFXChannelOrder(mDevice);
790 mDevice->DeviceName = name;
791 return ALC_NO_ERROR;
794 bool DSoundCapture::start()
796 HRESULT hr{mDSCbuffer->Start(DSCBSTART_LOOPING)};
797 if(FAILED(hr))
799 ERR("start failed: 0x%08lx\n", hr);
800 aluHandleDisconnect(mDevice, "Failure starting capture: 0x%lx", hr);
801 return false;
803 return true;
806 void DSoundCapture::stop()
808 HRESULT hr{mDSCbuffer->Stop()};
809 if(FAILED(hr))
811 ERR("stop failed: 0x%08lx\n", hr);
812 aluHandleDisconnect(mDevice, "Failure stopping capture: 0x%lx", hr);
816 ALCenum DSoundCapture::captureSamples(al::byte *buffer, ALCuint samples)
818 mRing->read(buffer, samples);
819 return ALC_NO_ERROR;
822 ALCuint DSoundCapture::availableSamples()
824 if(!mDevice->Connected.load(std::memory_order_acquire))
825 return static_cast<ALCuint>(mRing->readSpace());
827 ALuint FrameSize{mDevice->frameSizeFromFmt()};
828 DWORD BufferBytes{mBufferBytes};
829 DWORD LastCursor{mCursor};
831 DWORD ReadCursor{};
832 void *ReadPtr1{}, *ReadPtr2{};
833 DWORD ReadCnt1{}, ReadCnt2{};
834 HRESULT hr{mDSCbuffer->GetCurrentPosition(nullptr, &ReadCursor)};
835 if(SUCCEEDED(hr))
837 DWORD NumBytes{(ReadCursor-LastCursor + BufferBytes) % BufferBytes};
838 if(!NumBytes) return static_cast<ALCubyte>(mRing->readSpace());
839 hr = mDSCbuffer->Lock(LastCursor, NumBytes, &ReadPtr1, &ReadCnt1, &ReadPtr2, &ReadCnt2, 0);
841 if(SUCCEEDED(hr))
843 mRing->write(ReadPtr1, ReadCnt1/FrameSize);
844 if(ReadPtr2 != nullptr && ReadCnt2 > 0)
845 mRing->write(ReadPtr2, ReadCnt2/FrameSize);
846 hr = mDSCbuffer->Unlock(ReadPtr1, ReadCnt1, ReadPtr2, ReadCnt2);
847 mCursor = (LastCursor+ReadCnt1+ReadCnt2) % BufferBytes;
850 if(FAILED(hr))
852 ERR("update failed: 0x%08lx\n", hr);
853 aluHandleDisconnect(mDevice, "Failure retrieving capture data: 0x%lx", hr);
856 return static_cast<ALCuint>(mRing->readSpace());
859 } // namespace
862 BackendFactory &DSoundBackendFactory::getFactory()
864 static DSoundBackendFactory factory{};
865 return factory;
868 bool DSoundBackendFactory::init()
870 #ifdef HAVE_DYNLOAD
871 if(!ds_handle)
873 ds_handle = LoadLib("dsound.dll");
874 if(!ds_handle)
876 ERR("Failed to load dsound.dll\n");
877 return false;
880 #define LOAD_FUNC(f) do { \
881 p##f = reinterpret_cast<decltype(p##f)>(GetSymbol(ds_handle, #f)); \
882 if(!p##f) \
884 CloseLib(ds_handle); \
885 ds_handle = nullptr; \
886 return false; \
888 } while(0)
889 LOAD_FUNC(DirectSoundCreate);
890 LOAD_FUNC(DirectSoundEnumerateW);
891 LOAD_FUNC(DirectSoundCaptureCreate);
892 LOAD_FUNC(DirectSoundCaptureEnumerateW);
893 #undef LOAD_FUNC
895 #endif
896 return true;
899 bool DSoundBackendFactory::querySupport(BackendType type)
900 { return (type == BackendType::Playback || type == BackendType::Capture); }
902 void DSoundBackendFactory::probe(DevProbe type, std::string *outnames)
904 auto add_device = [outnames](const DevMap &entry) -> void
906 /* +1 to also append the null char (to ensure a null-separated list and
907 * double-null terminated list).
909 outnames->append(entry.name.c_str(), entry.name.length()+1);
912 /* Initialize COM to prevent name truncation */
913 HRESULT hr;
914 HRESULT hrcom{CoInitialize(nullptr)};
915 switch(type)
917 case DevProbe::Playback:
918 PlaybackDevices.clear();
919 hr = DirectSoundEnumerateW(DSoundEnumDevices, &PlaybackDevices);
920 if(FAILED(hr))
921 ERR("Error enumerating DirectSound playback devices (0x%lx)!\n", hr);
922 std::for_each(PlaybackDevices.cbegin(), PlaybackDevices.cend(), add_device);
923 break;
925 case DevProbe::Capture:
926 CaptureDevices.clear();
927 hr = DirectSoundCaptureEnumerateW(DSoundEnumDevices, &CaptureDevices);
928 if(FAILED(hr))
929 ERR("Error enumerating DirectSound capture devices (0x%lx)!\n", hr);
930 std::for_each(CaptureDevices.cbegin(), CaptureDevices.cend(), add_device);
931 break;
933 if(SUCCEEDED(hrcom))
934 CoUninitialize();
937 BackendPtr DSoundBackendFactory::createBackend(ALCdevice *device, BackendType type)
939 if(type == BackendType::Playback)
940 return BackendPtr{new DSoundPlayback{device}};
941 if(type == BackendType::Capture)
942 return BackendPtr{new DSoundCapture{device}};
943 return nullptr;