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