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