Better protect against negative attenuation
[openal-soft.git] / Alc / dsound.c
blob5779e5f78312df2e1fe32bf57cd829a2745328f9
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., 59 Temple Place - Suite 330,
17 * Boston, MA 02111-1307, USA.
18 * Or go to http://www.gnu.org/copyleft/lgpl.html
21 #include "config.h"
23 #define _WIN32_WINNT 0x0500
24 #define INITGUID
25 #include <stdlib.h>
26 #include <stdio.h>
27 #include <memory.h>
29 #include <dsound.h>
30 #include <mmreg.h>
31 #ifndef _WAVEFORMATEXTENSIBLE_
32 #include <ks.h>
33 #include <ksmedia.h>
34 #endif
36 #include "alMain.h"
37 #include "AL/al.h"
38 #include "AL/alc.h"
40 #ifndef DSSPEAKER_5POINT1
41 #define DSSPEAKER_5POINT1 6
42 #endif
43 #ifndef DSSPEAKER_7POINT1
44 #define DSSPEAKER_7POINT1 7
45 #endif
47 DEFINE_GUID(KSDATAFORMAT_SUBTYPE_PCM, 0x00000001, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71);
48 DEFINE_GUID(KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, 0x00000003, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71);
50 static void *ds_handle;
51 static HRESULT (WINAPI *pDirectSoundCreate)(LPCGUID pcGuidDevice, LPDIRECTSOUND *ppDS, LPUNKNOWN pUnkOuter);
52 static HRESULT (WINAPI *pDirectSoundEnumerateA)(LPDSENUMCALLBACKA pDSEnumCallback, LPVOID pContext);
55 typedef struct {
56 // DirectSound Playback Device
57 LPDIRECTSOUND lpDS;
58 LPDIRECTSOUNDBUFFER DSpbuffer;
59 LPDIRECTSOUNDBUFFER DSsbuffer;
61 volatile int killNow;
62 ALvoid *thread;
63 } DSoundData;
66 typedef struct {
67 ALCchar *name;
68 GUID guid;
69 } DevMap;
71 static const ALCchar dsDevice[] = "DirectSound Software";
72 static DevMap *DeviceList;
73 static ALuint NumDevices;
76 void *DSoundLoad(void)
78 if(!ds_handle)
80 #ifdef _WIN32
81 ds_handle = LoadLibraryA("dsound.dll");
82 if(ds_handle == NULL)
84 AL_PRINT("Failed to load dsound.dll\n");
85 return NULL;
88 #define LOAD_FUNC(f) do { \
89 p##f = (void*)GetProcAddress((HMODULE)ds_handle, #f); \
90 if(p##f == NULL) \
91 { \
92 FreeLibrary(ds_handle); \
93 ds_handle = NULL; \
94 AL_PRINT("Could not load %s from dsound.dll\n", #f); \
95 return NULL; \
96 } \
97 } while(0)
98 #else
99 ds_handle = (void*)0xDEADBEEF;
100 #define LOAD_FUNC(f) p##f = f
101 #endif
103 LOAD_FUNC(DirectSoundCreate);
104 LOAD_FUNC(DirectSoundEnumerateA);
105 #undef LOAD_FUNC
107 return ds_handle;
111 static BOOL CALLBACK DSoundEnumDevices(LPGUID guid, LPCSTR desc, LPCSTR drvname, LPVOID data)
113 char str[1024];
114 void *temp;
115 int count;
116 ALuint i;
118 (void)data;
119 (void)drvname;
121 if(!guid)
122 return TRUE;
124 count = 0;
125 do {
126 if(count == 0)
127 snprintf(str, sizeof(str), "%s via DirectSound", desc);
128 else
129 snprintf(str, sizeof(str), "%s #%d via DirectSound", desc, count+1);
130 count++;
132 for(i = 0;i < NumDevices;i++)
134 if(strcmp(str, DeviceList[i].name) == 0)
135 break;
137 } while(i != NumDevices);
139 temp = realloc(DeviceList, sizeof(DevMap) * (NumDevices+1));
140 if(temp)
142 DeviceList = temp;
143 DeviceList[NumDevices].name = strdup(str);
144 DeviceList[NumDevices].guid = *guid;
145 NumDevices++;
148 return TRUE;
152 static ALuint DSoundProc(ALvoid *ptr)
154 ALCdevice *pDevice = (ALCdevice*)ptr;
155 DSoundData *pData = (DSoundData*)pDevice->ExtraData;
156 DSBCAPS DSBCaps;
157 DWORD LastCursor = 0;
158 DWORD PlayCursor;
159 VOID *WritePtr1, *WritePtr2;
160 DWORD WriteCnt1, WriteCnt2;
161 BOOL Playing = FALSE;
162 DWORD FrameSize;
163 DWORD FragSize;
164 DWORD avail;
165 HRESULT err;
167 SetRTPriority();
169 memset(&DSBCaps, 0, sizeof(DSBCaps));
170 DSBCaps.dwSize = sizeof(DSBCaps);
171 err = IDirectSoundBuffer_GetCaps(pData->DSsbuffer, &DSBCaps);
172 if(FAILED(err))
174 AL_PRINT("Failed to get buffer caps: 0x%lx\n", err);
175 aluHandleDisconnect(pDevice);
176 return 1;
179 FrameSize = aluFrameSizeFromFormat(pDevice->Format);
180 FragSize = pDevice->UpdateSize * FrameSize;
182 IDirectSoundBuffer_GetCurrentPosition(pData->DSsbuffer, &LastCursor, NULL);
183 while(!pData->killNow)
185 // Get current play and write cursors
186 IDirectSoundBuffer_GetCurrentPosition(pData->DSsbuffer, &PlayCursor, NULL);
187 avail = (PlayCursor-LastCursor+DSBCaps.dwBufferBytes) % DSBCaps.dwBufferBytes;
189 if(avail < FragSize)
191 if(!Playing)
193 err = IDirectSoundBuffer_Play(pData->DSsbuffer, 0, 0, DSBPLAY_LOOPING);
194 if(FAILED(err))
196 AL_PRINT("Failed to play buffer: 0x%lx\n", err);
197 aluHandleDisconnect(pDevice);
198 return 1;
201 Sleep(1);
202 continue;
204 avail -= avail%FragSize;
206 // Lock output buffer
207 WriteCnt1 = 0;
208 WriteCnt2 = 0;
209 err = IDirectSoundBuffer_Lock(pData->DSsbuffer, LastCursor, avail, &WritePtr1, &WriteCnt1, &WritePtr2, &WriteCnt2, 0);
211 // If the buffer is lost, restore it and lock
212 if(err == DSERR_BUFFERLOST)
214 err = IDirectSoundBuffer_Restore(pData->DSsbuffer);
215 if(SUCCEEDED(err))
217 Playing = FALSE;
218 LastCursor = 0;
219 err = IDirectSoundBuffer_Lock(pData->DSsbuffer, 0, DSBCaps.dwBufferBytes, &WritePtr1, &WriteCnt1, &WritePtr2, &WriteCnt2, 0);
223 // Successfully locked the output buffer
224 if(SUCCEEDED(err))
226 // If we have an active context, mix data directly into output buffer otherwise fill with silence
227 aluMixData(pDevice, WritePtr1, WriteCnt1/FrameSize);
228 aluMixData(pDevice, WritePtr2, WriteCnt2/FrameSize);
230 // Unlock output buffer only when successfully locked
231 IDirectSoundBuffer_Unlock(pData->DSsbuffer, WritePtr1, WriteCnt1, WritePtr2, WriteCnt2);
233 else
235 AL_PRINT("Buffer lock error: %#lx\n", err);
236 aluHandleDisconnect(pDevice);
237 return 1;
240 // Update old write cursor location
241 LastCursor += WriteCnt1+WriteCnt2;
242 LastCursor %= DSBCaps.dwBufferBytes;
245 return 0;
248 static ALCboolean DSoundOpenPlayback(ALCdevice *device, const ALCchar *deviceName)
250 DSoundData *pData = NULL;
251 LPGUID guid = NULL;
252 HRESULT hr;
254 if(!DSoundLoad())
255 return ALC_FALSE;
257 if(!deviceName)
258 deviceName = dsDevice;
259 else if(strcmp(deviceName, dsDevice) != 0)
261 ALuint i;
263 if(!DeviceList)
265 hr = pDirectSoundEnumerateA(DSoundEnumDevices, NULL);
266 if(FAILED(hr))
267 AL_PRINT("Error enumerating DirectSound devices (%#x)!\n", (unsigned int)hr);
270 for(i = 0;i < NumDevices;i++)
272 if(strcmp(deviceName, DeviceList[i].name) == 0)
274 guid = &DeviceList[i].guid;
275 break;
278 if(i == NumDevices)
279 return ALC_FALSE;
282 //Initialise requested device
283 pData = calloc(1, sizeof(DSoundData));
284 if(!pData)
286 alcSetError(device, ALC_OUT_OF_MEMORY);
287 return ALC_FALSE;
290 //DirectSound Init code
291 hr = pDirectSoundCreate(guid, &pData->lpDS, NULL);
292 if(SUCCEEDED(hr))
293 hr = IDirectSound_SetCooperativeLevel(pData->lpDS, GetForegroundWindow(), DSSCL_PRIORITY);
294 if(FAILED(hr))
296 if(pData->lpDS)
297 IDirectSound_Release(pData->lpDS);
298 free(pData);
299 AL_PRINT("Device init failed: 0x%08lx\n", hr);
300 return ALC_FALSE;
303 device->szDeviceName = strdup(deviceName);
304 device->ExtraData = pData;
305 return ALC_TRUE;
308 static void DSoundClosePlayback(ALCdevice *device)
310 DSoundData *pData = device->ExtraData;
312 IDirectSound_Release(pData->lpDS);
313 free(pData);
314 device->ExtraData = NULL;
317 static ALCboolean DSoundResetPlayback(ALCdevice *device)
319 DSoundData *pData = (DSoundData*)device->ExtraData;
320 DSBUFFERDESC DSBDescription;
321 WAVEFORMATEXTENSIBLE OutputType;
322 DWORD frameSize = 0;
323 ALenum format = 0;
324 DWORD speakers;
325 HRESULT hr;
327 memset(&OutputType, 0, sizeof(OutputType));
329 hr = IDirectSound_GetSpeakerConfig(pData->lpDS, &speakers);
330 if(SUCCEEDED(hr) && ConfigValueExists(NULL, "format"))
332 if(aluChannelsFromFormat(device->Format) == 1)
333 speakers = DSSPEAKER_COMBINED(DSSPEAKER_MONO, 0);
334 else if(aluChannelsFromFormat(device->Format) == 2)
335 speakers = DSSPEAKER_COMBINED(DSSPEAKER_STEREO, 0);
336 else if(aluChannelsFromFormat(device->Format) == 4)
337 speakers = DSSPEAKER_COMBINED(DSSPEAKER_QUAD, 0);
338 else if(aluChannelsFromFormat(device->Format) == 6)
339 speakers = DSSPEAKER_COMBINED(DSSPEAKER_5POINT1, 0);
340 else if(aluChannelsFromFormat(device->Format) == 8)
341 speakers = DSSPEAKER_COMBINED(DSSPEAKER_7POINT1, 0);
342 else
344 AL_PRINT("Unknown format: 0x%x\n", device->Format);
345 return ALC_FALSE;
348 if(SUCCEEDED(hr))
350 speakers = DSSPEAKER_CONFIG(speakers);
351 if(speakers == DSSPEAKER_MONO)
353 if(aluBytesFromFormat(device->Format) == 1)
354 format = AL_FORMAT_MONO8;
355 else if(aluBytesFromFormat(device->Format) == 2)
356 format = AL_FORMAT_MONO16;
357 else if(aluBytesFromFormat(device->Format) == 4)
358 format = AL_FORMAT_MONO_FLOAT32;
359 OutputType.dwChannelMask = SPEAKER_FRONT_CENTER;
361 else if(speakers == DSSPEAKER_STEREO)
363 if(aluBytesFromFormat(device->Format) == 1)
364 format = AL_FORMAT_STEREO8;
365 else if(aluBytesFromFormat(device->Format) == 2)
366 format = AL_FORMAT_STEREO16;
367 else if(aluBytesFromFormat(device->Format) == 4)
368 format = AL_FORMAT_STEREO_FLOAT32;
369 OutputType.dwChannelMask = SPEAKER_FRONT_LEFT |
370 SPEAKER_FRONT_RIGHT;
372 else if(speakers == DSSPEAKER_QUAD)
374 if(aluBytesFromFormat(device->Format) == 1)
375 format = AL_FORMAT_QUAD8;
376 else if(aluBytesFromFormat(device->Format) == 2)
377 format = AL_FORMAT_QUAD16;
378 else if(aluBytesFromFormat(device->Format) == 4)
379 format = AL_FORMAT_QUAD32;
380 OutputType.dwChannelMask = SPEAKER_FRONT_LEFT |
381 SPEAKER_FRONT_RIGHT |
382 SPEAKER_BACK_LEFT |
383 SPEAKER_BACK_RIGHT;
385 else if(speakers == DSSPEAKER_5POINT1)
387 if(aluBytesFromFormat(device->Format) == 1)
388 format = AL_FORMAT_51CHN8;
389 else if(aluBytesFromFormat(device->Format) == 2)
390 format = AL_FORMAT_51CHN16;
391 else if(aluBytesFromFormat(device->Format) == 4)
392 format = AL_FORMAT_51CHN32;
393 OutputType.dwChannelMask = SPEAKER_FRONT_LEFT |
394 SPEAKER_FRONT_RIGHT |
395 SPEAKER_FRONT_CENTER |
396 SPEAKER_LOW_FREQUENCY |
397 SPEAKER_BACK_LEFT |
398 SPEAKER_BACK_RIGHT;
400 else if(speakers == DSSPEAKER_7POINT1)
402 if(aluBytesFromFormat(device->Format) == 1)
403 format = AL_FORMAT_71CHN8;
404 else if(aluBytesFromFormat(device->Format) == 2)
405 format = AL_FORMAT_71CHN16;
406 else if(aluBytesFromFormat(device->Format) == 4)
407 format = AL_FORMAT_71CHN32;
408 OutputType.dwChannelMask = SPEAKER_FRONT_LEFT |
409 SPEAKER_FRONT_RIGHT |
410 SPEAKER_FRONT_CENTER |
411 SPEAKER_LOW_FREQUENCY |
412 SPEAKER_BACK_LEFT |
413 SPEAKER_BACK_RIGHT |
414 SPEAKER_SIDE_LEFT |
415 SPEAKER_SIDE_RIGHT;
417 else
418 format = device->Format;
419 frameSize = aluFrameSizeFromFormat(format);
421 OutputType.Format.wFormatTag = WAVE_FORMAT_PCM;
422 OutputType.Format.nChannels = aluChannelsFromFormat(format);
423 OutputType.Format.wBitsPerSample = aluBytesFromFormat(format) * 8;
424 OutputType.Format.nBlockAlign = OutputType.Format.nChannels*OutputType.Format.wBitsPerSample/8;
425 OutputType.Format.nSamplesPerSec = device->Frequency;
426 OutputType.Format.nAvgBytesPerSec = OutputType.Format.nSamplesPerSec*OutputType.Format.nBlockAlign;
427 OutputType.Format.cbSize = 0;
430 if(OutputType.Format.nChannels > 2 || OutputType.Format.wBitsPerSample > 16)
432 OutputType.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
433 OutputType.Samples.wValidBitsPerSample = OutputType.Format.wBitsPerSample;
434 OutputType.Format.cbSize = 22;
435 if(OutputType.Format.wBitsPerSample == 32)
436 OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
437 else
438 OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
440 else
442 if(SUCCEEDED(hr))
444 memset(&DSBDescription,0,sizeof(DSBUFFERDESC));
445 DSBDescription.dwSize=sizeof(DSBUFFERDESC);
446 DSBDescription.dwFlags=DSBCAPS_PRIMARYBUFFER;
447 hr = IDirectSound_CreateSoundBuffer(pData->lpDS, &DSBDescription, &pData->DSpbuffer, NULL);
449 if(SUCCEEDED(hr))
450 hr = IDirectSoundBuffer_SetFormat(pData->DSpbuffer,&OutputType.Format);
453 if(SUCCEEDED(hr))
455 memset(&DSBDescription,0,sizeof(DSBUFFERDESC));
456 DSBDescription.dwSize=sizeof(DSBUFFERDESC);
457 DSBDescription.dwFlags=DSBCAPS_GLOBALFOCUS|DSBCAPS_GETCURRENTPOSITION2;
458 DSBDescription.dwBufferBytes=device->UpdateSize * device->NumUpdates * frameSize;
459 DSBDescription.lpwfxFormat=&OutputType.Format;
460 hr = IDirectSound_CreateSoundBuffer(pData->lpDS, &DSBDescription, &pData->DSsbuffer, NULL);
463 if(SUCCEEDED(hr))
465 device->TimeRes = (ALuint64)device->UpdateSize * 1000000000 /
466 device->Frequency;
467 device->Format = format;
468 SetDefaultWFXChannelOrder(device);
469 pData->thread = StartThread(DSoundProc, device);
470 if(!pData->thread)
471 hr = E_FAIL;
474 if(FAILED(hr))
476 if (pData->DSsbuffer)
477 IDirectSoundBuffer_Release(pData->DSsbuffer);
478 pData->DSsbuffer = NULL;
479 if (pData->DSpbuffer)
480 IDirectSoundBuffer_Release(pData->DSpbuffer);
481 pData->DSpbuffer = NULL;
482 return ALC_FALSE;
485 return ALC_TRUE;
488 static void DSoundStopPlayback(ALCdevice *device)
490 DSoundData *pData = device->ExtraData;
492 if(!pData->thread)
493 return;
495 pData->killNow = 1;
496 StopThread(pData->thread);
497 pData->thread = NULL;
499 pData->killNow = 0;
501 IDirectSoundBuffer_Release(pData->DSsbuffer);
502 pData->DSsbuffer = NULL;
503 if (pData->DSpbuffer)
504 IDirectSoundBuffer_Release(pData->DSpbuffer);
505 pData->DSpbuffer = NULL;
509 static ALCboolean DSoundOpenCapture(ALCdevice *pDevice, const ALCchar *deviceName)
511 (void)pDevice;
512 (void)deviceName;
513 return ALC_FALSE;
516 static void DSoundCloseCapture(ALCdevice *pDevice)
518 (void)pDevice;
521 static void DSoundStartCapture(ALCdevice *pDevice)
523 (void)pDevice;
526 static void DSoundStopCapture(ALCdevice *pDevice)
528 (void)pDevice;
531 static void DSoundCaptureSamples(ALCdevice *pDevice, ALCvoid *pBuffer, ALCuint lSamples)
533 (void)pDevice;
534 (void)pBuffer;
535 (void)lSamples;
538 static ALCuint DSoundAvailableSamples(ALCdevice *pDevice)
540 (void)pDevice;
541 return 0;
544 static ALuint64 DSoundGetTime(ALCdevice *Device)
546 return Device->SamplesPlayed * 1000000000 / Device->Frequency;
550 BackendFuncs DSoundFuncs = {
551 DSoundOpenPlayback,
552 DSoundClosePlayback,
553 DSoundResetPlayback,
554 DSoundStopPlayback,
555 DSoundOpenCapture,
556 DSoundCloseCapture,
557 DSoundStartCapture,
558 DSoundStopCapture,
559 DSoundCaptureSamples,
560 DSoundAvailableSamples,
561 DSoundGetTime
565 void alcDSoundInit(BackendFuncs *FuncList)
567 *FuncList = DSoundFuncs;
570 void alcDSoundDeinit(void)
572 ALuint i;
574 for(i = 0;i < NumDevices;++i)
575 free(DeviceList[i].name);
576 free(DeviceList);
577 DeviceList = NULL;
578 NumDevices = 0;
580 if(ds_handle)
582 #ifdef _WIN32
583 FreeLibrary(ds_handle);
584 #endif
585 ds_handle = NULL;
589 void alcDSoundProbe(int type)
591 if(!DSoundLoad()) return;
593 if(type == DEVICE_PROBE)
594 AppendDeviceList(dsDevice);
595 else if(type == ALL_DEVICE_PROBE)
597 HRESULT hr;
598 ALuint i;
600 for(i = 0;i < NumDevices;++i)
601 free(DeviceList[i].name);
602 free(DeviceList);
603 DeviceList = NULL;
604 NumDevices = 0;
606 hr = pDirectSoundEnumerateA(DSoundEnumDevices, NULL);
607 if(FAILED(hr))
608 AL_PRINT("Error enumerating DirectSound devices (%#x)!\n", (unsigned int)hr);
609 else
611 for(i = 0;i < NumDevices;i++)
612 AppendAllDeviceList(DeviceList[i].name);