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