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