Add a hack to workaround erroneous prebuf values from pulse
[openal-soft.git] / Alc / backends / pulseaudio.c
blobca8441aae932c20f017f89d86bfcdf014bf1b67b
1 /**
2 * OpenAL cross platform audio library
3 * Copyright (C) 2009 by Konstantinos Natsakis <konstantinos.natsakis@gmail.com>
4 * Copyright (C) 2010 by Chris Robinson <chris.kcat@gmail.com>
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Library General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Library General Public License for more details.
15 * You should have received a copy of the GNU Library General Public
16 * License along with this library; if not, write to the
17 * Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 * Or go to http://www.gnu.org/copyleft/lgpl.html
22 #include "config.h"
24 #include <string.h>
26 #include "alMain.h"
27 #include "alu.h"
28 #include "threads.h"
29 #include "compat.h"
31 #include "backends/base.h"
33 #include <pulse/pulseaudio.h>
35 #if PA_API_VERSION == 12
37 #ifdef HAVE_DYNLOAD
38 static void *pa_handle;
39 #define MAKE_FUNC(x) static __typeof(x) * p##x
40 MAKE_FUNC(pa_context_unref);
41 MAKE_FUNC(pa_sample_spec_valid);
42 MAKE_FUNC(pa_frame_size);
43 MAKE_FUNC(pa_stream_drop);
44 MAKE_FUNC(pa_strerror);
45 MAKE_FUNC(pa_context_get_state);
46 MAKE_FUNC(pa_stream_get_state);
47 MAKE_FUNC(pa_threaded_mainloop_signal);
48 MAKE_FUNC(pa_stream_peek);
49 MAKE_FUNC(pa_threaded_mainloop_wait);
50 MAKE_FUNC(pa_threaded_mainloop_unlock);
51 MAKE_FUNC(pa_threaded_mainloop_in_thread);
52 MAKE_FUNC(pa_context_new);
53 MAKE_FUNC(pa_threaded_mainloop_stop);
54 MAKE_FUNC(pa_context_disconnect);
55 MAKE_FUNC(pa_threaded_mainloop_start);
56 MAKE_FUNC(pa_threaded_mainloop_get_api);
57 MAKE_FUNC(pa_context_set_state_callback);
58 MAKE_FUNC(pa_stream_write);
59 MAKE_FUNC(pa_xfree);
60 MAKE_FUNC(pa_stream_connect_record);
61 MAKE_FUNC(pa_stream_connect_playback);
62 MAKE_FUNC(pa_stream_readable_size);
63 MAKE_FUNC(pa_stream_writable_size);
64 MAKE_FUNC(pa_stream_is_corked);
65 MAKE_FUNC(pa_stream_cork);
66 MAKE_FUNC(pa_stream_is_suspended);
67 MAKE_FUNC(pa_stream_get_device_name);
68 MAKE_FUNC(pa_stream_get_latency);
69 MAKE_FUNC(pa_path_get_filename);
70 MAKE_FUNC(pa_get_binary_name);
71 MAKE_FUNC(pa_threaded_mainloop_free);
72 MAKE_FUNC(pa_context_errno);
73 MAKE_FUNC(pa_xmalloc);
74 MAKE_FUNC(pa_stream_unref);
75 MAKE_FUNC(pa_threaded_mainloop_accept);
76 MAKE_FUNC(pa_stream_set_write_callback);
77 MAKE_FUNC(pa_threaded_mainloop_new);
78 MAKE_FUNC(pa_context_connect);
79 MAKE_FUNC(pa_stream_set_buffer_attr);
80 MAKE_FUNC(pa_stream_get_buffer_attr);
81 MAKE_FUNC(pa_stream_get_sample_spec);
82 MAKE_FUNC(pa_stream_get_time);
83 MAKE_FUNC(pa_stream_set_read_callback);
84 MAKE_FUNC(pa_stream_set_state_callback);
85 MAKE_FUNC(pa_stream_set_moved_callback);
86 MAKE_FUNC(pa_stream_set_underflow_callback);
87 MAKE_FUNC(pa_stream_new_with_proplist);
88 MAKE_FUNC(pa_stream_disconnect);
89 MAKE_FUNC(pa_threaded_mainloop_lock);
90 MAKE_FUNC(pa_channel_map_init_auto);
91 MAKE_FUNC(pa_channel_map_parse);
92 MAKE_FUNC(pa_channel_map_snprint);
93 MAKE_FUNC(pa_channel_map_equal);
94 MAKE_FUNC(pa_context_get_server_info);
95 MAKE_FUNC(pa_context_get_sink_info_by_name);
96 MAKE_FUNC(pa_context_get_sink_info_list);
97 MAKE_FUNC(pa_context_get_source_info_by_name);
98 MAKE_FUNC(pa_context_get_source_info_list);
99 MAKE_FUNC(pa_operation_get_state);
100 MAKE_FUNC(pa_operation_unref);
101 MAKE_FUNC(pa_proplist_new);
102 MAKE_FUNC(pa_proplist_free);
103 MAKE_FUNC(pa_proplist_set);
104 MAKE_FUNC(pa_channel_map_superset);
105 MAKE_FUNC(pa_stream_set_buffer_attr_callback);
106 MAKE_FUNC(pa_stream_begin_write);
107 #undef MAKE_FUNC
109 #define pa_context_unref ppa_context_unref
110 #define pa_sample_spec_valid ppa_sample_spec_valid
111 #define pa_frame_size ppa_frame_size
112 #define pa_stream_drop ppa_stream_drop
113 #define pa_strerror ppa_strerror
114 #define pa_context_get_state ppa_context_get_state
115 #define pa_stream_get_state ppa_stream_get_state
116 #define pa_threaded_mainloop_signal ppa_threaded_mainloop_signal
117 #define pa_stream_peek ppa_stream_peek
118 #define pa_threaded_mainloop_wait ppa_threaded_mainloop_wait
119 #define pa_threaded_mainloop_unlock ppa_threaded_mainloop_unlock
120 #define pa_threaded_mainloop_in_thread ppa_threaded_mainloop_in_thread
121 #define pa_context_new ppa_context_new
122 #define pa_threaded_mainloop_stop ppa_threaded_mainloop_stop
123 #define pa_context_disconnect ppa_context_disconnect
124 #define pa_threaded_mainloop_start ppa_threaded_mainloop_start
125 #define pa_threaded_mainloop_get_api ppa_threaded_mainloop_get_api
126 #define pa_context_set_state_callback ppa_context_set_state_callback
127 #define pa_stream_write ppa_stream_write
128 #define pa_xfree ppa_xfree
129 #define pa_stream_connect_record ppa_stream_connect_record
130 #define pa_stream_connect_playback ppa_stream_connect_playback
131 #define pa_stream_readable_size ppa_stream_readable_size
132 #define pa_stream_writable_size ppa_stream_writable_size
133 #define pa_stream_is_corked ppa_stream_is_corked
134 #define pa_stream_cork ppa_stream_cork
135 #define pa_stream_is_suspended ppa_stream_is_suspended
136 #define pa_stream_get_device_name ppa_stream_get_device_name
137 #define pa_stream_get_latency ppa_stream_get_latency
138 #define pa_path_get_filename ppa_path_get_filename
139 #define pa_get_binary_name ppa_get_binary_name
140 #define pa_threaded_mainloop_free ppa_threaded_mainloop_free
141 #define pa_context_errno ppa_context_errno
142 #define pa_xmalloc ppa_xmalloc
143 #define pa_stream_unref ppa_stream_unref
144 #define pa_threaded_mainloop_accept ppa_threaded_mainloop_accept
145 #define pa_stream_set_write_callback ppa_stream_set_write_callback
146 #define pa_threaded_mainloop_new ppa_threaded_mainloop_new
147 #define pa_context_connect ppa_context_connect
148 #define pa_stream_set_buffer_attr ppa_stream_set_buffer_attr
149 #define pa_stream_get_buffer_attr ppa_stream_get_buffer_attr
150 #define pa_stream_get_sample_spec ppa_stream_get_sample_spec
151 #define pa_stream_get_time ppa_stream_get_time
152 #define pa_stream_set_read_callback ppa_stream_set_read_callback
153 #define pa_stream_set_state_callback ppa_stream_set_state_callback
154 #define pa_stream_set_moved_callback ppa_stream_set_moved_callback
155 #define pa_stream_set_underflow_callback ppa_stream_set_underflow_callback
156 #define pa_stream_new_with_proplist ppa_stream_new_with_proplist
157 #define pa_stream_disconnect ppa_stream_disconnect
158 #define pa_threaded_mainloop_lock ppa_threaded_mainloop_lock
159 #define pa_channel_map_init_auto ppa_channel_map_init_auto
160 #define pa_channel_map_parse ppa_channel_map_parse
161 #define pa_channel_map_snprint ppa_channel_map_snprint
162 #define pa_channel_map_equal ppa_channel_map_equal
163 #define pa_context_get_server_info ppa_context_get_server_info
164 #define pa_context_get_sink_info_by_name ppa_context_get_sink_info_by_name
165 #define pa_context_get_sink_info_list ppa_context_get_sink_info_list
166 #define pa_context_get_source_info_by_name ppa_context_get_source_info_by_name
167 #define pa_context_get_source_info_list ppa_context_get_source_info_list
168 #define pa_operation_get_state ppa_operation_get_state
169 #define pa_operation_unref ppa_operation_unref
170 #define pa_proplist_new ppa_proplist_new
171 #define pa_proplist_free ppa_proplist_free
172 #define pa_proplist_set ppa_proplist_set
173 #define pa_channel_map_superset ppa_channel_map_superset
174 #define pa_stream_set_buffer_attr_callback ppa_stream_set_buffer_attr_callback
175 #define pa_stream_begin_write ppa_stream_begin_write
177 #endif
179 static ALCboolean pulse_load(void)
181 ALCboolean ret = ALC_TRUE;
182 #ifdef HAVE_DYNLOAD
183 if(!pa_handle)
185 #ifdef _WIN32
186 #define PALIB "libpulse-0.dll"
187 #elif defined(__APPLE__) && defined(__MACH__)
188 #define PALIB "libpulse.0.dylib"
189 #else
190 #define PALIB "libpulse.so.0"
191 #endif
192 pa_handle = LoadLib(PALIB);
193 if(!pa_handle)
194 return ALC_FALSE;
196 #define LOAD_FUNC(x) do { \
197 p##x = GetSymbol(pa_handle, #x); \
198 if(!(p##x)) { \
199 ret = ALC_FALSE; \
201 } while(0)
202 LOAD_FUNC(pa_context_unref);
203 LOAD_FUNC(pa_sample_spec_valid);
204 LOAD_FUNC(pa_stream_drop);
205 LOAD_FUNC(pa_frame_size);
206 LOAD_FUNC(pa_strerror);
207 LOAD_FUNC(pa_context_get_state);
208 LOAD_FUNC(pa_stream_get_state);
209 LOAD_FUNC(pa_threaded_mainloop_signal);
210 LOAD_FUNC(pa_stream_peek);
211 LOAD_FUNC(pa_threaded_mainloop_wait);
212 LOAD_FUNC(pa_threaded_mainloop_unlock);
213 LOAD_FUNC(pa_threaded_mainloop_in_thread);
214 LOAD_FUNC(pa_context_new);
215 LOAD_FUNC(pa_threaded_mainloop_stop);
216 LOAD_FUNC(pa_context_disconnect);
217 LOAD_FUNC(pa_threaded_mainloop_start);
218 LOAD_FUNC(pa_threaded_mainloop_get_api);
219 LOAD_FUNC(pa_context_set_state_callback);
220 LOAD_FUNC(pa_stream_write);
221 LOAD_FUNC(pa_xfree);
222 LOAD_FUNC(pa_stream_connect_record);
223 LOAD_FUNC(pa_stream_connect_playback);
224 LOAD_FUNC(pa_stream_readable_size);
225 LOAD_FUNC(pa_stream_writable_size);
226 LOAD_FUNC(pa_stream_is_corked);
227 LOAD_FUNC(pa_stream_cork);
228 LOAD_FUNC(pa_stream_is_suspended);
229 LOAD_FUNC(pa_stream_get_device_name);
230 LOAD_FUNC(pa_stream_get_latency);
231 LOAD_FUNC(pa_path_get_filename);
232 LOAD_FUNC(pa_get_binary_name);
233 LOAD_FUNC(pa_threaded_mainloop_free);
234 LOAD_FUNC(pa_context_errno);
235 LOAD_FUNC(pa_xmalloc);
236 LOAD_FUNC(pa_stream_unref);
237 LOAD_FUNC(pa_threaded_mainloop_accept);
238 LOAD_FUNC(pa_stream_set_write_callback);
239 LOAD_FUNC(pa_threaded_mainloop_new);
240 LOAD_FUNC(pa_context_connect);
241 LOAD_FUNC(pa_stream_set_buffer_attr);
242 LOAD_FUNC(pa_stream_get_buffer_attr);
243 LOAD_FUNC(pa_stream_get_sample_spec);
244 LOAD_FUNC(pa_stream_get_time);
245 LOAD_FUNC(pa_stream_set_read_callback);
246 LOAD_FUNC(pa_stream_set_state_callback);
247 LOAD_FUNC(pa_stream_set_moved_callback);
248 LOAD_FUNC(pa_stream_set_underflow_callback);
249 LOAD_FUNC(pa_stream_new_with_proplist);
250 LOAD_FUNC(pa_stream_disconnect);
251 LOAD_FUNC(pa_threaded_mainloop_lock);
252 LOAD_FUNC(pa_channel_map_init_auto);
253 LOAD_FUNC(pa_channel_map_parse);
254 LOAD_FUNC(pa_channel_map_snprint);
255 LOAD_FUNC(pa_channel_map_equal);
256 LOAD_FUNC(pa_context_get_server_info);
257 LOAD_FUNC(pa_context_get_sink_info_by_name);
258 LOAD_FUNC(pa_context_get_sink_info_list);
259 LOAD_FUNC(pa_context_get_source_info_by_name);
260 LOAD_FUNC(pa_context_get_source_info_list);
261 LOAD_FUNC(pa_operation_get_state);
262 LOAD_FUNC(pa_operation_unref);
263 LOAD_FUNC(pa_proplist_new);
264 LOAD_FUNC(pa_proplist_free);
265 LOAD_FUNC(pa_proplist_set);
266 LOAD_FUNC(pa_channel_map_superset);
267 LOAD_FUNC(pa_stream_set_buffer_attr_callback);
268 LOAD_FUNC(pa_stream_begin_write);
269 #undef LOAD_FUNC
271 if(ret == ALC_FALSE)
273 CloseLib(pa_handle);
274 pa_handle = NULL;
277 #endif /* HAVE_DYNLOAD */
278 return ret;
282 /* Global flags and properties */
283 static pa_context_flags_t pulse_ctx_flags;
284 static pa_proplist *prop_filter;
287 /* PulseAudio Event Callbacks */
288 static void context_state_callback(pa_context *context, void *pdata)
290 pa_threaded_mainloop *loop = pdata;
291 pa_context_state_t state;
293 state = pa_context_get_state(context);
294 if(state == PA_CONTEXT_READY || !PA_CONTEXT_IS_GOOD(state))
295 pa_threaded_mainloop_signal(loop, 0);
298 static void stream_state_callback(pa_stream *stream, void *pdata)
300 pa_threaded_mainloop *loop = pdata;
301 pa_stream_state_t state;
303 state = pa_stream_get_state(stream);
304 if(state == PA_STREAM_READY || !PA_STREAM_IS_GOOD(state))
305 pa_threaded_mainloop_signal(loop, 0);
308 static void stream_success_callback(pa_stream *UNUSED(stream), int UNUSED(success), void *pdata)
310 pa_threaded_mainloop *loop = pdata;
311 pa_threaded_mainloop_signal(loop, 0);
314 static void wait_for_operation(pa_operation *op, pa_threaded_mainloop *loop)
316 if(op)
318 while(pa_operation_get_state(op) == PA_OPERATION_RUNNING)
319 pa_threaded_mainloop_wait(loop);
320 pa_operation_unref(op);
325 static pa_context *connect_context(pa_threaded_mainloop *loop, ALboolean silent)
327 const char *name = "OpenAL Soft";
328 char path_name[PATH_MAX];
329 pa_context_state_t state;
330 pa_context *context;
331 int err;
333 if(pa_get_binary_name(path_name, sizeof(path_name)))
334 name = pa_path_get_filename(path_name);
336 context = pa_context_new(pa_threaded_mainloop_get_api(loop), name);
337 if(!context)
339 ERR("pa_context_new() failed\n");
340 return NULL;
343 pa_context_set_state_callback(context, context_state_callback, loop);
345 if((err=pa_context_connect(context, NULL, pulse_ctx_flags, NULL)) >= 0)
347 while((state=pa_context_get_state(context)) != PA_CONTEXT_READY)
349 if(!PA_CONTEXT_IS_GOOD(state))
351 err = pa_context_errno(context);
352 if(err > 0) err = -err;
353 break;
356 pa_threaded_mainloop_wait(loop);
359 pa_context_set_state_callback(context, NULL, NULL);
361 if(err < 0)
363 if(!silent)
364 ERR("Context did not connect: %s\n", pa_strerror(err));
365 pa_context_unref(context);
366 return NULL;
369 return context;
373 static ALCboolean pulse_open(pa_threaded_mainloop **loop, pa_context **context,
374 void(*state_cb)(pa_context*,void*), void *ptr)
376 if(!(*loop = pa_threaded_mainloop_new()))
378 ERR("pa_threaded_mainloop_new() failed!\n");
379 return ALC_FALSE;
381 if(pa_threaded_mainloop_start(*loop) < 0)
383 ERR("pa_threaded_mainloop_start() failed\n");
384 goto error;
387 pa_threaded_mainloop_lock(*loop);
389 *context = connect_context(*loop, AL_FALSE);
390 if(!*context)
392 pa_threaded_mainloop_unlock(*loop);
393 pa_threaded_mainloop_stop(*loop);
394 goto error;
396 pa_context_set_state_callback(*context, state_cb, ptr);
398 pa_threaded_mainloop_unlock(*loop);
399 return ALC_TRUE;
401 error:
402 pa_threaded_mainloop_free(*loop);
403 *loop = NULL;
405 return ALC_FALSE;
408 static void pulse_close(pa_threaded_mainloop *loop, pa_context *context, pa_stream *stream)
410 pa_threaded_mainloop_lock(loop);
412 if(stream)
414 pa_stream_set_state_callback(stream, NULL, NULL);
415 pa_stream_set_moved_callback(stream, NULL, NULL);
416 pa_stream_set_write_callback(stream, NULL, NULL);
417 pa_stream_set_buffer_attr_callback(stream, NULL, NULL);
418 pa_stream_disconnect(stream);
419 pa_stream_unref(stream);
422 pa_context_disconnect(context);
423 pa_context_unref(context);
425 pa_threaded_mainloop_unlock(loop);
427 pa_threaded_mainloop_stop(loop);
428 pa_threaded_mainloop_free(loop);
432 typedef struct {
433 al_string name;
434 al_string device_name;
435 } DevMap;
436 TYPEDEF_VECTOR(DevMap, vector_DevMap)
438 static vector_DevMap PlaybackDevices;
439 static vector_DevMap CaptureDevices;
441 static void clear_devlist(vector_DevMap *list)
443 #define DEINIT_STRS(i) (AL_STRING_DEINIT((i)->name),AL_STRING_DEINIT((i)->device_name))
444 VECTOR_FOR_EACH(DevMap, *list, DEINIT_STRS);
445 #undef DEINIT_STRS
446 VECTOR_RESIZE(*list, 0);
450 typedef struct ALCpulsePlayback {
451 DERIVE_FROM_TYPE(ALCbackend);
453 al_string device_name;
455 pa_buffer_attr attr;
456 pa_sample_spec spec;
458 pa_threaded_mainloop *loop;
460 pa_stream *stream;
461 pa_context *context;
463 volatile ALboolean killNow;
464 althrd_t thread;
465 } ALCpulsePlayback;
467 static void ALCpulsePlayback_deviceCallback(pa_context *context, const pa_sink_info *info, int eol, void *pdata);
468 static void ALCpulsePlayback_probeDevices(void);
470 static void ALCpulsePlayback_bufferAttrCallback(pa_stream *stream, void *pdata);
471 static void ALCpulsePlayback_contextStateCallback(pa_context *context, void *pdata);
472 static void ALCpulsePlayback_streamStateCallback(pa_stream *stream, void *pdata);
473 static void ALCpulsePlayback_streamWriteCallback(pa_stream *p, size_t nbytes, void *userdata);
474 static void ALCpulsePlayback_sinkInfoCallback(pa_context *context, const pa_sink_info *info, int eol, void *pdata);
475 static void ALCpulsePlayback_sinkNameCallback(pa_context *context, const pa_sink_info *info, int eol, void *pdata);
476 static void ALCpulsePlayback_streamMovedCallback(pa_stream *stream, void *pdata);
477 static pa_stream *ALCpulsePlayback_connectStream(const char *device_name, pa_threaded_mainloop *loop,
478 pa_context *context, pa_stream_flags_t flags,
479 pa_buffer_attr *attr, pa_sample_spec *spec,
480 pa_channel_map *chanmap);
481 static int ALCpulsePlayback_mixerProc(void *ptr);
483 static void ALCpulsePlayback_Construct(ALCpulsePlayback *self, ALCdevice *device);
484 static void ALCpulsePlayback_Destruct(ALCpulsePlayback *self);
485 static ALCenum ALCpulsePlayback_open(ALCpulsePlayback *self, const ALCchar *name);
486 static void ALCpulsePlayback_close(ALCpulsePlayback *self);
487 static ALCboolean ALCpulsePlayback_reset(ALCpulsePlayback *self);
488 static ALCboolean ALCpulsePlayback_start(ALCpulsePlayback *self);
489 static void ALCpulsePlayback_stop(ALCpulsePlayback *self);
490 static DECLARE_FORWARD2(ALCpulsePlayback, ALCbackend, ALCenum, captureSamples, ALCvoid*, ALCuint)
491 static DECLARE_FORWARD(ALCpulsePlayback, ALCbackend, ALCuint, availableSamples)
492 static ALint64 ALCpulsePlayback_getLatency(ALCpulsePlayback *self);
493 static void ALCpulsePlayback_lock(ALCpulsePlayback *self);
494 static void ALCpulsePlayback_unlock(ALCpulsePlayback *self);
495 DECLARE_DEFAULT_ALLOCATORS(ALCpulsePlayback)
497 DEFINE_ALCBACKEND_VTABLE(ALCpulsePlayback);
500 static void ALCpulsePlayback_Construct(ALCpulsePlayback *self, ALCdevice *device)
502 ALCbackend_Construct(STATIC_CAST(ALCbackend, self), device);
503 SET_VTABLE2(ALCpulsePlayback, ALCbackend, self);
505 AL_STRING_INIT(self->device_name);
508 static void ALCpulsePlayback_Destruct(ALCpulsePlayback *self)
510 AL_STRING_DEINIT(self->device_name);
511 ALCbackend_Destruct(STATIC_CAST(ALCbackend, self));
515 static void ALCpulsePlayback_deviceCallback(pa_context *UNUSED(context), const pa_sink_info *info, int eol, void *pdata)
517 pa_threaded_mainloop *loop = pdata;
518 const DevMap *iter;
519 DevMap entry;
520 int count;
522 if(eol)
524 pa_threaded_mainloop_signal(loop, 0);
525 return;
528 #define MATCH_INFO_NAME(iter) (al_string_cmp_cstr((iter)->device_name, info->name) == 0)
529 VECTOR_FIND_IF(iter, const DevMap, PlaybackDevices, MATCH_INFO_NAME);
530 if(iter != VECTOR_ITER_END(PlaybackDevices)) return;
531 #undef MATCH_INFO_NAME
533 AL_STRING_INIT(entry.name);
534 AL_STRING_INIT(entry.device_name);
536 al_string_copy_cstr(&entry.device_name, info->name);
538 count = 0;
539 while(1)
541 al_string_copy_cstr(&entry.name, info->description);
542 if(count != 0)
544 char str[64];
545 snprintf(str, sizeof(str), " #%d", count+1);
546 al_string_append_cstr(&entry.name, str);
549 #define MATCH_ENTRY(i) (al_string_cmp(entry.name, (i)->name) == 0)
550 VECTOR_FIND_IF(iter, const DevMap, PlaybackDevices, MATCH_ENTRY);
551 if(iter == VECTOR_ITER_END(PlaybackDevices)) break;
552 #undef MATCH_ENTRY
553 count++;
556 TRACE("Got device \"%s\", \"%s\"\n", al_string_get_cstr(entry.name), al_string_get_cstr(entry.device_name));
558 VECTOR_PUSH_BACK(PlaybackDevices, entry);
561 static void ALCpulsePlayback_probeDevices(void)
563 pa_threaded_mainloop *loop;
565 clear_devlist(&PlaybackDevices);
567 if((loop=pa_threaded_mainloop_new()) &&
568 pa_threaded_mainloop_start(loop) >= 0)
570 pa_context *context;
572 pa_threaded_mainloop_lock(loop);
573 context = connect_context(loop, AL_FALSE);
574 if(context)
576 pa_operation *o;
577 pa_stream_flags_t flags;
578 pa_sample_spec spec;
579 pa_stream *stream;
581 flags = PA_STREAM_FIX_FORMAT | PA_STREAM_FIX_RATE |
582 PA_STREAM_FIX_CHANNELS | PA_STREAM_DONT_MOVE;
584 spec.format = PA_SAMPLE_S16NE;
585 spec.rate = 44100;
586 spec.channels = 2;
588 stream = ALCpulsePlayback_connectStream(NULL, loop, context, flags,
589 NULL, &spec, NULL);
590 if(stream)
592 o = pa_context_get_sink_info_by_name(context, pa_stream_get_device_name(stream),
593 ALCpulsePlayback_deviceCallback, loop);
594 wait_for_operation(o, loop);
596 pa_stream_disconnect(stream);
597 pa_stream_unref(stream);
598 stream = NULL;
601 o = pa_context_get_sink_info_list(context, ALCpulsePlayback_deviceCallback, loop);
602 wait_for_operation(o, loop);
604 pa_context_disconnect(context);
605 pa_context_unref(context);
607 pa_threaded_mainloop_unlock(loop);
608 pa_threaded_mainloop_stop(loop);
610 if(loop)
611 pa_threaded_mainloop_free(loop);
615 static void ALCpulsePlayback_bufferAttrCallback(pa_stream *stream, void *pdata)
617 ALCpulsePlayback *self = pdata;
619 self->attr = *pa_stream_get_buffer_attr(stream);
620 TRACE("minreq=%d, tlength=%d, prebuf=%d\n", self->attr.minreq, self->attr.tlength, self->attr.prebuf);
623 static void ALCpulsePlayback_contextStateCallback(pa_context *context, void *pdata)
625 ALCpulsePlayback *self = pdata;
626 if(pa_context_get_state(context) == PA_CONTEXT_FAILED)
628 ERR("Received context failure!\n");
629 aluHandleDisconnect(STATIC_CAST(ALCbackend,self)->mDevice);
631 pa_threaded_mainloop_signal(self->loop, 0);
634 static void ALCpulsePlayback_streamStateCallback(pa_stream *stream, void *pdata)
636 ALCpulsePlayback *self = pdata;
637 if(pa_stream_get_state(stream) == PA_STREAM_FAILED)
639 ERR("Received stream failure!\n");
640 aluHandleDisconnect(STATIC_CAST(ALCbackend,self)->mDevice);
642 pa_threaded_mainloop_signal(self->loop, 0);
645 static void ALCpulsePlayback_streamWriteCallback(pa_stream* UNUSED(p), size_t UNUSED(nbytes), void *pdata)
647 ALCpulsePlayback *self = pdata;
648 pa_threaded_mainloop_signal(self->loop, 0);
651 static void ALCpulsePlayback_sinkInfoCallback(pa_context *UNUSED(context), const pa_sink_info *info, int eol, void *pdata)
653 static const struct {
654 enum DevFmtChannels chans;
655 pa_channel_map map;
656 } chanmaps[] = {
657 { DevFmtX71, { 8, {
658 PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT,
659 PA_CHANNEL_POSITION_FRONT_CENTER, PA_CHANNEL_POSITION_LFE,
660 PA_CHANNEL_POSITION_REAR_LEFT, PA_CHANNEL_POSITION_REAR_RIGHT,
661 PA_CHANNEL_POSITION_SIDE_LEFT, PA_CHANNEL_POSITION_SIDE_RIGHT
662 } } },
663 { DevFmtX61, { 7, {
664 PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT,
665 PA_CHANNEL_POSITION_FRONT_CENTER, PA_CHANNEL_POSITION_LFE,
666 PA_CHANNEL_POSITION_REAR_CENTER,
667 PA_CHANNEL_POSITION_SIDE_LEFT, PA_CHANNEL_POSITION_SIDE_RIGHT
668 } } },
669 { DevFmtX51, { 6, {
670 PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT,
671 PA_CHANNEL_POSITION_FRONT_CENTER, PA_CHANNEL_POSITION_LFE,
672 PA_CHANNEL_POSITION_SIDE_LEFT, PA_CHANNEL_POSITION_SIDE_RIGHT
673 } } },
674 { DevFmtX51Rear, { 6, {
675 PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT,
676 PA_CHANNEL_POSITION_FRONT_CENTER, PA_CHANNEL_POSITION_LFE,
677 PA_CHANNEL_POSITION_REAR_LEFT, PA_CHANNEL_POSITION_REAR_RIGHT
678 } } },
679 { DevFmtQuad, { 4, {
680 PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT,
681 PA_CHANNEL_POSITION_REAR_LEFT, PA_CHANNEL_POSITION_REAR_RIGHT
682 } } },
683 { DevFmtStereo, { 2, {
684 PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT
685 } } },
686 { DevFmtMono, { 1, {PA_CHANNEL_POSITION_MONO} } }
688 ALCpulsePlayback *self = pdata;
689 ALCdevice *device = STATIC_CAST(ALCbackend,self)->mDevice;
690 size_t i;
692 if(eol)
694 pa_threaded_mainloop_signal(self->loop, 0);
695 return;
698 for(i = 0;i < COUNTOF(chanmaps);i++)
700 if(pa_channel_map_superset(&info->channel_map, &chanmaps[i].map))
702 if(!(device->Flags&DEVICE_CHANNELS_REQUEST))
703 device->FmtChans = chanmaps[i].chans;
704 break;
707 if(i == COUNTOF(chanmaps))
709 char chanmap_str[PA_CHANNEL_MAP_SNPRINT_MAX] = "";
710 pa_channel_map_snprint(chanmap_str, sizeof(chanmap_str), &info->channel_map);
711 WARN("Failed to find format for channel map:\n %s\n", chanmap_str);
714 if(info->active_port)
715 TRACE("Active port: %s (%s)\n", info->active_port->name, info->active_port->description);
716 device->IsHeadphones = (info->active_port &&
717 strcmp(info->active_port->name, "analog-output-headphones") == 0 &&
718 device->FmtChans == DevFmtStereo);
721 static void ALCpulsePlayback_sinkNameCallback(pa_context *UNUSED(context), const pa_sink_info *info, int eol, void *pdata)
723 ALCpulsePlayback *self = pdata;
724 ALCdevice *device = STATIC_CAST(ALCbackend,self)->mDevice;
726 if(eol)
728 pa_threaded_mainloop_signal(self->loop, 0);
729 return;
732 al_string_copy_cstr(&device->DeviceName, info->description);
736 static void ALCpulsePlayback_streamMovedCallback(pa_stream *stream, void *pdata)
738 ALCpulsePlayback *self = pdata;
740 al_string_copy_cstr(&self->device_name, pa_stream_get_device_name(stream));
742 TRACE("Stream moved to %s\n", al_string_get_cstr(self->device_name));
746 static pa_stream *ALCpulsePlayback_connectStream(const char *device_name,
747 pa_threaded_mainloop *loop, pa_context *context,
748 pa_stream_flags_t flags, pa_buffer_attr *attr, pa_sample_spec *spec,
749 pa_channel_map *chanmap)
751 pa_stream_state_t state;
752 pa_stream *stream;
754 stream = pa_stream_new_with_proplist(context, "Playback Stream", spec, chanmap, prop_filter);
755 if(!stream)
757 ERR("pa_stream_new_with_proplist() failed: %s\n", pa_strerror(pa_context_errno(context)));
758 return NULL;
761 pa_stream_set_state_callback(stream, stream_state_callback, loop);
763 if(pa_stream_connect_playback(stream, device_name, attr, flags, NULL, NULL) < 0)
765 ERR("Stream did not connect: %s\n", pa_strerror(pa_context_errno(context)));
766 pa_stream_unref(stream);
767 return NULL;
770 while((state=pa_stream_get_state(stream)) != PA_STREAM_READY)
772 if(!PA_STREAM_IS_GOOD(state))
774 ERR("Stream did not get ready: %s\n", pa_strerror(pa_context_errno(context)));
775 pa_stream_unref(stream);
776 return NULL;
779 pa_threaded_mainloop_wait(loop);
781 pa_stream_set_state_callback(stream, NULL, NULL);
783 return stream;
787 static int ALCpulsePlayback_mixerProc(void *ptr)
789 ALCpulsePlayback *self = ptr;
790 ALCdevice *device = STATIC_CAST(ALCbackend,self)->mDevice;
791 ALuint buffer_size;
792 ALint update_size;
793 size_t frame_size;
794 ssize_t len;
796 SetRTPriority();
797 althrd_setname(althrd_current(), MIXER_THREAD_NAME);
799 pa_threaded_mainloop_lock(self->loop);
800 frame_size = pa_frame_size(&self->spec);
801 update_size = device->UpdateSize * frame_size;
803 /* Sanitize buffer metrics, in case we actually have less than what we
804 * asked for. */
805 buffer_size = minu(update_size*device->NumUpdates, self->attr.tlength);
806 update_size = minu(update_size, buffer_size/2);
807 do {
808 len = pa_stream_writable_size(self->stream) - self->attr.tlength +
809 buffer_size;
810 if(len < update_size)
812 if(pa_stream_is_corked(self->stream) == 1)
814 pa_operation *o;
815 o = pa_stream_cork(self->stream, 0, NULL, NULL);
816 if(o) pa_operation_unref(o);
818 pa_threaded_mainloop_wait(self->loop);
819 continue;
821 len -= len%update_size;
823 while(len > 0)
825 size_t newlen = len;
826 void *buf;
827 pa_free_cb_t free_func = NULL;
829 if(pa_stream_begin_write(self->stream, &buf, &newlen) < 0)
831 buf = pa_xmalloc(newlen);
832 free_func = pa_xfree;
835 aluMixData(device, buf, newlen/frame_size);
837 pa_stream_write(self->stream, buf, newlen, free_func, 0, PA_SEEK_RELATIVE);
838 len -= newlen;
840 } while(!self->killNow && device->Connected);
841 pa_threaded_mainloop_unlock(self->loop);
843 return 0;
847 static ALCenum ALCpulsePlayback_open(ALCpulsePlayback *self, const ALCchar *name)
849 const_al_string dev_name = AL_STRING_INIT_STATIC();
850 const char *pulse_name = NULL;
851 pa_stream_flags_t flags;
852 pa_sample_spec spec;
854 if(name)
856 const DevMap *iter;
858 if(VECTOR_SIZE(PlaybackDevices) == 0)
859 ALCpulsePlayback_probeDevices();
861 #define MATCH_NAME(iter) (al_string_cmp_cstr((iter)->name, name) == 0)
862 VECTOR_FIND_IF(iter, const DevMap, PlaybackDevices, MATCH_NAME);
863 #undef MATCH_NAME
864 if(iter == VECTOR_ITER_END(PlaybackDevices))
865 return ALC_INVALID_VALUE;
866 pulse_name = al_string_get_cstr(iter->device_name);
867 dev_name = iter->name;
870 if(!pulse_open(&self->loop, &self->context, ALCpulsePlayback_contextStateCallback, self))
871 return ALC_INVALID_VALUE;
873 pa_threaded_mainloop_lock(self->loop);
875 flags = PA_STREAM_FIX_FORMAT | PA_STREAM_FIX_RATE |
876 PA_STREAM_FIX_CHANNELS;
877 if(!GetConfigValueBool(NULL, "pulse", "allow-moves", 0))
878 flags |= PA_STREAM_DONT_MOVE;
880 spec.format = PA_SAMPLE_S16NE;
881 spec.rate = 44100;
882 spec.channels = 2;
884 TRACE("Connecting to \"%s\"\n", pulse_name ? pulse_name : "(default)");
885 self->stream = ALCpulsePlayback_connectStream(pulse_name, self->loop, self->context,
886 flags, NULL, &spec, NULL);
887 if(!self->stream)
889 pa_threaded_mainloop_unlock(self->loop);
890 pulse_close(self->loop, self->context, self->stream);
891 self->loop = NULL;
892 self->context = NULL;
893 return ALC_INVALID_VALUE;
895 pa_stream_set_moved_callback(self->stream, ALCpulsePlayback_streamMovedCallback, self);
897 al_string_copy_cstr(&self->device_name, pa_stream_get_device_name(self->stream));
898 if(al_string_empty(dev_name))
900 pa_operation *o = pa_context_get_sink_info_by_name(
901 self->context, al_string_get_cstr(self->device_name),
902 ALCpulsePlayback_sinkNameCallback, self
904 wait_for_operation(o, self->loop);
906 else
908 ALCdevice *device = STATIC_CAST(ALCbackend,self)->mDevice;
909 al_string_copy(&device->DeviceName, dev_name);
912 pa_threaded_mainloop_unlock(self->loop);
914 return ALC_NO_ERROR;
917 static void ALCpulsePlayback_close(ALCpulsePlayback *self)
919 pulse_close(self->loop, self->context, self->stream);
920 self->loop = NULL;
921 self->context = NULL;
922 self->stream = NULL;
924 al_string_clear(&self->device_name);
927 static ALCboolean ALCpulsePlayback_reset(ALCpulsePlayback *self)
929 ALCdevice *device = STATIC_CAST(ALCbackend,self)->mDevice;
930 pa_stream_flags_t flags = 0;
931 const char *mapname = NULL;
932 pa_channel_map chanmap;
933 pa_operation *o;
934 ALuint len;
936 pa_threaded_mainloop_lock(self->loop);
938 if(self->stream)
940 pa_stream_set_state_callback(self->stream, NULL, NULL);
941 pa_stream_set_moved_callback(self->stream, NULL, NULL);
942 pa_stream_set_write_callback(self->stream, NULL, NULL);
943 pa_stream_set_buffer_attr_callback(self->stream, NULL, NULL);
944 pa_stream_disconnect(self->stream);
945 pa_stream_unref(self->stream);
946 self->stream = NULL;
949 o = pa_context_get_sink_info_by_name(self->context, al_string_get_cstr(self->device_name),
950 ALCpulsePlayback_sinkInfoCallback, self);
951 wait_for_operation(o, self->loop);
953 if(GetConfigValueBool(al_string_get_cstr(device->DeviceName), "pulse", "fix-rate", 0) ||
954 !(device->Flags&DEVICE_FREQUENCY_REQUEST))
955 flags |= PA_STREAM_FIX_RATE;
956 flags |= PA_STREAM_INTERPOLATE_TIMING | PA_STREAM_AUTO_TIMING_UPDATE;
957 flags |= PA_STREAM_ADJUST_LATENCY;
958 flags |= PA_STREAM_START_CORKED;
959 if(!GetConfigValueBool(NULL, "pulse", "allow-moves", 0))
960 flags |= PA_STREAM_DONT_MOVE;
962 switch(device->FmtType)
964 case DevFmtByte:
965 device->FmtType = DevFmtUByte;
966 /* fall-through */
967 case DevFmtUByte:
968 self->spec.format = PA_SAMPLE_U8;
969 break;
970 case DevFmtUShort:
971 device->FmtType = DevFmtShort;
972 /* fall-through */
973 case DevFmtShort:
974 self->spec.format = PA_SAMPLE_S16NE;
975 break;
976 case DevFmtUInt:
977 device->FmtType = DevFmtInt;
978 /* fall-through */
979 case DevFmtInt:
980 self->spec.format = PA_SAMPLE_S32NE;
981 break;
982 case DevFmtFloat:
983 self->spec.format = PA_SAMPLE_FLOAT32NE;
984 break;
986 self->spec.rate = device->Frequency;
987 self->spec.channels = ChannelsFromDevFmt(device->FmtChans);
989 if(pa_sample_spec_valid(&self->spec) == 0)
991 ERR("Invalid sample format\n");
992 pa_threaded_mainloop_unlock(self->loop);
993 return ALC_FALSE;
996 switch(device->FmtChans)
998 case DevFmtMono:
999 mapname = "mono";
1000 break;
1001 case DevFmtBFormat3D:
1002 device->FmtChans = DevFmtStereo;
1003 /*fall-through*/
1004 case DevFmtStereo:
1005 mapname = "front-left,front-right";
1006 break;
1007 case DevFmtQuad:
1008 mapname = "front-left,front-right,rear-left,rear-right";
1009 break;
1010 case DevFmtX51:
1011 mapname = "front-left,front-right,front-center,lfe,side-left,side-right";
1012 break;
1013 case DevFmtX51Rear:
1014 mapname = "front-left,front-right,front-center,lfe,rear-left,rear-right";
1015 break;
1016 case DevFmtX61:
1017 mapname = "front-left,front-right,front-center,lfe,rear-center,side-left,side-right";
1018 break;
1019 case DevFmtX71:
1020 mapname = "front-left,front-right,front-center,lfe,rear-left,rear-right,side-left,side-right";
1021 break;
1023 if(!pa_channel_map_parse(&chanmap, mapname))
1025 ERR("Failed to build channel map for %s\n", DevFmtChannelsString(device->FmtChans));
1026 pa_threaded_mainloop_unlock(self->loop);
1027 return ALC_FALSE;
1029 SetDefaultWFXChannelOrder(device);
1031 self->attr.fragsize = -1;
1032 self->attr.prebuf = 0;
1033 self->attr.minreq = device->UpdateSize * pa_frame_size(&self->spec);
1034 self->attr.tlength = self->attr.minreq * maxu(device->NumUpdates, 2);
1035 self->attr.maxlength = -1;
1037 self->stream = ALCpulsePlayback_connectStream(al_string_get_cstr(self->device_name),
1038 self->loop, self->context, flags,
1039 &self->attr, &self->spec, &chanmap);
1040 if(!self->stream)
1042 pa_threaded_mainloop_unlock(self->loop);
1043 return ALC_FALSE;
1045 pa_stream_set_state_callback(self->stream, ALCpulsePlayback_streamStateCallback, self);
1046 pa_stream_set_moved_callback(self->stream, ALCpulsePlayback_streamMovedCallback, self);
1047 pa_stream_set_write_callback(self->stream, ALCpulsePlayback_streamWriteCallback, self);
1049 self->spec = *(pa_stream_get_sample_spec(self->stream));
1050 if(device->Frequency != self->spec.rate)
1052 /* Server updated our playback rate, so modify the buffer attribs
1053 * accordingly. */
1054 device->NumUpdates = (ALuint)clampd(
1055 (ALdouble)device->NumUpdates/device->Frequency*self->spec.rate + 0.5, 2.0, 16.0
1058 self->attr.minreq = device->UpdateSize * pa_frame_size(&self->spec);
1059 self->attr.tlength = self->attr.minreq * device->NumUpdates;
1060 self->attr.maxlength = -1;
1061 self->attr.prebuf = 0;
1063 o = pa_stream_set_buffer_attr(self->stream, &self->attr,
1064 stream_success_callback, self->loop);
1065 wait_for_operation(o, self->loop);
1067 device->Frequency = self->spec.rate;
1070 pa_stream_set_buffer_attr_callback(self->stream, ALCpulsePlayback_bufferAttrCallback, self);
1071 ALCpulsePlayback_bufferAttrCallback(self->stream, self);
1073 len = self->attr.minreq / pa_frame_size(&self->spec);
1074 device->NumUpdates = (ALuint)clampd(
1075 (ALdouble)device->NumUpdates/len*device->UpdateSize + 0.5, 2.0, 16.0
1077 device->UpdateSize = len;
1079 /* HACK: prebuf should be 0 as that's what we set it to. However on some
1080 * systems it comes back as non-0, so we have to make sure the device will
1081 * write enough audio to start playback. The lack of manual start control
1082 * may have unintended consequences, but it's better than not starting at
1083 * all.
1085 if(self->attr.prebuf != 0)
1087 len = self->attr.prebuf / pa_frame_size(&self->spec);
1088 if(len <= device->UpdateSize*device->NumUpdates)
1089 ERR("Non-0 prebuf, %u samples (%u bytes), device has %u samples\n",
1090 len, self->attr.prebuf, device->UpdateSize*device->NumUpdates);
1091 else
1093 ERR("Large prebuf, %u samples (%u bytes), increasing device from %u samples",
1094 len, self->attr.prebuf, device->UpdateSize*device->NumUpdates);
1095 device->NumUpdates = (len+device->UpdateSize-1) / device->UpdateSize;
1099 pa_threaded_mainloop_unlock(self->loop);
1100 return ALC_TRUE;
1103 static ALCboolean ALCpulsePlayback_start(ALCpulsePlayback *self)
1105 self->killNow = AL_FALSE;
1106 if(althrd_create(&self->thread, ALCpulsePlayback_mixerProc, self) != althrd_success)
1107 return ALC_FALSE;
1108 return ALC_TRUE;
1111 static void ALCpulsePlayback_stop(ALCpulsePlayback *self)
1113 pa_operation *o;
1114 int res;
1116 if(!self->stream || self->killNow)
1117 return;
1119 self->killNow = AL_TRUE;
1120 /* Signal the main loop in case PulseAudio isn't sending us audio requests
1121 * (e.g. if the device is suspended). We need to lock the mainloop in case
1122 * the mixer is between checking the killNow flag but before waiting for
1123 * the signal.
1125 pa_threaded_mainloop_lock(self->loop);
1126 pa_threaded_mainloop_unlock(self->loop);
1127 pa_threaded_mainloop_signal(self->loop, 0);
1128 althrd_join(self->thread, &res);
1130 pa_threaded_mainloop_lock(self->loop);
1132 o = pa_stream_cork(self->stream, 1, stream_success_callback, self->loop);
1133 wait_for_operation(o, self->loop);
1135 pa_threaded_mainloop_unlock(self->loop);
1139 static ALint64 ALCpulsePlayback_getLatency(ALCpulsePlayback *self)
1141 pa_usec_t latency = 0;
1142 int neg, err;
1144 if((err=pa_stream_get_latency(self->stream, &latency, &neg)) != 0)
1146 /* FIXME: if err = -PA_ERR_NODATA, it means we were called too soon
1147 * after starting the stream and no timing info has been received from
1148 * the server yet. Should we wait, possibly stalling the app, or give a
1149 * dummy value? Either way, it shouldn't be 0. */
1150 if(err != -PA_ERR_NODATA)
1151 ERR("Failed to get stream latency: 0x%x\n", err);
1152 return 0;
1155 if(neg) latency = 0;
1156 return (ALint64)minu64(latency, U64(0x7fffffffffffffff)/1000) * 1000;
1160 static void ALCpulsePlayback_lock(ALCpulsePlayback *self)
1162 pa_threaded_mainloop_lock(self->loop);
1165 static void ALCpulsePlayback_unlock(ALCpulsePlayback *self)
1167 pa_threaded_mainloop_unlock(self->loop);
1171 typedef struct ALCpulseCapture {
1172 DERIVE_FROM_TYPE(ALCbackend);
1174 al_string device_name;
1176 const void *cap_store;
1177 size_t cap_len;
1178 size_t cap_remain;
1180 ALCuint last_readable;
1182 pa_buffer_attr attr;
1183 pa_sample_spec spec;
1185 pa_threaded_mainloop *loop;
1187 pa_stream *stream;
1188 pa_context *context;
1189 } ALCpulseCapture;
1191 static void ALCpulseCapture_deviceCallback(pa_context *context, const pa_source_info *info, int eol, void *pdata);
1192 static void ALCpulseCapture_probeDevices(void);
1194 static void ALCpulseCapture_contextStateCallback(pa_context *context, void *pdata);
1195 static void ALCpulseCapture_streamStateCallback(pa_stream *stream, void *pdata);
1196 static void ALCpulseCapture_sourceNameCallback(pa_context *context, const pa_source_info *info, int eol, void *pdata);
1197 static void ALCpulseCapture_streamMovedCallback(pa_stream *stream, void *pdata);
1198 static pa_stream *ALCpulseCapture_connectStream(const char *device_name,
1199 pa_threaded_mainloop *loop, pa_context *context,
1200 pa_stream_flags_t flags, pa_buffer_attr *attr,
1201 pa_sample_spec *spec, pa_channel_map *chanmap);
1203 static void ALCpulseCapture_Construct(ALCpulseCapture *self, ALCdevice *device);
1204 static void ALCpulseCapture_Destruct(ALCpulseCapture *self);
1205 static ALCenum ALCpulseCapture_open(ALCpulseCapture *self, const ALCchar *name);
1206 static void ALCpulseCapture_close(ALCpulseCapture *self);
1207 static DECLARE_FORWARD(ALCpulseCapture, ALCbackend, ALCboolean, reset)
1208 static ALCboolean ALCpulseCapture_start(ALCpulseCapture *self);
1209 static void ALCpulseCapture_stop(ALCpulseCapture *self);
1210 static ALCenum ALCpulseCapture_captureSamples(ALCpulseCapture *self, ALCvoid *buffer, ALCuint samples);
1211 static ALCuint ALCpulseCapture_availableSamples(ALCpulseCapture *self);
1212 static ALint64 ALCpulseCapture_getLatency(ALCpulseCapture *self);
1213 static void ALCpulseCapture_lock(ALCpulseCapture *self);
1214 static void ALCpulseCapture_unlock(ALCpulseCapture *self);
1215 DECLARE_DEFAULT_ALLOCATORS(ALCpulseCapture)
1217 DEFINE_ALCBACKEND_VTABLE(ALCpulseCapture);
1220 static void ALCpulseCapture_Construct(ALCpulseCapture *self, ALCdevice *device)
1222 ALCbackend_Construct(STATIC_CAST(ALCbackend, self), device);
1223 SET_VTABLE2(ALCpulseCapture, ALCbackend, self);
1225 AL_STRING_INIT(self->device_name);
1228 static void ALCpulseCapture_Destruct(ALCpulseCapture *self)
1230 AL_STRING_DEINIT(self->device_name);
1231 ALCbackend_Destruct(STATIC_CAST(ALCbackend, self));
1235 static void ALCpulseCapture_deviceCallback(pa_context *UNUSED(context), const pa_source_info *info, int eol, void *pdata)
1237 pa_threaded_mainloop *loop = pdata;
1238 const DevMap *iter;
1239 DevMap entry;
1240 int count;
1242 if(eol)
1244 pa_threaded_mainloop_signal(loop, 0);
1245 return;
1248 #define MATCH_INFO_NAME(iter) (al_string_cmp_cstr((iter)->device_name, info->name) == 0)
1249 VECTOR_FIND_IF(iter, const DevMap, CaptureDevices, MATCH_INFO_NAME);
1250 if(iter != VECTOR_ITER_END(CaptureDevices)) return;
1251 #undef MATCH_INFO_NAME
1253 AL_STRING_INIT(entry.name);
1254 AL_STRING_INIT(entry.device_name);
1256 al_string_copy_cstr(&entry.device_name, info->name);
1258 count = 0;
1259 while(1)
1261 al_string_copy_cstr(&entry.name, info->description);
1262 if(count != 0)
1264 char str[64];
1265 snprintf(str, sizeof(str), " #%d", count+1);
1266 al_string_append_cstr(&entry.name, str);
1269 #define MATCH_ENTRY(i) (al_string_cmp(entry.name, (i)->name) == 0)
1270 VECTOR_FIND_IF(iter, const DevMap, CaptureDevices, MATCH_ENTRY);
1271 if(iter == VECTOR_ITER_END(CaptureDevices)) break;
1272 #undef MATCH_ENTRY
1273 count++;
1276 TRACE("Got device \"%s\", \"%s\"\n", al_string_get_cstr(entry.name), al_string_get_cstr(entry.device_name));
1278 VECTOR_PUSH_BACK(CaptureDevices, entry);
1281 static void ALCpulseCapture_probeDevices(void)
1283 pa_threaded_mainloop *loop;
1285 clear_devlist(&CaptureDevices);
1287 if((loop=pa_threaded_mainloop_new()) &&
1288 pa_threaded_mainloop_start(loop) >= 0)
1290 pa_context *context;
1292 pa_threaded_mainloop_lock(loop);
1293 context = connect_context(loop, AL_FALSE);
1294 if(context)
1296 pa_operation *o;
1297 pa_stream_flags_t flags;
1298 pa_sample_spec spec;
1299 pa_stream *stream;
1301 flags = PA_STREAM_FIX_FORMAT | PA_STREAM_FIX_RATE |
1302 PA_STREAM_FIX_CHANNELS | PA_STREAM_DONT_MOVE;
1304 spec.format = PA_SAMPLE_S16NE;
1305 spec.rate = 44100;
1306 spec.channels = 1;
1308 stream = ALCpulseCapture_connectStream(NULL, loop, context, flags,
1309 NULL, &spec, NULL);
1310 if(stream)
1312 o = pa_context_get_source_info_by_name(context, pa_stream_get_device_name(stream),
1313 ALCpulseCapture_deviceCallback, loop);
1314 wait_for_operation(o, loop);
1316 pa_stream_disconnect(stream);
1317 pa_stream_unref(stream);
1318 stream = NULL;
1321 o = pa_context_get_source_info_list(context, ALCpulseCapture_deviceCallback, loop);
1322 wait_for_operation(o, loop);
1324 pa_context_disconnect(context);
1325 pa_context_unref(context);
1327 pa_threaded_mainloop_unlock(loop);
1328 pa_threaded_mainloop_stop(loop);
1330 if(loop)
1331 pa_threaded_mainloop_free(loop);
1335 static void ALCpulseCapture_contextStateCallback(pa_context *context, void *pdata)
1337 ALCpulseCapture *self = pdata;
1338 if(pa_context_get_state(context) == PA_CONTEXT_FAILED)
1340 ERR("Received context failure!\n");
1341 aluHandleDisconnect(STATIC_CAST(ALCbackend,self)->mDevice);
1343 pa_threaded_mainloop_signal(self->loop, 0);
1346 static void ALCpulseCapture_streamStateCallback(pa_stream *stream, void *pdata)
1348 ALCpulseCapture *self = pdata;
1349 if(pa_stream_get_state(stream) == PA_STREAM_FAILED)
1351 ERR("Received stream failure!\n");
1352 aluHandleDisconnect(STATIC_CAST(ALCbackend,self)->mDevice);
1354 pa_threaded_mainloop_signal(self->loop, 0);
1358 static void ALCpulseCapture_sourceNameCallback(pa_context *UNUSED(context), const pa_source_info *info, int eol, void *pdata)
1360 ALCpulseCapture *self = pdata;
1361 ALCdevice *device = STATIC_CAST(ALCbackend,self)->mDevice;
1363 if(eol)
1365 pa_threaded_mainloop_signal(self->loop, 0);
1366 return;
1369 al_string_copy_cstr(&device->DeviceName, info->description);
1373 static void ALCpulseCapture_streamMovedCallback(pa_stream *stream, void *pdata)
1375 ALCpulseCapture *self = pdata;
1377 al_string_copy_cstr(&self->device_name, pa_stream_get_device_name(stream));
1379 TRACE("Stream moved to %s\n", al_string_get_cstr(self->device_name));
1383 static pa_stream *ALCpulseCapture_connectStream(const char *device_name,
1384 pa_threaded_mainloop *loop, pa_context *context,
1385 pa_stream_flags_t flags, pa_buffer_attr *attr, pa_sample_spec *spec,
1386 pa_channel_map *chanmap)
1388 pa_stream_state_t state;
1389 pa_stream *stream;
1391 stream = pa_stream_new_with_proplist(context, "Capture Stream", spec, chanmap, prop_filter);
1392 if(!stream)
1394 ERR("pa_stream_new_with_proplist() failed: %s\n", pa_strerror(pa_context_errno(context)));
1395 return NULL;
1398 pa_stream_set_state_callback(stream, stream_state_callback, loop);
1400 if(pa_stream_connect_record(stream, device_name, attr, flags) < 0)
1402 ERR("Stream did not connect: %s\n", pa_strerror(pa_context_errno(context)));
1403 pa_stream_unref(stream);
1404 return NULL;
1407 while((state=pa_stream_get_state(stream)) != PA_STREAM_READY)
1409 if(!PA_STREAM_IS_GOOD(state))
1411 ERR("Stream did not get ready: %s\n", pa_strerror(pa_context_errno(context)));
1412 pa_stream_unref(stream);
1413 return NULL;
1416 pa_threaded_mainloop_wait(loop);
1418 pa_stream_set_state_callback(stream, NULL, NULL);
1420 return stream;
1424 static ALCenum ALCpulseCapture_open(ALCpulseCapture *self, const ALCchar *name)
1426 ALCdevice *device = STATIC_CAST(ALCbackend,self)->mDevice;
1427 const char *pulse_name = NULL;
1428 pa_stream_flags_t flags = 0;
1429 pa_channel_map chanmap;
1430 ALuint samples;
1432 if(name)
1434 const DevMap *iter;
1436 if(VECTOR_SIZE(CaptureDevices) == 0)
1437 ALCpulseCapture_probeDevices();
1439 #define MATCH_NAME(iter) (al_string_cmp_cstr((iter)->name, name) == 0)
1440 VECTOR_FIND_IF(iter, const DevMap, CaptureDevices, MATCH_NAME);
1441 #undef MATCH_NAME
1442 if(iter == VECTOR_ITER_END(CaptureDevices))
1443 return ALC_INVALID_VALUE;
1444 pulse_name = al_string_get_cstr(iter->device_name);
1445 al_string_copy(&device->DeviceName, iter->name);
1448 if(!pulse_open(&self->loop, &self->context, ALCpulseCapture_contextStateCallback, self))
1449 return ALC_INVALID_VALUE;
1451 pa_threaded_mainloop_lock(self->loop);
1453 self->spec.rate = device->Frequency;
1454 self->spec.channels = ChannelsFromDevFmt(device->FmtChans);
1456 switch(device->FmtType)
1458 case DevFmtUByte:
1459 self->spec.format = PA_SAMPLE_U8;
1460 break;
1461 case DevFmtShort:
1462 self->spec.format = PA_SAMPLE_S16NE;
1463 break;
1464 case DevFmtInt:
1465 self->spec.format = PA_SAMPLE_S32NE;
1466 break;
1467 case DevFmtFloat:
1468 self->spec.format = PA_SAMPLE_FLOAT32NE;
1469 break;
1470 case DevFmtByte:
1471 case DevFmtUShort:
1472 case DevFmtUInt:
1473 ERR("%s capture samples not supported\n", DevFmtTypeString(device->FmtType));
1474 pa_threaded_mainloop_unlock(self->loop);
1475 goto fail;
1478 if(pa_sample_spec_valid(&self->spec) == 0)
1480 ERR("Invalid sample format\n");
1481 pa_threaded_mainloop_unlock(self->loop);
1482 goto fail;
1485 if(!pa_channel_map_init_auto(&chanmap, self->spec.channels, PA_CHANNEL_MAP_WAVEEX))
1487 ERR("Couldn't build map for channel count (%d)!\n", self->spec.channels);
1488 pa_threaded_mainloop_unlock(self->loop);
1489 goto fail;
1492 samples = device->UpdateSize * device->NumUpdates;
1493 samples = maxu(samples, 100 * device->Frequency / 1000);
1495 self->attr.minreq = -1;
1496 self->attr.prebuf = -1;
1497 self->attr.maxlength = samples * pa_frame_size(&self->spec);
1498 self->attr.tlength = -1;
1499 self->attr.fragsize = minu(samples, 50*device->Frequency/1000) *
1500 pa_frame_size(&self->spec);
1502 flags |= PA_STREAM_START_CORKED|PA_STREAM_ADJUST_LATENCY;
1503 if(!GetConfigValueBool(NULL, "pulse", "allow-moves", 0))
1504 flags |= PA_STREAM_DONT_MOVE;
1506 TRACE("Connecting to \"%s\"\n", pulse_name ? pulse_name : "(default)");
1507 self->stream = ALCpulseCapture_connectStream(pulse_name, self->loop, self->context,
1508 flags, &self->attr, &self->spec,
1509 &chanmap);
1510 if(!self->stream)
1512 pa_threaded_mainloop_unlock(self->loop);
1513 goto fail;
1515 pa_stream_set_moved_callback(self->stream, ALCpulseCapture_streamMovedCallback, self);
1516 pa_stream_set_state_callback(self->stream, ALCpulseCapture_streamStateCallback, self);
1518 al_string_copy_cstr(&self->device_name, pa_stream_get_device_name(self->stream));
1519 if(al_string_empty(device->DeviceName))
1521 pa_operation *o = pa_context_get_source_info_by_name(
1522 self->context, al_string_get_cstr(self->device_name),
1523 ALCpulseCapture_sourceNameCallback, self
1525 wait_for_operation(o, self->loop);
1528 pa_threaded_mainloop_unlock(self->loop);
1529 return ALC_NO_ERROR;
1531 fail:
1532 pulse_close(self->loop, self->context, self->stream);
1533 self->loop = NULL;
1534 self->context = NULL;
1535 self->stream = NULL;
1537 return ALC_INVALID_VALUE;
1540 static void ALCpulseCapture_close(ALCpulseCapture *self)
1542 pulse_close(self->loop, self->context, self->stream);
1543 self->loop = NULL;
1544 self->context = NULL;
1545 self->stream = NULL;
1547 al_string_clear(&self->device_name);
1550 static ALCboolean ALCpulseCapture_start(ALCpulseCapture *self)
1552 pa_operation *o;
1553 o = pa_stream_cork(self->stream, 0, stream_success_callback, self->loop);
1554 wait_for_operation(o, self->loop);
1556 return ALC_TRUE;
1559 static void ALCpulseCapture_stop(ALCpulseCapture *self)
1561 pa_operation *o;
1562 o = pa_stream_cork(self->stream, 1, stream_success_callback, self->loop);
1563 wait_for_operation(o, self->loop);
1566 static ALCenum ALCpulseCapture_captureSamples(ALCpulseCapture *self, ALCvoid *buffer, ALCuint samples)
1568 ALCdevice *device = STATIC_CAST(ALCbackend,self)->mDevice;
1569 ALCuint todo = samples * pa_frame_size(&self->spec);
1571 /* Capture is done in fragment-sized chunks, so we loop until we get all
1572 * that's available */
1573 self->last_readable -= todo;
1574 while(todo > 0)
1576 size_t rem = todo;
1578 if(self->cap_len == 0)
1580 pa_stream_state_t state;
1582 state = pa_stream_get_state(self->stream);
1583 if(!PA_STREAM_IS_GOOD(state))
1585 aluHandleDisconnect(device);
1586 break;
1588 if(pa_stream_peek(self->stream, &self->cap_store, &self->cap_len) < 0)
1590 ERR("pa_stream_peek() failed: %s\n",
1591 pa_strerror(pa_context_errno(self->context)));
1592 aluHandleDisconnect(device);
1593 break;
1595 self->cap_remain = self->cap_len;
1597 if(rem > self->cap_remain)
1598 rem = self->cap_remain;
1600 memcpy(buffer, self->cap_store, rem);
1602 buffer = (ALbyte*)buffer + rem;
1603 todo -= rem;
1605 self->cap_store = (ALbyte*)self->cap_store + rem;
1606 self->cap_remain -= rem;
1607 if(self->cap_remain == 0)
1609 pa_stream_drop(self->stream);
1610 self->cap_len = 0;
1613 if(todo > 0)
1614 memset(buffer, ((device->FmtType==DevFmtUByte) ? 0x80 : 0), todo);
1616 return ALC_NO_ERROR;
1619 static ALCuint ALCpulseCapture_availableSamples(ALCpulseCapture *self)
1621 ALCdevice *device = STATIC_CAST(ALCbackend,self)->mDevice;
1622 size_t readable = self->cap_remain;
1624 if(device->Connected)
1626 ssize_t got = pa_stream_readable_size(self->stream);
1627 if(got < 0)
1629 ERR("pa_stream_readable_size() failed: %s\n", pa_strerror(got));
1630 aluHandleDisconnect(device);
1632 else if((size_t)got > self->cap_len)
1633 readable += got - self->cap_len;
1636 if(self->last_readable < readable)
1637 self->last_readable = readable;
1638 return self->last_readable / pa_frame_size(&self->spec);
1642 static ALint64 ALCpulseCapture_getLatency(ALCpulseCapture *self)
1644 pa_usec_t latency = 0;
1645 int neg;
1647 if(pa_stream_get_latency(self->stream, &latency, &neg) != 0)
1649 ERR("Failed to get stream latency!\n");
1650 return 0;
1653 if(neg) latency = 0;
1654 return (ALint64)minu64(latency, U64(0x7fffffffffffffff)/1000) * 1000;
1658 static void ALCpulseCapture_lock(ALCpulseCapture *self)
1660 pa_threaded_mainloop_lock(self->loop);
1663 static void ALCpulseCapture_unlock(ALCpulseCapture *self)
1665 pa_threaded_mainloop_unlock(self->loop);
1669 typedef struct ALCpulseBackendFactory {
1670 DERIVE_FROM_TYPE(ALCbackendFactory);
1671 } ALCpulseBackendFactory;
1672 #define ALCPULSEBACKENDFACTORY_INITIALIZER { { GET_VTABLE2(ALCpulseBackendFactory, ALCbackendFactory) } }
1674 static ALCboolean ALCpulseBackendFactory_init(ALCpulseBackendFactory *self);
1675 static void ALCpulseBackendFactory_deinit(ALCpulseBackendFactory *self);
1676 static ALCboolean ALCpulseBackendFactory_querySupport(ALCpulseBackendFactory *self, ALCbackend_Type type);
1677 static void ALCpulseBackendFactory_probe(ALCpulseBackendFactory *self, enum DevProbe type);
1678 static ALCbackend* ALCpulseBackendFactory_createBackend(ALCpulseBackendFactory *self, ALCdevice *device, ALCbackend_Type type);
1680 DEFINE_ALCBACKENDFACTORY_VTABLE(ALCpulseBackendFactory);
1683 static ALCboolean ALCpulseBackendFactory_init(ALCpulseBackendFactory* UNUSED(self))
1685 ALCboolean ret = ALC_FALSE;
1687 VECTOR_INIT(PlaybackDevices);
1688 VECTOR_INIT(CaptureDevices);
1690 if(pulse_load())
1692 pa_threaded_mainloop *loop;
1694 pulse_ctx_flags = 0;
1695 if(!GetConfigValueBool(NULL, "pulse", "spawn-server", 1))
1696 pulse_ctx_flags |= PA_CONTEXT_NOAUTOSPAWN;
1698 if((loop=pa_threaded_mainloop_new()) &&
1699 pa_threaded_mainloop_start(loop) >= 0)
1701 pa_context *context;
1703 pa_threaded_mainloop_lock(loop);
1704 context = connect_context(loop, AL_TRUE);
1705 if(context)
1707 ret = ALC_TRUE;
1709 /* Some libraries (Phonon, Qt) set some pulseaudio properties
1710 * through environment variables, which causes all streams in
1711 * the process to inherit them. This attempts to filter those
1712 * properties out by setting them to 0-length data. */
1713 prop_filter = pa_proplist_new();
1714 pa_proplist_set(prop_filter, PA_PROP_MEDIA_ROLE, NULL, 0);
1715 pa_proplist_set(prop_filter, "phonon.streamid", NULL, 0);
1717 pa_context_disconnect(context);
1718 pa_context_unref(context);
1720 pa_threaded_mainloop_unlock(loop);
1721 pa_threaded_mainloop_stop(loop);
1723 if(loop)
1724 pa_threaded_mainloop_free(loop);
1727 return ret;
1730 static void ALCpulseBackendFactory_deinit(ALCpulseBackendFactory* UNUSED(self))
1732 clear_devlist(&PlaybackDevices);
1733 VECTOR_DEINIT(PlaybackDevices);
1735 clear_devlist(&CaptureDevices);
1736 VECTOR_DEINIT(CaptureDevices);
1738 if(prop_filter)
1739 pa_proplist_free(prop_filter);
1740 prop_filter = NULL;
1742 /* PulseAudio doesn't like being CloseLib'd sometimes */
1745 static ALCboolean ALCpulseBackendFactory_querySupport(ALCpulseBackendFactory* UNUSED(self), ALCbackend_Type type)
1747 if(type == ALCbackend_Playback || type == ALCbackend_Capture)
1748 return ALC_TRUE;
1749 return ALC_FALSE;
1752 static void ALCpulseBackendFactory_probe(ALCpulseBackendFactory* UNUSED(self), enum DevProbe type)
1754 switch(type)
1756 case ALL_DEVICE_PROBE:
1757 ALCpulsePlayback_probeDevices();
1758 #define APPEND_ALL_DEVICES_LIST(e) AppendAllDevicesList(al_string_get_cstr((e)->name))
1759 VECTOR_FOR_EACH(const DevMap, PlaybackDevices, APPEND_ALL_DEVICES_LIST);
1760 #undef APPEND_ALL_DEVICES_LIST
1761 break;
1763 case CAPTURE_DEVICE_PROBE:
1764 ALCpulseCapture_probeDevices();
1765 #define APPEND_CAPTURE_DEVICE_LIST(e) AppendCaptureDeviceList(al_string_get_cstr((e)->name))
1766 VECTOR_FOR_EACH(const DevMap, CaptureDevices, APPEND_CAPTURE_DEVICE_LIST);
1767 #undef APPEND_CAPTURE_DEVICE_LIST
1768 break;
1772 static ALCbackend* ALCpulseBackendFactory_createBackend(ALCpulseBackendFactory* UNUSED(self), ALCdevice *device, ALCbackend_Type type)
1774 if(type == ALCbackend_Playback)
1776 ALCpulsePlayback *backend;
1777 NEW_OBJ(backend, ALCpulsePlayback)(device);
1778 if(!backend) return NULL;
1779 return STATIC_CAST(ALCbackend, backend);
1781 if(type == ALCbackend_Capture)
1783 ALCpulseCapture *backend;
1784 NEW_OBJ(backend, ALCpulseCapture)(device);
1785 if(!backend) return NULL;
1786 return STATIC_CAST(ALCbackend, backend);
1789 return NULL;
1793 #else /* PA_API_VERSION == 12 */
1795 #warning "Unsupported API version, backend will be unavailable!"
1797 typedef struct ALCpulseBackendFactory {
1798 DERIVE_FROM_TYPE(ALCbackendFactory);
1799 } ALCpulseBackendFactory;
1800 #define ALCPULSEBACKENDFACTORY_INITIALIZER { { GET_VTABLE2(ALCpulseBackendFactory, ALCbackendFactory) } }
1802 static ALCboolean ALCpulseBackendFactory_init(ALCpulseBackendFactory* UNUSED(self))
1804 return ALC_FALSE;
1807 static void ALCpulseBackendFactory_deinit(ALCpulseBackendFactory* UNUSED(self))
1811 static ALCboolean ALCpulseBackendFactory_querySupport(ALCpulseBackendFactory* UNUSED(self), ALCbackend_Type UNUSED(type))
1813 return ALC_FALSE;
1816 static void ALCpulseBackendFactory_probe(ALCpulseBackendFactory* UNUSED(self), enum DevProbe UNUSED(type))
1820 static ALCbackend* ALCpulseBackendFactory_createBackend(ALCpulseBackendFactory* UNUSED(self), ALCdevice* UNUSED(device), ALCbackend_Type UNUSED(type))
1822 return NULL;
1825 DEFINE_ALCBACKENDFACTORY_VTABLE(ALCpulseBackendFactory);
1827 #endif /* PA_API_VERSION == 12 */
1829 ALCbackendFactory *ALCpulseBackendFactory_getFactory(void)
1831 static ALCpulseBackendFactory factory = ALCPULSEBACKENDFACTORY_INITIALIZER;
1832 return STATIC_CAST(ALCbackendFactory, &factory);