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 * Be careful what you do when the PulseAudio mainloop is held, which is to say
55 * within PulseAudio callbacks, or after pa_threaded_mainloop_lock().
56 * In particular, a VLC variable callback cannot be triggered nor deleted with
57 * the PulseAudio mainloop lock held, if the callback acquires the lock. */
61 pa_stream *stream; /**< PulseAudio playback stream object */
62 pa_context *context; /**< PulseAudio connection context */
63 pa_threaded_mainloop *mainloop; /**< PulseAudio thread */
64 pa_time_event *trigger; /**< Deferred stream trigger */
65 pa_volume_t base_volume; /**< 0dB reference volume */
66 pa_cvolume cvolume; /**< actual sink input volume */
67 mtime_t first_pts; /**< Play time of buffer start */
68 mtime_t last_pts; /**< Play time of buffer write offset */
69 mtime_t paused; /**< Time when (last) paused */
70 mtime_t desync; /**< Measured desynchronization */
71 unsigned nominal_rate; /**< Nominal stream sample rate */
72 unsigned actual_rate; /**< Current stream sample rate */
75 static void sink_list_cb(pa_context *, const pa_sink_info *, int, void *);
76 static void sink_input_info_cb(pa_context *, const pa_sink_input_info *,
80 static void context_cb(pa_context *ctx, pa_subscription_event_type_t type,
81 uint32_t idx, void *userdata)
83 audio_output_t *aout = userdata;
84 aout_sys_t *sys = aout->sys;
87 switch (type & PA_SUBSCRIPTION_EVENT_FACILITY_MASK)
89 case PA_SUBSCRIPTION_EVENT_SINK:
90 switch (type & PA_SUBSCRIPTION_EVENT_TYPE_MASK)
92 case PA_SUBSCRIPTION_EVENT_NEW:
93 case PA_SUBSCRIPTION_EVENT_CHANGE:
94 op = pa_context_get_sink_info_by_index(ctx, idx, sink_list_cb, aout);
95 if (likely(op != NULL))
96 pa_operation_unref(op);
99 case PA_SUBSCRIPTION_EVENT_REMOVE:
100 var_Change(aout, "audio-device", VLC_VAR_DELCHOICE,
101 &(vlc_value_t){ .i_int = idx }, NULL);
106 case PA_SUBSCRIPTION_EVENT_SINK_INPUT:
107 if (idx != pa_stream_get_index(sys->stream))
108 break; /* only interested in our sink input */
110 /* Gee... PA will not provide the infos directly in the event. */
111 switch (type & PA_SUBSCRIPTION_EVENT_TYPE_MASK)
113 case PA_SUBSCRIPTION_EVENT_REMOVE:
114 msg_Err(aout, "sink input killed!");
118 op = pa_context_get_sink_input_info(ctx, idx, sink_input_info_cb,
120 if (likely(op != NULL))
121 pa_operation_unref(op);
126 default: /* unsubscribed facility?! */
133 static void sink_list_cb(pa_context *c, const pa_sink_info *i, int eol,
136 audio_output_t *aout = userdata;
137 vlc_value_t val, text;
143 msg_Dbg(aout, "listing sink %s (%"PRIu32"): %s", i->name, i->index,
145 val.i_int = i->index;
146 text.psz_string = (char *)i->description;
147 /* FIXME: There is no way to replace a choice explicitly. */
148 var_Change(aout, "audio-device", VLC_VAR_DELCHOICE, &val, NULL);
149 var_Change(aout, "audio-device", VLC_VAR_ADDCHOICE, &val, &text);
150 /* FIXME: var_Change() can change the variable value if we remove the
151 * current value from the choice list, or if we add a choice while there
152 * was none. So force the correct value back. */
153 val.i_int = pa_stream_get_device_index(aout->sys->stream);
154 var_Change(aout, "audio-device", VLC_VAR_SETVALUE, &val, NULL);
157 static void sink_info_cb(pa_context *c, const pa_sink_info *i, int eol,
160 audio_output_t *aout = userdata;
161 aout_sys_t *sys = aout->sys;
167 /* PulseAudio flat volume NORM / 100% / 0dB corresponds to no software
168 * amplification and maximum hardware amplification.
169 * VLC maps DEFAULT / 100% to no gain at all (software/hardware).
170 * Thus we need to use the sink base_volume as a multiplier,
171 * if and only if flat volume is active for our current sink. */
172 if (i->flags & PA_SINK_FLAT_VOLUME)
173 sys->base_volume = i->base_volume;
175 sys->base_volume = PA_VOLUME_NORM;
176 msg_Dbg(aout, "base volume: %"PRIu32, sys->base_volume);
180 /*** Latency management and lip synchronization ***/
181 static void stream_reset_sync(pa_stream *s, audio_output_t *aout)
183 aout_sys_t *sys = aout->sys;
184 const unsigned rate = sys->nominal_rate;
186 sys->first_pts = VLC_TS_INVALID;
187 sys->last_pts = VLC_TS_INVALID;
189 pa_operation *op = pa_stream_update_sample_rate(s, rate, NULL, NULL);
190 if (unlikely(op == NULL))
192 pa_operation_unref(op);
193 sys->actual_rate = rate;
196 static void stream_start_now(pa_stream *s, audio_output_t *aout)
198 aout_sys_t *sys = aout->sys;
201 assert (sys->trigger == NULL);
203 op = pa_stream_cork(s, 0, NULL, NULL);
205 pa_operation_unref(op);
206 op = pa_stream_trigger(s, NULL, NULL);
207 if (likely(op != NULL))
208 pa_operation_unref(op);
211 static void stream_stop(pa_stream *s, audio_output_t *aout)
213 aout_sys_t *sys = aout->sys;
216 if (sys->trigger != NULL) {
217 vlc_pa_rttime_free(sys->mainloop, sys->trigger);
221 op = pa_stream_cork(s, 1, NULL, NULL);
223 pa_operation_unref(op);
226 static void stream_trigger_cb(pa_mainloop_api *api, pa_time_event *e,
227 const struct timeval *tv, void *userdata)
229 audio_output_t *aout = userdata;
230 aout_sys_t *sys = aout->sys;
232 assert (sys->trigger == e);
234 msg_Dbg(aout, "starting deferred");
235 vlc_pa_rttime_free(sys->mainloop, sys->trigger);
237 stream_start_now(sys->stream, aout);
238 (void) api; (void) e; (void) tv;
242 * Starts or resumes the playback stream.
243 * Tries start playing back audio samples at the most accurate time
244 * in order to minimize desync and resampling during early playback.
245 * @note PulseAudio lock required.
247 static void stream_start(pa_stream *s, audio_output_t *aout)
249 aout_sys_t *sys = aout->sys;
252 assert (sys->first_pts != VLC_TS_INVALID);
254 if (sys->trigger != NULL) {
255 vlc_pa_rttime_free(sys->mainloop, sys->trigger);
259 delta = vlc_pa_get_latency(aout, sys->context, s);
260 if (unlikely(delta == VLC_TS_INVALID)) {
261 msg_Dbg(aout, "cannot synchronize start");
262 delta = 0; /* screwed */
265 delta = (sys->first_pts - mdate()) - delta;
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);
272 msg_Warn(aout, "starting late (%"PRId64" us)", delta);
273 stream_start_now(s, aout);
277 static void stream_latency_cb(pa_stream *s, void *userdata)
279 audio_output_t *aout = userdata;
280 aout_sys_t *sys = aout->sys;
281 mtime_t delta, change;
283 if (sys->paused != VLC_TS_INVALID)
284 return; /* nothing to do while paused */
285 if (sys->last_pts == VLC_TS_INVALID) {
286 msg_Dbg(aout, "nothing to play");
287 assert (sys->first_pts == VLC_TS_INVALID);
290 if (pa_stream_is_corked(s) > 0) {
291 stream_start(s, aout);
295 /* Compute lip desynchronization */
296 delta = vlc_pa_get_latency(aout, sys->context, s);
297 if (delta == VLC_TS_INVALID)
300 delta = (sys->last_pts - mdate()) - delta;
301 change = delta - sys->desync;
303 //msg_Dbg(aout, "desync: %+"PRId64" us (variation: %+"PRId64" us)",
306 const unsigned inrate = sys->nominal_rate;
307 unsigned outrate = sys->actual_rate;
310 if (delta < -AOUT_MAX_PTS_DELAY)
311 msg_Warn(aout, "too late by %"PRId64" us", -delta);
312 else if (delta > +AOUT_MAX_PTS_ADVANCE)
313 msg_Warn(aout, "too early by %"PRId64" us", delta);
314 else if (outrate == inrate)
315 return; /* In sync, do not add unnecessary disturbance! */
319 /* Compute playback sample rate */
320 /* This is empirical (especially the shift values).
321 * Feel free to define something smarter. */
322 int adj = sync ? (outrate - inrate)
323 : outrate * ((delta >> 4) + change) / (CLOCK_FREQ << 2);
324 /* This avoids too quick rate variation. It sounds really bad and
325 * causes unstability (e.g. oscillation around the correct rate). */
326 int limit = inrate >> 10;
327 /* However, to improve stability and try to converge, closing to the
328 * nominal rate is favored over drifting from it. */
329 if ((adj > 0) == (sys->actual_rate > inrate))
337 /* This keeps the effective rate within specified range
338 * (+/-AOUT_MAX_RESAMPLING% - see <vlc_aout.h>) of the nominal rate. */
339 limit = inrate * AOUT_MAX_RESAMPLING / 100;
340 if (outrate > inrate + limit)
341 outrate = inrate + limit;
342 if (outrate < inrate - limit)
343 outrate = inrate - limit;
345 /* Apply adjusted sample rate */
346 if (outrate == sys->actual_rate)
348 pa_operation *op = pa_stream_update_sample_rate(s, outrate, NULL, NULL);
349 if (unlikely(op == NULL)) {
350 vlc_pa_error(aout, "cannot change sample rate", sys->context);
353 pa_operation_unref(op);
354 msg_Dbg(aout, "changed sample rate to %u Hz",outrate);
355 sys->actual_rate = outrate;
359 /*** Stream helpers ***/
360 static void stream_state_cb(pa_stream *s, void *userdata)
362 pa_threaded_mainloop *mainloop = userdata;
364 switch (pa_stream_get_state(s)) {
365 case PA_STREAM_READY:
366 case PA_STREAM_FAILED:
367 case PA_STREAM_TERMINATED:
368 pa_threaded_mainloop_signal(mainloop, 0);
374 static void stream_buffer_attr_cb(pa_stream *s, void *userdata)
376 audio_output_t *aout = userdata;
377 const pa_buffer_attr *pba = pa_stream_get_buffer_attr(s);
379 msg_Dbg(aout, "changed buffer metrics: maxlength=%u, tlength=%u, "
380 "prebuf=%u, minreq=%u",
381 pba->maxlength, pba->tlength, pba->prebuf, pba->minreq);
384 static void stream_event_cb(pa_stream *s, const char *name, pa_proplist *pl,
387 audio_output_t *aout = userdata;
389 if (!strcmp(name, PA_STREAM_EVENT_REQUEST_CORK))
390 aout_PolicyReport(aout, true);
392 if (!strcmp(name, PA_STREAM_EVENT_REQUEST_UNCORK))
393 aout_PolicyReport(aout, false);
395 #if PA_CHECK_VERSION(1,0,0)
396 /* FIXME: expose aout_Restart() directly */
397 if (!strcmp(name, PA_STREAM_EVENT_FORMAT_LOST)) {
398 vlc_value_t dummy = { .i_int = 0 };
400 msg_Dbg (aout, "format lost");
401 aout_ChannelsRestart (VLC_OBJECT(aout), "audio-device",
405 msg_Warn (aout, "unhandled stream event \"%s\"", name);
410 static void stream_moved_cb(pa_stream *s, void *userdata)
412 audio_output_t *aout = userdata;
413 aout_sys_t *sys = aout->sys;
415 uint32_t idx = pa_stream_get_device_index(s);
417 msg_Dbg(aout, "connected to sink %"PRIu32": %s", idx,
418 pa_stream_get_device_name(s));
419 op = pa_context_get_sink_info_by_index(sys->context, idx,
421 if (likely(op != NULL))
422 pa_operation_unref(op);
424 /* Update the variable if someone else moved our stream */
425 var_Change(aout, "audio-device", VLC_VAR_SETVALUE,
426 &(vlc_value_t){ .i_int = idx }, NULL);
428 /* Sink unknown as yet, create stub choice for it */
429 if (var_GetInteger(aout, "audio-device") != idx)
431 var_Change(aout, "audio-device", VLC_VAR_ADDCHOICE,
432 &(vlc_value_t){ .i_int = idx },
433 &(vlc_value_t){ .psz_string = (char *)"?" });
434 var_Change(aout, "audio-device", VLC_VAR_SETVALUE,
435 &(vlc_value_t){ .i_int = idx }, NULL);
439 static void stream_overflow_cb(pa_stream *s, void *userdata)
441 audio_output_t *aout = userdata;
444 msg_Err(aout, "overflow, flushing");
445 op = pa_stream_flush(s, NULL, NULL);
446 if (likely(op != NULL))
447 pa_operation_unref(op);
448 stream_reset_sync(s, aout);
451 static void stream_started_cb(pa_stream *s, void *userdata)
453 audio_output_t *aout = userdata;
455 msg_Dbg(aout, "started");
459 static void stream_suspended_cb(pa_stream *s, void *userdata)
461 audio_output_t *aout = userdata;
463 msg_Dbg(aout, "suspended");
467 static void stream_underflow_cb(pa_stream *s, void *userdata)
469 audio_output_t *aout = userdata;
471 msg_Warn(aout, "underflow");
472 stream_stop(s, aout);
473 stream_reset_sync(s, aout);
476 static int stream_wait(pa_stream *stream, pa_threaded_mainloop *mainloop)
478 pa_stream_state_t state;
480 while ((state = pa_stream_get_state(stream)) != PA_STREAM_READY) {
481 if (state == PA_STREAM_FAILED || state == PA_STREAM_TERMINATED)
483 pa_threaded_mainloop_wait(mainloop);
490 static void sink_input_info_cb(pa_context *ctx, const pa_sink_input_info *i,
491 int eol, void *userdata)
493 audio_output_t *aout = userdata;
494 aout_sys_t *sys = aout->sys;
500 sys->cvolume = i->volume; /* cache volume for balance preservation */
502 pa_volume_t volume = pa_cvolume_max(&i->volume);
503 volume = pa_sw_volume_divide(volume, sys->base_volume);
504 aout_VolumeReport(aout, (float)volume / PA_VOLUME_NORM);
505 aout_MuteReport(aout, i->mute);
509 /*** VLC audio output callbacks ***/
511 /* Memory free callback. The block_t address is in front of the data. */
512 static void data_free(void *data)
514 block_t **pp = data, *block;
516 memcpy(&block, pp - 1, sizeof (block));
517 block_Release(block);
520 static void *data_convert(block_t **pp)
522 block_t *block = *pp;
523 /* In most cases, there is enough head room, and this is really cheap: */
524 block = block_Realloc(block, sizeof (block), block->i_buffer);
526 if (unlikely(block == NULL))
529 memcpy(block->p_buffer, &block, sizeof (block));
530 block->p_buffer += sizeof (block);
531 block->i_buffer -= sizeof (block);
532 return block->p_buffer;
536 * Queue one audio frame to the playback stream
538 static void Play(audio_output_t *aout, block_t *block, mtime_t *restrict drift)
540 aout_sys_t *sys = aout->sys;
541 pa_stream *s = sys->stream;
543 assert (sys->paused == VLC_TS_INVALID);
545 const void *ptr = data_convert(&block);
546 if (unlikely(ptr == NULL))
549 size_t len = block->i_buffer;
550 mtime_t pts = block->i_pts + block->i_length;
552 /* Note: The core already holds the output FIFO lock at this point.
553 * Therefore we must not under any circumstances (try to) acquire the
554 * output FIFO lock while the PulseAudio threaded main loop lock is held
555 * (including from PulseAudio stream callbacks). Otherwise lock inversion
556 * will take place, and sooner or later a deadlock. */
557 pa_threaded_mainloop_lock(sys->mainloop);
559 if (sys->first_pts == VLC_TS_INVALID)
560 sys->first_pts = block->i_pts;
563 if (pa_stream_is_corked(s) > 0)
564 stream_start(s, aout);
566 #if 0 /* Fault injector to test underrun recovery */
567 static volatile unsigned u = 0;
568 if ((++u % 1000) == 0) {
569 msg_Err(aout, "fault injection");
570 pa_operation_unref(pa_stream_flush(s, NULL, NULL));
574 if (pa_stream_write(s, ptr, len, data_free, 0, PA_SEEK_RELATIVE) < 0) {
575 vlc_pa_error(aout, "cannot write", sys->context);
576 block_Release(block);
579 pa_threaded_mainloop_unlock(sys->mainloop);
584 * Cork or uncork the playback stream
586 static void Pause(audio_output_t *aout, bool paused, mtime_t date)
588 aout_sys_t *sys = aout->sys;
589 pa_stream *s = sys->stream;
591 pa_threaded_mainloop_lock(sys->mainloop);
595 stream_stop(s, aout);
597 assert (sys->paused != VLC_TS_INVALID);
599 msg_Dbg(aout, "resuming after %"PRId64" us", date);
600 sys->paused = VLC_TS_INVALID;
602 if (sys->last_pts != VLC_TS_INVALID) {
603 sys->first_pts += date;
604 sys->last_pts += date;
605 stream_start(s, aout);
609 pa_threaded_mainloop_unlock(sys->mainloop);
613 * Flush or drain the playback stream
615 static void Flush(audio_output_t *aout, bool wait)
617 aout_sys_t *sys = aout->sys;
618 pa_stream *s = sys->stream;
621 pa_threaded_mainloop_lock(sys->mainloop);
624 op = pa_stream_drain(s, NULL, NULL);
625 /* TODO: wait for drain completion*/
627 op = pa_stream_flush(s, NULL, NULL);
629 pa_operation_unref(op);
630 pa_threaded_mainloop_unlock(sys->mainloop);
633 static int VolumeSet(audio_output_t *aout, float vol)
635 aout_sys_t *sys = aout->sys;
636 if (sys->stream == NULL)
638 msg_Err (aout, "cannot change volume while not playing");
642 /* VLC provides the software volume so convert directly to PulseAudio
643 * software volume, pa_volume_t. This is not a linear amplification factor
644 * so do not use PulseAudio linear amplification! */
645 vol *= PA_VOLUME_NORM;
646 if (unlikely(vol >= PA_VOLUME_MAX))
648 pa_volume_t volume = pa_sw_volume_multiply(lround(vol), sys->base_volume);
650 /* Preserve the balance (VLC does not support it). */
651 pa_cvolume cvolume = sys->cvolume;
652 pa_cvolume_scale(&cvolume, PA_VOLUME_NORM);
653 pa_sw_cvolume_multiply_scalar(&cvolume, &cvolume, volume);
654 assert(pa_cvolume_valid(&cvolume));
657 uint32_t idx = pa_stream_get_index(sys->stream);
658 pa_threaded_mainloop_lock(sys->mainloop);
659 op = pa_context_set_sink_input_volume(sys->context, idx, &cvolume,
661 if (likely(op != NULL))
662 pa_operation_unref(op);
663 pa_threaded_mainloop_unlock(sys->mainloop);
668 static int MuteSet(audio_output_t *aout, bool mute)
670 aout_sys_t *sys = aout->sys;
671 if (sys->stream == NULL)
673 msg_Err (aout, "cannot change volume while not playing");
678 uint32_t idx = pa_stream_get_index(sys->stream);
679 pa_threaded_mainloop_lock(sys->mainloop);
680 op = pa_context_set_sink_input_mute(sys->context, idx, mute, NULL, NULL);
681 if (likely(op != NULL))
682 pa_operation_unref(op);
683 pa_threaded_mainloop_unlock(sys->mainloop);
688 static int StreamMove(vlc_object_t *obj, const char *varname, vlc_value_t old,
689 vlc_value_t val, void *userdata)
691 audio_output_t *aout = (audio_output_t *)obj;
692 aout_sys_t *sys = aout->sys;
693 pa_stream *s = userdata;
695 uint32_t idx = pa_stream_get_index(s);
696 uint32_t sink_idx = val.i_int;
698 (void) varname; (void) old;
700 pa_threaded_mainloop_lock(sys->mainloop);
701 op = pa_context_move_sink_input_by_index(sys->context, idx, sink_idx,
703 if (likely(op != NULL)) {
704 pa_operation_unref(op);
705 msg_Dbg(aout, "moving to sink %"PRIu32, sink_idx);
707 vlc_pa_error(obj, "cannot move sink", sys->context);
708 pa_threaded_mainloop_unlock(sys->mainloop);
710 return (op != NULL) ? VLC_SUCCESS : VLC_EGENERIC;
713 static void Stop(audio_output_t *);
716 * Create a PulseAudio playback stream, a.k.a. a sink input.
718 static int Start(audio_output_t *aout, audio_sample_format_t *restrict fmt)
720 aout_sys_t *sys = aout->sys;
723 /* Sample format specification */
724 struct pa_sample_spec ss;
725 #if PA_CHECK_VERSION(1,0,0)
726 pa_encoding_t encoding = PA_ENCODING_INVALID;
729 switch (fmt->i_format)
732 fmt->i_format = VLC_CODEC_F32B;
734 ss.format = PA_SAMPLE_FLOAT32BE;
737 fmt->i_format = VLC_CODEC_F32L;
739 ss.format = PA_SAMPLE_FLOAT32LE;
742 ss.format = PA_SAMPLE_S32BE;
745 ss.format = PA_SAMPLE_S32LE;
748 ss.format = PA_SAMPLE_S24BE;
751 ss.format = PA_SAMPLE_S24LE;
754 ss.format = PA_SAMPLE_S16BE;
757 ss.format = PA_SAMPLE_S16LE;
760 fmt->i_format = VLC_CODEC_U8;
762 ss.format = PA_SAMPLE_U8;
764 #if PA_CHECK_VERSION(1,0,0)
766 fmt->i_format = VLC_CODEC_SPDIFL;
767 encoding = PA_ENCODING_AC3_IEC61937;
768 ss.format = HAVE_FPU ? PA_SAMPLE_FLOAT32NE : PA_SAMPLE_S16NE;
770 /*case VLC_CODEC_EAC3:
771 fmt->i_format = VLC_CODEC_SPDIFL FIXME;
772 encoding = PA_ENCODING_EAC3_IEC61937;
773 ss.format = HAVE_FPU ? PA_SAMPLE_FLOAT32NE : PA_SAMPLE_S16NE;
776 fmt->i_format = VLC_CODEC_SPDIFL FIXME;
777 encoding = PA_ENCODING_MPEG_IEC61937;
778 ss.format = HAVE_FPU ? PA_SAMPLE_FLOAT32NE : PA_SAMPLE_S16NE;
781 fmt->i_format = VLC_CODEC_SPDIFL;
782 encoding = PA_ENCODING_DTS_IEC61937;
783 ss.format = HAVE_FPU ? PA_SAMPLE_FLOAT32NE : PA_SAMPLE_S16NE;
789 fmt->i_format = VLC_CODEC_FL32;
790 ss.format = PA_SAMPLE_FLOAT32NE;
794 fmt->i_format = VLC_CODEC_S16N;
795 ss.format = PA_SAMPLE_S16NE;
800 ss.rate = fmt->i_rate;
801 ss.channels = aout_FormatNbChannels(fmt);
802 if (!pa_sample_spec_valid(&ss)) {
803 msg_Err(aout, "unsupported sample specification");
807 /* Channel mapping (order defined in vlc_aout.h) */
808 struct pa_channel_map map;
811 if (fmt->i_physical_channels & AOUT_CHAN_LEFT)
812 map.map[map.channels++] = PA_CHANNEL_POSITION_FRONT_LEFT;
813 if (fmt->i_physical_channels & AOUT_CHAN_RIGHT)
814 map.map[map.channels++] = PA_CHANNEL_POSITION_FRONT_RIGHT;
815 if (fmt->i_physical_channels & AOUT_CHAN_MIDDLELEFT)
816 map.map[map.channels++] = PA_CHANNEL_POSITION_SIDE_LEFT;
817 if (fmt->i_physical_channels & AOUT_CHAN_MIDDLERIGHT)
818 map.map[map.channels++] = PA_CHANNEL_POSITION_SIDE_RIGHT;
819 if (fmt->i_physical_channels & AOUT_CHAN_REARLEFT)
820 map.map[map.channels++] = PA_CHANNEL_POSITION_REAR_LEFT;
821 if (fmt->i_physical_channels & AOUT_CHAN_REARRIGHT)
822 map.map[map.channels++] = PA_CHANNEL_POSITION_REAR_RIGHT;
823 if (fmt->i_physical_channels & AOUT_CHAN_REARCENTER)
824 map.map[map.channels++] = PA_CHANNEL_POSITION_REAR_CENTER;
825 if (fmt->i_physical_channels & AOUT_CHAN_CENTER)
827 if (ss.channels == 1)
828 map.map[map.channels++] = PA_CHANNEL_POSITION_MONO;
830 map.map[map.channels++] = PA_CHANNEL_POSITION_FRONT_CENTER;
832 if (fmt->i_physical_channels & AOUT_CHAN_LFE)
833 map.map[map.channels++] = PA_CHANNEL_POSITION_LFE;
835 for (unsigned i = 0; map.channels < ss.channels; i++) {
836 map.map[map.channels++] = PA_CHANNEL_POSITION_AUX0 + i;
837 msg_Warn(aout, "mapping channel %"PRIu8" to AUX%u", map.channels, i);
840 if (!pa_channel_map_valid(&map)) {
841 msg_Err(aout, "unsupported channel map");
844 const char *name = pa_channel_map_to_name(&map);
845 msg_Dbg(aout, "using %s channel map", (name != NULL) ? name : "?");
848 /* Stream parameters */
849 const pa_stream_flags_t flags = PA_STREAM_START_CORKED
850 //| PA_STREAM_INTERPOLATE_TIMING
851 | PA_STREAM_NOT_MONOTONIC
852 | PA_STREAM_AUTO_TIMING_UPDATE
853 | PA_STREAM_VARIABLE_RATE;
855 struct pa_buffer_attr attr;
857 /* PulseAudio assumes that tlength bytes are available in the buffer. Thus
858 * we need to be conservative and set the minimum value that the VLC
859 * audio decoder thread warrants. Otherwise, PulseAudio buffers will
860 * underrun on hardware with large buffers. VLC keeps at least
861 * AOUT_MIN_PREPARE and at most AOUT_MAX_PREPARE worth of audio buffers.
862 * TODO? tlength could be adaptively increased to reduce wakeups. */
863 attr.tlength = pa_usec_to_bytes(AOUT_MIN_PREPARE_TIME, &ss);
864 attr.prebuf = 0; /* trigger manually */
866 attr.fragsize = 0; /* not used for output */
870 sys->first_pts = VLC_TS_INVALID;
871 sys->last_pts = VLC_TS_INVALID;
872 sys->paused = VLC_TS_INVALID;
874 sys->nominal_rate = ss.rate;
875 sys->actual_rate = ss.rate;
878 sys->base_volume = PA_VOLUME_NORM;
879 pa_cvolume_set(&sys->cvolume, ss.channels, PA_VOLUME_NORM);
881 #if PA_CHECK_VERSION(1,0,0)
882 pa_format_info *formatv[2];
883 unsigned formatc = 0;
885 /* Favor digital pass-through if available*/
886 if (encoding != PA_ENCODING_INVALID) {
887 formatv[formatc] = pa_format_info_new();
888 formatv[formatc]->encoding = encoding;
889 pa_format_info_set_rate(formatv[formatc], ss.rate);
890 pa_format_info_set_channels(formatv[formatc], ss.channels);
891 pa_format_info_set_channel_map(formatv[formatc], &map);
895 /* Fallback to PCM */
896 formatv[formatc] = pa_format_info_new();
897 formatv[formatc]->encoding = PA_ENCODING_PCM;
898 pa_format_info_set_sample_format(formatv[formatc], ss.format);
899 pa_format_info_set_rate(formatv[formatc], ss.rate);
900 pa_format_info_set_channels(formatv[formatc], ss.channels);
901 pa_format_info_set_channel_map(formatv[formatc], &map);
904 /* Create a playback stream */
906 pa_proplist *props = pa_proplist_new();
907 if (likely(props != NULL))
908 /* TODO: set other stream properties */
909 pa_proplist_sets (props, PA_PROP_MEDIA_ROLE, "video");
911 pa_threaded_mainloop_lock(sys->mainloop);
912 s = pa_stream_new_extended(sys->context, "audio stream", formatv, formatc,
914 if (likely(props != NULL))
915 pa_proplist_free(props);
917 for (unsigned i = 0; i < formatc; i++)
918 pa_format_info_free(formatv[i]);
920 pa_threaded_mainloop_lock(sys->mainloop);
921 pa_stream *s = pa_stream_new(sys->context, "audio stream", &ss, &map);
924 pa_threaded_mainloop_unlock(sys->mainloop);
925 vlc_pa_error(aout, "stream creation failure", sys->context);
929 pa_stream_set_state_callback(s, stream_state_cb, sys->mainloop);
930 pa_stream_set_buffer_attr_callback(s, stream_buffer_attr_cb, aout);
931 pa_stream_set_event_callback(s, stream_event_cb, aout);
932 pa_stream_set_latency_update_callback(s, stream_latency_cb, aout);
933 pa_stream_set_moved_callback(s, stream_moved_cb, aout);
934 pa_stream_set_overflow_callback(s, stream_overflow_cb, aout);
935 pa_stream_set_started_callback(s, stream_started_cb, aout);
936 pa_stream_set_suspended_callback(s, stream_suspended_cb, aout);
937 pa_stream_set_underflow_callback(s, stream_underflow_cb, aout);
939 if (pa_stream_connect_playback(s, NULL, &attr, flags, NULL, NULL) < 0
940 || stream_wait(s, sys->mainloop)) {
941 vlc_pa_error(aout, "stream connection failure", sys->context);
945 #if PA_CHECK_VERSION(1,0,0)
946 if (encoding != PA_ENCODING_INVALID) {
947 const pa_format_info *info = pa_stream_get_format_info(s);
949 assert (info != NULL);
950 if (pa_format_info_is_pcm (info)) {
951 msg_Dbg(aout, "digital pass-through not available");
952 fmt->i_format = HAVE_FPU ? VLC_CODEC_FL32 : VLC_CODEC_S16N;
954 msg_Dbg(aout, "digital pass-through enabled");
955 pa_stream_set_latency_update_callback(s, NULL, NULL);
959 stream_buffer_attr_cb(s, aout);
961 var_Create(aout, "audio-device", VLC_VAR_INTEGER|VLC_VAR_HASCHOICE);
962 var_Change(aout, "audio-device", VLC_VAR_SETTEXT,
963 &(vlc_value_t){ .psz_string = (char *)_("Audio device") },
965 var_AddCallback (aout, "audio-device", StreamMove, s);
966 op = pa_context_get_sink_info_list(sys->context, sink_list_cb, aout);
967 /* We may need to wait for completion... once LibVLC supports this */
969 pa_operation_unref(op);
970 stream_moved_cb(s, aout);
973 const pa_subscription_mask_t mask = PA_SUBSCRIPTION_MASK_SINK
974 | PA_SUBSCRIPTION_MASK_SINK_INPUT;
975 pa_context_set_subscribe_callback(sys->context, context_cb, aout);
976 op = pa_context_subscribe(sys->context, mask, NULL, NULL);
977 if (likely(op != NULL))
978 pa_operation_unref(op);
979 pa_threaded_mainloop_unlock(sys->mainloop);
984 pa_threaded_mainloop_unlock(sys->mainloop);
990 * Removes a PulseAudio playback stream
992 static void Stop(audio_output_t *aout)
994 aout_sys_t *sys = aout->sys;
995 pa_stream *s = sys->stream;
997 /* The callback takes mainloop lock, so it CANNOT be held here! */
998 var_DelCallback (aout, "audio-device", StreamMove, s);
999 var_Destroy (aout, "audio-device");
1001 pa_threaded_mainloop_lock(sys->mainloop);
1002 if (unlikely(sys->trigger != NULL))
1003 vlc_pa_rttime_free(sys->mainloop, sys->trigger);
1004 pa_stream_disconnect(s);
1006 /* Clear all callbacks */
1007 pa_stream_set_state_callback(s, NULL, NULL);
1008 pa_stream_set_buffer_attr_callback(s, NULL, NULL);
1009 pa_stream_set_event_callback(s, NULL, NULL);
1010 pa_stream_set_latency_update_callback(s, NULL, NULL);
1011 pa_stream_set_moved_callback(s, NULL, NULL);
1012 pa_stream_set_overflow_callback(s, NULL, NULL);
1013 pa_stream_set_started_callback(s, NULL, NULL);
1014 pa_stream_set_suspended_callback(s, NULL, NULL);
1015 pa_stream_set_underflow_callback(s, NULL, NULL);
1016 pa_context_set_subscribe_callback(sys->context, NULL, NULL);
1019 pa_threaded_mainloop_unlock(sys->mainloop);
1022 static int Open(vlc_object_t *obj)
1024 audio_output_t *aout = (audio_output_t *)obj;
1025 aout_sys_t *sys = malloc(sizeof (*sys));
1027 #if !PA_CHECK_VERSION(0,9,22)
1028 if (!vlc_xlib_init(obj))
1029 return VLC_EGENERIC;
1031 if (unlikely(sys == NULL))
1034 /* Allocate structures */
1035 pa_context *ctx = vlc_pa_connect(obj, &sys->mainloop);
1039 return VLC_EGENERIC;
1044 aout->start = Start;
1047 aout->pause = Pause;
1048 aout->flush = Flush;
1049 aout->volume_set = VolumeSet;
1050 aout->mute_set = MuteSet;
1054 static void Close(vlc_object_t *obj)
1056 audio_output_t *aout = (audio_output_t *)obj;
1057 aout_sys_t *sys = aout->sys;
1058 pa_context *ctx = sys->context;
1060 vlc_pa_disconnect(obj, ctx, sys->mainloop);