1 /*****************************************************************************
2 * pulse.c : Pulseaudio output plugin for vlc
3 *****************************************************************************
4 * Copyright (C) 2008 the VideoLAN team
5 * Copyright (C) 2009-2011 RĂ©mi Denis-Courmont
7 * Authors: Martin Hamrle <hamrle @ post . cz>
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22 *****************************************************************************/
28 #include <vlc_common.h>
29 #include <vlc_plugin.h>
33 #include <pulse/pulseaudio.h>
35 static int Open ( vlc_object_t * );
36 static void Close ( vlc_object_t * );
39 set_shortname( "PulseAudio" )
40 set_description( N_("Pulseaudio audio output") )
41 set_capability( "audio output", 160 )
42 set_category( CAT_AUDIO )
43 set_subcategory( SUBCAT_AUDIO_AOUT )
44 add_shortcut( "pulseaudio", "pa" )
45 set_callbacks( Open, Close )
48 /* TODO: single static mainloop */
51 * Be careful what you do when the PulseAudio mainloop is held, which is to say
52 * within PulseAudio callbacks, or after pa_threaded_mainloop_lock().
53 * In particular, a VLC variable callback cannot be triggered nor deleted with
54 * the PulseAudio mainloop lock held, if the callback acquires the lock. */
58 pa_stream *stream; /**< PulseAudio playback stream object */
59 pa_context *context; /**< PulseAudio connection context */
60 pa_threaded_mainloop *mainloop; /**< PulseAudio event loop */
61 pa_volume_t base_volume; /**< 0dB reference volume */
62 pa_cvolume cvolume; /**< actual sink input volume */
63 //uint32_t byterate; /**< bytes per second */
67 static void context_state_cb(pa_context *c, void *userdata)
69 pa_threaded_mainloop *mainloop = userdata;
71 switch (pa_context_get_state(c)) {
72 case PA_CONTEXT_READY:
73 case PA_CONTEXT_FAILED:
74 case PA_CONTEXT_TERMINATED:
75 pa_threaded_mainloop_signal(mainloop, 0);
81 static bool context_wait(pa_threaded_mainloop *mainloop, pa_context *context)
83 pa_context_state_t state;
85 while ((state = pa_context_get_state(context)) != PA_CONTEXT_READY) {
86 if (state == PA_CONTEXT_FAILED || state == PA_CONTEXT_TERMINATED)
88 pa_threaded_mainloop_wait(mainloop);
93 static void error(aout_instance_t *aout, const char *msg, pa_context *context)
95 msg_Err(aout, "%s: %s", msg, pa_strerror(pa_context_errno(context)));
99 static void sink_list_cb(pa_context *c, const pa_sink_info *i, int eol,
102 aout_instance_t *aout = userdata;
103 vlc_value_t val, text;
109 msg_Dbg(aout, "listing sink %s (%"PRIu32"): %s", i->name, i->index,
111 val.i_int = i->index;
112 text.psz_string = (char *)i->description;
113 var_Change(aout, "audio-device", VLC_VAR_ADDCHOICE, &val, &text);
116 static void sink_info_cb(pa_context *c, const pa_sink_info *i, int eol,
119 aout_instance_t *aout = userdata;
120 aout_sys_t *sys = aout->output.p_sys;
126 /* PulseAudio flat volume NORM / 100% / 0dB corresponds to no software
127 * amplification and maximum hardware amplification.
128 * VLC maps DEFAULT / 100% to no gain at all (software/hardware).
129 * Thus we need to use the sink base_volume as a multiplier,
130 * if and only if flat volume is active for our current sink. */
131 if (i->flags & PA_SINK_FLAT_VOLUME)
132 sys->base_volume = i->base_volume;
134 sys->base_volume = PA_VOLUME_NORM;
135 msg_Dbg(aout, "base volume: %f", pa_sw_volume_to_linear(sys->base_volume));
139 static void stream_state_cb(pa_stream *s, void *userdata)
141 pa_threaded_mainloop *mainloop = userdata;
143 switch (pa_stream_get_state(s)) {
144 case PA_STREAM_READY:
145 case PA_STREAM_FAILED:
146 case PA_STREAM_TERMINATED:
147 pa_threaded_mainloop_signal(mainloop, 0);
153 static void stream_moved_cb(pa_stream *s, void *userdata)
155 aout_instance_t *aout = userdata;
156 aout_sys_t *sys = aout->output.p_sys;
158 uint32_t idx = pa_stream_get_device_index(s);
160 msg_Dbg(aout, "connected to sink %"PRIu32": %s", idx,
161 pa_stream_get_device_name(s));
162 op = pa_context_get_sink_info_by_index(sys->context, idx,
164 if (likely(op != NULL))
165 pa_operation_unref(op);
167 /* Update the variable if someone else moved our stream */
168 var_Change(aout, "audio-device", VLC_VAR_SETVALUE,
169 &(vlc_value_t){ .i_int = idx }, NULL);
172 static void stream_overflow_cb(pa_stream *s, void *userdata)
174 aout_instance_t *aout = userdata;
176 msg_Err(aout, "overflow");
180 static void stream_started_cb(pa_stream *s, void *userdata)
182 aout_instance_t *aout = userdata;
184 msg_Dbg(aout, "started");
188 static void stream_suspended_cb(pa_stream *s, void *userdata)
190 aout_instance_t *aout = userdata;
192 msg_Dbg(aout, "suspended");
196 static void stream_underflow_cb(pa_stream *s, void *userdata)
198 aout_instance_t *aout = userdata;
200 msg_Dbg(aout, "underflow");
204 static int stream_wait(pa_threaded_mainloop *mainloop, pa_stream *stream)
206 pa_stream_state_t state;
208 while ((state = pa_stream_get_state(stream)) != PA_STREAM_READY) {
209 if (state == PA_STREAM_FAILED || state == PA_STREAM_TERMINATED)
211 pa_threaded_mainloop_wait(mainloop);
216 /* Memory free callback. The block_t address is in front of the data. */
217 static void data_free(void *data)
219 block_t **pp = data, *block;
221 memcpy(&block, pp - 1, sizeof (block));
222 block_Release(block);
225 static void *data_convert(block_t **pp)
227 block_t *block = *pp;
228 /* In most cases, there is enough head room, and this is really cheap: */
229 block = block_Realloc(block, sizeof (block), block->i_buffer);
231 if (unlikely(block == NULL))
234 memcpy(block->p_buffer, &block, sizeof (block));
235 block->p_buffer += sizeof (block);
236 block->i_buffer -= sizeof (block);
237 return block->p_buffer;
240 /*****************************************************************************
241 * Play: play a sound samples buffer
242 *****************************************************************************/
243 static void Play(aout_instance_t *aout)
245 aout_sys_t *sys = aout->output.p_sys;
246 pa_stream *s = sys->stream;
248 /* Note: The core already holds the output FIFO lock at this point.
249 * Therefore we must not under any circumstances (try to) acquire the
250 * output FIFO lock while the PulseAudio threaded main loop lock is held
251 * (including from PulseAudio stream callbacks). Otherwise lock inversion
252 * will take place, and sooner or later a deadlock. */
253 pa_threaded_mainloop_lock(sys->mainloop);
255 if (pa_stream_is_corked(sys->stream) > 0) {
256 pa_operation *op = pa_stream_cork(s, 0, NULL, NULL);
258 pa_operation_unref(op);
259 msg_Dbg(aout, "uncorking");
263 /* This function should be called by the LibVLC core a header of time,
264 * but not more than AOUT_MAX_PREPARE. The PulseAudio latency should be
265 * shorter than that (though it might not be the case with some evil piece
266 * of audio output hardware). So we may need to trigger playback early,
267 * (that is to say, short cut the PulseAudio prebuffering). Otherwise,
268 * audio and video may be out of synchronization. */
271 if (pa_stream_get_latency(s, &latency, &negative) < 0) {
272 /* Especially at start of stream, latency may not be known (yet). */
273 if (pa_context_errno(sys->context) != PA_ERR_NODATA)
274 error(aout, "cannot determine latency", sys->context);
276 mtime_t gap = aout_FifoFirstDate(aout, &aout->output.fifo) - mdate()
279 if (gap > AOUT_PTS_TOLERANCE)
280 msg_Dbg(aout, "buffer too early (%"PRId64" us)", gap);
281 else if (gap < -AOUT_PTS_TOLERANCE)
282 msg_Err(aout, "buffer too late (%"PRId64" us)", -gap);
285 #if 0 /* Fault injector to test underrun recovery */
286 static unsigned u = 0;
287 if ((++u % 500) == 0) {
288 msg_Err(aout, "fault injection");
289 msleep(CLOCK_FREQ*2);
293 /* This function is called exactly once per block in the output FIFO, so
294 * this for-loop is not necessary.
295 * If this function is changed to not always dequeue blocks, be sure to
296 * limit the queue size to a reasonable limit to avoid huge leaks. */
298 block_t *block = aout_FifoPop(aout, &aout->output.fifo);
302 const void *ptr = data_convert(&block);
303 if (unlikely(ptr == NULL))
306 size_t len = block->i_buffer;
307 //mtime_t pts = block->i_pts, duration = block->i_length;
309 if (pa_stream_write(s, ptr, len, data_free, 0, PA_SEEK_RELATIVE) < 0)
311 error(aout, "cannot write", sys->context);
312 block_Release(block);
316 pa_threaded_mainloop_unlock(sys->mainloop);
319 static int VolumeSet(aout_instance_t *aout, audio_volume_t vol, bool mute)
321 aout_sys_t *sys = aout->output.p_sys;
322 pa_threaded_mainloop *mainloop = sys->mainloop;
325 uint32_t idx = pa_stream_get_index(sys->stream);
326 pa_volume_t volume = pa_sw_volume_from_linear(vol / (float)AOUT_VOLUME_DEFAULT);
329 /* TODO: do not ruin the channel balance (if set outside VLC) */
330 /* TODO: notify UI about volume changes by other PulseAudio clients */
331 pa_cvolume_set(&sys->cvolume, sys->cvolume.channels, volume);
332 pa_sw_cvolume_multiply_scalar(&cvolume, &sys->cvolume, sys->base_volume);
333 assert(pa_cvolume_valid(&cvolume));
335 pa_threaded_mainloop_lock(mainloop);
336 op = pa_context_set_sink_input_volume(sys->context, idx, &cvolume, NULL, NULL);
337 if (likely(op != NULL))
338 pa_operation_unref(op);
339 op = pa_context_set_sink_input_mute(sys->context, idx, mute, NULL, NULL);
340 if (likely(op != NULL))
341 pa_operation_unref(op);
342 pa_threaded_mainloop_unlock(mainloop);
347 static int StreamMove(vlc_object_t *obj, const char *varname, vlc_value_t old,
348 vlc_value_t val, void *userdata)
350 aout_instance_t *aout = (aout_instance_t *)obj;
351 aout_sys_t *sys = aout->output.p_sys;
352 pa_stream *s = userdata;
354 uint32_t idx = pa_stream_get_index(s);
355 uint32_t sink_idx = val.i_int;
357 (void) varname; (void) old;
359 pa_threaded_mainloop_lock(sys->mainloop);
360 op = pa_context_move_sink_input_by_index(sys->context, idx, sink_idx,
362 if (likely(op != NULL)) {
363 pa_operation_unref(op);
364 msg_Dbg(aout, "moving to sink %"PRIu32, sink_idx);
366 error(aout, "cannot move sink", sys->context);
367 pa_threaded_mainloop_unlock(sys->mainloop);
369 return (op != NULL) ? VLC_SUCCESS : VLC_EGENERIC;
373 /*****************************************************************************
374 * Open: open the audio device
375 *****************************************************************************/
376 static int Open(vlc_object_t *obj)
378 aout_instance_t *aout = (aout_instance_t *)obj;
381 /* Sample format specification */
382 struct pa_sample_spec ss;
384 switch(aout->output.output.i_format)
387 aout->output.output.i_format = VLC_CODEC_F32B;
389 ss.format = PA_SAMPLE_FLOAT32BE;
392 aout->output.output.i_format = VLC_CODEC_F32L;
394 ss.format = PA_SAMPLE_FLOAT32LE;
397 aout->output.output.i_format = VLC_CODEC_FL32;
398 ss.format = PA_SAMPLE_FLOAT32NE;
401 ss.format = PA_SAMPLE_S32BE;
404 ss.format = PA_SAMPLE_S32LE;
407 ss.format = PA_SAMPLE_S24BE;
410 ss.format = PA_SAMPLE_S24LE;
413 ss.format = PA_SAMPLE_S16BE;
416 ss.format = PA_SAMPLE_S16LE;
419 aout->output.output.i_format = VLC_CODEC_U8;
421 ss.format = PA_SAMPLE_U8;
426 aout->output.output.i_format = VLC_CODEC_FL32;
427 ss.format = PA_SAMPLE_FLOAT32NE;
431 aout->output.output.i_format = VLC_CODEC_S16N;
432 ss.format = PA_SAMPLE_S16NE;
437 ss.rate = aout->output.output.i_rate;
438 ss.channels = aout_FormatNbChannels(&aout->output.output);
439 if (!pa_sample_spec_valid(&ss)) {
440 msg_Err(aout, "unsupported sample specification");
444 /* Channel mapping (order defined in vlc_aout.h) */
445 struct pa_channel_map map;
448 if (aout->output.output.i_physical_channels & AOUT_CHAN_LEFT)
449 map.map[map.channels++] = PA_CHANNEL_POSITION_FRONT_LEFT;
450 if (aout->output.output.i_physical_channels & AOUT_CHAN_RIGHT)
451 map.map[map.channels++] = PA_CHANNEL_POSITION_FRONT_RIGHT;
452 if (aout->output.output.i_physical_channels & AOUT_CHAN_MIDDLELEFT)
453 map.map[map.channels++] = PA_CHANNEL_POSITION_SIDE_LEFT;
454 if (aout->output.output.i_physical_channels & AOUT_CHAN_MIDDLERIGHT)
455 map.map[map.channels++] = PA_CHANNEL_POSITION_SIDE_RIGHT;
456 if (aout->output.output.i_physical_channels & AOUT_CHAN_REARLEFT)
457 map.map[map.channels++] = PA_CHANNEL_POSITION_REAR_LEFT;
458 if (aout->output.output.i_physical_channels & AOUT_CHAN_REARRIGHT)
459 map.map[map.channels++] = PA_CHANNEL_POSITION_REAR_RIGHT;
460 if (aout->output.output.i_physical_channels & AOUT_CHAN_REARCENTER)
461 map.map[map.channels++] = PA_CHANNEL_POSITION_REAR_CENTER;
462 if (aout->output.output.i_physical_channels & AOUT_CHAN_CENTER)
464 if (ss.channels == 1)
465 map.map[map.channels++] = PA_CHANNEL_POSITION_MONO;
467 map.map[map.channels++] = PA_CHANNEL_POSITION_FRONT_CENTER;
469 if (aout->output.output.i_physical_channels & AOUT_CHAN_LFE)
470 map.map[map.channels++] = PA_CHANNEL_POSITION_LFE;
472 for (unsigned i = 0; map.channels < ss.channels; i++) {
473 map.map[map.channels++] = PA_CHANNEL_POSITION_AUX0 + i;
474 msg_Warn(aout, "mapping channel %"PRIu8" to AUX%u", map.channels, i);
477 if (!pa_channel_map_valid(&map)) {
478 msg_Err(aout, "unsupported channel map");
481 const char *name = pa_channel_map_to_pretty_name(&map);
482 msg_Dbg(aout, "using %s channel map", (name != NULL) ? name : "?");
485 /* Stream parameters */
486 const pa_stream_flags_t flags = PA_STREAM_INTERPOLATE_TIMING
487 | PA_STREAM_AUTO_TIMING_UPDATE
488 | PA_STREAM_ADJUST_LATENCY
489 | PA_STREAM_START_CORKED;
491 const uint32_t byterate = pa_bytes_per_second(&ss);
492 struct pa_buffer_attr attr;
493 /* no point in larger buffers on PA side than VLC */
495 attr.tlength = byterate * AOUT_MAX_ADVANCE_TIME / CLOCK_FREQ;
496 attr.prebuf = byterate * AOUT_MAX_PREPARE_TIME / CLOCK_FREQ;
498 attr.fragsize = 0; /* not used for output */
500 /* Allocate structures */
501 aout_sys_t *sys = malloc(sizeof(*sys));
502 if (unlikely(sys == NULL))
504 aout->output.p_sys = sys;
507 //sys->byterate = byterate;
510 sys->base_volume = PA_VOLUME_NORM;
511 pa_cvolume_set(&sys->cvolume, ss.channels, PA_VOLUME_NORM);
513 /* Allocate threaded main loop */
514 pa_threaded_mainloop *mainloop = pa_threaded_mainloop_new();
515 if (unlikely(mainloop == NULL)) {
519 sys->mainloop = mainloop;
521 if (pa_threaded_mainloop_start(mainloop) < 0) {
522 pa_threaded_mainloop_free(mainloop);
526 pa_threaded_mainloop_lock(mainloop);
528 /* Connect to PulseAudio server */
529 char *user_agent = var_InheritString(aout, "user-agent");
530 pa_context *ctx = pa_context_new(pa_threaded_mainloop_get_api(mainloop),
533 if (unlikely(ctx == NULL))
537 pa_context_set_state_callback(ctx, context_state_cb, mainloop);
538 if (pa_context_connect(ctx, NULL, 0, NULL) < 0
539 || context_wait(mainloop, ctx)) {
540 error(aout, "cannot connect to server", ctx);
544 /* Create a playback stream */
545 pa_stream *s = pa_stream_new(ctx, "audio stream", &ss, &map);
547 error(aout, "cannot create stream", ctx);
551 pa_stream_set_state_callback(s, stream_state_cb, mainloop);
552 pa_stream_set_moved_callback(s, stream_moved_cb, aout);
553 pa_stream_set_overflow_callback(s, stream_overflow_cb, aout);
554 pa_stream_set_started_callback(s, stream_started_cb, aout);
555 pa_stream_set_suspended_callback(s, stream_suspended_cb, aout);
556 pa_stream_set_underflow_callback(s, stream_underflow_cb, aout);
558 if (pa_stream_connect_playback(s, NULL, &attr, flags, NULL, NULL) < 0
559 || stream_wait(mainloop, s)) {
560 error(aout, "cannot connect stream", ctx);
564 const struct pa_buffer_attr *pba = pa_stream_get_buffer_attr(s);
565 msg_Dbg(aout, "using buffer metrics: maxlength=%u, tlength=%u, "
566 "prebuf=%u, minreq=%u",
567 pba->maxlength, pba->tlength, pba->prebuf, pba->minreq);
569 aout->output.i_nb_samples = pba->minreq / pa_frame_size(&ss);
571 var_Create(aout, "audio-device", VLC_VAR_INTEGER|VLC_VAR_HASCHOICE);
572 var_Change(aout, "audio-device", VLC_VAR_SETTEXT,
573 &(vlc_value_t){ .psz_string = (char *)_("Audio device") },
575 var_AddCallback (aout, "audio-device", StreamMove, s);
576 op = pa_context_get_sink_info_list(ctx, sink_list_cb, aout);
577 /* We may need to wait for completion... once LibVLC supports this */
579 pa_operation_unref(op);
580 stream_moved_cb(s, aout);
581 pa_threaded_mainloop_unlock(mainloop);
583 aout->output.pf_play = Play;
584 aout->output.pf_volume_set = VolumeSet;
588 pa_threaded_mainloop_unlock(mainloop);
593 /*****************************************************************************
594 * Close: close the audio device
595 *****************************************************************************/
596 static void Close (vlc_object_t *obj)
598 aout_instance_t *aout = (aout_instance_t *)obj;
599 aout_sys_t *sys = aout->output.p_sys;
600 pa_threaded_mainloop *mainloop = sys->mainloop;
601 pa_context *ctx = sys->context;
602 pa_stream *s = sys->stream;
605 /* The callback takes mainloop lock, so it CANNOT be held here! */
606 var_DelCallback (aout, "audio-device", StreamMove, s);
607 var_Destroy (aout, "audio-device");
610 pa_threaded_mainloop_lock(mainloop);
614 op = pa_stream_flush(s, NULL, NULL);
616 pa_operation_unref(op);
617 op = pa_stream_drain(s, NULL, NULL);
619 pa_operation_unref(op);
620 pa_stream_disconnect(s);
624 pa_context_unref(ctx);
625 pa_threaded_mainloop_unlock(mainloop);
626 pa_threaded_mainloop_free(mainloop);