]> git.sesse.net Git - vlc/blob - modules/audio_output/pulse.c
PulseAudio: higher priority than ALSA
[vlc] / modules / audio_output / pulse.c
1 /*****************************************************************************
2  * pulse.c : Pulseaudio output plugin for vlc
3  *****************************************************************************
4  * Copyright (C) 2008 the VideoLAN team
5  *
6  * Authors: Martin Hamrle <hamrle @ post . cz>
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
21  *****************************************************************************/
22
23 /*****************************************************************************
24  * Preamble
25  *****************************************************************************/
26 #ifdef HAVE_CONFIG_H
27 # include "config.h"
28 #endif
29
30 #include <vlc_common.h>
31 #include <vlc_plugin.h>
32
33 #include <vlc_aout.h>
34
35 #include <pulse/pulseaudio.h>
36
37 #include <assert.h>
38
39 /*****************************************************************************
40  * aout_sys_t: Pulseaudio output method descriptor
41  *****************************************************************************
42  * This structure is part of the audio output thread descriptor.
43  * It describes the specific properties of an audio device.
44  *****************************************************************************/
45 struct aout_sys_t
46 {
47     /** PulseAudio playback stream object */
48     struct pa_stream *stream;
49
50     /** PulseAudio connection context */
51     struct pa_context *context;
52
53     /** Main event loop object */
54     struct pa_threaded_mainloop *mainloop;
55
56     int started;
57     size_t buffer_size;
58     mtime_t start_date;
59 };
60
61 #define    PULSE_CLIENT_NAME N_("VLC media player")
62
63 #if 0
64 #define PULSE_DEBUG( ...) \
65     msg_Dbg( p_aout, __VA_ARGS__ )
66 #else
67 #define PULSE_DEBUG( ...) \
68     (void) 0
69 #endif
70
71
72 #define CHECK_DEAD_GOTO(label) do { \
73 if (!p_sys->context || pa_context_get_state(p_sys->context) != PA_CONTEXT_READY || \
74     !p_sys->stream || pa_stream_get_state(p_sys->stream) != PA_STREAM_READY) { \
75         msg_Err(p_aout, "Connection died: %s", p_sys->context ? pa_strerror(pa_context_errno(p_sys->context)) : "NULL"); \
76         goto label; \
77     }  \
78 } while(0);
79
80 /*****************************************************************************
81  * Local prototypes
82  *****************************************************************************/
83 static int  Open        ( vlc_object_t * );
84 static void Close       ( vlc_object_t * );
85 static void Play        ( aout_instance_t * );
86
87 static void context_state_cb(pa_context *c, void *userdata);
88 static void stream_state_cb(pa_stream *s, void * userdata);
89 static void stream_request_cb(pa_stream *s, size_t length, void *userdata);
90 static void stream_latency_update_cb(pa_stream *s, void *userdata);
91 static void success_cb(pa_stream *s, int sucess, void *userdata);
92 static void uninit(aout_instance_t *p_aout);
93
94 /*****************************************************************************
95  * Module descriptor
96  *****************************************************************************/
97 vlc_module_begin ()
98     set_shortname( "Pulse Audio" )
99     set_description( N_("Pulseaudio audio output") )
100     set_capability( "audio output", 160 )
101     set_category( CAT_AUDIO )
102     set_subcategory( SUBCAT_AUDIO_AOUT )
103     add_shortcut( "pulseaudio" )
104     add_shortcut( "pa" )
105     set_callbacks( Open, Close )
106     linked_with_a_crap_library_which_uses_atexit()
107 vlc_module_end ()
108
109 /*****************************************************************************
110  * Open: open the audio device
111  *****************************************************************************/
112 static int Open ( vlc_object_t *p_this )
113 {
114     aout_instance_t *p_aout = (aout_instance_t *)p_this;
115     struct aout_sys_t * p_sys;
116     struct pa_sample_spec ss;
117     const struct pa_buffer_attr *buffer_attr;
118     struct pa_buffer_attr a;
119     struct pa_channel_map map;
120
121     /* Allocate structures */
122     p_aout->output.p_sys = p_sys = calloc( 1, sizeof( aout_sys_t ) );
123     if( p_sys == NULL )
124         return VLC_ENOMEM;
125
126     PULSE_DEBUG( "Pulse start initialization");
127
128     ss.channels = aout_FormatNbChannels( &p_aout->output.output ); /* Get the input stream channel count */
129
130     /* Setup the pulse audio stream based on the input stream count */
131     switch(ss.channels)
132     {
133         case 8:
134             p_aout->output.output.i_physical_channels
135                 = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
136                 | AOUT_CHAN_MIDDLELEFT | AOUT_CHAN_MIDDLERIGHT
137                 | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT
138                 | AOUT_CHAN_LFE;
139             break;
140         case 6:
141             p_aout->output.output.i_physical_channels
142                 = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
143                 | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT
144                 | AOUT_CHAN_LFE;
145             break;
146
147         case 4:
148             p_aout->output.output.i_physical_channels
149                 = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT
150                 | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT;
151             break;
152
153         case 2:
154             p_aout->output.output.i_physical_channels
155                 = AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT;
156             break;
157
158         case 1:
159             p_aout->output.output.i_physical_channels = AOUT_CHAN_CENTER;
160             break;
161
162         default:
163             msg_Err(p_aout,"Invalid number of channels");
164         goto fail;
165     }
166
167     /* Add a quick command line info message */
168     msg_Dbg(p_aout, "%d audio channels", ss.channels);
169
170     ss.rate = p_aout->output.output.i_rate;
171     if (vlc_CPU() & CPU_CAPABILITY_FPU)
172     {
173         ss.format = PA_SAMPLE_FLOAT32NE;
174         p_aout->output.output.i_format = VLC_CODEC_FL32;
175     }
176     else
177     {
178         ss.format = PA_SAMPLE_S16NE;
179         p_aout->output.output.i_format = VLC_CODEC_S16N;
180     }
181
182     if (!pa_sample_spec_valid(&ss)) {
183         msg_Err(p_aout,"Invalid sample spec");
184         goto fail;
185     }
186
187     /* Reduce overall latency to 200mS to reduce audible clicks
188      * Also pulse minreq and internal buffers are now 20mS which reduces resampling
189      */
190     a.tlength = pa_bytes_per_second(&ss)/5;
191     a.maxlength = a.tlength * 2;
192     a.prebuf = a.tlength / 2;
193     a.minreq = a.tlength / 10;
194
195     /* Buffer size is 20mS */
196     p_sys->buffer_size = a.minreq;
197
198     /* Initialise the speaker map setup above */
199     pa_channel_map_init_auto(&map, ss.channels, PA_CHANNEL_MAP_ALSA);
200
201     if (!(p_sys->mainloop = pa_threaded_mainloop_new())) {
202         msg_Err(p_aout, "Failed to allocate main loop");
203         goto fail;
204     }
205
206     if (!(p_sys->context = pa_context_new(pa_threaded_mainloop_get_api(p_sys->mainloop), _( PULSE_CLIENT_NAME )))) {
207         msg_Err(p_aout, "Failed to allocate context");
208         goto fail;
209     }
210
211     pa_context_set_state_callback(p_sys->context, context_state_cb, p_aout);
212
213     PULSE_DEBUG( "Pulse before context connect");
214
215     if (pa_context_connect(p_sys->context, NULL, 0, NULL) < 0) {
216         msg_Err(p_aout, "Failed to connect to server: %s", pa_strerror(pa_context_errno(p_sys->context)));
217         goto fail;
218     }
219
220     PULSE_DEBUG( "Pulse after context connect");
221
222     pa_threaded_mainloop_lock(p_sys->mainloop);
223
224     if (pa_threaded_mainloop_start(p_sys->mainloop) < 0) {
225         msg_Err(p_aout, "Failed to start main loop");
226         goto unlock_and_fail;
227     }
228
229     msg_Dbg(p_aout, "Pulse mainloop started");
230
231     /* Wait until the context is ready */
232     pa_threaded_mainloop_wait(p_sys->mainloop);
233
234     if (pa_context_get_state(p_sys->context) != PA_CONTEXT_READY) {
235         msg_Err(p_aout, "Failed to connect to server: %s", pa_strerror(pa_context_errno(p_sys->context)));
236         goto unlock_and_fail;
237     }
238
239     if (!(p_sys->stream = pa_stream_new(p_sys->context, "audio stream", &ss, &map))) {
240         msg_Err(p_aout, "Failed to create stream: %s", pa_strerror(pa_context_errno(p_sys->context)));
241         goto unlock_and_fail;
242     }
243
244     PULSE_DEBUG( "Pulse after new stream");
245
246     pa_stream_set_state_callback(p_sys->stream, stream_state_cb, p_aout);
247     pa_stream_set_write_callback(p_sys->stream, stream_request_cb, p_aout);
248     pa_stream_set_latency_update_callback(p_sys->stream, stream_latency_update_cb, p_aout);
249
250     if (pa_stream_connect_playback(p_sys->stream, NULL, &a, PA_STREAM_INTERPOLATE_TIMING|PA_STREAM_AUTO_TIMING_UPDATE|PA_STREAM_ADJUST_LATENCY, NULL, NULL) < 0) {
251         msg_Err(p_aout, "Failed to connect stream: %s", pa_strerror(pa_context_errno(p_sys->context)));
252         goto unlock_and_fail;
253     }
254
255      PULSE_DEBUG("Pulse stream connect");
256
257     /* Wait until the stream is ready */
258     pa_threaded_mainloop_wait(p_sys->mainloop);
259
260     msg_Dbg(p_aout,"Pulse stream connected");
261
262     if (pa_stream_get_state(p_sys->stream) != PA_STREAM_READY) {
263         msg_Err(p_aout, "Failed to connect to server: %s", pa_strerror(pa_context_errno(p_sys->context)));
264         goto unlock_and_fail;
265     }
266
267
268     PULSE_DEBUG("Pulse after stream get status");
269
270     pa_threaded_mainloop_unlock(p_sys->mainloop);
271
272     buffer_attr = pa_stream_get_buffer_attr(p_sys->stream);
273     p_aout->output.i_nb_samples = buffer_attr->minreq / pa_frame_size(&ss);
274     p_aout->output.pf_play = Play;
275     aout_VolumeSoftInit(p_aout);
276     msg_Dbg(p_aout, "Pulse initialized successfully");
277     {
278         char cmt[PA_CHANNEL_MAP_SNPRINT_MAX], sst[PA_SAMPLE_SPEC_SNPRINT_MAX];
279
280         msg_Dbg(p_aout, "Buffer metrics: maxlength=%u, tlength=%u, prebuf=%u, minreq=%u", buffer_attr->maxlength, buffer_attr->tlength, buffer_attr->prebuf, buffer_attr->minreq);
281         msg_Dbg(p_aout, "Using sample spec '%s', channel map '%s'.",
282                 pa_sample_spec_snprint(sst, sizeof(sst), pa_stream_get_sample_spec(p_sys->stream)),
283                 pa_channel_map_snprint(cmt, sizeof(cmt), pa_stream_get_channel_map(p_sys->stream)));
284
285             msg_Dbg(p_aout, "Connected to device %s (%u, %ssuspended).",
286                         pa_stream_get_device_name(p_sys->stream),
287                         pa_stream_get_device_index(p_sys->stream),
288                         pa_stream_is_suspended(p_sys->stream) ? "" : "not ");
289     }
290
291     return VLC_SUCCESS;
292
293 unlock_and_fail:
294     msg_Dbg(p_aout, "Pulse initialization unlock and fail");
295
296     if (p_sys->mainloop)
297         pa_threaded_mainloop_unlock(p_sys->mainloop);
298 fail:
299     msg_Err(p_aout, "Pulse initialization failed");
300     uninit(p_aout);
301     return VLC_EGENERIC;
302 }
303
304 /*****************************************************************************
305  * Play: play a sound samples buffer
306  *****************************************************************************/
307 static void Play( aout_instance_t * p_aout )
308 {
309     struct aout_sys_t * p_sys = (struct aout_sys_t *) p_aout->output.p_sys;
310
311     pa_operation *o;
312
313     if(!p_sys->started){
314         msg_Dbg(p_aout, "Pulse stream started");
315         p_sys->start_date =
316             aout_FifoFirstDate( p_aout, &p_aout->output.fifo );
317         p_sys->started = 1;
318
319         pa_threaded_mainloop_lock(p_sys->mainloop);
320         if((o = pa_stream_flush(p_sys->stream, success_cb, p_aout))){
321             pa_operation_unref(o);
322         }
323         pa_threaded_mainloop_unlock(p_sys->mainloop);
324
325         pa_threaded_mainloop_signal(p_sys->mainloop, 0);
326     }
327 }
328
329 /*****************************************************************************
330  * Close: close the audio device
331  *****************************************************************************/
332 static void Close ( vlc_object_t *p_this )
333 {
334     aout_instance_t *p_aout = (aout_instance_t *)p_this;
335     struct aout_sys_t * p_sys = p_aout->output.p_sys;
336
337     msg_Dbg(p_aout, "Pulse Close");
338
339     if(p_sys->stream){
340         pa_operation *o;
341         pa_threaded_mainloop_lock(p_sys->mainloop);
342         pa_stream_set_write_callback(p_sys->stream, NULL, NULL);
343
344         if((o = pa_stream_drain(p_sys->stream, success_cb, p_aout))){
345             while (pa_operation_get_state(o) != PA_OPERATION_DONE) {
346                 CHECK_DEAD_GOTO(fail);
347                 pa_threaded_mainloop_wait(p_sys->mainloop);
348             }
349
350         fail:
351
352             pa_operation_unref(o);
353         }
354
355         pa_threaded_mainloop_unlock(p_sys->mainloop);
356     }
357     uninit(p_aout);
358 }
359
360 static void uninit(aout_instance_t *p_aout){
361     struct aout_sys_t * p_sys = p_aout->output.p_sys;
362
363     if (p_sys->mainloop)
364         pa_threaded_mainloop_stop(p_sys->mainloop);
365
366     if (p_sys->stream) {
367         pa_stream_disconnect(p_sys->stream);
368         pa_stream_unref(p_sys->stream);
369         p_sys->stream = NULL;
370     }
371
372     if (p_sys->context) {
373         pa_context_disconnect(p_sys->context);
374         pa_context_unref(p_sys->context);
375         p_sys->context = NULL;
376     }
377
378     if (p_sys->mainloop) {
379         pa_threaded_mainloop_free(p_sys->mainloop);
380         p_sys->mainloop = NULL;
381     }
382
383     free(p_sys);
384     p_aout->output.p_sys = NULL;
385 }
386
387 static void context_state_cb(pa_context *c, void *userdata) {
388     aout_instance_t *p_aout = (aout_instance_t *)userdata;
389     struct aout_sys_t * p_sys = (struct aout_sys_t *) p_aout->output.p_sys;
390
391     assert(c);
392
393     PULSE_DEBUG( "Pulse context state changed");
394
395     switch (pa_context_get_state(c)) {
396         case PA_CONTEXT_READY:
397         case PA_CONTEXT_TERMINATED:
398         case PA_CONTEXT_FAILED:
399         PULSE_DEBUG( "Pulse context state changed signal");
400             pa_threaded_mainloop_signal(p_sys->mainloop, 0);
401             break;
402
403         case PA_CONTEXT_UNCONNECTED:
404         case PA_CONTEXT_CONNECTING:
405         case PA_CONTEXT_AUTHORIZING:
406         case PA_CONTEXT_SETTING_NAME:
407         PULSE_DEBUG( "Pulse context state changed no signal");
408             break;
409     }
410 }
411
412 static void stream_state_cb(pa_stream *s, void * userdata) {
413     aout_instance_t *p_aout = (aout_instance_t *)userdata;
414     struct aout_sys_t * p_sys = (struct aout_sys_t *) p_aout->output.p_sys;
415
416     assert(s);
417
418     PULSE_DEBUG( "Pulse stream state changed");
419
420     switch (pa_stream_get_state(s)) {
421
422         case PA_STREAM_READY:
423         case PA_STREAM_FAILED:
424         case PA_STREAM_TERMINATED:
425             pa_threaded_mainloop_signal(p_sys->mainloop, 0);
426             break;
427
428         case PA_STREAM_UNCONNECTED:
429         case PA_STREAM_CREATING:
430             break;
431     }
432 }
433
434 static void stream_request_cb(pa_stream *s, size_t length, void *userdata) {
435     aout_instance_t *p_aout = (aout_instance_t *)userdata;
436     struct aout_sys_t * p_sys = (struct aout_sys_t *) p_aout->output.p_sys;
437     mtime_t next_date;
438
439     assert(s);
440     assert(p_sys);
441
442     size_t buffer_size = p_sys->buffer_size;
443
444     PULSE_DEBUG( "Pulse stream request %d", length);
445
446     do{
447         aout_buffer_t *   p_buffer = NULL;
448         if(p_sys->started){
449             pa_usec_t latency;
450             int negative;
451             if(pa_stream_get_latency(p_sys->stream, &latency, &negative)<0){
452                 if (pa_context_errno(p_sys->context) != PA_ERR_NODATA) {
453                     msg_Err(p_aout, "pa_stream_get_latency() failed: %s", pa_strerror(pa_context_errno(p_sys->context)));
454                 }
455                 latency = 0;
456
457             }
458
459             PULSE_DEBUG( "Pulse stream request latency=%"PRId64"", latency);
460             next_date = mdate() + latency;
461
462             if(p_sys->start_date < next_date + AOUT_PTS_TOLERANCE ){
463                 p_buffer = aout_OutputNextBuffer( p_aout, next_date, 0);
464             }
465         }
466
467         if ( p_buffer != NULL )
468         {
469             PULSE_DEBUG( "Pulse stream request write buffer %d", p_buffer->i_nb_bytes);
470             pa_stream_write(p_sys->stream, p_buffer->p_buffer, p_buffer->i_nb_bytes, NULL, 0, PA_SEEK_RELATIVE);
471             length -= p_buffer->i_nb_bytes;
472             aout_BufferFree( p_buffer );
473         }
474         else
475         {
476             PULSE_DEBUG( "Pulse stream request write zeroes");
477             void *data = pa_xmalloc(buffer_size);
478             bzero(data, buffer_size);
479             pa_stream_write(p_sys->stream, data, buffer_size, pa_xfree, 0, PA_SEEK_RELATIVE);
480             length -= buffer_size;
481         }
482     }while(length > buffer_size);
483
484     pa_threaded_mainloop_signal(p_sys->mainloop, 0);
485 }
486
487 static void stream_latency_update_cb(pa_stream *s, void *userdata) {
488     aout_instance_t *p_aout = (aout_instance_t *)userdata;
489     struct aout_sys_t * p_sys = (struct aout_sys_t *) p_aout->output.p_sys;
490
491     assert(s);
492
493     PULSE_DEBUG( "Pulse stream latency update");
494
495     pa_threaded_mainloop_signal(p_sys->mainloop, 0);
496 }
497
498 static void success_cb(pa_stream *s, int sucess, void *userdata)
499 {
500     aout_instance_t *p_aout = (aout_instance_t *)userdata;
501     struct aout_sys_t * p_sys = (struct aout_sys_t *) p_aout->output.p_sys;
502
503     VLC_UNUSED(sucess);
504
505     assert(s);
506
507     pa_threaded_mainloop_signal(p_sys->mainloop, 0);
508 }
509
510 #undef PULSE_DEBUG