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