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