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 *****************************************************************************/
29 #include <vlc_common.h>
30 #include <vlc_plugin.h>
34 #include <pulse/pulseaudio.h>
36 #if !PA_CHECK_VERSION(0,9,22)
37 # include <vlc_xlib.h>
40 static int Open ( vlc_object_t * );
41 static void Close ( vlc_object_t * );
44 set_shortname( "PulseAudio" )
45 set_description( N_("Pulseaudio audio output") )
46 set_capability( "audio output", 160 )
47 set_category( CAT_AUDIO )
48 set_subcategory( SUBCAT_AUDIO_AOUT )
49 add_shortcut( "pulseaudio", "pa" )
50 set_callbacks( Open, Close )
54 * - pause input on policy event
55 * - resample to compensate for long term drift
56 * - select music or video stream property correctly (?)
57 * - set further appropriate stream properties
58 * - update output devices list dynamically
62 * Be careful what you do when the PulseAudio mainloop is held, which is to say
63 * within PulseAudio callbacks, or after pa_threaded_mainloop_lock().
64 * In particular, a VLC variable callback cannot be triggered nor deleted with
65 * the PulseAudio mainloop lock held, if the callback acquires the lock. */
69 pa_stream *stream; /**< PulseAudio playback stream object */
70 pa_context *context; /**< PulseAudio connection context */
71 pa_threaded_mainloop *mainloop; /**< PulseAudio thread */
72 pa_time_event *trigger; /**< Deferred stream trigger */
73 pa_volume_t base_volume; /**< 0dB reference volume */
74 pa_cvolume cvolume; /**< actual sink input volume */
75 mtime_t paused; /**< Time when (last) paused */
76 mtime_t pts; /**< Play time of buffer write offset */
77 mtime_t desync; /**< Measured desynchronization */
78 unsigned rate; /**< Current stream sample rate */
81 static void sink_list_cb(pa_context *, const pa_sink_info *, int, void *);
82 static void sink_input_info_cb(pa_context *, const pa_sink_input_info *,
86 static void context_cb(pa_context *ctx, pa_subscription_event_type_t type,
87 uint32_t idx, void *userdata)
89 audio_output_t *aout = userdata;
90 aout_sys_t *sys = aout->sys;
93 switch (type & PA_SUBSCRIPTION_EVENT_FACILITY_MASK)
95 case PA_SUBSCRIPTION_EVENT_SINK:
96 switch (type & PA_SUBSCRIPTION_EVENT_TYPE_MASK)
98 case PA_SUBSCRIPTION_EVENT_NEW:
99 case PA_SUBSCRIPTION_EVENT_CHANGE:
100 op = pa_context_get_sink_info_by_index(ctx, idx, sink_list_cb, aout);
101 if (likely(op != NULL))
102 pa_operation_unref(op);
105 case PA_SUBSCRIPTION_EVENT_REMOVE:
106 var_Change(aout, "audio-device", VLC_VAR_DELCHOICE,
107 &(vlc_value_t){ .i_int = idx }, NULL);
112 case PA_SUBSCRIPTION_EVENT_SINK_INPUT:
113 if (idx != pa_stream_get_index(sys->stream))
114 break; /* only interested in our sink input */
116 /* Gee... PA will not provide the infos directly in the event. */
117 switch (type & PA_SUBSCRIPTION_EVENT_TYPE_MASK)
119 case PA_SUBSCRIPTION_EVENT_REMOVE:
120 msg_Err(aout, "sink input killed!");
124 op = pa_context_get_sink_input_info(ctx, idx, sink_input_info_cb,
126 if (likely(op != NULL))
127 pa_operation_unref(op);
132 default: /* unsubscribed facility?! */
139 static void sink_list_cb(pa_context *c, const pa_sink_info *i, int eol,
142 audio_output_t *aout = userdata;
143 vlc_value_t val, text;
149 msg_Dbg(aout, "listing sink %s (%"PRIu32"): %s", i->name, i->index,
151 val.i_int = i->index;
152 text.psz_string = (char *)i->description;
153 /* FIXME: There is no way to replace a choice explicitly. */
154 var_Change(aout, "audio-device", VLC_VAR_DELCHOICE, &val, NULL);
155 var_Change(aout, "audio-device", VLC_VAR_ADDCHOICE, &val, &text);
156 /* FIXME: var_Change() can change the variable value if we remove the
157 * current value from the choice list, or if we add a choice while there
158 * was none. So force the correct value back. */
159 val.i_int = pa_stream_get_device_index(aout->sys->stream);
160 var_Change(aout, "audio-device", VLC_VAR_SETVALUE, &val, NULL);
163 static void sink_info_cb(pa_context *c, const pa_sink_info *i, int eol,
166 audio_output_t *aout = userdata;
167 aout_sys_t *sys = aout->sys;
173 /* PulseAudio flat volume NORM / 100% / 0dB corresponds to no software
174 * amplification and maximum hardware amplification.
175 * VLC maps DEFAULT / 100% to no gain at all (software/hardware).
176 * Thus we need to use the sink base_volume as a multiplier,
177 * if and only if flat volume is active for our current sink. */
178 if (i->flags & PA_SINK_FLAT_VOLUME)
179 sys->base_volume = i->base_volume;
181 sys->base_volume = PA_VOLUME_NORM;
182 msg_Dbg(aout, "base volume: %"PRIu32, sys->base_volume);
186 /*** Latency management and lip synchronization ***/
187 static void stream_reset_sync(pa_stream *s, audio_output_t *aout)
189 aout_sys_t *sys = aout->sys;
190 const unsigned rate = aout->format.i_rate;
192 sys->pts = VLC_TS_INVALID;
194 pa_operation *op = pa_stream_update_sample_rate(s, rate, NULL, NULL);
195 if (unlikely(op == NULL))
197 pa_operation_unref(op);
201 static void stream_start(pa_stream *s, audio_output_t *aout)
203 aout_sys_t *sys = aout->sys;
206 if (sys->trigger != NULL) {
207 vlc_pa_rttime_free(sys->mainloop, sys->trigger);
211 op = pa_stream_cork(s, 0, NULL, NULL);
213 pa_operation_unref(op);
214 op = pa_stream_trigger(s, NULL, NULL);
215 if (likely(op != NULL))
216 pa_operation_unref(op);
219 static void stream_stop(pa_stream *s, audio_output_t *aout)
221 aout_sys_t *sys = aout->sys;
224 if (sys->trigger != NULL) {
225 vlc_pa_rttime_free(sys->mainloop, sys->trigger);
229 op = pa_stream_cork(s, 1, NULL, NULL);
231 pa_operation_unref(op);
234 static void stream_trigger_cb(pa_mainloop_api *api, pa_time_event *e,
235 const struct timeval *tv, void *userdata)
237 audio_output_t *aout = userdata;
238 aout_sys_t *sys = aout->sys;
240 msg_Dbg(aout, "starting deferred");
241 assert (sys->trigger == e);
242 stream_start(sys->stream, aout);
243 (void) api; (void) e; (void) tv;
247 * Starts or resumes the playback stream.
248 * Tries start playing back audio samples at the most accurate time
249 * in order to minimize desync and resampling during early playback.
250 * @note PulseAudio lock required.
252 static void stream_resync(audio_output_t *aout, pa_stream *s)
254 aout_sys_t *sys = aout->sys;
257 assert (pa_stream_is_corked(s) > 0);
258 assert (sys->pts != VLC_TS_INVALID);
260 delta = vlc_pa_get_latency(aout, sys->context, s);
261 if (unlikely(delta == VLC_TS_INVALID))
262 delta = 0; /* screwed */
264 delta = (sys->pts - mdate()) - delta;
266 if (sys->trigger == NULL) {
267 msg_Dbg(aout, "deferring start (%"PRId64" us)", delta);
268 delta += pa_rtclock_now();
269 sys->trigger = pa_context_rttime_new(sys->context, delta,
270 stream_trigger_cb, aout);
273 msg_Warn(aout, "starting late (%"PRId64" us)", delta);
274 stream_start(s, aout);
278 static void stream_latency_cb(pa_stream *s, void *userdata)
280 audio_output_t *aout = userdata;
281 aout_sys_t *sys = aout->sys;
282 mtime_t delta, change;
284 if (pa_stream_is_corked(s))
286 if (sys->pts == VLC_TS_INVALID)
288 msg_Dbg(aout, "missing latency from input");
292 /* Compute lip desynchronization */
293 delta = vlc_pa_get_latency(aout, sys->context, s);
294 if (delta == VLC_TS_INVALID)
297 delta = (sys->pts - mdate()) - delta;
298 change = delta - sys->desync;
300 //msg_Dbg(aout, "desync: %+"PRId64" us (variation: %+"PRId64" us)",
303 const unsigned inrate = aout->format.i_rate;
304 unsigned outrate = sys->rate;
307 if (delta < -AOUT_MAX_PTS_DELAY)
308 msg_Warn(aout, "too late by %"PRId64" us", -delta);
309 else if (delta > +AOUT_MAX_PTS_ADVANCE)
310 msg_Warn(aout, "too early by %"PRId64" us", delta);
311 else if (outrate == inrate)
312 return; /* In sync, do not add unnecessary disturbance! */
316 /* Compute playback sample rate */
317 /* This is empirical (especially the shift values).
318 * Feel free to define something smarter. */
319 int adj = sync ? (outrate - inrate)
320 : outrate * ((delta >> 4) + change) / (CLOCK_FREQ << 2);
321 /* This avoids too quick rate variation. It sounds really bad and
322 * causes unstability (e.g. oscillation around the correct rate). */
323 int limit = inrate >> 10;
324 /* However, to improve stability and try to converge, closing to the
325 * nominal rate is favored over drifting from it. */
326 if ((adj > 0) == (sys->rate > inrate))
334 /* This keeps the effective rate within specified range
335 * (+/-AOUT_MAX_RESAMPLING% - see <vlc_aout.h>) of the nominal rate. */
336 limit = inrate * AOUT_MAX_RESAMPLING / 100;
337 if (outrate > inrate + limit)
338 outrate = inrate + limit;
339 if (outrate < inrate - limit)
340 outrate = inrate - limit;
342 /* Apply adjusted sample rate */
343 if (outrate == sys->rate)
345 pa_operation *op = pa_stream_update_sample_rate(s, outrate, NULL, NULL);
346 if (unlikely(op == NULL)) {
347 vlc_pa_error(aout, "cannot change sample rate", sys->context);
350 pa_operation_unref(op);
351 msg_Dbg(aout, "changed sample rate to %u Hz",outrate);
356 /*** Stream helpers ***/
357 static void stream_state_cb(pa_stream *s, void *userdata)
359 pa_threaded_mainloop *mainloop = userdata;
361 switch (pa_stream_get_state(s)) {
362 case PA_STREAM_READY:
363 case PA_STREAM_FAILED:
364 case PA_STREAM_TERMINATED:
365 pa_threaded_mainloop_signal(mainloop, 0);
371 static void stream_event_cb(pa_stream *s, const char *name, pa_proplist *pl,
374 audio_output_t *aout = userdata;
376 #if PA_CHECK_VERSION(1,0,0)
377 /* FIXME: expose aout_Restart() directly */
378 if (!strcmp(name, PA_STREAM_EVENT_FORMAT_LOST)) {
379 vlc_value_t dummy = { .i_int = 0 };
381 msg_Dbg (aout, "format lost");
382 aout_ChannelsRestart (VLC_OBJECT(aout), "audio-device",
386 msg_Warn (aout, "unhandled event %s", name);
391 static void stream_moved_cb(pa_stream *s, void *userdata)
393 audio_output_t *aout = userdata;
394 aout_sys_t *sys = aout->sys;
396 uint32_t idx = pa_stream_get_device_index(s);
398 msg_Dbg(aout, "connected to sink %"PRIu32": %s", idx,
399 pa_stream_get_device_name(s));
400 op = pa_context_get_sink_info_by_index(sys->context, idx,
402 if (likely(op != NULL))
403 pa_operation_unref(op);
405 /* Update the variable if someone else moved our stream */
406 var_Change(aout, "audio-device", VLC_VAR_SETVALUE,
407 &(vlc_value_t){ .i_int = idx }, NULL);
409 /* Sink unknown as yet, create stub choice for it */
410 if (var_GetInteger(aout, "audio-device") != idx)
412 var_Change(aout, "audio-device", VLC_VAR_ADDCHOICE,
413 &(vlc_value_t){ .i_int = idx },
414 &(vlc_value_t){ .psz_string = (char *)"?" });
415 var_Change(aout, "audio-device", VLC_VAR_SETVALUE,
416 &(vlc_value_t){ .i_int = idx }, NULL);
420 static void stream_overflow_cb(pa_stream *s, void *userdata)
422 audio_output_t *aout = userdata;
425 msg_Err(aout, "overflow, flushing");
426 op = pa_stream_flush(s, NULL, NULL);
427 if (likely(op != NULL))
428 pa_operation_unref(op);
429 stream_reset_sync(s, aout);
432 static void stream_started_cb(pa_stream *s, void *userdata)
434 audio_output_t *aout = userdata;
436 msg_Dbg(aout, "started");
440 static void stream_suspended_cb(pa_stream *s, void *userdata)
442 audio_output_t *aout = userdata;
444 msg_Dbg(aout, "suspended");
445 stream_reset_sync(s, aout);
448 static void stream_underflow_cb(pa_stream *s, void *userdata)
450 audio_output_t *aout = userdata;
452 msg_Warn(aout, "underflow");
453 stream_stop(s, aout);
454 stream_reset_sync(s, aout);
457 static int stream_wait(pa_stream *stream, pa_threaded_mainloop *mainloop)
459 pa_stream_state_t state;
461 while ((state = pa_stream_get_state(stream)) != PA_STREAM_READY) {
462 if (state == PA_STREAM_FAILED || state == PA_STREAM_TERMINATED)
464 pa_threaded_mainloop_wait(mainloop);
471 static void sink_input_info_cb(pa_context *ctx, const pa_sink_input_info *i,
472 int eol, void *userdata)
474 audio_output_t *aout = userdata;
475 aout_sys_t *sys = aout->sys;
482 sys->cvolume = i->volume;
483 volume = pa_cvolume_max(&i->volume) / (float)PA_VOLUME_NORM;
484 aout_VolumeHardSet(aout, volume, i->mute);
488 /*** VLC audio output callbacks ***/
490 /* Memory free callback. The block_t address is in front of the data. */
491 static void data_free(void *data)
493 block_t **pp = data, *block;
495 memcpy(&block, pp - 1, sizeof (block));
496 block_Release(block);
499 static void *data_convert(block_t **pp)
501 block_t *block = *pp;
502 /* In most cases, there is enough head room, and this is really cheap: */
503 block = block_Realloc(block, sizeof (block), block->i_buffer);
505 if (unlikely(block == NULL))
508 memcpy(block->p_buffer, &block, sizeof (block));
509 block->p_buffer += sizeof (block);
510 block->i_buffer -= sizeof (block);
511 return block->p_buffer;
515 * Queue one audio frame to the playabck stream
517 static void Play(audio_output_t *aout, block_t *block)
519 aout_sys_t *sys = aout->sys;
520 pa_stream *s = sys->stream;
522 const void *ptr = data_convert(&block);
523 if (unlikely(ptr == NULL))
526 size_t len = block->i_buffer;
527 mtime_t pts = block->i_pts + block->i_length;
529 /* Note: The core already holds the output FIFO lock at this point.
530 * Therefore we must not under any circumstances (try to) acquire the
531 * output FIFO lock while the PulseAudio threaded main loop lock is held
532 * (including from PulseAudio stream callbacks). Otherwise lock inversion
533 * will take place, and sooner or later a deadlock. */
534 pa_threaded_mainloop_lock(sys->mainloop);
537 if (pa_stream_is_corked(s) > 0)
538 stream_resync(aout, s);
540 #if 0 /* Fault injector to test underrun recovery */
541 static volatile unsigned u = 0;
542 if ((++u % 1000) == 0) {
543 msg_Err(aout, "fault injection");
544 pa_operation_unref(pa_stream_flush(s, NULL, NULL));
548 if (pa_stream_write(s, ptr, len, data_free, 0, PA_SEEK_RELATIVE) < 0) {
549 vlc_pa_error(aout, "cannot write", sys->context);
550 block_Release(block);
553 pa_threaded_mainloop_unlock(sys->mainloop);
557 * Cork or uncork the playback stream
559 static void Pause(audio_output_t *aout, bool paused, mtime_t date)
561 aout_sys_t *sys = aout->sys;
562 pa_stream *s = sys->stream;
564 pa_threaded_mainloop_lock(sys->mainloop);
568 stream_stop(s, aout);
570 assert (sys->paused != VLC_TS_INVALID);
572 msg_Dbg(aout, "resuming after %"PRId64" us", date);
573 sys->paused = VLC_TS_INVALID;
575 stream_resync(aout, s);
578 pa_threaded_mainloop_unlock(sys->mainloop);
582 * Flush or drain the playback stream
584 static void Flush(audio_output_t *aout, bool wait)
586 aout_sys_t *sys = aout->sys;
587 pa_stream *s = sys->stream;
590 pa_threaded_mainloop_lock(sys->mainloop);
593 op = pa_stream_drain(s, NULL, NULL);
594 /* TODO: wait for drain completion*/
596 op = pa_stream_flush(s, NULL, NULL);
598 pa_operation_unref(op);
599 pa_threaded_mainloop_unlock(sys->mainloop);
602 static int VolumeSet(audio_output_t *aout, float vol, bool mute)
604 aout_sys_t *sys = aout->sys;
606 uint32_t idx = pa_stream_get_index(sys->stream);
608 pa_cvolume cvolume = sys->cvolume;
609 pa_volume_t volume = sys->base_volume;
611 pa_cvolume_scale(&cvolume, PA_VOLUME_NORM); /* preserve balance */
613 /* VLC provides the software volume so convert directly to PulseAudio
614 * software volume, pa_volume_t. This is not a linear amplification factor
615 * so do not use PulseAudio linear amplification! */
616 vol *= PA_VOLUME_NORM;
617 if (unlikely(vol >= PA_VOLUME_MAX))
619 volume = pa_sw_volume_multiply(volume, lround(vol));
620 pa_sw_cvolume_multiply_scalar(&cvolume, &cvolume, volume);
622 assert(pa_cvolume_valid(&cvolume));
624 pa_threaded_mainloop_lock(sys->mainloop);
625 op = pa_context_set_sink_input_volume(sys->context, idx, &cvolume, NULL, NULL);
626 if (likely(op != NULL))
627 pa_operation_unref(op);
628 op = pa_context_set_sink_input_mute(sys->context, idx, mute, NULL, NULL);
629 if (likely(op != NULL))
630 pa_operation_unref(op);
631 pa_threaded_mainloop_unlock(sys->mainloop);
636 static int StreamMove(vlc_object_t *obj, const char *varname, vlc_value_t old,
637 vlc_value_t val, void *userdata)
639 audio_output_t *aout = (audio_output_t *)obj;
640 aout_sys_t *sys = aout->sys;
641 pa_stream *s = userdata;
643 uint32_t idx = pa_stream_get_index(s);
644 uint32_t sink_idx = val.i_int;
646 (void) varname; (void) old;
648 pa_threaded_mainloop_lock(sys->mainloop);
649 op = pa_context_move_sink_input_by_index(sys->context, idx, sink_idx,
651 if (likely(op != NULL)) {
652 pa_operation_unref(op);
653 msg_Dbg(aout, "moving to sink %"PRIu32, sink_idx);
655 vlc_pa_error(obj, "cannot move sink", sys->context);
656 pa_threaded_mainloop_unlock(sys->mainloop);
658 return (op != NULL) ? VLC_SUCCESS : VLC_EGENERIC;
663 * Create a PulseAudio playback stream, a.k.a. a sink input.
665 static int Open(vlc_object_t *obj)
667 #if !PA_CHECK_VERSION(0,9,22)
668 if (!vlc_xlib_init(obj))
672 audio_output_t *aout = (audio_output_t *)obj;
675 /* Sample format specification */
676 struct pa_sample_spec ss;
677 vlc_fourcc_t format = aout->format.i_format;
678 #if PA_CHECK_VERSION(1,0,0)
679 pa_encoding_t encoding = PA_ENCODING_INVALID;
685 format = VLC_CODEC_F32B;
687 ss.format = PA_SAMPLE_FLOAT32BE;
690 format = VLC_CODEC_F32L;
692 ss.format = PA_SAMPLE_FLOAT32LE;
695 format = VLC_CODEC_FL32;
696 ss.format = PA_SAMPLE_FLOAT32NE;
699 ss.format = PA_SAMPLE_S32BE;
702 ss.format = PA_SAMPLE_S32LE;
705 ss.format = PA_SAMPLE_S24BE;
708 ss.format = PA_SAMPLE_S24LE;
711 ss.format = PA_SAMPLE_S16BE;
714 ss.format = PA_SAMPLE_S16LE;
717 format = VLC_CODEC_U8;
719 ss.format = PA_SAMPLE_U8;
721 #if PA_CHECK_VERSION(1,0,0)
723 format = VLC_CODEC_SPDIFL;
724 encoding = PA_ENCODING_AC3_IEC61937;
725 ss.format = HAVE_FPU ? PA_SAMPLE_FLOAT32NE : PA_SAMPLE_S16NE;
727 /*case VLC_CODEC_EAC3:
728 format = VLC_CODEC_SPDIFL FIXME;
729 encoding = PA_ENCODING_EAC3_IEC61937;
730 ss.format = HAVE_FPU ? PA_SAMPLE_FLOAT32NE : PA_SAMPLE_S16NE;
733 format = VLC_CODEC_SPDIFL FIXME;
734 encoding = PA_ENCODING_MPEG_IEC61937;
735 ss.format = HAVE_FPU ? PA_SAMPLE_FLOAT32NE : PA_SAMPLE_S16NE;
738 format = VLC_CODEC_SPDIFL;
739 encoding = PA_ENCODING_DTS_IEC61937;
740 ss.format = HAVE_FPU ? PA_SAMPLE_FLOAT32NE : PA_SAMPLE_S16NE;
746 format = VLC_CODEC_FL32;
747 ss.format = PA_SAMPLE_FLOAT32NE;
751 format = VLC_CODEC_S16N;
752 ss.format = PA_SAMPLE_S16NE;
757 ss.rate = aout->format.i_rate;
758 ss.channels = aout_FormatNbChannels(&aout->format);
759 if (!pa_sample_spec_valid(&ss)) {
760 msg_Err(aout, "unsupported sample specification");
764 /* Channel mapping (order defined in vlc_aout.h) */
765 struct pa_channel_map map;
768 if (aout->format.i_physical_channels & AOUT_CHAN_LEFT)
769 map.map[map.channels++] = PA_CHANNEL_POSITION_FRONT_LEFT;
770 if (aout->format.i_physical_channels & AOUT_CHAN_RIGHT)
771 map.map[map.channels++] = PA_CHANNEL_POSITION_FRONT_RIGHT;
772 if (aout->format.i_physical_channels & AOUT_CHAN_MIDDLELEFT)
773 map.map[map.channels++] = PA_CHANNEL_POSITION_SIDE_LEFT;
774 if (aout->format.i_physical_channels & AOUT_CHAN_MIDDLERIGHT)
775 map.map[map.channels++] = PA_CHANNEL_POSITION_SIDE_RIGHT;
776 if (aout->format.i_physical_channels & AOUT_CHAN_REARLEFT)
777 map.map[map.channels++] = PA_CHANNEL_POSITION_REAR_LEFT;
778 if (aout->format.i_physical_channels & AOUT_CHAN_REARRIGHT)
779 map.map[map.channels++] = PA_CHANNEL_POSITION_REAR_RIGHT;
780 if (aout->format.i_physical_channels & AOUT_CHAN_REARCENTER)
781 map.map[map.channels++] = PA_CHANNEL_POSITION_REAR_CENTER;
782 if (aout->format.i_physical_channels & AOUT_CHAN_CENTER)
784 if (ss.channels == 1)
785 map.map[map.channels++] = PA_CHANNEL_POSITION_MONO;
787 map.map[map.channels++] = PA_CHANNEL_POSITION_FRONT_CENTER;
789 if (aout->format.i_physical_channels & AOUT_CHAN_LFE)
790 map.map[map.channels++] = PA_CHANNEL_POSITION_LFE;
792 for (unsigned i = 0; map.channels < ss.channels; i++) {
793 map.map[map.channels++] = PA_CHANNEL_POSITION_AUX0 + i;
794 msg_Warn(aout, "mapping channel %"PRIu8" to AUX%u", map.channels, i);
797 if (!pa_channel_map_valid(&map)) {
798 msg_Err(aout, "unsupported channel map");
801 const char *name = pa_channel_map_to_name(&map);
802 msg_Dbg(aout, "using %s channel map", (name != NULL) ? name : "?");
805 /* Stream parameters */
806 const pa_stream_flags_t flags = PA_STREAM_START_CORKED
807 //| PA_STREAM_INTERPOLATE_TIMING
808 | PA_STREAM_AUTO_TIMING_UPDATE
809 | PA_STREAM_VARIABLE_RATE;
811 struct pa_buffer_attr attr;
813 /* PulseAudio assumes that tlength bytes are available in the buffer. Thus
814 * we need to be conservative and set the minimum value that the VLC
815 * audio decoder thread warrants. Otherwise, PulseAudio buffers will
816 * underrun on hardware with large buffers. VLC keeps at least
817 * AOUT_MIN_PREPARE and at most AOUT_MAX_PREPARE worth of audio buffers.
818 * TODO? tlength could be adaptively increased to reduce wakeups. */
819 attr.tlength = pa_usec_to_bytes(AOUT_MIN_PREPARE_TIME, &ss);
820 attr.prebuf = 0; /* trigger manually */
822 attr.fragsize = 0; /* not used for output */
824 /* Allocate structures */
825 aout_sys_t *sys = malloc(sizeof(*sys));
826 if (unlikely(sys == NULL))
829 pa_context *ctx = vlc_pa_connect(obj, &sys->mainloop);
840 sys->paused = VLC_TS_INVALID;
841 sys->pts = VLC_TS_INVALID;
846 sys->base_volume = PA_VOLUME_NORM;
847 pa_cvolume_set(&sys->cvolume, ss.channels, PA_VOLUME_NORM);
849 #if PA_CHECK_VERSION(1,0,0)
850 pa_format_info *formatv[2];
851 unsigned formatc = 0;
853 /* Favor digital pass-through if available*/
854 if (encoding != PA_ENCODING_INVALID) {
855 formatv[formatc] = pa_format_info_new();
856 formatv[formatc]->encoding = encoding;
857 pa_format_info_set_rate(formatv[formatc], ss.rate);
858 pa_format_info_set_channels(formatv[formatc], ss.channels);
859 pa_format_info_set_channel_map(formatv[formatc], &map);
863 /* Fallback to PCM */
864 formatv[formatc] = pa_format_info_new();
865 formatv[formatc]->encoding = PA_ENCODING_PCM;
866 pa_format_info_set_sample_format(formatv[formatc], ss.format);
867 pa_format_info_set_rate(formatv[formatc], ss.rate);
868 pa_format_info_set_channels(formatv[formatc], ss.channels);
869 pa_format_info_set_channel_map(formatv[formatc], &map);
872 /* Create a playback stream */
875 pa_threaded_mainloop_lock(sys->mainloop);
876 s = pa_stream_new_extended(ctx, "audio stream", formatv, formatc, NULL);
878 for (unsigned i = 0; i < formatc; i++)
879 pa_format_info_free(formatv[i]);
881 pa_threaded_mainloop_lock(sys->mainloop);
882 pa_stream *s = pa_stream_new(ctx, "audio stream", &ss, &map);
885 vlc_pa_error(obj, "stream creation failure", ctx);
889 pa_stream_set_state_callback(s, stream_state_cb, sys->mainloop);
890 pa_stream_set_event_callback(s, stream_event_cb, aout);
891 pa_stream_set_latency_update_callback(s, stream_latency_cb, aout);
892 pa_stream_set_moved_callback(s, stream_moved_cb, aout);
893 pa_stream_set_overflow_callback(s, stream_overflow_cb, aout);
894 pa_stream_set_started_callback(s, stream_started_cb, aout);
895 pa_stream_set_suspended_callback(s, stream_suspended_cb, aout);
896 pa_stream_set_underflow_callback(s, stream_underflow_cb, aout);
898 if (pa_stream_connect_playback(s, NULL, &attr, flags, NULL, NULL) < 0
899 || stream_wait(s, sys->mainloop)) {
900 vlc_pa_error(obj, "stream connection failure", ctx);
904 #if PA_CHECK_VERSION(1,0,0)
905 if (encoding != PA_ENCODING_INVALID) {
906 const pa_format_info *info = pa_stream_get_format_info(s);
908 assert (info != NULL);
909 if (pa_format_info_is_pcm (info)) {
910 msg_Dbg(aout, "digital pass-through not available");
911 format = HAVE_FPU ? VLC_CODEC_FL32 : VLC_CODEC_S16N;
913 msg_Dbg(aout, "digital pass-through enabled");
914 pa_stream_set_latency_update_callback(s, NULL, NULL);
919 const struct pa_buffer_attr *pba = pa_stream_get_buffer_attr(s);
920 msg_Dbg(aout, "using buffer metrics: maxlength=%u, tlength=%u, "
921 "prebuf=%u, minreq=%u",
922 pba->maxlength, pba->tlength, pba->prebuf, pba->minreq);
924 var_Create(aout, "audio-device", VLC_VAR_INTEGER|VLC_VAR_HASCHOICE);
925 var_Change(aout, "audio-device", VLC_VAR_SETTEXT,
926 &(vlc_value_t){ .psz_string = (char *)_("Audio device") },
928 var_AddCallback (aout, "audio-device", StreamMove, s);
929 op = pa_context_get_sink_info_list(ctx, sink_list_cb, aout);
930 /* We may need to wait for completion... once LibVLC supports this */
932 pa_operation_unref(op);
933 stream_moved_cb(s, aout);
936 const pa_subscription_mask_t mask = PA_SUBSCRIPTION_MASK_SINK
937 | PA_SUBSCRIPTION_MASK_SINK_INPUT;
938 pa_context_set_subscribe_callback(ctx, context_cb, aout);
939 op = pa_context_subscribe(ctx, mask, NULL, NULL);
940 if (likely(op != NULL))
941 pa_operation_unref(op);
942 pa_threaded_mainloop_unlock(sys->mainloop);
944 aout->format.i_format = format;
945 aout->pf_play = Play;
946 aout->pf_pause = Pause;
947 aout->pf_flush = Flush;
948 aout_VolumeHardInit (aout, VolumeSet);
952 pa_threaded_mainloop_unlock(sys->mainloop);
958 * Removes a PulseAudio playback stream
960 static void Close (vlc_object_t *obj)
962 audio_output_t *aout = (audio_output_t *)obj;
963 aout_sys_t *sys = aout->sys;
964 pa_context *ctx = sys->context;
965 pa_stream *s = sys->stream;
968 /* The callback takes mainloop lock, so it CANNOT be held here! */
969 var_DelCallback (aout, "audio-device", StreamMove, s);
970 var_Destroy (aout, "audio-device");
972 pa_threaded_mainloop_lock(sys->mainloop);
973 if (unlikely(sys->trigger != NULL))
974 vlc_pa_rttime_free(sys->mainloop, sys->trigger);
975 pa_stream_disconnect(s);
977 /* Clear all callbacks */
978 pa_stream_set_state_callback(s, NULL, NULL);
979 pa_stream_set_event_callback(s, NULL, NULL);
980 pa_stream_set_latency_update_callback(s, NULL, NULL);
981 pa_stream_set_moved_callback(s, NULL, NULL);
982 pa_stream_set_overflow_callback(s, NULL, NULL);
983 pa_stream_set_started_callback(s, NULL, NULL);
984 pa_stream_set_suspended_callback(s, NULL, NULL);
985 pa_stream_set_underflow_callback(s, NULL, NULL);
986 pa_context_set_subscribe_callback(ctx, NULL, NULL);
989 pa_threaded_mainloop_unlock(sys->mainloop);
992 vlc_pa_disconnect(obj, ctx, sys->mainloop);