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