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
25 #define WIN32_LEAN_AND_MEAN
34 #ifndef _WAVEFORMATEXTENSIBLE_
47 #include "alnumeric.h"
49 #include "core/device.h"
50 #include "core/helpers.h"
51 #include "core/logging.h"
53 #include "ringbuffer.h"
57 /* MinGW-w64 needs this for some unknown reason now. */
58 using LPCWAVEFORMATEX
= const WAVEFORMATEX
*;
62 #ifndef DSSPEAKER_5POINT1
63 # define DSSPEAKER_5POINT1 0x00000006
65 #ifndef DSSPEAKER_5POINT1_BACK
66 # define DSSPEAKER_5POINT1_BACK 0x00000006
68 #ifndef DSSPEAKER_7POINT1
69 # define DSSPEAKER_7POINT1 0x00000007
71 #ifndef DSSPEAKER_7POINT1_SURROUND
72 # define DSSPEAKER_7POINT1_SURROUND 0x00000008
74 #ifndef DSSPEAKER_5POINT1_SURROUND
75 # define DSSPEAKER_5POINT1_SURROUND 0x00000009
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);
86 #ifndef KSDATAFORMAT_SUBTYPE_IEEE_FLOAT
87 DEFINE_GUID(KSDATAFORMAT_SUBTYPE_IEEE_FLOAT
, 0x00000003, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71);
92 #define DEVNAME_HEAD "OpenAL Soft on "
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
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
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
146 auto& devices
= *static_cast<al::vector
<DevMap
>*>(data
);
147 const std::string basename
{DEVNAME_HEAD
+ wstr_to_utf8(desc
)};
150 std::string newname
{basename
};
151 while(checkName(devices
, 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
)};
164 TRACE("Got device \"%s\", GUID \"%ls\"\n", newentry
.name
.c_str(), guidstr
);
165 CoTaskMemFree(guidstr
);
172 struct DSoundPlayback final
: public BackendBase
{
173 DSoundPlayback(DeviceBase
*device
) noexcept
: BackendBase
{device
} { }
174 ~DSoundPlayback() override
;
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};
192 DEF_NEWDEL(DSoundPlayback
)
195 DSoundPlayback::~DSoundPlayback()
199 mPrimaryBuffer
= nullptr;
203 CloseHandle(mNotifyEvent
);
204 mNotifyEvent
= nullptr;
208 FORCE_ALIGN
int DSoundPlayback::mixerProc()
211 althrd_setname(MIXER_THREAD_NAME
);
214 DSBCaps
.dwSize
= sizeof(DSBCaps
);
215 HRESULT err
{mBuffer
->GetCaps(&DSBCaps
)};
218 ERR("Failed to get buffer caps: 0x%lx\n", err
);
219 mDevice
->handleDisconnect("Failure retrieving playback buffer info: 0x%lx", err
);
223 const size_t FrameStep
{mDevice
->channelsFromFmt()};
224 uint FrameSize
{mDevice
->frameSizeFromFmt()};
225 DWORD FragSize
{mDevice
->UpdateSize
* FrameSize
};
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
235 mBuffer
->GetCurrentPosition(&PlayCursor
, nullptr);
236 DWORD avail
= (PlayCursor
-LastCursor
+DSBCaps
.dwBufferBytes
) % DSBCaps
.dwBufferBytes
;
242 err
= mBuffer
->Play(0, 0, DSBPLAY_LOOPING
);
245 ERR("Failed to play buffer: 0x%lx\n", err
);
246 mDevice
->handleDisconnect("Failure starting playback: 0x%lx", err
);
252 avail
= WaitForSingleObjectEx(mNotifyEvent
, 2000, FALSE
);
253 if(avail
!= WAIT_OBJECT_0
)
254 ERR("WaitForSingleObjectEx error: 0x%lx\n", avail
);
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();
273 err
= mBuffer
->Lock(0, DSBCaps
.dwBufferBytes
, &WritePtr1
, &WriteCnt1
,
274 &WritePtr2
, &WriteCnt2
, 0);
280 mDevice
->renderSamples(WritePtr1
, WriteCnt1
/FrameSize
, FrameStep
);
282 mDevice
->renderSamples(WritePtr2
, WriteCnt2
/FrameSize
, FrameStep
);
284 mBuffer
->Unlock(WritePtr1
, WriteCnt1
, WritePtr2
, WriteCnt2
);
288 ERR("Buffer lock error: %#lx\n", err
);
289 mDevice
->handleDisconnect("Failed to lock output buffer: 0x%lx", err
);
293 // Update old write cursor location
294 LastCursor
+= WriteCnt1
+WriteCnt2
;
295 LastCursor
%= DSBCaps
.dwBufferBytes
;
301 void DSoundPlayback::open(const char *name
)
304 if(PlaybackDevices
.empty())
306 /* Initialize COM to prevent name truncation */
307 HRESULT hrcom
{CoInitialize(nullptr)};
308 hr
= DirectSoundEnumerateW(DSoundEnumDevices
, &PlaybackDevices
);
310 ERR("Error enumerating DirectSound devices (0x%lx)!\n", hr
);
315 const GUID
*guid
{nullptr};
316 if(!name
&& !PlaybackDevices
.empty())
318 name
= PlaybackDevices
[0].name
.c_str();
319 guid
= &PlaybackDevices
[0].guid
;
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())
328 hr
= CLSIDFromString(utf8_to_wstr(name
).c_str(), &id
);
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
};
342 mNotifyEvent
= CreateEventW(nullptr, FALSE
, FALSE
, nullptr);
343 if(!mNotifyEvent
) hr
= E_FAIL
;
346 //DirectSound Init code
347 ComPtr
<IDirectSound
> ds
;
349 hr
= DirectSoundCreate(guid
, ds
.getPtr(), nullptr);
351 hr
= ds
->SetCooperativeLevel(GetForegroundWindow(), DSSCL_PRIORITY
);
353 throw al::backend_exception
{al::backend_error::DeviceError
, "Device init failed: 0x%08lx",
358 mPrimaryBuffer
= nullptr;
361 mDevice
->DeviceName
= name
;
364 bool DSoundPlayback::reset()
368 mPrimaryBuffer
= nullptr;
370 switch(mDevice
->FmtType
)
373 mDevice
->FmtType
= DevFmtUByte
;
376 if(mDevice
->Flags
.test(SampleTypeRequest
))
380 mDevice
->FmtType
= DevFmtShort
;
383 mDevice
->FmtType
= DevFmtInt
;
391 WAVEFORMATEXTENSIBLE OutputType
{};
393 HRESULT hr
{mDS
->GetSpeakerConfig(&speakers
)};
396 speakers
= DSSPEAKER_CONFIG(speakers
);
397 if(!mDevice
->Flags
.test(ChannelsRequest
))
399 if(speakers
== DSSPEAKER_MONO
)
400 mDevice
->FmtChans
= DevFmtMono
;
401 else if(speakers
== DSSPEAKER_STEREO
|| speakers
== DSSPEAKER_HEADPHONE
)
402 mDevice
->FmtChans
= DevFmtStereo
;
403 else if(speakers
== DSSPEAKER_QUAD
)
404 mDevice
->FmtChans
= DevFmtQuad
;
405 else if(speakers
== DSSPEAKER_5POINT1_SURROUND
|| speakers
== DSSPEAKER_5POINT1_BACK
)
406 mDevice
->FmtChans
= DevFmtX51
;
407 else if(speakers
== DSSPEAKER_7POINT1
|| speakers
== DSSPEAKER_7POINT1_SURROUND
)
408 mDevice
->FmtChans
= DevFmtX71
;
410 ERR("Unknown system speaker config: 0x%lx\n", speakers
);
412 mDevice
->Flags
.set(DirectEar
, (speakers
== DSSPEAKER_HEADPHONE
));
414 switch(mDevice
->FmtChans
)
416 case DevFmtMono
: OutputType
.dwChannelMask
= MONO
; break;
417 case DevFmtAmbi3D
: mDevice
->FmtChans
= DevFmtStereo
;
419 case DevFmtStereo
: OutputType
.dwChannelMask
= STEREO
; break;
420 case DevFmtQuad
: OutputType
.dwChannelMask
= QUAD
; break;
421 case DevFmtX51
: OutputType
.dwChannelMask
= X5DOT1
; break;
422 case DevFmtX61
: OutputType
.dwChannelMask
= X6DOT1
; break;
423 case DevFmtX71
: OutputType
.dwChannelMask
= X7DOT1
; break;
428 OutputType
.Format
.wFormatTag
= WAVE_FORMAT_PCM
;
429 OutputType
.Format
.nChannels
= static_cast<WORD
>(mDevice
->channelsFromFmt());
430 OutputType
.Format
.wBitsPerSample
= static_cast<WORD
>(mDevice
->bytesFromFmt() * 8);
431 OutputType
.Format
.nBlockAlign
= static_cast<WORD
>(OutputType
.Format
.nChannels
*
432 OutputType
.Format
.wBitsPerSample
/ 8);
433 OutputType
.Format
.nSamplesPerSec
= mDevice
->Frequency
;
434 OutputType
.Format
.nAvgBytesPerSec
= OutputType
.Format
.nSamplesPerSec
*
435 OutputType
.Format
.nBlockAlign
;
436 OutputType
.Format
.cbSize
= 0;
439 if(OutputType
.Format
.nChannels
> 2 || mDevice
->FmtType
== DevFmtFloat
)
441 OutputType
.Format
.wFormatTag
= WAVE_FORMAT_EXTENSIBLE
;
442 OutputType
.Samples
.wValidBitsPerSample
= OutputType
.Format
.wBitsPerSample
;
443 OutputType
.Format
.cbSize
= sizeof(WAVEFORMATEXTENSIBLE
) - sizeof(WAVEFORMATEX
);
444 if(mDevice
->FmtType
== DevFmtFloat
)
445 OutputType
.SubFormat
= KSDATAFORMAT_SUBTYPE_IEEE_FLOAT
;
447 OutputType
.SubFormat
= KSDATAFORMAT_SUBTYPE_PCM
;
449 mPrimaryBuffer
= nullptr;
453 if(SUCCEEDED(hr
) && !mPrimaryBuffer
)
455 DSBUFFERDESC DSBDescription
{};
456 DSBDescription
.dwSize
= sizeof(DSBDescription
);
457 DSBDescription
.dwFlags
= DSBCAPS_PRIMARYBUFFER
;
458 hr
= mDS
->CreateSoundBuffer(&DSBDescription
, mPrimaryBuffer
.getPtr(), nullptr);
461 hr
= mPrimaryBuffer
->SetFormat(&OutputType
.Format
);
466 uint num_updates
{mDevice
->BufferSize
/ mDevice
->UpdateSize
};
467 if(num_updates
> MAX_UPDATES
)
468 num_updates
= MAX_UPDATES
;
469 mDevice
->BufferSize
= mDevice
->UpdateSize
* num_updates
;
471 DSBUFFERDESC DSBDescription
{};
472 DSBDescription
.dwSize
= sizeof(DSBDescription
);
473 DSBDescription
.dwFlags
= DSBCAPS_CTRLPOSITIONNOTIFY
| DSBCAPS_GETCURRENTPOSITION2
474 | DSBCAPS_GLOBALFOCUS
;
475 DSBDescription
.dwBufferBytes
= mDevice
->BufferSize
* OutputType
.Format
.nBlockAlign
;
476 DSBDescription
.lpwfxFormat
= &OutputType
.Format
;
478 hr
= mDS
->CreateSoundBuffer(&DSBDescription
, mBuffer
.getPtr(), nullptr);
479 if(FAILED(hr
) && mDevice
->FmtType
== DevFmtFloat
)
481 mDevice
->FmtType
= DevFmtShort
;
489 hr
= mBuffer
->QueryInterface(IID_IDirectSoundNotify
, &ptr
);
492 mNotifies
= ComPtr
<IDirectSoundNotify
>{static_cast<IDirectSoundNotify
*>(ptr
)};
494 uint num_updates
{mDevice
->BufferSize
/ mDevice
->UpdateSize
};
495 assert(num_updates
<= MAX_UPDATES
);
497 std::array
<DSBPOSITIONNOTIFY
,MAX_UPDATES
> nots
;
498 for(uint i
{0};i
< num_updates
;++i
)
500 nots
[i
].dwOffset
= i
* mDevice
->UpdateSize
* OutputType
.Format
.nBlockAlign
;
501 nots
[i
].hEventNotify
= mNotifyEvent
;
503 if(mNotifies
->SetNotificationPositions(num_updates
, nots
.data()) != DS_OK
)
512 mPrimaryBuffer
= nullptr;
516 ResetEvent(mNotifyEvent
);
517 setChannelOrderFromWFXMask(OutputType
.dwChannelMask
);
522 void DSoundPlayback::start()
525 mKillNow
.store(false, std::memory_order_release
);
526 mThread
= std::thread
{std::mem_fn(&DSoundPlayback::mixerProc
), this};
528 catch(std::exception
& e
) {
529 throw al::backend_exception
{al::backend_error::DeviceError
,
530 "Failed to start mixing thread: %s", e
.what()};
534 void DSoundPlayback::stop()
536 if(mKillNow
.exchange(true, std::memory_order_acq_rel
) || !mThread
.joinable())
544 struct DSoundCapture final
: public BackendBase
{
545 DSoundCapture(DeviceBase
*device
) noexcept
: BackendBase
{device
} { }
546 ~DSoundCapture() override
;
548 void open(const char *name
) override
;
549 void start() override
;
550 void stop() override
;
551 void captureSamples(al::byte
*buffer
, uint samples
) override
;
552 uint
availableSamples() override
;
554 ComPtr
<IDirectSoundCapture
> mDSC
;
555 ComPtr
<IDirectSoundCaptureBuffer
> mDSCbuffer
;
556 DWORD mBufferBytes
{0u};
561 DEF_NEWDEL(DSoundCapture
)
564 DSoundCapture::~DSoundCapture()
569 mDSCbuffer
= nullptr;
575 void DSoundCapture::open(const char *name
)
578 if(CaptureDevices
.empty())
580 /* Initialize COM to prevent name truncation */
581 HRESULT hrcom
{CoInitialize(nullptr)};
582 hr
= DirectSoundCaptureEnumerateW(DSoundEnumDevices
, &CaptureDevices
);
584 ERR("Error enumerating DirectSound devices (0x%lx)!\n", hr
);
589 const GUID
*guid
{nullptr};
590 if(!name
&& !CaptureDevices
.empty())
592 name
= CaptureDevices
[0].name
.c_str();
593 guid
= &CaptureDevices
[0].guid
;
597 auto iter
= std::find_if(CaptureDevices
.cbegin(), CaptureDevices
.cend(),
598 [name
](const DevMap
&entry
) -> bool { return entry
.name
== name
; });
599 if(iter
== CaptureDevices
.cend())
602 hr
= CLSIDFromString(utf8_to_wstr(name
).c_str(), &id
);
604 iter
= std::find_if(CaptureDevices
.cbegin(), CaptureDevices
.cend(),
605 [&id
](const DevMap
&entry
) -> bool { return entry
.guid
== id
; });
606 if(iter
== CaptureDevices
.cend())
607 throw al::backend_exception
{al::backend_error::NoDevice
,
608 "Device name \"%s\" not found", name
};
613 switch(mDevice
->FmtType
)
618 WARN("%s capture samples not supported\n", DevFmtTypeString(mDevice
->FmtType
));
619 throw al::backend_exception
{al::backend_error::DeviceError
,
620 "%s capture samples not supported", DevFmtTypeString(mDevice
->FmtType
)};
629 WAVEFORMATEXTENSIBLE InputType
{};
630 switch(mDevice
->FmtChans
)
632 case DevFmtMono
: InputType
.dwChannelMask
= MONO
; break;
633 case DevFmtStereo
: InputType
.dwChannelMask
= STEREO
; break;
634 case DevFmtQuad
: InputType
.dwChannelMask
= QUAD
; break;
635 case DevFmtX51
: InputType
.dwChannelMask
= X5DOT1
; break;
636 case DevFmtX61
: InputType
.dwChannelMask
= X6DOT1
; break;
637 case DevFmtX71
: InputType
.dwChannelMask
= X7DOT1
; break;
639 WARN("%s capture not supported\n", DevFmtChannelsString(mDevice
->FmtChans
));
640 throw al::backend_exception
{al::backend_error::DeviceError
, "%s capture not supported",
641 DevFmtChannelsString(mDevice
->FmtChans
)};
644 InputType
.Format
.wFormatTag
= WAVE_FORMAT_PCM
;
645 InputType
.Format
.nChannels
= static_cast<WORD
>(mDevice
->channelsFromFmt());
646 InputType
.Format
.wBitsPerSample
= static_cast<WORD
>(mDevice
->bytesFromFmt() * 8);
647 InputType
.Format
.nBlockAlign
= static_cast<WORD
>(InputType
.Format
.nChannels
*
648 InputType
.Format
.wBitsPerSample
/ 8);
649 InputType
.Format
.nSamplesPerSec
= mDevice
->Frequency
;
650 InputType
.Format
.nAvgBytesPerSec
= InputType
.Format
.nSamplesPerSec
*
651 InputType
.Format
.nBlockAlign
;
652 InputType
.Format
.cbSize
= 0;
653 InputType
.Samples
.wValidBitsPerSample
= InputType
.Format
.wBitsPerSample
;
654 if(mDevice
->FmtType
== DevFmtFloat
)
655 InputType
.SubFormat
= KSDATAFORMAT_SUBTYPE_IEEE_FLOAT
;
657 InputType
.SubFormat
= KSDATAFORMAT_SUBTYPE_PCM
;
659 if(InputType
.Format
.nChannels
> 2 || mDevice
->FmtType
== DevFmtFloat
)
661 InputType
.Format
.wFormatTag
= WAVE_FORMAT_EXTENSIBLE
;
662 InputType
.Format
.cbSize
= sizeof(WAVEFORMATEXTENSIBLE
) - sizeof(WAVEFORMATEX
);
665 uint samples
{mDevice
->BufferSize
};
666 samples
= maxu(samples
, 100 * mDevice
->Frequency
/ 1000);
668 DSCBUFFERDESC DSCBDescription
{};
669 DSCBDescription
.dwSize
= sizeof(DSCBDescription
);
670 DSCBDescription
.dwFlags
= 0;
671 DSCBDescription
.dwBufferBytes
= samples
* InputType
.Format
.nBlockAlign
;
672 DSCBDescription
.lpwfxFormat
= &InputType
.Format
;
674 //DirectSoundCapture Init code
675 hr
= DirectSoundCaptureCreate(guid
, mDSC
.getPtr(), nullptr);
677 mDSC
->CreateCaptureBuffer(&DSCBDescription
, mDSCbuffer
.getPtr(), nullptr);
679 mRing
= RingBuffer::Create(mDevice
->BufferSize
, InputType
.Format
.nBlockAlign
, false);
684 mDSCbuffer
= nullptr;
687 throw al::backend_exception
{al::backend_error::DeviceError
, "Device init failed: 0x%08lx",
691 mBufferBytes
= DSCBDescription
.dwBufferBytes
;
692 setChannelOrderFromWFXMask(InputType
.dwChannelMask
);
694 mDevice
->DeviceName
= name
;
697 void DSoundCapture::start()
699 const HRESULT hr
{mDSCbuffer
->Start(DSCBSTART_LOOPING
)};
701 throw al::backend_exception
{al::backend_error::DeviceError
,
702 "Failure starting capture: 0x%lx", hr
};
705 void DSoundCapture::stop()
707 HRESULT hr
{mDSCbuffer
->Stop()};
710 ERR("stop failed: 0x%08lx\n", hr
);
711 mDevice
->handleDisconnect("Failure stopping capture: 0x%lx", hr
);
715 void DSoundCapture::captureSamples(al::byte
*buffer
, uint samples
)
716 { mRing
->read(buffer
, samples
); }
718 uint
DSoundCapture::availableSamples()
720 if(!mDevice
->Connected
.load(std::memory_order_acquire
))
721 return static_cast<uint
>(mRing
->readSpace());
723 const uint FrameSize
{mDevice
->frameSizeFromFmt()};
724 const DWORD BufferBytes
{mBufferBytes
};
725 const DWORD LastCursor
{mCursor
};
728 void *ReadPtr1
{}, *ReadPtr2
{};
729 DWORD ReadCnt1
{}, ReadCnt2
{};
730 HRESULT hr
{mDSCbuffer
->GetCurrentPosition(nullptr, &ReadCursor
)};
733 const DWORD NumBytes
{(BufferBytes
+ReadCursor
-LastCursor
) % BufferBytes
};
734 if(!NumBytes
) return static_cast<uint
>(mRing
->readSpace());
735 hr
= mDSCbuffer
->Lock(LastCursor
, NumBytes
, &ReadPtr1
, &ReadCnt1
, &ReadPtr2
, &ReadCnt2
, 0);
739 mRing
->write(ReadPtr1
, ReadCnt1
/FrameSize
);
740 if(ReadPtr2
!= nullptr && ReadCnt2
> 0)
741 mRing
->write(ReadPtr2
, ReadCnt2
/FrameSize
);
742 hr
= mDSCbuffer
->Unlock(ReadPtr1
, ReadCnt1
, ReadPtr2
, ReadCnt2
);
743 mCursor
= ReadCursor
;
748 ERR("update failed: 0x%08lx\n", hr
);
749 mDevice
->handleDisconnect("Failure retrieving capture data: 0x%lx", hr
);
752 return static_cast<uint
>(mRing
->readSpace());
758 BackendFactory
&DSoundBackendFactory::getFactory()
760 static DSoundBackendFactory factory
{};
764 bool DSoundBackendFactory::init()
769 ds_handle
= LoadLib("dsound.dll");
772 ERR("Failed to load dsound.dll\n");
776 #define LOAD_FUNC(f) do { \
777 p##f = reinterpret_cast<decltype(p##f)>(GetSymbol(ds_handle, #f)); \
780 CloseLib(ds_handle); \
781 ds_handle = nullptr; \
785 LOAD_FUNC(DirectSoundCreate
);
786 LOAD_FUNC(DirectSoundEnumerateW
);
787 LOAD_FUNC(DirectSoundCaptureCreate
);
788 LOAD_FUNC(DirectSoundCaptureEnumerateW
);
795 bool DSoundBackendFactory::querySupport(BackendType type
)
796 { return (type
== BackendType::Playback
|| type
== BackendType::Capture
); }
798 std::string
DSoundBackendFactory::probe(BackendType type
)
800 std::string outnames
;
801 auto add_device
= [&outnames
](const DevMap
&entry
) -> void
803 /* +1 to also append the null char (to ensure a null-separated list and
804 * double-null terminated list).
806 outnames
.append(entry
.name
.c_str(), entry
.name
.length()+1);
809 /* Initialize COM to prevent name truncation */
811 HRESULT hrcom
{CoInitialize(nullptr)};
814 case BackendType::Playback
:
815 PlaybackDevices
.clear();
816 hr
= DirectSoundEnumerateW(DSoundEnumDevices
, &PlaybackDevices
);
818 ERR("Error enumerating DirectSound playback devices (0x%lx)!\n", hr
);
819 std::for_each(PlaybackDevices
.cbegin(), PlaybackDevices
.cend(), add_device
);
822 case BackendType::Capture
:
823 CaptureDevices
.clear();
824 hr
= DirectSoundCaptureEnumerateW(DSoundEnumDevices
, &CaptureDevices
);
826 ERR("Error enumerating DirectSound capture devices (0x%lx)!\n", hr
);
827 std::for_each(CaptureDevices
.cbegin(), CaptureDevices
.cend(), add_device
);
836 BackendPtr
DSoundBackendFactory::createBackend(DeviceBase
*device
, BackendType type
)
838 if(type
== BackendType::Playback
)
839 return BackendPtr
{new DSoundPlayback
{device
}};
840 if(type
== BackendType::Capture
)
841 return BackendPtr
{new DSoundCapture
{device
}};