winepulse v18: Latency and compilation improvements
[wine/multimedia.git] / dlls / winepulse.drv / mmdevdrv.c
blob8e76826f855259337a9bd8b93268e6130fb1163c
1 /*
2 * Copyright 2011-2012 Maarten Lankhorst
3 * Copyright 2010-2011 Maarten Lankhorst for CodeWeavers
4 * Copyright 2011 Andrew Eikum for CodeWeavers
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20 * Pulseaudio driver support.. hell froze over
23 #define NONAMELESSUNION
24 #define COBJMACROS
25 #include "config.h"
26 #include <poll.h>
27 #include <pthread.h>
29 #include <stdarg.h>
30 #include <unistd.h>
31 #include <math.h>
32 #include <stdio.h>
34 #include <pulse/pulseaudio.h>
36 #include "windef.h"
37 #include "winbase.h"
38 #include "winnls.h"
39 #include "winreg.h"
40 #include "wine/debug.h"
41 #include "wine/unicode.h"
42 #include "wine/list.h"
44 #include "ole2.h"
45 #include "dshow.h"
46 #include "dsound.h"
47 #include "propsys.h"
49 #include "initguid.h"
50 #include "ks.h"
51 #include "ksmedia.h"
52 #include "mmdeviceapi.h"
53 #include "audioclient.h"
54 #include "endpointvolume.h"
55 #include "audiopolicy.h"
57 #include "wine/list.h"
59 #define NULL_PTR_ERR MAKE_HRESULT(SEVERITY_ERROR, FACILITY_WIN32, RPC_X_NULL_REF_POINTER)
61 WINE_DEFAULT_DEBUG_CHANNEL(pulse);
62 WINE_DECLARE_DEBUG_CHANNEL(winediag);
64 static const REFERENCE_TIME MinimumPeriod = 30000;
65 static const REFERENCE_TIME DefaultPeriod = 100000;
67 static pa_context *pulse_ctx;
68 static pa_mainloop *pulse_ml;
70 static HANDLE pulse_thread;
71 static pthread_mutex_t pulse_lock = PTHREAD_MUTEX_INITIALIZER;
72 static pthread_cond_t pulse_cond = PTHREAD_COND_INITIALIZER;
73 static struct list g_sessions = LIST_INIT(g_sessions);
75 /* Mixer format + period times */
76 static WAVEFORMATEXTENSIBLE pulse_fmt[2];
77 static REFERENCE_TIME pulse_min_period[2], pulse_def_period[2];
79 static DWORD pulse_stream_volume;
81 const WCHAR pulse_keyW[] = {'S','o','f','t','w','a','r','e','\\',
82 'W','i','n','e','\\','P','u','l','s','e',0};
83 const WCHAR pulse_streamW[] = { 'S','t','r','e','a','m','V','o','l',0 };
85 static HANDLE warn_once;
87 BOOL WINAPI DllMain(HINSTANCE dll, DWORD reason, void *reserved)
89 if (reason == DLL_PROCESS_ATTACH) {
90 HKEY key;
91 if (RegOpenKeyW(HKEY_CURRENT_USER, pulse_keyW, &key) == ERROR_SUCCESS) {
92 DWORD size = sizeof(pulse_stream_volume);
93 RegQueryValueExW(key, pulse_streamW, 0, NULL,
94 (BYTE*)&pulse_stream_volume, &size);
95 RegCloseKey(key);
97 DisableThreadLibraryCalls(dll);
98 } else if (reason == DLL_PROCESS_DETACH) {
99 if (pulse_ctx) {
100 pa_context_disconnect(pulse_ctx);
101 pa_context_unref(pulse_ctx);
103 if (pulse_ml)
104 pa_mainloop_quit(pulse_ml, 0);
105 if (pulse_thread)
106 CloseHandle(pulse_thread);
107 if (warn_once)
108 CloseHandle(warn_once);
110 return TRUE;
113 typedef struct ACImpl ACImpl;
115 typedef struct _AudioSession {
116 GUID guid;
117 struct list clients;
119 IMMDevice *device;
121 float master_vol;
122 UINT32 channel_count;
123 float *channel_vols;
124 BOOL mute;
126 struct list entry;
127 } AudioSession;
129 typedef struct _AudioSessionWrapper {
130 IAudioSessionControl2 IAudioSessionControl2_iface;
131 IChannelAudioVolume IChannelAudioVolume_iface;
132 ISimpleAudioVolume ISimpleAudioVolume_iface;
134 LONG ref;
136 ACImpl *client;
137 AudioSession *session;
138 } AudioSessionWrapper;
140 typedef struct _ACPacket {
141 struct list entry;
142 UINT64 qpcpos;
143 BYTE *data;
144 UINT32 discont;
145 } ACPacket;
147 struct ACImpl {
148 IAudioClient IAudioClient_iface;
149 IAudioRenderClient IAudioRenderClient_iface;
150 IAudioCaptureClient IAudioCaptureClient_iface;
151 IAudioClock IAudioClock_iface;
152 IAudioClock2 IAudioClock2_iface;
153 IAudioStreamVolume IAudioStreamVolume_iface;
154 IMMDevice *parent;
155 struct list entry;
156 float vol[PA_CHANNELS_MAX];
158 LONG ref;
159 EDataFlow dataflow;
160 DWORD flags;
161 AUDCLNT_SHAREMODE share;
162 HANDLE event;
164 UINT32 bufsize_frames, bufsize_bytes, locked, capture_period, pad, started, peek_ofs;
165 void *locked_ptr, *tmp_buffer;
167 pa_stream *stream;
168 pa_sample_spec ss;
169 pa_channel_map map;
171 INT64 clock_lastpos, clock_written;
173 AudioSession *session;
174 AudioSessionWrapper *session_wrapper;
175 struct list packet_free_head;
176 struct list packet_filled_head;
179 static const WCHAR defaultW[] = {'P','u','l','s','e','a','u','d','i','o',0};
181 static const IAudioClientVtbl AudioClient_Vtbl;
182 static const IAudioRenderClientVtbl AudioRenderClient_Vtbl;
183 static const IAudioCaptureClientVtbl AudioCaptureClient_Vtbl;
184 static const IAudioSessionControl2Vtbl AudioSessionControl2_Vtbl;
185 static const ISimpleAudioVolumeVtbl SimpleAudioVolume_Vtbl;
186 static const IChannelAudioVolumeVtbl ChannelAudioVolume_Vtbl;
187 static const IAudioClockVtbl AudioClock_Vtbl;
188 static const IAudioClock2Vtbl AudioClock2_Vtbl;
189 static const IAudioStreamVolumeVtbl AudioStreamVolume_Vtbl;
191 static AudioSessionWrapper *AudioSessionWrapper_Create(ACImpl *client);
193 static inline ACImpl *impl_from_IAudioClient(IAudioClient *iface)
195 return CONTAINING_RECORD(iface, ACImpl, IAudioClient_iface);
198 static inline ACImpl *impl_from_IAudioRenderClient(IAudioRenderClient *iface)
200 return CONTAINING_RECORD(iface, ACImpl, IAudioRenderClient_iface);
203 static inline ACImpl *impl_from_IAudioCaptureClient(IAudioCaptureClient *iface)
205 return CONTAINING_RECORD(iface, ACImpl, IAudioCaptureClient_iface);
208 static inline AudioSessionWrapper *impl_from_IAudioSessionControl2(IAudioSessionControl2 *iface)
210 return CONTAINING_RECORD(iface, AudioSessionWrapper, IAudioSessionControl2_iface);
213 static inline AudioSessionWrapper *impl_from_ISimpleAudioVolume(ISimpleAudioVolume *iface)
215 return CONTAINING_RECORD(iface, AudioSessionWrapper, ISimpleAudioVolume_iface);
218 static inline AudioSessionWrapper *impl_from_IChannelAudioVolume(IChannelAudioVolume *iface)
220 return CONTAINING_RECORD(iface, AudioSessionWrapper, IChannelAudioVolume_iface);
223 static inline ACImpl *impl_from_IAudioClock(IAudioClock *iface)
225 return CONTAINING_RECORD(iface, ACImpl, IAudioClock_iface);
228 static inline ACImpl *impl_from_IAudioClock2(IAudioClock2 *iface)
230 return CONTAINING_RECORD(iface, ACImpl, IAudioClock2_iface);
233 static inline ACImpl *impl_from_IAudioStreamVolume(IAudioStreamVolume *iface)
235 return CONTAINING_RECORD(iface, ACImpl, IAudioStreamVolume_iface);
238 /* Following pulseaudio design here, mainloop has the lock taken whenever
239 * it is handling something for pulse, and the lock is required whenever
240 * doing any pa_* call that can affect the state in any way
242 * pa_cond_wait is used when waiting on results, because the mainloop needs
243 * the same lock taken to affect the state
245 * This is basically the same as the pa_threaded_mainloop implementation,
246 * but that cannot be used because it uses pthread_create directly
248 * pa_threaded_mainloop_(un)lock -> pthread_mutex_(un)lock
249 * pa_threaded_mainloop_signal -> pthread_cond_signal
250 * pa_threaded_mainloop_wait -> pthread_cond_wait
253 static int pulse_poll_func(struct pollfd *ufds, unsigned long nfds, int timeout, void *userdata) {
254 int r;
255 pthread_mutex_unlock(&pulse_lock);
256 r = poll(ufds, nfds, timeout);
257 pthread_mutex_lock(&pulse_lock);
258 return r;
261 static DWORD CALLBACK pulse_mainloop_thread(void *tmp) {
262 int ret;
263 pulse_ml = pa_mainloop_new();
264 pa_mainloop_set_poll_func(pulse_ml, pulse_poll_func, NULL);
265 pthread_mutex_lock(&pulse_lock);
266 pthread_cond_signal(&pulse_cond);
267 pa_mainloop_run(pulse_ml, &ret);
268 pthread_mutex_unlock(&pulse_lock);
269 pa_mainloop_free(pulse_ml);
270 CloseHandle(pulse_thread);
271 return ret;
274 static void pulse_contextcallback(pa_context *c, void *userdata);
275 static void pulse_stream_state(pa_stream *s, void *user);
277 static const enum pa_channel_position pulse_pos_from_wfx[] = {
278 PA_CHANNEL_POSITION_FRONT_LEFT,
279 PA_CHANNEL_POSITION_FRONT_RIGHT,
280 PA_CHANNEL_POSITION_FRONT_CENTER,
281 PA_CHANNEL_POSITION_LFE,
282 PA_CHANNEL_POSITION_REAR_LEFT,
283 PA_CHANNEL_POSITION_REAR_RIGHT,
284 PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER,
285 PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER,
286 PA_CHANNEL_POSITION_REAR_CENTER,
287 PA_CHANNEL_POSITION_SIDE_LEFT,
288 PA_CHANNEL_POSITION_SIDE_RIGHT,
289 PA_CHANNEL_POSITION_TOP_CENTER,
290 PA_CHANNEL_POSITION_TOP_FRONT_LEFT,
291 PA_CHANNEL_POSITION_TOP_FRONT_CENTER,
292 PA_CHANNEL_POSITION_TOP_FRONT_RIGHT,
293 PA_CHANNEL_POSITION_TOP_REAR_LEFT,
294 PA_CHANNEL_POSITION_TOP_REAR_CENTER,
295 PA_CHANNEL_POSITION_TOP_REAR_RIGHT
298 static void pulse_probe_settings(int render, WAVEFORMATEXTENSIBLE *fmt) {
299 WAVEFORMATEX *wfx = &fmt->Format;
300 pa_stream *stream;
301 pa_channel_map map;
302 pa_sample_spec ss;
303 pa_buffer_attr attr;
304 int ret, i;
305 unsigned int length = 0;
307 pa_channel_map_init_auto(&map, 2, PA_CHANNEL_MAP_ALSA);
308 ss.rate = 48000;
309 ss.format = PA_SAMPLE_FLOAT32LE;
310 ss.channels = map.channels;
312 attr.maxlength = -1;
313 attr.tlength = -1;
314 attr.minreq = attr.fragsize = pa_frame_size(&ss);
315 attr.prebuf = 0;
317 stream = pa_stream_new(pulse_ctx, "format test stream", &ss, &map);
318 if (stream)
319 pa_stream_set_state_callback(stream, pulse_stream_state, NULL);
320 if (!stream)
321 ret = -1;
322 else if (render)
323 ret = pa_stream_connect_playback(stream, NULL, &attr,
324 PA_STREAM_START_CORKED|PA_STREAM_FIX_RATE|PA_STREAM_FIX_CHANNELS|PA_STREAM_EARLY_REQUESTS, NULL, NULL);
325 else
326 ret = pa_stream_connect_record(stream, NULL, &attr, PA_STREAM_START_CORKED|PA_STREAM_FIX_RATE|PA_STREAM_FIX_CHANNELS|PA_STREAM_EARLY_REQUESTS);
327 if (ret >= 0) {
328 while (pa_stream_get_state(stream) == PA_STREAM_CREATING)
329 pthread_cond_wait(&pulse_cond, &pulse_lock);
330 if (pa_stream_get_state(stream) == PA_STREAM_READY) {
331 ss = *pa_stream_get_sample_spec(stream);
332 map = *pa_stream_get_channel_map(stream);
333 if (render)
334 length = pa_stream_get_buffer_attr(stream)->minreq;
335 else
336 length = pa_stream_get_buffer_attr(stream)->fragsize;
337 pa_stream_disconnect(stream);
338 while (pa_stream_get_state(stream) == PA_STREAM_READY)
339 pthread_cond_wait(&pulse_cond, &pulse_lock);
342 if (stream)
343 pa_stream_unref(stream);
344 if (length)
345 pulse_def_period[!render] = pulse_min_period[!render] = pa_bytes_to_usec(10 * length, &ss);
346 else
347 pulse_min_period[!render] = MinimumPeriod;
348 if (pulse_def_period[!render] <= DefaultPeriod)
349 pulse_def_period[!render] = DefaultPeriod;
351 wfx->wFormatTag = WAVE_FORMAT_EXTENSIBLE;
352 wfx->cbSize = sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX);
353 wfx->nChannels = ss.channels;
354 wfx->wBitsPerSample = 8 * pa_sample_size_of_format(ss.format);
355 wfx->nSamplesPerSec = ss.rate;
356 wfx->nBlockAlign = pa_frame_size(&ss);
357 wfx->nAvgBytesPerSec = wfx->nSamplesPerSec * wfx->nBlockAlign;
358 if (ss.format != PA_SAMPLE_S24_32LE)
359 fmt->Samples.wValidBitsPerSample = wfx->wBitsPerSample;
360 else
361 fmt->Samples.wValidBitsPerSample = 24;
362 if (ss.format == PA_SAMPLE_FLOAT32LE)
363 fmt->SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
364 else
365 fmt->SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
367 fmt->dwChannelMask = 0;
368 for (i = 0; i < map.channels; ++i)
369 switch (map.map[i]) {
370 default: FIXME("Unhandled channel %s\n", pa_channel_position_to_string(map.map[i])); break;
371 case PA_CHANNEL_POSITION_FRONT_LEFT: fmt->dwChannelMask |= SPEAKER_FRONT_LEFT; break;
372 case PA_CHANNEL_POSITION_MONO:
373 case PA_CHANNEL_POSITION_FRONT_CENTER: fmt->dwChannelMask |= SPEAKER_FRONT_CENTER; break;
374 case PA_CHANNEL_POSITION_FRONT_RIGHT: fmt->dwChannelMask |= SPEAKER_FRONT_RIGHT; break;
375 case PA_CHANNEL_POSITION_REAR_LEFT: fmt->dwChannelMask |= SPEAKER_BACK_LEFT; break;
376 case PA_CHANNEL_POSITION_REAR_CENTER: fmt->dwChannelMask |= SPEAKER_BACK_CENTER; break;
377 case PA_CHANNEL_POSITION_REAR_RIGHT: fmt->dwChannelMask |= SPEAKER_BACK_RIGHT; break;
378 case PA_CHANNEL_POSITION_LFE: fmt->dwChannelMask |= SPEAKER_LOW_FREQUENCY; break;
379 case PA_CHANNEL_POSITION_SIDE_LEFT: fmt->dwChannelMask |= SPEAKER_SIDE_LEFT; break;
380 case PA_CHANNEL_POSITION_SIDE_RIGHT: fmt->dwChannelMask |= SPEAKER_SIDE_RIGHT; break;
381 case PA_CHANNEL_POSITION_TOP_CENTER: fmt->dwChannelMask |= SPEAKER_TOP_CENTER; break;
382 case PA_CHANNEL_POSITION_TOP_FRONT_LEFT: fmt->dwChannelMask |= SPEAKER_TOP_FRONT_LEFT; break;
383 case PA_CHANNEL_POSITION_TOP_FRONT_CENTER: fmt->dwChannelMask |= SPEAKER_TOP_FRONT_CENTER; break;
384 case PA_CHANNEL_POSITION_TOP_FRONT_RIGHT: fmt->dwChannelMask |= SPEAKER_TOP_FRONT_RIGHT; break;
385 case PA_CHANNEL_POSITION_TOP_REAR_LEFT: fmt->dwChannelMask |= SPEAKER_TOP_BACK_LEFT; break;
386 case PA_CHANNEL_POSITION_TOP_REAR_CENTER: fmt->dwChannelMask |= SPEAKER_TOP_BACK_CENTER; break;
387 case PA_CHANNEL_POSITION_TOP_REAR_RIGHT: fmt->dwChannelMask |= SPEAKER_TOP_BACK_RIGHT; break;
391 static HRESULT pulse_connect(void)
393 int len;
394 WCHAR path[PATH_MAX], *name;
395 char *str;
397 if (!pulse_thread)
399 if (!(pulse_thread = CreateThread(NULL, 0, pulse_mainloop_thread, NULL, 0, NULL)))
401 ERR("Failed to create mainloop thread.");
402 return E_FAIL;
404 SetThreadPriority(pulse_thread, THREAD_PRIORITY_TIME_CRITICAL);
405 pthread_cond_wait(&pulse_cond, &pulse_lock);
408 if (pulse_ctx && PA_CONTEXT_IS_GOOD(pa_context_get_state(pulse_ctx)))
409 return S_OK;
410 if (pulse_ctx)
411 pa_context_unref(pulse_ctx);
413 GetModuleFileNameW(NULL, path, sizeof(path)/sizeof(*path));
414 name = strrchrW(path, '\\');
415 if (!name)
416 name = path;
417 else
418 name++;
419 len = WideCharToMultiByte(CP_UNIXCP, 0, name, -1, NULL, 0, NULL, NULL);
420 str = pa_xmalloc(len);
421 WideCharToMultiByte(CP_UNIXCP, 0, name, -1, str, len, NULL, NULL);
422 TRACE("Name: %s\n", str);
423 pulse_ctx = pa_context_new(pa_mainloop_get_api(pulse_ml), str);
424 pa_xfree(str);
425 if (!pulse_ctx) {
426 ERR("Failed to create context\n");
427 return E_FAIL;
430 pa_context_set_state_callback(pulse_ctx, pulse_contextcallback, NULL);
432 TRACE("libpulse protocol version: %u. API Version %u\n", pa_context_get_protocol_version(pulse_ctx), PA_API_VERSION);
433 if (pa_context_connect(pulse_ctx, NULL, 0, NULL) < 0)
434 goto fail;
436 /* Wait for connection */
437 while (pthread_cond_wait(&pulse_cond, &pulse_lock)) {
438 pa_context_state_t state = pa_context_get_state(pulse_ctx);
440 if (state == PA_CONTEXT_FAILED || state == PA_CONTEXT_TERMINATED)
441 goto fail;
443 if (state == PA_CONTEXT_READY)
444 break;
447 TRACE("Connected to server %s with protocol version: %i.\n",
448 pa_context_get_server(pulse_ctx),
449 pa_context_get_server_protocol_version(pulse_ctx));
450 pulse_probe_settings(1, &pulse_fmt[0]);
451 pulse_probe_settings(0, &pulse_fmt[1]);
452 return S_OK;
454 fail:
455 pa_context_unref(pulse_ctx);
456 pulse_ctx = NULL;
457 return E_FAIL;
460 static void pulse_contextcallback(pa_context *c, void *userdata) {
461 switch (pa_context_get_state(c)) {
462 default:
463 FIXME("Unhandled state: %i\n", pa_context_get_state(c));
464 case PA_CONTEXT_CONNECTING:
465 case PA_CONTEXT_UNCONNECTED:
466 case PA_CONTEXT_AUTHORIZING:
467 case PA_CONTEXT_SETTING_NAME:
468 case PA_CONTEXT_TERMINATED:
469 TRACE("State change to %i\n", pa_context_get_state(c));
470 return;
472 case PA_CONTEXT_READY:
473 TRACE("Ready\n");
474 break;
476 case PA_CONTEXT_FAILED:
477 ERR("Context failed: %s\n", pa_strerror(pa_context_errno(c)));
478 break;
480 pthread_cond_signal(&pulse_cond);
483 static HRESULT pulse_stream_valid(ACImpl *This) {
484 if (!This->stream)
485 return AUDCLNT_E_NOT_INITIALIZED;
486 if (!This->stream || pa_stream_get_state(This->stream) != PA_STREAM_READY)
487 return AUDCLNT_E_DEVICE_INVALIDATED;
488 return S_OK;
491 static void dump_attr(const pa_buffer_attr *attr) {
492 TRACE("maxlength: %u\n", attr->maxlength);
493 TRACE("minreq: %u\n", attr->minreq);
494 TRACE("fragsize: %u\n", attr->fragsize);
495 TRACE("tlength: %u\n", attr->tlength);
496 TRACE("prebuf: %u\n", attr->prebuf);
499 static void pulse_op_cb(pa_stream *s, int success, void *user) {
500 TRACE("Success: %i\n", success);
501 *(int*)user = success;
502 pthread_cond_signal(&pulse_cond);
505 static void pulse_ctx_op_cb(pa_context *c, int success, void *user) {
506 TRACE("Success: %i\n", success);
507 *(int*)user = success;
508 pthread_cond_signal(&pulse_cond);
511 static void pulse_attr_update(pa_stream *s, void *user) {
512 const pa_buffer_attr *attr = pa_stream_get_buffer_attr(s);
513 TRACE("New attributes or device moved:\n");
514 dump_attr(attr);
517 static void pulse_wr_callback(pa_stream *s, size_t bytes, void *userdata)
519 ACImpl *This = userdata;
520 UINT32 oldpad = This->pad;
522 if (bytes < This->bufsize_bytes)
523 This->pad = This->bufsize_bytes - bytes;
524 else
525 This->pad = 0;
527 assert(oldpad >= This->pad);
529 This->clock_written += oldpad - This->pad;
530 TRACE("New pad: %zu (-%zu)\n", This->pad / pa_frame_size(&This->ss), (oldpad - This->pad) / pa_frame_size(&This->ss));
532 if (This->event)
533 SetEvent(This->event);
536 static void pulse_underflow_callback(pa_stream *s, void *userdata)
538 WARN("Underflow\n");
541 /* Latency is periodically updated even when nothing is played,
542 * because of PA_STREAM_AUTO_TIMING_UPDATE so use it as timer
544 * Perfect for passing all tests :)
546 static void pulse_latency_callback(pa_stream *s, void *userdata)
548 ACImpl *This = userdata;
549 if (!This->pad && This->event)
550 SetEvent(This->event);
553 static void pulse_started_callback(pa_stream *s, void *userdata)
555 ACImpl *This = userdata;
557 TRACE("(Re)started playing\n");
558 if (This->event)
559 SetEvent(This->event);
562 static void pulse_rd_loop(ACImpl *This, size_t bytes)
564 while (bytes >= This->capture_period) {
565 ACPacket *p, *next;
566 LARGE_INTEGER stamp, freq;
567 BYTE *dst, *src;
568 size_t src_len, copy, rem = This->capture_period;
569 if (!(p = (ACPacket*)list_head(&This->packet_free_head))) {
570 p = (ACPacket*)list_head(&This->packet_filled_head);
571 if (!p->discont) {
572 next = (ACPacket*)p->entry.next;
573 next->discont = 1;
574 } else
575 p = (ACPacket*)list_tail(&This->packet_filled_head);
576 assert(This->pad == This->bufsize_bytes);
577 } else {
578 assert(This->pad < This->bufsize_bytes);
579 This->pad += This->capture_period;
580 assert(This->pad <= This->bufsize_bytes);
582 QueryPerformanceCounter(&stamp);
583 QueryPerformanceFrequency(&freq);
584 p->qpcpos = (stamp.QuadPart * (INT64)10000000) / freq.QuadPart;
585 p->discont = 0;
586 list_remove(&p->entry);
587 list_add_tail(&This->packet_filled_head, &p->entry);
589 dst = p->data;
590 while (rem) {
591 pa_stream_peek(This->stream, (const void**)&src, &src_len);
592 assert(src_len);
593 assert(This->peek_ofs < src_len);
594 src += This->peek_ofs;
595 src_len -= This->peek_ofs;
596 assert(src_len <= bytes);
598 copy = rem;
599 if (copy > src_len)
600 copy = src_len;
601 memcpy(dst, src, rem);
602 src += copy;
603 src_len -= copy;
604 dst += copy;
605 rem -= copy;
607 if (!src_len) {
608 This->peek_ofs = 0;
609 pa_stream_drop(This->stream);
610 } else
611 This->peek_ofs += copy;
613 bytes -= This->capture_period;
617 static void pulse_rd_drop(ACImpl *This, size_t bytes)
619 while (bytes >= This->capture_period) {
620 size_t src_len, copy, rem = This->capture_period;
621 while (rem) {
622 const void *src;
623 pa_stream_peek(This->stream, &src, &src_len);
624 assert(src_len);
625 assert(This->peek_ofs < src_len);
626 src_len -= This->peek_ofs;
627 assert(src_len <= bytes);
629 copy = rem;
630 if (copy > src_len)
631 copy = src_len;
633 src_len -= copy;
634 rem -= copy;
636 if (!src_len) {
637 This->peek_ofs = 0;
638 pa_stream_drop(This->stream);
639 } else
640 This->peek_ofs += copy;
641 bytes -= copy;
646 static void pulse_rd_callback(pa_stream *s, size_t bytes, void *userdata)
648 ACImpl *This = userdata;
650 TRACE("Readable total: %zu, fragsize: %u\n", bytes, pa_stream_get_buffer_attr(s)->fragsize);
651 assert(bytes >= This->peek_ofs);
652 bytes -= This->peek_ofs;
653 if (bytes < This->capture_period)
654 return;
656 if (This->started)
657 pulse_rd_loop(This, bytes);
658 else
659 pulse_rd_drop(This, bytes);
661 if (This->event)
662 SetEvent(This->event);
665 static void pulse_stream_state(pa_stream *s, void *user)
667 pa_stream_state_t state = pa_stream_get_state(s);
668 TRACE("Stream state changed to %i\n", state);
669 pthread_cond_signal(&pulse_cond);
672 static HRESULT pulse_stream_connect(ACImpl *This, UINT32 period_bytes) {
673 int ret;
674 char buffer[64];
675 static LONG number;
676 pa_buffer_attr attr;
677 if (This->stream) {
678 pa_stream_disconnect(This->stream);
679 while (pa_stream_get_state(This->stream) == PA_STREAM_READY)
680 pthread_cond_wait(&pulse_cond, &pulse_lock);
681 pa_stream_unref(This->stream);
683 ret = InterlockedIncrement(&number);
684 sprintf(buffer, "audio stream #%i", ret);
685 This->stream = pa_stream_new(pulse_ctx, buffer, &This->ss, &This->map);
686 pa_stream_set_state_callback(This->stream, pulse_stream_state, This);
687 pa_stream_set_buffer_attr_callback(This->stream, pulse_attr_update, This);
688 pa_stream_set_moved_callback(This->stream, pulse_attr_update, This);
690 /* Pulseaudio will fill in correct values */
691 attr.minreq = attr.fragsize = period_bytes;
692 attr.maxlength = attr.tlength = This->bufsize_bytes;
693 attr.prebuf = pa_frame_size(&This->ss);
694 dump_attr(&attr);
695 if (This->dataflow == eRender)
696 ret = pa_stream_connect_playback(This->stream, NULL, &attr,
697 PA_STREAM_START_CORKED|PA_STREAM_START_UNMUTED|PA_STREAM_AUTO_TIMING_UPDATE|PA_STREAM_INTERPOLATE_TIMING|PA_STREAM_EARLY_REQUESTS, NULL, NULL);
698 else
699 ret = pa_stream_connect_record(This->stream, NULL, &attr,
700 PA_STREAM_START_CORKED|PA_STREAM_START_UNMUTED|PA_STREAM_AUTO_TIMING_UPDATE|PA_STREAM_INTERPOLATE_TIMING|PA_STREAM_EARLY_REQUESTS);
701 if (ret < 0) {
702 WARN("Returns %i\n", ret);
703 return AUDCLNT_E_ENDPOINT_CREATE_FAILED;
705 while (pa_stream_get_state(This->stream) == PA_STREAM_CREATING)
706 pthread_cond_wait(&pulse_cond, &pulse_lock);
707 if (pa_stream_get_state(This->stream) != PA_STREAM_READY)
708 return AUDCLNT_E_ENDPOINT_CREATE_FAILED;
710 if (This->dataflow == eRender) {
711 pa_stream_set_write_callback(This->stream, pulse_wr_callback, This);
712 pa_stream_set_underflow_callback(This->stream, pulse_underflow_callback, This);
713 pa_stream_set_started_callback(This->stream, pulse_started_callback, This);
714 } else
715 pa_stream_set_read_callback(This->stream, pulse_rd_callback, This);
716 return S_OK;
719 HRESULT WINAPI AUDDRV_GetEndpointIDs(EDataFlow flow, WCHAR ***ids, void ***keys,
720 UINT *num, UINT *def_index)
722 HRESULT hr = S_OK;
723 TRACE("%d %p %p %p\n", flow, ids, num, def_index);
725 pthread_mutex_lock(&pulse_lock);
726 hr = pulse_connect();
727 pthread_mutex_unlock(&pulse_lock);
728 if (FAILED(hr))
729 return hr;
730 *num = 1;
731 *def_index = 0;
733 *ids = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR *));
734 if (!*ids)
735 return E_OUTOFMEMORY;
737 (*ids)[0] = HeapAlloc(GetProcessHeap(), 0, sizeof(defaultW));
738 if (!(*ids)[0]) {
739 HeapFree(GetProcessHeap(), 0, *ids);
740 return E_OUTOFMEMORY;
743 lstrcpyW((*ids)[0], defaultW);
745 *keys = HeapAlloc(GetProcessHeap(), 0, sizeof(void *));
746 (*keys)[0] = NULL;
748 return S_OK;
751 int WINAPI AUDDRV_GetPriority(void)
753 HRESULT hr;
754 if (getenv("WINENOPULSE")) {
755 FIXME_(winediag)("winepulse has been temporarily disabled through the environment\n");
756 return 0;
758 pthread_mutex_lock(&pulse_lock);
759 hr = pulse_connect();
760 pthread_mutex_unlock(&pulse_lock);
761 return SUCCEEDED(hr) ? 3 : 0;
764 HRESULT WINAPI AUDDRV_GetAudioEndpoint(void *key, IMMDevice *dev,
765 EDataFlow dataflow, IAudioClient **out)
767 HRESULT hr;
768 ACImpl *This;
769 int i;
771 /* Give one visible warning per session
772 * Sadly wine has chosen not to accept the winepulse patch, so support ourselves
774 if (!warn_once && (warn_once = CreateEventA(0, 0, 0, "__winepulse_warn_event")) && GetLastError() != ERROR_ALREADY_EXISTS) {
775 FIXME_(winediag)("Winepulse is not officially supported by the wine project\n");
776 FIXME_(winediag)("For sound related feedback and support, please visit http://ubuntuforums.org/showthread.php?t=1960599\n");
777 } else {
778 WARN_(winediag)("Winepulse is not officially supported by the wine project\n");
779 WARN_(winediag)("For sound related feedback and support, please visit http://ubuntuforums.org/showthread.php?t=1960599\n");
782 TRACE("%s %p %p\n", debugstr_guid(guid), dev, out);
783 if (dataflow != eRender && dataflow != eCapture)
784 return E_UNEXPECTED;
786 *out = NULL;
787 pthread_mutex_lock(&pulse_lock);
788 hr = pulse_connect();
789 pthread_mutex_unlock(&pulse_lock);
790 if (FAILED(hr))
791 return hr;
793 This = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*This));
794 if (!This)
795 return E_OUTOFMEMORY;
797 This->IAudioClient_iface.lpVtbl = &AudioClient_Vtbl;
798 This->IAudioRenderClient_iface.lpVtbl = &AudioRenderClient_Vtbl;
799 This->IAudioCaptureClient_iface.lpVtbl = &AudioCaptureClient_Vtbl;
800 This->IAudioClock_iface.lpVtbl = &AudioClock_Vtbl;
801 This->IAudioClock2_iface.lpVtbl = &AudioClock2_Vtbl;
802 This->IAudioStreamVolume_iface.lpVtbl = &AudioStreamVolume_Vtbl;
803 This->dataflow = dataflow;
804 This->parent = dev;
805 for (i = 0; i < PA_CHANNELS_MAX; ++i)
806 This->vol[i] = 1.f;
807 IMMDevice_AddRef(This->parent);
809 *out = &This->IAudioClient_iface;
810 IAudioClient_AddRef(&This->IAudioClient_iface);
812 return S_OK;
815 static HRESULT WINAPI AudioClient_QueryInterface(IAudioClient *iface,
816 REFIID riid, void **ppv)
818 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
820 if (!ppv)
821 return E_POINTER;
822 *ppv = NULL;
823 if (IsEqualIID(riid, &IID_IUnknown) || IsEqualIID(riid, &IID_IAudioClient))
824 *ppv = iface;
825 if (*ppv) {
826 IUnknown_AddRef((IUnknown*)*ppv);
827 return S_OK;
829 WARN("Unknown interface %s\n", debugstr_guid(riid));
830 return E_NOINTERFACE;
833 static ULONG WINAPI AudioClient_AddRef(IAudioClient *iface)
835 ACImpl *This = impl_from_IAudioClient(iface);
836 ULONG ref;
837 ref = InterlockedIncrement(&This->ref);
838 TRACE("(%p) Refcount now %u\n", This, ref);
839 return ref;
842 static ULONG WINAPI AudioClient_Release(IAudioClient *iface)
844 ACImpl *This = impl_from_IAudioClient(iface);
845 ULONG ref;
846 ref = InterlockedDecrement(&This->ref);
847 TRACE("(%p) Refcount now %u\n", This, ref);
848 if (!ref) {
849 if (This->stream) {
850 pthread_mutex_lock(&pulse_lock);
851 if (PA_STREAM_IS_GOOD(pa_stream_get_state(This->stream))) {
852 pa_stream_disconnect(This->stream);
853 while (PA_STREAM_IS_GOOD(pa_stream_get_state(This->stream)))
854 pthread_cond_wait(&pulse_cond, &pulse_lock);
856 pa_stream_unref(This->stream);
857 This->stream = NULL;
858 list_remove(&This->entry);
859 pthread_mutex_unlock(&pulse_lock);
861 IMMDevice_Release(This->parent);
862 HeapFree(GetProcessHeap(), 0, This->tmp_buffer);
863 HeapFree(GetProcessHeap(), 0, This);
865 return ref;
868 static void dump_fmt(const WAVEFORMATEX *fmt)
870 TRACE("wFormatTag: 0x%x (", fmt->wFormatTag);
871 switch(fmt->wFormatTag) {
872 case WAVE_FORMAT_PCM:
873 TRACE("WAVE_FORMAT_PCM");
874 break;
875 case WAVE_FORMAT_IEEE_FLOAT:
876 TRACE("WAVE_FORMAT_IEEE_FLOAT");
877 break;
878 case WAVE_FORMAT_EXTENSIBLE:
879 TRACE("WAVE_FORMAT_EXTENSIBLE");
880 break;
881 default:
882 TRACE("Unknown");
883 break;
885 TRACE(")\n");
887 TRACE("nChannels: %u\n", fmt->nChannels);
888 TRACE("nSamplesPerSec: %u\n", fmt->nSamplesPerSec);
889 TRACE("nAvgBytesPerSec: %u\n", fmt->nAvgBytesPerSec);
890 TRACE("nBlockAlign: %u\n", fmt->nBlockAlign);
891 TRACE("wBitsPerSample: %u\n", fmt->wBitsPerSample);
892 TRACE("cbSize: %u\n", fmt->cbSize);
894 if (fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
895 WAVEFORMATEXTENSIBLE *fmtex = (void*)fmt;
896 TRACE("dwChannelMask: %08x\n", fmtex->dwChannelMask);
897 TRACE("Samples: %04x\n", fmtex->Samples.wReserved);
898 TRACE("SubFormat: %s\n", wine_dbgstr_guid(&fmtex->SubFormat));
902 static WAVEFORMATEX *clone_format(const WAVEFORMATEX *fmt)
904 WAVEFORMATEX *ret;
905 size_t size;
907 if (fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE)
908 size = sizeof(WAVEFORMATEXTENSIBLE);
909 else
910 size = sizeof(WAVEFORMATEX);
912 ret = CoTaskMemAlloc(size);
913 if (!ret)
914 return NULL;
916 memcpy(ret, fmt, size);
918 ret->cbSize = size - sizeof(WAVEFORMATEX);
920 return ret;
923 static DWORD get_channel_mask(unsigned int channels)
925 switch(channels) {
926 case 0:
927 return 0;
928 case 1:
929 return SPEAKER_FRONT_CENTER;
930 case 2:
931 return SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT;
932 case 3:
933 return SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT |
934 SPEAKER_LOW_FREQUENCY;
935 case 4:
936 return SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT |
937 SPEAKER_BACK_RIGHT;
938 case 5:
939 return SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT |
940 SPEAKER_BACK_RIGHT | SPEAKER_LOW_FREQUENCY;
941 case 6:
942 return SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT |
943 SPEAKER_BACK_RIGHT | SPEAKER_LOW_FREQUENCY | SPEAKER_FRONT_CENTER;
944 case 7:
945 return SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT |
946 SPEAKER_BACK_RIGHT | SPEAKER_LOW_FREQUENCY | SPEAKER_FRONT_CENTER |
947 SPEAKER_BACK_CENTER;
948 case 8:
949 return SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT |
950 SPEAKER_BACK_RIGHT | SPEAKER_LOW_FREQUENCY | SPEAKER_FRONT_CENTER |
951 SPEAKER_SIDE_LEFT | SPEAKER_SIDE_RIGHT;
953 FIXME("Unknown speaker configuration: %u\n", channels);
954 return 0;
957 static void session_init_vols(AudioSession *session, UINT channels)
959 if (session->channel_count < channels) {
960 UINT i;
962 if (session->channel_vols)
963 session->channel_vols = HeapReAlloc(GetProcessHeap(), 0,
964 session->channel_vols, sizeof(float) * channels);
965 else
966 session->channel_vols = HeapAlloc(GetProcessHeap(), 0,
967 sizeof(float) * channels);
968 if (!session->channel_vols)
969 return;
971 for(i = session->channel_count; i < channels; ++i)
972 session->channel_vols[i] = 1.f;
974 session->channel_count = channels;
978 static AudioSession *create_session(const GUID *guid, IMMDevice *device,
979 UINT num_channels)
981 AudioSession *ret;
983 ret = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(AudioSession));
984 if (!ret)
985 return NULL;
987 memcpy(&ret->guid, guid, sizeof(GUID));
989 ret->device = device;
991 list_init(&ret->clients);
993 list_add_head(&g_sessions, &ret->entry);
995 session_init_vols(ret, num_channels);
997 ret->master_vol = 1.f;
999 return ret;
1002 /* if channels == 0, then this will return or create a session with
1003 * matching dataflow and GUID. otherwise, channels must also match */
1004 static HRESULT get_audio_session(const GUID *sessionguid,
1005 IMMDevice *device, UINT channels, AudioSession **out)
1007 AudioSession *session;
1009 if (!sessionguid || IsEqualGUID(sessionguid, &GUID_NULL)) {
1010 *out = create_session(&GUID_NULL, device, channels);
1011 if (!*out)
1012 return E_OUTOFMEMORY;
1014 return S_OK;
1017 *out = NULL;
1018 LIST_FOR_EACH_ENTRY(session, &g_sessions, AudioSession, entry) {
1019 if (session->device == device &&
1020 IsEqualGUID(sessionguid, &session->guid)) {
1021 session_init_vols(session, channels);
1022 *out = session;
1023 break;
1027 if (!*out) {
1028 *out = create_session(sessionguid, device, channels);
1029 if (!*out)
1030 return E_OUTOFMEMORY;
1033 return S_OK;
1036 static HRESULT pulse_spec_from_waveformat(ACImpl *This, const WAVEFORMATEX *fmt)
1038 pa_channel_map_init(&This->map);
1039 This->ss.rate = fmt->nSamplesPerSec;
1040 This->ss.format = PA_SAMPLE_INVALID;
1041 switch(fmt->wFormatTag) {
1042 case WAVE_FORMAT_IEEE_FLOAT:
1043 if (!fmt->nChannels || fmt->nChannels > 2 || fmt->wBitsPerSample != 32)
1044 break;
1045 This->ss.format = PA_SAMPLE_FLOAT32LE;
1046 pa_channel_map_init_auto(&This->map, fmt->nChannels, PA_CHANNEL_MAP_ALSA);
1047 break;
1048 case WAVE_FORMAT_PCM:
1049 if (!fmt->nChannels || fmt->nChannels > 2)
1050 break;
1051 if (fmt->wBitsPerSample == 8)
1052 This->ss.format = PA_SAMPLE_U8;
1053 else if (fmt->wBitsPerSample == 16)
1054 This->ss.format = PA_SAMPLE_S16LE;
1055 else
1056 return AUDCLNT_E_UNSUPPORTED_FORMAT;
1057 pa_channel_map_init_auto(&This->map, fmt->nChannels, PA_CHANNEL_MAP_ALSA);
1058 break;
1059 case WAVE_FORMAT_EXTENSIBLE: {
1060 WAVEFORMATEXTENSIBLE *wfe = (WAVEFORMATEXTENSIBLE*)fmt;
1061 DWORD mask = wfe->dwChannelMask;
1062 DWORD i = 0, j;
1063 if (fmt->cbSize != (sizeof(*wfe) - sizeof(*fmt)) && fmt->cbSize != sizeof(*wfe))
1064 break;
1065 if (IsEqualGUID(&wfe->SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT) &&
1066 (!wfe->Samples.wValidBitsPerSample || wfe->Samples.wValidBitsPerSample == 32) &&
1067 fmt->wBitsPerSample == 32)
1068 This->ss.format = PA_SAMPLE_FLOAT32LE;
1069 else if (IsEqualGUID(&wfe->SubFormat, &KSDATAFORMAT_SUBTYPE_PCM)) {
1070 DWORD valid = wfe->Samples.wValidBitsPerSample;
1071 if (!valid)
1072 valid = fmt->wBitsPerSample;
1073 if (!valid || valid > fmt->wBitsPerSample)
1074 break;
1075 switch (fmt->wBitsPerSample) {
1076 case 8:
1077 if (valid == 8)
1078 This->ss.format = PA_SAMPLE_U8;
1079 break;
1080 case 16:
1081 if (valid == 16)
1082 This->ss.format = PA_SAMPLE_S16LE;
1083 break;
1084 case 24:
1085 if (valid == 24)
1086 This->ss.format = PA_SAMPLE_S24LE;
1087 break;
1088 case 32:
1089 if (valid == 24)
1090 This->ss.format = PA_SAMPLE_S24_32LE;
1091 else if (valid == 32)
1092 This->ss.format = PA_SAMPLE_S32LE;
1093 break;
1094 default:
1095 return AUDCLNT_E_UNSUPPORTED_FORMAT;
1098 This->map.channels = fmt->nChannels;
1099 if (!mask || mask == SPEAKER_ALL)
1100 mask = get_channel_mask(fmt->nChannels);
1101 else if (mask == ~0U && fmt->nChannels == 1)
1102 mask = SPEAKER_FRONT_CENTER;
1103 for (j = 0; j < sizeof(pulse_pos_from_wfx)/sizeof(*pulse_pos_from_wfx) && i < fmt->nChannels; ++j) {
1104 if (mask & (1 << j))
1105 This->map.map[i++] = pulse_pos_from_wfx[j];
1108 /* Special case for mono since pulse appears to map it differently */
1109 if (mask == SPEAKER_FRONT_CENTER)
1110 This->map.map[0] = PA_CHANNEL_POSITION_MONO;
1112 if (i < fmt->nChannels || (mask & SPEAKER_RESERVED)) {
1113 This->map.channels = 0;
1114 ERR("Invalid channel mask: %i/%i and %x(%x)\n", i, fmt->nChannels, mask, wfe->dwChannelMask);
1115 break;
1117 break;
1119 case WAVE_FORMAT_ALAW:
1120 case WAVE_FORMAT_MULAW:
1121 if (fmt->wBitsPerSample != 8) {
1122 FIXME("Unsupported bpp %u for LAW\n", fmt->wBitsPerSample);
1123 return AUDCLNT_E_UNSUPPORTED_FORMAT;
1125 if (fmt->nChannels != 1 && fmt->nChannels != 2) {
1126 FIXME("Unsupported channels %u for LAW\n", fmt->nChannels);
1127 return AUDCLNT_E_UNSUPPORTED_FORMAT;
1129 This->ss.format = fmt->wFormatTag == WAVE_FORMAT_MULAW ? PA_SAMPLE_ULAW : PA_SAMPLE_ALAW;
1130 pa_channel_map_init_auto(&This->map, fmt->nChannels, PA_CHANNEL_MAP_ALSA);
1131 break;
1132 default:
1133 WARN("Unhandled tag %x\n", fmt->wFormatTag);
1134 return AUDCLNT_E_UNSUPPORTED_FORMAT;
1136 This->ss.channels = This->map.channels;
1137 if (!pa_channel_map_valid(&This->map) || This->ss.format == PA_SAMPLE_INVALID) {
1138 ERR("Invalid format! Channel spec valid: %i, format: %i\n", pa_channel_map_valid(&This->map), This->ss.format);
1139 dump_fmt(fmt);
1140 return AUDCLNT_E_UNSUPPORTED_FORMAT;
1142 return S_OK;
1145 static HRESULT WINAPI AudioClient_Initialize(IAudioClient *iface,
1146 AUDCLNT_SHAREMODE mode, DWORD flags, REFERENCE_TIME duration,
1147 REFERENCE_TIME period, const WAVEFORMATEX *fmt,
1148 const GUID *sessionguid)
1150 ACImpl *This = impl_from_IAudioClient(iface);
1151 HRESULT hr = S_OK;
1152 UINT period_bytes;
1154 TRACE("(%p)->(%x, %x, %s, %s, %p, %s)\n", This, mode, flags,
1155 wine_dbgstr_longlong(duration), wine_dbgstr_longlong(period), fmt, debugstr_guid(sessionguid));
1157 if (!fmt)
1158 return E_POINTER;
1160 if (mode != AUDCLNT_SHAREMODE_SHARED && mode != AUDCLNT_SHAREMODE_EXCLUSIVE)
1161 return AUDCLNT_E_NOT_INITIALIZED;
1162 if (mode == AUDCLNT_SHAREMODE_EXCLUSIVE)
1163 return AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED;
1165 if (flags & ~(AUDCLNT_STREAMFLAGS_CROSSPROCESS |
1166 AUDCLNT_STREAMFLAGS_LOOPBACK |
1167 AUDCLNT_STREAMFLAGS_EVENTCALLBACK |
1168 AUDCLNT_STREAMFLAGS_NOPERSIST |
1169 AUDCLNT_STREAMFLAGS_RATEADJUST |
1170 AUDCLNT_SESSIONFLAGS_EXPIREWHENUNOWNED |
1171 AUDCLNT_SESSIONFLAGS_DISPLAY_HIDE |
1172 AUDCLNT_SESSIONFLAGS_DISPLAY_HIDEWHENEXPIRED)) {
1173 TRACE("Unknown flags: %08x\n", flags);
1174 return E_INVALIDARG;
1177 pthread_mutex_lock(&pulse_lock);
1178 if (This->stream) {
1179 pthread_mutex_unlock(&pulse_lock);
1180 return AUDCLNT_E_ALREADY_INITIALIZED;
1183 hr = pulse_spec_from_waveformat(This, fmt);
1184 if (FAILED(hr))
1185 goto exit;
1187 if (mode == AUDCLNT_SHAREMODE_SHARED) {
1188 REFERENCE_TIME def = pulse_def_period[This->dataflow == eCapture];
1189 REFERENCE_TIME min = pulse_min_period[This->dataflow == eCapture];
1191 /* Switch to low latency mode if below 2 default periods,
1192 * which is 20 ms by default, this will increase the amount
1193 * of interrupts but allows very low latency. In dsound I
1194 * managed to get a total latency of ~8ms, which is well below
1195 * default
1197 if (duration < 2 * def)
1198 period = min;
1199 else
1200 period = def;
1201 if (duration < 2 * period)
1202 duration = 2 * period;
1204 period_bytes = pa_frame_size(&This->ss) * MulDiv(period, This->ss.rate, 10000000);
1206 if (duration < 20000000)
1207 This->bufsize_frames = ceil((duration / 10000000.) * fmt->nSamplesPerSec);
1208 else
1209 This->bufsize_frames = 2 * fmt->nSamplesPerSec;
1210 This->bufsize_bytes = This->bufsize_frames * pa_frame_size(&This->ss);
1212 This->share = mode;
1213 This->flags = flags;
1214 hr = pulse_stream_connect(This, period_bytes);
1215 if (SUCCEEDED(hr)) {
1216 UINT32 unalign;
1217 const pa_buffer_attr *attr = pa_stream_get_buffer_attr(This->stream);
1218 /* Update frames according to new size */
1219 dump_attr(attr);
1220 if (This->dataflow == eRender)
1221 This->bufsize_bytes = attr->tlength;
1222 else {
1223 This->capture_period = period_bytes = attr->fragsize;
1224 if ((unalign = This->bufsize_bytes % period_bytes))
1225 This->bufsize_bytes += period_bytes - unalign;
1227 This->bufsize_frames = This->bufsize_bytes / pa_frame_size(&This->ss);
1229 if (SUCCEEDED(hr)) {
1230 UINT32 i, capture_packets = This->capture_period ? This->bufsize_bytes / This->capture_period : 0;
1231 This->tmp_buffer = HeapAlloc(GetProcessHeap(), 0, This->bufsize_bytes + capture_packets * sizeof(ACPacket));
1232 if (!This->tmp_buffer)
1233 hr = E_OUTOFMEMORY;
1234 else {
1235 ACPacket *cur_packet = (ACPacket*)((char*)This->tmp_buffer + This->bufsize_bytes);
1236 BYTE *data = This->tmp_buffer;
1237 memset(This->tmp_buffer, This->ss.format == PA_SAMPLE_U8 ? 0x80 : 0, This->bufsize_bytes);
1238 list_init(&This->packet_free_head);
1239 list_init(&This->packet_filled_head);
1240 for (i = 0; i < capture_packets; ++i, ++cur_packet) {
1241 list_add_tail(&This->packet_free_head, &cur_packet->entry);
1242 cur_packet->data = data;
1243 data += This->capture_period;
1245 assert(!This->capture_period || This->bufsize_bytes == This->capture_period * capture_packets);
1246 assert(!capture_packets || data - This->bufsize_bytes == This->tmp_buffer);
1249 if (SUCCEEDED(hr))
1250 hr = get_audio_session(sessionguid, This->parent, fmt->nChannels, &This->session);
1251 if (SUCCEEDED(hr))
1252 list_add_tail(&This->session->clients, &This->entry);
1254 exit:
1255 if (FAILED(hr)) {
1256 HeapFree(GetProcessHeap(), 0, This->tmp_buffer);
1257 This->tmp_buffer = NULL;
1258 if (This->stream) {
1259 pa_stream_disconnect(This->stream);
1260 pa_stream_unref(This->stream);
1261 This->stream = NULL;
1264 pthread_mutex_unlock(&pulse_lock);
1265 return hr;
1268 static HRESULT WINAPI AudioClient_GetBufferSize(IAudioClient *iface,
1269 UINT32 *out)
1271 ACImpl *This = impl_from_IAudioClient(iface);
1272 HRESULT hr;
1274 TRACE("(%p)->(%p)\n", This, out);
1276 if (!out)
1277 return E_POINTER;
1279 pthread_mutex_lock(&pulse_lock);
1280 hr = pulse_stream_valid(This);
1281 if (SUCCEEDED(hr))
1282 *out = This->bufsize_frames;
1283 pthread_mutex_unlock(&pulse_lock);
1285 return hr;
1288 static HRESULT WINAPI AudioClient_GetStreamLatency(IAudioClient *iface,
1289 REFERENCE_TIME *latency)
1291 ACImpl *This = impl_from_IAudioClient(iface);
1292 const pa_buffer_attr *attr;
1293 REFERENCE_TIME lat;
1294 HRESULT hr;
1296 TRACE("(%p)->(%p)\n", This, latency);
1298 if (!latency)
1299 return E_POINTER;
1301 pthread_mutex_lock(&pulse_lock);
1302 hr = pulse_stream_valid(This);
1303 if (FAILED(hr)) {
1304 pthread_mutex_unlock(&pulse_lock);
1305 return hr;
1307 attr = pa_stream_get_buffer_attr(This->stream);
1308 if (This->dataflow == eRender)
1309 lat = attr->minreq / pa_frame_size(&This->ss);
1310 else
1311 lat = attr->fragsize / pa_frame_size(&This->ss);
1312 *latency = 10000000;
1313 *latency *= lat;
1314 *latency /= This->ss.rate;
1315 pthread_mutex_unlock(&pulse_lock);
1316 TRACE("Latency: %u ms\n", (DWORD)(*latency / 10000));
1317 return S_OK;
1320 static void ACImpl_GetRenderPad(ACImpl *This, UINT32 *out)
1322 *out = This->pad / pa_frame_size(&This->ss);
1325 static void ACImpl_GetCapturePad(ACImpl *This, UINT32 *out)
1327 ACPacket *packet = This->locked_ptr;
1328 if (!packet && !list_empty(&This->packet_filled_head)) {
1329 packet = (ACPacket*)list_head(&This->packet_filled_head);
1330 This->locked_ptr = packet;
1331 list_remove(&packet->entry);
1333 if (out)
1334 *out = This->pad / pa_frame_size(&This->ss);
1337 static HRESULT WINAPI AudioClient_GetCurrentPadding(IAudioClient *iface,
1338 UINT32 *out)
1340 ACImpl *This = impl_from_IAudioClient(iface);
1341 HRESULT hr;
1343 TRACE("(%p)->(%p)\n", This, out);
1345 if (!out)
1346 return E_POINTER;
1348 pthread_mutex_lock(&pulse_lock);
1349 hr = pulse_stream_valid(This);
1350 if (FAILED(hr)) {
1351 pthread_mutex_unlock(&pulse_lock);
1352 return hr;
1355 if (This->dataflow == eRender)
1356 ACImpl_GetRenderPad(This, out);
1357 else
1358 ACImpl_GetCapturePad(This, out);
1359 pthread_mutex_unlock(&pulse_lock);
1361 TRACE("%p Pad: %u ms (%u)\n", This, MulDiv(*out, 1000, This->ss.rate), *out);
1362 return S_OK;
1365 static HRESULT WINAPI AudioClient_IsFormatSupported(IAudioClient *iface,
1366 AUDCLNT_SHAREMODE mode, const WAVEFORMATEX *fmt,
1367 WAVEFORMATEX **out)
1369 ACImpl *This = impl_from_IAudioClient(iface);
1370 HRESULT hr = S_OK;
1371 WAVEFORMATEX *closest = NULL;
1373 TRACE("(%p)->(%x, %p, %p)\n", This, mode, fmt, out);
1375 if (!fmt || (mode == AUDCLNT_SHAREMODE_SHARED && !out))
1376 return E_POINTER;
1378 if (out)
1379 *out = NULL;
1380 if (mode != AUDCLNT_SHAREMODE_SHARED && mode != AUDCLNT_SHAREMODE_EXCLUSIVE)
1381 return E_INVALIDARG;
1382 if (mode == AUDCLNT_SHAREMODE_EXCLUSIVE)
1383 return This->dataflow == eCapture ? AUDCLNT_E_UNSUPPORTED_FORMAT : AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED;
1384 switch (fmt->wFormatTag) {
1385 case WAVE_FORMAT_EXTENSIBLE:
1386 if (fmt->cbSize < sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX))
1387 return E_INVALIDARG;
1388 dump_fmt(fmt);
1389 break;
1390 case WAVE_FORMAT_ALAW:
1391 case WAVE_FORMAT_MULAW:
1392 case WAVE_FORMAT_IEEE_FLOAT:
1393 case WAVE_FORMAT_PCM:
1394 dump_fmt(fmt);
1395 break;
1396 default:
1397 dump_fmt(fmt);
1398 return AUDCLNT_E_UNSUPPORTED_FORMAT;
1400 if (fmt->nChannels == 0)
1401 return AUDCLNT_E_UNSUPPORTED_FORMAT;
1402 closest = clone_format(fmt);
1403 if (!closest) {
1404 if (out)
1405 *out = NULL;
1406 return E_OUTOFMEMORY;
1409 if (fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
1410 UINT32 mask = 0, i, channels = 0;
1411 WAVEFORMATEXTENSIBLE *ext = (WAVEFORMATEXTENSIBLE*)closest;
1413 if ((fmt->nChannels > 1 && ext->dwChannelMask == SPEAKER_ALL) ||
1414 (fmt->nChannels == 1 && ext->dwChannelMask == ~0U)) {
1415 mask = ext->dwChannelMask;
1416 channels = fmt->nChannels;
1417 } else if (ext->dwChannelMask) {
1418 for (i = 1; !(i & SPEAKER_RESERVED); i <<= 1) {
1419 if (i & ext->dwChannelMask) {
1420 mask |= i;
1421 channels++;
1424 if (channels < fmt->nChannels)
1425 mask = get_channel_mask(fmt->nChannels);
1426 } else
1427 mask = ext->dwChannelMask;
1428 if (ext->dwChannelMask != mask) {
1429 ext->dwChannelMask = mask;
1430 hr = S_FALSE;
1434 if (hr == S_OK || !out) {
1435 CoTaskMemFree(closest);
1436 if (out)
1437 *out = NULL;
1438 } else if (closest) {
1439 closest->nBlockAlign =
1440 closest->nChannels * closest->wBitsPerSample / 8;
1441 closest->nAvgBytesPerSec =
1442 closest->nBlockAlign * closest->nSamplesPerSec;
1443 *out = closest;
1446 TRACE("returning: %08x %p\n", hr, out ? *out : NULL);
1447 return hr;
1450 static HRESULT WINAPI AudioClient_GetMixFormat(IAudioClient *iface,
1451 WAVEFORMATEX **pwfx)
1453 ACImpl *This = impl_from_IAudioClient(iface);
1454 WAVEFORMATEXTENSIBLE *fmt = &pulse_fmt[This->dataflow == eCapture];
1456 TRACE("(%p)->(%p)\n", This, pwfx);
1458 if (!pwfx)
1459 return E_POINTER;
1461 *pwfx = clone_format(&fmt->Format);
1462 if (!*pwfx)
1463 return E_OUTOFMEMORY;
1464 dump_fmt(*pwfx);
1465 return S_OK;
1468 static HRESULT WINAPI AudioClient_GetDevicePeriod(IAudioClient *iface,
1469 REFERENCE_TIME *defperiod, REFERENCE_TIME *minperiod)
1471 ACImpl *This = impl_from_IAudioClient(iface);
1473 TRACE("(%p)->(%p, %p)\n", This, defperiod, minperiod);
1475 if (!defperiod && !minperiod)
1476 return E_POINTER;
1478 if (defperiod)
1479 *defperiod = pulse_def_period[This->dataflow == eCapture];
1480 if (minperiod)
1481 *minperiod = pulse_min_period[This->dataflow == eCapture];
1483 return S_OK;
1486 static HRESULT WINAPI AudioClient_Start(IAudioClient *iface)
1488 ACImpl *This = impl_from_IAudioClient(iface);
1489 HRESULT hr = S_OK;
1490 int success;
1491 pa_operation *o;
1493 TRACE("(%p)\n", This);
1495 pthread_mutex_lock(&pulse_lock);
1496 hr = pulse_stream_valid(This);
1497 if (FAILED(hr)) {
1498 pthread_mutex_unlock(&pulse_lock);
1499 return hr;
1502 if ((This->flags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK) && !This->event) {
1503 pthread_mutex_unlock(&pulse_lock);
1504 return AUDCLNT_E_EVENTHANDLE_NOT_SET;
1507 if (This->started) {
1508 pthread_mutex_unlock(&pulse_lock);
1509 return AUDCLNT_E_NOT_STOPPED;
1512 if (pa_stream_is_corked(This->stream)) {
1513 o = pa_stream_cork(This->stream, 0, pulse_op_cb, &success);
1514 if (o) {
1515 while(pa_operation_get_state(o) == PA_OPERATION_RUNNING)
1516 pthread_cond_wait(&pulse_cond, &pulse_lock);
1517 pa_operation_unref(o);
1518 } else
1519 success = 0;
1520 if (!success)
1521 hr = E_FAIL;
1523 if (SUCCEEDED(hr)) {
1524 This->started = TRUE;
1525 if (This->dataflow == eRender && This->event)
1526 pa_stream_set_latency_update_callback(This->stream, pulse_latency_callback, This);
1528 pthread_mutex_unlock(&pulse_lock);
1529 return hr;
1532 static HRESULT WINAPI AudioClient_Stop(IAudioClient *iface)
1534 ACImpl *This = impl_from_IAudioClient(iface);
1535 HRESULT hr = S_OK;
1536 pa_operation *o;
1537 int success;
1539 TRACE("(%p)\n", This);
1541 pthread_mutex_lock(&pulse_lock);
1542 hr = pulse_stream_valid(This);
1543 if (FAILED(hr)) {
1544 pthread_mutex_unlock(&pulse_lock);
1545 return hr;
1548 if (!This->started) {
1549 pthread_mutex_unlock(&pulse_lock);
1550 return S_FALSE;
1553 if (This->dataflow == eRender) {
1554 o = pa_stream_cork(This->stream, 1, pulse_op_cb, &success);
1555 if (o) {
1556 while(pa_operation_get_state(o) == PA_OPERATION_RUNNING)
1557 pthread_cond_wait(&pulse_cond, &pulse_lock);
1558 pa_operation_unref(o);
1559 } else
1560 success = 0;
1561 if (!success)
1562 hr = E_FAIL;
1564 if (SUCCEEDED(hr)) {
1565 This->started = FALSE;
1567 pthread_mutex_unlock(&pulse_lock);
1568 return hr;
1571 static HRESULT WINAPI AudioClient_Reset(IAudioClient *iface)
1573 ACImpl *This = impl_from_IAudioClient(iface);
1574 HRESULT hr = S_OK;
1576 TRACE("(%p)\n", This);
1578 pthread_mutex_lock(&pulse_lock);
1579 hr = pulse_stream_valid(This);
1580 if (FAILED(hr)) {
1581 pthread_mutex_unlock(&pulse_lock);
1582 return hr;
1585 if (This->started) {
1586 pthread_mutex_unlock(&pulse_lock);
1587 return AUDCLNT_E_NOT_STOPPED;
1590 if (This->locked) {
1591 pthread_mutex_unlock(&pulse_lock);
1592 return AUDCLNT_E_BUFFER_OPERATION_PENDING;
1595 if (This->dataflow == eRender) {
1596 /* If there is still data in the render buffer it needs to be removed from the server */
1597 int success = 0;
1598 if (This->pad) {
1599 pa_operation *o = pa_stream_flush(This->stream, pulse_op_cb, &success);
1600 if (o) {
1601 while(pa_operation_get_state(o) == PA_OPERATION_RUNNING)
1602 pthread_cond_wait(&pulse_cond, &pulse_lock);
1603 pa_operation_unref(o);
1606 if (success || !This->pad)
1607 This->clock_lastpos = This->clock_written = This->pad = 0;
1608 } else {
1609 ACPacket *p;
1610 This->clock_written += This->pad;
1611 This->pad = 0;
1613 if ((p = This->locked_ptr)) {
1614 This->locked_ptr = NULL;
1615 list_add_tail(&This->packet_free_head, &p->entry);
1617 list_move_tail(&This->packet_free_head, &This->packet_filled_head);
1619 pthread_mutex_unlock(&pulse_lock);
1621 return hr;
1624 static HRESULT WINAPI AudioClient_SetEventHandle(IAudioClient *iface,
1625 HANDLE event)
1627 ACImpl *This = impl_from_IAudioClient(iface);
1628 HRESULT hr;
1630 TRACE("(%p)->(%p)\n", This, event);
1632 if (!event)
1633 return E_INVALIDARG;
1635 pthread_mutex_lock(&pulse_lock);
1636 hr = pulse_stream_valid(This);
1637 if (FAILED(hr)) {
1638 pthread_mutex_unlock(&pulse_lock);
1639 return hr;
1642 if (!(This->flags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK))
1643 hr = AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED;
1644 else if (This->event)
1645 hr = HRESULT_FROM_WIN32(ERROR_INVALID_NAME);
1646 else
1647 This->event = event;
1648 pthread_mutex_unlock(&pulse_lock);
1649 return hr;
1652 static HRESULT WINAPI AudioClient_GetService(IAudioClient *iface, REFIID riid,
1653 void **ppv)
1655 ACImpl *This = impl_from_IAudioClient(iface);
1656 HRESULT hr;
1658 TRACE("(%p)->(%s, %p)\n", This, debugstr_guid(riid), ppv);
1660 if (!ppv)
1661 return E_POINTER;
1662 *ppv = NULL;
1664 pthread_mutex_lock(&pulse_lock);
1665 hr = pulse_stream_valid(This);
1666 pthread_mutex_unlock(&pulse_lock);
1667 if (FAILED(hr))
1668 return hr;
1670 if (IsEqualIID(riid, &IID_IAudioRenderClient)) {
1671 if (This->dataflow != eRender)
1672 return AUDCLNT_E_WRONG_ENDPOINT_TYPE;
1673 *ppv = &This->IAudioRenderClient_iface;
1674 } else if (IsEqualIID(riid, &IID_IAudioCaptureClient)) {
1675 if (This->dataflow != eCapture)
1676 return AUDCLNT_E_WRONG_ENDPOINT_TYPE;
1677 *ppv = &This->IAudioCaptureClient_iface;
1678 } else if (IsEqualIID(riid, &IID_IAudioClock)) {
1679 *ppv = &This->IAudioClock_iface;
1680 } else if (IsEqualIID(riid, &IID_IAudioStreamVolume)) {
1681 *ppv = &This->IAudioStreamVolume_iface;
1682 } else if (IsEqualIID(riid, &IID_IAudioSessionControl) ||
1683 IsEqualIID(riid, &IID_IChannelAudioVolume) ||
1684 IsEqualIID(riid, &IID_ISimpleAudioVolume)) {
1685 if (!This->session_wrapper) {
1686 This->session_wrapper = AudioSessionWrapper_Create(This);
1687 if (!This->session_wrapper)
1688 return E_OUTOFMEMORY;
1690 if (IsEqualIID(riid, &IID_IAudioSessionControl))
1691 *ppv = &This->session_wrapper->IAudioSessionControl2_iface;
1692 else if (IsEqualIID(riid, &IID_IChannelAudioVolume))
1693 *ppv = &This->session_wrapper->IChannelAudioVolume_iface;
1694 else if (IsEqualIID(riid, &IID_ISimpleAudioVolume))
1695 *ppv = &This->session_wrapper->ISimpleAudioVolume_iface;
1698 if (*ppv) {
1699 IUnknown_AddRef((IUnknown*)*ppv);
1700 return S_OK;
1703 FIXME("stub %s\n", debugstr_guid(riid));
1704 return E_NOINTERFACE;
1707 static const IAudioClientVtbl AudioClient_Vtbl =
1709 AudioClient_QueryInterface,
1710 AudioClient_AddRef,
1711 AudioClient_Release,
1712 AudioClient_Initialize,
1713 AudioClient_GetBufferSize,
1714 AudioClient_GetStreamLatency,
1715 AudioClient_GetCurrentPadding,
1716 AudioClient_IsFormatSupported,
1717 AudioClient_GetMixFormat,
1718 AudioClient_GetDevicePeriod,
1719 AudioClient_Start,
1720 AudioClient_Stop,
1721 AudioClient_Reset,
1722 AudioClient_SetEventHandle,
1723 AudioClient_GetService
1726 static HRESULT WINAPI AudioRenderClient_QueryInterface(
1727 IAudioRenderClient *iface, REFIID riid, void **ppv)
1729 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
1731 if (!ppv)
1732 return E_POINTER;
1733 *ppv = NULL;
1735 if (IsEqualIID(riid, &IID_IUnknown) ||
1736 IsEqualIID(riid, &IID_IAudioRenderClient))
1737 *ppv = iface;
1738 if (*ppv) {
1739 IUnknown_AddRef((IUnknown*)*ppv);
1740 return S_OK;
1743 WARN("Unknown interface %s\n", debugstr_guid(riid));
1744 return E_NOINTERFACE;
1747 static ULONG WINAPI AudioRenderClient_AddRef(IAudioRenderClient *iface)
1749 ACImpl *This = impl_from_IAudioRenderClient(iface);
1750 return AudioClient_AddRef(&This->IAudioClient_iface);
1753 static ULONG WINAPI AudioRenderClient_Release(IAudioRenderClient *iface)
1755 ACImpl *This = impl_from_IAudioRenderClient(iface);
1756 return AudioClient_Release(&This->IAudioClient_iface);
1759 static HRESULT WINAPI AudioRenderClient_GetBuffer(IAudioRenderClient *iface,
1760 UINT32 frames, BYTE **data)
1762 ACImpl *This = impl_from_IAudioRenderClient(iface);
1763 size_t avail, req, bytes = frames * pa_frame_size(&This->ss);
1764 UINT32 pad;
1765 HRESULT hr = S_OK;
1766 int ret = -1;
1768 TRACE("(%p)->(%u, %p)\n", This, frames, data);
1770 if (!data)
1771 return E_POINTER;
1772 *data = NULL;
1774 pthread_mutex_lock(&pulse_lock);
1775 hr = pulse_stream_valid(This);
1776 if (FAILED(hr) || This->locked) {
1777 pthread_mutex_unlock(&pulse_lock);
1778 return FAILED(hr) ? hr : AUDCLNT_E_OUT_OF_ORDER;
1780 if (!frames) {
1781 pthread_mutex_unlock(&pulse_lock);
1782 return S_OK;
1785 ACImpl_GetRenderPad(This, &pad);
1786 avail = This->bufsize_frames - pad;
1787 if (avail < frames || bytes > This->bufsize_bytes) {
1788 pthread_mutex_unlock(&pulse_lock);
1789 WARN("Wanted to write %u, but only %zu available\n", frames, avail);
1790 return AUDCLNT_E_BUFFER_TOO_LARGE;
1793 This->locked = frames;
1794 req = bytes;
1795 ret = pa_stream_begin_write(This->stream, &This->locked_ptr, &req);
1796 if (ret < 0 || req < bytes) {
1797 FIXME("%p Not using pulse locked data: %i %zu/%u %u/%u\n", This, ret, req/pa_frame_size(&This->ss), frames, pad, This->bufsize_frames);
1798 if (ret >= 0)
1799 pa_stream_cancel_write(This->stream);
1800 *data = This->tmp_buffer;
1801 This->locked_ptr = NULL;
1802 } else
1803 *data = This->locked_ptr;
1804 pthread_mutex_unlock(&pulse_lock);
1805 return hr;
1808 static HRESULT WINAPI AudioRenderClient_ReleaseBuffer(
1809 IAudioRenderClient *iface, UINT32 written_frames, DWORD flags)
1811 ACImpl *This = impl_from_IAudioRenderClient(iface);
1812 UINT32 written_bytes = written_frames * pa_frame_size(&This->ss);
1814 TRACE("(%p)->(%u, %x)\n", This, written_frames, flags);
1816 pthread_mutex_lock(&pulse_lock);
1817 if (!This->locked || !written_frames) {
1818 if (This->locked_ptr)
1819 pa_stream_cancel_write(This->stream);
1820 This->locked = 0;
1821 This->locked_ptr = NULL;
1822 pthread_mutex_unlock(&pulse_lock);
1823 return written_frames ? AUDCLNT_E_OUT_OF_ORDER : S_OK;
1826 if (This->locked < written_frames) {
1827 pthread_mutex_unlock(&pulse_lock);
1828 return AUDCLNT_E_INVALID_SIZE;
1831 if (flags & AUDCLNT_BUFFERFLAGS_SILENT) {
1832 if (This->ss.format == PA_SAMPLE_U8)
1833 memset(This->tmp_buffer, 128, written_bytes);
1834 else
1835 memset(This->tmp_buffer, 0, written_bytes);
1838 This->locked = 0;
1839 if (This->locked_ptr)
1840 pa_stream_write(This->stream, This->locked_ptr, written_bytes, NULL, 0, PA_SEEK_RELATIVE);
1841 else
1842 pa_stream_write(This->stream, This->tmp_buffer, written_bytes, NULL, 0, PA_SEEK_RELATIVE);
1843 This->pad += written_bytes;
1844 This->locked_ptr = NULL;
1845 TRACE("Released %u, pad %zu\n", written_frames, This->pad / pa_frame_size(&This->ss));
1846 assert(This->pad <= This->bufsize_bytes);
1847 pthread_mutex_unlock(&pulse_lock);
1848 return S_OK;
1851 static const IAudioRenderClientVtbl AudioRenderClient_Vtbl = {
1852 AudioRenderClient_QueryInterface,
1853 AudioRenderClient_AddRef,
1854 AudioRenderClient_Release,
1855 AudioRenderClient_GetBuffer,
1856 AudioRenderClient_ReleaseBuffer
1859 static HRESULT WINAPI AudioCaptureClient_QueryInterface(
1860 IAudioCaptureClient *iface, REFIID riid, void **ppv)
1862 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
1864 if (!ppv)
1865 return E_POINTER;
1866 *ppv = NULL;
1868 if (IsEqualIID(riid, &IID_IUnknown) ||
1869 IsEqualIID(riid, &IID_IAudioCaptureClient))
1870 *ppv = iface;
1871 if (*ppv) {
1872 IUnknown_AddRef((IUnknown*)*ppv);
1873 return S_OK;
1876 WARN("Unknown interface %s\n", debugstr_guid(riid));
1877 return E_NOINTERFACE;
1880 static ULONG WINAPI AudioCaptureClient_AddRef(IAudioCaptureClient *iface)
1882 ACImpl *This = impl_from_IAudioCaptureClient(iface);
1883 return IAudioClient_AddRef(&This->IAudioClient_iface);
1886 static ULONG WINAPI AudioCaptureClient_Release(IAudioCaptureClient *iface)
1888 ACImpl *This = impl_from_IAudioCaptureClient(iface);
1889 return IAudioClient_Release(&This->IAudioClient_iface);
1892 static HRESULT WINAPI AudioCaptureClient_GetBuffer(IAudioCaptureClient *iface,
1893 BYTE **data, UINT32 *frames, DWORD *flags, UINT64 *devpos,
1894 UINT64 *qpcpos)
1896 ACImpl *This = impl_from_IAudioCaptureClient(iface);
1897 HRESULT hr;
1898 ACPacket *packet;
1900 TRACE("(%p)->(%p, %p, %p, %p, %p)\n", This, data, frames, flags,
1901 devpos, qpcpos);
1903 if (!data || !frames || !flags)
1904 return E_POINTER;
1906 pthread_mutex_lock(&pulse_lock);
1907 hr = pulse_stream_valid(This);
1908 if (FAILED(hr) || This->locked) {
1909 pthread_mutex_unlock(&pulse_lock);
1910 return FAILED(hr) ? hr : AUDCLNT_E_OUT_OF_ORDER;
1913 ACImpl_GetCapturePad(This, NULL);
1914 if ((packet = This->locked_ptr)) {
1915 *frames = This->capture_period / pa_frame_size(&This->ss);
1916 *flags = 0;
1917 if (packet->discont)
1918 *flags |= AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY;
1919 if (devpos) {
1920 if (packet->discont)
1921 *devpos = (This->clock_written + This->capture_period) / pa_frame_size(&This->ss);
1922 else
1923 *devpos = This->clock_written / pa_frame_size(&This->ss);
1925 if (qpcpos)
1926 *qpcpos = packet->qpcpos;
1927 *data = packet->data;
1929 else
1930 *frames = 0;
1931 This->locked = *frames;
1932 pthread_mutex_unlock(&pulse_lock);
1933 return *frames ? S_OK : AUDCLNT_S_BUFFER_EMPTY;
1936 static HRESULT WINAPI AudioCaptureClient_ReleaseBuffer(
1937 IAudioCaptureClient *iface, UINT32 done)
1939 ACImpl *This = impl_from_IAudioCaptureClient(iface);
1941 TRACE("(%p)->(%u)\n", This, done);
1943 pthread_mutex_lock(&pulse_lock);
1944 if (!This->locked && done) {
1945 pthread_mutex_unlock(&pulse_lock);
1946 return AUDCLNT_E_OUT_OF_ORDER;
1948 if (done && This->locked != done) {
1949 pthread_mutex_unlock(&pulse_lock);
1950 return AUDCLNT_E_INVALID_SIZE;
1952 if (done) {
1953 ACPacket *packet = This->locked_ptr;
1954 This->locked_ptr = NULL;
1955 This->pad -= This->capture_period;
1956 if (packet->discont)
1957 This->clock_written += 2 * This->capture_period;
1958 else
1959 This->clock_written += This->capture_period;
1960 list_add_tail(&This->packet_free_head, &packet->entry);
1962 This->locked = 0;
1963 pthread_mutex_unlock(&pulse_lock);
1964 return S_OK;
1967 static HRESULT WINAPI AudioCaptureClient_GetNextPacketSize(
1968 IAudioCaptureClient *iface, UINT32 *frames)
1970 ACImpl *This = impl_from_IAudioCaptureClient(iface);
1971 ACPacket *p;
1973 TRACE("(%p)->(%p)\n", This, frames);
1974 if (!frames)
1975 return E_POINTER;
1977 pthread_mutex_lock(&pulse_lock);
1978 ACImpl_GetCapturePad(This, NULL);
1979 p = This->locked_ptr;
1980 if (p)
1981 *frames = This->capture_period / pa_frame_size(&This->ss);
1982 else
1983 *frames = 0;
1984 pthread_mutex_unlock(&pulse_lock);
1985 return S_OK;
1988 static const IAudioCaptureClientVtbl AudioCaptureClient_Vtbl =
1990 AudioCaptureClient_QueryInterface,
1991 AudioCaptureClient_AddRef,
1992 AudioCaptureClient_Release,
1993 AudioCaptureClient_GetBuffer,
1994 AudioCaptureClient_ReleaseBuffer,
1995 AudioCaptureClient_GetNextPacketSize
1998 static HRESULT WINAPI AudioClock_QueryInterface(IAudioClock *iface,
1999 REFIID riid, void **ppv)
2001 ACImpl *This = impl_from_IAudioClock(iface);
2003 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
2005 if (!ppv)
2006 return E_POINTER;
2007 *ppv = NULL;
2009 if (IsEqualIID(riid, &IID_IUnknown) || IsEqualIID(riid, &IID_IAudioClock))
2010 *ppv = iface;
2011 else if (IsEqualIID(riid, &IID_IAudioClock2))
2012 *ppv = &This->IAudioClock2_iface;
2013 if (*ppv) {
2014 IUnknown_AddRef((IUnknown*)*ppv);
2015 return S_OK;
2018 WARN("Unknown interface %s\n", debugstr_guid(riid));
2019 return E_NOINTERFACE;
2022 static ULONG WINAPI AudioClock_AddRef(IAudioClock *iface)
2024 ACImpl *This = impl_from_IAudioClock(iface);
2025 return IAudioClient_AddRef(&This->IAudioClient_iface);
2028 static ULONG WINAPI AudioClock_Release(IAudioClock *iface)
2030 ACImpl *This = impl_from_IAudioClock(iface);
2031 return IAudioClient_Release(&This->IAudioClient_iface);
2034 static HRESULT WINAPI AudioClock_GetFrequency(IAudioClock *iface, UINT64 *freq)
2036 ACImpl *This = impl_from_IAudioClock(iface);
2037 HRESULT hr;
2039 TRACE("(%p)->(%p)\n", This, freq);
2041 pthread_mutex_lock(&pulse_lock);
2042 hr = pulse_stream_valid(This);
2043 if (SUCCEEDED(hr))
2044 *freq = This->ss.rate * pa_frame_size(&This->ss);
2045 pthread_mutex_unlock(&pulse_lock);
2046 return hr;
2049 static HRESULT WINAPI AudioClock_GetPosition(IAudioClock *iface, UINT64 *pos,
2050 UINT64 *qpctime)
2052 ACImpl *This = impl_from_IAudioClock(iface);
2053 HRESULT hr;
2055 TRACE("(%p)->(%p, %p)\n", This, pos, qpctime);
2057 if (!pos)
2058 return E_POINTER;
2060 pthread_mutex_lock(&pulse_lock);
2061 hr = pulse_stream_valid(This);
2062 if (FAILED(hr)) {
2063 pthread_mutex_unlock(&pulse_lock);
2064 return hr;
2067 *pos = This->clock_written;
2069 /* Make time never go backwards */
2070 if (*pos < This->clock_lastpos)
2071 *pos = This->clock_lastpos;
2072 else
2073 This->clock_lastpos = *pos;
2074 pthread_mutex_unlock(&pulse_lock);
2076 TRACE("%p Position: %u\n", This, (unsigned)*pos);
2078 if (qpctime) {
2079 LARGE_INTEGER stamp, freq;
2080 QueryPerformanceCounter(&stamp);
2081 QueryPerformanceFrequency(&freq);
2082 *qpctime = (stamp.QuadPart * (INT64)10000000) / freq.QuadPart;
2085 return S_OK;
2088 static HRESULT WINAPI AudioClock_GetCharacteristics(IAudioClock *iface,
2089 DWORD *chars)
2091 ACImpl *This = impl_from_IAudioClock(iface);
2093 TRACE("(%p)->(%p)\n", This, chars);
2095 if (!chars)
2096 return E_POINTER;
2098 *chars = AUDIOCLOCK_CHARACTERISTIC_FIXED_FREQ;
2100 return S_OK;
2103 static const IAudioClockVtbl AudioClock_Vtbl =
2105 AudioClock_QueryInterface,
2106 AudioClock_AddRef,
2107 AudioClock_Release,
2108 AudioClock_GetFrequency,
2109 AudioClock_GetPosition,
2110 AudioClock_GetCharacteristics
2113 static HRESULT WINAPI AudioClock2_QueryInterface(IAudioClock2 *iface,
2114 REFIID riid, void **ppv)
2116 ACImpl *This = impl_from_IAudioClock2(iface);
2117 return IAudioClock_QueryInterface(&This->IAudioClock_iface, riid, ppv);
2120 static ULONG WINAPI AudioClock2_AddRef(IAudioClock2 *iface)
2122 ACImpl *This = impl_from_IAudioClock2(iface);
2123 return IAudioClient_AddRef(&This->IAudioClient_iface);
2126 static ULONG WINAPI AudioClock2_Release(IAudioClock2 *iface)
2128 ACImpl *This = impl_from_IAudioClock2(iface);
2129 return IAudioClient_Release(&This->IAudioClient_iface);
2132 static HRESULT WINAPI AudioClock2_GetDevicePosition(IAudioClock2 *iface,
2133 UINT64 *pos, UINT64 *qpctime)
2135 ACImpl *This = impl_from_IAudioClock2(iface);
2136 HRESULT hr = AudioClock_GetPosition(&This->IAudioClock_iface, pos, qpctime);
2137 if (SUCCEEDED(hr))
2138 *pos /= pa_frame_size(&This->ss);
2139 return hr;
2142 static const IAudioClock2Vtbl AudioClock2_Vtbl =
2144 AudioClock2_QueryInterface,
2145 AudioClock2_AddRef,
2146 AudioClock2_Release,
2147 AudioClock2_GetDevicePosition
2150 static HRESULT WINAPI AudioStreamVolume_QueryInterface(
2151 IAudioStreamVolume *iface, REFIID riid, void **ppv)
2153 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
2155 if (!ppv)
2156 return E_POINTER;
2157 *ppv = NULL;
2159 if (IsEqualIID(riid, &IID_IUnknown) ||
2160 IsEqualIID(riid, &IID_IAudioStreamVolume))
2161 *ppv = iface;
2162 if (*ppv) {
2163 IUnknown_AddRef((IUnknown*)*ppv);
2164 return S_OK;
2167 WARN("Unknown interface %s\n", debugstr_guid(riid));
2168 return E_NOINTERFACE;
2171 static ULONG WINAPI AudioStreamVolume_AddRef(IAudioStreamVolume *iface)
2173 ACImpl *This = impl_from_IAudioStreamVolume(iface);
2174 return IAudioClient_AddRef(&This->IAudioClient_iface);
2177 static ULONG WINAPI AudioStreamVolume_Release(IAudioStreamVolume *iface)
2179 ACImpl *This = impl_from_IAudioStreamVolume(iface);
2180 return IAudioClient_Release(&This->IAudioClient_iface);
2183 static HRESULT WINAPI AudioStreamVolume_GetChannelCount(
2184 IAudioStreamVolume *iface, UINT32 *out)
2186 ACImpl *This = impl_from_IAudioStreamVolume(iface);
2188 TRACE("(%p)->(%p)\n", This, out);
2190 if (!out)
2191 return E_POINTER;
2193 *out = This->ss.channels;
2195 return S_OK;
2198 struct pulse_info_cb_data {
2199 UINT32 n;
2200 float *levels;
2203 static void pulse_sink_input_info_cb(pa_context *c, const pa_sink_input_info *info, int eol, void *data)
2205 struct pulse_info_cb_data *d = data;
2206 int i;
2207 if (eol)
2208 return;
2209 for (i = 0; i < d->n; ++i)
2210 d->levels[i] = (float)info->volume.values[i] / (float)PA_VOLUME_NORM;
2211 pthread_cond_signal(&pulse_cond);
2214 static void pulse_source_info_cb(pa_context *c, const pa_source_info *info, int eol, void *data)
2216 struct pulse_info_cb_data *d = data;
2217 int i;
2218 if (eol)
2219 return;
2220 for (i = 0; i < d->n; ++i)
2221 d->levels[i] = (float)info->volume.values[i] / (float)PA_VOLUME_NORM;
2222 pthread_cond_signal(&pulse_cond);
2225 static HRESULT WINAPI AudioStreamVolume_SetAllVolumes(
2226 IAudioStreamVolume *iface, UINT32 count, const float *levels)
2228 ACImpl *This = impl_from_IAudioStreamVolume(iface);
2229 pa_operation *o;
2230 HRESULT hr;
2231 int success = 0, i;
2232 pa_cvolume cv;
2234 TRACE("(%p)->(%d, %p)\n", This, count, levels);
2236 if (!levels)
2237 return E_POINTER;
2239 if (count != This->ss.channels)
2240 return E_INVALIDARG;
2242 pthread_mutex_lock(&pulse_lock);
2243 hr = pulse_stream_valid(This);
2244 if (FAILED(hr))
2245 goto out;
2247 if (pulse_stream_volume) {
2248 cv.channels = count;
2249 for (i = 0; i < cv.channels; ++i)
2250 cv.values[i] = levels[i] * (float)PA_VOLUME_NORM;
2251 if (This->dataflow == eRender)
2252 o = pa_context_set_sink_input_volume(pulse_ctx, pa_stream_get_index(This->stream), &cv, pulse_ctx_op_cb, &success);
2253 else
2254 o = pa_context_set_source_volume_by_index(pulse_ctx, pa_stream_get_device_index(This->stream), &cv, pulse_ctx_op_cb, &success);
2255 if (o) {
2256 while(pa_operation_get_state(o) == PA_OPERATION_RUNNING)
2257 pthread_cond_wait(&pulse_cond, &pulse_lock);
2258 pa_operation_unref(o);
2260 if (!success)
2261 hr = AUDCLNT_E_BUFFER_ERROR;
2262 } else {
2263 int i;
2264 for (i = 0; i < count; ++i)
2265 This->vol[i] = levels[i];
2268 out:
2269 pthread_mutex_unlock(&pulse_lock);
2270 return hr;
2273 static HRESULT WINAPI AudioStreamVolume_GetAllVolumes(
2274 IAudioStreamVolume *iface, UINT32 count, float *levels)
2276 ACImpl *This = impl_from_IAudioStreamVolume(iface);
2277 pa_operation *o;
2278 HRESULT hr;
2279 struct pulse_info_cb_data info;
2281 TRACE("(%p)->(%d, %p)\n", This, count, levels);
2283 if (!levels)
2284 return E_POINTER;
2286 if (count != This->ss.channels)
2287 return E_INVALIDARG;
2289 pthread_mutex_lock(&pulse_lock);
2290 hr = pulse_stream_valid(This);
2291 if (FAILED(hr))
2292 goto out;
2294 if (pulse_stream_volume) {
2295 info.n = count;
2296 info.levels = levels;
2297 if (This->dataflow == eRender)
2298 o = pa_context_get_sink_input_info(pulse_ctx, pa_stream_get_index(This->stream), pulse_sink_input_info_cb, &info);
2299 else
2300 o = pa_context_get_source_info_by_index(pulse_ctx, pa_stream_get_device_index(This->stream), pulse_source_info_cb, &info);
2301 if (o) {
2302 while(pa_operation_get_state(o) == PA_OPERATION_RUNNING)
2303 pthread_cond_wait(&pulse_cond, &pulse_lock);
2304 pa_operation_unref(o);
2305 } else
2306 hr = AUDCLNT_E_BUFFER_ERROR;
2307 } else {
2308 int i;
2309 for (i = 0; i < count; ++i)
2310 levels[i] = This->vol[i];
2313 out:
2314 pthread_mutex_unlock(&pulse_lock);
2315 return hr;
2318 static HRESULT WINAPI AudioStreamVolume_SetChannelVolume(
2319 IAudioStreamVolume *iface, UINT32 index, float level)
2321 ACImpl *This = impl_from_IAudioStreamVolume(iface);
2322 HRESULT hr;
2323 float volumes[PA_CHANNELS_MAX];
2325 TRACE("(%p)->(%d, %f)\n", This, index, level);
2327 if (level < 0.f || level > 1.f)
2328 return E_INVALIDARG;
2330 if (index >= This->ss.channels)
2331 return E_INVALIDARG;
2333 hr = AudioStreamVolume_GetAllVolumes(iface, This->ss.channels, volumes);
2334 volumes[index] = level;
2335 if (SUCCEEDED(hr))
2336 hr = AudioStreamVolume_SetAllVolumes(iface, This->ss.channels, volumes);
2337 return hr;
2340 static HRESULT WINAPI AudioStreamVolume_GetChannelVolume(
2341 IAudioStreamVolume *iface, UINT32 index, float *level)
2343 ACImpl *This = impl_from_IAudioStreamVolume(iface);
2344 float volumes[PA_CHANNELS_MAX];
2345 HRESULT hr;
2347 TRACE("(%p)->(%d, %p)\n", This, index, level);
2349 if (!level)
2350 return E_POINTER;
2352 if (index >= This->ss.channels)
2353 return E_INVALIDARG;
2355 hr = AudioStreamVolume_GetAllVolumes(iface, This->ss.channels, volumes);
2356 if (SUCCEEDED(hr))
2357 *level = volumes[index];
2358 return hr;
2361 static const IAudioStreamVolumeVtbl AudioStreamVolume_Vtbl =
2363 AudioStreamVolume_QueryInterface,
2364 AudioStreamVolume_AddRef,
2365 AudioStreamVolume_Release,
2366 AudioStreamVolume_GetChannelCount,
2367 AudioStreamVolume_SetChannelVolume,
2368 AudioStreamVolume_GetChannelVolume,
2369 AudioStreamVolume_SetAllVolumes,
2370 AudioStreamVolume_GetAllVolumes
2373 static AudioSessionWrapper *AudioSessionWrapper_Create(ACImpl *client)
2375 AudioSessionWrapper *ret;
2377 ret = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
2378 sizeof(AudioSessionWrapper));
2379 if (!ret)
2380 return NULL;
2382 ret->IAudioSessionControl2_iface.lpVtbl = &AudioSessionControl2_Vtbl;
2383 ret->ISimpleAudioVolume_iface.lpVtbl = &SimpleAudioVolume_Vtbl;
2384 ret->IChannelAudioVolume_iface.lpVtbl = &ChannelAudioVolume_Vtbl;
2386 ret->ref = !client;
2388 ret->client = client;
2389 if (client) {
2390 ret->session = client->session;
2391 AudioClient_AddRef(&client->IAudioClient_iface);
2394 return ret;
2397 static HRESULT WINAPI AudioSessionControl_QueryInterface(
2398 IAudioSessionControl2 *iface, REFIID riid, void **ppv)
2400 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
2402 if (!ppv)
2403 return E_POINTER;
2404 *ppv = NULL;
2406 if (IsEqualIID(riid, &IID_IUnknown) ||
2407 IsEqualIID(riid, &IID_IAudioSessionControl) ||
2408 IsEqualIID(riid, &IID_IAudioSessionControl2))
2409 *ppv = iface;
2410 if (*ppv) {
2411 IUnknown_AddRef((IUnknown*)*ppv);
2412 return S_OK;
2415 WARN("Unknown interface %s\n", debugstr_guid(riid));
2416 return E_NOINTERFACE;
2419 static ULONG WINAPI AudioSessionControl_AddRef(IAudioSessionControl2 *iface)
2421 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2422 ULONG ref;
2423 ref = InterlockedIncrement(&This->ref);
2424 TRACE("(%p) Refcount now %u\n", This, ref);
2425 return ref;
2428 static ULONG WINAPI AudioSessionControl_Release(IAudioSessionControl2 *iface)
2430 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2431 ULONG ref;
2432 ref = InterlockedDecrement(&This->ref);
2433 TRACE("(%p) Refcount now %u\n", This, ref);
2434 if (!ref) {
2435 if (This->client) {
2436 This->client->session_wrapper = NULL;
2437 AudioClient_Release(&This->client->IAudioClient_iface);
2439 HeapFree(GetProcessHeap(), 0, This);
2441 return ref;
2444 static HRESULT WINAPI AudioSessionControl_GetState(IAudioSessionControl2 *iface,
2445 AudioSessionState *state)
2447 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2448 ACImpl *client;
2450 TRACE("(%p)->(%p)\n", This, state);
2452 if (!state)
2453 return NULL_PTR_ERR;
2455 pthread_mutex_lock(&pulse_lock);
2456 if (list_empty(&This->session->clients)) {
2457 *state = AudioSessionStateExpired;
2458 goto out;
2460 LIST_FOR_EACH_ENTRY(client, &This->session->clients, ACImpl, entry) {
2461 if (client->started) {
2462 *state = AudioSessionStateActive;
2463 goto out;
2466 *state = AudioSessionStateInactive;
2468 out:
2469 pthread_mutex_unlock(&pulse_lock);
2470 return S_OK;
2473 static HRESULT WINAPI AudioSessionControl_GetDisplayName(
2474 IAudioSessionControl2 *iface, WCHAR **name)
2476 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2478 FIXME("(%p)->(%p) - stub\n", This, name);
2480 return E_NOTIMPL;
2483 static HRESULT WINAPI AudioSessionControl_SetDisplayName(
2484 IAudioSessionControl2 *iface, const WCHAR *name, const GUID *session)
2486 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2488 FIXME("(%p)->(%p, %s) - stub\n", This, name, debugstr_guid(session));
2490 return E_NOTIMPL;
2493 static HRESULT WINAPI AudioSessionControl_GetIconPath(
2494 IAudioSessionControl2 *iface, WCHAR **path)
2496 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2498 FIXME("(%p)->(%p) - stub\n", This, path);
2500 return E_NOTIMPL;
2503 static HRESULT WINAPI AudioSessionControl_SetIconPath(
2504 IAudioSessionControl2 *iface, const WCHAR *path, const GUID *session)
2506 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2508 FIXME("(%p)->(%p, %s) - stub\n", This, path, debugstr_guid(session));
2510 return E_NOTIMPL;
2513 static HRESULT WINAPI AudioSessionControl_GetGroupingParam(
2514 IAudioSessionControl2 *iface, GUID *group)
2516 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2518 FIXME("(%p)->(%p) - stub\n", This, group);
2520 return E_NOTIMPL;
2523 static HRESULT WINAPI AudioSessionControl_SetGroupingParam(
2524 IAudioSessionControl2 *iface, const GUID *group, const GUID *session)
2526 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2528 FIXME("(%p)->(%s, %s) - stub\n", This, debugstr_guid(group),
2529 debugstr_guid(session));
2531 return E_NOTIMPL;
2534 static HRESULT WINAPI AudioSessionControl_RegisterAudioSessionNotification(
2535 IAudioSessionControl2 *iface, IAudioSessionEvents *events)
2537 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2539 FIXME("(%p)->(%p) - stub\n", This, events);
2541 return S_OK;
2544 static HRESULT WINAPI AudioSessionControl_UnregisterAudioSessionNotification(
2545 IAudioSessionControl2 *iface, IAudioSessionEvents *events)
2547 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2549 FIXME("(%p)->(%p) - stub\n", This, events);
2551 return S_OK;
2554 static HRESULT WINAPI AudioSessionControl_GetSessionIdentifier(
2555 IAudioSessionControl2 *iface, WCHAR **id)
2557 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2559 FIXME("(%p)->(%p) - stub\n", This, id);
2561 return E_NOTIMPL;
2564 static HRESULT WINAPI AudioSessionControl_GetSessionInstanceIdentifier(
2565 IAudioSessionControl2 *iface, WCHAR **id)
2567 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2569 FIXME("(%p)->(%p) - stub\n", This, id);
2571 return E_NOTIMPL;
2574 static HRESULT WINAPI AudioSessionControl_GetProcessId(
2575 IAudioSessionControl2 *iface, DWORD *pid)
2577 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2579 TRACE("(%p)->(%p)\n", This, pid);
2581 if (!pid)
2582 return E_POINTER;
2584 *pid = GetCurrentProcessId();
2586 return S_OK;
2589 static HRESULT WINAPI AudioSessionControl_IsSystemSoundsSession(
2590 IAudioSessionControl2 *iface)
2592 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2594 TRACE("(%p)\n", This);
2596 return S_FALSE;
2599 static HRESULT WINAPI AudioSessionControl_SetDuckingPreference(
2600 IAudioSessionControl2 *iface, BOOL optout)
2602 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2604 TRACE("(%p)->(%d)\n", This, optout);
2606 return S_OK;
2609 static const IAudioSessionControl2Vtbl AudioSessionControl2_Vtbl =
2611 AudioSessionControl_QueryInterface,
2612 AudioSessionControl_AddRef,
2613 AudioSessionControl_Release,
2614 AudioSessionControl_GetState,
2615 AudioSessionControl_GetDisplayName,
2616 AudioSessionControl_SetDisplayName,
2617 AudioSessionControl_GetIconPath,
2618 AudioSessionControl_SetIconPath,
2619 AudioSessionControl_GetGroupingParam,
2620 AudioSessionControl_SetGroupingParam,
2621 AudioSessionControl_RegisterAudioSessionNotification,
2622 AudioSessionControl_UnregisterAudioSessionNotification,
2623 AudioSessionControl_GetSessionIdentifier,
2624 AudioSessionControl_GetSessionInstanceIdentifier,
2625 AudioSessionControl_GetProcessId,
2626 AudioSessionControl_IsSystemSoundsSession,
2627 AudioSessionControl_SetDuckingPreference
2630 typedef struct _SessionMgr {
2631 IAudioSessionManager2 IAudioSessionManager2_iface;
2633 LONG ref;
2635 IMMDevice *device;
2636 } SessionMgr;
2638 static HRESULT WINAPI AudioSessionManager_QueryInterface(IAudioSessionManager2 *iface,
2639 REFIID riid, void **ppv)
2641 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
2643 if (!ppv)
2644 return E_POINTER;
2645 *ppv = NULL;
2647 if (IsEqualIID(riid, &IID_IUnknown) ||
2648 IsEqualIID(riid, &IID_IAudioSessionManager) ||
2649 IsEqualIID(riid, &IID_IAudioSessionManager2))
2650 *ppv = iface;
2651 if (*ppv) {
2652 IUnknown_AddRef((IUnknown*)*ppv);
2653 return S_OK;
2656 WARN("Unknown interface %s\n", debugstr_guid(riid));
2657 return E_NOINTERFACE;
2660 static inline SessionMgr *impl_from_IAudioSessionManager2(IAudioSessionManager2 *iface)
2662 return CONTAINING_RECORD(iface, SessionMgr, IAudioSessionManager2_iface);
2665 static ULONG WINAPI AudioSessionManager_AddRef(IAudioSessionManager2 *iface)
2667 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
2668 ULONG ref;
2669 ref = InterlockedIncrement(&This->ref);
2670 TRACE("(%p) Refcount now %u\n", This, ref);
2671 return ref;
2674 static ULONG WINAPI AudioSessionManager_Release(IAudioSessionManager2 *iface)
2676 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
2677 ULONG ref;
2678 ref = InterlockedDecrement(&This->ref);
2679 TRACE("(%p) Refcount now %u\n", This, ref);
2680 if (!ref)
2681 HeapFree(GetProcessHeap(), 0, This);
2682 return ref;
2685 static HRESULT WINAPI AudioSessionManager_GetAudioSessionControl(
2686 IAudioSessionManager2 *iface, const GUID *session_guid, DWORD flags,
2687 IAudioSessionControl **out)
2689 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
2690 AudioSession *session;
2691 AudioSessionWrapper *wrapper;
2692 HRESULT hr;
2694 TRACE("(%p)->(%s, %x, %p)\n", This, debugstr_guid(session_guid),
2695 flags, out);
2697 hr = get_audio_session(session_guid, This->device, 0, &session);
2698 if (FAILED(hr))
2699 return hr;
2701 wrapper = AudioSessionWrapper_Create(NULL);
2702 if (!wrapper)
2703 return E_OUTOFMEMORY;
2705 wrapper->session = session;
2707 *out = (IAudioSessionControl*)&wrapper->IAudioSessionControl2_iface;
2709 return S_OK;
2712 static HRESULT WINAPI AudioSessionManager_GetSimpleAudioVolume(
2713 IAudioSessionManager2 *iface, const GUID *session_guid, DWORD flags,
2714 ISimpleAudioVolume **out)
2716 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
2717 AudioSession *session;
2718 AudioSessionWrapper *wrapper;
2719 HRESULT hr;
2721 TRACE("(%p)->(%s, %x, %p)\n", This, debugstr_guid(session_guid),
2722 flags, out);
2724 hr = get_audio_session(session_guid, This->device, 0, &session);
2725 if (FAILED(hr))
2726 return hr;
2728 wrapper = AudioSessionWrapper_Create(NULL);
2729 if (!wrapper)
2730 return E_OUTOFMEMORY;
2732 wrapper->session = session;
2734 *out = &wrapper->ISimpleAudioVolume_iface;
2736 return S_OK;
2739 static HRESULT WINAPI AudioSessionManager_GetSessionEnumerator(
2740 IAudioSessionManager2 *iface, IAudioSessionEnumerator **out)
2742 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
2743 FIXME("(%p)->(%p) - stub\n", This, out);
2744 return E_NOTIMPL;
2747 static HRESULT WINAPI AudioSessionManager_RegisterSessionNotification(
2748 IAudioSessionManager2 *iface, IAudioSessionNotification *notification)
2750 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
2751 FIXME("(%p)->(%p) - stub\n", This, notification);
2752 return E_NOTIMPL;
2755 static HRESULT WINAPI AudioSessionManager_UnregisterSessionNotification(
2756 IAudioSessionManager2 *iface, IAudioSessionNotification *notification)
2758 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
2759 FIXME("(%p)->(%p) - stub\n", This, notification);
2760 return E_NOTIMPL;
2763 static HRESULT WINAPI AudioSessionManager_RegisterDuckNotification(
2764 IAudioSessionManager2 *iface, const WCHAR *session_id,
2765 IAudioVolumeDuckNotification *notification)
2767 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
2768 FIXME("(%p)->(%p) - stub\n", This, notification);
2769 return E_NOTIMPL;
2772 static HRESULT WINAPI AudioSessionManager_UnregisterDuckNotification(
2773 IAudioSessionManager2 *iface,
2774 IAudioVolumeDuckNotification *notification)
2776 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
2777 FIXME("(%p)->(%p) - stub\n", This, notification);
2778 return E_NOTIMPL;
2781 static const IAudioSessionManager2Vtbl AudioSessionManager2_Vtbl =
2783 AudioSessionManager_QueryInterface,
2784 AudioSessionManager_AddRef,
2785 AudioSessionManager_Release,
2786 AudioSessionManager_GetAudioSessionControl,
2787 AudioSessionManager_GetSimpleAudioVolume,
2788 AudioSessionManager_GetSessionEnumerator,
2789 AudioSessionManager_RegisterSessionNotification,
2790 AudioSessionManager_UnregisterSessionNotification,
2791 AudioSessionManager_RegisterDuckNotification,
2792 AudioSessionManager_UnregisterDuckNotification
2795 static HRESULT WINAPI SimpleAudioVolume_QueryInterface(
2796 ISimpleAudioVolume *iface, REFIID riid, void **ppv)
2798 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
2800 if (!ppv)
2801 return E_POINTER;
2802 *ppv = NULL;
2804 if (IsEqualIID(riid, &IID_IUnknown) ||
2805 IsEqualIID(riid, &IID_ISimpleAudioVolume))
2806 *ppv = iface;
2807 if (*ppv) {
2808 IUnknown_AddRef((IUnknown*)*ppv);
2809 return S_OK;
2812 WARN("Unknown interface %s\n", debugstr_guid(riid));
2813 return E_NOINTERFACE;
2816 static ULONG WINAPI SimpleAudioVolume_AddRef(ISimpleAudioVolume *iface)
2818 AudioSessionWrapper *This = impl_from_ISimpleAudioVolume(iface);
2819 return AudioSessionControl_AddRef(&This->IAudioSessionControl2_iface);
2822 static ULONG WINAPI SimpleAudioVolume_Release(ISimpleAudioVolume *iface)
2824 AudioSessionWrapper *This = impl_from_ISimpleAudioVolume(iface);
2825 return AudioSessionControl_Release(&This->IAudioSessionControl2_iface);
2828 static HRESULT WINAPI SimpleAudioVolume_SetMasterVolume(
2829 ISimpleAudioVolume *iface, float level, const GUID *context)
2831 AudioSessionWrapper *This = impl_from_ISimpleAudioVolume(iface);
2832 AudioSession *session = This->session;
2834 TRACE("(%p)->(%f, %s)\n", session, level, wine_dbgstr_guid(context));
2836 if (level < 0.f || level > 1.f)
2837 return E_INVALIDARG;
2839 if (context)
2840 FIXME("Notifications not supported yet\n");
2842 TRACE("Pulseaudio does not support session volume control\n");
2844 pthread_mutex_lock(&pulse_lock);
2845 session->master_vol = level;
2846 pthread_mutex_unlock(&pulse_lock);
2848 return S_OK;
2851 static HRESULT WINAPI SimpleAudioVolume_GetMasterVolume(
2852 ISimpleAudioVolume *iface, float *level)
2854 AudioSessionWrapper *This = impl_from_ISimpleAudioVolume(iface);
2855 AudioSession *session = This->session;
2857 TRACE("(%p)->(%p)\n", session, level);
2859 if (!level)
2860 return NULL_PTR_ERR;
2862 *level = session->master_vol;
2864 return S_OK;
2867 static HRESULT WINAPI SimpleAudioVolume_SetMute(ISimpleAudioVolume *iface,
2868 BOOL mute, const GUID *context)
2870 AudioSessionWrapper *This = impl_from_ISimpleAudioVolume(iface);
2871 AudioSession *session = This->session;
2873 TRACE("(%p)->(%u, %p)\n", session, mute, context);
2875 if (context)
2876 FIXME("Notifications not supported yet\n");
2878 session->mute = mute;
2880 return S_OK;
2883 static HRESULT WINAPI SimpleAudioVolume_GetMute(ISimpleAudioVolume *iface,
2884 BOOL *mute)
2886 AudioSessionWrapper *This = impl_from_ISimpleAudioVolume(iface);
2887 AudioSession *session = This->session;
2889 TRACE("(%p)->(%p)\n", session, mute);
2891 if (!mute)
2892 return NULL_PTR_ERR;
2894 *mute = session->mute;
2896 return S_OK;
2899 static const ISimpleAudioVolumeVtbl SimpleAudioVolume_Vtbl =
2901 SimpleAudioVolume_QueryInterface,
2902 SimpleAudioVolume_AddRef,
2903 SimpleAudioVolume_Release,
2904 SimpleAudioVolume_SetMasterVolume,
2905 SimpleAudioVolume_GetMasterVolume,
2906 SimpleAudioVolume_SetMute,
2907 SimpleAudioVolume_GetMute
2910 static HRESULT WINAPI ChannelAudioVolume_QueryInterface(
2911 IChannelAudioVolume *iface, REFIID riid, void **ppv)
2913 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
2915 if (!ppv)
2916 return E_POINTER;
2917 *ppv = NULL;
2919 if (IsEqualIID(riid, &IID_IUnknown) ||
2920 IsEqualIID(riid, &IID_IChannelAudioVolume))
2921 *ppv = iface;
2922 if (*ppv) {
2923 IUnknown_AddRef((IUnknown*)*ppv);
2924 return S_OK;
2927 WARN("Unknown interface %s\n", debugstr_guid(riid));
2928 return E_NOINTERFACE;
2931 static ULONG WINAPI ChannelAudioVolume_AddRef(IChannelAudioVolume *iface)
2933 AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
2934 return AudioSessionControl_AddRef(&This->IAudioSessionControl2_iface);
2937 static ULONG WINAPI ChannelAudioVolume_Release(IChannelAudioVolume *iface)
2939 AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
2940 return AudioSessionControl_Release(&This->IAudioSessionControl2_iface);
2943 static HRESULT WINAPI ChannelAudioVolume_GetChannelCount(
2944 IChannelAudioVolume *iface, UINT32 *out)
2946 AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
2947 AudioSession *session = This->session;
2949 TRACE("(%p)->(%p)\n", session, out);
2951 if (!out)
2952 return NULL_PTR_ERR;
2954 *out = session->channel_count;
2956 return S_OK;
2959 static HRESULT WINAPI ChannelAudioVolume_SetChannelVolume(
2960 IChannelAudioVolume *iface, UINT32 index, float level,
2961 const GUID *context)
2963 AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
2964 AudioSession *session = This->session;
2966 TRACE("(%p)->(%d, %f, %s)\n", session, index, level,
2967 wine_dbgstr_guid(context));
2969 if (level < 0.f || level > 1.f)
2970 return E_INVALIDARG;
2972 if (index >= session->channel_count)
2973 return E_INVALIDARG;
2975 if (context)
2976 FIXME("Notifications not supported yet\n");
2978 TRACE("Pulseaudio does not support session volume control\n");
2980 pthread_mutex_lock(&pulse_lock);
2981 session->channel_vols[index] = level;
2982 pthread_mutex_unlock(&pulse_lock);
2984 return S_OK;
2987 static HRESULT WINAPI ChannelAudioVolume_GetChannelVolume(
2988 IChannelAudioVolume *iface, UINT32 index, float *level)
2990 AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
2991 AudioSession *session = This->session;
2993 TRACE("(%p)->(%d, %p)\n", session, index, level);
2995 if (!level)
2996 return NULL_PTR_ERR;
2998 if (index >= session->channel_count)
2999 return E_INVALIDARG;
3001 *level = session->channel_vols[index];
3003 return S_OK;
3006 static HRESULT WINAPI ChannelAudioVolume_SetAllVolumes(
3007 IChannelAudioVolume *iface, UINT32 count, const float *levels,
3008 const GUID *context)
3010 AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
3011 AudioSession *session = This->session;
3012 int i;
3014 TRACE("(%p)->(%d, %p, %s)\n", session, count, levels,
3015 wine_dbgstr_guid(context));
3017 if (!levels)
3018 return NULL_PTR_ERR;
3020 if (count != session->channel_count)
3021 return E_INVALIDARG;
3023 if (context)
3024 FIXME("Notifications not supported yet\n");
3026 TRACE("Pulseaudio does not support session volume control\n");
3028 pthread_mutex_lock(&pulse_lock);
3029 for(i = 0; i < count; ++i)
3030 session->channel_vols[i] = levels[i];
3031 pthread_mutex_unlock(&pulse_lock);
3032 return S_OK;
3035 static HRESULT WINAPI ChannelAudioVolume_GetAllVolumes(
3036 IChannelAudioVolume *iface, UINT32 count, float *levels)
3038 AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
3039 AudioSession *session = This->session;
3040 int i;
3042 TRACE("(%p)->(%d, %p)\n", session, count, levels);
3044 if (!levels)
3045 return NULL_PTR_ERR;
3047 if (count != session->channel_count)
3048 return E_INVALIDARG;
3050 for(i = 0; i < count; ++i)
3051 levels[i] = session->channel_vols[i];
3053 return S_OK;
3056 static const IChannelAudioVolumeVtbl ChannelAudioVolume_Vtbl =
3058 ChannelAudioVolume_QueryInterface,
3059 ChannelAudioVolume_AddRef,
3060 ChannelAudioVolume_Release,
3061 ChannelAudioVolume_GetChannelCount,
3062 ChannelAudioVolume_SetChannelVolume,
3063 ChannelAudioVolume_GetChannelVolume,
3064 ChannelAudioVolume_SetAllVolumes,
3065 ChannelAudioVolume_GetAllVolumes
3068 HRESULT WINAPI AUDDRV_GetAudioSessionManager(IMMDevice *device,
3069 IAudioSessionManager2 **out)
3071 SessionMgr *This = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(SessionMgr));
3072 *out = NULL;
3073 if (!This)
3074 return E_OUTOFMEMORY;
3075 This->IAudioSessionManager2_iface.lpVtbl = &AudioSessionManager2_Vtbl;
3076 This->device = device;
3077 This->ref = 1;
3078 *out = &This->IAudioSessionManager2_iface;
3079 return S_OK;