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