winecoreaudio: Fix latency calculation.
[wine] / dlls / winecoreaudio.drv / mmdevdrv.c
1 /*
2  * Copyright 2011 Andrew Eikum 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
25 #include "windef.h"
26 #include "winbase.h"
27 #include "winnls.h"
28 #include "winreg.h"
29 #include "wine/debug.h"
30 #include "wine/unicode.h"
31 #include "wine/list.h"
32
33 #include "ole2.h"
34 #include "mmdeviceapi.h"
35 #include "devpkey.h"
36 #include "dshow.h"
37 #include "dsound.h"
38
39 #include "initguid.h"
40 #include "endpointvolume.h"
41 #include "audioclient.h"
42 #include "audiopolicy.h"
43
44 #include <errno.h>
45 #include <limits.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <sys/types.h>
50 #include <sys/stat.h>
51 #include <sys/ioctl.h>
52 #include <fcntl.h>
53 #include <unistd.h>
54
55 #include <libkern/OSAtomic.h>
56 #include <CoreAudio/CoreAudio.h>
57 #include <AudioToolbox/AudioQueue.h>
58
59 WINE_DEFAULT_DEBUG_CHANNEL(coreaudio);
60
61 #define NULL_PTR_ERR MAKE_HRESULT(SEVERITY_ERROR, FACILITY_WIN32, RPC_X_NULL_REF_POINTER)
62
63 #define CAPTURE_BUFFERS 5
64
65 static const REFERENCE_TIME DefaultPeriod = 200000;
66 static const REFERENCE_TIME MinimumPeriod = 100000;
67
68 typedef struct _QueuedBufInfo {
69     Float64 start_sampletime;
70     UINT64 start_pos;
71     UINT32 len_frames;
72     struct list entry;
73 } QueuedBufInfo;
74
75 typedef struct _AQBuffer {
76     AudioQueueBufferRef buf;
77     struct list entry;
78 } AQBuffer;
79
80 struct ACImpl;
81 typedef struct ACImpl ACImpl;
82
83 typedef struct _AudioSession {
84     GUID guid;
85     struct list clients;
86
87     IMMDevice *device;
88
89     float master_vol;
90     UINT32 channel_count;
91     float *channel_vols;
92     BOOL mute;
93
94     CRITICAL_SECTION lock;
95
96     struct list entry;
97 } AudioSession;
98
99 typedef struct _AudioSessionWrapper {
100     IAudioSessionControl2 IAudioSessionControl2_iface;
101     IChannelAudioVolume IChannelAudioVolume_iface;
102     ISimpleAudioVolume ISimpleAudioVolume_iface;
103
104     LONG ref;
105
106     ACImpl *client;
107     AudioSession *session;
108 } AudioSessionWrapper;
109
110 struct ACImpl {
111     IAudioClient IAudioClient_iface;
112     IAudioRenderClient IAudioRenderClient_iface;
113     IAudioCaptureClient IAudioCaptureClient_iface;
114     IAudioClock IAudioClock_iface;
115     IAudioClock2 IAudioClock2_iface;
116     IAudioStreamVolume IAudioStreamVolume_iface;
117
118     LONG ref;
119
120     IMMDevice *parent;
121
122     WAVEFORMATEX *fmt;
123
124     EDataFlow dataflow;
125     DWORD flags;
126     AUDCLNT_SHAREMODE share;
127     HANDLE event;
128     float *vols;
129
130     AudioDeviceID adevid;
131     AudioQueueRef aqueue;
132     AudioObjectPropertyScope scope;
133     HANDLE timer;
134     UINT32 period_ms, bufsize_frames, inbuf_frames;
135     UINT64 last_time, written_frames;
136     AudioQueueBufferRef public_buffer;
137     UINT32 getbuf_last;
138     int playing;
139
140     Float64 highest_sampletime;
141
142     AudioSession *session;
143     AudioSessionWrapper *session_wrapper;
144
145     struct list entry;
146
147     struct list avail_buffers;
148     struct list queued_bufinfos;
149
150     /* We can't use debug printing or {Enter,Leave}CriticalSection from
151      * OSX callback threads, so we use OSX's OSSpinLock for synchronization
152      * instead. OSSpinLock is not a recursive lock, so don't call
153      * synchronized functions while holding the lock. */
154     OSSpinLock lock;
155 };
156
157 enum PlayingStates {
158     StateStopped = 0,
159     StatePlaying,
160     StateInTransition
161 };
162
163 static const IAudioClientVtbl AudioClient_Vtbl;
164 static const IAudioRenderClientVtbl AudioRenderClient_Vtbl;
165 static const IAudioCaptureClientVtbl AudioCaptureClient_Vtbl;
166 static const IAudioSessionControl2Vtbl AudioSessionControl2_Vtbl;
167 static const ISimpleAudioVolumeVtbl SimpleAudioVolume_Vtbl;
168 static const IAudioClockVtbl AudioClock_Vtbl;
169 static const IAudioClock2Vtbl AudioClock2_Vtbl;
170 static const IAudioStreamVolumeVtbl AudioStreamVolume_Vtbl;
171 static const IChannelAudioVolumeVtbl ChannelAudioVolume_Vtbl;
172 static const IAudioSessionManager2Vtbl AudioSessionManager2_Vtbl;
173
174 typedef struct _SessionMgr {
175     IAudioSessionManager2 IAudioSessionManager2_iface;
176
177     LONG ref;
178
179     IMMDevice *device;
180 } SessionMgr;
181
182 static HANDLE g_timer_q;
183
184 static CRITICAL_SECTION g_sessions_lock;
185 static CRITICAL_SECTION_DEBUG g_sessions_lock_debug =
186 {
187     0, 0, &g_sessions_lock,
188     { &g_sessions_lock_debug.ProcessLocksList, &g_sessions_lock_debug.ProcessLocksList },
189       0, 0, { (DWORD_PTR)(__FILE__ ": g_sessions_lock") }
190 };
191 static CRITICAL_SECTION g_sessions_lock = { &g_sessions_lock_debug, -1, 0, 0, 0, 0 };
192 static struct list g_sessions = LIST_INIT(g_sessions);
193
194 static HRESULT AudioClock_GetPosition_nolock(ACImpl *This, UINT64 *pos,
195         UINT64 *qpctime);
196 static AudioSessionWrapper *AudioSessionWrapper_Create(ACImpl *client);
197 static HRESULT ca_setvol(ACImpl *This, UINT32 index);
198
199 static inline ACImpl *impl_from_IAudioClient(IAudioClient *iface)
200 {
201     return CONTAINING_RECORD(iface, ACImpl, IAudioClient_iface);
202 }
203
204 static inline ACImpl *impl_from_IAudioRenderClient(IAudioRenderClient *iface)
205 {
206     return CONTAINING_RECORD(iface, ACImpl, IAudioRenderClient_iface);
207 }
208
209 static inline ACImpl *impl_from_IAudioCaptureClient(IAudioCaptureClient *iface)
210 {
211     return CONTAINING_RECORD(iface, ACImpl, IAudioCaptureClient_iface);
212 }
213
214 static inline AudioSessionWrapper *impl_from_IAudioSessionControl2(IAudioSessionControl2 *iface)
215 {
216     return CONTAINING_RECORD(iface, AudioSessionWrapper, IAudioSessionControl2_iface);
217 }
218
219 static inline AudioSessionWrapper *impl_from_ISimpleAudioVolume(ISimpleAudioVolume *iface)
220 {
221     return CONTAINING_RECORD(iface, AudioSessionWrapper, ISimpleAudioVolume_iface);
222 }
223
224 static inline AudioSessionWrapper *impl_from_IChannelAudioVolume(IChannelAudioVolume *iface)
225 {
226     return CONTAINING_RECORD(iface, AudioSessionWrapper, IChannelAudioVolume_iface);
227 }
228
229 static inline ACImpl *impl_from_IAudioClock(IAudioClock *iface)
230 {
231     return CONTAINING_RECORD(iface, ACImpl, IAudioClock_iface);
232 }
233
234 static inline ACImpl *impl_from_IAudioClock2(IAudioClock2 *iface)
235 {
236     return CONTAINING_RECORD(iface, ACImpl, IAudioClock2_iface);
237 }
238
239 static inline ACImpl *impl_from_IAudioStreamVolume(IAudioStreamVolume *iface)
240 {
241     return CONTAINING_RECORD(iface, ACImpl, IAudioStreamVolume_iface);
242 }
243
244 static inline SessionMgr *impl_from_IAudioSessionManager2(IAudioSessionManager2 *iface)
245 {
246     return CONTAINING_RECORD(iface, SessionMgr, IAudioSessionManager2_iface);
247 }
248
249 BOOL WINAPI DllMain(HINSTANCE dll, DWORD reason, void *reserved)
250 {
251     switch (reason)
252     {
253     case DLL_PROCESS_ATTACH:
254         g_timer_q = CreateTimerQueue();
255         if(!g_timer_q)
256             return FALSE;
257         break;
258
259     case DLL_PROCESS_DETACH:
260         DeleteCriticalSection(&g_sessions_lock);
261         break;
262     }
263     return TRUE;
264 }
265
266 /* From <dlls/mmdevapi/mmdevapi.h> */
267 enum DriverPriority {
268     Priority_Unavailable = 0,
269     Priority_Low,
270     Priority_Neutral,
271     Priority_Preferred
272 };
273
274 int WINAPI AUDDRV_GetPriority(void)
275 {
276     return Priority_Neutral;
277 }
278
279 HRESULT WINAPI AUDDRV_GetEndpointIDs(EDataFlow flow, WCHAR ***ids,
280         AudioDeviceID ***keys, UINT *num, UINT *def_index)
281 {
282     UInt32 devsize, size;
283     AudioDeviceID *devices;
284     AudioDeviceID default_id;
285     AudioObjectPropertyAddress addr;
286     OSStatus sc;
287     int i, ndevices;
288
289     TRACE("%d %p %p %p\n", flow, ids, num, def_index);
290
291     addr.mScope = kAudioObjectPropertyScopeGlobal;
292     addr.mElement = kAudioObjectPropertyElementMaster;
293     if(flow == eRender)
294         addr.mSelector = kAudioHardwarePropertyDefaultOutputDevice;
295     else if(flow == eCapture)
296         addr.mSelector = kAudioHardwarePropertyDefaultInputDevice;
297     else
298         return E_INVALIDARG;
299
300     size = sizeof(default_id);
301     sc = AudioObjectGetPropertyData(kAudioObjectSystemObject, &addr, 0,
302             NULL, &size, &default_id);
303     if(sc != noErr){
304         WARN("Getting _DefaultInputDevice property failed: %lx\n", sc);
305         default_id = -1;
306     }
307
308     addr.mSelector = kAudioHardwarePropertyDevices;
309     sc = AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &addr, 0,
310             NULL, &devsize);
311     if(sc != noErr){
312         WARN("Getting _Devices property size failed: %lx\n", sc);
313         return E_FAIL;
314     }
315
316     devices = HeapAlloc(GetProcessHeap(), 0, devsize);
317     if(!devices)
318         return E_OUTOFMEMORY;
319
320     sc = AudioObjectGetPropertyData(kAudioObjectSystemObject, &addr, 0, NULL,
321             &devsize, devices);
322     if(sc != noErr){
323         WARN("Getting _Devices property failed: %lx\n", sc);
324         HeapFree(GetProcessHeap(), 0, devices);
325         return E_FAIL;
326     }
327
328     ndevices = devsize / sizeof(AudioDeviceID);
329
330     *ids = HeapAlloc(GetProcessHeap(), 0, ndevices * sizeof(WCHAR *));
331     if(!*ids){
332         HeapFree(GetProcessHeap(), 0, devices);
333         return E_OUTOFMEMORY;
334     }
335
336     *keys = HeapAlloc(GetProcessHeap(), 0, ndevices * sizeof(AudioDeviceID *));
337     if(!*ids){
338         HeapFree(GetProcessHeap(), 0, *ids);
339         HeapFree(GetProcessHeap(), 0, devices);
340         return E_OUTOFMEMORY;
341     }
342
343     *num = 0;
344     *def_index = (UINT)-1;
345     for(i = 0; i < ndevices; ++i){
346         AudioBufferList *buffers;
347         CFStringRef name;
348         SIZE_T len;
349         int j;
350
351         addr.mSelector = kAudioDevicePropertyStreamConfiguration;
352         if(flow == eRender)
353             addr.mScope = kAudioDevicePropertyScopeOutput;
354         else
355             addr.mScope = kAudioDevicePropertyScopeInput;
356         addr.mElement = 0;
357         sc = AudioObjectGetPropertyDataSize(devices[i], &addr, 0, NULL, &size);
358         if(sc != noErr){
359             WARN("Unable to get _StreamConfiguration property size for "
360                     "device %lu: %lx\n", devices[i], sc);
361             continue;
362         }
363
364         buffers = HeapAlloc(GetProcessHeap(), 0, size);
365         if(!buffers){
366             HeapFree(GetProcessHeap(), 0, devices);
367             for(j = 0; j < *num; ++j){
368                 HeapFree(GetProcessHeap(), 0, (*ids)[j]);
369                 HeapFree(GetProcessHeap(), 0, (*keys)[j]);
370             }
371             HeapFree(GetProcessHeap(), 0, *keys);
372             HeapFree(GetProcessHeap(), 0, *ids);
373             return E_OUTOFMEMORY;
374         }
375
376         sc = AudioObjectGetPropertyData(devices[i], &addr, 0, NULL,
377                 &size, buffers);
378         if(sc != noErr){
379             WARN("Unable to get _StreamConfiguration property for "
380                     "device %lu: %lx\n", devices[i], sc);
381             HeapFree(GetProcessHeap(), 0, buffers);
382             continue;
383         }
384
385         /* check that there's at least one channel in this device before
386          * we claim it as usable */
387         for(j = 0; j < buffers->mNumberBuffers; ++j)
388             if(buffers->mBuffers[j].mNumberChannels > 0)
389                 break;
390         if(j >= buffers->mNumberBuffers){
391             HeapFree(GetProcessHeap(), 0, buffers);
392             continue;
393         }
394
395         HeapFree(GetProcessHeap(), 0, buffers);
396
397         size = sizeof(name);
398         addr.mSelector = kAudioObjectPropertyName;
399         sc = AudioObjectGetPropertyData(devices[i], &addr, 0, NULL,
400                 &size, &name);
401         if(sc != noErr){
402             WARN("Unable to get _Name property for device %lu: %lx\n",
403                     devices[i], sc);
404             continue;
405         }
406
407         len = CFStringGetLength(name) + 1;
408         (*ids)[*num] = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
409         if(!(*ids)[*num]){
410             CFRelease(name);
411             HeapFree(GetProcessHeap(), 0, devices);
412             for(j = 0; j < *num; ++j){
413                 HeapFree(GetProcessHeap(), 0, (*ids)[j]);
414                 HeapFree(GetProcessHeap(), 0, (*keys)[j]);
415             }
416             HeapFree(GetProcessHeap(), 0, *ids);
417             HeapFree(GetProcessHeap(), 0, *keys);
418             return E_OUTOFMEMORY;
419         }
420         CFStringGetCharacters(name, CFRangeMake(0, len - 1), (UniChar*)(*ids)[*num]);
421         ((*ids)[*num])[len - 1] = 0;
422         CFRelease(name);
423
424         (*keys)[*num] = HeapAlloc(GetProcessHeap(), 0, sizeof(AudioDeviceID));
425         if(!(*keys)[*num]){
426             HeapFree(GetProcessHeap(), 0, devices);
427             HeapFree(GetProcessHeap(), 0, (*ids)[*num]);
428             for(j = 0; j < *num; ++j){
429                 HeapFree(GetProcessHeap(), 0, (*ids)[j]);
430                 HeapFree(GetProcessHeap(), 0, (*keys)[j]);
431             }
432             HeapFree(GetProcessHeap(), 0, *ids);
433             HeapFree(GetProcessHeap(), 0, *keys);
434             return E_OUTOFMEMORY;
435         }
436         *(*keys)[*num] = devices[i];
437
438         if(*def_index == (UINT)-1 && devices[i] == default_id)
439             *def_index = *num;
440
441         TRACE("device %u: id %s key %u%s\n", *num, debugstr_w((*ids)[*num]),
442               (unsigned int)*(*keys)[*num], (*def_index == *num) ? " (default)" : "");
443
444         (*num)++;
445     }
446
447     if(*def_index == (UINT)-1)
448         *def_index = 0;
449
450     HeapFree(GetProcessHeap(), 0, devices);
451
452     return S_OK;
453 }
454
455 HRESULT WINAPI AUDDRV_GetAudioEndpoint(AudioDeviceID *adevid, IMMDevice *dev,
456         EDataFlow dataflow, IAudioClient **out)
457 {
458     ACImpl *This;
459
460     TRACE("%u %p %d %p\n", (unsigned int)*adevid, dev, dataflow, out);
461
462     This = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(ACImpl));
463     if(!This)
464         return E_OUTOFMEMORY;
465
466     This->IAudioClient_iface.lpVtbl = &AudioClient_Vtbl;
467     This->IAudioRenderClient_iface.lpVtbl = &AudioRenderClient_Vtbl;
468     This->IAudioCaptureClient_iface.lpVtbl = &AudioCaptureClient_Vtbl;
469     This->IAudioClock_iface.lpVtbl = &AudioClock_Vtbl;
470     This->IAudioClock2_iface.lpVtbl = &AudioClock2_Vtbl;
471     This->IAudioStreamVolume_iface.lpVtbl = &AudioStreamVolume_Vtbl;
472
473     This->dataflow = dataflow;
474
475     if(dataflow == eRender)
476         This->scope = kAudioDevicePropertyScopeOutput;
477     else if(dataflow == eCapture)
478         This->scope = kAudioDevicePropertyScopeInput;
479     else{
480         HeapFree(GetProcessHeap(), 0, This);
481         return E_INVALIDARG;
482     }
483
484     This->lock = 0;
485
486     This->parent = dev;
487     IMMDevice_AddRef(This->parent);
488
489     list_init(&This->avail_buffers);
490     list_init(&This->queued_bufinfos);
491
492     This->adevid = *adevid;
493
494     *out = &This->IAudioClient_iface;
495     IAudioClient_AddRef(&This->IAudioClient_iface);
496
497     return S_OK;
498 }
499
500 /* current position from start of stream */
501 #define BUFPOS_ABSOLUTE 1
502 /* current position from start of this buffer */
503 #define BUFPOS_RELATIVE 2
504
505 static UINT64 get_current_aqbuffer_position(ACImpl *This, int mode)
506 {
507     struct list *head;
508     QueuedBufInfo *bufinfo;
509     UINT64 ret;
510
511     head = list_head(&This->queued_bufinfos);
512     if(!head){
513         TRACE("No buffers queued\n");
514         if(mode == BUFPOS_ABSOLUTE)
515             return This->written_frames;
516         return 0;
517     }
518     bufinfo = LIST_ENTRY(head, QueuedBufInfo, entry);
519
520     if(This->playing == StatePlaying){
521         AudioTimeStamp tstamp;
522         OSStatus sc;
523
524         /* AudioQueueGetCurrentTime() is brain damaged. The returned
525          * mSampleTime member jumps backwards seemingly at random, so
526          * we record the highest sampletime and use that during these
527          * anomalies.
528          *
529          * It also behaves poorly when the queue is paused, jumping
530          * forwards during the pause and backwards again after resuming.
531          * So we record the sampletime when the queue is paused and use
532          * that. */
533         sc = AudioQueueGetCurrentTime(This->aqueue, NULL, &tstamp, NULL);
534         if(sc != noErr){
535             if(sc != kAudioQueueErr_InvalidRunState)
536                 WARN("Unable to get current time: %lx\n", sc);
537             return 0;
538         }
539
540         if(!(tstamp.mFlags & kAudioTimeStampSampleTimeValid)){
541             FIXME("SampleTime not valid: %lx\n", tstamp.mFlags);
542             return 0;
543         }
544
545         if(tstamp.mSampleTime > This->highest_sampletime)
546             This->highest_sampletime = tstamp.mSampleTime;
547     }
548
549     while(This->highest_sampletime > bufinfo->start_sampletime + bufinfo->len_frames){
550         This->inbuf_frames -= bufinfo->len_frames;
551         list_remove(&bufinfo->entry);
552         HeapFree(GetProcessHeap(), 0, bufinfo);
553
554         head = list_head(&This->queued_bufinfos);
555         if(!head){
556             TRACE("No buffers queued\n");
557             if(mode == BUFPOS_ABSOLUTE)
558                 return This->written_frames;
559             return 0;
560         }
561         bufinfo = LIST_ENTRY(head, QueuedBufInfo, entry);
562     }
563
564     if(This->highest_sampletime < bufinfo->start_sampletime)
565         ret = 0;
566     else
567         ret = This->highest_sampletime - bufinfo->start_sampletime;
568
569     if(mode == BUFPOS_ABSOLUTE)
570         ret += bufinfo->start_pos;
571
572     TRACE("%llu frames (%s)\n", ret,
573             mode == BUFPOS_ABSOLUTE ? "absolute" : "relative");
574
575     return ret;
576 }
577
578 static HRESULT WINAPI AudioClient_QueryInterface(IAudioClient *iface,
579         REFIID riid, void **ppv)
580 {
581     TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
582
583     if(!ppv)
584         return E_POINTER;
585     *ppv = NULL;
586     if(IsEqualIID(riid, &IID_IUnknown) || IsEqualIID(riid, &IID_IAudioClient))
587         *ppv = iface;
588     if(*ppv){
589         IUnknown_AddRef((IUnknown*)*ppv);
590         return S_OK;
591     }
592     WARN("Unknown interface %s\n", debugstr_guid(riid));
593     return E_NOINTERFACE;
594 }
595
596 static ULONG WINAPI AudioClient_AddRef(IAudioClient *iface)
597 {
598     ACImpl *This = impl_from_IAudioClient(iface);
599     ULONG ref;
600     ref = InterlockedIncrement(&This->ref);
601     TRACE("(%p) Refcount now %u\n", This, ref);
602     return ref;
603 }
604
605 static ULONG WINAPI AudioClient_Release(IAudioClient *iface)
606 {
607     ACImpl *This = impl_from_IAudioClient(iface);
608     ULONG ref;
609     ref = InterlockedDecrement(&This->ref);
610     TRACE("(%p) Refcount now %u\n", This, ref);
611     if(!ref){
612         if(This->aqueue){
613             AQBuffer *buf, *next;
614             QueuedBufInfo *bufinfo, *bufinfo2;
615
616             if(This->public_buffer){
617                 buf = This->public_buffer->mUserData;
618                 list_add_tail(&This->avail_buffers, &buf->entry);
619             }
620
621             IAudioClient_Stop(iface);
622             AudioQueueStop(This->aqueue, 1);
623
624             /* Stopped synchronously, all buffers returned. */
625             LIST_FOR_EACH_ENTRY_SAFE(buf, next, &This->avail_buffers, AQBuffer, entry){
626                 AudioQueueFreeBuffer(This->aqueue, buf->buf);
627                 HeapFree(GetProcessHeap(), 0, buf);
628             }
629
630             LIST_FOR_EACH_ENTRY_SAFE(bufinfo, bufinfo2, &This->queued_bufinfos,
631                     QueuedBufInfo, entry)
632                 HeapFree(GetProcessHeap(), 0, bufinfo);
633
634             AudioQueueDispose(This->aqueue, 1);
635         }
636         if(This->session){
637             EnterCriticalSection(&g_sessions_lock);
638             list_remove(&This->entry);
639             LeaveCriticalSection(&g_sessions_lock);
640         }
641         HeapFree(GetProcessHeap(), 0, This->vols);
642         CoTaskMemFree(This->fmt);
643         IMMDevice_Release(This->parent);
644         HeapFree(GetProcessHeap(), 0, This);
645     }
646     return ref;
647 }
648
649 static void dump_fmt(const WAVEFORMATEX *fmt)
650 {
651     TRACE("wFormatTag: 0x%x (", fmt->wFormatTag);
652     switch(fmt->wFormatTag){
653     case WAVE_FORMAT_PCM:
654         TRACE("WAVE_FORMAT_PCM");
655         break;
656     case WAVE_FORMAT_IEEE_FLOAT:
657         TRACE("WAVE_FORMAT_IEEE_FLOAT");
658         break;
659     case WAVE_FORMAT_EXTENSIBLE:
660         TRACE("WAVE_FORMAT_EXTENSIBLE");
661         break;
662     default:
663         TRACE("Unknown");
664         break;
665     }
666     TRACE(")\n");
667
668     TRACE("nChannels: %u\n", fmt->nChannels);
669     TRACE("nSamplesPerSec: %u\n", fmt->nSamplesPerSec);
670     TRACE("nAvgBytesPerSec: %u\n", fmt->nAvgBytesPerSec);
671     TRACE("nBlockAlign: %u\n", fmt->nBlockAlign);
672     TRACE("wBitsPerSample: %u\n", fmt->wBitsPerSample);
673     TRACE("cbSize: %u\n", fmt->cbSize);
674
675     if(fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE){
676         WAVEFORMATEXTENSIBLE *fmtex = (void*)fmt;
677         TRACE("dwChannelMask: %08x\n", fmtex->dwChannelMask);
678         TRACE("Samples: %04x\n", fmtex->Samples.wReserved);
679         TRACE("SubFormat: %s\n", wine_dbgstr_guid(&fmtex->SubFormat));
680     }
681 }
682
683 static DWORD get_channel_mask(unsigned int channels)
684 {
685     switch(channels){
686     case 0:
687         return 0;
688     case 1:
689         return KSAUDIO_SPEAKER_MONO;
690     case 2:
691         return KSAUDIO_SPEAKER_STEREO;
692     case 3:
693         return KSAUDIO_SPEAKER_STEREO | SPEAKER_LOW_FREQUENCY;
694     case 4:
695         return KSAUDIO_SPEAKER_QUAD;    /* not _SURROUND */
696     case 5:
697         return KSAUDIO_SPEAKER_QUAD | SPEAKER_LOW_FREQUENCY;
698     case 6:
699         return KSAUDIO_SPEAKER_5POINT1; /* not 5POINT1_SURROUND */
700     case 7:
701         return KSAUDIO_SPEAKER_5POINT1 | SPEAKER_BACK_CENTER;
702     case 8:
703         return KSAUDIO_SPEAKER_7POINT1; /* not 7POINT1_SURROUND */
704     }
705     FIXME("Unknown speaker configuration: %u\n", channels);
706     return 0;
707 }
708
709 static WAVEFORMATEX *clone_format(const WAVEFORMATEX *fmt)
710 {
711     WAVEFORMATEX *ret;
712     size_t size;
713
714     if(fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE)
715         size = sizeof(WAVEFORMATEXTENSIBLE);
716     else
717         size = sizeof(WAVEFORMATEX);
718
719     ret = CoTaskMemAlloc(size);
720     if(!ret)
721         return NULL;
722
723     memcpy(ret, fmt, size);
724
725     ret->cbSize = size - sizeof(WAVEFORMATEX);
726
727     return ret;
728 }
729
730 static HRESULT ca_get_audiodesc(AudioStreamBasicDescription *desc,
731         const WAVEFORMATEX *fmt)
732 {
733     const WAVEFORMATEXTENSIBLE *fmtex = (const WAVEFORMATEXTENSIBLE *)fmt;
734
735     desc->mFormatFlags = 0;
736
737     if(fmt->wFormatTag == WAVE_FORMAT_PCM ||
738             (fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
739              IsEqualGUID(&fmtex->SubFormat, &KSDATAFORMAT_SUBTYPE_PCM))){
740         desc->mFormatID = kAudioFormatLinearPCM;
741         if(fmt->wBitsPerSample > 8)
742             desc->mFormatFlags = kAudioFormatFlagIsSignedInteger;
743     }else if(fmt->wFormatTag == WAVE_FORMAT_IEEE_FLOAT ||
744             (fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
745              IsEqualGUID(&fmtex->SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))){
746         desc->mFormatID = kAudioFormatLinearPCM;
747         desc->mFormatFlags = kAudioFormatFlagIsFloat;
748     }else if(fmt->wFormatTag == WAVE_FORMAT_MULAW ||
749             (fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
750              IsEqualGUID(&fmtex->SubFormat, &KSDATAFORMAT_SUBTYPE_MULAW))){
751         desc->mFormatID = kAudioFormatULaw;
752     }else if(fmt->wFormatTag == WAVE_FORMAT_ALAW ||
753             (fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
754              IsEqualGUID(&fmtex->SubFormat, &KSDATAFORMAT_SUBTYPE_ALAW))){
755         desc->mFormatID = kAudioFormatALaw;
756     }else
757         return AUDCLNT_E_UNSUPPORTED_FORMAT;
758
759     desc->mSampleRate = fmt->nSamplesPerSec;
760     desc->mBytesPerPacket = fmt->nBlockAlign;
761     desc->mFramesPerPacket = 1;
762     desc->mBytesPerFrame = fmt->nBlockAlign;
763     desc->mChannelsPerFrame = fmt->nChannels;
764     desc->mBitsPerChannel = fmt->wBitsPerSample;
765     desc->mReserved = 0;
766
767     return S_OK;
768 }
769
770 static void ca_out_buffer_cb(void *user, AudioQueueRef aqueue,
771         AudioQueueBufferRef buffer)
772 {
773     ACImpl *This = user;
774     AQBuffer *buf = buffer->mUserData;
775
776     OSSpinLockLock(&This->lock);
777     list_add_tail(&This->avail_buffers, &buf->entry);
778     OSSpinLockUnlock(&This->lock);
779 }
780
781 static void ca_in_buffer_cb(void *user, AudioQueueRef aqueue,
782         AudioQueueBufferRef buffer, const AudioTimeStamp *start,
783         UInt32 ndesc, const AudioStreamPacketDescription *descs)
784 {
785     ACImpl *This = user;
786     AQBuffer *buf = buffer->mUserData;
787
788     OSSpinLockLock(&This->lock);
789     list_add_tail(&This->avail_buffers, &buf->entry);
790     This->inbuf_frames += buffer->mAudioDataByteSize / This->fmt->nBlockAlign;
791     OSSpinLockUnlock(&This->lock);
792 }
793
794 static HRESULT ca_setup_aqueue(AudioDeviceID did, EDataFlow flow,
795         const WAVEFORMATEX *fmt, void *user, AudioQueueRef *aqueue)
796 {
797     AudioStreamBasicDescription desc;
798     AudioObjectPropertyAddress addr;
799     CFStringRef uid;
800     OSStatus sc;
801     HRESULT hr;
802     UInt32 size;
803
804     addr.mScope = kAudioObjectPropertyScopeGlobal;
805     addr.mElement = 0;
806     addr.mSelector = kAudioDevicePropertyDeviceUID;
807
808     size = sizeof(uid);
809     sc = AudioObjectGetPropertyData(did, &addr, 0, NULL, &size, &uid);
810     if(sc != noErr){
811         WARN("Unable to get _DeviceUID property: %lx\n", sc);
812         return E_FAIL;
813     }
814
815     hr = ca_get_audiodesc(&desc, fmt);
816     if(FAILED(hr)){
817         CFRelease(uid);
818         return hr;
819     }
820
821     if(flow == eRender)
822         sc = AudioQueueNewOutput(&desc, ca_out_buffer_cb, user, NULL, NULL, 0,
823                 aqueue);
824     else if(flow == eCapture)
825         sc = AudioQueueNewInput(&desc, ca_in_buffer_cb, user, NULL, NULL, 0,
826                 aqueue);
827     else{
828         CFRelease(uid);
829         return E_UNEXPECTED;
830     }
831     if(sc != noErr){
832         WARN("Unable to create AudioQueue: %lx\n", sc);
833         CFRelease(uid);
834         return E_FAIL;
835     }
836
837     sc = AudioQueueSetProperty(*aqueue, kAudioQueueProperty_CurrentDevice,
838             &uid, sizeof(uid));
839     if(sc != noErr){
840         CFRelease(uid);
841         return E_FAIL;
842     }
843
844     CFRelease(uid);
845
846     return S_OK;
847 }
848
849 static void session_init_vols(AudioSession *session, UINT channels)
850 {
851     if(session->channel_count < channels){
852         UINT i;
853
854         if(session->channel_vols)
855             session->channel_vols = HeapReAlloc(GetProcessHeap(), 0,
856                     session->channel_vols, sizeof(float) * channels);
857         else
858             session->channel_vols = HeapAlloc(GetProcessHeap(), 0,
859                     sizeof(float) * channels);
860         if(!session->channel_vols)
861             return;
862
863         for(i = session->channel_count; i < channels; ++i)
864             session->channel_vols[i] = 1.f;
865
866         session->channel_count = channels;
867     }
868 }
869
870 static AudioSession *create_session(const GUID *guid, IMMDevice *device,
871         UINT num_channels)
872 {
873     AudioSession *ret;
874
875     ret = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(AudioSession));
876     if(!ret)
877         return NULL;
878
879     memcpy(&ret->guid, guid, sizeof(GUID));
880
881     ret->device = device;
882
883     list_init(&ret->clients);
884
885     list_add_head(&g_sessions, &ret->entry);
886
887     InitializeCriticalSection(&ret->lock);
888     ret->lock.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": AudioSession.lock");
889
890     session_init_vols(ret, num_channels);
891
892     ret->master_vol = 1.f;
893
894     return ret;
895 }
896
897 /* if channels == 0, then this will return or create a session with
898  * matching dataflow and GUID. otherwise, channels must also match */
899 static HRESULT get_audio_session(const GUID *sessionguid,
900         IMMDevice *device, UINT channels, AudioSession **out)
901 {
902     AudioSession *session;
903
904     if(!sessionguid || IsEqualGUID(sessionguid, &GUID_NULL)){
905         *out = create_session(&GUID_NULL, device, channels);
906         if(!*out)
907             return E_OUTOFMEMORY;
908
909         return S_OK;
910     }
911
912     *out = NULL;
913     LIST_FOR_EACH_ENTRY(session, &g_sessions, AudioSession, entry){
914         if(session->device == device &&
915                 IsEqualGUID(sessionguid, &session->guid)){
916             session_init_vols(session, channels);
917             *out = session;
918             break;
919         }
920     }
921
922     if(!*out){
923         *out = create_session(sessionguid, device, channels);
924         if(!*out)
925             return E_OUTOFMEMORY;
926     }
927
928     return S_OK;
929 }
930
931 static HRESULT WINAPI AudioClient_Initialize(IAudioClient *iface,
932         AUDCLNT_SHAREMODE mode, DWORD flags, REFERENCE_TIME duration,
933         REFERENCE_TIME period, const WAVEFORMATEX *fmt,
934         const GUID *sessionguid)
935 {
936     ACImpl *This = impl_from_IAudioClient(iface);
937     HRESULT hr;
938     OSStatus sc;
939     int i;
940
941     TRACE("(%p)->(%x, %x, %s, %s, %p, %s)\n", This, mode, flags,
942           wine_dbgstr_longlong(duration), wine_dbgstr_longlong(period), fmt, debugstr_guid(sessionguid));
943
944     if(!fmt)
945         return E_POINTER;
946
947     dump_fmt(fmt);
948
949     if(mode != AUDCLNT_SHAREMODE_SHARED && mode != AUDCLNT_SHAREMODE_EXCLUSIVE)
950         return AUDCLNT_E_NOT_INITIALIZED;
951
952     if(flags & ~(AUDCLNT_STREAMFLAGS_CROSSPROCESS |
953                 AUDCLNT_STREAMFLAGS_LOOPBACK |
954                 AUDCLNT_STREAMFLAGS_EVENTCALLBACK |
955                 AUDCLNT_STREAMFLAGS_NOPERSIST |
956                 AUDCLNT_STREAMFLAGS_RATEADJUST |
957                 AUDCLNT_SESSIONFLAGS_EXPIREWHENUNOWNED |
958                 AUDCLNT_SESSIONFLAGS_DISPLAY_HIDE |
959                 AUDCLNT_SESSIONFLAGS_DISPLAY_HIDEWHENEXPIRED)){
960         TRACE("Unknown flags: %08x\n", flags);
961         return E_INVALIDARG;
962     }
963
964     if(mode == AUDCLNT_SHAREMODE_SHARED){
965         period = DefaultPeriod;
966         if( duration < 3 * period)
967             duration = 3 * period;
968     }else{
969         if(!period)
970             period = DefaultPeriod; /* not minimum */
971         if(period < MinimumPeriod || period > 5000000)
972             return AUDCLNT_E_INVALID_DEVICE_PERIOD;
973         if(duration > 20000000) /* the smaller the period, the lower this limit */
974             return AUDCLNT_E_BUFFER_SIZE_ERROR;
975         if(flags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK){
976             if(duration != period)
977                 return AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL;
978             FIXME("EXCLUSIVE mode with EVENTCALLBACK\n");
979             return AUDCLNT_E_DEVICE_IN_USE;
980         }else{
981             if( duration < 8 * period)
982                 duration = 8 * period; /* may grow above 2s */
983         }
984     }
985
986     OSSpinLockLock(&This->lock);
987
988     if(This->aqueue){
989         OSSpinLockUnlock(&This->lock);
990         return AUDCLNT_E_ALREADY_INITIALIZED;
991     }
992
993     hr = ca_setup_aqueue(This->adevid, This->dataflow, fmt, This, &This->aqueue);
994     if(FAILED(hr)){
995         OSSpinLockUnlock(&This->lock);
996         return hr;
997     }
998
999     This->fmt = clone_format(fmt);
1000     if(!This->fmt){
1001         AudioQueueDispose(This->aqueue, 1);
1002         This->aqueue = NULL;
1003         OSSpinLockUnlock(&This->lock);
1004         return E_OUTOFMEMORY;
1005     }
1006
1007     This->period_ms = period / 10000;
1008
1009     This->bufsize_frames = ceil(fmt->nSamplesPerSec * (duration / 10000000.));
1010
1011     if(This->dataflow == eCapture){
1012         int i;
1013         UInt32 bsize = ceil((This->bufsize_frames / (double)CAPTURE_BUFFERS) *
1014                 This->fmt->nBlockAlign);
1015         for(i = 0; i < CAPTURE_BUFFERS; ++i){
1016             AQBuffer *buf;
1017
1018             buf = HeapAlloc(GetProcessHeap(), 0, sizeof(AQBuffer));
1019             if(!buf){
1020                 AudioQueueDispose(This->aqueue, 1);
1021                 This->aqueue = NULL;
1022                 CoTaskMemFree(This->fmt);
1023                 This->fmt = NULL;
1024                 OSSpinLockUnlock(&This->lock);
1025                 return E_OUTOFMEMORY;
1026             }
1027
1028             sc = AudioQueueAllocateBuffer(This->aqueue, bsize, &buf->buf);
1029             if(sc != noErr){
1030                 AudioQueueDispose(This->aqueue, 1);
1031                 This->aqueue = NULL;
1032                 CoTaskMemFree(This->fmt);
1033                 This->fmt = NULL;
1034                 OSSpinLockUnlock(&This->lock);
1035                 WARN("Couldn't allocate buffer: %lx\n", sc);
1036                 return E_FAIL;
1037             }
1038
1039             buf->buf->mUserData = buf;
1040
1041             sc = AudioQueueEnqueueBuffer(This->aqueue, buf->buf, 0, NULL);
1042             if(sc != noErr){
1043                 ERR("Couldn't enqueue buffer: %lx\n", sc);
1044                 break;
1045             }
1046         }
1047     }
1048
1049     This->vols = HeapAlloc(GetProcessHeap(), 0, fmt->nChannels * sizeof(float));
1050     if(!This->vols){
1051         AudioQueueDispose(This->aqueue, 1);
1052         This->aqueue = NULL;
1053         CoTaskMemFree(This->fmt);
1054         This->fmt = NULL;
1055         OSSpinLockUnlock(&This->lock);
1056         return E_OUTOFMEMORY;
1057     }
1058
1059     for(i = 0; i < fmt->nChannels; ++i)
1060         This->vols[i] = 1.f;
1061
1062     This->share = mode;
1063     This->flags = flags;
1064
1065     EnterCriticalSection(&g_sessions_lock);
1066
1067     hr = get_audio_session(sessionguid, This->parent, fmt->nChannels,
1068             &This->session);
1069     if(FAILED(hr)){
1070         LeaveCriticalSection(&g_sessions_lock);
1071         AudioQueueDispose(This->aqueue, 1);
1072         This->aqueue = NULL;
1073         CoTaskMemFree(This->fmt);
1074         This->fmt = NULL;
1075         HeapFree(GetProcessHeap(), 0, This->vols);
1076         This->vols = NULL;
1077         OSSpinLockUnlock(&This->lock);
1078         return E_INVALIDARG;
1079     }
1080
1081     list_add_tail(&This->session->clients, &This->entry);
1082
1083     LeaveCriticalSection(&g_sessions_lock);
1084
1085     ca_setvol(This, -1);
1086
1087     OSSpinLockUnlock(&This->lock);
1088
1089     return S_OK;
1090 }
1091
1092 static HRESULT WINAPI AudioClient_GetBufferSize(IAudioClient *iface,
1093         UINT32 *frames)
1094 {
1095     ACImpl *This = impl_from_IAudioClient(iface);
1096
1097     TRACE("(%p)->(%p)\n", This, frames);
1098
1099     if(!frames)
1100         return E_POINTER;
1101
1102     OSSpinLockLock(&This->lock);
1103
1104     if(!This->aqueue){
1105         OSSpinLockUnlock(&This->lock);
1106         return AUDCLNT_E_NOT_INITIALIZED;
1107     }
1108
1109     *frames = This->bufsize_frames;
1110
1111     OSSpinLockUnlock(&This->lock);
1112
1113     return S_OK;
1114 }
1115
1116 static HRESULT ca_get_max_stream_latency(ACImpl *This, UInt32 *max)
1117 {
1118     AudioObjectPropertyAddress addr;
1119     AudioStreamID *ids;
1120     UInt32 size;
1121     OSStatus sc;
1122     int nstreams, i;
1123
1124     addr.mScope = This->scope;
1125     addr.mElement = 0;
1126     addr.mSelector = kAudioDevicePropertyStreams;
1127
1128     sc = AudioObjectGetPropertyDataSize(This->adevid, &addr, 0, NULL,
1129             &size);
1130     if(sc != noErr){
1131         WARN("Unable to get size for _Streams property: %lx\n", sc);
1132         return E_FAIL;
1133     }
1134
1135     ids = HeapAlloc(GetProcessHeap(), 0, size);
1136     if(!ids)
1137         return E_OUTOFMEMORY;
1138
1139     sc = AudioObjectGetPropertyData(This->adevid, &addr, 0, NULL, &size, ids);
1140     if(sc != noErr){
1141         WARN("Unable to get _Streams property: %lx\n", sc);
1142         HeapFree(GetProcessHeap(), 0, ids);
1143         return E_FAIL;
1144     }
1145
1146     nstreams = size / sizeof(AudioStreamID);
1147     *max = 0;
1148
1149     addr.mSelector = kAudioStreamPropertyLatency;
1150     for(i = 0; i < nstreams; ++i){
1151         UInt32 latency;
1152
1153         size = sizeof(latency);
1154         sc = AudioObjectGetPropertyData(ids[i], &addr, 0, NULL,
1155                 &size, &latency);
1156         if(sc != noErr){
1157             WARN("Unable to get _Latency property: %lx\n", sc);
1158             continue;
1159         }
1160
1161         if(latency > *max)
1162             *max = latency;
1163     }
1164
1165     HeapFree(GetProcessHeap(), 0, ids);
1166
1167     return S_OK;
1168 }
1169
1170 static HRESULT WINAPI AudioClient_GetStreamLatency(IAudioClient *iface,
1171         REFERENCE_TIME *out)
1172 {
1173     ACImpl *This = impl_from_IAudioClient(iface);
1174     UInt32 latency, stream_latency, size;
1175     AudioObjectPropertyAddress addr;
1176     OSStatus sc;
1177     HRESULT hr;
1178
1179     TRACE("(%p)->(%p)\n", This, out);
1180
1181     if(!out)
1182         return E_POINTER;
1183
1184     OSSpinLockLock(&This->lock);
1185
1186     if(!This->aqueue){
1187         OSSpinLockUnlock(&This->lock);
1188         return AUDCLNT_E_NOT_INITIALIZED;
1189     }
1190
1191     addr.mScope = This->scope;
1192     addr.mSelector = kAudioDevicePropertyLatency;
1193     addr.mElement = 0;
1194
1195     size = sizeof(latency);
1196     sc = AudioObjectGetPropertyData(This->adevid, &addr, 0, NULL,
1197             &size, &latency);
1198     if(sc != noErr){
1199         WARN("Couldn't get _Latency property: %lx\n", sc);
1200         OSSpinLockUnlock(&This->lock);
1201         return E_FAIL;
1202     }
1203
1204     hr = ca_get_max_stream_latency(This, &stream_latency);
1205     if(FAILED(hr)){
1206         OSSpinLockUnlock(&This->lock);
1207         return hr;
1208     }
1209
1210     latency += stream_latency;
1211     /* pretend we process audio in Period chunks, so max latency includes
1212      * the period time */
1213     *out = MulDiv(latency, 10000000, This->fmt->nSamplesPerSec)
1214          + This->period_ms * 10000;
1215
1216     OSSpinLockUnlock(&This->lock);
1217
1218     return S_OK;
1219 }
1220
1221 static HRESULT AudioClient_GetCurrentPadding_nolock(ACImpl *This,
1222         UINT32 *numpad)
1223 {
1224     if(!This->aqueue)
1225         return AUDCLNT_E_NOT_INITIALIZED;
1226
1227     if(This->dataflow == eRender){
1228         UINT64 bufpos;
1229         bufpos = get_current_aqbuffer_position(This, BUFPOS_RELATIVE);
1230         *numpad = This->inbuf_frames - bufpos;
1231     }else
1232         *numpad = This->inbuf_frames;
1233
1234     return S_OK;
1235 }
1236
1237 static HRESULT WINAPI AudioClient_GetCurrentPadding(IAudioClient *iface,
1238         UINT32 *numpad)
1239 {
1240     ACImpl *This = impl_from_IAudioClient(iface);
1241     HRESULT hr;
1242
1243     TRACE("(%p)->(%p)\n", This, numpad);
1244
1245     if(!numpad)
1246         return E_POINTER;
1247
1248     OSSpinLockLock(&This->lock);
1249
1250     hr = AudioClient_GetCurrentPadding_nolock(This, numpad);
1251
1252     OSSpinLockUnlock(&This->lock);
1253
1254     return hr;
1255 }
1256
1257 static HRESULT WINAPI AudioClient_IsFormatSupported(IAudioClient *iface,
1258         AUDCLNT_SHAREMODE mode, const WAVEFORMATEX *pwfx,
1259         WAVEFORMATEX **outpwfx)
1260 {
1261     ACImpl *This = impl_from_IAudioClient(iface);
1262     WAVEFORMATEXTENSIBLE *fmtex = (WAVEFORMATEXTENSIBLE*)pwfx;
1263     AudioQueueRef aqueue;
1264     HRESULT hr;
1265
1266     TRACE("(%p)->(%x, %p, %p)\n", This, mode, pwfx, outpwfx);
1267
1268     if(!pwfx || (mode == AUDCLNT_SHAREMODE_SHARED && !outpwfx))
1269         return E_POINTER;
1270
1271     if(mode != AUDCLNT_SHAREMODE_SHARED && mode != AUDCLNT_SHAREMODE_EXCLUSIVE)
1272         return E_INVALIDARG;
1273
1274     if(pwfx->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
1275             pwfx->cbSize < sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX))
1276         return E_INVALIDARG;
1277
1278     dump_fmt(pwfx);
1279
1280     if(outpwfx)
1281         *outpwfx = NULL;
1282
1283     if(pwfx->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
1284             fmtex->dwChannelMask != 0 &&
1285             fmtex->dwChannelMask != get_channel_mask(pwfx->nChannels))
1286         return AUDCLNT_E_UNSUPPORTED_FORMAT;
1287
1288     OSSpinLockLock(&This->lock);
1289
1290     hr = ca_setup_aqueue(This->adevid, This->dataflow, pwfx, NULL, &aqueue);
1291     if(SUCCEEDED(hr)){
1292         AudioQueueDispose(aqueue, 1);
1293         OSSpinLockUnlock(&This->lock);
1294         TRACE("returning %08x\n", S_OK);
1295         return S_OK;
1296     }
1297
1298     OSSpinLockUnlock(&This->lock);
1299
1300     TRACE("returning %08x\n", AUDCLNT_E_UNSUPPORTED_FORMAT);
1301     return AUDCLNT_E_UNSUPPORTED_FORMAT;
1302 }
1303
1304 static HRESULT WINAPI AudioClient_GetMixFormat(IAudioClient *iface,
1305         WAVEFORMATEX **pwfx)
1306 {
1307     ACImpl *This = impl_from_IAudioClient(iface);
1308     WAVEFORMATEXTENSIBLE *fmt;
1309     OSStatus sc;
1310     UInt32 size;
1311     Float64 rate;
1312     AudioBufferList *buffers;
1313     AudioObjectPropertyAddress addr;
1314     int i;
1315
1316     TRACE("(%p)->(%p)\n", This, pwfx);
1317
1318     if(!pwfx)
1319         return E_POINTER;
1320     *pwfx = NULL;
1321
1322     fmt = CoTaskMemAlloc(sizeof(WAVEFORMATEXTENSIBLE));
1323     if(!fmt)
1324         return E_OUTOFMEMORY;
1325
1326     fmt->Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
1327
1328     addr.mScope = This->scope;
1329     addr.mElement = 0;
1330     addr.mSelector = kAudioDevicePropertyStreamConfiguration;
1331
1332     sc = AudioObjectGetPropertyDataSize(This->adevid, &addr, 0, NULL, &size);
1333     if(sc != noErr){
1334         CoTaskMemFree(fmt);
1335         WARN("Unable to get size for _StreamConfiguration property: %lx\n", sc);
1336         return E_FAIL;
1337     }
1338
1339     buffers = HeapAlloc(GetProcessHeap(), 0, size);
1340     if(!buffers){
1341         CoTaskMemFree(fmt);
1342         return E_OUTOFMEMORY;
1343     }
1344
1345     sc = AudioObjectGetPropertyData(This->adevid, &addr, 0, NULL,
1346             &size, buffers);
1347     if(sc != noErr){
1348         CoTaskMemFree(fmt);
1349         HeapFree(GetProcessHeap(), 0, buffers);
1350         WARN("Unable to get _StreamConfiguration property: %lx\n", sc);
1351         return E_FAIL;
1352     }
1353
1354     fmt->Format.nChannels = 0;
1355     for(i = 0; i < buffers->mNumberBuffers; ++i)
1356         fmt->Format.nChannels += buffers->mBuffers[i].mNumberChannels;
1357
1358     HeapFree(GetProcessHeap(), 0, buffers);
1359
1360     fmt->dwChannelMask = get_channel_mask(fmt->Format.nChannels);
1361
1362     addr.mSelector = kAudioDevicePropertyNominalSampleRate;
1363     size = sizeof(Float64);
1364     sc = AudioObjectGetPropertyData(This->adevid, &addr, 0, NULL, &size, &rate);
1365     if(sc != noErr){
1366         CoTaskMemFree(fmt);
1367         WARN("Unable to get _NominalSampleRate property: %lx\n", sc);
1368         return E_FAIL;
1369     }
1370     fmt->Format.nSamplesPerSec = rate;
1371
1372     fmt->Format.wBitsPerSample = 32;
1373     fmt->SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
1374
1375     fmt->Format.nBlockAlign = (fmt->Format.wBitsPerSample *
1376             fmt->Format.nChannels) / 8;
1377     fmt->Format.nAvgBytesPerSec = fmt->Format.nSamplesPerSec *
1378         fmt->Format.nBlockAlign;
1379
1380     fmt->Samples.wValidBitsPerSample = fmt->Format.wBitsPerSample;
1381     fmt->Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX);
1382
1383     *pwfx = (WAVEFORMATEX*)fmt;
1384     dump_fmt(*pwfx);
1385
1386     return S_OK;
1387 }
1388
1389 static HRESULT WINAPI AudioClient_GetDevicePeriod(IAudioClient *iface,
1390         REFERENCE_TIME *defperiod, REFERENCE_TIME *minperiod)
1391 {
1392     ACImpl *This = impl_from_IAudioClient(iface);
1393
1394     TRACE("(%p)->(%p, %p)\n", This, defperiod, minperiod);
1395
1396     if(!defperiod && !minperiod)
1397         return E_POINTER;
1398
1399     if(defperiod)
1400         *defperiod = DefaultPeriod;
1401     if(minperiod)
1402         *minperiod = MinimumPeriod;
1403
1404     return S_OK;
1405 }
1406
1407 void CALLBACK ca_period_cb(void *user, BOOLEAN timer)
1408 {
1409     ACImpl *This = user;
1410
1411     OSSpinLockLock(&This->lock);
1412     if(This->event)
1413         SetEvent(This->event);
1414     OSSpinLockUnlock(&This->lock);
1415 }
1416
1417 static HRESULT WINAPI AudioClient_Start(IAudioClient *iface)
1418 {
1419     ACImpl *This = impl_from_IAudioClient(iface);
1420     OSStatus sc;
1421
1422     TRACE("(%p)\n", This);
1423
1424     OSSpinLockLock(&This->lock);
1425
1426     if(!This->aqueue){
1427         OSSpinLockUnlock(&This->lock);
1428         return AUDCLNT_E_NOT_INITIALIZED;
1429     }
1430
1431     if(This->playing != StateStopped){
1432         OSSpinLockUnlock(&This->lock);
1433         return AUDCLNT_E_NOT_STOPPED;
1434     }
1435
1436     if((This->flags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK) && !This->event){
1437         OSSpinLockUnlock(&This->lock);
1438         return AUDCLNT_E_EVENTHANDLE_NOT_SET;
1439     }
1440
1441     if(This->event)
1442         if(!CreateTimerQueueTimer(&This->timer, g_timer_q,
1443                     ca_period_cb, This, 0, This->period_ms, 0))
1444             ERR("Unable to create timer: %u\n", GetLastError());
1445
1446     This->playing = StateInTransition;
1447
1448     OSSpinLockUnlock(&This->lock);
1449
1450     sc = AudioQueueStart(This->aqueue, NULL);
1451     if(sc != noErr){
1452         WARN("Unable to start audio queue: %lx\n", sc);
1453         return E_FAIL;
1454     }
1455
1456     OSSpinLockLock(&This->lock);
1457
1458     This->playing = StatePlaying;
1459
1460     OSSpinLockUnlock(&This->lock);
1461
1462     return S_OK;
1463 }
1464
1465 static HRESULT WINAPI AudioClient_Stop(IAudioClient *iface)
1466 {
1467     ACImpl *This = impl_from_IAudioClient(iface);
1468     AudioTimeStamp tstamp;
1469     OSStatus sc;
1470
1471     TRACE("(%p)\n", This);
1472
1473     OSSpinLockLock(&This->lock);
1474
1475     if(!This->aqueue){
1476         OSSpinLockUnlock(&This->lock);
1477         return AUDCLNT_E_NOT_INITIALIZED;
1478     }
1479
1480     if(This->playing == StateStopped){
1481         OSSpinLockUnlock(&This->lock);
1482         return S_FALSE;
1483     }
1484
1485     if(This->playing == StateInTransition){
1486         OSSpinLockUnlock(&This->lock);
1487         return S_OK;
1488     }
1489
1490     if(This->timer && This->timer != INVALID_HANDLE_VALUE){
1491         DeleteTimerQueueTimer(g_timer_q, This->timer, INVALID_HANDLE_VALUE);
1492         This->timer = NULL;
1493     }
1494
1495     This->playing = StateInTransition;
1496
1497     sc = AudioQueueGetCurrentTime(This->aqueue, NULL, &tstamp, NULL);
1498     if(sc == noErr){
1499         if(tstamp.mFlags & kAudioTimeStampSampleTimeValid){
1500             if(tstamp.mSampleTime > This->highest_sampletime)
1501                 This->highest_sampletime = tstamp.mSampleTime;
1502         }else
1503             WARN("Returned tstamp mSampleTime not valid: %lx\n", tstamp.mFlags);
1504     }else
1505         WARN("GetCurrentTime failed: %lx\n", sc);
1506
1507     OSSpinLockUnlock(&This->lock);
1508
1509     sc = AudioQueueFlush(This->aqueue);
1510     if(sc != noErr)
1511         WARN("Unable to flush audio queue: %lx\n", sc);
1512
1513     sc = AudioQueuePause(This->aqueue);
1514     if(sc != noErr){
1515         WARN("Unable to pause audio queue: %lx\n", sc);
1516         return E_FAIL;
1517     }
1518
1519     OSSpinLockLock(&This->lock);
1520
1521     This->playing = StateStopped;
1522
1523     OSSpinLockUnlock(&This->lock);
1524
1525     return S_OK;
1526 }
1527
1528 static HRESULT WINAPI AudioClient_Reset(IAudioClient *iface)
1529 {
1530     ACImpl *This = impl_from_IAudioClient(iface);
1531     OSStatus sc;
1532     QueuedBufInfo *bufinfo, *bufinfo2;
1533
1534     TRACE("(%p)\n", This);
1535
1536     OSSpinLockLock(&This->lock);
1537
1538     if(!This->aqueue){
1539         OSSpinLockUnlock(&This->lock);
1540         return AUDCLNT_E_NOT_INITIALIZED;
1541     }
1542
1543     if(This->playing != StateStopped){
1544         OSSpinLockUnlock(&This->lock);
1545         return AUDCLNT_E_NOT_STOPPED;
1546     }
1547
1548     if(This->getbuf_last){
1549         OSSpinLockUnlock(&This->lock);
1550         return AUDCLNT_E_BUFFER_OPERATION_PENDING;
1551     }
1552
1553     This->written_frames = 0;
1554     This->inbuf_frames = 0;
1555
1556     LIST_FOR_EACH_ENTRY_SAFE(bufinfo, bufinfo2, &This->queued_bufinfos,
1557             QueuedBufInfo, entry){
1558         list_remove(&bufinfo->entry);
1559         HeapFree(GetProcessHeap(), 0, bufinfo);
1560     }
1561
1562     OSSpinLockUnlock(&This->lock);
1563
1564     sc = AudioQueueReset(This->aqueue);
1565     if(sc != noErr){
1566         WARN("Unable to reset audio queue: %lx\n", sc);
1567         return E_FAIL;
1568     }
1569
1570     return S_OK;
1571 }
1572
1573 static HRESULT WINAPI AudioClient_SetEventHandle(IAudioClient *iface,
1574         HANDLE event)
1575 {
1576     ACImpl *This = impl_from_IAudioClient(iface);
1577
1578     TRACE("(%p)->(%p)\n", This, event);
1579
1580     if(!event)
1581         return E_INVALIDARG;
1582
1583     OSSpinLockLock(&This->lock);
1584
1585     if(!This->aqueue){
1586         OSSpinLockUnlock(&This->lock);
1587         return AUDCLNT_E_NOT_INITIALIZED;
1588     }
1589
1590     if(!(This->flags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK)){
1591         OSSpinLockUnlock(&This->lock);
1592         return AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED;
1593     }
1594
1595     This->event = event;
1596
1597     OSSpinLockUnlock(&This->lock);
1598
1599     return S_OK;
1600 }
1601
1602 static HRESULT WINAPI AudioClient_GetService(IAudioClient *iface, REFIID riid,
1603         void **ppv)
1604 {
1605     ACImpl *This = impl_from_IAudioClient(iface);
1606
1607     TRACE("(%p)->(%s, %p)\n", This, debugstr_guid(riid), ppv);
1608
1609     if(!ppv)
1610         return E_POINTER;
1611     *ppv = NULL;
1612
1613     OSSpinLockLock(&This->lock);
1614
1615     if(!This->aqueue){
1616         OSSpinLockUnlock(&This->lock);
1617         return AUDCLNT_E_NOT_INITIALIZED;
1618     }
1619
1620     if(IsEqualIID(riid, &IID_IAudioRenderClient)){
1621         if(This->dataflow != eRender){
1622             OSSpinLockUnlock(&This->lock);
1623             return AUDCLNT_E_WRONG_ENDPOINT_TYPE;
1624         }
1625         IAudioRenderClient_AddRef(&This->IAudioRenderClient_iface);
1626         *ppv = &This->IAudioRenderClient_iface;
1627     }else if(IsEqualIID(riid, &IID_IAudioCaptureClient)){
1628         if(This->dataflow != eCapture){
1629             OSSpinLockUnlock(&This->lock);
1630             return AUDCLNT_E_WRONG_ENDPOINT_TYPE;
1631         }
1632         IAudioCaptureClient_AddRef(&This->IAudioCaptureClient_iface);
1633         *ppv = &This->IAudioCaptureClient_iface;
1634     }else if(IsEqualIID(riid, &IID_IAudioClock)){
1635         IAudioClock_AddRef(&This->IAudioClock_iface);
1636         *ppv = &This->IAudioClock_iface;
1637     }else if(IsEqualIID(riid, &IID_IAudioStreamVolume)){
1638         IAudioStreamVolume_AddRef(&This->IAudioStreamVolume_iface);
1639         *ppv = &This->IAudioStreamVolume_iface;
1640     }else if(IsEqualIID(riid, &IID_IAudioSessionControl)){
1641         if(!This->session_wrapper){
1642             This->session_wrapper = AudioSessionWrapper_Create(This);
1643             if(!This->session_wrapper){
1644                 OSSpinLockUnlock(&This->lock);
1645                 return E_OUTOFMEMORY;
1646             }
1647         }else
1648             IAudioSessionControl2_AddRef(&This->session_wrapper->IAudioSessionControl2_iface);
1649
1650         *ppv = &This->session_wrapper->IAudioSessionControl2_iface;
1651     }else if(IsEqualIID(riid, &IID_IChannelAudioVolume)){
1652         if(!This->session_wrapper){
1653             This->session_wrapper = AudioSessionWrapper_Create(This);
1654             if(!This->session_wrapper){
1655                 OSSpinLockUnlock(&This->lock);
1656                 return E_OUTOFMEMORY;
1657             }
1658         }else
1659             IChannelAudioVolume_AddRef(&This->session_wrapper->IChannelAudioVolume_iface);
1660
1661         *ppv = &This->session_wrapper->IChannelAudioVolume_iface;
1662     }else if(IsEqualIID(riid, &IID_ISimpleAudioVolume)){
1663         if(!This->session_wrapper){
1664             This->session_wrapper = AudioSessionWrapper_Create(This);
1665             if(!This->session_wrapper){
1666                 OSSpinLockUnlock(&This->lock);
1667                 return E_OUTOFMEMORY;
1668             }
1669         }else
1670             ISimpleAudioVolume_AddRef(&This->session_wrapper->ISimpleAudioVolume_iface);
1671
1672         *ppv = &This->session_wrapper->ISimpleAudioVolume_iface;
1673     }
1674
1675     if(*ppv){
1676         OSSpinLockUnlock(&This->lock);
1677         return S_OK;
1678     }
1679
1680     OSSpinLockUnlock(&This->lock);
1681
1682     FIXME("stub %s\n", debugstr_guid(riid));
1683     return E_NOINTERFACE;
1684 }
1685
1686 static const IAudioClientVtbl AudioClient_Vtbl =
1687 {
1688     AudioClient_QueryInterface,
1689     AudioClient_AddRef,
1690     AudioClient_Release,
1691     AudioClient_Initialize,
1692     AudioClient_GetBufferSize,
1693     AudioClient_GetStreamLatency,
1694     AudioClient_GetCurrentPadding,
1695     AudioClient_IsFormatSupported,
1696     AudioClient_GetMixFormat,
1697     AudioClient_GetDevicePeriod,
1698     AudioClient_Start,
1699     AudioClient_Stop,
1700     AudioClient_Reset,
1701     AudioClient_SetEventHandle,
1702     AudioClient_GetService
1703 };
1704
1705 static HRESULT WINAPI AudioRenderClient_QueryInterface(
1706         IAudioRenderClient *iface, REFIID riid, void **ppv)
1707 {
1708     TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
1709
1710     if(!ppv)
1711         return E_POINTER;
1712     *ppv = NULL;
1713
1714     if(IsEqualIID(riid, &IID_IUnknown) ||
1715             IsEqualIID(riid, &IID_IAudioRenderClient))
1716         *ppv = iface;
1717     if(*ppv){
1718         IUnknown_AddRef((IUnknown*)*ppv);
1719         return S_OK;
1720     }
1721
1722     WARN("Unknown interface %s\n", debugstr_guid(riid));
1723     return E_NOINTERFACE;
1724 }
1725
1726 static ULONG WINAPI AudioRenderClient_AddRef(IAudioRenderClient *iface)
1727 {
1728     ACImpl *This = impl_from_IAudioRenderClient(iface);
1729     return AudioClient_AddRef(&This->IAudioClient_iface);
1730 }
1731
1732 static ULONG WINAPI AudioRenderClient_Release(IAudioRenderClient *iface)
1733 {
1734     ACImpl *This = impl_from_IAudioRenderClient(iface);
1735     return AudioClient_Release(&This->IAudioClient_iface);
1736 }
1737
1738 static HRESULT WINAPI AudioRenderClient_GetBuffer(IAudioRenderClient *iface,
1739         UINT32 frames, BYTE **data)
1740 {
1741     ACImpl *This = impl_from_IAudioRenderClient(iface);
1742     AQBuffer *buf;
1743     UINT32 pad, bytes = frames * This->fmt->nBlockAlign;
1744     HRESULT hr;
1745     OSStatus sc;
1746
1747     TRACE("(%p)->(%u, %p)\n", This, frames, data);
1748
1749     if(!data)
1750         return E_POINTER;
1751     *data = NULL;
1752
1753     OSSpinLockLock(&This->lock);
1754
1755     if(This->getbuf_last){
1756         OSSpinLockUnlock(&This->lock);
1757         return AUDCLNT_E_OUT_OF_ORDER;
1758     }
1759
1760     if(!frames){
1761         OSSpinLockUnlock(&This->lock);
1762         return S_OK;
1763     }
1764
1765     hr = AudioClient_GetCurrentPadding_nolock(This, &pad);
1766     if(FAILED(hr)){
1767         OSSpinLockUnlock(&This->lock);
1768         return hr;
1769     }
1770
1771     if(pad + frames > This->bufsize_frames){
1772         OSSpinLockUnlock(&This->lock);
1773         return AUDCLNT_E_BUFFER_TOO_LARGE;
1774     }
1775
1776     LIST_FOR_EACH_ENTRY(buf, &This->avail_buffers, AQBuffer, entry){
1777         if(buf->buf->mAudioDataBytesCapacity >= bytes){
1778             This->public_buffer = buf->buf;
1779             list_remove(&buf->entry);
1780             break;
1781         }
1782     }
1783
1784     if(&buf->entry == &This->avail_buffers){
1785         sc = AudioQueueAllocateBuffer(This->aqueue, bytes,
1786                 &This->public_buffer);
1787         if(sc != noErr){
1788             OSSpinLockUnlock(&This->lock);
1789             WARN("Unable to allocate buffer: %lx\n", sc);
1790             return E_FAIL;
1791         }
1792         buf = HeapAlloc(GetProcessHeap(), 0, sizeof(AQBuffer));
1793         if(!buf){
1794             AudioQueueFreeBuffer(This->aqueue, This->public_buffer);
1795             This->public_buffer = NULL;
1796             OSSpinLockUnlock(&This->lock);
1797             return E_OUTOFMEMORY;
1798         }
1799         buf->buf = This->public_buffer;
1800         This->public_buffer->mUserData = buf;
1801     }
1802
1803     *data = This->public_buffer->mAudioData;
1804
1805     This->getbuf_last = frames;
1806
1807     OSSpinLockUnlock(&This->lock);
1808
1809     return S_OK;
1810 }
1811
1812 static HRESULT WINAPI AudioRenderClient_ReleaseBuffer(
1813         IAudioRenderClient *iface, UINT32 frames, DWORD flags)
1814 {
1815     ACImpl *This = impl_from_IAudioRenderClient(iface);
1816     AudioTimeStamp start_time;
1817     OSStatus sc;
1818
1819     TRACE("(%p)->(%u, %x)\n", This, frames, flags);
1820
1821     OSSpinLockLock(&This->lock);
1822
1823     if(!frames){
1824         This->getbuf_last = 0;
1825         if(This->public_buffer){
1826             AQBuffer *buf = This->public_buffer->mUserData;
1827             list_add_tail(&This->avail_buffers, &buf->entry);
1828             This->public_buffer = NULL;
1829         }
1830         OSSpinLockUnlock(&This->lock);
1831         return S_OK;
1832     }
1833
1834     if(!This->getbuf_last){
1835         OSSpinLockUnlock(&This->lock);
1836         return AUDCLNT_E_OUT_OF_ORDER;
1837     }
1838
1839     if(frames > This->getbuf_last){
1840         OSSpinLockUnlock(&This->lock);
1841         return AUDCLNT_E_INVALID_SIZE;
1842     }
1843
1844     if(flags & AUDCLNT_BUFFERFLAGS_SILENT){
1845         WAVEFORMATEXTENSIBLE *fmtex = (WAVEFORMATEXTENSIBLE*)This->fmt;
1846         if((This->fmt->wFormatTag == WAVE_FORMAT_PCM ||
1847                 (This->fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
1848                  IsEqualGUID(&fmtex->SubFormat, &KSDATAFORMAT_SUBTYPE_PCM))) &&
1849                 This->fmt->wBitsPerSample == 8)
1850             memset(This->public_buffer->mAudioData, 128,
1851                     frames * This->fmt->nBlockAlign);
1852         else
1853             memset(This->public_buffer->mAudioData, 0,
1854                     frames * This->fmt->nBlockAlign);
1855     }
1856
1857     This->public_buffer->mAudioDataByteSize = frames * This->fmt->nBlockAlign;
1858
1859     sc = AudioQueueEnqueueBufferWithParameters(This->aqueue,
1860             This->public_buffer, 0, NULL, 0, 0, 0, NULL, NULL, &start_time);
1861     if(sc != noErr){
1862         OSSpinLockUnlock(&This->lock);
1863         WARN("Unable to enqueue buffer: %lx\n", sc);
1864         return E_FAIL;
1865     }
1866
1867     if(start_time.mFlags & kAudioTimeStampSampleTimeValid){
1868         QueuedBufInfo *bufinfo;
1869
1870         bufinfo = HeapAlloc(GetProcessHeap(), 0, sizeof(*bufinfo));
1871         bufinfo->start_sampletime = start_time.mSampleTime;
1872         bufinfo->start_pos = This->written_frames;
1873         bufinfo->len_frames = frames;
1874
1875         list_add_tail(&This->queued_bufinfos, &bufinfo->entry);
1876     }else
1877         WARN("Start time didn't contain valid SampleTime member\n");
1878
1879     if(This->playing == StateStopped)
1880         AudioQueuePrime(This->aqueue, 0, NULL);
1881
1882     This->public_buffer = NULL;
1883     This->getbuf_last = 0;
1884     This->written_frames += frames;
1885     This->inbuf_frames += frames;
1886
1887     OSSpinLockUnlock(&This->lock);
1888
1889     return S_OK;
1890 }
1891
1892 static const IAudioRenderClientVtbl AudioRenderClient_Vtbl = {
1893     AudioRenderClient_QueryInterface,
1894     AudioRenderClient_AddRef,
1895     AudioRenderClient_Release,
1896     AudioRenderClient_GetBuffer,
1897     AudioRenderClient_ReleaseBuffer
1898 };
1899
1900 static HRESULT WINAPI AudioCaptureClient_QueryInterface(
1901         IAudioCaptureClient *iface, REFIID riid, void **ppv)
1902 {
1903     TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
1904
1905     if(!ppv)
1906         return E_POINTER;
1907     *ppv = NULL;
1908
1909     if(IsEqualIID(riid, &IID_IUnknown) ||
1910             IsEqualIID(riid, &IID_IAudioCaptureClient))
1911         *ppv = iface;
1912     if(*ppv){
1913         IUnknown_AddRef((IUnknown*)*ppv);
1914         return S_OK;
1915     }
1916
1917     WARN("Unknown interface %s\n", debugstr_guid(riid));
1918     return E_NOINTERFACE;
1919 }
1920
1921 static ULONG WINAPI AudioCaptureClient_AddRef(IAudioCaptureClient *iface)
1922 {
1923     ACImpl *This = impl_from_IAudioCaptureClient(iface);
1924     return IAudioClient_AddRef(&This->IAudioClient_iface);
1925 }
1926
1927 static ULONG WINAPI AudioCaptureClient_Release(IAudioCaptureClient *iface)
1928 {
1929     ACImpl *This = impl_from_IAudioCaptureClient(iface);
1930     return IAudioClient_Release(&This->IAudioClient_iface);
1931 }
1932
1933 static HRESULT WINAPI AudioCaptureClient_GetBuffer(IAudioCaptureClient *iface,
1934         BYTE **data, UINT32 *frames, DWORD *flags, UINT64 *devpos,
1935         UINT64 *qpcpos)
1936 {
1937     ACImpl *This = impl_from_IAudioCaptureClient(iface);
1938
1939     TRACE("(%p)->(%p, %p, %p, %p, %p)\n", This, data, frames, flags,
1940             devpos, qpcpos);
1941
1942     if(!data || !frames || !flags)
1943         return E_POINTER;
1944
1945     OSSpinLockLock(&This->lock);
1946
1947     if(This->getbuf_last){
1948         OSSpinLockUnlock(&This->lock);
1949         return AUDCLNT_E_OUT_OF_ORDER;
1950     }
1951
1952     if(This->public_buffer){
1953         *data = This->public_buffer->mAudioData;
1954         *frames =
1955             This->public_buffer->mAudioDataByteSize / This->fmt->nBlockAlign;
1956     }else{
1957         struct list *head = list_head(&This->avail_buffers);
1958         if(!head){
1959             *data = NULL;
1960             *frames = 0;
1961         }else{
1962             AQBuffer *buf = LIST_ENTRY(head, AQBuffer, entry);
1963             This->public_buffer = buf->buf;
1964             *data = This->public_buffer->mAudioData;
1965             *frames =
1966                 This->public_buffer->mAudioDataByteSize / This->fmt->nBlockAlign;
1967             list_remove(&buf->entry);
1968         }
1969     }
1970
1971     *flags = 0;
1972     This->written_frames += *frames;
1973     This->inbuf_frames -= *frames;
1974     This->getbuf_last = 1;
1975
1976     if(devpos || qpcpos)
1977         AudioClock_GetPosition_nolock(This, devpos, qpcpos);
1978
1979     OSSpinLockUnlock(&This->lock);
1980
1981     return *frames ? S_OK : AUDCLNT_S_BUFFER_EMPTY;
1982 }
1983
1984 static HRESULT WINAPI AudioCaptureClient_ReleaseBuffer(
1985         IAudioCaptureClient *iface, UINT32 done)
1986 {
1987     ACImpl *This = impl_from_IAudioCaptureClient(iface);
1988     UINT32 pbuf_frames;
1989     OSStatus sc;
1990
1991     TRACE("(%p)->(%u)\n", This, done);
1992
1993     OSSpinLockLock(&This->lock);
1994
1995     if(!This->getbuf_last){
1996         OSSpinLockUnlock(&This->lock);
1997         return AUDCLNT_E_OUT_OF_ORDER;
1998     }
1999
2000     pbuf_frames = This->public_buffer->mAudioDataByteSize / This->fmt->nBlockAlign;
2001     if(done != 0 && done != pbuf_frames){
2002         OSSpinLockUnlock(&This->lock);
2003         return AUDCLNT_E_INVALID_SIZE;
2004     }
2005
2006     if(done){
2007         sc = AudioQueueEnqueueBuffer(This->aqueue, This->public_buffer,
2008                 0, NULL);
2009         if(sc != noErr)
2010             WARN("Unable to enqueue buffer: %lx\n", sc);
2011         This->public_buffer = NULL;
2012     }
2013
2014     This->getbuf_last = 0;
2015
2016     OSSpinLockUnlock(&This->lock);
2017
2018     return S_OK;
2019 }
2020
2021 static HRESULT WINAPI AudioCaptureClient_GetNextPacketSize(
2022         IAudioCaptureClient *iface, UINT32 *frames)
2023 {
2024     ACImpl *This = impl_from_IAudioCaptureClient(iface);
2025     struct list *head;
2026     AQBuffer *buf;
2027
2028     TRACE("(%p)->(%p)\n", This, frames);
2029
2030     if(!frames)
2031         return E_POINTER;
2032
2033     OSSpinLockLock(&This->lock);
2034
2035     head = list_head(&This->avail_buffers);
2036
2037     if(!head){
2038         *frames = This->bufsize_frames / CAPTURE_BUFFERS;
2039         OSSpinLockUnlock(&This->lock);
2040         return S_OK;
2041     }
2042
2043     buf = LIST_ENTRY(head, AQBuffer, entry);
2044     *frames = buf->buf->mAudioDataByteSize / This->fmt->nBlockAlign;
2045
2046     OSSpinLockUnlock(&This->lock);
2047
2048     return S_OK;
2049 }
2050
2051 static const IAudioCaptureClientVtbl AudioCaptureClient_Vtbl =
2052 {
2053     AudioCaptureClient_QueryInterface,
2054     AudioCaptureClient_AddRef,
2055     AudioCaptureClient_Release,
2056     AudioCaptureClient_GetBuffer,
2057     AudioCaptureClient_ReleaseBuffer,
2058     AudioCaptureClient_GetNextPacketSize
2059 };
2060
2061 static HRESULT WINAPI AudioClock_QueryInterface(IAudioClock *iface,
2062         REFIID riid, void **ppv)
2063 {
2064     ACImpl *This = impl_from_IAudioClock(iface);
2065
2066     TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
2067
2068     if(!ppv)
2069         return E_POINTER;
2070     *ppv = NULL;
2071
2072     if(IsEqualIID(riid, &IID_IUnknown) || IsEqualIID(riid, &IID_IAudioClock))
2073         *ppv = iface;
2074     else if(IsEqualIID(riid, &IID_IAudioClock2))
2075         *ppv = &This->IAudioClock2_iface;
2076     if(*ppv){
2077         IUnknown_AddRef((IUnknown*)*ppv);
2078         return S_OK;
2079     }
2080
2081     WARN("Unknown interface %s\n", debugstr_guid(riid));
2082     return E_NOINTERFACE;
2083 }
2084
2085 static ULONG WINAPI AudioClock_AddRef(IAudioClock *iface)
2086 {
2087     ACImpl *This = impl_from_IAudioClock(iface);
2088     return IAudioClient_AddRef(&This->IAudioClient_iface);
2089 }
2090
2091 static ULONG WINAPI AudioClock_Release(IAudioClock *iface)
2092 {
2093     ACImpl *This = impl_from_IAudioClock(iface);
2094     return IAudioClient_Release(&This->IAudioClient_iface);
2095 }
2096
2097 static HRESULT WINAPI AudioClock_GetFrequency(IAudioClock *iface, UINT64 *freq)
2098 {
2099     ACImpl *This = impl_from_IAudioClock(iface);
2100
2101     TRACE("(%p)->(%p)\n", This, freq);
2102
2103     *freq = This->fmt->nSamplesPerSec;
2104
2105     return S_OK;
2106 }
2107
2108 static HRESULT AudioClock_GetPosition_nolock(ACImpl *This,
2109         UINT64 *pos, UINT64 *qpctime)
2110 {
2111     if(This->dataflow == eRender)
2112         *pos = get_current_aqbuffer_position(This, BUFPOS_ABSOLUTE);
2113     else
2114         *pos = This->inbuf_frames + This->written_frames;
2115
2116     if(qpctime){
2117         LARGE_INTEGER stamp, freq;
2118         QueryPerformanceCounter(&stamp);
2119         QueryPerformanceFrequency(&freq);
2120         *qpctime = (stamp.QuadPart * (INT64)10000000) / freq.QuadPart;
2121     }
2122
2123     return S_OK;
2124 }
2125
2126 static HRESULT WINAPI AudioClock_GetPosition(IAudioClock *iface, UINT64 *pos,
2127         UINT64 *qpctime)
2128 {
2129     ACImpl *This = impl_from_IAudioClock(iface);
2130     HRESULT hr;
2131
2132     TRACE("(%p)->(%p, %p)\n", This, pos, qpctime);
2133
2134     if(!pos)
2135         return E_POINTER;
2136
2137     OSSpinLockLock(&This->lock);
2138
2139     hr = AudioClock_GetPosition_nolock(This, pos, qpctime);
2140
2141     OSSpinLockUnlock(&This->lock);
2142
2143     return hr;
2144 }
2145
2146 static HRESULT WINAPI AudioClock_GetCharacteristics(IAudioClock *iface,
2147         DWORD *chars)
2148 {
2149     ACImpl *This = impl_from_IAudioClock(iface);
2150
2151     TRACE("(%p)->(%p)\n", This, chars);
2152
2153     if(!chars)
2154         return E_POINTER;
2155
2156     *chars = AUDIOCLOCK_CHARACTERISTIC_FIXED_FREQ;
2157
2158     return S_OK;
2159 }
2160
2161 static const IAudioClockVtbl AudioClock_Vtbl =
2162 {
2163     AudioClock_QueryInterface,
2164     AudioClock_AddRef,
2165     AudioClock_Release,
2166     AudioClock_GetFrequency,
2167     AudioClock_GetPosition,
2168     AudioClock_GetCharacteristics
2169 };
2170
2171 static HRESULT WINAPI AudioClock2_QueryInterface(IAudioClock2 *iface,
2172         REFIID riid, void **ppv)
2173 {
2174     ACImpl *This = impl_from_IAudioClock2(iface);
2175     return IAudioClock_QueryInterface(&This->IAudioClock_iface, riid, ppv);
2176 }
2177
2178 static ULONG WINAPI AudioClock2_AddRef(IAudioClock2 *iface)
2179 {
2180     ACImpl *This = impl_from_IAudioClock2(iface);
2181     return IAudioClient_AddRef(&This->IAudioClient_iface);
2182 }
2183
2184 static ULONG WINAPI AudioClock2_Release(IAudioClock2 *iface)
2185 {
2186     ACImpl *This = impl_from_IAudioClock2(iface);
2187     return IAudioClient_Release(&This->IAudioClient_iface);
2188 }
2189
2190 static HRESULT WINAPI AudioClock2_GetDevicePosition(IAudioClock2 *iface,
2191         UINT64 *pos, UINT64 *qpctime)
2192 {
2193     ACImpl *This = impl_from_IAudioClock2(iface);
2194
2195     FIXME("(%p)->(%p, %p)\n", This, pos, qpctime);
2196
2197     return E_NOTIMPL;
2198 }
2199
2200 static const IAudioClock2Vtbl AudioClock2_Vtbl =
2201 {
2202     AudioClock2_QueryInterface,
2203     AudioClock2_AddRef,
2204     AudioClock2_Release,
2205     AudioClock2_GetDevicePosition
2206 };
2207
2208 static AudioSessionWrapper *AudioSessionWrapper_Create(ACImpl *client)
2209 {
2210     AudioSessionWrapper *ret;
2211
2212     ret = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
2213             sizeof(AudioSessionWrapper));
2214     if(!ret)
2215         return NULL;
2216
2217     ret->IAudioSessionControl2_iface.lpVtbl = &AudioSessionControl2_Vtbl;
2218     ret->ISimpleAudioVolume_iface.lpVtbl = &SimpleAudioVolume_Vtbl;
2219     ret->IChannelAudioVolume_iface.lpVtbl = &ChannelAudioVolume_Vtbl;
2220
2221     ret->ref = 1;
2222
2223     ret->client = client;
2224     if(client){
2225         ret->session = client->session;
2226         AudioClient_AddRef(&client->IAudioClient_iface);
2227     }
2228
2229     return ret;
2230 }
2231
2232 static HRESULT WINAPI AudioSessionControl_QueryInterface(
2233         IAudioSessionControl2 *iface, REFIID riid, void **ppv)
2234 {
2235     TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
2236
2237     if(!ppv)
2238         return E_POINTER;
2239     *ppv = NULL;
2240
2241     if(IsEqualIID(riid, &IID_IUnknown) ||
2242             IsEqualIID(riid, &IID_IAudioSessionControl) ||
2243             IsEqualIID(riid, &IID_IAudioSessionControl2))
2244         *ppv = iface;
2245     if(*ppv){
2246         IUnknown_AddRef((IUnknown*)*ppv);
2247         return S_OK;
2248     }
2249
2250     WARN("Unknown interface %s\n", debugstr_guid(riid));
2251     return E_NOINTERFACE;
2252 }
2253
2254 static ULONG WINAPI AudioSessionControl_AddRef(IAudioSessionControl2 *iface)
2255 {
2256     AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2257     ULONG ref;
2258     ref = InterlockedIncrement(&This->ref);
2259     TRACE("(%p) Refcount now %u\n", This, ref);
2260     return ref;
2261 }
2262
2263 static ULONG WINAPI AudioSessionControl_Release(IAudioSessionControl2 *iface)
2264 {
2265     AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2266     ULONG ref;
2267     ref = InterlockedDecrement(&This->ref);
2268     TRACE("(%p) Refcount now %u\n", This, ref);
2269     if(!ref){
2270         if(This->client){
2271             OSSpinLockLock(&This->client->lock);
2272             This->client->session_wrapper = NULL;
2273             OSSpinLockUnlock(&This->client->lock);
2274             AudioClient_Release(&This->client->IAudioClient_iface);
2275         }
2276         HeapFree(GetProcessHeap(), 0, This);
2277     }
2278     return ref;
2279 }
2280
2281 static HRESULT WINAPI AudioSessionControl_GetState(IAudioSessionControl2 *iface,
2282         AudioSessionState *state)
2283 {
2284     AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2285     ACImpl *client;
2286
2287     TRACE("(%p)->(%p)\n", This, state);
2288
2289     if(!state)
2290         return NULL_PTR_ERR;
2291
2292     EnterCriticalSection(&g_sessions_lock);
2293
2294     if(list_empty(&This->session->clients)){
2295         *state = AudioSessionStateExpired;
2296         LeaveCriticalSection(&g_sessions_lock);
2297         return S_OK;
2298     }
2299
2300     LIST_FOR_EACH_ENTRY(client, &This->session->clients, ACImpl, entry){
2301         OSSpinLockLock(&client->lock);
2302         if(client->playing == StatePlaying ||
2303                 client->playing == StateInTransition){
2304             *state = AudioSessionStateActive;
2305             OSSpinLockUnlock(&client->lock);
2306             LeaveCriticalSection(&g_sessions_lock);
2307             return S_OK;
2308         }
2309         OSSpinLockUnlock(&client->lock);
2310     }
2311
2312     LeaveCriticalSection(&g_sessions_lock);
2313
2314     *state = AudioSessionStateInactive;
2315
2316     return S_OK;
2317 }
2318
2319 static HRESULT WINAPI AudioSessionControl_GetDisplayName(
2320         IAudioSessionControl2 *iface, WCHAR **name)
2321 {
2322     AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2323
2324     FIXME("(%p)->(%p) - stub\n", This, name);
2325
2326     return E_NOTIMPL;
2327 }
2328
2329 static HRESULT WINAPI AudioSessionControl_SetDisplayName(
2330         IAudioSessionControl2 *iface, const WCHAR *name, const GUID *session)
2331 {
2332     AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2333
2334     FIXME("(%p)->(%p, %s) - stub\n", This, name, debugstr_guid(session));
2335
2336     return E_NOTIMPL;
2337 }
2338
2339 static HRESULT WINAPI AudioSessionControl_GetIconPath(
2340         IAudioSessionControl2 *iface, WCHAR **path)
2341 {
2342     AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2343
2344     FIXME("(%p)->(%p) - stub\n", This, path);
2345
2346     return E_NOTIMPL;
2347 }
2348
2349 static HRESULT WINAPI AudioSessionControl_SetIconPath(
2350         IAudioSessionControl2 *iface, const WCHAR *path, const GUID *session)
2351 {
2352     AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2353
2354     FIXME("(%p)->(%p, %s) - stub\n", This, path, debugstr_guid(session));
2355
2356     return E_NOTIMPL;
2357 }
2358
2359 static HRESULT WINAPI AudioSessionControl_GetGroupingParam(
2360         IAudioSessionControl2 *iface, GUID *group)
2361 {
2362     AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2363
2364     FIXME("(%p)->(%p) - stub\n", This, group);
2365
2366     return E_NOTIMPL;
2367 }
2368
2369 static HRESULT WINAPI AudioSessionControl_SetGroupingParam(
2370         IAudioSessionControl2 *iface, const GUID *group, const GUID *session)
2371 {
2372     AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2373
2374     FIXME("(%p)->(%s, %s) - stub\n", This, debugstr_guid(group),
2375             debugstr_guid(session));
2376
2377     return E_NOTIMPL;
2378 }
2379
2380 static HRESULT WINAPI AudioSessionControl_RegisterAudioSessionNotification(
2381         IAudioSessionControl2 *iface, IAudioSessionEvents *events)
2382 {
2383     AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2384
2385     FIXME("(%p)->(%p) - stub\n", This, events);
2386
2387     return S_OK;
2388 }
2389
2390 static HRESULT WINAPI AudioSessionControl_UnregisterAudioSessionNotification(
2391         IAudioSessionControl2 *iface, IAudioSessionEvents *events)
2392 {
2393     AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2394
2395     FIXME("(%p)->(%p) - stub\n", This, events);
2396
2397     return S_OK;
2398 }
2399
2400 static HRESULT WINAPI AudioSessionControl_GetSessionIdentifier(
2401         IAudioSessionControl2 *iface, WCHAR **id)
2402 {
2403     AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2404
2405     FIXME("(%p)->(%p) - stub\n", This, id);
2406
2407     return E_NOTIMPL;
2408 }
2409
2410 static HRESULT WINAPI AudioSessionControl_GetSessionInstanceIdentifier(
2411         IAudioSessionControl2 *iface, WCHAR **id)
2412 {
2413     AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2414
2415     FIXME("(%p)->(%p) - stub\n", This, id);
2416
2417     return E_NOTIMPL;
2418 }
2419
2420 static HRESULT WINAPI AudioSessionControl_GetProcessId(
2421         IAudioSessionControl2 *iface, DWORD *pid)
2422 {
2423     AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2424
2425     TRACE("(%p)->(%p)\n", This, pid);
2426
2427     if(!pid)
2428         return E_POINTER;
2429
2430     *pid = GetCurrentProcessId();
2431
2432     return S_OK;
2433 }
2434
2435 static HRESULT WINAPI AudioSessionControl_IsSystemSoundsSession(
2436         IAudioSessionControl2 *iface)
2437 {
2438     AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2439
2440     TRACE("(%p)\n", This);
2441
2442     return S_FALSE;
2443 }
2444
2445 static HRESULT WINAPI AudioSessionControl_SetDuckingPreference(
2446         IAudioSessionControl2 *iface, BOOL optout)
2447 {
2448     AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2449
2450     TRACE("(%p)->(%d)\n", This, optout);
2451
2452     return S_OK;
2453 }
2454
2455 static const IAudioSessionControl2Vtbl AudioSessionControl2_Vtbl =
2456 {
2457     AudioSessionControl_QueryInterface,
2458     AudioSessionControl_AddRef,
2459     AudioSessionControl_Release,
2460     AudioSessionControl_GetState,
2461     AudioSessionControl_GetDisplayName,
2462     AudioSessionControl_SetDisplayName,
2463     AudioSessionControl_GetIconPath,
2464     AudioSessionControl_SetIconPath,
2465     AudioSessionControl_GetGroupingParam,
2466     AudioSessionControl_SetGroupingParam,
2467     AudioSessionControl_RegisterAudioSessionNotification,
2468     AudioSessionControl_UnregisterAudioSessionNotification,
2469     AudioSessionControl_GetSessionIdentifier,
2470     AudioSessionControl_GetSessionInstanceIdentifier,
2471     AudioSessionControl_GetProcessId,
2472     AudioSessionControl_IsSystemSoundsSession,
2473     AudioSessionControl_SetDuckingPreference
2474 };
2475
2476 /* index == -1 means set all channels, otherwise sets only the given channel */
2477 static HRESULT ca_setvol(ACImpl *This, UINT32 index)
2478 {
2479     float level;
2480     OSStatus sc;
2481
2482     if(index == (UINT32)-1){
2483         HRESULT ret = S_OK;
2484         UINT32 i;
2485         for(i = 0; i < This->fmt->nChannels; ++i){
2486             HRESULT hr;
2487             hr = ca_setvol(This, i);
2488             if(FAILED(hr))
2489                 ret = hr;
2490         }
2491         return ret;
2492     }
2493
2494     if(This->session->mute)
2495         level = 0;
2496     else
2497         level = This->session->master_vol *
2498             This->session->channel_vols[index] * This->vols[index];
2499
2500     sc = AudioQueueSetParameter(This->aqueue, kAudioQueueParam_Volume, level);
2501     if(sc != noErr)
2502         WARN("Setting _Volume property failed: %lx\n", sc);
2503
2504     return S_OK;
2505 }
2506
2507 static HRESULT ca_session_setvol(AudioSession *session, UINT32 index)
2508 {
2509     HRESULT ret = S_OK;
2510     ACImpl *client;
2511
2512     LIST_FOR_EACH_ENTRY(client, &session->clients, ACImpl, entry){
2513         HRESULT hr;
2514         hr = ca_setvol(client, index);
2515         if(FAILED(hr))
2516             ret = hr;
2517     }
2518
2519     return ret;
2520 }
2521
2522 static HRESULT WINAPI SimpleAudioVolume_QueryInterface(
2523         ISimpleAudioVolume *iface, REFIID riid, void **ppv)
2524 {
2525     TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
2526
2527     if(!ppv)
2528         return E_POINTER;
2529     *ppv = NULL;
2530
2531     if(IsEqualIID(riid, &IID_IUnknown) ||
2532             IsEqualIID(riid, &IID_ISimpleAudioVolume))
2533         *ppv = iface;
2534     if(*ppv){
2535         IUnknown_AddRef((IUnknown*)*ppv);
2536         return S_OK;
2537     }
2538
2539     WARN("Unknown interface %s\n", debugstr_guid(riid));
2540     return E_NOINTERFACE;
2541 }
2542
2543 static ULONG WINAPI SimpleAudioVolume_AddRef(ISimpleAudioVolume *iface)
2544 {
2545     AudioSessionWrapper *This = impl_from_ISimpleAudioVolume(iface);
2546     return AudioSessionControl_AddRef(&This->IAudioSessionControl2_iface);
2547 }
2548
2549 static ULONG WINAPI SimpleAudioVolume_Release(ISimpleAudioVolume *iface)
2550 {
2551     AudioSessionWrapper *This = impl_from_ISimpleAudioVolume(iface);
2552     return AudioSessionControl_Release(&This->IAudioSessionControl2_iface);
2553 }
2554
2555 static HRESULT WINAPI SimpleAudioVolume_SetMasterVolume(
2556         ISimpleAudioVolume *iface, float level, const GUID *context)
2557 {
2558     AudioSessionWrapper *This = impl_from_ISimpleAudioVolume(iface);
2559     AudioSession *session = This->session;
2560     HRESULT ret;
2561
2562     TRACE("(%p)->(%f, %s)\n", session, level, wine_dbgstr_guid(context));
2563
2564     if(level < 0.f || level > 1.f)
2565         return E_INVALIDARG;
2566
2567     if(context)
2568         FIXME("Notifications not supported yet\n");
2569
2570     EnterCriticalSection(&session->lock);
2571
2572     session->master_vol = level;
2573
2574     ret = ca_session_setvol(session, -1);
2575
2576     LeaveCriticalSection(&session->lock);
2577
2578     return ret;
2579 }
2580
2581 static HRESULT WINAPI SimpleAudioVolume_GetMasterVolume(
2582         ISimpleAudioVolume *iface, float *level)
2583 {
2584     AudioSessionWrapper *This = impl_from_ISimpleAudioVolume(iface);
2585     AudioSession *session = This->session;
2586
2587     TRACE("(%p)->(%p)\n", session, level);
2588
2589     if(!level)
2590         return NULL_PTR_ERR;
2591
2592     *level = session->master_vol;
2593
2594     return S_OK;
2595 }
2596
2597 static HRESULT WINAPI SimpleAudioVolume_SetMute(ISimpleAudioVolume *iface,
2598         BOOL mute, const GUID *context)
2599 {
2600     AudioSessionWrapper *This = impl_from_ISimpleAudioVolume(iface);
2601     AudioSession *session = This->session;
2602
2603     TRACE("(%p)->(%u, %p)\n", session, mute, context);
2604
2605     if(context)
2606         FIXME("Notifications not supported yet\n");
2607
2608     EnterCriticalSection(&session->lock);
2609
2610     session->mute = mute;
2611
2612     ca_session_setvol(session, -1);
2613
2614     LeaveCriticalSection(&session->lock);
2615
2616     return S_OK;
2617 }
2618
2619 static HRESULT WINAPI SimpleAudioVolume_GetMute(ISimpleAudioVolume *iface,
2620         BOOL *mute)
2621 {
2622     AudioSessionWrapper *This = impl_from_ISimpleAudioVolume(iface);
2623     AudioSession *session = This->session;
2624
2625     TRACE("(%p)->(%p)\n", session, mute);
2626
2627     if(!mute)
2628         return NULL_PTR_ERR;
2629
2630     *mute = session->mute;
2631
2632     return S_OK;
2633 }
2634
2635 static const ISimpleAudioVolumeVtbl SimpleAudioVolume_Vtbl  =
2636 {
2637     SimpleAudioVolume_QueryInterface,
2638     SimpleAudioVolume_AddRef,
2639     SimpleAudioVolume_Release,
2640     SimpleAudioVolume_SetMasterVolume,
2641     SimpleAudioVolume_GetMasterVolume,
2642     SimpleAudioVolume_SetMute,
2643     SimpleAudioVolume_GetMute
2644 };
2645
2646 static HRESULT WINAPI AudioStreamVolume_QueryInterface(
2647         IAudioStreamVolume *iface, REFIID riid, void **ppv)
2648 {
2649     TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
2650
2651     if(!ppv)
2652         return E_POINTER;
2653     *ppv = NULL;
2654
2655     if(IsEqualIID(riid, &IID_IUnknown) ||
2656             IsEqualIID(riid, &IID_IAudioStreamVolume))
2657         *ppv = iface;
2658     if(*ppv){
2659         IUnknown_AddRef((IUnknown*)*ppv);
2660         return S_OK;
2661     }
2662
2663     WARN("Unknown interface %s\n", debugstr_guid(riid));
2664     return E_NOINTERFACE;
2665 }
2666
2667 static ULONG WINAPI AudioStreamVolume_AddRef(IAudioStreamVolume *iface)
2668 {
2669     ACImpl *This = impl_from_IAudioStreamVolume(iface);
2670     return IAudioClient_AddRef(&This->IAudioClient_iface);
2671 }
2672
2673 static ULONG WINAPI AudioStreamVolume_Release(IAudioStreamVolume *iface)
2674 {
2675     ACImpl *This = impl_from_IAudioStreamVolume(iface);
2676     return IAudioClient_Release(&This->IAudioClient_iface);
2677 }
2678
2679 static HRESULT WINAPI AudioStreamVolume_GetChannelCount(
2680         IAudioStreamVolume *iface, UINT32 *out)
2681 {
2682     ACImpl *This = impl_from_IAudioStreamVolume(iface);
2683
2684     TRACE("(%p)->(%p)\n", This, out);
2685
2686     if(!out)
2687         return E_POINTER;
2688
2689     *out = This->fmt->nChannels;
2690
2691     return S_OK;
2692 }
2693
2694 static HRESULT WINAPI AudioStreamVolume_SetChannelVolume(
2695         IAudioStreamVolume *iface, UINT32 index, float level)
2696 {
2697     ACImpl *This = impl_from_IAudioStreamVolume(iface);
2698     HRESULT ret;
2699
2700     TRACE("(%p)->(%d, %f)\n", This, index, level);
2701
2702     if(level < 0.f || level > 1.f)
2703         return E_INVALIDARG;
2704
2705     if(index >= This->fmt->nChannels)
2706         return E_INVALIDARG;
2707
2708     OSSpinLockLock(&This->lock);
2709
2710     This->vols[index] = level;
2711
2712     WARN("AudioQueue doesn't support per-channel volume control\n");
2713     ret = ca_setvol(This, index);
2714
2715     OSSpinLockUnlock(&This->lock);
2716
2717     return ret;
2718 }
2719
2720 static HRESULT WINAPI AudioStreamVolume_GetChannelVolume(
2721         IAudioStreamVolume *iface, UINT32 index, float *level)
2722 {
2723     ACImpl *This = impl_from_IAudioStreamVolume(iface);
2724
2725     TRACE("(%p)->(%d, %p)\n", This, index, level);
2726
2727     if(!level)
2728         return E_POINTER;
2729
2730     if(index >= This->fmt->nChannels)
2731         return E_INVALIDARG;
2732
2733     *level = This->vols[index];
2734
2735     return S_OK;
2736 }
2737
2738 static HRESULT WINAPI AudioStreamVolume_SetAllVolumes(
2739         IAudioStreamVolume *iface, UINT32 count, const float *levels)
2740 {
2741     ACImpl *This = impl_from_IAudioStreamVolume(iface);
2742     int i;
2743     HRESULT ret;
2744
2745     TRACE("(%p)->(%d, %p)\n", This, count, levels);
2746
2747     if(!levels)
2748         return E_POINTER;
2749
2750     if(count != This->fmt->nChannels)
2751         return E_INVALIDARG;
2752
2753     OSSpinLockLock(&This->lock);
2754
2755     for(i = 0; i < count; ++i)
2756         This->vols[i] = levels[i];
2757
2758     ret = ca_setvol(This, -1);
2759
2760     OSSpinLockUnlock(&This->lock);
2761
2762     return ret;
2763 }
2764
2765 static HRESULT WINAPI AudioStreamVolume_GetAllVolumes(
2766         IAudioStreamVolume *iface, UINT32 count, float *levels)
2767 {
2768     ACImpl *This = impl_from_IAudioStreamVolume(iface);
2769     int i;
2770
2771     TRACE("(%p)->(%d, %p)\n", This, count, levels);
2772
2773     if(!levels)
2774         return E_POINTER;
2775
2776     if(count != This->fmt->nChannels)
2777         return E_INVALIDARG;
2778
2779     OSSpinLockLock(&This->lock);
2780
2781     for(i = 0; i < count; ++i)
2782         levels[i] = This->vols[i];
2783
2784     OSSpinLockUnlock(&This->lock);
2785
2786     return S_OK;
2787 }
2788
2789 static const IAudioStreamVolumeVtbl AudioStreamVolume_Vtbl =
2790 {
2791     AudioStreamVolume_QueryInterface,
2792     AudioStreamVolume_AddRef,
2793     AudioStreamVolume_Release,
2794     AudioStreamVolume_GetChannelCount,
2795     AudioStreamVolume_SetChannelVolume,
2796     AudioStreamVolume_GetChannelVolume,
2797     AudioStreamVolume_SetAllVolumes,
2798     AudioStreamVolume_GetAllVolumes
2799 };
2800
2801 static HRESULT WINAPI ChannelAudioVolume_QueryInterface(
2802         IChannelAudioVolume *iface, REFIID riid, void **ppv)
2803 {
2804     TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
2805
2806     if(!ppv)
2807         return E_POINTER;
2808     *ppv = NULL;
2809
2810     if(IsEqualIID(riid, &IID_IUnknown) ||
2811             IsEqualIID(riid, &IID_IChannelAudioVolume))
2812         *ppv = iface;
2813     if(*ppv){
2814         IUnknown_AddRef((IUnknown*)*ppv);
2815         return S_OK;
2816     }
2817
2818     WARN("Unknown interface %s\n", debugstr_guid(riid));
2819     return E_NOINTERFACE;
2820 }
2821
2822 static ULONG WINAPI ChannelAudioVolume_AddRef(IChannelAudioVolume *iface)
2823 {
2824     AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
2825     return AudioSessionControl_AddRef(&This->IAudioSessionControl2_iface);
2826 }
2827
2828 static ULONG WINAPI ChannelAudioVolume_Release(IChannelAudioVolume *iface)
2829 {
2830     AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
2831     return AudioSessionControl_Release(&This->IAudioSessionControl2_iface);
2832 }
2833
2834 static HRESULT WINAPI ChannelAudioVolume_GetChannelCount(
2835         IChannelAudioVolume *iface, UINT32 *out)
2836 {
2837     AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
2838     AudioSession *session = This->session;
2839
2840     TRACE("(%p)->(%p)\n", session, out);
2841
2842     if(!out)
2843         return NULL_PTR_ERR;
2844
2845     *out = session->channel_count;
2846
2847     return S_OK;
2848 }
2849
2850 static HRESULT WINAPI ChannelAudioVolume_SetChannelVolume(
2851         IChannelAudioVolume *iface, UINT32 index, float level,
2852         const GUID *context)
2853 {
2854     AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
2855     AudioSession *session = This->session;
2856     HRESULT ret;
2857
2858     TRACE("(%p)->(%d, %f, %s)\n", session, index, level,
2859             wine_dbgstr_guid(context));
2860
2861     if(level < 0.f || level > 1.f)
2862         return E_INVALIDARG;
2863
2864     if(index >= session->channel_count)
2865         return E_INVALIDARG;
2866
2867     if(context)
2868         FIXME("Notifications not supported yet\n");
2869
2870     EnterCriticalSection(&session->lock);
2871
2872     session->channel_vols[index] = level;
2873
2874     WARN("AudioQueue doesn't support per-channel volume control\n");
2875     ret = ca_session_setvol(session, index);
2876
2877     LeaveCriticalSection(&session->lock);
2878
2879     return ret;
2880 }
2881
2882 static HRESULT WINAPI ChannelAudioVolume_GetChannelVolume(
2883         IChannelAudioVolume *iface, UINT32 index, float *level)
2884 {
2885     AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
2886     AudioSession *session = This->session;
2887
2888     TRACE("(%p)->(%d, %p)\n", session, index, level);
2889
2890     if(!level)
2891         return NULL_PTR_ERR;
2892
2893     if(index >= session->channel_count)
2894         return E_INVALIDARG;
2895
2896     *level = session->channel_vols[index];
2897
2898     return S_OK;
2899 }
2900
2901 static HRESULT WINAPI ChannelAudioVolume_SetAllVolumes(
2902         IChannelAudioVolume *iface, UINT32 count, const float *levels,
2903         const GUID *context)
2904 {
2905     AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
2906     AudioSession *session = This->session;
2907     int i;
2908     HRESULT ret;
2909
2910     TRACE("(%p)->(%d, %p, %s)\n", session, count, levels,
2911             wine_dbgstr_guid(context));
2912
2913     if(!levels)
2914         return NULL_PTR_ERR;
2915
2916     if(count != session->channel_count)
2917         return E_INVALIDARG;
2918
2919     if(context)
2920         FIXME("Notifications not supported yet\n");
2921
2922     EnterCriticalSection(&session->lock);
2923
2924     for(i = 0; i < count; ++i)
2925         session->channel_vols[i] = levels[i];
2926
2927     ret = ca_session_setvol(session, -1);
2928
2929     LeaveCriticalSection(&session->lock);
2930
2931     return ret;
2932 }
2933
2934 static HRESULT WINAPI ChannelAudioVolume_GetAllVolumes(
2935         IChannelAudioVolume *iface, UINT32 count, float *levels)
2936 {
2937     AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
2938     AudioSession *session = This->session;
2939     int i;
2940
2941     TRACE("(%p)->(%d, %p)\n", session, count, levels);
2942
2943     if(!levels)
2944         return NULL_PTR_ERR;
2945
2946     if(count != session->channel_count)
2947         return E_INVALIDARG;
2948
2949     for(i = 0; i < count; ++i)
2950         levels[i] = session->channel_vols[i];
2951
2952     return S_OK;
2953 }
2954
2955 static const IChannelAudioVolumeVtbl ChannelAudioVolume_Vtbl =
2956 {
2957     ChannelAudioVolume_QueryInterface,
2958     ChannelAudioVolume_AddRef,
2959     ChannelAudioVolume_Release,
2960     ChannelAudioVolume_GetChannelCount,
2961     ChannelAudioVolume_SetChannelVolume,
2962     ChannelAudioVolume_GetChannelVolume,
2963     ChannelAudioVolume_SetAllVolumes,
2964     ChannelAudioVolume_GetAllVolumes
2965 };
2966
2967 static HRESULT WINAPI AudioSessionManager_QueryInterface(IAudioSessionManager2 *iface,
2968         REFIID riid, void **ppv)
2969 {
2970     TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
2971
2972     if(!ppv)
2973         return E_POINTER;
2974     *ppv = NULL;
2975
2976     if(IsEqualIID(riid, &IID_IUnknown) ||
2977             IsEqualIID(riid, &IID_IAudioSessionManager) ||
2978             IsEqualIID(riid, &IID_IAudioSessionManager2))
2979         *ppv = iface;
2980     if(*ppv){
2981         IUnknown_AddRef((IUnknown*)*ppv);
2982         return S_OK;
2983     }
2984
2985     WARN("Unknown interface %s\n", debugstr_guid(riid));
2986     return E_NOINTERFACE;
2987 }
2988
2989 static ULONG WINAPI AudioSessionManager_AddRef(IAudioSessionManager2 *iface)
2990 {
2991     SessionMgr *This = impl_from_IAudioSessionManager2(iface);
2992     ULONG ref;
2993     ref = InterlockedIncrement(&This->ref);
2994     TRACE("(%p) Refcount now %u\n", This, ref);
2995     return ref;
2996 }
2997
2998 static ULONG WINAPI AudioSessionManager_Release(IAudioSessionManager2 *iface)
2999 {
3000     SessionMgr *This = impl_from_IAudioSessionManager2(iface);
3001     ULONG ref;
3002     ref = InterlockedDecrement(&This->ref);
3003     TRACE("(%p) Refcount now %u\n", This, ref);
3004     if(!ref)
3005         HeapFree(GetProcessHeap(), 0, This);
3006     return ref;
3007 }
3008
3009 static HRESULT WINAPI AudioSessionManager_GetAudioSessionControl(
3010         IAudioSessionManager2 *iface, const GUID *session_guid, DWORD flags,
3011         IAudioSessionControl **out)
3012 {
3013     SessionMgr *This = impl_from_IAudioSessionManager2(iface);
3014     AudioSession *session;
3015     AudioSessionWrapper *wrapper;
3016     HRESULT hr;
3017
3018     TRACE("(%p)->(%s, %x, %p)\n", This, debugstr_guid(session_guid),
3019             flags, out);
3020
3021     hr = get_audio_session(session_guid, This->device, 0, &session);
3022     if(FAILED(hr))
3023         return hr;
3024
3025     wrapper = AudioSessionWrapper_Create(NULL);
3026     if(!wrapper)
3027         return E_OUTOFMEMORY;
3028
3029     wrapper->session = session;
3030
3031     *out = (IAudioSessionControl*)&wrapper->IAudioSessionControl2_iface;
3032
3033     return S_OK;
3034 }
3035
3036 static HRESULT WINAPI AudioSessionManager_GetSimpleAudioVolume(
3037         IAudioSessionManager2 *iface, const GUID *session_guid, DWORD flags,
3038         ISimpleAudioVolume **out)
3039 {
3040     SessionMgr *This = impl_from_IAudioSessionManager2(iface);
3041     AudioSession *session;
3042     AudioSessionWrapper *wrapper;
3043     HRESULT hr;
3044
3045     TRACE("(%p)->(%s, %x, %p)\n", This, debugstr_guid(session_guid),
3046             flags, out);
3047
3048     hr = get_audio_session(session_guid, This->device, 0, &session);
3049     if(FAILED(hr))
3050         return hr;
3051
3052     wrapper = AudioSessionWrapper_Create(NULL);
3053     if(!wrapper)
3054         return E_OUTOFMEMORY;
3055
3056     wrapper->session = session;
3057
3058     *out = &wrapper->ISimpleAudioVolume_iface;
3059
3060     return S_OK;
3061 }
3062
3063 static HRESULT WINAPI AudioSessionManager_GetSessionEnumerator(
3064         IAudioSessionManager2 *iface, IAudioSessionEnumerator **out)
3065 {
3066     SessionMgr *This = impl_from_IAudioSessionManager2(iface);
3067     FIXME("(%p)->(%p) - stub\n", This, out);
3068     return E_NOTIMPL;
3069 }
3070
3071 static HRESULT WINAPI AudioSessionManager_RegisterSessionNotification(
3072         IAudioSessionManager2 *iface, IAudioSessionNotification *notification)
3073 {
3074     SessionMgr *This = impl_from_IAudioSessionManager2(iface);
3075     FIXME("(%p)->(%p) - stub\n", This, notification);
3076     return E_NOTIMPL;
3077 }
3078
3079 static HRESULT WINAPI AudioSessionManager_UnregisterSessionNotification(
3080         IAudioSessionManager2 *iface, IAudioSessionNotification *notification)
3081 {
3082     SessionMgr *This = impl_from_IAudioSessionManager2(iface);
3083     FIXME("(%p)->(%p) - stub\n", This, notification);
3084     return E_NOTIMPL;
3085 }
3086
3087 static HRESULT WINAPI AudioSessionManager_RegisterDuckNotification(
3088         IAudioSessionManager2 *iface, const WCHAR *session_id,
3089         IAudioVolumeDuckNotification *notification)
3090 {
3091     SessionMgr *This = impl_from_IAudioSessionManager2(iface);
3092     FIXME("(%p)->(%p) - stub\n", This, notification);
3093     return E_NOTIMPL;
3094 }
3095
3096 static HRESULT WINAPI AudioSessionManager_UnregisterDuckNotification(
3097         IAudioSessionManager2 *iface,
3098         IAudioVolumeDuckNotification *notification)
3099 {
3100     SessionMgr *This = impl_from_IAudioSessionManager2(iface);
3101     FIXME("(%p)->(%p) - stub\n", This, notification);
3102     return E_NOTIMPL;
3103 }
3104
3105 static const IAudioSessionManager2Vtbl AudioSessionManager2_Vtbl =
3106 {
3107     AudioSessionManager_QueryInterface,
3108     AudioSessionManager_AddRef,
3109     AudioSessionManager_Release,
3110     AudioSessionManager_GetAudioSessionControl,
3111     AudioSessionManager_GetSimpleAudioVolume,
3112     AudioSessionManager_GetSessionEnumerator,
3113     AudioSessionManager_RegisterSessionNotification,
3114     AudioSessionManager_UnregisterSessionNotification,
3115     AudioSessionManager_RegisterDuckNotification,
3116     AudioSessionManager_UnregisterDuckNotification
3117 };
3118
3119 HRESULT WINAPI AUDDRV_GetAudioSessionManager(IMMDevice *device,
3120         IAudioSessionManager2 **out)
3121 {
3122     SessionMgr *This;
3123
3124     This = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(SessionMgr));
3125     if(!This)
3126         return E_OUTOFMEMORY;
3127
3128     This->IAudioSessionManager2_iface.lpVtbl = &AudioSessionManager2_Vtbl;
3129     This->device = device;
3130     This->ref = 1;
3131
3132     *out = &This->IAudioSessionManager2_iface;
3133
3134     return S_OK;
3135 }