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