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