mmdevapi: Add support for IAudioRenderClient.
[wine] / dlls / mmdevapi / audio.c
1 /*
2  * Copyright 2010 Maarten Lankhorst for Codeweavers
3  *
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.
8  *
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.
13  *
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
17  */
18
19 #define NONAMELESSUNION
20 #define CINTERFACE
21 #define COBJMACROS
22 #include "config.h"
23
24 #include <stdarg.h>
25 #ifdef HAVE_AL_AL_H
26 #include <AL/al.h>
27 #include <AL/alc.h>
28 #elif defined(HAVE_OPENAL_AL_H)
29 #include <OpenAL/al.h>
30 #include <OpenAL/alc.h>
31 #endif
32
33 #include "windef.h"
34 #include "winbase.h"
35 #include "winnls.h"
36 #include "winreg.h"
37 #include "wine/debug.h"
38 #include "wine/unicode.h"
39
40 #include "ole2.h"
41 #include "mmdeviceapi.h"
42 #include "dshow.h"
43 #include "dsound.h"
44 #include "audioclient.h"
45 #include "endpointvolume.h"
46 #include "audiopolicy.h"
47
48 #include "mmdevapi.h"
49
50 WINE_DEFAULT_DEBUG_CHANNEL(mmdevapi);
51
52 #ifdef HAVE_OPENAL
53
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;
59
60 typedef struct ACImpl {
61     const IAudioClientVtbl *lpVtbl;
62     LONG ref;
63
64     MMDevice *parent;
65     BOOL init, running;
66     CRITICAL_SECTION *crst;
67     HANDLE handle;
68     DWORD locked, flags, bufsize, pad, padpartial, ofs, psize;
69     BYTE *buffer;
70     WAVEFORMATEX *pwfx;
71     ALuint source;
72     INT64 frameswritten;
73     REFERENCE_TIME laststamp;
74     HANDLE timer_id;
75     ALCdevice *capdev;
76     ALint format;
77
78     ACRender *render;
79 } ACImpl;
80
81 struct ACRender {
82     const IAudioRenderClientVtbl *lpVtbl;
83     LONG ref;
84     ACImpl *parent;
85 };
86
87 static const IAudioClientVtbl ACImpl_Vtbl;
88 static const IAudioRenderClientVtbl ACRender_Vtbl;
89
90 static HRESULT AudioRenderClient_Create(ACImpl *parent, ACRender **ppv);
91 static void AudioRenderClient_Destroy(ACRender *This);
92
93 static int get_format_PCM(WAVEFORMATEX *format)
94 {
95     if (format->nChannels > 2) {
96         FIXME("nChannels > 2 not documented for WAVE_FORMAT_PCM!\n");
97         return 0;
98     }
99
100     format->cbSize = 0;
101
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);
105         return 0;
106     }
107
108     switch (format->wBitsPerSample) {
109         case 8: {
110             switch (format->nChannels) {
111             case 1: return AL_FORMAT_MONO8;
112             case 2: return AL_FORMAT_STEREO8;
113             }
114         }
115         case 16: {
116             switch (format->nChannels) {
117             case 1: return AL_FORMAT_MONO16;
118             case 2: return AL_FORMAT_STEREO16;
119             }
120         }
121     }
122
123     if (!(format->wBitsPerSample % 8))
124         WARN("Could not get OpenAL format (%d-bit, %d channels)\n",
125              format->wBitsPerSample, format->nChannels);
126     return 0;
127 }
128
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)
137
138 static int get_format_EXT(WAVEFORMATEX *format)
139 {
140     WAVEFORMATEXTENSIBLE *wfe;
141
142     if(format->cbSize < sizeof(WAVEFORMATEXTENSIBLE)-sizeof(WAVEFORMATEX)) {
143         WARN("Invalid cbSize specified for WAVE_FORMAT_EXTENSIBLE (%d)\n", format->cbSize);
144         return 0;
145     }
146
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);
153         return 0;
154     }
155
156     TRACE("Extensible values:\n"
157           "    Samples     = %d\n"
158           "    ChannelMask = 0x%08x\n"
159           "    SubFormat   = %s\n",
160           wfe->Samples.wReserved, wfe->dwChannelMask,
161           debugstr_guid(&wfe->SubFormat));
162
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;
174         }
175         WARN("Not all formats available\n");
176         return 0;
177     }
178
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;
189             default: break;
190             }
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;
200             default: break;
201             }
202         }
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);
206         return 0;
207     }
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);
211             return 0;
212         }
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;
221         default:
222             ERR("Could not get OpenAL float format (%d-bit, mask 0x%08x)\n",
223                 format->wBitsPerSample, wfe->dwChannelMask);
224             return 0;
225         }
226     }
227     else if (!IsEqualGUID(&wfe->SubFormat, &GUID_NULL))
228         ERR("Unhandled extensible format: %s\n", debugstr_guid(&wfe->SubFormat));
229     return 0;
230 }
231
232 static ALint get_format(WAVEFORMATEX *in)
233 {
234     int ret = 0;
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);
239     return ret;
240 }
241
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;
247 }
248
249 HRESULT AudioClient_Create(MMDevice *parent, IAudioClient **ppv)
250 {
251     ACImpl *This = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*This));
252     *ppv = (IAudioClient*)This;
253     if (!*ppv)
254         return E_OUTOFMEMORY;
255     This->crst = &parent->crst;
256     This->lpVtbl = &ACImpl_Vtbl;
257     This->ref = 1;
258     This->parent = parent;
259     return S_OK;
260 }
261
262 static void AudioClient_Destroy(ACImpl *This)
263 {
264     if (This->timer_id)
265         DeleteTimerQueueTimer(NULL, This->timer_id, INVALID_HANDLE_VALUE);
266     if (This->render)
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);
273         getALError();
274         popALContext();
275     }
276     if (This->capdev)
277         palcCaptureCloseDevice(This->capdev);
278     HeapFree(GetProcessHeap(), 0, This->pwfx);
279     HeapFree(GetProcessHeap(), 0, This->buffer);
280     HeapFree(GetProcessHeap(), 0, This);
281 }
282
283 static void CALLBACK AC_tick(void *data, BOOLEAN fired)
284 {
285     ACImpl *This = data;
286     DWORD pad;
287
288     EnterCriticalSection(This->crst);
289     if (This->running)
290         IAudioClient_GetCurrentPadding((IAudioClient*)This, &pad);
291     LeaveCriticalSection(This->crst);
292 }
293
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
298  */
299 static HRESULT AC_OpenRenderAL(ACImpl *This)
300 {
301     char alname[MAX_PATH];
302     MMDevice *cur = This->parent;
303
304     alname[sizeof(alname)-1] = 0;
305     if (cur->device)
306         return cur->ctx ? S_OK : AUDCLNT_E_SERVICE_NOT_RUNNING;
307
308     WideCharToMultiByte(CP_UNIXCP, 0, cur->alname, -1,
309                         alname, sizeof(alname)/sizeof(*alname)-1, NULL, NULL);
310     cur->device = palcOpenDevice(alname);
311     if (!cur->device) {
312         ALCenum err = palcGetError(NULL);
313         FIXME("Could not open device %s: 0x%04x\n", alname, err);
314         return AUDCLNT_E_DEVICE_IN_USE;
315     }
316     cur->ctx = palcCreateContext(cur->device, NULL);
317     if (!cur->ctx) {
318         ALCenum err = palcGetError(cur->device);
319         FIXME("Could not create context: 0x%04x\n", err);
320         return AUDCLNT_E_SERVICE_NOT_RUNNING;
321     }
322     if (!cur->device)
323         return AUDCLNT_E_DEVICE_IN_USE;
324     return S_OK;
325 }
326
327 static HRESULT AC_OpenCaptureAL(ACImpl *This)
328 {
329     char alname[MAX_PATH];
330     ALint freq, size;
331
332     freq = This->pwfx->nSamplesPerSec;
333     size = This->bufsize;
334
335     alname[sizeof(alname)-1] = 0;
336     if (This->capdev) {
337         FIXME("Attempting to open device while already open\n");
338         return S_OK;
339     }
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);
343     if (!This->capdev) {
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;
348     }
349     return S_OK;
350 }
351
352 static HRESULT WINAPI AC_QueryInterface(IAudioClient *iface, REFIID riid, void **ppv)
353 {
354     TRACE("(%p)->(%s,%p)\n", iface, debugstr_guid(riid), ppv);
355
356     if (!ppv)
357         return E_POINTER;
358     *ppv = NULL;
359     if (IsEqualIID(riid, &IID_IUnknown)
360         || IsEqualIID(riid, &IID_IAudioClient))
361         *ppv = iface;
362     if (*ppv) {
363         IUnknown_AddRef((IUnknown*)*ppv);
364         return S_OK;
365     }
366     WARN("Unknown interface %s\n", debugstr_guid(riid));
367     return E_NOINTERFACE;
368 }
369
370 static ULONG WINAPI AC_AddRef(IAudioClient *iface)
371 {
372     ACImpl *This = (ACImpl*)iface;
373     ULONG ref;
374     ref = InterlockedIncrement(&This->ref);
375     TRACE("Refcount now %i\n", ref);
376     return ref;
377 }
378
379 static ULONG WINAPI AC_Release(IAudioClient *iface)
380 {
381     ACImpl *This = (ACImpl*)iface;
382     ULONG ref;
383     ref = InterlockedDecrement(&This->ref);
384     TRACE("Refcount now %i\n", ref);
385     if (!ref)
386         AudioClient_Destroy(This);
387     return ref;
388 }
389
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)
391 {
392     ACImpl *This = (ACImpl*)iface;
393     HRESULT hr = S_OK;
394     WAVEFORMATEX *pwfx2;
395     REFERENCE_TIME time, bufsize;
396
397     TRACE("(%p)->(%x,%x,%u,%u,%p,%s)\n", This, mode, flags, (int)duration, (int)period, pwfx, debugstr_guid(sessionguid));
398     if (This->init)
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;
404     }
405
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);
415         return E_INVALIDARG;
416     }
417     if (flags)
418         WARN("Flags 0x%08x ignored\n", flags);
419     if (!pwfx)
420         return E_POINTER;
421     if (sessionguid)
422         WARN("Session guid %s ignored\n", debugstr_guid(sessionguid));
423
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);
431     if (!This->pwfx) {
432         hr = E_OUTOFMEMORY;
433         goto out;
434     }
435     memcpy(This->pwfx, pwfx, sizeof(*pwfx) + pwfx->cbSize);
436
437     hr = IAudioClient_GetDevicePeriod(iface, &time, NULL);
438     if (FAILED(hr))
439         goto out;
440
441     This->psize = (DWORD64)This->pwfx->nSamplesPerSec * time / (DWORD64)10000000;
442     if (duration > 20000000)
443         duration = 20000000;
444
445     bufsize = duration / time * This->psize;
446     if (duration % time)
447         bufsize += This->psize;
448     This->bufsize = bufsize;
449     This->psize *= This->pwfx->nBlockAlign;
450     bufsize *= pwfx->nBlockAlign;
451
452     This->format = get_format(This->pwfx);
453     if (This->parent->flow == eRender) {
454         char silence[32];
455         ALuint buf = 0, towrite;
456
457         hr = AC_OpenRenderAL(This);
458         if (FAILED(hr))
459             goto out;
460
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));
466         else
467             memset(silence, 128, sizeof(silence));
468         setALContext(This->parent->ctx);
469         getALError();
470         palGenBuffers(1, &buf);
471         palBufferData(buf, This->format, silence, towrite, This->pwfx->nSamplesPerSec);
472         palDeleteBuffers(1, &buf);
473         if (palGetError())
474             hr = AUDCLNT_E_UNSUPPORTED_FORMAT;
475         else if (!This->source) {
476             palGenSources(1, &This->source);
477             palSourcei(This->source, AL_LOOPING, AL_FALSE);
478             getALError();
479         }
480         popALContext();
481     }
482     else
483         hr = AC_OpenCaptureAL(This);
484
485     if (FAILED(hr))
486         goto out;
487
488     This->buffer = HeapAlloc(GetProcessHeap(), 0, bufsize);
489     if (!This->buffer) {
490         hr = E_OUTOFMEMORY;
491         goto out;
492     }
493     This->flags = flags;
494     This->handle = NULL;
495     This->running = FALSE;
496     This->init = TRUE;
497 out:
498     LeaveCriticalSection(This->crst);
499     return hr;
500 }
501
502 static HRESULT WINAPI AC_GetBufferSize(IAudioClient *iface, UINT32 *frames)
503 {
504     ACImpl *This = (ACImpl*)iface;
505     TRACE("(%p)->(%p)\n", This, frames);
506     if (!This->init)
507         return AUDCLNT_E_NOT_INITIALIZED;
508     if (!frames)
509         return E_POINTER;
510     *frames = This->bufsize;
511     return S_OK;
512 }
513
514 static HRESULT WINAPI AC_GetStreamLatency(IAudioClient *iface, REFERENCE_TIME *latency)
515 {
516     ACImpl *This = (ACImpl*)iface;
517     TRACE("(%p)->(%p)\n", This, latency);
518
519     if (!This->init)
520         return AUDCLNT_E_NOT_INITIALIZED;
521
522     if (!latency)
523         return E_POINTER;
524
525     *latency = 50000;
526
527     return S_OK;
528 }
529
530 static HRESULT WINAPI AC_GetCurrentPadding(IAudioClient *iface, UINT32 *numpad)
531 {
532     ACImpl *This = (ACImpl*)iface;
533     ALint avail = 0;
534
535     TRACE("(%p)->(%p)\n", This, numpad);
536     if (!This->init)
537         return AUDCLNT_E_NOT_INITIALIZED;
538     if (!numpad)
539         return E_POINTER;
540     EnterCriticalSection(This->crst);
541     if (This->parent->flow == eRender) {
542         UINT64 played = 0;
543         ALint state, padpart;
544         setALContext(This->parent->ctx);
545
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)
550             padpart = This->pad;
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)
558                 size = This->psize;
559             played = (gettime() - This->laststamp)*8;
560             played = played * This->pwfx->nSamplesPerSec / 10000000;
561             if (played > size)
562                 played = size;
563 #endif
564         }
565         *numpad = This->pad - This->padpartial - played;
566         if (This->handle && *numpad + This->psize <= This->bufsize)
567             SetEvent(This->handle);
568         getALError();
569         popALContext();
570     } else {
571         DWORD block = This->pwfx->nBlockAlign;
572         DWORD psize = This->psize / block;
573         palcGetIntegerv(This->capdev, ALC_CAPTURE_SAMPLES, 1, &avail);
574         if (avail) {
575             DWORD ofs = This->ofs + This->pad;
576             BYTE *buf1;
577             ofs %= This->bufsize;
578             buf1 = This->buffer + (ofs * block);
579             This->laststamp = gettime();
580             if (This->handle)
581                 SetEvent(This->handle);
582
583             if (ofs + avail <= This->bufsize)
584                 palcCaptureSamples(This->capdev, buf1, avail);
585             else {
586                 DWORD part1 = This->bufsize - This->ofs;
587                 palcCaptureSamples(This->capdev, buf1, part1);
588                 palcCaptureSamples(This->capdev, This->buffer, avail - part1);
589             }
590             This->pad += avail;
591             This->frameswritten += avail;
592             /* Increase ofs if the app forgets to read */
593             if (This->pad > This->bufsize) {
594                 DWORD rest;
595                 WARN("Overflowed! %u bytes\n", This->pad - This->bufsize);
596                 This->ofs += This->pad - This->bufsize;
597                 rest = This->ofs % psize;
598                 if (rest)
599                     This->ofs += psize - rest;
600                 This->ofs %= This->bufsize;
601                 This->pad = This->bufsize - rest;
602             }
603         }
604         if (This->pad >= psize)
605             *numpad = psize;
606         else
607             *numpad = 0;
608     }
609     LeaveCriticalSection(This->crst);
610
611     TRACE("%u queued\n", *numpad);
612     return S_OK;
613 }
614
615 static HRESULT WINAPI AC_IsFormatSupported(IAudioClient *iface, AUDCLNT_SHAREMODE mode, const WAVEFORMATEX *pwfx, WAVEFORMATEX **outpwfx)
616 {
617     ACImpl *This = (ACImpl*)iface;
618     TRACE("(%p)->(%x,%p,%p)\n", This, mode, pwfx, outpwfx);
619     if (!pwfx)
620         return E_POINTER;
621
622     if (mode == AUDCLNT_SHAREMODE_SHARED && !outpwfx)
623         return E_POINTER;
624     if (mode != AUDCLNT_SHAREMODE_SHARED
625         && mode != AUDCLNT_SHAREMODE_EXCLUSIVE) {
626         WARN("Unknown mode %x\n", mode);
627         return E_INVALIDARG;
628     }
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;
639     }
640     if (outpwfx)
641         *outpwfx = NULL;
642     return S_OK;
643 }
644
645 static HRESULT WINAPI AC_GetMixFormat(IAudioClient *iface, WAVEFORMATEX **pwfx)
646 {
647     ACImpl *This = (ACImpl*)iface;
648     PROPVARIANT pv = { VT_EMPTY };
649     HRESULT hr = S_OK;
650
651     TRACE("(%p)->(%p)\n", This, pwfx);
652     if (!pwfx)
653         return E_POINTER;
654
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)
659         return E_FAIL;
660
661     TRACE("Returning 0x%08x\n", hr);
662     return hr;
663 }
664
665 static HRESULT WINAPI AC_GetDevicePeriod(IAudioClient *iface, REFERENCE_TIME *defperiod, REFERENCE_TIME *minperiod)
666 {
667     ACImpl *This = (ACImpl*)iface;
668
669     TRACE("(%p)->(%p)\n", This, minperiod);
670     if (!defperiod && !minperiod)
671         return E_POINTER;
672
673     if (minperiod)
674         *minperiod = 30000;
675     if (defperiod)
676         *defperiod = 200000;
677     return S_OK;
678 }
679
680 static HRESULT WINAPI AC_Start(IAudioClient *iface)
681 {
682     ACImpl *This = (ACImpl*)iface;
683     HRESULT hr;
684     REFERENCE_TIME refresh;
685
686     TRACE("(%p)\n", This);
687     if (!This->init)
688         return AUDCLNT_E_NOT_INITIALIZED;
689     if (This->flags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK) {
690         if (!This->handle)
691             return AUDCLNT_E_EVENTHANDLE_NOT_SET;
692         FIXME("Event handles not fully tested\n");
693     }
694     EnterCriticalSection(This->crst);
695     if (This->running) {
696         hr = AUDCLNT_E_NOT_STOPPED;
697         goto out;
698     }
699     if (This->parent->flow == eRender) {
700         setALContext(This->parent->ctx);
701         palSourcePlay(This->source);
702         getALError();
703         popALContext();
704     }
705     else
706         palcCaptureStart(This->capdev);
707
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
716      */
717     This->laststamp = 0;
718     This->running = TRUE;
719     hr = S_OK;
720 out:
721     LeaveCriticalSection(This->crst);
722     return hr;
723 }
724
725 static HRESULT WINAPI AC_Stop(IAudioClient *iface)
726 {
727     ACImpl *This = (ACImpl*)iface;
728     HANDLE timer_id;
729     TRACE("(%p)\n", This);
730     if (!This->init)
731         return AUDCLNT_E_NOT_INITIALIZED;
732     if (!This->running)
733         return S_FALSE;
734     EnterCriticalSection(This->crst);
735     if (This->parent->flow == eRender) {
736         ALint state;
737         setALContext(This->parent->ctx);
738         This->running = FALSE;
739         palSourcePause(This->source);
740         while (1) {
741             state = AL_STOPPED;
742             palGetSourcei(This->source, AL_SOURCE_STATE, &state);
743             if (state != AL_PLAYING)
744                 break;
745             Sleep(1);
746         }
747         getALError();
748         popALContext();
749     }
750     else
751         palcCaptureStop(This->capdev);
752     timer_id = This->timer_id;
753     This->timer_id = 0;
754     LeaveCriticalSection(This->crst);
755     if (timer_id)
756         DeleteTimerQueueTimer(NULL, timer_id, INVALID_HANDLE_VALUE);
757     return S_OK;
758 }
759
760 static HRESULT WINAPI AC_Reset(IAudioClient *iface)
761 {
762     ACImpl *This = (ACImpl*)iface;
763     HRESULT hr = S_OK;
764     TRACE("(%p)\n", This);
765     if (!This->init)
766         return AUDCLNT_E_NOT_INITIALIZED;
767     if (This->running)
768         return AUDCLNT_E_NOT_STOPPED;
769     EnterCriticalSection(This->crst);
770     if (This->locked) {
771         hr = AUDCLNT_E_BUFFER_OPERATION_PENDING;
772         goto out;
773     }
774     if (This->parent->flow == eRender) {
775         ALuint buf;
776         ALint n = 0;
777         setALContext(This->parent->ctx);
778         palSourceStop(This->source);
779         palGetSourcei(This->source, AL_BUFFERS_PROCESSED, &n);
780         while (n--) {
781             palSourceUnqueueBuffers(This->source, 1, &buf);
782             palDeleteBuffers(1, &buf);
783         }
784         getALError();
785         popALContext();
786     } else {
787         ALint avail = 0;
788         palcGetIntegerv(This->capdev, ALC_CAPTURE_SAMPLES, 1, &avail);
789         if (avail)
790             palcCaptureSamples(This->capdev, This->buffer, avail);
791     }
792     This->pad = This->padpartial = 0;
793     This->ofs = 0;
794     This->frameswritten = 0;
795 out:
796     LeaveCriticalSection(This->crst);
797     return hr;
798 }
799
800 static HRESULT WINAPI AC_SetEventHandle(IAudioClient *iface, HANDLE handle)
801 {
802     ACImpl *This = (ACImpl*)iface;
803     TRACE("(%p)\n", This);
804     if (!This->init)
805         return AUDCLNT_E_NOT_INITIALIZED;
806     if (!handle)
807         return E_INVALIDARG;
808     if (!(This->flags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK))
809         return AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED;
810     This->handle = handle;
811     return S_OK;
812 }
813
814 static HRESULT WINAPI AC_GetService(IAudioClient *iface, REFIID riid, void **ppv)
815 {
816     ACImpl *This = (ACImpl*)iface;
817     HRESULT hr = S_OK;
818     TRACE("(%p)->(%s,%p)\n", This, debugstr_guid(riid), ppv);
819     if (!This->init)
820         return AUDCLNT_E_NOT_INITIALIZED;
821     if (!ppv)
822         return E_POINTER;
823     *ppv = NULL;
824
825     if (IsEqualIID(riid, &IID_IAudioRenderClient)) {
826         if (This->parent->flow != eRender)
827             return AUDCLNT_E_WRONG_ENDPOINT_TYPE;
828         if (!This->render)
829             hr = AudioRenderClient_Create(This, &This->render);
830         *ppv = This->render;
831     }
832
833     if (FAILED(hr))
834         return hr;
835
836     if (*ppv) {
837         IUnknown_AddRef((IUnknown*)*ppv);
838         return S_OK;
839     }
840
841     FIXME("stub %s\n", debugstr_guid(riid));
842     return E_NOINTERFACE;
843 }
844
845 static const IAudioClientVtbl ACImpl_Vtbl =
846 {
847     AC_QueryInterface,
848     AC_AddRef,
849     AC_Release,
850     AC_Initialize,
851     AC_GetBufferSize,
852     AC_GetStreamLatency,
853     AC_GetCurrentPadding,
854     AC_IsFormatSupported,
855     AC_GetMixFormat,
856     AC_GetDevicePeriod,
857     AC_Start,
858     AC_Stop,
859     AC_Reset,
860     AC_SetEventHandle,
861     AC_GetService
862 };
863
864 static HRESULT AudioRenderClient_Create(ACImpl *parent, ACRender **ppv)
865 {
866     ACRender *This;
867
868     This = *ppv = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
869     if (!This)
870         return E_OUTOFMEMORY;
871     This->lpVtbl = &ACRender_Vtbl;
872     This->ref = 0;
873     This->parent = parent;
874     return S_OK;
875 }
876
877 static void AudioRenderClient_Destroy(ACRender *This)
878 {
879     This->parent->render = NULL;
880     HeapFree(GetProcessHeap(), 0, This);
881 }
882
883 static HRESULT WINAPI ACR_QueryInterface(IAudioRenderClient *iface, REFIID riid, void **ppv)
884 {
885     TRACE("(%p)->(%s,%p)\n", iface, debugstr_guid(riid), ppv);
886
887     if (!ppv)
888         return E_POINTER;
889     *ppv = NULL;
890     if (IsEqualIID(riid, &IID_IUnknown)
891         || IsEqualIID(riid, &IID_IAudioRenderClient))
892         *ppv = iface;
893     if (*ppv) {
894         IUnknown_AddRef((IUnknown*)*ppv);
895         return S_OK;
896     }
897     WARN("Unknown interface %s\n", debugstr_guid(riid));
898     return E_NOINTERFACE;
899 }
900
901 static ULONG WINAPI ACR_AddRef(IAudioRenderClient *iface)
902 {
903     ACRender *This = (ACRender*)iface;
904     ULONG ref;
905     ref = InterlockedIncrement(&This->ref);
906     TRACE("Refcount now %i\n", ref);
907     return ref;
908 }
909
910 static ULONG WINAPI ACR_Release(IAudioRenderClient *iface)
911 {
912     ACRender *This = (ACRender*)iface;
913     ULONG ref;
914     ref = InterlockedDecrement(&This->ref);
915     TRACE("Refcount now %i\n", ref);
916     if (!ref)
917         AudioRenderClient_Destroy(This);
918     return ref;
919 }
920
921 static HRESULT WINAPI ACR_GetBuffer(IAudioRenderClient *iface, UINT32 frames, BYTE **data)
922 {
923     ACRender *This = (ACRender*)iface;
924     DWORD free, framesize;
925     TRACE("(%p)->(%u,%p)\n", This, frames, data);
926
927     if (!data)
928         return E_POINTER;
929     if (!frames)
930         return S_OK;
931     *data = NULL;
932     if (This->parent->locked) {
933         ERR("Locked\n");
934         return AUDCLNT_E_OUT_OF_ORDER;
935     }
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;
940     }
941     EnterCriticalSection(This->parent->crst);
942     This->parent->locked = frames;
943     framesize = This->parent->pwfx->nBlockAlign;
944
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;
950
951     LeaveCriticalSection(This->parent->crst);
952     return S_OK;
953 }
954
955 static HRESULT WINAPI ACR_ReleaseBuffer(IAudioRenderClient *iface, UINT32 written, DWORD flags)
956 {
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;
965     ALuint albuf;
966
967     TRACE("(%p)->(%u,%x)\n", This, written, flags);
968
969     if (locked < written)
970         return AUDCLNT_E_INVALID_SIZE;
971
972     if (flags & ~AUDCLNT_BUFFERFLAGS_SILENT)
973         return E_INVALIDARG;
974
975     if (!written) {
976         FIXME("Handled right?\n");
977         This->parent->locked = 0;
978         return S_OK;
979     }
980
981     if (!This->parent->locked)
982         return AUDCLNT_E_OUT_OF_ORDER;
983
984     EnterCriticalSection(This->parent->crst);
985     setALContext(This->parent->parent->ctx);
986
987     This->parent->ofs += written;
988     This->parent->ofs %= bufsize;
989     This->parent->pad += written;
990     This->parent->frameswritten += written;
991
992     ofs *= framesize;
993     written *= framesize;
994     bufsize *= framesize;
995     locked *= framesize;
996
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);
1000
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);
1005
1006     if (This->parent->running) {
1007         ALint state = AL_PLAYING, done = 0, padpart = 0;
1008
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;
1013
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);
1019         }
1020         if (done || This->parent->padpartial != padpart)
1021             This->parent->laststamp = gettime();
1022         This->parent->padpartial = padpart;
1023
1024         while (done--) {
1025             ALint size, bits, chan;
1026             ALuint which;
1027
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) {
1034                 ERR("Overflow!\n");
1035                 size = This->parent->pad;
1036             }
1037             This->parent->pad -= size;
1038             This->parent->padpartial -= size;
1039             TRACE("Unqueued %u\n", which);
1040             palDeleteBuffers(1, &which);
1041         }
1042
1043         if (state != AL_PLAYING) {
1044             ERR("Starting from %x\n", state);
1045             palSourcePlay(This->parent->source);
1046         }
1047         getALError();
1048     }
1049     This->parent->locked = 0;
1050
1051     getALError();
1052     popALContext();
1053     LeaveCriticalSection(This->parent->crst);
1054
1055     return S_OK;
1056 }
1057
1058 static const IAudioRenderClientVtbl ACRender_Vtbl = {
1059     ACR_QueryInterface,
1060     ACR_AddRef,
1061     ACR_Release,
1062     ACR_GetBuffer,
1063     ACR_ReleaseBuffer
1064 };
1065
1066 #endif