]> git.sesse.net Git - vlc/blob - modules/audio_output/pulse.c
PulseAudio: implement sinks list (i.e. output devices)
[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     char *description;
63     uint32_t index;
64     char name[1];
65 };
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 first_pts; /**< Play time of buffer start */
76     mtime_t paused; /**< Time when (last) paused */
77
78     struct sink *sinks; /**< Locally-cached list of sinks */
79 };
80
81
82 /*** Sink ***/
83 static void sink_add_cb(pa_context *ctx, const pa_sink_info *i, int eol,
84                         void *userdata)
85 {
86     audio_output_t *aout = userdata;
87     aout_sys_t *sys = aout->sys;
88
89     if (eol)
90         return;
91     (void) ctx;
92
93     msg_Dbg(aout, "listing sink %s (%"PRIu32"): %s", i->name, i->index,
94             i->description);
95
96     size_t namelen = strlen(i->name);
97     struct sink *sink = malloc(sizeof (*sink) + namelen);
98     if (unlikely(sink == NULL))
99         return;
100
101     sink->next = sys->sinks;
102     sink->index = i->index;
103     sink->description = strdup(i->description);
104     memcpy(sink->name, i->name, namelen + 1);
105     sys->sinks = sink;
106 }
107
108 static void sink_mod_cb(pa_context *ctx, const pa_sink_info *i, int eol,
109                         void *userdata)
110 {
111     audio_output_t *aout = userdata;
112     aout_sys_t *sys = aout->sys;
113
114     if (eol)
115         return;
116     (void) ctx;
117
118     for (struct sink *sink = sys->sinks; sink != NULL; sink = sink->next)
119         if (sink->index == i->index)
120         {
121             free(sink->description);
122             sink->description = strdup(i->description);
123         }
124 }
125
126 static void sink_del(uint32_t index, audio_output_t *aout)
127 {
128     aout_sys_t *sys = aout->sys;
129     struct sink **pp = &sys->sinks, *sink;
130
131     while ((sink = *pp) != NULL)
132         if (sink->index == index)
133         {
134             *pp = sink->next;
135             free(sink->description);
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     if (sys->stream == NULL)
643     {
644         msg_Err (aout, "cannot change volume while not playing");
645         return -1;
646     }
647
648     pa_operation *op;
649     uint32_t idx = pa_stream_get_index(sys->stream);
650     pa_threaded_mainloop_lock(sys->mainloop);
651     op = pa_context_set_sink_input_mute(sys->context, idx, mute, NULL, NULL);
652     if (likely(op != NULL))
653         pa_operation_unref(op);
654     pa_threaded_mainloop_unlock(sys->mainloop);
655
656     return 0;
657 }
658
659 static int SinksList(audio_output_t *aout, char ***namesp, char ***descsp)
660 {
661     aout_sys_t *sys = aout->sys;
662     char **names, **descs;
663     unsigned n = 0;
664
665     pa_threaded_mainloop_lock(sys->mainloop);
666     for (struct sink *sink = sys->sinks; sink != NULL; sink = sink->next)
667         n++;
668
669     *namesp = names = xmalloc(sizeof(*names) * n);
670     *descsp = descs = xmalloc(sizeof(*descs) * n);
671
672     for (struct sink *sink = sys->sinks; sink != NULL; sink = sink->next)
673     {
674         *(names++) = strdup(sink->name);
675         *(descs++) = strdup(sink->description);
676     }
677     pa_threaded_mainloop_unlock(sys->mainloop);
678     return n;
679 }
680
681 static int StreamMove(audio_output_t *aout, const char *name)
682 {
683     aout_sys_t *sys = aout->sys;
684     pa_operation *op;
685     uint32_t idx = pa_stream_get_index(sys->stream);
686
687     pa_threaded_mainloop_lock(sys->mainloop);
688     op = pa_context_move_sink_input_by_name(sys->context, idx, name,
689                                             NULL, NULL);
690     if (likely(op != NULL)) {
691         pa_operation_unref(op);
692         msg_Dbg(aout, "moving to sink %s", name);
693     } else
694         vlc_pa_error(aout, "cannot move sink input", sys->context);
695     pa_threaded_mainloop_unlock(sys->mainloop);
696
697     return (op != NULL) ? VLC_SUCCESS : VLC_EGENERIC;
698 }
699
700 static void Stop(audio_output_t *);
701
702 /**
703  * Create a PulseAudio playback stream, a.k.a. a sink input.
704  */
705 static int Start(audio_output_t *aout, audio_sample_format_t *restrict fmt)
706 {
707     aout_sys_t *sys = aout->sys;
708
709     /* Sample format specification */
710     struct pa_sample_spec ss;
711 #if PA_CHECK_VERSION(1,0,0)
712     pa_encoding_t encoding = PA_ENCODING_INVALID;
713 #endif
714
715     switch (fmt->i_format)
716     {
717         case VLC_CODEC_FL64:
718             fmt->i_format = VLC_CODEC_FL32;
719         case VLC_CODEC_FL32:
720             ss.format = PA_SAMPLE_FLOAT32NE;
721             break;
722         case VLC_CODEC_S32N:
723             ss.format = PA_SAMPLE_S32NE;
724             break;
725         case VLC_CODEC_S16N:
726             ss.format = PA_SAMPLE_S16NE;
727             break;
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             fmt->i_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             fmt->i_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             fmt->i_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             fmt->i_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                 fmt->i_format = VLC_CODEC_FL32;
757                 ss.format = PA_SAMPLE_FLOAT32NE;
758             }
759             else
760             {
761                 fmt->i_format = VLC_CODEC_S16N;
762                 ss.format = PA_SAMPLE_S16NE;
763             }
764             break;
765     }
766
767     ss.rate = fmt->i_rate;
768     ss.channels = aout_FormatNbChannels(fmt);
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 (fmt->i_physical_channels & AOUT_CHAN_LEFT)
779         map.map[map.channels++] = PA_CHANNEL_POSITION_FRONT_LEFT;
780     if (fmt->i_physical_channels & AOUT_CHAN_RIGHT)
781         map.map[map.channels++] = PA_CHANNEL_POSITION_FRONT_RIGHT;
782     if (fmt->i_physical_channels & AOUT_CHAN_MIDDLELEFT)
783         map.map[map.channels++] = PA_CHANNEL_POSITION_SIDE_LEFT;
784     if (fmt->i_physical_channels & AOUT_CHAN_MIDDLERIGHT)
785         map.map[map.channels++] = PA_CHANNEL_POSITION_SIDE_RIGHT;
786     if (fmt->i_physical_channels & AOUT_CHAN_REARLEFT)
787         map.map[map.channels++] = PA_CHANNEL_POSITION_REAR_LEFT;
788     if (fmt->i_physical_channels & AOUT_CHAN_REARRIGHT)
789         map.map[map.channels++] = PA_CHANNEL_POSITION_REAR_RIGHT;
790     if (fmt->i_physical_channels & AOUT_CHAN_REARCENTER)
791         map.map[map.channels++] = PA_CHANNEL_POSITION_REAR_CENTER;
792     if (fmt->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 (fmt->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_NOT_MONOTONIC
819                                   | PA_STREAM_AUTO_TIMING_UPDATE
820                                   | PA_STREAM_FIX_RATE;
821
822     struct pa_buffer_attr attr;
823     attr.maxlength = -1;
824     /* PulseAudio goes berserk if the target length (tlength) is not
825      * significantly longer than 2 periods (minreq), or when the period length
826      * is unspecified and the target length is short. */
827     attr.tlength = pa_usec_to_bytes(3 * AOUT_MIN_PREPARE_TIME, &ss);
828     attr.prebuf = 0; /* trigger manually */
829     attr.minreq = pa_usec_to_bytes(AOUT_MIN_PREPARE_TIME, &ss);
830     attr.fragsize = 0; /* not used for output */
831
832     sys->stream = NULL;
833     sys->trigger = NULL;
834     sys->first_pts = VLC_TS_INVALID;
835     sys->paused = VLC_TS_INVALID;
836
837     /* Channel volume */
838     sys->base_volume = PA_VOLUME_NORM;
839     pa_cvolume_set(&sys->cvolume, ss.channels, PA_VOLUME_NORM);
840
841 #if PA_CHECK_VERSION(1,0,0)
842     pa_format_info *formatv[2];
843     unsigned formatc = 0;
844
845     /* Favor digital pass-through if available*/
846     if (encoding != PA_ENCODING_INVALID) {
847         formatv[formatc] = pa_format_info_new();
848         formatv[formatc]->encoding = encoding;
849         pa_format_info_set_rate(formatv[formatc], ss.rate);
850         pa_format_info_set_channels(formatv[formatc], ss.channels);
851         pa_format_info_set_channel_map(formatv[formatc], &map);
852         formatc++;
853     }
854
855     /* Fallback to PCM */
856     formatv[formatc] = pa_format_info_new();
857     formatv[formatc]->encoding = PA_ENCODING_PCM;
858     pa_format_info_set_sample_format(formatv[formatc], ss.format);
859     pa_format_info_set_rate(formatv[formatc], ss.rate);
860     pa_format_info_set_channels(formatv[formatc], ss.channels);
861     pa_format_info_set_channel_map(formatv[formatc], &map);
862     formatc++;
863
864     /* Create a playback stream */
865     pa_stream *s;
866     pa_proplist *props = pa_proplist_new();
867     if (likely(props != NULL))
868         /* TODO: set other stream properties */
869         pa_proplist_sets (props, PA_PROP_MEDIA_ROLE, "video");
870
871     pa_threaded_mainloop_lock(sys->mainloop);
872     s = pa_stream_new_extended(sys->context, "audio stream", formatv, formatc,
873                                props);
874     if (likely(props != NULL))
875         pa_proplist_free(props);
876
877     for (unsigned i = 0; i < formatc; i++)
878         pa_format_info_free(formatv[i]);
879 #else
880     pa_threaded_mainloop_lock(sys->mainloop);
881     pa_stream *s = pa_stream_new(sys->context, "audio stream", &ss, &map);
882 #endif
883     if (s == NULL) {
884         pa_threaded_mainloop_unlock(sys->mainloop);
885         vlc_pa_error(aout, "stream creation failure", sys->context);
886         return VLC_EGENERIC;
887     }
888     sys->stream = s;
889     pa_stream_set_state_callback(s, stream_state_cb, sys->mainloop);
890     pa_stream_set_buffer_attr_callback(s, stream_buffer_attr_cb, aout);
891     pa_stream_set_event_callback(s, stream_event_cb, aout);
892     pa_stream_set_latency_update_callback(s, stream_latency_cb, aout);
893     pa_stream_set_moved_callback(s, stream_moved_cb, aout);
894     pa_stream_set_overflow_callback(s, stream_overflow_cb, aout);
895     pa_stream_set_started_callback(s, stream_started_cb, aout);
896     pa_stream_set_suspended_callback(s, stream_suspended_cb, aout);
897     pa_stream_set_underflow_callback(s, stream_underflow_cb, aout);
898
899     if (pa_stream_connect_playback(s, NULL, &attr, flags, NULL, NULL) < 0
900      || stream_wait(s, sys->mainloop)) {
901         vlc_pa_error(aout, "stream connection failure", sys->context);
902         goto fail;
903     }
904
905     const struct pa_sample_spec *spec = pa_stream_get_sample_spec(s);
906 #if PA_CHECK_VERSION(1,0,0)
907     if (encoding != PA_ENCODING_INVALID) {
908         const pa_format_info *info = pa_stream_get_format_info(s);
909
910         assert (info != NULL);
911         if (pa_format_info_is_pcm (info)) {
912             msg_Dbg(aout, "digital pass-through not available");
913             fmt->i_format = HAVE_FPU ? VLC_CODEC_FL32 : VLC_CODEC_S16N;
914         } else {
915             msg_Dbg(aout, "digital pass-through enabled");
916             spec = NULL;
917         }
918     }
919 #endif
920     if (spec != NULL)
921         fmt->i_rate = spec->rate;
922
923     stream_buffer_attr_cb(s, aout);
924     stream_moved_cb(s, aout);
925     pa_threaded_mainloop_unlock(sys->mainloop);
926
927     return VLC_SUCCESS;
928
929 fail:
930     pa_threaded_mainloop_unlock(sys->mainloop);
931     Stop(aout);
932     return VLC_EGENERIC;
933 }
934
935 /**
936  * Removes a PulseAudio playback stream
937  */
938 static void Stop(audio_output_t *aout)
939 {
940     aout_sys_t *sys = aout->sys;
941     pa_stream *s = sys->stream;
942
943     pa_threaded_mainloop_lock(sys->mainloop);
944     if (unlikely(sys->trigger != NULL))
945         vlc_pa_rttime_free(sys->mainloop, sys->trigger);
946     pa_stream_disconnect(s);
947
948     /* Clear all callbacks */
949     pa_stream_set_state_callback(s, NULL, NULL);
950     pa_stream_set_buffer_attr_callback(s, NULL, NULL);
951     pa_stream_set_event_callback(s, NULL, NULL);
952     pa_stream_set_latency_update_callback(s, NULL, NULL);
953     pa_stream_set_moved_callback(s, NULL, NULL);
954     pa_stream_set_overflow_callback(s, NULL, NULL);
955     pa_stream_set_started_callback(s, NULL, NULL);
956     pa_stream_set_suspended_callback(s, NULL, NULL);
957     pa_stream_set_underflow_callback(s, NULL, NULL);
958
959     pa_stream_unref(s);
960     sys->stream = NULL;
961     pa_threaded_mainloop_unlock(sys->mainloop);
962 }
963
964 static int Open(vlc_object_t *obj)
965 {
966     audio_output_t *aout = (audio_output_t *)obj;
967     aout_sys_t *sys = malloc(sizeof (*sys));
968     pa_operation *op;
969
970 #if !PA_CHECK_VERSION(0,9,22)
971     if (!vlc_xlib_init(obj))
972         return VLC_EGENERIC;
973 #endif
974     if (unlikely(sys == NULL))
975         return VLC_ENOMEM;
976
977     /* Allocate structures */
978     pa_context *ctx = vlc_pa_connect(obj, &sys->mainloop);
979     if (ctx == NULL)
980     {
981         free(sys);
982         return VLC_EGENERIC;
983     }
984     sys->stream = NULL;
985     sys->context = ctx;
986     sys->sinks = NULL;
987
988     aout->sys = sys;
989     aout->start = Start;
990     aout->stop = Stop;
991     aout->time_get = TimeGet;
992     aout->play = Play;
993     aout->pause = Pause;
994     aout->flush = Flush;
995     aout->volume_set = VolumeSet;
996     aout->mute_set = MuteSet;
997     aout->device_enum = SinksList;
998     aout->device_select = StreamMove;
999
1000     pa_threaded_mainloop_lock(sys->mainloop);
1001     /* Sinks (output devices) list */
1002     op = pa_context_get_sink_info_list(sys->context, sink_add_cb, aout);
1003     if (op != NULL)
1004         pa_operation_unref(op);
1005
1006     /* Context events */
1007     const pa_subscription_mask_t mask = PA_SUBSCRIPTION_MASK_SINK
1008                                       | PA_SUBSCRIPTION_MASK_SINK_INPUT;
1009     pa_context_set_subscribe_callback(sys->context, context_cb, aout);
1010     op = pa_context_subscribe(sys->context, mask, NULL, NULL);
1011     if (likely(op != NULL))
1012        pa_operation_unref(op);
1013     pa_threaded_mainloop_unlock(sys->mainloop);
1014
1015     return VLC_SUCCESS;
1016 }
1017
1018 static void Close(vlc_object_t *obj)
1019 {
1020     audio_output_t *aout = (audio_output_t *)obj;
1021     aout_sys_t *sys = aout->sys;
1022     pa_context *ctx = sys->context;
1023
1024     pa_threaded_mainloop_lock(sys->mainloop);
1025     pa_context_set_subscribe_callback(sys->context, NULL, NULL);
1026     pa_threaded_mainloop_unlock(sys->mainloop);
1027     vlc_pa_disconnect(obj, ctx, sys->mainloop);
1028
1029     for (struct sink *sink = sys->sinks, *next; sink != NULL; sink = next)
1030     {
1031         next = sink->next;
1032         free(sink->description);
1033         free(sink);
1034     }
1035     free(sys);
1036 }