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