2 * Copyright 2010 Maarten Lankhorst for Codeweavers
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 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 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19 #define NONAMELESSUNION
28 #elif defined(HAVE_OPENAL_AL_H)
29 #include <OpenAL/al.h>
30 #include <OpenAL/alc.h>
37 #include "wine/debug.h"
38 #include "wine/unicode.h"
41 #include "mmdeviceapi.h"
44 #include "audioclient.h"
45 #include "endpointvolume.h"
46 #include "audiopolicy.h"
50 WINE_DEFAULT_DEBUG_CHANNEL(mmdevapi);
54 typedef struct ACRender ACRender;
55 typedef struct ACCapture ACCapture;
56 typedef struct ACSession ACSession;
57 typedef struct ASVolume ASVolume;
58 typedef struct AClock AClock;
60 typedef struct ACImpl {
61 const IAudioClientVtbl *lpVtbl;
66 CRITICAL_SECTION *crst;
68 DWORD locked, flags, bufsize, pad, padpartial, ofs, psize;
73 REFERENCE_TIME laststamp;
82 const IAudioRenderClientVtbl *lpVtbl;
87 static const IAudioClientVtbl ACImpl_Vtbl;
88 static const IAudioRenderClientVtbl ACRender_Vtbl;
90 static HRESULT AudioRenderClient_Create(ACImpl *parent, ACRender **ppv);
91 static void AudioRenderClient_Destroy(ACRender *This);
93 static int get_format_PCM(WAVEFORMATEX *format)
95 if (format->nChannels > 2) {
96 FIXME("nChannels > 2 not documented for WAVE_FORMAT_PCM!\n");
102 if (format->nBlockAlign != format->wBitsPerSample/8*format->nChannels) {
103 WARN("Invalid nBlockAlign %u, from %u %u\n",
104 format->nBlockAlign, format->wBitsPerSample, format->nChannels);
108 switch (format->wBitsPerSample) {
110 switch (format->nChannels) {
111 case 1: return AL_FORMAT_MONO8;
112 case 2: return AL_FORMAT_STEREO8;
116 switch (format->nChannels) {
117 case 1: return AL_FORMAT_MONO16;
118 case 2: return AL_FORMAT_STEREO16;
123 if (!(format->wBitsPerSample % 8))
124 WARN("Could not get OpenAL format (%d-bit, %d channels)\n",
125 format->wBitsPerSample, format->nChannels);
129 /* Speaker configs */
130 #define MONO SPEAKER_FRONT_CENTER
131 #define STEREO (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT)
132 #define REAR (SPEAKER_BACK_LEFT|SPEAKER_BACK_RIGHT)
133 #define QUAD (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_BACK_LEFT|SPEAKER_BACK_RIGHT)
134 #define X5DOT1 (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_BACK_LEFT|SPEAKER_BACK_RIGHT)
135 #define X6DOT1 (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_BACK_CENTER|SPEAKER_SIDE_LEFT|SPEAKER_SIDE_RIGHT)
136 #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)
138 static int get_format_EXT(WAVEFORMATEX *format)
140 WAVEFORMATEXTENSIBLE *wfe;
142 if(format->cbSize < sizeof(WAVEFORMATEXTENSIBLE)-sizeof(WAVEFORMATEX)) {
143 WARN("Invalid cbSize specified for WAVE_FORMAT_EXTENSIBLE (%d)\n", format->cbSize);
147 wfe = (WAVEFORMATEXTENSIBLE*)format;
148 wfe->Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE)-sizeof(WAVEFORMATEX);
149 if (wfe->Samples.wValidBitsPerSample &&
150 wfe->Samples.wValidBitsPerSample != format->wBitsPerSample) {
151 FIXME("wValidBitsPerSample(%u) != wBitsPerSample(%u) unsupported\n",
152 wfe->Samples.wValidBitsPerSample, format->wBitsPerSample);
156 TRACE("Extensible values:\n"
158 " ChannelMask = 0x%08x\n"
160 wfe->Samples.wReserved, wfe->dwChannelMask,
161 debugstr_guid(&wfe->SubFormat));
163 if (wfe->dwChannelMask != MONO
164 && wfe->dwChannelMask != STEREO
165 && !palIsExtensionPresent("AL_EXT_MCFORMATS")) {
166 /* QUAD PCM might still work, special case */
167 if (palIsExtensionPresent("AL_LOKI_quadriphonic")
168 && IsEqualGUID(&wfe->SubFormat, &KSDATAFORMAT_SUBTYPE_PCM)
169 && wfe->dwChannelMask == QUAD) {
170 if (format->wBitsPerSample == 16)
171 return AL_FORMAT_QUAD16_LOKI;
172 else if (format->wBitsPerSample == 8)
173 return AL_FORMAT_QUAD8_LOKI;
175 WARN("Not all formats available\n");
179 if(IsEqualGUID(&wfe->SubFormat, &KSDATAFORMAT_SUBTYPE_PCM)) {
180 if (format->wBitsPerSample == 8) {
181 switch (wfe->dwChannelMask) {
182 case MONO: return AL_FORMAT_MONO8;
183 case STEREO: return AL_FORMAT_STEREO8;
184 case REAR: return AL_FORMAT_REAR8;
185 case QUAD: return AL_FORMAT_QUAD8;
186 case X5DOT1: return AL_FORMAT_51CHN8;
187 case X6DOT1: return AL_FORMAT_61CHN8;
188 case X7DOT1: return AL_FORMAT_71CHN8;
191 } else if (format->wBitsPerSample == 16) {
192 switch (wfe->dwChannelMask) {
193 case MONO: return AL_FORMAT_MONO16;
194 case STEREO: return AL_FORMAT_STEREO16;
195 case REAR: return AL_FORMAT_REAR16;
196 case QUAD: return AL_FORMAT_QUAD16;
197 case X5DOT1: return AL_FORMAT_51CHN16;
198 case X6DOT1: return AL_FORMAT_61CHN16;
199 case X7DOT1: return AL_FORMAT_71CHN16;
203 else if (!(format->wBitsPerSample % 8))
204 ERR("Could not get OpenAL PCM format (%d-bit, mask 0x%08x)\n",
205 format->wBitsPerSample, wfe->dwChannelMask);
208 else if(IsEqualGUID(&wfe->SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT)) {
209 if (format->wBitsPerSample != 32) {
210 WARN("Invalid valid bits %u/32\n", format->wBitsPerSample);
213 switch (wfe->dwChannelMask) {
214 case MONO: return AL_FORMAT_MONO_FLOAT32;
215 case STEREO: return AL_FORMAT_STEREO_FLOAT32;
216 case REAR: return AL_FORMAT_REAR32;
217 case QUAD: return AL_FORMAT_QUAD32;
218 case X5DOT1: return AL_FORMAT_51CHN32;
219 case X6DOT1: return AL_FORMAT_61CHN32;
220 case X7DOT1: return AL_FORMAT_71CHN32;
222 ERR("Could not get OpenAL float format (%d-bit, mask 0x%08x)\n",
223 format->wBitsPerSample, wfe->dwChannelMask);
227 else if (!IsEqualGUID(&wfe->SubFormat, &GUID_NULL))
228 ERR("Unhandled extensible format: %s\n", debugstr_guid(&wfe->SubFormat));
232 static ALint get_format(WAVEFORMATEX *in)
235 if (in->wFormatTag == WAVE_FORMAT_PCM)
236 ret = get_format_PCM(in);
237 else if (in->wFormatTag == WAVE_FORMAT_EXTENSIBLE)
238 ret = get_format_EXT(in);
242 static REFERENCE_TIME gettime(void) {
243 LARGE_INTEGER stamp, freq;
244 QueryPerformanceCounter(&stamp);
245 QueryPerformanceFrequency(&freq);
246 return (stamp.QuadPart * (INT64)10000000) / freq.QuadPart;
249 HRESULT AudioClient_Create(MMDevice *parent, IAudioClient **ppv)
251 ACImpl *This = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*This));
252 *ppv = (IAudioClient*)This;
254 return E_OUTOFMEMORY;
255 This->crst = &parent->crst;
256 This->lpVtbl = &ACImpl_Vtbl;
258 This->parent = parent;
262 static void AudioClient_Destroy(ACImpl *This)
265 DeleteTimerQueueTimer(NULL, This->timer_id, INVALID_HANDLE_VALUE);
267 AudioRenderClient_Destroy(This->render);
268 if (This->parent->flow == eRender && This->init) {
269 setALContext(This->parent->ctx);
270 IAudioClient_Stop((IAudioClient*)This);
271 IAudioClient_Reset((IAudioClient*)This);
272 palDeleteSources(1, &This->source);
277 palcCaptureCloseDevice(This->capdev);
278 HeapFree(GetProcessHeap(), 0, This->pwfx);
279 HeapFree(GetProcessHeap(), 0, This->buffer);
280 HeapFree(GetProcessHeap(), 0, This);
283 static void CALLBACK AC_tick(void *data, BOOLEAN fired)
288 EnterCriticalSection(This->crst);
290 IAudioClient_GetCurrentPadding((IAudioClient*)This, &pad);
291 LeaveCriticalSection(This->crst);
294 /* Open device and set/update internal mixing format based on information
295 * openal provides us. if the device cannot be opened, assume 48khz
296 * Guessing the frequency is harmless, since if GetMixFormat fails to open
297 * the device, then Initialize will likely fail as well
299 static HRESULT AC_OpenRenderAL(ACImpl *This)
301 char alname[MAX_PATH];
302 MMDevice *cur = This->parent;
304 alname[sizeof(alname)-1] = 0;
306 return cur->ctx ? S_OK : AUDCLNT_E_SERVICE_NOT_RUNNING;
308 WideCharToMultiByte(CP_UNIXCP, 0, cur->alname, -1,
309 alname, sizeof(alname)/sizeof(*alname)-1, NULL, NULL);
310 cur->device = palcOpenDevice(alname);
312 ALCenum err = palcGetError(NULL);
313 FIXME("Could not open device %s: 0x%04x\n", alname, err);
314 return AUDCLNT_E_DEVICE_IN_USE;
316 cur->ctx = palcCreateContext(cur->device, NULL);
318 ALCenum err = palcGetError(cur->device);
319 FIXME("Could not create context: 0x%04x\n", err);
320 return AUDCLNT_E_SERVICE_NOT_RUNNING;
323 return AUDCLNT_E_DEVICE_IN_USE;
327 static HRESULT AC_OpenCaptureAL(ACImpl *This)
329 char alname[MAX_PATH];
332 freq = This->pwfx->nSamplesPerSec;
333 size = This->bufsize;
335 alname[sizeof(alname)-1] = 0;
337 FIXME("Attempting to open device while already open\n");
340 WideCharToMultiByte(CP_UNIXCP, 0, This->parent->alname, -1,
341 alname, sizeof(alname)/sizeof(*alname)-1, NULL, NULL);
342 This->capdev = palcCaptureOpenDevice(alname, freq, This->format, size);
344 ALCenum err = palcGetError(NULL);
345 FIXME("Could not open device %s with buf size %u: 0x%04x\n",
346 alname, This->bufsize, err);
347 return AUDCLNT_E_DEVICE_IN_USE;
352 static HRESULT WINAPI AC_QueryInterface(IAudioClient *iface, REFIID riid, void **ppv)
354 TRACE("(%p)->(%s,%p)\n", iface, debugstr_guid(riid), ppv);
359 if (IsEqualIID(riid, &IID_IUnknown)
360 || IsEqualIID(riid, &IID_IAudioClient))
363 IUnknown_AddRef((IUnknown*)*ppv);
366 WARN("Unknown interface %s\n", debugstr_guid(riid));
367 return E_NOINTERFACE;
370 static ULONG WINAPI AC_AddRef(IAudioClient *iface)
372 ACImpl *This = (ACImpl*)iface;
374 ref = InterlockedIncrement(&This->ref);
375 TRACE("Refcount now %i\n", ref);
379 static ULONG WINAPI AC_Release(IAudioClient *iface)
381 ACImpl *This = (ACImpl*)iface;
383 ref = InterlockedDecrement(&This->ref);
384 TRACE("Refcount now %i\n", ref);
386 AudioClient_Destroy(This);
390 static HRESULT WINAPI AC_Initialize(IAudioClient *iface, AUDCLNT_SHAREMODE mode, DWORD flags, REFERENCE_TIME duration, REFERENCE_TIME period, const WAVEFORMATEX *pwfx, const GUID *sessionguid)
392 ACImpl *This = (ACImpl*)iface;
395 REFERENCE_TIME time, bufsize;
397 TRACE("(%p)->(%x,%x,%u,%u,%p,%s)\n", This, mode, flags, (int)duration, (int)period, pwfx, debugstr_guid(sessionguid));
399 return AUDCLNT_E_ALREADY_INITIALIZED;
400 if (mode != AUDCLNT_SHAREMODE_SHARED
401 && mode != AUDCLNT_SHAREMODE_EXCLUSIVE) {
402 WARN("Unknown mode %x\n", mode);
403 return AUDCLNT_E_NOT_INITIALIZED;
406 if (flags & ~(AUDCLNT_STREAMFLAGS_CROSSPROCESS
407 |AUDCLNT_STREAMFLAGS_LOOPBACK
408 |AUDCLNT_STREAMFLAGS_EVENTCALLBACK
409 |AUDCLNT_STREAMFLAGS_NOPERSIST
410 |AUDCLNT_STREAMFLAGS_RATEADJUST
411 |AUDCLNT_SESSIONFLAGS_EXPIREWHENUNOWNED
412 |AUDCLNT_SESSIONFLAGS_DISPLAY_HIDE
413 |AUDCLNT_SESSIONFLAGS_DISPLAY_HIDEWHENEXPIRED)) {
414 WARN("Unknown flags 0x%08x\n", flags);
418 WARN("Flags 0x%08x ignored\n", flags);
422 WARN("Session guid %s ignored\n", debugstr_guid(sessionguid));
424 hr = IAudioClient_IsFormatSupported(iface, mode, pwfx, &pwfx2);
425 CoTaskMemFree(pwfx2);
426 if (FAILED(hr) || pwfx2)
427 return AUDCLNT_E_UNSUPPORTED_FORMAT;
428 EnterCriticalSection(This->crst);
429 HeapFree(GetProcessHeap(), 0, This->pwfx);
430 This->pwfx = HeapAlloc(GetProcessHeap(), 0, sizeof(*pwfx) + pwfx->cbSize);
435 memcpy(This->pwfx, pwfx, sizeof(*pwfx) + pwfx->cbSize);
437 hr = IAudioClient_GetDevicePeriod(iface, &time, NULL);
441 This->psize = (DWORD64)This->pwfx->nSamplesPerSec * time / (DWORD64)10000000;
442 if (duration > 20000000)
445 bufsize = duration / time * This->psize;
447 bufsize += This->psize;
448 This->bufsize = bufsize;
449 This->psize *= This->pwfx->nBlockAlign;
450 bufsize *= pwfx->nBlockAlign;
452 This->format = get_format(This->pwfx);
453 if (This->parent->flow == eRender) {
455 ALuint buf = 0, towrite;
457 hr = AC_OpenRenderAL(This);
461 /* Test the returned format */
462 towrite = sizeof(silence);
463 towrite -= towrite % This->pwfx->nBlockAlign;
464 if (This->pwfx->wBitsPerSample != 8)
465 memset(silence, 0, sizeof(silence));
467 memset(silence, 128, sizeof(silence));
468 setALContext(This->parent->ctx);
470 palGenBuffers(1, &buf);
471 palBufferData(buf, This->format, silence, towrite, This->pwfx->nSamplesPerSec);
472 palDeleteBuffers(1, &buf);
474 hr = AUDCLNT_E_UNSUPPORTED_FORMAT;
475 else if (!This->source) {
476 palGenSources(1, &This->source);
477 palSourcei(This->source, AL_LOOPING, AL_FALSE);
483 hr = AC_OpenCaptureAL(This);
488 This->buffer = HeapAlloc(GetProcessHeap(), 0, bufsize);
495 This->running = FALSE;
498 LeaveCriticalSection(This->crst);
502 static HRESULT WINAPI AC_GetBufferSize(IAudioClient *iface, UINT32 *frames)
504 ACImpl *This = (ACImpl*)iface;
505 TRACE("(%p)->(%p)\n", This, frames);
507 return AUDCLNT_E_NOT_INITIALIZED;
510 *frames = This->bufsize;
514 static HRESULT WINAPI AC_GetStreamLatency(IAudioClient *iface, REFERENCE_TIME *latency)
516 ACImpl *This = (ACImpl*)iface;
517 TRACE("(%p)->(%p)\n", This, latency);
520 return AUDCLNT_E_NOT_INITIALIZED;
530 static HRESULT WINAPI AC_GetCurrentPadding(IAudioClient *iface, UINT32 *numpad)
532 ACImpl *This = (ACImpl*)iface;
535 TRACE("(%p)->(%p)\n", This, numpad);
537 return AUDCLNT_E_NOT_INITIALIZED;
540 EnterCriticalSection(This->crst);
541 if (This->parent->flow == eRender) {
543 ALint state, padpart;
544 setALContext(This->parent->ctx);
546 palGetSourcei(This->source, AL_BYTE_OFFSET, &padpart);
547 palGetSourcei(This->source, AL_SOURCE_STATE, &state);
548 padpart /= This->pwfx->nBlockAlign;
549 if (state == AL_STOPPED && This->running)
551 if (This->running && This->padpartial != padpart) {
552 This->padpartial = padpart;
553 This->laststamp = gettime();
554 #if 0 /* Manipulative lie */
555 } else if (This->running) {
556 ALint size = This->pad - padpart;
557 if (size > This->psize)
559 played = (gettime() - This->laststamp)*8;
560 played = played * This->pwfx->nSamplesPerSec / 10000000;
565 *numpad = This->pad - This->padpartial - played;
566 if (This->handle && *numpad + This->psize <= This->bufsize)
567 SetEvent(This->handle);
571 DWORD block = This->pwfx->nBlockAlign;
572 DWORD psize = This->psize / block;
573 palcGetIntegerv(This->capdev, ALC_CAPTURE_SAMPLES, 1, &avail);
575 DWORD ofs = This->ofs + This->pad;
577 ofs %= This->bufsize;
578 buf1 = This->buffer + (ofs * block);
579 This->laststamp = gettime();
581 SetEvent(This->handle);
583 if (ofs + avail <= This->bufsize)
584 palcCaptureSamples(This->capdev, buf1, avail);
586 DWORD part1 = This->bufsize - This->ofs;
587 palcCaptureSamples(This->capdev, buf1, part1);
588 palcCaptureSamples(This->capdev, This->buffer, avail - part1);
591 This->frameswritten += avail;
592 /* Increase ofs if the app forgets to read */
593 if (This->pad > This->bufsize) {
595 WARN("Overflowed! %u bytes\n", This->pad - This->bufsize);
596 This->ofs += This->pad - This->bufsize;
597 rest = This->ofs % psize;
599 This->ofs += psize - rest;
600 This->ofs %= This->bufsize;
601 This->pad = This->bufsize - rest;
604 if (This->pad >= psize)
609 LeaveCriticalSection(This->crst);
611 TRACE("%u queued\n", *numpad);
615 static HRESULT WINAPI AC_IsFormatSupported(IAudioClient *iface, AUDCLNT_SHAREMODE mode, const WAVEFORMATEX *pwfx, WAVEFORMATEX **outpwfx)
617 ACImpl *This = (ACImpl*)iface;
618 TRACE("(%p)->(%x,%p,%p)\n", This, mode, pwfx, outpwfx);
622 if (mode == AUDCLNT_SHAREMODE_SHARED && !outpwfx)
624 if (mode != AUDCLNT_SHAREMODE_SHARED
625 && mode != AUDCLNT_SHAREMODE_EXCLUSIVE) {
626 WARN("Unknown mode %x\n", mode);
629 if (pwfx->wFormatTag != WAVE_FORMAT_EXTENSIBLE
630 && pwfx->wFormatTag != WAVE_FORMAT_PCM)
631 return AUDCLNT_E_UNSUPPORTED_FORMAT;
632 if (pwfx->nSamplesPerSec < 8000
633 || pwfx->nSamplesPerSec > 192000)
634 return AUDCLNT_E_UNSUPPORTED_FORMAT;
635 if (pwfx->wFormatTag != WAVE_FORMAT_EXTENSIBLE
636 || !IsEqualIID(&((WAVEFORMATEXTENSIBLE*)pwfx)->SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT)) {
637 if (pwfx->wBitsPerSample > 16)
638 return AUDCLNT_E_UNSUPPORTED_FORMAT;
645 static HRESULT WINAPI AC_GetMixFormat(IAudioClient *iface, WAVEFORMATEX **pwfx)
647 ACImpl *This = (ACImpl*)iface;
648 PROPVARIANT pv = { VT_EMPTY };
651 TRACE("(%p)->(%p)\n", This, pwfx);
655 hr = MMDevice_GetPropValue(&This->parent->devguid, This->parent->flow,
656 &PKEY_AudioEngine_DeviceFormat, &pv);
657 *pwfx = (WAVEFORMATEX*)pv.u.blob.pBlobData;
658 if (SUCCEEDED(hr) && pv.vt == VT_EMPTY)
661 TRACE("Returning 0x%08x\n", hr);
665 static HRESULT WINAPI AC_GetDevicePeriod(IAudioClient *iface, REFERENCE_TIME *defperiod, REFERENCE_TIME *minperiod)
667 ACImpl *This = (ACImpl*)iface;
669 TRACE("(%p)->(%p)\n", This, minperiod);
670 if (!defperiod && !minperiod)
680 static HRESULT WINAPI AC_Start(IAudioClient *iface)
682 ACImpl *This = (ACImpl*)iface;
684 REFERENCE_TIME refresh;
686 TRACE("(%p)\n", This);
688 return AUDCLNT_E_NOT_INITIALIZED;
689 if (This->flags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK) {
691 return AUDCLNT_E_EVENTHANDLE_NOT_SET;
692 FIXME("Event handles not fully tested\n");
694 EnterCriticalSection(This->crst);
696 hr = AUDCLNT_E_NOT_STOPPED;
699 if (This->parent->flow == eRender) {
700 setALContext(This->parent->ctx);
701 palSourcePlay(This->source);
706 palcCaptureStart(This->capdev);
708 AC_GetDevicePeriod(iface, &refresh, NULL);
709 if (!This->timer_id && This->handle)
710 CreateTimerQueueTimer(&This->timer_id, NULL, AC_tick, This,
711 refresh / 20000, refresh / 20000,
712 WT_EXECUTEINTIMERTHREAD);
713 /* Set to 0, otherwise risk running the clock backwards
714 * This will cause AudioClock::GetPosition to return the maximum
715 * possible value for the current buffer
718 This->running = TRUE;
721 LeaveCriticalSection(This->crst);
725 static HRESULT WINAPI AC_Stop(IAudioClient *iface)
727 ACImpl *This = (ACImpl*)iface;
729 TRACE("(%p)\n", This);
731 return AUDCLNT_E_NOT_INITIALIZED;
734 EnterCriticalSection(This->crst);
735 if (This->parent->flow == eRender) {
737 setALContext(This->parent->ctx);
738 This->running = FALSE;
739 palSourcePause(This->source);
742 palGetSourcei(This->source, AL_SOURCE_STATE, &state);
743 if (state != AL_PLAYING)
751 palcCaptureStop(This->capdev);
752 timer_id = This->timer_id;
754 LeaveCriticalSection(This->crst);
756 DeleteTimerQueueTimer(NULL, timer_id, INVALID_HANDLE_VALUE);
760 static HRESULT WINAPI AC_Reset(IAudioClient *iface)
762 ACImpl *This = (ACImpl*)iface;
764 TRACE("(%p)\n", This);
766 return AUDCLNT_E_NOT_INITIALIZED;
768 return AUDCLNT_E_NOT_STOPPED;
769 EnterCriticalSection(This->crst);
771 hr = AUDCLNT_E_BUFFER_OPERATION_PENDING;
774 if (This->parent->flow == eRender) {
777 setALContext(This->parent->ctx);
778 palSourceStop(This->source);
779 palGetSourcei(This->source, AL_BUFFERS_PROCESSED, &n);
781 palSourceUnqueueBuffers(This->source, 1, &buf);
782 palDeleteBuffers(1, &buf);
788 palcGetIntegerv(This->capdev, ALC_CAPTURE_SAMPLES, 1, &avail);
790 palcCaptureSamples(This->capdev, This->buffer, avail);
792 This->pad = This->padpartial = 0;
794 This->frameswritten = 0;
796 LeaveCriticalSection(This->crst);
800 static HRESULT WINAPI AC_SetEventHandle(IAudioClient *iface, HANDLE handle)
802 ACImpl *This = (ACImpl*)iface;
803 TRACE("(%p)\n", This);
805 return AUDCLNT_E_NOT_INITIALIZED;
808 if (!(This->flags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK))
809 return AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED;
810 This->handle = handle;
814 static HRESULT WINAPI AC_GetService(IAudioClient *iface, REFIID riid, void **ppv)
816 ACImpl *This = (ACImpl*)iface;
818 TRACE("(%p)->(%s,%p)\n", This, debugstr_guid(riid), ppv);
820 return AUDCLNT_E_NOT_INITIALIZED;
825 if (IsEqualIID(riid, &IID_IAudioRenderClient)) {
826 if (This->parent->flow != eRender)
827 return AUDCLNT_E_WRONG_ENDPOINT_TYPE;
829 hr = AudioRenderClient_Create(This, &This->render);
837 IUnknown_AddRef((IUnknown*)*ppv);
841 FIXME("stub %s\n", debugstr_guid(riid));
842 return E_NOINTERFACE;
845 static const IAudioClientVtbl ACImpl_Vtbl =
853 AC_GetCurrentPadding,
854 AC_IsFormatSupported,
864 static HRESULT AudioRenderClient_Create(ACImpl *parent, ACRender **ppv)
868 This = *ppv = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
870 return E_OUTOFMEMORY;
871 This->lpVtbl = &ACRender_Vtbl;
873 This->parent = parent;
877 static void AudioRenderClient_Destroy(ACRender *This)
879 This->parent->render = NULL;
880 HeapFree(GetProcessHeap(), 0, This);
883 static HRESULT WINAPI ACR_QueryInterface(IAudioRenderClient *iface, REFIID riid, void **ppv)
885 TRACE("(%p)->(%s,%p)\n", iface, debugstr_guid(riid), ppv);
890 if (IsEqualIID(riid, &IID_IUnknown)
891 || IsEqualIID(riid, &IID_IAudioRenderClient))
894 IUnknown_AddRef((IUnknown*)*ppv);
897 WARN("Unknown interface %s\n", debugstr_guid(riid));
898 return E_NOINTERFACE;
901 static ULONG WINAPI ACR_AddRef(IAudioRenderClient *iface)
903 ACRender *This = (ACRender*)iface;
905 ref = InterlockedIncrement(&This->ref);
906 TRACE("Refcount now %i\n", ref);
910 static ULONG WINAPI ACR_Release(IAudioRenderClient *iface)
912 ACRender *This = (ACRender*)iface;
914 ref = InterlockedDecrement(&This->ref);
915 TRACE("Refcount now %i\n", ref);
917 AudioRenderClient_Destroy(This);
921 static HRESULT WINAPI ACR_GetBuffer(IAudioRenderClient *iface, UINT32 frames, BYTE **data)
923 ACRender *This = (ACRender*)iface;
924 DWORD free, framesize;
925 TRACE("(%p)->(%u,%p)\n", This, frames, data);
932 if (This->parent->locked) {
934 return AUDCLNT_E_OUT_OF_ORDER;
936 AC_GetCurrentPadding((IAudioClient*)This->parent, &free);
937 if (This->parent->bufsize-free < frames) {
938 ERR("Too large: %u %u %u\n", This->parent->bufsize, free, frames);
939 return AUDCLNT_E_BUFFER_TOO_LARGE;
941 EnterCriticalSection(This->parent->crst);
942 This->parent->locked = frames;
943 framesize = This->parent->pwfx->nBlockAlign;
945 /* Exact offset doesn't matter, offset could be 0 forever
946 * but increasing it is easier to debug */
947 if (This->parent->ofs + frames > This->parent->bufsize)
948 This->parent->ofs = 0;
949 *data = This->parent->buffer + This->parent->ofs * framesize;
951 LeaveCriticalSection(This->parent->crst);
955 static HRESULT WINAPI ACR_ReleaseBuffer(IAudioRenderClient *iface, UINT32 written, DWORD flags)
957 ACRender *This = (ACRender*)iface;
958 BYTE *buf = This->parent->buffer;
959 DWORD framesize = This->parent->pwfx->nBlockAlign;
960 DWORD ofs = This->parent->ofs;
961 DWORD bufsize = This->parent->bufsize;
962 DWORD locked = This->parent->locked;
963 DWORD freq = This->parent->pwfx->nSamplesPerSec;
964 DWORD bpp = This->parent->pwfx->wBitsPerSample;
967 TRACE("(%p)->(%u,%x)\n", This, written, flags);
969 if (locked < written)
970 return AUDCLNT_E_INVALID_SIZE;
972 if (flags & ~AUDCLNT_BUFFERFLAGS_SILENT)
976 FIXME("Handled right?\n");
977 This->parent->locked = 0;
981 if (!This->parent->locked)
982 return AUDCLNT_E_OUT_OF_ORDER;
984 EnterCriticalSection(This->parent->crst);
985 setALContext(This->parent->parent->ctx);
987 This->parent->ofs += written;
988 This->parent->ofs %= bufsize;
989 This->parent->pad += written;
990 This->parent->frameswritten += written;
993 written *= framesize;
994 bufsize *= framesize;
997 if (flags & AUDCLNT_BUFFERFLAGS_SILENT)
998 memset(buf+ofs, bpp != 8 ? 0 : 128, written);
999 TRACE("buf: %p, ofs: %x, written %u, freq %u\n", buf, ofs, written, freq);
1001 palGenBuffers(1, &albuf);
1002 palBufferData(albuf, This->parent->format, buf+ofs, written, freq);
1003 palSourceQueueBuffers(This->parent->source, 1, &albuf);
1004 TRACE("Queued %u\n", albuf);
1006 if (This->parent->running) {
1007 ALint state = AL_PLAYING, done = 0, padpart = 0;
1009 palGetSourcei(This->parent->source, AL_BUFFERS_PROCESSED, &done);
1010 palGetSourcei(This->parent->source, AL_BYTE_OFFSET, &padpart);
1011 palGetSourcei(This->parent->source, AL_SOURCE_STATE, &state);
1012 padpart /= framesize;
1014 if (state == AL_STOPPED) {
1015 padpart = This->parent->pad;
1016 /* Buffer might have been processed in the small window
1017 * between first and third call */
1018 palGetSourcei(This->parent->source, AL_BUFFERS_PROCESSED, &done);
1020 if (done || This->parent->padpartial != padpart)
1021 This->parent->laststamp = gettime();
1022 This->parent->padpartial = padpart;
1025 ALint size, bits, chan;
1028 palSourceUnqueueBuffers(This->parent->source, 1, &which);
1029 palGetBufferi(which, AL_SIZE, &size);
1030 palGetBufferi(which, AL_BITS, &bits);
1031 palGetBufferi(which, AL_CHANNELS, &chan);
1032 size /= bits * chan / 8;
1033 if (size > This->parent->pad) {
1035 size = This->parent->pad;
1037 This->parent->pad -= size;
1038 This->parent->padpartial -= size;
1039 TRACE("Unqueued %u\n", which);
1040 palDeleteBuffers(1, &which);
1043 if (state != AL_PLAYING) {
1044 ERR("Starting from %x\n", state);
1045 palSourcePlay(This->parent->source);
1049 This->parent->locked = 0;
1053 LeaveCriticalSection(This->parent->crst);
1058 static const IAudioRenderClientVtbl ACRender_Vtbl = {