winepulse.drv: API Compatibility with 1.5.2 onward
[wine/multimedia.git] / dlls / winepulse.drv / mmdevdrv.c
blob5cc460f4f93db8dd4bcc23a5b9e31708139ca334
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 GUID pulse_render_guid =
86 { 0xfd47d9cc, 0x4218, 0x4135, { 0x9c, 0xe2, 0x0c, 0x19, 0x5c, 0x87, 0x40, 0x5b } };
87 static GUID pulse_capture_guid =
88 { 0x25da76d0, 0x033c, 0x4235, { 0x90, 0x02, 0x19, 0xf4, 0x88, 0x94, 0xac, 0x6f } };
90 static HANDLE warn_once;
92 BOOL WINAPI DllMain(HINSTANCE dll, DWORD reason, void *reserved)
94 if (reason == DLL_PROCESS_ATTACH) {
95 HKEY key;
96 if (RegOpenKeyW(HKEY_CURRENT_USER, pulse_keyW, &key) == ERROR_SUCCESS) {
97 DWORD size = sizeof(pulse_stream_volume);
98 RegQueryValueExW(key, pulse_streamW, 0, NULL,
99 (BYTE*)&pulse_stream_volume, &size);
100 RegCloseKey(key);
102 DisableThreadLibraryCalls(dll);
103 } else if (reason == DLL_PROCESS_DETACH) {
104 if (pulse_ctx) {
105 pa_context_disconnect(pulse_ctx);
106 pa_context_unref(pulse_ctx);
108 if (pulse_ml)
109 pa_mainloop_quit(pulse_ml, 0);
110 if (pulse_thread)
111 CloseHandle(pulse_thread);
112 if (warn_once)
113 CloseHandle(warn_once);
115 return TRUE;
118 typedef struct ACImpl ACImpl;
120 typedef struct _AudioSession {
121 GUID guid;
122 struct list clients;
124 IMMDevice *device;
126 float master_vol;
127 UINT32 channel_count;
128 float *channel_vols;
129 BOOL mute;
131 struct list entry;
132 } AudioSession;
134 typedef struct _AudioSessionWrapper {
135 IAudioSessionControl2 IAudioSessionControl2_iface;
136 IChannelAudioVolume IChannelAudioVolume_iface;
137 ISimpleAudioVolume ISimpleAudioVolume_iface;
139 LONG ref;
141 ACImpl *client;
142 AudioSession *session;
143 } AudioSessionWrapper;
145 typedef struct _ACPacket {
146 struct list entry;
147 UINT64 qpcpos;
148 BYTE *data;
149 UINT32 discont;
150 } ACPacket;
152 struct ACImpl {
153 IAudioClient IAudioClient_iface;
154 IAudioRenderClient IAudioRenderClient_iface;
155 IAudioCaptureClient IAudioCaptureClient_iface;
156 IAudioClock IAudioClock_iface;
157 IAudioClock2 IAudioClock2_iface;
158 IAudioStreamVolume IAudioStreamVolume_iface;
159 IMMDevice *parent;
160 struct list entry;
161 float vol[PA_CHANNELS_MAX];
163 LONG ref;
164 EDataFlow dataflow;
165 DWORD flags;
166 AUDCLNT_SHAREMODE share;
167 HANDLE event;
169 UINT32 bufsize_frames, bufsize_bytes, locked, capture_period, pad, started, peek_ofs;
170 void *locked_ptr, *tmp_buffer;
172 pa_stream *stream;
173 pa_sample_spec ss;
174 pa_channel_map map;
176 INT64 clock_lastpos, clock_written;
177 pa_usec_t clock_pulse;
179 AudioSession *session;
180 AudioSessionWrapper *session_wrapper;
181 struct list packet_free_head;
182 struct list packet_filled_head;
185 static const WCHAR defaultW[] = {'P','u','l','s','e','a','u','d','i','o',0};
187 static const IAudioClientVtbl AudioClient_Vtbl;
188 static const IAudioRenderClientVtbl AudioRenderClient_Vtbl;
189 static const IAudioCaptureClientVtbl AudioCaptureClient_Vtbl;
190 static const IAudioSessionControl2Vtbl AudioSessionControl2_Vtbl;
191 static const ISimpleAudioVolumeVtbl SimpleAudioVolume_Vtbl;
192 static const IChannelAudioVolumeVtbl ChannelAudioVolume_Vtbl;
193 static const IAudioClockVtbl AudioClock_Vtbl;
194 static const IAudioClock2Vtbl AudioClock2_Vtbl;
195 static const IAudioStreamVolumeVtbl AudioStreamVolume_Vtbl;
197 static AudioSessionWrapper *AudioSessionWrapper_Create(ACImpl *client);
199 static inline ACImpl *impl_from_IAudioClient(IAudioClient *iface)
201 return CONTAINING_RECORD(iface, ACImpl, IAudioClient_iface);
204 static inline ACImpl *impl_from_IAudioRenderClient(IAudioRenderClient *iface)
206 return CONTAINING_RECORD(iface, ACImpl, IAudioRenderClient_iface);
209 static inline ACImpl *impl_from_IAudioCaptureClient(IAudioCaptureClient *iface)
211 return CONTAINING_RECORD(iface, ACImpl, IAudioCaptureClient_iface);
214 static inline AudioSessionWrapper *impl_from_IAudioSessionControl2(IAudioSessionControl2 *iface)
216 return CONTAINING_RECORD(iface, AudioSessionWrapper, IAudioSessionControl2_iface);
219 static inline AudioSessionWrapper *impl_from_ISimpleAudioVolume(ISimpleAudioVolume *iface)
221 return CONTAINING_RECORD(iface, AudioSessionWrapper, ISimpleAudioVolume_iface);
224 static inline AudioSessionWrapper *impl_from_IChannelAudioVolume(IChannelAudioVolume *iface)
226 return CONTAINING_RECORD(iface, AudioSessionWrapper, IChannelAudioVolume_iface);
229 static inline ACImpl *impl_from_IAudioClock(IAudioClock *iface)
231 return CONTAINING_RECORD(iface, ACImpl, IAudioClock_iface);
234 static inline ACImpl *impl_from_IAudioClock2(IAudioClock2 *iface)
236 return CONTAINING_RECORD(iface, ACImpl, IAudioClock2_iface);
239 static inline ACImpl *impl_from_IAudioStreamVolume(IAudioStreamVolume *iface)
241 return CONTAINING_RECORD(iface, ACImpl, IAudioStreamVolume_iface);
244 /* Following pulseaudio design here, mainloop has the lock taken whenever
245 * it is handling something for pulse, and the lock is required whenever
246 * doing any pa_* call that can affect the state in any way
248 * pa_cond_wait is used when waiting on results, because the mainloop needs
249 * the same lock taken to affect the state
251 * This is basically the same as the pa_threaded_mainloop implementation,
252 * but that cannot be used because it uses pthread_create directly
254 * pa_threaded_mainloop_(un)lock -> pthread_mutex_(un)lock
255 * pa_threaded_mainloop_signal -> pthread_cond_signal
256 * pa_threaded_mainloop_wait -> pthread_cond_wait
259 static int pulse_poll_func(struct pollfd *ufds, unsigned long nfds, int timeout, void *userdata) {
260 int r;
261 pthread_mutex_unlock(&pulse_lock);
262 r = poll(ufds, nfds, timeout);
263 pthread_mutex_lock(&pulse_lock);
264 return r;
267 static DWORD CALLBACK pulse_mainloop_thread(void *tmp) {
268 int ret;
269 pulse_ml = pa_mainloop_new();
270 pa_mainloop_set_poll_func(pulse_ml, pulse_poll_func, NULL);
271 pthread_mutex_lock(&pulse_lock);
272 pthread_cond_signal(&pulse_cond);
273 pa_mainloop_run(pulse_ml, &ret);
274 pthread_mutex_unlock(&pulse_lock);
275 pa_mainloop_free(pulse_ml);
276 CloseHandle(pulse_thread);
277 return ret;
280 static void pulse_contextcallback(pa_context *c, void *userdata);
281 static void pulse_stream_state(pa_stream *s, void *user);
283 static const enum pa_channel_position pulse_pos_from_wfx[] = {
284 PA_CHANNEL_POSITION_FRONT_LEFT,
285 PA_CHANNEL_POSITION_FRONT_RIGHT,
286 PA_CHANNEL_POSITION_FRONT_CENTER,
287 PA_CHANNEL_POSITION_LFE,
288 PA_CHANNEL_POSITION_REAR_LEFT,
289 PA_CHANNEL_POSITION_REAR_RIGHT,
290 PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER,
291 PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER,
292 PA_CHANNEL_POSITION_REAR_CENTER,
293 PA_CHANNEL_POSITION_SIDE_LEFT,
294 PA_CHANNEL_POSITION_SIDE_RIGHT,
295 PA_CHANNEL_POSITION_TOP_CENTER,
296 PA_CHANNEL_POSITION_TOP_FRONT_LEFT,
297 PA_CHANNEL_POSITION_TOP_FRONT_CENTER,
298 PA_CHANNEL_POSITION_TOP_FRONT_RIGHT,
299 PA_CHANNEL_POSITION_TOP_REAR_LEFT,
300 PA_CHANNEL_POSITION_TOP_REAR_CENTER,
301 PA_CHANNEL_POSITION_TOP_REAR_RIGHT
304 static void pulse_probe_settings(int render, WAVEFORMATEXTENSIBLE *fmt) {
305 WAVEFORMATEX *wfx = &fmt->Format;
306 pa_stream *stream;
307 pa_channel_map map;
308 pa_sample_spec ss;
309 pa_buffer_attr attr;
310 int ret, i;
311 unsigned int length = 0;
313 pa_channel_map_init_auto(&map, 2, PA_CHANNEL_MAP_ALSA);
314 ss.rate = 48000;
315 ss.format = PA_SAMPLE_FLOAT32LE;
316 ss.channels = map.channels;
318 attr.maxlength = -1;
319 attr.tlength = -1;
320 attr.minreq = attr.fragsize = pa_frame_size(&ss);
321 attr.prebuf = 0;
323 stream = pa_stream_new(pulse_ctx, "format test stream", &ss, &map);
324 if (stream)
325 pa_stream_set_state_callback(stream, pulse_stream_state, NULL);
326 if (!stream)
327 ret = -1;
328 else if (render)
329 ret = pa_stream_connect_playback(stream, NULL, &attr,
330 PA_STREAM_START_CORKED|PA_STREAM_FIX_RATE|PA_STREAM_FIX_CHANNELS|PA_STREAM_EARLY_REQUESTS, NULL, NULL);
331 else
332 ret = pa_stream_connect_record(stream, NULL, &attr, PA_STREAM_START_CORKED|PA_STREAM_FIX_RATE|PA_STREAM_FIX_CHANNELS|PA_STREAM_EARLY_REQUESTS);
333 if (ret >= 0) {
334 while (pa_stream_get_state(stream) == PA_STREAM_CREATING)
335 pthread_cond_wait(&pulse_cond, &pulse_lock);
336 if (pa_stream_get_state(stream) == PA_STREAM_READY) {
337 ss = *pa_stream_get_sample_spec(stream);
338 map = *pa_stream_get_channel_map(stream);
339 if (render)
340 length = pa_stream_get_buffer_attr(stream)->minreq;
341 else
342 length = pa_stream_get_buffer_attr(stream)->fragsize;
343 pa_stream_disconnect(stream);
344 while (pa_stream_get_state(stream) == PA_STREAM_READY)
345 pthread_cond_wait(&pulse_cond, &pulse_lock);
348 if (stream)
349 pa_stream_unref(stream);
350 if (length)
351 pulse_def_period[!render] = pulse_min_period[!render] = pa_bytes_to_usec(10 * length, &ss);
352 else
353 pulse_min_period[!render] = MinimumPeriod;
354 if (pulse_def_period[!render] <= DefaultPeriod)
355 pulse_def_period[!render] = DefaultPeriod;
357 wfx->wFormatTag = WAVE_FORMAT_EXTENSIBLE;
358 wfx->cbSize = sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX);
359 wfx->nChannels = ss.channels;
360 wfx->wBitsPerSample = 8 * pa_sample_size_of_format(ss.format);
361 wfx->nSamplesPerSec = ss.rate;
362 wfx->nBlockAlign = pa_frame_size(&ss);
363 wfx->nAvgBytesPerSec = wfx->nSamplesPerSec * wfx->nBlockAlign;
364 if (ss.format != PA_SAMPLE_S24_32LE)
365 fmt->Samples.wValidBitsPerSample = wfx->wBitsPerSample;
366 else
367 fmt->Samples.wValidBitsPerSample = 24;
368 if (ss.format == PA_SAMPLE_FLOAT32LE)
369 fmt->SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
370 else
371 fmt->SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
373 fmt->dwChannelMask = 0;
374 for (i = 0; i < map.channels; ++i)
375 switch (map.map[i]) {
376 default: FIXME("Unhandled channel %s\n", pa_channel_position_to_string(map.map[i])); break;
377 case PA_CHANNEL_POSITION_FRONT_LEFT: fmt->dwChannelMask |= SPEAKER_FRONT_LEFT; break;
378 case PA_CHANNEL_POSITION_MONO:
379 case PA_CHANNEL_POSITION_FRONT_CENTER: fmt->dwChannelMask |= SPEAKER_FRONT_CENTER; break;
380 case PA_CHANNEL_POSITION_FRONT_RIGHT: fmt->dwChannelMask |= SPEAKER_FRONT_RIGHT; break;
381 case PA_CHANNEL_POSITION_REAR_LEFT: fmt->dwChannelMask |= SPEAKER_BACK_LEFT; break;
382 case PA_CHANNEL_POSITION_REAR_CENTER: fmt->dwChannelMask |= SPEAKER_BACK_CENTER; break;
383 case PA_CHANNEL_POSITION_REAR_RIGHT: fmt->dwChannelMask |= SPEAKER_BACK_RIGHT; break;
384 case PA_CHANNEL_POSITION_LFE: fmt->dwChannelMask |= SPEAKER_LOW_FREQUENCY; break;
385 case PA_CHANNEL_POSITION_SIDE_LEFT: fmt->dwChannelMask |= SPEAKER_SIDE_LEFT; break;
386 case PA_CHANNEL_POSITION_SIDE_RIGHT: fmt->dwChannelMask |= SPEAKER_SIDE_RIGHT; break;
387 case PA_CHANNEL_POSITION_TOP_CENTER: fmt->dwChannelMask |= SPEAKER_TOP_CENTER; break;
388 case PA_CHANNEL_POSITION_TOP_FRONT_LEFT: fmt->dwChannelMask |= SPEAKER_TOP_FRONT_LEFT; break;
389 case PA_CHANNEL_POSITION_TOP_FRONT_CENTER: fmt->dwChannelMask |= SPEAKER_TOP_FRONT_CENTER; break;
390 case PA_CHANNEL_POSITION_TOP_FRONT_RIGHT: fmt->dwChannelMask |= SPEAKER_TOP_FRONT_RIGHT; break;
391 case PA_CHANNEL_POSITION_TOP_REAR_LEFT: fmt->dwChannelMask |= SPEAKER_TOP_BACK_LEFT; break;
392 case PA_CHANNEL_POSITION_TOP_REAR_CENTER: fmt->dwChannelMask |= SPEAKER_TOP_BACK_CENTER; break;
393 case PA_CHANNEL_POSITION_TOP_REAR_RIGHT: fmt->dwChannelMask |= SPEAKER_TOP_BACK_RIGHT; break;
397 static HRESULT pulse_connect(void)
399 int len;
400 WCHAR path[PATH_MAX], *name;
401 char *str;
403 if (!pulse_thread)
405 if (!(pulse_thread = CreateThread(NULL, 0, pulse_mainloop_thread, NULL, 0, NULL)))
407 ERR("Failed to create mainloop thread.");
408 return E_FAIL;
410 SetThreadPriority(pulse_thread, THREAD_PRIORITY_TIME_CRITICAL);
411 pthread_cond_wait(&pulse_cond, &pulse_lock);
414 if (pulse_ctx && PA_CONTEXT_IS_GOOD(pa_context_get_state(pulse_ctx)))
415 return S_OK;
416 if (pulse_ctx)
417 pa_context_unref(pulse_ctx);
419 GetModuleFileNameW(NULL, path, sizeof(path)/sizeof(*path));
420 name = strrchrW(path, '\\');
421 if (!name)
422 name = path;
423 else
424 name++;
425 len = WideCharToMultiByte(CP_UNIXCP, 0, name, -1, NULL, 0, NULL, NULL);
426 str = pa_xmalloc(len);
427 WideCharToMultiByte(CP_UNIXCP, 0, name, -1, str, len, NULL, NULL);
428 TRACE("Name: %s\n", str);
429 pulse_ctx = pa_context_new(pa_mainloop_get_api(pulse_ml), str);
430 pa_xfree(str);
431 if (!pulse_ctx) {
432 ERR("Failed to create context\n");
433 return E_FAIL;
436 pa_context_set_state_callback(pulse_ctx, pulse_contextcallback, NULL);
438 TRACE("libpulse protocol version: %u. API Version %u\n", pa_context_get_protocol_version(pulse_ctx), PA_API_VERSION);
439 if (pa_context_connect(pulse_ctx, NULL, 0, NULL) < 0)
440 goto fail;
442 /* Wait for connection */
443 while (pthread_cond_wait(&pulse_cond, &pulse_lock)) {
444 pa_context_state_t state = pa_context_get_state(pulse_ctx);
446 if (state == PA_CONTEXT_FAILED || state == PA_CONTEXT_TERMINATED)
447 goto fail;
449 if (state == PA_CONTEXT_READY)
450 break;
453 TRACE("Connected to server %s with protocol version: %i.\n",
454 pa_context_get_server(pulse_ctx),
455 pa_context_get_server_protocol_version(pulse_ctx));
456 pulse_probe_settings(1, &pulse_fmt[0]);
457 pulse_probe_settings(0, &pulse_fmt[1]);
458 return S_OK;
460 fail:
461 pa_context_unref(pulse_ctx);
462 pulse_ctx = NULL;
463 return E_FAIL;
466 static void pulse_contextcallback(pa_context *c, void *userdata) {
467 switch (pa_context_get_state(c)) {
468 default:
469 FIXME("Unhandled state: %i\n", pa_context_get_state(c));
470 case PA_CONTEXT_CONNECTING:
471 case PA_CONTEXT_UNCONNECTED:
472 case PA_CONTEXT_AUTHORIZING:
473 case PA_CONTEXT_SETTING_NAME:
474 case PA_CONTEXT_TERMINATED:
475 TRACE("State change to %i\n", pa_context_get_state(c));
476 return;
478 case PA_CONTEXT_READY:
479 TRACE("Ready\n");
480 break;
482 case PA_CONTEXT_FAILED:
483 ERR("Context failed: %s\n", pa_strerror(pa_context_errno(c)));
484 break;
486 pthread_cond_signal(&pulse_cond);
489 static HRESULT pulse_stream_valid(ACImpl *This) {
490 if (!This->stream)
491 return AUDCLNT_E_NOT_INITIALIZED;
492 if (!This->stream || pa_stream_get_state(This->stream) != PA_STREAM_READY)
493 return AUDCLNT_E_DEVICE_INVALIDATED;
494 return S_OK;
497 static void dump_attr(const pa_buffer_attr *attr) {
498 TRACE("maxlength: %u\n", attr->maxlength);
499 TRACE("minreq: %u\n", attr->minreq);
500 TRACE("fragsize: %u\n", attr->fragsize);
501 TRACE("tlength: %u\n", attr->tlength);
502 TRACE("prebuf: %u\n", attr->prebuf);
505 static void pulse_op_cb(pa_stream *s, int success, void *user) {
506 TRACE("Success: %i\n", success);
507 *(int*)user = success;
508 pthread_cond_signal(&pulse_cond);
511 static void pulse_ctx_op_cb(pa_context *c, int success, void *user) {
512 TRACE("Success: %i\n", success);
513 *(int*)user = success;
514 pthread_cond_signal(&pulse_cond);
517 static void pulse_attr_update(pa_stream *s, void *user) {
518 const pa_buffer_attr *attr = pa_stream_get_buffer_attr(s);
519 TRACE("New attributes or device moved:\n");
520 dump_attr(attr);
523 static void pulse_wr_callback(pa_stream *s, size_t bytes, void *userdata)
525 ACImpl *This = userdata;
526 pa_usec_t time;
527 UINT32 oldpad = This->pad;
529 if (bytes < This->bufsize_bytes)
530 This->pad = This->bufsize_bytes - bytes;
531 else
532 This->pad = 0;
534 assert(oldpad >= This->pad);
536 if (0 && This->pad && pa_stream_get_time(This->stream, &time) >= 0)
537 This->clock_pulse = time;
538 else
539 This->clock_pulse = PA_USEC_INVALID;
541 This->clock_written += oldpad - This->pad;
542 TRACE("New pad: %u (-%u)\n", This->pad / pa_frame_size(&This->ss), (oldpad - This->pad) / pa_frame_size(&This->ss));
544 if (This->event)
545 SetEvent(This->event);
548 static void pulse_underflow_callback(pa_stream *s, void *userdata)
550 ACImpl *This = userdata;
551 This->clock_pulse = PA_USEC_INVALID;
552 WARN("Underflow\n");
555 /* Latency is periodically updated even when nothing is played,
556 * because of PA_STREAM_AUTO_TIMING_UPDATE so use it as timer
558 * Perfect for passing all tests :)
560 static void pulse_latency_callback(pa_stream *s, void *userdata)
562 ACImpl *This = userdata;
563 if (!This->pad && This->event)
564 SetEvent(This->event);
567 static void pulse_started_callback(pa_stream *s, void *userdata)
569 ACImpl *This = userdata;
570 pa_usec_t time;
572 TRACE("(Re)started playing\n");
573 assert(This->clock_pulse == PA_USEC_INVALID);
574 if (0 && pa_stream_get_time(This->stream, &time) >= 0)
575 This->clock_pulse = time;
576 if (This->event)
577 SetEvent(This->event);
580 static void pulse_rd_loop(ACImpl *This, size_t bytes)
582 while (bytes >= This->capture_period) {
583 ACPacket *p, *next;
584 LARGE_INTEGER stamp, freq;
585 BYTE *dst, *src;
586 UINT32 src_len, copy, rem = This->capture_period;
587 if (!(p = (ACPacket*)list_head(&This->packet_free_head))) {
588 p = (ACPacket*)list_head(&This->packet_filled_head);
589 if (!p->discont) {
590 next = (ACPacket*)p->entry.next;
591 next->discont = 1;
592 } else
593 p = (ACPacket*)list_tail(&This->packet_filled_head);
594 assert(This->pad == This->bufsize_bytes);
595 } else {
596 assert(This->pad < This->bufsize_bytes);
597 This->pad += This->capture_period;
598 assert(This->pad <= This->bufsize_bytes);
600 QueryPerformanceCounter(&stamp);
601 QueryPerformanceFrequency(&freq);
602 p->qpcpos = (stamp.QuadPart * (INT64)10000000) / freq.QuadPart;
603 p->discont = 0;
604 list_remove(&p->entry);
605 list_add_tail(&This->packet_filled_head, &p->entry);
607 dst = p->data;
608 while (rem) {
609 pa_stream_peek(This->stream, (const void**)&src, &src_len);
610 assert(src_len);
611 assert(This->peek_ofs < src_len);
612 src += This->peek_ofs;
613 src_len -= This->peek_ofs;
614 assert(src_len <= bytes);
616 copy = rem;
617 if (copy > src_len)
618 copy = src_len;
619 memcpy(dst, src, rem);
620 src += copy;
621 src_len -= copy;
622 dst += copy;
623 rem -= copy;
625 if (!src_len) {
626 This->peek_ofs = 0;
627 pa_stream_drop(This->stream);
628 } else
629 This->peek_ofs += copy;
631 bytes -= This->capture_period;
635 static void pulse_rd_drop(ACImpl *This, size_t bytes)
637 while (bytes >= This->capture_period) {
638 UINT32 src_len, copy, rem = This->capture_period;
639 while (rem) {
640 const void *src;
641 pa_stream_peek(This->stream, &src, &src_len);
642 assert(src_len);
643 assert(This->peek_ofs < src_len);
644 src_len -= This->peek_ofs;
645 assert(src_len <= bytes);
647 copy = rem;
648 if (copy > src_len)
649 copy = src_len;
651 src_len -= copy;
652 rem -= copy;
654 if (!src_len) {
655 This->peek_ofs = 0;
656 pa_stream_drop(This->stream);
657 } else
658 This->peek_ofs += copy;
659 bytes -= copy;
664 static void pulse_rd_callback(pa_stream *s, size_t bytes, void *userdata)
666 ACImpl *This = userdata;
668 TRACE("Readable total: %u, fragsize: %u\n", bytes, pa_stream_get_buffer_attr(s)->fragsize);
669 assert(bytes >= This->peek_ofs);
670 bytes -= This->peek_ofs;
671 if (bytes < This->capture_period)
672 return;
674 if (This->started)
675 pulse_rd_loop(This, bytes);
676 else
677 pulse_rd_drop(This, bytes);
679 if (This->event)
680 SetEvent(This->event);
683 static void pulse_stream_state(pa_stream *s, void *user)
685 pa_stream_state_t state = pa_stream_get_state(s);
686 TRACE("Stream state changed to %i\n", state);
687 pthread_cond_signal(&pulse_cond);
690 static HRESULT pulse_stream_connect(ACImpl *This, UINT32 period_bytes) {
691 int ret;
692 char buffer[64];
693 static LONG number;
694 pa_buffer_attr attr;
695 if (This->stream) {
696 pa_stream_disconnect(This->stream);
697 while (pa_stream_get_state(This->stream) == PA_STREAM_READY)
698 pthread_cond_wait(&pulse_cond, &pulse_lock);
699 pa_stream_unref(This->stream);
701 ret = InterlockedIncrement(&number);
702 sprintf(buffer, "audio stream #%i", ret);
703 This->stream = pa_stream_new(pulse_ctx, buffer, &This->ss, &This->map);
704 pa_stream_set_state_callback(This->stream, pulse_stream_state, This);
705 pa_stream_set_buffer_attr_callback(This->stream, pulse_attr_update, This);
706 pa_stream_set_moved_callback(This->stream, pulse_attr_update, This);
708 /* Pulseaudio will fill in correct values */
709 attr.minreq = attr.fragsize = period_bytes;
710 attr.maxlength = attr.tlength = This->bufsize_bytes;
711 attr.prebuf = pa_frame_size(&This->ss);
712 dump_attr(&attr);
713 if (This->dataflow == eRender)
714 ret = pa_stream_connect_playback(This->stream, NULL, &attr,
715 PA_STREAM_START_CORKED|PA_STREAM_START_UNMUTED|PA_STREAM_AUTO_TIMING_UPDATE|PA_STREAM_INTERPOLATE_TIMING|PA_STREAM_EARLY_REQUESTS, NULL, NULL);
716 else
717 ret = pa_stream_connect_record(This->stream, NULL, &attr,
718 PA_STREAM_START_CORKED|PA_STREAM_START_UNMUTED|PA_STREAM_AUTO_TIMING_UPDATE|PA_STREAM_INTERPOLATE_TIMING|PA_STREAM_EARLY_REQUESTS);
719 if (ret < 0) {
720 WARN("Returns %i\n", ret);
721 return AUDCLNT_E_ENDPOINT_CREATE_FAILED;
723 while (pa_stream_get_state(This->stream) == PA_STREAM_CREATING)
724 pthread_cond_wait(&pulse_cond, &pulse_lock);
725 if (pa_stream_get_state(This->stream) != PA_STREAM_READY)
726 return AUDCLNT_E_ENDPOINT_CREATE_FAILED;
728 if (This->dataflow == eRender) {
729 pa_stream_set_write_callback(This->stream, pulse_wr_callback, This);
730 pa_stream_set_underflow_callback(This->stream, pulse_underflow_callback, This);
731 pa_stream_set_started_callback(This->stream, pulse_started_callback, This);
732 } else
733 pa_stream_set_read_callback(This->stream, pulse_rd_callback, This);
734 return S_OK;
737 HRESULT WINAPI AUDDRV_GetEndpointIDs(EDataFlow flow, const WCHAR ***ids, GUID **keys,
738 UINT *num, UINT *def_index)
740 HRESULT hr = S_OK;
741 TRACE("%d %p %p %p\n", flow, ids, num, def_index);
743 pthread_mutex_lock(&pulse_lock);
744 hr = pulse_connect();
745 pthread_mutex_unlock(&pulse_lock);
746 if (FAILED(hr))
747 return hr;
748 *num = 1;
749 *def_index = 0;
751 *ids = HeapAlloc(GetProcessHeap(), 0, sizeof(**ids));
752 if (!*ids)
753 return E_OUTOFMEMORY;
754 (*ids)[0] = defaultW;
756 *keys = HeapAlloc(GetProcessHeap(), 0, sizeof(**keys));
757 if (!*keys) {
758 HeapFree(GetProcessHeap(), 0, *ids);
759 *ids = NULL;
760 return E_OUTOFMEMORY;
762 if (flow == eRender)
763 (*keys)[0] = pulse_render_guid;
764 else
765 (*keys)[0] = pulse_capture_guid;
767 return S_OK;
770 int WINAPI AUDDRV_GetPriority(void)
772 HRESULT hr;
773 if (getenv("WINENOPULSE")) {
774 FIXME_(winediag)("winepulse has been temporarily disabled through the environment\n");
775 return 0;
777 pthread_mutex_lock(&pulse_lock);
778 hr = pulse_connect();
779 pthread_mutex_unlock(&pulse_lock);
780 return SUCCEEDED(hr) ? 3 : 0;
783 HRESULT WINAPI AUDDRV_GetAudioEndpoint(GUID *guid, IMMDevice *dev, IAudioClient **out)
785 HRESULT hr;
786 ACImpl *This;
787 int i;
788 EDataFlow dataflow;
790 /* Give one visible warning per session
791 * Sadly wine has chosen not to accept the winepulse patch, so support ourselves
793 if (!warn_once && (warn_once = CreateEventA(0, 0, 0, "__winepulse_warn_event")) && GetLastError() != ERROR_ALREADY_EXISTS) {
794 FIXME_(winediag)("Winepulse is not officially supported by the wine project\n");
795 FIXME_(winediag)("For sound related feedback and support, please visit http://ubuntuforums.org/showthread.php?t=1960599\n");
796 } else {
797 WARN_(winediag)("Winepulse is not officially supported by the wine project\n");
798 WARN_(winediag)("For sound related feedback and support, please visit http://ubuntuforums.org/showthread.php?t=1960599\n");
801 TRACE("%s %p %p\n", debugstr_guid(guid), dev, out);
802 if (IsEqualGUID(guid, &pulse_render_guid))
803 dataflow = eRender;
804 else if (IsEqualGUID(guid, &pulse_capture_guid))
805 dataflow = eCapture;
806 else
807 return E_UNEXPECTED;
809 *out = NULL;
810 pthread_mutex_lock(&pulse_lock);
811 hr = pulse_connect();
812 pthread_mutex_unlock(&pulse_lock);
813 if (FAILED(hr))
814 return hr;
816 This = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*This));
817 if (!This)
818 return E_OUTOFMEMORY;
820 This->IAudioClient_iface.lpVtbl = &AudioClient_Vtbl;
821 This->IAudioRenderClient_iface.lpVtbl = &AudioRenderClient_Vtbl;
822 This->IAudioCaptureClient_iface.lpVtbl = &AudioCaptureClient_Vtbl;
823 This->IAudioClock_iface.lpVtbl = &AudioClock_Vtbl;
824 This->IAudioClock2_iface.lpVtbl = &AudioClock2_Vtbl;
825 This->IAudioStreamVolume_iface.lpVtbl = &AudioStreamVolume_Vtbl;
826 This->dataflow = dataflow;
827 This->parent = dev;
828 This->clock_pulse = PA_USEC_INVALID;
829 for (i = 0; i < PA_CHANNELS_MAX; ++i)
830 This->vol[i] = 1.f;
831 IMMDevice_AddRef(This->parent);
833 *out = &This->IAudioClient_iface;
834 IAudioClient_AddRef(&This->IAudioClient_iface);
836 return S_OK;
839 static HRESULT WINAPI AudioClient_QueryInterface(IAudioClient *iface,
840 REFIID riid, void **ppv)
842 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
844 if (!ppv)
845 return E_POINTER;
846 *ppv = NULL;
847 if (IsEqualIID(riid, &IID_IUnknown) || IsEqualIID(riid, &IID_IAudioClient))
848 *ppv = iface;
849 if (*ppv) {
850 IUnknown_AddRef((IUnknown*)*ppv);
851 return S_OK;
853 WARN("Unknown interface %s\n", debugstr_guid(riid));
854 return E_NOINTERFACE;
857 static ULONG WINAPI AudioClient_AddRef(IAudioClient *iface)
859 ACImpl *This = impl_from_IAudioClient(iface);
860 ULONG ref;
861 ref = InterlockedIncrement(&This->ref);
862 TRACE("(%p) Refcount now %u\n", This, ref);
863 return ref;
866 static ULONG WINAPI AudioClient_Release(IAudioClient *iface)
868 ACImpl *This = impl_from_IAudioClient(iface);
869 ULONG ref;
870 ref = InterlockedDecrement(&This->ref);
871 TRACE("(%p) Refcount now %u\n", This, ref);
872 if (!ref) {
873 if (This->stream) {
874 pthread_mutex_lock(&pulse_lock);
875 if (PA_STREAM_IS_GOOD(pa_stream_get_state(This->stream))) {
876 pa_stream_disconnect(This->stream);
877 while (PA_STREAM_IS_GOOD(pa_stream_get_state(This->stream)))
878 pthread_cond_wait(&pulse_cond, &pulse_lock);
880 pa_stream_unref(This->stream);
881 This->stream = NULL;
882 list_remove(&This->entry);
883 pthread_mutex_unlock(&pulse_lock);
885 IMMDevice_Release(This->parent);
886 HeapFree(GetProcessHeap(), 0, This->tmp_buffer);
887 HeapFree(GetProcessHeap(), 0, This);
889 return ref;
892 static void dump_fmt(const WAVEFORMATEX *fmt)
894 TRACE("wFormatTag: 0x%x (", fmt->wFormatTag);
895 switch(fmt->wFormatTag) {
896 case WAVE_FORMAT_PCM:
897 TRACE("WAVE_FORMAT_PCM");
898 break;
899 case WAVE_FORMAT_IEEE_FLOAT:
900 TRACE("WAVE_FORMAT_IEEE_FLOAT");
901 break;
902 case WAVE_FORMAT_EXTENSIBLE:
903 TRACE("WAVE_FORMAT_EXTENSIBLE");
904 break;
905 default:
906 TRACE("Unknown");
907 break;
909 TRACE(")\n");
911 TRACE("nChannels: %u\n", fmt->nChannels);
912 TRACE("nSamplesPerSec: %u\n", fmt->nSamplesPerSec);
913 TRACE("nAvgBytesPerSec: %u\n", fmt->nAvgBytesPerSec);
914 TRACE("nBlockAlign: %u\n", fmt->nBlockAlign);
915 TRACE("wBitsPerSample: %u\n", fmt->wBitsPerSample);
916 TRACE("cbSize: %u\n", fmt->cbSize);
918 if (fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
919 WAVEFORMATEXTENSIBLE *fmtex = (void*)fmt;
920 TRACE("dwChannelMask: %08x\n", fmtex->dwChannelMask);
921 TRACE("Samples: %04x\n", fmtex->Samples.wReserved);
922 TRACE("SubFormat: %s\n", wine_dbgstr_guid(&fmtex->SubFormat));
926 static WAVEFORMATEX *clone_format(const WAVEFORMATEX *fmt)
928 WAVEFORMATEX *ret;
929 size_t size;
931 if (fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE)
932 size = sizeof(WAVEFORMATEXTENSIBLE);
933 else
934 size = sizeof(WAVEFORMATEX);
936 ret = CoTaskMemAlloc(size);
937 if (!ret)
938 return NULL;
940 memcpy(ret, fmt, size);
942 ret->cbSize = size - sizeof(WAVEFORMATEX);
944 return ret;
947 static DWORD get_channel_mask(unsigned int channels)
949 switch(channels) {
950 case 0:
951 return 0;
952 case 1:
953 return SPEAKER_FRONT_CENTER;
954 case 2:
955 return SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT;
956 case 3:
957 return SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT |
958 SPEAKER_LOW_FREQUENCY;
959 case 4:
960 return SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT |
961 SPEAKER_BACK_RIGHT;
962 case 5:
963 return SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT |
964 SPEAKER_BACK_RIGHT | SPEAKER_LOW_FREQUENCY;
965 case 6:
966 return SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT |
967 SPEAKER_BACK_RIGHT | SPEAKER_LOW_FREQUENCY | SPEAKER_FRONT_CENTER;
968 case 7:
969 return SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT |
970 SPEAKER_BACK_RIGHT | SPEAKER_LOW_FREQUENCY | SPEAKER_FRONT_CENTER |
971 SPEAKER_BACK_CENTER;
972 case 8:
973 return SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT |
974 SPEAKER_BACK_RIGHT | SPEAKER_LOW_FREQUENCY | SPEAKER_FRONT_CENTER |
975 SPEAKER_SIDE_LEFT | SPEAKER_SIDE_RIGHT;
977 FIXME("Unknown speaker configuration: %u\n", channels);
978 return 0;
981 static void session_init_vols(AudioSession *session, UINT channels)
983 if (session->channel_count < channels) {
984 UINT i;
986 if (session->channel_vols)
987 session->channel_vols = HeapReAlloc(GetProcessHeap(), 0,
988 session->channel_vols, sizeof(float) * channels);
989 else
990 session->channel_vols = HeapAlloc(GetProcessHeap(), 0,
991 sizeof(float) * channels);
992 if (!session->channel_vols)
993 return;
995 for(i = session->channel_count; i < channels; ++i)
996 session->channel_vols[i] = 1.f;
998 session->channel_count = channels;
1002 static AudioSession *create_session(const GUID *guid, IMMDevice *device,
1003 UINT num_channels)
1005 AudioSession *ret;
1007 ret = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(AudioSession));
1008 if (!ret)
1009 return NULL;
1011 memcpy(&ret->guid, guid, sizeof(GUID));
1013 ret->device = device;
1015 list_init(&ret->clients);
1017 list_add_head(&g_sessions, &ret->entry);
1019 session_init_vols(ret, num_channels);
1021 ret->master_vol = 1.f;
1023 return ret;
1026 /* if channels == 0, then this will return or create a session with
1027 * matching dataflow and GUID. otherwise, channels must also match */
1028 static HRESULT get_audio_session(const GUID *sessionguid,
1029 IMMDevice *device, UINT channels, AudioSession **out)
1031 AudioSession *session;
1033 if (!sessionguid || IsEqualGUID(sessionguid, &GUID_NULL)) {
1034 *out = create_session(&GUID_NULL, device, channels);
1035 if (!*out)
1036 return E_OUTOFMEMORY;
1038 return S_OK;
1041 *out = NULL;
1042 LIST_FOR_EACH_ENTRY(session, &g_sessions, AudioSession, entry) {
1043 if (session->device == device &&
1044 IsEqualGUID(sessionguid, &session->guid)) {
1045 session_init_vols(session, channels);
1046 *out = session;
1047 break;
1051 if (!*out) {
1052 *out = create_session(sessionguid, device, channels);
1053 if (!*out)
1054 return E_OUTOFMEMORY;
1057 return S_OK;
1060 static HRESULT pulse_spec_from_waveformat(ACImpl *This, const WAVEFORMATEX *fmt)
1062 pa_channel_map_init(&This->map);
1063 This->ss.rate = fmt->nSamplesPerSec;
1064 This->ss.format = PA_SAMPLE_INVALID;
1065 switch(fmt->wFormatTag) {
1066 case WAVE_FORMAT_IEEE_FLOAT:
1067 if (!fmt->nChannels || fmt->nChannels > 2 || fmt->wBitsPerSample != 32)
1068 break;
1069 This->ss.format = PA_SAMPLE_FLOAT32LE;
1070 pa_channel_map_init_auto(&This->map, fmt->nChannels, PA_CHANNEL_MAP_ALSA);
1071 break;
1072 case WAVE_FORMAT_PCM:
1073 if (!fmt->nChannels || fmt->nChannels > 2)
1074 break;
1075 if (fmt->wBitsPerSample == 8)
1076 This->ss.format = PA_SAMPLE_U8;
1077 else if (fmt->wBitsPerSample == 16)
1078 This->ss.format = PA_SAMPLE_S16LE;
1079 else
1080 return AUDCLNT_E_UNSUPPORTED_FORMAT;
1081 pa_channel_map_init_auto(&This->map, fmt->nChannels, PA_CHANNEL_MAP_ALSA);
1082 break;
1083 case WAVE_FORMAT_EXTENSIBLE: {
1084 WAVEFORMATEXTENSIBLE *wfe = (WAVEFORMATEXTENSIBLE*)fmt;
1085 DWORD mask = wfe->dwChannelMask;
1086 DWORD i = 0, j;
1087 if (fmt->cbSize != (sizeof(*wfe) - sizeof(*fmt)) && fmt->cbSize != sizeof(*wfe))
1088 break;
1089 if (IsEqualGUID(&wfe->SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT) &&
1090 (!wfe->Samples.wValidBitsPerSample || wfe->Samples.wValidBitsPerSample == 32) &&
1091 fmt->wBitsPerSample == 32)
1092 This->ss.format = PA_SAMPLE_FLOAT32LE;
1093 else if (IsEqualGUID(&wfe->SubFormat, &KSDATAFORMAT_SUBTYPE_PCM)) {
1094 DWORD valid = wfe->Samples.wValidBitsPerSample;
1095 if (!valid)
1096 valid = fmt->wBitsPerSample;
1097 if (!valid || valid > fmt->wBitsPerSample)
1098 break;
1099 switch (fmt->wBitsPerSample) {
1100 case 8:
1101 if (valid == 8)
1102 This->ss.format = PA_SAMPLE_U8;
1103 break;
1104 case 16:
1105 if (valid == 16)
1106 This->ss.format = PA_SAMPLE_S16LE;
1107 break;
1108 case 24:
1109 if (valid == 24)
1110 This->ss.format = PA_SAMPLE_S24LE;
1111 break;
1112 case 32:
1113 if (valid == 24)
1114 This->ss.format = PA_SAMPLE_S24_32LE;
1115 else if (valid == 32)
1116 This->ss.format = PA_SAMPLE_S32LE;
1117 break;
1118 default:
1119 return AUDCLNT_E_UNSUPPORTED_FORMAT;
1122 This->map.channels = fmt->nChannels;
1123 if (!mask || mask == SPEAKER_ALL)
1124 mask = get_channel_mask(fmt->nChannels);
1125 else if (mask == ~0U && fmt->nChannels == 1)
1126 mask = SPEAKER_FRONT_CENTER;
1127 for (j = 0; j < sizeof(pulse_pos_from_wfx)/sizeof(*pulse_pos_from_wfx) && i < fmt->nChannels; ++j) {
1128 if (mask & (1 << j))
1129 This->map.map[i++] = pulse_pos_from_wfx[j];
1132 /* Special case for mono since pulse appears to map it differently */
1133 if (mask == SPEAKER_FRONT_CENTER)
1134 This->map.map[0] = PA_CHANNEL_POSITION_MONO;
1136 if (i < fmt->nChannels || (mask & SPEAKER_RESERVED)) {
1137 This->map.channels = 0;
1138 ERR("Invalid channel mask: %i/%i and %x(%x)\n", i, fmt->nChannels, mask, wfe->dwChannelMask);
1139 break;
1141 break;
1143 case WAVE_FORMAT_ALAW:
1144 case WAVE_FORMAT_MULAW:
1145 if (fmt->wBitsPerSample != 8) {
1146 FIXME("Unsupported bpp %u for LAW\n", fmt->wBitsPerSample);
1147 return AUDCLNT_E_UNSUPPORTED_FORMAT;
1149 if (fmt->nChannels != 1 && fmt->nChannels != 2) {
1150 FIXME("Unsupported channels %u for LAW\n", fmt->nChannels);
1151 return AUDCLNT_E_UNSUPPORTED_FORMAT;
1153 This->ss.format = fmt->wFormatTag == WAVE_FORMAT_MULAW ? PA_SAMPLE_ULAW : PA_SAMPLE_ALAW;
1154 pa_channel_map_init_auto(&This->map, fmt->nChannels, PA_CHANNEL_MAP_ALSA);
1155 break;
1156 default:
1157 WARN("Unhandled tag %x\n", fmt->wFormatTag);
1158 return AUDCLNT_E_UNSUPPORTED_FORMAT;
1160 This->ss.channels = This->map.channels;
1161 if (!pa_channel_map_valid(&This->map) || This->ss.format == PA_SAMPLE_INVALID) {
1162 ERR("Invalid format! Channel spec valid: %i, format: %i\n", pa_channel_map_valid(&This->map), This->ss.format);
1163 dump_fmt(fmt);
1164 return AUDCLNT_E_UNSUPPORTED_FORMAT;
1166 return S_OK;
1169 static HRESULT WINAPI AudioClient_Initialize(IAudioClient *iface,
1170 AUDCLNT_SHAREMODE mode, DWORD flags, REFERENCE_TIME duration,
1171 REFERENCE_TIME period, const WAVEFORMATEX *fmt,
1172 const GUID *sessionguid)
1174 ACImpl *This = impl_from_IAudioClient(iface);
1175 HRESULT hr = S_OK;
1176 UINT period_bytes;
1178 TRACE("(%p)->(%x, %x, %s, %s, %p, %s)\n", This, mode, flags,
1179 wine_dbgstr_longlong(duration), wine_dbgstr_longlong(period), fmt, debugstr_guid(sessionguid));
1181 if (!fmt)
1182 return E_POINTER;
1184 if (mode != AUDCLNT_SHAREMODE_SHARED && mode != AUDCLNT_SHAREMODE_EXCLUSIVE)
1185 return AUDCLNT_E_NOT_INITIALIZED;
1186 if (mode == AUDCLNT_SHAREMODE_EXCLUSIVE)
1187 return AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED;
1189 if (flags & ~(AUDCLNT_STREAMFLAGS_CROSSPROCESS |
1190 AUDCLNT_STREAMFLAGS_LOOPBACK |
1191 AUDCLNT_STREAMFLAGS_EVENTCALLBACK |
1192 AUDCLNT_STREAMFLAGS_NOPERSIST |
1193 AUDCLNT_STREAMFLAGS_RATEADJUST |
1194 AUDCLNT_SESSIONFLAGS_EXPIREWHENUNOWNED |
1195 AUDCLNT_SESSIONFLAGS_DISPLAY_HIDE |
1196 AUDCLNT_SESSIONFLAGS_DISPLAY_HIDEWHENEXPIRED)) {
1197 TRACE("Unknown flags: %08x\n", flags);
1198 return E_INVALIDARG;
1201 pthread_mutex_lock(&pulse_lock);
1202 if (This->stream) {
1203 pthread_mutex_unlock(&pulse_lock);
1204 return AUDCLNT_E_ALREADY_INITIALIZED;
1207 hr = pulse_spec_from_waveformat(This, fmt);
1208 if (FAILED(hr))
1209 goto exit;
1211 if (mode == AUDCLNT_SHAREMODE_SHARED) {
1212 period = pulse_def_period[This->dataflow == eCapture];
1213 if (duration < 2 * period)
1214 duration = 2 * period;
1216 period_bytes = pa_frame_size(&This->ss) * MulDiv(period, This->ss.rate, 10000000);
1218 if (duration < 20000000)
1219 This->bufsize_frames = ceil((duration / 10000000.) * fmt->nSamplesPerSec);
1220 else
1221 This->bufsize_frames = 2 * fmt->nSamplesPerSec;
1222 This->bufsize_bytes = This->bufsize_frames * pa_frame_size(&This->ss);
1224 This->share = mode;
1225 This->flags = flags;
1226 hr = pulse_stream_connect(This, period_bytes);
1227 if (SUCCEEDED(hr)) {
1228 UINT32 unalign;
1229 const pa_buffer_attr *attr = pa_stream_get_buffer_attr(This->stream);
1230 /* Update frames according to new size */
1231 dump_attr(attr);
1232 if (This->dataflow == eRender)
1233 This->bufsize_bytes = attr->tlength;
1234 else {
1235 This->capture_period = period_bytes = attr->fragsize;
1236 if ((unalign = This->bufsize_bytes % period_bytes))
1237 This->bufsize_bytes += period_bytes - unalign;
1239 This->bufsize_frames = This->bufsize_bytes / pa_frame_size(&This->ss);
1241 if (SUCCEEDED(hr)) {
1242 UINT32 i, capture_packets = This->capture_period ? This->bufsize_bytes / This->capture_period : 0;
1243 This->tmp_buffer = HeapAlloc(GetProcessHeap(), 0, This->bufsize_bytes + capture_packets * sizeof(ACPacket));
1244 if (!This->tmp_buffer)
1245 hr = E_OUTOFMEMORY;
1246 else {
1247 ACPacket *cur_packet = (ACPacket*)((char*)This->tmp_buffer + This->bufsize_bytes);
1248 BYTE *data = This->tmp_buffer;
1249 memset(This->tmp_buffer, This->ss.format == PA_SAMPLE_U8 ? 0x80 : 0, This->bufsize_bytes);
1250 list_init(&This->packet_free_head);
1251 list_init(&This->packet_filled_head);
1252 for (i = 0; i < capture_packets; ++i, ++cur_packet) {
1253 list_add_tail(&This->packet_free_head, &cur_packet->entry);
1254 cur_packet->data = data;
1255 data += This->capture_period;
1257 assert(!This->capture_period || This->bufsize_bytes == This->capture_period * capture_packets);
1258 assert(!capture_packets || data - This->bufsize_bytes == This->tmp_buffer);
1261 if (SUCCEEDED(hr))
1262 hr = get_audio_session(sessionguid, This->parent, fmt->nChannels, &This->session);
1263 if (SUCCEEDED(hr))
1264 list_add_tail(&This->session->clients, &This->entry);
1266 exit:
1267 if (FAILED(hr)) {
1268 HeapFree(GetProcessHeap(), 0, This->tmp_buffer);
1269 This->tmp_buffer = NULL;
1270 if (This->stream) {
1271 pa_stream_disconnect(This->stream);
1272 pa_stream_unref(This->stream);
1273 This->stream = NULL;
1276 pthread_mutex_unlock(&pulse_lock);
1277 return hr;
1280 static HRESULT WINAPI AudioClient_GetBufferSize(IAudioClient *iface,
1281 UINT32 *out)
1283 ACImpl *This = impl_from_IAudioClient(iface);
1284 HRESULT hr;
1286 TRACE("(%p)->(%p)\n", This, out);
1288 if (!out)
1289 return E_POINTER;
1291 pthread_mutex_lock(&pulse_lock);
1292 hr = pulse_stream_valid(This);
1293 if (SUCCEEDED(hr))
1294 *out = This->bufsize_frames;
1295 pthread_mutex_unlock(&pulse_lock);
1297 return hr;
1300 static HRESULT WINAPI AudioClient_GetStreamLatency(IAudioClient *iface,
1301 REFERENCE_TIME *latency)
1303 ACImpl *This = impl_from_IAudioClient(iface);
1304 const pa_buffer_attr *attr;
1305 REFERENCE_TIME lat;
1306 HRESULT hr;
1308 TRACE("(%p)->(%p)\n", This, latency);
1310 if (!latency)
1311 return E_POINTER;
1313 pthread_mutex_lock(&pulse_lock);
1314 hr = pulse_stream_valid(This);
1315 if (FAILED(hr)) {
1316 pthread_mutex_unlock(&pulse_lock);
1317 return hr;
1319 attr = pa_stream_get_buffer_attr(This->stream);
1320 if (This->dataflow == eRender)
1321 lat = attr->minreq / pa_frame_size(&This->ss);
1322 else
1323 lat = attr->fragsize / pa_frame_size(&This->ss);
1324 *latency = 10000000;
1325 *latency *= lat;
1326 *latency /= This->ss.rate;
1327 pthread_mutex_unlock(&pulse_lock);
1328 TRACE("Latency: %u ms\n", (DWORD)(*latency / 10000));
1329 return S_OK;
1332 static void ACImpl_GetRenderPad(ACImpl *This, UINT32 *out)
1334 *out = This->pad / pa_frame_size(&This->ss);
1337 static void ACImpl_GetCapturePad(ACImpl *This, UINT32 *out)
1339 ACPacket *packet = This->locked_ptr;
1340 if (!packet && !list_empty(&This->packet_filled_head)) {
1341 packet = (ACPacket*)list_head(&This->packet_filled_head);
1342 This->locked_ptr = packet;
1343 list_remove(&packet->entry);
1345 if (out)
1346 *out = This->pad / pa_frame_size(&This->ss);
1349 static HRESULT WINAPI AudioClient_GetCurrentPadding(IAudioClient *iface,
1350 UINT32 *out)
1352 ACImpl *This = impl_from_IAudioClient(iface);
1353 HRESULT hr;
1355 TRACE("(%p)->(%p)\n", This, out);
1357 if (!out)
1358 return E_POINTER;
1360 pthread_mutex_lock(&pulse_lock);
1361 hr = pulse_stream_valid(This);
1362 if (FAILED(hr)) {
1363 pthread_mutex_unlock(&pulse_lock);
1364 return hr;
1367 if (This->dataflow == eRender)
1368 ACImpl_GetRenderPad(This, out);
1369 else
1370 ACImpl_GetCapturePad(This, out);
1371 pthread_mutex_unlock(&pulse_lock);
1373 TRACE("%p Pad: %u ms (%u)\n", This, MulDiv(*out, 1000, This->ss.rate), *out);
1374 return S_OK;
1377 static HRESULT WINAPI AudioClient_IsFormatSupported(IAudioClient *iface,
1378 AUDCLNT_SHAREMODE mode, const WAVEFORMATEX *fmt,
1379 WAVEFORMATEX **out)
1381 ACImpl *This = impl_from_IAudioClient(iface);
1382 HRESULT hr = S_OK;
1383 WAVEFORMATEX *closest = NULL;
1385 TRACE("(%p)->(%x, %p, %p)\n", This, mode, fmt, out);
1387 if (!fmt || (mode == AUDCLNT_SHAREMODE_SHARED && !out))
1388 return E_POINTER;
1390 if (out)
1391 *out = NULL;
1392 if (mode != AUDCLNT_SHAREMODE_SHARED && mode != AUDCLNT_SHAREMODE_EXCLUSIVE)
1393 return E_INVALIDARG;
1394 if (mode == AUDCLNT_SHAREMODE_EXCLUSIVE)
1395 return This->dataflow == eCapture ? AUDCLNT_E_UNSUPPORTED_FORMAT : AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED;
1396 switch (fmt->wFormatTag) {
1397 case WAVE_FORMAT_EXTENSIBLE:
1398 if (fmt->cbSize < sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX))
1399 return E_INVALIDARG;
1400 dump_fmt(fmt);
1401 break;
1402 case WAVE_FORMAT_ALAW:
1403 case WAVE_FORMAT_MULAW:
1404 case WAVE_FORMAT_IEEE_FLOAT:
1405 case WAVE_FORMAT_PCM:
1406 dump_fmt(fmt);
1407 break;
1408 default:
1409 dump_fmt(fmt);
1410 return AUDCLNT_E_UNSUPPORTED_FORMAT;
1412 if (fmt->nChannels == 0)
1413 return AUDCLNT_E_UNSUPPORTED_FORMAT;
1414 closest = clone_format(fmt);
1415 if (!closest) {
1416 if (out)
1417 *out = NULL;
1418 return E_OUTOFMEMORY;
1421 if (fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
1422 UINT32 mask = 0, i, channels = 0;
1423 WAVEFORMATEXTENSIBLE *ext = (WAVEFORMATEXTENSIBLE*)closest;
1425 if ((fmt->nChannels > 1 && ext->dwChannelMask == SPEAKER_ALL) ||
1426 (fmt->nChannels == 1 && ext->dwChannelMask == ~0U)) {
1427 mask = ext->dwChannelMask;
1428 channels = fmt->nChannels;
1429 } else if (ext->dwChannelMask) {
1430 for (i = 1; !(i & SPEAKER_RESERVED); i <<= 1) {
1431 if (i & ext->dwChannelMask) {
1432 mask |= i;
1433 channels++;
1436 if (channels < fmt->nChannels)
1437 mask = get_channel_mask(fmt->nChannels);
1438 } else
1439 mask = ext->dwChannelMask;
1440 if (ext->dwChannelMask != mask) {
1441 ext->dwChannelMask = mask;
1442 hr = S_FALSE;
1446 if (hr == S_OK || !out) {
1447 CoTaskMemFree(closest);
1448 if (out)
1449 *out = NULL;
1450 } else if (closest) {
1451 closest->nBlockAlign =
1452 closest->nChannels * closest->wBitsPerSample / 8;
1453 closest->nAvgBytesPerSec =
1454 closest->nBlockAlign * closest->nSamplesPerSec;
1455 *out = closest;
1458 TRACE("returning: %08x %p\n", hr, out ? *out : NULL);
1459 return hr;
1462 static HRESULT WINAPI AudioClient_GetMixFormat(IAudioClient *iface,
1463 WAVEFORMATEX **pwfx)
1465 ACImpl *This = impl_from_IAudioClient(iface);
1466 WAVEFORMATEXTENSIBLE *fmt = &pulse_fmt[This->dataflow == eCapture];
1468 TRACE("(%p)->(%p)\n", This, pwfx);
1470 if (!pwfx)
1471 return E_POINTER;
1473 *pwfx = clone_format(&fmt->Format);
1474 if (!*pwfx)
1475 return E_OUTOFMEMORY;
1476 dump_fmt(*pwfx);
1477 return S_OK;
1480 static HRESULT WINAPI AudioClient_GetDevicePeriod(IAudioClient *iface,
1481 REFERENCE_TIME *defperiod, REFERENCE_TIME *minperiod)
1483 ACImpl *This = impl_from_IAudioClient(iface);
1485 TRACE("(%p)->(%p, %p)\n", This, defperiod, minperiod);
1487 if (!defperiod && !minperiod)
1488 return E_POINTER;
1490 if (defperiod)
1491 *defperiod = pulse_def_period[This->dataflow == eCapture];
1492 if (minperiod)
1493 *minperiod = pulse_min_period[This->dataflow == eCapture];
1495 return S_OK;
1498 static HRESULT WINAPI AudioClient_Start(IAudioClient *iface)
1500 ACImpl *This = impl_from_IAudioClient(iface);
1501 HRESULT hr = S_OK;
1502 int success;
1503 pa_operation *o;
1505 TRACE("(%p)\n", This);
1507 pthread_mutex_lock(&pulse_lock);
1508 hr = pulse_stream_valid(This);
1509 if (FAILED(hr)) {
1510 pthread_mutex_unlock(&pulse_lock);
1511 return hr;
1514 if ((This->flags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK) && !This->event) {
1515 pthread_mutex_unlock(&pulse_lock);
1516 return AUDCLNT_E_EVENTHANDLE_NOT_SET;
1519 if (This->started) {
1520 pthread_mutex_unlock(&pulse_lock);
1521 return AUDCLNT_E_NOT_STOPPED;
1523 This->clock_pulse = PA_USEC_INVALID;
1525 if (pa_stream_is_corked(This->stream)) {
1526 o = pa_stream_cork(This->stream, 0, pulse_op_cb, &success);
1527 if (o) {
1528 while(pa_operation_get_state(o) == PA_OPERATION_RUNNING)
1529 pthread_cond_wait(&pulse_cond, &pulse_lock);
1530 pa_operation_unref(o);
1531 } else
1532 success = 0;
1533 if (!success)
1534 hr = E_FAIL;
1536 if (SUCCEEDED(hr)) {
1537 This->started = TRUE;
1538 if (This->dataflow == eRender && This->event)
1539 pa_stream_set_latency_update_callback(This->stream, pulse_latency_callback, This);
1541 pthread_mutex_unlock(&pulse_lock);
1542 return hr;
1545 static HRESULT WINAPI AudioClient_Stop(IAudioClient *iface)
1547 ACImpl *This = impl_from_IAudioClient(iface);
1548 HRESULT hr = S_OK;
1549 pa_operation *o;
1550 int success;
1552 TRACE("(%p)\n", This);
1554 pthread_mutex_lock(&pulse_lock);
1555 hr = pulse_stream_valid(This);
1556 if (FAILED(hr)) {
1557 pthread_mutex_unlock(&pulse_lock);
1558 return hr;
1561 if (!This->started) {
1562 pthread_mutex_unlock(&pulse_lock);
1563 return S_FALSE;
1566 if (This->dataflow == eRender) {
1567 o = pa_stream_cork(This->stream, 1, pulse_op_cb, &success);
1568 if (o) {
1569 while(pa_operation_get_state(o) == PA_OPERATION_RUNNING)
1570 pthread_cond_wait(&pulse_cond, &pulse_lock);
1571 pa_operation_unref(o);
1572 } else
1573 success = 0;
1574 if (!success)
1575 hr = E_FAIL;
1577 if (SUCCEEDED(hr)) {
1578 This->started = FALSE;
1579 This->clock_pulse = PA_USEC_INVALID;
1581 pthread_mutex_unlock(&pulse_lock);
1582 return hr;
1585 static HRESULT WINAPI AudioClient_Reset(IAudioClient *iface)
1587 ACImpl *This = impl_from_IAudioClient(iface);
1588 HRESULT hr = S_OK;
1590 TRACE("(%p)\n", This);
1592 pthread_mutex_lock(&pulse_lock);
1593 hr = pulse_stream_valid(This);
1594 if (FAILED(hr)) {
1595 pthread_mutex_unlock(&pulse_lock);
1596 return hr;
1599 if (This->started) {
1600 pthread_mutex_unlock(&pulse_lock);
1601 return AUDCLNT_E_NOT_STOPPED;
1604 if (This->locked) {
1605 pthread_mutex_unlock(&pulse_lock);
1606 return AUDCLNT_E_BUFFER_OPERATION_PENDING;
1609 if (This->dataflow == eRender) {
1610 /* If there is still data in the render buffer it needs to be removed from the server */
1611 int success = 0;
1612 if (This->pad) {
1613 pa_operation *o = pa_stream_flush(This->stream, pulse_op_cb, &success);
1614 if (o) {
1615 while(pa_operation_get_state(o) == PA_OPERATION_RUNNING)
1616 pthread_cond_wait(&pulse_cond, &pulse_lock);
1617 pa_operation_unref(o);
1620 if (success || !This->pad)
1621 This->clock_lastpos = This->clock_written = This->pad = 0;
1622 } else {
1623 ACPacket *p;
1624 This->clock_written += This->pad;
1625 This->pad = 0;
1627 if ((p = This->locked_ptr)) {
1628 This->locked_ptr = NULL;
1629 list_add_tail(&This->packet_free_head, &p->entry);
1631 list_move_tail(&This->packet_free_head, &This->packet_filled_head);
1633 pthread_mutex_unlock(&pulse_lock);
1635 return hr;
1638 static HRESULT WINAPI AudioClient_SetEventHandle(IAudioClient *iface,
1639 HANDLE event)
1641 ACImpl *This = impl_from_IAudioClient(iface);
1642 HRESULT hr;
1644 TRACE("(%p)->(%p)\n", This, event);
1646 if (!event)
1647 return E_INVALIDARG;
1649 pthread_mutex_lock(&pulse_lock);
1650 hr = pulse_stream_valid(This);
1651 if (FAILED(hr)) {
1652 pthread_mutex_unlock(&pulse_lock);
1653 return hr;
1656 if (!(This->flags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK))
1657 hr = AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED;
1658 else if (This->event)
1659 hr = HRESULT_FROM_WIN32(ERROR_INVALID_NAME);
1660 else
1661 This->event = event;
1662 pthread_mutex_unlock(&pulse_lock);
1663 return hr;
1666 static HRESULT WINAPI AudioClient_GetService(IAudioClient *iface, REFIID riid,
1667 void **ppv)
1669 ACImpl *This = impl_from_IAudioClient(iface);
1670 HRESULT hr;
1672 TRACE("(%p)->(%s, %p)\n", This, debugstr_guid(riid), ppv);
1674 if (!ppv)
1675 return E_POINTER;
1676 *ppv = NULL;
1678 pthread_mutex_lock(&pulse_lock);
1679 hr = pulse_stream_valid(This);
1680 pthread_mutex_unlock(&pulse_lock);
1681 if (FAILED(hr))
1682 return hr;
1684 if (IsEqualIID(riid, &IID_IAudioRenderClient)) {
1685 if (This->dataflow != eRender)
1686 return AUDCLNT_E_WRONG_ENDPOINT_TYPE;
1687 *ppv = &This->IAudioRenderClient_iface;
1688 } else if (IsEqualIID(riid, &IID_IAudioCaptureClient)) {
1689 if (This->dataflow != eCapture)
1690 return AUDCLNT_E_WRONG_ENDPOINT_TYPE;
1691 *ppv = &This->IAudioCaptureClient_iface;
1692 } else if (IsEqualIID(riid, &IID_IAudioClock)) {
1693 *ppv = &This->IAudioClock_iface;
1694 } else if (IsEqualIID(riid, &IID_IAudioStreamVolume)) {
1695 *ppv = &This->IAudioStreamVolume_iface;
1696 } else if (IsEqualIID(riid, &IID_IAudioSessionControl) ||
1697 IsEqualIID(riid, &IID_IChannelAudioVolume) ||
1698 IsEqualIID(riid, &IID_ISimpleAudioVolume)) {
1699 if (!This->session_wrapper) {
1700 This->session_wrapper = AudioSessionWrapper_Create(This);
1701 if (!This->session_wrapper)
1702 return E_OUTOFMEMORY;
1704 if (IsEqualIID(riid, &IID_IAudioSessionControl))
1705 *ppv = &This->session_wrapper->IAudioSessionControl2_iface;
1706 else if (IsEqualIID(riid, &IID_IChannelAudioVolume))
1707 *ppv = &This->session_wrapper->IChannelAudioVolume_iface;
1708 else if (IsEqualIID(riid, &IID_ISimpleAudioVolume))
1709 *ppv = &This->session_wrapper->ISimpleAudioVolume_iface;
1712 if (*ppv) {
1713 IUnknown_AddRef((IUnknown*)*ppv);
1714 return S_OK;
1717 FIXME("stub %s\n", debugstr_guid(riid));
1718 return E_NOINTERFACE;
1721 static const IAudioClientVtbl AudioClient_Vtbl =
1723 AudioClient_QueryInterface,
1724 AudioClient_AddRef,
1725 AudioClient_Release,
1726 AudioClient_Initialize,
1727 AudioClient_GetBufferSize,
1728 AudioClient_GetStreamLatency,
1729 AudioClient_GetCurrentPadding,
1730 AudioClient_IsFormatSupported,
1731 AudioClient_GetMixFormat,
1732 AudioClient_GetDevicePeriod,
1733 AudioClient_Start,
1734 AudioClient_Stop,
1735 AudioClient_Reset,
1736 AudioClient_SetEventHandle,
1737 AudioClient_GetService
1740 static HRESULT WINAPI AudioRenderClient_QueryInterface(
1741 IAudioRenderClient *iface, REFIID riid, void **ppv)
1743 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
1745 if (!ppv)
1746 return E_POINTER;
1747 *ppv = NULL;
1749 if (IsEqualIID(riid, &IID_IUnknown) ||
1750 IsEqualIID(riid, &IID_IAudioRenderClient))
1751 *ppv = iface;
1752 if (*ppv) {
1753 IUnknown_AddRef((IUnknown*)*ppv);
1754 return S_OK;
1757 WARN("Unknown interface %s\n", debugstr_guid(riid));
1758 return E_NOINTERFACE;
1761 static ULONG WINAPI AudioRenderClient_AddRef(IAudioRenderClient *iface)
1763 ACImpl *This = impl_from_IAudioRenderClient(iface);
1764 return AudioClient_AddRef(&This->IAudioClient_iface);
1767 static ULONG WINAPI AudioRenderClient_Release(IAudioRenderClient *iface)
1769 ACImpl *This = impl_from_IAudioRenderClient(iface);
1770 return AudioClient_Release(&This->IAudioClient_iface);
1773 static HRESULT WINAPI AudioRenderClient_GetBuffer(IAudioRenderClient *iface,
1774 UINT32 frames, BYTE **data)
1776 ACImpl *This = impl_from_IAudioRenderClient(iface);
1777 UINT32 avail, pad, req, bytes = frames * pa_frame_size(&This->ss);
1778 HRESULT hr = S_OK;
1779 int ret = -1;
1781 TRACE("(%p)->(%u, %p)\n", This, frames, data);
1783 if (!data)
1784 return E_POINTER;
1785 *data = NULL;
1787 pthread_mutex_lock(&pulse_lock);
1788 hr = pulse_stream_valid(This);
1789 if (FAILED(hr) || This->locked) {
1790 pthread_mutex_unlock(&pulse_lock);
1791 return FAILED(hr) ? hr : AUDCLNT_E_OUT_OF_ORDER;
1793 if (!frames) {
1794 pthread_mutex_unlock(&pulse_lock);
1795 return S_OK;
1798 ACImpl_GetRenderPad(This, &pad);
1799 avail = This->bufsize_frames - pad;
1800 if (avail < frames || bytes > This->bufsize_bytes) {
1801 pthread_mutex_unlock(&pulse_lock);
1802 WARN("Wanted to write %u, but only %u available\n", frames, avail);
1803 return AUDCLNT_E_BUFFER_TOO_LARGE;
1806 This->locked = frames;
1807 req = bytes;
1808 ret = pa_stream_begin_write(This->stream, &This->locked_ptr, &req);
1809 if (ret < 0 || req < bytes) {
1810 FIXME("%p Not using pulse locked data: %i %u/%u %u/%u\n", This, ret, req/pa_frame_size(&This->ss), frames, pad, This->bufsize_frames);
1811 if (ret >= 0)
1812 pa_stream_cancel_write(This->stream);
1813 *data = This->tmp_buffer;
1814 This->locked_ptr = NULL;
1815 } else
1816 *data = This->locked_ptr;
1817 pthread_mutex_unlock(&pulse_lock);
1818 return hr;
1821 static HRESULT WINAPI AudioRenderClient_ReleaseBuffer(
1822 IAudioRenderClient *iface, UINT32 written_frames, DWORD flags)
1824 ACImpl *This = impl_from_IAudioRenderClient(iface);
1825 UINT32 written_bytes = written_frames * pa_frame_size(&This->ss);
1827 TRACE("(%p)->(%u, %x)\n", This, written_frames, flags);
1829 pthread_mutex_lock(&pulse_lock);
1830 if (!This->locked || !written_frames) {
1831 if (This->locked_ptr)
1832 pa_stream_cancel_write(This->stream);
1833 This->locked = 0;
1834 This->locked_ptr = NULL;
1835 pthread_mutex_unlock(&pulse_lock);
1836 return written_frames ? AUDCLNT_E_OUT_OF_ORDER : S_OK;
1839 if (This->locked < written_frames) {
1840 pthread_mutex_unlock(&pulse_lock);
1841 return AUDCLNT_E_INVALID_SIZE;
1844 if (flags & AUDCLNT_BUFFERFLAGS_SILENT) {
1845 if (This->ss.format == PA_SAMPLE_U8)
1846 memset(This->tmp_buffer, 128, written_bytes);
1847 else
1848 memset(This->tmp_buffer, 0, written_bytes);
1851 This->locked = 0;
1852 if (This->locked_ptr)
1853 pa_stream_write(This->stream, This->locked_ptr, written_bytes, NULL, 0, PA_SEEK_RELATIVE);
1854 else
1855 pa_stream_write(This->stream, This->tmp_buffer, written_bytes, NULL, 0, PA_SEEK_RELATIVE);
1856 This->pad += written_bytes;
1857 This->locked_ptr = NULL;
1858 TRACE("Released %u, pad %u\n", written_frames, This->pad / pa_frame_size(&This->ss));
1859 assert(This->pad <= This->bufsize_bytes);
1860 pthread_mutex_unlock(&pulse_lock);
1861 return S_OK;
1864 static const IAudioRenderClientVtbl AudioRenderClient_Vtbl = {
1865 AudioRenderClient_QueryInterface,
1866 AudioRenderClient_AddRef,
1867 AudioRenderClient_Release,
1868 AudioRenderClient_GetBuffer,
1869 AudioRenderClient_ReleaseBuffer
1872 static HRESULT WINAPI AudioCaptureClient_QueryInterface(
1873 IAudioCaptureClient *iface, REFIID riid, void **ppv)
1875 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
1877 if (!ppv)
1878 return E_POINTER;
1879 *ppv = NULL;
1881 if (IsEqualIID(riid, &IID_IUnknown) ||
1882 IsEqualIID(riid, &IID_IAudioCaptureClient))
1883 *ppv = iface;
1884 if (*ppv) {
1885 IUnknown_AddRef((IUnknown*)*ppv);
1886 return S_OK;
1889 WARN("Unknown interface %s\n", debugstr_guid(riid));
1890 return E_NOINTERFACE;
1893 static ULONG WINAPI AudioCaptureClient_AddRef(IAudioCaptureClient *iface)
1895 ACImpl *This = impl_from_IAudioCaptureClient(iface);
1896 return IAudioClient_AddRef(&This->IAudioClient_iface);
1899 static ULONG WINAPI AudioCaptureClient_Release(IAudioCaptureClient *iface)
1901 ACImpl *This = impl_from_IAudioCaptureClient(iface);
1902 return IAudioClient_Release(&This->IAudioClient_iface);
1905 static HRESULT WINAPI AudioCaptureClient_GetBuffer(IAudioCaptureClient *iface,
1906 BYTE **data, UINT32 *frames, DWORD *flags, UINT64 *devpos,
1907 UINT64 *qpcpos)
1909 ACImpl *This = impl_from_IAudioCaptureClient(iface);
1910 HRESULT hr;
1911 ACPacket *packet;
1913 TRACE("(%p)->(%p, %p, %p, %p, %p)\n", This, data, frames, flags,
1914 devpos, qpcpos);
1916 if (!data || !frames || !flags)
1917 return E_POINTER;
1919 pthread_mutex_lock(&pulse_lock);
1920 hr = pulse_stream_valid(This);
1921 if (FAILED(hr) || This->locked) {
1922 pthread_mutex_unlock(&pulse_lock);
1923 return FAILED(hr) ? hr : AUDCLNT_E_OUT_OF_ORDER;
1926 ACImpl_GetCapturePad(This, NULL);
1927 if ((packet = This->locked_ptr)) {
1928 *frames = This->capture_period / pa_frame_size(&This->ss);
1929 *flags = 0;
1930 if (packet->discont)
1931 *flags |= AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY;
1932 if (devpos) {
1933 if (packet->discont)
1934 *devpos = (This->clock_written + This->capture_period) / pa_frame_size(&This->ss);
1935 else
1936 *devpos = This->clock_written / pa_frame_size(&This->ss);
1938 if (qpcpos)
1939 *qpcpos = packet->qpcpos;
1940 *data = packet->data;
1942 else
1943 *frames = 0;
1944 This->locked = *frames;
1945 pthread_mutex_unlock(&pulse_lock);
1946 return *frames ? S_OK : AUDCLNT_S_BUFFER_EMPTY;
1949 static HRESULT WINAPI AudioCaptureClient_ReleaseBuffer(
1950 IAudioCaptureClient *iface, UINT32 done)
1952 ACImpl *This = impl_from_IAudioCaptureClient(iface);
1954 TRACE("(%p)->(%u)\n", This, done);
1956 pthread_mutex_lock(&pulse_lock);
1957 if (!This->locked && done) {
1958 pthread_mutex_unlock(&pulse_lock);
1959 return AUDCLNT_E_OUT_OF_ORDER;
1961 if (done && This->locked != done) {
1962 pthread_mutex_unlock(&pulse_lock);
1963 return AUDCLNT_E_INVALID_SIZE;
1965 if (done) {
1966 ACPacket *packet = This->locked_ptr;
1967 This->locked_ptr = NULL;
1968 This->pad -= This->capture_period;
1969 if (packet->discont)
1970 This->clock_written += 2 * This->capture_period;
1971 else
1972 This->clock_written += This->capture_period;
1973 list_add_tail(&This->packet_free_head, &packet->entry);
1975 This->locked = 0;
1976 pthread_mutex_unlock(&pulse_lock);
1977 return S_OK;
1980 static HRESULT WINAPI AudioCaptureClient_GetNextPacketSize(
1981 IAudioCaptureClient *iface, UINT32 *frames)
1983 ACImpl *This = impl_from_IAudioCaptureClient(iface);
1984 ACPacket *p;
1986 TRACE("(%p)->(%p)\n", This, frames);
1987 if (!frames)
1988 return E_POINTER;
1990 pthread_mutex_lock(&pulse_lock);
1991 ACImpl_GetCapturePad(This, NULL);
1992 p = This->locked_ptr;
1993 if (p)
1994 *frames = This->capture_period / pa_frame_size(&This->ss);
1995 else
1996 *frames = 0;
1997 pthread_mutex_unlock(&pulse_lock);
1998 return S_OK;
2001 static const IAudioCaptureClientVtbl AudioCaptureClient_Vtbl =
2003 AudioCaptureClient_QueryInterface,
2004 AudioCaptureClient_AddRef,
2005 AudioCaptureClient_Release,
2006 AudioCaptureClient_GetBuffer,
2007 AudioCaptureClient_ReleaseBuffer,
2008 AudioCaptureClient_GetNextPacketSize
2011 static HRESULT WINAPI AudioClock_QueryInterface(IAudioClock *iface,
2012 REFIID riid, void **ppv)
2014 ACImpl *This = impl_from_IAudioClock(iface);
2016 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
2018 if (!ppv)
2019 return E_POINTER;
2020 *ppv = NULL;
2022 if (IsEqualIID(riid, &IID_IUnknown) || IsEqualIID(riid, &IID_IAudioClock))
2023 *ppv = iface;
2024 else if (IsEqualIID(riid, &IID_IAudioClock2))
2025 *ppv = &This->IAudioClock2_iface;
2026 if (*ppv) {
2027 IUnknown_AddRef((IUnknown*)*ppv);
2028 return S_OK;
2031 WARN("Unknown interface %s\n", debugstr_guid(riid));
2032 return E_NOINTERFACE;
2035 static ULONG WINAPI AudioClock_AddRef(IAudioClock *iface)
2037 ACImpl *This = impl_from_IAudioClock(iface);
2038 return IAudioClient_AddRef(&This->IAudioClient_iface);
2041 static ULONG WINAPI AudioClock_Release(IAudioClock *iface)
2043 ACImpl *This = impl_from_IAudioClock(iface);
2044 return IAudioClient_Release(&This->IAudioClient_iface);
2047 static HRESULT WINAPI AudioClock_GetFrequency(IAudioClock *iface, UINT64 *freq)
2049 ACImpl *This = impl_from_IAudioClock(iface);
2050 HRESULT hr;
2052 TRACE("(%p)->(%p)\n", This, freq);
2054 pthread_mutex_lock(&pulse_lock);
2055 hr = pulse_stream_valid(This);
2056 if (SUCCEEDED(hr))
2057 *freq = This->ss.rate * pa_frame_size(&This->ss);
2058 pthread_mutex_unlock(&pulse_lock);
2059 return hr;
2062 static HRESULT WINAPI AudioClock_GetPosition(IAudioClock *iface, UINT64 *pos,
2063 UINT64 *qpctime)
2065 ACImpl *This = impl_from_IAudioClock(iface);
2066 pa_usec_t time;
2067 HRESULT hr;
2069 TRACE("(%p)->(%p, %p)\n", This, pos, qpctime);
2071 if (!pos)
2072 return E_POINTER;
2074 pthread_mutex_lock(&pulse_lock);
2075 hr = pulse_stream_valid(This);
2076 if (FAILED(hr)) {
2077 pthread_mutex_unlock(&pulse_lock);
2078 return hr;
2081 *pos = This->clock_written;
2082 if (This->clock_pulse != PA_USEC_INVALID && pa_stream_get_time(This->stream, &time) >= 0) {
2083 UINT32 delta = pa_usec_to_bytes(time - This->clock_pulse, &This->ss);
2084 if (delta < This->pad)
2085 *pos += delta;
2086 else
2087 *pos += This->pad;
2090 /* Make time never go backwards */
2091 if (*pos < This->clock_lastpos)
2092 *pos = This->clock_lastpos;
2093 else
2094 This->clock_lastpos = *pos;
2095 pthread_mutex_unlock(&pulse_lock);
2097 TRACE("%p Position: %u\n", This, (unsigned)*pos);
2099 if (qpctime) {
2100 LARGE_INTEGER stamp, freq;
2101 QueryPerformanceCounter(&stamp);
2102 QueryPerformanceFrequency(&freq);
2103 *qpctime = (stamp.QuadPart * (INT64)10000000) / freq.QuadPart;
2106 return S_OK;
2109 static HRESULT WINAPI AudioClock_GetCharacteristics(IAudioClock *iface,
2110 DWORD *chars)
2112 ACImpl *This = impl_from_IAudioClock(iface);
2114 TRACE("(%p)->(%p)\n", This, chars);
2116 if (!chars)
2117 return E_POINTER;
2119 *chars = AUDIOCLOCK_CHARACTERISTIC_FIXED_FREQ;
2121 return S_OK;
2124 static const IAudioClockVtbl AudioClock_Vtbl =
2126 AudioClock_QueryInterface,
2127 AudioClock_AddRef,
2128 AudioClock_Release,
2129 AudioClock_GetFrequency,
2130 AudioClock_GetPosition,
2131 AudioClock_GetCharacteristics
2134 static HRESULT WINAPI AudioClock2_QueryInterface(IAudioClock2 *iface,
2135 REFIID riid, void **ppv)
2137 ACImpl *This = impl_from_IAudioClock2(iface);
2138 return IAudioClock_QueryInterface(&This->IAudioClock_iface, riid, ppv);
2141 static ULONG WINAPI AudioClock2_AddRef(IAudioClock2 *iface)
2143 ACImpl *This = impl_from_IAudioClock2(iface);
2144 return IAudioClient_AddRef(&This->IAudioClient_iface);
2147 static ULONG WINAPI AudioClock2_Release(IAudioClock2 *iface)
2149 ACImpl *This = impl_from_IAudioClock2(iface);
2150 return IAudioClient_Release(&This->IAudioClient_iface);
2153 static HRESULT WINAPI AudioClock2_GetDevicePosition(IAudioClock2 *iface,
2154 UINT64 *pos, UINT64 *qpctime)
2156 ACImpl *This = impl_from_IAudioClock2(iface);
2157 HRESULT hr = AudioClock_GetPosition(&This->IAudioClock_iface, pos, qpctime);
2158 if (SUCCEEDED(hr))
2159 *pos /= pa_frame_size(&This->ss);
2160 return hr;
2163 static const IAudioClock2Vtbl AudioClock2_Vtbl =
2165 AudioClock2_QueryInterface,
2166 AudioClock2_AddRef,
2167 AudioClock2_Release,
2168 AudioClock2_GetDevicePosition
2171 static HRESULT WINAPI AudioStreamVolume_QueryInterface(
2172 IAudioStreamVolume *iface, REFIID riid, void **ppv)
2174 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
2176 if (!ppv)
2177 return E_POINTER;
2178 *ppv = NULL;
2180 if (IsEqualIID(riid, &IID_IUnknown) ||
2181 IsEqualIID(riid, &IID_IAudioStreamVolume))
2182 *ppv = iface;
2183 if (*ppv) {
2184 IUnknown_AddRef((IUnknown*)*ppv);
2185 return S_OK;
2188 WARN("Unknown interface %s\n", debugstr_guid(riid));
2189 return E_NOINTERFACE;
2192 static ULONG WINAPI AudioStreamVolume_AddRef(IAudioStreamVolume *iface)
2194 ACImpl *This = impl_from_IAudioStreamVolume(iface);
2195 return IAudioClient_AddRef(&This->IAudioClient_iface);
2198 static ULONG WINAPI AudioStreamVolume_Release(IAudioStreamVolume *iface)
2200 ACImpl *This = impl_from_IAudioStreamVolume(iface);
2201 return IAudioClient_Release(&This->IAudioClient_iface);
2204 static HRESULT WINAPI AudioStreamVolume_GetChannelCount(
2205 IAudioStreamVolume *iface, UINT32 *out)
2207 ACImpl *This = impl_from_IAudioStreamVolume(iface);
2209 TRACE("(%p)->(%p)\n", This, out);
2211 if (!out)
2212 return E_POINTER;
2214 *out = This->ss.channels;
2216 return S_OK;
2219 struct pulse_info_cb_data {
2220 UINT32 n;
2221 float *levels;
2224 static void pulse_sink_input_info_cb(pa_context *c, const pa_sink_input_info *info, int eol, void *data)
2226 struct pulse_info_cb_data *d = data;
2227 int i;
2228 if (eol)
2229 return;
2230 for (i = 0; i < d->n; ++i)
2231 d->levels[i] = (float)info->volume.values[i] / (float)PA_VOLUME_NORM;
2232 pthread_cond_signal(&pulse_cond);
2235 static void pulse_source_info_cb(pa_context *c, const pa_source_info *info, int eol, void *data)
2237 struct pulse_info_cb_data *d = data;
2238 int i;
2239 if (eol)
2240 return;
2241 for (i = 0; i < d->n; ++i)
2242 d->levels[i] = (float)info->volume.values[i] / (float)PA_VOLUME_NORM;
2243 pthread_cond_signal(&pulse_cond);
2246 static HRESULT WINAPI AudioStreamVolume_SetAllVolumes(
2247 IAudioStreamVolume *iface, UINT32 count, const float *levels)
2249 ACImpl *This = impl_from_IAudioStreamVolume(iface);
2250 pa_operation *o;
2251 HRESULT hr;
2252 int success = 0, i;
2253 pa_cvolume cv;
2255 TRACE("(%p)->(%d, %p)\n", This, count, levels);
2257 if (!levels)
2258 return E_POINTER;
2260 if (count != This->ss.channels)
2261 return E_INVALIDARG;
2263 pthread_mutex_lock(&pulse_lock);
2264 hr = pulse_stream_valid(This);
2265 if (FAILED(hr))
2266 goto out;
2268 if (pulse_stream_volume) {
2269 cv.channels = count;
2270 for (i = 0; i < cv.channels; ++i)
2271 cv.values[i] = levels[i] * (float)PA_VOLUME_NORM;
2272 if (This->dataflow == eRender)
2273 o = pa_context_set_sink_input_volume(pulse_ctx, pa_stream_get_index(This->stream), &cv, pulse_ctx_op_cb, &success);
2274 else
2275 o = pa_context_set_source_volume_by_index(pulse_ctx, pa_stream_get_device_index(This->stream), &cv, pulse_ctx_op_cb, &success);
2276 if (o) {
2277 while(pa_operation_get_state(o) == PA_OPERATION_RUNNING)
2278 pthread_cond_wait(&pulse_cond, &pulse_lock);
2279 pa_operation_unref(o);
2281 if (!success)
2282 hr = AUDCLNT_E_BUFFER_ERROR;
2283 } else {
2284 int i;
2285 for (i = 0; i < count; ++i)
2286 This->vol[i] = levels[i];
2289 out:
2290 pthread_mutex_unlock(&pulse_lock);
2291 return hr;
2294 static HRESULT WINAPI AudioStreamVolume_GetAllVolumes(
2295 IAudioStreamVolume *iface, UINT32 count, float *levels)
2297 ACImpl *This = impl_from_IAudioStreamVolume(iface);
2298 pa_operation *o;
2299 HRESULT hr;
2300 struct pulse_info_cb_data info;
2302 TRACE("(%p)->(%d, %p)\n", This, count, levels);
2304 if (!levels)
2305 return E_POINTER;
2307 if (count != This->ss.channels)
2308 return E_INVALIDARG;
2310 pthread_mutex_lock(&pulse_lock);
2311 hr = pulse_stream_valid(This);
2312 if (FAILED(hr))
2313 goto out;
2315 if (pulse_stream_volume) {
2316 info.n = count;
2317 info.levels = levels;
2318 if (This->dataflow == eRender)
2319 o = pa_context_get_sink_input_info(pulse_ctx, pa_stream_get_index(This->stream), pulse_sink_input_info_cb, &info);
2320 else
2321 o = pa_context_get_source_info_by_index(pulse_ctx, pa_stream_get_device_index(This->stream), pulse_source_info_cb, &info);
2322 if (o) {
2323 while(pa_operation_get_state(o) == PA_OPERATION_RUNNING)
2324 pthread_cond_wait(&pulse_cond, &pulse_lock);
2325 pa_operation_unref(o);
2326 } else
2327 hr = AUDCLNT_E_BUFFER_ERROR;
2328 } else {
2329 int i;
2330 for (i = 0; i < count; ++i)
2331 levels[i] = This->vol[i];
2334 out:
2335 pthread_mutex_unlock(&pulse_lock);
2336 return hr;
2339 static HRESULT WINAPI AudioStreamVolume_SetChannelVolume(
2340 IAudioStreamVolume *iface, UINT32 index, float level)
2342 ACImpl *This = impl_from_IAudioStreamVolume(iface);
2343 HRESULT hr;
2344 float volumes[PA_CHANNELS_MAX];
2346 TRACE("(%p)->(%d, %f)\n", This, index, level);
2348 if (level < 0.f || level > 1.f)
2349 return E_INVALIDARG;
2351 if (index >= This->ss.channels)
2352 return E_INVALIDARG;
2354 hr = AudioStreamVolume_GetAllVolumes(iface, This->ss.channels, volumes);
2355 volumes[index] = level;
2356 if (SUCCEEDED(hr))
2357 hr = AudioStreamVolume_SetAllVolumes(iface, This->ss.channels, volumes);
2358 return hr;
2361 static HRESULT WINAPI AudioStreamVolume_GetChannelVolume(
2362 IAudioStreamVolume *iface, UINT32 index, float *level)
2364 ACImpl *This = impl_from_IAudioStreamVolume(iface);
2365 float volumes[PA_CHANNELS_MAX];
2366 HRESULT hr;
2368 TRACE("(%p)->(%d, %p)\n", This, index, level);
2370 if (!level)
2371 return E_POINTER;
2373 if (index >= This->ss.channels)
2374 return E_INVALIDARG;
2376 hr = AudioStreamVolume_GetAllVolumes(iface, This->ss.channels, volumes);
2377 if (SUCCEEDED(hr))
2378 *level = volumes[index];
2379 return hr;
2382 static const IAudioStreamVolumeVtbl AudioStreamVolume_Vtbl =
2384 AudioStreamVolume_QueryInterface,
2385 AudioStreamVolume_AddRef,
2386 AudioStreamVolume_Release,
2387 AudioStreamVolume_GetChannelCount,
2388 AudioStreamVolume_SetChannelVolume,
2389 AudioStreamVolume_GetChannelVolume,
2390 AudioStreamVolume_SetAllVolumes,
2391 AudioStreamVolume_GetAllVolumes
2394 static AudioSessionWrapper *AudioSessionWrapper_Create(ACImpl *client)
2396 AudioSessionWrapper *ret;
2398 ret = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
2399 sizeof(AudioSessionWrapper));
2400 if (!ret)
2401 return NULL;
2403 ret->IAudioSessionControl2_iface.lpVtbl = &AudioSessionControl2_Vtbl;
2404 ret->ISimpleAudioVolume_iface.lpVtbl = &SimpleAudioVolume_Vtbl;
2405 ret->IChannelAudioVolume_iface.lpVtbl = &ChannelAudioVolume_Vtbl;
2407 ret->ref = !client;
2409 ret->client = client;
2410 if (client) {
2411 ret->session = client->session;
2412 AudioClient_AddRef(&client->IAudioClient_iface);
2415 return ret;
2418 static HRESULT WINAPI AudioSessionControl_QueryInterface(
2419 IAudioSessionControl2 *iface, REFIID riid, void **ppv)
2421 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
2423 if (!ppv)
2424 return E_POINTER;
2425 *ppv = NULL;
2427 if (IsEqualIID(riid, &IID_IUnknown) ||
2428 IsEqualIID(riid, &IID_IAudioSessionControl) ||
2429 IsEqualIID(riid, &IID_IAudioSessionControl2))
2430 *ppv = iface;
2431 if (*ppv) {
2432 IUnknown_AddRef((IUnknown*)*ppv);
2433 return S_OK;
2436 WARN("Unknown interface %s\n", debugstr_guid(riid));
2437 return E_NOINTERFACE;
2440 static ULONG WINAPI AudioSessionControl_AddRef(IAudioSessionControl2 *iface)
2442 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2443 ULONG ref;
2444 ref = InterlockedIncrement(&This->ref);
2445 TRACE("(%p) Refcount now %u\n", This, ref);
2446 return ref;
2449 static ULONG WINAPI AudioSessionControl_Release(IAudioSessionControl2 *iface)
2451 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2452 ULONG ref;
2453 ref = InterlockedDecrement(&This->ref);
2454 TRACE("(%p) Refcount now %u\n", This, ref);
2455 if (!ref) {
2456 if (This->client) {
2457 This->client->session_wrapper = NULL;
2458 AudioClient_Release(&This->client->IAudioClient_iface);
2460 HeapFree(GetProcessHeap(), 0, This);
2462 return ref;
2465 static HRESULT WINAPI AudioSessionControl_GetState(IAudioSessionControl2 *iface,
2466 AudioSessionState *state)
2468 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2469 ACImpl *client;
2471 TRACE("(%p)->(%p)\n", This, state);
2473 if (!state)
2474 return NULL_PTR_ERR;
2476 pthread_mutex_lock(&pulse_lock);
2477 if (list_empty(&This->session->clients)) {
2478 *state = AudioSessionStateExpired;
2479 goto out;
2481 LIST_FOR_EACH_ENTRY(client, &This->session->clients, ACImpl, entry) {
2482 if (client->started) {
2483 *state = AudioSessionStateActive;
2484 goto out;
2487 *state = AudioSessionStateInactive;
2489 out:
2490 pthread_mutex_unlock(&pulse_lock);
2491 return S_OK;
2494 static HRESULT WINAPI AudioSessionControl_GetDisplayName(
2495 IAudioSessionControl2 *iface, WCHAR **name)
2497 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2499 FIXME("(%p)->(%p) - stub\n", This, name);
2501 return E_NOTIMPL;
2504 static HRESULT WINAPI AudioSessionControl_SetDisplayName(
2505 IAudioSessionControl2 *iface, const WCHAR *name, const GUID *session)
2507 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2509 FIXME("(%p)->(%p, %s) - stub\n", This, name, debugstr_guid(session));
2511 return E_NOTIMPL;
2514 static HRESULT WINAPI AudioSessionControl_GetIconPath(
2515 IAudioSessionControl2 *iface, WCHAR **path)
2517 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2519 FIXME("(%p)->(%p) - stub\n", This, path);
2521 return E_NOTIMPL;
2524 static HRESULT WINAPI AudioSessionControl_SetIconPath(
2525 IAudioSessionControl2 *iface, const WCHAR *path, const GUID *session)
2527 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2529 FIXME("(%p)->(%p, %s) - stub\n", This, path, debugstr_guid(session));
2531 return E_NOTIMPL;
2534 static HRESULT WINAPI AudioSessionControl_GetGroupingParam(
2535 IAudioSessionControl2 *iface, GUID *group)
2537 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2539 FIXME("(%p)->(%p) - stub\n", This, group);
2541 return E_NOTIMPL;
2544 static HRESULT WINAPI AudioSessionControl_SetGroupingParam(
2545 IAudioSessionControl2 *iface, const GUID *group, const GUID *session)
2547 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2549 FIXME("(%p)->(%s, %s) - stub\n", This, debugstr_guid(group),
2550 debugstr_guid(session));
2552 return E_NOTIMPL;
2555 static HRESULT WINAPI AudioSessionControl_RegisterAudioSessionNotification(
2556 IAudioSessionControl2 *iface, IAudioSessionEvents *events)
2558 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2560 FIXME("(%p)->(%p) - stub\n", This, events);
2562 return S_OK;
2565 static HRESULT WINAPI AudioSessionControl_UnregisterAudioSessionNotification(
2566 IAudioSessionControl2 *iface, IAudioSessionEvents *events)
2568 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2570 FIXME("(%p)->(%p) - stub\n", This, events);
2572 return S_OK;
2575 static HRESULT WINAPI AudioSessionControl_GetSessionIdentifier(
2576 IAudioSessionControl2 *iface, WCHAR **id)
2578 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2580 FIXME("(%p)->(%p) - stub\n", This, id);
2582 return E_NOTIMPL;
2585 static HRESULT WINAPI AudioSessionControl_GetSessionInstanceIdentifier(
2586 IAudioSessionControl2 *iface, WCHAR **id)
2588 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2590 FIXME("(%p)->(%p) - stub\n", This, id);
2592 return E_NOTIMPL;
2595 static HRESULT WINAPI AudioSessionControl_GetProcessId(
2596 IAudioSessionControl2 *iface, DWORD *pid)
2598 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2600 TRACE("(%p)->(%p)\n", This, pid);
2602 if (!pid)
2603 return E_POINTER;
2605 *pid = GetCurrentProcessId();
2607 return S_OK;
2610 static HRESULT WINAPI AudioSessionControl_IsSystemSoundsSession(
2611 IAudioSessionControl2 *iface)
2613 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2615 TRACE("(%p)\n", This);
2617 return S_FALSE;
2620 static HRESULT WINAPI AudioSessionControl_SetDuckingPreference(
2621 IAudioSessionControl2 *iface, BOOL optout)
2623 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2625 TRACE("(%p)->(%d)\n", This, optout);
2627 return S_OK;
2630 static const IAudioSessionControl2Vtbl AudioSessionControl2_Vtbl =
2632 AudioSessionControl_QueryInterface,
2633 AudioSessionControl_AddRef,
2634 AudioSessionControl_Release,
2635 AudioSessionControl_GetState,
2636 AudioSessionControl_GetDisplayName,
2637 AudioSessionControl_SetDisplayName,
2638 AudioSessionControl_GetIconPath,
2639 AudioSessionControl_SetIconPath,
2640 AudioSessionControl_GetGroupingParam,
2641 AudioSessionControl_SetGroupingParam,
2642 AudioSessionControl_RegisterAudioSessionNotification,
2643 AudioSessionControl_UnregisterAudioSessionNotification,
2644 AudioSessionControl_GetSessionIdentifier,
2645 AudioSessionControl_GetSessionInstanceIdentifier,
2646 AudioSessionControl_GetProcessId,
2647 AudioSessionControl_IsSystemSoundsSession,
2648 AudioSessionControl_SetDuckingPreference
2651 typedef struct _SessionMgr {
2652 IAudioSessionManager2 IAudioSessionManager2_iface;
2654 LONG ref;
2656 IMMDevice *device;
2657 } SessionMgr;
2659 static HRESULT WINAPI AudioSessionManager_QueryInterface(IAudioSessionManager2 *iface,
2660 REFIID riid, void **ppv)
2662 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
2664 if (!ppv)
2665 return E_POINTER;
2666 *ppv = NULL;
2668 if (IsEqualIID(riid, &IID_IUnknown) ||
2669 IsEqualIID(riid, &IID_IAudioSessionManager) ||
2670 IsEqualIID(riid, &IID_IAudioSessionManager2))
2671 *ppv = iface;
2672 if (*ppv) {
2673 IUnknown_AddRef((IUnknown*)*ppv);
2674 return S_OK;
2677 WARN("Unknown interface %s\n", debugstr_guid(riid));
2678 return E_NOINTERFACE;
2681 static inline SessionMgr *impl_from_IAudioSessionManager2(IAudioSessionManager2 *iface)
2683 return CONTAINING_RECORD(iface, SessionMgr, IAudioSessionManager2_iface);
2686 static ULONG WINAPI AudioSessionManager_AddRef(IAudioSessionManager2 *iface)
2688 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
2689 ULONG ref;
2690 ref = InterlockedIncrement(&This->ref);
2691 TRACE("(%p) Refcount now %u\n", This, ref);
2692 return ref;
2695 static ULONG WINAPI AudioSessionManager_Release(IAudioSessionManager2 *iface)
2697 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
2698 ULONG ref;
2699 ref = InterlockedDecrement(&This->ref);
2700 TRACE("(%p) Refcount now %u\n", This, ref);
2701 if (!ref)
2702 HeapFree(GetProcessHeap(), 0, This);
2703 return ref;
2706 static HRESULT WINAPI AudioSessionManager_GetAudioSessionControl(
2707 IAudioSessionManager2 *iface, const GUID *session_guid, DWORD flags,
2708 IAudioSessionControl **out)
2710 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
2711 AudioSession *session;
2712 AudioSessionWrapper *wrapper;
2713 HRESULT hr;
2715 TRACE("(%p)->(%s, %x, %p)\n", This, debugstr_guid(session_guid),
2716 flags, out);
2718 hr = get_audio_session(session_guid, This->device, 0, &session);
2719 if (FAILED(hr))
2720 return hr;
2722 wrapper = AudioSessionWrapper_Create(NULL);
2723 if (!wrapper)
2724 return E_OUTOFMEMORY;
2726 wrapper->session = session;
2728 *out = (IAudioSessionControl*)&wrapper->IAudioSessionControl2_iface;
2730 return S_OK;
2733 static HRESULT WINAPI AudioSessionManager_GetSimpleAudioVolume(
2734 IAudioSessionManager2 *iface, const GUID *session_guid, DWORD flags,
2735 ISimpleAudioVolume **out)
2737 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
2738 AudioSession *session;
2739 AudioSessionWrapper *wrapper;
2740 HRESULT hr;
2742 TRACE("(%p)->(%s, %x, %p)\n", This, debugstr_guid(session_guid),
2743 flags, out);
2745 hr = get_audio_session(session_guid, This->device, 0, &session);
2746 if (FAILED(hr))
2747 return hr;
2749 wrapper = AudioSessionWrapper_Create(NULL);
2750 if (!wrapper)
2751 return E_OUTOFMEMORY;
2753 wrapper->session = session;
2755 *out = &wrapper->ISimpleAudioVolume_iface;
2757 return S_OK;
2760 static HRESULT WINAPI AudioSessionManager_GetSessionEnumerator(
2761 IAudioSessionManager2 *iface, IAudioSessionEnumerator **out)
2763 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
2764 FIXME("(%p)->(%p) - stub\n", This, out);
2765 return E_NOTIMPL;
2768 static HRESULT WINAPI AudioSessionManager_RegisterSessionNotification(
2769 IAudioSessionManager2 *iface, IAudioSessionNotification *notification)
2771 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
2772 FIXME("(%p)->(%p) - stub\n", This, notification);
2773 return E_NOTIMPL;
2776 static HRESULT WINAPI AudioSessionManager_UnregisterSessionNotification(
2777 IAudioSessionManager2 *iface, IAudioSessionNotification *notification)
2779 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
2780 FIXME("(%p)->(%p) - stub\n", This, notification);
2781 return E_NOTIMPL;
2784 static HRESULT WINAPI AudioSessionManager_RegisterDuckNotification(
2785 IAudioSessionManager2 *iface, const WCHAR *session_id,
2786 IAudioVolumeDuckNotification *notification)
2788 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
2789 FIXME("(%p)->(%p) - stub\n", This, notification);
2790 return E_NOTIMPL;
2793 static HRESULT WINAPI AudioSessionManager_UnregisterDuckNotification(
2794 IAudioSessionManager2 *iface,
2795 IAudioVolumeDuckNotification *notification)
2797 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
2798 FIXME("(%p)->(%p) - stub\n", This, notification);
2799 return E_NOTIMPL;
2802 static const IAudioSessionManager2Vtbl AudioSessionManager2_Vtbl =
2804 AudioSessionManager_QueryInterface,
2805 AudioSessionManager_AddRef,
2806 AudioSessionManager_Release,
2807 AudioSessionManager_GetAudioSessionControl,
2808 AudioSessionManager_GetSimpleAudioVolume,
2809 AudioSessionManager_GetSessionEnumerator,
2810 AudioSessionManager_RegisterSessionNotification,
2811 AudioSessionManager_UnregisterSessionNotification,
2812 AudioSessionManager_RegisterDuckNotification,
2813 AudioSessionManager_UnregisterDuckNotification
2816 static HRESULT WINAPI SimpleAudioVolume_QueryInterface(
2817 ISimpleAudioVolume *iface, REFIID riid, void **ppv)
2819 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
2821 if (!ppv)
2822 return E_POINTER;
2823 *ppv = NULL;
2825 if (IsEqualIID(riid, &IID_IUnknown) ||
2826 IsEqualIID(riid, &IID_ISimpleAudioVolume))
2827 *ppv = iface;
2828 if (*ppv) {
2829 IUnknown_AddRef((IUnknown*)*ppv);
2830 return S_OK;
2833 WARN("Unknown interface %s\n", debugstr_guid(riid));
2834 return E_NOINTERFACE;
2837 static ULONG WINAPI SimpleAudioVolume_AddRef(ISimpleAudioVolume *iface)
2839 AudioSessionWrapper *This = impl_from_ISimpleAudioVolume(iface);
2840 return AudioSessionControl_AddRef(&This->IAudioSessionControl2_iface);
2843 static ULONG WINAPI SimpleAudioVolume_Release(ISimpleAudioVolume *iface)
2845 AudioSessionWrapper *This = impl_from_ISimpleAudioVolume(iface);
2846 return AudioSessionControl_Release(&This->IAudioSessionControl2_iface);
2849 static HRESULT WINAPI SimpleAudioVolume_SetMasterVolume(
2850 ISimpleAudioVolume *iface, float level, const GUID *context)
2852 AudioSessionWrapper *This = impl_from_ISimpleAudioVolume(iface);
2853 AudioSession *session = This->session;
2855 TRACE("(%p)->(%f, %s)\n", session, level, wine_dbgstr_guid(context));
2857 if (level < 0.f || level > 1.f)
2858 return E_INVALIDARG;
2860 if (context)
2861 FIXME("Notifications not supported yet\n");
2863 TRACE("Pulseaudio does not support session volume control\n");
2865 pthread_mutex_lock(&pulse_lock);
2866 session->master_vol = level;
2867 pthread_mutex_unlock(&pulse_lock);
2869 return S_OK;
2872 static HRESULT WINAPI SimpleAudioVolume_GetMasterVolume(
2873 ISimpleAudioVolume *iface, float *level)
2875 AudioSessionWrapper *This = impl_from_ISimpleAudioVolume(iface);
2876 AudioSession *session = This->session;
2878 TRACE("(%p)->(%p)\n", session, level);
2880 if (!level)
2881 return NULL_PTR_ERR;
2883 *level = session->master_vol;
2885 return S_OK;
2888 static HRESULT WINAPI SimpleAudioVolume_SetMute(ISimpleAudioVolume *iface,
2889 BOOL mute, const GUID *context)
2891 AudioSessionWrapper *This = impl_from_ISimpleAudioVolume(iface);
2892 AudioSession *session = This->session;
2894 TRACE("(%p)->(%u, %p)\n", session, mute, context);
2896 if (context)
2897 FIXME("Notifications not supported yet\n");
2899 session->mute = mute;
2901 return S_OK;
2904 static HRESULT WINAPI SimpleAudioVolume_GetMute(ISimpleAudioVolume *iface,
2905 BOOL *mute)
2907 AudioSessionWrapper *This = impl_from_ISimpleAudioVolume(iface);
2908 AudioSession *session = This->session;
2910 TRACE("(%p)->(%p)\n", session, mute);
2912 if (!mute)
2913 return NULL_PTR_ERR;
2915 *mute = session->mute;
2917 return S_OK;
2920 static const ISimpleAudioVolumeVtbl SimpleAudioVolume_Vtbl =
2922 SimpleAudioVolume_QueryInterface,
2923 SimpleAudioVolume_AddRef,
2924 SimpleAudioVolume_Release,
2925 SimpleAudioVolume_SetMasterVolume,
2926 SimpleAudioVolume_GetMasterVolume,
2927 SimpleAudioVolume_SetMute,
2928 SimpleAudioVolume_GetMute
2931 static HRESULT WINAPI ChannelAudioVolume_QueryInterface(
2932 IChannelAudioVolume *iface, REFIID riid, void **ppv)
2934 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
2936 if (!ppv)
2937 return E_POINTER;
2938 *ppv = NULL;
2940 if (IsEqualIID(riid, &IID_IUnknown) ||
2941 IsEqualIID(riid, &IID_IChannelAudioVolume))
2942 *ppv = iface;
2943 if (*ppv) {
2944 IUnknown_AddRef((IUnknown*)*ppv);
2945 return S_OK;
2948 WARN("Unknown interface %s\n", debugstr_guid(riid));
2949 return E_NOINTERFACE;
2952 static ULONG WINAPI ChannelAudioVolume_AddRef(IChannelAudioVolume *iface)
2954 AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
2955 return AudioSessionControl_AddRef(&This->IAudioSessionControl2_iface);
2958 static ULONG WINAPI ChannelAudioVolume_Release(IChannelAudioVolume *iface)
2960 AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
2961 return AudioSessionControl_Release(&This->IAudioSessionControl2_iface);
2964 static HRESULT WINAPI ChannelAudioVolume_GetChannelCount(
2965 IChannelAudioVolume *iface, UINT32 *out)
2967 AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
2968 AudioSession *session = This->session;
2970 TRACE("(%p)->(%p)\n", session, out);
2972 if (!out)
2973 return NULL_PTR_ERR;
2975 *out = session->channel_count;
2977 return S_OK;
2980 static HRESULT WINAPI ChannelAudioVolume_SetChannelVolume(
2981 IChannelAudioVolume *iface, UINT32 index, float level,
2982 const GUID *context)
2984 AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
2985 AudioSession *session = This->session;
2987 TRACE("(%p)->(%d, %f, %s)\n", session, index, level,
2988 wine_dbgstr_guid(context));
2990 if (level < 0.f || level > 1.f)
2991 return E_INVALIDARG;
2993 if (index >= session->channel_count)
2994 return E_INVALIDARG;
2996 if (context)
2997 FIXME("Notifications not supported yet\n");
2999 TRACE("Pulseaudio does not support session volume control\n");
3001 pthread_mutex_lock(&pulse_lock);
3002 session->channel_vols[index] = level;
3003 pthread_mutex_unlock(&pulse_lock);
3005 return S_OK;
3008 static HRESULT WINAPI ChannelAudioVolume_GetChannelVolume(
3009 IChannelAudioVolume *iface, UINT32 index, float *level)
3011 AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
3012 AudioSession *session = This->session;
3014 TRACE("(%p)->(%d, %p)\n", session, index, level);
3016 if (!level)
3017 return NULL_PTR_ERR;
3019 if (index >= session->channel_count)
3020 return E_INVALIDARG;
3022 *level = session->channel_vols[index];
3024 return S_OK;
3027 static HRESULT WINAPI ChannelAudioVolume_SetAllVolumes(
3028 IChannelAudioVolume *iface, UINT32 count, const float *levels,
3029 const GUID *context)
3031 AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
3032 AudioSession *session = This->session;
3033 int i;
3035 TRACE("(%p)->(%d, %p, %s)\n", session, count, levels,
3036 wine_dbgstr_guid(context));
3038 if (!levels)
3039 return NULL_PTR_ERR;
3041 if (count != session->channel_count)
3042 return E_INVALIDARG;
3044 if (context)
3045 FIXME("Notifications not supported yet\n");
3047 TRACE("Pulseaudio does not support session volume control\n");
3049 pthread_mutex_lock(&pulse_lock);
3050 for(i = 0; i < count; ++i)
3051 session->channel_vols[i] = levels[i];
3052 pthread_mutex_unlock(&pulse_lock);
3053 return S_OK;
3056 static HRESULT WINAPI ChannelAudioVolume_GetAllVolumes(
3057 IChannelAudioVolume *iface, UINT32 count, float *levels)
3059 AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
3060 AudioSession *session = This->session;
3061 int i;
3063 TRACE("(%p)->(%d, %p)\n", session, count, levels);
3065 if (!levels)
3066 return NULL_PTR_ERR;
3068 if (count != session->channel_count)
3069 return E_INVALIDARG;
3071 for(i = 0; i < count; ++i)
3072 levels[i] = session->channel_vols[i];
3074 return S_OK;
3077 static const IChannelAudioVolumeVtbl ChannelAudioVolume_Vtbl =
3079 ChannelAudioVolume_QueryInterface,
3080 ChannelAudioVolume_AddRef,
3081 ChannelAudioVolume_Release,
3082 ChannelAudioVolume_GetChannelCount,
3083 ChannelAudioVolume_SetChannelVolume,
3084 ChannelAudioVolume_GetChannelVolume,
3085 ChannelAudioVolume_SetAllVolumes,
3086 ChannelAudioVolume_GetAllVolumes
3089 HRESULT WINAPI AUDDRV_GetAudioSessionManager(IMMDevice *device,
3090 IAudioSessionManager2 **out)
3092 SessionMgr *This = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(SessionMgr));
3093 *out = NULL;
3094 if (!This)
3095 return E_OUTOFMEMORY;
3096 This->IAudioSessionManager2_iface.lpVtbl = &AudioSessionManager2_Vtbl;
3097 This->device = device;
3098 This->ref = 1;
3099 *out = &This->IAudioSessionManager2_iface;
3100 return S_OK;