wined3d: Implement parallel point lights in process_vertices_strided().
[wine.git] / dlls / winecoreaudio.drv / mmdevdrv.c
blob2f4683af976c3520c4b476cea86335f2cd2e8982
1 /*
2 * Copyright 2011 Andrew Eikum for CodeWeavers
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.
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.
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
19 #define NONAMELESSUNION
20 #define COBJMACROS
21 #include "config.h"
23 #define LoadResource __carbon_LoadResource
24 #define CompareString __carbon_CompareString
25 #define GetCurrentThread __carbon_GetCurrentThread
26 #define GetCurrentProcess __carbon_GetCurrentProcess
28 #include <stdarg.h>
30 #include <errno.h>
31 #include <limits.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <sys/types.h>
36 #include <sys/stat.h>
37 #include <sys/ioctl.h>
38 #include <fcntl.h>
39 #include <fenv.h>
40 #include <unistd.h>
42 #include <libkern/OSAtomic.h>
43 #include <CoreAudio/CoreAudio.h>
44 #include <AudioToolbox/AudioFormat.h>
45 #include <AudioToolbox/AudioConverter.h>
46 #include <AudioUnit/AudioUnit.h>
48 #undef LoadResource
49 #undef CompareString
50 #undef GetCurrentThread
51 #undef GetCurrentProcess
52 #undef _CDECL
54 #include "windef.h"
55 #include "winbase.h"
56 #include "winnls.h"
57 #include "winreg.h"
58 #include "wine/debug.h"
59 #include "wine/unicode.h"
60 #include "wine/list.h"
62 #include "ole2.h"
63 #include "mmdeviceapi.h"
64 #include "devpkey.h"
65 #include "dshow.h"
66 #include "dsound.h"
68 #include "initguid.h"
69 #include "endpointvolume.h"
70 #include "audioclient.h"
71 #include "audiopolicy.h"
73 WINE_DEFAULT_DEBUG_CHANNEL(coreaudio);
75 #ifndef HAVE_AUDIOUNIT_AUDIOCOMPONENT_H
76 /* Define new AudioComponent Manager functions for OSX 10.5 */
77 typedef Component AudioComponent;
78 typedef ComponentDescription AudioComponentDescription;
79 typedef ComponentInstance AudioComponentInstance;
81 static inline AudioComponent AudioComponentFindNext(AudioComponent ac, AudioComponentDescription *desc)
83 return FindNextComponent(ac, desc);
86 static inline OSStatus AudioComponentInstanceNew(AudioComponent ac, AudioComponentInstance *aci)
88 return OpenAComponent(ac, aci);
91 static inline OSStatus AudioComponentInstanceDispose(AudioComponentInstance aci)
93 return CloseComponent(aci);
95 #endif
97 #define NULL_PTR_ERR MAKE_HRESULT(SEVERITY_ERROR, FACILITY_WIN32, RPC_X_NULL_REF_POINTER)
99 static const REFERENCE_TIME DefaultPeriod = 100000;
100 static const REFERENCE_TIME MinimumPeriod = 50000;
102 struct ACImpl;
103 typedef struct ACImpl ACImpl;
105 typedef struct _AudioSession {
106 GUID guid;
107 struct list clients;
109 IMMDevice *device;
111 float master_vol;
112 UINT32 channel_count;
113 float *channel_vols;
114 BOOL mute;
116 CRITICAL_SECTION lock;
118 struct list entry;
119 } AudioSession;
121 typedef struct _AudioSessionWrapper {
122 IAudioSessionControl2 IAudioSessionControl2_iface;
123 IChannelAudioVolume IChannelAudioVolume_iface;
124 ISimpleAudioVolume ISimpleAudioVolume_iface;
126 LONG ref;
128 ACImpl *client;
129 AudioSession *session;
130 } AudioSessionWrapper;
132 struct ACImpl {
133 IAudioClient IAudioClient_iface;
134 IAudioRenderClient IAudioRenderClient_iface;
135 IAudioCaptureClient IAudioCaptureClient_iface;
136 IAudioClock IAudioClock_iface;
137 IAudioClock2 IAudioClock2_iface;
138 IAudioStreamVolume IAudioStreamVolume_iface;
140 LONG ref;
142 IMMDevice *parent;
143 IUnknown *pUnkFTMarshal;
145 WAVEFORMATEX *fmt;
147 EDataFlow dataflow;
148 DWORD flags;
149 AUDCLNT_SHAREMODE share;
150 HANDLE event;
151 float *vols;
153 BOOL initted;
154 AudioDeviceID adevid;
155 AudioObjectPropertyScope scope;
156 AudioConverterRef converter;
157 AudioComponentInstance unit;
158 AudioStreamBasicDescription dev_desc; /* audio unit format, not necessarily the same as fmt */
159 HANDLE timer;
160 UINT32 period_ms, bufsize_frames, period_frames;
161 UINT64 written_frames;
162 UINT32 lcl_offs_frames, wri_offs_frames, held_frames, tmp_buffer_frames;
163 UINT32 cap_bufsize_frames, cap_offs_frames, cap_held_frames, wrap_bufsize_frames, resamp_bufsize_frames;
164 INT32 getbuf_last;
165 BOOL playing;
166 BYTE *cap_buffer, *wrap_buffer, *resamp_buffer, *local_buffer, *tmp_buffer;
168 AudioSession *session;
169 AudioSessionWrapper *session_wrapper;
171 struct list entry;
173 OSSpinLock lock;
176 static const IAudioClientVtbl AudioClient_Vtbl;
177 static const IAudioRenderClientVtbl AudioRenderClient_Vtbl;
178 static const IAudioCaptureClientVtbl AudioCaptureClient_Vtbl;
179 static const IAudioSessionControl2Vtbl AudioSessionControl2_Vtbl;
180 static const ISimpleAudioVolumeVtbl SimpleAudioVolume_Vtbl;
181 static const IAudioClockVtbl AudioClock_Vtbl;
182 static const IAudioClock2Vtbl AudioClock2_Vtbl;
183 static const IAudioStreamVolumeVtbl AudioStreamVolume_Vtbl;
184 static const IChannelAudioVolumeVtbl ChannelAudioVolume_Vtbl;
185 static const IAudioSessionManager2Vtbl AudioSessionManager2_Vtbl;
187 typedef struct _SessionMgr {
188 IAudioSessionManager2 IAudioSessionManager2_iface;
190 LONG ref;
192 IMMDevice *device;
193 } SessionMgr;
195 static const WCHAR drv_key_devicesW[] = {'S','o','f','t','w','a','r','e','\\',
196 'W','i','n','e','\\','D','r','i','v','e','r','s','\\',
197 'w','i','n','e','c','o','r','e','a','u','d','i','o','.','d','r','v','\\','d','e','v','i','c','e','s',0};
198 static const WCHAR guidW[] = {'g','u','i','d',0};
200 static HANDLE g_timer_q;
202 static CRITICAL_SECTION g_sessions_lock;
203 static CRITICAL_SECTION_DEBUG g_sessions_lock_debug =
205 0, 0, &g_sessions_lock,
206 { &g_sessions_lock_debug.ProcessLocksList, &g_sessions_lock_debug.ProcessLocksList },
207 0, 0, { (DWORD_PTR)(__FILE__ ": g_sessions_lock") }
209 static CRITICAL_SECTION g_sessions_lock = { &g_sessions_lock_debug, -1, 0, 0, 0, 0 };
210 static struct list g_sessions = LIST_INIT(g_sessions);
212 static AudioSessionWrapper *AudioSessionWrapper_Create(ACImpl *client);
213 static HRESULT ca_setvol(ACImpl *This, UINT32 index);
215 static inline ACImpl *impl_from_IAudioClient(IAudioClient *iface)
217 return CONTAINING_RECORD(iface, ACImpl, IAudioClient_iface);
220 static inline ACImpl *impl_from_IAudioRenderClient(IAudioRenderClient *iface)
222 return CONTAINING_RECORD(iface, ACImpl, IAudioRenderClient_iface);
225 static inline ACImpl *impl_from_IAudioCaptureClient(IAudioCaptureClient *iface)
227 return CONTAINING_RECORD(iface, ACImpl, IAudioCaptureClient_iface);
230 static inline AudioSessionWrapper *impl_from_IAudioSessionControl2(IAudioSessionControl2 *iface)
232 return CONTAINING_RECORD(iface, AudioSessionWrapper, IAudioSessionControl2_iface);
235 static inline AudioSessionWrapper *impl_from_ISimpleAudioVolume(ISimpleAudioVolume *iface)
237 return CONTAINING_RECORD(iface, AudioSessionWrapper, ISimpleAudioVolume_iface);
240 static inline AudioSessionWrapper *impl_from_IChannelAudioVolume(IChannelAudioVolume *iface)
242 return CONTAINING_RECORD(iface, AudioSessionWrapper, IChannelAudioVolume_iface);
245 static inline ACImpl *impl_from_IAudioClock(IAudioClock *iface)
247 return CONTAINING_RECORD(iface, ACImpl, IAudioClock_iface);
250 static inline ACImpl *impl_from_IAudioClock2(IAudioClock2 *iface)
252 return CONTAINING_RECORD(iface, ACImpl, IAudioClock2_iface);
255 static inline ACImpl *impl_from_IAudioStreamVolume(IAudioStreamVolume *iface)
257 return CONTAINING_RECORD(iface, ACImpl, IAudioStreamVolume_iface);
260 static inline SessionMgr *impl_from_IAudioSessionManager2(IAudioSessionManager2 *iface)
262 return CONTAINING_RECORD(iface, SessionMgr, IAudioSessionManager2_iface);
265 BOOL WINAPI DllMain(HINSTANCE dll, DWORD reason, void *reserved)
267 switch (reason)
269 case DLL_PROCESS_ATTACH:
270 g_timer_q = CreateTimerQueue();
271 if(!g_timer_q)
272 return FALSE;
273 break;
275 case DLL_PROCESS_DETACH:
276 if (reserved) break;
277 DeleteCriticalSection(&g_sessions_lock);
278 break;
280 return TRUE;
283 /* From <dlls/mmdevapi/mmdevapi.h> */
284 enum DriverPriority {
285 Priority_Unavailable = 0,
286 Priority_Low,
287 Priority_Neutral,
288 Priority_Preferred
291 int WINAPI AUDDRV_GetPriority(void)
293 return Priority_Neutral;
296 static HRESULT osstatus_to_hresult(OSStatus sc)
298 switch(sc){
299 case kAudioFormatUnsupportedDataFormatError:
300 case kAudioFormatUnknownFormatError:
301 case kAudioDeviceUnsupportedFormatError:
302 return AUDCLNT_E_UNSUPPORTED_FORMAT;
303 case kAudioHardwareBadDeviceError:
304 return AUDCLNT_E_DEVICE_INVALIDATED;
306 return E_FAIL;
309 static void set_device_guid(EDataFlow flow, HKEY drv_key, const WCHAR *key_name,
310 GUID *guid)
312 HKEY key;
313 BOOL opened = FALSE;
314 LONG lr;
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;
323 opened = TRUE;
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;
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);
338 RegCloseKey(key);
339 exit:
340 if(opened)
341 RegCloseKey(drv_key);
344 static void get_device_guid(EDataFlow flow, AudioDeviceID device, GUID *guid)
346 HKEY key = NULL, dev_key;
347 DWORD type, size = sizeof(*guid);
348 WCHAR key_name[256];
350 static const WCHAR key_fmt[] = {'%','u',0};
352 if(flow == eCapture)
353 key_name[0] = '1';
354 else
355 key_name[0] = '0';
356 key_name[1] = ',';
358 sprintfW(key_name + 2, key_fmt, device);
360 if(RegOpenKeyExW(HKEY_CURRENT_USER, drv_key_devicesW, 0, KEY_WRITE|KEY_READ, &key) == ERROR_SUCCESS){
361 if(RegOpenKeyExW(key, key_name, 0, KEY_READ, &dev_key) == ERROR_SUCCESS){
362 if(RegQueryValueExW(dev_key, guidW, 0, &type,
363 (BYTE*)guid, &size) == ERROR_SUCCESS){
364 if(type == REG_BINARY){
365 RegCloseKey(dev_key);
366 RegCloseKey(key);
367 return;
369 ERR("Invalid type for device %s GUID: %u; ignoring and overwriting\n",
370 wine_dbgstr_w(key_name), type);
372 RegCloseKey(dev_key);
376 CoCreateGuid(guid);
378 set_device_guid(flow, key, key_name, guid);
380 if(key)
381 RegCloseKey(key);
384 HRESULT WINAPI AUDDRV_GetEndpointIDs(EDataFlow flow, WCHAR ***ids,
385 GUID **guids, UINT *num, UINT *def_index)
387 UInt32 devsize, size;
388 AudioDeviceID *devices;
389 AudioDeviceID default_id;
390 AudioObjectPropertyAddress addr;
391 OSStatus sc;
392 int i, ndevices;
394 TRACE("%d %p %p %p\n", flow, ids, num, def_index);
396 addr.mScope = kAudioObjectPropertyScopeGlobal;
397 addr.mElement = kAudioObjectPropertyElementMaster;
398 if(flow == eRender)
399 addr.mSelector = kAudioHardwarePropertyDefaultOutputDevice;
400 else if(flow == eCapture)
401 addr.mSelector = kAudioHardwarePropertyDefaultInputDevice;
402 else
403 return E_INVALIDARG;
405 size = sizeof(default_id);
406 sc = AudioObjectGetPropertyData(kAudioObjectSystemObject, &addr, 0,
407 NULL, &size, &default_id);
408 if(sc != noErr){
409 WARN("Getting _DefaultInputDevice property failed: %x\n", (int)sc);
410 default_id = -1;
413 addr.mSelector = kAudioHardwarePropertyDevices;
414 sc = AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &addr, 0,
415 NULL, &devsize);
416 if(sc != noErr){
417 WARN("Getting _Devices property size failed: %x\n", (int)sc);
418 return osstatus_to_hresult(sc);
421 devices = HeapAlloc(GetProcessHeap(), 0, devsize);
422 if(!devices)
423 return E_OUTOFMEMORY;
425 sc = AudioObjectGetPropertyData(kAudioObjectSystemObject, &addr, 0, NULL,
426 &devsize, devices);
427 if(sc != noErr){
428 WARN("Getting _Devices property failed: %x\n", (int)sc);
429 HeapFree(GetProcessHeap(), 0, devices);
430 return osstatus_to_hresult(sc);
433 ndevices = devsize / sizeof(AudioDeviceID);
435 *ids = HeapAlloc(GetProcessHeap(), 0, ndevices * sizeof(WCHAR *));
436 if(!*ids){
437 HeapFree(GetProcessHeap(), 0, devices);
438 return E_OUTOFMEMORY;
441 *guids = HeapAlloc(GetProcessHeap(), 0, ndevices * sizeof(GUID));
442 if(!*guids){
443 HeapFree(GetProcessHeap(), 0, *ids);
444 HeapFree(GetProcessHeap(), 0, devices);
445 return E_OUTOFMEMORY;
448 *num = 0;
449 *def_index = (UINT)-1;
450 for(i = 0; i < ndevices; ++i){
451 AudioBufferList *buffers;
452 CFStringRef name;
453 SIZE_T len;
454 int j;
456 addr.mSelector = kAudioDevicePropertyStreamConfiguration;
457 if(flow == eRender)
458 addr.mScope = kAudioDevicePropertyScopeOutput;
459 else
460 addr.mScope = kAudioDevicePropertyScopeInput;
461 addr.mElement = 0;
462 sc = AudioObjectGetPropertyDataSize(devices[i], &addr, 0, NULL, &size);
463 if(sc != noErr){
464 WARN("Unable to get _StreamConfiguration property size for "
465 "device %u: %x\n", (unsigned int)devices[i], (int)sc);
466 continue;
469 buffers = HeapAlloc(GetProcessHeap(), 0, size);
470 if(!buffers){
471 HeapFree(GetProcessHeap(), 0, devices);
472 for(j = 0; j < *num; ++j)
473 HeapFree(GetProcessHeap(), 0, (*ids)[j]);
474 HeapFree(GetProcessHeap(), 0, *guids);
475 HeapFree(GetProcessHeap(), 0, *ids);
476 return E_OUTOFMEMORY;
479 sc = AudioObjectGetPropertyData(devices[i], &addr, 0, NULL,
480 &size, buffers);
481 if(sc != noErr){
482 WARN("Unable to get _StreamConfiguration property for "
483 "device %u: %x\n", (unsigned int)devices[i], (int)sc);
484 HeapFree(GetProcessHeap(), 0, buffers);
485 continue;
488 /* check that there's at least one channel in this device before
489 * we claim it as usable */
490 for(j = 0; j < buffers->mNumberBuffers; ++j)
491 if(buffers->mBuffers[j].mNumberChannels > 0)
492 break;
493 if(j >= buffers->mNumberBuffers){
494 HeapFree(GetProcessHeap(), 0, buffers);
495 continue;
498 HeapFree(GetProcessHeap(), 0, buffers);
500 size = sizeof(name);
501 addr.mSelector = kAudioObjectPropertyName;
502 sc = AudioObjectGetPropertyData(devices[i], &addr, 0, NULL,
503 &size, &name);
504 if(sc != noErr){
505 WARN("Unable to get _Name property for device %u: %x\n",
506 (unsigned int)devices[i], (int)sc);
507 continue;
510 len = CFStringGetLength(name) + 1;
511 (*ids)[*num] = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
512 if(!(*ids)[*num]){
513 CFRelease(name);
514 HeapFree(GetProcessHeap(), 0, devices);
515 for(j = 0; j < *num; ++j)
516 HeapFree(GetProcessHeap(), 0, (*ids)[j]);
517 HeapFree(GetProcessHeap(), 0, *ids);
518 HeapFree(GetProcessHeap(), 0, *guids);
519 return E_OUTOFMEMORY;
521 CFStringGetCharacters(name, CFRangeMake(0, len - 1), (UniChar*)(*ids)[*num]);
522 ((*ids)[*num])[len - 1] = 0;
523 CFRelease(name);
525 get_device_guid(flow, devices[i], &(*guids)[*num]);
527 if(*def_index == (UINT)-1 && devices[i] == default_id)
528 *def_index = *num;
530 TRACE("device %u: id %s key %u%s\n", *num, debugstr_w((*ids)[*num]),
531 (unsigned int)devices[i], (*def_index == *num) ? " (default)" : "");
533 (*num)++;
536 if(*def_index == (UINT)-1)
537 *def_index = 0;
539 HeapFree(GetProcessHeap(), 0, devices);
541 return S_OK;
544 static BOOL get_deviceid_by_guid(GUID *guid, AudioDeviceID *id, EDataFlow *flow)
546 HKEY devices_key;
547 UINT i = 0;
548 WCHAR key_name[256];
549 DWORD key_name_size;
551 if(RegOpenKeyExW(HKEY_CURRENT_USER, drv_key_devicesW, 0, KEY_READ, &devices_key) != ERROR_SUCCESS){
552 ERR("No devices in registry?\n");
553 return FALSE;
556 while(1){
557 HKEY key;
558 DWORD size, type;
559 GUID reg_guid;
561 key_name_size = sizeof(key_name);
562 if(RegEnumKeyExW(devices_key, i++, key_name, &key_name_size, NULL,
563 NULL, NULL, NULL) != ERROR_SUCCESS)
564 break;
566 if(RegOpenKeyExW(devices_key, key_name, 0, KEY_READ, &key) != ERROR_SUCCESS){
567 WARN("Couldn't open key: %s\n", wine_dbgstr_w(key_name));
568 continue;
571 size = sizeof(reg_guid);
572 if(RegQueryValueExW(key, guidW, 0, &type,
573 (BYTE*)&reg_guid, &size) == ERROR_SUCCESS){
574 if(IsEqualGUID(&reg_guid, guid)){
575 RegCloseKey(key);
576 RegCloseKey(devices_key);
578 TRACE("Found matching device key: %s\n", wine_dbgstr_w(key_name));
580 if(key_name[0] == '0')
581 *flow = eRender;
582 else if(key_name[0] == '1')
583 *flow = eCapture;
584 else{
585 ERR("Unknown device type: %c\n", key_name[0]);
586 return FALSE;
589 *id = strtoulW(key_name + 2, NULL, 10);
591 return TRUE;
595 RegCloseKey(key);
598 RegCloseKey(devices_key);
600 WARN("No matching device in registry for GUID %s\n", debugstr_guid(guid));
602 return FALSE;
605 static AudioComponentInstance get_audiounit(EDataFlow dataflow, AudioDeviceID adevid)
607 AudioComponentInstance unit;
608 AudioComponent comp;
609 AudioComponentDescription desc;
610 OSStatus sc;
612 memset(&desc, 0, sizeof(desc));
613 desc.componentType = kAudioUnitType_Output;
614 desc.componentSubType = kAudioUnitSubType_HALOutput;
615 desc.componentManufacturer = kAudioUnitManufacturer_Apple;
617 if(!(comp = AudioComponentFindNext(NULL, &desc))){
618 WARN("AudioComponentFindNext failed\n");
619 return NULL;
622 sc = AudioComponentInstanceNew(comp, &unit);
623 if(sc != noErr){
624 WARN("AudioComponentInstanceNew failed: %x\n", (int)sc);
625 return NULL;
628 if(dataflow == eCapture){
629 UInt32 enableio;
631 enableio = 1;
632 sc = AudioUnitSetProperty(unit, kAudioOutputUnitProperty_EnableIO,
633 kAudioUnitScope_Input, 1, &enableio, sizeof(enableio));
634 if(sc != noErr){
635 WARN("Couldn't enable I/O on input element: %x\n", (int)sc);
636 AudioComponentInstanceDispose(unit);
637 return NULL;
640 enableio = 0;
641 sc = AudioUnitSetProperty(unit, kAudioOutputUnitProperty_EnableIO,
642 kAudioUnitScope_Output, 0, &enableio, sizeof(enableio));
643 if(sc != noErr){
644 WARN("Couldn't disable I/O on output element: %x\n", (int)sc);
645 AudioComponentInstanceDispose(unit);
646 return NULL;
650 sc = AudioUnitSetProperty(unit, kAudioOutputUnitProperty_CurrentDevice,
651 kAudioUnitScope_Global, 0, &adevid, sizeof(adevid));
652 if(sc != noErr){
653 WARN("Couldn't set audio unit device\n");
654 AudioComponentInstanceDispose(unit);
655 return NULL;
658 return unit;
661 HRESULT WINAPI AUDDRV_GetAudioEndpoint(GUID *guid, IMMDevice *dev, IAudioClient **out)
663 ACImpl *This;
664 AudioDeviceID adevid;
665 EDataFlow dataflow;
666 HRESULT hr;
668 TRACE("%s %p %p\n", debugstr_guid(guid), dev, out);
670 if(!get_deviceid_by_guid(guid, &adevid, &dataflow))
671 return AUDCLNT_E_DEVICE_INVALIDATED;
673 This = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(ACImpl));
674 if(!This)
675 return E_OUTOFMEMORY;
677 This->IAudioClient_iface.lpVtbl = &AudioClient_Vtbl;
678 This->IAudioRenderClient_iface.lpVtbl = &AudioRenderClient_Vtbl;
679 This->IAudioCaptureClient_iface.lpVtbl = &AudioCaptureClient_Vtbl;
680 This->IAudioClock_iface.lpVtbl = &AudioClock_Vtbl;
681 This->IAudioClock2_iface.lpVtbl = &AudioClock2_Vtbl;
682 This->IAudioStreamVolume_iface.lpVtbl = &AudioStreamVolume_Vtbl;
684 This->dataflow = dataflow;
686 if(dataflow == eRender)
687 This->scope = kAudioDevicePropertyScopeOutput;
688 else if(dataflow == eCapture)
689 This->scope = kAudioDevicePropertyScopeInput;
690 else{
691 HeapFree(GetProcessHeap(), 0, This);
692 return E_INVALIDARG;
695 This->lock = 0;
697 hr = CoCreateFreeThreadedMarshaler((IUnknown *)&This->IAudioClient_iface, &This->pUnkFTMarshal);
698 if (FAILED(hr)) {
699 HeapFree(GetProcessHeap(), 0, This);
700 return hr;
703 This->parent = dev;
704 IMMDevice_AddRef(This->parent);
706 This->adevid = adevid;
708 if(!(This->unit = get_audiounit(This->dataflow, This->adevid))){
709 HeapFree(GetProcessHeap(), 0, This);
710 return AUDCLNT_E_DEVICE_INVALIDATED;
713 *out = &This->IAudioClient_iface;
714 IAudioClient_AddRef(&This->IAudioClient_iface);
716 return S_OK;
719 static HRESULT WINAPI AudioClient_QueryInterface(IAudioClient *iface,
720 REFIID riid, void **ppv)
722 ACImpl *This = impl_from_IAudioClient(iface);
723 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
725 if(!ppv)
726 return E_POINTER;
727 *ppv = NULL;
728 if(IsEqualIID(riid, &IID_IUnknown) || IsEqualIID(riid, &IID_IAudioClient))
729 *ppv = iface;
730 else if(IsEqualIID(riid, &IID_IMarshal))
731 return IUnknown_QueryInterface(This->pUnkFTMarshal, riid, ppv);
733 if(*ppv){
734 IUnknown_AddRef((IUnknown*)*ppv);
735 return S_OK;
737 WARN("Unknown interface %s\n", debugstr_guid(riid));
738 return E_NOINTERFACE;
741 static ULONG WINAPI AudioClient_AddRef(IAudioClient *iface)
743 ACImpl *This = impl_from_IAudioClient(iface);
744 ULONG ref;
745 ref = InterlockedIncrement(&This->ref);
746 TRACE("(%p) Refcount now %u\n", This, ref);
747 return ref;
750 static ULONG WINAPI AudioClient_Release(IAudioClient *iface)
752 ACImpl *This = impl_from_IAudioClient(iface);
753 ULONG ref;
754 ref = InterlockedDecrement(&This->ref);
755 TRACE("(%p) Refcount now %u\n", This, ref);
756 if(!ref){
757 if(This->timer){
758 HANDLE event;
759 BOOL wait;
760 event = CreateEventW(NULL, TRUE, FALSE, NULL);
761 wait = !DeleteTimerQueueTimer(g_timer_q, This->timer, event);
762 wait = wait && GetLastError() == ERROR_IO_PENDING;
763 if(event && wait)
764 WaitForSingleObject(event, INFINITE);
765 CloseHandle(event);
767 AudioOutputUnitStop(This->unit);
768 AudioComponentInstanceDispose(This->unit);
769 if(This->converter)
770 AudioConverterDispose(This->converter);
771 if(This->session){
772 EnterCriticalSection(&g_sessions_lock);
773 list_remove(&This->entry);
774 LeaveCriticalSection(&g_sessions_lock);
776 HeapFree(GetProcessHeap(), 0, This->vols);
777 HeapFree(GetProcessHeap(), 0, This->tmp_buffer);
778 HeapFree(GetProcessHeap(), 0, This->cap_buffer);
779 HeapFree(GetProcessHeap(), 0, This->local_buffer);
780 free(This->wrap_buffer);
781 HeapFree(GetProcessHeap(), 0, This->resamp_buffer);
782 CoTaskMemFree(This->fmt);
783 IMMDevice_Release(This->parent);
784 IUnknown_Release(This->pUnkFTMarshal);
785 HeapFree(GetProcessHeap(), 0, This);
787 return ref;
790 static void dump_fmt(const WAVEFORMATEX *fmt)
792 TRACE("wFormatTag: 0x%x (", fmt->wFormatTag);
793 switch(fmt->wFormatTag){
794 case WAVE_FORMAT_PCM:
795 TRACE("WAVE_FORMAT_PCM");
796 break;
797 case WAVE_FORMAT_IEEE_FLOAT:
798 TRACE("WAVE_FORMAT_IEEE_FLOAT");
799 break;
800 case WAVE_FORMAT_EXTENSIBLE:
801 TRACE("WAVE_FORMAT_EXTENSIBLE");
802 break;
803 default:
804 TRACE("Unknown");
805 break;
807 TRACE(")\n");
809 TRACE("nChannels: %u\n", fmt->nChannels);
810 TRACE("nSamplesPerSec: %u\n", fmt->nSamplesPerSec);
811 TRACE("nAvgBytesPerSec: %u\n", fmt->nAvgBytesPerSec);
812 TRACE("nBlockAlign: %u\n", fmt->nBlockAlign);
813 TRACE("wBitsPerSample: %u\n", fmt->wBitsPerSample);
814 TRACE("cbSize: %u\n", fmt->cbSize);
816 if(fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE){
817 WAVEFORMATEXTENSIBLE *fmtex = (void*)fmt;
818 TRACE("dwChannelMask: %08x\n", fmtex->dwChannelMask);
819 TRACE("Samples: %04x\n", fmtex->Samples.wReserved);
820 TRACE("SubFormat: %s\n", wine_dbgstr_guid(&fmtex->SubFormat));
824 static DWORD get_channel_mask(unsigned int channels)
826 switch(channels){
827 case 0:
828 return 0;
829 case 1:
830 return KSAUDIO_SPEAKER_MONO;
831 case 2:
832 return KSAUDIO_SPEAKER_STEREO;
833 case 3:
834 return KSAUDIO_SPEAKER_STEREO | SPEAKER_LOW_FREQUENCY;
835 case 4:
836 return KSAUDIO_SPEAKER_QUAD; /* not _SURROUND */
837 case 5:
838 return KSAUDIO_SPEAKER_QUAD | SPEAKER_LOW_FREQUENCY;
839 case 6:
840 return KSAUDIO_SPEAKER_5POINT1; /* not 5POINT1_SURROUND */
841 case 7:
842 return KSAUDIO_SPEAKER_5POINT1 | SPEAKER_BACK_CENTER;
843 case 8:
844 return KSAUDIO_SPEAKER_7POINT1_SURROUND; /* Vista deprecates 7POINT1 */
846 FIXME("Unknown speaker configuration: %u\n", channels);
847 return 0;
850 static WAVEFORMATEX *clone_format(const WAVEFORMATEX *fmt)
852 WAVEFORMATEX *ret;
853 size_t size;
855 if(fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE)
856 size = sizeof(WAVEFORMATEXTENSIBLE);
857 else
858 size = sizeof(WAVEFORMATEX);
860 ret = CoTaskMemAlloc(size);
861 if(!ret)
862 return NULL;
864 memcpy(ret, fmt, size);
866 ret->cbSize = size - sizeof(WAVEFORMATEX);
868 return ret;
871 static HRESULT ca_get_audiodesc(AudioStreamBasicDescription *desc,
872 const WAVEFORMATEX *fmt)
874 const WAVEFORMATEXTENSIBLE *fmtex = (const WAVEFORMATEXTENSIBLE *)fmt;
876 desc->mFormatFlags = 0;
878 if(fmt->wFormatTag == WAVE_FORMAT_PCM ||
879 (fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
880 IsEqualGUID(&fmtex->SubFormat, &KSDATAFORMAT_SUBTYPE_PCM))){
881 desc->mFormatID = kAudioFormatLinearPCM;
882 if(fmt->wBitsPerSample > 8)
883 desc->mFormatFlags = kAudioFormatFlagIsSignedInteger;
884 }else if(fmt->wFormatTag == WAVE_FORMAT_IEEE_FLOAT ||
885 (fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
886 IsEqualGUID(&fmtex->SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))){
887 desc->mFormatID = kAudioFormatLinearPCM;
888 desc->mFormatFlags = kAudioFormatFlagIsFloat;
889 }else if(fmt->wFormatTag == WAVE_FORMAT_MULAW ||
890 (fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
891 IsEqualGUID(&fmtex->SubFormat, &KSDATAFORMAT_SUBTYPE_MULAW))){
892 desc->mFormatID = kAudioFormatULaw;
893 }else if(fmt->wFormatTag == WAVE_FORMAT_ALAW ||
894 (fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
895 IsEqualGUID(&fmtex->SubFormat, &KSDATAFORMAT_SUBTYPE_ALAW))){
896 desc->mFormatID = kAudioFormatALaw;
897 }else
898 return AUDCLNT_E_UNSUPPORTED_FORMAT;
900 desc->mSampleRate = fmt->nSamplesPerSec;
901 desc->mBytesPerPacket = fmt->nBlockAlign;
902 desc->mFramesPerPacket = 1;
903 desc->mBytesPerFrame = fmt->nBlockAlign;
904 desc->mChannelsPerFrame = fmt->nChannels;
905 desc->mBitsPerChannel = fmt->wBitsPerSample;
906 desc->mReserved = 0;
908 return S_OK;
911 static void session_init_vols(AudioSession *session, UINT channels)
913 if(session->channel_count < channels){
914 UINT i;
916 if(session->channel_vols)
917 session->channel_vols = HeapReAlloc(GetProcessHeap(), 0,
918 session->channel_vols, sizeof(float) * channels);
919 else
920 session->channel_vols = HeapAlloc(GetProcessHeap(), 0,
921 sizeof(float) * channels);
922 if(!session->channel_vols)
923 return;
925 for(i = session->channel_count; i < channels; ++i)
926 session->channel_vols[i] = 1.f;
928 session->channel_count = channels;
932 static AudioSession *create_session(const GUID *guid, IMMDevice *device,
933 UINT num_channels)
935 AudioSession *ret;
937 ret = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(AudioSession));
938 if(!ret)
939 return NULL;
941 memcpy(&ret->guid, guid, sizeof(GUID));
943 ret->device = device;
945 list_init(&ret->clients);
947 list_add_head(&g_sessions, &ret->entry);
949 InitializeCriticalSection(&ret->lock);
950 ret->lock.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": AudioSession.lock");
952 session_init_vols(ret, num_channels);
954 ret->master_vol = 1.f;
956 return ret;
959 /* if channels == 0, then this will return or create a session with
960 * matching dataflow and GUID. otherwise, channels must also match */
961 static HRESULT get_audio_session(const GUID *sessionguid,
962 IMMDevice *device, UINT channels, AudioSession **out)
964 AudioSession *session;
966 if(!sessionguid || IsEqualGUID(sessionguid, &GUID_NULL)){
967 *out = create_session(&GUID_NULL, device, channels);
968 if(!*out)
969 return E_OUTOFMEMORY;
971 return S_OK;
974 *out = NULL;
975 LIST_FOR_EACH_ENTRY(session, &g_sessions, AudioSession, entry){
976 if(session->device == device &&
977 IsEqualGUID(sessionguid, &session->guid)){
978 session_init_vols(session, channels);
979 *out = session;
980 break;
984 if(!*out){
985 *out = create_session(sessionguid, device, channels);
986 if(!*out)
987 return E_OUTOFMEMORY;
990 return S_OK;
993 static void ca_wrap_buffer(BYTE *dst, UINT32 dst_offs, UINT32 dst_bytes,
994 BYTE *src, UINT32 src_bytes)
996 UINT32 chunk_bytes = dst_bytes - dst_offs;
998 if(chunk_bytes < src_bytes){
999 memcpy(dst + dst_offs, src, chunk_bytes);
1000 memcpy(dst, src + chunk_bytes, src_bytes - chunk_bytes);
1001 }else
1002 memcpy(dst + dst_offs, src, src_bytes);
1005 static void silence_buffer(ACImpl *This, BYTE *buffer, UINT32 frames)
1007 WAVEFORMATEXTENSIBLE *fmtex = (WAVEFORMATEXTENSIBLE*)This->fmt;
1008 if((This->fmt->wFormatTag == WAVE_FORMAT_PCM ||
1009 (This->fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
1010 IsEqualGUID(&fmtex->SubFormat, &KSDATAFORMAT_SUBTYPE_PCM))) &&
1011 This->fmt->wBitsPerSample == 8)
1012 memset(buffer, 128, frames * This->fmt->nBlockAlign);
1013 else
1014 memset(buffer, 0, frames * This->fmt->nBlockAlign);
1017 /* CA is pulling data from us */
1018 static OSStatus ca_render_cb(void *user, AudioUnitRenderActionFlags *flags,
1019 const AudioTimeStamp *ts, UInt32 bus, UInt32 nframes,
1020 AudioBufferList *data)
1022 ACImpl *This = user;
1023 UINT32 to_copy_bytes, to_copy_frames, chunk_bytes, lcl_offs_bytes;
1025 OSSpinLockLock(&This->lock);
1027 if(This->playing){
1028 lcl_offs_bytes = This->lcl_offs_frames * This->fmt->nBlockAlign;
1029 to_copy_frames = min(nframes, This->held_frames);
1030 to_copy_bytes = to_copy_frames * This->fmt->nBlockAlign;
1032 chunk_bytes = (This->bufsize_frames - This->lcl_offs_frames) * This->fmt->nBlockAlign;
1034 if(to_copy_bytes > chunk_bytes){
1035 memcpy(data->mBuffers[0].mData, This->local_buffer + lcl_offs_bytes, chunk_bytes);
1036 memcpy(((BYTE *)data->mBuffers[0].mData) + chunk_bytes, This->local_buffer, to_copy_bytes - chunk_bytes);
1037 }else
1038 memcpy(data->mBuffers[0].mData, This->local_buffer + lcl_offs_bytes, to_copy_bytes);
1040 This->lcl_offs_frames += to_copy_frames;
1041 This->lcl_offs_frames %= This->bufsize_frames;
1042 This->held_frames -= to_copy_frames;
1043 }else
1044 to_copy_bytes = to_copy_frames = 0;
1046 if(nframes > to_copy_frames)
1047 silence_buffer(This, ((BYTE *)data->mBuffers[0].mData) + to_copy_bytes, nframes - to_copy_frames);
1049 OSSpinLockUnlock(&This->lock);
1051 return noErr;
1054 static UINT buf_ptr_diff(UINT left, UINT right, UINT bufsize)
1056 if(left <= right)
1057 return right - left;
1058 return bufsize - (left - right);
1061 /* place data from cap_buffer into provided AudioBufferList */
1062 static OSStatus feed_cb(AudioConverterRef converter, UInt32 *nframes, AudioBufferList *data,
1063 AudioStreamPacketDescription **packets, void *user)
1065 ACImpl *This = user;
1067 *nframes = min(*nframes, This->cap_held_frames);
1068 if(!*nframes){
1069 data->mBuffers[0].mData = NULL;
1070 data->mBuffers[0].mDataByteSize = 0;
1071 data->mBuffers[0].mNumberChannels = This->fmt->nChannels;
1072 return noErr;
1075 data->mBuffers[0].mDataByteSize = *nframes * This->fmt->nBlockAlign;
1076 data->mBuffers[0].mNumberChannels = This->fmt->nChannels;
1078 if(This->cap_offs_frames + *nframes > This->cap_bufsize_frames){
1079 UINT32 chunk_frames = This->cap_bufsize_frames - This->cap_offs_frames;
1081 if(This->wrap_bufsize_frames < *nframes){
1082 free(This->wrap_buffer);
1083 This->wrap_buffer = malloc(data->mBuffers[0].mDataByteSize);
1084 This->wrap_bufsize_frames = *nframes;
1087 memcpy(This->wrap_buffer, This->cap_buffer + This->cap_offs_frames * This->fmt->nBlockAlign,
1088 chunk_frames * This->fmt->nBlockAlign);
1089 memcpy(This->wrap_buffer + chunk_frames * This->fmt->nBlockAlign, This->cap_buffer,
1090 (*nframes - chunk_frames) * This->fmt->nBlockAlign);
1092 data->mBuffers[0].mData = This->wrap_buffer;
1093 }else
1094 data->mBuffers[0].mData = This->cap_buffer + This->cap_offs_frames * This->fmt->nBlockAlign;
1096 This->cap_offs_frames += *nframes;
1097 This->cap_offs_frames %= This->cap_bufsize_frames;
1098 This->cap_held_frames -= *nframes;
1100 if(packets)
1101 *packets = NULL;
1103 return noErr;
1106 static void capture_resample(ACImpl *This)
1108 UINT32 resamp_period_frames = MulDiv(This->period_frames, This->dev_desc.mSampleRate, This->fmt->nSamplesPerSec);
1109 OSStatus sc;
1111 /* the resampling process often needs more source frames than we'd
1112 * guess from a straight conversion using the sample rate ratio. so
1113 * only convert if we have extra source data. */
1114 while(This->cap_held_frames > resamp_period_frames * 2){
1115 AudioBufferList converted_list;
1116 UInt32 wanted_frames = This->period_frames;
1118 converted_list.mNumberBuffers = 1;
1119 converted_list.mBuffers[0].mNumberChannels = This->fmt->nChannels;
1120 converted_list.mBuffers[0].mDataByteSize = wanted_frames * This->fmt->nBlockAlign;
1122 if(This->resamp_bufsize_frames < wanted_frames){
1123 HeapFree(GetProcessHeap(), 0, This->resamp_buffer);
1124 This->resamp_buffer = HeapAlloc(GetProcessHeap(), 0, converted_list.mBuffers[0].mDataByteSize);
1125 This->resamp_bufsize_frames = wanted_frames;
1128 converted_list.mBuffers[0].mData = This->resamp_buffer;
1130 sc = AudioConverterFillComplexBuffer(This->converter, feed_cb,
1131 This, &wanted_frames, &converted_list, NULL);
1132 if(sc != noErr){
1133 WARN("AudioConverterFillComplexBuffer failed: %x\n", (int)sc);
1134 break;
1137 ca_wrap_buffer(This->local_buffer,
1138 This->wri_offs_frames * This->fmt->nBlockAlign,
1139 This->bufsize_frames * This->fmt->nBlockAlign,
1140 This->resamp_buffer, wanted_frames * This->fmt->nBlockAlign);
1142 This->wri_offs_frames += wanted_frames;
1143 This->wri_offs_frames %= This->bufsize_frames;
1144 if(This->held_frames + wanted_frames > This->bufsize_frames){
1145 This->lcl_offs_frames += buf_ptr_diff(This->lcl_offs_frames,
1146 This->wri_offs_frames, This->bufsize_frames);
1147 This->held_frames = This->bufsize_frames;
1148 }else
1149 This->held_frames += wanted_frames;
1153 /* we need to trigger CA to pull data from the device and give it to us
1155 * raw data from CA is stored in cap_buffer, possibly via wrap_buffer
1157 * raw data is resampled from cap_buffer into resamp_buffer in period-size
1158 * chunks and copied to local_buffer
1160 static OSStatus ca_capture_cb(void *user, AudioUnitRenderActionFlags *flags,
1161 const AudioTimeStamp *ts, UInt32 bus, UInt32 nframes,
1162 AudioBufferList *data)
1164 ACImpl *This = user;
1165 AudioBufferList list;
1166 OSStatus sc;
1167 UINT32 cap_wri_offs_frames;
1169 OSSpinLockLock(&This->lock);
1171 cap_wri_offs_frames = (This->cap_offs_frames + This->cap_held_frames) % This->cap_bufsize_frames;
1173 list.mNumberBuffers = 1;
1174 list.mBuffers[0].mNumberChannels = This->fmt->nChannels;
1175 list.mBuffers[0].mDataByteSize = nframes * This->fmt->nBlockAlign;
1177 if(!This->playing || cap_wri_offs_frames + nframes > This->cap_bufsize_frames){
1178 if(This->wrap_bufsize_frames < nframes){
1179 free(This->wrap_buffer);
1180 This->wrap_buffer = malloc(list.mBuffers[0].mDataByteSize);
1181 This->wrap_bufsize_frames = nframes;
1184 list.mBuffers[0].mData = This->wrap_buffer;
1185 }else
1186 list.mBuffers[0].mData = This->cap_buffer + cap_wri_offs_frames * This->fmt->nBlockAlign;
1188 sc = AudioUnitRender(This->unit, flags, ts, bus, nframes, &list);
1189 if(sc != noErr){
1190 OSSpinLockUnlock(&This->lock);
1191 return sc;
1194 if(This->playing){
1195 if(list.mBuffers[0].mData == This->wrap_buffer){
1196 ca_wrap_buffer(This->cap_buffer,
1197 cap_wri_offs_frames * This->fmt->nBlockAlign,
1198 This->cap_bufsize_frames * This->fmt->nBlockAlign,
1199 This->wrap_buffer, list.mBuffers[0].mDataByteSize);
1202 This->cap_held_frames += list.mBuffers[0].mDataByteSize / This->fmt->nBlockAlign;
1203 if(This->cap_held_frames > This->cap_bufsize_frames){
1204 This->cap_offs_frames += This->cap_held_frames % This->cap_bufsize_frames;
1205 This->cap_offs_frames %= This->cap_bufsize_frames;
1206 This->cap_held_frames = This->cap_bufsize_frames;
1210 OSSpinLockUnlock(&This->lock);
1211 return noErr;
1214 static void dump_adesc(const char *aux, AudioStreamBasicDescription *desc)
1216 TRACE("%s: mSampleRate: %f\n", aux, desc->mSampleRate);
1217 TRACE("%s: mBytesPerPacket: %u\n", aux, (unsigned int)desc->mBytesPerPacket);
1218 TRACE("%s: mFramesPerPacket: %u\n", aux, (unsigned int)desc->mFramesPerPacket);
1219 TRACE("%s: mBytesPerFrame: %u\n", aux, (unsigned int)desc->mBytesPerFrame);
1220 TRACE("%s: mChannelsPerFrame: %u\n", aux, (unsigned int)desc->mChannelsPerFrame);
1221 TRACE("%s: mBitsPerChannel: %u\n", aux, (unsigned int)desc->mBitsPerChannel);
1224 static HRESULT ca_setup_audiounit(EDataFlow dataflow, AudioComponentInstance unit,
1225 const WAVEFORMATEX *fmt, AudioStreamBasicDescription *dev_desc,
1226 AudioConverterRef *converter)
1228 OSStatus sc;
1229 HRESULT hr;
1231 if(dataflow == eCapture){
1232 AudioStreamBasicDescription desc;
1233 UInt32 size;
1234 Float64 rate;
1235 fenv_t fenv;
1236 BOOL fenv_stored = TRUE;
1238 hr = ca_get_audiodesc(&desc, fmt);
1239 if(FAILED(hr))
1240 return hr;
1241 dump_adesc("requested", &desc);
1243 /* input-only units can't perform sample rate conversion, so we have to
1244 * set up our own AudioConverter to support arbitrary sample rates. */
1245 size = sizeof(*dev_desc);
1246 sc = AudioUnitGetProperty(unit, kAudioUnitProperty_StreamFormat,
1247 kAudioUnitScope_Input, 1, dev_desc, &size);
1248 if(sc != noErr){
1249 WARN("Couldn't get unit format: %x\n", (int)sc);
1250 return osstatus_to_hresult(sc);
1252 dump_adesc("hardware", dev_desc);
1254 rate = dev_desc->mSampleRate;
1255 *dev_desc = desc;
1256 dev_desc->mSampleRate = rate;
1258 dump_adesc("final", dev_desc);
1259 sc = AudioUnitSetProperty(unit, kAudioUnitProperty_StreamFormat,
1260 kAudioUnitScope_Output, 1, dev_desc, sizeof(*dev_desc));
1261 if(sc != noErr){
1262 WARN("Couldn't set unit format: %x\n", (int)sc);
1263 return osstatus_to_hresult(sc);
1266 /* AudioConverterNew requires divide-by-zero SSE exceptions to be masked */
1267 if(feholdexcept(&fenv)){
1268 WARN("Failed to store fenv state\n");
1269 fenv_stored = FALSE;
1272 sc = AudioConverterNew(dev_desc, &desc, converter);
1274 if(fenv_stored && fesetenv(&fenv))
1275 WARN("Failed to restore fenv state\n");
1277 if(sc != noErr){
1278 WARN("Couldn't create audio converter: %x\n", (int)sc);
1279 return osstatus_to_hresult(sc);
1281 }else{
1282 hr = ca_get_audiodesc(dev_desc, fmt);
1283 if(FAILED(hr))
1284 return hr;
1286 dump_adesc("final", dev_desc);
1287 sc = AudioUnitSetProperty(unit, kAudioUnitProperty_StreamFormat,
1288 kAudioUnitScope_Input, 0, dev_desc, sizeof(*dev_desc));
1289 if(sc != noErr){
1290 WARN("Couldn't set format: %x\n", (int)sc);
1291 return osstatus_to_hresult(sc);
1295 return S_OK;
1298 static HRESULT WINAPI AudioClient_Initialize(IAudioClient *iface,
1299 AUDCLNT_SHAREMODE mode, DWORD flags, REFERENCE_TIME duration,
1300 REFERENCE_TIME period, const WAVEFORMATEX *fmt,
1301 const GUID *sessionguid)
1303 ACImpl *This = impl_from_IAudioClient(iface);
1304 HRESULT hr;
1305 OSStatus sc;
1306 int i;
1308 TRACE("(%p)->(%x, %x, %s, %s, %p, %s)\n", This, mode, flags,
1309 wine_dbgstr_longlong(duration), wine_dbgstr_longlong(period), fmt, debugstr_guid(sessionguid));
1311 if(!fmt)
1312 return E_POINTER;
1314 dump_fmt(fmt);
1316 if(mode != AUDCLNT_SHAREMODE_SHARED && mode != AUDCLNT_SHAREMODE_EXCLUSIVE)
1317 return AUDCLNT_E_NOT_INITIALIZED;
1319 if(flags & ~(AUDCLNT_STREAMFLAGS_CROSSPROCESS |
1320 AUDCLNT_STREAMFLAGS_LOOPBACK |
1321 AUDCLNT_STREAMFLAGS_EVENTCALLBACK |
1322 AUDCLNT_STREAMFLAGS_NOPERSIST |
1323 AUDCLNT_STREAMFLAGS_RATEADJUST |
1324 AUDCLNT_SESSIONFLAGS_EXPIREWHENUNOWNED |
1325 AUDCLNT_SESSIONFLAGS_DISPLAY_HIDE |
1326 AUDCLNT_SESSIONFLAGS_DISPLAY_HIDEWHENEXPIRED)){
1327 TRACE("Unknown flags: %08x\n", flags);
1328 return E_INVALIDARG;
1331 if(mode == AUDCLNT_SHAREMODE_SHARED){
1332 period = DefaultPeriod;
1333 if( duration < 3 * period)
1334 duration = 3 * period;
1335 }else{
1336 if(fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE){
1337 if(((WAVEFORMATEXTENSIBLE*)fmt)->dwChannelMask == 0 ||
1338 ((WAVEFORMATEXTENSIBLE*)fmt)->dwChannelMask & SPEAKER_RESERVED)
1339 return AUDCLNT_E_UNSUPPORTED_FORMAT;
1342 if(!period)
1343 period = DefaultPeriod; /* not minimum */
1344 if(period < MinimumPeriod || period > 5000000)
1345 return AUDCLNT_E_INVALID_DEVICE_PERIOD;
1346 if(duration > 20000000) /* the smaller the period, the lower this limit */
1347 return AUDCLNT_E_BUFFER_SIZE_ERROR;
1348 if(flags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK){
1349 if(duration != period)
1350 return AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL;
1351 FIXME("EXCLUSIVE mode with EVENTCALLBACK\n");
1352 return AUDCLNT_E_DEVICE_IN_USE;
1353 }else{
1354 if( duration < 8 * period)
1355 duration = 8 * period; /* may grow above 2s */
1359 OSSpinLockLock(&This->lock);
1361 if(This->initted){
1362 OSSpinLockUnlock(&This->lock);
1363 return AUDCLNT_E_ALREADY_INITIALIZED;
1366 This->fmt = clone_format(fmt);
1367 if(!This->fmt){
1368 OSSpinLockUnlock(&This->lock);
1369 return E_OUTOFMEMORY;
1372 This->period_ms = period / 10000;
1373 This->period_frames = MulDiv(period, This->fmt->nSamplesPerSec, 10000000);
1375 This->bufsize_frames = MulDiv(duration, fmt->nSamplesPerSec, 10000000);
1376 if(mode == AUDCLNT_SHAREMODE_EXCLUSIVE)
1377 This->bufsize_frames -= This->bufsize_frames % This->period_frames;
1379 hr = ca_setup_audiounit(This->dataflow, This->unit, This->fmt, &This->dev_desc, &This->converter);
1380 if(FAILED(hr)){
1381 CoTaskMemFree(This->fmt);
1382 This->fmt = NULL;
1383 OSSpinLockUnlock(&This->lock);
1384 return hr;
1387 if(This->dataflow == eCapture){
1388 AURenderCallbackStruct input;
1390 memset(&input, 0, sizeof(input));
1391 input.inputProc = &ca_capture_cb;
1392 input.inputProcRefCon = This;
1394 sc = AudioUnitSetProperty(This->unit, kAudioOutputUnitProperty_SetInputCallback,
1395 kAudioUnitScope_Output, 1, &input, sizeof(input));
1396 if(sc != noErr){
1397 WARN("Couldn't set callback: %x\n", (int)sc);
1398 AudioConverterDispose(This->converter);
1399 This->converter = NULL;
1400 CoTaskMemFree(This->fmt);
1401 This->fmt = NULL;
1402 OSSpinLockUnlock(&This->lock);
1403 return osstatus_to_hresult(sc);
1405 }else{
1406 AURenderCallbackStruct input;
1408 memset(&input, 0, sizeof(input));
1409 input.inputProc = &ca_render_cb;
1410 input.inputProcRefCon = This;
1412 sc = AudioUnitSetProperty(This->unit, kAudioUnitProperty_SetRenderCallback,
1413 kAudioUnitScope_Input, 0, &input, sizeof(input));
1414 if(sc != noErr){
1415 WARN("Couldn't set callback: %x\n", (int)sc);
1416 CoTaskMemFree(This->fmt);
1417 This->fmt = NULL;
1418 OSSpinLockUnlock(&This->lock);
1419 return osstatus_to_hresult(sc);
1423 sc = AudioUnitInitialize(This->unit);
1424 if(sc != noErr){
1425 WARN("Couldn't initialize: %x\n", (int)sc);
1426 if(This->converter){
1427 AudioConverterDispose(This->converter);
1428 This->converter = NULL;
1430 CoTaskMemFree(This->fmt);
1431 This->fmt = NULL;
1432 OSSpinLockUnlock(&This->lock);
1433 return osstatus_to_hresult(sc);
1436 /* we play audio continuously because AudioOutputUnitStart sometimes takes
1437 * a while to return */
1438 sc = AudioOutputUnitStart(This->unit);
1439 if(sc != noErr){
1440 WARN("Unit failed to start: %x\n", (int)sc);
1441 if(This->converter){
1442 AudioConverterDispose(This->converter);
1443 This->converter = NULL;
1445 CoTaskMemFree(This->fmt);
1446 This->fmt = NULL;
1447 OSSpinLockUnlock(&This->lock);
1448 return osstatus_to_hresult(sc);
1451 This->local_buffer = HeapAlloc(GetProcessHeap(), 0, This->bufsize_frames * fmt->nBlockAlign);
1452 silence_buffer(This, This->local_buffer, This->bufsize_frames);
1454 if(This->dataflow == eCapture){
1455 This->cap_bufsize_frames = MulDiv(duration, This->dev_desc.mSampleRate, 10000000);
1456 This->cap_buffer = HeapAlloc(GetProcessHeap(), 0, This->cap_bufsize_frames * This->fmt->nBlockAlign);
1459 This->vols = HeapAlloc(GetProcessHeap(), 0, fmt->nChannels * sizeof(float));
1460 if(!This->vols){
1461 CoTaskMemFree(This->fmt);
1462 This->fmt = NULL;
1463 OSSpinLockUnlock(&This->lock);
1464 return E_OUTOFMEMORY;
1467 for(i = 0; i < fmt->nChannels; ++i)
1468 This->vols[i] = 1.f;
1470 This->share = mode;
1471 This->flags = flags;
1473 EnterCriticalSection(&g_sessions_lock);
1475 hr = get_audio_session(sessionguid, This->parent, fmt->nChannels,
1476 &This->session);
1477 if(FAILED(hr)){
1478 LeaveCriticalSection(&g_sessions_lock);
1479 CoTaskMemFree(This->fmt);
1480 This->fmt = NULL;
1481 HeapFree(GetProcessHeap(), 0, This->vols);
1482 This->vols = NULL;
1483 OSSpinLockUnlock(&This->lock);
1484 return E_INVALIDARG;
1487 list_add_tail(&This->session->clients, &This->entry);
1489 LeaveCriticalSection(&g_sessions_lock);
1491 ca_setvol(This, -1);
1493 This->initted = TRUE;
1495 OSSpinLockUnlock(&This->lock);
1497 return S_OK;
1500 static HRESULT WINAPI AudioClient_GetBufferSize(IAudioClient *iface,
1501 UINT32 *frames)
1503 ACImpl *This = impl_from_IAudioClient(iface);
1505 TRACE("(%p)->(%p)\n", This, frames);
1507 if(!frames)
1508 return E_POINTER;
1510 OSSpinLockLock(&This->lock);
1512 if(!This->initted){
1513 OSSpinLockUnlock(&This->lock);
1514 return AUDCLNT_E_NOT_INITIALIZED;
1517 *frames = This->bufsize_frames;
1519 OSSpinLockUnlock(&This->lock);
1521 return S_OK;
1524 static HRESULT ca_get_max_stream_latency(ACImpl *This, UInt32 *max)
1526 AudioObjectPropertyAddress addr;
1527 AudioStreamID *ids;
1528 UInt32 size;
1529 OSStatus sc;
1530 int nstreams, i;
1532 addr.mScope = This->scope;
1533 addr.mElement = 0;
1534 addr.mSelector = kAudioDevicePropertyStreams;
1536 sc = AudioObjectGetPropertyDataSize(This->adevid, &addr, 0, NULL,
1537 &size);
1538 if(sc != noErr){
1539 WARN("Unable to get size for _Streams property: %x\n", (int)sc);
1540 return osstatus_to_hresult(sc);
1543 ids = HeapAlloc(GetProcessHeap(), 0, size);
1544 if(!ids)
1545 return E_OUTOFMEMORY;
1547 sc = AudioObjectGetPropertyData(This->adevid, &addr, 0, NULL, &size, ids);
1548 if(sc != noErr){
1549 WARN("Unable to get _Streams property: %x\n", (int)sc);
1550 HeapFree(GetProcessHeap(), 0, ids);
1551 return osstatus_to_hresult(sc);
1554 nstreams = size / sizeof(AudioStreamID);
1555 *max = 0;
1557 addr.mSelector = kAudioStreamPropertyLatency;
1558 for(i = 0; i < nstreams; ++i){
1559 UInt32 latency;
1561 size = sizeof(latency);
1562 sc = AudioObjectGetPropertyData(ids[i], &addr, 0, NULL,
1563 &size, &latency);
1564 if(sc != noErr){
1565 WARN("Unable to get _Latency property: %x\n", (int)sc);
1566 continue;
1569 if(latency > *max)
1570 *max = latency;
1573 HeapFree(GetProcessHeap(), 0, ids);
1575 return S_OK;
1578 static HRESULT WINAPI AudioClient_GetStreamLatency(IAudioClient *iface,
1579 REFERENCE_TIME *out)
1581 ACImpl *This = impl_from_IAudioClient(iface);
1582 UInt32 latency, stream_latency, size;
1583 AudioObjectPropertyAddress addr;
1584 OSStatus sc;
1585 HRESULT hr;
1587 TRACE("(%p)->(%p)\n", This, out);
1589 if(!out)
1590 return E_POINTER;
1592 OSSpinLockLock(&This->lock);
1594 if(!This->initted){
1595 OSSpinLockUnlock(&This->lock);
1596 return AUDCLNT_E_NOT_INITIALIZED;
1599 addr.mScope = This->scope;
1600 addr.mSelector = kAudioDevicePropertyLatency;
1601 addr.mElement = 0;
1603 size = sizeof(latency);
1604 sc = AudioObjectGetPropertyData(This->adevid, &addr, 0, NULL,
1605 &size, &latency);
1606 if(sc != noErr){
1607 WARN("Couldn't get _Latency property: %x\n", (int)sc);
1608 OSSpinLockUnlock(&This->lock);
1609 return osstatus_to_hresult(sc);
1612 hr = ca_get_max_stream_latency(This, &stream_latency);
1613 if(FAILED(hr)){
1614 OSSpinLockUnlock(&This->lock);
1615 return hr;
1618 latency += stream_latency;
1619 /* pretend we process audio in Period chunks, so max latency includes
1620 * the period time */
1621 *out = MulDiv(latency, 10000000, This->fmt->nSamplesPerSec)
1622 + This->period_ms * 10000;
1624 OSSpinLockUnlock(&This->lock);
1626 return S_OK;
1629 static HRESULT AudioClient_GetCurrentPadding_nolock(ACImpl *This,
1630 UINT32 *numpad)
1632 if(!This->initted)
1633 return AUDCLNT_E_NOT_INITIALIZED;
1635 if(This->dataflow == eCapture)
1636 capture_resample(This);
1638 *numpad = This->held_frames;
1640 return S_OK;
1643 static HRESULT WINAPI AudioClient_GetCurrentPadding(IAudioClient *iface,
1644 UINT32 *numpad)
1646 ACImpl *This = impl_from_IAudioClient(iface);
1647 HRESULT hr;
1649 TRACE("(%p)->(%p)\n", This, numpad);
1651 if(!numpad)
1652 return E_POINTER;
1654 OSSpinLockLock(&This->lock);
1656 hr = AudioClient_GetCurrentPadding_nolock(This, numpad);
1658 OSSpinLockUnlock(&This->lock);
1660 return hr;
1663 static HRESULT WINAPI AudioClient_IsFormatSupported(IAudioClient *iface,
1664 AUDCLNT_SHAREMODE mode, const WAVEFORMATEX *pwfx,
1665 WAVEFORMATEX **outpwfx)
1667 ACImpl *This = impl_from_IAudioClient(iface);
1668 AudioStreamBasicDescription dev_desc;
1669 AudioConverterRef converter;
1670 AudioComponentInstance unit;
1671 WAVEFORMATEXTENSIBLE *fmtex = (WAVEFORMATEXTENSIBLE*)pwfx;
1672 HRESULT hr;
1674 TRACE("(%p)->(%x, %p, %p)\n", This, mode, pwfx, outpwfx);
1676 if(!pwfx || (mode == AUDCLNT_SHAREMODE_SHARED && !outpwfx))
1677 return E_POINTER;
1679 if(mode != AUDCLNT_SHAREMODE_SHARED && mode != AUDCLNT_SHAREMODE_EXCLUSIVE)
1680 return E_INVALIDARG;
1682 if(pwfx->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
1683 pwfx->cbSize < sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX))
1684 return E_INVALIDARG;
1686 dump_fmt(pwfx);
1688 if(outpwfx){
1689 *outpwfx = NULL;
1690 if(mode != AUDCLNT_SHAREMODE_SHARED)
1691 outpwfx = NULL;
1694 if(pwfx->wFormatTag == WAVE_FORMAT_EXTENSIBLE){
1695 if(pwfx->nAvgBytesPerSec == 0 ||
1696 pwfx->nBlockAlign == 0 ||
1697 fmtex->Samples.wValidBitsPerSample > pwfx->wBitsPerSample)
1698 return E_INVALIDARG;
1699 if(fmtex->Samples.wValidBitsPerSample < pwfx->wBitsPerSample)
1700 goto unsupported;
1701 if(mode == AUDCLNT_SHAREMODE_EXCLUSIVE){
1702 if(fmtex->dwChannelMask == 0 ||
1703 fmtex->dwChannelMask & SPEAKER_RESERVED)
1704 goto unsupported;
1708 if(pwfx->nBlockAlign != pwfx->nChannels * pwfx->wBitsPerSample / 8 ||
1709 pwfx->nAvgBytesPerSec != pwfx->nBlockAlign * pwfx->nSamplesPerSec)
1710 goto unsupported;
1712 if(pwfx->nChannels == 0)
1713 return AUDCLNT_E_UNSUPPORTED_FORMAT;
1715 unit = get_audiounit(This->dataflow, This->adevid);
1717 converter = NULL;
1718 hr = ca_setup_audiounit(This->dataflow, unit, pwfx, &dev_desc, &converter);
1719 AudioComponentInstanceDispose(unit);
1720 if(FAILED(hr))
1721 goto unsupported;
1723 if(converter)
1724 AudioConverterDispose(converter);
1726 return S_OK;
1728 unsupported:
1729 if(outpwfx){
1730 hr = IAudioClient_GetMixFormat(&This->IAudioClient_iface, outpwfx);
1731 if(FAILED(hr))
1732 return hr;
1733 return S_FALSE;
1736 return AUDCLNT_E_UNSUPPORTED_FORMAT;
1739 static HRESULT WINAPI AudioClient_GetMixFormat(IAudioClient *iface,
1740 WAVEFORMATEX **pwfx)
1742 ACImpl *This = impl_from_IAudioClient(iface);
1743 WAVEFORMATEXTENSIBLE *fmt;
1744 OSStatus sc;
1745 UInt32 size;
1746 Float64 rate;
1747 AudioBufferList *buffers;
1748 AudioObjectPropertyAddress addr;
1749 int i;
1751 TRACE("(%p)->(%p)\n", This, pwfx);
1753 if(!pwfx)
1754 return E_POINTER;
1755 *pwfx = NULL;
1757 fmt = CoTaskMemAlloc(sizeof(WAVEFORMATEXTENSIBLE));
1758 if(!fmt)
1759 return E_OUTOFMEMORY;
1761 fmt->Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
1763 addr.mScope = This->scope;
1764 addr.mElement = 0;
1765 addr.mSelector = kAudioDevicePropertyStreamConfiguration;
1767 sc = AudioObjectGetPropertyDataSize(This->adevid, &addr, 0, NULL, &size);
1768 if(sc != noErr){
1769 CoTaskMemFree(fmt);
1770 WARN("Unable to get size for _StreamConfiguration property: %x\n", (int)sc);
1771 return osstatus_to_hresult(sc);
1774 buffers = HeapAlloc(GetProcessHeap(), 0, size);
1775 if(!buffers){
1776 CoTaskMemFree(fmt);
1777 return E_OUTOFMEMORY;
1780 sc = AudioObjectGetPropertyData(This->adevid, &addr, 0, NULL,
1781 &size, buffers);
1782 if(sc != noErr){
1783 CoTaskMemFree(fmt);
1784 HeapFree(GetProcessHeap(), 0, buffers);
1785 WARN("Unable to get _StreamConfiguration property: %x\n", (int)sc);
1786 return osstatus_to_hresult(sc);
1789 fmt->Format.nChannels = 0;
1790 for(i = 0; i < buffers->mNumberBuffers; ++i)
1791 fmt->Format.nChannels += buffers->mBuffers[i].mNumberChannels;
1793 HeapFree(GetProcessHeap(), 0, buffers);
1795 fmt->dwChannelMask = get_channel_mask(fmt->Format.nChannels);
1797 addr.mSelector = kAudioDevicePropertyNominalSampleRate;
1798 size = sizeof(Float64);
1799 sc = AudioObjectGetPropertyData(This->adevid, &addr, 0, NULL, &size, &rate);
1800 if(sc != noErr){
1801 CoTaskMemFree(fmt);
1802 WARN("Unable to get _NominalSampleRate property: %x\n", (int)sc);
1803 return osstatus_to_hresult(sc);
1805 fmt->Format.nSamplesPerSec = rate;
1807 fmt->Format.wBitsPerSample = 32;
1808 fmt->SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
1810 fmt->Format.nBlockAlign = (fmt->Format.wBitsPerSample *
1811 fmt->Format.nChannels) / 8;
1812 fmt->Format.nAvgBytesPerSec = fmt->Format.nSamplesPerSec *
1813 fmt->Format.nBlockAlign;
1815 fmt->Samples.wValidBitsPerSample = fmt->Format.wBitsPerSample;
1816 fmt->Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX);
1818 *pwfx = (WAVEFORMATEX*)fmt;
1819 dump_fmt(*pwfx);
1821 return S_OK;
1824 static HRESULT WINAPI AudioClient_GetDevicePeriod(IAudioClient *iface,
1825 REFERENCE_TIME *defperiod, REFERENCE_TIME *minperiod)
1827 ACImpl *This = impl_from_IAudioClient(iface);
1829 TRACE("(%p)->(%p, %p)\n", This, defperiod, minperiod);
1831 if(!defperiod && !minperiod)
1832 return E_POINTER;
1834 if(defperiod)
1835 *defperiod = DefaultPeriod;
1836 if(minperiod)
1837 *minperiod = MinimumPeriod;
1839 return S_OK;
1842 void CALLBACK ca_period_cb(void *user, BOOLEAN timer)
1844 ACImpl *This = user;
1846 if(This->event)
1847 SetEvent(This->event);
1850 static HRESULT WINAPI AudioClient_Start(IAudioClient *iface)
1852 ACImpl *This = impl_from_IAudioClient(iface);
1854 TRACE("(%p)\n", This);
1856 OSSpinLockLock(&This->lock);
1858 if(!This->initted){
1859 OSSpinLockUnlock(&This->lock);
1860 return AUDCLNT_E_NOT_INITIALIZED;
1863 if(This->playing){
1864 OSSpinLockUnlock(&This->lock);
1865 return AUDCLNT_E_NOT_STOPPED;
1868 if((This->flags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK) && !This->event){
1869 OSSpinLockUnlock(&This->lock);
1870 return AUDCLNT_E_EVENTHANDLE_NOT_SET;
1873 if(This->event && !This->timer)
1874 if(!CreateTimerQueueTimer(&This->timer, g_timer_q, ca_period_cb,
1875 This, 0, This->period_ms, WT_EXECUTEINTIMERTHREAD)){
1876 This->timer = NULL;
1877 OSSpinLockUnlock(&This->lock);
1878 WARN("Unable to create timer: %u\n", GetLastError());
1879 return E_OUTOFMEMORY;
1882 This->playing = TRUE;
1884 OSSpinLockUnlock(&This->lock);
1886 return S_OK;
1889 static HRESULT WINAPI AudioClient_Stop(IAudioClient *iface)
1891 ACImpl *This = impl_from_IAudioClient(iface);
1893 TRACE("(%p)\n", This);
1895 OSSpinLockLock(&This->lock);
1897 if(!This->initted){
1898 OSSpinLockUnlock(&This->lock);
1899 return AUDCLNT_E_NOT_INITIALIZED;
1902 if(!This->playing){
1903 OSSpinLockUnlock(&This->lock);
1904 return S_FALSE;
1907 This->playing = FALSE;
1909 OSSpinLockUnlock(&This->lock);
1911 return S_OK;
1914 static HRESULT WINAPI AudioClient_Reset(IAudioClient *iface)
1916 ACImpl *This = impl_from_IAudioClient(iface);
1918 TRACE("(%p)\n", This);
1920 OSSpinLockLock(&This->lock);
1922 if(!This->initted){
1923 OSSpinLockUnlock(&This->lock);
1924 return AUDCLNT_E_NOT_INITIALIZED;
1927 if(This->playing){
1928 OSSpinLockUnlock(&This->lock);
1929 return AUDCLNT_E_NOT_STOPPED;
1932 if(This->getbuf_last){
1933 OSSpinLockUnlock(&This->lock);
1934 return AUDCLNT_E_BUFFER_OPERATION_PENDING;
1937 if(This->dataflow == eRender){
1938 This->written_frames = 0;
1939 }else{
1940 This->written_frames += This->held_frames;
1943 This->held_frames = 0;
1944 This->lcl_offs_frames = 0;
1945 This->wri_offs_frames = 0;
1946 This->cap_offs_frames = 0;
1947 This->cap_held_frames = 0;
1949 OSSpinLockUnlock(&This->lock);
1951 return S_OK;
1954 static HRESULT WINAPI AudioClient_SetEventHandle(IAudioClient *iface,
1955 HANDLE event)
1957 ACImpl *This = impl_from_IAudioClient(iface);
1959 TRACE("(%p)->(%p)\n", This, event);
1961 if(!event)
1962 return E_INVALIDARG;
1964 OSSpinLockLock(&This->lock);
1966 if(!This->initted){
1967 OSSpinLockUnlock(&This->lock);
1968 return AUDCLNT_E_NOT_INITIALIZED;
1971 if(!(This->flags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK)){
1972 OSSpinLockUnlock(&This->lock);
1973 return AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED;
1976 if (This->event){
1977 OSSpinLockUnlock(&This->lock);
1978 FIXME("called twice\n");
1979 return HRESULT_FROM_WIN32(ERROR_INVALID_NAME);
1982 This->event = event;
1984 OSSpinLockUnlock(&This->lock);
1986 return S_OK;
1989 static HRESULT WINAPI AudioClient_GetService(IAudioClient *iface, REFIID riid,
1990 void **ppv)
1992 ACImpl *This = impl_from_IAudioClient(iface);
1994 TRACE("(%p)->(%s, %p)\n", This, debugstr_guid(riid), ppv);
1996 if(!ppv)
1997 return E_POINTER;
1998 *ppv = NULL;
2000 OSSpinLockLock(&This->lock);
2002 if(!This->initted){
2003 OSSpinLockUnlock(&This->lock);
2004 return AUDCLNT_E_NOT_INITIALIZED;
2007 if(IsEqualIID(riid, &IID_IAudioRenderClient)){
2008 if(This->dataflow != eRender){
2009 OSSpinLockUnlock(&This->lock);
2010 return AUDCLNT_E_WRONG_ENDPOINT_TYPE;
2012 IAudioRenderClient_AddRef(&This->IAudioRenderClient_iface);
2013 *ppv = &This->IAudioRenderClient_iface;
2014 }else if(IsEqualIID(riid, &IID_IAudioCaptureClient)){
2015 if(This->dataflow != eCapture){
2016 OSSpinLockUnlock(&This->lock);
2017 return AUDCLNT_E_WRONG_ENDPOINT_TYPE;
2019 IAudioCaptureClient_AddRef(&This->IAudioCaptureClient_iface);
2020 *ppv = &This->IAudioCaptureClient_iface;
2021 }else if(IsEqualIID(riid, &IID_IAudioClock)){
2022 IAudioClock_AddRef(&This->IAudioClock_iface);
2023 *ppv = &This->IAudioClock_iface;
2024 }else if(IsEqualIID(riid, &IID_IAudioStreamVolume)){
2025 IAudioStreamVolume_AddRef(&This->IAudioStreamVolume_iface);
2026 *ppv = &This->IAudioStreamVolume_iface;
2027 }else if(IsEqualIID(riid, &IID_IAudioSessionControl)){
2028 if(!This->session_wrapper){
2029 This->session_wrapper = AudioSessionWrapper_Create(This);
2030 if(!This->session_wrapper){
2031 OSSpinLockUnlock(&This->lock);
2032 return E_OUTOFMEMORY;
2034 }else
2035 IAudioSessionControl2_AddRef(&This->session_wrapper->IAudioSessionControl2_iface);
2037 *ppv = &This->session_wrapper->IAudioSessionControl2_iface;
2038 }else if(IsEqualIID(riid, &IID_IChannelAudioVolume)){
2039 if(!This->session_wrapper){
2040 This->session_wrapper = AudioSessionWrapper_Create(This);
2041 if(!This->session_wrapper){
2042 OSSpinLockUnlock(&This->lock);
2043 return E_OUTOFMEMORY;
2045 }else
2046 IChannelAudioVolume_AddRef(&This->session_wrapper->IChannelAudioVolume_iface);
2048 *ppv = &This->session_wrapper->IChannelAudioVolume_iface;
2049 }else if(IsEqualIID(riid, &IID_ISimpleAudioVolume)){
2050 if(!This->session_wrapper){
2051 This->session_wrapper = AudioSessionWrapper_Create(This);
2052 if(!This->session_wrapper){
2053 OSSpinLockUnlock(&This->lock);
2054 return E_OUTOFMEMORY;
2056 }else
2057 ISimpleAudioVolume_AddRef(&This->session_wrapper->ISimpleAudioVolume_iface);
2059 *ppv = &This->session_wrapper->ISimpleAudioVolume_iface;
2062 if(*ppv){
2063 OSSpinLockUnlock(&This->lock);
2064 return S_OK;
2067 OSSpinLockUnlock(&This->lock);
2069 FIXME("stub %s\n", debugstr_guid(riid));
2070 return E_NOINTERFACE;
2073 static const IAudioClientVtbl AudioClient_Vtbl =
2075 AudioClient_QueryInterface,
2076 AudioClient_AddRef,
2077 AudioClient_Release,
2078 AudioClient_Initialize,
2079 AudioClient_GetBufferSize,
2080 AudioClient_GetStreamLatency,
2081 AudioClient_GetCurrentPadding,
2082 AudioClient_IsFormatSupported,
2083 AudioClient_GetMixFormat,
2084 AudioClient_GetDevicePeriod,
2085 AudioClient_Start,
2086 AudioClient_Stop,
2087 AudioClient_Reset,
2088 AudioClient_SetEventHandle,
2089 AudioClient_GetService
2092 static HRESULT WINAPI AudioRenderClient_QueryInterface(
2093 IAudioRenderClient *iface, REFIID riid, void **ppv)
2095 ACImpl *This = impl_from_IAudioRenderClient(iface);
2096 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
2098 if(!ppv)
2099 return E_POINTER;
2100 *ppv = NULL;
2102 if(IsEqualIID(riid, &IID_IUnknown) ||
2103 IsEqualIID(riid, &IID_IAudioRenderClient))
2104 *ppv = iface;
2105 else if(IsEqualIID(riid, &IID_IMarshal))
2106 return IUnknown_QueryInterface(This->pUnkFTMarshal, riid, ppv);
2108 if(*ppv){
2109 IUnknown_AddRef((IUnknown*)*ppv);
2110 return S_OK;
2113 WARN("Unknown interface %s\n", debugstr_guid(riid));
2114 return E_NOINTERFACE;
2117 static ULONG WINAPI AudioRenderClient_AddRef(IAudioRenderClient *iface)
2119 ACImpl *This = impl_from_IAudioRenderClient(iface);
2120 return AudioClient_AddRef(&This->IAudioClient_iface);
2123 static ULONG WINAPI AudioRenderClient_Release(IAudioRenderClient *iface)
2125 ACImpl *This = impl_from_IAudioRenderClient(iface);
2126 return AudioClient_Release(&This->IAudioClient_iface);
2129 static HRESULT WINAPI AudioRenderClient_GetBuffer(IAudioRenderClient *iface,
2130 UINT32 frames, BYTE **data)
2132 ACImpl *This = impl_from_IAudioRenderClient(iface);
2133 UINT32 pad;
2134 HRESULT hr;
2136 TRACE("(%p)->(%u, %p)\n", This, frames, data);
2138 if(!data)
2139 return E_POINTER;
2140 *data = NULL;
2142 OSSpinLockLock(&This->lock);
2144 if(This->getbuf_last){
2145 OSSpinLockUnlock(&This->lock);
2146 return AUDCLNT_E_OUT_OF_ORDER;
2149 if(!frames){
2150 OSSpinLockUnlock(&This->lock);
2151 return S_OK;
2154 hr = AudioClient_GetCurrentPadding_nolock(This, &pad);
2155 if(FAILED(hr)){
2156 OSSpinLockUnlock(&This->lock);
2157 return hr;
2160 if(pad + frames > This->bufsize_frames){
2161 OSSpinLockUnlock(&This->lock);
2162 return AUDCLNT_E_BUFFER_TOO_LARGE;
2165 if(This->wri_offs_frames + frames > This->bufsize_frames){
2166 if(This->tmp_buffer_frames < frames){
2167 HeapFree(GetProcessHeap(), 0, This->tmp_buffer);
2168 This->tmp_buffer = HeapAlloc(GetProcessHeap(), 0, frames * This->fmt->nBlockAlign);
2169 if(!This->tmp_buffer){
2170 OSSpinLockUnlock(&This->lock);
2171 return E_OUTOFMEMORY;
2173 This->tmp_buffer_frames = frames;
2175 *data = This->tmp_buffer;
2176 This->getbuf_last = -frames;
2177 }else{
2178 *data = This->local_buffer + This->wri_offs_frames * This->fmt->nBlockAlign;
2179 This->getbuf_last = frames;
2182 silence_buffer(This, *data, frames);
2184 OSSpinLockUnlock(&This->lock);
2186 return S_OK;
2189 static HRESULT WINAPI AudioRenderClient_ReleaseBuffer(
2190 IAudioRenderClient *iface, UINT32 frames, DWORD flags)
2192 ACImpl *This = impl_from_IAudioRenderClient(iface);
2193 BYTE *buffer;
2195 TRACE("(%p)->(%u, %x)\n", This, frames, flags);
2197 OSSpinLockLock(&This->lock);
2199 if(!frames){
2200 This->getbuf_last = 0;
2201 OSSpinLockUnlock(&This->lock);
2202 return S_OK;
2205 if(!This->getbuf_last){
2206 OSSpinLockUnlock(&This->lock);
2207 return AUDCLNT_E_OUT_OF_ORDER;
2210 if(frames > (This->getbuf_last >= 0 ? This->getbuf_last : -This->getbuf_last)){
2211 OSSpinLockUnlock(&This->lock);
2212 return AUDCLNT_E_INVALID_SIZE;
2215 if(This->getbuf_last >= 0)
2216 buffer = This->local_buffer + This->wri_offs_frames * This->fmt->nBlockAlign;
2217 else
2218 buffer = This->tmp_buffer;
2220 if(flags & AUDCLNT_BUFFERFLAGS_SILENT)
2221 silence_buffer(This, buffer, frames);
2223 if(This->getbuf_last < 0)
2224 ca_wrap_buffer(This->local_buffer,
2225 This->wri_offs_frames * This->fmt->nBlockAlign,
2226 This->bufsize_frames * This->fmt->nBlockAlign,
2227 buffer, frames * This->fmt->nBlockAlign);
2230 This->wri_offs_frames += frames;
2231 This->wri_offs_frames %= This->bufsize_frames;
2232 This->held_frames += frames;
2233 This->written_frames += frames;
2234 This->getbuf_last = 0;
2236 OSSpinLockUnlock(&This->lock);
2238 return S_OK;
2241 static const IAudioRenderClientVtbl AudioRenderClient_Vtbl = {
2242 AudioRenderClient_QueryInterface,
2243 AudioRenderClient_AddRef,
2244 AudioRenderClient_Release,
2245 AudioRenderClient_GetBuffer,
2246 AudioRenderClient_ReleaseBuffer
2249 static HRESULT WINAPI AudioCaptureClient_QueryInterface(
2250 IAudioCaptureClient *iface, REFIID riid, void **ppv)
2252 ACImpl *This = impl_from_IAudioCaptureClient(iface);
2253 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
2255 if(!ppv)
2256 return E_POINTER;
2257 *ppv = NULL;
2259 if(IsEqualIID(riid, &IID_IUnknown) ||
2260 IsEqualIID(riid, &IID_IAudioCaptureClient))
2261 *ppv = iface;
2262 else if(IsEqualIID(riid, &IID_IMarshal))
2263 return IUnknown_QueryInterface(This->pUnkFTMarshal, riid, ppv);
2265 if(*ppv){
2266 IUnknown_AddRef((IUnknown*)*ppv);
2267 return S_OK;
2270 WARN("Unknown interface %s\n", debugstr_guid(riid));
2271 return E_NOINTERFACE;
2274 static ULONG WINAPI AudioCaptureClient_AddRef(IAudioCaptureClient *iface)
2276 ACImpl *This = impl_from_IAudioCaptureClient(iface);
2277 return IAudioClient_AddRef(&This->IAudioClient_iface);
2280 static ULONG WINAPI AudioCaptureClient_Release(IAudioCaptureClient *iface)
2282 ACImpl *This = impl_from_IAudioCaptureClient(iface);
2283 return IAudioClient_Release(&This->IAudioClient_iface);
2286 static HRESULT WINAPI AudioCaptureClient_GetBuffer(IAudioCaptureClient *iface,
2287 BYTE **data, UINT32 *frames, DWORD *flags, UINT64 *devpos,
2288 UINT64 *qpcpos)
2290 ACImpl *This = impl_from_IAudioCaptureClient(iface);
2291 UINT32 chunk_bytes, chunk_frames;
2293 TRACE("(%p)->(%p, %p, %p, %p, %p)\n", This, data, frames, flags,
2294 devpos, qpcpos);
2296 if(!data || !frames || !flags)
2297 return E_POINTER;
2299 OSSpinLockLock(&This->lock);
2301 if(This->getbuf_last){
2302 OSSpinLockUnlock(&This->lock);
2303 return AUDCLNT_E_OUT_OF_ORDER;
2306 capture_resample(This);
2308 if(This->held_frames < This->period_frames){
2309 *frames = 0;
2310 OSSpinLockUnlock(&This->lock);
2311 return AUDCLNT_S_BUFFER_EMPTY;
2314 *flags = 0;
2316 chunk_frames = This->bufsize_frames - This->lcl_offs_frames;
2317 if(chunk_frames < This->period_frames){
2318 chunk_bytes = chunk_frames * This->fmt->nBlockAlign;
2319 if(!This->tmp_buffer)
2320 This->tmp_buffer = HeapAlloc(GetProcessHeap(), 0, This->period_frames * This->fmt->nBlockAlign);
2321 *data = This->tmp_buffer;
2322 memcpy(*data, This->local_buffer + This->lcl_offs_frames * This->fmt->nBlockAlign, chunk_bytes);
2323 memcpy((*data) + chunk_bytes, This->local_buffer, This->period_frames * This->fmt->nBlockAlign - chunk_bytes);
2324 }else
2325 *data = This->local_buffer + This->lcl_offs_frames * This->fmt->nBlockAlign;
2327 This->getbuf_last = *frames = This->period_frames;
2329 if(devpos)
2330 *devpos = This->written_frames;
2331 if(qpcpos){ /* fixme: qpc of recording time */
2332 LARGE_INTEGER stamp, freq;
2333 QueryPerformanceCounter(&stamp);
2334 QueryPerformanceFrequency(&freq);
2335 *qpcpos = (stamp.QuadPart * (INT64)10000000) / freq.QuadPart;
2338 OSSpinLockUnlock(&This->lock);
2340 return S_OK;
2343 static HRESULT WINAPI AudioCaptureClient_ReleaseBuffer(
2344 IAudioCaptureClient *iface, UINT32 done)
2346 ACImpl *This = impl_from_IAudioCaptureClient(iface);
2348 TRACE("(%p)->(%u)\n", This, done);
2350 OSSpinLockLock(&This->lock);
2352 if(!done){
2353 This->getbuf_last = 0;
2354 OSSpinLockUnlock(&This->lock);
2355 return S_OK;
2358 if(!This->getbuf_last){
2359 OSSpinLockUnlock(&This->lock);
2360 return AUDCLNT_E_OUT_OF_ORDER;
2363 if(This->getbuf_last != done){
2364 OSSpinLockUnlock(&This->lock);
2365 return AUDCLNT_E_INVALID_SIZE;
2368 This->written_frames += done;
2369 This->held_frames -= done;
2370 This->lcl_offs_frames += done;
2371 This->lcl_offs_frames %= This->bufsize_frames;
2372 This->getbuf_last = 0;
2374 OSSpinLockUnlock(&This->lock);
2376 return S_OK;
2379 static HRESULT WINAPI AudioCaptureClient_GetNextPacketSize(
2380 IAudioCaptureClient *iface, UINT32 *frames)
2382 ACImpl *This = impl_from_IAudioCaptureClient(iface);
2384 TRACE("(%p)->(%p)\n", This, frames);
2386 if(!frames)
2387 return E_POINTER;
2389 OSSpinLockLock(&This->lock);
2391 capture_resample(This);
2393 if(This->held_frames >= This->period_frames)
2394 *frames = This->period_frames;
2395 else
2396 *frames = 0;
2398 OSSpinLockUnlock(&This->lock);
2400 return S_OK;
2403 static const IAudioCaptureClientVtbl AudioCaptureClient_Vtbl =
2405 AudioCaptureClient_QueryInterface,
2406 AudioCaptureClient_AddRef,
2407 AudioCaptureClient_Release,
2408 AudioCaptureClient_GetBuffer,
2409 AudioCaptureClient_ReleaseBuffer,
2410 AudioCaptureClient_GetNextPacketSize
2413 static HRESULT WINAPI AudioClock_QueryInterface(IAudioClock *iface,
2414 REFIID riid, void **ppv)
2416 ACImpl *This = impl_from_IAudioClock(iface);
2418 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
2420 if(!ppv)
2421 return E_POINTER;
2422 *ppv = NULL;
2424 if(IsEqualIID(riid, &IID_IUnknown) || IsEqualIID(riid, &IID_IAudioClock))
2425 *ppv = iface;
2426 else if(IsEqualIID(riid, &IID_IAudioClock2))
2427 *ppv = &This->IAudioClock2_iface;
2428 if(*ppv){
2429 IUnknown_AddRef((IUnknown*)*ppv);
2430 return S_OK;
2433 WARN("Unknown interface %s\n", debugstr_guid(riid));
2434 return E_NOINTERFACE;
2437 static ULONG WINAPI AudioClock_AddRef(IAudioClock *iface)
2439 ACImpl *This = impl_from_IAudioClock(iface);
2440 return IAudioClient_AddRef(&This->IAudioClient_iface);
2443 static ULONG WINAPI AudioClock_Release(IAudioClock *iface)
2445 ACImpl *This = impl_from_IAudioClock(iface);
2446 return IAudioClient_Release(&This->IAudioClient_iface);
2449 static HRESULT WINAPI AudioClock_GetFrequency(IAudioClock *iface, UINT64 *freq)
2451 ACImpl *This = impl_from_IAudioClock(iface);
2453 TRACE("(%p)->(%p)\n", This, freq);
2455 if(This->share == AUDCLNT_SHAREMODE_SHARED)
2456 *freq = (UINT64)This->fmt->nSamplesPerSec * This->fmt->nBlockAlign;
2457 else
2458 *freq = This->fmt->nSamplesPerSec;
2460 return S_OK;
2463 static HRESULT AudioClock_GetPosition_nolock(ACImpl *This,
2464 UINT64 *pos, UINT64 *qpctime)
2466 *pos = This->written_frames - This->held_frames;
2468 if(This->share == AUDCLNT_SHAREMODE_SHARED)
2469 *pos *= This->fmt->nBlockAlign;
2471 if(qpctime){
2472 LARGE_INTEGER stamp, freq;
2473 QueryPerformanceCounter(&stamp);
2474 QueryPerformanceFrequency(&freq);
2475 *qpctime = (stamp.QuadPart * (INT64)10000000) / freq.QuadPart;
2478 return S_OK;
2481 static HRESULT WINAPI AudioClock_GetPosition(IAudioClock *iface, UINT64 *pos,
2482 UINT64 *qpctime)
2484 ACImpl *This = impl_from_IAudioClock(iface);
2485 HRESULT hr;
2487 TRACE("(%p)->(%p, %p)\n", This, pos, qpctime);
2489 if(!pos)
2490 return E_POINTER;
2492 OSSpinLockLock(&This->lock);
2494 hr = AudioClock_GetPosition_nolock(This, pos, qpctime);
2496 OSSpinLockUnlock(&This->lock);
2498 return hr;
2501 static HRESULT WINAPI AudioClock_GetCharacteristics(IAudioClock *iface,
2502 DWORD *chars)
2504 ACImpl *This = impl_from_IAudioClock(iface);
2506 TRACE("(%p)->(%p)\n", This, chars);
2508 if(!chars)
2509 return E_POINTER;
2511 *chars = AUDIOCLOCK_CHARACTERISTIC_FIXED_FREQ;
2513 return S_OK;
2516 static const IAudioClockVtbl AudioClock_Vtbl =
2518 AudioClock_QueryInterface,
2519 AudioClock_AddRef,
2520 AudioClock_Release,
2521 AudioClock_GetFrequency,
2522 AudioClock_GetPosition,
2523 AudioClock_GetCharacteristics
2526 static HRESULT WINAPI AudioClock2_QueryInterface(IAudioClock2 *iface,
2527 REFIID riid, void **ppv)
2529 ACImpl *This = impl_from_IAudioClock2(iface);
2530 return IAudioClock_QueryInterface(&This->IAudioClock_iface, riid, ppv);
2533 static ULONG WINAPI AudioClock2_AddRef(IAudioClock2 *iface)
2535 ACImpl *This = impl_from_IAudioClock2(iface);
2536 return IAudioClient_AddRef(&This->IAudioClient_iface);
2539 static ULONG WINAPI AudioClock2_Release(IAudioClock2 *iface)
2541 ACImpl *This = impl_from_IAudioClock2(iface);
2542 return IAudioClient_Release(&This->IAudioClient_iface);
2545 static HRESULT WINAPI AudioClock2_GetDevicePosition(IAudioClock2 *iface,
2546 UINT64 *pos, UINT64 *qpctime)
2548 ACImpl *This = impl_from_IAudioClock2(iface);
2550 FIXME("(%p)->(%p, %p)\n", This, pos, qpctime);
2552 return E_NOTIMPL;
2555 static const IAudioClock2Vtbl AudioClock2_Vtbl =
2557 AudioClock2_QueryInterface,
2558 AudioClock2_AddRef,
2559 AudioClock2_Release,
2560 AudioClock2_GetDevicePosition
2563 static AudioSessionWrapper *AudioSessionWrapper_Create(ACImpl *client)
2565 AudioSessionWrapper *ret;
2567 ret = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
2568 sizeof(AudioSessionWrapper));
2569 if(!ret)
2570 return NULL;
2572 ret->IAudioSessionControl2_iface.lpVtbl = &AudioSessionControl2_Vtbl;
2573 ret->ISimpleAudioVolume_iface.lpVtbl = &SimpleAudioVolume_Vtbl;
2574 ret->IChannelAudioVolume_iface.lpVtbl = &ChannelAudioVolume_Vtbl;
2576 ret->ref = 1;
2578 ret->client = client;
2579 if(client){
2580 ret->session = client->session;
2581 AudioClient_AddRef(&client->IAudioClient_iface);
2584 return ret;
2587 static HRESULT WINAPI AudioSessionControl_QueryInterface(
2588 IAudioSessionControl2 *iface, REFIID riid, void **ppv)
2590 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
2592 if(!ppv)
2593 return E_POINTER;
2594 *ppv = NULL;
2596 if(IsEqualIID(riid, &IID_IUnknown) ||
2597 IsEqualIID(riid, &IID_IAudioSessionControl) ||
2598 IsEqualIID(riid, &IID_IAudioSessionControl2))
2599 *ppv = iface;
2600 if(*ppv){
2601 IUnknown_AddRef((IUnknown*)*ppv);
2602 return S_OK;
2605 WARN("Unknown interface %s\n", debugstr_guid(riid));
2606 return E_NOINTERFACE;
2609 static ULONG WINAPI AudioSessionControl_AddRef(IAudioSessionControl2 *iface)
2611 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2612 ULONG ref;
2613 ref = InterlockedIncrement(&This->ref);
2614 TRACE("(%p) Refcount now %u\n", This, ref);
2615 return ref;
2618 static ULONG WINAPI AudioSessionControl_Release(IAudioSessionControl2 *iface)
2620 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2621 ULONG ref;
2622 ref = InterlockedDecrement(&This->ref);
2623 TRACE("(%p) Refcount now %u\n", This, ref);
2624 if(!ref){
2625 if(This->client){
2626 OSSpinLockLock(&This->client->lock);
2627 This->client->session_wrapper = NULL;
2628 OSSpinLockUnlock(&This->client->lock);
2629 AudioClient_Release(&This->client->IAudioClient_iface);
2631 HeapFree(GetProcessHeap(), 0, This);
2633 return ref;
2636 static HRESULT WINAPI AudioSessionControl_GetState(IAudioSessionControl2 *iface,
2637 AudioSessionState *state)
2639 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2640 ACImpl *client;
2642 TRACE("(%p)->(%p)\n", This, state);
2644 if(!state)
2645 return NULL_PTR_ERR;
2647 EnterCriticalSection(&g_sessions_lock);
2649 if(list_empty(&This->session->clients)){
2650 *state = AudioSessionStateExpired;
2651 LeaveCriticalSection(&g_sessions_lock);
2652 return S_OK;
2655 LIST_FOR_EACH_ENTRY(client, &This->session->clients, ACImpl, entry){
2656 OSSpinLockLock(&client->lock);
2657 if(client->playing){
2658 *state = AudioSessionStateActive;
2659 OSSpinLockUnlock(&client->lock);
2660 LeaveCriticalSection(&g_sessions_lock);
2661 return S_OK;
2663 OSSpinLockUnlock(&client->lock);
2666 LeaveCriticalSection(&g_sessions_lock);
2668 *state = AudioSessionStateInactive;
2670 return S_OK;
2673 static HRESULT WINAPI AudioSessionControl_GetDisplayName(
2674 IAudioSessionControl2 *iface, WCHAR **name)
2676 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2678 FIXME("(%p)->(%p) - stub\n", This, name);
2680 return E_NOTIMPL;
2683 static HRESULT WINAPI AudioSessionControl_SetDisplayName(
2684 IAudioSessionControl2 *iface, const WCHAR *name, const GUID *session)
2686 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2688 FIXME("(%p)->(%p, %s) - stub\n", This, name, debugstr_guid(session));
2690 return E_NOTIMPL;
2693 static HRESULT WINAPI AudioSessionControl_GetIconPath(
2694 IAudioSessionControl2 *iface, WCHAR **path)
2696 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2698 FIXME("(%p)->(%p) - stub\n", This, path);
2700 return E_NOTIMPL;
2703 static HRESULT WINAPI AudioSessionControl_SetIconPath(
2704 IAudioSessionControl2 *iface, const WCHAR *path, const GUID *session)
2706 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2708 FIXME("(%p)->(%p, %s) - stub\n", This, path, debugstr_guid(session));
2710 return E_NOTIMPL;
2713 static HRESULT WINAPI AudioSessionControl_GetGroupingParam(
2714 IAudioSessionControl2 *iface, GUID *group)
2716 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2718 FIXME("(%p)->(%p) - stub\n", This, group);
2720 return E_NOTIMPL;
2723 static HRESULT WINAPI AudioSessionControl_SetGroupingParam(
2724 IAudioSessionControl2 *iface, const GUID *group, const GUID *session)
2726 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2728 FIXME("(%p)->(%s, %s) - stub\n", This, debugstr_guid(group),
2729 debugstr_guid(session));
2731 return E_NOTIMPL;
2734 static HRESULT WINAPI AudioSessionControl_RegisterAudioSessionNotification(
2735 IAudioSessionControl2 *iface, IAudioSessionEvents *events)
2737 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2739 FIXME("(%p)->(%p) - stub\n", This, events);
2741 return S_OK;
2744 static HRESULT WINAPI AudioSessionControl_UnregisterAudioSessionNotification(
2745 IAudioSessionControl2 *iface, IAudioSessionEvents *events)
2747 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2749 FIXME("(%p)->(%p) - stub\n", This, events);
2751 return S_OK;
2754 static HRESULT WINAPI AudioSessionControl_GetSessionIdentifier(
2755 IAudioSessionControl2 *iface, WCHAR **id)
2757 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2759 FIXME("(%p)->(%p) - stub\n", This, id);
2761 return E_NOTIMPL;
2764 static HRESULT WINAPI AudioSessionControl_GetSessionInstanceIdentifier(
2765 IAudioSessionControl2 *iface, WCHAR **id)
2767 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2769 FIXME("(%p)->(%p) - stub\n", This, id);
2771 return E_NOTIMPL;
2774 static HRESULT WINAPI AudioSessionControl_GetProcessId(
2775 IAudioSessionControl2 *iface, DWORD *pid)
2777 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2779 TRACE("(%p)->(%p)\n", This, pid);
2781 if(!pid)
2782 return E_POINTER;
2784 *pid = GetCurrentProcessId();
2786 return S_OK;
2789 static HRESULT WINAPI AudioSessionControl_IsSystemSoundsSession(
2790 IAudioSessionControl2 *iface)
2792 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2794 TRACE("(%p)\n", This);
2796 return S_FALSE;
2799 static HRESULT WINAPI AudioSessionControl_SetDuckingPreference(
2800 IAudioSessionControl2 *iface, BOOL optout)
2802 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2804 TRACE("(%p)->(%d)\n", This, optout);
2806 return S_OK;
2809 static const IAudioSessionControl2Vtbl AudioSessionControl2_Vtbl =
2811 AudioSessionControl_QueryInterface,
2812 AudioSessionControl_AddRef,
2813 AudioSessionControl_Release,
2814 AudioSessionControl_GetState,
2815 AudioSessionControl_GetDisplayName,
2816 AudioSessionControl_SetDisplayName,
2817 AudioSessionControl_GetIconPath,
2818 AudioSessionControl_SetIconPath,
2819 AudioSessionControl_GetGroupingParam,
2820 AudioSessionControl_SetGroupingParam,
2821 AudioSessionControl_RegisterAudioSessionNotification,
2822 AudioSessionControl_UnregisterAudioSessionNotification,
2823 AudioSessionControl_GetSessionIdentifier,
2824 AudioSessionControl_GetSessionInstanceIdentifier,
2825 AudioSessionControl_GetProcessId,
2826 AudioSessionControl_IsSystemSoundsSession,
2827 AudioSessionControl_SetDuckingPreference
2830 /* index == -1 means set all channels, otherwise sets only the given channel */
2831 static HRESULT ca_setvol(ACImpl *This, UINT32 index)
2833 Float32 level;
2834 OSStatus sc;
2836 if(This->session->mute)
2837 level = 0.;
2838 else{
2839 if(index == (UINT32)-1){
2840 UINT32 i;
2841 level = 1.;
2842 for(i = 0; i < This->fmt->nChannels; ++i){
2843 Float32 tmp;
2844 tmp = This->session->master_vol *
2845 This->session->channel_vols[i] * This->vols[i];
2846 level = tmp < level ? tmp : level;
2848 }else
2849 level = This->session->master_vol *
2850 This->session->channel_vols[index] * This->vols[index];
2853 sc = AudioUnitSetParameter(This->unit, kHALOutputParam_Volume,
2854 kAudioUnitScope_Global, 0, level, 0);
2855 if(sc != noErr)
2856 WARN("Couldn't set volume: %x\n", (int)sc);
2858 return S_OK;
2861 static HRESULT ca_session_setvol(AudioSession *session, UINT32 index)
2863 HRESULT ret = S_OK;
2864 ACImpl *client;
2866 LIST_FOR_EACH_ENTRY(client, &session->clients, ACImpl, entry){
2867 HRESULT hr;
2868 hr = ca_setvol(client, index);
2869 if(FAILED(hr))
2870 ret = hr;
2873 return ret;
2876 static HRESULT WINAPI SimpleAudioVolume_QueryInterface(
2877 ISimpleAudioVolume *iface, REFIID riid, void **ppv)
2879 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
2881 if(!ppv)
2882 return E_POINTER;
2883 *ppv = NULL;
2885 if(IsEqualIID(riid, &IID_IUnknown) ||
2886 IsEqualIID(riid, &IID_ISimpleAudioVolume))
2887 *ppv = iface;
2888 if(*ppv){
2889 IUnknown_AddRef((IUnknown*)*ppv);
2890 return S_OK;
2893 WARN("Unknown interface %s\n", debugstr_guid(riid));
2894 return E_NOINTERFACE;
2897 static ULONG WINAPI SimpleAudioVolume_AddRef(ISimpleAudioVolume *iface)
2899 AudioSessionWrapper *This = impl_from_ISimpleAudioVolume(iface);
2900 return AudioSessionControl_AddRef(&This->IAudioSessionControl2_iface);
2903 static ULONG WINAPI SimpleAudioVolume_Release(ISimpleAudioVolume *iface)
2905 AudioSessionWrapper *This = impl_from_ISimpleAudioVolume(iface);
2906 return AudioSessionControl_Release(&This->IAudioSessionControl2_iface);
2909 static HRESULT WINAPI SimpleAudioVolume_SetMasterVolume(
2910 ISimpleAudioVolume *iface, float level, const GUID *context)
2912 AudioSessionWrapper *This = impl_from_ISimpleAudioVolume(iface);
2913 AudioSession *session = This->session;
2914 HRESULT ret;
2916 TRACE("(%p)->(%f, %s)\n", session, level, wine_dbgstr_guid(context));
2918 if(level < 0.f || level > 1.f)
2919 return E_INVALIDARG;
2921 if(context)
2922 FIXME("Notifications not supported yet\n");
2924 EnterCriticalSection(&session->lock);
2926 session->master_vol = level;
2928 ret = ca_session_setvol(session, -1);
2930 LeaveCriticalSection(&session->lock);
2932 return ret;
2935 static HRESULT WINAPI SimpleAudioVolume_GetMasterVolume(
2936 ISimpleAudioVolume *iface, float *level)
2938 AudioSessionWrapper *This = impl_from_ISimpleAudioVolume(iface);
2939 AudioSession *session = This->session;
2941 TRACE("(%p)->(%p)\n", session, level);
2943 if(!level)
2944 return NULL_PTR_ERR;
2946 *level = session->master_vol;
2948 return S_OK;
2951 static HRESULT WINAPI SimpleAudioVolume_SetMute(ISimpleAudioVolume *iface,
2952 BOOL mute, const GUID *context)
2954 AudioSessionWrapper *This = impl_from_ISimpleAudioVolume(iface);
2955 AudioSession *session = This->session;
2957 TRACE("(%p)->(%u, %s)\n", session, mute, debugstr_guid(context));
2959 if(context)
2960 FIXME("Notifications not supported yet\n");
2962 EnterCriticalSection(&session->lock);
2964 session->mute = mute;
2966 ca_session_setvol(session, -1);
2968 LeaveCriticalSection(&session->lock);
2970 return S_OK;
2973 static HRESULT WINAPI SimpleAudioVolume_GetMute(ISimpleAudioVolume *iface,
2974 BOOL *mute)
2976 AudioSessionWrapper *This = impl_from_ISimpleAudioVolume(iface);
2977 AudioSession *session = This->session;
2979 TRACE("(%p)->(%p)\n", session, mute);
2981 if(!mute)
2982 return NULL_PTR_ERR;
2984 *mute = session->mute;
2986 return S_OK;
2989 static const ISimpleAudioVolumeVtbl SimpleAudioVolume_Vtbl =
2991 SimpleAudioVolume_QueryInterface,
2992 SimpleAudioVolume_AddRef,
2993 SimpleAudioVolume_Release,
2994 SimpleAudioVolume_SetMasterVolume,
2995 SimpleAudioVolume_GetMasterVolume,
2996 SimpleAudioVolume_SetMute,
2997 SimpleAudioVolume_GetMute
3000 static HRESULT WINAPI AudioStreamVolume_QueryInterface(
3001 IAudioStreamVolume *iface, REFIID riid, void **ppv)
3003 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
3005 if(!ppv)
3006 return E_POINTER;
3007 *ppv = NULL;
3009 if(IsEqualIID(riid, &IID_IUnknown) ||
3010 IsEqualIID(riid, &IID_IAudioStreamVolume))
3011 *ppv = iface;
3012 if(*ppv){
3013 IUnknown_AddRef((IUnknown*)*ppv);
3014 return S_OK;
3017 WARN("Unknown interface %s\n", debugstr_guid(riid));
3018 return E_NOINTERFACE;
3021 static ULONG WINAPI AudioStreamVolume_AddRef(IAudioStreamVolume *iface)
3023 ACImpl *This = impl_from_IAudioStreamVolume(iface);
3024 return IAudioClient_AddRef(&This->IAudioClient_iface);
3027 static ULONG WINAPI AudioStreamVolume_Release(IAudioStreamVolume *iface)
3029 ACImpl *This = impl_from_IAudioStreamVolume(iface);
3030 return IAudioClient_Release(&This->IAudioClient_iface);
3033 static HRESULT WINAPI AudioStreamVolume_GetChannelCount(
3034 IAudioStreamVolume *iface, UINT32 *out)
3036 ACImpl *This = impl_from_IAudioStreamVolume(iface);
3038 TRACE("(%p)->(%p)\n", This, out);
3040 if(!out)
3041 return E_POINTER;
3043 *out = This->fmt->nChannels;
3045 return S_OK;
3048 static HRESULT WINAPI AudioStreamVolume_SetChannelVolume(
3049 IAudioStreamVolume *iface, UINT32 index, float level)
3051 ACImpl *This = impl_from_IAudioStreamVolume(iface);
3052 HRESULT ret;
3054 TRACE("(%p)->(%d, %f)\n", This, index, level);
3056 if(level < 0.f || level > 1.f)
3057 return E_INVALIDARG;
3059 if(index >= This->fmt->nChannels)
3060 return E_INVALIDARG;
3062 OSSpinLockLock(&This->lock);
3064 This->vols[index] = level;
3066 WARN("CoreAudio doesn't support per-channel volume control\n");
3067 ret = ca_setvol(This, index);
3069 OSSpinLockUnlock(&This->lock);
3071 return ret;
3074 static HRESULT WINAPI AudioStreamVolume_GetChannelVolume(
3075 IAudioStreamVolume *iface, UINT32 index, float *level)
3077 ACImpl *This = impl_from_IAudioStreamVolume(iface);
3079 TRACE("(%p)->(%d, %p)\n", This, index, level);
3081 if(!level)
3082 return E_POINTER;
3084 if(index >= This->fmt->nChannels)
3085 return E_INVALIDARG;
3087 *level = This->vols[index];
3089 return S_OK;
3092 static HRESULT WINAPI AudioStreamVolume_SetAllVolumes(
3093 IAudioStreamVolume *iface, UINT32 count, const float *levels)
3095 ACImpl *This = impl_from_IAudioStreamVolume(iface);
3096 int i;
3097 HRESULT ret;
3099 TRACE("(%p)->(%d, %p)\n", This, count, levels);
3101 if(!levels)
3102 return E_POINTER;
3104 if(count != This->fmt->nChannels)
3105 return E_INVALIDARG;
3107 OSSpinLockLock(&This->lock);
3109 for(i = 0; i < count; ++i)
3110 This->vols[i] = levels[i];
3112 ret = ca_setvol(This, -1);
3114 OSSpinLockUnlock(&This->lock);
3116 return ret;
3119 static HRESULT WINAPI AudioStreamVolume_GetAllVolumes(
3120 IAudioStreamVolume *iface, UINT32 count, float *levels)
3122 ACImpl *This = impl_from_IAudioStreamVolume(iface);
3123 int i;
3125 TRACE("(%p)->(%d, %p)\n", This, count, levels);
3127 if(!levels)
3128 return E_POINTER;
3130 if(count != This->fmt->nChannels)
3131 return E_INVALIDARG;
3133 OSSpinLockLock(&This->lock);
3135 for(i = 0; i < count; ++i)
3136 levels[i] = This->vols[i];
3138 OSSpinLockUnlock(&This->lock);
3140 return S_OK;
3143 static const IAudioStreamVolumeVtbl AudioStreamVolume_Vtbl =
3145 AudioStreamVolume_QueryInterface,
3146 AudioStreamVolume_AddRef,
3147 AudioStreamVolume_Release,
3148 AudioStreamVolume_GetChannelCount,
3149 AudioStreamVolume_SetChannelVolume,
3150 AudioStreamVolume_GetChannelVolume,
3151 AudioStreamVolume_SetAllVolumes,
3152 AudioStreamVolume_GetAllVolumes
3155 static HRESULT WINAPI ChannelAudioVolume_QueryInterface(
3156 IChannelAudioVolume *iface, REFIID riid, void **ppv)
3158 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
3160 if(!ppv)
3161 return E_POINTER;
3162 *ppv = NULL;
3164 if(IsEqualIID(riid, &IID_IUnknown) ||
3165 IsEqualIID(riid, &IID_IChannelAudioVolume))
3166 *ppv = iface;
3167 if(*ppv){
3168 IUnknown_AddRef((IUnknown*)*ppv);
3169 return S_OK;
3172 WARN("Unknown interface %s\n", debugstr_guid(riid));
3173 return E_NOINTERFACE;
3176 static ULONG WINAPI ChannelAudioVolume_AddRef(IChannelAudioVolume *iface)
3178 AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
3179 return AudioSessionControl_AddRef(&This->IAudioSessionControl2_iface);
3182 static ULONG WINAPI ChannelAudioVolume_Release(IChannelAudioVolume *iface)
3184 AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
3185 return AudioSessionControl_Release(&This->IAudioSessionControl2_iface);
3188 static HRESULT WINAPI ChannelAudioVolume_GetChannelCount(
3189 IChannelAudioVolume *iface, UINT32 *out)
3191 AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
3192 AudioSession *session = This->session;
3194 TRACE("(%p)->(%p)\n", session, out);
3196 if(!out)
3197 return NULL_PTR_ERR;
3199 *out = session->channel_count;
3201 return S_OK;
3204 static HRESULT WINAPI ChannelAudioVolume_SetChannelVolume(
3205 IChannelAudioVolume *iface, UINT32 index, float level,
3206 const GUID *context)
3208 AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
3209 AudioSession *session = This->session;
3210 HRESULT ret;
3212 TRACE("(%p)->(%d, %f, %s)\n", session, index, level,
3213 wine_dbgstr_guid(context));
3215 if(level < 0.f || level > 1.f)
3216 return E_INVALIDARG;
3218 if(index >= session->channel_count)
3219 return E_INVALIDARG;
3221 if(context)
3222 FIXME("Notifications not supported yet\n");
3224 EnterCriticalSection(&session->lock);
3226 session->channel_vols[index] = level;
3228 WARN("CoreAudio doesn't support per-channel volume control\n");
3229 ret = ca_session_setvol(session, index);
3231 LeaveCriticalSection(&session->lock);
3233 return ret;
3236 static HRESULT WINAPI ChannelAudioVolume_GetChannelVolume(
3237 IChannelAudioVolume *iface, UINT32 index, float *level)
3239 AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
3240 AudioSession *session = This->session;
3242 TRACE("(%p)->(%d, %p)\n", session, index, level);
3244 if(!level)
3245 return NULL_PTR_ERR;
3247 if(index >= session->channel_count)
3248 return E_INVALIDARG;
3250 *level = session->channel_vols[index];
3252 return S_OK;
3255 static HRESULT WINAPI ChannelAudioVolume_SetAllVolumes(
3256 IChannelAudioVolume *iface, UINT32 count, const float *levels,
3257 const GUID *context)
3259 AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
3260 AudioSession *session = This->session;
3261 int i;
3262 HRESULT ret;
3264 TRACE("(%p)->(%d, %p, %s)\n", session, count, levels,
3265 wine_dbgstr_guid(context));
3267 if(!levels)
3268 return NULL_PTR_ERR;
3270 if(count != session->channel_count)
3271 return E_INVALIDARG;
3273 if(context)
3274 FIXME("Notifications not supported yet\n");
3276 EnterCriticalSection(&session->lock);
3278 for(i = 0; i < count; ++i)
3279 session->channel_vols[i] = levels[i];
3281 ret = ca_session_setvol(session, -1);
3283 LeaveCriticalSection(&session->lock);
3285 return ret;
3288 static HRESULT WINAPI ChannelAudioVolume_GetAllVolumes(
3289 IChannelAudioVolume *iface, UINT32 count, float *levels)
3291 AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
3292 AudioSession *session = This->session;
3293 int i;
3295 TRACE("(%p)->(%d, %p)\n", session, count, levels);
3297 if(!levels)
3298 return NULL_PTR_ERR;
3300 if(count != session->channel_count)
3301 return E_INVALIDARG;
3303 for(i = 0; i < count; ++i)
3304 levels[i] = session->channel_vols[i];
3306 return S_OK;
3309 static const IChannelAudioVolumeVtbl ChannelAudioVolume_Vtbl =
3311 ChannelAudioVolume_QueryInterface,
3312 ChannelAudioVolume_AddRef,
3313 ChannelAudioVolume_Release,
3314 ChannelAudioVolume_GetChannelCount,
3315 ChannelAudioVolume_SetChannelVolume,
3316 ChannelAudioVolume_GetChannelVolume,
3317 ChannelAudioVolume_SetAllVolumes,
3318 ChannelAudioVolume_GetAllVolumes
3321 static HRESULT WINAPI AudioSessionManager_QueryInterface(IAudioSessionManager2 *iface,
3322 REFIID riid, void **ppv)
3324 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
3326 if(!ppv)
3327 return E_POINTER;
3328 *ppv = NULL;
3330 if(IsEqualIID(riid, &IID_IUnknown) ||
3331 IsEqualIID(riid, &IID_IAudioSessionManager) ||
3332 IsEqualIID(riid, &IID_IAudioSessionManager2))
3333 *ppv = iface;
3334 if(*ppv){
3335 IUnknown_AddRef((IUnknown*)*ppv);
3336 return S_OK;
3339 WARN("Unknown interface %s\n", debugstr_guid(riid));
3340 return E_NOINTERFACE;
3343 static ULONG WINAPI AudioSessionManager_AddRef(IAudioSessionManager2 *iface)
3345 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
3346 ULONG ref;
3347 ref = InterlockedIncrement(&This->ref);
3348 TRACE("(%p) Refcount now %u\n", This, ref);
3349 return ref;
3352 static ULONG WINAPI AudioSessionManager_Release(IAudioSessionManager2 *iface)
3354 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
3355 ULONG ref;
3356 ref = InterlockedDecrement(&This->ref);
3357 TRACE("(%p) Refcount now %u\n", This, ref);
3358 if(!ref)
3359 HeapFree(GetProcessHeap(), 0, This);
3360 return ref;
3363 static HRESULT WINAPI AudioSessionManager_GetAudioSessionControl(
3364 IAudioSessionManager2 *iface, const GUID *session_guid, DWORD flags,
3365 IAudioSessionControl **out)
3367 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
3368 AudioSession *session;
3369 AudioSessionWrapper *wrapper;
3370 HRESULT hr;
3372 TRACE("(%p)->(%s, %x, %p)\n", This, debugstr_guid(session_guid),
3373 flags, out);
3375 hr = get_audio_session(session_guid, This->device, 0, &session);
3376 if(FAILED(hr))
3377 return hr;
3379 wrapper = AudioSessionWrapper_Create(NULL);
3380 if(!wrapper)
3381 return E_OUTOFMEMORY;
3383 wrapper->session = session;
3385 *out = (IAudioSessionControl*)&wrapper->IAudioSessionControl2_iface;
3387 return S_OK;
3390 static HRESULT WINAPI AudioSessionManager_GetSimpleAudioVolume(
3391 IAudioSessionManager2 *iface, const GUID *session_guid, DWORD flags,
3392 ISimpleAudioVolume **out)
3394 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
3395 AudioSession *session;
3396 AudioSessionWrapper *wrapper;
3397 HRESULT hr;
3399 TRACE("(%p)->(%s, %x, %p)\n", This, debugstr_guid(session_guid),
3400 flags, out);
3402 hr = get_audio_session(session_guid, This->device, 0, &session);
3403 if(FAILED(hr))
3404 return hr;
3406 wrapper = AudioSessionWrapper_Create(NULL);
3407 if(!wrapper)
3408 return E_OUTOFMEMORY;
3410 wrapper->session = session;
3412 *out = &wrapper->ISimpleAudioVolume_iface;
3414 return S_OK;
3417 static HRESULT WINAPI AudioSessionManager_GetSessionEnumerator(
3418 IAudioSessionManager2 *iface, IAudioSessionEnumerator **out)
3420 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
3421 FIXME("(%p)->(%p) - stub\n", This, out);
3422 return E_NOTIMPL;
3425 static HRESULT WINAPI AudioSessionManager_RegisterSessionNotification(
3426 IAudioSessionManager2 *iface, IAudioSessionNotification *notification)
3428 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
3429 FIXME("(%p)->(%p) - stub\n", This, notification);
3430 return E_NOTIMPL;
3433 static HRESULT WINAPI AudioSessionManager_UnregisterSessionNotification(
3434 IAudioSessionManager2 *iface, IAudioSessionNotification *notification)
3436 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
3437 FIXME("(%p)->(%p) - stub\n", This, notification);
3438 return E_NOTIMPL;
3441 static HRESULT WINAPI AudioSessionManager_RegisterDuckNotification(
3442 IAudioSessionManager2 *iface, const WCHAR *session_id,
3443 IAudioVolumeDuckNotification *notification)
3445 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
3446 FIXME("(%p)->(%p) - stub\n", This, notification);
3447 return E_NOTIMPL;
3450 static HRESULT WINAPI AudioSessionManager_UnregisterDuckNotification(
3451 IAudioSessionManager2 *iface,
3452 IAudioVolumeDuckNotification *notification)
3454 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
3455 FIXME("(%p)->(%p) - stub\n", This, notification);
3456 return E_NOTIMPL;
3459 static const IAudioSessionManager2Vtbl AudioSessionManager2_Vtbl =
3461 AudioSessionManager_QueryInterface,
3462 AudioSessionManager_AddRef,
3463 AudioSessionManager_Release,
3464 AudioSessionManager_GetAudioSessionControl,
3465 AudioSessionManager_GetSimpleAudioVolume,
3466 AudioSessionManager_GetSessionEnumerator,
3467 AudioSessionManager_RegisterSessionNotification,
3468 AudioSessionManager_UnregisterSessionNotification,
3469 AudioSessionManager_RegisterDuckNotification,
3470 AudioSessionManager_UnregisterDuckNotification
3473 HRESULT WINAPI AUDDRV_GetAudioSessionManager(IMMDevice *device,
3474 IAudioSessionManager2 **out)
3476 SessionMgr *This;
3478 This = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(SessionMgr));
3479 if(!This)
3480 return E_OUTOFMEMORY;
3482 This->IAudioSessionManager2_iface.lpVtbl = &AudioSessionManager2_Vtbl;
3483 This->device = device;
3484 This->ref = 1;
3486 *out = &This->IAudioSessionManager2_iface;
3488 return S_OK;