]> git.sesse.net Git - vlc/blob - modules/audio_output/pulse.c
2c6de917d96967c2de1c2bf824892267112ec3da
[vlc] / modules / audio_output / pulse.c
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
6  *
7  * Authors: Martin Hamrle <hamrle @ post . cz>
8  *
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.
13  *
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.
18  *
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  *****************************************************************************/
23
24 #ifdef HAVE_CONFIG_H
25 # include "config.h"
26 #endif
27
28 #include <math.h>
29 #include <vlc_common.h>
30 #include <vlc_plugin.h>
31 #include <vlc_aout.h>
32 #include <vlc_cpu.h>
33
34 #include <pulse/pulseaudio.h>
35 #include <vlc_pulse.h>
36 #if !PA_CHECK_VERSION(0,9,22)
37 # include <vlc_xlib.h>
38 #endif
39
40 static int  Open        ( vlc_object_t * );
41 static void Close       ( vlc_object_t * );
42
43 vlc_module_begin ()
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 )
51 vlc_module_end ()
52
53 /* TODO:
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
59  */
60
61 /* NOTE:
62  * Be careful what you do when the PulseAudio mainloop is held, which is to say
63  * within PulseAudio callbacks, or after vlc_pa_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. */
66
67 struct aout_sys_t
68 {
69     pa_stream *stream; /**< PulseAudio playback stream object */
70     pa_context *context; /**< PulseAudio connection context */
71     pa_volume_t base_volume; /**< 0dB reference volume */
72     pa_cvolume cvolume; /**< actual sink input volume */
73     mtime_t paused; /**< Time when (last) paused */
74     mtime_t pts; /**< Play time of buffer write offset */
75     mtime_t desync; /**< Measured desynchronization */
76     unsigned rate; /**< Current stream sample rate */
77 };
78
79 static void sink_input_info_cb(pa_context *, const pa_sink_input_info *,
80                                int, void *);
81
82 /*** Context ***/
83 static void context_cb(pa_context *ctx, pa_subscription_event_type_t type,
84                        uint32_t idx, void *userdata)
85 {
86     audio_output_t *aout = userdata;
87     aout_sys_t *sys = aout->sys;
88     pa_operation *op;
89
90     switch (type & PA_SUBSCRIPTION_EVENT_FACILITY_MASK)
91     {
92       case PA_SUBSCRIPTION_EVENT_SINK_INPUT:
93         if (idx != pa_stream_get_index(sys->stream))
94             break; /* only interested in our sink input */
95
96         /* Gee... PA will not provide the infos directly in the event. */
97         switch (type & PA_SUBSCRIPTION_EVENT_TYPE_MASK)
98         {
99           case PA_SUBSCRIPTION_EVENT_REMOVE:
100             msg_Err(aout, "sink input killed!");
101             break;
102
103           default:
104             op = pa_context_get_sink_input_info(ctx, idx, sink_input_info_cb,
105                                                 aout);
106             if (likely(op != NULL))
107                 pa_operation_unref(op);
108             break;
109         }
110         break;
111
112       default: /* unsubscribed facility?! */
113         assert(0);
114     }
115 }
116
117
118 /*** Sink ***/
119 static void sink_list_cb(pa_context *c, const pa_sink_info *i, int eol,
120                          void *userdata)
121 {
122     audio_output_t *aout = userdata;
123     vlc_value_t val, text;
124
125     if (eol)
126         return;
127     (void) c;
128
129     msg_Dbg(aout, "listing sink %s (%"PRIu32"): %s", i->name, i->index,
130             i->description);
131     val.i_int = i->index;
132     text.psz_string = (char *)i->description;
133     var_Change(aout, "audio-device", VLC_VAR_ADDCHOICE, &val, &text);
134 }
135
136 static void sink_info_cb(pa_context *c, const pa_sink_info *i, int eol,
137                          void *userdata)
138 {
139     audio_output_t *aout = userdata;
140     aout_sys_t *sys = aout->sys;
141
142     if (eol)
143         return;
144     (void) c;
145
146     /* PulseAudio flat volume NORM / 100% / 0dB corresponds to no software
147      * amplification and maximum hardware amplification.
148      * VLC maps DEFAULT / 100% to no gain at all (software/hardware).
149      * Thus we need to use the sink base_volume as a multiplier,
150      * if and only if flat volume is active for our current sink. */
151     if (i->flags & PA_SINK_FLAT_VOLUME)
152         sys->base_volume = i->base_volume;
153     else
154         sys->base_volume = PA_VOLUME_NORM;
155     msg_Dbg(aout, "base volume: %"PRIu32, sys->base_volume);
156 }
157
158
159 /*** Latency management and lip synchronization ***/
160 static mtime_t vlc_pa_get_latency(audio_output_t *aout,
161                                   pa_context *ctx, pa_stream *s)
162 {
163     pa_usec_t latency;
164     int negative;
165
166     if (pa_stream_get_latency(s, &latency, &negative)) {
167         vlc_pa_error(aout, "unknown latency", ctx);
168         return VLC_TS_INVALID;
169     }
170     return negative ? -latency : +latency;
171 }
172
173 static void stream_reset_sync(pa_stream *s, audio_output_t *aout)
174 {
175     aout_sys_t *sys = aout->sys;
176     const unsigned rate = aout->format.i_rate;
177
178     sys->pts = VLC_TS_INVALID;
179     sys->desync = 0;
180     pa_operation *op = pa_stream_update_sample_rate(s, rate, NULL, NULL);
181     if (unlikely(op == NULL))
182         return;
183     pa_operation_unref(op);
184     sys->rate = rate;
185 }
186
187 /**
188  * Starts or resumes the playback stream.
189  * Tries start playing back audio samples at the most accurate time
190  * in order to minimize desync and resampling during early playback.
191  * @note PulseAudio lock required.
192  */
193 static void stream_resync(audio_output_t *aout, pa_stream *s)
194 {
195     aout_sys_t *sys = aout->sys;
196     pa_operation *op;
197     mtime_t delta;
198
199     assert (pa_stream_is_corked(s) > 0);
200     assert (sys->pts != VLC_TS_INVALID);
201
202     delta = vlc_pa_get_latency(aout, sys->context, s);
203     if (unlikely(delta == VLC_TS_INVALID))
204         delta = 0; /* screwed */
205
206     delta = (sys->pts - mdate()) - delta;
207
208     /* TODO: adjust prebuf instead of padding? */
209     if (delta > 0) {
210         size_t nb = (delta * sys->rate) / CLOCK_FREQ;
211         size_t size = aout->format.i_bytes_per_frame;
212         float *zeroes = calloc (nb, size);
213
214         msg_Dbg(aout, "starting with %zu zeroes (%"PRId64" us)", nb,
215                 delta);
216 #if 0 /* Fault injector: add delay */
217         pa_stream_write(s, zeroes, nb * size, NULL, 0, PA_SEEK_RELATIVE);
218         pa_stream_write(s, zeroes, nb * size, NULL, 0, PA_SEEK_RELATIVE);
219 #endif
220         if (likely(zeroes != NULL))
221             if (pa_stream_write(s, zeroes, nb * size, free, 0,
222                                 PA_SEEK_RELATIVE) < 0)
223                 free(zeroes);
224     } else
225         msg_Warn(aout, "starting late (%"PRId64" us)", delta);
226
227     op = pa_stream_cork(s, 0, NULL, NULL);
228     if (op != NULL)
229         pa_operation_unref(op);
230     op = pa_stream_trigger(s, NULL, NULL);
231     if (op != NULL)
232         pa_operation_unref(op);
233 }
234
235 static void stream_latency_cb(pa_stream *s, void *userdata)
236 {
237     audio_output_t *aout = userdata;
238     aout_sys_t *sys = aout->sys;
239     mtime_t delta, change;
240
241     if (pa_stream_is_corked(s))
242         return;
243     if (sys->pts == VLC_TS_INVALID)
244     {
245         msg_Dbg(aout, "missing latency from input");
246         return;
247     }
248
249     /* Compute lip desynchronization */
250     delta = vlc_pa_get_latency(aout, sys->context, s);
251     if (delta == VLC_TS_INVALID)
252         return;
253
254     delta = (sys->pts - mdate()) - delta;
255     change = delta - sys->desync;
256     sys->desync = delta;
257     //msg_Dbg(aout, "desync: %+"PRId64" us (variation: %+"PRId64" us)",
258     //        delta, change);
259
260     const unsigned inrate = aout->format.i_rate;
261     unsigned outrate = sys->rate;
262     bool sync = false;
263
264     if (delta < -AOUT_MAX_PTS_DELAY)
265         msg_Warn(aout, "too late by %"PRId64" us", -delta);
266     else if (delta > +AOUT_MAX_PTS_ADVANCE)
267         msg_Warn(aout, "too early by %"PRId64" us", delta);
268     else if (outrate  == inrate)
269         return; /* In sync, do not add unnecessary disturbance! */
270     else
271         sync = true;
272
273     /* Compute playback sample rate */
274     /* This is empirical. Feel free to define something smarter. */
275     int adj = sync ? (outrate - inrate)
276                    : outrate * (delta + change) / (CLOCK_FREQ << 4);
277     /* This avoids too quick rate variation. It sounds really bad and
278      * causes unstability (e.g. oscillation around the correct rate). */
279     int limit = inrate >> 10;
280     /* However, to improve stability and try to converge, closing to the
281      * nominal rate is favored over drifting from it. */
282     if ((adj > 0) == (sys->rate > inrate))
283         limit *= 2;
284     if (adj > +limit)
285         adj = +limit;
286     if (adj < -limit)
287         adj = -limit;
288     outrate -= adj;
289
290     /* This keeps the effective rate within specified range
291      * (+/-AOUT_MAX_RESAMPLING% - see <vlc_aout.h>) of the nominal rate. */
292     limit = inrate * AOUT_MAX_RESAMPLING / 100;
293     if (outrate > inrate + limit)
294         outrate = inrate + limit;
295     if (outrate < inrate - limit)
296         outrate = inrate - limit;
297
298     /* Apply adjusted sample rate */
299     if (outrate == sys->rate)
300         return;
301     pa_operation *op = pa_stream_update_sample_rate(s, outrate, NULL, NULL);
302     if (unlikely(op == NULL)) {
303         vlc_pa_error(aout, "cannot change sample rate", sys->context);
304         return;
305     }
306     pa_operation_unref(op);
307     msg_Dbg(aout, "changed sample rate to %u Hz",outrate);
308     sys->rate = outrate;
309 }
310
311
312 /*** Stream helpers ***/
313 static void stream_state_cb(pa_stream *s, void *userdata)
314 {
315     switch (pa_stream_get_state(s)) {
316         case PA_STREAM_READY:
317         case PA_STREAM_FAILED:
318         case PA_STREAM_TERMINATED:
319             vlc_pa_signal(0);
320         default:
321             break;
322     }
323     (void) userdata;
324 }
325
326 static void stream_moved_cb(pa_stream *s, void *userdata)
327 {
328     audio_output_t *aout = userdata;
329     aout_sys_t *sys = aout->sys;
330     pa_operation *op;
331     uint32_t idx = pa_stream_get_device_index(s);
332
333     msg_Dbg(aout, "connected to sink %"PRIu32": %s", idx,
334                   pa_stream_get_device_name(s));
335     op = pa_context_get_sink_info_by_index(sys->context, idx,
336                                            sink_info_cb, aout);
337     if (likely(op != NULL))
338         pa_operation_unref(op);
339
340     /* Update the variable if someone else moved our stream */
341     var_Change(aout, "audio-device", VLC_VAR_SETVALUE,
342                &(vlc_value_t){ .i_int = idx }, NULL);
343 }
344
345 static void stream_overflow_cb(pa_stream *s, void *userdata)
346 {
347     audio_output_t *aout = userdata;
348
349     msg_Err(aout, "overflow");
350     (void) s;
351 }
352
353 static void stream_started_cb(pa_stream *s, void *userdata)
354 {
355     audio_output_t *aout = userdata;
356
357     msg_Dbg(aout, "started");
358     (void) s;
359 }
360
361 static void stream_suspended_cb(pa_stream *s, void *userdata)
362 {
363     audio_output_t *aout = userdata;
364
365     msg_Dbg(aout, "suspended");
366     stream_reset_sync(s, aout);
367 }
368
369 static void stream_underflow_cb(pa_stream *s, void *userdata)
370 {
371     audio_output_t *aout = userdata;
372     pa_operation *op;
373
374     msg_Warn(aout, "underflow");
375     op = pa_stream_cork(s, 1, NULL, NULL);
376     if (op != NULL)
377         pa_operation_unref(op);
378     stream_reset_sync(s, aout);
379 }
380
381 static int stream_wait(pa_stream *stream)
382 {
383     pa_stream_state_t state;
384
385     while ((state = pa_stream_get_state(stream)) != PA_STREAM_READY) {
386         if (state == PA_STREAM_FAILED || state == PA_STREAM_TERMINATED)
387             return -1;
388         vlc_pa_wait();
389     }
390     return 0;
391 }
392
393 #ifdef LIBPULSE_GETS_A_CLUE
394 static void stream_success_cb(pa_stream *s, int success, void *userdata)
395 {
396     vlc_pa_signal(0);
397     (void) s; (void) success; (void) userdata;
398 }
399 #else
400 # define stream_success_cb NULL
401 #endif
402
403
404 /*** Sink input ***/
405 static void sink_input_info_cb(pa_context *ctx, const pa_sink_input_info *i,
406                                int eol, void *userdata)
407 {
408     audio_output_t *aout = userdata;
409     aout_sys_t *sys = aout->sys;
410     float volume;
411
412     if (eol)
413         return;
414     (void) ctx;
415
416     sys->cvolume = i->volume;
417     volume = pa_cvolume_max(&i->volume) / (float)PA_VOLUME_NORM;
418     aout_VolumeHardSet(aout, volume, i->mute);
419 }
420
421
422 /*** VLC audio output callbacks ***/
423
424 /* Memory free callback. The block_t address is in front of the data. */
425 static void data_free(void *data)
426 {
427     block_t **pp = data, *block;
428
429     memcpy(&block, pp - 1, sizeof (block));
430     block_Release(block);
431 }
432
433 static void *data_convert(block_t **pp)
434 {
435     block_t *block = *pp;
436     /* In most cases, there is enough head room, and this is really cheap: */
437     block = block_Realloc(block, sizeof (block), block->i_buffer);
438     *pp = block;
439     if (unlikely(block == NULL))
440         return NULL;
441
442     memcpy(block->p_buffer, &block, sizeof (block));
443     block->p_buffer += sizeof (block);
444     block->i_buffer -= sizeof (block);
445     return block->p_buffer;
446 }
447
448 /**
449  * Queue one audio frame to the playabck stream
450  */
451 static void Play(audio_output_t *aout, block_t *block)
452 {
453     aout_sys_t *sys = aout->sys;
454     pa_stream *s = sys->stream;
455
456     const void *ptr = data_convert(&block);
457     if (unlikely(ptr == NULL))
458         return;
459
460     size_t len = block->i_buffer;
461     mtime_t pts = block->i_pts + block->i_length;
462
463     /* Note: The core already holds the output FIFO lock at this point.
464      * Therefore we must not under any circumstances (try to) acquire the
465      * output FIFO lock while the PulseAudio threaded main loop lock is held
466      * (including from PulseAudio stream callbacks). Otherwise lock inversion
467      * will take place, and sooner or later a deadlock. */
468     vlc_pa_lock();
469
470     sys->pts = pts;
471     if (pa_stream_is_corked(s) > 0)
472         stream_resync(aout, s);
473
474 #if 0 /* Fault injector to test underrun recovery */
475     static volatile unsigned u = 0;
476     if ((++u % 1000) == 0) {
477         msg_Err(aout, "fault injection");
478         pa_operation_unref(pa_stream_flush(s, NULL, NULL));
479     }
480 #endif
481
482     if (pa_stream_write(s, ptr, len, data_free, 0, PA_SEEK_RELATIVE) < 0) {
483         vlc_pa_error(aout, "cannot write", sys->context);
484         block_Release(block);
485     }
486
487     vlc_pa_unlock();
488 }
489
490 /**
491  * Cork or uncork the playback stream
492  */
493 static void Pause(audio_output_t *aout, bool paused, mtime_t date)
494 {
495     aout_sys_t *sys = aout->sys;
496     pa_stream *s = sys->stream;
497     pa_operation *op;
498
499     vlc_pa_lock();
500
501     if (paused) {
502         sys->paused = date;
503         op = pa_stream_cork(s, paused, NULL, NULL);
504         if (op != NULL)
505             pa_operation_unref(op);
506     } else {
507         assert (sys->paused != VLC_TS_INVALID);
508         date -= sys->paused;
509         msg_Dbg(aout, "resuming after %"PRId64" us", date);
510         sys->paused = VLC_TS_INVALID;
511         sys->pts += date;
512         stream_resync(aout, s);
513     }
514
515     vlc_pa_unlock();
516 }
517
518 /**
519  * Flush or drain the playback stream
520  */
521 static void Flush(audio_output_t *aout, bool wait)
522 {
523     aout_sys_t *sys = aout->sys;
524     pa_stream *s = sys->stream;
525     pa_operation *op;
526
527     vlc_pa_lock();
528
529     if (wait)
530         op = pa_stream_drain(s, NULL, NULL);
531         /* TODO: wait for drain completion*/
532     else
533         op = pa_stream_flush(s, NULL, NULL);
534     if (op != NULL)
535         pa_operation_unref(op);
536     vlc_pa_unlock();
537 }
538
539 static int VolumeSet(audio_output_t *aout, float vol, bool mute)
540 {
541     aout_sys_t *sys = aout->sys;
542     pa_operation *op;
543     uint32_t idx = pa_stream_get_index(sys->stream);
544
545     pa_cvolume cvolume = sys->cvolume;
546     pa_volume_t volume = sys->base_volume;
547
548     pa_cvolume_scale(&cvolume, PA_VOLUME_NORM); /* preserve balance */
549
550     /* VLC provides the software volume so convert directly to PulseAudio
551      * software volume, pa_volume_t. This is not a linear amplification factor
552      * so do not use PulseAudio linear amplification! */
553     vol *= PA_VOLUME_NORM;
554     if (unlikely(vol >= PA_VOLUME_MAX))
555         vol = PA_VOLUME_MAX;
556     volume = pa_sw_volume_multiply(volume, lround(vol));
557     pa_sw_cvolume_multiply_scalar(&cvolume, &cvolume, volume);
558
559     assert(pa_cvolume_valid(&cvolume));
560
561     vlc_pa_lock();
562     op = pa_context_set_sink_input_volume(sys->context, idx, &cvolume, NULL, NULL);
563     if (likely(op != NULL))
564         pa_operation_unref(op);
565     op = pa_context_set_sink_input_mute(sys->context, idx, mute, NULL, NULL);
566     if (likely(op != NULL))
567         pa_operation_unref(op);
568     vlc_pa_unlock();
569
570     return 0;
571 }
572
573 static int StreamMove(vlc_object_t *obj, const char *varname, vlc_value_t old,
574                       vlc_value_t val, void *userdata)
575 {
576     audio_output_t *aout = (audio_output_t *)obj;
577     aout_sys_t *sys = aout->sys;
578     pa_stream *s = userdata;
579     pa_operation *op;
580     uint32_t idx = pa_stream_get_index(s);
581     uint32_t sink_idx = val.i_int;
582
583     (void) varname; (void) old;
584
585     vlc_pa_lock();
586     op = pa_context_move_sink_input_by_index(sys->context, idx, sink_idx,
587                                              NULL, NULL);
588     if (likely(op != NULL)) {
589         pa_operation_unref(op);
590         msg_Dbg(aout, "moving to sink %"PRIu32, sink_idx);
591     } else
592         vlc_pa_error(obj, "cannot move sink", sys->context);
593     vlc_pa_unlock();
594
595     return (op != NULL) ? VLC_SUCCESS : VLC_EGENERIC;
596 }
597
598
599 /**
600  * Create a PulseAudio playback stream, a.k.a. a sink input.
601  */
602 static int Open(vlc_object_t *obj)
603 {
604 #if !PA_CHECK_VERSION(0,9,22)
605     if (!vlc_xlib_init(obj))
606         return VLC_EGENERIC;
607 #endif
608
609     audio_output_t *aout = (audio_output_t *)obj;
610     pa_operation *op;
611
612     /* Sample format specification */
613     struct pa_sample_spec ss;
614     vlc_fourcc_t format = aout->format.i_format;
615
616     switch(format)
617     {
618         case VLC_CODEC_F64B:
619             format = VLC_CODEC_F32B;
620         case VLC_CODEC_F32B:
621             ss.format = PA_SAMPLE_FLOAT32BE;
622             break;
623         case VLC_CODEC_F64L:
624             format = VLC_CODEC_F32L;
625         case VLC_CODEC_F32L:
626             ss.format = PA_SAMPLE_FLOAT32LE;
627             break;
628         case VLC_CODEC_FI32:
629             format = VLC_CODEC_FL32;
630             ss.format = PA_SAMPLE_FLOAT32NE;
631             break;
632         case VLC_CODEC_S32B:
633             ss.format = PA_SAMPLE_S32BE;
634             break;
635         case VLC_CODEC_S32L:
636             ss.format = PA_SAMPLE_S32LE;
637             break;
638         case VLC_CODEC_S24B:
639             ss.format = PA_SAMPLE_S24BE;
640             break;
641         case VLC_CODEC_S24L:
642             ss.format = PA_SAMPLE_S24LE;
643             break;
644         case VLC_CODEC_S16B:
645             ss.format = PA_SAMPLE_S16BE;
646             break;
647         case VLC_CODEC_S16L:
648             ss.format = PA_SAMPLE_S16LE;
649             break;
650         case VLC_CODEC_S8:
651             format = VLC_CODEC_U8;
652         case VLC_CODEC_U8:
653             ss.format = PA_SAMPLE_U8;
654             break;
655         default:
656             if (HAVE_FPU)
657             {
658                 format = VLC_CODEC_FL32;
659                 ss.format = PA_SAMPLE_FLOAT32NE;
660             }
661             else
662             {
663                 format = VLC_CODEC_S16N;
664                 ss.format = PA_SAMPLE_S16NE;
665             }
666             break;
667     }
668
669     ss.rate = aout->format.i_rate;
670     ss.channels = aout_FormatNbChannels(&aout->format);
671     if (!pa_sample_spec_valid(&ss)) {
672         msg_Err(aout, "unsupported sample specification");
673         return VLC_EGENERIC;
674     }
675
676     /* Channel mapping (order defined in vlc_aout.h) */
677     struct pa_channel_map map;
678     map.channels = 0;
679
680     if (aout->format.i_physical_channels & AOUT_CHAN_LEFT)
681         map.map[map.channels++] = PA_CHANNEL_POSITION_FRONT_LEFT;
682     if (aout->format.i_physical_channels & AOUT_CHAN_RIGHT)
683         map.map[map.channels++] = PA_CHANNEL_POSITION_FRONT_RIGHT;
684     if (aout->format.i_physical_channels & AOUT_CHAN_MIDDLELEFT)
685         map.map[map.channels++] = PA_CHANNEL_POSITION_SIDE_LEFT;
686     if (aout->format.i_physical_channels & AOUT_CHAN_MIDDLERIGHT)
687         map.map[map.channels++] = PA_CHANNEL_POSITION_SIDE_RIGHT;
688     if (aout->format.i_physical_channels & AOUT_CHAN_REARLEFT)
689         map.map[map.channels++] = PA_CHANNEL_POSITION_REAR_LEFT;
690     if (aout->format.i_physical_channels & AOUT_CHAN_REARRIGHT)
691         map.map[map.channels++] = PA_CHANNEL_POSITION_REAR_RIGHT;
692     if (aout->format.i_physical_channels & AOUT_CHAN_REARCENTER)
693         map.map[map.channels++] = PA_CHANNEL_POSITION_REAR_CENTER;
694     if (aout->format.i_physical_channels & AOUT_CHAN_CENTER)
695     {
696         if (ss.channels == 1)
697             map.map[map.channels++] = PA_CHANNEL_POSITION_MONO;
698         else
699             map.map[map.channels++] = PA_CHANNEL_POSITION_FRONT_CENTER;
700     }
701     if (aout->format.i_physical_channels & AOUT_CHAN_LFE)
702         map.map[map.channels++] = PA_CHANNEL_POSITION_LFE;
703
704     for (unsigned i = 0; map.channels < ss.channels; i++) {
705         map.map[map.channels++] = PA_CHANNEL_POSITION_AUX0 + i;
706         msg_Warn(aout, "mapping channel %"PRIu8" to AUX%u", map.channels, i);
707     }
708
709     if (!pa_channel_map_valid(&map)) {
710         msg_Err(aout, "unsupported channel map");
711         return VLC_EGENERIC;
712     } else {
713         const char *name = pa_channel_map_to_name(&map);
714         msg_Dbg(aout, "using %s channel map", (name != NULL) ? name : "?");
715     }
716
717     /* Stream parameters */
718     const pa_stream_flags_t flags = PA_STREAM_START_CORKED
719                                   //| PA_STREAM_INTERPOLATE_TIMING
720                                   | PA_STREAM_AUTO_TIMING_UPDATE
721                                   | PA_STREAM_VARIABLE_RATE;
722
723     struct pa_buffer_attr attr;
724     attr.maxlength = -1;
725     /* PulseAudio assumes that tlength bytes are available in the buffer. Thus
726      * we need to be conservative and set the minimum value that the VLC
727      * audio decoder thread warrants. Otherwise, PulseAudio buffers will
728      * underrun on hardware with large buffers. VLC keeps at least
729      * AOUT_MIN_PREPARE and at most AOUT_MAX_PREPARE worth of audio buffers.
730      * TODO? tlength could be adaptively increased to reduce wakeups. */
731     attr.tlength = pa_usec_to_bytes(AOUT_MIN_PREPARE_TIME, &ss);
732     attr.prebuf = 0; /* trigger manually */
733     attr.minreq = -1;
734     attr.fragsize = 0; /* not used for output */
735
736     /* Allocate structures */
737     aout_sys_t *sys = malloc(sizeof(*sys));
738     if (unlikely(sys == NULL))
739         return VLC_ENOMEM;
740
741     pa_context *ctx = vlc_pa_connect (obj);
742     if (ctx == NULL)
743     {
744         free (sys);
745         return VLC_EGENERIC;
746     }
747
748     aout->sys = sys;
749     sys->stream = NULL;
750     sys->context = ctx;
751     sys->paused = VLC_TS_INVALID;
752     sys->pts = VLC_TS_INVALID;
753     sys->desync = 0;
754     sys->rate = ss.rate;
755
756     /* Context events */
757     const pa_subscription_mask_t mask = PA_SUBSCRIPTION_MASK_SINK_INPUT;
758
759     pa_context_set_subscribe_callback(ctx, context_cb, aout);
760     op = pa_context_subscribe(ctx, mask, NULL, NULL);
761     if (likely(op != NULL))
762        pa_operation_unref(op);
763
764     /* Channel volume */
765     sys->base_volume = PA_VOLUME_NORM;
766     pa_cvolume_set(&sys->cvolume, ss.channels, PA_VOLUME_NORM);
767
768     vlc_pa_lock();
769     /* Create a playback stream */
770     pa_stream *s = pa_stream_new(ctx, "audio stream", &ss, &map);
771     if (s == NULL) {
772         vlc_pa_error(obj, "stream creation failure", ctx);
773         goto fail;
774     }
775     sys->stream = s;
776     pa_stream_set_state_callback(s, stream_state_cb, NULL);
777     pa_stream_set_latency_update_callback(s, stream_latency_cb, aout);
778     pa_stream_set_moved_callback(s, stream_moved_cb, aout);
779     pa_stream_set_overflow_callback(s, stream_overflow_cb, aout);
780     pa_stream_set_started_callback(s, stream_started_cb, aout);
781     pa_stream_set_suspended_callback(s, stream_suspended_cb, aout);
782     pa_stream_set_underflow_callback(s, stream_underflow_cb, aout);
783
784     if (pa_stream_connect_playback(s, NULL, &attr, flags, NULL, NULL) < 0
785      || stream_wait(s)) {
786         vlc_pa_error(obj, "stream connection failure", ctx);
787         goto fail;
788     }
789
790     const struct pa_buffer_attr *pba = pa_stream_get_buffer_attr(s);
791     msg_Dbg(aout, "using buffer metrics: maxlength=%u, tlength=%u, "
792             "prebuf=%u, minreq=%u",
793             pba->maxlength, pba->tlength, pba->prebuf, pba->minreq);
794
795     var_Create(aout, "audio-device", VLC_VAR_INTEGER|VLC_VAR_HASCHOICE);
796     var_Change(aout, "audio-device", VLC_VAR_SETTEXT,
797                &(vlc_value_t){ .psz_string = (char *)_("Audio device") },
798                NULL);
799     var_AddCallback (aout, "audio-device", StreamMove, s);
800     op = pa_context_get_sink_info_list(ctx, sink_list_cb, aout);
801     /* We may need to wait for completion... once LibVLC supports this */
802     if (op != NULL)
803         pa_operation_unref(op);
804     stream_moved_cb(s, aout);
805     vlc_pa_unlock();
806
807     aout->format.i_format = format;
808     aout->pf_play = Play;
809     aout->pf_pause = Pause;
810     aout->pf_flush = Flush;
811     aout_VolumeHardInit (aout, VolumeSet);
812     return VLC_SUCCESS;
813
814 fail:
815     vlc_pa_unlock();
816     Close(obj);
817     return VLC_EGENERIC;
818 }
819
820 /**
821  * Removes a PulseAudio playback stream
822  */
823 static void Close (vlc_object_t *obj)
824 {
825     audio_output_t *aout = (audio_output_t *)obj;
826     aout_sys_t *sys = aout->sys;
827     pa_context *ctx = sys->context;
828     pa_stream *s = sys->stream;
829
830     if (s != NULL) {
831         /* The callback takes mainloop lock, so it CANNOT be held here! */
832         var_DelCallback (aout, "audio-device", StreamMove, s);
833         var_Destroy (aout, "audio-device");
834
835         pa_stream_disconnect(s);
836
837         /* Clear all callbacks */
838         pa_stream_set_state_callback(s, NULL, NULL);
839         pa_stream_set_latency_update_callback(s, NULL, aout);
840         pa_stream_set_moved_callback(s, NULL, aout);
841         pa_stream_set_overflow_callback(s, NULL, aout);
842         pa_stream_set_started_callback(s, NULL, aout);
843         pa_stream_set_suspended_callback(s, NULL, aout);
844         pa_stream_set_underflow_callback(s, NULL, aout);
845
846         pa_stream_unref(s);
847     }
848
849     vlc_pa_disconnect(obj, ctx);
850     free(sys);
851 }