winealsa.drv: Request ALSA period time to match MMDevAPI period time.
[wine/multimedia.git] / dlls / winealsa.drv / mmdevdrv.c
blobe79a7b62b6caa677361e8793b196561678e6e714
1 /*
2 * Copyright 2010 Maarten Lankhorst for CodeWeavers
3 * Copyright 2011 Andrew Eikum for CodeWeavers
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20 #define NONAMELESSUNION
21 #define COBJMACROS
22 #include "config.h"
24 #include <stdarg.h>
25 #include <math.h>
27 #include "windef.h"
28 #include "winbase.h"
29 #include "winnls.h"
30 #include "winreg.h"
31 #include "wine/debug.h"
32 #include "wine/unicode.h"
33 #include "wine/list.h"
35 #include "ole2.h"
36 #include "mmdeviceapi.h"
37 #include "devpkey.h"
38 #include "dshow.h"
39 #include "dsound.h"
41 #include "initguid.h"
42 #include "endpointvolume.h"
43 #include "audioclient.h"
44 #include "audiopolicy.h"
46 #include <alsa/asoundlib.h>
48 WINE_DEFAULT_DEBUG_CHANNEL(alsa);
49 WINE_DECLARE_DEBUG_CHANNEL(winediag);
51 #define NULL_PTR_ERR MAKE_HRESULT(SEVERITY_ERROR, FACILITY_WIN32, RPC_X_NULL_REF_POINTER)
53 static const REFERENCE_TIME DefaultPeriod = 100000;
54 static const REFERENCE_TIME MinimumPeriod = 50000;
56 struct ACImpl;
57 typedef struct ACImpl ACImpl;
59 typedef struct _AudioSession {
60 GUID guid;
61 struct list clients;
63 IMMDevice *device;
65 float master_vol;
66 UINT32 channel_count;
67 float *channel_vols;
68 BOOL mute;
70 CRITICAL_SECTION lock;
72 struct list entry;
73 } AudioSession;
75 typedef struct _AudioSessionWrapper {
76 IAudioSessionControl2 IAudioSessionControl2_iface;
77 IChannelAudioVolume IChannelAudioVolume_iface;
78 ISimpleAudioVolume ISimpleAudioVolume_iface;
80 LONG ref;
82 ACImpl *client;
83 AudioSession *session;
84 } AudioSessionWrapper;
86 struct ACImpl {
87 IAudioClient IAudioClient_iface;
88 IAudioRenderClient IAudioRenderClient_iface;
89 IAudioCaptureClient IAudioCaptureClient_iface;
90 IAudioClock IAudioClock_iface;
91 IAudioClock2 IAudioClock2_iface;
92 IAudioStreamVolume IAudioStreamVolume_iface;
94 LONG ref;
96 snd_pcm_t *pcm_handle;
97 snd_pcm_uframes_t alsa_bufsize_frames, alsa_period_frames;
98 snd_pcm_hw_params_t *hw_params; /* does not hold state between calls */
99 snd_pcm_format_t alsa_format;
101 IMMDevice *parent;
103 EDataFlow dataflow;
104 WAVEFORMATEX *fmt;
105 DWORD flags;
106 AUDCLNT_SHAREMODE share;
107 HANDLE event;
108 float *vols;
110 BOOL initted, started;
111 REFERENCE_TIME mmdev_period_rt;
112 UINT64 written_frames, last_pos_frames;
113 UINT32 bufsize_frames, held_frames, tmp_buffer_frames, mmdev_period_frames;
114 UINT32 lcl_offs_frames; /* offs into local_buffer where valid data starts */
116 HANDLE timer;
117 BYTE *local_buffer, *tmp_buffer;
118 int buf_state;
120 CRITICAL_SECTION lock;
122 AudioSession *session;
123 AudioSessionWrapper *session_wrapper;
125 struct list entry;
128 enum BufferStates {
129 NOT_LOCKED = 0,
130 LOCKED_NORMAL, /* public buffer piece is from local_buffer */
131 LOCKED_WRAPPED /* public buffer piece is wrapped around, in tmp_buffer */
134 typedef struct _SessionMgr {
135 IAudioSessionManager2 IAudioSessionManager2_iface;
137 LONG ref;
139 IMMDevice *device;
140 } SessionMgr;
142 static HANDLE g_timer_q;
144 static CRITICAL_SECTION g_sessions_lock;
145 static CRITICAL_SECTION_DEBUG g_sessions_lock_debug =
147 0, 0, &g_sessions_lock,
148 { &g_sessions_lock_debug.ProcessLocksList, &g_sessions_lock_debug.ProcessLocksList },
149 0, 0, { (DWORD_PTR)(__FILE__ ": g_sessions_lock") }
151 static CRITICAL_SECTION g_sessions_lock = { &g_sessions_lock_debug, -1, 0, 0, 0, 0 };
152 static struct list g_sessions = LIST_INIT(g_sessions);
154 static const WCHAR defaultW[] = {'d','e','f','a','u','l','t',0};
155 static const char defname[] = "default";
157 static const IAudioClientVtbl AudioClient_Vtbl;
158 static const IAudioRenderClientVtbl AudioRenderClient_Vtbl;
159 static const IAudioCaptureClientVtbl AudioCaptureClient_Vtbl;
160 static const IAudioSessionControl2Vtbl AudioSessionControl2_Vtbl;
161 static const ISimpleAudioVolumeVtbl SimpleAudioVolume_Vtbl;
162 static const IAudioClockVtbl AudioClock_Vtbl;
163 static const IAudioClock2Vtbl AudioClock2_Vtbl;
164 static const IAudioStreamVolumeVtbl AudioStreamVolume_Vtbl;
165 static const IChannelAudioVolumeVtbl ChannelAudioVolume_Vtbl;
166 static const IAudioSessionManager2Vtbl AudioSessionManager2_Vtbl;
168 static AudioSessionWrapper *AudioSessionWrapper_Create(ACImpl *client);
170 static inline ACImpl *impl_from_IAudioClient(IAudioClient *iface)
172 return CONTAINING_RECORD(iface, ACImpl, IAudioClient_iface);
175 static inline ACImpl *impl_from_IAudioRenderClient(IAudioRenderClient *iface)
177 return CONTAINING_RECORD(iface, ACImpl, IAudioRenderClient_iface);
180 static inline ACImpl *impl_from_IAudioCaptureClient(IAudioCaptureClient *iface)
182 return CONTAINING_RECORD(iface, ACImpl, IAudioCaptureClient_iface);
185 static inline AudioSessionWrapper *impl_from_IAudioSessionControl2(IAudioSessionControl2 *iface)
187 return CONTAINING_RECORD(iface, AudioSessionWrapper, IAudioSessionControl2_iface);
190 static inline AudioSessionWrapper *impl_from_ISimpleAudioVolume(ISimpleAudioVolume *iface)
192 return CONTAINING_RECORD(iface, AudioSessionWrapper, ISimpleAudioVolume_iface);
195 static inline AudioSessionWrapper *impl_from_IChannelAudioVolume(IChannelAudioVolume *iface)
197 return CONTAINING_RECORD(iface, AudioSessionWrapper, IChannelAudioVolume_iface);
200 static inline ACImpl *impl_from_IAudioClock(IAudioClock *iface)
202 return CONTAINING_RECORD(iface, ACImpl, IAudioClock_iface);
205 static inline ACImpl *impl_from_IAudioClock2(IAudioClock2 *iface)
207 return CONTAINING_RECORD(iface, ACImpl, IAudioClock2_iface);
210 static inline ACImpl *impl_from_IAudioStreamVolume(IAudioStreamVolume *iface)
212 return CONTAINING_RECORD(iface, ACImpl, IAudioStreamVolume_iface);
215 static inline SessionMgr *impl_from_IAudioSessionManager2(IAudioSessionManager2 *iface)
217 return CONTAINING_RECORD(iface, SessionMgr, IAudioSessionManager2_iface);
220 BOOL WINAPI DllMain(HINSTANCE dll, DWORD reason, void *reserved)
222 switch (reason)
224 case DLL_PROCESS_ATTACH:
225 g_timer_q = CreateTimerQueue();
226 if(!g_timer_q)
227 return FALSE;
228 break;
230 case DLL_PROCESS_DETACH:
231 DeleteCriticalSection(&g_sessions_lock);
232 break;
234 return TRUE;
237 /* From <dlls/mmdevapi/mmdevapi.h> */
238 enum DriverPriority {
239 Priority_Unavailable = 0,
240 Priority_Low,
241 Priority_Neutral,
242 Priority_Preferred
245 int WINAPI AUDDRV_GetPriority(void)
247 return Priority_Neutral;
250 static BOOL alsa_try_open(const char *devnode, snd_pcm_stream_t stream)
252 snd_pcm_t *handle;
253 int err;
255 if((err = snd_pcm_open(&handle, devnode, stream, SND_PCM_NONBLOCK)) < 0){
256 WARN("The device \"%s\" failed to open: %d (%s).\n",
257 devnode, err, snd_strerror(err));
258 return FALSE;
261 snd_pcm_close(handle);
262 return TRUE;
265 static HRESULT alsa_get_card_devices(snd_pcm_stream_t stream, WCHAR **ids, char **keys,
266 UINT *num, snd_ctl_t *ctl, int card, const WCHAR *cardnameW)
268 static const WCHAR dashW[] = {' ','-',' ',0};
269 int err, device;
270 snd_pcm_info_t *info;
272 info = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, snd_pcm_info_sizeof());
273 if(!info)
274 return E_OUTOFMEMORY;
276 snd_pcm_info_set_subdevice(info, 0);
277 snd_pcm_info_set_stream(info, stream);
279 device = -1;
280 for(err = snd_ctl_pcm_next_device(ctl, &device); device != -1 && err >= 0;
281 err = snd_ctl_pcm_next_device(ctl, &device)){
282 const char *devname;
283 char devnode[32];
285 snd_pcm_info_set_device(info, device);
287 if((err = snd_ctl_pcm_info(ctl, info)) < 0){
288 if(err == -ENOENT)
289 /* This device doesn't have the right stream direction */
290 continue;
292 WARN("Failed to get info for card %d, device %d: %d (%s)\n",
293 card, device, err, snd_strerror(err));
294 continue;
297 sprintf(devnode, "plughw:%d,%d", card, device);
298 if(!alsa_try_open(devnode, stream))
299 continue;
301 if(ids && keys){
302 DWORD len, cardlen;
304 devname = snd_pcm_info_get_name(info);
305 if(!devname){
306 WARN("Unable to get device name for card %d, device %d\n", card,
307 device);
308 continue;
311 cardlen = lstrlenW(cardnameW);
312 len = MultiByteToWideChar(CP_UNIXCP, 0, devname, -1, NULL, 0);
313 len += lstrlenW(dashW);
314 len += cardlen;
315 ids[*num] = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
316 if(!ids[*num]){
317 HeapFree(GetProcessHeap(), 0, info);
318 return E_OUTOFMEMORY;
320 memcpy(ids[*num], cardnameW, cardlen * sizeof(WCHAR));
321 memcpy(ids[*num] + cardlen, dashW, lstrlenW(dashW) * sizeof(WCHAR));
322 cardlen += lstrlenW(dashW);
323 MultiByteToWideChar(CP_UNIXCP, 0, devname, -1, ids[*num] + cardlen,
324 len - cardlen);
326 keys[*num] = HeapAlloc(GetProcessHeap(), 0, 32);
327 if(!keys[*num]){
328 HeapFree(GetProcessHeap(), 0, info);
329 HeapFree(GetProcessHeap(), 0, ids[*num]);
330 return E_OUTOFMEMORY;
332 memcpy(keys[*num], devnode, sizeof(devnode));
335 ++(*num);
338 HeapFree(GetProcessHeap(), 0, info);
340 if(err != 0)
341 WARN("Got a failure during device enumeration on card %d: %d (%s)\n",
342 card, err, snd_strerror(err));
344 return S_OK;
347 static HRESULT alsa_enum_devices(EDataFlow flow, WCHAR **ids, char **keys,
348 UINT *num)
350 snd_pcm_stream_t stream = (flow == eRender ? SND_PCM_STREAM_PLAYBACK :
351 SND_PCM_STREAM_CAPTURE);
352 int err, card;
354 card = -1;
355 *num = 0;
357 if(alsa_try_open(defname, stream)){
358 if(ids && keys){
359 *ids = HeapAlloc(GetProcessHeap(), 0, sizeof(defaultW));
360 memcpy(*ids, defaultW, sizeof(defaultW));
361 *keys = HeapAlloc(GetProcessHeap(), 0, sizeof(defname));
362 memcpy(*keys, defname, sizeof(defname));
364 ++*num;
367 for(err = snd_card_next(&card); card != -1 && err >= 0;
368 err = snd_card_next(&card)){
369 char cardpath[64];
370 const char *cardname;
371 WCHAR *cardnameW;
372 snd_ctl_t *ctl;
373 DWORD len;
375 sprintf(cardpath, "hw:%u", card);
377 if((err = snd_ctl_open(&ctl, cardpath, 0)) < 0){
378 WARN("Unable to open ctl for ALSA device %s: %d (%s)\n", cardpath,
379 err, snd_strerror(err));
380 continue;
383 if((err = snd_card_get_name(card, (char **)&cardname)) < 0){
384 WARN("Unable to get card name for ALSA device %s: %d (%s)\n",
385 cardpath, err, snd_strerror(err));
386 /* FIXME: Should be localized */
387 cardname = "Unknown soundcard";
390 len = MultiByteToWideChar(CP_UNIXCP, 0, cardname, -1, NULL, 0);
391 cardnameW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
392 if(!cardnameW){
393 snd_ctl_close(ctl);
394 return E_OUTOFMEMORY;
396 MultiByteToWideChar(CP_UNIXCP, 0, cardname, -1, cardnameW, len);
398 alsa_get_card_devices(stream, ids, keys, num, ctl, card, cardnameW);
400 HeapFree(GetProcessHeap(), 0, cardnameW);
402 snd_ctl_close(ctl);
405 if(err != 0)
406 WARN("Got a failure during card enumeration: %d (%s)\n",
407 err, snd_strerror(err));
409 return S_OK;
412 HRESULT WINAPI AUDDRV_GetEndpointIDs(EDataFlow flow, WCHAR ***ids, char ***keys,
413 UINT *num, UINT *def_index)
415 HRESULT hr;
417 TRACE("%d %p %p %p %p\n", flow, ids, keys, num, def_index);
419 hr = alsa_enum_devices(flow, NULL, NULL, num);
420 if(FAILED(hr))
421 return hr;
423 if(*num == 0)
425 *ids = NULL;
426 *keys = NULL;
427 return S_OK;
430 *ids = HeapAlloc(GetProcessHeap(), 0, *num * sizeof(WCHAR *));
431 *keys = HeapAlloc(GetProcessHeap(), 0, *num * sizeof(char *));
432 if(!*ids || !*keys){
433 HeapFree(GetProcessHeap(), 0, *ids);
434 HeapFree(GetProcessHeap(), 0, *keys);
435 return E_OUTOFMEMORY;
438 *def_index = 0;
440 hr = alsa_enum_devices(flow, *ids, *keys, num);
441 if(FAILED(hr)){
442 int i;
443 for(i = 0; i < *num; ++i){
444 HeapFree(GetProcessHeap(), 0, (*ids)[i]);
445 HeapFree(GetProcessHeap(), 0, (*keys)[i]);
447 HeapFree(GetProcessHeap(), 0, *ids);
448 HeapFree(GetProcessHeap(), 0, *keys);
449 return E_OUTOFMEMORY;
452 return S_OK;
455 /* Using the pulse PCM device from alsa-plugins 1.0.24 triggers a bug
456 * which causes audio to cease playing after a few minutes of playback.
457 * Setting handle_underrun=1 on pulse-backed ALSA devices seems to work
458 * around this issue. */
459 static snd_config_t *make_handle_underrun_config(const char *name)
461 snd_config_t *lconf, *dev_node, *hu_node, *type_node;
462 char dev_node_name[64];
463 const char *type_str;
464 int err;
466 snd_config_update();
468 if((err = snd_config_copy(&lconf, snd_config)) < 0){
469 WARN("snd_config_copy failed: %d (%s)\n", err, snd_strerror(err));
470 return NULL;
473 sprintf(dev_node_name, "pcm.%s", name);
474 err = snd_config_search(lconf, dev_node_name, &dev_node);
475 if(err == -ENOENT){
476 snd_config_delete(lconf);
477 return NULL;
479 if(err < 0){
480 snd_config_delete(lconf);
481 WARN("snd_config_search failed: %d (%s)\n", err, snd_strerror(err));
482 return NULL;
485 /* ALSA is extremely fragile. If it runs into a config setting it doesn't
486 * recognize, it tends to fail or assert. So we only want to inject
487 * handle_underrun=1 on devices that we know will recognize it. */
488 err = snd_config_search(dev_node, "type", &type_node);
489 if(err == -ENOENT){
490 snd_config_delete(lconf);
491 return NULL;
493 if(err < 0){
494 snd_config_delete(lconf);
495 WARN("snd_config_search failed: %d (%s)\n", err, snd_strerror(err));
496 return NULL;
499 if((err = snd_config_get_string(type_node, &type_str)) < 0){
500 snd_config_delete(lconf);
501 return NULL;
504 if(strcmp(type_str, "pulse") != 0){
505 snd_config_delete(lconf);
506 return NULL;
509 err = snd_config_search(dev_node, "handle_underrun", &hu_node);
510 if(err >= 0){
511 /* user already has an explicit handle_underrun setting, so don't
512 * use a local config */
513 snd_config_delete(lconf);
514 return NULL;
516 if(err != -ENOENT){
517 snd_config_delete(lconf);
518 WARN("snd_config_search failed: %d (%s)\n", err, snd_strerror(err));
519 return NULL;
522 if((err = snd_config_imake_integer(&hu_node, "handle_underrun", 1)) < 0){
523 snd_config_delete(lconf);
524 WARN("snd_config_imake_integer failed: %d (%s)\n", err,
525 snd_strerror(err));
526 return NULL;
529 if((err = snd_config_add(dev_node, hu_node)) < 0){
530 snd_config_delete(lconf);
531 WARN("snd_config_add failed: %d (%s)\n", err, snd_strerror(err));
532 return NULL;
535 return lconf;
538 HRESULT WINAPI AUDDRV_GetAudioEndpoint(const char *key, IMMDevice *dev,
539 EDataFlow dataflow, IAudioClient **out)
541 ACImpl *This;
542 int err;
543 snd_pcm_stream_t stream;
544 snd_config_t *lconf;
545 static int handle_underrun = 1;
547 TRACE("\"%s\" %p %d %p\n", key, dev, dataflow, out);
549 This = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(ACImpl));
550 if(!This)
551 return E_OUTOFMEMORY;
553 This->IAudioClient_iface.lpVtbl = &AudioClient_Vtbl;
554 This->IAudioRenderClient_iface.lpVtbl = &AudioRenderClient_Vtbl;
555 This->IAudioCaptureClient_iface.lpVtbl = &AudioCaptureClient_Vtbl;
556 This->IAudioClock_iface.lpVtbl = &AudioClock_Vtbl;
557 This->IAudioClock2_iface.lpVtbl = &AudioClock2_Vtbl;
558 This->IAudioStreamVolume_iface.lpVtbl = &AudioStreamVolume_Vtbl;
560 if(dataflow == eRender)
561 stream = SND_PCM_STREAM_PLAYBACK;
562 else if(dataflow == eCapture)
563 stream = SND_PCM_STREAM_CAPTURE;
564 else{
565 HeapFree(GetProcessHeap(), 0, This);
566 return E_UNEXPECTED;
569 This->dataflow = dataflow;
570 if(handle_underrun && ((lconf = make_handle_underrun_config(key)))){
571 err = snd_pcm_open_lconf(&This->pcm_handle, key, stream, SND_PCM_NONBLOCK, lconf);
572 TRACE("Opening PCM device \"%s\" with handle_underrun: %d\n", key, err);
573 snd_config_delete(lconf);
574 /* Pulse <= 2010 returns EINVAL, it does not know handle_underrun. */
575 if(err == -EINVAL){
576 ERR_(winediag)("PulseAudio \"%s\" %d without handle_underrun. Audio may hang."
577 " Please upgrade to alsa_plugins >= 1.0.24\n", key, err);
578 handle_underrun = 0;
580 }else
581 err = -EINVAL;
582 if(err == -EINVAL){
583 err = snd_pcm_open(&This->pcm_handle, key, stream, SND_PCM_NONBLOCK);
585 if(err < 0){
586 HeapFree(GetProcessHeap(), 0, This);
587 WARN("Unable to open PCM \"%s\": %d (%s)\n", key, err, snd_strerror(err));
588 return E_FAIL;
591 This->hw_params = HeapAlloc(GetProcessHeap(), 0,
592 snd_pcm_hw_params_sizeof());
593 if(!This->hw_params){
594 snd_pcm_close(This->pcm_handle);
595 HeapFree(GetProcessHeap(), 0, This);
596 return E_OUTOFMEMORY;
599 InitializeCriticalSection(&This->lock);
600 This->lock.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": ACImpl.lock");
602 This->parent = dev;
603 IMMDevice_AddRef(This->parent);
605 *out = &This->IAudioClient_iface;
606 IAudioClient_AddRef(&This->IAudioClient_iface);
608 return S_OK;
611 static HRESULT WINAPI AudioClient_QueryInterface(IAudioClient *iface,
612 REFIID riid, void **ppv)
614 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
616 if(!ppv)
617 return E_POINTER;
618 *ppv = NULL;
619 if(IsEqualIID(riid, &IID_IUnknown) || IsEqualIID(riid, &IID_IAudioClient))
620 *ppv = iface;
621 if(*ppv){
622 IUnknown_AddRef((IUnknown*)*ppv);
623 return S_OK;
625 WARN("Unknown interface %s\n", debugstr_guid(riid));
626 return E_NOINTERFACE;
629 static ULONG WINAPI AudioClient_AddRef(IAudioClient *iface)
631 ACImpl *This = impl_from_IAudioClient(iface);
632 ULONG ref;
633 ref = InterlockedIncrement(&This->ref);
634 TRACE("(%p) Refcount now %u\n", This, ref);
635 return ref;
638 static ULONG WINAPI AudioClient_Release(IAudioClient *iface)
640 ACImpl *This = impl_from_IAudioClient(iface);
641 ULONG ref;
642 ref = InterlockedDecrement(&This->ref);
643 TRACE("(%p) Refcount now %u\n", This, ref);
644 if(!ref){
645 IAudioClient_Stop(iface);
646 IMMDevice_Release(This->parent);
647 This->lock.DebugInfo->Spare[0] = 0;
648 DeleteCriticalSection(&This->lock);
649 snd_pcm_drop(This->pcm_handle);
650 snd_pcm_close(This->pcm_handle);
651 if(This->initted){
652 EnterCriticalSection(&g_sessions_lock);
653 list_remove(&This->entry);
654 LeaveCriticalSection(&g_sessions_lock);
656 HeapFree(GetProcessHeap(), 0, This->vols);
657 HeapFree(GetProcessHeap(), 0, This->local_buffer);
658 HeapFree(GetProcessHeap(), 0, This->tmp_buffer);
659 HeapFree(GetProcessHeap(), 0, This->hw_params);
660 CoTaskMemFree(This->fmt);
661 HeapFree(GetProcessHeap(), 0, This);
663 return ref;
666 static void dump_fmt(const WAVEFORMATEX *fmt)
668 TRACE("wFormatTag: 0x%x (", fmt->wFormatTag);
669 switch(fmt->wFormatTag){
670 case WAVE_FORMAT_PCM:
671 TRACE("WAVE_FORMAT_PCM");
672 break;
673 case WAVE_FORMAT_IEEE_FLOAT:
674 TRACE("WAVE_FORMAT_IEEE_FLOAT");
675 break;
676 case WAVE_FORMAT_EXTENSIBLE:
677 TRACE("WAVE_FORMAT_EXTENSIBLE");
678 break;
679 default:
680 TRACE("Unknown");
681 break;
683 TRACE(")\n");
685 TRACE("nChannels: %u\n", fmt->nChannels);
686 TRACE("nSamplesPerSec: %u\n", fmt->nSamplesPerSec);
687 TRACE("nAvgBytesPerSec: %u\n", fmt->nAvgBytesPerSec);
688 TRACE("nBlockAlign: %u\n", fmt->nBlockAlign);
689 TRACE("wBitsPerSample: %u\n", fmt->wBitsPerSample);
690 TRACE("cbSize: %u\n", fmt->cbSize);
692 if(fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE){
693 WAVEFORMATEXTENSIBLE *fmtex = (void*)fmt;
694 TRACE("dwChannelMask: %08x\n", fmtex->dwChannelMask);
695 TRACE("Samples: %04x\n", fmtex->Samples.wReserved);
696 TRACE("SubFormat: %s\n", wine_dbgstr_guid(&fmtex->SubFormat));
700 static WAVEFORMATEX *clone_format(const WAVEFORMATEX *fmt)
702 WAVEFORMATEX *ret;
703 size_t size;
705 if(fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE)
706 size = sizeof(WAVEFORMATEXTENSIBLE);
707 else
708 size = sizeof(WAVEFORMATEX);
710 ret = CoTaskMemAlloc(size);
711 if(!ret)
712 return NULL;
714 memcpy(ret, fmt, size);
716 ret->cbSize = size - sizeof(WAVEFORMATEX);
718 return ret;
721 static void session_init_vols(AudioSession *session, UINT channels)
723 if(session->channel_count < channels){
724 UINT i;
726 if(session->channel_vols)
727 session->channel_vols = HeapReAlloc(GetProcessHeap(), 0,
728 session->channel_vols, sizeof(float) * channels);
729 else
730 session->channel_vols = HeapAlloc(GetProcessHeap(), 0,
731 sizeof(float) * channels);
732 if(!session->channel_vols)
733 return;
735 for(i = session->channel_count; i < channels; ++i)
736 session->channel_vols[i] = 1.f;
738 session->channel_count = channels;
742 static AudioSession *create_session(const GUID *guid, IMMDevice *device,
743 UINT num_channels)
745 AudioSession *ret;
747 ret = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(AudioSession));
748 if(!ret)
749 return NULL;
751 memcpy(&ret->guid, guid, sizeof(GUID));
753 ret->device = device;
755 list_init(&ret->clients);
757 list_add_head(&g_sessions, &ret->entry);
759 InitializeCriticalSection(&ret->lock);
760 ret->lock.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": AudioSession.lock");
762 session_init_vols(ret, num_channels);
764 ret->master_vol = 1.f;
766 return ret;
769 /* if channels == 0, then this will return or create a session with
770 * matching dataflow and GUID. otherwise, channels must also match */
771 static HRESULT get_audio_session(const GUID *sessionguid,
772 IMMDevice *device, UINT channels, AudioSession **out)
774 AudioSession *session;
776 if(!sessionguid || IsEqualGUID(sessionguid, &GUID_NULL)){
777 *out = create_session(&GUID_NULL, device, channels);
778 if(!*out)
779 return E_OUTOFMEMORY;
781 return S_OK;
784 *out = NULL;
785 LIST_FOR_EACH_ENTRY(session, &g_sessions, AudioSession, entry){
786 if(session->device == device &&
787 IsEqualGUID(sessionguid, &session->guid)){
788 session_init_vols(session, channels);
789 *out = session;
790 break;
794 if(!*out){
795 *out = create_session(sessionguid, device, channels);
796 if(!*out)
797 return E_OUTOFMEMORY;
800 return S_OK;
803 static HRESULT WINAPI AudioClient_Initialize(IAudioClient *iface,
804 AUDCLNT_SHAREMODE mode, DWORD flags, REFERENCE_TIME duration,
805 REFERENCE_TIME period, const WAVEFORMATEX *fmt,
806 const GUID *sessionguid)
808 ACImpl *This = impl_from_IAudioClient(iface);
809 snd_pcm_sw_params_t *sw_params = NULL;
810 snd_pcm_format_t format;
811 const WAVEFORMATEXTENSIBLE *fmtex = (const WAVEFORMATEXTENSIBLE *)fmt;
812 unsigned int rate, alsa_period_us;
813 int err, i;
814 HRESULT hr = S_OK;
816 TRACE("(%p)->(%x, %x, %s, %s, %p, %s)\n", This, mode, flags,
817 wine_dbgstr_longlong(duration), wine_dbgstr_longlong(period), fmt, debugstr_guid(sessionguid));
819 if(!fmt)
820 return E_POINTER;
822 if(mode != AUDCLNT_SHAREMODE_SHARED && mode != AUDCLNT_SHAREMODE_EXCLUSIVE)
823 return AUDCLNT_E_NOT_INITIALIZED;
825 if(flags & ~(AUDCLNT_STREAMFLAGS_CROSSPROCESS |
826 AUDCLNT_STREAMFLAGS_LOOPBACK |
827 AUDCLNT_STREAMFLAGS_EVENTCALLBACK |
828 AUDCLNT_STREAMFLAGS_NOPERSIST |
829 AUDCLNT_STREAMFLAGS_RATEADJUST |
830 AUDCLNT_SESSIONFLAGS_EXPIREWHENUNOWNED |
831 AUDCLNT_SESSIONFLAGS_DISPLAY_HIDE |
832 AUDCLNT_SESSIONFLAGS_DISPLAY_HIDEWHENEXPIRED)){
833 TRACE("Unknown flags: %08x\n", flags);
834 return E_INVALIDARG;
837 if(mode == AUDCLNT_SHAREMODE_SHARED){
838 period = DefaultPeriod;
839 if( duration < 3 * period)
840 duration = 3 * period;
841 }else{
842 if(!period)
843 period = DefaultPeriod; /* not minimum */
844 if(period < MinimumPeriod || period > 5000000)
845 return AUDCLNT_E_INVALID_DEVICE_PERIOD;
846 if(duration > 20000000) /* the smaller the period, the lower this limit */
847 return AUDCLNT_E_BUFFER_SIZE_ERROR;
848 if(flags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK){
849 if(duration != period)
850 return AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL;
851 FIXME("EXCLUSIVE mode with EVENTCALLBACK\n");
852 return AUDCLNT_E_DEVICE_IN_USE;
853 }else{
854 if( duration < 8 * period)
855 duration = 8 * period; /* may grow above 2s */
859 EnterCriticalSection(&This->lock);
861 if(This->initted){
862 LeaveCriticalSection(&This->lock);
863 return AUDCLNT_E_ALREADY_INITIALIZED;
866 dump_fmt(fmt);
868 if((err = snd_pcm_hw_params_any(This->pcm_handle, This->hw_params)) < 0){
869 WARN("Unable to get hw_params: %d (%s)\n", err, snd_strerror(err));
870 hr = E_FAIL;
871 goto exit;
874 if((err = snd_pcm_hw_params_set_access(This->pcm_handle, This->hw_params,
875 SND_PCM_ACCESS_RW_INTERLEAVED)) < 0){
876 WARN("Unable to set access: %d (%s)\n", err, snd_strerror(err));
877 hr = E_FAIL;
878 goto exit;
881 if(fmt->wFormatTag == WAVE_FORMAT_PCM ||
882 (fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
883 IsEqualGUID(&fmtex->SubFormat, &KSDATAFORMAT_SUBTYPE_PCM))){
884 if(fmt->wBitsPerSample == 8)
885 format = SND_PCM_FORMAT_U8;
886 else if(fmt->wBitsPerSample == 16)
887 format = SND_PCM_FORMAT_S16_LE;
888 else if(fmt->wBitsPerSample == 24)
889 format = SND_PCM_FORMAT_S24_3LE;
890 else if(fmt->wBitsPerSample == 32)
891 format = SND_PCM_FORMAT_S32_LE;
892 else{
893 WARN("Unsupported bit depth: %u\n", fmt->wBitsPerSample);
894 hr = AUDCLNT_E_UNSUPPORTED_FORMAT;
895 goto exit;
897 }else if(fmt->wFormatTag == WAVE_FORMAT_IEEE_FLOAT ||
898 (fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
899 IsEqualGUID(&fmtex->SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))){
900 if(fmt->wBitsPerSample == 32)
901 format = SND_PCM_FORMAT_FLOAT_LE;
902 else if(fmt->wBitsPerSample == 64)
903 format = SND_PCM_FORMAT_FLOAT64_LE;
904 else{
905 WARN("Unsupported float size: %u\n", fmt->wBitsPerSample);
906 hr = AUDCLNT_E_UNSUPPORTED_FORMAT;
907 goto exit;
909 }else{
910 WARN("Unknown wave format: %04x\n", fmt->wFormatTag);
911 hr = AUDCLNT_E_UNSUPPORTED_FORMAT;
912 goto exit;
915 if((err = snd_pcm_hw_params_set_format(This->pcm_handle, This->hw_params,
916 format)) < 0){
917 WARN("Unable to set ALSA format to %u: %d (%s)\n", format, err,
918 snd_strerror(err));
919 hr = E_FAIL;
920 goto exit;
923 This->alsa_format = format;
925 rate = fmt->nSamplesPerSec;
926 if((err = snd_pcm_hw_params_set_rate_near(This->pcm_handle, This->hw_params,
927 &rate, NULL)) < 0){
928 WARN("Unable to set rate to %u: %d (%s)\n", rate, err,
929 snd_strerror(err));
930 hr = E_FAIL;
931 goto exit;
934 if((err = snd_pcm_hw_params_set_channels(This->pcm_handle, This->hw_params,
935 fmt->nChannels)) < 0){
936 WARN("Unable to set channels to %u: %d (%s)\n", fmt->nChannels, err,
937 snd_strerror(err));
938 hr = E_FAIL;
939 goto exit;
942 This->mmdev_period_rt = period;
943 alsa_period_us = This->mmdev_period_rt / 10;
944 if((err = snd_pcm_hw_params_set_period_time_near(This->pcm_handle,
945 This->hw_params, &alsa_period_us, NULL)) < 0)
946 WARN("Unable to set period time near %u: %d (%s)\n", alsa_period_us,
947 err, snd_strerror(err));
949 if((err = snd_pcm_hw_params(This->pcm_handle, This->hw_params)) < 0){
950 WARN("Unable to set hw params: %d (%s)\n", err, snd_strerror(err));
951 hr = E_FAIL;
952 goto exit;
955 if((err = snd_pcm_hw_params_get_period_size(This->hw_params,
956 &This->alsa_period_frames, NULL)) < 0){
957 WARN("Unable to get period size: %d (%s)\n", err, snd_strerror(err));
958 hr = E_FAIL;
959 goto exit;
962 if((err = snd_pcm_hw_params_get_buffer_size(This->hw_params,
963 &This->alsa_bufsize_frames)) < 0){
964 WARN("Unable to get buffer size: %d (%s)\n", err, snd_strerror(err));
965 hr = E_FAIL;
966 goto exit;
969 sw_params = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, snd_pcm_sw_params_sizeof());
970 if(!sw_params){
971 hr = E_OUTOFMEMORY;
972 goto exit;
975 if((err = snd_pcm_sw_params_current(This->pcm_handle, sw_params)) < 0){
976 WARN("Unable to get sw_params: %d (%s)\n", err, snd_strerror(err));
977 hr = E_FAIL;
978 goto exit;
981 if((err = snd_pcm_sw_params_set_start_threshold(This->pcm_handle,
982 sw_params, 1)) < 0){
983 WARN("Unable set start threshold to 0: %d (%s)\n", err, snd_strerror(err));
984 hr = E_FAIL;
985 goto exit;
988 if((err = snd_pcm_sw_params_set_stop_threshold(This->pcm_handle,
989 sw_params, This->alsa_bufsize_frames)) < 0){
990 WARN("Unable set stop threshold to %lu: %d (%s)\n",
991 This->alsa_bufsize_frames, err, snd_strerror(err));
992 hr = E_FAIL;
993 goto exit;
996 if((err = snd_pcm_sw_params(This->pcm_handle, sw_params)) < 0){
997 WARN("Unable set sw params: %d (%s)\n", err, snd_strerror(err));
998 hr = E_FAIL;
999 goto exit;
1002 if((err = snd_pcm_prepare(This->pcm_handle)) < 0){
1003 WARN("Unable to prepare device: %d (%s)\n", err, snd_strerror(err));
1004 hr = E_FAIL;
1005 goto exit;
1008 /* Check if the ALSA buffer is so small that it will run out before
1009 * the next MMDevAPI period tick occurs. Allow a little wiggle room
1010 * with 120% of the period time. */
1011 This->mmdev_period_frames = (fmt->nSamplesPerSec * This->mmdev_period_rt) / 10000000.;
1012 if(This->alsa_bufsize_frames < 1.2 * This->mmdev_period_frames)
1013 FIXME("ALSA buffer time is smaller than our period time. Expect underruns. (%lu < %u)\n",
1014 This->alsa_bufsize_frames, This->mmdev_period_frames);
1016 This->bufsize_frames = ceil((duration / 10000000.) * fmt->nSamplesPerSec);
1017 This->local_buffer = HeapAlloc(GetProcessHeap(), 0,
1018 This->bufsize_frames * fmt->nBlockAlign);
1019 if(!This->local_buffer){
1020 hr = E_OUTOFMEMORY;
1021 goto exit;
1023 if (fmt->wBitsPerSample == 8)
1024 memset(This->local_buffer, 128, This->bufsize_frames * fmt->nBlockAlign);
1025 else
1026 memset(This->local_buffer, 0, This->bufsize_frames * fmt->nBlockAlign);
1028 This->fmt = clone_format(fmt);
1029 if(!This->fmt){
1030 hr = E_OUTOFMEMORY;
1031 goto exit;
1034 This->vols = HeapAlloc(GetProcessHeap(), 0, fmt->nChannels * sizeof(float));
1035 if(!This->vols){
1036 hr = E_OUTOFMEMORY;
1037 goto exit;
1040 for(i = 0; i < fmt->nChannels; ++i)
1041 This->vols[i] = 1.f;
1043 This->share = mode;
1044 This->flags = flags;
1046 EnterCriticalSection(&g_sessions_lock);
1048 hr = get_audio_session(sessionguid, This->parent, fmt->nChannels,
1049 &This->session);
1050 if(FAILED(hr)){
1051 LeaveCriticalSection(&g_sessions_lock);
1052 goto exit;
1055 list_add_tail(&This->session->clients, &This->entry);
1057 LeaveCriticalSection(&g_sessions_lock);
1059 This->initted = TRUE;
1061 TRACE("ALSA period: %lu frames\n", This->alsa_period_frames);
1062 TRACE("ALSA buffer: %lu frames\n", This->alsa_bufsize_frames);
1063 TRACE("MMDevice period: %u frames\n", This->mmdev_period_frames);
1064 TRACE("MMDevice buffer: %u frames\n", This->bufsize_frames);
1066 exit:
1067 HeapFree(GetProcessHeap(), 0, sw_params);
1068 if(FAILED(hr)){
1069 HeapFree(GetProcessHeap(), 0, This->local_buffer);
1070 This->local_buffer = NULL;
1071 CoTaskMemFree(This->fmt);
1072 This->fmt = NULL;
1073 HeapFree(GetProcessHeap(), 0, This->vols);
1074 This->vols = NULL;
1077 LeaveCriticalSection(&This->lock);
1079 return hr;
1082 static HRESULT WINAPI AudioClient_GetBufferSize(IAudioClient *iface,
1083 UINT32 *out)
1085 ACImpl *This = impl_from_IAudioClient(iface);
1087 TRACE("(%p)->(%p)\n", This, out);
1089 if(!out)
1090 return E_POINTER;
1092 EnterCriticalSection(&This->lock);
1094 if(!This->initted){
1095 LeaveCriticalSection(&This->lock);
1096 return AUDCLNT_E_NOT_INITIALIZED;
1099 *out = This->bufsize_frames;
1101 LeaveCriticalSection(&This->lock);
1103 return S_OK;
1106 static HRESULT WINAPI AudioClient_GetStreamLatency(IAudioClient *iface,
1107 REFERENCE_TIME *latency)
1109 ACImpl *This = impl_from_IAudioClient(iface);
1111 TRACE("(%p)->(%p)\n", This, latency);
1113 if(!latency)
1114 return E_POINTER;
1116 EnterCriticalSection(&This->lock);
1118 if(!This->initted){
1119 LeaveCriticalSection(&This->lock);
1120 return AUDCLNT_E_NOT_INITIALIZED;
1123 LeaveCriticalSection(&This->lock);
1125 *latency = 500000;
1127 return S_OK;
1130 static HRESULT WINAPI AudioClient_GetCurrentPadding(IAudioClient *iface,
1131 UINT32 *out)
1133 ACImpl *This = impl_from_IAudioClient(iface);
1135 TRACE("(%p)->(%p)\n", This, out);
1137 if(!out)
1138 return E_POINTER;
1140 EnterCriticalSection(&This->lock);
1142 if(!This->initted){
1143 LeaveCriticalSection(&This->lock);
1144 return AUDCLNT_E_NOT_INITIALIZED;
1147 *out = This->held_frames;
1149 /* call required to get accurate snd_pcm_state() */
1150 snd_pcm_avail_update(This->pcm_handle);
1151 TRACE("pad: %u, state: %u\n", *out, snd_pcm_state(This->pcm_handle));
1153 LeaveCriticalSection(&This->lock);
1155 return S_OK;
1158 static DWORD get_channel_mask(unsigned int channels)
1160 switch(channels){
1161 case 0:
1162 return 0;
1163 case 1:
1164 return KSAUDIO_SPEAKER_MONO;
1165 case 2:
1166 return KSAUDIO_SPEAKER_STEREO;
1167 case 3:
1168 return KSAUDIO_SPEAKER_STEREO | SPEAKER_LOW_FREQUENCY;
1169 case 4:
1170 return KSAUDIO_SPEAKER_QUAD; /* not _SURROUND */
1171 case 5:
1172 return KSAUDIO_SPEAKER_QUAD | SPEAKER_LOW_FREQUENCY;
1173 case 6:
1174 return KSAUDIO_SPEAKER_5POINT1; /* not 5POINT1_SURROUND */
1175 case 7:
1176 return KSAUDIO_SPEAKER_5POINT1 | SPEAKER_BACK_CENTER;
1177 case 8:
1178 return KSAUDIO_SPEAKER_7POINT1; /* not 7POINT1_SURROUND */
1180 FIXME("Unknown speaker configuration: %u\n", channels);
1181 return 0;
1184 static HRESULT WINAPI AudioClient_IsFormatSupported(IAudioClient *iface,
1185 AUDCLNT_SHAREMODE mode, const WAVEFORMATEX *fmt,
1186 WAVEFORMATEX **out)
1188 ACImpl *This = impl_from_IAudioClient(iface);
1189 snd_pcm_format_mask_t *formats = NULL;
1190 HRESULT hr = S_OK;
1191 WAVEFORMATEX *closest = NULL;
1192 const WAVEFORMATEXTENSIBLE *fmtex = (const WAVEFORMATEXTENSIBLE *)fmt;
1193 unsigned int max = 0, min = 0;
1194 int err;
1196 TRACE("(%p)->(%x, %p, %p)\n", This, mode, fmt, out);
1198 if(!fmt || (mode == AUDCLNT_SHAREMODE_SHARED && !out))
1199 return E_POINTER;
1201 if(mode != AUDCLNT_SHAREMODE_SHARED && mode != AUDCLNT_SHAREMODE_EXCLUSIVE)
1202 return E_INVALIDARG;
1204 if(fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
1205 fmt->cbSize < sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX))
1206 return E_INVALIDARG;
1208 dump_fmt(fmt);
1210 if(out){
1211 *out = NULL;
1212 if(mode != AUDCLNT_SHAREMODE_SHARED)
1213 out = NULL;
1216 EnterCriticalSection(&This->lock);
1218 if((err = snd_pcm_hw_params_any(This->pcm_handle, This->hw_params)) < 0){
1219 hr = E_FAIL;
1220 goto exit;
1223 formats = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1224 snd_pcm_format_mask_sizeof());
1225 if(!formats){
1226 hr = E_OUTOFMEMORY;
1227 goto exit;
1230 snd_pcm_hw_params_get_format_mask(This->hw_params, formats);
1232 if(fmt->wFormatTag == WAVE_FORMAT_PCM ||
1233 (fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
1234 IsEqualGUID(&fmtex->SubFormat, &KSDATAFORMAT_SUBTYPE_PCM))){
1235 switch(fmt->wBitsPerSample){
1236 case 8:
1237 if(!snd_pcm_format_mask_test(formats, SND_PCM_FORMAT_U8)){
1238 hr = AUDCLNT_E_UNSUPPORTED_FORMAT;
1239 goto exit;
1241 break;
1242 case 16:
1243 if(!snd_pcm_format_mask_test(formats, SND_PCM_FORMAT_S16_LE)){
1244 hr = AUDCLNT_E_UNSUPPORTED_FORMAT;
1245 goto exit;
1247 break;
1248 case 24:
1249 if(!snd_pcm_format_mask_test(formats, SND_PCM_FORMAT_S24_3LE)){
1250 hr = AUDCLNT_E_UNSUPPORTED_FORMAT;
1251 goto exit;
1253 break;
1254 case 32:
1255 if(!snd_pcm_format_mask_test(formats, SND_PCM_FORMAT_S32_LE)){
1256 hr = AUDCLNT_E_UNSUPPORTED_FORMAT;
1257 goto exit;
1259 break;
1260 default:
1261 hr = AUDCLNT_E_UNSUPPORTED_FORMAT;
1262 goto exit;
1264 }else if(fmt->wFormatTag == WAVE_FORMAT_IEEE_FLOAT ||
1265 (fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
1266 IsEqualGUID(&fmtex->SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))){
1267 switch(fmt->wBitsPerSample){
1268 case 32:
1269 if(!snd_pcm_format_mask_test(formats, SND_PCM_FORMAT_FLOAT_LE)){
1270 hr = AUDCLNT_E_UNSUPPORTED_FORMAT;
1271 goto exit;
1273 break;
1274 case 64:
1275 if(!snd_pcm_format_mask_test(formats, SND_PCM_FORMAT_FLOAT64_LE)){
1276 hr = AUDCLNT_E_UNSUPPORTED_FORMAT;
1277 goto exit;
1279 break;
1280 default:
1281 hr = AUDCLNT_E_UNSUPPORTED_FORMAT;
1282 goto exit;
1284 }else{
1285 hr = AUDCLNT_E_UNSUPPORTED_FORMAT;
1286 goto exit;
1289 closest = clone_format(fmt);
1290 if(!closest){
1291 hr = E_OUTOFMEMORY;
1292 goto exit;
1295 if((err = snd_pcm_hw_params_get_rate_min(This->hw_params, &min, NULL)) < 0){
1296 hr = E_FAIL;
1297 WARN("Unable to get min rate: %d (%s)\n", err, snd_strerror(err));
1298 goto exit;
1301 if((err = snd_pcm_hw_params_get_rate_max(This->hw_params, &max, NULL)) < 0){
1302 hr = E_FAIL;
1303 WARN("Unable to get max rate: %d (%s)\n", err, snd_strerror(err));
1304 goto exit;
1307 if(fmt->nSamplesPerSec < min || fmt->nSamplesPerSec > max){
1308 hr = AUDCLNT_E_UNSUPPORTED_FORMAT;
1309 goto exit;
1312 if((err = snd_pcm_hw_params_get_channels_min(This->hw_params, &min)) < 0){
1313 hr = E_FAIL;
1314 WARN("Unable to get min channels: %d (%s)\n", err, snd_strerror(err));
1315 goto exit;
1318 if((err = snd_pcm_hw_params_get_channels_max(This->hw_params, &max)) < 0){
1319 hr = E_FAIL;
1320 WARN("Unable to get max channels: %d (%s)\n", err, snd_strerror(err));
1321 goto exit;
1323 if(max > 8)
1324 max = 2;
1325 if(fmt->nChannels > max){
1326 hr = S_FALSE;
1327 closest->nChannels = max;
1328 }else if(fmt->nChannels < min){
1329 hr = S_FALSE;
1330 closest->nChannels = min;
1333 if(closest->wFormatTag == WAVE_FORMAT_EXTENSIBLE){
1334 DWORD mask = get_channel_mask(closest->nChannels);
1336 ((WAVEFORMATEXTENSIBLE*)closest)->dwChannelMask = mask;
1338 if(fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
1339 fmtex->dwChannelMask != 0 &&
1340 fmtex->dwChannelMask != mask)
1341 hr = S_FALSE;
1344 exit:
1345 LeaveCriticalSection(&This->lock);
1346 HeapFree(GetProcessHeap(), 0, formats);
1348 if(hr == S_FALSE && !out)
1349 hr = AUDCLNT_E_UNSUPPORTED_FORMAT;
1351 if(hr == S_FALSE && out) {
1352 closest->nBlockAlign =
1353 closest->nChannels * closest->wBitsPerSample / 8;
1354 closest->nAvgBytesPerSec =
1355 closest->nBlockAlign * closest->nSamplesPerSec;
1356 *out = closest;
1357 } else
1358 CoTaskMemFree(closest);
1360 TRACE("returning: %08x\n", hr);
1361 return hr;
1364 static HRESULT WINAPI AudioClient_GetMixFormat(IAudioClient *iface,
1365 WAVEFORMATEX **pwfx)
1367 ACImpl *This = impl_from_IAudioClient(iface);
1368 WAVEFORMATEXTENSIBLE *fmt;
1369 snd_pcm_format_mask_t *formats;
1370 unsigned int max_rate, max_channels;
1371 int err;
1372 HRESULT hr = S_OK;
1374 TRACE("(%p)->(%p)\n", This, pwfx);
1376 if(!pwfx)
1377 return E_POINTER;
1378 *pwfx = NULL;
1380 fmt = CoTaskMemAlloc(sizeof(WAVEFORMATEXTENSIBLE));
1381 if(!fmt)
1382 return E_OUTOFMEMORY;
1384 formats = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, snd_pcm_format_mask_sizeof());
1385 if(!formats){
1386 CoTaskMemFree(fmt);
1387 return E_OUTOFMEMORY;
1390 EnterCriticalSection(&This->lock);
1392 if((err = snd_pcm_hw_params_any(This->pcm_handle, This->hw_params)) < 0){
1393 WARN("Unable to get hw_params: %d (%s)\n", err, snd_strerror(err));
1394 hr = E_FAIL;
1395 goto exit;
1398 snd_pcm_hw_params_get_format_mask(This->hw_params, formats);
1400 fmt->Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
1401 if(snd_pcm_format_mask_test(formats, SND_PCM_FORMAT_FLOAT_LE)){
1402 fmt->Format.wBitsPerSample = 32;
1403 fmt->SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
1404 }else if(snd_pcm_format_mask_test(formats, SND_PCM_FORMAT_S16_LE)){
1405 fmt->Format.wBitsPerSample = 16;
1406 fmt->SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
1407 }else if(snd_pcm_format_mask_test(formats, SND_PCM_FORMAT_U8)){
1408 fmt->Format.wBitsPerSample = 8;
1409 fmt->SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
1410 }else if(snd_pcm_format_mask_test(formats, SND_PCM_FORMAT_S32_LE)){
1411 fmt->Format.wBitsPerSample = 32;
1412 fmt->SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
1413 }else if(snd_pcm_format_mask_test(formats, SND_PCM_FORMAT_S24_3LE)){
1414 fmt->Format.wBitsPerSample = 24;
1415 fmt->SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
1416 }else{
1417 ERR("Didn't recognize any available ALSA formats\n");
1418 hr = E_FAIL;
1419 goto exit;
1422 if((err = snd_pcm_hw_params_get_channels_max(This->hw_params,
1423 &max_channels)) < 0){
1424 WARN("Unable to get max channels: %d (%s)\n", err, snd_strerror(err));
1425 hr = E_FAIL;
1426 goto exit;
1429 if(max_channels > 2){
1430 FIXME("Don't know what to do with %u channels, pretending there's "
1431 "only 2 channels\n", max_channels);
1432 fmt->Format.nChannels = 2;
1433 }else
1434 fmt->Format.nChannels = max_channels;
1436 fmt->dwChannelMask = get_channel_mask(fmt->Format.nChannels);
1438 if((err = snd_pcm_hw_params_get_rate_max(This->hw_params, &max_rate,
1439 NULL)) < 0){
1440 WARN("Unable to get max rate: %d (%s)\n", err, snd_strerror(err));
1441 hr = E_FAIL;
1442 goto exit;
1445 if(max_rate >= 48000)
1446 fmt->Format.nSamplesPerSec = 48000;
1447 else if(max_rate >= 44100)
1448 fmt->Format.nSamplesPerSec = 44100;
1449 else if(max_rate >= 22050)
1450 fmt->Format.nSamplesPerSec = 22050;
1451 else if(max_rate >= 11025)
1452 fmt->Format.nSamplesPerSec = 11025;
1453 else if(max_rate >= 8000)
1454 fmt->Format.nSamplesPerSec = 8000;
1455 else{
1456 ERR("Unknown max rate: %u\n", max_rate);
1457 hr = E_FAIL;
1458 goto exit;
1461 fmt->Format.nBlockAlign = (fmt->Format.wBitsPerSample *
1462 fmt->Format.nChannels) / 8;
1463 fmt->Format.nAvgBytesPerSec = fmt->Format.nSamplesPerSec *
1464 fmt->Format.nBlockAlign;
1466 fmt->Samples.wValidBitsPerSample = fmt->Format.wBitsPerSample;
1467 fmt->Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX);
1469 dump_fmt((WAVEFORMATEX*)fmt);
1470 *pwfx = (WAVEFORMATEX*)fmt;
1472 exit:
1473 LeaveCriticalSection(&This->lock);
1474 if(FAILED(hr))
1475 CoTaskMemFree(fmt);
1476 HeapFree(GetProcessHeap(), 0, formats);
1478 return hr;
1481 static HRESULT WINAPI AudioClient_GetDevicePeriod(IAudioClient *iface,
1482 REFERENCE_TIME *defperiod, REFERENCE_TIME *minperiod)
1484 ACImpl *This = impl_from_IAudioClient(iface);
1486 TRACE("(%p)->(%p, %p)\n", This, defperiod, minperiod);
1488 if(!defperiod && !minperiod)
1489 return E_POINTER;
1491 if(defperiod)
1492 *defperiod = DefaultPeriod;
1493 if(minperiod)
1494 *minperiod = MinimumPeriod;
1496 return S_OK;
1499 static snd_pcm_sframes_t alsa_write_best_effort(snd_pcm_t *handle, BYTE *buf,
1500 snd_pcm_uframes_t frames, ACImpl *This)
1502 snd_pcm_sframes_t written;
1504 if(This->session->mute){
1505 int err;
1506 if((err = snd_pcm_format_set_silence(This->alsa_format, buf,
1507 frames * This->fmt->nChannels)) < 0)
1508 WARN("Setting buffer to silence failed: %d (%s)\n", err,
1509 snd_strerror(err));
1512 written = snd_pcm_writei(handle, buf, frames);
1513 if(written < 0){
1514 int ret;
1516 if(written == -EAGAIN)
1517 /* buffer full */
1518 return 0;
1520 WARN("writei failed, recovering: %ld (%s)\n", written,
1521 snd_strerror(written));
1523 ret = snd_pcm_recover(handle, written, 0);
1524 if(ret < 0){
1525 WARN("Could not recover: %d (%s)\n", ret, snd_strerror(ret));
1526 return ret;
1529 written = snd_pcm_writei(handle, buf, frames);
1532 return written;
1535 static void alsa_write_data(ACImpl *This)
1537 snd_pcm_sframes_t written;
1538 snd_pcm_uframes_t to_write, avail, write_limit, max_period, in_alsa;
1539 int err;
1540 BYTE *buf =
1541 This->local_buffer + (This->lcl_offs_frames * This->fmt->nBlockAlign);
1543 /* this call seems to be required to get an accurate snd_pcm_state() */
1544 avail = snd_pcm_avail_update(This->pcm_handle);
1546 if(snd_pcm_state(This->pcm_handle) == SND_PCM_STATE_XRUN ||
1547 avail > This->alsa_bufsize_frames){
1548 TRACE("XRun state, recovering\n");
1550 avail = This->alsa_bufsize_frames;
1552 if((err = snd_pcm_recover(This->pcm_handle, -EPIPE, 1)) < 0)
1553 WARN("snd_pcm_recover failed: %d (%s)\n", err, snd_strerror(err));
1555 if((err = snd_pcm_reset(This->pcm_handle)) < 0)
1556 WARN("snd_pcm_reset failed: %d (%s)\n", err, snd_strerror(err));
1558 if((err = snd_pcm_prepare(This->pcm_handle)) < 0)
1559 WARN("snd_pcm_prepare failed: %d (%s)\n", err, snd_strerror(err));
1562 if(This->held_frames == 0)
1563 return;
1565 if(This->lcl_offs_frames + This->held_frames > This->bufsize_frames)
1566 to_write = This->bufsize_frames - This->lcl_offs_frames;
1567 else
1568 to_write = This->held_frames;
1570 max_period = max(This->mmdev_period_frames, This->alsa_period_frames);
1572 /* try to keep 3 ALSA periods or 3 MMDevAPI periods in the ALSA buffer and
1573 * no more */
1574 write_limit = 0;
1575 in_alsa = This->alsa_bufsize_frames - avail;
1576 while(in_alsa + write_limit < max_period * 3)
1577 write_limit += max_period;
1578 if(write_limit == 0)
1579 return;
1581 to_write = min(to_write, write_limit);
1583 written = alsa_write_best_effort(This->pcm_handle, buf, to_write, This);
1584 if(written < 0){
1585 WARN("Couldn't write: %ld (%s)\n", written, snd_strerror(written));
1586 return;
1589 This->lcl_offs_frames += written;
1590 This->lcl_offs_frames %= This->bufsize_frames;
1591 This->held_frames -= written;
1593 if(written < to_write){
1594 /* ALSA buffer probably full */
1595 return;
1598 if(This->held_frames && (written < write_limit)){
1599 /* wrapped and have some data back at the start to write */
1600 written = alsa_write_best_effort(This->pcm_handle, This->local_buffer,
1601 min(This->held_frames, write_limit - written), This);
1602 if(written < 0){
1603 WARN("Couldn't write: %ld (%s)\n", written, snd_strerror(written));
1604 return;
1607 This->lcl_offs_frames += written;
1608 This->lcl_offs_frames %= This->bufsize_frames;
1609 This->held_frames -= written;
1613 static void alsa_read_data(ACImpl *This)
1615 snd_pcm_sframes_t pos, readable, nread;
1617 pos = (This->held_frames + This->lcl_offs_frames) % This->bufsize_frames;
1618 readable = This->bufsize_frames - pos;
1620 nread = snd_pcm_readi(This->pcm_handle,
1621 This->local_buffer + pos * This->fmt->nBlockAlign, readable);
1622 if(nread < 0){
1623 int ret;
1625 WARN("read failed, recovering: %ld (%s)\n", nread, snd_strerror(nread));
1627 ret = snd_pcm_recover(This->pcm_handle, nread, 0);
1628 if(ret < 0){
1629 WARN("Recover failed: %d (%s)\n", ret, snd_strerror(ret));
1630 return;
1633 nread = snd_pcm_readi(This->pcm_handle,
1634 This->local_buffer + pos * This->fmt->nBlockAlign, readable);
1635 if(nread < 0){
1636 WARN("read failed: %ld (%s)\n", nread, snd_strerror(nread));
1637 return;
1641 if(This->session->mute){
1642 int err;
1643 if((err = snd_pcm_format_set_silence(This->alsa_format,
1644 This->local_buffer + pos * This->fmt->nBlockAlign,
1645 nread)) < 0)
1646 WARN("Setting buffer to silence failed: %d (%s)\n", err,
1647 snd_strerror(err));
1650 This->held_frames += nread;
1652 if(This->held_frames > This->bufsize_frames){
1653 WARN("Overflow of unread data\n");
1654 This->lcl_offs_frames += This->held_frames;
1655 This->lcl_offs_frames %= This->bufsize_frames;
1656 This->held_frames = This->bufsize_frames;
1660 static void CALLBACK alsa_push_buffer_data(void *user, BOOLEAN timer)
1662 ACImpl *This = user;
1664 EnterCriticalSection(&This->lock);
1666 if(This->started){
1667 if(This->dataflow == eRender)
1668 alsa_write_data(This);
1669 else if(This->dataflow == eCapture)
1670 alsa_read_data(This);
1672 if(This->event)
1673 SetEvent(This->event);
1676 LeaveCriticalSection(&This->lock);
1679 static HRESULT WINAPI AudioClient_Start(IAudioClient *iface)
1681 ACImpl *This = impl_from_IAudioClient(iface);
1683 TRACE("(%p)\n", This);
1685 EnterCriticalSection(&This->lock);
1687 if(!This->initted){
1688 LeaveCriticalSection(&This->lock);
1689 return AUDCLNT_E_NOT_INITIALIZED;
1692 if((This->flags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK) && !This->event){
1693 LeaveCriticalSection(&This->lock);
1694 return AUDCLNT_E_EVENTHANDLE_NOT_SET;
1697 if(This->started){
1698 LeaveCriticalSection(&This->lock);
1699 return AUDCLNT_E_NOT_STOPPED;
1702 if(This->dataflow == eCapture){
1703 /* dump any data that might be leftover in the ALSA capture buffer */
1704 snd_pcm_readi(This->pcm_handle, This->local_buffer,
1705 This->bufsize_frames);
1708 if(!CreateTimerQueueTimer(&This->timer, g_timer_q, alsa_push_buffer_data,
1709 This, 0, This->mmdev_period_rt / 10000, WT_EXECUTEINTIMERTHREAD)){
1710 LeaveCriticalSection(&This->lock);
1711 WARN("Unable to create timer: %u\n", GetLastError());
1712 return E_FAIL;
1715 This->started = TRUE;
1717 LeaveCriticalSection(&This->lock);
1719 return S_OK;
1722 static HRESULT WINAPI AudioClient_Stop(IAudioClient *iface)
1724 ACImpl *This = impl_from_IAudioClient(iface);
1725 HANDLE event;
1726 BOOL wait;
1728 TRACE("(%p)\n", This);
1730 EnterCriticalSection(&This->lock);
1732 if(!This->initted){
1733 LeaveCriticalSection(&This->lock);
1734 return AUDCLNT_E_NOT_INITIALIZED;
1737 if(!This->started){
1738 LeaveCriticalSection(&This->lock);
1739 return S_FALSE;
1742 if(snd_pcm_drop(This->pcm_handle) < 0)
1743 WARN("snd_pcm_drop failed\n");
1745 if(snd_pcm_reset(This->pcm_handle) < 0)
1746 WARN("snd_pcm_reset failed\n");
1748 if(snd_pcm_prepare(This->pcm_handle) < 0)
1749 WARN("snd_pcm_prepare failed\n");
1751 event = CreateEventW(NULL, TRUE, FALSE, NULL);
1752 wait = !DeleteTimerQueueTimer(g_timer_q, This->timer, event);
1753 if(wait)
1754 WARN("DeleteTimerQueueTimer error %u\n", GetLastError());
1755 wait = wait && GetLastError() == ERROR_IO_PENDING;
1757 This->started = FALSE;
1759 LeaveCriticalSection(&This->lock);
1761 if(event && wait)
1762 WaitForSingleObject(event, INFINITE);
1763 CloseHandle(event);
1765 return S_OK;
1768 static HRESULT WINAPI AudioClient_Reset(IAudioClient *iface)
1770 ACImpl *This = impl_from_IAudioClient(iface);
1772 TRACE("(%p)\n", This);
1774 EnterCriticalSection(&This->lock);
1776 if(!This->initted){
1777 LeaveCriticalSection(&This->lock);
1778 return AUDCLNT_E_NOT_INITIALIZED;
1781 if(This->started){
1782 LeaveCriticalSection(&This->lock);
1783 return AUDCLNT_E_NOT_STOPPED;
1786 if(This->buf_state != NOT_LOCKED){
1787 LeaveCriticalSection(&This->lock);
1788 return AUDCLNT_E_BUFFER_OPERATION_PENDING;
1791 if(snd_pcm_drop(This->pcm_handle) < 0)
1792 WARN("snd_pcm_drop failed\n");
1794 if(snd_pcm_reset(This->pcm_handle) < 0)
1795 WARN("snd_pcm_reset failed\n");
1797 if(snd_pcm_prepare(This->pcm_handle) < 0)
1798 WARN("snd_pcm_prepare failed\n");
1800 This->last_pos_frames = 0;
1801 This->held_frames = 0;
1802 This->written_frames = 0;
1803 This->lcl_offs_frames = 0;
1805 LeaveCriticalSection(&This->lock);
1807 return S_OK;
1810 static HRESULT WINAPI AudioClient_SetEventHandle(IAudioClient *iface,
1811 HANDLE event)
1813 ACImpl *This = impl_from_IAudioClient(iface);
1815 TRACE("(%p)->(%p)\n", This, event);
1817 if(!event)
1818 return E_INVALIDARG;
1820 EnterCriticalSection(&This->lock);
1822 if(!This->initted){
1823 LeaveCriticalSection(&This->lock);
1824 return AUDCLNT_E_NOT_INITIALIZED;
1827 if(!(This->flags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK)){
1828 LeaveCriticalSection(&This->lock);
1829 return AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED;
1832 This->event = event;
1834 LeaveCriticalSection(&This->lock);
1836 return S_OK;
1839 static HRESULT WINAPI AudioClient_GetService(IAudioClient *iface, REFIID riid,
1840 void **ppv)
1842 ACImpl *This = impl_from_IAudioClient(iface);
1844 TRACE("(%p)->(%s, %p)\n", This, debugstr_guid(riid), ppv);
1846 if(!ppv)
1847 return E_POINTER;
1848 *ppv = NULL;
1850 EnterCriticalSection(&This->lock);
1852 if(!This->initted){
1853 LeaveCriticalSection(&This->lock);
1854 return AUDCLNT_E_NOT_INITIALIZED;
1857 if(IsEqualIID(riid, &IID_IAudioRenderClient)){
1858 if(This->dataflow != eRender){
1859 LeaveCriticalSection(&This->lock);
1860 return AUDCLNT_E_WRONG_ENDPOINT_TYPE;
1862 IAudioRenderClient_AddRef(&This->IAudioRenderClient_iface);
1863 *ppv = &This->IAudioRenderClient_iface;
1864 }else if(IsEqualIID(riid, &IID_IAudioCaptureClient)){
1865 if(This->dataflow != eCapture){
1866 LeaveCriticalSection(&This->lock);
1867 return AUDCLNT_E_WRONG_ENDPOINT_TYPE;
1869 IAudioCaptureClient_AddRef(&This->IAudioCaptureClient_iface);
1870 *ppv = &This->IAudioCaptureClient_iface;
1871 }else if(IsEqualIID(riid, &IID_IAudioClock)){
1872 IAudioClock_AddRef(&This->IAudioClock_iface);
1873 *ppv = &This->IAudioClock_iface;
1874 }else if(IsEqualIID(riid, &IID_IAudioStreamVolume)){
1875 IAudioStreamVolume_AddRef(&This->IAudioStreamVolume_iface);
1876 *ppv = &This->IAudioStreamVolume_iface;
1877 }else if(IsEqualIID(riid, &IID_IAudioSessionControl)){
1878 if(!This->session_wrapper){
1879 This->session_wrapper = AudioSessionWrapper_Create(This);
1880 if(!This->session_wrapper){
1881 LeaveCriticalSection(&This->lock);
1882 return E_OUTOFMEMORY;
1884 }else
1885 IAudioSessionControl2_AddRef(&This->session_wrapper->IAudioSessionControl2_iface);
1887 *ppv = &This->session_wrapper->IAudioSessionControl2_iface;
1888 }else if(IsEqualIID(riid, &IID_IChannelAudioVolume)){
1889 if(!This->session_wrapper){
1890 This->session_wrapper = AudioSessionWrapper_Create(This);
1891 if(!This->session_wrapper){
1892 LeaveCriticalSection(&This->lock);
1893 return E_OUTOFMEMORY;
1895 }else
1896 IChannelAudioVolume_AddRef(&This->session_wrapper->IChannelAudioVolume_iface);
1898 *ppv = &This->session_wrapper->IChannelAudioVolume_iface;
1899 }else if(IsEqualIID(riid, &IID_ISimpleAudioVolume)){
1900 if(!This->session_wrapper){
1901 This->session_wrapper = AudioSessionWrapper_Create(This);
1902 if(!This->session_wrapper){
1903 LeaveCriticalSection(&This->lock);
1904 return E_OUTOFMEMORY;
1906 }else
1907 ISimpleAudioVolume_AddRef(&This->session_wrapper->ISimpleAudioVolume_iface);
1909 *ppv = &This->session_wrapper->ISimpleAudioVolume_iface;
1912 if(*ppv){
1913 LeaveCriticalSection(&This->lock);
1914 return S_OK;
1917 LeaveCriticalSection(&This->lock);
1919 FIXME("stub %s\n", debugstr_guid(riid));
1920 return E_NOINTERFACE;
1923 static const IAudioClientVtbl AudioClient_Vtbl =
1925 AudioClient_QueryInterface,
1926 AudioClient_AddRef,
1927 AudioClient_Release,
1928 AudioClient_Initialize,
1929 AudioClient_GetBufferSize,
1930 AudioClient_GetStreamLatency,
1931 AudioClient_GetCurrentPadding,
1932 AudioClient_IsFormatSupported,
1933 AudioClient_GetMixFormat,
1934 AudioClient_GetDevicePeriod,
1935 AudioClient_Start,
1936 AudioClient_Stop,
1937 AudioClient_Reset,
1938 AudioClient_SetEventHandle,
1939 AudioClient_GetService
1942 static HRESULT WINAPI AudioRenderClient_QueryInterface(
1943 IAudioRenderClient *iface, REFIID riid, void **ppv)
1945 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
1947 if(!ppv)
1948 return E_POINTER;
1949 *ppv = NULL;
1951 if(IsEqualIID(riid, &IID_IUnknown) ||
1952 IsEqualIID(riid, &IID_IAudioRenderClient))
1953 *ppv = iface;
1954 if(*ppv){
1955 IUnknown_AddRef((IUnknown*)*ppv);
1956 return S_OK;
1959 WARN("Unknown interface %s\n", debugstr_guid(riid));
1960 return E_NOINTERFACE;
1963 static ULONG WINAPI AudioRenderClient_AddRef(IAudioRenderClient *iface)
1965 ACImpl *This = impl_from_IAudioRenderClient(iface);
1966 return AudioClient_AddRef(&This->IAudioClient_iface);
1969 static ULONG WINAPI AudioRenderClient_Release(IAudioRenderClient *iface)
1971 ACImpl *This = impl_from_IAudioRenderClient(iface);
1972 return AudioClient_Release(&This->IAudioClient_iface);
1975 static HRESULT WINAPI AudioRenderClient_GetBuffer(IAudioRenderClient *iface,
1976 UINT32 frames, BYTE **data)
1978 ACImpl *This = impl_from_IAudioRenderClient(iface);
1979 UINT32 write_pos;
1980 UINT32 pad;
1981 HRESULT hr;
1983 TRACE("(%p)->(%u, %p)\n", This, frames, data);
1985 if(!data)
1986 return E_POINTER;
1988 EnterCriticalSection(&This->lock);
1990 if(This->buf_state != NOT_LOCKED){
1991 LeaveCriticalSection(&This->lock);
1992 return AUDCLNT_E_OUT_OF_ORDER;
1995 if(!frames){
1996 This->buf_state = LOCKED_NORMAL;
1997 LeaveCriticalSection(&This->lock);
1998 return S_OK;
2001 hr = IAudioClient_GetCurrentPadding(&This->IAudioClient_iface, &pad);
2002 if(FAILED(hr)){
2003 LeaveCriticalSection(&This->lock);
2004 return hr;
2007 if(pad + frames > This->bufsize_frames){
2008 LeaveCriticalSection(&This->lock);
2009 return AUDCLNT_E_BUFFER_TOO_LARGE;
2012 write_pos =
2013 (This->lcl_offs_frames + This->held_frames) % This->bufsize_frames;
2014 if(write_pos + frames > This->bufsize_frames){
2015 if(This->tmp_buffer_frames < frames){
2016 if(This->tmp_buffer)
2017 This->tmp_buffer = HeapReAlloc(GetProcessHeap(), 0,
2018 This->tmp_buffer, frames * This->fmt->nBlockAlign);
2019 else
2020 This->tmp_buffer = HeapAlloc(GetProcessHeap(), 0,
2021 frames * This->fmt->nBlockAlign);
2022 if(!This->tmp_buffer){
2023 LeaveCriticalSection(&This->lock);
2024 return E_OUTOFMEMORY;
2026 This->tmp_buffer_frames = frames;
2028 *data = This->tmp_buffer;
2029 This->buf_state = LOCKED_WRAPPED;
2030 }else{
2031 *data = This->local_buffer + write_pos * This->fmt->nBlockAlign;
2032 This->buf_state = LOCKED_NORMAL;
2035 LeaveCriticalSection(&This->lock);
2037 return S_OK;
2040 static void alsa_wrap_buffer(ACImpl *This, BYTE *buffer, UINT32 written_frames)
2042 snd_pcm_uframes_t write_offs_frames =
2043 (This->lcl_offs_frames + This->held_frames) % This->bufsize_frames;
2044 UINT32 write_offs_bytes = write_offs_frames * This->fmt->nBlockAlign;
2045 snd_pcm_uframes_t chunk_frames = This->bufsize_frames - write_offs_frames;
2046 UINT32 chunk_bytes = chunk_frames * This->fmt->nBlockAlign;
2047 UINT32 written_bytes = written_frames * This->fmt->nBlockAlign;
2049 if(written_bytes <= chunk_bytes){
2050 memcpy(This->local_buffer + write_offs_bytes, buffer, written_bytes);
2051 }else{
2052 memcpy(This->local_buffer + write_offs_bytes, buffer, chunk_bytes);
2053 memcpy(This->local_buffer, buffer + chunk_bytes,
2054 written_bytes - chunk_bytes);
2058 static HRESULT WINAPI AudioRenderClient_ReleaseBuffer(
2059 IAudioRenderClient *iface, UINT32 written_frames, DWORD flags)
2061 ACImpl *This = impl_from_IAudioRenderClient(iface);
2062 BYTE *buffer;
2064 TRACE("(%p)->(%u, %x)\n", This, written_frames, flags);
2066 EnterCriticalSection(&This->lock);
2068 if(This->buf_state == NOT_LOCKED || !written_frames){
2069 This->buf_state = NOT_LOCKED;
2070 LeaveCriticalSection(&This->lock);
2071 return written_frames ? AUDCLNT_E_OUT_OF_ORDER : S_OK;
2074 if(This->buf_state == LOCKED_NORMAL)
2075 buffer = This->local_buffer + This->fmt->nBlockAlign *
2076 ((This->lcl_offs_frames + This->held_frames) % This->bufsize_frames);
2077 else
2078 buffer = This->tmp_buffer;
2080 if(flags & AUDCLNT_BUFFERFLAGS_SILENT){
2081 if(This->fmt->wBitsPerSample == 8)
2082 memset(buffer, 128, written_frames * This->fmt->nBlockAlign);
2083 else
2084 memset(buffer, 0, written_frames * This->fmt->nBlockAlign);
2087 if(This->buf_state == LOCKED_WRAPPED)
2088 alsa_wrap_buffer(This, buffer, written_frames);
2090 This->held_frames += written_frames;
2091 This->written_frames += written_frames;
2092 This->buf_state = NOT_LOCKED;
2094 LeaveCriticalSection(&This->lock);
2096 return S_OK;
2099 static const IAudioRenderClientVtbl AudioRenderClient_Vtbl = {
2100 AudioRenderClient_QueryInterface,
2101 AudioRenderClient_AddRef,
2102 AudioRenderClient_Release,
2103 AudioRenderClient_GetBuffer,
2104 AudioRenderClient_ReleaseBuffer
2107 static HRESULT WINAPI AudioCaptureClient_QueryInterface(
2108 IAudioCaptureClient *iface, REFIID riid, void **ppv)
2110 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
2112 if(!ppv)
2113 return E_POINTER;
2114 *ppv = NULL;
2116 if(IsEqualIID(riid, &IID_IUnknown) ||
2117 IsEqualIID(riid, &IID_IAudioCaptureClient))
2118 *ppv = iface;
2119 if(*ppv){
2120 IUnknown_AddRef((IUnknown*)*ppv);
2121 return S_OK;
2124 WARN("Unknown interface %s\n", debugstr_guid(riid));
2125 return E_NOINTERFACE;
2128 static ULONG WINAPI AudioCaptureClient_AddRef(IAudioCaptureClient *iface)
2130 ACImpl *This = impl_from_IAudioCaptureClient(iface);
2131 return IAudioClient_AddRef(&This->IAudioClient_iface);
2134 static ULONG WINAPI AudioCaptureClient_Release(IAudioCaptureClient *iface)
2136 ACImpl *This = impl_from_IAudioCaptureClient(iface);
2137 return IAudioClient_Release(&This->IAudioClient_iface);
2140 static HRESULT WINAPI AudioCaptureClient_GetBuffer(IAudioCaptureClient *iface,
2141 BYTE **data, UINT32 *frames, DWORD *flags, UINT64 *devpos,
2142 UINT64 *qpcpos)
2144 ACImpl *This = impl_from_IAudioCaptureClient(iface);
2145 HRESULT hr;
2147 TRACE("(%p)->(%p, %p, %p, %p, %p)\n", This, data, frames, flags,
2148 devpos, qpcpos);
2150 if(!data || !frames || !flags)
2151 return E_POINTER;
2153 EnterCriticalSection(&This->lock);
2155 if(This->buf_state != NOT_LOCKED){
2156 LeaveCriticalSection(&This->lock);
2157 return AUDCLNT_E_OUT_OF_ORDER;
2160 hr = IAudioCaptureClient_GetNextPacketSize(iface, frames);
2161 if(FAILED(hr)){
2162 LeaveCriticalSection(&This->lock);
2163 return hr;
2166 *flags = 0;
2168 if(This->lcl_offs_frames + *frames > This->bufsize_frames){
2169 UINT32 chunk_bytes, offs_bytes, frames_bytes;
2170 if(This->tmp_buffer_frames < *frames){
2171 if(This->tmp_buffer)
2172 This->tmp_buffer = HeapReAlloc(GetProcessHeap(), 0,
2173 This->tmp_buffer, *frames * This->fmt->nBlockAlign);
2174 else
2175 This->tmp_buffer = HeapAlloc(GetProcessHeap(), 0,
2176 *frames * This->fmt->nBlockAlign);
2177 if(!This->tmp_buffer){
2178 LeaveCriticalSection(&This->lock);
2179 return E_OUTOFMEMORY;
2181 This->tmp_buffer_frames = *frames;
2184 *data = This->tmp_buffer;
2185 chunk_bytes = (This->bufsize_frames - This->lcl_offs_frames) *
2186 This->fmt->nBlockAlign;
2187 offs_bytes = This->lcl_offs_frames * This->fmt->nBlockAlign;
2188 frames_bytes = *frames * This->fmt->nBlockAlign;
2189 memcpy(This->tmp_buffer, This->local_buffer + offs_bytes, chunk_bytes);
2190 memcpy(This->tmp_buffer + chunk_bytes, This->local_buffer,
2191 frames_bytes - chunk_bytes);
2192 }else
2193 *data = This->local_buffer +
2194 This->lcl_offs_frames * This->fmt->nBlockAlign;
2196 This->buf_state = LOCKED_NORMAL;
2198 if(devpos || qpcpos)
2199 IAudioClock_GetPosition(&This->IAudioClock_iface, devpos, qpcpos);
2201 LeaveCriticalSection(&This->lock);
2203 return *frames ? S_OK : AUDCLNT_S_BUFFER_EMPTY;
2206 static HRESULT WINAPI AudioCaptureClient_ReleaseBuffer(
2207 IAudioCaptureClient *iface, UINT32 done)
2209 ACImpl *This = impl_from_IAudioCaptureClient(iface);
2211 TRACE("(%p)->(%u)\n", This, done);
2213 EnterCriticalSection(&This->lock);
2215 if(This->buf_state == NOT_LOCKED){
2216 LeaveCriticalSection(&This->lock);
2217 return AUDCLNT_E_OUT_OF_ORDER;
2220 This->held_frames -= done;
2221 This->lcl_offs_frames += done;
2222 This->lcl_offs_frames %= This->bufsize_frames;
2224 This->buf_state = NOT_LOCKED;
2226 LeaveCriticalSection(&This->lock);
2228 return S_OK;
2231 static HRESULT WINAPI AudioCaptureClient_GetNextPacketSize(
2232 IAudioCaptureClient *iface, UINT32 *frames)
2234 ACImpl *This = impl_from_IAudioCaptureClient(iface);
2236 TRACE("(%p)->(%p)\n", This, frames);
2238 return AudioClient_GetCurrentPadding(&This->IAudioClient_iface, frames);
2241 static const IAudioCaptureClientVtbl AudioCaptureClient_Vtbl =
2243 AudioCaptureClient_QueryInterface,
2244 AudioCaptureClient_AddRef,
2245 AudioCaptureClient_Release,
2246 AudioCaptureClient_GetBuffer,
2247 AudioCaptureClient_ReleaseBuffer,
2248 AudioCaptureClient_GetNextPacketSize
2251 static HRESULT WINAPI AudioClock_QueryInterface(IAudioClock *iface,
2252 REFIID riid, void **ppv)
2254 ACImpl *This = impl_from_IAudioClock(iface);
2256 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
2258 if(!ppv)
2259 return E_POINTER;
2260 *ppv = NULL;
2262 if(IsEqualIID(riid, &IID_IUnknown) || IsEqualIID(riid, &IID_IAudioClock))
2263 *ppv = iface;
2264 else if(IsEqualIID(riid, &IID_IAudioClock2))
2265 *ppv = &This->IAudioClock2_iface;
2266 if(*ppv){
2267 IUnknown_AddRef((IUnknown*)*ppv);
2268 return S_OK;
2271 WARN("Unknown interface %s\n", debugstr_guid(riid));
2272 return E_NOINTERFACE;
2275 static ULONG WINAPI AudioClock_AddRef(IAudioClock *iface)
2277 ACImpl *This = impl_from_IAudioClock(iface);
2278 return IAudioClient_AddRef(&This->IAudioClient_iface);
2281 static ULONG WINAPI AudioClock_Release(IAudioClock *iface)
2283 ACImpl *This = impl_from_IAudioClock(iface);
2284 return IAudioClient_Release(&This->IAudioClient_iface);
2287 static HRESULT WINAPI AudioClock_GetFrequency(IAudioClock *iface, UINT64 *freq)
2289 ACImpl *This = impl_from_IAudioClock(iface);
2291 TRACE("(%p)->(%p)\n", This, freq);
2293 *freq = This->fmt->nSamplesPerSec;
2295 return S_OK;
2298 static HRESULT WINAPI AudioClock_GetPosition(IAudioClock *iface, UINT64 *pos,
2299 UINT64 *qpctime)
2301 ACImpl *This = impl_from_IAudioClock(iface);
2302 UINT64 written_frames, position;
2303 UINT32 held_frames;
2304 int err;
2305 snd_pcm_state_t alsa_state;
2306 snd_pcm_uframes_t avail_frames;
2307 snd_pcm_sframes_t delay_frames;
2309 TRACE("(%p)->(%p, %p)\n", This, pos, qpctime);
2311 if(!pos)
2312 return E_POINTER;
2314 EnterCriticalSection(&This->lock);
2316 /* call required to get accurate snd_pcm_state() */
2317 avail_frames = snd_pcm_avail_update(This->pcm_handle);
2318 alsa_state = snd_pcm_state(This->pcm_handle);
2319 written_frames = This->written_frames;
2320 held_frames = This->held_frames;
2322 err = snd_pcm_delay(This->pcm_handle, &delay_frames);
2323 if(err < 0){
2324 /* old Pulse, shortly after start */
2325 WARN("snd_pcm_delay failed in state %u: %d (%s)\n", alsa_state, err, snd_strerror(err));
2328 if(This->dataflow == eRender){
2329 position = written_frames - held_frames; /* maximum */
2330 if(!This->started || alsa_state > SND_PCM_STATE_RUNNING)
2331 ; /* mmdevapi stopped or ALSA underrun: pretend everything was played */
2332 else if(err<0 || delay_frames > position - This->last_pos_frames)
2333 /* Pulse bug: past underrun, despite recovery, avail_frames & delay
2334 * may be larger than alsa_bufsize_frames, as if cumulating frames. */
2335 /* Pulse bug: EIO(-5) shortly after starting: nothing played */
2336 position = This->last_pos_frames;
2337 else if(delay_frames > 0)
2338 position -= delay_frames;
2339 }else
2340 position = written_frames + held_frames;
2342 /* ensure monotic growth */
2343 This->last_pos_frames = position;
2345 LeaveCriticalSection(&This->lock);
2347 TRACE("frames written: %u, held: %u, avail: %ld, delay: %ld state %d, pos: %u\n",
2348 (UINT32)(written_frames%1000000000), held_frames,
2349 avail_frames, delay_frames, alsa_state, (UINT32)(position%1000000000));
2350 *pos = position;
2352 if(qpctime){
2353 LARGE_INTEGER stamp, freq;
2354 QueryPerformanceCounter(&stamp);
2355 QueryPerformanceFrequency(&freq);
2356 *qpctime = (stamp.QuadPart * (INT64)10000000) / freq.QuadPart;
2359 return S_OK;
2362 static HRESULT WINAPI AudioClock_GetCharacteristics(IAudioClock *iface,
2363 DWORD *chars)
2365 ACImpl *This = impl_from_IAudioClock(iface);
2367 TRACE("(%p)->(%p)\n", This, chars);
2369 if(!chars)
2370 return E_POINTER;
2372 *chars = AUDIOCLOCK_CHARACTERISTIC_FIXED_FREQ;
2374 return S_OK;
2377 static const IAudioClockVtbl AudioClock_Vtbl =
2379 AudioClock_QueryInterface,
2380 AudioClock_AddRef,
2381 AudioClock_Release,
2382 AudioClock_GetFrequency,
2383 AudioClock_GetPosition,
2384 AudioClock_GetCharacteristics
2387 static HRESULT WINAPI AudioClock2_QueryInterface(IAudioClock2 *iface,
2388 REFIID riid, void **ppv)
2390 ACImpl *This = impl_from_IAudioClock2(iface);
2391 return IAudioClock_QueryInterface(&This->IAudioClock_iface, riid, ppv);
2394 static ULONG WINAPI AudioClock2_AddRef(IAudioClock2 *iface)
2396 ACImpl *This = impl_from_IAudioClock2(iface);
2397 return IAudioClient_AddRef(&This->IAudioClient_iface);
2400 static ULONG WINAPI AudioClock2_Release(IAudioClock2 *iface)
2402 ACImpl *This = impl_from_IAudioClock2(iface);
2403 return IAudioClient_Release(&This->IAudioClient_iface);
2406 static HRESULT WINAPI AudioClock2_GetDevicePosition(IAudioClock2 *iface,
2407 UINT64 *pos, UINT64 *qpctime)
2409 ACImpl *This = impl_from_IAudioClock2(iface);
2411 FIXME("(%p)->(%p, %p)\n", This, pos, qpctime);
2413 return E_NOTIMPL;
2416 static const IAudioClock2Vtbl AudioClock2_Vtbl =
2418 AudioClock2_QueryInterface,
2419 AudioClock2_AddRef,
2420 AudioClock2_Release,
2421 AudioClock2_GetDevicePosition
2424 static AudioSessionWrapper *AudioSessionWrapper_Create(ACImpl *client)
2426 AudioSessionWrapper *ret;
2428 ret = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
2429 sizeof(AudioSessionWrapper));
2430 if(!ret)
2431 return NULL;
2433 ret->IAudioSessionControl2_iface.lpVtbl = &AudioSessionControl2_Vtbl;
2434 ret->ISimpleAudioVolume_iface.lpVtbl = &SimpleAudioVolume_Vtbl;
2435 ret->IChannelAudioVolume_iface.lpVtbl = &ChannelAudioVolume_Vtbl;
2437 ret->ref = 1;
2439 ret->client = client;
2440 if(client){
2441 ret->session = client->session;
2442 AudioClient_AddRef(&client->IAudioClient_iface);
2445 return ret;
2448 static HRESULT WINAPI AudioSessionControl_QueryInterface(
2449 IAudioSessionControl2 *iface, REFIID riid, void **ppv)
2451 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
2453 if(!ppv)
2454 return E_POINTER;
2455 *ppv = NULL;
2457 if(IsEqualIID(riid, &IID_IUnknown) ||
2458 IsEqualIID(riid, &IID_IAudioSessionControl) ||
2459 IsEqualIID(riid, &IID_IAudioSessionControl2))
2460 *ppv = iface;
2461 if(*ppv){
2462 IUnknown_AddRef((IUnknown*)*ppv);
2463 return S_OK;
2466 WARN("Unknown interface %s\n", debugstr_guid(riid));
2467 return E_NOINTERFACE;
2470 static ULONG WINAPI AudioSessionControl_AddRef(IAudioSessionControl2 *iface)
2472 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2473 ULONG ref;
2474 ref = InterlockedIncrement(&This->ref);
2475 TRACE("(%p) Refcount now %u\n", This, ref);
2476 return ref;
2479 static ULONG WINAPI AudioSessionControl_Release(IAudioSessionControl2 *iface)
2481 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2482 ULONG ref;
2483 ref = InterlockedDecrement(&This->ref);
2484 TRACE("(%p) Refcount now %u\n", This, ref);
2485 if(!ref){
2486 if(This->client){
2487 EnterCriticalSection(&This->client->lock);
2488 This->client->session_wrapper = NULL;
2489 LeaveCriticalSection(&This->client->lock);
2490 AudioClient_Release(&This->client->IAudioClient_iface);
2492 HeapFree(GetProcessHeap(), 0, This);
2494 return ref;
2497 static HRESULT WINAPI AudioSessionControl_GetState(IAudioSessionControl2 *iface,
2498 AudioSessionState *state)
2500 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2501 ACImpl *client;
2503 TRACE("(%p)->(%p)\n", This, state);
2505 if(!state)
2506 return NULL_PTR_ERR;
2508 EnterCriticalSection(&g_sessions_lock);
2510 if(list_empty(&This->session->clients)){
2511 *state = AudioSessionStateExpired;
2512 LeaveCriticalSection(&g_sessions_lock);
2513 return S_OK;
2516 LIST_FOR_EACH_ENTRY(client, &This->session->clients, ACImpl, entry){
2517 EnterCriticalSection(&client->lock);
2518 if(client->started){
2519 *state = AudioSessionStateActive;
2520 LeaveCriticalSection(&client->lock);
2521 LeaveCriticalSection(&g_sessions_lock);
2522 return S_OK;
2524 LeaveCriticalSection(&client->lock);
2527 LeaveCriticalSection(&g_sessions_lock);
2529 *state = AudioSessionStateInactive;
2531 return S_OK;
2534 static HRESULT WINAPI AudioSessionControl_GetDisplayName(
2535 IAudioSessionControl2 *iface, WCHAR **name)
2537 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2539 FIXME("(%p)->(%p) - stub\n", This, name);
2541 return E_NOTIMPL;
2544 static HRESULT WINAPI AudioSessionControl_SetDisplayName(
2545 IAudioSessionControl2 *iface, const WCHAR *name, const GUID *session)
2547 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2549 FIXME("(%p)->(%p, %s) - stub\n", This, name, debugstr_guid(session));
2551 return E_NOTIMPL;
2554 static HRESULT WINAPI AudioSessionControl_GetIconPath(
2555 IAudioSessionControl2 *iface, WCHAR **path)
2557 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2559 FIXME("(%p)->(%p) - stub\n", This, path);
2561 return E_NOTIMPL;
2564 static HRESULT WINAPI AudioSessionControl_SetIconPath(
2565 IAudioSessionControl2 *iface, const WCHAR *path, const GUID *session)
2567 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2569 FIXME("(%p)->(%p, %s) - stub\n", This, path, debugstr_guid(session));
2571 return E_NOTIMPL;
2574 static HRESULT WINAPI AudioSessionControl_GetGroupingParam(
2575 IAudioSessionControl2 *iface, GUID *group)
2577 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2579 FIXME("(%p)->(%p) - stub\n", This, group);
2581 return E_NOTIMPL;
2584 static HRESULT WINAPI AudioSessionControl_SetGroupingParam(
2585 IAudioSessionControl2 *iface, const GUID *group, const GUID *session)
2587 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2589 FIXME("(%p)->(%s, %s) - stub\n", This, debugstr_guid(group),
2590 debugstr_guid(session));
2592 return E_NOTIMPL;
2595 static HRESULT WINAPI AudioSessionControl_RegisterAudioSessionNotification(
2596 IAudioSessionControl2 *iface, IAudioSessionEvents *events)
2598 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2600 FIXME("(%p)->(%p) - stub\n", This, events);
2602 return S_OK;
2605 static HRESULT WINAPI AudioSessionControl_UnregisterAudioSessionNotification(
2606 IAudioSessionControl2 *iface, IAudioSessionEvents *events)
2608 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2610 FIXME("(%p)->(%p) - stub\n", This, events);
2612 return S_OK;
2615 static HRESULT WINAPI AudioSessionControl_GetSessionIdentifier(
2616 IAudioSessionControl2 *iface, WCHAR **id)
2618 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2620 FIXME("(%p)->(%p) - stub\n", This, id);
2622 return E_NOTIMPL;
2625 static HRESULT WINAPI AudioSessionControl_GetSessionInstanceIdentifier(
2626 IAudioSessionControl2 *iface, WCHAR **id)
2628 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2630 FIXME("(%p)->(%p) - stub\n", This, id);
2632 return E_NOTIMPL;
2635 static HRESULT WINAPI AudioSessionControl_GetProcessId(
2636 IAudioSessionControl2 *iface, DWORD *pid)
2638 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2640 TRACE("(%p)->(%p)\n", This, pid);
2642 if(!pid)
2643 return E_POINTER;
2645 *pid = GetCurrentProcessId();
2647 return S_OK;
2650 static HRESULT WINAPI AudioSessionControl_IsSystemSoundsSession(
2651 IAudioSessionControl2 *iface)
2653 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2655 TRACE("(%p)\n", This);
2657 return S_FALSE;
2660 static HRESULT WINAPI AudioSessionControl_SetDuckingPreference(
2661 IAudioSessionControl2 *iface, BOOL optout)
2663 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2665 TRACE("(%p)->(%d)\n", This, optout);
2667 return S_OK;
2670 static const IAudioSessionControl2Vtbl AudioSessionControl2_Vtbl =
2672 AudioSessionControl_QueryInterface,
2673 AudioSessionControl_AddRef,
2674 AudioSessionControl_Release,
2675 AudioSessionControl_GetState,
2676 AudioSessionControl_GetDisplayName,
2677 AudioSessionControl_SetDisplayName,
2678 AudioSessionControl_GetIconPath,
2679 AudioSessionControl_SetIconPath,
2680 AudioSessionControl_GetGroupingParam,
2681 AudioSessionControl_SetGroupingParam,
2682 AudioSessionControl_RegisterAudioSessionNotification,
2683 AudioSessionControl_UnregisterAudioSessionNotification,
2684 AudioSessionControl_GetSessionIdentifier,
2685 AudioSessionControl_GetSessionInstanceIdentifier,
2686 AudioSessionControl_GetProcessId,
2687 AudioSessionControl_IsSystemSoundsSession,
2688 AudioSessionControl_SetDuckingPreference
2691 static HRESULT WINAPI SimpleAudioVolume_QueryInterface(
2692 ISimpleAudioVolume *iface, REFIID riid, void **ppv)
2694 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
2696 if(!ppv)
2697 return E_POINTER;
2698 *ppv = NULL;
2700 if(IsEqualIID(riid, &IID_IUnknown) ||
2701 IsEqualIID(riid, &IID_ISimpleAudioVolume))
2702 *ppv = iface;
2703 if(*ppv){
2704 IUnknown_AddRef((IUnknown*)*ppv);
2705 return S_OK;
2708 WARN("Unknown interface %s\n", debugstr_guid(riid));
2709 return E_NOINTERFACE;
2712 static ULONG WINAPI SimpleAudioVolume_AddRef(ISimpleAudioVolume *iface)
2714 AudioSessionWrapper *This = impl_from_ISimpleAudioVolume(iface);
2715 return AudioSessionControl_AddRef(&This->IAudioSessionControl2_iface);
2718 static ULONG WINAPI SimpleAudioVolume_Release(ISimpleAudioVolume *iface)
2720 AudioSessionWrapper *This = impl_from_ISimpleAudioVolume(iface);
2721 return AudioSessionControl_Release(&This->IAudioSessionControl2_iface);
2724 static HRESULT WINAPI SimpleAudioVolume_SetMasterVolume(
2725 ISimpleAudioVolume *iface, float level, const GUID *context)
2727 AudioSessionWrapper *This = impl_from_ISimpleAudioVolume(iface);
2728 AudioSession *session = This->session;
2730 TRACE("(%p)->(%f, %s)\n", session, level, wine_dbgstr_guid(context));
2732 if(level < 0.f || level > 1.f)
2733 return E_INVALIDARG;
2735 if(context)
2736 FIXME("Notifications not supported yet\n");
2738 TRACE("ALSA does not support volume control\n");
2740 EnterCriticalSection(&session->lock);
2742 session->master_vol = level;
2744 LeaveCriticalSection(&session->lock);
2746 return S_OK;
2749 static HRESULT WINAPI SimpleAudioVolume_GetMasterVolume(
2750 ISimpleAudioVolume *iface, float *level)
2752 AudioSessionWrapper *This = impl_from_ISimpleAudioVolume(iface);
2753 AudioSession *session = This->session;
2755 TRACE("(%p)->(%p)\n", session, level);
2757 if(!level)
2758 return NULL_PTR_ERR;
2760 *level = session->master_vol;
2762 return S_OK;
2765 static HRESULT WINAPI SimpleAudioVolume_SetMute(ISimpleAudioVolume *iface,
2766 BOOL mute, const GUID *context)
2768 AudioSessionWrapper *This = impl_from_ISimpleAudioVolume(iface);
2769 AudioSession *session = This->session;
2771 TRACE("(%p)->(%u, %p)\n", session, mute, context);
2773 if(context)
2774 FIXME("Notifications not supported yet\n");
2776 session->mute = mute;
2778 return S_OK;
2781 static HRESULT WINAPI SimpleAudioVolume_GetMute(ISimpleAudioVolume *iface,
2782 BOOL *mute)
2784 AudioSessionWrapper *This = impl_from_ISimpleAudioVolume(iface);
2785 AudioSession *session = This->session;
2787 TRACE("(%p)->(%p)\n", session, mute);
2789 if(!mute)
2790 return NULL_PTR_ERR;
2792 *mute = session->mute;
2794 return S_OK;
2797 static const ISimpleAudioVolumeVtbl SimpleAudioVolume_Vtbl =
2799 SimpleAudioVolume_QueryInterface,
2800 SimpleAudioVolume_AddRef,
2801 SimpleAudioVolume_Release,
2802 SimpleAudioVolume_SetMasterVolume,
2803 SimpleAudioVolume_GetMasterVolume,
2804 SimpleAudioVolume_SetMute,
2805 SimpleAudioVolume_GetMute
2808 static HRESULT WINAPI AudioStreamVolume_QueryInterface(
2809 IAudioStreamVolume *iface, REFIID riid, void **ppv)
2811 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
2813 if(!ppv)
2814 return E_POINTER;
2815 *ppv = NULL;
2817 if(IsEqualIID(riid, &IID_IUnknown) ||
2818 IsEqualIID(riid, &IID_IAudioStreamVolume))
2819 *ppv = iface;
2820 if(*ppv){
2821 IUnknown_AddRef((IUnknown*)*ppv);
2822 return S_OK;
2825 WARN("Unknown interface %s\n", debugstr_guid(riid));
2826 return E_NOINTERFACE;
2829 static ULONG WINAPI AudioStreamVolume_AddRef(IAudioStreamVolume *iface)
2831 ACImpl *This = impl_from_IAudioStreamVolume(iface);
2832 return IAudioClient_AddRef(&This->IAudioClient_iface);
2835 static ULONG WINAPI AudioStreamVolume_Release(IAudioStreamVolume *iface)
2837 ACImpl *This = impl_from_IAudioStreamVolume(iface);
2838 return IAudioClient_Release(&This->IAudioClient_iface);
2841 static HRESULT WINAPI AudioStreamVolume_GetChannelCount(
2842 IAudioStreamVolume *iface, UINT32 *out)
2844 ACImpl *This = impl_from_IAudioStreamVolume(iface);
2846 TRACE("(%p)->(%p)\n", This, out);
2848 if(!out)
2849 return E_POINTER;
2851 *out = This->fmt->nChannels;
2853 return S_OK;
2856 static HRESULT WINAPI AudioStreamVolume_SetChannelVolume(
2857 IAudioStreamVolume *iface, UINT32 index, float level)
2859 ACImpl *This = impl_from_IAudioStreamVolume(iface);
2861 TRACE("(%p)->(%d, %f)\n", This, index, level);
2863 if(level < 0.f || level > 1.f)
2864 return E_INVALIDARG;
2866 if(index >= This->fmt->nChannels)
2867 return E_INVALIDARG;
2869 TRACE("ALSA does not support volume control\n");
2871 EnterCriticalSection(&This->lock);
2873 This->vols[index] = level;
2875 LeaveCriticalSection(&This->lock);
2877 return S_OK;
2880 static HRESULT WINAPI AudioStreamVolume_GetChannelVolume(
2881 IAudioStreamVolume *iface, UINT32 index, float *level)
2883 ACImpl *This = impl_from_IAudioStreamVolume(iface);
2885 TRACE("(%p)->(%d, %p)\n", This, index, level);
2887 if(!level)
2888 return E_POINTER;
2890 if(index >= This->fmt->nChannels)
2891 return E_INVALIDARG;
2893 *level = This->vols[index];
2895 return S_OK;
2898 static HRESULT WINAPI AudioStreamVolume_SetAllVolumes(
2899 IAudioStreamVolume *iface, UINT32 count, const float *levels)
2901 ACImpl *This = impl_from_IAudioStreamVolume(iface);
2902 int i;
2904 TRACE("(%p)->(%d, %p)\n", This, count, levels);
2906 if(!levels)
2907 return E_POINTER;
2909 if(count != This->fmt->nChannels)
2910 return E_INVALIDARG;
2912 TRACE("ALSA does not support volume control\n");
2914 EnterCriticalSection(&This->lock);
2916 for(i = 0; i < count; ++i)
2917 This->vols[i] = levels[i];
2919 LeaveCriticalSection(&This->lock);
2921 return S_OK;
2924 static HRESULT WINAPI AudioStreamVolume_GetAllVolumes(
2925 IAudioStreamVolume *iface, UINT32 count, float *levels)
2927 ACImpl *This = impl_from_IAudioStreamVolume(iface);
2928 int i;
2930 TRACE("(%p)->(%d, %p)\n", This, count, levels);
2932 if(!levels)
2933 return E_POINTER;
2935 if(count != This->fmt->nChannels)
2936 return E_INVALIDARG;
2938 EnterCriticalSection(&This->lock);
2940 for(i = 0; i < count; ++i)
2941 levels[i] = This->vols[i];
2943 LeaveCriticalSection(&This->lock);
2945 return S_OK;
2948 static const IAudioStreamVolumeVtbl AudioStreamVolume_Vtbl =
2950 AudioStreamVolume_QueryInterface,
2951 AudioStreamVolume_AddRef,
2952 AudioStreamVolume_Release,
2953 AudioStreamVolume_GetChannelCount,
2954 AudioStreamVolume_SetChannelVolume,
2955 AudioStreamVolume_GetChannelVolume,
2956 AudioStreamVolume_SetAllVolumes,
2957 AudioStreamVolume_GetAllVolumes
2960 static HRESULT WINAPI ChannelAudioVolume_QueryInterface(
2961 IChannelAudioVolume *iface, REFIID riid, void **ppv)
2963 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
2965 if(!ppv)
2966 return E_POINTER;
2967 *ppv = NULL;
2969 if(IsEqualIID(riid, &IID_IUnknown) ||
2970 IsEqualIID(riid, &IID_IChannelAudioVolume))
2971 *ppv = iface;
2972 if(*ppv){
2973 IUnknown_AddRef((IUnknown*)*ppv);
2974 return S_OK;
2977 WARN("Unknown interface %s\n", debugstr_guid(riid));
2978 return E_NOINTERFACE;
2981 static ULONG WINAPI ChannelAudioVolume_AddRef(IChannelAudioVolume *iface)
2983 AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
2984 return AudioSessionControl_AddRef(&This->IAudioSessionControl2_iface);
2987 static ULONG WINAPI ChannelAudioVolume_Release(IChannelAudioVolume *iface)
2989 AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
2990 return AudioSessionControl_Release(&This->IAudioSessionControl2_iface);
2993 static HRESULT WINAPI ChannelAudioVolume_GetChannelCount(
2994 IChannelAudioVolume *iface, UINT32 *out)
2996 AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
2997 AudioSession *session = This->session;
2999 TRACE("(%p)->(%p)\n", session, out);
3001 if(!out)
3002 return NULL_PTR_ERR;
3004 *out = session->channel_count;
3006 return S_OK;
3009 static HRESULT WINAPI ChannelAudioVolume_SetChannelVolume(
3010 IChannelAudioVolume *iface, UINT32 index, float level,
3011 const GUID *context)
3013 AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
3014 AudioSession *session = This->session;
3016 TRACE("(%p)->(%d, %f, %s)\n", session, index, level,
3017 wine_dbgstr_guid(context));
3019 if(level < 0.f || level > 1.f)
3020 return E_INVALIDARG;
3022 if(index >= session->channel_count)
3023 return E_INVALIDARG;
3025 if(context)
3026 FIXME("Notifications not supported yet\n");
3028 TRACE("ALSA does not support volume control\n");
3030 EnterCriticalSection(&session->lock);
3032 session->channel_vols[index] = level;
3034 LeaveCriticalSection(&session->lock);
3036 return S_OK;
3039 static HRESULT WINAPI ChannelAudioVolume_GetChannelVolume(
3040 IChannelAudioVolume *iface, UINT32 index, float *level)
3042 AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
3043 AudioSession *session = This->session;
3045 TRACE("(%p)->(%d, %p)\n", session, index, level);
3047 if(!level)
3048 return NULL_PTR_ERR;
3050 if(index >= session->channel_count)
3051 return E_INVALIDARG;
3053 *level = session->channel_vols[index];
3055 return S_OK;
3058 static HRESULT WINAPI ChannelAudioVolume_SetAllVolumes(
3059 IChannelAudioVolume *iface, UINT32 count, const float *levels,
3060 const GUID *context)
3062 AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
3063 AudioSession *session = This->session;
3064 int i;
3066 TRACE("(%p)->(%d, %p, %s)\n", session, count, levels,
3067 wine_dbgstr_guid(context));
3069 if(!levels)
3070 return NULL_PTR_ERR;
3072 if(count != session->channel_count)
3073 return E_INVALIDARG;
3075 if(context)
3076 FIXME("Notifications not supported yet\n");
3078 TRACE("ALSA does not support volume control\n");
3080 EnterCriticalSection(&session->lock);
3082 for(i = 0; i < count; ++i)
3083 session->channel_vols[i] = levels[i];
3085 LeaveCriticalSection(&session->lock);
3087 return S_OK;
3090 static HRESULT WINAPI ChannelAudioVolume_GetAllVolumes(
3091 IChannelAudioVolume *iface, UINT32 count, float *levels)
3093 AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
3094 AudioSession *session = This->session;
3095 int i;
3097 TRACE("(%p)->(%d, %p)\n", session, count, levels);
3099 if(!levels)
3100 return NULL_PTR_ERR;
3102 if(count != session->channel_count)
3103 return E_INVALIDARG;
3105 for(i = 0; i < count; ++i)
3106 levels[i] = session->channel_vols[i];
3108 return S_OK;
3111 static const IChannelAudioVolumeVtbl ChannelAudioVolume_Vtbl =
3113 ChannelAudioVolume_QueryInterface,
3114 ChannelAudioVolume_AddRef,
3115 ChannelAudioVolume_Release,
3116 ChannelAudioVolume_GetChannelCount,
3117 ChannelAudioVolume_SetChannelVolume,
3118 ChannelAudioVolume_GetChannelVolume,
3119 ChannelAudioVolume_SetAllVolumes,
3120 ChannelAudioVolume_GetAllVolumes
3123 static HRESULT WINAPI AudioSessionManager_QueryInterface(IAudioSessionManager2 *iface,
3124 REFIID riid, void **ppv)
3126 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
3128 if(!ppv)
3129 return E_POINTER;
3130 *ppv = NULL;
3132 if(IsEqualIID(riid, &IID_IUnknown) ||
3133 IsEqualIID(riid, &IID_IAudioSessionManager) ||
3134 IsEqualIID(riid, &IID_IAudioSessionManager2))
3135 *ppv = iface;
3136 if(*ppv){
3137 IUnknown_AddRef((IUnknown*)*ppv);
3138 return S_OK;
3141 WARN("Unknown interface %s\n", debugstr_guid(riid));
3142 return E_NOINTERFACE;
3145 static ULONG WINAPI AudioSessionManager_AddRef(IAudioSessionManager2 *iface)
3147 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
3148 ULONG ref;
3149 ref = InterlockedIncrement(&This->ref);
3150 TRACE("(%p) Refcount now %u\n", This, ref);
3151 return ref;
3154 static ULONG WINAPI AudioSessionManager_Release(IAudioSessionManager2 *iface)
3156 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
3157 ULONG ref;
3158 ref = InterlockedDecrement(&This->ref);
3159 TRACE("(%p) Refcount now %u\n", This, ref);
3160 if(!ref)
3161 HeapFree(GetProcessHeap(), 0, This);
3162 return ref;
3165 static HRESULT WINAPI AudioSessionManager_GetAudioSessionControl(
3166 IAudioSessionManager2 *iface, const GUID *session_guid, DWORD flags,
3167 IAudioSessionControl **out)
3169 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
3170 AudioSession *session;
3171 AudioSessionWrapper *wrapper;
3172 HRESULT hr;
3174 TRACE("(%p)->(%s, %x, %p)\n", This, debugstr_guid(session_guid),
3175 flags, out);
3177 hr = get_audio_session(session_guid, This->device, 0, &session);
3178 if(FAILED(hr))
3179 return hr;
3181 wrapper = AudioSessionWrapper_Create(NULL);
3182 if(!wrapper)
3183 return E_OUTOFMEMORY;
3185 wrapper->session = session;
3187 *out = (IAudioSessionControl*)&wrapper->IAudioSessionControl2_iface;
3189 return S_OK;
3192 static HRESULT WINAPI AudioSessionManager_GetSimpleAudioVolume(
3193 IAudioSessionManager2 *iface, const GUID *session_guid, DWORD flags,
3194 ISimpleAudioVolume **out)
3196 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
3197 AudioSession *session;
3198 AudioSessionWrapper *wrapper;
3199 HRESULT hr;
3201 TRACE("(%p)->(%s, %x, %p)\n", This, debugstr_guid(session_guid),
3202 flags, out);
3204 hr = get_audio_session(session_guid, This->device, 0, &session);
3205 if(FAILED(hr))
3206 return hr;
3208 wrapper = AudioSessionWrapper_Create(NULL);
3209 if(!wrapper)
3210 return E_OUTOFMEMORY;
3212 wrapper->session = session;
3214 *out = &wrapper->ISimpleAudioVolume_iface;
3216 return S_OK;
3219 static HRESULT WINAPI AudioSessionManager_GetSessionEnumerator(
3220 IAudioSessionManager2 *iface, IAudioSessionEnumerator **out)
3222 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
3223 FIXME("(%p)->(%p) - stub\n", This, out);
3224 return E_NOTIMPL;
3227 static HRESULT WINAPI AudioSessionManager_RegisterSessionNotification(
3228 IAudioSessionManager2 *iface, IAudioSessionNotification *notification)
3230 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
3231 FIXME("(%p)->(%p) - stub\n", This, notification);
3232 return E_NOTIMPL;
3235 static HRESULT WINAPI AudioSessionManager_UnregisterSessionNotification(
3236 IAudioSessionManager2 *iface, IAudioSessionNotification *notification)
3238 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
3239 FIXME("(%p)->(%p) - stub\n", This, notification);
3240 return E_NOTIMPL;
3243 static HRESULT WINAPI AudioSessionManager_RegisterDuckNotification(
3244 IAudioSessionManager2 *iface, const WCHAR *session_id,
3245 IAudioVolumeDuckNotification *notification)
3247 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
3248 FIXME("(%p)->(%p) - stub\n", This, notification);
3249 return E_NOTIMPL;
3252 static HRESULT WINAPI AudioSessionManager_UnregisterDuckNotification(
3253 IAudioSessionManager2 *iface,
3254 IAudioVolumeDuckNotification *notification)
3256 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
3257 FIXME("(%p)->(%p) - stub\n", This, notification);
3258 return E_NOTIMPL;
3261 static const IAudioSessionManager2Vtbl AudioSessionManager2_Vtbl =
3263 AudioSessionManager_QueryInterface,
3264 AudioSessionManager_AddRef,
3265 AudioSessionManager_Release,
3266 AudioSessionManager_GetAudioSessionControl,
3267 AudioSessionManager_GetSimpleAudioVolume,
3268 AudioSessionManager_GetSessionEnumerator,
3269 AudioSessionManager_RegisterSessionNotification,
3270 AudioSessionManager_UnregisterSessionNotification,
3271 AudioSessionManager_RegisterDuckNotification,
3272 AudioSessionManager_UnregisterDuckNotification
3275 HRESULT WINAPI AUDDRV_GetAudioSessionManager(IMMDevice *device,
3276 IAudioSessionManager2 **out)
3278 SessionMgr *This;
3280 This = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(SessionMgr));
3281 if(!This)
3282 return E_OUTOFMEMORY;
3284 This->IAudioSessionManager2_iface.lpVtbl = &AudioSessionManager2_Vtbl;
3285 This->device = device;
3286 This->ref = 1;
3288 *out = &This->IAudioSessionManager2_iface;
3290 return S_OK;