mmdevapi: Implement SetClientProperties.
[wine.git] / dlls / winecoreaudio.drv / mmdevdrv.c
blobf065d5bc1efa07f853b6944cb96742f6659c3378
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 IAudioClient2 IAudioClient2_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 IAudioClient2Vtbl AudioClient2_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_IAudioClient2(IAudioClient2 *iface)
217 return CONTAINING_RECORD(iface, ACImpl, IAudioClient2_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->IAudioClient2_iface.lpVtbl = &AudioClient2_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->IAudioClient2_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 = (IAudioClient *)&This->IAudioClient2_iface;
714 IAudioClient2_AddRef(&This->IAudioClient2_iface);
716 return S_OK;
719 static HRESULT WINAPI AudioClient_QueryInterface(IAudioClient2 *iface,
720 REFIID riid, void **ppv)
722 ACImpl *This = impl_from_IAudioClient2(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) ||
729 IsEqualIID(riid, &IID_IAudioClient) ||
730 IsEqualIID(riid, &IID_IAudioClient2))
731 *ppv = iface;
732 else if(IsEqualIID(riid, &IID_IMarshal))
733 return IUnknown_QueryInterface(This->pUnkFTMarshal, riid, ppv);
735 if(*ppv){
736 IUnknown_AddRef((IUnknown*)*ppv);
737 return S_OK;
739 WARN("Unknown interface %s\n", debugstr_guid(riid));
740 return E_NOINTERFACE;
743 static ULONG WINAPI AudioClient_AddRef(IAudioClient2 *iface)
745 ACImpl *This = impl_from_IAudioClient2(iface);
746 ULONG ref;
747 ref = InterlockedIncrement(&This->ref);
748 TRACE("(%p) Refcount now %u\n", This, ref);
749 return ref;
752 static ULONG WINAPI AudioClient_Release(IAudioClient2 *iface)
754 ACImpl *This = impl_from_IAudioClient2(iface);
755 ULONG ref;
756 ref = InterlockedDecrement(&This->ref);
757 TRACE("(%p) Refcount now %u\n", This, ref);
758 if(!ref){
759 if(This->timer){
760 HANDLE event;
761 BOOL wait;
762 event = CreateEventW(NULL, TRUE, FALSE, NULL);
763 wait = !DeleteTimerQueueTimer(g_timer_q, This->timer, event);
764 wait = wait && GetLastError() == ERROR_IO_PENDING;
765 if(event && wait)
766 WaitForSingleObject(event, INFINITE);
767 CloseHandle(event);
769 AudioOutputUnitStop(This->unit);
770 AudioComponentInstanceDispose(This->unit);
771 if(This->converter)
772 AudioConverterDispose(This->converter);
773 if(This->session){
774 EnterCriticalSection(&g_sessions_lock);
775 list_remove(&This->entry);
776 LeaveCriticalSection(&g_sessions_lock);
778 HeapFree(GetProcessHeap(), 0, This->vols);
779 HeapFree(GetProcessHeap(), 0, This->tmp_buffer);
780 HeapFree(GetProcessHeap(), 0, This->cap_buffer);
781 HeapFree(GetProcessHeap(), 0, This->local_buffer);
782 free(This->wrap_buffer);
783 HeapFree(GetProcessHeap(), 0, This->resamp_buffer);
784 CoTaskMemFree(This->fmt);
785 IMMDevice_Release(This->parent);
786 IUnknown_Release(This->pUnkFTMarshal);
787 HeapFree(GetProcessHeap(), 0, This);
789 return ref;
792 static void dump_fmt(const WAVEFORMATEX *fmt)
794 TRACE("wFormatTag: 0x%x (", fmt->wFormatTag);
795 switch(fmt->wFormatTag){
796 case WAVE_FORMAT_PCM:
797 TRACE("WAVE_FORMAT_PCM");
798 break;
799 case WAVE_FORMAT_IEEE_FLOAT:
800 TRACE("WAVE_FORMAT_IEEE_FLOAT");
801 break;
802 case WAVE_FORMAT_EXTENSIBLE:
803 TRACE("WAVE_FORMAT_EXTENSIBLE");
804 break;
805 default:
806 TRACE("Unknown");
807 break;
809 TRACE(")\n");
811 TRACE("nChannels: %u\n", fmt->nChannels);
812 TRACE("nSamplesPerSec: %u\n", fmt->nSamplesPerSec);
813 TRACE("nAvgBytesPerSec: %u\n", fmt->nAvgBytesPerSec);
814 TRACE("nBlockAlign: %u\n", fmt->nBlockAlign);
815 TRACE("wBitsPerSample: %u\n", fmt->wBitsPerSample);
816 TRACE("cbSize: %u\n", fmt->cbSize);
818 if(fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE){
819 WAVEFORMATEXTENSIBLE *fmtex = (void*)fmt;
820 TRACE("dwChannelMask: %08x\n", fmtex->dwChannelMask);
821 TRACE("Samples: %04x\n", fmtex->Samples.wReserved);
822 TRACE("SubFormat: %s\n", wine_dbgstr_guid(&fmtex->SubFormat));
826 static DWORD get_channel_mask(unsigned int channels)
828 switch(channels){
829 case 0:
830 return 0;
831 case 1:
832 return KSAUDIO_SPEAKER_MONO;
833 case 2:
834 return KSAUDIO_SPEAKER_STEREO;
835 case 3:
836 return KSAUDIO_SPEAKER_STEREO | SPEAKER_LOW_FREQUENCY;
837 case 4:
838 return KSAUDIO_SPEAKER_QUAD; /* not _SURROUND */
839 case 5:
840 return KSAUDIO_SPEAKER_QUAD | SPEAKER_LOW_FREQUENCY;
841 case 6:
842 return KSAUDIO_SPEAKER_5POINT1; /* not 5POINT1_SURROUND */
843 case 7:
844 return KSAUDIO_SPEAKER_5POINT1 | SPEAKER_BACK_CENTER;
845 case 8:
846 return KSAUDIO_SPEAKER_7POINT1_SURROUND; /* Vista deprecates 7POINT1 */
848 FIXME("Unknown speaker configuration: %u\n", channels);
849 return 0;
852 static WAVEFORMATEX *clone_format(const WAVEFORMATEX *fmt)
854 WAVEFORMATEX *ret;
855 size_t size;
857 if(fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE)
858 size = sizeof(WAVEFORMATEXTENSIBLE);
859 else
860 size = sizeof(WAVEFORMATEX);
862 ret = CoTaskMemAlloc(size);
863 if(!ret)
864 return NULL;
866 memcpy(ret, fmt, size);
868 ret->cbSize = size - sizeof(WAVEFORMATEX);
870 return ret;
873 static HRESULT ca_get_audiodesc(AudioStreamBasicDescription *desc,
874 const WAVEFORMATEX *fmt)
876 const WAVEFORMATEXTENSIBLE *fmtex = (const WAVEFORMATEXTENSIBLE *)fmt;
878 desc->mFormatFlags = 0;
880 if(fmt->wFormatTag == WAVE_FORMAT_PCM ||
881 (fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
882 IsEqualGUID(&fmtex->SubFormat, &KSDATAFORMAT_SUBTYPE_PCM))){
883 desc->mFormatID = kAudioFormatLinearPCM;
884 if(fmt->wBitsPerSample > 8)
885 desc->mFormatFlags = kAudioFormatFlagIsSignedInteger;
886 }else if(fmt->wFormatTag == WAVE_FORMAT_IEEE_FLOAT ||
887 (fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
888 IsEqualGUID(&fmtex->SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))){
889 desc->mFormatID = kAudioFormatLinearPCM;
890 desc->mFormatFlags = kAudioFormatFlagIsFloat;
891 }else if(fmt->wFormatTag == WAVE_FORMAT_MULAW ||
892 (fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
893 IsEqualGUID(&fmtex->SubFormat, &KSDATAFORMAT_SUBTYPE_MULAW))){
894 desc->mFormatID = kAudioFormatULaw;
895 }else if(fmt->wFormatTag == WAVE_FORMAT_ALAW ||
896 (fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
897 IsEqualGUID(&fmtex->SubFormat, &KSDATAFORMAT_SUBTYPE_ALAW))){
898 desc->mFormatID = kAudioFormatALaw;
899 }else
900 return AUDCLNT_E_UNSUPPORTED_FORMAT;
902 desc->mSampleRate = fmt->nSamplesPerSec;
903 desc->mBytesPerPacket = fmt->nBlockAlign;
904 desc->mFramesPerPacket = 1;
905 desc->mBytesPerFrame = fmt->nBlockAlign;
906 desc->mChannelsPerFrame = fmt->nChannels;
907 desc->mBitsPerChannel = fmt->wBitsPerSample;
908 desc->mReserved = 0;
910 return S_OK;
913 static void session_init_vols(AudioSession *session, UINT channels)
915 if(session->channel_count < channels){
916 UINT i;
918 if(session->channel_vols)
919 session->channel_vols = HeapReAlloc(GetProcessHeap(), 0,
920 session->channel_vols, sizeof(float) * channels);
921 else
922 session->channel_vols = HeapAlloc(GetProcessHeap(), 0,
923 sizeof(float) * channels);
924 if(!session->channel_vols)
925 return;
927 for(i = session->channel_count; i < channels; ++i)
928 session->channel_vols[i] = 1.f;
930 session->channel_count = channels;
934 static AudioSession *create_session(const GUID *guid, IMMDevice *device,
935 UINT num_channels)
937 AudioSession *ret;
939 ret = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(AudioSession));
940 if(!ret)
941 return NULL;
943 memcpy(&ret->guid, guid, sizeof(GUID));
945 ret->device = device;
947 list_init(&ret->clients);
949 list_add_head(&g_sessions, &ret->entry);
951 InitializeCriticalSection(&ret->lock);
952 ret->lock.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": AudioSession.lock");
954 session_init_vols(ret, num_channels);
956 ret->master_vol = 1.f;
958 return ret;
961 /* if channels == 0, then this will return or create a session with
962 * matching dataflow and GUID. otherwise, channels must also match */
963 static HRESULT get_audio_session(const GUID *sessionguid,
964 IMMDevice *device, UINT channels, AudioSession **out)
966 AudioSession *session;
968 if(!sessionguid || IsEqualGUID(sessionguid, &GUID_NULL)){
969 *out = create_session(&GUID_NULL, device, channels);
970 if(!*out)
971 return E_OUTOFMEMORY;
973 return S_OK;
976 *out = NULL;
977 LIST_FOR_EACH_ENTRY(session, &g_sessions, AudioSession, entry){
978 if(session->device == device &&
979 IsEqualGUID(sessionguid, &session->guid)){
980 session_init_vols(session, channels);
981 *out = session;
982 break;
986 if(!*out){
987 *out = create_session(sessionguid, device, channels);
988 if(!*out)
989 return E_OUTOFMEMORY;
992 return S_OK;
995 static void ca_wrap_buffer(BYTE *dst, UINT32 dst_offs, UINT32 dst_bytes,
996 BYTE *src, UINT32 src_bytes)
998 UINT32 chunk_bytes = dst_bytes - dst_offs;
1000 if(chunk_bytes < src_bytes){
1001 memcpy(dst + dst_offs, src, chunk_bytes);
1002 memcpy(dst, src + chunk_bytes, src_bytes - chunk_bytes);
1003 }else
1004 memcpy(dst + dst_offs, src, src_bytes);
1007 static void silence_buffer(ACImpl *This, BYTE *buffer, UINT32 frames)
1009 WAVEFORMATEXTENSIBLE *fmtex = (WAVEFORMATEXTENSIBLE*)This->fmt;
1010 if((This->fmt->wFormatTag == WAVE_FORMAT_PCM ||
1011 (This->fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
1012 IsEqualGUID(&fmtex->SubFormat, &KSDATAFORMAT_SUBTYPE_PCM))) &&
1013 This->fmt->wBitsPerSample == 8)
1014 memset(buffer, 128, frames * This->fmt->nBlockAlign);
1015 else
1016 memset(buffer, 0, frames * This->fmt->nBlockAlign);
1019 /* CA is pulling data from us */
1020 static OSStatus ca_render_cb(void *user, AudioUnitRenderActionFlags *flags,
1021 const AudioTimeStamp *ts, UInt32 bus, UInt32 nframes,
1022 AudioBufferList *data)
1024 ACImpl *This = user;
1025 UINT32 to_copy_bytes, to_copy_frames, chunk_bytes, lcl_offs_bytes;
1027 OSSpinLockLock(&This->lock);
1029 if(This->playing){
1030 lcl_offs_bytes = This->lcl_offs_frames * This->fmt->nBlockAlign;
1031 to_copy_frames = min(nframes, This->held_frames);
1032 to_copy_bytes = to_copy_frames * This->fmt->nBlockAlign;
1034 chunk_bytes = (This->bufsize_frames - This->lcl_offs_frames) * This->fmt->nBlockAlign;
1036 if(to_copy_bytes > chunk_bytes){
1037 memcpy(data->mBuffers[0].mData, This->local_buffer + lcl_offs_bytes, chunk_bytes);
1038 memcpy(((BYTE *)data->mBuffers[0].mData) + chunk_bytes, This->local_buffer, to_copy_bytes - chunk_bytes);
1039 }else
1040 memcpy(data->mBuffers[0].mData, This->local_buffer + lcl_offs_bytes, to_copy_bytes);
1042 This->lcl_offs_frames += to_copy_frames;
1043 This->lcl_offs_frames %= This->bufsize_frames;
1044 This->held_frames -= to_copy_frames;
1045 }else
1046 to_copy_bytes = to_copy_frames = 0;
1048 if(nframes > to_copy_frames)
1049 silence_buffer(This, ((BYTE *)data->mBuffers[0].mData) + to_copy_bytes, nframes - to_copy_frames);
1051 OSSpinLockUnlock(&This->lock);
1053 return noErr;
1056 static UINT buf_ptr_diff(UINT left, UINT right, UINT bufsize)
1058 if(left <= right)
1059 return right - left;
1060 return bufsize - (left - right);
1063 /* place data from cap_buffer into provided AudioBufferList */
1064 static OSStatus feed_cb(AudioConverterRef converter, UInt32 *nframes, AudioBufferList *data,
1065 AudioStreamPacketDescription **packets, void *user)
1067 ACImpl *This = user;
1069 *nframes = min(*nframes, This->cap_held_frames);
1070 if(!*nframes){
1071 data->mBuffers[0].mData = NULL;
1072 data->mBuffers[0].mDataByteSize = 0;
1073 data->mBuffers[0].mNumberChannels = This->fmt->nChannels;
1074 return noErr;
1077 data->mBuffers[0].mDataByteSize = *nframes * This->fmt->nBlockAlign;
1078 data->mBuffers[0].mNumberChannels = This->fmt->nChannels;
1080 if(This->cap_offs_frames + *nframes > This->cap_bufsize_frames){
1081 UINT32 chunk_frames = This->cap_bufsize_frames - This->cap_offs_frames;
1083 if(This->wrap_bufsize_frames < *nframes){
1084 free(This->wrap_buffer);
1085 This->wrap_buffer = malloc(data->mBuffers[0].mDataByteSize);
1086 This->wrap_bufsize_frames = *nframes;
1089 memcpy(This->wrap_buffer, This->cap_buffer + This->cap_offs_frames * This->fmt->nBlockAlign,
1090 chunk_frames * This->fmt->nBlockAlign);
1091 memcpy(This->wrap_buffer + chunk_frames * This->fmt->nBlockAlign, This->cap_buffer,
1092 (*nframes - chunk_frames) * This->fmt->nBlockAlign);
1094 data->mBuffers[0].mData = This->wrap_buffer;
1095 }else
1096 data->mBuffers[0].mData = This->cap_buffer + This->cap_offs_frames * This->fmt->nBlockAlign;
1098 This->cap_offs_frames += *nframes;
1099 This->cap_offs_frames %= This->cap_bufsize_frames;
1100 This->cap_held_frames -= *nframes;
1102 if(packets)
1103 *packets = NULL;
1105 return noErr;
1108 static void capture_resample(ACImpl *This)
1110 UINT32 resamp_period_frames = MulDiv(This->period_frames, This->dev_desc.mSampleRate, This->fmt->nSamplesPerSec);
1111 OSStatus sc;
1113 /* the resampling process often needs more source frames than we'd
1114 * guess from a straight conversion using the sample rate ratio. so
1115 * only convert if we have extra source data. */
1116 while(This->cap_held_frames > resamp_period_frames * 2){
1117 AudioBufferList converted_list;
1118 UInt32 wanted_frames = This->period_frames;
1120 converted_list.mNumberBuffers = 1;
1121 converted_list.mBuffers[0].mNumberChannels = This->fmt->nChannels;
1122 converted_list.mBuffers[0].mDataByteSize = wanted_frames * This->fmt->nBlockAlign;
1124 if(This->resamp_bufsize_frames < wanted_frames){
1125 HeapFree(GetProcessHeap(), 0, This->resamp_buffer);
1126 This->resamp_buffer = HeapAlloc(GetProcessHeap(), 0, converted_list.mBuffers[0].mDataByteSize);
1127 This->resamp_bufsize_frames = wanted_frames;
1130 converted_list.mBuffers[0].mData = This->resamp_buffer;
1132 sc = AudioConverterFillComplexBuffer(This->converter, feed_cb,
1133 This, &wanted_frames, &converted_list, NULL);
1134 if(sc != noErr){
1135 WARN("AudioConverterFillComplexBuffer failed: %x\n", (int)sc);
1136 break;
1139 ca_wrap_buffer(This->local_buffer,
1140 This->wri_offs_frames * This->fmt->nBlockAlign,
1141 This->bufsize_frames * This->fmt->nBlockAlign,
1142 This->resamp_buffer, wanted_frames * This->fmt->nBlockAlign);
1144 This->wri_offs_frames += wanted_frames;
1145 This->wri_offs_frames %= This->bufsize_frames;
1146 if(This->held_frames + wanted_frames > This->bufsize_frames){
1147 This->lcl_offs_frames += buf_ptr_diff(This->lcl_offs_frames,
1148 This->wri_offs_frames, This->bufsize_frames);
1149 This->held_frames = This->bufsize_frames;
1150 }else
1151 This->held_frames += wanted_frames;
1155 /* we need to trigger CA to pull data from the device and give it to us
1157 * raw data from CA is stored in cap_buffer, possibly via wrap_buffer
1159 * raw data is resampled from cap_buffer into resamp_buffer in period-size
1160 * chunks and copied to local_buffer
1162 static OSStatus ca_capture_cb(void *user, AudioUnitRenderActionFlags *flags,
1163 const AudioTimeStamp *ts, UInt32 bus, UInt32 nframes,
1164 AudioBufferList *data)
1166 ACImpl *This = user;
1167 AudioBufferList list;
1168 OSStatus sc;
1169 UINT32 cap_wri_offs_frames;
1171 OSSpinLockLock(&This->lock);
1173 cap_wri_offs_frames = (This->cap_offs_frames + This->cap_held_frames) % This->cap_bufsize_frames;
1175 list.mNumberBuffers = 1;
1176 list.mBuffers[0].mNumberChannels = This->fmt->nChannels;
1177 list.mBuffers[0].mDataByteSize = nframes * This->fmt->nBlockAlign;
1179 if(!This->playing || cap_wri_offs_frames + nframes > This->cap_bufsize_frames){
1180 if(This->wrap_bufsize_frames < nframes){
1181 free(This->wrap_buffer);
1182 This->wrap_buffer = malloc(list.mBuffers[0].mDataByteSize);
1183 This->wrap_bufsize_frames = nframes;
1186 list.mBuffers[0].mData = This->wrap_buffer;
1187 }else
1188 list.mBuffers[0].mData = This->cap_buffer + cap_wri_offs_frames * This->fmt->nBlockAlign;
1190 sc = AudioUnitRender(This->unit, flags, ts, bus, nframes, &list);
1191 if(sc != noErr){
1192 OSSpinLockUnlock(&This->lock);
1193 return sc;
1196 if(This->playing){
1197 if(list.mBuffers[0].mData == This->wrap_buffer){
1198 ca_wrap_buffer(This->cap_buffer,
1199 cap_wri_offs_frames * This->fmt->nBlockAlign,
1200 This->cap_bufsize_frames * This->fmt->nBlockAlign,
1201 This->wrap_buffer, list.mBuffers[0].mDataByteSize);
1204 This->cap_held_frames += list.mBuffers[0].mDataByteSize / This->fmt->nBlockAlign;
1205 if(This->cap_held_frames > This->cap_bufsize_frames){
1206 This->cap_offs_frames += This->cap_held_frames % This->cap_bufsize_frames;
1207 This->cap_offs_frames %= This->cap_bufsize_frames;
1208 This->cap_held_frames = This->cap_bufsize_frames;
1212 OSSpinLockUnlock(&This->lock);
1213 return noErr;
1216 static void dump_adesc(const char *aux, AudioStreamBasicDescription *desc)
1218 TRACE("%s: mSampleRate: %f\n", aux, desc->mSampleRate);
1219 TRACE("%s: mBytesPerPacket: %u\n", aux, (unsigned int)desc->mBytesPerPacket);
1220 TRACE("%s: mFramesPerPacket: %u\n", aux, (unsigned int)desc->mFramesPerPacket);
1221 TRACE("%s: mBytesPerFrame: %u\n", aux, (unsigned int)desc->mBytesPerFrame);
1222 TRACE("%s: mChannelsPerFrame: %u\n", aux, (unsigned int)desc->mChannelsPerFrame);
1223 TRACE("%s: mBitsPerChannel: %u\n", aux, (unsigned int)desc->mBitsPerChannel);
1226 static HRESULT ca_setup_audiounit(EDataFlow dataflow, AudioComponentInstance unit,
1227 const WAVEFORMATEX *fmt, AudioStreamBasicDescription *dev_desc,
1228 AudioConverterRef *converter)
1230 OSStatus sc;
1231 HRESULT hr;
1233 if(dataflow == eCapture){
1234 AudioStreamBasicDescription desc;
1235 UInt32 size;
1236 Float64 rate;
1237 fenv_t fenv;
1238 BOOL fenv_stored = TRUE;
1240 hr = ca_get_audiodesc(&desc, fmt);
1241 if(FAILED(hr))
1242 return hr;
1243 dump_adesc("requested", &desc);
1245 /* input-only units can't perform sample rate conversion, so we have to
1246 * set up our own AudioConverter to support arbitrary sample rates. */
1247 size = sizeof(*dev_desc);
1248 sc = AudioUnitGetProperty(unit, kAudioUnitProperty_StreamFormat,
1249 kAudioUnitScope_Input, 1, dev_desc, &size);
1250 if(sc != noErr){
1251 WARN("Couldn't get unit format: %x\n", (int)sc);
1252 return osstatus_to_hresult(sc);
1254 dump_adesc("hardware", dev_desc);
1256 rate = dev_desc->mSampleRate;
1257 *dev_desc = desc;
1258 dev_desc->mSampleRate = rate;
1260 dump_adesc("final", dev_desc);
1261 sc = AudioUnitSetProperty(unit, kAudioUnitProperty_StreamFormat,
1262 kAudioUnitScope_Output, 1, dev_desc, sizeof(*dev_desc));
1263 if(sc != noErr){
1264 WARN("Couldn't set unit format: %x\n", (int)sc);
1265 return osstatus_to_hresult(sc);
1268 /* AudioConverterNew requires divide-by-zero SSE exceptions to be masked */
1269 if(feholdexcept(&fenv)){
1270 WARN("Failed to store fenv state\n");
1271 fenv_stored = FALSE;
1274 sc = AudioConverterNew(dev_desc, &desc, converter);
1276 if(fenv_stored && fesetenv(&fenv))
1277 WARN("Failed to restore fenv state\n");
1279 if(sc != noErr){
1280 WARN("Couldn't create audio converter: %x\n", (int)sc);
1281 return osstatus_to_hresult(sc);
1283 }else{
1284 hr = ca_get_audiodesc(dev_desc, fmt);
1285 if(FAILED(hr))
1286 return hr;
1288 dump_adesc("final", dev_desc);
1289 sc = AudioUnitSetProperty(unit, kAudioUnitProperty_StreamFormat,
1290 kAudioUnitScope_Input, 0, dev_desc, sizeof(*dev_desc));
1291 if(sc != noErr){
1292 WARN("Couldn't set format: %x\n", (int)sc);
1293 return osstatus_to_hresult(sc);
1297 return S_OK;
1300 static HRESULT WINAPI AudioClient_Initialize(IAudioClient2 *iface,
1301 AUDCLNT_SHAREMODE mode, DWORD flags, REFERENCE_TIME duration,
1302 REFERENCE_TIME period, const WAVEFORMATEX *fmt,
1303 const GUID *sessionguid)
1305 ACImpl *This = impl_from_IAudioClient2(iface);
1306 HRESULT hr;
1307 OSStatus sc;
1308 int i;
1310 TRACE("(%p)->(%x, %x, %s, %s, %p, %s)\n", This, mode, flags,
1311 wine_dbgstr_longlong(duration), wine_dbgstr_longlong(period), fmt, debugstr_guid(sessionguid));
1313 if(!fmt)
1314 return E_POINTER;
1316 dump_fmt(fmt);
1318 if(mode != AUDCLNT_SHAREMODE_SHARED && mode != AUDCLNT_SHAREMODE_EXCLUSIVE)
1319 return E_INVALIDARG;
1321 if(flags & ~(AUDCLNT_STREAMFLAGS_CROSSPROCESS |
1322 AUDCLNT_STREAMFLAGS_LOOPBACK |
1323 AUDCLNT_STREAMFLAGS_EVENTCALLBACK |
1324 AUDCLNT_STREAMFLAGS_NOPERSIST |
1325 AUDCLNT_STREAMFLAGS_RATEADJUST |
1326 AUDCLNT_SESSIONFLAGS_EXPIREWHENUNOWNED |
1327 AUDCLNT_SESSIONFLAGS_DISPLAY_HIDE |
1328 AUDCLNT_SESSIONFLAGS_DISPLAY_HIDEWHENEXPIRED |
1329 AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY |
1330 AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM)){
1331 FIXME("Unknown flags: %08x\n", flags);
1332 return E_INVALIDARG;
1335 if(mode == AUDCLNT_SHAREMODE_SHARED){
1336 period = DefaultPeriod;
1337 if( duration < 3 * period)
1338 duration = 3 * period;
1339 }else{
1340 if(fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE){
1341 if(((WAVEFORMATEXTENSIBLE*)fmt)->dwChannelMask == 0 ||
1342 ((WAVEFORMATEXTENSIBLE*)fmt)->dwChannelMask & SPEAKER_RESERVED)
1343 return AUDCLNT_E_UNSUPPORTED_FORMAT;
1346 if(!period)
1347 period = DefaultPeriod; /* not minimum */
1348 if(period < MinimumPeriod || period > 5000000)
1349 return AUDCLNT_E_INVALID_DEVICE_PERIOD;
1350 if(duration > 20000000) /* the smaller the period, the lower this limit */
1351 return AUDCLNT_E_BUFFER_SIZE_ERROR;
1352 if(flags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK){
1353 if(duration != period)
1354 return AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL;
1355 FIXME("EXCLUSIVE mode with EVENTCALLBACK\n");
1356 return AUDCLNT_E_DEVICE_IN_USE;
1357 }else{
1358 if( duration < 8 * period)
1359 duration = 8 * period; /* may grow above 2s */
1363 OSSpinLockLock(&This->lock);
1365 if(This->initted){
1366 OSSpinLockUnlock(&This->lock);
1367 return AUDCLNT_E_ALREADY_INITIALIZED;
1370 This->fmt = clone_format(fmt);
1371 if(!This->fmt){
1372 OSSpinLockUnlock(&This->lock);
1373 return E_OUTOFMEMORY;
1376 This->period_ms = period / 10000;
1377 This->period_frames = MulDiv(period, This->fmt->nSamplesPerSec, 10000000);
1379 This->bufsize_frames = MulDiv(duration, fmt->nSamplesPerSec, 10000000);
1380 if(mode == AUDCLNT_SHAREMODE_EXCLUSIVE)
1381 This->bufsize_frames -= This->bufsize_frames % This->period_frames;
1383 hr = ca_setup_audiounit(This->dataflow, This->unit, This->fmt, &This->dev_desc, &This->converter);
1384 if(FAILED(hr)){
1385 CoTaskMemFree(This->fmt);
1386 This->fmt = NULL;
1387 OSSpinLockUnlock(&This->lock);
1388 return hr;
1391 if(This->dataflow == eCapture){
1392 AURenderCallbackStruct input;
1394 memset(&input, 0, sizeof(input));
1395 input.inputProc = &ca_capture_cb;
1396 input.inputProcRefCon = This;
1398 sc = AudioUnitSetProperty(This->unit, kAudioOutputUnitProperty_SetInputCallback,
1399 kAudioUnitScope_Output, 1, &input, sizeof(input));
1400 if(sc != noErr){
1401 WARN("Couldn't set callback: %x\n", (int)sc);
1402 AudioConverterDispose(This->converter);
1403 This->converter = NULL;
1404 CoTaskMemFree(This->fmt);
1405 This->fmt = NULL;
1406 OSSpinLockUnlock(&This->lock);
1407 return osstatus_to_hresult(sc);
1409 }else{
1410 AURenderCallbackStruct input;
1412 memset(&input, 0, sizeof(input));
1413 input.inputProc = &ca_render_cb;
1414 input.inputProcRefCon = This;
1416 sc = AudioUnitSetProperty(This->unit, kAudioUnitProperty_SetRenderCallback,
1417 kAudioUnitScope_Input, 0, &input, sizeof(input));
1418 if(sc != noErr){
1419 WARN("Couldn't set callback: %x\n", (int)sc);
1420 CoTaskMemFree(This->fmt);
1421 This->fmt = NULL;
1422 OSSpinLockUnlock(&This->lock);
1423 return osstatus_to_hresult(sc);
1427 sc = AudioUnitInitialize(This->unit);
1428 if(sc != noErr){
1429 WARN("Couldn't initialize: %x\n", (int)sc);
1430 if(This->converter){
1431 AudioConverterDispose(This->converter);
1432 This->converter = NULL;
1434 CoTaskMemFree(This->fmt);
1435 This->fmt = NULL;
1436 OSSpinLockUnlock(&This->lock);
1437 return osstatus_to_hresult(sc);
1440 /* we play audio continuously because AudioOutputUnitStart sometimes takes
1441 * a while to return */
1442 sc = AudioOutputUnitStart(This->unit);
1443 if(sc != noErr){
1444 WARN("Unit failed to start: %x\n", (int)sc);
1445 if(This->converter){
1446 AudioConverterDispose(This->converter);
1447 This->converter = NULL;
1449 CoTaskMemFree(This->fmt);
1450 This->fmt = NULL;
1451 OSSpinLockUnlock(&This->lock);
1452 return osstatus_to_hresult(sc);
1455 This->local_buffer = HeapAlloc(GetProcessHeap(), 0, This->bufsize_frames * fmt->nBlockAlign);
1456 silence_buffer(This, This->local_buffer, This->bufsize_frames);
1458 if(This->dataflow == eCapture){
1459 This->cap_bufsize_frames = MulDiv(duration, This->dev_desc.mSampleRate, 10000000);
1460 This->cap_buffer = HeapAlloc(GetProcessHeap(), 0, This->cap_bufsize_frames * This->fmt->nBlockAlign);
1463 This->vols = HeapAlloc(GetProcessHeap(), 0, fmt->nChannels * sizeof(float));
1464 if(!This->vols){
1465 CoTaskMemFree(This->fmt);
1466 This->fmt = NULL;
1467 OSSpinLockUnlock(&This->lock);
1468 return E_OUTOFMEMORY;
1471 for(i = 0; i < fmt->nChannels; ++i)
1472 This->vols[i] = 1.f;
1474 This->share = mode;
1475 This->flags = flags;
1477 EnterCriticalSection(&g_sessions_lock);
1479 hr = get_audio_session(sessionguid, This->parent, fmt->nChannels,
1480 &This->session);
1481 if(FAILED(hr)){
1482 LeaveCriticalSection(&g_sessions_lock);
1483 CoTaskMemFree(This->fmt);
1484 This->fmt = NULL;
1485 HeapFree(GetProcessHeap(), 0, This->vols);
1486 This->vols = NULL;
1487 OSSpinLockUnlock(&This->lock);
1488 return E_INVALIDARG;
1491 list_add_tail(&This->session->clients, &This->entry);
1493 LeaveCriticalSection(&g_sessions_lock);
1495 ca_setvol(This, -1);
1497 This->initted = TRUE;
1499 OSSpinLockUnlock(&This->lock);
1501 return S_OK;
1504 static HRESULT WINAPI AudioClient_GetBufferSize(IAudioClient2 *iface,
1505 UINT32 *frames)
1507 ACImpl *This = impl_from_IAudioClient2(iface);
1509 TRACE("(%p)->(%p)\n", This, frames);
1511 if(!frames)
1512 return E_POINTER;
1514 OSSpinLockLock(&This->lock);
1516 if(!This->initted){
1517 OSSpinLockUnlock(&This->lock);
1518 return AUDCLNT_E_NOT_INITIALIZED;
1521 *frames = This->bufsize_frames;
1523 OSSpinLockUnlock(&This->lock);
1525 return S_OK;
1528 static HRESULT ca_get_max_stream_latency(ACImpl *This, UInt32 *max)
1530 AudioObjectPropertyAddress addr;
1531 AudioStreamID *ids;
1532 UInt32 size;
1533 OSStatus sc;
1534 int nstreams, i;
1536 addr.mScope = This->scope;
1537 addr.mElement = 0;
1538 addr.mSelector = kAudioDevicePropertyStreams;
1540 sc = AudioObjectGetPropertyDataSize(This->adevid, &addr, 0, NULL,
1541 &size);
1542 if(sc != noErr){
1543 WARN("Unable to get size for _Streams property: %x\n", (int)sc);
1544 return osstatus_to_hresult(sc);
1547 ids = HeapAlloc(GetProcessHeap(), 0, size);
1548 if(!ids)
1549 return E_OUTOFMEMORY;
1551 sc = AudioObjectGetPropertyData(This->adevid, &addr, 0, NULL, &size, ids);
1552 if(sc != noErr){
1553 WARN("Unable to get _Streams property: %x\n", (int)sc);
1554 HeapFree(GetProcessHeap(), 0, ids);
1555 return osstatus_to_hresult(sc);
1558 nstreams = size / sizeof(AudioStreamID);
1559 *max = 0;
1561 addr.mSelector = kAudioStreamPropertyLatency;
1562 for(i = 0; i < nstreams; ++i){
1563 UInt32 latency;
1565 size = sizeof(latency);
1566 sc = AudioObjectGetPropertyData(ids[i], &addr, 0, NULL,
1567 &size, &latency);
1568 if(sc != noErr){
1569 WARN("Unable to get _Latency property: %x\n", (int)sc);
1570 continue;
1573 if(latency > *max)
1574 *max = latency;
1577 HeapFree(GetProcessHeap(), 0, ids);
1579 return S_OK;
1582 static HRESULT WINAPI AudioClient_GetStreamLatency(IAudioClient2 *iface,
1583 REFERENCE_TIME *out)
1585 ACImpl *This = impl_from_IAudioClient2(iface);
1586 UInt32 latency, stream_latency, size;
1587 AudioObjectPropertyAddress addr;
1588 OSStatus sc;
1589 HRESULT hr;
1591 TRACE("(%p)->(%p)\n", This, out);
1593 if(!out)
1594 return E_POINTER;
1596 OSSpinLockLock(&This->lock);
1598 if(!This->initted){
1599 OSSpinLockUnlock(&This->lock);
1600 return AUDCLNT_E_NOT_INITIALIZED;
1603 addr.mScope = This->scope;
1604 addr.mSelector = kAudioDevicePropertyLatency;
1605 addr.mElement = 0;
1607 size = sizeof(latency);
1608 sc = AudioObjectGetPropertyData(This->adevid, &addr, 0, NULL,
1609 &size, &latency);
1610 if(sc != noErr){
1611 WARN("Couldn't get _Latency property: %x\n", (int)sc);
1612 OSSpinLockUnlock(&This->lock);
1613 return osstatus_to_hresult(sc);
1616 hr = ca_get_max_stream_latency(This, &stream_latency);
1617 if(FAILED(hr)){
1618 OSSpinLockUnlock(&This->lock);
1619 return hr;
1622 latency += stream_latency;
1623 /* pretend we process audio in Period chunks, so max latency includes
1624 * the period time */
1625 *out = MulDiv(latency, 10000000, This->fmt->nSamplesPerSec)
1626 + This->period_ms * 10000;
1628 OSSpinLockUnlock(&This->lock);
1630 return S_OK;
1633 static HRESULT AudioClient_GetCurrentPadding_nolock(ACImpl *This,
1634 UINT32 *numpad)
1636 if(!This->initted)
1637 return AUDCLNT_E_NOT_INITIALIZED;
1639 if(This->dataflow == eCapture)
1640 capture_resample(This);
1642 *numpad = This->held_frames;
1644 return S_OK;
1647 static HRESULT WINAPI AudioClient_GetCurrentPadding(IAudioClient2 *iface,
1648 UINT32 *numpad)
1650 ACImpl *This = impl_from_IAudioClient2(iface);
1651 HRESULT hr;
1653 TRACE("(%p)->(%p)\n", This, numpad);
1655 if(!numpad)
1656 return E_POINTER;
1658 OSSpinLockLock(&This->lock);
1660 hr = AudioClient_GetCurrentPadding_nolock(This, numpad);
1662 OSSpinLockUnlock(&This->lock);
1664 return hr;
1667 static HRESULT WINAPI AudioClient_IsFormatSupported(IAudioClient2 *iface,
1668 AUDCLNT_SHAREMODE mode, const WAVEFORMATEX *pwfx,
1669 WAVEFORMATEX **outpwfx)
1671 ACImpl *This = impl_from_IAudioClient2(iface);
1672 AudioStreamBasicDescription dev_desc;
1673 AudioConverterRef converter;
1674 AudioComponentInstance unit;
1675 WAVEFORMATEXTENSIBLE *fmtex = (WAVEFORMATEXTENSIBLE*)pwfx;
1676 HRESULT hr;
1678 TRACE("(%p)->(%x, %p, %p)\n", This, mode, pwfx, outpwfx);
1680 if(!pwfx || (mode == AUDCLNT_SHAREMODE_SHARED && !outpwfx))
1681 return E_POINTER;
1683 if(mode != AUDCLNT_SHAREMODE_SHARED && mode != AUDCLNT_SHAREMODE_EXCLUSIVE)
1684 return E_INVALIDARG;
1686 if(pwfx->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
1687 pwfx->cbSize < sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX))
1688 return E_INVALIDARG;
1690 dump_fmt(pwfx);
1692 if(outpwfx){
1693 *outpwfx = NULL;
1694 if(mode != AUDCLNT_SHAREMODE_SHARED)
1695 outpwfx = NULL;
1698 if(pwfx->wFormatTag == WAVE_FORMAT_EXTENSIBLE){
1699 if(pwfx->nAvgBytesPerSec == 0 ||
1700 pwfx->nBlockAlign == 0 ||
1701 fmtex->Samples.wValidBitsPerSample > pwfx->wBitsPerSample)
1702 return E_INVALIDARG;
1703 if(fmtex->Samples.wValidBitsPerSample < pwfx->wBitsPerSample)
1704 goto unsupported;
1705 if(mode == AUDCLNT_SHAREMODE_EXCLUSIVE){
1706 if(fmtex->dwChannelMask == 0 ||
1707 fmtex->dwChannelMask & SPEAKER_RESERVED)
1708 goto unsupported;
1712 if(pwfx->nBlockAlign != pwfx->nChannels * pwfx->wBitsPerSample / 8 ||
1713 pwfx->nAvgBytesPerSec != pwfx->nBlockAlign * pwfx->nSamplesPerSec)
1714 goto unsupported;
1716 if(pwfx->nChannels == 0)
1717 return AUDCLNT_E_UNSUPPORTED_FORMAT;
1719 unit = get_audiounit(This->dataflow, This->adevid);
1721 converter = NULL;
1722 hr = ca_setup_audiounit(This->dataflow, unit, pwfx, &dev_desc, &converter);
1723 AudioComponentInstanceDispose(unit);
1724 if(FAILED(hr))
1725 goto unsupported;
1727 if(converter)
1728 AudioConverterDispose(converter);
1730 return S_OK;
1732 unsupported:
1733 if(outpwfx){
1734 hr = IAudioClient2_GetMixFormat(&This->IAudioClient2_iface, outpwfx);
1735 if(FAILED(hr))
1736 return hr;
1737 return S_FALSE;
1740 return AUDCLNT_E_UNSUPPORTED_FORMAT;
1743 static DWORD ca_channel_layout_to_channel_mask(const AudioChannelLayout *layout)
1745 int i;
1746 DWORD mask = 0;
1748 for (i = 0; i < layout->mNumberChannelDescriptions; ++i) {
1749 switch (layout->mChannelDescriptions[i].mChannelLabel) {
1750 default: FIXME("Unhandled channel 0x%x\n", layout->mChannelDescriptions[i].mChannelLabel); break;
1751 case kAudioChannelLabel_Left: mask |= SPEAKER_FRONT_LEFT; break;
1752 case kAudioChannelLabel_Mono:
1753 case kAudioChannelLabel_Center: mask |= SPEAKER_FRONT_CENTER; break;
1754 case kAudioChannelLabel_Right: mask |= SPEAKER_FRONT_RIGHT; break;
1755 case kAudioChannelLabel_LeftSurround: mask |= SPEAKER_BACK_LEFT; break;
1756 case kAudioChannelLabel_CenterSurround: mask |= SPEAKER_BACK_CENTER; break;
1757 case kAudioChannelLabel_RightSurround: mask |= SPEAKER_BACK_RIGHT; break;
1758 case kAudioChannelLabel_LFEScreen: mask |= SPEAKER_LOW_FREQUENCY; break;
1759 case kAudioChannelLabel_LeftSurroundDirect: mask |= SPEAKER_SIDE_LEFT; break;
1760 case kAudioChannelLabel_RightSurroundDirect: mask |= SPEAKER_SIDE_RIGHT; break;
1761 case kAudioChannelLabel_TopCenterSurround: mask |= SPEAKER_TOP_CENTER; break;
1762 case kAudioChannelLabel_VerticalHeightLeft: mask |= SPEAKER_TOP_FRONT_LEFT; break;
1763 case kAudioChannelLabel_VerticalHeightCenter: mask |= SPEAKER_TOP_FRONT_CENTER; break;
1764 case kAudioChannelLabel_VerticalHeightRight: mask |= SPEAKER_TOP_FRONT_RIGHT; break;
1765 case kAudioChannelLabel_TopBackLeft: mask |= SPEAKER_TOP_BACK_LEFT; break;
1766 case kAudioChannelLabel_TopBackCenter: mask |= SPEAKER_TOP_BACK_CENTER; break;
1767 case kAudioChannelLabel_TopBackRight: mask |= SPEAKER_TOP_BACK_RIGHT; break;
1768 case kAudioChannelLabel_LeftCenter: mask |= SPEAKER_FRONT_LEFT_OF_CENTER; break;
1769 case kAudioChannelLabel_RightCenter: mask |= SPEAKER_FRONT_RIGHT_OF_CENTER; break;
1773 return mask;
1776 /* For most hardware on Windows, users must choose a configuration with an even
1777 * number of channels (stereo, quad, 5.1, 7.1). Users can then disable
1778 * channels, but those channels are still reported to applications from
1779 * GetMixFormat! Some applications behave badly if given an odd number of
1780 * channels (e.g. 2.1). Here, we find the nearest configuration that Windows
1781 * would report for a given channel layout. */
1782 static void convert_channel_layout(const AudioChannelLayout *ca_layout, WAVEFORMATEXTENSIBLE *fmt)
1784 DWORD ca_mask = ca_channel_layout_to_channel_mask(ca_layout);
1786 TRACE("Got channel mask for CA: 0x%x\n", ca_mask);
1788 if (ca_layout->mNumberChannelDescriptions == 1)
1790 fmt->Format.nChannels = 1;
1791 fmt->dwChannelMask = ca_mask;
1792 return;
1795 /* compare against known configurations and find smallest configuration
1796 * which is a superset of the given speakers */
1798 if (ca_layout->mNumberChannelDescriptions <= 2 &&
1799 (ca_mask & ~KSAUDIO_SPEAKER_STEREO) == 0)
1801 fmt->Format.nChannels = 2;
1802 fmt->dwChannelMask = KSAUDIO_SPEAKER_STEREO;
1803 return;
1806 if (ca_layout->mNumberChannelDescriptions <= 4 &&
1807 (ca_mask & ~KSAUDIO_SPEAKER_QUAD) == 0)
1809 fmt->Format.nChannels = 4;
1810 fmt->dwChannelMask = KSAUDIO_SPEAKER_QUAD;
1811 return;
1814 if (ca_layout->mNumberChannelDescriptions <= 4 &&
1815 (ca_mask & ~KSAUDIO_SPEAKER_SURROUND) == 0)
1817 fmt->Format.nChannels = 4;
1818 fmt->dwChannelMask = KSAUDIO_SPEAKER_SURROUND;
1819 return;
1822 if (ca_layout->mNumberChannelDescriptions <= 6 &&
1823 (ca_mask & ~KSAUDIO_SPEAKER_5POINT1) == 0)
1825 fmt->Format.nChannels = 6;
1826 fmt->dwChannelMask = KSAUDIO_SPEAKER_5POINT1;
1827 return;
1830 if (ca_layout->mNumberChannelDescriptions <= 6 &&
1831 (ca_mask & ~KSAUDIO_SPEAKER_5POINT1_SURROUND) == 0)
1833 fmt->Format.nChannels = 6;
1834 fmt->dwChannelMask = KSAUDIO_SPEAKER_5POINT1_SURROUND;
1835 return;
1838 if (ca_layout->mNumberChannelDescriptions <= 8 &&
1839 (ca_mask & ~KSAUDIO_SPEAKER_7POINT1) == 0)
1841 fmt->Format.nChannels = 8;
1842 fmt->dwChannelMask = KSAUDIO_SPEAKER_7POINT1;
1843 return;
1846 if (ca_layout->mNumberChannelDescriptions <= 8 &&
1847 (ca_mask & ~KSAUDIO_SPEAKER_7POINT1_SURROUND) == 0)
1849 fmt->Format.nChannels = 8;
1850 fmt->dwChannelMask = KSAUDIO_SPEAKER_7POINT1_SURROUND;
1851 return;
1854 /* oddball format, report truthfully */
1855 fmt->Format.nChannels = ca_layout->mNumberChannelDescriptions;
1856 fmt->dwChannelMask = ca_mask;
1859 static HRESULT WINAPI AudioClient_GetMixFormat(IAudioClient2 *iface,
1860 WAVEFORMATEX **pwfx)
1862 ACImpl *This = impl_from_IAudioClient2(iface);
1863 WAVEFORMATEXTENSIBLE *fmt;
1864 OSStatus sc;
1865 UInt32 size;
1866 Float64 rate;
1867 AudioBufferList *buffers;
1868 AudioChannelLayout *layout;
1869 AudioObjectPropertyAddress addr;
1870 int i;
1872 TRACE("(%p)->(%p)\n", This, pwfx);
1874 if(!pwfx)
1875 return E_POINTER;
1876 *pwfx = NULL;
1878 fmt = CoTaskMemAlloc(sizeof(WAVEFORMATEXTENSIBLE));
1879 if(!fmt)
1880 return E_OUTOFMEMORY;
1882 fmt->Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
1884 addr.mScope = This->scope;
1885 addr.mElement = 0;
1886 addr.mSelector = kAudioDevicePropertyPreferredChannelLayout;
1888 sc = AudioObjectGetPropertyDataSize(This->adevid, &addr, 0, NULL, &size);
1889 if(sc == noErr){
1890 layout = HeapAlloc(GetProcessHeap(), 0, size);
1892 sc = AudioObjectGetPropertyData(This->adevid, &addr, 0, NULL, &size, layout);
1893 if(sc == noErr){
1894 TRACE("Got channel layout: {tag: 0x%x, bitmap: 0x%x, num_descs: %u}\n",
1895 layout->mChannelLayoutTag, layout->mChannelBitmap, layout->mNumberChannelDescriptions);
1897 if(layout->mChannelLayoutTag == kAudioChannelLayoutTag_UseChannelDescriptions){
1898 convert_channel_layout(layout, fmt);
1899 }else{
1900 WARN("Haven't implemented support for this layout tag: 0x%x, guessing at layout\n", layout->mChannelLayoutTag);
1901 fmt->Format.nChannels = 0;
1903 }else{
1904 TRACE("Unable to get _PreferredChannelLayout property: %x, guessing at layout\n", (int)sc);
1905 fmt->Format.nChannels = 0;
1908 HeapFree(GetProcessHeap(), 0, layout);
1909 }else{
1910 TRACE("Unable to get size for _PreferredChannelLayout property: %x, guessing at layout\n", (int)sc);
1911 fmt->Format.nChannels = 0;
1914 if(fmt->Format.nChannels == 0){
1915 addr.mScope = This->scope;
1916 addr.mElement = 0;
1917 addr.mSelector = kAudioDevicePropertyStreamConfiguration;
1919 sc = AudioObjectGetPropertyDataSize(This->adevid, &addr, 0, NULL, &size);
1920 if(sc != noErr){
1921 CoTaskMemFree(fmt);
1922 WARN("Unable to get size for _StreamConfiguration property: %x\n", (int)sc);
1923 return osstatus_to_hresult(sc);
1926 buffers = HeapAlloc(GetProcessHeap(), 0, size);
1927 if(!buffers){
1928 CoTaskMemFree(fmt);
1929 return E_OUTOFMEMORY;
1932 sc = AudioObjectGetPropertyData(This->adevid, &addr, 0, NULL,
1933 &size, buffers);
1934 if(sc != noErr){
1935 CoTaskMemFree(fmt);
1936 HeapFree(GetProcessHeap(), 0, buffers);
1937 WARN("Unable to get _StreamConfiguration property: %x\n", (int)sc);
1938 return osstatus_to_hresult(sc);
1941 fmt->Format.nChannels = 0;
1942 for(i = 0; i < buffers->mNumberBuffers; ++i)
1943 fmt->Format.nChannels += buffers->mBuffers[i].mNumberChannels;
1945 HeapFree(GetProcessHeap(), 0, buffers);
1947 fmt->dwChannelMask = get_channel_mask(fmt->Format.nChannels);
1950 addr.mSelector = kAudioDevicePropertyNominalSampleRate;
1951 size = sizeof(Float64);
1952 sc = AudioObjectGetPropertyData(This->adevid, &addr, 0, NULL, &size, &rate);
1953 if(sc != noErr){
1954 CoTaskMemFree(fmt);
1955 WARN("Unable to get _NominalSampleRate property: %x\n", (int)sc);
1956 return osstatus_to_hresult(sc);
1958 fmt->Format.nSamplesPerSec = rate;
1960 fmt->Format.wBitsPerSample = 32;
1961 fmt->SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
1963 fmt->Format.nBlockAlign = (fmt->Format.wBitsPerSample *
1964 fmt->Format.nChannels) / 8;
1965 fmt->Format.nAvgBytesPerSec = fmt->Format.nSamplesPerSec *
1966 fmt->Format.nBlockAlign;
1968 fmt->Samples.wValidBitsPerSample = fmt->Format.wBitsPerSample;
1969 fmt->Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX);
1971 *pwfx = (WAVEFORMATEX*)fmt;
1972 dump_fmt(*pwfx);
1974 return S_OK;
1977 static HRESULT WINAPI AudioClient_GetDevicePeriod(IAudioClient2 *iface,
1978 REFERENCE_TIME *defperiod, REFERENCE_TIME *minperiod)
1980 ACImpl *This = impl_from_IAudioClient2(iface);
1982 TRACE("(%p)->(%p, %p)\n", This, defperiod, minperiod);
1984 if(!defperiod && !minperiod)
1985 return E_POINTER;
1987 if(defperiod)
1988 *defperiod = DefaultPeriod;
1989 if(minperiod)
1990 *minperiod = MinimumPeriod;
1992 return S_OK;
1995 void CALLBACK ca_period_cb(void *user, BOOLEAN timer)
1997 ACImpl *This = user;
1999 if(This->event)
2000 SetEvent(This->event);
2003 static HRESULT WINAPI AudioClient_Start(IAudioClient2 *iface)
2005 ACImpl *This = impl_from_IAudioClient2(iface);
2007 TRACE("(%p)\n", This);
2009 OSSpinLockLock(&This->lock);
2011 if(!This->initted){
2012 OSSpinLockUnlock(&This->lock);
2013 return AUDCLNT_E_NOT_INITIALIZED;
2016 if(This->playing){
2017 OSSpinLockUnlock(&This->lock);
2018 return AUDCLNT_E_NOT_STOPPED;
2021 if((This->flags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK) && !This->event){
2022 OSSpinLockUnlock(&This->lock);
2023 return AUDCLNT_E_EVENTHANDLE_NOT_SET;
2026 if(This->event && !This->timer)
2027 if(!CreateTimerQueueTimer(&This->timer, g_timer_q, ca_period_cb,
2028 This, 0, This->period_ms, WT_EXECUTEINTIMERTHREAD)){
2029 This->timer = NULL;
2030 OSSpinLockUnlock(&This->lock);
2031 WARN("Unable to create timer: %u\n", GetLastError());
2032 return E_OUTOFMEMORY;
2035 This->playing = TRUE;
2037 OSSpinLockUnlock(&This->lock);
2039 return S_OK;
2042 static HRESULT WINAPI AudioClient_Stop(IAudioClient2 *iface)
2044 ACImpl *This = impl_from_IAudioClient2(iface);
2046 TRACE("(%p)\n", This);
2048 OSSpinLockLock(&This->lock);
2050 if(!This->initted){
2051 OSSpinLockUnlock(&This->lock);
2052 return AUDCLNT_E_NOT_INITIALIZED;
2055 if(!This->playing){
2056 OSSpinLockUnlock(&This->lock);
2057 return S_FALSE;
2060 This->playing = FALSE;
2062 OSSpinLockUnlock(&This->lock);
2064 return S_OK;
2067 static HRESULT WINAPI AudioClient_Reset(IAudioClient2 *iface)
2069 ACImpl *This = impl_from_IAudioClient2(iface);
2071 TRACE("(%p)\n", This);
2073 OSSpinLockLock(&This->lock);
2075 if(!This->initted){
2076 OSSpinLockUnlock(&This->lock);
2077 return AUDCLNT_E_NOT_INITIALIZED;
2080 if(This->playing){
2081 OSSpinLockUnlock(&This->lock);
2082 return AUDCLNT_E_NOT_STOPPED;
2085 if(This->getbuf_last){
2086 OSSpinLockUnlock(&This->lock);
2087 return AUDCLNT_E_BUFFER_OPERATION_PENDING;
2090 if(This->dataflow == eRender){
2091 This->written_frames = 0;
2092 }else{
2093 This->written_frames += This->held_frames;
2096 This->held_frames = 0;
2097 This->lcl_offs_frames = 0;
2098 This->wri_offs_frames = 0;
2099 This->cap_offs_frames = 0;
2100 This->cap_held_frames = 0;
2102 OSSpinLockUnlock(&This->lock);
2104 return S_OK;
2107 static HRESULT WINAPI AudioClient_SetEventHandle(IAudioClient2 *iface,
2108 HANDLE event)
2110 ACImpl *This = impl_from_IAudioClient2(iface);
2112 TRACE("(%p)->(%p)\n", This, event);
2114 if(!event)
2115 return E_INVALIDARG;
2117 OSSpinLockLock(&This->lock);
2119 if(!This->initted){
2120 OSSpinLockUnlock(&This->lock);
2121 return AUDCLNT_E_NOT_INITIALIZED;
2124 if(!(This->flags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK)){
2125 OSSpinLockUnlock(&This->lock);
2126 return AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED;
2129 if (This->event){
2130 OSSpinLockUnlock(&This->lock);
2131 FIXME("called twice\n");
2132 return HRESULT_FROM_WIN32(ERROR_INVALID_NAME);
2135 This->event = event;
2137 OSSpinLockUnlock(&This->lock);
2139 return S_OK;
2142 static HRESULT WINAPI AudioClient_GetService(IAudioClient2 *iface, REFIID riid,
2143 void **ppv)
2145 ACImpl *This = impl_from_IAudioClient2(iface);
2147 TRACE("(%p)->(%s, %p)\n", This, debugstr_guid(riid), ppv);
2149 if(!ppv)
2150 return E_POINTER;
2151 *ppv = NULL;
2153 OSSpinLockLock(&This->lock);
2155 if(!This->initted){
2156 OSSpinLockUnlock(&This->lock);
2157 return AUDCLNT_E_NOT_INITIALIZED;
2160 if(IsEqualIID(riid, &IID_IAudioRenderClient)){
2161 if(This->dataflow != eRender){
2162 OSSpinLockUnlock(&This->lock);
2163 return AUDCLNT_E_WRONG_ENDPOINT_TYPE;
2165 IAudioRenderClient_AddRef(&This->IAudioRenderClient_iface);
2166 *ppv = &This->IAudioRenderClient_iface;
2167 }else if(IsEqualIID(riid, &IID_IAudioCaptureClient)){
2168 if(This->dataflow != eCapture){
2169 OSSpinLockUnlock(&This->lock);
2170 return AUDCLNT_E_WRONG_ENDPOINT_TYPE;
2172 IAudioCaptureClient_AddRef(&This->IAudioCaptureClient_iface);
2173 *ppv = &This->IAudioCaptureClient_iface;
2174 }else if(IsEqualIID(riid, &IID_IAudioClock)){
2175 IAudioClock_AddRef(&This->IAudioClock_iface);
2176 *ppv = &This->IAudioClock_iface;
2177 }else if(IsEqualIID(riid, &IID_IAudioStreamVolume)){
2178 IAudioStreamVolume_AddRef(&This->IAudioStreamVolume_iface);
2179 *ppv = &This->IAudioStreamVolume_iface;
2180 }else if(IsEqualIID(riid, &IID_IAudioSessionControl)){
2181 if(!This->session_wrapper){
2182 This->session_wrapper = AudioSessionWrapper_Create(This);
2183 if(!This->session_wrapper){
2184 OSSpinLockUnlock(&This->lock);
2185 return E_OUTOFMEMORY;
2187 }else
2188 IAudioSessionControl2_AddRef(&This->session_wrapper->IAudioSessionControl2_iface);
2190 *ppv = &This->session_wrapper->IAudioSessionControl2_iface;
2191 }else if(IsEqualIID(riid, &IID_IChannelAudioVolume)){
2192 if(!This->session_wrapper){
2193 This->session_wrapper = AudioSessionWrapper_Create(This);
2194 if(!This->session_wrapper){
2195 OSSpinLockUnlock(&This->lock);
2196 return E_OUTOFMEMORY;
2198 }else
2199 IChannelAudioVolume_AddRef(&This->session_wrapper->IChannelAudioVolume_iface);
2201 *ppv = &This->session_wrapper->IChannelAudioVolume_iface;
2202 }else if(IsEqualIID(riid, &IID_ISimpleAudioVolume)){
2203 if(!This->session_wrapper){
2204 This->session_wrapper = AudioSessionWrapper_Create(This);
2205 if(!This->session_wrapper){
2206 OSSpinLockUnlock(&This->lock);
2207 return E_OUTOFMEMORY;
2209 }else
2210 ISimpleAudioVolume_AddRef(&This->session_wrapper->ISimpleAudioVolume_iface);
2212 *ppv = &This->session_wrapper->ISimpleAudioVolume_iface;
2215 if(*ppv){
2216 OSSpinLockUnlock(&This->lock);
2217 return S_OK;
2220 OSSpinLockUnlock(&This->lock);
2222 FIXME("stub %s\n", debugstr_guid(riid));
2223 return E_NOINTERFACE;
2226 static HRESULT WINAPI AudioClient_IsOffloadCapable(IAudioClient2 *iface,
2227 AUDIO_STREAM_CATEGORY category, BOOL *offload_capable)
2229 ACImpl *This = impl_from_IAudioClient2(iface);
2231 TRACE("(%p)->(0x%x, %p)\n", This, category, offload_capable);
2233 if(!offload_capable)
2234 return E_INVALIDARG;
2236 *offload_capable = FALSE;
2238 return S_OK;
2241 static HRESULT WINAPI AudioClient_SetClientProperties(IAudioClient2 *iface,
2242 const AudioClientProperties *prop)
2244 ACImpl *This = impl_from_IAudioClient2(iface);
2246 TRACE("(%p)->(%p)\n", This, prop);
2248 if(!prop)
2249 return E_POINTER;
2251 if(prop->cbSize != sizeof(*prop))
2252 return E_INVALIDARG;
2254 TRACE("{ bIsOffload: %u, eCategory: 0x%x, Options: 0x%x }\n",
2255 prop->bIsOffload,
2256 prop->eCategory,
2257 prop->Options);
2259 if(prop->bIsOffload)
2260 return AUDCLNT_E_ENDPOINT_OFFLOAD_NOT_CAPABLE;
2262 return S_OK;
2265 static HRESULT WINAPI AudioClient_GetBufferSizeLimits(IAudioClient2 *iface,
2266 const WAVEFORMATEX *format, BOOL event_driven, REFERENCE_TIME *min_duration,
2267 REFERENCE_TIME *max_duration)
2269 ACImpl *This = impl_from_IAudioClient2(iface);
2271 FIXME("(%p)->(%p, %u, %p, %p)\n", This, format, event_driven, min_duration, max_duration);
2273 return E_NOTIMPL;
2276 static const IAudioClient2Vtbl AudioClient2_Vtbl =
2278 AudioClient_QueryInterface,
2279 AudioClient_AddRef,
2280 AudioClient_Release,
2281 AudioClient_Initialize,
2282 AudioClient_GetBufferSize,
2283 AudioClient_GetStreamLatency,
2284 AudioClient_GetCurrentPadding,
2285 AudioClient_IsFormatSupported,
2286 AudioClient_GetMixFormat,
2287 AudioClient_GetDevicePeriod,
2288 AudioClient_Start,
2289 AudioClient_Stop,
2290 AudioClient_Reset,
2291 AudioClient_SetEventHandle,
2292 AudioClient_GetService,
2293 AudioClient_IsOffloadCapable,
2294 AudioClient_SetClientProperties,
2295 AudioClient_GetBufferSizeLimits,
2298 static HRESULT WINAPI AudioRenderClient_QueryInterface(
2299 IAudioRenderClient *iface, REFIID riid, void **ppv)
2301 ACImpl *This = impl_from_IAudioRenderClient(iface);
2302 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
2304 if(!ppv)
2305 return E_POINTER;
2306 *ppv = NULL;
2308 if(IsEqualIID(riid, &IID_IUnknown) ||
2309 IsEqualIID(riid, &IID_IAudioRenderClient))
2310 *ppv = iface;
2311 else if(IsEqualIID(riid, &IID_IMarshal))
2312 return IUnknown_QueryInterface(This->pUnkFTMarshal, riid, ppv);
2314 if(*ppv){
2315 IUnknown_AddRef((IUnknown*)*ppv);
2316 return S_OK;
2319 WARN("Unknown interface %s\n", debugstr_guid(riid));
2320 return E_NOINTERFACE;
2323 static ULONG WINAPI AudioRenderClient_AddRef(IAudioRenderClient *iface)
2325 ACImpl *This = impl_from_IAudioRenderClient(iface);
2326 return AudioClient_AddRef(&This->IAudioClient2_iface);
2329 static ULONG WINAPI AudioRenderClient_Release(IAudioRenderClient *iface)
2331 ACImpl *This = impl_from_IAudioRenderClient(iface);
2332 return AudioClient_Release(&This->IAudioClient2_iface);
2335 static HRESULT WINAPI AudioRenderClient_GetBuffer(IAudioRenderClient *iface,
2336 UINT32 frames, BYTE **data)
2338 ACImpl *This = impl_from_IAudioRenderClient(iface);
2339 UINT32 pad;
2340 HRESULT hr;
2342 TRACE("(%p)->(%u, %p)\n", This, frames, data);
2344 if(!data)
2345 return E_POINTER;
2346 *data = NULL;
2348 OSSpinLockLock(&This->lock);
2350 if(This->getbuf_last){
2351 OSSpinLockUnlock(&This->lock);
2352 return AUDCLNT_E_OUT_OF_ORDER;
2355 if(!frames){
2356 OSSpinLockUnlock(&This->lock);
2357 return S_OK;
2360 hr = AudioClient_GetCurrentPadding_nolock(This, &pad);
2361 if(FAILED(hr)){
2362 OSSpinLockUnlock(&This->lock);
2363 return hr;
2366 if(pad + frames > This->bufsize_frames){
2367 OSSpinLockUnlock(&This->lock);
2368 return AUDCLNT_E_BUFFER_TOO_LARGE;
2371 if(This->wri_offs_frames + frames > This->bufsize_frames){
2372 if(This->tmp_buffer_frames < frames){
2373 HeapFree(GetProcessHeap(), 0, This->tmp_buffer);
2374 This->tmp_buffer = HeapAlloc(GetProcessHeap(), 0, frames * This->fmt->nBlockAlign);
2375 if(!This->tmp_buffer){
2376 OSSpinLockUnlock(&This->lock);
2377 return E_OUTOFMEMORY;
2379 This->tmp_buffer_frames = frames;
2381 *data = This->tmp_buffer;
2382 This->getbuf_last = -frames;
2383 }else{
2384 *data = This->local_buffer + This->wri_offs_frames * This->fmt->nBlockAlign;
2385 This->getbuf_last = frames;
2388 silence_buffer(This, *data, frames);
2390 OSSpinLockUnlock(&This->lock);
2392 return S_OK;
2395 static HRESULT WINAPI AudioRenderClient_ReleaseBuffer(
2396 IAudioRenderClient *iface, UINT32 frames, DWORD flags)
2398 ACImpl *This = impl_from_IAudioRenderClient(iface);
2399 BYTE *buffer;
2401 TRACE("(%p)->(%u, %x)\n", This, frames, flags);
2403 OSSpinLockLock(&This->lock);
2405 if(!frames){
2406 This->getbuf_last = 0;
2407 OSSpinLockUnlock(&This->lock);
2408 return S_OK;
2411 if(!This->getbuf_last){
2412 OSSpinLockUnlock(&This->lock);
2413 return AUDCLNT_E_OUT_OF_ORDER;
2416 if(frames > (This->getbuf_last >= 0 ? This->getbuf_last : -This->getbuf_last)){
2417 OSSpinLockUnlock(&This->lock);
2418 return AUDCLNT_E_INVALID_SIZE;
2421 if(This->getbuf_last >= 0)
2422 buffer = This->local_buffer + This->wri_offs_frames * This->fmt->nBlockAlign;
2423 else
2424 buffer = This->tmp_buffer;
2426 if(flags & AUDCLNT_BUFFERFLAGS_SILENT)
2427 silence_buffer(This, buffer, frames);
2429 if(This->getbuf_last < 0)
2430 ca_wrap_buffer(This->local_buffer,
2431 This->wri_offs_frames * This->fmt->nBlockAlign,
2432 This->bufsize_frames * This->fmt->nBlockAlign,
2433 buffer, frames * This->fmt->nBlockAlign);
2436 This->wri_offs_frames += frames;
2437 This->wri_offs_frames %= This->bufsize_frames;
2438 This->held_frames += frames;
2439 This->written_frames += frames;
2440 This->getbuf_last = 0;
2442 OSSpinLockUnlock(&This->lock);
2444 return S_OK;
2447 static const IAudioRenderClientVtbl AudioRenderClient_Vtbl = {
2448 AudioRenderClient_QueryInterface,
2449 AudioRenderClient_AddRef,
2450 AudioRenderClient_Release,
2451 AudioRenderClient_GetBuffer,
2452 AudioRenderClient_ReleaseBuffer
2455 static HRESULT WINAPI AudioCaptureClient_QueryInterface(
2456 IAudioCaptureClient *iface, REFIID riid, void **ppv)
2458 ACImpl *This = impl_from_IAudioCaptureClient(iface);
2459 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
2461 if(!ppv)
2462 return E_POINTER;
2463 *ppv = NULL;
2465 if(IsEqualIID(riid, &IID_IUnknown) ||
2466 IsEqualIID(riid, &IID_IAudioCaptureClient))
2467 *ppv = iface;
2468 else if(IsEqualIID(riid, &IID_IMarshal))
2469 return IUnknown_QueryInterface(This->pUnkFTMarshal, riid, ppv);
2471 if(*ppv){
2472 IUnknown_AddRef((IUnknown*)*ppv);
2473 return S_OK;
2476 WARN("Unknown interface %s\n", debugstr_guid(riid));
2477 return E_NOINTERFACE;
2480 static ULONG WINAPI AudioCaptureClient_AddRef(IAudioCaptureClient *iface)
2482 ACImpl *This = impl_from_IAudioCaptureClient(iface);
2483 return IAudioClient2_AddRef(&This->IAudioClient2_iface);
2486 static ULONG WINAPI AudioCaptureClient_Release(IAudioCaptureClient *iface)
2488 ACImpl *This = impl_from_IAudioCaptureClient(iface);
2489 return IAudioClient2_Release(&This->IAudioClient2_iface);
2492 static HRESULT WINAPI AudioCaptureClient_GetBuffer(IAudioCaptureClient *iface,
2493 BYTE **data, UINT32 *frames, DWORD *flags, UINT64 *devpos,
2494 UINT64 *qpcpos)
2496 ACImpl *This = impl_from_IAudioCaptureClient(iface);
2497 UINT32 chunk_bytes, chunk_frames;
2499 TRACE("(%p)->(%p, %p, %p, %p, %p)\n", This, data, frames, flags,
2500 devpos, qpcpos);
2502 if(!data)
2503 return E_POINTER;
2505 *data = NULL;
2507 if(!frames || !flags)
2508 return E_POINTER;
2510 OSSpinLockLock(&This->lock);
2512 if(This->getbuf_last){
2513 OSSpinLockUnlock(&This->lock);
2514 return AUDCLNT_E_OUT_OF_ORDER;
2517 capture_resample(This);
2519 if(This->held_frames < This->period_frames){
2520 *frames = 0;
2521 OSSpinLockUnlock(&This->lock);
2522 return AUDCLNT_S_BUFFER_EMPTY;
2525 *flags = 0;
2527 chunk_frames = This->bufsize_frames - This->lcl_offs_frames;
2528 if(chunk_frames < This->period_frames){
2529 chunk_bytes = chunk_frames * This->fmt->nBlockAlign;
2530 if(!This->tmp_buffer)
2531 This->tmp_buffer = HeapAlloc(GetProcessHeap(), 0, This->period_frames * This->fmt->nBlockAlign);
2532 *data = This->tmp_buffer;
2533 memcpy(*data, This->local_buffer + This->lcl_offs_frames * This->fmt->nBlockAlign, chunk_bytes);
2534 memcpy((*data) + chunk_bytes, This->local_buffer, This->period_frames * This->fmt->nBlockAlign - chunk_bytes);
2535 }else
2536 *data = This->local_buffer + This->lcl_offs_frames * This->fmt->nBlockAlign;
2538 This->getbuf_last = *frames = This->period_frames;
2540 if(devpos)
2541 *devpos = This->written_frames;
2542 if(qpcpos){ /* fixme: qpc of recording time */
2543 LARGE_INTEGER stamp, freq;
2544 QueryPerformanceCounter(&stamp);
2545 QueryPerformanceFrequency(&freq);
2546 *qpcpos = (stamp.QuadPart * (INT64)10000000) / freq.QuadPart;
2549 OSSpinLockUnlock(&This->lock);
2551 return S_OK;
2554 static HRESULT WINAPI AudioCaptureClient_ReleaseBuffer(
2555 IAudioCaptureClient *iface, UINT32 done)
2557 ACImpl *This = impl_from_IAudioCaptureClient(iface);
2559 TRACE("(%p)->(%u)\n", This, done);
2561 OSSpinLockLock(&This->lock);
2563 if(!done){
2564 This->getbuf_last = 0;
2565 OSSpinLockUnlock(&This->lock);
2566 return S_OK;
2569 if(!This->getbuf_last){
2570 OSSpinLockUnlock(&This->lock);
2571 return AUDCLNT_E_OUT_OF_ORDER;
2574 if(This->getbuf_last != done){
2575 OSSpinLockUnlock(&This->lock);
2576 return AUDCLNT_E_INVALID_SIZE;
2579 This->written_frames += done;
2580 This->held_frames -= done;
2581 This->lcl_offs_frames += done;
2582 This->lcl_offs_frames %= This->bufsize_frames;
2583 This->getbuf_last = 0;
2585 OSSpinLockUnlock(&This->lock);
2587 return S_OK;
2590 static HRESULT WINAPI AudioCaptureClient_GetNextPacketSize(
2591 IAudioCaptureClient *iface, UINT32 *frames)
2593 ACImpl *This = impl_from_IAudioCaptureClient(iface);
2595 TRACE("(%p)->(%p)\n", This, frames);
2597 if(!frames)
2598 return E_POINTER;
2600 OSSpinLockLock(&This->lock);
2602 capture_resample(This);
2604 if(This->held_frames >= This->period_frames)
2605 *frames = This->period_frames;
2606 else
2607 *frames = 0;
2609 OSSpinLockUnlock(&This->lock);
2611 return S_OK;
2614 static const IAudioCaptureClientVtbl AudioCaptureClient_Vtbl =
2616 AudioCaptureClient_QueryInterface,
2617 AudioCaptureClient_AddRef,
2618 AudioCaptureClient_Release,
2619 AudioCaptureClient_GetBuffer,
2620 AudioCaptureClient_ReleaseBuffer,
2621 AudioCaptureClient_GetNextPacketSize
2624 static HRESULT WINAPI AudioClock_QueryInterface(IAudioClock *iface,
2625 REFIID riid, void **ppv)
2627 ACImpl *This = impl_from_IAudioClock(iface);
2629 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
2631 if(!ppv)
2632 return E_POINTER;
2633 *ppv = NULL;
2635 if(IsEqualIID(riid, &IID_IUnknown) || IsEqualIID(riid, &IID_IAudioClock))
2636 *ppv = iface;
2637 else if(IsEqualIID(riid, &IID_IAudioClock2))
2638 *ppv = &This->IAudioClock2_iface;
2639 if(*ppv){
2640 IUnknown_AddRef((IUnknown*)*ppv);
2641 return S_OK;
2644 WARN("Unknown interface %s\n", debugstr_guid(riid));
2645 return E_NOINTERFACE;
2648 static ULONG WINAPI AudioClock_AddRef(IAudioClock *iface)
2650 ACImpl *This = impl_from_IAudioClock(iface);
2651 return IAudioClient2_AddRef(&This->IAudioClient2_iface);
2654 static ULONG WINAPI AudioClock_Release(IAudioClock *iface)
2656 ACImpl *This = impl_from_IAudioClock(iface);
2657 return IAudioClient2_Release(&This->IAudioClient2_iface);
2660 static HRESULT WINAPI AudioClock_GetFrequency(IAudioClock *iface, UINT64 *freq)
2662 ACImpl *This = impl_from_IAudioClock(iface);
2664 TRACE("(%p)->(%p)\n", This, freq);
2666 if(This->share == AUDCLNT_SHAREMODE_SHARED)
2667 *freq = (UINT64)This->fmt->nSamplesPerSec * This->fmt->nBlockAlign;
2668 else
2669 *freq = This->fmt->nSamplesPerSec;
2671 return S_OK;
2674 static HRESULT AudioClock_GetPosition_nolock(ACImpl *This,
2675 UINT64 *pos, UINT64 *qpctime)
2677 *pos = This->written_frames - This->held_frames;
2679 if(This->share == AUDCLNT_SHAREMODE_SHARED)
2680 *pos *= This->fmt->nBlockAlign;
2682 if(qpctime){
2683 LARGE_INTEGER stamp, freq;
2684 QueryPerformanceCounter(&stamp);
2685 QueryPerformanceFrequency(&freq);
2686 *qpctime = (stamp.QuadPart * (INT64)10000000) / freq.QuadPart;
2689 return S_OK;
2692 static HRESULT WINAPI AudioClock_GetPosition(IAudioClock *iface, UINT64 *pos,
2693 UINT64 *qpctime)
2695 ACImpl *This = impl_from_IAudioClock(iface);
2696 HRESULT hr;
2698 TRACE("(%p)->(%p, %p)\n", This, pos, qpctime);
2700 if(!pos)
2701 return E_POINTER;
2703 OSSpinLockLock(&This->lock);
2705 hr = AudioClock_GetPosition_nolock(This, pos, qpctime);
2707 OSSpinLockUnlock(&This->lock);
2709 return hr;
2712 static HRESULT WINAPI AudioClock_GetCharacteristics(IAudioClock *iface,
2713 DWORD *chars)
2715 ACImpl *This = impl_from_IAudioClock(iface);
2717 TRACE("(%p)->(%p)\n", This, chars);
2719 if(!chars)
2720 return E_POINTER;
2722 *chars = AUDIOCLOCK_CHARACTERISTIC_FIXED_FREQ;
2724 return S_OK;
2727 static const IAudioClockVtbl AudioClock_Vtbl =
2729 AudioClock_QueryInterface,
2730 AudioClock_AddRef,
2731 AudioClock_Release,
2732 AudioClock_GetFrequency,
2733 AudioClock_GetPosition,
2734 AudioClock_GetCharacteristics
2737 static HRESULT WINAPI AudioClock2_QueryInterface(IAudioClock2 *iface,
2738 REFIID riid, void **ppv)
2740 ACImpl *This = impl_from_IAudioClock2(iface);
2741 return IAudioClock_QueryInterface(&This->IAudioClock_iface, riid, ppv);
2744 static ULONG WINAPI AudioClock2_AddRef(IAudioClock2 *iface)
2746 ACImpl *This = impl_from_IAudioClock2(iface);
2747 return IAudioClient2_AddRef(&This->IAudioClient2_iface);
2750 static ULONG WINAPI AudioClock2_Release(IAudioClock2 *iface)
2752 ACImpl *This = impl_from_IAudioClock2(iface);
2753 return IAudioClient2_Release(&This->IAudioClient2_iface);
2756 static HRESULT WINAPI AudioClock2_GetDevicePosition(IAudioClock2 *iface,
2757 UINT64 *pos, UINT64 *qpctime)
2759 ACImpl *This = impl_from_IAudioClock2(iface);
2761 FIXME("(%p)->(%p, %p)\n", This, pos, qpctime);
2763 return E_NOTIMPL;
2766 static const IAudioClock2Vtbl AudioClock2_Vtbl =
2768 AudioClock2_QueryInterface,
2769 AudioClock2_AddRef,
2770 AudioClock2_Release,
2771 AudioClock2_GetDevicePosition
2774 static AudioSessionWrapper *AudioSessionWrapper_Create(ACImpl *client)
2776 AudioSessionWrapper *ret;
2778 ret = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
2779 sizeof(AudioSessionWrapper));
2780 if(!ret)
2781 return NULL;
2783 ret->IAudioSessionControl2_iface.lpVtbl = &AudioSessionControl2_Vtbl;
2784 ret->ISimpleAudioVolume_iface.lpVtbl = &SimpleAudioVolume_Vtbl;
2785 ret->IChannelAudioVolume_iface.lpVtbl = &ChannelAudioVolume_Vtbl;
2787 ret->ref = 1;
2789 ret->client = client;
2790 if(client){
2791 ret->session = client->session;
2792 AudioClient2_AddRef(&client->IAudioClient2_iface);
2795 return ret;
2798 static HRESULT WINAPI AudioSessionControl_QueryInterface(
2799 IAudioSessionControl2 *iface, REFIID riid, void **ppv)
2801 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
2803 if(!ppv)
2804 return E_POINTER;
2805 *ppv = NULL;
2807 if(IsEqualIID(riid, &IID_IUnknown) ||
2808 IsEqualIID(riid, &IID_IAudioSessionControl) ||
2809 IsEqualIID(riid, &IID_IAudioSessionControl2))
2810 *ppv = iface;
2811 if(*ppv){
2812 IUnknown_AddRef((IUnknown*)*ppv);
2813 return S_OK;
2816 WARN("Unknown interface %s\n", debugstr_guid(riid));
2817 return E_NOINTERFACE;
2820 static ULONG WINAPI AudioSessionControl_AddRef(IAudioSessionControl2 *iface)
2822 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2823 ULONG ref;
2824 ref = InterlockedIncrement(&This->ref);
2825 TRACE("(%p) Refcount now %u\n", This, ref);
2826 return ref;
2829 static ULONG WINAPI AudioSessionControl_Release(IAudioSessionControl2 *iface)
2831 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2832 ULONG ref;
2833 ref = InterlockedDecrement(&This->ref);
2834 TRACE("(%p) Refcount now %u\n", This, ref);
2835 if(!ref){
2836 if(This->client){
2837 OSSpinLockLock(&This->client->lock);
2838 This->client->session_wrapper = NULL;
2839 OSSpinLockUnlock(&This->client->lock);
2840 AudioClient_Release(&This->client->IAudioClient2_iface);
2842 HeapFree(GetProcessHeap(), 0, This);
2844 return ref;
2847 static HRESULT WINAPI AudioSessionControl_GetState(IAudioSessionControl2 *iface,
2848 AudioSessionState *state)
2850 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2851 ACImpl *client;
2853 TRACE("(%p)->(%p)\n", This, state);
2855 if(!state)
2856 return NULL_PTR_ERR;
2858 EnterCriticalSection(&g_sessions_lock);
2860 if(list_empty(&This->session->clients)){
2861 *state = AudioSessionStateExpired;
2862 LeaveCriticalSection(&g_sessions_lock);
2863 return S_OK;
2866 LIST_FOR_EACH_ENTRY(client, &This->session->clients, ACImpl, entry){
2867 OSSpinLockLock(&client->lock);
2868 if(client->playing){
2869 *state = AudioSessionStateActive;
2870 OSSpinLockUnlock(&client->lock);
2871 LeaveCriticalSection(&g_sessions_lock);
2872 return S_OK;
2874 OSSpinLockUnlock(&client->lock);
2877 LeaveCriticalSection(&g_sessions_lock);
2879 *state = AudioSessionStateInactive;
2881 return S_OK;
2884 static HRESULT WINAPI AudioSessionControl_GetDisplayName(
2885 IAudioSessionControl2 *iface, WCHAR **name)
2887 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2889 FIXME("(%p)->(%p) - stub\n", This, name);
2891 return E_NOTIMPL;
2894 static HRESULT WINAPI AudioSessionControl_SetDisplayName(
2895 IAudioSessionControl2 *iface, const WCHAR *name, const GUID *session)
2897 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2899 FIXME("(%p)->(%p, %s) - stub\n", This, name, debugstr_guid(session));
2901 return E_NOTIMPL;
2904 static HRESULT WINAPI AudioSessionControl_GetIconPath(
2905 IAudioSessionControl2 *iface, WCHAR **path)
2907 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2909 FIXME("(%p)->(%p) - stub\n", This, path);
2911 return E_NOTIMPL;
2914 static HRESULT WINAPI AudioSessionControl_SetIconPath(
2915 IAudioSessionControl2 *iface, const WCHAR *path, const GUID *session)
2917 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2919 FIXME("(%p)->(%p, %s) - stub\n", This, path, debugstr_guid(session));
2921 return E_NOTIMPL;
2924 static HRESULT WINAPI AudioSessionControl_GetGroupingParam(
2925 IAudioSessionControl2 *iface, GUID *group)
2927 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2929 FIXME("(%p)->(%p) - stub\n", This, group);
2931 return E_NOTIMPL;
2934 static HRESULT WINAPI AudioSessionControl_SetGroupingParam(
2935 IAudioSessionControl2 *iface, const GUID *group, const GUID *session)
2937 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2939 FIXME("(%p)->(%s, %s) - stub\n", This, debugstr_guid(group),
2940 debugstr_guid(session));
2942 return E_NOTIMPL;
2945 static HRESULT WINAPI AudioSessionControl_RegisterAudioSessionNotification(
2946 IAudioSessionControl2 *iface, IAudioSessionEvents *events)
2948 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2950 FIXME("(%p)->(%p) - stub\n", This, events);
2952 return S_OK;
2955 static HRESULT WINAPI AudioSessionControl_UnregisterAudioSessionNotification(
2956 IAudioSessionControl2 *iface, IAudioSessionEvents *events)
2958 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2960 FIXME("(%p)->(%p) - stub\n", This, events);
2962 return S_OK;
2965 static HRESULT WINAPI AudioSessionControl_GetSessionIdentifier(
2966 IAudioSessionControl2 *iface, WCHAR **id)
2968 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2970 FIXME("(%p)->(%p) - stub\n", This, id);
2972 return E_NOTIMPL;
2975 static HRESULT WINAPI AudioSessionControl_GetSessionInstanceIdentifier(
2976 IAudioSessionControl2 *iface, WCHAR **id)
2978 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2980 FIXME("(%p)->(%p) - stub\n", This, id);
2982 return E_NOTIMPL;
2985 static HRESULT WINAPI AudioSessionControl_GetProcessId(
2986 IAudioSessionControl2 *iface, DWORD *pid)
2988 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2990 TRACE("(%p)->(%p)\n", This, pid);
2992 if(!pid)
2993 return E_POINTER;
2995 *pid = GetCurrentProcessId();
2997 return S_OK;
3000 static HRESULT WINAPI AudioSessionControl_IsSystemSoundsSession(
3001 IAudioSessionControl2 *iface)
3003 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
3005 TRACE("(%p)\n", This);
3007 return S_FALSE;
3010 static HRESULT WINAPI AudioSessionControl_SetDuckingPreference(
3011 IAudioSessionControl2 *iface, BOOL optout)
3013 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
3015 TRACE("(%p)->(%d)\n", This, optout);
3017 return S_OK;
3020 static const IAudioSessionControl2Vtbl AudioSessionControl2_Vtbl =
3022 AudioSessionControl_QueryInterface,
3023 AudioSessionControl_AddRef,
3024 AudioSessionControl_Release,
3025 AudioSessionControl_GetState,
3026 AudioSessionControl_GetDisplayName,
3027 AudioSessionControl_SetDisplayName,
3028 AudioSessionControl_GetIconPath,
3029 AudioSessionControl_SetIconPath,
3030 AudioSessionControl_GetGroupingParam,
3031 AudioSessionControl_SetGroupingParam,
3032 AudioSessionControl_RegisterAudioSessionNotification,
3033 AudioSessionControl_UnregisterAudioSessionNotification,
3034 AudioSessionControl_GetSessionIdentifier,
3035 AudioSessionControl_GetSessionInstanceIdentifier,
3036 AudioSessionControl_GetProcessId,
3037 AudioSessionControl_IsSystemSoundsSession,
3038 AudioSessionControl_SetDuckingPreference
3041 /* index == -1 means set all channels, otherwise sets only the given channel */
3042 static HRESULT ca_setvol(ACImpl *This, UINT32 index)
3044 Float32 level;
3045 OSStatus sc;
3047 if(This->session->mute)
3048 level = 0.;
3049 else{
3050 if(index == (UINT32)-1){
3051 UINT32 i;
3052 level = 1.;
3053 for(i = 0; i < This->fmt->nChannels; ++i){
3054 Float32 tmp;
3055 tmp = This->session->master_vol *
3056 This->session->channel_vols[i] * This->vols[i];
3057 level = tmp < level ? tmp : level;
3059 }else
3060 level = This->session->master_vol *
3061 This->session->channel_vols[index] * This->vols[index];
3064 sc = AudioUnitSetParameter(This->unit, kHALOutputParam_Volume,
3065 kAudioUnitScope_Global, 0, level, 0);
3066 if(sc != noErr)
3067 WARN("Couldn't set volume: %x\n", (int)sc);
3069 return S_OK;
3072 static HRESULT ca_session_setvol(AudioSession *session, UINT32 index)
3074 HRESULT ret = S_OK;
3075 ACImpl *client;
3077 LIST_FOR_EACH_ENTRY(client, &session->clients, ACImpl, entry){
3078 HRESULT hr;
3079 hr = ca_setvol(client, index);
3080 if(FAILED(hr))
3081 ret = hr;
3084 return ret;
3087 static HRESULT WINAPI SimpleAudioVolume_QueryInterface(
3088 ISimpleAudioVolume *iface, REFIID riid, void **ppv)
3090 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
3092 if(!ppv)
3093 return E_POINTER;
3094 *ppv = NULL;
3096 if(IsEqualIID(riid, &IID_IUnknown) ||
3097 IsEqualIID(riid, &IID_ISimpleAudioVolume))
3098 *ppv = iface;
3099 if(*ppv){
3100 IUnknown_AddRef((IUnknown*)*ppv);
3101 return S_OK;
3104 WARN("Unknown interface %s\n", debugstr_guid(riid));
3105 return E_NOINTERFACE;
3108 static ULONG WINAPI SimpleAudioVolume_AddRef(ISimpleAudioVolume *iface)
3110 AudioSessionWrapper *This = impl_from_ISimpleAudioVolume(iface);
3111 return AudioSessionControl_AddRef(&This->IAudioSessionControl2_iface);
3114 static ULONG WINAPI SimpleAudioVolume_Release(ISimpleAudioVolume *iface)
3116 AudioSessionWrapper *This = impl_from_ISimpleAudioVolume(iface);
3117 return AudioSessionControl_Release(&This->IAudioSessionControl2_iface);
3120 static HRESULT WINAPI SimpleAudioVolume_SetMasterVolume(
3121 ISimpleAudioVolume *iface, float level, const GUID *context)
3123 AudioSessionWrapper *This = impl_from_ISimpleAudioVolume(iface);
3124 AudioSession *session = This->session;
3125 HRESULT ret;
3127 TRACE("(%p)->(%f, %s)\n", session, level, wine_dbgstr_guid(context));
3129 if(level < 0.f || level > 1.f)
3130 return E_INVALIDARG;
3132 if(context)
3133 FIXME("Notifications not supported yet\n");
3135 EnterCriticalSection(&session->lock);
3137 session->master_vol = level;
3139 ret = ca_session_setvol(session, -1);
3141 LeaveCriticalSection(&session->lock);
3143 return ret;
3146 static HRESULT WINAPI SimpleAudioVolume_GetMasterVolume(
3147 ISimpleAudioVolume *iface, float *level)
3149 AudioSessionWrapper *This = impl_from_ISimpleAudioVolume(iface);
3150 AudioSession *session = This->session;
3152 TRACE("(%p)->(%p)\n", session, level);
3154 if(!level)
3155 return NULL_PTR_ERR;
3157 *level = session->master_vol;
3159 return S_OK;
3162 static HRESULT WINAPI SimpleAudioVolume_SetMute(ISimpleAudioVolume *iface,
3163 BOOL mute, const GUID *context)
3165 AudioSessionWrapper *This = impl_from_ISimpleAudioVolume(iface);
3166 AudioSession *session = This->session;
3168 TRACE("(%p)->(%u, %s)\n", session, mute, debugstr_guid(context));
3170 if(context)
3171 FIXME("Notifications not supported yet\n");
3173 EnterCriticalSection(&session->lock);
3175 session->mute = mute;
3177 ca_session_setvol(session, -1);
3179 LeaveCriticalSection(&session->lock);
3181 return S_OK;
3184 static HRESULT WINAPI SimpleAudioVolume_GetMute(ISimpleAudioVolume *iface,
3185 BOOL *mute)
3187 AudioSessionWrapper *This = impl_from_ISimpleAudioVolume(iface);
3188 AudioSession *session = This->session;
3190 TRACE("(%p)->(%p)\n", session, mute);
3192 if(!mute)
3193 return NULL_PTR_ERR;
3195 *mute = session->mute;
3197 return S_OK;
3200 static const ISimpleAudioVolumeVtbl SimpleAudioVolume_Vtbl =
3202 SimpleAudioVolume_QueryInterface,
3203 SimpleAudioVolume_AddRef,
3204 SimpleAudioVolume_Release,
3205 SimpleAudioVolume_SetMasterVolume,
3206 SimpleAudioVolume_GetMasterVolume,
3207 SimpleAudioVolume_SetMute,
3208 SimpleAudioVolume_GetMute
3211 static HRESULT WINAPI AudioStreamVolume_QueryInterface(
3212 IAudioStreamVolume *iface, REFIID riid, void **ppv)
3214 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
3216 if(!ppv)
3217 return E_POINTER;
3218 *ppv = NULL;
3220 if(IsEqualIID(riid, &IID_IUnknown) ||
3221 IsEqualIID(riid, &IID_IAudioStreamVolume))
3222 *ppv = iface;
3223 if(*ppv){
3224 IUnknown_AddRef((IUnknown*)*ppv);
3225 return S_OK;
3228 WARN("Unknown interface %s\n", debugstr_guid(riid));
3229 return E_NOINTERFACE;
3232 static ULONG WINAPI AudioStreamVolume_AddRef(IAudioStreamVolume *iface)
3234 ACImpl *This = impl_from_IAudioStreamVolume(iface);
3235 return IAudioClient2_AddRef(&This->IAudioClient2_iface);
3238 static ULONG WINAPI AudioStreamVolume_Release(IAudioStreamVolume *iface)
3240 ACImpl *This = impl_from_IAudioStreamVolume(iface);
3241 return IAudioClient2_Release(&This->IAudioClient2_iface);
3244 static HRESULT WINAPI AudioStreamVolume_GetChannelCount(
3245 IAudioStreamVolume *iface, UINT32 *out)
3247 ACImpl *This = impl_from_IAudioStreamVolume(iface);
3249 TRACE("(%p)->(%p)\n", This, out);
3251 if(!out)
3252 return E_POINTER;
3254 *out = This->fmt->nChannels;
3256 return S_OK;
3259 static HRESULT WINAPI AudioStreamVolume_SetChannelVolume(
3260 IAudioStreamVolume *iface, UINT32 index, float level)
3262 ACImpl *This = impl_from_IAudioStreamVolume(iface);
3263 HRESULT ret;
3265 TRACE("(%p)->(%d, %f)\n", This, index, level);
3267 if(level < 0.f || level > 1.f)
3268 return E_INVALIDARG;
3270 if(index >= This->fmt->nChannels)
3271 return E_INVALIDARG;
3273 OSSpinLockLock(&This->lock);
3275 This->vols[index] = level;
3277 WARN("CoreAudio doesn't support per-channel volume control\n");
3278 ret = ca_setvol(This, index);
3280 OSSpinLockUnlock(&This->lock);
3282 return ret;
3285 static HRESULT WINAPI AudioStreamVolume_GetChannelVolume(
3286 IAudioStreamVolume *iface, UINT32 index, float *level)
3288 ACImpl *This = impl_from_IAudioStreamVolume(iface);
3290 TRACE("(%p)->(%d, %p)\n", This, index, level);
3292 if(!level)
3293 return E_POINTER;
3295 if(index >= This->fmt->nChannels)
3296 return E_INVALIDARG;
3298 *level = This->vols[index];
3300 return S_OK;
3303 static HRESULT WINAPI AudioStreamVolume_SetAllVolumes(
3304 IAudioStreamVolume *iface, UINT32 count, const float *levels)
3306 ACImpl *This = impl_from_IAudioStreamVolume(iface);
3307 int i;
3308 HRESULT ret;
3310 TRACE("(%p)->(%d, %p)\n", This, count, levels);
3312 if(!levels)
3313 return E_POINTER;
3315 if(count != This->fmt->nChannels)
3316 return E_INVALIDARG;
3318 OSSpinLockLock(&This->lock);
3320 for(i = 0; i < count; ++i)
3321 This->vols[i] = levels[i];
3323 ret = ca_setvol(This, -1);
3325 OSSpinLockUnlock(&This->lock);
3327 return ret;
3330 static HRESULT WINAPI AudioStreamVolume_GetAllVolumes(
3331 IAudioStreamVolume *iface, UINT32 count, float *levels)
3333 ACImpl *This = impl_from_IAudioStreamVolume(iface);
3334 int i;
3336 TRACE("(%p)->(%d, %p)\n", This, count, levels);
3338 if(!levels)
3339 return E_POINTER;
3341 if(count != This->fmt->nChannels)
3342 return E_INVALIDARG;
3344 OSSpinLockLock(&This->lock);
3346 for(i = 0; i < count; ++i)
3347 levels[i] = This->vols[i];
3349 OSSpinLockUnlock(&This->lock);
3351 return S_OK;
3354 static const IAudioStreamVolumeVtbl AudioStreamVolume_Vtbl =
3356 AudioStreamVolume_QueryInterface,
3357 AudioStreamVolume_AddRef,
3358 AudioStreamVolume_Release,
3359 AudioStreamVolume_GetChannelCount,
3360 AudioStreamVolume_SetChannelVolume,
3361 AudioStreamVolume_GetChannelVolume,
3362 AudioStreamVolume_SetAllVolumes,
3363 AudioStreamVolume_GetAllVolumes
3366 static HRESULT WINAPI ChannelAudioVolume_QueryInterface(
3367 IChannelAudioVolume *iface, REFIID riid, void **ppv)
3369 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
3371 if(!ppv)
3372 return E_POINTER;
3373 *ppv = NULL;
3375 if(IsEqualIID(riid, &IID_IUnknown) ||
3376 IsEqualIID(riid, &IID_IChannelAudioVolume))
3377 *ppv = iface;
3378 if(*ppv){
3379 IUnknown_AddRef((IUnknown*)*ppv);
3380 return S_OK;
3383 WARN("Unknown interface %s\n", debugstr_guid(riid));
3384 return E_NOINTERFACE;
3387 static ULONG WINAPI ChannelAudioVolume_AddRef(IChannelAudioVolume *iface)
3389 AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
3390 return AudioSessionControl_AddRef(&This->IAudioSessionControl2_iface);
3393 static ULONG WINAPI ChannelAudioVolume_Release(IChannelAudioVolume *iface)
3395 AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
3396 return AudioSessionControl_Release(&This->IAudioSessionControl2_iface);
3399 static HRESULT WINAPI ChannelAudioVolume_GetChannelCount(
3400 IChannelAudioVolume *iface, UINT32 *out)
3402 AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
3403 AudioSession *session = This->session;
3405 TRACE("(%p)->(%p)\n", session, out);
3407 if(!out)
3408 return NULL_PTR_ERR;
3410 *out = session->channel_count;
3412 return S_OK;
3415 static HRESULT WINAPI ChannelAudioVolume_SetChannelVolume(
3416 IChannelAudioVolume *iface, UINT32 index, float level,
3417 const GUID *context)
3419 AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
3420 AudioSession *session = This->session;
3421 HRESULT ret;
3423 TRACE("(%p)->(%d, %f, %s)\n", session, index, level,
3424 wine_dbgstr_guid(context));
3426 if(level < 0.f || level > 1.f)
3427 return E_INVALIDARG;
3429 if(index >= session->channel_count)
3430 return E_INVALIDARG;
3432 if(context)
3433 FIXME("Notifications not supported yet\n");
3435 EnterCriticalSection(&session->lock);
3437 session->channel_vols[index] = level;
3439 WARN("CoreAudio doesn't support per-channel volume control\n");
3440 ret = ca_session_setvol(session, index);
3442 LeaveCriticalSection(&session->lock);
3444 return ret;
3447 static HRESULT WINAPI ChannelAudioVolume_GetChannelVolume(
3448 IChannelAudioVolume *iface, UINT32 index, float *level)
3450 AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
3451 AudioSession *session = This->session;
3453 TRACE("(%p)->(%d, %p)\n", session, index, level);
3455 if(!level)
3456 return NULL_PTR_ERR;
3458 if(index >= session->channel_count)
3459 return E_INVALIDARG;
3461 *level = session->channel_vols[index];
3463 return S_OK;
3466 static HRESULT WINAPI ChannelAudioVolume_SetAllVolumes(
3467 IChannelAudioVolume *iface, UINT32 count, const float *levels,
3468 const GUID *context)
3470 AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
3471 AudioSession *session = This->session;
3472 int i;
3473 HRESULT ret;
3475 TRACE("(%p)->(%d, %p, %s)\n", session, count, levels,
3476 wine_dbgstr_guid(context));
3478 if(!levels)
3479 return NULL_PTR_ERR;
3481 if(count != session->channel_count)
3482 return E_INVALIDARG;
3484 if(context)
3485 FIXME("Notifications not supported yet\n");
3487 EnterCriticalSection(&session->lock);
3489 for(i = 0; i < count; ++i)
3490 session->channel_vols[i] = levels[i];
3492 ret = ca_session_setvol(session, -1);
3494 LeaveCriticalSection(&session->lock);
3496 return ret;
3499 static HRESULT WINAPI ChannelAudioVolume_GetAllVolumes(
3500 IChannelAudioVolume *iface, UINT32 count, float *levels)
3502 AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
3503 AudioSession *session = This->session;
3504 int i;
3506 TRACE("(%p)->(%d, %p)\n", session, count, levels);
3508 if(!levels)
3509 return NULL_PTR_ERR;
3511 if(count != session->channel_count)
3512 return E_INVALIDARG;
3514 for(i = 0; i < count; ++i)
3515 levels[i] = session->channel_vols[i];
3517 return S_OK;
3520 static const IChannelAudioVolumeVtbl ChannelAudioVolume_Vtbl =
3522 ChannelAudioVolume_QueryInterface,
3523 ChannelAudioVolume_AddRef,
3524 ChannelAudioVolume_Release,
3525 ChannelAudioVolume_GetChannelCount,
3526 ChannelAudioVolume_SetChannelVolume,
3527 ChannelAudioVolume_GetChannelVolume,
3528 ChannelAudioVolume_SetAllVolumes,
3529 ChannelAudioVolume_GetAllVolumes
3532 static HRESULT WINAPI AudioSessionManager_QueryInterface(IAudioSessionManager2 *iface,
3533 REFIID riid, void **ppv)
3535 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
3537 if(!ppv)
3538 return E_POINTER;
3539 *ppv = NULL;
3541 if(IsEqualIID(riid, &IID_IUnknown) ||
3542 IsEqualIID(riid, &IID_IAudioSessionManager) ||
3543 IsEqualIID(riid, &IID_IAudioSessionManager2))
3544 *ppv = iface;
3545 if(*ppv){
3546 IUnknown_AddRef((IUnknown*)*ppv);
3547 return S_OK;
3550 WARN("Unknown interface %s\n", debugstr_guid(riid));
3551 return E_NOINTERFACE;
3554 static ULONG WINAPI AudioSessionManager_AddRef(IAudioSessionManager2 *iface)
3556 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
3557 ULONG ref;
3558 ref = InterlockedIncrement(&This->ref);
3559 TRACE("(%p) Refcount now %u\n", This, ref);
3560 return ref;
3563 static ULONG WINAPI AudioSessionManager_Release(IAudioSessionManager2 *iface)
3565 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
3566 ULONG ref;
3567 ref = InterlockedDecrement(&This->ref);
3568 TRACE("(%p) Refcount now %u\n", This, ref);
3569 if(!ref)
3570 HeapFree(GetProcessHeap(), 0, This);
3571 return ref;
3574 static HRESULT WINAPI AudioSessionManager_GetAudioSessionControl(
3575 IAudioSessionManager2 *iface, const GUID *session_guid, DWORD flags,
3576 IAudioSessionControl **out)
3578 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
3579 AudioSession *session;
3580 AudioSessionWrapper *wrapper;
3581 HRESULT hr;
3583 TRACE("(%p)->(%s, %x, %p)\n", This, debugstr_guid(session_guid),
3584 flags, out);
3586 hr = get_audio_session(session_guid, This->device, 0, &session);
3587 if(FAILED(hr))
3588 return hr;
3590 wrapper = AudioSessionWrapper_Create(NULL);
3591 if(!wrapper)
3592 return E_OUTOFMEMORY;
3594 wrapper->session = session;
3596 *out = (IAudioSessionControl*)&wrapper->IAudioSessionControl2_iface;
3598 return S_OK;
3601 static HRESULT WINAPI AudioSessionManager_GetSimpleAudioVolume(
3602 IAudioSessionManager2 *iface, const GUID *session_guid, DWORD flags,
3603 ISimpleAudioVolume **out)
3605 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
3606 AudioSession *session;
3607 AudioSessionWrapper *wrapper;
3608 HRESULT hr;
3610 TRACE("(%p)->(%s, %x, %p)\n", This, debugstr_guid(session_guid),
3611 flags, out);
3613 hr = get_audio_session(session_guid, This->device, 0, &session);
3614 if(FAILED(hr))
3615 return hr;
3617 wrapper = AudioSessionWrapper_Create(NULL);
3618 if(!wrapper)
3619 return E_OUTOFMEMORY;
3621 wrapper->session = session;
3623 *out = &wrapper->ISimpleAudioVolume_iface;
3625 return S_OK;
3628 static HRESULT WINAPI AudioSessionManager_GetSessionEnumerator(
3629 IAudioSessionManager2 *iface, IAudioSessionEnumerator **out)
3631 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
3632 FIXME("(%p)->(%p) - stub\n", This, out);
3633 return E_NOTIMPL;
3636 static HRESULT WINAPI AudioSessionManager_RegisterSessionNotification(
3637 IAudioSessionManager2 *iface, IAudioSessionNotification *notification)
3639 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
3640 FIXME("(%p)->(%p) - stub\n", This, notification);
3641 return E_NOTIMPL;
3644 static HRESULT WINAPI AudioSessionManager_UnregisterSessionNotification(
3645 IAudioSessionManager2 *iface, IAudioSessionNotification *notification)
3647 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
3648 FIXME("(%p)->(%p) - stub\n", This, notification);
3649 return E_NOTIMPL;
3652 static HRESULT WINAPI AudioSessionManager_RegisterDuckNotification(
3653 IAudioSessionManager2 *iface, const WCHAR *session_id,
3654 IAudioVolumeDuckNotification *notification)
3656 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
3657 FIXME("(%p)->(%p) - stub\n", This, notification);
3658 return E_NOTIMPL;
3661 static HRESULT WINAPI AudioSessionManager_UnregisterDuckNotification(
3662 IAudioSessionManager2 *iface,
3663 IAudioVolumeDuckNotification *notification)
3665 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
3666 FIXME("(%p)->(%p) - stub\n", This, notification);
3667 return E_NOTIMPL;
3670 static const IAudioSessionManager2Vtbl AudioSessionManager2_Vtbl =
3672 AudioSessionManager_QueryInterface,
3673 AudioSessionManager_AddRef,
3674 AudioSessionManager_Release,
3675 AudioSessionManager_GetAudioSessionControl,
3676 AudioSessionManager_GetSimpleAudioVolume,
3677 AudioSessionManager_GetSessionEnumerator,
3678 AudioSessionManager_RegisterSessionNotification,
3679 AudioSessionManager_UnregisterSessionNotification,
3680 AudioSessionManager_RegisterDuckNotification,
3681 AudioSessionManager_UnregisterDuckNotification
3684 HRESULT WINAPI AUDDRV_GetAudioSessionManager(IMMDevice *device,
3685 IAudioSessionManager2 **out)
3687 SessionMgr *This;
3689 This = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(SessionMgr));
3690 if(!This)
3691 return E_OUTOFMEMORY;
3693 This->IAudioSessionManager2_iface.lpVtbl = &AudioSessionManager2_Vtbl;
3694 This->device = device;
3695 This->ref = 1;
3697 *out = &This->IAudioSessionManager2_iface;
3699 return S_OK;