kernel32: Update the Dutch (Suriname) NLS file.
[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     ACCapture *capture;
80     ACSession *session;
81     ASVolume *svolume;
82     AClock *clock;
83 } ACImpl;
84
85 struct ACRender {
86     const IAudioRenderClientVtbl *lpVtbl;
87     LONG ref;
88     ACImpl *parent;
89 };
90
91 struct ACCapture {
92     const IAudioCaptureClientVtbl *lpVtbl;
93     LONG ref;
94     ACImpl *parent;
95 };
96
97 struct ACSession {
98     const IAudioSessionControl2Vtbl *lpVtbl;
99     LONG ref;
100     ACImpl *parent;
101 };
102
103 struct ASVolume {
104     const ISimpleAudioVolumeVtbl *lpVtbl;
105     LONG ref;
106     ACImpl *parent;
107 };
108
109 struct AClock {
110     const IAudioClockVtbl *lpVtbl;
111     const IAudioClock2Vtbl *lp2Vtbl;
112     LONG ref;
113     ACImpl *parent;
114 };
115
116 static const IAudioClientVtbl ACImpl_Vtbl;
117 static const IAudioRenderClientVtbl ACRender_Vtbl;
118 static const IAudioCaptureClientVtbl ACCapture_Vtbl;
119 static const IAudioSessionControl2Vtbl ACSession_Vtbl;
120 static const ISimpleAudioVolumeVtbl ASVolume_Vtbl;
121 static const IAudioClockVtbl AClock_Vtbl;
122 static const IAudioClock2Vtbl AClock2_Vtbl;
123
124 static HRESULT AudioRenderClient_Create(ACImpl *parent, ACRender **ppv);
125 static void AudioRenderClient_Destroy(ACRender *This);
126 static HRESULT AudioCaptureClient_Create(ACImpl *parent, ACCapture **ppv);
127 static void AudioCaptureClient_Destroy(ACCapture *This);
128 static HRESULT AudioSessionControl_Create(ACImpl *parent, ACSession **ppv);
129 static void AudioSessionControl_Destroy(ACSession *This);
130 static HRESULT AudioSimpleVolume_Create(ACImpl *parent, ASVolume **ppv);
131 static void AudioSimpleVolume_Destroy(ASVolume *This);
132 static HRESULT AudioClock_Create(ACImpl *parent, AClock **ppv);
133 static void AudioClock_Destroy(AClock *This);
134
135 static int get_format_PCM(WAVEFORMATEX *format)
136 {
137     if (format->nChannels > 2) {
138         FIXME("nChannels > 2 not documented for WAVE_FORMAT_PCM!\n");
139         return 0;
140     }
141
142     format->cbSize = 0;
143
144     if (format->nBlockAlign != format->wBitsPerSample/8*format->nChannels) {
145         WARN("Invalid nBlockAlign %u, from %u %u\n",
146              format->nBlockAlign, format->wBitsPerSample, format->nChannels);
147         return 0;
148     }
149
150     switch (format->wBitsPerSample) {
151         case 8: {
152             switch (format->nChannels) {
153             case 1: return AL_FORMAT_MONO8;
154             case 2: return AL_FORMAT_STEREO8;
155             }
156         }
157         case 16: {
158             switch (format->nChannels) {
159             case 1: return AL_FORMAT_MONO16;
160             case 2: return AL_FORMAT_STEREO16;
161             }
162         }
163     }
164
165     if (!(format->wBitsPerSample % 8))
166         WARN("Could not get OpenAL format (%d-bit, %d channels)\n",
167              format->wBitsPerSample, format->nChannels);
168     return 0;
169 }
170
171 /* Speaker configs */
172 #define MONO SPEAKER_FRONT_CENTER
173 #define STEREO (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT)
174 #define REAR (SPEAKER_BACK_LEFT|SPEAKER_BACK_RIGHT)
175 #define QUAD (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_BACK_LEFT|SPEAKER_BACK_RIGHT)
176 #define X5DOT1 (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_BACK_LEFT|SPEAKER_BACK_RIGHT)
177 #define X6DOT1 (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_BACK_CENTER|SPEAKER_SIDE_LEFT|SPEAKER_SIDE_RIGHT)
178 #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)
179
180 static int get_format_EXT(WAVEFORMATEX *format)
181 {
182     WAVEFORMATEXTENSIBLE *wfe;
183
184     if(format->cbSize < sizeof(WAVEFORMATEXTENSIBLE)-sizeof(WAVEFORMATEX)) {
185         WARN("Invalid cbSize specified for WAVE_FORMAT_EXTENSIBLE (%d)\n", format->cbSize);
186         return 0;
187     }
188
189     wfe = (WAVEFORMATEXTENSIBLE*)format;
190     wfe->Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE)-sizeof(WAVEFORMATEX);
191     if (wfe->Samples.wValidBitsPerSample &&
192         wfe->Samples.wValidBitsPerSample != format->wBitsPerSample) {
193         FIXME("wValidBitsPerSample(%u) != wBitsPerSample(%u) unsupported\n",
194               wfe->Samples.wValidBitsPerSample, format->wBitsPerSample);
195         return 0;
196     }
197
198     TRACE("Extensible values:\n"
199           "    Samples     = %d\n"
200           "    ChannelMask = 0x%08x\n"
201           "    SubFormat   = %s\n",
202           wfe->Samples.wReserved, wfe->dwChannelMask,
203           debugstr_guid(&wfe->SubFormat));
204
205     if (wfe->dwChannelMask != MONO
206         && wfe->dwChannelMask != STEREO
207         && !palIsExtensionPresent("AL_EXT_MCFORMATS")) {
208         /* QUAD PCM might still work, special case */
209         if (palIsExtensionPresent("AL_LOKI_quadriphonic")
210             && IsEqualGUID(&wfe->SubFormat, &KSDATAFORMAT_SUBTYPE_PCM)
211             && wfe->dwChannelMask == QUAD) {
212             if (format->wBitsPerSample == 16)
213                 return AL_FORMAT_QUAD16_LOKI;
214             else if (format->wBitsPerSample == 8)
215                 return AL_FORMAT_QUAD8_LOKI;
216         }
217         WARN("Not all formats available\n");
218         return 0;
219     }
220
221     if(IsEqualGUID(&wfe->SubFormat, &KSDATAFORMAT_SUBTYPE_PCM)) {
222         if (format->wBitsPerSample == 8) {
223             switch (wfe->dwChannelMask) {
224             case   MONO: return AL_FORMAT_MONO8;
225             case STEREO: return AL_FORMAT_STEREO8;
226             case   REAR: return AL_FORMAT_REAR8;
227             case   QUAD: return AL_FORMAT_QUAD8;
228             case X5DOT1: return AL_FORMAT_51CHN8;
229             case X6DOT1: return AL_FORMAT_61CHN8;
230             case X7DOT1: return AL_FORMAT_71CHN8;
231             default: break;
232             }
233         } else if (format->wBitsPerSample  == 16) {
234             switch (wfe->dwChannelMask) {
235             case   MONO: return AL_FORMAT_MONO16;
236             case STEREO: return AL_FORMAT_STEREO16;
237             case   REAR: return AL_FORMAT_REAR16;
238             case   QUAD: return AL_FORMAT_QUAD16;
239             case X5DOT1: return AL_FORMAT_51CHN16;
240             case X6DOT1: return AL_FORMAT_61CHN16;
241             case X7DOT1: return AL_FORMAT_71CHN16;
242             default: break;
243             }
244         }
245         else if (!(format->wBitsPerSample  % 8))
246             ERR("Could not get OpenAL PCM format (%d-bit, mask 0x%08x)\n",
247                 format->wBitsPerSample, wfe->dwChannelMask);
248         return 0;
249     }
250     else if(IsEqualGUID(&wfe->SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT)) {
251         if (format->wBitsPerSample != 32) {
252             WARN("Invalid valid bits %u/32\n", format->wBitsPerSample);
253             return 0;
254         }
255         switch (wfe->dwChannelMask) {
256         case   MONO: return AL_FORMAT_MONO_FLOAT32;
257         case STEREO: return AL_FORMAT_STEREO_FLOAT32;
258         case   REAR: return AL_FORMAT_REAR32;
259         case   QUAD: return AL_FORMAT_QUAD32;
260         case X5DOT1: return AL_FORMAT_51CHN32;
261         case X6DOT1: return AL_FORMAT_61CHN32;
262         case X7DOT1: return AL_FORMAT_71CHN32;
263         default:
264             ERR("Could not get OpenAL float format (%d-bit, mask 0x%08x)\n",
265                 format->wBitsPerSample, wfe->dwChannelMask);
266             return 0;
267         }
268     }
269     else if (!IsEqualGUID(&wfe->SubFormat, &GUID_NULL))
270         ERR("Unhandled extensible format: %s\n", debugstr_guid(&wfe->SubFormat));
271     return 0;
272 }
273
274 static ALint get_format(WAVEFORMATEX *in)
275 {
276     int ret = 0;
277     if (in->wFormatTag == WAVE_FORMAT_PCM)
278         ret = get_format_PCM(in);
279     else if (in->wFormatTag == WAVE_FORMAT_EXTENSIBLE)
280         ret = get_format_EXT(in);
281     return ret;
282 }
283
284 static REFERENCE_TIME gettime(void) {
285     LARGE_INTEGER stamp, freq;
286     QueryPerformanceCounter(&stamp);
287     QueryPerformanceFrequency(&freq);
288     return (stamp.QuadPart * (INT64)10000000) / freq.QuadPart;
289 }
290
291 HRESULT AudioClient_Create(MMDevice *parent, IAudioClient **ppv)
292 {
293     ACImpl *This = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*This));
294     *ppv = (IAudioClient*)This;
295     if (!*ppv)
296         return E_OUTOFMEMORY;
297     This->crst = &parent->crst;
298     This->lpVtbl = &ACImpl_Vtbl;
299     This->ref = 1;
300     This->parent = parent;
301     return S_OK;
302 }
303
304 static void AudioClient_Destroy(ACImpl *This)
305 {
306     if (This->timer_id)
307         DeleteTimerQueueTimer(NULL, This->timer_id, INVALID_HANDLE_VALUE);
308     if (This->render)
309         AudioRenderClient_Destroy(This->render);
310     if (This->capture)
311         AudioCaptureClient_Destroy(This->capture);
312     if (This->session)
313         AudioSessionControl_Destroy(This->session);
314     if (This->svolume)
315         AudioSimpleVolume_Destroy(This->svolume);
316     if (This->clock)
317         AudioClock_Destroy(This->clock);
318     if (This->parent->flow == eRender && This->init) {
319         setALContext(This->parent->ctx);
320         IAudioClient_Stop((IAudioClient*)This);
321         IAudioClient_Reset((IAudioClient*)This);
322         palDeleteSources(1, &This->source);
323         getALError();
324         popALContext();
325     }
326     if (This->capdev)
327         palcCaptureCloseDevice(This->capdev);
328     HeapFree(GetProcessHeap(), 0, This->pwfx);
329     HeapFree(GetProcessHeap(), 0, This->buffer);
330     HeapFree(GetProcessHeap(), 0, This);
331 }
332
333 static void CALLBACK AC_tick(void *data, BOOLEAN fired)
334 {
335     ACImpl *This = data;
336     DWORD pad;
337
338     EnterCriticalSection(This->crst);
339     if (This->running)
340         IAudioClient_GetCurrentPadding((IAudioClient*)This, &pad);
341     LeaveCriticalSection(This->crst);
342 }
343
344 /* Open device and set/update internal mixing format based on information
345  * openal provides us. if the device cannot be opened, assume 48khz
346  * Guessing the frequency is harmless, since if GetMixFormat fails to open
347  * the device, then Initialize will likely fail as well
348  */
349 static HRESULT AC_OpenRenderAL(ACImpl *This)
350 {
351     char alname[MAX_PATH];
352     MMDevice *cur = This->parent;
353
354     alname[sizeof(alname)-1] = 0;
355     if (cur->device)
356         return cur->ctx ? S_OK : AUDCLNT_E_SERVICE_NOT_RUNNING;
357
358     WideCharToMultiByte(CP_UNIXCP, 0, cur->alname, -1,
359                         alname, sizeof(alname)/sizeof(*alname)-1, NULL, NULL);
360     cur->device = palcOpenDevice(alname);
361     if (!cur->device) {
362         ALCenum err = palcGetError(NULL);
363         FIXME("Could not open device %s: 0x%04x\n", alname, err);
364         return AUDCLNT_E_DEVICE_IN_USE;
365     }
366     cur->ctx = palcCreateContext(cur->device, NULL);
367     if (!cur->ctx) {
368         ALCenum err = palcGetError(cur->device);
369         FIXME("Could not create context: 0x%04x\n", err);
370         return AUDCLNT_E_SERVICE_NOT_RUNNING;
371     }
372     if (!cur->device)
373         return AUDCLNT_E_DEVICE_IN_USE;
374     return S_OK;
375 }
376
377 static HRESULT AC_OpenCaptureAL(ACImpl *This)
378 {
379     char alname[MAX_PATH];
380     ALint freq, size;
381
382     freq = This->pwfx->nSamplesPerSec;
383     size = This->bufsize;
384
385     alname[sizeof(alname)-1] = 0;
386     if (This->capdev) {
387         FIXME("Attempting to open device while already open\n");
388         return S_OK;
389     }
390     WideCharToMultiByte(CP_UNIXCP, 0, This->parent->alname, -1,
391                         alname, sizeof(alname)/sizeof(*alname)-1, NULL, NULL);
392     This->capdev = palcCaptureOpenDevice(alname, freq, This->format, size);
393     if (!This->capdev) {
394         ALCenum err = palcGetError(NULL);
395         FIXME("Could not open device %s with buf size %u: 0x%04x\n",
396               alname, This->bufsize, err);
397         return AUDCLNT_E_DEVICE_IN_USE;
398     }
399     return S_OK;
400 }
401
402 static HRESULT WINAPI AC_QueryInterface(IAudioClient *iface, REFIID riid, void **ppv)
403 {
404     TRACE("(%p)->(%s,%p)\n", iface, debugstr_guid(riid), ppv);
405
406     if (!ppv)
407         return E_POINTER;
408     *ppv = NULL;
409     if (IsEqualIID(riid, &IID_IUnknown)
410         || IsEqualIID(riid, &IID_IAudioClient))
411         *ppv = iface;
412     if (*ppv) {
413         IUnknown_AddRef((IUnknown*)*ppv);
414         return S_OK;
415     }
416     WARN("Unknown interface %s\n", debugstr_guid(riid));
417     return E_NOINTERFACE;
418 }
419
420 static ULONG WINAPI AC_AddRef(IAudioClient *iface)
421 {
422     ACImpl *This = (ACImpl*)iface;
423     ULONG ref;
424     ref = InterlockedIncrement(&This->ref);
425     TRACE("Refcount now %i\n", ref);
426     return ref;
427 }
428
429 static ULONG WINAPI AC_Release(IAudioClient *iface)
430 {
431     ACImpl *This = (ACImpl*)iface;
432     ULONG ref;
433     ref = InterlockedDecrement(&This->ref);
434     TRACE("Refcount now %i\n", ref);
435     if (!ref)
436         AudioClient_Destroy(This);
437     return ref;
438 }
439
440 static HRESULT WINAPI AC_Initialize(IAudioClient *iface, AUDCLNT_SHAREMODE mode, DWORD flags, REFERENCE_TIME duration, REFERENCE_TIME period, const WAVEFORMATEX *pwfx, const GUID *sessionguid)
441 {
442     ACImpl *This = (ACImpl*)iface;
443     HRESULT hr = S_OK;
444     WAVEFORMATEX *pwfx2;
445     REFERENCE_TIME time, bufsize;
446
447     TRACE("(%p)->(%x,%x,%u,%u,%p,%s)\n", This, mode, flags, (int)duration, (int)period, pwfx, debugstr_guid(sessionguid));
448     if (This->init)
449         return AUDCLNT_E_ALREADY_INITIALIZED;
450     if (mode != AUDCLNT_SHAREMODE_SHARED
451         && mode != AUDCLNT_SHAREMODE_EXCLUSIVE) {
452         WARN("Unknown mode %x\n", mode);
453         return AUDCLNT_E_NOT_INITIALIZED;
454     }
455
456     if (flags & ~(AUDCLNT_STREAMFLAGS_CROSSPROCESS
457                   |AUDCLNT_STREAMFLAGS_LOOPBACK
458                   |AUDCLNT_STREAMFLAGS_EVENTCALLBACK
459                   |AUDCLNT_STREAMFLAGS_NOPERSIST
460                   |AUDCLNT_STREAMFLAGS_RATEADJUST
461                   |AUDCLNT_SESSIONFLAGS_EXPIREWHENUNOWNED
462                   |AUDCLNT_SESSIONFLAGS_DISPLAY_HIDE
463                   |AUDCLNT_SESSIONFLAGS_DISPLAY_HIDEWHENEXPIRED)) {
464         WARN("Unknown flags 0x%08x\n", flags);
465         return E_INVALIDARG;
466     }
467     if (flags)
468         WARN("Flags 0x%08x ignored\n", flags);
469     if (!pwfx)
470         return E_POINTER;
471     if (sessionguid)
472         WARN("Session guid %s ignored\n", debugstr_guid(sessionguid));
473
474     hr = IAudioClient_IsFormatSupported(iface, mode, pwfx, &pwfx2);
475     CoTaskMemFree(pwfx2);
476     if (FAILED(hr) || pwfx2)
477         return AUDCLNT_E_UNSUPPORTED_FORMAT;
478     EnterCriticalSection(This->crst);
479     HeapFree(GetProcessHeap(), 0, This->pwfx);
480     This->pwfx = HeapAlloc(GetProcessHeap(), 0, sizeof(*pwfx) + pwfx->cbSize);
481     if (!This->pwfx) {
482         hr = E_OUTOFMEMORY;
483         goto out;
484     }
485     memcpy(This->pwfx, pwfx, sizeof(*pwfx) + pwfx->cbSize);
486
487     hr = IAudioClient_GetDevicePeriod(iface, &time, NULL);
488     if (FAILED(hr))
489         goto out;
490
491     This->psize = (DWORD64)This->pwfx->nSamplesPerSec * time / (DWORD64)10000000;
492     if (duration > 20000000)
493         duration = 20000000;
494
495     bufsize = duration / time * This->psize;
496     if (duration % time)
497         bufsize += This->psize;
498     This->bufsize = bufsize;
499     This->psize *= This->pwfx->nBlockAlign;
500     bufsize *= pwfx->nBlockAlign;
501
502     This->format = get_format(This->pwfx);
503     if (This->parent->flow == eRender) {
504         char silence[32];
505         ALuint buf = 0, towrite;
506
507         hr = AC_OpenRenderAL(This);
508         if (FAILED(hr))
509             goto out;
510
511         /* Test the returned format */
512         towrite = sizeof(silence);
513         towrite -= towrite % This->pwfx->nBlockAlign;
514         if (This->pwfx->wBitsPerSample != 8)
515             memset(silence, 0, sizeof(silence));
516         else
517             memset(silence, 128, sizeof(silence));
518         setALContext(This->parent->ctx);
519         getALError();
520         palGenBuffers(1, &buf);
521         palBufferData(buf, This->format, silence, towrite, This->pwfx->nSamplesPerSec);
522         palDeleteBuffers(1, &buf);
523         if (palGetError())
524             hr = AUDCLNT_E_UNSUPPORTED_FORMAT;
525         else if (!This->source) {
526             palGenSources(1, &This->source);
527             palSourcei(This->source, AL_LOOPING, AL_FALSE);
528             getALError();
529         }
530         popALContext();
531     }
532     else
533         hr = AC_OpenCaptureAL(This);
534
535     if (FAILED(hr))
536         goto out;
537
538     This->buffer = HeapAlloc(GetProcessHeap(), 0, bufsize);
539     if (!This->buffer) {
540         hr = E_OUTOFMEMORY;
541         goto out;
542     }
543     This->flags = flags;
544     This->handle = NULL;
545     This->running = FALSE;
546     This->init = TRUE;
547 out:
548     LeaveCriticalSection(This->crst);
549     return hr;
550 }
551
552 static HRESULT WINAPI AC_GetBufferSize(IAudioClient *iface, UINT32 *frames)
553 {
554     ACImpl *This = (ACImpl*)iface;
555     TRACE("(%p)->(%p)\n", This, frames);
556     if (!This->init)
557         return AUDCLNT_E_NOT_INITIALIZED;
558     if (!frames)
559         return E_POINTER;
560     *frames = This->bufsize;
561     return S_OK;
562 }
563
564 static HRESULT WINAPI AC_GetStreamLatency(IAudioClient *iface, REFERENCE_TIME *latency)
565 {
566     ACImpl *This = (ACImpl*)iface;
567     TRACE("(%p)->(%p)\n", This, latency);
568
569     if (!This->init)
570         return AUDCLNT_E_NOT_INITIALIZED;
571
572     if (!latency)
573         return E_POINTER;
574
575     *latency = 50000;
576
577     return S_OK;
578 }
579
580 static HRESULT WINAPI AC_GetCurrentPadding(IAudioClient *iface, UINT32 *numpad)
581 {
582     ACImpl *This = (ACImpl*)iface;
583     ALint avail = 0;
584
585     TRACE("(%p)->(%p)\n", This, numpad);
586     if (!This->init)
587         return AUDCLNT_E_NOT_INITIALIZED;
588     if (!numpad)
589         return E_POINTER;
590     EnterCriticalSection(This->crst);
591     if (This->parent->flow == eRender) {
592         UINT64 played = 0;
593         ALint state, padpart;
594         setALContext(This->parent->ctx);
595
596         palGetSourcei(This->source, AL_BYTE_OFFSET, &padpart);
597         palGetSourcei(This->source, AL_SOURCE_STATE, &state);
598         padpart /= This->pwfx->nBlockAlign;
599         if (state == AL_STOPPED && This->running)
600             padpart = This->pad;
601         if (This->running && This->padpartial != padpart) {
602             This->padpartial = padpart;
603             This->laststamp = gettime();
604 #if 0 /* Manipulative lie */
605         } else if (This->running) {
606             ALint size = This->pad - padpart;
607             if (size > This->psize)
608                 size = This->psize;
609             played = (gettime() - This->laststamp)*8;
610             played = played * This->pwfx->nSamplesPerSec / 10000000;
611             if (played > size)
612                 played = size;
613 #endif
614         }
615         *numpad = This->pad - This->padpartial - played;
616         if (This->handle && *numpad + This->psize <= This->bufsize)
617             SetEvent(This->handle);
618         getALError();
619         popALContext();
620     } else {
621         DWORD block = This->pwfx->nBlockAlign;
622         DWORD psize = This->psize / block;
623         palcGetIntegerv(This->capdev, ALC_CAPTURE_SAMPLES, 1, &avail);
624         if (avail) {
625             DWORD ofs = This->ofs + This->pad;
626             BYTE *buf1;
627             ofs %= This->bufsize;
628             buf1 = This->buffer + (ofs * block);
629             This->laststamp = gettime();
630             if (This->handle)
631                 SetEvent(This->handle);
632
633             if (ofs + avail <= This->bufsize)
634                 palcCaptureSamples(This->capdev, buf1, avail);
635             else {
636                 DWORD part1 = This->bufsize - ofs;
637                 palcCaptureSamples(This->capdev, buf1, part1);
638                 palcCaptureSamples(This->capdev, This->buffer, avail - part1);
639             }
640             This->pad += avail;
641             This->frameswritten += avail;
642             /* Increase ofs if the app forgets to read */
643             if (This->pad > This->bufsize) {
644                 DWORD rest;
645                 WARN("Overflowed! %u bytes\n", This->pad - This->bufsize);
646                 This->ofs += This->pad - This->bufsize;
647                 rest = This->ofs % psize;
648                 if (rest)
649                     This->ofs += psize - rest;
650                 This->ofs %= This->bufsize;
651                 This->pad = This->bufsize;
652             }
653         }
654         if (This->pad >= psize)
655             *numpad = psize;
656         else
657             *numpad = 0;
658     }
659     LeaveCriticalSection(This->crst);
660
661     TRACE("%u queued\n", *numpad);
662     return S_OK;
663 }
664
665 static HRESULT WINAPI AC_IsFormatSupported(IAudioClient *iface, AUDCLNT_SHAREMODE mode, const WAVEFORMATEX *pwfx, WAVEFORMATEX **outpwfx)
666 {
667     ACImpl *This = (ACImpl*)iface;
668     TRACE("(%p)->(%x,%p,%p)\n", This, mode, pwfx, outpwfx);
669     if (!pwfx)
670         return E_POINTER;
671
672     if (mode == AUDCLNT_SHAREMODE_SHARED && !outpwfx)
673         return E_POINTER;
674     if (mode != AUDCLNT_SHAREMODE_SHARED
675         && mode != AUDCLNT_SHAREMODE_EXCLUSIVE) {
676         WARN("Unknown mode %x\n", mode);
677         return E_INVALIDARG;
678     }
679     if (pwfx->wFormatTag != WAVE_FORMAT_EXTENSIBLE
680         && pwfx->wFormatTag != WAVE_FORMAT_PCM)
681         return AUDCLNT_E_UNSUPPORTED_FORMAT;
682     if (pwfx->nSamplesPerSec < 8000
683         || pwfx->nSamplesPerSec > 192000)
684         return AUDCLNT_E_UNSUPPORTED_FORMAT;
685     if (pwfx->wFormatTag != WAVE_FORMAT_EXTENSIBLE
686         || !IsEqualIID(&((WAVEFORMATEXTENSIBLE*)pwfx)->SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT)) {
687         if (pwfx->wBitsPerSample > 16)
688             return AUDCLNT_E_UNSUPPORTED_FORMAT;
689     }
690     if (outpwfx)
691         *outpwfx = NULL;
692     return S_OK;
693 }
694
695 static HRESULT WINAPI AC_GetMixFormat(IAudioClient *iface, WAVEFORMATEX **pwfx)
696 {
697     ACImpl *This = (ACImpl*)iface;
698     PROPVARIANT pv = { VT_EMPTY };
699     HRESULT hr = S_OK;
700
701     TRACE("(%p)->(%p)\n", This, pwfx);
702     if (!pwfx)
703         return E_POINTER;
704
705     hr = MMDevice_GetPropValue(&This->parent->devguid, This->parent->flow,
706                                &PKEY_AudioEngine_DeviceFormat, &pv);
707     *pwfx = (WAVEFORMATEX*)pv.u.blob.pBlobData;
708     if (SUCCEEDED(hr) && pv.vt == VT_EMPTY)
709         return E_FAIL;
710
711     TRACE("Returning 0x%08x\n", hr);
712     return hr;
713 }
714
715 static HRESULT WINAPI AC_GetDevicePeriod(IAudioClient *iface, REFERENCE_TIME *defperiod, REFERENCE_TIME *minperiod)
716 {
717     ACImpl *This = (ACImpl*)iface;
718
719     TRACE("(%p)->(%p)\n", This, minperiod);
720     if (!defperiod && !minperiod)
721         return E_POINTER;
722
723     if (minperiod)
724         *minperiod = 30000;
725     if (defperiod)
726         *defperiod = 200000;
727     return S_OK;
728 }
729
730 static HRESULT WINAPI AC_Start(IAudioClient *iface)
731 {
732     ACImpl *This = (ACImpl*)iface;
733     HRESULT hr;
734     REFERENCE_TIME refresh;
735
736     TRACE("(%p)\n", This);
737     if (!This->init)
738         return AUDCLNT_E_NOT_INITIALIZED;
739     if (This->flags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK) {
740         if (!This->handle)
741             return AUDCLNT_E_EVENTHANDLE_NOT_SET;
742         FIXME("Event handles not fully tested\n");
743     }
744     EnterCriticalSection(This->crst);
745     if (This->running) {
746         hr = AUDCLNT_E_NOT_STOPPED;
747         goto out;
748     }
749     if (This->parent->flow == eRender) {
750         setALContext(This->parent->ctx);
751         palSourcePlay(This->source);
752         getALError();
753         popALContext();
754     }
755     else
756         palcCaptureStart(This->capdev);
757
758     AC_GetDevicePeriod(iface, &refresh, NULL);
759     if (!This->timer_id && This->handle)
760         CreateTimerQueueTimer(&This->timer_id, NULL, AC_tick, This,
761                               refresh / 20000, refresh / 20000,
762                               WT_EXECUTEINTIMERTHREAD);
763     /* Set to 0, otherwise risk running the clock backwards
764      * This will cause AudioClock::GetPosition to return the maximum
765      * possible value for the current buffer
766      */
767     This->laststamp = 0;
768     This->running = TRUE;
769     hr = S_OK;
770 out:
771     LeaveCriticalSection(This->crst);
772     return hr;
773 }
774
775 static HRESULT WINAPI AC_Stop(IAudioClient *iface)
776 {
777     ACImpl *This = (ACImpl*)iface;
778     HANDLE timer_id;
779     TRACE("(%p)\n", This);
780     if (!This->init)
781         return AUDCLNT_E_NOT_INITIALIZED;
782     if (!This->running)
783         return S_FALSE;
784     EnterCriticalSection(This->crst);
785     if (This->parent->flow == eRender) {
786         ALint state;
787         setALContext(This->parent->ctx);
788         This->running = FALSE;
789         palSourcePause(This->source);
790         while (1) {
791             state = AL_STOPPED;
792             palGetSourcei(This->source, AL_SOURCE_STATE, &state);
793             if (state != AL_PLAYING)
794                 break;
795             Sleep(1);
796         }
797         getALError();
798         popALContext();
799     }
800     else
801         palcCaptureStop(This->capdev);
802     timer_id = This->timer_id;
803     This->timer_id = 0;
804     LeaveCriticalSection(This->crst);
805     if (timer_id)
806         DeleteTimerQueueTimer(NULL, timer_id, INVALID_HANDLE_VALUE);
807     return S_OK;
808 }
809
810 static HRESULT WINAPI AC_Reset(IAudioClient *iface)
811 {
812     ACImpl *This = (ACImpl*)iface;
813     HRESULT hr = S_OK;
814     TRACE("(%p)\n", This);
815     if (!This->init)
816         return AUDCLNT_E_NOT_INITIALIZED;
817     if (This->running)
818         return AUDCLNT_E_NOT_STOPPED;
819     EnterCriticalSection(This->crst);
820     if (This->locked) {
821         hr = AUDCLNT_E_BUFFER_OPERATION_PENDING;
822         goto out;
823     }
824     if (This->parent->flow == eRender) {
825         ALuint buf;
826         ALint n = 0;
827         setALContext(This->parent->ctx);
828         palSourceStop(This->source);
829         palGetSourcei(This->source, AL_BUFFERS_PROCESSED, &n);
830         while (n--) {
831             palSourceUnqueueBuffers(This->source, 1, &buf);
832             palDeleteBuffers(1, &buf);
833         }
834         getALError();
835         popALContext();
836     } else {
837         ALint avail = 0;
838         palcGetIntegerv(This->capdev, ALC_CAPTURE_SAMPLES, 1, &avail);
839         if (avail)
840             palcCaptureSamples(This->capdev, This->buffer, avail);
841     }
842     This->pad = This->padpartial = 0;
843     This->ofs = 0;
844     This->frameswritten = 0;
845 out:
846     LeaveCriticalSection(This->crst);
847     return hr;
848 }
849
850 static HRESULT WINAPI AC_SetEventHandle(IAudioClient *iface, HANDLE handle)
851 {
852     ACImpl *This = (ACImpl*)iface;
853     TRACE("(%p)\n", This);
854     if (!This->init)
855         return AUDCLNT_E_NOT_INITIALIZED;
856     if (!handle)
857         return E_INVALIDARG;
858     if (!(This->flags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK))
859         return AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED;
860     This->handle = handle;
861     return S_OK;
862 }
863
864 static HRESULT WINAPI AC_GetService(IAudioClient *iface, REFIID riid, void **ppv)
865 {
866     ACImpl *This = (ACImpl*)iface;
867     HRESULT hr = S_OK;
868     TRACE("(%p)->(%s,%p)\n", This, debugstr_guid(riid), ppv);
869     if (!This->init)
870         return AUDCLNT_E_NOT_INITIALIZED;
871     if (!ppv)
872         return E_POINTER;
873     *ppv = NULL;
874
875     if (IsEqualIID(riid, &IID_IAudioRenderClient)) {
876         if (This->parent->flow != eRender)
877             return AUDCLNT_E_WRONG_ENDPOINT_TYPE;
878         if (!This->render)
879             hr = AudioRenderClient_Create(This, &This->render);
880         *ppv = This->render;
881     } else if (IsEqualIID(riid, &IID_IAudioCaptureClient)) {
882         if (This->parent->flow != eCapture)
883             return AUDCLNT_E_WRONG_ENDPOINT_TYPE;
884         if (!This->capture)
885             hr = AudioCaptureClient_Create(This, &This->capture);
886         *ppv = This->capture;
887     } else if (IsEqualIID(riid, &IID_IAudioSessionControl)) {
888         if (!This->session)
889             hr = AudioSessionControl_Create(This, &This->session);
890         *ppv = This->session;
891     } else if (IsEqualIID(riid, &IID_ISimpleAudioVolume)) {
892         if (!This->svolume)
893             hr = AudioSimpleVolume_Create(This, &This->svolume);
894         *ppv = This->svolume;
895     } else if (IsEqualIID(riid, &IID_IAudioClock)) {
896         if (!This->clock)
897             hr = AudioClock_Create(This, &This->clock);
898         *ppv = This->clock;
899     }
900
901     if (FAILED(hr))
902         return hr;
903
904     if (*ppv) {
905         IUnknown_AddRef((IUnknown*)*ppv);
906         return S_OK;
907     }
908
909     FIXME("stub %s\n", debugstr_guid(riid));
910     return E_NOINTERFACE;
911 }
912
913 static const IAudioClientVtbl ACImpl_Vtbl =
914 {
915     AC_QueryInterface,
916     AC_AddRef,
917     AC_Release,
918     AC_Initialize,
919     AC_GetBufferSize,
920     AC_GetStreamLatency,
921     AC_GetCurrentPadding,
922     AC_IsFormatSupported,
923     AC_GetMixFormat,
924     AC_GetDevicePeriod,
925     AC_Start,
926     AC_Stop,
927     AC_Reset,
928     AC_SetEventHandle,
929     AC_GetService
930 };
931
932 static HRESULT AudioRenderClient_Create(ACImpl *parent, ACRender **ppv)
933 {
934     ACRender *This;
935
936     This = *ppv = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
937     if (!This)
938         return E_OUTOFMEMORY;
939     This->lpVtbl = &ACRender_Vtbl;
940     This->ref = 0;
941     This->parent = parent;
942     return S_OK;
943 }
944
945 static void AudioRenderClient_Destroy(ACRender *This)
946 {
947     This->parent->render = NULL;
948     HeapFree(GetProcessHeap(), 0, This);
949 }
950
951 static HRESULT WINAPI ACR_QueryInterface(IAudioRenderClient *iface, REFIID riid, void **ppv)
952 {
953     TRACE("(%p)->(%s,%p)\n", iface, debugstr_guid(riid), ppv);
954
955     if (!ppv)
956         return E_POINTER;
957     *ppv = NULL;
958     if (IsEqualIID(riid, &IID_IUnknown)
959         || IsEqualIID(riid, &IID_IAudioRenderClient))
960         *ppv = iface;
961     if (*ppv) {
962         IUnknown_AddRef((IUnknown*)*ppv);
963         return S_OK;
964     }
965     WARN("Unknown interface %s\n", debugstr_guid(riid));
966     return E_NOINTERFACE;
967 }
968
969 static ULONG WINAPI ACR_AddRef(IAudioRenderClient *iface)
970 {
971     ACRender *This = (ACRender*)iface;
972     ULONG ref;
973     ref = InterlockedIncrement(&This->ref);
974     TRACE("Refcount now %i\n", ref);
975     return ref;
976 }
977
978 static ULONG WINAPI ACR_Release(IAudioRenderClient *iface)
979 {
980     ACRender *This = (ACRender*)iface;
981     ULONG ref;
982     ref = InterlockedDecrement(&This->ref);
983     TRACE("Refcount now %i\n", ref);
984     if (!ref)
985         AudioRenderClient_Destroy(This);
986     return ref;
987 }
988
989 static HRESULT WINAPI ACR_GetBuffer(IAudioRenderClient *iface, UINT32 frames, BYTE **data)
990 {
991     ACRender *This = (ACRender*)iface;
992     DWORD free, framesize;
993     TRACE("(%p)->(%u,%p)\n", This, frames, data);
994
995     if (!data)
996         return E_POINTER;
997     if (!frames)
998         return S_OK;
999     *data = NULL;
1000     if (This->parent->locked) {
1001         ERR("Locked\n");
1002         return AUDCLNT_E_OUT_OF_ORDER;
1003     }
1004     AC_GetCurrentPadding((IAudioClient*)This->parent, &free);
1005     if (This->parent->bufsize-free < frames) {
1006         ERR("Too large: %u %u %u\n", This->parent->bufsize, free, frames);
1007         return AUDCLNT_E_BUFFER_TOO_LARGE;
1008     }
1009     EnterCriticalSection(This->parent->crst);
1010     This->parent->locked = frames;
1011     framesize = This->parent->pwfx->nBlockAlign;
1012
1013     /* Exact offset doesn't matter, offset could be 0 forever
1014      * but increasing it is easier to debug */
1015     if (This->parent->ofs + frames > This->parent->bufsize)
1016         This->parent->ofs = 0;
1017     *data = This->parent->buffer + This->parent->ofs * framesize;
1018
1019     LeaveCriticalSection(This->parent->crst);
1020     return S_OK;
1021 }
1022
1023 static HRESULT WINAPI ACR_ReleaseBuffer(IAudioRenderClient *iface, UINT32 written, DWORD flags)
1024 {
1025     ACRender *This = (ACRender*)iface;
1026     BYTE *buf = This->parent->buffer;
1027     DWORD framesize = This->parent->pwfx->nBlockAlign;
1028     DWORD ofs = This->parent->ofs;
1029     DWORD bufsize = This->parent->bufsize;
1030     DWORD locked = This->parent->locked;
1031     DWORD freq = This->parent->pwfx->nSamplesPerSec;
1032     DWORD bpp = This->parent->pwfx->wBitsPerSample;
1033     ALuint albuf;
1034
1035     TRACE("(%p)->(%u,%x)\n", This, written, flags);
1036
1037     if (locked < written)
1038         return AUDCLNT_E_INVALID_SIZE;
1039
1040     if (flags & ~AUDCLNT_BUFFERFLAGS_SILENT)
1041         return E_INVALIDARG;
1042
1043     if (!written) {
1044         FIXME("Handled right?\n");
1045         This->parent->locked = 0;
1046         return S_OK;
1047     }
1048
1049     if (!This->parent->locked)
1050         return AUDCLNT_E_OUT_OF_ORDER;
1051
1052     EnterCriticalSection(This->parent->crst);
1053     setALContext(This->parent->parent->ctx);
1054
1055     This->parent->ofs += written;
1056     This->parent->ofs %= bufsize;
1057     This->parent->pad += written;
1058     This->parent->frameswritten += written;
1059
1060     ofs *= framesize;
1061     written *= framesize;
1062     bufsize *= framesize;
1063     locked *= framesize;
1064
1065     if (flags & AUDCLNT_BUFFERFLAGS_SILENT)
1066         memset(buf+ofs, bpp != 8 ? 0 : 128, written);
1067     TRACE("buf: %p, ofs: %x, written %u, freq %u\n", buf, ofs, written, freq);
1068
1069     palGenBuffers(1, &albuf);
1070     palBufferData(albuf, This->parent->format, buf+ofs, written, freq);
1071     palSourceQueueBuffers(This->parent->source, 1, &albuf);
1072     TRACE("Queued %u\n", albuf);
1073
1074     if (This->parent->running) {
1075         ALint state = AL_PLAYING, done = 0, padpart = 0;
1076
1077         palGetSourcei(This->parent->source, AL_BUFFERS_PROCESSED, &done);
1078         palGetSourcei(This->parent->source, AL_BYTE_OFFSET, &padpart);
1079         palGetSourcei(This->parent->source, AL_SOURCE_STATE, &state);
1080         padpart /= framesize;
1081
1082         if (state == AL_STOPPED) {
1083             padpart = This->parent->pad;
1084             /* Buffer might have been processed in the small window
1085              * between first and third call */
1086             palGetSourcei(This->parent->source, AL_BUFFERS_PROCESSED, &done);
1087         }
1088         if (done || This->parent->padpartial != padpart)
1089             This->parent->laststamp = gettime();
1090         This->parent->padpartial = padpart;
1091
1092         while (done--) {
1093             ALint size, bits, chan;
1094             ALuint which;
1095
1096             palSourceUnqueueBuffers(This->parent->source, 1, &which);
1097             palGetBufferi(which, AL_SIZE, &size);
1098             palGetBufferi(which, AL_BITS, &bits);
1099             palGetBufferi(which, AL_CHANNELS, &chan);
1100             size /= bits * chan / 8;
1101             if (size > This->parent->pad) {
1102                 ERR("Overflow!\n");
1103                 size = This->parent->pad;
1104             }
1105             This->parent->pad -= size;
1106             This->parent->padpartial -= size;
1107             TRACE("Unqueued %u\n", which);
1108             palDeleteBuffers(1, &which);
1109         }
1110
1111         if (state != AL_PLAYING) {
1112             ERR("Starting from %x\n", state);
1113             palSourcePlay(This->parent->source);
1114         }
1115         getALError();
1116     }
1117     This->parent->locked = 0;
1118
1119     getALError();
1120     popALContext();
1121     LeaveCriticalSection(This->parent->crst);
1122
1123     return S_OK;
1124 }
1125
1126 static const IAudioRenderClientVtbl ACRender_Vtbl = {
1127     ACR_QueryInterface,
1128     ACR_AddRef,
1129     ACR_Release,
1130     ACR_GetBuffer,
1131     ACR_ReleaseBuffer
1132 };
1133
1134 static HRESULT AudioCaptureClient_Create(ACImpl *parent, ACCapture **ppv)
1135 {
1136     ACCapture *This;
1137     This = *ppv = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
1138     if (!This)
1139         return E_OUTOFMEMORY;
1140     This->lpVtbl = &ACCapture_Vtbl;
1141     This->ref = 0;
1142     This->parent = parent;
1143     return S_OK;
1144 }
1145
1146 static void AudioCaptureClient_Destroy(ACCapture *This)
1147 {
1148     This->parent->capture = NULL;
1149     HeapFree(GetProcessHeap(), 0, This);
1150 }
1151
1152 static HRESULT WINAPI ACC_QueryInterface(IAudioCaptureClient *iface, REFIID riid, void **ppv)
1153 {
1154     TRACE("(%p)->(%s,%p)\n", iface, debugstr_guid(riid), ppv);
1155
1156     if (!ppv)
1157         return E_POINTER;
1158     *ppv = NULL;
1159     if (IsEqualIID(riid, &IID_IUnknown)
1160         || IsEqualIID(riid, &IID_IAudioCaptureClient))
1161         *ppv = iface;
1162     if (*ppv) {
1163         IUnknown_AddRef((IUnknown*)*ppv);
1164         return S_OK;
1165     }
1166     WARN("Unknown interface %s\n", debugstr_guid(riid));
1167     return E_NOINTERFACE;
1168 }
1169
1170 static ULONG WINAPI ACC_AddRef(IAudioCaptureClient *iface)
1171 {
1172     ACCapture *This = (ACCapture*)iface;
1173     ULONG ref;
1174     ref = InterlockedIncrement(&This->ref);
1175     TRACE("Refcount now %i\n", ref);
1176     return ref;
1177 }
1178
1179 static ULONG WINAPI ACC_Release(IAudioCaptureClient *iface)
1180 {
1181     ACCapture *This = (ACCapture*)iface;
1182     ULONG ref;
1183     ref = InterlockedDecrement(&This->ref);
1184     TRACE("Refcount now %i\n", ref);
1185     if (!ref)
1186         AudioCaptureClient_Destroy(This);
1187     return ref;
1188 }
1189
1190 static HRESULT WINAPI ACC_GetBuffer(IAudioCaptureClient *iface, BYTE **data, UINT32 *frames, DWORD *flags, UINT64 *devpos, UINT64 *qpcpos)
1191 {
1192     ACCapture *This = (ACCapture*)iface;
1193     HRESULT hr;
1194     DWORD block = This->parent->pwfx->nBlockAlign;
1195     DWORD ofs, bufsize;
1196     TRACE("(%p)->(%p,%p,%p,%p,%p)\n", This, data, frames, flags, devpos, qpcpos);
1197
1198     if (!data)
1199         return E_POINTER;
1200     if (!frames)
1201         return E_POINTER;
1202     if (!flags) {
1203         FIXME("Flags can be null?\n");
1204         return E_POINTER;
1205     }
1206     EnterCriticalSection(This->parent->crst);
1207     hr = AUDCLNT_E_OUT_OF_ORDER;
1208     if (This->parent->locked)
1209         goto out;
1210     IAudioCaptureClient_GetNextPacketSize(iface, frames);
1211     ofs = This->parent->ofs;
1212     bufsize = This->parent->bufsize;
1213     if ( (ofs*block) % This->parent->psize)
1214         ERR("Unaligned offset %u with %u\n", ofs*block, This->parent->psize);
1215     *data = This->parent->buffer + ofs * block;
1216     This->parent->locked = *frames;
1217     if (devpos)
1218         *devpos = This->parent->frameswritten - This->parent->pad;
1219     if (qpcpos)
1220         *qpcpos = This->parent->laststamp;
1221     if (*frames)
1222         hr = S_OK;
1223     else
1224         hr = AUDCLNT_S_BUFFER_EMPTY;
1225 out:
1226     LeaveCriticalSection(This->parent->crst);
1227     TRACE("Returning %08x %i\n", hr, *frames);
1228     return hr;
1229 }
1230
1231 static HRESULT WINAPI ACC_ReleaseBuffer(IAudioCaptureClient *iface, UINT32 written)
1232 {
1233     ACCapture *This = (ACCapture*)iface;
1234     HRESULT hr = S_OK;
1235     EnterCriticalSection(This->parent->crst);
1236     if (!written || written == This->parent->locked) {
1237         This->parent->locked = 0;
1238         This->parent->ofs += written;
1239         This->parent->ofs %= This->parent->bufsize;
1240         This->parent->pad -= written;
1241     } else if (!This->parent->locked)
1242         hr = AUDCLNT_E_OUT_OF_ORDER;
1243     else
1244         hr = AUDCLNT_E_INVALID_SIZE;
1245     LeaveCriticalSection(This->parent->crst);
1246     return hr;
1247 }
1248
1249 static HRESULT WINAPI ACC_GetNextPacketSize(IAudioCaptureClient *iface, UINT32 *frames)
1250 {
1251     ACCapture *This = (ACCapture*)iface;
1252
1253     return AC_GetCurrentPadding((IAudioClient*)This->parent, frames);
1254 }
1255
1256 static const IAudioCaptureClientVtbl ACCapture_Vtbl =
1257 {
1258     ACC_QueryInterface,
1259     ACC_AddRef,
1260     ACC_Release,
1261     ACC_GetBuffer,
1262     ACC_ReleaseBuffer,
1263     ACC_GetNextPacketSize
1264 };
1265
1266 static HRESULT AudioSessionControl_Create(ACImpl *parent, ACSession **ppv)
1267 {
1268     ACSession *This;
1269     This = *ppv = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
1270     if (!This)
1271         return E_OUTOFMEMORY;
1272     This->lpVtbl = &ACSession_Vtbl;
1273     This->ref = 0;
1274     This->parent = parent;
1275     return S_OK;
1276 }
1277
1278 static void AudioSessionControl_Destroy(ACSession *This)
1279 {
1280     This->parent->session = NULL;
1281     HeapFree(GetProcessHeap(), 0, This);
1282 }
1283
1284 static HRESULT WINAPI ACS_QueryInterface(IAudioSessionControl2 *iface, REFIID riid, void **ppv)
1285 {
1286     TRACE("(%p)->(%s,%p)\n", iface, debugstr_guid(riid), ppv);
1287
1288     if (!ppv)
1289         return E_POINTER;
1290     *ppv = NULL;
1291     if (IsEqualIID(riid, &IID_IUnknown)
1292         || IsEqualIID(riid, &IID_IAudioSessionControl)
1293         || IsEqualIID(riid, &IID_IAudioSessionControl2))
1294         *ppv = iface;
1295     if (*ppv) {
1296         IUnknown_AddRef((IUnknown*)*ppv);
1297         return S_OK;
1298     }
1299     WARN("Unknown interface %s\n", debugstr_guid(riid));
1300     return E_NOINTERFACE;
1301 }
1302
1303 static ULONG WINAPI ACS_AddRef(IAudioSessionControl2 *iface)
1304 {
1305     ACSession *This = (ACSession*)iface;
1306     ULONG ref;
1307     ref = InterlockedIncrement(&This->ref);
1308     TRACE("Refcount now %i\n", ref);
1309     return ref;
1310 }
1311
1312 static ULONG WINAPI ACS_Release(IAudioSessionControl2 *iface)
1313 {
1314     ACSession *This = (ACSession*)iface;
1315     ULONG ref;
1316     ref = InterlockedDecrement(&This->ref);
1317     TRACE("Refcount now %i\n", ref);
1318     if (!ref)
1319         AudioSessionControl_Destroy(This);
1320     return ref;
1321 }
1322
1323 static HRESULT WINAPI ACS_GetState(IAudioSessionControl2 *iface, AudioSessionState *state)
1324 {
1325     ACSession *This = (ACSession*)iface;
1326     TRACE("(%p)->(%p)\n", This, state);
1327
1328     if (!state)
1329         return E_POINTER;
1330     *state = This->parent->parent->state;
1331     return E_NOTIMPL;
1332 }
1333
1334 static HRESULT WINAPI ACS_GetDisplayName(IAudioSessionControl2 *iface, WCHAR **name)
1335 {
1336     ACSession *This = (ACSession*)iface;
1337     TRACE("(%p)->(%p)\n", This, name);
1338     FIXME("stub\n");
1339     if (name)
1340         *name = NULL;
1341     return E_NOTIMPL;
1342 }
1343
1344 static HRESULT WINAPI ACS_SetDisplayName(IAudioSessionControl2 *iface, const WCHAR *name, const GUID *session)
1345 {
1346     ACSession *This = (ACSession*)iface;
1347     TRACE("(%p)->(%p,%s)\n", This, name, debugstr_guid(session));
1348     FIXME("stub\n");
1349     return E_NOTIMPL;
1350 }
1351
1352 static HRESULT WINAPI ACS_GetIconPath(IAudioSessionControl2 *iface, WCHAR **path)
1353 {
1354     ACSession *This = (ACSession*)iface;
1355     TRACE("(%p)->(%p)\n", This, path);
1356     FIXME("stub\n");
1357     if (path)
1358         *path = NULL;
1359     return E_NOTIMPL;
1360 }
1361
1362 static HRESULT WINAPI ACS_SetIconPath(IAudioSessionControl2 *iface, const WCHAR *path, const GUID *session)
1363 {
1364     ACSession *This = (ACSession*)iface;
1365     TRACE("(%p)->(%p,%s)\n", This, path, debugstr_guid(session));
1366     FIXME("stub\n");
1367     return E_NOTIMPL;
1368 }
1369
1370 static HRESULT WINAPI ACS_GetGroupingParam(IAudioSessionControl2 *iface, GUID *group)
1371 {
1372     ACSession *This = (ACSession*)iface;
1373     TRACE("(%p)->(%p)\n", This, group);
1374     FIXME("stub\n");
1375     if (group)
1376         *group = GUID_NULL;
1377     return E_NOTIMPL;
1378 }
1379
1380 static HRESULT WINAPI ACS_SetGroupingParam(IAudioSessionControl2 *iface, GUID *group, const GUID *session)
1381 {
1382     ACSession *This = (ACSession*)iface;
1383     TRACE("(%p)->(%s,%s)\n", This, debugstr_guid(group), debugstr_guid(session));
1384     FIXME("stub\n");
1385     return E_NOTIMPL;
1386 }
1387
1388 static HRESULT WINAPI ACS_RegisterAudioSessionNotification(IAudioSessionControl2 *iface, IAudioSessionEvents *events)
1389 {
1390     ACSession *This = (ACSession*)iface;
1391     TRACE("(%p)->(%p)\n", This, events);
1392     FIXME("stub\n");
1393     return S_OK;
1394 }
1395
1396 static HRESULT WINAPI ACS_UnregisterAudioSessionNotification(IAudioSessionControl2 *iface, IAudioSessionEvents *events)
1397 {
1398     ACSession *This = (ACSession*)iface;
1399     TRACE("(%p)->(%p)\n", This, events);
1400     FIXME("stub\n");
1401     return S_OK;
1402 }
1403
1404 static HRESULT WINAPI ACS_GetSessionIdentifier(IAudioSessionControl2 *iface, WCHAR **id)
1405 {
1406     ACSession *This = (ACSession*)iface;
1407     TRACE("(%p)->(%p)\n", This, id);
1408     FIXME("stub\n");
1409     if (id)
1410         *id = NULL;
1411     return E_NOTIMPL;
1412 }
1413
1414 static HRESULT WINAPI ACS_GetSessionInstanceIdentifier(IAudioSessionControl2 *iface, WCHAR **id)
1415 {
1416     ACSession *This = (ACSession*)iface;
1417     TRACE("(%p)->(%p)\n", This, id);
1418     FIXME("stub\n");
1419     if (id)
1420         *id = NULL;
1421     return E_NOTIMPL;
1422 }
1423
1424 static HRESULT WINAPI ACS_GetProcessId(IAudioSessionControl2 *iface, DWORD *pid)
1425 {
1426     ACSession *This = (ACSession*)iface;
1427     TRACE("(%p)->(%p)\n", This, pid);
1428
1429     if (!pid)
1430         return E_POINTER;
1431     *pid = GetCurrentProcessId();
1432     return S_OK;
1433 }
1434
1435 static HRESULT WINAPI ACS_IsSystemSoundsSession(IAudioSessionControl2 *iface)
1436 {
1437     ACSession *This = (ACSession*)iface;
1438     TRACE("(%p)\n", This);
1439
1440     return S_FALSE;
1441 }
1442
1443 static HRESULT WINAPI ACS_SetDuckingPreference(IAudioSessionControl2 *iface, BOOL optout)
1444 {
1445     ACSession *This = (ACSession*)iface;
1446     TRACE("(%p)\n", This);
1447
1448     return S_OK;
1449 }
1450
1451 static const IAudioSessionControl2Vtbl ACSession_Vtbl =
1452 {
1453     ACS_QueryInterface,
1454     ACS_AddRef,
1455     ACS_Release,
1456     ACS_GetState,
1457     ACS_GetDisplayName,
1458     ACS_SetDisplayName,
1459     ACS_GetIconPath,
1460     ACS_SetIconPath,
1461     ACS_GetGroupingParam,
1462     ACS_SetGroupingParam,
1463     ACS_RegisterAudioSessionNotification,
1464     ACS_UnregisterAudioSessionNotification,
1465     ACS_GetSessionIdentifier,
1466     ACS_GetSessionInstanceIdentifier,
1467     ACS_GetProcessId,
1468     ACS_IsSystemSoundsSession,
1469     ACS_SetDuckingPreference
1470 };
1471
1472 static HRESULT AudioSimpleVolume_Create(ACImpl *parent, ASVolume **ppv)
1473 {
1474     ASVolume *This;
1475     This = *ppv = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
1476     if (!This)
1477         return E_OUTOFMEMORY;
1478     This->lpVtbl = &ASVolume_Vtbl;
1479     This->ref = 0;
1480     This->parent = parent;
1481     return S_OK;
1482 }
1483
1484 static void AudioSimpleVolume_Destroy(ASVolume *This)
1485 {
1486     This->parent->svolume = NULL;
1487     HeapFree(GetProcessHeap(), 0, This);
1488 }
1489
1490 static HRESULT WINAPI ASV_QueryInterface(ISimpleAudioVolume *iface, REFIID riid, void **ppv)
1491 {
1492     TRACE("(%p)->(%s,%p)\n", iface, debugstr_guid(riid), ppv);
1493
1494     if (!ppv)
1495         return E_POINTER;
1496     *ppv = NULL;
1497     if (IsEqualIID(riid, &IID_IUnknown)
1498         || IsEqualIID(riid, &IID_ISimpleAudioVolume))
1499         *ppv = iface;
1500     if (*ppv) {
1501         IUnknown_AddRef((IUnknown*)*ppv);
1502         return S_OK;
1503     }
1504     WARN("Unknown interface %s\n", debugstr_guid(riid));
1505     return E_NOINTERFACE;
1506 }
1507
1508 static ULONG WINAPI ASV_AddRef(ISimpleAudioVolume *iface)
1509 {
1510     ASVolume *This = (ASVolume*)iface;
1511     ULONG ref;
1512     ref = InterlockedIncrement(&This->ref);
1513     TRACE("Refcount now %i\n", ref);
1514     return ref;
1515 }
1516
1517 static ULONG WINAPI ASV_Release(ISimpleAudioVolume *iface)
1518 {
1519     ASVolume *This = (ASVolume*)iface;
1520     ULONG ref;
1521     ref = InterlockedDecrement(&This->ref);
1522     TRACE("Refcount now %i\n", ref);
1523     if (!ref)
1524         AudioSimpleVolume_Destroy(This);
1525     return ref;
1526 }
1527
1528 static HRESULT WINAPI ASV_SetMasterVolume(ISimpleAudioVolume *iface, float level, const GUID *context)
1529 {
1530     ASVolume *This = (ASVolume*)iface;
1531     TRACE("(%p)->(%f,%p)\n", This, level, context);
1532
1533     FIXME("stub\n");
1534     return S_OK;
1535 }
1536
1537 static HRESULT WINAPI ASV_GetMasterVolume(ISimpleAudioVolume *iface, float *level)
1538 {
1539     ASVolume *This = (ASVolume*)iface;
1540     TRACE("(%p)->(%p)\n", This, level);
1541
1542     *level = 1.f;
1543     FIXME("stub\n");
1544     return S_OK;
1545 }
1546
1547 static HRESULT WINAPI ASV_SetMute(ISimpleAudioVolume *iface, BOOL mute, const GUID *context)
1548 {
1549     ASVolume *This = (ASVolume*)iface;
1550     TRACE("(%p)->(%u,%p)\n", This, mute, context);
1551
1552     FIXME("stub\n");
1553     return S_OK;
1554 }
1555
1556 static HRESULT WINAPI ASV_GetMute(ISimpleAudioVolume *iface, BOOL *mute)
1557 {
1558     ASVolume *This = (ASVolume*)iface;
1559     TRACE("(%p)->(%p)\n", This, mute);
1560
1561     *mute = 0;
1562     FIXME("stub\n");
1563     return S_OK;
1564 }
1565
1566 static const ISimpleAudioVolumeVtbl ASVolume_Vtbl  =
1567 {
1568     ASV_QueryInterface,
1569     ASV_AddRef,
1570     ASV_Release,
1571     ASV_SetMasterVolume,
1572     ASV_GetMasterVolume,
1573     ASV_SetMute,
1574     ASV_GetMute
1575 };
1576
1577 static HRESULT AudioClock_Create(ACImpl *parent, AClock **ppv)
1578 {
1579     AClock *This;
1580     This = *ppv = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
1581     if (!This)
1582         return E_OUTOFMEMORY;
1583     This->lpVtbl = &AClock_Vtbl;
1584     This->lp2Vtbl = &AClock2_Vtbl;
1585     This->ref = 0;
1586     This->parent = parent;
1587     return S_OK;
1588 }
1589
1590 static void AudioClock_Destroy(AClock *This)
1591 {
1592     This->parent->clock = NULL;
1593     HeapFree(GetProcessHeap(), 0, This);
1594 }
1595
1596 static HRESULT WINAPI AClock_QueryInterface(IAudioClock *iface, REFIID riid, void **ppv)
1597 {
1598     AClock *This = (AClock*)iface;
1599     TRACE("(%p)->(%s,%p)\n", iface, debugstr_guid(riid), ppv);
1600
1601     if (!ppv)
1602         return E_POINTER;
1603     *ppv = NULL;
1604     if (IsEqualIID(riid, &IID_IUnknown)
1605         || IsEqualIID(riid, &IID_IAudioClock))
1606         *ppv = iface;
1607     else if (IsEqualIID(riid, &IID_IAudioClock2))
1608         *ppv = &This->lp2Vtbl;
1609     if (*ppv) {
1610         IUnknown_AddRef((IUnknown*)*ppv);
1611         return S_OK;
1612     }
1613     WARN("Unknown interface %s\n", debugstr_guid(riid));
1614     return E_NOINTERFACE;
1615 }
1616
1617 static ULONG WINAPI AClock_AddRef(IAudioClock *iface)
1618 {
1619     AClock *This = (AClock*)iface;
1620     ULONG ref;
1621     ref = InterlockedIncrement(&This->ref);
1622     TRACE("Refcount now %i\n", ref);
1623     return ref;
1624 }
1625
1626 static ULONG WINAPI AClock_Release(IAudioClock *iface)
1627 {
1628     AClock *This = (AClock*)iface;
1629     ULONG ref;
1630     ref = InterlockedDecrement(&This->ref);
1631     TRACE("Refcount now %i\n", ref);
1632     if (!ref)
1633         AudioClock_Destroy(This);
1634     return ref;
1635 }
1636
1637 static HRESULT WINAPI AClock_GetFrequency(IAudioClock *iface, UINT64 *freq)
1638 {
1639     AClock *This = (AClock*)iface;
1640     TRACE("(%p)->(%p)\n", This, freq);
1641
1642     *freq = (UINT64)This->parent->pwfx->nSamplesPerSec;
1643     return S_OK;
1644 }
1645
1646 static HRESULT WINAPI AClock_GetPosition(IAudioClock *iface, UINT64 *pos, UINT64 *qpctime)
1647 {
1648     AClock *This = (AClock*)iface;
1649     DWORD pad;
1650
1651     TRACE("(%p)->(%p,%p)\n", This, pos, qpctime);
1652
1653     if (!pos)
1654         return E_POINTER;
1655
1656     EnterCriticalSection(This->parent->crst);
1657     AC_GetCurrentPadding((IAudioClient*)This->parent, &pad);
1658     *pos = This->parent->frameswritten - pad;
1659     if (qpctime)
1660         *qpctime = gettime();
1661     LeaveCriticalSection(This->parent->crst);
1662
1663     return S_OK;
1664 }
1665
1666 static HRESULT WINAPI AClock_GetCharacteristics(IAudioClock *iface, DWORD *chars)
1667 {
1668     AClock *This = (AClock*)iface;
1669     TRACE("(%p)->(%p)\n", This, chars);
1670
1671     if (!chars)
1672         return E_POINTER;
1673     *chars = AUDIOCLOCK_CHARACTERISTIC_FIXED_FREQ;
1674     return S_OK;
1675 }
1676
1677 static const IAudioClockVtbl AClock_Vtbl =
1678 {
1679     AClock_QueryInterface,
1680     AClock_AddRef,
1681     AClock_Release,
1682     AClock_GetFrequency,
1683     AClock_GetPosition,
1684     AClock_GetCharacteristics
1685 };
1686
1687 static AClock *get_clock_from_clock2(IAudioClock2 *iface)
1688 {
1689     return (AClock*)((char*)iface - offsetof(AClock,lp2Vtbl));
1690 }
1691
1692 static HRESULT WINAPI AClock2_QueryInterface(IAudioClock2 *iface, REFIID riid, void **ppv)
1693 {
1694     AClock *This = get_clock_from_clock2(iface);
1695     return IUnknown_QueryInterface((IUnknown*)This, riid, ppv);
1696 }
1697
1698 static ULONG WINAPI AClock2_AddRef(IAudioClock2 *iface)
1699 {
1700     AClock *This = get_clock_from_clock2(iface);
1701     return IUnknown_AddRef((IUnknown*)This);
1702 }
1703
1704 static ULONG WINAPI AClock2_Release(IAudioClock2 *iface)
1705 {
1706     AClock *This = get_clock_from_clock2(iface);
1707     return IUnknown_Release((IUnknown*)This);
1708 }
1709
1710 static HRESULT WINAPI AClock2_GetPosition(IAudioClock2 *iface, UINT64 *pos, UINT64 *qpctime)
1711 {
1712     AClock *This = get_clock_from_clock2(iface);
1713     return AClock_GetPosition((IAudioClock*)This, pos, qpctime);
1714 }
1715
1716 static const IAudioClock2Vtbl AClock2_Vtbl =
1717 {
1718     AClock2_QueryInterface,
1719     AClock2_AddRef,
1720     AClock2_Release,
1721     AClock2_GetPosition
1722 };
1723
1724 #endif