Combine VECTOR_RESIZE and VECTOR_RESERVE
[openal-soft.git] / Alc / backends / dsound.c
blobda6fbacf72d5fa6a632815db6b331dbe6e9a01d2
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 <stdlib.h>
24 #include <stdio.h>
25 #include <memory.h>
27 #include <dsound.h>
28 #include <cguid.h>
29 #include <mmreg.h>
30 #ifndef _WAVEFORMATEXTENSIBLE_
31 #include <ks.h>
32 #include <ksmedia.h>
33 #endif
35 #include "alMain.h"
36 #include "alu.h"
37 #include "threads.h"
38 #include "compat.h"
39 #include "alstring.h"
41 #include "backends/base.h"
43 #ifndef DSSPEAKER_5POINT1
44 # define DSSPEAKER_5POINT1 0x00000006
45 #endif
46 #ifndef DSSPEAKER_5POINT1_BACK
47 # define DSSPEAKER_5POINT1_BACK 0x00000006
48 #endif
49 #ifndef DSSPEAKER_7POINT1
50 # define DSSPEAKER_7POINT1 0x00000007
51 #endif
52 #ifndef DSSPEAKER_7POINT1_SURROUND
53 # define DSSPEAKER_7POINT1_SURROUND 0x00000008
54 #endif
55 #ifndef DSSPEAKER_5POINT1_SURROUND
56 # define DSSPEAKER_5POINT1_SURROUND 0x00000009
57 #endif
60 DEFINE_GUID(KSDATAFORMAT_SUBTYPE_PCM, 0x00000001, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71);
61 DEFINE_GUID(KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, 0x00000003, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71);
63 #define DEVNAME_HEAD "OpenAL Soft on "
66 #ifdef HAVE_DYNLOAD
67 static void *ds_handle;
68 static HRESULT (WINAPI *pDirectSoundCreate)(const GUID *pcGuidDevice, IDirectSound **ppDS, IUnknown *pUnkOuter);
69 static HRESULT (WINAPI *pDirectSoundEnumerateW)(LPDSENUMCALLBACKW pDSEnumCallback, void *pContext);
70 static HRESULT (WINAPI *pDirectSoundCaptureCreate)(const GUID *pcGuidDevice, IDirectSoundCapture **ppDSC, IUnknown *pUnkOuter);
71 static HRESULT (WINAPI *pDirectSoundCaptureEnumerateW)(LPDSENUMCALLBACKW pDSEnumCallback, void *pContext);
73 #define DirectSoundCreate pDirectSoundCreate
74 #define DirectSoundEnumerateW pDirectSoundEnumerateW
75 #define DirectSoundCaptureCreate pDirectSoundCaptureCreate
76 #define DirectSoundCaptureEnumerateW pDirectSoundCaptureEnumerateW
77 #endif
80 static ALCboolean DSoundLoad(void)
82 #ifdef HAVE_DYNLOAD
83 if(!ds_handle)
85 ds_handle = LoadLib("dsound.dll");
86 if(ds_handle == NULL)
88 ERR("Failed to load dsound.dll\n");
89 return ALC_FALSE;
92 #define LOAD_FUNC(f) do { \
93 p##f = GetSymbol(ds_handle, #f); \
94 if(p##f == NULL) { \
95 CloseLib(ds_handle); \
96 ds_handle = NULL; \
97 return ALC_FALSE; \
98 } \
99 } while(0)
100 LOAD_FUNC(DirectSoundCreate);
101 LOAD_FUNC(DirectSoundEnumerateW);
102 LOAD_FUNC(DirectSoundCaptureCreate);
103 LOAD_FUNC(DirectSoundCaptureEnumerateW);
104 #undef LOAD_FUNC
106 #endif
107 return ALC_TRUE;
111 #define MAX_UPDATES 128
113 typedef struct {
114 al_string name;
115 GUID guid;
116 } DevMap;
117 TYPEDEF_VECTOR(DevMap, vector_DevMap)
119 static vector_DevMap PlaybackDevices;
120 static vector_DevMap CaptureDevices;
122 static void clear_devlist(vector_DevMap *list)
124 #define DEINIT_STR(i) AL_STRING_DEINIT((i)->name)
125 VECTOR_FOR_EACH(DevMap, *list, DEINIT_STR);
126 VECTOR_RESIZE(*list, 0, 0);
127 #undef DEINIT_STR
130 static BOOL CALLBACK DSoundEnumDevices(GUID *guid, const WCHAR *desc, const WCHAR* UNUSED(drvname), void *data)
132 vector_DevMap *devices = data;
133 OLECHAR *guidstr = NULL;
134 DevMap entry;
135 HRESULT hr;
136 int count;
138 if(!guid)
139 return TRUE;
141 AL_STRING_INIT(entry.name);
143 count = 0;
144 while(1)
146 const DevMap *iter;
148 al_string_copy_cstr(&entry.name, DEVNAME_HEAD);
149 al_string_append_wcstr(&entry.name, desc);
150 if(count != 0)
152 char str[64];
153 snprintf(str, sizeof(str), " #%d", count+1);
154 al_string_append_cstr(&entry.name, str);
157 #define MATCH_ENTRY(i) (al_string_cmp(entry.name, (i)->name) == 0)
158 VECTOR_FIND_IF(iter, const DevMap, *devices, MATCH_ENTRY);
159 if(iter == VECTOR_END(*devices)) break;
160 #undef MATCH_ENTRY
161 count++;
163 entry.guid = *guid;
165 hr = StringFromCLSID(guid, &guidstr);
166 if(SUCCEEDED(hr))
168 TRACE("Got device \"%s\", GUID \"%ls\"\n", al_string_get_cstr(entry.name), guidstr);
169 CoTaskMemFree(guidstr);
172 VECTOR_PUSH_BACK(*devices, entry);
174 return TRUE;
178 typedef struct ALCdsoundPlayback {
179 DERIVE_FROM_TYPE(ALCbackend);
181 IDirectSound *DS;
182 IDirectSoundBuffer *PrimaryBuffer;
183 IDirectSoundBuffer *Buffer;
184 IDirectSoundNotify *Notifies;
185 HANDLE NotifyEvent;
187 volatile int killNow;
188 althrd_t thread;
189 } ALCdsoundPlayback;
191 static int ALCdsoundPlayback_mixerProc(void *ptr);
193 static void ALCdsoundPlayback_Construct(ALCdsoundPlayback *self, ALCdevice *device);
194 static DECLARE_FORWARD(ALCdsoundPlayback, ALCbackend, void, Destruct)
195 static ALCenum ALCdsoundPlayback_open(ALCdsoundPlayback *self, const ALCchar *name);
196 static void ALCdsoundPlayback_close(ALCdsoundPlayback *self);
197 static ALCboolean ALCdsoundPlayback_reset(ALCdsoundPlayback *self);
198 static ALCboolean ALCdsoundPlayback_start(ALCdsoundPlayback *self);
199 static void ALCdsoundPlayback_stop(ALCdsoundPlayback *self);
200 static DECLARE_FORWARD2(ALCdsoundPlayback, ALCbackend, ALCenum, captureSamples, void*, ALCuint)
201 static DECLARE_FORWARD(ALCdsoundPlayback, ALCbackend, ALCuint, availableSamples)
202 static DECLARE_FORWARD(ALCdsoundPlayback, ALCbackend, ClockLatency, getClockLatency)
203 static DECLARE_FORWARD(ALCdsoundPlayback, ALCbackend, void, lock)
204 static DECLARE_FORWARD(ALCdsoundPlayback, ALCbackend, void, unlock)
205 DECLARE_DEFAULT_ALLOCATORS(ALCdsoundPlayback)
207 DEFINE_ALCBACKEND_VTABLE(ALCdsoundPlayback);
210 static void ALCdsoundPlayback_Construct(ALCdsoundPlayback *self, ALCdevice *device)
212 ALCbackend_Construct(STATIC_CAST(ALCbackend, self), device);
213 SET_VTABLE2(ALCdsoundPlayback, ALCbackend, self);
217 FORCE_ALIGN static int ALCdsoundPlayback_mixerProc(void *ptr)
219 ALCdsoundPlayback *self = ptr;
220 ALCdevice *device = STATIC_CAST(ALCbackend, self)->mDevice;
221 DSBCAPS DSBCaps;
222 DWORD LastCursor = 0;
223 DWORD PlayCursor;
224 void *WritePtr1, *WritePtr2;
225 DWORD WriteCnt1, WriteCnt2;
226 BOOL Playing = FALSE;
227 DWORD FrameSize;
228 DWORD FragSize;
229 DWORD avail;
230 HRESULT err;
232 SetRTPriority();
233 althrd_setname(althrd_current(), MIXER_THREAD_NAME);
235 memset(&DSBCaps, 0, sizeof(DSBCaps));
236 DSBCaps.dwSize = sizeof(DSBCaps);
237 err = IDirectSoundBuffer_GetCaps(self->Buffer, &DSBCaps);
238 if(FAILED(err))
240 ERR("Failed to get buffer caps: 0x%lx\n", err);
241 ALCdevice_Lock(device);
242 aluHandleDisconnect(device);
243 ALCdevice_Unlock(device);
244 return 1;
247 FrameSize = FrameSizeFromDevFmt(device->FmtChans, device->FmtType);
248 FragSize = device->UpdateSize * FrameSize;
250 IDirectSoundBuffer_GetCurrentPosition(self->Buffer, &LastCursor, NULL);
251 while(!self->killNow)
253 // Get current play cursor
254 IDirectSoundBuffer_GetCurrentPosition(self->Buffer, &PlayCursor, NULL);
255 avail = (PlayCursor-LastCursor+DSBCaps.dwBufferBytes) % DSBCaps.dwBufferBytes;
257 if(avail < FragSize)
259 if(!Playing)
261 err = IDirectSoundBuffer_Play(self->Buffer, 0, 0, DSBPLAY_LOOPING);
262 if(FAILED(err))
264 ERR("Failed to play buffer: 0x%lx\n", err);
265 ALCdevice_Lock(device);
266 aluHandleDisconnect(device);
267 ALCdevice_Unlock(device);
268 return 1;
270 Playing = TRUE;
273 avail = WaitForSingleObjectEx(self->NotifyEvent, 2000, FALSE);
274 if(avail != WAIT_OBJECT_0)
275 ERR("WaitForSingleObjectEx error: 0x%lx\n", avail);
276 continue;
278 avail -= avail%FragSize;
280 // Lock output buffer
281 WriteCnt1 = 0;
282 WriteCnt2 = 0;
283 err = IDirectSoundBuffer_Lock(self->Buffer, LastCursor, avail, &WritePtr1, &WriteCnt1, &WritePtr2, &WriteCnt2, 0);
285 // If the buffer is lost, restore it and lock
286 if(err == DSERR_BUFFERLOST)
288 WARN("Buffer lost, restoring...\n");
289 err = IDirectSoundBuffer_Restore(self->Buffer);
290 if(SUCCEEDED(err))
292 Playing = FALSE;
293 LastCursor = 0;
294 err = IDirectSoundBuffer_Lock(self->Buffer, 0, DSBCaps.dwBufferBytes, &WritePtr1, &WriteCnt1, &WritePtr2, &WriteCnt2, 0);
298 // Successfully locked the output buffer
299 if(SUCCEEDED(err))
301 // If we have an active context, mix data directly into output buffer otherwise fill with silence
302 aluMixData(device, WritePtr1, WriteCnt1/FrameSize);
303 aluMixData(device, WritePtr2, WriteCnt2/FrameSize);
305 // Unlock output buffer only when successfully locked
306 IDirectSoundBuffer_Unlock(self->Buffer, WritePtr1, WriteCnt1, WritePtr2, WriteCnt2);
308 else
310 ERR("Buffer lock error: %#lx\n", err);
311 ALCdevice_Lock(device);
312 aluHandleDisconnect(device);
313 ALCdevice_Unlock(device);
314 return 1;
317 // Update old write cursor location
318 LastCursor += WriteCnt1+WriteCnt2;
319 LastCursor %= DSBCaps.dwBufferBytes;
322 return 0;
325 static ALCenum ALCdsoundPlayback_open(ALCdsoundPlayback *self, const ALCchar *deviceName)
327 ALCdevice *device = STATIC_CAST(ALCbackend, self)->mDevice;
328 const GUID *guid = NULL;
329 HRESULT hr, hrcom;
331 if(VECTOR_SIZE(PlaybackDevices) == 0)
333 /* Initialize COM to prevent name truncation */
334 hrcom = CoInitialize(NULL);
335 hr = DirectSoundEnumerateW(DSoundEnumDevices, &PlaybackDevices);
336 if(FAILED(hr))
337 ERR("Error enumerating DirectSound devices (0x%lx)!\n", hr);
338 if(SUCCEEDED(hrcom))
339 CoUninitialize();
342 if(!deviceName && VECTOR_SIZE(PlaybackDevices) > 0)
344 deviceName = al_string_get_cstr(VECTOR_FRONT(PlaybackDevices).name);
345 guid = &VECTOR_FRONT(PlaybackDevices).guid;
347 else
349 const DevMap *iter;
351 #define MATCH_NAME(i) (al_string_cmp_cstr((i)->name, deviceName) == 0)
352 VECTOR_FIND_IF(iter, const DevMap, PlaybackDevices, MATCH_NAME);
353 #undef MATCH_NAME
354 if(iter == VECTOR_END(PlaybackDevices))
355 return ALC_INVALID_VALUE;
356 guid = &iter->guid;
359 hr = DS_OK;
360 self->NotifyEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
361 if(self->NotifyEvent == NULL)
362 hr = E_FAIL;
364 //DirectSound Init code
365 if(SUCCEEDED(hr))
366 hr = DirectSoundCreate(guid, &self->DS, NULL);
367 if(SUCCEEDED(hr))
368 hr = IDirectSound_SetCooperativeLevel(self->DS, GetForegroundWindow(), DSSCL_PRIORITY);
369 if(FAILED(hr))
371 if(self->DS)
372 IDirectSound_Release(self->DS);
373 self->DS = NULL;
374 if(self->NotifyEvent)
375 CloseHandle(self->NotifyEvent);
376 self->NotifyEvent = NULL;
378 ERR("Device init failed: 0x%08lx\n", hr);
379 return ALC_INVALID_VALUE;
382 al_string_copy_cstr(&device->DeviceName, deviceName);
384 return ALC_NO_ERROR;
387 static void ALCdsoundPlayback_close(ALCdsoundPlayback *self)
389 if(self->Notifies)
390 IDirectSoundNotify_Release(self->Notifies);
391 self->Notifies = NULL;
392 if(self->Buffer)
393 IDirectSoundBuffer_Release(self->Buffer);
394 self->Buffer = NULL;
395 if(self->PrimaryBuffer != NULL)
396 IDirectSoundBuffer_Release(self->PrimaryBuffer);
397 self->PrimaryBuffer = NULL;
399 IDirectSound_Release(self->DS);
400 self->DS = NULL;
401 CloseHandle(self->NotifyEvent);
402 self->NotifyEvent = NULL;
405 static ALCboolean ALCdsoundPlayback_reset(ALCdsoundPlayback *self)
407 ALCdevice *device = STATIC_CAST(ALCbackend, self)->mDevice;
408 DSBUFFERDESC DSBDescription;
409 WAVEFORMATEXTENSIBLE OutputType;
410 DWORD speakers;
411 HRESULT hr;
413 memset(&OutputType, 0, sizeof(OutputType));
415 if(self->Notifies)
416 IDirectSoundNotify_Release(self->Notifies);
417 self->Notifies = NULL;
418 if(self->Buffer)
419 IDirectSoundBuffer_Release(self->Buffer);
420 self->Buffer = NULL;
421 if(self->PrimaryBuffer != NULL)
422 IDirectSoundBuffer_Release(self->PrimaryBuffer);
423 self->PrimaryBuffer = NULL;
425 switch(device->FmtType)
427 case DevFmtByte:
428 device->FmtType = DevFmtUByte;
429 break;
430 case DevFmtFloat:
431 if((device->Flags&DEVICE_SAMPLE_TYPE_REQUEST))
432 break;
433 /* fall-through */
434 case DevFmtUShort:
435 device->FmtType = DevFmtShort;
436 break;
437 case DevFmtUInt:
438 device->FmtType = DevFmtInt;
439 break;
440 case DevFmtUByte:
441 case DevFmtShort:
442 case DevFmtInt:
443 break;
446 hr = IDirectSound_GetSpeakerConfig(self->DS, &speakers);
447 if(SUCCEEDED(hr))
449 speakers = DSSPEAKER_CONFIG(speakers);
450 if(!(device->Flags&DEVICE_CHANNELS_REQUEST))
452 if(speakers == DSSPEAKER_MONO)
453 device->FmtChans = DevFmtMono;
454 else if(speakers == DSSPEAKER_STEREO || speakers == DSSPEAKER_HEADPHONE)
455 device->FmtChans = DevFmtStereo;
456 else if(speakers == DSSPEAKER_QUAD)
457 device->FmtChans = DevFmtQuad;
458 else if(speakers == DSSPEAKER_5POINT1_SURROUND)
459 device->FmtChans = DevFmtX51;
460 else if(speakers == DSSPEAKER_5POINT1_BACK)
461 device->FmtChans = DevFmtX51Rear;
462 else if(speakers == DSSPEAKER_7POINT1 || speakers == DSSPEAKER_7POINT1_SURROUND)
463 device->FmtChans = DevFmtX71;
464 else
465 ERR("Unknown system speaker config: 0x%lx\n", speakers);
467 device->IsHeadphones = (device->FmtChans == DevFmtStereo &&
468 speakers == DSSPEAKER_HEADPHONE);
470 switch(device->FmtChans)
472 case DevFmtMono:
473 OutputType.dwChannelMask = SPEAKER_FRONT_CENTER;
474 break;
475 case DevFmtBFormat3D:
476 device->FmtChans = DevFmtStereo;
477 /*fall-through*/
478 case DevFmtStereo:
479 OutputType.dwChannelMask = SPEAKER_FRONT_LEFT |
480 SPEAKER_FRONT_RIGHT;
481 break;
482 case DevFmtQuad:
483 OutputType.dwChannelMask = SPEAKER_FRONT_LEFT |
484 SPEAKER_FRONT_RIGHT |
485 SPEAKER_BACK_LEFT |
486 SPEAKER_BACK_RIGHT;
487 break;
488 case DevFmtX51:
489 OutputType.dwChannelMask = SPEAKER_FRONT_LEFT |
490 SPEAKER_FRONT_RIGHT |
491 SPEAKER_FRONT_CENTER |
492 SPEAKER_LOW_FREQUENCY |
493 SPEAKER_SIDE_LEFT |
494 SPEAKER_SIDE_RIGHT;
495 break;
496 case DevFmtX51Rear:
497 OutputType.dwChannelMask = SPEAKER_FRONT_LEFT |
498 SPEAKER_FRONT_RIGHT |
499 SPEAKER_FRONT_CENTER |
500 SPEAKER_LOW_FREQUENCY |
501 SPEAKER_BACK_LEFT |
502 SPEAKER_BACK_RIGHT;
503 break;
504 case DevFmtX61:
505 OutputType.dwChannelMask = SPEAKER_FRONT_LEFT |
506 SPEAKER_FRONT_RIGHT |
507 SPEAKER_FRONT_CENTER |
508 SPEAKER_LOW_FREQUENCY |
509 SPEAKER_BACK_CENTER |
510 SPEAKER_SIDE_LEFT |
511 SPEAKER_SIDE_RIGHT;
512 break;
513 case DevFmtX71:
514 OutputType.dwChannelMask = SPEAKER_FRONT_LEFT |
515 SPEAKER_FRONT_RIGHT |
516 SPEAKER_FRONT_CENTER |
517 SPEAKER_LOW_FREQUENCY |
518 SPEAKER_BACK_LEFT |
519 SPEAKER_BACK_RIGHT |
520 SPEAKER_SIDE_LEFT |
521 SPEAKER_SIDE_RIGHT;
522 break;
525 retry_open:
526 hr = S_OK;
527 OutputType.Format.wFormatTag = WAVE_FORMAT_PCM;
528 OutputType.Format.nChannels = ChannelsFromDevFmt(device->FmtChans);
529 OutputType.Format.wBitsPerSample = BytesFromDevFmt(device->FmtType) * 8;
530 OutputType.Format.nBlockAlign = OutputType.Format.nChannels*OutputType.Format.wBitsPerSample/8;
531 OutputType.Format.nSamplesPerSec = device->Frequency;
532 OutputType.Format.nAvgBytesPerSec = OutputType.Format.nSamplesPerSec*OutputType.Format.nBlockAlign;
533 OutputType.Format.cbSize = 0;
536 if(OutputType.Format.nChannels > 2 || device->FmtType == DevFmtFloat)
538 OutputType.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
539 OutputType.Samples.wValidBitsPerSample = OutputType.Format.wBitsPerSample;
540 OutputType.Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX);
541 if(device->FmtType == DevFmtFloat)
542 OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
543 else
544 OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
546 if(self->PrimaryBuffer)
547 IDirectSoundBuffer_Release(self->PrimaryBuffer);
548 self->PrimaryBuffer = NULL;
550 else
552 if(SUCCEEDED(hr) && !self->PrimaryBuffer)
554 memset(&DSBDescription,0,sizeof(DSBUFFERDESC));
555 DSBDescription.dwSize=sizeof(DSBUFFERDESC);
556 DSBDescription.dwFlags=DSBCAPS_PRIMARYBUFFER;
557 hr = IDirectSound_CreateSoundBuffer(self->DS, &DSBDescription, &self->PrimaryBuffer, NULL);
559 if(SUCCEEDED(hr))
560 hr = IDirectSoundBuffer_SetFormat(self->PrimaryBuffer,&OutputType.Format);
563 if(SUCCEEDED(hr))
565 if(device->NumUpdates > MAX_UPDATES)
567 device->UpdateSize = (device->UpdateSize*device->NumUpdates +
568 MAX_UPDATES-1) / MAX_UPDATES;
569 device->NumUpdates = MAX_UPDATES;
572 memset(&DSBDescription,0,sizeof(DSBUFFERDESC));
573 DSBDescription.dwSize=sizeof(DSBUFFERDESC);
574 DSBDescription.dwFlags=DSBCAPS_CTRLPOSITIONNOTIFY|DSBCAPS_GETCURRENTPOSITION2|DSBCAPS_GLOBALFOCUS;
575 DSBDescription.dwBufferBytes=device->UpdateSize * device->NumUpdates *
576 OutputType.Format.nBlockAlign;
577 DSBDescription.lpwfxFormat=&OutputType.Format;
578 hr = IDirectSound_CreateSoundBuffer(self->DS, &DSBDescription, &self->Buffer, NULL);
579 if(FAILED(hr) && device->FmtType == DevFmtFloat)
581 device->FmtType = DevFmtShort;
582 goto retry_open;
586 if(SUCCEEDED(hr))
588 hr = IDirectSoundBuffer_QueryInterface(self->Buffer, &IID_IDirectSoundNotify, (void**)&self->Notifies);
589 if(SUCCEEDED(hr))
591 DSBPOSITIONNOTIFY notifies[MAX_UPDATES];
592 ALuint i;
594 for(i = 0;i < device->NumUpdates;++i)
596 notifies[i].dwOffset = i * device->UpdateSize *
597 OutputType.Format.nBlockAlign;
598 notifies[i].hEventNotify = self->NotifyEvent;
600 if(IDirectSoundNotify_SetNotificationPositions(self->Notifies, device->NumUpdates, notifies) != DS_OK)
601 hr = E_FAIL;
605 if(FAILED(hr))
607 if(self->Notifies != NULL)
608 IDirectSoundNotify_Release(self->Notifies);
609 self->Notifies = NULL;
610 if(self->Buffer != NULL)
611 IDirectSoundBuffer_Release(self->Buffer);
612 self->Buffer = NULL;
613 if(self->PrimaryBuffer != NULL)
614 IDirectSoundBuffer_Release(self->PrimaryBuffer);
615 self->PrimaryBuffer = NULL;
616 return ALC_FALSE;
619 ResetEvent(self->NotifyEvent);
620 SetDefaultWFXChannelOrder(device);
622 return ALC_TRUE;
625 static ALCboolean ALCdsoundPlayback_start(ALCdsoundPlayback *self)
627 self->killNow = 0;
628 if(althrd_create(&self->thread, ALCdsoundPlayback_mixerProc, self) != althrd_success)
629 return ALC_FALSE;
631 return ALC_TRUE;
634 static void ALCdsoundPlayback_stop(ALCdsoundPlayback *self)
636 int res;
638 if(self->killNow)
639 return;
641 self->killNow = 1;
642 althrd_join(self->thread, &res);
644 IDirectSoundBuffer_Stop(self->Buffer);
649 typedef struct ALCdsoundCapture {
650 DERIVE_FROM_TYPE(ALCbackend);
652 IDirectSoundCapture *DSC;
653 IDirectSoundCaptureBuffer *DSCbuffer;
654 DWORD BufferBytes;
655 DWORD Cursor;
657 ll_ringbuffer_t *Ring;
658 } ALCdsoundCapture;
660 static void ALCdsoundCapture_Construct(ALCdsoundCapture *self, ALCdevice *device);
661 static DECLARE_FORWARD(ALCdsoundCapture, ALCbackend, void, Destruct)
662 static ALCenum ALCdsoundCapture_open(ALCdsoundCapture *self, const ALCchar *name);
663 static void ALCdsoundCapture_close(ALCdsoundCapture *self);
664 static DECLARE_FORWARD(ALCdsoundCapture, ALCbackend, ALCboolean, reset)
665 static ALCboolean ALCdsoundCapture_start(ALCdsoundCapture *self);
666 static void ALCdsoundCapture_stop(ALCdsoundCapture *self);
667 static ALCenum ALCdsoundCapture_captureSamples(ALCdsoundCapture *self, ALCvoid *buffer, ALCuint samples);
668 static ALCuint ALCdsoundCapture_availableSamples(ALCdsoundCapture *self);
669 static DECLARE_FORWARD(ALCdsoundCapture, ALCbackend, ClockLatency, getClockLatency)
670 static DECLARE_FORWARD(ALCdsoundCapture, ALCbackend, void, lock)
671 static DECLARE_FORWARD(ALCdsoundCapture, ALCbackend, void, unlock)
672 DECLARE_DEFAULT_ALLOCATORS(ALCdsoundCapture)
674 DEFINE_ALCBACKEND_VTABLE(ALCdsoundCapture);
676 static void ALCdsoundCapture_Construct(ALCdsoundCapture *self, ALCdevice *device)
678 ALCbackend_Construct(STATIC_CAST(ALCbackend, self), device);
679 SET_VTABLE2(ALCdsoundCapture, ALCbackend, self);
683 static ALCenum ALCdsoundCapture_open(ALCdsoundCapture *self, const ALCchar *deviceName)
685 ALCdevice *device = STATIC_CAST(ALCbackend, self)->mDevice;
686 WAVEFORMATEXTENSIBLE InputType;
687 DSCBUFFERDESC DSCBDescription;
688 const GUID *guid = NULL;
689 HRESULT hr, hrcom;
690 ALuint samples;
692 if(VECTOR_SIZE(CaptureDevices) == 0)
694 /* Initialize COM to prevent name truncation */
695 hrcom = CoInitialize(NULL);
696 hr = DirectSoundCaptureEnumerateW(DSoundEnumDevices, &CaptureDevices);
697 if(FAILED(hr))
698 ERR("Error enumerating DirectSound devices (0x%lx)!\n", hr);
699 if(SUCCEEDED(hrcom))
700 CoUninitialize();
703 if(!deviceName && VECTOR_SIZE(CaptureDevices) > 0)
705 deviceName = al_string_get_cstr(VECTOR_FRONT(CaptureDevices).name);
706 guid = &VECTOR_FRONT(CaptureDevices).guid;
708 else
710 const DevMap *iter;
712 #define MATCH_NAME(i) (al_string_cmp_cstr((i)->name, deviceName) == 0)
713 VECTOR_FIND_IF(iter, const DevMap, CaptureDevices, MATCH_NAME);
714 #undef MATCH_NAME
715 if(iter == VECTOR_END(CaptureDevices))
716 return ALC_INVALID_VALUE;
717 guid = &iter->guid;
720 switch(device->FmtType)
722 case DevFmtByte:
723 case DevFmtUShort:
724 case DevFmtUInt:
725 WARN("%s capture samples not supported\n", DevFmtTypeString(device->FmtType));
726 return ALC_INVALID_ENUM;
728 case DevFmtUByte:
729 case DevFmtShort:
730 case DevFmtInt:
731 case DevFmtFloat:
732 break;
735 //DirectSoundCapture Init code
736 hr = DirectSoundCaptureCreate(guid, &self->DSC, NULL);
737 if(SUCCEEDED(hr))
739 memset(&InputType, 0, sizeof(InputType));
741 switch(device->FmtChans)
743 case DevFmtMono:
744 InputType.dwChannelMask = SPEAKER_FRONT_CENTER;
745 break;
746 case DevFmtStereo:
747 InputType.dwChannelMask = SPEAKER_FRONT_LEFT |
748 SPEAKER_FRONT_RIGHT;
749 break;
750 case DevFmtQuad:
751 InputType.dwChannelMask = SPEAKER_FRONT_LEFT |
752 SPEAKER_FRONT_RIGHT |
753 SPEAKER_BACK_LEFT |
754 SPEAKER_BACK_RIGHT;
755 break;
756 case DevFmtX51:
757 InputType.dwChannelMask = SPEAKER_FRONT_LEFT |
758 SPEAKER_FRONT_RIGHT |
759 SPEAKER_FRONT_CENTER |
760 SPEAKER_LOW_FREQUENCY |
761 SPEAKER_SIDE_LEFT |
762 SPEAKER_SIDE_RIGHT;
763 break;
764 case DevFmtX51Rear:
765 InputType.dwChannelMask = SPEAKER_FRONT_LEFT |
766 SPEAKER_FRONT_RIGHT |
767 SPEAKER_FRONT_CENTER |
768 SPEAKER_LOW_FREQUENCY |
769 SPEAKER_BACK_LEFT |
770 SPEAKER_BACK_RIGHT;
771 break;
772 case DevFmtX61:
773 InputType.dwChannelMask = SPEAKER_FRONT_LEFT |
774 SPEAKER_FRONT_RIGHT |
775 SPEAKER_FRONT_CENTER |
776 SPEAKER_LOW_FREQUENCY |
777 SPEAKER_BACK_CENTER |
778 SPEAKER_SIDE_LEFT |
779 SPEAKER_SIDE_RIGHT;
780 break;
781 case DevFmtX71:
782 InputType.dwChannelMask = SPEAKER_FRONT_LEFT |
783 SPEAKER_FRONT_RIGHT |
784 SPEAKER_FRONT_CENTER |
785 SPEAKER_LOW_FREQUENCY |
786 SPEAKER_BACK_LEFT |
787 SPEAKER_BACK_RIGHT |
788 SPEAKER_SIDE_LEFT |
789 SPEAKER_SIDE_RIGHT;
790 break;
791 case DevFmtBFormat3D:
792 break;
795 InputType.Format.wFormatTag = WAVE_FORMAT_PCM;
796 InputType.Format.nChannels = ChannelsFromDevFmt(device->FmtChans);
797 InputType.Format.wBitsPerSample = BytesFromDevFmt(device->FmtType) * 8;
798 InputType.Format.nBlockAlign = InputType.Format.nChannels*InputType.Format.wBitsPerSample/8;
799 InputType.Format.nSamplesPerSec = device->Frequency;
800 InputType.Format.nAvgBytesPerSec = InputType.Format.nSamplesPerSec*InputType.Format.nBlockAlign;
801 InputType.Format.cbSize = 0;
803 if(InputType.Format.nChannels > 2 || device->FmtType == DevFmtFloat)
805 InputType.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
806 InputType.Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX);
807 InputType.Samples.wValidBitsPerSample = InputType.Format.wBitsPerSample;
808 if(device->FmtType == DevFmtFloat)
809 InputType.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
810 else
811 InputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
814 samples = device->UpdateSize * device->NumUpdates;
815 samples = maxu(samples, 100 * device->Frequency / 1000);
817 memset(&DSCBDescription, 0, sizeof(DSCBUFFERDESC));
818 DSCBDescription.dwSize = sizeof(DSCBUFFERDESC);
819 DSCBDescription.dwFlags = 0;
820 DSCBDescription.dwBufferBytes = samples * InputType.Format.nBlockAlign;
821 DSCBDescription.lpwfxFormat = &InputType.Format;
823 hr = IDirectSoundCapture_CreateCaptureBuffer(self->DSC, &DSCBDescription, &self->DSCbuffer, NULL);
825 if(SUCCEEDED(hr))
827 self->Ring = ll_ringbuffer_create(device->UpdateSize*device->NumUpdates + 1,
828 InputType.Format.nBlockAlign);
829 if(self->Ring == NULL)
830 hr = DSERR_OUTOFMEMORY;
833 if(FAILED(hr))
835 ERR("Device init failed: 0x%08lx\n", hr);
837 ll_ringbuffer_free(self->Ring);
838 self->Ring = NULL;
839 if(self->DSCbuffer != NULL)
840 IDirectSoundCaptureBuffer_Release(self->DSCbuffer);
841 self->DSCbuffer = NULL;
842 if(self->DSC)
843 IDirectSoundCapture_Release(self->DSC);
844 self->DSC = NULL;
846 return ALC_INVALID_VALUE;
849 self->BufferBytes = DSCBDescription.dwBufferBytes;
850 SetDefaultWFXChannelOrder(device);
852 al_string_copy_cstr(&device->DeviceName, deviceName);
854 return ALC_NO_ERROR;
857 static void ALCdsoundCapture_close(ALCdsoundCapture *self)
859 ll_ringbuffer_free(self->Ring);
860 self->Ring = NULL;
862 if(self->DSCbuffer != NULL)
864 IDirectSoundCaptureBuffer_Stop(self->DSCbuffer);
865 IDirectSoundCaptureBuffer_Release(self->DSCbuffer);
866 self->DSCbuffer = NULL;
869 IDirectSoundCapture_Release(self->DSC);
870 self->DSC = NULL;
873 static ALCboolean ALCdsoundCapture_start(ALCdsoundCapture *self)
875 HRESULT hr;
877 hr = IDirectSoundCaptureBuffer_Start(self->DSCbuffer, DSCBSTART_LOOPING);
878 if(FAILED(hr))
880 ERR("start failed: 0x%08lx\n", hr);
881 aluHandleDisconnect(STATIC_CAST(ALCbackend, self)->mDevice);
882 return ALC_FALSE;
885 return ALC_TRUE;
888 static void ALCdsoundCapture_stop(ALCdsoundCapture *self)
890 HRESULT hr;
892 hr = IDirectSoundCaptureBuffer_Stop(self->DSCbuffer);
893 if(FAILED(hr))
895 ERR("stop failed: 0x%08lx\n", hr);
896 aluHandleDisconnect(STATIC_CAST(ALCbackend, self)->mDevice);
900 static ALCenum ALCdsoundCapture_captureSamples(ALCdsoundCapture *self, ALCvoid *buffer, ALCuint samples)
902 ll_ringbuffer_read(self->Ring, buffer, samples);
903 return ALC_NO_ERROR;
906 static ALCuint ALCdsoundCapture_availableSamples(ALCdsoundCapture *self)
908 ALCdevice *device = STATIC_CAST(ALCbackend, self)->mDevice;
909 DWORD ReadCursor, LastCursor, BufferBytes, NumBytes;
910 void *ReadPtr1, *ReadPtr2;
911 DWORD ReadCnt1, ReadCnt2;
912 DWORD FrameSize;
913 HRESULT hr;
915 if(!device->Connected)
916 goto done;
918 FrameSize = FrameSizeFromDevFmt(device->FmtChans, device->FmtType);
919 BufferBytes = self->BufferBytes;
920 LastCursor = self->Cursor;
922 hr = IDirectSoundCaptureBuffer_GetCurrentPosition(self->DSCbuffer, NULL, &ReadCursor);
923 if(SUCCEEDED(hr))
925 NumBytes = (ReadCursor-LastCursor + BufferBytes) % BufferBytes;
926 if(NumBytes == 0)
927 goto done;
928 hr = IDirectSoundCaptureBuffer_Lock(self->DSCbuffer, LastCursor, NumBytes,
929 &ReadPtr1, &ReadCnt1,
930 &ReadPtr2, &ReadCnt2, 0);
932 if(SUCCEEDED(hr))
934 ll_ringbuffer_write(self->Ring, ReadPtr1, ReadCnt1/FrameSize);
935 if(ReadPtr2 != NULL)
936 ll_ringbuffer_write(self->Ring, ReadPtr2, ReadCnt2/FrameSize);
937 hr = IDirectSoundCaptureBuffer_Unlock(self->DSCbuffer,
938 ReadPtr1, ReadCnt1,
939 ReadPtr2, ReadCnt2);
940 self->Cursor = (LastCursor+ReadCnt1+ReadCnt2) % BufferBytes;
943 if(FAILED(hr))
945 ERR("update failed: 0x%08lx\n", hr);
946 aluHandleDisconnect(device);
949 done:
950 return ll_ringbuffer_read_space(self->Ring);
954 static inline void AppendAllDevicesList2(const DevMap *entry)
955 { AppendAllDevicesList(al_string_get_cstr(entry->name)); }
956 static inline void AppendCaptureDeviceList2(const DevMap *entry)
957 { AppendCaptureDeviceList(al_string_get_cstr(entry->name)); }
959 typedef struct ALCdsoundBackendFactory {
960 DERIVE_FROM_TYPE(ALCbackendFactory);
961 } ALCdsoundBackendFactory;
962 #define ALCDSOUNDBACKENDFACTORY_INITIALIZER { { GET_VTABLE2(ALCdsoundBackendFactory, ALCbackendFactory) } }
964 ALCbackendFactory *ALCdsoundBackendFactory_getFactory(void);
966 static ALCboolean ALCdsoundBackendFactory_init(ALCdsoundBackendFactory *self);
967 static void ALCdsoundBackendFactory_deinit(ALCdsoundBackendFactory *self);
968 static ALCboolean ALCdsoundBackendFactory_querySupport(ALCdsoundBackendFactory *self, ALCbackend_Type type);
969 static void ALCdsoundBackendFactory_probe(ALCdsoundBackendFactory *self, enum DevProbe type);
970 static ALCbackend* ALCdsoundBackendFactory_createBackend(ALCdsoundBackendFactory *self, ALCdevice *device, ALCbackend_Type type);
971 DEFINE_ALCBACKENDFACTORY_VTABLE(ALCdsoundBackendFactory);
974 ALCbackendFactory *ALCdsoundBackendFactory_getFactory(void)
976 static ALCdsoundBackendFactory factory = ALCDSOUNDBACKENDFACTORY_INITIALIZER;
977 return STATIC_CAST(ALCbackendFactory, &factory);
981 static ALCboolean ALCdsoundBackendFactory_init(ALCdsoundBackendFactory* UNUSED(self))
983 VECTOR_INIT(PlaybackDevices);
984 VECTOR_INIT(CaptureDevices);
986 if(!DSoundLoad())
987 return ALC_FALSE;
988 return ALC_TRUE;
991 static void ALCdsoundBackendFactory_deinit(ALCdsoundBackendFactory* UNUSED(self))
993 clear_devlist(&PlaybackDevices);
994 VECTOR_DEINIT(PlaybackDevices);
996 clear_devlist(&CaptureDevices);
997 VECTOR_DEINIT(CaptureDevices);
999 #ifdef HAVE_DYNLOAD
1000 if(ds_handle)
1001 CloseLib(ds_handle);
1002 ds_handle = NULL;
1003 #endif
1006 static ALCboolean ALCdsoundBackendFactory_querySupport(ALCdsoundBackendFactory* UNUSED(self), ALCbackend_Type type)
1008 if(type == ALCbackend_Playback || type == ALCbackend_Capture)
1009 return ALC_TRUE;
1010 return ALC_FALSE;
1013 static void ALCdsoundBackendFactory_probe(ALCdsoundBackendFactory* UNUSED(self), enum DevProbe type)
1015 HRESULT hr, hrcom;
1017 /* Initialize COM to prevent name truncation */
1018 hrcom = CoInitialize(NULL);
1019 switch(type)
1021 case ALL_DEVICE_PROBE:
1022 clear_devlist(&PlaybackDevices);
1023 hr = DirectSoundEnumerateW(DSoundEnumDevices, &PlaybackDevices);
1024 if(FAILED(hr))
1025 ERR("Error enumerating DirectSound playback devices (0x%lx)!\n", hr);
1026 VECTOR_FOR_EACH(const DevMap, PlaybackDevices, AppendAllDevicesList2);
1027 break;
1029 case CAPTURE_DEVICE_PROBE:
1030 clear_devlist(&CaptureDevices);
1031 hr = DirectSoundCaptureEnumerateW(DSoundEnumDevices, &CaptureDevices);
1032 if(FAILED(hr))
1033 ERR("Error enumerating DirectSound capture devices (0x%lx)!\n", hr);
1034 VECTOR_FOR_EACH(const DevMap, CaptureDevices, AppendCaptureDeviceList2);
1035 break;
1037 if(SUCCEEDED(hrcom))
1038 CoUninitialize();
1041 static ALCbackend* ALCdsoundBackendFactory_createBackend(ALCdsoundBackendFactory* UNUSED(self), ALCdevice *device, ALCbackend_Type type)
1043 if(type == ALCbackend_Playback)
1045 ALCdsoundPlayback *backend;
1046 NEW_OBJ(backend, ALCdsoundPlayback)(device);
1047 if(!backend) return NULL;
1048 return STATIC_CAST(ALCbackend, backend);
1051 if(type == ALCbackend_Capture)
1053 ALCdsoundCapture *backend;
1054 NEW_OBJ(backend, ALCdsoundCapture)(device);
1055 if(!backend) return NULL;
1056 return STATIC_CAST(ALCbackend, backend);
1059 return NULL;