mmdevapi: Fill buffer with silence in IAudioRenderClient::GetBuffer.
[wine.git] / dlls / winealsa.drv / mmdevdrv.c
blob6e854e410eff76129afe1537a7b7b9df24cadf4d
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 "mmsystem.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;
55 #define EXTRA_SAFE_RT 40000
57 struct ACImpl;
58 typedef struct ACImpl ACImpl;
60 typedef struct _AudioSession {
61 GUID guid;
62 struct list clients;
64 IMMDevice *device;
66 float master_vol;
67 UINT32 channel_count;
68 float *channel_vols;
69 BOOL mute;
71 CRITICAL_SECTION lock;
73 struct list entry;
74 } AudioSession;
76 typedef struct _AudioSessionWrapper {
77 IAudioSessionControl2 IAudioSessionControl2_iface;
78 IChannelAudioVolume IChannelAudioVolume_iface;
79 ISimpleAudioVolume ISimpleAudioVolume_iface;
81 LONG ref;
83 ACImpl *client;
84 AudioSession *session;
85 } AudioSessionWrapper;
87 struct ACImpl {
88 IAudioClient IAudioClient_iface;
89 IAudioRenderClient IAudioRenderClient_iface;
90 IAudioCaptureClient IAudioCaptureClient_iface;
91 IAudioClock IAudioClock_iface;
92 IAudioClock2 IAudioClock2_iface;
93 IAudioStreamVolume IAudioStreamVolume_iface;
95 LONG ref;
97 snd_pcm_t *pcm_handle;
98 snd_pcm_uframes_t alsa_bufsize_frames, alsa_period_frames;
99 snd_pcm_hw_params_t *hw_params; /* does not hold state between calls */
100 snd_pcm_format_t alsa_format;
102 IMMDevice *parent;
103 IUnknown *pUnkFTMarshal;
105 EDataFlow dataflow;
106 WAVEFORMATEX *fmt;
107 DWORD flags;
108 AUDCLNT_SHAREMODE share;
109 HANDLE event;
110 float *vols;
112 BOOL need_remapping;
113 int alsa_channels;
114 int alsa_channel_map[32];
116 BOOL initted, started;
117 REFERENCE_TIME mmdev_period_rt;
118 UINT64 written_frames, last_pos_frames;
119 UINT32 bufsize_frames, held_frames, tmp_buffer_frames, mmdev_period_frames;
120 snd_pcm_uframes_t remapping_buf_frames;
121 UINT32 lcl_offs_frames; /* offs into local_buffer where valid data starts */
122 UINT32 wri_offs_frames; /* where to write fresh data in local_buffer */
123 UINT32 hidden_frames; /* ALSA reserve to ensure continuous rendering */
125 HANDLE timer;
126 BYTE *local_buffer, *tmp_buffer, *remapping_buf;
127 LONG32 getbuf_last; /* <0 when using tmp_buffer */
129 CRITICAL_SECTION lock;
131 AudioSession *session;
132 AudioSessionWrapper *session_wrapper;
134 struct list entry;
137 typedef struct _SessionMgr {
138 IAudioSessionManager2 IAudioSessionManager2_iface;
140 LONG ref;
142 IMMDevice *device;
143 } SessionMgr;
145 static HANDLE g_timer_q;
147 static CRITICAL_SECTION g_sessions_lock;
148 static CRITICAL_SECTION_DEBUG g_sessions_lock_debug =
150 0, 0, &g_sessions_lock,
151 { &g_sessions_lock_debug.ProcessLocksList, &g_sessions_lock_debug.ProcessLocksList },
152 0, 0, { (DWORD_PTR)(__FILE__ ": g_sessions_lock") }
154 static CRITICAL_SECTION g_sessions_lock = { &g_sessions_lock_debug, -1, 0, 0, 0, 0 };
155 static struct list g_sessions = LIST_INIT(g_sessions);
157 static const WCHAR defaultW[] = {'d','e','f','a','u','l','t',0};
158 static const char defname[] = "default";
160 static const WCHAR drv_keyW[] = {'S','o','f','t','w','a','r','e','\\',
161 'W','i','n','e','\\','D','r','i','v','e','r','s','\\',
162 'w','i','n','e','a','l','s','a','.','d','r','v',0};
163 static const WCHAR drv_key_devicesW[] = {'S','o','f','t','w','a','r','e','\\',
164 'W','i','n','e','\\','D','r','i','v','e','r','s','\\',
165 'w','i','n','e','a','l','s','a','.','d','r','v','\\','d','e','v','i','c','e','s',0};
166 static const WCHAR guidW[] = {'g','u','i','d',0};
168 static const IAudioClientVtbl AudioClient_Vtbl;
169 static const IAudioRenderClientVtbl AudioRenderClient_Vtbl;
170 static const IAudioCaptureClientVtbl AudioCaptureClient_Vtbl;
171 static const IAudioSessionControl2Vtbl AudioSessionControl2_Vtbl;
172 static const ISimpleAudioVolumeVtbl SimpleAudioVolume_Vtbl;
173 static const IAudioClockVtbl AudioClock_Vtbl;
174 static const IAudioClock2Vtbl AudioClock2_Vtbl;
175 static const IAudioStreamVolumeVtbl AudioStreamVolume_Vtbl;
176 static const IChannelAudioVolumeVtbl ChannelAudioVolume_Vtbl;
177 static const IAudioSessionManager2Vtbl AudioSessionManager2_Vtbl;
179 static AudioSessionWrapper *AudioSessionWrapper_Create(ACImpl *client);
181 static inline ACImpl *impl_from_IAudioClient(IAudioClient *iface)
183 return CONTAINING_RECORD(iface, ACImpl, IAudioClient_iface);
186 static inline ACImpl *impl_from_IAudioRenderClient(IAudioRenderClient *iface)
188 return CONTAINING_RECORD(iface, ACImpl, IAudioRenderClient_iface);
191 static inline ACImpl *impl_from_IAudioCaptureClient(IAudioCaptureClient *iface)
193 return CONTAINING_RECORD(iface, ACImpl, IAudioCaptureClient_iface);
196 static inline AudioSessionWrapper *impl_from_IAudioSessionControl2(IAudioSessionControl2 *iface)
198 return CONTAINING_RECORD(iface, AudioSessionWrapper, IAudioSessionControl2_iface);
201 static inline AudioSessionWrapper *impl_from_ISimpleAudioVolume(ISimpleAudioVolume *iface)
203 return CONTAINING_RECORD(iface, AudioSessionWrapper, ISimpleAudioVolume_iface);
206 static inline AudioSessionWrapper *impl_from_IChannelAudioVolume(IChannelAudioVolume *iface)
208 return CONTAINING_RECORD(iface, AudioSessionWrapper, IChannelAudioVolume_iface);
211 static inline ACImpl *impl_from_IAudioClock(IAudioClock *iface)
213 return CONTAINING_RECORD(iface, ACImpl, IAudioClock_iface);
216 static inline ACImpl *impl_from_IAudioClock2(IAudioClock2 *iface)
218 return CONTAINING_RECORD(iface, ACImpl, IAudioClock2_iface);
221 static inline ACImpl *impl_from_IAudioStreamVolume(IAudioStreamVolume *iface)
223 return CONTAINING_RECORD(iface, ACImpl, IAudioStreamVolume_iface);
226 static inline SessionMgr *impl_from_IAudioSessionManager2(IAudioSessionManager2 *iface)
228 return CONTAINING_RECORD(iface, SessionMgr, IAudioSessionManager2_iface);
231 BOOL WINAPI DllMain(HINSTANCE dll, DWORD reason, void *reserved)
233 switch (reason)
235 case DLL_PROCESS_ATTACH:
236 g_timer_q = CreateTimerQueue();
237 if(!g_timer_q)
238 return FALSE;
239 break;
241 case DLL_PROCESS_DETACH:
242 if (reserved) break;
243 DeleteCriticalSection(&g_sessions_lock);
244 break;
246 return TRUE;
249 /* From <dlls/mmdevapi/mmdevapi.h> */
250 enum DriverPriority {
251 Priority_Unavailable = 0,
252 Priority_Low,
253 Priority_Neutral,
254 Priority_Preferred
257 int WINAPI AUDDRV_GetPriority(void)
259 return Priority_Neutral;
262 static void set_device_guid(EDataFlow flow, HKEY drv_key, const WCHAR *key_name,
263 GUID *guid)
265 HKEY key;
266 BOOL opened = FALSE;
267 LONG lr;
269 if(!drv_key){
270 lr = RegCreateKeyExW(HKEY_CURRENT_USER, drv_key_devicesW, 0, NULL, 0, KEY_WRITE,
271 NULL, &drv_key, NULL);
272 if(lr != ERROR_SUCCESS){
273 ERR("RegCreateKeyEx(drv_key) failed: %u\n", lr);
274 return;
276 opened = TRUE;
279 lr = RegCreateKeyExW(drv_key, key_name, 0, NULL, 0, KEY_WRITE,
280 NULL, &key, NULL);
281 if(lr != ERROR_SUCCESS){
282 ERR("RegCreateKeyEx(%s) failed: %u\n", wine_dbgstr_w(key_name), lr);
283 goto exit;
286 lr = RegSetValueExW(key, guidW, 0, REG_BINARY, (BYTE*)guid,
287 sizeof(GUID));
288 if(lr != ERROR_SUCCESS)
289 ERR("RegSetValueEx(%s\\guid) failed: %u\n", wine_dbgstr_w(key_name), lr);
291 RegCloseKey(key);
292 exit:
293 if(opened)
294 RegCloseKey(drv_key);
297 static void get_device_guid(EDataFlow flow, const char *device, GUID *guid)
299 HKEY key = NULL, dev_key;
300 DWORD type, size = sizeof(*guid);
301 WCHAR key_name[256];
303 if(flow == eCapture)
304 key_name[0] = '1';
305 else
306 key_name[0] = '0';
307 key_name[1] = ',';
308 MultiByteToWideChar(CP_UNIXCP, 0, device, -1, key_name + 2,
309 (sizeof(key_name) / sizeof(*key_name)) - 2);
311 if(RegOpenKeyExW(HKEY_CURRENT_USER, drv_key_devicesW, 0, KEY_WRITE|KEY_READ, &key) == ERROR_SUCCESS){
312 if(RegOpenKeyExW(key, key_name, 0, KEY_READ, &dev_key) == ERROR_SUCCESS){
313 if(RegQueryValueExW(dev_key, guidW, 0, &type,
314 (BYTE*)guid, &size) == ERROR_SUCCESS){
315 if(type == REG_BINARY){
316 RegCloseKey(dev_key);
317 RegCloseKey(key);
318 return;
320 ERR("Invalid type for device %s GUID: %u; ignoring and overwriting\n",
321 wine_dbgstr_w(key_name), type);
323 RegCloseKey(dev_key);
327 CoCreateGuid(guid);
329 set_device_guid(flow, key, key_name, guid);
331 if(key)
332 RegCloseKey(key);
335 static BOOL alsa_try_open(const char *devnode, snd_pcm_stream_t stream)
337 snd_pcm_t *handle;
338 int err;
340 TRACE("devnode: %s, stream: %d\n", devnode, stream);
342 if((err = snd_pcm_open(&handle, devnode, stream, SND_PCM_NONBLOCK)) < 0){
343 WARN("The device \"%s\" failed to open: %d (%s).\n",
344 devnode, err, snd_strerror(err));
345 return FALSE;
348 snd_pcm_close(handle);
349 return TRUE;
352 static WCHAR *construct_device_id(EDataFlow flow, const WCHAR *chunk1, const char *chunk2)
354 WCHAR *ret;
355 const WCHAR *prefix;
356 DWORD len_wchars = 0, chunk1_len, copied = 0, prefix_len;
358 static const WCHAR dashW[] = {' ','-',' ',0};
359 static const size_t dashW_len = (sizeof(dashW) / sizeof(*dashW)) - 1;
360 static const WCHAR outW[] = {'O','u','t',':',' ',0};
361 static const WCHAR inW[] = {'I','n',':',' ',0};
363 if(flow == eRender){
364 prefix = outW;
365 prefix_len = (sizeof(outW) / sizeof(*outW)) - 1;
366 len_wchars += prefix_len;
367 }else{
368 prefix = inW;
369 prefix_len = (sizeof(inW) / sizeof(*inW)) - 1;
370 len_wchars += prefix_len;
372 if(chunk1){
373 chunk1_len = strlenW(chunk1);
374 len_wchars += chunk1_len;
376 if(chunk1 && chunk2)
377 len_wchars += dashW_len;
378 if(chunk2)
379 len_wchars += MultiByteToWideChar(CP_UNIXCP, 0, chunk2, -1, NULL, 0) - 1;
380 len_wchars += 1; /* NULL byte */
382 ret = HeapAlloc(GetProcessHeap(), 0, len_wchars * sizeof(WCHAR));
384 memcpy(ret, prefix, prefix_len * sizeof(WCHAR));
385 copied += prefix_len;
386 if(chunk1){
387 memcpy(ret + copied, chunk1, chunk1_len * sizeof(WCHAR));
388 copied += chunk1_len;
390 if(chunk1 && chunk2){
391 memcpy(ret + copied, dashW, dashW_len * sizeof(WCHAR));
392 copied += dashW_len;
394 if(chunk2){
395 MultiByteToWideChar(CP_UNIXCP, 0, chunk2, -1, ret + copied, len_wchars - copied);
396 }else
397 ret[copied] = 0;
399 TRACE("Enumerated device: %s\n", wine_dbgstr_w(ret));
401 return ret;
404 static HRESULT alsa_get_card_devices(EDataFlow flow, snd_pcm_stream_t stream,
405 WCHAR ***ids, GUID **guids, UINT *num, snd_ctl_t *ctl, int card,
406 const WCHAR *cardnameW)
408 int err, device;
409 snd_pcm_info_t *info;
411 info = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, snd_pcm_info_sizeof());
412 if(!info)
413 return E_OUTOFMEMORY;
415 snd_pcm_info_set_subdevice(info, 0);
416 snd_pcm_info_set_stream(info, stream);
418 device = -1;
419 for(err = snd_ctl_pcm_next_device(ctl, &device); device != -1 && err >= 0;
420 err = snd_ctl_pcm_next_device(ctl, &device)){
421 const char *devname;
422 char devnode[32];
424 snd_pcm_info_set_device(info, device);
426 if((err = snd_ctl_pcm_info(ctl, info)) < 0){
427 if(err == -ENOENT)
428 /* This device doesn't have the right stream direction */
429 continue;
431 WARN("Failed to get info for card %d, device %d: %d (%s)\n",
432 card, device, err, snd_strerror(err));
433 continue;
436 sprintf(devnode, "plughw:%d,%d", card, device);
437 if(!alsa_try_open(devnode, stream))
438 continue;
440 if(*num){
441 *ids = HeapReAlloc(GetProcessHeap(), 0, *ids, sizeof(WCHAR *) * (*num + 1));
442 *guids = HeapReAlloc(GetProcessHeap(), 0, *guids, sizeof(GUID) * (*num + 1));
443 }else{
444 *ids = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR *));
445 *guids = HeapAlloc(GetProcessHeap(), 0, sizeof(GUID));
448 devname = snd_pcm_info_get_name(info);
449 if(!devname){
450 WARN("Unable to get device name for card %d, device %d\n", card,
451 device);
452 continue;
455 (*ids)[*num] = construct_device_id(flow, cardnameW, devname);
456 get_device_guid(flow, devnode, &(*guids)[*num]);
458 ++(*num);
461 HeapFree(GetProcessHeap(), 0, info);
463 if(err != 0)
464 WARN("Got a failure during device enumeration on card %d: %d (%s)\n",
465 card, err, snd_strerror(err));
467 return S_OK;
470 static void get_reg_devices(EDataFlow flow, snd_pcm_stream_t stream, WCHAR ***ids,
471 GUID **guids, UINT *num)
473 static const WCHAR ALSAOutputDevices[] = {'A','L','S','A','O','u','t','p','u','t','D','e','v','i','c','e','s',0};
474 static const WCHAR ALSAInputDevices[] = {'A','L','S','A','I','n','p','u','t','D','e','v','i','c','e','s',0};
475 HKEY key;
476 WCHAR reg_devices[256];
477 DWORD size = sizeof(reg_devices), type;
478 const WCHAR *value_name = (stream == SND_PCM_STREAM_PLAYBACK) ? ALSAOutputDevices : ALSAInputDevices;
480 /* @@ Wine registry key: HKCU\Software\Wine\Drivers\winealsa.drv */
481 if(RegOpenKeyW(HKEY_CURRENT_USER, drv_keyW, &key) == ERROR_SUCCESS){
482 if(RegQueryValueExW(key, value_name, 0, &type,
483 (BYTE*)reg_devices, &size) == ERROR_SUCCESS){
484 WCHAR *p = reg_devices;
486 if(type != REG_MULTI_SZ){
487 ERR("Registry ALSA device list value type must be REG_MULTI_SZ\n");
488 RegCloseKey(key);
489 return;
492 while(*p){
493 char devname[64];
495 WideCharToMultiByte(CP_UNIXCP, 0, p, -1, devname, sizeof(devname), NULL, NULL);
497 if(alsa_try_open(devname, stream)){
498 if(*num){
499 *ids = HeapReAlloc(GetProcessHeap(), 0, *ids, sizeof(WCHAR *) * (*num + 1));
500 *guids = HeapReAlloc(GetProcessHeap(), 0, *guids, sizeof(GUID) * (*num + 1));
501 }else{
502 *ids = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR *));
503 *guids = HeapAlloc(GetProcessHeap(), 0, sizeof(GUID));
505 (*ids)[*num] = construct_device_id(flow, p, NULL);
506 get_device_guid(flow, devname, &(*guids)[*num]);
507 ++*num;
510 p += lstrlenW(p) + 1;
514 RegCloseKey(key);
518 static HRESULT alsa_enum_devices(EDataFlow flow, WCHAR ***ids, GUID **guids,
519 UINT *num)
521 snd_pcm_stream_t stream = (flow == eRender ? SND_PCM_STREAM_PLAYBACK :
522 SND_PCM_STREAM_CAPTURE);
523 int err, card;
525 card = -1;
526 *num = 0;
528 if(alsa_try_open(defname, stream)){
529 *ids = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR *));
530 (*ids)[0] = construct_device_id(flow, defaultW, NULL);
531 *guids = HeapAlloc(GetProcessHeap(), 0, sizeof(GUID));
532 get_device_guid(flow, defname, &(*guids)[0]);
533 ++*num;
536 get_reg_devices(flow, stream, ids, guids, num);
538 for(err = snd_card_next(&card); card != -1 && err >= 0;
539 err = snd_card_next(&card)){
540 char cardpath[64];
541 char *cardname;
542 WCHAR *cardnameW;
543 snd_ctl_t *ctl;
544 DWORD len;
546 sprintf(cardpath, "hw:%u", card);
548 if((err = snd_ctl_open(&ctl, cardpath, 0)) < 0){
549 WARN("Unable to open ctl for ALSA device %s: %d (%s)\n", cardpath,
550 err, snd_strerror(err));
551 continue;
554 if(snd_card_get_name(card, &cardname) < 0) {
555 /* FIXME: Should be localized */
556 static const WCHAR nameW[] = {'U','n','k','n','o','w','n',' ','s','o','u','n','d','c','a','r','d',0};
557 WARN("Unable to get card name for ALSA device %s: %d (%s)\n",
558 cardpath, err, snd_strerror(err));
559 alsa_get_card_devices(flow, stream, ids, guids, num, ctl, card, nameW);
560 }else{
561 len = MultiByteToWideChar(CP_UNIXCP, 0, cardname, -1, NULL, 0);
562 cardnameW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
564 if(!cardnameW){
565 free(cardname);
566 snd_ctl_close(ctl);
567 return E_OUTOFMEMORY;
569 MultiByteToWideChar(CP_UNIXCP, 0, cardname, -1, cardnameW, len);
571 alsa_get_card_devices(flow, stream, ids, guids, num, ctl, card, cardnameW);
573 HeapFree(GetProcessHeap(), 0, cardnameW);
574 free(cardname);
577 snd_ctl_close(ctl);
580 if(err != 0)
581 WARN("Got a failure during card enumeration: %d (%s)\n",
582 err, snd_strerror(err));
584 return S_OK;
587 HRESULT WINAPI AUDDRV_GetEndpointIDs(EDataFlow flow, WCHAR ***ids, GUID **guids,
588 UINT *num, UINT *def_index)
590 HRESULT hr;
592 TRACE("%d %p %p %p %p\n", flow, ids, guids, num, def_index);
594 *ids = NULL;
595 *guids = NULL;
597 hr = alsa_enum_devices(flow, ids, guids, num);
598 if(FAILED(hr)){
599 UINT i;
600 for(i = 0; i < *num; ++i)
601 HeapFree(GetProcessHeap(), 0, (*ids)[i]);
602 HeapFree(GetProcessHeap(), 0, *ids);
603 HeapFree(GetProcessHeap(), 0, *guids);
604 return E_OUTOFMEMORY;
607 TRACE("Enumerated %u devices\n", *num);
609 if(*num == 0){
610 HeapFree(GetProcessHeap(), 0, *ids);
611 *ids = NULL;
612 HeapFree(GetProcessHeap(), 0, *guids);
613 *guids = NULL;
616 *def_index = 0;
618 return S_OK;
621 /* Using the pulse PCM device from alsa-plugins 1.0.24 triggers a bug
622 * which causes audio to cease playing after a few minutes of playback.
623 * Setting handle_underrun=1 on pulse-backed ALSA devices seems to work
624 * around this issue. */
625 static snd_config_t *make_handle_underrun_config(const char *name)
627 snd_config_t *lconf, *dev_node, *hu_node, *type_node;
628 char dev_node_name[64];
629 const char *type_str;
630 int err;
632 snd_config_update();
634 if((err = snd_config_copy(&lconf, snd_config)) < 0){
635 WARN("snd_config_copy failed: %d (%s)\n", err, snd_strerror(err));
636 return NULL;
639 sprintf(dev_node_name, "pcm.%s", name);
640 err = snd_config_search(lconf, dev_node_name, &dev_node);
641 if(err == -ENOENT){
642 snd_config_delete(lconf);
643 return NULL;
645 if(err < 0){
646 snd_config_delete(lconf);
647 WARN("snd_config_search failed: %d (%s)\n", err, snd_strerror(err));
648 return NULL;
651 /* ALSA is extremely fragile. If it runs into a config setting it doesn't
652 * recognize, it tends to fail or assert. So we only want to inject
653 * handle_underrun=1 on devices that we know will recognize it. */
654 err = snd_config_search(dev_node, "type", &type_node);
655 if(err == -ENOENT){
656 snd_config_delete(lconf);
657 return NULL;
659 if(err < 0){
660 snd_config_delete(lconf);
661 WARN("snd_config_search failed: %d (%s)\n", err, snd_strerror(err));
662 return NULL;
665 if((err = snd_config_get_string(type_node, &type_str)) < 0){
666 snd_config_delete(lconf);
667 return NULL;
670 if(strcmp(type_str, "pulse") != 0){
671 snd_config_delete(lconf);
672 return NULL;
675 err = snd_config_search(dev_node, "handle_underrun", &hu_node);
676 if(err >= 0){
677 /* user already has an explicit handle_underrun setting, so don't
678 * use a local config */
679 snd_config_delete(lconf);
680 return NULL;
682 if(err != -ENOENT){
683 snd_config_delete(lconf);
684 WARN("snd_config_search failed: %d (%s)\n", err, snd_strerror(err));
685 return NULL;
688 if((err = snd_config_imake_integer(&hu_node, "handle_underrun", 1)) < 0){
689 snd_config_delete(lconf);
690 WARN("snd_config_imake_integer failed: %d (%s)\n", err,
691 snd_strerror(err));
692 return NULL;
695 if((err = snd_config_add(dev_node, hu_node)) < 0){
696 snd_config_delete(lconf);
697 WARN("snd_config_add failed: %d (%s)\n", err, snd_strerror(err));
698 return NULL;
701 return lconf;
704 static BOOL get_alsa_name_by_guid(GUID *guid, char *name, DWORD name_size, EDataFlow *flow)
706 HKEY devices_key;
707 UINT i = 0;
708 WCHAR key_name[256];
709 DWORD key_name_size;
711 if(RegOpenKeyExW(HKEY_CURRENT_USER, drv_key_devicesW, 0, KEY_READ, &devices_key) != ERROR_SUCCESS){
712 ERR("No devices found in registry?\n");
713 return FALSE;
716 while(1){
717 HKEY key;
718 DWORD size, type;
719 GUID reg_guid;
721 key_name_size = sizeof(key_name)/sizeof(WCHAR);
722 if(RegEnumKeyExW(devices_key, i, key_name, &key_name_size, NULL,
723 NULL, NULL, NULL) != ERROR_SUCCESS)
724 break;
726 if(RegOpenKeyExW(devices_key, key_name, 0, KEY_READ, &key) != ERROR_SUCCESS){
727 WARN("Couldn't open key: %s\n", wine_dbgstr_w(key_name));
728 continue;
731 size = sizeof(reg_guid);
732 if(RegQueryValueExW(key, guidW, 0, &type,
733 (BYTE*)&reg_guid, &size) == ERROR_SUCCESS){
734 if(IsEqualGUID(&reg_guid, guid)){
735 RegCloseKey(key);
736 RegCloseKey(devices_key);
738 TRACE("Found matching device key: %s\n", wine_dbgstr_w(key_name));
740 if(key_name[0] == '0')
741 *flow = eRender;
742 else if(key_name[0] == '1')
743 *flow = eCapture;
744 else{
745 ERR("Unknown device type: %c\n", key_name[0]);
746 return FALSE;
749 WideCharToMultiByte(CP_UNIXCP, 0, key_name + 2, -1, name, name_size, NULL, NULL);
751 return TRUE;
755 RegCloseKey(key);
757 ++i;
760 RegCloseKey(devices_key);
762 WARN("No matching device in registry for GUID %s\n", debugstr_guid(guid));
764 return FALSE;
767 HRESULT WINAPI AUDDRV_GetAudioEndpoint(GUID *guid, IMMDevice *dev, IAudioClient **out)
769 ACImpl *This;
770 int err;
771 snd_pcm_stream_t stream;
772 snd_config_t *lconf;
773 static int handle_underrun = 1;
774 char alsa_name[256];
775 EDataFlow dataflow;
776 HRESULT hr;
778 TRACE("%s %p %p\n", debugstr_guid(guid), dev, out);
780 if(!get_alsa_name_by_guid(guid, alsa_name, sizeof(alsa_name), &dataflow))
781 return AUDCLNT_E_DEVICE_INVALIDATED;
783 This = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(ACImpl));
784 if(!This)
785 return E_OUTOFMEMORY;
787 This->IAudioClient_iface.lpVtbl = &AudioClient_Vtbl;
788 This->IAudioRenderClient_iface.lpVtbl = &AudioRenderClient_Vtbl;
789 This->IAudioCaptureClient_iface.lpVtbl = &AudioCaptureClient_Vtbl;
790 This->IAudioClock_iface.lpVtbl = &AudioClock_Vtbl;
791 This->IAudioClock2_iface.lpVtbl = &AudioClock2_Vtbl;
792 This->IAudioStreamVolume_iface.lpVtbl = &AudioStreamVolume_Vtbl;
794 if(dataflow == eRender)
795 stream = SND_PCM_STREAM_PLAYBACK;
796 else if(dataflow == eCapture)
797 stream = SND_PCM_STREAM_CAPTURE;
798 else{
799 HeapFree(GetProcessHeap(), 0, This);
800 return E_UNEXPECTED;
803 hr = CoCreateFreeThreadedMarshaler((IUnknown *)&This->IAudioClient_iface,
804 (IUnknown **)&This->pUnkFTMarshal);
805 if (FAILED(hr)) {
806 HeapFree(GetProcessHeap(), 0, This);
807 return hr;
810 This->dataflow = dataflow;
811 if(handle_underrun && ((lconf = make_handle_underrun_config(alsa_name)))){
812 err = snd_pcm_open_lconf(&This->pcm_handle, alsa_name, stream, SND_PCM_NONBLOCK, lconf);
813 TRACE("Opening PCM device \"%s\" with handle_underrun: %d\n", alsa_name, err);
814 snd_config_delete(lconf);
815 /* Pulse <= 2010 returns EINVAL, it does not know handle_underrun. */
816 if(err == -EINVAL){
817 ERR_(winediag)("PulseAudio \"%s\" %d without handle_underrun. Audio may hang."
818 " Please upgrade to alsa_plugins >= 1.0.24\n", alsa_name, err);
819 handle_underrun = 0;
821 }else
822 err = -EINVAL;
823 if(err == -EINVAL){
824 err = snd_pcm_open(&This->pcm_handle, alsa_name, stream, SND_PCM_NONBLOCK);
826 if(err < 0){
827 HeapFree(GetProcessHeap(), 0, This);
828 WARN("Unable to open PCM \"%s\": %d (%s)\n", alsa_name, err, snd_strerror(err));
829 switch(err){
830 case -EBUSY:
831 return AUDCLNT_E_DEVICE_IN_USE;
832 default:
833 return AUDCLNT_E_ENDPOINT_CREATE_FAILED;
837 This->hw_params = HeapAlloc(GetProcessHeap(), 0,
838 snd_pcm_hw_params_sizeof());
839 if(!This->hw_params){
840 snd_pcm_close(This->pcm_handle);
841 HeapFree(GetProcessHeap(), 0, This);
842 return E_OUTOFMEMORY;
845 InitializeCriticalSection(&This->lock);
846 This->lock.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": ACImpl.lock");
848 This->parent = dev;
849 IMMDevice_AddRef(This->parent);
851 *out = &This->IAudioClient_iface;
852 IAudioClient_AddRef(&This->IAudioClient_iface);
854 return S_OK;
857 static HRESULT WINAPI AudioClient_QueryInterface(IAudioClient *iface,
858 REFIID riid, void **ppv)
860 ACImpl *This = impl_from_IAudioClient(iface);
861 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
863 if(!ppv)
864 return E_POINTER;
865 *ppv = NULL;
866 if(IsEqualIID(riid, &IID_IUnknown) || IsEqualIID(riid, &IID_IAudioClient))
867 *ppv = iface;
868 else if(IsEqualIID(riid, &IID_IMarshal))
869 return IUnknown_QueryInterface(This->pUnkFTMarshal, riid, ppv);
871 if(*ppv){
872 IUnknown_AddRef((IUnknown*)*ppv);
873 return S_OK;
875 WARN("Unknown interface %s\n", debugstr_guid(riid));
876 return E_NOINTERFACE;
879 static ULONG WINAPI AudioClient_AddRef(IAudioClient *iface)
881 ACImpl *This = impl_from_IAudioClient(iface);
882 ULONG ref;
883 ref = InterlockedIncrement(&This->ref);
884 TRACE("(%p) Refcount now %u\n", This, ref);
885 return ref;
888 static ULONG WINAPI AudioClient_Release(IAudioClient *iface)
890 ACImpl *This = impl_from_IAudioClient(iface);
891 ULONG ref;
892 ref = InterlockedDecrement(&This->ref);
893 TRACE("(%p) Refcount now %u\n", This, ref);
894 if(!ref){
895 IAudioClient_Stop(iface);
896 IMMDevice_Release(This->parent);
897 IUnknown_Release(This->pUnkFTMarshal);
898 This->lock.DebugInfo->Spare[0] = 0;
899 DeleteCriticalSection(&This->lock);
900 snd_pcm_drop(This->pcm_handle);
901 snd_pcm_close(This->pcm_handle);
902 if(This->initted){
903 EnterCriticalSection(&g_sessions_lock);
904 list_remove(&This->entry);
905 LeaveCriticalSection(&g_sessions_lock);
907 HeapFree(GetProcessHeap(), 0, This->vols);
908 HeapFree(GetProcessHeap(), 0, This->local_buffer);
909 HeapFree(GetProcessHeap(), 0, This->remapping_buf);
910 HeapFree(GetProcessHeap(), 0, This->tmp_buffer);
911 HeapFree(GetProcessHeap(), 0, This->hw_params);
912 CoTaskMemFree(This->fmt);
913 HeapFree(GetProcessHeap(), 0, This);
915 return ref;
918 static void dump_fmt(const WAVEFORMATEX *fmt)
920 TRACE("wFormatTag: 0x%x (", fmt->wFormatTag);
921 switch(fmt->wFormatTag){
922 case WAVE_FORMAT_PCM:
923 TRACE("WAVE_FORMAT_PCM");
924 break;
925 case WAVE_FORMAT_IEEE_FLOAT:
926 TRACE("WAVE_FORMAT_IEEE_FLOAT");
927 break;
928 case WAVE_FORMAT_EXTENSIBLE:
929 TRACE("WAVE_FORMAT_EXTENSIBLE");
930 break;
931 default:
932 TRACE("Unknown");
933 break;
935 TRACE(")\n");
937 TRACE("nChannels: %u\n", fmt->nChannels);
938 TRACE("nSamplesPerSec: %u\n", fmt->nSamplesPerSec);
939 TRACE("nAvgBytesPerSec: %u\n", fmt->nAvgBytesPerSec);
940 TRACE("nBlockAlign: %u\n", fmt->nBlockAlign);
941 TRACE("wBitsPerSample: %u\n", fmt->wBitsPerSample);
942 TRACE("cbSize: %u\n", fmt->cbSize);
944 if(fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE){
945 WAVEFORMATEXTENSIBLE *fmtex = (void*)fmt;
946 TRACE("dwChannelMask: %08x\n", fmtex->dwChannelMask);
947 TRACE("Samples: %04x\n", fmtex->Samples.wReserved);
948 TRACE("SubFormat: %s\n", wine_dbgstr_guid(&fmtex->SubFormat));
952 static WAVEFORMATEX *clone_format(const WAVEFORMATEX *fmt)
954 WAVEFORMATEX *ret;
955 size_t size;
957 if(fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE)
958 size = sizeof(WAVEFORMATEXTENSIBLE);
959 else
960 size = sizeof(WAVEFORMATEX);
962 ret = CoTaskMemAlloc(size);
963 if(!ret)
964 return NULL;
966 memcpy(ret, fmt, size);
968 ret->cbSize = size - sizeof(WAVEFORMATEX);
970 return ret;
973 static snd_pcm_format_t alsa_format(const WAVEFORMATEX *fmt)
975 snd_pcm_format_t format = SND_PCM_FORMAT_UNKNOWN;
976 const WAVEFORMATEXTENSIBLE *fmtex = (const WAVEFORMATEXTENSIBLE *)fmt;
978 if(fmt->wFormatTag == WAVE_FORMAT_PCM ||
979 (fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
980 IsEqualGUID(&fmtex->SubFormat, &KSDATAFORMAT_SUBTYPE_PCM))){
981 if(fmt->wBitsPerSample == 8)
982 format = SND_PCM_FORMAT_U8;
983 else if(fmt->wBitsPerSample == 16)
984 format = SND_PCM_FORMAT_S16_LE;
985 else if(fmt->wBitsPerSample == 24)
986 format = SND_PCM_FORMAT_S24_3LE;
987 else if(fmt->wBitsPerSample == 32)
988 format = SND_PCM_FORMAT_S32_LE;
989 else
990 WARN("Unsupported bit depth: %u\n", fmt->wBitsPerSample);
991 if(fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
992 fmt->wBitsPerSample != fmtex->Samples.wValidBitsPerSample){
993 if(fmtex->Samples.wValidBitsPerSample == 20 && fmt->wBitsPerSample == 24)
994 format = SND_PCM_FORMAT_S20_3LE;
995 else
996 WARN("Unsupported ValidBits: %u\n", fmtex->Samples.wValidBitsPerSample);
998 }else if(fmt->wFormatTag == WAVE_FORMAT_IEEE_FLOAT ||
999 (fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
1000 IsEqualGUID(&fmtex->SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))){
1001 if(fmt->wBitsPerSample == 32)
1002 format = SND_PCM_FORMAT_FLOAT_LE;
1003 else if(fmt->wBitsPerSample == 64)
1004 format = SND_PCM_FORMAT_FLOAT64_LE;
1005 else
1006 WARN("Unsupported float size: %u\n", fmt->wBitsPerSample);
1007 }else
1008 WARN("Unknown wave format: %04x\n", fmt->wFormatTag);
1009 return format;
1012 static void session_init_vols(AudioSession *session, UINT channels)
1014 if(session->channel_count < channels){
1015 UINT i;
1017 if(session->channel_vols)
1018 session->channel_vols = HeapReAlloc(GetProcessHeap(), 0,
1019 session->channel_vols, sizeof(float) * channels);
1020 else
1021 session->channel_vols = HeapAlloc(GetProcessHeap(), 0,
1022 sizeof(float) * channels);
1023 if(!session->channel_vols)
1024 return;
1026 for(i = session->channel_count; i < channels; ++i)
1027 session->channel_vols[i] = 1.f;
1029 session->channel_count = channels;
1033 static AudioSession *create_session(const GUID *guid, IMMDevice *device,
1034 UINT num_channels)
1036 AudioSession *ret;
1038 ret = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(AudioSession));
1039 if(!ret)
1040 return NULL;
1042 memcpy(&ret->guid, guid, sizeof(GUID));
1044 ret->device = device;
1046 list_init(&ret->clients);
1048 list_add_head(&g_sessions, &ret->entry);
1050 InitializeCriticalSection(&ret->lock);
1051 ret->lock.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": AudioSession.lock");
1053 session_init_vols(ret, num_channels);
1055 ret->master_vol = 1.f;
1057 return ret;
1060 /* if channels == 0, then this will return or create a session with
1061 * matching dataflow and GUID. otherwise, channels must also match */
1062 static HRESULT get_audio_session(const GUID *sessionguid,
1063 IMMDevice *device, UINT channels, AudioSession **out)
1065 AudioSession *session;
1067 if(!sessionguid || IsEqualGUID(sessionguid, &GUID_NULL)){
1068 *out = create_session(&GUID_NULL, device, channels);
1069 if(!*out)
1070 return E_OUTOFMEMORY;
1072 return S_OK;
1075 *out = NULL;
1076 LIST_FOR_EACH_ENTRY(session, &g_sessions, AudioSession, entry){
1077 if(session->device == device &&
1078 IsEqualGUID(sessionguid, &session->guid)){
1079 session_init_vols(session, channels);
1080 *out = session;
1081 break;
1085 if(!*out){
1086 *out = create_session(sessionguid, device, channels);
1087 if(!*out)
1088 return E_OUTOFMEMORY;
1091 return S_OK;
1094 static int alsa_channel_index(DWORD flag)
1096 switch(flag){
1097 case SPEAKER_FRONT_LEFT:
1098 return 0;
1099 case SPEAKER_FRONT_RIGHT:
1100 return 1;
1101 case SPEAKER_BACK_LEFT:
1102 return 2;
1103 case SPEAKER_BACK_RIGHT:
1104 return 3;
1105 case SPEAKER_FRONT_CENTER:
1106 return 4;
1107 case SPEAKER_LOW_FREQUENCY:
1108 return 5;
1109 case SPEAKER_SIDE_LEFT:
1110 return 6;
1111 case SPEAKER_SIDE_RIGHT:
1112 return 7;
1114 return -1;
1117 static BOOL need_remapping(ACImpl *This, const WAVEFORMATEX *fmt)
1119 unsigned int i;
1120 for(i = 0; i < fmt->nChannels; ++i){
1121 if(This->alsa_channel_map[i] != i)
1122 return TRUE;
1124 return FALSE;
1127 static DWORD get_channel_mask(unsigned int channels)
1129 switch(channels){
1130 case 0:
1131 return 0;
1132 case 1:
1133 return KSAUDIO_SPEAKER_MONO;
1134 case 2:
1135 return KSAUDIO_SPEAKER_STEREO;
1136 case 3:
1137 return KSAUDIO_SPEAKER_STEREO | SPEAKER_LOW_FREQUENCY;
1138 case 4:
1139 return KSAUDIO_SPEAKER_QUAD; /* not _SURROUND */
1140 case 5:
1141 return KSAUDIO_SPEAKER_QUAD | SPEAKER_LOW_FREQUENCY;
1142 case 6:
1143 return KSAUDIO_SPEAKER_5POINT1; /* not 5POINT1_SURROUND */
1144 case 7:
1145 return KSAUDIO_SPEAKER_5POINT1 | SPEAKER_BACK_CENTER;
1146 case 8:
1147 return KSAUDIO_SPEAKER_7POINT1_SURROUND; /* Vista deprecates 7POINT1 */
1149 FIXME("Unknown speaker configuration: %u\n", channels);
1150 return 0;
1153 static HRESULT map_channels(ACImpl *This, const WAVEFORMATEX *fmt)
1155 if(fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE || fmt->nChannels > 2){
1156 WAVEFORMATEXTENSIBLE *fmtex = (void*)fmt;
1157 DWORD mask, flag = SPEAKER_FRONT_LEFT;
1158 UINT i = 0;
1160 if(fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
1161 fmtex->dwChannelMask != 0)
1162 mask = fmtex->dwChannelMask;
1163 else
1164 mask = get_channel_mask(fmt->nChannels);
1166 This->alsa_channels = 0;
1168 while(i < fmt->nChannels && !(flag & SPEAKER_RESERVED)){
1169 if(mask & flag){
1170 This->alsa_channel_map[i] = alsa_channel_index(flag);
1171 TRACE("Mapping mmdevapi channel %u (0x%x) to ALSA channel %d\n",
1172 i, flag, This->alsa_channel_map[i]);
1173 if(This->alsa_channel_map[i] >= This->alsa_channels)
1174 This->alsa_channels = This->alsa_channel_map[i] + 1;
1175 ++i;
1177 flag <<= 1;
1180 while(i < fmt->nChannels){
1181 This->alsa_channel_map[i] = This->alsa_channels;
1182 TRACE("Mapping mmdevapi channel %u to ALSA channel %d\n",
1183 i, This->alsa_channel_map[i]);
1184 ++This->alsa_channels;
1185 ++i;
1188 for(i = 0; i < fmt->nChannels; ++i){
1189 if(This->alsa_channel_map[i] == -1){
1190 This->alsa_channel_map[i] = This->alsa_channels;
1191 ++This->alsa_channels;
1192 TRACE("Remapping mmdevapi channel %u to ALSA channel %d\n",
1193 i, This->alsa_channel_map[i]);
1197 This->need_remapping = need_remapping(This, fmt);
1199 TRACE("need_remapping: %u, alsa_channels: %d\n", This->need_remapping, This->alsa_channels);
1200 }else{
1201 This->need_remapping = FALSE;
1202 This->alsa_channels = fmt->nChannels;
1203 TRACE("need_remapping: %u, alsa_channels: %d\n", This->need_remapping, This->alsa_channels);
1206 return S_OK;
1209 static HRESULT WINAPI AudioClient_Initialize(IAudioClient *iface,
1210 AUDCLNT_SHAREMODE mode, DWORD flags, REFERENCE_TIME duration,
1211 REFERENCE_TIME period, const WAVEFORMATEX *fmt,
1212 const GUID *sessionguid)
1214 ACImpl *This = impl_from_IAudioClient(iface);
1215 snd_pcm_sw_params_t *sw_params = NULL;
1216 snd_pcm_format_t format;
1217 unsigned int rate, alsa_period_us;
1218 int err, i;
1219 HRESULT hr = S_OK;
1221 TRACE("(%p)->(%x, %x, %s, %s, %p, %s)\n", This, mode, flags,
1222 wine_dbgstr_longlong(duration), wine_dbgstr_longlong(period), fmt, debugstr_guid(sessionguid));
1224 if(!fmt)
1225 return E_POINTER;
1227 if(mode != AUDCLNT_SHAREMODE_SHARED && mode != AUDCLNT_SHAREMODE_EXCLUSIVE)
1228 return AUDCLNT_E_NOT_INITIALIZED;
1230 if(flags & ~(AUDCLNT_STREAMFLAGS_CROSSPROCESS |
1231 AUDCLNT_STREAMFLAGS_LOOPBACK |
1232 AUDCLNT_STREAMFLAGS_EVENTCALLBACK |
1233 AUDCLNT_STREAMFLAGS_NOPERSIST |
1234 AUDCLNT_STREAMFLAGS_RATEADJUST |
1235 AUDCLNT_SESSIONFLAGS_EXPIREWHENUNOWNED |
1236 AUDCLNT_SESSIONFLAGS_DISPLAY_HIDE |
1237 AUDCLNT_SESSIONFLAGS_DISPLAY_HIDEWHENEXPIRED)){
1238 TRACE("Unknown flags: %08x\n", flags);
1239 return E_INVALIDARG;
1242 if(mode == AUDCLNT_SHAREMODE_SHARED){
1243 period = DefaultPeriod;
1244 if( duration < 3 * period)
1245 duration = 3 * period;
1246 }else{
1247 if(fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE){
1248 if(((WAVEFORMATEXTENSIBLE*)fmt)->dwChannelMask == 0 ||
1249 ((WAVEFORMATEXTENSIBLE*)fmt)->dwChannelMask & SPEAKER_RESERVED)
1250 return AUDCLNT_E_UNSUPPORTED_FORMAT;
1253 if(!period)
1254 period = DefaultPeriod; /* not minimum */
1255 if(period < MinimumPeriod || period > 5000000)
1256 return AUDCLNT_E_INVALID_DEVICE_PERIOD;
1257 if(duration > 20000000) /* the smaller the period, the lower this limit */
1258 return AUDCLNT_E_BUFFER_SIZE_ERROR;
1259 if(flags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK){
1260 if(duration != period)
1261 return AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL;
1262 FIXME("EXCLUSIVE mode with EVENTCALLBACK\n");
1263 return AUDCLNT_E_DEVICE_IN_USE;
1264 }else{
1265 if( duration < 8 * period)
1266 duration = 8 * period; /* may grow above 2s */
1270 EnterCriticalSection(&This->lock);
1272 if(This->initted){
1273 LeaveCriticalSection(&This->lock);
1274 return AUDCLNT_E_ALREADY_INITIALIZED;
1277 dump_fmt(fmt);
1279 if(FAILED(map_channels(This, fmt))){
1280 WARN("map_channels failed\n");
1281 hr = AUDCLNT_E_ENDPOINT_CREATE_FAILED;
1282 goto exit;
1285 if((err = snd_pcm_hw_params_any(This->pcm_handle, This->hw_params)) < 0){
1286 WARN("Unable to get hw_params: %d (%s)\n", err, snd_strerror(err));
1287 hr = AUDCLNT_E_ENDPOINT_CREATE_FAILED;
1288 goto exit;
1291 if((err = snd_pcm_hw_params_set_access(This->pcm_handle, This->hw_params,
1292 SND_PCM_ACCESS_RW_INTERLEAVED)) < 0){
1293 WARN("Unable to set access: %d (%s)\n", err, snd_strerror(err));
1294 hr = AUDCLNT_E_ENDPOINT_CREATE_FAILED;
1295 goto exit;
1298 format = alsa_format(fmt);
1299 if (format == SND_PCM_FORMAT_UNKNOWN){
1300 hr = AUDCLNT_E_UNSUPPORTED_FORMAT;
1301 goto exit;
1304 if((err = snd_pcm_hw_params_set_format(This->pcm_handle, This->hw_params,
1305 format)) < 0){
1306 WARN("Unable to set ALSA format to %u: %d (%s)\n", format, err,
1307 snd_strerror(err));
1308 hr = AUDCLNT_E_UNSUPPORTED_FORMAT;
1309 goto exit;
1312 This->alsa_format = format;
1314 rate = fmt->nSamplesPerSec;
1315 if((err = snd_pcm_hw_params_set_rate_near(This->pcm_handle, This->hw_params,
1316 &rate, NULL)) < 0){
1317 WARN("Unable to set rate to %u: %d (%s)\n", rate, err,
1318 snd_strerror(err));
1319 hr = AUDCLNT_E_UNSUPPORTED_FORMAT;
1320 goto exit;
1323 if((err = snd_pcm_hw_params_set_channels(This->pcm_handle, This->hw_params,
1324 This->alsa_channels)) < 0){
1325 WARN("Unable to set channels to %u: %d (%s)\n", fmt->nChannels, err,
1326 snd_strerror(err));
1327 hr = AUDCLNT_E_UNSUPPORTED_FORMAT;
1328 goto exit;
1331 This->mmdev_period_rt = period;
1332 alsa_period_us = This->mmdev_period_rt / 10;
1333 if((err = snd_pcm_hw_params_set_period_time_near(This->pcm_handle,
1334 This->hw_params, &alsa_period_us, NULL)) < 0)
1335 WARN("Unable to set period time near %u: %d (%s)\n", alsa_period_us,
1336 err, snd_strerror(err));
1337 /* ALSA updates the output variable alsa_period_us */
1339 This->mmdev_period_frames = MulDiv(fmt->nSamplesPerSec,
1340 This->mmdev_period_rt, 10000000);
1342 /* Buffer 4 ALSA periods if large enough, else 4 mmdevapi periods */
1343 This->alsa_bufsize_frames = This->mmdev_period_frames * 4;
1344 if(err < 0 || alsa_period_us < period / 10)
1345 err = snd_pcm_hw_params_set_buffer_size_near(This->pcm_handle,
1346 This->hw_params, &This->alsa_bufsize_frames);
1347 else{
1348 unsigned int periods = 4;
1349 err = snd_pcm_hw_params_set_periods_near(This->pcm_handle, This->hw_params, &periods, NULL);
1351 if(err < 0)
1352 WARN("Unable to set buffer size: %d (%s)\n", err, snd_strerror(err));
1354 if((err = snd_pcm_hw_params(This->pcm_handle, This->hw_params)) < 0){
1355 WARN("Unable to set hw params: %d (%s)\n", err, snd_strerror(err));
1356 hr = AUDCLNT_E_ENDPOINT_CREATE_FAILED;
1357 goto exit;
1360 if((err = snd_pcm_hw_params_get_period_size(This->hw_params,
1361 &This->alsa_period_frames, NULL)) < 0){
1362 WARN("Unable to get period size: %d (%s)\n", err, snd_strerror(err));
1363 hr = AUDCLNT_E_ENDPOINT_CREATE_FAILED;
1364 goto exit;
1367 if((err = snd_pcm_hw_params_get_buffer_size(This->hw_params,
1368 &This->alsa_bufsize_frames)) < 0){
1369 WARN("Unable to get buffer size: %d (%s)\n", err, snd_strerror(err));
1370 hr = AUDCLNT_E_ENDPOINT_CREATE_FAILED;
1371 goto exit;
1374 sw_params = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, snd_pcm_sw_params_sizeof());
1375 if(!sw_params){
1376 hr = E_OUTOFMEMORY;
1377 goto exit;
1380 if((err = snd_pcm_sw_params_current(This->pcm_handle, sw_params)) < 0){
1381 WARN("Unable to get sw_params: %d (%s)\n", err, snd_strerror(err));
1382 hr = AUDCLNT_E_ENDPOINT_CREATE_FAILED;
1383 goto exit;
1386 if((err = snd_pcm_sw_params_set_start_threshold(This->pcm_handle,
1387 sw_params, 1)) < 0){
1388 WARN("Unable set start threshold to 0: %d (%s)\n", err, snd_strerror(err));
1389 hr = AUDCLNT_E_ENDPOINT_CREATE_FAILED;
1390 goto exit;
1393 if((err = snd_pcm_sw_params_set_stop_threshold(This->pcm_handle,
1394 sw_params, This->alsa_bufsize_frames)) < 0){
1395 WARN("Unable set stop threshold to %lu: %d (%s)\n",
1396 This->alsa_bufsize_frames, err, snd_strerror(err));
1397 hr = AUDCLNT_E_ENDPOINT_CREATE_FAILED;
1398 goto exit;
1401 if((err = snd_pcm_sw_params(This->pcm_handle, sw_params)) < 0){
1402 WARN("Unable to set sw params: %d (%s)\n", err, snd_strerror(err));
1403 hr = AUDCLNT_E_ENDPOINT_CREATE_FAILED;
1404 goto exit;
1407 if((err = snd_pcm_prepare(This->pcm_handle)) < 0){
1408 WARN("Unable to prepare device: %d (%s)\n", err, snd_strerror(err));
1409 hr = AUDCLNT_E_ENDPOINT_CREATE_FAILED;
1410 goto exit;
1413 /* Bear in mind weird situations where
1414 * ALSA period (50ms) > mmdevapi buffer (3x10ms)
1415 * or surprising rounding as seen with 22050x8x1 with Pulse:
1416 * ALSA period 220 vs. 221 frames in mmdevapi and
1417 * buffer 883 vs. 2205 frames in mmdevapi! */
1418 This->bufsize_frames = MulDiv(duration, fmt->nSamplesPerSec, 10000000);
1419 This->hidden_frames = This->alsa_period_frames + This->mmdev_period_frames +
1420 MulDiv(fmt->nSamplesPerSec, EXTRA_SAFE_RT, 10000000);
1422 /* Check if the ALSA buffer is so small that it will run out before
1423 * the next MMDevAPI period tick occurs. Allow a little wiggle room
1424 * with 120% of the period time. */
1425 if(This->alsa_bufsize_frames < 1.2 * This->mmdev_period_frames)
1426 FIXME("ALSA buffer time is too small. Expect underruns. (%lu < %u * 1.2)\n",
1427 This->alsa_bufsize_frames, This->mmdev_period_frames);
1429 This->local_buffer = HeapAlloc(GetProcessHeap(), 0,
1430 This->bufsize_frames * fmt->nBlockAlign);
1431 if(!This->local_buffer){
1432 hr = E_OUTOFMEMORY;
1433 goto exit;
1435 if (fmt->wBitsPerSample == 8)
1436 memset(This->local_buffer, 128, This->bufsize_frames * fmt->nBlockAlign);
1437 else
1438 memset(This->local_buffer, 0, This->bufsize_frames * fmt->nBlockAlign);
1440 This->fmt = clone_format(fmt);
1441 if(!This->fmt){
1442 hr = E_OUTOFMEMORY;
1443 goto exit;
1446 This->vols = HeapAlloc(GetProcessHeap(), 0, fmt->nChannels * sizeof(float));
1447 if(!This->vols){
1448 hr = E_OUTOFMEMORY;
1449 goto exit;
1452 for(i = 0; i < fmt->nChannels; ++i)
1453 This->vols[i] = 1.f;
1455 This->share = mode;
1456 This->flags = flags;
1458 EnterCriticalSection(&g_sessions_lock);
1460 hr = get_audio_session(sessionguid, This->parent, fmt->nChannels,
1461 &This->session);
1462 if(FAILED(hr)){
1463 LeaveCriticalSection(&g_sessions_lock);
1464 goto exit;
1467 list_add_tail(&This->session->clients, &This->entry);
1469 LeaveCriticalSection(&g_sessions_lock);
1471 This->initted = TRUE;
1473 TRACE("ALSA period: %lu frames\n", This->alsa_period_frames);
1474 TRACE("ALSA buffer: %lu frames\n", This->alsa_bufsize_frames);
1475 TRACE("MMDevice period: %u frames\n", This->mmdev_period_frames);
1476 TRACE("MMDevice buffer: %u frames\n", This->bufsize_frames);
1478 exit:
1479 HeapFree(GetProcessHeap(), 0, sw_params);
1480 if(FAILED(hr)){
1481 HeapFree(GetProcessHeap(), 0, This->local_buffer);
1482 This->local_buffer = NULL;
1483 CoTaskMemFree(This->fmt);
1484 This->fmt = NULL;
1485 HeapFree(GetProcessHeap(), 0, This->vols);
1486 This->vols = NULL;
1489 LeaveCriticalSection(&This->lock);
1491 return hr;
1494 static HRESULT WINAPI AudioClient_GetBufferSize(IAudioClient *iface,
1495 UINT32 *out)
1497 ACImpl *This = impl_from_IAudioClient(iface);
1499 TRACE("(%p)->(%p)\n", This, out);
1501 if(!out)
1502 return E_POINTER;
1504 EnterCriticalSection(&This->lock);
1506 if(!This->initted){
1507 LeaveCriticalSection(&This->lock);
1508 return AUDCLNT_E_NOT_INITIALIZED;
1511 *out = This->bufsize_frames;
1513 LeaveCriticalSection(&This->lock);
1515 return S_OK;
1518 static HRESULT WINAPI AudioClient_GetStreamLatency(IAudioClient *iface,
1519 REFERENCE_TIME *latency)
1521 ACImpl *This = impl_from_IAudioClient(iface);
1523 TRACE("(%p)->(%p)\n", This, latency);
1525 if(!latency)
1526 return E_POINTER;
1528 EnterCriticalSection(&This->lock);
1530 if(!This->initted){
1531 LeaveCriticalSection(&This->lock);
1532 return AUDCLNT_E_NOT_INITIALIZED;
1535 /* Hide some frames in the ALSA buffer. Allows us to return GetCurrentPadding=0
1536 * yet have enough data left to play (as if it were in native's mixer). Add:
1537 * + mmdevapi_period such that at the end of it, ALSA still has data;
1538 * + EXTRA_SAFE (~4ms) to allow for late callback invocation / fluctuation;
1539 * + alsa_period such that ALSA always has at least one period to play. */
1540 if(This->dataflow == eRender)
1541 *latency = MulDiv(This->hidden_frames, 10000000, This->fmt->nSamplesPerSec);
1542 else
1543 *latency = MulDiv(This->alsa_period_frames, 10000000, This->fmt->nSamplesPerSec)
1544 + This->mmdev_period_rt;
1546 LeaveCriticalSection(&This->lock);
1548 return S_OK;
1551 static HRESULT WINAPI AudioClient_GetCurrentPadding(IAudioClient *iface,
1552 UINT32 *out)
1554 ACImpl *This = impl_from_IAudioClient(iface);
1556 TRACE("(%p)->(%p)\n", This, out);
1558 if(!out)
1559 return E_POINTER;
1561 EnterCriticalSection(&This->lock);
1563 if(!This->initted){
1564 LeaveCriticalSection(&This->lock);
1565 return AUDCLNT_E_NOT_INITIALIZED;
1568 /* padding is solely updated at callback time in shared mode */
1569 *out = This->held_frames;
1571 LeaveCriticalSection(&This->lock);
1573 TRACE("pad: %u\n", *out);
1575 return S_OK;
1578 static HRESULT WINAPI AudioClient_IsFormatSupported(IAudioClient *iface,
1579 AUDCLNT_SHAREMODE mode, const WAVEFORMATEX *fmt,
1580 WAVEFORMATEX **out)
1582 ACImpl *This = impl_from_IAudioClient(iface);
1583 snd_pcm_format_mask_t *formats = NULL;
1584 snd_pcm_format_t format;
1585 HRESULT hr = S_OK;
1586 WAVEFORMATEX *closest = NULL;
1587 unsigned int max = 0, min = 0;
1588 int err;
1590 TRACE("(%p)->(%x, %p, %p)\n", This, mode, fmt, out);
1592 if(!fmt || (mode == AUDCLNT_SHAREMODE_SHARED && !out))
1593 return E_POINTER;
1595 if(mode != AUDCLNT_SHAREMODE_SHARED && mode != AUDCLNT_SHAREMODE_EXCLUSIVE)
1596 return E_INVALIDARG;
1598 if(fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
1599 fmt->cbSize < sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX))
1600 return E_INVALIDARG;
1602 dump_fmt(fmt);
1604 if(out){
1605 *out = NULL;
1606 if(mode != AUDCLNT_SHAREMODE_SHARED)
1607 out = NULL;
1610 if(fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
1611 (fmt->nAvgBytesPerSec == 0 ||
1612 fmt->nBlockAlign == 0 ||
1613 ((WAVEFORMATEXTENSIBLE*)fmt)->Samples.wValidBitsPerSample > fmt->wBitsPerSample))
1614 return E_INVALIDARG;
1616 if(fmt->nChannels == 0)
1617 return AUDCLNT_E_UNSUPPORTED_FORMAT;
1619 EnterCriticalSection(&This->lock);
1621 if((err = snd_pcm_hw_params_any(This->pcm_handle, This->hw_params)) < 0){
1622 hr = AUDCLNT_E_DEVICE_INVALIDATED;
1623 goto exit;
1626 formats = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1627 snd_pcm_format_mask_sizeof());
1628 if(!formats){
1629 hr = E_OUTOFMEMORY;
1630 goto exit;
1633 snd_pcm_hw_params_get_format_mask(This->hw_params, formats);
1634 format = alsa_format(fmt);
1635 if (format == SND_PCM_FORMAT_UNKNOWN ||
1636 !snd_pcm_format_mask_test(formats, format)){
1637 hr = AUDCLNT_E_UNSUPPORTED_FORMAT;
1638 goto exit;
1641 closest = clone_format(fmt);
1642 if(!closest){
1643 hr = E_OUTOFMEMORY;
1644 goto exit;
1647 if((err = snd_pcm_hw_params_get_rate_min(This->hw_params, &min, NULL)) < 0){
1648 hr = AUDCLNT_E_DEVICE_INVALIDATED;
1649 WARN("Unable to get min rate: %d (%s)\n", err, snd_strerror(err));
1650 goto exit;
1653 if((err = snd_pcm_hw_params_get_rate_max(This->hw_params, &max, NULL)) < 0){
1654 hr = AUDCLNT_E_DEVICE_INVALIDATED;
1655 WARN("Unable to get max rate: %d (%s)\n", err, snd_strerror(err));
1656 goto exit;
1659 if(fmt->nSamplesPerSec < min || fmt->nSamplesPerSec > max){
1660 hr = AUDCLNT_E_UNSUPPORTED_FORMAT;
1661 goto exit;
1664 if((err = snd_pcm_hw_params_get_channels_min(This->hw_params, &min)) < 0){
1665 hr = AUDCLNT_E_DEVICE_INVALIDATED;
1666 WARN("Unable to get min channels: %d (%s)\n", err, snd_strerror(err));
1667 goto exit;
1670 if((err = snd_pcm_hw_params_get_channels_max(This->hw_params, &max)) < 0){
1671 hr = AUDCLNT_E_DEVICE_INVALIDATED;
1672 WARN("Unable to get max channels: %d (%s)\n", err, snd_strerror(err));
1673 goto exit;
1675 if(fmt->nChannels > max){
1676 hr = S_FALSE;
1677 closest->nChannels = max;
1678 }else if(fmt->nChannels < min){
1679 hr = S_FALSE;
1680 closest->nChannels = min;
1683 if(FAILED(map_channels(This, fmt))){
1684 hr = AUDCLNT_E_DEVICE_INVALIDATED;
1685 WARN("map_channels failed\n");
1686 goto exit;
1688 if(This->alsa_channels > max){
1689 hr = S_FALSE;
1690 closest->nChannels = max;
1693 if(closest->wFormatTag == WAVE_FORMAT_EXTENSIBLE)
1694 ((WAVEFORMATEXTENSIBLE*)closest)->dwChannelMask = get_channel_mask(closest->nChannels);
1696 if(fmt->nBlockAlign != fmt->nChannels * fmt->wBitsPerSample / 8 ||
1697 fmt->nAvgBytesPerSec != fmt->nBlockAlign * fmt->nSamplesPerSec ||
1698 (fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
1699 ((WAVEFORMATEXTENSIBLE*)fmt)->Samples.wValidBitsPerSample < fmt->wBitsPerSample))
1700 hr = S_FALSE;
1702 if(mode == AUDCLNT_SHAREMODE_EXCLUSIVE &&
1703 fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE){
1704 if(((WAVEFORMATEXTENSIBLE*)fmt)->dwChannelMask == 0 ||
1705 ((WAVEFORMATEXTENSIBLE*)fmt)->dwChannelMask & SPEAKER_RESERVED)
1706 hr = S_FALSE;
1709 exit:
1710 LeaveCriticalSection(&This->lock);
1711 HeapFree(GetProcessHeap(), 0, formats);
1713 if(hr == S_FALSE && !out)
1714 hr = AUDCLNT_E_UNSUPPORTED_FORMAT;
1716 if(hr == S_FALSE && out) {
1717 closest->nBlockAlign =
1718 closest->nChannels * closest->wBitsPerSample / 8;
1719 closest->nAvgBytesPerSec =
1720 closest->nBlockAlign * closest->nSamplesPerSec;
1721 if(closest->wFormatTag == WAVE_FORMAT_EXTENSIBLE)
1722 ((WAVEFORMATEXTENSIBLE*)closest)->Samples.wValidBitsPerSample = closest->wBitsPerSample;
1723 *out = closest;
1724 } else
1725 CoTaskMemFree(closest);
1727 TRACE("returning: %08x\n", hr);
1728 return hr;
1731 static HRESULT WINAPI AudioClient_GetMixFormat(IAudioClient *iface,
1732 WAVEFORMATEX **pwfx)
1734 ACImpl *This = impl_from_IAudioClient(iface);
1735 WAVEFORMATEXTENSIBLE *fmt;
1736 snd_pcm_format_mask_t *formats;
1737 unsigned int max_rate, max_channels;
1738 int err;
1739 HRESULT hr = S_OK;
1741 TRACE("(%p)->(%p)\n", This, pwfx);
1743 if(!pwfx)
1744 return E_POINTER;
1745 *pwfx = NULL;
1747 fmt = CoTaskMemAlloc(sizeof(WAVEFORMATEXTENSIBLE));
1748 if(!fmt)
1749 return E_OUTOFMEMORY;
1751 formats = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, snd_pcm_format_mask_sizeof());
1752 if(!formats){
1753 CoTaskMemFree(fmt);
1754 return E_OUTOFMEMORY;
1757 EnterCriticalSection(&This->lock);
1759 if((err = snd_pcm_hw_params_any(This->pcm_handle, This->hw_params)) < 0){
1760 WARN("Unable to get hw_params: %d (%s)\n", err, snd_strerror(err));
1761 hr = AUDCLNT_E_DEVICE_INVALIDATED;
1762 goto exit;
1765 snd_pcm_hw_params_get_format_mask(This->hw_params, formats);
1767 fmt->Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
1768 if(snd_pcm_format_mask_test(formats, SND_PCM_FORMAT_FLOAT_LE)){
1769 fmt->Format.wBitsPerSample = 32;
1770 fmt->SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
1771 }else if(snd_pcm_format_mask_test(formats, SND_PCM_FORMAT_S16_LE)){
1772 fmt->Format.wBitsPerSample = 16;
1773 fmt->SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
1774 }else if(snd_pcm_format_mask_test(formats, SND_PCM_FORMAT_U8)){
1775 fmt->Format.wBitsPerSample = 8;
1776 fmt->SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
1777 }else if(snd_pcm_format_mask_test(formats, SND_PCM_FORMAT_S32_LE)){
1778 fmt->Format.wBitsPerSample = 32;
1779 fmt->SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
1780 }else if(snd_pcm_format_mask_test(formats, SND_PCM_FORMAT_S24_3LE)){
1781 fmt->Format.wBitsPerSample = 24;
1782 fmt->SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
1783 }else{
1784 ERR("Didn't recognize any available ALSA formats\n");
1785 hr = AUDCLNT_E_DEVICE_INVALIDATED;
1786 goto exit;
1789 if((err = snd_pcm_hw_params_get_channels_max(This->hw_params,
1790 &max_channels)) < 0){
1791 WARN("Unable to get max channels: %d (%s)\n", err, snd_strerror(err));
1792 hr = AUDCLNT_E_DEVICE_INVALIDATED;
1793 goto exit;
1796 if(max_channels > 2)
1797 fmt->Format.nChannels = 2;
1798 else
1799 fmt->Format.nChannels = max_channels;
1801 fmt->dwChannelMask = get_channel_mask(fmt->Format.nChannels);
1803 if((err = snd_pcm_hw_params_get_rate_max(This->hw_params, &max_rate,
1804 NULL)) < 0){
1805 WARN("Unable to get max rate: %d (%s)\n", err, snd_strerror(err));
1806 hr = AUDCLNT_E_DEVICE_INVALIDATED;
1807 goto exit;
1810 if(max_rate >= 48000)
1811 fmt->Format.nSamplesPerSec = 48000;
1812 else if(max_rate >= 44100)
1813 fmt->Format.nSamplesPerSec = 44100;
1814 else if(max_rate >= 22050)
1815 fmt->Format.nSamplesPerSec = 22050;
1816 else if(max_rate >= 11025)
1817 fmt->Format.nSamplesPerSec = 11025;
1818 else if(max_rate >= 8000)
1819 fmt->Format.nSamplesPerSec = 8000;
1820 else{
1821 ERR("Unknown max rate: %u\n", max_rate);
1822 hr = AUDCLNT_E_DEVICE_INVALIDATED;
1823 goto exit;
1826 fmt->Format.nBlockAlign = (fmt->Format.wBitsPerSample *
1827 fmt->Format.nChannels) / 8;
1828 fmt->Format.nAvgBytesPerSec = fmt->Format.nSamplesPerSec *
1829 fmt->Format.nBlockAlign;
1831 fmt->Samples.wValidBitsPerSample = fmt->Format.wBitsPerSample;
1832 fmt->Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX);
1834 dump_fmt((WAVEFORMATEX*)fmt);
1835 *pwfx = (WAVEFORMATEX*)fmt;
1837 exit:
1838 LeaveCriticalSection(&This->lock);
1839 if(FAILED(hr))
1840 CoTaskMemFree(fmt);
1841 HeapFree(GetProcessHeap(), 0, formats);
1843 return hr;
1846 static HRESULT WINAPI AudioClient_GetDevicePeriod(IAudioClient *iface,
1847 REFERENCE_TIME *defperiod, REFERENCE_TIME *minperiod)
1849 ACImpl *This = impl_from_IAudioClient(iface);
1851 TRACE("(%p)->(%p, %p)\n", This, defperiod, minperiod);
1853 if(!defperiod && !minperiod)
1854 return E_POINTER;
1856 if(defperiod)
1857 *defperiod = DefaultPeriod;
1858 if(minperiod)
1859 *minperiod = MinimumPeriod;
1861 return S_OK;
1864 static BYTE *remap_channels(ACImpl *This, BYTE *buf, snd_pcm_uframes_t frames)
1866 snd_pcm_uframes_t i;
1867 UINT c;
1868 UINT bytes_per_sample = This->fmt->wBitsPerSample / 8;
1870 if(!This->need_remapping)
1871 return buf;
1873 if(!This->remapping_buf){
1874 This->remapping_buf = HeapAlloc(GetProcessHeap(), 0,
1875 bytes_per_sample * This->alsa_channels * frames);
1876 This->remapping_buf_frames = frames;
1877 }else if(This->remapping_buf_frames < frames){
1878 This->remapping_buf = HeapReAlloc(GetProcessHeap(), 0, This->remapping_buf,
1879 bytes_per_sample * This->alsa_channels * frames);
1880 This->remapping_buf_frames = frames;
1883 snd_pcm_format_set_silence(This->alsa_format, This->remapping_buf,
1884 frames * This->alsa_channels);
1886 switch(This->fmt->wBitsPerSample){
1887 case 8: {
1888 UINT8 *tgt_buf, *src_buf;
1889 tgt_buf = This->remapping_buf;
1890 src_buf = buf;
1891 for(i = 0; i < frames; ++i){
1892 for(c = 0; c < This->fmt->nChannels; ++c)
1893 tgt_buf[This->alsa_channel_map[c]] = src_buf[c];
1894 tgt_buf += This->alsa_channels;
1895 src_buf += This->fmt->nChannels;
1897 break;
1899 case 16: {
1900 UINT16 *tgt_buf, *src_buf;
1901 tgt_buf = (UINT16*)This->remapping_buf;
1902 src_buf = (UINT16*)buf;
1903 for(i = 0; i < frames; ++i){
1904 for(c = 0; c < This->fmt->nChannels; ++c)
1905 tgt_buf[This->alsa_channel_map[c]] = src_buf[c];
1906 tgt_buf += This->alsa_channels;
1907 src_buf += This->fmt->nChannels;
1910 break;
1911 case 32: {
1912 UINT32 *tgt_buf, *src_buf;
1913 tgt_buf = (UINT32*)This->remapping_buf;
1914 src_buf = (UINT32*)buf;
1915 for(i = 0; i < frames; ++i){
1916 for(c = 0; c < This->fmt->nChannels; ++c)
1917 tgt_buf[This->alsa_channel_map[c]] = src_buf[c];
1918 tgt_buf += This->alsa_channels;
1919 src_buf += This->fmt->nChannels;
1922 break;
1923 default: {
1924 BYTE *tgt_buf, *src_buf;
1925 tgt_buf = This->remapping_buf;
1926 src_buf = buf;
1927 for(i = 0; i < frames; ++i){
1928 for(c = 0; c < This->fmt->nChannels; ++c)
1929 memcpy(&tgt_buf[This->alsa_channel_map[c] * bytes_per_sample],
1930 &src_buf[c * bytes_per_sample], bytes_per_sample);
1931 tgt_buf += This->alsa_channels * bytes_per_sample;
1932 src_buf += This->fmt->nChannels * bytes_per_sample;
1935 break;
1938 return This->remapping_buf;
1941 static snd_pcm_sframes_t alsa_write_best_effort(snd_pcm_t *handle, BYTE *buf,
1942 snd_pcm_uframes_t frames, ACImpl *This, BOOL mute)
1944 snd_pcm_sframes_t written;
1946 if(mute){
1947 int err;
1948 if((err = snd_pcm_format_set_silence(This->alsa_format, buf,
1949 frames * This->fmt->nChannels)) < 0)
1950 WARN("Setting buffer to silence failed: %d (%s)\n", err,
1951 snd_strerror(err));
1954 buf = remap_channels(This, buf, frames);
1956 written = snd_pcm_writei(handle, buf, frames);
1957 if(written < 0){
1958 int ret;
1960 if(written == -EAGAIN)
1961 /* buffer full */
1962 return 0;
1964 WARN("writei failed, recovering: %ld (%s)\n", written,
1965 snd_strerror(written));
1967 ret = snd_pcm_recover(handle, written, 0);
1968 if(ret < 0){
1969 WARN("Could not recover: %d (%s)\n", ret, snd_strerror(ret));
1970 return ret;
1973 written = snd_pcm_writei(handle, buf, frames);
1976 return written;
1979 /* The callback and mmdevapi API functions execute concurrently.
1980 * Shared state & life time after Start:
1981 * This constant until _Release
1982 *->pcm_handle likewise
1983 *->fmt likewise
1984 *->alsa_format, hidden_frames likewise
1985 *->local_buffer, bufsize_frames, alsa_bufsize_frames likewise
1986 *->event Read Only, even constant until _Release(!)
1987 *->started Read Only from cb POV, constant if _Stop kills the cb
1989 *->held_frames is the only R/W object.
1990 *->lcl_offs_frames/wri_offs_frames are written by one side exclusively:
1991 * lcl_offs_frames by CaptureClient & write callback
1992 * wri_offs_frames by read callback & RenderClient
1994 static void alsa_write_data(ACImpl *This)
1996 snd_pcm_sframes_t written, in_alsa;
1997 snd_pcm_uframes_t to_write, avail, write_limit, max_period;
1998 int err;
1999 BYTE *buf =
2000 This->local_buffer + This->lcl_offs_frames * This->fmt->nBlockAlign;
2002 /* this call seems to be required to get an accurate snd_pcm_state() */
2003 avail = snd_pcm_avail_update(This->pcm_handle);
2005 if(snd_pcm_state(This->pcm_handle) == SND_PCM_STATE_XRUN ||
2006 avail > This->alsa_bufsize_frames){
2007 TRACE("XRun state avail %ld, recovering\n", avail);
2009 avail = This->alsa_bufsize_frames;
2011 if((err = snd_pcm_recover(This->pcm_handle, -EPIPE, 1)) < 0)
2012 WARN("snd_pcm_recover failed: %d (%s)\n", err, snd_strerror(err));
2014 if((err = snd_pcm_reset(This->pcm_handle)) < 0)
2015 WARN("snd_pcm_reset failed: %d (%s)\n", err, snd_strerror(err));
2017 if((err = snd_pcm_prepare(This->pcm_handle)) < 0)
2018 WARN("snd_pcm_prepare failed: %d (%s)\n", err, snd_strerror(err));
2019 }else
2020 TRACE("pad: %ld\n", This->alsa_bufsize_frames - avail);
2022 if(This->held_frames == 0)
2023 return;
2025 if(This->lcl_offs_frames + This->held_frames > This->bufsize_frames)
2026 to_write = This->bufsize_frames - This->lcl_offs_frames;
2027 else
2028 to_write = This->held_frames;
2030 max_period = max(This->mmdev_period_frames, This->alsa_period_frames);
2032 /* try to keep 3 ALSA periods or 3 MMDevAPI periods in the ALSA buffer and
2033 * no more */
2034 write_limit = 0;
2035 in_alsa = This->alsa_bufsize_frames - avail;
2036 while(in_alsa + write_limit < max_period * 3)
2037 write_limit += max_period;
2038 if(write_limit == 0)
2039 return;
2041 to_write = min(to_write, write_limit);
2043 /* Add a lead-in when starting with too few frames to ensure
2044 * continuous rendering. Additional benefit: Force ALSA to start.
2045 * GetPosition continues to reflect the speaker position because
2046 * snd_pcm_delay includes buffered frames in its total delay
2047 * and last_pos_frames prevents moving backwards. */
2048 if(!in_alsa && This->held_frames < This->hidden_frames){
2049 UINT32 s_frames = This->hidden_frames - This->held_frames;
2050 BYTE *silence = HeapAlloc(GetProcessHeap(), 0,
2051 s_frames * This->fmt->nBlockAlign);
2053 if(silence){
2054 in_alsa = alsa_write_best_effort(This->pcm_handle,
2055 silence, s_frames, This, TRUE);
2056 TRACE("lead-in %ld\n", in_alsa);
2057 HeapFree(GetProcessHeap(), 0, silence);
2058 if(in_alsa <= 0)
2059 return;
2060 }else
2061 WARN("Couldn't allocate lead-in, expect underrun\n");
2064 written = alsa_write_best_effort(This->pcm_handle, buf, to_write, This,
2065 This->session->mute);
2066 if(written < 0){
2067 WARN("Couldn't write: %ld (%s)\n", written, snd_strerror(written));
2068 return;
2071 This->lcl_offs_frames += written;
2072 This->lcl_offs_frames %= This->bufsize_frames;
2073 This->held_frames -= written;
2075 if(written < to_write){
2076 /* ALSA buffer probably full */
2077 return;
2080 if(This->held_frames && (written < write_limit)){
2081 /* wrapped and have some data back at the start to write */
2082 written = alsa_write_best_effort(This->pcm_handle, This->local_buffer,
2083 min(This->held_frames, write_limit - written), This,
2084 This->session->mute);
2085 if(written < 0){
2086 WARN("Couldn't write: %ld (%s)\n", written, snd_strerror(written));
2087 return;
2090 This->lcl_offs_frames += written;
2091 This->lcl_offs_frames %= This->bufsize_frames;
2092 This->held_frames -= written;
2096 static void alsa_read_data(ACImpl *This)
2098 snd_pcm_sframes_t nread;
2099 UINT32 pos = This->wri_offs_frames, limit = This->held_frames;
2101 /* FIXME: Detect overrun and signal DATA_DISCONTINUITY
2102 * How to count overrun frames and report them as position increase? */
2103 limit = This->bufsize_frames - max(limit, pos);
2105 nread = snd_pcm_readi(This->pcm_handle,
2106 This->local_buffer + pos * This->fmt->nBlockAlign, limit);
2107 TRACE("read %ld from %u limit %u\n", nread, pos, limit);
2108 if(nread < 0){
2109 int ret;
2111 if(nread == -EAGAIN) /* no data yet */
2112 return;
2114 WARN("read failed, recovering: %ld (%s)\n", nread, snd_strerror(nread));
2116 ret = snd_pcm_recover(This->pcm_handle, nread, 0);
2117 if(ret < 0){
2118 WARN("Recover failed: %d (%s)\n", ret, snd_strerror(ret));
2119 return;
2122 nread = snd_pcm_readi(This->pcm_handle,
2123 This->local_buffer + pos * This->fmt->nBlockAlign, limit);
2124 if(nread < 0){
2125 WARN("read failed: %ld (%s)\n", nread, snd_strerror(nread));
2126 return;
2130 if(This->session->mute){
2131 int err;
2132 if((err = snd_pcm_format_set_silence(This->alsa_format,
2133 This->local_buffer + pos * This->fmt->nBlockAlign,
2134 nread)) < 0)
2135 WARN("Setting buffer to silence failed: %d (%s)\n", err,
2136 snd_strerror(err));
2139 This->wri_offs_frames += nread;
2140 This->wri_offs_frames %= This->bufsize_frames;
2141 This->held_frames += nread;
2144 static void CALLBACK alsa_push_buffer_data(void *user, BOOLEAN timer)
2146 ACImpl *This = user;
2148 EnterCriticalSection(&This->lock);
2150 if(This->started){
2151 if(This->dataflow == eRender)
2152 alsa_write_data(This);
2153 else if(This->dataflow == eCapture)
2154 alsa_read_data(This);
2157 LeaveCriticalSection(&This->lock);
2159 if(This->event)
2160 SetEvent(This->event);
2163 static HRESULT WINAPI AudioClient_Start(IAudioClient *iface)
2165 ACImpl *This = impl_from_IAudioClient(iface);
2167 TRACE("(%p)\n", This);
2169 EnterCriticalSection(&This->lock);
2171 if(!This->initted){
2172 LeaveCriticalSection(&This->lock);
2173 return AUDCLNT_E_NOT_INITIALIZED;
2176 if((This->flags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK) && !This->event){
2177 LeaveCriticalSection(&This->lock);
2178 return AUDCLNT_E_EVENTHANDLE_NOT_SET;
2181 if(This->started){
2182 LeaveCriticalSection(&This->lock);
2183 return AUDCLNT_E_NOT_STOPPED;
2186 if(This->dataflow == eCapture){
2187 /* dump any data that might be leftover in the ALSA capture buffer */
2188 snd_pcm_readi(This->pcm_handle, This->local_buffer,
2189 This->bufsize_frames);
2192 if(!CreateTimerQueueTimer(&This->timer, g_timer_q, alsa_push_buffer_data,
2193 This, 0, This->mmdev_period_rt / 10000, WT_EXECUTEINTIMERTHREAD)){
2194 LeaveCriticalSection(&This->lock);
2195 WARN("Unable to create timer: %u\n", GetLastError());
2196 return E_OUTOFMEMORY;
2199 This->started = TRUE;
2201 LeaveCriticalSection(&This->lock);
2203 return S_OK;
2206 static HRESULT WINAPI AudioClient_Stop(IAudioClient *iface)
2208 ACImpl *This = impl_from_IAudioClient(iface);
2209 HANDLE event;
2210 BOOL wait;
2212 TRACE("(%p)\n", This);
2214 EnterCriticalSection(&This->lock);
2216 if(!This->initted){
2217 LeaveCriticalSection(&This->lock);
2218 return AUDCLNT_E_NOT_INITIALIZED;
2221 if(!This->started){
2222 LeaveCriticalSection(&This->lock);
2223 return S_FALSE;
2226 /* Stop without losing written frames or position.
2227 * snd_pcm_pause would be appropriate but is unsupported by dmix.
2228 * snd_pcm_drain yields EAGAIN in NONBLOCK mode, except with Pulse. */
2230 event = CreateEventW(NULL, TRUE, FALSE, NULL);
2231 wait = !DeleteTimerQueueTimer(g_timer_q, This->timer, event);
2232 if(wait)
2233 WARN("DeleteTimerQueueTimer error %u\n", GetLastError());
2234 wait = wait && GetLastError() == ERROR_IO_PENDING;
2236 This->started = FALSE;
2238 LeaveCriticalSection(&This->lock);
2240 if(event && wait)
2241 WaitForSingleObject(event, INFINITE);
2242 CloseHandle(event);
2244 return S_OK;
2247 static HRESULT WINAPI AudioClient_Reset(IAudioClient *iface)
2249 ACImpl *This = impl_from_IAudioClient(iface);
2251 TRACE("(%p)\n", This);
2253 EnterCriticalSection(&This->lock);
2255 if(!This->initted){
2256 LeaveCriticalSection(&This->lock);
2257 return AUDCLNT_E_NOT_INITIALIZED;
2260 if(This->started){
2261 LeaveCriticalSection(&This->lock);
2262 return AUDCLNT_E_NOT_STOPPED;
2265 if(This->getbuf_last){
2266 LeaveCriticalSection(&This->lock);
2267 return AUDCLNT_E_BUFFER_OPERATION_PENDING;
2270 if(snd_pcm_drop(This->pcm_handle) < 0)
2271 WARN("snd_pcm_drop failed\n");
2273 if(snd_pcm_reset(This->pcm_handle) < 0)
2274 WARN("snd_pcm_reset failed\n");
2276 if(snd_pcm_prepare(This->pcm_handle) < 0)
2277 WARN("snd_pcm_prepare failed\n");
2279 if(This->dataflow == eRender){
2280 This->written_frames = 0;
2281 This->last_pos_frames = 0;
2282 }else{
2283 This->written_frames += This->held_frames;
2285 This->held_frames = 0;
2286 This->lcl_offs_frames = 0;
2287 This->wri_offs_frames = 0;
2289 LeaveCriticalSection(&This->lock);
2291 return S_OK;
2294 static HRESULT WINAPI AudioClient_SetEventHandle(IAudioClient *iface,
2295 HANDLE event)
2297 ACImpl *This = impl_from_IAudioClient(iface);
2299 TRACE("(%p)->(%p)\n", This, event);
2301 if(!event)
2302 return E_INVALIDARG;
2304 EnterCriticalSection(&This->lock);
2306 if(!This->initted){
2307 LeaveCriticalSection(&This->lock);
2308 return AUDCLNT_E_NOT_INITIALIZED;
2311 if(!(This->flags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK)){
2312 LeaveCriticalSection(&This->lock);
2313 return AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED;
2316 if (This->event){
2317 LeaveCriticalSection(&This->lock);
2318 FIXME("called twice\n");
2319 return HRESULT_FROM_WIN32(ERROR_INVALID_NAME);
2322 This->event = event;
2324 LeaveCriticalSection(&This->lock);
2326 return S_OK;
2329 static HRESULT WINAPI AudioClient_GetService(IAudioClient *iface, REFIID riid,
2330 void **ppv)
2332 ACImpl *This = impl_from_IAudioClient(iface);
2334 TRACE("(%p)->(%s, %p)\n", This, debugstr_guid(riid), ppv);
2336 if(!ppv)
2337 return E_POINTER;
2338 *ppv = NULL;
2340 EnterCriticalSection(&This->lock);
2342 if(!This->initted){
2343 LeaveCriticalSection(&This->lock);
2344 return AUDCLNT_E_NOT_INITIALIZED;
2347 if(IsEqualIID(riid, &IID_IAudioRenderClient)){
2348 if(This->dataflow != eRender){
2349 LeaveCriticalSection(&This->lock);
2350 return AUDCLNT_E_WRONG_ENDPOINT_TYPE;
2352 IAudioRenderClient_AddRef(&This->IAudioRenderClient_iface);
2353 *ppv = &This->IAudioRenderClient_iface;
2354 }else if(IsEqualIID(riid, &IID_IAudioCaptureClient)){
2355 if(This->dataflow != eCapture){
2356 LeaveCriticalSection(&This->lock);
2357 return AUDCLNT_E_WRONG_ENDPOINT_TYPE;
2359 IAudioCaptureClient_AddRef(&This->IAudioCaptureClient_iface);
2360 *ppv = &This->IAudioCaptureClient_iface;
2361 }else if(IsEqualIID(riid, &IID_IAudioClock)){
2362 IAudioClock_AddRef(&This->IAudioClock_iface);
2363 *ppv = &This->IAudioClock_iface;
2364 }else if(IsEqualIID(riid, &IID_IAudioStreamVolume)){
2365 IAudioStreamVolume_AddRef(&This->IAudioStreamVolume_iface);
2366 *ppv = &This->IAudioStreamVolume_iface;
2367 }else if(IsEqualIID(riid, &IID_IAudioSessionControl)){
2368 if(!This->session_wrapper){
2369 This->session_wrapper = AudioSessionWrapper_Create(This);
2370 if(!This->session_wrapper){
2371 LeaveCriticalSection(&This->lock);
2372 return E_OUTOFMEMORY;
2374 }else
2375 IAudioSessionControl2_AddRef(&This->session_wrapper->IAudioSessionControl2_iface);
2377 *ppv = &This->session_wrapper->IAudioSessionControl2_iface;
2378 }else if(IsEqualIID(riid, &IID_IChannelAudioVolume)){
2379 if(!This->session_wrapper){
2380 This->session_wrapper = AudioSessionWrapper_Create(This);
2381 if(!This->session_wrapper){
2382 LeaveCriticalSection(&This->lock);
2383 return E_OUTOFMEMORY;
2385 }else
2386 IChannelAudioVolume_AddRef(&This->session_wrapper->IChannelAudioVolume_iface);
2388 *ppv = &This->session_wrapper->IChannelAudioVolume_iface;
2389 }else if(IsEqualIID(riid, &IID_ISimpleAudioVolume)){
2390 if(!This->session_wrapper){
2391 This->session_wrapper = AudioSessionWrapper_Create(This);
2392 if(!This->session_wrapper){
2393 LeaveCriticalSection(&This->lock);
2394 return E_OUTOFMEMORY;
2396 }else
2397 ISimpleAudioVolume_AddRef(&This->session_wrapper->ISimpleAudioVolume_iface);
2399 *ppv = &This->session_wrapper->ISimpleAudioVolume_iface;
2402 if(*ppv){
2403 LeaveCriticalSection(&This->lock);
2404 return S_OK;
2407 LeaveCriticalSection(&This->lock);
2409 FIXME("stub %s\n", debugstr_guid(riid));
2410 return E_NOINTERFACE;
2413 static const IAudioClientVtbl AudioClient_Vtbl =
2415 AudioClient_QueryInterface,
2416 AudioClient_AddRef,
2417 AudioClient_Release,
2418 AudioClient_Initialize,
2419 AudioClient_GetBufferSize,
2420 AudioClient_GetStreamLatency,
2421 AudioClient_GetCurrentPadding,
2422 AudioClient_IsFormatSupported,
2423 AudioClient_GetMixFormat,
2424 AudioClient_GetDevicePeriod,
2425 AudioClient_Start,
2426 AudioClient_Stop,
2427 AudioClient_Reset,
2428 AudioClient_SetEventHandle,
2429 AudioClient_GetService
2432 static HRESULT WINAPI AudioRenderClient_QueryInterface(
2433 IAudioRenderClient *iface, REFIID riid, void **ppv)
2435 ACImpl *This = impl_from_IAudioRenderClient(iface);
2436 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
2438 if(!ppv)
2439 return E_POINTER;
2440 *ppv = NULL;
2442 if(IsEqualIID(riid, &IID_IUnknown) ||
2443 IsEqualIID(riid, &IID_IAudioRenderClient))
2444 *ppv = iface;
2445 else if(IsEqualIID(riid, &IID_IMarshal))
2446 return IUnknown_QueryInterface(This->pUnkFTMarshal, riid, ppv);
2448 if(*ppv){
2449 IUnknown_AddRef((IUnknown*)*ppv);
2450 return S_OK;
2453 WARN("Unknown interface %s\n", debugstr_guid(riid));
2454 return E_NOINTERFACE;
2457 static ULONG WINAPI AudioRenderClient_AddRef(IAudioRenderClient *iface)
2459 ACImpl *This = impl_from_IAudioRenderClient(iface);
2460 return AudioClient_AddRef(&This->IAudioClient_iface);
2463 static ULONG WINAPI AudioRenderClient_Release(IAudioRenderClient *iface)
2465 ACImpl *This = impl_from_IAudioRenderClient(iface);
2466 return AudioClient_Release(&This->IAudioClient_iface);
2469 static void silence_buffer(ACImpl *This, BYTE *buffer, UINT32 frames)
2471 WAVEFORMATEXTENSIBLE *fmtex = (WAVEFORMATEXTENSIBLE*)This->fmt;
2472 if((This->fmt->wFormatTag == WAVE_FORMAT_PCM ||
2473 (This->fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
2474 IsEqualGUID(&fmtex->SubFormat, &KSDATAFORMAT_SUBTYPE_PCM))) &&
2475 This->fmt->wBitsPerSample == 8)
2476 memset(buffer, 128, frames * This->fmt->nBlockAlign);
2477 else
2478 memset(buffer, 0, frames * This->fmt->nBlockAlign);
2481 static HRESULT WINAPI AudioRenderClient_GetBuffer(IAudioRenderClient *iface,
2482 UINT32 frames, BYTE **data)
2484 ACImpl *This = impl_from_IAudioRenderClient(iface);
2485 UINT32 write_pos;
2487 TRACE("(%p)->(%u, %p)\n", This, frames, data);
2489 if(!data)
2490 return E_POINTER;
2491 *data = NULL;
2493 EnterCriticalSection(&This->lock);
2495 if(This->getbuf_last){
2496 LeaveCriticalSection(&This->lock);
2497 return AUDCLNT_E_OUT_OF_ORDER;
2500 if(!frames){
2501 LeaveCriticalSection(&This->lock);
2502 return S_OK;
2505 /* held_frames == GetCurrentPadding_nolock(); */
2506 if(This->held_frames + frames > This->bufsize_frames){
2507 LeaveCriticalSection(&This->lock);
2508 return AUDCLNT_E_BUFFER_TOO_LARGE;
2511 write_pos = This->wri_offs_frames;
2512 if(write_pos + frames > This->bufsize_frames){
2513 if(This->tmp_buffer_frames < frames){
2514 HeapFree(GetProcessHeap(), 0, This->tmp_buffer);
2515 This->tmp_buffer = HeapAlloc(GetProcessHeap(), 0,
2516 frames * This->fmt->nBlockAlign);
2517 if(!This->tmp_buffer){
2518 LeaveCriticalSection(&This->lock);
2519 return E_OUTOFMEMORY;
2521 This->tmp_buffer_frames = frames;
2523 *data = This->tmp_buffer;
2524 This->getbuf_last = -frames;
2525 }else{
2526 *data = This->local_buffer + write_pos * This->fmt->nBlockAlign;
2527 This->getbuf_last = frames;
2530 silence_buffer(This, *data, frames);
2532 LeaveCriticalSection(&This->lock);
2534 return S_OK;
2537 static void alsa_wrap_buffer(ACImpl *This, BYTE *buffer, UINT32 written_frames)
2539 snd_pcm_uframes_t write_offs_frames = This->wri_offs_frames;
2540 UINT32 write_offs_bytes = write_offs_frames * This->fmt->nBlockAlign;
2541 snd_pcm_uframes_t chunk_frames = This->bufsize_frames - write_offs_frames;
2542 UINT32 chunk_bytes = chunk_frames * This->fmt->nBlockAlign;
2543 UINT32 written_bytes = written_frames * This->fmt->nBlockAlign;
2545 if(written_bytes <= chunk_bytes){
2546 memcpy(This->local_buffer + write_offs_bytes, buffer, written_bytes);
2547 }else{
2548 memcpy(This->local_buffer + write_offs_bytes, buffer, chunk_bytes);
2549 memcpy(This->local_buffer, buffer + chunk_bytes,
2550 written_bytes - chunk_bytes);
2554 static HRESULT WINAPI AudioRenderClient_ReleaseBuffer(
2555 IAudioRenderClient *iface, UINT32 written_frames, DWORD flags)
2557 ACImpl *This = impl_from_IAudioRenderClient(iface);
2558 BYTE *buffer;
2560 TRACE("(%p)->(%u, %x)\n", This, written_frames, flags);
2562 EnterCriticalSection(&This->lock);
2564 if(!written_frames){
2565 This->getbuf_last = 0;
2566 LeaveCriticalSection(&This->lock);
2567 return S_OK;
2570 if(!This->getbuf_last){
2571 LeaveCriticalSection(&This->lock);
2572 return AUDCLNT_E_OUT_OF_ORDER;
2575 if(written_frames > (This->getbuf_last >= 0 ? This->getbuf_last : -This->getbuf_last)){
2576 LeaveCriticalSection(&This->lock);
2577 return AUDCLNT_E_INVALID_SIZE;
2580 if(This->getbuf_last >= 0)
2581 buffer = This->local_buffer + This->wri_offs_frames * This->fmt->nBlockAlign;
2582 else
2583 buffer = This->tmp_buffer;
2585 if(flags & AUDCLNT_BUFFERFLAGS_SILENT)
2586 silence_buffer(This, buffer, written_frames);
2588 if(This->getbuf_last < 0)
2589 alsa_wrap_buffer(This, buffer, written_frames);
2591 This->wri_offs_frames += written_frames;
2592 This->wri_offs_frames %= This->bufsize_frames;
2593 This->held_frames += written_frames;
2594 This->written_frames += written_frames;
2595 This->getbuf_last = 0;
2597 LeaveCriticalSection(&This->lock);
2599 return S_OK;
2602 static const IAudioRenderClientVtbl AudioRenderClient_Vtbl = {
2603 AudioRenderClient_QueryInterface,
2604 AudioRenderClient_AddRef,
2605 AudioRenderClient_Release,
2606 AudioRenderClient_GetBuffer,
2607 AudioRenderClient_ReleaseBuffer
2610 static HRESULT WINAPI AudioCaptureClient_QueryInterface(
2611 IAudioCaptureClient *iface, REFIID riid, void **ppv)
2613 ACImpl *This = impl_from_IAudioCaptureClient(iface);
2614 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
2616 if(!ppv)
2617 return E_POINTER;
2618 *ppv = NULL;
2620 if(IsEqualIID(riid, &IID_IUnknown) ||
2621 IsEqualIID(riid, &IID_IAudioCaptureClient))
2622 *ppv = iface;
2623 else if(IsEqualIID(riid, &IID_IMarshal))
2624 return IUnknown_QueryInterface(This->pUnkFTMarshal, riid, ppv);
2626 if(*ppv){
2627 IUnknown_AddRef((IUnknown*)*ppv);
2628 return S_OK;
2631 WARN("Unknown interface %s\n", debugstr_guid(riid));
2632 return E_NOINTERFACE;
2635 static ULONG WINAPI AudioCaptureClient_AddRef(IAudioCaptureClient *iface)
2637 ACImpl *This = impl_from_IAudioCaptureClient(iface);
2638 return IAudioClient_AddRef(&This->IAudioClient_iface);
2641 static ULONG WINAPI AudioCaptureClient_Release(IAudioCaptureClient *iface)
2643 ACImpl *This = impl_from_IAudioCaptureClient(iface);
2644 return IAudioClient_Release(&This->IAudioClient_iface);
2647 static HRESULT WINAPI AudioCaptureClient_GetBuffer(IAudioCaptureClient *iface,
2648 BYTE **data, UINT32 *frames, DWORD *flags, UINT64 *devpos,
2649 UINT64 *qpcpos)
2651 ACImpl *This = impl_from_IAudioCaptureClient(iface);
2653 TRACE("(%p)->(%p, %p, %p, %p, %p)\n", This, data, frames, flags,
2654 devpos, qpcpos);
2656 if(!data || !frames || !flags)
2657 return E_POINTER;
2659 EnterCriticalSection(&This->lock);
2661 if(This->getbuf_last){
2662 LeaveCriticalSection(&This->lock);
2663 return AUDCLNT_E_OUT_OF_ORDER;
2666 /* hr = GetNextPacketSize(iface, frames); */
2667 if(This->held_frames < This->mmdev_period_frames){
2668 *frames = 0;
2669 LeaveCriticalSection(&This->lock);
2670 return AUDCLNT_S_BUFFER_EMPTY;
2672 *frames = This->mmdev_period_frames;
2674 if(This->lcl_offs_frames + *frames > This->bufsize_frames){
2675 UINT32 chunk_bytes, offs_bytes, frames_bytes;
2676 if(This->tmp_buffer_frames < *frames){
2677 HeapFree(GetProcessHeap(), 0, This->tmp_buffer);
2678 This->tmp_buffer = HeapAlloc(GetProcessHeap(), 0,
2679 *frames * This->fmt->nBlockAlign);
2680 if(!This->tmp_buffer){
2681 LeaveCriticalSection(&This->lock);
2682 return E_OUTOFMEMORY;
2684 This->tmp_buffer_frames = *frames;
2687 *data = This->tmp_buffer;
2688 chunk_bytes = (This->bufsize_frames - This->lcl_offs_frames) *
2689 This->fmt->nBlockAlign;
2690 offs_bytes = This->lcl_offs_frames * This->fmt->nBlockAlign;
2691 frames_bytes = *frames * This->fmt->nBlockAlign;
2692 memcpy(This->tmp_buffer, This->local_buffer + offs_bytes, chunk_bytes);
2693 memcpy(This->tmp_buffer + chunk_bytes, This->local_buffer,
2694 frames_bytes - chunk_bytes);
2695 }else
2696 *data = This->local_buffer +
2697 This->lcl_offs_frames * This->fmt->nBlockAlign;
2699 This->getbuf_last = *frames;
2700 *flags = 0;
2702 if(devpos)
2703 *devpos = This->written_frames;
2704 if(qpcpos){ /* fixme: qpc of recording time */
2705 LARGE_INTEGER stamp, freq;
2706 QueryPerformanceCounter(&stamp);
2707 QueryPerformanceFrequency(&freq);
2708 *qpcpos = (stamp.QuadPart * (INT64)10000000) / freq.QuadPart;
2711 LeaveCriticalSection(&This->lock);
2713 return *frames ? S_OK : AUDCLNT_S_BUFFER_EMPTY;
2716 static HRESULT WINAPI AudioCaptureClient_ReleaseBuffer(
2717 IAudioCaptureClient *iface, UINT32 done)
2719 ACImpl *This = impl_from_IAudioCaptureClient(iface);
2721 TRACE("(%p)->(%u)\n", This, done);
2723 EnterCriticalSection(&This->lock);
2725 if(!done){
2726 This->getbuf_last = 0;
2727 LeaveCriticalSection(&This->lock);
2728 return S_OK;
2731 if(!This->getbuf_last){
2732 LeaveCriticalSection(&This->lock);
2733 return AUDCLNT_E_OUT_OF_ORDER;
2736 if(This->getbuf_last != done){
2737 LeaveCriticalSection(&This->lock);
2738 return AUDCLNT_E_INVALID_SIZE;
2741 This->written_frames += done;
2742 This->held_frames -= done;
2743 This->lcl_offs_frames += done;
2744 This->lcl_offs_frames %= This->bufsize_frames;
2745 This->getbuf_last = 0;
2747 LeaveCriticalSection(&This->lock);
2749 return S_OK;
2752 static HRESULT WINAPI AudioCaptureClient_GetNextPacketSize(
2753 IAudioCaptureClient *iface, UINT32 *frames)
2755 ACImpl *This = impl_from_IAudioCaptureClient(iface);
2757 TRACE("(%p)->(%p)\n", This, frames);
2759 if(!frames)
2760 return E_POINTER;
2762 EnterCriticalSection(&This->lock);
2764 *frames = This->held_frames < This->mmdev_period_frames ? 0 : This->mmdev_period_frames;
2766 LeaveCriticalSection(&This->lock);
2768 return S_OK;
2771 static const IAudioCaptureClientVtbl AudioCaptureClient_Vtbl =
2773 AudioCaptureClient_QueryInterface,
2774 AudioCaptureClient_AddRef,
2775 AudioCaptureClient_Release,
2776 AudioCaptureClient_GetBuffer,
2777 AudioCaptureClient_ReleaseBuffer,
2778 AudioCaptureClient_GetNextPacketSize
2781 static HRESULT WINAPI AudioClock_QueryInterface(IAudioClock *iface,
2782 REFIID riid, void **ppv)
2784 ACImpl *This = impl_from_IAudioClock(iface);
2786 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
2788 if(!ppv)
2789 return E_POINTER;
2790 *ppv = NULL;
2792 if(IsEqualIID(riid, &IID_IUnknown) || IsEqualIID(riid, &IID_IAudioClock))
2793 *ppv = iface;
2794 else if(IsEqualIID(riid, &IID_IAudioClock2))
2795 *ppv = &This->IAudioClock2_iface;
2796 if(*ppv){
2797 IUnknown_AddRef((IUnknown*)*ppv);
2798 return S_OK;
2801 WARN("Unknown interface %s\n", debugstr_guid(riid));
2802 return E_NOINTERFACE;
2805 static ULONG WINAPI AudioClock_AddRef(IAudioClock *iface)
2807 ACImpl *This = impl_from_IAudioClock(iface);
2808 return IAudioClient_AddRef(&This->IAudioClient_iface);
2811 static ULONG WINAPI AudioClock_Release(IAudioClock *iface)
2813 ACImpl *This = impl_from_IAudioClock(iface);
2814 return IAudioClient_Release(&This->IAudioClient_iface);
2817 static HRESULT WINAPI AudioClock_GetFrequency(IAudioClock *iface, UINT64 *freq)
2819 ACImpl *This = impl_from_IAudioClock(iface);
2821 TRACE("(%p)->(%p)\n", This, freq);
2823 *freq = This->fmt->nSamplesPerSec;
2825 return S_OK;
2828 static HRESULT WINAPI AudioClock_GetPosition(IAudioClock *iface, UINT64 *pos,
2829 UINT64 *qpctime)
2831 ACImpl *This = impl_from_IAudioClock(iface);
2832 UINT64 written_frames, position;
2833 UINT32 held_frames;
2834 int err;
2835 snd_pcm_state_t alsa_state;
2836 snd_pcm_uframes_t avail_frames;
2837 snd_pcm_sframes_t delay_frames;
2839 TRACE("(%p)->(%p, %p)\n", This, pos, qpctime);
2841 if(!pos)
2842 return E_POINTER;
2844 EnterCriticalSection(&This->lock);
2846 /* call required to get accurate snd_pcm_state() */
2847 avail_frames = snd_pcm_avail_update(This->pcm_handle);
2848 alsa_state = snd_pcm_state(This->pcm_handle);
2849 written_frames = This->written_frames;
2850 held_frames = This->held_frames;
2852 err = snd_pcm_delay(This->pcm_handle, &delay_frames);
2853 if(err < 0){
2854 /* old Pulse, shortly after start */
2855 WARN("snd_pcm_delay failed in state %u: %d (%s)\n", alsa_state, err, snd_strerror(err));
2858 if(This->dataflow == eRender){
2859 position = written_frames - held_frames; /* maximum */
2860 if(!This->started || alsa_state > SND_PCM_STATE_RUNNING)
2861 ; /* mmdevapi stopped or ALSA underrun: pretend everything was played */
2862 else if(err<0 || delay_frames > position - This->last_pos_frames)
2863 /* Pulse bug: past underrun, despite recovery, avail_frames & delay
2864 * may be larger than alsa_bufsize_frames, as if cumulating frames. */
2865 /* Pulse bug: EIO(-5) shortly after starting: nothing played */
2866 position = This->last_pos_frames;
2867 else if(delay_frames > 0)
2868 position -= delay_frames;
2869 }else
2870 position = written_frames + held_frames;
2872 /* ensure monotic growth */
2873 This->last_pos_frames = position;
2875 LeaveCriticalSection(&This->lock);
2877 TRACE("frames written: %u, held: %u, avail: %ld, delay: %ld state %d, pos: %u\n",
2878 (UINT32)(written_frames%1000000000), held_frames,
2879 avail_frames, delay_frames, alsa_state, (UINT32)(position%1000000000));
2880 *pos = position;
2882 if(qpctime){
2883 LARGE_INTEGER stamp, freq;
2884 QueryPerformanceCounter(&stamp);
2885 QueryPerformanceFrequency(&freq);
2886 *qpctime = (stamp.QuadPart * (INT64)10000000) / freq.QuadPart;
2889 return S_OK;
2892 static HRESULT WINAPI AudioClock_GetCharacteristics(IAudioClock *iface,
2893 DWORD *chars)
2895 ACImpl *This = impl_from_IAudioClock(iface);
2897 TRACE("(%p)->(%p)\n", This, chars);
2899 if(!chars)
2900 return E_POINTER;
2902 *chars = AUDIOCLOCK_CHARACTERISTIC_FIXED_FREQ;
2904 return S_OK;
2907 static const IAudioClockVtbl AudioClock_Vtbl =
2909 AudioClock_QueryInterface,
2910 AudioClock_AddRef,
2911 AudioClock_Release,
2912 AudioClock_GetFrequency,
2913 AudioClock_GetPosition,
2914 AudioClock_GetCharacteristics
2917 static HRESULT WINAPI AudioClock2_QueryInterface(IAudioClock2 *iface,
2918 REFIID riid, void **ppv)
2920 ACImpl *This = impl_from_IAudioClock2(iface);
2921 return IAudioClock_QueryInterface(&This->IAudioClock_iface, riid, ppv);
2924 static ULONG WINAPI AudioClock2_AddRef(IAudioClock2 *iface)
2926 ACImpl *This = impl_from_IAudioClock2(iface);
2927 return IAudioClient_AddRef(&This->IAudioClient_iface);
2930 static ULONG WINAPI AudioClock2_Release(IAudioClock2 *iface)
2932 ACImpl *This = impl_from_IAudioClock2(iface);
2933 return IAudioClient_Release(&This->IAudioClient_iface);
2936 static HRESULT WINAPI AudioClock2_GetDevicePosition(IAudioClock2 *iface,
2937 UINT64 *pos, UINT64 *qpctime)
2939 ACImpl *This = impl_from_IAudioClock2(iface);
2941 FIXME("(%p)->(%p, %p)\n", This, pos, qpctime);
2943 return E_NOTIMPL;
2946 static const IAudioClock2Vtbl AudioClock2_Vtbl =
2948 AudioClock2_QueryInterface,
2949 AudioClock2_AddRef,
2950 AudioClock2_Release,
2951 AudioClock2_GetDevicePosition
2954 static AudioSessionWrapper *AudioSessionWrapper_Create(ACImpl *client)
2956 AudioSessionWrapper *ret;
2958 ret = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
2959 sizeof(AudioSessionWrapper));
2960 if(!ret)
2961 return NULL;
2963 ret->IAudioSessionControl2_iface.lpVtbl = &AudioSessionControl2_Vtbl;
2964 ret->ISimpleAudioVolume_iface.lpVtbl = &SimpleAudioVolume_Vtbl;
2965 ret->IChannelAudioVolume_iface.lpVtbl = &ChannelAudioVolume_Vtbl;
2967 ret->ref = 1;
2969 ret->client = client;
2970 if(client){
2971 ret->session = client->session;
2972 AudioClient_AddRef(&client->IAudioClient_iface);
2975 return ret;
2978 static HRESULT WINAPI AudioSessionControl_QueryInterface(
2979 IAudioSessionControl2 *iface, REFIID riid, void **ppv)
2981 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
2983 if(!ppv)
2984 return E_POINTER;
2985 *ppv = NULL;
2987 if(IsEqualIID(riid, &IID_IUnknown) ||
2988 IsEqualIID(riid, &IID_IAudioSessionControl) ||
2989 IsEqualIID(riid, &IID_IAudioSessionControl2))
2990 *ppv = iface;
2991 if(*ppv){
2992 IUnknown_AddRef((IUnknown*)*ppv);
2993 return S_OK;
2996 WARN("Unknown interface %s\n", debugstr_guid(riid));
2997 return E_NOINTERFACE;
3000 static ULONG WINAPI AudioSessionControl_AddRef(IAudioSessionControl2 *iface)
3002 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
3003 ULONG ref;
3004 ref = InterlockedIncrement(&This->ref);
3005 TRACE("(%p) Refcount now %u\n", This, ref);
3006 return ref;
3009 static ULONG WINAPI AudioSessionControl_Release(IAudioSessionControl2 *iface)
3011 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
3012 ULONG ref;
3013 ref = InterlockedDecrement(&This->ref);
3014 TRACE("(%p) Refcount now %u\n", This, ref);
3015 if(!ref){
3016 if(This->client){
3017 EnterCriticalSection(&This->client->lock);
3018 This->client->session_wrapper = NULL;
3019 LeaveCriticalSection(&This->client->lock);
3020 AudioClient_Release(&This->client->IAudioClient_iface);
3022 HeapFree(GetProcessHeap(), 0, This);
3024 return ref;
3027 static HRESULT WINAPI AudioSessionControl_GetState(IAudioSessionControl2 *iface,
3028 AudioSessionState *state)
3030 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
3031 ACImpl *client;
3033 TRACE("(%p)->(%p)\n", This, state);
3035 if(!state)
3036 return NULL_PTR_ERR;
3038 EnterCriticalSection(&g_sessions_lock);
3040 if(list_empty(&This->session->clients)){
3041 *state = AudioSessionStateExpired;
3042 LeaveCriticalSection(&g_sessions_lock);
3043 return S_OK;
3046 LIST_FOR_EACH_ENTRY(client, &This->session->clients, ACImpl, entry){
3047 EnterCriticalSection(&client->lock);
3048 if(client->started){
3049 *state = AudioSessionStateActive;
3050 LeaveCriticalSection(&client->lock);
3051 LeaveCriticalSection(&g_sessions_lock);
3052 return S_OK;
3054 LeaveCriticalSection(&client->lock);
3057 LeaveCriticalSection(&g_sessions_lock);
3059 *state = AudioSessionStateInactive;
3061 return S_OK;
3064 static HRESULT WINAPI AudioSessionControl_GetDisplayName(
3065 IAudioSessionControl2 *iface, WCHAR **name)
3067 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
3069 FIXME("(%p)->(%p) - stub\n", This, name);
3071 return E_NOTIMPL;
3074 static HRESULT WINAPI AudioSessionControl_SetDisplayName(
3075 IAudioSessionControl2 *iface, const WCHAR *name, const GUID *session)
3077 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
3079 FIXME("(%p)->(%p, %s) - stub\n", This, name, debugstr_guid(session));
3081 return E_NOTIMPL;
3084 static HRESULT WINAPI AudioSessionControl_GetIconPath(
3085 IAudioSessionControl2 *iface, WCHAR **path)
3087 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
3089 FIXME("(%p)->(%p) - stub\n", This, path);
3091 return E_NOTIMPL;
3094 static HRESULT WINAPI AudioSessionControl_SetIconPath(
3095 IAudioSessionControl2 *iface, const WCHAR *path, const GUID *session)
3097 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
3099 FIXME("(%p)->(%p, %s) - stub\n", This, path, debugstr_guid(session));
3101 return E_NOTIMPL;
3104 static HRESULT WINAPI AudioSessionControl_GetGroupingParam(
3105 IAudioSessionControl2 *iface, GUID *group)
3107 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
3109 FIXME("(%p)->(%p) - stub\n", This, group);
3111 return E_NOTIMPL;
3114 static HRESULT WINAPI AudioSessionControl_SetGroupingParam(
3115 IAudioSessionControl2 *iface, const GUID *group, const GUID *session)
3117 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
3119 FIXME("(%p)->(%s, %s) - stub\n", This, debugstr_guid(group),
3120 debugstr_guid(session));
3122 return E_NOTIMPL;
3125 static HRESULT WINAPI AudioSessionControl_RegisterAudioSessionNotification(
3126 IAudioSessionControl2 *iface, IAudioSessionEvents *events)
3128 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
3130 FIXME("(%p)->(%p) - stub\n", This, events);
3132 return S_OK;
3135 static HRESULT WINAPI AudioSessionControl_UnregisterAudioSessionNotification(
3136 IAudioSessionControl2 *iface, IAudioSessionEvents *events)
3138 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
3140 FIXME("(%p)->(%p) - stub\n", This, events);
3142 return S_OK;
3145 static HRESULT WINAPI AudioSessionControl_GetSessionIdentifier(
3146 IAudioSessionControl2 *iface, WCHAR **id)
3148 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
3150 FIXME("(%p)->(%p) - stub\n", This, id);
3152 return E_NOTIMPL;
3155 static HRESULT WINAPI AudioSessionControl_GetSessionInstanceIdentifier(
3156 IAudioSessionControl2 *iface, WCHAR **id)
3158 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
3160 FIXME("(%p)->(%p) - stub\n", This, id);
3162 return E_NOTIMPL;
3165 static HRESULT WINAPI AudioSessionControl_GetProcessId(
3166 IAudioSessionControl2 *iface, DWORD *pid)
3168 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
3170 TRACE("(%p)->(%p)\n", This, pid);
3172 if(!pid)
3173 return E_POINTER;
3175 *pid = GetCurrentProcessId();
3177 return S_OK;
3180 static HRESULT WINAPI AudioSessionControl_IsSystemSoundsSession(
3181 IAudioSessionControl2 *iface)
3183 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
3185 TRACE("(%p)\n", This);
3187 return S_FALSE;
3190 static HRESULT WINAPI AudioSessionControl_SetDuckingPreference(
3191 IAudioSessionControl2 *iface, BOOL optout)
3193 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
3195 TRACE("(%p)->(%d)\n", This, optout);
3197 return S_OK;
3200 static const IAudioSessionControl2Vtbl AudioSessionControl2_Vtbl =
3202 AudioSessionControl_QueryInterface,
3203 AudioSessionControl_AddRef,
3204 AudioSessionControl_Release,
3205 AudioSessionControl_GetState,
3206 AudioSessionControl_GetDisplayName,
3207 AudioSessionControl_SetDisplayName,
3208 AudioSessionControl_GetIconPath,
3209 AudioSessionControl_SetIconPath,
3210 AudioSessionControl_GetGroupingParam,
3211 AudioSessionControl_SetGroupingParam,
3212 AudioSessionControl_RegisterAudioSessionNotification,
3213 AudioSessionControl_UnregisterAudioSessionNotification,
3214 AudioSessionControl_GetSessionIdentifier,
3215 AudioSessionControl_GetSessionInstanceIdentifier,
3216 AudioSessionControl_GetProcessId,
3217 AudioSessionControl_IsSystemSoundsSession,
3218 AudioSessionControl_SetDuckingPreference
3221 static HRESULT WINAPI SimpleAudioVolume_QueryInterface(
3222 ISimpleAudioVolume *iface, REFIID riid, void **ppv)
3224 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
3226 if(!ppv)
3227 return E_POINTER;
3228 *ppv = NULL;
3230 if(IsEqualIID(riid, &IID_IUnknown) ||
3231 IsEqualIID(riid, &IID_ISimpleAudioVolume))
3232 *ppv = iface;
3233 if(*ppv){
3234 IUnknown_AddRef((IUnknown*)*ppv);
3235 return S_OK;
3238 WARN("Unknown interface %s\n", debugstr_guid(riid));
3239 return E_NOINTERFACE;
3242 static ULONG WINAPI SimpleAudioVolume_AddRef(ISimpleAudioVolume *iface)
3244 AudioSessionWrapper *This = impl_from_ISimpleAudioVolume(iface);
3245 return AudioSessionControl_AddRef(&This->IAudioSessionControl2_iface);
3248 static ULONG WINAPI SimpleAudioVolume_Release(ISimpleAudioVolume *iface)
3250 AudioSessionWrapper *This = impl_from_ISimpleAudioVolume(iface);
3251 return AudioSessionControl_Release(&This->IAudioSessionControl2_iface);
3254 static HRESULT WINAPI SimpleAudioVolume_SetMasterVolume(
3255 ISimpleAudioVolume *iface, float level, const GUID *context)
3257 AudioSessionWrapper *This = impl_from_ISimpleAudioVolume(iface);
3258 AudioSession *session = This->session;
3260 TRACE("(%p)->(%f, %s)\n", session, level, wine_dbgstr_guid(context));
3262 if(level < 0.f || level > 1.f)
3263 return E_INVALIDARG;
3265 if(context)
3266 FIXME("Notifications not supported yet\n");
3268 TRACE("ALSA does not support volume control\n");
3270 EnterCriticalSection(&session->lock);
3272 session->master_vol = level;
3274 LeaveCriticalSection(&session->lock);
3276 return S_OK;
3279 static HRESULT WINAPI SimpleAudioVolume_GetMasterVolume(
3280 ISimpleAudioVolume *iface, float *level)
3282 AudioSessionWrapper *This = impl_from_ISimpleAudioVolume(iface);
3283 AudioSession *session = This->session;
3285 TRACE("(%p)->(%p)\n", session, level);
3287 if(!level)
3288 return NULL_PTR_ERR;
3290 *level = session->master_vol;
3292 return S_OK;
3295 static HRESULT WINAPI SimpleAudioVolume_SetMute(ISimpleAudioVolume *iface,
3296 BOOL mute, const GUID *context)
3298 AudioSessionWrapper *This = impl_from_ISimpleAudioVolume(iface);
3299 AudioSession *session = This->session;
3301 TRACE("(%p)->(%u, %p)\n", session, mute, context);
3303 if(context)
3304 FIXME("Notifications not supported yet\n");
3306 session->mute = mute;
3308 return S_OK;
3311 static HRESULT WINAPI SimpleAudioVolume_GetMute(ISimpleAudioVolume *iface,
3312 BOOL *mute)
3314 AudioSessionWrapper *This = impl_from_ISimpleAudioVolume(iface);
3315 AudioSession *session = This->session;
3317 TRACE("(%p)->(%p)\n", session, mute);
3319 if(!mute)
3320 return NULL_PTR_ERR;
3322 *mute = session->mute;
3324 return S_OK;
3327 static const ISimpleAudioVolumeVtbl SimpleAudioVolume_Vtbl =
3329 SimpleAudioVolume_QueryInterface,
3330 SimpleAudioVolume_AddRef,
3331 SimpleAudioVolume_Release,
3332 SimpleAudioVolume_SetMasterVolume,
3333 SimpleAudioVolume_GetMasterVolume,
3334 SimpleAudioVolume_SetMute,
3335 SimpleAudioVolume_GetMute
3338 static HRESULT WINAPI AudioStreamVolume_QueryInterface(
3339 IAudioStreamVolume *iface, REFIID riid, void **ppv)
3341 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
3343 if(!ppv)
3344 return E_POINTER;
3345 *ppv = NULL;
3347 if(IsEqualIID(riid, &IID_IUnknown) ||
3348 IsEqualIID(riid, &IID_IAudioStreamVolume))
3349 *ppv = iface;
3350 if(*ppv){
3351 IUnknown_AddRef((IUnknown*)*ppv);
3352 return S_OK;
3355 WARN("Unknown interface %s\n", debugstr_guid(riid));
3356 return E_NOINTERFACE;
3359 static ULONG WINAPI AudioStreamVolume_AddRef(IAudioStreamVolume *iface)
3361 ACImpl *This = impl_from_IAudioStreamVolume(iface);
3362 return IAudioClient_AddRef(&This->IAudioClient_iface);
3365 static ULONG WINAPI AudioStreamVolume_Release(IAudioStreamVolume *iface)
3367 ACImpl *This = impl_from_IAudioStreamVolume(iface);
3368 return IAudioClient_Release(&This->IAudioClient_iface);
3371 static HRESULT WINAPI AudioStreamVolume_GetChannelCount(
3372 IAudioStreamVolume *iface, UINT32 *out)
3374 ACImpl *This = impl_from_IAudioStreamVolume(iface);
3376 TRACE("(%p)->(%p)\n", This, out);
3378 if(!out)
3379 return E_POINTER;
3381 *out = This->fmt->nChannels;
3383 return S_OK;
3386 static HRESULT WINAPI AudioStreamVolume_SetChannelVolume(
3387 IAudioStreamVolume *iface, UINT32 index, float level)
3389 ACImpl *This = impl_from_IAudioStreamVolume(iface);
3391 TRACE("(%p)->(%d, %f)\n", This, index, level);
3393 if(level < 0.f || level > 1.f)
3394 return E_INVALIDARG;
3396 if(index >= This->fmt->nChannels)
3397 return E_INVALIDARG;
3399 TRACE("ALSA does not support volume control\n");
3401 EnterCriticalSection(&This->lock);
3403 This->vols[index] = level;
3405 LeaveCriticalSection(&This->lock);
3407 return S_OK;
3410 static HRESULT WINAPI AudioStreamVolume_GetChannelVolume(
3411 IAudioStreamVolume *iface, UINT32 index, float *level)
3413 ACImpl *This = impl_from_IAudioStreamVolume(iface);
3415 TRACE("(%p)->(%d, %p)\n", This, index, level);
3417 if(!level)
3418 return E_POINTER;
3420 if(index >= This->fmt->nChannels)
3421 return E_INVALIDARG;
3423 *level = This->vols[index];
3425 return S_OK;
3428 static HRESULT WINAPI AudioStreamVolume_SetAllVolumes(
3429 IAudioStreamVolume *iface, UINT32 count, const float *levels)
3431 ACImpl *This = impl_from_IAudioStreamVolume(iface);
3432 unsigned int i;
3434 TRACE("(%p)->(%d, %p)\n", This, count, levels);
3436 if(!levels)
3437 return E_POINTER;
3439 if(count != This->fmt->nChannels)
3440 return E_INVALIDARG;
3442 TRACE("ALSA does not support volume control\n");
3444 EnterCriticalSection(&This->lock);
3446 for(i = 0; i < count; ++i)
3447 This->vols[i] = levels[i];
3449 LeaveCriticalSection(&This->lock);
3451 return S_OK;
3454 static HRESULT WINAPI AudioStreamVolume_GetAllVolumes(
3455 IAudioStreamVolume *iface, UINT32 count, float *levels)
3457 ACImpl *This = impl_from_IAudioStreamVolume(iface);
3458 unsigned int i;
3460 TRACE("(%p)->(%d, %p)\n", This, count, levels);
3462 if(!levels)
3463 return E_POINTER;
3465 if(count != This->fmt->nChannels)
3466 return E_INVALIDARG;
3468 EnterCriticalSection(&This->lock);
3470 for(i = 0; i < count; ++i)
3471 levels[i] = This->vols[i];
3473 LeaveCriticalSection(&This->lock);
3475 return S_OK;
3478 static const IAudioStreamVolumeVtbl AudioStreamVolume_Vtbl =
3480 AudioStreamVolume_QueryInterface,
3481 AudioStreamVolume_AddRef,
3482 AudioStreamVolume_Release,
3483 AudioStreamVolume_GetChannelCount,
3484 AudioStreamVolume_SetChannelVolume,
3485 AudioStreamVolume_GetChannelVolume,
3486 AudioStreamVolume_SetAllVolumes,
3487 AudioStreamVolume_GetAllVolumes
3490 static HRESULT WINAPI ChannelAudioVolume_QueryInterface(
3491 IChannelAudioVolume *iface, REFIID riid, void **ppv)
3493 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
3495 if(!ppv)
3496 return E_POINTER;
3497 *ppv = NULL;
3499 if(IsEqualIID(riid, &IID_IUnknown) ||
3500 IsEqualIID(riid, &IID_IChannelAudioVolume))
3501 *ppv = iface;
3502 if(*ppv){
3503 IUnknown_AddRef((IUnknown*)*ppv);
3504 return S_OK;
3507 WARN("Unknown interface %s\n", debugstr_guid(riid));
3508 return E_NOINTERFACE;
3511 static ULONG WINAPI ChannelAudioVolume_AddRef(IChannelAudioVolume *iface)
3513 AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
3514 return AudioSessionControl_AddRef(&This->IAudioSessionControl2_iface);
3517 static ULONG WINAPI ChannelAudioVolume_Release(IChannelAudioVolume *iface)
3519 AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
3520 return AudioSessionControl_Release(&This->IAudioSessionControl2_iface);
3523 static HRESULT WINAPI ChannelAudioVolume_GetChannelCount(
3524 IChannelAudioVolume *iface, UINT32 *out)
3526 AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
3527 AudioSession *session = This->session;
3529 TRACE("(%p)->(%p)\n", session, out);
3531 if(!out)
3532 return NULL_PTR_ERR;
3534 *out = session->channel_count;
3536 return S_OK;
3539 static HRESULT WINAPI ChannelAudioVolume_SetChannelVolume(
3540 IChannelAudioVolume *iface, UINT32 index, float level,
3541 const GUID *context)
3543 AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
3544 AudioSession *session = This->session;
3546 TRACE("(%p)->(%d, %f, %s)\n", session, index, level,
3547 wine_dbgstr_guid(context));
3549 if(level < 0.f || level > 1.f)
3550 return E_INVALIDARG;
3552 if(index >= session->channel_count)
3553 return E_INVALIDARG;
3555 if(context)
3556 FIXME("Notifications not supported yet\n");
3558 TRACE("ALSA does not support volume control\n");
3560 EnterCriticalSection(&session->lock);
3562 session->channel_vols[index] = level;
3564 LeaveCriticalSection(&session->lock);
3566 return S_OK;
3569 static HRESULT WINAPI ChannelAudioVolume_GetChannelVolume(
3570 IChannelAudioVolume *iface, UINT32 index, float *level)
3572 AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
3573 AudioSession *session = This->session;
3575 TRACE("(%p)->(%d, %p)\n", session, index, level);
3577 if(!level)
3578 return NULL_PTR_ERR;
3580 if(index >= session->channel_count)
3581 return E_INVALIDARG;
3583 *level = session->channel_vols[index];
3585 return S_OK;
3588 static HRESULT WINAPI ChannelAudioVolume_SetAllVolumes(
3589 IChannelAudioVolume *iface, UINT32 count, const float *levels,
3590 const GUID *context)
3592 AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
3593 AudioSession *session = This->session;
3594 unsigned int i;
3596 TRACE("(%p)->(%d, %p, %s)\n", session, count, levels,
3597 wine_dbgstr_guid(context));
3599 if(!levels)
3600 return NULL_PTR_ERR;
3602 if(count != session->channel_count)
3603 return E_INVALIDARG;
3605 if(context)
3606 FIXME("Notifications not supported yet\n");
3608 TRACE("ALSA does not support volume control\n");
3610 EnterCriticalSection(&session->lock);
3612 for(i = 0; i < count; ++i)
3613 session->channel_vols[i] = levels[i];
3615 LeaveCriticalSection(&session->lock);
3617 return S_OK;
3620 static HRESULT WINAPI ChannelAudioVolume_GetAllVolumes(
3621 IChannelAudioVolume *iface, UINT32 count, float *levels)
3623 AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
3624 AudioSession *session = This->session;
3625 unsigned int i;
3627 TRACE("(%p)->(%d, %p)\n", session, count, levels);
3629 if(!levels)
3630 return NULL_PTR_ERR;
3632 if(count != session->channel_count)
3633 return E_INVALIDARG;
3635 for(i = 0; i < count; ++i)
3636 levels[i] = session->channel_vols[i];
3638 return S_OK;
3641 static const IChannelAudioVolumeVtbl ChannelAudioVolume_Vtbl =
3643 ChannelAudioVolume_QueryInterface,
3644 ChannelAudioVolume_AddRef,
3645 ChannelAudioVolume_Release,
3646 ChannelAudioVolume_GetChannelCount,
3647 ChannelAudioVolume_SetChannelVolume,
3648 ChannelAudioVolume_GetChannelVolume,
3649 ChannelAudioVolume_SetAllVolumes,
3650 ChannelAudioVolume_GetAllVolumes
3653 static HRESULT WINAPI AudioSessionManager_QueryInterface(IAudioSessionManager2 *iface,
3654 REFIID riid, void **ppv)
3656 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
3658 if(!ppv)
3659 return E_POINTER;
3660 *ppv = NULL;
3662 if(IsEqualIID(riid, &IID_IUnknown) ||
3663 IsEqualIID(riid, &IID_IAudioSessionManager) ||
3664 IsEqualIID(riid, &IID_IAudioSessionManager2))
3665 *ppv = iface;
3666 if(*ppv){
3667 IUnknown_AddRef((IUnknown*)*ppv);
3668 return S_OK;
3671 WARN("Unknown interface %s\n", debugstr_guid(riid));
3672 return E_NOINTERFACE;
3675 static ULONG WINAPI AudioSessionManager_AddRef(IAudioSessionManager2 *iface)
3677 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
3678 ULONG ref;
3679 ref = InterlockedIncrement(&This->ref);
3680 TRACE("(%p) Refcount now %u\n", This, ref);
3681 return ref;
3684 static ULONG WINAPI AudioSessionManager_Release(IAudioSessionManager2 *iface)
3686 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
3687 ULONG ref;
3688 ref = InterlockedDecrement(&This->ref);
3689 TRACE("(%p) Refcount now %u\n", This, ref);
3690 if(!ref)
3691 HeapFree(GetProcessHeap(), 0, This);
3692 return ref;
3695 static HRESULT WINAPI AudioSessionManager_GetAudioSessionControl(
3696 IAudioSessionManager2 *iface, const GUID *session_guid, DWORD flags,
3697 IAudioSessionControl **out)
3699 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
3700 AudioSession *session;
3701 AudioSessionWrapper *wrapper;
3702 HRESULT hr;
3704 TRACE("(%p)->(%s, %x, %p)\n", This, debugstr_guid(session_guid),
3705 flags, out);
3707 hr = get_audio_session(session_guid, This->device, 0, &session);
3708 if(FAILED(hr))
3709 return hr;
3711 wrapper = AudioSessionWrapper_Create(NULL);
3712 if(!wrapper)
3713 return E_OUTOFMEMORY;
3715 wrapper->session = session;
3717 *out = (IAudioSessionControl*)&wrapper->IAudioSessionControl2_iface;
3719 return S_OK;
3722 static HRESULT WINAPI AudioSessionManager_GetSimpleAudioVolume(
3723 IAudioSessionManager2 *iface, const GUID *session_guid, DWORD flags,
3724 ISimpleAudioVolume **out)
3726 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
3727 AudioSession *session;
3728 AudioSessionWrapper *wrapper;
3729 HRESULT hr;
3731 TRACE("(%p)->(%s, %x, %p)\n", This, debugstr_guid(session_guid),
3732 flags, out);
3734 hr = get_audio_session(session_guid, This->device, 0, &session);
3735 if(FAILED(hr))
3736 return hr;
3738 wrapper = AudioSessionWrapper_Create(NULL);
3739 if(!wrapper)
3740 return E_OUTOFMEMORY;
3742 wrapper->session = session;
3744 *out = &wrapper->ISimpleAudioVolume_iface;
3746 return S_OK;
3749 static HRESULT WINAPI AudioSessionManager_GetSessionEnumerator(
3750 IAudioSessionManager2 *iface, IAudioSessionEnumerator **out)
3752 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
3753 FIXME("(%p)->(%p) - stub\n", This, out);
3754 return E_NOTIMPL;
3757 static HRESULT WINAPI AudioSessionManager_RegisterSessionNotification(
3758 IAudioSessionManager2 *iface, IAudioSessionNotification *notification)
3760 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
3761 FIXME("(%p)->(%p) - stub\n", This, notification);
3762 return E_NOTIMPL;
3765 static HRESULT WINAPI AudioSessionManager_UnregisterSessionNotification(
3766 IAudioSessionManager2 *iface, IAudioSessionNotification *notification)
3768 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
3769 FIXME("(%p)->(%p) - stub\n", This, notification);
3770 return E_NOTIMPL;
3773 static HRESULT WINAPI AudioSessionManager_RegisterDuckNotification(
3774 IAudioSessionManager2 *iface, const WCHAR *session_id,
3775 IAudioVolumeDuckNotification *notification)
3777 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
3778 FIXME("(%p)->(%p) - stub\n", This, notification);
3779 return E_NOTIMPL;
3782 static HRESULT WINAPI AudioSessionManager_UnregisterDuckNotification(
3783 IAudioSessionManager2 *iface,
3784 IAudioVolumeDuckNotification *notification)
3786 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
3787 FIXME("(%p)->(%p) - stub\n", This, notification);
3788 return E_NOTIMPL;
3791 static const IAudioSessionManager2Vtbl AudioSessionManager2_Vtbl =
3793 AudioSessionManager_QueryInterface,
3794 AudioSessionManager_AddRef,
3795 AudioSessionManager_Release,
3796 AudioSessionManager_GetAudioSessionControl,
3797 AudioSessionManager_GetSimpleAudioVolume,
3798 AudioSessionManager_GetSessionEnumerator,
3799 AudioSessionManager_RegisterSessionNotification,
3800 AudioSessionManager_UnregisterSessionNotification,
3801 AudioSessionManager_RegisterDuckNotification,
3802 AudioSessionManager_UnregisterDuckNotification
3805 HRESULT WINAPI AUDDRV_GetAudioSessionManager(IMMDevice *device,
3806 IAudioSessionManager2 **out)
3808 SessionMgr *This;
3810 This = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(SessionMgr));
3811 if(!This)
3812 return E_OUTOFMEMORY;
3814 This->IAudioSessionManager2_iface.lpVtbl = &AudioSessionManager2_Vtbl;
3815 This->device = device;
3816 This->ref = 1;
3818 *out = &This->IAudioSessionManager2_iface;
3820 return S_OK;