]> git.sesse.net Git - vlc/blob - modules/audio_output/pulse.c
8784371a3bf62dc9c0ec46a0a5ebb8f8fe501daf
[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_event_cb(pa_stream *s, const char *name, pa_proplist *pl,
359                             void *userdata)
360 {
361     audio_output_t *aout = userdata;
362
363 #if PA_CHECK_VERSION(1,0,0)
364     /* FIXME: expose aout_Restart() directly */
365     if (!strcmp(name, PA_STREAM_EVENT_FORMAT_LOST)) {
366         vlc_value_t dummy = { .i_int = 0 };
367
368         msg_Dbg (aout, "format lost");
369         aout_ChannelsRestart (VLC_OBJECT(aout), "audio-device",
370                               dummy, dummy, NULL);
371     } else
372 #endif
373         msg_Warn (aout, "unhandled event %s", name);
374     (void) s;
375     (void) pl;
376 }
377
378 static void stream_moved_cb(pa_stream *s, void *userdata)
379 {
380     audio_output_t *aout = userdata;
381     aout_sys_t *sys = aout->sys;
382     pa_operation *op;
383     uint32_t idx = pa_stream_get_device_index(s);
384
385     msg_Dbg(aout, "connected to sink %"PRIu32": %s", idx,
386                   pa_stream_get_device_name(s));
387     op = pa_context_get_sink_info_by_index(sys->context, idx,
388                                            sink_info_cb, aout);
389     if (likely(op != NULL))
390         pa_operation_unref(op);
391
392     /* Update the variable if someone else moved our stream */
393     var_Change(aout, "audio-device", VLC_VAR_SETVALUE,
394                &(vlc_value_t){ .i_int = idx }, NULL);
395 }
396
397 static void stream_overflow_cb(pa_stream *s, void *userdata)
398 {
399     audio_output_t *aout = userdata;
400
401     msg_Err(aout, "overflow");
402     (void) s;
403 }
404
405 static void stream_started_cb(pa_stream *s, void *userdata)
406 {
407     audio_output_t *aout = userdata;
408
409     msg_Dbg(aout, "started");
410     (void) s;
411 }
412
413 static void stream_suspended_cb(pa_stream *s, void *userdata)
414 {
415     audio_output_t *aout = userdata;
416
417     msg_Dbg(aout, "suspended");
418     stream_reset_sync(s, aout);
419 }
420
421 static void stream_underflow_cb(pa_stream *s, void *userdata)
422 {
423     audio_output_t *aout = userdata;
424
425     msg_Warn(aout, "underflow");
426     stream_stop(s, aout);
427     stream_reset_sync(s, aout);
428 }
429
430 static int stream_wait(pa_stream *stream)
431 {
432     pa_stream_state_t state;
433
434     while ((state = pa_stream_get_state(stream)) != PA_STREAM_READY) {
435         if (state == PA_STREAM_FAILED || state == PA_STREAM_TERMINATED)
436             return -1;
437         vlc_pa_wait();
438     }
439     return 0;
440 }
441
442
443 /*** Sink input ***/
444 static void sink_input_info_cb(pa_context *ctx, const pa_sink_input_info *i,
445                                int eol, void *userdata)
446 {
447     audio_output_t *aout = userdata;
448     aout_sys_t *sys = aout->sys;
449     float volume;
450
451     if (eol)
452         return;
453     (void) ctx;
454
455     sys->cvolume = i->volume;
456     volume = pa_cvolume_max(&i->volume) / (float)PA_VOLUME_NORM;
457     aout_VolumeHardSet(aout, volume, i->mute);
458 }
459
460
461 /*** VLC audio output callbacks ***/
462
463 /* Memory free callback. The block_t address is in front of the data. */
464 static void data_free(void *data)
465 {
466     block_t **pp = data, *block;
467
468     memcpy(&block, pp - 1, sizeof (block));
469     block_Release(block);
470 }
471
472 static void *data_convert(block_t **pp)
473 {
474     block_t *block = *pp;
475     /* In most cases, there is enough head room, and this is really cheap: */
476     block = block_Realloc(block, sizeof (block), block->i_buffer);
477     *pp = block;
478     if (unlikely(block == NULL))
479         return NULL;
480
481     memcpy(block->p_buffer, &block, sizeof (block));
482     block->p_buffer += sizeof (block);
483     block->i_buffer -= sizeof (block);
484     return block->p_buffer;
485 }
486
487 /**
488  * Queue one audio frame to the playabck stream
489  */
490 static void Play(audio_output_t *aout, block_t *block)
491 {
492     aout_sys_t *sys = aout->sys;
493     pa_stream *s = sys->stream;
494
495     const void *ptr = data_convert(&block);
496     if (unlikely(ptr == NULL))
497         return;
498
499     size_t len = block->i_buffer;
500     mtime_t pts = block->i_pts + block->i_length;
501
502     /* Note: The core already holds the output FIFO lock at this point.
503      * Therefore we must not under any circumstances (try to) acquire the
504      * output FIFO lock while the PulseAudio threaded main loop lock is held
505      * (including from PulseAudio stream callbacks). Otherwise lock inversion
506      * will take place, and sooner or later a deadlock. */
507     vlc_pa_lock();
508
509     sys->pts = pts;
510     if (pa_stream_is_corked(s) > 0)
511         stream_resync(aout, s);
512
513 #if 0 /* Fault injector to test underrun recovery */
514     static volatile unsigned u = 0;
515     if ((++u % 1000) == 0) {
516         msg_Err(aout, "fault injection");
517         pa_operation_unref(pa_stream_flush(s, NULL, NULL));
518     }
519 #endif
520
521     if (pa_stream_write(s, ptr, len, data_free, 0, PA_SEEK_RELATIVE) < 0) {
522         vlc_pa_error(aout, "cannot write", sys->context);
523         block_Release(block);
524     }
525
526     vlc_pa_unlock();
527 }
528
529 /**
530  * Cork or uncork the playback stream
531  */
532 static void Pause(audio_output_t *aout, bool paused, mtime_t date)
533 {
534     aout_sys_t *sys = aout->sys;
535     pa_stream *s = sys->stream;
536
537     vlc_pa_lock();
538
539     if (paused) {
540         sys->paused = date;
541         stream_stop(s, aout);
542     } else {
543         assert (sys->paused != VLC_TS_INVALID);
544         date -= sys->paused;
545         msg_Dbg(aout, "resuming after %"PRId64" us", date);
546         sys->paused = VLC_TS_INVALID;
547         sys->pts += date;
548         stream_resync(aout, s);
549     }
550
551     vlc_pa_unlock();
552 }
553
554 /**
555  * Flush or drain the playback stream
556  */
557 static void Flush(audio_output_t *aout, bool wait)
558 {
559     aout_sys_t *sys = aout->sys;
560     pa_stream *s = sys->stream;
561     pa_operation *op;
562
563     vlc_pa_lock();
564
565     if (wait)
566         op = pa_stream_drain(s, NULL, NULL);
567         /* TODO: wait for drain completion*/
568     else
569         op = pa_stream_flush(s, NULL, NULL);
570     if (op != NULL)
571         pa_operation_unref(op);
572     vlc_pa_unlock();
573 }
574
575 static int VolumeSet(audio_output_t *aout, float vol, bool mute)
576 {
577     aout_sys_t *sys = aout->sys;
578     pa_operation *op;
579     uint32_t idx = pa_stream_get_index(sys->stream);
580
581     pa_cvolume cvolume = sys->cvolume;
582     pa_volume_t volume = sys->base_volume;
583
584     pa_cvolume_scale(&cvolume, PA_VOLUME_NORM); /* preserve balance */
585
586     /* VLC provides the software volume so convert directly to PulseAudio
587      * software volume, pa_volume_t. This is not a linear amplification factor
588      * so do not use PulseAudio linear amplification! */
589     vol *= PA_VOLUME_NORM;
590     if (unlikely(vol >= PA_VOLUME_MAX))
591         vol = PA_VOLUME_MAX;
592     volume = pa_sw_volume_multiply(volume, lround(vol));
593     pa_sw_cvolume_multiply_scalar(&cvolume, &cvolume, volume);
594
595     assert(pa_cvolume_valid(&cvolume));
596
597     vlc_pa_lock();
598     op = pa_context_set_sink_input_volume(sys->context, idx, &cvolume, NULL, NULL);
599     if (likely(op != NULL))
600         pa_operation_unref(op);
601     op = pa_context_set_sink_input_mute(sys->context, idx, mute, NULL, NULL);
602     if (likely(op != NULL))
603         pa_operation_unref(op);
604     vlc_pa_unlock();
605
606     return 0;
607 }
608
609 static int StreamMove(vlc_object_t *obj, const char *varname, vlc_value_t old,
610                       vlc_value_t val, void *userdata)
611 {
612     audio_output_t *aout = (audio_output_t *)obj;
613     aout_sys_t *sys = aout->sys;
614     pa_stream *s = userdata;
615     pa_operation *op;
616     uint32_t idx = pa_stream_get_index(s);
617     uint32_t sink_idx = val.i_int;
618
619     (void) varname; (void) old;
620
621     vlc_pa_lock();
622     op = pa_context_move_sink_input_by_index(sys->context, idx, sink_idx,
623                                              NULL, NULL);
624     if (likely(op != NULL)) {
625         pa_operation_unref(op);
626         msg_Dbg(aout, "moving to sink %"PRIu32, sink_idx);
627     } else
628         vlc_pa_error(obj, "cannot move sink", sys->context);
629     vlc_pa_unlock();
630
631     return (op != NULL) ? VLC_SUCCESS : VLC_EGENERIC;
632 }
633
634
635 /**
636  * Create a PulseAudio playback stream, a.k.a. a sink input.
637  */
638 static int Open(vlc_object_t *obj)
639 {
640 #if !PA_CHECK_VERSION(0,9,22)
641     if (!vlc_xlib_init(obj))
642         return VLC_EGENERIC;
643 #endif
644
645     audio_output_t *aout = (audio_output_t *)obj;
646     pa_operation *op;
647
648     /* Sample format specification */
649     struct pa_sample_spec ss;
650     vlc_fourcc_t format = aout->format.i_format;
651
652     switch(format)
653     {
654         case VLC_CODEC_F64B:
655             format = VLC_CODEC_F32B;
656         case VLC_CODEC_F32B:
657             ss.format = PA_SAMPLE_FLOAT32BE;
658             break;
659         case VLC_CODEC_F64L:
660             format = VLC_CODEC_F32L;
661         case VLC_CODEC_F32L:
662             ss.format = PA_SAMPLE_FLOAT32LE;
663             break;
664         case VLC_CODEC_FI32:
665             format = VLC_CODEC_FL32;
666             ss.format = PA_SAMPLE_FLOAT32NE;
667             break;
668         case VLC_CODEC_S32B:
669             ss.format = PA_SAMPLE_S32BE;
670             break;
671         case VLC_CODEC_S32L:
672             ss.format = PA_SAMPLE_S32LE;
673             break;
674         case VLC_CODEC_S24B:
675             ss.format = PA_SAMPLE_S24BE;
676             break;
677         case VLC_CODEC_S24L:
678             ss.format = PA_SAMPLE_S24LE;
679             break;
680         case VLC_CODEC_S16B:
681             ss.format = PA_SAMPLE_S16BE;
682             break;
683         case VLC_CODEC_S16L:
684             ss.format = PA_SAMPLE_S16LE;
685             break;
686         case VLC_CODEC_S8:
687             format = VLC_CODEC_U8;
688         case VLC_CODEC_U8:
689             ss.format = PA_SAMPLE_U8;
690             break;
691         default:
692             if (HAVE_FPU)
693             {
694                 format = VLC_CODEC_FL32;
695                 ss.format = PA_SAMPLE_FLOAT32NE;
696             }
697             else
698             {
699                 format = VLC_CODEC_S16N;
700                 ss.format = PA_SAMPLE_S16NE;
701             }
702             break;
703     }
704
705     ss.rate = aout->format.i_rate;
706     ss.channels = aout_FormatNbChannels(&aout->format);
707     if (!pa_sample_spec_valid(&ss)) {
708         msg_Err(aout, "unsupported sample specification");
709         return VLC_EGENERIC;
710     }
711
712     /* Channel mapping (order defined in vlc_aout.h) */
713     struct pa_channel_map map;
714     map.channels = 0;
715
716     if (aout->format.i_physical_channels & AOUT_CHAN_LEFT)
717         map.map[map.channels++] = PA_CHANNEL_POSITION_FRONT_LEFT;
718     if (aout->format.i_physical_channels & AOUT_CHAN_RIGHT)
719         map.map[map.channels++] = PA_CHANNEL_POSITION_FRONT_RIGHT;
720     if (aout->format.i_physical_channels & AOUT_CHAN_MIDDLELEFT)
721         map.map[map.channels++] = PA_CHANNEL_POSITION_SIDE_LEFT;
722     if (aout->format.i_physical_channels & AOUT_CHAN_MIDDLERIGHT)
723         map.map[map.channels++] = PA_CHANNEL_POSITION_SIDE_RIGHT;
724     if (aout->format.i_physical_channels & AOUT_CHAN_REARLEFT)
725         map.map[map.channels++] = PA_CHANNEL_POSITION_REAR_LEFT;
726     if (aout->format.i_physical_channels & AOUT_CHAN_REARRIGHT)
727         map.map[map.channels++] = PA_CHANNEL_POSITION_REAR_RIGHT;
728     if (aout->format.i_physical_channels & AOUT_CHAN_REARCENTER)
729         map.map[map.channels++] = PA_CHANNEL_POSITION_REAR_CENTER;
730     if (aout->format.i_physical_channels & AOUT_CHAN_CENTER)
731     {
732         if (ss.channels == 1)
733             map.map[map.channels++] = PA_CHANNEL_POSITION_MONO;
734         else
735             map.map[map.channels++] = PA_CHANNEL_POSITION_FRONT_CENTER;
736     }
737     if (aout->format.i_physical_channels & AOUT_CHAN_LFE)
738         map.map[map.channels++] = PA_CHANNEL_POSITION_LFE;
739
740     for (unsigned i = 0; map.channels < ss.channels; i++) {
741         map.map[map.channels++] = PA_CHANNEL_POSITION_AUX0 + i;
742         msg_Warn(aout, "mapping channel %"PRIu8" to AUX%u", map.channels, i);
743     }
744
745     if (!pa_channel_map_valid(&map)) {
746         msg_Err(aout, "unsupported channel map");
747         return VLC_EGENERIC;
748     } else {
749         const char *name = pa_channel_map_to_name(&map);
750         msg_Dbg(aout, "using %s channel map", (name != NULL) ? name : "?");
751     }
752
753     /* Stream parameters */
754     const pa_stream_flags_t flags = PA_STREAM_START_CORKED
755                                   //| PA_STREAM_INTERPOLATE_TIMING
756                                   | PA_STREAM_AUTO_TIMING_UPDATE
757                                   | PA_STREAM_VARIABLE_RATE;
758
759     struct pa_buffer_attr attr;
760     attr.maxlength = -1;
761     /* PulseAudio assumes that tlength bytes are available in the buffer. Thus
762      * we need to be conservative and set the minimum value that the VLC
763      * audio decoder thread warrants. Otherwise, PulseAudio buffers will
764      * underrun on hardware with large buffers. VLC keeps at least
765      * AOUT_MIN_PREPARE and at most AOUT_MAX_PREPARE worth of audio buffers.
766      * TODO? tlength could be adaptively increased to reduce wakeups. */
767     attr.tlength = pa_usec_to_bytes(AOUT_MIN_PREPARE_TIME, &ss);
768     attr.prebuf = 0; /* trigger manually */
769     attr.minreq = -1;
770     attr.fragsize = 0; /* not used for output */
771
772     /* Allocate structures */
773     aout_sys_t *sys = malloc(sizeof(*sys));
774     if (unlikely(sys == NULL))
775         return VLC_ENOMEM;
776
777     pa_context *ctx = vlc_pa_connect (obj);
778     if (ctx == NULL)
779     {
780         free (sys);
781         return VLC_EGENERIC;
782     }
783
784     aout->sys = sys;
785     sys->stream = NULL;
786     sys->context = ctx;
787     sys->trigger = NULL;
788     sys->paused = VLC_TS_INVALID;
789     sys->pts = VLC_TS_INVALID;
790     sys->desync = 0;
791     sys->rate = ss.rate;
792
793     /* Context events */
794     const pa_subscription_mask_t mask = PA_SUBSCRIPTION_MASK_SINK_INPUT;
795
796     pa_context_set_subscribe_callback(ctx, context_cb, aout);
797     op = pa_context_subscribe(ctx, mask, NULL, NULL);
798     if (likely(op != NULL))
799        pa_operation_unref(op);
800
801     /* Channel volume */
802     sys->base_volume = PA_VOLUME_NORM;
803     pa_cvolume_set(&sys->cvolume, ss.channels, PA_VOLUME_NORM);
804
805     vlc_pa_lock();
806     /* Create a playback stream */
807     pa_stream *s = pa_stream_new(ctx, "audio stream", &ss, &map);
808     if (s == NULL) {
809         vlc_pa_error(obj, "stream creation failure", ctx);
810         goto fail;
811     }
812     sys->stream = s;
813     pa_stream_set_state_callback(s, stream_state_cb, NULL);
814     pa_stream_set_event_callback(s, stream_event_cb, aout);
815     pa_stream_set_latency_update_callback(s, stream_latency_cb, aout);
816     pa_stream_set_moved_callback(s, stream_moved_cb, aout);
817     pa_stream_set_overflow_callback(s, stream_overflow_cb, aout);
818     pa_stream_set_started_callback(s, stream_started_cb, aout);
819     pa_stream_set_suspended_callback(s, stream_suspended_cb, aout);
820     pa_stream_set_underflow_callback(s, stream_underflow_cb, aout);
821
822     if (pa_stream_connect_playback(s, NULL, &attr, flags, NULL, NULL) < 0
823      || stream_wait(s)) {
824         vlc_pa_error(obj, "stream connection failure", ctx);
825         goto fail;
826     }
827
828     const struct pa_buffer_attr *pba = pa_stream_get_buffer_attr(s);
829     msg_Dbg(aout, "using buffer metrics: maxlength=%u, tlength=%u, "
830             "prebuf=%u, minreq=%u",
831             pba->maxlength, pba->tlength, pba->prebuf, pba->minreq);
832
833     var_Create(aout, "audio-device", VLC_VAR_INTEGER|VLC_VAR_HASCHOICE);
834     var_Change(aout, "audio-device", VLC_VAR_SETTEXT,
835                &(vlc_value_t){ .psz_string = (char *)_("Audio device") },
836                NULL);
837     var_AddCallback (aout, "audio-device", StreamMove, s);
838     op = pa_context_get_sink_info_list(ctx, sink_list_cb, aout);
839     /* We may need to wait for completion... once LibVLC supports this */
840     if (op != NULL)
841         pa_operation_unref(op);
842     stream_moved_cb(s, aout);
843     vlc_pa_unlock();
844
845     aout->format.i_format = format;
846     aout->pf_play = Play;
847     aout->pf_pause = Pause;
848     aout->pf_flush = Flush;
849     aout_VolumeHardInit (aout, VolumeSet);
850     return VLC_SUCCESS;
851
852 fail:
853     vlc_pa_unlock();
854     Close(obj);
855     return VLC_EGENERIC;
856 }
857
858 /**
859  * Removes a PulseAudio playback stream
860  */
861 static void Close (vlc_object_t *obj)
862 {
863     audio_output_t *aout = (audio_output_t *)obj;
864     aout_sys_t *sys = aout->sys;
865     pa_context *ctx = sys->context;
866     pa_stream *s = sys->stream;
867
868     if (s != NULL) {
869         /* The callback takes mainloop lock, so it CANNOT be held here! */
870         var_DelCallback (aout, "audio-device", StreamMove, s);
871         var_Destroy (aout, "audio-device");
872
873         vlc_pa_lock ();
874         if (unlikely(sys->trigger != NULL))
875             vlc_pa_rttime_free(sys->trigger);
876         pa_stream_disconnect(s);
877
878         /* Clear all callbacks */
879         pa_stream_set_state_callback(s, NULL, NULL);
880         pa_stream_set_event_callback(s, NULL, NULL);
881         pa_stream_set_latency_update_callback(s, NULL, NULL);
882         pa_stream_set_moved_callback(s, NULL, NULL);
883         pa_stream_set_overflow_callback(s, NULL, NULL);
884         pa_stream_set_started_callback(s, NULL, NULL);
885         pa_stream_set_suspended_callback(s, NULL, NULL);
886         pa_stream_set_underflow_callback(s, NULL, NULL);
887
888         pa_stream_unref(s);
889         vlc_pa_unlock ();
890     }
891
892     vlc_pa_disconnect(obj, ctx);
893     free(sys);
894 }