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