]> git.sesse.net Git - vlc/blob - modules/audio_output/pulse.c
8a71c019fdb8de86a1e8edcc97dca967a0a03435
[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 pts; /**< Play time of buffer write offset */
70     mtime_t desync; /**< Measured desynchronization */
71     unsigned rate; /**< Current stream sample rate */
72 };
73
74 /*** Sink ***/
75 static void sink_list_cb(pa_context *c, const pa_sink_info *i, int eol,
76                          void *userdata)
77 {
78     aout_instance_t *aout = userdata;
79     vlc_value_t val, text;
80
81     if (eol)
82         return;
83     (void) c;
84
85     msg_Dbg(aout, "listing sink %s (%"PRIu32"): %s", i->name, i->index,
86             i->description);
87     val.i_int = i->index;
88     text.psz_string = (char *)i->description;
89     var_Change(aout, "audio-device", VLC_VAR_ADDCHOICE, &val, &text);
90 }
91
92 static void sink_info_cb(pa_context *c, const pa_sink_info *i, int eol,
93                          void *userdata)
94 {
95     aout_instance_t *aout = userdata;
96     aout_sys_t *sys = aout->sys;
97
98     if (eol)
99         return;
100     (void) c;
101
102     /* PulseAudio flat volume NORM / 100% / 0dB corresponds to no software
103      * amplification and maximum hardware amplification.
104      * VLC maps DEFAULT / 100% to no gain at all (software/hardware).
105      * Thus we need to use the sink base_volume as a multiplier,
106      * if and only if flat volume is active for our current sink. */
107     if (i->flags & PA_SINK_FLAT_VOLUME)
108         sys->base_volume = i->base_volume;
109     else
110         sys->base_volume = PA_VOLUME_NORM;
111     msg_Dbg(aout, "base volume: %f", pa_sw_volume_to_linear(sys->base_volume));
112 }
113
114 /*** Stream helpers ***/
115 static void stream_reset_sync(pa_stream *s, aout_instance_t *aout)
116 {
117     aout_sys_t *sys = aout->sys;
118     const unsigned rate = aout->format.i_rate;
119
120     sys->pts = VLC_TS_INVALID;
121     sys->desync = 0;
122     pa_operation *op = pa_stream_update_sample_rate(s, rate, NULL, NULL);
123     if (unlikely(op == NULL))
124         return;
125     pa_operation_unref(op);
126     sys->rate = rate;
127 }
128
129 static void stream_state_cb(pa_stream *s, void *userdata)
130 {
131     switch (pa_stream_get_state(s)) {
132         case PA_STREAM_READY:
133         case PA_STREAM_FAILED:
134         case PA_STREAM_TERMINATED:
135             vlc_pa_signal(0);
136         default:
137             break;
138     }
139     (void) userdata;
140 }
141
142 /* Latency management and lip synchronization */
143 static void stream_latency_cb(pa_stream *s, void *userdata)
144 {
145     aout_instance_t *aout = userdata;
146     aout_sys_t *sys = aout->sys;
147     mtime_t delta, change;
148
149     if (sys->pts == VLC_TS_INVALID)
150     {
151         msg_Dbg(aout, "missing latency from input");
152         return;
153     }
154
155     /* Compute lip desynchronization */
156     {
157         pa_usec_t latency;
158         int negative;
159
160         if (pa_stream_get_latency(s, &latency, &negative)) {
161             vlc_pa_error(aout, "missing latency", sys->context);
162             return;
163         }
164         delta = sys->pts - mdate();
165         if (unlikely(negative))
166            delta += latency;
167         else
168            delta -= latency;
169     }
170
171     change = delta - sys->desync;
172     sys->desync = delta;
173     //msg_Dbg(aout, "desync: %+"PRId64" us (variation: %+"PRId64" us)",
174     //        delta, change);
175
176     if (delta < -AOUT_MAX_PTS_DELAY)
177         msg_Warn(aout, "too late by %"PRId64" us", -delta);
178     else if (delta > +AOUT_MAX_PTS_ADVANCE)
179         msg_Warn(aout, "too early by %"PRId64" us", delta);
180
181     /* Compute playback sample rate */
182     const unsigned inrate = aout->format.i_rate;
183
184 #define ADJUST_FACTOR 4
185 #define ADJUST_MAX    1000 /* Hz (max rate variation per call) */
186     /* This is empirical. Feel free to define something smarter. */
187     int adj = sys->rate * (delta + change) / (CLOCK_FREQ * ADJUST_FACTOR);
188
189     /* This avoids too fast rate variation. They sound ugly as hell and they
190      * make the algorithm unstable (e.g. oscillation around inrate). */
191     if (adj > +ADJUST_MAX)
192         adj = +ADJUST_MAX;
193     if (adj < -ADJUST_MAX)
194         adj = -ADJUST_MAX;
195
196     unsigned outrate = sys->rate - adj;
197     /* Favor native rate to avoid resampling (FIXME: really a good idea?) */
198     if (abs(outrate - inrate) < (inrate >> 10))
199         outrate = inrate;
200
201     /* This keeps the effective rate within specified range
202      * (+/-AOUT_MAX_RESAMPLING% - see <vlc_aout.h>) of the nominal rate. */
203     const int limit = inrate * AOUT_MAX_RESAMPLING / 100;
204     if (outrate > inrate + limit)
205         outrate = inrate + limit;
206     if (outrate < inrate - limit)
207         outrate = inrate - limit;
208
209     /* Apply adjusted sample rate */
210     if (outrate == sys->rate)
211         return;
212     pa_operation *op = pa_stream_update_sample_rate(s, outrate, NULL, NULL);
213     if (unlikely(op == NULL)) {
214         vlc_pa_error(aout, "cannot change sample rate", sys->context);
215         return;
216     }
217     pa_operation_unref(op);
218     msg_Dbg(aout, "changed sample rate to %u Hz",outrate);
219     sys->rate = outrate;
220 }
221
222 static void stream_moved_cb(pa_stream *s, void *userdata)
223 {
224     aout_instance_t *aout = userdata;
225     aout_sys_t *sys = aout->sys;
226     pa_operation *op;
227     uint32_t idx = pa_stream_get_device_index(s);
228
229     msg_Dbg(aout, "connected to sink %"PRIu32": %s", idx,
230                   pa_stream_get_device_name(s));
231     op = pa_context_get_sink_info_by_index(sys->context, idx,
232                                            sink_info_cb, aout);
233     if (likely(op != NULL))
234         pa_operation_unref(op);
235
236     /* Update the variable if someone else moved our stream */
237     var_Change(aout, "audio-device", VLC_VAR_SETVALUE,
238                &(vlc_value_t){ .i_int = idx }, NULL);
239 }
240
241 static void stream_overflow_cb(pa_stream *s, void *userdata)
242 {
243     aout_instance_t *aout = userdata;
244
245     msg_Err(aout, "overflow");
246     (void) s;
247 }
248
249 static void stream_started_cb(pa_stream *s, void *userdata)
250 {
251     aout_instance_t *aout = userdata;
252
253     msg_Dbg(aout, "started");
254     (void) s;
255 }
256
257 static void stream_suspended_cb(pa_stream *s, void *userdata)
258 {
259     aout_instance_t *aout = userdata;
260
261     msg_Dbg(aout, "suspended");
262     stream_reset_sync(s, aout);
263 }
264
265 static void stream_underflow_cb(pa_stream *s, void *userdata)
266 {
267     aout_instance_t *aout = userdata;
268     pa_operation *op;
269
270     msg_Warn(aout, "underflow");
271     op = pa_stream_cork(s, 1, NULL, NULL);
272     if (op != NULL)
273         pa_operation_unref(op);
274     stream_reset_sync(s, aout);
275 }
276
277 static int stream_wait(pa_stream *stream)
278 {
279     pa_stream_state_t state;
280
281     while ((state = pa_stream_get_state(stream)) != PA_STREAM_READY) {
282         if (state == PA_STREAM_FAILED || state == PA_STREAM_TERMINATED)
283             return -1;
284         vlc_pa_wait();
285     }
286     return 0;
287 }
288
289 #ifdef LIBPULSE_GETS_A_CLUE
290 static void stream_success_cb(pa_stream *s, int success, void *userdata)
291 {
292     vlc_pa_signal(0);
293     (void) s; (void) success; (void) userdata;
294 }
295 #else
296 # define stream_success_cb NULL
297 #endif
298
299 /* Memory free callback. The block_t address is in front of the data. */
300 static void data_free(void *data)
301 {
302     block_t **pp = data, *block;
303
304     memcpy(&block, pp - 1, sizeof (block));
305     block_Release(block);
306 }
307
308 static void *data_convert(block_t **pp)
309 {
310     block_t *block = *pp;
311     /* In most cases, there is enough head room, and this is really cheap: */
312     block = block_Realloc(block, sizeof (block), block->i_buffer);
313     *pp = block;
314     if (unlikely(block == NULL))
315         return NULL;
316
317     memcpy(block->p_buffer, &block, sizeof (block));
318     block->p_buffer += sizeof (block);
319     block->i_buffer -= sizeof (block);
320     return block->p_buffer;
321 }
322
323 /**
324  * Queue one audio frame to the playabck stream
325  */
326 static void Play(aout_instance_t *aout)
327 {
328     aout_sys_t *sys = aout->sys;
329     pa_stream *s = sys->stream;
330
331     /* This function is called exactly once per block in the output FIFO. */
332     block_t *block = aout_FifoPop(&aout->fifo);
333     assert (block != NULL);
334
335     const void *ptr = data_convert(&block);
336     if (unlikely(ptr == NULL))
337         return;
338
339     size_t len = block->i_buffer;
340     mtime_t pts = block->i_pts + block->i_length;
341
342     /* Note: The core already holds the output FIFO lock at this point.
343      * Therefore we must not under any circumstances (try to) acquire the
344      * output FIFO lock while the PulseAudio threaded main loop lock is held
345      * (including from PulseAudio stream callbacks). Otherwise lock inversion
346      * will take place, and sooner or later a deadlock. */
347     vlc_pa_lock();
348
349     if (pa_stream_is_corked(s) > 0) {
350         /* Start or resume the stream. Zeroes are prepended to sync.
351          * This does not really work because PulseAudio latency measurement is
352          * garbage at start. */
353         pa_operation *op;
354         pa_usec_t latency;
355         int negative;
356
357         if (pa_stream_get_latency(s, &latency, &negative) == 0)
358             msg_Dbg(aout, "starting with %c%"PRIu64" us latency",
359                     negative ? '-' : '+', latency);
360         else
361             latency = negative = 0;
362
363         mtime_t advance = block->i_pts - mdate();
364         if (negative)
365             advance += latency;
366         else
367             advance -= latency;
368
369         if (advance > 0) {
370             size_t nb = (advance * aout->format.i_rate) / CLOCK_FREQ;
371             size_t size = aout->format.i_bytes_per_frame;
372             float *zeroes = calloc (nb, size);
373
374             msg_Dbg(aout, "prepending %zu zeroes", nb);
375 #if 0 /* Fault injector: add delay */
376             pa_stream_write(s, zeroes, nb * size, NULL, 0, PA_SEEK_RELATIVE);
377             pa_stream_write(s, zeroes, nb * size, NULL, 0, PA_SEEK_RELATIVE);
378 #endif
379             if (likely(zeroes != NULL))
380                 if (pa_stream_write(s, zeroes, nb * size, free, 0,
381                                     PA_SEEK_RELATIVE) < 0)
382                     free(zeroes);
383         }
384
385         op = pa_stream_cork(s, 0, NULL, NULL);
386         if (op != NULL)
387             pa_operation_unref(op);
388         op = pa_stream_trigger(s, NULL, NULL);
389         if (op != NULL)
390             pa_operation_unref(op);
391         msg_Dbg(aout, "uncorking");
392     }
393
394 #if 0 /* Fault injector to test underrun recovery */
395     static volatile unsigned u = 0;
396     if ((++u % 1000) == 0) {
397         msg_Err(aout, "fault injection");
398         pa_operation_unref(pa_stream_flush(s, NULL, NULL));
399     }
400 #endif
401
402     if (pa_stream_write(s, ptr, len, data_free, 0, PA_SEEK_RELATIVE) < 0) {
403         vlc_pa_error(aout, "cannot write", sys->context);
404         block_Release(block);
405     }
406     sys->pts = pts;
407
408     vlc_pa_unlock();
409 }
410
411 /**
412  * Cork or uncork the playback stream
413  */
414 static void Pause(aout_instance_t *aout, bool b_paused, mtime_t i_date)
415 {
416     aout_sys_t *sys = aout->sys;
417     pa_stream *s = sys->stream;
418
419     if (!b_paused)
420         return; /* nothing to do - yet */
421
422     vlc_pa_lock();
423
424     pa_operation *op = pa_stream_cork(s, 1, NULL, NULL);
425     if (op != NULL)
426         pa_operation_unref(op);
427     stream_reset_sync(s, aout);
428
429     vlc_pa_unlock();
430     (void) i_date;
431 }
432
433 static int VolumeSet(aout_instance_t *aout, float vol, bool mute)
434 {
435     aout_sys_t *sys = aout->sys;
436     pa_operation *op;
437
438     uint32_t idx = pa_stream_get_index(sys->stream);
439     pa_volume_t volume = pa_sw_volume_from_linear(vol);
440     pa_cvolume cvolume;
441
442     /* TODO: do not ruin the channel balance (if set outside VLC) */
443     /* TODO: notify UI about volume changes by other PulseAudio clients */
444     pa_cvolume_set(&sys->cvolume, sys->cvolume.channels, volume);
445     pa_sw_cvolume_multiply_scalar(&cvolume, &sys->cvolume, sys->base_volume);
446     assert(pa_cvolume_valid(&cvolume));
447
448     vlc_pa_lock();
449     op = pa_context_set_sink_input_volume(sys->context, idx, &cvolume, NULL, NULL);
450     if (likely(op != NULL))
451         pa_operation_unref(op);
452     op = pa_context_set_sink_input_mute(sys->context, idx, mute, NULL, NULL);
453     if (likely(op != NULL))
454         pa_operation_unref(op);
455     vlc_pa_unlock();
456
457     return 0;
458 }
459
460 static int StreamMove(vlc_object_t *obj, const char *varname, vlc_value_t old,
461                       vlc_value_t val, void *userdata)
462 {
463     aout_instance_t *aout = (aout_instance_t *)obj;
464     aout_sys_t *sys = aout->sys;
465     pa_stream *s = userdata;
466     pa_operation *op;
467     uint32_t idx = pa_stream_get_index(s);
468     uint32_t sink_idx = val.i_int;
469
470     (void) varname; (void) old;
471
472     vlc_pa_lock();
473     op = pa_context_move_sink_input_by_index(sys->context, idx, sink_idx,
474                                              NULL, NULL);
475     if (likely(op != NULL)) {
476         pa_operation_unref(op);
477         msg_Dbg(aout, "moving to sink %"PRIu32, sink_idx);
478     } else
479         vlc_pa_error(obj, "cannot move sink", sys->context);
480     vlc_pa_unlock();
481
482     return (op != NULL) ? VLC_SUCCESS : VLC_EGENERIC;
483 }
484
485
486 /**
487  * Create a PulseAudio playback stream, a.k.a. a sink input.
488  */
489 static int Open(vlc_object_t *obj)
490 {
491     aout_instance_t *aout = (aout_instance_t *)obj;
492     pa_operation *op;
493
494     /* Sample format specification */
495     struct pa_sample_spec ss;
496
497     switch(aout->format.i_format)
498     {
499         case VLC_CODEC_F64B:
500             aout->format.i_format = VLC_CODEC_F32B;
501         case VLC_CODEC_F32B:
502             ss.format = PA_SAMPLE_FLOAT32BE;
503             break;
504         case VLC_CODEC_F64L:
505             aout->format.i_format = VLC_CODEC_F32L;
506         case VLC_CODEC_F32L:
507             ss.format = PA_SAMPLE_FLOAT32LE;
508             break;
509         case VLC_CODEC_FI32:
510             aout->format.i_format = VLC_CODEC_FL32;
511             ss.format = PA_SAMPLE_FLOAT32NE;
512             break;
513         case VLC_CODEC_S32B:
514             ss.format = PA_SAMPLE_S32BE;
515             break;
516         case VLC_CODEC_S32L:
517             ss.format = PA_SAMPLE_S32LE;
518             break;
519         case VLC_CODEC_S24B:
520             ss.format = PA_SAMPLE_S24BE;
521             break;
522         case VLC_CODEC_S24L:
523             ss.format = PA_SAMPLE_S24LE;
524             break;
525         case VLC_CODEC_S16B:
526             ss.format = PA_SAMPLE_S16BE;
527             break;
528         case VLC_CODEC_S16L:
529             ss.format = PA_SAMPLE_S16LE;
530             break;
531         case VLC_CODEC_S8:
532             aout->format.i_format = VLC_CODEC_U8;
533         case VLC_CODEC_U8:
534             ss.format = PA_SAMPLE_U8;
535             break;
536         default:
537             if (HAVE_FPU)
538             {
539                 aout->format.i_format = VLC_CODEC_FL32;
540                 ss.format = PA_SAMPLE_FLOAT32NE;
541             }
542             else
543             {
544                 aout->format.i_format = VLC_CODEC_S16N;
545                 ss.format = PA_SAMPLE_S16NE;
546             }
547             break;
548     }
549
550     ss.rate = aout->format.i_rate;
551     ss.channels = aout_FormatNbChannels(&aout->format);
552     if (!pa_sample_spec_valid(&ss)) {
553         msg_Err(aout, "unsupported sample specification");
554         return VLC_EGENERIC;
555     }
556
557     /* Channel mapping (order defined in vlc_aout.h) */
558     struct pa_channel_map map;
559     map.channels = 0;
560
561     if (aout->format.i_physical_channels & AOUT_CHAN_LEFT)
562         map.map[map.channels++] = PA_CHANNEL_POSITION_FRONT_LEFT;
563     if (aout->format.i_physical_channels & AOUT_CHAN_RIGHT)
564         map.map[map.channels++] = PA_CHANNEL_POSITION_FRONT_RIGHT;
565     if (aout->format.i_physical_channels & AOUT_CHAN_MIDDLELEFT)
566         map.map[map.channels++] = PA_CHANNEL_POSITION_SIDE_LEFT;
567     if (aout->format.i_physical_channels & AOUT_CHAN_MIDDLERIGHT)
568         map.map[map.channels++] = PA_CHANNEL_POSITION_SIDE_RIGHT;
569     if (aout->format.i_physical_channels & AOUT_CHAN_REARLEFT)
570         map.map[map.channels++] = PA_CHANNEL_POSITION_REAR_LEFT;
571     if (aout->format.i_physical_channels & AOUT_CHAN_REARRIGHT)
572         map.map[map.channels++] = PA_CHANNEL_POSITION_REAR_RIGHT;
573     if (aout->format.i_physical_channels & AOUT_CHAN_REARCENTER)
574         map.map[map.channels++] = PA_CHANNEL_POSITION_REAR_CENTER;
575     if (aout->format.i_physical_channels & AOUT_CHAN_CENTER)
576     {
577         if (ss.channels == 1)
578             map.map[map.channels++] = PA_CHANNEL_POSITION_MONO;
579         else
580             map.map[map.channels++] = PA_CHANNEL_POSITION_FRONT_CENTER;
581     }
582     if (aout->format.i_physical_channels & AOUT_CHAN_LFE)
583         map.map[map.channels++] = PA_CHANNEL_POSITION_LFE;
584
585     for (unsigned i = 0; map.channels < ss.channels; i++) {
586         map.map[map.channels++] = PA_CHANNEL_POSITION_AUX0 + i;
587         msg_Warn(aout, "mapping channel %"PRIu8" to AUX%u", map.channels, i);
588     }
589
590     if (!pa_channel_map_valid(&map)) {
591         msg_Err(aout, "unsupported channel map");
592         return VLC_EGENERIC;
593     } else {
594         const char *name = pa_channel_map_to_name(&map);
595         msg_Dbg(aout, "using %s channel map", (name != NULL) ? name : "?");
596     }
597
598     /* Stream parameters */
599     const pa_stream_flags_t flags = PA_STREAM_START_CORKED
600                                   //| PA_STREAM_INTERPOLATE_TIMING
601                                   | PA_STREAM_AUTO_TIMING_UPDATE
602                                   | PA_STREAM_VARIABLE_RATE;
603
604     struct pa_buffer_attr attr;
605     attr.maxlength = -1;
606     /* PulseAudio assumes that tlength bytes are available in the buffer. Thus
607      * we need to be conservative and set the minimum value that the VLC
608      * audio decoder thread warrants. Otherwise, PulseAudio buffers will
609      * underrun on hardware with large buffers. VLC keeps at least
610      * AOUT_MIN_PREPARE and at most AOUT_MAX_PREPARE worth of audio buffers.
611      * TODO? tlength could be adaptively increased to reduce wakeups. */
612     attr.tlength = pa_usec_to_bytes(AOUT_MIN_PREPARE_TIME, &ss);
613     attr.prebuf = 0; /* trigger manually */
614     attr.minreq = -1;
615     attr.fragsize = 0; /* not used for output */
616
617     /* Allocate structures */
618     aout_sys_t *sys = malloc(sizeof(*sys));
619     if (unlikely(sys == NULL))
620         return VLC_ENOMEM;
621
622     pa_context *ctx = vlc_pa_connect (obj);
623     if (ctx == NULL)
624     {
625         free (sys);
626         return VLC_EGENERIC;
627     }
628
629     aout->sys = sys;
630     sys->stream = NULL;
631     sys->context = ctx;
632     sys->pts = VLC_TS_INVALID;
633     sys->desync = 0;
634     sys->rate = ss.rate;
635
636     /* Channel volume */
637     sys->base_volume = PA_VOLUME_NORM;
638     pa_cvolume_set(&sys->cvolume, ss.channels, PA_VOLUME_NORM);
639
640     vlc_pa_lock();
641     /* Create a playback stream */
642     pa_stream *s = pa_stream_new(ctx, "audio stream", &ss, &map);
643     if (s == NULL) {
644         vlc_pa_error(obj, "stream creation failure", ctx);
645         goto fail;
646     }
647     sys->stream = s;
648     pa_stream_set_state_callback(s, stream_state_cb, NULL);
649     pa_stream_set_latency_update_callback(s, stream_latency_cb, aout);
650     pa_stream_set_moved_callback(s, stream_moved_cb, aout);
651     pa_stream_set_overflow_callback(s, stream_overflow_cb, aout);
652     pa_stream_set_started_callback(s, stream_started_cb, aout);
653     pa_stream_set_suspended_callback(s, stream_suspended_cb, aout);
654     pa_stream_set_underflow_callback(s, stream_underflow_cb, aout);
655
656     if (pa_stream_connect_playback(s, NULL, &attr, flags, NULL, NULL) < 0
657      || stream_wait(s)) {
658         vlc_pa_error(obj, "stream connection failure", ctx);
659         goto fail;
660     }
661
662     const struct pa_buffer_attr *pba = pa_stream_get_buffer_attr(s);
663     msg_Dbg(aout, "using buffer metrics: maxlength=%u, tlength=%u, "
664             "prebuf=%u, minreq=%u",
665             pba->maxlength, pba->tlength, pba->prebuf, pba->minreq);
666
667     aout->i_nb_samples = pba->minreq / pa_frame_size(&ss);
668
669     var_Create(aout, "audio-device", VLC_VAR_INTEGER|VLC_VAR_HASCHOICE);
670     var_Change(aout, "audio-device", VLC_VAR_SETTEXT,
671                &(vlc_value_t){ .psz_string = (char *)_("Audio device") },
672                NULL);
673     var_AddCallback (aout, "audio-device", StreamMove, s);
674     op = pa_context_get_sink_info_list(ctx, sink_list_cb, aout);
675     /* We may need to wait for completion... once LibVLC supports this */
676     if (op != NULL)
677         pa_operation_unref(op);
678     stream_moved_cb(s, aout);
679     vlc_pa_unlock();
680
681     aout->pf_play = Play;
682     aout->pf_pause = Pause;
683     aout->pf_volume_set = VolumeSet;
684     return VLC_SUCCESS;
685
686 fail:
687     vlc_pa_unlock();
688     Close(obj);
689     return VLC_EGENERIC;
690 }
691
692 /**
693  * Removes a PulseAudio playback stream
694  */
695 static void Close (vlc_object_t *obj)
696 {
697     aout_instance_t *aout = (aout_instance_t *)obj;
698     aout_sys_t *sys = aout->sys;
699     pa_context *ctx = sys->context;
700     pa_stream *s = sys->stream;
701
702     if (s != NULL) {
703         /* The callback takes mainloop lock, so it CANNOT be held here! */
704         var_DelCallback (aout, "audio-device", StreamMove, s);
705         var_Destroy (aout, "audio-device");
706     }
707
708     vlc_pa_lock();
709     if (s != NULL) {
710         pa_operation *op;
711
712         if (pa_stream_is_corked(s) > 0)
713             /* Stream paused: discard all buffers */
714             op = pa_stream_flush(s, stream_success_cb, NULL);
715         else
716             /* Stream playing: wait until buffers are played */
717             op = pa_stream_drain(s, stream_success_cb, NULL);
718         if (likely(op != NULL)) {
719 #ifdef LIBPULSE_GETS_A_CLUE
720             while (pa_operation_get_state(op) == PA_OPERATION_RUNNING)
721                 vlc_pa_wait();
722 #endif
723             pa_operation_unref(op);
724         }
725
726         pa_stream_disconnect(s);
727         pa_stream_unref(s);
728     }
729     vlc_pa_unlock();
730
731     vlc_pa_disconnect(obj, ctx);
732     free(sys);
733 }