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