winepulse: Fixup IsFormatSupported calls.
[wine/multimedia.git] / dlls / winepulse.drv / mmdevdrv.c
blob9f933efa200d0114d0f6621b675134caa022dd1b
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
21 #define NONAMELESSUNION
22 #define COBJMACROS
23 #define _GNU_SOURCE
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>
33 #include <errno.h>
35 #include <pulse/pulseaudio.h>
37 #include "windef.h"
38 #include "winbase.h"
39 #include "winnls.h"
40 #include "winreg.h"
41 #include "wine/debug.h"
42 #include "wine/unicode.h"
43 #include "wine/list.h"
45 #include "ole2.h"
46 #include "dshow.h"
47 #include "dsound.h"
48 #include "propsys.h"
50 #include "initguid.h"
51 #include "ks.h"
52 #include "ksmedia.h"
53 #include "mmdeviceapi.h"
54 #include "audioclient.h"
55 #include "endpointvolume.h"
56 #include "audiopolicy.h"
58 WINE_DEFAULT_DEBUG_CHANNEL(pulse);
60 #define NULL_PTR_ERR MAKE_HRESULT(SEVERITY_ERROR, FACILITY_WIN32, RPC_X_NULL_REF_POINTER)
62 /* From <dlls/mmdevapi/mmdevapi.h> */
63 enum DriverPriority {
64 Priority_Unavailable = 0,
65 Priority_Low,
66 Priority_Neutral,
67 Priority_Preferred
70 static const REFERENCE_TIME MinimumPeriod = 30000;
71 static const REFERENCE_TIME DefaultPeriod = 100000;
73 static pa_context *pulse_ctx;
74 static pa_mainloop *pulse_ml;
76 static HANDLE pulse_thread;
77 static pthread_mutex_t pulse_lock;
78 static pthread_cond_t pulse_cond = PTHREAD_COND_INITIALIZER;
79 static struct list g_sessions = LIST_INIT(g_sessions);
81 /* Mixer format + period times */
82 static WAVEFORMATEXTENSIBLE pulse_fmt[2];
83 static REFERENCE_TIME pulse_min_period[2], pulse_def_period[2];
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 BOOL WINAPI DllMain(HINSTANCE dll, DWORD reason, void *reserved)
92 if (reason == DLL_PROCESS_ATTACH) {
93 pthread_mutexattr_t attr;
95 DisableThreadLibraryCalls(dll);
97 pthread_mutexattr_init(&attr);
98 pthread_mutexattr_setprotocol(&attr, PTHREAD_PRIO_INHERIT);
100 if (pthread_mutex_init(&pulse_lock, &attr) != 0)
101 pthread_mutex_init(&pulse_lock, NULL);
102 } else if (reason == DLL_PROCESS_DETACH) {
103 if (pulse_thread)
104 SetThreadPriority(pulse_thread, 0);
105 if (pulse_ctx) {
106 pa_context_disconnect(pulse_ctx);
107 pa_context_unref(pulse_ctx);
109 if (pulse_ml)
110 pa_mainloop_quit(pulse_ml, 0);
111 if (pulse_thread) {
112 WaitForSingleObject(pulse_thread, INFINITE);
113 CloseHandle(pulse_thread);
116 return TRUE;
119 typedef struct ACImpl ACImpl;
121 typedef struct _AudioSession {
122 GUID guid;
123 struct list clients;
125 IMMDevice *device;
127 float master_vol;
128 UINT32 channel_count;
129 float *channel_vols;
130 BOOL mute;
132 struct list entry;
133 } AudioSession;
135 typedef struct _AudioSessionWrapper {
136 IAudioSessionControl2 IAudioSessionControl2_iface;
137 IChannelAudioVolume IChannelAudioVolume_iface;
138 ISimpleAudioVolume ISimpleAudioVolume_iface;
140 LONG ref;
142 ACImpl *client;
143 AudioSession *session;
144 } AudioSessionWrapper;
146 typedef struct _ACPacket {
147 struct list entry;
148 UINT64 qpcpos;
149 BYTE *data;
150 UINT32 discont;
151 } ACPacket;
153 struct ACImpl {
154 IAudioClient IAudioClient_iface;
155 IAudioRenderClient IAudioRenderClient_iface;
156 IAudioCaptureClient IAudioCaptureClient_iface;
157 IAudioClock IAudioClock_iface;
158 IAudioClock2 IAudioClock2_iface;
159 IAudioStreamVolume IAudioStreamVolume_iface;
160 IMMDevice *parent;
161 struct list entry;
162 float vol[PA_CHANNELS_MAX];
164 LONG ref;
165 EDataFlow dataflow;
166 DWORD flags;
167 AUDCLNT_SHAREMODE share;
168 HANDLE event;
170 UINT32 bufsize_frames, bufsize_bytes, locked, capture_period, pad, started, peek_ofs;
171 void *locked_ptr, *tmp_buffer;
173 pa_stream *stream;
174 pa_sample_spec ss;
175 pa_channel_map map;
177 INT64 clock_lastpos, clock_written;
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 return ret;
279 static void pulse_contextcallback(pa_context *c, void *userdata)
281 switch (pa_context_get_state(c)) {
282 default:
283 FIXME("Unhandled state: %i\n", pa_context_get_state(c));
284 case PA_CONTEXT_CONNECTING:
285 case PA_CONTEXT_UNCONNECTED:
286 case PA_CONTEXT_AUTHORIZING:
287 case PA_CONTEXT_SETTING_NAME:
288 case PA_CONTEXT_TERMINATED:
289 TRACE("State change to %i\n", pa_context_get_state(c));
290 return;
292 case PA_CONTEXT_READY:
293 TRACE("Ready\n");
294 break;
296 case PA_CONTEXT_FAILED:
297 ERR("Context failed: %s\n", pa_strerror(pa_context_errno(c)));
298 break;
300 pthread_cond_signal(&pulse_cond);
303 static void pulse_stream_state(pa_stream *s, void *user)
305 pa_stream_state_t state = pa_stream_get_state(s);
306 TRACE("Stream state changed to %i\n", state);
307 pthread_cond_signal(&pulse_cond);
310 static const enum pa_channel_position pulse_pos_from_wfx[] = {
311 PA_CHANNEL_POSITION_FRONT_LEFT,
312 PA_CHANNEL_POSITION_FRONT_RIGHT,
313 PA_CHANNEL_POSITION_FRONT_CENTER,
314 PA_CHANNEL_POSITION_LFE,
315 PA_CHANNEL_POSITION_REAR_LEFT,
316 PA_CHANNEL_POSITION_REAR_RIGHT,
317 PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER,
318 PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER,
319 PA_CHANNEL_POSITION_REAR_CENTER,
320 PA_CHANNEL_POSITION_SIDE_LEFT,
321 PA_CHANNEL_POSITION_SIDE_RIGHT,
322 PA_CHANNEL_POSITION_TOP_CENTER,
323 PA_CHANNEL_POSITION_TOP_FRONT_LEFT,
324 PA_CHANNEL_POSITION_TOP_FRONT_CENTER,
325 PA_CHANNEL_POSITION_TOP_FRONT_RIGHT,
326 PA_CHANNEL_POSITION_TOP_REAR_LEFT,
327 PA_CHANNEL_POSITION_TOP_REAR_CENTER,
328 PA_CHANNEL_POSITION_TOP_REAR_RIGHT
331 static void pulse_probe_settings(int render, WAVEFORMATEXTENSIBLE *fmt) {
332 WAVEFORMATEX *wfx = &fmt->Format;
333 pa_stream *stream;
334 pa_channel_map map;
335 pa_sample_spec ss;
336 pa_buffer_attr attr;
337 int ret, i;
338 unsigned int length = 0;
340 pa_channel_map_init_auto(&map, 2, PA_CHANNEL_MAP_ALSA);
341 ss.rate = 48000;
342 ss.format = PA_SAMPLE_FLOAT32LE;
343 ss.channels = map.channels;
345 attr.maxlength = -1;
346 attr.tlength = -1;
347 attr.minreq = attr.fragsize = pa_frame_size(&ss);
348 attr.prebuf = 0;
350 stream = pa_stream_new(pulse_ctx, "format test stream", &ss, &map);
351 if (stream)
352 pa_stream_set_state_callback(stream, pulse_stream_state, NULL);
353 if (!stream)
354 ret = -1;
355 else if (render)
356 ret = pa_stream_connect_playback(stream, NULL, &attr,
357 PA_STREAM_START_CORKED|PA_STREAM_FIX_RATE|PA_STREAM_FIX_CHANNELS|PA_STREAM_EARLY_REQUESTS, NULL, NULL);
358 else
359 ret = pa_stream_connect_record(stream, NULL, &attr, PA_STREAM_START_CORKED|PA_STREAM_FIX_RATE|PA_STREAM_FIX_CHANNELS|PA_STREAM_EARLY_REQUESTS);
360 if (ret >= 0) {
361 while (pa_mainloop_iterate(pulse_ml, 1, &ret) >= 0 &&
362 pa_stream_get_state(stream) == PA_STREAM_CREATING)
364 if (pa_stream_get_state(stream) == PA_STREAM_READY) {
365 ss = *pa_stream_get_sample_spec(stream);
366 map = *pa_stream_get_channel_map(stream);
367 if (render)
368 length = pa_stream_get_buffer_attr(stream)->minreq;
369 else
370 length = pa_stream_get_buffer_attr(stream)->fragsize;
371 pa_stream_disconnect(stream);
372 while (pa_mainloop_iterate(pulse_ml, 1, &ret) >= 0 &&
373 pa_stream_get_state(stream) == PA_STREAM_READY)
377 if (stream)
378 pa_stream_unref(stream);
379 if (length)
380 pulse_def_period[!render] = pulse_min_period[!render] = pa_bytes_to_usec(10 * length, &ss);
381 else
382 pulse_min_period[!render] = MinimumPeriod;
383 if (pulse_def_period[!render] <= DefaultPeriod)
384 pulse_def_period[!render] = DefaultPeriod;
386 wfx->wFormatTag = WAVE_FORMAT_EXTENSIBLE;
387 wfx->cbSize = sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX);
388 wfx->nChannels = ss.channels;
389 wfx->wBitsPerSample = 8 * pa_sample_size_of_format(ss.format);
390 wfx->nSamplesPerSec = ss.rate;
391 wfx->nBlockAlign = pa_frame_size(&ss);
392 wfx->nAvgBytesPerSec = wfx->nSamplesPerSec * wfx->nBlockAlign;
393 if (ss.format != PA_SAMPLE_S24_32LE)
394 fmt->Samples.wValidBitsPerSample = wfx->wBitsPerSample;
395 else
396 fmt->Samples.wValidBitsPerSample = 24;
397 if (ss.format == PA_SAMPLE_FLOAT32LE)
398 fmt->SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
399 else
400 fmt->SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
402 fmt->dwChannelMask = 0;
403 for (i = 0; i < map.channels; ++i)
404 switch (map.map[i]) {
405 default: FIXME("Unhandled channel %s\n", pa_channel_position_to_string(map.map[i])); break;
406 case PA_CHANNEL_POSITION_FRONT_LEFT: fmt->dwChannelMask |= SPEAKER_FRONT_LEFT; break;
407 case PA_CHANNEL_POSITION_MONO:
408 case PA_CHANNEL_POSITION_FRONT_CENTER: fmt->dwChannelMask |= SPEAKER_FRONT_CENTER; break;
409 case PA_CHANNEL_POSITION_FRONT_RIGHT: fmt->dwChannelMask |= SPEAKER_FRONT_RIGHT; break;
410 case PA_CHANNEL_POSITION_REAR_LEFT: fmt->dwChannelMask |= SPEAKER_BACK_LEFT; break;
411 case PA_CHANNEL_POSITION_REAR_CENTER: fmt->dwChannelMask |= SPEAKER_BACK_CENTER; break;
412 case PA_CHANNEL_POSITION_REAR_RIGHT: fmt->dwChannelMask |= SPEAKER_BACK_RIGHT; break;
413 case PA_CHANNEL_POSITION_LFE: fmt->dwChannelMask |= SPEAKER_LOW_FREQUENCY; break;
414 case PA_CHANNEL_POSITION_SIDE_LEFT: fmt->dwChannelMask |= SPEAKER_SIDE_LEFT; break;
415 case PA_CHANNEL_POSITION_SIDE_RIGHT: fmt->dwChannelMask |= SPEAKER_SIDE_RIGHT; break;
416 case PA_CHANNEL_POSITION_TOP_CENTER: fmt->dwChannelMask |= SPEAKER_TOP_CENTER; break;
417 case PA_CHANNEL_POSITION_TOP_FRONT_LEFT: fmt->dwChannelMask |= SPEAKER_TOP_FRONT_LEFT; break;
418 case PA_CHANNEL_POSITION_TOP_FRONT_CENTER: fmt->dwChannelMask |= SPEAKER_TOP_FRONT_CENTER; break;
419 case PA_CHANNEL_POSITION_TOP_FRONT_RIGHT: fmt->dwChannelMask |= SPEAKER_TOP_FRONT_RIGHT; break;
420 case PA_CHANNEL_POSITION_TOP_REAR_LEFT: fmt->dwChannelMask |= SPEAKER_TOP_BACK_LEFT; break;
421 case PA_CHANNEL_POSITION_TOP_REAR_CENTER: fmt->dwChannelMask |= SPEAKER_TOP_BACK_CENTER; break;
422 case PA_CHANNEL_POSITION_TOP_REAR_RIGHT: fmt->dwChannelMask |= SPEAKER_TOP_BACK_RIGHT; break;
426 static HRESULT pulse_connect(void)
428 int len;
429 WCHAR path[PATH_MAX], *name;
430 char *str;
432 if (!pulse_thread)
434 if (!(pulse_thread = CreateThread(NULL, 0, pulse_mainloop_thread, NULL, 0, NULL)))
436 ERR("Failed to create mainloop thread.");
437 return E_FAIL;
439 SetThreadPriority(pulse_thread, THREAD_PRIORITY_TIME_CRITICAL);
440 pthread_cond_wait(&pulse_cond, &pulse_lock);
443 if (pulse_ctx && PA_CONTEXT_IS_GOOD(pa_context_get_state(pulse_ctx)))
444 return S_OK;
445 if (pulse_ctx)
446 pa_context_unref(pulse_ctx);
448 GetModuleFileNameW(NULL, path, sizeof(path)/sizeof(*path));
449 name = strrchrW(path, '\\');
450 if (!name)
451 name = path;
452 else
453 name++;
454 len = WideCharToMultiByte(CP_UNIXCP, 0, name, -1, NULL, 0, NULL, NULL);
455 str = pa_xmalloc(len);
456 WideCharToMultiByte(CP_UNIXCP, 0, name, -1, str, len, NULL, NULL);
457 TRACE("Name: %s\n", str);
458 pulse_ctx = pa_context_new(pa_mainloop_get_api(pulse_ml), str);
459 pa_xfree(str);
460 if (!pulse_ctx) {
461 ERR("Failed to create context\n");
462 return E_FAIL;
465 pa_context_set_state_callback(pulse_ctx, pulse_contextcallback, NULL);
467 TRACE("libpulse protocol version: %u. API Version %u\n", pa_context_get_protocol_version(pulse_ctx), PA_API_VERSION);
468 if (pa_context_connect(pulse_ctx, NULL, 0, NULL) < 0)
469 goto fail;
471 /* Wait for connection */
472 while (pthread_cond_wait(&pulse_cond, &pulse_lock)) {
473 pa_context_state_t state = pa_context_get_state(pulse_ctx);
475 if (state == PA_CONTEXT_FAILED || state == PA_CONTEXT_TERMINATED)
476 goto fail;
478 if (state == PA_CONTEXT_READY)
479 break;
482 TRACE("Connected to server %s with protocol version: %i.\n",
483 pa_context_get_server(pulse_ctx),
484 pa_context_get_server_protocol_version(pulse_ctx));
485 return S_OK;
487 fail:
488 pa_context_unref(pulse_ctx);
489 pulse_ctx = NULL;
490 return E_FAIL;
493 /* some poorly-behaved applications call audio functions during DllMain, so we
494 * have to do as much as possible without creating a new thread. this function
495 * sets up a synchronous connection to verify the server is running and query
496 * static data. */
497 static HRESULT pulse_test_connect(void)
499 int len, ret;
500 WCHAR path[PATH_MAX], *name;
501 char *str;
503 pulse_ml = pa_mainloop_new();
505 pa_mainloop_set_poll_func(pulse_ml, pulse_poll_func, NULL);
507 GetModuleFileNameW(NULL, path, sizeof(path)/sizeof(*path));
508 name = strrchrW(path, '\\');
509 if (!name)
510 name = path;
511 else
512 name++;
513 len = WideCharToMultiByte(CP_UNIXCP, 0, name, -1, NULL, 0, NULL, NULL);
514 str = pa_xmalloc(len);
515 WideCharToMultiByte(CP_UNIXCP, 0, name, -1, str, len, NULL, NULL);
516 TRACE("Name: %s\n", str);
517 pulse_ctx = pa_context_new(pa_mainloop_get_api(pulse_ml), str);
518 pa_xfree(str);
519 if (!pulse_ctx) {
520 ERR("Failed to create context\n");
521 pa_mainloop_free(pulse_ml);
522 pulse_ml = NULL;
523 return E_FAIL;
526 pa_context_set_state_callback(pulse_ctx, pulse_contextcallback, NULL);
528 TRACE("libpulse protocol version: %u. API Version %u\n", pa_context_get_protocol_version(pulse_ctx), PA_API_VERSION);
529 if (pa_context_connect(pulse_ctx, NULL, 0, NULL) < 0)
530 goto fail;
532 /* Wait for connection */
533 while (pa_mainloop_iterate(pulse_ml, 1, &ret) >= 0) {
534 pa_context_state_t state = pa_context_get_state(pulse_ctx);
536 if (state == PA_CONTEXT_FAILED || state == PA_CONTEXT_TERMINATED)
537 goto fail;
539 if (state == PA_CONTEXT_READY)
540 break;
543 TRACE("Test-connected to server %s with protocol version: %i.\n",
544 pa_context_get_server(pulse_ctx),
545 pa_context_get_server_protocol_version(pulse_ctx));
547 pulse_probe_settings(1, &pulse_fmt[0]);
548 pulse_probe_settings(0, &pulse_fmt[1]);
550 pa_context_unref(pulse_ctx);
551 pulse_ctx = NULL;
552 pa_mainloop_free(pulse_ml);
553 pulse_ml = NULL;
555 return S_OK;
557 fail:
558 pa_context_unref(pulse_ctx);
559 pulse_ctx = NULL;
560 pa_mainloop_free(pulse_ml);
561 pulse_ml = NULL;
563 return E_FAIL;
566 static HRESULT pulse_stream_valid(ACImpl *This) {
567 if (!This->stream)
568 return AUDCLNT_E_NOT_INITIALIZED;
569 if (!This->stream || pa_stream_get_state(This->stream) != PA_STREAM_READY)
570 return AUDCLNT_E_DEVICE_INVALIDATED;
571 return S_OK;
574 static void dump_attr(const pa_buffer_attr *attr) {
575 TRACE("maxlength: %u\n", attr->maxlength);
576 TRACE("minreq: %u\n", attr->minreq);
577 TRACE("fragsize: %u\n", attr->fragsize);
578 TRACE("tlength: %u\n", attr->tlength);
579 TRACE("prebuf: %u\n", attr->prebuf);
582 static void pulse_op_cb(pa_stream *s, int success, void *user) {
583 TRACE("Success: %i\n", success);
584 *(int*)user = success;
585 pthread_cond_signal(&pulse_cond);
588 static void pulse_attr_update(pa_stream *s, void *user) {
589 const pa_buffer_attr *attr = pa_stream_get_buffer_attr(s);
590 TRACE("New attributes or device moved:\n");
591 dump_attr(attr);
594 static void pulse_wr_callback(pa_stream *s, size_t bytes, void *userdata)
596 ACImpl *This = userdata;
597 UINT32 oldpad = This->pad;
599 if (bytes < This->bufsize_bytes)
600 This->pad = This->bufsize_bytes - bytes;
601 else
602 This->pad = 0;
604 if (oldpad == This->pad)
605 return;
607 assert(oldpad > This->pad);
609 This->clock_written += oldpad - This->pad;
610 TRACE("New pad: %zu (-%zu)\n", This->pad / pa_frame_size(&This->ss), (oldpad - This->pad) / pa_frame_size(&This->ss));
612 if (This->event)
613 SetEvent(This->event);
616 static void pulse_underflow_callback(pa_stream *s, void *userdata)
618 WARN("Underflow\n");
621 /* Latency is periodically updated even when nothing is played,
622 * because of PA_STREAM_AUTO_TIMING_UPDATE so use it as timer
624 * Perfect for passing all tests :)
626 static void pulse_latency_callback(pa_stream *s, void *userdata)
628 ACImpl *This = userdata;
629 if (!This->pad && This->event)
630 SetEvent(This->event);
633 static void pulse_started_callback(pa_stream *s, void *userdata)
635 TRACE("(Re)started playing\n");
638 static void pulse_rd_loop(ACImpl *This, size_t bytes)
640 while (bytes >= This->capture_period) {
641 ACPacket *p, *next;
642 LARGE_INTEGER stamp, freq;
643 BYTE *dst, *src;
644 size_t src_len, copy, rem = This->capture_period;
645 if (!(p = (ACPacket*)list_head(&This->packet_free_head))) {
646 p = (ACPacket*)list_head(&This->packet_filled_head);
647 if (!p->discont) {
648 next = (ACPacket*)p->entry.next;
649 next->discont = 1;
650 } else
651 p = (ACPacket*)list_tail(&This->packet_filled_head);
652 assert(This->pad == This->bufsize_bytes);
653 } else {
654 assert(This->pad < This->bufsize_bytes);
655 This->pad += This->capture_period;
656 assert(This->pad <= This->bufsize_bytes);
658 QueryPerformanceCounter(&stamp);
659 QueryPerformanceFrequency(&freq);
660 p->qpcpos = (stamp.QuadPart * (INT64)10000000) / freq.QuadPart;
661 p->discont = 0;
662 list_remove(&p->entry);
663 list_add_tail(&This->packet_filled_head, &p->entry);
665 dst = p->data;
666 while (rem) {
667 pa_stream_peek(This->stream, (const void**)&src, &src_len);
668 assert(src_len);
669 assert(This->peek_ofs < src_len);
670 src += This->peek_ofs;
671 src_len -= This->peek_ofs;
672 assert(src_len <= bytes);
674 copy = rem;
675 if (copy > src_len)
676 copy = src_len;
677 memcpy(dst, src, rem);
678 src += copy;
679 src_len -= copy;
680 dst += copy;
681 rem -= copy;
683 if (!src_len) {
684 This->peek_ofs = 0;
685 pa_stream_drop(This->stream);
686 } else
687 This->peek_ofs += copy;
689 bytes -= This->capture_period;
693 static void pulse_rd_drop(ACImpl *This, size_t bytes)
695 while (bytes >= This->capture_period) {
696 size_t src_len, copy, rem = This->capture_period;
697 while (rem) {
698 const void *src;
699 pa_stream_peek(This->stream, &src, &src_len);
700 assert(src_len);
701 assert(This->peek_ofs < src_len);
702 src_len -= This->peek_ofs;
703 assert(src_len <= bytes);
705 copy = rem;
706 if (copy > src_len)
707 copy = src_len;
709 src_len -= copy;
710 rem -= copy;
712 if (!src_len) {
713 This->peek_ofs = 0;
714 pa_stream_drop(This->stream);
715 } else
716 This->peek_ofs += copy;
717 bytes -= copy;
722 static void pulse_rd_callback(pa_stream *s, size_t bytes, void *userdata)
724 ACImpl *This = userdata;
726 TRACE("Readable total: %zu, fragsize: %u\n", bytes, pa_stream_get_buffer_attr(s)->fragsize);
727 assert(bytes >= This->peek_ofs);
728 bytes -= This->peek_ofs;
729 if (bytes < This->capture_period)
730 return;
732 if (This->started)
733 pulse_rd_loop(This, bytes);
734 else
735 pulse_rd_drop(This, bytes);
737 if (This->event)
738 SetEvent(This->event);
741 static HRESULT pulse_stream_connect(ACImpl *This, UINT32 period_bytes) {
742 int ret;
743 char buffer[64];
744 static LONG number;
745 pa_buffer_attr attr;
746 if (This->stream) {
747 pa_stream_disconnect(This->stream);
748 while (pa_stream_get_state(This->stream) == PA_STREAM_READY)
749 pthread_cond_wait(&pulse_cond, &pulse_lock);
750 pa_stream_unref(This->stream);
752 ret = InterlockedIncrement(&number);
753 sprintf(buffer, "audio stream #%i", ret);
754 This->stream = pa_stream_new(pulse_ctx, buffer, &This->ss, &This->map);
755 pa_stream_set_state_callback(This->stream, pulse_stream_state, This);
756 pa_stream_set_buffer_attr_callback(This->stream, pulse_attr_update, This);
757 pa_stream_set_moved_callback(This->stream, pulse_attr_update, This);
759 /* Pulseaudio will fill in correct values */
760 attr.minreq = attr.fragsize = period_bytes;
761 attr.maxlength = attr.tlength = This->bufsize_bytes;
762 attr.prebuf = pa_frame_size(&This->ss);
763 dump_attr(&attr);
764 if (This->dataflow == eRender)
765 ret = pa_stream_connect_playback(This->stream, NULL, &attr,
766 PA_STREAM_START_CORKED|PA_STREAM_START_UNMUTED|PA_STREAM_AUTO_TIMING_UPDATE|PA_STREAM_INTERPOLATE_TIMING|PA_STREAM_EARLY_REQUESTS, NULL, NULL);
767 else
768 ret = pa_stream_connect_record(This->stream, NULL, &attr,
769 PA_STREAM_START_CORKED|PA_STREAM_START_UNMUTED|PA_STREAM_AUTO_TIMING_UPDATE|PA_STREAM_INTERPOLATE_TIMING|PA_STREAM_EARLY_REQUESTS);
770 if (ret < 0) {
771 WARN("Returns %i\n", ret);
772 return AUDCLNT_E_ENDPOINT_CREATE_FAILED;
774 while (pa_stream_get_state(This->stream) == PA_STREAM_CREATING)
775 pthread_cond_wait(&pulse_cond, &pulse_lock);
776 if (pa_stream_get_state(This->stream) != PA_STREAM_READY)
777 return AUDCLNT_E_ENDPOINT_CREATE_FAILED;
779 if (This->dataflow == eRender) {
780 pa_stream_set_write_callback(This->stream, pulse_wr_callback, This);
781 pa_stream_set_underflow_callback(This->stream, pulse_underflow_callback, This);
782 pa_stream_set_started_callback(This->stream, pulse_started_callback, This);
783 } else
784 pa_stream_set_read_callback(This->stream, pulse_rd_callback, This);
785 return S_OK;
788 HRESULT WINAPI AUDDRV_GetEndpointIDs(EDataFlow flow, const WCHAR ***ids, GUID **keys,
789 UINT *num, UINT *def_index)
791 WCHAR *id;
793 TRACE("%d %p %p %p\n", flow, ids, num, def_index);
795 *num = 1;
796 *def_index = 0;
798 *ids = HeapAlloc(GetProcessHeap(), 0, sizeof(**ids));
799 *keys = NULL;
800 if (!*ids)
801 return E_OUTOFMEMORY;
803 (*ids)[0] = id = HeapAlloc(GetProcessHeap(), 0, sizeof(defaultW));
804 *keys = HeapAlloc(GetProcessHeap(), 0, sizeof(**keys));
805 if (!*keys || !id) {
806 HeapFree(GetProcessHeap(), 0, id);
807 HeapFree(GetProcessHeap(), 0, *keys);
808 HeapFree(GetProcessHeap(), 0, *ids);
809 *ids = NULL;
810 *keys = NULL;
811 return E_OUTOFMEMORY;
813 memcpy(id, defaultW, sizeof(defaultW));
815 if (flow == eRender)
816 (*keys)[0] = pulse_render_guid;
817 else
818 (*keys)[0] = pulse_capture_guid;
820 return S_OK;
823 int WINAPI AUDDRV_GetPriority(void)
825 HRESULT hr;
826 pthread_mutex_lock(&pulse_lock);
827 hr = pulse_test_connect();
828 pthread_mutex_unlock(&pulse_lock);
829 return SUCCEEDED(hr) ? Priority_Low : Priority_Unavailable;
832 HRESULT WINAPI AUDDRV_GetAudioEndpoint(GUID *guid, IMMDevice *dev, IAudioClient **out)
834 ACImpl *This;
835 int i;
836 EDataFlow dataflow;
838 TRACE("%s %p %p\n", debugstr_guid(guid), dev, out);
839 if (IsEqualGUID(guid, &pulse_render_guid))
840 dataflow = eRender;
841 else if (IsEqualGUID(guid, &pulse_capture_guid))
842 dataflow = eCapture;
843 else
844 return E_UNEXPECTED;
846 *out = NULL;
848 This = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*This));
849 if (!This)
850 return E_OUTOFMEMORY;
852 This->IAudioClient_iface.lpVtbl = &AudioClient_Vtbl;
853 This->IAudioRenderClient_iface.lpVtbl = &AudioRenderClient_Vtbl;
854 This->IAudioCaptureClient_iface.lpVtbl = &AudioCaptureClient_Vtbl;
855 This->IAudioClock_iface.lpVtbl = &AudioClock_Vtbl;
856 This->IAudioClock2_iface.lpVtbl = &AudioClock2_Vtbl;
857 This->IAudioStreamVolume_iface.lpVtbl = &AudioStreamVolume_Vtbl;
858 This->dataflow = dataflow;
859 This->parent = dev;
860 for (i = 0; i < PA_CHANNELS_MAX; ++i)
861 This->vol[i] = 1.f;
862 IMMDevice_AddRef(This->parent);
864 *out = &This->IAudioClient_iface;
865 IAudioClient_AddRef(&This->IAudioClient_iface);
867 return S_OK;
870 static HRESULT WINAPI AudioClient_QueryInterface(IAudioClient *iface,
871 REFIID riid, void **ppv)
873 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
875 if (!ppv)
876 return E_POINTER;
877 *ppv = NULL;
878 if (IsEqualIID(riid, &IID_IUnknown) || IsEqualIID(riid, &IID_IAudioClient))
879 *ppv = iface;
880 if (*ppv) {
881 IUnknown_AddRef((IUnknown*)*ppv);
882 return S_OK;
884 WARN("Unknown interface %s\n", debugstr_guid(riid));
885 return E_NOINTERFACE;
888 static ULONG WINAPI AudioClient_AddRef(IAudioClient *iface)
890 ACImpl *This = impl_from_IAudioClient(iface);
891 ULONG ref;
892 ref = InterlockedIncrement(&This->ref);
893 TRACE("(%p) Refcount now %u\n", This, ref);
894 return ref;
897 static ULONG WINAPI AudioClient_Release(IAudioClient *iface)
899 ACImpl *This = impl_from_IAudioClient(iface);
900 ULONG ref;
901 ref = InterlockedDecrement(&This->ref);
902 TRACE("(%p) Refcount now %u\n", This, ref);
903 if (!ref) {
904 if (This->stream) {
905 pthread_mutex_lock(&pulse_lock);
906 if (PA_STREAM_IS_GOOD(pa_stream_get_state(This->stream))) {
907 pa_stream_disconnect(This->stream);
908 while (PA_STREAM_IS_GOOD(pa_stream_get_state(This->stream)))
909 pthread_cond_wait(&pulse_cond, &pulse_lock);
911 pa_stream_unref(This->stream);
912 This->stream = NULL;
913 list_remove(&This->entry);
914 pthread_mutex_unlock(&pulse_lock);
916 IMMDevice_Release(This->parent);
917 HeapFree(GetProcessHeap(), 0, This->tmp_buffer);
918 HeapFree(GetProcessHeap(), 0, This);
920 return ref;
923 static void dump_fmt(const WAVEFORMATEX *fmt)
925 TRACE("wFormatTag: 0x%x (", fmt->wFormatTag);
926 switch(fmt->wFormatTag) {
927 case WAVE_FORMAT_PCM:
928 TRACE("WAVE_FORMAT_PCM");
929 break;
930 case WAVE_FORMAT_IEEE_FLOAT:
931 TRACE("WAVE_FORMAT_IEEE_FLOAT");
932 break;
933 case WAVE_FORMAT_EXTENSIBLE:
934 TRACE("WAVE_FORMAT_EXTENSIBLE");
935 break;
936 default:
937 TRACE("Unknown");
938 break;
940 TRACE(")\n");
942 TRACE("nChannels: %u\n", fmt->nChannels);
943 TRACE("nSamplesPerSec: %u\n", fmt->nSamplesPerSec);
944 TRACE("nAvgBytesPerSec: %u\n", fmt->nAvgBytesPerSec);
945 TRACE("nBlockAlign: %u\n", fmt->nBlockAlign);
946 TRACE("wBitsPerSample: %u\n", fmt->wBitsPerSample);
947 TRACE("cbSize: %u\n", fmt->cbSize);
949 if (fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
950 WAVEFORMATEXTENSIBLE *fmtex = (void*)fmt;
951 TRACE("dwChannelMask: %08x\n", fmtex->dwChannelMask);
952 TRACE("Samples: %04x\n", fmtex->Samples.wReserved);
953 TRACE("SubFormat: %s\n", wine_dbgstr_guid(&fmtex->SubFormat));
957 static WAVEFORMATEX *clone_format(const WAVEFORMATEX *fmt)
959 WAVEFORMATEX *ret;
960 size_t size;
962 if (fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE)
963 size = sizeof(WAVEFORMATEXTENSIBLE);
964 else
965 size = sizeof(WAVEFORMATEX);
967 ret = CoTaskMemAlloc(size);
968 if (!ret)
969 return NULL;
971 memcpy(ret, fmt, size);
973 ret->cbSize = size - sizeof(WAVEFORMATEX);
975 return ret;
978 static DWORD get_channel_mask(unsigned int channels)
980 switch(channels) {
981 case 0:
982 return 0;
983 case 1:
984 return KSAUDIO_SPEAKER_MONO;
985 case 2:
986 return KSAUDIO_SPEAKER_STEREO;
987 case 3:
988 return KSAUDIO_SPEAKER_STEREO | SPEAKER_LOW_FREQUENCY;
989 case 4:
990 return KSAUDIO_SPEAKER_QUAD; /* not _SURROUND */
991 case 5:
992 return KSAUDIO_SPEAKER_QUAD | SPEAKER_LOW_FREQUENCY;
993 case 6:
994 return KSAUDIO_SPEAKER_5POINT1; /* not 5POINT1_SURROUND */
995 case 7:
996 return KSAUDIO_SPEAKER_5POINT1 | SPEAKER_BACK_CENTER;
997 case 8:
998 return KSAUDIO_SPEAKER_7POINT1_SURROUND; /* Vista deprecates 7POINT1 */
1000 FIXME("Unknown speaker configuration: %u\n", channels);
1001 return 0;
1004 static void session_init_vols(AudioSession *session, UINT channels)
1006 if (session->channel_count < channels) {
1007 UINT i;
1009 if (session->channel_vols)
1010 session->channel_vols = HeapReAlloc(GetProcessHeap(), 0,
1011 session->channel_vols, sizeof(float) * channels);
1012 else
1013 session->channel_vols = HeapAlloc(GetProcessHeap(), 0,
1014 sizeof(float) * channels);
1015 if (!session->channel_vols)
1016 return;
1018 for(i = session->channel_count; i < channels; ++i)
1019 session->channel_vols[i] = 1.f;
1021 session->channel_count = channels;
1025 static AudioSession *create_session(const GUID *guid, IMMDevice *device,
1026 UINT num_channels)
1028 AudioSession *ret;
1030 ret = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(AudioSession));
1031 if (!ret)
1032 return NULL;
1034 memcpy(&ret->guid, guid, sizeof(GUID));
1036 ret->device = device;
1038 list_init(&ret->clients);
1040 list_add_head(&g_sessions, &ret->entry);
1042 session_init_vols(ret, num_channels);
1044 ret->master_vol = 1.f;
1046 return ret;
1049 /* if channels == 0, then this will return or create a session with
1050 * matching dataflow and GUID. otherwise, channels must also match */
1051 static HRESULT get_audio_session(const GUID *sessionguid,
1052 IMMDevice *device, UINT channels, AudioSession **out)
1054 AudioSession *session;
1056 if (!sessionguid || IsEqualGUID(sessionguid, &GUID_NULL)) {
1057 *out = create_session(&GUID_NULL, device, channels);
1058 if (!*out)
1059 return E_OUTOFMEMORY;
1061 return S_OK;
1064 *out = NULL;
1065 LIST_FOR_EACH_ENTRY(session, &g_sessions, AudioSession, entry) {
1066 if (session->device == device &&
1067 IsEqualGUID(sessionguid, &session->guid)) {
1068 session_init_vols(session, channels);
1069 *out = session;
1070 break;
1074 if (!*out) {
1075 *out = create_session(sessionguid, device, channels);
1076 if (!*out)
1077 return E_OUTOFMEMORY;
1080 return S_OK;
1083 static HRESULT pulse_spec_from_waveformat(ACImpl *This, const WAVEFORMATEX *fmt)
1085 pa_channel_map_init(&This->map);
1086 This->ss.rate = fmt->nSamplesPerSec;
1087 This->ss.format = PA_SAMPLE_INVALID;
1089 switch(fmt->wFormatTag) {
1090 case WAVE_FORMAT_IEEE_FLOAT:
1091 if (!fmt->nChannels || fmt->nChannels > 2 || fmt->wBitsPerSample != 32)
1092 break;
1093 This->ss.format = PA_SAMPLE_FLOAT32LE;
1094 pa_channel_map_init_auto(&This->map, fmt->nChannels, PA_CHANNEL_MAP_ALSA);
1095 break;
1096 case WAVE_FORMAT_PCM:
1097 if (!fmt->nChannels || fmt->nChannels > 2)
1098 break;
1099 if (fmt->wBitsPerSample == 8)
1100 This->ss.format = PA_SAMPLE_U8;
1101 else if (fmt->wBitsPerSample == 16)
1102 This->ss.format = PA_SAMPLE_S16LE;
1103 else
1104 return AUDCLNT_E_UNSUPPORTED_FORMAT;
1105 pa_channel_map_init_auto(&This->map, fmt->nChannels, PA_CHANNEL_MAP_ALSA);
1106 break;
1107 case WAVE_FORMAT_EXTENSIBLE: {
1108 WAVEFORMATEXTENSIBLE *wfe = (WAVEFORMATEXTENSIBLE*)fmt;
1109 DWORD mask = wfe->dwChannelMask;
1110 DWORD i = 0, j;
1111 if (fmt->cbSize != (sizeof(*wfe) - sizeof(*fmt)) && fmt->cbSize != sizeof(*wfe))
1112 break;
1113 if (IsEqualGUID(&wfe->SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT) &&
1114 (!wfe->Samples.wValidBitsPerSample || wfe->Samples.wValidBitsPerSample == 32) &&
1115 fmt->wBitsPerSample == 32)
1116 This->ss.format = PA_SAMPLE_FLOAT32LE;
1117 else if (IsEqualGUID(&wfe->SubFormat, &KSDATAFORMAT_SUBTYPE_PCM)) {
1118 DWORD valid = wfe->Samples.wValidBitsPerSample;
1119 if (!valid)
1120 valid = fmt->wBitsPerSample;
1121 if (!valid || valid > fmt->wBitsPerSample)
1122 break;
1123 switch (fmt->wBitsPerSample) {
1124 case 8:
1125 if (valid == 8)
1126 This->ss.format = PA_SAMPLE_U8;
1127 break;
1128 case 16:
1129 if (valid == 16)
1130 This->ss.format = PA_SAMPLE_S16LE;
1131 break;
1132 case 24:
1133 if (valid == 24)
1134 This->ss.format = PA_SAMPLE_S24LE;
1135 break;
1136 case 32:
1137 if (valid == 24)
1138 This->ss.format = PA_SAMPLE_S24_32LE;
1139 else if (valid == 32)
1140 This->ss.format = PA_SAMPLE_S32LE;
1141 break;
1142 default:
1143 return AUDCLNT_E_UNSUPPORTED_FORMAT;
1146 This->map.channels = fmt->nChannels;
1147 if (!mask || (mask & (SPEAKER_ALL|SPEAKER_RESERVED)))
1148 mask = get_channel_mask(fmt->nChannels);
1149 for (j = 0; j < sizeof(pulse_pos_from_wfx)/sizeof(*pulse_pos_from_wfx) && i < fmt->nChannels; ++j) {
1150 if (mask & (1 << j))
1151 This->map.map[i++] = pulse_pos_from_wfx[j];
1154 /* Special case for mono since pulse appears to map it differently */
1155 if (mask == SPEAKER_FRONT_CENTER)
1156 This->map.map[0] = PA_CHANNEL_POSITION_MONO;
1158 if (i < fmt->nChannels || (mask & SPEAKER_RESERVED)) {
1159 This->map.channels = 0;
1160 ERR("Invalid channel mask: %i/%i and %x(%x)\n", i, fmt->nChannels, mask, wfe->dwChannelMask);
1161 break;
1163 break;
1165 case WAVE_FORMAT_ALAW:
1166 case WAVE_FORMAT_MULAW:
1167 if (fmt->wBitsPerSample != 8) {
1168 FIXME("Unsupported bpp %u for LAW\n", fmt->wBitsPerSample);
1169 return AUDCLNT_E_UNSUPPORTED_FORMAT;
1171 if (fmt->nChannels != 1 && fmt->nChannels != 2) {
1172 FIXME("Unsupported channels %u for LAW\n", fmt->nChannels);
1173 return AUDCLNT_E_UNSUPPORTED_FORMAT;
1175 This->ss.format = fmt->wFormatTag == WAVE_FORMAT_MULAW ? PA_SAMPLE_ULAW : PA_SAMPLE_ALAW;
1176 pa_channel_map_init_auto(&This->map, fmt->nChannels, PA_CHANNEL_MAP_ALSA);
1177 break;
1178 default:
1179 WARN("Unhandled tag %x\n", fmt->wFormatTag);
1180 return AUDCLNT_E_UNSUPPORTED_FORMAT;
1182 This->ss.channels = This->map.channels;
1183 if (!pa_channel_map_valid(&This->map) || This->ss.format == PA_SAMPLE_INVALID) {
1184 ERR("Invalid format! Channel spec valid: %i, format: %i\n", pa_channel_map_valid(&This->map), This->ss.format);
1185 return AUDCLNT_E_UNSUPPORTED_FORMAT;
1187 return S_OK;
1190 static HRESULT WINAPI AudioClient_Initialize(IAudioClient *iface,
1191 AUDCLNT_SHAREMODE mode, DWORD flags, REFERENCE_TIME duration,
1192 REFERENCE_TIME period, const WAVEFORMATEX *fmt,
1193 const GUID *sessionguid)
1195 ACImpl *This = impl_from_IAudioClient(iface);
1196 HRESULT hr = S_OK;
1197 UINT period_bytes;
1199 TRACE("(%p)->(%x, %x, %s, %s, %p, %s)\n", This, mode, flags,
1200 wine_dbgstr_longlong(duration), wine_dbgstr_longlong(period), fmt, debugstr_guid(sessionguid));
1202 if (!fmt)
1203 return E_POINTER;
1205 if (mode != AUDCLNT_SHAREMODE_SHARED && mode != AUDCLNT_SHAREMODE_EXCLUSIVE)
1206 return AUDCLNT_E_NOT_INITIALIZED;
1207 if (mode == AUDCLNT_SHAREMODE_EXCLUSIVE)
1208 return AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED;
1210 if (flags & ~(AUDCLNT_STREAMFLAGS_CROSSPROCESS |
1211 AUDCLNT_STREAMFLAGS_LOOPBACK |
1212 AUDCLNT_STREAMFLAGS_EVENTCALLBACK |
1213 AUDCLNT_STREAMFLAGS_NOPERSIST |
1214 AUDCLNT_STREAMFLAGS_RATEADJUST |
1215 AUDCLNT_SESSIONFLAGS_EXPIREWHENUNOWNED |
1216 AUDCLNT_SESSIONFLAGS_DISPLAY_HIDE |
1217 AUDCLNT_SESSIONFLAGS_DISPLAY_HIDEWHENEXPIRED)) {
1218 TRACE("Unknown flags: %08x\n", flags);
1219 return E_INVALIDARG;
1222 pthread_mutex_lock(&pulse_lock);
1224 hr = pulse_connect();
1225 if (FAILED(hr)) {
1226 pthread_mutex_unlock(&pulse_lock);
1227 return hr;
1230 if (This->stream) {
1231 pthread_mutex_unlock(&pulse_lock);
1232 return AUDCLNT_E_ALREADY_INITIALIZED;
1235 hr = pulse_spec_from_waveformat(This, fmt);
1236 TRACE("Obtaining format returns %08x\n", hr);
1237 dump_fmt(fmt);
1239 if (FAILED(hr))
1240 goto exit;
1242 if (mode == AUDCLNT_SHAREMODE_SHARED) {
1243 REFERENCE_TIME def = pulse_def_period[This->dataflow == eCapture];
1244 REFERENCE_TIME min = pulse_min_period[This->dataflow == eCapture];
1246 /* Switch to low latency mode if below 2 default periods,
1247 * which is 20 ms by default, this will increase the amount
1248 * of interrupts but allows very low latency. In dsound I
1249 * managed to get a total latency of ~8ms, which is well below
1250 * default
1252 if (duration < 2 * def)
1253 period = min;
1254 else
1255 period = def;
1256 if (duration < 2 * period)
1257 duration = 2 * period;
1259 /* Uh oh, really low latency requested.. */
1260 if (duration <= 2 * period)
1261 period /= 2;
1263 period_bytes = pa_frame_size(&This->ss) * MulDiv(period, This->ss.rate, 10000000);
1265 if (duration < 20000000)
1266 This->bufsize_frames = ceil((duration / 10000000.) * fmt->nSamplesPerSec);
1267 else
1268 This->bufsize_frames = 2 * fmt->nSamplesPerSec;
1269 This->bufsize_bytes = This->bufsize_frames * pa_frame_size(&This->ss);
1271 This->share = mode;
1272 This->flags = flags;
1273 hr = pulse_stream_connect(This, period_bytes);
1274 if (SUCCEEDED(hr)) {
1275 UINT32 unalign;
1276 const pa_buffer_attr *attr = pa_stream_get_buffer_attr(This->stream);
1277 /* Update frames according to new size */
1278 dump_attr(attr);
1279 if (This->dataflow == eRender)
1280 This->bufsize_bytes = attr->tlength;
1281 else {
1282 This->capture_period = period_bytes = attr->fragsize;
1283 if ((unalign = This->bufsize_bytes % period_bytes))
1284 This->bufsize_bytes += period_bytes - unalign;
1286 This->bufsize_frames = This->bufsize_bytes / pa_frame_size(&This->ss);
1288 if (SUCCEEDED(hr)) {
1289 UINT32 i, capture_packets = This->capture_period ? This->bufsize_bytes / This->capture_period : 0;
1290 This->tmp_buffer = HeapAlloc(GetProcessHeap(), 0, This->bufsize_bytes + capture_packets * sizeof(ACPacket));
1291 if (!This->tmp_buffer)
1292 hr = E_OUTOFMEMORY;
1293 else {
1294 ACPacket *cur_packet = (ACPacket*)((char*)This->tmp_buffer + This->bufsize_bytes);
1295 BYTE *data = This->tmp_buffer;
1296 memset(This->tmp_buffer, This->ss.format == PA_SAMPLE_U8 ? 0x80 : 0, This->bufsize_bytes);
1297 list_init(&This->packet_free_head);
1298 list_init(&This->packet_filled_head);
1299 for (i = 0; i < capture_packets; ++i, ++cur_packet) {
1300 list_add_tail(&This->packet_free_head, &cur_packet->entry);
1301 cur_packet->data = data;
1302 data += This->capture_period;
1304 assert(!This->capture_period || This->bufsize_bytes == This->capture_period * capture_packets);
1305 assert(!capture_packets || data - This->bufsize_bytes == This->tmp_buffer);
1308 if (SUCCEEDED(hr))
1309 hr = get_audio_session(sessionguid, This->parent, fmt->nChannels, &This->session);
1310 if (SUCCEEDED(hr))
1311 list_add_tail(&This->session->clients, &This->entry);
1313 exit:
1314 if (FAILED(hr)) {
1315 HeapFree(GetProcessHeap(), 0, This->tmp_buffer);
1316 This->tmp_buffer = NULL;
1317 if (This->stream) {
1318 pa_stream_disconnect(This->stream);
1319 pa_stream_unref(This->stream);
1320 This->stream = NULL;
1323 pthread_mutex_unlock(&pulse_lock);
1324 return hr;
1327 static HRESULT WINAPI AudioClient_GetBufferSize(IAudioClient *iface,
1328 UINT32 *out)
1330 ACImpl *This = impl_from_IAudioClient(iface);
1331 HRESULT hr;
1333 TRACE("(%p)->(%p)\n", This, out);
1335 if (!out)
1336 return E_POINTER;
1338 pthread_mutex_lock(&pulse_lock);
1339 hr = pulse_stream_valid(This);
1340 if (SUCCEEDED(hr))
1341 *out = This->bufsize_frames;
1342 pthread_mutex_unlock(&pulse_lock);
1344 return hr;
1347 static HRESULT WINAPI AudioClient_GetStreamLatency(IAudioClient *iface,
1348 REFERENCE_TIME *latency)
1350 ACImpl *This = impl_from_IAudioClient(iface);
1351 const pa_buffer_attr *attr;
1352 REFERENCE_TIME lat;
1353 HRESULT hr;
1355 TRACE("(%p)->(%p)\n", This, latency);
1357 if (!latency)
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;
1366 attr = pa_stream_get_buffer_attr(This->stream);
1367 if (This->dataflow == eRender)
1368 lat = attr->minreq / pa_frame_size(&This->ss);
1369 else
1370 lat = attr->fragsize / pa_frame_size(&This->ss);
1371 *latency = 10000000;
1372 *latency *= lat;
1373 *latency /= This->ss.rate;
1374 pthread_mutex_unlock(&pulse_lock);
1375 TRACE("Latency: %u ms\n", (DWORD)(*latency / 10000));
1376 return S_OK;
1379 static void ACImpl_GetRenderPad(ACImpl *This, UINT32 *out)
1381 *out = This->pad / pa_frame_size(&This->ss);
1384 static void ACImpl_GetCapturePad(ACImpl *This, UINT32 *out)
1386 ACPacket *packet = This->locked_ptr;
1387 if (!packet && !list_empty(&This->packet_filled_head)) {
1388 packet = (ACPacket*)list_head(&This->packet_filled_head);
1389 This->locked_ptr = packet;
1390 list_remove(&packet->entry);
1392 if (out)
1393 *out = This->pad / pa_frame_size(&This->ss);
1396 static HRESULT WINAPI AudioClient_GetCurrentPadding(IAudioClient *iface,
1397 UINT32 *out)
1399 ACImpl *This = impl_from_IAudioClient(iface);
1400 HRESULT hr;
1402 TRACE("(%p)->(%p)\n", This, out);
1404 if (!out)
1405 return E_POINTER;
1407 pthread_mutex_lock(&pulse_lock);
1408 hr = pulse_stream_valid(This);
1409 if (FAILED(hr)) {
1410 pthread_mutex_unlock(&pulse_lock);
1411 return hr;
1414 if (This->dataflow == eRender)
1415 ACImpl_GetRenderPad(This, out);
1416 else
1417 ACImpl_GetCapturePad(This, out);
1418 pthread_mutex_unlock(&pulse_lock);
1420 TRACE("%p Pad: %u ms (%u)\n", This, MulDiv(*out, 1000, This->ss.rate), *out);
1421 return S_OK;
1424 static HRESULT WINAPI AudioClient_IsFormatSupported(IAudioClient *iface,
1425 AUDCLNT_SHAREMODE mode, const WAVEFORMATEX *fmt,
1426 WAVEFORMATEX **out)
1428 ACImpl *This = impl_from_IAudioClient(iface);
1429 HRESULT hr = S_OK;
1430 WAVEFORMATEX *closest = NULL;
1431 BOOL exclusive;
1433 TRACE("(%p)->(%x, %p, %p)\n", This, mode, fmt, out);
1435 if (!fmt)
1436 return E_POINTER;
1438 if (out)
1439 *out = NULL;
1441 if (mode == AUDCLNT_SHAREMODE_EXCLUSIVE) {
1442 exclusive = 1;
1443 out = NULL;
1444 } else if (mode == AUDCLNT_SHAREMODE_SHARED) {
1445 exclusive = 0;
1446 if (!out)
1447 return E_POINTER;
1448 } else
1449 return E_INVALIDARG;
1451 if (fmt->nChannels == 0)
1452 return AUDCLNT_E_UNSUPPORTED_FORMAT;
1454 closest = clone_format(fmt);
1455 if (!closest)
1456 return E_OUTOFMEMORY;
1458 dump_fmt(fmt);
1460 switch (fmt->wFormatTag) {
1461 case WAVE_FORMAT_EXTENSIBLE: {
1462 WAVEFORMATEXTENSIBLE *ext = (WAVEFORMATEXTENSIBLE*)closest;
1464 if ((fmt->cbSize != sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX) &&
1465 fmt->cbSize != sizeof(WAVEFORMATEXTENSIBLE)) ||
1466 fmt->nBlockAlign != fmt->wBitsPerSample / 8 * fmt->nChannels ||
1467 ext->Samples.wValidBitsPerSample > fmt->wBitsPerSample ||
1468 fmt->nAvgBytesPerSec != fmt->nBlockAlign * fmt->nSamplesPerSec) {
1469 hr = E_INVALIDARG;
1470 break;
1473 if (exclusive) {
1474 UINT32 mask = 0, i, channels = 0;
1476 if (!(ext->dwChannelMask & (SPEAKER_ALL | SPEAKER_RESERVED))) {
1477 for (i = 1; !(i & SPEAKER_RESERVED); i <<= 1) {
1478 if (i & ext->dwChannelMask) {
1479 mask |= i;
1480 channels++;
1484 if (channels != fmt->nChannels || (ext->dwChannelMask & ~mask)) {
1485 hr = AUDCLNT_E_UNSUPPORTED_FORMAT;
1486 break;
1488 } else {
1489 hr = AUDCLNT_E_UNSUPPORTED_FORMAT;
1490 break;
1494 if (IsEqualGUID(&ext->SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT)) {
1495 if (fmt->wBitsPerSample != 32) {
1496 hr = E_INVALIDARG;
1497 break;
1500 if (ext->Samples.wValidBitsPerSample != fmt->wBitsPerSample) {
1501 hr = S_FALSE;
1502 ext->Samples.wValidBitsPerSample = fmt->wBitsPerSample;
1504 } else if (IsEqualGUID(&ext->SubFormat, &KSDATAFORMAT_SUBTYPE_PCM)) {
1505 if (!fmt->wBitsPerSample || fmt->wBitsPerSample > 32 || fmt->wBitsPerSample % 8) {
1506 hr = E_INVALIDARG;
1507 break;
1510 if (ext->Samples.wValidBitsPerSample != fmt->wBitsPerSample &&
1511 !(fmt->wBitsPerSample == 32 &&
1512 ext->Samples.wValidBitsPerSample == 24)) {
1513 hr = S_FALSE;
1514 ext->Samples.wValidBitsPerSample = fmt->wBitsPerSample;
1515 break;
1517 } else {
1518 hr = AUDCLNT_E_UNSUPPORTED_FORMAT;
1519 break;
1522 break;
1525 case WAVE_FORMAT_ALAW:
1526 case WAVE_FORMAT_MULAW:
1527 if (fmt->wBitsPerSample != 8) {
1528 hr = E_INVALIDARG;
1529 break;
1531 /* Fall-through */
1532 case WAVE_FORMAT_IEEE_FLOAT:
1533 if (fmt->wFormatTag == WAVE_FORMAT_IEEE_FLOAT && fmt->wBitsPerSample != 32) {
1534 hr = E_INVALIDARG;
1535 break;
1537 /* Fall-through */
1538 case WAVE_FORMAT_PCM:
1539 if (fmt->wFormatTag == WAVE_FORMAT_PCM &&
1540 (!fmt->wBitsPerSample || fmt->wBitsPerSample > 32 || fmt->wBitsPerSample % 8)) {
1541 hr = E_INVALIDARG;
1542 break;
1545 if (fmt->nChannels > 2) {
1546 hr = AUDCLNT_E_UNSUPPORTED_FORMAT;
1547 break;
1550 * fmt->cbSize, fmt->nBlockAlign and fmt->nAvgBytesPerSec seem to be
1551 * ignored, invalid values are happily accepted.
1553 break;
1554 default:
1555 hr = AUDCLNT_E_UNSUPPORTED_FORMAT;
1556 break;
1559 if (exclusive && hr != S_OK) {
1560 hr = AUDCLNT_E_UNSUPPORTED_FORMAT;
1561 CoTaskMemFree(closest);
1562 } else if (hr != S_FALSE)
1563 CoTaskMemFree(closest);
1564 else
1565 *out = closest;
1567 /* Winepulse does not currently support exclusive mode, if you know of an
1568 * application that uses it, I will correct this..
1570 if (hr == S_OK && exclusive)
1571 return This->dataflow == eCapture ? AUDCLNT_E_UNSUPPORTED_FORMAT : AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED;
1573 TRACE("returning: %08x %p\n", hr, out ? *out : NULL);
1574 return hr;
1577 static HRESULT WINAPI AudioClient_GetMixFormat(IAudioClient *iface,
1578 WAVEFORMATEX **pwfx)
1580 ACImpl *This = impl_from_IAudioClient(iface);
1581 WAVEFORMATEXTENSIBLE *fmt = &pulse_fmt[This->dataflow == eCapture];
1583 TRACE("(%p)->(%p)\n", This, pwfx);
1585 if (!pwfx)
1586 return E_POINTER;
1588 *pwfx = clone_format(&fmt->Format);
1589 if (!*pwfx)
1590 return E_OUTOFMEMORY;
1591 dump_fmt(*pwfx);
1592 return S_OK;
1595 static HRESULT WINAPI AudioClient_GetDevicePeriod(IAudioClient *iface,
1596 REFERENCE_TIME *defperiod, REFERENCE_TIME *minperiod)
1598 ACImpl *This = impl_from_IAudioClient(iface);
1600 TRACE("(%p)->(%p, %p)\n", This, defperiod, minperiod);
1602 if (!defperiod && !minperiod)
1603 return E_POINTER;
1605 if (defperiod)
1606 *defperiod = pulse_def_period[This->dataflow == eCapture];
1607 if (minperiod)
1608 *minperiod = pulse_min_period[This->dataflow == eCapture];
1610 return S_OK;
1613 static HRESULT WINAPI AudioClient_Start(IAudioClient *iface)
1615 ACImpl *This = impl_from_IAudioClient(iface);
1616 HRESULT hr = S_OK;
1617 int success;
1618 pa_operation *o;
1620 TRACE("(%p)\n", This);
1622 pthread_mutex_lock(&pulse_lock);
1623 hr = pulse_stream_valid(This);
1624 if (FAILED(hr)) {
1625 pthread_mutex_unlock(&pulse_lock);
1626 return hr;
1629 if ((This->flags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK) && !This->event) {
1630 pthread_mutex_unlock(&pulse_lock);
1631 return AUDCLNT_E_EVENTHANDLE_NOT_SET;
1634 if (This->started) {
1635 pthread_mutex_unlock(&pulse_lock);
1636 return AUDCLNT_E_NOT_STOPPED;
1639 if (pa_stream_is_corked(This->stream)) {
1640 o = pa_stream_cork(This->stream, 0, pulse_op_cb, &success);
1641 if (o) {
1642 while(pa_operation_get_state(o) == PA_OPERATION_RUNNING)
1643 pthread_cond_wait(&pulse_cond, &pulse_lock);
1644 pa_operation_unref(o);
1645 } else
1646 success = 0;
1647 if (!success)
1648 hr = E_FAIL;
1650 if (SUCCEEDED(hr)) {
1651 This->started = TRUE;
1652 if (This->dataflow == eRender && This->event)
1653 pa_stream_set_latency_update_callback(This->stream, pulse_latency_callback, This);
1655 pthread_mutex_unlock(&pulse_lock);
1656 return hr;
1659 static HRESULT WINAPI AudioClient_Stop(IAudioClient *iface)
1661 ACImpl *This = impl_from_IAudioClient(iface);
1662 HRESULT hr = S_OK;
1663 pa_operation *o;
1664 int success;
1666 TRACE("(%p)\n", This);
1668 pthread_mutex_lock(&pulse_lock);
1669 hr = pulse_stream_valid(This);
1670 if (FAILED(hr)) {
1671 pthread_mutex_unlock(&pulse_lock);
1672 return hr;
1675 if (!This->started) {
1676 pthread_mutex_unlock(&pulse_lock);
1677 return S_FALSE;
1680 if (This->dataflow == eRender) {
1681 o = pa_stream_cork(This->stream, 1, pulse_op_cb, &success);
1682 if (o) {
1683 while(pa_operation_get_state(o) == PA_OPERATION_RUNNING)
1684 pthread_cond_wait(&pulse_cond, &pulse_lock);
1685 pa_operation_unref(o);
1686 } else
1687 success = 0;
1688 if (!success)
1689 hr = E_FAIL;
1691 if (SUCCEEDED(hr)) {
1692 This->started = FALSE;
1694 pthread_mutex_unlock(&pulse_lock);
1695 return hr;
1698 static HRESULT WINAPI AudioClient_Reset(IAudioClient *iface)
1700 ACImpl *This = impl_from_IAudioClient(iface);
1701 HRESULT hr = S_OK;
1703 TRACE("(%p)\n", This);
1705 pthread_mutex_lock(&pulse_lock);
1706 hr = pulse_stream_valid(This);
1707 if (FAILED(hr)) {
1708 pthread_mutex_unlock(&pulse_lock);
1709 return hr;
1712 if (This->started) {
1713 pthread_mutex_unlock(&pulse_lock);
1714 return AUDCLNT_E_NOT_STOPPED;
1717 if (This->locked) {
1718 pthread_mutex_unlock(&pulse_lock);
1719 return AUDCLNT_E_BUFFER_OPERATION_PENDING;
1722 if (This->dataflow == eRender) {
1723 /* If there is still data in the render buffer it needs to be removed from the server */
1724 int success = 0;
1725 if (This->pad) {
1726 pa_operation *o = pa_stream_flush(This->stream, pulse_op_cb, &success);
1727 if (o) {
1728 while(pa_operation_get_state(o) == PA_OPERATION_RUNNING)
1729 pthread_cond_wait(&pulse_cond, &pulse_lock);
1730 pa_operation_unref(o);
1733 if (success || !This->pad)
1734 This->clock_lastpos = This->clock_written = This->pad = 0;
1735 } else {
1736 ACPacket *p;
1737 This->clock_written += This->pad;
1738 This->pad = 0;
1740 if ((p = This->locked_ptr)) {
1741 This->locked_ptr = NULL;
1742 list_add_tail(&This->packet_free_head, &p->entry);
1744 list_move_tail(&This->packet_free_head, &This->packet_filled_head);
1746 pthread_mutex_unlock(&pulse_lock);
1748 return hr;
1751 static HRESULT WINAPI AudioClient_SetEventHandle(IAudioClient *iface,
1752 HANDLE event)
1754 ACImpl *This = impl_from_IAudioClient(iface);
1755 HRESULT hr;
1757 TRACE("(%p)->(%p)\n", This, event);
1759 if (!event)
1760 return E_INVALIDARG;
1762 pthread_mutex_lock(&pulse_lock);
1763 hr = pulse_stream_valid(This);
1764 if (FAILED(hr)) {
1765 pthread_mutex_unlock(&pulse_lock);
1766 return hr;
1769 if (!(This->flags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK))
1770 hr = AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED;
1771 else if (This->event)
1772 hr = HRESULT_FROM_WIN32(ERROR_INVALID_NAME);
1773 else
1774 This->event = event;
1775 pthread_mutex_unlock(&pulse_lock);
1776 return hr;
1779 static HRESULT WINAPI AudioClient_GetService(IAudioClient *iface, REFIID riid,
1780 void **ppv)
1782 ACImpl *This = impl_from_IAudioClient(iface);
1783 HRESULT hr;
1785 TRACE("(%p)->(%s, %p)\n", This, debugstr_guid(riid), ppv);
1787 if (!ppv)
1788 return E_POINTER;
1789 *ppv = NULL;
1791 pthread_mutex_lock(&pulse_lock);
1792 hr = pulse_stream_valid(This);
1793 pthread_mutex_unlock(&pulse_lock);
1794 if (FAILED(hr))
1795 return hr;
1797 if (IsEqualIID(riid, &IID_IAudioRenderClient)) {
1798 if (This->dataflow != eRender)
1799 return AUDCLNT_E_WRONG_ENDPOINT_TYPE;
1800 *ppv = &This->IAudioRenderClient_iface;
1801 } else if (IsEqualIID(riid, &IID_IAudioCaptureClient)) {
1802 if (This->dataflow != eCapture)
1803 return AUDCLNT_E_WRONG_ENDPOINT_TYPE;
1804 *ppv = &This->IAudioCaptureClient_iface;
1805 } else if (IsEqualIID(riid, &IID_IAudioClock)) {
1806 *ppv = &This->IAudioClock_iface;
1807 } else if (IsEqualIID(riid, &IID_IAudioStreamVolume)) {
1808 *ppv = &This->IAudioStreamVolume_iface;
1809 } else if (IsEqualIID(riid, &IID_IAudioSessionControl) ||
1810 IsEqualIID(riid, &IID_IChannelAudioVolume) ||
1811 IsEqualIID(riid, &IID_ISimpleAudioVolume)) {
1812 if (!This->session_wrapper) {
1813 This->session_wrapper = AudioSessionWrapper_Create(This);
1814 if (!This->session_wrapper)
1815 return E_OUTOFMEMORY;
1817 if (IsEqualIID(riid, &IID_IAudioSessionControl))
1818 *ppv = &This->session_wrapper->IAudioSessionControl2_iface;
1819 else if (IsEqualIID(riid, &IID_IChannelAudioVolume))
1820 *ppv = &This->session_wrapper->IChannelAudioVolume_iface;
1821 else if (IsEqualIID(riid, &IID_ISimpleAudioVolume))
1822 *ppv = &This->session_wrapper->ISimpleAudioVolume_iface;
1825 if (*ppv) {
1826 IUnknown_AddRef((IUnknown*)*ppv);
1827 return S_OK;
1830 FIXME("stub %s\n", debugstr_guid(riid));
1831 return E_NOINTERFACE;
1834 static const IAudioClientVtbl AudioClient_Vtbl =
1836 AudioClient_QueryInterface,
1837 AudioClient_AddRef,
1838 AudioClient_Release,
1839 AudioClient_Initialize,
1840 AudioClient_GetBufferSize,
1841 AudioClient_GetStreamLatency,
1842 AudioClient_GetCurrentPadding,
1843 AudioClient_IsFormatSupported,
1844 AudioClient_GetMixFormat,
1845 AudioClient_GetDevicePeriod,
1846 AudioClient_Start,
1847 AudioClient_Stop,
1848 AudioClient_Reset,
1849 AudioClient_SetEventHandle,
1850 AudioClient_GetService
1853 static HRESULT WINAPI AudioRenderClient_QueryInterface(
1854 IAudioRenderClient *iface, REFIID riid, void **ppv)
1856 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
1858 if (!ppv)
1859 return E_POINTER;
1860 *ppv = NULL;
1862 if (IsEqualIID(riid, &IID_IUnknown) ||
1863 IsEqualIID(riid, &IID_IAudioRenderClient))
1864 *ppv = iface;
1865 if (*ppv) {
1866 IUnknown_AddRef((IUnknown*)*ppv);
1867 return S_OK;
1870 WARN("Unknown interface %s\n", debugstr_guid(riid));
1871 return E_NOINTERFACE;
1874 static ULONG WINAPI AudioRenderClient_AddRef(IAudioRenderClient *iface)
1876 ACImpl *This = impl_from_IAudioRenderClient(iface);
1877 return AudioClient_AddRef(&This->IAudioClient_iface);
1880 static ULONG WINAPI AudioRenderClient_Release(IAudioRenderClient *iface)
1882 ACImpl *This = impl_from_IAudioRenderClient(iface);
1883 return AudioClient_Release(&This->IAudioClient_iface);
1886 static HRESULT WINAPI AudioRenderClient_GetBuffer(IAudioRenderClient *iface,
1887 UINT32 frames, BYTE **data)
1889 ACImpl *This = impl_from_IAudioRenderClient(iface);
1890 size_t avail, req, bytes = frames * pa_frame_size(&This->ss);
1891 UINT32 pad;
1892 HRESULT hr = S_OK;
1893 int ret = -1;
1895 TRACE("(%p)->(%u, %p)\n", This, frames, data);
1897 if (!data)
1898 return E_POINTER;
1899 *data = NULL;
1901 pthread_mutex_lock(&pulse_lock);
1902 hr = pulse_stream_valid(This);
1903 if (FAILED(hr) || This->locked) {
1904 pthread_mutex_unlock(&pulse_lock);
1905 return FAILED(hr) ? hr : AUDCLNT_E_OUT_OF_ORDER;
1907 if (!frames) {
1908 pthread_mutex_unlock(&pulse_lock);
1909 return S_OK;
1912 ACImpl_GetRenderPad(This, &pad);
1913 avail = This->bufsize_frames - pad;
1914 if (avail < frames || bytes > This->bufsize_bytes) {
1915 pthread_mutex_unlock(&pulse_lock);
1916 WARN("Wanted to write %u, but only %zu available\n", frames, avail);
1917 return AUDCLNT_E_BUFFER_TOO_LARGE;
1920 This->locked = frames;
1921 req = bytes;
1922 ret = pa_stream_begin_write(This->stream, &This->locked_ptr, &req);
1923 if (ret < 0 || req < bytes) {
1924 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);
1925 if (ret >= 0)
1926 pa_stream_cancel_write(This->stream);
1927 *data = This->tmp_buffer;
1928 This->locked_ptr = NULL;
1929 } else
1930 *data = This->locked_ptr;
1931 pthread_mutex_unlock(&pulse_lock);
1932 return hr;
1935 static void pulse_free_noop(void *buf)
1939 static HRESULT WINAPI AudioRenderClient_ReleaseBuffer(
1940 IAudioRenderClient *iface, UINT32 written_frames, DWORD flags)
1942 ACImpl *This = impl_from_IAudioRenderClient(iface);
1943 UINT32 written_bytes = written_frames * pa_frame_size(&This->ss);
1945 TRACE("(%p)->(%u, %x)\n", This, written_frames, flags);
1947 pthread_mutex_lock(&pulse_lock);
1948 if (!This->locked || !written_frames) {
1949 if (This->locked_ptr)
1950 pa_stream_cancel_write(This->stream);
1951 This->locked = 0;
1952 This->locked_ptr = NULL;
1953 pthread_mutex_unlock(&pulse_lock);
1954 return written_frames ? AUDCLNT_E_OUT_OF_ORDER : S_OK;
1957 if (This->locked < written_frames) {
1958 pthread_mutex_unlock(&pulse_lock);
1959 return AUDCLNT_E_INVALID_SIZE;
1962 if (flags & AUDCLNT_BUFFERFLAGS_SILENT) {
1963 if (This->ss.format == PA_SAMPLE_U8)
1964 memset(This->tmp_buffer, 128, written_bytes);
1965 else
1966 memset(This->tmp_buffer, 0, written_bytes);
1969 This->locked = 0;
1970 if (This->locked_ptr)
1971 pa_stream_write(This->stream, This->locked_ptr, written_bytes, NULL, 0, PA_SEEK_RELATIVE);
1972 else
1973 pa_stream_write(This->stream, This->tmp_buffer, written_bytes, pulse_free_noop, 0, PA_SEEK_RELATIVE);
1974 This->pad += written_bytes;
1975 This->locked_ptr = NULL;
1976 TRACE("Released %u, pad %zu\n", written_frames, This->pad / pa_frame_size(&This->ss));
1977 assert(This->pad <= This->bufsize_bytes);
1979 pthread_mutex_unlock(&pulse_lock);
1980 return S_OK;
1983 static const IAudioRenderClientVtbl AudioRenderClient_Vtbl = {
1984 AudioRenderClient_QueryInterface,
1985 AudioRenderClient_AddRef,
1986 AudioRenderClient_Release,
1987 AudioRenderClient_GetBuffer,
1988 AudioRenderClient_ReleaseBuffer
1991 static HRESULT WINAPI AudioCaptureClient_QueryInterface(
1992 IAudioCaptureClient *iface, REFIID riid, void **ppv)
1994 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
1996 if (!ppv)
1997 return E_POINTER;
1998 *ppv = NULL;
2000 if (IsEqualIID(riid, &IID_IUnknown) ||
2001 IsEqualIID(riid, &IID_IAudioCaptureClient))
2002 *ppv = iface;
2003 if (*ppv) {
2004 IUnknown_AddRef((IUnknown*)*ppv);
2005 return S_OK;
2008 WARN("Unknown interface %s\n", debugstr_guid(riid));
2009 return E_NOINTERFACE;
2012 static ULONG WINAPI AudioCaptureClient_AddRef(IAudioCaptureClient *iface)
2014 ACImpl *This = impl_from_IAudioCaptureClient(iface);
2015 return IAudioClient_AddRef(&This->IAudioClient_iface);
2018 static ULONG WINAPI AudioCaptureClient_Release(IAudioCaptureClient *iface)
2020 ACImpl *This = impl_from_IAudioCaptureClient(iface);
2021 return IAudioClient_Release(&This->IAudioClient_iface);
2024 static HRESULT WINAPI AudioCaptureClient_GetBuffer(IAudioCaptureClient *iface,
2025 BYTE **data, UINT32 *frames, DWORD *flags, UINT64 *devpos,
2026 UINT64 *qpcpos)
2028 ACImpl *This = impl_from_IAudioCaptureClient(iface);
2029 HRESULT hr;
2030 ACPacket *packet;
2032 TRACE("(%p)->(%p, %p, %p, %p, %p)\n", This, data, frames, flags,
2033 devpos, qpcpos);
2035 if (!data || !frames || !flags)
2036 return E_POINTER;
2038 pthread_mutex_lock(&pulse_lock);
2039 hr = pulse_stream_valid(This);
2040 if (FAILED(hr) || This->locked) {
2041 pthread_mutex_unlock(&pulse_lock);
2042 return FAILED(hr) ? hr : AUDCLNT_E_OUT_OF_ORDER;
2045 ACImpl_GetCapturePad(This, NULL);
2046 if ((packet = This->locked_ptr)) {
2047 *frames = This->capture_period / pa_frame_size(&This->ss);
2048 *flags = 0;
2049 if (packet->discont)
2050 *flags |= AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY;
2051 if (devpos) {
2052 if (packet->discont)
2053 *devpos = (This->clock_written + This->capture_period) / pa_frame_size(&This->ss);
2054 else
2055 *devpos = This->clock_written / pa_frame_size(&This->ss);
2057 if (qpcpos)
2058 *qpcpos = packet->qpcpos;
2059 *data = packet->data;
2061 else
2062 *frames = 0;
2063 This->locked = *frames;
2064 pthread_mutex_unlock(&pulse_lock);
2065 return *frames ? S_OK : AUDCLNT_S_BUFFER_EMPTY;
2068 static HRESULT WINAPI AudioCaptureClient_ReleaseBuffer(
2069 IAudioCaptureClient *iface, UINT32 done)
2071 ACImpl *This = impl_from_IAudioCaptureClient(iface);
2073 TRACE("(%p)->(%u)\n", This, done);
2075 pthread_mutex_lock(&pulse_lock);
2076 if (!This->locked && done) {
2077 pthread_mutex_unlock(&pulse_lock);
2078 return AUDCLNT_E_OUT_OF_ORDER;
2080 if (done && This->locked != done) {
2081 pthread_mutex_unlock(&pulse_lock);
2082 return AUDCLNT_E_INVALID_SIZE;
2084 if (done) {
2085 ACPacket *packet = This->locked_ptr;
2086 This->locked_ptr = NULL;
2087 This->pad -= This->capture_period;
2088 if (packet->discont)
2089 This->clock_written += 2 * This->capture_period;
2090 else
2091 This->clock_written += This->capture_period;
2092 list_add_tail(&This->packet_free_head, &packet->entry);
2094 This->locked = 0;
2095 pthread_mutex_unlock(&pulse_lock);
2096 return S_OK;
2099 static HRESULT WINAPI AudioCaptureClient_GetNextPacketSize(
2100 IAudioCaptureClient *iface, UINT32 *frames)
2102 ACImpl *This = impl_from_IAudioCaptureClient(iface);
2104 TRACE("(%p)->(%p)\n", This, frames);
2105 if (!frames)
2106 return E_POINTER;
2108 pthread_mutex_lock(&pulse_lock);
2109 ACImpl_GetCapturePad(This, NULL);
2110 if (This->locked_ptr)
2111 *frames = This->capture_period / pa_frame_size(&This->ss);
2112 else
2113 *frames = 0;
2114 pthread_mutex_unlock(&pulse_lock);
2115 return S_OK;
2118 static const IAudioCaptureClientVtbl AudioCaptureClient_Vtbl =
2120 AudioCaptureClient_QueryInterface,
2121 AudioCaptureClient_AddRef,
2122 AudioCaptureClient_Release,
2123 AudioCaptureClient_GetBuffer,
2124 AudioCaptureClient_ReleaseBuffer,
2125 AudioCaptureClient_GetNextPacketSize
2128 static HRESULT WINAPI AudioClock_QueryInterface(IAudioClock *iface,
2129 REFIID riid, void **ppv)
2131 ACImpl *This = impl_from_IAudioClock(iface);
2133 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
2135 if (!ppv)
2136 return E_POINTER;
2137 *ppv = NULL;
2139 if (IsEqualIID(riid, &IID_IUnknown) || IsEqualIID(riid, &IID_IAudioClock))
2140 *ppv = iface;
2141 else if (IsEqualIID(riid, &IID_IAudioClock2))
2142 *ppv = &This->IAudioClock2_iface;
2143 if (*ppv) {
2144 IUnknown_AddRef((IUnknown*)*ppv);
2145 return S_OK;
2148 WARN("Unknown interface %s\n", debugstr_guid(riid));
2149 return E_NOINTERFACE;
2152 static ULONG WINAPI AudioClock_AddRef(IAudioClock *iface)
2154 ACImpl *This = impl_from_IAudioClock(iface);
2155 return IAudioClient_AddRef(&This->IAudioClient_iface);
2158 static ULONG WINAPI AudioClock_Release(IAudioClock *iface)
2160 ACImpl *This = impl_from_IAudioClock(iface);
2161 return IAudioClient_Release(&This->IAudioClient_iface);
2164 static HRESULT WINAPI AudioClock_GetFrequency(IAudioClock *iface, UINT64 *freq)
2166 ACImpl *This = impl_from_IAudioClock(iface);
2167 HRESULT hr;
2169 TRACE("(%p)->(%p)\n", This, freq);
2171 pthread_mutex_lock(&pulse_lock);
2172 hr = pulse_stream_valid(This);
2173 if (SUCCEEDED(hr))
2174 *freq = This->ss.rate * pa_frame_size(&This->ss);
2175 pthread_mutex_unlock(&pulse_lock);
2176 return hr;
2179 static HRESULT WINAPI AudioClock_GetPosition(IAudioClock *iface, UINT64 *pos,
2180 UINT64 *qpctime)
2182 ACImpl *This = impl_from_IAudioClock(iface);
2183 HRESULT hr;
2185 TRACE("(%p)->(%p, %p)\n", This, pos, qpctime);
2187 if (!pos)
2188 return E_POINTER;
2190 pthread_mutex_lock(&pulse_lock);
2191 hr = pulse_stream_valid(This);
2192 if (FAILED(hr)) {
2193 pthread_mutex_unlock(&pulse_lock);
2194 return hr;
2197 *pos = This->clock_written;
2199 /* Make time never go backwards */
2200 if (*pos < This->clock_lastpos)
2201 *pos = This->clock_lastpos;
2202 else
2203 This->clock_lastpos = *pos;
2204 pthread_mutex_unlock(&pulse_lock);
2206 TRACE("%p Position: %u\n", This, (unsigned)*pos);
2208 if (qpctime) {
2209 LARGE_INTEGER stamp, freq;
2210 QueryPerformanceCounter(&stamp);
2211 QueryPerformanceFrequency(&freq);
2212 *qpctime = (stamp.QuadPart * (INT64)10000000) / freq.QuadPart;
2215 return S_OK;
2218 static HRESULT WINAPI AudioClock_GetCharacteristics(IAudioClock *iface,
2219 DWORD *chars)
2221 ACImpl *This = impl_from_IAudioClock(iface);
2223 TRACE("(%p)->(%p)\n", This, chars);
2225 if (!chars)
2226 return E_POINTER;
2228 *chars = AUDIOCLOCK_CHARACTERISTIC_FIXED_FREQ;
2230 return S_OK;
2233 static const IAudioClockVtbl AudioClock_Vtbl =
2235 AudioClock_QueryInterface,
2236 AudioClock_AddRef,
2237 AudioClock_Release,
2238 AudioClock_GetFrequency,
2239 AudioClock_GetPosition,
2240 AudioClock_GetCharacteristics
2243 static HRESULT WINAPI AudioClock2_QueryInterface(IAudioClock2 *iface,
2244 REFIID riid, void **ppv)
2246 ACImpl *This = impl_from_IAudioClock2(iface);
2247 return IAudioClock_QueryInterface(&This->IAudioClock_iface, riid, ppv);
2250 static ULONG WINAPI AudioClock2_AddRef(IAudioClock2 *iface)
2252 ACImpl *This = impl_from_IAudioClock2(iface);
2253 return IAudioClient_AddRef(&This->IAudioClient_iface);
2256 static ULONG WINAPI AudioClock2_Release(IAudioClock2 *iface)
2258 ACImpl *This = impl_from_IAudioClock2(iface);
2259 return IAudioClient_Release(&This->IAudioClient_iface);
2262 static HRESULT WINAPI AudioClock2_GetDevicePosition(IAudioClock2 *iface,
2263 UINT64 *pos, UINT64 *qpctime)
2265 ACImpl *This = impl_from_IAudioClock2(iface);
2266 HRESULT hr = AudioClock_GetPosition(&This->IAudioClock_iface, pos, qpctime);
2267 if (SUCCEEDED(hr))
2268 *pos /= pa_frame_size(&This->ss);
2269 return hr;
2272 static const IAudioClock2Vtbl AudioClock2_Vtbl =
2274 AudioClock2_QueryInterface,
2275 AudioClock2_AddRef,
2276 AudioClock2_Release,
2277 AudioClock2_GetDevicePosition
2280 static HRESULT WINAPI AudioStreamVolume_QueryInterface(
2281 IAudioStreamVolume *iface, REFIID riid, void **ppv)
2283 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
2285 if (!ppv)
2286 return E_POINTER;
2287 *ppv = NULL;
2289 if (IsEqualIID(riid, &IID_IUnknown) ||
2290 IsEqualIID(riid, &IID_IAudioStreamVolume))
2291 *ppv = iface;
2292 if (*ppv) {
2293 IUnknown_AddRef((IUnknown*)*ppv);
2294 return S_OK;
2297 WARN("Unknown interface %s\n", debugstr_guid(riid));
2298 return E_NOINTERFACE;
2301 static ULONG WINAPI AudioStreamVolume_AddRef(IAudioStreamVolume *iface)
2303 ACImpl *This = impl_from_IAudioStreamVolume(iface);
2304 return IAudioClient_AddRef(&This->IAudioClient_iface);
2307 static ULONG WINAPI AudioStreamVolume_Release(IAudioStreamVolume *iface)
2309 ACImpl *This = impl_from_IAudioStreamVolume(iface);
2310 return IAudioClient_Release(&This->IAudioClient_iface);
2313 static HRESULT WINAPI AudioStreamVolume_GetChannelCount(
2314 IAudioStreamVolume *iface, UINT32 *out)
2316 ACImpl *This = impl_from_IAudioStreamVolume(iface);
2318 TRACE("(%p)->(%p)\n", This, out);
2320 if (!out)
2321 return E_POINTER;
2323 *out = This->ss.channels;
2325 return S_OK;
2328 struct pulse_info_cb_data {
2329 UINT32 n;
2330 float *levels;
2333 static HRESULT WINAPI AudioStreamVolume_SetAllVolumes(
2334 IAudioStreamVolume *iface, UINT32 count, const float *levels)
2336 ACImpl *This = impl_from_IAudioStreamVolume(iface);
2337 HRESULT hr;
2338 int i;
2340 TRACE("(%p)->(%d, %p)\n", This, count, levels);
2342 if (!levels)
2343 return E_POINTER;
2345 if (count != This->ss.channels)
2346 return E_INVALIDARG;
2348 pthread_mutex_lock(&pulse_lock);
2349 hr = pulse_stream_valid(This);
2350 if (FAILED(hr))
2351 goto out;
2353 for (i = 0; i < count; ++i)
2354 This->vol[i] = levels[i];
2356 out:
2357 pthread_mutex_unlock(&pulse_lock);
2358 return hr;
2361 static HRESULT WINAPI AudioStreamVolume_GetAllVolumes(
2362 IAudioStreamVolume *iface, UINT32 count, float *levels)
2364 ACImpl *This = impl_from_IAudioStreamVolume(iface);
2365 HRESULT hr;
2366 int i;
2368 TRACE("(%p)->(%d, %p)\n", This, count, levels);
2370 if (!levels)
2371 return E_POINTER;
2373 if (count != This->ss.channels)
2374 return E_INVALIDARG;
2376 pthread_mutex_lock(&pulse_lock);
2377 hr = pulse_stream_valid(This);
2378 if (FAILED(hr))
2379 goto out;
2381 for (i = 0; i < count; ++i)
2382 levels[i] = This->vol[i];
2384 out:
2385 pthread_mutex_unlock(&pulse_lock);
2386 return hr;
2389 static HRESULT WINAPI AudioStreamVolume_SetChannelVolume(
2390 IAudioStreamVolume *iface, UINT32 index, float level)
2392 ACImpl *This = impl_from_IAudioStreamVolume(iface);
2393 HRESULT hr;
2394 float volumes[PA_CHANNELS_MAX];
2396 TRACE("(%p)->(%d, %f)\n", This, index, level);
2398 if (level < 0.f || level > 1.f)
2399 return E_INVALIDARG;
2401 if (index >= This->ss.channels)
2402 return E_INVALIDARG;
2404 hr = AudioStreamVolume_GetAllVolumes(iface, This->ss.channels, volumes);
2405 volumes[index] = level;
2406 if (SUCCEEDED(hr))
2407 hr = AudioStreamVolume_SetAllVolumes(iface, This->ss.channels, volumes);
2408 return hr;
2411 static HRESULT WINAPI AudioStreamVolume_GetChannelVolume(
2412 IAudioStreamVolume *iface, UINT32 index, float *level)
2414 ACImpl *This = impl_from_IAudioStreamVolume(iface);
2415 float volumes[PA_CHANNELS_MAX];
2416 HRESULT hr;
2418 TRACE("(%p)->(%d, %p)\n", This, index, level);
2420 if (!level)
2421 return E_POINTER;
2423 if (index >= This->ss.channels)
2424 return E_INVALIDARG;
2426 hr = AudioStreamVolume_GetAllVolumes(iface, This->ss.channels, volumes);
2427 if (SUCCEEDED(hr))
2428 *level = volumes[index];
2429 return hr;
2432 static const IAudioStreamVolumeVtbl AudioStreamVolume_Vtbl =
2434 AudioStreamVolume_QueryInterface,
2435 AudioStreamVolume_AddRef,
2436 AudioStreamVolume_Release,
2437 AudioStreamVolume_GetChannelCount,
2438 AudioStreamVolume_SetChannelVolume,
2439 AudioStreamVolume_GetChannelVolume,
2440 AudioStreamVolume_SetAllVolumes,
2441 AudioStreamVolume_GetAllVolumes
2444 static AudioSessionWrapper *AudioSessionWrapper_Create(ACImpl *client)
2446 AudioSessionWrapper *ret;
2448 ret = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
2449 sizeof(AudioSessionWrapper));
2450 if (!ret)
2451 return NULL;
2453 ret->IAudioSessionControl2_iface.lpVtbl = &AudioSessionControl2_Vtbl;
2454 ret->ISimpleAudioVolume_iface.lpVtbl = &SimpleAudioVolume_Vtbl;
2455 ret->IChannelAudioVolume_iface.lpVtbl = &ChannelAudioVolume_Vtbl;
2457 ret->ref = !client;
2459 ret->client = client;
2460 if (client) {
2461 ret->session = client->session;
2462 AudioClient_AddRef(&client->IAudioClient_iface);
2465 return ret;
2468 static HRESULT WINAPI AudioSessionControl_QueryInterface(
2469 IAudioSessionControl2 *iface, REFIID riid, void **ppv)
2471 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
2473 if (!ppv)
2474 return E_POINTER;
2475 *ppv = NULL;
2477 if (IsEqualIID(riid, &IID_IUnknown) ||
2478 IsEqualIID(riid, &IID_IAudioSessionControl) ||
2479 IsEqualIID(riid, &IID_IAudioSessionControl2))
2480 *ppv = iface;
2481 if (*ppv) {
2482 IUnknown_AddRef((IUnknown*)*ppv);
2483 return S_OK;
2486 WARN("Unknown interface %s\n", debugstr_guid(riid));
2487 return E_NOINTERFACE;
2490 static ULONG WINAPI AudioSessionControl_AddRef(IAudioSessionControl2 *iface)
2492 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2493 ULONG ref;
2494 ref = InterlockedIncrement(&This->ref);
2495 TRACE("(%p) Refcount now %u\n", This, ref);
2496 return ref;
2499 static ULONG WINAPI AudioSessionControl_Release(IAudioSessionControl2 *iface)
2501 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2502 ULONG ref;
2503 ref = InterlockedDecrement(&This->ref);
2504 TRACE("(%p) Refcount now %u\n", This, ref);
2505 if (!ref) {
2506 if (This->client) {
2507 This->client->session_wrapper = NULL;
2508 AudioClient_Release(&This->client->IAudioClient_iface);
2510 HeapFree(GetProcessHeap(), 0, This);
2512 return ref;
2515 static HRESULT WINAPI AudioSessionControl_GetState(IAudioSessionControl2 *iface,
2516 AudioSessionState *state)
2518 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2519 ACImpl *client;
2521 TRACE("(%p)->(%p)\n", This, state);
2523 if (!state)
2524 return NULL_PTR_ERR;
2526 pthread_mutex_lock(&pulse_lock);
2527 if (list_empty(&This->session->clients)) {
2528 *state = AudioSessionStateExpired;
2529 goto out;
2531 LIST_FOR_EACH_ENTRY(client, &This->session->clients, ACImpl, entry) {
2532 if (client->started) {
2533 *state = AudioSessionStateActive;
2534 goto out;
2537 *state = AudioSessionStateInactive;
2539 out:
2540 pthread_mutex_unlock(&pulse_lock);
2541 return S_OK;
2544 static HRESULT WINAPI AudioSessionControl_GetDisplayName(
2545 IAudioSessionControl2 *iface, WCHAR **name)
2547 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2549 FIXME("(%p)->(%p) - stub\n", This, name);
2551 return E_NOTIMPL;
2554 static HRESULT WINAPI AudioSessionControl_SetDisplayName(
2555 IAudioSessionControl2 *iface, const WCHAR *name, const GUID *session)
2557 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2559 FIXME("(%p)->(%p, %s) - stub\n", This, name, debugstr_guid(session));
2561 return E_NOTIMPL;
2564 static HRESULT WINAPI AudioSessionControl_GetIconPath(
2565 IAudioSessionControl2 *iface, WCHAR **path)
2567 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2569 FIXME("(%p)->(%p) - stub\n", This, path);
2571 return E_NOTIMPL;
2574 static HRESULT WINAPI AudioSessionControl_SetIconPath(
2575 IAudioSessionControl2 *iface, const WCHAR *path, const GUID *session)
2577 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2579 FIXME("(%p)->(%p, %s) - stub\n", This, path, debugstr_guid(session));
2581 return E_NOTIMPL;
2584 static HRESULT WINAPI AudioSessionControl_GetGroupingParam(
2585 IAudioSessionControl2 *iface, GUID *group)
2587 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2589 FIXME("(%p)->(%p) - stub\n", This, group);
2591 return E_NOTIMPL;
2594 static HRESULT WINAPI AudioSessionControl_SetGroupingParam(
2595 IAudioSessionControl2 *iface, const GUID *group, const GUID *session)
2597 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2599 FIXME("(%p)->(%s, %s) - stub\n", This, debugstr_guid(group),
2600 debugstr_guid(session));
2602 return E_NOTIMPL;
2605 static HRESULT WINAPI AudioSessionControl_RegisterAudioSessionNotification(
2606 IAudioSessionControl2 *iface, IAudioSessionEvents *events)
2608 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2610 FIXME("(%p)->(%p) - stub\n", This, events);
2612 return S_OK;
2615 static HRESULT WINAPI AudioSessionControl_UnregisterAudioSessionNotification(
2616 IAudioSessionControl2 *iface, IAudioSessionEvents *events)
2618 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2620 FIXME("(%p)->(%p) - stub\n", This, events);
2622 return S_OK;
2625 static HRESULT WINAPI AudioSessionControl_GetSessionIdentifier(
2626 IAudioSessionControl2 *iface, WCHAR **id)
2628 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2630 FIXME("(%p)->(%p) - stub\n", This, id);
2632 return E_NOTIMPL;
2635 static HRESULT WINAPI AudioSessionControl_GetSessionInstanceIdentifier(
2636 IAudioSessionControl2 *iface, WCHAR **id)
2638 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2640 FIXME("(%p)->(%p) - stub\n", This, id);
2642 return E_NOTIMPL;
2645 static HRESULT WINAPI AudioSessionControl_GetProcessId(
2646 IAudioSessionControl2 *iface, DWORD *pid)
2648 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2650 TRACE("(%p)->(%p)\n", This, pid);
2652 if (!pid)
2653 return E_POINTER;
2655 *pid = GetCurrentProcessId();
2657 return S_OK;
2660 static HRESULT WINAPI AudioSessionControl_IsSystemSoundsSession(
2661 IAudioSessionControl2 *iface)
2663 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2665 TRACE("(%p)\n", This);
2667 return S_FALSE;
2670 static HRESULT WINAPI AudioSessionControl_SetDuckingPreference(
2671 IAudioSessionControl2 *iface, BOOL optout)
2673 AudioSessionWrapper *This = impl_from_IAudioSessionControl2(iface);
2675 TRACE("(%p)->(%d)\n", This, optout);
2677 return S_OK;
2680 static const IAudioSessionControl2Vtbl AudioSessionControl2_Vtbl =
2682 AudioSessionControl_QueryInterface,
2683 AudioSessionControl_AddRef,
2684 AudioSessionControl_Release,
2685 AudioSessionControl_GetState,
2686 AudioSessionControl_GetDisplayName,
2687 AudioSessionControl_SetDisplayName,
2688 AudioSessionControl_GetIconPath,
2689 AudioSessionControl_SetIconPath,
2690 AudioSessionControl_GetGroupingParam,
2691 AudioSessionControl_SetGroupingParam,
2692 AudioSessionControl_RegisterAudioSessionNotification,
2693 AudioSessionControl_UnregisterAudioSessionNotification,
2694 AudioSessionControl_GetSessionIdentifier,
2695 AudioSessionControl_GetSessionInstanceIdentifier,
2696 AudioSessionControl_GetProcessId,
2697 AudioSessionControl_IsSystemSoundsSession,
2698 AudioSessionControl_SetDuckingPreference
2701 typedef struct _SessionMgr {
2702 IAudioSessionManager2 IAudioSessionManager2_iface;
2704 LONG ref;
2706 IMMDevice *device;
2707 } SessionMgr;
2709 static HRESULT WINAPI AudioSessionManager_QueryInterface(IAudioSessionManager2 *iface,
2710 REFIID riid, void **ppv)
2712 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
2714 if (!ppv)
2715 return E_POINTER;
2716 *ppv = NULL;
2718 if (IsEqualIID(riid, &IID_IUnknown) ||
2719 IsEqualIID(riid, &IID_IAudioSessionManager) ||
2720 IsEqualIID(riid, &IID_IAudioSessionManager2))
2721 *ppv = iface;
2722 if (*ppv) {
2723 IUnknown_AddRef((IUnknown*)*ppv);
2724 return S_OK;
2727 WARN("Unknown interface %s\n", debugstr_guid(riid));
2728 return E_NOINTERFACE;
2731 static inline SessionMgr *impl_from_IAudioSessionManager2(IAudioSessionManager2 *iface)
2733 return CONTAINING_RECORD(iface, SessionMgr, IAudioSessionManager2_iface);
2736 static ULONG WINAPI AudioSessionManager_AddRef(IAudioSessionManager2 *iface)
2738 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
2739 ULONG ref;
2740 ref = InterlockedIncrement(&This->ref);
2741 TRACE("(%p) Refcount now %u\n", This, ref);
2742 return ref;
2745 static ULONG WINAPI AudioSessionManager_Release(IAudioSessionManager2 *iface)
2747 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
2748 ULONG ref;
2749 ref = InterlockedDecrement(&This->ref);
2750 TRACE("(%p) Refcount now %u\n", This, ref);
2751 if (!ref)
2752 HeapFree(GetProcessHeap(), 0, This);
2753 return ref;
2756 static HRESULT WINAPI AudioSessionManager_GetAudioSessionControl(
2757 IAudioSessionManager2 *iface, const GUID *session_guid, DWORD flags,
2758 IAudioSessionControl **out)
2760 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
2761 AudioSession *session;
2762 AudioSessionWrapper *wrapper;
2763 HRESULT hr;
2765 TRACE("(%p)->(%s, %x, %p)\n", This, debugstr_guid(session_guid),
2766 flags, out);
2768 hr = get_audio_session(session_guid, This->device, 0, &session);
2769 if (FAILED(hr))
2770 return hr;
2772 wrapper = AudioSessionWrapper_Create(NULL);
2773 if (!wrapper)
2774 return E_OUTOFMEMORY;
2776 wrapper->session = session;
2778 *out = (IAudioSessionControl*)&wrapper->IAudioSessionControl2_iface;
2780 return S_OK;
2783 static HRESULT WINAPI AudioSessionManager_GetSimpleAudioVolume(
2784 IAudioSessionManager2 *iface, const GUID *session_guid, DWORD flags,
2785 ISimpleAudioVolume **out)
2787 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
2788 AudioSession *session;
2789 AudioSessionWrapper *wrapper;
2790 HRESULT hr;
2792 TRACE("(%p)->(%s, %x, %p)\n", This, debugstr_guid(session_guid),
2793 flags, out);
2795 hr = get_audio_session(session_guid, This->device, 0, &session);
2796 if (FAILED(hr))
2797 return hr;
2799 wrapper = AudioSessionWrapper_Create(NULL);
2800 if (!wrapper)
2801 return E_OUTOFMEMORY;
2803 wrapper->session = session;
2805 *out = &wrapper->ISimpleAudioVolume_iface;
2807 return S_OK;
2810 static HRESULT WINAPI AudioSessionManager_GetSessionEnumerator(
2811 IAudioSessionManager2 *iface, IAudioSessionEnumerator **out)
2813 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
2814 FIXME("(%p)->(%p) - stub\n", This, out);
2815 return E_NOTIMPL;
2818 static HRESULT WINAPI AudioSessionManager_RegisterSessionNotification(
2819 IAudioSessionManager2 *iface, IAudioSessionNotification *notification)
2821 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
2822 FIXME("(%p)->(%p) - stub\n", This, notification);
2823 return E_NOTIMPL;
2826 static HRESULT WINAPI AudioSessionManager_UnregisterSessionNotification(
2827 IAudioSessionManager2 *iface, IAudioSessionNotification *notification)
2829 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
2830 FIXME("(%p)->(%p) - stub\n", This, notification);
2831 return E_NOTIMPL;
2834 static HRESULT WINAPI AudioSessionManager_RegisterDuckNotification(
2835 IAudioSessionManager2 *iface, const WCHAR *session_id,
2836 IAudioVolumeDuckNotification *notification)
2838 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
2839 FIXME("(%p)->(%p) - stub\n", This, notification);
2840 return E_NOTIMPL;
2843 static HRESULT WINAPI AudioSessionManager_UnregisterDuckNotification(
2844 IAudioSessionManager2 *iface,
2845 IAudioVolumeDuckNotification *notification)
2847 SessionMgr *This = impl_from_IAudioSessionManager2(iface);
2848 FIXME("(%p)->(%p) - stub\n", This, notification);
2849 return E_NOTIMPL;
2852 static const IAudioSessionManager2Vtbl AudioSessionManager2_Vtbl =
2854 AudioSessionManager_QueryInterface,
2855 AudioSessionManager_AddRef,
2856 AudioSessionManager_Release,
2857 AudioSessionManager_GetAudioSessionControl,
2858 AudioSessionManager_GetSimpleAudioVolume,
2859 AudioSessionManager_GetSessionEnumerator,
2860 AudioSessionManager_RegisterSessionNotification,
2861 AudioSessionManager_UnregisterSessionNotification,
2862 AudioSessionManager_RegisterDuckNotification,
2863 AudioSessionManager_UnregisterDuckNotification
2866 static HRESULT WINAPI SimpleAudioVolume_QueryInterface(
2867 ISimpleAudioVolume *iface, REFIID riid, void **ppv)
2869 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
2871 if (!ppv)
2872 return E_POINTER;
2873 *ppv = NULL;
2875 if (IsEqualIID(riid, &IID_IUnknown) ||
2876 IsEqualIID(riid, &IID_ISimpleAudioVolume))
2877 *ppv = iface;
2878 if (*ppv) {
2879 IUnknown_AddRef((IUnknown*)*ppv);
2880 return S_OK;
2883 WARN("Unknown interface %s\n", debugstr_guid(riid));
2884 return E_NOINTERFACE;
2887 static ULONG WINAPI SimpleAudioVolume_AddRef(ISimpleAudioVolume *iface)
2889 AudioSessionWrapper *This = impl_from_ISimpleAudioVolume(iface);
2890 return AudioSessionControl_AddRef(&This->IAudioSessionControl2_iface);
2893 static ULONG WINAPI SimpleAudioVolume_Release(ISimpleAudioVolume *iface)
2895 AudioSessionWrapper *This = impl_from_ISimpleAudioVolume(iface);
2896 return AudioSessionControl_Release(&This->IAudioSessionControl2_iface);
2899 static HRESULT WINAPI SimpleAudioVolume_SetMasterVolume(
2900 ISimpleAudioVolume *iface, float level, const GUID *context)
2902 AudioSessionWrapper *This = impl_from_ISimpleAudioVolume(iface);
2903 AudioSession *session = This->session;
2905 TRACE("(%p)->(%f, %s)\n", session, level, wine_dbgstr_guid(context));
2907 if (level < 0.f || level > 1.f)
2908 return E_INVALIDARG;
2910 if (context)
2911 FIXME("Notifications not supported yet\n");
2913 TRACE("Pulseaudio does not support session volume control\n");
2915 pthread_mutex_lock(&pulse_lock);
2916 session->master_vol = level;
2917 pthread_mutex_unlock(&pulse_lock);
2919 return S_OK;
2922 static HRESULT WINAPI SimpleAudioVolume_GetMasterVolume(
2923 ISimpleAudioVolume *iface, float *level)
2925 AudioSessionWrapper *This = impl_from_ISimpleAudioVolume(iface);
2926 AudioSession *session = This->session;
2928 TRACE("(%p)->(%p)\n", session, level);
2930 if (!level)
2931 return NULL_PTR_ERR;
2933 *level = session->master_vol;
2935 return S_OK;
2938 static HRESULT WINAPI SimpleAudioVolume_SetMute(ISimpleAudioVolume *iface,
2939 BOOL mute, const GUID *context)
2941 AudioSessionWrapper *This = impl_from_ISimpleAudioVolume(iface);
2942 AudioSession *session = This->session;
2944 TRACE("(%p)->(%u, %p)\n", session, mute, context);
2946 if (context)
2947 FIXME("Notifications not supported yet\n");
2949 session->mute = mute;
2951 return S_OK;
2954 static HRESULT WINAPI SimpleAudioVolume_GetMute(ISimpleAudioVolume *iface,
2955 BOOL *mute)
2957 AudioSessionWrapper *This = impl_from_ISimpleAudioVolume(iface);
2958 AudioSession *session = This->session;
2960 TRACE("(%p)->(%p)\n", session, mute);
2962 if (!mute)
2963 return NULL_PTR_ERR;
2965 *mute = session->mute;
2967 return S_OK;
2970 static const ISimpleAudioVolumeVtbl SimpleAudioVolume_Vtbl =
2972 SimpleAudioVolume_QueryInterface,
2973 SimpleAudioVolume_AddRef,
2974 SimpleAudioVolume_Release,
2975 SimpleAudioVolume_SetMasterVolume,
2976 SimpleAudioVolume_GetMasterVolume,
2977 SimpleAudioVolume_SetMute,
2978 SimpleAudioVolume_GetMute
2981 static HRESULT WINAPI ChannelAudioVolume_QueryInterface(
2982 IChannelAudioVolume *iface, REFIID riid, void **ppv)
2984 TRACE("(%p)->(%s, %p)\n", iface, debugstr_guid(riid), ppv);
2986 if (!ppv)
2987 return E_POINTER;
2988 *ppv = NULL;
2990 if (IsEqualIID(riid, &IID_IUnknown) ||
2991 IsEqualIID(riid, &IID_IChannelAudioVolume))
2992 *ppv = iface;
2993 if (*ppv) {
2994 IUnknown_AddRef((IUnknown*)*ppv);
2995 return S_OK;
2998 WARN("Unknown interface %s\n", debugstr_guid(riid));
2999 return E_NOINTERFACE;
3002 static ULONG WINAPI ChannelAudioVolume_AddRef(IChannelAudioVolume *iface)
3004 AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
3005 return AudioSessionControl_AddRef(&This->IAudioSessionControl2_iface);
3008 static ULONG WINAPI ChannelAudioVolume_Release(IChannelAudioVolume *iface)
3010 AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
3011 return AudioSessionControl_Release(&This->IAudioSessionControl2_iface);
3014 static HRESULT WINAPI ChannelAudioVolume_GetChannelCount(
3015 IChannelAudioVolume *iface, UINT32 *out)
3017 AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
3018 AudioSession *session = This->session;
3020 TRACE("(%p)->(%p)\n", session, out);
3022 if (!out)
3023 return NULL_PTR_ERR;
3025 *out = session->channel_count;
3027 return S_OK;
3030 static HRESULT WINAPI ChannelAudioVolume_SetChannelVolume(
3031 IChannelAudioVolume *iface, UINT32 index, float level,
3032 const GUID *context)
3034 AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
3035 AudioSession *session = This->session;
3037 TRACE("(%p)->(%d, %f, %s)\n", session, index, level,
3038 wine_dbgstr_guid(context));
3040 if (level < 0.f || level > 1.f)
3041 return E_INVALIDARG;
3043 if (index >= session->channel_count)
3044 return E_INVALIDARG;
3046 if (context)
3047 FIXME("Notifications not supported yet\n");
3049 TRACE("Pulseaudio does not support session volume control\n");
3051 pthread_mutex_lock(&pulse_lock);
3052 session->channel_vols[index] = level;
3053 pthread_mutex_unlock(&pulse_lock);
3055 return S_OK;
3058 static HRESULT WINAPI ChannelAudioVolume_GetChannelVolume(
3059 IChannelAudioVolume *iface, UINT32 index, float *level)
3061 AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
3062 AudioSession *session = This->session;
3064 TRACE("(%p)->(%d, %p)\n", session, index, level);
3066 if (!level)
3067 return NULL_PTR_ERR;
3069 if (index >= session->channel_count)
3070 return E_INVALIDARG;
3072 *level = session->channel_vols[index];
3074 return S_OK;
3077 static HRESULT WINAPI ChannelAudioVolume_SetAllVolumes(
3078 IChannelAudioVolume *iface, UINT32 count, const float *levels,
3079 const GUID *context)
3081 AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
3082 AudioSession *session = This->session;
3083 int i;
3085 TRACE("(%p)->(%d, %p, %s)\n", session, count, levels,
3086 wine_dbgstr_guid(context));
3088 if (!levels)
3089 return NULL_PTR_ERR;
3091 if (count != session->channel_count)
3092 return E_INVALIDARG;
3094 if (context)
3095 FIXME("Notifications not supported yet\n");
3097 TRACE("Pulseaudio does not support session volume control\n");
3099 pthread_mutex_lock(&pulse_lock);
3100 for(i = 0; i < count; ++i)
3101 session->channel_vols[i] = levels[i];
3102 pthread_mutex_unlock(&pulse_lock);
3103 return S_OK;
3106 static HRESULT WINAPI ChannelAudioVolume_GetAllVolumes(
3107 IChannelAudioVolume *iface, UINT32 count, float *levels)
3109 AudioSessionWrapper *This = impl_from_IChannelAudioVolume(iface);
3110 AudioSession *session = This->session;
3111 int i;
3113 TRACE("(%p)->(%d, %p)\n", session, count, levels);
3115 if (!levels)
3116 return NULL_PTR_ERR;
3118 if (count != session->channel_count)
3119 return E_INVALIDARG;
3121 for(i = 0; i < count; ++i)
3122 levels[i] = session->channel_vols[i];
3124 return S_OK;
3127 static const IChannelAudioVolumeVtbl ChannelAudioVolume_Vtbl =
3129 ChannelAudioVolume_QueryInterface,
3130 ChannelAudioVolume_AddRef,
3131 ChannelAudioVolume_Release,
3132 ChannelAudioVolume_GetChannelCount,
3133 ChannelAudioVolume_SetChannelVolume,
3134 ChannelAudioVolume_GetChannelVolume,
3135 ChannelAudioVolume_SetAllVolumes,
3136 ChannelAudioVolume_GetAllVolumes
3139 HRESULT WINAPI AUDDRV_GetAudioSessionManager(IMMDevice *device,
3140 IAudioSessionManager2 **out)
3142 SessionMgr *This = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(SessionMgr));
3143 *out = NULL;
3144 if (!This)
3145 return E_OUTOFMEMORY;
3146 This->IAudioSessionManager2_iface.lpVtbl = &AudioSessionManager2_Vtbl;
3147 This->device = device;
3148 This->ref = 1;
3149 *out = &This->IAudioSessionManager2_iface;
3150 return S_OK;