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 */
52 pa_stream *stream; /**< PulseAudio playback stream object */
53 pa_context *context; /**< PulseAudio connection context */
54 pa_threaded_mainloop *mainloop; /**< PulseAudio event loop */
55 pa_volume_t base_volume; /**< 0dB reference volume */
56 pa_cvolume cvolume; /**< actual sink input volume */
57 //uint32_t byterate; /**< bytes per second */
61 static void context_state_cb(pa_context *c, void *userdata)
63 pa_threaded_mainloop *mainloop = userdata;
65 switch (pa_context_get_state(c)) {
66 case PA_CONTEXT_READY:
67 case PA_CONTEXT_FAILED:
68 case PA_CONTEXT_TERMINATED:
69 pa_threaded_mainloop_signal(mainloop, 0);
75 static bool context_wait(pa_threaded_mainloop *mainloop, pa_context *context)
77 pa_context_state_t state;
79 while ((state = pa_context_get_state(context)) != PA_CONTEXT_READY) {
80 if (state == PA_CONTEXT_FAILED || state == PA_CONTEXT_TERMINATED)
82 pa_threaded_mainloop_wait(mainloop);
87 static void error(aout_instance_t *aout, const char *msg, pa_context *context)
89 msg_Err(aout, "%s: %s", msg, pa_strerror(pa_context_errno(context)));
93 static void sink_info_cb(pa_context *c, const pa_sink_info *i, int eol,
96 aout_instance_t *aout = userdata;
97 aout_sys_t *sys = aout->output.p_sys;
103 /* PulseAudio flat volume NORM / 100% / 0dB corresponds to no software
104 * amplification and maximum hardware amplification.
105 * VLC maps DEFAULT / 100% to no gain at all (software/hardware).
106 * Thus we need to use the sink base_volume as a multiplier,
107 * if and only if flat volume is active for our current sink. */
108 if (i->flags & PA_SINK_FLAT_VOLUME)
109 sys->base_volume = i->base_volume;
111 sys->base_volume = PA_VOLUME_NORM;
112 msg_Dbg(aout, "base volume: %f", pa_sw_volume_to_linear(sys->base_volume));
116 static void stream_state_cb(pa_stream *s, void *userdata)
118 pa_threaded_mainloop *mainloop = userdata;
120 switch (pa_stream_get_state(s)) {
121 case PA_STREAM_READY:
122 case PA_STREAM_FAILED:
123 case PA_STREAM_TERMINATED:
124 pa_threaded_mainloop_signal(mainloop, 0);
130 static void stream_moved_cb(pa_stream *s, void *userdata)
132 aout_instance_t *aout = userdata;
133 aout_sys_t *sys = aout->output.p_sys;
135 uint32_t idx = pa_stream_get_device_index(s);
137 msg_Dbg(aout, "connected to sink %"PRIu32": %s", idx,
138 pa_stream_get_device_name(s));
139 op = pa_context_get_sink_info_by_index(sys->context, idx,
141 if (likely(op != NULL))
142 pa_operation_unref(op);
145 static void stream_overflow_cb(pa_stream *s, void *userdata)
147 aout_instance_t *aout = userdata;
149 msg_Err(aout, "overflow");
153 static void stream_started_cb(pa_stream *s, void *userdata)
155 aout_instance_t *aout = userdata;
157 msg_Dbg(aout, "started");
161 static void stream_suspended_cb(pa_stream *s, void *userdata)
163 aout_instance_t *aout = userdata;
165 msg_Dbg(aout, "suspended");
169 static void stream_underflow_cb(pa_stream *s, void *userdata)
171 aout_instance_t *aout = userdata;
173 msg_Dbg(aout, "underflow");
177 static int stream_wait(pa_threaded_mainloop *mainloop, pa_stream *stream)
179 pa_stream_state_t state;
181 while ((state = pa_stream_get_state(stream)) != PA_STREAM_READY) {
182 if (state == PA_STREAM_FAILED || state == PA_STREAM_TERMINATED)
184 pa_threaded_mainloop_wait(mainloop);
189 /* Memory free callback. The block_t address is in front of the data. */
190 static void data_free(void *data)
192 block_t **pp = data, *block;
194 memcpy(&block, pp - 1, sizeof (block));
195 block_Release(block);
198 static void *data_convert(block_t **pp)
200 block_t *block = *pp;
201 /* In most cases, there is enough head room, and this is really cheap: */
202 block = block_Realloc(block, sizeof (block), block->i_buffer);
204 if (unlikely(block == NULL))
207 memcpy(block->p_buffer, &block, sizeof (block));
208 block->p_buffer += sizeof (block);
209 block->i_buffer -= sizeof (block);
210 return block->p_buffer;
213 /*****************************************************************************
214 * Play: play a sound samples buffer
215 *****************************************************************************/
216 static void Play(aout_instance_t *aout)
218 aout_sys_t *sys = aout->output.p_sys;
219 pa_stream *s = sys->stream;
221 /* Note: The core already holds the output FIFO lock at this point.
222 * Therefore we must not under any circumstances (try to) acquire the
223 * output FIFO lock while the PulseAudio threaded main loop lock is held
224 * (including from PulseAudio stream callbacks). Otherwise lock inversion
225 * will take place, and sooner or later a deadlock. */
226 pa_threaded_mainloop_lock(sys->mainloop);
228 if (pa_stream_is_corked(sys->stream) > 0) {
229 pa_operation *op = pa_stream_cork(s, 0, NULL, NULL);
231 pa_operation_unref(op);
232 msg_Dbg(aout, "uncorking");
236 /* This function should be called by the LibVLC core a header of time,
237 * but not more than AOUT_MAX_PREPARE. The PulseAudio latency should be
238 * shorter than that (though it might not be the case with some evil piece
239 * of audio output hardware). So we may need to trigger playback early,
240 * (that is to say, short cut the PulseAudio prebuffering). Otherwise,
241 * audio and video may be out of synchronization. */
244 if (pa_stream_get_latency(s, &latency, &negative) < 0) {
245 /* Especially at start of stream, latency may not be known (yet). */
246 if (pa_context_errno(sys->context) != PA_ERR_NODATA)
247 error(aout, "cannot determine latency", sys->context);
249 mtime_t gap = aout_FifoFirstDate(aout, &aout->output.fifo) - mdate()
252 if (gap > AOUT_PTS_TOLERANCE)
253 msg_Dbg(aout, "buffer too early (%"PRId64" us)", gap);
254 else if (gap < -AOUT_PTS_TOLERANCE)
255 msg_Err(aout, "buffer too late (%"PRId64" us)", -gap);
258 #if 0 /* Fault injector to test underrun recovery */
259 static unsigned u = 0;
260 if ((++u % 500) == 0) {
261 msg_Err(aout, "fault injection");
262 msleep(CLOCK_FREQ*2);
266 /* This function is called exactly once per block in the output FIFO, so
267 * this for-loop is not necessary.
268 * If this function is changed to not always dequeue blocks, be sure to
269 * limit the queue size to a reasonable limit to avoid huge leaks. */
271 block_t *block = aout_FifoPop(aout, &aout->output.fifo);
275 const void *ptr = data_convert(&block);
276 if (unlikely(ptr == NULL))
279 size_t len = block->i_buffer;
280 //mtime_t pts = block->i_pts, duration = block->i_length;
282 if (pa_stream_write(s, ptr, len, data_free, 0, PA_SEEK_RELATIVE) < 0)
284 error(aout, "cannot write", sys->context);
285 block_Release(block);
289 pa_threaded_mainloop_unlock(sys->mainloop);
292 static int VolumeSet(aout_instance_t *aout, audio_volume_t vol, bool mute)
294 aout_sys_t *sys = aout->output.p_sys;
295 pa_threaded_mainloop *mainloop = sys->mainloop;
298 uint32_t idx = pa_stream_get_index(sys->stream);
299 pa_volume_t volume = pa_sw_volume_from_linear(vol / (float)AOUT_VOLUME_DEFAULT);
302 /* TODO: do not ruin the channel balance (if set outside VLC) */
303 /* TODO: notify UI about volume changes by other PulseAudio clients */
304 pa_cvolume_set(&sys->cvolume, sys->cvolume.channels, volume);
305 pa_sw_cvolume_multiply_scalar(&cvolume, &sys->cvolume, sys->base_volume);
306 assert(pa_cvolume_valid(&cvolume));
308 pa_threaded_mainloop_lock(mainloop);
309 op = pa_context_set_sink_input_volume(sys->context, idx, &cvolume, NULL, NULL);
310 if (likely(op != NULL))
311 pa_operation_unref(op);
312 op = pa_context_set_sink_input_mute(sys->context, idx, mute, NULL, NULL);
313 if (likely(op != NULL))
314 pa_operation_unref(op);
315 pa_threaded_mainloop_unlock(mainloop);
320 /*****************************************************************************
321 * Open: open the audio device
322 *****************************************************************************/
323 static int Open(vlc_object_t *obj)
325 aout_instance_t *aout = (aout_instance_t *)obj;
327 /* Sample format specification */
328 struct pa_sample_spec ss;
330 switch(aout->output.output.i_format)
333 aout->output.output.i_format = VLC_CODEC_F32B;
335 ss.format = PA_SAMPLE_FLOAT32BE;
338 aout->output.output.i_format = VLC_CODEC_F32L;
340 ss.format = PA_SAMPLE_FLOAT32LE;
343 aout->output.output.i_format = VLC_CODEC_FL32;
344 ss.format = PA_SAMPLE_FLOAT32NE;
347 ss.format = PA_SAMPLE_S32BE;
350 ss.format = PA_SAMPLE_S32LE;
353 ss.format = PA_SAMPLE_S24BE;
356 ss.format = PA_SAMPLE_S24LE;
359 ss.format = PA_SAMPLE_S16BE;
362 ss.format = PA_SAMPLE_S16LE;
365 aout->output.output.i_format = VLC_CODEC_U8;
367 ss.format = PA_SAMPLE_U8;
372 aout->output.output.i_format = VLC_CODEC_FL32;
373 ss.format = PA_SAMPLE_FLOAT32NE;
377 aout->output.output.i_format = VLC_CODEC_S16N;
378 ss.format = PA_SAMPLE_S16NE;
383 ss.rate = aout->output.output.i_rate;
384 ss.channels = aout_FormatNbChannels(&aout->output.output);
385 if (!pa_sample_spec_valid(&ss)) {
386 msg_Err(aout, "unsupported sample specification");
390 /* Channel mapping (order defined in vlc_aout.h) */
391 struct pa_channel_map map;
394 if (aout->output.output.i_physical_channels & AOUT_CHAN_LEFT)
395 map.map[map.channels++] = PA_CHANNEL_POSITION_FRONT_LEFT;
396 if (aout->output.output.i_physical_channels & AOUT_CHAN_RIGHT)
397 map.map[map.channels++] = PA_CHANNEL_POSITION_FRONT_RIGHT;
398 if (aout->output.output.i_physical_channels & AOUT_CHAN_MIDDLELEFT)
399 map.map[map.channels++] = PA_CHANNEL_POSITION_SIDE_LEFT;
400 if (aout->output.output.i_physical_channels & AOUT_CHAN_MIDDLERIGHT)
401 map.map[map.channels++] = PA_CHANNEL_POSITION_SIDE_RIGHT;
402 if (aout->output.output.i_physical_channels & AOUT_CHAN_REARLEFT)
403 map.map[map.channels++] = PA_CHANNEL_POSITION_REAR_LEFT;
404 if (aout->output.output.i_physical_channels & AOUT_CHAN_REARRIGHT)
405 map.map[map.channels++] = PA_CHANNEL_POSITION_REAR_RIGHT;
406 if (aout->output.output.i_physical_channels & AOUT_CHAN_REARCENTER)
407 map.map[map.channels++] = PA_CHANNEL_POSITION_REAR_CENTER;
408 if (aout->output.output.i_physical_channels & AOUT_CHAN_CENTER)
410 if (ss.channels == 1)
411 map.map[map.channels++] = PA_CHANNEL_POSITION_MONO;
413 map.map[map.channels++] = PA_CHANNEL_POSITION_FRONT_CENTER;
415 if (aout->output.output.i_physical_channels & AOUT_CHAN_LFE)
416 map.map[map.channels++] = PA_CHANNEL_POSITION_LFE;
418 for (unsigned i = 0; map.channels < ss.channels; i++) {
419 map.map[map.channels++] = PA_CHANNEL_POSITION_AUX0 + i;
420 msg_Warn(aout, "mapping channel %"PRIu8" to AUX%u", map.channels, i);
423 if (!pa_channel_map_valid(&map)) {
424 msg_Err(aout, "unsupported channel map");
427 const char *name = pa_channel_map_to_pretty_name(&map);
428 msg_Dbg(aout, "using %s channel map", (name != NULL) ? name : "?");
431 /* Stream parameters */
432 const pa_stream_flags_t flags = PA_STREAM_INTERPOLATE_TIMING
433 | PA_STREAM_AUTO_TIMING_UPDATE
434 | PA_STREAM_ADJUST_LATENCY
435 | PA_STREAM_START_CORKED;
437 const uint32_t byterate = pa_bytes_per_second(&ss);
438 struct pa_buffer_attr attr;
439 /* no point in larger buffers on PA side than VLC */
441 attr.tlength = byterate * AOUT_MAX_ADVANCE_TIME / CLOCK_FREQ;
442 attr.prebuf = byterate * AOUT_MAX_PREPARE_TIME / CLOCK_FREQ;
444 attr.fragsize = 0; /* not used for output */
446 /* Allocate structures */
447 aout_sys_t *sys = malloc(sizeof(*sys));
448 if (unlikely(sys == NULL))
450 aout->output.p_sys = sys;
453 //sys->byterate = byterate;
456 sys->base_volume = PA_VOLUME_NORM;
457 pa_cvolume_set(&sys->cvolume, ss.channels, PA_VOLUME_NORM);
459 /* Allocate threaded main loop */
460 pa_threaded_mainloop *mainloop = pa_threaded_mainloop_new();
461 if (unlikely(mainloop == NULL)) {
465 sys->mainloop = mainloop;
467 if (pa_threaded_mainloop_start(mainloop) < 0) {
468 pa_threaded_mainloop_free(mainloop);
472 pa_threaded_mainloop_lock(mainloop);
474 /* Connect to PulseAudio server */
475 char *user_agent = var_InheritString(aout, "user-agent");
476 pa_context *ctx = pa_context_new(pa_threaded_mainloop_get_api(mainloop),
479 if (unlikely(ctx == NULL))
483 pa_context_set_state_callback(ctx, context_state_cb, mainloop);
484 if (pa_context_connect(ctx, NULL, 0, NULL) < 0
485 || context_wait(mainloop, ctx)) {
486 error(aout, "cannot connect to server", ctx);
490 /* Create a playback stream */
491 pa_stream *s = pa_stream_new(ctx, "audio stream", &ss, &map);
493 error(aout, "cannot create stream", ctx);
497 pa_stream_set_state_callback(s, stream_state_cb, mainloop);
498 pa_stream_set_moved_callback(s, stream_moved_cb, aout);
499 pa_stream_set_overflow_callback(s, stream_overflow_cb, aout);
500 pa_stream_set_started_callback(s, stream_started_cb, aout);
501 pa_stream_set_suspended_callback(s, stream_suspended_cb, aout);
502 pa_stream_set_underflow_callback(s, stream_underflow_cb, aout);
504 if (pa_stream_connect_playback(s, NULL, &attr, flags, NULL, NULL) < 0
505 || stream_wait(mainloop, s)) {
506 error(aout, "cannot connect stream", ctx);
509 stream_moved_cb(s, aout);
511 const struct pa_buffer_attr *pba = pa_stream_get_buffer_attr(s);
512 msg_Dbg(aout, "using buffer metrics: maxlength=%u, tlength=%u, "
513 "prebuf=%u, minreq=%u",
514 pba->maxlength, pba->tlength, pba->prebuf, pba->minreq);
516 aout->output.i_nb_samples = pba->minreq / pa_frame_size(&ss);
517 pa_threaded_mainloop_unlock(mainloop);
519 aout->output.pf_play = Play;
520 aout->output.pf_volume_set = VolumeSet;
524 pa_threaded_mainloop_unlock(mainloop);
529 /*****************************************************************************
530 * Close: close the audio device
531 *****************************************************************************/
532 static void Close (vlc_object_t *obj)
534 aout_instance_t *aout = (aout_instance_t *)obj;
535 aout_sys_t *sys = aout->output.p_sys;
536 pa_threaded_mainloop *mainloop = sys->mainloop;
537 pa_context *ctx = sys->context;
538 pa_stream *s = sys->stream;
540 pa_threaded_mainloop_lock(mainloop);
544 op = pa_stream_flush(s, NULL, NULL);
546 pa_operation_unref(op);
547 op = pa_stream_drain(s, NULL, NULL);
549 pa_operation_unref(op);
550 pa_stream_disconnect(s);
554 pa_context_unref(ctx);
555 pa_threaded_mainloop_unlock(mainloop);
556 pa_threaded_mainloop_free(mainloop);