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