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