mshtml: Don't use PRInt32 in property getters implementations.
[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
1486     LeaveCriticalSection(&This->lock);
1487
1488     if(This->event)
1489         SetEvent(This->event);
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     if (This->event){
1624         LeaveCriticalSection(&This->lock);
1625         FIXME("called twice\n");
1626         return HRESULT_FROM_WIN32(ERROR_INVALID_NAME);
1627     }
1628
1629     This->event = event;
1630
1631     LeaveCriticalSection(&This->lock);
1632
1633     return S_OK;
1634 }
1635
1636 static HRESULT WINAPI AudioClient_GetService(IAudioClient *iface, REFIID riid,
1637         void **ppv)
1638 {
1639     ACImpl *This = impl_from_IAudioClient(iface);
1640
1641     TRACE("(%p)->(%s, %p)\n", This, debugstr_guid(riid), ppv);
1642
1643     if(!ppv)
1644         return E_POINTER;
1645     *ppv = NULL;
1646
1647     EnterCriticalSection(&This->lock);
1648
1649     if(!This->initted){
1650         LeaveCriticalSection(&This->lock);
1651         return AUDCLNT_E_NOT_INITIALIZED;
1652     }
1653
1654     if(IsEqualIID(riid, &IID_IAudioRenderClient)){
1655         if(This->dataflow != eRender){
1656             LeaveCriticalSection(&This->lock);
1657             return AUDCLNT_E_WRONG_ENDPOINT_TYPE;
1658         }
1659         IAudioRenderClient_AddRef(&This->IAudioRenderClient_iface);
1660         *ppv = &This->IAudioRenderClient_iface;
1661     }else if(IsEqualIID(riid, &IID_IAudioCaptureClient)){
1662         if(This->dataflow != eCapture){
1663             LeaveCriticalSection(&This->lock);
1664             return AUDCLNT_E_WRONG_ENDPOINT_TYPE;
1665         }
1666         IAudioCaptureClient_AddRef(&This->IAudioCaptureClient_iface);
1667         *ppv = &This->IAudioCaptureClient_iface;
1668     }else if(IsEqualIID(riid, &IID_IAudioClock)){
1669         IAudioClock_AddRef(&This->IAudioClock_iface);
1670         *ppv = &This->IAudioClock_iface;
1671     }else if(IsEqualIID(riid, &IID_IAudioStreamVolume)){
1672         IAudioStreamVolume_AddRef(&This->IAudioStreamVolume_iface);
1673         *ppv = &This->IAudioStreamVolume_iface;
1674     }else if(IsEqualIID(riid, &IID_IAudioSessionControl)){
1675         if(!This->session_wrapper){
1676             This->session_wrapper = AudioSessionWrapper_Create(This);
1677             if(!This->session_wrapper){
1678                 LeaveCriticalSection(&This->lock);
1679                 return E_OUTOFMEMORY;
1680             }
1681         }else
1682             IAudioSessionControl2_AddRef(&This->session_wrapper->IAudioSessionControl2_iface);
1683
1684         *ppv = &This->session_wrapper->IAudioSessionControl2_iface;
1685     }else if(IsEqualIID(riid, &IID_IChannelAudioVolume)){
1686         if(!This->session_wrapper){
1687             This->session_wrapper = AudioSessionWrapper_Create(This);
1688             if(!This->session_wrapper){
1689                 LeaveCriticalSection(&This->lock);
1690                 return E_OUTOFMEMORY;
1691             }
1692         }else
1693             IChannelAudioVolume_AddRef(&This->session_wrapper->IChannelAudioVolume_iface);
1694
1695         *ppv = &This->session_wrapper->IChannelAudioVolume_iface;
1696     }else if(IsEqualIID(riid, &IID_ISimpleAudioVolume)){
1697         if(!This->session_wrapper){
1698             This->session_wrapper = AudioSessionWrapper_Create(This);
1699             if(!This->session_wrapper){
1700                 LeaveCriticalSection(&This->lock);
1701                 return E_OUTOFMEMORY;
1702             }
1703         }else
1704             ISimpleAudioVolume_AddRef(&This->session_wrapper->ISimpleAudioVolume_iface);
1705
1706         *ppv = &This->session_wrapper->ISimpleAudioVolume_iface;
1707     }
1708
1709     if(*ppv){
1710         LeaveCriticalSection(&This->lock);
1711         return S_OK;
1712     }
1713
1714     LeaveCriticalSection(&This->lock);
1715
1716     FIXME("stub %s\n", debugstr_guid(riid));
1717     return E_NOINTERFACE;
1718 }
1719
1720 static const IAudioClientVtbl AudioClient_Vtbl =
1721 {
1722     AudioClient_QueryInterface,
1723     AudioClient_AddRef,
1724     AudioClient_Release,
1725     AudioClient_Initialize,
1726     AudioClient_GetBufferSize,
1727     AudioClient_GetStreamLatency,
1728     AudioClient_GetCurrentPadding,
1729     AudioClient_IsFormatSupported,
1730     AudioClient_GetMixFormat,
1731     AudioClient_GetDevicePeriod,
1732     AudioClient_Start,
1733     AudioClient_Stop,
1734     AudioClient_Reset,
1735     AudioClient_SetEventHandle,
1736     AudioClient_GetService
1737 };
1738
1739 static HRESULT WINAPI AudioRenderClient_QueryInterface(
1740         IAudioRenderClient *iface, REFIID riid, void **ppv)
1741 {
1742     TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
1743
1744     if(!ppv)
1745         return E_POINTER;
1746     *ppv = NULL;
1747
1748     if(IsEqualIID(riid, &IID_IUnknown) ||
1749             IsEqualIID(riid, &IID_IAudioRenderClient))
1750         *ppv = iface;
1751     if(*ppv){
1752         IUnknown_AddRef((IUnknown*)*ppv);
1753         return S_OK;
1754     }
1755
1756     WARN("Unknown interface %s\n", debugstr_guid(riid));
1757     return E_NOINTERFACE;
1758 }
1759
1760 static ULONG WINAPI AudioRenderClient_AddRef(IAudioRenderClient *iface)
1761 {
1762     ACImpl *This = impl_from_IAudioRenderClient(iface);
1763     return AudioClient_AddRef(&This->IAudioClient_iface);
1764 }
1765
1766 static ULONG WINAPI AudioRenderClient_Release(IAudioRenderClient *iface)
1767 {
1768     ACImpl *This = impl_from_IAudioRenderClient(iface);
1769     return AudioClient_Release(&This->IAudioClient_iface);
1770 }
1771
1772 static HRESULT WINAPI AudioRenderClient_GetBuffer(IAudioRenderClient *iface,
1773         UINT32 frames, BYTE **data)
1774 {
1775     ACImpl *This = impl_from_IAudioRenderClient(iface);
1776     UINT32 write_pos;
1777
1778     TRACE("(%p)->(%u, %p)\n", This, frames, data);
1779
1780     if(!data)
1781         return E_POINTER;
1782
1783     *data = NULL;
1784
1785     EnterCriticalSection(&This->lock);
1786
1787     if(This->getbuf_last){
1788         LeaveCriticalSection(&This->lock);
1789         return AUDCLNT_E_OUT_OF_ORDER;
1790     }
1791
1792     if(!frames){
1793         LeaveCriticalSection(&This->lock);
1794         return S_OK;
1795     }
1796
1797     if(This->held_frames + frames > This->bufsize_frames){
1798         LeaveCriticalSection(&This->lock);
1799         return AUDCLNT_E_BUFFER_TOO_LARGE;
1800     }
1801
1802     write_pos =
1803         (This->lcl_offs_frames + This->held_frames) % This->bufsize_frames;
1804     if(write_pos + frames > This->bufsize_frames){
1805         if(This->tmp_buffer_frames < frames){
1806             HeapFree(GetProcessHeap(), 0, This->tmp_buffer);
1807             This->tmp_buffer = HeapAlloc(GetProcessHeap(), 0,
1808                     frames * This->fmt->nBlockAlign);
1809             if(!This->tmp_buffer){
1810                 LeaveCriticalSection(&This->lock);
1811                 return E_OUTOFMEMORY;
1812             }
1813             This->tmp_buffer_frames = frames;
1814         }
1815         *data = This->tmp_buffer;
1816         This->getbuf_last = -frames;
1817     }else{
1818         *data = This->local_buffer + write_pos * This->fmt->nBlockAlign;
1819         This->getbuf_last = frames;
1820     }
1821
1822     LeaveCriticalSection(&This->lock);
1823
1824     return S_OK;
1825 }
1826
1827 static void oss_wrap_buffer(ACImpl *This, BYTE *buffer, UINT32 written_frames)
1828 {
1829     UINT32 write_offs_frames =
1830         (This->lcl_offs_frames + This->held_frames) % This->bufsize_frames;
1831     UINT32 write_offs_bytes = write_offs_frames * This->fmt->nBlockAlign;
1832     UINT32 chunk_frames = This->bufsize_frames - write_offs_frames;
1833     UINT32 chunk_bytes = chunk_frames * This->fmt->nBlockAlign;
1834     UINT32 written_bytes = written_frames * This->fmt->nBlockAlign;
1835
1836     if(written_bytes <= chunk_bytes){
1837         memcpy(This->local_buffer + write_offs_bytes, buffer, written_bytes);
1838     }else{
1839         memcpy(This->local_buffer + write_offs_bytes, buffer, chunk_bytes);
1840         memcpy(This->local_buffer, buffer + chunk_bytes,
1841                 written_bytes - chunk_bytes);
1842     }
1843 }
1844
1845 static HRESULT WINAPI AudioRenderClient_ReleaseBuffer(
1846         IAudioRenderClient *iface, UINT32 written_frames, DWORD flags)
1847 {
1848     ACImpl *This = impl_from_IAudioRenderClient(iface);
1849     BYTE *buffer;
1850
1851     TRACE("(%p)->(%u, %x)\n", This, written_frames, flags);
1852
1853     EnterCriticalSection(&This->lock);
1854
1855     if(!written_frames){
1856         This->getbuf_last = 0;
1857         LeaveCriticalSection(&This->lock);
1858         return S_OK;
1859     }
1860
1861     if(!This->getbuf_last){
1862         LeaveCriticalSection(&This->lock);
1863         return AUDCLNT_E_OUT_OF_ORDER;
1864     }
1865
1866     if(written_frames > (This->getbuf_last >= 0 ? This->getbuf_last : -This->getbuf_last)){
1867         LeaveCriticalSection(&This->lock);
1868         return AUDCLNT_E_INVALID_SIZE;
1869     }
1870
1871     if(This->getbuf_last >= 0)
1872         buffer = This->local_buffer + This->fmt->nBlockAlign *
1873           ((This->lcl_offs_frames + This->held_frames) % This->bufsize_frames);
1874     else
1875         buffer = This->tmp_buffer;
1876
1877     if(flags & AUDCLNT_BUFFERFLAGS_SILENT)
1878         oss_silence_buffer(This, buffer, written_frames);
1879
1880     if(This->getbuf_last < 0)
1881         oss_wrap_buffer(This, buffer, written_frames);
1882
1883     This->held_frames += written_frames;
1884     This->written_frames += written_frames;
1885     This->getbuf_last = 0;
1886
1887     LeaveCriticalSection(&This->lock);
1888
1889     return S_OK;
1890 }
1891
1892 static const IAudioRenderClientVtbl AudioRenderClient_Vtbl = {
1893     AudioRenderClient_QueryInterface,
1894     AudioRenderClient_AddRef,
1895     AudioRenderClient_Release,
1896     AudioRenderClient_GetBuffer,
1897     AudioRenderClient_ReleaseBuffer
1898 };
1899
1900 static HRESULT WINAPI AudioCaptureClient_QueryInterface(
1901         IAudioCaptureClient *iface, REFIID riid, void **ppv)
1902 {
1903     TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
1904
1905     if(!ppv)
1906         return E_POINTER;
1907     *ppv = NULL;
1908
1909     if(IsEqualIID(riid, &IID_IUnknown) ||
1910             IsEqualIID(riid, &IID_IAudioCaptureClient))
1911         *ppv = iface;
1912     if(*ppv){
1913         IUnknown_AddRef((IUnknown*)*ppv);
1914         return S_OK;
1915     }
1916
1917     WARN("Unknown interface %s\n", debugstr_guid(riid));
1918     return E_NOINTERFACE;
1919 }
1920
1921 static ULONG WINAPI AudioCaptureClient_AddRef(IAudioCaptureClient *iface)
1922 {
1923     ACImpl *This = impl_from_IAudioCaptureClient(iface);
1924     return IAudioClient_AddRef(&This->IAudioClient_iface);
1925 }
1926
1927 static ULONG WINAPI AudioCaptureClient_Release(IAudioCaptureClient *iface)
1928 {
1929     ACImpl *This = impl_from_IAudioCaptureClient(iface);
1930     return IAudioClient_Release(&This->IAudioClient_iface);
1931 }
1932
1933 static HRESULT WINAPI AudioCaptureClient_GetBuffer(IAudioCaptureClient *iface,
1934         BYTE **data, UINT32 *frames, DWORD *flags, UINT64 *devpos,
1935         UINT64 *qpcpos)
1936 {
1937     ACImpl *This = impl_from_IAudioCaptureClient(iface);
1938
1939     TRACE("(%p)->(%p, %p, %p, %p, %p)\n", This, data, frames, flags,
1940             devpos, qpcpos);
1941
1942     if(!data || !frames || !flags)
1943         return E_POINTER;
1944
1945     EnterCriticalSection(&This->lock);
1946
1947     if(This->getbuf_last){
1948         LeaveCriticalSection(&This->lock);
1949         return AUDCLNT_E_OUT_OF_ORDER;
1950     }
1951
1952     if(This->held_frames < This->period_frames){
1953         *frames = 0;
1954         LeaveCriticalSection(&This->lock);
1955         return AUDCLNT_S_BUFFER_EMPTY;
1956     }
1957
1958     *flags = 0;
1959
1960     *frames = This->period_frames;
1961
1962     if(This->lcl_offs_frames + *frames > This->bufsize_frames){
1963         UINT32 chunk_bytes, offs_bytes, frames_bytes;
1964         if(This->tmp_buffer_frames < *frames){
1965             HeapFree(GetProcessHeap(), 0, This->tmp_buffer);
1966             This->tmp_buffer = HeapAlloc(GetProcessHeap(), 0,
1967                     *frames * This->fmt->nBlockAlign);
1968             if(!This->tmp_buffer){
1969                 LeaveCriticalSection(&This->lock);
1970                 return E_OUTOFMEMORY;
1971             }
1972             This->tmp_buffer_frames = *frames;
1973         }
1974
1975         *data = This->tmp_buffer;
1976         chunk_bytes = (This->bufsize_frames - This->lcl_offs_frames) *
1977             This->fmt->nBlockAlign;
1978         offs_bytes = This->lcl_offs_frames * This->fmt->nBlockAlign;
1979         frames_bytes = *frames * This->fmt->nBlockAlign;
1980         memcpy(This->tmp_buffer, This->local_buffer + offs_bytes, chunk_bytes);
1981         memcpy(This->tmp_buffer + chunk_bytes, This->local_buffer,
1982                 frames_bytes - chunk_bytes);
1983     }else
1984         *data = This->local_buffer +
1985             This->lcl_offs_frames * This->fmt->nBlockAlign;
1986
1987     This->getbuf_last = *frames;
1988
1989     if(devpos)
1990        *devpos = This->written_frames;
1991     if(qpcpos){
1992         LARGE_INTEGER stamp, freq;
1993         QueryPerformanceCounter(&stamp);
1994         QueryPerformanceFrequency(&freq);
1995         *qpcpos = (stamp.QuadPart * (INT64)10000000) / freq.QuadPart;
1996     }
1997
1998     LeaveCriticalSection(&This->lock);
1999
2000     return *frames ? S_OK : AUDCLNT_S_BUFFER_EMPTY;
2001 }
2002
2003 static HRESULT WINAPI AudioCaptureClient_ReleaseBuffer(
2004         IAudioCaptureClient *iface, UINT32 done)
2005 {
2006     ACImpl *This = impl_from_IAudioCaptureClient(iface);
2007
2008     TRACE("(%p)->(%u)\n", This, done);
2009
2010     EnterCriticalSection(&This->lock);
2011
2012     if(!done){
2013         This->getbuf_last = 0;
2014         LeaveCriticalSection(&This->lock);
2015         return S_OK;
2016     }
2017
2018     if(!This->getbuf_last){
2019         LeaveCriticalSection(&This->lock);
2020         return AUDCLNT_E_OUT_OF_ORDER;
2021     }
2022
2023     if(This->getbuf_last != done){
2024         LeaveCriticalSection(&This->lock);
2025         return AUDCLNT_E_INVALID_SIZE;
2026     }
2027
2028     This->written_frames += done;
2029     This->held_frames -= done;
2030     This->lcl_offs_frames += done;
2031     This->lcl_offs_frames %= This->bufsize_frames;
2032     This->getbuf_last = 0;
2033
2034     LeaveCriticalSection(&This->lock);
2035
2036     return S_OK;
2037 }
2038
2039 static HRESULT WINAPI AudioCaptureClient_GetNextPacketSize(
2040         IAudioCaptureClient *iface, UINT32 *frames)
2041 {
2042     ACImpl *This = impl_from_IAudioCaptureClient(iface);
2043
2044     TRACE("(%p)->(%p)\n", This, frames);
2045
2046     if(!frames)
2047         return E_POINTER;
2048
2049     EnterCriticalSection(&This->lock);
2050
2051     *frames = This->held_frames < This->period_frames ? 0 : This->period_frames;
2052
2053     LeaveCriticalSection(&This->lock);
2054
2055     return S_OK;
2056 }
2057
2058 static const IAudioCaptureClientVtbl AudioCaptureClient_Vtbl =
2059 {
2060     AudioCaptureClient_QueryInterface,
2061     AudioCaptureClient_AddRef,
2062     AudioCaptureClient_Release,
2063     AudioCaptureClient_GetBuffer,
2064     AudioCaptureClient_ReleaseBuffer,
2065     AudioCaptureClient_GetNextPacketSize
2066 };
2067
2068 static HRESULT WINAPI AudioClock_QueryInterface(IAudioClock *iface,
2069         REFIID riid, void **ppv)
2070 {
2071     ACImpl *This = impl_from_IAudioClock(iface);
2072
2073     TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
2074
2075     if(!ppv)
2076         return E_POINTER;
2077     *ppv = NULL;
2078
2079     if(IsEqualIID(riid, &IID_IUnknown) || IsEqualIID(riid, &IID_IAudioClock))
2080         *ppv = iface;
2081     else if(IsEqualIID(riid, &IID_IAudioClock2))
2082         *ppv = &This->IAudioClock2_iface;
2083     if(*ppv){
2084         IUnknown_AddRef((IUnknown*)*ppv);
2085         return S_OK;
2086     }
2087
2088     WARN("Unknown interface %s\n", debugstr_guid(riid));
2089     return E_NOINTERFACE;
2090 }
2091
2092 static ULONG WINAPI AudioClock_AddRef(IAudioClock *iface)
2093 {
2094     ACImpl *This = impl_from_IAudioClock(iface);
2095     return IAudioClient_AddRef(&This->IAudioClient_iface);
2096 }
2097
2098 static ULONG WINAPI AudioClock_Release(IAudioClock *iface)
2099 {
2100     ACImpl *This = impl_from_IAudioClock(iface);
2101     return IAudioClient_Release(&This->IAudioClient_iface);
2102 }
2103
2104 static HRESULT WINAPI AudioClock_GetFrequency(IAudioClock *iface, UINT64 *freq)
2105 {
2106     ACImpl *This = impl_from_IAudioClock(iface);
2107
2108     TRACE("(%p)->(%p)\n", This, freq);
2109
2110     *freq = This->fmt->nSamplesPerSec;
2111
2112     return S_OK;
2113 }
2114
2115 static HRESULT WINAPI AudioClock_GetPosition(IAudioClock *iface, UINT64 *pos,
2116         UINT64 *qpctime)
2117 {
2118     ACImpl *This = impl_from_IAudioClock(iface);
2119     int delay;
2120
2121     TRACE("(%p)->(%p, %p)\n", This, pos, qpctime);
2122
2123     if(!pos)
2124         return E_POINTER;
2125
2126     EnterCriticalSection(&This->lock);
2127
2128     if(This->dataflow == eRender){
2129         if(!This->playing || !This->held_frames ||
2130                 ioctl(This->fd, SNDCTL_DSP_GETODELAY, &delay) < 0)
2131             delay = 0;
2132         else
2133             delay /= This->fmt->nBlockAlign;
2134         if(This->held_frames + delay >= This->written_frames)
2135             *pos = This->last_pos_frames;
2136         else{
2137             *pos = This->written_frames - This->held_frames - delay;
2138             if(*pos < This->last_pos_frames)
2139                 *pos = This->last_pos_frames;
2140         }
2141     }else if(This->dataflow == eCapture){
2142         audio_buf_info bi;
2143         UINT32 held;
2144
2145         if(ioctl(This->fd, SNDCTL_DSP_GETISPACE, &bi) < 0){
2146             TRACE("GETISPACE failed: %d (%s)\n", errno, strerror(errno));
2147             held = 0;
2148         }else{
2149             if(bi.bytes <= bi.fragsize)
2150                 held = 0;
2151             else
2152                 held = bi.bytes / This->fmt->nBlockAlign;
2153         }
2154
2155         *pos = This->written_frames + held;
2156     }
2157
2158     This->last_pos_frames = *pos;
2159
2160     LeaveCriticalSection(&This->lock);
2161
2162     if(qpctime){
2163         LARGE_INTEGER stamp, freq;
2164         QueryPerformanceCounter(&stamp);
2165         QueryPerformanceFrequency(&freq);
2166         *qpctime = (stamp.QuadPart * (INT64)10000000) / freq.QuadPart;
2167     }
2168
2169     return S_OK;
2170 }
2171
2172 static HRESULT WINAPI AudioClock_GetCharacteristics(IAudioClock *iface,
2173         DWORD *chars)
2174 {
2175     ACImpl *This = impl_from_IAudioClock(iface);
2176
2177     TRACE("(%p)->(%p)\n", This, chars);
2178
2179     if(!chars)
2180         return E_POINTER;
2181
2182     *chars = AUDIOCLOCK_CHARACTERISTIC_FIXED_FREQ;
2183
2184     return S_OK;
2185 }
2186
2187 static const IAudioClockVtbl AudioClock_Vtbl =
2188 {
2189     AudioClock_QueryInterface,
2190     AudioClock_AddRef,
2191     AudioClock_Release,
2192     AudioClock_GetFrequency,
2193     AudioClock_GetPosition,
2194     AudioClock_GetCharacteristics
2195 };
2196
2197 static HRESULT WINAPI AudioClock2_QueryInterface(IAudioClock2 *iface,
2198         REFIID riid, void **ppv)
2199 {
2200     ACImpl *This = impl_from_IAudioClock2(iface);
2201     return IAudioClock_QueryInterface(&This->IAudioClock_iface, riid, ppv);
2202 }
2203
2204 static ULONG WINAPI AudioClock2_AddRef(IAudioClock2 *iface)
2205 {
2206     ACImpl *This = impl_from_IAudioClock2(iface);
2207     return IAudioClient_AddRef(&This->IAudioClient_iface);
2208 }
2209
2210 static ULONG WINAPI AudioClock2_Release(IAudioClock2 *iface)
2211 {
2212     ACImpl *This = impl_from_IAudioClock2(iface);
2213     return IAudioClient_Release(&This->IAudioClient_iface);
2214 }
2215
2216 static HRESULT WINAPI AudioClock2_GetDevicePosition(IAudioClock2 *iface,
2217         UINT64 *pos, UINT64 *qpctime)
2218 {
2219     ACImpl *This = impl_from_IAudioClock2(iface);
2220
2221     FIXME("(%p)->(%p, %p)\n", This, pos, qpctime);
2222
2223     return E_NOTIMPL;
2224 }
2225
2226 static const IAudioClock2Vtbl AudioClock2_Vtbl =
2227 {
2228     AudioClock2_QueryInterface,
2229     AudioClock2_AddRef,
2230     AudioClock2_Release,
2231     AudioClock2_GetDevicePosition
2232 };
2233
2234 static AudioSessionWrapper *AudioSessionWrapper_Create(ACImpl *client)
2235 {
2236     AudioSessionWrapper *ret;
2237
2238     ret = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
2239             sizeof(AudioSessionWrapper));
2240     if(!ret)
2241         return NULL;
2242
2243     ret->IAudioSessionControl2_iface.lpVtbl = &AudioSessionControl2_Vtbl;
2244     ret->ISimpleAudioVolume_iface.lpVtbl = &SimpleAudioVolume_Vtbl;
2245     ret->IChannelAudioVolume_iface.lpVtbl = &ChannelAudioVolume_Vtbl;
2246
2247     ret->ref = 1;
2248
2249     ret->client = client;
2250     if(client){
2251         ret->session = client->session;
2252         AudioClient_AddRef(&client->IAudioClient_iface);
2253     }
2254
2255     return ret;
2256 }
2257
2258 static HRESULT WINAPI AudioSessionControl_QueryInterface(
2259         IAudioSessionControl2 *iface, REFIID riid, void **ppv)
2260 {
2261     TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
2262
2263     if(!ppv)
2264         return E_POINTER;
2265     *ppv = NULL;
2266
2267     if(IsEqualIID(riid, &IID_IUnknown) ||
2268             IsEqualIID(riid, &IID_IAudioSessionControl) ||
2269             IsEqualIID(riid, &IID_IAudioSessionControl2))
2270         *ppv = iface;
2271     if(*ppv){
2272         IUnknown_AddRef((IUnknown*)*ppv);
2273         return S_OK;
2274     }
2275
2276     WARN("Unknown interface %s\n", debugstr_guid(riid));
2277     return E_NOINTERFACE;
2278 }
2279
2280 static ULONG WINAPI AudioSessionControl_AddRef(IAudioSessionControl2 *iface)
2281 {
2282     AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2283     ULONG ref;
2284     ref = InterlockedIncrement(&This->ref);
2285     TRACE("(%p) Refcount now %u\n", This, ref);
2286     return ref;
2287 }
2288
2289 static ULONG WINAPI AudioSessionControl_Release(IAudioSessionControl2 *iface)
2290 {
2291     AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2292     ULONG ref;
2293     ref = InterlockedDecrement(&This->ref);
2294     TRACE("(%p) Refcount now %u\n", This, ref);
2295     if(!ref){
2296         if(This->client){
2297             EnterCriticalSection(&This->client->lock);
2298             This->client->session_wrapper = NULL;
2299             LeaveCriticalSection(&This->client->lock);
2300             AudioClient_Release(&This->client->IAudioClient_iface);
2301         }
2302         HeapFree(GetProcessHeap(), 0, This);
2303     }
2304     return ref;
2305 }
2306
2307 static HRESULT WINAPI AudioSessionControl_GetState(IAudioSessionControl2 *iface,
2308         AudioSessionState *state)
2309 {
2310     AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2311     ACImpl *client;
2312
2313     TRACE("(%p)->(%p)\n", This, state);
2314
2315     if(!state)
2316         return NULL_PTR_ERR;
2317
2318     EnterCriticalSection(&g_sessions_lock);
2319
2320     if(list_empty(&This->session->clients)){
2321         *state = AudioSessionStateExpired;
2322         LeaveCriticalSection(&g_sessions_lock);
2323         return S_OK;
2324     }
2325
2326     LIST_FOR_EACH_ENTRY(client, &This->session->clients, ACImpl, entry){
2327         EnterCriticalSection(&client->lock);
2328         if(client->playing){
2329             *state = AudioSessionStateActive;
2330             LeaveCriticalSection(&client->lock);
2331             LeaveCriticalSection(&g_sessions_lock);
2332             return S_OK;
2333         }
2334         LeaveCriticalSection(&client->lock);
2335     }
2336
2337     LeaveCriticalSection(&g_sessions_lock);
2338
2339     *state = AudioSessionStateInactive;
2340
2341     return S_OK;
2342 }
2343
2344 static HRESULT WINAPI AudioSessionControl_GetDisplayName(
2345         IAudioSessionControl2 *iface, WCHAR **name)
2346 {
2347     AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2348
2349     FIXME("(%p)->(%p) - stub\n", This, name);
2350
2351     return E_NOTIMPL;
2352 }
2353
2354 static HRESULT WINAPI AudioSessionControl_SetDisplayName(
2355         IAudioSessionControl2 *iface, const WCHAR *name, const GUID *session)
2356 {
2357     AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2358
2359     FIXME("(%p)->(%p, %s) - stub\n", This, name, debugstr_guid(session));
2360
2361     return E_NOTIMPL;
2362 }
2363
2364 static HRESULT WINAPI AudioSessionControl_GetIconPath(
2365         IAudioSessionControl2 *iface, WCHAR **path)
2366 {
2367     AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2368
2369     FIXME("(%p)->(%p) - stub\n", This, path);
2370
2371     return E_NOTIMPL;
2372 }
2373
2374 static HRESULT WINAPI AudioSessionControl_SetIconPath(
2375         IAudioSessionControl2 *iface, const WCHAR *path, const GUID *session)
2376 {
2377     AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2378
2379     FIXME("(%p)->(%p, %s) - stub\n", This, path, debugstr_guid(session));
2380
2381     return E_NOTIMPL;
2382 }
2383
2384 static HRESULT WINAPI AudioSessionControl_GetGroupingParam(
2385         IAudioSessionControl2 *iface, GUID *group)
2386 {
2387     AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2388
2389     FIXME("(%p)->(%p) - stub\n", This, group);
2390
2391     return E_NOTIMPL;
2392 }
2393
2394 static HRESULT WINAPI AudioSessionControl_SetGroupingParam(
2395         IAudioSessionControl2 *iface, const GUID *group, const GUID *session)
2396 {
2397     AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2398
2399     FIXME("(%p)->(%s, %s) - stub\n", This, debugstr_guid(group),
2400             debugstr_guid(session));
2401
2402     return E_NOTIMPL;
2403 }
2404
2405 static HRESULT WINAPI AudioSessionControl_RegisterAudioSessionNotification(
2406         IAudioSessionControl2 *iface, IAudioSessionEvents *events)
2407 {
2408     AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2409
2410     FIXME("(%p)->(%p) - stub\n", This, events);
2411
2412     return S_OK;
2413 }
2414
2415 static HRESULT WINAPI AudioSessionControl_UnregisterAudioSessionNotification(
2416         IAudioSessionControl2 *iface, IAudioSessionEvents *events)
2417 {
2418     AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2419
2420     FIXME("(%p)->(%p) - stub\n", This, events);
2421
2422     return S_OK;
2423 }
2424
2425 static HRESULT WINAPI AudioSessionControl_GetSessionIdentifier(
2426         IAudioSessionControl2 *iface, WCHAR **id)
2427 {
2428     AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2429
2430     FIXME("(%p)->(%p) - stub\n", This, id);
2431
2432     return E_NOTIMPL;
2433 }
2434
2435 static HRESULT WINAPI AudioSessionControl_GetSessionInstanceIdentifier(
2436         IAudioSessionControl2 *iface, WCHAR **id)
2437 {
2438     AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2439
2440     FIXME("(%p)->(%p) - stub\n", This, id);
2441
2442     return E_NOTIMPL;
2443 }
2444
2445 static HRESULT WINAPI AudioSessionControl_GetProcessId(
2446         IAudioSessionControl2 *iface, DWORD *pid)
2447 {
2448     AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2449
2450     TRACE("(%p)->(%p)\n", This, pid);
2451
2452     if(!pid)
2453         return E_POINTER;
2454
2455     *pid = GetCurrentProcessId();
2456
2457     return S_OK;
2458 }
2459
2460 static HRESULT WINAPI AudioSessionControl_IsSystemSoundsSession(
2461         IAudioSessionControl2 *iface)
2462 {
2463     AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2464
2465     TRACE("(%p)\n", This);
2466
2467     return S_FALSE;
2468 }
2469
2470 static HRESULT WINAPI AudioSessionControl_SetDuckingPreference(
2471         IAudioSessionControl2 *iface, BOOL optout)
2472 {
2473     AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2474
2475     TRACE("(%p)->(%d)\n", This, optout);
2476
2477     return S_OK;
2478 }
2479
2480 static const IAudioSessionControl2Vtbl AudioSessionControl2_Vtbl =
2481 {
2482     AudioSessionControl_QueryInterface,
2483     AudioSessionControl_AddRef,
2484     AudioSessionControl_Release,
2485     AudioSessionControl_GetState,
2486     AudioSessionControl_GetDisplayName,
2487     AudioSessionControl_SetDisplayName,
2488     AudioSessionControl_GetIconPath,
2489     AudioSessionControl_SetIconPath,
2490     AudioSessionControl_GetGroupingParam,
2491     AudioSessionControl_SetGroupingParam,
2492     AudioSessionControl_RegisterAudioSessionNotification,
2493     AudioSessionControl_UnregisterAudioSessionNotification,
2494     AudioSessionControl_GetSessionIdentifier,
2495     AudioSessionControl_GetSessionInstanceIdentifier,
2496     AudioSessionControl_GetProcessId,
2497     AudioSessionControl_IsSystemSoundsSession,
2498     AudioSessionControl_SetDuckingPreference
2499 };
2500
2501 static HRESULT WINAPI SimpleAudioVolume_QueryInterface(
2502         ISimpleAudioVolume *iface, REFIID riid, void **ppv)
2503 {
2504     TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
2505
2506     if(!ppv)
2507         return E_POINTER;
2508     *ppv = NULL;
2509
2510     if(IsEqualIID(riid, &IID_IUnknown) ||
2511             IsEqualIID(riid, &IID_ISimpleAudioVolume))
2512         *ppv = iface;
2513     if(*ppv){
2514         IUnknown_AddRef((IUnknown*)*ppv);
2515         return S_OK;
2516     }
2517
2518     WARN("Unknown interface %s\n", debugstr_guid(riid));
2519     return E_NOINTERFACE;
2520 }
2521
2522 static ULONG WINAPI SimpleAudioVolume_AddRef(ISimpleAudioVolume *iface)
2523 {
2524     AudioSessionWrapper *This = impl_from_ISimpleAudioVolume(iface);
2525     return AudioSessionControl_AddRef(&This->IAudioSessionControl2_iface);
2526 }
2527
2528 static ULONG WINAPI SimpleAudioVolume_Release(ISimpleAudioVolume *iface)
2529 {
2530     AudioSessionWrapper *This = impl_from_ISimpleAudioVolume(iface);
2531     return AudioSessionControl_Release(&This->IAudioSessionControl2_iface);
2532 }
2533
2534 static HRESULT WINAPI SimpleAudioVolume_SetMasterVolume(
2535         ISimpleAudioVolume *iface, float level, const GUID *context)
2536 {
2537     AudioSessionWrapper *This = impl_from_ISimpleAudioVolume(iface);
2538     AudioSession *session = This->session;
2539
2540     TRACE("(%p)->(%f, %s)\n", session, level, wine_dbgstr_guid(context));
2541
2542     if(level < 0.f || level > 1.f)
2543         return E_INVALIDARG;
2544
2545     if(context)
2546         FIXME("Notifications not supported yet\n");
2547
2548     EnterCriticalSection(&session->lock);
2549
2550     session->master_vol = level;
2551
2552     TRACE("OSS doesn't support setting volume\n");
2553
2554     LeaveCriticalSection(&session->lock);
2555
2556     return S_OK;
2557 }
2558
2559 static HRESULT WINAPI SimpleAudioVolume_GetMasterVolume(
2560         ISimpleAudioVolume *iface, float *level)
2561 {
2562     AudioSessionWrapper *This = impl_from_ISimpleAudioVolume(iface);
2563     AudioSession *session = This->session;
2564
2565     TRACE("(%p)->(%p)\n", session, level);
2566
2567     if(!level)
2568         return NULL_PTR_ERR;
2569
2570     *level = session->master_vol;
2571
2572     return S_OK;
2573 }
2574
2575 static HRESULT WINAPI SimpleAudioVolume_SetMute(ISimpleAudioVolume *iface,
2576         BOOL mute, const GUID *context)
2577 {
2578     AudioSessionWrapper *This = impl_from_ISimpleAudioVolume(iface);
2579     AudioSession *session = This->session;
2580
2581     TRACE("(%p)->(%u, %p)\n", session, mute, context);
2582
2583     EnterCriticalSection(&session->lock);
2584
2585     session->mute = mute;
2586
2587     LeaveCriticalSection(&session->lock);
2588
2589     return S_OK;
2590 }
2591
2592 static HRESULT WINAPI SimpleAudioVolume_GetMute(ISimpleAudioVolume *iface,
2593         BOOL *mute)
2594 {
2595     AudioSessionWrapper *This = impl_from_ISimpleAudioVolume(iface);
2596     AudioSession *session = This->session;
2597
2598     TRACE("(%p)->(%p)\n", session, mute);
2599
2600     if(!mute)
2601         return NULL_PTR_ERR;
2602
2603     *mute = This->session->mute;
2604
2605     return S_OK;
2606 }
2607
2608 static const ISimpleAudioVolumeVtbl SimpleAudioVolume_Vtbl  =
2609 {
2610     SimpleAudioVolume_QueryInterface,
2611     SimpleAudioVolume_AddRef,
2612     SimpleAudioVolume_Release,
2613     SimpleAudioVolume_SetMasterVolume,
2614     SimpleAudioVolume_GetMasterVolume,
2615     SimpleAudioVolume_SetMute,
2616     SimpleAudioVolume_GetMute
2617 };
2618
2619 static HRESULT WINAPI AudioStreamVolume_QueryInterface(
2620         IAudioStreamVolume *iface, REFIID riid, void **ppv)
2621 {
2622     TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
2623
2624     if(!ppv)
2625         return E_POINTER;
2626     *ppv = NULL;
2627
2628     if(IsEqualIID(riid, &IID_IUnknown) ||
2629             IsEqualIID(riid, &IID_IAudioStreamVolume))
2630         *ppv = iface;
2631     if(*ppv){
2632         IUnknown_AddRef((IUnknown*)*ppv);
2633         return S_OK;
2634     }
2635
2636     WARN("Unknown interface %s\n", debugstr_guid(riid));
2637     return E_NOINTERFACE;
2638 }
2639
2640 static ULONG WINAPI AudioStreamVolume_AddRef(IAudioStreamVolume *iface)
2641 {
2642     ACImpl *This = impl_from_IAudioStreamVolume(iface);
2643     return IAudioClient_AddRef(&This->IAudioClient_iface);
2644 }
2645
2646 static ULONG WINAPI AudioStreamVolume_Release(IAudioStreamVolume *iface)
2647 {
2648     ACImpl *This = impl_from_IAudioStreamVolume(iface);
2649     return IAudioClient_Release(&This->IAudioClient_iface);
2650 }
2651
2652 static HRESULT WINAPI AudioStreamVolume_GetChannelCount(
2653         IAudioStreamVolume *iface, UINT32 *out)
2654 {
2655     ACImpl *This = impl_from_IAudioStreamVolume(iface);
2656
2657     TRACE("(%p)->(%p)\n", This, out);
2658
2659     if(!out)
2660         return E_POINTER;
2661
2662     *out = This->fmt->nChannels;
2663
2664     return S_OK;
2665 }
2666
2667 static HRESULT WINAPI AudioStreamVolume_SetChannelVolume(
2668         IAudioStreamVolume *iface, UINT32 index, float level)
2669 {
2670     ACImpl *This = impl_from_IAudioStreamVolume(iface);
2671
2672     TRACE("(%p)->(%d, %f)\n", This, index, level);
2673
2674     if(level < 0.f || level > 1.f)
2675         return E_INVALIDARG;
2676
2677     if(index >= This->fmt->nChannels)
2678         return E_INVALIDARG;
2679
2680     EnterCriticalSection(&This->lock);
2681
2682     This->vols[index] = level;
2683
2684     TRACE("OSS doesn't support setting volume\n");
2685
2686     LeaveCriticalSection(&This->lock);
2687
2688     return S_OK;
2689 }
2690
2691 static HRESULT WINAPI AudioStreamVolume_GetChannelVolume(
2692         IAudioStreamVolume *iface, UINT32 index, float *level)
2693 {
2694     ACImpl *This = impl_from_IAudioStreamVolume(iface);
2695
2696     TRACE("(%p)->(%d, %p)\n", This, index, level);
2697
2698     if(!level)
2699         return E_POINTER;
2700
2701     if(index >= This->fmt->nChannels)
2702         return E_INVALIDARG;
2703
2704     *level = This->vols[index];
2705
2706     return S_OK;
2707 }
2708
2709 static HRESULT WINAPI AudioStreamVolume_SetAllVolumes(
2710         IAudioStreamVolume *iface, UINT32 count, const float *levels)
2711 {
2712     ACImpl *This = impl_from_IAudioStreamVolume(iface);
2713     int i;
2714
2715     TRACE("(%p)->(%d, %p)\n", This, count, levels);
2716
2717     if(!levels)
2718         return E_POINTER;
2719
2720     if(count != This->fmt->nChannels)
2721         return E_INVALIDARG;
2722
2723     EnterCriticalSection(&This->lock);
2724
2725     for(i = 0; i < count; ++i)
2726         This->vols[i] = levels[i];
2727
2728     TRACE("OSS doesn't support setting volume\n");
2729
2730     LeaveCriticalSection(&This->lock);
2731
2732     return S_OK;
2733 }
2734
2735 static HRESULT WINAPI AudioStreamVolume_GetAllVolumes(
2736         IAudioStreamVolume *iface, UINT32 count, float *levels)
2737 {
2738     ACImpl *This = impl_from_IAudioStreamVolume(iface);
2739     int i;
2740
2741     TRACE("(%p)->(%d, %p)\n", This, count, levels);
2742
2743     if(!levels)
2744         return E_POINTER;
2745
2746     if(count != This->fmt->nChannels)
2747         return E_INVALIDARG;
2748
2749     EnterCriticalSection(&This->lock);
2750
2751     for(i = 0; i < count; ++i)
2752         levels[i] = This->vols[i];
2753
2754     LeaveCriticalSection(&This->lock);
2755
2756     return S_OK;
2757 }
2758
2759 static const IAudioStreamVolumeVtbl AudioStreamVolume_Vtbl =
2760 {
2761     AudioStreamVolume_QueryInterface,
2762     AudioStreamVolume_AddRef,
2763     AudioStreamVolume_Release,
2764     AudioStreamVolume_GetChannelCount,
2765     AudioStreamVolume_SetChannelVolume,
2766     AudioStreamVolume_GetChannelVolume,
2767     AudioStreamVolume_SetAllVolumes,
2768     AudioStreamVolume_GetAllVolumes
2769 };
2770
2771 static HRESULT WINAPI ChannelAudioVolume_QueryInterface(
2772         IChannelAudioVolume *iface, REFIID riid, void **ppv)
2773 {
2774     TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
2775
2776     if(!ppv)
2777         return E_POINTER;
2778     *ppv = NULL;
2779
2780     if(IsEqualIID(riid, &IID_IUnknown) ||
2781             IsEqualIID(riid, &IID_IChannelAudioVolume))
2782         *ppv = iface;
2783     if(*ppv){
2784         IUnknown_AddRef((IUnknown*)*ppv);
2785         return S_OK;
2786     }
2787
2788     WARN("Unknown interface %s\n", debugstr_guid(riid));
2789     return E_NOINTERFACE;
2790 }
2791
2792 static ULONG WINAPI ChannelAudioVolume_AddRef(IChannelAudioVolume *iface)
2793 {
2794     AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
2795     return AudioSessionControl_AddRef(&This->IAudioSessionControl2_iface);
2796 }
2797
2798 static ULONG WINAPI ChannelAudioVolume_Release(IChannelAudioVolume *iface)
2799 {
2800     AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
2801     return AudioSessionControl_Release(&This->IAudioSessionControl2_iface);
2802 }
2803
2804 static HRESULT WINAPI ChannelAudioVolume_GetChannelCount(
2805         IChannelAudioVolume *iface, UINT32 *out)
2806 {
2807     AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
2808     AudioSession *session = This->session;
2809
2810     TRACE("(%p)->(%p)\n", session, out);
2811
2812     if(!out)
2813         return NULL_PTR_ERR;
2814
2815     *out = session->channel_count;
2816
2817     return S_OK;
2818 }
2819
2820 static HRESULT WINAPI ChannelAudioVolume_SetChannelVolume(
2821         IChannelAudioVolume *iface, UINT32 index, float level,
2822         const GUID *context)
2823 {
2824     AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
2825     AudioSession *session = This->session;
2826
2827     TRACE("(%p)->(%d, %f, %s)\n", session, index, level,
2828             wine_dbgstr_guid(context));
2829
2830     if(level < 0.f || level > 1.f)
2831         return E_INVALIDARG;
2832
2833     if(index >= session->channel_count)
2834         return E_INVALIDARG;
2835
2836     if(context)
2837         FIXME("Notifications not supported yet\n");
2838
2839     EnterCriticalSection(&session->lock);
2840
2841     session->channel_vols[index] = level;
2842
2843     TRACE("OSS doesn't support setting volume\n");
2844
2845     LeaveCriticalSection(&session->lock);
2846
2847     return S_OK;
2848 }
2849
2850 static HRESULT WINAPI ChannelAudioVolume_GetChannelVolume(
2851         IChannelAudioVolume *iface, UINT32 index, float *level)
2852 {
2853     AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
2854     AudioSession *session = This->session;
2855
2856     TRACE("(%p)->(%d, %p)\n", session, index, level);
2857
2858     if(!level)
2859         return NULL_PTR_ERR;
2860
2861     if(index >= session->channel_count)
2862         return E_INVALIDARG;
2863
2864     *level = session->channel_vols[index];
2865
2866     return S_OK;
2867 }
2868
2869 static HRESULT WINAPI ChannelAudioVolume_SetAllVolumes(
2870         IChannelAudioVolume *iface, UINT32 count, const float *levels,
2871         const GUID *context)
2872 {
2873     AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
2874     AudioSession *session = This->session;
2875     int i;
2876
2877     TRACE("(%p)->(%d, %p, %s)\n", session, count, levels,
2878             wine_dbgstr_guid(context));
2879
2880     if(!levels)
2881         return NULL_PTR_ERR;
2882
2883     if(count != session->channel_count)
2884         return E_INVALIDARG;
2885
2886     if(context)
2887         FIXME("Notifications not supported yet\n");
2888
2889     EnterCriticalSection(&session->lock);
2890
2891     for(i = 0; i < count; ++i)
2892         session->channel_vols[i] = levels[i];
2893
2894     TRACE("OSS doesn't support setting volume\n");
2895
2896     LeaveCriticalSection(&session->lock);
2897
2898     return S_OK;
2899 }
2900
2901 static HRESULT WINAPI ChannelAudioVolume_GetAllVolumes(
2902         IChannelAudioVolume *iface, UINT32 count, float *levels)
2903 {
2904     AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
2905     AudioSession *session = This->session;
2906     int i;
2907
2908     TRACE("(%p)->(%d, %p)\n", session, count, levels);
2909
2910     if(!levels)
2911         return NULL_PTR_ERR;
2912
2913     if(count != session->channel_count)
2914         return E_INVALIDARG;
2915
2916     for(i = 0; i < count; ++i)
2917         levels[i] = session->channel_vols[i];
2918
2919     return S_OK;
2920 }
2921
2922 static const IChannelAudioVolumeVtbl ChannelAudioVolume_Vtbl =
2923 {
2924     ChannelAudioVolume_QueryInterface,
2925     ChannelAudioVolume_AddRef,
2926     ChannelAudioVolume_Release,
2927     ChannelAudioVolume_GetChannelCount,
2928     ChannelAudioVolume_SetChannelVolume,
2929     ChannelAudioVolume_GetChannelVolume,
2930     ChannelAudioVolume_SetAllVolumes,
2931     ChannelAudioVolume_GetAllVolumes
2932 };
2933
2934 static HRESULT WINAPI AudioSessionManager_QueryInterface(IAudioSessionManager2 *iface,
2935         REFIID riid, void **ppv)
2936 {
2937     TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
2938
2939     if(!ppv)
2940         return E_POINTER;
2941     *ppv = NULL;
2942
2943     if(IsEqualIID(riid, &IID_IUnknown) ||
2944             IsEqualIID(riid, &IID_IAudioSessionManager) ||
2945             IsEqualIID(riid, &IID_IAudioSessionManager2))
2946         *ppv = iface;
2947     if(*ppv){
2948         IUnknown_AddRef((IUnknown*)*ppv);
2949         return S_OK;
2950     }
2951
2952     WARN("Unknown interface %s\n", debugstr_guid(riid));
2953     return E_NOINTERFACE;
2954 }
2955
2956 static ULONG WINAPI AudioSessionManager_AddRef(IAudioSessionManager2 *iface)
2957 {
2958     SessionMgr *This = impl_from_IAudioSessionManager2(iface);
2959     ULONG ref;
2960     ref = InterlockedIncrement(&This->ref);
2961     TRACE("(%p) Refcount now %u\n", This, ref);
2962     return ref;
2963 }
2964
2965 static ULONG WINAPI AudioSessionManager_Release(IAudioSessionManager2 *iface)
2966 {
2967     SessionMgr *This = impl_from_IAudioSessionManager2(iface);
2968     ULONG ref;
2969     ref = InterlockedDecrement(&This->ref);
2970     TRACE("(%p) Refcount now %u\n", This, ref);
2971     if(!ref)
2972         HeapFree(GetProcessHeap(), 0, This);
2973     return ref;
2974 }
2975
2976 static HRESULT WINAPI AudioSessionManager_GetAudioSessionControl(
2977         IAudioSessionManager2 *iface, const GUID *session_guid, DWORD flags,
2978         IAudioSessionControl **out)
2979 {
2980     SessionMgr *This = impl_from_IAudioSessionManager2(iface);
2981     AudioSession *session;
2982     AudioSessionWrapper *wrapper;
2983     HRESULT hr;
2984
2985     TRACE("(%p)->(%s, %x, %p)\n", This, debugstr_guid(session_guid),
2986             flags, out);
2987
2988     hr = get_audio_session(session_guid, This->device, 0, &session);
2989     if(FAILED(hr))
2990         return hr;
2991
2992     wrapper = AudioSessionWrapper_Create(NULL);
2993     if(!wrapper)
2994         return E_OUTOFMEMORY;
2995
2996     wrapper->session = session;
2997
2998     *out = (IAudioSessionControl*)&wrapper->IAudioSessionControl2_iface;
2999
3000     return S_OK;
3001 }
3002
3003 static HRESULT WINAPI AudioSessionManager_GetSimpleAudioVolume(
3004         IAudioSessionManager2 *iface, const GUID *session_guid, DWORD flags,
3005         ISimpleAudioVolume **out)
3006 {
3007     SessionMgr *This = impl_from_IAudioSessionManager2(iface);
3008     AudioSession *session;
3009     AudioSessionWrapper *wrapper;
3010     HRESULT hr;
3011
3012     TRACE("(%p)->(%s, %x, %p)\n", This, debugstr_guid(session_guid),
3013             flags, out);
3014
3015     hr = get_audio_session(session_guid, This->device, 0, &session);
3016     if(FAILED(hr))
3017         return hr;
3018
3019     wrapper = AudioSessionWrapper_Create(NULL);
3020     if(!wrapper)
3021         return E_OUTOFMEMORY;
3022
3023     wrapper->session = session;
3024
3025     *out = &wrapper->ISimpleAudioVolume_iface;
3026
3027     return S_OK;
3028 }
3029
3030 static HRESULT WINAPI AudioSessionManager_GetSessionEnumerator(
3031         IAudioSessionManager2 *iface, IAudioSessionEnumerator **out)
3032 {
3033     SessionMgr *This = impl_from_IAudioSessionManager2(iface);
3034     FIXME("(%p)->(%p) - stub\n", This, out);
3035     return E_NOTIMPL;
3036 }
3037
3038 static HRESULT WINAPI AudioSessionManager_RegisterSessionNotification(
3039         IAudioSessionManager2 *iface, IAudioSessionNotification *notification)
3040 {
3041     SessionMgr *This = impl_from_IAudioSessionManager2(iface);
3042     FIXME("(%p)->(%p) - stub\n", This, notification);
3043     return E_NOTIMPL;
3044 }
3045
3046 static HRESULT WINAPI AudioSessionManager_UnregisterSessionNotification(
3047         IAudioSessionManager2 *iface, IAudioSessionNotification *notification)
3048 {
3049     SessionMgr *This = impl_from_IAudioSessionManager2(iface);
3050     FIXME("(%p)->(%p) - stub\n", This, notification);
3051     return E_NOTIMPL;
3052 }
3053
3054 static HRESULT WINAPI AudioSessionManager_RegisterDuckNotification(
3055         IAudioSessionManager2 *iface, const WCHAR *session_id,
3056         IAudioVolumeDuckNotification *notification)
3057 {
3058     SessionMgr *This = impl_from_IAudioSessionManager2(iface);
3059     FIXME("(%p)->(%p) - stub\n", This, notification);
3060     return E_NOTIMPL;
3061 }
3062
3063 static HRESULT WINAPI AudioSessionManager_UnregisterDuckNotification(
3064         IAudioSessionManager2 *iface,
3065         IAudioVolumeDuckNotification *notification)
3066 {
3067     SessionMgr *This = impl_from_IAudioSessionManager2(iface);
3068     FIXME("(%p)->(%p) - stub\n", This, notification);
3069     return E_NOTIMPL;
3070 }
3071
3072 static const IAudioSessionManager2Vtbl AudioSessionManager2_Vtbl =
3073 {
3074     AudioSessionManager_QueryInterface,
3075     AudioSessionManager_AddRef,
3076     AudioSessionManager_Release,
3077     AudioSessionManager_GetAudioSessionControl,
3078     AudioSessionManager_GetSimpleAudioVolume,
3079     AudioSessionManager_GetSessionEnumerator,
3080     AudioSessionManager_RegisterSessionNotification,
3081     AudioSessionManager_UnregisterSessionNotification,
3082     AudioSessionManager_RegisterDuckNotification,
3083     AudioSessionManager_UnregisterDuckNotification
3084 };
3085
3086 HRESULT WINAPI AUDDRV_GetAudioSessionManager(IMMDevice *device,
3087         IAudioSessionManager2 **out)
3088 {
3089     SessionMgr *This;
3090
3091     This = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(SessionMgr));
3092     if(!This)
3093         return E_OUTOFMEMORY;
3094
3095     This->IAudioSessionManager2_iface.lpVtbl = &AudioSessionManager2_Vtbl;
3096     This->device = device;
3097     This->ref = 1;
3098
3099     *out = &This->IAudioSessionManager2_iface;
3100
3101     return S_OK;
3102 }