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